pxt-core 11.1.4 → 11.2.2

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.
@@ -1 +1 @@
1
- var e=function(){"use strict";function t(e,t){postMessage({action:$e,cbn:t,result:e})}function n(e){var t=[];return t[e-1]=void 0,t}function i(e,t){return o(e[0]+t[0],e[1]+t[1])}function s(e,t){return function(e,t){var n;return n=t,0>t&&(n+=Ve),[n,e*Ve]}(~~Math.max(Math.min(e[1]/Ve,2147483647),-2147483648)&~~Math.max(Math.min(t[1]/Ve,2147483647),-2147483648),c(e)&c(t))}function r(e,t){var n,i;return e[0]==t[0]&&e[1]==t[1]?0:(n=0>e[1],i=0>t[1],n&&!i?-1:!n&&i?1:p(e,t)[1]<0?-1:1)}function o(e,t){var n,i;for(e%=0x10000000000000000,t=(t%=0x10000000000000000)-(n=t%Ve)+(i=Math.floor(e/Ve)*Ve),e=e-i+n;0>e;)e+=Ve,t-=Ve;for(;e>4294967295;)e-=Ve,t+=Ve;for(t%=0x10000000000000000;t>0x7fffffff00000000;)t-=0x10000000000000000;for(;-0x8000000000000000>t;)t+=0x10000000000000000;return[e,t]}function a(e,t){return e[0]==t[0]&&e[1]==t[1]}function l(e){return e>=0?[e,0]:[e+Ve,-Ve]}function c(e){return e[0]>=2147483648?~~Math.max(Math.min(e[0]-Ve,2147483647),-2147483648):~~Math.max(Math.min(e[0],2147483647),-2147483648)}function u(e){return 30>=e?1<<e:u(30)*u(e-30)}function d(e,t){var n,i,s,r;if(t&=63,a(e,He))return t?Ge:e;if(0>e[1])throw Error("Neg");return r=u(t),i=e[1]*r%0x10000000000000000,(i+=n=(s=e[0]*r)-s%Ve)>=0x8000000000000000&&(i-=0x10000000000000000),[s-=n,i]}function h(e,t){var n;return n=u(t&=63),o(Math.floor(e[0]/n),e[1]/n)}function p(e,t){return o(e[0]-t[0],e[1]-t[1])}function f(e,t){return e.Mc=t,e.Lc=0,e.Yb=t.length,e}function m(e){return e.Lc>=e.Yb?-1:255&e.Mc[e.Lc++]}function g(e,t,n,i){return e.Lc>=e.Yb?-1:(i=Math.min(i,e.Yb-e.Lc),k(e.Mc,e.Lc,t,n,i),e.Lc+=i,i)}function b(e){return e.Mc=n(32),e.Yb=0,e}function y(e){var t=e.Mc;return t.length=e.Yb,t}function v(e,t){e.Mc[e.Yb++]=t<<24>>24}function w(e,t,n,i){k(t,n,e.Mc,e.Yb,i),e.Yb+=i}function k(e,t,n,i,s){for(var r=0;s>r;++r)n[i+r]=e[t+r]}function x(t,n,i,s,o){var a,l;if(r(s,qe)<0)throw Error("invalid length "+s);for(t.Tb=s,function(e,t){(function(e,t){e.ab=t;for(var n=0;t>1<<n;++n);e.$b=2*n})(t,1<<e.s),t.n=e.f,function(e,t){var n=e.X;e.X=t,e.b&&n!=e.X&&(e.wb=-1,e.b=null)}(t,e.m),t.eb=0,t.fb=3,t.Y=2,t.y=3}(o,a=Y({})),a.Gc=void 0===e.disableEndMark,function(e,t){e.fc[0]=9*(5*e.Y+e.eb)+e.fb<<24>>24;for(var n=0;4>n;++n)e.fc[1+n]=e.ab>>8*n<<24>>24;w(t,e.fc,0,5)}(a,i),l=0;64>l;l+=8)v(i,255&c(h(s,l)));t.yb=(a.W=0,a.oc=n,a.pc=0,function(e){var t,n;e.b||(t={},n=4,e.X||(n=2),function(e,t){e.qb=t>2,e.qb?(e.w=0,e.xb=4,e.R=66560):(e.w=2,e.xb=3,e.R=0)}(t,n),e.b=t),he(e.A,e.eb,e.fb),(e.ab!=e.wb||e.Hb!=e.n)&&(U(e.b,e.ab,4096,e.n,274),e.wb=e.ab,e.Hb=e.n)}(a),a.d.Ab=i,function(e){(function(e){e.l=0,e.J=0;for(var t=0;4>t;++t)e.v[t]=0})(e),function(e){e.mc=Ge,e.xc=Ge,e.E=-1,e.Jb=1,e.Oc=0}(e.d),_e(e.C),_e(e._),_e(e.bb),_e(e.hb),_e(e.Ub),_e(e.vc),_e(e.Sb),function(e){var t,n=1<<e.u+e.I;for(t=0;n>t;++t)_e(e.V[t].tb)}(e.A);for(var t=0;4>t;++t)_e(e.K[t].G);oe(e.$,1<<e.Y),oe(e.i,1<<e.Y),_e(e.S.G),e.N=0,e.jb=0,e.q=0,e.s=0}(a),X(a),K(a),a.$.rb=a.n+1-2,de(a.$,1<<a.Y),a.i.rb=a.n+1-2,de(a.i,1<<a.Y),a.g=Ge,function(e,t){return e.cb=t,e.Z=null,e.zc=1,e}({},a))}function A(e,t,n){return e.Nb=b({}),x(e,f({},t),e.Nb,l(t.length),n),e}function E(e,t,n){var i,s,r,o,a="",c=[];for(s=0;5>s;++s){if(-1==(r=m(t)))throw Error("truncated input");c[s]=r<<24>>24}if(!function(e,t){var n,i,s,r,o,a,l;if(5>t.length)return 0;for(l=255&t[0],s=l%9,r=(a=~~(l/9))%5,o=~~(a/5),n=0,i=0;4>i;++i)n+=(255&t[1+i])<<8*i;return n>99999999||!function(e,t,n,i){if(t>8||n>4||i>4)return 0;z(e.gb,n,t);var s=1<<i;return V(e.Rb,s),V(e.sb,s),e.Dc=s-1,1}(e,s,r,o)?0:function(e,t){return 0>t?0:(e.Ob!=t&&(e.Ob=t,e.nb=Math.max(e.Ob,1),R(e.B,Math.max(e.nb,4096))),1)}(e,n)}(i=j({}),c))throw Error("corrupted input");for(s=0;64>s;s+=8){if(-1==(r=m(t)))throw Error("truncated input");1==(r=r.toString(16)).length&&(r="0"+r),a=r+""+a}/^0+$|^f+$/i.test(a)?e.Tb=qe:(o=parseInt(a,16),e.Tb=o>4294967295?qe:l(o)),e.yb=function(e,t,n,i){return e.e.Ab=t,L(e.B),e.B.cc=n,function(e){e.B.h=0,e.B.o=0,_e(e.Gb),_e(e.pb),_e(e.Zb),_e(e.Cb),_e(e.Db),_e(e.Eb),_e(e.kc),function(e){var t,n;for(n=1<<e.u+e.I,t=0;n>t;++t)_e(e.V[t].Ib)}(e.gb);for(var t=0;4>t;++t)_e(e.kb[t].G);G(e.Rb),G(e.sb),_e(e.Fb.G),function(e){e.Bb=0,e.E=-1;for(var t=0;5>t;++t)e.Bb=e.Bb<<8|m(e.Ab)}(e.e)}(e),e.U=0,e.ib=0,e.Jc=0,e.Ic=0,e.Qc=0,e.Nc=i,e.g=Ge,e.jc=0,function(e,t){return e.Z=t,e.cb=null,e.zc=1,e}({},e)}(i,t,n,e.Tb)}function T(e,t){return e.Nb=b({}),E(e,f({},t),e.Nb),e}function S(e,t){return e.c[e.f+e.o+t]}function C(e,t,n,i){var s,r;for(e.T&&e.o+t+i>e.h&&(i=e.h-(e.o+t)),++n,r=e.f+e.o+t,s=0;i>s&&e.c[r+s]==e.c[r+s-n];++s);return s}function I(e){return e.h-e.o}function _(e){var t,n;if(!e.T)for(;;){if(!(n=-e.f+e.Kb-e.h))return;if(-1==(t=g(e.cc,e.c,e.f+e.h,n)))return e.zb=e.h,e.f+e.zb>e.H&&(e.zb=e.H-e.f),void(e.T=1);e.h+=t,e.h>=e.o+e._b&&(e.zb=e.h-e._b)}}function P(e,t){e.f+=t,e.zb-=t,e.o-=t,e.h-=t}function U(e,t,i,s,r){var o,a;1073741567>t&&(e.Fc=16+(s>>1),function(e,t,i,s){var r;e.Bc=t,e._b=i,r=t+i+s,(null==e.c||e.Kb!=r)&&(e.c=null,e.Kb=r,e.c=n(e.Kb)),e.H=e.Kb-i}(e,t+i,s+r,256+~~((t+i+s+r)/2)),e.ob=s,o=t+1,e.p!=o&&(e.L=n(2*(e.p=o))),a=65536,e.qb&&(a=t-1,a|=a>>1,a|=a>>2,a|=a>>4,a|=a>>8,a>>=1,(a|=65535)>16777216&&(a>>=1),e.Ec=a,++a,a+=e.R),a!=e.rc&&(e.ub=n(e.rc=a)))}function O(e){var t;++e.k>=e.p&&(e.k=0),function(e){++e.o,e.o>e.zb&&(e.f+e.o>e.H&&function(e){var t,n,i;for((i=e.f+e.o-e.Bc)>0&&--i,n=e.f+e.h-i,t=0;n>t;++t)e.c[t]=e.c[i+t];e.f-=i}(e),_(e))}(e),1073741823==e.o&&(t=e.o-e.p,N(e.L,2*e.p,t),N(e.ub,e.rc,t),P(e,t))}function N(e,t,n){var i,s;for(i=0;t>i;++i)n>=(s=e[i]||0)?s=0:s-=n,e[i]=s}function R(e,t){(null==e.Lb||e.M!=t)&&(e.Lb=n(t)),e.M=t,e.o=0,e.h=0}function M(e){var t=e.o-e.h;t&&(w(e.cc,e.Lb,e.h,t),e.o>=e.M&&(e.o=0),e.h=e.o)}function D(e,t){var n=e.o-t-1;return 0>n&&(n+=e.M),e.Lb[n]}function L(e){M(e),e.cc=null}function F(e){return 4>(e-=2)?e:3}function B(e){return 4>e?0:10>e?e-3:e-6}function $(e){if(!e.zc)throw Error("bad state");return e.cb?function(e){(function(e,t,n,s){var o,u,d,h,f,m,g,b,y,v,w,k,x,A,E;if(t[0]=Ge,n[0]=Ge,s[0]=1,e.oc&&(e.b.cc=e.oc,function(e){e.f=0,e.o=0,e.h=0,e.T=0,_(e),e.k=0,P(e,-1)}(e.b),e.W=1,e.oc=null),!e.pc){if(e.pc=1,A=e.g,a(e.g,Ge)){if(!I(e.b))return void Q(e,c(e.g));ie(e),x=c(e.g)&e.y,Pe(e.d,e.C,(e.l<<4)+x,0),e.l=B(e.l),d=S(e.b,-e.s),fe(pe(e.A,c(e.g),e.J),e.d,d),e.J=d,--e.s,e.g=i(e.g,ze)}if(!I(e.b))return void Q(e,c(e.g));for(;;){if(g=Z(e,c(e.g)),v=e.mb,x=c(e.g)&e.y,u=(e.l<<4)+x,1==g&&-1==v)Pe(e.d,e.C,u,0),d=S(e.b,-e.s),E=pe(e.A,c(e.g),e.J),7>e.l?fe(E,e.d,d):(y=S(e.b,-e.v[0]-1-e.s),me(E,e.d,y,d)),e.J=d,e.l=B(e.l);else{if(Pe(e.d,e.C,u,1),4>v){if(Pe(e.d,e.bb,e.l,1),v?(Pe(e.d,e.hb,e.l,1),1==v?Pe(e.d,e.Ub,e.l,0):(Pe(e.d,e.Ub,e.l,1),Pe(e.d,e.vc,e.l,v-2))):(Pe(e.d,e.hb,e.l,0),Pe(e.d,e._,u,1==g?0:1)),1==g?e.l=7>e.l?9:11:(le(e.i,e.d,g-2,x),e.l=7>e.l?8:11),h=e.v[v],0!=v){for(m=v;m>=1;--m)e.v[m]=e.v[m-1];e.v[0]=h}}else{for(Pe(e.d,e.bb,e.l,0),e.l=7>e.l?7:10,le(e.$,e.d,g-2,x),k=re(v-=4),b=F(g),xe(e.K[b],e.d,k),k>=4&&(w=v-(o=(2|1&k)<<(f=(k>>1)-1)),14>k?Se(e.Sb,o-k-1,e.d,f,w):(Ue(e.d,w>>4,f-4),Ee(e.S,e.d,15&w),++e.Qb)),h=v,m=3;m>=1;--m)e.v[m]=e.v[m-1];e.v[0]=h,++e.Mb}e.J=S(e.b,g-1-e.s)}if(e.s-=g,e.g=i(e.g,l(g)),!e.s){if(e.Mb>=128&&X(e),e.Qb>=16&&K(e),t[0]=e.g,n[0]=Oe(e.d),!I(e.b))return void Q(e,c(e.g));if(r(p(e.g,A),[4096,0])>=0)return e.pc=0,void(s[0]=0)}}}})(e.cb,e.cb.Xb,e.cb.uc,e.cb.Kc),e.Pb=e.cb.Xb[0],e.cb.Kc[0]&&(function(e){se(e),e.d.Ab=null}(e.cb),e.zc=0)}(e):function(e){var t=function(e){var t,n,s,o,a,u;if(u=c(e.g)&e.Dc,Ie(e.e,e.Gb,(e.U<<4)+u)){if(Ie(e.e,e.Zb,e.U))s=0,Ie(e.e,e.Cb,e.U)?(Ie(e.e,e.Db,e.U)?(Ie(e.e,e.Eb,e.U)?(n=e.Qc,e.Qc=e.Ic):n=e.Ic,e.Ic=e.Jc):n=e.Jc,e.Jc=e.ib,e.ib=n):Ie(e.e,e.pb,(e.U<<4)+u)||(e.U=7>e.U?9:11,s=1),s||(s=q(e.sb,e.e,u)+2,e.U=7>e.U?8:11);else if(e.Qc=e.Ic,e.Ic=e.Jc,e.Jc=e.ib,s=2+q(e.Rb,e.e,u),e.U=7>e.U?7:10,(a=we(e.kb[F(s)],e.e))>=4){if(o=(a>>1)-1,e.ib=(2|1&a)<<o,14>a)e.ib+=function(e,t,n,i){var s,r,o=1,a=0;for(r=0;i>r;++r)s=Ie(n,e,t+o),o<<=1,o+=s,a|=s<<r;return a}(e.kc,e.ib-a-1,e.e,o);else if(e.ib+=function(e,t){var n,i,s=0;for(n=t;0!=n;--n)e.E>>>=1,i=e.Bb-e.E>>>31,e.Bb-=e.E&i-1,s=s<<1|1-i,-16777216&e.E||(e.Bb=e.Bb<<8|m(e.Ab),e.E<<=8);return s}(e.e,o-4)<<4,e.ib+=function(e,t){var n,i,s=1,r=0;for(i=0;e.F>i;++i)n=Ie(t,e.G,s),s<<=1,s+=n,r|=n<<i;return r}(e.Fb,e.e),0>e.ib)return-1==e.ib?1:-1}else e.ib=a;if(r(l(e.ib),e.g)>=0||e.ib>=e.nb)return-1;(function(e,t,n){var i=e.o-t-1;for(0>i&&(i+=e.M);0!=n;--n)i>=e.M&&(i=0),e.Lb[e.o++]=e.Lb[i++],e.o>=e.M&&M(e)})(e.B,e.ib,s),e.g=i(e.g,l(s)),e.jc=D(e.B,0)}else t=function(e,t,n){return e.V[((t&e.qc)<<e.u)+((255&n)>>>8-e.u)]}(e.gb,c(e.g),e.jc),e.jc=7>e.U?function(e,t){var n=1;do{n=n<<1|Ie(t,e.Ib,n)}while(256>n);return n<<24>>24}(t,e.e):function(e,t,n){var i,s,r=1;do{if(s=n>>7&1,n<<=1,i=Ie(t,e.Ib,(1+s<<8)+r),r=r<<1|i,s!=i){for(;256>r;)r=r<<1|Ie(t,e.Ib,r);break}}while(256>r);return r<<24>>24}(t,e.e,D(e.B,e.ib)),function(e,t){e.Lb[e.o++]=t,e.o>=e.M&&M(e)}(e.B,e.jc),e.U=B(e.U),e.g=i(e.g,ze);return 0}(e.Z);if(-1==t)throw Error("corrupted input");e.Pb=qe,e.Pc=e.Z.g,(t||r(e.Z.Nc,Ge)>=0&&r(e.Z.g,e.Z.Nc)>=0)&&(M(e.Z.B),L(e.Z.B),e.Z.e.Ab=null,e.zc=0)}(e),e.zc}function j(e){e.B={},e.e={},e.Gb=n(192),e.Zb=n(12),e.Cb=n(12),e.Db=n(12),e.Eb=n(12),e.pb=n(192),e.kb=n(4),e.kc=n(114),e.Fb=ve({},4),e.Rb=H({}),e.sb=H({}),e.gb={};for(var t=0;4>t;++t)e.kb[t]=ve({},6);return e}function V(e,t){for(;t>e.O;++e.O)e.ec[e.O]=ve({},3),e.hc[e.O]=ve({},3)}function q(e,t,n){return Ie(t,e.wc,0)?8+(Ie(t,e.wc,1)?8+we(e.tc,t):we(e.hc[n],t)):we(e.ec[n],t)}function H(e){return e.wc=n(2),e.ec=n(16),e.hc=n(16),e.tc=ve({},8),e.O=0,e}function G(e){_e(e.wc);for(var t=0;e.O>t;++t)_e(e.ec[t].G),_e(e.hc[t].G);_e(e.tc.G)}function z(e,t,i){var s,r;if(null==e.V||e.u!=i||e.I!=t)for(e.I=t,e.qc=(1<<t)-1,e.u=i,r=1<<e.u+e.I,e.V=n(r),s=0;r>s;++s)e.V[s]=W({})}function W(e){return e.Ib=n(768),e}function J(e,t){var n,i,s,r;e.jb=t,s=e.a[t].r,i=e.a[t].j;do{e.a[t].t&&(ye(e.a[s]),e.a[s].r=s-1,e.a[t].Ac&&(e.a[s-1].t=0,e.a[s-1].r=e.a[t].r2,e.a[s-1].j=e.a[t].j2)),r=s,n=i,i=e.a[r].j,s=e.a[r].r,e.a[r].j=n,e.a[r].r=t,t=r}while(t>0);return e.mb=e.a[0].j,e.q=e.a[0].r}function Y(e){var t;for(e.v=n(4),e.a=[],e.d={},e.C=n(192),e.bb=n(12),e.hb=n(12),e.Ub=n(12),e.vc=n(12),e._=n(192),e.K=[],e.Sb=n(114),e.S=ke({},4),e.$=ce({}),e.i=ce({}),e.A={},e.m=[],e.P=[],e.lb=[],e.nc=n(16),e.x=n(4),e.Q=n(4),e.Xb=[Ge],e.uc=[Ge],e.Kc=[0],e.fc=n(5),e.yc=n(128),e.vb=0,e.X=1,e.D=0,e.Hb=-1,e.mb=0,t=0;4096>t;++t)e.a[t]={};for(t=0;4>t;++t)e.K[t]=ke({},6);return e}function K(e){for(var t=0;16>t;++t)e.nc[t]=Te(e.S,t);e.Qb=0}function X(e){var t,n,i,s,r,o,a,l;for(s=4;128>s;++s)t=(2|1&(o=re(s)))<<(i=(o>>1)-1),e.yc[s]=Ce(e.Sb,t-o-1,i,s-t);for(r=0;4>r;++r){for(n=e.K[r],a=r<<6,o=0;e.$b>o;++o)e.P[a+o]=Ae(n,o);for(o=14;e.$b>o;++o)e.P[a+o]+=(o>>1)-1-4<<6;for(l=128*r,s=0;4>s;++s)e.lb[l+s]=e.P[a+s];for(;128>s;++s)e.lb[l+s]=e.P[a+re(s)]+e.yc[s]}e.Mb=0}function Q(e,t){se(e),function(e,t){if(e.Gc){Pe(e.d,e.C,(e.l<<4)+t,1),Pe(e.d,e.bb,e.l,0),e.l=7>e.l?7:10,le(e.$,e.d,0,t);var n=F(2);xe(e.K[n],e.d,63),Ue(e.d,67108863,26),Ee(e.S,e.d,15)}}(e,t&e.y);for(var n=0;5>n;++n)Ne(e.d)}function Z(e,t){var n,i,s,r,o,a,l,c,u,d,h,p,f,m,g,b,y,v,w,k,x,A,E,T,_,P,U,O,N,R,M,D,L,F,$,j,V,q,H,G,z,W,Y,K;if(e.jb!=e.q)return f=e.a[e.q].r-e.q,e.mb=e.a[e.q].j,e.q=e.a[e.q].r,f;if(e.q=e.jb=0,e.N?(p=e.vb,e.N=0):p=ie(e),P=e.D,2>(T=I(e.b)+1))return e.mb=-1,1;for(T>273&&(T=273),H=0,u=0;4>u;++u)e.x[u]=e.v[u],e.Q[u]=C(e.b,-1,e.x[u],273),e.Q[u]>e.Q[H]&&(H=u);if(e.Q[H]>=e.n)return e.mb=H,ne(e,(f=e.Q[H])-1),f;if(p>=e.n)return e.mb=e.m[P-1]+4,ne(e,p-1),p;if(l=S(e.b,-1),y=S(e.b,-e.v[0]-1-1),2>p&&l!=y&&2>e.Q[H])return e.mb=-1,1;if(e.a[0].Hc=e.l,L=t&e.y,e.a[1].z=Ye[e.C[(e.l<<4)+L]>>>2]+be(pe(e.A,t,e.J),e.l>=7,y,l),ye(e.a[1]),q=(v=Ye[2048-e.C[(e.l<<4)+L]>>>2])+Ye[2048-e.bb[e.l]>>>2],y==l&&(G=q+function(e,t,n){return Ye[e.hb[t]>>>2]+Ye[e._[(t<<4)+n]>>>2]}(e,e.l,L),e.a[1].z>G&&(e.a[1].z=G,function(e){e.j=0,e.t=0}(e.a[1]))),2>(h=p>=e.Q[H]?p:e.Q[H]))return e.mb=e.a[1].j,1;e.a[1].r=0,e.a[0].bc=e.x[0],e.a[0].ac=e.x[1],e.a[0].dc=e.x[2],e.a[0].lc=e.x[3],d=h;do{e.a[d--].z=268435455}while(d>=2);for(u=0;4>u;++u)if(!(2>(V=e.Q[u]))){$=q+te(e,u,e.l,L);do{r=$+ue(e.i,V-2,L),(R=e.a[V]).z>r&&(R.z=r,R.r=0,R.j=u,R.t=0)}while(--V>=2)}if(E=v+Ye[e.bb[e.l]>>>2],p>=(d=e.Q[0]>=2?e.Q[0]+1:2)){for(U=0;d>e.m[U];)U+=2;for(;r=E+ee(e,c=e.m[U+1],d,L),(R=e.a[d]).z>r&&(R.z=r,R.r=0,R.j=c+4,R.t=0),d!=e.m[U]||(U+=2)!=P;++d);}for(n=0;;){if(++n==h)return J(e,n);if(w=ie(e),P=e.D,w>=e.n)return e.vb=w,e.N=1,J(e,n);if(++t,D=e.a[n].r,e.a[n].t?(--D,e.a[n].Ac?(W=e.a[e.a[n].r2].Hc,W=4>e.a[n].j2?7>W?8:11:7>W?7:10):W=e.a[D].Hc,W=B(W)):W=e.a[D].Hc,D==n-1?W=e.a[n].j?B(W):7>W?9:11:(e.a[n].t&&e.a[n].Ac?(D=e.a[n].r2,M=e.a[n].j2,W=7>W?8:11):W=4>(M=e.a[n].j)?7>W?8:11:7>W?7:10,N=e.a[D],4>M?M?1==M?(e.x[0]=N.ac,e.x[1]=N.bc,e.x[2]=N.dc,e.x[3]=N.lc):2==M?(e.x[0]=N.dc,e.x[1]=N.bc,e.x[2]=N.ac,e.x[3]=N.lc):(e.x[0]=N.lc,e.x[1]=N.bc,e.x[2]=N.ac,e.x[3]=N.dc):(e.x[0]=N.bc,e.x[1]=N.ac,e.x[2]=N.dc,e.x[3]=N.lc):(e.x[0]=M-4,e.x[1]=N.bc,e.x[2]=N.ac,e.x[3]=N.dc)),e.a[n].Hc=W,e.a[n].bc=e.x[0],e.a[n].ac=e.x[1],e.a[n].dc=e.x[2],e.a[n].lc=e.x[3],a=e.a[n].z,l=S(e.b,-1),y=S(e.b,-e.x[0]-1-1),L=t&e.y,i=a+Ye[e.C[(W<<4)+L]>>>2]+be(pe(e.A,t,S(e.b,-2)),W>=7,y,l),k=0,(x=e.a[n+1]).z>i&&(x.z=i,x.r=n,x.j=-1,x.t=0,k=1),q=(v=a+Ye[2048-e.C[(W<<4)+L]>>>2])+Ye[2048-e.bb[W]>>>2],y!=l||n>x.r&&!x.j||(G=q+(Ye[e.hb[W]>>>2]+Ye[e._[(W<<4)+L]>>>2]),x.z>=G&&(x.z=G,x.r=n,x.j=0,x.t=0,k=1)),!(2>(T=_=(_=I(e.b)+1)>4095-n?4095-n:_))){if(T>e.n&&(T=e.n),!k&&y!=l&&(K=Math.min(_-1,e.n),(g=C(e.b,0,e.x[0],K))>=2)){for(Y=B(W),F=t+1&e.y,A=i+Ye[2048-e.C[(Y<<4)+F]>>>2]+Ye[2048-e.bb[Y]>>>2],O=n+1+g;O>h;)e.a[++h].z=268435455;r=A+(ue(e.i,g-2,F)+te(e,0,Y,F)),(R=e.a[O]).z>r&&(R.z=r,R.r=n+1,R.j=0,R.t=1,R.Ac=0)}for(z=2,j=0;4>j;++j)if(!(2>(m=C(e.b,-1,e.x[j],T)))){b=m;do{for(;n+m>h;)e.a[++h].z=268435455;r=q+(ue(e.i,m-2,L)+te(e,j,W,L)),(R=e.a[n+m]).z>r&&(R.z=r,R.r=n,R.j=j,R.t=0)}while(--m>=2);if(m=b,j||(z=m+1),_>m&&(K=Math.min(_-1-m,e.n),(g=C(e.b,m,e.x[j],K))>=2)){for(Y=7>W?8:11,F=t+m&e.y,s=q+(ue(e.i,m-2,L)+te(e,j,W,L))+Ye[e.C[(Y<<4)+F]>>>2]+be(pe(e.A,t+m,S(e.b,m-1-1)),1,S(e.b,m-1-(e.x[j]+1)),S(e.b,m-1)),Y=B(Y),F=t+m+1&e.y,A=s+Ye[2048-e.C[(Y<<4)+F]>>>2]+Ye[2048-e.bb[Y]>>>2],O=m+1+g;n+O>h;)e.a[++h].z=268435455;r=A+(ue(e.i,g-2,F)+te(e,0,Y,F)),(R=e.a[n+O]).z>r&&(R.z=r,R.r=n+m+1,R.j=0,R.t=1,R.Ac=1,R.r2=n,R.j2=j)}}if(w>T){for(w=T,P=0;w>e.m[P];P+=2);e.m[P]=w,P+=2}if(w>=z){for(E=v+Ye[e.bb[W]>>>2];n+w>h;)e.a[++h].z=268435455;for(U=0;z>e.m[U];)U+=2;for(m=z;;++m)if(r=E+ee(e,o=e.m[U+1],m,L),(R=e.a[n+m]).z>r&&(R.z=r,R.r=n,R.j=o+4,R.t=0),m==e.m[U]){if(_>m&&(K=Math.min(_-1-m,e.n),(g=C(e.b,m,o,K))>=2)){for(Y=7>W?7:10,F=t+m&e.y,s=r+Ye[e.C[(Y<<4)+F]>>>2]+be(pe(e.A,t+m,S(e.b,m-1-1)),1,S(e.b,m-(o+1)-1),S(e.b,m-1)),Y=B(Y),F=t+m+1&e.y,A=s+Ye[2048-e.C[(Y<<4)+F]>>>2]+Ye[2048-e.bb[Y]>>>2],O=m+1+g;n+O>h;)e.a[++h].z=268435455;r=A+(ue(e.i,g-2,F)+te(e,0,Y,F)),(R=e.a[n+O]).z>r&&(R.z=r,R.r=n+m+1,R.j=0,R.t=1,R.Ac=1,R.r2=n,R.j2=o+4)}if((U+=2)==P)break}}}}}function ee(e,t,n,i){var s=F(n);return(128>t?e.lb[128*s+t]:e.P[(s<<6)+function(e){return 131072>e?Je[e>>6]+12:134217728>e?Je[e>>16]+32:Je[e>>26]+52}(t)]+e.nc[15&t])+ue(e.$,n-2,i)}function te(e,t,n,i){var s;return t?(s=Ye[2048-e.hb[n]>>>2],1==t?s+=Ye[e.Ub[n]>>>2]:(s+=Ye[2048-e.Ub[n]>>>2],s+=Re(e.vc[n],t-2))):(s=Ye[e.hb[n]>>>2],s+=Ye[2048-e._[(n<<4)+i]>>>2]),s}function ne(e,t){t>0&&(function(e,t){var n,i,s,r,o,a,l,c,u,d,h,p,f,m,g,b,y;do{if(e.h>=e.o+e.ob)p=e.ob;else if(p=e.h-e.o,e.xb>p){O(e);continue}for(f=e.o>e.p?e.o-e.p:0,i=e.f+e.o,e.qb?(a=1023&(y=We[255&e.c[i]]^255&e.c[i+1]),e.ub[a]=e.o,l=65535&(y^=(255&e.c[i+2])<<8),e.ub[1024+l]=e.o,c=(y^We[255&e.c[i+3]]<<5)&e.Ec):c=255&e.c[i]^(255&e.c[i+1])<<8,s=e.ub[e.R+c],e.ub[e.R+c]=e.o,g=1+(e.k<<1),b=e.k<<1,d=h=e.w,n=e.Fc;;){if(f>=s||0==n--){e.L[g]=e.L[b]=0;break}if(o=e.o-s,r=(e.k>=o?e.k-o:e.k-o+e.p)<<1,m=e.f+s,u=h>d?d:h,e.c[m+u]==e.c[i+u]){for(;++u!=p&&e.c[m+u]==e.c[i+u];);if(u==p){e.L[b]=e.L[r],e.L[g]=e.L[r+1];break}}(255&e.c[i+u])>(255&e.c[m+u])?(e.L[b]=s,b=r+1,s=e.L[b],h=u):(e.L[g]=s,g=r,s=e.L[g],d=u)}O(e)}while(0!=--t)}(e.b,t),e.s+=t)}function ie(e){var t=0;return e.D=function(e,t){var n,i,s,r,o,a,l,c,u,d,h,p,f,m,g,b,y,v,w,k,x;if(e.h>=e.o+e.ob)m=e.ob;else if(m=e.h-e.o,e.xb>m)return O(e),0;for(y=0,g=e.o>e.p?e.o-e.p:0,i=e.f+e.o,b=1,c=0,u=0,e.qb?(c=1023&(x=We[255&e.c[i]]^255&e.c[i+1]),u=65535&(x^=(255&e.c[i+2])<<8),d=(x^We[255&e.c[i+3]]<<5)&e.Ec):d=255&e.c[i]^(255&e.c[i+1])<<8,s=e.ub[e.R+d]||0,e.qb&&(r=e.ub[c]||0,o=e.ub[1024+u]||0,e.ub[c]=e.o,e.ub[1024+u]=e.o,r>g&&e.c[e.f+r]==e.c[i]&&(t[y++]=b=2,t[y++]=e.o-r-1),o>g&&e.c[e.f+o]==e.c[i]&&(o==r&&(y-=2),t[y++]=b=3,t[y++]=e.o-o-1,r=o),0!=y&&r==s&&(y-=2,b=1)),e.ub[e.R+d]=e.o,w=1+(e.k<<1),k=e.k<<1,p=f=e.w,0!=e.w&&s>g&&e.c[e.f+s+e.w]!=e.c[i+e.w]&&(t[y++]=b=e.w,t[y++]=e.o-s-1),n=e.Fc;;){if(g>=s||0==n--){e.L[w]=e.L[k]=0;break}if(l=e.o-s,a=(e.k>=l?e.k-l:e.k-l+e.p)<<1,v=e.f+s,h=f>p?p:f,e.c[v+h]==e.c[i+h]){for(;++h!=m&&e.c[v+h]==e.c[i+h];);if(h>b&&(t[y++]=b=h,t[y++]=l-1,h==m)){e.L[k]=e.L[a],e.L[w]=e.L[a+1];break}}(255&e.c[i+h])>(255&e.c[v+h])?(e.L[k]=s,k=a+1,s=e.L[k],f=h):(e.L[w]=s,w=a,s=e.L[w],p=h)}return O(e),y}(e.b,e.m),e.D>0&&((t=e.m[e.D-2])==e.n&&(t+=C(e.b,t-1,e.m[e.D-1],273-t))),++e.s,t}function se(e){e.b&&e.W&&(e.b.cc=null,e.W=0)}function re(e){return 2048>e?Je[e]:2097152>e?Je[e>>10]+20:Je[e>>20]+40}function oe(e,t){_e(e.db);for(var n=0;t>n;++n)_e(e.Vb[n].G),_e(e.Wb[n].G);_e(e.ic.G)}function ae(e,t,n,i,s){var r,o,a,l,c;for(r=Ye[e.db[0]>>>2],a=(o=Ye[2048-e.db[0]>>>2])+Ye[e.db[1]>>>2],l=o+Ye[2048-e.db[1]>>>2],c=0,c=0;8>c;++c){if(c>=n)return;i[s+c]=r+Ae(e.Vb[t],c)}for(;16>c;++c){if(c>=n)return;i[s+c]=a+Ae(e.Wb[t],c-8)}for(;n>c;++c)i[s+c]=l+Ae(e.ic,c-8-8)}function le(e,t,n,i){(function(e,t,n,i){8>n?(Pe(t,e.db,0,0),xe(e.Vb[i],t,n)):(n-=8,Pe(t,e.db,0,1),8>n?(Pe(t,e.db,1,0),xe(e.Wb[i],t,n)):(Pe(t,e.db,1,1),xe(e.ic,t,n-8)))})(e,t,n,i),0==--e.sc[i]&&(ae(e,i,e.rb,e.Cc,272*i),e.sc[i]=e.rb)}function ce(e){return function(e){e.db=n(2),e.Vb=n(16),e.Wb=n(16),e.ic=ke({},8);for(var t=0;16>t;++t)e.Vb[t]=ke({},3),e.Wb[t]=ke({},3)}(e),e.Cc=[],e.sc=[],e}function ue(e,t,n){return e.Cc[272*n+t]}function de(e,t){for(var n=0;t>n;++n)ae(e,n,e.rb,e.Cc,272*n),e.sc[n]=e.rb}function he(e,t,i){var s,r;if(null==e.V||e.u!=i||e.I!=t)for(e.I=t,e.qc=(1<<t)-1,e.u=i,r=1<<e.u+e.I,e.V=n(r),s=0;r>s;++s)e.V[s]=ge({})}function pe(e,t,n){return e.V[((t&e.qc)<<e.u)+((255&n)>>>8-e.u)]}function fe(e,t,n){var i,s,r=1;for(s=7;s>=0;--s)i=n>>s&1,Pe(t,e.tb,r,i),r=r<<1|i}function me(e,t,n,i){var s,r,o,a,l=1,c=1;for(r=7;r>=0;--r)s=i>>r&1,a=c,l&&(a+=1+(o=n>>r&1)<<8,l=o==s),Pe(t,e.tb,a,s),c=c<<1|s}function ge(e){return e.tb=n(768),e}function be(e,t,n,i){var s,r,o=1,a=7,l=0;if(t)for(;a>=0;--a)if(r=n>>a&1,s=i>>a&1,l+=Re(e.tb[(1+r<<8)+o],s),o=o<<1|s,r!=s){--a;break}for(;a>=0;--a)s=i>>a&1,l+=Re(e.tb[o],s),o=o<<1|s;return l}function ye(e){e.j=-1,e.t=0}function ve(e,t){return e.F=t,e.G=n(1<<t),e}function we(e,t){var n,i=1;for(n=e.F;0!=n;--n)i=(i<<1)+Ie(t,e.G,i);return i-(1<<e.F)}function ke(e,t){return e.F=t,e.G=n(1<<t),e}function xe(e,t,n){var i,s,r=1;for(s=e.F;0!=s;)i=n>>>--s&1,Pe(t,e.G,r,i),r=r<<1|i}function Ae(e,t){var n,i,s=1,r=0;for(i=e.F;0!=i;)n=t>>>--i&1,r+=Re(e.G[s],n),s=(s<<1)+n;return r}function Ee(e,t,n){var i,s,r=1;for(s=0;e.F>s;++s)i=1&n,Pe(t,e.G,r,i),r=r<<1|i,n>>=1}function Te(e,t){var n,i,s=1,r=0;for(i=e.F;0!=i;--i)n=1&t,t>>>=1,r+=Re(e.G[s],n),s=s<<1|n;return r}function Se(e,t,n,i,s){var r,o,a=1;for(o=0;i>o;++o)Pe(n,e,t+a,r=1&s),a=a<<1|r,s>>=1}function Ce(e,t,n,i){var s,r,o=1,a=0;for(r=n;0!=r;--r)s=1&i,i>>>=1,a+=Ye[(2047&(e[t+o]-s^-s))>>>2],o=o<<1|s;return a}function Ie(e,t,n){var i,s=t[n];return(-2147483648^(i=(e.E>>>11)*s))>(-2147483648^e.Bb)?(e.E=i,t[n]=s+(2048-s>>>5)<<16>>16,-16777216&e.E||(e.Bb=e.Bb<<8|m(e.Ab),e.E<<=8),0):(e.E-=i,e.Bb-=i,t[n]=s-(s>>>5)<<16>>16,-16777216&e.E||(e.Bb=e.Bb<<8|m(e.Ab),e.E<<=8),1)}function _e(e){for(var t=e.length-1;t>=0;--t)e[t]=1024}function Pe(e,t,n,r){var o,a=t[n];o=(e.E>>>11)*a,r?(e.xc=i(e.xc,s(l(o),[4294967295,0])),e.E-=o,t[n]=a-(a>>>5)<<16>>16):(e.E=o,t[n]=a+(2048-a>>>5)<<16>>16),-16777216&e.E||(e.E<<=8,Ne(e))}function Ue(e,t,n){for(var s=n-1;s>=0;--s)e.E>>>=1,1==(t>>>s&1)&&(e.xc=i(e.xc,l(e.E))),-16777216&e.E||(e.E<<=8,Ne(e))}function Oe(e){return i(i(l(e.Jb),e.mc),[4,0])}function Ne(e){var t,n=c(function(e,t){var n;return n=h(e,t&=63),0>e[1]&&(n=i(n,d([2,0],63-t))),n}(e.xc,32));if(0!=n||r(e.xc,[4278190080,0])<0){e.mc=i(e.mc,l(e.Jb)),t=e.Oc;do{v(e.Ab,t+n),t=255}while(0!=--e.Jb);e.Oc=c(e.xc)>>>24}++e.Jb,e.xc=d(s(e.xc,[16777215,0]),8)}function Re(e,t){return Ye[(2047&(e-t^-t))>>>2]}function Me(e){for(var t,n,i,s=0,r=0,o=e.length,a=[],l=[];o>s;++s,++r){if(128&(t=255&e[s]))if(192==(224&t)){if(s+1>=o)return e;if(128!=(192&(n=255&e[++s])))return e;l[r]=(31&t)<<6|63&n}else{if(224!=(240&t))return e;if(s+2>=o)return e;if(128!=(192&(n=255&e[++s])))return e;if(128!=(192&(i=255&e[++s])))return e;l[r]=(15&t)<<12|(63&n)<<6|63&i}else{if(!t)return e;l[r]=t}16383==r&&(a.push(String.fromCharCode.apply(String,l)),r=-1)}return r>0&&(l.length=r,a.push(String.fromCharCode.apply(String,l))),a.join("")}function De(e){var t,n,i,s=[],r=0,o=e.length;if("object"==typeof e)return e;for(function(e,t,n,i,s){var r;for(r=t;n>r;++r)i[s++]=e.charCodeAt(r)}(e,0,o,s,0),i=0;o>i;++i)(t=s[i])>=1&&127>=t?++r:r+=!t||t>=128&&2047>=t?2:3;for(n=[],r=0,i=0;o>i;++i)(t=s[i])>=1&&127>=t?n[r++]=t<<24>>24:!t||t>=128&&2047>=t?(n[r++]=(192|t>>6&31)<<24>>24,n[r++]=(128|63&t)<<24>>24):(n[r++]=(224|t>>12&15)<<24>>24,n[r++]=(128|t>>6&63)<<24>>24,n[r++]=(128|63&t)<<24>>24);return n}function Le(e){return e[1]+e[0]}var Fe=1,Be=2,$e=3,je="function"==typeof setImmediate?setImmediate:setTimeout,Ve=4294967296,qe=[4294967295,-Ve],He=[0,-0x8000000000000000],Ge=[0,0],ze=[1,0],We=function(){var e,t,n,i=[];for(e=0;256>e;++e){for(n=e,t=0;8>t;++t)0!=(1&n)?n=n>>>1^-306674912:n>>>=1;i[e]=n}return i}(),Je=function(){var e,t,n,i=2,s=[0,1];for(n=2;22>n;++n)for(t=1<<(n>>1)-1,e=0;t>e;++e,++i)s[i]=n<<24>>24;return s}(),Ye=function(){var e,t,n,i=[];for(t=8;t>=0;--t)for(e=1<<9-t,n=1<<9-t-1;e>n;++n)i[n]=(t<<6)+(e-n<<6>>>9-t-1);return i}(),Ke=function(){var e=[{s:16,f:64,m:0},{s:20,f:64,m:0},{s:19,f:64,m:1},{s:20,f:64,m:1},{s:21,f:128,m:1},{s:22,f:128,m:1},{s:23,f:128,m:1},{s:24,f:255,m:1},{s:25,f:255,m:1}];return function(t){return e[t-1]||e[6]}}();return"undefined"==typeof onmessage||"undefined"!=typeof window&&void 0!==window.document||(onmessage=function(t){t&&t.gc&&(t.gc.action==Be?e.decompress(t.gc.gc,t.gc.cbn):t.gc.action==Fe&&e.compress(t.gc.gc,t.gc.Rc,t.gc.cbn))}),{compress:function(e,n,i,s){var r,o,a={},l=void 0===i&&void 0===s;if("function"!=typeof i&&(o=i,i=s=0),s=s||function(e){return void 0!==o?t(e,o):void 0},i=i||function(e,t){return void 0!==o?postMessage({action:Fe,cbn:o,result:e,error:t}):void 0},l){for(a.c=A({},De(e),Ke(n));$(a.c.yb););return y(a.c.Nb)}try{a.c=A({},De(e),Ke(n)),s(0)}catch(e){return i(null,e)}je((function e(){try{for(var t,n=(new Date).getTime();$(a.c.yb);)if(r=Le(a.c.yb.Pb)/Le(a.c.Tb),(new Date).getTime()-n>200)return s(r),je(e,0),0;s(1),t=y(a.c.Nb),je(i.bind(null,t),0)}catch(e){i(null,e)}}),0)},decompress:function(e,n,i){var s,r,o,a,l={},c=void 0===n&&void 0===i;if("function"!=typeof n&&(r=n,n=i=0),i=i||function(e){return void 0!==r?t(o?e:-1,r):void 0},n=n||function(e,t){return void 0!==r?postMessage({action:Be,cbn:r,result:e,error:t}):void 0},c){for(l.d=T({},e);$(l.d.yb););return Me(y(l.d.Nb))}try{l.d=T({},e),a=Le(l.d.Tb),o=a>-1,i(0)}catch(e){return n(null,e)}je((function e(){try{for(var t,r=0,c=(new Date).getTime();$(l.d.yb);)if(++r%1e3==0&&(new Date).getTime()-c>200)return o&&(s=Le(l.d.yb.Z.g)/a,i(s)),je(e,0),0;i(1),t=Me(y(l.d.Nb)),je(n.bind(null,t),0)}catch(e){n(null,e)}}),0)}}}(),pxt,pxt,pxt,pxt,pxt,ts;this.LZMA=this.LZMA_WORKER=e,function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).DOMPurify=t()}(this,(function(){"use strict";var e=Object.hasOwnProperty,t=Object.setPrototypeOf,n=Object.isFrozen,i=Object.keys,s=Object.freeze,r=Object.seal,o=Object.create,a="undefined"!=typeof Reflect&&Reflect,l=a.apply,c=a.construct;l||(l=function(e,t,n){return e.apply(t,n)}),s||(s=function(e){return e}),r||(r=function(e){return e}),c||(c=function(e,t){return new(Function.prototype.bind.apply(e,[null].concat(function(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}(t))))});var u=E(Array.prototype.forEach),d=E(Array.prototype.indexOf),h=E(Array.prototype.join),p=E(Array.prototype.pop),f=E(Array.prototype.push),m=E(Array.prototype.slice),g=E(String.prototype.toLowerCase),b=E(String.prototype.match),y=E(String.prototype.replace),v=E(String.prototype.indexOf),w=E(String.prototype.trim),k=E(RegExp.prototype.test),x=T(RegExp),A=T(TypeError);function E(e){return function(t){for(var n=arguments.length,i=Array(n>1?n-1:0),s=1;s<n;s++)i[s-1]=arguments[s];return l(e,t,i)}}function T(e){return function(){for(var t=arguments.length,n=Array(t),i=0;i<t;i++)n[i]=arguments[i];return c(e,n)}}function S(e,i){t&&t(e,null);for(var s=i.length;s--;){var r=i[s];if("string"==typeof r){var o=g(r);o!==r&&(n(i)||(i[s]=o),r=o)}e[r]=!0}return e}function C(t){var n=o(null),i=void 0;for(i in t)l(e,t,[i])&&(n[i]=t[i]);return n}var I=s(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),_=s(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","audio","canvas","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","video","view","vkern"]),P=s(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),U=s(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover"]),O=s(["#text"]),N=s(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","face","for","headers","height","hidden","high","href","hreflang","id","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","playsinline","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","xmlns"]),R=s(["accent-height","accumulate","additive","alignment-baseline","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","targetx","targety","transform","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),M=s(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),D=s(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),L=r(/\{\{[\s\S]*|[\s\S]*\}\}/gm),F=r(/<%[\s\S]*|[\s\S]*%>/gm),B=r(/^data-[\-\w.\u00B7-\uFFFF]/),$=r(/^aria-[\-\w]+$/),j=r(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),V=r(/^(?:\w+script|data):/i),q=r(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),H="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};function G(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}var z=function(){return"undefined"==typeof window?null:window},W=function(e,t){if("object"!==(void 0===e?"undefined":H(e))||"function"!=typeof e.createPolicy)return null;var n=null;t.currentScript&&t.currentScript.hasAttribute("data-tt-policy-suffix")&&(n=t.currentScript.getAttribute("data-tt-policy-suffix"));var i="dompurify"+(n?"#"+n:"");try{return e.createPolicy(i,{createHTML:function(e){return e}})}catch(e){return console.warn("TrustedTypes policy "+i+" could not be created."),null}};return function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:z(),n=function(t){return e(t)};if(n.version="2.0.17",n.removed=[],!t||!t.document||9!==t.document.nodeType)return n.isSupported=!1,n;var r=t.document,o=!1,a=t.document,l=t.DocumentFragment,c=t.HTMLTemplateElement,E=t.Node,T=t.NodeFilter,J=t.NamedNodeMap,Y=void 0===J?t.NamedNodeMap||t.MozNamedAttrMap:J,K=t.Text,X=t.Comment,Q=t.DOMParser,Z=t.trustedTypes;if("function"==typeof c){var ee=a.createElement("template");ee.content&&ee.content.ownerDocument&&(a=ee.content.ownerDocument)}var te=W(Z,r),ne=te&&Me?te.createHTML(""):"",ie=a,se=ie.implementation,re=ie.createNodeIterator,oe=ie.getElementsByTagName,ae=ie.createDocumentFragment,le=r.importNode,ce={};try{ce=C(a).documentMode?a.documentMode:{}}catch(e){}var ue={};n.isSupported=se&&void 0!==se.createHTMLDocument&&9!==ce;var de=L,he=F,pe=B,fe=$,me=V,ge=q,be=j,ye=null,ve=S({},[].concat(G(I),G(_),G(P),G(U),G(O))),we=null,ke=S({},[].concat(G(N),G(R),G(M),G(D))),xe=null,Ae=null,Ee=!0,Te=!0,Se=!1,Ce=!1,Ie=!1,_e=!1,Pe=!1,Ue=!1,Oe=!1,Ne=!1,Re=!1,Me=!1,De=!0,Le=!0,Fe=!1,Be={},$e=S({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","plaintext","script","style","svg","template","thead","title","video","xmp"]),je=null,Ve=S({},["audio","video","img","source","image","track"]),qe=null,He=S({},["alt","class","for","id","label","name","pattern","placeholder","summary","title","value","style","xmlns"]),Ge=null,ze=a.createElement("form"),We=function(e){Ge&&Ge===e||(e&&"object"===(void 0===e?"undefined":H(e))||(e={}),e=C(e),ye="ALLOWED_TAGS"in e?S({},e.ALLOWED_TAGS):ve,we="ALLOWED_ATTR"in e?S({},e.ALLOWED_ATTR):ke,qe="ADD_URI_SAFE_ATTR"in e?S(C(He),e.ADD_URI_SAFE_ATTR):He,je="ADD_DATA_URI_TAGS"in e?S(C(Ve),e.ADD_DATA_URI_TAGS):Ve,xe="FORBID_TAGS"in e?S({},e.FORBID_TAGS):{},Ae="FORBID_ATTR"in e?S({},e.FORBID_ATTR):{},Be="USE_PROFILES"in e&&e.USE_PROFILES,Ee=!1!==e.ALLOW_ARIA_ATTR,Te=!1!==e.ALLOW_DATA_ATTR,Se=e.ALLOW_UNKNOWN_PROTOCOLS||!1,Ce=e.SAFE_FOR_JQUERY||!1,Ie=e.SAFE_FOR_TEMPLATES||!1,_e=e.WHOLE_DOCUMENT||!1,Oe=e.RETURN_DOM||!1,Ne=e.RETURN_DOM_FRAGMENT||!1,Re=e.RETURN_DOM_IMPORT||!1,Me=e.RETURN_TRUSTED_TYPE||!1,Ue=e.FORCE_BODY||!1,De=!1!==e.SANITIZE_DOM,Le=!1!==e.KEEP_CONTENT,Fe=e.IN_PLACE||!1,be=e.ALLOWED_URI_REGEXP||be,Ie&&(Te=!1),Ne&&(Oe=!0),Be&&(ye=S({},[].concat(G(O))),we=[],!0===Be.html&&(S(ye,I),S(we,N)),!0===Be.svg&&(S(ye,_),S(we,R),S(we,D)),!0===Be.svgFilters&&(S(ye,P),S(we,R),S(we,D)),!0===Be.mathMl&&(S(ye,U),S(we,M),S(we,D))),e.ADD_TAGS&&(ye===ve&&(ye=C(ye)),S(ye,e.ADD_TAGS)),e.ADD_ATTR&&(we===ke&&(we=C(we)),S(we,e.ADD_ATTR)),e.ADD_URI_SAFE_ATTR&&S(qe,e.ADD_URI_SAFE_ATTR),Le&&(ye["#text"]=!0),_e&&S(ye,["html","head","body"]),ye.table&&(S(ye,["tbody"]),delete xe.tbody),s&&s(e),Ge=e)},Je=function(e){f(n.removed,{element:e});try{e.parentNode.removeChild(e)}catch(t){e.outerHTML=ne}},Ye=function(e,t){try{f(n.removed,{attribute:t.getAttributeNode(e),from:t})}catch(e){f(n.removed,{attribute:null,from:t})}t.removeAttribute(e)},Ke=function(e){var t=void 0,n=void 0;if(Ue)e="<remove></remove>"+e;else{var i=b(e,/^[\r\n\t ]+/);n=i&&i[0]}var s=te?te.createHTML(e):e;try{t=(new Q).parseFromString(s,"text/html")}catch(e){}if(o&&S(xe,["title"]),!t||!t.documentElement){var r=(t=se.createHTMLDocument("")).body;r.parentNode.removeChild(r.parentNode.firstElementChild),r.outerHTML=s}return e&&n&&t.body.insertBefore(a.createTextNode(n),t.body.childNodes[0]||null),oe.call(t,_e?"html":"body")[0]};n.isSupported&&function(){try{var e=Ke("<x/><title>&lt;/title&gt;&lt;img&gt;");k(/<\/title/,e.querySelector("title").innerHTML)&&(o=!0)}catch(e){}}();var Xe=function(e){return re.call(e.ownerDocument||e,e,T.SHOW_ELEMENT|T.SHOW_COMMENT|T.SHOW_TEXT,(function(){return T.FILTER_ACCEPT}),!1)},Qe=function(e){return!(e instanceof K||e instanceof X||"string"==typeof e.nodeName&&"string"==typeof e.textContent&&"function"==typeof e.removeChild&&e.attributes instanceof Y&&"function"==typeof e.removeAttribute&&"function"==typeof e.setAttribute&&"string"==typeof e.namespaceURI)},Ze=function(e){return"object"===(void 0===E?"undefined":H(E))?e instanceof E:e&&"object"===(void 0===e?"undefined":H(e))&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName},et=function(e,t,i){ue[e]&&u(ue[e],(function(e){e.call(n,t,i,Ge)}))},tt=function(e){var t=void 0;if(et("beforeSanitizeElements",e,null),Qe(e))return Je(e),!0;if(b(e.nodeName,/[\u0080-\uFFFF]/))return Je(e),!0;var i=g(e.nodeName);if(et("uponSanitizeElement",e,{tagName:i,allowedTags:ye}),("svg"===i||"math"===i)&&0!==e.querySelectorAll("p, br, form, table").length)return Je(e),!0;if(!ye[i]||xe[i]){if(Le&&!$e[i]&&"function"==typeof e.insertAdjacentHTML)try{var s=e.innerHTML;e.insertAdjacentHTML("AfterEnd",te?te.createHTML(s):s)}catch(e){}return Je(e),!0}return"noscript"===i&&k(/<\/noscript/i,e.innerHTML)||"noembed"===i&&k(/<\/noembed/i,e.innerHTML)?(Je(e),!0):(!Ce||Ze(e.firstElementChild)||Ze(e.content)&&Ze(e.content.firstElementChild)||!k(/</g,e.textContent)||(f(n.removed,{element:e.cloneNode()}),e.innerHTML?e.innerHTML=y(e.innerHTML,/</g,"&lt;"):e.innerHTML=y(e.textContent,/</g,"&lt;")),Ie&&3===e.nodeType&&(t=e.textContent,t=y(t,de," "),t=y(t,he," "),e.textContent!==t&&(f(n.removed,{element:e.cloneNode()}),e.textContent=t)),et("afterSanitizeElements",e,null),!1)},nt=function(e,t,n){if(De&&("id"===t||"name"===t)&&(n in a||n in ze))return!1;if(Te&&k(pe,t));else if(Ee&&k(fe,t));else{if(!we[t]||Ae[t])return!1;if(qe[t]);else if(k(be,y(n,ge,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==v(n,"data:")||!je[e])if(Se&&!k(me,y(n,ge,"")));else if(n)return!1}return!0},it=function(e){var t=void 0,s=void 0,r=void 0,o=void 0,a=void 0;et("beforeSanitizeAttributes",e,null);var l=e.attributes;if(l){var c={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:we};for(a=l.length;a--;){var u=t=l[a],f=u.name,b=u.namespaceURI;if(s=w(t.value),r=g(f),c.attrName=r,c.attrValue=s,c.keepAttr=!0,c.forceKeepAttr=void 0,et("uponSanitizeAttribute",e,c),s=c.attrValue,!c.forceKeepAttr){if("name"===r&&"IMG"===e.nodeName&&l.id)o=l.id,l=m(l,[]),Ye("id",e),Ye(f,e),d(l,o)>a&&e.setAttribute("id",o.value);else{if("INPUT"===e.nodeName&&"type"===r&&"file"===s&&c.keepAttr&&(we[r]||!Ae[r]))continue;"id"===f&&e.setAttribute(f,""),Ye(f,e)}if(c.keepAttr)if(Ce&&k(/\/>/i,s))Ye(f,e);else if(k(/svg|math/i,e.namespaceURI)&&k(x("</("+h(i($e),"|")+")","i"),s))Ye(f,e);else{Ie&&(s=y(s,de," "),s=y(s,he," "));var v=e.nodeName.toLowerCase();if(nt(v,r,s))try{b?e.setAttributeNS(b,f,s):e.setAttribute(f,s),p(n.removed)}catch(e){}}}}et("afterSanitizeAttributes",e,null)}},st=function e(t){var n=void 0,i=Xe(t);for(et("beforeSanitizeShadowDOM",t,null);n=i.nextNode();)et("uponSanitizeShadowNode",n,null),tt(n)||(n.content instanceof l&&e(n.content),it(n));et("afterSanitizeShadowDOM",t,null)};return n.sanitize=function(e,i){var s=void 0,o=void 0,a=void 0,c=void 0,u=void 0;if(e||(e="\x3c!--\x3e"),"string"!=typeof e&&!Ze(e)){if("function"!=typeof e.toString)throw A("toString is not a function");if("string"!=typeof(e=e.toString()))throw A("dirty is not a string, aborting")}if(!n.isSupported){if("object"===H(t.toStaticHTML)||"function"==typeof t.toStaticHTML){if("string"==typeof e)return t.toStaticHTML(e);if(Ze(e))return t.toStaticHTML(e.outerHTML)}return e}if(Pe||We(i),n.removed=[],"string"==typeof e&&(Fe=!1),Fe);else if(e instanceof E)1===(o=(s=Ke("\x3c!--\x3e")).ownerDocument.importNode(e,!0)).nodeType&&"BODY"===o.nodeName||"HTML"===o.nodeName?s=o:s.appendChild(o);else{if(!Oe&&!Ie&&!_e&&-1===e.indexOf("<"))return te&&Me?te.createHTML(e):e;if(!(s=Ke(e)))return Oe?null:ne}s&&Ue&&Je(s.firstChild);for(var d=Xe(Fe?e:s);a=d.nextNode();)3===a.nodeType&&a===c||tt(a)||(a.content instanceof l&&st(a.content),it(a),c=a);if(c=null,Fe)return e;if(Oe){if(Ne)for(u=ae.call(s.ownerDocument);s.firstChild;)u.appendChild(s.firstChild);else u=s;return Re&&(u=le.call(r,u,!0)),u}var h=_e?s.outerHTML:s.innerHTML;return Ie&&(h=y(h,de," "),h=y(h,he," ")),te&&Me?te.createHTML(h):h},n.setConfig=function(e){We(e),Pe=!0},n.clearConfig=function(){Ge=null,Pe=!1},n.isValidAttribute=function(e,t,n){Ge||We({});var i=g(e),s=g(t);return nt(i,s,n)},n.addHook=function(e,t){"function"==typeof t&&(ue[e]=ue[e]||[],f(ue[e],t))},n.removeHook=function(e){ue[e]&&p(ue[e])},n.removeHooks=function(e){ue[e]&&(ue[e]=[])},n.removeAllHooks=function(){ue={}},n}()})),pxt||(pxt={}),function(e){!function(t){const n={},i={};let s,r=!1;function o(e){Object.keys(e).forEach((t=>{"string"==typeof e[t]?n[t]=e[t]:i[t]=e[t]}))}!function(e){e[e.Off=0]="Off",e[e.Short=1]="Short",e[e.Verbose=2]="Verbose"}(s=t.ConsoleTickOptions||(t.ConsoleTickOptions={})),t.consoleTicks=s.Off,t.addDefaultProperties=o,t.enable=function(a){if(!e.aiTrackException||!e.aiTrackEvent||r)return;r=!0,"string"==typeof a&&0!=a.length||(a="en"),o({lang:a}),e.debug("setting up app insights");const l=e.tickEvent;e.tickEvent=function(r,o,a){if(t.consoleTicks!=s.Off){const e=t.consoleTicks==s.Short?"":`${(new Date).toLocaleTimeString(void 0,{hour12:!1})} - Tick - `,n=`${r} ${o?JSON.stringify(o):"<no data>"} ${a?JSON.stringify(a):"<no opts>"}`;console.log(e+n)}if(l&&l(r,o,a),(null==a?void 0:a.interactiveConsent)&&e.setInteractiveConsent(!0),o){const t=Object.assign({},n)||{},s=Object.assign({},i)||{};Object.keys(o).forEach((e=>{"string"==typeof o[e]?t[e]=o[e]:"number"==typeof o[e]?s[e]=o[e]:t[e]=JSON.stringify(o[e]||"")})),e.aiTrackEvent(r,t,s)}else e.aiTrackEvent(r)};const c=e.reportException;e.reportException=function(t,n){c&&c(t,n);const i={target:e.appTarget.id,version:e.appTarget.versions.target};n&&e.Util.jsonMergeFrom(i,n),e.aiTrackException(t,"exception",i)};const u=e.reportError;e.reportError=function(t,n,i){u&&u(t,n,i);try{throw n}catch(s){const r={target:e.appTarget.id,version:e.appTarget.versions.target,category:t,message:n};i&&e.Util.jsonMergeFrom(r,i),e.aiTrackException(s,"error",r)}}},t.trackPerformanceReport=function(){if(e.perf.perfReportLogged)return;const t=e.perf.report();if(t){const{durations:n,milestones:i}=t;e.tickEvent("performance.milestones",i),e.tickEvent("performance.durations",n)}}}(e.analytics||(e.analytics={}))}(pxt||(pxt={})),pxt||(pxt={}),function(e){!function(e){let t,n,i,s=0,r=!1;function o(){return t||(t=function(){if(window.AudioContext=window.AudioContext||window.webkitAudioContext,window.AudioContext)try{return new window.AudioContext}catch(e){}return}()),t}function a(){t&&(i.gain.setTargetAtTime(0,t.currentTime,.015),s=0)}e.mute=function(e){t&&(r=e,a(),e&&n&&(n.disconnect(),i.disconnect(),n=void 0,i=void 0))},e.stop=a,e.frequency=function(){return s},e.tone=function(e){if(r)return;if(isNaN(e)||e<0)return;s=e;let a=o();if(a)try{n||(n=a.createOscillator(),n.type="triangle",i=a.createGain(),i.gain.value=0,i.connect(a.destination),n.connect(i),n.start(0)),n.frequency.linearRampToValueAtTime(e,t.currentTime),i.gain.setTargetAtTime(.2,t.currentTime,.015)}catch(e){return void(n=void 0)}}}(e.AudioContextManager||(e.AudioContextManager={}))}(pxt||(pxt={})),function(e){!function(t){const n="auth",i="csrf-token",s="login-state",r="user-state",o="interactive-login-until";let a,l=!1;t.DEFAULT_USER_PREFERENCES=()=>({highContrast:!1,language:e.appTarget.appTheme.defaultLocale,reader:"",skillmap:{mapProgress:{},completedTags:{}},email:!1}),t.client=function(){if(!l)return a};let c=0,u=0;async function d(t,i){return i?await e.storage.shared.setAsync(n,t,i):await e.storage.shared.delAsync(n,t)}async function h(t){try{return await e.storage.shared.getAsync(n,t)}catch(e){return}}async function p(){const e=await h(i);return t.cachedHasAuthToken=!!e,e}async function f(e){return t.cachedHasAuthToken=!!e,await d(i,e)}async function m(){return!!await p()}async function g(){return t.cachedHasAuthToken=!1,await d(i,void 0)}async function b(){let i;try{i=await e.storage.shared.getAsync(n,r)}catch(e){i={}}return t.cachedUserState=i,i}async function y(i){return t.cachedUserState=Object.assign({},i),await e.storage.shared.setAsync(n,r,i)}async function v(){return t.cachedUserState=void 0,await e.storage.shared.delAsync(n,r)}async function w(t){var n;const i={};return(t=t||await p())&&(i.authorization=`mkcd ${t}`),i["x-pxt-target"]=null===(n=e.appTarget)||void 0===n?void 0:n.id,i}t.cachedHasAuthToken=!1,t.getAuthTokenAsync=p,t.hasAuthTokenAsync=m,t.getUserStateAsync=b,t.getAuthHeadersAsync=w;class k{constructor(){this.initialUserPreferences_=void 0,this.initialAuthCheck_=void 0,this.patchQueue=[],a=this}async initAsync(){const e=await b();this.setUserProfileAsync(null==e?void 0:e.profile),this.setUserPreferencesAsync(null==e?void 0:e.preferences)}async loginAsync(t,i,r){if(!E()||!function(e){return A().filter((t=>t.id===e)).length>0}(t))return;r=null!=r?r:x,this.clearAuthStateAsync();const a={key:(Math.PI*Math.random()).toString(36).slice(2),callbackState:r,callbackPathname:window.location.pathname,idp:t,persistent:i},l=(parseInt(await h(o))||0)>Date.now(),c=e.Util.stringifyQueryString("/api/auth/login",{response_type:"token",provider:t,persistent:i,redirect_uri:`${window.location.origin}${window.location.pathname}?authcallback=1&state=${a.key}`,prompt:l?"select_account":"silent"}),u=await this.apiAsync(c);if(u.success)a.authCodeVerifier=u.resp.authCodeVerifier,await e.storage.shared.setAsync(n,s,a),e.tickEvent("auth.login.start",{provider:t}),window.location.href=u.resp.loginUrl;else try{await this.onSignInFailed()}catch(e){}}async logoutAsync(e){if(E()){await k.staticLogoutAsync(e);try{await this.onStateCleared()}catch(e){}try{await this.onSignedOut()}catch(e){}}}static async staticLogoutAsync(t){if(!E())return;e.tickEvent("auth.logout"),await d(o,(Date.now()+6e4).toString()),t=t?t.startsWith("#")?t:`#${t}`:"";const n=`${window.location.origin}${window.location.pathname}${window.location.search}${t}`;let i="";try{const t=e.Util.stringifyQueryString("/api/auth/logout",{redirect_uri:n,authcallback:"1"}),s=await k.staticApiAsync(t);s.success&&(i=s.resp.logoutUrl)}catch(e){}await g(),await v(),e.BrowserUtils.hasWindow()&&(i?window.location.href=i:(window.location.href=n,location.reload()))}async deleteProfileAsync(){var t;if(!await this.loggedInAsync())return;const n=await b(),i=null===(t=null==n?void 0:n.profile)||void 0===t?void 0:t.id,s=await this.apiAsync("/api/user",null,"DELETE");if(s.err)try{await this.onApiError(s.err)}catch(e){}else try{await this.clearAuthStateAsync();try{await this.onProfileDeleted(i)}catch(e){}}finally{e.tickEvent("auth.profile.deleted")}}async initialUserPreferencesAsync(){if(await this.loggedInAsync())return this.initialUserPreferences_||(this.initialUserPreferences_=this.fetchUserPreferencesAsync()),this.initialUserPreferences_}async userProfileAsync(){if(!await this.loggedInAsync())return;const e=await b();return Object.assign({},e.profile)}async userPreferencesAsync(){const e=await b();return Object.assign({},e.preferences)}async authCheckAsync(){var e;if(!E())return;if(!await m())return;const t=await b();return(null===(e=null==t?void 0:t.profile)||void 0===e?void 0:e.id)?this.initialAuthCheck_||(this.initialAuthCheck_=Promise.resolve(t.profile)):this.initialAuthCheck_||(this.initialAuthCheck_=this.fetchUserAsync()),this.initialAuthCheck_}async loggedInAsync(){return!!await this.authCheckAsync()&&await this.hasUserIdAsync()}async updateUserProfileAsync(e){if(!await this.loggedInAsync())return!1;const t=await b(),n=await this.apiAsync("/api/user/profile",{id:t.profile.id,username:e.username,avatarUrl:e.avatarUrl});return n.success&&await this.setUserProfileAsync(n.resp),n.success}async patchUserPreferencesAsync(n,i={}){const s=async()=>({success:!0,res:await this.userPreferencesAsync()});if(!(n=(n=Array.isArray(n)?n:[n]).filter((e=>!!e))).length)return await s();const r=(t,n,i)=>{const s=e.U.deepCopy(t);ts.pxtc.jsonPatch.patchInPlace(s,n);let r=ts.pxtc.jsonPatch.diff(t,s);return r.length&&i&&(r=r.filter(i)),r},o=await this.userPreferencesAsync(),a=r(o,n,i.filter);if(!a.length)return await s();if(ts.pxtc.jsonPatch.patchInPlace(o,a),await this.setUserPreferencesAsync(o),!await this.loggedInAsync())return await s();this.patchQueue.push({ops:n,filter:i.filter}),clearTimeout(c);const l=async()=>{if(u=0,!this.patchQueue.length)return await s();const n=await this.apiAsync("/api/user/preferences");if(!n.success)return e.reportError("identity","failed to fetch preferences for patch",n),{success:!1,res:void 0};const i=e.U.deepCopy(n.resp)||t.DEFAULT_USER_PREFERENCES(),o=this.patchQueue;this.patchQueue=[],o.forEach((e=>{const t=r(i,e.ops,e.filter);ts.pxtc.jsonPatch.patchInPlace(i,t)}));const a=pxtc.jsonPatch.diff(n.resp,i),l=await this.apiAsync("/api/user/preferences",a,"PATCH");return l.success?this.setUserPreferencesAsync(l.resp):e.reportError("identity","failed to patch preferences",l),{success:l.success,res:l.resp}};return i.immediate?await l():(u||(u=e.U.now()),1e4<e.U.now()-u?await l():(c=setTimeout(l,1e3),{success:!1,res:void 0}))}async hasUserIdAsync(){var e;if(!E())return!1;if(!await m())return;const t=await b();return!!(null===(e=null==t?void 0:t.profile)||void 0===e?void 0:e.id)}async fetchUserAsync(){var e;if(!E())return;if(!await m())return;const t=await b();if(null===(e=null==t?void 0:t.profile)||void 0===e?void 0:e.id)return t.profile;const n=await this.apiAsync("/api/user/profile");if(n.success){const e=n.resp;return await this.setUserProfileAsync(e),e}}async setUserProfileAsync(e){const t=await this.hasUserIdAsync();await this.transformUserProfileAsync(e);const n=await this.hasUserIdAsync();try{await this.onUserProfileChanged()}catch(e){}if(n&&!t)try{await this.onSignedIn()}catch(e){}else if(!n&&t)try{await this.onSignedOut()}catch(e){}}async setUserPreferencesAsync(e){var n;const i=await b(),s=null!==(n=null==i?void 0:i.preferences)&&void 0!==n?n:t.DEFAULT_USER_PREFERENCES(),r=ts.pxtc.jsonPatch.diff(s,e),o=await this.transformUserPreferencesAsync(Object.assign(Object.assign({},s),e));try{await this.onUserPreferencesChanged(r)}catch(e){}return o}async fetchUserPreferencesAsync(){if(!await this.loggedInAsync())return;await b();const e=await this.apiAsync("/api/user/preferences");if(e.success&&e.resp){return this.setUserPreferencesAsync(e.resp)}}async transformUserProfileAsync(e){let t=await b();return t=Object.assign(Object.assign({},t),{profile:Object.assign({},e)}),await y(t),t.profile}async transformUserPreferencesAsync(e){let t=await b();return t=Object.assign(Object.assign({},t),{preferences:Object.assign({},e)}),await y(t),t.preferences}async clearAuthStateAsync(){await g(),await v();try{await this.onStateCleared()}catch(e){}}async apiAsync(e,t,n,i){return await k.staticApiAsync(e,t,n,i)}static async staticApiAsync(t,n,i,s){const r=await w(s);return t=e.BrowserUtils.isLocalHostDev()?`${e.cloud.DEV_BACKEND}${t}`:t,e.Util.requestAsync({url:t,headers:r,data:n,method:i||(n?"POST":"GET"),withCredentials:!0}).then((e=>({statusCode:e.statusCode,resp:e.json,success:2===Math.floor(e.statusCode/100),err:null}))).catch((async e=>(/logout/.test(t)||401!=e.statusCode||await k.staticLogoutAsync(),{statusCode:e.statusCode,err:e,resp:null,success:!1})))}}t.AuthClient=k;const x={hash:"",params:{}};function A(){var t,n;return Object.keys((null===(n=null===(t=e.appTarget)||void 0===t?void 0:t.cloud)||void 0===n?void 0:n.cloudProviders)||{}).map((t=>e.appTarget.cloud.cloudProviders[t])).filter((e=>e.identity)).sort(((e,t)=>e.order-t.order))}function E(){return!l&&!e.BrowserUtils.isPxtElectron()&&A().length>0}function T(e,t){return e.id===t.id&&e.sourceURL===t.sourceURL}t.loginCallbackAsync=async function(t){let i,r=Object.assign({},x);do{if(i=await e.storage.shared.getAsync(n,s),!i)return void e.debug("Auth state not found in storge.");await e.storage.shared.delAsync(n,s);const a=t.state;if(!a||i.key!==a)return void e.debug("Failed to get auth state for key");r=Object.assign(Object.assign({},x),i.callbackState);const l=t.error;if(l){const n=t.error_description;e.tickEvent("auth.login.error",{error:l,provider:i.idp}),e.log(`Auth failed: ${l}:${n}`),r=Object.assign({},x);break}const c=t.token;if(!c){e.debug("Missing authToken in auth callback.");break}if(i.authCodeVerifier){const t=e.Util.stringifyQueryString("/api/otac/check",{persistent:i.persistent});await k.staticApiAsync(t,null,null,i.authCodeVerifier)}await f(c),await d(o,void 0),e.tickEvent("auth.login.success",{provider:i.idp})}while(0);const a=r.hash.startsWith("#")?r.hash:`#${r.hash}`,l=e.Util.stringifyQueryString("",r.params),c=`${i.callbackPathname.startsWith("/")?i.callbackPathname:`/${i.callbackPathname}`}${l}${a}`;window.location.href=c},t.identityProviders=A,t.identityProvider=function(e){return A().filter((t=>t.id===e)).shift()},t.hasIdentity=E,t.enableAuth=function(e=!0){l=!e},t.userName=function(e){var t,n,i,s;return null!==(s=null!==(n=null===(t=null==e?void 0:e.idp)||void 0===t?void 0:t.displayName)&&void 0!==n?n:null===(i=null==e?void 0:e.idp)||void 0===i?void 0:i.username)&&void 0!==s?s:"??"},t.identityProviderId=function(e){var t;return null===(t=null==e?void 0:e.idp)||void 0===t?void 0:t.provider},t.firstName=function(t){const n=e.auth.userName(t);return(null==n?void 0:n.split(" ").shift())||n},t.userInitials=function(t){const n=e.auth.userName(t);return ts.pxtc.Util.initials(n)},t.generateUserProfilePicDataUrl=function(t){var n,i;if(null===(i=null===(n=null==t?void 0:t.idp)||void 0===n?void 0:n.picture)||void 0===i?void 0:i.encoded){const n=window.URL||window.webkitURL;try{const i=e.Util.stringToUint8Array(atob(t.idp.picture.encoded)),s=new Blob([i],{type:t.idp.picture.mimeType});t.idp.picture.dataUrl=n.createObjectURL(s)}catch(e){}}},t.badgeEquals=T,t.hasBadge=function(e,t){return e.badges.some((e=>T(e,t)))}}(e.auth||(e.auth={}))}(pxt||(pxt={})),function(e){e.tickEvent=function(e){}}(pxt||(pxt={})),function(e){!function(e){e.__dummy=42}(e.pxtc||(e.pxtc={}))}(ts||(ts={}));var pxtc=ts.pxtc;!function(e){!function(e){!function(e){function t(e){return e.replace(/[^\w .!?\-$]/g,(e=>{let t=e.charCodeAt(0).toString(16);return"\\u"+"0000".substr(0,4-t.length)+t}))}e.assert=function(e,t="Assertion failed"){if(!e)throw new Error(t)},e.flatClone=function(e){if(null==e)return null;let t={};return Object.keys(e).forEach((n=>{t[n]=e[n]})),t},e.clone=function(e){return null==e?null:JSON.parse(JSON.stringify(e))},e.htmlEscape=function(e){return e?e.replace(/([^\w .!?\-$])/g,(e=>"&#"+e.charCodeAt(0)+";")):e},e.htmlUnescape=function(e){return e?e.replace(/(&#\d+;)/g,(e=>String.fromCharCode(Number(e.substr(2,e.length-3))))):e},e.jsStringQuote=t,e.jsStringLiteral=function(e){return'"'+t(e)+'"'},e.initials=function(e){if(/^\w+@/.test(e)){return e.match(/^\w\w/).shift().toUpperCase()}{const t=e.match(/\b\w/g)||[];return((t.shift()||"")+(t.pop()||"")).toUpperCase()}};let n="en",i={},s={},r=!1;function o(){return n}function a(e){const t=/^(\w{2,3})-(\w{2,4}$)/i.exec(e);return t&&t[1]&&t[2]?[`${t[1].toLowerCase()}-${t[2].toUpperCase()}`,t[1].toLowerCase(),`${t[1].toLowerCase()}-${t[2].toLowerCase()}`]:[(e||"en").toLowerCase()]}function l(t,n){return 0==n.length?t:t.replace(/\{([0-9]+)(\:[^\}]+)?\}/g,(function(t,i,s){let r=n[parseInt(i)],o="",a=/^:f(\d*)\.(\d+)/.exec(s);if(a){let e=parseInt(a[2]),t=parseInt(a[1])||0,n=/^0/.test(a[1])?"0":" ",i=r.toFixed(e);if(t>0&&e>0&&(t+=e+1),t>0)for(;i.length<t;)i=n+i;o=i}else o=":x"==s?"0x"+r.toString(16):void 0===r?"(undef)":null===r?"(null)":r.toString?r.toString():r+"";return":a"==s?/^\s*[euioah]/.test(o.toLowerCase())?o="an "+o:/^\s*[bcdfgjklmnpqrstvwxz]/.test(o.toLowerCase())&&(o="a "+o):":s"==s?o=1==r?"":"s":":q"==s?o=e.htmlEscape(o):":jq"==s?o=e.jsStringQuote(o):":uri"==s?o=encodeURIComponent(o).replace(/'/g,"%27").replace(/"/g,"%22"):":url"==s?o=encodeURI(o).replace(/'/g,"%27").replace(/"/g,"%22"):":%"==s&&(o=(100*r).toFixed(1).toString()+"%"),o}))}e.enableLiveLocalizationUpdates=function(){r=!0},e.liveLocalizationEnabled=function(){return r},e.localeInfo=function(){return`${r?"live-":""}${o()}`},e.userLanguage=o,e.normalizeLanguageCode=a,e.setUserLanguage=function(e){n=a(e)[0]},e.isUserLanguageRtl=function(){return/^ar|dv|fa|ha|he|ks|ku|ps|ur|yi/i.test(n)},e.TRANSLATION_LOCALE="pxt",e.isTranslationMode=function(){return o()==e.TRANSLATION_LOCALE},e._localize=function(e){return i[e]||e},e.getLocalizedStrings=function(){return i},e.setLocalizedStrings=function(e){i=e},e.translationsCache=function(){return s},e.fmt_va=l,e.fmt=function(e,...t){return l(e,t)};const c={};e.dumpLocStats=function(){const e={};Object.keys(c).sort(((e,t)=>c[t]-c[e])).forEach((t=>e[t]=t)),console.log("prioritized list of strings:"),console.log(JSON.stringify(e,null,2))};function u(t,n){if(!t)return t;c[t]=(c[t]||0)+1;let i=e._localize(t);return i=i.replace(/^\{(id|loc):[^\}]+\}/g,""),l(i,n)}e.lf_va=u,e.lf=function(e,...t){return u(e,t)},e.rlf=function(e,...t){return u(e,t)},e.lookup=function(e,t){return e.hasOwnProperty(t)?e[t]:null},e.isoTime=function(t){let n=new Date(1e3*t);return e.fmt("{0}-{1:f02.0}-{2:f02.0} {3:f02.0}:{4:f02.0}:{5:f02.0}",n.getFullYear(),n.getMonth()+1,n.getDate(),n.getHours(),n.getMinutes(),n.getSeconds())},e.userError=function(e){let t=new Error(e);throw t.isUserError=!0,t},e.deq=function e(t,n){if(t===n)return null;if(!t||!n)return"Null value";if("object"==typeof t&&"object"==typeof n){if(Array.isArray(t)){if(!Array.isArray(n))return"Expected array";if(t.length!=n.length)return"Expected array of length "+t.length+", got "+n.length;for(let i=0;i<t.length;i++)if(null!=e(t[i],n[i]))return"Expected array value "+t[i]+" got "+n[i];return null}let i=Object.keys(t),s=Object.keys(t);if(i.length!=s.length)return"Expected "+i.length+" keys, got "+s.length;for(let s=0;s<i.length;s++){if(!Object.prototype.hasOwnProperty.call(n,i[s]))return"Missing key "+i[s];if(null!=e(t[i[s]],n[i[s]]))return"Expected value of "+i[s]+" to be "+t[i[s]]+", got "+n[i[s]]}return null}return"Unable to compare "+t+", "+n}}(e.Util||(e.Util={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={}));const lf=ts.pxtc.Util.lf;var ts,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,ts,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,ts,pxt,pxt,pxt,pxt,ts,pxt,ts,pxtmelody,pxtmelody,pxtmelody,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim;!function(e){!function(e){e.decodeBase64=function(e){return atob(e)},e.encodeBase64=function(e){return btoa(e)}}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){!function(n){function i(e,t){if(t)for(let n=0;n<t.length;++n)e.push(t[n])}function s(e){let t=[];for(let n=0;n<e.length;++n)i(t,e[n]);return t}function r(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function o(e,t,n,i,s){void 0===i&&(i=0),void 0===s&&(s=n.length-i);for(let r=0;r<s;++r)e[t+r]=n[i+r]}function a(e,t){return e==t?0:e<t?-1:1}n.CancellationToken=class{constructor(){this.pending=!1,this.cancelled=!1}startOperation(){this.pending=!0}isRunning(){return this.pending}onProgress(e){this.progressHandler=e}reportProgress(e,t){this.progressHandler&&this.progressHandler(e,t)}cancel(){this.cancelled=!0,this.pending=!1}cancelAsync(){return this.cancelled||!this.pending?(this.cancelled=!0,this.pending=!1,Promise.resolve()):(this.cancelled=!0,this.deferred=new Promise((e=>{this.resolve=e})),this.deferred)}isCancelled(){return this.cancelled}throwIfCancelled(){if(this.isCancelled())throw new Error}resolveCancel(){this.pending=!1,this.deferred&&(this.resolve(),this.deferred=void 0,this.resolve=void 0)}},n.codalHash16=function(e){const t=[251,175,119,215,81,14,79,191,103,49,181,143,186,157,0,232,31,32,55,60,152,58,17,237,174,70,160,144,220,90,57,223,59,3,18,140,111,166,203,196,134,243,124,95,222,179,197,65,180,48,36,15,107,46,233,130,165,30,123,161,209,23,97,16,40,91,219,61,100,10,210,109,250,127,22,138,29,108,244,67,207,9,178,204,74,98,126,249,167,116,34,77,193,200,121,5,20,113,71,35,128,13,182,94,25,226,227,199,75,27,41,245,230,224,43,225,177,26,155,150,212,142,218,115,241,73,88,105,39,114,62,255,192,201,145,214,168,158,221,148,154,122,12,84,82,163,44,139,228,236,205,242,217,11,187,146,159,64,86,239,195,42,106,198,118,112,184,172,87,2,173,117,176,229,247,253,137,185,99,164,102,147,45,66,231,52,141,211,194,206,246,238,56,110,78,248,63,240,189,93,92,51,53,183,19,171,72,50,33,104,101,69,8,252,83,120,76,135,85,54,202,125,188,213,96,235,136,208,162,129,190,132,156,38,47,1,7,254,24,4,216,131,89,21,28,133,37,153,149,80,170,68,6,169,234,151];function n(e){let n=0;for(let i=0;i<e.length;i++){let s=e[i];n=t[n^s]}return n}return e?function(e,t){let i;const s=new Uint8Array(e.length);for(let t=0;t<e.length;++t){const n=e.charCodeAt(t);s[t]=255&n}let r=0;for(let e=0;e<t;++e)i=n(s),r|=i<<8*e,s[0]=(s[0]+1)%255;return r}(e,2):0},n.bufferSerial=function(e,t="",n="?",i=255){for(let s=0;s<t.length;++s){const r=t[s];if(e[n]=(e[n]||"")+r,"\n"===r||e[n].length>i){let t=e[n];e[n]="",window.postMessage({type:"serial",id:n,data:t},"*")}}},n.blobReadAsDataURL=function(e){return e?new Promise(((t,n)=>{const i=new FileReader;i.onload=()=>t(i.result),i.onerror=e=>n(e),i.readAsDataURL(e)})):Promise.resolve(void 0)},n.fileReadAsBufferAsync=function(e){return e?new Promise(((t,n)=>{let i=new FileReader;i.onerror=e=>t(null),i.onload=e=>t(new Uint8Array(i.result)),i.readAsArrayBuffer(e)})):Promise.resolve(null)},n.fileReadAsTextAsync=function(e){return e?new Promise(((t,n)=>{let i=new FileReader;i.onerror=e=>t(null),i.onload=e=>t(i.result),i.readAsText(e)})):Promise.resolve(null)},n.sanitizeFileName=function(e){return e.replace(/[()\\\/.,?*^:<>!;'#$%^&|"@+=«»°{}\[\]¾½¼³²¦¬¤¢£~­¯¸`±\x00-\x1F]/g,"").trim().replace(/\s+/g,"-")},n.repeatMap=function(e,t){e=e||0;let n=[];for(let i=0;i<e;++i)n.push(t(i));return n},n.listsEqual=function(e,t){if(!e||!t||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0},n.oops=function(e="OOPS"){throw new Error(e)},n.reversed=function(e){return(e=e.slice(0)).reverse(),e},n.arrayEquals=function(e,t,n=((e,t)=>e===t)){if(e==t)return!0;if(!e&&t||!t&&e||e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!n(e[i],t[i]))return!1;return!0},n.iterMap=function(e,t){Object.keys(e).forEach((n=>t(n,e[n])))},n.mapMap=function(e,t){let n={};return Object.keys(e).forEach((i=>n[i]=t(i,e[i]))),n},n.values=function(e){return Object.keys(e||{}).map((t=>e[t]))},n.pushRange=i,n.concatArrayLike=function(e){return s(e)},n.concat=s,n.memcpy=o,n.uint8ArrayConcat=function(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),i=0;for(let t of e)o(n,i,t),i+=t.length;return n},n.jsonTryParse=function(e){try{return JSON.parse(e)}catch(e){return}},n.jsonMergeFrom=function e(t,i){i&&Object.keys(i).forEach((s=>{r(t[s])&&r(i[s])?e(t[s],i[s]):t[s]=n.clone(i[s])}))},n.jsonCopyFrom=function(e,t){let i=n.clone(t);for(let n of Object.keys(t))e[n]=i[n]},n.jsonFlatten=function(e){let t={},i=(e,s)=>{if(null!==s&&"object"==typeof s){n.assert(!Array.isArray(s)),e&&(e+=".");for(let t of Object.keys(s))i(e+t,s[t])}else t[e]=s};return i("",e),t},n.jsonUnFlatten=function(e){let t={};for(let n of Object.keys(e)){let i=t,s=n.split(".");for(let t=0;t<s.length;++t){let r=s[t];t==s.length-1?i[r]=e[n]:("object"!=typeof i[r]&&(i[r]={}),i=i[r])}}return t},n.strcmp=a,n.stringMapEq=function(e,t){let n=Object.keys(e),i=Object.keys(t);if(n.length!=i.length)return!1;for(let i of n){if(!t.hasOwnProperty(i))return!1;if(e[i]!==t[i])return!1}return!0},n.endsWith=function(e,t){return!(e.length<t.length)&&(0==t.length||e.slice(-t.length)==t)},n.startsWith=function(e,t){return!(e.length<t.length)&&(0==t.length||e.slice(0,t.length)==t)},n.contains=function(e,t){return!(e.length<t.length)&&(0==t.length||e.indexOf(t)>-1)},n.replaceAll=function(e,t,n){return t?e.split(t).join(n):e},n.snakify=function(e){const t=e.toUpperCase(),n=e.toLowerCase();if(e==t||e==n)return e;if(e.lastIndexOf("_")>0)return e;const i=t=>e[t]!=n[t],s=n=>e[n]!=t[n];let r="",o=0;for(;o<e.length;){let t=i(o),n=o;for(;n<e.length;){if(t&&s(n)){if(n-o>2){n--;break}t=!1}if(!t&&i(n))break;n++}r&&(r+="_"),r+=e.slice(o,n),o=n}return r.toUpperCase()===r?r:r.toLowerCase()},n.sortObjectFields=function(e){let t=Object.keys(e);t.sort(a);let n={};return t.forEach((t=>n[t]=e[t])),n},n.chopArray=function(e,t){let n=[];for(let i=0;i<e.length;i+=t)n.push(e.slice(i,i+t));return n},n.unique=function(e,t){let n=[],i={};return e.forEach((e=>{let s=t(e);i.hasOwnProperty(s)||(i[s]=null,n.push(e))})),n},n.groupBy=function(e,t){let n={};return e.forEach((e=>{let i=t(e);n.hasOwnProperty(i)||(n[i]=[]),n[i].push(e)})),n},n.toDictionary=function(e,t){let n={};return e.forEach((e=>{n[t(e)]=e})),n},n.toSet=function(e,t){let n={};return e.forEach((e=>{n[t(e)]=!0})),n},n.deepCopy=function e(t){if("object"!=typeof t||null===t)return t;const n=Array.isArray(t)?[]:{};for(const i in t){const s=t[i];n[i]=e(s)}return n},n.toArray=function(e){if(Array.isArray(e))return e;let t=[];if(!e)return t;for(let n=0;n<e.length;++n)t.push(e[n]);return t},n.indexOfMatching=function(e,t){for(let n=0;n<e.length;++n)if(t(e[n]))return n;return-1};const l=Promise.resolve();async function c(e,t,n){let i=0;const s=[],r=[];for(let o=0;o<e;o++){const e=(async()=>{for(;i<t.length;){const e=i++,s=t[e];r[e]=await n(s)}})();s.push(e)}try{await Promise.all(s)}catch(e){throw i=t.length,e}return r}function u(e,t){const n={};return i=>{const s=e(i);return n.hasOwnProperty(s)?n[s]:n[s]=t(i)}}n.nextTick=function(e){l.then(e)},n.delay=async function(e,t){const n=await t;return await new Promise((t=>setTimeout((()=>t()),e))),n},n.promiseMapAll=function(e,t){return Promise.all(e.map((e=>t(e))))},n.promiseMapAllSeries=function(e,t){return c(1,e,t)},n.promisePoolAsync=c,n.memoizeString=function(e){return u((e=>e),e)},n.promiseTimeout=async function(e,t,n){let i,s;const r=new Promise(((t,r)=>{s=t,i=setTimeout((()=>{s=void 0,clearTimeout(i),r(n||`Promise timed out after ${e}ms`)}),e)}));return Promise.race([t,r]).then((e=>(s&&(clearTimeout(i),s()),e)))},n.defer=function(){let e,t,n,i=!1;return{resolve:function(n){i?pxt.debug("Deferred promise already resolved"):(t?t(n):e=e||new Promise((function(e){e(n)})),i=!0)},reject:function(t){i?pxt.debug("Deferred promise already resolved"):(n?n(t):e=e||new Promise((function(e,n){n(t)})),i=!0)},promise:new Promise((function(i,s){e?i(e):(t=i,n=s)}))}},n.memoize=u,n.debounce=function(e,t,n){let i;return function(){let s=this,r=arguments,o=function(){i=null,n||e.apply(s,r)},a=n&&!i;return clearTimeout(i),i=setTimeout(o,t),a&&e.apply(s,r),i}};function d(e){return e&&(e=e.replace(/\\/g,"/")),e}function h(e){return n.httpRequestCoreAsync(e).then((i=>{const s=i.statusCode;if((e.successCodes||[304,200,201,202]).indexOf(s)<0&&!e.allowHttpErrors){const t=n.lf("Bad HTTP status code: {0} at {1}; message: {2}",i.statusCode,e.url,(i.text||"").slice(0,500)),s=new Error(t);return s.statusCode=i.statusCode,Promise.reject(s)}return i.text&&/application\/json/.test(i.headers["content-type"])&&(i.json=t.U.jsonTryParse(i.text)),i}))}function p(e,t){let n="";if(!e)return n;for(let i=0;i<e.length;++i){let s=e.charCodeAt(i);if(s<=127)n+=e.charAt(i);else if(s<=2047)n+=String.fromCharCode(192|s>>6,128|63&s);else{if(!t&&55296<=s&&s<=56319){let t=e.charCodeAt(++i);isNaN(t)||(s=65536+(s-55296<<10)+(t-56320))}n+=s<=65535?String.fromCharCode(224|s>>12,128|s>>6&63,128|63&s):String.fromCharCode(240|s>>18,128|s>>12&63,128|s>>6&63,128|63&s)}}return n}n.AdaptiveDebouncer=class{constructor(e,t=300,n=2e3,i=2){this.func=e,this.minDelay=t,this.maxDelay=n,this.slowdownFactor=i,this.lastPoke=0,this.recentGaps=[],this.wrapped=()=>{this.timeout=null,this.func()}}poke(){const e=Date.now();if(this.lastPoke){const t=e-this.lastPoke;if(t<10)return;for(t<4e3&&this.recentGaps.push(t);this.recentGaps.length>10;)this.recentGaps.shift()}this.lastPoke=e}trigger(){let e=this.maxDelay;if(this.lastPoke){const t=this.recentGaps.slice();t.sort();const n=t[t.length>>1]||1;e=Math.min(Math.max(n*this.slowdownFactor|0,this.minDelay),this.maxDelay);e-=Date.now()-this.lastPoke,e<0&&(e=0),this.lastPoke=null}clearTimeout(this.timeout),this.timeout=setTimeout(this.wrapped,e)}},n.throttle=function(e,t,n){let i;return function(){let s=this,r=arguments,o=function(){i=null,n||e.apply(s,r)},a=n&&!i;i||(i=setTimeout(o,t)),a&&e.apply(s,r)}},n.randomPermute=function(e){for(let t=0;t<e.length;++t){let n=m()%e.length,i=e[t];e[t]=e[n],e[n]=i}},n.randomPick=function(e){return 0==e.length?null:e[m()%e.length]},n.timeSince=function(e){let t=(Date.now()-(e*=1e3))/1e3;return isNaN(t)?"":t<-30?(t=-t,t<60?n.lf("in a few seconds"):t<120?n.lf("in a minute"):t<3600?n.lf("in {0} minute{0:s}",Math.floor(t/60)):t<7200?n.lf("in an hour"):t<86400?n.lf("in {0} hour{0:s}",Math.floor(t/60/60)):t<2592e3?n.lf("in {0} day{0:s}",Math.floor(t/60/60/24)):t<31536e3?n.lf("in {0} month{0:s}",Math.floor(t/60/60/24/30)):n.lf("in {0} year{0:s}",Math.floor(t/60/60/24/365))):t<0?n.lf("now"):t<10?n.lf("a few seconds ago"):t<60?n.lf("{0} second{0:s} ago",Math.floor(t)):t<120?n.lf("a minute ago"):t<3600?n.lf("{0} minute{0:s} ago",Math.floor(t/60)):t<7200?n.lf("an hour ago"):t<86400?n.lf("{0} hour{0:s} ago",Math.floor(t/60/60)):t<2592e3?n.lf("{0} day{0:s} ago",Math.floor(t/60/60/24)):t<31536e3?n.lf("{0} month{0:s} ago",Math.floor(t/60/60/24/30)):n.lf("{0} year{0:s} ago",Math.floor(t/60/60/24/365))},n.unicodeToChar=function(e){return e.replace(/\\u([\d\w]{4})/gi,(function(e,t){return String.fromCharCode(parseInt(t,16))}))},n.escapeForRegex=function(e){return null==e?void 0:e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},n.stripUrlProtocol=function(e){return null==e?void 0:e.replace(/.*?:\/\//g,"")},n.normalizePath=d,n.pathJoin=function(e,t){if(d(e),d(t),e||t)return e?t?("/"!==e.charAt(e.length-1)&&(e+="/"),"/"==t.charAt(0)&&(t=t.substring(1)),e+t):e:t},n.isNodeJS="undefined"==typeof window,n.requestAsync=h,n.httpGetTextAsync=function(e){return h({url:e}).then((e=>e.text))},n.httpGetJsonAsync=function(e){return h({url:e}).then((e=>e.json))},n.httpPostJsonAsync=function(e,t){return h({url:e,data:t||{}}).then((e=>e.json))},n.stringToUint8Array=function(e){let t=e.length,n=new Uint8Array(t);for(let i=0;i<t;++i)n[i]=255&e.charCodeAt(i);return n},n.uint8ArrayToString=function(e){let t=e.length,n="";for(let i=0;i<t;++i)n+=String.fromCharCode(e[i]);return n},n.fromUTF8=function(e){if(!e)return"";let t="";for(let n=0;n<e.length;++n){let i=255&e.charCodeAt(n);t+=37==i||i>127?"%"+i.toString(16):e.charAt(n)}return decodeURIComponent(t)},n.toUTF8=p,n.toHex=function(e){let t="";for(let n=0;n<e.length;++n)t+=("0"+e[n].toString(16)).slice(-2);return t},n.fromHex=function(e){let t=new Uint8Array(e.length>>1);for(let n=0;n<e.length;n+=2)t[n>>1]=parseInt(e.slice(n,n+2),16);return t};n.PromiseQueue=class{constructor(){this.promises={}}enqueue(e,t){return new Promise(((n,i)=>{let s=this.promises[e];s||(s=this.promises[e]=[]),s.push((()=>t().finally((()=>{s.shift(),0==s.length?delete this.promises[e]:s[0]()})).then(n,i))),1==s.length&&s[0]()}))}};function f(){return Date.now()}function m(){let e=new Uint8Array(4);return n.getRandomBuf(e),new Uint32Array(e.buffer)[0]}function g(e,t,n){function i(i){pxt.debug(`downloading translations for ${e} ${t}`);let s=pxt.BrowserUtils.isLocalHost()||pxt.webConfig.isStatic?"https://makecode.com/api/":"",r=`${s}translations?lang=${encodeURIComponent(e)}&filename=${encodeURIComponent(t)}&approved=true`;const o={};return n&&!pxt.Cloud.useCdnApi()&&(o["If-None-Match"]=n),(s?h:pxt.Cloud.apiRequestWithCdnAsync)({url:r,headers:o}).then((s=>304==s.statusCode||200==s.statusCode?(n=s.headers.etag||"",pxt.BrowserUtils.translationDbAsync().then((r=>r.setAsync(e,t,n,s.json||i))).then((()=>s.json||i))):s.json),(e=>{console.log(`failed to load translations from ${r}`)}))}return pxt.BrowserUtils.translationDbAsync().then((n=>n.getAsync(e,t))).then((e=>{if(e){n=e.etag;return(Date.now()-e.time)/1e3>300&&i(e.strings),e.strings}return i()}))}function b(e){let[t,i]=n.normalizeLanguageCode(e),s=pxt.appTarget.appTheme;if(s&&s.availableLocales){if(s.availableLocales.indexOf(t)>-1)return!0;if(i&&s.availableLocales.indexOf(i)>-1)return!0}return!1}let y;function v(e,i,s,r,o){if(o=o||y.Editor,"en-US"===(s=n.normalizeLanguageCode(s)[0])||"en"===s)return Promise.resolve(void 0);let a,l,c=`${s}/${r}/${o}`;if(n.translationsCache()[c])return Promise.resolve(n.translationsCache()[c]);switch(o){case y.Editor:a=[{staticName:"strings.json",path:"strings.json"},{staticName:"target-strings.json",path:e+"/target-strings.json"}];break;case y.Sim:a=[{staticName:"sim-strings.json",path:e+"/sim-strings.json"}];break;case y.Apis:a=[{staticName:"bundled-strings.json",path:e+"/bundled-strings.json"}];break;case y.SkillMap:a=[{staticName:"skillmap-strings.json",path:"/skillmap-strings.json"}]}function u(e){e&&(l||(l={}),Object.keys(e).filter((t=>!!e[t])).forEach((t=>l[t]=e[t])))}if(r){let r=0;return t.U.promiseMapAllSeries(a,(e=>g(s,e.path).then(u,(e=>{console.log(e.message),++r})))).then((()=>(r&&(n.translationsCache()[c]=l),r!==a.length&&l?Promise.resolve(l):(pxt.tickEvent("translations.livetranslationsfailed"),v(e,i,s,!1,o)))))}return Promise.all(a.map((e=>n.httpGetJsonAsync(`${i}locales/${s}/${e.staticName}`).catch((e=>{}))))).then((e=>{let t={};e.forEach((e=>pxt.Util.jsonMergeFrom(t,e))),Object.keys(t).length&&(l=t,n.translationsCache()[c]=l)}),(e=>{console.error("failed to load localizations")})).then((()=>l))}function w(e){const t={};for(const n of Object.keys(e))t[n]=k(e[n]);return t}function k(e){var t;return{attributes:Object.assign({},e.attributes),parameters:null===(t=e.parameters)||void 0===t?void 0:t.map(x),extendsTypes:e.extendsTypes?[...e.extendsTypes]:void 0,pkgs:e.pkgs?[...e.pkgs]:void 0,combinedProperties:e.combinedProperties?[...e.combinedProperties]:void 0,name:e.name,namespace:e.namespace,fileName:e.fileName,kind:e.kind,retType:e.retType,isInstance:e.isInstance,isContextual:e.isContextual,qName:e.qName,pkg:e.pkg,snippet:e.snippet,snippetName:e.snippetName,snippetWithMarkers:e.snippetWithMarkers,pySnippet:e.pySnippet,pySnippetName:e.pySnippetName,pySnippetWithMarkers:e.pySnippetWithMarkers,blockFields:e.blockFields,isReadOnly:e.isReadOnly,pyName:e.pyName,pyQName:e.pyQName,snippetAddsDefinitions:e.snippetAddsDefinitions}}function x(e){var n,i;return{name:e.name,description:e.description,type:e.type,pyTypeString:e.pyTypeString,initializer:e.initializer,default:e.default,properties:null===(n=e.properties)||void 0===n?void 0:n.map(A),handlerParameters:null===(i=e.handlerParameters)||void 0===i?void 0:i.map(A),options:e.options?t.U.clone(e.options):void 0,isEnum:e.isEnum}}function A(e){return{name:e.name,type:e.type}}n.PromiseBuffer=class{constructor(){this.waiting=[],this.available=[]}drain(){for(let e of this.waiting)e(new Error("Promise Buffer Reset"));this.waiting=[],this.available=[]}pushError(e){this.push(e)}push(e){let t=this.waiting.shift();t?t(e):this.available.push(e)}shiftAsync(e=0){if(this.available.length>0){let e=this.available.shift();return e instanceof Error?Promise.reject(e):Promise.resolve(e)}return new Promise(((n,i)=>{let s=e=>{e instanceof Error?i(e):n(e)};this.waiting.push(s),e>0&&t.U.delay(e).then((()=>{let e=this.waiting.indexOf(s);e>=0&&(this.waiting.splice(e,1),i(new Error("Timeout")))}))}))}},n.now=f,n.nowSeconds=function(){return Math.round(f()/1e3)},n.timeout=function(e){return new Promise((t=>setTimeout((()=>t()),e)))},n.cpuUs=()=>{const e="undefined"!=typeof performance?performance.now.bind(performance)||performance.moznow.bind(performance)||performance.msNow.bind(performance)||performance.webkitNow.bind(performance)||performance.oNow.bind(performance):Date.now;return n.cpuUs=()=>1e3*e(),n.cpuUs()},n.getMime=function(e){let t=/\.([a-zA-Z0-9]+)$/.exec(e);if(!t)return"application/octet-stream";switch(t[1].toLowerCase()){case"txt":return"text/plain";case"html":case"htm":return"text/html";case"css":return"text/css";case"js":return"application/javascript";case"jpg":case"jpeg":return"image/jpeg";case"png":return"image/png";case"ico":return"image/x-icon";case"manifest":return"text/cache-manifest";case"webmanifest":return"application/manifest+json";case"json":return"application/json";case"svg":return"image/svg+xml";case"eot":return"application/vnd.ms-fontobject";case"ttf":return"font/ttf";case"woff":return"application/font-woff";case"woff2":return"application/font-woff2";case"md":return"text/markdown";case"xml":return"application/xml";case"m4a":return"audio/m4a";case"mp3":return"audio/mp3";default:return"application/octet-stream"}},n.randomUint32=m,n.guidGen=function(){function e(){return(65536|m()).toString(16).slice(-4)}return e()+e()+"-"+e()+"-4"+e().slice(-3)+"-"+e()+"-"+e()+e()+e()},n.downloadLiveTranslationsAsync=g,n.pxtLangCookieId="PXT_LANG",n.langCookieExpirationDays=30,n.allLanguages={af:{englishName:"Afrikaans",localizedName:"Afrikaans"},ar:{englishName:"Arabic",localizedName:"العربية"},az:{englishName:"Azerbaijani",localizedName:"آذربایجان دیلی"},bg:{englishName:"Bulgarian",localizedName:"български"},bi:{englishName:"Bislama",localizedName:"Bislama"},bn:{englishName:"Bengali",localizedName:"বাংলা"},ca:{englishName:"Catalan",localizedName:"Català"},cs:{englishName:"Czech",localizedName:"Čeština"},cy:{englishName:"Welsh",localizedName:"Cymraeg"},da:{englishName:"Danish",localizedName:"Dansk"},de:{englishName:"German",localizedName:"Deutsch"},el:{englishName:"Greek",localizedName:"Ελληνικά"},en:{englishName:"English",localizedName:"English"},"es-ES":{englishName:"Spanish (Spain)",localizedName:"Español (España)"},"es-MX":{englishName:"Spanish (Mexico)",localizedName:"Español (México)"},et:{englishName:"Estonian",localizedName:"Eesti"},eu:{englishName:"Basque",localizedName:"Euskara"},fa:{englishName:"Persian",localizedName:"فارسی"},fi:{englishName:"Finnish",localizedName:"Suomi"},fil:{englishName:"Filipino",localizedName:"Filipino"},fo:{englishName:"Faroese",localizedName:"føroyskt"},fr:{englishName:"French",localizedName:"Français"},"fr-CA":{englishName:"French (Canada)",localizedName:"Français (Canada)"},"ga-IE":{englishName:"Irish",localizedName:"Gaeilge"},gl:{englishName:"Galician",localizedName:"galego"},"gu-IN":{englishName:"Gujarati",localizedName:"ગુજરાતી"},haw:{englishName:"Hawaiian",localizedName:"ʻŌlelo Hawaiʻi"},hi:{englishName:"Hindi",localizedName:"हिन्दी"},he:{englishName:"Hebrew",localizedName:"עברית"},hr:{englishName:"Croatian",localizedName:"Hrvatski"},hu:{englishName:"Hungarian",localizedName:"Magyar"},"hy-AM":{englishName:"Armenian (Armenia)",localizedName:"Հայերէն (Հայաստան)"},id:{englishName:"Indonesian",localizedName:"Bahasa Indonesia"},is:{englishName:"Icelandic",localizedName:"Íslenska"},it:{englishName:"Italian",localizedName:"Italiano"},ja:{englishName:"Japanese",localizedName:"日本語"},"ja-HIRA":{englishName:"Hiragana",localizedName:"にほんご"},ka:{englishName:"Georgian",localizedName:"ქართული"},kab:{englishName:"Kabyle",localizedName:"شئعم"},kk:{englishName:"Kazakh",localizedName:"қазақ тілі"},km:{englishName:"Khmer",localizedName:"ខ្មែរ"},kmr:{englishName:"Kurmanji (Kurdish)",localizedName:"کورمانجی‎"},kn:{englishName:"Kannada",localizedName:"ಕನ್ನಡ"},ko:{englishName:"Korean",localizedName:"한국어"},lt:{englishName:"Lithuanian",localizedName:"Lietuvių"},lv:{englishName:"Latvian",localizedName:"Latviešu"},"ml-IN":{englishName:"Malayalam",localizedName:"മലയാളം"},mr:{englishName:"Marathi",localizedName:"मराठी"},ms:{englishName:"Malay",localizedName:"Melayu"},nl:{englishName:"Dutch",localizedName:"Nederlands"},no:{englishName:"Norwegian",localizedName:"Norsk"},nb:{englishName:"Norwegian Bokmal",localizedName:"Norsk bokmål"},"nn-NO":{englishName:"Norwegian Nynorsk",localizedName:"Norsk nynorsk"},"pa-IN":{englishName:"Punjabi",localizedName:"ਪੰਜਾਬੀ"},pl:{englishName:"Polish",localizedName:"Polski"},ps:{englishName:"Pashto",localizedName:"پښتو"},"pt-BR":{englishName:"Portuguese (Brazil)",localizedName:"Português (Brasil)"},"pt-PT":{englishName:"Portuguese (Portugal)",localizedName:"Português (Portugal)"},ro:{englishName:"Romanian",localizedName:"Română"},ru:{englishName:"Russian",localizedName:"Русский"},sat:{englishName:"Santali",localizedName:"ᱥᱚᱸᱴᱚᱞᱤ"},"si-LK":{englishName:"Sinhala",localizedName:"සිංහල"},sk:{englishName:"Slovak",localizedName:"Slovenčina"},sl:{englishName:"Slovenian",localizedName:"Slovenski"},sq:{englishName:"Albanian",localizedName:"shqip"},sr:{englishName:"Serbian (Cyrillic)",localizedName:"Srpski"},su:{englishName:"Sundanese",localizedName:"ᮘᮞ ᮞᮥᮔ᮪ᮓ"},"sv-SE":{englishName:"Swedish",localizedName:"Svenska"},sw:{englishName:"Swahili",localizedName:"Kiswahili"},"sw-TZ":{englishName:"Swahili (Tanzania)",localizedName:"Kiswahili (Tanzania)"},ta:{englishName:"Tamil",localizedName:"தமிழ்"},te:{englishName:"Telugu",localizedName:"తెలుగు"},th:{englishName:"Thai",localizedName:"ภาษาไทย"},tl:{englishName:"Tagalog",localizedName:"ᜏᜒᜃᜅ᜔ ᜆᜄᜎᜓᜄ᜔"},tr:{englishName:"Turkish",localizedName:"Türkçe"},uk:{englishName:"Ukrainian",localizedName:"Українська"},"ur-IN":{englishName:"Urdu (India)",localizedName:"اردو (ہندوستان)"},"ur-PK":{englishName:"Urdu (Pakistan)",localizedName:"اردو (پاکستان)"},vi:{englishName:"Vietnamese",localizedName:"Tiếng việt"},"zh-CN":{englishName:"Chinese (Simplified)",localizedName:"中文(简体)"},"zh-TW":{englishName:"Chinese (Traditional)",localizedName:"中文(繁體)"}},n.isLocaleEnabled=b,n.updateLocalizationAsync=function(t){const{targetId:i,baseUrl:s,force:r}=t;let{code:o}=t;if(o=n.normalizeLanguageCode(o)[0],"en-US"===o&&(o="en"),o===n.userLanguage()||!b(o)&&!r)return pxt.debug(`loc: ${o} (using built-in)`),Promise.resolve();pxt.debug(`loc: ${o}`);const a=pxt.Util.liveLocalizationEnabled();return v(i,s,o,a,e.pxtc.Util.TranslationsKind.Editor).then((t=>{var r;return t&&(n.setUserLanguage(o),null===(r=pxt.analytics)||void 0===r||r.addDefaultProperties({lang:o}),n.setLocalizedStrings(t)),e.pxtc.Util.downloadTranslationsAsync(i,s,o,a,e.pxtc.Util.TranslationsKind.Apis).then((t=>{t&&(e.pxtc.apiLocalizationStrings=t)}))}))},function(e){e[e.Editor=0]="Editor",e[e.Sim=1]="Sim",e[e.Apis=2]="Apis",e[e.SkillMap=3]="SkillMap"}(y=n.TranslationsKind||(n.TranslationsKind={})),n.downloadTranslationsAsync=v,n.capitalize=function(e){return e?e[0].toLocaleUpperCase()+e.slice(1):e},n.uncapitalize=function(e){return(e||"").split(/(?=[A-Z])/g).join(" ").toLowerCase()},n.camelCaseToLowercaseWithSpaces=function(e){return e.replace(/([A-Z])/gm," $1").toLocaleLowerCase().trim()},n.snakeCaseToLowercaseWithSpaces=function(e){return e.replace(/_/g," ").toLocaleLowerCase().trim()},n.range=function(e){let t=[];for(let n=0;n<e;++n)t.push(n);return t},n.multipartPostAsync=function(e,t={},i=null,s=null){const r="--------------------------0461489f461126c5";let o="";Object.keys(t).forEach((e=>function(e,t){o+=r+"\r\n",o+='Content-Disposition: form-data; name="'+e+'"\r\n\r\n',o+=t+"\r\n"}(e,t[e]))),i&&function(e,t){const n=e.split("/").reverse()[0];o+=r+"\r\n",o+='Content-Disposition: form-data; name="files['+e+']"; filename="'+n+'"\r\n',o+="\r\n",o+=t+"\r\n"}(i,s),o+=r+"--\r\n";const a={url:e,method:"POST",headers:{"Content-Type":"multipart/form-data; boundary="+r.slice(2)},data:o};return n.httpRequestCoreAsync(a)},n.toDataUri=function(e,n){return/^https?:/i.test(e)||/^data:/i.test(e)?e:(n||/^<svg/i.test(e)&&(n="image/svg+xml"),/xml|svg/.test(n)?`data:${n},${encodeURIComponent(e)}`:`data:${n||"image/png"};base64,${t.encodeBase64(p(e))}`)},n.imageMagic=1496611453,n.imageHeaderSize=36,n.encodeBlobAsync=function(e,t){const i=n.imageHeaderSize+t.length,s=3*(e.width*e.height-1);let r=1;for(;r<4&&!(s*r>=8*i);)r++;let o=s*r>>3,a=i-o,l=0,c=e.width*e.height*4;if(a>0){const t=3*e.width;l=Math.ceil(a/t);const n=document.createElement("canvas");n.width=e.width,n.height=e.height+l;n.getContext("2d").drawImage(e,0,0),e=n}let u=pxt.HF2.encodeU32LE([n.imageMagic,t.length,l,0,0,0,0,0,0]);function d(e,t,n,i){let s=0,r=0,o=i[r++];const a=(1<<n)-1;let l=!0;for(;l;){let c=o>>s&a,u=8-s;if(u<=n){if(r>=i.length){if(0==u)break;l=!1}o=i[r++],c|=o<<u&a,s=n-u}else s+=n;e[t]=255&(e[t]&~a|c),3==(3&++t)&&(e[t++]=255)}return t}pxt.Util.assert(u.length==n.imageHeaderSize);const h=e.getContext("2d"),p=h.getImageData(0,0,e.width,e.height);d(p.data,0,1,[r]);let f=4;if(f=d(p.data,f,r,u),pxt.Util.assert(0==(3&f)),0==l)f=d(p.data,f,r,t);else{let e=o-u.length;f=d(p.data,f,r,t.slice(0,e)),f=d(p.data,c,8,t.slice(e))}for(f|=3;f<p.data.length;)p.data[f]=255,f+=4;return h.putImageData(p,0,0),e},n.decodeBlobAsync=function(e){return pxt.BrowserUtils.loadCanvasAsync(e).then((e=>{const t=e.getContext("2d").getImageData(0,0,e.width,e.height).data,i=1&t[0]|(1&t[1])<<1|(1&t[2])<<2;if(i>5||0==i)return Promise.reject(new Error(n.lf("Invalid encoded PNG format")));function s(e,n,i){let s=0,r=0,o=0;const a=(1<<n)-1;for(;r<i.length;)o|=(t[e++]&a)<<s,3==(3&e)&&e++,s+=n,s>=8&&(i[r++]=255&o,o>>=8,s-=8);return e}const r=new Uint8Array(pxt.Util.imageHeaderSize);let o=s(4,i,r);const a=pxt.HF2.decodeU32LE(r);if(a[0]!=pxt.Util.imageMagic)return Promise.reject(new Error(n.lf("Invalid magic in encoded PNG")));const l=new Uint8Array(a[1]),c=a[2];if(c>0){const t=(e.height-c)*e.width,n=new Uint8Array((3*(t-1)*i>>3)-pxt.Util.imageHeaderSize);s(o,i,n),l.set(n);const r=new Uint8Array(l.length-n.length);s(4*t,8,r),l.set(r,n.length)}else s(o,i,l);return l}))},n.parseQueryString=function(e){let t={};return e.replace(/\+/g," ").replace(/([^#?&=]+)=([^#?&=]*)/g,((e,n,i)=>(t[decodeURIComponent(n)]=decodeURIComponent(i),""))),t},n.stringifyQueryString=function(e,t){for(let n of Object.keys(t))e.indexOf("?")>=0?e+="&":e+="?",e+=encodeURIComponent(n)+"="+encodeURIComponent(t[n]);return e},n.cloneTargetBundle=function(e){const t=(e=Object.assign({},e)).apiInfo;delete e.apiInfo;const i=e.bundleddirs;delete e.bundleddirs;const s=e.bundledpkgs;delete e.bundledpkgs;const r=e.tutorialInfo;delete e.tutorialInfo;const o=n.clone(e);if(t){o.apiInfo={};for(const e of Object.keys(t)){const n=t[e].apis;o.apiInfo[e]={sha:t[e].sha,apis:{jres:Object.assign({},n.jres),byQName:w(n.byQName)}}}}if(i&&(o.bundleddirs=[...i]),s){o.bundledpkgs={};for(const e of Object.keys(s))o.bundledpkgs[e]=Object.assign({},s[e])}if(r){o.tutorialInfo={};for(const e of Object.keys(r)){const t=r[e];o.tutorialInfo[e]={hash:t.hash,usedBlocks:Object.assign({},t.usedBlocks),snippetBlocks:Object.assign({},t.snippetBlocks),highlightBlocks:Object.assign({},t.highlightBlocks),validateBlocks:Object.assign({},t.validateBlocks)}}}return o},n.cloneApis=w,n.cloneSymbolInfo=k,n.toUTF8Array=function(e){return(new TextEncoder).encode(e)},n.fromUTF8Array=function(e){return(new TextDecoder).decode(e)}}(t.Util||(t.Util={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){!function(t){e.Util.httpRequestCoreAsync=function(t){return new Promise(((n,i)=>{let s,r=!1,o=e.Util.clone(t.headers)||{};s=new XMLHttpRequest,t.responseArrayBuffer&&(s.responseType="arraybuffer"),t.withCredentials&&(s.withCredentials=!0),s.onreadystatechange=()=>{if(!r&&4==s.readyState){r=!0;let e={statusCode:s.status,headers:{},buffer:s.responseBody||s.response,text:t.responseArrayBuffer?void 0:s.responseText};s.getAllResponseHeaders().split(/\r?\n/).forEach((t=>{let n=/^\s*([^:]+): (.*)/.exec(t);n&&(e.headers[n[1].toLowerCase()]=n[2])})),n(e)}};let a,l=t.data,c=t.method||(null==l?"GET":"POST");null==l?a=null:l instanceof Uint8Array?a=l:"object"==typeof l?(a=JSON.stringify(l),o["content-type"]="application/json; charset=utf8"):"string"==typeof l?a=l:e.Util.oops("bad data"),s.open(c,t.url),Object.keys(o).forEach((e=>{s.setRequestHeader(e,o[e])})),null==a?s.send():s.send(a)}))},e.Util.sha256=o,e.Util.getRandomBuf=e=>{if(window.crypto)window.crypto.getRandomValues(e);else for(let t=0;t<e.length;++t)e[t]=Math.floor(255*Math.random())};const n=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function i(e,t){return e>>>t|e<<32-t}function s(t,s){e.Util.assert(8==t.length),e.Util.assert(64==s.length);for(let e=16;e<64;++e){let t=i(s[e-15],7)^i(s[e-15],18)^s[e-15]>>>3,n=i(s[e-2],17)^i(s[e-2],19)^s[e-2]>>>10;s[e]=s[e-16]+t+s[e-7]+n|0}let r=t[0],o=t[1],a=t[2],l=t[3],c=t[4],u=t[5],d=t[6],h=t[7];for(let e=0;e<64;++e){let t=h+(i(c,6)^i(c,11)^i(c,25))+(c&u^~c&d)+n[e]+s[e]|0,p=r&o^r&a^o&a;h=d,d=u,u=c,c=l+t|0,l=a,a=o,o=r,r=t+((i(r,2)^i(r,13)^i(r,22))+p|0)|0}t[0]+=r,t[1]+=o,t[2]+=a,t[3]+=l,t[4]+=c,t[5]+=u,t[6]+=d,t[7]+=h}function r(e){let t=new Uint32Array(8);t[0]=1779033703,t[1]=3144134277,t[2]=1013904242,t[3]=2773480762,t[4]=1359893119,t[5]=2600822924,t[6]=528734635,t[7]=1541459225;let n=new Uint32Array(64);function i(e){let i=e.length-63;for(let r=0;r<i;r+=64){for(let t=0;t<16;t++){let i=(t<<2)+r;n[t]=e[i]<<24|e[i+1]<<16|e[i+2]<<8|e[i+3]}s(t,n)}}i(e);let r=64-(e.length+9)%64;64==r&&(r=0);let o=e.length-e.length%64,a=new Uint8Array(e.length-o+1+r+8),l=0;for(;o<e.length;)a[l++]=e[o++];for(a[l++]=128;r-- >0;)a[l++]=0;let c=8*e.length;for(l=a.length;c>0;)a[--l]=255&c,c>>=8;i(a);let u="";for(let e=0;e<t.length;++e)u+=("000000000"+t[e].toString(16)).slice(-8);return u.toLowerCase()}function o(t){pxt.perf.measureStart("sha256buffer");const n=r(e.Util.toUTF8Array(t));return pxt.perf.measureEnd("sha256buffer"),n}t.sha256buffer=r,t.sha256string=o}(e.BrowserImpl||(e.BrowserImpl={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){!function(t){const n={add:(e,t,n)=>{if("object"!=typeof e)throw new Error("jsonPatch: expected object type");if(t in e)throw new Error(`jsonPatch: object already contains key ${t}`);e[t]=n},replace:(e,t,n)=>{if("object"!=typeof e)throw new Error("jsonPatch: expected object type");e[t]=n},remove:(e,t)=>{if("object"!=typeof e)throw new Error("jsonPatch: expected object type");delete e[t]}},i={add:(e,t,n)=>{if(!Array.isArray(e))throw new Error("jsonPatch: expected array type");if(t in e)throw new Error(`jsonPatch: key ${t} already exists in array`);"number"!=typeof t||t!==Math.floor(t)?e[t]=n:e.splice(t,0,n)},replace:(e,t,n)=>{if(!Array.isArray(e))throw new Error("jsonPatch: expected array type");"number"!=typeof t||t!==Math.floor(t)?e[t]=n:e.splice(t,1,n)},remove:(e,t)=>{if(!Array.isArray(e))throw new Error("jsonPatch: expected array type");"number"!=typeof t||t!==Math.floor(t)?delete e[t]:e.splice(t,1)}};t.diff=function(e,t){const n={add:[],remove:[],replace:[]};function i(e,t){if(!Array.isArray(e))return t;const n=Number.parseFloat(t);return Number.isNaN(n)?t:n}return function e(t,s,r){if(!Object.is(t,s)){s=s||{},t=t||{};for(let e of Object.keys(t))if(!(e in s)){const s=i(t,e);n.remove.push({op:"remove",path:r.concat(s)})}for(const o of Object.keys(s)){const a=t[o],l=s[o],c=i(s,o);c in t?"object"!=typeof a&&"object"!=typeof l&&a!==l||typeof a!=typeof l||Array.isArray(a)!==Array.isArray(l)?n.replace.push({op:"replace",path:r.concat(c),value:l}):e(a,l,r.concat(c)):void 0!==s[c]&&(r.length&&n.add.push({op:"add",path:r,value:Array.isArray(s)?[]:{}}),n.add.push({op:"add",path:r.concat(c),value:l}))}}}(e,t,[]),[...n.remove.reverse(),...n.replace,...n.add.sort(((e,t)=>e.path.length-t.path.length))]},t.patchInPlace=function(e,t){if(!e||"object"!=typeof e)throw new Error("jsonPatch: Must be an object or an array.");for(const s of t){const t=s.path.slice(),r=t.pop();if(null==r)throw new Error("jsonPatch: missing last key");let o=e,a=t.shift();for(;null!=a;){if(!(a in o))throw new Error(`jsonPatch: missing parent element ${a}`);o=o[a],a=t.shift()}if(Array.isArray(o)&&"number"!=typeof r)throw new Error("jsonPatch: expected numeric index for array object");const l=Array.isArray(o)?i:n;"remove"===s.op?l.remove(o,r):"add"!==s.op||r in o?"replace"===s.op&&l.replace(o,r,s.value):l.add(o,r,s.value)}},t.opsAreEqual=function(t,n){return t.op===n.op&&e.U.arrayEquals(t.path,n.path)}}(e.jsonPatch||(e.jsonPatch={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){!function(t){!function(t){function n(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){const i=Array.isArray(e),s=Array.isArray(t);if(i&&s){if(e.length!==t.length)return!1;for(let i=0;i<e.length;++i)if(!n(e[i],t[i]))return!1;return!0}if(i!==s)return!1;const r=Object.keys(e);if(r.length!==Object.keys(t).length)return!1;for(const i of r){if(!t.hasOwnProperty(i))return!1;if(!n(e[i],t[i]))return!1}return!0}return e!=e&&t!=t}t.diffTests=function(){const t=[{comment:"test 1",obja:{a:4,b:5},objb:{a:3,b:5},expected:[{op:"replace",path:["a"],value:3}]},{comment:"test 2",obja:{a:3,b:5},objb:{a:4,c:5},expected:[{op:"remove",path:["b"]},{op:"replace",path:["a"],value:4},{op:"add",path:["c"],value:5}]},{comment:"test 3",obja:{a:4,b:[1,2,3]},objb:{a:3,b:[1,2,4]},expected:[{op:"replace",path:["a"],value:3},{op:"replace",path:["b",2],value:4}]},{comment:"test 4",obja:{a:3,b:[1,2,4]},objb:{a:3,b:[1,2,4,5]},expected:[{op:"add",path:["b"],value:[]},{op:"add",path:["b",3],value:5}]},{comment:"test 5",obja:{a:4,b:{c:3}},objb:{a:4,b:{c:4}},expected:[{op:"replace",path:["b","c"],value:4}]},{comment:"test 6",obja:{a:4,b:{c:4}},objb:{a:5,b:{d:4}},expected:[{op:"remove",path:["b","c"]},{op:"replace",path:["a"],value:5},{op:"add",path:["b"],value:{}},{op:"add",path:["b","d"],value:4}]},{comment:"test 7",obja:{a:4,b:[2,"foo"]},objb:{a:4,b:[2,"foo",["this","that"]]},expected:[{op:"add",path:["b"],value:[]},{op:"add",path:["b",2],value:["this","that"]}]}];for(const i of t){console.log(i.comment);const t=e.pxtc.jsonPatch.diff(i.obja,i.objb);n(t,i.expected)?console.log("succeeded"):(console.error("FAILED"),console.log("got",t),console.log("exp",i.expected))}},t.patchTests=function(){const t=[{comment:"test 1",obj:{a:"foo",b:[4,11]},patches:[{op:"remove",path:["b"]},{op:"replace",path:["a"],value:4},{op:"add",path:["c"],value:5}],expected:{a:4,c:5}},{comment:"test 2",obj:{a:4,b:[1,2,3]},patches:[{op:"replace",path:["a"],value:3},{op:"replace",path:["b",2],value:4},{op:"add",path:["b",3],value:9}],expected:{a:3,b:[1,2,4,9]}},{comment:"test 3",obj:{a:4,b:{c:3}},patches:[{op:"replace",path:["a"],value:5},{op:"remove",path:["b","c"]},{op:"add",path:["b","d"],value:4}],expected:{a:5,b:{d:4}}},{comment:"test 4",obj:{a:4},patches:[{op:"add",path:["b"],value:[]},{op:"add",path:["b",0],value:"foo"},{op:"add",path:["b",1],value:"bar"}],expected:{a:4,b:["foo","bar"]},validate:e=>e.b&&e.b.forEach}];for(const i of t){console.log(i.comment),e.pxtc.jsonPatch.patchInPlace(i.obj,i.patches);!n(i.obj,i.expected)||!i.validate||i.validate(i.obj)?console.log("succeeded"):i.expected&&(console.error("FAILED"),console.log("got",i.obj),console.log("exp",i.expected))}}}(t.tests||(t.tests={}))}(t.jsonPatch||(t.jsonPatch={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){e.perf||(e.perf={})}(pxt||(pxt={})),pxt.perf.report||(pxt.perf.report=()=>{}),pxt.perf.recordMilestone||(pxt.perf.recordMilestone=()=>{}),pxt.perf.measureStart||(pxt.perf.measureStart=()=>{}),pxt.perf.measureEnd||(pxt.perf.measureEnd=()=>{}),function(e){let t;e.U=pxtc.Util,e.Util=pxtc.Util;let n,i,s,r={};function o(n,i){/^csv-/.test(n)?e.setAppTargetVariant(n.replace(/^csv-*/,"")):e.appTarget&&(r[n]=i,e.U.jsonCopyFrom(e.appTarget.compile.switches,r),e.U.jsonCopyFrom(t.compile.switches,r))}function a(e,t,n){if(Array.isArray(e))return e.map((e=>a(e,t,n)));if("object"==typeof e){for(const i of Object.keys(e))e[i]=a(e[i],t,n);return e}return"string"==typeof e&&t.test(e)?n(e):e}function l(){let t=e.appTarget.compile;t||(t=e.appTarget.compile={isNative:!1,hasHex:!1,switches:{}}),t.hasHex&&(t.nativeType||(t.nativeType=pxtc.NATIVE_TYPE_THUMB)),t.switches||(t.switches={}),t.nativeType==pxtc.NATIVE_TYPE_VM&&(t.sourceMap=!0),e.U.jsonCopyFrom(t.switches,r),t.jsRefCounting=!1,t.useUF2||t.useELF||null!=t.noSourceInFlash||(t.noSourceInFlash=!0),void 0===t.utf8&&(t.utf8=!0),e.appTarget.appTheme||(e.appTarget.appTheme={}),e.appTarget.appTheme.embedUrl||(e.appTarget.appTheme.embedUrl=e.appTarget.appTheme.homeUrl);let n=e.appTarget.compileService;if(n&&n.yottaTarget&&!n.yottaBinary&&(n.yottaBinary="pxt-microbit-app-combined.hex"),e.appTarget=a(e.appTarget,/^@cdnUrl@/i,(t=>e.BrowserUtils.patchCdn(t))),Object.keys(e.appTarget.bundledpkgs).forEach((t=>{const n=e.appTarget.bundledpkgs[t],i=JSON.parse(n[e.CONFIG_NAME]);i.icon&&(i.icon=e.BrowserUtils.patchCdn(i.icon)),n[e.CONFIG_NAME]=e.Package.stringifyConfig(i)})),"undefined"!=typeof window){const t={"lockededitor=1":{appTheme:{lockedEditor:!0}},"hidemenu=1":{appTheme:{hideMenuBar:!0}}};e.appTarget.queryVariants&&e.Util.jsonCopyFrom(t,e.appTarget.queryVariants);const n=window.location.href;Object.keys(t).forEach((i=>{if(new RegExp(i,"i").exec(n)){let n=t[i];n&&e.U.jsonMergeFrom(e.appTarget,n)}}))}}function c(n=!1){e.perf.measureStart("reloadAppTargetVariant");const i=n?"":JSON.stringify(e.appTarget);if(e.appTarget=e.U.cloneTargetBundle(t),e.appTargetVariant){const t=e.appTarget.variants&&e.appTarget.variants[e.appTargetVariant];t?e.U.jsonMergeFrom(e.appTarget,t):e.U.userError(lf("Variant '{0}' not defined in pxtarget.json",e.appTargetVariant))}l(),!n&&e.onAppTargetChanged&&i!=JSON.stringify(e.appTarget)&&e.onAppTargetChanged(),e.perf.measureEnd("reloadAppTargetVariant")}function u(){return{relprefix:"/--",workerjs:"/worker.js",monacoworkerjs:"/monacoworker.js",gifworkerjs:"/gifjs/gif.worker.js",serviceworkerjs:"/serviceworker.js",typeScriptWorkerJs:"/tsworker.js",pxtVersion:"local",pxtRelId:"localRelId",pxtCdnUrl:"/cdn/",commitCdnUrl:"/cdn/",blobCdnUrl:"/blb/",cdnUrl:"/cdn/",targetUrl:"",targetVersion:"local",targetRelId:"",targetId:e.appTarget?e.appTarget.id:"",simUrl:"/sim/simulator.html",simserviceworkerUrl:"/simulatorserviceworker.js",simworkerconfigUrl:"/sim/workerConfig.js",partsUrl:"/sim/siminstructions.html"}}function d(){return s||(s=e.Cloud.downloadTargetConfigAsync().then((e=>e||{}),(e=>({})))),s}function h(t=null){return t||(t=e.appTarget.compile),t.nativeType==ts.pxtc.NATIVE_TYPE_VM?t.useESP?t.useUF2?ts.pxtc.BINARY_UF2:ts.pxtc.BINARY_ESP:ts.pxtc.BINARY_PXT64:t.useUF2&&!t.switches.rawELF?ts.pxtc.BINARY_UF2:t.useELF?ts.pxtc.BINARY_ELF:ts.pxtc.BINARY_HEX}e.setAppTarget=function(n){e.appTarget=n||{},l(),t=e.U.cloneTargetBundle(e.appTarget)},e.setBundledApiInfo=function(e){for(const t of Object.keys(e)){const n=e[t].apis.byQName;for(const e of Object.keys(n)){const t=n[e],i=e.lastIndexOf("."),s=t.pyQName,r=n[e]={kind:Math.abs(t.kind||7),qName:e,namespace:e.slice(0,i<0?0:i),name:e.slice(i+1),pyQName:s,pyName:s?s.slice(s.lastIndexOf(".")+1):void 0,fileName:"",attributes:t.attributes||{},retType:t.retType||"void",parameters:t.parameters?t.parameters.map((e=>({name:e.name,description:e.description||"",type:e.type||"number",initializer:e.initializer,default:e.default,options:e.options||{},isEnum:!!e.isEnum,handlerParameters:e.handlerParameters}))):null,extendsTypes:t.extendsTypes,snippet:t.kind&&t.kind<0?null:void 0,isInstance:!!t.isInstance,isReadOnly:!!t.isReadOnly},o=r.attributes;o.paramDefl||(o.paramDefl={}),o.callingConvention||(o.callingConvention=0),o.paramHelp||(o.paramHelp={}),o.jsDoc||(o.jsDoc=""),o._name=r.name.replace(/@.*/,"")}}n=e},e.getBundledApiInfo=function(){return n},e.savedAppTheme=function(){return t?t.appTheme:void 0},e.setCompileSwitch=o,e.setCompileSwitches=function(e){if(e)for(let t of e.split(/[\s,;:]+/))t&&("-"==t[0]?o(t.slice(1),!1):o(t,!0))},e.bundledSvg=function(t){if(!t)return;let n=i&&i[t];if(n)return n;if(!e.appTarget.simulator||!e.appTarget.simulator.dynamicBoardDefinition)return;i||(i={});const s=e.appTarget.bundledpkgs[t];if(!s)return;if(JSON.parse(s["pxt.json"]).core&&s["board.json"]){const n=JSON.parse(s["board.json"]);if(n&&n.visual&&n.visual.image){let r=n.visual.image;/^pkg:\/\//.test(r)&&(r=s[r.slice(6)]),i[t]=`data:image/svg+xml;base64,${ts.pxtc.encodeBase64(e.Util.toUTF8(r))}`}}return i[t]},e.replaceStringsInJsonBlob=a,e.reloadAppTargetVariant=c,e.setAppTargetVariant=function(t,n={}){e.debug(`app variant: ${t}`),(n.force||e.appTargetVariant!==t&&(e.appTargetVariant||t))&&(e.appTargetVariant=t,c(n.temporary))},e.setHwVariant=function(t,n){t=t.replace(/.*---/,""),/^[\w\-]+$/.test(t)?(e.hwVariant=t,e.hwName=n||t):(e.hwVariant=null,e.hwName=null),e.debug(`hwVariant: ${e.hwVariant} (${e.hwName})`)},e.hasHwVariants=function(){return!!e.appTarget.variants&&Object.keys(e.appTarget.bundledpkgs).some((e=>/^hw---/.test(e)))},e.getHwVariants=function(){return e.appTarget.variants?Object.keys(e.appTarget.bundledpkgs).filter((e=>/^hw---/.test(e))).map((t=>JSON.parse(e.appTarget.bundledpkgs[t][e.CONFIG_NAME]))).filter((t=>!!e.appTarget.appTheme.experimentalHw||!t.experimentalHw)):[]},e.options={},e.debug="undefined"!=typeof console&&console.debug?t=>{e.options.debug&&console.debug(t)}:()=>{},e.log="undefined"!=typeof console&&console.log?e=>{console.log(e)}:()=>{},e.reportException=function(e,t){if(console&&(console.error(e),t))try{console.log(t)}catch(e){}},e.reportError=function(t,n,i){if(console&&(console.error(`${t}: ${n}`),i))try{e.log(JSON.stringify(i,null,2))}catch(e){}},e.localWebConfig=u,e.getOnlineCdnUrl=function(){if(!e.webConfig)return null;let t=/^(https:\/\/[^\/]+)/.exec(e.webConfig.commitCdnUrl);return t?t[1]:null},e.setupWebConfig=function(t){t?e.webConfig=t:e.webConfig||(e.webConfig=u())},e.getEmbeddedScript=function(t){return e.U.lookup(e.appTarget.bundledpkgs||{},t)},e.targetConfigAsync=d,e.packagesConfigAsync=function(){return d().then((e=>e?e.packages:void 0))},e.CONFIG_NAME="pxt.json",e.SIMSTATE_JSON=".simstate.json",e.SERIAL_EDITOR_FILE="serial.txt",e.README_FILE="README.md",e.GITIGNORE_FILE=".gitignore",e.ASSETS_FILE="assets.json",e.CLOUD_ID="pxt/",e.BLOCKS_PROJECT_NAME="blocksprj",e.JAVASCRIPT_PROJECT_NAME="tsprj",e.PYTHON_PROJECT_NAME="pyprj",e.MAIN_BLOCKS="main.blocks",e.MAIN_TS="main.ts",e.MAIN_PY="main.py",e.DEFAULT_GROUP_NAME="other",e.TILEMAP_CODE="tilemap.g.ts",e.TILEMAP_JRES="tilemap.g.jres",e.IMAGES_CODE="images.g.ts",e.IMAGES_JRES="images.g.jres",e.TUTORIAL_CODE_START="_onCodeStart.ts",e.TUTORIAL_CODE_STOP="_onCodeStop.ts",e.TUTORIAL_INFO_FILE="tutorial-info-cache.json",e.TUTORIAL_CUSTOM_TS="tutorial.custom.ts",e.BREAKPOINT_TABLET=991,e.PALETTES_FILE="_palettes.json",e.HISTORY_FILE="_history",e.outputName=h,e.isOutputText=function(e=null){return h(e)==ts.pxtc.BINARY_HEX}}(pxt||(pxt={})),function(e){!function(t){const n="this";let i;function s(){if(i={device_while:{name:e.Util.lf("a loop that repeats while the condition is true"),tooltip:e.Util.lf("Run the same sequence of actions while the condition is met."),url:"/blocks/loops/while",category:"loops",block:{message0:e.Util.lf("while %1"),appendField:e.Util.lf("{id:while}do")}},pxt_controls_for:{name:e.Util.lf("a loop that repeats the number of times you say"),tooltip:e.Util.lf("Have the variable '{0}' take on the values from 0 to the end number, counting by 1, and do the specified blocks."),url:"/blocks/loops/for",category:"loops",block:{message0:e.Util.lf("for %1 from 0 to %2"),variable:e.Util.lf("{id:var}index"),appendField:e.Util.lf("{id:for}do")}},controls_simple_for:{name:e.Util.lf("a loop that repeats the number of times you say"),tooltip:e.Util.lf("Have the variable '{0}' take on the values from 0 to the end number, counting by 1, and do the specified blocks."),url:"/blocks/loops/for",category:"loops",block:{message0:e.Util.lf("for %1 from 0 to %2"),variable:e.Util.lf("{id:var}index"),appendField:e.Util.lf("{id:for}do")}},pxt_controls_for_of:{name:e.Util.lf("a loop that repeats for each value in an array"),tooltip:e.Util.lf("Have the variable '{0}' take the value of each item in the array one by one, and do the specified blocks."),url:"/blocks/loops/for-of",category:"loops",block:{message0:e.Util.lf("for element %1 of %2"),variable:e.Util.lf("{id:var}value"),appendField:e.Util.lf("{id:for_of}do")}},controls_for_of:{name:e.Util.lf("a loop that repeats for each value in an array"),tooltip:e.Util.lf("Have the variable '{0}' take the value of each item in the array one by one, and do the specified blocks."),url:"/blocks/loops/for-of",category:"loops",block:{message0:e.Util.lf("for element %1 of %2"),variable:e.Util.lf("{id:var}value"),appendField:e.Util.lf("{id:for_of}do")}},math_op2:{name:e.Util.lf("minimum or maximum of 2 numbers"),tooltip:{min:e.Util.lf("smaller value of 2 numbers"),max:e.Util.lf("larger value of 2 numbers")},url:"/blocks/math",operators:{op:["min","max"]},category:"math"},math_op3:{name:e.Util.lf("absolute number"),tooltip:e.Util.lf("absolute value of a number"),url:"/reference/math",category:"math",block:{message0:e.Util.lf("absolute of %1")}},math_number:{name:e.Util.lf("{id:block}number"),url:"/types/number",category:"math",tooltip:e.appTarget&&e.appTarget.compile?e.Util.lf("a decimal number"):e.Util.lf("an integer number")},math_integer:{name:e.Util.lf("{id:block}number"),url:"/types/number",category:"math",tooltip:e.Util.lf("an integer number")},math_whole_number:{name:e.Util.lf("{id:block}number"),url:"/types/number",category:"math",tooltip:e.Util.lf("a whole number")},math_number_minmax:{name:e.Util.lf("{id:block}number"),url:"/blocks/math",category:"math"},math_arithmetic:{name:e.Util.lf("arithmetic operation"),url:"/blocks/math",tooltip:{ADD:e.Util.lf("Return the sum of the two numbers."),MINUS:e.Util.lf("Return the difference of the two numbers."),MULTIPLY:e.Util.lf("Return the product of the two numbers."),DIVIDE:e.Util.lf("Return the quotient of the two numbers."),POWER:e.Util.lf("Return the first number raised to the power of the second number.")},operators:{OP:["ADD","MINUS","MULTIPLY","DIVIDE","POWER"]},category:"math",block:{MATH_ADDITION_SYMBOL:e.Util.lf("{id:op}+"),MATH_SUBTRACTION_SYMBOL:e.Util.lf("{id:op}-"),MATH_MULTIPLICATION_SYMBOL:e.Util.lf("{id:op}×"),MATH_DIVISION_SYMBOL:e.Util.lf("{id:op}/"),MATH_POWER_SYMBOL:e.Util.lf("{id:op}**")}},math_modulo:{name:e.Util.lf("division remainder"),tooltip:e.Util.lf("Return the remainder from dividing the two numbers."),url:"/blocks/math",category:"math",block:{MATH_MODULO_TITLE:e.Util.lf("remainder of %1 / %2")}},math_js_op:{name:e.Util.lf("math function"),tooltip:{sqrt:e.Util.lf("Returns the square root of the argument"),sin:e.Util.lf("Returns the sine of the argument"),cos:e.Util.lf("Returns the cosine of the argument"),acos:e.Util.lf("Returns the arccosine of the argument"),asine:e.Util.lf("Returns the arcsine of the argument"),tan:e.Util.lf("Returns the tangent of the argument"),atan2:e.Util.lf("Returns the arctangent of the quotient of the two arguments"),idiv:e.Util.lf("Returns the integer portion of the division operation on the two arguments"),imul:e.Util.lf("Returns the integer portion of the multiplication operation on the two arguments")},url:"/blocks/math",operators:{OP:["sqrt","sin","cos","tan","atan2","idiv","imul"]},category:"math",block:{sqrt:e.Util.lf("{id:op}square root"),sin:e.Util.lf("{id:op}sin"),cos:e.Util.lf("{id:op}cos"),asin:e.Util.lf("{id:op}asin"),acos:e.Util.lf("{id:op}acos"),tan:e.Util.lf("{id:op}tan"),atan2:e.Util.lf("{id:op}atan2"),idiv:e.Util.lf("{id:op}integer /"),imul:e.Util.lf("{id:op}integer ×")}},math_js_round:{name:e.Util.lf("rounding functions"),tooltip:{round:e.Util.lf("Increases the argument to the next higher whole number if its fractional part is more than one half"),ceil:e.Util.lf("Increases the argument to the next higher whole number"),floor:e.Util.lf("Decreases the argument to the next lower whole number"),trunc:e.Util.lf("Removes the fractional part of the argument")},url:"/blocks/math",operators:{OP:["round","ceil","floor","trunc"]},category:"math",block:{round:e.Util.lf("{id:op}round"),ceil:e.Util.lf("{id:op}ceiling"),floor:e.Util.lf("{id:op}floor"),trunc:e.Util.lf("{id:op}truncate")}},variables_change:{name:e.Util.lf("update the value of a number variable"),tooltip:e.Util.lf("Changes the value of the variable by this amount"),url:"/blocks/variables/change",category:"variables",block:{message0:e.Util.lf("change %1 by %2")}},controls_repeat_ext:{name:e.Util.lf("a loop that repeats and increments an index"),tooltip:e.Util.lf("Do some statements several times."),url:"/blocks/loops/repeat",category:"loops",block:{CONTROLS_REPEAT_TITLE:e.Util.lf("repeat %1 times"),CONTROLS_REPEAT_INPUT_DO:e.Util.lf("{id:repeat}do")}},variables_get:{name:e.Util.lf("get the value of a variable"),tooltip:e.Util.lf("Returns the value of this variable."),url:"/blocks/variables",category:"variables",block:{VARIABLES_GET_CREATE_SET:e.Util.lf("Create 'set %1'")}},variables_get_reporter:{name:e.Util.lf("get the value of a variable"),tooltip:e.Util.lf("Returns the value of this variable."),url:"/blocks/variables",category:"variables",block:{VARIABLES_GET_CREATE_SET:e.Util.lf("Create 'set %1'")}},variables_set:{name:e.Util.lf("assign the value of a variable"),tooltip:e.Util.lf("Sets this variable to be equal to the input."),url:"/blocks/variables/assign",category:"variables",block:{VARIABLES_SET:e.Util.lf("set %1 to %2")}},controls_if:{name:e.Util.lf("a conditional statement"),tooltip:{CONTROLS_IF_TOOLTIP_1:e.Util.lf("If a value is true, then do some statements."),CONTROLS_IF_TOOLTIP_2:e.Util.lf("If a value is true, then do the first block of statements. Otherwise, do the second block of statements."),CONTROLS_IF_TOOLTIP_3:e.Util.lf("If the first value is true, then do the first block of statements. Otherwise, if the second value is true, do the second block of statements."),CONTROLS_IF_TOOLTIP_4:e.Util.lf("If the first value is true, then do the first block of statements. Otherwise, if the second value is true, do the second block of statements. If none of the values are true, do the last block of statements.")},tooltipSearch:"CONTROLS_IF_TOOLTIP_2",url:"/blocks/logic/if",category:"logic",block:{CONTROLS_IF_MSG_IF:e.Util.lf("{id:logic}if"),CONTROLS_IF_MSG_THEN:e.Util.lf("{id:logic}then"),CONTROLS_IF_MSG_ELSE:e.Util.lf("{id:logic}else"),CONTROLS_IF_MSG_ELSEIF:e.Util.lf("{id:logic}else if")}},lists_create_with:{name:e.Util.lf("create an array"),tooltip:e.Util.lf("Creates a new array."),url:"/reference/arrays/create",category:"arrays",blockTextSearch:"LISTS_CREATE_WITH_INPUT_WITH",block:{LISTS_CREATE_EMPTY_TITLE:e.Util.lf("empty array"),LISTS_CREATE_WITH_INPUT_WITH:e.Util.lf("array of"),LISTS_CREATE_WITH_CONTAINER_TITLE_ADD:e.Util.lf("array"),LISTS_CREATE_WITH_ITEM_TITLE:e.Util.lf("value")}},lists_length:{name:e.Util.lf("array length"),tooltip:e.Util.lf("Returns the number of items in an array."),url:"/reference/arrays/length",category:"arrays",block:{LISTS_LENGTH_TITLE:e.Util.lf("length of array %1")}},lists_index_get:{name:e.Util.lf("get a value in an array"),tooltip:e.Util.lf("Returns the value at the given index in an array."),url:"/reference/arrays/get",category:"arrays",block:{message0:e.Util.lf("%1 get value at %2")}},lists_index_set:{name:e.Util.lf("set a value in an array"),tooltip:e.Util.lf("Sets the value at the given index in an array"),url:"/reference/arrays/set",category:"arrays",block:{message0:e.Util.lf("%1 set value at %2 to %3")}},logic_compare:{name:e.Util.lf("comparing two numbers"),tooltip:{LOGIC_COMPARE_TOOLTIP_EQ:e.Util.lf("Return true if both inputs equal each other."),LOGIC_COMPARE_TOOLTIP_NEQ:e.Util.lf("Return true if both inputs are not equal to each other."),LOGIC_COMPARE_TOOLTIP_LT:e.Util.lf("Return true if the first input is smaller than the second input."),LOGIC_COMPARE_TOOLTIP_LTE:e.Util.lf("Return true if the first input is smaller than or equal to the second input."),LOGIC_COMPARE_TOOLTIP_GT:e.Util.lf("Return true if the first input is greater than the second input."),LOGIC_COMPARE_TOOLTIP_GTE:e.Util.lf("Return true if the first input is greater than or equal to the second input.")},url:"/blocks/logic/boolean",category:"logic",block:{search:"= ≠ < ≤ > ≥"}},logic_operation:{name:e.Util.lf("boolean operation"),tooltip:{LOGIC_OPERATION_TOOLTIP_AND:e.Util.lf("Return true if both inputs are true."),LOGIC_OPERATION_TOOLTIP_OR:e.Util.lf("Return true if at least one of the inputs is true.")},url:"/blocks/logic/boolean",category:"logic",block:{LOGIC_OPERATION_AND:e.Util.lf("{id:op}and"),LOGIC_OPERATION_OR:e.Util.lf("{id:op}or")}},logic_negate:{name:e.Util.lf("logical negation"),tooltip:e.Util.lf("Returns true if the input is false. Returns false if the input is true."),url:"/blocks/logic/boolean",category:"logic",block:{LOGIC_NEGATE_TITLE:e.Util.lf("not %1")}},logic_boolean:{name:e.Util.lf("a `true` or `false` value"),tooltip:e.Util.lf("Returns either true or false."),url:"/blocks/logic/boolean",category:"logic",block:{LOGIC_BOOLEAN_TRUE:e.Util.lf("{id:boolean}true"),LOGIC_BOOLEAN_FALSE:e.Util.lf("{id:boolean}false")}},text:{name:e.Util.lf("a piece of text"),tooltip:e.Util.lf("A letter, word, or line of text."),url:"/types/string",category:"text",block:{search:e.Util.lf("a piece of text")}},text_length:{name:e.Util.lf("number of characters in the string"),tooltip:e.Util.lf("Returns the number of letters (including spaces) in the provided text."),url:"/reference/text/length",category:"text",block:{TEXT_LENGTH_TITLE:e.Util.lf("length of %1")}},text_join:{name:e.Util.lf("join items to create text"),tooltip:e.Util.lf("Create a piece of text by joining together any number of items."),url:"/reference/text/join",category:"text",block:{TEXT_JOIN_TITLE_CREATEWITH:e.Util.lf("join")}},procedures_defnoreturn:{name:e.Util.lf("define the function"),tooltip:e.Util.lf("Create a function."),url:"/types/function/define",category:"functions",block:{PROCEDURES_DEFNORETURN_TITLE:e.Util.lf("function"),PROCEDURE_ALREADY_EXISTS:e.Util.lf("A function named '%1' already exists.")}},procedures_callnoreturn:{name:e.Util.lf("call the function"),tooltip:e.Util.lf("Call the user-defined function."),url:"/types/function/call",category:"functions",block:{PROCEDURES_CALLNORETURN_TITLE:e.Util.lf("call function")}},function_return:{name:e.Util.lf("return a value from within a function"),tooltip:e.Util.lf("Return a value from within a user-defined function."),url:"/types/function/return",category:"functions",block:{message_with_value:e.Util.lf("return %1"),message_no_value:e.Util.lf("return")}},function_definition:{name:e.Util.lf("define the function"),tooltip:e.Util.lf("Create a function."),url:"/types/function/define",category:"functions",block:{FUNCTIONS_EDIT_OPTION:e.Util.lf("Edit Function")}},function_call:{name:e.Util.lf("call the function"),tooltip:e.Util.lf("Call the user-defined function."),url:"/types/function/call",category:"functions",block:{FUNCTIONS_CALL_TITLE:e.Util.lf("call"),FUNCTIONS_GO_TO_DEFINITION_OPTION:e.Util.lf("Go to Definition")}},function_call_output:{name:e.Util.lf("call the function with a return value"),tooltip:e.Util.lf("Call the user-defined function with a return value."),url:"/types/function/call",category:"functions",block:{}}},i[pxtc.ON_START_TYPE]={name:e.Util.lf("on start event"),tooltip:e.Util.lf("Run code when the program starts"),url:"/blocks/on-start",category:"loops",block:{message0:e.Util.lf("on start %1 %2")}},i[pxtc.PAUSE_UNTIL_TYPE]={name:e.Util.lf("pause until"),tooltip:e.Util.lf("Pause execution of code until the given boolean expression is true"),url:"/blocks/pause-until",category:"loops",block:{message0:e.Util.lf("pause until %1")}},i[pxtc.TS_BREAK_TYPE]={name:e.Util.lf("break"),tooltip:e.Util.lf("Break out of the current loop or switch"),url:"/blocks/loops/break",category:"loops",block:{message0:e.Util.lf("break")}},i[pxtc.TS_CONTINUE_TYPE]={name:e.Util.lf("continue"),tooltip:e.Util.lf("Skip current iteration and continues with the next iteration in the loop"),url:"/blocks/loops/continue",category:"loops",block:{message0:e.Util.lf("continue")}},e.blocks.showBlockIdInTooltip)for(const e of Object.keys(i)){const t=i[e].tooltip;if("object"==typeof t&&null!==t)for(const n in t)t.hasOwnProperty(n)&&(i[e].tooltip[n]=`${t[n]} (id: ${e})`);else i[e].tooltip=`${i[e].tooltip} (id: ${e})`}}t.showBlockIdInTooltip=!1,t.requirePxtBlockly=()=>{},t.requireBlockly=()=>{},t.registerFieldEditor=()=>{},t.MATH_FUNCTIONS={unary:["sqrt","sin","cos","tan","asin","acos"],binary:["atan2"],infix:["idiv","imul"]},t.ROUNDING_FUNCTIONS=["round","ceil","floor","trunc"],t.builtinFunctionInfo={"Math.abs":{blockId:"math_op3",params:["x"]},"Math.min":{blockId:"math_op2",params:["x","y"]},"Math.max":{blockId:"math_op2",params:["x","y"]}},t.normalizeBlock=function(t,n=e.log){if(!t)return t;let i=t.replace(/(?:^|[^\\])([%$])\s+/g,"$1");return i!=t&&(n(`block has extra spaces: ${t}`),t=i),i=(t=i).replace(/([%$]\w+)\s*=\s*(\w+)/,"$1=$2"),i!=t&&(n(`block has space between %name and = : ${t}`),t=i),i=i.replace(/\s*\|\s*/g,"|"),i},t.compileInfo=function(e){const i={parameters:[],actualNameToParam:{},definitionNameToParam:{},handlerArgs:[]},s=(1==e.kind||2==e.kind)&&!e.attributes.defaultInstance,r=!!e.attributes._def,o=r?e.attributes._def.parameters.slice(0):void 0,a=r?o.length:e.parameters?e.parameters.length:0,l=t.builtinFunctionInfo[e.qName];r&&e.attributes._expandedDef&&o.push(...e.attributes._expandedDef.parameters);const c={},u=o?o.filter((e=>!e.ref||(c[e.name]=e,!1))):[];if(s&&r&&o.length){const t=c.this||o[0],s=t.name,r=!t.shadowBlockId||"variables_get"===t.shadowBlockId;let a=e.attributes.paramDefl[s]||e.attributes.paramDefl.this;r&&(a=t.varName||a),i.thisParameter={actualName:n,definitionName:s,shadowBlockId:t.shadowBlockId,type:e.namespace,defaultValue:a,definitionIndex:o.indexOf(t),fieldEditor:d(s,n),fieldOptions:h(s,n),shadowOptions:p(s,n)}}if(e.parameters){let t=s&&!c.this?1:0;e.parameters.forEach(((e,n)=>{let s;if(c[e.name]?s=c[e.name]:t<u.length&&(s=u[t],++t),s||!r){let r;e.options&&e.options.min&&e.options.max&&(r={min:e.options.min.value,max:e.options.max.value});const c=s?s.name:l?l.params[t++]:e.name,u=s&&("variables_get"===s.shadowBlockId||"lists_create_with"==s.shadowBlockId);i.parameters.push({actualName:e.name,type:e.type,defaultValue:u&&s.varName||e.default,definitionName:c,definitionIndex:s?o.indexOf(s):n,shadowBlockId:s&&s.shadowBlockId,isOptional:!!o&&o.indexOf(s)>=a,fieldEditor:d(c,e.name),fieldOptions:h(c,e.name),shadowOptions:p(c,e.name),range:r})}e.handlerParameters&&e.handlerParameters.forEach((e=>{i.handlerArgs.push({name:e.name,type:e.type,inBlockDef:!!o&&o.some((t=>t.ref&&t.name===e.name))})}))}))}return i.parameters.forEach((e=>{i.actualNameToParam[e.actualName]=e,i.definitionNameToParam[e.definitionName]=e})),i;function d(t,n){return e.attributes.paramFieldEditor&&(e.attributes.paramFieldEditor[t]||e.attributes.paramFieldEditor[n])}function h(t,n){return e.attributes.paramFieldEditorOptions&&(e.attributes.paramFieldEditorOptions[t]||e.attributes.paramFieldEditorOptions[n])}function p(t,n){return e.attributes.paramShadowOptions&&(e.attributes.paramShadowOptions[t]||e.attributes.paramShadowOptions[n])}},t.hasHandler=function(e){return e.parameters&&e.parameters.some((e=>{var t,n;return"() => void"==e.type||"Action"==e.type||!!(null===(t=e.properties)||void 0===t?void 0:t.length)||!!(null===(n=e.handlerParameters)||void 0===n?void 0:n.length)}))},t.getHelpUrl=function(t){if(t.attributes.help){const e=t.attributes.help.replace(/^\//,"");if(/^github:/.test(e))return e;if("none"!==e)return"/reference/"+e}else if(t.pkg&&!e.appTarget.bundledpkgs[t.pkg]){let e=t.qName.toLowerCase().split(".");return e[0]==t.pkg&&e.shift(),`/pkg/${t.pkg}#${encodeURIComponent(e.join("-"))}`}},t.reporterTypeForArgType=function(e){let t="argument_reporter_custom";return"boolean"!==e&&"number"!==e&&"string"!==e||(t=`argument_reporter_${e}`),/^(?:Array<(?:.+)>)|(?:(?:.+)\[\])$/.test(e)&&(t="argument_reporter_array"),t},t.defaultIconForArgType=function(e=""){switch(e){case"number":return"calculator";case"string":return"text width";case"boolean":return"random";case"Array":return"list";default:return"align justify"}},t.parseFields=function(e){return e.split("|").map(((e,t)=>{let n=/([^%]*)\s*%([a-zA-Z0-9_]+)/.exec(e);if(!n)return{n:e,ni:t};let i=n[1];return i&&(i=i.trim()),{n:e,ni:t,pre:i,p:n[2]}}))},t.blockDefinitions=function(){return i||s(),i},t.getBlockDefinition=function(e){return i||s(),i[e]},t.initInContextTranslationAsync=async function(){i||s();const t={};return await Promise.all(e.Util.values(i).filter((e=>e.block)).map((async n=>{const i=Object.keys(n.block);n.translationIds=e.Util.values(n.block),await Promise.all(i.map((async i=>{const s=await e.crowdin.inContextLoadAsync(n.block[i]);n.block[i]=s,/^[A-Z_]+$/.test(i)&&(t[i]=s)})))}))),t}}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(t){function n(){return"undefined"!=typeof navigator}function i(){return n()&&/(Win32|Win64|WOW64)/i.test(navigator.platform)}function s(){return n()&&/mobi/i.test(navigator.userAgent)}function r(){return n()&&/Mac/i.test(navigator.platform)}function o(){return!!navigator&&/Linux/i.test(navigator.platform)}function a(){return n()&&/arm/i.test(navigator.platform)}function l(){return n()&&/Edge/i.test(navigator.userAgent)}function c(){return n()&&/Trident/i.test(navigator.userAgent)}function u(){return!l()&&!c()&&!!navigator&&(/Chrome/i.test(navigator.userAgent)||/Chromium/i.test(navigator.userAgent))}function d(){return!u()&&!l()&&!!navigator&&/(Macintosh|Safari|iPod|iPhone|iPad)/i.test(navigator.userAgent)}function h(){return!d()&&!!navigator&&(/Firefox/i.test(navigator.userAgent)||/Seamonkey/i.test(navigator.userAgent))}function p(){return n()&&/Opera|OPR/i.test(navigator.userAgent)}function f(){return n()&&/Midori/i.test(navigator.userAgent)}function m(){return n()&&/Epiphany/i.test(navigator.userAgent)}function g(){return"undefined"!=typeof window&&("ontouchstart"in window||navigator&&navigator.maxTouchPoints>0)}function b(){return"undefined"!=typeof window&&!!window.pxtElectron}function y(){return"undefined"!=typeof window&&!!window.ipcRenderer}function v(){return b()||y()}function w(t){var n;try{return"undefined"!=typeof window&&/^http:\/\/(localhost|127\.0\.0\.1|192\.168\.\d+\.\d+):\d+\//.test(window.location.href)&&(t||!/nolocalhost=1/.test(window.location.href))&&!(null===(n=null==e?void 0:e.webConfig)||void 0===n?void 0:n.isStatic)}catch(e){return!1}}function k(){return"undefined"!=typeof window&&!!window.PointerEvent}function x(){return i()?"windows":r()?"mac":o()&&a()?"rpi":o()?"linux":"unknown"}function A(){return l()?"edge":m()?"epiphany":f()?"midori":p()?"opera":c()?"ie":u()?"chrome":d()?"safari":h()?"firefox":"unknown"}function E(){if(!n())return null;let e=[];return p()&&(e=/(Opera|OPR)\/([0-9\.]+)/i.exec(navigator.userAgent)),m()?e=/Epiphany\/([0-9\.]+)/i.exec(navigator.userAgent):f()?e=/Midori\/([0-9\.]+)/i.exec(navigator.userAgent):d()?(e=/Version\/([0-9\.]+)/i.exec(navigator.userAgent),e||(e=/(Macintosh|iPod( touch)?|iPhone|iPad); (CPU|Intel).*?OS (X )?(\d+)/i.exec(navigator.userAgent))):e=u()?/(Chrome|Chromium)\/([0-9\.]+)/i.exec(navigator.userAgent):l()?/Edge\/([0-9\.]+)/i.exec(navigator.userAgent):c()?/(MSIE |rv:)([0-9\.]+)/i.exec(navigator.userAgent):/(Firefox|Seamonkey)\/([0-9\.]+)/i.exec(navigator.userAgent),e&&0!=e.length?e[e.length-1]:null}t.isDocumentVisible=function(){return"undefined"!=typeof window&&"visible"===document.visibilityState},t.isIFrame=function(){try{return window&&window.self!==window.top}catch(e){return!0}},t.hasNavigator=n,t.hasWindow=function(){return"undefined"!=typeof window},t.isWindows=i,t.isWindows10=function(){return n()&&/(Win32|Win64|WOW64)/i.test(navigator.platform)&&/Windows NT 10/i.test(navigator.userAgent)},t.isMobile=s,t.isIOS=function(){return n()&&(/iPad|iPhone|iPod/.test(navigator.userAgent)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1)},t.isAndroid=function(){return n()&&/android/i.test(navigator.userAgent)},t.isMac=r,t.isLinux=o,t.isARM=a,t.isEdge=l,t.isChromiumEdge=function(){return n()&&/Edg\//i.test(navigator.userAgent)},t.isIE=c,t.isChrome=u,t.isSafari=d,t.isFirefox=h,t.isOpera=p,t.isMidori=f,t.isEpiphany=m,t.isTouchEnabled=g,t.isPxtElectron=b,t.isIpcRenderer=y,t.isElectron=v,t.isWinRT=()=>"undefined"!=typeof Windows,t.isLocalHost=w,t.isLocalHostDev=function(){return w()&&!v()},t.isSkillmapEditor=function(){try{return/skill(?:s?)Map=1/.test(window.location.href)}catch(e){return!1}},t.isTabletSize=function(){return(null===window||void 0===window?void 0:window.innerWidth)<=e.BREAKPOINT_TABLET},t.isComputerSize=function(){return(null===window||void 0===window?void 0:window.innerWidth)>e.BREAKPOINT_TABLET},t.noSharedLocalStorage=function(){try{return/nosharedlocalstorage/i.test(window.location.href)}catch(e){return!1}},t.useOldTutorialLayout=function(){var t,n;if(null===(n=null===(t=e.appTarget)||void 0===t?void 0:t.appTheme)||void 0===n?void 0:n.legacyTutorial)return!0;try{return/tutorialview=old/.test(window.location.href)}catch(e){return!1}},t.hasPointerEvents=k,t.os=x,t.browser=A,t.browserVersion=E;let T=!1;function S(){return s()&&d()&&!/downloadWindowOpen=0/i.test(window.location.href)}function C(t,n,i){const r=S(),o=E(),a=parseInt(o||"0");if(r)i?i.location.href=t:window.open(t,"_self");else if(e.BrowserUtils.isSafari()&&(a<10||0==o.indexOf("10.0")||s())){let n=document.getElementById("downloader");n||(e.debug("injecting downloader iframe"),n=document.createElement("iframe"),n.id="downloader",n.style.position="absolute",n.style.right="0",n.style.bottom="0",n.style.zIndex="-1",n.style.width="1px",n.style.height="1px",document.body.appendChild(n)),n.src=t}else if(/^data:/i.test(t)&&(e.BrowserUtils.isEdge()||e.BrowserUtils.isIE())){let i=atob(t.split(",")[1]),s=e.Util.stringToUint8Array(i),r=new Blob([s],{type:"img/png"});window.navigator.msSaveOrOpenBlob(r,n)}else{let e=window.document.createElement("a");"string"==typeof e.download?(e.href=t,e.download=n,document.body.appendChild(e),e.click(),document.body.removeChild(e)):document.location.href=t}}function I(t,n){let i="data";s()&&d()&&e.appTarget.appTheme.mobileSafariDownloadProtocol&&(i=e.appTarget.appTheme.mobileSafariDownloadProtocol);const r=/downloadProtocol=([a-z0-9:/?]+)/i.exec(window.location.href);r&&(i=r[1]);return i+":"+n+";base64,"+t}function _(t,n,i={}){var s;e.debug("trigger download");const{contentType:r="application/octet-stream",userContextWindow:o,onError:a,maintainObjectURL:l}=i,c=null===(s=window.URL)||void 0===s?void 0:s.createObjectURL,u=e.appTarget.appTheme.disableBlobObjectDownload;let d;try{if(c&&!u){const i=c(new Blob([e.Util.stringToUint8Array(atob(t))],{type:r}));C(i,n,o),l?d=i:window.setTimeout((()=>window.URL.revokeObjectURL(d)),0)}else d=I(t,n),C(d,n,o)}catch(t){a&&a(t),e.debug("saving failed")}return d}function P(e){const t=document.createElement("img");return new Promise(((n,i)=>{t.onload=()=>n(t),t.onerror=()=>n(void 0),t.crossOrigin="anonymous",t.src=e}))}t.isBrowserSupported=function(){var t,n;if(!navigator)return!0;if(/bot|crawler|spider|crawling/i.test(navigator.userAgent))return!0;const i=(null===(t=e.appTarget)||void 0===t?void 0:t.unsupportedBrowsers)||(null===(n=window.pxtTargetBundle)||void 0===n?void 0:n.unsupportedBrowsers);if(null==i?void 0:i.some((e=>e.id==A())))return!1;const s=E(),r=parseInt(s||"0"),c=u()&&r>=38,g=h()&&r>=31,b=l(),y=d()&&r>=9,v=p()&&u()&&r>=21;let w=c||g||b||y||v;const k=f()||o()&&a()&&m();return w=w&&!k,w=w||/anybrowser=(true|1)/.test(window.location.href),T||(e.log(`Browser: ${A()} ${s} on ${x()}`),w||e.tickEvent("browser.unsupported",{useragent:navigator.userAgent}),T=!0),w},t.devicePixelRatio=function(){if("undefined"==typeof window||!window.screen)return 1;const e=window.screen.systemXDPI,t=window.screen.logicalXDPI;return void 0!==e&&void 0!==t&&e>t?e/t:window&&void 0!==window.devicePixelRatio?window.devicePixelRatio:1},t.browserDownloadBinText=function(e,t,n){return _(ts.pxtc.encodeBase64(e),t,n)},t.browserDownloadText=function(t,n,i){return _(ts.pxtc.encodeBase64(e.Util.toUTF8(t)),n,i)},t.isBrowserDownloadInSameWindow=S,t.isBrowserDownloadWithinUserContext=function(){const e=E(),t=parseInt(e||"0");return s()&&d()&&t>=11||/downloadUserContext=1/i.test(window.location.href)},t.browserDownloadDataUri=C,t.browserDownloadUInt8Array=function(t,n,i){return _(ts.pxtc.encodeBase64(e.Util.uint8ArrayToString(t)),n,i)},t.toDownloadDataUri=I,t.browserDownloadBase64=_,t.loadImageAsync=P,t.loadCanvasAsync=function(e){return P(e).then((e=>{const t=document.createElement("canvas");t.width=e.width,t.height=e.height;return t.getContext("2d").drawImage(e,0,0),t}))},t.scaleImageData=function(e,t){const n=document.createElement("canvas"),i=document.createElement("canvas");n.width=e.width,n.height=e.height,i.width=e.width*t,i.height=e.height*t;const s=n.getContext("2d"),r=i.getContext("2d");return s.putImageData(e,0,0),r.imageSmoothingEnabled=!1,r.scale(t,t),r.drawImage(n,0,0),r.getImageData(0,0,e.width*t,e.height*t)},t.imageDataToPNG=function(e,t=1){if(!e)return;const n=document.createElement("canvas"),i=document.createElement("canvas");n.width=e.width,n.height=e.height,i.width=e.width*t,i.height=e.height*t;const s=n.getContext("2d"),r=i.getContext("2d");return s.putImageData(e,0,0),r.imageSmoothingEnabled=!1,r.scale(t,t),r.drawImage(n,0,0),i.toDataURL("image/png")};const U=1e6;function O(t){if(/^https?:\/\//i.test(t))return t;const n=(window.MonacoPaths||{})[t];return n||(e.U.startsWith(t,e.webConfig.commitCdnUrl)?t:e.webConfig.commitCdnUrl+t)}t.encodeToPngAsync=function(t,n){const{width:i,height:s,pixelDensity:r=4,maxSize:o=U,text:a}=n||{};return new Promise(((n,l)=>{const c=new Image;c.onload=function(){const t=document.createElement("canvas"),l=t.getContext("2d");t.width=(i||c.width)*r,t.height=(s||c.height)*r,a&&(l.fillStyle="#fff",l.fillRect(0,0,t.width,t.height)),l.drawImage(c,0,0,i,s,0,0,t.width,t.height);let u=t.toDataURL("image/png");for(;u.length>o;)t.width=t.width/2>>0,t.height=t.height/2>>0,e.debug(`screenshot size ${u.length}b, shrinking to ${t.width}x${t.height}`),l.drawImage(c,0,0,i,s,0,0,t.width,t.height),u=t.toDataURL("image/png");if(a){e.lzmaCompressAsync(a).then((i=>{const s=e.Util.encodeBlobAsync(t,i);n(s.toDataURL("image/png"))}))}else n(u)},c.onerror=t=>{e.reportError("png","png rendering failed"),n(void 0)},c.src=t}))},t.resolveCdnUrl=O,t.loadStyleAsync=function(t,n){n&&(t="rtl"+t);const i="style-"+t;if(document.getElementById(i))return Promise.resolve();const s=O(t),r=e.Util.toArray(document.head.getElementsByTagName("link")).filter((e=>e.getAttribute("href")==s))[0];return r?(r.id||(r.id=i),Promise.resolve()):new Promise(((e,t)=>{const n=document.createElement("link");n.href=s,n.rel="stylesheet",n.type="text/css",n.id=i,n.addEventListener("load",(()=>e())),n.addEventListener("error",(e=>t(e))),document.head.appendChild(n)}))};let N,R,M,D={};function L(e,t){if(!e)return t;if(!t)return e;return(e.indexOf("/")==e.length-1?e.substring(0,e.length-1):e)+"/"+(0==t.indexOf("/")?t.substring(1):t)}function F(){const e=n()&&window.navigator;return e&&e.storage&&e.storage.estimate?e.storage.estimate():Promise.resolve({})}t.loadScriptAsync=function(t){const n=O(t);let i=D[n];return i||(i=D[n]=new Promise(((t,i)=>{e.debug(`script: loading ${n}`);const s=document.createElement("script");s.type="text/javascript",s.addEventListener("load",(()=>t())),s.addEventListener("error",(e=>{delete D[n],i(e)})),s.src=n,s.async=!0,document.body.appendChild(s)}))),i},t.loadAjaxAsync=function(e){return new Promise(((t,n)=>{let i=new XMLHttpRequest;i.onreadystatechange=function(){i.readyState==XMLHttpRequest.DONE&&(200==i.status?t(i.responseText):n(i.status))},i.open("GET",e,!0),i.send()}))},t.loadBlocklyAsync=function(){if(!N){e.debug("blockly: delay load");let t=e.BrowserUtils.loadStyleAsync("blockly.css",ts.pxtc.Util.isUserLanguageRtl());t=t.then((()=>{e.debug("blockly: loaded")})),N=t}return N},t.patchCdn=function(t){if(!t)return t;const n=e.getOnlineCdnUrl();return n?t.replace("@cdnUrl@",n):t.replace(/@cdnUrl@\/(blob|commit)\/[a-f0-9]{40}\//,"./")},t.initTheme=function(){const t=e.appTarget.appTheme;if(t&&t.accentColor){let e=document.createElement("style");e.type="text/css",e.appendChild(document.createTextNode(`.ui.accent { color: ${t.accentColor}; }\n .ui.inverted.menu .accent.active.item, .ui.inverted.accent.menu { background-color: ${t.accentColor}; }`)),document.getElementsByTagName("head")[0].appendChild(e)}if(e.Util.isUserLanguageRtl()){e.debug("rtl layout"),e.BrowserUtils.addClass(document.body,"rtl"),document.body.style.direction="rtl";const t=e.Util.toArray(document.head.getElementsByTagName("link")),n=t.filter((t=>e.Util.endsWith(t.getAttribute("href"),"semantic.css")))[0];if(n){const t=n.getAttribute("data-rtl");t&&(e.debug(`swapping to ${t}`),n.setAttribute("href",t))}const i=t.filter((t=>e.Util.endsWith(t.getAttribute("href"),"blockly.css")))[0];if(i){const t=i.getAttribute("data-rtl");t&&(e.debug(`swapping to ${t}`),i.setAttribute("href",t),i.removeAttribute("data-rtl"))}}},t.changeHash=function(e,t){"#"!=e.charAt(0)&&(e="#"+e),t?window.location.hash=e:window.history.replaceState("","",e)},t.urlJoin=L,t.joinURLs=function(...e){let t;if(e)for(let n=0;n<e.length;n++)t=L(t,e[n]);return t},t.storageEstimateAsync=F,t.scheduleStorageCleanup=n()&&navigator.storage&&navigator.storage.estimate?ts.pxtc.Util.throttle((function(){F().then((t=>(e.debug(`storage estimate: ${t.usage/t.quota*100>>0}%, ${t.usage/1e6>>0}/${t.quota/1e6>>0}Mb`),t.quota&&t.usage&&t.quota>1e6&&t.usage/t.quota>.9?(e.log("quota usage exceeded, clearing translations"),e.tickEvent("storage.cleanup"),H()):Promise.resolve()))).catch((t=>{e.reportException(t)}))}),1e4,!1):()=>{},t.stressTranslationsAsync=function t(){let n="...";for(let e=0;e<16;++e)n+=n+Math.random();return console.log(`adding entry ${2*n.length} bytes`),e.U.delay(1).then((()=>q())).then((e=>e.setAsync("foobar",Math.random().toString(),null,void 0,n))).then((()=>e.BrowserUtils.storageEstimateAsync())).then((e=>!e.quota||e.usage/e.quota<.8?t():Promise.resolve()))};class B{constructor(){this.translations={}}key(e,t){return`${e}|${t}|master`}get(e,t){return this.translations[this.key(e,t)]}getAsync(e,t){return Promise.resolve(this.get(e,t))}set(e,t,n,i,s,r){this.translations[this.key(e,t)]={etag:n,time:i,strings:s,md:r}}setAsync(t,n,i,s,r){return this.set(t,n,i,e.Util.now(),s),Promise.resolve()}clearAsync(){return this.translations={},Promise.resolve()}}class ${constructor(e,t,n,i,s=!1){this.name=e,this.version=t,this.upgradeHandler=n,this.quotaExceededHandler=i,this.skipErrorLog=s}throwIfNotOpened(){if(!this._db)throw new Error("Database not opened; call IDBWrapper.openAsync() first")}errorHandler(t,n,i){this.skipErrorLog?i(t):(console.error(new Error(`${this.name} IDBWrapper error for ${n}: ${t.message}`)),i(t),"QuotaExceededError"==t.name&&(e.log("storage quota exceeded..."),e.tickEvent("storage.quotaexceedederror"),this.quotaExceededHandler&&this.quotaExceededHandler()))}getObjectStore(e,t="readonly"){this.throwIfNotOpened();return this._db.transaction([e],t).objectStore(e)}static deleteDatabaseAsync(e){return new Promise(((t,n)=>{const i=(window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB).deleteDatabase(e);i.onsuccess=()=>t(),i.onerror=()=>n(i.error)}))}openAsync(){return new Promise(((e,t)=>{const n=(window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB).open(this.name,this.version);n.onsuccess=()=>{this._db=n.result,e()},n.onerror=()=>this.errorHandler(n.error,"open",t),n.onupgradeneeded=e=>this.upgradeHandler(e,n)}))}getAsync(e,t){return new Promise(((n,i)=>{const s=this.getObjectStore(e).get(t);s.onsuccess=()=>n(s.result),s.onerror=()=>this.errorHandler(s.error,"get",i)}))}getAllAsync(e){return new Promise(((t,n)=>{const i=this.getObjectStore(e).openCursor(),s=[];i.onsuccess=()=>{i.result?(s.push(i.result.value),i.result.continue()):t(s)},i.onerror=()=>this.errorHandler(i.error,"getAll",n)}))}setAsync(e,t){return new Promise(((n,i)=>{const s=this.getObjectStore(e,"readwrite");let r;r=void 0!==t.id&&null!==t.id?s.put(t):s.add(t),r.onsuccess=()=>n(),r.onerror=()=>this.errorHandler(r.error,"set",i)}))}deleteAsync(e,t){return new Promise(((n,i)=>{const s=this.getObjectStore(e,"readwrite").delete(t);s.onsuccess=()=>n(),s.onerror=()=>this.errorHandler(s.error,"delete",i)}))}deleteAllAsync(e){return new Promise(((t,n)=>{const i=this.getObjectStore(e,"readwrite").clear();i.onsuccess=()=>t(),i.onerror=()=>this.errorHandler(i.error,"deleteAll",n)}))}getObjectStoreWrapper(e){return new j(this,e)}}t.IDBWrapper=$;class j{constructor(e,t){this.db=e,this.storeName=t}getAsync(e){return this.db.getAsync(this.storeName,e)}getAllAsync(){return this.db.getAllAsync(this.storeName)}setAsync(e){return this.db.setAsync(this.storeName,e)}async deleteAsync(e){await this.db.deleteAsync(this.storeName,e)}async deleteAllAsync(){await this.db.deleteAllAsync(this.storeName)}}t.IDBObjectStoreWrapper=j;class V{constructor(e){this.db=e,this.mem=new B}static dbName(){return`__pxt_translations_${e.appTarget.id||""}`}static createAsync(){function e(){const e=new $(V.dbName(),2,((e,t)=>{t.result.createObjectStore(V.TABLE,{keyPath:V.KEYPATH})}),(()=>{H().catch((e=>{}))}));return e.openAsync().then((()=>new V(e)))}return e().catch((t=>(console.log("db: failed to open database, try delete entire store..."),$.deleteDatabaseAsync(V.dbName()).then((()=>e())))))}getAsync(e,t){e=(e||"en-US").toLowerCase();const n=this.mem.key(e,t),i=this.mem.get(e,t);return i?Promise.resolve(i):this.db.getAsync(V.TABLE,n).then((n=>n?(this.mem.set(e,t,n.etag,n.time,n.strings),Promise.resolve(n)):Promise.resolve(void 0))).catch((e=>Promise.resolve(void 0)))}setAsync(n,i,s,r,o){n=(n||"en-US").toLowerCase();const a=this.mem.key(n,i);let l=e.Util.now();this.mem.set(n,i,s,l,r,o),r&&Object.keys(r).filter((e=>!r[e])).forEach((e=>delete r[e]));const c={id:a,etag:s,time:l,strings:r,md:o};return this.db.setAsync(V.TABLE,c).finally((()=>t.scheduleStorageCleanup())).catch((e=>(console.log(`db: set failed (${e.message}), recycling...`),this.clearAsync())))}clearAsync(){return this.db.deleteAllAsync(V.TABLE).then((()=>console.debug("db: all clean"))).catch((e=>{console.error("db: failed to delete all")}))}}function q(){return e.Util.isNodeJS?Promise.resolve(new B):(R||(R=V.createAsync().catch((()=>new B))),R)}function H(){function t(){const t=V.dbName();return $.deleteDatabaseAsync(t).then((()=>{R=void 0})).catch((n=>{e.log(`db: failed to delete ${t}`),R=void 0}))}return R?R.then((e=>e.clearAsync())).catch((e=>t().then())):t()}function G(t){const n=JSON.stringify(t)+e.appTarget.versions.pxt+"_"+e.appTarget.versions.target;return pxtc.U.sha256(n)}function z(e,t){return`${e}|${t||"master"}`}V.TABLE="files",V.KEYPATH="id",t.translationDbAsync=q,t.clearTranslationDbAsync=H,t.getTutorialCodeHash=G;class W{constructor(e){this.db=e}static dbName(){return`__pxt_tutorialinfo_${e.appTarget.id||""}`}static createAsync(){function t(){const t=new e.BrowserUtils.IDBWrapper(W.dbName(),2,((e,t)=>{t.result.createObjectStore(W.TABLE,{keyPath:W.KEYPATH})}),(()=>{e.BrowserUtils.IDBWrapper.deleteDatabaseAsync(W.dbName())}));return t.openAsync().then((()=>new W(t)))}return t().catch((n=>(console.log("db: failed to open tutorial info database, try delete entire store..."),e.BrowserUtils.IDBWrapper.deleteDatabaseAsync(W.dbName()).then((()=>t())))))}getAsync(t,n,i){const s=z(t,i),r=G(n);return this.db.getAsync(W.TABLE,s).then((t=>{if(t&&t.hash==r&&e.Util.now()-(t.time||0)<864e5)return t;this.db.deleteAsync(W.TABLE,s)}))}setAsync(t,n,i,s,r,o){e.perf.measureStart("tutorial info db setAsync");z(t,o);const a=G(i);return this.setWithHashAsync(t,n,a,s,r)}setWithHashAsync(t,n,i,s,r,o){e.perf.measureStart("tutorial info db setAsync");const a=z(t,o),l={};Object.keys(n).forEach((e=>{Object.keys(n[e]).forEach((t=>{l[t]=n[e][t]}))}));const c={id:a,time:e.Util.now(),hash:i,snippets:n,blocks:l,highlightBlocks:s,validateBlocks:r};return this.db.setAsync(W.TABLE,c).then((()=>{e.perf.measureEnd("tutorial info db setAsync")}))}clearAsync(){return this.db.deleteAllAsync(W.TABLE).then((()=>console.debug("db: all clean"))).catch((e=>{console.error("db: failed to delete all")}))}}function J(e){return e.split(/\s+/).filter((e=>!!e))}function Y(){const t=new RegExp(`${e.Util.escapeForRegex(e.Util.pxtLangCookieId)}=(.*?)(?:;|$)`).exec(document.cookie);return t&&t[1]||null}W.TABLE="info",W.KEYPATH="id",t.tutorialInfoDbAsync=function(){return M||(M=W.createAsync()),M},t.clearTutorialInfoDbAsync=function(){function t(){const t=W.dbName();return $.deleteDatabaseAsync(t).then((()=>{M=void 0})).catch((n=>{e.log(`db: failed to delete ${t}`),M=void 0}))}return M?M.then((e=>e.clearAsync())).catch((e=>t().then())):t()},t.pointerEvents=k()?{up:"pointerup",down:["pointerdown"],move:"pointermove",enter:"pointerenter",leave:"pointerleave"}:g()?{up:"mouseup",down:["mousedown","touchstart"],move:"touchmove",enter:"touchenter",leave:"touchend"}:{up:"mouseup",down:["mousedown"],move:"mousemove",enter:"mouseenter",leave:"mouseleave"},t.getPageX=function(e){return"pageX"in e?e.pageX:e.changedTouches[0].pageX},t.getPageY=function(e){return"pageY"in e?e.pageY:e.changedTouches[0].pageY},t.getClientX=function(e){return"clientX"in e?e.clientX:e.changedTouches[0].clientX},t.getClientY=function(e){return"clientY"in e?e.clientY:e.changedTouches[0].clientY},t.popupWindow=function(t,n,i,s){try{const r=window.screenLeft?window.screenLeft:window.screenX,o=window.screenTop?window.screenTop:window.screenY,a=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth,l=window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight,c="width="+i+", height="+s+", top="+(l/2-s/2+o)+", left="+(a/2-i/2+r),u=window.open(t,n,e.BrowserUtils.isIpcRenderer()?void 0:c);return u.focus&&u.focus(),u}catch(t){return e.tickEvent("pxt.popupError",{msg:t.message}),null}},t.containsClass=function(e,t){return J(t).every((t=>function(e,t){if(e.classList)return e.classList.contains(t);return!((e.className+"").split(/\s+/).indexOf(t)<0)}(e,t)))},t.addClass=function(e,t){J(t).forEach((t=>function(e,t){if(e.classList)e.classList.add(t);else{(e.className+"").split(/\s+/).indexOf(t)<0&&(e.className.baseVal+=" "+t)}}(e,t)))},t.removeClass=function(e,t){J(t).forEach((t=>function(e,t){e.classList?e.classList.remove(t):e.className.baseVal=(e.className+"").split(/\s+/).filter((e=>e!=t)).join(" ")}(e,t)))},t.getCookieLang=Y,t.setCookieLang=function(t,n=!1){if(e.Util.allLanguages[t]&&t!==Y()){e.tickEvent("menu.lang.setcookielang",{lang:t,docs:`${n}`});const i=new Date;i.setTime(i.getTime()+24*e.Util.langCookieExpirationDays*60*60*1e3),document.cookie=`${e.Util.pxtLangCookieId}=${t}; expires=${i.toUTCString()}; path=/`}},t.cacheBustingUrl=function(e){return e?/[?&]rnd=/.test(e)?e:`${e}${e.indexOf("?")>0?"&":"?"}rnd=${Math.random()}`:e},t.legacyCopyText=function(t){t.focus(),t.setSelectionRange(0,9999);try{const t=document.execCommand("copy");return e.debug("copy: "+t),!!t}catch(e){return!1}},t.setApplicationTheme=function(e){const t=document.body,n=t.classList;for(let e=0;e<n.length;e++)/^theme-/.test(n[e])&&t.classList.remove(n[e]);e&&t.classList.add(`theme-${e}`)},t.isElement=function(e){return e.nodeType===Node.ELEMENT_NODE}}(e.BrowserUtils||(e.BrowserUtils={}))}(pxt||(pxt={})),function(e){!function(e){const t="https://staging.pxt.io";e.DEV_BACKEND=t,e.devBackendType=function(){return"https://makecode.com"===e.DEV_BACKEND?"prod":e.DEV_BACKEND===t?"staging":"http://localhost:8080"===e.DEV_BACKEND?"localhost":"prod"},e.cloudStatus={none:{value:"none"},synced:{value:"synced",icon:"cloud-saved-b",tooltip:lf("Project saved to cloud"),shortStatus:lf("saved"),longStatus:lf("Saved to cloud"),indicator:""},justSynced:{value:"justSynced",icon:"cloud-saved-b",tooltip:lf("Project saved to cloud"),shortStatus:lf("saved!"),longStatus:lf("Saved to cloud!"),indicator:""},offline:{value:"offline",icon:"cloud-error-b",tooltip:lf("Unable to connect to cloud"),shortStatus:lf("offline"),longStatus:lf("Offline"),indicator:lf("offline")},syncing:{value:"syncing",icon:"cloud-saving-b",tooltip:lf("Saving project to cloud..."),shortStatus:lf("saving..."),longStatus:lf("Saving to cloud..."),indicator:lf("syncing...")},conflict:{value:"conflict",icon:"cloud-error-b",tooltip:lf("Project was edited in two places and the changes conflict"),shortStatus:lf("conflict!"),longStatus:lf("Project has a conflict!"),indicator:"!"},localEdits:{value:"localEdits",icon:"cloud-saving-b",tooltip:lf("Project has local changes and will save to cloud soon."),shortStatus:"",longStatus:"",indicator:"*"}}}(e.cloud||(e.cloud={}))}(pxt||(pxt={})),function(e){!function(e){let t;!function(e){e[e.Failed=0]="Failed",e[e.Success=1]="Success",e[e.UserRejected=2]="UserRejected"}(t=e.WebUSBPairResult||(e.WebUSBPairResult={})),e.deployCoreAsync=void 0,e.deployFallbackAsync=void 0,e.hasDeployFn=()=>e.deployCoreAsync||e.deployFallbackAsync,e.deployAsync=(t,n)=>(e.deployCoreAsync||e.deployFallbackAsync)(t,n),e.patchCompileResultAsync=void 0,e.browserDownloadAsync=void 0,e.saveOnlyAsync=void 0,e.renderBrowserDownloadInstructions=void 0,e.renderUsbPairDialog=void 0,e.renderIncompatibleHardwareDialog=void 0,e.showUploadInstructionsAsync=void 0,e.saveProjectAsync=void 0,e.electronDeployAsync=void 0,e.webUsbPairDialogAsync=void 0,e.onTutorialCompleted=void 0,e.workspaceLoadedAsync=void 0}(e.commands||(e.commands={}))}(pxt||(pxt={})),function(e){function t(t){const n=e.toolbox.convertColor(t),i=parseInt(n.slice(1,3),16)/255,s=parseInt(n.slice(3,5),16)/255,r=parseInt(n.slice(5,7),16)/255;return.2126*(i<=.03928?i/12.92:Math.pow((i+.055)/1.055,2.4))+.7152*(s<=.03928?s/12.92:Math.pow((s+.055)/1.055,2.4))+.0722*(r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4))}function n(e,n){return(t(e)+.05)/(t(n)+.05)}function i(e){const t=(1-Math.abs(2*e.l-1))*e.s,n=e.h/60,i=t*(1-Math.abs(n%2-1));let r;void 0===e.h?r=[0,0,0]:n<=1?r=[t,i,0]:n<=2?r=[i,t,0]:n<=3?r=[0,t,i]:n<=4?r=[0,i,t]:n<=5?r=[i,0,t]:n<=6&&(r=[t,0,i]);let o=e.l-.5*t;return a=Math.round(255*(r[0]+o)),l=Math.round(255*(r[1]+o)),c=Math.round(255*(r[2]+o)),"#"+s(a)+s(l)+s(c);var a,l,c}function s(e){return("0"+e.toString(16)).slice(-2)}e.getWhiteContrastingBackground=function(t){if(n("#ffffff",t)>=4.5)return t;const s=function(t){const n=e.toolbox.convertColor(t),i=parseInt(n.slice(1,3),16)/255,s=parseInt(n.slice(3,5),16)/255,r=parseInt(n.slice(5,7),16)/255,o=Math.max(Math.max(i,s),r),a=Math.min(Math.min(i,s),r),l=o-a;let c;0===l?c=0:o===i?c=((s-r)/l%6+6)%6:o===s?c=(r-i)/l+2:o===r&&(c=(i-s)/l+4);let u=(a+o)/2,d=0===l?0:l/(1-Math.abs(2*u-1));return{h:60*c,s:d,l:u}}(t);let r=s.l-.05;for(;r>0;){const e=i({h:s.h,s:s.s,l:r});if(n("#ffffff",e)>=4.5)return e;r-=.05}return console.warn(`Couldn't find a contrasting background for color ${t}`),t},e.contrastRatio=n}(pxt||(pxt={})),function(e){function t(){let t;return t||(t=e.U.isNodeJS?Promise.resolve(require("lzma")):Promise.resolve(window.LZMA),t.then((t=>(t||e.reportError("lzma","failed to load"),t)))),t}e.lzmaDecompressAsync=function(n){return t().then((t=>new Promise(((i,s)=>{try{t.decompress(n,((t,n)=>{n&&e.debug("lzma decompression failed"),i(n?void 0:t)}))}catch(t){t&&e.debug("lzma decompression failed"),i(void 0)}}))))},e.lzmaCompressAsync=function(n){return t().then((t=>new Promise(((i,s)=>{try{t.compress(n,7,((t,n)=>{n&&e.reportException(n),i(n?void 0:new Uint8Array(t))}))}catch(t){e.reportException(t),i(void 0)}}))))}}(pxt||(pxt={})),function(e){!function(t){var n=pxtc.Util;let i=n.lf;const s={"pxt::mkAction":1,"pxt::dumpPerfCounters":1,"pxt::deepSleep":1,"pxt::getConfig":1,"pxtrt::mkMap":1,"pxtrt::mapSet":1,"pxtrt::stclo":1,"pxtrt::mklocRef":1,"pxtrt::stlocRef":1,"pxtrt::ldlocRef":1,"pxtrt::panic":1};function r(e="namespace"){let t="",n="",i=(i,s="")=>{n!=i&&(n&&(t+="}\n"),i&&(t+=s||e+" "+i+" {\n"),n=i)},s=" ";return{setNs:i,clear:()=>{t="",n=""},write:e=>{e.trim()?(e=e.trim().replace(/^\s*/gm,s).replace(/^(\s*)\*/gm,((e,t)=>t+" *")),t+=e+"\n"):t+="\n"},incrIndent:()=>{s+=" "},decrIndent:()=>{s=s.slice(4)},finish:()=>(i(""),t)}}function o(e){if(!e)return null;e=e.trim();let t=/^\((.*)\)/.exec(e);return t&&(e=t[1]),/^-?(\d+|0[xX][0-9a-fA-F]+)$/.test(e)?parseInt(e):null}t.nsWriter=r,t.parseCppInt=o;let a={};class l extends Error{constructor(e){super(e),this.isUserError=!0,this.message=e}}function c(e){if(!e)return"";let t="";for(let n=0;n<e.length;++n){let i=255&e[n];t+=37==i||i>127?"%"+i.toString(16):String.fromCharCode(i)}return decodeURIComponent(t)}function u(t){let n="",i=0;for(;i<t.length;i+=2)n=t[i]+t[i+1]+n;return e.Util.assert(i==t.length),n}function d(e){let t=[65,20,14,47,184,47,162,187];e:for(let n=0;n<e.length;n+=16){if(e[n]!=t[0])continue;for(let i=0;i<t.length;++i)if(e[n+i]!=t[i])continue e;let i=e[n+8]|e[n+9]<<8,s=e[n+10]|e[n+11]<<8|e[n+12]<<16|e[n+13]<<24;n+=16;let r=n+i+s;if(r>e.length)continue;let o=e.slice(n,n+i),a=e.slice(n+i,r);return{meta:c(o),text:a}}return null}function h(t){function n(t){return e.debug(t),Promise.reject(new Error(t))}let i;if(e.HF2.read32(t,0)==ts.pxtc.UF2.UF2_MAGIC_START0){let e=ts.pxtc.UF2.toBin(t);e&&(i=d(e.buf))}if(1179403647==e.HF2.read32(t,0)&&(i=d(t)),58==t[0]){i=function(e){if(!e)return;let t,n=0,i=0,s=0,r=0;if(e.split(/\r?\n/).forEach((e=>{let o=/^:10....0[0E]41140E2FB82FA2BB(....)(....)(....)(....)(..)/.exec(e);if(o)n=parseInt(u(o[1]),16),i=parseInt(u(o[2]),16),s=n+i,t=new Uint8Array(s);else if(s>0){if(o=/^:10....0[0E](.*)(..)$/.exec(e),!o)return;let n=o[1];for(;s>0&&n.length>0;)t[r++]=parseInt(n[0]+n[1],16),n=n.slice(2),s--}})),!t||0!=s||r!=t.length)return;let o=new Uint8Array(n),a=new Uint8Array(i);for(let e=0;e<n;++e)o[e]=t[e];for(let e=0;e<i;++e)a[e]=t[n+e];return{meta:c(o),text:a}}(c(t)||"")}if(!i||!i.meta||!i.text)return n("This .hex file doesn't contain source.");let s=JSON.parse(i.meta);return s?"LZMA"==s.compression?e.lzmaDecompressAsync(i.text).then((t=>{if(!t)return null;let n=t.slice(0,s.headerSize||s.metaSize||0),i=t.slice(n.length);return n&&e.Util.jsonCopyFrom(s,JSON.parse(n)),{meta:s,source:i}})):s.compression?n(`Compression type ${s.compression} not supported.`):Promise.resolve({source:c(i.text)}):n("This .hex file is not valid.")}t.PkgConflictError=l,t.getExtensionInfo=function(t){const c={__appVariant:e.appTargetVariant||""},u="dal.d.ts";let d="/source/",h="",p=[];const f=t.sortedDeps(!0).sort(((e,t)=>"this"==e.id?1:"this"==t.id?-1:n.strcmp(e.id,t.id)));for(let t of f)t.disablesVariant(e.appTargetVariant)||t.resolvedDependencies().some((t=>t.disablesVariant(e.appTargetVariant)))?(h&&(h+=", "),h+=t.id,e.debug(`disable variant ${e.appTargetVariant} due to ${t.id}`)):(p.push(t),t.addSnapshot(c,[u,".h",".cpp"]));const m=JSON.stringify(c),g=a[m];if(g){e.debug("Using cached extinfo");const t=n.flatClone(g);return t.disabledDeps=h,t}e.debug("Generating new extinfo");const b=pxtc.emptyExtInfo();b.disabledDeps=h;let y=e.appTarget.compileService;y||(y={gittag:"none",serviceId:"nocompile"}),y=n.clone(y);let v=t.getTargetOptions();v||(v={isNative:!1,hasHex:!1,switches:{}});const w=!!y.platformioIni,k="codal"==y.buildEngine||"dockercodal"==y.buildEngine,x="dockermake"==y.buildEngine||"dockercross"==y.buildEngine,A="dockerespidf"==y.buildEngine,E=!(w||k||x||A),T=v.nativeType==pxtc.NATIVE_TYPE_VM;w?d="/src/":k||x?d="/pxtapp/":A&&(d="/main/");let S="// Configuration defines\n",C="\nPXT_SHIMS_BEGIN\n",I="",_="",P='#include "pxt.h"\n',U="",O=e=>U+=` ${R}(${N}): ${e}\n`,N=0,R="",M=r("namespace"),D=r("declare namespace"),L=r("declare namespace"),F="",B={},$={};const j={true:"1",false:"0",null:"0",NULL:"0"};function V(e){return e.trim().replace(/[\_\*]$/,"")}for(const t of p){if(t.getFiles().indexOf(u)>=0){const n=t.host().readFile(t,u);e.Util.assert(!!n,`dal.d.ts not found in ${t.id}`),n.split(/\r?\n/).forEach((e=>{let t=/^\s*(\w+) = (.*),/.exec(e);t&&(j[t[1]]=t[2])}))}for(const e of t.getFiles())(["Makefile","sdkconfig.defaults","CMakeLists.txt"].indexOf(e)>=0||n.endsWith(e,".mk"))&&(b.generatedFiles["/"+e]=t.host().readFile(t,e))}let q=["0","false","PXT_UTF8"],H={};function G(e){return e.replace(/\/\/.*/,"").replace(/\/\*/,"")}v.switches.boxDebug&&(H.PXT_BOX_DEBUG=1),v.utf8&&(H.PXT_UTF8=1),v.switches.profile&&(H.PXT_PROFILE=1),v.switches.gcDebug&&(H.PXT_GC_DEBUG=1),v.switches.numFloat&&(H.PXT_USE_FLOAT=1),v.nativeType==pxtc.NATIVE_TYPE_VM&&(H.PXT_VM=1);let z=0,W=!1,J="",Y="",K="",X=!1;function Q(){D.setNs(""),D.write(""),D.write(""),(K||Y)&&(D.write(Y),D.write(K),K="",Y="")}function Z(e,t){let r;J="",Y="",K="",X=!1;let a=-1;function l(){let e=J.replace(/Methods$/,"");return e==J?null:e}function c(e){switch(e.replace(/\s+/g,"")){case"void":return"void";case"int32_t":case"int":return"int32";case"uint32_t":case"unsigned":return"uint32";case"TNumber":case"float":case"double":return"number";case"uint16_t":return"uint16";case"int16_t":case"short":return"int16";case"uint8_t":case"byte":return"uint8";case"int8_t":case"sbyte":return"int8";case"bool":return v.shortPointers&&O("use 'boolean' not 'bool' on 8 bit targets"),"boolean";case"StringData*":case"String":case"ImageLiteral_":case"ImageLiteral":return"string";case"Action":return"() => void";case"TValue":return"any";default:return V(e)}}function u(e){switch(e=e.replace(/\s+/g,"")){case"int32_t":case"uint32_t":case"unsigned":case"uint16_t":case"int16_t":case"short":case"uint8_t":case"byte":case"int8_t":case"sbyte":case"int":case"ramint_t":return"I";case"void":return"V";case"float":return"F";case"TNumber":return"N";case"TValue":return"T";case"bool":return"B";case"double":return"D";case"ImageLiteral_":return"T";case"String":return"S";default:return n.lookup(B,e)?"I":"_"+e.replace(/[\*_]+$/,"")}}e=e.replace(/^(\s*#\s*if\s+(\w+)\s*$)([^]*?)(^\s*#\s*(elif|else|endif)\s*$)/gm,((e,t,n,i,s)=>q.indexOf(n)>=0&&!H[n]?t+i.replace(/[^\n]/g,"")+s:e)),N=0,W=!1,z=0,L.setNs(""),D.setNs(""),e.split(/\r?\n/).forEach((e=>{++N;let d=G(e);!function(e){let t=G(e);if(W&&t.indexOf("}")>=0&&(W=!1,L.write("}")),!W)return;let i=/^\s*(\w+)\s*(=\s*(.*?))?,?\s*$/.exec(t);if(i){let e=i[1],s=i[3],r="";if(s){s=s.trim();let e=n.lookup(j,s);null!=e&&(r=" // "+s,s=e),z=o(s),null==z&&O("cannot determine value of "+t)}else z++,s=z+"";L.write(` ${V(e)} = ${s},${r}`)}else L.write(e)}(e);let h=/^\s*enum\s+(|class\s+|struct\s+)(\w+)\s*({|$)/.exec(d);var p,f;if(h&&(p=h[2],f=h[3],W=!0,z=-1,L.write(""),L.write(""),(K||Y)&&(L.write(Y),L.write(K),K="",Y=""),L.write(`declare const enum ${V(p)} ${f}`),B[p]=!0,t||(M.setNs(J),M.write(`enum ${h[2]} : int;`))),function(e){return!(!W&&(/^\s*\/\*\*/.test(e)?(X=!0,Y=e+"\n",/\*\//.test(e)&&(X=!1),0):X?(Y+=e+"\n",/\*\//.test(e)&&(X=!1),0):!/^\s*\/\/%/.test(e)||(K+=e+"\n",0)))}(e))return;/^typedef.*;\s*$/.test(e)&&(M.setNs(J),M.write(e));let m=/^\s*namespace\s+(\w+)/.exec(e);if(m)if(J=m[1],l()){Q();let e=l();D.setNs(J,`declare interface ${e} {`)}else(K||Y)&&(Q(),D.setNs(V(J)),L.setNs(V(J)));else{if(m=/^PXT_ABI\((\w+)\)/.exec(e),m&&!T&&(C+=`PXT_FNPTR(::${m[1]}),\n`,_+=`extern "C" void ${m[1]}();\n`,b.functions.push({name:m[1],argsFmt:[],value:0})),m=/^\s*PXT_EXPORT\(([:\&\w]+)\)/.exec(e),m&&(b.vmPointers||(b.vmPointers=[]),b.vmPointers.push(m[1])),m=/^#define\s+PXT_COMM_BASE\s+([0-9a-fx]+)/.exec(e),m&&(b.commBase=parseInt(m[1])),m=/^\s*(\w+)([\*\&]*\s+[\*\&]*)(\w+)\s*\(([^\(\)]*)\)\s*(;\s*$|\{|$)/.exec(e),!K||!m){if(m=/^\s*extern const (\w+) (\w+);/.exec(e),K&&m){let e={name:J+"::"+m[2],argsFmt:[],value:null};return b.functions.push(e),T||(C+="PXT_FNPTR(&::"+e.name+"),\n"),void(K="")}if(m=/^\s*(\w+)\s+(\w+)\s*;/.exec(e),K&&m){let e=pxtc.parseCommentString(K);e.indexedInstanceNS&&(r=e,D.setNs(e.indexedInstanceNS),a=0);let t=m[1],n=m[2];if(r)return K=K.trim(),K+=` fixedInstance shim=${r.indexedInstanceShim}(${a++})`,D.write(""),D.write(Y),D.write(K),D.write(`const ${n}: ${c(t)};`),Y="",void(K="")}return K&&e.trim()?(O("declaration not understood: "+e),K="",void(Y="")):void 0}{r=null;let e=pxtc.parseCommentString(K);J||O("missing namespace declaration");let a=(m[1]+m[2]).replace(/\s+/g,""),d=m[3],h=m[4];K=K.trim().replace(/ \w+\.defl=\w+/g,"");let p=[u(a)],f=[],g=h.split(/,/).filter((e=>!!e)).map((t=>{let i=function(e,t){t=t.trim();let i=/(.*)=\s*(-?\w+)$/.exec(t),s="",r="";if(i&&(s=i[2],r="?",t=i[1].trim()),i=/^(.*?)(\w+)$/.exec(t),!i)return O("invalid argument: "+t),{name:"???",type:"int"};let a=i[2];e.paramDefl[a]&&(s=e.paramDefl[a],r="?");let l=s?n.lookup(j,s):null;return null!=l&&(s=l),s&&(null==o(s)&&O("Invalid default value (non-integer): "+s),K+=` ${a}.defl=${s}`),{name:a+r,type:i[1]}}(e,t);return p.push(u(i.type)),f.push(i.type.replace(/ /g,"")),`${i.name}: ${c(i.type)}`})),y={name:J+"::"+d,argsFmt:p,value:null};if(Y)if(D.setNs(V(J)),D.write(""),D.write(Y),/ImageLiteral/.test(m[4])&&!/imageLiteral=/.test(K)&&(K+=" imageLiteral=1"),K+=` shim=${y.name}`,D.write(K),d=V(d),l()){let e=(g[0]||"").replace(/^.*:\s*/,"").trim();e.toLowerCase()!=l().toLowerCase()&&O(i("Invalid first argument; should be of type '{0}', but is '{1}'",l(),e)),g.shift(),0==g.length&&/\bproperty\b/.test(K)?D.write(`${d}: ${c(a)};`):D.write(`${d}(${g.join(", ")}): ${c(a)};`)}else D.write(`function ${d}(${g.join(", ")}): ${c(a)};`);if(Y="",K="",t||(M.setNs(J),M.write(`${a} ${d}(${h});`)),b.functions.push(y),E)C+="(uint32_t)(void*)::"+y.name+",\n";else if(T){if(n.startsWith(y.name,"pxt::op_")||s[y.name]||e.expose||!n.startsWith(y.name,"pxt::")&&!n.startsWith(y.name,"pxtrt::")){const e=function(e,t){if("FiberContext*"==t[0])return"::"+e.name;let n="_wrp_"+e.name.replace(/:/g,"_");if($[e.name])return n;$[e.name]=!0,I+=`\nvoid ${n}(FiberContext *ctx) {\n`;const i=t.length;let s=[],r=!1,o="";for(let n=0;n<i;++n){const a=e.argsFmt[n+1],l=t[n];let c="I"==a?"toInt":"B"==a?"numops::toBool":"";const u=n==i-1?"ctx->r0":`ctx->sp[${i-n-2}]`;let d="";switch(l){case"TValue":case"TNumber":break;case"Action":c="asRefAction";break;case"String":c="convertToString",d="ctx, ",r=!0;break;default:c||(c="as"+l.replace(/\*/g,""))}o+=` ${l} a${n} = (${l}) ${c}(${d}${u});\n`,s.push("a"+n)}r&&(I+=" auto prevSP = ctx->sp;\n"),I+=o,r&&(I+=" if (panicCode) { ctx->sp = prevSP; return; }\n");const a=`::${e.name}(${s.join(", ")})`;return"V"==e.argsFmt[0]?(I+=` ${a};\n`,I+=" ctx->r0 = NULL;\n"):"I"==e.argsFmt[0]?I+=` ctx->r0 = fromInt(${a});\n`:"B"==e.argsFmt[0]?I+=` ctx->r0 = fromBool(${a});\n`:I+=` ctx->r0 = (TValue)${a};\n`,r&&(I+=" ctx->sp = prevSP;\n"),i>1&&(I+=` ctx->sp += ${i-1};\n`),I+="}\n",n}(y,f),t=y.argsFmt.length-1;C+=`{ "${y.name}", (OpFun)(void*)${e}, ${t} },\n`}}else C+="PXT_FNPTR(::"+y.name+"),\n"}}}))}const ee=n.clone(y.yottaConfig||{}),te={},ne={},ie={};function se(t){const s=t.config.platformio;s&&s.dependencies&&n.jsonCopyFrom(b.platformio.dependencies,s.dependencies),b.npmDependencies&&t.config.npmDependencies&&n.jsonCopyFrom(b.npmDependencies,t.config.npmDependencies);const r=t.config.codal;if(k&&r)for(const t of r.libraries||[]){const s=e.github.parseRepoId(t);s||n.userError(i("codal library {0} doesn't look like github repo",t));const r=e.github.stringifyRepo(s),o=n.lookup(ie,s.project);o?e.github.stringifyRepo(o)!=r&&n.userError(i("conflict between codal libraries: {0} and {1}",e.github.stringifyRepo(o),r)):ie[s.project]=s}const o=t.config.yotta;if(o){if(o.dependencies&&n.jsonCopyFrom(b.yotta.dependencies,o.dependencies),o.config){const e=n.jsonFlatten(o.config);for(const s of Object.keys(e)){const r=n.lookup(ne,s),o=e[s];if(!r||r.config.yotta.configIsJustDefaults)ne[s]=t,ee[s]=o;else if(ee[s]===o);else if(!t.parent.config.yotta||!t.parent.config.yotta.ignoreConflicts){let e=new l(i("conflict on yotta setting {0} between extensions {1} and {2}",s,t.id,r.id));throw e.pkg0=r,e.pkg1=t,e.settingName=s,e}}}if(o.optionalConfig){const e=n.jsonFlatten(o.optionalConfig);for(const t of Object.keys(e)){const n=e[t];te[t]=n}}}}if(E&&v.hasHex){let e=y;n.assert(!!e.yottaCorePackage),n.assert(!!e.githubCorePackage),n.assert(!!e.gittag);let t=e.githubCorePackage+"#"+y.gittag;b.yotta.dependencies[e.yottaCorePackage]=t}if(t){let e=!1;for(let s of p){U="",se(s),s==t?(e=!0,D.clear(),L.clear()):n.assert(!e);const r=e=>n.endsWith(e,".h"),o=".cpp",a=s.getFiles().filter(r).concat(s.getFiles().filter((e=>!r(e))));for(let e of a){const t=r(e);if(t||n.endsWith(e,o)){let r=s.config.name+"/"+e;("base"==s.config.name||/^core($|---)/.test(s.config.name))&&t&&(r=e),t&&(P+=`#include "${E?d.slice(1):""}${r}"\n`);let o=s.readFile(e);null==o&&n.userError(i("C++ file {0} is missing in extension {1}.",e,s.config.name)),R=r,Z(o,t),b.extensionFiles[d+r]=o,0==s.level&&(b.onlyPublic=!1),s.verProtocol()&&"pub"!=s.verProtocol()&&"embed"!=s.verProtocol()&&(b.onlyPublic=!1)}if(n.endsWith(e,".c")||n.endsWith(e,".S")||n.endsWith(e,".s")){let t=s.readFile(e);b.extensionFiles[d+s.config.name+"/"+e.replace(/\.S$/,".s")]=t}}U&&(F+=i("Extension {0}:\n",s.id)+U)}e||(D.clear(),L.clear())}function re(e){return Object.keys(b.extensionFiles).concat(Object.keys(b.generatedFiles)).filter((t=>n.endsWith(t,e))).map((e=>e.slice(1)))}F&&n.userError(F),n.jsonCopyFrom(te,ee),n.iterMap(te,((e,t)=>{null===t&&delete te[e]})),Object.keys(te).filter((e=>/-/.test(e))).forEach((e=>{const t=te[e];delete te[e],te[e.replace(/-/g,"_")]=t})),!E&&y.yottaConfigCompatibility&&Object.keys(te).forEach((e=>te["YOTTA_CFG_"+e]=te[e])),te.PXT_TARGET=JSON.stringify(e.appTarget.id);const oe=n.jsonUnFlatten(te);if(x){let e={name:"pxt-app",private:!0,dependencies:b.npmDependencies};b.generatedFiles["/package.json"]=JSON.stringify(e,null,4)+"\n"}else if(A){const e=n.concatArrayLike([re(".c"),re(".cpp"),re(".s")]).map((e=>e.slice(d.length-1))).concat(["main.cpp"]);e.push("pointers.cpp"),b.generatedFiles[d+"CMakeLists.txt"]="idf_component_register(\n SRCS\n"+e.map((e=>` "${e}"\n`)).join("")+' INCLUDE_DIRS\n "."\n)\n'}else if(k){let t=y,i=n.clone(t.codalDefinitions)||{},s=t.codalTarget;"string"==typeof s&&(s+=".json");let r={target:s,definitions:i,config:i,application:"pxtapp",output_folder:"build",pxt_gitrepo:t.githubCorePackage,pxt_gittag:t.gittag,libraries:n.values(ie).map((e=>({name:e.project,url:"https://github.com/"+e.fullName,branch:e.tag||"master",type:"git"})))};0==r.libraries.length&&delete r.libraries,n.iterMap(n.jsonFlatten(oe),((e,t)=>{e=e.replace(/^codal\./,"device.").toUpperCase().replace(/\./g,"_"),i[e]=t})),b.generatedFiles["/codal.json"]=JSON.stringify(r,null,4)+"\n",e.debug(`codal.json: ${b.generatedFiles["/codal.json"]}`),b.codal=r}else if(w){const e=y.platformioIni.slice();e.push("lib_deps ="),n.iterMap(b.platformio.dependencies,((t,n)=>{let i=/[@#\/]/.test(n)?n:t+"@"+n;e.push(" "+i)})),b.generatedFiles["/platformio.ini"]=e.join("\n")+"\n"}else{b.yotta.config=oe;let t="pxt-app";y.yottaBinary&&(t=y.yottaBinary.replace(/-combined/,"").replace(/\.hex$/,""));let n={name:t,version:"0.0.0",description:"Auto-generated. Do not edit.",license:"n/a",dependencies:b.yotta.dependencies,targetDependencies:{},bin:"./source"};b.generatedFiles["/module.json"]=JSON.stringify(n,null,4)+"\n",e.debug(`module.json: ${b.generatedFiles["/module.json"]}`)}for(let e of Object.keys(H))S+=`#define ${e} ${H[e]}\n`;if(v.uf2Family&&(S+=`#define PXT_UF2_FAMILY ${v.uf2Family}\n`),b.generatedFiles[d+"pointers.cpp"]=P+M.finish()+_+I+C+"\nPXT_SHIMS_END\n",b.generatedFiles[d+"pxtconfig.h"]=S,e.debug(`pxtconfig.h: ${b.generatedFiles[d+"pxtconfig.h"]}`),E&&(b.generatedFiles["/config.json"]=JSON.stringify(oe,null,4)+"\n",e.debug(`yotta config.json: ${b.generatedFiles["/config.json"]}`)),b.generatedFiles[d+"main.cpp"]='\n#include "pxt.h"\n#ifdef PXT_MAIN\nPXT_MAIN\n#else\nint main() {\n uBit.init();\n pxt::start();\n release_fiber();\n return 0; // your program will never reach this line.\n}\n#endif\n',b.generatedFiles["/Makefile"]){let e="",t=(t,n)=>{e+=`${t} = ${re(n).join(" ")}\n`};t("PXT_C",".c"),t("PXT_CPP",".cpp"),t("PXT_S",".s"),t("PXT_HEADERS",".h"),e+="PXT_SOURCES := $(PXT_C) $(PXT_S) $(PXT_CPP)\n",e+="PXT_OBJS := $(addprefix bld/, $(PXT_C:.c=.o) $(PXT_S:.s=.o) $(PXT_CPP:.cpp=.o))\n",b.generatedFiles["/Makefile.inc"]=e}b.generatedFiles["/functions.json"]=JSON.stringify(b.functions,null,1);let ae=b.extensionFiles;n.jsonCopyFrom(ae,b.generatedFiles);let le={config:y.serviceId,tag:y.gittag,replaceFiles:ae,dependencies:E?b.yotta.dependencies:null},ce=JSON.stringify(le);return b.sha=n.sha256(ce),b.skipCloudBuild=!!y.skipCloudBuild,b.compileData=ts.pxtc.encodeBase64(n.toUTF8(ce)),b.shimsDTS=D.finish(),b.enumsDTS=L.finish(),Object.keys(a).length>10&&(a={}),a[m]=b,b},t.unpackSourceFromHexFileAsync=function(t){if(t)return e.Util.fileReadAsBufferAsync(t).then((e=>h(new Uint8Array(e))))},t.unpackSourceFromHexAsync=h}(e.cpp||(e.cpp={}))}(pxt||(pxt={})),function(e){!function(t){const n={};let i,s={};function r(s){return n.hasOwnProperty(s.sha)||(n[s.sha]=function(n){let s="";return t.showLoading(e.U.lf("Compiling (this may take a minute)...")),e.tickEvent("cppcompile.start"),function(t){if(t.skipCloudBuild)return Promise.resolve({hex:["SKIP"]});if(e.webConfig&&e.webConfig.isStatic)return e.Util.requestAsync({url:`${e.webConfig.cdnUrl}hexcache/${t.sha}.hex`}).then((t=>{if(t.text){const e={enums:[],functions:[],hex:t.text.split(/\r?\n/)};return Promise.resolve(e)}return e.log("Hex info not found in bundled hex cache"),Promise.resolve()})).catch((t=>(e.log("Error fetching hex info from bundled hex cache"),Promise.resolve())));if(!e.Cloud.localToken||!window||!e.BrowserUtils.isLocalHost())return Promise.resolve(void 0);return(n="compile/"+t.sha,e.Cloud.localRequestAsync(n,i).then((e=>e.json))).then((e=>e&&!e.notInOfflineCache&&e.hex?(e.hex=e.hex.split(/\r?\n/),e):Promise.resolve(void 0))).catch((e=>Promise.resolve(void 0)));var n,i}(n).then((r=>r?(e.tickEvent("cppcompile.cachehit"),r):function(){if(i)return i;{let t=e.getOnlineCdnUrl();if(t)return i=Promise.resolve(t);const n=e.webConfig&&e.webConfig.isStatic;return i=e.Cloud.privateGetAsync("clientconfig",n).then((e=>e.primaryCdnUrl))}}().then((t=>(s=t+"/compile/"+n.sha,e.U.httpGetTextAsync(s+".hex")))).then((e=>e),(t=>e.Cloud.privatePostAsync("compile/extension",{data:n.compileData},!0).then((t=>new Promise(((n,i)=>{let r=0;const o=8e3,a=3e5,l=e.U.now(),c=()=>{if(r++,e.U.now()-l>a)return e.log("abandoning C++ build"),e.tickEvent("cppcompile.cancel",{retry:r}),n(null),null;let i=t.hex.replace(/\.hex/,".json");return e.log(`polling C++ build ${i} (attempt #${r})`),e.tickEvent("cppcompile.poll",{retry:r}),e.Util.httpGetJsonAsync(i).then((t=>{e.log(`build log ${i.replace(/\.json$/,".log")}`),e.tickEvent("cppcompile.done",{success:(null==t?void 0:t.success)?1:0,retry:r,duration:e.U.now()-l}),t.success?(e.log("fetching "+s+".hex"),n(e.U.httpGetTextAsync(s+".hex"))):(e.log("build failed"),t.mbedresponse&&t.mbedresponse.result&&t.mbedresponse.result.exception&&e.log(t.mbedresponse.result.exception),n(null))}),(t=>(e.log(`waiting ${o/1e3|0}s for C++ build...`),setTimeout(c,o),null)))};c()})))))).then((e=>(t.hideLoading(),{hex:e&&e.split(/\r?\n/)}))))).finally((()=>{t.hideLoading()}))}(s)),n[s.sha]}function o(t,n,i,s,r=10){return t.cacheStoreAsync(i,s).then((()=>t.cacheGetAsync(n))).then((s=>{let o;try{o=JSON.parse(s||"[]")}catch(e){console.error("invalid cache entry, clearing entry"),o=[]}o=o.filter((e=>e!=i)),o.unshift(i);let a=o.slice(r);return o=o.slice(0,r),e.U.promiseMapAll(a,(e=>t.cacheStoreAsync(e,"[]"))).then((()=>t.cacheStoreAsync(n,JSON.stringify(o))))}))}function a(e,t,n){return e.cacheGetAsync(t).then((i=>{let s;try{s=JSON.parse(i||"[]")}catch(n){return console.error("invalid cache entry, clearing entry"),e.cacheStoreAsync(t,"[]")}return s[0]!=n?(s=s.filter((e=>e!=n)),s.unshift(n),e.cacheStoreAsync(t,JSON.stringify(s))):null}))}t.showLoading=e=>{},t.hideLoading=()=>{},t.storeWithLimitAsync=o,t.recordGetAsync=a,t.getHexInfoAsync=function(t,n,i){if(!n.sha)return Promise.resolve(null);const l=s[n.sha];if(l)return Promise.resolve(l);e.debug("get hex info: "+n.sha);let c="hex-"+n.sha;return t.cacheGetAsync(c).then((i=>{let s;try{s=i?JSON.parse(i):null}catch(e){console.log("invalid cache entry, clearing entry"),s=null}return s&&s.hex?(e.debug("cache hit, size="+i.length),s.hex=function(t){let n=[];for(let i=0;i<t.length;i++){let s=/^([@!])(....)$/.exec(t[i]);if(!s){n.push(t[i]);continue}let r=parseInt(s[2],16),o=t[++i],a="";if("@"==s[1]){a="";let e=parseInt(o,16);for(;e-- >0;)a+="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"}else a=ts.pxtc.decodeBase64(o);e.Util.assert(a.length>0),e.Util.assert(a.length%16==0);for(let e=0;e<a.length;){let t=[16,r>>8&255,255&r,0];r+=16;for(let n=0;n<16;++n)t.push(a.charCodeAt(e++));let i=0;for(let e=0;e<t.length;++e)i+=t[e];t.push(255&-i);let s=":";for(let e=0;e<t.length;++e){let n=255&t[e];n<=15&&(s+="0"),s+=n.toString(16)}n.push(s.toUpperCase())}}return n}(s.hex),a(t,"hex-keys",c).then((()=>s))):r(n).then((e=>{let n=e.hex;e.hex=function(e){let t=[],n=0;for(let i=0;i<e.length;i+=n){let s=-1,r="";n=0;let o=!1;for(;n<500;){let a=/^:10(....)00(.{32})(..)$/.exec(e[i+n]);if(!a)break;let l=a[2],c=/^0+$/.test(l),u=parseInt(a[1],16);if(-1==s)o=c,t.push((o?"@":"!")+a[1]),s=u-16;else{if(c!=o)break;if(s+16!=u)break}o||(r+=l),s=u,n++}if(0==n)t.push(e[i]),n=1;else if(o)t.push(n.toString(16));else{let e="";for(let t=0;t<r.length;t+=2)e+=String.fromCharCode(parseInt(r.slice(t,t+2),16));t.push(ts.pxtc.encodeBase64(e))}}return t}(e.hex);let i=JSON.stringify(e);return e.hex=n,o(t,"hex-keys",c,i).then((()=>e))})).catch((t=>(e.reportException(t,{sha:n.sha}),Promise.resolve(null))))})).then((e=>(e&&(Object.keys(s).length>20&&(s={}),s[n.sha]=e),e)))}}(e.hexloader||(e.hexloader={}))}(pxt||(pxt={})),function(e){!function(t){t.KEY_VARIABLE="CROWDIN_KEY",t.testMode=!1,t.setTestMode=function(){e.crowdin.testMode=!0,e.log("CROWDIN TEST MODE - files will NOT be uploaded")},t.inContextLoadAsync=function(t){const n=document.createElement("input");n.type="text",n.setAttribute("class","hidden"),n.value=t;let i=new Promise(((i,s)=>{const r=new MutationObserver((()=>{if(t==n.value)return;const s=e.Util.rlf(n.value);n.remove(),r.disconnect(),i(s)}));r.observe(n,{attributes:!0})}));return document.body.appendChild(n),i}}(e.crowdin||(e.crowdin={}))}(pxt||(pxt={})),function(e){!function(t){function n(e){return e?e.split(/\r?\n/):[]}function i(e,t,i={}){i.ignoreWhitespace&&(e=e.replace(/[\r\n]+$/,""),t=t.replace(/[\r\n]+$/,""));const s=n(e),r=n(t),o=Math.min(i.maxDiffSize||1024,s.length+r.length);if(0==o)return[];const a=s.length>65520?Uint32Array:Uint16Array,l={};let c=0;const u=h(s),d=h(r);function h(e){const t=new a(e.length);let n=0;for(let s of e)i.ignoreWhitespace&&(s=s.replace(/\s+$/g,"").replace(/^\s+/g,"")),l.hasOwnProperty(s)?t[n]=l[s]:(++c,t[n]=c,l[s]=c),n++;return t}const p=new a(2*o+1);let f=-1;for(let e=0;e<=o;e++)null!=E(e,p)&&(f=e);if(-1==f)return null;const m=[];let g=null;for(let e=0;e<=f;e++){const t=m.length?m[m.length-1].slice(0):new a(2*f+1);if(m.push(t),g=E(e,t),null!=g)break}const b=[];let y=g;for(let e=m.length-1;e>=0;e--){const t=m[e];let n=0,i=0;y==-e||y!=e&&t[o+y-1]<t[o+y+1]?(i=y+1,n=t[o+i]):(i=y-1,n=t[o+i]+1);let a=n-y;for(let e=t[o+y]-n-1;e>=0;--e)b.push(" "+r[a+e]);i==y-1?b.push("- "+s[n-1]):a>0&&b.push("+ "+r[a-1]),y=i}if(b.reverse(),i.context==1/0||i.full)return b;let v=1,w=1,k=0;const x=[],A=i.context||3;for(;k<b.length;){let e=k;for(;e<b.length&&" "==b[e][0];)e++;if(e==b.length)break;const t=e-A,n=t-k;n>0&&(v+=n,w+=n,k=t);const i=x.length,s=v,r=w;x.push("@@");let o=k,a=0;for(;o<b.length;){if(" "==b[o][0]){if(a++,a>2*A+2){o-=A+2;break}}else a=0;o++}for(;k<o;){x.push(b[k]);switch(b[k][0]){case"-":v++;break;case"+":w++;break;case" ":v++,w++}k++}x[i]=`@@ -${s},${v-s} +${r},${w-r} @@`}return x;function E(e,t){for(let n=-e;n<=e;n+=2){let i=0;i=n==-e||n!=e&&t[o+n-1]<t[o+n+1]?t[o+n+1]:t[o+n-1]+1;let s=i-n;for(;i<u.length&&s<d.length&&u[i]==d[s];)i++,s++;if(t[o+n]=i,i>=u.length&&s>=d.length)return n}return null}}function s(e){return n(e).map((e=>e.replace(/;\s*$/,""))).join("\n")}function r(e){const t=/^@@ -(\d+),(\d+) \+(\d+),(\d+)/.exec(e);return t&&{oldStart:parseInt(t[1])-1,oldLength:parseInt(t[2]),newStart:parseInt(t[3])-1,newLength:parseInt(t[4])}}t.toLines=n,t.compute=i,t.diff3=function(t,s,r,o,a){const l=g(t),c=g(r);if(!l||!c)return;const u=n(t),d=n(r);let h=0,p=[],f=0,m=0;for(let t=0;t<l.length-1;)if(l[t]==f&&c[t]==m)p.push(u[f]),f++,m++,t++;else{let n=!0,i=!0,s=t;for(;s<l.length&&(l[s]!=f+s-t&&(n=!1),c[s]!=m+s-t&&(i=!1),null==l[s]||null==c[s]);)s++;if(e.U.assert(s<l.length),n)for(;m<c[s];)p.push(d[m++]);else if(i)for(;f<l[s];)p.push(u[f++]);else if(u.slice(f,l[s]).join("\n")==d.slice(m,c[s]).join("\n"))for(;f<l[s];)p.push(u[f++]);else{for(h++,p.push("<<<<<<< "+o);f<l[s];)p.push(u[f++]);for(p.push("=======");m<c[s];)p.push(d[m++]);p.push(">>>>>>> "+a)}t=s,f=l[s],m=c[s]}return{merged:p.join("\n"),numConflicts:h};function g(t){const n=i(s,t,{context:1/0});if(!n)return;const r=[];let o=0,a=0;for(let t of n)"+"==t[0]?o++:"-"==t[0]?(r[a]=null,a++):" "==t[0]?(r[a]=o,o++,a++):e.U.oops();return r.push(o+1),r}},t.removeTrailingSemiColumns=s,t.split=function(e,t){const n=e.split(/-{10,}/,2);if(n.length<2)return{fileA:e,fileB:void 0};let i=n[0].replace(/\n$/,""),r=n[1].replace(/^\n/,"");return t&&t.removeTrailingSemiColumns&&(i=s(i),r=s(r)),{fileA:i,fileB:r}},t.parseDiffMarker=r,t.render=function(t,n,s={}){const o=i(t,n,s);if(!o)return e.dom.el("div",null,pxtc.Util.lf("Too many differences to render diff."));const a={"@":"diff-marker"," ":"diff-unchanged","+":"diff-added","-":"diff-removed"};let l=0,c=0,u="";const d=e.dom.el("tbody"),h=e.dom.el("table",{class:"diffview "+(s.update?"update":"")},d);let p=null;return o.forEach(((t,n)=>{const h=r(t);h?(l=h.oldStart,c=h.newStart):("+"!=t[0]&&l++,"-"!=t[0]&&c++);const f=o[n+1]?o[n+1][0]:"",m=o[n+2]?o[n+2][0]:"",g=t.slice(2);let b=e.dom.el("code",null,g);if(p)b=p,p=null;else if(!("-"!=t[0]||" "!=u&&"@"!=u||"+"!=f||" "!=m&&"@"!=m&&""!=m)){const s=function(t,n){const s=i(t.split("").join("\n"),n.split("").join("\n"),{context:1/0});if(!s)return{a:e.dom.el("div",{class:"inline-diff"},e.dom.el("code",null,t)),b:e.dom.el("div",{class:"inline-diff"},e.dom.el("code",null,n))};const r=[],o=[];for(let t=0;t<s.length;){let n=t;const i=s[t][0];for(;s[n]&&s[n][0]==i;)n++;const a=s.slice(t,n).map((e=>e.slice(2))).join("");" "==i?(r.push(e.dom.el("code",{class:"ch-common"},a)),o.push(e.dom.el("code",{class:"ch-common"},a))):"-"==i?r.push(e.dom.el("code",{class:"ch-removed"},a)):"+"==i?o.push(e.dom.el("code",{class:"ch-added"},a)):e.Util.oops(),t=n}return{a:e.dom.el("div",{class:"inline-diff"},r),b:e.dom.el("div",{class:"inline-diff"},o)}}(t.slice(2),o[n+1].slice(2));b=s.a,p=s.b}if(u=t[0],s.hideMarkerLine&&"@"==u||s.hideRemoved&&"-"==u)return;const y="@"==u,v=`${a[u]}`;d.appendChild(e.dom.el("tr",{class:v},[!s.hideLineNumbers&&e.dom.el("td",{class:"line-a","data-content":l}),!s.hideLineNumbers&&e.dom.el("td",{class:"line-b","data-content":c}),y&&e.dom.el("td",{colspan:2,class:"change"},e.dom.el("code",null,t)),!s.hideMarker&&!y&&e.dom.el("td",{class:"marker","data-content":u}),!y&&e.dom.el("td",{class:"change"},b)]))})),h},t.resolveMergeConflictMarker=function(t,n,i,s){let r=e.diff.toLines(t),o=n;for(;o<r.length&&!/^<<<<<<<[^<]/.test(r[o]);)o++;let a=o+1;for(;a<r.length&&!/^=======$/.test(r[a]);)a++;let l=a+1;for(;l<r.length&&!/^>>>>>>>[^>]/.test(r[l]);)l++;if(l>=r.length)return e.debug(`diff marker mistmatch: ${r.length} -> ${o} ${a} ${l}`),t;if(r[o]=void 0,r[a]=void 0,r[l]=void 0,!i)for(let e=o;e<=a;++e)r[e]=void 0;if(!s)for(let e=a;e<=l;++e)r[e]=void 0;return r.filter((e=>void 0!==e)).join("\n")},t.mergeDiff3Config=function(t,n,i){let s=e.Util.jsonTryParse(t),r=e.Util.jsonTryParse(n),o=e.Util.jsonTryParse(i);if(s&&!o)return t;if(!s)return i||n;if(!r&&o&&(r=o),!s||!r||!o)return;delete s.installedVersion,delete r.installedVersion,delete o.installedVersion;const a={},l=e.U.unique(Object.keys(r).concat(Object.keys(s)).concat(Object.keys(o)),(e=>e));for(const t of l){const n=s[t],i=r[t],l=o[t];if(JSON.stringify(n)==JSON.stringify(l))void 0!==n&&(a[t]=n);else switch(t){case"name":a[t]=c(n,i,l);break;case"version":a[t]=e.semver.strcmp(n,l)>0?n:l;break;case"languageRestriction":case"preferredEditor":case"targetVersion":a[t]=n;break;case"public":a[t]=n&&l;break;case"files":case"testFiles":{const e=u(n||[],i||[],l||[]);if(!e)return;a[t]=e.length?e:void 0;break}case"dependencies":case"testDependencies":{const e=d(n||{},i||{},l||{});if(Object.keys(e).length)return;a[t]=e;break}case"description":if(n&&!l)a[t]=n;else{if(n||!l)return;a[t]=l}break;default:return}}return e.Package.stringifyConfig(a);function c(e,t,n){return e==t?n:n==t?e:e==lf("Untitled")?n:e}function u(t,n,i){const s=[],r=e.U.unique(n.concat(t).concat(i),(e=>e));for(const e of r){const r=t.indexOf(e)>-1,o=i.indexOf(e)>-1,a=n.indexOf(e)>-1;r==o||o==a?r&&s.push(e):o&&s.push(e)}return s}function d(t,n,i){const s={},r=e.U.unique(Object.keys(n).concat(Object.keys(t)).concat(Object.keys(i)),(e=>e));for(const o of r){const r=t[o],a=i[o],l=n[o];if(r==a)r&&(s[o]=r);else{const t=e.github.parseRepoId(r),n=e.github.parseRepoId(a);if(t&&n&&e.semver.tryParse(t.tag)&&e.semver.tryParse(n.tag)&&t.owner&&t.project&&t.owner==n.owner&&t.project==n.project){const i=e.semver.strcmp(t.tag,n.tag)>0?t.tag:n.tag;s[o]=`github:${t.owner}/${t.project}#${i}`}else a==l?r&&(s[o]=r):a&&(s[o]=a)}}return s}},t.hasMergeConflictMarker=function(e){return e&&/^(<<<<<<<[^<]|>>>>>>>[^>])/m.test(e)},t.reconstructConfig=function(t,n,i,s){let r={},o=i.tree.tree.map((e=>e.path)).filter((e=>/\.(ts|blocks|md|jres|asm|json)$/.test(e))).filter((t=>t!=e.CONFIG_NAME));return t.fileName&&(o=o.filter((e=>0===e.indexOf(t.fileName))).map((e=>e.slice(t.fileName.length+1)))),o.find((e=>/\.ts$/.test(e)))||(s.config.files.filter((e=>o.indexOf(e)<0)).forEach((e=>{o.push(e),n[e]=s.files[e]})),e.Util.jsonCopyFrom(r,s.config.dependencies)),Object.keys(r).length||(r[e.appTarget.corepkg]="*"),{name:"",files:o,dependencies:r,preferredEditor:o.find((e=>/.blocks$/.test(e)))?e.BLOCKS_PROJECT_NAME:e.JAVASCRIPT_PROJECT_NAME}}}(e.diff||(e.diff={}))}(pxt||(pxt={})),function(e){!function(t){t.extractSharedIdFromPostUrl=function(t){return e.Util.httpGetJsonAsync(t+".json").then((t=>t.post_stream&&t.post_stream.posts&&t.post_stream.posts[0]&&t.post_stream.posts[0].link_counts.map((t=>e.Cloud.parseScriptId(t.url))).filter((e=>!!e))[0]))},t.topicsByTag=function(t,n){const i=`${t=t.replace(/\/$/,"")}/tag/${n}.json`;return e.Util.httpGetJsonAsync(i).then((n=>{const i=e.Util.toDictionary(n.users,(e=>e.id.toString()));return n.topic_list.topics.map((e=>({id:e.id,title:e.title,url:`${t}/t/${e.slug}/${e.id}`,imageUrl:e.image_url,author:i[e.posters[0].user_id].username,cardType:"forumUrl"})))}))}}(e.discourse||(e.discourse={}))}(pxt||(pxt={})),function(e){!function(t){var n=pxtc.Util;let i,s={},r={};const o="\x3c!-- @CMD@ @ARGS@ --\x3e";let a={parent:o,short:o,description:"\x3c!-- desc --\x3e",activities:"\x3c!-- activities --\x3e",explicitHints:"\x3c!-- hints --\x3e",flyoutOnly:"\x3c!-- flyout --\x3e",hideIteration:"\x3c!-- iter --\x3e",codeStart:"\x3c!-- start --\x3e",codeStop:"\x3c!-- stop --\x3e",autoOpen:"\x3c!-- autoOpen --\x3e",autoexpandOff:"\x3c!-- autoexpandOff --\x3e",preferredEditor:"\x3c!-- preferredEditor --\x3e"};function l(e,t,n){return e.split(t).join(n)}function c(e){return e=l(e,"&","&amp;"),e=l(e,"<","&lt;"),e=l(e,">","&gt;"),e=l(e,'"',"&quot;"),e=l(e,"'","&#39;")}function u(e){return e?c(e.replace(/\&([#a-z0-9A-Z]+);/g,((e,t)=>{switch(t){case"amp":return"&";case"lt":return"<";case"gt":return">";case"quot":return'"';default:return"#"==t[0]?String.fromCharCode(parseInt(t.slice(1))):e}}))):e}t.htmlQuote=c,t.html2Quote=u;const d=[{rx:/^vimeo\.com\/(\d+)/i,cmd:"### @vimeo $1"},{rx:/^(www\.youtube\.com\/watch\?v=|youtu\.be\/)([\w\-]+(\#t=([0-9]+m[0-9]+s|[0-9]+m|[0-9]+s))?)/i,cmd:"### @youtube $2"}];t.requireMarked=()=>"undefined"!=typeof marked?marked:"undefined"!=typeof require?require("marked"):void 0,t.requireDOMSanitizer=()=>"undefined"!=typeof DOMPurify?DOMPurify.sanitize:"undefined"!=typeof require?require("DOMPurify").sanitize:void 0;const h=e=>`<div class='ui negative message'>${c(e)}</div>`;function p(e){let t=n.clone(s),i=n.clone(r),o=n.clone(a),l={},c={},d=e.params,p=e.theme;e.boxes=t,e.macros=i,e.settings=o,e.html=e.html.replace(/<aside\s+([^<>]+)>([^]*?)<\/aside>/g,((e,n,s)=>{let r=function(e){let t={};for(;e.trim();){let n=/\s*([^=\s]+)=("([^"]*)"|'([^']*)'|(\S*))/.exec(e);if(n){let e=n[3]||n[4]||n[5]||"";t[n[1].toLowerCase()]=e}else n=/^\s*(\S+)/.exec(e),t[n[1]]="true";e=e.slice(n[0].length)}return t}(n),a=r["data-name"]||r.id;return a?(/box/.test(r.class)?t[a]=s:/aside/.test(r.class)?t[a]=`\x3c!-- BEGIN-ASIDE ${a} --\x3e${s}\x3c!-- END-ASIDE --\x3e`:/setting/.test(r.class)?o[a]=s:/menu/.test(r.class)?l[a]=s:/toc/.test(r.class)?c[a]=s:i[a]=s,`\x3c!-- macro ${a} --\x3e`):h("id or data-name missing on macro")}));let f=(e,t)=>{let n=l.item,i={NAME:e.name};if(e.subitems)n=l["toc-dropdown"]?l["toc-dropdown"]:0==t?l["top-dropdown"]:l["inner-dropdown"],i.ITEMS=e.subitems.map((e=>f(e,t+1))).join("\n");else{if(/^-+$/.test(e.name)&&(n=l.divider),e.path&&!/^(https?:|\/)/.test(e.path))return h("Invalid link: "+e.path);i.LINK=e.path}return g(n,i,["ITEMS"])},m=[{name:lf("Docs"),href:"/docs"}];const b=e.TOC||p.TOC||[];let y=[],v=t=>{for(let e of t.subitems||[])if(v(e))return y.push(t),!0;return!(!e.filepath||!t.path||0!=e.filepath.indexOf(t.path))&&(y.push(t),!0)};b.forEach(v);let w=(t,n)=>{let i=c.item,s={NAME:t.name};return t.path&&!/^(https?:|\/)/.test(t.path)?h("Invalid link: "+t.path):(/^\//.test(t.path)&&e.versionPath&&(t.path=`/${e.versionPath}${t.path}`),s.LINK=t.path,y.indexOf(t)>=0?(s.ACTIVE="active",s.EXPANDED="true",m.push({name:t.name,href:t.path})):s.EXPANDED="false",t.subitems&&t.subitems.length>0?(i=c["toc-dropdown"]?""!==t.name?c["toc-dropdown"]:c["toc-dropdown-noLink"]:0==n?""!==t.name?c["top-dropdown"]:c["top-dropdown-noHeading"]:1==n?c["inner-dropdown"]:c["nested-dropdown"],s.ITEMS=t.subitems.map((e=>w(e,n+1))).join("\n")):/^-+$/.test(t.name)&&(i=c.divider),g(i,s,["ITEMS"]))};d.menu=(p.docMenu||[]).map((e=>f(e,0))).join("\n"),d.TOC=b.map((e=>w(e,0))).join("\n"),p.appStoreID&&(d.appstoremeta=`<meta name="apple-itunes-app" content="app-id=${n.htmlEscape(p.appStoreID)}"/>`);let k="";m.length>1&&(k=`\n <nav class="ui breadcrumb" aria-label="${lf("Breadcrumb")}">\n ${m.map(((e,t)=>`<a class="${t==m.length-1?"active":""} section"\n href="${u(e.href)}" aria-current="${t==m.length-1?"page":""}">${u(e.name)}</a>`)).join('<i class="right chevron icon divider"></i>')}\n </nav>`),d.breadcrumb=k,p.boardName&&(d.boardname=u(p.boardName)),p.boardNickname&&(d.boardnickname=u(p.boardNickname)),p.driveDisplayName&&(d.drivename=u(p.driveDisplayName)),p.homeUrl&&(d.homeurl=u(p.homeUrl)),d.targetid=p.id||"???",d.targetname=p.name||"Microsoft MakeCode",d.docsheader=p.docsHeader||"Documentation",d.orgtitle="MakeCode";const x=p.docsLogo&&n.htmlEscape(p.docsLogo),A=(p.organizationWideLogo||p.organizationLogo)&&n.htmlEscape(p.organizationWideLogo||p.organizationLogo),E=p.organizationLogo&&n.htmlEscape(p.organizationLogo);d.targetlogo=x?`<img aria-hidden="true" role="presentation" class="ui ${p.logoWide?"small":"mini"} image" src="${x}" />`:"",d.orglogo=A?`<img aria-hidden="true" role="presentation" class="ui image" src="${A}" />`:"",d.orglogomobile=E?`<img aria-hidden="true" role="presentation" class="ui image" src="${E}" />`:"";let T=e.ghEditURLs||[];if(T.length){let e='<p style="margin-top:1em">\n',t=lf("Edit this page on GitHub");for(let n of T)e+=`<a href="${n}"><i class="write icon"></i>${t}</a><br>\n`,t=lf("Edit template of this page on GitHub");e+="</p>\n",d.github=e}else d.github="";const S=`\n <a href="#maincontent" class="ui item link" tabindex="0" role="menuitem">${lf("Skip to main content")}</a>\n `;d.accMenu=S;const C=lf("Print this page"),I=`\n <button id="printbtn" class="circular ui icon right floated button hideprint" title="${C}" aria-label="${C}">\n <i class="icon print"></i>\n </button>\n `;d.printBtn=I;const _=`\n <a id="togglesidebar" class="launch icon item" tabindex="0" title="Side menu" aria-label="${lf("Side menu")}" role="menuitem" aria-expanded="false">\n <i class="content icon"></i>\n </a>\n `;d.sidebarToggle=_;const P=["tocsearch1","tocsearch2"].map((e=>`\n <input type="search" name="q" placeholder="${lf("Search...")}" aria-label="${lf("Search Documentation")}">\n <i onclick="document.getElementById('${e}').submit();" tabindex="0" class="search link icon" aria-label="${lf("Search")}" role="button"></i>\n `));d.searchBar1=P[0],d.searchBar2=P[1];let U="";p.accentColor&&(U+=`\n.ui.accent { color: ${p.accentColor}; }\n.ui.inverted.accent { background: ${p.accentColor}; }\n`),d.targetstyle=U,d.tocclass=p.lightToc?"lighttoc":"inverted";for(let e of Object.keys(p)){let t=p[e];void 0===d[e]&&"string"==typeof t&&(d[e]=t)}e.finish=()=>g(e.html,d,["body","menu","accMenu","TOC","prev","next","printBtn","breadcrumb","targetlogo","orglogo","orglogomobile","github","JSON","appstoremeta","sidebarToggle","searchBar1","searchBar2"])}function f(e){e.image=function(e,t,n){var i,s;if(e.startsWith("youtube:")){return'<div class="tutorial-video-embed"><iframe class="yt-embed" src="https://www.youtube.com/embed/'+e.split(":").pop()+'" title="'+n+'" frameborder="0" allowFullScreen allow="autoplay; picture-in-picture"></iframe></div>'}if(e.startsWith("azuremedia:")){let t=e.split(":")[1];const n=t.split("?");let r,o;if(n[1]){t=n[0];const e=n[1];r=null===(i=/start(?:time)?=(\d+)/i.exec(e))||void 0===i?void 0:i[1],o=null===(s=/end(?:time)?=(\d+)/i.exec(e))||void 0===s?void 0:s[1]}const a=new URL(`https://makecodeprodmediaeastus-usea.streaming.media.azure.net/${t}/manifest(format=mpd-time-csf).mpd`);return r&&(a.hash=`t=${r}`,a.searchParams.append("startTime",r)),o&&a.searchParams.append("endTime",o),`<div class="tutorial-video-embed"><video class="ams-embed" controls src="${a.toString()}" /></div>`}{let i='<img class="ui image" src="'+e+'" alt="'+n+'"';return t&&(i+=' title="'+t+'"'),i+=' loading="lazy"',i+=this.options.xhtml?"/>":">",i}},e.listitem=function(e){const t=/^\s*\[( |x)\]/i.exec(e);return t?`<li class="${" "==t[1]?"unchecked":"checked"}">`+e.slice(t[0].length)+"</li>\n":"<li>"+e+"</li>\n"},e.heading=function(e,t,n){let i=/(.*)#([\w\-]+)\s*$/.exec(e),s="";return i&&(e=i[1],s=i[2]),e&&(e=e.replace(/@(fullscreen|unplugged|showdialog|showhint)/gi,"")),e.match(/\{([\s\S]+)\}/)&&(e=e.match(/\{([\s\S]+)\}/)[1].trim()),""===s&&(s=e.toLowerCase().replace(/[^\w]+/g,"-")),`<h${t} id="${this.options.headerPrefix}${s}">${e}</h${t}>`}}function m(e,t){return e.replace(/<!--\s*@(ifn?def)\s+(\w+)\s*-->([^]*?)<!--\s*@endif\s*-->/g,((e,n,i,s)=>"ifdef"==n&&t[i]||"ifndef"==n&&!t[i]?`\x3c!-- ${n} ${i} --\x3e${s}\x3c!-- endif --\x3e`:`\x3c!-- ${n} ${i} endif --\x3e`))}function g(e,t,i=[]){return e?e.replace(/@(\w+)@/g,((e,s)=>{let r=n.lookup(t,s)||"";return r+="",i.indexOf(s)<0&&(r=u(r)),r})):""}t.prepTemplate=p,t.setupRenderer=f,t.renderConditionalMacros=m,t.renderMarkdown=function(e){let s=!0;e.pubinfo||(s=!1,e.pubinfo={});let r=e.pubinfo;if(e.theme||(e.theme={}),delete e.pubinfo.private,r.time){let e=parseInt(r.time);r.timems||(r.timems=1e3*e+""),r.humantime||(r.humantime=n.isoTime(e))}r.name&&(r.dirname=r.name.replace(/[^A-Za-z0-9_]/g,"-"),r.title=r.name),s&&(r.JSON=JSON.stringify(r,null,4).replace(/</g,"\\u003c"));let o=e.template;o=o.replace(/<!--\s*@include\s+(\S+)\s*-->/g,((t,n)=>"\x3c!-- include "+n+" --\x3e\n"+((e.theme.htmlDocIncludes||{})[n]||"")+"\n\x3c!-- end include --\x3e\n")),o=m(o,r),e.locale&&(o=y(o,e.locale).text);let a={html:o,theme:e.theme,filepath:e.filepath,versionPath:e.versionPath,ghEditURLs:e.ghEditURLs,params:r,TOC:e.TOC};p(a),i||(i=t.requireMarked());let l=new i.Renderer;f(l);const c=l.link;l.link=function(e,t,n){const i=new RegExp("^[/#]").test(e),s=i?"":"_blank";i&&a.versionPath&&(e=`/${a.versionPath}${e}`);return c.call(l,e,t,n).replace(/^<a /,`<a ${s?`target="${s}"`:""} rel="nofollow noopener" `)};let b=t.requireDOMSanitizer();i.setOptions({renderer:l,gfm:!0,tables:!0,breaks:!1,pedantic:!1,sanitize:!0,sanitizer:b,smartLists:!0,smartypants:!0});let v=e.markdown;e.repo&&(v+=`\n\`\`\`package\n${e.repo.name.replace(/^pxt-/,"")}=github:${e.repo.fullName}#${e.repo.tag||"master"}\n\`\`\`\n`),v=v.replace(/^\s*https?:\/\/(\S+)\s*$/gm,((e,t)=>{for(let e of d){let n=e.rx.exec(t);if(n)return e.cmd.replace(/\$(\d+)/g,((e,t)=>n[parseInt(t)]||""))+"\n"}return e})),v=v.replace(/@([a-z]+)@/gi,((t,i)=>{let s=r[i];return!s&&e.throwOnError&&n.userError(`unknown macro ${i}`),s||"unknown macro"}));let w=i(v);w=w.replace(/&lt;br\s*\/&gt;/gi,"<br/>"),w=w.replace(/(<img [^>]* src=")\/docs\/static\/([^">]+)"/g,((e,t,n)=>t+"/static/"+n+'"'));let k="",x=0;function A(e,t,n){let i=n;return e<=x&&(i=k+i,k="",x=0),i}if(w=w.replace(/<h(\d)[^>]+>\s*([~@])?\s*(.*?)<\/h\d>/g,((t,i,s,o)=>{let l=/^(\w+)\s+(.*)/.exec(o),c=l?l[1]:o,d=l?l[2]:"";if(d=u(d),c=u(c),i=parseInt(i),s){if("@"==s){let t=n.lookup(a.settings,c);if(null!=t)r[c]=d;else if(t=n.lookup(a.macros,c),null==t)return e.throwOnError&&n.userError(`Unknown command: @${c}`),h(`Unknown command: @${c}`);return A(i,0,g(t,{ARGS:d,CMD:c},["ARGS","CMD"]))}{if(!c){let e=k;return k="",e}let t=n.lookup(a.boxes,c);if(t){let e=t.split("@BODY@"),n=A(i,0,e[0].replace("@ARGS@",d));k=e[1];let s=t.match(/data-[^>\s]+/gi);return s&&s.indexOf("data-inferred")>=0&&(x=i),n}return e.throwOnError&&n.userError(`Unknown box: ~ ${c}`),h(`Unknown box: ~ ${c}`)}}return A(i,0,t)})),k&&(w+=k),!r.title){let e=/<h1[^<>]*>([^<>]+)<\/h1>/.exec(w);e&&(r.title=u(e[1]))}if(!r.description){let e=/<p>([^]+?)<\/p>/.exec(w);e&&(r.description=u(e[1]))}const E=/<div class="ui embed mdvid"[^<>]+?data-placeholder="([^"]+)"[^>]*\/?>/i.exec(w)||/<img class="ui [^"]*image" src="([^"]+)"[^>]*\/?>/i.exec(w);E&&(r.cardLogo=u(E[1])),r.twitter=u(e.theme.twitter||"@msmakecode");let T={main:""};w=w.replace(/<!-- BEGIN-ASIDE (\S+) -->([^]*?)<!-- END-ASIDE -->/g,((e,t,i)=>{let s=n.lookup(T,t);return T[t]=(s||"")+i,"\x3c!-- aside --\x3e"})),w=w.replace(/\n<\/code>/g,"</code>"),T.main=w,w="";for(let e of Object.keys(T))w+=(S=e+"-container",C=T[e],g(a.boxes[S]||"@BODY@",{BODY:C},["BODY"]));var S,C;r.body=w,r.name=r.title||"";for(let t of Object.keys(e.theme)){let n=e.theme[t];"string"==typeof n&&(r["theme_"+t]=n)}return a.finish()},t.embedUrl=function(e,t,n,i){return`<div style="position:relative;height:0;padding-bottom:70%;overflow:hidden;"><iframe style="position:absolute;top:0;left:0;width:100%;height:100%;" src="${`${e}#${t}:${n}`}" frameborder="0" sandbox="allow-popups allow-forms allow-scripts allow-same-origin"></iframe></div>`},t.runUrl=function(e,t,n){return`<div style="position:relative;height:0;padding-bottom:${t};overflow:hidden;"><iframe style="position:absolute;top:0;left:0;width:100%;height:100%;" src="${e}?id=${encodeURIComponent(n)}" allowfullscreen="allowfullscreen" sandbox="allow-popups allow-forms allow-scripts allow-same-origin" frameborder="0"></iframe></div>`},t.codeEmbedUrl=function(e,t,n){const i=`${e}---codeembed#pub:${t}`;return`<div style="position:relative;height:calc(${n=Math.ceil(n||300)}px + 5em);width:100%;overflow:hidden;"><iframe style="position:absolute;top:0;left:0;width:100%;height:100%;" src="${i}" allowfullscreen="allowfullscreen" frameborder="0" sandbox="allow-scripts allow-same-origin"></iframe></div>`};const b={b:1,strong:1,em:1};function y(e,t){const i={};function s(e){let s=/^(\s*)([^]*?)(\s*)$/.exec(e),r=s[2].replace(/\s+/g," ");if(""==r||/^((IE=edge,.*|width=device-width.*|(https?:\/\/|\/)[\w@\/\.]+|@[\-\w]+@|\{[^\{\}]+\}|[^a-zA-Z]*|(&nbsp;)+)\s*)+$/.test(r))return null;let o=n.lookup(t,r);return o?r=o:i[r]="",s[1]+r+s[3]}function r(e){return e.replace(/&llt;/g,"<").replace(/&ggt;/g,">")}return{text:e=(e=(e=(e="<start>"+(e=e.replace(/<([\/\w]+)([^<>]*)>/g,((e,t,n)=>{let i=t.replace(/^\//,"").toLowerCase();return 1===b[i]?"&llt;"+t+n+"&ggt;":e})))).replace(/(<([\/\w]+)([^<>]*)>)([^<>]+)/g,((e,t,n,i,o)=>{if("script"==n||"style"==n)return r(e);let a=s(r(o));return null==a?r(e):t+a}))).replace(/(<[^<>]*)(content|placeholder|alt|title)="([^"]+)"/g,((e,t,n,i)=>null==s(i)?e:t+n+'="'+i.replace(/"/g,"''")+'"'))).replace(/^<start>/g,""),missing:i}}function v(e,t){if(e.id==t)return e;for(let n of e.children){let e=v(n,t);if(e)return e}return null}function w(e,t){let n=0,i=[{level:0,id:"",title:"",start:n,text:"",children:[]}],s=(e=e.replace(/\r/g,"")).split(/\n/),r={};for(let e of s){let s=/^\s*(#+)\s*(.*?)(#(\S+)\s*)?$/.exec(e),o=null;if(t&&s)if(s[4])if(r[s[4]])s=null;else{o=v(t,s[4]);let e=t=>{t.id&&(r[t.id]=!0),t.children.forEach(e)};o&&e(o)}else s=null;if(s){let r={level:t?1:s[1].length,title:s[2].trim(),id:s[4]||"",start:n,text:"",children:[]};if(o){e="";for(let t=0;t<o.level;++t)e+="#";e+=" ",e+=r.title||o.title,e+=" #"+r.id}for(;i[i.length-1].level>=r.level;)i.pop();i[i.length-1].children.push(r),i.push(r)}i[i.length-1].text+=e+"\n",n++}return i[0]}t.translate=y,t.buildTOC=function(n){if(!n)return null;const i=e.docs.requireMarked(),s=t.requireDOMSanitizer(),r={renderer:new i.Renderer,gfm:!0,tables:!1,breaks:!1,pedantic:!1,sanitize:!0,sanitizer:s,smartLists:!1,smartypants:!1};let o={name:"dummy",subitems:[]},a=[];a.push(o);let l=i.lexer(n,r),c=!1;l.forEach((e=>{switch(e.type){case"heading":e.depth;break;case"list_start":break;case"list_item_start":case"loose_item_start":c=!0;let t={name:"",path:"",subitems:[]};return void a.push(t);case"text":let n=a[a.length-1];e.text.indexOf("[")>=0?e.text.replace(/\[(.*?)\]\((.*?)\)/i,(function(e,t,i){n.name=t,n.path=i.replace(".md","")})):c&&(n.name=e.text);break;case"list_item_end":case"loose_item_end":let i=a.pop();a[a.length-1].subitems.push(i)}c=!1}));let u=o.subitems;return u&&0!=u.length?u:null},t.visitTOC=function(e,t){e.forEach((function(e){t(e),e.subitems&&e.subitems.forEach(t)}))};let k=!1;function x(e,t){if(k||function(){function e(e,t,n){let i=x(e,t).trim();if(i!=(n=n.trim()))throw console.log(`*** Template:\n${e}\n*** Input:\n${t}\n*** Expected:\n${n}\n*** Output:\n${i}`),new Error("augment docs test fail")}k=!0;let t="\n# T0\n## Examples #ex\n### Example 1\nTEx1\n### Example 2 #ex2\nTEx2\n### Example 3\nTEx3\n\n## See also #also\nTAlso\n",n="\n# @extends\n# #ex2\nMy example\n## See Also These! #also\nMy links\n",i="\n# T0\n## Examples #ex\n### Example 1\nTEx1\n### Example 2 #ex2\nMy example\n### Example 3\nTEx3\n\n## See Also These! #also\nMy links\n",s="\n# @extends\n### #ex\nFoo\n#### Example 1\nEx1\n#### Example 2x #ex2\nEx2\n## See Also These! #also\nMy links\n",r="\n# T0\n## Examples #ex\nFoo\n#### Example 1\nEx1\n#### Example 2x #ex2\nEx2\n## See Also These! #also\nMy links\n";e(t,"",t),e(t," ",t),e(t,n,i),e(t,s,r)}(),!t)return e;let i=w(e,null),s=w(t,i),r={},o={};for(let e of s.children)n.assert(0==e.children.length),n.assert(!!e.id),r[e.id]=e.text;let a=e=>{e.id&&void 0!==r[e.id]&&(o[e.id]=!0,e.text=r[e.id],e.children=[]),e.children.forEach(a)};a(i);let l="",c=e=>{l+=e.text,e.children.forEach(c)};c(i);let u="",d=s.text.replace(/^\s*#+\s*@extends.*/gm,"").replace(/^\s*\n/gm,"");d.trim()&&(u+=d.trim()+"\n");for(let e of s.children)o[e.id]||(u+=e.text);return u&&(l+="## Couldn't apply replacement logic to:\n"+u),l}t.augmentDocs=x}(e.docs||(e.docs={}))}(pxt||(pxt={})),function(e){!function(e){e.el=function(e,t,n){const i=document.createElement(e);return t&&Object.keys(t).forEach((e=>i.setAttribute(e,t[e]+""))),function e(t){Array.isArray(t)?t.forEach((t=>e(t))):"string"==typeof t?i.appendChild(document.createTextNode(t)):t instanceof HTMLElement&&i.appendChild(t)}(n),i}}(e.dom||(e.dom={}))}(pxt||(pxt={})),function(e){!function(t){function n(e){const t=/```package\s+((.|\s)+?)\s*```/i.exec(e);let n;return t&&(n={},t[1].split("\n").map((e=>e.replace(/\s*/g,""))).filter((e=>!!e)).map((e=>e.split("="))).forEach((e=>n[e[0]]=e[1]||"*"))),n}function i(e){const t=/```config\s+((.|\s)+?)\s*```/i.exec(e);let n=[];return t&&t[1].split("\n").map((e=>e.replace(/\s*/g,""))).filter((e=>!!e)).map((e=>e.split("="))).filter((e=>"feature"==e[0]&&!!e[1])).forEach((e=>n.push(e[1]))),n.length?n:void 0}function s(t){const n=/```jres\s+((.|\s)+?)\s*```/i.exec(t);if(n){const t=n[1],i=JSON.parse(t);return{jres:t,ts:e.emitTilemapsFromJRes(i)}}}function r(t){const n=/```assetjson\s+((.|\s)+?)\s*```/i.exec(t);return n?e.tutorial.parseAssetJson(n[1]):{}}function o(t){const n=/```simtheme\s+([\s\S]*?)```/i.exec(t);return n?e.tutorial.parseSimThemeJson(n[1]):{}}function a(t){let n=e.Util.jsonTryParse(t);return n&&!Array.isArray(n)&&(n=[n]),(null==n?void 0:n.length)?n:(n=t.split(/^---$/gm).filter((e=>!!e)).map((e=>{let t={};return e.replace(/^\s*(?:-|\*)\s+(\w+)\s*:\s*(.*)$/gm,((e,n,i)=>{if("flags"==n)t[n]=i.split(",");else if("otherAction"===n){const e=i.split(",").map((e=>null==e?void 0:e.trim()));(t.otherActions||(t.otherActions=[])).push({url:e[0],editor:e[1],cardType:e[2]})}else t[n]=i;return""})),!!Object.keys(t).length&&t})).filter((e=>!!e)),(null==n?void 0:n.length)?n:void 0)}function l(t){if(!t)return[];const n=[];let i,s=!1,r="";return t.split(/\r?\n/).forEach((t=>{if(/^## /.test(t))i=t.substr(2).trim();else if(/^(### ~ |```)codecard$/.test(t))s=!0;else if(/^(### ~|```)$/.test(t)){if(s=!1,i&&r){const t=a(r);(null==t?void 0:t.length)?n.push({name:i,cards:t}):e.log("invalid gallery format")}r="",i=void 0}else s&&(r+=t+"\n")})),n.forEach((t=>t.cards.forEach((t=>{if(t.otherActions&&!t.otherActions.length&&("tutorial"==t.cardType||"example"==t.cardType)){const n=["js"];e.appTarget.appTheme.python&&n.unshift("py"),t.otherActions=n.map((e=>({url:t.url,cardType:t.cardType,editor:e})))}})))),n}t.parsePackagesFromMarkdown=n,t.parseFeaturesFromMarkdown=i,t.parseJResFromMarkdown=s,t.parseTemplateProjectJSON=r,t.parseSimThemeJSON=o,t.parseExampleMarkdown=function(t,a){if(!a)return;const l=/```(blocks?|typescript|python|spy|sim)\s+((.|\s)+?)\s*```/i.exec(a);if(!l)return;const c=n(a),u=l[1],d=l[2],h=i(a),p=s(a),f=o(a),m={name:t,filesOverride:{[e.MAIN_BLOCKS]:'<xml xmlns="http://www.w3.org/1999/xhtml"></xml>',["python"===l[1]?e.MAIN_PY:e.MAIN_TS]:d},dependencies:c,features:h,snippetType:u,source:d,simTheme:f};return m.filesOverride=Object.assign(Object.assign({},m.filesOverride),r(a)),p&&(m.filesOverride[e.TILEMAP_JRES]=p.jres,m.filesOverride[e.TILEMAP_CODE]=p.ts),m},t.parseCodeCards=a,t.parseCodeCardsHtml=function(t){let n,i=[];return Array.from(t.children).forEach((e=>{"UL"===e.tagName||"OL"===e.tagName?(n||(n={}),Array.from(e.querySelectorAll("li")).forEach((e=>{const t=e.innerText,i=/^\s*(\w+)\s*:\s*(.*)$/.exec(t);if(i){const e=i[1];n[e]=i[2].trim(),"flags"===e&&(n[e]=n[e].split(/,\s*/))}}))):"HR"==e.tagName&&(n&&i.push(n),n=void 0)})),n&&i.push(n),0===i.length&&"CODE"===t.tagName&&(i=e.Util.jsonTryParse(t.textContent)),!!(null==i?void 0:i.length)&&i},t.parseGalleryMardown=l,t.loadGalleryAsync=function(t){return e.Cloud.markdownAsync(t).then((e=>l(e)))},t.codeCardsToMarkdown=function(e){return`### ~ codecard\n\n${(e||[]).map((e=>Object.keys(e).filter((t=>!!e[t])).map((t=>"otherActions"===t?e[t].map((e=>`* otherAction: ${e.url}, ${e.editor||""}, ${e.cardType||""}`)).join("\n"):`* ${t}: ${e[t]}`)).join("\n"))).join("\n\n---\n\n")}\n\n### ~\n`}}(e.gallery||(e.gallery={}))}(pxt||(pxt={})),function(e){e.GDBServer=class{constructor(t){this.io=t,this.q=new e.U.PromiseQueue,this.dataBuf="",this.numSent=0,this.pktSize=400,this.trace=!1,this.bmpMode=!0,this.targetInfo="",this.onEvent=e=>{},this.io.onData=e=>this.onData(e)}onData(t){for(this.dataBuf+=e.U.uint8ArrayToString(t);this.dataBuf.length>0;){let e=this.dataBuf[0];if("+"==e)this.dataBuf=this.dataBuf.slice(1);else if("$"==e||"%"==e){let t=this.decodeResp(this.dataBuf.slice(1));if(null==t)break;"$"==e?(this.io.sendPacketAsync(this.buildCmd("+")),this.onResponse?this.onResponse(t):this.numSent>0&&this.io.error("unexpected response: "+t)):this.onEvent(t)}else this.io.error("invalid character: "+e)}}buildCmd(t){if("+"==t)return e.U.stringToUint8Array(t);let n="";for(let e=0;e<t.length;++e){let i=t.charAt(e);"}"==i||"#"==i||"$"==i?(n+="}",n+=String.fromCharCode(32^i.charCodeAt(0))):n+=i}let i=0;t=n;for(let e=0;e<t.length;++e)i=i+t.charCodeAt(e)&255;return n="$"+t+"#"+("0"+i.toString(16)).slice(-2),e.U.stringToUint8Array(n)}decodeResp(e){let t="";for(let n=0;n<e.length;++n){let i=e[n];if("}"==i)++n,t+=String.fromCharCode(32^e.charCodeAt(n));else if("*"==i){++n;let i=e.charCodeAt(n)-29,s=t.charAt(t.length-1);for(;i-- >0;)t+=s}else{if("#"==i){return 2==e.slice(n+1,n+3).length?(this.dataBuf=e.slice(n+3),t):null}t+=i}}return null}sendCmdOKAsync(e){return this.sendCmdAsync(e,(e=>"OK"==e))}error(e){this.io.error(e),this.io.disconnectAsync()}sendCmdAsync(t,n){this.numSent++;const i=this.buildCmd(t);return this.q.enqueue("one",(()=>null===n?this.io.sendPacketAsync(i).then((()=>null)):new Promise((s=>{this.onResponse=i=>{this.onResponse=null,this.trace&&e.log(`GDB: '${t}' -> '${i}'`),void 0===n||n(i)||this.error(`Invalid GDB command response: '${t}' -> '${i}'`),s(i)},this.io.sendPacketAsync(i)}))))}sendRCmdAsync(t){return this.sendMCmdAsync("qRcmd,"+(n=t,e.U.toHex(e.U.stringToUint8Array(n))));var n}sendMCmdAsync(t){this.numSent++;const n=this.buildCmd(t);let i="";return this.q.enqueue("one",(()=>new Promise((s=>{this.onResponse=n=>{var r;"OK"!=n&&"O"==n[0]?i+=(r=n.slice(1),e.U.uint8ArrayToString(e.U.fromHex(r))):("OK"!=n&&(i+=" - "+n),this.onResponse=null,this.trace&&e.log(`Final GDB: '${t}' -> '${i}'`),s(i))},this.io.sendPacketAsync(n)}))))}write32Async(t,n){let i=new Uint8Array(4);return e.HF2.write32(i,0,n),this.writeMemAsync(t,i)}writeMemAsync(t,n){const i=this.pktSize/2-10;return e.U.assert(n.length<i),this.sendCmdOKAsync("M"+t.toString(16)+","+n.length.toString(16)+":"+e.U.toHex(n)).then((e=>{console.log(e)}))}readMemAsync(t,n){const i=this.pktSize/2-6;if(n>i){const s=new Uint8Array(n),r=o=>{const a=Math.min(n-o,i);return 0==a?Promise.resolve(s):this.readMemAsync(t+o,a).then((t=>(e.U.memcpy(s,o,t),r(o+a))))};return r(0)}return this.sendCmdAsync("m"+t.toString(16)+","+n.toString(16)).then((t=>e.U.fromHex(t)))}initBMPAsync(){return Promise.resolve().then((()=>this.sendRCmdAsync("swdp_scan"))).then((e=>(this.targetInfo=e,this.sendCmdAsync("vAttach;1",(e=>"T"==e[0]))))).then((()=>{}))}initAsync(){return e.U.delay(1e3).then((()=>this.sendCmdAsync("!"))).then((()=>this.sendCmdAsync("qSupported"))).then((t=>{let n={};return t=(t=";"+t+";").replace(/;([^;]+)[=:]([^:;]+)/g,((e,t,i)=>(n[t]=i,";"))),this.pktSize=parseInt(n.PacketSize)||1024,e.log("GDB-server caps: "+JSON.stringify(n)+" "+t.replace(/;+/g,";")),this.bmpMode?this.initBMPAsync():this.sendCmdAsync("c").then((()=>{}))}))}}}(pxt||(pxt={})),function(e){!function(t){function n(){var n,i;return!!t.forceProxy||!e.U.isNodeJS&&!(null===(i=null===(n=null==e?void 0:e.appTarget)||void 0===n?void 0:n.cloud)||void 0===i?void 0:i.noGithubProxy)}t.token=null,t.forceProxy=!1;const i={};function s(n){var i;return n.method=null!==(i=n.method)&&void 0!==i?i:"GET",function i(s){var r;const o=e.U.clone(n);t.token&&(o.headers||(o.headers={}),o.url==U?o.headers.Authorization=`bearer ${t.token}`:(o.url=e.BrowserUtils.cacheBustingUrl(o.url),o.headers.Authorization=`token ${t.token}`));return o.allowHttpErrors=null!==(r=o.allowHttpErrors)&&void 0!==r&&r,e.U.requestAsync(o).catch((n=>{if(e.tickEvent("github.error",{statusCode:n.statusCode}),t.handleGithubNetworkError){if(t.handleGithubNetworkError(o,n))return i(!1)}throw n}))}(t.token)}function r(e){return s({url:e,method:"GET"}).then((e=>e.json))}function o(t){return e.Cloud.apiRequestWithCdnAsync({url:"gh/"+t,forceLiveEndpoint:!0}).then((e=>e.json))}function a(t){e.log(`github proxy error: ${t.message}`),e.debug(t)}t.isOrgAsync=function(e){return s({url:`https://api.github.com/orgs/${e}`,method:"GET",allowHttpErrors:!0}).then((e=>200==e.statusCode))};class l{constructor(){this.latestVersions={},this.configs={},this.packages={}}proxyWithCdnLoadPackageAsync(t,n){const i=`${t}/${n}`;let s=this.packages[i];if(s)return e.debug(`github cache ${t}/${n}/text`),Promise.resolve(s);const r=T(t);return o(I(r.slug,n,r.fileName,"text")).then((e=>this.packages[i]={files:e}))}cacheConfig(t,n){const i=e.Package.parseAndValidConfig(n);return this.configs[t]=i,e.U.clone(i)}async loadConfigAsync(t,i){i||(e.debug("dep: default to master branch"),i="master");const s=`${t}/${i}`;let r=this.configs[s];if(r)return e.debug(`github cache ${t}/${i}/config`),e.U.clone(r);if(n())try{const n=await this.proxyWithCdnLoadPackageAsync(t,i);return this.cacheConfig(s,n.files[e.CONFIG_NAME])}catch(e){a(e)}const o=await u(t,i,e.CONFIG_NAME);return this.cacheConfig(s,o)}async latestVersionAsync(t,n){let i=this.latestVersions[t];return i||(e.debug(`dep: resolve latest version of ${t}`),this.latestVersions[t]=i=await e.github.latestVersionAsync(t,n,!0,!1)),i}async loadPackageAsync(t,i){if(i||(e.debug("load pkg: default to master branch"),i="master"),n())try{return await this.proxyWithCdnLoadPackageAsync(t,i).then((t=>e.U.clone(t)))}catch(e){a(e)}return await this.githubLoadPackageAsync(t,i)}githubLoadPackageAsync(t,n){return g(t,n).then((i=>{const s=`${t}/${i}`;let r=this.packages[s];return r?(e.debug(`github cache ${t}/${n}/text`),Promise.resolve(e.U.clone(r))):(e.log(`Downloading ${t}/${n} -> ${i}`),u(t,i,e.CONFIG_NAME).then((n=>{const r={files:{}};r.files[e.CONFIG_NAME]=n;const o=JSON.parse(n);return e.U.promiseMapAll(e.allPkgFiles(o).slice(1),(e=>u(t,i,e).then((t=>{r.files[e]=t})))).then((()=>(this.packages[s]=r,e.U.clone(r))))})))}))}}function c(t,n,r){return s({url:"https://api.github.com/repos/"+I(t.slug,"contents",t.fileName,r+"?ref="+n),method:"GET"}).then((n=>{const s=n.json;return i[t.slug]=!0,s&&"base64"==s.encoding&&null!=s.content?e.Util.fromUTF8(atob(s.content)):e.U.httpGetTextAsync(s.download_url)}))}function u(t,n,s){const r=T(t);return i[r.slug]?c(r,n,s):e.U.requestAsync({url:"https://raw.githubusercontent.com/"+I(r.slug,n,r.fileName,s),allowHttpErrors:!0}).then((e=>200==e.statusCode?e.text:c(r,n,s)))}function d(e,t,n,i){return s({url:/^https:/.test(e)?e:"https://api.github.com/repos/"+e,headers:n,method:i||"POST",data:t,successCodes:[200,201,202,204]}).then((e=>e.json))}function h(e,t){let n=1;for(;e.refs[t+n];)n++;return t+n}async function p(e,t,n){return await d(e+"/git/refs",{ref:"refs/heads/"+t,sha:n}),t}function f(i,s="tags",o,a){const l=T(i),c=(u=o,!!t.forceProxy||!(t.token&&!u)&&n());var u;let d=null;const h=c?e.U.httpGetJsonAsync(e.BrowserUtils.cacheBustingUrl(`${e.Cloud.apiRoot}gh/${l.slug}/refs${a?"?nocache=1":""}`)).then((t=>{let n=Object.keys(t.refs).filter((t=>e.U.startsWith(t,"refs/"+s+"/"))).map((e=>({ref:e,object:{sha:t.refs[e]}})));return d=t.refs.HEAD,n})):r(`https://api.github.com/repos/${l.slug}/git/refs/${s}/?per_page=100`);let p=e=>e.replace(/^refs\/[^\/]+\//,"");return h.then((t=>{t.sort(((t,n)=>e.semver.strcmp(p(t.ref),p(n.ref))));let n={};for(let e of t)n[p(e.ref)]=e.object.sha;return{refs:n,head:d}}),(e=>404==e.statusCode?{refs:{}}:Promise.reject(e)))}function m(e){return"commit"==e.object.type?Promise.resolve(e.object.sha):"tag"==e.object.type?r(e.object.url).then((e=>"commit"==e.object.type?e.object.sha:Promise.reject(new Error("Bad type (2nd order) "+e.object.type)))):Promise.reject(new Error("Bad type "+e.object.type))}function g(e,t){if(/^[a-f0-9]{40}$/.test(t))return Promise.resolve(t);const n=T(e);return r(`https://api.github.com/repos/${n.slug}/git/refs/tags/${t}`).then(m,(e=>r(`https://api.github.com/repos/${n.slug}/git/refs/heads/${t}`).then(m)))}async function b(e,n,i){return n||(n=await t.db.latestVersionAsync(e,i)),await t.db.loadConfigAsync(e,n)}async function y(n,i){const s=T(n);if(!s)return void e.log("Unknown GitHub syntax");if(A(s,i))return e.tickEvent("github.download.banned"),void e.log("Github repo is banned");s.tag||(s.tag=await t.db.latestVersionAsync(s.slug,i));const r=await t.db.loadPackageAsync(s.fullName,s.tag),o=P(i,n);if(o){const t=e.Package.parseAndValidConfig(r.files[e.CONFIG_NAME]);t&&(e.log(`auto-disable ${o.join(",")} due to targetconfig entry for ${n}`),t.disablesVariants=o,r.files[e.CONFIG_NAME]=e.Package.stringifyConfig(t))}return r}let v;function w(t){return e.Cloud.cdnApiUrl(`gh/${t.fullName}/icon`)}function k(e,t){var n;if(!e)return;const i={owner:e.owner.login.toLowerCase(),slug:e.full_name.toLowerCase(),fullName:((null==t?void 0:t.fullName)||e.full_name).toLowerCase(),fileName:null===(n=null==t?void 0:t.fileName)||void 0===n?void 0:n.toLocaleLowerCase(),name:e.name,description:e.description,defaultBranch:e.default_branch,tag:null==t?void 0:t.tag,updatedAt:Math.round(new Date(e.updated_at).getTime()/1e3),fork:e.fork,private:e.private};return i.status=x(i,null==t?void 0:t.config),i}function x(e,t){return e?A(e,t)?v.Banned:function(e,t){var n,i;if(function(e,t){return!(!e||!t)&&!!(e.owner&&t.approvedOrgs&&t.approvedOrgs.some((t=>t.toLowerCase()==e.owner.toLowerCase())))}(e,t))return!0;const s=null===(n=null==e?void 0:e.fullName)||void 0===n?void 0:n.toLowerCase(),r=null===(i=null==e?void 0:e.slug)||void 0===i?void 0:i.toLowerCase();return!(!(null==t?void 0:t.approvedRepoLib)||!s&&!r)&&!(!t.approvedRepoLib[s]&&!t.approvedRepoLib[r])}(e,t)?v.Approved:v.Unknown:v.Unknown}function A(e,t){var n,i;if(function(e,t){return!(!t||e&&e.owner&&(!t.bannedOrgs||!t.bannedOrgs.some((t=>t.toLowerCase()==e.owner.toLowerCase()))))}(e,t))return!0;if(!t)return!1;if(!e)return!0;const s=null===(n=e.fullName)||void 0===n?void 0:n.toLowerCase(),r=null===(i=e.slug)||void 0===i?void 0:i.toLowerCase();return!(!t.bannedRepos||!t.bannedRepos.some((e=>e&&(e.toLowerCase()==s||e.toLowerCase()==r))))}async function E(t,i){const s=T(t);if(!s)return;const l=x(s,i);if(l==v.Banned)return;if(n())try{return await function(t,n){return o(t.slug).then((e=>{if(e)return{github:!0,owner:t.owner,fullName:t.fullName,fileName:t.fileName,slug:t.slug,name:t.fileName?`${e.name}-${t.fileName}`:e.name,description:e.description,defaultBranch:e.defaultBranch||"master",tag:t.tag,status:n}})).catch((t=>{e.reportException(t)}))}(s,l)}catch(e){a(e)}return k(await r("https://api.github.com/repos/"+s.slug),{config:i,fullName:s.fullName,fileName:s.fileName,tag:s.tag})}function T(e){if(!e)return;e=(e=e.trim()).replace(/\/$/,"");const t=/^https:\/\/([^./#]+)\.github\.io\/([^/#]+)\/?$/i.exec(e);t&&(e=`github:${t[1]}/${t[2]}`),e=(e=(e=e.replace(/^github:/i,"")).replace(/^https:\/\/github\.com\//i,"")).replace(/\.git\b/i,"");const n=/^([^#\/:]+)\/([^#\/:]+)(\/([^#]+))?(#([^\/:]*))?$/.exec(e);if(!n)return;const i=n[1],s=n[2];let r=n[4];const o=n[6],a=r&&/^tree\/([^\/]+\/)/.exec(r);return a&&(r=r.slice(a[0].length)),{owner:i,project:s,slug:I(i,s),fullName:I(i,s,r),tag:o,fileName:r}}function S(e){return!!e&&"github:"==e.slice(0,7)}function C(e,t=!1){return e?"github:"+(t?e.fullName:e.fullName.toLowerCase())+(e.tag?`#${e.tag}`:""):void 0}function I(...e){return e.filter((e=>!!e)).join("/")}function _(t,n){var i;if(!t)return null;const s=T(n);if(!s)return null;t.approvedRepoLib;return t.approvedRepoLib&&(null===(i=e.U.lookup(t.approvedRepoLib,s.slug.toLowerCase()))||void 0===i?void 0:i.upgrades)}function P(e,t){const n=_(e,t)||[];if(!n)return null;for(const e of n){const t=/^dv:(.*)/.exec(e);if(t){const e=t[1].split(/,/);return e.some((e=>!/^\w+$/.test(e)))?null:e}}return null}t.MemoryGithubDb=l,t.downloadTextAsync=u,t.db=new l,t.authenticatedUserAsync=function(){return t.token?r("https://api.github.com/user"):Promise.resolve(void 0)},t.getCommitsAsync=function(e,t){return r("https://api.github.com/repos/"+T(e).slug+"/commits?sha="+t).then((e=>e.map((e=>{const t=e.commit;return t.url=e.url,t.sha=e.sha,t}))))},t.getCommitAsync=function(e,t){return r("https://api.github.com/repos/"+T(e).slug+"/git/commits/"+t).then((e=>r(e.tree.url+"?recursive=1").then((t=>(e.tree=t,e)))))},t.createObjectAsync=function(e,t,n){return d(T(e).slug+"/git/"+t+"s",n).then((e=>e.sha))},t.postCommitComment=function(e,t,n,i,s){return d(`${T(e).slug}/commits/${t}/comments`,{body:n,path:i,position:s}).then((e=>e.id))},t.fastForwardAsync=async function(e,t,n){const i=T(e);return 200==(await s({url:`https://api.github.com/repos/${i.slug}/git/refs/heads/${t}`,method:"PATCH",allowHttpErrors:!0,data:{sha:n,force:!1}})).statusCode},t.putFileAsync=async function(t,n,i){const r=T(t);await s({url:`https://api.github.com/repos/${e.github.join(r.slug,"contents",r.fileName,n)}`,method:"PUT",allowHttpErrors:!0,data:{message:lf("Initialize empty repo"),content:btoa(e.U.toUTF8(i)),branch:"master"},successCodes:[201]})},t.createTagAsync=async function(e,t,n){await d(e+"/git/refs",{ref:"refs/tags/"+t,sha:n})},t.createReleaseAsync=async function(e,t,n){await d(e+"/releases",{tag_name:t,target_commitish:n,name:t,draft:!1,prerelease:!1})},t.createPRFromBranchAsync=async function(e,t,n,i,s){const r=await d(e+"/pulls",{title:i,body:s||lf("Automatically created from MakeCode."),head:n,base:t,maintainer_can_modify:!0});return null==r?void 0:r.html_url},t.mergeAsync=function(t,n,i,r){return s({url:`https://api.github.com/repos/${T(t).slug}/merges`,method:"POST",successCodes:[201,204,409],data:{base:n,head:i,commit_message:r}}).then((n=>{if(201==n.statusCode||204==n.statusCode)return n.json.sha;if(409==n.statusCode)return null;throw e.U.userError(lf("Cannot merge in github.com/{1}; code: {2}",t,n.statusCode))}))},t.getRefAsync=function(e,t){return r("https://api.github.com/repos/"+e+"/git/refs/heads/"+(t=t||"master")).then(m).catch((e=>{404!=e.statusCode&&Promise.reject(e)}))},t.getNewBranchNameAsync=async function(e,t="patch-"){return h(await f(e,"heads"),t)},t.createNewBranchAsync=p,t.forkRepoAsync=async function(t,n,i="pr-"){const s=T(t),r=k(await d(`${s.slug}/forks`,{}),{fullName:s.fullName,fileName:s.fileName}),o=Date.now()+3e5;let a=null;for(;!a&&Date.now()<o;){await e.U.delay(1e3);try{a=await f(r.slug,"heads")}catch(e){}}if(!a)throw new Error(lf("Timeout waiting for fork"));const l=h(a,i);return await p(r.slug,l,n),r.fullName+"#"+l},t.listRefsAsync=function(e,t="tags",n,i){return f(e,t,n,i).then((e=>Object.keys(e.refs)))},t.listRefsExtAsync=f,t.pkgConfigAsync=b,t.downloadPackageAsync=y,t.downloadLatestPackageAsync=async function(t,n,i){const s=await e.packagesConfigAsync(),r=await e.github.latestVersionAsync(t.slug,s,n,i),o=`${t.fullName}#${r}`;return await e.github.downloadPackageAsync(o,s),{version:`github:${o}`,config:await b(t.fullName,r,s)}},t.cacheProjectDependenciesAsync=async function(t){var n;const i=null===(n=Object.keys(t.dependencies))||void 0===n?void 0:n.filter((e=>S(t.dependencies[e])));if(i.length){const n=await e.packagesConfigAsync();await Promise.all(i.map((async e=>{const i=t.dependencies[e];if(!await y(i,n))throw new Error(lf("Cannot load extension {0} from {1}",e,i))})))}},function(e){e[e.Unknown=0]="Unknown",e[e.Approved=1]="Approved",e[e.Banned=2]="Banned"}(v=t.GitRepoStatus||(t.GitRepoStatus={})),t.isDefaultBranch=function(e,t){return t&&t.defaultBranch?e===t.defaultBranch:/^(main|master)$/.test(e)},t.listUserReposAsync=function(){return O('{\n viewer {\n repositories(first: 100, affiliations: [OWNER, COLLABORATOR], orderBy: {field: PUSHED_AT, direction: DESC}) {\n nodes {\n name\n description\n full_name: nameWithOwner\n private: isPrivate\n fork: isFork\n updated_at: updatedAt\n owner {\n login\n }\n defaultBranchRef {\n name\n }\n pxtjson: object(expression: "HEAD:pxt.json") {\n ... on Blob {\n text\n }\n }\n readme: object(expression: "HEAD:README.md") {\n ... on Blob {\n text\n }\n }\n }\n }\n }\n}').then((t=>t.data.viewer.repositories.nodes.filter((e=>e.pxtjson)).filter((t=>{t.default_branch=t.defaultBranchRef.name;const n=e.Package.parseAndValidConfig(t.pxtjson&&t.pxtjson.text),i=t.readme&&t.readme.text;return!!n&&(n.supportedTargets?n.supportedTargets.indexOf(e.appTarget.id)>-1:i&&i.indexOf("PXT/"+e.appTarget.id)>-1)})).map((e=>k(e,{fullName:e.full_name})))))},t.createRepoAsync=function(e,t,n){return d("https://api.github.com/user/repos",{name:e,description:t,private:!!n,has_issues:!0,has_projects:!1,has_wiki:!1,allow_rebase_merge:!1,allow_merge_commit:!0,delete_branch_on_merge:!1}).then((e=>k(e)))},t.enablePagesAsync=async function(t){const n=T(t);let i;try{const e=await r(`https://api.github.com/repos/${n.slug}/pages`);e&&(i=e.html_url)}catch(e){}if(!i)try{i=(await d(`https://api.github.com/repos/${n.slug}/pages`,{source:{branch:"master",path:"/"}},{Accept:"application/vnd.github.switcheroo-preview+json"})).html_url}catch(t){e.tickEvent("github.pages.error"),e.reportException(t)}if(i){const n=await r(`https://api.github.com/repos/${t}`);if(n&&!n.homepage)try{await d(`https://api.github.com/repos/${t}`,{homepage:i},void 0,"PATCH")}catch(t){e.tickEvent("github.homepage.error")}}},t.repoIconUrl=function(e){if(e.status==v.Approved)return w(e)},t.mkRepoIconUrl=w,t.repoStatus=x,t.repoAsync=E,t.searchAsync=function(t,n){if(!n)return Promise.resolve([]);let i=t.split("|").map(T).filter((e=>!!e));return i.length>0?Promise.all(i.map((e=>E(e.fullName,n)))).then((e=>e.filter((e=>e&&e.status!=v.Banned)))):e.U.httpGetJsonAsync(`${e.Cloud.apiRoot}ghsearch/${e.appTarget.id}/${e.appTarget.platformid||e.appTarget.id}?q=${encodeURIComponent(t)}`).then((t=>t.items.map((e=>k(e,{config:n,fullName:e.full_name}))).filter((e=>e.status==v.Approved||n.allowUnapproved&&e.status==v.Unknown)).filter((t=>!e.appTarget.appTheme.githubUrl||`https://github.com/${t.fullName}`!=e.appTarget.appTheme.githubUrl.toLowerCase())))).catch((e=>[]))},t.parseRepoId=T,t.toGithubDependencyPath=function(e,t){let n="github:"+e;return t&&(n+="#"+t),n},t.isGithubId=S,t.stringifyRepo=C,t.normalizeRepoId=function(e,t){const n=T(e);if(n)return!n.tag&&t&&(n.tag=t),C(n)},t.join=I,t.upgradedPackageReference=function(t,n){const i=_(t,n);if(!i)return null;for(const s of i){const i=/^min:(.*)/.exec(s),r=i&&e.semver.tryParse(i[1]);if(r){const t=T(n),s=e.semver.tryParse(t.tag);return s&&e.semver.cmp(s,r)<0?(t.tag=i[1],e.debug(`upgrading ${n} to ${i[1]}`),C(t)):(s||e.log(`not upgrading ${n} - cannot parse version`),null)}P(t,n)||e.log(`invalid upgrade rule: ${n} -> ${s}`)}return n},t.upgradedPackageId=function(e,t){const n=P(e,t);return n?t+"?dv="+n.join(","):t},t.latestVersionAsync=function(t,n,i,s){const r=T(t);return r?E(r.slug,n).then((t=>{if(t)return f(t.slug,"tags",i,s).then((i=>{let s=Object.keys(i.refs);s=e.semver.sortLatestTags(s);const o=e.appTarget.versions&&e.semver.tryParse(e.appTarget.versions.target);if(o&&n.releases&&n.releases["v"+o.major]){const i=n.releases["v"+o.major].map((t=>e.github.parseRepoId(t))).filter((e=>e&&e.fullName.toLowerCase()==r.fullName.toLowerCase()))[0];if(i){if(s.some((e=>e==i.tag)))return e.debug(`approved release ${i.fullName}#${i.tag} for v${o.major}`),Promise.resolve(i.tag);e.reportError("packages",`approved release ${i.fullName}#${i.tag} for v${o.major} not found anymore`,{repo:t.fullName})}}return s[0]?Promise.resolve(s[0]):i.head||g(t.slug,t.defaultBranch)}))})):Promise.resolve(null)},t.resolveMonoRepoVersions=function(n){n=e.Util.clone(n);const i={};return Object.keys(n).map((e=>({id:e,ghid:t.parseRepoId(n[e])}))).filter((e=>{var t;return null===(t=e.ghid)||void 0===t?void 0:t.tag})).forEach((t=>{const{id:n,ghid:s}=t;let r=i[s.slug];r||(r=i[s.slug]={tag:s.tag,deps:[]}),r.deps.push(t),e.semver.strcmp(r.tag,s.tag)<0&&(e.debug(`dep: resolve later monorepo tag to ${e.github.stringifyRepo(s)}`),r.tag=s.tag)})),e.U.values(i).forEach((t=>t.deps.forEach((i=>{i.ghid.tag!==t.tag&&(e.debug(`dep: ${e.github.stringifyRepo(i.ghid)} -> ${t.tag}`),i.ghid.tag=t.tag,n[i.id]=e.github.stringifyRepo(i.ghid))})))),n},t.GIT_JSON=".git.json";const U="https://api.github.com/graphql";function O(e){const t=JSON.stringify({query:e});return d(U,t)}t.lookupFile=function(e,t,n){if(!t)return null;const i=I(e.fileName,n);return t.tree.tree.find((e=>e.path==i))},t.ghGraphQLQueryAsync=O,t.findPRNumberforBranchAsync=function(e,t){const n=T(e);return O(`\n{\n repository(owner: ${JSON.stringify(n.owner)}, name: ${JSON.stringify(n.project)}) {\n pullRequests(last: 1, states: [OPEN, MERGED], headRefName: ${JSON.stringify(t)}) {\n edges {\n node {\n number\n state\n mergeable\n baseRefName\n url\n isDraft\n }\n }\n }\n }\n}\n`).then((e=>{const t=e.data.repository.pullRequests.edges[0];if(t&&t.node){const e=t.node;return{number:e.number,mergeable:e.mergeable,state:e.state,title:e.title,url:e.url,base:e.baseRefName}}return{number:-1}}))},t.getPagesStatusAsync=function(e){return r(`https://api.github.com/repos/${e}/pages`).catch((e=>({status:null})))}}(e.github||(e.github={}))}(pxt||(pxt={})),function(e){let t;e.REFCNT_FLASH="0xfffe",e.VTABLE_MAGIC=249,e.ValTypeObject=4,function(e){e[e.BoxedString=1]="BoxedString",e[e.BoxedNumber=2]="BoxedNumber",e[e.BoxedBuffer=3]="BoxedBuffer",e[e.RefAction=4]="RefAction",e[e.RefImage=5]="RefImage",e[e.RefCollection=6]="RefCollection",e[e.RefRefLocal=7]="RefRefLocal",e[e.RefMap=8]="RefMap",e[e.RefMImage=9]="RefMImage",e[e.MMap=10]="MMap",e[e.BoxedString_SkipList=11]="BoxedString_SkipList",e[e.BoxedString_ASCII=12]="BoxedString_ASCII",e[e.ZPin=13]="ZPin",e[e.User0=16]="User0"}(t=e.BuiltInType||(e.BuiltInType={}))}(pxt||(pxt={})),function(e){!function(t){function n(e,t,n){e[t+0]=n>>0&255,e[t+1]=n>>8&255,e[t+2]=n>>16&255,e[t+3]=n>>24&255}function i(e,t,n){e[t+0]=n>>0&255,e[t+1]=n>>8&255}function s(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function r(e,t){return e[t]|e[t+1]<<8}function o(e){let t=new Uint8Array(4*e.length);for(let i=0;i<e.length;++i)n(t,4*i,e[i]);return t}t.HF2_CMD_BININFO=1,t.HF2_MODE_BOOTLOADER=1,t.HF2_MODE_USERSPACE=2,t.HF2_CMD_INFO=2,t.HF2_CMD_RESET_INTO_APP=3,t.HF2_CMD_RESET_INTO_BOOTLOADER=4,t.HF2_CMD_START_FLASH=5,t.HF2_CMD_WRITE_FLASH_PAGE=6,t.HF2_CMD_CHKSUM_PAGES=7,t.HF2_CMD_READ_WORDS=8,t.HF2_CMD_WRITE_WORDS=9,t.HF2_CMD_DMESG=16,t.HF2_FLAG_SERIAL_OUT=128,t.HF2_FLAG_SERIAL_ERR=192,t.HF2_FLAG_CMDPKT_LAST=64,t.HF2_FLAG_CMDPKT_BODY=0,t.HF2_FLAG_MASK=192,t.HF2_SIZE_MASK=63,t.HF2_STATUS_OK=0,t.HF2_STATUS_INVALID_CMD=1,t.HF2_STATUS_EXEC_ERR=2,t.HF2_STATUS_EVENT=128,t.HF2_CMD_JDS_CONFIG=32,t.HF2_CMD_JDS_SEND=33,t.HF2_EV_JDS_PACKET=8388640,t.CUSTOM_EV_JACDAC="jacdac",t.HF2_EV_MASK=8388608,t.write32=n,t.write16=i,t.read32=s,t.read16=r,t.encodeU32LE=o,t.decodeU32LE=function(e){let t=[];for(let n=0;n<e.length;n+=4)t.push(s(e,n));return t};let a=!1;function l(t){a?e.log("HF2: "+t):e.debug("HF2: "+t)}t.enableLog=function(){a=!0};class c{constructor(n){var i;this.io=n,this.initialized=!1,this.cmdSeq=e.U.randomUint32(),this.lock=new e.U.PromiseQueue,this.flashing=!1,this.rawMode=!1,this.maxMsgSize=63,this.bootloaderMode=!1,this.reconnectTries=0,this.autoReconnect=!1,this.icon=(null===(i=e.appTarget.appTheme.downloadDialogTheme)||void 0===i?void 0:i.deviceIcon)||"usb",this.msgs=new e.U.PromiseBuffer,this.eventHandlers={},this.jacdacAvailable=!1,this.onSerial=(e,t)=>{},this.onCustomEvent=(e,t)=>{},this.onConnectionChanged=()=>{};let r=[];n.onDeviceConnectionChanged=e=>this.disconnectAsync().then((()=>e&&this.reconnectAsync())),n.onSerial=(e,t)=>this.onSerial(e,t),n.onData=i=>{let s=i[0]&t.HF2_FLAG_MASK,o=63&i[0],a=new Uint8Array(o);if(e.U.memcpy(a,0,i,1,o),s&t.HF2_FLAG_SERIAL_OUT)this.onSerial(a,s==t.HF2_FLAG_SERIAL_ERR);else if(r.push(a),s!=t.HF2_FLAG_CMDPKT_BODY){e.U.assert(s==t.HF2_FLAG_CMDPKT_LAST);let i=0;for(let e of r)i+=e.length;let o=new Uint8Array(i),a=0;for(let t of r)e.U.memcpy(o,a,t),a+=t.length;r=[],o[2]&t.HF2_STATUS_EVENT?n.onEvent(o):this.msgs.push(o)}},n.onEvent=t=>{let n=s(t,0),i=e.U.lookup(this.eventHandlers,n+"");i?i(t.slice(4)):l("unhandled event: "+n.toString(16))},n.onError=e=>{l("recv error: "+e.message),this.autoReconnect&&(this.autoReconnect=!1,this.reconnectAsync().then((()=>{this.autoReconnect=!0}),(e=>{l("reconnect error: "+e.message)})))},this.onEvent(t.HF2_EV_JDS_PACKET,(e=>{this.onCustomEvent(t.CUSTOM_EV_JACDAC,e)}))}resetState(){this.initialized=!1,this.lock=new e.U.PromiseQueue,this.info=null,this.infoRaw=null,this.pageSize=null,this.flashSize=null,this.maxMsgSize=63,this.bootloaderMode=!1,this.msgs.drain()}onEvent(n,i){e.U.assert(!!(n&t.HF2_EV_MASK)),this.eventHandlers[n+""]=i}sendCustomEventAsync(e,n){return e==t.CUSTOM_EV_JACDAC?this.jacdacAvailable?this.talkAsync(t.HF2_CMD_JDS_SEND,n).then((()=>{})):Promise.resolve():Promise.reject(new Error("invalid custom event type"))}isConnected(){return this.io.isConnected()&&this.initialized}isConnecting(){return this.io.isConnecting()||this.io.isConnected()&&!this.initialized}reconnectAsync(){return this.resetState(),l(`reconnect raw=${this.rawMode}`),this.io.reconnectAsync().then((()=>this.initAsync())).catch((t=>{if(this.reconnectTries<5)return this.reconnectTries++,l(`error ${t.message}; reconnecting attempt #${this.reconnectTries}`),e.U.delay(500).then((()=>this.reconnectAsync()));throw t}))}disconnectAsync(){return l("disconnect"),this.io.disconnectAsync()}error(e){return this.io.error(e)}talkAsync(s,o){if(this.io.talksAsync)return this.io.talksAsync([{cmd:s,data:o}]).then((e=>e[0]));let a=8;o&&(a+=o.length);let c=new Uint8Array(a),u=65535&++this.cmdSeq;n(c,0,s),i(c,4,u),i(c,6,0),o&&e.U.memcpy(c,8,o,0,o.length);let d=0,h=()=>this.msgs.shiftAsync(1e3).then((e=>{if(r(e,0)!=u){if(d<3)return d++,l(`message out of sync, (${u} vs ${r(e,0)}); will re-try`),h();this.error("out of sync")}let n="";switch(e[3]&&(n="; info="+e[3]),e[2]){case t.HF2_STATUS_OK:return e.slice(4);case t.HF2_STATUS_INVALID_CMD:this.error("invalid command"+n);break;case t.HF2_STATUS_EXEC_ERR:this.error("execution error"+n);break;default:this.error("error "+e[2]+n)}return null}));return this.sendMsgAsync(c).then(h)}sendMsgAsync(e){return this.sendMsgCoreAsync(e)}sendSerialAsync(e,t=!1){return this.io.sendSerialAsync?this.io.sendSerialAsync(e,t):this.sendMsgCoreAsync(e,t?2:1)}sendMsgCoreAsync(e,n=0){let i=new Uint8Array(64),s=r=>{let o=e.length-r;if(o<=0)return Promise.resolve();o>63?(o=63,i[0]=t.HF2_FLAG_CMDPKT_BODY):i[0]=t.HF2_FLAG_CMDPKT_LAST,n&&(i[0]=1==n?t.HF2_FLAG_SERIAL_OUT:t.HF2_FLAG_SERIAL_ERR),i[0]|=o;for(let t=0;t<o;++t)i[t+1]=e[r+t];return this.io.sendPacketAsync(i).then((()=>s(r+o)))};return this.lock.enqueue("out",(()=>s(0)))}switchToBootloaderAsync(){return this.bootloaderMode?Promise.resolve():(l("Switching into bootloader mode"),this.io.isSwitchingToBootloader&&this.io.isSwitchingToBootloader(),this.maybeReconnectAsync().then((()=>this.talkAsync(t.HF2_CMD_START_FLASH).then((()=>{}),(e=>this.talkAsync(t.HF2_CMD_RESET_INTO_BOOTLOADER).then((()=>{}),(e=>{})).then((()=>this.reconnectAsync().catch((e=>{throw"devicenotfound"===e.type&&(e.type="repairbootloader"),e})))))))).then((()=>this.initAsync())).then((()=>{this.bootloaderMode||this.error("cannot switch into bootloader mode")})))}isFlashing(){return!!this.flashing}reflashAsync(t){l("reflash"),e.U.assert(e.appTarget.compile.useUF2);const n=t.outfiles[pxtc.BINARY_UF2],i=pxtc.UF2.parseFile(e.Util.stringToUint8Array(atob(n)));return this.flashing=!0,this.io.reconnectAsync().then((()=>this.flashAsync(i))).then((()=>e.U.delay(100))).finally((()=>this.flashing=!1)).then((()=>this.reconnectAsync()))}writeWordsAsync(n,i){return e.U.assert(i.length<=64),this.talkAsync(t.HF2_CMD_WRITE_WORDS,o([n,i.length].concat(i))).then((()=>{}))}readWordsAsync(i,s){let r=new Uint8Array(8);return n(r,0,i),n(r,4,s),e.U.assert(s<=64),this.talkAsync(t.HF2_CMD_READ_WORDS,r)}pingAsync(){return this.rawMode?Promise.resolve():this.talkAsync(t.HF2_CMD_BININFO).then((e=>{}))}maybeReconnectAsync(){return this.pingAsync().catch((e=>this.reconnectAsync().then((()=>this.pingAsync()))))}flashAsync(i){let s=Date.now(),r=0,o=s=>{if(s>=i.length)return Promise.resolve();let r=i[s],a=new Uint8Array(4+r.payloadSize);return n(a,0,r.targetAddr),e.U.memcpy(a,4,r.data,0,r.payloadSize),this.talkAsync(t.HF2_CMD_WRITE_FLASH_PAGE,a).then((()=>o(s+1)))};return this.switchToBootloaderAsync().then((()=>{let e=256*i.length;return l(`Starting flash (${Math.round(e/1024)}kB).`),r=Date.now(),this.pageSize>16384?i:u(i,((e,t)=>this.readWordsAsync(e,t)))})).then((e=>{if(e.length!=i.length){let t=256*(i=e).length;l(`Performing partial flash (${Math.round(t/1024)}kB).`)}})).then((()=>o(0))).then((()=>{let e=Date.now(),t=e-s,n=e-r;l(`Flashing done at ${Math.round(256*i.length/n*1e3/1024)} kB/s in ${t}ms (reset ${t-n}ms). Resetting.`)})).then((()=>this.talkAsync(t.HF2_CMD_RESET_INTO_APP).catch((e=>{})))).then((()=>{}))}initAsync(){return this.rawMode?(this.initialized=!0,Promise.resolve()):Promise.resolve().then((()=>this.talkAsync(t.HF2_CMD_BININFO))).then((e=>(this.bootloaderMode=e[0]==t.HF2_MODE_BOOTLOADER,this.pageSize=s(e,4),this.flashSize=s(e,8)*this.pageSize,this.maxMsgSize=s(e,12),this.familyID=s(e,16),l(`Connected; msgSize ${this.maxMsgSize}B; flash ${this.flashSize/1024}kB; ${this.bootloaderMode?"bootloader":"application"} mode; family=0x${this.familyID.toString(16)}`),this.talkAsync(t.HF2_CMD_INFO)))).then((t=>{this.infoRaw=e.Util.fromUTF8Array(t),e.debug("Info: "+this.infoRaw);let n={};("Header: "+this.infoRaw).replace(/^([\w\-]+):\s*([^\n\r]*)/gm,((e,t,i)=>(n[t.replace(/-/g,"")]=i,""))),this.info=n;let i=/v(\d\S+)(\s+(\S+))?/.exec(this.info.Header);this.info.Parsed=i?{Version:i[1],Features:i[3]||""}:{Version:"?",Features:""},l(`Board-ID: ${this.info.BoardID} v${this.info.Parsed.Version} f${this.info.Parsed.Features}`)})).then((()=>this.talkAsync(t.HF2_CMD_JDS_CONFIG,new Uint8Array([1])).then((()=>{this.jacdacAvailable=!0}),(e=>{this.jacdacAvailable=!1})))).then((()=>{this.reconnectTries=0,this.initialized=!0,this.io.onConnectionChanged()}))}}function u(t,n){if(!e.appTarget.compile.flashChecksumAddr)return Promise.resolve(t);let i=pxtc.UF2.readBytes(t,e.appTarget.compile.flashChecksumAddr,48),r=pxtc.parseChecksumBlock(i);return r?function(t){return e.appTarget.compile.flashChecksumAddr?t(e.appTarget.compile.flashChecksumAddr,12).then((n=>{let i=pxtc.parseChecksumBlock(n);return i?t(i.endMarkerPos,1).then((t=>s(t,0)!=i.endMarker?(e.log("end-marker mismatch"),null):i)):null})):Promise.resolve(null)}(n).then((e=>{if(!e)return t;let n=e.regions.filter((e=>r.regions.some((t=>e.checksum==t.checksum&&e.length==t.length&&e.start==t.start))));if(0==n.length)return t;l("skipping flash at: "+n.map((e=>`${pxtc.assembler.tohex(e.start)} (${e.length/1024}kB)`)).join(", "));let i=e=>n.some((t=>t.start<=e&&e<t.start+t.length));return t.filter((e=>!(i(e.targetAddr)&&i(e.targetAddr+e.payloadSize-1))))})):Promise.resolve(t)}t.Wrapper=c,t.mkHF2PacketIOWrapper=function(t){return e.debug("packetio: wrapper hf2"),new c(t)},t.onlyChangedBlocksAsync=u}(e.HF2||(e.HF2={}))}(pxt||(pxt={})),function(e){!function(t){var n=e.Util,i=e.HF2;const s=i.read32;let r,o,a,l,c,u,d,h,p=!1;function f(e){return e<<2|2}function m(e){return 1&e?e>>1:0!=e?2&e?e==t.taggedNull?null:e!=t.taggedFalse&&(e==t.taggedTrue||{tagged:e>>2}):{ptr:e}:void 0}function g(e,t){if(n.assert(!(3&e)),n.assert(e>=0),e<2097152){let i=new Uint8Array(t);return e-=d.start,n.memcpy(i,0,d.buf,e,t),Promise.resolve(i)}let i=h.maxMsgSize-32;if(t>i){let s=[];for(;t>0;){let n=Math.min(i,t);s.push(g(e,n)),t-=n,e+=n}return Promise.all(s).then(n.uint8ArrayConcat)}return h.readWordsAsync(e,Math.ceil(t/4)).then((e=>e.length>t?e.slice(0,t):e))}function b(t){if("object"!=typeof t||!t)return Promise.resolve(t);if("number"==typeof t.ptr){if(3&t.ptr)return Promise.resolve({unalignedPtr:t.ptr});let s=0;return g(t.ptr,56).then((r=>{s=i.read16(r,2);let o=r.length;return s==e.BuiltInType.BoxedString||s==e.BuiltInType.BoxedBuffer?o=i.read16(r,4)+6:s==e.BuiltInType.BoxedNumber&&(o=12),o>r.length?g(t.ptr+r.length,o-r.length).then((e=>n.uint8ArrayConcat([r,e]))):o<r.length?r.slice(0,o):r})).then((t=>s==e.BuiltInType.BoxedString?n.uint8ArrayToString(t.slice(6)):s==e.BuiltInType.BoxedBuffer?{type:"buffer",data:t.slice(6)}:s==e.BuiltInType.BoxedNumber?new Float64Array(t.buffer.slice(4))[0]:{type:"unknown",tag:s,refcnt:i.read16(t,0),data:t.slice(4)}))}return Promise.resolve(t)}function y(e){let t=[];for(let n of Object.keys(e))t.push(b(e[n]).then((t=>{e[n]=t})));return Promise.all(t).then((()=>{}))}function v(e){let t=r.breakpoints,n=t[0],i=1/0;for(let s of t){let t=e-s.binAddr;t>=0&&t<i&&(i=t,n=s)}return n}function w(e){if(p)return Promise.resolve();let s;return p=!0,E().then((t=>{let o=i.decodeU32LE(e)[0],l={};for(let e of r.procDebugInfo[0].locals){let s=t.globals,r=(()=>{switch(e.type){case"uint32":return i.read32(s,e.index);case"int32":return 0|i.read32(s,e.index);case"uint16":return i.read16(s,e.index);case"int16":return i.read16(s,e.index)<<16>>16;case"uint8":return s[e.index];case"int8":return s[e.index]<<24>>24;default:return null}})();null===r&&(n.assert(0==(3&e.index)),r=m(i.read32(s,e.index))),l[e.name]=r}return c=v(o),s={type:"debugger",subtype:"breakpoint",breakpointId:c.id,globals:l,stackframes:[]},a(),h.talkAsync(1888490768)})).then((e=>{!function(e,t){let i=c.binAddr,s=0,o=r.procDebugInfo.filter((e=>e.codeStartLoc<=i&&i<=e.codeEndLoc))[0];for(;o&&o!=r.procDebugInfo[0];){let r=v(i),a=n.clone(r);a.functionName=o.name,a.argumentNames=o.args&&o.args.map((e=>e.name)),t.stackframes.push({locals:{},funcInfo:a,breakpointId:r.id});let l=t.stackframes[t.stackframes.length-1],c=0;for(let t of o.locals)n.assert(t.index==c++),l.locals[t.name]=m(e[s++]);i=2147483646&e[s++];let d=u[i+""];for(let t of o.args)l.locals[t.name]=m(e[s+(o.args.length-1-t.index)]);if(!d)break;o=d.from,s+=d.stack-o.localsMark}}(i.decodeU32LE(e),s);let t=[s.globals].concat(s.stackframes.map((e=>e.locals)));return n.promiseMapAll(t,y)})).then((()=>t.postMessage(s)))}function k(){p=!1,o=new Promise(((e,t)=>{a=e}))}function x(e=!1){return Promise.resolve().then((()=>h.talkAsync(665147697,i.encodeU32LE([e?1:3])))).then(k)}function A(){return o||(o=Promise.resolve()),o}function E(){return(l?Promise.resolve(l):h.talkAsync(1409050336).then((e=>l={numGlobals:s(e,0),globalsPtr:s(e,4)}))).then((e=>h.readWordsAsync(e.globalsPtr,e.numGlobals))).then((e=>({staticState:l,globals:e})))}t.taggedUndefined=0,t.taggedNull=f(1),t.taggedFalse=f(2),t.taggedTrue=f(16),t.postMessage=e=>console.log(e),t.decodeValue=m,t.heapExpandAsync=b,t.heapExpandMapAsync=y,t.startDebugAsync=function(e,t){return h=t,h.onEvent(915601917,w),(p=!1,r=null,l=null,Promise.resolve()).then((()=>{r=e,u={};let t=[];for(let n of e.procDebugInfo)t[n.idx]=n;for(let n of e.procDebugInfo)for(let e of n.calls)u[e.addr+""]={from:n,to:t[e.procIndex],stack:e.stack}})).then((()=>{let e=r.outfiles[pxtc.BINARY_UF2],t=n.stringToUint8Array(atob(e));return d=pxtc.UF2.toBin(t),h.reflashAsync(r).then((()=>h.reconnectAsync()))})).then((()=>h.talkAsync(287358355).catch((e=>{})))).then((()=>n.delay(200))).then((()=>h.reconnectAsync())).then(k).then(A)},t.handleMessage=function(e){if(console.log("HWDBGMSG",e),"debugger"!=e.type)return;let t=!1;switch(e.subtype){case"stepinto":t=!0;case"stepover":x(t)}},t.resumeAsync=x,t.waitForHaltAsync=A,t.getHwStateAsync=E}(e.HWDBG||(e.HWDBG={}))}(pxt||(pxt={})),function(e){e.ImageConverter=class{logTime(){if(this.start){let t=Date.now()-this.start;e.debug("Icon creation: "+t+"ms")}}convert(t){this.start||(this.start=Date.now());let n=atob(t.slice(t.indexOf(",")+1)),i=n.charCodeAt(0),s=n.charCodeAt(1),r=n.charCodeAt(2);if(135===i&&(i=224|n.charCodeAt(1),s=n.charCodeAt(2)|n.charCodeAt(3)<<8,r=n.charCodeAt(4)|n.charCodeAt(5)<<8,n=n.slice(4)),225!=i&&228!=i)return null;if(this.palette||this.setPalette(e.appTarget.runtime.palette.map((function(e){const t=parseInt(e.replace(/#/,""),16);return[t>>0&255,t>>8&255,t>>16&255,255]}))),225==i)return this.genMonochrome(n,s,r);const o=(e.BrowserUtils.isEdge()||e.BrowserUtils.isIE())&&s<100&&r<100?3:1;return this.genColor(n,s,r,o)}setPalette(e){e[0][3]=0,this.palette=new Uint8Array(4*e.length);for(let t=0;t<e.length;++t)this.palette[4*t+0]=e[t][0],this.palette[4*t+1]=e[t][1],this.palette[4*t+2]=e[t][2],this.palette[4*t+3]=e[t][3]}genMonochrome(t,n,i){let s=n+3&-4,r=54+this.palette.length,o=r+s*i,a=new Uint8Array(o);a[0]=66,a[1]=77,e.HF2.write32(a,2,o),e.HF2.write32(a,10,r),e.HF2.write32(a,14,40),e.HF2.write32(a,18,n),e.HF2.write32(a,22,-i),e.HF2.write16(a,26,1),e.HF2.write16(a,28,8),e.HF2.write32(a,38,2835),e.HF2.write32(a,42,2835),e.HF2.write32(a,46,this.palette.length>>2),a.set(this.palette,54);let l=4,c=r,u=1,d=t.charCodeAt(l++);for(let e=0;e<n;++e){c=r+e;for(let e=0;e<i;++e)a[c]=d&u?1:0,c+=s,u<<=1,256==u&&(u=1,d=t.charCodeAt(l++))}return"data:image/bmp;base64,"+btoa(e.U.uint8ArrayToString(a))}genColor(t,n,i,s){const r=n*(s=Math.max(1,0|s)),o=i*s;let a=r<<2,l=138,c=l+a*o,u=new Uint8Array(c);u[0]=66,u[1]=77,e.HF2.write32(u,2,c),e.HF2.write32(u,10,l),e.HF2.write32(u,14,124),e.HF2.write32(u,18,r),e.HF2.write32(u,22,-o),e.HF2.write16(u,26,1),e.HF2.write16(u,28,32),e.HF2.write16(u,30,3),e.HF2.write32(u,38,2835),e.HF2.write32(u,42,2835),e.HF2.write32(u,54,16711680),e.HF2.write32(u,58,65280),e.HF2.write32(u,62,255),e.HF2.write32(u,66,4278190080),u[70]=66,u[71]=71,u[72]=82,u[73]=115;let d=4,h=l,p=!0;for(let e=0;e<r;e++){let n=!1;h=l+(e<<2);let r=d,c=t.charCodeAt(d++),f=n?(c>>4&15)<<2:(15&c)<<2;for(let e=0;e<o;e++)c&&(p=!1),u[h]=this.palette[f],u[h+1]=this.palette[f+1],u[h+2]=this.palette[f+2],u[h+3]=this.palette[f+3],h+=a,e%s==s-1&&(n&&(c=t.charCodeAt(d++)),n=!n,f=n?(c>>4&15)<<2:(15&c)<<2);if(p&&(u[141]=1),e%s==s-1)for(i%2||--d;3&d;)d++;else d=r}return"data:image/bmp;base64,"+btoa(e.U.uint8ArrayToString(u))}},e.convertUint8BufferToPngUri=function(t,n){const i=new e.ImageConverter,s=[];for(let e=0;e<16;e++)s.push([t[3*e+2],t[3*e+1],t[3*e+0],255]);i.setPalette(s);const r=String.fromCharCode.apply(null,n),o=`data:image/x-mkcd-f4;base64,${btoa(r)}`;return i.convert(o)}}(pxt||(pxt={})),function(e){!function(t){function n(){const e={"tsconfig.json":t.TS_CONFIG,"test.ts":`// ${lf("tests go here; this will not be compiled when this package is used as an extension.")}\n`,"_config.yml":"makecode:\n target: @TARGET@\n platform: @PLATFORM@\n home_url: @HOMEURL@\ntheme: jekyll-theme-slate\ninclude:\n - assets\n - README.md\n",Makefile:"all: deploy\n\nbuild:\n\tpxt build\n\ndeploy:\n\tpxt deploy\n\ntest:\n\tpxt test\n",Gemfile:"source 'https://rubygems.org'\ngem 'github-pages', group: :jekyll_plugins","README.md":`\n> ${lf("Open this page at {0}","[https://@REPOOWNER@.github.io/@REPONAME@/](https://@REPOOWNER@.github.io/@REPONAME@/)")}\n\n## ${lf("Use as Extension")}\n\n${lf("This repository can be added as an **extension** in MakeCode.")}\n\n* ${lf("open [@HOMEURL@](@HOMEURL@)")}\n* ${lf("click on **New Project**")}\n* ${lf("click on **Extensions** under the gearwheel menu")}\n* ${lf("search for **https://github.com/@REPO@** and import")}\n\n## ${lf("Edit this project")}\n\n${lf("To edit this repository in MakeCode.")}\n\n* ${lf("open [@HOMEURL@](@HOMEURL@)")}\n* ${lf("click on **Import** then click on **Import URL**")}\n* ${lf("paste **https://github.com/@REPO@** and click import")}\n\n#### ${lf("Metadata (used for search, rendering)")}\n\n* for PXT/@TARGET@\n<script src="https://makecode.com/gh-pages-embed.js"><\/script><script>makeCodeRender("{{ site.makecode.home_url }}", "{{ site.github.owner_name }}/{{ site.github.repository_name }}");<\/script>\n`,".gitignore":"# MakeCode\nbuilt\nnode_modules\nyotta_modules\nyotta_targets\npxt_modules\n.pxt\n_site\n*.db\n*.tgz\n.header.json\n.simstate.json\n",".vscode/settings.json":'{\n "editor.formatOnType": true,\n "files.autoSave": "afterDelay",\n "files.watcherExclude": {\n "**/.git/objects/**": true,\n "**/built/**": true,\n "**/node_modules/**": true,\n "**/yotta_modules/**": true,\n "**/yotta_targets": true,\n "**/pxt_modules/**": true,\n "**/.pxt/**": true\n },\n "files.associations": {\n "*.blocks": "html",\n "*.jres": "json"\n },\n "search.exclude": {\n "**/built": true,\n "**/node_modules": true,\n "**/yotta_modules": true,\n "**/yotta_targets": true,\n "**/pxt_modules": true,\n "**/.pxt": true\n },\n "files.exclude": {\n "**/pxt_modules": true,\n "**/.pxt": true\n }\n}',".vscode/extensions.json":'{\n "recommendations": ["ms-edu.pxt-vscode-web"]\n}'},n=i();return n&&Object.keys(n).forEach((t=>e[t]=n[t])),e}function i(){const t=e.appTarget.bundledpkgs[e.template.TEMPLATE_PRJ];if(t){const n=e.Util.clone(t);return delete n[e.CONFIG_NAME],n}}t.TS_CONFIG='{\n "compilerOptions": {\n "target": "ES5",\n "noImplicitAny": true,\n "outDir": "built",\n "rootDir": "."\n },\n "exclude": ["pxt_modules/**/*test.ts"]\n}\n',t.defaultFiles=n,t.targetTemplateFiles=i,t.TEMPLATE_PRJ="template",t.packageFiles=function(t){const i=e.appTarget.blocksprj||e.appTarget.tsprj,s=e.U.clone(i.config);delete s.installedVersion,delete s.additionalFilePath,delete s.additionalFilePaths,s.preferredEditor=s.files.find((e=>/\.blocks$/.test(e)))?e.BLOCKS_PROJECT_NAME:e.JAVASCRIPT_PROJECT_NAME,s.name=t,s.public=!0,s.version||(s.version="0.0.0");const r={},o=n();for(const e in o)r[e]=o[e];for(const e in i.files)"README.md"!=e&&(r[e]=i.files[e]);const a=Object.keys(r).filter((e=>/\.(blocks|md|ts|asm|cpp|h|py)$/.test(e)));return s.files=a.filter((e=>!/test/.test(e))),s.testFiles=a.filter((e=>/test/.test(e))),s.supportedTargets=[e.appTarget.id],r[e.CONFIG_NAME]=e.Package.stringifyConfig(s),r},t.packageFilesFixup=function(t,n){const i=JSON.parse(t[e.CONFIG_NAME]);n&&e.Util.jsonMergeFrom(i,n),e.webConfig&&(Object.keys(e.webConfig).forEach((t=>i[t.toLowerCase()]=e.webConfig[t])),i.platform=e.appTarget.platformid||e.appTarget.id,i.target=e.appTarget.id,i.docs=e.appTarget.appTheme.homeUrl||"./",i.homeurl=e.appTarget.appTheme.homeUrl||"???"),e.U.iterMap(t,((e,n)=>{n=n.replace(/@([A-Z]+)@/g,((e,t)=>i[t.toLowerCase()]||"")),t[e]=n}))}}(e.template||(e.template={}))}(pxt||(pxt={})),function(e){!function(t){let n,i;!function(e){e[e.Prefix=0]="Prefix",e[e.Postfix=1]="Postfix",e[e.Infix=2]="Infix",e[e.Block=3]="Block",e[e.NewLine=4]="NewLine"}(n=t.NT||(t.NT={})),function(e){e[e.None=0]="None",e[e.WithSpace=1]="WithSpace",e[e.NoSpace=2]="NoSpace"}(i=t.GlueMode||(t.GlueMode={}));const s=["break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","import","in","instanceof","new","null","return","super","switch","this","throw","true","try","typeof","var","void","while","with"];function r(e){return"`"+e.replace(/[\\`${}]/g,(e=>"\\"+e))+"`"}function o(e){return e.length>20&&/\n/.test(e)?r(e):JSON.stringify(e)}function a(e,t,n){return{type:e,op:t,children:n}}function l(){return a(n.NewLine,"",[])}function c(e,t){return a(n.Prefix,e,t)}function u(e,t,i){return a(n.Infix,t,null==e?[i]:[e,i])}function d(e){return c(e,[])}function h(e){return a(n.Block,"",e)}function p(e){return c("",e)}function f(e,t=!1){const n=[];for(const i of e)t?(n.length>0&&n.push(d(",")),n.push(l())):n.length>0&&n.push(d(", ")),n.push(i);return t&&n.push(l()),p(n)}let m;t.backtickLit=r,t.stringLit=o,t.mkNode=a,t.mkNewLine=l,t.mkPrefix=c,t.mkPostfix=function(e,t){return a(n.Postfix,t,e)},t.mkInfix=u,t.mkText=d,t.mkBlock=h,t.mkGroup=p,t.mkStmt=function(...e){let t=e[e.length-1];return t&&t.type==n.Block||e.push(l()),p(e)},t.mkCommaSep=f,function(t){function n(e,t,n=!1,i=!1){return p(i?[u(t[0],".",d(e)),d("("),f(t.slice(1),n),d(")")]:[d(e),d("("),f(t,n),d(")")])}function i(e,t,i,s){return n(e+"."+t,i,s)}function s(t,n){return e.U.assert(2==n.length),u(n[0],t,n[1])}t.mkArrayLiteral=function(e,t){return p([d("["),f(e,t),d("]")])},t.mkNumberLiteral=function(e){return d(e.toString())},t.mkBooleanLiteral=function(e){return d(e?"true":"false")},t.mkStringLiteral=function(e){return d(o(e))},t.mkPropertyAccess=function(e,t){return p([u(t,".",d(e))])},t.mkCall=n,t.stdCall=function(e,t,i){return n(e,t,i)},t.extensionCall=function(e,t,i){return n(e,t,i,!0)},t.namespaceCall=i,t.mathCall=function(e,t){return i("Math",e,t,!1)},t.mkGlobalRef=function(e){return d(e)},t.mkSimpleCall=s,t.mkWhile=function(e,t){return p([d("while ("),e,d(")"),h(t)])},t.mkComment=function(e){return d("// "+e)},t.mkMultiComment=function(e){let t=[d("/**"),l()];return e.split("\n").forEach(((e,n,i)=>{e&&(t.push(d(" * "+e)),t.push(l()),n<i.length-1&&(t.push(d(" * ")),t.push(l())))})),p(t.concat([d(" */"),l()]))},t.mkAssign=function(e,t){return s("=",[e,t])},t.mkParenthesizedExpression=function(e){return y(b([e]).output)?e:p([d("("),e,d(")")])}}(m=t.Helpers||(t.Helpers={})),t.H=m;const g={"=":3,"+=":3,"-=":3,"?":4,":":4,"||":5,"&&":6,"|":7,"^":8,"&":9,"==":10,"!=":10,"===":10,"!==":10,"<":11,">":11,"<=":11,">=":11,">>":12,">>>":12,"<<":12,"+":13,"-":13,"*":14,"/":14,"%":14,"**":15,"!":16,"~":16,"P-":16,"P+":16,"++":16,"--":16,".":18};function b(t){let s=[],r={},o="",a="",l=[{}],c=0;function u(e){"string"==typeof e&&(c+=(e.match(/\n/g)||[]).length),o+=e}let h=p(t);return function t(i,s){if(i.type!=n.Infix){for(let e of i.children)t(e,-1);return}let r=[];function o(e){"P"==e[0]&&(e=e.slice(1)),r.push(d(e))}let a=e.U.lookup(g,i.op);if(null==a&&e.U.oops("bad infix op: "+i.op),a<s&&o("("),1==i.children.length)o(i.op),t(i.children[0],a),r.push(i.children[0]);else{let e,n=3!=a&&"**"!=i.op;t(i.children[0],n?a:a+.1),r.push(i.children[0]),e&&"number"!=e&&(o(": "),o(e)),"."==i.op?o("."):o(" "+i.op+" "),t(i.children[1],n?a+.1:a),r.push(i.children[1])}a<s&&o(")"),i.type=n.Prefix,i.op="",i.children=r}(h,-1),f(h),o||u("\n"),{output:o,sourceMap:s};function f(t){t.glueToBlock&&(b(),t.glueToBlock==i.WithSpace&&u(" "));let d=c,h=o.length;switch(t.type){case n.Infix:e.U.oops("no infix should be left");break;case n.NewLine:u("\n"+a);break;case n.Block:!function(t){let n=t.noFinalNewline?"":"\n";if(0==t.children.length)return void m(" {\n\t\n}"+n);let i=e.U.clone(l[l.length-1]||{});l.push(i),a+=" "," "!=o[o.length-1]&&m(" ");m("{\n");for(let e of t.children)f(e);a=a.slice(4),b(),m("\n}"+n),l.pop()}(t);break;case n.Prefix:t.canIndentInside?u(t.op.replace(/\n/g,"\n"+a+" ")):u(t.op),t.children.forEach(f);break;case n.Postfix:t.children.forEach(f),t.canIndentInside?u(t.op.replace(/\n/g,"\n"+a+" ")):u(t.op)}let p=c,g=Math.max(o.length,1);if(t.id)if(r[t.id]){const e=r[t.id];e.startLine=Math.min(e.startLine,d),e.endLine=Math.max(e.endLine,p),e.startPos=Math.min(e.startPos,h),e.endPos=Math.max(e.endPos,g)}else{const e={id:t.id,startLine:d,startPos:h,endLine:p,endPos:g};r[t.id]=e,s.push(e)}}function m(e){u(e.replace(/\n/g,"\n"+a))}function b(){o=o.replace(/\n *$/,(function(){return c--,""}))}}function y(e){if("("!==e[0]||")"!==e[e.length-1])return!1;let t=1;for(let n=1;n<e.length;n++){const i=e[n];if("("===i)t++;else if(")"===i&&(t--,0===t))return n===e.length-1}return!1}t.flattenNode=b,t.isReservedWord=function(e){return-1!==s.indexOf(e)},t.isParenthesized=y}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(t){const n=[".","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];t.BLOCKLY_TILESET_TYPE="BLOCKLY_TILESET_TYPE",t.TILE_PREFIX="tile",t.TILE_NAMESPACE="myTiles",t.IMAGES_NAMESPACE="myImages",t.IMAGE_PREFIX="image",t.ANIMATION_NAMESPACE="myAnimations",t.ANIMATION_PREFIX="anim",t.SONG_NAMESPACE="mySongs",t.SONG_PREFIX="song";class i{constructor(e,t,n=0,i=0,s){this.width=e,this.height=t,this.x0=n,this.y0=i,this.width||(this.width=16),this.height||(this.height=16),this.buf=s||new Uint8ClampedArray(this.dataLength())}static fromData(e){return new i(e.width,e.height,e.x0,e.y0,e.data)}set(e,t,n){if(e<this.width&&t<this.height&&e>=0&&t>=0){const i=this.coordToIndex(e,t);this.setCore(i,n)}}get(e,t){if(e<this.width&&t<this.height&&e>=0&&t>=0){const n=this.coordToIndex(e,t);return this.getCore(n)}return 0}copy(e=0,t=0,n=this.width,s=this.height){const r=new i(n,s);r.x0=e,r.y0=t;for(let i=0;i<n;i++)for(let n=0;n<s;n++)r.set(i,n,this.get(e+i,t+n));return r}apply(e,t=!1){let n;for(let i=0;i<e.width;i++)for(let s=0;s<e.height;s++)n=e.get(i,s),!n&&t||this.set(e.x0+i,e.y0+s,n)}equals(e){if(this.width===e.width&&this.height===e.height&&this.x0===e.x0&&this.y0===e.y0&&this.buf.length===e.buf.length){for(let t=0;t<this.buf.length;t++)if(this.buf[t]!==e.buf[t])return!1;return!0}return!1}data(){return{width:this.width,height:this.height,x0:this.x0,y0:this.y0,data:this.buf}}resize(e,t){return h(this,e,t)}coordToIndex(e,t){return e+t*this.width}getCore(e){const t=Math.floor(e/2);return e%2==0?15&this.buf[t]:(240&this.buf[t])>>4}setCore(e,t){const n=Math.floor(e/2);this.buf[n]=e%2==0?240&this.buf[n]|15&t:15&this.buf[n]|(15&t)<<4}dataLength(){return Math.ceil(this.width*this.height/2)}}t.Bitmap=i;class s extends i{static fromData(e){return new s(e.width,e.height,e.x0,e.y0,e.data)}copy(e=0,t=0,n=this.width,i=this.height){const r=new s(n,i);r.x0=e,r.y0=t;for(let s=0;s<n;s++)for(let n=0;n<i;n++)r.set(s,n,this.get(e+s,t+n));return r}resize(e,t){return p(this,e,t)}getCore(e){return this.buf[e]}setCore(e,t){this.buf[e]=t}dataLength(){return this.width*this.height}}t.Tilemap=s;class r{constructor(e,t,n){this.tilemap=e,this.tileset=t,this.layers=n,this.nextId=0}cloneData(){const e=this.tilemap.copy(),t={tileWidth:this.tileset.tileWidth,tiles:this.tileset.tiles.map((e=>Object.assign(Object.assign({},e),{bitmap:i.fromData(e.bitmap).copy().data()})))},n=i.fromData(this.layers).copy().data();return new r(e,t,n)}equals(t){if(!this.tilemap.equals(t.tilemap)||this.tileset.tileWidth!=t.tileset.tileWidth||this.tileset.tiles.length!=t.tileset.tiles.length||!y(this.layers,t.layers))return!1;for(let n=0;n<this.tileset.tiles.length;n++)if(!e.assetEquals(this.tileset.tiles[n],t.tileset.tiles[n]))return!1;return!0}}t.TilemapData=r;function o(e){return a(atob(e.slice(e.indexOf(",")+1)))}function a(t){let n=t.charCodeAt(0),i=t.charCodeAt(1),s=t.charCodeAt(2);135===n&&(n=224|t.charCodeAt(1),i=t.charCodeAt(2)|t.charCodeAt(3)<<8,s=t.charCodeAt(4)|t.charCodeAt(5)<<8,t=t.slice(4));const r=new e.sprite.Bitmap(i,s);let o=4;if(225===n){let e=1,n=t.charCodeAt(o++);for(let a=0;a<i;++a)for(let i=0;i<s;++i)r.set(a,i,n&e?1:0),e<<=1,256==e&&(e=1,n=t.charCodeAt(o++))}else for(let e=0;e<i;e++){for(let n=0;n<s;n+=2){let i=t.charCodeAt(o++);r.set(e,n,15&i),n!=s-1&&r.set(e,n+1,i>>4&15)}for(;3&o;)o++}return r}function l(e,t){!(e=(e=(e=e.replace(/[ `]|(?:&#96;)|(?:&#9;)|(?:hex)/g,"").trim()).replace(/^["`\(\)]*/,"").replace(/["`\(\)]*$/,"")).replace(/&#10;/g,"\n"))&&t&&(e=t);const n=parseInt(e.substr(0,2),16)|parseInt(e.substr(2,2),16)<<8,i=parseInt(e.substr(4,2),16)|parseInt(e.substr(6,2),16)<<8,r=k(e.substring(8));return s.fromData({width:n,height:i,x0:0,y0:0,data:r})}function c(e){return`${d(e.width,2)}${d(e.height,2)}${x(e.data().data)}`}function u(e,t){return(e=e.replace(/[\[\]]/g,""))?e.split(",").filter((e=>!!e.trim())).map((e=>function(e,t){if(0===(e=e.trim()).indexOf("img")){const n=f(e);return t.createNewTile(n.data())}switch(e){case"myTiles.tile0":case"myTiles.transparency16":return t.getTransparency(16);case"myTiles.transparency8":return t.getTransparency(8);case"myTiles.transparency4":return t.getTransparency(4);case"myTiles.transparency32":return t.getTransparency(32);default:return t.resolveTile(e)}}(e,t))):[]}function d(e,t){let n=e.toString(16);const i=t<<1;for(1&n.length&&(n="0"+n);n.length<i;)n+="0";return n}function h(e,t,n){const s=new i(t,n);return s.apply(e),s}function p(e,t,n){const i=new s(t,n);return i.apply(e),i}function f(e,t="img"){const n=(e=(e=(e=(e=e.replace(/[ `]|(?:&#96;)|(?:&#9;)|(?:img)/g,"").trim()).replaceAll(t,"")).replace(/^["`\(\)]*/,"").replace(/["`\(\)]*$/,"")).replace(/&#10;/g,"\n")).split("\n"),s=[];let r=0;for(let e=0;e<n.length;e++){const t=n[e],i=[];for(let e=0;e<t.length;e++)switch(t[e]){case"0":case".":i.push(0);break;case"1":case"#":i.push(1);break;case"2":case"T":i.push(2);break;case"3":case"t":i.push(3);break;case"4":case"N":i.push(4);break;case"5":case"n":i.push(5);break;case"6":case"G":i.push(6);break;case"7":case"g":i.push(7);break;case"8":i.push(8);break;case"9":i.push(9);break;case"a":case"A":case"R":i.push(10);break;case"b":case"B":case"P":i.push(11);break;case"c":case"C":case"p":i.push(12);break;case"d":case"D":case"O":i.push(13);break;case"e":case"E":case"Y":i.push(14);break;case"f":case"F":case"W":i.push(15);break;default:if(!/\s/.test(t[e]))return}i.length&&(s.push(i),r=Math.max(r,i.length))}const o=s.length,a=new i(r,o);for(let e=0;e<o;e++){const t=s[e];for(let n=0;n<r;n++)n<t.length?a.set(n,e,t[n]):a.set(n,e,0)}return a}function m(e,t="img"){let n="";switch(e){case"python":n=`${t}("""`;break;default:n=`${t}\``}return n}function g(e){let t="";switch(e){case"python":t+='""")';break;default:t+="`"}return t}function b(e,t,i="img"){if(!e||0===e.height||0===e.width)return"";let s=m(t,i);if(e){const t=e.width*e.height>300?"":" ";for(let i=0;i<e.height;i++){s+="\n";for(let r=0;r<e.width;r++)s+=n[e.get(r,i)]+t}}return s+="\n",s+=g(t),s}function y(t,n){return e.sprite.Bitmap.fromData(t).equals(e.sprite.Bitmap.fromData(n))}function v(e){switch(e){case 4:return"TileScale.Four";case 8:return"TileScale.Eight";case 16:return"TileScale.Sixteen";case 32:return"TileScale.ThirtyTwo";default:return Math.floor(Math.log2(e)).toString()}}function w(e){switch(e=e.replace(/\s/g,"")){case"TileScale.Four":return 4;case"TileScale.Eight":return 8;case"TileScale.Sixteen":return 16;case"TileScale.ThirtyTwo":return 32;default:return Math.pow(2,parseInt(e))}}function k(e){let t=new Uint8ClampedArray(e.length>>1);for(let n=0;n<e.length;n+=2)t[n>>1]=parseInt(e.slice(n,n+2),16);return t}function x(e){const t="0123456789abcdef";let n="";for(let i=0;i<e.length;++i)n+=t[e[i]>>4],n+=t[15&e[i]];return n}function A(e,t,n){e[t]=255&n,e[t+1]=n>>8&255}function E(e){const t=function(e){if(e){if(6===e.length)return parseInt("0x"+e);if(7===e.length)return parseInt("0x"+e.substr(1))}return 0}(e);return[T(t),S(t),C(t)]}function T(e){return e>>16&255}function S(e){return e>>8&255}function C(e){return 255&e}t.Bitmask=class{constructor(e,t){this.width=e,this.height=t,this.mask=new Uint8Array(Math.ceil(e*t/8))}set(e,t){const n=e+this.width*t,i=n>>3,s=7&n;this.mask[i]|=1<<s}get(e,t){const n=e+this.width*t,i=n>>3,s=7&n;return this.mask[i]>>s&1}},t.encodeTilemap=function(e,t,n){return e?`tiles.createTilemap(${function(e){return e?`hex\`${c(e)}\``:"hex``"}(e.tilemap)}, ${b(i.fromData(e.layers),t)}, [${e.tileset.tiles.map((e=>function(e,t,n){if(n&&n[e.id])return n[e.id];return e.id}(e,0,n)))}], ${v(e.tileset.tileWidth)})`:"null"},t.decodeTilemap=function(t,n,i){if(!(t=e.Util.htmlUnescape(t).trim()).trim())return null;const s=(t=(t=t.substr(t.indexOf("(")+1)).substr(0,t.lastIndexOf(")"))).substr(0,t.indexOf(",")),o=(t=t.substr(s.length+1)).substr(0,t.indexOf(",")),a=(t=t.substr(o.length+1)).substr(0,t.lastIndexOf("]")+1),c=t=t.substr(a.length+1);return new r(l(s),{tiles:u(a,i),tileWidth:w(c)},f(o).data())},t.trimTilemapTileset=function(e){const t=e.tileset.tiles.slice(),n=e.tilemap,i={};i[t[0].id]=!0;for(let e=0;e<n.width;e++)for(let s=0;s<n.height;s++)i[t[n.get(e,s)].id]=!0;const s=e.editedTiles||[],r=t.filter((e=>i[e.id]||"*"===e.id.charAt(0)||-1!==s.indexOf(e.id)));if(r.length===t.length)return;const o=[];for(let e=0;e<t.length;e++)o.push(r.indexOf(t[e]));for(let e=0;e<n.width;e++)for(let t=0;t<n.height;t++)n.set(e,t,o[n.get(e,t)]);e.tileset.tiles=r},t.isEmptyTilemap=function(e){const t=e.tileset.tiles,n=e.tilemap,i=t[0].id;for(let e=0;e<n.width;e++)for(let s=0;s<n.height;s++)if(t[n.get(e,s)].id!==i)return!1;return!0},t.computeAverageColor=function(e,t){const n=t.map(E),i=[0,0,0];let s=0;for(let t=0;t<e.width;t++)for(let r=0;r<e.height;r++){const o=e.get(t,r);if(o){++s;const e=n[o];i[0]+=e[0],i[1]+=e[1],i[2]+=e[2]}}return s?"#"+function(e){let t="";for(let n=0;n<e.length;++n)t+=("0"+e[n].toString(16)).slice(-2);return t}(i.map((e=>Math.floor(e/s)))):"#00000000"},t.getBitmap=function(e,t){const n=e.apis.byQName[t];return n?o(n.attributes.jresURL):null},t.getBitmapFromJResURL=o,t.hexToBitmap=a,t.filterItems=function(e,t){const n=(t=t.filter((e=>!!e)).map((e=>e.toLowerCase()))).filter((e=>0!==e.indexOf("!"))),i=t.filter((e=>0===e.indexOf("!")&&e.length>1)).map((e=>e.substring(1)));return e.filter((e=>{return t=e,n.every((e=>{const n=`?${e}`;return t.tags.some((t=>t===e||t===n))}))&&function(e){return i.every((t=>!e.tags.some((e=>e===t))))}(e);var t}))},t.getGalleryItems=function(n,i){let s=function(t,n){return e.Util.values(t.byQName).filter((e=>4===e.kind&&e.attributes.fixedInstance&&function(e,t,n){if(t==n)return!0;let i=e.byQName[t];return!(!i||!i.extendsTypes)&&i.extendsTypes.indexOf(n)>=0}(t,e.retType,n)))}(n.apis,i);return s=s.filter((e=>e.namespace!=t.TILE_NAMESPACE)),function(t){const n=new e.ImageConverter;t.forEach((e=>{e.attributes.jresURL&&!e.attributes.iconURL&&0==e.attributes.jresURL.indexOf("data:image/x-mkcd-f")&&(e.attributes.iconURL=n.convert(e.attributes.jresURL))}))}(s),s.map((t=>{const n=(t.attributes.tags||"").split(" ").filter((e=>!!e)).map((t=>e.Util.startsWith(t,"category-")?t:t.toLowerCase()));return{qName:t.qName,src:t.attributes.iconURL,alt:t.qName,tags:n}}))},t.base64EncodeBitmap=function(t){const n=i.fromData(t),s=pxtc.f4EncodeImg(t.width,t.height,4,((e,t)=>n.get(e,t)));return btoa(e.U.uint8ArrayToString(k(s)))},t.tilemapLiteralToTilemap=l,t.hexEncodeTilemap=c,t.formatByte=d,t.resizeBitmap=h,t.resizeTilemap=p,t.imageLiteralToBitmap=f,t.encodeAnimationString=function(t,n){const i=t.map((e=>e.data)),s=new Uint8ClampedArray(8+i[0].length*i.length);A(s,0,n),A(s,2,t[0].width),A(s,4,t[0].height),A(s,6,t.length);let r=8;return i.forEach((e=>{s.set(e,r),r+=e.length})),btoa(e.sprite.uint8ArrayToHex(s))},t.addMissingTilemapTilesAndReferences=function(e,t){const n=e.getProjectTiles(t.data.tileset.tileWidth,!0);t.data.projectReferences=[];for(const i of n.tiles)t.data.tileset.tiles.some((e=>e.id===i.id))||t.data.tileset.tiles.push(i),e.isAssetUsed(i,null,[t.id])&&t.data.projectReferences.push(i.id)},t.updateTilemapReferencesFromResult=function(t,n){const i=n.data;if(i.deletedTiles)for(const e of i.deletedTiles)t.deleteTile(e);if(i.editedTiles)for(const e of i.editedTiles){const n=i.tileset.tiles.findIndex((t=>t.id===e)),s=i.tileset.tiles[n];s&&(i.tileset.tiles[n]=t.updateTile(s))}for(let e=0;e<i.tileset.tiles.length;e++){const n=i.tileset.tiles[e];n.jresData||(i.tileset.tiles[e]=t.resolveTile(n.id))}e.sprite.trimTilemapTileset(i)},t.imageLiteralFromDimensions=function(e,t,i,s){let r=m(s);const o=e*t>300?"":" ";for(let s=0;s<t;s++){r+="\n";for(let t=0;t<e;t++)r+=n[i]+o}return r+="\n",r+=g(s),r},t.bitmapToImageLiteral=b,t.bitmapEquals=y,t.tileWidthToTileScale=v,t.tileScaleToTileWidth=w,t.hexToUint8Array=k,t.uint8ArrayToHex=x,t.colorStringToRGB=E}(e.sprite||(e.sprite={}))}(pxt||(pxt={})),function(e){!function(t){!function(n){const i=new RegExp(`^\\s*${t.TILE_NAMESPACE}\\s*\\.\\s*${t.TILE_PREFIX}(\\d+)\\s*$`);class s{constructor(e,t,n){this.tilemap=e,this.tileset=t,this.layers=n,this.nextId=0}}function r(e){return(e=e.replace(/[\[\]]/g,""))?e.split(",").filter((e=>!!e.trim())).map((e=>function(e){if(0===(e=e.trim()).indexOf("img")){return{data:t.imageLiteralToBitmap(e).data()}}const n=i.exec(e);if(n)return{data:null,projectId:Number(n[1])};return{data:null,qualifiedName:e}}(e))):[]}n.LegacyTilemapData=s,n.decodeTilemap=function(n,i){var o;if(!(null==(n=null===(o=e.Util.htmlUnescape(n))||void 0===o?void 0:o.trim())?void 0:n.trim()))return new s(new t.Tilemap(16,16),{tileWidth:16,tiles:[]},new t.Bitmap(16,16).data());const a=(n=(n=n.substr(n.indexOf("(")+1)).substr(0,n.lastIndexOf(")"))).substr(0,n.indexOf(",")),l=(n=n.substr(a.length+1)).substr(0,n.indexOf(",")),c=(n=n.substr(l.length+1)).substr(0,n.lastIndexOf("]")+1),u=n=n.substr(c.length+1);return new s(t.tilemapLiteralToTilemap(a),{tiles:r(c),tileWidth:t.tileScaleToTileWidth(u)},t.imageLiteralToBitmap(l).data())},n.tileToBlocklyVariable=function(e){return`${e.projectId};${e.data.width};${e.data.height};${pxtc.Util.toHex(e.data.data)}`},n.blocklyVariableToTile=function(e){const t=e.split(";");return 4!==t.length?null:{projectId:parseInt(t[0]),data:{width:parseInt(t[1]),height:parseInt(t[2]),data:new Uint8ClampedArray(pxtc.Util.fromHex(t[3])),x0:0,y0:0}}}}(t.legacy||(t.legacy={}))}(e.sprite||(e.sprite={}))}(pxt||(pxt={})),function(e){!function(t){class n{constructor(){this.items={}}removeItem(e){delete this.items[e]}getItem(e){return this.items[e]}setItem(e,t){this.items[e]=t}clear(){this.items={}}}class i{constructor(e){this.storageId=e,this.type="localstorage"}targetKey(e){return this.storageId+"/"+e}removeItem(e){window.localStorage.removeItem(this.targetKey(e))}getItem(e){return window.localStorage[this.targetKey(e)]}setItem(e,t){window.localStorage[this.targetKey(e)]=t}clear(){let e=this.targetKey(""),t=[];for(let n=0;n<window.localStorage.length;++n){let i=window.localStorage.key(n);0==i.indexOf(e)&&t.push(i)}t.forEach((e=>window.localStorage.removeItem(e)))}}function s(){if(e.appTarget)return e.appTarget.id;const t=window.pxtConfig;if(t)return t.targetId;const n=window.pxtTargetBundle;return n?n.id:""}let r;function o(){if(r)return;const t=s();let o=!1;if(!e.shell.isSandboxMode())try{const n=e.Util.guidGen();window.localStorage[t]=n;o=window.localStorage[t]===n}catch(e){}o?(r=new i(t),e.debug(`storage: local under ${t}`)):(r=new n,e.debug("storage: in memory"))}t.storageId=s,t.setLocal=function(e,t){o(),r.setItem(e,t)},t.getLocal=function(e){return o(),r.getItem(e)},t.removeLocal=function(e){o(),r.removeItem(e)},t.clearLocal=function(){o(),r.clear()}}(e.storage||(e.storage={}))}(pxt||(pxt={})),function(e){!function(t){!function(t){const n="http://localhost:3232/api/store/";function i(){return e.BrowserUtils.isLocalHostDev()&&!e.BrowserUtils.noSharedLocalStorage()}function s(){return e.BrowserUtils.isChromiumEdge()?"chromium-edge":e.BrowserUtils.browser()}t.getAsync=async function(t,r){if(i()){t+="-"+s();const i=await e.Util.requestAsync({url:`${n}${encodeURIComponent(t)}/${encodeURIComponent(r)}`,method:"GET",allowHttpErrors:!0});if(204===i.statusCode)throw new Error(`Missing ${r} not available in ${t}`);return i.json?i.json:i.text?i.text:void 0}{const n=e.storage.getLocal(`${t}:${r}`),i=e.Util.jsonTryParse(n);return i||n}},t.setAsync=async function(t,r,o){if(void 0===o)return void await e.storage.shared.delAsync(t,r);let a="";if(a="object"==typeof o?JSON.stringify(o):o.toString(),i()){t+="-"+s();const i={type:"object"==typeof o?"json":"text",val:a},l=JSON.stringify(i);await e.Util.requestAsync({url:`${n}${encodeURIComponent(t)}/${encodeURIComponent(r)}`,method:"POST",data:l})}else e.storage.setLocal(`${t}:${r}`,a)},t.delAsync=async function(t,r){i()?(t+="-"+s(),await e.Util.requestAsync({url:`${n}${encodeURIComponent(t)}/${encodeURIComponent(r)}`,method:"DELETE",allowHttpErrors:!0})):e.storage.removeLocal(`${t}:${r}`)}}(t.shared||(t.shared={}))}(e.storage||(e.storage={}))}(pxt||(pxt={})),function(e){function t(e){let t=0;for(let n=0;n<e.length;n++)if(" "===e.charAt(n))t++;else{if("\t"!==e.charAt(n))return t;t+=4}return 0}e.getSectionsFromMarkdownMetadata=function(e){const n=e.split(/\r?\n/);let i=[],s=null,r=null,o=null,a=[],l=0;for(const e of n)if(e.trim()){if(e.startsWith("#")){const t=/^(#+)\s*(.+)$/.exec(e);if(t){c(),s={headerKind:1===t[1].length?"single":2===t[1].length?"double":"triple",header:t[2],attributes:{}},r=null,o=null,l=0;continue}}if(s){const n=t(e),i=e.trim(),c=/^[*-]\s+(?:([^:]+):)?(.*)$/.exec(i);if(!c)continue;if(Math.abs(n-l)>1&&r){if(n>l){const e={key:r,items:[]};a.length?a[a.length-1].items.push(e):(s.listAttributes||(s.listAttributes={}),s.listAttributes[r]=e),r=null,a.push(e)}else{const e=a.pop();r&&o&&(null==e||e.items.push((r+":"+o).trim()),o=null)}l=n}c&&(c[1]?(r&&o&&(a.length?a[a.length-1].items.push((r+":"+o).trim()):s.attributes[r]=o.trim()),r=c[1].toLowerCase(),o=c[2]):r&&(o+=c[2]))}}else o&&(o+="\n");return c(),i;function c(){s&&(r&&o&&(a.length?a[a.length-1].items.push((r+":"+o).trim()):s.attributes[r]=o.trim()),i.push(s)),a=[]}}}(pxt||(pxt={})),function(e){!function(t){let n;!function(e){e[e.PROD=0]="PROD",e[e.STAGING=1]="STAGING",e[e.LOCAL=2]="LOCAL"}(n||(n={}));let i=n.STAGING;t.ABSOLUTE_LINKS={PROD_BETA:"https://arcade.makecode.com/beta--multiplayer",STAGING_BETA:"https://arcade.staging.pxt.io/beta--multiplayer",LOCAL:"http://localhost:3000"},t.RELATIVE_LINKS={PROD:"/--multiplayer",BETA:"/beta--multiplayer"},t.SHORT_LINKS={PROD:"https://aka.ms/a9",PROD_BETA:"https://aka.ms/a9b",STAGING:"https://aka.ms/a9s",STAGING_BETA:"https://aka.ms/a9sb"},t.RELATIVE_LINK=()=>{if(e.BrowserUtils.isLocalHostDev())switch(i){case n.PROD:return t.ABSOLUTE_LINKS.PROD_BETA;case n.STAGING:return t.ABSOLUTE_LINKS.STAGING_BETA;case n.LOCAL:return t.ABSOLUTE_LINKS.LOCAL}return window.location.pathname.startsWith("/beta")?t.RELATIVE_LINKS.BETA:t.RELATIVE_LINKS.PROD},t.SHORT_LINK=()=>{if(e.BrowserUtils.isLocalHostDev())switch(i){case n.PROD:return t.SHORT_LINKS.PROD_BETA;case n.STAGING:return t.SHORT_LINKS.STAGING_BETA;case n.LOCAL:return t.ABSOLUTE_LINKS.LOCAL}return window.location.host.endsWith(".staging.pxt.io")?window.location.pathname.startsWith("/beta")?t.SHORT_LINKS.STAGING_BETA:t.SHORT_LINKS.STAGING:window.location.pathname.startsWith("/beta")?t.SHORT_LINKS.PROD_BETA:t.SHORT_LINKS.PROD},t.makeHostLink=function(e,n){return`${n?t.SHORT_LINK():t.RELATIVE_LINK()}?host=${encodeURIComponent(e)}`},t.makeJoinLink=function(e,n){return`${n?t.SHORT_LINK():t.RELATIVE_LINK()}?join=${encodeURIComponent(e)}`}}(e.multiplayer||(e.multiplayer={}))}(pxt||(pxt={})),function(e){!function(t){!function(t){function n(e,t,n){const i=new Uint8Array(2);new Uint16Array(i.buffer)[0]=0|n,e[t]=i[0],e[t+1]=i[1]}function i(e,t){const n=new Uint8Array(2);return n[0]=e[t],n[1]=e[t+1],new Uint16Array(n.buffer)[0]}function s(e){const t=new Uint8Array(5+7*e.steps.length);t[0]=e.steps.length,n(t,1,e.startFrequency),n(t,3,e.startVolume);for(let i=0;i<e.steps.length;i++){const s=5+7*i;t[s]=e.steps[i].waveform,n(t,s+1,e.steps[i].frequency),n(t,s+3,e.steps[i].volume),n(t,s+5,e.steps[i].duration)}return t}function r(e,t,i){const s=new Uint8Array(5+e.notes.length);n(s,0,e.startTick),n(s,2,e.endTick),s[4]=e.notes.length;for(let n=0;n<e.notes.length;n++)s[5+n]=o(e.notes[n],t,i);return s}function o(e,t,n){if(n)return e.note;let i=0;return"flat"===e.enharmonicSpelling?i=1:"sharp"===e.enharmonicSpelling&&(i=2),e.note-12*(t-2)|i<<6}function a(e){return e.drums?function(e){const t=e.drums.map(s),i=t.reduce(((e,t)=>t.length+e),0),o=e.notes.map((e=>r(e,0,!0))),a=o.reduce(((e,t)=>t.length+e),0),l=new Uint8Array(6+i+a);l[0]=e.id,l[1]=1,n(l,2,i);let c=4;for(const e of t)l.set(e,c),c+=e.length;n(l,c,a),c+=2;for(const e of o)l.set(e,c),c+=e.length;return l}(e):function(e){const t=function(e){var t,i,s,r,o,a,l,c,u;const d=new Uint8Array(28);return d[0]=e.waveform,n(d,1,e.ampEnvelope.attack),n(d,3,e.ampEnvelope.decay),n(d,5,e.ampEnvelope.sustain),n(d,7,e.ampEnvelope.release),n(d,9,e.ampEnvelope.amplitude),n(d,11,(null===(t=e.pitchEnvelope)||void 0===t?void 0:t.attack)||0),n(d,13,(null===(i=e.pitchEnvelope)||void 0===i?void 0:i.decay)||0),n(d,15,(null===(s=e.pitchEnvelope)||void 0===s?void 0:s.sustain)||0),n(d,17,(null===(r=e.pitchEnvelope)||void 0===r?void 0:r.release)||0),n(d,19,(null===(o=e.pitchEnvelope)||void 0===o?void 0:o.amplitude)||0),d[21]=(null===(a=e.ampLFO)||void 0===a?void 0:a.frequency)||0,n(d,22,(null===(l=e.ampLFO)||void 0===l?void 0:l.amplitude)||0),d[24]=(null===(c=e.pitchLFO)||void 0===c?void 0:c.frequency)||0,n(d,25,(null===(u=e.pitchLFO)||void 0===u?void 0:u.amplitude)||0),d[27]=e.octave,d}(e.instrument),i=e.notes.map((t=>r(t,e.instrument.octave,!1))),s=i.reduce(((e,t)=>t.length+e),0),o=new Uint8Array(6+t.length+s);o[0]=e.id,o[1]=0,n(o,2,t.length);let a=4;o.set(t,a),a+=t.length,n(o,a,s),a+=2;for(const e of i)o.set(e,a),a+=e.length;return o}(e)}function l(e,t){return{waveform:e[t],ampEnvelope:{attack:i(e,t+1),decay:i(e,t+3),sustain:i(e,t+5),release:i(e,t+7),amplitude:i(e,t+9)},pitchEnvelope:{attack:i(e,t+11),decay:i(e,t+13),sustain:i(e,t+15),release:i(e,t+17),amplitude:i(e,t+19)},ampLFO:{frequency:e[t+21],amplitude:i(e,22)},pitchLFO:{frequency:e[t+24],amplitude:i(e,25)},octave:e[t+27]}}function c(e,t){return e[t+1]?function(e,t){const n={id:e[t],instrument:{ampEnvelope:{attack:0,decay:0,sustain:0,release:0,amplitude:0},waveform:0},notes:[],drums:[]},s=i(e,t+2);let r=t+4;for(;r<t+4+s;)n.drums.push(u(e,r)),r+=5+7*n.drums[n.drums.length-1].steps.length;const o=i(e,r);r+=2;for(;r<t+4+s+o;)n.notes.push(d(e,r,0,!0)),r+=5+n.notes[n.notes.length-1].notes.length;return[n,r]}(e,t):function(e,t){const n={id:e[t],instrument:l(e,t+4),notes:[]},s=t+4+i(e,t+2),r=i(e,s);let o=s+2;for(;o<s+2+r;)n.notes.push(d(e,o,n.instrument.octave,!1)),o+=5+n.notes[n.notes.length-1].notes.length;return[n,o]}(e,t)}function u(e,t){const n={startFrequency:i(e,t+1),startVolume:i(e,t+3),steps:[]};for(let s=0;s<e[t];s++){const r=t+5+7*s;n.steps.push({waveform:e[r],frequency:i(e,r+1),volume:i(e,r+3),duration:i(e,r+5)})}return n}function d(e,t,n,s){const r={startTick:i(e,t),endTick:i(e,t+2),notes:[]};for(let i=0;i<e[t+4];i++)r.notes.push(h(e[t+5+i],n,s));return r}function h(e,t,n){const i=e>>6,s={note:n?e:(63&e)+12*(t-2),enharmonicSpelling:"normal"};return 1===i?s.enharmonicSpelling="flat":2===i&&(s.enharmonicSpelling="sharp"),s}function p(e,t){if(typeof e!=typeof t)return!1;if("object"!=typeof e)return e===t;if(Array.isArray(e)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!p(e[n],t[n]))return!1;return!0}const n=Object.keys(e),i=Object.keys(t);if(n.length!==i.length)return!1;for(const s of n){if(-1===i.indexOf(s))return!1;if(!p(e[s],t[s]))return!1}return!0}function f(e){return{ticksPerBeat:8,beatsPerMeasure:4,beatsPerMinute:120,measures:e,tracks:[{id:0,name:lf("Dog"),notes:[],iconURI:"music-editor/dog.png",instrument:{waveform:1,octave:4,ampEnvelope:{attack:10,decay:100,sustain:500,release:100,amplitude:1024},pitchLFO:{frequency:5,amplitude:0}}},{id:1,name:lf("Duck"),notes:[],iconURI:"music-editor/duck.png",instrument:{waveform:15,octave:4,ampEnvelope:{attack:5,decay:530,sustain:705,release:450,amplitude:1024},pitchEnvelope:{attack:5,decay:40,sustain:0,release:100,amplitude:40},ampLFO:{frequency:3,amplitude:20},pitchLFO:{frequency:6,amplitude:2}}},{id:2,name:lf("Cat"),notes:[],iconURI:"music-editor/cat.png",instrument:{waveform:12,octave:5,ampEnvelope:{attack:150,decay:100,sustain:365,release:400,amplitude:1024},pitchEnvelope:{attack:120,decay:300,sustain:0,release:100,amplitude:50},pitchLFO:{frequency:10,amplitude:6}}},{id:3,name:lf("Fish"),notes:[],iconURI:"music-editor/fish.png",instrument:{waveform:1,octave:3,ampEnvelope:{attack:220,decay:105,sustain:1024,release:350,amplitude:1024},ampLFO:{frequency:5,amplitude:100},pitchLFO:{frequency:1,amplitude:4}}},{id:4,name:lf("Car"),notes:[],iconURI:"music-editor/car.png",instrument:{waveform:16,octave:4,ampEnvelope:{attack:5,decay:100,sustain:1024,release:30,amplitude:1024},pitchLFO:{frequency:10,amplitude:4}}},{id:5,name:lf("Computer"),notes:[],iconURI:"music-editor/computer.png",instrument:{waveform:15,octave:2,ampEnvelope:{attack:10,decay:100,sustain:500,release:10,amplitude:1024}}},{id:6,name:lf("Burger"),notes:[],iconURI:"music-editor/burger.png",instrument:{waveform:1,octave:2,ampEnvelope:{attack:10,decay:100,sustain:500,release:100,amplitude:1024}}},{id:7,name:lf("Cherry"),notes:[],iconURI:"music-editor/cherry.png",instrument:{waveform:2,octave:3,ampEnvelope:{attack:10,decay:100,sustain:500,release:100,amplitude:1024}}},{id:8,name:lf("Lemon"),notes:[],iconURI:"music-editor/lemon.png",instrument:{waveform:14,octave:2,ampEnvelope:{attack:5,decay:70,sustain:870,release:50,amplitude:1024},pitchEnvelope:{attack:10,decay:45,sustain:0,release:100,amplitude:20},ampLFO:{frequency:1,amplitude:50},pitchLFO:{frequency:2,amplitude:1}}},{id:9,name:lf("Drums"),notes:[],iconURI:"music-editor/explosion.png",instrument:{waveform:11,octave:4,ampEnvelope:{attack:10,decay:100,sustain:500,release:100,amplitude:1024}},drums:[{startFrequency:100,startVolume:1024,steps:[{waveform:3,frequency:120,duration:10,volume:1024},{waveform:3,frequency:1,duration:100,volume:0}]},{startFrequency:200,startVolume:1024,steps:[{frequency:0,volume:0,duration:100,waveform:1}]},{startFrequency:100,startVolume:1024,steps:[{frequency:0,volume:0,duration:250,waveform:1}]},{startFrequency:175,startVolume:1024,steps:[{waveform:1,frequency:200,duration:10,volume:1024},{waveform:1,frequency:150,duration:20,volume:1024},{waveform:5,frequency:1,duration:20,volume:100},{waveform:5,frequency:1,duration:300,volume:0}]},{startFrequency:220,startVolume:1024,steps:[{waveform:1,frequency:250,duration:10,volume:1024},{waveform:1,frequency:200,duration:20,volume:1024},{waveform:5,frequency:2e3,duration:20,volume:100},{waveform:5,frequency:2e3,duration:200,volume:0}]},{startFrequency:400,startVolume:500,steps:[{frequency:450,volume:500,duration:10,waveform:5},{frequency:400,volume:20,duration:20,waveform:5}]},{startFrequency:400,startVolume:0,steps:[{frequency:450,volume:500,duration:5,waveform:5},{frequency:900,volume:5,duration:50,waveform:5},{frequency:900,volume:0,duration:250,waveform:5}]},{startFrequency:400,startVolume:0,steps:[{frequency:450,volume:500,duration:5,waveform:5},{frequency:900,volume:200,duration:50,waveform:5},{frequency:900,volume:5,duration:100,waveform:5},{frequency:900,volume:0,duration:400,waveform:5}]},{startFrequency:400,startVolume:0,steps:[{frequency:450,volume:500,duration:5,waveform:5},{frequency:900,volume:200,duration:100,waveform:5},{frequency:900,volume:5,duration:200,waveform:5},{frequency:900,volume:0,duration:500,waveform:5}]},{startFrequency:3500,startVolume:1024,steps:[{frequency:4e3,volume:0,duration:10,waveform:4},{frequency:3500,volume:800,duration:1,waveform:4},{frequency:4e3,volume:0,duration:40,waveform:4},{frequency:3500,volume:400,duration:1,waveform:4},{frequency:4e3,volume:0,duration:40,waveform:4}]},{startFrequency:2e3,startVolume:1024,steps:[{frequency:1800,volume:15,duration:100,waveform:4},{frequency:1800,volume:0,duration:200,waveform:4}]},{startFrequency:200,startVolume:200,steps:[{frequency:125,volume:200,duration:25,waveform:14},{frequency:100,volume:15,duration:50,waveform:14},{frequency:120,volume:0,duration:250,waveform:14}]},{startFrequency:300,startVolume:200,steps:[{frequency:225,volume:200,duration:25,waveform:14},{frequency:200,volume:15,duration:50,waveform:14},{frequency:220,volume:0,duration:250,waveform:14}]},{startFrequency:500,startVolume:200,steps:[{frequency:425,volume:200,duration:25,waveform:14},{frequency:400,volume:15,duration:50,waveform:14},{frequency:420,volume:0,duration:250,waveform:14}]},{startFrequency:200,startVolume:1024,steps:[{frequency:75,volume:0,duration:200,waveform:1}]},{startFrequency:300,startVolume:1024,steps:[{frequency:200,volume:0,duration:200,waveform:1}]},{startFrequency:400,startVolume:1024,steps:[{frequency:300,volume:0,duration:200,waveform:1}]},{startFrequency:200,startVolume:1024,steps:[{frequency:200,volume:15,duration:100,waveform:4},{frequency:150,volume:0,duration:200,waveform:4}]},{startFrequency:450,startVolume:1024,steps:[{frequency:350,volume:15,duration:100,waveform:4},{frequency:300,volume:0,duration:100,waveform:4}]},{startFrequency:2500,startVolume:1024,steps:[{frequency:2500,volume:100,duration:150,waveform:4},{frequency:2550,volume:0,duration:500,waveform:4}]},{startFrequency:3e3,startVolume:1024,steps:[{frequency:3e3,volume:100,duration:300,waveform:4},{frequency:3060,volume:0,duration:500,waveform:4}]},{startFrequency:800,startVolume:0,steps:[{frequency:800,volume:1024,duration:10,waveform:4},{frequency:800,volume:0,duration:490,waveform:4}]},{startFrequency:400,startVolume:0,steps:[{frequency:400,volume:1024,duration:10,waveform:4},{frequency:400,volume:0,duration:400,waveform:4}]},{startFrequency:2e3,startVolume:1024,steps:[{frequency:2e3,volume:100,duration:150,waveform:16},{frequency:2e3,volume:0,duration:200,waveform:16}]}]}]}}t.encodeSongToHex=function(t){const i=function(e){const t=e.tracks.filter((e=>e.notes.length>0)).map(a),i=t.reduce(((e,t)=>t.length+e),0),s=new Uint8Array(7+i);s[0]=0,n(s,1,e.beatsPerMinute),s[3]=e.beatsPerMeasure,s[4]=e.ticksPerBeat,s[5]=e.measures,s[6]=t.length;let r=7;for(const e of t)s.set(e,r),r+=e.length;return s}(t);return e.U.toHex(i)},t.decodeSongFromHex=function(t){return function(e){const t={beatsPerMinute:i(e,1),beatsPerMeasure:e[3],ticksPerBeat:e[4],measures:e[5],tracks:[]};let n=7;for(;n<e.length;){const[i,s]=c(e,n);n=s,t.tracks.push(i)}return t}(e.U.fromHex(t))},t.cloneSong=function(e){return Object.assign(Object.assign({},e),{tracks:e.tracks.map((e=>Object.assign(Object.assign({},e),{instrument:e.instrument&&Object.assign(Object.assign({},e.instrument),{ampEnvelope:Object.assign({},e.instrument.ampEnvelope),pitchEnvelope:e.instrument.pitchEnvelope&&Object.assign({},e.instrument.pitchEnvelope),ampLFO:e.instrument.ampLFO&&Object.assign({},e.instrument.ampLFO),pitchLFO:e.instrument.pitchLFO&&Object.assign({},e.instrument.pitchLFO)}),drums:e.drums&&e.drums.map((e=>Object.assign(Object.assign({},e),{steps:e.steps.map((e=>Object.assign({},e)))}))),notes:e.notes.map((e=>Object.assign(Object.assign({},e),{notes:e.notes.slice()})))})))})},t.songEquals=function(e,t){return p(e,t)},t.inflateSong=function(e){const t=f(1);e.tracks=t.tracks.map(((t,n)=>{const i=e.tracks.find((e=>e.id===n));return i&&(t.notes=i.notes),t}))},t.getSongInfo=function(e){return{ticksPerBeat:e.ticksPerBeat,beatsPerMeasure:e.beatsPerMeasure,beatsPerMinute:e.beatsPerMinute,measures:e.measures}},t.getEmptySong=f}(t.music||(t.music={}))}(e.assets||(e.assets={}))}(pxt||(pxt={})),function(e){const t=["name","version","description","license","dependencies","files","testFiles","testDependencies","fileDependencies","public","targetVersions","supportedTargets","preferredEditor","languageRestriction","additionalFilePath","additionalFilePaths"];class n{constructor(e,t,n,i,s){this.id=e,this._verspec=t,this.parent=n,this.depName=s,this.level=-1,this.isLoaded=!1,this.ignoreTests=!1,this.cppOnly=!1,i&&(this.level=i.level+1),this.addedBy=[i]}static stringifyConfig(e){const n=e,i={};for(const e of t)n.hasOwnProperty(e)&&(i[e]=n[e]);for(const e of Object.keys(n))i.hasOwnProperty(e)||(i[e]=n[e]);return JSON.stringify(i,null,4)+"\n"}static parseAndValidConfig(t){const n=e.Util.jsonTryParse(t);return n&&void 0!==n.name&&"string"==typeof n.name&&n.files&&Array.isArray(n.files)&&n.files.every((e=>"string"==typeof e))&&n.dependencies&&Object.keys(n.dependencies).every((e=>"string"==typeof n.dependencies[e]))&&n}static async getConfigAsync(t,n,i){if(e.github.isGithubId(i)){const t=e.github.parseRepoId(i),n=await e.packagesConfigAsync();return await e.github.repoAsync(t.fullName,n)?await e.github.pkgConfigAsync(t.fullName,t.tag,n):null}if(i.startsWith("workspace:")){i.slice("workspace:".length);return null}if(!i.startsWith("pub:")){const s=e.patching.upgradePackageReference(t,n,i),r=e.appTarget.bundledpkgs[s];return JSON.parse(r[e.CONFIG_NAME])}{const t=i.slice("pub:".length);try{const n=await e.Cloud.downloadScriptFilesAsync(t);return JSON.parse(n[e.CONFIG_NAME])}catch(t){return e.log(`Unable to fetch files for published script '${i}'`),null}}}static corePackages(){const t=e.appTarget.bundledpkgs;return Object.keys(t).map((n=>JSON.parse(t[n][e.CONFIG_NAME]))).filter((e=>!!e))}disablesVariant(e){return this.config&&this.config.disablesVariants&&this.config.disablesVariants.indexOf(e)>=0}invalid(){return/^invalid:/.test(this.version())}version(){return this.resolvedVersion||this._verspec}verProtocol(){let e=this.version().split(":");return e.length>1?e[0]:""}verArgument(){let e=this.verProtocol();return e?this.version().slice(e.length+1):this.version()}targetVersion(){return this.parent&&this.parent!=this?this.parent.targetVersion():this.config.targetVersions?this.config.targetVersions.target:void 0}async commonDownloadAsync(){const t=this.verProtocol();let n;if("pub"==t)n=await e.Cloud.downloadScriptFilesAsync(this.verArgument());else if("github"==t){const t=await e.packagesConfigAsync();n=(await e.github.downloadPackageAsync(this.verArgument(),t)).files}else if("embed"==t)n=e.getEmbeddedScript(this.verArgument());else if("pkg"==t){const t=(this.parent||this).readFile(this.verArgument()),i=e.U.jsonTryParse(t);i||e.log(`unable to find ${this.verArgument()}`),n=i}return n}writeAssetPackFiles(){const t=JSON.parse(JSON.stringify(this.config));t.files=t.files.filter((e=>e.endsWith(".jres"))),t.files.push("gallery.ts"),t.dependencies={},t.assetPack=!0,this.config=t,this.saveConfig();let n="";for(const i of t.files){const t=this.readFile(i),s=e.U.jsonTryParse(t);if(s){const[t,r]=e.emitGalleryDeclarations(s,this.getNamespaceName());this.writeFile(i,JSON.stringify(t,null,4)),n+=r}}this.writeFile("gallery.ts",n)}getNamespaceName(){let e=this,t=e.addedBy[0];const n=[];for(;t&&t!==e;)e.depName&&n.push(e.depName),e=t,t=e.addedBy[0];return n.reverse().map((e=>ts.pxtc.escapeIdentifier(e))).join(".")}host(){return this.parent._host}readFile(e){return this.host().readFile(this,e)}writeFile(e,t){this.host().writeFile(this,e,t,!0)}readGitJson(){const t=this.readFile(e.github.GIT_JSON);return e.Util.jsonTryParse(t)}resolveDep(e){return this.parent.deps.hasOwnProperty(e)?this.parent.deps[e]:null}saveConfig(){const t=e.U.clone(this.config);delete t.additionalFilePaths;const n=e.Package.stringifyConfig(t);this.host().writeFile(this,e.CONFIG_NAME,n)}setPreferredEditor(e){this.config.preferredEditor!=e&&(this.config.preferredEditor=e,this.saveConfig())}getPreferredEditor(){let t=this.config.preferredEditor;if(!t){if(!(this.getFiles().indexOf(e.MAIN_BLOCKS)>=0))return e.JAVASCRIPT_PROJECT_NAME;const t=this.readFile(e.MAIN_BLOCKS),n=this.readFile(e.MAIN_TS);return!t&&n?e.JAVASCRIPT_PROJECT_NAME:e.BLOCKS_PROJECT_NAME}return t}parseJRes(t={}){for(const n of this.getFiles())e.U.endsWith(n,".jres")&&i(JSON.parse(this.readFile(n)),t);return t}isAssetPack(){var e;return this.level>0&&!!(null===(e=this.config)||void 0===e?void 0:e.assetPack)}resolveVersionAsync(){var t;let n=this._verspec;if(e.getEmbeddedScript(this.id))this.resolvedVersion=n="embed:"+this.id;else if(n&&"*"!=n){if("github"==this.verProtocol()){const i=e.github.parseRepoId(this._verspec);if(i&&!i.tag&&this.parent){e.debug("dep: unbound github extensions, trying to resolve tag");const s=e.semver.sortLatestTags(e.Util.values((null===(t=this.parent)||void 0===t?void 0:t.deps)||{}).map((t=>e.github.parseRepoId(t.version()))).filter((e=>(null==e?void 0:e.slug)===i.slug)).map((e=>e.tag)))[0];s&&(i.tag=s,this.resolvedVersion=n=e.github.stringifyRepo(i),e.debug(`dep: github patched ${this._verspec} to ${n}`))}}}else this.configureAsInvalidPackage(lf("version not specified for {0}",this.id)),n=this._verspec;return Promise.resolve(n)}downloadAsync(){return this.resolveVersionAsync().then((t=>{if(this.invalid())e.debug(`skip download of invalid package ${this.id}`);else if(/^embed:/.test(t)||this.installedVersion!=t)return e.debug("downloading "+t),this.host().downloadPackageAsync(this).then((()=>{this.loadConfig(),this.isAssetPack()&&this.writeAssetPackFiles(),e.debug(`installed ${this.id} /${t}`)}))}))}loadConfig(){if(0!=this.level&&this.invalid())return;const t=this.readFile(e.CONFIG_NAME);t||e.U.userError(`extension ${this.id} is missing ${e.CONFIG_NAME}`),this.parseConfig(t),0!=this.level&&(this.installedVersion=this.version()),this.saveConfig()}validateConfig(){this.config.dependencies||e.U.userError("Missing dependencies in config of: "+this.id),Array.isArray(this.config.files)||e.U.userError("Missing files in config of: "+this.id),"string"==typeof this.config.name&&this.config.name||(this.config.name=lf("Untitled")),this.config.targetVersions&&this.config.targetVersions.target&&this.config.targetVersions.targetId===e.appTarget.id&&e.appTarget.versions&&e.semver.majorCmp(this.config.targetVersions.target,e.appTarget.versions.target)>0&&e.U.userError(lf("{0} requires target version {1} (you are running {2})",this.config.name,this.config.targetVersions.target,e.appTarget.versions.target))}isPackageInUse(t,n=this.readFile(e.MAIN_TS)){let i=null;const s=e.patching.computePatches(this.targetVersion(),"missingPackage");return s&&s.forEach((e=>{Object.keys(e.map).forEach((n=>{e.map[n]===t&&(i=new RegExp(n,"g"))}))})),i||(i=new RegExp(t+"\\.","g")),i.test(n)}upgradePackagesAsync(){return this.config||this.loadConfig(),e.packagesConfigAsync().then((t=>{let n=0,i={};return e.U.iterMap(this.config.dependencies,((s,r)=>{if(e.github.isGithubId(r)){const o=e.github.upgradedPackageReference(t,r);o&&o!=r&&(e.log(`upgrading dep ${s}: ${r} -> ${o}`),i[r]=o,this.config.dependencies[s]=o,n++)}})),n&&this.saveConfig(),n&&i}))}getMissingPackages(t,n){const i=e.patching.computePatches(this.targetVersion(),"missingPackage"),s={};return n&&i&&i.forEach((e=>{Object.keys(e.map).forEach((i=>{const r=new RegExp(i,"g"),o=e.map[i];n.replace(r,(e=>(t.dependencies[o]||(s[o]="*"),"")))}))})),s}findConflictsAsync(t,i){let s,r=[];return Promise.resolve().then((()=>"string"==typeof t?n.getConfigAsync(this.targetVersion(),t,i):Promise.resolve(t))).then((t=>{var n;if(s=t,s){const t=s.yotta?e.U.jsonFlatten(s.yotta.config):null;this.parent.sortedDeps().forEach((n=>{if(s.core&&n.config.core&&s.name!=n.config.name){const t=new e.cpp.PkgConflictError(lf("conflict between core extensions {0} and {1}",s.name,n.id));return t.pkg0=n,void r.push(t)}let o=!1;if(t){const i=n.config||JSON.parse(n.readFile(e.CONFIG_NAME));if(!!i&&!!i.yotta&&!!n.config.yotta.config){const a=e.U.jsonFlatten(i.yotta.config);for(const l of Object.keys(t)){const c=a[l],u=s.yotta.configIsJustDefaults||i.yotta.configIsJustDefaults;if(a.hasOwnProperty(l)&&c!==t[l]&&!u&&(!n.parent.config.yotta||!n.parent.config.yotta.ignoreConflicts)){const t=new e.cpp.PkgConflictError(lf("conflict on yotta setting {0} between extensions {1} and {2}",l,s.name,n.id));t.pkg0=n,t.settingName=l,r.push(t),o=!0}}}}if(!o&&s.name===n.id&&n._verspec!==i&&!/^file:/.test(n._verspec)&&!/^file:/.test(i)){const t=/^github:/.test(n._verspec)&&e.github.parseRepoId(n._verspec),s=/^github:/.test(i)&&e.github.parseRepoId(i);if(!t||!s||t.fullName!==s.fullName||s.tag&&e.semver.strcmp(t.tag,s.tag)<0){const t=new e.cpp.PkgConflictError(lf("version mismatch for extension {0} (added: {1}, adding: {2})",n.id,n._verspec,i));t.pkg0=n,t.isVersionConflict=!0,r.push(t)}}}))}return Object.keys(null!==(n=null==s?void 0:s.dependencies)&&void 0!==n?n:{}).reduce(((e,t)=>e.then((()=>this.findConflictsAsync(t,s.dependencies[t]))).then((e=>r.push.apply(r,e)))),Promise.resolve())})).then((()=>{const t=e=>{const n=[];return e.addedBy.forEach((e=>{e.id!==this.id&&(n.push.apply(t(e)),n.push(e))})),n},n=[];return r.forEach((r=>{n.push.apply(n,t(r.pkg0).map((t=>{const n=new e.cpp.PkgConflictError(r.isVersionConflict?lf("a dependency of {0} has a version mismatch with extension {1} (added: {1}, adding: {2})",t.id,s.name,r.pkg0._verspec,i):lf("conflict on yotta setting {0} between extensions {1} and {2}",r.settingName,s.name,r.pkg0.id));return n.pkg0=t,n})))})),r.push.apply(r,n),r=r.filter(((e,t)=>{for(let n=0;n<t;++n)if(e.pkg0.id===r[n].pkg0.id)return!1;return!0})),r}))}configureAsInvalidPackage(t){e.log(`invalid package ${this.id}: ${t}`),this._verspec="invalid:"+this.id,this.config={name:this.id,description:t,dependencies:{},files:[]}}parseConfig(t,n){try{const e=JSON.parse(t);this.config=e}catch(t){this.configureAsInvalidPackage(lf("Syntax error in pxt.json")),e.tickEvent("package.invalidConfigEncountered")}const i=JSON.stringify(this.config);for(const t in this.config.dependencies){const n=e.patching.upgradePackageReference(this.targetVersion(),t,this.config.dependencies[t]);n!=t&&(delete this.config.dependencies[t],n&&(this.config.dependencies[n]="*"))}n&&(this.config.targetVersions={target:n}),JSON.stringify(this.config)!=i&&this.saveConfig(),this.validateConfig()}patchCorePackage(){e.Util.assert(e.appTarget.simulator&&e.appTarget.simulator.dynamicBoardDefinition),e.Util.assert(0==this.level);const t=Object.keys(this.config.dependencies).filter((t=>!!t&&(t==e.BLOCKS_PROJECT_NAME||t==e.JAVASCRIPT_PROJECT_NAME||JSON.parse((e.appTarget.bundledpkgs[t]||{})[e.CONFIG_NAME]||"{}").core)));if(0==t.length){const t=e.Package.corePackages();t.length&&this.config.dependencies[t[0].name]}else t.length>1&&(t.pop(),t.forEach((t=>{e.log(`removing core package ${t}`),delete this.config.dependencies[t]})))}resolvedDependencies(){return Object.keys(this.dependencies()).map((e=>this.resolveDep(e)))}dependencies(t=!1){if(!this.config)return{};const n=e.Util.clone(this.config.dependencies||{});return 0==this.level&&this.config.testDependencies&&e.Util.iterMap(this.config.testDependencies,((t,i)=>{("*"!=i||e.appTarget.bundledpkgs[t])&&(n[t]=i)})),t&&this.config.cppDependencies&&e.Util.jsonMergeFrom(n,this.config.cppDependencies),n}async loadAsync(t=!1,i){var s;if(this.isLoaded)return;0!=this.level||e.appTarget.multiVariants||e.setAppTargetVariant(null),this.isLoaded=!0;const r=this.readFile(e.CONFIG_NAME);if(null==r?t||e.U.userError("Package not installed: "+this.id+", did you forget to run `pxt install`?"):this.parseConfig(r),0!=this.level||t||await this.upgradePackagesAsync(),t&&(await this.downloadAsync(),0!==this.level&&!this.isAssetPack()))for(const e of this.addedBy)if(null===(s=e.config.assetPacks)||void 0===s?void 0:s[this.id]){this.writeAssetPackFiles();break}if(0==this.level&&t){const t=await this.upgradePackagesAsync();t&&(Object.keys(t).forEach((t=>e.tickEvent("package.doubleload",{extension:t}))),e.log("upgraded, downloading again"),e.debug(t),await this.downloadAsync())}if(e.appTarget.simulator&&e.appTarget.simulator.dynamicBoardDefinition&&(0==this.level&&this.patchCorePackage(),this.config.compileServiceVariant&&e.setAppTargetVariant(this.config.compileServiceVariant),this.config.files.indexOf("board.json")>=0)){const t=e.appTarget.simulator.boardDefinition=JSON.parse(this.readFile("board.json"));t.id=this.config.name,e.appTarget.appTheme.boardName=t.boardName||lf("board"),e.appTarget.appTheme.driveDisplayName=t.driveDisplayName||lf("DRIVE");let n=t=>{let n=/^pkg:\/\/(.*)/.exec(t);if(n){let t=n[1],i=this.readFile(t);return e.U.toDataUri(i,e.U.getMime(t))}return t},i=e.appTarget.simulator.boardDefinition;if("object"==typeof i.visual){let e=i.visual;e.image=n(e.image),e.outlineImage=n(e.outlineImage)}}const o=(t,n)=>{var i;if(e.debug(`version spec mismatch: ${t._verspec} != ${n}`),/^github:/.test(t._verspec)&&/^github:/.test(n)){const s=e.github.parseRepoId(t._verspec),r=e.github.parseRepoId(n);if((null==s?void 0:s.slug)&&(null==s?void 0:s.slug)===(null==r?void 0:r.slug)){const o=(null==s?void 0:s.tag)||(null===(i=t.config)||void 0===i?void 0:i.version),a=r.tag;if(o&&!a)return void e.debug(`unversioned ${n}, using ${o}`);const l=e.semver.strcmp(o,r.tag);if(0==l)return void e.debug(`resolved version are ${o}`);if(l>0)return void e.debug(`auto-upgraded ${n} to ${o}`)}}/^file:/.test(t._verspec)||/^file:/.test(n)?e.debug("ignore file: mismatch issues"):t.configureAsInvalidPackage(lf("version mismatch"))},a=async(i,s,r=!1)=>{i||(i=s.dependencies(r)),e.debug(`deps: ${s.id}->${Object.keys(i).join(", ")}`),i=e.github.resolveMonoRepoVersions(i),e.debug(`deps: resolved ${s.id}->${Object.keys(i).join(", ")}`);for(let a of Object.keys(i)){let l=i[a]||"*";e.debug(`dep: load ${s.id}.${a}${r?"++":""}: ${l}`),"hw"==a&&e.hwVariant&&(a="hw---"+e.hwVariant);const c=e.github.parseRepoId(l);if(null==c?void 0:c.slug){const t=Object.values(s.parent.deps).map((t=>e.github.parseRepoId(t._verspec))).filter((e=>(null==e?void 0:e.slug)===c.slug)).map((e=>e.tag)).reduce(((t,n)=>e.semver.strcmp(t,n)>0?t:n),"0.0.0");e.debug(`dep: common repo ${c.slug} version found ${t}`),e.semver.strcmp(t,"0.0.0")>0&&(!c.tag||e.semver.strcmp(t,c.tag)>0)&&(e.debug(`dep: upgrade from ${c.tag} to ${t}`),c.tag=t,l=e.github.stringifyRepo(c,!0))}let u=s.resolveDep(a);if(u){if(u.invalid()||u._verspec===l||o(u,l),u.invalid()){u.level=Math.min(u.level,s.level+1),u.addedBy.push(s);continue}r||(u.level=Math.min(u.level,s.level+1),u.addedBy.push(s))}else u=new n(a,l,s.parent,s,a),r&&(u.cppOnly=!0),s.parent.deps[a]=u,s.parent.deps[a.replace(/---.*/,"")]=u,await u.loadAsync(t)}};if(await a(null,this),this.patchAppTargetPalette(),this.config.screenSize&&e.appTarget.runtime&&(e.appTarget.runtime.screenSize=e.U.clone(this.config.screenSize)),0===this.level){const t=this.readFile(e.MAIN_TS);if(t){const n=this.getMissingPackages(this.config,t);let i=!1;for(const t of Object.keys(n)){const s=await this.findConflictsAsync(t,n[t]);if(s.length){const n=s.map((e=>e.pkg0.id)).join(", "),i=s.map((e=>e.settingName)).filter((e=>!!e)).join(", ");e.log(`skipping missing package ${t} because it conflicts with the following packages: ${n} (conflicting settings: ${i})`)}else{e.log(`adding missing package ${t}`),i=!0,this.config.dependencies[t]="*";const s={};s[t]=n[t],await a(s,this)}}i&&(this.saveConfig(),this.validateConfig())}await Promise.all(e.U.values(this.parent.deps).map((e=>a(null,e,!0))))}e.debug(` installed ${this.id}`)}getFiles(){let t;t=0!=this.level||this.ignoreTests?this.config.files.slice(0):this.config.files.concat(this.config.testFiles||[]);const i=this.config.fileDependencies;return this.config.fileDependencies&&(t=t.filter((t=>{const s=i=>{if("!"==(i=i.trim())[0])return!s(i.slice(1));if(/^[\w-]+$/.test(i)){const e=this.parent.resolveDep(i);return!(!e||e.cppOnly)}const r=/^target:(\w+)$/.exec(i);return r?r[1]==e.appTarget.id||r[1]==e.appTarget.platformid:(n.depWarnings[i]||(n.depWarnings[i]=!0,e.log(`invalid dependency expression: ${i} in ${this.id}/${t}`)),!1)},r=e.U.lookup(i,t);return!r||!r.trim()||r.split("||").some((e=>e.split("&&").every(s)))}))),t}addSnapshot(t,n=[""]){for(let i of this.getFiles())n.some((t=>e.U.endsWith(i,t)))&&(t[this.id+"/"+i]=this.readFile(i));t[this.id+"/"+e.CONFIG_NAME]=this.readFile(e.CONFIG_NAME)}packageLocalizationStringsAsync(t){const n=e.appTarget.id,i=[this.config.name+"-jsdoc",this.config.name],s={};e.appTarget.appTheme;return this.config.skipLocalization?Promise.resolve(s):e.Util.liveLocalizationEnabled()&&"this"!=this.id&&e.appTarget.bundledpkgs[this.id]?(e.debug(`loading live translations for ${this.id}`),Promise.all(i.map((i=>e.Util.downloadLiveTranslationsAsync(t,`${n}/${i}-strings.json`).then((n=>{n&&Object.keys(n).length?e.Util.jsonMergeFrom(s,n):(e.tickEvent("translations.livetranslationsfailed",{filename:i}),e.Util.jsonMergeFrom(s,this.bundledStringsForFile(t,i)))})).catch((r=>{e.tickEvent("translations.livetranslationsfailed",{filename:i}),e.log(`error while downloading ${n}/${i}-strings.json`),e.Util.jsonMergeFrom(s,this.bundledStringsForFile(t,i))}))))).then((()=>s))):(i.map((e=>this.bundledStringsForFile(t,e))).filter((e=>!!e)).forEach((t=>e.Util.jsonMergeFrom(s,t))),Promise.resolve(s))}bundledStringsForFile(t,n){let i={},[s,r,o]=e.Util.normalizeLanguageCode(t);const a=this.config.files;let l=`_locales/${s}/${n}-strings.json`;if(o&&-1===a.indexOf(l)&&(l=`_locales/${o}/${n}-strings.json`),r&&-1===a.indexOf(l)&&(l=`_locales/${r}/${n}-strings.json`),a.indexOf(l)>-1)try{i=JSON.parse(this.readFile(l))}catch(n){e.reportError("extension","Extension localization JSON failed to parse",{fileName:l,lang:t,extension:this.verArgument()});"github"===this.verProtocol()&&e.tickEvent("loc.errors.json",{repo:this.verArgument(),file:l})}return i}patchAppTargetPalette(){this.config.palette&&e.appTarget.runtime&&(e.appTarget.runtime.palette=e.U.clone(this.config.palette),this.config.paletteNames&&(e.appTarget.runtime.paletteNames=this.config.paletteNames))}}n.depWarnings={},e.Package=n;function i(e,t={}){let n=e["*"]||{};for(let i of Object.keys(e)){if("*"==i)continue;let s=e[i];"string"==typeof s&&(s={data:s});let r=s.namespace||n.namespace||"";r&&!r.endsWith(".")&&(r+=".");let o=s.id||r+i,a=s.icon,l=s.mimeType||n.mimeType,c=s.dataEncoding||n.dataEncoding||"base64";a||"base64"!=c||"image/png"!=l&&"image/jpeg"!=l||(a="data:"+l+";base64,"+s.data),t[o]={id:o,data:s.data,dataEncoding:c,icon:a,namespace:r,mimeType:l,tilemapTile:s.tilemapTile,displayName:s.displayName,tileset:s.tileset,tags:s.tags}}return t}e.MainPackage=class extends n{constructor(e){super("this","file:.",null,null,null),this._host=e,this.deps={},this.parent=this,this.addedBy=[this],this.level=0,this.deps[this.id]=this}installAllAsync(e){return this.loadAsync(!0,e)}sortedDeps(t=!1){let n={},i=[];const s=e=>e.config?Object.keys(e.config.cppDependencies||{}).length:0,r=o=>{if(!o||e.U.lookup(n,o.id))return;n[o.id]=!0;const a=Object.keys(o.dependencies(t)).map((e=>this.resolveDep(e)));a.sort(((t,n)=>s(n)-s(t)||e.U.strcmp(t.id,n.id))),a.forEach(r),i.push(o.id)};return r(this),i.map((e=>this.resolveDep(e)))}localizationStringsAsync(t){const n={};return Promise.all(e.Util.values(this.deps).map((e=>e.packageLocalizationStringsAsync(t).then((e=>{e&&Object.keys(e).forEach((t=>{n[t]||(n[t]=e[t])}))}))))).then((()=>{const t=e.U.getLocalizedStrings();return Object.keys(n).forEach((i=>{(e.U.startsWith(i,"{id:subcategory}")||e.U.startsWith(i,"{id:group}"))&&(t[i]||(t[i]=n[i]))})),e.U.setLocalizedStrings(t),Promise.resolve(n)}))}getTargetOptions(){let t=e.U.clone(e.appTarget.compile);return e.U.assert(!!t),t.utf8||this.sortedDeps(!0).forEach((n=>{n.config&&n.config.utf8&&(e.debug("forcing utf8 mode: pkg="+n.id),t.utf8=!0)})),t}getJRes(){if(!this._jres){this._jres={};for(const e of this.sortedDeps())e.parseJRes(this._jres);const t=(e.appTarget.runtime&&e.appTarget.runtime.palette?e.appTarget.runtime.palette:["#000000","#ffffff"]).map((e=>("000000"+parseInt(e.replace(/#/,""),16).toString(16)).slice(-6))).join("");this._jres.__palette={id:"__palette",data:t,dataEncoding:"hex",mimeType:"application/x-palette"}}return this._jres}updateJRes(){this._jres&&this.parseJRes(this._jres)}resolveBannedCategories(){if(void 0!==this._resolvedBannedCategories)return this._resolvedBannedCategories;let t=[];return e.appTarget&&e.appTarget.runtime&&e.appTarget.runtime.bannedCategories&&e.appTarget.runtime.bannedCategories.length&&(t=e.appTarget.runtime.bannedCategories.slice(),Object.keys(this.deps).map((e=>this.deps[e])).filter((e=>!!e)).map((t=>e.Util.jsonTryParse(t.readFile(e.CONFIG_NAME)))).filter((e=>e&&e.requiredCategories)).forEach((e=>e.requiredCategories.forEach((e=>{const n=t.indexOf(e);n>-1&&t.splice(n,1)})))),this._resolvedBannedCategories=t),this._resolvedBannedCategories=t,this._resolvedBannedCategories.length||(this._resolvedBannedCategories=null),this._resolvedBannedCategories}async getCompileOptionsAsync(t=this.getTargetOptions()){let n={sourceFiles:[],fileSystem:{},target:t,name:this.config?this.config.name:""};const i=(t,n)=>{this.config.files.indexOf(t)<0&&e.U.userError(lf("please add '{0}' to \"files\" in {1}",t,e.CONFIG_NAME)),n="// Auto-generated. Do not edit.\n"+n+"\n// Auto-generated. Do not edit. Really.\n",this.host().readFile(this,t,!0)!==n&&(e.debug(`updating ${t} (size=${n.length})...`),this.host().writeFile(this,t,n,!0))};let s=!1;const r=async n=>{const r={extinfo:null,target:null},o=e.appTargetVariant;let a;n&&e.setAppTargetVariant(n,{temporary:!0});try{r.target=e.appTarget.compile,a=e.cpp.getExtensionInfo(this),s||!a.shimsDTS&&!a.enumsDTS||(s=!0,a.shimsDTS&&i("shims.d.ts",a.shimsDTS),a.enumsDTS&&i("enums.d.ts",a.enumsDTS))}finally{n&&e.setAppTargetVariant(o,{temporary:!0})}a.appVariant=n;const l=t.isNative?await this.host().getHexInfoAsync(a):null;return a=e.U.flatClone(a),t.keepCppFiles||(delete a.compileData,delete a.generatedFiles,delete a.extensionFiles),a.hexinfo=l,r.extinfo=a,r};let o;await this.loadAsync(),n.bannedCategories=this.resolveBannedCategories(),e.debug(`building: ${this.sortedDeps().map((e=>e.config.name)).join(", ")}`),o=e.appTarget.multiVariants?e.appTargetVariant?[e.appTargetVariant]:e.appTarget.alwaysMultiVariant||e.appTarget.compile.switches.multiVariant?e.appTarget.multiVariants:[e.appTarget.multiVariants[0]]:[null];let a=null;await Promise.all(o.map((async t=>{a&&e.debug(`building for ${t}`);const i=await r(t),s=i.extinfo;s.appVariant=t,s.outputPrefix=1!=o.length&&t?t+"-":"",a?n.otherMultiVariants.push(i):(i.target.isNative=n.target.isNative,n.target=i.target,a=s,n.otherMultiVariants=[])}))),n.extinfo=a,n.target.preferredEditor=this.getPreferredEditor();if(!(e.appTarget.compile.shortPointers||"vm"==e.appTarget.compile.nativeType||this.config.binaryonly||!n.target.isNative)){const t=await this.filesToBePublishedAsync(!0),i=JSON.stringify({name:this.config.name,comment:this.config.description,status:"unpublished",scriptId:this.installedVersion,cloudId:e.CLOUD_ID+e.appTarget.id,editor:this.getPreferredEditor(),targetVersions:e.appTarget.versions}),s=JSON.stringify(t),r=await e.lzmaCompressAsync(i+s);r&&(n.embedMeta=JSON.stringify({compression:"LZMA",headerSize:i.length,textSize:s.length,name:this.config.name,eURL:e.appTarget.appTheme.embedUrl,eVER:e.appTarget.versions?e.appTarget.versions.target:"",pxtTarget:e.appTarget.id}),n.embedBlob=ts.pxtc.encodeBase64(e.U.uint8ArrayToString(r)))}for(const e of this.sortedDeps())for(const t of e.getFiles())if(/\.(ts|asm|py)$/.test(t)){let i=t;e.level>0&&(i="pxt_modules/"+e.id+"/"+t),n.sourceFiles.push(i),n.fileSystem[i]=e.readFile(t)}n.jres=this.getJRes();const l=e.appTarget.runtime&&e.appTarget.runtime.functionsOptions;n.allowedArgumentTypes=l&&l.extraFunctionEditorTypes&&l.extraFunctionEditorTypes.map((e=>e.typeName)).concat("number","boolean","string");for(const e of this.sortedDeps())e.patchAppTargetPalette();return this.patchAppTargetPalette(),n}prepareConfigToBePublished(){const t=e.U.clone(this.config);return delete t.installedVersion,delete t.additionalFilePath,delete t.additionalFilePaths,t.targetVersions||(t.targetVersions=e.Util.clone(e.appTarget.versions)),e.U.iterMap(t.dependencies,((n,i)=>{if(!i||/^(file|workspace):/.test(i)){i="*";try{const t=this.resolveDep(n).readGitJson();if(t&&t.repo){let n=e.github.parseRepoId(t.repo);n.tag=t.commit.tag||t.commit.sha,i=e.github.stringifyRepo(n)}}catch(e){}t.dependencies[n]=i}})),t}filesToBePublishedAsync(t=!1){const n={};return this.loadAsync().then((()=>{t||this.config.public||e.U.userError('Only packages with "public":true can be published');const i=this.prepareConfigToBePublished();n[e.CONFIG_NAME]=e.Package.stringifyConfig(i);for(let t of this.getFiles()){if(t==e.CONFIG_NAME)continue;let i=this.readFile(t);null==i&&e.U.userError("referenced file missing: "+t),n[t]=i}return e.U.sortObjectFields(n)}))}saveToJsonAsync(){return this.filesToBePublishedAsync(!0).then((t=>({meta:{cloudId:e.CLOUD_ID+e.appTarget.id,targetVersions:e.appTarget.versions,editor:this.getPreferredEditor(),name:this.config.name},source:JSON.stringify(t,null,2)})))}compressToFileAsync(){return this.saveToJsonAsync().then((t=>e.lzmaCompressAsync(JSON.stringify(t,null,2))))}computePartDefinitions(t){if(!t||!t.length)return{};let n={};return this.sortedDeps().forEach((i=>{let s=i.readFile("pxtparts.json");if(s)try{let r=JSON.parse(s);Object.keys(r).forEach((s=>{if(t.indexOf(s)>=0){let t=n[s]=r[s];if("string"==typeof t.visual.image&&/\.svg$/i.test(t.visual.image)){let n=i.readFile(t.visual.image);n||e.reportError("parts","invalid part definition",{error:`missing visual ${t.visual.image}`}),/^data:image\/svg\+xml/.test(n)||(n="data:image/svg+xml,"+encodeURIComponent(n)),t.visual.image=n}}}))}catch(t){e.reportError("parts","invalid pxtparts.json file")}})),n}},e.inflateJRes=i,e.allPkgFiles=function(t){return[e.CONFIG_NAME].concat(t.files||[]).concat(t.testFiles||[])},e.isPkgBeta=function(e){return e&&/\bbeta\b/.test(e.description)}}(pxt||(pxt={})),function(e){!function(t){let n,i,s,r,o,a=()=>{};function l(){if(o)return o;let t=Promise.resolve();if(n){e.debug("packetio: disconnect");const s=n;t=t.then((()=>s.disconnectAsync())).then((()=>s.io.disposeAsync())).catch((t=>{e.reportException(t)})).finally((()=>{i=void 0,n=void 0,o=void 0})),a&&(t=t.then((()=>a()))),o=t}return t}t.isActive=function(){return!!n},t.isConnected=function(){return!!(null==n?void 0:n.isConnected())},t.isConnecting=function(){return!!(null==n?void 0:n.isConnecting())},t.icon=function(){var t;return!!n&&(n.icon||(null===(t=e.appTarget.appTheme.downloadDialogTheme)||void 0===t?void 0:t.deviceIcon)||"usb")},t.unsupportedParts=function(){return(null==n?void 0:n.unsupportedParts)?n.unsupportedParts():[]},t.deviceVariant=function(){return null==n?void 0:n.devVariant},t.disconnectAsync=l,t.configureEvents=function(e,t,i){a=e,s=t,r=i,n&&(n.io.onConnectionChanged=a,n.onSerial=s,n.onCustomEvent=i)},t.sendCustomEventAsync=function(e,t){return n?n.sendCustomEventAsync(e,t):Promise.resolve()},t.initAsync=function(o=!1){if(e.debug("packetio: init "+(o?"(force)":"")),!i){let c=Promise.resolve();o&&(c=c.then((()=>l()))),i=c.then((()=>n?Promise.resolve(n):t.mkPacketIOAsync?(e.debug("packetio: new wrapper"),t.mkPacketIOAsync().then((e=>(e.onConnectionChanged=a,n=t.mkPacketIOWrapper(e),s&&(n.onSerial=s),r&&(n.onCustomEvent=r),a&&a(),n)))):(e.debug("packetio: not defined, skipping"),Promise.resolve(void 0)))).finally((()=>{i=void 0}))}return i}}(e.packetio||(e.packetio={}))}(pxt||(pxt={})),function(e){!function(t){function n(t,n,i){const s=e.semver.tryParse(t||"0.0.0")||e.semver.tryParse("0.0.0");let r=[];return Object.keys(n).filter((t=>e.semver.inRange(t,s))).forEach((e=>r=r.concat(n[e]))),i&&(r=r.filter((e=>e.type==i))),r.length?r:void 0}function i(e,t,n){let i=t;return n&&(n.filter((e=>"api"===e.type)).forEach((e=>{Object.keys(e.map).forEach((t=>{const n=new RegExp(t,"g");i=i.replace(n,e.map[t])}))})),n.filter((e=>"userenum"===e.type)).forEach((e=>{Object.keys(e.map).forEach((t=>{const n=new RegExp("enum\\s+"+t+"\\s*{","gm");i=i.replace(n,`enum ${e.map[t]} {`);const s=new RegExp(`(^|[^_a-zA-Z0-9])${t}(\\s*\\.)`,"g");i=i.replace(s,`$1${e.map[t]}$2`)}))}))),i}t.computePatches=function(t,i){const s=e.appTarget.compile?e.appTarget.compile.patches:void 0;if(s)return n(t,s,i)},t.computePyPatches=function(t,i){const s=e.appTarget.compile?e.appTarget.compile.pyPatches:void 0;if(s)return n(t,s,i)},t.upgradePackageReference=function(t,n,i){if("*"!=i)return n;const s=e.patching.computePatches(t,"package");let r=n;return s&&s.forEach((e=>{Object.keys(e.map).forEach((t=>{r==t&&(r=e.map[t])}))})),r},t.patchJavaScript=function(t,n){return i(t,n,e.patching.computePatches(t))},t.patchPython=function(t,n){return i(t,n,e.patching.computePyPatches(t))}}(e.patching||(e.patching={}))}(pxt||(pxt={})),function(e){e.react||(e.react={})}(pxt||(pxt={})),function(e){!function(t){function n(t,n){if(t){if(n){let i=t.major-n.major||t.minor-n.minor||t.patch-n.patch;if(i)return i;if(0==t.pre.length&&n.pre.length>0)return 1;if(t.pre.length>0&&0==n.pre.length)return-1;for(let s=0;s<t.pre.length+1;++s){let r=t.pre[s],o=n.pre[s];if(!r)return o?-1:0;if(!o)return 1;if(/^\d+$/.test(r)){if(!/^\d+$/.test(o))return-1;if(i=parseInt(r)-parseInt(o),i)return i}else{if(/^\d+$/.test(o))return 1;if(i=e.U.strcmp(r,o),i)return i}}return 0}return-1}return n?1:0}function i(t,n){let i=s(t)||s(n);return i||e.U.userError(e.U.lf("'{0}' doesn't look like a semantic version number",t)),i}function s(e){if(!e)return null;if("*"===e)return{major:Number.MAX_SAFE_INTEGER,minor:Number.MAX_SAFE_INTEGER,patch:Number.MAX_SAFE_INTEGER,pre:[],build:[]};/^v\d/i.test(e)&&(e=e.slice(1));let t=/^(\d+)\.(\d+)\.(\d+)(-([0-9a-zA-Z\-\.]+))?(\+([0-9a-zA-Z\-\.]+))?$/.exec(e);return t?{major:parseInt(t[1]),minor:parseInt(t[2]),patch:parseInt(t[3]),pre:t[5]?t[5].split("."):[],build:t[7]?t[7].split("."):[]}:null}function r(e){let t=e.major+"."+e.minor+"."+e.patch;return e.pre.length&&(t+="-"+e.pre.join(".")),e.build.length&&(t+="+"+e.build.join(".")),t}function o(t,i){let r=s(t),o=s(i);return r||o?n(r,o):e.U.strcmp(t,i)}function a(e,t){let i=e.split(" - ");if(2!=i.length)return!1;let r=s(i[0]),o=s(i[1]);if(!r||!o)return!1;if(!t)return!0;const a=n(r,t),l=n(t,o);return a<=0&&l<0}t.cmp=n,t.parse=i,t.tryParse=s,t.normalize=function(e){return r(i(e))},t.stringify=r,t.majorCmp=function(e,t){let n=s(e),i=s(t);return n.major-i.major},t.strcmp=o,t.inRange=a,t.sortLatestTags=function(e){const n=e.filter((e=>!!t.tryParse(e)));return n.sort(o),n.reverse(),n},t.test=function(){console.log("Test semver");let t=["0.9.0","1.0.0-0.3.7","1.0.0-alpha","1.0.0-alpha.1","1.0.0-alpha.beta","1.0.0-beta","1.0.0-beta.2","1.0.0-beta.11","1.0.0-rc.1","1.0.0-x.7.z.92","1.0.0","1.0.1","1.9.0","1.10.0","1.11.0"];for(let s=0;s<t.length;++s){let o=i(t[s]);console.log(t[s],o),e.U.assert(r(o)==t[s]);for(let r=0;r<t.length;++r){let a=n(o,i(t[r]));console.log(t[s],t[r],a),s<r?e.U.assert(a<0):s>r?e.U.assert(a>0):e.U.assert(0==a)}}const o=s("1.2.3");e.U.assert(a("0.1.2 - 2.2.3",o)),e.U.assert(a("1.2.3 - 2.2.3",o)),e.U.assert(!a("0.0.0 - 1.2.3",o)),e.U.assert(!a("1.2.4 - 4.2.3",o)),e.U.assert(!a("0.0.0 - 0.0.1",o))}}(e.semver||(e.semver={}))}(pxt||(pxt={})),function(e){!function(e){function t(t){return e.Util.values(t.byQName).filter((e=>e.attributes.block&&/^{[^:]+:[^}]+}/.test(e.attributes.block))).forEach((e=>{e.attributes.block=e.attributes.block.replace(/^{[^:]+:[^}]+}/,"")})),t}e.assert=e.Util.assert,e.oops=e.Util.oops,e.U=e.Util,e.ON_START_TYPE="pxt-on-start",e.ON_START_COMMENT="on start",e.HANDLER_COMMENT="code goes here",e.TS_STATEMENT_TYPE="typescript_statement",e.TS_DEBUGGER_TYPE="debugger_keyword",e.TS_BREAK_TYPE="break_keyword",e.TS_CONTINUE_TYPE="continue_keyword",e.TS_OUTPUT_TYPE="typescript_expression",e.TS_RETURN_STATEMENT_TYPE="function_return",e.PAUSE_UNTIL_TYPE="pxt_pause_until",e.COLLAPSED_BLOCK="pxt_collapsed_block",e.FUNCTION_DEFINITION_TYPE="function_definition",e.BINARY_JS="binary.js",e.BINARY_ASM="binary.asm",e.BINARY_HEX="binary.hex",e.BINARY_UF2="binary.uf2",e.BINARY_ELF="binary.elf",e.BINARY_PXT64="binary.pxt64",e.BINARY_ESP="binary.bin",e.BINARY_SRCMAP="binary.srcmap",e.NATIVE_TYPE_THUMB="thumb",e.NATIVE_TYPE_VM="vm",e.BuildSourceMapHelpers=function(e,t,n){const i=e=>{const t=e.split("\n").map((e=>e.length)),n=t.reduce((({lens:e,sum:t},n)=>({lens:[...e,t+n+1],sum:t+n+1})),{lens:[],sum:0}).lens;return{posToLineCol:e=>{const i=n.reduce(((t,n,i)=>e<n?t:i+1),0);return[i,t[i]-(n[i]-e)+1]},lineColToPos:(e,t)=>(n[e-1]||0)+t}},s={ts:i(t),py:i(n)},r=e=>e.endPos-e.startPos,o=(t,n)=>{const{startPos:i,endPos:s}=t;return e.filter((e=>e[n].startPos<=i&&s<=e[n].endPos))},a=(e,t)=>{const n=o(e,t);return n.reduce(((e,n)=>r(n[t])<r(e[t])?n:e),n[0])},l={ts:{allOverlaps:e=>o(e,"ts"),smallestOverlap:e=>a(e,"ts")},py:{allOverlaps:e=>o(e,"py"),smallestOverlap:e=>a(e,"py")}},c=(e,t)=>n=>{const[i,o]=(t=>[s[e].lineColToPos(t.line,t.column),t.length])(n),l=a({startPos:i,endPos:i+o},e);if(!l)return;const[c,u]=s[t].posToLineCol(l[t].startPos);return{fileName:`main.${t}`,start:l[t].startPos,length:r(l[t]),line:c,column:u}},u=c("ts","py"),d=c("py","ts");return{ts:Object.assign(Object.assign(Object.assign({},s.ts),l.ts),{locToLoc:u,getText:e=>t.substring(e.startPos,e.endPos)}),py:Object.assign(Object.assign(Object.assign({},s.py),l.py),{locToLoc:d,getText:e=>n.substring(e.startPos,e.endPos)})}},e.computeUsedParts=function(e,t,n=!1){if(!e.usedSymbols||!pxt.appTarget.simulator||!n&&!pxt.appTarget.simulator.parts)return[];const i=(e,t)=>{if(e){const n=e.split(/[ ,]+/g);t.push(...n.filter((e=>!!e&&t.indexOf(e)<0)))}};let s=[],r=[];if(Object.keys(e.usedSymbols).forEach((t=>{const n=e.usedSymbols[t];i(null==n?void 0:n.attributes.parts,s),i(null==n?void 0:n.attributes.hiddenParts,r)})),t){const e=pxt.appTarget.simulator.boardDefinition.onboardComponents;e&&("ignorebuiltin"===t?s=s.filter((t=>-1===e.indexOf(t))):"onlybuiltin"===t&&(s=s.filter((t=>e.indexOf(t)>=0))))}return s=s.filter((e=>r.indexOf(e)<0)),s.sort(),s=s.reverse(),s},e.buildSimJsInfo=function(t){var n;return{js:t.outfiles[e.BINARY_JS],targetVersion:pxt.appTarget.versions.target,fnArgs:t.usedArguments,parts:e.computeUsedParts(t,"ignorebuiltin"),usedBuiltinParts:e.computeUsedParts(t,"onlybuiltin"),allParts:e.computeUsedParts(t,void 0,!0),breakpoints:null===(n=t.breakpoints)||void 0===n?void 0:n.map((e=>e.id))}},e.blocksCategory=function(t){const n=t?t.attributes.blockNamespace||t.namespace:void 0;return n?e.Util.capitalize(n.split(".")[0]):void 0},e.getBlocksInfo=function(t,n){var i,o;let a=[];const l={},c={},u={},d={},h={};function p(t,n){const i="get"==t,s="set"==t,o="number"==n.retType,d=i?c:s?l:u,h=`${n.namespace}.${n.retType}`;let p=e.U.lookup(d,h);if(!p){const l=`@${t}@`;let c,u;if(n.attributes.blockCombineShadow){const t=n.attributes.blockCombineShadow,i=t.match(/^([^,.]*),?([^,.]*)$/);i&&3==i.length&&(c=i[1].trim(),u=i[2].trim(),0!=u.length||e.Util.endsWith(t,",")||(u=c,c=""))}const f=`${n.attributes.blockSetVariable||n.namespace.toLocaleLowerCase()}=${c||""}`,m=`value=${u||""}`;p=d[h]={attributes:{blockId:`${o?n.namespace:h}_blockCombine_${t}`,callingConvention:0,group:n.attributes.group,paramDefl:{},jsDoc:i?e.U.lf("Read value of a property on an object"):e.U.lf("Update value of property on an object")},name:l,namespace:n.namespace,fileName:n.fileName,qName:`${h}.${l}`,pkg:n.pkg,kind:2,parameters:[{name:"property",description:i?e.U.lf("the name of the property to read"):e.U.lf("the name of the property to change"),isEnum:!0,type:"@combined@"},{name:"value",description:s?e.U.lf("the new value of the property"):e.U.lf("the amount by which to change the property"),type:n.retType}].slice(0,i?1:2),retType:i?n.retType:"void",combinedProperties:[]},p.attributes.block=i?e.U.lf("%{0} %property",f):s?e.U.lf("set %{0} %property to %{1}",f,m):e.U.lf("change %{0} %property by %{1}",f,m),r(p.attributes),pxt.Util.isTranslationMode()&&(p.attributes.translationId=p.attributes.block,p.attributes.block=i?`%${f} %property`:s?`set %${f} %property to %${m}`:`change %${f} %property by %${m}`,r(p.attributes),pxt.crowdin.inContextLoadAsync(p.attributes.translationId).then((e=>{p.attributes.block=e,r(p.attributes)}))),a.push(p)}p.combinedProperties.push(n.qName)}for(let n of e.Util.values(t.byQName)){if("ENUM_GET"===n.attributes.shim&&n.attributes.enumName&&n.attributes.blockId){let e=!1;if(d[n.attributes.enumName]&&(console.warn(`Enum block ${n.attributes.blockId} trying to overwrite enum ${n.attributes.enumName}`),e=!0),n.attributes.enumMemberName||(console.warn(`Enum block ${n.attributes.blockId} should specify enumMemberName`),e=!0),n.attributes.enumPromptHint||(console.warn(`Enum block ${n.attributes.blockId} should specify enumPromptHint`),e=!0),n.attributes.enumInitialMembers&&n.attributes.enumInitialMembers.length||(console.warn(`Enum block ${n.attributes.blockId} should specify enumInitialMembers`),e=!0),e)continue;const t=parseInt(n.attributes.enumStartValue);d[n.attributes.enumName]={blockId:n.attributes.blockId,name:n.attributes.enumName,memberName:n.attributes.enumMemberName,firstValue:isNaN(t)?void 0:t,isBitMask:n.attributes.enumIsBitMask,isHash:n.attributes.enumIsHash,initialMembers:n.attributes.enumInitialMembers,promptHint:n.attributes.enumPromptHint}}if("KIND_GET"===n.attributes.shim&&n.attributes.blockId){const i=n.attributes.kindNamespace||n.attributes.blockNamespace||n.namespace;if(h[i]){console.warn(`More than one block defined for kind ${i}`);continue}const s=[];if(t.byQName[i])for(const n of e.Util.values(t.byQName))n.namespace===i&&n.attributes.isKind&&s.push(n.name);h[i]={blockId:n.attributes.blockId,name:i,memberName:n.attributes.kindMemberName||i,initialMembers:s,promptHint:n.attributes.enumPromptHint||e.Util.lf("Create a new kind..."),createFunctionName:n.attributes.kindCreateFunction||"create"}}if(n.attributes.blockCombine)/@set/.test(n.name)||p("get",n),n.isReadOnly||("number"==n.retType&&p("change",n),p("set",n));else if(n.attributes.block&&!n.attributes.fixedInstance&&7!=n.kind&&5!=n.kind&&9!=n.kind&&8!=n.kind){if(n.attributes.blockId||(n.attributes.blockId=n.qName.replace(/\./g,"_")),"true"==n.attributes.block){let t=e.U.uncapitalize(n.name);1!=n.kind&&2!=n.kind||(t+=" %"+n.namespace.toLowerCase());const a=null!==(o=null===(i=n.parameters)||void 0===i?void 0:i.filter((e=>!s(e))))&&void 0!==o?o:[];for(let e of a)t+=" %"+e.name;n.attributes.block=t,r(n.attributes)}a.push(n)}}for(let n of a){let i=e.U.lookup(t.byQName,n.namespace);if(!i)continue;let s=i.attributes,r=n.attributes;for(let e of["blockNamespace","color","blockGap"])void 0===r[e]&&s[e]&&(r[e]=s[e])}var f;return n&&((f=n).length&&(a=a.filter((e=>{let t=(e.attributes.blockNamespace||e.namespace).split(".")[0];return-1===f.indexOf(t)})))),{apis:t,blocks:a,blocksById:pxt.Util.toDictionary(a,(e=>e.attributes.blockId)),enumsByName:d,kindsByName:h}},e.tsSnippetToPySnippet=function(t,n){const i={true:"True",false:"False",null:"None"}[t];if(i)return i;if(n&&6==n.kind||!n&&t.includes(".")){const n=t.lastIndexOf("."),i=t.substr(0,n);let s=t.substr(n+1);return s=e.U.snakify(s).toUpperCase(),i?`${i}.${s}`:s}return t},e.apiLocalizationStrings={},e.localizeApisAsync=async function(n,i){const s=e.Util.userLanguage();if("en"==s)return Promise.resolve(t(n));const o=s.toLowerCase(),a=o+"|jsdoc",l=o+"|block",c=await i.localizationStringsAsync(s);e.apiLocalizationStrings&&e.Util.jsonMergeFrom(c,e.apiLocalizationStrings);const u=e.Util.values(n.byQName).filter((e=>e.attributes._translatedLanguageCode!==s));return await e.Util.promiseMapAll(u,(async t=>{var i,u,d;const h=t.attributes.useLoc||t.attributes.blockAliasFor,p=h&&n.byQName[h];t.attributes._untranslatedJsDoc&&(t.attributes.jsDoc=t.attributes._untranslatedJsDoc),t.attributes._untranslatedBlock&&(t.attributes.jsDoc=t.attributes._untranslatedBlock);const f=(e,n)=>{var i,s;return c[t.qName+e]||(null===(i=t.attributes.locs)||void 0===i?void 0:i[n])||p&&(c[p.qName+e]||(null===(s=p.attributes.locs)||void 0===s?void 0:s[n]))},m=f("",a);m&&(t.attributes._untranslatedJsDoc||(t.attributes._untranslatedJsDoc=t.attributes.jsDoc),t.attributes.jsDoc=m),null===(i=t.parameters)||void 0===i||i.forEach((e=>{const t=`|param|${e.name}`,n=f(t,o+t);n&&(e.description=n)}));const g=c["{id:category}"+e.Util.capitalize(t.qName)];let b=c[`${t.qName}|block`]||(null===(u=t.attributes.locs)||void 0===u?void 0:u[l]);if(!b&&p){const e=c[`${p.qName}|block`]||(null===(d=p.attributes.locs)||void 0===d?void 0:d[l]);t.attributes.block===(p.attributes._untranslatedBlock||p.attributes.block)&&e&&(b=e)}if(b&&pxt.Util.isTranslationMode()&&(t.attributes.translationId=b,b=await pxt.crowdin.inContextLoadAsync(b)),g)t.attributes.block?t.attributes.block=b||t.attributes.block:t.attributes.block=g,r(t.attributes);else if(t.attributes.block&&b){const e=pxt.blocks.compileInfo(t),n=t.attributes.block;if(t.attributes.block=pxt.blocks.normalizeBlock(b,(e=>{pxt.tickEvent("loc.normalized",{block:t.attributes.block,lang:s,error:e})})),t.attributes._untranslatedBlock||(t.attributes._untranslatedBlock=n),n!=t.attributes.block){r(t.attributes);(function(e,t){if(e.parameters.length!=t.parameters.length)return pxt.debug("Localized block has extra or missing parameters"),!1;for(const n of e.parameters){const e=t.actualNameToParam[n.actualName];if(!e||n.type!=e.type||n.shadowBlockId!=e.shadowBlockId||n.definitionName!=e.definitionName)return pxt.debug(`Parameter ${n.actualName} type, shadow block, or definition name does not match after localization`),!1}return!0})(e,pxt.blocks.compileInfo(t))||(pxt.reportError("loc.errors","block has non matching arguments",{block:t.attributes.blockId,lang:s,originalDefinition:n,translatedBlock:t.attributes.block}),pxt.tickEvent("loc.errors",{block:t.attributes.blockId,lang:s}),t.attributes.block=n,r(t.attributes))}}else r(t.attributes);t.attributes._translatedLanguageCode=s})),t(n)},e.emptyExtInfo=function(){let e=pxt.appTarget.compileService;e||(e={});const t=!!e.platformioIni,n="dockermake"==e.buildEngine||"dockercross"==e.buildEngine||"dockerespidf"==e.buildEngine,i={functions:[],generatedFiles:{},extensionFiles:{},sha:"",compileData:"",shimsDTS:"",enumsDTS:"",onlyPublic:!0};return t?i.platformio={dependencies:{}}:n?i.npmDependencies={}:i.yotta={config:{},dependencies:{}},i};const n=["weight","imageLiteral","gridLiteral","topblockWeight","inlineInputModeLimit"],i=["advanced","handlerStatement","afterOnStart","optionalVariableArgs","blockHidden","constantShim","blockCombine","enumIsBitMask","enumIsHash","decompileIndirectFixedInstances","topblock","callInDebugger","duplicateShadowOnDrag","argsNullable","compileHiddenArguments"];function s(e){return"Action"===e.type||/^\([^\)]*\)\s*=>/.test(e.type)}function r(e){if(e.block){const n=e.block.split("||");e._def=t(o(n[0])),e._def||pxt.debug("Unable to parse block def for id: "+e.blockId),n[1]&&(e._expandedDef=t(o(n[1]))),n[1]&&!e._expandedDef&&pxt.debug("Unable to parse expanded block def for id: "+e.blockId)}function t(t){return e._shadowOverrides&&t.parameters.forEach((t=>{const n=e._shadowOverrides[t.name];"unset"===n?delete t.shadowBlockId:null!=n&&(t.shadowBlockId=n)})),t}}function o(e){const t=[];let n,i=0;for(;i<e.length;i++){const s=e[i],r=i;let o;switch(s){case"*":case"_":const t=d((e=>e==s)),n="_"===s?2:0;1===t.length?o={kind:1<<n,content:t}:2===t.length?o={kind:2<<n,content:t}:3===t.length?o={kind:3<<n,content:t}:i=r;break;case"`":const a=h("`");if(void 0===a){i=r;break}o={kind:256,content:a};break;case"|":o={kind:32};break;case"\\":i<e.length-1&&(o={kind:16,content:e[1+i++]});break;case"[":const l=h("]");if(void 0!==l&&"("===e[1+i++]){const e=h(")");if(void 0!==e){o={kind:512,content:l,type:e};break}}i=r;break;case"$":case"%":const c=d((e=>/[a-zA-Z0-9_=]/.test(e)),!0).split("=");if(c.length>2){i=r;break}let u;if("("===e[i+1]){const e=i;++i,u=h(")"),u||(i=e)}o={kind:"$"===s?1024:64,content:c[0],type:c[1],name:u}}o?(n&&t.push({kind:128,content:n}),n=void 0,t.push(o)):n?n+=s:n=s}n&&t.push({kind:128,content:n});const s=[],r=[];let o=[],l=0,c="",u=[];for(let e=0;e<t.length;e++){const n=t[e].kind,i=o[o.length-1];if(15&n)if(m(t[e].content),n&l)if(i&n){o.pop(),l^=n;const e=i&l|n&l;e&&o.push(e)}else p();else l|=n,o.push(n);else 144&n?c+=t[e].content:1120&n&&f();if(64==n){const n={kind:"param",name:t[e].content,shadowBlockId:t[e].type,ref:!1};t[e].name&&(n.varName=t[e].name),s.push(n),r.push(n)}else if(1024==n){const n={kind:"param",name:t[e].content,shadowBlockId:t[e].type,ref:!0};t[e].name&&(n.varName=t[e].name),s.push(n),r.push(n)}else 256==n?(m(),u.push({kind:"image",uri:t[e].content})):512==n?(m(),u.push({kind:"label",text:t[e].content,cssClass:t[e].type})):32==n&&s.push({kind:"break"})}return f(),{parts:s,parameters:r};function d(t,n=!1){let s="";for(n&&i++;i<e.length&&t(e[i]);)s+=e[i],++i;return s&&i--,s}function h(t){const n=d((e=>e!==t),!0);if(e[i+1]===t)return++i,n}function p(){let e="",t=[];for(const n of u)a(n)?(t.push({content:e,styles:0}),t.push(n),e=""):(e+=n.content,n.endingToken&&(e+=n.endingToken));u=t,e&&u.push({content:e,styles:0}),o=[],l=0}function f(){for(m(),l&&p();u.length;){const e=u.shift();if(a(e))s.push(e);else{if(!e.content)continue;const t=[];10&e.styles&&t.push("bold"),5&e.styles&&t.push("italics"),s.push({kind:"label",text:e.content,style:t})}}}function m(e){u.push({content:c,styles:l,endingToken:e}),c=""}}function a(e){return!!e.kind}let l;e.parseCommentString=function(t){let s={paramDefl:{},callingConvention:0,_source:t},o=!0;for(;o;)o=!1,t=t.replace(/\/\/%[ \t]*([\w\.-]+)(=(("[^"\n]*")|'([^'\n]*)'|([^\s]*)))?/,((t,n,i,r,a,l,c)=>{let u=a?JSON.parse(a):i?a||l||c:"true";if(u||(u=""),e.U.startsWith(n,"block.loc."))s.locs||(s.locs={}),s.locs[n.slice("block.loc.".length).toLowerCase()+"|block"]=u;else if(e.U.startsWith(n,"jsdoc.loc."))s.locs||(s.locs={}),s.locs[n.slice("jsdoc.loc.".length).toLowerCase()+"|jsdoc"]=u;else if(e.U.contains(n,".loc.")){s.locs||(s.locs={});const e=n.slice(0,n.indexOf(".loc.")),t=n.slice(n.indexOf(".loc.")+".loc.".length);s.locs[t+"|param|"+e]=u}else if(e.U.endsWith(n,".defl"))u.indexOf(" ")>-1?s.paramDefl[n.slice(0,n.length-5)]=`"${u}"`:s.paramDefl[n.slice(0,n.length-5)]=u,s.explicitDefaults||(s.explicitDefaults=[]),s.explicitDefaults.push(n.slice(0,n.length-5));else if(e.U.endsWith(n,".shadow"))s._shadowOverrides||(s._shadowOverrides={}),s._shadowOverrides[n.slice(0,n.length-7)]=u;else if(e.U.endsWith(n,".snippet")){s.paramSnippets||(s.paramSnippets={});const e=n.slice(0,n.length-8);s.paramSnippets[e]||(s.paramSnippets[e]={}),s.paramSnippets[e].ts=u}else if(e.U.endsWith(n,".pySnippet")){s.paramSnippets||(s.paramSnippets={});const e=n.slice(0,n.length-10);s.paramSnippets[e]||(s.paramSnippets[e]={}),s.paramSnippets[e].python=u}else if(e.U.endsWith(n,".fieldEditor"))s.paramFieldEditor||(s.paramFieldEditor={}),s.paramFieldEditor[n.slice(0,n.length-12)]=u;else if(e.U.contains(n,".fieldOptions.")){s.paramFieldEditorOptions||(s.paramFieldEditorOptions={});const e=n.slice(0,n.indexOf(".fieldOptions.")),t=n.slice(n.indexOf(".fieldOptions.")+14,n.length);s.paramFieldEditorOptions[e]||(s.paramFieldEditorOptions[e]={}),s.paramFieldEditorOptions[e][t]=u}else if(e.U.contains(n,".shadowOptions.")){s.paramShadowOptions||(s.paramShadowOptions={});const e=n.slice(0,n.indexOf(".shadowOptions.")),t=n.slice(n.indexOf(".shadowOptions.")+15,n.length);s.paramShadowOptions[e]||(s.paramShadowOptions[e]={}),s.paramShadowOptions[e][t]=u}else e.U.endsWith(n,".min")?(s.paramMin||(s.paramMin={}),s.paramMin[n.slice(0,n.length-4)]=u):e.U.endsWith(n,".max")?(s.paramMax||(s.paramMax={}),s.paramMax[n.slice(0,n.length-4)]=u):s[n]=u;return o=!0,"//% "}));for(let e of n)"string"==typeof s[e]&&(s[e]=parseInt(s[e]));for(let e of i)"string"==typeof s[e]&&(s[e]="true"==s[e]||"1"==s[e]);if(s.trackArgs&&(s.trackArgs=s.trackArgs.split(/[ ,]+/).map((e=>parseInt(e)||0))),s.enumInitialMembers&&(s.enumInitialMembers=s.enumInitialMembers.split(/[ ,]+/)),s.blockExternalInputs&&!s.inlineInputMode&&(s.inlineInputMode="external"),s.paramHelp={},s.jsDoc="",t=t.replace(/\/\*\*([^]*?)\*\//g,((e,t)=>(t=(t=t.replace(/\n\s*(\*\s*)?/g,"\n")).replace(/^\s*@param\s+(\w+)\s+(.*)$/gm,((e,t,n)=>{if(s.paramHelp[t]=n,!s.paramDefl[t]){let e=/\beg\.?:\s*(.+)/.exec(n);if(e&&e[1]){let n=/(?:"([^"]*)")|(?:'([^']*)')|(?:([^\s,]+))/g.exec(e[1]);if(n){let e=n[1]||n[2]||n[3];e||(e=""),e.indexOf(" ")>-1?s.paramDefl[t]=`"${e}"`:s.paramDefl[t]=e}}}return""})),s.jsDoc+=t,""))),s.jsDoc=s.jsDoc.trim(),s.async&&(s.callingConvention=1),s.promise&&(s.callingConvention=2),s.jres&&(s.whenUsed=!0),s.subcategories)try{s.subcategories=JSON.parse(s.subcategories)}catch(e){s.subcategories=void 0}if(s.groups)try{s.groups=JSON.parse(s.groups)}catch(e){s.groups=void 0}if(s.groupIcons)try{s.groupIcons=JSON.parse(s.groupIcons)}catch(e){s.groupIcons=void 0}if(s.groupHelp)try{s.groupHelp=JSON.parse(s.groupHelp)}catch(e){s.groupHelp=void 0}return r(s),s},e.parameterTypeIsArrowFunction=s,e.updateBlockDef=r,e.parseBlockDefinition=o,e.parseChecksumBlock=function(e,t=0){let n=pxt.HF2.read32(e,t);if(133083260!=(2147483647&n))return pxt.log("no checksum block magic"),null;let i=pxt.HF2.read32(e,t+4),s=pxt.HF2.read32(e,t+8);if(3&i)return pxt.log("invalid end marker position"),null;let r=1<<(255&s);if(r!=pxt.appTarget.compile.flashCodeAlign)return pxt.log("invalid page size: "+r),null;let o={magic:n,endMarkerPos:i,endMarker:s,regions:[]};for(let n=t+12;n<e.length-7;n+=8){let t={start:r*pxt.HF2.read16(e,n),length:r*pxt.HF2.read16(e,n+2),checksum:pxt.HF2.read32(e,n+4)};if(!t.length||!t.checksum)break;o.regions.push(t)}return o},function(t){function n(n){let i=e=>n[e]+(n[e+1]<<8)+(n[e+2]<<16)+(n[e+3]<<24)>>>0;if(!n||512!=n.length||i(0)!=t.UF2_MAGIC_START0||i(4)!=t.UF2_MAGIC_START1||i(n.length-4)!=t.UF2_MAGIC_END)return null;let s=i(8),r=i(16);r>476&&(r=256);let o=null,a=0,l=0;if(s&t.UF2_FLAG_FILE){let t=n.slice(32+r),s=t.indexOf(0);s>=0&&(t=t.slice(0,s)),o=e.U.fromUTF8Array(t),l=i(28)}return s&t.UF2_FLAG_FAMILY_ID_PRESENT&&(a=i(28)),{flags:s,targetAddr:i(12),payloadSize:r,blockNo:i(20),numBlocks:i(24),fileSize:l,familyId:a,data:n.slice(32,32+r),filename:o}}function i(e,t){return!!e&&(e.targetAddr<=t&&t<e.targetAddr+e.payloadSize)}function s(e,t,n){e[t]=255&n,e[t+1]=n>>8&255,e[t+2]=n>>16&255,e[t+3]=n>>24&255}function r(e){return"string"==typeof e&&(e=parseInt(e)),{currBlock:null,currPtr:-1,blocks:[],ptrs:[],filesize:0,familyId:e||0}}function o(e){for(let t=0;t<e.blocks.length;++t)s(e.blocks[t],20,t),s(e.blocks[t],24,e.blocks.length),e.filename&&s(e.blocks[t],28,e.filesize)}function a(n,i,r,o=0){let l=n.currBlock,c=i>>8,u=256-(255&i);if(r.length>u){let e=new Uint8Array(r);for(a(n,i,e.slice(0,u));u<r.length;){let t=Math.min(u+256,r.length);a(n,i+u,e.slice(u,t)),u=t}return}if(c!=n.currPtr){l=null;for(let e=0;e<n.ptrs.length;++e)if(n.ptrs[e]==c){l=n.blocks[e];break}if(!l){l=new Uint8Array(512),n.filename?o|=t.UF2_FLAG_FILE:n.familyId&&(o|=t.UF2_FLAG_FAMILY_ID_PRESENT),s(l,0,t.UF2_MAGIC_START0),s(l,4,t.UF2_MAGIC_START1),s(l,8,o),s(l,12,c<<8),s(l,16,256),s(l,20,n.blocks.length),s(l,28,n.familyId),s(l,508,t.UF2_MAGIC_END);for(let e=32;e<288;++e)l[e]=255;n.filename&&e.U.memcpy(l,288,e.U.toUTF8Array(n.filename)),n.blocks.push(l),n.ptrs.push(c)}n.currPtr=c,n.currBlock=l}let d=32+(255&i);for(let e=0;e<r.length;++e)l[d+e]=r[e];n.filesize=Math.max(n.filesize,r.length+i)}t.UF2_MAGIC_START0=171066965,t.UF2_MAGIC_START1=2656915799,t.UF2_MAGIC_END=179400496,t.UF2_FLAG_NONE=0,t.UF2_FLAG_NOFLASH=1,t.UF2_FLAG_FILE=4096,t.UF2_FLAG_FAMILY_ID_PRESENT=8192,t.parseBlock=n,t.parseFile=function(e){let t=[];for(let i=0;i<e.length;i+=512){let s=n(e.slice(i,i+512));s&&t.push(s)}return t},t.toBin=function(e,t){if(e.length<512)return null;let i=-1,s=-1,r=[];for(let o=0;o<e.length;++o){let a=512*o,l=n(e.slice(a,a+512));if(!l)continue;if(t&&l.targetAddr+256>t)break;-1==i&&(i=l.targetAddr,s=i);let c=l.targetAddr-i;c<0||c%4||c>1048576||(c>0&&r.push(new Uint8Array(c)),r.push(e.slice(a+32,a+32+l.payloadSize)),i=l.targetAddr+l.payloadSize)}let o=0;for(let e of r)o+=e.length;if(0==o)return null;let a=new Uint8Array(o),l=0;for(let e of r)for(let t=0;t<e.length;++t)a[l++]=e[t];return{buf:a,start:s}},t.readBytes=function(e,t,n){let s,r=new Uint8Array(n);for(let o=0;o<n;++o,++t)i(s,t)||(s=e.filter((e=>i(e,t)))[0]),s&&(r[o]=s.data[t-s.targetAddr]);return r},t.newBlockFile=r,t.finalizeFile=o,t.concatFiles=function(t){for(let e of t)o(e),e.filename=null;let n=r();n.blocks=e.U.concat(t.map((e=>e.blocks)));for(let e of t)e.blocks=[];return n},t.serializeFile=function(t){o(t);let n="";for(let i of t.blocks)n+=e.Util.uint8ArrayToString(i);return n},t.readBytesFromFile=function t(n,i,s){let r,o=i>>8;if(o==n.currPtr)r=n.currBlock;else{for(let e=0;e<n.ptrs.length;++e)if(n.ptrs[e]==o){r=n.blocks[e];break}r&&(n.currPtr=o,n.currBlock=r)}if(!r)return null;let a=new Uint8Array(s),l=Math.min(s,256-(255&i));e.U.memcpy(a,0,r,32+(255&i),l);let c=s-l;if(c>0){let s=t(n,i+l,c);e.U.memcpy(a,l,s)}return a},t.writeBytes=a,t.writeHex=function(e,t){let n="0000";for(let i=0;i<t.length;++i){let s=/:02000004(....)/.exec(t[i]);if(s&&(n=s[1]),s=/^:..(....)00(.*)[0-9A-F][0-9A-F]$/.exec(t[i]),s){let t=parseInt(n+s[1],16),i=s[2],r=[];for(let e=0;e<i.length;e+=2)r.push(parseInt(i[e]+i[e+1],16));a(e,t,r)}}}}(l=e.UF2||(e.UF2={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){!function(e){let t;!function(e){e[e.Bundled=1]="Bundled",e[e.Github=2]="Github",e[e.ShareScript=3]="ShareScript"}(t=e.ExtensionType||(e.ExtensionType={}))}(e.service||(e.service={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){let n,i,s;!function(e){e[e.IDE=0]="IDE",e[e.Sandbox=1]="Sandbox",e[e.Widget=2]="Widget",e[e.Controller=3]="Controller"}(n=t.EditorLayoutType||(t.EditorLayoutType={})),function(e){e[e.None=0]="None",e[e.Basic=1]="Basic",e[e.App=2]="App"}(i=t.ControllerMode||(t.ControllerMode={}));let r=i.None,o=!1,a=!1;function l(){if(void 0===s){if(e.BrowserUtils.hasWindow()){const t=/sandbox=1|#sandbox|#sandboxproject/i.test(window.location.href)||e.BrowserUtils.isIFrame(),l=/nosandbox=1/i.test(window.location.href),c=/controller=(0|1|2)/i.exec(window.location.href);c&&e.BrowserUtils.isIFrame()&&(r=parseInt(c[1]));const u=r!==i.None,d=/readonly=1/i.test(window.location.href),h=/editorlayout=(widget|sandbox|ide)/i.exec(window.location.href),p=/noproject=1/i.test(window.location.href);if(s=n.IDE,l?s=n.Widget:u?s=n.Controller:t&&(s=n.Sandbox),u&&d&&(o=!0),u&&p&&(a=!0),h)switch(h[1].toLowerCase()){case"widget":s=n.Widget;break;case"sandbox":s=n.Sandbox;break;case"ide":s=n.IDE}}else s=n.Sandbox;e.debug(`shell: layout type ${n[s]}, readonly ${d()}`)}}function c(){return l(),s==n.Sandbox}function u(){return/[?&]timeMachine=1/i.test(window.location.href)}function d(){return!e.BrowserUtils.hasWindow()||u()||c()&&!/[?&]edit=1/i.test(window.location.href)||h()&&o}function h(){return l(),s==n.Controller}t.layoutTypeClass=function(){return l(),e.shell.EditorLayoutType[s].toLowerCase()},t.isSandboxMode=c,t.isTimeMachineEmbed=u,t.isReadOnly=d,t.isNoProject=function(){return a},t.isControllerMode=h,t.getControllerMode=function(){return l(),r},t.isPyLangPref=function(){return"py"==e.storage.getLocal("editorlangpref")},t.getEditorLanguagePref=function(){return e.storage.getLocal("editorlangpref")},t.setEditorLanguagePref=function(t){t.match(/prj$/)&&(t=t.replace(/prj$/,"")),e.storage.setLocal("editorlangpref",t)},t.getToolboxAnimation=function(){return e.storage.getLocal("toolboxanimation")},t.setToolboxAnimation=function(){e.storage.setLocal("toolboxanimation","1")}}(e.shell||(e.shell={}))}(pxt||(pxt={})),function(e){!function(t){t.USER_VERSION="0.0.1";class n{constructor(){this.db=new e.BrowserUtils.IDBWrapper(n.databaseName,n.version,((e,t)=>{const i=t.result;e.oldVersion<1&&(i.createObjectStore(n.projectTable,{keyPath:n.projectKey}),i.createObjectStore(n.userTable,{keyPath:n.userKey}))}))}initAsync(){return this.db.openAsync()}getAllProjectsAsync(){return this.db.getAllAsync(n.projectTable).then((e=>e.map((e=>e.project)).filter((e=>!e.deleted))))}deleteProjectAsync(e){return this.getProjectAsync(e).then((e=>{e.deleted=!0,this.saveProjectAsync(e)}))}getProjectAsync(e){return this.db.getAsync(n.projectTable,e).then((e=>null==e?void 0:e.project))}saveProjectAsync(e){return this.db.setAsync(n.projectTable,{id:e.header.id,project:e})}getUserStateAsync(){return this.db.getAsync(n.userTable,"local-user").then((e=>null==e?void 0:e.user))}saveUserStateAsync(e){return this.db.setAsync(n.userTable,{id:"local-user",user:e})}}n.version=6,n.databaseName="local-skill-map",n.projectTable="projects",n.projectKey="id",n.userTable="users",n.userKey="id",t.IndexedDBWorkspace=n}(e.skillmap||(e.skillmap={}))}(pxt||(pxt={})),function(e){!function(e){e.MAX_FREQUENCY=5e3,e.MAX_VOLUME=255,e.renderSoundPath=function(i,s,r){let{startFrequency:o,endFrequency:a,startVolume:l,endVolume:c,wave:u,interpolation:d}=i;o=Math.max(Math.min(o,e.MAX_FREQUENCY),1),a=Math.max(Math.min(a,e.MAX_FREQUENCY),1),l=Math.max(Math.min(l,e.MAX_VOLUME),0),c=Math.max(Math.min(c,e.MAX_VOLUME),0);const h=new t(o+a+1);let p;switch(d){case"linear":p=e=>o+e*(a-o)/s;break;case"curve":p=e=>o+(a-o)*Math.sin(e/s*(Math.PI/2));break;case"logarithmic":p=e=>o+Math.log10(1+e/s*9)*(a-o)}"noise"===u&&(p=()=>h.randomRange(500,5e3));const f=t=>Math.max(Math.min((c-l)/s*t+l,e.MAX_VOLUME),0),m=s/2,g=t=>t/e.MAX_VOLUME*(r-2)/2,b=t=>(1-t/e.MAX_FREQUENCY)*(m-10)+10,y=["M 2 "+r/2];let v=0;for(;v<s;)y.push(n(g(f(v)),b(p(v))/2,u,!1,h)),v+=b(p(v))/2,y.push(n(g(f(v)),b(p(v))/2,u,!0,h)),v+=b(p(v))/2;return y.join(" ")},e.renderWaveSnapshot=function(i,s,r,o,a,l){const c=new t(i);"noise"===r&&(i=c.randomRange(500,5e3)),i=Math.max(Math.min(i,e.MAX_FREQUENCY),1);const u=s/e.MAX_VOLUME*(a-2)/2,d=o/(i*l/1e3)/2;let h=Math.ceil(o/(2*d));h%2==1&&h++;const p=[`M ${o/2-h*d} ${a/2}`];let f=0;for(let e=0;e<h;e++)p.push(n(u,d,r,!1,c)),f+=d,p.push(n(u,d,r,!0,c)),f+=d;return p.join(" ")};class t{constructor(e){this.seed=e,this.lfsr=e}next(){return(this.lfsr=this.lfsr>>1^46080&-(1&this.lfsr))/65535}randomRange(e,t){return e+(t-e)*this.next()}}function n(e,t,n,i,s){switch(n){case"triangle":return`l ${t/2} ${i?e:-e} l ${t/2} ${i?-e:e}`;case"square":return`v ${i?e:-e} h ${t} v ${i?-e:e}`;case"sawtooth":return i?`l ${t} ${e} v ${-e}`:`v ${-e} l ${t} ${e}`;case"sine":return`q ${t/2} ${1.9*(i?e:-e)} ${t} 0`;case"noise":const n=[],r=[],o=Math.min(4,t/4);let a=i;for(let n=0;n<t;n+=o)r.push(s.randomRange(0,e)*(a?1:-1)),a=!a;r[0]=i?e:-e,r[r.length-1]=0;let l=0,c=0;for(const e of r){let i=Math.min(o,t-c);if(n.push(`v ${e-l} h ${i}`),l=e,c+=i,c>=t)break}return n.join(" ")}}function i(e){switch(e){case"square":return 15;case"sine":return 3;case"triangle":return 1;case"noise":return 18;case"sawtooth":return 2}}function s(e,t,n){const i=new Uint8Array(2);new Uint16Array(i.buffer)[0]=0|n,e[t]=i[0],e[t+1]=i[1]}e.soundToInstructionBuffer=function(t,n,r){const{startFrequency:o,endFrequency:a,startVolume:l,endVolume:c,interpolation:u,duration:d}=t,h=[];if("linear"===t.interpolation&&"none"===t.effect)h.push({frequency:o,volume:l/e.MAX_VOLUME*1024}),h.push({frequency:a,volume:c/e.MAX_VOLUME*1024});else{n=Math.min(n,Math.floor(d/5));const i=t=>(l+t*(c-l)/d)/e.MAX_VOLUME*1024;let s;switch(u){case"linear":s=e=>o+e*(a-o)/d;break;case"curve":s=e=>o+(a-o)*Math.sin(e/d*(Math.PI/2));break;case"logarithmic":s=e=>o+Math.log10(1+e/d*9)*(a-o)}const p=d/n;for(let e=0;e<n;e++){const n={frequency:Math.max(s(e*p),1),volume:i(e*p)};"tremolo"===t.effect?n.volume=e%2==0?Math.max(n.volume-500*r,0):Math.min(n.volume+500*r,1023):"vibrato"===t.effect?n.frequency=e%2==0?Math.max(n.frequency-100*r,1):n.frequency+100*r:"warble"===t.effect&&(n.frequency=e%2==0?Math.max(n.frequency-1e3*r,1):n.frequency+1e3*r),h.push(n)}}const p=new Uint8Array(12*(h.length-1)),f=Math.floor(d/(h.length-1));for(let e=0;e<h.length-1;e++){const n=12*e;p[n]=i(t.wave),s(p,n+2,h[e].frequency),s(p,n+4,f),s(p,n+6,h[e].volume),s(p,n+8,h[e+1].volume),s(p,n+10,h[e+1].frequency)}return p}}(e.assets||(e.assets={}))}(pxt||(pxt={})),function(e){!function(t){t.createStreamAsync=function(t,n){return e.Cloud.privatePostAsync("streams",{target:t,name:n||"data"}).then((e=>e))},t.postPayloadAsync=function(t,n){return e.Util.assert(!!t.privatekey),e.Cloud.privatePostAsync(`${t.id}/data?privatekey=${t.privatekey}`,n)}}(e.streams||(e.streams={}))}(pxt||(pxt={})),function(e){!function(t){let n,i;!function(e){e[e.userSpaceOnUse=0]="userSpaceOnUse",e[e.objectBoundingBox=1]="objectBoundingBox"}(n=t.PatternUnits||(t.PatternUnits={})),function(e){e[e.em=0]="em",e[e.ex=1]="ex",e[e.px=2]="px",e[e.in=3]="in",e[e.cm=4]="cm",e[e.mm=5]="mm",e[e.pt=6]="pt",e[e.pc=7]="pc",e[e.percent=8]="percent"}(i=t.LengthUnit||(t.LengthUnit={}));class s{constructor(e){this.el=A(e)}attr(e){return Object.keys(e).forEach((t=>{this.setAttribute(t,e[t])})),this}setAttribute(e,t){return this.el.setAttribute(e,t.toString()),this}setAttributeNS(e,t,n){return this.el.setAttributeNS(e,t,n.toString()),this}id(e){return this.setAttribute("id",e)}setClass(...e){return this.setAttribute("class",e.join(" "))}appendClass(t){return e.BrowserUtils.addClass(this.el,t),this}removeClass(t){e.BrowserUtils.removeClass(this.el,t)}title(e){this.titleElement||(this.titleElement=A("title"),this.el.firstChild?this.el.insertBefore(this.titleElement,this.el.firstChild):this.el.appendChild(this.titleElement)),this.titleElement.textContent=e}setVisible(e){return this.setAttribute("visibility",e?"visible":"hidden")}}t.BaseElement=s;class r extends s{draw(e){const t=function(e){switch(e){case"text":return new d;case"circle":return new p;case"rect":return new h;case"line":return new f;case"polygon":return new b;case"polyline":return new g;case"path":return new y;default:return new u(e)}}(e);return this.el.appendChild(t.el),t}element(e,t){return t(this.draw(e)),this}group(){const e=new o;return this.el.appendChild(e.el),e}appendChild(e){this.el.appendChild(e.el)}onDown(e){return t.events.down(this.el,e),this}onUp(e){return t.events.up(this.el,e),this}onMove(e){return t.events.move(this.el,e),this}onEnter(e){return t.events.enter(this.el,e),this}onLeave(e){return t.events.leave(this.el,e),this}onClick(e){return t.events.click(this.el,e),this}}t.DrawContext=r;t.SVG=class extends r{constructor(e){super("svg"),e&&e.appendChild(this.el)}define(e){return this.defs||(this.defs=new l(this.el)),e(this.defs),this}};class o extends r{constructor(e){super("g"),e&&e.appendChild(this.el)}translate(e,t){return this.left=e,this.top=t,this.updateTransform()}scale(e){return this.scaleFactor=e,this.updateTransform()}def(){return new l(this.el)}style(){return new c(this.el)}updateTransform(){let e="";return null!=this.left&&(e+=`translate(${this.left} ${this.top})`),null!=this.scaleFactor&&(e+=` scale(${this.scaleFactor})`),this.setAttribute("transform",e),this}}t.Group=o;class a extends r{constructor(){super("pattern")}units(e){return this.setAttribute("patternUnits",e===n.objectBoundingBox?"objectBoundingBox":"userSpaceOnUse")}contentUnits(e){return this.setAttribute("patternContentUnits",e===n.objectBoundingBox?"objectBoundingBox":"userSpaceOnUse")}size(e,t){return this.setAttribute("width",e),this.setAttribute("height",t),this}}t.Pattern=a;class l extends s{constructor(e){super("defs"),e.appendChild(this.el)}create(e,t){let n;switch(e){case"path":n=new y;break;case"pattern":n=new a;break;case"radialGradient":n=new k;break;case"linearGradient":n=new w;break;case"clipPath":n=new x;break;default:n=new s(e)}return n.id(t),this.el.appendChild(n.el),n}}t.DefsElement=l;class c extends s{constructor(e){super("style"),e.appendChild(this.el)}content(e){this.el.textContent=e}}t.StyleElement=c;class u extends r{at(e,t){return this.setAttribute("x",e),this.setAttribute("y",t),this}moveTo(e,t){return this.at(e,t)}fill(e,t){return this.setAttribute("fill",e),null!=t&&this.opacity(t),this}opacity(e){return this.setAttribute("fill-opacity",e)}stroke(e,t){return this.setAttribute("stroke",e),null!=t&&this.strokeWidth(t),this}strokeWidth(e){return this.setAttribute("stroke-width",e)}strokeOpacity(e){return this.setAttribute("stroke-opacity",e)}clipPath(e){return this.setAttribute("clip-path",e)}}t.Drawable=u;class d extends u{constructor(e){super("text"),null!=e&&this.text(e)}text(e){return this.el.textContent=e,this}fontFamily(e){return this.setAttribute("font-family",e)}fontSize(e,t){return this.setAttribute("font-size",T(e,t))}offset(e,t,n){return 0!==e&&this.setAttribute("dx",T(e,n)),0!==t&&this.setAttribute("dy",T(t,n)),this}anchor(e){return this.setAttribute("text-anchor",e)}}t.Text=d;class h extends u{constructor(){super("rect")}width(e,t=i.px){return this.setAttribute("width",T(e,t))}height(e,t=i.px){return this.setAttribute("height",T(e,t))}corner(e){return this.corners(e,e)}corners(e,t){return this.setAttribute("rx",e),this.setAttribute("ry",t),this}size(e,t,n=i.px){return this.width(e,n),this.height(t,n),this}}t.Rect=h;class p extends u{constructor(){super("circle")}at(e,t){return this.setAttribute("cx",e),this.setAttribute("cy",t),this}radius(e){return this.setAttribute("r",e)}}t.Circle=p;class f extends u{constructor(){super("line")}at(e,t,n,i){return this.from(e,t),null!=n&&null!=i&&this.to(n,i),this}from(e,t){return this.setAttribute("x1",e),this.setAttribute("y1",t),this}to(e,t){return this.setAttribute("x2",e),this.setAttribute("y2",t),this}}t.Line=f;class m extends u{points(e){return this.setAttribute("points",e)}with(e){return this.points(e.map((({x:e,y:t})=>e+" "+t)).join(","))}}t.PolyElement=m;class g extends m{constructor(){super("polyline")}}t.Polyline=g;class b extends m{constructor(){super("polygon")}}t.Polygon=b;class y extends u{constructor(){super("path"),this.d=new E}update(){return this.setAttribute("d",this.d.toAttribute())}path(e){return e(this.d),this.update()}setD(e){return this.setAttribute("d",e),this}}t.Path=y;t.Image=class extends u{constructor(){super("image")}src(e){return this.setAttributeNS("http://www.w3.org/1999/xlink","href",e)}width(e,t=i.px){return this.setAttribute("width",T(e,t))}height(e,t=i.px){return this.setAttribute("height",T(e,t))}size(e,t,n=i.px){return this.width(e,n),this.height(t,n),this}};class v extends s{units(e){return this.setAttribute("gradientUnits",e===n.objectBoundingBox?"objectBoundingBox":"userSpaceOnUse")}stop(e,t,n){const i=A("stop");return i.setAttribute("offset",e+"%"),null!=t&&i.setAttribute("stop-color",t),null!=n&&i.setAttribute("stop-opacity",n),this.el.appendChild(i),this}}t.Gradient=v;class w extends v{constructor(){super("linearGradient")}start(e,t){return this.setAttribute("x1",e),this.setAttribute("y1",t),this}end(e,t){return this.setAttribute("x2",e),this.setAttribute("y2",t),this}}t.LinearGradient=w;class k extends v{constructor(){super("radialGradient")}center(e,t){return this.setAttribute("cx",e),this.setAttribute("cy",t),this}focus(e,t,n){return this.setAttribute("fx",e),this.setAttribute("fy",t),this.setAttribute("fr",n),this}radius(e){return this.setAttribute("r",e)}}t.RadialGradient=k;class x extends r{constructor(){super("clipPath")}clipPathUnits(e){return e?this.setAttribute("clipPathUnits","objectBoundingBox"):this.setAttribute("clipPathUnits","userSpaceOnUse")}}function A(e){return document.createElementNS("http://www.w3.org/2000/svg",e)}t.ClipPath=x;class E{constructor(){this.ops=[]}clear(){this.ops=[]}moveTo(e,t){return this.op("M",e,t)}moveBy(e,t){return this.op("m",e,t)}lineTo(e,t){return this.op("L",e,t)}lineBy(e,t){return this.op("l",e,t)}cCurveTo(e,t,n,i,s,r){return this.op("C",e,t,n,i,s,r)}cCurveBy(e,t,n,i,s,r){return this.op("c",e,t,n,i,s,r)}qCurveTo(e,t,n,i){return this.op("Q",e,t,n,i)}qCurveBy(e,t,n,i){return this.op("q",e,t,n,i)}sCurveTo(e,t,n,i){return this.op("S",e,t,n,i)}sCurveBy(e,t,n,i){return this.op("s",e,t,n,i)}tCurveTo(e,t){return this.op("T",e,t)}tCurveBy(e,t){return this.op("t",e,t)}arcTo(e,t,n,i,s,r,o){return this.op("A",e,t,n,i?1:0,s?1:0,r,o)}arcBy(e,t,n,i,s,r,o){return this.op("a",e,t,n,i?1:0,s?1:0,r,o)}close(){return this.op("z")}toAttribute(){return this.ops.map((e=>e.op+" "+e.args.join(" "))).join(" ")}op(e,...t){return this.ops.push({op:e,args:t}),this}}function T(e,t){switch(t){case i.em:return e+"em";case i.ex:return e+"ex";case i.px:return e+"px";case i.in:return e+"in";case i.cm:return e+"cm";case i.mm:return e+"mm";case i.pt:return e+"pt";case i.pc:return e+"pc";case i.percent:return e+"%";default:return e.toString()}}t.PathContext=E}(e.svgUtil||(e.svgUtil={}))}(pxt||(pxt={})),function(e){!function(e){!function(e){function t(){return"undefined"!=typeof window&&("ontouchstart"in window||navigator&&navigator.maxTouchPoints>0)}function n(){return"undefined"!=typeof window&&!!window.PointerEvent}e.isTouchEnabled=t,e.hasPointerEvents=n,e.down=function(e,i){n()?e.addEventListener("pointerdown",i):t()?(e.addEventListener("mousedown",i),e.addEventListener("touchstart",i)):e.addEventListener("mousedown",i)},e.up=function(e,i){n()?e.addEventListener("pointerup",i):(t(),e.addEventListener("mouseup",i))},e.enter=function(e,i){n()?e.addEventListener("pointerover",(e=>{i(!!(1&e.buttons))})):t()?e.addEventListener("touchstart",(e=>{i(!0)})):e.addEventListener("mouseover",(e=>{i(!!(1&e.buttons))}))},e.leave=function(e,i){n()?e.addEventListener("pointerleave",i):t()?e.addEventListener("touchend",i):e.addEventListener("mouseleave",i)},e.move=function(e,i){n()?e.addEventListener("pointermove",i):t()?e.addEventListener("touchmove",i):e.addEventListener("mousemove",i)},e.click=function(e,t){e.addEventListener("click",t)}}(e.events||(e.events={}))}(e.svgUtil||(e.svgUtil={}))}(pxt||(pxt={})),function(e){!function(e){!function(t){class n extends e.Text{at(e,t){return this.cx=e,this.cy=t,this.rePosition(),this}text(e,t=12){return super.text(e),this.fontSizePixels=t,this.setAttribute("font-size",t+"px"),this.rePosition(),this}rePosition(){null!=this.cx&&null!=this.cy&&null!=this.fontSizePixels&&(this.setAttribute("x",this.cx),this.setAttribute("y",this.cy),this.setAttribute("text-anchor","middle"),this.setAttribute("alignment-baseline","middle"))}}t.CenteredText=n}(e.helpers||(e.helpers={}))}(e.svgUtil||(e.svgUtil={}))}(pxt||(pxt={})),function(e){!function(e){e.initExtensionsAsync=e=>Promise.resolve({}),e.initFieldExtensionsAsync=e=>Promise.resolve({})}(e.editor||(e.editor={}))}(pxt||(pxt={})),function(e){e.IMAGE_MIME_TYPE="image/x-mkcd-f4",e.TILEMAP_MIME_TYPE="application/mkcd-tilemap",e.ANIMATION_MIME_TYPE="application/mkcd-animation",e.SONG_MIME_TYPE="application/mkcd-song";class t{constructor(){this.assets=[],this.takenNames={},this.listeners=[]}add(e){if(this.takenNames[e.id])return this.update(e.id,e);{const t=a(e);return this.takenNames[t.id]=!0,this.takenNames[f(t)]=!0,t.meta.displayName&&t.meta.displayName!==t.id&&(this.takenNames[t.meta.displayName]&&(t.meta.displayName=this.generateNewDisplayName(t.meta.displayName)),this.takenNames[t.meta.displayName]=!0),this.assets.push(t),a(t)}}getSnapshot(e){return e?this.assets.filter((t=>e(t))).map(a):this.assets.map(a)}update(e,t){let n;if(this.takenNames[e]){h(this.lookupByID(e),t)?n=t:(this.removeByID(e),n=this.add(t),this.notifyListener(t.internalID))}else n=this.add(t);return n}removeByID(e){const t=this.lookupByID(e);this.assets=this.assets.filter((t=>t.id!==e)),delete this.takenNames[e],t&&delete this.takenNames[f(t)],(null==t?void 0:t.meta.displayName)&&delete this.takenNames[null==t?void 0:t.meta.displayName]}getByID(e){const t=this.lookupByID(e);return t&&a(t)}getByDisplayName(e){if(this.takenNames[e])for(const t of this.assets)if(t.meta.displayName===e||f(t)===e)return a(t)}isIDTaken(e){return!!this.takenNames[e]}clone(){const e=new t;return e.assets=this.getSnapshot(),e.takenNames=Object.assign({},this.takenNames),e}serializeToJRes(e={}){for(const t of this.assets)d(t,e);return e}addListener(e,t){this.listeners.push({internalID:e,callback:t})}removeListener(e){this.listeners=this.listeners.filter((t=>t.callback!==e))}diff(e){let t={before:[],after:[]},n={};for(const i of e.assets){n[i.internalID]=!0;const e=this.lookupByInternalID(i.internalID);e&&h(i,e)||(t.before.push(i),t.after.push(e))}for(const e of this.assets.filter((e=>!n[e.internalID])))t.before.push(null),t.after.push(e);return t}applyDiff(t,n=!1){const i=n?t.after:t.before,s=n?t.before:t.after;e.Util.assert(i.length===s.length);for(let e=0;e<i.length;e++)i[e]?(this.removeByInternalID(i[e].internalID),s[e]&&this.assets.push(s[e]),this.notifyListener(i[e].internalID)):(this.assets.push(s[e]),this.notifyListener(s[e].internalID));this.takenNames={};for(const t of this.assets)e.Util.assert(!this.takenNames[t.id]),this.takenNames[t.id]=!0,this.takenNames[f(t)]=!0,t.meta.displayName&&(t.meta.displayName!==t.id&&e.Util.assert(!this.takenNames[t.meta.displayName]),this.takenNames[t.meta.displayName]=!0)}lookupByID(e){for(const t of this.assets)if(t.id===e)return t;return null}lookupByInternalID(e){for(const t of this.assets)if(t.internalID===e)return t;return null}removeByInternalID(e){this.assets=this.assets.filter((t=>t.internalID!==e))}notifyListener(e){for(const t of this.listeners)t.internalID===e&&t.callback()}generateNewDisplayName(e){e=e.replace(/\d+$/,"");let t=0;for(;this.takenNames[e+t];)++t;return e+t}}class n{constructor(){this.needsRebuild=!0,this.nextID=0,this.nextInternalID=0,this.committedState={revision:0,tilemaps:new t,tiles:new t,animations:new t,images:new t,songs:new t},this.state={revision:this.nextID++,tilemaps:new t,tiles:new t,animations:new t,images:new t,songs:new t},this.gallery={revision:0,tilemaps:new t,tiles:new t,animations:new t,images:new t,songs:new t},this.undoStack=[],this.redoStack=[]}getNewInternalId(){return this.nextInternalID++}createNewImage(t=16,n=16){this.onChange();const i=this.generateNewID("image"),s=new e.sprite.Bitmap(t,n).data(),r={internalID:this.getNewInternalId(),id:i,type:"image",bitmap:s,meta:{},jresData:e.sprite.base64EncodeBitmap(s)};return this.state.images.add(r)}createNewAnimation(t=16,n=16){this.onChange();const i=this.generateNewID("animation"),s=new e.sprite.Bitmap(t,n).data(),r={internalID:this.getNewInternalId(),id:i,type:"animation",frames:[s],interval:500,meta:{}};return this.state.animations.add(r)}createNewAnimationFromData(e,t=500,n){this.onChange();const i=this.generateNewID("animation"),s={internalID:this.getNewInternalId(),id:i,type:"animation",frames:e,interval:t,meta:{displayName:n}};return this.state.animations.add(s)}getGalleryTiles(e){return this.extensionTileSets?this.extensionTileSets.map((t=>t.tileSets.find((t=>t.tileWidth===e)))).filter((e=>null==e?void 0:e.tiles.length)):null}getProjectImages(){return this.state.images.getSnapshot()}getProjectTiles(t,n){const i=this.state.tiles.getSnapshot((e=>e.bitmap.width===t));return 0===i.length?n?(this.createNewTile(new e.sprite.Bitmap(t,t).data()),this.getProjectTiles(t,!1)):null:{tileWidth:t,tiles:i}}createNewTile(t,n,i){this.onChange(),n&&!this.isNameTaken("tile",n)||(n=this.generateNewID("tile"));const s={internalID:this.getNewInternalId(),id:n,type:"tile",jresData:e.sprite.base64EncodeBitmap(t),bitmap:t,meta:{displayName:i},isProjectTile:!0};return this.state.tiles.add(s)}createNewProjectImage(t,n){this.onChange();const i={internalID:this.getNewInternalId(),id:this.generateNewID("image"),type:"image",jresData:e.sprite.base64EncodeBitmap(t),meta:{displayName:n},bitmap:t};return this.state.images.add(i)}createNewSong(t,n){this.onChange();const i={internalID:this.getNewInternalId(),id:this.generateNewID("song"),type:"song",song:e.assets.music.cloneSong(t),meta:{displayName:n}};return this.state.songs.add(i)}updateTile(t){this.onChange();const n=this.resolveProjectTileByInternalID(t.internalID);if(n){if(this.state.tiles.update(n.id,t),n.id!==t.id||!e.sprite.bitmapEquals(n.bitmap,t.bitmap))for(const e of this.getAssets("tilemap"))e.data.tileset.tiles.some((e=>e.internalID===t.internalID))&&(e.data.tileset.tiles=e.data.tileset.tiles.map((e=>e.internalID===t.internalID?t:e)),this.updateTilemap(e.id,e.data));return t}return null}deleteTile(e){this.onChange(),this.state.tiles.removeByID(e)}getProjectTilesetJRes(){const t={};return this.state.tiles.serializeToJRes(t),this.state.tilemaps.serializeToJRes(t),t["*"]={mimeType:"image/x-mkcd-f4",dataEncoding:"base64",namespace:e.sprite.TILE_NAMESPACE},t}getProjectAssetsJRes(){const t={};return this.state.images.serializeToJRes(t),this.state.animations.serializeToJRes(t),this.state.songs.serializeToJRes(t),t["*"]={mimeType:"image/x-mkcd-f4",dataEncoding:"base64",namespace:e.sprite.IMAGES_NAMESPACE},t}getTilemap(e){return this.state.tilemaps.getByID(e)}updateTilemap(e,t){const n=this.state.tilemaps.getByID(e);if(n){this.onChange();const i=Object.assign(Object.assign({},n),{data:t});return this.state.tilemaps.update(e,i),i}return null}createNewTilemap(e,t,n=16,i=16){return this.createNewTilemapFromData(this.blankTilemap(t,n,i),e)}blankTilemap(t,n=16,i=16){const s=new e.sprite.Tilemap(n,i),r=new e.sprite.Bitmap(n,i),o={tileWidth:t,tiles:[this.getTransparency(t)]};return new e.sprite.TilemapData(s,o,r.data())}resolveTile(e){return this.lookupAsset("tile",e)}resolveProjectTileByInternalID(e){return this.state.tiles.getSnapshot((t=>t.internalID===e))[0]}resolveTileByBitmap(t){const n=e.sprite.base64EncodeBitmap(t);return this.state.tiles.getSnapshot((e=>e.jresData===n))[0]}getTransparency(t){const n=e.sprite.TILE_NAMESPACE+".transparency"+t;let i=this.state.tiles.getByID(n);if(!i){const s=new e.sprite.Bitmap(t,t).data();return i={internalID:this.getNewInternalId(),id:n,type:"tile",bitmap:s,jresData:e.sprite.base64EncodeBitmap(s),meta:{},isProjectTile:!0},this.state.tiles.add(i)}return i}createNewTilemapFromData(e,t){this.onChange();const n=this.generateNewIDInternal("tilemap",t||lf("level"));return this.state.tilemaps.add({internalID:this.getNewInternalId(),id:n,type:"tilemap",meta:{displayName:t||n},data:e}),[n,e]}cloneState(){return{revision:this.state.revision,images:this.state.images.clone(),tilemaps:this.state.tilemaps.clone(),animations:this.state.animations.clone(),tiles:this.state.tiles.clone(),songs:this.state.songs.clone()}}undo(){if(this.state.revision!==this.committedState.revision&&this.pushUndo(),this.undoStack.length){const e=this.undoStack.pop();this.state.tiles.applyDiff(e.tiles,!0),this.state.images.applyDiff(e.images,!0),this.state.tilemaps.applyDiff(e.tilemaps,!0),this.state.animations.applyDiff(e.animations,!0),this.state.songs.applyDiff(e.songs,!0),this.state.revision=e.beforeRevision,this.redoStack.push(e),this.committedState=this.cloneState(),this.needsRebuild=!0}}redo(){if(this.redoStack.length){const e=this.redoStack.pop();this.state.tiles.applyDiff(e.tiles),this.state.images.applyDiff(e.images),this.state.tilemaps.applyDiff(e.tilemaps),this.state.animations.applyDiff(e.animations),this.state.songs.applyDiff(e.songs),this.state.revision=e.afterRevision,this.undoStack.push(e),this.committedState=this.cloneState(),this.needsRebuild=!0}}pushUndo(){this.undoStack.length&&this.committedState.revision===this.state.revision||(this.redoStack=[],this.undoStack.push({beforeRevision:this.committedState.revision,afterRevision:this.state.revision,tiles:this.state.tiles.diff(this.committedState.tiles),images:this.state.images.diff(this.committedState.images),tilemaps:this.state.tilemaps.diff(this.committedState.tilemaps),animations:this.state.animations.diff(this.committedState.animations),songs:this.state.songs.diff(this.committedState.songs)}),this.committedState=this.cloneState(),this.cleanupTemporaryAssets())}revision(){return this.state.revision}encodeTilemap(t,n){const i=t.tilemap.data(),s=new Uint8ClampedArray(5+i.data.length+t.layers.data.length);return s[0]=t.tileset.tileWidth,s[1]=255&i.width,s[2]=i.width>>8&255,s[3]=255&i.height,s[4]=i.height>>8&255,s.set(i.data,5),s.set(t.layers.data,5+i.data.length),{id:n,mimeType:e.TILEMAP_MIME_TYPE,data:btoa(e.sprite.uint8ArrayToHex(s)),tileset:t.tileset.tiles.map((e=>e.id))}}forceUpdate(){this.onChange()}isNameTaken(e,t){const n=t=>y(this.state,e).isIDTaken(t)||y(this.gallery,e).isIDTaken(t),i=m(e,t),s=i&&i!==t;return n(t)||s&&n(i)}isAssetUsed(t,n,i){var s,r,o;if(((null===(r=null===(s=t.meta)||void 0===s?void 0:s.blockIDs)||void 0===r?void 0:r.filter((e=>!i||(null==i?void 0:i.indexOf(e))<0)))||[]).length>0)return!0;if("tile"==t.type)for(const e of this.getAssets("tilemap"))if(!((null==i?void 0:i.indexOf(e.id))>=0)&&e.data.tileset.tiles.some((e=>e.id===t.id)))return!0;if(n){const s=e.Util.escapeForRegex(f(t)),r=e.Util.escapeForRegex(null===(o=t.meta)||void 0===o?void 0:o.displayName)||"";let a;switch(t.type){case"tile":a=`myTiles.${s}|assets.tile\`${s}\``,r&&(a+=`|assets.tile\`${r}\``);break;case"tilemap":a=`tilemap\`${s}\``;break;case"animation":a=`assets.animation\`${s}\``,r&&(a+=`|assets.animation\`${r}\``);break;case"song":a=`assets.song\`${s}\``,r&&(a+=`|assets.song\`${r}\``);break;default:a=`assets.image\`${s}\``,r&&(a+=`|assets.image\`${r}\``)}const l=new RegExp(a,"gm");let c;switch(t.type){case"tile":c=`myTiles.${s}|assets.tile("""${s}""")`,r&&(c+=`|assets.tile("""${r}""")`);break;case"tilemap":c=`assets.tilemap("""${s}""")`;break;case"animation":c=`assets.animation("""${s}""")`,r&&(c+=`|assets.animation("""${r}""")`);break;case"song":c=`assets.song("""${s}""")`,r&&(c+=`|assets.song("""${r}""")`);break;default:c=`assets.image("""${s}""")`,r&&(c+=`|assets.image("""${r}""")`)}const u=new RegExp(c,"gm");for(let e of Object.keys(n)){if((null==i?void 0:i.indexOf(e))>=0)continue;const t=n[e];if(e.match(/((?!\.g).{2}|^.{0,1})\.ts$/i)){if(t.content.match(l))return!0}else if(e.endsWith(".py")&&t.content.match(u))return!0}}return!1}lookupAsset(e,t){return y(this.state,e).getByID(t)||y(this.gallery,e).getByID(t)}lookupAssetByName(e,t){return y(this.state,e).getByDisplayName(t)}getAssets(e){return y(this.state,e).getSnapshot()}getGalleryAssets(e){return y(this.gallery,e).getSnapshot()}lookupBlockAsset(e,t){return y(this.state,e).getSnapshot((e=>{var n,i;return-1!==(null===(i=null===(n=e.meta)||void 0===n?void 0:n.blockIDs)||void 0===i?void 0:i.indexOf(t))}))[0]}updateAsset(e){switch(this.onChange(),e.type){case"tile":return this.updateTile(e);default:return y(this.state,e.type).update(e.id,e)}}duplicateAsset(e,t){var n;this.onChange();const i=a(e),s=t||(null===(n=i.meta)||void 0===n?void 0:n.displayName);let r;switch(e.type){case"image":r=this.createNewProjectImage(i.bitmap,s);break;case"tile":r=this.createNewTile(i.bitmap,null,s);break;case"tilemap":const[t,n]=this.createNewTilemapFromData(i.data,s);r=this.getTilemap(t);break;case"animation":r=this.createNewAnimationFromData(i.frames,i.interval,s);break;case"song":r=this.createNewSong(e.song,s)}return r}removeAsset(e){this.onChange(),y(this.state,e.type).removeByID(e.id)}addChangeListener(e,t){y(this.state,e.type).addListener(e.internalID,t)}removeChangeListener(e,t){y(this.state,e).removeListener(t)}loadPackage(e){const t=e.sortedDeps();this.extensionTileSets=[];for(const e of t){const t="this"===e.id,n=this.readImages(e.parseJRes(),t);for(const i of n)i.meta.package=e.id,"tile"===i.type?t?this.state.tiles.add(i):this.gallery.tiles.add(i):"image"===i.type?t?this.state.images.add(i):this.gallery.images.add(i):"animation"===i.type?t?this.state.animations.add(i):this.gallery.animations.add(i):t?this.state.songs.add(i):this.gallery.songs.add(i)}for(const n of t){const t="this"===n.id;for(const s of i(n.parseJRes()))t?this.state.tilemaps.add({internalID:this.getNewInternalId(),type:"tilemap",id:s.id,meta:{displayName:s.displayName||s.id,package:e.id},data:o(s,(e=>this.resolveTile(e)))}):this.gallery.tilemaps.add({internalID:this.getNewInternalId(),type:"tilemap",id:s.id,meta:{displayName:s.displayName||s.id,package:e.id},data:o(s,(e=>this.gallery.tiles.getByID(e)))})}this.committedState=this.cloneState(),this.undoStack=[],this.redoStack=[]}loadTilemapJRes(t,n=!1,s=!1){t=e.inflateJRes(t);const r=this.readImages(t,!s).filter((e=>"tile"===e.type));let a={};if(s)for(const e of r)this.gallery.tiles.add(e);else for(const e of r){if(n){const t=this.resolveTileByBitmap(e.bitmap);if(t){a[e.id]=t.id;continue}}const t=this.createNewTile(e.bitmap,e.id,e.meta.displayName);t.id!==e.id&&(a[e.id]=t.id)}const l=s?this.gallery:this.state;for(const e of i(t))l.tilemaps.add({internalID:this.getNewInternalId(),type:"tilemap",id:e.id,meta:{displayName:e.displayName||e.id},data:o(e,(e=>(a[e]&&(e=a[e]),this.resolveTile(e))))})}loadAssetsJRes(t,n=!1){t=e.inflateJRes(t);const i=[],s=n?this.gallery:this.state;for(const n of Object.keys(t)){const r=t[n];if(r.tilemapTile)s.tiles.add(this.generateImage(r,"tile"));else if(r.mimeType===e.IMAGE_MIME_TYPE)s.images.add(this.generateImage(r,"image"));else if(r.mimeType===e.ANIMATION_MIME_TYPE){const[e,t]=this.generateAnimation(r);t?i.push(e):s.animations.add(e)}else r.mimeType===e.SONG_MIME_TYPE&&s.songs.add(this.generateSong(r))}for(const e of i)s.animations.add(this.inflateAnimation(e,s.images.getSnapshot()))}removeInactiveBlockAssets(e){function t(t){const n=t.getSnapshot((t=>{var n;return!t.meta.displayName&&(null===(n=t.meta.blockIDs)||void 0===n?void 0:n.some((t=>-1===e.indexOf(t))))})),i=[];for(const t of n)1===t.meta.blockIDs.length?i.push(t):(t.meta.blockIDs=t.meta.blockIDs.filter((t=>-1!==e.indexOf(t))),0===t.meta.blockIDs.length&&i.push(t));for(const e of i)t.removeByID(e.id)}t(this.state.images),t(this.state.tiles),t(this.state.tilemaps),t(this.state.animations),t(this.state.songs)}clone(){var e;const t=new n;return t.committedState=l(this.committedState),t.state=l(this.state),t.gallery=l(this.gallery),t.extensionTileSets=null===(e=this.extensionTileSets)||void 0===e?void 0:e.map((e=>Object.assign(Object.assign({},e),{tileSets:e.tileSets.map((e=>Object.assign(Object.assign({},e),{tiles:e.tiles.map((e=>a(e)))})))}))),t.needsRebuild=this.needsRebuild,t.nextID=this.nextID,t.nextInternalID=this.nextInternalID,t.undoStack=this.undoStack.map((e=>c(e))),t.redoStack=this.undoStack.map((e=>c(e))),t}generateImage(t,n){return{internalID:this.getNewInternalId(),type:n,id:t.id,meta:{displayName:t.displayName,tags:t.tags},jresData:t.data,bitmap:e.sprite.getBitmapFromJResURL(`data:${e.IMAGE_MIME_TYPE};base64,${t.data}`).data()}}generateSong(t){return{internalID:this.getNewInternalId(),type:"song",id:t.id,meta:{displayName:t.displayName,tags:t.tags},song:e.assets.music.decodeSongFromHex(t.data)}}generateAnimation(e){if("json"===e.dataEncoding){let t;try{t=JSON.parse(e.data)}catch(t){console.warn("could not parse json data of '"+e.id+"'")}return[{internalID:this.getNewInternalId(),type:"animation",meta:{displayName:e.displayName,tags:e.tags},id:e.id,frames:[],frameIds:t.frames,interval:100,flippedHorizontal:t.flippedHorizontal},!0]}return[Object.assign(Object.assign({},g(e)),{internalID:this.getNewInternalId()}),!1]}inflateAnimation(t,n){return t.frames=t.frameIds.map((e=>n.find((t=>t.id===e)).bitmap)),t.flippedHorizontal&&(t.frames=t.frames.map((t=>{const n=e.sprite.Bitmap.fromData(t),i=new e.sprite.Bitmap(t.width,t.height);for(let e=0;e<i.width;e++)for(let t=0;t<i.height;t++)i.set(e,t,n.get(n.width-e-1,t));return i.data()}))),t}generateNewID(t){switch(t){case"animation":return this.generateNewIDInternal("animation",e.sprite.ANIMATION_PREFIX,e.sprite.ANIMATION_NAMESPACE);case"image":return this.generateNewIDInternal("image",e.sprite.IMAGE_PREFIX,e.sprite.IMAGES_NAMESPACE);case"tile":return this.generateNewIDInternal("tile",e.sprite.TILE_PREFIX,e.sprite.TILE_NAMESPACE);case"tilemap":return this.generateNewIDInternal("tilemap",lf("level"));case"song":return this.generateNewIDInternal("song",e.sprite.SONG_PREFIX,e.sprite.SONG_NAMESPACE)}}generateNewIDInternal(e,t,n){t=t.replace(/\d+$/,"");const i=n?n+"."+t:t;let s=1;for(;this.isNameTaken(e,i+s);)++s;return i+s}onChange(){this.needsRebuild=!0,this.state.revision=this.nextID++}readImages(t,n=!1){const i=[],s=[];for(const r of Object.keys(t)){const o=t[r];if(o.tilemapTile){const e=this.generateImage(o,"tile");e.isProjectTile=n,i.push(e)}else if(o.mimeType===e.IMAGE_MIME_TYPE)i.push(this.generateImage(o,"image"));else if(o.mimeType===e.ANIMATION_MIME_TYPE){const[e,t]=this.generateAnimation(o);t?s.push(e):i.push(e)}else o.mimeType===e.SONG_MIME_TYPE&&i.push(this.generateSong(o))}for(const e of s)i.push(this.inflateAnimation(e,i));return i}cleanupTemporaryAssets(){const e=this.state.images.getSnapshot((e=>{var t;return!e.meta.displayName&&!(null===(t=e.meta.blockIDs)||void 0===t?void 0:t.length)}));for(const t of e)this.state.images.removeByID(t.id)}}function i(t){const n=[];for(const i of Object.keys(t)){const s=t[i];s.mimeType===e.TILEMAP_MIME_TYPE&&n.push(s)}return n}function s(e,t){return`\n helpers._registerFactory("${e}", function(name: string) {\n switch(helpers.stringTrim(name)) {\n`+t.map((e=>e.keys.filter((e=>!!e)).map((e=>` case "${e}":`)).join("\n")+`return ${e.expression};`)).join("\n")+"\n }\n return null;\n })\n"}function r(t){return e.sprite.Bitmap.fromData(t).copy().data()}function o(t,n){const i=atob(t.data),s=e.U.fromHex(i),r=s[1]|s[2]<<8,o=s[3]|s[4]<<8,a={tileWidth:s[0],tiles:t.tileset.map((e=>n&&n(e)||{id:e}))},l=s.slice(5,5+r*o),c=new e.sprite.Tilemap(r,o,0,0,new Uint8ClampedArray(l)),u=s.slice(5+l.length),d=new e.sprite.Bitmap(r,o,0,0,new Uint8ClampedArray(u)).data();return new e.sprite.TilemapData(c,a,d)}function a(t){switch(t.meta=Object.assign({},t.meta),t.type){case"tile":case"image":return Object.assign(Object.assign({},t),{bitmap:r(t.bitmap)});case"animation":return Object.assign(Object.assign({},t),{frames:t.frames.map((e=>r(e)))});case"tilemap":return Object.assign(Object.assign({},t),{data:t.data.cloneData()});case"song":return Object.assign(Object.assign({},t),{song:e.assets.music.cloneSong(t.song)})}}function l(e){return{revision:e.revision,tilemaps:e.tilemaps.clone(),images:e.images.clone(),animations:e.animations.clone(),songs:e.songs.clone(),tiles:e.tiles.clone()}}function c(e){return Object.assign(Object.assign({},e),{animations:u(e.animations),tiles:u(e.tiles),images:u(e.images),tilemaps:u(e.tilemaps),songs:u(e.songs)})}function u(e){return Object.assign(Object.assign({},e),{before:e.before.map((e=>a(e))),after:e.after.map((e=>a(e)))})}function d(t,n){const i=t.id.substr(t.id.lastIndexOf(".")+1),s=t.meta.tags;switch(t.type){case"image":if(n[i]=t.jresData,t.meta.displayName||(null==s?void 0:s.length)){const r={data:t.jresData,mimeType:e.IMAGE_MIME_TYPE};t.meta.displayName&&(r.displayName=t.meta.displayName),(null==s?void 0:s.length)&&(r.tags=s),n[i]=r}break;case"tile":const r={data:t.jresData,mimeType:e.IMAGE_MIME_TYPE,tilemapTile:!0,displayName:t.meta.displayName};(null==s?void 0:s.length)&&(r.tags=s),n[i]=r;break;case"tilemap":const o=function(t,n,i){const s=t.tilemap.data(),r=new Uint8ClampedArray(5+s.data.length+t.layers.data.length);return r[0]=t.tileset.tileWidth,r[1]=255&s.width,r[2]=s.width>>8&255,r[3]=255&s.height,r[4]=s.height>>8&255,r.set(s.data,5),r.set(t.layers.data,5+s.data.length),{id:n,mimeType:e.TILEMAP_MIME_TYPE,data:btoa(e.sprite.uint8ArrayToHex(r)),tileset:t.tileset.tiles.map((e=>e.id)),displayName:i}}(t.data,t.id,t.meta.displayName);n[o.id]=o;break;case"animation":n[i]=function(t){var n;const i={namespace:t.id.substr(0,t.id.lastIndexOf(".")),id:t.id.substr(t.id.lastIndexOf(".")+1),mimeType:e.ANIMATION_MIME_TYPE,data:e.sprite.encodeAnimationString(t.frames,t.interval),displayName:t.meta.displayName};(null===(n=t.meta.tags)||void 0===n?void 0:n.length)&&(i.tags=t.meta.tags);return i}(t);break;case"song":const a={data:e.assets.music.encodeSongToHex(t.song),mimeType:e.SONG_MIME_TYPE,displayName:t.meta.displayName,namespace:e.sprite.SONG_NAMESPACE+"."};(null==s?void 0:s.length)&&(a.tags=s),n[i]=a}}function h(t,n){if(t==n)return!0;if(t.id!==n.id||t.type!==n.type||!e.U.arrayEquals(t.meta.tags,n.meta.tags)||!e.U.arrayEquals(t.meta.blockIDs,n.meta.blockIDs)||t.meta.displayName!==n.meta.displayName)return!1;switch(t.type){case"image":case"tile":return e.sprite.bitmapEquals(t.bitmap,n.bitmap);case"animation":const i=n;return t.interval===i.interval&&e.U.arrayEquals(t.frames,i.frames,e.sprite.bitmapEquals);case"tilemap":return t.data.equals(n.data);case"song":return e.assets.music.songEquals(t.song,n.song)}}function p(e){const t=/^\s*(?:(?:assets\s*\.\s*(image|tile|animation|tilemap|song))|(tilemap))\s*(?:`|\(""")([^`"]+)(?:`|"""\))\s*$/m.exec(e);if(t){return{type:t[1]||t[2],name:t[3].trim()}}}function f(e){return m(e.type,e.id)}function m(t,n,i=!1){let s;switch(t){case"image":s=e.sprite.IMAGES_NAMESPACE+".";break;case"tile":s=e.sprite.TILE_NAMESPACE+".";break;case"tilemap":s="";break;case"animation":s=e.sprite.ANIMATION_NAMESPACE+".";break;case"song":s=e.sprite.SONG_NAMESPACE+"."}if(s)if(n.startsWith(s)){const e=n.substr(s.length);if(-1===e.indexOf("."))return e}else if(!i)return null;return n}function g(t){const n=atob(t.data),i=new Uint8ClampedArray(e.U.fromHex(n)),s=b(i,0),r=b(i,2),o=b(i,4),a=b(i,6),l=Math.ceil(r*o/2);let c=8;const u=[];for(let e=0;e<a;e++){const e=i.slice(c,c+l);u.push({x0:0,y0:0,width:r,height:o,data:e}),c+=l}let d=t.id;return d.startsWith(t.namespace)||(d=t.namespace+"."+d,d=d.replace(/\.\./g,".")),{type:"animation",internalID:0,id:d,interval:s,frames:u,meta:{displayName:t.displayName,tags:t.tags}}}function b(e,t){return e[t]|e[t+1]<<8}function y(e,t){switch(t){case"animation":return e.animations;case"image":return e.images;case"tile":return e.tiles;case"tilemap":return e.tilemaps;case"song":return e.songs}}e.TilemapProject=n,e.emitGalleryDeclarations=function(t,n){var i;const s=Object.keys(t);let r="";const a={},l={},c={},u=e=>{let n=t[e].namespace||t["*"].namespace;const i=t[e].id||e;return n&&(n.endsWith(".")&&(n=n.slice(0,n.length-1)),!i.startsWith(n+"."))?n+"."+i:i};t["*"]&&(c["*"]=Object.assign(Object.assign({},t["*"]),{namespace:n}));for(const e of s){if("*"===e)continue;const i=t[e],s=u(e);let r=ts.pxtc.escapeIdentifier(i.displayName||s.split(".").pop());if(a[r]){const e=r;let t=2;for(;a[r];)r=e+t,t++}a[r]=!0,l[s]=n+"."+r}for(const a of s){if("*"===a)continue;const s=t[a];let d,h,p=s.mimeType||(null===(i=t["*"])||void 0===i?void 0:i.mimeType);const f=l[u(a)].split(".").pop();let m=s.tags;if(m||(m=[],-1!==f.toLowerCase().indexOf("background")&&m.push("background"),-1!==f.toLowerCase().indexOf("dialog")&&m.push("dialog"),s.tilemapTile&&m.push("tile")),p===e.IMAGE_MIME_TYPE)h="image.ofBuffer(hex``)",d=s.tilemapTile?"images._tile":"images._image";else if(p===e.ANIMATION_MIME_TYPE){h=`[${g(s).frames.map((t=>e.sprite.bitmapToImageLiteral(e.sprite.Bitmap.fromData(t),"typescript"))).join(",")}]`}else if(p===e.TILEMAP_MIME_TYPE){const t=o(s);h=e.sprite.encodeTilemap(t,"typescript",l)}else p===e.SONG_MIME_TYPE&&(h=`hex\`${s.data}\``);r+=" //% fixedInstance jres whenUsed\n",d&&(r+=` //% blockIdentity=${d}\n`),m.length&&(r+=` //% tags="${m.join(" ")}"\n`),r+=` export const ${f} = ${h};\n`,"string"==typeof s?c[f]=s:(c[f]=Object.assign(Object.assign({},s),{id:l[u(a)],tags:m}),s.namespace&&(c[f].namespace=n,s.namespace.endsWith(".")&&(c[f].namespace+=".")),c[f].tileset&&(c[f].tileset=s.tileset.map((e=>l[e]||e))))}const d=lf("Auto-generated code. Do not edit.");return[c,`// ${d}\nnamespace ${n} {\n${r}\n}\n// ${d}\n`]},e.emitTilemapsFromJRes=function(t){const n=Object.keys(t);let i="";const r=[],a=[];for(const s of n){if("*"===s)continue;const n=t[s];if(n.tilemapTile){let e=s;-1!==e.indexOf(".")&&(e=e.split(".").slice(-1)[0]),i+=" //% fixedInstance jres blockIdentity=images._tile\n",i+=` export const ${e} = image.ofBuffer(hex\`\`);\n`,a.push({keys:[n.displayName,m("tile",s,!0)],expression:s})}if(n.mimeType===e.TILEMAP_MIME_TYPE){const t=o(n);r.push({keys:[n.displayName,m("tilemap",n.id)],expression:e.sprite.encodeTilemap(t,"typescript")})}}r.length&&(i+=s("tilemap",r)),a.length&&(i+=s("tile",a));const l=lf("Auto-generated code. Do not edit.");return`// ${l}\nnamespace ${e.sprite.TILE_NAMESPACE} {\n${i}\n}\n// ${l}\n`},e.emitProjectImages=function(t){const n=Object.keys(t);let i="";const r=[],o=[],a=[];for(const i of n){if("*"===i)continue;const n=t[i];if("string"==typeof n||n.mimeType===e.IMAGE_MIME_TYPE){let t,s=[m("image",i,!0)];"string"==typeof n?t=e.sprite.bitmapToImageLiteral(e.sprite.getBitmapFromJResURL(n),"typescript"):(t=e.sprite.bitmapToImageLiteral(e.sprite.getBitmapFromJResURL(n.data),"typescript"),s.push(n.displayName)),r.push({keys:s,expression:t})}else if(n.mimeType===e.ANIMATION_MIME_TYPE){const t=g(n);o.push({keys:[n.displayName,m("animation",i,!0)],expression:`[${t.frames.map((t=>e.sprite.bitmapToImageLiteral(e.sprite.Bitmap.fromData(t),"typescript"))).join(", ")}]`})}else n.mimeType===e.SONG_MIME_TYPE&&a.push({keys:[m("song",i,!0),n.displayName],expression:`hex\`${n.data}\``})}const l=lf("Auto-generated code. Do not edit.");return i+=s("image",r),i+=s("animation",o),i+=s("song",a),`// ${l}\nnamespace ${e.sprite.IMAGES_NAMESPACE} {\n${i}\n}\n// ${l}\n`},e.cloneAsset=a,e.assetEquals=h,e.validateAssetName=function(e){return!!e&&!/[\u0000-\u001f\u0021-\u002c\u002e\u002f\u003a-\u0040\u005b-\u005e\u0060\u007b-\u007f]/.test(e)},e.getTSReferenceForAsset=function(e,t=!1){var n;let i;if(i=(null===(n=e.meta)||void 0===n?void 0:n.displayName)?e.meta.displayName:f(e),!i)return"image"===e.type||"tile"===e.type?e.id:void 0;const s=t?'("""':"`",r=t?'""")':"`";switch(e.type){case"tile":return`assets.tile${s}${i}${r}`;case"image":return`assets.image${s}${i}${r}`;case"animation":return`assets.animation${s}${i}${r}`;case"tilemap":return`tilemap${s}${i}${r}`;case"song":return`assets.song${s}${i}${r}`}},e.parseAssetTSReference=p,e.lookupProjectAssetByTSReference=function(e,t){const n=p(e);if(n){const{type:e,name:i}=n;switch(e){case"tile":return t.lookupAssetByName("tile",i);case"image":return t.lookupAssetByName("image",i);case"tilemap":return t.lookupAssetByName("tilemap",i)||t.lookupAsset("tilemap",i);case"animation":return t.lookupAssetByName("animation",i);case"song":return t.lookupAssetByName("song",i)}}},e.getDefaultAssetDisplayName=function(e){switch(e){case"image":return lf("myImage");case"tile":return lf("myTile");case"tilemap":return lf("level");case"animation":return lf("myAnim");case"song":return lf("mySong");default:return lf("asset")}},e.getShortIDForAsset=f}(pxt||(pxt={})),function(e){!function(t){const n={};t.blockColors={loops:"#107c10",logic:"#006970",math:"#712672",variables:"#A80000",functions:"#005a9e",text:"#996600",arrays:"#A94400",advanced:"#3c3c3c",addpackage:"#717171",search:"#000",debug:"#e03030",default:"#dddddd",topblocks:"#aa8f00",recipes:"#717171"},t.blockIcons={loops:"",logic:"",math:"",variables:"",functions:"",text:"",arrays:"",advancedcollapsed:"",advancedexpanded:"",more:"",addpackage:"",search:"",debug:"",default:"",topblocks:"",recipes:""};let i="";function s(e){const t=function(e,t,n){let i=0,s=0,r=0;if(0==t)i=n,s=n,r=n;else{let o=Math.floor(e/60),a=e/60-o,l=n*(1-t),c=n*(1-t*a),u=n*(1-t*(1-a));switch(o){case 1:i=c,s=n,r=l;break;case 2:i=l,s=n,r=u;break;case 3:i=l,s=c,r=n;break;case 4:i=u,s=l,r=n;break;case 5:i=n,s=l,r=c;break;case 6:case 0:i=n,s=u,r=l}}return[Math.floor(i),Math.floor(s),Math.floor(r)]}(e,.45,165.75);return`#${r(t[0])}${r(t[1])}${r(t[2])}`}function r(e){const t=e.toString(16);return 1==t.length?"0"+t:t}function o(t){var i,s;return(null===(s=null===(i=e.appTarget)||void 0===i?void 0:i.appTheme)||void 0===s?void 0:s.adjustBlockContrast)?(n[t]||(n[t]=e.getWhiteContrastingBackground(t)),n[t]):t}t.appendToolboxIconCss=function(t,n){if(!(i.indexOf(t)>-1))if(1===n.length){const s=e.Util.unicodeToChar(n);i+=`\n .blocklyTreeIcon.${t}::before {\n content: "${s}";\n }\n `}else i+=`\n .blocklyTreeIcon.${t} {\n background-image: url("${e.Util.pathJoin(e.webConfig.commitCdnUrl,encodeURI(n))}")!important;\n width: 30px;\n height: 100%;\n background-size: 20px !important;\n background-repeat: no-repeat !important;\n background-position: 50% 50% !important;\n }\n `},t.getNamespaceColor=function(t){let n;return t=t.toLowerCase(),e.appTarget.appTheme.blockColors&&e.appTarget.appTheme.blockColors[t]?n=e.appTarget.appTheme.blockColors[t]:e.toolbox.blockColors[t]&&(n=e.toolbox.blockColors[t]),n?o(n):""},t.getNamespaceIcon=function(t){return t=t.toLowerCase(),e.appTarget.appTheme.blockIcons&&e.appTarget.appTheme.blockIcons[t]?e.appTarget.appTheme.blockIcons[t]:e.toolbox.blockIcons[t]?e.toolbox.blockIcons[t]:""},t.advancedTitle=function(){return e.Util.lf("{id:category}Advanced")},t.addPackageTitle=function(){return e.Util.lf("{id:category}Extensions")},t.recipesTitle=function(){return e.Util.lf("{id:category}Tutorials")},t.convertColor=function(e){var t;e=(t=e)?"0x"==t.substring(0,2)?"#"+t.substring(2):t:"#000000";const n=parseInt(e);return isNaN(n)?e:s(n)},t.hueToRgb=s,t.fadeColor=function(e,t,n){(e=e.replace(/[^0-9a-f]/gi,"")).length<6&&(e=e[0]+e[0]+e[1]+e[1]+e[2]+e[2]);let i="#";for(let s=0;s<3;s++){let r=parseInt(e.substr(2*s,2),16);r=Math.round(Math.min(Math.max(0,n?r+r*t:r-r*t),255));let o=r.toString(16);i+=("00"+o).substr(o.length)}return i},t.getAccessibleBackground=o}(e.toolbox||(e.toolbox={}))}(pxt||(pxt={})),function(e){!function(t){const n=/^##[^#](.*)$([\s\S]*?)(?=^##[^#]|$(?![\r\n]))/gim,i=/^###[^#](.*)$([\s\S]*?)(?=^###[^#]|$(?![\r\n]))/gim;function s(){return/``` *(sim|block|blocks|filterblocks|spy|ghost|typescript|ts|js|javascript|template|python|jres|assetjson|customts|simtheme|python-template|ts-template|typescript-template|js-template|javascript-template)\s*\n([\s\S]*?)\n```/gim}function r(t,i,s){let r=i||n,c=[];if(t.replace(r,(function(e,t,n){n=n.trim();let{header:i,hint:r}=function(e,t){let n,i=e=l(e);if(t){const t=/#+ ~ tutorialhint([\s\S]*)/i;i=e.replace(t,(function(e,t){return n=t,""}))}else{const t=/(^[\s\S]*?\S)\s*((```|\[?\!\[[\s\S]+?\]\(\S+?\)\]?)[\s\S]*)/im;let s=e.match(t);s&&s.length>2&&(i=s[1].trim(),n=s[2].trim())}return{header:i,hint:n}}(n,s&&s.explicitHints);const u=o("local",n),d=a("local",n);let h={title:t.match(/^\{.*\}$/)?void 0:t.replace(/@(fullscreen|unplugged|showdialog|showhint|tutorialCompleted|resetDiff)/gi,"").trim(),contentMd:n,headerContentMd:i,localBlockConfig:u,localValidationConfig:d};return/@(fullscreen|unplugged|showdialog|showhint)/i.test(t)&&(h.showHint=!0),/@(unplugged|showdialog)/i.test(t)&&(h.showDialog=!0),/@tutorialCompleted/.test(t)&&(h.tutorialCompleted=!0),/@resetDiff/.test(t)&&(h.resetDiff=!0),r&&(h.hintContentMd=r),c.push(h),""})),0!=t.indexOf("# Not found"))return c;e.debug("tutorial not found")}function o(e,t){let n={md:"",blocks:[]};const i=new RegExp(`\`\`\`\\s*blockconfig\\.${e}\\s*\\n([\\s\\S]*?)\\n\`\`\``,"gmi");return t.replace(i,((e,t)=>(n.md+=`${t}\n`,""))),n}function a(t,n){let i;const s=new RegExp(`\`\`\`\\s*validation\\.${t}\\s*\\n([\\s\\S]*?)\\n\`\`\``,"gmi");if(n.replace(s,((e,t)=>(i=t,""))),!i||""==i)return null;return{validatorsMetadata:e.getSectionsFromMarkdownMetadata(i).map((e=>({validatorType:e.header,properties:e.attributes})))}}function l(e){if(!e)return e;return e.replace(/```(filterblocks|package|ghost|config|template|jres|assetjson|simtheme|customts|blockconfig\.local|blockconfig\.global|validation\.local|validation\.global)\s*\n([\s\S]*?)\n```/gim,"").trim()}function c(t){if(!t)return;const n=JSON.parse(t);return{[e.TILEMAP_JRES]:n[e.TILEMAP_JRES],[e.TILEMAP_CODE]:n[e.TILEMAP_CODE],[e.IMAGES_JRES]:n[e.IMAGES_JRES],[e.IMAGES_CODE]:n[e.IMAGES_CODE]}}function u(t){const n=e.Util.jsonTryParse(t);if(!n)return;const i={};return n.theme&&(i.theme=n.theme),n.palette&&(i.palette=n.palette),i}t.parseTutorial=function(t){const{metadata:s,body:d}=function(t){const n=/### @(\S+) ([ \S]+)/gi,i={},s=t.replace(n,(function(e,t,n){try{i[t]=JSON.parse(n)}catch(e){i[t]=n}return""})),r=i;void 0!==r.explicitHints&&e.appTarget.appTheme&&e.appTarget.appTheme.tutorialExplicitHints&&(r.explicitHints=!0);return{metadata:r,body:s}}(t),{steps:h,activities:p}=function(e,t){if(t&&t.activities)return function(e,t){let s=[],o=[];return e.replace(n,(function(e,n,a){let l=o.length;o.push({name:n||lf("Activity {0}",l),step:s.length});let c=r(a,i,t);return c=c.map((e=>(e.activity=l,e))),s=s.concat(c),""})),{steps:s,activities:o}}(e,t);{let n=r(e,null,t);return(!n||n.length<1)&&(n=r(e,i,t)),{steps:n,activities:null}}}(d,s),f=function(e){let t=e.match(/^#[^#](.*)$/im);return t&&t.length>1?t[1].trim():null}(d);if(!h)return;const{code:m,templateCode:g,templateLanguage:b,editor:y,language:v,jres:w,assetJson:k,customTs:x,simThemeJson:A}=function(t){let n;const i=/``` *(sim|block|blocks|filterblocks|spy|ghost|typescript|ts|js|javascript|template|python|jres|assetjson|customts|simtheme|python-template|ts-template|typescript-template|js-template|javascript-template)\s*\n([\s\S]*?)\n```/gim;let s,r,o,a,l,c,u,d=[];return t.replace(/((?!.)\s)+/g,"\n").replace(i,(function(t,n,i){switch(n){case"block":case"blocks":case"blockconfig.local":case"blockconfig.global":case"filterblocks":if(!h(e.BLOCKS_PROJECT_NAME))return;break;case"spy":case"python":if(!h(e.PYTHON_PROJECT_NAME))return;"python"==n&&(a=n);break;case"typescript":case"ts":case"javascript":case"js":if(!h(e.JAVASCRIPT_PROJECT_NAME))return;break;case"template":r=i;break;case"python-template":if(!h(e.PYTHON_PROJECT_NAME))return;r=i,o="python",a="python";break;case"ts-template":case"typescript-template":case"js-template":case"javascript-template":if(!h(e.JAVASCRIPT_PROJECT_NAME))return;r=i,o="typescript";break;case"jres":s=i;break;case"assetjson":l=i;break;case"simtheme":u=i;break;case"customts":c=i,i=""}return d.push("python"==n?`\n${i}\n`:`{\n${i}\n}`),""})),n=n||e.BLOCKS_PROJECT_NAME,{code:d,templateCode:r,templateLanguage:o,editor:n,language:a,jres:s,assetJson:l,customTs:c,simThemeJson:u};function h(t){return n&&n!=t?(e.debug("tutorial ambiguous: contains snippets of different types"),!1):(n=t,!0)}}(d);(!0===s.diffs||!1!==s.diffs&&!0!==s.noDiffs&&(y==e.BLOCKS_PROJECT_NAME&&e.appTarget.appTheme.tutorialBlocksDiff||y!=e.BLOCKS_PROJECT_NAME&&e.appTarget.appTheme.tutorialTextDiff))&&function(e,t){let n;function i(e){const t={typescript:"diff",spy:"diffspy",blocks:"diffblocks",python:"diff"},i=/\s*(\/\/|#)\s*@highlight/gm;return e?e.replace(/```(typescript|spy|python|blocks|ghost|template)((?:.|[\r\n])+)```/,(function(e,s,r){const o=n,a=/^(template|ghost)$/.test(s),l=i.test(r);return r=r.replace(/^\n+/,"").replace(/\n+$/,""),l&&(r=r.replace(i,"")),n=r,!o||l||a?e:`\`\`\`${t[s]}\n${o}\n----------\n${r}\n\`\`\``})):e}e.forEach(((e,s)=>{if((e.resetDiff||t&&t.find((e=>e.step==s)))&&(n=void 0),e.hintContentMd){const t=i(e.hintContentMd);if(t&&t!=e.hintContentMd)return void(e.hintContentMd=t)}if(e.headerContentMd){const t=i(e.headerContentMd);if(t&&t!=e.headerContentMd)return void(e.headerContentMd=t)}}))}(h,p);const E=c(k),T=u(A),S=o("global",t),C=a("global",t);return h.forEach((e=>{e.contentMd=l(e.contentMd),e.headerContentMd=l(e.headerContentMd),e.hintContentMd=l(e.hintContentMd)})),{editor:y,title:f,steps:h,activities:p,code:m,templateCode:g,templateLanguage:b,metadata:s,language:v,jres:w,assetFiles:E,customTs:x,globalBlockConfig:S,globalValidationConfig:C,simTheme:T}},t.getMetadataRegex=s,t.highlight=function(e){let t=e.textContent;if(t=t.replace(/img\s*\(\s*"{3}[\s\da-f.#tngrpoyw]*"{3}\s*\)/g,'img(""" """)'),t=t.replace(/img\s*`[\s\da-f.#tngrpoyw]*`\s*/g,"img` `"),!/@highlight/.test(t))return void(e.textContent=t);e.textContent="";const n=t.split("\n");for(let t=0;t<n.length;++t){t>0&&t<n.length&&e.appendChild(document.createTextNode("\n"));let i=n[t];if(/@highlight/.test(i)){if(i=n[++t],void 0!==i){const t=document.createElement("span");t.className="highlight-line",t.textContent=i,e.appendChild(t)}}else e.appendChild(document.createTextNode(i))}},t.getTutorialOptions=function(t,n,i,s,r){var o;const a=e.tutorial.parseTutorial(t);if(!a)throw new Error(lf("Invalid tutorial format"));return{options:{tutorial:n,tutorialName:a.title||i,tutorialReportId:s,tutorialStep:0,tutorialReady:!0,tutorialHintCounter:0,tutorialStepInfo:a.steps,tutorialActivityInfo:a.activities,tutorialMd:t,tutorialCode:a.code,tutorialRecipe:!!r,templateCode:a.templateCode,templateLanguage:a.templateLanguage,autoexpandStep:!(null===(o=a.metadata)||void 0===o?void 0:o.autoexpandOff),metadata:a.metadata,language:a.language,jres:a.jres,assetFiles:a.assetFiles,customTs:a.customTs,globalBlockConfig:a.globalBlockConfig,globalValidationConfig:a.globalValidationConfig,simTheme:a.simTheme},editor:a.editor}},t.parseCachedTutorialInfo=function(t,n){let i=e.Util.jsonTryParse(t);return i?e.BrowserUtils.tutorialInfoDbAsync().then((e=>{if(n&&i[n]){const t=i[n];t.usedBlocks&&t.hash&&e.setWithHashAsync(n,t.snippetBlocks,t.hash,t.highlightBlocks,t.validateBlocks)}else for(let t of Object.keys(i)){const n=i[t];n.usedBlocks&&n.hash&&e.setWithHashAsync(t,n.snippetBlocks,n.hash,n.highlightBlocks,n.validateBlocks)}})).catch((e=>{})):Promise.resolve()},t.resolveLocalizedMarkdown=function(t,n,i){const s=(i||t.fileName||"README")+".md";let r;const[o,a,l]=e.Util.normalizeLanguageCode(e.Util.userLanguage());return r=o&&a&&l?n[`_locales/${o}/${s}`]||n[`_locales/${l}/${s}`]||n[`_locales/${a}/${s}`]:n[`_locales/${o}/${s}`],r=r||n[s],r},t.parseAssetJson=c,t.parseSimThemeJson=u,t.getTutorialHighlightedBlocks=async function(t){const n=await e.BrowserUtils.tutorialInfoDbAsync(),i=await n.getAsync(t.tutorial,t.tutorialCode);return null==i?void 0:i.highlightBlocks},t.getTutorialValidateBlocks=async function(t){const n=await e.BrowserUtils.tutorialInfoDbAsync(),i=await n.getAsync(t.tutorial,t.tutorialCode);return null==i?void 0:i.validateBlocks},t.getRequiredBlockCounts=function(e){if(!e)return;const t={},n=e["validate-exists"];return n&&n.forEach((e=>{t[e]=(t[e]||0)+1})),t},t.getTutorialStepHash=function(t){const{tutorialStepInfo:n,tutorialStep:i}=t,s=function(e){let t=[];return null==e||e.replace(/((?!.)\s)+/g,"\n").replace(/``` *(block|blocks)\s*\n([\s\S]*?)\n```/gim,(function(e,n,i){return t.push(`{\n${i}\n}`),""})),t}(n[i].hintContentMd);return e.BrowserUtils.getTutorialCodeHash(s)}}(e.tutorial||(e.tutorial={}))}(pxt||(pxt={})),function(e){!function(t){let n;t.flattenDiagnosticMessageText=function(e,t){if("string"==typeof e)return e;{let n=e,i="",s=0;for(;n;){if(s){i+=t;for(let e=0;e<s;e++)i+=" "}i+=n.messageText,s++,n=n.next}return i}},function(e){e[e.ES3=0]="ES3",e[e.ES5=1]="ES5",e[e.ES6=2]="ES6",e[e.ES2015=2]="ES2015",e[e.Latest=2]="Latest"}(n=t.ScriptTarget||(t.ScriptTarget={})),t.isIdentifierStart=function(e,t){return e>=65&&e<=90||e>=97&&e<=122||36===e||95===e||e>127&&a(e,t)},t.isIdentifierPart=function(e,t){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||36===e||95===e||e>127&&function(e,t){return t>=n.ES5?l(e,s):l(e,o)}(e,t)},t.reservedWords=["abstract","any","as","break","case","catch","class","continue","const","constructor","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","is","let","module","namespace","new","null","package","private","protected","public","require","global","return","set","static","super","switch","symbol","this","throw","true","try","type","typeof","var","void","while","with","yield","async","await","of","Math"],t.keywordTypes=["boolean","number","string"],t.escapeIdentifier=function(n){if(!n)return"_";let i=n.replace(/\s+/g,"_").replace(/[^a-zA-Z0-9_$]/g,(t=>e.pxtc.isIdentifierPart(t.charCodeAt(0),e.pxtc.ScriptTarget.ES5)?t:""));return i&&e.pxtc.isIdentifierStart(i.charCodeAt(0),e.pxtc.ScriptTarget.ES5)&&-1===t.reservedWords.indexOf(i)||(i="_"+i),i};const i=[170,170,181,181,186,186,192,214,216,246,248,705,710,721,736,740,748,748,750,750,880,884,886,887,890,893,902,902,904,906,908,908,910,929,931,1013,1015,1153,1162,1319,1329,1366,1369,1369,1377,1415,1488,1514,1520,1522,1568,1610,1646,1647,1649,1747,1749,1749,1765,1766,1774,1775,1786,1788,1791,1791,1808,1808,1810,1839,1869,1957,1969,1969,1994,2026,2036,2037,2042,2042,2048,2069,2074,2074,2084,2084,2088,2088,2112,2136,2208,2208,2210,2220,2308,2361,2365,2365,2384,2384,2392,2401,2417,2423,2425,2431,2437,2444,2447,2448,2451,2472,2474,2480,2482,2482,2486,2489,2493,2493,2510,2510,2524,2525,2527,2529,2544,2545,2565,2570,2575,2576,2579,2600,2602,2608,2610,2611,2613,2614,2616,2617,2649,2652,2654,2654,2674,2676,2693,2701,2703,2705,2707,2728,2730,2736,2738,2739,2741,2745,2749,2749,2768,2768,2784,2785,2821,2828,2831,2832,2835,2856,2858,2864,2866,2867,2869,2873,2877,2877,2908,2909,2911,2913,2929,2929,2947,2947,2949,2954,2958,2960,2962,2965,2969,2970,2972,2972,2974,2975,2979,2980,2984,2986,2990,3001,3024,3024,3077,3084,3086,3088,3090,3112,3114,3123,3125,3129,3133,3133,3160,3161,3168,3169,3205,3212,3214,3216,3218,3240,3242,3251,3253,3257,3261,3261,3294,3294,3296,3297,3313,3314,3333,3340,3342,3344,3346,3386,3389,3389,3406,3406,3424,3425,3450,3455,3461,3478,3482,3505,3507,3515,3517,3517,3520,3526,3585,3632,3634,3635,3648,3654,3713,3714,3716,3716,3719,3720,3722,3722,3725,3725,3732,3735,3737,3743,3745,3747,3749,3749,3751,3751,3754,3755,3757,3760,3762,3763,3773,3773,3776,3780,3782,3782,3804,3807,3840,3840,3904,3911,3913,3948,3976,3980,4096,4138,4159,4159,4176,4181,4186,4189,4193,4193,4197,4198,4206,4208,4213,4225,4238,4238,4256,4293,4295,4295,4301,4301,4304,4346,4348,4680,4682,4685,4688,4694,4696,4696,4698,4701,4704,4744,4746,4749,4752,4784,4786,4789,4792,4798,4800,4800,4802,4805,4808,4822,4824,4880,4882,4885,4888,4954,4992,5007,5024,5108,5121,5740,5743,5759,5761,5786,5792,5866,5870,5872,5888,5900,5902,5905,5920,5937,5952,5969,5984,5996,5998,6e3,6016,6067,6103,6103,6108,6108,6176,6263,6272,6312,6314,6314,6320,6389,6400,6428,6480,6509,6512,6516,6528,6571,6593,6599,6656,6678,6688,6740,6823,6823,6917,6963,6981,6987,7043,7072,7086,7087,7098,7141,7168,7203,7245,7247,7258,7293,7401,7404,7406,7409,7413,7414,7424,7615,7680,7957,7960,7965,7968,8005,8008,8013,8016,8023,8025,8025,8027,8027,8029,8029,8031,8061,8064,8116,8118,8124,8126,8126,8130,8132,8134,8140,8144,8147,8150,8155,8160,8172,8178,8180,8182,8188,8305,8305,8319,8319,8336,8348,8450,8450,8455,8455,8458,8467,8469,8469,8473,8477,8484,8484,8486,8486,8488,8488,8490,8493,8495,8505,8508,8511,8517,8521,8526,8526,8544,8584,11264,11310,11312,11358,11360,11492,11499,11502,11506,11507,11520,11557,11559,11559,11565,11565,11568,11623,11631,11631,11648,11670,11680,11686,11688,11694,11696,11702,11704,11710,11712,11718,11720,11726,11728,11734,11736,11742,11823,11823,12293,12295,12321,12329,12337,12341,12344,12348,12353,12438,12445,12447,12449,12538,12540,12543,12549,12589,12593,12686,12704,12730,12784,12799,13312,19893,19968,40908,40960,42124,42192,42237,42240,42508,42512,42527,42538,42539,42560,42606,42623,42647,42656,42735,42775,42783,42786,42888,42891,42894,42896,42899,42912,42922,43e3,43009,43011,43013,43015,43018,43020,43042,43072,43123,43138,43187,43250,43255,43259,43259,43274,43301,43312,43334,43360,43388,43396,43442,43471,43471,43520,43560,43584,43586,43588,43595,43616,43638,43642,43642,43648,43695,43697,43697,43701,43702,43705,43709,43712,43712,43714,43714,43739,43741,43744,43754,43762,43764,43777,43782,43785,43790,43793,43798,43808,43814,43816,43822,43968,44002,44032,55203,55216,55238,55243,55291,63744,64109,64112,64217,64256,64262,64275,64279,64285,64285,64287,64296,64298,64310,64312,64316,64318,64318,64320,64321,64323,64324,64326,64433,64467,64829,64848,64911,64914,64967,65008,65019,65136,65140,65142,65276,65313,65338,65345,65370,65382,65470,65474,65479,65482,65487,65490,65495,65498,65500],s=[170,170,181,181,186,186,192,214,216,246,248,705,710,721,736,740,748,748,750,750,768,884,886,887,890,893,902,902,904,906,908,908,910,929,931,1013,1015,1153,1155,1159,1162,1319,1329,1366,1369,1369,1377,1415,1425,1469,1471,1471,1473,1474,1476,1477,1479,1479,1488,1514,1520,1522,1552,1562,1568,1641,1646,1747,1749,1756,1759,1768,1770,1788,1791,1791,1808,1866,1869,1969,1984,2037,2042,2042,2048,2093,2112,2139,2208,2208,2210,2220,2276,2302,2304,2403,2406,2415,2417,2423,2425,2431,2433,2435,2437,2444,2447,2448,2451,2472,2474,2480,2482,2482,2486,2489,2492,2500,2503,2504,2507,2510,2519,2519,2524,2525,2527,2531,2534,2545,2561,2563,2565,2570,2575,2576,2579,2600,2602,2608,2610,2611,2613,2614,2616,2617,2620,2620,2622,2626,2631,2632,2635,2637,2641,2641,2649,2652,2654,2654,2662,2677,2689,2691,2693,2701,2703,2705,2707,2728,2730,2736,2738,2739,2741,2745,2748,2757,2759,2761,2763,2765,2768,2768,2784,2787,2790,2799,2817,2819,2821,2828,2831,2832,2835,2856,2858,2864,2866,2867,2869,2873,2876,2884,2887,2888,2891,2893,2902,2903,2908,2909,2911,2915,2918,2927,2929,2929,2946,2947,2949,2954,2958,2960,2962,2965,2969,2970,2972,2972,2974,2975,2979,2980,2984,2986,2990,3001,3006,3010,3014,3016,3018,3021,3024,3024,3031,3031,3046,3055,3073,3075,3077,3084,3086,3088,3090,3112,3114,3123,3125,3129,3133,3140,3142,3144,3146,3149,3157,3158,3160,3161,3168,3171,3174,3183,3202,3203,3205,3212,3214,3216,3218,3240,3242,3251,3253,3257,3260,3268,3270,3272,3274,3277,3285,3286,3294,3294,3296,3299,3302,3311,3313,3314,3330,3331,3333,3340,3342,3344,3346,3386,3389,3396,3398,3400,3402,3406,3415,3415,3424,3427,3430,3439,3450,3455,3458,3459,3461,3478,3482,3505,3507,3515,3517,3517,3520,3526,3530,3530,3535,3540,3542,3542,3544,3551,3570,3571,3585,3642,3648,3662,3664,3673,3713,3714,3716,3716,3719,3720,3722,3722,3725,3725,3732,3735,3737,3743,3745,3747,3749,3749,3751,3751,3754,3755,3757,3769,3771,3773,3776,3780,3782,3782,3784,3789,3792,3801,3804,3807,3840,3840,3864,3865,3872,3881,3893,3893,3895,3895,3897,3897,3902,3911,3913,3948,3953,3972,3974,3991,3993,4028,4038,4038,4096,4169,4176,4253,4256,4293,4295,4295,4301,4301,4304,4346,4348,4680,4682,4685,4688,4694,4696,4696,4698,4701,4704,4744,4746,4749,4752,4784,4786,4789,4792,4798,4800,4800,4802,4805,4808,4822,4824,4880,4882,4885,4888,4954,4957,4959,4992,5007,5024,5108,5121,5740,5743,5759,5761,5786,5792,5866,5870,5872,5888,5900,5902,5908,5920,5940,5952,5971,5984,5996,5998,6e3,6002,6003,6016,6099,6103,6103,6108,6109,6112,6121,6155,6157,6160,6169,6176,6263,6272,6314,6320,6389,6400,6428,6432,6443,6448,6459,6470,6509,6512,6516,6528,6571,6576,6601,6608,6617,6656,6683,6688,6750,6752,6780,6783,6793,6800,6809,6823,6823,6912,6987,6992,7001,7019,7027,7040,7155,7168,7223,7232,7241,7245,7293,7376,7378,7380,7414,7424,7654,7676,7957,7960,7965,7968,8005,8008,8013,8016,8023,8025,8025,8027,8027,8029,8029,8031,8061,8064,8116,8118,8124,8126,8126,8130,8132,8134,8140,8144,8147,8150,8155,8160,8172,8178,8180,8182,8188,8204,8205,8255,8256,8276,8276,8305,8305,8319,8319,8336,8348,8400,8412,8417,8417,8421,8432,8450,8450,8455,8455,8458,8467,8469,8469,8473,8477,8484,8484,8486,8486,8488,8488,8490,8493,8495,8505,8508,8511,8517,8521,8526,8526,8544,8584,11264,11310,11312,11358,11360,11492,11499,11507,11520,11557,11559,11559,11565,11565,11568,11623,11631,11631,11647,11670,11680,11686,11688,11694,11696,11702,11704,11710,11712,11718,11720,11726,11728,11734,11736,11742,11744,11775,11823,11823,12293,12295,12321,12335,12337,12341,12344,12348,12353,12438,12441,12442,12445,12447,12449,12538,12540,12543,12549,12589,12593,12686,12704,12730,12784,12799,13312,19893,19968,40908,40960,42124,42192,42237,42240,42508,42512,42539,42560,42607,42612,42621,42623,42647,42655,42737,42775,42783,42786,42888,42891,42894,42896,42899,42912,42922,43e3,43047,43072,43123,43136,43204,43216,43225,43232,43255,43259,43259,43264,43309,43312,43347,43360,43388,43392,43456,43471,43481,43520,43574,43584,43597,43600,43609,43616,43638,43642,43643,43648,43714,43739,43741,43744,43759,43762,43766,43777,43782,43785,43790,43793,43798,43808,43814,43816,43822,43968,44010,44012,44013,44016,44025,44032,55203,55216,55238,55243,55291,63744,64109,64112,64217,64256,64262,64275,64279,64285,64296,64298,64310,64312,64316,64318,64318,64320,64321,64323,64324,64326,64433,64467,64829,64848,64911,64914,64967,65008,65019,65024,65039,65056,65062,65075,65076,65101,65103,65136,65140,65142,65276,65296,65305,65313,65338,65343,65343,65345,65370,65382,65470,65474,65479,65482,65487,65490,65495,65498,65500],r=[170,170,181,181,186,186,192,214,216,246,248,543,546,563,592,685,688,696,699,705,720,721,736,740,750,750,890,890,902,902,904,906,908,908,910,929,931,974,976,983,986,1011,1024,1153,1164,1220,1223,1224,1227,1228,1232,1269,1272,1273,1329,1366,1369,1369,1377,1415,1488,1514,1520,1522,1569,1594,1600,1610,1649,1747,1749,1749,1765,1766,1786,1788,1808,1808,1810,1836,1920,1957,2309,2361,2365,2365,2384,2384,2392,2401,2437,2444,2447,2448,2451,2472,2474,2480,2482,2482,2486,2489,2524,2525,2527,2529,2544,2545,2565,2570,2575,2576,2579,2600,2602,2608,2610,2611,2613,2614,2616,2617,2649,2652,2654,2654,2674,2676,2693,2699,2701,2701,2703,2705,2707,2728,2730,2736,2738,2739,2741,2745,2749,2749,2768,2768,2784,2784,2821,2828,2831,2832,2835,2856,2858,2864,2866,2867,2870,2873,2877,2877,2908,2909,2911,2913,2949,2954,2958,2960,2962,2965,2969,2970,2972,2972,2974,2975,2979,2980,2984,2986,2990,2997,2999,3001,3077,3084,3086,3088,3090,3112,3114,3123,3125,3129,3168,3169,3205,3212,3214,3216,3218,3240,3242,3251,3253,3257,3294,3294,3296,3297,3333,3340,3342,3344,3346,3368,3370,3385,3424,3425,3461,3478,3482,3505,3507,3515,3517,3517,3520,3526,3585,3632,3634,3635,3648,3654,3713,3714,3716,3716,3719,3720,3722,3722,3725,3725,3732,3735,3737,3743,3745,3747,3749,3749,3751,3751,3754,3755,3757,3760,3762,3763,3773,3773,3776,3780,3782,3782,3804,3805,3840,3840,3904,3911,3913,3946,3976,3979,4096,4129,4131,4135,4137,4138,4176,4181,4256,4293,4304,4342,4352,4441,4447,4514,4520,4601,4608,4614,4616,4678,4680,4680,4682,4685,4688,4694,4696,4696,4698,4701,4704,4742,4744,4744,4746,4749,4752,4782,4784,4784,4786,4789,4792,4798,4800,4800,4802,4805,4808,4814,4816,4822,4824,4846,4848,4878,4880,4880,4882,4885,4888,4894,4896,4934,4936,4954,5024,5108,5121,5740,5743,5750,5761,5786,5792,5866,6016,6067,6176,6263,6272,6312,7680,7835,7840,7929,7936,7957,7960,7965,7968,8005,8008,8013,8016,8023,8025,8025,8027,8027,8029,8029,8031,8061,8064,8116,8118,8124,8126,8126,8130,8132,8134,8140,8144,8147,8150,8155,8160,8172,8178,8180,8182,8188,8319,8319,8450,8450,8455,8455,8458,8467,8469,8469,8473,8477,8484,8484,8486,8486,8488,8488,8490,8493,8495,8497,8499,8505,8544,8579,12293,12295,12321,12329,12337,12341,12344,12346,12353,12436,12445,12446,12449,12538,12540,12542,12549,12588,12593,12686,12704,12727,13312,19893,19968,40869,40960,42124,44032,55203,63744,64045,64256,64262,64275,64279,64285,64285,64287,64296,64298,64310,64312,64316,64318,64318,64320,64321,64323,64324,64326,64433,64467,64829,64848,64911,64914,64967,65008,65019,65136,65138,65140,65140,65142,65276,65313,65338,65345,65370,65382,65470,65474,65479,65482,65487,65490,65495,65498,65500],o=[170,170,181,181,186,186,192,214,216,246,248,543,546,563,592,685,688,696,699,705,720,721,736,740,750,750,768,846,864,866,890,890,902,902,904,906,908,908,910,929,931,974,976,983,986,1011,1024,1153,1155,1158,1164,1220,1223,1224,1227,1228,1232,1269,1272,1273,1329,1366,1369,1369,1377,1415,1425,1441,1443,1465,1467,1469,1471,1471,1473,1474,1476,1476,1488,1514,1520,1522,1569,1594,1600,1621,1632,1641,1648,1747,1749,1756,1759,1768,1770,1773,1776,1788,1808,1836,1840,1866,1920,1968,2305,2307,2309,2361,2364,2381,2384,2388,2392,2403,2406,2415,2433,2435,2437,2444,2447,2448,2451,2472,2474,2480,2482,2482,2486,2489,2492,2492,2494,2500,2503,2504,2507,2509,2519,2519,2524,2525,2527,2531,2534,2545,2562,2562,2565,2570,2575,2576,2579,2600,2602,2608,2610,2611,2613,2614,2616,2617,2620,2620,2622,2626,2631,2632,2635,2637,2649,2652,2654,2654,2662,2676,2689,2691,2693,2699,2701,2701,2703,2705,2707,2728,2730,2736,2738,2739,2741,2745,2748,2757,2759,2761,2763,2765,2768,2768,2784,2784,2790,2799,2817,2819,2821,2828,2831,2832,2835,2856,2858,2864,2866,2867,2870,2873,2876,2883,2887,2888,2891,2893,2902,2903,2908,2909,2911,2913,2918,2927,2946,2947,2949,2954,2958,2960,2962,2965,2969,2970,2972,2972,2974,2975,2979,2980,2984,2986,2990,2997,2999,3001,3006,3010,3014,3016,3018,3021,3031,3031,3047,3055,3073,3075,3077,3084,3086,3088,3090,3112,3114,3123,3125,3129,3134,3140,3142,3144,3146,3149,3157,3158,3168,3169,3174,3183,3202,3203,3205,3212,3214,3216,3218,3240,3242,3251,3253,3257,3262,3268,3270,3272,3274,3277,3285,3286,3294,3294,3296,3297,3302,3311,3330,3331,3333,3340,3342,3344,3346,3368,3370,3385,3390,3395,3398,3400,3402,3405,3415,3415,3424,3425,3430,3439,3458,3459,3461,3478,3482,3505,3507,3515,3517,3517,3520,3526,3530,3530,3535,3540,3542,3542,3544,3551,3570,3571,3585,3642,3648,3662,3664,3673,3713,3714,3716,3716,3719,3720,3722,3722,3725,3725,3732,3735,3737,3743,3745,3747,3749,3749,3751,3751,3754,3755,3757,3769,3771,3773,3776,3780,3782,3782,3784,3789,3792,3801,3804,3805,3840,3840,3864,3865,3872,3881,3893,3893,3895,3895,3897,3897,3902,3911,3913,3946,3953,3972,3974,3979,3984,3991,3993,4028,4038,4038,4096,4129,4131,4135,4137,4138,4140,4146,4150,4153,4160,4169,4176,4185,4256,4293,4304,4342,4352,4441,4447,4514,4520,4601,4608,4614,4616,4678,4680,4680,4682,4685,4688,4694,4696,4696,4698,4701,4704,4742,4744,4744,4746,4749,4752,4782,4784,4784,4786,4789,4792,4798,4800,4800,4802,4805,4808,4814,4816,4822,4824,4846,4848,4878,4880,4880,4882,4885,4888,4894,4896,4934,4936,4954,4969,4977,5024,5108,5121,5740,5743,5750,5761,5786,5792,5866,6016,6099,6112,6121,6160,6169,6176,6263,6272,6313,7680,7835,7840,7929,7936,7957,7960,7965,7968,8005,8008,8013,8016,8023,8025,8025,8027,8027,8029,8029,8031,8061,8064,8116,8118,8124,8126,8126,8130,8132,8134,8140,8144,8147,8150,8155,8160,8172,8178,8180,8182,8188,8255,8256,8319,8319,8400,8412,8417,8417,8450,8450,8455,8455,8458,8467,8469,8469,8473,8477,8484,8484,8486,8486,8488,8488,8490,8493,8495,8497,8499,8505,8544,8579,12293,12295,12321,12335,12337,12341,12344,12346,12353,12436,12441,12442,12445,12446,12449,12542,12549,12588,12593,12686,12704,12727,13312,19893,19968,40869,40960,42124,44032,55203,63744,64045,64256,64262,64275,64279,64285,64296,64298,64310,64312,64316,64318,64318,64320,64321,64323,64324,64326,64433,64467,64829,64848,64911,64914,64967,65008,65019,65056,65059,65075,65076,65101,65103,65136,65138,65140,65140,65142,65276,65296,65305,65313,65338,65343,65343,65345,65370,65381,65470,65474,65479,65482,65487,65490,65495,65498,65500];function a(e,t){return t>=n.ES5?l(e,i):l(e,r)}function l(e,t){if(e<t[0])return!1;let n,i=0,s=t.length;for(;i+1<s;){if(n=i+(s-i)/2,n-=n%2,t[n]<=e&&e<=t[n+1])return!0;e<t[n]?s=n:i=n+2}return!1}let c;t.isUnicodeIdentifierStart=a,function(e){e[e.Warning=0]="Warning",e[e.Error=1]="Error",e[e.Message=2]="Message"}(c=t.DiagnosticCategory||(t.DiagnosticCategory={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){function n(){return!!navigator&&!!navigator.bluetooth&&"TextDecoder"in window&&e.appTarget.appTheme.bluetoothUartConsole&&e.appTarget.appTheme.bluetoothUartFilters&&e.appTarget.appTheme.bluetoothUartFilters.length>0}function i(){return!!navigator&&!!navigator.bluetooth&&!!e.appTarget.appTheme.bluetoothPartialFlashing}t.isAvailable=function(){return n()||i()},t.hasConsole=n,t.hasPartialFlash=i,t.isValidUUID=function(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(e)};class s{constructor(e,t){this.connectionTimeout=2e4,this.connectPromise=void 0,this.id=e,this.aliveToken=t}debug(t){e.debug(`${this.id}: ${t}`)}alivePromise(e){return new Promise(((t,n)=>{this.aliveToken.isCancelled()&&n(new Error),e.then((e=>t(e)),(e=>n(e)))}))}cancelConnect(){this.connectPromise=void 0}createConnectPromise(){return Promise.resolve()}connectAsync(){return this.connectPromise||(this.connectPromise=this.alivePromise(this.createConnectPromise())),e.Util.promiseTimeout(this.connectionTimeout,this.connectPromise,"connection timeout").then((()=>this.aliveToken.throwIfCancelled())).catch((e=>{throw this.connectPromise=void 0,e}))}disconnect(){this.cancelConnect()}kill(){this.disconnect(),this.aliveToken.cancel()}}t.BLERemote=s;class r extends s{constructor(e,t,n){super(e,t.aliveToken),this.device=t,this.autoReconnect=n,this.autoReconnectDelay=1e3,this.disconnectOnAutoReconnect=!1,this.reconnectPromise=void 0,this.failedConnectionServicesVersion=-1,this.handleDisconnected=this.handleDisconnected.bind(this),this.device.device.addEventListener("gattserverdisconnected",this.handleDisconnected)}handleDisconnected(t){this.aliveToken.isCancelled()||(this.disconnect(),this.autoReconnect&&!this.reconnectPromise&&(this.reconnectPromise=e.U.delay(this.autoReconnectDelay).then((()=>this.exponentialBackoffConnectAsync(8,500))).finally((()=>this.reconnectPromise=void 0))))}exponentialBackoffConnectAsync(t,n){return this.debug("retry connect"),this.aliveToken.throwIfCancelled(),this.connectAsync().then((()=>{this.aliveToken.throwIfCancelled(),this.debug("reconnect success"),this.reconnectPromise=void 0})).catch((i=>(this.debug(`reconnect error ${i.message}`),this.aliveToken.throwIfCancelled(),this.device.isPaired?this.autoReconnect?0==t?(this.debug("give up, max tries"),void(this.reconnectPromise=void 0)):this.failedConnectionServicesVersion==this.device.servicesVersion?(this.debug("services haven't changed, giving up"),void(this.reconnectPromise=void 0)):(this.debug(`retry connect ${n}ms... (${t} tries left)`),this.device.connected&&(this.failedConnectionServicesVersion=this.device.servicesVersion),this.disconnectOnAutoReconnect&&this.device.disconnect(),e.U.delay(n).then((()=>this.exponentialBackoffConnectAsync(--t,1.8*n)))):(this.debug("autoreconnect disabled"),void(this.reconnectPromise=void 0)):(this.debug("give up, device unpaired"),void(this.reconnectPromise=void 0)))))}}t.BLEService=r;class o extends r{constructor(e,t,n,i){super(e,t,!0),this.device=t,this.serviceUUID=n,this.txCharacteristicUUID=i,this.handleValueChanged=this.handleValueChanged.bind(this)}createConnectPromise(){return this.debug("connecting"),this.device.connectAsync().then((()=>this.alivePromise(this.device.gatt.getPrimaryService(this.serviceUUID)))).then((e=>(this.debug("service connected"),this.service=e,this.alivePromise(this.service.getCharacteristic(this.txCharacteristicUUID))))).then((e=>(this.debug("tx characteristic connected"),this.txCharacteristic=e,this.txCharacteristic.addEventListener("characteristicvaluechanged",this.handleValueChanged),this.txCharacteristic.startNotifications()))).then((()=>{e.tickEvent("webble.connected",{id:this.id})}))}handlePacket(e){}handleValueChanged(e){const t=e.target.value;this.handlePacket(t)}disconnect(){if(super.disconnect(),this.txCharacteristic&&this.device&&this.device.connected)try{this.txCharacteristic.stopNotifications(),this.txCharacteristic.removeEventListener("characteristicvaluechanged",this.handleValueChanged)}catch(t){e.log(`${this.id}: error ${t.message}`)}this.service=void 0,this.txCharacteristic=void 0}}t.BLETXService=o;class a extends o{constructor(e){super("hf2",e,a.SERVICE_UUID,a.CHARACTERISTIC_TX_UUID),this.device=e}handlePacket(e){const t=e.getUint8(0);switch(192&t){case a.BLEHF2_FLAG_SERIAL_OUT:case a.BLEHF2_FLAG_SERIAL_ERR:const n=Math.min(e.byteLength-1,-193&t);let i="";for(let t=0;t<n;++t)i+=String.fromCharCode(e.getUint8(t+1));i&&window.postMessage({type:"serial",id:this.device.name||"hf2",data:i},"*")}}}a.SERVICE_UUID="b112f5e6-2679-30da-a26e-0273b6043849",a.CHARACTERISTIC_TX_UUID="b112f5e6-2679-30da-a26e-0273b604384a",a.BLEHF2_FLAG_SERIAL_OUT=128,a.BLEHF2_FLAG_SERIAL_ERR=192,t.HF2Service=a;class l extends o{constructor(e){super("uart",e,l.SERVICE_UUID,l.CHARACTERISTIC_TX_UUID),this.device=e}handlePacket(e){const t=(new window.TextDecoder).decode(e);t&&window.postMessage({type:"serial",id:this.device.name||"uart",data:t},"*")}}let c;l.SERVICE_UUID="6e400001-b5a3-f393-e0a9-e50e24dcca9e",l.CHARACTERISTIC_TX_UUID="6e400002-b5a3-f393-e0a9-e50e24dcca9e",t.UARTService=l,function(e){e[e.Idle=1]="Idle",e[e.StatusRequested=2]="StatusRequested",e[e.PairingModeRequested=4]="PairingModeRequested",e[e.RegionDALRequested=8]="RegionDALRequested",e[e.RegionMakeCodeRequested=16]="RegionMakeCodeRequested",e[e.Flash=32]="Flash",e[e.EndOfTransmision=64]="EndOfTransmision",e[e.USBFlashRequired=128]="USBFlashRequired"}(c||(c={}));class u extends r{constructor(e){super("partial flashing",e,!1),this.device=e,this.state=c.Idle,this.disconnectOnAutoReconnect=!0,this.handleCharacteristic=this.handleCharacteristic.bind(this)}clearFlashData(){this.version=0,this.mode=0,this.regions=[],this.chunkDelay=u.CHUNK_MIN_DELAY,this.hex=void 0,this.bin=void 0,this.magicOffset=void 0,this.dalHash=void 0,this.makeCodeHash=void 0,this.flashReject=void 0,this.flashResolve=void 0,this.flashOffset=void 0}createConnectPromise(){return this.debug("connecting to partial flash service"),this.device.connectAsync().then((()=>this.alivePromise(this.device.gatt.getPrimaryService(u.SERVICE_UUID)))).then((e=>(this.debug("connecting to characteristic"),this.alivePromise(e.getCharacteristic(u.CHARACTERISTIC_UUID))))).then((e=>(this.debug("starting notifications"),this.pfCharacteristic=e,this.pfCharacteristic.startNotifications(),this.pfCharacteristic.addEventListener("characteristicvaluechanged",this.handleCharacteristic),this.state==c.PairingModeRequested?(this.debug("checking pairing mode"),this.autoReconnect=!1,this.pfCharacteristic.writeValue(new Uint8Array([u.STATUS]))):Promise.resolve())))}disconnect(){if(super.disconnect(),this.flashPacketToken&&this.flashPacketToken.cancel(),this.pfCharacteristic&&this.device.connected)try{this.pfCharacteristic.stopNotifications(),this.pfCharacteristic.removeEventListener("characteristicvaluechanged",this.handleCharacteristic)}catch(t){e.log(`ble: partial flash disconnect error ${t.message}`)}this.pfCharacteristic=void 0}findMarker(e,t){if(!this.bin)return-1;for(;e+t.length<this.bin.length;e+=16){let n=!0;for(let i=0;i<t.length;++i)if(t[i]!=this.bin[e+i]){n=!1;break}if(n)return e}return-1}flashAsync(e){return this.hex?(this.debug("flashing already in progress"),Promise.resolve()):(this.device.pauseLog(),this.createFlashPromise(e).finally((()=>this.device.resumeLogOnDisconnection())))}createFlashPromise(t){if(this.hex)return this.debug("flashing already in progress"),Promise.resolve();this.clearFlashData(),this.hex=t;const n=ts.pxtc.UF2.newBlockFile();ts.pxtc.UF2.writeHex(n,this.hex.split(/\r?\n/));const i=e.appTarget.compile.flashUsableEnd;this.bin=ts.pxtc.UF2.toBin(e.U.stringToUint8Array(ts.pxtc.UF2.serializeFile(n)),i).buf,this.debug(`bin bytes ${this.bin.length}`),this.magicOffset=this.findMarker(0,u.MAGIC_MARKER),this.debug(`magic block ${this.magicOffset.toString(16)}`),this.magicOffset<0&&(this.debug("magic block not found, not a valid HEX file"),e.U.userError(lf("Invalid file"))),this.debug("bytes to flash "+(this.bin.length-this.magicOffset));const s=this.magicOffset+u.MAGIC_MARKER.length;return this.dalHash=e.Util.toHex(this.bin.slice(s,s+8)),this.makeCodeHash=e.Util.toHex(this.bin.slice(s+8,s+16)),this.debug(`DAL hash ${this.dalHash}`),this.debug(`MakeCode hash ${this.makeCodeHash}`),this.connectAsync().then((()=>new Promise(((e,t)=>(this.flashResolve=e,this.flashReject=t,this.debug("check service version"),this.state=c.StatusRequested,this.pfCharacteristic.writeValue(new Uint8Array([u.STATUS]))))))).then((()=>{}),(t=>{e.log(`pf: error ${t.message}`),this.clearFlashData()}))}checkStateTransition(e,t){return!!(this.state&t)||(this.debug(`flash cmd ${e} in state ${this.state.toString(16)} `),this.flashReject(new Error),this.clearFlashData(),!1)}handleCharacteristic(t){this.aliveToken.isCancelled()&&(this.flashReject(new Error),this.clearFlashData());const n=event.target.value,i=new Uint8Array(n.buffer),s=i[0];if(this.state!=c.Idle)switch(s){case u.STATUS:if(!this.checkStateTransition(s,c.StatusRequested|c.PairingModeRequested))return;this.version=i[1],this.mode=i[2],this.debug(`flash service version ${this.version} mode ${this.mode}`),this.debug("reading DAL region"),this.state=c.RegionDALRequested,this.pfCharacteristic.writeValue(new Uint8Array([u.REGION_INFO,u.REGION_DAL])).then((()=>{}));break;case u.REGION_INFO:if(!this.checkStateTransition(s,c.RegionDALRequested|c.RegionMakeCodeRequested))return;const t=this.regions[i[1]]={start:i[2]<<24|i[3]<<16|i[4]<<8|i[5],end:i[6]<<24|i[7]<<16|i[8]<<8|i[9],hash:e.Util.toHex(i.slice(10))};if(this.debug(`read region ${i[1]} start ${t.start.toString(16)} end ${t.end.toString(16)} hash ${t.hash}`),i[1]==u.REGION_DAL){if(t.hash!=this.dalHash)return e.tickEvent("webble.flash.DALrequired"),this.debug("DAL hash does not match, partial flashing not possible"),this.state=c.USBFlashRequired,this.flashReject(new Error("USB flashing required")),void this.clearFlashData();this.debug("DAL hash match, reading makecode region"),this.state=c.RegionMakeCodeRequested,this.pfCharacteristic.writeValue(new Uint8Array([u.REGION_INFO,u.REGION_MAKECODE])).then((()=>{}))}else if(i[1]==u.REGION_MAKECODE)if(t.start!=this.magicOffset&&(this.debug("magic offset and MakeCode region.start not matching"),e.U.userError(lf("Invalid file"))),t.hash==this.makeCodeHash)e.tickEvent("webble.flash.noop"),this.debug("MakeCode hash matches, same code!"),this.debug("restart application mode"),this.pfCharacteristic.writeValue(new Uint8Array([u.RESET,u.MODE_APPLICATION])).then((()=>{this.state=c.Idle,this.flashResolve(),this.clearFlashData()}));else{if(this.mode!=u.MODE_PAIRING)return this.debug("application mode, reset into pairing mode"),this.state=c.PairingModeRequested,this.autoReconnect=!0,void this.pfCharacteristic.writeValue(new Uint8Array([u.RESET,u.MODE_PAIRING])).then((()=>{}));this.flashOffset=t.start,this.flashPacketNumber=0,this.debug(`starting to flash from address ${this.flashOffset.toString(16)}`),this.flashNextPacket()}break;case u.FLASH_DATA:if(!this.checkStateTransition(s,c.Flash))return;switch(i[1]){case u.PACKET_OUT_OF_ORDER:this.debug("packet out of order"),this.flashPacketToken.cancel(),this.flashPacketNumber+=4,this.chunkDelay=Math.min(this.chunkDelay+10,u.CHUNK_MAX_DELAY),this.flashNextPacket();break;case u.PACKET_WRITTEN:this.chunkDelay=Math.max(this.chunkDelay-1,u.CHUNK_MIN_DELAY),this.flashOffset+=64,this.flashPacketNumber+=4,this.flashOffset>=this.bin.length?(this.debug("end transmission"),this.state=c.EndOfTransmision,this.pfCharacteristic.writeValue(new Uint8Array([u.END_OF_TRANSMISSION])).finally((()=>{this.flashResolve&&this.flashResolve(),this.clearFlashData()}))):this.flashNextPacket()}break;default:this.debug(`unknown message ${e.Util.toHex(i)}`),this.disconnect()}}flashNextPacket(){this.state=c.Flash,this.flashPacketToken=new e.Util.CancellationToken,this.flashPacketToken.startOperation();const t=this.bin.slice(this.flashOffset,this.flashOffset+64);this.debug(`flashing ${this.flashOffset.toString(16)} / ${this.bin.length.toString(16)} ${(this.flashOffset-this.magicOffset)/(this.bin.length-this.magicOffset)*100>>0}%`);let n=new Uint8Array(20);e.U.delay(this.chunkDelay).then((()=>{this.flashPacketToken.throwIfCancelled(),n[0]=u.FLASH_DATA,n[1]=this.flashOffset>>8&255,n[2]=this.flashOffset>>0&255,n[3]=this.flashPacketNumber;for(let e=0;e<16;e++)n[4+e]=t[e];return this.pfCharacteristic.writeValue(n)})).then((()=>e.U.delay(this.chunkDelay))).then((()=>{this.flashPacketToken.throwIfCancelled(),n[0]=u.FLASH_DATA,n[1]=this.flashOffset>>24&255,n[2]=this.flashOffset>>16&255,n[3]=this.flashPacketNumber+1;for(let e=0;e<16;e++)n[4+e]=t[16+e]||0;return this.pfCharacteristic.writeValue(n)})).then((()=>e.U.delay(this.chunkDelay))).then((()=>{this.flashPacketToken.throwIfCancelled(),n[0]=u.FLASH_DATA,n[1]=0,n[2]=0,n[3]=this.flashPacketNumber+2;for(let e=0;e<16;e++)n[4+e]=t[32+e]||0;return this.pfCharacteristic.writeValue(n)})).then((()=>e.U.delay(this.chunkDelay))).then((()=>{this.flashPacketToken.throwIfCancelled(),n[0]=u.FLASH_DATA,n[1]=0,n[2]=0,n[3]=this.flashPacketNumber+3;for(let e=0;e<16;e++)n[4+e]=t[48+e]||0;return this.pfCharacteristic.writeValue(n)})).then((()=>{const t=this.flashOffset,i=()=>e.U.delay(500).then((()=>{if(t!=this.flashOffset||this.flashPacketToken.isCancelled()||this.aliveToken.isCancelled()||this.state!=c.Flash)return Promise.resolve();this.debug("packet transfer deadlock, force restart"),n[0]=u.FLASH_DATA,n[1]=0,n[2]=0,n[3]=-1;for(let e=0;e<16;e++)n[4+e]=0;return this.pfCharacteristic.writeValue(n).then((()=>i()))}));i().catch((e=>{this.flashReject&&(this.flashReject(new Error("failed packet transfer")),this.clearFlashData())}))})).catch((()=>{this.flashPacketToken.resolveCancel()}))}}u.SERVICE_UUID="e97dd91d-251d-470a-a062-fa1922dfa9a8",u.CHARACTERISTIC_UUID="e97d3b10-251d-470a-a062-fa1922dfa9a8",u.REGION_INFO=0,u.FLASH_DATA=1,u.PACKET_OUT_OF_ORDER=170,u.PACKET_WRITTEN=255,u.END_OF_TRANSMISSION=2,u.STATUS=238,u.RESET=255,u.MODE_PAIRING=0,u.MODE_APPLICATION=1,u.REGION_SOFTDEVICE=0,u.REGION_DAL=1,u.REGION_MAKECODE=2,u.MAGIC_MARKER=e.Util.fromHex("708E3B92C615A841C49866C975EE5197"),u.CHUNK_MIN_DELAY=0,u.CHUNK_MAX_DELAY=75,t.PartialFlashingService=u;class d extends s{constructor(t){super("ble",new e.Util.CancellationToken),this.device=void 0,this.services=[],this.pendingResumeLogOnDisconnection=!1,this.servicesVersion=0,this.device=t,this.handleDisconnected=this.handleDisconnected.bind(this),this.handleServiceAdded=this.handleServiceAdded.bind(this),this.handleServiceChanged=this.handleServiceChanged.bind(this),this.handleServiceRemoved=this.handleServiceRemoved.bind(this),this.device.addEventListener("gattserverdisconnected",this.handleDisconnected),this.device.addEventListener("serviceadded",this.handleServiceAdded),this.device.addEventListener("servicechanged",this.handleServiceChanged),this.device.addEventListener("serviceremoved",this.handleServiceRemoved),n()&&(this.services.push(this.uartService=new l(this)),this.services.push(this.hf2Service=new a(this))),i()&&this.services.push(this.partialFlashingService=new u(this)),this.aliveToken.startOperation()}startServices(){this.services.filter((e=>e.autoReconnect)).forEach((e=>e.connectAsync().catch((()=>{}))))}pauseLog(){this.uartService&&(this.uartService.autoReconnect=!1,this.uartService.disconnect()),this.hf2Service&&(this.hf2Service.autoReconnect=!1,this.hf2Service.disconnect())}resumeLogOnDisconnection(){this.pendingResumeLogOnDisconnection=!0}resumeLog(){this.uartService&&(this.uartService.autoReconnect=!0,this.uartService.connectAsync().catch((()=>{}))),this.hf2Service&&(this.hf2Service.autoReconnect=!0,this.hf2Service.connectAsync().catch((()=>{})))}get isPaired(){return this===t.bleDevice}get name(){return this.device.name||"?"}get connected(){return this.device&&this.device.gatt&&this.device.gatt.connected}get gatt(){return this.device.gatt}createConnectPromise(){return this.debug("connecting gatt server"),this.alivePromise(this.device.gatt.connect().then((()=>this.debug("gatt server connected"))))}handleServiceAdded(e){this.debug("service added"),this.servicesVersion++}handleServiceRemoved(e){this.debug("service removed"),this.servicesVersion++}handleServiceChanged(e){this.debug("service changed"),this.servicesVersion++}handleDisconnected(t){this.debug("disconnected"),this.disconnect(),this.pendingResumeLogOnDisconnection&&(this.pendingResumeLogOnDisconnection=!1,e.U.delay(500).then((()=>this.resumeLog())))}disconnect(){if(super.disconnect(),this.services.forEach((e=>e.disconnect())),this.connected){this.debug("disconnect");try{this.device.gatt&&this.device.gatt.connected&&this.device.gatt.disconnect()}catch(e){this.debug(`gatt disconnect error ${e.message}`)}}}}function h(){if(t.bleDevice)return Promise.resolve();e.log("ble: requesting device");const s=[];return n()&&(s.push(l.SERVICE_UUID),s.push(a.SERVICE_UUID)),i()&&s.push(u.SERVICE_UUID),navigator.bluetooth.requestDevice({filters:e.appTarget.appTheme.bluetoothUartFilters,optionalServices:s}).then((n=>(e.log(`ble: received device ${n.name}`),t.bleDevice=new d(n),t.bleDevice.startServices(),t.bleDevice.connectAsync())))}t.BLEDevice=d,t.bleDevice=void 0,t.isPaired=function(){return!!t.bleDevice},t.pairAsync=function(){return t.bleDevice&&(t.bleDevice.kill(),t.bleDevice=void 0),h().catch((n=>{t.bleDevice&&t.bleDevice.aliveToken&&t.bleDevice.aliveToken.resolveCancel(),e.log(`ble: error ${n.message}`)}))},t.flashAsync=function(n,i){e.tickEvent("webble.flash");const s=n.outfiles[ts.pxtc.BINARY_HEX];return h().then((()=>t.bleDevice.partialFlashingService.flashAsync(s))).then((()=>e.tickEvent("webble.flash.success"))).catch((t=>{throw e.tickEvent("webble.fail.fail",{message:t.message}),t}))}}(e.webBluetooth||(e.webBluetooth={}))}(pxt||(pxt={})),function(e){!function(t){class n extends Error{constructor(e){super(e),this.message=e}}t.USBError=n;t.filters=[{classCode:255,subclassCode:42}];let i,s,r=!0;t.setFilters=function(e){r=!1,t.filters=e};class o{constructor(){this.ready=!1,this.connecting=!1,this.readLoopStarted=!1,this.onDeviceConnectionChanged=e=>{},this.onConnectionChanged=()=>{},this.onData=e=>{},this.onError=e=>{},this.onEvent=e=>{},this.enabled=!1,this.handleUSBConnected=this.handleUSBConnected.bind(this),this.handleUSBDisconnected=this.handleUSBDisconnected.bind(this)}enable(){var e,t;this.enabled||(this.enabled=!0,this.log("registering webusb events"),null===(e=navigator.usb)||void 0===e||e.addEventListener("disconnect",this.handleUSBDisconnected,!1),null===(t=navigator.usb)||void 0===t||t.addEventListener("connect",this.handleUSBConnected,!1))}disable(){var e,t;this.enabled&&(this.enabled=!1,this.log("unregistering webusb events"),null===(e=navigator.usb)||void 0===e||e.removeEventListener("disconnect",this.handleUSBDisconnected),null===(t=navigator.usb)||void 0===t||t.removeEventListener("connect",this.handleUSBConnected))}async disposeAsync(){this.disable()}handleUSBDisconnected(e){var t;this.log("device disconnected"),e.device==this.dev&&(this.log("clear device"),this.clearDev(),null===(t=this.onDeviceConnectionChanged)||void 0===t||t.call(this,!1))}handleUSBConnected(e){var t;const n=e.device;this.log(`device connected ${n.serialNumber}`),this.dev||this.connecting||(this.log("attach device"),null===(t=this.onDeviceConnectionChanged)||void 0===t||t.call(this,!0))}clearDev(){var e;this.dev&&(this.dev=null,this.epIn=null,this.epOut=null,null===(e=this.onConnectionChanged)||void 0===e||e.call(this))}error(t){throw new n(e.U.lf("USB error on device {0} ({1})",this.dev.productName,t))}log(t){e.debug("webusb: "+t)}async disconnectAsync(){if(this.ready=!1,this.dev){this.log("close device");try{await this.dev.close()}catch(e){}this.clearDev(),await e.U.delay(500)}}async forgetAsync(){var e;if(!(null===(e=this.dev)||void 0===e?void 0:e.forget))return!1;try{const e=this.dev;return await this.disconnectAsync(),await e.forget(),!0}catch(e){return!1}}async reconnectAsync(){this.log("reconnect"),this.setConnecting(!0);try{await this.disconnectAsync();const e=await a();await this.connectAsync(e)}finally{this.setConnecting(!1)}}setConnecting(e){var t;e!=this.connecting&&(this.connecting=e,null===(t=this.onConnectionChanged)||void 0===t||t.call(this))}isConnecting(){return this.connecting}isConnected(){return!!this.dev&&this.ready}async connectAsync(t){if(this.log(`trying to connect (${t.length} devices)`),0==t.length){const e=new Error("Device not found.");throw e.type="devicenotfound",e}this.setConnecting(!0);try{if(this.lastKnownDeviceSerialNumber){const n=t.find((e=>e.serialNumber===this.lastKnownDeviceSerialNumber));n?(this.log("last known device spotted"),t.splice(t.indexOf(n),1),t.unshift(n)):(this.log("delay for last known device"),await e.U.delay(2e3))}for(let e=0;e<t.length;++e){const n=t[e];this.dev=n,this.log(`connect device: ${n.manufacturerName} ${n.productName}`),this.log(`serial number: ${n.serialNumber} ${this.lastKnownDeviceSerialNumber===n.serialNumber?"(last known device)":""} `);try{return void await this.initAsync()}catch(e){this.dev=void 0,this.log(`connection failed, ${e.message}`)}}const n=new Error(e.U.lf("Device in use or not found."));throw n.type="devicelocked",n}finally{this.setConnecting(!1)}}async sendPacketAsync(t){if(!this.dev)throw new Error("Disconnected");if(e.Util.assert(t.length<=64),this.epOut){"ok"!=(await this.dev.transferOut(this.epOut.endpointNumber,t)).status&&this.error("USB OUT transfer failed")}else{"ok"!=(await this.dev.controlTransferOut({requestType:"class",recipient:"interface",request:9,value:512,index:this.iface.interfaceNumber},t)).status&&this.error("USB CTRL OUT transfer failed")}}async readLoop(){if(!this.readLoopStarted)for(this.readLoopStarted=!0,this.log("start read loop");;)if(this.ready)try{const t=await this.recvPacketAsync();t[0]?this.onData(t):await e.U.delay(500)}catch(t){this.dev&&this.onError(t),await e.U.delay(300)}else await e.U.delay(300)}async recvPacketAsync(e){const t=Date.now();for(;!e||Date.now()<t+e;){if(!this.dev)throw new Error("Disconnected");const e=await(this.epIn?this.dev.transferIn(this.epIn.endpointNumber,64):this.dev.controlTransferIn({requestType:"class",recipient:"interface",request:1,value:256,index:this.iface.interfaceNumber},64));"ok"!=e.status&&this.error("USB IN transfer failed");let t=new Uint8Array(e.data.buffer);if(0!=t.length)return t}this.error("USB IN timed out")}async initAsync(){var n;if(!this.dev)throw new Error("Disconnected");const i=this.dev;this.log("open device"),await i.open(),this.log("select configuration"),await i.selectConfiguration(1);this.log("got "+i.configurations[0].interfaces.length+" interfaces");const s=i.configurations[0].interfaces.filter((e=>{let n=e.alternates[0];for(let e of t.filters)if((null==e.classCode||n.interfaceClass===e.classCode)&&!(null!=e.subclassCode&&n.interfaceSubclass!==e.subclassCode||null!=e.protocolCode&&n.interfaceProtocol!==e.protocolCode)){if(0==n.endpoints.length)return!0;if(2==n.endpoints.length&&n.endpoints.every((e=>64==e.packetSize)))return!0}return!1}));let o=s[s.length-1];this.log(`${s.length} matching interfaces; picking ${o?"#"+o.interfaceNumber:"n/a"}`),o||this.error("cannot find supported USB interface"),this.altIface=o.alternates[0],this.iface=o,this.altIface.endpoints.length?(this.log("using dedicated endpoints"),this.epIn=this.altIface.endpoints.filter((e=>"in"==e.direction))[0],this.epOut=this.altIface.endpoints.filter((e=>"out"==e.direction))[0],e.Util.assert(64==this.epIn.packetSize),e.Util.assert(64==this.epOut.packetSize)):this.log("using ctrl pipe"),this.log("claim interface"),await i.claimInterface(o.interfaceNumber),this.log("device ready"),this.lastKnownDeviceSerialNumber=this.dev.serialNumber,this.ready=!0,r&&this.readLoop(),null===(n=this.onConnectionChanged)||void 0===n||n.call(this)}}async function a(){var t;e.log("webusb: get devices");try{return await(null===(t=navigator.usb)||void 0===t?void 0:t.getDevices())||[]}catch(t){return e.reportException(t),[]}}async function l(){var t,n;if(void 0!==s)return;if(e.debug("webusb: checking availability"),!(null===(n=null===(t=e.appTarget)||void 0===t?void 0:t.compile)||void 0===n?void 0:n.webUSB))return void(s=!1);const i=await c();if(i)switch(s=!1,e.tickEvent("webusb.off",{reason:i}),i){case"electron":e.debug("webusb: off, electron");break;case"notimpl":e.debug("webusb: off, not implemented by browser");break;case"oldwindows":e.debug("webusb: off, older windows version");break;case"security":e.debug("webusb: off, security exception")}else s=!0}async function c(){if(e.BrowserUtils.isElectron())return"electron";const t=navigator.usb;if(!t)return"notimpl";let n=/Windows NT (\d+\.\d+)/.exec(navigator.userAgent);if(n&&parseFloat(n[1])<6.3)return"oldwindows";try{await t.getDevices()}catch(e){return"security"}}function u(){return void 0===s&&(console.error("checkAvailableAsync not called"),l()),!!s}t.pairAsync=async function(){var e;try{return!!await(null===(e=navigator.usb)||void 0===e?void 0:e.requestDevice({filters:t.filters}))}catch(e){if("NotFoundError"==e.name)return;throw e}},t.tryGetDevicesAsync=a,t.mkWebUSBHIDPacketIOAsync=function(){return e.debug("packetio: mk webusb io"),i||(i=new o),i.enable(),Promise.resolve(i)},t.forgetDeviceAsync=async function(){return e.debug("packetio: forget webusb io"),!!i&&i.forgetAsync()},t.isEnabled=!1,t.setEnabled=function(e){u()||(e=!1),t.isEnabled=e},t.checkAvailableAsync=l,t.getReasonUnavailable=c,t.isAvailable=u}(e.usb||(e.usb={}))}(pxt||(pxt={})),function(e){!function(t){var n=e.Util;let i={};function s(e){let t={},i=0,s=new n.PromiseQueue,r=new Promise(((e,n)=>{t.ready=e}));s.enqueue("main",(()=>r));return{opAsync:function(n,r){return s.enqueue("main",(()=>new Promise(((s,o)=>{let a=""+i++;t[a]=e=>{e?e.errorMessage?o(new Error(e.errorMessage)):s(e):o(new Error("no response"))},e({id:a,op:n,arg:r})}))))},recvHandler:e=>{if(t.hasOwnProperty(e.id)){let n=t[e.id];delete t[e.id],n(e.result)}}}}function r(t){let n=new Worker(t),i=s((e=>n.postMessage(e)));return n.onmessage=t=>{e.perf.measureStart("webworker recvHandler"),i.recvHandler(t.data),e.perf.measureEnd("webworker recvHandler")},i}t.getWorker=function(e){let t=i[e];return t||(t=i[e]=r(e)),t},t.wrap=s,t.makeWebWorker=r,t.makeWebSocket=function(t,n=null){let i=new WebSocket(t),r=[],o=s((e=>{let t=JSON.stringify(e);r?r.push(t):i.send(t)}));return i.onmessage=e=>{let t=JSON.parse(e.data);n&&null==t.id?n(t):o.recvHandler(t)},i.onopen=t=>{e.debug("socket opened");for(let e of r)i.send(e);r=null},i.onclose=t=>{e.debug("socket closed")},i.onerror=t=>{e.debug("socket errored")},o}}(e.worker||(e.worker={}))}(pxt||(pxt={})),function(e){!function(t){function n(){t.apiKey||e.U.userError("YouTube API key missing")}function i(e){if(!e)return"";const t=e.medium||e.high||e.standard||e.default;return(null==t?void 0:t.url)||""}t.apiKey=void 0,t.playlistItemToCodeCard=function(e){return{name:e.snippet.title.replace(/[^-]*-/,"").trim(),description:(t=e.snippet.description,t.split(/\n\s+/,1)[0].trim()),youTubeId:e.snippet.resourceId.videoId,youTubePlaylistId:e.snippet.playlistId,imageUrl:i(e.snippet.thumbnails)};var t},t.playlistInfoAsync=function(i){n();const s=`https://www.googleapis.com/youtube/v3/playlists?part=snippet&id=${i}&key=${t.apiKey}`;return e.Util.httpGetJsonAsync(s).then((e=>e.items[0]))},t.listPlaylistVideosAsync=async function(i){n();let s,r=[];do{let n=`https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=${i}&key=${t.apiKey}`;s&&(n+=`&pageToken=${s}`);const o=await e.Util.httpGetJsonAsync(n);r=r.concat(o.items),s=o.nextPageToken}while(s);return e.options.debug&&e.debug(JSON.stringify(r,null,2)),r},t.watchUrl=function(e,t){let n;return e?(n=`https://www.youtube.com/watch?v=${e}`,t&&(n+=`&list=${t}`)):t&&(n=`https://www.youtube.com/playlist?list=${t}`),n}}(e.youtube||(e.youtube={}))}(pxt||(pxt={})),function(e){!function(e){!function(t){function n(e,...t){return e.replace(/{(\d+)}/g,((e,n)=>t[+n]))}t.debug=!1,t.lf=n;let i=u("opcode name doesn't match","<name>");class s{constructor(t,n,i,s,r){this.opcode=i,this.mask=s,this.is32bit=r,this.canBeShared=!1,e.assert((i&s)==i),this.ei=t,this.code=n.replace(/\s+/g," "),this.friendlyFmt=n.replace(/\$\w+/g,(e=>this.ei.encoders[e]?this.ei.encoders[e].pretty:e));let o=l(n);this.name=o[0],this.args=o.slice(1)}emit(t){let n=t.words;if(n[0]!=this.name)return i;let s=this.opcode,r=1,o=0,a=[],l=null,c=null,d=null;for(let i=0;i<this.args.length;++i){let h=this.args[i],p=n[r++];if("$"==h[0]){let i=this.ei.encoders[h],f=null;if(i.isRegister){if(f=this.ei.registerNo(p),null==f)return u("expecting register name",p);this.ei.isPush(this.opcode)?o++:this.ei.isPop(this.opcode)&&o--}else if(i.isImmediate){if(p=p.replace(/^#/,""),f=t.bin.parseOneInt(p),null==f)return u("expecting number",p);this.ei.isAddSP(this.opcode)?o=-f/this.ei.wordSize():this.ei.isSubSP(this.opcode)&&(o=f/this.ei.wordSize())}else if(i.isRegList){if("{"!=p)return u("expecting {",p);for(f=0;"}"!=n[r];){if(p=n[r++],!p)return u("expecting }",n[r-2]);let e=this.ei.registerNo(p);if(null==e)return u("expecting register name",p);if(f&1<<e)return u("duplicate register name",p);f|=1<<e,this.ei.isPush(this.opcode)?o++:this.ei.isPop(this.opcode)&&o--,","==n[r]&&r++}p=n[r++]}else if(i.isLabel){if(p=p.replace(/^#/,""),/^[+-]?\d+$/.test(p))f=parseInt(p,10),l="rel"+f;else if(/^0x[0-9a-fA-F]+$/.test(p))f=parseInt(p,16),l="abs"+f;else if(l=p,f=this.ei.getAddressFromLabel(t.bin,this,p,i.isWordAligned),null==f){if(t.bin.finalEmit)return u("unknown label",p);f=8}if(this.ei.is32bit(this)){c=f,d=p;continue}}else e.oops();if(null==f)return u("didn't understand it",p);if(a.push(f),f=i.encode(f),null==f)return u("argument out of range or mis-aligned",p);e.assert(0==(s&f)),s|=f}else if(h!=p)return u("expecting "+h,p)}return n[r]?u("trailing tokens",n[r]):this.ei.is32bit(this)?this.ei.emit32(s,c,t.bin.normalizeExternalLabel(d)):{stack:o,opcode:s,numArgs:a,labelName:t.bin.normalizeExternalLabel(l)}}toString(){return this.friendlyFmt}}t.Instruction=s;class r{constructor(e,t){this.bin=e,this.text=t}getOpExt(){return this.instruction?this.instruction.code:""}getOp(){return this.instruction?this.instruction.name:""}update(e){this.bin.peepOps++,(e=e.replace(/^\s*/,""))||this.bin.peepDel++,e&&(e+=" "),e=" "+e,this.text=e+"; WAS: "+this.text.trim(),this.instruction=null,this.numArgs=null,this.words=l(e)||[],0==this.words.length?this.type="empty":"@"==this.words[0][0]&&(this.type="directive")}}t.Line=r;class o{constructor(e,t){this.id=e,this.description=t,this.sizeAdj=0,this.users=[]}get size(){return this.endLocation-this.startLocation-this.sizeAdj}}class a{constructor(e){this.baseOffset=0,this.checkStack=!0,this.inlineMode=!1,this.normalizeExternalLabel=e=>e,this.currLineNo=0,this.scope="",this.scopeId=0,this.errors=[],this.labels={},this.equs={},this.stackpointers={},this.stack=0,this.commPtr=0,this.peepOps=0,this.peepDel=0,this.peepCounts={},this.stats="",this.throwOnError=!1,this.disablePeepHole=!1,this.stackAtLabel={},this.codeSizeStats=!1,this.labelToObject={},this.idToObject={},this.objSuspendStart=0,this.labelsToObjectDone=!1,this.currLine=new r(this,"<start>"),this.currLine.lineNo=0,this.ei=e,this.ei.file=this}emitShort(t){e.assert(0<=t&&t<=65535),this.buf.push(t)}emitOpCode(e){this.emitShort(e)}location(){return 2*this.buf.length}pc(){return this.location()+this.baseOffset}useLabel(t){if(!this.currObject||"."==t[0]||this.objSuspendStart)return;const n=e.U.lookup(this.labelToObject,t);n&&n!=this.currObject&&n.users.length<5&&n.users.indexOf(this.currObject)<0&&n.users.push(this.currObject)}parseOneInt(t){if(!t)return null;if(/^\d+$/.test(t))return parseInt(t,10);const i=t.indexOf("-");if(i>0)return this.parseOneInt(t.slice(0,i))-this.parseOneInt(t.slice(i+1));let s=1;if(t.indexOf("*")>=0){let e=null;for(;null!=(e=/^([^\*]*)\*(.*)$/.exec(t));){let n=this.parseOneInt(e[1]);if(null==n)return null;s*=n,t=e[2]}}if("-"==t[0]?(s*=-1,t=t.slice(1)):"+"==t[0]&&(t=t.slice(1)),/^\d+$/.test(t))return s*parseInt(t,10);if(e.U.endsWith(t,"|1"))return 1|this.parseOneInt(t.slice(0,t.length-2));if(e.U.endsWith(t,"-1"))return this.parseOneInt(t.slice(0,t.length-2))-1;if(e.U.endsWith(t,"+1"))return this.parseOneInt(t.slice(0,t.length-2))+1;let r=/(.*)>>(\d+)$/.exec(t);if(r){let e=this.parseOneInt(r[1]);return e&=~(-16777216&this.baseOffset),e>>parseInt(r[2])}let o=null;if("0"==t[0])if("x"==t[1]||"X"==t[1]){let e=/^0x([a-f0-9]+)$/i.exec(t);e&&(o=parseInt(e[1],16))}else if("b"==t[1]||"B"==t[1]){let e=/^0b([01]+)$/i.exec(t);e&&(o=parseInt(e[1],2))}if(t.indexOf("@")>=0){let i=/^(\w+)@(-?\d+)$/.exec(t);i&&(1!=s&&this.directiveError(n("multiplication not supported with saved stacks")),this.stackpointers.hasOwnProperty(i[1])?o=this.ei.wordSize()*this.ei.computeStackOffset(i[1],this.stack-this.stackpointers[i[1]]+parseInt(i[2])):this.directiveError(n("saved stack not found"))),i=/^(.*)@(hi|lo|fn)$/.exec(t),i&&this.looksLikeLabel(i[1])&&(o=this.lookupLabel(i[1],!0),null!=o&&("fn"==i[2]?o=this.ei.toFnPtr(o,this.baseOffset,i[1]):(o>>=1,0<=o&&o<=65535?"hi"==i[2]?o=o>>8&255:"lo"==i[2]?o&=255:e.oops():(this.directiveError(n("@hi/lo out of range")),o=null))))}return null==o&&this.looksLikeLabel(t)&&(o=this.lookupLabel(t,!0),null!=o&&1==this.ei.postProcessRelAddress(this,1)&&(o+=this.baseOffset)),null==o||isNaN(o)?null:o*s}looksLikeLabel(e){return!/^(r\d|pc|sp|lr)$/i.test(e)&&/^[\.a-zA-Z_][\.:\w+]*$/.test(e)}scopedName(e){return"."==e[0]&&this.scope?this.scope+"$"+e:e}lookupLabel(e,t=!1){this.useLabel(e);let i=null,s=this.scopedName(e);return this.labels.hasOwnProperty(s)?(i=this.labels[s],i=this.ei.postProcessRelAddress(this,i)):this.lookupExternalLabel&&(i=this.lookupExternalLabel(e),null!=i&&(i=this.ei.postProcessAbsAddress(this,i))),null==i&&this.equs.hasOwnProperty(s)&&(i=this.equs[s]),null==i&&t&&(this.finalEmit?this.directiveError(n("unknown label: {0}",e)):i=11111),i}align(t){for(e.assert(2==t||4==t||8==t||16==t);this.location()%t!=0;)this.emitOpCode(0)}pushError(e,t=""){let i={scope:this.scope,message:n(" -> Line {2} ('{1}'), error: {0}\n{3}",e,this.currLine.text,this.currLine.lineNo,t),lineNo:this.currLine.lineNo,line:this.currLine.text,coremsg:e,hints:t};if(this.errors.push(i),this.throwOnError)throw new Error(i.message)}directiveError(e){this.pushError(e)}emitString(e,t=!1){function i(e,t){return 255&(e.charCodeAt(t)||0)}let s,r=/^\s*([\w\.]+\s*:\s*)?.\w+\s+(".*")\s*$/.exec(e);if(r&&null!=(s=c(r[2])))if(this.align(2),t)for(let e=0;e<s.length;e++)this.emitShort(s.charCodeAt(e));else for(let e=0;e<s.length+1;e+=2)this.emitShort(i(s,e+1)<<8|i(s,e));else this.directiveError(n("expecting string"))}parseNumber(e){let t=this.parseOneInt(e.shift());return null==t?null:t}parseNumbers(e){e=e.slice(1);let t=[];for(;;){let i=this.parseNumber(e);if(null==i){this.directiveError(n("cannot parse number at '{0}'",e[0]));break}if(t.push(i),","!=e[0]){if(null==e[0])break;this.directiveError(n("expecting number, got '{0}'",e[0]));break}if(e.shift(),null==e[0])break}return t}emitSpace(e){let t=this.parseNumbers(e);if(1==t.length&&t.push(0),2!=t.length)this.directiveError(n("expecting one or two numbers"));else if(t[0]%2!=0)this.directiveError(n("only even space supported"));else{let e=255&t[1];e|=e<<8;for(let n=0;n<t[0];n+=2)this.emitShort(e)}}emitBytes(e){let t=this.parseNumbers(e);t.length%2!=0&&(this.directiveError(".bytes needs an even number of arguments"),t.push(0));for(let e=0;e<t.length;e+=2){let i=t[e],s=t[e+1];0<=i&&s<=255&&0<=s&&i<=255?this.emitShort(255&i|(255&s)<<8):this.directiveError(n("expecting uint8"))}}emitHex(e){e.slice(1).forEach((e=>{if(","!=e)if(e.length%4!=0)this.directiveError(".hex needs an even number of bytes");else if(/^[a-f0-9]+$/i.test(e))for(let t=0;t<e.length;t+=4){let n=parseInt(e.slice(t,t+4),16);n=(255&n)<<8|n>>8&255,this.emitShort(n)}else this.directiveError(".hex needs a hex number")}))}handleDirective(t){let i,s=t.words,r=()=>{2!=s.length&&this.directiveError(n("expecting one argument"))};switch(s[0]){case".object":if(this.codeSizeStats)if("PUSH"==s[1])this.objSuspendStart=this.location();else if("POP"==s[1])this.objSuspendStart&&(this.currObject.sizeAdj+=this.location()-this.objSuspendStart),this.objSuspendStart=0;else{if(this.currObject&&(this.currObject.endLocation=this.location()),this.currObject=e.U.lookup(this.idToObject,s[1]),!this.currObject){const e=t.text.replace(/^[^"]*/,"");let i=s[1];s.length>2&&(i=c(e.trim()),null==i&&this.directiveError(n("expecting string in .object"))),this.currObject=new o(s[1],i),this.idToObject[s[1]]=this.currObject}this.currObject.sizeAdj=0,this.currObject.startLocation=this.location()}else;break;case".ascii":case".asciz":case".string":this.emitString(t.text);break;case".utf16":this.emitString(t.text,!0);break;case".align":if(r(),i=this.parseOneInt(s[1]),null!=i){if(0==i)return;i<=4?this.align(1<<i):this.directiveError(n("expecting 1, 2, 3 or 4 (for 2, 4, 8, or 16 byte alignment)"))}else this.directiveError(n("expecting number"));break;case".balign":if(r(),i=this.parseOneInt(s[1]),null!=i){if(1==i)return;2==i||4==i||8==i||16==i?this.align(i):this.directiveError(n("expecting 2, 4, 8, or 16"))}else this.directiveError(n("expecting number"));break;case".p2align":r(),i=this.parseOneInt(s[1]),null!=i?this.align(1<<i):this.directiveError(n("expecting number"));break;case".byte":this.emitBytes(s);break;case".hex":this.emitHex(s);break;case".hword":case".short":case".2bytes":this.parseNumbers(s).forEach((e=>{-32768<=e&&e<=65535?this.emitShort(65535&e):this.directiveError(n("expecting int16"))}));break;case".word":case".4bytes":case".long":this.parseNumbers(s).forEach((e=>{-2147483648<=e&&e<=4294967295?(this.emitShort(65535&e),this.emitShort(e>>16&65535)):this.directiveError(n("expecting int32"))}));break;case".skip":case".space":this.emitSpace(s);break;case".set":case".equ":/^\w+$/.test(s[1])||this.directiveError(n("expecting name"));const a=this.parseNumbers(s.slice(","==s[2]||"="==s[2]?2:1));1!=a.length&&this.directiveError(n("expecting one value")),void 0!==this.equs[s[1]]&&this.equs[s[1]]!=a[0]&&this.directiveError(n("redefinition of {0}",s[1])),this.equs[s[1]]=a[0];break;case".startaddr":this.location()&&this.directiveError(n(".startaddr can be only be specified at the beginning of the file")),r(),this.baseOffset=this.parseOneInt(s[1]);break;case"@stackmark":r(),this.stackpointers[s[1]]=this.stack;break;case"@stackempty":this.checkStack&&(null==this.stackpointers[s[1]]?this.directiveError(n("no such saved stack")):this.stackpointers[s[1]]!=this.stack&&this.directiveError(n("stack mismatch")));break;case"@scope":this.scope=s[1]||"",this.currLineNo=this.scope?0:this.realCurrLineNo;break;case".syntax":case"@nostackcheck":this.checkStack=!1;break;case"@dummystack":r(),this.stack+=this.parseOneInt(s[1]);break;case".section":case".global":this.stackpointers={},this.stack=0,this.scope="$S"+this.scopeId++;break;case".comm":{s=s.filter((e=>","!=e)),s.shift();let e=this.parseOneInt(s[1]),t=0;if(t=s[2]?this.parseOneInt(s[2]):4,null==this.lookupLabel(s[0])){for(this.commPtr||(this.commPtr=this.lookupExternalLabel("_pxt_comm_base")||0,this.commPtr||this.directiveError(n("PXT_COMM_BASE not defined")));this.commPtr&t-1;)this.commPtr++;this.labels[this.scopedName(s[0])]=this.commPtr-this.baseOffset,this.commPtr+=e}break}case".file":case".text":case".cpu":case".fpu":case".eabi_attribute":case".code":case".thumb_func":case".type":case".fnstart":case".save":case".size":case".fnend":case".pad":case".globl":case".local":case"@":break;default:/^\.cfi_/.test(s[0])||this.directiveError(n("unknown directive"))}}handleOneInstruction(e,t){this.codeSizeStats&&e.ldlitLabel&&this.useLabel(e.ldlitLabel);let i=t.emit(e);return!i.error&&(this.stack+=i.stack,this.checkStack&&this.stack<0&&this.pushError(n("stack underflow")),e.location=this.location(),e.opcode=i.opcode,e.stack=i.stack,this.emitOpCode(i.opcode),null!=i.opcode2&&this.emitOpCode(i.opcode2),null!=i.opcode3&&this.emitOpCode(i.opcode3),e.instruction=t,e.numArgs=i.numArgs,!0)}handleInstruction(e){if(e.instruction&&this.handleOneInstruction(e,e.instruction))return;let t=e=>this.ei.instructions.hasOwnProperty(e)?this.ei.instructions[e]:[];if(!e.instruction){let n=t(e.words[0]);for(let t=0;t<n.length;++t)if(this.handleOneInstruction(e,n[t]))return}let i=e.words[0].toLowerCase().replace(/s$/,"").replace(/[^a-z]/g,""),s="",r=t(i).concat(t(i+"s"));r.length>0&&r.forEach((t=>{let i=t.emit(e);s+=n(" Maybe: {0} ({1} at '{2}')\n",t.toString(),i.error,i.errorAt)})),this.pushError(n("assembly error"),s)}buildLine(e,t){let n=e=>{let n=new r(this,e);return n.scope=this.scope,n.lineNo=this.currLineNo,t.push(n),n},i=n(e),s=l(i.text)||[];i.words=s;let o=s[0]||"";if(":"==o.charAt(o.length-1)){let t=/^([\.\w]+):$/.exec(s[0]);if(t){if(i.type="label",i.text=t[1]+":",i.words=[t[1]],!(s.length>1))return;s.shift(),i=n(e.replace(/^[^:]*:/,"")),i.words=s,o=s[0]||""}}let a=o.charAt(0);"."==a||"@"==a?(i.type="directive","@scope"==i.words[0]&&this.handleDirective(i)):0==i.words.length?i.type="empty":i.type="instruction"}prepLines(e){this.currLineNo=0,this.realCurrLineNo=0,this.lines=[],e.split(/\r?\n/).forEach((e=>{this.errors.length>10||(this.currLineNo++,this.realCurrLineNo++,this.buildLine(e,this.lines))}))}iterLines(){this.stack=0,this.buf=[],this.scopeId=0,this.lines.forEach((t=>{if(!(this.errors.length>10)&&(this.currLine=t,0!=t.words.length))if("label"==t.type){this.currObject&&!this.labelsToObjectDone&&"."!=t.words[0][0]&&(this.labelToObject[t.words[0]]=this.currObject);let i=this.scopedName(t.words[0]);if(this.prevLabel=i,this.finalEmit){null!=this.equs[i]&&this.directiveError(n(".equ redefined as label"));let t=this.labels[i];null==t&&e.oops(),0==this.errors.length&&t!=this.location()&&e.oops(`invalid location: ${this.location()} != ${t} at ${i}`),e.assert(this.errors.length>0||t==this.location()),this.reallyFinalEmit&&(this.stackAtLabel[i]=this.stack)}else this.labels.hasOwnProperty(i)?this.directiveError(n("label redefinition")):this.inlineMode&&/^_/.test(i)?this.directiveError(n("labels starting with '_' are reserved for the compiler")):this.labels[i]=this.location();t.location=this.location()}else"directive"==t.type?this.handleDirective(t):"instruction"==t.type?this.handleInstruction(t):"empty"==t.type||e.oops()})),this.labelsToObjectDone=!0,this.currObject=null}getSourceMap(){const e={};let t="",n=0,i=0,s=0;function r(){t&&i&&(e[t]||(e[t]=[]),e[t].push(n,i,s-i)),i=0,s=0}return this.lines.forEach(((e,o)=>{const a=/^; ([\w\/\.-]+)\(([\d]+),\d+\):/.exec(e.text);a&&(r(),t=a[1],n=parseInt(a[2])),"instruction"==e.type&&(i||(i=e.location),s=e.location)})),r(),e}getCodeSizeStats(){if(!this.codeSizeStats)return"";const t=e.U.values(this.idToObject);t.sort(((e,t)=>t.size-e.size));let n=";\n; Code size:\n;\n";for(const e of t)if(n+=`; ${(" "+e.size).slice(-6)} ${e.description} [${e.id}]\n`,e.users.length>=5)n+=`; by many, including ${e.users[0].description}\n`;else for(const t of e.users)n+=`; by ${t.description} [${t.id}]\n`;return n}getSource(e,i=1,s=0){let r=0,o=e=>{let t=this.labels[e]||r,n=t-r;return r=t,n},a=this.buf?this.location():0,l=o("_code_end"),c=o("_helpers_end"),u=o("_vtables_end"),d=o("_literals_end"),h=r,p=a+this.baseOffset&16777215;if(s&&p>s){const e=new Error(n("program too big by {0} bytes!",p-s));throw e.ksErrorCode=9283,e}let f=n("; total bytes: {0} ({1}% of {2}k flash with {3} free)",p,(100*p/(s=s||131072)).toFixed(1),(s/1024).toFixed(1),s-p),m=n("; generated code sizes (bytes): {0} (incl. {1} user, {2} helpers, {3} vtables, {4} lits); src size {5}\n",h,l,c,u,d,a-h)+n("; assembly: {0} lines; density: {1} bytes/stmt; ({2} stmts)\n",this.lines.length,Math.round(100*l/i)/100,i)+f+"\n"+this.stats+this.getCodeSizeStats()+"\n\n",g=!1;return this.lines.forEach(((n,i)=>{if("_stored_program"==n.words[0])return m+='_stored_program: .string "..."\n',void(g=!0);if(g)return void(g=!1);let s=n.text;if(e){if("@stackempty"==n.words[0]&&this.lines[i-1].text==n.text)return;if(s=s.replace(/; WAS: .*/,""),!s.trim())return}t.debug&&("label"!=n.type&&"instruction"!=n.type||(s+=` \t; 0x${(n.location+this.baseOffset).toString(16)}`)),m+=s+"\n"})),m}peepHole(){let e=this.lines.filter((e=>"empty"!=e.type));for(let t=0;t<e.length;++t){let n=e[t];if(/^user/.test(n.scope))continue;let i=e[t+1];if(!i)continue;let s=e[t+2];"instruction"==n.type&&this.ei.peephole(n,i,s)}}clearLabels(){this.labels={},this.commPtr=0}peepPass(t){this.disablePeepHole||(this.peepOps=0,this.peepDel=0,this.peepCounts={},this.peepHole(),this.throwOnError=!0,this.finalEmit=!1,this.clearLabels(),this.iterLines(),e.assert(!this.checkStack||0==this.stack),this.finalEmit=!0,this.reallyFinalEmit=t||0==this.peepOps,this.iterLines(),this.stats+=n("; peep hole pass: {0} instructions removed and {1} updated\n",this.peepDel,this.peepOps-this.peepDel))}getLabels(){return this.userLabelsCache||(this.userLabelsCache=e.U.mapMap(this.labels,((e,t)=>t+this.baseOffset))),this.userLabelsCache}emit(t){if(e.assert(null==this.buf),this.prepLines(t),this.errors.length>0)return;if(this.clearLabels(),this.iterLines(),this.checkStack&&0!=this.stack&&this.directiveError(n("stack misaligned at the end of the file")),this.errors.length>0)return;if(this.ei.expandLdlit(this),this.clearLabels(),this.iterLines(),this.finalEmit=!0,this.reallyFinalEmit=this.disablePeepHole,this.iterLines(),this.errors.length>0)return;for(let e=0;e<5&&(pxt.debug(`Peephole OPT, pass ${e}`),this.peepPass(5==e),0!=this.peepOps);++e);pxt.debug("emit done")}}t.File=a;t.VMFile=class extends a{constructor(e){super(e)}};function l(e){let t=[],n="";e:for(let i=0;i<e.length;++i)switch(e[i]){case"[":case"]":case"!":case"{":case"}":case",":n&&(t.push(n),n=""),t.push(e[i]);break;case" ":case"\t":case"\r":case"\n":n&&(t.push(n),n="");break;case";":break e;default:n+=e[i]}return n&&(t.push(n),n=""),t[0]?t:null}function c(e){e=e.replace(/\\\\/g,"\\B").replace(/\\(['\?])/g,((e,t)=>t)).replace(/\\[z0]/g,"\0").replace(/\\x([0-9a-f][0-9a-f])/gi,((e,t)=>"\\u00"+t)).replace(/\\B/g,"\\\\");try{return JSON.parse(e)}catch(e){return null}}function u(e,t){return{stack:null,opcode:null,error:e,errorAt:t}}function d(e){return e<0||e>65535?("0x"+e.toString(16)).toLowerCase():("0x"+("000"+e.toString(16)).slice(-4)).toLowerCase()}t.AbstractProcessor=class{constructor(){this.file=null,this.addEnc=(e,t,n)=>{let i={name:e,pretty:t,encode:n,isRegister:/^\$r\d/.test(e),isImmediate:/^\$i\d/.test(e),isRegList:/^\$rl\d/.test(e),isLabel:/^\$l[a-z]/.test(e)};return this.encoders[e]=i,i},this.inrange=(e,t,n)=>Math.floor(t)!=t||t<0||t>e?null:n,this.inminmax=(e,t,n,i)=>Math.floor(n)!=n||n<e||n>t?null:i,this.inseq=(e,t)=>{let n=e.indexOf(t);return n<0?null:n},this.inrangeSigned=(e,t,n)=>{if(Math.floor(t)!=t)return null;if(t<-(e+1))return null;if(t>e)return null;return n&(e<<1|1)},this.addInst=(e,t,n,i)=>{let r=new s(this,e,t,n,i);return this.instructions.hasOwnProperty(r.name)||(this.instructions[r.name]=[]),this.instructions[r.name].push(r),r},this.encoders={},this.instructions={}}toFnPtr(e,t,n){return e}wordSize(){return-1}computeStackOffset(e,t){return t}is32bit(e){return!1}emit32(e,t,n){return null}postProcessRelAddress(e,t){return t}postProcessAbsAddress(e,t){return t}peephole(e,t,n){}registerNo(e){return null}getAddressFromLabel(e,t,n,i=!1){return null}isPop(e){return!1}isPush(e){return!1}isAddSP(e){return!1}isSubSP(e){return!1}testAssembler(){e.assert(!1)}expandLdlit(e){}},t.emitErr=u,t.expectError=function(t,n){let i=new a(t);i.emit(n),0==i.errors.length&&e.oops("ASMTEST: expecting error for: "+n)},t.tohex=d,t.expect=function(t,n){let i=[],s=n.replace(/^([0-9a-fA-F]{4,8})\s/gm,((e,t)=>(i.push(parseInt(t.slice(0,4),16)),8==t.length&&i.push(parseInt(t.slice(4,8),16)),""))),r=new a(t);r.throwOnError=!0,r.disablePeepHole=!0,r.emit(s),r.errors.length>0&&(console.debug(r.errors[0].message),e.oops("ASMTEST: not expecting errors")),r.buf.length!=i.length&&e.oops("ASMTEST: wrong buf len");for(let t=0;t<i.length;++t)r.buf[t]!=i[t]&&e.oops("ASMTEST: wrong buf content at "+t+" , exp:"+d(i[t])+", got: "+d(r.buf[t]))}}(e.assembler||(e.assembler={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){var n=pxtc.Util;t.apiRoot=e.BrowserUtils.isLocalHost()||n.isNodeJS?"https://www.makecode.com/api/":"/api/",t.accessToken="",t.localToken="";let i=!0;function s(t){let i=new Error(n.lf("Cannot access {0} while offline",t));return i.isOffline=!0,e.U.delay(1e3).then((()=>Promise.reject(i)))}function r(n,i){return e.U.requestAsync({url:"/api/"+n,headers:{Authorization:t.localToken},method:i?"POST":"GET",data:i||void 0,allowHttpErrors:!0})}function o(){return e.webConfig&&!e.webConfig.isStatic&&!e.BrowserUtils.isLocalHost()&&!!e.webConfig.cdnUrl}function a(n){if(n=n.replace(/^\//,""),!o())return t.apiRoot+n;const i=new Date,s=i.getUTCFullYear()+("0"+(i.getUTCMonth()+1)).slice(-2)+("0"+i.getUTCDate()).slice(-2);return n.indexOf("?")<0?n+="?":n+="&",n+="cdn="+s,e.webConfig.cdnUrl+"/api/"+n}function l(e){return o()?(e.url=a(e.url),n.requestAsync(e).catch((t=>c(e,t)))):u(e)}function c(e,n){return 0==n.statusCode?(i&&(i=!1,t.onOffline()),s(e.url)):Promise.reject(n)}function u(i){var r;return i.url=(null===(r=e.webConfig)||void 0===r?void 0:r.isStatic)&&!i.forceLiveEndpoint?e.webConfig.relprefix+i.url:t.apiRoot+i.url,i.allowGzipPost=!0,t.isOnline()||e.BrowserUtils.isPxtElectron()?(i.headers||(i.headers={}),e.BrowserUtils.isLocalHost()?t.localToken&&(i.headers.Authorization=t.localToken):t.accessToken&&(i.headers["x-td-access-token"]=t.accessToken),n.requestAsync(i).catch((e=>c(i,e)))):s(i.url)}function d(){return navigator&&navigator.onLine}t.onOffline=()=>{},t.hasAccessToken=function(){return!!t.accessToken},t.localRequestAsync=r,t.useCdnApi=o,t.cdnApiUrl=a,t.apiRequestWithCdnAsync=l,t.privateRequestAsync=u,t.privateGetTextAsync=function(e,t){return u({url:e,headers:t}).then((e=>e.text))},t.privateGetAsync=function(e,t=!1){return u({url:e,forceLiveEndpoint:t}).then((e=>e.json))},t.downloadTargetConfigAsync=function(){if(!t.isOnline())return Promise.resolve(void 0);const n=e.appTarget.versions&&e.appTarget.versions.target,i=e.webConfig&&e.webConfig.isStatic?"targetconfig.json":`config/${e.appTarget.id}/targetconfig${n?`/v${n}`:""}`;return e.BrowserUtils.isLocalHost()?r(i).then((e=>e?e.json:void 0)):l({url:i}).then((e=>e.json))},t.downloadScriptFilesAsync=function(e){return u({url:e+"/text"+(e.startsWith("S")?`?time=${Date.now()}`:""),forceLiveEndpoint:!0}).then((e=>JSON.parse(e.text)))},t.downloadScriptMetaAsync=function(e){return u({url:e+(e.startsWith("S")?`?time=${Date.now()}`:""),forceLiveEndpoint:!0}).then((e=>JSON.parse(e.text).meta))},t.downloadBuiltSimJsInfoAsync=async function(t){const n=e.appTarget.versions&&e.appTarget.versions.target||"",i=e.U.stringifyQueryString(t+"/js",{v:"v"+n})+(t.startsWith("S")?`&time=${Date.now()}`:"");return(await u({url:i,forceLiveEndpoint:!0})).json},t.markdownAsync=async function(t,n,i){const s=e.BrowserUtils.isLocalHostDev()?0:36e5,a=24*s*7;n=n||e.Util.userLanguage();const c=await e.BrowserUtils.translationDbAsync(),d=await c.getAsync(n,t),h=async()=>{try{const i=await function(t,n,i){var s;const a=null===(s=e.webConfig)||void 0===s?void 0:s.isStatic,c=e.appTarget.versions&&e.appTarget.versions.target||"?";let d;if(a){d=t;const e=/\/?docs\//.test(d),n=/\.\w+$/.test(d);if(!e){const e="/"===d[0];d=`docs${e?"":"/"}${d}`}n||(d=`${d}.md`)}else d=`md/${e.appTarget.id}/${t.replace(/^\//,"")}?targetVersion=${encodeURIComponent(c)}`;"en"!=n&&(d+=`${a?"?":"&"}lang=${encodeURIComponent(n)}`);if(e.BrowserUtils.isLocalHost()&&!e.Util.liveLocalizationEnabled())return r(d).then((e=>404==e.statusCode?u({url:d,method:"GET"}).then((e=>({md:e.text,etag:e.headers.etag}))):{md:e.text,etag:void 0}));{const e=i&&!o()?{"If-None-Match":i}:void 0;return l({url:d,method:"GET",headers:e}).then((e=>({md:e.text,etag:e.headers.etag})))}}(t,n,null==d?void 0:d.etag);return!d||i.md&&d.md!==i.md?(await c.setAsync(n,t,i.etag,void 0,i.md),i.md):d.md}catch(e){if(i)throw e;return""}};if(d){const t=Date.now()-d.time,n=t>s;if(t>a)e.tickEvent("markdown.update.wait");else if(n&&(e.tickEvent("markdown.update.background"),h()),d.md)return d.md}return h()},t.privateDeleteAsync=function(e){return u({url:e,method:"DELETE"}).then((e=>e.json))},t.privatePostAsync=function(e,t,n=!1){return u({url:e,data:t||{},forceLiveEndpoint:n}).then((e=>e.json))},t.isLoggedIn=function(){return!!t.accessToken},t.isNavigatorOnline=d,t.isOnline=function(){return"undefined"!=typeof navigator&&d()&&(i=!0),i},t.getServiceUrl=function(){return t.apiRoot.replace(/\/api\/$/,"")},t.getUserId=function(){let e=/^0(\w+)\./.exec(t.accessToken);return e?e[1]:null},t.parseScriptId=function(t){var i;const s=e.appTarget;if(!t||!s.appTheme||!(null===(i=s.cloud)||void 0===i?void 0:i.sharing))return;let r=["makecode.com"];s.appTheme.embedUrl&&r.push(s.appTheme.embedUrl),s.appTheme.shareUrl&&r.push(s.appTheme.shareUrl),r=n.unique(r,(e=>e)).map((e=>n.escapeForRegex(n.stripUrlProtocol(e).replace(/\/$/,"")).toLowerCase()));const o=`(?:(?:https://)?(?:${r.join("|")})/)`,a=new RegExp(`^${o}?(?:v[0-9]+/)?(?:(?:api/oembed\\?url=.*%2F([^&#]*)&.*)|(?:/?([a-z0-9\\-_]+)(?:[#?&].*)?))$`,"i").exec(t.trim()),l=(null==a?void 0:a[1])||(null==a?void 0:a[2]);return/^(_.{12}|S?[0-9\-]{23})$/.test(l)?l:void 0}}(e.Cloud||(e.Cloud={}))}(pxt||(pxt={})),function(e){!function(e){e.f4EncodeImg=function(e,t,n,i){let s=[135,n,255&e,e>>8,255&t,t>>8,0,0].map(c).join(""),r=4,o=0,a=0,l=e=>{o|=e<<a,a==8-n?(s+=c(o),r++,o=0,a=0):a+=n};for(let s=0;s<e;++s){for(let e=0;e<t;++e)l(i(s,e));for(;0!=a;)l(0);if(n>1)for(;3&r;)l(0)}return s;function c(e){return("0"+e.toString(16)).slice(-2)}}}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){function t(e){let t="";switch(e){case 0:t="C5";break;case 1:t="B";break;case 2:t="A";break;case 3:t="G";break;case 4:t="F";break;case 5:t="E";break;case 6:t="D";break;case 7:t="C"}return t}function n(e){let t=-1;switch(e){case"C5":t=0;break;case"B":t=1;break;case"A":t=2;break;case"G":t=3;break;case"F":t=4;break;case"E":t=5;break;case"D":t=6;break;case"C":t=7}return t}e.MelodyArray=class{constructor(e){this.numCols=8,this.numRows=8,this.polyphonic=!1,e&&(this.tempo=e),this.resetMelody()}setTempo(e){this.tempo=e}getArray(){return this.melody}setArray(e){this.melody=e}getColor(e){return 0}getValue(e,t){return this.melody[e][t]}getWidth(){return this.numCols}getHeight(){return this.numRows}updateMelody(e,t){const n=!this.melody[e][t];if(n&&!this.polyphonic)for(let e=0;e<this.numRows;e++)this.melody[e][t]=!1;this.melody[e][t]=n}getStringRepresentation(){let e="",n=new Array(this.numCols),i=0;for(let e=0;e<this.numRows;e++){let s=0;n[e]=[];for(let i=0;i<this.numCols;i++)this.melody[i][e]&&(n[e].push(t(i)),s++);s>i&&(i=s)}if(0==i)return"- - - - - - - - ";for(let t=0;t<i;t++)for(let t=0;t<this.numCols;t++)n[t]&&n[t].length>0?e+=n[t].shift()+" ":e+="- ";return e}parseNotes(e){let t=(e=e.trim()).split(" ");for(let e=0;e<t.length;e++){for(let t=0;t<this.numRows;t++)this.melody[t][e]=!1;"-"!=t[e]&&(this.melody[n(t[e])][e]=!0)}}setPolyphonic(e){this.polyphonic=e}isPolyphonic(){return this.polyphonic}resetMelody(){this.melody=new Array(this.numCols);for(let e=0;e<this.numCols;e++)this.melody[e]=new Array(this.numRows).fill(!1)}},e.rowToNote=t,e.noteToRow=n,e.getColorClass=function(e){let t="melody-default";switch(e){case 0:t="melody-red";break;case 1:t="melody-orange";break;case 2:t="melody-yellow";break;case 3:t="melody-green";break;case 4:t="melody-teal";break;case 5:t="melody-blue";break;case 6:t="melody-purple";break;case 7:t="melody-violet"}return t}}(pxtmelody||(pxtmelody={})),function(e){function t(e,t,n){return function(e,t,n){if(t)for(const n of Object.keys(t))"className"===n?e.setAttribute("class",t[n]+""):e.setAttribute(n,t[n]+"");n&&e.addEventListener("click",n);return e}(document.createElement(e),t,n)}e.MelodyGallery=class{constructor(){this.value=null,this.visible=!1,this.timeouts=[],this.numSamples=e.SampleMelodies.length,this.containerDiv=document.createElement("div"),this.containerDiv.setAttribute("id","melody-editor-gallery-outer"),this.contentDiv=document.createElement("div"),this.contentDiv.setAttribute("id","melody-editor-gallery"),this.itemBackgroundColor="#DCDCDC",this.itemBorderColor="white",this.initStyles(),this.containerDiv.appendChild(this.contentDiv),this.containerDiv.style.display="none",this.contentDiv.addEventListener("animationend",(()=>{this.visible||(this.containerDiv.style.display="none")})),this.contentDiv.addEventListener("wheel",(e=>{e.stopPropagation()}),!0)}getElement(){return this.containerDiv}getValue(){return this.value}show(e){this.pending=e,this.containerDiv.style.display="block",this.buildDom(),this.visible=!0,pxt.BrowserUtils.removeClass(this.contentDiv,"hidden-above"),pxt.BrowserUtils.addClass(this.contentDiv,"shown")}hide(){this.visible=!1,pxt.BrowserUtils.removeClass(this.contentDiv,"shown"),pxt.BrowserUtils.addClass(this.contentDiv,"hidden-above"),this.value=null,this.stopMelody()}clearDomReferences(){this.contentDiv=null,this.containerDiv=null}layout(e,t,n){this.containerDiv.style.left=e+"px",this.containerDiv.style.top=t+"px",this.containerDiv.style.height=n+"px"}buildDom(){for(;this.contentDiv.firstChild;)this.contentDiv.removeChild(this.contentDiv.firstChild);const t=e.SampleMelodies;this.buttons=[];for(let e=0;e<t.length;e++)this.mkButton(t[e],e,"255px","45px")}initStyles(){const e=document.createElement("style");e.textContent="\n #melody-editor-gallery {\n margin-top: -100%;\n }\n\n #melody-editor-gallery.hidden-above {\n margin-top: -100%;\n animation: slide-up 0.2s 0s ease;\n }\n\n #melody-editor-gallery.shown {\n margin-top: 0px;\n animation: slide-down 0.2s 0s ease;\n }\n\n @keyframes slide-down {\n 0% {\n margin-top: -100%;\n }\n 100% {\n margin-top: 0px;\n }\n }\n\n @keyframes slide-up {\n 0% {\n margin-top: 0px;\n }\n 100% {\n margin-top: -100%;\n }\n }\n ",this.containerDiv.appendChild(e)}mkButton(e,n,i,s){const r=t("div",{className:"melody-gallery-button melody-editor-card",role:"menuitem",id:`:${n}`}),o=t("i",{className:"music icon melody-icon"}),a=t("div",{className:"melody-editor-text"});a.innerText=e.name;const l=this.createColorBlock(e),c=t("div",{className:"melody-editor-button left-button",role:"button",title:e.name},(()=>this.handleSelection(e)));c.appendChild(o),c.appendChild(a),c.appendChild(l),r.appendChild(c);const u=t("div",{className:"melody-editor-button right-button",role:"button",title:lf("Preview {0}",e.name)},(()=>this.togglePlay(e,n))),d=t("i",{className:"play icon"});this.buttons[n]=d,u.appendChild(d),r.appendChild(u),this.contentDiv.appendChild(r)}handleSelection(e){if(this.pending){const t=this.pending;this.pending=void 0,t(e.notes)}}playNote(e,t,n){let i=0;switch(e){case"C5":i=523;break;case"B":i=494;break;case"A":i=440;break;case"G":i=392;break;case"F":i=349;break;case"E":i=330;break;case"D":i=294;break;case"C":i=262}this.timeouts.push(setTimeout((()=>{pxt.AudioContextManager.tone(i)}),t*this.getDuration(n))),this.timeouts.push(setTimeout((()=>{pxt.AudioContextManager.stop()}),(t+1)*this.getDuration(n)))}getDuration(e){return 6e4/e}previewMelody(e){this.stopMelody();let t=e.notes.split(" ");for(let n=0;n<t.length;n++)this.playNote(t[n],n,e.tempo)}togglePlay(e,t){let n=this.buttons[t];pxt.BrowserUtils.containsClass(n,"play icon")?(this.resetPlayIcons(),pxt.BrowserUtils.removeClass(n,"play icon"),pxt.BrowserUtils.addClass(n,"stop icon"),this.previewMelody(e),this.timeouts.push(setTimeout((()=>{pxt.BrowserUtils.removeClass(n,"stop icon"),pxt.BrowserUtils.addClass(n,"play icon")}),e.notes.split(" ").length*this.getDuration(e.tempo)))):(pxt.BrowserUtils.removeClass(n,"stop icon"),pxt.BrowserUtils.addClass(n,"play icon"),this.stopMelody())}stopMelody(){for(;this.timeouts.length;)clearTimeout(this.timeouts.shift());pxt.AudioContextManager.stop()}resetPlayIcons(){for(let e=0;e<this.numSamples;e++){let t=this.buttons[e];if(pxt.BrowserUtils.containsClass(t,"stop icon")){pxt.BrowserUtils.removeClass(t,"stop icon"),pxt.BrowserUtils.addClass(t,"play icon");break}}}createColorBlock(t){let n=document.createElement("div");pxt.BrowserUtils.addClass(n,"melody-color-block");let i=t.notes.split(" ");for(let t=0;t<i.length;t++){let s=e.getColorClass(e.noteToRow(i[t])),r=document.createElement("div");0==t?pxt.BrowserUtils.addClass(r,"left-edge sliver "+s):t==i.length-1?pxt.BrowserUtils.addClass(r,"right-edge sliver "+s):pxt.BrowserUtils.addClass(r,"sliver "+s),n.appendChild(r)}return n}}}(pxtmelody||(pxtmelody={})),function(e){class t{constructor(e,t,n){this.name=e,this.notes=t,this.tempo=n}}e.MelodyInfo=t,e.SampleMelodies=[new t(lf("Scale"),"C5 B A G F E D C",120),new t(lf("Reverse"),"C D E F G A B C5",120),new t(lf("Mystery"),"E B C5 A B G A F",120),new t(lf("Gilroy"),"A F E F D G E F",120),new t(lf("Falling"),"C5 A B G A F G E",120),new t(lf("Hopeful"),"G B A G C5 B A B",120),new t(lf("Tokyo"),"B A G A G F A C5",120),new t(lf("Paris"),"G F G A - F E D",120),new t(lf("Rising"),"E D G F B A C5 B",120),new t(lf("Sitka"),"C5 G B A F A C5 B",120)]}(pxtmelody||(pxtmelody={})),function(e){!function(e){let t;e.makeFocusable=function(e){e.setAttribute("focusable","true"),e.setAttribute("tabindex","0")},e.enableKeyboardInteraction=function(e,t,n){t&&e.addEventListener("keydown",(e=>{const n="number"==typeof e.which?e.which:e.keyCode;32!==n&&13!==n||t()})),n&&e.addEventListener("keyup",(e=>{const t="number"==typeof e.which?e.which:e.keyCode;32!==t&&13!==t||n()}))},e.setAria=function(e,t,n){t&&!e.hasAttribute("role")&&e.setAttribute("role",t),n&&!e.hasAttribute("aria-label")&&e.setAttribute("aria-label",n)},e.setLiveContent=function(e){if(!t){let e="position: absolute !important;display: block;visibility: visible;overflow: hidden;width: 1px;height: 1px;margin: -1px;border: 0;padding: 0;clip: rect(0 0 0 0);";t=document.createElement("div"),t.setAttribute("role","status"),t.setAttribute("aria-live","polite"),t.setAttribute("aria-hidden","false"),t.setAttribute("style",e),document.body.appendChild(t)}t.textContent!==e&&(t.textContent=e)}}(e.accessibility||(e.accessibility={}))}(pxsim||(pxsim={})),function(e){const t="blue",n="red",i="orange";const s=e=>(e=>e.reduce(((e,t)=>e+(t?1:0)),0))(e)>0;function r(e,t){let n={};for(let t in e)n[t]=e[t];for(let e in t)n[e]=t[e];return n}function o(t){e.U.assert(!!t,"Invalid pin: "+t);const n=/^(\w+)\.\s*(?:[a-z]*)?([A-Z][A-Z\d_]+)$/.exec(t);return n?n[2]:void 0}function a(e){return"-Z"===e.orientation&&"male"===e.style}e.readPin=o;class l{constructor(t){this.availablePowerPins={top:{fiveVolt:e.mkRange(26,51).map((e=>({type:"breadboard",row:"+",col:`${e}`}))),threeVolt:e.mkRange(26,51).map((e=>({type:"breadboard",row:"+",col:`${e}`}))),ground:e.mkRange(26,51).map((e=>({type:"breadboard",row:"-",col:`${e}`})))},bottom:{fiveVolt:e.mkRange(1,26).map((e=>({type:"breadboard",row:"+",col:`${e}`}))),threeVolt:e.mkRange(1,26).map((e=>({type:"breadboard",row:"+",col:`${e}`}))),ground:e.mkRange(1,26).map((e=>({type:"breadboard",row:"-",col:`${e}`})))}},this.opts=t}allocPartIRs(e,t,n){let i=[];const s=(e,t,i,s)=>{let r=[];for(let t=0;t<e.numberOfPins;t++){let s,o=e.pinDefinitions[t];if("string"==typeof o.target)s=o.target;else{let e=o.target.pinInstantiationIdx;if(!i||void 0===i[e])return void console.log(`error: parts no pin found for PinInstantiationIdx: ${e}. (Is the part missing an ArgumentRole or "trackArgs=" annotations?)`);s=i[e]}let a=e.visual.pinLocations[t],l=n.yOffset+a.y,c=Math.round(l/e.visual.pinDistance),u=l-c*e.visual.pinDistance,d=n.xOffset+a.x,h=Math.round(d/e.visual.pinDistance),p={partRelativeRowIdx:c,partRelativeColIdx:h,xOffset:d-h*e.visual.pinDistance,yOffset:u};r.push({def:o,loc:a,target:s,bbFit:p})}return{name:t,def:e,pins:r,partParams:s||{},bbFit:n}},r=e.instantiations||[];return e.instantiation&&r.push(e.instantiation),r.forEach((n=>{if("singleton"===n.kind)i.push(s(e,t));else if("function"===n.kind){let r=n,a=r.fullyQualifiedName.split(","),l={};a.forEach((e=>{this.opts.fnArgs[e]&&this.opts.fnArgs[e].forEach((e=>{l[e]=1}))}));let c=Object.keys(l);if(!c||!c.length)return void console.log(`error: parts failed to read pin(s) from callsite for: ${a}`);c.forEach((n=>{const l=n.split(",");if(l.length!=r.argumentRoles.length)return void console.log(`error: parts mismatch between number of arguments at callsite (function name: ${a}) vs number of argument roles in part definition (part: ${t}).`);let c=[],u={};l.forEach(((e,t)=>{let n=r.argumentRoles[t];if(void 0!==n.partParameter&&(u[n.partParameter]=e),void 0!==n.pinInstantiationIdx){let t=n.pinInstantiationIdx,i=o(e);c[t]=i}})),i.push(s(e,t,c,u))}))}})),i.filter((e=>!!e))}computePartDimensions(t,n){let i=t.visual.pinLocations,s=t.pinDefinitions,o=t.numberOfPins;e.U.assert(i.length===o,`Mismatch between "numberOfPins" and length of "visual.pinLocations" for "${n}"`),e.U.assert(s.length===o,`Mismatch between "numberOfPins" and length of "pinDefinitions" for "${n}"`),e.U.assert(o>0,`Part "${n}" has no pins`);let a,l,c,u,d=i.map(((e,t)=>{return n={idx:t},i=e,o=s[t],r(r(n,i),o);var n,i,o})).filter((e=>"-Z"===e.orientation)),h=d.length>0,p=t.visual.pinDistance;if(h){let e=d[0],n=Math.ceil(e.x/p),i=Math.ceil(e.y/p);a=n*p-e.x,l=i*p-e.y,c=Math.ceil((a+t.visual.width)/p)+1,u=Math.ceil((l+t.visual.height)/p)+1}else c=Math.ceil(t.visual.width/p),u=Math.ceil(t.visual.height/p),a=c*p-t.visual.width,l=u*p-t.visual.height;return{xOffset:a,yOffset:l,rowCount:u,colCount:c}}allocColumns(t){let n=t.length;let i=e.visuals.BREADBOARD_MID_COLS-t.map((e=>e.colCount)).reduce(((e,t)=>e+t),0);i<=0&&console.log("Not enough breadboard space!");let s=Math.floor(i/(n-1+2)),r=i-s*(n-1),o=Math.floor(r/2),a=(Math.ceil(r/2),1+o);return t.map((e=>{let t=a;return a+=e.colCount+s,t}))}placeParts(t){const n=e.visuals.BREADBOARD_MID_ROWS+2;let i=this.allocColumns(t.map((e=>e.bbFit))),s=t.map((e=>{let t=n-e.bbFit.rowCount,i=Math.floor(t/2);return i>4&&(i=4),i<1&&(i=1),i}));return t.map(((e,t)=>{let n=s[t];return r({startColumnIdx:i[t],startRowIdx:n},e)}))}nextColor(){return(!this.availableWireColors||this.availableWireColors.length<=0)&&(this.availableWireColors=e.visuals.GPIO_WIRE_COLORS.map((e=>e))),this.availableWireColors.pop()}allocWireIRs(s){let o=[],l=s.pins.map(((r,l)=>{let c,u,d=r.target,h=s.startColumnIdx+r.bbFit.partRelativeColIdx,p=e.visuals.getColumnName(h),f=s.startRowIdx+r.bbFit.partRelativeRowIdx;if(f>=7&&(f-=2),a(r.def)){c={type:"breadboard",row:f<5?"j":"a",col:p,style:r.def.style}}else{c={type:"breadboard",row:e.visuals.getRowName(f),col:p,xOffset:r.bbFit.xOffset/s.def.visual.pinDistance,yOffset:r.bbFit.yOffset/s.def.visual.pinDistance,style:r.def.style}}return u="ground"===d?t:"threeVolt"===d?n:"fiveVolt"===d?i:"number"==typeof r.def.colorGroup?o[r.def.colorGroup]?o[r.def.colorGroup]:o[r.def.colorGroup]=this.nextColor():this.nextColor(),{start:c,end:d,color:u,pinIdx:l}}));return r(s,{wires:l})}allocLocation(t,n){if("ground"===t||"threeVolt"===t||"fiveVolt"==t){if("ground"===t&&this.powerUsage.singleGround){return{type:"dalboard",pin:this.getBoardGroundPin()}}if("threeVolt"===t&&this.powerUsage.singleThreeVolt){return{type:"dalboard",pin:this.getBoardThreeVoltPin()}}if("fiveVolt"===t&&this.powerUsage.singleFiveVolt){return{type:"dalboard",pin:this.getBoardFiveVoltPin()}}e.U.assert(!!n.referenceBBPin);let i=this.opts.getBBCoord(n.referenceBBPin),s=[this.availablePowerPins.top.ground[0]||this.availablePowerPins.top.threeVolt[0],this.availablePowerPins.bottom.ground[0]||this.availablePowerPins.bottom.threeVolt[0]].map((e=>this.opts.getBBCoord(e)));s[0]&&s[1]||console.debug(`No more available "${t}" locations!`);let r,o=0==e.visuals.findClosestCoordIdx(i,s);o?"ground"===t?r=this.availablePowerPins.top.ground:"threeVolt"===t?r=this.availablePowerPins.top.threeVolt:"fiveVolt"===t&&(r=this.availablePowerPins.top.fiveVolt):"ground"===t?r=this.availablePowerPins.bottom.ground:"threeVolt"===t?r=this.availablePowerPins.bottom.threeVolt:"fiveVolt"===t&&(r=this.availablePowerPins.bottom.fiveVolt);let a=r.map((e=>this.opts.getBBCoord(e))),l=e.visuals.findClosestCoordIdx(i,a),c=r[l];return o?(this.availablePowerPins.top.ground.splice(l,1),this.availablePowerPins.top.threeVolt.splice(l,1)):(this.availablePowerPins.bottom.ground.splice(l,1),this.availablePowerPins.bottom.threeVolt.splice(l,1)),c}if("breadboard"===t.type)return t;if("MOSI"===t||"MISO"===t||"SCK"===t){return this.opts.boardDef.spiPins||console.debug("No SPI pin mappings found!"),{type:"dalboard",pin:this.opts.boardDef.spiPins[t]}}if("SDA"===t||"SCL"===t){return this.opts.boardDef.i2cPins||console.debug("No I2C pin mappings found!"),{type:"dalboard",pin:this.opts.boardDef.i2cPins[t]}}{e.U.assert("string"==typeof t,"Unknown location type: "+t);let n=t,i=this.opts.boardDef.gpioPinMap[n]||n;return i?{type:"dalboard",pin:i}:void console.debug(`unknown pin location for ${n}`)}}getBoardGroundPin(){let e=this.opts.boardDef.groundPins&&this.opts.boardDef.groundPins[0]||null;return e||console.debug("No available ground pin on board!"),e}getBoardThreeVoltPin(){let e=this.opts.boardDef.threeVoltPins&&this.opts.boardDef.threeVoltPins[0]||null;return e||console.debug("No available 3.3V pin on board!"),e}getBoardFiveVoltPin(){let e=this.opts.boardDef.fiveVoltPins&&this.opts.boardDef.fiveVoltPins[0]||null;return e||console.debug("No available 5V pin on board!"),e}allocPowerWires(e){let s=this.getBoardGroundPin(),r=this.getBoardThreeVoltPin(),o=this.getBoardFiveVoltPin();const a={type:"breadboard",row:"-",col:"26"},l={type:"breadboard",row:"-",col:"1"},c={type:"breadboard",row:"-",col:"50"},u={type:"breadboard",row:"-",col:"25"};let d,h;this.opts.boardDef.attachPowerOnRight?(d=c,h=u):(d=a,h=l);let p=[],f=[],m=[];e.bottomGround&&e.topGround&&p.push({start:this.allocLocation("ground",{referenceBBPin:d}),end:this.allocLocation("ground",{referenceBBPin:h}),color:t}),e.topGround?p.push({start:this.allocLocation("ground",{referenceBBPin:d}),end:{type:"dalboard",pin:s},color:t}):e.bottomGround&&p.push({start:this.allocLocation("ground",{referenceBBPin:h}),end:{type:"dalboard",pin:s},color:t}),e.bottomThreeVolt&&e.bottomGround?f.push({start:this.allocLocation("threeVolt",{referenceBBPin:d}),end:this.allocLocation("threeVolt",{referenceBBPin:h}),color:n}):e.bottomFiveVolt&&e.bottomGround&&m.push({start:this.allocLocation("fiveVolt",{referenceBBPin:d}),end:this.allocLocation("fiveVolt",{referenceBBPin:h}),color:i}),e.topThreeVolt?f.push({start:this.allocLocation("threeVolt",{referenceBBPin:d}),end:{type:"dalboard",pin:r},color:n}):e.bottomThreeVolt&&f.push({start:this.allocLocation("threeVolt",{referenceBBPin:h}),end:{type:"dalboard",pin:r},color:i}),e.topFiveVolt&&!e.topThreeVolt?m.push({start:this.allocLocation("fiveVolt",{referenceBBPin:d}),end:{type:"dalboard",pin:o},color:n}):e.bottomFiveVolt&&!e.bottomThreeVolt&&m.push({start:this.allocLocation("fiveVolt",{referenceBBPin:h}),end:{type:"dalboard",pin:o},color:i});let g=[];p.length>0&&g.push({wireIndices:p.map(((e,t)=>t))});let b=p.length;return f.length>0&&g.push({wireIndices:f.map(((e,t)=>t+b))}),m.length>0&&g.push({wireIndices:f.map(((e,t)=>t+b+f.length))}),{wires:p.concat(f).concat(m),assembly:g}}allocWire(e){const t=[e.start,e.end],n=t.map((e=>"ground"===e||"threeVolt"===e||"fiveVolt"===e));let i=t.map(((e,t)=>n[t]?void 0:this.allocLocation(e,{})));if(i=i.map(((e,n)=>{if(e)return e;const s=i[1-n];return this.allocLocation(t[n],{referenceBBPin:s})})),i[0]&&i[1])return{start:i[0],end:i[1],color:e.color}}allocPart(t){let n=t.pins.filter((e=>a(e.def))).map((n=>{let i=t.startRowIdx+n.bbFit.partRelativeRowIdx;i>=7&&(i-=2);let s=e.visuals.getRowName(i),r=t.startColumnIdx+n.bbFit.partRelativeColIdx;return{type:"breadboard",row:s,col:e.visuals.getColumnName(r)}}));return{name:t.name,visual:t.def.visual,bbFit:t.bbFit,startColumnIdx:t.startColumnIdx,startRowIdx:t.startRowIdx,breadboardConnections:n,params:t.partParams,simulationBehavior:t.def.simulationBehavior}}allocAll(){let e=this.opts.partsList.map((e=>({name:e,def:this.opts.partDefs[e]}))).filter((e=>!!e.def));if(e.length>0){let t=e.map((e=>this.computePartDimensions(e.def,e.name))),n=[];e.forEach(((e,i)=>{let s=t[i],r=this.allocPartIRs(e.def,e.name,s);n=n.concat(r)}));const i=this.placeParts(n).map((e=>this.allocWireIRs(e))),r=i.map((e=>e.wires)).reduce(((e,t)=>e.concat(t)),[]).map((e=>function(e){let t=[e.start,e.end],n=t.map((e=>"ground"===e)),i=t.map((e=>"threeVolt"===e)),r=t.map((e=>"fiveVolt"===e)),o=t.map((e=>function(e){let t=!1;if("string"!=typeof e&&"breadboard"===e.type){let n=e.row;t=0<=["a","b","c","d","e"].indexOf(n)}return t}(e))),a=s(n),l=s(i),c=s(r),u=s(o);return{topGround:a&&!u,topThreeVolt:l&&!u,topFiveVolt:c&&!u,bottomGround:a&&u,bottomThreeVolt:l&&u,bottomFiveVolt:c&&u,singleGround:a,singleThreeVolt:l,singleFiveVolt:c}}(e)));this.powerUsage=function(e){const t=e.reduce(((e,t)=>({topGround:e.topGround||t.topGround,topThreeVolt:e.topThreeVolt||t.topThreeVolt,topFiveVolt:e.topFiveVolt||t.topFiveVolt,bottomGround:e.bottomGround||t.bottomGround,bottomThreeVolt:e.bottomThreeVolt||t.bottomThreeVolt,bottomFiveVolt:e.bottomFiveVolt||t.bottomFiveVolt,singleGround:t.singleGround?null===e.singleGround:e.singleGround,singleThreeVolt:t.singleThreeVolt?null===e.singleThreeVolt:e.singleThreeVolt,singleFiveVolt:t.singleFiveVolt?null===e.singleFiveVolt:e.singleFiveVolt})),{topGround:!1,topThreeVolt:!1,topFiveVolt:!1,bottomGround:!1,bottomThreeVolt:!1,bottomFiveVolt:!1,singleGround:null,singleThreeVolt:null,singleFiveVolt:null});return t.singleGround&&(t.topGround=t.bottomGround=!1),t.singleThreeVolt&&(t.topThreeVolt=t.bottomThreeVolt=!1),t.singleFiveVolt&&(t.topFiveVolt=t.bottomFiveVolt=!1),t}(r);const o=this.allocPowerWires(this.powerUsage),a=i.map(((e,t)=>{const n=this.allocPart(e),i=e.wires.map((e=>this.allocWire(e)));if(i.some((e=>!e)))return;const s=[];e.wires.forEach(((e,t)=>{s[e.pinIdx]=t}));return{part:n,wires:i,assembly:e.def.assembly.map((e=>({part:e.part,wireIndices:(e.pinIndices||[]).map((e=>s[e]))})))}})).filter((e=>!!e)),l=[o].concat(a).filter((e=>e.assembly&&e.assembly.length)),c=!l.some((e=>e.part&&e.part.breadboardConnections&&e.part.breadboardConnections.length>0||e.wires&&e.wires.some((e=>"breadboard"==e.end.type&&"croc"!=e.end.style||"breadboard"==e.start.type&&"croc"!=e.start.style))));return{partsAndWires:l,wires:[],parts:[],hideBreadboard:c}}return{partsAndWires:[],wires:[],parts:[]}}}e.allocateDefinitions=function(e){return new l(e).allocAll()}}(pxsim||(pxsim={})),function(e){!function(e){class t{constructor(e){this.seq=0,this.type=e}}e.Message=t;e.Response=class extends t{constructor(e,t){super("response"),this.request_seq=e.seq,this.command=e.command,t?(this.success=!1,this.message=t):this.success=!0}};class n extends t{constructor(e,t){super("event"),this.event=e,t&&(this.body=t)}}e.Event=n;e.Source=class{constructor(e,t,n=0,i,s){this.name=e,this.path=t,this.sourceReference=n,i&&(this.origin=i),s&&(this.adapterData=s)}};e.Scope=class{constructor(e,t,n=!1){this.name=e,this.variablesReference=t,this.expensive=n}};e.StackFrame=class{constructor(e,t,n,i=0,s=0){this.id=e,this.source=n,this.line=i,this.column=s,this.name=t}};e.Thread=class{constructor(e,t){this.id=e,this.name=t||"Thread #"+e}};e.Variable=class{constructor(e,t,n=0,i,s){this.name=e,this.value=t,this.variablesReference=n,"number"==typeof s&&(this.namedVariables=s),"number"==typeof i&&(this.indexedVariables=i)}};e.Breakpoint=class{constructor(e,t,n,i){this.verified=e;const s=this;"number"==typeof t&&(s.line=t),"number"==typeof n&&(s.column=n),i&&(s.source=i)}};e.Module=class{constructor(e,t){this.id=e,this.name=t}};e.CompletionItem=class{constructor(e,t,n=0){this.label=e,this.start=t,this.length=n}};e.StoppedEvent=class extends n{constructor(e,t,n=null){if(super("stopped"),this.body={reason:e,threadId:t},n){this.body.text=n}}};e.ContinuedEvent=class extends n{constructor(e,t){super("continued"),this.body={threadId:e},"boolean"==typeof t&&(this.body.allThreadsContinued=t)}};e.InitializedEvent=class extends n{constructor(){super("initialized")}};e.TerminatedEvent=class extends n{constructor(e){if(super("terminated"),"boolean"==typeof e){this.body={restart:e}}}};e.OutputEvent=class extends n{constructor(e,t="console",n){super("output"),this.body={category:t,output:e},void 0!==n&&(this.body.data=n)}};e.ThreadEvent=class extends n{constructor(e,t){super("thread"),this.body={reason:e,threadId:t}}};e.BreakpointEvent=class extends n{constructor(e,t){super("breakpoint"),this.body={reason:e,breakpoint:t}}};e.ModuleEvent=class extends n{constructor(e,t){super("module"),this.body={reason:e,module:t}}};class i{constructor(){this._pendingRequests={}}start(e){this._sequence=1,this.host=e,this.host.onData((e=>{if("request"===e.type)this.dispatchRequest(e);else if("response"===e.type){const t=e,n=this._pendingRequests[t.seq];n&&(delete this._pendingRequests[t.seq],n(t))}}))}stop(){this.host&&this.host.close()}sendEvent(e){this.send("event",e)}sendResponse(e){e.seq>0?console.error(`attempt to send more than one response for command ${e.command}`):this.send("response",e)}sendRequest(t,n,i,s){const r={command:t};if(n&&Object.keys(n).length>0&&(r.arguments=n),this.send("request",r),s){this._pendingRequests[r.seq]=s;const t=setTimeout((()=>{clearTimeout(t);const n=this._pendingRequests[r.seq];n&&(delete this._pendingRequests[r.seq],n(new e.Response(r,"timeout")))}),i)}}send(e,t){if(t.type=e,t.seq=this._sequence++,this.host){const e=JSON.stringify(t);this.host.send(e)}}dispatchRequest(e){}}e.ProtocolServer=i;class s extends i{constructor(){super(...arguments),this._debuggerLinesStartAt1=!1,this._debuggerColumnsStartAt1=!1,this._clientLinesStartAt1=!0,this._clientColumnsStartAt1=!0}shutdown(){}dispatchRequest(t){const n=new e.Response(t);try{if("initialize"===t.command){let e=t.arguments;if("boolean"==typeof e.linesStartAt1&&(this._clientLinesStartAt1=e.linesStartAt1),"boolean"==typeof e.columnsStartAt1&&(this._clientColumnsStartAt1=e.columnsStartAt1),"path"!==e.pathFormat)this.sendErrorResponse(n,2018,"debug adapter only supports native paths",null);else{const t=n;t.body={},this.initializeRequest(t,e)}}else"launch"===t.command?this.launchRequest(n,t.arguments):"attach"===t.command?this.attachRequest(n,t.arguments):"disconnect"===t.command?this.disconnectRequest(n,t.arguments):"setBreakpoints"===t.command?this.setBreakPointsRequest(n,t.arguments):"setFunctionBreakpoints"===t.command?this.setFunctionBreakPointsRequest(n,t.arguments):"setExceptionBreakpoints"===t.command?this.setExceptionBreakPointsRequest(n,t.arguments):"configurationDone"===t.command?this.configurationDoneRequest(n,t.arguments):"continue"===t.command?this.continueRequest(n,t.arguments):"next"===t.command?this.nextRequest(n,t.arguments):"stepIn"===t.command?this.stepInRequest(n,t.arguments):"stepOut"===t.command?this.stepOutRequest(n,t.arguments):"stepBack"===t.command?this.stepBackRequest(n,t.arguments):"restartFrame"===t.command?this.restartFrameRequest(n,t.arguments):"goto"===t.command?this.gotoRequest(n,t.arguments):"pause"===t.command?this.pauseRequest(n,t.arguments):"stackTrace"===t.command?this.stackTraceRequest(n,t.arguments):"scopes"===t.command?this.scopesRequest(n,t.arguments):"variables"===t.command?this.variablesRequest(n,t.arguments):"setVariable"===t.command?this.setVariableRequest(n,t.arguments):"source"===t.command?this.sourceRequest(n,t.arguments):"threads"===t.command?this.threadsRequest(n):"evaluate"===t.command?this.evaluateRequest(n,t.arguments):"stepInTargets"===t.command?this.stepInTargetsRequest(n,t.arguments):"gotoTargets"===t.command?this.gotoTargetsRequest(n,t.arguments):"completions"===t.command?this.completionsRequest(n,t.arguments):this.customRequest(t.command,n,t.arguments)}catch(e){this.sendErrorResponse(n,1104,"{_stack}",{_exception:e.message,_stack:e.stack})}}initializeRequest(e,t){e.body.supportsConditionalBreakpoints=!1,e.body.supportsHitConditionalBreakpoints=!1,e.body.supportsFunctionBreakpoints=!1,e.body.supportsConfigurationDoneRequest=!0,e.body.supportsEvaluateForHovers=!1,e.body.supportsStepBack=!1,e.body.supportsSetVariable=!1,e.body.supportsRestartFrame=!1,e.body.supportsStepInTargetsRequest=!1,e.body.supportsGotoTargetsRequest=!1,e.body.supportsCompletionsRequest=!1,this.sendResponse(e)}disconnectRequest(e,t){this.sendResponse(e),this.shutdown()}launchRequest(e,t){this.sendResponse(e)}attachRequest(e,t){this.sendResponse(e)}setBreakPointsRequest(e,t){this.sendResponse(e)}setFunctionBreakPointsRequest(e,t){this.sendResponse(e)}setExceptionBreakPointsRequest(e,t){this.sendResponse(e)}configurationDoneRequest(e,t){this.sendResponse(e)}continueRequest(e,t){this.sendResponse(e)}nextRequest(e,t){this.sendResponse(e)}stepInRequest(e,t){this.sendResponse(e)}stepOutRequest(e,t){this.sendResponse(e)}stepBackRequest(e,t){this.sendResponse(e)}restartFrameRequest(e,t){this.sendResponse(e)}gotoRequest(e,t){this.sendResponse(e)}pauseRequest(e,t){this.sendResponse(e)}sourceRequest(e,t){this.sendResponse(e)}threadsRequest(e){this.sendResponse(e)}stackTraceRequest(e,t){this.sendResponse(e)}scopesRequest(e,t){this.sendResponse(e)}variablesRequest(e,t){this.sendResponse(e)}setVariableRequest(e,t){this.sendResponse(e)}evaluateRequest(e,t){this.sendResponse(e)}stepInTargetsRequest(e,t){this.sendResponse(e)}gotoTargetsRequest(e,t){this.sendResponse(e)}completionsRequest(e,t){this.sendResponse(e)}customRequest(e,t,n){this.sendErrorResponse(t,1014,"unrecognized request",null)}sendErrorResponse(e,t,n,i){let r;"number"==typeof t?(r={id:t,format:n},i&&(r.variables=i),r.showUser=!0):r=t,e.success=!1,s.formatPII(r.format,!0,r.variables),e.body||(e.body={}),e.body.error=r,this.sendResponse(e)}convertClientLineToDebugger(e){return this._debuggerLinesStartAt1?this._clientLinesStartAt1?e:e+1:this._clientLinesStartAt1?e-1:e}convertDebuggerLineToClient(e){return this._debuggerLinesStartAt1?this._clientLinesStartAt1?e:e-1:this._clientLinesStartAt1?e+1:e}convertClientColumnToDebugger(e){return this._debuggerColumnsStartAt1?this._clientColumnsStartAt1?e:e+1:this._clientColumnsStartAt1?e-1:e}convertDebuggerColumnToClient(e){return this._debuggerColumnsStartAt1?this._clientColumnsStartAt1?e:e-1:this._clientColumnsStartAt1?e+1:e}convertClientPathToDebugger(e){return this._clientPathsAreURIs!=this._debuggerPathsAreURIs?this._clientPathsAreURIs?s.uri2path(e):s.path2uri(e):e}convertDebuggerPathToClient(e){return this._debuggerPathsAreURIs!=this._clientPathsAreURIs?this._debuggerPathsAreURIs?s.uri2path(e):s.path2uri(e):e}static path2uri(e){let t=e.replace(/\\/g,"/");return"/"!==t[0]&&(t="/"+t),encodeURI("file://"+t)}static uri2path(e){return e}static formatPII(e,t,n){return e.replace(s._formatPIIRegexp,(function(e,i){return t&&i.length>0&&"_"!==i[0]?e:n[i]&&n.hasOwnProperty(i)?n[i]:e}))}}s._formatPIIRegexp=/{([^}]+)}/g,e.DebugSession=s}(e.protocol||(e.protocol={}))}(pxsim||(pxsim={})),function(e){!function(e){e.injectPolyphils=function(){String.prototype.startsWith||Object.defineProperty(String.prototype,"startsWith",{value:function(e,t){return void 0!==e&&null!=e&&(t=!t||t<0?0:+t,this.substring(t,t+e.length)===e)}}),Array.prototype.fill||Object.defineProperty(Array.prototype,"fill",{writable:!0,enumerable:!0,value:function(e){if(null==this)throw new TypeError("this is null or not defined");let t=Object(this),n=t.length>>>0,i=arguments[1],s=i>>0,r=s<0?Math.max(n+s,0):Math.min(s,n),o=arguments[2],a=void 0===o?n:o>>0,l=a<0?Math.max(n+a,0):Math.min(a,n);for(;r<l;)t[r]=e,r++;return t}}),Array.prototype.find||Object.defineProperty(Array.prototype,"find",{writable:!0,enumerable:!0,value:function(e){if(null==this)throw new TypeError('"this" is null or not defined');let t=Object(this);const n=t.length>>>0;if("function"!=typeof e)throw new TypeError("predicate must be a function");const i=arguments[1];let s=0;for(;s<n;){const n=t[s];if(e.call(i,n,s,t))return n;s++}}}),Uint8Array.prototype.slice||Object.defineProperty(Uint8Array.prototype,"slice",{value:Array.prototype.slice,writable:!0,enumerable:!0}),Uint16Array.prototype.slice||Object.defineProperty(Uint16Array.prototype,"slice",{value:Array.prototype.slice,writable:!0,enumerable:!0}),Uint32Array.prototype.slice||Object.defineProperty(Uint32Array.prototype,"slice",{value:Array.prototype.slice,writable:!0,enumerable:!0}),Uint8Array.prototype.fill||Object.defineProperty(Uint8Array.prototype,"fill",{value:Array.prototype.fill,writable:!0,enumerable:!0}),Uint16Array.prototype.fill||Object.defineProperty(Uint16Array.prototype,"fill",{value:Array.prototype.fill,writable:!0,enumerable:!0}),Uint32Array.prototype.fill||Object.defineProperty(Uint32Array.prototype,"fill",{value:Array.prototype.fill,writable:!0,enumerable:!0}),Uint8Array.prototype.some||Object.defineProperty(Uint8Array.prototype,"some",{value:Array.prototype.some,writable:!0,enumerable:!0}),Uint16Array.prototype.some||Object.defineProperty(Uint16Array.prototype,"some",{value:Array.prototype.some,writable:!0,enumerable:!0}),Uint32Array.prototype.some||Object.defineProperty(Uint32Array.prototype,"some",{value:Array.prototype.some,writable:!0,enumerable:!0}),Uint8Array.prototype.reverse||Object.defineProperty(Uint8Array.prototype,"reverse",{value:Array.prototype.reverse,writable:!0,enumerable:!0}),Uint16Array.prototype.reverse||Object.defineProperty(Uint16Array.prototype,"reverse",{value:Array.prototype.reverse,writable:!0,enumerable:!0}),Uint32Array.prototype.reverse||Object.defineProperty(Uint32Array.prototype,"reverse",{value:Array.prototype.reverse,writable:!0,enumerable:!0}),Math.imul||(Math.imul=function(e,t){const n=65535&e,i=65535&t;return n*i+((e>>>16&65535)*i+n*(t>>>16&65535)<<16>>>0)|0}),"function"!=typeof Object.assign&&Object.defineProperty(Object,"assign",{value:function(e,t){"use strict";if(null==e)throw new TypeError("Cannot convert undefined or null to object");let n=Object(e);for(let e=1;e<arguments.length;e++){let t=arguments[e];if(null!=t)for(let e in t)Object.prototype.hasOwnProperty.call(t,e)&&(n[e]=t[e])}return n},writable:!0,configurable:!0}),Promise.prototype.finally||(Promise.prototype.finally=Promise.prototype.finally||{finally(e){const t=t=>Promise.resolve(e()).then(t);return this.then((e=>t((()=>e))),(e=>t((()=>Promise.reject(e)))))}}.finally)};function t(e){e=e.replace(/\\/g,"/");const t=[];return e.split("/").forEach((e=>{".."===e&&t.length?t.pop():e&&"."!==e&&t.push(e)})),t}e.Lazy=class{constructor(e){this._func=e,this._evaluated=!1}get value(){return this._evaluated||(this._value=this._func(),this._evaluated=!0),this._value}},e.getNormalizedParts=t,e.normalizePath=function(e){return t(e).join("/")},e.relativePath=function(e,n){const i=t(e),s=t(n);let r=0;for(;i[r]===s[r]&&(r++,r!==i.length&&r!==s.length););const o=i.slice(r),a=s.slice(r);for(let e=0;e<o.length;e++)a.unshift("..");return a.join("/")},e.pathJoin=function(...e){let t="";return e.forEach((e=>{e.replace(/\\/g,"/"),e.lastIndexOf("/")===e.length-1&&(e=e.slice(0,e.length-1)),t+="/"+e})),t},e.toArray=function(e){if(Array.isArray(e))return e;let t=[];for(let n=0;n<e.length;++n)t.push(e[n]);return t}}(e.util||(e.util={}))}(pxsim||(pxsim={})),function(e){e.getWarningMessage=function(t){let n={type:"debugger",subtype:"warning",breakpointIds:[],message:t},i=e.runtime.currFrame;for(;null!=i;)n.breakpointIds.push(i.lastBrkId),i=i.parent;return n};function t(t,n){switch(typeof t){case"string":case"number":case"boolean":return t;case"function":return{text:"(function)",type:"function"};case"undefined":return null;case"object":if(!t)return null;if(t instanceof e.RefObject){n&&(n[t.id]=t);let i=e.RefObject.toDebugString(t),s=i.startsWith("[")?"array":i;return{id:t.id,preview:i,hasFields:null!==t.fields||i.startsWith("["),type:s}}return t._width&&t._height?{text:t._width+"x"+t._height,type:"image"}:{text:"(object)",type:"object"};default:throw new Error}}function n(n,s,r,o,a=!1){return function(n,r){const l={};for(let e of Object.keys(n))/^__/.test(e)||!/___\d+$/.test(e)||o&&-1===o.indexOf(e)||(l[e]=t(n[e],s));if(n.fields&&r)for(let e of r)e=e.substring(e.lastIndexOf(".")+1),l[e]=t(i(n.vtable.iface[e],n),s);if(n.fields)for(let e of Object.keys(n.fields).filter((e=>a||!e.startsWith("_"))))l[e]=t(n.fields[e],s);else if(n instanceof e.RefMap)for(const e of n.data)l[e.key]=t(e.val,s);else Array.isArray(n.data)?n.data.forEach(((e,n)=>{l[n]=t(e,s)})):void 0!==n._width&&void 0!==n._height&&(l.width=n._width,l.height=n._height,a&&void 0!==n._bpp&&(l.isMono=1===n._bpp));return l}(n,r)}function i(e,t){let n={pc:0,arg0:t,fn:e,parent:{}};for(;n.fn;)n=n.fn(n);return n.retval}function s(e,i){let s=e.fn?e.fn.info:null;if(s){let r={thisParam:t(e.argL,i),params:[]};if(s.argumentNames){const n=s.argumentNames;r.params=n.map(((n,s)=>({name:n,value:t(e["arg"+s],i)})))}return{locals:n(e,i),funcInfo:s,breakpointId:e.lastBrkId,callLocationId:e.callLocIdx,arguments:r}}}e.BreakpointMap=class{constructor(e){this.fileMap={},this.idMap={},e.forEach((e=>{const[t,n]=e;this.fileMap[n.source.path]||(this.fileMap[n.source.path]=[]),this.fileMap[n.source.path].push(e),this.idMap[t]=n}));for(const e in this.fileMap){const t=this.fileMap[e];this.fileMap[e]=t.sort((([,e],[,t])=>e.line===t.line?t.endLine===e.endLine?e.column-t.column:t.endLine-e.endLine:e.line-t.line))}}getById(e){return this.idMap[e]}verifyBreakpoint(e,t){const n=this.fileMap[e];let i;if(n)for(const[e,s]of n)s.line<=t.line&&s.endLine>=t.line&&(i=[e,s]);return i?(i[1].verified=!0,i):[-1,{verified:!1}]}},e.dumpHeap=n,e.injectEnvironmentGlobals=function(n,i){const s=e.runtime.environmentGlobals;if(!Object.keys(s).length)return;const r=n.environmentGlobals={};Object.keys(s).forEach((n=>r[n]=t(e.runtime.environmentGlobals[n],i)))},e.getBreakpointMsg=function(t,i,r){const o={},a={type:"debugger",subtype:"breakpoint",breakpointId:i,globals:n(e.runtime.globals,o,void 0,r),stackframes:[]};for(;null!=t;){let e=s(t,o);e&&a.stackframes.push(e),t=t.parent}return{msg:a,heap:o}};class r extends e.protocol.DebugSession{constructor(t){super();let n={onDebuggerBreakpoint:e=>this.onDebuggerBreakpoint(e),onDebuggerWarning:e=>this.onDebuggerWarning(e),onDebuggerResume:()=>this.onDebuggerResume(),onStateChanged:e=>this.onStateChanged(e)};this.driver=new e.SimulatorDriver(t,n)}runCode(t,n,i,s,r){this.breakpoints=s,this.projectDir&&this.fixBreakpoints(),this.sendEvent(new e.protocol.InitializedEvent),this.driver.run(t,{parts:n,fnArgs:i,boardDefinition:r})}stopSimulator(e=!1){this.driver.stop(e)}initializeRequest(e,t){e.body.supportsConditionalBreakpoints=!1,e.body.supportsHitConditionalBreakpoints=!1,e.body.supportsFunctionBreakpoints=!1,e.body.supportsEvaluateForHovers=!1,e.body.supportsStepBack=!1,e.body.supportsSetVariable=!1,e.body.supportsRestartFrame=!1,e.body.supportsStepInTargetsRequest=!1,e.body.supportsGotoTargetsRequest=!1,e.body.supportsCompletionsRequest=!1,e.body.supportsConfigurationDoneRequest=!0,this.sendResponse(e)}disconnectRequest(e,t){this.sendResponse(e),this.shutdown()}launchRequest(t,n){this.projectDir||(this.projectDir=e.util.normalizePath(n.projectDir),this.breakpoints&&this.fixBreakpoints()),this.sendResponse(t)}setBreakPointsRequest(t,n){t.body={breakpoints:[]};const i=[];n.breakpoints.forEach((s=>{if(this.breakpoints){const[r,o]=this.breakpoints.verifyBreakpoint(e.util.relativePath(this.projectDir,n.source.path),s);t.body.breakpoints.push(o),o.verified&&i.push(r)}else t.body.breakpoints.push({verified:!1})})),this.driver.setBreakpoints(i),this.sendResponse(t)}continueRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.Resume),this.sendResponse(t)}nextRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.StepOver),this.sendResponse(t)}stepInRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.StepInto),this.sendResponse(t)}stepOutRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.StepOut),this.sendResponse(t)}pauseRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.Pause),this.sendResponse(t)}threadsRequest(e){e.body={threads:[{id:r.THREAD_ID,name:"main"}]},this.sendResponse(e)}stackTraceRequest(e,t){if(this.lastBreak){const t=this.state.getFrames();e.body={stackFrames:t}}this.sendResponse(e)}scopesRequest(e,t){this.state&&(e.body={scopes:this.state.getScopes(t.frameId)}),this.sendResponse(e)}variablesRequest(e,t){this.state&&(e.body={variables:this.state.getVariables(t.variablesReference)}),this.sendResponse(e)}onDebuggerBreakpoint(t){if(this.lastBreak=t,this.state=new o(this.lastBreak,this.breakpoints,this.projectDir),t.exceptionMessage){const n=t.exceptionMessage.replace(/___\d+/g,"");this.sendEvent(new e.protocol.StoppedEvent("exception",r.THREAD_ID,n))}else this.sendEvent(new e.protocol.StoppedEvent("breakpoint",r.THREAD_ID))}onDebuggerWarning(e){}onDebuggerResume(){this.sendEvent(new e.protocol.ContinuedEvent(r.THREAD_ID,!0))}onStateChanged(t){switch(t){case e.SimulatorState.Paused:break;case e.SimulatorState.Running:this.sendEvent(new e.protocol.ContinuedEvent(r.THREAD_ID,!0));break;case e.SimulatorState.Stopped:this.sendEvent(new e.protocol.TerminatedEvent)}}fixBreakpoints(){for(const t in this.breakpoints.idMap){const n=this.breakpoints.idMap[t];n.source.path=e.util.pathJoin(this.projectDir,n.source.path),n.line=this.convertDebuggerLineToClient(n.line),n.endLine=this.convertDebuggerLineToClient(n.endLine),n.column=this.convertDebuggerColumnToClient(n.column),n.endColumn=this.convertDebuggerColumnToClient(n.endColumn)}}}r.THREAD_ID=1,e.SimDebugSession=r;class o{constructor(e,t,n){this._message=e,this._map=t,this._dir=n,this._currentId=1,this._frames={},this._vars={};const i=this.nextId();this._vars[i]=this.getVariableValues(this._message.globals),this._globalScope={name:"Globals",variablesReference:i,expensive:!1}}getFrames(){return this._message.stackframes.map(((e,t)=>{const n=this._map.getById(e.breakpointId);if(n)return this._frames[e.breakpointId]=e,{id:e.breakpointId,name:e.funcInfo?e.funcInfo.functionName:0===t?"main":"anonymous",line:n.line,column:n.column,endLine:n.endLine,endColumn:n.endLine,source:n.source}})).filter((e=>!!e))}getScopes(e){const t=this._frames[e];if(t){const e=this.nextId();return this._vars[e]=this.getVariableValues(t.locals),[{name:"Locals",variablesReference:e,expensive:!1},this._globalScope]}return[this._globalScope]}getVariables(e){const t=this._vars[e];return t&&t.value||[]}getVariableValues(t){return new e.util.Lazy((()=>{const e=[];for(const n in t){const i=t[n];let s,r=0;null===i?s="null":void 0===i?s="undefined":"object"==typeof i?(s="(object)",r=this.nextId(),this._vars[r]=this.getVariableValues(i)):s=i.toString();const o=n.substr(0,n.lastIndexOf("___"));e.push({name:o,value:s,variablesReference:r})}return e}))}nextId(){return this._currentId++}}}(pxsim||(pxsim={})),function(e){let t,n;function i(e=0){function t(){try{window.print()}catch(e){}}e?setTimeout(t,e):t()}function s(e,t){r({type:"pxtsim",action:"event",tick:e,data:t})}function r(e){"undefined"!=typeof window&&window.parent&&window.parent!==window&&window.parent.postMessage(e,"*")}function o(){setInterval((()=>{e.Runtime.postMessage({type:"simulator",command:"reload"})}),3e3)}!function(e){let t;!function(e){e[e.Player=0]="Player",e[e.Reaction=1]="Reaction"}(t=e.IconType||(e.IconType={}))}(t=e.multiplayer||(e.multiplayer={})),e.print=i,function(t){function n(t){t.origin;let n=t.data||{},o=n.type;if(o)switch(o){case"run":l(n);break;case"instructions":e.instructions.renderInstructions(n);break;case"stop":a();break;case"mute":c(n.mute);break;case"stopsound":e.AudioContextManager.stopAll();break;case"print":i();break;case"recorder":!function(e){if(!r)return;switch(e.action){case"start":r.startRecording(e.width);break;case"stop":r.stopRecording()}}(n);break;case"screenshot":e.Runtime.postScreenshotAsync(n);break;case"custom":e.handleCustomMessage&&e.handleCustomMessage(n);break;case"pxteditor":break;case"debugger":r&&r.handleDebuggerMsg(n);break;case"simulator":let t=n;switch(t.command){case"focus":s("simulator.focus",{timestamp:t.timestamp});break;case"blur":s("simulator.blur",{timestamp:t.timestamp})}default:!function(e){if(!r||r.dead)return;r.board.receiveMessage(e)}(n)}}let r;function a(){r&&(r.kill(),r.board&&r.board.kill())}function l(t){a(),t.mute&&c(t.mute),t.localizedStrings&&e.localization.setLocalizedStrings(t.localizedStrings);const n=new e.Runtime(t);r=n,n.board.initAsync(t).then((()=>{n===r&&n.run((t=>{e.dumpLivePointers(),e.Runtime.postMessage({type:"toplevelcodefinished"})}))}))}function c(t){e.AudioContextManager.mute(t)}t.start=function(){window.addEventListener("message",n,!1),t.frameid=window.location.hash.slice(1),function(){if("serviceWorker"in navigator&&-1!==window.location.href.indexOf("---simulator")&&!e.U.isLocalHost()){const e=window.location.pathname,t=e.substring(1,e.indexOf("---"));navigator.serviceWorker.controller&&navigator.serviceWorker.addEventListener("message",(e=>{const n=e.data;n&&"serviceworker"===n.type&&"activated"===n.state&&n.ref===t&&o()}));const n=window.location.href.replace(/---simulator.*$/,"---simserviceworker");navigator.serviceWorker.register(n).then((function(e){console.log("Simulator ServiceWorker registration successful with scope: ",e.scope)}),(function(e){console.log("Simulator ServiceWorker registration failed: ",e)}))}}(),e.Runtime.postMessage({type:"ready",frameid:t.frameid})},t.stop=a,t.run=l}(n=e.Embed||(e.Embed={})),e.tickEvent=s,e.reportError=function(e,t,n){r({type:"pxtsim",action:"event",tick:"error",category:e,message:t,data:n})},e.reload=o}(pxsim||(pxsim={})),pxsim.util.injectPolyphils(),"undefined"!=typeof window&&window.addEventListener("load",(function(e){pxsim.Embed.start()})),function(e){!function(t){const n=e=>`${e}x`,i=.95,[s,r]=[816*i,1056*i],o=s-86.4,a=r-86.4,[l,c]=[1,1],u=24,d=o/c-48*c,h=`\n .instr-panel {\n margin: 20px;\n padding: 24px;\n border-width: 4px;\n border-color: gray;\n border-style: solid;\n border-radius: 20px;\n display: inline-block;\n width: ${d}px;\n height: ${a/l-48*l}px;\n position: relative;\n overflow: hidden;\n page-break-inside: avoid;\n }\n .board-svg {\n margin: 0 auto;\n display: block;\n position: absolute;\n bottom: 24px;\n left: ${(d-465)/2+u}px;\n }\n .panel-num-outer {\n position: absolute;\n left: -4px;\n top: -4px;\n width: 120px;\n height: 120px;\n border-width: 4px;\n border-style: solid;\n border-color: gray;\n border-radius: 20px 0 20px 0;\n }\n .panel-num {\n margin: 10px 0;\n text-align: center;\n font-size: 80px;\n }\n .cmp-div {\n display: inline-block;\n }\n .reqs-div {\n margin-left: 144px;\n margin-top: 5px;\n }\n .partslist-wire,\n .partslist-cmp {\n margin: 10px;\n }\n .partslist-wire {\n display: inline-block;\n }\n `;function p(t,n){let i=document.createElementNS("http://www.w3.org/2000/svg","svg"),s={l:0,t:0,w:0,h:0},r=document.createElementNS("http://www.w3.org/2000/svg","svg");i.appendChild(r),r.appendChild(t.el);let o={viewBox:`${t.x} ${t.y} ${t.w} ${t.h}`,preserveAspectRatio:"xMidYMid"};s.w=t.w,s.h=t.h;let a=e=>{s.h*=e,s.w*=e,o.width=s.w,o.height=s.h};n.cmpScale&&a(n.cmpScale),n.cmpWidth&&n.cmpWidth<s.w?a(n.cmpWidth/s.w):n.cmpHeight&&n.cmpHeight<s.h&&a(n.cmpHeight/s.h),e.svg.hydrate(r,o);let l=s.l,c=s.t,u=s.w,d=s.h,h=e=>{if(e<s.l){let t=s.l-e;s.l=e,s.w+=t}},p=e=>{let t=s.l+s.w;if(t<e){let n=e-t;s.w+=n}},f=e=>{if(e<s.t){let t=s.t-e;s.t=e,s.h+=t}},m=e=>{let t=s.t+s.h;if(t<e){let n=e-t;s.h+=n}},[g,b]=[-.3,.3];const y=[1.4,1];if(n&&n.top){let t=n.topSize,s=t/y[0],r=t/y[1],[o,a]=[l+u/2,c-3-r/2],d=e.visuals.mkTxt(o,a,t,0,n.top,g,b);e.U.addClass(d,"cmp-lbl"),i.appendChild(d);let m=s*n.top.length;f(a-r/2),h(o-m/2),p(o+m/2)}if(n&&n.bot){let t=n.botSize,s=t/y[0],r=t/y[1],[o,a]=[l+u/2,c+d+3+r/2],f=e.visuals.mkTxt(o,a,t,0,n.bot,g,b);e.U.addClass(f,"cmp-lbl"),i.appendChild(f);let v=s*n.bot.length;m(a+r/2),h(o-v/2),p(o+v/2)}if(n&&n.right){let t=n.rightSize,s=t/y[1],r=t/y[0]*n.right.length,[o,a]=[l+u+5+r/2,c+d/2],h=e.visuals.mkTxt(o,a,t,0,n.right,g,b);e.U.addClass(h,"cmp-lbl"),i.appendChild(h),f(a-s/2),p(o+r/2),m(a+s/2)}if(n&&n.left){let t=n.leftSize,s=t/y[1],r=t/y[0]*n.left.length,[o,a]=[l-5-r/2,c+d/2],u=e.visuals.mkTxt(o,a,t,0,n.left,g,b);e.U.addClass(u,"cmp-lbl"),i.appendChild(u),f(a-s/2),h(o-r/2),m(a+s/2)}let v={viewBox:`${s.l} ${s.t} ${s.w} ${s.h}`,width:1.7*s.w,height:1.7*s.h,preserveAspectRatio:"xMidYMid"};e.svg.hydrate(i,v);let w=document.createElement("div");return w.appendChild(i),w}function f(t,n){let i,s=e.runtime.board;if("wire"==t)i=e.visuals.mkWirePart([0,0],n.wireClr||"red",n.crocClips);else{let n=t;if("string"==typeof n.builtIn){i=(0,s.builtinPartVisuals[n.builtIn])([0,0])}else i=e.visuals.mkGenericPartSVG(n)}return p(i,n)}function m(t,n,i=!1){const s={state:e.runtime.board,boardDef:t.boardDef,forceBreadboardLayout:!0,forceBreadboardRender:t.allAlloc.requiresBreadboard,partDefs:t.cmpDefs,maxWidth:`${n}px`,fnArgs:t.fnArgs,wireframe:i,partsList:[]};let r=new e.visuals.BoardHost(e.visuals.mkBoardView({visual:s.boardDef.visual,boardDef:s.boardDef,wireframe:s.wireframe}),s),o=r.getView();return e.U.addClass(o,"board-svg"),r}function g(){let t=document.createElement("div");return e.U.addClass(t,"instr-panel"),t}function b(t){let i=g();var s;let r=p((s=t.boardDef,e.visuals.mkBoardView({visual:s.visual,boardDef:s}).getView()),{left:n(1),leftSize:30,cmpScale:.17});i.appendChild(r);let o=p(new e.visuals.Breadboard({}).getSVGAndSize(),{left:n(1),leftSize:30,cmpScale:.25});return i.appendChild(o),t.allCmps.forEach((t=>{let s=1;"buttonpair"===t.visual.builtIn&&(s=2);let r=f(t.visual,{left:n(s),leftSize:30,cmpScale:.3});e.U.addClass(r,"partslist-cmp"),i.appendChild(r)})),t.allWireColors.forEach((s=>{let r=t.colorToWires[s].length,o=t.boardDef.pinStyles[s]||"female",a=f("wire",{left:n(r),leftSize:20,wireClr:s,cmpScale:.23,crocClips:"croc"==o});e.U.addClass(a,"partslist-wire"),i.appendChild(a)})),i}function y(t,n){let i=g(),s=m(n,465,!0);!function(t,n,i){let s=t.getView();n>0&&e.U.addClass(s,"grayed");for(let s=0;s<=n;s++){let r=i.stepToCmps[s];r&&r.forEach((i=>{let r=t.addPart(i);s===n&&(i.breadboardConnections.forEach((e=>t.highlightBreadboardPin(e))),e.U.addClass(r.element,"notgrayed"))}));let o=i.stepToWires[s];o&&o.forEach((e=>{let i=t.addWire(e);i&&s===n&&("breadboard"==e.start.type?t.highlightBreadboardPin(e.start):t.highlightBoardPin(e.start.pin),"breadboard"==e.end.type?t.highlightBreadboardPin(e.end):t.highlightBoardPin(e.end.pin),t.highlightWire(i))}))}}(s,t,n),i.appendChild(s.getView());let r=document.createElement("div");e.U.addClass(r,"panel-num-outer"),e.U.addClass(r,"noselect"),i.appendChild(r);let o=document.createElement("div");e.U.addClass(o,"panel-num"),o.textContent=t+1+"",r.appendChild(o);let a=document.createElement("div");e.U.addClass(a,"reqs-div"),i.appendChild(a);let l=n.stepToWires[t]||[],c=e=>{if("breadboard"===e.type){let{row:t,col:n}=e;return`(${t},${n})`}return e.pin};return l.forEach((t=>{let i=!1;"dalboard"==t.end.type&&(i="croc"==n.boardDef.pinStyles[t.end.pin]);let s=f("wire",{top:c(t.end),topSize:10,bot:c(t.start),botSize:10,wireClr:t.color,cmpHeight:40,crocClips:i});e.U.addClass(s,"cmp-div"),a.appendChild(s)})),(n.stepToCmps[t]||[]).forEach((t=>{let n;n="buttonpair"===t.visual.builtIn?[t.breadboardConnections[0],t.breadboardConnections[2]]:[t.breadboardConnections[0]],n.forEach(((n,i)=>{let s;if(n){let{row:e,col:t}=n;s=`(${e},${t})`}else s="";let r=1.5;"buttonpair"===t.visual.builtIn&&(r*=.5);let o=f(t.visual,{top:s,topSize:10,cmpHeight:50,cmpScale:r});e.U.addClass(o,"cmp-div"),a.appendChild(o)}))})),i}function v(t,n){n.boardDef.pinStyles||(n.boardDef.pinStyles={}),n.configData&&e.setConfigData(n.configData.cfg,n.configData.cfgKey);const i={type:"run",code:"",boardDefinition:n.boardDef,partDefinitions:n.partDefinitions};e.runtime=new e.Runtime(i),e.runtime.board=null,e.initCurrentRuntime(i);let s=document.createElement("style");s.textContent+=h,document.head.appendChild(s);const r=n.partDefinitions;let o=new e.visuals.Breadboard({}),a=function(t){let n=e.allocateDefinitions(t),i=[],s=[],r=1;n.partsAndWires.forEach((e=>{let t=e.part,n=e.wires;e.assembly.forEach(((e,o)=>{e.part&&t&&(s[r+o]=[t]),e.wireIndices&&e.wireIndices.length>0&&n&&(i[r+o]=e.wireIndices.map((e=>n[e])))})),r+=e.assembly.length}));let o=r-1,a=n.partsAndWires.map((e=>e.part)).filter((e=>!!e)),l=n.partsAndWires.map((e=>e.wires||[])).reduce(((e,t)=>e.concat(t)),[]),c={},u=[];return l.forEach((e=>{c[e.color]||(c[e.color]=[],u.push(e.color)),c[e.color].push(e)})),{boardDef:t.boardDef,cmpDefs:t.partDefs,fnArgs:t.fnArgs,allAlloc:n,stepToWires:i,stepToCmps:s,allWires:l,allCmps:a,lastStep:o,colorToWires:c,allWireColors:u}}({boardDef:n.boardDef,partDefs:r,partsList:n.parts,fnArgs:n.fnArgs,getBBCoord:o.getCoord.bind(o)});a.allAlloc.requiresBreadboard=!0;!function(e){let t=document.getElementById("front-panel"),n=m(e,400,!1);n.addAll(e.allAlloc),t.appendChild(n.getView())}(a);let l=b(a);t.appendChild(l);for(let e=0;e<=a.lastStep;e++){let n=y(e,a);t.appendChild(n)}n.print&&e.print(2e3)}t.renderParts=v,t.renderInstructions=function(e){document.getElementById("proj-title").innerText=e.options.name||"",v(document.body,e.options)}}(e.instructions||(e.instructions={}))}(pxsim||(pxsim={})),function(e){function t(e,t="sim: check failed"){if(!e)throw new Error(t)}e.quiet=!1,e.check=t,e.title="";let n,i,s,r,o,a={},l={};e.getConfig=function(e){return l.hasOwnProperty(e+"")?l[e+""]:null},e.getConfigKey=function(e){return a.hasOwnProperty(e)?a[e]:null},e.getAllConfigKeys=function(){return Object.keys(a)},e.setConfigKey=function(e,t){a[e]=t},e.setConfig=function(e,t){l[e]=t},e.setConfigData=function(e,t){l=e,a=t},e.getConfigData=function(){return{cfg:l,cfgKey:a}},e.setTitle=function(t){e.title=t};class c{constructor(){e.runtime?this.id=e.runtime.registerLiveObject(this):this.id=0}destroy(){}scan(t){throw e.U.userError("scan not implemented")}gcKey(){throw e.U.userError("gcKey not implemented")}gcSize(){throw e.U.userError("gcSize not implemented")}gcIsStatic(){return!1}print(){e.runtime&&e.runtime.refCountingDebug&&console.log(`RefObject id:${this.id}`)}toDebugString(){return"(object)"}static toAny(e){return e&&e.toAny?e.toAny():e}static toDebugString(e){return null===e?"null":void 0===e?"undefined;":e.vtable&&e.vtable.name?"_Map"===e.vtable.name&&e instanceof f?"(object)":e.vtable.name:e.toDebugString?e.toDebugString():"string"==typeof e?JSON.stringify(e):e.toString()}}e.RefObject=c;class u{constructor(e,t,n){this.func=e,this.caps=t,this.args=n}}e.FnWrapper=u;class d extends c{constructor(){super(...arguments),this.fields={}}scan(e){for(let t of Object.keys(this.fields))e(t,this.fields[t])}gcKey(){return this.vtable.name}gcSize(){return this.vtable.numFields+1}destroy(){this.fields=null,this.vtable=null}print(){e.runtime&&e.runtime.refCountingDebug&&console.log(`RefRecord id:${this.id} (${this.vtable.name})`)}}e.RefRecord=d;class h extends c{constructor(){super(...arguments),this.fields=[]}scan(e){for(let t=0;t<this.fields.length;++t)e("_cap"+t,this.fields[t])}gcKey(){return e.functionName(this.func)}gcSize(){return this.fields.length+3}isRef(e){return t(0<=e&&e<this.fields.length),e<this.len}ldclo(e){return t(0<=(e>>=2)&&e<this.fields.length),this.fields[e]}destroy(){this.fields=null,this.func=null}print(){e.runtime&&e.runtime.refCountingDebug&&console.log(`RefAction id:${this.id} len:${this.fields.length}`)}}e.RefAction=h,function(t){t.seedAddRandom=function(e){},t.mkAction=function(e,t){let n=new h;n.len=e,n.func=t;for(let t=0;t<e;++t)n.fields.push(null);return n},t.runAction=function(t,n){let i=e.getResume();i(t instanceof h?new u(t.func,t.fields,n):new u(t,null,n))};let n={};t.dumpPerfCounters=function(){if(!e.runtime||!e.runtime.perfCounters)return;let t="calls,us,name\n";for(let n of e.runtime.perfCounters){n.lastFew.sort();const e=n.lastFew[n.lastFew.length>>1];t+=`${n.numstops},${n.value},${n.name},${e}\n`}!function(e){let t="";const i=(e,n)=>{t+=e.length>=n?e:(" "+e).slice(-n)},s=e=>i(""+Math.round(e),6),r=(e,n)=>{i(Math.round(n)+"",8),t+=" /",s(e),t+=" =",s(n/e)};for(let i of e.split(/\n/)){if(!i)continue;if(!/^\d/.test(i))continue;const e=i.split(/,/);let l=n[e[2]];l||(n[e[2]]=l={stops:0,us:0,meds:[]}),o=e[2],a=25,t+=o.length>=a?o:(o+" ").slice(0,a);const c=parseInt(e[0]),u=parseInt(e[1]);r(c,u),t+=" |",r(c-l.stops,u-l.us),t+=" ~";const d=parseInt(e[3]);s(d),l.meds.length>10&&l.meds.shift(),l.meds.push(d);const h=l.meds.slice();h.sort(((e,t)=>e-t));const p=h[h.length>>1];t+=" ~~",s(p),l.stops=c,l.us=u,t+="\n"}var o,a;console.log(t)}(t)}}(n=e.pxtcore||(e.pxtcore={}));class p extends c{constructor(){super(...arguments),this.v=void 0}scan(e){e("*",this.v)}gcKey(){return"LOC"}gcSize(){return 2}destroy(){}print(){e.runtime&&e.runtime.refCountingDebug&&console.log(`RefRefLocal id:${this.id} v:${this.v}`)}}e.RefRefLocal=p;class f extends c{constructor(){super(...arguments),this.vtable=e.mkMapVTable(),this.data=[]}scan(e){for(let t of this.data)e(t.key,t.val)}gcKey(){return"{...}"}gcSize(){return 2*this.data.length+4}findIdx(e){e+="";for(let t=0;t<this.data.length;++t)if(this.data[t].key==e)return t;return-1}destroy(){super.destroy();for(let e=0;e<this.data.length;++e)this.data[e].val=0;this.data=[]}print(){e.runtime&&e.runtime.refCountingDebug&&console.log(`RefMap id:${this.id} size:${this.data.length}`)}toAny(){const e={};return this.data.forEach((t=>{e[t.key]=c.toAny(t.val)})),e}}function m(){e.runtime&&e.runtime.dumpLivePointers()}e.RefMap=f,e.dumpLivePointers=m,function(e){e.toString=function(e){return null===e?"null":void 0===e?"undefined":e.toString()},e.toBoolDecr=function(e){return!!e},e.toBool=function(e){return!!e}}(i=e.numops||(e.numops={})),function(e){e.toInt=function(e){return 0|e},e.toFloat=function(e){return e},e.ignore=function(e){return e}}(s=e.langsupp||(e.langsupp={})),function(t){t.ptrOfLiteral=function(e){return e},t.debugMemLeaks=function(){m()},t.templateHash=function(){return 0},t.programHash=function(){return 0},t.programName=function(){return e.title},t.programSize=function(){return 0},t.afterProgramPage=function(){return 0},t.getConfig=function(t,n){let i=e.getConfig(t);return null==i?n:i},t.toInt=function(e){return e>>0},t.toUInt=function(e){return e>>>0},t.toDouble=function(e){return e},t.toFloat=function(e){return e},t.fromInt=function(e){return e},t.fromUInt=function(e){return e},t.fromDouble=function(e){return e},t.fromFloat=function(e){return e},t.fromBool=function(e){return!!e}}(n=e.pxtcore||(e.pxtcore={})),function(n){function i(e,t){if(t+="",e instanceof d){return e.fields[t]}let n=e.findIdx(t);if(!(n<0))return e.data[n].val}function s(e,t,n){if(t+="",e instanceof d){return void(e.fields[t]=n)}let i=e.findIdx(t);i<0?e.data.push({key:t,val:n}):e.data[i].val=n}n.toInt8=function(e){return(255&e)<<24>>24},n.toInt16=function(e){return(65535&e)<<16>>16},n.toInt32=function(e){return 0|e},n.toUInt32=function(e){return e>>>0},n.toUInt8=function(e){return 255&e},n.toUInt16=function(e){return 65535&e},n.nullFix=function(e){return null==e||!1===e?0:!0===e?1:e},n.nullCheck=function(t){null==t&&e.U.userError("Dereferencing null/undefined value.")},n.panic=function(t){e.U.userError("PANIC! Code "+t)},n.stringToBool=function(e){return e?1:0},n.ptrToBool=function(e){return e?1:0},n.emptyToNull=function(e){return""==e?0:e},n.ldlocRef=function(e){return e.v},n.stlocRef=function(e,t){e.v=t},n.mklocRef=function(){return new p},n.stclo=function(e,n,i){return t(0<=n&&n<e.fields.length),t(null===e.fields[n]),e.fields[n]=i,e},n.runtimeWarning=function(t){e.Runtime.postMessage(e.getWarningMessage(t))},n.mkMap=function(){return new f},n.mapGet=function(e,t){return i(e,n.mapKeyNames[t])},n.mapSet=function(e,t,i){return s(e,n.mapKeyNames[t],i)},n.mapGetByString=i,n.mapDeleteByString=function(e,t){e instanceof f||n.panic(923);let i=e.findIdx(t);return i>=0&&e.data.splice(i,1),!0},n.mapSetGeneric=s,n.mapGetGeneric=i,n.mapSetByString=s,n.keysOf=function(t){let n=new e.RefCollection;if(t instanceof f)for(let e of t.data)n.push(e.key);return n}}(r=e.pxtrt||(e.pxtrt={})),function(e){e.mkClassInstance=function(e){t(!!e.methods);let n=new d;return n.vtable=e,n},e.switch_eq=function(e,t){return e==t},e.typeOf=function(e){return typeof e}}(n=e.pxtcore||(e.pxtcore={})),function(t){t.panic=r.panic,t.pause=function(t){let n=e.getResume();e.runtime.schedule((()=>{n()}),t)},t.runInBackground=function(t){e.runtime.runFiberAsync(t)},t.forever=function(t){r.nullCheck(t),function n(){e.runtime.runFiberAsync(t).then((()=>e.U.delay(20))).then(n)}()}}(o=e.thread||(e.thread={}))}(pxsim||(pxsim={})),function(e){class t extends e.RefObject{constructor(){super(),this.data=[]}scan(e){for(let t=0;t<this.data.length;++t)e("["+t+"]",this.data[t])}gcKey(){return"[...]"}gcSize(){return this.data.length+2}toArray(){return this.data.slice(0)}toAny(){return this.data.map((t=>e.RefObject.toAny(t)))}toDebugString(){let t="[";for(let n=0;n<this.data.length;++n){n>0&&(t+=",");let i=e.RefObject.toDebugString(this.data[n]);if(t.length+i.length>100){0==n&&(t+=i.substr(0,100)),t+="...";break}t+=i}return t+="]",t}destroy(){let e=this.data;for(let t=0;t<e.length;++t)e[t]=0;this.data=[]}isValidIndex(e){return e>=0&&e<this.data.length}push(e){this.data.push(e)}pop(){return this.data.pop()}getLength(){return this.data.length}setLength(e){this.data.length=e}getAt(e){return this.data[e]}setAt(e,t){this.data[e]=t}insertAt(e,t){this.data.splice(e,0,t)}removeAt(e){return this.data.splice(e,1)[0]}indexOf(e,t){return this.data.indexOf(e,t)}print(){}}let n,i,s,r,o,a,l,c;e.RefCollection=t,function(n){function i(t,n){if(e.pxtrt.nullCheck(t),t.isValidIndex(n))return t.removeAt(n)}function s(t,n,i){return e.pxtrt.nullCheck(t),t.indexOf(n,i)}n.mk=function(){return new t},n.isArray=function(e){return e instanceof t},n.length=function(t){return e.pxtrt.nullCheck(t),t.getLength()},n.setLength=function(t,n){e.pxtrt.nullCheck(t),t.setLength(n)},n.push=function(t,n){e.pxtrt.nullCheck(t),t.push(n)},n.pop=function(t,n){return e.pxtrt.nullCheck(t),t.pop()},n.getAt=function(t,n){return e.pxtrt.nullCheck(t),t.getAt(n)},n.removeAt=i,n.insertAt=function(t,n,i){e.pxtrt.nullCheck(t),t.insertAt(n,i)},n.setAt=function(t,n,i){e.pxtrt.nullCheck(t),t.setAt(n,i)},n.indexOf=s,n.removeElement=function(t,n){e.pxtrt.nullCheck(t);let r=s(t,n,0);return r>=0?(i(t,r),1):0}}(n=e.Array_||(e.Array_={})),function(e){e.imul=Math.imul||function(e,t){const n=65535&e,i=65535&t;return n*i+((e>>>16&65535)*i+n*(t>>>16&65535)<<16>>>0)|0},e.idiv=function(e,t){return(0|e)/(0|t)|0},e.round=function(e){return Math.round(e)},e.roundWithPrecision=function(e,t){if((t|=0)<=0)return Math.round(e);if(0==e)return 0;let n=0;for(;0==n&&t<21;){const i=Math.pow(10,t++);n=Math.round(e*i+Number.EPSILON)/i}return n},e.ceil=function(e){return Math.ceil(e)},e.floor=function(e){return Math.floor(e)},e.sqrt=function(e){return Math.sqrt(e)},e.pow=function(e,t){return Math.pow(e,t)},e.clz32=function(e){return Math.clz32(e)},e.log=function(e){return Math.log(e)},e.log10=function(e){return Math.log10(e)},e.log2=function(e){return Math.log2(e)},e.exp=function(e){return Math.exp(e)},e.sin=function(e){return Math.sin(e)},e.sinh=function(e){return Math.sinh(e)},e.cos=function(e){return Math.cos(e)},e.cosh=function(e){return Math.cosh(e)},e.tan=function(e){return Math.tan(e)},e.tanh=function(e){return Math.tanh(e)},e.asin=function(e){return Math.asin(e)},e.asinh=function(e){return Math.asinh(e)},e.acos=function(e){return Math.acos(e)},e.acosh=function(e){return Math.acosh(e)},e.atan=function(e){return Math.atan(e)},e.atanh=function(e){return Math.atanh(e)},e.atan2=function(e,t){return Math.atan2(e,t)},e.trunc=function(e){return e>0?Math.floor(e):Math.ceil(e)},e.random=function(){return Math.random()},e.randomRange=function(e,t){if(e==t)return e;if(e>t){let n=e;e=t,t=n}return Math.floor(e)==e&&Math.floor(t)==t?e+Math.floor(Math.random()*(t-e+1)):e+Math.random()*(t-e)}}(i=e.Math_||(e.Math_={})),function(t){function n(t,n){return e.pxtrt.nullFix(t)==e.pxtrt.nullFix(n)}t.lt=function(e,t){return e<t},t.le=function(e,t){return e<=t},t.neq=function(e,t){return!n(e,t)},t.eq=n,t.eqDecr=function(t,n){return e.pxtrt.nullFix(t)==e.pxtrt.nullFix(n)},t.gt=function(e,t){return e>t},t.ge=function(e,t){return e>=t},t.div=function(e,t){return 0|Math.floor(e/t)},t.mod=function(e,t){return e%t},t.bnot=function(e){return~e},t.toString=function(e){return e+""}}(s=e.Number_||(e.Number_={})),function(e){e.adds=function(e,t){return e+t|0},e.subs=function(e,t){return e-t|0},e.divs=function(e,t){return 0|Math.floor(e/t)},e.muls=function(e,t){return i.imul(e,t)},e.ands=function(e,t){return e&t},e.orrs=function(e,t){return e|t},e.eors=function(e,t){return e^t},e.lsls=function(e,t){return e<<t},e.lsrs=function(e,t){return e>>>t},e.asrs=function(e,t){return e>>t},e.bnot=function(e){return~e},e.ignore=function(e){return e}}(r=e.thumb||(e.thumb={})),function(e){function t(e){return e<<16>>16}e.adds=function(e,n){return t(e+n)},e.subs=function(e,n){return t(e-n)},e.divs=function(e,n){return t(Math.floor(e/n))},e.muls=function(e,n){return t(i.imul(e,n))},e.ands=function(e,n){return t(e&n)},e.orrs=function(e,n){return t(e|n)},e.eors=function(e,n){return t(e^n)},e.lsls=function(e,n){return t(e<<n)},e.lsrs=function(e,t){return(65535&e)>>>t},e.asrs=function(e,n){return t(e>>n)},e.bnot=function(e){return~e},e.ignore=function(e){return e}}(o=e.avr||(e.avr={})),function(t){t.stringConv=function(t){const n=e.getResume();t instanceof e.RefRecord&&t.vtable.toStringMethod?e.runtime.runFiberAsync(t.vtable.toStringMethod,t).then((()=>{n(e.runtime.currFrame.retval+"")})):n(t+"")},t.mkEmpty=function(){return""},t.fromCharCode=function(e){return String.fromCharCode(e)},t.toNumber=function(e){return parseFloat(e)},t.concat=function(e,t){return e+t},t.substring=function(t,n,i){return e.pxtrt.nullCheck(t),t.slice(n,n+i)},t.equals=function(e,t){return e==t},t.compare=function(e,t){return e==t?0:e<t?-1:1},t.compareDecr=function(e,t){return e==t?0:e<t?-1:1},t.length=function(e){return e.length},t.substr=function(e,t,n){return e.substr(t,n)},t.charAt=function(e,t){return e.charAt(t)},t.charCodeAt=function(t,n){return e.pxtrt.nullCheck(t),function(t,n){return e.pxtrt.nullCheck(t),0<=n&&n<t.length}(t,n)?t.charCodeAt(n):0},t.indexOf=function(t,n,i){return e.pxtrt.nullCheck(t),null==n?-1:t.indexOf(n,i)},t.lastIndexOf=function(t,n,i){return e.pxtrt.nullCheck(t),null==n?-1:t.lastIndexOf(n,i)},t.includes=function(t,n,i){return e.pxtrt.nullCheck(t),null!=n&&t.includes(n,i)}}(a=e.String_||(e.String_={})),function(e){e.toString=function(e){return e?"true":"false"},e.bang=function(e){return!e}}(l=e.Boolean_||(e.Boolean_={}));class u extends e.RefObject{constructor(e){super(),this.data=e,this.isStatic=!1}scan(e){}gcKey(){return"Buffer"}gcSize(){return 2+(this.data.length+3>>2)}gcIsStatic(){return this.isStatic}print(){}toDebugString(){return c.toHex(this)}}e.RefBuffer=u,function(t){let n;function i(t){let i=function(t){switch(t){case n.Int8LE:return-1;case n.UInt8LE:return 1;case n.Int16LE:return-2;case n.UInt16LE:return 2;case n.Int32LE:return-4;case n.UInt32LE:return 4;case n.Int8BE:return-10;case n.UInt8BE:return 10;case n.Int16BE:return-20;case n.UInt16BE:return 20;case n.Int32BE:return-40;case n.UInt32BE:return 40;case n.Float32LE:return 4;case n.Float32BE:return 40;case n.Float64LE:return 8;case n.Float64BE:return 80;default:throw e.U.userError("bad format")}}(t),s=!1;i<0&&(s=!0,i=-i);let r=!1;return i>=10&&(r=!0,i/=10),{size:i,signed:s,swap:r,isFloat:t>=n.Float32LE}}function s(e){return new u(new Uint8Array(e))}function r(t,n){return e.pxtrt.nullCheck(t),0<=n&&n<t.data.length}function o(e,t){return r(e,t)?e.data[t]:0}function a(t){t.isStatic&&e.U.userError("Writing to read only buffer.")}function l(e,t,n){r(e,t)&&(a(e),e.data[t]=n)}function c(e,t,n=0,i=-1){n<0||n>e.data.length||(i<0&&(i=e.data.length),i=Math.min(i,e.data.length-n),a(e),e.data.fill(t,n,n+i))}function d(e,t,n,i,s){if(n.buffer===e.buffer)d(e,t,n.slice(i,i+s),0,s);else for(let r=0;r<s;++r)e[t+r]=n[i+r]}!function(e){e[e.Int8LE=1]="Int8LE",e[e.UInt8LE=2]="UInt8LE",e[e.Int16LE=3]="Int16LE",e[e.UInt16LE=4]="UInt16LE",e[e.Int32LE=5]="Int32LE",e[e.Int8BE=6]="Int8BE",e[e.UInt8BE=7]="UInt8BE",e[e.Int16BE=8]="Int16BE",e[e.UInt16BE=9]="UInt16BE",e[e.Int32BE=10]="Int32BE",e[e.UInt32LE=11]="UInt32LE",e[e.UInt32BE=12]="UInt32BE",e[e.Float32LE=13]="Float32LE",e[e.Float64LE=14]="Float64LE",e[e.Float32BE=15]="Float32BE",e[e.Float64BE=16]="Float64BE"}(n=t.NumberFormat||(t.NumberFormat={})),t.getNumber=function(e,t,n){let s=i(t);if(s.isFloat){let t=e.data.buffer.slice(n,n+s.size);if(s.swap){new Uint8Array(t).reverse()}return 4==s.size?new Float32Array(t)[0]:new Float64Array(t)[0]}let r=0;for(let t=0;t<s.size;++t){r<<=8;let i=s.swap?n+t:n+s.size-t-1;r|=e.data[i]}if(s.signed){let e=32-8*s.size;r=r<<e>>e}else r>>>=0;return r},t.setNumber=function(e,t,n,s){let r=i(t);if(r.isFloat){let t=new Uint8Array(r.size);4==r.size?new Float32Array(t.buffer)[0]=s:new Float64Array(t.buffer)[0]=s,r.swap&&t.reverse();for(let i=0;i<r.size;++i)e.data[n+i]=t[i]}else for(let t=0;t<r.size;++t){let i=r.swap?n+r.size-t-1:n+t;e.data[i]=255&s,s>>=8}},t.createBuffer=s,t.createBufferFromHex=function(e){let t=s(e.length>>1);for(let n=0;n<e.length;n+=2)t.data[n>>1]=parseInt(e.slice(n,n+2),16);return t.isStatic=!0,t},t.isReadOnly=function(e){return e.isStatic},t.getBytes=function(e){return e.data},t.getUint8=function(e,t){return o(e,t)},t.getByte=o,t.setUint8=function(e,t,n){l(e,t,n)},t.setByte=l,t.length=function(e){return e.data.length},t.fill=c,t.slice=function(e,t,n){return t=Math.min(e.data.length,t),n<0&&(n=e.data.length),n=Math.min(n,e.data.length-t),new u(e.data.slice(t,t+n))},t.toHex=function(e){const t="0123456789abcdef";let n="";for(let i=0;i<e.data.length;++i)n+=t[e.data[i]>>4],n+=t[15&e.data[i]];return n},t.toString=function(t){return e.U.fromUTF8Array(t.data)};const h=-2147483648;t.shift=function(e,t,n,i){i<0&&(i=e.data.length-n),n<0||n+i>e.data.length||n+i<n||0==i||0==t||t==h||0!=i&&0!=t&&t!=h&&(t<=-i||t>=i?c(e,0):(a(e),t<0?(t=-t,d(e.data,n+t,e.data,n,i-t),e.data.fill(0,n,n+t)):(i-=t,d(e.data,n,e.data,n+t,i),e.data.fill(0,n+i,n+i+t))))},t.rotate=function(e,t,n,i){if(i<0&&(i=e.data.length-n),n<0||n+i>e.data.length||n+i<n||0==i||0==t||t==h)return;a(e),t<0&&(t+=i<<8),(t%=i)<0&&(t+=i);let s=e.data,r=t,o=0,l=r,c=i;for(;o!=l;){let e=s[o+n];s[o+++n]=s[l+n],s[l+++n]=e,l==c?l=r:o==r&&(r=l)}},t.write=function(e,t,n,i=0,s=-1){s<0&&(s=n.data.length),i<0||t<0||t>e.data.length||(s=Math.min(n.data.length-i,e.data.length-t))<0||(a(e),d(e.data,t,n.data,i,s))}}(c=e.BufferMethods||(e.BufferMethods={}))}(pxsim||(pxsim={})),function(e){!function(t){t.createBufferFromUTF8=function(t){return new e.RefBuffer(e.U.toUTF8Array(t))}}(e.control||(e.control={}))}(pxsim||(pxsim={})),function(e){!function(e){let t={};e.setLocalizedStrings=function(e){t=e||{}};function n(e,t){return 0==t.length?e:e.replace(/\{([0-9]+)(\:[^\}]+)?\}/g,(function(e,n,r){let o=t[parseInt(n)],a="",l=/^:f(\d*)\.(\d+)/.exec(r);if(l){let e=parseInt(l[2]),t=parseInt(l[1])||0,n=/^0/.test(l[1])?"0":" ",i=o.toFixed(e);if(t>0&&e>0&&(t+=e+1),t>0)for(;i.length<t;)i=n+i;a=i}else a=":x"==r?"0x"+o.toString(16):void 0===o?"(undef)":null===o?"(null)":o.toString?o.toString():o+"";return":a"==r?/^\s*[euioah]/.test(a.toLowerCase())?a="an "+a:/^\s*[bcdfgjklmnpqrstvwxz]/.test(a.toLowerCase())&&(a="a "+a):":s"==r?a=1==o?"":"s":":q"==r?a=i(a):":jq"==r?a=s(a):":uri"==r?a=encodeURIComponent(a).replace(/'/g,"%27").replace(/"/g,"%22"):":url"==r?a=encodeURI(a).replace(/'/g,"%27").replace(/"/g,"%22"):":%"==r&&(a=(100*o).toFixed(1).toString()+"%"),a}))}function i(e){return e?e.replace(/([^\w .!?\-$])/g,(e=>"&#"+e.charCodeAt(0)+";")):e}function s(e){return e.replace(/[^\w .!?\-$]/g,(e=>{let t=e.charCodeAt(0).toString(16);return"\\u"+"0000".substr(0,4-t.length)+t}))}e.lf=function(e,...i){let s=t[e]||e;return s=s.replace(/^\{(id|loc):[^\}]+\}/g,""),n(s,i)},e.fmt_va=n,e.htmlEscape=i,e.jsStringQuote=s}(e.localization||(e.localization={}))}(pxsim||(pxsim={})),function(pxsim){const MIN_MESSAGE_WAIT_MS=200;let tracePauseMs=0,MessageListenerFlags,U,pxtcore;!function(e){e[e.MESSAGE_BUS_LISTENER_REENTRANT=8]="MESSAGE_BUS_LISTENER_REENTRANT",e[e.MESSAGE_BUS_LISTENER_QUEUE_IF_BUSY=16]="MESSAGE_BUS_LISTENER_QUEUE_IF_BUSY",e[e.MESSAGE_BUS_LISTENER_DROP_IF_BUSY=32]="MESSAGE_BUS_LISTENER_DROP_IF_BUSY",e[e.MESSAGE_BUS_LISTENER_IMMEDIATE=192]="MESSAGE_BUS_LISTENER_IMMEDIATE"}(MessageListenerFlags||(MessageListenerFlags={})),function(e){function t(e){return e.split(/\s+/).filter((e=>!!e))}function n(e){for(;e.firstChild;)e.removeChild(e.firstChild)}let i;e.containsClass=function(e,n){return t(n).every((t=>function(e,t){if(e.classList)return e.classList.contains(t);return!((e.className+"").split(/\s+/).indexOf(t)<0)}(e,t)))},e.addClass=function(e,n){t(n).forEach((t=>function(e,t){if(e.classList)e.classList.add(t);else{(e.className+"").split(/\s+/).indexOf(t)<0&&(e.className.baseVal+=" "+t)}}(e,t)))},e.removeClass=function(e,n){t(n).forEach((t=>function(e,t){e.classList?e.classList.remove(t):e.className.baseVal=(e.className+"").split(/\s+/).filter((e=>e!=t)).join(" ")}(e,t)))},e.remove=function(e){e.parentElement.removeChild(e)},e.removeChildren=n,e.clear=function(e){n(e)},e.assert=function(e,t="Assertion failed"){if(!e)throw new Error(t)},e.repeatMap=function(e,t){e=e||0;let n=[];for(let i=0;i<e;++i)n.push(t(i));return n},e.userError=function(e){let t=new Error(e);throw t.isUserError=!0,t},e.now=function(){return Date.now()},e.perfNowUs=function(){return i||(i="undefined"!=typeof performance?performance.now.bind(performance)||performance.moznow.bind(performance)||performance.msNow.bind(performance)||performance.webkitNow.bind(performance)||performance.oNow.bind(performance):Date.now),1e3*i()};const s=Promise.resolve();async function r(e,t,n){let i=0;const s=[],r=[];for(let o=0;o<e;o++){const e=(async()=>{for(;i<t.length;){const e=i++,s=t[e];r[e]=await n(s)}})();s.push(e)}try{await Promise.all(s)}catch(e){throw i=t.length,e}return r}function o(){return"undefined"!=typeof window&&!!window.pxtElectron}function a(){return"undefined"!=typeof window&&!!window.ipcRenderer}function l(){return o()||a()}function c(){try{return"undefined"!=typeof window&&/^http:\/\/(localhost|127\.0\.0\.1):\d+\//.test(window.location.href)&&!/nolocalhost=1/.test(window.location.href)}catch(e){return!1}}e.nextTick=function(e){s.then(e)},e.delay=async function(e,t){const n=await t;return await new Promise((t=>setTimeout((()=>t()),e))),n},e.throttle=function(e,t,n){let i;return function(){let s=this,r=arguments,o=function(){i=null,n||e.apply(s,r)},a=n&&!i;i||(i=setTimeout(o,t)),a&&e.apply(s,r)}},e.promiseMapAll=function(e,t){return Promise.all(e.map((e=>t(e))))},e.promiseMapAllSeries=function(e,t){return r(1,e,t)},e.promisePoolAsync=r,e.promiseTimeout=async function(e,t,n){let i,s;const r=new Promise(((t,r)=>{s=t,i=setTimeout((()=>{s=void 0,clearTimeout(i),r(n||`Promise timed out after ${e}ms`)}),e)}));return Promise.race([t,r]).then((e=>(s&&(clearTimeout(i),s()),e)))},e.stringToUint8Array=function(e){let t=e.length,n=new Uint8Array(t);for(let i=0;i<t;++i)n[i]=255&e.charCodeAt(i);return n},e.uint8ArrayToString=function(e){let t=e.length,n="";for(let i=0;i<t;++i)n+=String.fromCharCode(e[i]);return n},e.fromUTF8=function(e){if(!e)return"";let t="";for(let n=0;n<e.length;++n){let i=255&e.charCodeAt(n);t+=37==i||i>127?"%"+i.toString(16):e.charAt(n)}return decodeURIComponent(t)},e.toUTF8=function(e,t){let n="";if(!e)return n;for(let i=0;i<e.length;++i){let s=e.charCodeAt(i);if(s<=127)n+=e.charAt(i);else if(s<=2047)n+=String.fromCharCode(192|s>>6,128|63&s);else{if(!t&&55296<=s&&s<=56319){let t=e.charCodeAt(++i);isNaN(t)||(s=65536+(s-55296<<10)+(t-56320))}n+=s<=65535?String.fromCharCode(224|s>>12,128|s>>6&63,128|63&s):String.fromCharCode(240|s>>18,128|s>>12&63,128|s>>6&63,128|63&s)}}return n},e.toUTF8Array=function(e){return(new TextEncoder).encode(e)},e.fromUTF8Array=function(e){return(new TextDecoder).decode(e)},e.isPxtElectron=o,e.isIpcRenderer=a,e.isElectron=l,e.isLocalHost=c,e.isLocalHostDev=function(){return c()&&!l()},e.unique=function(e,t){let n=[],i={};return e.forEach((e=>{let s=t(e);i.hasOwnProperty(s)||(i[s]=null,n.push(e))})),n}}(U=pxsim.U||(pxsim.U={}));class BreakLoopException{}function getResume(){return pxsim.runtime.getResume()}pxsim.BreakLoopException=BreakLoopException,function(e){function t(e){let t=pxsim.runtime.currTryFrame();t||U.userError("unhandled exception: "+e);const n=t.handlerFrame;throw pxsim.runtime.currFrame=n,n.pc=t.handlerPC,n.tryFrame=t.parent,n.thrownValue=e,n.hasThrownValue=!0,new BreakLoopException}e.beginTry=function(e){pxsim.runtime.currFrame.tryFrame={parent:pxsim.runtime.currTryFrame(),handlerPC:e,handlerFrame:pxsim.runtime.currFrame}},e.endTry=function(){const e=pxsim.runtime.currFrame;e.tryFrame=e.tryFrame.parent},e.throwValue=t,e.getThrownValue=function(){const e=pxsim.runtime.currFrame;return U.assert(e.hasThrownValue),e.hasThrownValue=!1,e.thrownValue},e.endFinally=function(){const e=pxsim.runtime.currFrame;e.hasThrownValue&&(e.hasThrownValue=!1,t(e.thrownValue))}}(pxtcore=pxsim.pxtcore||(pxsim.pxtcore={})),pxsim.getResume=getResume;const SERIAL_BUFFER_LENGTH=16;class BaseBoard{constructor(){this.messageListeners=[],this.serialOutBuffer="",this.messages=[],this.lastSerialTime=0,this.debouncedPostAll=()=>{const e=Date.now();e-this.lastSerialTime>MIN_MESSAGE_WAIT_MS?(clearTimeout(this.serialTimeout),this.messages.length&&(Runtime.postMessage({type:"bulkserial",data:this.messages,id:pxsim.runtime.id,sim:!0}),this.messages=[],this.lastSerialTime=e)):this.serialTimeout=setTimeout(this.debouncedPostAll,50)},this.id=pxsim.Embed.frameid||"b"+Math.round(2147483647*Math.random()),this.bus=new pxsim.EventBus(pxsim.runtime,this)}updateView(){}receiveMessage(e){pxsim.runtime&&!pxsim.runtime.dead&&this.dispatchMessage(e)}dispatchMessage(e){for(const t of this.messageListeners)t(e)}addMessageListener(e){this.messageListeners.push(e)}get storedState(){return this.runOptions?(this.runOptions.storedState||(this.runOptions.storedState={}),this.runOptions.storedState):{}}initAsync(e){return this.runOptions=e,Promise.resolve()}setStoredState(e,t){null==t?delete this.storedState[e]:this.storedState[e]=t,Runtime.postMessage({type:"simulator",command:"setstate",stateKey:e,stateValue:t})}onDebuggerResume(){}screenshotAsync(e){return Promise.resolve(void 0)}kill(){}writeSerial(e){this.serialOutBuffer+=e,(/\n/.test(this.serialOutBuffer)||this.serialOutBuffer.length>SERIAL_BUFFER_LENGTH)&&(this.messages.push({time:Date.now(),data:this.serialOutBuffer}),this.debouncedPostAll(),this.serialOutBuffer="")}}pxsim.BaseBoard=BaseBoard;class CoreBoard extends BaseBoard{constructor(){super(),this.updateSubscribers=[],this.updateView=()=>{this.updateSubscribers.forEach((e=>e()))},this.builtinParts={},this.builtinVisuals={},this.builtinPartVisuals={}}kill(){super.kill(),pxsim.codal.music.__stopSoundExpressions(),pxsim.AudioContextManager.stopAll()}}pxsim.CoreBoard=CoreBoard;class BareBoard extends BaseBoard{}function initBareRuntime(){pxsim.runtime.board=new BareBoard;let e=pxsim;e.basic={pause:pxsim.thread.pause,showNumber:e=>{let t=getResume();console.log("SHOW NUMBER:",e),U.nextTick(t)}},e.serial={writeString:e=>pxsim.runtime.board.writeSerial(e)},e.pins={createBuffer:pxsim.BufferMethods.createBuffer},e.control={inBackground:pxsim.thread.runInBackground,createBuffer:pxsim.BufferMethods.createBuffer,dmesg:e=>console.log("DMESG: "+e),deviceDalVersion:()=>"sim",__log:(e,t)=>console.log("LOG: "+t.trim())}}let LogType;pxsim.initBareRuntime=initBareRuntime,function(e){e[e.UserSet=0]="UserSet",e[e.BackAdd=1]="BackAdd",e[e.BackRemove=2]="BackRemove"}(LogType||(LogType={}));class EventHandler{constructor(e,t){this.handler=e,this.flags=t,this.busy=0}async runAsync(e,t,n){const i=this.flags||MessageListenerFlags.MESSAGE_BUS_LISTENER_QUEUE_IF_BUSY;if(i!==MessageListenerFlags.MESSAGE_BUS_LISTENER_IMMEDIATE)return i===MessageListenerFlags.MESSAGE_BUS_LISTENER_QUEUE_IF_BUSY?this.runFiberAsync(e,t,n):void(i===MessageListenerFlags.MESSAGE_BUS_LISTENER_DROP_IF_BUSY&&this.busy||this.runFiberAsync(e,t,n));U.userError("MESSAGE_BUS_LISTENER_IMMEDIATE is not supported!")}async runFiberAsync(e,t,n){this.busy++,await t.runFiberAsync(this.handler,...n?n(e):[e]),this.busy--}}class EventQueue{constructor(e,t){this.runtime=e,this.valueToArgs=t,this.max=5,this.events=[],this.awaiters=[],this._handlers=[],this._addRemoveLog=[]}push(e,t){if(this.awaiters.length>0)if(t){const e=this.awaiters.shift();e&&e()}else{const e=this.awaiters.slice();this.awaiters=[],e.forEach((e=>e()))}return 0==this.handlers.length||this.events.length>this.max?Promise.resolve():(this.events.push(e),this.lock?Promise.resolve():this.poke())}async poke(){this.lock=!0;let e=this.events;this.events=[];for(const t of e)for(const e of this.handlers)await e.runAsync(t,this.runtime,this.valueToArgs);if(this.events.length>0)return this.poke();this.lock=!1;for(const e of this._addRemoveLog)e.log===LogType.BackAdd?this.addHandler(e.act,e.flags):e.log===LogType.BackRemove?this.removeHandler(e.act):this.setHandler(e.act,e.flags);this._addRemoveLog=[]}get handlers(){return this._handlers}setHandler(e,t=0){this.lock?this._addRemoveLog.push({act:e,log:LogType.UserSet,flags:t}):this._handlers=[new EventHandler(e,t)]}addHandler(e,t=0){this.lock?this._addRemoveLog.push({act:e,log:LogType.BackAdd,flags:t}):this._handlers.some((t=>t.handler===e))||this._handlers.push(new EventHandler(e,t))}removeHandler(e){if(this.lock)this._addRemoveLog.push({act:e,log:LogType.BackRemove,flags:0});else{let t=this._handlers.findIndex((t=>t.handler===e));-1!=t&&this._handlers.splice(t,1)}}addAwaiter(e){this.awaiters.push(e)}}function bind(e){const t=e.arg0,n=e.fn;return e=>{let i=0;for(;e.hasOwnProperty("arg"+i);)i++;const s=e;for(let e=i;e>0;e--)s["arg"+e]=s["arg"+(e-1)];return e.arg0=t,n(e)}}function _leave(e,t){return e.parent.retval=t,e.parent}function syntheticRefAction(e){return pxtcore.mkAction(0,(t=>_leave(t,e(t))))}pxsim.EventQueue=EventQueue,pxsim.initCurrentRuntime=void 0,pxsim.handleCustomMessage=void 0,pxsim.syntheticRefAction=syntheticRefAction;class TimeoutScheduled{constructor(e,t,n,i){this.id=e,this.fn=t,this.totalRuntime=n,this.timestampCall=i}}pxsim.TimeoutScheduled=TimeoutScheduled;class PausedTimeout{constructor(e,t){this.fn=e,this.timeRemaining=t}}function mkVTable(e){return{name:e.name,numFields:e.numFields,classNo:e.classNo,methods:e.methods,iface:e.iface,lastSubtypeNo:e.lastSubtypeNo,toStringMethod:e.toStringMethod,maxBgInstances:e.maxBgInstances}}pxsim.PausedTimeout=PausedTimeout,pxsim.mkVTable=mkVTable;let mapVTable=null;function mkMapVTable(){return mapVTable||(mapVTable=mkVTable({name:"_Map",numFields:0,classNo:0,lastSubtypeNo:0,methods:null})),mapVTable}function functionName(e){const t=e.info;return t?`${t.functionName} (${t.fileName}:${t.line+1}:${t.column+1})`:"()"}pxsim.mkMapVTable=mkMapVTable,pxsim.functionName=functionName;class Runtime{constructor(msg){this.numGlobals=1e3,this.dead=!1,this.running=!1,this.idleTimer=void 0,this.recording=!1,this.recordingTimer=0,this.recordingLastImageData=void 0,this.recordingWidth=void 0,this.startTime=0,this.startTimeUs=0,this.pausedTime=0,this.lastPauseTimestamp=0,this.globals={},this.environmentGlobals={},this.otherFrames=[],this.loopLock=null,this.loopLockWaitList=[],this.heapSnapshots=[],this.timeoutsScheduled=[],this.timeoutsPausedOnBreakpoint=[],this.pausedOnBreakpoint=!1,this.traceDisabled=!1,this.perfOffset=0,this.perfElapsed=0,this.perfStack=0,this.refCountingDebug=!1,this.refObjId=1,this.numDisplayUpdates=0,U.assert(!!pxsim.initCurrentRuntime),this.id=msg.id,this.refCountingDebug=!!msg.refCountingDebug;let threadId=0,breakpoints=null,currResume,dbgHeap,dbgResume,breakFrame=null,lastYield=Date.now(),userGlobals,__this=this;this.traceDisabled=!!msg.traceDisabled;const yieldDelay=void 0!==msg.yieldDelay?msg.yieldDelay:5,evalIface={runtime:this,oops:oops,doNothing:doNothing,pxsim:pxsim,globals:this.globals,setupYield:setupYield,maybeYield:maybeYield,setupDebugger:setupDebugger,isBreakFrame:isBreakFrame,breakpoint:breakpoint,trace:trace,checkStack:checkStack,leave:_leave,checkResumeConsumed:checkResumeConsumed,setupResume:setupResume,setupLambda:setupLambda,checkSubtype:checkSubtype,failedCast:failedCast,buildResume:buildResume,mkVTable:mkVTable,bind:bind,leaveAccessor:leaveAccessor};function oops(e){throw new Error("sim error: "+e)}function doNothing(e){return e.pc=-1,_leave(e,e.parent.retval)}function flushLoopLock(){for(;__this.loopLockWaitList.length>0&&!__this.loopLock;){__this.loopLockWaitList.shift()()}}let yieldReset=()=>{};function setupYield(e){yieldReset=e}function loopForSchedule(e){const t=new Object,n=e.pc;return __this.loopLock=t,__this.otherFrames.push(e),()=>{__this.dead||(U.assert(e.pc==n),U.assert(__this.loopLock===t),__this.loopLock=null,loop(e),flushLoopLock())}}function maybeYield(e,t,n){if(__this.pausedOnBreakpoint)return!1;__this.cleanScheduledExpired(),yieldReset();let i=Date.now();return i-lastYield>=20&&(lastYield=i,e.pc=t,e.r0=n,setTimeout(loopForSchedule(e),yieldDelay),!0)}function setupDebugger(e,t){return breakpoints=new Uint8Array(e),breakpoints[0]=msg.breakOnStart?1:0,userGlobals=t,breakpoints}function isBreakFrame(e){if(!breakFrame)return!0;for(let t=breakFrame;t;t=t.parent)if(t==e)return!0;return!1}function breakpoint(e,t,n,i){let s={};__this.loopLock=s,U.assert(!dbgResume),U.assert(!dbgHeap),e.pc=t,e.r0=i;const{msg:r,heap:o}=pxsim.getBreakpointMsg(e,n,userGlobals);return dbgHeap=o,pxsim.injectEnvironmentGlobals(r,o),Runtime.postMessage(r),breakpoints[0]=0,breakFrame=null,__this.pauseScheduled(),dbgResume=n=>{if(dbgResume=null,dbgHeap=null,__this.dead)return null;switch(__this.resumeAllPausedScheduled(),__this.board.onDebuggerResume(),pxsim.runtime=__this,U.assert(e.pc==t),breakpoints[0]=0,breakFrame=null,n.subtype){case"resume":break;case"stepover":breakpoints[0]=1,breakFrame=e;break;case"stepinto":breakpoints[0]=1;break;case"stepout":breakpoints[0]=1,breakFrame=e.parent||e}U.assert(__this.loopLock==s),__this.loopLock=null,__this.otherFrames.push(e),loop(e),flushLoopLock()},null}function trace(e,t,n,i){if(setupResume(t,n),"<main>"===i.functionName||"main.ts"===i.fileName){if(!pxsim.runtime.traceDisabled){const{msg:n}=pxsim.getBreakpointMsg(t,e,userGlobals);n.subtype="trace",Runtime.postMessage(n)}pxsim.thread.pause(tracePauseMs||1)}else pxsim.thread.pause(0);checkResumeConsumed()}function handleDebuggerMsg(e){switch(e.subtype){case"config":let t=e;if(t.setBreakpoints&&breakpoints){breakpoints.fill(0);for(let e of t.setBreakpoints)breakpoints[e]=1}break;case"traceConfig":tracePauseMs=e.interval;break;case"pause":breakpoints[0]=1,breakFrame=null;break;case"resume":case"stepover":case"stepinto":case"stepout":dbgResume&&dbgResume(e);break;case"variables":const n=e;let i;if(dbgHeap){const e=dbgHeap[n.variablesReference];void 0!==e&&(i=pxsim.dumpHeap(e,dbgHeap,n.fields,void 0,n.includeAll))}Runtime.postMessage({type:"debugger",subtype:"variables",req_seq:e.seq,variables:i})}}function removeFrame(e){const t=__this.otherFrames;for(let n=t.length-1;n>=0;--n)if(t[n]===e)return void t.splice(n,1);U.userError("frame cannot be removed!")}function loop(e){if(__this.dead)console.log("Runtime terminated");else{U.assert(!__this.loopLock),__this.perfStartRuntime(),removeFrame(e);try{for(pxsim.runtime=__this;e;)__this.currFrame=e,__this.currFrame.overwrittenPC=!1,e=e.fn(e),__this.maybeUpdateDisplay(),__this.currFrame.overwrittenPC&&(e=__this.currFrame);__this.perfStopRuntime()}catch(t){if(t instanceof BreakLoopException)return void U.nextTick(loopForSchedule(__this.currFrame));if(__this.perfStopRuntime(),__this.errorHandler)__this.errorHandler(t);else{console.error("Simulator crashed, no error handler",t.stack);const{msg:n,heap:i}=pxsim.getBreakpointMsg(e,e.lastBrkId,userGlobals);pxsim.injectEnvironmentGlobals(n,i),n.exceptionMessage=t.message,n.exceptionStack=t.stack,Runtime.postMessage(n),__this.postError&&__this.postError(t)}}}}function checkStack(e){e>100&&U.userError("Stack overflow")}function actionCall(e){return e.depth=e.parent.depth+1,checkStack(e.depth),e.pc=0,e}function setupTop(e){let t=setupTopCore(e);return setupResume(t,0),t}function setupTopCore(e){let t={parent:null,pc:0,depth:0,threadId:++threadId,fn:()=>(e&&e(t.retval),null)};return t}function topCall(e,t){U.assert(!!__this.board),U.assert(!__this.running),__this.setRunning(!0);let n={parent:setupTopCore(t),fn:e,depth:0,pc:0};__this.otherFrames=[n],loop(actionCall(n))}function checkResumeConsumed(){currResume&&oops("getResume() not called")}function setupResume(e,t){currResume=buildResume(e,t)}function leaveAccessor(e,t){if(e.stage2Call){const n={pc:0,fn:null,depth:e.depth,parent:e.parent};let i=1;for(;e.hasOwnProperty("arg"+i);)n["arg"+(i-1)]=e["arg"+i],i++;return setupLambda(n,t),n}return e.parent.retval=t,e.parent}function setupLambda(e,t,n){if(n){const t=e;for(let e=1;e<n;++e)t["arg"+(e-1)]=t["arg"+e];delete t["arg"+(n-1)]}t instanceof pxsim.RefAction?(e.fn=t.func,e.caps=t.fields):"function"==typeof t?e.fn=t:oops("calling non-function")}function checkSubtype(e,t){if(!e)return!1;const n=e.vtable;return t===n||n&&t.classNo<=n.classNo&&n.classNo<=t.lastSubtypeNo}function failedCast(e){pxsim.control&&pxsim.control.dmesgValue&&pxsim.control.dmesgValue(e),oops("failed cast on "+e)}function buildResume(e,t){currResume&&oops("already has resume"),e.pc=t;let n=Date.now();__this.otherFrames.push(e);let i=s=>{if(__this.dead)return;if(__this.loopLock)return void __this.loopLockWaitList.push((()=>i(s)));pxsim.runtime=__this;let r=Date.now();if(r-n>3&&(lastYield=r),U.assert(e.pc==t),s instanceof pxsim.FnWrapper){let t=s,n={parent:e,fn:t.func,lambdaArgs:t.args,pc:0,caps:t.caps,depth:e.depth+1},i={};return __this.loopLock=i,removeFrame(e),__this.otherFrames.push(n),U.nextTick((()=>{U.assert(__this.loopLock===i),__this.loopLock=null,loop(actionCall(n)),flushLoopLock()}))}return e.retval=s,loop(e)};return i}const entryPoint=msg.code&&eval(msg.code)(evalIface);this.run=e=>topCall(entryPoint,e),this.getResume=()=>{currResume||oops("noresume");let e=currResume;return currResume=null,e},this.setupTop=setupTop,this.handleDebuggerMsg=handleDebuggerMsg,this.entry=entryPoint,this.overwriteResume=e=>{currResume=null,e>=0&&(this.currFrame.pc=e),this.currFrame.overwrittenPC=!0},pxsim.runtime=this,pxsim.initCurrentRuntime(msg)}registerLiveObject(e){return this.refObjId++}runningTime(){return U.now()-this.startTime-this.pausedTime}runningTimeUs(){return 4294967295&U.perfNowUs()-this.startTimeUs>>0}runFiberAsync(e,t,n,i){return new Promise(((s,r)=>U.nextTick((()=>{pxsim.runtime=this,this.setupTop(s),pxtcore.runAction(e,[t,n,i])}))))}currTryFrame(){for(let e=this.currFrame;e;e=e.parent)if(e.tryFrame)return e.tryFrame;return null}traceObjects(){const e={};for(;this.heapSnapshots.length>2;)this.heapSnapshots.shift();const t={count:0,size:0,name:"TOTAL"},n={TOTAL:t};function i(t,n,s=null){if(!(n instanceof pxsim.RefObject))return;const r=n;if(r.gcIsStatic())return;const o=e[r.id];if(o)return void(s&&o.pointers.push([s,t]));const a={obj:r,path:null,pointers:[[s,t]]};e[r.id]=a,r.scan(((t,n)=>{n instanceof pxsim.RefObject&&!e[n.id]&&i(t,n,a)}))}this.heapSnapshots.push({visited:e,statsByType:n});for(let e of Object.keys(this.globals))i(e.replace(/___\d+$/,""),this.globals[e]);const s=this.otherFrames.slice();this.currFrame&&s.indexOf(this.currFrame)<0&&s.unshift(this.currFrame);for(const e of this.getThreads()){const t="Thread-"+this.rootFrame(e).threadId;for(let n=e;n;n=n.parent){const e=t+"."+functionName(n.fn);for(let t of Object.keys(n))if(/^(r0|arg\d+|.*___\d+)/.test(t)){const s=n[t];s instanceof pxsim.RefObject&&(t=t.replace(/___.*/,""),i(e+"."+t,s))}if(n.caps)for(let t of n.caps)i(e+".cap",t)}}const r=Object.keys(e).map((t=>e[t]));r.sort(((e,t)=>t.obj.gcSize()-e.obj.gcSize()));const o=e=>{if(null!=e.path)return;let t="";e.path="(cycle)";for(let[n,i]of e.pointers){if(null==n)return void(e.path=i);o(n);const s=n.path+"."+i;(!t||t.length>s.length)&&(t=s)}e.path=t};r.forEach(o);const a=[t];for(const e of r){const i=e.obj.gcSize(),s=e.obj.gcKey();n.hasOwnProperty(s)||a.push(n[s]={count:0,size:0,name:s});const r=n[s];r.size+=i,r.count++,t.size+=i,t.count++}a.sort(((e,t)=>e.size-t.size));let l="";const c=e=>(" "+e.toString()).slice(-7);for(const e of a)l+=c(4*e.size)+c(e.count)+" "+e.name+"\n";const u=e=>c(4*e.obj.gcSize())+" "+e.obj.gcKey()+" "+e.path,d=r.slice(0,20).map(u).join("\n");let h="";if(this.heapSnapshots.length>=3){const e=this.heapSnapshots[this.heapSnapshots.length-3].visited,t=this.heapSnapshots[this.heapSnapshots.length-2].visited,i=e=>e instanceof pxsim.RefRecord&&!!(e.vtable&&e.vtable.maxBgInstances&&n[e.gcKey()].count<=e.vtable.maxBgInstances);h=r.filter((n=>!e[n.obj.id]&&t[n.obj.id])).filter((e=>!i(e.obj))).map(u).join("\n")}return"Threads:\n"+this.threadInfo()+"\n\nSummary:\n"+l+"\n\nLarge Objects:\n"+d+"\n\nNew Objects:\n"+h}getThreads(){const e=this.otherFrames.slice();return this.currFrame&&e.indexOf(this.currFrame)<0&&e.unshift(this.currFrame),e}rootFrame(e){let t=e;for(;t.parent;)t=t.parent;return t}threadInfo(){const e=this.getThreads();let t="";for(let n of e){t+=`Thread ${this.rootFrame(n).threadId}:\n`;for(let e of pxsim.getBreakpointMsg(n,n.lastBrkId).msg.stackframes){let n=e.funcInfo;t+=` at ${n.functionName} (${n.fileName}:${n.line+1}:${n.column+1})\n`}t+="\n"}return t}static postMessage(e){e&&("undefined"!=typeof window&&window.parent&&window.parent.postMessage&&window.parent.postMessage(e,"*"),Runtime.messagePosted&&Runtime.messagePosted(e))}static async postScreenshotAsync(e){const t=pxsim.runtime&&pxsim.runtime.board;if(!t)return;const n=await t.screenshotAsync();Runtime.postMessage({type:"screenshot",data:n,delay:e&&e.delay})}static requestToggleRecording(){const e=pxsim.runtime;e&&Runtime.postMessage({type:"recorder",action:e.recording?"stop":"start"})}restart(){this.kill(),setTimeout((()=>pxsim.Runtime.postMessage({type:"simulator",command:"restart"})),500)}kill(){this.dead=!0,this.stopRecording(),this.stopIdle(),this.setRunning(!1)}updateDisplay(){this.board.updateView(),this.postFrame()}startRecording(e){!this.recording&&this.running&&(this.recording=!0,this.recordingTimer=setInterval((()=>this.postFrame()),66),this.recordingLastImageData=void 0,this.recordingWidth=e)}stopRecording(){this.recording&&(this.recordingTimer&&clearInterval(this.recordingTimer),this.recording=!1,this.recordingTimer=0,this.recordingLastImageData=void 0,this.recordingWidth=void 0)}postFrame(){if(!this.recording||!this.running)return;let e=pxsim.U.now();this.board.screenshotAsync(this.recordingWidth).then((t=>{this.recordingLastImageData&&isImageDataEqual(this.recordingLastImageData,t)||(this.recordingLastImageData=t,Runtime.postMessage({type:"screenshot",data:t,time:e}))}))}queueDisplayUpdate(){this.numDisplayUpdates++}maybeUpdateDisplay(){this.numDisplayUpdates&&(this.numDisplayUpdates=0,this.updateDisplay())}setRunning(e){this.running!=e&&(this.running=e,this.running?(this.startTime=U.now(),this.startTimeUs=U.perfNowUs(),Runtime.postMessage({type:"status",frameid:pxsim.Embed.frameid,runtimeid:this.id,state:"running"})):(this.stopRecording(),this.stopIdle(),Runtime.postMessage({type:"status",frameid:pxsim.Embed.frameid,runtimeid:this.id,state:"killed"})),this.stateChanged&&this.stateChanged())}dumpLivePointers(){}setupPerfCounters(e){e&&e.length&&(this.perfCounters=e.map((e=>new PerfCounter(e))))}perfStartRuntime(){0!==this.perfOffset?this.perfStack++:this.perfOffset=U.perfNowUs()-this.perfElapsed}perfStopRuntime(){this.perfStack?this.perfStack--:(this.perfElapsed=this.perfNow(),this.perfOffset=0)}perfNow(){return 0===this.perfOffset&&U.userError("bad time now"),U.perfNowUs()-this.perfOffset|0}startPerfCounter(e){if(!this.perfCounters)return;const t=this.perfCounters[e];t.start&&U.userError("startPerf"),t.start=this.perfNow()}stopPerfCounter(e){if(!this.perfCounters)return;const t=this.perfCounters[e];t.start||U.userError("stopPerf");const n=this.perfNow()-t.start;t.start=0,t.value+=n,t.numstops++;let i=t.lastFewPtr++;i>=t.lastFew.length&&(i=0,t.lastFewPtr=1),t.lastFew[i]=n}startIdle(){void 0===this.idleTimer&&(this.idleTimer=setInterval((()=>{if(!this.running||this.pausedOnBreakpoint)return;const e=this.board.bus;e&&e.queueIdle()}),20))}stopIdle(){void 0!==this.idleTimer&&(clearInterval(this.idleTimer),this.idleTimer=void 0)}schedule(e,t){if(t<=0&&(t=0),this.pausedOnBreakpoint)return this.timeoutsPausedOnBreakpoint.push(new PausedTimeout(e,t)),-1;const n=U.now(),i=new TimeoutScheduled(-1,e,t,n);return i.id=setTimeout((()=>{const t=this.timeoutsScheduled.indexOf(i);t>=0&&this.timeoutsScheduled.splice(t,1),e()}),t),this.timeoutsScheduled.push(i),i.id}pauseScheduled(){this.pausedOnBreakpoint=!0,this.timeoutsScheduled.forEach((e=>{clearTimeout(e.id);let t=U.now()-e.timestampCall,n=e.totalRuntime-t;n<=0&&(n=1),this.timeoutsPausedOnBreakpoint.push(new PausedTimeout(e.fn,n))})),this.lastPauseTimestamp=U.now(),this.timeoutsScheduled=[]}resumeAllPausedScheduled(){this.pausedOnBreakpoint=!1,this.timeoutsPausedOnBreakpoint.forEach((e=>{this.schedule(e.fn,e.timeRemaining)})),this.lastPauseTimestamp&&(this.pausedTime+=U.now()-this.lastPauseTimestamp,this.lastPauseTimestamp=0),this.timeoutsPausedOnBreakpoint=[]}cleanScheduledExpired(){let e=U.now();this.timeoutsScheduled=this.timeoutsScheduled.filter((t=>{let n=e-t.timestampCall;return t.totalRuntime>n}))}registerUserInteraction(){this.lastInteractionTime=Date.now(),this.thumbnailRecordingIntervalRef||this.lastThumbnailTime&&this.lastInteractionTime-this.lastThumbnailTime<1e3||(this.thumbnailFrames=[],this.thumbnailRecordingIntervalRef=setInterval((async()=>{const e=await this.board.screenshotAsync();this.thumbnailFrames.length&&isImageDataEqual(e,this.thumbnailFrames[this.thumbnailFrames.length-1])||(this.thumbnailFrames.push(e),(Date.now()-this.lastInteractionTime>1e4||this.thumbnailFrames.length>30)&&(clearInterval(this.thumbnailRecordingIntervalRef),this.thumbnailRecordingIntervalRef=void 0,this.lastThumbnailTime=Date.now(),Runtime.postMessage({type:"thumbnail",frames:this.thumbnailFrames})))}),66))}}function setParentMuteState(e){Runtime.postMessage({type:"setmutebuttonstate",state:e})}pxsim.Runtime=Runtime,pxsim.setParentMuteState=setParentMuteState;class PerfCounter{constructor(e){this.name=e,this.start=0,this.numstops=0,this.value=0,this.lastFew=new Uint32Array(32),this.lastFewPtr=0}}function isImageDataEqual(e,t){if(e.data.byteLength!==t.data.byteLength)return!1;const n=e.data.byteLength;let i=0;for(i=0;i<n&&e.data[i]==t.data[i];++i);return i===n}pxsim.PerfCounter=PerfCounter}(pxsim||(pxsim={})),function(e){let t,n;!function(e){e[e.Unloaded=0]="Unloaded",e[e.Stopped=1]="Stopped",e[e.Pending=2]="Pending",e[e.Starting=3]="Starting",e[e.Running=4]="Running",e[e.Paused=5]="Paused",e[e.Suspended=6]="Suspended"}(t=e.SimulatorState||(e.SimulatorState={})),function(e){e[e.StepInto=0]="StepInto",e[e.StepOver=1]="StepOver",e[e.StepOut=2]="StepOut",e[e.Resume=3]="Resume",e[e.Pause=4]="Pause"}(n=e.SimulatorDebuggerCommand||(e.SimulatorDebuggerCommand={}));const i="pxtdriver";e.SimulatorDriver=class{constructor(n,i={}){this.container=n,this.options=i,this.themes=["blue","red","green","yellow"],this.runId="",this.nextFrameId=0,this.frameCounter=0,this.traceInterval=0,this.breakpointsSet=!1,this._runOptions={},this.state=t.Unloaded,this._allowedOrigins=[],this.frameCleanupTimeout=void 0,this.debuggerSeq=1,this.debuggerResolvers={},this._allowedOrigins.push(window.location.origin),i.parentOrigin&&this._allowedOrigins.push(i.parentOrigin),this._allowedOrigins.push(this.getSimUrl().origin);const s=null==i?void 0:i.messageSimulators;s&&Object.keys(s).map((e=>s[e])).forEach((e=>{this._allowedOrigins.push(new URL(e.url).origin),e.localHostUrl&&this._allowedOrigins.push(new URL(e.localHostUrl).origin)})),this._allowedOrigins=e.U.unique(this._allowedOrigins,(e=>e))}isDebug(){return this._runOptions&&!!this._runOptions.debug}isTracing(){return this._runOptions&&!!this._runOptions.trace}hasParts(){return this._runOptions&&this._runOptions.parts&&!!this._runOptions.parts.length}setDirty(){this.state==e.SimulatorState.Running&&this.suspend()}setPending(){this.setState(t.Pending)}focus(){const e=this.simFrames()[0];e&&e.focus()}registerDependentEditor(e){e&&(this._dependentEditors||(this._dependentEditors=[]),this._dependentEditors.push(e))}dependentEditors(){return this._dependentEditors&&(this._dependentEditors=this._dependentEditors.filter((e=>!!e.parent)),this._dependentEditors.length||(this._dependentEditors=void 0)),this._dependentEditors}setStarting(){this.setState(t.Starting)}setHwDebugger(e){e?(this.hwdbg=e,this.setState(t.Running),this.container.style.opacity="0.3"):(delete this.container.style.opacity,this.hwdbg=null,this.setState(t.Running),this.stop())}handleHwDebuggerMsg(e){this.hwdbg&&this.handleMessage(e)}setThemes(t){e.U.assert(t&&t.length>0),this.themes=t}startRecording(e){this.simFrames()[0]&&this.postMessage({type:"recorder",action:"start",source:i,width:e})}stopRecording(){this.postMessage({type:"recorder",source:i,action:"stop"})}setFrameState(n){const i=n.nextElementSibling,s=i.nextElementSibling;switch(this.state){case t.Pending:case t.Starting:i.style.display="",i.className="",s.style.display="";break;case t.Stopped:case t.Suspended:e.U.addClass(n,this.state==t.Stopped||this._runOptions&&this._runOptions.autoRun?this.stoppedClass:this.invalidatedClass),this._runOptions&&this._runOptions.autoRun?i.style.display="none":(i.style.display="",i.className="videoplay xicon icon"),s.style.display="none",this.scheduleFrameCleanup();break;default:e.U.removeClass(n,this.stoppedClass),e.U.removeClass(n,this.invalidatedClass),i.style.display="none",s.style.display="none"}}setState(e){this.state!=e&&(this.state=e,this.freeze(this.state==t.Paused),this.simFrames().forEach((e=>this.setFrameState(e))),this.options.onStateChanged&&this.options.onStateChanged(this.state))}freeze(t){const n="pause-overlay";t?e.util.toArray(this.container.querySelectorAll("div.simframe")).forEach((e=>{if(e.querySelector(`div.${n}`))return;const t=document.createElement("div");t.className=n,t.onclick=e=>(e.preventDefault(),!1),e.appendChild(t)})):e.util.toArray(this.container.querySelectorAll(`div.simframe div.${n}`)).forEach((e=>e.parentElement.removeChild(e)))}simFrames(t=!1){let n=e.util.toArray(this.container.getElementsByTagName("iframe"));const i=this.loanedIFrame();return i&&!t&&n.unshift(i),n}getSimUrl(){var e,t;const n=this.options.simUrl||(null===(e=window.pxtConfig)||void 0===e?void 0:e.simUrl)||(null===(t=pxt.webConfig)||void 0===t?void 0:t.simUrl)||`${location.origin}/sim/simulator.html`;try{return new URL(n)}catch(e){return new URL(n,location.origin)}}postMessage(t,n,i){var s;if(this.hwdbg)return void this.hwdbg.postMessage(t);const r=this.dependentEditors();let o=this.simFrames();i&&(o=o.filter((e=>e.id===i)));let a=!1;const l=t;if(n&&(null==l?void 0:l.broadcast)){l.srcFrameIndex=this.simFrames().findIndex((e=>e.contentWindow===n));const i=!!(null===(s=this._currentRuntime)||void 0===s?void 0:s.single),c=window.parent&&window.parent!==window.window?window.parent:window.opener;if(c&&n!==c&&c.postMessage(t,"*"),!this.options.nestedEditorSim&&!(null==l?void 0:l.toParentIFrameOnly))if(r)r.forEach((e=>{n!==e&&e.postMessage(t,window.location.origin)}));else if(!i){const n="messagepacket"===t.type&&t.channel,i=n&&this.options.messageSimulators&&this.options.messageSimulators[n];if(i){let t=o.find((e=>e.dataset.messagechannel===n));if(t)t.dataset.runid!=this.runId&&this.startFrame(t);else{const s=(e.U.isLocalHost()&&/localhostmessagesims=1/i.test(window.location.href)&&i.localHostUrl||i.url).replace("$PARENT_ORIGIN$",encodeURIComponent(this.options.parentOrigin||"")).replace("$LANGUAGE$",encodeURIComponent(this.options.userLanguage));let r=this.createFrame(s);this.container.appendChild(r),t=r.firstElementChild,t.dataset.messagechannel=n,e.U.addClass(r,"simmsg"),e.U.addClass(r,"simmsg"+n),i.permanent&&(t.dataset.permanent="true"),this.startFrame(t),o=this.simFrames()}}else{a=!0;const e=o.filter((e=>!e.dataset.messagechannel));e.length<2?(this.container.appendChild(this.createFrame()),o=this.simFrames()):e[1].dataset.runid!=this.runId&&this.startFrame(e[1])}}}for(let e=0;e<o.length;++e){const i=o[e];if((!n||i.contentWindow!=n)&&(i.contentWindow&&(a?this.postDeferrableMessage(i,t):this.postMessageCore(i,t),"recorder"==t.type&&"start"==t.action)))break}}postDeferrableMessage(e,t){!e.dataset.loading?this.postMessageCore(e,t):(this.deferredMessages||(this.deferredMessages=[]),this.deferredMessages.push([e,t]))}postMessageCore(t,n){const i=e.U.isLocalHostDev()?"*":t.dataset.origin;t.contentWindow.postMessage(n,i)}setRunOptionQueryParams(e){var t,n;const i=new URL(e);if((null===(t=this._runOptions)||void 0===t?void 0:t.hideSimButtons)&&i.searchParams.set("hideSimButtons","1"),null===(n=this._runOptions)||void 0===n?void 0:n.queryParameters){const e=this._runOptions.queryParameters.split("&");for(const t of e){const[e,n]=t.split(/[:=]/);e&&n&&i.searchParams.set(e,n)}}return i.toString()}createFrame(n){var i;const s=document.createElement("div");s.className="simframe ui embed";const r=document.createElement("iframe");r.id="sim-frame-"+this.nextId(),r.title=e.localization.lf("Simulator"),r.allowFullscreen=!0,r.setAttribute("allow","autoplay;microphone"),r.setAttribute("sandbox","allow-same-origin allow-scripts"),r.className="no-select";let o=this.setRunOptionQueryParams(n||this.getSimUrl().toString());o+="#"+r.id,r.src=o,r.frameBorder="0",r.dataset.runid=this.runId,r.dataset.origin=new URL(o).origin||"*",r.dataset.loading="true",(null===(i=this._runOptions)||void 0===i?void 0:i.autofocus)&&r.setAttribute("autofocus","true"),s.appendChild(r);const a=document.createElement("i");a.className="videoplay xicon icon",a.style.display="none",a.onclick=e=>(e.preventDefault(),this.state!=t.Running&&this.state!=t.Starting&&(this.options.restart?this.options.restart():this.start()),r.focus(),!1),s.appendChild(a);const l=document.createElement("div");return l.className="ui active loader",a.style.display="none",s.appendChild(l),this._runOptions&&this.applyAspectRatioToFrame(r),s}preload(e,t){this.addEventListeners(),t&&(this._currentRuntime=void 0,this.container.textContent=""),this.simFrames().length||(this.container.appendChild(this.createFrame()),this.applyAspectRatio(e),this.setStarting())}stop(e=!1,n=!1){this.state!==t.Stopped&&this.state!==t.Unloaded&&(this.clearDebugger(),this.stopSound(),this.postMessage({type:"stop",source:i}),this.setState(n?t.Starting:t.Stopped)),e&&this.unload()}suspend(){this.stopSound(),this.postMessage({type:"stop",source:i}),this.setState(t.Suspended)}unload(){this.cancelFrameCleanup(),e.U.removeChildren(this.container),this.setState(t.Unloaded),this._runOptions=void 0,this._currentRuntime=void 0,this.runId=void 0,this.deferredMessages=void 0}mute(e){this._currentRuntime&&(this._currentRuntime.mute=e),this.postMessage({type:"mute",source:i,mute:e})}stopSound(){this.postMessage({type:"stopsound",source:i})}isLoanedSimulator(e){return!!this.loanedSimulator&&this.loanedIFrame()==e}loanSimulator(){return this.loanedSimulator||(this.loanedSimulator=this.container.firstElementChild||this.createFrame(),this.loanedSimulator.parentNode&&this.container.removeChild(this.loanedSimulator)),this.loanedSimulator}unloanSimulator(){this.loanedSimulator&&(this.loanedSimulator.parentNode&&this.loanedSimulator.parentNode.removeChild(this.loanedSimulator),this.container.insertBefore(this.loanedSimulator,this.container.firstElementChild),delete this.loanedSimulator)}loanedIFrame(){return this.loanedSimulator&&this.loanedSimulator.parentNode&&this.loanedSimulator.querySelector("iframe")}cancelFrameCleanup(){this.frameCleanupTimeout&&(clearTimeout(this.frameCleanupTimeout),this.frameCleanupTimeout=void 0)}scheduleFrameCleanup(){this.cancelFrameCleanup(),this.frameCleanupTimeout=setTimeout((()=>{this.frameCleanupTimeout=void 0,this.cleanupFrames()}),5e3)}applyAspectRatio(e){if(!e&&!this._runOptions)return;this.simFrames().forEach((t=>this.applyAspectRatioToFrame(t,e)))}applyAspectRatioToFrame(e,t){var n,i,s,r;let o=t;if(void 0===o){const t=parseFloat(e.dataset.aspectratio);isNaN(t)||(o=t)}if(void 0===o){const t=e.dataset.messagechannel;if(t){const e=null===(s=null===(i=null===(n=this.options)||void 0===n?void 0:n.messageSimulators)||void 0===i?void 0:i[t])||void 0===s?void 0:s.aspectRatio;e&&(o=e)}}void 0===o&&(o=(null===(r=this._runOptions)||void 0===r?void 0:r.aspectRatio)||1.22),e.parentElement.style.paddingBottom=100/o+"%"}cleanupFrames(){const e=this.simFrames(!0);e.shift(),e.filter((e=>!e.dataset.permanent)).forEach((e=>{this.state!=t.Stopped&&e.dataset.runid==this.runId||(this.options.removeElement?this.options.removeElement(e.parentElement):e.parentElement.remove())}))}hide(e){if(this.suspend(),!this.options.removeElement)return;const t=this.simFrames();t.forEach((t=>{this.options.removeElement(t.parentElement,e)})),0==t.length&&e&&e()}unhide(){if(!this.options.unhideElement)return;this.simFrames().forEach((e=>{this.options.unhideElement(e.parentElement)}))}setRunOptions(e={}){this._runOptions=e}run(e,t={}){this.setRunOptions(t),this.runId=this.nextId(),this._currentRuntime={type:"run",source:i,boardDefinition:t.boardDefinition,parts:t.parts,builtinParts:t.builtinParts,fnArgs:t.fnArgs,code:e,partDefinitions:t.partDefinitions,mute:t.mute,highContrast:t.highContrast,light:t.light,cdnUrl:t.cdnUrl,localizedStrings:t.localizedStrings,refCountingDebug:t.refCountingDebug,version:t.version,clickTrigger:t.clickTrigger,breakOnStart:t.breakOnStart,storedState:t.storedState,ipc:t.ipc,single:t.single,dependencies:t.dependencies,activePlayer:t.activePlayer,theme:t.theme},this.stopSound(),this.start()}restart(){this.stop(),this.cleanupFrames(),this.start()}areBreakpointsSet(){return this.breakpointsSet}start(){if(this.clearDebugger(),this.addEventListeners(),this.applyAspectRatio(),this.scheduleFrameCleanup(),!this._currentRuntime)return;this.breakpointsSet=!1;let e=this.simFrames()[0];if(e)this.startFrame(e);else{let t=this.createFrame();this.container.appendChild(t),e=t.firstElementChild}this.debuggingFrame=e.id,this.setState(t.Running),this.setTraceInterval(this.traceInterval)}startFrame(e){var t,n,i;if(!this._currentRuntime||!e.contentWindow)return!1;const s=JSON.parse(JSON.stringify(this._currentRuntime));s.frameCounter=++this.frameCounter;const r=(null===(t=this._runOptions)||void 0===t?void 0:t.mpRole)||(null===(i=null===(n=/[\&\?]mp=(server|client)/i.exec(window.location.href))||void 0===n?void 0:n[1])||void 0===i?void 0:i.toLowerCase());return s.options={theme:this.themes[this.nextFrameId++%this.themes.length],mpRole:r},s.id=`${s.options.theme}-${this.nextId()}`,e.dataset.runid=this.runId,e.dataset.runtimeid=s.id,e.id!==this.debuggingFrame&&(s.traceDisabled=!0,s.breakOnStart=!1),this.postMessageCore(e,s),this.traceInterval&&this.setTraceInterval(this.traceInterval),this.applyAspectRatioToFrame(e),this.setFrameState(e),!0}handleDeferredMessages(e){var t,n,i;e.dataset.loading&&(delete e.dataset.loading,null===(n=null===(t=this.deferredMessages)||void 0===t?void 0:t.filter((t=>t[0]===e)))||void 0===n||n.forEach((t=>{const[n,i]=t;this.postMessageCore(e,i)})),this.deferredMessages=null===(i=this.deferredMessages)||void 0===i?void 0:i.filter((t=>t[0]!==e)))}handleMessage(e,n){var i,s,r;switch(e.type||""){case"ready":{const t=e.frameid,n=document.getElementById(t);n&&((null===(i=this._runOptions)||void 0===i?void 0:i.autofocus)&&n.focus(),this.startFrame(n),this.options.revealElement&&this.options.revealElement(n),this.handleDeferredMessages(n)),this.options.onSimulatorReady&&this.options.onSimulatorReady();break}case"status":{const n=e.frameid,i=document.getElementById(n);if(i){const n=e;if(n.runtimeid==i.dataset.runtimeid)switch(n.state){case"running":this.setState(t.Running),this.handleDeferredMessages(i);break;case"killed":this.setState(t.Stopped)}}break}case"simulator":this.handleSimulatorCommand(e);break;case"serial":case"pxteditor":case"screenshot":case"custom":case"recorder":case"addextensions":break;case"aspectratio":{const t=e,n=t.frameid,i=document.getElementById(n);i&&(i.dataset.aspectratio=t.value+"",this.applyAspectRatioToFrame(i));break}case"debugger":this.handleDebuggerMessage(e);break;case"toplevelcodefinished":this.options.onTopLevelCodeEnd&&this.options.onTopLevelCodeEnd();break;case"setmutebuttonstate":null===(r=(s=this.options).onMuteButtonStateChange)||void 0===r||r.call(s,e.state);break;default:this.postMessage(e,n)}}addEventListeners(){this.listener||(this.listener=t=>{if(!this.hwdbg){if(e.U.isLocalHost());else if(this._allowedOrigins.indexOf(t.origin)<0)return;this.handleMessage(t.data,t.source)}},window.addEventListener("message",this.listener,!1))}removeEventListeners(){this.listener&&(window.removeEventListener("message",this.listener,!1),this.listener=void 0)}resume(e){let s;switch(e){case n.Resume:s="resume",this.setState(t.Running);break;case n.StepInto:s="stepinto",this.setState(t.Running);break;case n.StepOut:s="stepout",this.setState(t.Running);break;case n.StepOver:s="stepover",this.setState(t.Running);break;case n.Pause:s="pause";break;default:return void console.debug("unknown command")}this.postMessage({type:"debugger",subtype:s,source:i})}setBreakpoints(e){this.breakpointsSet=!0,this.postDebuggerMessage("config",{setBreakpoints:e},void 0,this.debuggingFrame)}setTraceInterval(e){this.traceInterval=e,this.postDebuggerMessage("traceConfig",{interval:e})}variablesAsync(e,t,n=!1){return this.postDebuggerMessageAsync("variables",{variablesReference:e,fields:t,includeAll:n},this.debuggingFrame).then((e=>e),(e=>{}))}handleSimulatorCommand(e){this.options.onSimulatorCommand&&this.options.onSimulatorCommand(e)}clearDebugger(){const e=new Error("Debugging cancelled");Object.keys(this.debuggerResolvers).forEach((t=>{const{reject:n}=this.debuggerResolvers[t];n(e)})),this.debuggerResolvers={},this.debuggerSeq++}handleDebuggerMessage(e){if("trace"!==e.subtype&&console.log("DBG-MSG",e.subtype,e),e.seq){const{resolve:t}=this.debuggerResolvers[e.seq];t&&t(e)}switch(e.subtype){case"warning":this.options.onDebuggerWarning&&this.options.onDebuggerWarning(e);break;case"breakpoint":{const i=e;if(this.state==t.Running){if(i.exceptionMessage)this.suspend();else{this.setState(t.Paused);this.simFrames(!0).length>1&&this.resume(n.Pause)}this.options.onDebuggerBreakpoint&&this.options.onDebuggerBreakpoint(i);let e=i.exceptionMessage+"\n";for(let t of i.stackframes){let n=t.funcInfo;e+=` at ${n.functionName} (${n.fileName}:${n.line+1}:${n.column+1})\n`}i.exceptionMessage&&console.error(e)}else console.error("debugger: trying to pause from "+this.state);break}case"trace":{const n=e;this.state==t.Running&&this.options.onTraceMessage&&this.options.onTraceMessage(n);break}default:const i=e.req_seq;if(i){const{resolve:t}=this.debuggerResolvers[i];t&&(delete this.debuggerResolvers[i],t(e))}}}postDebuggerMessageAsync(e,t={},n){return new Promise(((i,s)=>{const r=this.debuggerSeq++;this.debuggerResolvers[r.toString()]={resolve:i,reject:s},this.postDebuggerMessage(e,t,r,n)}))}postDebuggerMessage(e,t={},n,s){const r=JSON.parse(JSON.stringify(t));r.type="debugger",r.subtype=e,r.source=i,n&&(r.seq=n),this.postMessage(r,void 0,s)}nextId(){return this.nextFrameId+++(Math.random()+""+Math.random()).replace(/[^\d]/,"")}get stoppedClass(){return this.options&&this.options.stoppedClass||"grayscale"}get invalidatedClass(){return this.options&&this.options.invalidatedClass||"sepia"}}}(pxsim||(pxsim={})),function(e){e.mkRange=function(e,t){let n=[];for(;e<t;e++)n.push(e);return n};e.EventBus=class{constructor(e,t,n){this.runtime=e,this.board=t,this.valueToArgs=n,this.queues={},this.backgroundHandlerFlag=!1,this.nextNotifyEvent=1024,this.schedulerID=15,this.idleEventID=2,this.board.addMessageListener(this.handleMessage.bind(this))}handleMessage(e){if("eventbus"===e.type){const t=e;this.queue(t.id,t.eventid,t.value)}}setBackgroundHandlerFlag(){this.backgroundHandlerFlag=!0}setNotify(e,t){this.notifyID=e,this.notifyOneID=t}setIdle(e,t){this.schedulerID=e,this.idleEventID=t}start(t,n,i,s=!1){let r=(i?"back":"fore")+":"+t+":"+n;return!this.queues[r]&&s&&(this.queues[r]=new e.EventQueue(this.runtime,this.valueToArgs)),this.queues[r]}listen(e,t,n,i=0){e==this.schedulerID&&t==this.idleEventID&&this.runtime.startIdle();let s=this.start(e,t,this.backgroundHandlerFlag,!0);this.backgroundHandlerFlag?s.addHandler(n,i):s.setHandler(n,i),this.backgroundHandlerFlag=!1}removeBackgroundHandler(e){Object.keys(this.queues).forEach((t=>{t.startsWith("back:")&&this.queues[t].removeHandler(e)}))}getQueues(e,t,n){let i=[this.start(0,0,n)];return 0==e&&0==t||(t&&i.push(this.start(0,t,n)),e&&i.push(this.start(e,0,n)),e&&t&&i.push(this.start(e,t,n))),i}queue(t,n,i=null){if(e.runtime.pausedOnBreakpoint)return;const s=this.notifyID&&this.notifyOneID&&t==this.notifyOneID;s&&(t=this.notifyID);let r=this.getQueues(t,n,!0).concat(this.getQueues(t,n,!1));this.lastEventValue=n,this.lastEventTimestampUs=e.U.perfNowUs(),e.U.promiseMapAllSeries(r,(e=>e?e.push(i,s):Promise.resolve()))}queueIdle(){this.schedulerID&&this.idleEventID&&this.queue(this.schedulerID,this.idleEventID)}wait(e,t,n){this.start(e,t,!1,!0).addAwaiter(n)}getLastEventValue(){return this.lastEventValue}getLastEventTime(){return 4294967295&this.lastEventTimestampUs-e.runtime.startTimeUs}};let t;function n(){return"undefined"!=typeof window&&("ontouchstart"in window||navigator&&navigator.maxTouchPoints>0)}function i(){return"undefined"!=typeof window&&!!window.PointerEvent}e.AnimationQueue=class{constructor(e){this.runtime=e,this.queue=[],this.process=()=>{let t=this.queue[0];if(!t)return;if(this.runtime.dead)return;e=this.runtime;let n=t.frame();e.queueDisplayUpdate(),e.maybeUpdateDisplay(),!1===n?(this.queue.shift(),this.queue[0]&&(this.queue[0].setTimeoutHandle=setTimeout(this.process,this.queue[0].interval)),t.whenDone(!1)):t.setTimeoutHandle=setTimeout(this.process,t.interval)}}cancelAll(){let e=this.queue;this.queue=[];for(let t of e)t.whenDone(!0),t.setTimeoutHandle&&clearTimeout(t.setTimeoutHandle)}cancelCurrent(){let e=this.queue[0];e&&(this.queue.shift(),e.whenDone(!0),e.setTimeoutHandle&&clearTimeout(e.setTimeoutHandle))}enqueue(e){e.whenDone||(e.whenDone=()=>{}),this.queue.push(e),1==this.queue.length&&this.process()}executeAsync(t){return e.U.assert(!t.whenDone),new Promise(((e,n)=>{t.whenDone=e,this.enqueue(t)}))}},function(t){let n,i,s,r,o=0,a=!1;const l=[];let c,u=[];function d(){return n||(n=function(){if(window.AudioContext=window.AudioContext||window.webkitAudioContext,window.AudioContext)try{return new window.AudioContext}catch(e){}return}(),n&&(c=n.createGain(),c.connect(n.destination),c.gain.setValueAtTime(1,0))),n}function h(){E(0),o=0,r&&r.pause()}function p(e,t){e.gain.value&&e.gain.setTargetAtTime(0,d().currentTime,.015),setTimeout((()=>{e.disconnect(),t&&t.disconnect()}),450)}t.isAudioElementActive=function(){return!!s},t.mute=function(e){a=e;const t=d();e?c.gain.setTargetAtTime(0,t.currentTime,.015):c.gain.setTargetAtTime(1,t.currentTime,.015),!e&&t&&"suspended"===t.state&&t.resume()},t.isMuted=function(){return a},t.stopAll=function(){h(),x();for(const e of u)e()},t.stop=function(){h(),function(){if(s){try{p(s,i)}catch(e){}s=void 0,i=void 0}}()},t.onStopAll=function(e){u.push(e)},t.frequency=function(){return o};const f=[null,"triangle","sawtooth","sine"];let m,g,b=[],y=[];function v(e,t){let n,i=f[e];if(i){let e=d().createOscillator();return e.type=i,e.frequency.value=t,e}if(4==e)n=function(){if(!g){const e=131072;g=d().createBuffer(1,e,d().sampleRate);const t=g.getChannelData(0);let n=251771520;for(let i=0;i<e;i+=4)n^=n<<13,n^=n>>17,n^=n<<5,32768&n?(t[i]=1,t[i+1]=1,t[i+2]=-1,t[i+3]=-1):(t[i]=0,t[i+1]=0,t[i+2]=0,t[i+3]=0)}return g}();else if(5==e)n=function(){if(!m){const e=1e5;m=d().createBuffer(1,e,d().sampleRate);const t=m.getChannelData(0);let n=251771520;for(let i=0;i<e;i++)n^=n<<13,n^=n>>17,n^=n<<5,t[i]=(1023&n)/512-1}return m}();else if(11<=e&&e<=15)n=function(e){if(!y[e]){const t=1024,n=d().createBuffer(1,t,d().sampleRate),i=n.getChannelData(0);for(let n=0;n<t;n++)i[n]=n<e/100*t?1:-1;y[e]=n}return y[e]}(10*(e-10));else{if(!(16<=e&&e<=18))return null;n=function(e){if(!b[e]){const t=1024,n=d().createBuffer(1,t,d().sampleRate),i=n.getChannelData(0),s=[770763591,3356908179],r=[15,31,63];for(let n=0;n<t;n+=4){let t,o=n/4;o&=r[e-4],t=0!=(s[o>>5]&1<<(31&o)),t?(i[n]=1,i[n+1]=1,i[n+2]=-1,i[n+3]=-1):(i[n]=0,i[n+1]=0,i[n+2]=0,i[n+3]=0)}b[e]=n}return b[e]}(e-16+4)}let s=d().createBufferSource();s.buffer=n,s.loop=!0;return 4==e||16<=e&&e<=18?s.playbackRate.value=t/(d().sampleRate/4):5!=e&&(s.playbackRate.value=t/(d().sampleRate/1024)),s}class w{disconnectNodes(){this.gain?p(this.gain,this.generator):this.generator&&(this.generator.stop(),this.generator.disconnect()),this.gain=null,this.generator=null}remove(){const e=l.indexOf(this);e>=0&&l.splice(e,1),this.disconnectNodes()}}let k=1;function x(){for(null===t.soundEventCallback||void 0===t.soundEventCallback||t.soundEventCallback("muteallchannels"),k++;l.length;)l[0].remove()}function A(e,t){if(e<0)return;o=e;let n=d();if(n){t=Math.max(0,Math.min(1,t));try{i||(i=n.createOscillator(),s=n.createGain(),s.gain.value=0,i.type="triangle",i.connect(s),s.connect(c),i.start(0)),E(t)}catch(e){return i=void 0,void(s=void 0)}i.frequency.value=e,E(t)}}function E(e){(null==s?void 0:s.gain)&&s.gain.setTargetAtTime(e,n.currentTime,.015)}t.muteAllChannels=x,t.queuePlayInstructions=function(t,n){const i=k;e.U.delay(t).then((()=>i!=k?Promise.resolve():T(n.data)))},t.tone=A,t.setCurrentToneGain=E,t.playBufferAsync=function(e){return e?new Promise((t=>{function n(){t&&t(),t=void 0}const i="data:audio/wav;base64,"+window.btoa(function(e){let t=e.length,n="";for(let i=0;i<t;++i)n+=String.fromCharCode(e[i]);return n}(e.data));r=new Audio(i),a&&(r.volume=0),r.onended=()=>n(),r.onpause=()=>n(),r.onerror=()=>n(),r.play()})):Promise.resolve()};function T(n,i,s){return new Promise((async r=>{null===t.soundEventCallback||void 0===t.soundEventCallback||t.soundEventCallback("playinstructions",n);let o=!1,a=d(),u=new w;l.length>20&&l[0].remove(),l.push(u),u.gain=a.createGain(),u.gain.gain.value=1,u.gain.connect(c);const h={},p={};let f=a.currentTime,m=f,g=0,b=0;const y=(e,t)=>e/1024/4*(t?.5:1),k=()=>{if(!o){o=!0,u.disconnectNodes();for(const e of Object.keys(h))h[e].stop(),h[e].disconnect(),p[e].disconnect();r()}};for(let e=0;e<n.length;e+=12){const t=n[e],i=S(n,e+2),s=S(n,e+4)/1e3,r=S(n,e+6),o=S(n,e+8),l=S(n,e+10);if(b+=s,0===t){m+=s;continue}const c=11<=t&&t<=15;h[t]||(h[t]=v(t,i),p[t]=a.createGain(),p[t].gain.value=0,p[t].connect(u.gain),h[t].connect(p[t]),h[t].start()),g&&t!==g&&p[g].gain.setTargetAtTime(0,m,.015);const d=h[t],f=p[t];if(d instanceof OscillatorNode)d.frequency.setValueAtTime(i,m),d.frequency.linearRampToValueAtTime(l,m+s);else{4==t||16<=t&&t<=18?d.playbackRate.linearRampToValueAtTime(l/(a.sampleRate/4),m+s):5!=t&&d.playbackRate.linearRampToValueAtTime(l/(a.sampleRate/1024),m+s)}f.gain.setValueAtTime(y(r,c),m),f.gain.linearRampToValueAtTime(y(o,c),m+s),g=t,m+=s}if(u.gain.gain.setTargetAtTime(0,m,.015),i||s){const e=()=>{const t=a.currentTime;if(t>f+b)return;if(i&&i())return void k();const{frequency:r,volume:o}=function(e,t){let n=0;for(let i=0;i<t.length;i+=12){const s=S(t,i+2),r=S(t,i+4),o=S(t,i+6),a=S(t,i+8),l=S(t,i+10);if(n+r<e){n+=r;continue}const c=(e-n)/r;return{frequency:s+(l-s)*c,volume:o+(a-o)*c}}return{frequency:-1,volume:-1}}(1e3*(t-f),n);s&&s(r,o/1024),requestAnimationFrame(e)};requestAnimationFrame(e)}await e.U.delay(1e3*b),k()}))}function S(e,t){const n=new Uint8Array(2);return n[0]=e[t],n[1]=e[t+1],new Uint16Array(n.buffer)[0]}t.playPCMBufferStreamAsync=function(e,t,n=.3,i){return new Promise((s=>{let r=[],o=d().currentTime,a=!1;const u=new w;u.gain=d().createGain(),u.gain.gain.value=0,u.gain.gain.setValueAtTime(n,d().currentTime),u.gain.connect(c),l.length>20&&l[0].remove(),l.push(u);const h=()=>!!(i&&i()||!u.gain)&&(s&&s(),s=void 0,u.remove(),!0);function p(){for(;!a&&r.length<3&&!h();){const t=e();if(!t||!t.length){a=!0;break}f(t)}a&&0===r.length&&(u.remove(),s&&s(),s=void 0)}function f(e){if(h())return;const n=d().createBuffer(1,e.length,t);if(n.copyToChannel)n.copyToChannel(e,0);else{const t=n.getChannelData(0);for(let n=0;n<e.length;n++)t[n]=e[n]}const i=d().createBufferSource();r.push(i),i.connect(u.gain),i.buffer=n,i.addEventListener("ended",(()=>{r.shift().disconnect(),p()})),i.start(o),o+=n.duration}p()}))},t.playInstructionsAsync=T,t.sendMidiMessage=function(e){const t=e.data;if(!t.length)return;const n=t[0]>>4,i=15&t[0],s=t[1]||0,r=(o=s,440*Math.pow(2,(o-69)/12));var o;const a=t[2]||0;8==n||9==n&&0==a?h():9==n&&(A(r,1),9==i&&setTimeout((()=>h()),500))}}(t=e.AudioContextManager||(e.AudioContextManager={})),e.isTouchEnabled=n,e.hasPointerEvents=i,e.pointerEvents=i()?{up:"pointerup",down:["pointerdown"],move:"pointermove",enter:"pointerenter",leave:"pointerleave"}:n()?{up:"mouseup",down:["mousedown","touchstart"],move:"touchmove",enter:"touchenter",leave:"touchend"}:{up:"mouseup",down:["mousedown"],move:"mousemove",enter:"mouseenter",leave:"mouseleave"}}(pxsim||(pxsim={})),function(e){!function(t){function n(e,t){return n=>n*(t/e)}function i(e,t){let n=e[0]-t[0],i=e[1]-t[1];return n*n+i*i}t.translateEl=function(t,n){e.svg.hydrate(t,{transform:`translate(${n[0]} ${n[1]})`})},t.composeSVG=function(t){let[n,i]=[t.el1,t.el2];e.U.assert(0==n.x&&0==n.y&&0==i.x&&0==i.y,"el1 and el2 x,y offsets not supported");let s=(t,n,i)=>e.svg.hydrate(t,{x:n,y:i}),r=(t,n,i)=>e.svg.hydrate(t,{width:`${n}px`,height:`${i}px`}),o=t.scaleUnit2,a=t.scaleUnit2/t.scaleUnit1,l=n.w*a,c=n.h*a;r(n.el,l,c);let u=1*i.w,d=1*i.h;r(i.el,u,d);let[h,p,f,m]=t.margin,g=t.middleMargin,b=Math.max(l,u),y=p+(b-l)/2,v=h;s(n.el,y,v);let w=p+(b-u)/2,k=v+c+g;s(i.el,w,k);let x=[v,v+c,k,k+d],A=p+b+m,E=h+c+g+d+f,T=e.svg.elt("svg",{version:"1.0",viewBox:`0 0 ${A} ${E}`,class:"sim-bb"});((t,n,i)=>{n&&e.svg.hydrate(t,{width:n}),i&&e.svg.hydrate(t,{height:i})})(T,t.maxWidth,t.maxHeight),s(T,0,0);let S=e.svg.child(T,"g");return T.appendChild(n.el),T.appendChild(i.el),{under:S,over:e.svg.child(T,"g"),host:T,edges:x,scaleUnit:o,toHostCoord1:e=>{let[t,n]=e;return[t*a+y,n*a+v]},toHostCoord2:e=>{let[t,n]=e;return[1*t+w,1*n+k]}}},t.mkScaleFn=n,t.mkImageSVG=function(t){let i=n(t.imageUnitDist,t.targetUnitDist),s=i(t.width),r=i(t.height),o=e.svg.elt("image",{width:s,height:r});return o.setAttributeNS("http://www.w3.org/1999/xlink","href",`${t.image}`),{el:o,w:s,h:r,x:0,y:0}},t.findDistSqrd=i,t.findClosestCoordIdx=function(e,t){return t.map((t=>i(e,t))).reduce(((e,t,n,i)=>t<i[e]?n:e),0)},t.mkTxt=function(t,n,i,s,r,o,a){let l=e.svg.elt("text");a=a||.3;const c=(o=o||-.33333)*i*r.length,u=a*i;return e.svg.hydrate(l,{style:`font-size:${i}px;`,transform:`translate(${t} ${n}) rotate(${s}) translate(${c} ${u})`}),e.U.addClass(l,"noselect"),l.textContent=r,l},t.GPIO_WIRE_COLORS=["pink","orange","yellow","green","purple"],t.WIRE_COLOR_MAP={black:"#514f4d",white:"#fcfdfc",gray:"#acabab",purple:"#a772a1",blue:"#01a6e8",green:"#3cce73",yellow:"#ece600",orange:"#fdb262",red:"#f44f43",brown:"#c89764",pink:"#ff80fa"},t.mapWireColor=function(e){return t.WIRE_COLOR_MAP[e]||e},t.PIN_DIST=15,t.rgbToHsl=function(e){let t,n,i,[s,r,o]=e,[a,l,c]=[s/255,r/255,o/255],u=Math.min(a,l,c),d=Math.max(a,l,c),h=d-u,p=d+u;return i=p/2*100,0===h?n=t=0:(d===a?t=(l-c)/h%6*60:d===l?t=60*((c-a)/h+2):d===c&&(t=60*((a-l)/h+4)),n=i>50?h/(2-p)*100:h/p*100),[Math.floor(t),Math.floor(n),Math.floor(i)]}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){var t;!function(n){function i(e,n,i){let s={class:e,d:n};i&&(s.title=i);let r=t.elt("path");return t.hydrate(r,s),r}function s(e,n=!1){let i=t.elt("linearGradient");t.hydrate(i,{id:e,x1:"0%",y1:"0%",x2:n?"100%":"0%",y2:n?"0%":"100%"});t.child(i,"stop",{offset:"0%"}),t.child(i,"stop",{offset:"100%"}),t.child(i,"stop",{offset:"100%"}),t.child(i,"stop",{offset:"100%"});return i}function r(e){let n=t.elt("title");return n.textContent=e,n}n.parseString=function(e){return(new DOMParser).parseFromString(e,"image/svg+xml").getElementsByTagName("svg").item(0)},n.toDataUri=function(e){return"data:image/svg+xml,"+encodeURI(e)},n.cursorPoint=function(e,t,n){return e.x=null!=n.clientX?n.clientX:n.pageX,e.y=null!=n.clientY?n.clientY:n.pageY,e.matrixTransform(t.getScreenCTM().inverse())},n.rotateElement=function(e,t,n,i){e.setAttribute("transform",`translate(${t},${n}) rotate(${i+90}) translate(${-t},${-n})`)},n.hydrate=function(e,n){for(let i in n)"title"==i?t.title(e,n[i]):e.setAttributeNS(null,i,n[i])},n.elt=function(e,n){let i=document.createElementNS("http://www.w3.org/2000/svg",e);return n&&t.hydrate(i,n),i},n.child=function(e,n,i){let s=t.elt(n,i);return e.appendChild(s),s},n.mkPath=i,n.path=function(e,t,n,s){let r=i(t,n,s);return e.appendChild(r),r},n.fill=function(e,t){e.style.fill=t},n.filter=function(e,t){e.style.filter=t},n.fills=function(e,t){e.forEach((e=>e.style.fill=t))},n.isTouchEnabled=function(){return"undefined"!=typeof window&&("ontouchstart"in window||navigator.maxTouchPoints>0)},n.onClick=function(t,n){let i=!1;e.pointerEvents.down.forEach((e=>t.addEventListener(e,(e=>(i=!0,!0)),!1))),t.addEventListener(e.pointerEvents.up,(e=>!i||(i=!1,n(e),e.preventDefault(),!1)),!1)},n.buttonEvents=function(t,n,i,s,r){let o=!1;e.pointerEvents.down.forEach((e=>t.addEventListener(e,(e=>(o=!0,i&&i(e),!0)),!1))),t.addEventListener(e.pointerEvents.move,(e=>!o||(n&&n(e),e.preventDefault(),!1)),!1),t.addEventListener(e.pointerEvents.up,(e=>{o=!1,s&&s(e)}),!1),t.addEventListener(e.pointerEvents.leave,(e=>{o=!1,s&&s(e)}),!1),t.addEventListener("keydown",(e=>{o=!1,r&&r(e)}))},n.mkLinearGradient=s,n.linearGradient=function(e,t,n=!1){let i=s(t,n);return e.appendChild(i),i},n.setGradientColors=function(e,t,n){e&&(e.childNodes[0].style.stopColor=t,e.childNodes[1].style.stopColor=t,e.childNodes[2].style.stopColor=n,e.childNodes[3].style.stopColor=n)},n.setGradientValue=function(e,t){e.childNodes[1].getAttribute("offset")!=t&&(e.childNodes[1].setAttribute("offset",t),e.childNodes[2].setAttribute("offset",t))},n.animate=function(t,n){e.U.addClass(t,n);let i=t.parentElement;i&&(i.removeChild(t),i.appendChild(t))},n.mkTitle=r,n.title=function(e,t){let n=r(t);return e.appendChild(n),n},n.toHtmlColor=function(e){return`rgba(${e>>16&255}, ${e>>8&255}, ${255&e}, ${e>>24&1})`}}(t=e.svg||(e.svg={}))}(pxsim||(pxsim={})),function(e){!function(e){e.Metronome=class{constructor(){this.tickListeners=[],this.onTick=()=>{for(const e of this.tickListeners)e()}}initAsync(){return this.metronomeLoadPromise?this.metronomeLoadPromise:this.metronomeWorker?this.metronomeWorker:(this.metronomeLoadPromise=new Promise((e=>{this.metronomeWorker=new Worker("data:application/javascript,"+encodeURIComponent(t));const n=t=>{"ready"===t.data&&(e(this.metronomeWorker),this.metronomeWorker.removeEventListener("message",n),this.metronomeWorker.addEventListener("message",this.onTick))};this.metronomeWorker.addEventListener("message",n)})),this.metronomeLoadPromise)}stop(){this.postMessage({type:"stop"})}setInterval(e){this.currentInterval=e,this.postMessage({type:"set-interval",interval:e})}start(e){this.currentInterval=e,this.postMessage({type:"start",interval:e})}addTickListener(e){this.tickListeners.push(e)}removeTickListener(e){this.tickListeners=this.tickListeners.filter((t=>t!==e))}interval(){return this.currentInterval}dispose(){if(this.metronomeWorker)this.metronomeWorker.terminate(),this.metronomeWorker=void 0,this.metronomeLoadPromise=void 0,this.tickListeners=[],this.interval=void 0;else if(this.metronomeLoadPromise)return void this.metronomeLoadPromise.then((()=>this.dispose()))}postMessage(e){if(!this.metronomeWorker)throw new Error("initAsync not called on metronome");this.metronomeWorker.postMessage(e)}};const t='\n/**\n * Adpated from https://github.com/cwilso/metronome/\n */\n\nlet timerRef;\nlet interval;\n\naddEventListener("message", ev => {\n const message = ev.data;\n\n if (message.type === "start") {\n updateInterval(message.interval, true);\n }\n else if (message.type === "stop") {\n clearInterval(timerRef);\n timerRef = undefined;\n }\n else if (message.type === "set-interval") {\n updateInterval(message.interval, false);\n }\n})\n\npostMessage("ready");\n\nfunction updateInterval(interval, startIfStopped) {\n if (timerRef) {\n clearInterval(timerRef);\n startIfStopped = true;\n }\n interval = interval;\n\n if (startIfStopped) {\n timerRef = setInterval(() => postMessage("tick"), interval);\n }\n}\n'}(e.music||(e.music={}))}(pxsim||(pxsim={})),function(e){!function(e){!function(e){!function(e){e.chromaticInterval=[1,1.0417,1.125,1.2,1.25,1.3333,1.4063,1.5,1.6,1.6667,1.8,1.875],e.majorScaleInterval=[e.chromaticInterval[0],e.chromaticInterval[2],e.chromaticInterval[4],e.chromaticInterval[5],e.chromaticInterval[7],e.chromaticInterval[9],e.chromaticInterval[11]],e.minorScaleInterval=[e.chromaticInterval[0],e.chromaticInterval[2],e.chromaticInterval[3],e.chromaticInterval[5],e.chromaticInterval[7],e.chromaticInterval[8],e.chromaticInterval[10]],e.pentatonicScaleInterval=[e.chromaticInterval[0],e.chromaticInterval[2],e.chromaticInterval[4],e.chromaticInterval[7],e.chromaticInterval[9]],e.majorTriadInterval=[e.chromaticInterval[0],e.chromaticInterval[4],e.chromaticInterval[7]],e.minorTriadInterval=[e.chromaticInterval[0],e.chromaticInterval[3],e.chromaticInterval[7]],e.diminishedInterval=[e.chromaticInterval[0],e.chromaticInterval[3],e.chromaticInterval[6],e.chromaticInterval[9]],e.wholeToneInterval=[e.chromaticInterval[0],e.chromaticInterval[2],e.chromaticInterval[4],e.chromaticInterval[6],e.chromaticInterval[8],e.chromaticInterval[10]]}(e.MusicalIntervals||(e.MusicalIntervals={}))}(e.music||(e.music={}))}(e.codal||(e.codal={}))}(pxsim||(pxsim={})),function(e){!function(e){!function(e){!function(t){t.chromatic={interval:e.MusicalIntervals.chromaticInterval,length:12},t.majorScale={interval:e.MusicalIntervals.majorScaleInterval,length:7},t.minorScale={interval:e.MusicalIntervals.minorScaleInterval,length:7},t.pentatonicScale={interval:e.MusicalIntervals.pentatonicScaleInterval,length:5},t.majorTriad={interval:e.MusicalIntervals.majorTriadInterval,length:3},t.minorTriad={interval:e.MusicalIntervals.minorTriadInterval,length:3},t.diminished={interval:e.MusicalIntervals.diminishedInterval,length:4},t.wholeTone={interval:e.MusicalIntervals.wholeToneInterval,length:6},t.calculateFrequencyFromProgression=function(e,t,n){let i=Math.floor(n/t.length),s=n%t.length;return e*Math.pow(2,i)*t.interval[s]}}(e.MusicalProgressions||(e.MusicalProgressions={}))}(e.music||(e.music={}))}(e.codal||(e.codal={}))}(pxsim||(pxsim={})),function(e){!function(t){const n=[31,33,35,37,39,41,44,46,49,52,55,58,62,65,69,73,78,82,87,92,98,104,110,117,123,131,139,147,156,165,175,185,196,208,220,233,247,262,277,294,311,330,349,370,392,415,440,466,494,523,554,587,622,659,698,740,784,831,880,932,988,1047,1109,1175,1245,1319,1397,1480,1568,1661,1760,1865,1976,2093,2217,2349,2489,2637,2794,2960,3136,3322,3520,3729,3951,4186,4435,4699,4978,5274,5588,5920,6272,6645,7040,7459,7902];async function i(t,i,s,r,o=100){await e.AudioContextManager.playInstructionsAsync(e.music.renderInstrument(i,n[t],s,o),r)}async function s(t,n,i=100){await e.AudioContextManager.playInstructionsAsync(e.music.renderDrumInstrument(t,i),n)}function r(e,t,n){return 6e4/e/t*n}t.Sequencer=class{constructor(){this._currentTick=0,this._state="stop",this.listeners={},this.globalVolume=1024,this.trackVolumes=[],this.drumTrackVolumes=[],this.currentCancelToken={cancelled:!1},this.onTick=()=>{const e=this.currentCancelToken;for(let t=0;t<this.currentlyPlaying.tracks.length;t++){const n=this.currentlyPlaying.tracks[t];for(const o of n.notes)if(o.startTick===this._currentTick)for(const a of o.notes)n.drums?s(n.drums[a.note],(()=>e.cancelled),this.getDrumTrackVolume(t,a.note)):i(a.note,n.instrument,r(this.currentlyPlaying.beatsPerMinute,this.currentlyPlaying.ticksPerBeat,o.endTick-o.startTick),(()=>e.cancelled),this.getMelodicTrackVolume(t));else if(o.startTick>this._currentTick)break}this.fireEvent("tick"),this._currentTick++,this._currentTick>=this.maxTick()&&("loop"===this._state?(this._currentTick=0,this.fireEvent("looped")):this.stop(!0))}}async initAsync(){this.metronome?await this.metronome.initAsync():(this.metronome=new t.Metronome,await this.metronome.initAsync(),this.metronome.addTickListener(this.onTick))}dispose(){this.metronome&&this.metronome.dispose(),this.metronome=void 0,this.stop(),this.currentlyPlaying=void 0,this.listeners={}}state(){return this._state}currentTick(){return this._currentTick}currentTime(){return r(this.currentlyPlaying.beatsPerMinute,this.currentlyPlaying.ticksPerBeat,this.currentTick())}maxTick(){return this.currentlyPlaying?this.currentlyPlaying.measures*this.currentlyPlaying.beatsPerMeasure*this.currentlyPlaying.ticksPerBeat:0}duration(){return r(this.currentlyPlaying.beatsPerMinute,this.currentlyPlaying.ticksPerBeat,this.maxTick())}start(e,t){this.startFrom(e,t,0)}startFrom(e,t,n){"stop"!==this._state&&this.stop(),void 0!==t&&(this.shouldLoop=t),this._currentTick=null!=n?n:0,this.currentlyPlaying=e,this.metronome.start(r(e.beatsPerMinute,e.ticksPerBeat,1)),this._state=this.shouldLoop?"loop":"play",this.fireStateChange()}stop(e=!1){"stop"!==this._state&&(this._state="stop",this.metronome&&this.metronome.stop(),this.fireStateChange(),e||(this.currentCancelToken.cancelled=!0),this.currentCancelToken={cancelled:!1})}updateSong(e){this.currentlyPlaying=e,"stop"!==this._state&&this.metronome.setInterval(r(e.beatsPerMinute,e.ticksPerBeat,1))}setLooping(e){e&&"play"===this._state?(this._state="loop",this.fireStateChange()):e||"loop"!==this._state||(this._state="play",this.fireStateChange()),this.shouldLoop=e}addEventListener(e,t){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(t)}removeEventListener(e,t){this.listeners[e]&&(this.listeners[e]=this.listeners[e].filter((e=>e!==t)))}setVolume(e){this.globalVolume=Math.min(Math.max(e,0),1024)}setTrackVolume(e,t){for(t=Math.min(Math.max(t,0),1024);this.trackVolumes.length<e;)this.trackVolumes.push(1024);this.trackVolumes[e]=t}setDrumTrackVolume(e,t,n){for(n=Math.min(Math.max(n,0),1024);this.drumTrackVolumes.length<e;)this.drumTrackVolumes.push([]);for(;this.drumTrackVolumes[e].length<t;)this.drumTrackVolumes[e].push(1024);this.drumTrackVolumes[e][t]=n}getMelodicTrackVolume(e){let t=1024;return e<this.trackVolumes.length&&(t=this.trackVolumes[e]),this.globalVolume*(t/1024)}getDrumTrackVolume(e,t){const n=this.getMelodicTrackVolume(e);let i=1024;return e<this.drumTrackVolumes.length&&t<this.drumTrackVolumes[e].length&&(i=this.drumTrackVolumes[e][t]),n*(i/1024)}fireStateChange(){this.fireEvent(this._state),this.fireEvent("state-change")}fireEvent(e){if(this.listeners[e])for(const t of this.listeners[e])t()}},t.playNoteAsync=i,t.playDrumAsync=s,t.tickToMs=r}(e.music||(e.music={}))}(pxsim||(pxsim={})),function(e){!function(e){function t(e,t,n,r){var o,a;let l=0;return(null===(o=e.pitchEnvelope)||void 0===o?void 0:o.amplitude)&&(l+=i(e.pitchEnvelope,r,n)),(null===(a=e.pitchLFO)||void 0===a?void 0:a.amplitude)&&(l+=s(e.pitchLFO,r)),Math.max(t+l,0)}function n(e,t,n,r){var o;let a=0;return e.ampEnvelope.amplitude&&(a+=i(e.ampEnvelope,n,t)),(null===(o=e.ampLFO)||void 0===o?void 0:o.amplitude)&&(a+=s(e.ampLFO,n)),Math.max(Math.min(a,e.ampEnvelope.amplitude),0)/1024*r|0}function i(e,t,n){const i=e.sustain/1024*e.amplitude;if(t>n){if(t-n>e.release)return 0;if(t<e.attack){const i=e.amplitude/e.attack*n;return i-i/e.release*(t-n)}if(t<e.attack+e.decay){const s=e.amplitude-(e.amplitude-i)/e.decay*(n-e.attack);return s-s/e.release*(t-n)}return i-i/e.release*(t-n)}return t<e.attack?e.amplitude/e.attack*t:t<e.attack+e.decay?e.amplitude-(e.amplitude-i)/e.decay*(t-e.attack):i}function s(e,t){return Math.cos(t/1e3*e.frequency*2*Math.PI)*e.amplitude}function r(e,t,n,i,s,r,a,l){return n>0&&(e[t]=r,e[t+1]=0,o(e,t+2,a),o(e,t+4,n),o(e,t+6,255*i>>6),o(e,t+8,255*s>>6),o(e,t+10,l),t+=12),e[t]=0,t}function o(e,t,n){const i=new Uint8Array(2);new Uint16Array(i.buffer)[0]=0|n,e[t]=i[0],e[t+1]=i[1]}function a(e,t){const n=new Uint8Array(2);return n[0]=e[t],n[1]=e[t+1],new Uint16Array(n.buffer)[0]}function l(e,t){return{waveform:e[t],ampEnvelope:{attack:a(e,t+1),decay:a(e,t+3),sustain:a(e,t+5),release:a(e,t+7),amplitude:a(e,t+9)},pitchEnvelope:{attack:a(e,t+11),decay:a(e,t+13),sustain:a(e,t+15),release:a(e,t+17),amplitude:a(e,t+19)},ampLFO:{frequency:e[t+21],amplitude:a(e,22)},pitchLFO:{frequency:e[t+24],amplitude:a(e,25)},octave:e[t+27]}}function c(e,t){return e[t+1]?function(e,t){const n={id:e[t],instrument:{ampEnvelope:{attack:0,decay:0,sustain:0,release:0,amplitude:0},waveform:0},notes:[],drums:[]},i=a(e,t+2);let s=t+4;for(;s<t+4+i;)n.drums.push(u(e,s)),s+=5+7*n.drums[n.drums.length-1].steps.length;const r=a(e,s);s+=2;for(;s<t+4+i+r;)n.notes.push(d(e,s,0,!0)),s+=5+n.notes[n.notes.length-1].notes.length;return[n,s]}(e,t):function(e,t){const n={id:e[t],instrument:l(e,t+4),notes:[]},i=t+4+a(e,t+2),s=a(e,i);let r=i+2;for(;r<i+2+s;)n.notes.push(d(e,r,n.instrument.octave,!1)),r+=5+n.notes[n.notes.length-1].notes.length;return[n,r]}(e,t)}function u(e,t){const n={startFrequency:a(e,t+1),startVolume:a(e,t+3),steps:[]};for(let i=0;i<e[t];i++){const s=t+5+7*i;n.steps.push({waveform:e[s],frequency:a(e,s+1),volume:a(e,s+3),duration:a(e,s+5)})}return n}function d(e,t,n,i){const s={startTick:a(e,t),endTick:a(e,t+2),notes:[]};for(let r=0;r<e[t+4];r++)s.notes.push(h(e[t+5+r],n,i));return s}function h(e,t,n){const i=e>>6,s={note:n?e:(63&e)+12*(t-2),enharmonicSpelling:"normal"};return 1===i?s.enharmonicSpelling="flat":2===i&&(s.enharmonicSpelling="sharp"),s}e.renderInstrument=function(e,i,s,o){var a,l,c,u,d;const h=s+e.ampEnvelope.release,p=(null===(a=e.ampLFO)||void 0===a?void 0:a.amplitude)?Math.max(500/e.ampLFO.frequency,50):50,f=(null===(l=e.pitchLFO)||void 0===l?void 0:l.amplitude)?Math.max(500/e.pitchLFO.frequency,50):50;let m=[0],g=e.ampEnvelope.attack,b=(null===(c=e.pitchEnvelope)||void 0===c?void 0:c.amplitude)?e.pitchEnvelope.attack:h,y=(null===(u=e.pitchLFO)||void 0===u?void 0:u.amplitude)?f:h,v=(null===(d=e.ampLFO)||void 0===d?void 0:d.amplitude)?p:h,w=0;for(;w<h&&(g<=b&&g<=y&&g<=v?(w=g,m.push(g),g=w<e.ampEnvelope.attack+e.ampEnvelope.decay&&e.ampEnvelope.attack+e.ampEnvelope.decay<s?e.ampEnvelope.attack+e.ampEnvelope.decay:w<s?s:h):b<=y&&b<=v&&b<h?(w=b,m.push(b),b=w<e.pitchEnvelope.attack+e.pitchEnvelope.decay&&e.pitchEnvelope.attack+e.pitchEnvelope.decay<s?e.pitchEnvelope.attack+e.pitchEnvelope.decay:w<s?s:w<s+e.pitchEnvelope.release?Math.min(h,s+e.pitchEnvelope.release):h):y<=v&&y<h?(w=y,m.push(y),y+=f):v<h&&(w=v,m.push(v),v+=p),!(w>=h));){for(g<=w&&(g=w<e.ampEnvelope.attack+e.ampEnvelope.decay&&e.ampEnvelope.attack+e.ampEnvelope.decay<s?e.ampEnvelope.attack+e.ampEnvelope.decay:w<s?s:h),b<=w&&(b=w<e.pitchEnvelope.attack+e.pitchEnvelope.decay&&e.pitchEnvelope.attack+e.pitchEnvelope.decay<s?e.pitchEnvelope.attack+e.pitchEnvelope.decay:w<s?s:w<s+e.pitchEnvelope.release?Math.min(h,s+e.pitchEnvelope.release):h);v<=w;)v+=p;for(;y<=w;)y+=f}let k,x,A=0|n(e,s,0,o),E=0|t(e,i,s,0),T=0;const S=new Uint8Array(12*(m.length+1));for(let a=1;a<m.length;a++)m[a]-T<5||(k=0|n(e,s,m[a],o),x=0|t(e,i,s,m[a]),r(S,12*(a-1),m[a]-T|0,A,k,e.waveform,E,x),A=k,E=x),T=m[a];return r(S,12*m.length,10,A,0,e.waveform,E,E),S},e.renderDrumInstrument=function(e,t){let n=e.startVolume,i=e.startFrequency;const s=e=>e/1024*t;let o=new Uint8Array(12*(e.steps.length+1));for(let t=0;t<e.steps.length;t++)r(o,12*t,e.steps[t].duration,s(n),s(e.steps[t].volume),e.steps[t].waveform,i,e.steps[t].frequency),n=e.steps[t].volume,i=e.steps[t].frequency;return r(o,12*e.steps.length,10,s(n),0,e.steps[e.steps.length-1].waveform,i,i),o},e.decodeSong=function(e){const t={beatsPerMinute:a(e,1),beatsPerMeasure:e[3],ticksPerBeat:e[4],measures:e[5],tracks:[]};let n=7;for(;n<e.length;){const[i,s]=c(e,n);n=s,t.tracks.push(i)}return t}}(e.music||(e.music={}))}(pxsim||(pxsim={})),function(e){!function(e){!function(e){e.EMOJI_SYNTHESIZER_SAMPLE_RATE=44100,e.EMOJI_SYNTHESIZER_TONE_WIDTH_F=1024,e.EMOJI_SYNTHESIZER_TONE_WIDTH=1024,e.EMOJI_SYNTHESIZER_BUFFER_SIZE=512,e.EMOJI_SYNTHESIZER_TONE_EFFECT_PARAMETERS=2,e.EMOJI_SYNTHESIZER_TONE_EFFECTS=3,e.EMOJI_SYNTHESIZER_STATUS_ACTIVE=1,e.EMOJI_SYNTHESIZER_STATUS_OUTPUT_SILENCE_AS_EMPTY=2,e.EMOJI_SYNTHESIZER_STATUS_STOPPING=4;e.SoundEmojiSynthesizer=class{constructor(t,n=e.EMOJI_SYNTHESIZER_SAMPLE_RATE){this.samplesPerStep=[],this.status=0,this.effectPointer=0,this.position=0,this.bufferSize=e.EMOJI_SYNTHESIZER_BUFFER_SIZE,this.sampleRate=n,this.samplesToWrite=0,this.samplesWritten=0,this.sampleRange=1023,this.orMask=0,this.effectPointer=-1,this.volume=1}get effect(){return this.effectBuffer[this.effectPointer]}play(e){this.effectBuffer=e,this.effectPointer=-1,this.nextSoundEffect()}nextSoundEffect(){const t=null!=this.effect;if(this.status&e.EMOJI_SYNTHESIZER_STATUS_STOPPING&&(this.effectPointer=null,this.effectBuffer=[]),this.effect?this.effectPointer++:this.effectPointer=0,this.effectPointer>=this.effectBuffer.length&&(this.effectPointer=0,this.effect.duration>=0))return this.effectPointer=-1,this.effectBuffer=[],this.samplesWritten=0,this.samplesToWrite=0,this.position=0,t;this.samplesToWrite=this.determineSampleCount(this.effect.duration),this.frequency=this.effect.frequency,this.volume=this.effect.volume,this.samplesWritten=0;for(let t=0;t<e.EMOJI_SYNTHESIZER_TONE_EFFECTS;t++)this.effect.effects[t].step=0,this.effect.effects[t].steps=Math.max(this.effect.effects[t].steps,1),this.samplesPerStep[t]=Math.floor(this.samplesToWrite/this.effect.effects[t].steps);return!1}pull(){let t,n,i=!1;for(;!i;){if(this.samplesWritten==this.samplesToWrite||this.status&e.EMOJI_SYNTHESIZER_STATUS_STOPPING){let t=this.nextSoundEffect();(0==this.samplesToWrite||this.status&e.EMOJI_SYNTHESIZER_STATUS_STOPPING)&&(i=!0,(t||this.status&e.EMOJI_SYNTHESIZER_STATUS_STOPPING)&&(this.status&=~e.EMOJI_SYNTHESIZER_STATUS_STOPPING))}for(!(this.samplesWritten<this.samplesToWrite)&&this.status&e.EMOJI_SYNTHESIZER_STATUS_OUTPUT_SILENCE_AS_EMPTY||null!=t||(this.buffer=new Array(this.bufferSize),t=0,n=this.buffer.length);this.samplesWritten<this.samplesToWrite;){let i=e.EMOJI_SYNTHESIZER_TONE_WIDTH_F*this.frequency/this.sampleRate,s=this.sampleRange*this.volume/1024,r=512-512*s,o=[];for(let t=0;t<e.EMOJI_SYNTHESIZER_TONE_EFFECTS;t++)o[t]=this.samplesPerStep[t]*this.effect.effects[t].step,this.effect.effects[t].step==this.effect.effects[t].steps-1&&(o[t]=this.samplesToWrite);let a=o[0];for(let t=1;t<e.EMOJI_SYNTHESIZER_TONE_EFFECTS;t++)a=Math.min(a,o[t]);for(;this.samplesWritten<a;){if(t==n)return this.buffer;let o=this.effect.tone.tonePrint(this.effect.tone.parameter,Math.max(this.position,0));for(this.buffer[t]=o*s+r,t++,this.samplesWritten++,this.position+=i;this.position>e.EMOJI_SYNTHESIZER_TONE_WIDTH_F;)this.position-=e.EMOJI_SYNTHESIZER_TONE_WIDTH_F}for(let t=0;t<e.EMOJI_SYNTHESIZER_TONE_EFFECTS;t++)this.samplesWritten==o[t]&&this.effect.effects[t].step<this.effect.effects[t].steps&&(this.effect.effects[t].effect&&this.effect.effects[t].effect(this,this.effect.effects[t]),this.effect.effects[t].step++)}}if(null==t)this.buffer=[];else{const e=.5*this.sampleRange;for(;t<n;)this.buffer[t]=e,t++}return this.buffer}determineSampleCount(e){e<0&&(e=-e);const t=e/1e3;return Math.floor(this.sampleRate*t)}totalDuration(){let e=0;for(const t of this.effectBuffer)e+=t.duration;return e}}}(e.music||(e.music={}))}(e.codal||(e.codal={}))}(pxsim||(pxsim={})),function(e){!function(e){!function(e){!function(e){const t=[0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,3,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,11,11,12,13,13,14,15,16,16,17,18,19,20,21,22,22,23,24,25,26,27,28,29,30,32,33,34,35,36,37,38,40,41,42,43,45,46,47,49,50,51,53,54,56,57,58,60,61,63,64,66,68,69,71,72,74,76,77,79,81,82,84,86,87,89,91,93,95,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,141,143,145,147,149,152,154,156,158,161,163,165,167,170,172,175,177,179,182,184,187,189,191,194,196,199,201,204,206,209,211,214,216,219,222,224,227,229,232,235,237,240,243,245,248,251,253,256,259,262,264,267,270,273,275,278,281,284,287,289,292,295,298,301,304,307,309,312,315,318,321,324,327,330,333,336,339,342,345,348,351,354,357,360,363,366,369,372,375,378,381,384,387,390,393,396,399,402,405,408,411,414,417,420,424,427,430,433,436,439,442,445,448,452,455,458,461,464,467,470,473,477,480,483,486,489,492,495,498,502,505,508,511,514,517,520,524,527,530,533,536,539,542,545,549,552,555,558,561,564,567,570,574,577,580,583,586,589,592,595,598,602,605,608,611,614,617,620,623,626,629,632,635,638,641,644,647,650,653,656,659,662,665,668,671,674,677,680,683,686,689,692,695,698,701,704,707,710,713,715,718,721,724,727,730,733,735,738,741,744,747,749,752,755,758,760,763,766,769,771,774,777,779,782,785,787,790,793,795,798,800,803,806,808,811,813,816,818,821,823,826,828,831,833,835,838,840,843,845,847,850,852,855,857,859,861,864,866,868,870,873,875,877,879,881,884,886,888,890,892,894,896,898,900,902,904,906,908,910,912,914,916,918,920,922,924,926,927,929,931,933,935,936,938,940,941,943,945,946,948,950,951,953,954,956,958,959,961,962,964,965,966,968,969,971,972,973,975,976,977,979,980,981,982,984,985,986,987,988,989,990,992,993,994,995,996,997,998,999,1e3,1e3,1001,1002,1003,1004,1005,1006,1006,1007,1008,1009,1009,1010,1011,1011,1012,1013,1013,1014,1014,1015,1015,1016,1016,1017,1017,1018,1018,1019,1019,1019,1020,1020,1020,1021,1021,1021,1021,1022,1022,1022,1022,1022,1022,1022,1022,1022,1022,1023,1022];e.SineTone=function(e,n){let i=1024-(n|=0);return i<512&&(n=i),t[n]},e.SawtoothTone=function(e,t){return t},e.TriangleTone=function(e,t){return t<512?2*t:2*(1023-t)},e.NoiseTone=function(e,t){let n=e[0];return 0==n&&(n=7919),t*n&1023},e.SquareWaveTone=function(e,t){return t<512?1023:0}}(e.Synthesizer||(e.Synthesizer={}))}(e.music||(e.music={}))}(e.codal||(e.codal={}))}(pxsim||(pxsim={})),function(e){!function(e){!function(e){!function(t){t.noInterpolation=function(e,t){},t.linearInterpolation=function(e,t){let n=(t.parameter[0]-e.effect.frequency)/t.steps;e.frequency=e.effect.frequency+n*t.step},t.logarithmicInterpolation=function(e,t){e.frequency=e.effect.frequency+Math.log10(Math.max(t.step,.1))*(t.parameter[0]-e.effect.frequency)/1.95},t.curveInterpolation=function(e,t){e.frequency=Math.sin(3.12159*t.step/180)*(t.parameter[0]-e.effect.frequency)+e.effect.frequency},t.slowVibratoInterpolation=function(e,t){e.frequency=Math.sin(t.step/10)*t.parameter[0]+e.effect.frequency},t.warbleInterpolation=function(e,t){e.frequency=Math.sin(t.step)*(t.parameter[0]-e.effect.frequency)+e.effect.frequency},t.vibratoInterpolation=function(e,t){e.frequency=e.effect.frequency+Math.sin(t.step)*t.parameter[0]},t.exponentialRisingInterpolation=function(e,t){e.frequency=e.effect.frequency+Math.sin(.01745329*t.step)*t.parameter[0]},t.exponentialFallingInterpolation=function(e,t){e.frequency=e.effect.frequency+Math.cos(.01745329*t.step)*t.parameter[0]},t.appregrioAscending=function(t,n){t.frequency=e.MusicalProgressions.calculateFrequencyFromProgression(t.effect.frequency,n.parameter_p[0],n.step)},t.appregrioDescending=function(t,n){t.frequency=e.MusicalProgressions.calculateFrequencyFromProgression(t.effect.frequency,n.parameter_p[0],n.steps-n.step-1)},t.frequencyVibratoEffect=function(e,t){0!=t.step&&(t.step%2==0?e.frequency/=t.parameter[0]:e.frequency*=t.parameter[0])},t.volumeVibratoEffect=function(e,t){0!=t.step&&(t.step%2==0?e.volume/=t.parameter[0]:e.volume*=t.parameter[0])},t.adsrVolumeEffect=function(e,t){let n=.5*t.steps;if(t.step<=n){let i=(t.parameter[0]-e.effect.volume)/n;e.volume=e.effect.volume+t.step*i}else{let i=(t.parameter[1]-t.parameter[0])/n;e.volume=t.parameter[0]+(t.step-n)*i}},t.volumeRampEffect=function(e,t){let n=(t.parameter[0]-e.effect.volume)/t.steps;e.volume=e.effect.volume+t.step*n}}(e.SoundSynthesizerEffects||(e.SoundSynthesizerEffects={}))}(e.music||(e.music={}))}(e.codal||(e.codal={}))}(pxsim||(pxsim={})),function(e){!function(t){!function(t){let n,i,s;!function(e){e[e.Sine=0]="Sine",e[e.Sawtooth=1]="Sawtooth",e[e.Triangle=2]="Triangle",e[e.Square=3]="Square",e[e.Noise=4]="Noise"}(n=t.WaveShape||(t.WaveShape={})),function(e){e[e.None=0]="None",e[e.Linear=1]="Linear",e[e.Curve=2]="Curve",e[e.ExponentialRising=5]="ExponentialRising",e[e.ExponentialFalling=6]="ExponentialFalling",e[e.ArpeggioRisingMajor=8]="ArpeggioRisingMajor",e[e.ArpeggioRisingMinor=10]="ArpeggioRisingMinor",e[e.ArpeggioRisingDiminished=12]="ArpeggioRisingDiminished",e[e.ArpeggioRisingChromatic=14]="ArpeggioRisingChromatic",e[e.ArpeggioRisingWholeTone=16]="ArpeggioRisingWholeTone",e[e.ArpeggioFallingMajor=9]="ArpeggioFallingMajor",e[e.ArpeggioFallingMinor=11]="ArpeggioFallingMinor",e[e.ArpeggioFallingDiminished=13]="ArpeggioFallingDiminished",e[e.ArpeggioFallingChromatic=15]="ArpeggioFallingChromatic",e[e.ArpeggioFallingWholeTone=17]="ArpeggioFallingWholeTone",e[e.Logarithmic=18]="Logarithmic"}(i=t.InterpolationEffect||(t.InterpolationEffect={})),function(e){e[e.None=0]="None",e[e.Vibrato=1]="Vibrato",e[e.Tremolo=2]="Tremolo",e[e.Warble=3]="Warble"}(s=t.Effect||(t.Effect={}));class r{constructor(){this.src="000000000000000000000000000000000000000000000000000000000000000000000000"}get wave(){return this.getValue(0,1)}set wave(e){this.setValue(0,g(e,0,4),1)}get volume(){return this.getValue(1,4)}set volume(e){this.setValue(1,g(e,0,1023),4)}get frequency(){return this.getValue(5,4)}set frequency(e){this.setValue(5,e,4)}get duration(){return this.getValue(9,4)}set duration(e){this.setValue(9,e,4)}get shape(){return this.getValue(13,2)}set shape(e){this.setValue(13,e,2)}get endFrequency(){return this.getValue(18,4)}set endFrequency(e){this.setValue(18,e,4)}get endVolume(){return this.getValue(26,4)}set endVolume(e){this.setValue(26,g(e,0,1023),4)}get steps(){return this.getValue(30,4)}set steps(e){this.setValue(30,e,4)}get fx(){return this.getValue(34,2)}set fx(e){this.setValue(34,g(e,0,3),2)}get fxParam(){return this.getValue(36,4)}set fxParam(e){this.setValue(36,e,4)}get fxnSteps(){return this.getValue(40,4)}set fxnSteps(e){this.setValue(40,e,4)}get frequencyRandomness(){return this.getValue(44,4)}set frequencyRandomness(e){this.setValue(44,e,4)}get endFrequencyRandomness(){return this.getValue(48,4)}set endFrequencyRandomness(e){this.setValue(48,e,4)}get volumeRandomness(){return this.getValue(52,4)}set volumeRandomness(e){this.setValue(52,e,4)}get endVolumeRandomness(){return this.getValue(56,4)}set endVolumeRandomness(e){this.setValue(56,e,4)}get durationRandomness(){return this.getValue(60,4)}set durationRandomness(e){this.setValue(60,e,4)}get fxParamRandomness(){return this.getValue(64,4)}set fxParamRandomness(e){this.setValue(64,e,4)}get fxnStepsRandomness(){return this.getValue(68,4)}set fxnStepsRandomness(e){this.setValue(68,e,4)}copy(){const e=new r;return e.src=this.src.slice(0),e}setValue(e,t,n){t=g(0|t,0,Math.pow(10,n)-1),this.src=this.src.substr(0,e)+function(e,t){let n=e+"";for(;n.length<t;)n="0"+n;return n}(t,n)+this.src.substr(e+n)}getValue(e,t){return parseInt(this.src.substr(e,t))}}t.Sound=r;let o,a=!1,l={cancelled:!1};async function c(){if(o.length){a=!0;const e=o.shift();let t=l;try{e.onStarted(),await d(e.notes,(()=>t.cancelled)),t.cancelled?e.onCancelled():e.onFinished()}catch(t){e.onCancelled()}c()}else a=!1}function u(){o=[],l.cancelled=!0,l={cancelled:!1}}function d(n,i,s){const r=new t.SoundEmojiSynthesizer(0),o=function(e){const t=72,n=Math.floor((e.length+1)/(t+1)),i=n*(t+1)-1;if(e.length!=i)return[];const s=[];for(let i=0;i<n;++i){const n=i*t+i;if(n>0&&","!=e[n-1])return[];const r=m();if(!h(e.substr(n),r))return[];s.push(r)}return s}(n);r.play(o);let a=!1;return Promise.race([(l=r.totalDuration(),new Promise((e=>setTimeout(e,l)))).then((()=>{a=!0})),e.AudioContextManager.playPCMBufferStreamAsync((()=>{if(!r.effect)return;const e=r.pull();s&&s(r.frequency,r.volume);const t=new Float32Array(e.length);for(let n=0;n<e.length;n++)t[n]=(e[n]-512)/512;return t}),r.sampleRate,.03,(()=>a||i&&i()))]);var l}function h(e,n){let i=parseInt(e.substr(0,1)),s=parseInt(e.substr(1,4)),r=parseInt(e.substr(5,4)),o=parseInt(e.substr(9,4)),a=parseInt(e.substr(13,2)),l=parseInt(e.substr(18,4)),c=parseInt(e.substr(26,4)),u=parseInt(e.substr(30,4)),d=parseInt(e.substr(34,2)),h=parseInt(e.substr(36,4)),m=parseInt(e.substr(40,4));if(r=f(r,parseInt(e.substr(44,4))),l=f(l,parseInt(e.substr(48,4))),s=f(s,parseInt(e.substr(52,4))),c=f(c,parseInt(e.substr(56,4))),o=f(o,parseInt(e.substr(60,4))),h=f(h,parseInt(e.substr(64,4))),m=f(m,parseInt(e.substr(68,4))),-1==r||-1==l||-1==s||-1==c||-1==o||-1==h||-1==m)return!1;switch(i){case 0:n.tone.tonePrint=t.Synthesizer.SineTone;break;case 1:n.tone.tonePrint=t.Synthesizer.SawtoothTone;break;case 2:n.tone.tonePrint=t.Synthesizer.TriangleTone;break;case 3:n.tone.tonePrint=t.Synthesizer.SquareWaveTone;break;case 4:n.tone.tonePrint=t.Synthesizer.NoiseTone}switch(n.frequency=r,n.duration=o,n.effects[0].steps=u,a){case 0:n.effects[0].effect=t.SoundSynthesizerEffects.noInterpolation;break;case 1:n.effects[0].effect=t.SoundSynthesizerEffects.linearInterpolation,n.effects[0].parameter[0]=l;break;case 2:n.effects[0].effect=t.SoundSynthesizerEffects.curveInterpolation,n.effects[0].parameter[0]=l;break;case 5:n.effects[0].effect=t.SoundSynthesizerEffects.exponentialRisingInterpolation,n.effects[0].parameter[0]=l;break;case 6:n.effects[0].effect=t.SoundSynthesizerEffects.exponentialFallingInterpolation,n.effects[0].parameter[0]=l;break;case 8:case 10:case 12:case 14:case 16:n.effects[0].effect=t.SoundSynthesizerEffects.appregrioAscending;break;case 9:case 11:case 13:case 15:case 17:n.effects[0].effect=t.SoundSynthesizerEffects.appregrioDescending;break;case 18:n.effects[0].effect=t.SoundSynthesizerEffects.logarithmicInterpolation,n.effects[0].parameter[0]=l}switch(a){case 8:case 9:n.effects[0].parameter_p[0]=t.MusicalProgressions.majorScale;break;case 10:case 11:n.effects[0].parameter_p[0]=t.MusicalProgressions.minorScale;break;case 12:case 13:n.effects[0].parameter_p[0]=t.MusicalProgressions.diminished;break;case 14:case 15:n.effects[0].parameter_p[0]=t.MusicalProgressions.chromatic;break;case 16:case 17:n.effects[0].parameter_p[0]=t.MusicalProgressions.wholeTone}let g=p(0,s,1023)/1023,b=p(0,c,1023)/1023;n.volume=1*g,n.effects[1].effect=t.SoundSynthesizerEffects.volumeRampEffect,n.effects[1].steps=36,n.effects[1].parameter[0]=1*b;let y=Math.round(n.duration/1e4*m);switch(d){case 1:n.effects[2].steps=y,n.effects[2].effect=t.SoundSynthesizerEffects.frequencyVibratoEffect,n.effects[2].parameter[0]=h;break;case 2:n.effects[2].steps=y,n.effects[2].effect=t.SoundSynthesizerEffects.volumeVibratoEffect,n.effects[2].parameter[0]=h;break;case 3:n.effects[2].steps=y,n.effects[2].effect=t.SoundSynthesizerEffects.warbleInterpolation,n.effects[2].parameter[0]=h}return!0}function p(e,t,n){return Math.min(n,Math.max(e,t))}function f(e,t){if(e<0||t<0)return-1;const n=(i=2*t+1,Math.floor(Math.random()*i)-t);var i;return Math.abs(e+n)}function m(){const e={frequency:0,volume:1,duration:0,tone:{tonePrint:void 0,parameter:[0]},effects:[]};for(let n=0;n<t.EMOJI_SYNTHESIZER_TONE_EFFECTS;n++)e.effects.push({effect:void 0,step:0,steps:0,parameter:[],parameter_p:[]});return e}function g(e,t,n){return Math.min(Math.max(e,t),n)}t.isSoundExpPlaying=function(){return a},t.__playSoundExpression=function(t,n){o||(o=[]);const i=e.getResume(),s=new Promise(((e,s)=>{o.push({notes:t,onStarted:()=>{n||i()},onFinished:e,onCancelled:e})}));a||c(),n&&s.then(i)},t.clearSoundQueue=u,t.playSoundExpressionAsync=d,t.__stopSoundExpressions=function(){u(),e.AudioContextManager.stopAll()},t.parseSoundExpression=h}(t.music||(t.music={}))}(e.codal||(e.codal={}))}(pxsim||(pxsim={})),function(e){class t{constructor(e){this.id=e}}e.Button=t;e.ButtonPairState=class{constructor(e){this.props=e,this.usesButtonAB=!1,this.aBtn=new t(this.props.ID_BUTTON_A),this.bBtn=new t(this.props.ID_BUTTON_B),this.abBtn=new t(this.props.ID_BUTTON_AB),this.abBtn.virtual=!0}}}(pxsim||(pxsim={})),function(e){e.CompassState=class{constructor(){this.usesHeading=!1,this.heading=90}}}(pxsim||(pxsim={})),function(e){e.FileSystemState=class{constructor(){this.files={}}append(e,t){this.files[e]=(this.files[e]||"")+t}remove(e){delete this.files[e]}}}(pxsim||(pxsim={})),function(e){e.LightSensorState=class{constructor(){this.usesLightLevel=!1,this.lightLevel=128}}}(pxsim||(pxsim={})),function(e){!function(t){t.mkBoardView=e=>{const n=e.visual;return new t.GenericBoardSvg({visualDef:n,boardDef:e.boardDef,wireframe:e.wireframe})};t.BoardHost=class{constructor(n,i){this.parts=[],this.boardView=n,this.opts=i,i.boardDef.pinStyles||(i.boardDef.pinStyles={}),this.state=i.state;let s=i.partsList,r=0<s.length||i.forceBreadboardLayout;if(r){this.breadboard=new t.Breadboard({wireframe:i.wireframe});const n=i.boardDef.marginWhenBreadboarding||[0,0,40,0],o=t.composeSVG({el1:this.boardView.getView(),scaleUnit1:this.boardView.getPinDist(),el2:this.breadboard.getSVGAndSize(),scaleUnit2:this.breadboard.getPinDist(),margin:[n[0],n[1],20,n[3]],middleMargin:n[2],maxWidth:i.maxWidth,maxHeight:i.maxHeight}),a=o.under,l=o.over;this.view=o.host;const c=o.edges;this.fromMBCoord=o.toHostCoord1,this.fromBBCoord=o.toHostCoord2,this.partGroup=l,this.partOverGroup=e.svg.child(this.view,"g"),this.style=e.svg.child(this.view,"style",{}),this.defs=e.svg.child(this.view,"defs",{}),this.wireFactory=new t.WireFactory(a,l,c,this.style,this.getLocCoord.bind(this),this.getPinStyle.bind(this));const u=e.allocateDefinitions({boardDef:i.boardDef,partDefs:i.partDefs,fnArgs:i.fnArgs,getBBCoord:this.breadboard.getCoord.bind(this.breadboard),partsList:s});u.partsAndWires.length||i.forceBreadboardLayout?(this.addAll(u),u.requiresBreadboard||i.forceBreadboardRender?u.hideBreadboard&&this.breadboard&&this.breadboard.hide():r=!1):r=!1}if(!r){delete this.breadboard,delete this.wireFactory,delete this.partOverGroup,delete this.partGroup,delete this.style,delete this.defs,delete this.fromBBCoord,delete this.fromMBCoord;const t=this.boardView.getView().el;this.view=t,this.partGroup=e.svg.child(this.view,"g"),this.partOverGroup=e.svg.child(this.view,"g"),i.maxWidth&&e.svg.hydrate(this.view,{width:i.maxWidth}),i.maxHeight&&e.svg.hydrate(this.view,{height:i.maxHeight})}this.state.updateSubscribers.push((()=>this.updateState()))}highlightBoardPin(e){this.boardView.highlightPin(e)}removeEventListeners(){this.boardView.removeEventListeners&&this.boardView.removeEventListeners()}highlightBreadboardPin(e){this.breadboard.highlightLoc(e)}highlightWire(t){t.wires.forEach((t=>{e.U.addClass(t,"highlight"),t.style.visibility="visible"})),e.U.addClass(t.endG,"highlight")}getView(){return this.view}screenshotAsync(e){const t=this.view.classList.contains("sim")?this.view:this.view.querySelector(".sim"),n=t?t.cloneNode(!0):this.view.cloneNode(!0);n.setAttribute("width",n.viewBox.baseVal.width+""),n.setAttribute("height",n.viewBox.baseVal.height+"");const i=(new XMLSerializer).serializeToString(n),s="data:image/svg+xml,"+encodeURIComponent(i.replace(/\s+/g," ").replace(/"/g,"'"));return new Promise(((t,n)=>{const i=document.createElement("img");i.onload=()=>{const n=document.createElement("canvas");n.width=i.width,n.height=i.height,e>0?(n.width=e,n.height=i.height*e/i.width|0):n.width<200?(n.width*=2,n.height*=2):n.width>480&&(n.width/=2,n.height/=2);const s=n.getContext("2d");s.drawImage(i,0,0,n.width,n.height),t(s.getImageData(0,0,n.width,n.height))},i.onerror=e=>{console.log(e),t(void 0)},i.src=s}))}updateState(){this.parts.forEach((e=>e.updateState()))}getBBCoord(e){let t=this.breadboard.getCoord(e);return this.fromBBCoord(t)}getPinCoord(e){let t=this.boardView.getCoord(e);if(t)return this.fromMBCoord(t);console.error(`Unable to find coord for pin: ${e}`)}getLocCoord(e){let t;if("breadboard"===e.type){let n=e;t=this.getBBCoord(n)}else{let n=e.pin;t=this.getPinCoord(n)}return t||console.debug("Unknown location: "+name),t}getPinStyle(e){return"breadboard"==e.type?"female":this.opts.boardDef.pinStyles[e.pin]||"female"}addPart(n){let i=null;if(n.simulationBehavior){let e=n.simulationBehavior,t=this.state.builtinVisuals[e],s=this.state.builtinParts[e];i=t(),i.init(this.state.bus,s,this.view,n.params)}else{let e=n.visual;i=new t.GenericPart(e)}this.parts.push(i),this.partGroup.appendChild(i.element),i.overElement&&this.partOverGroup.appendChild(i.overElement),i.defs&&i.defs.forEach((e=>this.defs.appendChild(e))),this.style.textContent+=i.style||"";let s=n.startColumnIdx,r=n.startRowIdx,o={type:"breadboard",row:t.getRowName(r),col:t.getColumnName(s),xOffset:n.bbFit.xOffset/n.visual.pinDistance,yOffset:n.bbFit.yOffset/n.visual.pinDistance},a=this.getBBCoord(o);i.moveToCoord(a);let l=`sim-${n.name}-cmp`;return e.U.addClass(i.element,l),e.U.addClass(i.element,"sim-cmp"),i.updateTheme(),i.updateState(),i}addWire(e){return this.wireFactory.addWire(e.start,e.end,e.color)}addAll(e){e.partsAndWires.forEach((t=>{const n=t.wires,i=n&&n.every((e=>this.wireFactory.checkWire(e.start,e.end)));i&&n.forEach((t=>e.wires.push(this.addWire(t))));let s=t.part;!s||n&&!i||e.parts.push(this.addPart(s))})),e.requiresBreadboard=!!e.wires.length||!!e.parts.length}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){!function(t){const n=15,i="#DD4BA0",s=`\n /* bread board */\n .sim-bb-background {\n fill:#E0E0E0;\n }\n .sim-bb-pin {\n fill:#999;\n }\n .sim-bb-pin-hover {\n visibility: hidden;\n pointer-events: all;\n stroke-width: 7.5px;\n stroke: transparent;\n fill: #777;\n }\n .sim-bb-pin-hover:hover {\n visibility: visible;\n fill:#444;\n }\n .sim-bb-group-wire {\n stroke: #999;\n stroke-width: 3.75px;\n visibility: hidden;\n }\n .sim-bb-pin-group {\n pointer-events: all;\n }\n .sim-bb-label,\n .sim-bb-label-hover {\n font-family:"Lucida Console", Monaco, monospace;\n fill:#555;\n pointer-events: all;\n stroke-width: 0;\n cursor: default;\n }\n .sim-bb-label-hover {\n visibility: hidden;\n fill:#000;\n font-weight: bold;\n }\n .sim-bb-bar {\n stroke-width: 0;\n }\n .sim-bb-blue {\n fill:#1AA5D7;\n stroke:#1AA5D7\n }\n .sim-bb-red {\n fill:${i};\n stroke:${i};\n }\n .sim-bb-pin-group:hover .sim-bb-pin-hover,\n .sim-bb-pin-group:hover .sim-bb-group-wire,\n .sim-bb-pin-group:hover .sim-bb-label-hover {\n visibility: visible;\n }\n .sim-bb-pin-group:hover .sim-bb-label {\n visibility: hidden;\n }\n /* outline mode */\n .sim-bb-outline .sim-bb-background {\n stroke-width: ${n/7}px;\n fill: #FFF;\n stroke: #000;\n }\n .sim-bb-outline .sim-bb-mid-channel {\n fill: #FFF;\n stroke: #888;\n stroke-width: 2px;\n }\n /* grayed out */\n .grayed .sim-bb-background {\n stroke-width: 3px;\n }\n .grayed .sim-bb-red,\n .grayed .sim-bb-blue {\n fill: #BBB;\n }\n .grayed .sim-bb-bar {\n fill: #FFF;\n }\n .grayed .sim-bb-pin {\n fill: #000;\n stroke: #FFF;\n stroke-width: 3px;\n }\n .grayed .sim-bb-label {\n fill: none;\n }\n .grayed .sim-bb-background {\n stroke-width: 7.5px;\n stroke: #555;\n }\n .grayed .sim-bb-group-wire {\n stroke: #DDD;\n }\n .grayed .sim-bb-channel {\n visibility: hidden;\n }\n /* highlighted */\n .sim-bb-label.highlight {\n visibility: hidden;\n }\n .sim-bb-label-hover.highlight {\n visibility: visible;\n }\n .sim-bb-blue.highlight {\n fill:#1AA5D7;\n }\n .sim-bb-red.highlight {\n fill:${i};\n }\n .sim-bb-bar.highlight {\n stroke-width: 0px;\n }\n `;t.BREADBOARD_MID_ROWS=10,t.BREADBOARD_MID_COLS=30;const r=[4,4],o=t.BREADBOARD_MID_ROWS+r.length,a=25,l=[4,9,14,19],c=a+l.length,u=n*(t.BREADBOARD_MID_COLS+3),d=n*(o+4+5.5),h=2/3,p=d*h,f=.16666666666666669*d,m=(t.BREADBOARD_MID_COLS-1)*n,g=(u-m)/2,b=f+(p-(o-1)*n)/2,y=(c-1)*n,v=(u-y)/2,w=(f-15)/2,k=v,x=w+f+p,A=25.5,E=12,T=1.05,S=-90,C="abcdefghij".split("").reverse();function I(e){return`${e+1}`}function _(e){return C[e]}function P(t){let n=t.xOffset||0,i=t.yOffset||0,s=[],r=e.svg.elt("g"),o=t.colStartIdx||0,a=t.rowStartIdx||0,l=e=>e?e.slice(0,e.length):[],c=(e,t)=>{let n,i=0;for(;0<=(n=e.indexOf(t));)e.splice(n,1),i+=1;return i},u=0,d=l(t.rowIdxsWithGap);for(let h=0;h<t.rowCount;h++){let p=0,f=l(t.colIdxsWithGap),m=i+h*t.pinDist+u*t.pinDist,g=h+a;for(let i=0;i<t.colCount;i++){let a=n+i*t.pinDist+p*t.pinDist,l=i+o;const u=t=>(e.svg.hydrate(t.el,"circle"==t.el.tagName?{cx:a,cy:m}:{x:a-.5*t.w,y:m-.5*t.h}),r.appendChild(t.el),t.el);let d=u(t.mkPin()),h=u(t.mkHoverPin()),b=t.getRowName(g),y=t.getColName(l),v=t.getGroupName?t.getGroupName(g,l):null,w={el:d,hoverEl:h,cx:a,cy:m,row:b,col:y,group:v};s.push(w),p+=c(f,l)}u+=c(d,g)}return{g:r,allPins:s}}function U(){let t=e.svg.elt("rect");return e.svg.hydrate(t,{class:"sim-bb-pin",rx:2,ry:2,width:6,height:6}),{el:t,w:6,h:6,x:0,y:0}}function O(){let t=e.svg.elt("rect"),n=6*1.3;return e.svg.hydrate(t,{class:"sim-bb-pin-hover",rx:2,ry:2,width:n,height:n}),{el:t,w:n,h:n,x:0,y:0}}function N(n,i,s,r,o,a,l){let c=t.mkTxt(n,i,s,r,o);e.U.addClass(c,"sim-bb-label"),l&&l.forEach((t=>e.U.addClass(c,t)));let u=t.mkTxt(n,i,1.3*s,r,o);return e.U.addClass(u,"sim-bb-label-hover"),l&&l.forEach((t=>e.U.addClass(u,t))),{el:c,hoverEl:u,txt:o,group:a}}t.getColumnName=I,t.getRowName=_,t.mkGrid=P;t.Breadboard=class{constructor(t){this.allPins=[],this.allLabels=[],this.allPowerBars=[],this.rowColToPin={},this.rowColToLbls={},this.buildDom(),t.wireframe&&e.U.addClass(this.bb,"sim-bb-outline")}hide(){this.bb.style.display="none"}updateLocation(t,n){e.svg.hydrate(this.bb,{x:`${t}px`,y:`${n}px`})}getPin(e,t){let n=this.rowColToPin[e];if(!n)return null;let i=n[t];return i||null}getCoord(e){let{row:t,col:i,xOffset:s,yOffset:r}=e,o=this.getPin(t,i);if(!o)return null;let a=(s||0)*n,l=(r||0)*n;return[o.cx+a,o.cy+l]}getPinDist(){return n}buildDom(){this.bb=e.svg.elt("svg",{version:"1.0",viewBox:`0 0 ${u} ${d}`,class:"sim-bb",width:u+"px",height:d+"px"}),this.styleEl=e.svg.child(this.bb,"style",{}),this.styleEl.textContent+=s,this.defs=e.svg.child(this.bb,"defs",{}),e.svg.child(this.bb,"rect",{class:"sim-bb-background",width:u,height:d,rx:4.5,ry:4.5});let i="sim-bb-channel-grad",o=e.svg.elt("linearGradient");e.svg.hydrate(o,{id:i,x1:"0%",y1:"0%",x2:"0%",y2:"100%"}),this.defs.appendChild(o);e.svg.child(o,"stop",{offset:"0%",style:"stop-color: #AAA;"}),e.svg.child(o,"stop",{offset:"20%",style:"stop-color: #CCC;"}),e.svg.child(o,"stop",{offset:"80%",style:"stop-color: #CCC;"}),e.svg.child(o,"stop",{offset:"100%",style:"stop-color: #AAA;"});const c=(t,n,s)=>{let r=e.svg.child(this.bb,"rect",{class:`sim-bb-channel ${s||""}`,y:t-n/2,width:u,height:n});return r.setAttribute("fill",`url(#${i})`),r};c(f+p/2,15,"sim-bb-mid-channel"),c(f,.75,"sim-bb-sml-channel"),c(f+p,.75,"sim-bb-sml-channel");const h=(e,n)=>`${(e=>e<t.BREADBOARD_MID_ROWS/2?"b":"t")(e)}${I(n)}`,m=e=>0===e?"-":"+",C=(e,t)=>{let n=(e=>e<25?"b":"t")(t);return`${m(e)}${n}`};let R=P({xOffset:g,yOffset:b,rowCount:t.BREADBOARD_MID_ROWS,colCount:t.BREADBOARD_MID_COLS,pinDist:n,mkPin:U,mkHoverPin:O,getRowName:_,getColName:I,getGroupName:h,rowIdxsWithGap:r});R.g;this.allPins=this.allPins.concat(R.allPins);let M=P({xOffset:k,yOffset:x,rowCount:2,colCount:a,pinDist:n,mkPin:U,mkHoverPin:O,getRowName:m,getColName:I,getGroupName:C,colIdxsWithGap:l});M.g;this.allPins=this.allPins.concat(M.allPins);let D=P({xOffset:v,yOffset:w,rowCount:2,colCount:a,colStartIdx:a,pinDist:n,mkPin:U,mkHoverPin:O,getRowName:m,getColName:I,getGroupName:C,colIdxsWithGap:l.map((e=>e+a))});D.g;this.allPins=this.allPins.concat(D.allPins),this.allPins.forEach((t=>{let{el:n,row:i,col:s,hoverEl:r}=t,o=`(${i},${s})`;e.svg.hydrate(n,{title:o}),e.svg.hydrate(r,{title:o})})),this.allPins.forEach((e=>{let t=this.rowColToPin[e.row];t||(t=this.rowColToPin[e.row]={}),t[e.col]=e}));const L=(e,t,n,i,s,r)=>{let o=this.getCoord({type:"breadboard",row:e,col:t}),[a,l]=o;return N(a+n,l+i,10.5,-90,s,r)};for(let e=0;e<t.BREADBOARD_MID_COLS;e++){let n=I(e),i=0,s=L(_(i),n,0,-15,n,h(i,e));this.allLabels.push(s);let r=t.BREADBOARD_MID_ROWS-1,o=L(_(r),n,0,15,n,h(r,e));this.allLabels.push(o)}for(let e=0;e<t.BREADBOARD_MID_ROWS;e++){let n=_(e),i=L(n,I(0),-15,0,n);this.allLabels.push(i);let s=L(n,I(t.BREADBOARD_MID_COLS-1),15,0,n);this.allLabels.push(s)}let F=[N(13.05,f+p+E,30,S,"-",C(0,0),["sim-bb-blue"]),N(12,f+p+f-E,A,S,"+",C(1,0),["sim-bb-red"]),N(u-E+T,f+p+E,30,S,"-",C(0,24),["sim-bb-blue"]),N(u-E,f+p+f-E,A,S,"+",C(1,24),["sim-bb-red"])];this.allLabels=this.allLabels.concat(F);let B=[N(13.05,12,30,S,"-",C(0,a),["sim-bb-blue"]),N(12,f-E,A,S,"+",C(1,a),["sim-bb-red"]),N(u-E+T,12,30,S,"-",C(0,49),["sim-bb-blue"]),N(u-E,f-E,A,S,"+",C(1,49),["sim-bb-red"])];this.allLabels=this.allLabels.concat(B);let $={};this.allLabels.forEach((e=>{let{el:t,txt:n}=e;($[n]=$[n]||[]).push(e)}));this.allPins.forEach((e=>{let{row:t,col:n,group:i}=e,s=this.rowColToLbls[t]||(this.rowColToLbls[t]={}),r=s[n]||(s[n]=[]);if((e=>"-"===e.row||"+"===e.row)(e)){Number(n)<=a?F.filter((t=>t.group==e.group)).forEach((e=>r.push(e))):B.filter((t=>t.group==e.group)).forEach((e=>r.push(e)))}else{$[t].forEach((e=>r.push(e))),$[n].forEach((e=>r.push(e)))}}));const j=y+22.5,V=(j-y)/2,q=(t,n,i,s)=>{let r=e.svg.elt("rect");return e.svg.hydrate(r,{class:`sim-bb-bar ${s}`,x:t,y:n-1.5,width:j,height:3}),{el:r,group:i}};let H=[q(k-V,x-9,C(0,49),"sim-bb-blue"),q(k-V,x+n+9,C(1,49),"sim-bb-red"),q(v-V,w-9,C(0,0),"sim-bb-blue"),q(v-V,w+n+9,C(1,0),"sim-bb-red")];this.allPowerBars=this.allPowerBars.concat(H),this.allPowerBars.forEach((e=>this.bb.appendChild(e.el)));let G=this.allPins.map((e=>e.group)).filter(((e,t,n)=>n.indexOf(e)==t)),z=G.map((t=>e.svg.elt("g")));z.forEach((t=>e.U.addClass(t,"sim-bb-pin-group"))),z.forEach(((t,n)=>e.U.addClass(t,`group-${G[n]}`)));let W={};G.forEach(((e,t)=>W[e]=z[t]));let J={};this.allPins.forEach(((e,t)=>{let n=e.group;(J[n]||(J[n]=[])).push(e)})),G.forEach((t=>{let n=J[t],[i,s]=[n.map((e=>e.cx)),n.map((e=>e.cy))],r=e=>e.reduce(((e,t)=>e<t?e:t)),o=e=>e.reduce(((e,t)=>e>t?e:t)),[a,l,c,u]=[r(i),o(i),r(s),o(s)],d=e.svg.elt("rect"),h=Math.max(l-a,1e-4),p=Math.max(u-c,1e-4);e.svg.hydrate(d,{x:a,y:c,width:h,height:p}),e.U.addClass(d,"sim-bb-group-wire"),W[t].appendChild(d)})),this.allPins.forEach((e=>{let t=W[e.group];t.appendChild(e.el),t.appendChild(e.hoverEl)}));let Y=e.svg.elt("g");e.svg.hydrate(Y,{class:"sim-bb-group-misc"}),z.push(Y),this.allLabels.forEach((e=>{if(e.group){let t=W[e.group];t.appendChild(e.el),t.appendChild(e.hoverEl)}else Y.appendChild(e.el),Y.appendChild(e.hoverEl)})),z.forEach((e=>this.bb.appendChild(e)))}getSVGAndSize(){return{el:this.bb,y:0,x:0,w:u,h:d}}highlightLoc(t){let{row:n,col:i}=t,s=this.rowColToPin[n][i],{cx:r,cy:o}=s;this.rowColToLbls[n][i].forEach((t=>{e.U.addClass(t.el,"highlight"),e.U.addClass(t.hoverEl,"highlight")}))}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){!function(t){t.BOARD_SYTLE=`\n .noselect {\n -webkit-touch-callout: none; /* iOS Safari */\n -webkit-user-select: none; /* Chrome/Safari/Opera */\n -khtml-user-select: none; /* Konqueror */\n -moz-user-select: none; /* Firefox */\n -ms-user-select: none; /* Internet Explorer/Microsoft Edge */\n user-select: none; /* Non-prefixed version, currently\n not supported by any browser */\n }\n\n .sim-board-pin {\n fill:#999;\n stroke:#000;\n stroke-width:${t.PIN_DIST/3}px;\n }\n .sim-board-pin-lbl {\n fill: #333;\n }\n .gray-cover {\n fill:#FFF;\n opacity: 0.3;\n stroke-width:0;\n visibility: hidden;\n }\n .sim-board-pin-hover {\n visibility: hidden;\n pointer-events: all;\n stroke-width:${t.PIN_DIST/6}px;\n }\n .sim-board-pin-hover:hover {\n visibility: visible;\n }\n .sim-board-pin-lbl {\n visibility: hidden;\n }\n .sim-board-outline .sim-board-pin-lbl {\n visibility: visible;\n }\n .sim-board-pin-lbl {\n fill: #555;\n }\n .sim-board-pin-lbl-hover {\n fill: red;\n }\n .sim-board-outline .sim-board-pin-lbl-hover {\n fill: black;\n }\n .sim-board-pin-lbl,\n .sim-board-pin-lbl-hover {\n font-family:"Lucida Console", Monaco, monospace;\n pointer-events: all;\n stroke-width: 0;\n }\n .sim-board-pin-lbl-hover {\n visibility: hidden;\n }\n .sim-board-outline .sim-board-pin-hover:hover + .sim-board-pin-lbl,\n .sim-board-pin-lbl.highlight {\n visibility: hidden;\n }\n .sim-board-outline .sim-board-pin-hover:hover + * + .sim-board-pin-lbl-hover,\n .sim-board-pin-lbl-hover.highlight {\n visibility: visible;\n }\n /* Graying out */\n .grayed .sim-board-pin-lbl:not(.highlight) {\n fill: #AAA;\n }\n .grayed .sim-board-pin:not(.highlight) {\n fill:#BBB;\n stroke:#777;\n }\n .grayed .gray-cover {\n visibility: inherit;\n }\n .grayed .sim-cmp:not(.notgrayed) {\n opacity: 0.3;\n }\n /* Highlighting */\n .sim-board-pin-lbl.highlight {\n fill: #000;\n font-weight: bold;\n }\n .sim-board-pin.highlight {\n fill:#999;\n stroke:#000;\n }\n `;const n=.7*t.PIN_DIST,i=1.5*n,s=.66666*t.PIN_DIST,r=.66666*t.PIN_DIST+t.PIN_DIST/3;let o=0;t.GenericBoardSvg=class{constructor(a){this.props=a,this.allPins=[],this.allLabels=[],this.pinNmToLbl={},this.pinNmToPin={},this.id=o++;let l=a.visualDef,c=a.wireframe&&l.outlineImage?l.outlineImage:l.image,u=t.mkImageSVG({image:c,width:l.width,height:l.height,imageUnitDist:l.pinDist,targetUnitDist:t.PIN_DIST}),d=t.mkScaleFn(l.pinDist,t.PIN_DIST);this.width=u.w,this.height=u.h;let h=u.el;this.element=e.svg.elt("svg"),e.svg.hydrate(this.element,{version:"1.0",viewBox:`0 0 ${this.width} ${this.height}`,class:`sim sim-board-id-${this.id}`,x:"0px",y:"0px"}),a.wireframe&&e.U.addClass(this.element,"sim-board-outline"),this.style=e.svg.child(this.element,"style",{}),this.style.textContent+=t.BOARD_SYTLE,this.defs=e.svg.child(this.element,"defs",{}),this.g=e.svg.elt("g"),this.element.appendChild(this.g),this.g.appendChild(h),this.background=h,e.svg.hydrate(h,{class:"sim-board"});const p=()=>{let t=e.svg.elt("circle"),n=s;return e.svg.hydrate(t,{class:"sim-board-pin",r:n/2}),{el:t,w:n,h:n,x:0,y:0}},f=()=>{let t=e.svg.elt("circle"),n=r;return e.svg.hydrate(t,{class:"sim-board-pin-hover",r:n/2}),{el:t,w:n,h:n,x:0,y:0}},m=()=>{let t=e.svg.elt("rect"),n=s;return e.svg.hydrate(t,{class:"sim-board-pin",width:n,height:n}),{el:t,w:n,h:n,x:0,y:0}},g=()=>{let t=e.svg.elt("rect"),n=r;return e.svg.hydrate(t,{class:"sim-board-pin-hover",width:n,height:n}),{el:t,w:n,h:n,x:0,y:0}};let b=l.pinBlocks.map(((n,i)=>{let s=d(n.x)+t.PIN_DIST/2,r=d(n.y)+t.PIN_DIST/2,o=n.labels.length,a=t.mkGrid({xOffset:s,yOffset:r,rowCount:1,colCount:o,pinDist:t.PIN_DIST,mkPin:l.useCrocClips?p:m,mkHoverPin:l.useCrocClips?f:g,getRowName:()=>`${i+1}`,getColName:e=>n.labels[e],getGroupName:()=>n.labels.join(" ")});a.allPins,a.g;return e.U.addClass(a.g,"sim-board-pin-group"),a})),y=[];b.forEach(((e,t)=>e.allPins.forEach(((e,n)=>{this.allPins.push(e),y.push(l.pinBlocks[t])})))),this.allPins.forEach((t=>{let n=t.col;e.svg.hydrate(t.el,{title:n}),e.svg.hydrate(t.hoverEl,{title:n})})),this.allPins.forEach((e=>{this.pinNmToPin[e.col]=e}));const v=(e,n,i,s,r)=>{let o,a;if("below"===r){a=e,o=n+12+.25*i*s.length}else{a=e,o=n-11-.32*i*s.length}return t.mkTxt(a,o,i,-90,s)};this.allLabels=this.allPins.map(((t,s)=>{let r=y[s];return((t,s,r,o)=>{let a=v(t,s,n,r,o);e.U.addClass(a,"sim-board-pin-lbl");let l=v(t,s,i,r,o);return e.U.addClass(l,"sim-board-pin-lbl-hover"),{el:a,hoverEl:l,txt:r}})(t.cx,t.cy,t.col,r.labelPosition||"above")})),this.allPins.forEach(((e,t)=>{let n=this.allLabels[t];this.pinNmToLbl[e.col]=n})),this.allPins.forEach(((e,t)=>{let n=this.allLabels[t];this.g.appendChild(e.el),this.g.appendChild(e.hoverEl),this.g.appendChild(n.el),this.g.appendChild(n.hoverEl)}))}findPin(e){let t=this.pinNmToPin[e];return!t&&this.props.boardDef.gpioPinMap&&(e=this.props.boardDef.gpioPinMap[e])&&(t=this.pinNmToPin[e]),t}findPinLabel(e){let t=this.pinNmToLbl[e];return!t&&this.props.boardDef.gpioPinMap&&(e=this.props.boardDef.gpioPinMap[e])&&(t=this.pinNmToLbl[e]),t}getCoord(e){let t=this.findPin(e);return t?[t.cx,t.cy]:null}mkGrayCover(t,n,i,s){let r=e.svg.elt("rect");return e.svg.hydrate(r,{x:t,y:n,width:i,height:s,class:"gray-cover"}),r}getView(){return{el:this.element,w:this.width,h:this.height,x:0,y:0}}getPinDist(){return t.PIN_DIST}highlightPin(t){let n=this.findPinLabel(t),i=this.findPin(t);n&&i&&(e.U.addClass(n.el,"highlight"),e.U.addClass(n.hoverEl,"highlight"),e.U.addClass(i.el,"highlight"),e.U.addClass(i.hoverEl,"highlight"))}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){!function(t){function n(e){return t.mkImageSVG({image:e.image,width:e.width,height:e.height,imageUnitDist:e.pinDistance,targetUnitDist:t.PIN_DIST})}t.mkGenericPartSVG=n;t.GenericPart=class{constructor(t){this.style="",this.defs=[];let i=n(t).el;this.element=e.svg.elt("g"),this.element.appendChild(i)}moveToCoord(e){t.translateEl(this.element,e)}init(e,t,n){}updateState(){}updateTheme(){}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){!function(t){const n=t.PIN_DIST/2.5,i=.7;function s(e){return e.replace(/\#/g,"-").replace(/\(/g,"-").replace(/\)/g,"-").replace(/\,/g,"-").replace(/\./g,"-").replace(/\s/g,"")}let r;function o(t,n,i,s){const r=e=>`${e[0]}, ${e[1]}`;let[o,a]=t,[l,c]=n,u=c-a,d=[o,a+u*i],h=[l,c-u*i],p=e.svg.mkPath("sim-bb-wire",`M${r(t)} C${r(d)} ${r(h)} ${r(n)}`);return e.U.addClass(p,`wire-stroke-${s}`),p}function a(t,n,i){const s=e=>`${e[0]}, ${e[1]}`;let r=e.svg.mkPath("sim-bb-wire",`M${s(t)} L${s(n)}`);return e.U.addClass(r,`wire-stroke-${i}`),r}function l(i,s){const r=t.PIN_DIST/4;let o=e.svg.elt("circle"),a=i[0],l=i[1],c=n/2+r/2;return e.svg.hydrate(o,{cx:a,cy:l,r:c,class:"sim-bb-wire-end"}),e.U.addClass(o,`wire-fill-${s}`),o.style["stroke-width"]=`${r}px`,o}function c(n,i,s){let r=.24*t.PIN_DIST,o=10*r,a=2*r,l=6*r,c=r;const u=t.PIN_DIST/4;let[d,h]=n,p=i?-1:1,f=e.svg.elt("g"),m=e.svg.elt("rect"),g=o,b=a,y=d-b/2,v=h-g/2;e.svg.hydrate(m,{x:y,y:v,width:b,height:g,rx:.5,ry:.5,class:"sim-bb-wire-end"}),m.style["stroke-width"]=`${u}px`;let w=e.svg.elt("rect"),k=l,x=c,A=d-x/2,E=h+p*(g/2+k/2)-k/2;return e.svg.hydrate(w,{x:A,y:E,width:x,height:k,class:"sim-bb-wire-bare-end"}),w.style.fill="#bbb",f.appendChild(w),f.appendChild(m),{el:f,x:y-u,y:Math.min(v,E),w:b+2*u,h:g+k}}function u(n,i,s){let r=.24*t.PIN_DIST;const o=4*r,a=10*r,l=3.5*r,c=3.5*r,u=t.PIN_DIST/4;let[d,h]=n,p=i?-1:1,f=e.svg.elt("g"),m=e.svg.elt("polygon"),g=a,b=o,y=d-b/2,v=h-g/2;const w=i?.15:.3,k=i?.7:1-.7,x=i?.3:.15;e.svg.hydrate(m,{points:((...e)=>e.map((e=>(e=>`${e[0]},${e[1]}`)(e))).join(" "))([y+b*w,v],[y+b*(1-w),v],[y+b,v+g*k],[y+b*(1-x),v+g],[y+b*x,v+g],[y,v+g*k])}),e.svg.hydrate(m,{rx:.5,ry:.5,class:"sim-bb-wire-end"}),m.style["stroke-width"]=`${u}px`;let A=e.svg.elt("rect"),E=l,T=c,S=d-T/2,C=h+p*(g/2+E/2)-E/2;return e.svg.hydrate(A,{x:S,y:C,width:T,height:E,class:"sim-bb-wire-bare-end"}),f.appendChild(A),f.appendChild(m),{el:f,x:y-u,y:Math.min(v,C),w:b+2*u,h:g+E}}t.WIRES_CSS=`\n .sim-bb-wire {\n fill:none;\n stroke-linecap: round;\n stroke-width:${n}px;\n pointer-events: none;\n }\n .sim-bb-wire-end {\n stroke:#333;\n fill:#333;\n }\n .sim-bb-wire-bare-end {\n fill: #ccc;\n }\n .sim-bb-wire-hover {\n stroke-width: ${n}px;\n visibility: hidden;\n stroke-dasharray: ${t.PIN_DIST/10},${t.PIN_DIST/1.5};\n /*stroke-opacity: 0.4;*/\n }\n .grayed .sim-bb-wire-ends-g:not(.highlight) .sim-bb-wire-end {\n stroke: #777;\n fill: #777;\n }\n .grayed .sim-bb-wire:not(.highlight) {\n stroke: #CCC;\n }\n .sim-bb-wire-ends-g:hover .sim-bb-wire-end {\n stroke: red;\n fill: red;\n }\n .sim-bb-wire-ends-g:hover .sim-bb-wire-bare-end {\n stroke: #FFF;\n fill: #FFF;\n }\n `,function(e){e[e.BBJumper=0]="BBJumper",e[e.OpenJumper=1]="OpenJumper",e[e.Croc=2]="Croc"}(r=t.WireEndStyle||(t.WireEndStyle={})),t.mkWirePart=function(n,i,s=!1){let r,o=e.svg.elt("g"),[a,l]=n,d=[a-15,l-50],h=[a+15,l+50];i=t.mapWireColor(i),r=s?u(d,!0,i):c(d,!0,i);let p=function(t,n,i){const s=e=>`${e[0]}, ${e[1]}`;let[r,o]=t,[a,l]=n,c=l-o,u=[r,o+.8*c],d=[a,l-.8*c],h=e.svg.mkPath("sim-bb-wire",`M${s(t)} C${s(u)} ${s(d)} ${s(n)}`);return h.style.stroke=i,{el:h,x:Math.min(r,a),y:Math.min(o,l),w:Math.abs(r-a),h:Math.abs(o-l)}}(d,h,i),f=c(h,!1,i);o.appendChild(p.el),o.appendChild(r.el),o.appendChild(f.el);let m=Math.min(r.x,f.x),g=Math.max(r.x+r.w,f.x+f.w),b=Math.min(r.y,f.y);return{el:o,x:m,y:b,w:g-m,h:Math.max(r.y+r.h,f.y+f.h)-b}};t.WireFactory=class{constructor(e,n,i,s,r,o){this.nextWireId=0,this.styleEl=s,this.styleEl.textContent+=t.WIRES_CSS,this.underboard=e,this.overboard=n,this.boardEdges=i,this.getLocCoord=r,this.getPinStyle=o}indexOfMin(e){let t=0,n=e[0];for(let i=1;i<e.length;i++)e[i]<n&&(n=e[i],t=i);return t}closestEdgeIdx(e){let t=this.boardEdges.map((t=>Math.abs(e[1]-t)));return this.indexOfMin(t)}closestEdge(e){return this.boardEdges[this.closestEdgeIdx(e)]}drawWire(n,r,c){let u=[],d=e.svg.child(this.overboard,"g",{class:"sim-bb-wire-group"});const h=e=>{const n=t.PIN_DIST/2;let i,s=this.closestEdge(e);return i=s-e[1]<0?s-n:s+n,[e[0],i]};let p=this.nextWireId++,f=s(c),m=l(n,f),g=l(r,f),b=e.svg.child(d,"g",{class:"sim-bb-wire-ends-g"});b.appendChild(m),b.appendChild(g);let y=this.closestEdgeIdx(n),v=this.closestEdgeIdx(r);if(y==v){let e=a(n,r,f);d.appendChild(e),u.push(e)}else{let t,s,l=h(n),c=h(r),m=a(n,l,f),g=a(r,c,f);!(1!=y&&2!=y||1!=v&&2!=v)?(t=o(l,c,i,f),s=o(l,c,i,f)):(t=a(l,c,f),s=a(l,c,f)),e.U.addClass(s,"sim-bb-wire-hover"),d.appendChild(m),u.push(m),d.appendChild(g),u.push(g),this.underboard.appendChild(t),u.push(t),d.appendChild(s),u.push(s);let w=`sim-bb-wire-id-${p}`;const k=t=>e.U.addClass(t,w);k(b),k(s),this.styleEl.textContent+=`\n .${w}:hover ~ .${w}.sim-bb-wire-hover {\n visibility: visible;\n }`}let w=`\n .wire-stroke-${f} {\n stroke: ${t.mapWireColor(c)};\n }\n .wire-fill-${f} {\n fill: ${t.mapWireColor(c)};\n }\n `;return this.styleEl.textContent+=w,{endG:b,end1:m,end2:g,wires:u}}drawWireWithCrocs(n,r,c,d=!1){let h=[],p=e.svg.child(this.overboard,"g",{class:"sim-bb-wire-group"});const f=e=>{const n=t.PIN_DIST/2;let i,s=this.closestEdge(e);return i=s-e[1]<0?s-n:s+n,[e[0],i]};let m=this.nextWireId++,g=s(c),b=l(n,g),y=r,[v,w]=r;r=[v,w+40],[v,w]=r;let k,x=[v,w+-17];k=d?function(n,i,s){let r=.24*t.PIN_DIST,o=4*r,a=1.2*r,l=10*r,c=r;const u=t.PIN_DIST/4;let[d,h]=n,p=i?-1:1,f=e.svg.elt("g"),m=e.svg.elt("rect"),g=o,b=a,y=d-b/2,v=h+10-g/2;e.svg.hydrate(m,{x:y,y:v,width:b,height:g,rx:.5,ry:.5,class:"sim-bb-wire-end"}),m.style["stroke-width"]=`${u}px`;let w=e.svg.elt("rect"),k=l,x=c,A=d-x/2,E=h+10+p*(g/2+k/2)-k/2;return e.svg.hydrate(w,{x:A,y:E,width:x,height:k,class:"sim-bb-wire-bare-end"}),w.style.fill="#bbb",f.appendChild(w),f.appendChild(m),{el:f,x:y-u,y:Math.min(v,E),w:b+2*u,h:g+k}}(x,!0):u(x,!0);let A=k.el,E=e.svg.child(p,"g",{class:"sim-bb-wire-ends-g"});E.appendChild(b);let T=this.closestEdgeIdx(n),S=this.closestEdgeIdx(y);if(T==S){let e=a(n,r,g);p.appendChild(e),h.push(e)}else{let t,s,l=f(n),c=a(n,l,g);!(1!=T&&2!=T||1!=S&&2!=S)?(t=o(l,r,i,g),s=o(l,r,i,g)):(t=a(l,r,g),s=a(l,r,g)),e.U.addClass(s,"sim-bb-wire-hover"),p.appendChild(c),h.push(c),this.underboard.appendChild(t),h.push(t);let u=`sim-bb-wire-id-${m}`;const d=t=>e.U.addClass(t,u);d(E),d(s),this.styleEl.textContent+=`\n .${u}:hover ~ .${u}.sim-bb-wire-hover {\n visibility: visible;\n }`}E.appendChild(A);let C=`\n .wire-stroke-${g} {\n stroke: ${t.mapWireColor(c)};\n }\n .wire-fill-${g} {\n fill: ${t.mapWireColor(c)};\n }\n `;return this.styleEl.textContent+=C,{endG:E,end1:b,end2:A,wires:h}}checkWire(e,t){let n=this.getLocCoord(e),i=this.getLocCoord(t);return!!n&&!!i}addWire(e,t,n){let i=this.getLocCoord(e),s=this.getLocCoord(t);if(!i||!s)return void console.debug(`unable to allocate wire for ${e} or ${t}`);let r,o=this.getPinStyle(t);return r="dalboard"==t.type&&"croc"==o?this.drawWireWithCrocs(i,s,n):this.drawWire(i,s,n),r}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={}));
1
+ var e=function(){"use strict";function t(e,t){postMessage({action:$e,cbn:t,result:e})}function n(e){var t=[];return t[e-1]=void 0,t}function i(e,t){return o(e[0]+t[0],e[1]+t[1])}function s(e,t){return function(e,t){var n;return n=t,0>t&&(n+=Ve),[n,e*Ve]}(~~Math.max(Math.min(e[1]/Ve,2147483647),-2147483648)&~~Math.max(Math.min(t[1]/Ve,2147483647),-2147483648),c(e)&c(t))}function r(e,t){var n,i;return e[0]==t[0]&&e[1]==t[1]?0:(n=0>e[1],i=0>t[1],n&&!i?-1:!n&&i?1:p(e,t)[1]<0?-1:1)}function o(e,t){var n,i;for(e%=0x10000000000000000,t=(t%=0x10000000000000000)-(n=t%Ve)+(i=Math.floor(e/Ve)*Ve),e=e-i+n;0>e;)e+=Ve,t-=Ve;for(;e>4294967295;)e-=Ve,t+=Ve;for(t%=0x10000000000000000;t>0x7fffffff00000000;)t-=0x10000000000000000;for(;-0x8000000000000000>t;)t+=0x10000000000000000;return[e,t]}function a(e,t){return e[0]==t[0]&&e[1]==t[1]}function l(e){return e>=0?[e,0]:[e+Ve,-Ve]}function c(e){return e[0]>=2147483648?~~Math.max(Math.min(e[0]-Ve,2147483647),-2147483648):~~Math.max(Math.min(e[0],2147483647),-2147483648)}function u(e){return 30>=e?1<<e:u(30)*u(e-30)}function d(e,t){var n,i,s,r;if(t&=63,a(e,He))return t?Ge:e;if(0>e[1])throw Error("Neg");return r=u(t),i=e[1]*r%0x10000000000000000,(i+=n=(s=e[0]*r)-s%Ve)>=0x8000000000000000&&(i-=0x10000000000000000),[s-=n,i]}function h(e,t){var n;return n=u(t&=63),o(Math.floor(e[0]/n),e[1]/n)}function p(e,t){return o(e[0]-t[0],e[1]-t[1])}function f(e,t){return e.Mc=t,e.Lc=0,e.Yb=t.length,e}function m(e){return e.Lc>=e.Yb?-1:255&e.Mc[e.Lc++]}function g(e,t,n,i){return e.Lc>=e.Yb?-1:(i=Math.min(i,e.Yb-e.Lc),k(e.Mc,e.Lc,t,n,i),e.Lc+=i,i)}function b(e){return e.Mc=n(32),e.Yb=0,e}function y(e){var t=e.Mc;return t.length=e.Yb,t}function v(e,t){e.Mc[e.Yb++]=t<<24>>24}function w(e,t,n,i){k(t,n,e.Mc,e.Yb,i),e.Yb+=i}function k(e,t,n,i,s){for(var r=0;s>r;++r)n[i+r]=e[t+r]}function x(t,n,i,s,o){var a,l;if(r(s,qe)<0)throw Error("invalid length "+s);for(t.Tb=s,function(e,t){(function(e,t){e.ab=t;for(var n=0;t>1<<n;++n);e.$b=2*n})(t,1<<e.s),t.n=e.f,function(e,t){var n=e.X;e.X=t,e.b&&n!=e.X&&(e.wb=-1,e.b=null)}(t,e.m),t.eb=0,t.fb=3,t.Y=2,t.y=3}(o,a=Y({})),a.Gc=void 0===e.disableEndMark,function(e,t){e.fc[0]=9*(5*e.Y+e.eb)+e.fb<<24>>24;for(var n=0;4>n;++n)e.fc[1+n]=e.ab>>8*n<<24>>24;w(t,e.fc,0,5)}(a,i),l=0;64>l;l+=8)v(i,255&c(h(s,l)));t.yb=(a.W=0,a.oc=n,a.pc=0,function(e){var t,n;e.b||(t={},n=4,e.X||(n=2),function(e,t){e.qb=t>2,e.qb?(e.w=0,e.xb=4,e.R=66560):(e.w=2,e.xb=3,e.R=0)}(t,n),e.b=t),he(e.A,e.eb,e.fb),(e.ab!=e.wb||e.Hb!=e.n)&&(U(e.b,e.ab,4096,e.n,274),e.wb=e.ab,e.Hb=e.n)}(a),a.d.Ab=i,function(e){(function(e){e.l=0,e.J=0;for(var t=0;4>t;++t)e.v[t]=0})(e),function(e){e.mc=Ge,e.xc=Ge,e.E=-1,e.Jb=1,e.Oc=0}(e.d),_e(e.C),_e(e._),_e(e.bb),_e(e.hb),_e(e.Ub),_e(e.vc),_e(e.Sb),function(e){var t,n=1<<e.u+e.I;for(t=0;n>t;++t)_e(e.V[t].tb)}(e.A);for(var t=0;4>t;++t)_e(e.K[t].G);oe(e.$,1<<e.Y),oe(e.i,1<<e.Y),_e(e.S.G),e.N=0,e.jb=0,e.q=0,e.s=0}(a),X(a),K(a),a.$.rb=a.n+1-2,de(a.$,1<<a.Y),a.i.rb=a.n+1-2,de(a.i,1<<a.Y),a.g=Ge,function(e,t){return e.cb=t,e.Z=null,e.zc=1,e}({},a))}function A(e,t,n){return e.Nb=b({}),x(e,f({},t),e.Nb,l(t.length),n),e}function E(e,t,n){var i,s,r,o,a="",c=[];for(s=0;5>s;++s){if(-1==(r=m(t)))throw Error("truncated input");c[s]=r<<24>>24}if(!function(e,t){var n,i,s,r,o,a,l;if(5>t.length)return 0;for(l=255&t[0],s=l%9,r=(a=~~(l/9))%5,o=~~(a/5),n=0,i=0;4>i;++i)n+=(255&t[1+i])<<8*i;return n>99999999||!function(e,t,n,i){if(t>8||n>4||i>4)return 0;z(e.gb,n,t);var s=1<<i;return V(e.Rb,s),V(e.sb,s),e.Dc=s-1,1}(e,s,r,o)?0:function(e,t){return 0>t?0:(e.Ob!=t&&(e.Ob=t,e.nb=Math.max(e.Ob,1),R(e.B,Math.max(e.nb,4096))),1)}(e,n)}(i=j({}),c))throw Error("corrupted input");for(s=0;64>s;s+=8){if(-1==(r=m(t)))throw Error("truncated input");1==(r=r.toString(16)).length&&(r="0"+r),a=r+""+a}/^0+$|^f+$/i.test(a)?e.Tb=qe:(o=parseInt(a,16),e.Tb=o>4294967295?qe:l(o)),e.yb=function(e,t,n,i){return e.e.Ab=t,L(e.B),e.B.cc=n,function(e){e.B.h=0,e.B.o=0,_e(e.Gb),_e(e.pb),_e(e.Zb),_e(e.Cb),_e(e.Db),_e(e.Eb),_e(e.kc),function(e){var t,n;for(n=1<<e.u+e.I,t=0;n>t;++t)_e(e.V[t].Ib)}(e.gb);for(var t=0;4>t;++t)_e(e.kb[t].G);G(e.Rb),G(e.sb),_e(e.Fb.G),function(e){e.Bb=0,e.E=-1;for(var t=0;5>t;++t)e.Bb=e.Bb<<8|m(e.Ab)}(e.e)}(e),e.U=0,e.ib=0,e.Jc=0,e.Ic=0,e.Qc=0,e.Nc=i,e.g=Ge,e.jc=0,function(e,t){return e.Z=t,e.cb=null,e.zc=1,e}({},e)}(i,t,n,e.Tb)}function T(e,t){return e.Nb=b({}),E(e,f({},t),e.Nb),e}function S(e,t){return e.c[e.f+e.o+t]}function C(e,t,n,i){var s,r;for(e.T&&e.o+t+i>e.h&&(i=e.h-(e.o+t)),++n,r=e.f+e.o+t,s=0;i>s&&e.c[r+s]==e.c[r+s-n];++s);return s}function I(e){return e.h-e.o}function _(e){var t,n;if(!e.T)for(;;){if(!(n=-e.f+e.Kb-e.h))return;if(-1==(t=g(e.cc,e.c,e.f+e.h,n)))return e.zb=e.h,e.f+e.zb>e.H&&(e.zb=e.H-e.f),void(e.T=1);e.h+=t,e.h>=e.o+e._b&&(e.zb=e.h-e._b)}}function P(e,t){e.f+=t,e.zb-=t,e.o-=t,e.h-=t}function U(e,t,i,s,r){var o,a;1073741567>t&&(e.Fc=16+(s>>1),function(e,t,i,s){var r;e.Bc=t,e._b=i,r=t+i+s,(null==e.c||e.Kb!=r)&&(e.c=null,e.Kb=r,e.c=n(e.Kb)),e.H=e.Kb-i}(e,t+i,s+r,256+~~((t+i+s+r)/2)),e.ob=s,o=t+1,e.p!=o&&(e.L=n(2*(e.p=o))),a=65536,e.qb&&(a=t-1,a|=a>>1,a|=a>>2,a|=a>>4,a|=a>>8,a>>=1,(a|=65535)>16777216&&(a>>=1),e.Ec=a,++a,a+=e.R),a!=e.rc&&(e.ub=n(e.rc=a)))}function O(e){var t;++e.k>=e.p&&(e.k=0),function(e){++e.o,e.o>e.zb&&(e.f+e.o>e.H&&function(e){var t,n,i;for((i=e.f+e.o-e.Bc)>0&&--i,n=e.f+e.h-i,t=0;n>t;++t)e.c[t]=e.c[i+t];e.f-=i}(e),_(e))}(e),1073741823==e.o&&(t=e.o-e.p,N(e.L,2*e.p,t),N(e.ub,e.rc,t),P(e,t))}function N(e,t,n){var i,s;for(i=0;t>i;++i)n>=(s=e[i]||0)?s=0:s-=n,e[i]=s}function R(e,t){(null==e.Lb||e.M!=t)&&(e.Lb=n(t)),e.M=t,e.o=0,e.h=0}function M(e){var t=e.o-e.h;t&&(w(e.cc,e.Lb,e.h,t),e.o>=e.M&&(e.o=0),e.h=e.o)}function D(e,t){var n=e.o-t-1;return 0>n&&(n+=e.M),e.Lb[n]}function L(e){M(e),e.cc=null}function F(e){return 4>(e-=2)?e:3}function B(e){return 4>e?0:10>e?e-3:e-6}function $(e){if(!e.zc)throw Error("bad state");return e.cb?function(e){(function(e,t,n,s){var o,u,d,h,f,m,g,b,y,v,w,k,x,A,E;if(t[0]=Ge,n[0]=Ge,s[0]=1,e.oc&&(e.b.cc=e.oc,function(e){e.f=0,e.o=0,e.h=0,e.T=0,_(e),e.k=0,P(e,-1)}(e.b),e.W=1,e.oc=null),!e.pc){if(e.pc=1,A=e.g,a(e.g,Ge)){if(!I(e.b))return void Q(e,c(e.g));ie(e),x=c(e.g)&e.y,Pe(e.d,e.C,(e.l<<4)+x,0),e.l=B(e.l),d=S(e.b,-e.s),fe(pe(e.A,c(e.g),e.J),e.d,d),e.J=d,--e.s,e.g=i(e.g,ze)}if(!I(e.b))return void Q(e,c(e.g));for(;;){if(g=Z(e,c(e.g)),v=e.mb,x=c(e.g)&e.y,u=(e.l<<4)+x,1==g&&-1==v)Pe(e.d,e.C,u,0),d=S(e.b,-e.s),E=pe(e.A,c(e.g),e.J),7>e.l?fe(E,e.d,d):(y=S(e.b,-e.v[0]-1-e.s),me(E,e.d,y,d)),e.J=d,e.l=B(e.l);else{if(Pe(e.d,e.C,u,1),4>v){if(Pe(e.d,e.bb,e.l,1),v?(Pe(e.d,e.hb,e.l,1),1==v?Pe(e.d,e.Ub,e.l,0):(Pe(e.d,e.Ub,e.l,1),Pe(e.d,e.vc,e.l,v-2))):(Pe(e.d,e.hb,e.l,0),Pe(e.d,e._,u,1==g?0:1)),1==g?e.l=7>e.l?9:11:(le(e.i,e.d,g-2,x),e.l=7>e.l?8:11),h=e.v[v],0!=v){for(m=v;m>=1;--m)e.v[m]=e.v[m-1];e.v[0]=h}}else{for(Pe(e.d,e.bb,e.l,0),e.l=7>e.l?7:10,le(e.$,e.d,g-2,x),k=re(v-=4),b=F(g),xe(e.K[b],e.d,k),k>=4&&(w=v-(o=(2|1&k)<<(f=(k>>1)-1)),14>k?Se(e.Sb,o-k-1,e.d,f,w):(Ue(e.d,w>>4,f-4),Ee(e.S,e.d,15&w),++e.Qb)),h=v,m=3;m>=1;--m)e.v[m]=e.v[m-1];e.v[0]=h,++e.Mb}e.J=S(e.b,g-1-e.s)}if(e.s-=g,e.g=i(e.g,l(g)),!e.s){if(e.Mb>=128&&X(e),e.Qb>=16&&K(e),t[0]=e.g,n[0]=Oe(e.d),!I(e.b))return void Q(e,c(e.g));if(r(p(e.g,A),[4096,0])>=0)return e.pc=0,void(s[0]=0)}}}})(e.cb,e.cb.Xb,e.cb.uc,e.cb.Kc),e.Pb=e.cb.Xb[0],e.cb.Kc[0]&&(function(e){se(e),e.d.Ab=null}(e.cb),e.zc=0)}(e):function(e){var t=function(e){var t,n,s,o,a,u;if(u=c(e.g)&e.Dc,Ie(e.e,e.Gb,(e.U<<4)+u)){if(Ie(e.e,e.Zb,e.U))s=0,Ie(e.e,e.Cb,e.U)?(Ie(e.e,e.Db,e.U)?(Ie(e.e,e.Eb,e.U)?(n=e.Qc,e.Qc=e.Ic):n=e.Ic,e.Ic=e.Jc):n=e.Jc,e.Jc=e.ib,e.ib=n):Ie(e.e,e.pb,(e.U<<4)+u)||(e.U=7>e.U?9:11,s=1),s||(s=q(e.sb,e.e,u)+2,e.U=7>e.U?8:11);else if(e.Qc=e.Ic,e.Ic=e.Jc,e.Jc=e.ib,s=2+q(e.Rb,e.e,u),e.U=7>e.U?7:10,(a=we(e.kb[F(s)],e.e))>=4){if(o=(a>>1)-1,e.ib=(2|1&a)<<o,14>a)e.ib+=function(e,t,n,i){var s,r,o=1,a=0;for(r=0;i>r;++r)s=Ie(n,e,t+o),o<<=1,o+=s,a|=s<<r;return a}(e.kc,e.ib-a-1,e.e,o);else if(e.ib+=function(e,t){var n,i,s=0;for(n=t;0!=n;--n)e.E>>>=1,i=e.Bb-e.E>>>31,e.Bb-=e.E&i-1,s=s<<1|1-i,-16777216&e.E||(e.Bb=e.Bb<<8|m(e.Ab),e.E<<=8);return s}(e.e,o-4)<<4,e.ib+=function(e,t){var n,i,s=1,r=0;for(i=0;e.F>i;++i)n=Ie(t,e.G,s),s<<=1,s+=n,r|=n<<i;return r}(e.Fb,e.e),0>e.ib)return-1==e.ib?1:-1}else e.ib=a;if(r(l(e.ib),e.g)>=0||e.ib>=e.nb)return-1;(function(e,t,n){var i=e.o-t-1;for(0>i&&(i+=e.M);0!=n;--n)i>=e.M&&(i=0),e.Lb[e.o++]=e.Lb[i++],e.o>=e.M&&M(e)})(e.B,e.ib,s),e.g=i(e.g,l(s)),e.jc=D(e.B,0)}else t=function(e,t,n){return e.V[((t&e.qc)<<e.u)+((255&n)>>>8-e.u)]}(e.gb,c(e.g),e.jc),e.jc=7>e.U?function(e,t){var n=1;do{n=n<<1|Ie(t,e.Ib,n)}while(256>n);return n<<24>>24}(t,e.e):function(e,t,n){var i,s,r=1;do{if(s=n>>7&1,n<<=1,i=Ie(t,e.Ib,(1+s<<8)+r),r=r<<1|i,s!=i){for(;256>r;)r=r<<1|Ie(t,e.Ib,r);break}}while(256>r);return r<<24>>24}(t,e.e,D(e.B,e.ib)),function(e,t){e.Lb[e.o++]=t,e.o>=e.M&&M(e)}(e.B,e.jc),e.U=B(e.U),e.g=i(e.g,ze);return 0}(e.Z);if(-1==t)throw Error("corrupted input");e.Pb=qe,e.Pc=e.Z.g,(t||r(e.Z.Nc,Ge)>=0&&r(e.Z.g,e.Z.Nc)>=0)&&(M(e.Z.B),L(e.Z.B),e.Z.e.Ab=null,e.zc=0)}(e),e.zc}function j(e){e.B={},e.e={},e.Gb=n(192),e.Zb=n(12),e.Cb=n(12),e.Db=n(12),e.Eb=n(12),e.pb=n(192),e.kb=n(4),e.kc=n(114),e.Fb=ve({},4),e.Rb=H({}),e.sb=H({}),e.gb={};for(var t=0;4>t;++t)e.kb[t]=ve({},6);return e}function V(e,t){for(;t>e.O;++e.O)e.ec[e.O]=ve({},3),e.hc[e.O]=ve({},3)}function q(e,t,n){return Ie(t,e.wc,0)?8+(Ie(t,e.wc,1)?8+we(e.tc,t):we(e.hc[n],t)):we(e.ec[n],t)}function H(e){return e.wc=n(2),e.ec=n(16),e.hc=n(16),e.tc=ve({},8),e.O=0,e}function G(e){_e(e.wc);for(var t=0;e.O>t;++t)_e(e.ec[t].G),_e(e.hc[t].G);_e(e.tc.G)}function z(e,t,i){var s,r;if(null==e.V||e.u!=i||e.I!=t)for(e.I=t,e.qc=(1<<t)-1,e.u=i,r=1<<e.u+e.I,e.V=n(r),s=0;r>s;++s)e.V[s]=W({})}function W(e){return e.Ib=n(768),e}function J(e,t){var n,i,s,r;e.jb=t,s=e.a[t].r,i=e.a[t].j;do{e.a[t].t&&(ye(e.a[s]),e.a[s].r=s-1,e.a[t].Ac&&(e.a[s-1].t=0,e.a[s-1].r=e.a[t].r2,e.a[s-1].j=e.a[t].j2)),r=s,n=i,i=e.a[r].j,s=e.a[r].r,e.a[r].j=n,e.a[r].r=t,t=r}while(t>0);return e.mb=e.a[0].j,e.q=e.a[0].r}function Y(e){var t;for(e.v=n(4),e.a=[],e.d={},e.C=n(192),e.bb=n(12),e.hb=n(12),e.Ub=n(12),e.vc=n(12),e._=n(192),e.K=[],e.Sb=n(114),e.S=ke({},4),e.$=ce({}),e.i=ce({}),e.A={},e.m=[],e.P=[],e.lb=[],e.nc=n(16),e.x=n(4),e.Q=n(4),e.Xb=[Ge],e.uc=[Ge],e.Kc=[0],e.fc=n(5),e.yc=n(128),e.vb=0,e.X=1,e.D=0,e.Hb=-1,e.mb=0,t=0;4096>t;++t)e.a[t]={};for(t=0;4>t;++t)e.K[t]=ke({},6);return e}function K(e){for(var t=0;16>t;++t)e.nc[t]=Te(e.S,t);e.Qb=0}function X(e){var t,n,i,s,r,o,a,l;for(s=4;128>s;++s)t=(2|1&(o=re(s)))<<(i=(o>>1)-1),e.yc[s]=Ce(e.Sb,t-o-1,i,s-t);for(r=0;4>r;++r){for(n=e.K[r],a=r<<6,o=0;e.$b>o;++o)e.P[a+o]=Ae(n,o);for(o=14;e.$b>o;++o)e.P[a+o]+=(o>>1)-1-4<<6;for(l=128*r,s=0;4>s;++s)e.lb[l+s]=e.P[a+s];for(;128>s;++s)e.lb[l+s]=e.P[a+re(s)]+e.yc[s]}e.Mb=0}function Q(e,t){se(e),function(e,t){if(e.Gc){Pe(e.d,e.C,(e.l<<4)+t,1),Pe(e.d,e.bb,e.l,0),e.l=7>e.l?7:10,le(e.$,e.d,0,t);var n=F(2);xe(e.K[n],e.d,63),Ue(e.d,67108863,26),Ee(e.S,e.d,15)}}(e,t&e.y);for(var n=0;5>n;++n)Ne(e.d)}function Z(e,t){var n,i,s,r,o,a,l,c,u,d,h,p,f,m,g,b,y,v,w,k,x,A,E,T,_,P,U,O,N,R,M,D,L,F,$,j,V,q,H,G,z,W,Y,K;if(e.jb!=e.q)return f=e.a[e.q].r-e.q,e.mb=e.a[e.q].j,e.q=e.a[e.q].r,f;if(e.q=e.jb=0,e.N?(p=e.vb,e.N=0):p=ie(e),P=e.D,2>(T=I(e.b)+1))return e.mb=-1,1;for(T>273&&(T=273),H=0,u=0;4>u;++u)e.x[u]=e.v[u],e.Q[u]=C(e.b,-1,e.x[u],273),e.Q[u]>e.Q[H]&&(H=u);if(e.Q[H]>=e.n)return e.mb=H,ne(e,(f=e.Q[H])-1),f;if(p>=e.n)return e.mb=e.m[P-1]+4,ne(e,p-1),p;if(l=S(e.b,-1),y=S(e.b,-e.v[0]-1-1),2>p&&l!=y&&2>e.Q[H])return e.mb=-1,1;if(e.a[0].Hc=e.l,L=t&e.y,e.a[1].z=Ye[e.C[(e.l<<4)+L]>>>2]+be(pe(e.A,t,e.J),e.l>=7,y,l),ye(e.a[1]),q=(v=Ye[2048-e.C[(e.l<<4)+L]>>>2])+Ye[2048-e.bb[e.l]>>>2],y==l&&(G=q+function(e,t,n){return Ye[e.hb[t]>>>2]+Ye[e._[(t<<4)+n]>>>2]}(e,e.l,L),e.a[1].z>G&&(e.a[1].z=G,function(e){e.j=0,e.t=0}(e.a[1]))),2>(h=p>=e.Q[H]?p:e.Q[H]))return e.mb=e.a[1].j,1;e.a[1].r=0,e.a[0].bc=e.x[0],e.a[0].ac=e.x[1],e.a[0].dc=e.x[2],e.a[0].lc=e.x[3],d=h;do{e.a[d--].z=268435455}while(d>=2);for(u=0;4>u;++u)if(!(2>(V=e.Q[u]))){$=q+te(e,u,e.l,L);do{r=$+ue(e.i,V-2,L),(R=e.a[V]).z>r&&(R.z=r,R.r=0,R.j=u,R.t=0)}while(--V>=2)}if(E=v+Ye[e.bb[e.l]>>>2],p>=(d=e.Q[0]>=2?e.Q[0]+1:2)){for(U=0;d>e.m[U];)U+=2;for(;r=E+ee(e,c=e.m[U+1],d,L),(R=e.a[d]).z>r&&(R.z=r,R.r=0,R.j=c+4,R.t=0),d!=e.m[U]||(U+=2)!=P;++d);}for(n=0;;){if(++n==h)return J(e,n);if(w=ie(e),P=e.D,w>=e.n)return e.vb=w,e.N=1,J(e,n);if(++t,D=e.a[n].r,e.a[n].t?(--D,e.a[n].Ac?(W=e.a[e.a[n].r2].Hc,W=4>e.a[n].j2?7>W?8:11:7>W?7:10):W=e.a[D].Hc,W=B(W)):W=e.a[D].Hc,D==n-1?W=e.a[n].j?B(W):7>W?9:11:(e.a[n].t&&e.a[n].Ac?(D=e.a[n].r2,M=e.a[n].j2,W=7>W?8:11):W=4>(M=e.a[n].j)?7>W?8:11:7>W?7:10,N=e.a[D],4>M?M?1==M?(e.x[0]=N.ac,e.x[1]=N.bc,e.x[2]=N.dc,e.x[3]=N.lc):2==M?(e.x[0]=N.dc,e.x[1]=N.bc,e.x[2]=N.ac,e.x[3]=N.lc):(e.x[0]=N.lc,e.x[1]=N.bc,e.x[2]=N.ac,e.x[3]=N.dc):(e.x[0]=N.bc,e.x[1]=N.ac,e.x[2]=N.dc,e.x[3]=N.lc):(e.x[0]=M-4,e.x[1]=N.bc,e.x[2]=N.ac,e.x[3]=N.dc)),e.a[n].Hc=W,e.a[n].bc=e.x[0],e.a[n].ac=e.x[1],e.a[n].dc=e.x[2],e.a[n].lc=e.x[3],a=e.a[n].z,l=S(e.b,-1),y=S(e.b,-e.x[0]-1-1),L=t&e.y,i=a+Ye[e.C[(W<<4)+L]>>>2]+be(pe(e.A,t,S(e.b,-2)),W>=7,y,l),k=0,(x=e.a[n+1]).z>i&&(x.z=i,x.r=n,x.j=-1,x.t=0,k=1),q=(v=a+Ye[2048-e.C[(W<<4)+L]>>>2])+Ye[2048-e.bb[W]>>>2],y!=l||n>x.r&&!x.j||(G=q+(Ye[e.hb[W]>>>2]+Ye[e._[(W<<4)+L]>>>2]),x.z>=G&&(x.z=G,x.r=n,x.j=0,x.t=0,k=1)),!(2>(T=_=(_=I(e.b)+1)>4095-n?4095-n:_))){if(T>e.n&&(T=e.n),!k&&y!=l&&(K=Math.min(_-1,e.n),(g=C(e.b,0,e.x[0],K))>=2)){for(Y=B(W),F=t+1&e.y,A=i+Ye[2048-e.C[(Y<<4)+F]>>>2]+Ye[2048-e.bb[Y]>>>2],O=n+1+g;O>h;)e.a[++h].z=268435455;r=A+(ue(e.i,g-2,F)+te(e,0,Y,F)),(R=e.a[O]).z>r&&(R.z=r,R.r=n+1,R.j=0,R.t=1,R.Ac=0)}for(z=2,j=0;4>j;++j)if(!(2>(m=C(e.b,-1,e.x[j],T)))){b=m;do{for(;n+m>h;)e.a[++h].z=268435455;r=q+(ue(e.i,m-2,L)+te(e,j,W,L)),(R=e.a[n+m]).z>r&&(R.z=r,R.r=n,R.j=j,R.t=0)}while(--m>=2);if(m=b,j||(z=m+1),_>m&&(K=Math.min(_-1-m,e.n),(g=C(e.b,m,e.x[j],K))>=2)){for(Y=7>W?8:11,F=t+m&e.y,s=q+(ue(e.i,m-2,L)+te(e,j,W,L))+Ye[e.C[(Y<<4)+F]>>>2]+be(pe(e.A,t+m,S(e.b,m-1-1)),1,S(e.b,m-1-(e.x[j]+1)),S(e.b,m-1)),Y=B(Y),F=t+m+1&e.y,A=s+Ye[2048-e.C[(Y<<4)+F]>>>2]+Ye[2048-e.bb[Y]>>>2],O=m+1+g;n+O>h;)e.a[++h].z=268435455;r=A+(ue(e.i,g-2,F)+te(e,0,Y,F)),(R=e.a[n+O]).z>r&&(R.z=r,R.r=n+m+1,R.j=0,R.t=1,R.Ac=1,R.r2=n,R.j2=j)}}if(w>T){for(w=T,P=0;w>e.m[P];P+=2);e.m[P]=w,P+=2}if(w>=z){for(E=v+Ye[e.bb[W]>>>2];n+w>h;)e.a[++h].z=268435455;for(U=0;z>e.m[U];)U+=2;for(m=z;;++m)if(r=E+ee(e,o=e.m[U+1],m,L),(R=e.a[n+m]).z>r&&(R.z=r,R.r=n,R.j=o+4,R.t=0),m==e.m[U]){if(_>m&&(K=Math.min(_-1-m,e.n),(g=C(e.b,m,o,K))>=2)){for(Y=7>W?7:10,F=t+m&e.y,s=r+Ye[e.C[(Y<<4)+F]>>>2]+be(pe(e.A,t+m,S(e.b,m-1-1)),1,S(e.b,m-(o+1)-1),S(e.b,m-1)),Y=B(Y),F=t+m+1&e.y,A=s+Ye[2048-e.C[(Y<<4)+F]>>>2]+Ye[2048-e.bb[Y]>>>2],O=m+1+g;n+O>h;)e.a[++h].z=268435455;r=A+(ue(e.i,g-2,F)+te(e,0,Y,F)),(R=e.a[n+O]).z>r&&(R.z=r,R.r=n+m+1,R.j=0,R.t=1,R.Ac=1,R.r2=n,R.j2=o+4)}if((U+=2)==P)break}}}}}function ee(e,t,n,i){var s=F(n);return(128>t?e.lb[128*s+t]:e.P[(s<<6)+function(e){return 131072>e?Je[e>>6]+12:134217728>e?Je[e>>16]+32:Je[e>>26]+52}(t)]+e.nc[15&t])+ue(e.$,n-2,i)}function te(e,t,n,i){var s;return t?(s=Ye[2048-e.hb[n]>>>2],1==t?s+=Ye[e.Ub[n]>>>2]:(s+=Ye[2048-e.Ub[n]>>>2],s+=Re(e.vc[n],t-2))):(s=Ye[e.hb[n]>>>2],s+=Ye[2048-e._[(n<<4)+i]>>>2]),s}function ne(e,t){t>0&&(function(e,t){var n,i,s,r,o,a,l,c,u,d,h,p,f,m,g,b,y;do{if(e.h>=e.o+e.ob)p=e.ob;else if(p=e.h-e.o,e.xb>p){O(e);continue}for(f=e.o>e.p?e.o-e.p:0,i=e.f+e.o,e.qb?(a=1023&(y=We[255&e.c[i]]^255&e.c[i+1]),e.ub[a]=e.o,l=65535&(y^=(255&e.c[i+2])<<8),e.ub[1024+l]=e.o,c=(y^We[255&e.c[i+3]]<<5)&e.Ec):c=255&e.c[i]^(255&e.c[i+1])<<8,s=e.ub[e.R+c],e.ub[e.R+c]=e.o,g=1+(e.k<<1),b=e.k<<1,d=h=e.w,n=e.Fc;;){if(f>=s||0==n--){e.L[g]=e.L[b]=0;break}if(o=e.o-s,r=(e.k>=o?e.k-o:e.k-o+e.p)<<1,m=e.f+s,u=h>d?d:h,e.c[m+u]==e.c[i+u]){for(;++u!=p&&e.c[m+u]==e.c[i+u];);if(u==p){e.L[b]=e.L[r],e.L[g]=e.L[r+1];break}}(255&e.c[i+u])>(255&e.c[m+u])?(e.L[b]=s,b=r+1,s=e.L[b],h=u):(e.L[g]=s,g=r,s=e.L[g],d=u)}O(e)}while(0!=--t)}(e.b,t),e.s+=t)}function ie(e){var t=0;return e.D=function(e,t){var n,i,s,r,o,a,l,c,u,d,h,p,f,m,g,b,y,v,w,k,x;if(e.h>=e.o+e.ob)m=e.ob;else if(m=e.h-e.o,e.xb>m)return O(e),0;for(y=0,g=e.o>e.p?e.o-e.p:0,i=e.f+e.o,b=1,c=0,u=0,e.qb?(c=1023&(x=We[255&e.c[i]]^255&e.c[i+1]),u=65535&(x^=(255&e.c[i+2])<<8),d=(x^We[255&e.c[i+3]]<<5)&e.Ec):d=255&e.c[i]^(255&e.c[i+1])<<8,s=e.ub[e.R+d]||0,e.qb&&(r=e.ub[c]||0,o=e.ub[1024+u]||0,e.ub[c]=e.o,e.ub[1024+u]=e.o,r>g&&e.c[e.f+r]==e.c[i]&&(t[y++]=b=2,t[y++]=e.o-r-1),o>g&&e.c[e.f+o]==e.c[i]&&(o==r&&(y-=2),t[y++]=b=3,t[y++]=e.o-o-1,r=o),0!=y&&r==s&&(y-=2,b=1)),e.ub[e.R+d]=e.o,w=1+(e.k<<1),k=e.k<<1,p=f=e.w,0!=e.w&&s>g&&e.c[e.f+s+e.w]!=e.c[i+e.w]&&(t[y++]=b=e.w,t[y++]=e.o-s-1),n=e.Fc;;){if(g>=s||0==n--){e.L[w]=e.L[k]=0;break}if(l=e.o-s,a=(e.k>=l?e.k-l:e.k-l+e.p)<<1,v=e.f+s,h=f>p?p:f,e.c[v+h]==e.c[i+h]){for(;++h!=m&&e.c[v+h]==e.c[i+h];);if(h>b&&(t[y++]=b=h,t[y++]=l-1,h==m)){e.L[k]=e.L[a],e.L[w]=e.L[a+1];break}}(255&e.c[i+h])>(255&e.c[v+h])?(e.L[k]=s,k=a+1,s=e.L[k],f=h):(e.L[w]=s,w=a,s=e.L[w],p=h)}return O(e),y}(e.b,e.m),e.D>0&&((t=e.m[e.D-2])==e.n&&(t+=C(e.b,t-1,e.m[e.D-1],273-t))),++e.s,t}function se(e){e.b&&e.W&&(e.b.cc=null,e.W=0)}function re(e){return 2048>e?Je[e]:2097152>e?Je[e>>10]+20:Je[e>>20]+40}function oe(e,t){_e(e.db);for(var n=0;t>n;++n)_e(e.Vb[n].G),_e(e.Wb[n].G);_e(e.ic.G)}function ae(e,t,n,i,s){var r,o,a,l,c;for(r=Ye[e.db[0]>>>2],a=(o=Ye[2048-e.db[0]>>>2])+Ye[e.db[1]>>>2],l=o+Ye[2048-e.db[1]>>>2],c=0,c=0;8>c;++c){if(c>=n)return;i[s+c]=r+Ae(e.Vb[t],c)}for(;16>c;++c){if(c>=n)return;i[s+c]=a+Ae(e.Wb[t],c-8)}for(;n>c;++c)i[s+c]=l+Ae(e.ic,c-8-8)}function le(e,t,n,i){(function(e,t,n,i){8>n?(Pe(t,e.db,0,0),xe(e.Vb[i],t,n)):(n-=8,Pe(t,e.db,0,1),8>n?(Pe(t,e.db,1,0),xe(e.Wb[i],t,n)):(Pe(t,e.db,1,1),xe(e.ic,t,n-8)))})(e,t,n,i),0==--e.sc[i]&&(ae(e,i,e.rb,e.Cc,272*i),e.sc[i]=e.rb)}function ce(e){return function(e){e.db=n(2),e.Vb=n(16),e.Wb=n(16),e.ic=ke({},8);for(var t=0;16>t;++t)e.Vb[t]=ke({},3),e.Wb[t]=ke({},3)}(e),e.Cc=[],e.sc=[],e}function ue(e,t,n){return e.Cc[272*n+t]}function de(e,t){for(var n=0;t>n;++n)ae(e,n,e.rb,e.Cc,272*n),e.sc[n]=e.rb}function he(e,t,i){var s,r;if(null==e.V||e.u!=i||e.I!=t)for(e.I=t,e.qc=(1<<t)-1,e.u=i,r=1<<e.u+e.I,e.V=n(r),s=0;r>s;++s)e.V[s]=ge({})}function pe(e,t,n){return e.V[((t&e.qc)<<e.u)+((255&n)>>>8-e.u)]}function fe(e,t,n){var i,s,r=1;for(s=7;s>=0;--s)i=n>>s&1,Pe(t,e.tb,r,i),r=r<<1|i}function me(e,t,n,i){var s,r,o,a,l=1,c=1;for(r=7;r>=0;--r)s=i>>r&1,a=c,l&&(a+=1+(o=n>>r&1)<<8,l=o==s),Pe(t,e.tb,a,s),c=c<<1|s}function ge(e){return e.tb=n(768),e}function be(e,t,n,i){var s,r,o=1,a=7,l=0;if(t)for(;a>=0;--a)if(r=n>>a&1,s=i>>a&1,l+=Re(e.tb[(1+r<<8)+o],s),o=o<<1|s,r!=s){--a;break}for(;a>=0;--a)s=i>>a&1,l+=Re(e.tb[o],s),o=o<<1|s;return l}function ye(e){e.j=-1,e.t=0}function ve(e,t){return e.F=t,e.G=n(1<<t),e}function we(e,t){var n,i=1;for(n=e.F;0!=n;--n)i=(i<<1)+Ie(t,e.G,i);return i-(1<<e.F)}function ke(e,t){return e.F=t,e.G=n(1<<t),e}function xe(e,t,n){var i,s,r=1;for(s=e.F;0!=s;)i=n>>>--s&1,Pe(t,e.G,r,i),r=r<<1|i}function Ae(e,t){var n,i,s=1,r=0;for(i=e.F;0!=i;)n=t>>>--i&1,r+=Re(e.G[s],n),s=(s<<1)+n;return r}function Ee(e,t,n){var i,s,r=1;for(s=0;e.F>s;++s)i=1&n,Pe(t,e.G,r,i),r=r<<1|i,n>>=1}function Te(e,t){var n,i,s=1,r=0;for(i=e.F;0!=i;--i)n=1&t,t>>>=1,r+=Re(e.G[s],n),s=s<<1|n;return r}function Se(e,t,n,i,s){var r,o,a=1;for(o=0;i>o;++o)Pe(n,e,t+a,r=1&s),a=a<<1|r,s>>=1}function Ce(e,t,n,i){var s,r,o=1,a=0;for(r=n;0!=r;--r)s=1&i,i>>>=1,a+=Ye[(2047&(e[t+o]-s^-s))>>>2],o=o<<1|s;return a}function Ie(e,t,n){var i,s=t[n];return(-2147483648^(i=(e.E>>>11)*s))>(-2147483648^e.Bb)?(e.E=i,t[n]=s+(2048-s>>>5)<<16>>16,-16777216&e.E||(e.Bb=e.Bb<<8|m(e.Ab),e.E<<=8),0):(e.E-=i,e.Bb-=i,t[n]=s-(s>>>5)<<16>>16,-16777216&e.E||(e.Bb=e.Bb<<8|m(e.Ab),e.E<<=8),1)}function _e(e){for(var t=e.length-1;t>=0;--t)e[t]=1024}function Pe(e,t,n,r){var o,a=t[n];o=(e.E>>>11)*a,r?(e.xc=i(e.xc,s(l(o),[4294967295,0])),e.E-=o,t[n]=a-(a>>>5)<<16>>16):(e.E=o,t[n]=a+(2048-a>>>5)<<16>>16),-16777216&e.E||(e.E<<=8,Ne(e))}function Ue(e,t,n){for(var s=n-1;s>=0;--s)e.E>>>=1,1==(t>>>s&1)&&(e.xc=i(e.xc,l(e.E))),-16777216&e.E||(e.E<<=8,Ne(e))}function Oe(e){return i(i(l(e.Jb),e.mc),[4,0])}function Ne(e){var t,n=c(function(e,t){var n;return n=h(e,t&=63),0>e[1]&&(n=i(n,d([2,0],63-t))),n}(e.xc,32));if(0!=n||r(e.xc,[4278190080,0])<0){e.mc=i(e.mc,l(e.Jb)),t=e.Oc;do{v(e.Ab,t+n),t=255}while(0!=--e.Jb);e.Oc=c(e.xc)>>>24}++e.Jb,e.xc=d(s(e.xc,[16777215,0]),8)}function Re(e,t){return Ye[(2047&(e-t^-t))>>>2]}function Me(e){for(var t,n,i,s=0,r=0,o=e.length,a=[],l=[];o>s;++s,++r){if(128&(t=255&e[s]))if(192==(224&t)){if(s+1>=o)return e;if(128!=(192&(n=255&e[++s])))return e;l[r]=(31&t)<<6|63&n}else{if(224!=(240&t))return e;if(s+2>=o)return e;if(128!=(192&(n=255&e[++s])))return e;if(128!=(192&(i=255&e[++s])))return e;l[r]=(15&t)<<12|(63&n)<<6|63&i}else{if(!t)return e;l[r]=t}16383==r&&(a.push(String.fromCharCode.apply(String,l)),r=-1)}return r>0&&(l.length=r,a.push(String.fromCharCode.apply(String,l))),a.join("")}function De(e){var t,n,i,s=[],r=0,o=e.length;if("object"==typeof e)return e;for(function(e,t,n,i,s){var r;for(r=t;n>r;++r)i[s++]=e.charCodeAt(r)}(e,0,o,s,0),i=0;o>i;++i)(t=s[i])>=1&&127>=t?++r:r+=!t||t>=128&&2047>=t?2:3;for(n=[],r=0,i=0;o>i;++i)(t=s[i])>=1&&127>=t?n[r++]=t<<24>>24:!t||t>=128&&2047>=t?(n[r++]=(192|t>>6&31)<<24>>24,n[r++]=(128|63&t)<<24>>24):(n[r++]=(224|t>>12&15)<<24>>24,n[r++]=(128|t>>6&63)<<24>>24,n[r++]=(128|63&t)<<24>>24);return n}function Le(e){return e[1]+e[0]}var Fe=1,Be=2,$e=3,je="function"==typeof setImmediate?setImmediate:setTimeout,Ve=4294967296,qe=[4294967295,-Ve],He=[0,-0x8000000000000000],Ge=[0,0],ze=[1,0],We=function(){var e,t,n,i=[];for(e=0;256>e;++e){for(n=e,t=0;8>t;++t)0!=(1&n)?n=n>>>1^-306674912:n>>>=1;i[e]=n}return i}(),Je=function(){var e,t,n,i=2,s=[0,1];for(n=2;22>n;++n)for(t=1<<(n>>1)-1,e=0;t>e;++e,++i)s[i]=n<<24>>24;return s}(),Ye=function(){var e,t,n,i=[];for(t=8;t>=0;--t)for(e=1<<9-t,n=1<<9-t-1;e>n;++n)i[n]=(t<<6)+(e-n<<6>>>9-t-1);return i}(),Ke=function(){var e=[{s:16,f:64,m:0},{s:20,f:64,m:0},{s:19,f:64,m:1},{s:20,f:64,m:1},{s:21,f:128,m:1},{s:22,f:128,m:1},{s:23,f:128,m:1},{s:24,f:255,m:1},{s:25,f:255,m:1}];return function(t){return e[t-1]||e[6]}}();return"undefined"==typeof onmessage||"undefined"!=typeof window&&void 0!==window.document||(onmessage=function(t){t&&t.gc&&(t.gc.action==Be?e.decompress(t.gc.gc,t.gc.cbn):t.gc.action==Fe&&e.compress(t.gc.gc,t.gc.Rc,t.gc.cbn))}),{compress:function(e,n,i,s){var r,o,a={},l=void 0===i&&void 0===s;if("function"!=typeof i&&(o=i,i=s=0),s=s||function(e){return void 0!==o?t(e,o):void 0},i=i||function(e,t){return void 0!==o?postMessage({action:Fe,cbn:o,result:e,error:t}):void 0},l){for(a.c=A({},De(e),Ke(n));$(a.c.yb););return y(a.c.Nb)}try{a.c=A({},De(e),Ke(n)),s(0)}catch(e){return i(null,e)}je((function e(){try{for(var t,n=(new Date).getTime();$(a.c.yb);)if(r=Le(a.c.yb.Pb)/Le(a.c.Tb),(new Date).getTime()-n>200)return s(r),je(e,0),0;s(1),t=y(a.c.Nb),je(i.bind(null,t),0)}catch(e){i(null,e)}}),0)},decompress:function(e,n,i){var s,r,o,a,l={},c=void 0===n&&void 0===i;if("function"!=typeof n&&(r=n,n=i=0),i=i||function(e){return void 0!==r?t(o?e:-1,r):void 0},n=n||function(e,t){return void 0!==r?postMessage({action:Be,cbn:r,result:e,error:t}):void 0},c){for(l.d=T({},e);$(l.d.yb););return Me(y(l.d.Nb))}try{l.d=T({},e),a=Le(l.d.Tb),o=a>-1,i(0)}catch(e){return n(null,e)}je((function e(){try{for(var t,r=0,c=(new Date).getTime();$(l.d.yb);)if(++r%1e3==0&&(new Date).getTime()-c>200)return o&&(s=Le(l.d.yb.Z.g)/a,i(s)),je(e,0),0;i(1),t=Me(y(l.d.Nb)),je(n.bind(null,t),0)}catch(e){n(null,e)}}),0)}}}(),pxt,pxt,pxt,pxt,pxt,ts;this.LZMA=this.LZMA_WORKER=e,function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).DOMPurify=t()}(this,(function(){"use strict";var e=Object.hasOwnProperty,t=Object.setPrototypeOf,n=Object.isFrozen,i=Object.keys,s=Object.freeze,r=Object.seal,o=Object.create,a="undefined"!=typeof Reflect&&Reflect,l=a.apply,c=a.construct;l||(l=function(e,t,n){return e.apply(t,n)}),s||(s=function(e){return e}),r||(r=function(e){return e}),c||(c=function(e,t){return new(Function.prototype.bind.apply(e,[null].concat(function(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}(t))))});var u=E(Array.prototype.forEach),d=E(Array.prototype.indexOf),h=E(Array.prototype.join),p=E(Array.prototype.pop),f=E(Array.prototype.push),m=E(Array.prototype.slice),g=E(String.prototype.toLowerCase),b=E(String.prototype.match),y=E(String.prototype.replace),v=E(String.prototype.indexOf),w=E(String.prototype.trim),k=E(RegExp.prototype.test),x=T(RegExp),A=T(TypeError);function E(e){return function(t){for(var n=arguments.length,i=Array(n>1?n-1:0),s=1;s<n;s++)i[s-1]=arguments[s];return l(e,t,i)}}function T(e){return function(){for(var t=arguments.length,n=Array(t),i=0;i<t;i++)n[i]=arguments[i];return c(e,n)}}function S(e,i){t&&t(e,null);for(var s=i.length;s--;){var r=i[s];if("string"==typeof r){var o=g(r);o!==r&&(n(i)||(i[s]=o),r=o)}e[r]=!0}return e}function C(t){var n=o(null),i=void 0;for(i in t)l(e,t,[i])&&(n[i]=t[i]);return n}var I=s(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),_=s(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","audio","canvas","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","video","view","vkern"]),P=s(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),U=s(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover"]),O=s(["#text"]),N=s(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","face","for","headers","height","hidden","high","href","hreflang","id","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","playsinline","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","xmlns"]),R=s(["accent-height","accumulate","additive","alignment-baseline","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","targetx","targety","transform","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),M=s(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),D=s(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),L=r(/\{\{[\s\S]*|[\s\S]*\}\}/gm),F=r(/<%[\s\S]*|[\s\S]*%>/gm),B=r(/^data-[\-\w.\u00B7-\uFFFF]/),$=r(/^aria-[\-\w]+$/),j=r(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),V=r(/^(?:\w+script|data):/i),q=r(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),H="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};function G(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}var z=function(){return"undefined"==typeof window?null:window},W=function(e,t){if("object"!==(void 0===e?"undefined":H(e))||"function"!=typeof e.createPolicy)return null;var n=null;t.currentScript&&t.currentScript.hasAttribute("data-tt-policy-suffix")&&(n=t.currentScript.getAttribute("data-tt-policy-suffix"));var i="dompurify"+(n?"#"+n:"");try{return e.createPolicy(i,{createHTML:function(e){return e}})}catch(e){return console.warn("TrustedTypes policy "+i+" could not be created."),null}};return function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:z(),n=function(t){return e(t)};if(n.version="2.0.17",n.removed=[],!t||!t.document||9!==t.document.nodeType)return n.isSupported=!1,n;var r=t.document,o=!1,a=t.document,l=t.DocumentFragment,c=t.HTMLTemplateElement,E=t.Node,T=t.NodeFilter,J=t.NamedNodeMap,Y=void 0===J?t.NamedNodeMap||t.MozNamedAttrMap:J,K=t.Text,X=t.Comment,Q=t.DOMParser,Z=t.trustedTypes;if("function"==typeof c){var ee=a.createElement("template");ee.content&&ee.content.ownerDocument&&(a=ee.content.ownerDocument)}var te=W(Z,r),ne=te&&Me?te.createHTML(""):"",ie=a,se=ie.implementation,re=ie.createNodeIterator,oe=ie.getElementsByTagName,ae=ie.createDocumentFragment,le=r.importNode,ce={};try{ce=C(a).documentMode?a.documentMode:{}}catch(e){}var ue={};n.isSupported=se&&void 0!==se.createHTMLDocument&&9!==ce;var de=L,he=F,pe=B,fe=$,me=V,ge=q,be=j,ye=null,ve=S({},[].concat(G(I),G(_),G(P),G(U),G(O))),we=null,ke=S({},[].concat(G(N),G(R),G(M),G(D))),xe=null,Ae=null,Ee=!0,Te=!0,Se=!1,Ce=!1,Ie=!1,_e=!1,Pe=!1,Ue=!1,Oe=!1,Ne=!1,Re=!1,Me=!1,De=!0,Le=!0,Fe=!1,Be={},$e=S({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","plaintext","script","style","svg","template","thead","title","video","xmp"]),je=null,Ve=S({},["audio","video","img","source","image","track"]),qe=null,He=S({},["alt","class","for","id","label","name","pattern","placeholder","summary","title","value","style","xmlns"]),Ge=null,ze=a.createElement("form"),We=function(e){Ge&&Ge===e||(e&&"object"===(void 0===e?"undefined":H(e))||(e={}),e=C(e),ye="ALLOWED_TAGS"in e?S({},e.ALLOWED_TAGS):ve,we="ALLOWED_ATTR"in e?S({},e.ALLOWED_ATTR):ke,qe="ADD_URI_SAFE_ATTR"in e?S(C(He),e.ADD_URI_SAFE_ATTR):He,je="ADD_DATA_URI_TAGS"in e?S(C(Ve),e.ADD_DATA_URI_TAGS):Ve,xe="FORBID_TAGS"in e?S({},e.FORBID_TAGS):{},Ae="FORBID_ATTR"in e?S({},e.FORBID_ATTR):{},Be="USE_PROFILES"in e&&e.USE_PROFILES,Ee=!1!==e.ALLOW_ARIA_ATTR,Te=!1!==e.ALLOW_DATA_ATTR,Se=e.ALLOW_UNKNOWN_PROTOCOLS||!1,Ce=e.SAFE_FOR_JQUERY||!1,Ie=e.SAFE_FOR_TEMPLATES||!1,_e=e.WHOLE_DOCUMENT||!1,Oe=e.RETURN_DOM||!1,Ne=e.RETURN_DOM_FRAGMENT||!1,Re=e.RETURN_DOM_IMPORT||!1,Me=e.RETURN_TRUSTED_TYPE||!1,Ue=e.FORCE_BODY||!1,De=!1!==e.SANITIZE_DOM,Le=!1!==e.KEEP_CONTENT,Fe=e.IN_PLACE||!1,be=e.ALLOWED_URI_REGEXP||be,Ie&&(Te=!1),Ne&&(Oe=!0),Be&&(ye=S({},[].concat(G(O))),we=[],!0===Be.html&&(S(ye,I),S(we,N)),!0===Be.svg&&(S(ye,_),S(we,R),S(we,D)),!0===Be.svgFilters&&(S(ye,P),S(we,R),S(we,D)),!0===Be.mathMl&&(S(ye,U),S(we,M),S(we,D))),e.ADD_TAGS&&(ye===ve&&(ye=C(ye)),S(ye,e.ADD_TAGS)),e.ADD_ATTR&&(we===ke&&(we=C(we)),S(we,e.ADD_ATTR)),e.ADD_URI_SAFE_ATTR&&S(qe,e.ADD_URI_SAFE_ATTR),Le&&(ye["#text"]=!0),_e&&S(ye,["html","head","body"]),ye.table&&(S(ye,["tbody"]),delete xe.tbody),s&&s(e),Ge=e)},Je=function(e){f(n.removed,{element:e});try{e.parentNode.removeChild(e)}catch(t){e.outerHTML=ne}},Ye=function(e,t){try{f(n.removed,{attribute:t.getAttributeNode(e),from:t})}catch(e){f(n.removed,{attribute:null,from:t})}t.removeAttribute(e)},Ke=function(e){var t=void 0,n=void 0;if(Ue)e="<remove></remove>"+e;else{var i=b(e,/^[\r\n\t ]+/);n=i&&i[0]}var s=te?te.createHTML(e):e;try{t=(new Q).parseFromString(s,"text/html")}catch(e){}if(o&&S(xe,["title"]),!t||!t.documentElement){var r=(t=se.createHTMLDocument("")).body;r.parentNode.removeChild(r.parentNode.firstElementChild),r.outerHTML=s}return e&&n&&t.body.insertBefore(a.createTextNode(n),t.body.childNodes[0]||null),oe.call(t,_e?"html":"body")[0]};n.isSupported&&function(){try{var e=Ke("<x/><title>&lt;/title&gt;&lt;img&gt;");k(/<\/title/,e.querySelector("title").innerHTML)&&(o=!0)}catch(e){}}();var Xe=function(e){return re.call(e.ownerDocument||e,e,T.SHOW_ELEMENT|T.SHOW_COMMENT|T.SHOW_TEXT,(function(){return T.FILTER_ACCEPT}),!1)},Qe=function(e){return!(e instanceof K||e instanceof X||"string"==typeof e.nodeName&&"string"==typeof e.textContent&&"function"==typeof e.removeChild&&e.attributes instanceof Y&&"function"==typeof e.removeAttribute&&"function"==typeof e.setAttribute&&"string"==typeof e.namespaceURI)},Ze=function(e){return"object"===(void 0===E?"undefined":H(E))?e instanceof E:e&&"object"===(void 0===e?"undefined":H(e))&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName},et=function(e,t,i){ue[e]&&u(ue[e],(function(e){e.call(n,t,i,Ge)}))},tt=function(e){var t=void 0;if(et("beforeSanitizeElements",e,null),Qe(e))return Je(e),!0;if(b(e.nodeName,/[\u0080-\uFFFF]/))return Je(e),!0;var i=g(e.nodeName);if(et("uponSanitizeElement",e,{tagName:i,allowedTags:ye}),("svg"===i||"math"===i)&&0!==e.querySelectorAll("p, br, form, table").length)return Je(e),!0;if(!ye[i]||xe[i]){if(Le&&!$e[i]&&"function"==typeof e.insertAdjacentHTML)try{var s=e.innerHTML;e.insertAdjacentHTML("AfterEnd",te?te.createHTML(s):s)}catch(e){}return Je(e),!0}return"noscript"===i&&k(/<\/noscript/i,e.innerHTML)||"noembed"===i&&k(/<\/noembed/i,e.innerHTML)?(Je(e),!0):(!Ce||Ze(e.firstElementChild)||Ze(e.content)&&Ze(e.content.firstElementChild)||!k(/</g,e.textContent)||(f(n.removed,{element:e.cloneNode()}),e.innerHTML?e.innerHTML=y(e.innerHTML,/</g,"&lt;"):e.innerHTML=y(e.textContent,/</g,"&lt;")),Ie&&3===e.nodeType&&(t=e.textContent,t=y(t,de," "),t=y(t,he," "),e.textContent!==t&&(f(n.removed,{element:e.cloneNode()}),e.textContent=t)),et("afterSanitizeElements",e,null),!1)},nt=function(e,t,n){if(De&&("id"===t||"name"===t)&&(n in a||n in ze))return!1;if(Te&&k(pe,t));else if(Ee&&k(fe,t));else{if(!we[t]||Ae[t])return!1;if(qe[t]);else if(k(be,y(n,ge,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==v(n,"data:")||!je[e])if(Se&&!k(me,y(n,ge,"")));else if(n)return!1}return!0},it=function(e){var t=void 0,s=void 0,r=void 0,o=void 0,a=void 0;et("beforeSanitizeAttributes",e,null);var l=e.attributes;if(l){var c={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:we};for(a=l.length;a--;){var u=t=l[a],f=u.name,b=u.namespaceURI;if(s=w(t.value),r=g(f),c.attrName=r,c.attrValue=s,c.keepAttr=!0,c.forceKeepAttr=void 0,et("uponSanitizeAttribute",e,c),s=c.attrValue,!c.forceKeepAttr){if("name"===r&&"IMG"===e.nodeName&&l.id)o=l.id,l=m(l,[]),Ye("id",e),Ye(f,e),d(l,o)>a&&e.setAttribute("id",o.value);else{if("INPUT"===e.nodeName&&"type"===r&&"file"===s&&c.keepAttr&&(we[r]||!Ae[r]))continue;"id"===f&&e.setAttribute(f,""),Ye(f,e)}if(c.keepAttr)if(Ce&&k(/\/>/i,s))Ye(f,e);else if(k(/svg|math/i,e.namespaceURI)&&k(x("</("+h(i($e),"|")+")","i"),s))Ye(f,e);else{Ie&&(s=y(s,de," "),s=y(s,he," "));var v=e.nodeName.toLowerCase();if(nt(v,r,s))try{b?e.setAttributeNS(b,f,s):e.setAttribute(f,s),p(n.removed)}catch(e){}}}}et("afterSanitizeAttributes",e,null)}},st=function e(t){var n=void 0,i=Xe(t);for(et("beforeSanitizeShadowDOM",t,null);n=i.nextNode();)et("uponSanitizeShadowNode",n,null),tt(n)||(n.content instanceof l&&e(n.content),it(n));et("afterSanitizeShadowDOM",t,null)};return n.sanitize=function(e,i){var s=void 0,o=void 0,a=void 0,c=void 0,u=void 0;if(e||(e="\x3c!--\x3e"),"string"!=typeof e&&!Ze(e)){if("function"!=typeof e.toString)throw A("toString is not a function");if("string"!=typeof(e=e.toString()))throw A("dirty is not a string, aborting")}if(!n.isSupported){if("object"===H(t.toStaticHTML)||"function"==typeof t.toStaticHTML){if("string"==typeof e)return t.toStaticHTML(e);if(Ze(e))return t.toStaticHTML(e.outerHTML)}return e}if(Pe||We(i),n.removed=[],"string"==typeof e&&(Fe=!1),Fe);else if(e instanceof E)1===(o=(s=Ke("\x3c!--\x3e")).ownerDocument.importNode(e,!0)).nodeType&&"BODY"===o.nodeName||"HTML"===o.nodeName?s=o:s.appendChild(o);else{if(!Oe&&!Ie&&!_e&&-1===e.indexOf("<"))return te&&Me?te.createHTML(e):e;if(!(s=Ke(e)))return Oe?null:ne}s&&Ue&&Je(s.firstChild);for(var d=Xe(Fe?e:s);a=d.nextNode();)3===a.nodeType&&a===c||tt(a)||(a.content instanceof l&&st(a.content),it(a),c=a);if(c=null,Fe)return e;if(Oe){if(Ne)for(u=ae.call(s.ownerDocument);s.firstChild;)u.appendChild(s.firstChild);else u=s;return Re&&(u=le.call(r,u,!0)),u}var h=_e?s.outerHTML:s.innerHTML;return Ie&&(h=y(h,de," "),h=y(h,he," ")),te&&Me?te.createHTML(h):h},n.setConfig=function(e){We(e),Pe=!0},n.clearConfig=function(){Ge=null,Pe=!1},n.isValidAttribute=function(e,t,n){Ge||We({});var i=g(e),s=g(t);return nt(i,s,n)},n.addHook=function(e,t){"function"==typeof t&&(ue[e]=ue[e]||[],f(ue[e],t))},n.removeHook=function(e){ue[e]&&p(ue[e])},n.removeHooks=function(e){ue[e]&&(ue[e]=[])},n.removeAllHooks=function(){ue={}},n}()})),pxt||(pxt={}),function(e){!function(t){const n={},i={};let s,r=!1;function o(e){Object.keys(e).forEach((t=>{"string"==typeof e[t]?n[t]=e[t]:i[t]=e[t]}))}!function(e){e[e.Off=0]="Off",e[e.Short=1]="Short",e[e.Verbose=2]="Verbose"}(s=t.ConsoleTickOptions||(t.ConsoleTickOptions={})),t.consoleTicks=s.Off,t.addDefaultProperties=o,t.enable=function(a){if(!e.aiTrackException||!e.aiTrackEvent||r)return;r=!0,"string"==typeof a&&0!=a.length||(a="en"),o({lang:a}),e.debug("setting up app insights");const l=e.tickEvent;e.tickEvent=function(r,o,a){if(t.consoleTicks!=s.Off){const e=t.consoleTicks==s.Short?"":`${(new Date).toLocaleTimeString(void 0,{hour12:!1})} - Tick - `,n=`${r} ${o?JSON.stringify(o):"<no data>"} ${a?JSON.stringify(a):"<no opts>"}`;console.log(e+n)}if(l&&l(r,o,a),(null==a?void 0:a.interactiveConsent)&&e.setInteractiveConsent(!0),o){const t=Object.assign({},n)||{},s=Object.assign({},i)||{};Object.keys(o).forEach((e=>{"string"==typeof o[e]?t[e]=o[e]:"number"==typeof o[e]?s[e]=o[e]:t[e]=JSON.stringify(o[e]||"")})),e.aiTrackEvent(r,t,s)}else e.aiTrackEvent(r)};const c=e.reportException;e.reportException=function(t,n){c&&c(t,n);const i={target:e.appTarget.id,version:e.appTarget.versions.target};n&&e.Util.jsonMergeFrom(i,n),e.aiTrackException(t,"exception",i)};const u=e.reportError;e.reportError=function(t,n,i){u&&u(t,n,i);try{throw n}catch(s){const r={target:e.appTarget.id,version:e.appTarget.versions.target,category:t,message:n};i&&e.Util.jsonMergeFrom(r,i),e.aiTrackException(s,"error",r)}}},t.trackPerformanceReport=function(){if(e.perf.perfReportLogged)return;const t=e.perf.report();if(t){const{durations:n,milestones:i}=t;e.tickEvent("performance.milestones",i),e.tickEvent("performance.durations",n)}}}(e.analytics||(e.analytics={}))}(pxt||(pxt={})),pxt||(pxt={}),function(e){!function(e){let t,n,i,s=0,r=!1;function o(){return t||(t=function(){if(window.AudioContext=window.AudioContext||window.webkitAudioContext,window.AudioContext)try{return new window.AudioContext}catch(e){}return}()),t}function a(){t&&(i.gain.setTargetAtTime(0,t.currentTime,.015),s=0)}e.mute=function(e){t&&(r=e,a(),e&&n&&(n.disconnect(),i.disconnect(),n=void 0,i=void 0))},e.stop=a,e.frequency=function(){return s},e.tone=function(e){if(r)return;if(isNaN(e)||e<0)return;s=e;let a=o();if(a)try{n||(n=a.createOscillator(),n.type="triangle",i=a.createGain(),i.gain.value=0,i.connect(a.destination),n.connect(i),n.start(0)),n.frequency.linearRampToValueAtTime(e,t.currentTime),i.gain.setTargetAtTime(.2,t.currentTime,.015)}catch(e){return void(n=void 0)}}}(e.AudioContextManager||(e.AudioContextManager={}))}(pxt||(pxt={})),function(e){!function(t){const n="auth",i="csrf-token",s="login-state",r="user-state",o="interactive-login-until";let a,l=!1;t.DEFAULT_USER_PREFERENCES=()=>({highContrast:!1,language:e.appTarget.appTheme.defaultLocale,reader:"",skillmap:{mapProgress:{},completedTags:{}},email:!1}),t.client=function(){if(!l)return a};let c=0,u=0;async function d(t,i){return i?await e.storage.shared.setAsync(n,t,i):await e.storage.shared.delAsync(n,t)}async function h(t){try{return await e.storage.shared.getAsync(n,t)}catch(e){return}}async function p(){const e=await h(i);return t.cachedHasAuthToken=!!e,e}async function f(e){return t.cachedHasAuthToken=!!e,await d(i,e)}async function m(){return!!await p()}async function g(){return t.cachedHasAuthToken=!1,await d(i,void 0)}async function b(){let i;try{i=await e.storage.shared.getAsync(n,r)}catch(e){i={}}return t.cachedUserState=i,i}async function y(i){return t.cachedUserState=Object.assign({},i),await e.storage.shared.setAsync(n,r,i)}async function v(){return t.cachedUserState=void 0,await e.storage.shared.delAsync(n,r)}async function w(t){var n;const i={};return(t=t||await p())&&(i.authorization=`mkcd ${t}`),i["x-pxt-target"]=null===(n=e.appTarget)||void 0===n?void 0:n.id,i}t.cachedHasAuthToken=!1,t.getAuthTokenAsync=p,t.hasAuthTokenAsync=m,t.getUserStateAsync=b,t.getAuthHeadersAsync=w;class k{constructor(){this.initialUserPreferences_=void 0,this.initialAuthCheck_=void 0,this.patchQueue=[],a=this}async initAsync(){const e=await b();this.setUserProfileAsync(null==e?void 0:e.profile),this.setUserPreferencesAsync(null==e?void 0:e.preferences)}async loginAsync(t,i,r){if(!E()||!function(e){return A().filter((t=>t.id===e)).length>0}(t))return;r=null!=r?r:x,this.clearAuthStateAsync();const a={key:(Math.PI*Math.random()).toString(36).slice(2),callbackState:r,callbackPathname:window.location.pathname,idp:t,persistent:i},l=(parseInt(await h(o))||0)>Date.now(),c=e.Util.stringifyQueryString("/api/auth/login",{response_type:"token",provider:t,persistent:i,redirect_uri:`${window.location.origin}${window.location.pathname}?authcallback=1&state=${a.key}`,prompt:l?"select_account":"silent"}),u=await this.apiAsync(c);if(u.success)a.authCodeVerifier=u.resp.authCodeVerifier,await e.storage.shared.setAsync(n,s,a),e.tickEvent("auth.login.start",{provider:t}),window.location.href=u.resp.loginUrl;else try{await this.onSignInFailed()}catch(e){}}async logoutAsync(e){if(E()){await k.staticLogoutAsync(e);try{await this.onStateCleared()}catch(e){}try{await this.onSignedOut()}catch(e){}}}static async staticLogoutAsync(t){if(!E())return;e.tickEvent("auth.logout"),await d(o,(Date.now()+6e4).toString()),t=t?t.startsWith("#")?t:`#${t}`:"";const n=`${window.location.origin}${window.location.pathname}${window.location.search}${t}`;let i="";try{const t=e.Util.stringifyQueryString("/api/auth/logout",{redirect_uri:n,authcallback:"1"}),s=await k.staticApiAsync(t);s.success&&(i=s.resp.logoutUrl)}catch(e){}await g(),await v(),e.BrowserUtils.hasWindow()&&(i?window.location.href=i:(window.location.href=n,location.reload()))}async deleteProfileAsync(){var t;if(!await this.loggedInAsync())return;const n=await b(),i=null===(t=null==n?void 0:n.profile)||void 0===t?void 0:t.id,s=await this.apiAsync("/api/user",null,"DELETE");if(s.err)try{await this.onApiError(s.err)}catch(e){}else try{await this.clearAuthStateAsync();try{await this.onProfileDeleted(i)}catch(e){}}finally{e.tickEvent("auth.profile.deleted")}}async initialUserPreferencesAsync(){if(await this.loggedInAsync())return this.initialUserPreferences_||(this.initialUserPreferences_=this.fetchUserPreferencesAsync()),this.initialUserPreferences_}async userProfileAsync(){if(!await this.loggedInAsync())return;const e=await b();return Object.assign({},e.profile)}async userPreferencesAsync(){const e=await b();return Object.assign({},e.preferences)}async authCheckAsync(){var e;if(!E())return;if(!await m())return;const t=await b();return(null===(e=null==t?void 0:t.profile)||void 0===e?void 0:e.id)?this.initialAuthCheck_||(this.initialAuthCheck_=Promise.resolve(t.profile)):this.initialAuthCheck_||(this.initialAuthCheck_=this.fetchUserAsync()),this.initialAuthCheck_}async loggedInAsync(){return!!await this.authCheckAsync()&&await this.hasUserIdAsync()}async updateUserProfileAsync(e){if(!await this.loggedInAsync())return!1;const t=await b(),n=await this.apiAsync("/api/user/profile",{id:t.profile.id,username:e.username,avatarUrl:e.avatarUrl});return n.success&&await this.setUserProfileAsync(n.resp),n.success}async patchUserPreferencesAsync(n,i={}){const s=async()=>({success:!0,res:await this.userPreferencesAsync()});if(!(n=(n=Array.isArray(n)?n:[n]).filter((e=>!!e))).length)return await s();const r=(t,n,i)=>{const s=e.U.deepCopy(t);ts.pxtc.jsonPatch.patchInPlace(s,n);let r=ts.pxtc.jsonPatch.diff(t,s);return r.length&&i&&(r=r.filter(i)),r},o=await this.userPreferencesAsync(),a=r(o,n,i.filter);if(!a.length)return await s();if(ts.pxtc.jsonPatch.patchInPlace(o,a),await this.setUserPreferencesAsync(o),!await this.loggedInAsync())return await s();this.patchQueue.push({ops:n,filter:i.filter}),clearTimeout(c);const l=async()=>{if(u=0,!this.patchQueue.length)return await s();const n=await this.apiAsync("/api/user/preferences");if(!n.success)return e.reportError("identity","failed to fetch preferences for patch",n),{success:!1,res:void 0};const i=e.U.deepCopy(n.resp)||t.DEFAULT_USER_PREFERENCES(),o=this.patchQueue;this.patchQueue=[],o.forEach((e=>{const t=r(i,e.ops,e.filter);ts.pxtc.jsonPatch.patchInPlace(i,t)}));const a=pxtc.jsonPatch.diff(n.resp,i),l=await this.apiAsync("/api/user/preferences",a,"PATCH");return l.success?this.setUserPreferencesAsync(l.resp):e.reportError("identity","failed to patch preferences",l),{success:l.success,res:l.resp}};return i.immediate?await l():(u||(u=e.U.now()),1e4<e.U.now()-u?await l():(c=setTimeout(l,1e3),{success:!1,res:void 0}))}async hasUserIdAsync(){var e;if(!E())return!1;if(!await m())return;const t=await b();return!!(null===(e=null==t?void 0:t.profile)||void 0===e?void 0:e.id)}async fetchUserAsync(){var e;if(!E())return;if(!await m())return;const t=await b();if(null===(e=null==t?void 0:t.profile)||void 0===e?void 0:e.id)return t.profile;const n=await this.apiAsync("/api/user/profile");if(n.success){const e=n.resp;return await this.setUserProfileAsync(e),e}}async setUserProfileAsync(e){const t=await this.hasUserIdAsync();await this.transformUserProfileAsync(e);const n=await this.hasUserIdAsync();try{await this.onUserProfileChanged()}catch(e){}if(n&&!t)try{await this.onSignedIn()}catch(e){}else if(!n&&t)try{await this.onSignedOut()}catch(e){}}async setUserPreferencesAsync(e){var n;const i=await b(),s=null!==(n=null==i?void 0:i.preferences)&&void 0!==n?n:t.DEFAULT_USER_PREFERENCES(),r=ts.pxtc.jsonPatch.diff(s,e),o=await this.transformUserPreferencesAsync(Object.assign(Object.assign({},s),e));try{await this.onUserPreferencesChanged(r)}catch(e){}return o}async fetchUserPreferencesAsync(){if(!await this.loggedInAsync())return;await b();const e=await this.apiAsync("/api/user/preferences");if(e.success&&e.resp){return this.setUserPreferencesAsync(e.resp)}}async transformUserProfileAsync(e){let t=await b();return t=Object.assign(Object.assign({},t),{profile:Object.assign({},e)}),await y(t),t.profile}async transformUserPreferencesAsync(e){let t=await b();return t=Object.assign(Object.assign({},t),{preferences:Object.assign({},e)}),await y(t),t.preferences}async clearAuthStateAsync(){await g(),await v();try{await this.onStateCleared()}catch(e){}}async apiAsync(e,t,n,i){return await k.staticApiAsync(e,t,n,i)}static async staticApiAsync(t,n,i,s){const r=await w(s);return t=e.BrowserUtils.isLocalHostDev()?`${e.cloud.DEV_BACKEND}${t}`:t,e.Util.requestAsync({url:t,headers:r,data:n,method:i||(n?"POST":"GET"),withCredentials:!0}).then((e=>({statusCode:e.statusCode,resp:e.json,success:2===Math.floor(e.statusCode/100),err:null}))).catch((async e=>(/logout/.test(t)||401!=e.statusCode||await k.staticLogoutAsync(),{statusCode:e.statusCode,err:e,resp:null,success:!1})))}}t.AuthClient=k;const x={hash:"",params:{}};function A(){var t,n;return Object.keys((null===(n=null===(t=e.appTarget)||void 0===t?void 0:t.cloud)||void 0===n?void 0:n.cloudProviders)||{}).map((t=>e.appTarget.cloud.cloudProviders[t])).filter((e=>e.identity)).sort(((e,t)=>e.order-t.order))}function E(){return!l&&!e.BrowserUtils.isPxtElectron()&&A().length>0}function T(e,t){return e.id===t.id&&e.sourceURL===t.sourceURL}t.loginCallbackAsync=async function(t){let i,r=Object.assign({},x);do{if(i=await e.storage.shared.getAsync(n,s),!i)return void e.debug("Auth state not found in storge.");await e.storage.shared.delAsync(n,s);const a=t.state;if(!a||i.key!==a)return void e.debug("Failed to get auth state for key");r=Object.assign(Object.assign({},x),i.callbackState);const l=t.error;if(l){const n=t.error_description;e.tickEvent("auth.login.error",{error:l,provider:i.idp}),e.log(`Auth failed: ${l}:${n}`),r=Object.assign({},x);break}const c=t.token;if(!c){e.debug("Missing authToken in auth callback.");break}if(i.authCodeVerifier){const t=e.Util.stringifyQueryString("/api/otac/check",{persistent:i.persistent});await k.staticApiAsync(t,null,null,i.authCodeVerifier)}await f(c),await d(o,void 0),e.tickEvent("auth.login.success",{provider:i.idp})}while(0);const a=r.hash.startsWith("#")?r.hash:`#${r.hash}`,l=e.Util.stringifyQueryString("",r.params),c=`${i.callbackPathname.startsWith("/")?i.callbackPathname:`/${i.callbackPathname}`}${l}${a}`;window.location.href=c},t.identityProviders=A,t.identityProvider=function(e){return A().filter((t=>t.id===e)).shift()},t.hasIdentity=E,t.enableAuth=function(e=!0){l=!e},t.userName=function(e){var t,n,i,s;return null!==(s=null!==(n=null===(t=null==e?void 0:e.idp)||void 0===t?void 0:t.displayName)&&void 0!==n?n:null===(i=null==e?void 0:e.idp)||void 0===i?void 0:i.username)&&void 0!==s?s:"??"},t.identityProviderId=function(e){var t;return null===(t=null==e?void 0:e.idp)||void 0===t?void 0:t.provider},t.firstName=function(t){const n=e.auth.userName(t);return(null==n?void 0:n.split(" ").shift())||n},t.userInitials=function(t){const n=e.auth.userName(t);return ts.pxtc.Util.initials(n)},t.generateUserProfilePicDataUrl=function(t){var n,i;if(null===(i=null===(n=null==t?void 0:t.idp)||void 0===n?void 0:n.picture)||void 0===i?void 0:i.encoded){const n=window.URL||window.webkitURL;try{const i=e.Util.stringToUint8Array(atob(t.idp.picture.encoded)),s=new Blob([i],{type:t.idp.picture.mimeType});t.idp.picture.dataUrl=n.createObjectURL(s)}catch(e){}}},t.badgeEquals=T,t.hasBadge=function(e,t){return e.badges.some((e=>T(e,t)))}}(e.auth||(e.auth={}))}(pxt||(pxt={})),function(e){e.tickEvent=function(e){}}(pxt||(pxt={})),function(e){!function(e){e.__dummy=42}(e.pxtc||(e.pxtc={}))}(ts||(ts={}));var pxtc=ts.pxtc;!function(e){!function(e){!function(e){function t(e){return e.replace(/[^\w .!?\-$]/g,(e=>{let t=e.charCodeAt(0).toString(16);return"\\u"+"0000".substr(0,4-t.length)+t}))}e.assert=function(e,t="Assertion failed"){if(!e)throw new Error(t)},e.flatClone=function(e){if(null==e)return null;let t={};return Object.keys(e).forEach((n=>{t[n]=e[n]})),t},e.clone=function(e){return null==e?null:JSON.parse(JSON.stringify(e))},e.htmlEscape=function(e){return e?e.replace(/([^\w .!?\-$])/g,(e=>"&#"+e.charCodeAt(0)+";")):e},e.htmlUnescape=function(e){return e?e.replace(/(&#\d+;)/g,(e=>String.fromCharCode(Number(e.substr(2,e.length-3))))):e},e.jsStringQuote=t,e.jsStringLiteral=function(e){return'"'+t(e)+'"'},e.initials=function(e){if(/^\w+@/.test(e)){return e.match(/^\w\w/).shift().toUpperCase()}{const t=e.match(/\b\w/g)||[];return((t.shift()||"")+(t.pop()||"")).toUpperCase()}};let n="en",i={},s={},r=!1;function o(){return n}function a(e){const t=/^(\w{2,3})-(\w{2,4}$)/i.exec(e);return t&&t[1]&&t[2]?[`${t[1].toLowerCase()}-${t[2].toUpperCase()}`,t[1].toLowerCase(),`${t[1].toLowerCase()}-${t[2].toLowerCase()}`]:[(e||"en").toLowerCase()]}function l(t,n){return 0==n.length?t:t.replace(/\{([0-9]+)(\:[^\}]+)?\}/g,(function(t,i,s){let r=n[parseInt(i)],o="",a=/^:f(\d*)\.(\d+)/.exec(s);if(a){let e=parseInt(a[2]),t=parseInt(a[1])||0,n=/^0/.test(a[1])?"0":" ",i=r.toFixed(e);if(t>0&&e>0&&(t+=e+1),t>0)for(;i.length<t;)i=n+i;o=i}else o=":x"==s?"0x"+r.toString(16):void 0===r?"(undef)":null===r?"(null)":r.toString?r.toString():r+"";return":a"==s?/^\s*[euioah]/.test(o.toLowerCase())?o="an "+o:/^\s*[bcdfgjklmnpqrstvwxz]/.test(o.toLowerCase())&&(o="a "+o):":s"==s?o=1==r?"":"s":":q"==s?o=e.htmlEscape(o):":jq"==s?o=e.jsStringQuote(o):":uri"==s?o=encodeURIComponent(o).replace(/'/g,"%27").replace(/"/g,"%22"):":url"==s?o=encodeURI(o).replace(/'/g,"%27").replace(/"/g,"%22"):":%"==s&&(o=(100*r).toFixed(1).toString()+"%"),o}))}e.enableLiveLocalizationUpdates=function(){r=!0},e.liveLocalizationEnabled=function(){return r},e.localeInfo=function(){return`${r?"live-":""}${o()}`},e.userLanguage=o,e.normalizeLanguageCode=a,e.setUserLanguage=function(e){n=a(e)[0]},e.isUserLanguageRtl=function(){return/^ar|dv|fa|ha|he|ks|ku|ps|ur|yi/i.test(n)},e.TRANSLATION_LOCALE="pxt",e.isTranslationMode=function(){return o()==e.TRANSLATION_LOCALE},e._localize=function(e){return i[e]||e},e.getLocalizedStrings=function(){return i},e.setLocalizedStrings=function(e){i=e},e.translationsCache=function(){return s},e.fmt_va=l,e.fmt=function(e,...t){return l(e,t)};const c={};e.dumpLocStats=function(){const e={};Object.keys(c).sort(((e,t)=>c[t]-c[e])).forEach((t=>e[t]=t)),console.log("prioritized list of strings:"),console.log(JSON.stringify(e,null,2))};function u(t,n){if(!t)return t;c[t]=(c[t]||0)+1;let i=e._localize(t);return i=i.replace(/^\{(id|loc):[^\}]+\}/g,""),l(i,n)}e.lf_va=u,e.lf=function(e,...t){return u(e,t)},e.rlf=function(e,...t){return u(e,t)},e.lookup=function(e,t){return e.hasOwnProperty(t)?e[t]:null},e.isoTime=function(t){let n=new Date(1e3*t);return e.fmt("{0}-{1:f02.0}-{2:f02.0} {3:f02.0}:{4:f02.0}:{5:f02.0}",n.getFullYear(),n.getMonth()+1,n.getDate(),n.getHours(),n.getMinutes(),n.getSeconds())},e.userError=function(e){let t=new Error(e);throw t.isUserError=!0,t},e.deq=function e(t,n){if(t===n)return null;if(!t||!n)return"Null value";if("object"==typeof t&&"object"==typeof n){if(Array.isArray(t)){if(!Array.isArray(n))return"Expected array";if(t.length!=n.length)return"Expected array of length "+t.length+", got "+n.length;for(let i=0;i<t.length;i++)if(null!=e(t[i],n[i]))return"Expected array value "+t[i]+" got "+n[i];return null}let i=Object.keys(t),s=Object.keys(t);if(i.length!=s.length)return"Expected "+i.length+" keys, got "+s.length;for(let s=0;s<i.length;s++){if(!Object.prototype.hasOwnProperty.call(n,i[s]))return"Missing key "+i[s];if(null!=e(t[i[s]],n[i[s]]))return"Expected value of "+i[s]+" to be "+t[i[s]]+", got "+n[i[s]]}return null}return"Unable to compare "+t+", "+n}}(e.Util||(e.Util={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={}));const lf=ts.pxtc.Util.lf;var ts,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,ts,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,ts,pxt,pxt,pxt,pxt,ts,pxt,ts,pxtmelody,pxtmelody,pxtmelody,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim;!function(e){!function(e){e.decodeBase64=function(e){return atob(e)},e.encodeBase64=function(e){return btoa(e)}}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){!function(n){function i(e,t){if(t)for(let n=0;n<t.length;++n)e.push(t[n])}function s(e){let t=[];for(let n=0;n<e.length;++n)i(t,e[n]);return t}function r(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function o(e,t,n,i,s){void 0===i&&(i=0),void 0===s&&(s=n.length-i);for(let r=0;r<s;++r)e[t+r]=n[i+r]}function a(e,t){return e==t?0:e<t?-1:1}n.CancellationToken=class{constructor(){this.pending=!1,this.cancelled=!1}startOperation(){this.pending=!0}isRunning(){return this.pending}onProgress(e){this.progressHandler=e}reportProgress(e,t){this.progressHandler&&this.progressHandler(e,t)}cancel(){this.cancelled=!0,this.pending=!1}cancelAsync(){return this.cancelled||!this.pending?(this.cancelled=!0,this.pending=!1,Promise.resolve()):(this.cancelled=!0,this.deferred=new Promise((e=>{this.resolve=e})),this.deferred)}isCancelled(){return this.cancelled}throwIfCancelled(){if(this.isCancelled())throw new Error}resolveCancel(){this.pending=!1,this.deferred&&(this.resolve(),this.deferred=void 0,this.resolve=void 0)}},n.codalHash16=function(e){const t=[251,175,119,215,81,14,79,191,103,49,181,143,186,157,0,232,31,32,55,60,152,58,17,237,174,70,160,144,220,90,57,223,59,3,18,140,111,166,203,196,134,243,124,95,222,179,197,65,180,48,36,15,107,46,233,130,165,30,123,161,209,23,97,16,40,91,219,61,100,10,210,109,250,127,22,138,29,108,244,67,207,9,178,204,74,98,126,249,167,116,34,77,193,200,121,5,20,113,71,35,128,13,182,94,25,226,227,199,75,27,41,245,230,224,43,225,177,26,155,150,212,142,218,115,241,73,88,105,39,114,62,255,192,201,145,214,168,158,221,148,154,122,12,84,82,163,44,139,228,236,205,242,217,11,187,146,159,64,86,239,195,42,106,198,118,112,184,172,87,2,173,117,176,229,247,253,137,185,99,164,102,147,45,66,231,52,141,211,194,206,246,238,56,110,78,248,63,240,189,93,92,51,53,183,19,171,72,50,33,104,101,69,8,252,83,120,76,135,85,54,202,125,188,213,96,235,136,208,162,129,190,132,156,38,47,1,7,254,24,4,216,131,89,21,28,133,37,153,149,80,170,68,6,169,234,151];function n(e){let n=0;for(let i=0;i<e.length;i++){let s=e[i];n=t[n^s]}return n}return e?function(e,t){let i;const s=new Uint8Array(e.length);for(let t=0;t<e.length;++t){const n=e.charCodeAt(t);s[t]=255&n}let r=0;for(let e=0;e<t;++e)i=n(s),r|=i<<8*e,s[0]=(s[0]+1)%255;return r}(e,2):0},n.bufferSerial=function(e,t="",n="?",i=255){for(let s=0;s<t.length;++s){const r=t[s];if(e[n]=(e[n]||"")+r,"\n"===r||e[n].length>i){let t=e[n];e[n]="",window.postMessage({type:"serial",id:n,data:t},"*")}}},n.blobReadAsDataURL=function(e){return e?new Promise(((t,n)=>{const i=new FileReader;i.onload=()=>t(i.result),i.onerror=e=>n(e),i.readAsDataURL(e)})):Promise.resolve(void 0)},n.fileReadAsBufferAsync=function(e){return e?new Promise(((t,n)=>{let i=new FileReader;i.onerror=e=>t(null),i.onload=e=>t(new Uint8Array(i.result)),i.readAsArrayBuffer(e)})):Promise.resolve(null)},n.fileReadAsTextAsync=function(e){return e?new Promise(((t,n)=>{let i=new FileReader;i.onerror=e=>t(null),i.onload=e=>t(i.result),i.readAsText(e)})):Promise.resolve(null)},n.sanitizeFileName=function(e){return e.replace(/[()\\\/.,?*^:<>!;'#$%^&|"@+=«»°{}\[\]¾½¼³²¦¬¤¢£~­¯¸`±\x00-\x1F]/g,"").trim().replace(/\s+/g,"-")},n.repeatMap=function(e,t){e=e||0;let n=[];for(let i=0;i<e;++i)n.push(t(i));return n},n.listsEqual=function(e,t){if(!e||!t||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0},n.oops=function(e="OOPS"){throw new Error(e)},n.reversed=function(e){return(e=e.slice(0)).reverse(),e},n.arrayEquals=function(e,t,n=((e,t)=>e===t)){if(e==t)return!0;if(!e&&t||!t&&e||e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!n(e[i],t[i]))return!1;return!0},n.iterMap=function(e,t){Object.keys(e).forEach((n=>t(n,e[n])))},n.mapMap=function(e,t){let n={};return Object.keys(e).forEach((i=>n[i]=t(i,e[i]))),n},n.values=function(e){return Object.keys(e||{}).map((t=>e[t]))},n.pushRange=i,n.concatArrayLike=function(e){return s(e)},n.concat=s,n.memcpy=o,n.uint8ArrayConcat=function(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),i=0;for(let t of e)o(n,i,t),i+=t.length;return n},n.jsonTryParse=function(e){try{return JSON.parse(e)}catch(e){return}},n.jsonMergeFrom=function e(t,i){i&&Object.keys(i).forEach((s=>{r(t[s])&&r(i[s])?e(t[s],i[s]):t[s]=n.clone(i[s])}))},n.jsonCopyFrom=function(e,t){let i=n.clone(t);for(let n of Object.keys(t))e[n]=i[n]},n.jsonFlatten=function(e){let t={},i=(e,s)=>{if(null!==s&&"object"==typeof s){n.assert(!Array.isArray(s)),e&&(e+=".");for(let t of Object.keys(s))i(e+t,s[t])}else t[e]=s};return i("",e),t},n.jsonUnFlatten=function(e){let t={};for(let n of Object.keys(e)){let i=t,s=n.split(".");for(let t=0;t<s.length;++t){let r=s[t];t==s.length-1?i[r]=e[n]:("object"!=typeof i[r]&&(i[r]={}),i=i[r])}}return t},n.strcmp=a,n.stringMapEq=function(e,t){let n=Object.keys(e),i=Object.keys(t);if(n.length!=i.length)return!1;for(let i of n){if(!t.hasOwnProperty(i))return!1;if(e[i]!==t[i])return!1}return!0},n.endsWith=function(e,t){return!(e.length<t.length)&&(0==t.length||e.slice(-t.length)==t)},n.startsWith=function(e,t){return!(e.length<t.length)&&(0==t.length||e.slice(0,t.length)==t)},n.contains=function(e,t){return!(e.length<t.length)&&(0==t.length||e.indexOf(t)>-1)},n.replaceAll=function(e,t,n){return t?e.split(t).join(n):e},n.snakify=function(e){const t=e.toUpperCase(),n=e.toLowerCase();if(e==t||e==n)return e;if(e.lastIndexOf("_")>0)return e;const i=t=>e[t]!=n[t],s=n=>e[n]!=t[n];let r="",o=0;for(;o<e.length;){let t=i(o),n=o;for(;n<e.length;){if(t&&s(n)){if(n-o>2){n--;break}t=!1}if(!t&&i(n))break;n++}r&&(r+="_"),r+=e.slice(o,n),o=n}return r.toUpperCase()===r?r:r.toLowerCase()},n.sortObjectFields=function(e){let t=Object.keys(e);t.sort(a);let n={};return t.forEach((t=>n[t]=e[t])),n},n.chopArray=function(e,t){let n=[];for(let i=0;i<e.length;i+=t)n.push(e.slice(i,i+t));return n},n.unique=function(e,t){let n=[],i={};return e.forEach((e=>{let s=t(e);i.hasOwnProperty(s)||(i[s]=null,n.push(e))})),n},n.groupBy=function(e,t){let n={};return e.forEach((e=>{let i=t(e);n.hasOwnProperty(i)||(n[i]=[]),n[i].push(e)})),n},n.toDictionary=function(e,t){let n={};return e.forEach((e=>{n[t(e)]=e})),n},n.toSet=function(e,t){let n={};return e.forEach((e=>{n[t(e)]=!0})),n},n.deepCopy=function e(t){if("object"!=typeof t||null===t)return t;const n=Array.isArray(t)?[]:{};for(const i in t){const s=t[i];n[i]=e(s)}return n},n.toArray=function(e){if(Array.isArray(e))return e;let t=[];if(!e)return t;for(let n=0;n<e.length;++n)t.push(e[n]);return t},n.indexOfMatching=function(e,t){for(let n=0;n<e.length;++n)if(t(e[n]))return n;return-1};const l=Promise.resolve();async function c(e,t,n){let i=0;const s=[],r=[];for(let o=0;o<e;o++){const e=(async()=>{for(;i<t.length;){const e=i++,s=t[e];r[e]=await n(s)}})();s.push(e)}try{await Promise.all(s)}catch(e){throw i=t.length,e}return r}function u(e,t){const n={};return i=>{const s=e(i);return n.hasOwnProperty(s)?n[s]:n[s]=t(i)}}n.nextTick=function(e){l.then(e)},n.delay=async function(e,t){const n=await t;return await new Promise((t=>setTimeout((()=>t()),e))),n},n.promiseMapAll=function(e,t){return Promise.all(e.map((e=>t(e))))},n.promiseMapAllSeries=function(e,t){return c(1,e,t)},n.promisePoolAsync=c,n.memoizeString=function(e){return u((e=>e),e)},n.promiseTimeout=async function(e,t,n){let i,s;const r=new Promise(((t,r)=>{s=t,i=setTimeout((()=>{s=void 0,clearTimeout(i),r(n||`Promise timed out after ${e}ms`)}),e)}));return Promise.race([t,r]).then((e=>(s&&(clearTimeout(i),s()),e)))},n.defer=function(){let e,t,n,i=!1;return{resolve:function(n){i?pxt.debug("Deferred promise already resolved"):(t?t(n):e=e||new Promise((function(e){e(n)})),i=!0)},reject:function(t){i?pxt.debug("Deferred promise already resolved"):(n?n(t):e=e||new Promise((function(e,n){n(t)})),i=!0)},promise:new Promise((function(i,s){e?i(e):(t=i,n=s)}))}},n.memoize=u,n.debounce=function(e,t,n){let i;return function(){let s=this,r=arguments,o=function(){i=null,n||e.apply(s,r)},a=n&&!i;return clearTimeout(i),i=setTimeout(o,t),a&&e.apply(s,r),i}};function d(e){return e&&(e=e.replace(/\\/g,"/")),e}function h(e){return n.httpRequestCoreAsync(e).then((i=>{const s=i.statusCode;if((e.successCodes||[304,200,201,202]).indexOf(s)<0&&!e.allowHttpErrors){const t=n.lf("Bad HTTP status code: {0} at {1}; message: {2}",i.statusCode,e.url,(i.text||"").slice(0,500)),s=new Error(t);return s.statusCode=i.statusCode,Promise.reject(s)}return i.text&&/application\/json/.test(i.headers["content-type"])&&(i.json=t.U.jsonTryParse(i.text)),i}))}function p(e,t){let n="";if(!e)return n;for(let i=0;i<e.length;++i){let s=e.charCodeAt(i);if(s<=127)n+=e.charAt(i);else if(s<=2047)n+=String.fromCharCode(192|s>>6,128|63&s);else{if(!t&&55296<=s&&s<=56319){let t=e.charCodeAt(++i);isNaN(t)||(s=65536+(s-55296<<10)+(t-56320))}n+=s<=65535?String.fromCharCode(224|s>>12,128|s>>6&63,128|63&s):String.fromCharCode(240|s>>18,128|s>>12&63,128|s>>6&63,128|63&s)}}return n}n.AdaptiveDebouncer=class{constructor(e,t=300,n=2e3,i=2){this.func=e,this.minDelay=t,this.maxDelay=n,this.slowdownFactor=i,this.lastPoke=0,this.recentGaps=[],this.wrapped=()=>{this.timeout=null,this.func()}}poke(){const e=Date.now();if(this.lastPoke){const t=e-this.lastPoke;if(t<10)return;for(t<4e3&&this.recentGaps.push(t);this.recentGaps.length>10;)this.recentGaps.shift()}this.lastPoke=e}trigger(){let e=this.maxDelay;if(this.lastPoke){const t=this.recentGaps.slice();t.sort();const n=t[t.length>>1]||1;e=Math.min(Math.max(n*this.slowdownFactor|0,this.minDelay),this.maxDelay);e-=Date.now()-this.lastPoke,e<0&&(e=0),this.lastPoke=null}clearTimeout(this.timeout),this.timeout=setTimeout(this.wrapped,e)}},n.throttle=function(e,t,n){let i;return function(){let s=this,r=arguments,o=function(){i=null,n||e.apply(s,r)},a=n&&!i;i||(i=setTimeout(o,t)),a&&e.apply(s,r)}},n.randomPermute=function(e){for(let t=0;t<e.length;++t){let n=m()%e.length,i=e[t];e[t]=e[n],e[n]=i}},n.randomPick=function(e){return 0==e.length?null:e[m()%e.length]},n.timeSince=function(e){let t=(Date.now()-(e*=1e3))/1e3;return isNaN(t)?"":t<-30?(t=-t,t<60?n.lf("in a few seconds"):t<120?n.lf("in a minute"):t<3600?n.lf("in {0} minute{0:s}",Math.floor(t/60)):t<7200?n.lf("in an hour"):t<86400?n.lf("in {0} hour{0:s}",Math.floor(t/60/60)):t<2592e3?n.lf("in {0} day{0:s}",Math.floor(t/60/60/24)):t<31536e3?n.lf("in {0} month{0:s}",Math.floor(t/60/60/24/30)):n.lf("in {0} year{0:s}",Math.floor(t/60/60/24/365))):t<0?n.lf("now"):t<10?n.lf("a few seconds ago"):t<60?n.lf("{0} second{0:s} ago",Math.floor(t)):t<120?n.lf("a minute ago"):t<3600?n.lf("{0} minute{0:s} ago",Math.floor(t/60)):t<7200?n.lf("an hour ago"):t<86400?n.lf("{0} hour{0:s} ago",Math.floor(t/60/60)):t<2592e3?n.lf("{0} day{0:s} ago",Math.floor(t/60/60/24)):t<31536e3?n.lf("{0} month{0:s} ago",Math.floor(t/60/60/24/30)):n.lf("{0} year{0:s} ago",Math.floor(t/60/60/24/365))},n.unicodeToChar=function(e){return e.replace(/\\u([\d\w]{4})/gi,(function(e,t){return String.fromCharCode(parseInt(t,16))}))},n.escapeForRegex=function(e){return null==e?void 0:e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},n.stripUrlProtocol=function(e){return null==e?void 0:e.replace(/.*?:\/\//g,"")},n.normalizePath=d,n.pathJoin=function(e,t){if(d(e),d(t),e||t)return e?t?("/"!==e.charAt(e.length-1)&&(e+="/"),"/"==t.charAt(0)&&(t=t.substring(1)),e+t):e:t},n.isNodeJS="undefined"==typeof window,n.requestAsync=h,n.httpGetTextAsync=function(e){return h({url:e}).then((e=>e.text))},n.httpGetJsonAsync=function(e){return h({url:e}).then((e=>e.json))},n.httpPostJsonAsync=function(e,t){return h({url:e,data:t||{}}).then((e=>e.json))},n.stringToUint8Array=function(e){let t=e.length,n=new Uint8Array(t);for(let i=0;i<t;++i)n[i]=255&e.charCodeAt(i);return n},n.uint8ArrayToString=function(e){let t=e.length,n="";for(let i=0;i<t;++i)n+=String.fromCharCode(e[i]);return n},n.fromUTF8=function(e){if(!e)return"";let t="";for(let n=0;n<e.length;++n){let i=255&e.charCodeAt(n);t+=37==i||i>127?"%"+i.toString(16):e.charAt(n)}return decodeURIComponent(t)},n.toUTF8=p,n.toHex=function(e){let t="";for(let n=0;n<e.length;++n)t+=("0"+e[n].toString(16)).slice(-2);return t},n.fromHex=function(e){let t=new Uint8Array(e.length>>1);for(let n=0;n<e.length;n+=2)t[n>>1]=parseInt(e.slice(n,n+2),16);return t};n.PromiseQueue=class{constructor(){this.promises={}}enqueue(e,t){return new Promise(((n,i)=>{let s=this.promises[e];s||(s=this.promises[e]=[]),s.push((()=>t().finally((()=>{s.shift(),0==s.length?delete this.promises[e]:s[0]()})).then(n,i))),1==s.length&&s[0]()}))}};function f(){return Date.now()}function m(){let e=new Uint8Array(4);return n.getRandomBuf(e),new Uint32Array(e.buffer)[0]}function g(e,t,n){function i(i){pxt.debug(`downloading translations for ${e} ${t}`);let s=pxt.BrowserUtils.isLocalHost()||pxt.webConfig.isStatic?"https://makecode.com/api/":"",r=`${s}translations?lang=${encodeURIComponent(e)}&filename=${encodeURIComponent(t)}&approved=true`;const o={};return n&&!pxt.Cloud.useCdnApi()&&(o["If-None-Match"]=n),(s?h:pxt.Cloud.apiRequestWithCdnAsync)({url:r,headers:o}).then((s=>304==s.statusCode||200==s.statusCode?(n=s.headers.etag||"",pxt.BrowserUtils.translationDbAsync().then((r=>r.setAsync(e,t,n,s.json||i))).then((()=>s.json||i))):s.json),(e=>{console.log(`failed to load translations from ${r}`)}))}return pxt.BrowserUtils.translationDbAsync().then((n=>n.getAsync(e,t))).then((e=>{if(e){n=e.etag;return(Date.now()-e.time)/1e3>300&&i(e.strings),e.strings}return i()}))}function b(e){let[t,i]=n.normalizeLanguageCode(e),s=pxt.appTarget.appTheme;if(s&&s.availableLocales){if(s.availableLocales.indexOf(t)>-1)return!0;if(i&&s.availableLocales.indexOf(i)>-1)return!0}return!1}let y;function v(e,i,s,r,o){if(o=o||y.Editor,"en-US"===(s=n.normalizeLanguageCode(s)[0])||"en"===s)return Promise.resolve(void 0);let a,l,c=`${s}/${r}/${o}`;if(n.translationsCache()[c])return Promise.resolve(n.translationsCache()[c]);switch(o){case y.Editor:a=[{staticName:"strings.json",path:"strings.json"},{staticName:"target-strings.json",path:e+"/target-strings.json"}];break;case y.Sim:a=[{staticName:"sim-strings.json",path:e+"/sim-strings.json"}];break;case y.Apis:a=[{staticName:"bundled-strings.json",path:e+"/bundled-strings.json"}];break;case y.SkillMap:a=[{staticName:"skillmap-strings.json",path:"/skillmap-strings.json"}]}function u(e){e&&(l||(l={}),Object.keys(e).filter((t=>!!e[t])).forEach((t=>l[t]=e[t])))}if(r){let r=0;return t.U.promiseMapAllSeries(a,(e=>g(s,e.path).then(u,(e=>{console.log(e.message),++r})))).then((()=>(r&&(n.translationsCache()[c]=l),r!==a.length&&l?Promise.resolve(l):(pxt.tickEvent("translations.livetranslationsfailed"),v(e,i,s,!1,o)))))}return Promise.all(a.map((e=>n.httpGetJsonAsync(`${i}locales/${s}/${e.staticName}`).catch((e=>{}))))).then((e=>{let t={};e.forEach((e=>pxt.Util.jsonMergeFrom(t,e))),Object.keys(t).length&&(l=t,n.translationsCache()[c]=l)}),(e=>{console.error("failed to load localizations")})).then((()=>l))}function w(e){const t={};for(const n of Object.keys(e))t[n]=k(e[n]);return t}function k(e){var t;return{attributes:Object.assign({},e.attributes),parameters:null===(t=e.parameters)||void 0===t?void 0:t.map(x),extendsTypes:e.extendsTypes?[...e.extendsTypes]:void 0,pkgs:e.pkgs?[...e.pkgs]:void 0,combinedProperties:e.combinedProperties?[...e.combinedProperties]:void 0,name:e.name,namespace:e.namespace,fileName:e.fileName,kind:e.kind,retType:e.retType,isInstance:e.isInstance,isContextual:e.isContextual,qName:e.qName,pkg:e.pkg,snippet:e.snippet,snippetName:e.snippetName,snippetWithMarkers:e.snippetWithMarkers,pySnippet:e.pySnippet,pySnippetName:e.pySnippetName,pySnippetWithMarkers:e.pySnippetWithMarkers,blockFields:e.blockFields,isReadOnly:e.isReadOnly,pyName:e.pyName,pyQName:e.pyQName,snippetAddsDefinitions:e.snippetAddsDefinitions}}function x(e){var n,i;return{name:e.name,description:e.description,type:e.type,pyTypeString:e.pyTypeString,initializer:e.initializer,default:e.default,properties:null===(n=e.properties)||void 0===n?void 0:n.map(A),handlerParameters:null===(i=e.handlerParameters)||void 0===i?void 0:i.map(A),options:e.options?t.U.clone(e.options):void 0,isEnum:e.isEnum}}function A(e){return{name:e.name,type:e.type}}n.PromiseBuffer=class{constructor(){this.waiting=[],this.available=[]}drain(){for(let e of this.waiting)e(new Error("Promise Buffer Reset"));this.waiting=[],this.available=[]}pushError(e){this.push(e)}push(e){let t=this.waiting.shift();t?t(e):this.available.push(e)}shiftAsync(e=0){if(this.available.length>0){let e=this.available.shift();return e instanceof Error?Promise.reject(e):Promise.resolve(e)}return new Promise(((n,i)=>{let s=e=>{e instanceof Error?i(e):n(e)};this.waiting.push(s),e>0&&t.U.delay(e).then((()=>{let e=this.waiting.indexOf(s);e>=0&&(this.waiting.splice(e,1),i(new Error("Timeout")))}))}))}},n.now=f,n.nowSeconds=function(){return Math.round(f()/1e3)},n.timeout=function(e){return new Promise((t=>setTimeout((()=>t()),e)))},n.cpuUs=()=>{const e="undefined"!=typeof performance?performance.now.bind(performance)||performance.moznow.bind(performance)||performance.msNow.bind(performance)||performance.webkitNow.bind(performance)||performance.oNow.bind(performance):Date.now;return n.cpuUs=()=>1e3*e(),n.cpuUs()},n.getMime=function(e){let t=/\.([a-zA-Z0-9]+)$/.exec(e);if(!t)return"application/octet-stream";switch(t[1].toLowerCase()){case"txt":return"text/plain";case"html":case"htm":return"text/html";case"css":return"text/css";case"js":return"application/javascript";case"jpg":case"jpeg":return"image/jpeg";case"png":return"image/png";case"ico":return"image/x-icon";case"manifest":return"text/cache-manifest";case"webmanifest":return"application/manifest+json";case"json":return"application/json";case"svg":return"image/svg+xml";case"eot":return"application/vnd.ms-fontobject";case"ttf":return"font/ttf";case"woff":return"application/font-woff";case"woff2":return"application/font-woff2";case"md":return"text/markdown";case"xml":return"application/xml";case"m4a":return"audio/m4a";case"mp3":return"audio/mp3";default:return"application/octet-stream"}},n.randomUint32=m,n.guidGen=function(){function e(){return(65536|m()).toString(16).slice(-4)}return e()+e()+"-"+e()+"-4"+e().slice(-3)+"-"+e()+"-"+e()+e()+e()},n.downloadLiveTranslationsAsync=g,n.pxtLangCookieId="PXT_LANG",n.langCookieExpirationDays=30,n.allLanguages={af:{englishName:"Afrikaans",localizedName:"Afrikaans"},ar:{englishName:"Arabic",localizedName:"العربية"},az:{englishName:"Azerbaijani",localizedName:"آذربایجان دیلی"},bg:{englishName:"Bulgarian",localizedName:"български"},bi:{englishName:"Bislama",localizedName:"Bislama"},bn:{englishName:"Bengali",localizedName:"বাংলা"},ca:{englishName:"Catalan",localizedName:"Català"},cs:{englishName:"Czech",localizedName:"Čeština"},cy:{englishName:"Welsh",localizedName:"Cymraeg"},da:{englishName:"Danish",localizedName:"Dansk"},de:{englishName:"German",localizedName:"Deutsch"},el:{englishName:"Greek",localizedName:"Ελληνικά"},en:{englishName:"English",localizedName:"English"},"es-ES":{englishName:"Spanish (Spain)",localizedName:"Español (España)"},"es-MX":{englishName:"Spanish (Mexico)",localizedName:"Español (México)"},et:{englishName:"Estonian",localizedName:"Eesti"},eu:{englishName:"Basque",localizedName:"Euskara"},fa:{englishName:"Persian",localizedName:"فارسی"},fi:{englishName:"Finnish",localizedName:"Suomi"},fil:{englishName:"Filipino",localizedName:"Filipino"},fo:{englishName:"Faroese",localizedName:"føroyskt"},fr:{englishName:"French",localizedName:"Français"},"fr-CA":{englishName:"French (Canada)",localizedName:"Français (Canada)"},"ga-IE":{englishName:"Irish",localizedName:"Gaeilge"},gl:{englishName:"Galician",localizedName:"galego"},"gu-IN":{englishName:"Gujarati",localizedName:"ગુજરાતી"},haw:{englishName:"Hawaiian",localizedName:"ʻŌlelo Hawaiʻi"},hi:{englishName:"Hindi",localizedName:"हिन्दी"},he:{englishName:"Hebrew",localizedName:"עברית"},hr:{englishName:"Croatian",localizedName:"Hrvatski"},hu:{englishName:"Hungarian",localizedName:"Magyar"},"hy-AM":{englishName:"Armenian (Armenia)",localizedName:"Հայերէն (Հայաստան)"},id:{englishName:"Indonesian",localizedName:"Bahasa Indonesia"},is:{englishName:"Icelandic",localizedName:"Íslenska"},it:{englishName:"Italian",localizedName:"Italiano"},ja:{englishName:"Japanese",localizedName:"日本語"},"ja-HIRA":{englishName:"Hiragana",localizedName:"にほんご"},ka:{englishName:"Georgian",localizedName:"ქართული"},kab:{englishName:"Kabyle",localizedName:"شئعم"},kk:{englishName:"Kazakh",localizedName:"қазақ тілі"},km:{englishName:"Khmer",localizedName:"ខ្មែរ"},kmr:{englishName:"Kurmanji (Kurdish)",localizedName:"کورمانجی‎"},kn:{englishName:"Kannada",localizedName:"ಕನ್ನಡ"},ko:{englishName:"Korean",localizedName:"한국어"},lt:{englishName:"Lithuanian",localizedName:"Lietuvių"},lv:{englishName:"Latvian",localizedName:"Latviešu"},"ml-IN":{englishName:"Malayalam",localizedName:"മലയാളം"},mr:{englishName:"Marathi",localizedName:"मराठी"},ms:{englishName:"Malay",localizedName:"Melayu"},nl:{englishName:"Dutch",localizedName:"Nederlands"},no:{englishName:"Norwegian",localizedName:"Norsk"},nb:{englishName:"Norwegian Bokmal",localizedName:"Norsk bokmål"},"nn-NO":{englishName:"Norwegian Nynorsk",localizedName:"Norsk nynorsk"},"pa-IN":{englishName:"Punjabi",localizedName:"ਪੰਜਾਬੀ"},pl:{englishName:"Polish",localizedName:"Polski"},ps:{englishName:"Pashto",localizedName:"پښتو"},"pt-BR":{englishName:"Portuguese (Brazil)",localizedName:"Português (Brasil)"},"pt-PT":{englishName:"Portuguese (Portugal)",localizedName:"Português (Portugal)"},ro:{englishName:"Romanian",localizedName:"Română"},ru:{englishName:"Russian",localizedName:"Русский"},sat:{englishName:"Santali",localizedName:"ᱥᱚᱸᱴᱚᱞᱤ"},"si-LK":{englishName:"Sinhala",localizedName:"සිංහල"},sk:{englishName:"Slovak",localizedName:"Slovenčina"},sl:{englishName:"Slovenian",localizedName:"Slovenski"},sq:{englishName:"Albanian",localizedName:"shqip"},sr:{englishName:"Serbian (Cyrillic)",localizedName:"Srpski"},su:{englishName:"Sundanese",localizedName:"ᮘᮞ ᮞᮥᮔ᮪ᮓ"},"sv-SE":{englishName:"Swedish",localizedName:"Svenska"},sw:{englishName:"Swahili",localizedName:"Kiswahili"},"sw-TZ":{englishName:"Swahili (Tanzania)",localizedName:"Kiswahili (Tanzania)"},ta:{englishName:"Tamil",localizedName:"தமிழ்"},te:{englishName:"Telugu",localizedName:"తెలుగు"},th:{englishName:"Thai",localizedName:"ภาษาไทย"},tl:{englishName:"Tagalog",localizedName:"ᜏᜒᜃᜅ᜔ ᜆᜄᜎᜓᜄ᜔"},tr:{englishName:"Turkish",localizedName:"Türkçe"},uk:{englishName:"Ukrainian",localizedName:"Українська"},"ur-IN":{englishName:"Urdu (India)",localizedName:"اردو (ہندوستان)"},"ur-PK":{englishName:"Urdu (Pakistan)",localizedName:"اردو (پاکستان)"},vi:{englishName:"Vietnamese",localizedName:"Tiếng việt"},"zh-CN":{englishName:"Chinese (Simplified)",localizedName:"中文(简体)"},"zh-TW":{englishName:"Chinese (Traditional)",localizedName:"中文(繁體)"}},n.isLocaleEnabled=b,n.updateLocalizationAsync=function(t){const{targetId:i,baseUrl:s,force:r}=t;let{code:o}=t;if(o=n.normalizeLanguageCode(o)[0],"en-US"===o&&(o="en"),o===n.userLanguage()||!b(o)&&!r)return pxt.debug(`loc: ${o} (using built-in)`),Promise.resolve();pxt.debug(`loc: ${o}`);const a=pxt.Util.liveLocalizationEnabled();return v(i,s,o,a,e.pxtc.Util.TranslationsKind.Editor).then((t=>{var r;return t&&(n.setUserLanguage(o),null===(r=pxt.analytics)||void 0===r||r.addDefaultProperties({lang:o}),n.setLocalizedStrings(t)),e.pxtc.Util.downloadTranslationsAsync(i,s,o,a,e.pxtc.Util.TranslationsKind.Apis).then((t=>{t&&(e.pxtc.apiLocalizationStrings=t)}))}))},function(e){e[e.Editor=0]="Editor",e[e.Sim=1]="Sim",e[e.Apis=2]="Apis",e[e.SkillMap=3]="SkillMap"}(y=n.TranslationsKind||(n.TranslationsKind={})),n.downloadTranslationsAsync=v,n.capitalize=function(e){return e?e[0].toLocaleUpperCase()+e.slice(1):e},n.uncapitalize=function(e){return(e||"").split(/(?=[A-Z])/g).join(" ").toLowerCase()},n.camelCaseToLowercaseWithSpaces=function(e){return e.replace(/([A-Z])/gm," $1").toLocaleLowerCase().trim()},n.snakeCaseToLowercaseWithSpaces=function(e){return e.replace(/_/g," ").toLocaleLowerCase().trim()},n.range=function(e){let t=[];for(let n=0;n<e;++n)t.push(n);return t},n.multipartPostAsync=function(e,t={},i=null,s=null){const r="--------------------------0461489f461126c5";let o="";Object.keys(t).forEach((e=>function(e,t){o+=r+"\r\n",o+='Content-Disposition: form-data; name="'+e+'"\r\n\r\n',o+=t+"\r\n"}(e,t[e]))),i&&function(e,t){const n=e.split("/").reverse()[0];o+=r+"\r\n",o+='Content-Disposition: form-data; name="files['+e+']"; filename="'+n+'"\r\n',o+="\r\n",o+=t+"\r\n"}(i,s),o+=r+"--\r\n";const a={url:e,method:"POST",headers:{"Content-Type":"multipart/form-data; boundary="+r.slice(2)},data:o};return n.httpRequestCoreAsync(a)},n.toDataUri=function(e,n){return/^https?:/i.test(e)||/^data:/i.test(e)?e:(n||/^<svg/i.test(e)&&(n="image/svg+xml"),/xml|svg/.test(n)?`data:${n},${encodeURIComponent(e)}`:`data:${n||"image/png"};base64,${t.encodeBase64(p(e))}`)},n.imageMagic=1496611453,n.imageHeaderSize=36,n.encodeBlobAsync=function(e,t){const i=n.imageHeaderSize+t.length,s=3*(e.width*e.height-1);let r=1;for(;r<4&&!(s*r>=8*i);)r++;let o=s*r>>3,a=i-o,l=0,c=e.width*e.height*4;if(a>0){const t=3*e.width;l=Math.ceil(a/t);const n=document.createElement("canvas");n.width=e.width,n.height=e.height+l;n.getContext("2d").drawImage(e,0,0),e=n}let u=pxt.HF2.encodeU32LE([n.imageMagic,t.length,l,0,0,0,0,0,0]);function d(e,t,n,i){let s=0,r=0,o=i[r++];const a=(1<<n)-1;let l=!0;for(;l;){let c=o>>s&a,u=8-s;if(u<=n){if(r>=i.length){if(0==u)break;l=!1}o=i[r++],c|=o<<u&a,s=n-u}else s+=n;e[t]=255&(e[t]&~a|c),3==(3&++t)&&(e[t++]=255)}return t}pxt.Util.assert(u.length==n.imageHeaderSize);const h=e.getContext("2d"),p=h.getImageData(0,0,e.width,e.height);d(p.data,0,1,[r]);let f=4;if(f=d(p.data,f,r,u),pxt.Util.assert(0==(3&f)),0==l)f=d(p.data,f,r,t);else{let e=o-u.length;f=d(p.data,f,r,t.slice(0,e)),f=d(p.data,c,8,t.slice(e))}for(f|=3;f<p.data.length;)p.data[f]=255,f+=4;return h.putImageData(p,0,0),e},n.decodeBlobAsync=function(e){return pxt.BrowserUtils.loadCanvasAsync(e).then((e=>{const t=e.getContext("2d").getImageData(0,0,e.width,e.height).data,i=1&t[0]|(1&t[1])<<1|(1&t[2])<<2;if(i>5||0==i)return Promise.reject(new Error(n.lf("Invalid encoded PNG format")));function s(e,n,i){let s=0,r=0,o=0;const a=(1<<n)-1;for(;r<i.length;)o|=(t[e++]&a)<<s,3==(3&e)&&e++,s+=n,s>=8&&(i[r++]=255&o,o>>=8,s-=8);return e}const r=new Uint8Array(pxt.Util.imageHeaderSize);let o=s(4,i,r);const a=pxt.HF2.decodeU32LE(r);if(a[0]!=pxt.Util.imageMagic)return Promise.reject(new Error(n.lf("Invalid magic in encoded PNG")));const l=new Uint8Array(a[1]),c=a[2];if(c>0){const t=(e.height-c)*e.width,n=new Uint8Array((3*(t-1)*i>>3)-pxt.Util.imageHeaderSize);s(o,i,n),l.set(n);const r=new Uint8Array(l.length-n.length);s(4*t,8,r),l.set(r,n.length)}else s(o,i,l);return l}))},n.parseQueryString=function(e){let t={};return e.replace(/\+/g," ").replace(/([^#?&=]+)=([^#?&=]*)/g,((e,n,i)=>(t[decodeURIComponent(n)]=decodeURIComponent(i),""))),t},n.stringifyQueryString=function(e,t){for(let n of Object.keys(t))e.indexOf("?")>=0?e+="&":e+="?",e+=encodeURIComponent(n)+"="+encodeURIComponent(t[n]);return e},n.cloneTargetBundle=function(e){const t=(e=Object.assign({},e)).apiInfo;delete e.apiInfo;const i=e.bundleddirs;delete e.bundleddirs;const s=e.bundledpkgs;delete e.bundledpkgs;const r=e.tutorialInfo;delete e.tutorialInfo;const o=n.clone(e);if(t){o.apiInfo={};for(const e of Object.keys(t)){const n=t[e].apis;o.apiInfo[e]={sha:t[e].sha,apis:{jres:Object.assign({},n.jres),byQName:w(n.byQName)}}}}if(i&&(o.bundleddirs=[...i]),s){o.bundledpkgs={};for(const e of Object.keys(s))o.bundledpkgs[e]=Object.assign({},s[e])}if(r){o.tutorialInfo={};for(const e of Object.keys(r)){const t=r[e];o.tutorialInfo[e]={hash:t.hash,usedBlocks:Object.assign({},t.usedBlocks),snippetBlocks:Object.assign({},t.snippetBlocks),highlightBlocks:Object.assign({},t.highlightBlocks),validateBlocks:Object.assign({},t.validateBlocks)}}}return o},n.cloneApis=w,n.cloneSymbolInfo=k,n.toUTF8Array=function(e){return(new TextEncoder).encode(e)},n.fromUTF8Array=function(e){return(new TextDecoder).decode(e)}}(t.Util||(t.Util={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){!function(t){e.Util.httpRequestCoreAsync=function(t){return new Promise(((n,i)=>{let s,r=!1,o=e.Util.clone(t.headers)||{};s=new XMLHttpRequest,t.responseArrayBuffer&&(s.responseType="arraybuffer"),t.withCredentials&&(s.withCredentials=!0),s.onreadystatechange=()=>{if(!r&&4==s.readyState){r=!0;let e={statusCode:s.status,headers:{},buffer:s.responseBody||s.response,text:t.responseArrayBuffer?void 0:s.responseText};s.getAllResponseHeaders().split(/\r?\n/).forEach((t=>{let n=/^\s*([^:]+): (.*)/.exec(t);n&&(e.headers[n[1].toLowerCase()]=n[2])})),n(e)}};let a,l=t.data,c=t.method||(null==l?"GET":"POST");null==l?a=null:l instanceof Uint8Array?a=l:"object"==typeof l?(a=JSON.stringify(l),o["content-type"]="application/json; charset=utf8"):"string"==typeof l?a=l:e.Util.oops("bad data"),s.open(c,t.url),Object.keys(o).forEach((e=>{s.setRequestHeader(e,o[e])})),null==a?s.send():s.send(a)}))},e.Util.sha256=o,e.Util.getRandomBuf=e=>{if(window.crypto)window.crypto.getRandomValues(e);else for(let t=0;t<e.length;++t)e[t]=Math.floor(255*Math.random())};const n=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function i(e,t){return e>>>t|e<<32-t}function s(t,s){e.Util.assert(8==t.length),e.Util.assert(64==s.length);for(let e=16;e<64;++e){let t=i(s[e-15],7)^i(s[e-15],18)^s[e-15]>>>3,n=i(s[e-2],17)^i(s[e-2],19)^s[e-2]>>>10;s[e]=s[e-16]+t+s[e-7]+n|0}let r=t[0],o=t[1],a=t[2],l=t[3],c=t[4],u=t[5],d=t[6],h=t[7];for(let e=0;e<64;++e){let t=h+(i(c,6)^i(c,11)^i(c,25))+(c&u^~c&d)+n[e]+s[e]|0,p=r&o^r&a^o&a;h=d,d=u,u=c,c=l+t|0,l=a,a=o,o=r,r=t+((i(r,2)^i(r,13)^i(r,22))+p|0)|0}t[0]+=r,t[1]+=o,t[2]+=a,t[3]+=l,t[4]+=c,t[5]+=u,t[6]+=d,t[7]+=h}function r(e){let t=new Uint32Array(8);t[0]=1779033703,t[1]=3144134277,t[2]=1013904242,t[3]=2773480762,t[4]=1359893119,t[5]=2600822924,t[6]=528734635,t[7]=1541459225;let n=new Uint32Array(64);function i(e){let i=e.length-63;for(let r=0;r<i;r+=64){for(let t=0;t<16;t++){let i=(t<<2)+r;n[t]=e[i]<<24|e[i+1]<<16|e[i+2]<<8|e[i+3]}s(t,n)}}i(e);let r=64-(e.length+9)%64;64==r&&(r=0);let o=e.length-e.length%64,a=new Uint8Array(e.length-o+1+r+8),l=0;for(;o<e.length;)a[l++]=e[o++];for(a[l++]=128;r-- >0;)a[l++]=0;let c=8*e.length;for(l=a.length;c>0;)a[--l]=255&c,c>>=8;i(a);let u="";for(let e=0;e<t.length;++e)u+=("000000000"+t[e].toString(16)).slice(-8);return u.toLowerCase()}function o(t){pxt.perf.measureStart("sha256buffer");const n=r(e.Util.toUTF8Array(t));return pxt.perf.measureEnd("sha256buffer"),n}t.sha256buffer=r,t.sha256string=o}(e.BrowserImpl||(e.BrowserImpl={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){!function(t){const n={add:(e,t,n)=>{if("object"!=typeof e)throw new Error("jsonPatch: expected object type");if(t in e)throw new Error(`jsonPatch: object already contains key ${t}`);e[t]=n},replace:(e,t,n)=>{if("object"!=typeof e)throw new Error("jsonPatch: expected object type");e[t]=n},remove:(e,t)=>{if("object"!=typeof e)throw new Error("jsonPatch: expected object type");delete e[t]}},i={add:(e,t,n)=>{if(!Array.isArray(e))throw new Error("jsonPatch: expected array type");if(t in e)throw new Error(`jsonPatch: key ${t} already exists in array`);"number"!=typeof t||t!==Math.floor(t)?e[t]=n:e.splice(t,0,n)},replace:(e,t,n)=>{if(!Array.isArray(e))throw new Error("jsonPatch: expected array type");"number"!=typeof t||t!==Math.floor(t)?e[t]=n:e.splice(t,1,n)},remove:(e,t)=>{if(!Array.isArray(e))throw new Error("jsonPatch: expected array type");"number"!=typeof t||t!==Math.floor(t)?delete e[t]:e.splice(t,1)}};t.diff=function(e,t){const n={add:[],remove:[],replace:[]};function i(e,t){if(!Array.isArray(e))return t;const n=Number.parseFloat(t);return Number.isNaN(n)?t:n}return function e(t,s,r){if(!Object.is(t,s)){s=s||{},t=t||{};for(let e of Object.keys(t))if(!(e in s)){const s=i(t,e);n.remove.push({op:"remove",path:r.concat(s)})}for(const o of Object.keys(s)){const a=t[o],l=s[o],c=i(s,o);c in t?"object"!=typeof a&&"object"!=typeof l&&a!==l||typeof a!=typeof l||Array.isArray(a)!==Array.isArray(l)?n.replace.push({op:"replace",path:r.concat(c),value:l}):e(a,l,r.concat(c)):void 0!==s[c]&&(r.length&&n.add.push({op:"add",path:r,value:Array.isArray(s)?[]:{}}),n.add.push({op:"add",path:r.concat(c),value:l}))}}}(e,t,[]),[...n.remove.reverse(),...n.replace,...n.add.sort(((e,t)=>e.path.length-t.path.length))]},t.patchInPlace=function(e,t){if(!e||"object"!=typeof e)throw new Error("jsonPatch: Must be an object or an array.");for(const s of t){const t=s.path.slice(),r=t.pop();if(null==r)throw new Error("jsonPatch: missing last key");let o=e,a=t.shift();for(;null!=a;){if(!(a in o))throw new Error(`jsonPatch: missing parent element ${a}`);o=o[a],a=t.shift()}if(Array.isArray(o)&&"number"!=typeof r)throw new Error("jsonPatch: expected numeric index for array object");const l=Array.isArray(o)?i:n;"remove"===s.op?l.remove(o,r):"add"!==s.op||r in o?"replace"===s.op&&l.replace(o,r,s.value):l.add(o,r,s.value)}},t.opsAreEqual=function(t,n){return t.op===n.op&&e.U.arrayEquals(t.path,n.path)}}(e.jsonPatch||(e.jsonPatch={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){!function(t){!function(t){function n(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){const i=Array.isArray(e),s=Array.isArray(t);if(i&&s){if(e.length!==t.length)return!1;for(let i=0;i<e.length;++i)if(!n(e[i],t[i]))return!1;return!0}if(i!==s)return!1;const r=Object.keys(e);if(r.length!==Object.keys(t).length)return!1;for(const i of r){if(!t.hasOwnProperty(i))return!1;if(!n(e[i],t[i]))return!1}return!0}return e!=e&&t!=t}t.diffTests=function(){const t=[{comment:"test 1",obja:{a:4,b:5},objb:{a:3,b:5},expected:[{op:"replace",path:["a"],value:3}]},{comment:"test 2",obja:{a:3,b:5},objb:{a:4,c:5},expected:[{op:"remove",path:["b"]},{op:"replace",path:["a"],value:4},{op:"add",path:["c"],value:5}]},{comment:"test 3",obja:{a:4,b:[1,2,3]},objb:{a:3,b:[1,2,4]},expected:[{op:"replace",path:["a"],value:3},{op:"replace",path:["b",2],value:4}]},{comment:"test 4",obja:{a:3,b:[1,2,4]},objb:{a:3,b:[1,2,4,5]},expected:[{op:"add",path:["b"],value:[]},{op:"add",path:["b",3],value:5}]},{comment:"test 5",obja:{a:4,b:{c:3}},objb:{a:4,b:{c:4}},expected:[{op:"replace",path:["b","c"],value:4}]},{comment:"test 6",obja:{a:4,b:{c:4}},objb:{a:5,b:{d:4}},expected:[{op:"remove",path:["b","c"]},{op:"replace",path:["a"],value:5},{op:"add",path:["b"],value:{}},{op:"add",path:["b","d"],value:4}]},{comment:"test 7",obja:{a:4,b:[2,"foo"]},objb:{a:4,b:[2,"foo",["this","that"]]},expected:[{op:"add",path:["b"],value:[]},{op:"add",path:["b",2],value:["this","that"]}]}];for(const i of t){console.log(i.comment);const t=e.pxtc.jsonPatch.diff(i.obja,i.objb);n(t,i.expected)?console.log("succeeded"):(console.error("FAILED"),console.log("got",t),console.log("exp",i.expected))}},t.patchTests=function(){const t=[{comment:"test 1",obj:{a:"foo",b:[4,11]},patches:[{op:"remove",path:["b"]},{op:"replace",path:["a"],value:4},{op:"add",path:["c"],value:5}],expected:{a:4,c:5}},{comment:"test 2",obj:{a:4,b:[1,2,3]},patches:[{op:"replace",path:["a"],value:3},{op:"replace",path:["b",2],value:4},{op:"add",path:["b",3],value:9}],expected:{a:3,b:[1,2,4,9]}},{comment:"test 3",obj:{a:4,b:{c:3}},patches:[{op:"replace",path:["a"],value:5},{op:"remove",path:["b","c"]},{op:"add",path:["b","d"],value:4}],expected:{a:5,b:{d:4}}},{comment:"test 4",obj:{a:4},patches:[{op:"add",path:["b"],value:[]},{op:"add",path:["b",0],value:"foo"},{op:"add",path:["b",1],value:"bar"}],expected:{a:4,b:["foo","bar"]},validate:e=>e.b&&e.b.forEach}];for(const i of t){console.log(i.comment),e.pxtc.jsonPatch.patchInPlace(i.obj,i.patches);!n(i.obj,i.expected)||!i.validate||i.validate(i.obj)?console.log("succeeded"):i.expected&&(console.error("FAILED"),console.log("got",i.obj),console.log("exp",i.expected))}}}(t.tests||(t.tests={}))}(t.jsonPatch||(t.jsonPatch={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){e.perf||(e.perf={})}(pxt||(pxt={})),pxt.perf.report||(pxt.perf.report=()=>{}),pxt.perf.recordMilestone||(pxt.perf.recordMilestone=()=>{}),pxt.perf.measureStart||(pxt.perf.measureStart=()=>{}),pxt.perf.measureEnd||(pxt.perf.measureEnd=()=>{}),function(e){let t;e.U=pxtc.Util,e.Util=pxtc.Util;let n,i,s,r={};function o(n,i){/^csv-/.test(n)?e.setAppTargetVariant(n.replace(/^csv-*/,"")):e.appTarget&&(r[n]=i,e.U.jsonCopyFrom(e.appTarget.compile.switches,r),e.U.jsonCopyFrom(t.compile.switches,r))}function a(e,t,n){if(Array.isArray(e))return e.map((e=>a(e,t,n)));if("object"==typeof e){for(const i of Object.keys(e))e[i]=a(e[i],t,n);return e}return"string"==typeof e&&t.test(e)?n(e):e}function l(){let t=e.appTarget.compile;t||(t=e.appTarget.compile={isNative:!1,hasHex:!1,switches:{}}),t.hasHex&&(t.nativeType||(t.nativeType=pxtc.NATIVE_TYPE_THUMB)),t.switches||(t.switches={}),t.nativeType==pxtc.NATIVE_TYPE_VM&&(t.sourceMap=!0),e.U.jsonCopyFrom(t.switches,r),t.jsRefCounting=!1,t.useUF2||t.useELF||null!=t.noSourceInFlash||(t.noSourceInFlash=!0),void 0===t.utf8&&(t.utf8=!0),e.appTarget.appTheme||(e.appTarget.appTheme={}),e.appTarget.appTheme.embedUrl||(e.appTarget.appTheme.embedUrl=e.appTarget.appTheme.homeUrl);let n=e.appTarget.compileService;if(n&&n.yottaTarget&&!n.yottaBinary&&(n.yottaBinary="pxt-microbit-app-combined.hex"),e.appTarget=a(e.appTarget,/^@cdnUrl@/i,(t=>e.BrowserUtils.patchCdn(t))),Object.keys(e.appTarget.bundledpkgs).forEach((t=>{const n=e.appTarget.bundledpkgs[t],i=JSON.parse(n[e.CONFIG_NAME]);i.icon&&(i.icon=e.BrowserUtils.patchCdn(i.icon)),n[e.CONFIG_NAME]=e.Package.stringifyConfig(i)})),"undefined"!=typeof window){const t={"lockededitor=1":{appTheme:{lockedEditor:!0}},"hidemenu=1":{appTheme:{hideMenuBar:!0}}};e.appTarget.queryVariants&&e.Util.jsonCopyFrom(t,e.appTarget.queryVariants);const n=window.location.href;Object.keys(t).forEach((i=>{if(new RegExp(i,"i").exec(n)){let n=t[i];n&&e.U.jsonMergeFrom(e.appTarget,n)}}))}}function c(n=!1){e.perf.measureStart("reloadAppTargetVariant");const i=n?"":JSON.stringify(e.appTarget);if(e.appTarget=e.U.cloneTargetBundle(t),e.appTargetVariant){const t=e.appTarget.variants&&e.appTarget.variants[e.appTargetVariant];t?e.U.jsonMergeFrom(e.appTarget,t):e.U.userError(lf("Variant '{0}' not defined in pxtarget.json",e.appTargetVariant))}l(),!n&&e.onAppTargetChanged&&i!=JSON.stringify(e.appTarget)&&e.onAppTargetChanged(),e.perf.measureEnd("reloadAppTargetVariant")}function u(){return{relprefix:"/--",workerjs:"/worker.js",monacoworkerjs:"/monacoworker.js",gifworkerjs:"/gifjs/gif.worker.js",serviceworkerjs:"/serviceworker.js",typeScriptWorkerJs:"/tsworker.js",pxtVersion:"local",pxtRelId:"localRelId",pxtCdnUrl:"/cdn/",commitCdnUrl:"/cdn/",blobCdnUrl:"/blb/",cdnUrl:"/cdn/",targetUrl:"",targetVersion:"local",targetRelId:"",targetId:e.appTarget?e.appTarget.id:"",simUrl:"/sim/simulator.html",simserviceworkerUrl:"/simulatorserviceworker.js",simworkerconfigUrl:"/sim/workerConfig.js",partsUrl:"/sim/siminstructions.html"}}function d(){return s||(s=e.Cloud.downloadTargetConfigAsync().then((e=>e||{}),(e=>({})))),s}function h(t=null){return t||(t=e.appTarget.compile),t.nativeType==ts.pxtc.NATIVE_TYPE_VM?t.useESP?t.useUF2?ts.pxtc.BINARY_UF2:ts.pxtc.BINARY_ESP:ts.pxtc.BINARY_PXT64:t.useUF2&&!t.switches.rawELF?ts.pxtc.BINARY_UF2:t.useELF?ts.pxtc.BINARY_ELF:ts.pxtc.BINARY_HEX}e.setAppTarget=function(n){e.appTarget=n||{},l(),t=e.U.cloneTargetBundle(e.appTarget)},e.setBundledApiInfo=function(e){for(const t of Object.keys(e)){const n=e[t].apis.byQName;for(const e of Object.keys(n)){const t=n[e],i=e.lastIndexOf("."),s=t.pyQName,r=n[e]={kind:Math.abs(t.kind||7),qName:e,namespace:e.slice(0,i<0?0:i),name:e.slice(i+1),pyQName:s,pyName:s?s.slice(s.lastIndexOf(".")+1):void 0,fileName:"",attributes:t.attributes||{},retType:t.retType||"void",parameters:t.parameters?t.parameters.map((e=>({name:e.name,description:e.description||"",type:e.type||"number",initializer:e.initializer,default:e.default,options:e.options||{},isEnum:!!e.isEnum,handlerParameters:e.handlerParameters}))):null,extendsTypes:t.extendsTypes,snippet:t.kind&&t.kind<0?null:void 0,isInstance:!!t.isInstance,isReadOnly:!!t.isReadOnly},o=r.attributes;o.paramDefl||(o.paramDefl={}),o.callingConvention||(o.callingConvention=0),o.paramHelp||(o.paramHelp={}),o.jsDoc||(o.jsDoc=""),o._name=r.name.replace(/@.*/,"")}}n=e},e.getBundledApiInfo=function(){return n},e.savedAppTheme=function(){return t?t.appTheme:void 0},e.setCompileSwitch=o,e.setCompileSwitches=function(e){if(e)for(let t of e.split(/[\s,;:]+/))t&&("-"==t[0]?o(t.slice(1),!1):o(t,!0))},e.bundledSvg=function(t){if(!t)return;let n=i&&i[t];if(n)return n;if(!e.appTarget.simulator||!e.appTarget.simulator.dynamicBoardDefinition)return;i||(i={});const s=e.appTarget.bundledpkgs[t];if(!s)return;if(JSON.parse(s["pxt.json"]).core&&s["board.json"]){const n=JSON.parse(s["board.json"]);if(n&&n.visual&&n.visual.image){let r=n.visual.image;/^pkg:\/\//.test(r)&&(r=s[r.slice(6)]),i[t]=`data:image/svg+xml;base64,${ts.pxtc.encodeBase64(e.Util.toUTF8(r))}`}}return i[t]},e.replaceStringsInJsonBlob=a,e.reloadAppTargetVariant=c,e.setAppTargetVariant=function(t,n={}){e.debug(`app variant: ${t}`),(n.force||e.appTargetVariant!==t&&(e.appTargetVariant||t))&&(e.appTargetVariant=t,c(n.temporary))},e.setHwVariant=function(t,n){t=t.replace(/.*---/,""),/^[\w\-]+$/.test(t)?(e.hwVariant=t,e.hwName=n||t):(e.hwVariant=null,e.hwName=null),e.debug(`hwVariant: ${e.hwVariant} (${e.hwName})`)},e.hasHwVariants=function(){return!!e.appTarget.variants&&Object.keys(e.appTarget.bundledpkgs).some((e=>/^hw---/.test(e)))},e.getHwVariants=function(){return e.appTarget.variants?Object.keys(e.appTarget.bundledpkgs).filter((e=>/^hw---/.test(e))).map((t=>JSON.parse(e.appTarget.bundledpkgs[t][e.CONFIG_NAME]))).filter((t=>!!e.appTarget.appTheme.experimentalHw||!t.experimentalHw)):[]},e.options={},e.debug="undefined"!=typeof console&&console.debug?t=>{e.options.debug&&console.debug(t)}:()=>{},e.log="undefined"!=typeof console&&console.log?e=>{console.log(e)}:()=>{},e.reportException=function(e,t){if(console&&(console.error(e),t))try{console.log(t)}catch(e){}},e.reportError=function(t,n,i){if(console&&(console.error(`${t}: ${n}`),i))try{e.log(JSON.stringify(i,null,2))}catch(e){}},e.localWebConfig=u,e.getOnlineCdnUrl=function(){if(!e.webConfig)return null;let t=/^(https:\/\/[^\/]+)/.exec(e.webConfig.commitCdnUrl);return t?t[1]:null},e.setupWebConfig=function(t){t?e.webConfig=t:e.webConfig||(e.webConfig=u())},e.getEmbeddedScript=function(t){return e.U.lookup(e.appTarget.bundledpkgs||{},t)},e.targetConfigAsync=d,e.packagesConfigAsync=function(){return d().then((e=>e?e.packages:void 0))},e.CONFIG_NAME="pxt.json",e.SIMSTATE_JSON=".simstate.json",e.SERIAL_EDITOR_FILE="serial.txt",e.README_FILE="README.md",e.GITIGNORE_FILE=".gitignore",e.ASSETS_FILE="assets.json",e.CLOUD_ID="pxt/",e.BLOCKS_PROJECT_NAME="blocksprj",e.JAVASCRIPT_PROJECT_NAME="tsprj",e.PYTHON_PROJECT_NAME="pyprj",e.MAIN_BLOCKS="main.blocks",e.MAIN_TS="main.ts",e.MAIN_PY="main.py",e.DEFAULT_GROUP_NAME="other",e.TILEMAP_CODE="tilemap.g.ts",e.TILEMAP_JRES="tilemap.g.jres",e.IMAGES_CODE="images.g.ts",e.IMAGES_JRES="images.g.jres",e.TUTORIAL_CODE_START="_onCodeStart.ts",e.TUTORIAL_CODE_STOP="_onCodeStop.ts",e.TUTORIAL_INFO_FILE="tutorial-info-cache.json",e.TUTORIAL_CUSTOM_TS="tutorial.custom.ts",e.BREAKPOINT_TABLET=991,e.PALETTES_FILE="_palettes.json",e.HISTORY_FILE="_history",e.outputName=h,e.isOutputText=function(e=null){return h(e)==ts.pxtc.BINARY_HEX}}(pxt||(pxt={})),function(e){!function(t){const n="this";let i;function s(){if(i={device_while:{name:e.Util.lf("a loop that repeats while the condition is true"),tooltip:e.Util.lf("Run the same sequence of actions while the condition is met."),url:"/blocks/loops/while",category:"loops",block:{message0:e.Util.lf("while %1"),appendField:e.Util.lf("{id:while}do")}},pxt_controls_for:{name:e.Util.lf("a loop that repeats the number of times you say"),tooltip:e.Util.lf("Have the variable '{0}' take on the values from 0 to the end number, counting by 1, and do the specified blocks."),url:"/blocks/loops/for",category:"loops",block:{message0:e.Util.lf("for %1 from 0 to %2"),variable:e.Util.lf("{id:var}index"),appendField:e.Util.lf("{id:for}do")}},controls_simple_for:{name:e.Util.lf("a loop that repeats the number of times you say"),tooltip:e.Util.lf("Have the variable '{0}' take on the values from 0 to the end number, counting by 1, and do the specified blocks."),url:"/blocks/loops/for",category:"loops",block:{message0:e.Util.lf("for %1 from 0 to %2"),variable:e.Util.lf("{id:var}index"),appendField:e.Util.lf("{id:for}do")}},pxt_controls_for_of:{name:e.Util.lf("a loop that repeats for each value in an array"),tooltip:e.Util.lf("Have the variable '{0}' take the value of each item in the array one by one, and do the specified blocks."),url:"/blocks/loops/for-of",category:"loops",block:{message0:e.Util.lf("for element %1 of %2"),variable:e.Util.lf("{id:var}value"),appendField:e.Util.lf("{id:for_of}do")}},controls_for_of:{name:e.Util.lf("a loop that repeats for each value in an array"),tooltip:e.Util.lf("Have the variable '{0}' take the value of each item in the array one by one, and do the specified blocks."),url:"/blocks/loops/for-of",category:"loops",block:{message0:e.Util.lf("for element %1 of %2"),variable:e.Util.lf("{id:var}value"),appendField:e.Util.lf("{id:for_of}do")}},math_op2:{name:e.Util.lf("minimum or maximum of 2 numbers"),tooltip:{min:e.Util.lf("smaller value of 2 numbers"),max:e.Util.lf("larger value of 2 numbers")},url:"/blocks/math",operators:{op:["min","max"]},category:"math"},math_op3:{name:e.Util.lf("absolute number"),tooltip:e.Util.lf("absolute value of a number"),url:"/reference/math",category:"math",block:{message0:e.Util.lf("absolute of %1")}},math_number:{name:e.Util.lf("{id:block}number"),url:"/types/number",category:"math",tooltip:e.appTarget&&e.appTarget.compile?e.Util.lf("a decimal number"):e.Util.lf("an integer number")},math_integer:{name:e.Util.lf("{id:block}number"),url:"/types/number",category:"math",tooltip:e.Util.lf("an integer number")},math_whole_number:{name:e.Util.lf("{id:block}number"),url:"/types/number",category:"math",tooltip:e.Util.lf("a whole number")},math_number_minmax:{name:e.Util.lf("{id:block}number"),url:"/blocks/math",category:"math"},math_arithmetic:{name:e.Util.lf("arithmetic operation"),url:"/blocks/math",tooltip:{ADD:e.Util.lf("Return the sum of the two numbers."),MINUS:e.Util.lf("Return the difference of the two numbers."),MULTIPLY:e.Util.lf("Return the product of the two numbers."),DIVIDE:e.Util.lf("Return the quotient of the two numbers."),POWER:e.Util.lf("Return the first number raised to the power of the second number.")},operators:{OP:["ADD","MINUS","MULTIPLY","DIVIDE","POWER"]},category:"math",block:{MATH_ADDITION_SYMBOL:e.Util.lf("{id:op}+"),MATH_SUBTRACTION_SYMBOL:e.Util.lf("{id:op}-"),MATH_MULTIPLICATION_SYMBOL:e.Util.lf("{id:op}×"),MATH_DIVISION_SYMBOL:e.Util.lf("{id:op}/"),MATH_POWER_SYMBOL:e.Util.lf("{id:op}**")}},math_modulo:{name:e.Util.lf("division remainder"),tooltip:e.Util.lf("Return the remainder from dividing the two numbers."),url:"/blocks/math",category:"math",block:{MATH_MODULO_TITLE:e.Util.lf("remainder of %1 / %2")}},math_js_op:{name:e.Util.lf("math function"),tooltip:{sqrt:e.Util.lf("Returns the square root of the argument"),sin:e.Util.lf("Returns the sine of the argument"),cos:e.Util.lf("Returns the cosine of the argument"),acos:e.Util.lf("Returns the arccosine of the argument"),asine:e.Util.lf("Returns the arcsine of the argument"),tan:e.Util.lf("Returns the tangent of the argument"),atan2:e.Util.lf("Returns the arctangent of the quotient of the two arguments"),idiv:e.Util.lf("Returns the integer portion of the division operation on the two arguments"),imul:e.Util.lf("Returns the integer portion of the multiplication operation on the two arguments")},url:"/blocks/math",operators:{OP:["sqrt","sin","cos","tan","atan2","idiv","imul"]},category:"math",block:{sqrt:e.Util.lf("{id:op}square root"),sin:e.Util.lf("{id:op}sin"),cos:e.Util.lf("{id:op}cos"),asin:e.Util.lf("{id:op}asin"),acos:e.Util.lf("{id:op}acos"),tan:e.Util.lf("{id:op}tan"),atan2:e.Util.lf("{id:op}atan2"),idiv:e.Util.lf("{id:op}integer /"),imul:e.Util.lf("{id:op}integer ×")}},math_js_round:{name:e.Util.lf("rounding functions"),tooltip:{round:e.Util.lf("Increases the argument to the next higher whole number if its fractional part is more than one half"),ceil:e.Util.lf("Increases the argument to the next higher whole number"),floor:e.Util.lf("Decreases the argument to the next lower whole number"),trunc:e.Util.lf("Removes the fractional part of the argument")},url:"/blocks/math",operators:{OP:["round","ceil","floor","trunc"]},category:"math",block:{round:e.Util.lf("{id:op}round"),ceil:e.Util.lf("{id:op}ceiling"),floor:e.Util.lf("{id:op}floor"),trunc:e.Util.lf("{id:op}truncate")}},variables_change:{name:e.Util.lf("update the value of a number variable"),tooltip:e.Util.lf("Changes the value of the variable by this amount"),url:"/blocks/variables/change",category:"variables",block:{message0:e.Util.lf("change %1 by %2")}},controls_repeat_ext:{name:e.Util.lf("a loop that repeats and increments an index"),tooltip:e.Util.lf("Do some statements several times."),url:"/blocks/loops/repeat",category:"loops",block:{CONTROLS_REPEAT_TITLE:e.Util.lf("repeat %1 times"),CONTROLS_REPEAT_INPUT_DO:e.Util.lf("{id:repeat}do")}},variables_get:{name:e.Util.lf("get the value of a variable"),tooltip:e.Util.lf("Returns the value of this variable."),url:"/blocks/variables",category:"variables",block:{VARIABLES_GET_CREATE_SET:e.Util.lf("Create 'set %1'")}},variables_get_reporter:{name:e.Util.lf("get the value of a variable"),tooltip:e.Util.lf("Returns the value of this variable."),url:"/blocks/variables",category:"variables",block:{VARIABLES_GET_CREATE_SET:e.Util.lf("Create 'set %1'")}},variables_set:{name:e.Util.lf("assign the value of a variable"),tooltip:e.Util.lf("Sets this variable to be equal to the input."),url:"/blocks/variables/assign",category:"variables",block:{VARIABLES_SET:e.Util.lf("set %1 to %2")}},controls_if:{name:e.Util.lf("a conditional statement"),tooltip:{CONTROLS_IF_TOOLTIP_1:e.Util.lf("If a value is true, then do some statements."),CONTROLS_IF_TOOLTIP_2:e.Util.lf("If a value is true, then do the first block of statements. Otherwise, do the second block of statements."),CONTROLS_IF_TOOLTIP_3:e.Util.lf("If the first value is true, then do the first block of statements. Otherwise, if the second value is true, do the second block of statements."),CONTROLS_IF_TOOLTIP_4:e.Util.lf("If the first value is true, then do the first block of statements. Otherwise, if the second value is true, do the second block of statements. If none of the values are true, do the last block of statements.")},tooltipSearch:"CONTROLS_IF_TOOLTIP_2",url:"/blocks/logic/if",category:"logic",block:{CONTROLS_IF_MSG_IF:e.Util.lf("{id:logic}if"),CONTROLS_IF_MSG_THEN:e.Util.lf("{id:logic}then"),CONTROLS_IF_MSG_ELSE:e.Util.lf("{id:logic}else"),CONTROLS_IF_MSG_ELSEIF:e.Util.lf("{id:logic}else if")}},lists_create_with:{name:e.Util.lf("create an array"),tooltip:e.Util.lf("Creates a new array."),url:"/reference/arrays/create",category:"arrays",blockTextSearch:"LISTS_CREATE_WITH_INPUT_WITH",block:{LISTS_CREATE_EMPTY_TITLE:e.Util.lf("empty array"),LISTS_CREATE_WITH_INPUT_WITH:e.Util.lf("array of"),LISTS_CREATE_WITH_CONTAINER_TITLE_ADD:e.Util.lf("array"),LISTS_CREATE_WITH_ITEM_TITLE:e.Util.lf("value")}},lists_length:{name:e.Util.lf("array length"),tooltip:e.Util.lf("Returns the number of items in an array."),url:"/reference/arrays/length",category:"arrays",block:{LISTS_LENGTH_TITLE:e.Util.lf("length of array %1")}},lists_index_get:{name:e.Util.lf("get a value in an array"),tooltip:e.Util.lf("Returns the value at the given index in an array."),url:"/reference/arrays/get",category:"arrays",block:{message0:e.Util.lf("%1 get value at %2")}},lists_index_set:{name:e.Util.lf("set a value in an array"),tooltip:e.Util.lf("Sets the value at the given index in an array"),url:"/reference/arrays/set",category:"arrays",block:{message0:e.Util.lf("%1 set value at %2 to %3")}},logic_compare:{name:e.Util.lf("comparing two numbers"),tooltip:{LOGIC_COMPARE_TOOLTIP_EQ:e.Util.lf("Return true if both inputs equal each other."),LOGIC_COMPARE_TOOLTIP_NEQ:e.Util.lf("Return true if both inputs are not equal to each other."),LOGIC_COMPARE_TOOLTIP_LT:e.Util.lf("Return true if the first input is smaller than the second input."),LOGIC_COMPARE_TOOLTIP_LTE:e.Util.lf("Return true if the first input is smaller than or equal to the second input."),LOGIC_COMPARE_TOOLTIP_GT:e.Util.lf("Return true if the first input is greater than the second input."),LOGIC_COMPARE_TOOLTIP_GTE:e.Util.lf("Return true if the first input is greater than or equal to the second input.")},url:"/blocks/logic/boolean",category:"logic",block:{search:"= ≠ < ≤ > ≥"}},logic_operation:{name:e.Util.lf("boolean operation"),tooltip:{LOGIC_OPERATION_TOOLTIP_AND:e.Util.lf("Return true if both inputs are true."),LOGIC_OPERATION_TOOLTIP_OR:e.Util.lf("Return true if at least one of the inputs is true.")},url:"/blocks/logic/boolean",category:"logic",block:{LOGIC_OPERATION_AND:e.Util.lf("{id:op}and"),LOGIC_OPERATION_OR:e.Util.lf("{id:op}or")}},logic_negate:{name:e.Util.lf("logical negation"),tooltip:e.Util.lf("Returns true if the input is false. Returns false if the input is true."),url:"/blocks/logic/boolean",category:"logic",block:{LOGIC_NEGATE_TITLE:e.Util.lf("not %1")}},logic_boolean:{name:e.Util.lf("a `true` or `false` value"),tooltip:e.Util.lf("Returns either true or false."),url:"/blocks/logic/boolean",category:"logic",block:{LOGIC_BOOLEAN_TRUE:e.Util.lf("{id:boolean}true"),LOGIC_BOOLEAN_FALSE:e.Util.lf("{id:boolean}false")}},text:{name:e.Util.lf("a piece of text"),tooltip:e.Util.lf("A letter, word, or line of text."),url:"/types/string",category:"text",block:{search:e.Util.lf("a piece of text")}},text_length:{name:e.Util.lf("number of characters in the string"),tooltip:e.Util.lf("Returns the number of letters (including spaces) in the provided text."),url:"/reference/text/length",category:"text",block:{TEXT_LENGTH_TITLE:e.Util.lf("length of %1")}},text_join:{name:e.Util.lf("join items to create text"),tooltip:e.Util.lf("Create a piece of text by joining together any number of items."),url:"/reference/text/join",category:"text",block:{TEXT_JOIN_TITLE_CREATEWITH:e.Util.lf("join")}},procedures_defnoreturn:{name:e.Util.lf("define the function"),tooltip:e.Util.lf("Create a function."),url:"/types/function/define",category:"functions",block:{PROCEDURES_DEFNORETURN_TITLE:e.Util.lf("function"),PROCEDURE_ALREADY_EXISTS:e.Util.lf("A function named '%1' already exists.")}},procedures_callnoreturn:{name:e.Util.lf("call the function"),tooltip:e.Util.lf("Call the user-defined function."),url:"/types/function/call",category:"functions",block:{PROCEDURES_CALLNORETURN_TITLE:e.Util.lf("call function")}},function_return:{name:e.Util.lf("return a value from within a function"),tooltip:e.Util.lf("Return a value from within a user-defined function."),url:"/types/function/return",category:"functions",block:{message_with_value:e.Util.lf("return %1"),message_no_value:e.Util.lf("return")}},function_definition:{name:e.Util.lf("define the function"),tooltip:e.Util.lf("Create a function."),url:"/types/function/define",category:"functions",block:{FUNCTIONS_EDIT_OPTION:e.Util.lf("Edit Function")}},function_call:{name:e.Util.lf("call the function"),tooltip:e.Util.lf("Call the user-defined function."),url:"/types/function/call",category:"functions",block:{FUNCTIONS_CALL_TITLE:e.Util.lf("call"),FUNCTIONS_GO_TO_DEFINITION_OPTION:e.Util.lf("Go to Definition")}},function_call_output:{name:e.Util.lf("call the function with a return value"),tooltip:e.Util.lf("Call the user-defined function with a return value."),url:"/types/function/call",category:"functions",block:{}}},i[pxtc.ON_START_TYPE]={name:e.Util.lf("on start event"),tooltip:e.Util.lf("Run code when the program starts"),url:"/blocks/on-start",category:"loops",block:{message0:e.Util.lf("on start %1 %2")}},i[pxtc.PAUSE_UNTIL_TYPE]={name:e.Util.lf("pause until"),tooltip:e.Util.lf("Pause execution of code until the given boolean expression is true"),url:"/blocks/pause-until",category:"loops",block:{message0:e.Util.lf("pause until %1")}},i[pxtc.TS_BREAK_TYPE]={name:e.Util.lf("break"),tooltip:e.Util.lf("Break out of the current loop or switch"),url:"/blocks/loops/break",category:"loops",block:{message0:e.Util.lf("break")}},i[pxtc.TS_CONTINUE_TYPE]={name:e.Util.lf("continue"),tooltip:e.Util.lf("Skip current iteration and continues with the next iteration in the loop"),url:"/blocks/loops/continue",category:"loops",block:{message0:e.Util.lf("continue")}},e.blocks.showBlockIdInTooltip)for(const e of Object.keys(i)){const t=i[e].tooltip;if("object"==typeof t&&null!==t)for(const n in t)t.hasOwnProperty(n)&&(i[e].tooltip[n]=`${t[n]} (id: ${e})`);else i[e].tooltip=`${i[e].tooltip} (id: ${e})`}}t.showBlockIdInTooltip=!1,t.requirePxtBlockly=()=>{},t.requireBlockly=()=>{},t.registerFieldEditor=()=>{},t.MATH_FUNCTIONS={unary:["sqrt","sin","cos","tan","asin","acos"],binary:["atan2"],infix:["idiv","imul"]},t.ROUNDING_FUNCTIONS=["round","ceil","floor","trunc"],t.builtinFunctionInfo={"Math.abs":{blockId:"math_op3",params:["x"]},"Math.min":{blockId:"math_op2",params:["x","y"]},"Math.max":{blockId:"math_op2",params:["x","y"]}},t.normalizeBlock=function(t,n=e.log){if(!t)return t;let i=t.replace(/(?:^|[^\\])([%$])\s+/g,"$1");return i!=t&&(n(`block has extra spaces: ${t}`),t=i),i=(t=i).replace(/([%$]\w+)\s*=\s*(\w+)/,"$1=$2"),i!=t&&(n(`block has space between %name and = : ${t}`),t=i),i=i.replace(/\s*\|\s*/g,"|"),i},t.compileInfo=function(e){const i={parameters:[],actualNameToParam:{},definitionNameToParam:{},handlerArgs:[]},s=!(1!=e.kind&&2!=e.kind||e.attributes.defaultInstance||e.isStatic),r=!!e.attributes._def,o=r?e.attributes._def.parameters.slice(0):void 0,a=r?o.length:e.parameters?e.parameters.length:0,l=t.builtinFunctionInfo[e.qName];r&&e.attributes._expandedDef&&o.push(...e.attributes._expandedDef.parameters);const c={},u=o?o.filter((e=>!e.ref||(c[e.name]=e,!1))):[];if(s&&r&&o.length){const t=c.this||o[0],s=t.name,r=!t.shadowBlockId||"variables_get"===t.shadowBlockId;let a=e.attributes.paramDefl[s]||e.attributes.paramDefl.this;r&&(a=t.varName||a),i.thisParameter={actualName:n,definitionName:s,shadowBlockId:t.shadowBlockId,type:e.namespace,defaultValue:a,definitionIndex:o.indexOf(t),fieldEditor:d(s,n),fieldOptions:h(s,n),shadowOptions:p(s,n)}}if(e.parameters){let t=s&&!c.this?1:0;e.parameters.forEach(((e,n)=>{let s;if(c[e.name]?s=c[e.name]:t<u.length&&(s=u[t],++t),s||!r){let r;e.options&&e.options.min&&e.options.max&&(r={min:e.options.min.value,max:e.options.max.value});const c=s?s.name:l?l.params[t++]:e.name,u=s&&("variables_get"===s.shadowBlockId||"lists_create_with"==s.shadowBlockId);i.parameters.push({actualName:e.name,type:e.type,defaultValue:u&&s.varName||e.default,definitionName:c,definitionIndex:s?o.indexOf(s):n,shadowBlockId:s&&s.shadowBlockId,isOptional:!!o&&o.indexOf(s)>=a,fieldEditor:d(c,e.name),fieldOptions:h(c,e.name),shadowOptions:p(c,e.name),range:r})}e.handlerParameters&&e.handlerParameters.forEach((e=>{i.handlerArgs.push({name:e.name,type:e.type,inBlockDef:!!o&&o.some((t=>t.ref&&t.name===e.name))})}))}))}return i.parameters.forEach((e=>{i.actualNameToParam[e.actualName]=e,i.definitionNameToParam[e.definitionName]=e})),i;function d(t,n){return e.attributes.paramFieldEditor&&(e.attributes.paramFieldEditor[t]||e.attributes.paramFieldEditor[n])}function h(t,n){return e.attributes.paramFieldEditorOptions&&(e.attributes.paramFieldEditorOptions[t]||e.attributes.paramFieldEditorOptions[n])}function p(t,n){return e.attributes.paramShadowOptions&&(e.attributes.paramShadowOptions[t]||e.attributes.paramShadowOptions[n])}},t.hasHandler=function(e){return e.parameters&&e.parameters.some((e=>{var t,n;return"() => void"==e.type||"Action"==e.type||!!(null===(t=e.properties)||void 0===t?void 0:t.length)||!!(null===(n=e.handlerParameters)||void 0===n?void 0:n.length)}))},t.getHelpUrl=function(t){if(t.attributes.help){const e=t.attributes.help.replace(/^\//,"");if(/^github:/.test(e))return e;if("none"!==e)return"/reference/"+e}else if(t.pkg&&!e.appTarget.bundledpkgs[t.pkg]){let e=t.qName.toLowerCase().split(".");return e[0]==t.pkg&&e.shift(),`/pkg/${t.pkg}#${encodeURIComponent(e.join("-"))}`}},t.reporterTypeForArgType=function(e){let t="argument_reporter_custom";return"boolean"!==e&&"number"!==e&&"string"!==e||(t=`argument_reporter_${e}`),/^(?:Array<(?:.+)>)|(?:(?:.+)\[\])$/.test(e)&&(t="argument_reporter_array"),t},t.defaultIconForArgType=function(e=""){switch(e){case"number":return"calculator";case"string":return"text width";case"boolean":return"random";case"Array":return"list";default:return"align justify"}},t.parseFields=function(e){return e.split("|").map(((e,t)=>{let n=/([^%]*)\s*%([a-zA-Z0-9_]+)/.exec(e);if(!n)return{n:e,ni:t};let i=n[1];return i&&(i=i.trim()),{n:e,ni:t,pre:i,p:n[2]}}))},t.blockDefinitions=function(){return i||s(),i},t.getBlockDefinition=function(e){return i||s(),i[e]},t.initInContextTranslationAsync=async function(){i||s();const t={};return await Promise.all(e.Util.values(i).filter((e=>e.block)).map((async n=>{const i=Object.keys(n.block);n.translationIds=e.Util.values(n.block),await Promise.all(i.map((async i=>{const s=await e.crowdin.inContextLoadAsync(n.block[i]);n.block[i]=s,/^[A-Z_]+$/.test(i)&&(t[i]=s)})))}))),t}}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(t){function n(){return"undefined"!=typeof navigator}function i(){return n()&&/(Win32|Win64|WOW64)/i.test(navigator.platform)}function s(){return n()&&/mobi/i.test(navigator.userAgent)}function r(){return n()&&/Mac/i.test(navigator.platform)}function o(){return!!navigator&&/Linux/i.test(navigator.platform)}function a(){return n()&&/arm/i.test(navigator.platform)}function l(){return n()&&/Edge/i.test(navigator.userAgent)}function c(){return n()&&/Trident/i.test(navigator.userAgent)}function u(){return!l()&&!c()&&!!navigator&&(/Chrome/i.test(navigator.userAgent)||/Chromium/i.test(navigator.userAgent))}function d(){return!u()&&!l()&&!!navigator&&/(Macintosh|Safari|iPod|iPhone|iPad)/i.test(navigator.userAgent)}function h(){return!d()&&!!navigator&&(/Firefox/i.test(navigator.userAgent)||/Seamonkey/i.test(navigator.userAgent))}function p(){return n()&&/Opera|OPR/i.test(navigator.userAgent)}function f(){return n()&&/Midori/i.test(navigator.userAgent)}function m(){return n()&&/Epiphany/i.test(navigator.userAgent)}function g(){return"undefined"!=typeof window&&("ontouchstart"in window||navigator&&navigator.maxTouchPoints>0)}function b(){return"undefined"!=typeof window&&!!window.pxtElectron}function y(){return"undefined"!=typeof window&&!!window.ipcRenderer}function v(){return b()||y()}function w(t){var n;try{return"undefined"!=typeof window&&/^http:\/\/(localhost|127\.0\.0\.1|192\.168\.\d+\.\d+):\d+\//.test(window.location.href)&&(t||!/nolocalhost=1/.test(window.location.href))&&!(null===(n=null==e?void 0:e.webConfig)||void 0===n?void 0:n.isStatic)}catch(e){return!1}}function k(){return"undefined"!=typeof window&&!!window.PointerEvent}function x(){return i()?"windows":r()?"mac":o()&&a()?"rpi":o()?"linux":"unknown"}function A(){return l()?"edge":m()?"epiphany":f()?"midori":p()?"opera":c()?"ie":u()?"chrome":d()?"safari":h()?"firefox":"unknown"}function E(){if(!n())return null;let e=[];return p()&&(e=/(Opera|OPR)\/([0-9\.]+)/i.exec(navigator.userAgent)),m()?e=/Epiphany\/([0-9\.]+)/i.exec(navigator.userAgent):f()?e=/Midori\/([0-9\.]+)/i.exec(navigator.userAgent):d()?(e=/Version\/([0-9\.]+)/i.exec(navigator.userAgent),e||(e=/(Macintosh|iPod( touch)?|iPhone|iPad); (CPU|Intel).*?OS (X )?(\d+)/i.exec(navigator.userAgent))):e=u()?/(Chrome|Chromium)\/([0-9\.]+)/i.exec(navigator.userAgent):l()?/Edge\/([0-9\.]+)/i.exec(navigator.userAgent):c()?/(MSIE |rv:)([0-9\.]+)/i.exec(navigator.userAgent):/(Firefox|Seamonkey)\/([0-9\.]+)/i.exec(navigator.userAgent),e&&0!=e.length?e[e.length-1]:null}t.isDocumentVisible=function(){return"undefined"!=typeof window&&"visible"===document.visibilityState},t.isIFrame=function(){try{return window&&window.self!==window.top}catch(e){return!0}},t.hasNavigator=n,t.hasWindow=function(){return"undefined"!=typeof window},t.isWindows=i,t.isWindows10=function(){return n()&&/(Win32|Win64|WOW64)/i.test(navigator.platform)&&/Windows NT 10/i.test(navigator.userAgent)},t.isMobile=s,t.isIOS=function(){return n()&&(/iPad|iPhone|iPod/.test(navigator.userAgent)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1)},t.isAndroid=function(){return n()&&/android/i.test(navigator.userAgent)},t.isMac=r,t.isLinux=o,t.isARM=a,t.isEdge=l,t.isChromiumEdge=function(){return n()&&/Edg\//i.test(navigator.userAgent)},t.isIE=c,t.isChrome=u,t.isSafari=d,t.isFirefox=h,t.isOpera=p,t.isMidori=f,t.isEpiphany=m,t.isTouchEnabled=g,t.isPxtElectron=b,t.isIpcRenderer=y,t.isElectron=v,t.isWinRT=()=>"undefined"!=typeof Windows,t.isLocalHost=w,t.isLocalHostDev=function(){return w()&&!v()},t.isSkillmapEditor=function(){try{return/skill(?:s?)Map=1/.test(window.location.href)}catch(e){return!1}},t.isTabletSize=function(){return(null===window||void 0===window?void 0:window.innerWidth)<=e.BREAKPOINT_TABLET},t.isComputerSize=function(){return(null===window||void 0===window?void 0:window.innerWidth)>e.BREAKPOINT_TABLET},t.noSharedLocalStorage=function(){try{return/nosharedlocalstorage/i.test(window.location.href)}catch(e){return!1}},t.useOldTutorialLayout=function(){var t,n;if(null===(n=null===(t=e.appTarget)||void 0===t?void 0:t.appTheme)||void 0===n?void 0:n.legacyTutorial)return!0;try{return/tutorialview=old/.test(window.location.href)}catch(e){return!1}},t.hasPointerEvents=k,t.os=x,t.browser=A,t.browserVersion=E;let T=!1;function S(){return s()&&d()&&!/downloadWindowOpen=0/i.test(window.location.href)}function C(t,n,i){const r=S(),o=E(),a=parseInt(o||"0");if(r)i?i.location.href=t:window.open(t,"_self");else if(e.BrowserUtils.isSafari()&&(a<10||0==o.indexOf("10.0")||s())){let n=document.getElementById("downloader");n||(e.debug("injecting downloader iframe"),n=document.createElement("iframe"),n.id="downloader",n.style.position="absolute",n.style.right="0",n.style.bottom="0",n.style.zIndex="-1",n.style.width="1px",n.style.height="1px",document.body.appendChild(n)),n.src=t}else if(/^data:/i.test(t)&&(e.BrowserUtils.isEdge()||e.BrowserUtils.isIE())){let i=atob(t.split(",")[1]),s=e.Util.stringToUint8Array(i),r=new Blob([s],{type:"img/png"});window.navigator.msSaveOrOpenBlob(r,n)}else{let e=window.document.createElement("a");"string"==typeof e.download?(e.href=t,e.download=n,document.body.appendChild(e),e.click(),document.body.removeChild(e)):document.location.href=t}}function I(t,n){let i="data";s()&&d()&&e.appTarget.appTheme.mobileSafariDownloadProtocol&&(i=e.appTarget.appTheme.mobileSafariDownloadProtocol);const r=/downloadProtocol=([a-z0-9:/?]+)/i.exec(window.location.href);r&&(i=r[1]);return i+":"+n+";base64,"+t}function _(t,n,i={}){var s;e.debug("trigger download");const{contentType:r="application/octet-stream",userContextWindow:o,onError:a,maintainObjectURL:l}=i,c=null===(s=window.URL)||void 0===s?void 0:s.createObjectURL,u=e.appTarget.appTheme.disableBlobObjectDownload;let d;try{if(c&&!u){const i=c(new Blob([e.Util.stringToUint8Array(atob(t))],{type:r}));C(i,n,o),l?d=i:window.setTimeout((()=>window.URL.revokeObjectURL(d)),0)}else d=I(t,n),C(d,n,o)}catch(t){a&&a(t),e.debug("saving failed")}return d}function P(e){const t=document.createElement("img");return new Promise(((n,i)=>{t.onload=()=>n(t),t.onerror=()=>n(void 0),t.crossOrigin="anonymous",t.src=e}))}t.isBrowserSupported=function(){var t,n;if(!navigator)return!0;if(/bot|crawler|spider|crawling/i.test(navigator.userAgent))return!0;const i=(null===(t=e.appTarget)||void 0===t?void 0:t.unsupportedBrowsers)||(null===(n=window.pxtTargetBundle)||void 0===n?void 0:n.unsupportedBrowsers);if(null==i?void 0:i.some((e=>e.id==A())))return!1;const s=E(),r=parseInt(s||"0"),c=u()&&r>=38,g=h()&&r>=31,b=l(),y=d()&&r>=9,v=p()&&u()&&r>=21;let w=c||g||b||y||v;const k=f()||o()&&a()&&m();return w=w&&!k,w=w||/anybrowser=(true|1)/.test(window.location.href),T||(e.log(`Browser: ${A()} ${s} on ${x()}`),w||e.tickEvent("browser.unsupported",{useragent:navigator.userAgent}),T=!0),w},t.devicePixelRatio=function(){if("undefined"==typeof window||!window.screen)return 1;const e=window.screen.systemXDPI,t=window.screen.logicalXDPI;return void 0!==e&&void 0!==t&&e>t?e/t:window&&void 0!==window.devicePixelRatio?window.devicePixelRatio:1},t.browserDownloadBinText=function(e,t,n){return _(ts.pxtc.encodeBase64(e),t,n)},t.browserDownloadText=function(t,n,i){return _(ts.pxtc.encodeBase64(e.Util.toUTF8(t)),n,i)},t.isBrowserDownloadInSameWindow=S,t.isBrowserDownloadWithinUserContext=function(){const e=E(),t=parseInt(e||"0");return s()&&d()&&t>=11||/downloadUserContext=1/i.test(window.location.href)},t.browserDownloadDataUri=C,t.browserDownloadUInt8Array=function(t,n,i){return _(ts.pxtc.encodeBase64(e.Util.uint8ArrayToString(t)),n,i)},t.toDownloadDataUri=I,t.browserDownloadBase64=_,t.loadImageAsync=P,t.loadCanvasAsync=function(e){return P(e).then((e=>{const t=document.createElement("canvas");t.width=e.width,t.height=e.height;return t.getContext("2d").drawImage(e,0,0),t}))},t.scaleImageData=function(e,t){const n=document.createElement("canvas"),i=document.createElement("canvas");n.width=e.width,n.height=e.height,i.width=e.width*t,i.height=e.height*t;const s=n.getContext("2d"),r=i.getContext("2d");return s.putImageData(e,0,0),r.imageSmoothingEnabled=!1,r.scale(t,t),r.drawImage(n,0,0),r.getImageData(0,0,e.width*t,e.height*t)},t.imageDataToPNG=function(e,t=1){if(!e)return;const n=document.createElement("canvas"),i=document.createElement("canvas");n.width=e.width,n.height=e.height,i.width=e.width*t,i.height=e.height*t;const s=n.getContext("2d"),r=i.getContext("2d");return s.putImageData(e,0,0),r.imageSmoothingEnabled=!1,r.scale(t,t),r.drawImage(n,0,0),i.toDataURL("image/png")};const U=1e6;function O(t){if(/^https?:\/\//i.test(t))return t;const n=(window.MonacoPaths||{})[t];return n||(e.U.startsWith(t,e.webConfig.commitCdnUrl)?t:e.webConfig.commitCdnUrl+t)}t.encodeToPngAsync=function(t,n){const{width:i,height:s,pixelDensity:r=4,maxSize:o=U,text:a}=n||{};return new Promise(((n,l)=>{const c=new Image;c.onload=function(){const t=document.createElement("canvas"),l=t.getContext("2d");t.width=(i||c.width)*r,t.height=(s||c.height)*r,a&&(l.fillStyle="#fff",l.fillRect(0,0,t.width,t.height)),l.drawImage(c,0,0,i,s,0,0,t.width,t.height);let u=t.toDataURL("image/png");for(;u.length>o;)t.width=t.width/2>>0,t.height=t.height/2>>0,e.debug(`screenshot size ${u.length}b, shrinking to ${t.width}x${t.height}`),l.drawImage(c,0,0,i,s,0,0,t.width,t.height),u=t.toDataURL("image/png");if(a){e.lzmaCompressAsync(a).then((i=>{const s=e.Util.encodeBlobAsync(t,i);n(s.toDataURL("image/png"))}))}else n(u)},c.onerror=t=>{e.reportError("png","png rendering failed"),n(void 0)},c.src=t}))},t.resolveCdnUrl=O,t.loadStyleAsync=function(t,n){n&&(t="rtl"+t);const i="style-"+t;if(document.getElementById(i))return Promise.resolve();const s=O(t),r=e.Util.toArray(document.head.getElementsByTagName("link")).filter((e=>e.getAttribute("href")==s))[0];return r?(r.id||(r.id=i),Promise.resolve()):new Promise(((e,t)=>{const n=document.createElement("link");n.href=s,n.rel="stylesheet",n.type="text/css",n.id=i,n.addEventListener("load",(()=>e())),n.addEventListener("error",(e=>t(e))),document.head.appendChild(n)}))};let N,R,M,D={};function L(e,t){if(!e)return t;if(!t)return e;return(e.indexOf("/")==e.length-1?e.substring(0,e.length-1):e)+"/"+(0==t.indexOf("/")?t.substring(1):t)}function F(){const e=n()&&window.navigator;return e&&e.storage&&e.storage.estimate?e.storage.estimate():Promise.resolve({})}t.loadScriptAsync=function(t){const n=O(t);let i=D[n];return i||(i=D[n]=new Promise(((t,i)=>{e.debug(`script: loading ${n}`);const s=document.createElement("script");s.type="text/javascript",s.addEventListener("load",(()=>t())),s.addEventListener("error",(e=>{delete D[n],i(e)})),s.src=n,s.async=!0,document.body.appendChild(s)}))),i},t.loadAjaxAsync=function(e){return new Promise(((t,n)=>{let i=new XMLHttpRequest;i.onreadystatechange=function(){i.readyState==XMLHttpRequest.DONE&&(200==i.status?t(i.responseText):n(i.status))},i.open("GET",e,!0),i.send()}))},t.loadBlocklyAsync=function(){if(!N){e.debug("blockly: delay load");let t=e.BrowserUtils.loadStyleAsync("blockly.css",ts.pxtc.Util.isUserLanguageRtl());t=t.then((()=>{e.debug("blockly: loaded")})),N=t}return N},t.patchCdn=function(t){if(!t)return t;const n=e.getOnlineCdnUrl();return n?t.replace("@cdnUrl@",n):t.replace(/@cdnUrl@\/(blob|commit)\/[a-f0-9]{40}\//,"./")},t.initTheme=function(){const t=e.appTarget.appTheme;if(t&&t.accentColor){let e=document.createElement("style");e.type="text/css",e.appendChild(document.createTextNode(`.ui.accent { color: ${t.accentColor}; }\n .ui.inverted.menu .accent.active.item, .ui.inverted.accent.menu { background-color: ${t.accentColor}; }`)),document.getElementsByTagName("head")[0].appendChild(e)}if(e.Util.isUserLanguageRtl()){e.debug("rtl layout"),e.BrowserUtils.addClass(document.body,"rtl"),document.body.style.direction="rtl";const t=e.Util.toArray(document.head.getElementsByTagName("link")),n=t.filter((t=>e.Util.endsWith(t.getAttribute("href"),"semantic.css")))[0];if(n){const t=n.getAttribute("data-rtl");t&&(e.debug(`swapping to ${t}`),n.setAttribute("href",t))}const i=t.filter((t=>e.Util.endsWith(t.getAttribute("href"),"blockly.css")))[0];if(i){const t=i.getAttribute("data-rtl");t&&(e.debug(`swapping to ${t}`),i.setAttribute("href",t),i.removeAttribute("data-rtl"))}}},t.changeHash=function(e,t){"#"!=e.charAt(0)&&(e="#"+e),t?window.location.hash=e:window.history.replaceState("","",e)},t.urlJoin=L,t.joinURLs=function(...e){let t;if(e)for(let n=0;n<e.length;n++)t=L(t,e[n]);return t},t.storageEstimateAsync=F,t.scheduleStorageCleanup=n()&&navigator.storage&&navigator.storage.estimate?ts.pxtc.Util.throttle((function(){F().then((t=>(e.debug(`storage estimate: ${t.usage/t.quota*100>>0}%, ${t.usage/1e6>>0}/${t.quota/1e6>>0}Mb`),t.quota&&t.usage&&t.quota>1e6&&t.usage/t.quota>.9?(e.log("quota usage exceeded, clearing translations"),e.tickEvent("storage.cleanup"),H()):Promise.resolve()))).catch((t=>{e.reportException(t)}))}),1e4,!1):()=>{},t.stressTranslationsAsync=function t(){let n="...";for(let e=0;e<16;++e)n+=n+Math.random();return console.log(`adding entry ${2*n.length} bytes`),e.U.delay(1).then((()=>q())).then((e=>e.setAsync("foobar",Math.random().toString(),null,void 0,n))).then((()=>e.BrowserUtils.storageEstimateAsync())).then((e=>!e.quota||e.usage/e.quota<.8?t():Promise.resolve()))};class B{constructor(){this.translations={}}key(e,t){return`${e}|${t}|master`}get(e,t){return this.translations[this.key(e,t)]}getAsync(e,t){return Promise.resolve(this.get(e,t))}set(e,t,n,i,s,r){this.translations[this.key(e,t)]={etag:n,time:i,strings:s,md:r}}setAsync(t,n,i,s,r){return this.set(t,n,i,e.Util.now(),s),Promise.resolve()}clearAsync(){return this.translations={},Promise.resolve()}}class ${constructor(e,t,n,i,s=!1){this.name=e,this.version=t,this.upgradeHandler=n,this.quotaExceededHandler=i,this.skipErrorLog=s}throwIfNotOpened(){if(!this._db)throw new Error("Database not opened; call IDBWrapper.openAsync() first")}errorHandler(t,n,i){this.skipErrorLog?i(t):(console.error(new Error(`${this.name} IDBWrapper error for ${n}: ${t.message}`)),i(t),"QuotaExceededError"==t.name&&(e.log("storage quota exceeded..."),e.tickEvent("storage.quotaexceedederror"),this.quotaExceededHandler&&this.quotaExceededHandler()))}getObjectStore(e,t="readonly"){this.throwIfNotOpened();return this._db.transaction([e],t).objectStore(e)}static deleteDatabaseAsync(e){return new Promise(((t,n)=>{const i=(window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB).deleteDatabase(e);i.onsuccess=()=>t(),i.onerror=()=>n(i.error)}))}openAsync(){return new Promise(((e,t)=>{const n=(window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB).open(this.name,this.version);n.onsuccess=()=>{this._db=n.result,e()},n.onerror=()=>this.errorHandler(n.error,"open",t),n.onupgradeneeded=e=>this.upgradeHandler(e,n)}))}getAsync(e,t){return new Promise(((n,i)=>{const s=this.getObjectStore(e).get(t);s.onsuccess=()=>n(s.result),s.onerror=()=>this.errorHandler(s.error,"get",i)}))}getAllAsync(e){return new Promise(((t,n)=>{const i=this.getObjectStore(e).openCursor(),s=[];i.onsuccess=()=>{i.result?(s.push(i.result.value),i.result.continue()):t(s)},i.onerror=()=>this.errorHandler(i.error,"getAll",n)}))}setAsync(e,t){return new Promise(((n,i)=>{const s=this.getObjectStore(e,"readwrite");let r;r=void 0!==t.id&&null!==t.id?s.put(t):s.add(t),r.onsuccess=()=>n(),r.onerror=()=>this.errorHandler(r.error,"set",i)}))}deleteAsync(e,t){return new Promise(((n,i)=>{const s=this.getObjectStore(e,"readwrite").delete(t);s.onsuccess=()=>n(),s.onerror=()=>this.errorHandler(s.error,"delete",i)}))}deleteAllAsync(e){return new Promise(((t,n)=>{const i=this.getObjectStore(e,"readwrite").clear();i.onsuccess=()=>t(),i.onerror=()=>this.errorHandler(i.error,"deleteAll",n)}))}getObjectStoreWrapper(e){return new j(this,e)}}t.IDBWrapper=$;class j{constructor(e,t){this.db=e,this.storeName=t}getAsync(e){return this.db.getAsync(this.storeName,e)}getAllAsync(){return this.db.getAllAsync(this.storeName)}setAsync(e){return this.db.setAsync(this.storeName,e)}async deleteAsync(e){await this.db.deleteAsync(this.storeName,e)}async deleteAllAsync(){await this.db.deleteAllAsync(this.storeName)}}t.IDBObjectStoreWrapper=j;class V{constructor(e){this.db=e,this.mem=new B}static dbName(){return`__pxt_translations_${e.appTarget.id||""}`}static createAsync(){function e(){const e=new $(V.dbName(),2,((e,t)=>{t.result.createObjectStore(V.TABLE,{keyPath:V.KEYPATH})}),(()=>{H().catch((e=>{}))}));return e.openAsync().then((()=>new V(e)))}return e().catch((t=>(console.log("db: failed to open database, try delete entire store..."),$.deleteDatabaseAsync(V.dbName()).then((()=>e())))))}getAsync(e,t){e=(e||"en-US").toLowerCase();const n=this.mem.key(e,t),i=this.mem.get(e,t);return i?Promise.resolve(i):this.db.getAsync(V.TABLE,n).then((n=>n?(this.mem.set(e,t,n.etag,n.time,n.strings),Promise.resolve(n)):Promise.resolve(void 0))).catch((e=>Promise.resolve(void 0)))}setAsync(n,i,s,r,o){n=(n||"en-US").toLowerCase();const a=this.mem.key(n,i);let l=e.Util.now();this.mem.set(n,i,s,l,r,o),r&&Object.keys(r).filter((e=>!r[e])).forEach((e=>delete r[e]));const c={id:a,etag:s,time:l,strings:r,md:o};return this.db.setAsync(V.TABLE,c).finally((()=>t.scheduleStorageCleanup())).catch((e=>(console.log(`db: set failed (${e.message}), recycling...`),this.clearAsync())))}clearAsync(){return this.db.deleteAllAsync(V.TABLE).then((()=>console.debug("db: all clean"))).catch((e=>{console.error("db: failed to delete all")}))}}function q(){return e.Util.isNodeJS?Promise.resolve(new B):(R||(R=V.createAsync().catch((()=>new B))),R)}function H(){function t(){const t=V.dbName();return $.deleteDatabaseAsync(t).then((()=>{R=void 0})).catch((n=>{e.log(`db: failed to delete ${t}`),R=void 0}))}return R?R.then((e=>e.clearAsync())).catch((e=>t().then())):t()}function G(t){const n=JSON.stringify(t)+e.appTarget.versions.pxt+"_"+e.appTarget.versions.target;return pxtc.U.sha256(n)}function z(e,t){return`${e}|${t||"master"}`}V.TABLE="files",V.KEYPATH="id",t.translationDbAsync=q,t.clearTranslationDbAsync=H,t.getTutorialCodeHash=G;class W{constructor(e){this.db=e}static dbName(){return`__pxt_tutorialinfo_${e.appTarget.id||""}`}static createAsync(){function t(){const t=new e.BrowserUtils.IDBWrapper(W.dbName(),2,((e,t)=>{t.result.createObjectStore(W.TABLE,{keyPath:W.KEYPATH})}),(()=>{e.BrowserUtils.IDBWrapper.deleteDatabaseAsync(W.dbName())}));return t.openAsync().then((()=>new W(t)))}return t().catch((n=>(console.log("db: failed to open tutorial info database, try delete entire store..."),e.BrowserUtils.IDBWrapper.deleteDatabaseAsync(W.dbName()).then((()=>t())))))}getAsync(t,n,i){const s=z(t,i),r=G(n);return this.db.getAsync(W.TABLE,s).then((t=>{if(t&&t.hash==r&&e.Util.now()-(t.time||0)<864e5)return t;this.db.deleteAsync(W.TABLE,s)}))}setAsync(t,n,i,s,r,o){e.perf.measureStart("tutorial info db setAsync");z(t,o);const a=G(i);return this.setWithHashAsync(t,n,a,s,r)}setWithHashAsync(t,n,i,s,r,o){e.perf.measureStart("tutorial info db setAsync");const a=z(t,o),l={};Object.keys(n).forEach((e=>{Object.keys(n[e]).forEach((t=>{l[t]=n[e][t]}))}));const c={id:a,time:e.Util.now(),hash:i,snippets:n,blocks:l,highlightBlocks:s,validateBlocks:r};return this.db.setAsync(W.TABLE,c).then((()=>{e.perf.measureEnd("tutorial info db setAsync")}))}clearAsync(){return this.db.deleteAllAsync(W.TABLE).then((()=>console.debug("db: all clean"))).catch((e=>{console.error("db: failed to delete all")}))}}function J(e){return e.split(/\s+/).filter((e=>!!e))}function Y(){const t=new RegExp(`${e.Util.escapeForRegex(e.Util.pxtLangCookieId)}=(.*?)(?:;|$)`).exec(document.cookie);return t&&t[1]||null}W.TABLE="info",W.KEYPATH="id",t.tutorialInfoDbAsync=function(){return M||(M=W.createAsync()),M},t.clearTutorialInfoDbAsync=function(){function t(){const t=W.dbName();return $.deleteDatabaseAsync(t).then((()=>{M=void 0})).catch((n=>{e.log(`db: failed to delete ${t}`),M=void 0}))}return M?M.then((e=>e.clearAsync())).catch((e=>t().then())):t()},t.pointerEvents=k()?{up:"pointerup",down:["pointerdown"],move:"pointermove",enter:"pointerenter",leave:"pointerleave"}:g()?{up:"mouseup",down:["mousedown","touchstart"],move:"touchmove",enter:"touchenter",leave:"touchend"}:{up:"mouseup",down:["mousedown"],move:"mousemove",enter:"mouseenter",leave:"mouseleave"},t.getPageX=function(e){return"pageX"in e?e.pageX:e.changedTouches[0].pageX},t.getPageY=function(e){return"pageY"in e?e.pageY:e.changedTouches[0].pageY},t.getClientX=function(e){return"clientX"in e?e.clientX:e.changedTouches[0].clientX},t.getClientY=function(e){return"clientY"in e?e.clientY:e.changedTouches[0].clientY},t.popupWindow=function(t,n,i,s){try{const r=window.screenLeft?window.screenLeft:window.screenX,o=window.screenTop?window.screenTop:window.screenY,a=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth,l=window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight,c="width="+i+", height="+s+", top="+(l/2-s/2+o)+", left="+(a/2-i/2+r),u=window.open(t,n,e.BrowserUtils.isIpcRenderer()?void 0:c);return u.focus&&u.focus(),u}catch(t){return e.tickEvent("pxt.popupError",{msg:t.message}),null}},t.containsClass=function(e,t){return J(t).every((t=>function(e,t){if(e.classList)return e.classList.contains(t);return!((e.className+"").split(/\s+/).indexOf(t)<0)}(e,t)))},t.addClass=function(e,t){J(t).forEach((t=>function(e,t){if(e.classList)e.classList.add(t);else{(e.className+"").split(/\s+/).indexOf(t)<0&&(e.className.baseVal+=" "+t)}}(e,t)))},t.removeClass=function(e,t){J(t).forEach((t=>function(e,t){e.classList?e.classList.remove(t):e.className.baseVal=(e.className+"").split(/\s+/).filter((e=>e!=t)).join(" ")}(e,t)))},t.getCookieLang=Y,t.setCookieLang=function(t,n=!1){if(e.Util.allLanguages[t]&&t!==Y()){e.tickEvent("menu.lang.setcookielang",{lang:t,docs:`${n}`});const i=new Date;i.setTime(i.getTime()+24*e.Util.langCookieExpirationDays*60*60*1e3),document.cookie=`${e.Util.pxtLangCookieId}=${t}; expires=${i.toUTCString()}; path=/`}},t.cacheBustingUrl=function(e){return e?/[?&]rnd=/.test(e)?e:`${e}${e.indexOf("?")>0?"&":"?"}rnd=${Math.random()}`:e},t.legacyCopyText=function(t){t.focus(),t.setSelectionRange(0,9999);try{const t=document.execCommand("copy");return e.debug("copy: "+t),!!t}catch(e){return!1}},t.setApplicationTheme=function(e){const t=document.body,n=t.classList;for(let e=0;e<n.length;e++)/^theme-/.test(n[e])&&t.classList.remove(n[e]);e&&t.classList.add(`theme-${e}`)},t.isElement=function(e){return e.nodeType===Node.ELEMENT_NODE}}(e.BrowserUtils||(e.BrowserUtils={}))}(pxt||(pxt={})),function(e){!function(e){const t="https://staging.pxt.io";e.DEV_BACKEND=t,e.devBackendType=function(){return"https://makecode.com"===e.DEV_BACKEND?"prod":e.DEV_BACKEND===t?"staging":"http://localhost:8080"===e.DEV_BACKEND?"localhost":"prod"},e.cloudStatus={none:{value:"none"},synced:{value:"synced",icon:"cloud-saved-b",tooltip:lf("Project saved to cloud"),shortStatus:lf("saved"),longStatus:lf("Saved to cloud"),indicator:""},justSynced:{value:"justSynced",icon:"cloud-saved-b",tooltip:lf("Project saved to cloud"),shortStatus:lf("saved!"),longStatus:lf("Saved to cloud!"),indicator:""},offline:{value:"offline",icon:"cloud-error-b",tooltip:lf("Unable to connect to cloud"),shortStatus:lf("offline"),longStatus:lf("Offline"),indicator:lf("offline")},syncing:{value:"syncing",icon:"cloud-saving-b",tooltip:lf("Saving project to cloud..."),shortStatus:lf("saving..."),longStatus:lf("Saving to cloud..."),indicator:lf("syncing...")},conflict:{value:"conflict",icon:"cloud-error-b",tooltip:lf("Project was edited in two places and the changes conflict"),shortStatus:lf("conflict!"),longStatus:lf("Project has a conflict!"),indicator:"!"},localEdits:{value:"localEdits",icon:"cloud-saving-b",tooltip:lf("Project has local changes and will save to cloud soon."),shortStatus:"",longStatus:"",indicator:"*"}}}(e.cloud||(e.cloud={}))}(pxt||(pxt={})),function(e){!function(e){let t;!function(e){e[e.Failed=0]="Failed",e[e.Success=1]="Success",e[e.UserRejected=2]="UserRejected"}(t=e.WebUSBPairResult||(e.WebUSBPairResult={})),e.deployCoreAsync=void 0,e.deployFallbackAsync=void 0,e.hasDeployFn=()=>e.deployCoreAsync||e.deployFallbackAsync,e.deployAsync=(t,n)=>(e.deployCoreAsync||e.deployFallbackAsync)(t,n),e.patchCompileResultAsync=void 0,e.browserDownloadAsync=void 0,e.saveOnlyAsync=void 0,e.renderBrowserDownloadInstructions=void 0,e.renderUsbPairDialog=void 0,e.renderIncompatibleHardwareDialog=void 0,e.showUploadInstructionsAsync=void 0,e.saveProjectAsync=void 0,e.electronDeployAsync=void 0,e.webUsbPairDialogAsync=void 0,e.onTutorialCompleted=void 0,e.workspaceLoadedAsync=void 0}(e.commands||(e.commands={}))}(pxt||(pxt={})),function(e){function t(t){const n=e.toolbox.convertColor(t),i=parseInt(n.slice(1,3),16)/255,s=parseInt(n.slice(3,5),16)/255,r=parseInt(n.slice(5,7),16)/255;return.2126*(i<=.03928?i/12.92:Math.pow((i+.055)/1.055,2.4))+.7152*(s<=.03928?s/12.92:Math.pow((s+.055)/1.055,2.4))+.0722*(r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4))}function n(e,n){return(t(e)+.05)/(t(n)+.05)}function i(e){const t=(1-Math.abs(2*e.l-1))*e.s,n=e.h/60,i=t*(1-Math.abs(n%2-1));let r;void 0===e.h?r=[0,0,0]:n<=1?r=[t,i,0]:n<=2?r=[i,t,0]:n<=3?r=[0,t,i]:n<=4?r=[0,i,t]:n<=5?r=[i,0,t]:n<=6&&(r=[t,0,i]);let o=e.l-.5*t;return a=Math.round(255*(r[0]+o)),l=Math.round(255*(r[1]+o)),c=Math.round(255*(r[2]+o)),"#"+s(a)+s(l)+s(c);var a,l,c}function s(e){return("0"+e.toString(16)).slice(-2)}e.getWhiteContrastingBackground=function(t){if(n("#ffffff",t)>=4.5)return t;const s=function(t){const n=e.toolbox.convertColor(t),i=parseInt(n.slice(1,3),16)/255,s=parseInt(n.slice(3,5),16)/255,r=parseInt(n.slice(5,7),16)/255,o=Math.max(Math.max(i,s),r),a=Math.min(Math.min(i,s),r),l=o-a;let c;0===l?c=0:o===i?c=((s-r)/l%6+6)%6:o===s?c=(r-i)/l+2:o===r&&(c=(i-s)/l+4);let u=(a+o)/2,d=0===l?0:l/(1-Math.abs(2*u-1));return{h:60*c,s:d,l:u}}(t);let r=s.l-.05;for(;r>0;){const e=i({h:s.h,s:s.s,l:r});if(n("#ffffff",e)>=4.5)return e;r-=.05}return console.warn(`Couldn't find a contrasting background for color ${t}`),t},e.contrastRatio=n}(pxt||(pxt={})),function(e){function t(){let t;return t||(t=e.U.isNodeJS?Promise.resolve(require("lzma")):Promise.resolve(window.LZMA),t.then((t=>(t||e.reportError("lzma","failed to load"),t)))),t}e.lzmaDecompressAsync=function(n){return t().then((t=>new Promise(((i,s)=>{try{t.decompress(n,((t,n)=>{n&&e.debug("lzma decompression failed"),i(n?void 0:t)}))}catch(t){t&&e.debug("lzma decompression failed"),i(void 0)}}))))},e.lzmaCompressAsync=function(n){return t().then((t=>new Promise(((i,s)=>{try{t.compress(n,7,((t,n)=>{n&&e.reportException(n),i(n?void 0:new Uint8Array(t))}))}catch(t){e.reportException(t),i(void 0)}}))))}}(pxt||(pxt={})),function(e){!function(t){var n=pxtc.Util;let i=n.lf;const s={"pxt::mkAction":1,"pxt::dumpPerfCounters":1,"pxt::deepSleep":1,"pxt::getConfig":1,"pxtrt::mkMap":1,"pxtrt::mapSet":1,"pxtrt::stclo":1,"pxtrt::mklocRef":1,"pxtrt::stlocRef":1,"pxtrt::ldlocRef":1,"pxtrt::panic":1};function r(e="namespace"){let t="",n="",i=(i,s="")=>{n!=i&&(n&&(t+="}\n"),i&&(t+=s||e+" "+i+" {\n"),n=i)},s=" ";return{setNs:i,clear:()=>{t="",n=""},write:e=>{e.trim()?(e=e.trim().replace(/^\s*/gm,s).replace(/^(\s*)\*/gm,((e,t)=>t+" *")),t+=e+"\n"):t+="\n"},incrIndent:()=>{s+=" "},decrIndent:()=>{s=s.slice(4)},finish:()=>(i(""),t)}}function o(e){if(!e)return null;e=e.trim();let t=/^\((.*)\)/.exec(e);return t&&(e=t[1]),/^-?(\d+|0[xX][0-9a-fA-F]+)$/.test(e)?parseInt(e):null}t.nsWriter=r,t.parseCppInt=o;let a={};class l extends Error{constructor(e){super(e),this.isUserError=!0,this.message=e}}function c(e){if(!e)return"";let t="";for(let n=0;n<e.length;++n){let i=255&e[n];t+=37==i||i>127?"%"+i.toString(16):String.fromCharCode(i)}return decodeURIComponent(t)}function u(t){let n="",i=0;for(;i<t.length;i+=2)n=t[i]+t[i+1]+n;return e.Util.assert(i==t.length),n}function d(e){let t=[65,20,14,47,184,47,162,187];e:for(let n=0;n<e.length;n+=16){if(e[n]!=t[0])continue;for(let i=0;i<t.length;++i)if(e[n+i]!=t[i])continue e;let i=e[n+8]|e[n+9]<<8,s=e[n+10]|e[n+11]<<8|e[n+12]<<16|e[n+13]<<24;n+=16;let r=n+i+s;if(r>e.length)continue;let o=e.slice(n,n+i),a=e.slice(n+i,r);return{meta:c(o),text:a}}return null}function h(t){function n(t){return e.debug(t),Promise.reject(new Error(t))}let i;if(e.HF2.read32(t,0)==ts.pxtc.UF2.UF2_MAGIC_START0){let e=ts.pxtc.UF2.toBin(t);e&&(i=d(e.buf))}if(1179403647==e.HF2.read32(t,0)&&(i=d(t)),58==t[0]){i=function(e){if(!e)return;let t,n=0,i=0,s=0,r=0;if(e.split(/\r?\n/).forEach((e=>{let o=/^:10....0[0E]41140E2FB82FA2BB(....)(....)(....)(....)(..)/.exec(e);if(o)n=parseInt(u(o[1]),16),i=parseInt(u(o[2]),16),s=n+i,t=new Uint8Array(s);else if(s>0){if(o=/^:10....0[0E](.*)(..)$/.exec(e),!o)return;let n=o[1];for(;s>0&&n.length>0;)t[r++]=parseInt(n[0]+n[1],16),n=n.slice(2),s--}})),!t||0!=s||r!=t.length)return;let o=new Uint8Array(n),a=new Uint8Array(i);for(let e=0;e<n;++e)o[e]=t[e];for(let e=0;e<i;++e)a[e]=t[n+e];return{meta:c(o),text:a}}(c(t)||"")}if(!i||!i.meta||!i.text)return n("This .hex file doesn't contain source.");let s=JSON.parse(i.meta);return s?"LZMA"==s.compression?e.lzmaDecompressAsync(i.text).then((t=>{if(!t)return null;let n=t.slice(0,s.headerSize||s.metaSize||0),i=t.slice(n.length);return n&&e.Util.jsonCopyFrom(s,JSON.parse(n)),{meta:s,source:i}})):s.compression?n(`Compression type ${s.compression} not supported.`):Promise.resolve({source:c(i.text)}):n("This .hex file is not valid.")}t.PkgConflictError=l,t.getExtensionInfo=function(t){const c={__appVariant:e.appTargetVariant||""},u="dal.d.ts";let d="/source/",h="",p=[];const f=t.sortedDeps(!0).sort(((e,t)=>"this"==e.id?1:"this"==t.id?-1:n.strcmp(e.id,t.id)));for(let t of f)t.disablesVariant(e.appTargetVariant)||t.resolvedDependencies().some((t=>t.disablesVariant(e.appTargetVariant)))?(h&&(h+=", "),h+=t.id,e.debug(`disable variant ${e.appTargetVariant} due to ${t.id}`)):(p.push(t),t.addSnapshot(c,[u,".h",".cpp"]));const m=JSON.stringify(c),g=a[m];if(g){e.debug("Using cached extinfo");const t=n.flatClone(g);return t.disabledDeps=h,t}e.debug("Generating new extinfo");const b=pxtc.emptyExtInfo();b.disabledDeps=h;let y=e.appTarget.compileService;y||(y={gittag:"none",serviceId:"nocompile"}),y=n.clone(y);let v=t.getTargetOptions();v||(v={isNative:!1,hasHex:!1,switches:{}});const w=!!y.platformioIni,k="codal"==y.buildEngine||"dockercodal"==y.buildEngine,x="dockermake"==y.buildEngine||"dockercross"==y.buildEngine,A="dockerespidf"==y.buildEngine,E=!(w||k||x||A),T=v.nativeType==pxtc.NATIVE_TYPE_VM;w?d="/src/":k||x?d="/pxtapp/":A&&(d="/main/");let S="// Configuration defines\n",C="\nPXT_SHIMS_BEGIN\n",I="",_="",P='#include "pxt.h"\n',U="",O=e=>U+=` ${R}(${N}): ${e}\n`,N=0,R="",M=r("namespace"),D=r("declare namespace"),L=r("declare namespace"),F="",B={},$={};const j={true:"1",false:"0",null:"0",NULL:"0"};function V(e){return e.trim().replace(/[\_\*]$/,"")}for(const t of p){if(t.getFiles().indexOf(u)>=0){const n=t.host().readFile(t,u);e.Util.assert(!!n,`dal.d.ts not found in ${t.id}`),n.split(/\r?\n/).forEach((e=>{let t=/^\s*(\w+) = (.*),/.exec(e);t&&(j[t[1]]=t[2])}))}for(const e of t.getFiles())(["Makefile","sdkconfig.defaults","CMakeLists.txt"].indexOf(e)>=0||n.endsWith(e,".mk"))&&(b.generatedFiles["/"+e]=t.host().readFile(t,e))}let q=["0","false","PXT_UTF8"],H={};function G(e){return e.replace(/\/\/.*/,"").replace(/\/\*/,"")}v.switches.boxDebug&&(H.PXT_BOX_DEBUG=1),v.utf8&&(H.PXT_UTF8=1),v.switches.profile&&(H.PXT_PROFILE=1),v.switches.gcDebug&&(H.PXT_GC_DEBUG=1),v.switches.numFloat&&(H.PXT_USE_FLOAT=1),v.nativeType==pxtc.NATIVE_TYPE_VM&&(H.PXT_VM=1);let z=0,W=!1,J="",Y="",K="",X=!1;function Q(){D.setNs(""),D.write(""),D.write(""),(K||Y)&&(D.write(Y),D.write(K),K="",Y="")}function Z(e,t){let r;J="",Y="",K="",X=!1;let a=-1;function l(){let e=J.replace(/Methods$/,"");return e==J?null:e}function c(e){switch(e.replace(/\s+/g,"")){case"void":return"void";case"int32_t":case"int":return"int32";case"uint32_t":case"unsigned":return"uint32";case"TNumber":case"float":case"double":return"number";case"uint16_t":return"uint16";case"int16_t":case"short":return"int16";case"uint8_t":case"byte":return"uint8";case"int8_t":case"sbyte":return"int8";case"bool":return v.shortPointers&&O("use 'boolean' not 'bool' on 8 bit targets"),"boolean";case"StringData*":case"String":case"ImageLiteral_":case"ImageLiteral":return"string";case"Action":return"() => void";case"TValue":return"any";default:return V(e)}}function u(e){switch(e=e.replace(/\s+/g,"")){case"int32_t":case"uint32_t":case"unsigned":case"uint16_t":case"int16_t":case"short":case"uint8_t":case"byte":case"int8_t":case"sbyte":case"int":case"ramint_t":return"I";case"void":return"V";case"float":return"F";case"TNumber":return"N";case"TValue":return"T";case"bool":return"B";case"double":return"D";case"ImageLiteral_":return"T";case"String":return"S";default:return n.lookup(B,e)?"I":"_"+e.replace(/[\*_]+$/,"")}}e=e.replace(/^(\s*#\s*if\s+(\w+)\s*$)([^]*?)(^\s*#\s*(elif|else|endif)\s*$)/gm,((e,t,n,i,s)=>q.indexOf(n)>=0&&!H[n]?t+i.replace(/[^\n]/g,"")+s:e)),N=0,W=!1,z=0,L.setNs(""),D.setNs(""),e.split(/\r?\n/).forEach((e=>{++N;let d=G(e);!function(e){let t=G(e);if(W&&t.indexOf("}")>=0&&(W=!1,L.write("}")),!W)return;let i=/^\s*(\w+)\s*(=\s*(.*?))?,?\s*$/.exec(t);if(i){let e=i[1],s=i[3],r="";if(s){s=s.trim();let e=n.lookup(j,s);null!=e&&(r=" // "+s,s=e),z=o(s),null==z&&O("cannot determine value of "+t)}else z++,s=z+"";L.write(` ${V(e)} = ${s},${r}`)}else L.write(e)}(e);let h=/^\s*enum\s+(|class\s+|struct\s+)(\w+)\s*({|$)/.exec(d);var p,f;if(h&&(p=h[2],f=h[3],W=!0,z=-1,L.write(""),L.write(""),(K||Y)&&(L.write(Y),L.write(K),K="",Y=""),L.write(`declare const enum ${V(p)} ${f}`),B[p]=!0,t||(M.setNs(J),M.write(`enum ${h[2]} : int;`))),function(e){return!(!W&&(/^\s*\/\*\*/.test(e)?(X=!0,Y=e+"\n",/\*\//.test(e)&&(X=!1),0):X?(Y+=e+"\n",/\*\//.test(e)&&(X=!1),0):!/^\s*\/\/%/.test(e)||(K+=e+"\n",0)))}(e))return;/^typedef.*;\s*$/.test(e)&&(M.setNs(J),M.write(e));let m=/^\s*namespace\s+(\w+)/.exec(e);if(m)if(J=m[1],l()){Q();let e=l();D.setNs(J,`declare interface ${e} {`)}else(K||Y)&&(Q(),D.setNs(V(J)),L.setNs(V(J)));else{if(m=/^PXT_ABI\((\w+)\)/.exec(e),m&&!T&&(C+=`PXT_FNPTR(::${m[1]}),\n`,_+=`extern "C" void ${m[1]}();\n`,b.functions.push({name:m[1],argsFmt:[],value:0})),m=/^\s*PXT_EXPORT\(([:\&\w]+)\)/.exec(e),m&&(b.vmPointers||(b.vmPointers=[]),b.vmPointers.push(m[1])),m=/^#define\s+PXT_COMM_BASE\s+([0-9a-fx]+)/.exec(e),m&&(b.commBase=parseInt(m[1])),m=/^\s*(\w+)([\*\&]*\s+[\*\&]*)(\w+)\s*\(([^\(\)]*)\)\s*(;\s*$|\{|$)/.exec(e),!K||!m){if(m=/^\s*extern const (\w+) (\w+);/.exec(e),K&&m){let e={name:J+"::"+m[2],argsFmt:[],value:null};return b.functions.push(e),T||(C+="PXT_FNPTR(&::"+e.name+"),\n"),void(K="")}if(m=/^\s*(\w+)\s+(\w+)\s*;/.exec(e),K&&m){let e=pxtc.parseCommentString(K);e.indexedInstanceNS&&(r=e,D.setNs(e.indexedInstanceNS),a=0);let t=m[1],n=m[2];if(r)return K=K.trim(),K+=` fixedInstance shim=${r.indexedInstanceShim}(${a++})`,D.write(""),D.write(Y),D.write(K),D.write(`const ${n}: ${c(t)};`),Y="",void(K="")}return K&&e.trim()?(O("declaration not understood: "+e),K="",void(Y="")):void 0}{r=null;let e=pxtc.parseCommentString(K);J||O("missing namespace declaration");let a=(m[1]+m[2]).replace(/\s+/g,""),d=m[3],h=m[4];K=K.trim().replace(/ \w+\.defl=\w+/g,"");let p=[u(a)],f=[],g=h.split(/,/).filter((e=>!!e)).map((t=>{let i=function(e,t){t=t.trim();let i=/(.*)=\s*(-?\w+)$/.exec(t),s="",r="";if(i&&(s=i[2],r="?",t=i[1].trim()),i=/^(.*?)(\w+)$/.exec(t),!i)return O("invalid argument: "+t),{name:"???",type:"int"};let a=i[2];e.paramDefl[a]&&(s=e.paramDefl[a],r="?");let l=s?n.lookup(j,s):null;return null!=l&&(s=l),s&&(null==o(s)&&O("Invalid default value (non-integer): "+s),K+=` ${a}.defl=${s}`),{name:a+r,type:i[1]}}(e,t);return p.push(u(i.type)),f.push(i.type.replace(/ /g,"")),`${i.name}: ${c(i.type)}`})),y={name:J+"::"+d,argsFmt:p,value:null};if(Y)if(D.setNs(V(J)),D.write(""),D.write(Y),/ImageLiteral/.test(m[4])&&!/imageLiteral=/.test(K)&&(K+=" imageLiteral=1"),K+=` shim=${y.name}`,D.write(K),d=V(d),l()){let e=(g[0]||"").replace(/^.*:\s*/,"").trim();e.toLowerCase()!=l().toLowerCase()&&O(i("Invalid first argument; should be of type '{0}', but is '{1}'",l(),e)),g.shift(),0==g.length&&/\bproperty\b/.test(K)?D.write(`${d}: ${c(a)};`):D.write(`${d}(${g.join(", ")}): ${c(a)};`)}else D.write(`function ${d}(${g.join(", ")}): ${c(a)};`);if(Y="",K="",t||(M.setNs(J),M.write(`${a} ${d}(${h});`)),b.functions.push(y),E)C+="(uint32_t)(void*)::"+y.name+",\n";else if(T){if(n.startsWith(y.name,"pxt::op_")||s[y.name]||e.expose||!n.startsWith(y.name,"pxt::")&&!n.startsWith(y.name,"pxtrt::")){const e=function(e,t){if("FiberContext*"==t[0])return"::"+e.name;let n="_wrp_"+e.name.replace(/:/g,"_");if($[e.name])return n;$[e.name]=!0,I+=`\nvoid ${n}(FiberContext *ctx) {\n`;const i=t.length;let s=[],r=!1,o="";for(let n=0;n<i;++n){const a=e.argsFmt[n+1],l=t[n];let c="I"==a?"toInt":"B"==a?"numops::toBool":"";const u=n==i-1?"ctx->r0":`ctx->sp[${i-n-2}]`;let d="";switch(l){case"TValue":case"TNumber":break;case"Action":c="asRefAction";break;case"String":c="convertToString",d="ctx, ",r=!0;break;default:c||(c="as"+l.replace(/\*/g,""))}o+=` ${l} a${n} = (${l}) ${c}(${d}${u});\n`,s.push("a"+n)}r&&(I+=" auto prevSP = ctx->sp;\n"),I+=o,r&&(I+=" if (panicCode) { ctx->sp = prevSP; return; }\n");const a=`::${e.name}(${s.join(", ")})`;return"V"==e.argsFmt[0]?(I+=` ${a};\n`,I+=" ctx->r0 = NULL;\n"):"I"==e.argsFmt[0]?I+=` ctx->r0 = fromInt(${a});\n`:"B"==e.argsFmt[0]?I+=` ctx->r0 = fromBool(${a});\n`:I+=` ctx->r0 = (TValue)${a};\n`,r&&(I+=" ctx->sp = prevSP;\n"),i>1&&(I+=` ctx->sp += ${i-1};\n`),I+="}\n",n}(y,f),t=y.argsFmt.length-1;C+=`{ "${y.name}", (OpFun)(void*)${e}, ${t} },\n`}}else C+="PXT_FNPTR(::"+y.name+"),\n"}}}))}const ee=n.clone(y.yottaConfig||{}),te={},ne={},ie={};function se(t){const s=t.config.platformio;s&&s.dependencies&&n.jsonCopyFrom(b.platformio.dependencies,s.dependencies),b.npmDependencies&&t.config.npmDependencies&&n.jsonCopyFrom(b.npmDependencies,t.config.npmDependencies);const r=t.config.codal;if(k&&r)for(const t of r.libraries||[]){const s=e.github.parseRepoId(t);s||n.userError(i("codal library {0} doesn't look like github repo",t));const r=e.github.stringifyRepo(s),o=n.lookup(ie,s.project);o?e.github.stringifyRepo(o)!=r&&n.userError(i("conflict between codal libraries: {0} and {1}",e.github.stringifyRepo(o),r)):ie[s.project]=s}const o=t.config.yotta;if(o){if(o.dependencies&&n.jsonCopyFrom(b.yotta.dependencies,o.dependencies),o.config){const e=n.jsonFlatten(o.config);for(const s of Object.keys(e)){const r=n.lookup(ne,s),o=e[s];if(!r||r.config.yotta.configIsJustDefaults)ne[s]=t,ee[s]=o;else if(ee[s]===o);else if(!t.parent.config.yotta||!t.parent.config.yotta.ignoreConflicts){let e=new l(i("conflict on yotta setting {0} between extensions {1} and {2}",s,t.id,r.id));throw e.pkg0=r,e.pkg1=t,e.settingName=s,e}}}if(o.optionalConfig){const e=n.jsonFlatten(o.optionalConfig);for(const t of Object.keys(e)){const n=e[t];te[t]=n}}}}if(E&&v.hasHex){let e=y;n.assert(!!e.yottaCorePackage),n.assert(!!e.githubCorePackage),n.assert(!!e.gittag);let t=e.githubCorePackage+"#"+y.gittag;b.yotta.dependencies[e.yottaCorePackage]=t}if(t){let e=!1;for(let s of p){U="",se(s),s==t?(e=!0,D.clear(),L.clear()):n.assert(!e);const r=e=>n.endsWith(e,".h"),o=".cpp",a=s.getFiles().filter(r).concat(s.getFiles().filter((e=>!r(e))));for(let e of a){const t=r(e);if(t||n.endsWith(e,o)){let r=s.config.name+"/"+e;("base"==s.config.name||/^core($|---)/.test(s.config.name))&&t&&(r=e),t&&(P+=`#include "${E?d.slice(1):""}${r}"\n`);let o=s.readFile(e);null==o&&n.userError(i("C++ file {0} is missing in extension {1}.",e,s.config.name)),R=r,Z(o,t),b.extensionFiles[d+r]=o,0==s.level&&(b.onlyPublic=!1),s.verProtocol()&&"pub"!=s.verProtocol()&&"embed"!=s.verProtocol()&&(b.onlyPublic=!1)}if(n.endsWith(e,".c")||n.endsWith(e,".S")||n.endsWith(e,".s")){let t=s.readFile(e);b.extensionFiles[d+s.config.name+"/"+e.replace(/\.S$/,".s")]=t}}U&&(F+=i("Extension {0}:\n",s.id)+U)}e||(D.clear(),L.clear())}function re(e){return Object.keys(b.extensionFiles).concat(Object.keys(b.generatedFiles)).filter((t=>n.endsWith(t,e))).map((e=>e.slice(1)))}F&&n.userError(F),n.jsonCopyFrom(te,ee),n.iterMap(te,((e,t)=>{null===t&&delete te[e]})),Object.keys(te).filter((e=>/-/.test(e))).forEach((e=>{const t=te[e];delete te[e],te[e.replace(/-/g,"_")]=t})),!E&&y.yottaConfigCompatibility&&Object.keys(te).forEach((e=>te["YOTTA_CFG_"+e]=te[e])),te.PXT_TARGET=JSON.stringify(e.appTarget.id);const oe=n.jsonUnFlatten(te);if(x){let e={name:"pxt-app",private:!0,dependencies:b.npmDependencies};b.generatedFiles["/package.json"]=JSON.stringify(e,null,4)+"\n"}else if(A){const e=n.concatArrayLike([re(".c"),re(".cpp"),re(".s")]).map((e=>e.slice(d.length-1))).concat(["main.cpp"]);e.push("pointers.cpp"),b.generatedFiles[d+"CMakeLists.txt"]="idf_component_register(\n SRCS\n"+e.map((e=>` "${e}"\n`)).join("")+' INCLUDE_DIRS\n "."\n)\n'}else if(k){let t=y,i=n.clone(t.codalDefinitions)||{},s=t.codalTarget;"string"==typeof s&&(s+=".json");let r={target:s,definitions:i,config:i,application:"pxtapp",output_folder:"build",pxt_gitrepo:t.githubCorePackage,pxt_gittag:t.gittag,libraries:n.values(ie).map((e=>({name:e.project,url:"https://github.com/"+e.fullName,branch:e.tag||"master",type:"git"})))};0==r.libraries.length&&delete r.libraries,n.iterMap(n.jsonFlatten(oe),((e,t)=>{e=e.replace(/^codal\./,"device.").toUpperCase().replace(/\./g,"_"),i[e]=t})),b.generatedFiles["/codal.json"]=JSON.stringify(r,null,4)+"\n",e.debug(`codal.json: ${b.generatedFiles["/codal.json"]}`),b.codal=r}else if(w){const e=y.platformioIni.slice();e.push("lib_deps ="),n.iterMap(b.platformio.dependencies,((t,n)=>{let i=/[@#\/]/.test(n)?n:t+"@"+n;e.push(" "+i)})),b.generatedFiles["/platformio.ini"]=e.join("\n")+"\n"}else{b.yotta.config=oe;let t="pxt-app";y.yottaBinary&&(t=y.yottaBinary.replace(/-combined/,"").replace(/\.hex$/,""));let n={name:t,version:"0.0.0",description:"Auto-generated. Do not edit.",license:"n/a",dependencies:b.yotta.dependencies,targetDependencies:{},bin:"./source"};b.generatedFiles["/module.json"]=JSON.stringify(n,null,4)+"\n",e.debug(`module.json: ${b.generatedFiles["/module.json"]}`)}for(let e of Object.keys(H))S+=`#define ${e} ${H[e]}\n`;if(v.uf2Family&&(S+=`#define PXT_UF2_FAMILY ${v.uf2Family}\n`),b.generatedFiles[d+"pointers.cpp"]=P+M.finish()+_+I+C+"\nPXT_SHIMS_END\n",b.generatedFiles[d+"pxtconfig.h"]=S,e.debug(`pxtconfig.h: ${b.generatedFiles[d+"pxtconfig.h"]}`),E&&(b.generatedFiles["/config.json"]=JSON.stringify(oe,null,4)+"\n",e.debug(`yotta config.json: ${b.generatedFiles["/config.json"]}`)),b.generatedFiles[d+"main.cpp"]='\n#include "pxt.h"\n#ifdef PXT_MAIN\nPXT_MAIN\n#else\nint main() {\n uBit.init();\n pxt::start();\n release_fiber();\n return 0; // your program will never reach this line.\n}\n#endif\n',b.generatedFiles["/Makefile"]){let e="",t=(t,n)=>{e+=`${t} = ${re(n).join(" ")}\n`};t("PXT_C",".c"),t("PXT_CPP",".cpp"),t("PXT_S",".s"),t("PXT_HEADERS",".h"),e+="PXT_SOURCES := $(PXT_C) $(PXT_S) $(PXT_CPP)\n",e+="PXT_OBJS := $(addprefix bld/, $(PXT_C:.c=.o) $(PXT_S:.s=.o) $(PXT_CPP:.cpp=.o))\n",b.generatedFiles["/Makefile.inc"]=e}b.generatedFiles["/functions.json"]=JSON.stringify(b.functions,null,1);let ae=b.extensionFiles;n.jsonCopyFrom(ae,b.generatedFiles);let le={config:y.serviceId,tag:y.gittag,replaceFiles:ae,dependencies:E?b.yotta.dependencies:null},ce=JSON.stringify(le);return b.sha=n.sha256(ce),b.skipCloudBuild=!!y.skipCloudBuild,b.compileData=ts.pxtc.encodeBase64(n.toUTF8(ce)),b.shimsDTS=D.finish(),b.enumsDTS=L.finish(),Object.keys(a).length>10&&(a={}),a[m]=b,b},t.unpackSourceFromHexFileAsync=function(t){if(t)return e.Util.fileReadAsBufferAsync(t).then((e=>h(new Uint8Array(e))))},t.unpackSourceFromHexAsync=h}(e.cpp||(e.cpp={}))}(pxt||(pxt={})),function(e){!function(t){const n={};let i,s={};function r(s){return n.hasOwnProperty(s.sha)||(n[s.sha]=function(n){let s="";return t.showLoading(e.U.lf("Compiling (this may take a minute)...")),e.tickEvent("cppcompile.start"),function(t){if(t.skipCloudBuild)return Promise.resolve({hex:["SKIP"]});if(e.webConfig&&e.webConfig.isStatic)return e.Util.requestAsync({url:`${e.webConfig.cdnUrl}hexcache/${t.sha}.hex`}).then((t=>{if(t.text){const e={enums:[],functions:[],hex:t.text.split(/\r?\n/)};return Promise.resolve(e)}return e.log("Hex info not found in bundled hex cache"),Promise.resolve()})).catch((t=>(e.log("Error fetching hex info from bundled hex cache"),Promise.resolve())));if(!e.Cloud.localToken||!window||!e.BrowserUtils.isLocalHost())return Promise.resolve(void 0);return(n="compile/"+t.sha,e.Cloud.localRequestAsync(n,i).then((e=>e.json))).then((e=>e&&!e.notInOfflineCache&&e.hex?(e.hex=e.hex.split(/\r?\n/),e):Promise.resolve(void 0))).catch((e=>Promise.resolve(void 0)));var n,i}(n).then((r=>r?(e.tickEvent("cppcompile.cachehit"),r):function(){if(i)return i;{let t=e.getOnlineCdnUrl();if(t)return i=Promise.resolve(t);const n=e.webConfig&&e.webConfig.isStatic;return i=e.Cloud.privateGetAsync("clientconfig",n).then((e=>e.primaryCdnUrl))}}().then((t=>(s=t+"/compile/"+n.sha,e.U.httpGetTextAsync(s+".hex")))).then((e=>e),(t=>e.Cloud.privatePostAsync("compile/extension",{data:n.compileData},!0).then((t=>new Promise(((n,i)=>{let r=0;const o=8e3,a=3e5,l=e.U.now(),c=()=>{if(r++,e.U.now()-l>a)return e.log("abandoning C++ build"),e.tickEvent("cppcompile.cancel",{retry:r}),n(null),null;let i=t.hex.replace(/\.hex/,".json");return e.log(`polling C++ build ${i} (attempt #${r})`),e.tickEvent("cppcompile.poll",{retry:r}),e.Util.httpGetJsonAsync(i).then((t=>{e.log(`build log ${i.replace(/\.json$/,".log")}`),e.tickEvent("cppcompile.done",{success:(null==t?void 0:t.success)?1:0,retry:r,duration:e.U.now()-l}),t.success?(e.log("fetching "+s+".hex"),n(e.U.httpGetTextAsync(s+".hex"))):(e.log("build failed"),t.mbedresponse&&t.mbedresponse.result&&t.mbedresponse.result.exception&&e.log(t.mbedresponse.result.exception),n(null))}),(t=>(e.log(`waiting ${o/1e3|0}s for C++ build...`),setTimeout(c,o),null)))};c()})))))).then((e=>(t.hideLoading(),{hex:e&&e.split(/\r?\n/)}))))).finally((()=>{t.hideLoading()}))}(s)),n[s.sha]}function o(t,n,i,s,r=10){return t.cacheStoreAsync(i,s).then((()=>t.cacheGetAsync(n))).then((s=>{let o;try{o=JSON.parse(s||"[]")}catch(e){console.error("invalid cache entry, clearing entry"),o=[]}o=o.filter((e=>e!=i)),o.unshift(i);let a=o.slice(r);return o=o.slice(0,r),e.U.promiseMapAll(a,(e=>t.cacheStoreAsync(e,"[]"))).then((()=>t.cacheStoreAsync(n,JSON.stringify(o))))}))}function a(e,t,n){return e.cacheGetAsync(t).then((i=>{let s;try{s=JSON.parse(i||"[]")}catch(n){return console.error("invalid cache entry, clearing entry"),e.cacheStoreAsync(t,"[]")}return s[0]!=n?(s=s.filter((e=>e!=n)),s.unshift(n),e.cacheStoreAsync(t,JSON.stringify(s))):null}))}t.showLoading=e=>{},t.hideLoading=()=>{},t.storeWithLimitAsync=o,t.recordGetAsync=a,t.getHexInfoAsync=function(t,n,i){if(!n.sha)return Promise.resolve(null);const l=s[n.sha];if(l)return Promise.resolve(l);e.debug("get hex info: "+n.sha);let c="hex-"+n.sha;return t.cacheGetAsync(c).then((i=>{let s;try{s=i?JSON.parse(i):null}catch(e){console.log("invalid cache entry, clearing entry"),s=null}return s&&s.hex?(e.debug("cache hit, size="+i.length),s.hex=function(t){let n=[];for(let i=0;i<t.length;i++){let s=/^([@!])(....)$/.exec(t[i]);if(!s){n.push(t[i]);continue}let r=parseInt(s[2],16),o=t[++i],a="";if("@"==s[1]){a="";let e=parseInt(o,16);for(;e-- >0;)a+="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"}else a=ts.pxtc.decodeBase64(o);e.Util.assert(a.length>0),e.Util.assert(a.length%16==0);for(let e=0;e<a.length;){let t=[16,r>>8&255,255&r,0];r+=16;for(let n=0;n<16;++n)t.push(a.charCodeAt(e++));let i=0;for(let e=0;e<t.length;++e)i+=t[e];t.push(255&-i);let s=":";for(let e=0;e<t.length;++e){let n=255&t[e];n<=15&&(s+="0"),s+=n.toString(16)}n.push(s.toUpperCase())}}return n}(s.hex),a(t,"hex-keys",c).then((()=>s))):r(n).then((e=>{let n=e.hex;e.hex=function(e){let t=[],n=0;for(let i=0;i<e.length;i+=n){let s=-1,r="";n=0;let o=!1;for(;n<500;){let a=/^:10(....)00(.{32})(..)$/.exec(e[i+n]);if(!a)break;let l=a[2],c=/^0+$/.test(l),u=parseInt(a[1],16);if(-1==s)o=c,t.push((o?"@":"!")+a[1]),s=u-16;else{if(c!=o)break;if(s+16!=u)break}o||(r+=l),s=u,n++}if(0==n)t.push(e[i]),n=1;else if(o)t.push(n.toString(16));else{let e="";for(let t=0;t<r.length;t+=2)e+=String.fromCharCode(parseInt(r.slice(t,t+2),16));t.push(ts.pxtc.encodeBase64(e))}}return t}(e.hex);let i=JSON.stringify(e);return e.hex=n,o(t,"hex-keys",c,i).then((()=>e))})).catch((t=>(e.reportException(t,{sha:n.sha}),Promise.resolve(null))))})).then((e=>(e&&(Object.keys(s).length>20&&(s={}),s[n.sha]=e),e)))}}(e.hexloader||(e.hexloader={}))}(pxt||(pxt={})),function(e){!function(t){t.KEY_VARIABLE="CROWDIN_KEY",t.testMode=!1,t.setTestMode=function(){e.crowdin.testMode=!0,e.log("CROWDIN TEST MODE - files will NOT be uploaded")},t.inContextLoadAsync=function(t){const n=document.createElement("input");n.type="text",n.setAttribute("class","hidden"),n.value=t;let i=new Promise(((i,s)=>{const r=new MutationObserver((()=>{if(t==n.value)return;const s=e.Util.rlf(n.value);n.remove(),r.disconnect(),i(s)}));r.observe(n,{attributes:!0})}));return document.body.appendChild(n),i}}(e.crowdin||(e.crowdin={}))}(pxt||(pxt={})),function(e){!function(t){function n(e){return e?e.split(/\r?\n/):[]}function i(e,t,i={}){i.ignoreWhitespace&&(e=e.replace(/[\r\n]+$/,""),t=t.replace(/[\r\n]+$/,""));const s=n(e),r=n(t),o=Math.min(i.maxDiffSize||1024,s.length+r.length);if(0==o)return[];const a=s.length>65520?Uint32Array:Uint16Array,l={};let c=0;const u=h(s),d=h(r);function h(e){const t=new a(e.length);let n=0;for(let s of e)i.ignoreWhitespace&&(s=s.replace(/\s+$/g,"").replace(/^\s+/g,"")),l.hasOwnProperty(s)?t[n]=l[s]:(++c,t[n]=c,l[s]=c),n++;return t}const p=new a(2*o+1);let f=-1;for(let e=0;e<=o;e++)null!=E(e,p)&&(f=e);if(-1==f)return null;const m=[];let g=null;for(let e=0;e<=f;e++){const t=m.length?m[m.length-1].slice(0):new a(2*f+1);if(m.push(t),g=E(e,t),null!=g)break}const b=[];let y=g;for(let e=m.length-1;e>=0;e--){const t=m[e];let n=0,i=0;y==-e||y!=e&&t[o+y-1]<t[o+y+1]?(i=y+1,n=t[o+i]):(i=y-1,n=t[o+i]+1);let a=n-y;for(let e=t[o+y]-n-1;e>=0;--e)b.push(" "+r[a+e]);i==y-1?b.push("- "+s[n-1]):a>0&&b.push("+ "+r[a-1]),y=i}if(b.reverse(),i.context==1/0||i.full)return b;let v=1,w=1,k=0;const x=[],A=i.context||3;for(;k<b.length;){let e=k;for(;e<b.length&&" "==b[e][0];)e++;if(e==b.length)break;const t=e-A,n=t-k;n>0&&(v+=n,w+=n,k=t);const i=x.length,s=v,r=w;x.push("@@");let o=k,a=0;for(;o<b.length;){if(" "==b[o][0]){if(a++,a>2*A+2){o-=A+2;break}}else a=0;o++}for(;k<o;){x.push(b[k]);switch(b[k][0]){case"-":v++;break;case"+":w++;break;case" ":v++,w++}k++}x[i]=`@@ -${s},${v-s} +${r},${w-r} @@`}return x;function E(e,t){for(let n=-e;n<=e;n+=2){let i=0;i=n==-e||n!=e&&t[o+n-1]<t[o+n+1]?t[o+n+1]:t[o+n-1]+1;let s=i-n;for(;i<u.length&&s<d.length&&u[i]==d[s];)i++,s++;if(t[o+n]=i,i>=u.length&&s>=d.length)return n}return null}}function s(e){return n(e).map((e=>e.replace(/;\s*$/,""))).join("\n")}function r(e){const t=/^@@ -(\d+),(\d+) \+(\d+),(\d+)/.exec(e);return t&&{oldStart:parseInt(t[1])-1,oldLength:parseInt(t[2]),newStart:parseInt(t[3])-1,newLength:parseInt(t[4])}}t.toLines=n,t.compute=i,t.diff3=function(t,s,r,o,a){const l=g(t),c=g(r);if(!l||!c)return;const u=n(t),d=n(r);let h=0,p=[],f=0,m=0;for(let t=0;t<l.length-1;)if(l[t]==f&&c[t]==m)p.push(u[f]),f++,m++,t++;else{let n=!0,i=!0,s=t;for(;s<l.length&&(l[s]!=f+s-t&&(n=!1),c[s]!=m+s-t&&(i=!1),null==l[s]||null==c[s]);)s++;if(e.U.assert(s<l.length),n)for(;m<c[s];)p.push(d[m++]);else if(i)for(;f<l[s];)p.push(u[f++]);else if(u.slice(f,l[s]).join("\n")==d.slice(m,c[s]).join("\n"))for(;f<l[s];)p.push(u[f++]);else{for(h++,p.push("<<<<<<< "+o);f<l[s];)p.push(u[f++]);for(p.push("=======");m<c[s];)p.push(d[m++]);p.push(">>>>>>> "+a)}t=s,f=l[s],m=c[s]}return{merged:p.join("\n"),numConflicts:h};function g(t){const n=i(s,t,{context:1/0});if(!n)return;const r=[];let o=0,a=0;for(let t of n)"+"==t[0]?o++:"-"==t[0]?(r[a]=null,a++):" "==t[0]?(r[a]=o,o++,a++):e.U.oops();return r.push(o+1),r}},t.removeTrailingSemiColumns=s,t.split=function(e,t){const n=e.split(/-{10,}/,2);if(n.length<2)return{fileA:e,fileB:void 0};let i=n[0].replace(/\n$/,""),r=n[1].replace(/^\n/,"");return t&&t.removeTrailingSemiColumns&&(i=s(i),r=s(r)),{fileA:i,fileB:r}},t.parseDiffMarker=r,t.render=function(t,n,s={}){const o=i(t,n,s);if(!o)return e.dom.el("div",null,pxtc.Util.lf("Too many differences to render diff."));const a={"@":"diff-marker"," ":"diff-unchanged","+":"diff-added","-":"diff-removed"};let l=0,c=0,u="";const d=e.dom.el("tbody"),h=e.dom.el("table",{class:"diffview "+(s.update?"update":"")},d);let p=null;return o.forEach(((t,n)=>{const h=r(t);h?(l=h.oldStart,c=h.newStart):("+"!=t[0]&&l++,"-"!=t[0]&&c++);const f=o[n+1]?o[n+1][0]:"",m=o[n+2]?o[n+2][0]:"",g=t.slice(2);let b=e.dom.el("code",null,g);if(p)b=p,p=null;else if(!("-"!=t[0]||" "!=u&&"@"!=u||"+"!=f||" "!=m&&"@"!=m&&""!=m)){const s=function(t,n){const s=i(t.split("").join("\n"),n.split("").join("\n"),{context:1/0});if(!s)return{a:e.dom.el("div",{class:"inline-diff"},e.dom.el("code",null,t)),b:e.dom.el("div",{class:"inline-diff"},e.dom.el("code",null,n))};const r=[],o=[];for(let t=0;t<s.length;){let n=t;const i=s[t][0];for(;s[n]&&s[n][0]==i;)n++;const a=s.slice(t,n).map((e=>e.slice(2))).join("");" "==i?(r.push(e.dom.el("code",{class:"ch-common"},a)),o.push(e.dom.el("code",{class:"ch-common"},a))):"-"==i?r.push(e.dom.el("code",{class:"ch-removed"},a)):"+"==i?o.push(e.dom.el("code",{class:"ch-added"},a)):e.Util.oops(),t=n}return{a:e.dom.el("div",{class:"inline-diff"},r),b:e.dom.el("div",{class:"inline-diff"},o)}}(t.slice(2),o[n+1].slice(2));b=s.a,p=s.b}if(u=t[0],s.hideMarkerLine&&"@"==u||s.hideRemoved&&"-"==u)return;const y="@"==u,v=`${a[u]}`;d.appendChild(e.dom.el("tr",{class:v},[!s.hideLineNumbers&&e.dom.el("td",{class:"line-a","data-content":l}),!s.hideLineNumbers&&e.dom.el("td",{class:"line-b","data-content":c}),y&&e.dom.el("td",{colspan:2,class:"change"},e.dom.el("code",null,t)),!s.hideMarker&&!y&&e.dom.el("td",{class:"marker","data-content":u}),!y&&e.dom.el("td",{class:"change"},b)]))})),h},t.resolveMergeConflictMarker=function(t,n,i,s){let r=e.diff.toLines(t),o=n;for(;o<r.length&&!/^<<<<<<<[^<]/.test(r[o]);)o++;let a=o+1;for(;a<r.length&&!/^=======$/.test(r[a]);)a++;let l=a+1;for(;l<r.length&&!/^>>>>>>>[^>]/.test(r[l]);)l++;if(l>=r.length)return e.debug(`diff marker mistmatch: ${r.length} -> ${o} ${a} ${l}`),t;if(r[o]=void 0,r[a]=void 0,r[l]=void 0,!i)for(let e=o;e<=a;++e)r[e]=void 0;if(!s)for(let e=a;e<=l;++e)r[e]=void 0;return r.filter((e=>void 0!==e)).join("\n")},t.mergeDiff3Config=function(t,n,i){let s=e.Util.jsonTryParse(t),r=e.Util.jsonTryParse(n),o=e.Util.jsonTryParse(i);if(s&&!o)return t;if(!s)return i||n;if(!r&&o&&(r=o),!s||!r||!o)return;delete s.installedVersion,delete r.installedVersion,delete o.installedVersion;const a={},l=e.U.unique(Object.keys(r).concat(Object.keys(s)).concat(Object.keys(o)),(e=>e));for(const t of l){const n=s[t],i=r[t],l=o[t];if(JSON.stringify(n)==JSON.stringify(l))void 0!==n&&(a[t]=n);else switch(t){case"name":a[t]=c(n,i,l);break;case"version":a[t]=e.semver.strcmp(n,l)>0?n:l;break;case"languageRestriction":case"preferredEditor":case"targetVersion":a[t]=n;break;case"public":a[t]=n&&l;break;case"files":case"testFiles":{const e=u(n||[],i||[],l||[]);if(!e)return;a[t]=e.length?e:void 0;break}case"dependencies":case"testDependencies":{const e=d(n||{},i||{},l||{});if(Object.keys(e).length)return;a[t]=e;break}case"description":if(n&&!l)a[t]=n;else{if(n||!l)return;a[t]=l}break;default:return}}return e.Package.stringifyConfig(a);function c(e,t,n){return e==t?n:n==t?e:e==lf("Untitled")?n:e}function u(t,n,i){const s=[],r=e.U.unique(n.concat(t).concat(i),(e=>e));for(const e of r){const r=t.indexOf(e)>-1,o=i.indexOf(e)>-1,a=n.indexOf(e)>-1;r==o||o==a?r&&s.push(e):o&&s.push(e)}return s}function d(t,n,i){const s={},r=e.U.unique(Object.keys(n).concat(Object.keys(t)).concat(Object.keys(i)),(e=>e));for(const o of r){const r=t[o],a=i[o],l=n[o];if(r==a)r&&(s[o]=r);else{const t=e.github.parseRepoId(r),n=e.github.parseRepoId(a);if(t&&n&&e.semver.tryParse(t.tag)&&e.semver.tryParse(n.tag)&&t.owner&&t.project&&t.owner==n.owner&&t.project==n.project){const i=e.semver.strcmp(t.tag,n.tag)>0?t.tag:n.tag;s[o]=`github:${t.owner}/${t.project}#${i}`}else a==l?r&&(s[o]=r):a&&(s[o]=a)}}return s}},t.hasMergeConflictMarker=function(e){return e&&/^(<<<<<<<[^<]|>>>>>>>[^>])/m.test(e)},t.reconstructConfig=function(t,n,i,s){let r={},o=i.tree.tree.map((e=>e.path)).filter((e=>/\.(ts|blocks|md|jres|asm|json)$/.test(e))).filter((t=>t!=e.CONFIG_NAME));return t.fileName&&(o=o.filter((e=>0===e.indexOf(t.fileName))).map((e=>e.slice(t.fileName.length+1)))),o.find((e=>/\.ts$/.test(e)))||(s.config.files.filter((e=>o.indexOf(e)<0)).forEach((e=>{o.push(e),n[e]=s.files[e]})),e.Util.jsonCopyFrom(r,s.config.dependencies)),Object.keys(r).length||(r[e.appTarget.corepkg]="*"),{name:"",files:o,dependencies:r,preferredEditor:o.find((e=>/.blocks$/.test(e)))?e.BLOCKS_PROJECT_NAME:e.JAVASCRIPT_PROJECT_NAME}}}(e.diff||(e.diff={}))}(pxt||(pxt={})),function(e){!function(t){t.extractSharedIdFromPostUrl=function(t){return e.Util.httpGetJsonAsync(t+".json").then((t=>t.post_stream&&t.post_stream.posts&&t.post_stream.posts[0]&&t.post_stream.posts[0].link_counts.map((t=>e.Cloud.parseScriptId(t.url))).filter((e=>!!e))[0]))},t.topicsByTag=function(t,n){const i=`${t=t.replace(/\/$/,"")}/tag/${n}.json`;return e.Util.httpGetJsonAsync(i).then((n=>{const i=e.Util.toDictionary(n.users,(e=>e.id.toString()));return n.topic_list.topics.map((e=>({id:e.id,title:e.title,url:`${t}/t/${e.slug}/${e.id}`,imageUrl:e.image_url,author:i[e.posters[0].user_id].username,cardType:"forumUrl"})))}))}}(e.discourse||(e.discourse={}))}(pxt||(pxt={})),function(e){!function(t){var n=pxtc.Util;let i,s={},r={};const o="\x3c!-- @CMD@ @ARGS@ --\x3e";let a={parent:o,short:o,description:"\x3c!-- desc --\x3e",activities:"\x3c!-- activities --\x3e",explicitHints:"\x3c!-- hints --\x3e",flyoutOnly:"\x3c!-- flyout --\x3e",hideIteration:"\x3c!-- iter --\x3e",codeStart:"\x3c!-- start --\x3e",codeStop:"\x3c!-- stop --\x3e",autoOpen:"\x3c!-- autoOpen --\x3e",autoexpandOff:"\x3c!-- autoexpandOff --\x3e",preferredEditor:"\x3c!-- preferredEditor --\x3e"};function l(e,t,n){return e.split(t).join(n)}function c(e){return e=l(e,"&","&amp;"),e=l(e,"<","&lt;"),e=l(e,">","&gt;"),e=l(e,'"',"&quot;"),e=l(e,"'","&#39;")}function u(e){return e?c(e.replace(/\&([#a-z0-9A-Z]+);/g,((e,t)=>{switch(t){case"amp":return"&";case"lt":return"<";case"gt":return">";case"quot":return'"';default:return"#"==t[0]?String.fromCharCode(parseInt(t.slice(1))):e}}))):e}t.htmlQuote=c,t.html2Quote=u;const d=[{rx:/^vimeo\.com\/(\d+)/i,cmd:"### @vimeo $1"},{rx:/^(www\.youtube\.com\/watch\?v=|youtu\.be\/)([\w\-]+(\#t=([0-9]+m[0-9]+s|[0-9]+m|[0-9]+s))?)/i,cmd:"### @youtube $2"}];t.requireMarked=()=>"undefined"!=typeof marked?marked:"undefined"!=typeof require?require("marked"):void 0,t.requireDOMSanitizer=()=>"undefined"!=typeof DOMPurify?DOMPurify.sanitize:"undefined"!=typeof require?require("DOMPurify").sanitize:void 0;const h=e=>`<div class='ui negative message'>${c(e)}</div>`;function p(e){let t=n.clone(s),i=n.clone(r),o=n.clone(a),l={},c={},d=e.params,p=e.theme;e.boxes=t,e.macros=i,e.settings=o,e.html=e.html.replace(/<aside\s+([^<>]+)>([^]*?)<\/aside>/g,((e,n,s)=>{let r=function(e){let t={};for(;e.trim();){let n=/\s*([^=\s]+)=("([^"]*)"|'([^']*)'|(\S*))/.exec(e);if(n){let e=n[3]||n[4]||n[5]||"";t[n[1].toLowerCase()]=e}else n=/^\s*(\S+)/.exec(e),t[n[1]]="true";e=e.slice(n[0].length)}return t}(n),a=r["data-name"]||r.id;return a?(/box/.test(r.class)?t[a]=s:/aside/.test(r.class)?t[a]=`\x3c!-- BEGIN-ASIDE ${a} --\x3e${s}\x3c!-- END-ASIDE --\x3e`:/setting/.test(r.class)?o[a]=s:/menu/.test(r.class)?l[a]=s:/toc/.test(r.class)?c[a]=s:i[a]=s,`\x3c!-- macro ${a} --\x3e`):h("id or data-name missing on macro")}));let f=(e,t)=>{let n=l.item,i={NAME:e.name};if(e.subitems)n=l["toc-dropdown"]?l["toc-dropdown"]:0==t?l["top-dropdown"]:l["inner-dropdown"],i.ITEMS=e.subitems.map((e=>f(e,t+1))).join("\n");else{if(/^-+$/.test(e.name)&&(n=l.divider),e.path&&!/^(https?:|\/)/.test(e.path))return h("Invalid link: "+e.path);i.LINK=e.path}return g(n,i,["ITEMS"])},m=[{name:lf("Docs"),href:"/docs"}];const b=e.TOC||p.TOC||[];let y=[],v=t=>{for(let e of t.subitems||[])if(v(e))return y.push(t),!0;return!(!e.filepath||!t.path||0!=e.filepath.indexOf(t.path))&&(y.push(t),!0)};b.forEach(v);let w=(t,n)=>{let i=c.item,s={NAME:t.name};return t.path&&!/^(https?:|\/)/.test(t.path)?h("Invalid link: "+t.path):(/^\//.test(t.path)&&e.versionPath&&(t.path=`/${e.versionPath}${t.path}`),s.LINK=t.path,y.indexOf(t)>=0?(s.ACTIVE="active",s.EXPANDED="true",m.push({name:t.name,href:t.path})):s.EXPANDED="false",t.subitems&&t.subitems.length>0?(i=c["toc-dropdown"]?""!==t.name?c["toc-dropdown"]:c["toc-dropdown-noLink"]:0==n?""!==t.name?c["top-dropdown"]:c["top-dropdown-noHeading"]:1==n?c["inner-dropdown"]:c["nested-dropdown"],s.ITEMS=t.subitems.map((e=>w(e,n+1))).join("\n")):/^-+$/.test(t.name)&&(i=c.divider),g(i,s,["ITEMS"]))};d.menu=(p.docMenu||[]).map((e=>f(e,0))).join("\n"),d.TOC=b.map((e=>w(e,0))).join("\n"),p.appStoreID&&(d.appstoremeta=`<meta name="apple-itunes-app" content="app-id=${n.htmlEscape(p.appStoreID)}"/>`);let k="";m.length>1&&(k=`\n <nav class="ui breadcrumb" aria-label="${lf("Breadcrumb")}">\n ${m.map(((e,t)=>`<a class="${t==m.length-1?"active":""} section"\n href="${u(e.href)}" aria-current="${t==m.length-1?"page":""}">${u(e.name)}</a>`)).join('<i class="right chevron icon divider"></i>')}\n </nav>`),d.breadcrumb=k,p.boardName&&(d.boardname=u(p.boardName)),p.boardNickname&&(d.boardnickname=u(p.boardNickname)),p.driveDisplayName&&(d.drivename=u(p.driveDisplayName)),p.homeUrl&&(d.homeurl=u(p.homeUrl)),d.targetid=p.id||"???",d.targetname=p.name||"Microsoft MakeCode",d.docsheader=p.docsHeader||"Documentation",d.orgtitle="MakeCode";const x=p.docsLogo&&n.htmlEscape(p.docsLogo),A=(p.organizationWideLogo||p.organizationLogo)&&n.htmlEscape(p.organizationWideLogo||p.organizationLogo),E=p.organizationLogo&&n.htmlEscape(p.organizationLogo);d.targetlogo=x?`<img aria-hidden="true" role="presentation" class="ui ${p.logoWide?"small":"mini"} image" src="${x}" />`:"",d.orglogo=A?`<img aria-hidden="true" role="presentation" class="ui image" src="${A}" />`:"",d.orglogomobile=E?`<img aria-hidden="true" role="presentation" class="ui image" src="${E}" />`:"";let T=e.ghEditURLs||[];if(T.length){let e='<p style="margin-top:1em">\n',t=lf("Edit this page on GitHub");for(let n of T)e+=`<a href="${n}"><i class="write icon"></i>${t}</a><br>\n`,t=lf("Edit template of this page on GitHub");e+="</p>\n",d.github=e}else d.github="";const S=`\n <a href="#maincontent" class="ui item link" tabindex="0" role="menuitem">${lf("Skip to main content")}</a>\n `;d.accMenu=S;const C=lf("Print this page"),I=`\n <button id="printbtn" class="circular ui icon right floated button hideprint" title="${C}" aria-label="${C}">\n <i class="icon print"></i>\n </button>\n `;d.printBtn=I;const _=`\n <a id="togglesidebar" class="launch icon item" tabindex="0" title="Side menu" aria-label="${lf("Side menu")}" role="menuitem" aria-expanded="false">\n <i class="content icon"></i>\n </a>\n `;d.sidebarToggle=_;const P=["tocsearch1","tocsearch2"].map((e=>`\n <input type="search" name="q" placeholder="${lf("Search...")}" aria-label="${lf("Search Documentation")}">\n <i onclick="document.getElementById('${e}').submit();" tabindex="0" class="search link icon" aria-label="${lf("Search")}" role="button"></i>\n `));d.searchBar1=P[0],d.searchBar2=P[1];let U="";p.accentColor&&(U+=`\n.ui.accent { color: ${p.accentColor}; }\n.ui.inverted.accent { background: ${p.accentColor}; }\n`),d.targetstyle=U,d.tocclass=p.lightToc?"lighttoc":"inverted";for(let e of Object.keys(p)){let t=p[e];void 0===d[e]&&"string"==typeof t&&(d[e]=t)}e.finish=()=>g(e.html,d,["body","menu","accMenu","TOC","prev","next","printBtn","breadcrumb","targetlogo","orglogo","orglogomobile","github","JSON","appstoremeta","sidebarToggle","searchBar1","searchBar2"])}function f(e){e.image=function(e,t,n){var i,s;if(e.startsWith("youtube:")){return'<div class="tutorial-video-embed"><iframe class="yt-embed" src="https://www.youtube.com/embed/'+e.split(":").pop()+'" title="'+n+'" frameborder="0" allowFullScreen allow="autoplay; picture-in-picture"></iframe></div>'}if(e.startsWith("azuremedia:")){let t=e.split(":")[1];const n=t.split("?");let r,o;if(n[1]){t=n[0];const e=n[1];r=null===(i=/start(?:time)?=(\d+)/i.exec(e))||void 0===i?void 0:i[1],o=null===(s=/end(?:time)?=(\d+)/i.exec(e))||void 0===s?void 0:s[1]}const a=new URL(`https://makecodeprodmediaeastus-usea.streaming.media.azure.net/${t}/manifest(format=mpd-time-csf).mpd`);return r&&(a.hash=`t=${r}`,a.searchParams.append("startTime",r)),o&&a.searchParams.append("endTime",o),`<div class="tutorial-video-embed"><video class="ams-embed" controls src="${a.toString()}" /></div>`}{let i='<img class="ui image" src="'+e+'" alt="'+n+'"';return t&&(i+=' title="'+t+'"'),i+=' loading="lazy"',i+=this.options.xhtml?"/>":">",i}},e.listitem=function(e){const t=/^\s*\[( |x)\]/i.exec(e);return t?`<li class="${" "==t[1]?"unchecked":"checked"}">`+e.slice(t[0].length)+"</li>\n":"<li>"+e+"</li>\n"},e.heading=function(e,t,n){let i=/(.*)#([\w\-]+)\s*$/.exec(e),s="";return i&&(e=i[1],s=i[2]),e&&(e=e.replace(/@(fullscreen|unplugged|showdialog|showhint)/gi,"")),e.match(/\{([\s\S]+)\}/)&&(e=e.match(/\{([\s\S]+)\}/)[1].trim()),""===s&&(s=e.toLowerCase().replace(/[^\w]+/g,"-")),`<h${t} id="${this.options.headerPrefix}${s}">${e}</h${t}>`}}function m(e,t){return e.replace(/<!--\s*@(ifn?def)\s+(\w+)\s*-->([^]*?)<!--\s*@endif\s*-->/g,((e,n,i,s)=>"ifdef"==n&&t[i]||"ifndef"==n&&!t[i]?`\x3c!-- ${n} ${i} --\x3e${s}\x3c!-- endif --\x3e`:`\x3c!-- ${n} ${i} endif --\x3e`))}function g(e,t,i=[]){return e?e.replace(/@(\w+)@/g,((e,s)=>{let r=n.lookup(t,s)||"";return r+="",i.indexOf(s)<0&&(r=u(r)),r})):""}t.prepTemplate=p,t.setupRenderer=f,t.renderConditionalMacros=m,t.renderMarkdown=function(e){let s=!0;e.pubinfo||(s=!1,e.pubinfo={});let r=e.pubinfo;if(e.theme||(e.theme={}),delete e.pubinfo.private,r.time){let e=parseInt(r.time);r.timems||(r.timems=1e3*e+""),r.humantime||(r.humantime=n.isoTime(e))}r.name&&(r.dirname=r.name.replace(/[^A-Za-z0-9_]/g,"-"),r.title=r.name),s&&(r.JSON=JSON.stringify(r,null,4).replace(/</g,"\\u003c"));let o=e.template;o=o.replace(/<!--\s*@include\s+(\S+)\s*-->/g,((t,n)=>"\x3c!-- include "+n+" --\x3e\n"+((e.theme.htmlDocIncludes||{})[n]||"")+"\n\x3c!-- end include --\x3e\n")),o=m(o,r),e.locale&&(o=y(o,e.locale).text);let a={html:o,theme:e.theme,filepath:e.filepath,versionPath:e.versionPath,ghEditURLs:e.ghEditURLs,params:r,TOC:e.TOC};p(a),i||(i=t.requireMarked());let l=new i.Renderer;f(l);const c=l.link;l.link=function(e,t,n){const i=new RegExp("^[/#]").test(e),s=i?"":"_blank";i&&a.versionPath&&(e=`/${a.versionPath}${e}`);return c.call(l,e,t,n).replace(/^<a /,`<a ${s?`target="${s}"`:""} rel="nofollow noopener" `)};let b=t.requireDOMSanitizer();i.setOptions({renderer:l,gfm:!0,tables:!0,breaks:!1,pedantic:!1,sanitize:!0,sanitizer:b,smartLists:!0,smartypants:!0});let v=e.markdown;e.repo&&(v+=`\n\`\`\`package\n${e.repo.name.replace(/^pxt-/,"")}=github:${e.repo.fullName}#${e.repo.tag||"master"}\n\`\`\`\n`),v=v.replace(/^\s*https?:\/\/(\S+)\s*$/gm,((e,t)=>{for(let e of d){let n=e.rx.exec(t);if(n)return e.cmd.replace(/\$(\d+)/g,((e,t)=>n[parseInt(t)]||""))+"\n"}return e})),v=v.replace(/@([a-z]+)@/gi,((t,i)=>{let s=r[i];return!s&&e.throwOnError&&n.userError(`unknown macro ${i}`),s||"unknown macro"}));let w=i(v);w=w.replace(/&lt;br\s*\/&gt;/gi,"<br/>"),w=w.replace(/(<img [^>]* src=")\/docs\/static\/([^">]+)"/g,((e,t,n)=>t+"/static/"+n+'"'));let k="",x=0;function A(e,t,n){let i=n;return e<=x&&(i=k+i,k="",x=0),i}if(w=w.replace(/<h(\d)[^>]+>\s*([~@])?\s*(.*?)<\/h\d>/g,((t,i,s,o)=>{let l=/^(\w+)\s+(.*)/.exec(o),c=l?l[1]:o,d=l?l[2]:"";if(d=u(d),c=u(c),i=parseInt(i),s){if("@"==s){let t=n.lookup(a.settings,c);if(null!=t)r[c]=d;else if(t=n.lookup(a.macros,c),null==t)return e.throwOnError&&n.userError(`Unknown command: @${c}`),h(`Unknown command: @${c}`);return A(i,0,g(t,{ARGS:d,CMD:c},["ARGS","CMD"]))}{if(!c){let e=k;return k="",e}let t=n.lookup(a.boxes,c);if(t){let e=t.split("@BODY@"),n=A(i,0,e[0].replace("@ARGS@",d));k=e[1];let s=t.match(/data-[^>\s]+/gi);return s&&s.indexOf("data-inferred")>=0&&(x=i),n}return e.throwOnError&&n.userError(`Unknown box: ~ ${c}`),h(`Unknown box: ~ ${c}`)}}return A(i,0,t)})),k&&(w+=k),!r.title){let e=/<h1[^<>]*>([^<>]+)<\/h1>/.exec(w);e&&(r.title=u(e[1]))}if(!r.description){let e=/<p>([^]+?)<\/p>/.exec(w);e&&(r.description=u(e[1]))}const E=/<div class="ui embed mdvid"[^<>]+?data-placeholder="([^"]+)"[^>]*\/?>/i.exec(w)||/<img class="ui [^"]*image" src="([^"]+)"[^>]*\/?>/i.exec(w);E&&(r.cardLogo=u(E[1])),r.twitter=u(e.theme.twitter||"@msmakecode");let T={main:""};w=w.replace(/<!-- BEGIN-ASIDE (\S+) -->([^]*?)<!-- END-ASIDE -->/g,((e,t,i)=>{let s=n.lookup(T,t);return T[t]=(s||"")+i,"\x3c!-- aside --\x3e"})),w=w.replace(/\n<\/code>/g,"</code>"),T.main=w,w="";for(let e of Object.keys(T))w+=(S=e+"-container",C=T[e],g(a.boxes[S]||"@BODY@",{BODY:C},["BODY"]));var S,C;r.body=w,r.name=r.title||"";for(let t of Object.keys(e.theme)){let n=e.theme[t];"string"==typeof n&&(r["theme_"+t]=n)}return a.finish()},t.embedUrl=function(e,t,n,i){return`<div style="position:relative;height:0;padding-bottom:70%;overflow:hidden;"><iframe style="position:absolute;top:0;left:0;width:100%;height:100%;" src="${`${e}#${t}:${n}`}" frameborder="0" sandbox="allow-popups allow-forms allow-scripts allow-same-origin"></iframe></div>`},t.runUrl=function(e,t,n){return`<div style="position:relative;height:0;padding-bottom:${t};overflow:hidden;"><iframe style="position:absolute;top:0;left:0;width:100%;height:100%;" src="${e}?id=${encodeURIComponent(n)}" allowfullscreen="allowfullscreen" sandbox="allow-popups allow-forms allow-scripts allow-same-origin" frameborder="0"></iframe></div>`},t.codeEmbedUrl=function(e,t,n){const i=`${e}---codeembed#pub:${t}`;return`<div style="position:relative;height:calc(${n=Math.ceil(n||300)}px + 5em);width:100%;overflow:hidden;"><iframe style="position:absolute;top:0;left:0;width:100%;height:100%;" src="${i}" allowfullscreen="allowfullscreen" frameborder="0" sandbox="allow-scripts allow-same-origin"></iframe></div>`};const b={b:1,strong:1,em:1};function y(e,t){const i={};function s(e){let s=/^(\s*)([^]*?)(\s*)$/.exec(e),r=s[2].replace(/\s+/g," ");if(""==r||/^((IE=edge,.*|width=device-width.*|(https?:\/\/|\/)[\w@\/\.]+|@[\-\w]+@|\{[^\{\}]+\}|[^a-zA-Z]*|(&nbsp;)+)\s*)+$/.test(r))return null;let o=n.lookup(t,r);return o?r=o:i[r]="",s[1]+r+s[3]}function r(e){return e.replace(/&llt;/g,"<").replace(/&ggt;/g,">")}return{text:e=(e=(e=(e="<start>"+(e=e.replace(/<([\/\w]+)([^<>]*)>/g,((e,t,n)=>{let i=t.replace(/^\//,"").toLowerCase();return 1===b[i]?"&llt;"+t+n+"&ggt;":e})))).replace(/(<([\/\w]+)([^<>]*)>)([^<>]+)/g,((e,t,n,i,o)=>{if("script"==n||"style"==n)return r(e);let a=s(r(o));return null==a?r(e):t+a}))).replace(/(<[^<>]*)(content|placeholder|alt|title)="([^"]+)"/g,((e,t,n,i)=>null==s(i)?e:t+n+'="'+i.replace(/"/g,"''")+'"'))).replace(/^<start>/g,""),missing:i}}function v(e,t){if(e.id==t)return e;for(let n of e.children){let e=v(n,t);if(e)return e}return null}function w(e,t){let n=0,i=[{level:0,id:"",title:"",start:n,text:"",children:[]}],s=(e=e.replace(/\r/g,"")).split(/\n/),r={};for(let e of s){let s=/^\s*(#+)\s*(.*?)(#(\S+)\s*)?$/.exec(e),o=null;if(t&&s)if(s[4])if(r[s[4]])s=null;else{o=v(t,s[4]);let e=t=>{t.id&&(r[t.id]=!0),t.children.forEach(e)};o&&e(o)}else s=null;if(s){let r={level:t?1:s[1].length,title:s[2].trim(),id:s[4]||"",start:n,text:"",children:[]};if(o){e="";for(let t=0;t<o.level;++t)e+="#";e+=" ",e+=r.title||o.title,e+=" #"+r.id}for(;i[i.length-1].level>=r.level;)i.pop();i[i.length-1].children.push(r),i.push(r)}i[i.length-1].text+=e+"\n",n++}return i[0]}t.translate=y,t.buildTOC=function(n){if(!n)return null;const i=e.docs.requireMarked(),s=t.requireDOMSanitizer(),r={renderer:new i.Renderer,gfm:!0,tables:!1,breaks:!1,pedantic:!1,sanitize:!0,sanitizer:s,smartLists:!1,smartypants:!1};let o={name:"dummy",subitems:[]},a=[];a.push(o);let l=i.lexer(n,r),c=!1;l.forEach((e=>{switch(e.type){case"heading":e.depth;break;case"list_start":break;case"list_item_start":case"loose_item_start":c=!0;let t={name:"",path:"",subitems:[]};return void a.push(t);case"text":let n=a[a.length-1];e.text.indexOf("[")>=0?e.text.replace(/\[(.*?)\]\((.*?)\)/i,(function(e,t,i){n.name=t,n.path=i.replace(".md","")})):c&&(n.name=e.text);break;case"list_item_end":case"loose_item_end":let i=a.pop();a[a.length-1].subitems.push(i)}c=!1}));let u=o.subitems;return u&&0!=u.length?u:null},t.visitTOC=function(e,t){e.forEach((function(e){t(e),e.subitems&&e.subitems.forEach(t)}))};let k=!1;function x(e,t){if(k||function(){function e(e,t,n){let i=x(e,t).trim();if(i!=(n=n.trim()))throw console.log(`*** Template:\n${e}\n*** Input:\n${t}\n*** Expected:\n${n}\n*** Output:\n${i}`),new Error("augment docs test fail")}k=!0;let t="\n# T0\n## Examples #ex\n### Example 1\nTEx1\n### Example 2 #ex2\nTEx2\n### Example 3\nTEx3\n\n## See also #also\nTAlso\n",n="\n# @extends\n# #ex2\nMy example\n## See Also These! #also\nMy links\n",i="\n# T0\n## Examples #ex\n### Example 1\nTEx1\n### Example 2 #ex2\nMy example\n### Example 3\nTEx3\n\n## See Also These! #also\nMy links\n",s="\n# @extends\n### #ex\nFoo\n#### Example 1\nEx1\n#### Example 2x #ex2\nEx2\n## See Also These! #also\nMy links\n",r="\n# T0\n## Examples #ex\nFoo\n#### Example 1\nEx1\n#### Example 2x #ex2\nEx2\n## See Also These! #also\nMy links\n";e(t,"",t),e(t," ",t),e(t,n,i),e(t,s,r)}(),!t)return e;let i=w(e,null),s=w(t,i),r={},o={};for(let e of s.children)n.assert(0==e.children.length),n.assert(!!e.id),r[e.id]=e.text;let a=e=>{e.id&&void 0!==r[e.id]&&(o[e.id]=!0,e.text=r[e.id],e.children=[]),e.children.forEach(a)};a(i);let l="",c=e=>{l+=e.text,e.children.forEach(c)};c(i);let u="",d=s.text.replace(/^\s*#+\s*@extends.*/gm,"").replace(/^\s*\n/gm,"");d.trim()&&(u+=d.trim()+"\n");for(let e of s.children)o[e.id]||(u+=e.text);return u&&(l+="## Couldn't apply replacement logic to:\n"+u),l}t.augmentDocs=x}(e.docs||(e.docs={}))}(pxt||(pxt={})),function(e){!function(e){e.el=function(e,t,n){const i=document.createElement(e);return t&&Object.keys(t).forEach((e=>i.setAttribute(e,t[e]+""))),function e(t){Array.isArray(t)?t.forEach((t=>e(t))):"string"==typeof t?i.appendChild(document.createTextNode(t)):t instanceof HTMLElement&&i.appendChild(t)}(n),i}}(e.dom||(e.dom={}))}(pxt||(pxt={})),function(e){!function(t){function n(e){const t=/```package\s+((.|\s)+?)\s*```/i.exec(e);let n;return t&&(n={},t[1].split("\n").map((e=>e.replace(/\s*/g,""))).filter((e=>!!e)).map((e=>e.split("="))).forEach((e=>n[e[0]]=e[1]||"*"))),n}function i(e){const t=/```config\s+((.|\s)+?)\s*```/i.exec(e);let n=[];return t&&t[1].split("\n").map((e=>e.replace(/\s*/g,""))).filter((e=>!!e)).map((e=>e.split("="))).filter((e=>"feature"==e[0]&&!!e[1])).forEach((e=>n.push(e[1]))),n.length?n:void 0}function s(t){const n=/```jres\s+((.|\s)+?)\s*```/i.exec(t);if(n){const t=n[1],i=JSON.parse(t);return{jres:t,ts:e.emitTilemapsFromJRes(i)}}}function r(t){const n=/```assetjson\s+((.|\s)+?)\s*```/i.exec(t);return n?e.tutorial.parseAssetJson(n[1]):{}}function o(t){const n=/```simtheme\s+([\s\S]*?)```/i.exec(t);return n?e.tutorial.parseSimThemeJson(n[1]):{}}function a(t){let n=e.Util.jsonTryParse(t);return n&&!Array.isArray(n)&&(n=[n]),(null==n?void 0:n.length)?n:(n=t.split(/^---$/gm).filter((e=>!!e)).map((e=>{let t={};return e.replace(/^\s*(?:-|\*)\s+(\w+)\s*:\s*(.*)$/gm,((e,n,i)=>{if("flags"==n)t[n]=i.split(",");else if("otherAction"===n){const e=i.split(",").map((e=>null==e?void 0:e.trim()));(t.otherActions||(t.otherActions=[])).push({url:e[0],editor:e[1],cardType:e[2]})}else t[n]=i;return""})),!!Object.keys(t).length&&t})).filter((e=>!!e)),(null==n?void 0:n.length)?n:void 0)}function l(t){if(!t)return[];const n=[];let i,s=!1,r="";return t.split(/\r?\n/).forEach((t=>{if(/^## /.test(t))i=t.substr(2).trim();else if(/^(### ~ |```)codecard$/.test(t))s=!0;else if(/^(### ~|```)$/.test(t)){if(s=!1,i&&r){const t=a(r);(null==t?void 0:t.length)?n.push({name:i,cards:t}):e.log("invalid gallery format")}r="",i=void 0}else s&&(r+=t+"\n")})),n.forEach((t=>t.cards.forEach((t=>{if(t.otherActions&&!t.otherActions.length&&("tutorial"==t.cardType||"example"==t.cardType)){const n=["js"];e.appTarget.appTheme.python&&n.unshift("py"),t.otherActions=n.map((e=>({url:t.url,cardType:t.cardType,editor:e})))}})))),n}t.parsePackagesFromMarkdown=n,t.parseFeaturesFromMarkdown=i,t.parseJResFromMarkdown=s,t.parseTemplateProjectJSON=r,t.parseSimThemeJSON=o,t.parseExampleMarkdown=function(t,a){if(!a)return;const l=/```(blocks?|typescript|python|spy|sim)\s+((.|\s)+?)\s*```/i.exec(a);if(!l)return;const c=n(a),u=l[1],d=l[2],h=i(a),p=s(a),f=o(a),m={name:t,filesOverride:{[e.MAIN_BLOCKS]:'<xml xmlns="http://www.w3.org/1999/xhtml"></xml>',["python"===l[1]?e.MAIN_PY:e.MAIN_TS]:d},dependencies:c,features:h,snippetType:u,source:d,simTheme:f};return m.filesOverride=Object.assign(Object.assign({},m.filesOverride),r(a)),p&&(m.filesOverride[e.TILEMAP_JRES]=p.jres,m.filesOverride[e.TILEMAP_CODE]=p.ts),m},t.parseCodeCards=a,t.parseCodeCardsHtml=function(t){let n,i=[];return Array.from(t.children).forEach((e=>{"UL"===e.tagName||"OL"===e.tagName?(n||(n={}),Array.from(e.querySelectorAll("li")).forEach((e=>{const t=e.innerText,i=/^\s*(\w+)\s*:\s*(.*)$/.exec(t);if(i){const e=i[1];n[e]=i[2].trim(),"flags"===e&&(n[e]=n[e].split(/,\s*/))}}))):"HR"==e.tagName&&(n&&i.push(n),n=void 0)})),n&&i.push(n),0===i.length&&"CODE"===t.tagName&&(i=e.Util.jsonTryParse(t.textContent)),!!(null==i?void 0:i.length)&&i},t.parseGalleryMardown=l,t.loadGalleryAsync=function(t){return e.Cloud.markdownAsync(t).then((e=>l(e)))},t.codeCardsToMarkdown=function(e){return`### ~ codecard\n\n${(e||[]).map((e=>Object.keys(e).filter((t=>!!e[t])).map((t=>"otherActions"===t?e[t].map((e=>`* otherAction: ${e.url}, ${e.editor||""}, ${e.cardType||""}`)).join("\n"):`* ${t}: ${e[t]}`)).join("\n"))).join("\n\n---\n\n")}\n\n### ~\n`}}(e.gallery||(e.gallery={}))}(pxt||(pxt={})),function(e){e.GDBServer=class{constructor(t){this.io=t,this.q=new e.U.PromiseQueue,this.dataBuf="",this.numSent=0,this.pktSize=400,this.trace=!1,this.bmpMode=!0,this.targetInfo="",this.onEvent=e=>{},this.io.onData=e=>this.onData(e)}onData(t){for(this.dataBuf+=e.U.uint8ArrayToString(t);this.dataBuf.length>0;){let e=this.dataBuf[0];if("+"==e)this.dataBuf=this.dataBuf.slice(1);else if("$"==e||"%"==e){let t=this.decodeResp(this.dataBuf.slice(1));if(null==t)break;"$"==e?(this.io.sendPacketAsync(this.buildCmd("+")),this.onResponse?this.onResponse(t):this.numSent>0&&this.io.error("unexpected response: "+t)):this.onEvent(t)}else this.io.error("invalid character: "+e)}}buildCmd(t){if("+"==t)return e.U.stringToUint8Array(t);let n="";for(let e=0;e<t.length;++e){let i=t.charAt(e);"}"==i||"#"==i||"$"==i?(n+="}",n+=String.fromCharCode(32^i.charCodeAt(0))):n+=i}let i=0;t=n;for(let e=0;e<t.length;++e)i=i+t.charCodeAt(e)&255;return n="$"+t+"#"+("0"+i.toString(16)).slice(-2),e.U.stringToUint8Array(n)}decodeResp(e){let t="";for(let n=0;n<e.length;++n){let i=e[n];if("}"==i)++n,t+=String.fromCharCode(32^e.charCodeAt(n));else if("*"==i){++n;let i=e.charCodeAt(n)-29,s=t.charAt(t.length-1);for(;i-- >0;)t+=s}else{if("#"==i){return 2==e.slice(n+1,n+3).length?(this.dataBuf=e.slice(n+3),t):null}t+=i}}return null}sendCmdOKAsync(e){return this.sendCmdAsync(e,(e=>"OK"==e))}error(e){this.io.error(e),this.io.disconnectAsync()}sendCmdAsync(t,n){this.numSent++;const i=this.buildCmd(t);return this.q.enqueue("one",(()=>null===n?this.io.sendPacketAsync(i).then((()=>null)):new Promise((s=>{this.onResponse=i=>{this.onResponse=null,this.trace&&e.log(`GDB: '${t}' -> '${i}'`),void 0===n||n(i)||this.error(`Invalid GDB command response: '${t}' -> '${i}'`),s(i)},this.io.sendPacketAsync(i)}))))}sendRCmdAsync(t){return this.sendMCmdAsync("qRcmd,"+(n=t,e.U.toHex(e.U.stringToUint8Array(n))));var n}sendMCmdAsync(t){this.numSent++;const n=this.buildCmd(t);let i="";return this.q.enqueue("one",(()=>new Promise((s=>{this.onResponse=n=>{var r;"OK"!=n&&"O"==n[0]?i+=(r=n.slice(1),e.U.uint8ArrayToString(e.U.fromHex(r))):("OK"!=n&&(i+=" - "+n),this.onResponse=null,this.trace&&e.log(`Final GDB: '${t}' -> '${i}'`),s(i))},this.io.sendPacketAsync(n)}))))}write32Async(t,n){let i=new Uint8Array(4);return e.HF2.write32(i,0,n),this.writeMemAsync(t,i)}writeMemAsync(t,n){const i=this.pktSize/2-10;return e.U.assert(n.length<i),this.sendCmdOKAsync("M"+t.toString(16)+","+n.length.toString(16)+":"+e.U.toHex(n)).then((e=>{console.log(e)}))}readMemAsync(t,n){const i=this.pktSize/2-6;if(n>i){const s=new Uint8Array(n),r=o=>{const a=Math.min(n-o,i);return 0==a?Promise.resolve(s):this.readMemAsync(t+o,a).then((t=>(e.U.memcpy(s,o,t),r(o+a))))};return r(0)}return this.sendCmdAsync("m"+t.toString(16)+","+n.toString(16)).then((t=>e.U.fromHex(t)))}initBMPAsync(){return Promise.resolve().then((()=>this.sendRCmdAsync("swdp_scan"))).then((e=>(this.targetInfo=e,this.sendCmdAsync("vAttach;1",(e=>"T"==e[0]))))).then((()=>{}))}initAsync(){return e.U.delay(1e3).then((()=>this.sendCmdAsync("!"))).then((()=>this.sendCmdAsync("qSupported"))).then((t=>{let n={};return t=(t=";"+t+";").replace(/;([^;]+)[=:]([^:;]+)/g,((e,t,i)=>(n[t]=i,";"))),this.pktSize=parseInt(n.PacketSize)||1024,e.log("GDB-server caps: "+JSON.stringify(n)+" "+t.replace(/;+/g,";")),this.bmpMode?this.initBMPAsync():this.sendCmdAsync("c").then((()=>{}))}))}}}(pxt||(pxt={})),function(e){!function(t){function n(){var n,i;return!!t.forceProxy||!e.U.isNodeJS&&!(null===(i=null===(n=null==e?void 0:e.appTarget)||void 0===n?void 0:n.cloud)||void 0===i?void 0:i.noGithubProxy)}t.token=null,t.forceProxy=!1;const i={};function s(n){var i;return n.method=null!==(i=n.method)&&void 0!==i?i:"GET",function i(s){var r;const o=e.U.clone(n);t.token&&(o.headers||(o.headers={}),o.url==U?o.headers.Authorization=`bearer ${t.token}`:(o.url=e.BrowserUtils.cacheBustingUrl(o.url),o.headers.Authorization=`token ${t.token}`));return o.allowHttpErrors=null!==(r=o.allowHttpErrors)&&void 0!==r&&r,e.U.requestAsync(o).catch((n=>{if(e.tickEvent("github.error",{statusCode:n.statusCode}),t.handleGithubNetworkError){if(t.handleGithubNetworkError(o,n))return i(!1)}throw n}))}(t.token)}function r(e){return s({url:e,method:"GET"}).then((e=>e.json))}function o(t){return e.Cloud.apiRequestWithCdnAsync({url:"gh/"+t,forceLiveEndpoint:!0}).then((e=>e.json))}function a(t){e.log(`github proxy error: ${t.message}`),e.debug(t)}t.isOrgAsync=function(e){return s({url:`https://api.github.com/orgs/${e}`,method:"GET",allowHttpErrors:!0}).then((e=>200==e.statusCode))};class l{constructor(){this.latestVersions={},this.configs={},this.packages={}}proxyWithCdnLoadPackageAsync(t,n){const i=`${t}/${n}`;let s=this.packages[i];if(s)return e.debug(`github cache ${t}/${n}/text`),Promise.resolve(s);const r=T(t);return o(I(r.slug,n,r.fileName,"text")).then((e=>this.packages[i]={files:e}))}cacheConfig(t,n){const i=e.Package.parseAndValidConfig(n);return this.configs[t]=i,e.U.clone(i)}async loadConfigAsync(t,i){i||(e.debug("dep: default to master branch"),i="master");const s=`${t}/${i}`;let r=this.configs[s];if(r)return e.debug(`github cache ${t}/${i}/config`),e.U.clone(r);if(n())try{const n=await this.proxyWithCdnLoadPackageAsync(t,i);return this.cacheConfig(s,n.files[e.CONFIG_NAME])}catch(e){a(e)}const o=await u(t,i,e.CONFIG_NAME);return this.cacheConfig(s,o)}async latestVersionAsync(t,n){let i=this.latestVersions[t];return i||(e.debug(`dep: resolve latest version of ${t}`),this.latestVersions[t]=i=await e.github.latestVersionAsync(t,n,!0,!1)),i}async loadPackageAsync(t,i){if(i||(e.debug("load pkg: default to master branch"),i="master"),n())try{return await this.proxyWithCdnLoadPackageAsync(t,i).then((t=>e.U.clone(t)))}catch(e){a(e)}return await this.githubLoadPackageAsync(t,i)}githubLoadPackageAsync(t,n){return g(t,n).then((i=>{const s=`${t}/${i}`;let r=this.packages[s];return r?(e.debug(`github cache ${t}/${n}/text`),Promise.resolve(e.U.clone(r))):(e.log(`Downloading ${t}/${n} -> ${i}`),u(t,i,e.CONFIG_NAME).then((n=>{const r={files:{}};r.files[e.CONFIG_NAME]=n;const o=JSON.parse(n);return e.U.promiseMapAll(e.allPkgFiles(o).slice(1),(e=>u(t,i,e).then((t=>{r.files[e]=t})))).then((()=>(this.packages[s]=r,e.U.clone(r))))})))}))}}function c(t,n,r){return s({url:"https://api.github.com/repos/"+I(t.slug,"contents",t.fileName,r+"?ref="+n),method:"GET"}).then((n=>{const s=n.json;return i[t.slug]=!0,s&&"base64"==s.encoding&&null!=s.content?e.Util.fromUTF8(atob(s.content)):e.U.httpGetTextAsync(s.download_url)}))}function u(t,n,s){const r=T(t);return i[r.slug]?c(r,n,s):e.U.requestAsync({url:"https://raw.githubusercontent.com/"+I(r.slug,n,r.fileName,s),allowHttpErrors:!0}).then((e=>200==e.statusCode?e.text:c(r,n,s)))}function d(e,t,n,i){return s({url:/^https:/.test(e)?e:"https://api.github.com/repos/"+e,headers:n,method:i||"POST",data:t,successCodes:[200,201,202,204]}).then((e=>e.json))}function h(e,t){let n=1;for(;e.refs[t+n];)n++;return t+n}async function p(e,t,n){return await d(e+"/git/refs",{ref:"refs/heads/"+t,sha:n}),t}function f(i,s="tags",o,a){const l=T(i),c=(u=o,!!t.forceProxy||!(t.token&&!u)&&n());var u;let d=null;const h=c?e.U.httpGetJsonAsync(e.BrowserUtils.cacheBustingUrl(`${e.Cloud.apiRoot}gh/${l.slug}/refs${a?"?nocache=1":""}`)).then((t=>{let n=Object.keys(t.refs).filter((t=>e.U.startsWith(t,"refs/"+s+"/"))).map((e=>({ref:e,object:{sha:t.refs[e]}})));return d=t.refs.HEAD,n})):r(`https://api.github.com/repos/${l.slug}/git/refs/${s}/?per_page=100`);let p=e=>e.replace(/^refs\/[^\/]+\//,"");return h.then((t=>{t.sort(((t,n)=>e.semver.strcmp(p(t.ref),p(n.ref))));let n={};for(let e of t)n[p(e.ref)]=e.object.sha;return{refs:n,head:d}}),(e=>404==e.statusCode?{refs:{}}:Promise.reject(e)))}function m(e){return"commit"==e.object.type?Promise.resolve(e.object.sha):"tag"==e.object.type?r(e.object.url).then((e=>"commit"==e.object.type?e.object.sha:Promise.reject(new Error("Bad type (2nd order) "+e.object.type)))):Promise.reject(new Error("Bad type "+e.object.type))}function g(e,t){if(/^[a-f0-9]{40}$/.test(t))return Promise.resolve(t);const n=T(e);return r(`https://api.github.com/repos/${n.slug}/git/refs/tags/${t}`).then(m,(e=>r(`https://api.github.com/repos/${n.slug}/git/refs/heads/${t}`).then(m)))}async function b(e,n,i){return n||(n=await t.db.latestVersionAsync(e,i)),await t.db.loadConfigAsync(e,n)}async function y(n,i){const s=T(n);if(!s)return void e.log("Unknown GitHub syntax");if(A(s,i))return e.tickEvent("github.download.banned"),void e.log("Github repo is banned");s.tag||(s.tag=await t.db.latestVersionAsync(s.slug,i));const r=await t.db.loadPackageAsync(s.fullName,s.tag),o=P(i,n);if(o){const t=e.Package.parseAndValidConfig(r.files[e.CONFIG_NAME]);t&&(e.log(`auto-disable ${o.join(",")} due to targetconfig entry for ${n}`),t.disablesVariants=o,r.files[e.CONFIG_NAME]=e.Package.stringifyConfig(t))}return r}let v;function w(t){return e.Cloud.cdnApiUrl(`gh/${t.fullName}/icon`)}function k(e,t){var n;if(!e)return;const i={owner:e.owner.login.toLowerCase(),slug:e.full_name.toLowerCase(),fullName:((null==t?void 0:t.fullName)||e.full_name).toLowerCase(),fileName:null===(n=null==t?void 0:t.fileName)||void 0===n?void 0:n.toLocaleLowerCase(),name:e.name,description:e.description,defaultBranch:e.default_branch,tag:null==t?void 0:t.tag,updatedAt:Math.round(new Date(e.updated_at).getTime()/1e3),fork:e.fork,private:e.private};return i.status=x(i,null==t?void 0:t.config),i}function x(e,t){return e?A(e,t)?v.Banned:function(e,t){var n,i;if(function(e,t){return!(!e||!t)&&!!(e.owner&&t.approvedOrgs&&t.approvedOrgs.some((t=>t.toLowerCase()==e.owner.toLowerCase())))}(e,t))return!0;const s=null===(n=null==e?void 0:e.fullName)||void 0===n?void 0:n.toLowerCase(),r=null===(i=null==e?void 0:e.slug)||void 0===i?void 0:i.toLowerCase();return!(!(null==t?void 0:t.approvedRepoLib)||!s&&!r)&&!(!t.approvedRepoLib[s]&&!t.approvedRepoLib[r])}(e,t)?v.Approved:v.Unknown:v.Unknown}function A(e,t){var n,i;if(function(e,t){return!(!t||e&&e.owner&&(!t.bannedOrgs||!t.bannedOrgs.some((t=>t.toLowerCase()==e.owner.toLowerCase()))))}(e,t))return!0;if(!t)return!1;if(!e)return!0;const s=null===(n=e.fullName)||void 0===n?void 0:n.toLowerCase(),r=null===(i=e.slug)||void 0===i?void 0:i.toLowerCase();return!(!t.bannedRepos||!t.bannedRepos.some((e=>e&&(e.toLowerCase()==s||e.toLowerCase()==r))))}async function E(t,i){const s=T(t);if(!s)return;const l=x(s,i);if(l==v.Banned)return;if(n())try{return await function(t,n){return o(t.slug).then((e=>{if(e)return{github:!0,owner:t.owner,fullName:t.fullName,fileName:t.fileName,slug:t.slug,name:t.fileName?`${e.name}-${t.fileName}`:e.name,description:e.description,defaultBranch:e.defaultBranch||"master",tag:t.tag,status:n}})).catch((t=>{e.reportException(t)}))}(s,l)}catch(e){a(e)}return k(await r("https://api.github.com/repos/"+s.slug),{config:i,fullName:s.fullName,fileName:s.fileName,tag:s.tag})}function T(e){if(!e)return;e=(e=e.trim()).replace(/\/$/,"");const t=/^https:\/\/([^./#]+)\.github\.io\/([^/#]+)\/?$/i.exec(e);t&&(e=`github:${t[1]}/${t[2]}`),e=(e=(e=e.replace(/^github:/i,"")).replace(/^https:\/\/github\.com\//i,"")).replace(/\.git\b/i,"");const n=/^([^#\/:]+)\/([^#\/:]+)(\/([^#]+))?(#([^\/:]*))?$/.exec(e);if(!n)return;const i=n[1],s=n[2];let r=n[4];const o=n[6],a=r&&/^tree\/([^\/]+\/)/.exec(r);return a&&(r=r.slice(a[0].length)),{owner:i,project:s,slug:I(i,s),fullName:I(i,s,r),tag:o,fileName:r}}function S(e){return!!e&&"github:"==e.slice(0,7)}function C(e,t=!1){return e?"github:"+(t?e.fullName:e.fullName.toLowerCase())+(e.tag?`#${e.tag}`:""):void 0}function I(...e){return e.filter((e=>!!e)).join("/")}function _(t,n){var i;if(!t)return null;const s=T(n);if(!s)return null;t.approvedRepoLib;return t.approvedRepoLib&&(null===(i=e.U.lookup(t.approvedRepoLib,s.slug.toLowerCase()))||void 0===i?void 0:i.upgrades)}function P(e,t){const n=_(e,t)||[];if(!n)return null;for(const e of n){const t=/^dv:(.*)/.exec(e);if(t){const e=t[1].split(/,/);return e.some((e=>!/^\w+$/.test(e)))?null:e}}return null}t.MemoryGithubDb=l,t.downloadTextAsync=u,t.db=new l,t.authenticatedUserAsync=function(){return t.token?r("https://api.github.com/user"):Promise.resolve(void 0)},t.getCommitsAsync=function(e,t){return r("https://api.github.com/repos/"+T(e).slug+"/commits?sha="+t).then((e=>e.map((e=>{const t=e.commit;return t.url=e.url,t.sha=e.sha,t}))))},t.getCommitAsync=function(e,t){return r("https://api.github.com/repos/"+T(e).slug+"/git/commits/"+t).then((e=>r(e.tree.url+"?recursive=1").then((t=>(e.tree=t,e)))))},t.createObjectAsync=function(e,t,n){return d(T(e).slug+"/git/"+t+"s",n).then((e=>e.sha))},t.postCommitComment=function(e,t,n,i,s){return d(`${T(e).slug}/commits/${t}/comments`,{body:n,path:i,position:s}).then((e=>e.id))},t.fastForwardAsync=async function(e,t,n){const i=T(e);return 200==(await s({url:`https://api.github.com/repos/${i.slug}/git/refs/heads/${t}`,method:"PATCH",allowHttpErrors:!0,data:{sha:n,force:!1}})).statusCode},t.putFileAsync=async function(t,n,i){const r=T(t);await s({url:`https://api.github.com/repos/${e.github.join(r.slug,"contents",r.fileName,n)}`,method:"PUT",allowHttpErrors:!0,data:{message:lf("Initialize empty repo"),content:btoa(e.U.toUTF8(i)),branch:"master"},successCodes:[201]})},t.createTagAsync=async function(e,t,n){await d(e+"/git/refs",{ref:"refs/tags/"+t,sha:n})},t.createReleaseAsync=async function(e,t,n){await d(e+"/releases",{tag_name:t,target_commitish:n,name:t,draft:!1,prerelease:!1})},t.createPRFromBranchAsync=async function(e,t,n,i,s){const r=await d(e+"/pulls",{title:i,body:s||lf("Automatically created from MakeCode."),head:n,base:t,maintainer_can_modify:!0});return null==r?void 0:r.html_url},t.mergeAsync=function(t,n,i,r){return s({url:`https://api.github.com/repos/${T(t).slug}/merges`,method:"POST",successCodes:[201,204,409],data:{base:n,head:i,commit_message:r}}).then((n=>{if(201==n.statusCode||204==n.statusCode)return n.json.sha;if(409==n.statusCode)return null;throw e.U.userError(lf("Cannot merge in github.com/{1}; code: {2}",t,n.statusCode))}))},t.getRefAsync=function(e,t){return r("https://api.github.com/repos/"+e+"/git/refs/heads/"+(t=t||"master")).then(m).catch((e=>{404!=e.statusCode&&Promise.reject(e)}))},t.getNewBranchNameAsync=async function(e,t="patch-"){return h(await f(e,"heads"),t)},t.createNewBranchAsync=p,t.forkRepoAsync=async function(t,n,i="pr-"){const s=T(t),r=k(await d(`${s.slug}/forks`,{}),{fullName:s.fullName,fileName:s.fileName}),o=Date.now()+3e5;let a=null;for(;!a&&Date.now()<o;){await e.U.delay(1e3);try{a=await f(r.slug,"heads")}catch(e){}}if(!a)throw new Error(lf("Timeout waiting for fork"));const l=h(a,i);return await p(r.slug,l,n),r.fullName+"#"+l},t.listRefsAsync=function(e,t="tags",n,i){return f(e,t,n,i).then((e=>Object.keys(e.refs)))},t.listRefsExtAsync=f,t.pkgConfigAsync=b,t.downloadPackageAsync=y,t.downloadLatestPackageAsync=async function(t,n,i){const s=await e.packagesConfigAsync(),r=await e.github.latestVersionAsync(t.slug,s,n,i),o=`${t.fullName}#${r}`;return await e.github.downloadPackageAsync(o,s),{version:`github:${o}`,config:await b(t.fullName,r,s)}},t.cacheProjectDependenciesAsync=async function(t){var n;const i=null===(n=Object.keys(t.dependencies))||void 0===n?void 0:n.filter((e=>S(t.dependencies[e])));if(i.length){const n=await e.packagesConfigAsync();await Promise.all(i.map((async e=>{const i=t.dependencies[e];if(!await y(i,n))throw new Error(lf("Cannot load extension {0} from {1}",e,i))})))}},function(e){e[e.Unknown=0]="Unknown",e[e.Approved=1]="Approved",e[e.Banned=2]="Banned"}(v=t.GitRepoStatus||(t.GitRepoStatus={})),t.isDefaultBranch=function(e,t){return t&&t.defaultBranch?e===t.defaultBranch:/^(main|master)$/.test(e)},t.listUserReposAsync=function(){return O('{\n viewer {\n repositories(first: 100, affiliations: [OWNER, COLLABORATOR], orderBy: {field: PUSHED_AT, direction: DESC}) {\n nodes {\n name\n description\n full_name: nameWithOwner\n private: isPrivate\n fork: isFork\n updated_at: updatedAt\n owner {\n login\n }\n defaultBranchRef {\n name\n }\n pxtjson: object(expression: "HEAD:pxt.json") {\n ... on Blob {\n text\n }\n }\n readme: object(expression: "HEAD:README.md") {\n ... on Blob {\n text\n }\n }\n }\n }\n }\n}').then((t=>t.data.viewer.repositories.nodes.filter((e=>e.pxtjson)).filter((t=>{t.default_branch=t.defaultBranchRef.name;const n=e.Package.parseAndValidConfig(t.pxtjson&&t.pxtjson.text),i=t.readme&&t.readme.text;return!!n&&(n.supportedTargets?n.supportedTargets.indexOf(e.appTarget.id)>-1:i&&i.indexOf("PXT/"+e.appTarget.id)>-1)})).map((e=>k(e,{fullName:e.full_name})))))},t.createRepoAsync=function(e,t,n){return d("https://api.github.com/user/repos",{name:e,description:t,private:!!n,has_issues:!0,has_projects:!1,has_wiki:!1,allow_rebase_merge:!1,allow_merge_commit:!0,delete_branch_on_merge:!1}).then((e=>k(e)))},t.enablePagesAsync=async function(t){const n=T(t);let i;try{const e=await r(`https://api.github.com/repos/${n.slug}/pages`);e&&(i=e.html_url)}catch(e){}if(!i)try{i=(await d(`https://api.github.com/repos/${n.slug}/pages`,{source:{branch:"master",path:"/"}},{Accept:"application/vnd.github.switcheroo-preview+json"})).html_url}catch(t){e.tickEvent("github.pages.error"),e.reportException(t)}if(i){const n=await r(`https://api.github.com/repos/${t}`);if(n&&!n.homepage)try{await d(`https://api.github.com/repos/${t}`,{homepage:i},void 0,"PATCH")}catch(t){e.tickEvent("github.homepage.error")}}},t.repoIconUrl=function(e){if(e.status==v.Approved)return w(e)},t.mkRepoIconUrl=w,t.repoStatus=x,t.repoAsync=E,t.searchAsync=function(t,n){if(!n)return Promise.resolve([]);let i=t.split("|").map(T).filter((e=>!!e));return i.length>0?Promise.all(i.map((e=>E(e.fullName,n)))).then((e=>e.filter((e=>e&&e.status!=v.Banned)))):e.U.httpGetJsonAsync(`${e.Cloud.apiRoot}ghsearch/${e.appTarget.id}/${e.appTarget.platformid||e.appTarget.id}?q=${encodeURIComponent(t)}`).then((t=>t.items.map((e=>k(e,{config:n,fullName:e.full_name}))).filter((e=>e.status==v.Approved||n.allowUnapproved&&e.status==v.Unknown)).filter((t=>!e.appTarget.appTheme.githubUrl||`https://github.com/${t.fullName}`!=e.appTarget.appTheme.githubUrl.toLowerCase())))).catch((e=>[]))},t.parseRepoId=T,t.toGithubDependencyPath=function(e,t){let n="github:"+e;return t&&(n+="#"+t),n},t.isGithubId=S,t.stringifyRepo=C,t.normalizeRepoId=function(e,t){const n=T(e);if(n)return!n.tag&&t&&(n.tag=t),C(n)},t.join=I,t.upgradedPackageReference=function(t,n){const i=_(t,n);if(!i)return null;for(const s of i){const i=/^min:(.*)/.exec(s),r=i&&e.semver.tryParse(i[1]);if(r){const t=T(n),s=e.semver.tryParse(t.tag);return s&&e.semver.cmp(s,r)<0?(t.tag=i[1],e.debug(`upgrading ${n} to ${i[1]}`),C(t)):(s||e.log(`not upgrading ${n} - cannot parse version`),null)}P(t,n)||e.log(`invalid upgrade rule: ${n} -> ${s}`)}return n},t.upgradedPackageId=function(e,t){const n=P(e,t);return n?t+"?dv="+n.join(","):t},t.latestVersionAsync=function(t,n,i,s){const r=T(t);return r?E(r.slug,n).then((t=>{if(t)return f(t.slug,"tags",i,s).then((i=>{let s=Object.keys(i.refs);s=e.semver.sortLatestTags(s);const o=e.appTarget.versions&&e.semver.tryParse(e.appTarget.versions.target);if(o&&n.releases&&n.releases["v"+o.major]){const i=n.releases["v"+o.major].map((t=>e.github.parseRepoId(t))).filter((e=>e&&e.fullName.toLowerCase()==r.fullName.toLowerCase()))[0];if(i){if(s.some((e=>e==i.tag)))return e.debug(`approved release ${i.fullName}#${i.tag} for v${o.major}`),Promise.resolve(i.tag);e.reportError("packages",`approved release ${i.fullName}#${i.tag} for v${o.major} not found anymore`,{repo:t.fullName})}}return s[0]?Promise.resolve(s[0]):i.head||g(t.slug,t.defaultBranch)}))})):Promise.resolve(null)},t.resolveMonoRepoVersions=function(n){n=e.Util.clone(n);const i={};return Object.keys(n).map((e=>({id:e,ghid:t.parseRepoId(n[e])}))).filter((e=>{var t;return null===(t=e.ghid)||void 0===t?void 0:t.tag})).forEach((t=>{const{id:n,ghid:s}=t;let r=i[s.slug];r||(r=i[s.slug]={tag:s.tag,deps:[]}),r.deps.push(t),e.semver.strcmp(r.tag,s.tag)<0&&(e.debug(`dep: resolve later monorepo tag to ${e.github.stringifyRepo(s)}`),r.tag=s.tag)})),e.U.values(i).forEach((t=>t.deps.forEach((i=>{i.ghid.tag!==t.tag&&(e.debug(`dep: ${e.github.stringifyRepo(i.ghid)} -> ${t.tag}`),i.ghid.tag=t.tag,n[i.id]=e.github.stringifyRepo(i.ghid))})))),n},t.GIT_JSON=".git.json";const U="https://api.github.com/graphql";function O(e){const t=JSON.stringify({query:e});return d(U,t)}t.lookupFile=function(e,t,n){if(!t)return null;const i=I(e.fileName,n);return t.tree.tree.find((e=>e.path==i))},t.ghGraphQLQueryAsync=O,t.findPRNumberforBranchAsync=function(e,t){const n=T(e);return O(`\n{\n repository(owner: ${JSON.stringify(n.owner)}, name: ${JSON.stringify(n.project)}) {\n pullRequests(last: 1, states: [OPEN, MERGED], headRefName: ${JSON.stringify(t)}) {\n edges {\n node {\n number\n state\n mergeable\n baseRefName\n url\n isDraft\n }\n }\n }\n }\n}\n`).then((e=>{const t=e.data.repository.pullRequests.edges[0];if(t&&t.node){const e=t.node;return{number:e.number,mergeable:e.mergeable,state:e.state,title:e.title,url:e.url,base:e.baseRefName}}return{number:-1}}))},t.getPagesStatusAsync=function(e){return r(`https://api.github.com/repos/${e}/pages`).catch((e=>({status:null})))}}(e.github||(e.github={}))}(pxt||(pxt={})),function(e){let t;e.REFCNT_FLASH="0xfffe",e.VTABLE_MAGIC=249,e.ValTypeObject=4,function(e){e[e.BoxedString=1]="BoxedString",e[e.BoxedNumber=2]="BoxedNumber",e[e.BoxedBuffer=3]="BoxedBuffer",e[e.RefAction=4]="RefAction",e[e.RefImage=5]="RefImage",e[e.RefCollection=6]="RefCollection",e[e.RefRefLocal=7]="RefRefLocal",e[e.RefMap=8]="RefMap",e[e.RefMImage=9]="RefMImage",e[e.MMap=10]="MMap",e[e.BoxedString_SkipList=11]="BoxedString_SkipList",e[e.BoxedString_ASCII=12]="BoxedString_ASCII",e[e.ZPin=13]="ZPin",e[e.User0=16]="User0"}(t=e.BuiltInType||(e.BuiltInType={}))}(pxt||(pxt={})),function(e){!function(t){function n(e,t,n){e[t+0]=n>>0&255,e[t+1]=n>>8&255,e[t+2]=n>>16&255,e[t+3]=n>>24&255}function i(e,t,n){e[t+0]=n>>0&255,e[t+1]=n>>8&255}function s(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function r(e,t){return e[t]|e[t+1]<<8}function o(e){let t=new Uint8Array(4*e.length);for(let i=0;i<e.length;++i)n(t,4*i,e[i]);return t}t.HF2_CMD_BININFO=1,t.HF2_MODE_BOOTLOADER=1,t.HF2_MODE_USERSPACE=2,t.HF2_CMD_INFO=2,t.HF2_CMD_RESET_INTO_APP=3,t.HF2_CMD_RESET_INTO_BOOTLOADER=4,t.HF2_CMD_START_FLASH=5,t.HF2_CMD_WRITE_FLASH_PAGE=6,t.HF2_CMD_CHKSUM_PAGES=7,t.HF2_CMD_READ_WORDS=8,t.HF2_CMD_WRITE_WORDS=9,t.HF2_CMD_DMESG=16,t.HF2_FLAG_SERIAL_OUT=128,t.HF2_FLAG_SERIAL_ERR=192,t.HF2_FLAG_CMDPKT_LAST=64,t.HF2_FLAG_CMDPKT_BODY=0,t.HF2_FLAG_MASK=192,t.HF2_SIZE_MASK=63,t.HF2_STATUS_OK=0,t.HF2_STATUS_INVALID_CMD=1,t.HF2_STATUS_EXEC_ERR=2,t.HF2_STATUS_EVENT=128,t.HF2_CMD_JDS_CONFIG=32,t.HF2_CMD_JDS_SEND=33,t.HF2_EV_JDS_PACKET=8388640,t.CUSTOM_EV_JACDAC="jacdac",t.HF2_EV_MASK=8388608,t.write32=n,t.write16=i,t.read32=s,t.read16=r,t.encodeU32LE=o,t.decodeU32LE=function(e){let t=[];for(let n=0;n<e.length;n+=4)t.push(s(e,n));return t};let a=!1;function l(t){a?e.log("HF2: "+t):e.debug("HF2: "+t)}t.enableLog=function(){a=!0};class c{constructor(n){var i;this.io=n,this.initialized=!1,this.cmdSeq=e.U.randomUint32(),this.lock=new e.U.PromiseQueue,this.flashing=!1,this.rawMode=!1,this.maxMsgSize=63,this.bootloaderMode=!1,this.reconnectTries=0,this.autoReconnect=!1,this.icon=(null===(i=e.appTarget.appTheme.downloadDialogTheme)||void 0===i?void 0:i.deviceIcon)||"usb",this.msgs=new e.U.PromiseBuffer,this.eventHandlers={},this.jacdacAvailable=!1,this.onSerial=(e,t)=>{},this.onCustomEvent=(e,t)=>{},this.onConnectionChanged=()=>{};let r=[];n.onDeviceConnectionChanged=e=>this.disconnectAsync().then((()=>e&&this.reconnectAsync())),n.onSerial=(e,t)=>this.onSerial(e,t),n.onData=i=>{let s=i[0]&t.HF2_FLAG_MASK,o=63&i[0],a=new Uint8Array(o);if(e.U.memcpy(a,0,i,1,o),s&t.HF2_FLAG_SERIAL_OUT)this.onSerial(a,s==t.HF2_FLAG_SERIAL_ERR);else if(r.push(a),s!=t.HF2_FLAG_CMDPKT_BODY){e.U.assert(s==t.HF2_FLAG_CMDPKT_LAST);let i=0;for(let e of r)i+=e.length;let o=new Uint8Array(i),a=0;for(let t of r)e.U.memcpy(o,a,t),a+=t.length;r=[],o[2]&t.HF2_STATUS_EVENT?n.onEvent(o):this.msgs.push(o)}},n.onEvent=t=>{let n=s(t,0),i=e.U.lookup(this.eventHandlers,n+"");i?i(t.slice(4)):l("unhandled event: "+n.toString(16))},n.onError=e=>{l("recv error: "+e.message),this.autoReconnect&&(this.autoReconnect=!1,this.reconnectAsync().then((()=>{this.autoReconnect=!0}),(e=>{l("reconnect error: "+e.message)})))},this.onEvent(t.HF2_EV_JDS_PACKET,(e=>{this.onCustomEvent(t.CUSTOM_EV_JACDAC,e)}))}resetState(){this.initialized=!1,this.lock=new e.U.PromiseQueue,this.info=null,this.infoRaw=null,this.pageSize=null,this.flashSize=null,this.maxMsgSize=63,this.bootloaderMode=!1,this.msgs.drain()}onEvent(n,i){e.U.assert(!!(n&t.HF2_EV_MASK)),this.eventHandlers[n+""]=i}sendCustomEventAsync(e,n){return e==t.CUSTOM_EV_JACDAC?this.jacdacAvailable?this.talkAsync(t.HF2_CMD_JDS_SEND,n).then((()=>{})):Promise.resolve():Promise.reject(new Error("invalid custom event type"))}isConnected(){return this.io.isConnected()&&this.initialized}isConnecting(){return this.io.isConnecting()||this.io.isConnected()&&!this.initialized}reconnectAsync(){return this.resetState(),l(`reconnect raw=${this.rawMode}`),this.io.reconnectAsync().then((()=>this.initAsync())).catch((t=>{if(this.reconnectTries<5)return this.reconnectTries++,l(`error ${t.message}; reconnecting attempt #${this.reconnectTries}`),e.U.delay(500).then((()=>this.reconnectAsync()));throw t}))}disconnectAsync(){return l("disconnect"),this.io.disconnectAsync()}error(e){return this.io.error(e)}talkAsync(s,o){if(this.io.talksAsync)return this.io.talksAsync([{cmd:s,data:o}]).then((e=>e[0]));let a=8;o&&(a+=o.length);let c=new Uint8Array(a),u=65535&++this.cmdSeq;n(c,0,s),i(c,4,u),i(c,6,0),o&&e.U.memcpy(c,8,o,0,o.length);let d=0,h=()=>this.msgs.shiftAsync(1e3).then((e=>{if(r(e,0)!=u){if(d<3)return d++,l(`message out of sync, (${u} vs ${r(e,0)}); will re-try`),h();this.error("out of sync")}let n="";switch(e[3]&&(n="; info="+e[3]),e[2]){case t.HF2_STATUS_OK:return e.slice(4);case t.HF2_STATUS_INVALID_CMD:this.error("invalid command"+n);break;case t.HF2_STATUS_EXEC_ERR:this.error("execution error"+n);break;default:this.error("error "+e[2]+n)}return null}));return this.sendMsgAsync(c).then(h)}sendMsgAsync(e){return this.sendMsgCoreAsync(e)}sendSerialAsync(e,t=!1){return this.io.sendSerialAsync?this.io.sendSerialAsync(e,t):this.sendMsgCoreAsync(e,t?2:1)}sendMsgCoreAsync(e,n=0){let i=new Uint8Array(64),s=r=>{let o=e.length-r;if(o<=0)return Promise.resolve();o>63?(o=63,i[0]=t.HF2_FLAG_CMDPKT_BODY):i[0]=t.HF2_FLAG_CMDPKT_LAST,n&&(i[0]=1==n?t.HF2_FLAG_SERIAL_OUT:t.HF2_FLAG_SERIAL_ERR),i[0]|=o;for(let t=0;t<o;++t)i[t+1]=e[r+t];return this.io.sendPacketAsync(i).then((()=>s(r+o)))};return this.lock.enqueue("out",(()=>s(0)))}switchToBootloaderAsync(){return this.bootloaderMode?Promise.resolve():(l("Switching into bootloader mode"),this.io.isSwitchingToBootloader&&this.io.isSwitchingToBootloader(),this.maybeReconnectAsync().then((()=>this.talkAsync(t.HF2_CMD_START_FLASH).then((()=>{}),(e=>this.talkAsync(t.HF2_CMD_RESET_INTO_BOOTLOADER).then((()=>{}),(e=>{})).then((()=>this.reconnectAsync().catch((e=>{throw"devicenotfound"===e.type&&(e.type="repairbootloader"),e})))))))).then((()=>this.initAsync())).then((()=>{this.bootloaderMode||this.error("cannot switch into bootloader mode")})))}isFlashing(){return!!this.flashing}reflashAsync(t){l("reflash"),e.U.assert(e.appTarget.compile.useUF2);const n=t.outfiles[pxtc.BINARY_UF2],i=pxtc.UF2.parseFile(e.Util.stringToUint8Array(atob(n)));return this.flashing=!0,this.io.reconnectAsync().then((()=>this.flashAsync(i))).then((()=>e.U.delay(100))).finally((()=>this.flashing=!1)).then((()=>this.reconnectAsync()))}writeWordsAsync(n,i){return e.U.assert(i.length<=64),this.talkAsync(t.HF2_CMD_WRITE_WORDS,o([n,i.length].concat(i))).then((()=>{}))}readWordsAsync(i,s){let r=new Uint8Array(8);return n(r,0,i),n(r,4,s),e.U.assert(s<=64),this.talkAsync(t.HF2_CMD_READ_WORDS,r)}pingAsync(){return this.rawMode?Promise.resolve():this.talkAsync(t.HF2_CMD_BININFO).then((e=>{}))}maybeReconnectAsync(){return this.pingAsync().catch((e=>this.reconnectAsync().then((()=>this.pingAsync()))))}flashAsync(i){let s=Date.now(),r=0,o=s=>{if(s>=i.length)return Promise.resolve();let r=i[s],a=new Uint8Array(4+r.payloadSize);return n(a,0,r.targetAddr),e.U.memcpy(a,4,r.data,0,r.payloadSize),this.talkAsync(t.HF2_CMD_WRITE_FLASH_PAGE,a).then((()=>o(s+1)))};return this.switchToBootloaderAsync().then((()=>{let e=256*i.length;return l(`Starting flash (${Math.round(e/1024)}kB).`),r=Date.now(),this.pageSize>16384?i:u(i,((e,t)=>this.readWordsAsync(e,t)))})).then((e=>{if(e.length!=i.length){let t=256*(i=e).length;l(`Performing partial flash (${Math.round(t/1024)}kB).`)}})).then((()=>o(0))).then((()=>{let e=Date.now(),t=e-s,n=e-r;l(`Flashing done at ${Math.round(256*i.length/n*1e3/1024)} kB/s in ${t}ms (reset ${t-n}ms). Resetting.`)})).then((()=>this.talkAsync(t.HF2_CMD_RESET_INTO_APP).catch((e=>{})))).then((()=>{}))}initAsync(){return this.rawMode?(this.initialized=!0,Promise.resolve()):Promise.resolve().then((()=>this.talkAsync(t.HF2_CMD_BININFO))).then((e=>(this.bootloaderMode=e[0]==t.HF2_MODE_BOOTLOADER,this.pageSize=s(e,4),this.flashSize=s(e,8)*this.pageSize,this.maxMsgSize=s(e,12),this.familyID=s(e,16),l(`Connected; msgSize ${this.maxMsgSize}B; flash ${this.flashSize/1024}kB; ${this.bootloaderMode?"bootloader":"application"} mode; family=0x${this.familyID.toString(16)}`),this.talkAsync(t.HF2_CMD_INFO)))).then((t=>{this.infoRaw=e.Util.fromUTF8Array(t),e.debug("Info: "+this.infoRaw);let n={};("Header: "+this.infoRaw).replace(/^([\w\-]+):\s*([^\n\r]*)/gm,((e,t,i)=>(n[t.replace(/-/g,"")]=i,""))),this.info=n;let i=/v(\d\S+)(\s+(\S+))?/.exec(this.info.Header);this.info.Parsed=i?{Version:i[1],Features:i[3]||""}:{Version:"?",Features:""},l(`Board-ID: ${this.info.BoardID} v${this.info.Parsed.Version} f${this.info.Parsed.Features}`)})).then((()=>this.talkAsync(t.HF2_CMD_JDS_CONFIG,new Uint8Array([1])).then((()=>{this.jacdacAvailable=!0}),(e=>{this.jacdacAvailable=!1})))).then((()=>{this.reconnectTries=0,this.initialized=!0,this.io.onConnectionChanged()}))}}function u(t,n){if(!e.appTarget.compile.flashChecksumAddr)return Promise.resolve(t);let i=pxtc.UF2.readBytes(t,e.appTarget.compile.flashChecksumAddr,48),r=pxtc.parseChecksumBlock(i);return r?function(t){return e.appTarget.compile.flashChecksumAddr?t(e.appTarget.compile.flashChecksumAddr,12).then((n=>{let i=pxtc.parseChecksumBlock(n);return i?t(i.endMarkerPos,1).then((t=>s(t,0)!=i.endMarker?(e.log("end-marker mismatch"),null):i)):null})):Promise.resolve(null)}(n).then((e=>{if(!e)return t;let n=e.regions.filter((e=>r.regions.some((t=>e.checksum==t.checksum&&e.length==t.length&&e.start==t.start))));if(0==n.length)return t;l("skipping flash at: "+n.map((e=>`${pxtc.assembler.tohex(e.start)} (${e.length/1024}kB)`)).join(", "));let i=e=>n.some((t=>t.start<=e&&e<t.start+t.length));return t.filter((e=>!(i(e.targetAddr)&&i(e.targetAddr+e.payloadSize-1))))})):Promise.resolve(t)}t.Wrapper=c,t.mkHF2PacketIOWrapper=function(t){return e.debug("packetio: wrapper hf2"),new c(t)},t.onlyChangedBlocksAsync=u}(e.HF2||(e.HF2={}))}(pxt||(pxt={})),function(e){!function(t){var n=e.Util,i=e.HF2;const s=i.read32;let r,o,a,l,c,u,d,h,p=!1;function f(e){return e<<2|2}function m(e){return 1&e?e>>1:0!=e?2&e?e==t.taggedNull?null:e!=t.taggedFalse&&(e==t.taggedTrue||{tagged:e>>2}):{ptr:e}:void 0}function g(e,t){if(n.assert(!(3&e)),n.assert(e>=0),e<2097152){let i=new Uint8Array(t);return e-=d.start,n.memcpy(i,0,d.buf,e,t),Promise.resolve(i)}let i=h.maxMsgSize-32;if(t>i){let s=[];for(;t>0;){let n=Math.min(i,t);s.push(g(e,n)),t-=n,e+=n}return Promise.all(s).then(n.uint8ArrayConcat)}return h.readWordsAsync(e,Math.ceil(t/4)).then((e=>e.length>t?e.slice(0,t):e))}function b(t){if("object"!=typeof t||!t)return Promise.resolve(t);if("number"==typeof t.ptr){if(3&t.ptr)return Promise.resolve({unalignedPtr:t.ptr});let s=0;return g(t.ptr,56).then((r=>{s=i.read16(r,2);let o=r.length;return s==e.BuiltInType.BoxedString||s==e.BuiltInType.BoxedBuffer?o=i.read16(r,4)+6:s==e.BuiltInType.BoxedNumber&&(o=12),o>r.length?g(t.ptr+r.length,o-r.length).then((e=>n.uint8ArrayConcat([r,e]))):o<r.length?r.slice(0,o):r})).then((t=>s==e.BuiltInType.BoxedString?n.uint8ArrayToString(t.slice(6)):s==e.BuiltInType.BoxedBuffer?{type:"buffer",data:t.slice(6)}:s==e.BuiltInType.BoxedNumber?new Float64Array(t.buffer.slice(4))[0]:{type:"unknown",tag:s,refcnt:i.read16(t,0),data:t.slice(4)}))}return Promise.resolve(t)}function y(e){let t=[];for(let n of Object.keys(e))t.push(b(e[n]).then((t=>{e[n]=t})));return Promise.all(t).then((()=>{}))}function v(e){let t=r.breakpoints,n=t[0],i=1/0;for(let s of t){let t=e-s.binAddr;t>=0&&t<i&&(i=t,n=s)}return n}function w(e){if(p)return Promise.resolve();let s;return p=!0,E().then((t=>{let o=i.decodeU32LE(e)[0],l={};for(let e of r.procDebugInfo[0].locals){let s=t.globals,r=(()=>{switch(e.type){case"uint32":return i.read32(s,e.index);case"int32":return 0|i.read32(s,e.index);case"uint16":return i.read16(s,e.index);case"int16":return i.read16(s,e.index)<<16>>16;case"uint8":return s[e.index];case"int8":return s[e.index]<<24>>24;default:return null}})();null===r&&(n.assert(0==(3&e.index)),r=m(i.read32(s,e.index))),l[e.name]=r}return c=v(o),s={type:"debugger",subtype:"breakpoint",breakpointId:c.id,globals:l,stackframes:[]},a(),h.talkAsync(1888490768)})).then((e=>{!function(e,t){let i=c.binAddr,s=0,o=r.procDebugInfo.filter((e=>e.codeStartLoc<=i&&i<=e.codeEndLoc))[0];for(;o&&o!=r.procDebugInfo[0];){let r=v(i),a=n.clone(r);a.functionName=o.name,a.argumentNames=o.args&&o.args.map((e=>e.name)),t.stackframes.push({locals:{},funcInfo:a,breakpointId:r.id});let l=t.stackframes[t.stackframes.length-1],c=0;for(let t of o.locals)n.assert(t.index==c++),l.locals[t.name]=m(e[s++]);i=2147483646&e[s++];let d=u[i+""];for(let t of o.args)l.locals[t.name]=m(e[s+(o.args.length-1-t.index)]);if(!d)break;o=d.from,s+=d.stack-o.localsMark}}(i.decodeU32LE(e),s);let t=[s.globals].concat(s.stackframes.map((e=>e.locals)));return n.promiseMapAll(t,y)})).then((()=>t.postMessage(s)))}function k(){p=!1,o=new Promise(((e,t)=>{a=e}))}function x(e=!1){return Promise.resolve().then((()=>h.talkAsync(665147697,i.encodeU32LE([e?1:3])))).then(k)}function A(){return o||(o=Promise.resolve()),o}function E(){return(l?Promise.resolve(l):h.talkAsync(1409050336).then((e=>l={numGlobals:s(e,0),globalsPtr:s(e,4)}))).then((e=>h.readWordsAsync(e.globalsPtr,e.numGlobals))).then((e=>({staticState:l,globals:e})))}t.taggedUndefined=0,t.taggedNull=f(1),t.taggedFalse=f(2),t.taggedTrue=f(16),t.postMessage=e=>console.log(e),t.decodeValue=m,t.heapExpandAsync=b,t.heapExpandMapAsync=y,t.startDebugAsync=function(e,t){return h=t,h.onEvent(915601917,w),(p=!1,r=null,l=null,Promise.resolve()).then((()=>{r=e,u={};let t=[];for(let n of e.procDebugInfo)t[n.idx]=n;for(let n of e.procDebugInfo)for(let e of n.calls)u[e.addr+""]={from:n,to:t[e.procIndex],stack:e.stack}})).then((()=>{let e=r.outfiles[pxtc.BINARY_UF2],t=n.stringToUint8Array(atob(e));return d=pxtc.UF2.toBin(t),h.reflashAsync(r).then((()=>h.reconnectAsync()))})).then((()=>h.talkAsync(287358355).catch((e=>{})))).then((()=>n.delay(200))).then((()=>h.reconnectAsync())).then(k).then(A)},t.handleMessage=function(e){if(console.log("HWDBGMSG",e),"debugger"!=e.type)return;let t=!1;switch(e.subtype){case"stepinto":t=!0;case"stepover":x(t)}},t.resumeAsync=x,t.waitForHaltAsync=A,t.getHwStateAsync=E}(e.HWDBG||(e.HWDBG={}))}(pxt||(pxt={})),function(e){e.ImageConverter=class{logTime(){if(this.start){let t=Date.now()-this.start;e.debug("Icon creation: "+t+"ms")}}convert(t){this.start||(this.start=Date.now());let n=atob(t.slice(t.indexOf(",")+1)),i=n.charCodeAt(0),s=n.charCodeAt(1),r=n.charCodeAt(2);if(135===i&&(i=224|n.charCodeAt(1),s=n.charCodeAt(2)|n.charCodeAt(3)<<8,r=n.charCodeAt(4)|n.charCodeAt(5)<<8,n=n.slice(4)),225!=i&&228!=i)return null;if(this.palette||this.setPalette(e.appTarget.runtime.palette.map((function(e){const t=parseInt(e.replace(/#/,""),16);return[t>>0&255,t>>8&255,t>>16&255,255]}))),225==i)return this.genMonochrome(n,s,r);const o=(e.BrowserUtils.isEdge()||e.BrowserUtils.isIE())&&s<100&&r<100?3:1;return this.genColor(n,s,r,o)}setPalette(e){e[0][3]=0,this.palette=new Uint8Array(4*e.length);for(let t=0;t<e.length;++t)this.palette[4*t+0]=e[t][0],this.palette[4*t+1]=e[t][1],this.palette[4*t+2]=e[t][2],this.palette[4*t+3]=e[t][3]}genMonochrome(t,n,i){let s=n+3&-4,r=54+this.palette.length,o=r+s*i,a=new Uint8Array(o);a[0]=66,a[1]=77,e.HF2.write32(a,2,o),e.HF2.write32(a,10,r),e.HF2.write32(a,14,40),e.HF2.write32(a,18,n),e.HF2.write32(a,22,-i),e.HF2.write16(a,26,1),e.HF2.write16(a,28,8),e.HF2.write32(a,38,2835),e.HF2.write32(a,42,2835),e.HF2.write32(a,46,this.palette.length>>2),a.set(this.palette,54);let l=4,c=r,u=1,d=t.charCodeAt(l++);for(let e=0;e<n;++e){c=r+e;for(let e=0;e<i;++e)a[c]=d&u?1:0,c+=s,u<<=1,256==u&&(u=1,d=t.charCodeAt(l++))}return"data:image/bmp;base64,"+btoa(e.U.uint8ArrayToString(a))}genColor(t,n,i,s){const r=n*(s=Math.max(1,0|s)),o=i*s;let a=r<<2,l=138,c=l+a*o,u=new Uint8Array(c);u[0]=66,u[1]=77,e.HF2.write32(u,2,c),e.HF2.write32(u,10,l),e.HF2.write32(u,14,124),e.HF2.write32(u,18,r),e.HF2.write32(u,22,-o),e.HF2.write16(u,26,1),e.HF2.write16(u,28,32),e.HF2.write16(u,30,3),e.HF2.write32(u,38,2835),e.HF2.write32(u,42,2835),e.HF2.write32(u,54,16711680),e.HF2.write32(u,58,65280),e.HF2.write32(u,62,255),e.HF2.write32(u,66,4278190080),u[70]=66,u[71]=71,u[72]=82,u[73]=115;let d=4,h=l,p=!0;for(let e=0;e<r;e++){let n=!1;h=l+(e<<2);let r=d,c=t.charCodeAt(d++),f=n?(c>>4&15)<<2:(15&c)<<2;for(let e=0;e<o;e++)c&&(p=!1),u[h]=this.palette[f],u[h+1]=this.palette[f+1],u[h+2]=this.palette[f+2],u[h+3]=this.palette[f+3],h+=a,e%s==s-1&&(n&&(c=t.charCodeAt(d++)),n=!n,f=n?(c>>4&15)<<2:(15&c)<<2);if(p&&(u[141]=1),e%s==s-1)for(i%2||--d;3&d;)d++;else d=r}return"data:image/bmp;base64,"+btoa(e.U.uint8ArrayToString(u))}},e.convertUint8BufferToPngUri=function(t,n){const i=new e.ImageConverter,s=[];for(let e=0;e<16;e++)s.push([t[3*e+2],t[3*e+1],t[3*e+0],255]);i.setPalette(s);const r=String.fromCharCode.apply(null,n),o=`data:image/x-mkcd-f4;base64,${btoa(r)}`;return i.convert(o)}}(pxt||(pxt={})),function(e){!function(t){function n(){const e={"tsconfig.json":t.TS_CONFIG,"test.ts":`// ${lf("tests go here; this will not be compiled when this package is used as an extension.")}\n`,"_config.yml":"makecode:\n target: @TARGET@\n platform: @PLATFORM@\n home_url: @HOMEURL@\ntheme: jekyll-theme-slate\ninclude:\n - assets\n - README.md\n",Makefile:"all: deploy\n\nbuild:\n\tpxt build\n\ndeploy:\n\tpxt deploy\n\ntest:\n\tpxt test\n",Gemfile:"source 'https://rubygems.org'\ngem 'github-pages', group: :jekyll_plugins","README.md":`\n> ${lf("Open this page at {0}","[https://@REPOOWNER@.github.io/@REPONAME@/](https://@REPOOWNER@.github.io/@REPONAME@/)")}\n\n## ${lf("Use as Extension")}\n\n${lf("This repository can be added as an **extension** in MakeCode.")}\n\n* ${lf("open [@HOMEURL@](@HOMEURL@)")}\n* ${lf("click on **New Project**")}\n* ${lf("click on **Extensions** under the gearwheel menu")}\n* ${lf("search for **https://github.com/@REPO@** and import")}\n\n## ${lf("Edit this project")}\n\n${lf("To edit this repository in MakeCode.")}\n\n* ${lf("open [@HOMEURL@](@HOMEURL@)")}\n* ${lf("click on **Import** then click on **Import URL**")}\n* ${lf("paste **https://github.com/@REPO@** and click import")}\n\n#### ${lf("Metadata (used for search, rendering)")}\n\n* for PXT/@TARGET@\n<script src="https://makecode.com/gh-pages-embed.js"><\/script><script>makeCodeRender("{{ site.makecode.home_url }}", "{{ site.github.owner_name }}/{{ site.github.repository_name }}");<\/script>\n`,".gitignore":"# MakeCode\nbuilt\nnode_modules\nyotta_modules\nyotta_targets\npxt_modules\n.pxt\n_site\n*.db\n*.tgz\n.header.json\n.simstate.json\n",".vscode/settings.json":'{\n "editor.formatOnType": true,\n "files.autoSave": "afterDelay",\n "files.watcherExclude": {\n "**/.git/objects/**": true,\n "**/built/**": true,\n "**/node_modules/**": true,\n "**/yotta_modules/**": true,\n "**/yotta_targets": true,\n "**/pxt_modules/**": true,\n "**/.pxt/**": true\n },\n "files.associations": {\n "*.blocks": "html",\n "*.jres": "json"\n },\n "search.exclude": {\n "**/built": true,\n "**/node_modules": true,\n "**/yotta_modules": true,\n "**/yotta_targets": true,\n "**/pxt_modules": true,\n "**/.pxt": true\n },\n "files.exclude": {\n "**/pxt_modules": true,\n "**/.pxt": true\n }\n}',".vscode/extensions.json":'{\n "recommendations": ["ms-edu.pxt-vscode-web"]\n}'},n=i();return n&&Object.keys(n).forEach((t=>e[t]=n[t])),e}function i(){const t=e.appTarget.bundledpkgs[e.template.TEMPLATE_PRJ];if(t){const n=e.Util.clone(t);return delete n[e.CONFIG_NAME],n}}t.TS_CONFIG='{\n "compilerOptions": {\n "target": "ES5",\n "noImplicitAny": true,\n "outDir": "built",\n "rootDir": "."\n },\n "exclude": ["pxt_modules/**/*test.ts"]\n}\n',t.defaultFiles=n,t.targetTemplateFiles=i,t.TEMPLATE_PRJ="template",t.packageFiles=function(t){const i=e.appTarget.blocksprj||e.appTarget.tsprj,s=e.U.clone(i.config);delete s.installedVersion,delete s.additionalFilePath,delete s.additionalFilePaths,s.preferredEditor=s.files.find((e=>/\.blocks$/.test(e)))?e.BLOCKS_PROJECT_NAME:e.JAVASCRIPT_PROJECT_NAME,s.name=t,s.public=!0,s.version||(s.version="0.0.0");const r={},o=n();for(const e in o)r[e]=o[e];for(const e in i.files)"README.md"!=e&&(r[e]=i.files[e]);const a=Object.keys(r).filter((e=>/\.(blocks|md|ts|asm|cpp|h|py)$/.test(e)));return s.files=a.filter((e=>!/test/.test(e))),s.testFiles=a.filter((e=>/test/.test(e))),s.supportedTargets=[e.appTarget.id],r[e.CONFIG_NAME]=e.Package.stringifyConfig(s),r},t.packageFilesFixup=function(t,n){const i=JSON.parse(t[e.CONFIG_NAME]);n&&e.Util.jsonMergeFrom(i,n),e.webConfig&&(Object.keys(e.webConfig).forEach((t=>i[t.toLowerCase()]=e.webConfig[t])),i.platform=e.appTarget.platformid||e.appTarget.id,i.target=e.appTarget.id,i.docs=e.appTarget.appTheme.homeUrl||"./",i.homeurl=e.appTarget.appTheme.homeUrl||"???"),e.U.iterMap(t,((e,n)=>{n=n.replace(/@([A-Z]+)@/g,((e,t)=>i[t.toLowerCase()]||"")),t[e]=n}))}}(e.template||(e.template={}))}(pxt||(pxt={})),function(e){!function(t){let n,i;!function(e){e[e.Prefix=0]="Prefix",e[e.Postfix=1]="Postfix",e[e.Infix=2]="Infix",e[e.Block=3]="Block",e[e.NewLine=4]="NewLine"}(n=t.NT||(t.NT={})),function(e){e[e.None=0]="None",e[e.WithSpace=1]="WithSpace",e[e.NoSpace=2]="NoSpace"}(i=t.GlueMode||(t.GlueMode={}));const s=["break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","import","in","instanceof","new","null","return","super","switch","this","throw","true","try","typeof","var","void","while","with"];function r(e){return"`"+e.replace(/[\\`${}]/g,(e=>"\\"+e))+"`"}function o(e){return e.length>20&&/\n/.test(e)?r(e):JSON.stringify(e)}function a(e,t,n){return{type:e,op:t,children:n}}function l(){return a(n.NewLine,"",[])}function c(e,t){return a(n.Prefix,e,t)}function u(e,t,i){return a(n.Infix,t,null==e?[i]:[e,i])}function d(e){return c(e,[])}function h(e){return a(n.Block,"",e)}function p(e){return c("",e)}function f(e,t=!1){const n=[];for(const i of e)t?(n.length>0&&n.push(d(",")),n.push(l())):n.length>0&&n.push(d(", ")),n.push(i);return t&&n.push(l()),p(n)}let m;t.backtickLit=r,t.stringLit=o,t.mkNode=a,t.mkNewLine=l,t.mkPrefix=c,t.mkPostfix=function(e,t){return a(n.Postfix,t,e)},t.mkInfix=u,t.mkText=d,t.mkBlock=h,t.mkGroup=p,t.mkStmt=function(...e){let t=e[e.length-1];return t&&t.type==n.Block||e.push(l()),p(e)},t.mkCommaSep=f,function(t){function n(e,t,n=!1,i=!1){return p(i?[u(t[0],".",d(e)),d("("),f(t.slice(1),n),d(")")]:[d(e),d("("),f(t,n),d(")")])}function i(e,t,i,s){return n(e+"."+t,i,s)}function s(t,n){return e.U.assert(2==n.length),u(n[0],t,n[1])}t.mkArrayLiteral=function(e,t){return p([d("["),f(e,t),d("]")])},t.mkNumberLiteral=function(e){return d(e.toString())},t.mkBooleanLiteral=function(e){return d(e?"true":"false")},t.mkStringLiteral=function(e){return d(o(e))},t.mkPropertyAccess=function(e,t){return p([u(t,".",d(e))])},t.mkCall=n,t.stdCall=function(e,t,i){return n(e,t,i)},t.extensionCall=function(e,t,i){return n(e,t,i,!0)},t.namespaceCall=i,t.mathCall=function(e,t){return i("Math",e,t,!1)},t.mkGlobalRef=function(e){return d(e)},t.mkSimpleCall=s,t.mkWhile=function(e,t){return p([d("while ("),e,d(")"),h(t)])},t.mkComment=function(e){return d("// "+e)},t.mkMultiComment=function(e){let t=[d("/**"),l()];return e.split("\n").forEach(((e,n,i)=>{e&&(t.push(d(" * "+e)),t.push(l()),n<i.length-1&&(t.push(d(" * ")),t.push(l())))})),p(t.concat([d(" */"),l()]))},t.mkAssign=function(e,t){return s("=",[e,t])},t.mkParenthesizedExpression=function(e){return y(b([e]).output)?e:p([d("("),e,d(")")])}}(m=t.Helpers||(t.Helpers={})),t.H=m;const g={"=":3,"+=":3,"-=":3,"?":4,":":4,"||":5,"&&":6,"|":7,"^":8,"&":9,"==":10,"!=":10,"===":10,"!==":10,"<":11,">":11,"<=":11,">=":11,">>":12,">>>":12,"<<":12,"+":13,"-":13,"*":14,"/":14,"%":14,"**":15,"!":16,"~":16,"P-":16,"P+":16,"++":16,"--":16,".":18};function b(t){let s=[],r={},o="",a="",l=[{}],c=0;function u(e){"string"==typeof e&&(c+=(e.match(/\n/g)||[]).length),o+=e}let h=p(t);return function t(i,s){if(i.type!=n.Infix){for(let e of i.children)t(e,-1);return}let r=[];function o(e){"P"==e[0]&&(e=e.slice(1)),r.push(d(e))}let a=e.U.lookup(g,i.op);if(null==a&&e.U.oops("bad infix op: "+i.op),a<s&&o("("),1==i.children.length)o(i.op),t(i.children[0],a),r.push(i.children[0]);else{let e,n=3!=a&&"**"!=i.op;t(i.children[0],n?a:a+.1),r.push(i.children[0]),e&&"number"!=e&&(o(": "),o(e)),"."==i.op?o("."):o(" "+i.op+" "),t(i.children[1],n?a+.1:a),r.push(i.children[1])}a<s&&o(")"),i.type=n.Prefix,i.op="",i.children=r}(h,-1),f(h),o||u("\n"),{output:o,sourceMap:s};function f(t){t.glueToBlock&&(b(),t.glueToBlock==i.WithSpace&&u(" "));let d=c,h=o.length;switch(t.type){case n.Infix:e.U.oops("no infix should be left");break;case n.NewLine:u("\n"+a);break;case n.Block:!function(t){let n=t.noFinalNewline?"":"\n";if(0==t.children.length)return void m(" {\n\t\n}"+n);let i=e.U.clone(l[l.length-1]||{});l.push(i),a+=" "," "!=o[o.length-1]&&m(" ");m("{\n");for(let e of t.children)f(e);a=a.slice(4),b(),m("\n}"+n),l.pop()}(t);break;case n.Prefix:t.canIndentInside?u(t.op.replace(/\n/g,"\n"+a+" ")):u(t.op),t.children.forEach(f);break;case n.Postfix:t.children.forEach(f),t.canIndentInside?u(t.op.replace(/\n/g,"\n"+a+" ")):u(t.op)}let p=c,g=Math.max(o.length,1);if(t.id)if(r[t.id]){const e=r[t.id];e.startLine=Math.min(e.startLine,d),e.endLine=Math.max(e.endLine,p),e.startPos=Math.min(e.startPos,h),e.endPos=Math.max(e.endPos,g)}else{const e={id:t.id,startLine:d,startPos:h,endLine:p,endPos:g};r[t.id]=e,s.push(e)}}function m(e){u(e.replace(/\n/g,"\n"+a))}function b(){o=o.replace(/\n *$/,(function(){return c--,""}))}}function y(e){if("("!==e[0]||")"!==e[e.length-1])return!1;let t=1;for(let n=1;n<e.length;n++){const i=e[n];if("("===i)t++;else if(")"===i&&(t--,0===t))return n===e.length-1}return!1}t.flattenNode=b,t.isReservedWord=function(e){return-1!==s.indexOf(e)},t.isParenthesized=y}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(t){const n=[".","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];t.BLOCKLY_TILESET_TYPE="BLOCKLY_TILESET_TYPE",t.TILE_PREFIX="tile",t.TILE_NAMESPACE="myTiles",t.IMAGES_NAMESPACE="myImages",t.IMAGE_PREFIX="image",t.ANIMATION_NAMESPACE="myAnimations",t.ANIMATION_PREFIX="anim",t.SONG_NAMESPACE="mySongs",t.SONG_PREFIX="song";class i{constructor(e,t,n=0,i=0,s){this.width=e,this.height=t,this.x0=n,this.y0=i,this.width||(this.width=16),this.height||(this.height=16),this.buf=s||new Uint8ClampedArray(this.dataLength())}static fromData(e){return new i(e.width,e.height,e.x0,e.y0,e.data)}set(e,t,n){if(e<this.width&&t<this.height&&e>=0&&t>=0){const i=this.coordToIndex(e,t);this.setCore(i,n)}}get(e,t){if(e<this.width&&t<this.height&&e>=0&&t>=0){const n=this.coordToIndex(e,t);return this.getCore(n)}return 0}copy(e=0,t=0,n=this.width,s=this.height){const r=new i(n,s);r.x0=e,r.y0=t;for(let i=0;i<n;i++)for(let n=0;n<s;n++)r.set(i,n,this.get(e+i,t+n));return r}apply(e,t=!1){let n;for(let i=0;i<e.width;i++)for(let s=0;s<e.height;s++)n=e.get(i,s),!n&&t||this.set(e.x0+i,e.y0+s,n)}equals(e){if(this.width===e.width&&this.height===e.height&&this.x0===e.x0&&this.y0===e.y0&&this.buf.length===e.buf.length){for(let t=0;t<this.buf.length;t++)if(this.buf[t]!==e.buf[t])return!1;return!0}return!1}data(){return{width:this.width,height:this.height,x0:this.x0,y0:this.y0,data:this.buf}}resize(e,t){return h(this,e,t)}coordToIndex(e,t){return e+t*this.width}getCore(e){const t=Math.floor(e/2);return e%2==0?15&this.buf[t]:(240&this.buf[t])>>4}setCore(e,t){const n=Math.floor(e/2);this.buf[n]=e%2==0?240&this.buf[n]|15&t:15&this.buf[n]|(15&t)<<4}dataLength(){return Math.ceil(this.width*this.height/2)}}t.Bitmap=i;class s extends i{static fromData(e){return new s(e.width,e.height,e.x0,e.y0,e.data)}copy(e=0,t=0,n=this.width,i=this.height){const r=new s(n,i);r.x0=e,r.y0=t;for(let s=0;s<n;s++)for(let n=0;n<i;n++)r.set(s,n,this.get(e+s,t+n));return r}resize(e,t){return p(this,e,t)}getCore(e){return this.buf[e]}setCore(e,t){this.buf[e]=t}dataLength(){return this.width*this.height}}t.Tilemap=s;class r{constructor(e,t,n){this.tilemap=e,this.tileset=t,this.layers=n,this.nextId=0}cloneData(){const e=this.tilemap.copy(),t={tileWidth:this.tileset.tileWidth,tiles:this.tileset.tiles.map((e=>Object.assign(Object.assign({},e),{bitmap:i.fromData(e.bitmap).copy().data()})))},n=i.fromData(this.layers).copy().data();return new r(e,t,n)}equals(t){if(!this.tilemap.equals(t.tilemap)||this.tileset.tileWidth!=t.tileset.tileWidth||this.tileset.tiles.length!=t.tileset.tiles.length||!y(this.layers,t.layers))return!1;for(let n=0;n<this.tileset.tiles.length;n++)if(!e.assetEquals(this.tileset.tiles[n],t.tileset.tiles[n]))return!1;return!0}}t.TilemapData=r;function o(e){return a(atob(e.slice(e.indexOf(",")+1)))}function a(t){let n=t.charCodeAt(0),i=t.charCodeAt(1),s=t.charCodeAt(2);135===n&&(n=224|t.charCodeAt(1),i=t.charCodeAt(2)|t.charCodeAt(3)<<8,s=t.charCodeAt(4)|t.charCodeAt(5)<<8,t=t.slice(4));const r=new e.sprite.Bitmap(i,s);let o=4;if(225===n){let e=1,n=t.charCodeAt(o++);for(let a=0;a<i;++a)for(let i=0;i<s;++i)r.set(a,i,n&e?1:0),e<<=1,256==e&&(e=1,n=t.charCodeAt(o++))}else for(let e=0;e<i;e++){for(let n=0;n<s;n+=2){let i=t.charCodeAt(o++);r.set(e,n,15&i),n!=s-1&&r.set(e,n+1,i>>4&15)}for(;3&o;)o++}return r}function l(e,t){!(e=(e=(e=e.replace(/[ `]|(?:&#96;)|(?:&#9;)|(?:hex)/g,"").trim()).replace(/^["`\(\)]*/,"").replace(/["`\(\)]*$/,"")).replace(/&#10;/g,"\n"))&&t&&(e=t);const n=parseInt(e.substr(0,2),16)|parseInt(e.substr(2,2),16)<<8,i=parseInt(e.substr(4,2),16)|parseInt(e.substr(6,2),16)<<8,r=k(e.substring(8));return s.fromData({width:n,height:i,x0:0,y0:0,data:r})}function c(e){return`${d(e.width,2)}${d(e.height,2)}${x(e.data().data)}`}function u(e,t){return(e=e.replace(/[\[\]]/g,""))?e.split(",").filter((e=>!!e.trim())).map((e=>function(e,t){if(0===(e=e.trim()).indexOf("img")){const n=f(e);return t.createNewTile(n.data())}switch(e){case"myTiles.tile0":case"myTiles.transparency16":return t.getTransparency(16);case"myTiles.transparency8":return t.getTransparency(8);case"myTiles.transparency4":return t.getTransparency(4);case"myTiles.transparency32":return t.getTransparency(32);default:return t.resolveTile(e)}}(e,t))):[]}function d(e,t){let n=e.toString(16);const i=t<<1;for(1&n.length&&(n="0"+n);n.length<i;)n+="0";return n}function h(e,t,n){const s=new i(t,n);return s.apply(e),s}function p(e,t,n){const i=new s(t,n);return i.apply(e),i}function f(e,t="img"){const n=(e=(e=(e=(e=e.replace(/[ `]|(?:&#96;)|(?:&#9;)|(?:img)/g,"").trim()).replaceAll(t,"")).replace(/^["`\(\)]*/,"").replace(/["`\(\)]*$/,"")).replace(/&#10;/g,"\n")).split("\n"),s=[];let r=0;for(let e=0;e<n.length;e++){const t=n[e],i=[];for(let e=0;e<t.length;e++)switch(t[e]){case"0":case".":i.push(0);break;case"1":case"#":i.push(1);break;case"2":case"T":i.push(2);break;case"3":case"t":i.push(3);break;case"4":case"N":i.push(4);break;case"5":case"n":i.push(5);break;case"6":case"G":i.push(6);break;case"7":case"g":i.push(7);break;case"8":i.push(8);break;case"9":i.push(9);break;case"a":case"A":case"R":i.push(10);break;case"b":case"B":case"P":i.push(11);break;case"c":case"C":case"p":i.push(12);break;case"d":case"D":case"O":i.push(13);break;case"e":case"E":case"Y":i.push(14);break;case"f":case"F":case"W":i.push(15);break;default:if(!/\s/.test(t[e]))return}i.length&&(s.push(i),r=Math.max(r,i.length))}const o=s.length,a=new i(r,o);for(let e=0;e<o;e++){const t=s[e];for(let n=0;n<r;n++)n<t.length?a.set(n,e,t[n]):a.set(n,e,0)}return a}function m(e,t="img"){let n="";switch(e){case"python":n=`${t}("""`;break;default:n=`${t}\``}return n}function g(e){let t="";switch(e){case"python":t+='""")';break;default:t+="`"}return t}function b(e,t,i="img"){if(!e||0===e.height||0===e.width)return"";let s=m(t,i);if(e){const t=e.width*e.height>300?"":" ";for(let i=0;i<e.height;i++){s+="\n";for(let r=0;r<e.width;r++)s+=n[e.get(r,i)]+t}}return s+="\n",s+=g(t),s}function y(t,n){return e.sprite.Bitmap.fromData(t).equals(e.sprite.Bitmap.fromData(n))}function v(e){switch(e){case 4:return"TileScale.Four";case 8:return"TileScale.Eight";case 16:return"TileScale.Sixteen";case 32:return"TileScale.ThirtyTwo";default:return Math.floor(Math.log2(e)).toString()}}function w(e){switch(e=e.replace(/\s/g,"")){case"TileScale.Four":return 4;case"TileScale.Eight":return 8;case"TileScale.Sixteen":return 16;case"TileScale.ThirtyTwo":return 32;default:return Math.pow(2,parseInt(e))}}function k(e){let t=new Uint8ClampedArray(e.length>>1);for(let n=0;n<e.length;n+=2)t[n>>1]=parseInt(e.slice(n,n+2),16);return t}function x(e){const t="0123456789abcdef";let n="";for(let i=0;i<e.length;++i)n+=t[e[i]>>4],n+=t[15&e[i]];return n}function A(e,t,n){e[t]=255&n,e[t+1]=n>>8&255}function E(e){const t=function(e){if(e){if(6===e.length)return parseInt("0x"+e);if(7===e.length)return parseInt("0x"+e.substr(1))}return 0}(e);return[T(t),S(t),C(t)]}function T(e){return e>>16&255}function S(e){return e>>8&255}function C(e){return 255&e}t.Bitmask=class{constructor(e,t){this.width=e,this.height=t,this.mask=new Uint8Array(Math.ceil(e*t/8))}set(e,t){const n=e+this.width*t,i=n>>3,s=7&n;this.mask[i]|=1<<s}get(e,t){const n=e+this.width*t,i=n>>3,s=7&n;return this.mask[i]>>s&1}},t.encodeTilemap=function(e,t,n){return e?`tiles.createTilemap(${function(e){return e?`hex\`${c(e)}\``:"hex``"}(e.tilemap)}, ${b(i.fromData(e.layers),t)}, [${e.tileset.tiles.map((e=>function(e,t,n){if(n&&n[e.id])return n[e.id];return e.id}(e,0,n)))}], ${v(e.tileset.tileWidth)})`:"null"},t.decodeTilemap=function(t,n,i){if(!(t=e.Util.htmlUnescape(t).trim()).trim())return null;const s=(t=(t=t.substr(t.indexOf("(")+1)).substr(0,t.lastIndexOf(")"))).substr(0,t.indexOf(",")),o=(t=t.substr(s.length+1)).substr(0,t.indexOf(",")),a=(t=t.substr(o.length+1)).substr(0,t.lastIndexOf("]")+1),c=t=t.substr(a.length+1);return new r(l(s),{tiles:u(a,i),tileWidth:w(c)},f(o).data())},t.trimTilemapTileset=function(e){const t=e.tileset.tiles.slice(),n=e.tilemap,i={};i[t[0].id]=!0;for(let e=0;e<n.width;e++)for(let s=0;s<n.height;s++)i[t[n.get(e,s)].id]=!0;const s=e.editedTiles||[],r=t.filter((e=>i[e.id]||"*"===e.id.charAt(0)||-1!==s.indexOf(e.id)));if(r.length===t.length)return;const o=[];for(let e=0;e<t.length;e++)o.push(r.indexOf(t[e]));for(let e=0;e<n.width;e++)for(let t=0;t<n.height;t++)n.set(e,t,o[n.get(e,t)]);e.tileset.tiles=r},t.isEmptyTilemap=function(e){const t=e.tileset.tiles,n=e.tilemap,i=t[0].id;for(let e=0;e<n.width;e++)for(let s=0;s<n.height;s++)if(t[n.get(e,s)].id!==i)return!1;return!0},t.computeAverageColor=function(e,t){const n=t.map(E),i=[0,0,0];let s=0;for(let t=0;t<e.width;t++)for(let r=0;r<e.height;r++){const o=e.get(t,r);if(o){++s;const e=n[o];i[0]+=e[0],i[1]+=e[1],i[2]+=e[2]}}return s?"#"+function(e){let t="";for(let n=0;n<e.length;++n)t+=("0"+e[n].toString(16)).slice(-2);return t}(i.map((e=>Math.floor(e/s)))):"#00000000"},t.getBitmap=function(e,t){const n=e.apis.byQName[t];return n?o(n.attributes.jresURL):null},t.getBitmapFromJResURL=o,t.hexToBitmap=a,t.filterItems=function(e,t){const n=(t=t.filter((e=>!!e)).map((e=>e.toLowerCase()))).filter((e=>0!==e.indexOf("!"))),i=t.filter((e=>0===e.indexOf("!")&&e.length>1)).map((e=>e.substring(1)));return e.filter((e=>{return t=e,n.every((e=>{const n=`?${e}`;return t.tags.some((t=>t===e||t===n))}))&&function(e){return i.every((t=>!e.tags.some((e=>e===t))))}(e);var t}))},t.getGalleryItems=function(n,i){let s=function(t,n){return e.Util.values(t.byQName).filter((e=>4===e.kind&&e.attributes.fixedInstance&&function(e,t,n){if(t==n)return!0;let i=e.byQName[t];return!(!i||!i.extendsTypes)&&i.extendsTypes.indexOf(n)>=0}(t,e.retType,n)))}(n.apis,i);return s=s.filter((e=>e.namespace!=t.TILE_NAMESPACE)),function(t){const n=new e.ImageConverter;t.forEach((e=>{e.attributes.jresURL&&!e.attributes.iconURL&&0==e.attributes.jresURL.indexOf("data:image/x-mkcd-f")&&(e.attributes.iconURL=n.convert(e.attributes.jresURL))}))}(s),s.map((t=>{const n=(t.attributes.tags||"").split(" ").filter((e=>!!e)).map((t=>e.Util.startsWith(t,"category-")?t:t.toLowerCase()));return{qName:t.qName,src:t.attributes.iconURL,alt:t.qName,tags:n}}))},t.base64EncodeBitmap=function(t){const n=i.fromData(t),s=pxtc.f4EncodeImg(t.width,t.height,4,((e,t)=>n.get(e,t)));return btoa(e.U.uint8ArrayToString(k(s)))},t.tilemapLiteralToTilemap=l,t.hexEncodeTilemap=c,t.formatByte=d,t.resizeBitmap=h,t.resizeTilemap=p,t.imageLiteralToBitmap=f,t.encodeAnimationString=function(t,n){const i=t.map((e=>e.data)),s=new Uint8ClampedArray(8+i[0].length*i.length);A(s,0,n),A(s,2,t[0].width),A(s,4,t[0].height),A(s,6,t.length);let r=8;return i.forEach((e=>{s.set(e,r),r+=e.length})),btoa(e.sprite.uint8ArrayToHex(s))},t.addMissingTilemapTilesAndReferences=function(e,t){const n=e.getProjectTiles(t.data.tileset.tileWidth,!0);t.data.projectReferences=[];for(const i of n.tiles)t.data.tileset.tiles.some((e=>e.id===i.id))||t.data.tileset.tiles.push(i),e.isAssetUsed(i,null,[t.id])&&t.data.projectReferences.push(i.id)},t.updateTilemapReferencesFromResult=function(t,n){const i=n.data;if(i.deletedTiles)for(const e of i.deletedTiles)t.deleteTile(e);if(i.editedTiles)for(const e of i.editedTiles){const n=i.tileset.tiles.findIndex((t=>t.id===e)),s=i.tileset.tiles[n];s&&(i.tileset.tiles[n]=t.updateTile(s))}for(let e=0;e<i.tileset.tiles.length;e++){const n=i.tileset.tiles[e];n.jresData||(i.tileset.tiles[e]=t.resolveTile(n.id))}e.sprite.trimTilemapTileset(i)},t.imageLiteralFromDimensions=function(e,t,i,s){let r=m(s);const o=e*t>300?"":" ";for(let s=0;s<t;s++){r+="\n";for(let t=0;t<e;t++)r+=n[i]+o}return r+="\n",r+=g(s),r},t.bitmapToImageLiteral=b,t.bitmapEquals=y,t.tileWidthToTileScale=v,t.tileScaleToTileWidth=w,t.hexToUint8Array=k,t.uint8ArrayToHex=x,t.colorStringToRGB=E}(e.sprite||(e.sprite={}))}(pxt||(pxt={})),function(e){!function(t){!function(n){const i=new RegExp(`^\\s*${t.TILE_NAMESPACE}\\s*\\.\\s*${t.TILE_PREFIX}(\\d+)\\s*$`);class s{constructor(e,t,n){this.tilemap=e,this.tileset=t,this.layers=n,this.nextId=0}}function r(e){return(e=e.replace(/[\[\]]/g,""))?e.split(",").filter((e=>!!e.trim())).map((e=>function(e){if(0===(e=e.trim()).indexOf("img")){return{data:t.imageLiteralToBitmap(e).data()}}const n=i.exec(e);if(n)return{data:null,projectId:Number(n[1])};return{data:null,qualifiedName:e}}(e))):[]}n.LegacyTilemapData=s,n.decodeTilemap=function(n,i){var o;if(!(null==(n=null===(o=e.Util.htmlUnescape(n))||void 0===o?void 0:o.trim())?void 0:n.trim()))return new s(new t.Tilemap(16,16),{tileWidth:16,tiles:[]},new t.Bitmap(16,16).data());const a=(n=(n=n.substr(n.indexOf("(")+1)).substr(0,n.lastIndexOf(")"))).substr(0,n.indexOf(",")),l=(n=n.substr(a.length+1)).substr(0,n.indexOf(",")),c=(n=n.substr(l.length+1)).substr(0,n.lastIndexOf("]")+1),u=n=n.substr(c.length+1);return new s(t.tilemapLiteralToTilemap(a),{tiles:r(c),tileWidth:t.tileScaleToTileWidth(u)},t.imageLiteralToBitmap(l).data())},n.tileToBlocklyVariable=function(e){return`${e.projectId};${e.data.width};${e.data.height};${pxtc.Util.toHex(e.data.data)}`},n.blocklyVariableToTile=function(e){const t=e.split(";");return 4!==t.length?null:{projectId:parseInt(t[0]),data:{width:parseInt(t[1]),height:parseInt(t[2]),data:new Uint8ClampedArray(pxtc.Util.fromHex(t[3])),x0:0,y0:0}}}}(t.legacy||(t.legacy={}))}(e.sprite||(e.sprite={}))}(pxt||(pxt={})),function(e){!function(t){class n{constructor(){this.items={}}removeItem(e){delete this.items[e]}getItem(e){return this.items[e]}setItem(e,t){this.items[e]=t}clear(){this.items={}}}class i{constructor(e){this.storageId=e,this.type="localstorage"}targetKey(e){return this.storageId+"/"+e}removeItem(e){window.localStorage.removeItem(this.targetKey(e))}getItem(e){return window.localStorage[this.targetKey(e)]}setItem(e,t){window.localStorage[this.targetKey(e)]=t}clear(){let e=this.targetKey(""),t=[];for(let n=0;n<window.localStorage.length;++n){let i=window.localStorage.key(n);0==i.indexOf(e)&&t.push(i)}t.forEach((e=>window.localStorage.removeItem(e)))}}function s(){if(e.appTarget)return e.appTarget.id;const t=window.pxtConfig;if(t)return t.targetId;const n=window.pxtTargetBundle;return n?n.id:""}let r;function o(){if(r)return;const t=s();let o=!1;if(!e.shell.isSandboxMode())try{const n=e.Util.guidGen();window.localStorage[t]=n;o=window.localStorage[t]===n}catch(e){}o?(r=new i(t),e.debug(`storage: local under ${t}`)):(r=new n,e.debug("storage: in memory"))}t.storageId=s,t.setLocal=function(e,t){o(),r.setItem(e,t)},t.getLocal=function(e){return o(),r.getItem(e)},t.removeLocal=function(e){o(),r.removeItem(e)},t.clearLocal=function(){o(),r.clear()}}(e.storage||(e.storage={}))}(pxt||(pxt={})),function(e){!function(t){!function(t){const n="http://localhost:3232/api/store/";function i(){return e.BrowserUtils.isLocalHostDev()&&!e.BrowserUtils.noSharedLocalStorage()}function s(){return e.BrowserUtils.isChromiumEdge()?"chromium-edge":e.BrowserUtils.browser()}t.getAsync=async function(t,r){if(i()){t+="-"+s();const i=await e.Util.requestAsync({url:`${n}${encodeURIComponent(t)}/${encodeURIComponent(r)}`,method:"GET",allowHttpErrors:!0});if(204===i.statusCode)throw new Error(`Missing ${r} not available in ${t}`);return i.json?i.json:i.text?i.text:void 0}{const n=e.storage.getLocal(`${t}:${r}`),i=e.Util.jsonTryParse(n);return i||n}},t.setAsync=async function(t,r,o){if(void 0===o)return void await e.storage.shared.delAsync(t,r);let a="";if(a="object"==typeof o?JSON.stringify(o):o.toString(),i()){t+="-"+s();const i={type:"object"==typeof o?"json":"text",val:a},l=JSON.stringify(i);await e.Util.requestAsync({url:`${n}${encodeURIComponent(t)}/${encodeURIComponent(r)}`,method:"POST",data:l})}else e.storage.setLocal(`${t}:${r}`,a)},t.delAsync=async function(t,r){i()?(t+="-"+s(),await e.Util.requestAsync({url:`${n}${encodeURIComponent(t)}/${encodeURIComponent(r)}`,method:"DELETE",allowHttpErrors:!0})):e.storage.removeLocal(`${t}:${r}`)}}(t.shared||(t.shared={}))}(e.storage||(e.storage={}))}(pxt||(pxt={})),function(e){function t(e){let t=0;for(let n=0;n<e.length;n++)if(" "===e.charAt(n))t++;else{if("\t"!==e.charAt(n))return t;t+=4}return 0}e.getSectionsFromMarkdownMetadata=function(e){const n=e.split(/\r?\n/);let i=[],s=null,r=null,o=null,a=[],l=0;for(const e of n)if(e.trim()){if(e.startsWith("#")){const t=/^(#+)\s*(.+)$/.exec(e);if(t){c(),s={headerKind:1===t[1].length?"single":2===t[1].length?"double":"triple",header:t[2],attributes:{}},r=null,o=null,l=0;continue}}if(s){const n=t(e),i=e.trim(),c=/^[*-]\s+(?:([^:]+):)?(.*)$/.exec(i);if(!c)continue;if(Math.abs(n-l)>1&&r){if(n>l){const e={key:r,items:[]};a.length?a[a.length-1].items.push(e):(s.listAttributes||(s.listAttributes={}),s.listAttributes[r]=e),r=null,a.push(e)}else{const e=a.pop();r&&o&&(null==e||e.items.push((r+":"+o).trim()),o=null)}l=n}c&&(c[1]?(r&&o&&(a.length?a[a.length-1].items.push((r+":"+o).trim()):s.attributes[r]=o.trim()),r=c[1].toLowerCase(),o=c[2]):r&&(o+=c[2]))}}else o&&(o+="\n");return c(),i;function c(){s&&(r&&o&&(a.length?a[a.length-1].items.push((r+":"+o).trim()):s.attributes[r]=o.trim()),i.push(s)),a=[]}}}(pxt||(pxt={})),function(e){!function(t){let n;!function(e){e[e.PROD=0]="PROD",e[e.STAGING=1]="STAGING",e[e.LOCAL=2]="LOCAL"}(n||(n={}));let i=n.STAGING;t.ABSOLUTE_LINKS={PROD_BETA:"https://arcade.makecode.com/beta--multiplayer",STAGING_BETA:"https://arcade.staging.pxt.io/beta--multiplayer",LOCAL:"http://localhost:3000"},t.RELATIVE_LINKS={PROD:"/--multiplayer",BETA:"/beta--multiplayer"},t.SHORT_LINKS={PROD:"https://aka.ms/a9",PROD_BETA:"https://aka.ms/a9b",STAGING:"https://aka.ms/a9s",STAGING_BETA:"https://aka.ms/a9sb"},t.RELATIVE_LINK=()=>{if(e.BrowserUtils.isLocalHostDev())switch(i){case n.PROD:return t.ABSOLUTE_LINKS.PROD_BETA;case n.STAGING:return t.ABSOLUTE_LINKS.STAGING_BETA;case n.LOCAL:return t.ABSOLUTE_LINKS.LOCAL}return window.location.pathname.startsWith("/beta")?t.RELATIVE_LINKS.BETA:t.RELATIVE_LINKS.PROD},t.SHORT_LINK=()=>{if(e.BrowserUtils.isLocalHostDev())switch(i){case n.PROD:return t.SHORT_LINKS.PROD_BETA;case n.STAGING:return t.SHORT_LINKS.STAGING_BETA;case n.LOCAL:return t.ABSOLUTE_LINKS.LOCAL}return window.location.host.endsWith(".staging.pxt.io")?window.location.pathname.startsWith("/beta")?t.SHORT_LINKS.STAGING_BETA:t.SHORT_LINKS.STAGING:window.location.pathname.startsWith("/beta")?t.SHORT_LINKS.PROD_BETA:t.SHORT_LINKS.PROD},t.makeHostLink=function(e,n){return`${n?t.SHORT_LINK():t.RELATIVE_LINK()}?host=${encodeURIComponent(e)}`},t.makeJoinLink=function(e,n){return`${n?t.SHORT_LINK():t.RELATIVE_LINK()}?join=${encodeURIComponent(e)}`}}(e.multiplayer||(e.multiplayer={}))}(pxt||(pxt={})),function(e){!function(t){!function(t){function n(e,t,n){const i=new Uint8Array(2);new Uint16Array(i.buffer)[0]=0|n,e[t]=i[0],e[t+1]=i[1]}function i(e,t){const n=new Uint8Array(2);return n[0]=e[t],n[1]=e[t+1],new Uint16Array(n.buffer)[0]}function s(e){const t=new Uint8Array(5+7*e.steps.length);t[0]=e.steps.length,n(t,1,e.startFrequency),n(t,3,e.startVolume);for(let i=0;i<e.steps.length;i++){const s=5+7*i;t[s]=e.steps[i].waveform,n(t,s+1,e.steps[i].frequency),n(t,s+3,e.steps[i].volume),n(t,s+5,e.steps[i].duration)}return t}function r(e,t,i){const s=new Uint8Array(5+e.notes.length);n(s,0,e.startTick),n(s,2,e.endTick),s[4]=e.notes.length;for(let n=0;n<e.notes.length;n++)s[5+n]=o(e.notes[n],t,i);return s}function o(e,t,n){if(n)return e.note;let i=0;return"flat"===e.enharmonicSpelling?i=1:"sharp"===e.enharmonicSpelling&&(i=2),e.note-12*(t-2)|i<<6}function a(e){return e.drums?function(e){const t=e.drums.map(s),i=t.reduce(((e,t)=>t.length+e),0),o=e.notes.map((e=>r(e,0,!0))),a=o.reduce(((e,t)=>t.length+e),0),l=new Uint8Array(6+i+a);l[0]=e.id,l[1]=1,n(l,2,i);let c=4;for(const e of t)l.set(e,c),c+=e.length;n(l,c,a),c+=2;for(const e of o)l.set(e,c),c+=e.length;return l}(e):function(e){const t=function(e){var t,i,s,r,o,a,l,c,u;const d=new Uint8Array(28);return d[0]=e.waveform,n(d,1,e.ampEnvelope.attack),n(d,3,e.ampEnvelope.decay),n(d,5,e.ampEnvelope.sustain),n(d,7,e.ampEnvelope.release),n(d,9,e.ampEnvelope.amplitude),n(d,11,(null===(t=e.pitchEnvelope)||void 0===t?void 0:t.attack)||0),n(d,13,(null===(i=e.pitchEnvelope)||void 0===i?void 0:i.decay)||0),n(d,15,(null===(s=e.pitchEnvelope)||void 0===s?void 0:s.sustain)||0),n(d,17,(null===(r=e.pitchEnvelope)||void 0===r?void 0:r.release)||0),n(d,19,(null===(o=e.pitchEnvelope)||void 0===o?void 0:o.amplitude)||0),d[21]=(null===(a=e.ampLFO)||void 0===a?void 0:a.frequency)||0,n(d,22,(null===(l=e.ampLFO)||void 0===l?void 0:l.amplitude)||0),d[24]=(null===(c=e.pitchLFO)||void 0===c?void 0:c.frequency)||0,n(d,25,(null===(u=e.pitchLFO)||void 0===u?void 0:u.amplitude)||0),d[27]=e.octave,d}(e.instrument),i=e.notes.map((t=>r(t,e.instrument.octave,!1))),s=i.reduce(((e,t)=>t.length+e),0),o=new Uint8Array(6+t.length+s);o[0]=e.id,o[1]=0,n(o,2,t.length);let a=4;o.set(t,a),a+=t.length,n(o,a,s),a+=2;for(const e of i)o.set(e,a),a+=e.length;return o}(e)}function l(e,t){return{waveform:e[t],ampEnvelope:{attack:i(e,t+1),decay:i(e,t+3),sustain:i(e,t+5),release:i(e,t+7),amplitude:i(e,t+9)},pitchEnvelope:{attack:i(e,t+11),decay:i(e,t+13),sustain:i(e,t+15),release:i(e,t+17),amplitude:i(e,t+19)},ampLFO:{frequency:e[t+21],amplitude:i(e,22)},pitchLFO:{frequency:e[t+24],amplitude:i(e,25)},octave:e[t+27]}}function c(e,t){return e[t+1]?function(e,t){const n={id:e[t],instrument:{ampEnvelope:{attack:0,decay:0,sustain:0,release:0,amplitude:0},waveform:0},notes:[],drums:[]},s=i(e,t+2);let r=t+4;for(;r<t+4+s;)n.drums.push(u(e,r)),r+=5+7*n.drums[n.drums.length-1].steps.length;const o=i(e,r);r+=2;for(;r<t+4+s+o;)n.notes.push(d(e,r,0,!0)),r+=5+n.notes[n.notes.length-1].notes.length;return[n,r]}(e,t):function(e,t){const n={id:e[t],instrument:l(e,t+4),notes:[]},s=t+4+i(e,t+2),r=i(e,s);let o=s+2;for(;o<s+2+r;)n.notes.push(d(e,o,n.instrument.octave,!1)),o+=5+n.notes[n.notes.length-1].notes.length;return[n,o]}(e,t)}function u(e,t){const n={startFrequency:i(e,t+1),startVolume:i(e,t+3),steps:[]};for(let s=0;s<e[t];s++){const r=t+5+7*s;n.steps.push({waveform:e[r],frequency:i(e,r+1),volume:i(e,r+3),duration:i(e,r+5)})}return n}function d(e,t,n,s){const r={startTick:i(e,t),endTick:i(e,t+2),notes:[]};for(let i=0;i<e[t+4];i++)r.notes.push(h(e[t+5+i],n,s));return r}function h(e,t,n){const i=e>>6,s={note:n?e:(63&e)+12*(t-2),enharmonicSpelling:"normal"};return 1===i?s.enharmonicSpelling="flat":2===i&&(s.enharmonicSpelling="sharp"),s}function p(e,t){if(typeof e!=typeof t)return!1;if("object"!=typeof e)return e===t;if(Array.isArray(e)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!p(e[n],t[n]))return!1;return!0}const n=Object.keys(e),i=Object.keys(t);if(n.length!==i.length)return!1;for(const s of n){if(-1===i.indexOf(s))return!1;if(!p(e[s],t[s]))return!1}return!0}function f(e){return{ticksPerBeat:8,beatsPerMeasure:4,beatsPerMinute:120,measures:e,tracks:[{id:0,name:lf("Dog"),notes:[],iconURI:"music-editor/dog.png",instrument:{waveform:1,octave:4,ampEnvelope:{attack:10,decay:100,sustain:500,release:100,amplitude:1024},pitchLFO:{frequency:5,amplitude:0}}},{id:1,name:lf("Duck"),notes:[],iconURI:"music-editor/duck.png",instrument:{waveform:15,octave:4,ampEnvelope:{attack:5,decay:530,sustain:705,release:450,amplitude:1024},pitchEnvelope:{attack:5,decay:40,sustain:0,release:100,amplitude:40},ampLFO:{frequency:3,amplitude:20},pitchLFO:{frequency:6,amplitude:2}}},{id:2,name:lf("Cat"),notes:[],iconURI:"music-editor/cat.png",instrument:{waveform:12,octave:5,ampEnvelope:{attack:150,decay:100,sustain:365,release:400,amplitude:1024},pitchEnvelope:{attack:120,decay:300,sustain:0,release:100,amplitude:50},pitchLFO:{frequency:10,amplitude:6}}},{id:3,name:lf("Fish"),notes:[],iconURI:"music-editor/fish.png",instrument:{waveform:1,octave:3,ampEnvelope:{attack:220,decay:105,sustain:1024,release:350,amplitude:1024},ampLFO:{frequency:5,amplitude:100},pitchLFO:{frequency:1,amplitude:4}}},{id:4,name:lf("Car"),notes:[],iconURI:"music-editor/car.png",instrument:{waveform:16,octave:4,ampEnvelope:{attack:5,decay:100,sustain:1024,release:30,amplitude:1024},pitchLFO:{frequency:10,amplitude:4}}},{id:5,name:lf("Computer"),notes:[],iconURI:"music-editor/computer.png",instrument:{waveform:15,octave:2,ampEnvelope:{attack:10,decay:100,sustain:500,release:10,amplitude:1024}}},{id:6,name:lf("Burger"),notes:[],iconURI:"music-editor/burger.png",instrument:{waveform:1,octave:2,ampEnvelope:{attack:10,decay:100,sustain:500,release:100,amplitude:1024}}},{id:7,name:lf("Cherry"),notes:[],iconURI:"music-editor/cherry.png",instrument:{waveform:2,octave:3,ampEnvelope:{attack:10,decay:100,sustain:500,release:100,amplitude:1024}}},{id:8,name:lf("Lemon"),notes:[],iconURI:"music-editor/lemon.png",instrument:{waveform:14,octave:2,ampEnvelope:{attack:5,decay:70,sustain:870,release:50,amplitude:1024},pitchEnvelope:{attack:10,decay:45,sustain:0,release:100,amplitude:20},ampLFO:{frequency:1,amplitude:50},pitchLFO:{frequency:2,amplitude:1}}},{id:9,name:lf("Drums"),notes:[],iconURI:"music-editor/explosion.png",instrument:{waveform:11,octave:4,ampEnvelope:{attack:10,decay:100,sustain:500,release:100,amplitude:1024}},drums:[{startFrequency:100,startVolume:1024,steps:[{waveform:3,frequency:120,duration:10,volume:1024},{waveform:3,frequency:1,duration:100,volume:0}]},{startFrequency:200,startVolume:1024,steps:[{frequency:0,volume:0,duration:100,waveform:1}]},{startFrequency:100,startVolume:1024,steps:[{frequency:0,volume:0,duration:250,waveform:1}]},{startFrequency:175,startVolume:1024,steps:[{waveform:1,frequency:200,duration:10,volume:1024},{waveform:1,frequency:150,duration:20,volume:1024},{waveform:5,frequency:1,duration:20,volume:100},{waveform:5,frequency:1,duration:300,volume:0}]},{startFrequency:220,startVolume:1024,steps:[{waveform:1,frequency:250,duration:10,volume:1024},{waveform:1,frequency:200,duration:20,volume:1024},{waveform:5,frequency:2e3,duration:20,volume:100},{waveform:5,frequency:2e3,duration:200,volume:0}]},{startFrequency:400,startVolume:500,steps:[{frequency:450,volume:500,duration:10,waveform:5},{frequency:400,volume:20,duration:20,waveform:5}]},{startFrequency:400,startVolume:0,steps:[{frequency:450,volume:500,duration:5,waveform:5},{frequency:900,volume:5,duration:50,waveform:5},{frequency:900,volume:0,duration:250,waveform:5}]},{startFrequency:400,startVolume:0,steps:[{frequency:450,volume:500,duration:5,waveform:5},{frequency:900,volume:200,duration:50,waveform:5},{frequency:900,volume:5,duration:100,waveform:5},{frequency:900,volume:0,duration:400,waveform:5}]},{startFrequency:400,startVolume:0,steps:[{frequency:450,volume:500,duration:5,waveform:5},{frequency:900,volume:200,duration:100,waveform:5},{frequency:900,volume:5,duration:200,waveform:5},{frequency:900,volume:0,duration:500,waveform:5}]},{startFrequency:3500,startVolume:1024,steps:[{frequency:4e3,volume:0,duration:10,waveform:4},{frequency:3500,volume:800,duration:1,waveform:4},{frequency:4e3,volume:0,duration:40,waveform:4},{frequency:3500,volume:400,duration:1,waveform:4},{frequency:4e3,volume:0,duration:40,waveform:4}]},{startFrequency:2e3,startVolume:1024,steps:[{frequency:1800,volume:15,duration:100,waveform:4},{frequency:1800,volume:0,duration:200,waveform:4}]},{startFrequency:200,startVolume:200,steps:[{frequency:125,volume:200,duration:25,waveform:14},{frequency:100,volume:15,duration:50,waveform:14},{frequency:120,volume:0,duration:250,waveform:14}]},{startFrequency:300,startVolume:200,steps:[{frequency:225,volume:200,duration:25,waveform:14},{frequency:200,volume:15,duration:50,waveform:14},{frequency:220,volume:0,duration:250,waveform:14}]},{startFrequency:500,startVolume:200,steps:[{frequency:425,volume:200,duration:25,waveform:14},{frequency:400,volume:15,duration:50,waveform:14},{frequency:420,volume:0,duration:250,waveform:14}]},{startFrequency:200,startVolume:1024,steps:[{frequency:75,volume:0,duration:200,waveform:1}]},{startFrequency:300,startVolume:1024,steps:[{frequency:200,volume:0,duration:200,waveform:1}]},{startFrequency:400,startVolume:1024,steps:[{frequency:300,volume:0,duration:200,waveform:1}]},{startFrequency:200,startVolume:1024,steps:[{frequency:200,volume:15,duration:100,waveform:4},{frequency:150,volume:0,duration:200,waveform:4}]},{startFrequency:450,startVolume:1024,steps:[{frequency:350,volume:15,duration:100,waveform:4},{frequency:300,volume:0,duration:100,waveform:4}]},{startFrequency:2500,startVolume:1024,steps:[{frequency:2500,volume:100,duration:150,waveform:4},{frequency:2550,volume:0,duration:500,waveform:4}]},{startFrequency:3e3,startVolume:1024,steps:[{frequency:3e3,volume:100,duration:300,waveform:4},{frequency:3060,volume:0,duration:500,waveform:4}]},{startFrequency:800,startVolume:0,steps:[{frequency:800,volume:1024,duration:10,waveform:4},{frequency:800,volume:0,duration:490,waveform:4}]},{startFrequency:400,startVolume:0,steps:[{frequency:400,volume:1024,duration:10,waveform:4},{frequency:400,volume:0,duration:400,waveform:4}]},{startFrequency:2e3,startVolume:1024,steps:[{frequency:2e3,volume:100,duration:150,waveform:16},{frequency:2e3,volume:0,duration:200,waveform:16}]}]}]}}t.encodeSongToHex=function(t){const i=function(e){const t=e.tracks.filter((e=>e.notes.length>0)).map(a),i=t.reduce(((e,t)=>t.length+e),0),s=new Uint8Array(7+i);s[0]=0,n(s,1,e.beatsPerMinute),s[3]=e.beatsPerMeasure,s[4]=e.ticksPerBeat,s[5]=e.measures,s[6]=t.length;let r=7;for(const e of t)s.set(e,r),r+=e.length;return s}(t);return e.U.toHex(i)},t.decodeSongFromHex=function(t){return function(e){const t={beatsPerMinute:i(e,1),beatsPerMeasure:e[3],ticksPerBeat:e[4],measures:e[5],tracks:[]};let n=7;for(;n<e.length;){const[i,s]=c(e,n);n=s,t.tracks.push(i)}return t}(e.U.fromHex(t))},t.cloneSong=function(e){return Object.assign(Object.assign({},e),{tracks:e.tracks.map((e=>Object.assign(Object.assign({},e),{instrument:e.instrument&&Object.assign(Object.assign({},e.instrument),{ampEnvelope:Object.assign({},e.instrument.ampEnvelope),pitchEnvelope:e.instrument.pitchEnvelope&&Object.assign({},e.instrument.pitchEnvelope),ampLFO:e.instrument.ampLFO&&Object.assign({},e.instrument.ampLFO),pitchLFO:e.instrument.pitchLFO&&Object.assign({},e.instrument.pitchLFO)}),drums:e.drums&&e.drums.map((e=>Object.assign(Object.assign({},e),{steps:e.steps.map((e=>Object.assign({},e)))}))),notes:e.notes.map((e=>Object.assign(Object.assign({},e),{notes:e.notes.slice()})))})))})},t.songEquals=function(e,t){return p(e,t)},t.inflateSong=function(e){const t=f(1);e.tracks=t.tracks.map(((t,n)=>{const i=e.tracks.find((e=>e.id===n));return i&&(t.notes=i.notes),t}))},t.getSongInfo=function(e){return{ticksPerBeat:e.ticksPerBeat,beatsPerMeasure:e.beatsPerMeasure,beatsPerMinute:e.beatsPerMinute,measures:e.measures}},t.getEmptySong=f}(t.music||(t.music={}))}(e.assets||(e.assets={}))}(pxt||(pxt={})),function(e){const t=["name","version","description","license","dependencies","files","testFiles","testDependencies","fileDependencies","public","targetVersions","supportedTargets","preferredEditor","languageRestriction","additionalFilePath","additionalFilePaths"];class n{constructor(e,t,n,i,s){this.id=e,this._verspec=t,this.parent=n,this.depName=s,this.level=-1,this.isLoaded=!1,this.ignoreTests=!1,this.cppOnly=!1,i&&(this.level=i.level+1),this.addedBy=[i]}static stringifyConfig(e){const n=e,i={};for(const e of t)n.hasOwnProperty(e)&&(i[e]=n[e]);for(const e of Object.keys(n))i.hasOwnProperty(e)||(i[e]=n[e]);return JSON.stringify(i,null,4)+"\n"}static parseAndValidConfig(t){const n=e.Util.jsonTryParse(t);return n&&void 0!==n.name&&"string"==typeof n.name&&n.files&&Array.isArray(n.files)&&n.files.every((e=>"string"==typeof e))&&n.dependencies&&Object.keys(n.dependencies).every((e=>"string"==typeof n.dependencies[e]))&&n}static async getConfigAsync(t,n,i){if(e.github.isGithubId(i)){const t=e.github.parseRepoId(i),n=await e.packagesConfigAsync();return await e.github.repoAsync(t.fullName,n)?await e.github.pkgConfigAsync(t.fullName,t.tag,n):null}if(i.startsWith("workspace:")){i.slice("workspace:".length);return null}if(!i.startsWith("pub:")){const s=e.patching.upgradePackageReference(t,n,i),r=e.appTarget.bundledpkgs[s];return JSON.parse(r[e.CONFIG_NAME])}{const t=i.slice("pub:".length);try{const n=await e.Cloud.downloadScriptFilesAsync(t);return JSON.parse(n[e.CONFIG_NAME])}catch(t){return e.log(`Unable to fetch files for published script '${i}'`),null}}}static corePackages(){const t=e.appTarget.bundledpkgs;return Object.keys(t).map((n=>JSON.parse(t[n][e.CONFIG_NAME]))).filter((e=>!!e))}disablesVariant(e){return this.config&&this.config.disablesVariants&&this.config.disablesVariants.indexOf(e)>=0}invalid(){return/^invalid:/.test(this.version())}version(){return this.resolvedVersion||this._verspec}verProtocol(){let e=this.version().split(":");return e.length>1?e[0]:""}verArgument(){let e=this.verProtocol();return e?this.version().slice(e.length+1):this.version()}targetVersion(){return this.parent&&this.parent!=this?this.parent.targetVersion():this.config.targetVersions?this.config.targetVersions.target:void 0}async commonDownloadAsync(){const t=this.verProtocol();let n;if("pub"==t)n=await e.Cloud.downloadScriptFilesAsync(this.verArgument());else if("github"==t){const t=await e.packagesConfigAsync();n=(await e.github.downloadPackageAsync(this.verArgument(),t)).files}else if("embed"==t)n=e.getEmbeddedScript(this.verArgument());else if("pkg"==t){const t=(this.parent||this).readFile(this.verArgument()),i=e.U.jsonTryParse(t);i||e.log(`unable to find ${this.verArgument()}`),n=i}return n}writeAssetPackFiles(){const t=JSON.parse(JSON.stringify(this.config));t.files=t.files.filter((e=>e.endsWith(".jres"))),t.files.push("gallery.ts"),t.dependencies={},t.assetPack=!0,this.config=t,this.saveConfig();let n="";for(const i of t.files){const t=this.readFile(i),s=e.U.jsonTryParse(t);if(s){const[t,r]=e.emitGalleryDeclarations(s,this.getNamespaceName());this.writeFile(i,JSON.stringify(t,null,4)),n+=r}}this.writeFile("gallery.ts",n)}getNamespaceName(){let e=this,t=e.addedBy[0];const n=[];for(;t&&t!==e;)e.depName&&n.push(e.depName),e=t,t=e.addedBy[0];return n.reverse().map((e=>ts.pxtc.escapeIdentifier(e))).join(".")}host(){return this.parent._host}readFile(e){return this.host().readFile(this,e)}writeFile(e,t){this.host().writeFile(this,e,t,!0)}readGitJson(){const t=this.readFile(e.github.GIT_JSON);return e.Util.jsonTryParse(t)}resolveDep(e){return this.parent.deps.hasOwnProperty(e)?this.parent.deps[e]:null}saveConfig(){const t=e.U.clone(this.config);delete t.additionalFilePaths;const n=e.Package.stringifyConfig(t);this.host().writeFile(this,e.CONFIG_NAME,n)}setPreferredEditor(e){this.config.preferredEditor!=e&&(this.config.preferredEditor=e,this.saveConfig())}getPreferredEditor(){let t=this.config.preferredEditor;if(!t){if(!(this.getFiles().indexOf(e.MAIN_BLOCKS)>=0))return e.JAVASCRIPT_PROJECT_NAME;const t=this.readFile(e.MAIN_BLOCKS),n=this.readFile(e.MAIN_TS);return!t&&n?e.JAVASCRIPT_PROJECT_NAME:e.BLOCKS_PROJECT_NAME}return t}parseJRes(t={}){for(const n of this.getFiles())e.U.endsWith(n,".jres")&&i(JSON.parse(this.readFile(n)),t);return t}isAssetPack(){var e;return this.level>0&&!!(null===(e=this.config)||void 0===e?void 0:e.assetPack)}resolveVersionAsync(){var t;let n=this._verspec;if(e.getEmbeddedScript(this.id))this.resolvedVersion=n="embed:"+this.id;else if(n&&"*"!=n){if("github"==this.verProtocol()){const i=e.github.parseRepoId(this._verspec);if(i&&!i.tag&&this.parent){e.debug("dep: unbound github extensions, trying to resolve tag");const s=e.semver.sortLatestTags(e.Util.values((null===(t=this.parent)||void 0===t?void 0:t.deps)||{}).map((t=>e.github.parseRepoId(t.version()))).filter((e=>(null==e?void 0:e.slug)===i.slug)).map((e=>e.tag)))[0];s&&(i.tag=s,this.resolvedVersion=n=e.github.stringifyRepo(i),e.debug(`dep: github patched ${this._verspec} to ${n}`))}}}else this.configureAsInvalidPackage(lf("version not specified for {0}",this.id)),n=this._verspec;return Promise.resolve(n)}downloadAsync(){return this.resolveVersionAsync().then((t=>{if(this.invalid())e.debug(`skip download of invalid package ${this.id}`);else if(/^embed:/.test(t)||this.installedVersion!=t)return e.debug("downloading "+t),this.host().downloadPackageAsync(this).then((()=>{this.loadConfig(),this.isAssetPack()&&this.writeAssetPackFiles(),e.debug(`installed ${this.id} /${t}`)}))}))}loadConfig(){if(0!=this.level&&this.invalid())return;const t=this.readFile(e.CONFIG_NAME);t||e.U.userError(`extension ${this.id} is missing ${e.CONFIG_NAME}`),this.parseConfig(t),0!=this.level&&(this.installedVersion=this.version()),this.saveConfig()}validateConfig(){this.config.dependencies||e.U.userError("Missing dependencies in config of: "+this.id),Array.isArray(this.config.files)||e.U.userError("Missing files in config of: "+this.id),"string"==typeof this.config.name&&this.config.name||(this.config.name=lf("Untitled")),this.config.targetVersions&&this.config.targetVersions.target&&this.config.targetVersions.targetId===e.appTarget.id&&e.appTarget.versions&&e.semver.majorCmp(this.config.targetVersions.target,e.appTarget.versions.target)>0&&e.U.userError(lf("{0} requires target version {1} (you are running {2})",this.config.name,this.config.targetVersions.target,e.appTarget.versions.target))}isPackageInUse(t,n=this.readFile(e.MAIN_TS)){let i=null;const s=e.patching.computePatches(this.targetVersion(),"missingPackage");return s&&s.forEach((e=>{Object.keys(e.map).forEach((n=>{e.map[n]===t&&(i=new RegExp(n,"g"))}))})),i||(i=new RegExp(t+"\\.","g")),i.test(n)}upgradePackagesAsync(){return this.config||this.loadConfig(),e.packagesConfigAsync().then((t=>{let n=0,i={};return e.U.iterMap(this.config.dependencies,((s,r)=>{if(e.github.isGithubId(r)){const o=e.github.upgradedPackageReference(t,r);o&&o!=r&&(e.log(`upgrading dep ${s}: ${r} -> ${o}`),i[r]=o,this.config.dependencies[s]=o,n++)}})),n&&this.saveConfig(),n&&i}))}getMissingPackages(t,n){const i=e.patching.computePatches(this.targetVersion(),"missingPackage"),s={};return n&&i&&i.forEach((e=>{Object.keys(e.map).forEach((i=>{const r=new RegExp(i,"g"),o=e.map[i];n.replace(r,(e=>(t.dependencies[o]||(s[o]="*"),"")))}))})),s}findConflictsAsync(t,i){let s,r=[];return Promise.resolve().then((()=>"string"==typeof t?n.getConfigAsync(this.targetVersion(),t,i):Promise.resolve(t))).then((t=>{var n;if(s=t,s){const t=s.yotta?e.U.jsonFlatten(s.yotta.config):null;this.parent.sortedDeps().forEach((n=>{if(s.core&&n.config.core&&s.name!=n.config.name){const t=new e.cpp.PkgConflictError(lf("conflict between core extensions {0} and {1}",s.name,n.id));return t.pkg0=n,void r.push(t)}let o=!1;if(t){const i=n.config||JSON.parse(n.readFile(e.CONFIG_NAME));if(!!i&&!!i.yotta&&!!n.config.yotta.config){const a=e.U.jsonFlatten(i.yotta.config);for(const l of Object.keys(t)){const c=a[l],u=s.yotta.configIsJustDefaults||i.yotta.configIsJustDefaults;if(a.hasOwnProperty(l)&&c!==t[l]&&!u&&(!n.parent.config.yotta||!n.parent.config.yotta.ignoreConflicts)){const t=new e.cpp.PkgConflictError(lf("conflict on yotta setting {0} between extensions {1} and {2}",l,s.name,n.id));t.pkg0=n,t.settingName=l,r.push(t),o=!0}}}}if(!o&&s.name===n.id&&n._verspec!==i&&!/^file:/.test(n._verspec)&&!/^file:/.test(i)){const t=/^github:/.test(n._verspec)&&e.github.parseRepoId(n._verspec),s=/^github:/.test(i)&&e.github.parseRepoId(i);if(!t||!s||t.fullName!==s.fullName||s.tag&&e.semver.strcmp(t.tag,s.tag)<0){const t=new e.cpp.PkgConflictError(lf("version mismatch for extension {0} (added: {1}, adding: {2})",n.id,n._verspec,i));t.pkg0=n,t.isVersionConflict=!0,r.push(t)}}}))}return Object.keys(null!==(n=null==s?void 0:s.dependencies)&&void 0!==n?n:{}).reduce(((e,t)=>e.then((()=>this.findConflictsAsync(t,s.dependencies[t]))).then((e=>r.push.apply(r,e)))),Promise.resolve())})).then((()=>{const t=e=>{const n=[];return e.addedBy.forEach((e=>{e.id!==this.id&&(n.push.apply(t(e)),n.push(e))})),n},n=[];return r.forEach((r=>{n.push.apply(n,t(r.pkg0).map((t=>{const n=new e.cpp.PkgConflictError(r.isVersionConflict?lf("a dependency of {0} has a version mismatch with extension {1} (added: {1}, adding: {2})",t.id,s.name,r.pkg0._verspec,i):lf("conflict on yotta setting {0} between extensions {1} and {2}",r.settingName,s.name,r.pkg0.id));return n.pkg0=t,n})))})),r.push.apply(r,n),r=r.filter(((e,t)=>{for(let n=0;n<t;++n)if(e.pkg0.id===r[n].pkg0.id)return!1;return!0})),r}))}configureAsInvalidPackage(t){e.log(`invalid package ${this.id}: ${t}`),this._verspec="invalid:"+this.id,this.config={name:this.id,description:t,dependencies:{},files:[]}}parseConfig(t,n){try{const e=JSON.parse(t);this.config=e}catch(t){this.configureAsInvalidPackage(lf("Syntax error in pxt.json")),e.tickEvent("package.invalidConfigEncountered")}const i=JSON.stringify(this.config);for(const t in this.config.dependencies){const n=e.patching.upgradePackageReference(this.targetVersion(),t,this.config.dependencies[t]);n!=t&&(delete this.config.dependencies[t],n&&(this.config.dependencies[n]="*"))}n&&(this.config.targetVersions={target:n}),JSON.stringify(this.config)!=i&&this.saveConfig(),this.validateConfig()}patchCorePackage(){e.Util.assert(e.appTarget.simulator&&e.appTarget.simulator.dynamicBoardDefinition),e.Util.assert(0==this.level);const t=Object.keys(this.config.dependencies).filter((t=>!!t&&(t==e.BLOCKS_PROJECT_NAME||t==e.JAVASCRIPT_PROJECT_NAME||JSON.parse((e.appTarget.bundledpkgs[t]||{})[e.CONFIG_NAME]||"{}").core)));if(0==t.length){const t=e.Package.corePackages();t.length&&this.config.dependencies[t[0].name]}else t.length>1&&(t.pop(),t.forEach((t=>{e.log(`removing core package ${t}`),delete this.config.dependencies[t]})))}resolvedDependencies(){return Object.keys(this.dependencies()).map((e=>this.resolveDep(e)))}dependencies(t=!1){if(!this.config)return{};const n=e.Util.clone(this.config.dependencies||{});return 0==this.level&&this.config.testDependencies&&e.Util.iterMap(this.config.testDependencies,((t,i)=>{("*"!=i||e.appTarget.bundledpkgs[t])&&(n[t]=i)})),t&&this.config.cppDependencies&&e.Util.jsonMergeFrom(n,this.config.cppDependencies),n}async loadAsync(t=!1,i){var s;if(this.isLoaded)return;0!=this.level||e.appTarget.multiVariants||e.setAppTargetVariant(null),this.isLoaded=!0;const r=this.readFile(e.CONFIG_NAME);if(null==r?t||e.U.userError("Package not installed: "+this.id+", did you forget to run `pxt install`?"):this.parseConfig(r),0!=this.level||t||await this.upgradePackagesAsync(),t&&(await this.downloadAsync(),0!==this.level&&!this.isAssetPack()))for(const e of this.addedBy)if(null===(s=e.config.assetPacks)||void 0===s?void 0:s[this.id]){this.writeAssetPackFiles();break}if(0==this.level&&t){const t=await this.upgradePackagesAsync();t&&(Object.keys(t).forEach((t=>e.tickEvent("package.doubleload",{extension:t}))),e.log("upgraded, downloading again"),e.debug(t),await this.downloadAsync())}if(e.appTarget.simulator&&e.appTarget.simulator.dynamicBoardDefinition&&(0==this.level&&this.patchCorePackage(),this.config.compileServiceVariant&&e.setAppTargetVariant(this.config.compileServiceVariant),this.config.files.indexOf("board.json")>=0)){const t=e.appTarget.simulator.boardDefinition=JSON.parse(this.readFile("board.json"));t.id=this.config.name,e.appTarget.appTheme.boardName=t.boardName||lf("board"),e.appTarget.appTheme.driveDisplayName=t.driveDisplayName||lf("DRIVE");let n=t=>{let n=/^pkg:\/\/(.*)/.exec(t);if(n){let t=n[1],i=this.readFile(t);return e.U.toDataUri(i,e.U.getMime(t))}return t},i=e.appTarget.simulator.boardDefinition;if("object"==typeof i.visual){let e=i.visual;e.image=n(e.image),e.outlineImage=n(e.outlineImage)}}const o=(t,n)=>{var i;if(e.debug(`version spec mismatch: ${t._verspec} != ${n}`),/^github:/.test(t._verspec)&&/^github:/.test(n)){const s=e.github.parseRepoId(t._verspec),r=e.github.parseRepoId(n);if((null==s?void 0:s.slug)&&(null==s?void 0:s.slug)===(null==r?void 0:r.slug)){const o=(null==s?void 0:s.tag)||(null===(i=t.config)||void 0===i?void 0:i.version),a=r.tag;if(o&&!a)return void e.debug(`unversioned ${n}, using ${o}`);const l=e.semver.strcmp(o,r.tag);if(0==l)return void e.debug(`resolved version are ${o}`);if(l>0)return void e.debug(`auto-upgraded ${n} to ${o}`)}}/^file:/.test(t._verspec)||/^file:/.test(n)?e.debug("ignore file: mismatch issues"):t.configureAsInvalidPackage(lf("version mismatch"))},a=async(i,s,r=!1)=>{i||(i=s.dependencies(r)),e.debug(`deps: ${s.id}->${Object.keys(i).join(", ")}`),i=e.github.resolveMonoRepoVersions(i),e.debug(`deps: resolved ${s.id}->${Object.keys(i).join(", ")}`);for(let a of Object.keys(i)){let l=i[a]||"*";e.debug(`dep: load ${s.id}.${a}${r?"++":""}: ${l}`),"hw"==a&&e.hwVariant&&(a="hw---"+e.hwVariant);const c=e.github.parseRepoId(l);if(null==c?void 0:c.slug){const t=Object.values(s.parent.deps).map((t=>e.github.parseRepoId(t._verspec))).filter((e=>(null==e?void 0:e.slug)===c.slug)).map((e=>e.tag)).reduce(((t,n)=>e.semver.strcmp(t,n)>0?t:n),"0.0.0");e.debug(`dep: common repo ${c.slug} version found ${t}`),e.semver.strcmp(t,"0.0.0")>0&&(!c.tag||e.semver.strcmp(t,c.tag)>0)&&(e.debug(`dep: upgrade from ${c.tag} to ${t}`),c.tag=t,l=e.github.stringifyRepo(c,!0))}let u=s.resolveDep(a);if(u){if(u.invalid()||u._verspec===l||o(u,l),u.invalid()){u.level=Math.min(u.level,s.level+1),u.addedBy.push(s);continue}r||(u.level=Math.min(u.level,s.level+1),u.addedBy.push(s))}else u=new n(a,l,s.parent,s,a),r&&(u.cppOnly=!0),s.parent.deps[a]=u,s.parent.deps[a.replace(/---.*/,"")]=u,await u.loadAsync(t)}};if(await a(null,this),this.patchAppTargetPalette(),this.config.screenSize&&e.appTarget.runtime&&(e.appTarget.runtime.screenSize=e.U.clone(this.config.screenSize)),0===this.level){const t=this.readFile(e.MAIN_TS);if(t){const n=this.getMissingPackages(this.config,t);let i=!1;for(const t of Object.keys(n)){const s=await this.findConflictsAsync(t,n[t]);if(s.length){const n=s.map((e=>e.pkg0.id)).join(", "),i=s.map((e=>e.settingName)).filter((e=>!!e)).join(", ");e.log(`skipping missing package ${t} because it conflicts with the following packages: ${n} (conflicting settings: ${i})`)}else{e.log(`adding missing package ${t}`),i=!0,this.config.dependencies[t]="*";const s={};s[t]=n[t],await a(s,this)}}i&&(this.saveConfig(),this.validateConfig())}await Promise.all(e.U.values(this.parent.deps).map((e=>a(null,e,!0))))}e.debug(` installed ${this.id}`)}getFiles(){let t;t=0!=this.level||this.ignoreTests?this.config.files.slice(0):this.config.files.concat(this.config.testFiles||[]);const i=this.config.fileDependencies;return this.config.fileDependencies&&(t=t.filter((t=>{const s=i=>{if("!"==(i=i.trim())[0])return!s(i.slice(1));if(/^[\w-]+$/.test(i)){const e=this.parent.resolveDep(i);return!(!e||e.cppOnly)}const r=/^target:(\w+)$/.exec(i);return r?r[1]==e.appTarget.id||r[1]==e.appTarget.platformid:(n.depWarnings[i]||(n.depWarnings[i]=!0,e.log(`invalid dependency expression: ${i} in ${this.id}/${t}`)),!1)},r=e.U.lookup(i,t);return!r||!r.trim()||r.split("||").some((e=>e.split("&&").every(s)))}))),t}addSnapshot(t,n=[""]){for(let i of this.getFiles())n.some((t=>e.U.endsWith(i,t)))&&(t[this.id+"/"+i]=this.readFile(i));t[this.id+"/"+e.CONFIG_NAME]=this.readFile(e.CONFIG_NAME)}packageLocalizationStringsAsync(t){const n=e.appTarget.id,i=[this.config.name+"-jsdoc",this.config.name],s={};e.appTarget.appTheme;return this.config.skipLocalization?Promise.resolve(s):e.Util.liveLocalizationEnabled()&&"this"!=this.id&&e.appTarget.bundledpkgs[this.id]?(e.debug(`loading live translations for ${this.id}`),Promise.all(i.map((i=>e.Util.downloadLiveTranslationsAsync(t,`${n}/${i}-strings.json`).then((n=>{n&&Object.keys(n).length?e.Util.jsonMergeFrom(s,n):(e.tickEvent("translations.livetranslationsfailed",{filename:i}),e.Util.jsonMergeFrom(s,this.bundledStringsForFile(t,i)))})).catch((r=>{e.tickEvent("translations.livetranslationsfailed",{filename:i}),e.log(`error while downloading ${n}/${i}-strings.json`),e.Util.jsonMergeFrom(s,this.bundledStringsForFile(t,i))}))))).then((()=>s))):(i.map((e=>this.bundledStringsForFile(t,e))).filter((e=>!!e)).forEach((t=>e.Util.jsonMergeFrom(s,t))),Promise.resolve(s))}bundledStringsForFile(t,n){let i={},[s,r,o]=e.Util.normalizeLanguageCode(t);const a=this.config.files;let l=`_locales/${s}/${n}-strings.json`;if(o&&-1===a.indexOf(l)&&(l=`_locales/${o}/${n}-strings.json`),r&&-1===a.indexOf(l)&&(l=`_locales/${r}/${n}-strings.json`),a.indexOf(l)>-1)try{i=JSON.parse(this.readFile(l))}catch(n){e.reportError("extension","Extension localization JSON failed to parse",{fileName:l,lang:t,extension:this.verArgument()});"github"===this.verProtocol()&&e.tickEvent("loc.errors.json",{repo:this.verArgument(),file:l})}return i}patchAppTargetPalette(){this.config.palette&&e.appTarget.runtime&&(e.appTarget.runtime.palette=e.U.clone(this.config.palette),this.config.paletteNames&&(e.appTarget.runtime.paletteNames=this.config.paletteNames))}}n.depWarnings={},e.Package=n;function i(e,t={}){let n=e["*"]||{};for(let i of Object.keys(e)){if("*"==i)continue;let s=e[i];"string"==typeof s&&(s={data:s});let r=s.namespace||n.namespace||"";r&&!r.endsWith(".")&&(r+=".");let o=s.id||r+i,a=s.icon,l=s.mimeType||n.mimeType,c=s.dataEncoding||n.dataEncoding||"base64";a||"base64"!=c||"image/png"!=l&&"image/jpeg"!=l||(a="data:"+l+";base64,"+s.data),t[o]={id:o,data:s.data,dataEncoding:c,icon:a,namespace:r,mimeType:l,tilemapTile:s.tilemapTile,displayName:s.displayName,tileset:s.tileset,tags:s.tags}}return t}e.MainPackage=class extends n{constructor(e){super("this","file:.",null,null,null),this._host=e,this.deps={},this.parent=this,this.addedBy=[this],this.level=0,this.deps[this.id]=this}installAllAsync(e){return this.loadAsync(!0,e)}sortedDeps(t=!1){let n={},i=[];const s=e=>e.config?Object.keys(e.config.cppDependencies||{}).length:0,r=o=>{if(!o||e.U.lookup(n,o.id))return;n[o.id]=!0;const a=Object.keys(o.dependencies(t)).map((e=>this.resolveDep(e)));a.sort(((t,n)=>s(n)-s(t)||e.U.strcmp(t.id,n.id))),a.forEach(r),i.push(o.id)};return r(this),i.map((e=>this.resolveDep(e)))}localizationStringsAsync(t){const n={};return Promise.all(e.Util.values(this.deps).map((e=>e.packageLocalizationStringsAsync(t).then((e=>{e&&Object.keys(e).forEach((t=>{n[t]||(n[t]=e[t])}))}))))).then((()=>{const t=e.U.getLocalizedStrings();return Object.keys(n).forEach((i=>{(e.U.startsWith(i,"{id:subcategory}")||e.U.startsWith(i,"{id:group}"))&&(t[i]||(t[i]=n[i]))})),e.U.setLocalizedStrings(t),Promise.resolve(n)}))}getTargetOptions(){let t=e.U.clone(e.appTarget.compile);return e.U.assert(!!t),t.utf8||this.sortedDeps(!0).forEach((n=>{n.config&&n.config.utf8&&(e.debug("forcing utf8 mode: pkg="+n.id),t.utf8=!0)})),t}getJRes(){if(!this._jres){this._jres={};for(const e of this.sortedDeps())e.parseJRes(this._jres);const t=(e.appTarget.runtime&&e.appTarget.runtime.palette?e.appTarget.runtime.palette:["#000000","#ffffff"]).map((e=>("000000"+parseInt(e.replace(/#/,""),16).toString(16)).slice(-6))).join("");this._jres.__palette={id:"__palette",data:t,dataEncoding:"hex",mimeType:"application/x-palette"}}return this._jres}updateJRes(){this._jres&&this.parseJRes(this._jres)}resolveBannedCategories(){if(void 0!==this._resolvedBannedCategories)return this._resolvedBannedCategories;let t=[];return e.appTarget&&e.appTarget.runtime&&e.appTarget.runtime.bannedCategories&&e.appTarget.runtime.bannedCategories.length&&(t=e.appTarget.runtime.bannedCategories.slice(),Object.keys(this.deps).map((e=>this.deps[e])).filter((e=>!!e)).map((t=>e.Util.jsonTryParse(t.readFile(e.CONFIG_NAME)))).filter((e=>e&&e.requiredCategories)).forEach((e=>e.requiredCategories.forEach((e=>{const n=t.indexOf(e);n>-1&&t.splice(n,1)})))),this._resolvedBannedCategories=t),this._resolvedBannedCategories=t,this._resolvedBannedCategories.length||(this._resolvedBannedCategories=null),this._resolvedBannedCategories}async getCompileOptionsAsync(t=this.getTargetOptions()){let n={sourceFiles:[],fileSystem:{},target:t,name:this.config?this.config.name:""};const i=(t,n)=>{this.config.files.indexOf(t)<0&&e.U.userError(lf("please add '{0}' to \"files\" in {1}",t,e.CONFIG_NAME)),n="// Auto-generated. Do not edit.\n"+n+"\n// Auto-generated. Do not edit. Really.\n",this.host().readFile(this,t,!0)!==n&&(e.debug(`updating ${t} (size=${n.length})...`),this.host().writeFile(this,t,n,!0))};let s=!1;const r=async n=>{const r={extinfo:null,target:null},o=e.appTargetVariant;let a;n&&e.setAppTargetVariant(n,{temporary:!0});try{r.target=e.appTarget.compile,a=e.cpp.getExtensionInfo(this),s||!a.shimsDTS&&!a.enumsDTS||(s=!0,a.shimsDTS&&i("shims.d.ts",a.shimsDTS),a.enumsDTS&&i("enums.d.ts",a.enumsDTS))}finally{n&&e.setAppTargetVariant(o,{temporary:!0})}a.appVariant=n;const l=t.isNative?await this.host().getHexInfoAsync(a):null;return a=e.U.flatClone(a),t.keepCppFiles||(delete a.compileData,delete a.generatedFiles,delete a.extensionFiles),a.hexinfo=l,r.extinfo=a,r};let o;await this.loadAsync(),n.bannedCategories=this.resolveBannedCategories(),e.debug(`building: ${this.sortedDeps().map((e=>e.config.name)).join(", ")}`),o=e.appTarget.multiVariants?e.appTargetVariant?[e.appTargetVariant]:e.appTarget.alwaysMultiVariant||e.appTarget.compile.switches.multiVariant?e.appTarget.multiVariants:[e.appTarget.multiVariants[0]]:[null];let a=null;await Promise.all(o.map((async t=>{a&&e.debug(`building for ${t}`);const i=await r(t),s=i.extinfo;s.appVariant=t,s.outputPrefix=1!=o.length&&t?t+"-":"",a?n.otherMultiVariants.push(i):(i.target.isNative=n.target.isNative,n.target=i.target,a=s,n.otherMultiVariants=[])}))),n.extinfo=a,n.target.preferredEditor=this.getPreferredEditor();if(!(e.appTarget.compile.shortPointers||"vm"==e.appTarget.compile.nativeType||this.config.binaryonly||!n.target.isNative)){const t=await this.filesToBePublishedAsync(!0),i=JSON.stringify({name:this.config.name,comment:this.config.description,status:"unpublished",scriptId:this.installedVersion,cloudId:e.CLOUD_ID+e.appTarget.id,editor:this.getPreferredEditor(),targetVersions:e.appTarget.versions}),s=JSON.stringify(t),r=await e.lzmaCompressAsync(i+s);r&&(n.embedMeta=JSON.stringify({compression:"LZMA",headerSize:i.length,textSize:s.length,name:this.config.name,eURL:e.appTarget.appTheme.embedUrl,eVER:e.appTarget.versions?e.appTarget.versions.target:"",pxtTarget:e.appTarget.id}),n.embedBlob=ts.pxtc.encodeBase64(e.U.uint8ArrayToString(r)))}for(const e of this.sortedDeps())for(const t of e.getFiles())if(/\.(ts|asm|py)$/.test(t)){let i=t;e.level>0&&(i="pxt_modules/"+e.id+"/"+t),n.sourceFiles.push(i),n.fileSystem[i]=e.readFile(t)}n.jres=this.getJRes();const l=e.appTarget.runtime&&e.appTarget.runtime.functionsOptions;n.allowedArgumentTypes=l&&l.extraFunctionEditorTypes&&l.extraFunctionEditorTypes.map((e=>e.typeName)).concat("number","boolean","string");for(const e of this.sortedDeps())e.patchAppTargetPalette();return this.patchAppTargetPalette(),n}prepareConfigToBePublished(){const t=e.U.clone(this.config);return delete t.installedVersion,delete t.additionalFilePath,delete t.additionalFilePaths,t.targetVersions||(t.targetVersions=e.Util.clone(e.appTarget.versions)),e.U.iterMap(t.dependencies,((n,i)=>{if(!i||/^(file|workspace):/.test(i)){i="*";try{const t=this.resolveDep(n).readGitJson();if(t&&t.repo){let n=e.github.parseRepoId(t.repo);n.tag=t.commit.tag||t.commit.sha,i=e.github.stringifyRepo(n)}}catch(e){}t.dependencies[n]=i}})),t}filesToBePublishedAsync(t=!1){const n={};return this.loadAsync().then((()=>{t||this.config.public||e.U.userError('Only packages with "public":true can be published');const i=this.prepareConfigToBePublished();n[e.CONFIG_NAME]=e.Package.stringifyConfig(i);for(let t of this.getFiles()){if(t==e.CONFIG_NAME)continue;let i=this.readFile(t);null==i&&e.U.userError("referenced file missing: "+t),n[t]=i}return e.U.sortObjectFields(n)}))}saveToJsonAsync(){return this.filesToBePublishedAsync(!0).then((t=>({meta:{cloudId:e.CLOUD_ID+e.appTarget.id,targetVersions:e.appTarget.versions,editor:this.getPreferredEditor(),name:this.config.name},source:JSON.stringify(t,null,2)})))}compressToFileAsync(){return this.saveToJsonAsync().then((t=>e.lzmaCompressAsync(JSON.stringify(t,null,2))))}computePartDefinitions(t){if(!t||!t.length)return{};let n={};return this.sortedDeps().forEach((i=>{let s=i.readFile("pxtparts.json");if(s)try{let r=JSON.parse(s);Object.keys(r).forEach((s=>{if(t.indexOf(s)>=0){let t=n[s]=r[s];if("string"==typeof t.visual.image&&/\.svg$/i.test(t.visual.image)){let n=i.readFile(t.visual.image);n||e.reportError("parts","invalid part definition",{error:`missing visual ${t.visual.image}`}),/^data:image\/svg\+xml/.test(n)||(n="data:image/svg+xml,"+encodeURIComponent(n)),t.visual.image=n}}}))}catch(t){e.reportError("parts","invalid pxtparts.json file")}})),n}},e.inflateJRes=i,e.allPkgFiles=function(t){return[e.CONFIG_NAME].concat(t.files||[]).concat(t.testFiles||[])},e.isPkgBeta=function(e){return e&&/\bbeta\b/.test(e.description)}}(pxt||(pxt={})),function(e){!function(t){let n,i,s,r,o,a=()=>{};function l(){if(o)return o;let t=Promise.resolve();if(n){e.debug("packetio: disconnect");const s=n;t=t.then((()=>s.disconnectAsync())).then((()=>s.io.disposeAsync())).catch((t=>{e.reportException(t)})).finally((()=>{i=void 0,n=void 0,o=void 0})),a&&(t=t.then((()=>a()))),o=t}return t}t.isActive=function(){return!!n},t.isConnected=function(){return!!(null==n?void 0:n.isConnected())},t.isConnecting=function(){return!!(null==n?void 0:n.isConnecting())},t.icon=function(){var t;return!!n&&(n.icon||(null===(t=e.appTarget.appTheme.downloadDialogTheme)||void 0===t?void 0:t.deviceIcon)||"usb")},t.unsupportedParts=function(){return(null==n?void 0:n.unsupportedParts)?n.unsupportedParts():[]},t.deviceVariant=function(){return null==n?void 0:n.devVariant},t.disconnectAsync=l,t.configureEvents=function(e,t,i){a=e,s=t,r=i,n&&(n.io.onConnectionChanged=a,n.onSerial=s,n.onCustomEvent=i)},t.sendCustomEventAsync=function(e,t){return n?n.sendCustomEventAsync(e,t):Promise.resolve()},t.initAsync=function(o=!1){if(e.debug("packetio: init "+(o?"(force)":"")),!i){let c=Promise.resolve();o&&(c=c.then((()=>l()))),i=c.then((()=>n?Promise.resolve(n):t.mkPacketIOAsync?(e.debug("packetio: new wrapper"),t.mkPacketIOAsync().then((e=>(e.onConnectionChanged=a,n=t.mkPacketIOWrapper(e),s&&(n.onSerial=s),r&&(n.onCustomEvent=r),a&&a(),n)))):(e.debug("packetio: not defined, skipping"),Promise.resolve(void 0)))).finally((()=>{i=void 0}))}return i}}(e.packetio||(e.packetio={}))}(pxt||(pxt={})),function(e){!function(t){function n(t,n,i){const s=e.semver.tryParse(t||"0.0.0")||e.semver.tryParse("0.0.0");let r=[];return Object.keys(n).filter((t=>e.semver.inRange(t,s))).forEach((e=>r=r.concat(n[e]))),i&&(r=r.filter((e=>e.type==i))),r.length?r:void 0}function i(e,t,n){let i=t;return n&&(n.filter((e=>"api"===e.type)).forEach((e=>{Object.keys(e.map).forEach((t=>{const n=new RegExp(t,"g");i=i.replace(n,e.map[t])}))})),n.filter((e=>"userenum"===e.type)).forEach((e=>{Object.keys(e.map).forEach((t=>{const n=new RegExp("enum\\s+"+t+"\\s*{","gm");i=i.replace(n,`enum ${e.map[t]} {`);const s=new RegExp(`(^|[^_a-zA-Z0-9])${t}(\\s*\\.)`,"g");i=i.replace(s,`$1${e.map[t]}$2`)}))}))),i}t.computePatches=function(t,i){const s=e.appTarget.compile?e.appTarget.compile.patches:void 0;if(s)return n(t,s,i)},t.computePyPatches=function(t,i){const s=e.appTarget.compile?e.appTarget.compile.pyPatches:void 0;if(s)return n(t,s,i)},t.upgradePackageReference=function(t,n,i){if("*"!=i)return n;const s=e.patching.computePatches(t,"package");let r=n;return s&&s.forEach((e=>{Object.keys(e.map).forEach((t=>{r==t&&(r=e.map[t])}))})),r},t.patchJavaScript=function(t,n){return i(t,n,e.patching.computePatches(t))},t.patchPython=function(t,n){return i(t,n,e.patching.computePyPatches(t))}}(e.patching||(e.patching={}))}(pxt||(pxt={})),function(e){e.react||(e.react={})}(pxt||(pxt={})),function(e){!function(t){function n(t,n){if(t){if(n){let i=t.major-n.major||t.minor-n.minor||t.patch-n.patch;if(i)return i;if(0==t.pre.length&&n.pre.length>0)return 1;if(t.pre.length>0&&0==n.pre.length)return-1;for(let s=0;s<t.pre.length+1;++s){let r=t.pre[s],o=n.pre[s];if(!r)return o?-1:0;if(!o)return 1;if(/^\d+$/.test(r)){if(!/^\d+$/.test(o))return-1;if(i=parseInt(r)-parseInt(o),i)return i}else{if(/^\d+$/.test(o))return 1;if(i=e.U.strcmp(r,o),i)return i}}return 0}return-1}return n?1:0}function i(t,n){let i=s(t)||s(n);return i||e.U.userError(e.U.lf("'{0}' doesn't look like a semantic version number",t)),i}function s(e){if(!e)return null;if("*"===e)return{major:Number.MAX_SAFE_INTEGER,minor:Number.MAX_SAFE_INTEGER,patch:Number.MAX_SAFE_INTEGER,pre:[],build:[]};/^v\d/i.test(e)&&(e=e.slice(1));let t=/^(\d+)\.(\d+)\.(\d+)(-([0-9a-zA-Z\-\.]+))?(\+([0-9a-zA-Z\-\.]+))?$/.exec(e);return t?{major:parseInt(t[1]),minor:parseInt(t[2]),patch:parseInt(t[3]),pre:t[5]?t[5].split("."):[],build:t[7]?t[7].split("."):[]}:null}function r(e){let t=e.major+"."+e.minor+"."+e.patch;return e.pre.length&&(t+="-"+e.pre.join(".")),e.build.length&&(t+="+"+e.build.join(".")),t}function o(t,i){let r=s(t),o=s(i);return r||o?n(r,o):e.U.strcmp(t,i)}function a(e,t){let i=e.split(" - ");if(2!=i.length)return!1;let r=s(i[0]),o=s(i[1]);if(!r||!o)return!1;if(!t)return!0;const a=n(r,t),l=n(t,o);return a<=0&&l<0}t.cmp=n,t.parse=i,t.tryParse=s,t.normalize=function(e){return r(i(e))},t.stringify=r,t.majorCmp=function(e,t){let n=s(e),i=s(t);return n.major-i.major},t.strcmp=o,t.inRange=a,t.sortLatestTags=function(e){const n=e.filter((e=>!!t.tryParse(e)));return n.sort(o),n.reverse(),n},t.test=function(){console.log("Test semver");let t=["0.9.0","1.0.0-0.3.7","1.0.0-alpha","1.0.0-alpha.1","1.0.0-alpha.beta","1.0.0-beta","1.0.0-beta.2","1.0.0-beta.11","1.0.0-rc.1","1.0.0-x.7.z.92","1.0.0","1.0.1","1.9.0","1.10.0","1.11.0"];for(let s=0;s<t.length;++s){let o=i(t[s]);console.log(t[s],o),e.U.assert(r(o)==t[s]);for(let r=0;r<t.length;++r){let a=n(o,i(t[r]));console.log(t[s],t[r],a),s<r?e.U.assert(a<0):s>r?e.U.assert(a>0):e.U.assert(0==a)}}const o=s("1.2.3");e.U.assert(a("0.1.2 - 2.2.3",o)),e.U.assert(a("1.2.3 - 2.2.3",o)),e.U.assert(!a("0.0.0 - 1.2.3",o)),e.U.assert(!a("1.2.4 - 4.2.3",o)),e.U.assert(!a("0.0.0 - 0.0.1",o))}}(e.semver||(e.semver={}))}(pxt||(pxt={})),function(e){!function(e){function t(t){return e.Util.values(t.byQName).filter((e=>e.attributes.block&&/^{[^:]+:[^}]+}/.test(e.attributes.block))).forEach((e=>{e.attributes.block=e.attributes.block.replace(/^{[^:]+:[^}]+}/,"")})),t}e.assert=e.Util.assert,e.oops=e.Util.oops,e.U=e.Util,e.ON_START_TYPE="pxt-on-start",e.ON_START_COMMENT="on start",e.HANDLER_COMMENT="code goes here",e.TS_STATEMENT_TYPE="typescript_statement",e.TS_DEBUGGER_TYPE="debugger_keyword",e.TS_BREAK_TYPE="break_keyword",e.TS_CONTINUE_TYPE="continue_keyword",e.TS_OUTPUT_TYPE="typescript_expression",e.TS_RETURN_STATEMENT_TYPE="function_return",e.PAUSE_UNTIL_TYPE="pxt_pause_until",e.COLLAPSED_BLOCK="pxt_collapsed_block",e.FUNCTION_DEFINITION_TYPE="function_definition",e.BINARY_JS="binary.js",e.BINARY_ASM="binary.asm",e.BINARY_HEX="binary.hex",e.BINARY_UF2="binary.uf2",e.BINARY_ELF="binary.elf",e.BINARY_PXT64="binary.pxt64",e.BINARY_ESP="binary.bin",e.BINARY_SRCMAP="binary.srcmap",e.NATIVE_TYPE_THUMB="thumb",e.NATIVE_TYPE_VM="vm",e.BuildSourceMapHelpers=function(e,t,n){const i=e=>{const t=e.split("\n").map((e=>e.length)),n=t.reduce((({lens:e,sum:t},n)=>({lens:[...e,t+n+1],sum:t+n+1})),{lens:[],sum:0}).lens;return{posToLineCol:e=>{const i=n.reduce(((t,n,i)=>e<n?t:i+1),0);return[i,t[i]-(n[i]-e)+1]},lineColToPos:(e,t)=>(n[e-1]||0)+t}},s={ts:i(t),py:i(n)},r=e=>e.endPos-e.startPos,o=(t,n)=>{const{startPos:i,endPos:s}=t;return e.filter((e=>e[n].startPos<=i&&s<=e[n].endPos))},a=(e,t)=>{const n=o(e,t);return n.reduce(((e,n)=>r(n[t])<r(e[t])?n:e),n[0])},l={ts:{allOverlaps:e=>o(e,"ts"),smallestOverlap:e=>a(e,"ts")},py:{allOverlaps:e=>o(e,"py"),smallestOverlap:e=>a(e,"py")}},c=(e,t)=>n=>{const[i,o]=(t=>[s[e].lineColToPos(t.line,t.column),t.length])(n),l=a({startPos:i,endPos:i+o},e);if(!l)return;const[c,u]=s[t].posToLineCol(l[t].startPos);return{fileName:`main.${t}`,start:l[t].startPos,length:r(l[t]),line:c,column:u}},u=c("ts","py"),d=c("py","ts");return{ts:Object.assign(Object.assign(Object.assign({},s.ts),l.ts),{locToLoc:u,getText:e=>t.substring(e.startPos,e.endPos)}),py:Object.assign(Object.assign(Object.assign({},s.py),l.py),{locToLoc:d,getText:e=>n.substring(e.startPos,e.endPos)})}},e.computeUsedParts=function(e,t,n=!1){if(!e.usedSymbols||!pxt.appTarget.simulator||!n&&!pxt.appTarget.simulator.parts)return[];const i=(e,t)=>{if(e){const n=e.split(/[ ,]+/g);t.push(...n.filter((e=>!!e&&t.indexOf(e)<0)))}};let s=[],r=[];if(Object.keys(e.usedSymbols).forEach((t=>{const n=e.usedSymbols[t];i(null==n?void 0:n.attributes.parts,s),i(null==n?void 0:n.attributes.hiddenParts,r)})),t){const e=pxt.appTarget.simulator.boardDefinition.onboardComponents;e&&("ignorebuiltin"===t?s=s.filter((t=>-1===e.indexOf(t))):"onlybuiltin"===t&&(s=s.filter((t=>e.indexOf(t)>=0))))}return s=s.filter((e=>r.indexOf(e)<0)),s.sort(),s=s.reverse(),s},e.buildSimJsInfo=function(t){var n;return{js:t.outfiles[e.BINARY_JS],targetVersion:pxt.appTarget.versions.target,fnArgs:t.usedArguments,parts:e.computeUsedParts(t,"ignorebuiltin"),usedBuiltinParts:e.computeUsedParts(t,"onlybuiltin"),allParts:e.computeUsedParts(t,void 0,!0),breakpoints:null===(n=t.breakpoints)||void 0===n?void 0:n.map((e=>e.id))}},e.blocksCategory=function(t){const n=t?t.attributes.blockNamespace||t.namespace:void 0;return n?e.Util.capitalize(n.split(".")[0]):void 0},e.getBlocksInfo=function(t,n){var i,o;let a=[];const l={},c={},u={},d={},h={};function p(t,n){const i="get"==t,s="set"==t,o="number"==n.retType,d=i?c:s?l:u,h=`${n.namespace}.${n.retType}`;let p=e.U.lookup(d,h);if(!p){const l=`@${t}@`;let c,u;if(n.attributes.blockCombineShadow){const t=n.attributes.blockCombineShadow,i=t.match(/^([^,.]*),?([^,.]*)$/);i&&3==i.length&&(c=i[1].trim(),u=i[2].trim(),0!=u.length||e.Util.endsWith(t,",")||(u=c,c=""))}const f=`${n.attributes.blockSetVariable||n.namespace.toLocaleLowerCase()}=${c||""}`,m=`value=${u||""}`;p=d[h]={attributes:{blockId:`${o?n.namespace:h}_blockCombine_${t}`,callingConvention:0,group:n.attributes.group,paramDefl:{},jsDoc:i?e.U.lf("Read value of a property on an object"):e.U.lf("Update value of property on an object")},name:l,namespace:n.namespace,fileName:n.fileName,qName:`${h}.${l}`,pkg:n.pkg,kind:2,parameters:[{name:"property",description:i?e.U.lf("the name of the property to read"):e.U.lf("the name of the property to change"),isEnum:!0,type:"@combined@"},{name:"value",description:s?e.U.lf("the new value of the property"):e.U.lf("the amount by which to change the property"),type:n.retType}].slice(0,i?1:2),retType:i?n.retType:"void",combinedProperties:[]},p.attributes.block=i?e.U.lf("%{0} %property",f):s?e.U.lf("set %{0} %property to %{1}",f,m):e.U.lf("change %{0} %property by %{1}",f,m),r(p.attributes),pxt.Util.isTranslationMode()&&(p.attributes.translationId=p.attributes.block,p.attributes.block=i?`%${f} %property`:s?`set %${f} %property to %${m}`:`change %${f} %property by %${m}`,r(p.attributes),pxt.crowdin.inContextLoadAsync(p.attributes.translationId).then((e=>{p.attributes.block=e,r(p.attributes)}))),a.push(p)}p.combinedProperties.push(n.qName)}for(let n of e.Util.values(t.byQName)){if("ENUM_GET"===n.attributes.shim&&n.attributes.enumName&&n.attributes.blockId){let e=!1;if(d[n.attributes.enumName]&&(console.warn(`Enum block ${n.attributes.blockId} trying to overwrite enum ${n.attributes.enumName}`),e=!0),n.attributes.enumMemberName||(console.warn(`Enum block ${n.attributes.blockId} should specify enumMemberName`),e=!0),n.attributes.enumPromptHint||(console.warn(`Enum block ${n.attributes.blockId} should specify enumPromptHint`),e=!0),n.attributes.enumInitialMembers&&n.attributes.enumInitialMembers.length||(console.warn(`Enum block ${n.attributes.blockId} should specify enumInitialMembers`),e=!0),e)continue;const t=parseInt(n.attributes.enumStartValue);d[n.attributes.enumName]={blockId:n.attributes.blockId,name:n.attributes.enumName,memberName:n.attributes.enumMemberName,firstValue:isNaN(t)?void 0:t,isBitMask:n.attributes.enumIsBitMask,isHash:n.attributes.enumIsHash,initialMembers:n.attributes.enumInitialMembers,promptHint:n.attributes.enumPromptHint}}if("KIND_GET"===n.attributes.shim&&n.attributes.blockId){const i=n.attributes.kindNamespace||n.attributes.blockNamespace||n.namespace;if(h[i]){console.warn(`More than one block defined for kind ${i}`);continue}const s=[];if(t.byQName[i])for(const n of e.Util.values(t.byQName))n.namespace===i&&n.attributes.isKind&&s.push(n.name);h[i]={blockId:n.attributes.blockId,name:i,memberName:n.attributes.kindMemberName||i,initialMembers:s,promptHint:n.attributes.enumPromptHint||e.Util.lf("Create a new kind..."),createFunctionName:n.attributes.kindCreateFunction||"create"}}if(n.attributes.blockCombine)/@set/.test(n.name)||p("get",n),n.isReadOnly||("number"==n.retType&&p("change",n),p("set",n));else if(n.attributes.block&&!n.attributes.fixedInstance&&7!=n.kind&&5!=n.kind&&9!=n.kind&&8!=n.kind){if(n.attributes.blockId||(n.attributes.blockId=n.qName.replace(/\./g,"_")),"true"==n.attributes.block){let t=e.U.uncapitalize(n.name);1!=n.kind&&2!=n.kind||(t+=" %"+n.namespace.toLowerCase());const a=null!==(o=null===(i=n.parameters)||void 0===i?void 0:i.filter((e=>!s(e))))&&void 0!==o?o:[];for(let e of a)t+=" %"+e.name;n.attributes.block=t,r(n.attributes)}a.push(n)}}for(let n of a){let i=e.U.lookup(t.byQName,n.namespace);if(!i)continue;let s=i.attributes,r=n.attributes;for(let e of["blockNamespace","color","blockGap"])void 0===r[e]&&s[e]&&(r[e]=s[e])}var f;return n&&((f=n).length&&(a=a.filter((e=>{let t=(e.attributes.blockNamespace||e.namespace).split(".")[0];return-1===f.indexOf(t)})))),{apis:t,blocks:a,blocksById:pxt.Util.toDictionary(a,(e=>e.attributes.blockId)),enumsByName:d,kindsByName:h}},e.tsSnippetToPySnippet=function(t,n){const i={true:"True",false:"False",null:"None"}[t];if(i)return i;if(n&&6==n.kind||!n&&t.includes(".")){const n=t.lastIndexOf("."),i=t.substr(0,n);let s=t.substr(n+1);return s=e.U.snakify(s).toUpperCase(),i?`${i}.${s}`:s}return t},e.apiLocalizationStrings={},e.localizeApisAsync=async function(n,i){const s=e.Util.userLanguage();if("en"==s)return Promise.resolve(t(n));const o=s.toLowerCase(),a=o+"|jsdoc",l=o+"|block",c=await i.localizationStringsAsync(s);e.apiLocalizationStrings&&e.Util.jsonMergeFrom(c,e.apiLocalizationStrings);const u=e.Util.values(n.byQName).filter((e=>e.attributes._translatedLanguageCode!==s));return await e.Util.promiseMapAll(u,(async t=>{var i,u,d;const h=t.attributes.useLoc||t.attributes.blockAliasFor,p=h&&n.byQName[h];t.attributes._untranslatedJsDoc&&(t.attributes.jsDoc=t.attributes._untranslatedJsDoc),t.attributes._untranslatedBlock&&(t.attributes.jsDoc=t.attributes._untranslatedBlock);const f=(e,n)=>{var i,s;return c[t.qName+e]||(null===(i=t.attributes.locs)||void 0===i?void 0:i[n])||p&&(c[p.qName+e]||(null===(s=p.attributes.locs)||void 0===s?void 0:s[n]))},m=f("",a);m&&(t.attributes._untranslatedJsDoc||(t.attributes._untranslatedJsDoc=t.attributes.jsDoc),t.attributes.jsDoc=m),null===(i=t.parameters)||void 0===i||i.forEach((e=>{const t=`|param|${e.name}`,n=f(t,o+t);n&&(e.description=n)}));const g=c["{id:category}"+e.Util.capitalize(t.qName)];let b=c[`${t.qName}|block`]||(null===(u=t.attributes.locs)||void 0===u?void 0:u[l]);if(!b&&p){const e=c[`${p.qName}|block`]||(null===(d=p.attributes.locs)||void 0===d?void 0:d[l]);t.attributes.block===(p.attributes._untranslatedBlock||p.attributes.block)&&e&&(b=e)}if(b&&pxt.Util.isTranslationMode()&&(t.attributes.translationId=b,b=await pxt.crowdin.inContextLoadAsync(b)),g)t.attributes.block?t.attributes.block=b||t.attributes.block:t.attributes.block=g,r(t.attributes);else if(t.attributes.block&&b){const e=pxt.blocks.compileInfo(t),n=t.attributes.block;if(t.attributes.block=pxt.blocks.normalizeBlock(b,(e=>{pxt.tickEvent("loc.normalized",{block:t.attributes.block,lang:s,error:e})})),t.attributes._untranslatedBlock||(t.attributes._untranslatedBlock=n),n!=t.attributes.block){r(t.attributes);(function(e,t){if(e.parameters.length!=t.parameters.length)return pxt.debug("Localized block has extra or missing parameters"),!1;for(const n of e.parameters){const e=t.actualNameToParam[n.actualName];if(!e||n.type!=e.type||n.shadowBlockId!=e.shadowBlockId||n.definitionName!=e.definitionName)return pxt.debug(`Parameter ${n.actualName} type, shadow block, or definition name does not match after localization`),!1}return!0})(e,pxt.blocks.compileInfo(t))||(pxt.reportError("loc.errors","block has non matching arguments",{block:t.attributes.blockId,lang:s,originalDefinition:n,translatedBlock:t.attributes.block}),pxt.tickEvent("loc.errors",{block:t.attributes.blockId,lang:s}),t.attributes.block=n,r(t.attributes))}}else r(t.attributes);t.attributes._translatedLanguageCode=s})),t(n)},e.emptyExtInfo=function(){let e=pxt.appTarget.compileService;e||(e={});const t=!!e.platformioIni,n="dockermake"==e.buildEngine||"dockercross"==e.buildEngine||"dockerespidf"==e.buildEngine,i={functions:[],generatedFiles:{},extensionFiles:{},sha:"",compileData:"",shimsDTS:"",enumsDTS:"",onlyPublic:!0};return t?i.platformio={dependencies:{}}:n?i.npmDependencies={}:i.yotta={config:{},dependencies:{}},i};const n=["weight","imageLiteral","gridLiteral","topblockWeight","inlineInputModeLimit"],i=["advanced","handlerStatement","afterOnStart","optionalVariableArgs","blockHidden","constantShim","blockCombine","enumIsBitMask","enumIsHash","decompileIndirectFixedInstances","topblock","callInDebugger","duplicateShadowOnDrag","argsNullable","compileHiddenArguments"];function s(e){return"Action"===e.type||/^\([^\)]*\)\s*=>/.test(e.type)}function r(e){if(e.block){const n=e.block.split("||");e._def=t(o(n[0])),e._def||pxt.debug("Unable to parse block def for id: "+e.blockId),n[1]&&(e._expandedDef=t(o(n[1]))),n[1]&&!e._expandedDef&&pxt.debug("Unable to parse expanded block def for id: "+e.blockId)}function t(t){return e._shadowOverrides&&t.parameters.forEach((t=>{const n=e._shadowOverrides[t.name];"unset"===n?delete t.shadowBlockId:null!=n&&(t.shadowBlockId=n)})),t}}function o(e){const t=[];let n,i=0;for(;i<e.length;i++){const s=e[i],r=i;let o;switch(s){case"*":case"_":const t=d((e=>e==s)),n="_"===s?2:0;1===t.length?o={kind:1<<n,content:t}:2===t.length?o={kind:2<<n,content:t}:3===t.length?o={kind:3<<n,content:t}:i=r;break;case"`":const a=h("`");if(void 0===a){i=r;break}o={kind:256,content:a};break;case"|":o={kind:32};break;case"\\":i<e.length-1&&(o={kind:16,content:e[1+i++]});break;case"[":const l=h("]");if(void 0!==l&&"("===e[1+i++]){const e=h(")");if(void 0!==e){o={kind:512,content:l,type:e};break}}i=r;break;case"$":case"%":const c=d((e=>/[a-zA-Z0-9_=]/.test(e)),!0).split("=");if(c.length>2){i=r;break}let u;if("("===e[i+1]){const e=i;++i,u=h(")"),u||(i=e)}o={kind:"$"===s?1024:64,content:c[0],type:c[1],name:u}}o?(n&&t.push({kind:128,content:n}),n=void 0,t.push(o)):n?n+=s:n=s}n&&t.push({kind:128,content:n});const s=[],r=[];let o=[],l=0,c="",u=[];for(let e=0;e<t.length;e++){const n=t[e].kind,i=o[o.length-1];if(15&n)if(m(t[e].content),n&l)if(i&n){o.pop(),l^=n;const e=i&l|n&l;e&&o.push(e)}else p();else l|=n,o.push(n);else 144&n?c+=t[e].content:1120&n&&f();if(64==n){const n={kind:"param",name:t[e].content,shadowBlockId:t[e].type,ref:!1};t[e].name&&(n.varName=t[e].name),s.push(n),r.push(n)}else if(1024==n){const n={kind:"param",name:t[e].content,shadowBlockId:t[e].type,ref:!0};t[e].name&&(n.varName=t[e].name),s.push(n),r.push(n)}else 256==n?(m(),u.push({kind:"image",uri:t[e].content})):512==n?(m(),u.push({kind:"label",text:t[e].content,cssClass:t[e].type})):32==n&&s.push({kind:"break"})}return f(),{parts:s,parameters:r};function d(t,n=!1){let s="";for(n&&i++;i<e.length&&t(e[i]);)s+=e[i],++i;return s&&i--,s}function h(t){const n=d((e=>e!==t),!0);if(e[i+1]===t)return++i,n}function p(){let e="",t=[];for(const n of u)a(n)?(t.push({content:e,styles:0}),t.push(n),e=""):(e+=n.content,n.endingToken&&(e+=n.endingToken));u=t,e&&u.push({content:e,styles:0}),o=[],l=0}function f(){for(m(),l&&p();u.length;){const e=u.shift();if(a(e))s.push(e);else{if(!e.content)continue;const t=[];10&e.styles&&t.push("bold"),5&e.styles&&t.push("italics"),s.push({kind:"label",text:e.content,style:t})}}}function m(e){u.push({content:c,styles:l,endingToken:e}),c=""}}function a(e){return!!e.kind}let l;e.parseCommentString=function(t){let s={paramDefl:{},callingConvention:0,_source:t},o=!0;for(;o;)o=!1,t=t.replace(/\/\/%[ \t]*([\w\.-]+)(=(("[^"\n]*")|'([^'\n]*)'|([^\s]*)))?/,((t,n,i,r,a,l,c)=>{let u=a?JSON.parse(a):i?a||l||c:"true";if(u||(u=""),e.U.startsWith(n,"block.loc."))s.locs||(s.locs={}),s.locs[n.slice("block.loc.".length).toLowerCase()+"|block"]=u;else if(e.U.startsWith(n,"jsdoc.loc."))s.locs||(s.locs={}),s.locs[n.slice("jsdoc.loc.".length).toLowerCase()+"|jsdoc"]=u;else if(e.U.contains(n,".loc.")){s.locs||(s.locs={});const e=n.slice(0,n.indexOf(".loc.")),t=n.slice(n.indexOf(".loc.")+".loc.".length);s.locs[t+"|param|"+e]=u}else if(e.U.endsWith(n,".defl"))u.indexOf(" ")>-1?s.paramDefl[n.slice(0,n.length-5)]=`"${u}"`:s.paramDefl[n.slice(0,n.length-5)]=u,s.explicitDefaults||(s.explicitDefaults=[]),s.explicitDefaults.push(n.slice(0,n.length-5));else if(e.U.endsWith(n,".shadow"))s._shadowOverrides||(s._shadowOverrides={}),s._shadowOverrides[n.slice(0,n.length-7)]=u;else if(e.U.endsWith(n,".snippet")){s.paramSnippets||(s.paramSnippets={});const e=n.slice(0,n.length-8);s.paramSnippets[e]||(s.paramSnippets[e]={}),s.paramSnippets[e].ts=u}else if(e.U.endsWith(n,".pySnippet")){s.paramSnippets||(s.paramSnippets={});const e=n.slice(0,n.length-10);s.paramSnippets[e]||(s.paramSnippets[e]={}),s.paramSnippets[e].python=u}else if(e.U.endsWith(n,".fieldEditor"))s.paramFieldEditor||(s.paramFieldEditor={}),s.paramFieldEditor[n.slice(0,n.length-12)]=u;else if(e.U.contains(n,".fieldOptions.")){s.paramFieldEditorOptions||(s.paramFieldEditorOptions={});const e=n.slice(0,n.indexOf(".fieldOptions.")),t=n.slice(n.indexOf(".fieldOptions.")+14,n.length);s.paramFieldEditorOptions[e]||(s.paramFieldEditorOptions[e]={}),s.paramFieldEditorOptions[e][t]=u}else if(e.U.contains(n,".shadowOptions.")){s.paramShadowOptions||(s.paramShadowOptions={});const e=n.slice(0,n.indexOf(".shadowOptions.")),t=n.slice(n.indexOf(".shadowOptions.")+15,n.length);s.paramShadowOptions[e]||(s.paramShadowOptions[e]={}),s.paramShadowOptions[e][t]=u}else e.U.endsWith(n,".min")?(s.paramMin||(s.paramMin={}),s.paramMin[n.slice(0,n.length-4)]=u):e.U.endsWith(n,".max")?(s.paramMax||(s.paramMax={}),s.paramMax[n.slice(0,n.length-4)]=u):s[n]=u;return o=!0,"//% "}));for(let e of n)"string"==typeof s[e]&&(s[e]=parseInt(s[e]));for(let e of i)"string"==typeof s[e]&&(s[e]="true"==s[e]||"1"==s[e]);if(s.trackArgs&&(s.trackArgs=s.trackArgs.split(/[ ,]+/).map((e=>parseInt(e)||0))),s.enumInitialMembers&&(s.enumInitialMembers=s.enumInitialMembers.split(/[ ,]+/)),s.blockExternalInputs&&!s.inlineInputMode&&(s.inlineInputMode="external"),s.paramHelp={},s.jsDoc="",t=t.replace(/\/\*\*([^]*?)\*\//g,((e,t)=>(t=(t=t.replace(/\n\s*(\*\s*)?/g,"\n")).replace(/^\s*@param\s+(\w+)\s+(.*)$/gm,((e,t,n)=>{if(s.paramHelp[t]=n,!s.paramDefl[t]){let e=/\beg\.?:\s*(.+)/.exec(n);if(e&&e[1]){let n=/(?:"([^"]*)")|(?:'([^']*)')|(?:([^\s,]+))/g.exec(e[1]);if(n){let e=n[1]||n[2]||n[3];e||(e=""),e.indexOf(" ")>-1?s.paramDefl[t]=`"${e}"`:s.paramDefl[t]=e}}}return""})),s.jsDoc+=t,""))),s.jsDoc=s.jsDoc.trim(),s.async&&(s.callingConvention=1),s.promise&&(s.callingConvention=2),s.jres&&(s.whenUsed=!0),s.subcategories)try{s.subcategories=JSON.parse(s.subcategories)}catch(e){s.subcategories=void 0}if(s.groups)try{s.groups=JSON.parse(s.groups)}catch(e){s.groups=void 0}if(s.groupIcons)try{s.groupIcons=JSON.parse(s.groupIcons)}catch(e){s.groupIcons=void 0}if(s.groupHelp)try{s.groupHelp=JSON.parse(s.groupHelp)}catch(e){s.groupHelp=void 0}return r(s),s},e.parameterTypeIsArrowFunction=s,e.updateBlockDef=r,e.parseBlockDefinition=o,e.parseChecksumBlock=function(e,t=0){let n=pxt.HF2.read32(e,t);if(133083260!=(2147483647&n))return pxt.log("no checksum block magic"),null;let i=pxt.HF2.read32(e,t+4),s=pxt.HF2.read32(e,t+8);if(3&i)return pxt.log("invalid end marker position"),null;let r=1<<(255&s);if(r!=pxt.appTarget.compile.flashCodeAlign)return pxt.log("invalid page size: "+r),null;let o={magic:n,endMarkerPos:i,endMarker:s,regions:[]};for(let n=t+12;n<e.length-7;n+=8){let t={start:r*pxt.HF2.read16(e,n),length:r*pxt.HF2.read16(e,n+2),checksum:pxt.HF2.read32(e,n+4)};if(!t.length||!t.checksum)break;o.regions.push(t)}return o},function(t){function n(n){let i=e=>n[e]+(n[e+1]<<8)+(n[e+2]<<16)+(n[e+3]<<24)>>>0;if(!n||512!=n.length||i(0)!=t.UF2_MAGIC_START0||i(4)!=t.UF2_MAGIC_START1||i(n.length-4)!=t.UF2_MAGIC_END)return null;let s=i(8),r=i(16);r>476&&(r=256);let o=null,a=0,l=0;if(s&t.UF2_FLAG_FILE){let t=n.slice(32+r),s=t.indexOf(0);s>=0&&(t=t.slice(0,s)),o=e.U.fromUTF8Array(t),l=i(28)}return s&t.UF2_FLAG_FAMILY_ID_PRESENT&&(a=i(28)),{flags:s,targetAddr:i(12),payloadSize:r,blockNo:i(20),numBlocks:i(24),fileSize:l,familyId:a,data:n.slice(32,32+r),filename:o}}function i(e,t){return!!e&&(e.targetAddr<=t&&t<e.targetAddr+e.payloadSize)}function s(e,t,n){e[t]=255&n,e[t+1]=n>>8&255,e[t+2]=n>>16&255,e[t+3]=n>>24&255}function r(e){return"string"==typeof e&&(e=parseInt(e)),{currBlock:null,currPtr:-1,blocks:[],ptrs:[],filesize:0,familyId:e||0}}function o(e){for(let t=0;t<e.blocks.length;++t)s(e.blocks[t],20,t),s(e.blocks[t],24,e.blocks.length),e.filename&&s(e.blocks[t],28,e.filesize)}function a(n,i,r,o=0){let l=n.currBlock,c=i>>8,u=256-(255&i);if(r.length>u){let e=new Uint8Array(r);for(a(n,i,e.slice(0,u));u<r.length;){let t=Math.min(u+256,r.length);a(n,i+u,e.slice(u,t)),u=t}return}if(c!=n.currPtr){l=null;for(let e=0;e<n.ptrs.length;++e)if(n.ptrs[e]==c){l=n.blocks[e];break}if(!l){l=new Uint8Array(512),n.filename?o|=t.UF2_FLAG_FILE:n.familyId&&(o|=t.UF2_FLAG_FAMILY_ID_PRESENT),s(l,0,t.UF2_MAGIC_START0),s(l,4,t.UF2_MAGIC_START1),s(l,8,o),s(l,12,c<<8),s(l,16,256),s(l,20,n.blocks.length),s(l,28,n.familyId),s(l,508,t.UF2_MAGIC_END);for(let e=32;e<288;++e)l[e]=255;n.filename&&e.U.memcpy(l,288,e.U.toUTF8Array(n.filename)),n.blocks.push(l),n.ptrs.push(c)}n.currPtr=c,n.currBlock=l}let d=32+(255&i);for(let e=0;e<r.length;++e)l[d+e]=r[e];n.filesize=Math.max(n.filesize,r.length+i)}t.UF2_MAGIC_START0=171066965,t.UF2_MAGIC_START1=2656915799,t.UF2_MAGIC_END=179400496,t.UF2_FLAG_NONE=0,t.UF2_FLAG_NOFLASH=1,t.UF2_FLAG_FILE=4096,t.UF2_FLAG_FAMILY_ID_PRESENT=8192,t.parseBlock=n,t.parseFile=function(e){let t=[];for(let i=0;i<e.length;i+=512){let s=n(e.slice(i,i+512));s&&t.push(s)}return t},t.toBin=function(e,t){if(e.length<512)return null;let i=-1,s=-1,r=[];for(let o=0;o<e.length;++o){let a=512*o,l=n(e.slice(a,a+512));if(!l)continue;if(t&&l.targetAddr+256>t)break;-1==i&&(i=l.targetAddr,s=i);let c=l.targetAddr-i;c<0||c%4||c>1048576||(c>0&&r.push(new Uint8Array(c)),r.push(e.slice(a+32,a+32+l.payloadSize)),i=l.targetAddr+l.payloadSize)}let o=0;for(let e of r)o+=e.length;if(0==o)return null;let a=new Uint8Array(o),l=0;for(let e of r)for(let t=0;t<e.length;++t)a[l++]=e[t];return{buf:a,start:s}},t.readBytes=function(e,t,n){let s,r=new Uint8Array(n);for(let o=0;o<n;++o,++t)i(s,t)||(s=e.filter((e=>i(e,t)))[0]),s&&(r[o]=s.data[t-s.targetAddr]);return r},t.newBlockFile=r,t.finalizeFile=o,t.concatFiles=function(t){for(let e of t)o(e),e.filename=null;let n=r();n.blocks=e.U.concat(t.map((e=>e.blocks)));for(let e of t)e.blocks=[];return n},t.serializeFile=function(t){o(t);let n="";for(let i of t.blocks)n+=e.Util.uint8ArrayToString(i);return n},t.readBytesFromFile=function t(n,i,s){let r,o=i>>8;if(o==n.currPtr)r=n.currBlock;else{for(let e=0;e<n.ptrs.length;++e)if(n.ptrs[e]==o){r=n.blocks[e];break}r&&(n.currPtr=o,n.currBlock=r)}if(!r)return null;let a=new Uint8Array(s),l=Math.min(s,256-(255&i));e.U.memcpy(a,0,r,32+(255&i),l);let c=s-l;if(c>0){let s=t(n,i+l,c);e.U.memcpy(a,l,s)}return a},t.writeBytes=a,t.writeHex=function(e,t){let n="0000";for(let i=0;i<t.length;++i){let s=/:02000004(....)/.exec(t[i]);if(s&&(n=s[1]),s=/^:..(....)00(.*)[0-9A-F][0-9A-F]$/.exec(t[i]),s){let t=parseInt(n+s[1],16),i=s[2],r=[];for(let e=0;e<i.length;e+=2)r.push(parseInt(i[e]+i[e+1],16));a(e,t,r)}}}}(l=e.UF2||(e.UF2={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){!function(e){let t;!function(e){e[e.Bundled=1]="Bundled",e[e.Github=2]="Github",e[e.ShareScript=3]="ShareScript"}(t=e.ExtensionType||(e.ExtensionType={}))}(e.service||(e.service={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){let n,i,s;!function(e){e[e.IDE=0]="IDE",e[e.Sandbox=1]="Sandbox",e[e.Widget=2]="Widget",e[e.Controller=3]="Controller"}(n=t.EditorLayoutType||(t.EditorLayoutType={})),function(e){e[e.None=0]="None",e[e.Basic=1]="Basic",e[e.App=2]="App"}(i=t.ControllerMode||(t.ControllerMode={}));let r=i.None,o=!1,a=!1;function l(){if(void 0===s){if(e.BrowserUtils.hasWindow()){const t=/sandbox=1|#sandbox|#sandboxproject/i.test(window.location.href)||e.BrowserUtils.isIFrame(),l=/nosandbox=1/i.test(window.location.href),c=/controller=(0|1|2)/i.exec(window.location.href);c&&e.BrowserUtils.isIFrame()&&(r=parseInt(c[1]));const u=r!==i.None,d=/readonly=1/i.test(window.location.href),h=/editorlayout=(widget|sandbox|ide)/i.exec(window.location.href),p=/noproject=1/i.test(window.location.href);if(s=n.IDE,l?s=n.Widget:u?s=n.Controller:t&&(s=n.Sandbox),u&&d&&(o=!0),u&&p&&(a=!0),h)switch(h[1].toLowerCase()){case"widget":s=n.Widget;break;case"sandbox":s=n.Sandbox;break;case"ide":s=n.IDE}}else s=n.Sandbox;e.debug(`shell: layout type ${n[s]}, readonly ${d()}`)}}function c(){return l(),s==n.Sandbox}function u(){return/[?&]timeMachine=1/i.test(window.location.href)}function d(){return!e.BrowserUtils.hasWindow()||u()||c()&&!/[?&]edit=1/i.test(window.location.href)||h()&&o}function h(){return l(),s==n.Controller}t.layoutTypeClass=function(){return l(),e.shell.EditorLayoutType[s].toLowerCase()},t.isSandboxMode=c,t.isTimeMachineEmbed=u,t.isReadOnly=d,t.isNoProject=function(){return a},t.isControllerMode=h,t.getControllerMode=function(){return l(),r},t.isPyLangPref=function(){return"py"==e.storage.getLocal("editorlangpref")},t.getEditorLanguagePref=function(){return e.storage.getLocal("editorlangpref")},t.setEditorLanguagePref=function(t){t.match(/prj$/)&&(t=t.replace(/prj$/,"")),e.storage.setLocal("editorlangpref",t)},t.getToolboxAnimation=function(){return e.storage.getLocal("toolboxanimation")},t.setToolboxAnimation=function(){e.storage.setLocal("toolboxanimation","1")}}(e.shell||(e.shell={}))}(pxt||(pxt={})),function(e){!function(t){t.USER_VERSION="0.0.1";class n{constructor(){this.db=new e.BrowserUtils.IDBWrapper(n.databaseName,n.version,((e,t)=>{const i=t.result;e.oldVersion<1&&(i.createObjectStore(n.projectTable,{keyPath:n.projectKey}),i.createObjectStore(n.userTable,{keyPath:n.userKey}))}))}initAsync(){return this.db.openAsync()}getAllProjectsAsync(){return this.db.getAllAsync(n.projectTable).then((e=>e.map((e=>e.project)).filter((e=>!e.deleted))))}deleteProjectAsync(e){return this.getProjectAsync(e).then((e=>{e.deleted=!0,this.saveProjectAsync(e)}))}getProjectAsync(e){return this.db.getAsync(n.projectTable,e).then((e=>null==e?void 0:e.project))}saveProjectAsync(e){return this.db.setAsync(n.projectTable,{id:e.header.id,project:e})}getUserStateAsync(){return this.db.getAsync(n.userTable,"local-user").then((e=>null==e?void 0:e.user))}saveUserStateAsync(e){return this.db.setAsync(n.userTable,{id:"local-user",user:e})}}n.version=6,n.databaseName="local-skill-map",n.projectTable="projects",n.projectKey="id",n.userTable="users",n.userKey="id",t.IndexedDBWorkspace=n}(e.skillmap||(e.skillmap={}))}(pxt||(pxt={})),function(e){!function(e){e.MAX_FREQUENCY=5e3,e.MAX_VOLUME=255,e.renderSoundPath=function(i,s,r){let{startFrequency:o,endFrequency:a,startVolume:l,endVolume:c,wave:u,interpolation:d}=i;o=Math.max(Math.min(o,e.MAX_FREQUENCY),1),a=Math.max(Math.min(a,e.MAX_FREQUENCY),1),l=Math.max(Math.min(l,e.MAX_VOLUME),0),c=Math.max(Math.min(c,e.MAX_VOLUME),0);const h=new t(o+a+1);let p;switch(d){case"linear":p=e=>o+e*(a-o)/s;break;case"curve":p=e=>o+(a-o)*Math.sin(e/s*(Math.PI/2));break;case"logarithmic":p=e=>o+Math.log10(1+e/s*9)*(a-o)}"noise"===u&&(p=()=>h.randomRange(500,5e3));const f=t=>Math.max(Math.min((c-l)/s*t+l,e.MAX_VOLUME),0),m=s/2,g=t=>t/e.MAX_VOLUME*(r-2)/2,b=t=>(1-t/e.MAX_FREQUENCY)*(m-10)+10,y=["M 2 "+r/2];let v=0;for(;v<s;)y.push(n(g(f(v)),b(p(v))/2,u,!1,h)),v+=b(p(v))/2,y.push(n(g(f(v)),b(p(v))/2,u,!0,h)),v+=b(p(v))/2;return y.join(" ")},e.renderWaveSnapshot=function(i,s,r,o,a,l){const c=new t(i);"noise"===r&&(i=c.randomRange(500,5e3)),i=Math.max(Math.min(i,e.MAX_FREQUENCY),1);const u=s/e.MAX_VOLUME*(a-2)/2,d=o/(i*l/1e3)/2;let h=Math.ceil(o/(2*d));h%2==1&&h++;const p=[`M ${o/2-h*d} ${a/2}`];let f=0;for(let e=0;e<h;e++)p.push(n(u,d,r,!1,c)),f+=d,p.push(n(u,d,r,!0,c)),f+=d;return p.join(" ")};class t{constructor(e){this.seed=e,this.lfsr=e}next(){return(this.lfsr=this.lfsr>>1^46080&-(1&this.lfsr))/65535}randomRange(e,t){return e+(t-e)*this.next()}}function n(e,t,n,i,s){switch(n){case"triangle":return`l ${t/2} ${i?e:-e} l ${t/2} ${i?-e:e}`;case"square":return`v ${i?e:-e} h ${t} v ${i?-e:e}`;case"sawtooth":return i?`l ${t} ${e} v ${-e}`:`v ${-e} l ${t} ${e}`;case"sine":return`q ${t/2} ${1.9*(i?e:-e)} ${t} 0`;case"noise":const n=[],r=[],o=Math.min(4,t/4);let a=i;for(let n=0;n<t;n+=o)r.push(s.randomRange(0,e)*(a?1:-1)),a=!a;r[0]=i?e:-e,r[r.length-1]=0;let l=0,c=0;for(const e of r){let i=Math.min(o,t-c);if(n.push(`v ${e-l} h ${i}`),l=e,c+=i,c>=t)break}return n.join(" ")}}function i(e){switch(e){case"square":return 15;case"sine":return 3;case"triangle":return 1;case"noise":return 18;case"sawtooth":return 2}}function s(e,t,n){const i=new Uint8Array(2);new Uint16Array(i.buffer)[0]=0|n,e[t]=i[0],e[t+1]=i[1]}e.soundToInstructionBuffer=function(t,n,r){const{startFrequency:o,endFrequency:a,startVolume:l,endVolume:c,interpolation:u,duration:d}=t,h=[];if("linear"===t.interpolation&&"none"===t.effect)h.push({frequency:o,volume:l/e.MAX_VOLUME*1024}),h.push({frequency:a,volume:c/e.MAX_VOLUME*1024});else{n=Math.min(n,Math.floor(d/5));const i=t=>(l+t*(c-l)/d)/e.MAX_VOLUME*1024;let s;switch(u){case"linear":s=e=>o+e*(a-o)/d;break;case"curve":s=e=>o+(a-o)*Math.sin(e/d*(Math.PI/2));break;case"logarithmic":s=e=>o+Math.log10(1+e/d*9)*(a-o)}const p=d/n;for(let e=0;e<n;e++){const n={frequency:Math.max(s(e*p),1),volume:i(e*p)};"tremolo"===t.effect?n.volume=e%2==0?Math.max(n.volume-500*r,0):Math.min(n.volume+500*r,1023):"vibrato"===t.effect?n.frequency=e%2==0?Math.max(n.frequency-100*r,1):n.frequency+100*r:"warble"===t.effect&&(n.frequency=e%2==0?Math.max(n.frequency-1e3*r,1):n.frequency+1e3*r),h.push(n)}}const p=new Uint8Array(12*(h.length-1)),f=Math.floor(d/(h.length-1));for(let e=0;e<h.length-1;e++){const n=12*e;p[n]=i(t.wave),s(p,n+2,h[e].frequency),s(p,n+4,f),s(p,n+6,h[e].volume),s(p,n+8,h[e+1].volume),s(p,n+10,h[e+1].frequency)}return p}}(e.assets||(e.assets={}))}(pxt||(pxt={})),function(e){!function(t){t.createStreamAsync=function(t,n){return e.Cloud.privatePostAsync("streams",{target:t,name:n||"data"}).then((e=>e))},t.postPayloadAsync=function(t,n){return e.Util.assert(!!t.privatekey),e.Cloud.privatePostAsync(`${t.id}/data?privatekey=${t.privatekey}`,n)}}(e.streams||(e.streams={}))}(pxt||(pxt={})),function(e){!function(t){let n,i;!function(e){e[e.userSpaceOnUse=0]="userSpaceOnUse",e[e.objectBoundingBox=1]="objectBoundingBox"}(n=t.PatternUnits||(t.PatternUnits={})),function(e){e[e.em=0]="em",e[e.ex=1]="ex",e[e.px=2]="px",e[e.in=3]="in",e[e.cm=4]="cm",e[e.mm=5]="mm",e[e.pt=6]="pt",e[e.pc=7]="pc",e[e.percent=8]="percent"}(i=t.LengthUnit||(t.LengthUnit={}));class s{constructor(e){this.el=A(e)}attr(e){return Object.keys(e).forEach((t=>{this.setAttribute(t,e[t])})),this}setAttribute(e,t){return this.el.setAttribute(e,t.toString()),this}setAttributeNS(e,t,n){return this.el.setAttributeNS(e,t,n.toString()),this}id(e){return this.setAttribute("id",e)}setClass(...e){return this.setAttribute("class",e.join(" "))}appendClass(t){return e.BrowserUtils.addClass(this.el,t),this}removeClass(t){e.BrowserUtils.removeClass(this.el,t)}title(e){this.titleElement||(this.titleElement=A("title"),this.el.firstChild?this.el.insertBefore(this.titleElement,this.el.firstChild):this.el.appendChild(this.titleElement)),this.titleElement.textContent=e}setVisible(e){return this.setAttribute("visibility",e?"visible":"hidden")}}t.BaseElement=s;class r extends s{draw(e){const t=function(e){switch(e){case"text":return new d;case"circle":return new p;case"rect":return new h;case"line":return new f;case"polygon":return new b;case"polyline":return new g;case"path":return new y;default:return new u(e)}}(e);return this.el.appendChild(t.el),t}element(e,t){return t(this.draw(e)),this}group(){const e=new o;return this.el.appendChild(e.el),e}appendChild(e){this.el.appendChild(e.el)}onDown(e){return t.events.down(this.el,e),this}onUp(e){return t.events.up(this.el,e),this}onMove(e){return t.events.move(this.el,e),this}onEnter(e){return t.events.enter(this.el,e),this}onLeave(e){return t.events.leave(this.el,e),this}onClick(e){return t.events.click(this.el,e),this}}t.DrawContext=r;t.SVG=class extends r{constructor(e){super("svg"),e&&e.appendChild(this.el)}define(e){return this.defs||(this.defs=new l(this.el)),e(this.defs),this}};class o extends r{constructor(e){super("g"),e&&e.appendChild(this.el)}translate(e,t){return this.left=e,this.top=t,this.updateTransform()}scale(e){return this.scaleFactor=e,this.updateTransform()}def(){return new l(this.el)}style(){return new c(this.el)}updateTransform(){let e="";return null!=this.left&&(e+=`translate(${this.left} ${this.top})`),null!=this.scaleFactor&&(e+=` scale(${this.scaleFactor})`),this.setAttribute("transform",e),this}}t.Group=o;class a extends r{constructor(){super("pattern")}units(e){return this.setAttribute("patternUnits",e===n.objectBoundingBox?"objectBoundingBox":"userSpaceOnUse")}contentUnits(e){return this.setAttribute("patternContentUnits",e===n.objectBoundingBox?"objectBoundingBox":"userSpaceOnUse")}size(e,t){return this.setAttribute("width",e),this.setAttribute("height",t),this}}t.Pattern=a;class l extends s{constructor(e){super("defs"),e.appendChild(this.el)}create(e,t){let n;switch(e){case"path":n=new y;break;case"pattern":n=new a;break;case"radialGradient":n=new k;break;case"linearGradient":n=new w;break;case"clipPath":n=new x;break;default:n=new s(e)}return n.id(t),this.el.appendChild(n.el),n}}t.DefsElement=l;class c extends s{constructor(e){super("style"),e.appendChild(this.el)}content(e){this.el.textContent=e}}t.StyleElement=c;class u extends r{at(e,t){return this.setAttribute("x",e),this.setAttribute("y",t),this}moveTo(e,t){return this.at(e,t)}fill(e,t){return this.setAttribute("fill",e),null!=t&&this.opacity(t),this}opacity(e){return this.setAttribute("fill-opacity",e)}stroke(e,t){return this.setAttribute("stroke",e),null!=t&&this.strokeWidth(t),this}strokeWidth(e){return this.setAttribute("stroke-width",e)}strokeOpacity(e){return this.setAttribute("stroke-opacity",e)}clipPath(e){return this.setAttribute("clip-path",e)}}t.Drawable=u;class d extends u{constructor(e){super("text"),null!=e&&this.text(e)}text(e){return this.el.textContent=e,this}fontFamily(e){return this.setAttribute("font-family",e)}fontSize(e,t){return this.setAttribute("font-size",T(e,t))}offset(e,t,n){return 0!==e&&this.setAttribute("dx",T(e,n)),0!==t&&this.setAttribute("dy",T(t,n)),this}anchor(e){return this.setAttribute("text-anchor",e)}}t.Text=d;class h extends u{constructor(){super("rect")}width(e,t=i.px){return this.setAttribute("width",T(e,t))}height(e,t=i.px){return this.setAttribute("height",T(e,t))}corner(e){return this.corners(e,e)}corners(e,t){return this.setAttribute("rx",e),this.setAttribute("ry",t),this}size(e,t,n=i.px){return this.width(e,n),this.height(t,n),this}}t.Rect=h;class p extends u{constructor(){super("circle")}at(e,t){return this.setAttribute("cx",e),this.setAttribute("cy",t),this}radius(e){return this.setAttribute("r",e)}}t.Circle=p;class f extends u{constructor(){super("line")}at(e,t,n,i){return this.from(e,t),null!=n&&null!=i&&this.to(n,i),this}from(e,t){return this.setAttribute("x1",e),this.setAttribute("y1",t),this}to(e,t){return this.setAttribute("x2",e),this.setAttribute("y2",t),this}}t.Line=f;class m extends u{points(e){return this.setAttribute("points",e)}with(e){return this.points(e.map((({x:e,y:t})=>e+" "+t)).join(","))}}t.PolyElement=m;class g extends m{constructor(){super("polyline")}}t.Polyline=g;class b extends m{constructor(){super("polygon")}}t.Polygon=b;class y extends u{constructor(){super("path"),this.d=new E}update(){return this.setAttribute("d",this.d.toAttribute())}path(e){return e(this.d),this.update()}setD(e){return this.setAttribute("d",e),this}}t.Path=y;t.Image=class extends u{constructor(){super("image")}src(e){return this.setAttributeNS("http://www.w3.org/1999/xlink","href",e)}width(e,t=i.px){return this.setAttribute("width",T(e,t))}height(e,t=i.px){return this.setAttribute("height",T(e,t))}size(e,t,n=i.px){return this.width(e,n),this.height(t,n),this}};class v extends s{units(e){return this.setAttribute("gradientUnits",e===n.objectBoundingBox?"objectBoundingBox":"userSpaceOnUse")}stop(e,t,n){const i=A("stop");return i.setAttribute("offset",e+"%"),null!=t&&i.setAttribute("stop-color",t),null!=n&&i.setAttribute("stop-opacity",n),this.el.appendChild(i),this}}t.Gradient=v;class w extends v{constructor(){super("linearGradient")}start(e,t){return this.setAttribute("x1",e),this.setAttribute("y1",t),this}end(e,t){return this.setAttribute("x2",e),this.setAttribute("y2",t),this}}t.LinearGradient=w;class k extends v{constructor(){super("radialGradient")}center(e,t){return this.setAttribute("cx",e),this.setAttribute("cy",t),this}focus(e,t,n){return this.setAttribute("fx",e),this.setAttribute("fy",t),this.setAttribute("fr",n),this}radius(e){return this.setAttribute("r",e)}}t.RadialGradient=k;class x extends r{constructor(){super("clipPath")}clipPathUnits(e){return e?this.setAttribute("clipPathUnits","objectBoundingBox"):this.setAttribute("clipPathUnits","userSpaceOnUse")}}function A(e){return document.createElementNS("http://www.w3.org/2000/svg",e)}t.ClipPath=x;class E{constructor(){this.ops=[]}clear(){this.ops=[]}moveTo(e,t){return this.op("M",e,t)}moveBy(e,t){return this.op("m",e,t)}lineTo(e,t){return this.op("L",e,t)}lineBy(e,t){return this.op("l",e,t)}cCurveTo(e,t,n,i,s,r){return this.op("C",e,t,n,i,s,r)}cCurveBy(e,t,n,i,s,r){return this.op("c",e,t,n,i,s,r)}qCurveTo(e,t,n,i){return this.op("Q",e,t,n,i)}qCurveBy(e,t,n,i){return this.op("q",e,t,n,i)}sCurveTo(e,t,n,i){return this.op("S",e,t,n,i)}sCurveBy(e,t,n,i){return this.op("s",e,t,n,i)}tCurveTo(e,t){return this.op("T",e,t)}tCurveBy(e,t){return this.op("t",e,t)}arcTo(e,t,n,i,s,r,o){return this.op("A",e,t,n,i?1:0,s?1:0,r,o)}arcBy(e,t,n,i,s,r,o){return this.op("a",e,t,n,i?1:0,s?1:0,r,o)}close(){return this.op("z")}toAttribute(){return this.ops.map((e=>e.op+" "+e.args.join(" "))).join(" ")}op(e,...t){return this.ops.push({op:e,args:t}),this}}function T(e,t){switch(t){case i.em:return e+"em";case i.ex:return e+"ex";case i.px:return e+"px";case i.in:return e+"in";case i.cm:return e+"cm";case i.mm:return e+"mm";case i.pt:return e+"pt";case i.pc:return e+"pc";case i.percent:return e+"%";default:return e.toString()}}t.PathContext=E}(e.svgUtil||(e.svgUtil={}))}(pxt||(pxt={})),function(e){!function(e){!function(e){function t(){return"undefined"!=typeof window&&("ontouchstart"in window||navigator&&navigator.maxTouchPoints>0)}function n(){return"undefined"!=typeof window&&!!window.PointerEvent}e.isTouchEnabled=t,e.hasPointerEvents=n,e.down=function(e,i){n()?e.addEventListener("pointerdown",i):t()?(e.addEventListener("mousedown",i),e.addEventListener("touchstart",i)):e.addEventListener("mousedown",i)},e.up=function(e,i){n()?e.addEventListener("pointerup",i):(t(),e.addEventListener("mouseup",i))},e.enter=function(e,i){n()?e.addEventListener("pointerover",(e=>{i(!!(1&e.buttons))})):t()?e.addEventListener("touchstart",(e=>{i(!0)})):e.addEventListener("mouseover",(e=>{i(!!(1&e.buttons))}))},e.leave=function(e,i){n()?e.addEventListener("pointerleave",i):t()?e.addEventListener("touchend",i):e.addEventListener("mouseleave",i)},e.move=function(e,i){n()?e.addEventListener("pointermove",i):t()?e.addEventListener("touchmove",i):e.addEventListener("mousemove",i)},e.click=function(e,t){e.addEventListener("click",t)}}(e.events||(e.events={}))}(e.svgUtil||(e.svgUtil={}))}(pxt||(pxt={})),function(e){!function(e){!function(t){class n extends e.Text{at(e,t){return this.cx=e,this.cy=t,this.rePosition(),this}text(e,t=12){return super.text(e),this.fontSizePixels=t,this.setAttribute("font-size",t+"px"),this.rePosition(),this}rePosition(){null!=this.cx&&null!=this.cy&&null!=this.fontSizePixels&&(this.setAttribute("x",this.cx),this.setAttribute("y",this.cy),this.setAttribute("text-anchor","middle"),this.setAttribute("alignment-baseline","middle"))}}t.CenteredText=n}(e.helpers||(e.helpers={}))}(e.svgUtil||(e.svgUtil={}))}(pxt||(pxt={})),function(e){!function(e){e.initExtensionsAsync=e=>Promise.resolve({}),e.initFieldExtensionsAsync=e=>Promise.resolve({})}(e.editor||(e.editor={}))}(pxt||(pxt={})),function(e){e.IMAGE_MIME_TYPE="image/x-mkcd-f4",e.TILEMAP_MIME_TYPE="application/mkcd-tilemap",e.ANIMATION_MIME_TYPE="application/mkcd-animation",e.SONG_MIME_TYPE="application/mkcd-song";class t{constructor(){this.assets=[],this.takenNames={},this.listeners=[]}add(e){if(this.takenNames[e.id])return this.update(e.id,e);{const t=a(e);return this.takenNames[t.id]=!0,this.takenNames[f(t)]=!0,t.meta.displayName&&t.meta.displayName!==t.id&&(this.takenNames[t.meta.displayName]&&(t.meta.displayName=this.generateNewDisplayName(t.meta.displayName)),this.takenNames[t.meta.displayName]=!0),this.assets.push(t),a(t)}}getSnapshot(e){return e?this.assets.filter((t=>e(t))).map(a):this.assets.map(a)}update(e,t){let n;if(this.takenNames[e]){h(this.lookupByID(e),t)?n=t:(this.removeByID(e),n=this.add(t),this.notifyListener(t.internalID))}else n=this.add(t);return n}removeByID(e){const t=this.lookupByID(e);this.assets=this.assets.filter((t=>t.id!==e)),delete this.takenNames[e],t&&delete this.takenNames[f(t)],(null==t?void 0:t.meta.displayName)&&delete this.takenNames[null==t?void 0:t.meta.displayName]}getByID(e){const t=this.lookupByID(e);return t&&a(t)}getByDisplayName(e){if(this.takenNames[e])for(const t of this.assets)if(t.meta.displayName===e||f(t)===e)return a(t)}isIDTaken(e){return!!this.takenNames[e]}clone(){const e=new t;return e.assets=this.getSnapshot(),e.takenNames=Object.assign({},this.takenNames),e}serializeToJRes(e={}){for(const t of this.assets)d(t,e);return e}addListener(e,t){this.listeners.push({internalID:e,callback:t})}removeListener(e){this.listeners=this.listeners.filter((t=>t.callback!==e))}diff(e){let t={before:[],after:[]},n={};for(const i of e.assets){n[i.internalID]=!0;const e=this.lookupByInternalID(i.internalID);e&&h(i,e)||(t.before.push(i),t.after.push(e))}for(const e of this.assets.filter((e=>!n[e.internalID])))t.before.push(null),t.after.push(e);return t}applyDiff(t,n=!1){const i=n?t.after:t.before,s=n?t.before:t.after;e.Util.assert(i.length===s.length);for(let e=0;e<i.length;e++)i[e]?(this.removeByInternalID(i[e].internalID),s[e]&&this.assets.push(s[e]),this.notifyListener(i[e].internalID)):(this.assets.push(s[e]),this.notifyListener(s[e].internalID));this.takenNames={};for(const t of this.assets)e.Util.assert(!this.takenNames[t.id]),this.takenNames[t.id]=!0,this.takenNames[f(t)]=!0,t.meta.displayName&&(t.meta.displayName!==t.id&&e.Util.assert(!this.takenNames[t.meta.displayName]),this.takenNames[t.meta.displayName]=!0)}lookupByID(e){for(const t of this.assets)if(t.id===e)return t;return null}lookupByInternalID(e){for(const t of this.assets)if(t.internalID===e)return t;return null}removeByInternalID(e){this.assets=this.assets.filter((t=>t.internalID!==e))}notifyListener(e){for(const t of this.listeners)t.internalID===e&&t.callback()}generateNewDisplayName(e){e=e.replace(/\d+$/,"");let t=0;for(;this.takenNames[e+t];)++t;return e+t}}class n{constructor(){this.needsRebuild=!0,this.nextID=0,this.nextInternalID=0,this.committedState={revision:0,tilemaps:new t,tiles:new t,animations:new t,images:new t,songs:new t},this.state={revision:this.nextID++,tilemaps:new t,tiles:new t,animations:new t,images:new t,songs:new t},this.gallery={revision:0,tilemaps:new t,tiles:new t,animations:new t,images:new t,songs:new t},this.undoStack=[],this.redoStack=[]}getNewInternalId(){return this.nextInternalID++}createNewImage(t=16,n=16){this.onChange();const i=this.generateNewID("image"),s=new e.sprite.Bitmap(t,n).data(),r={internalID:this.getNewInternalId(),id:i,type:"image",bitmap:s,meta:{},jresData:e.sprite.base64EncodeBitmap(s)};return this.state.images.add(r)}createNewAnimation(t=16,n=16){this.onChange();const i=this.generateNewID("animation"),s=new e.sprite.Bitmap(t,n).data(),r={internalID:this.getNewInternalId(),id:i,type:"animation",frames:[s],interval:500,meta:{}};return this.state.animations.add(r)}createNewAnimationFromData(e,t=500,n){this.onChange();const i=this.generateNewID("animation"),s={internalID:this.getNewInternalId(),id:i,type:"animation",frames:e,interval:t,meta:{displayName:n}};return this.state.animations.add(s)}getGalleryTiles(e){return this.extensionTileSets?this.extensionTileSets.map((t=>t.tileSets.find((t=>t.tileWidth===e)))).filter((e=>null==e?void 0:e.tiles.length)):null}getProjectImages(){return this.state.images.getSnapshot()}getProjectTiles(t,n){const i=this.state.tiles.getSnapshot((e=>e.bitmap.width===t));return 0===i.length?n?(this.createNewTile(new e.sprite.Bitmap(t,t).data()),this.getProjectTiles(t,!1)):null:{tileWidth:t,tiles:i}}createNewTile(t,n,i){this.onChange(),n&&!this.isNameTaken("tile",n)||(n=this.generateNewID("tile"));const s={internalID:this.getNewInternalId(),id:n,type:"tile",jresData:e.sprite.base64EncodeBitmap(t),bitmap:t,meta:{displayName:i},isProjectTile:!0};return this.state.tiles.add(s)}createNewProjectImage(t,n){this.onChange();const i={internalID:this.getNewInternalId(),id:this.generateNewID("image"),type:"image",jresData:e.sprite.base64EncodeBitmap(t),meta:{displayName:n},bitmap:t};return this.state.images.add(i)}createNewSong(t,n){this.onChange();const i={internalID:this.getNewInternalId(),id:this.generateNewID("song"),type:"song",song:e.assets.music.cloneSong(t),meta:{displayName:n}};return this.state.songs.add(i)}updateTile(t){this.onChange();const n=this.resolveProjectTileByInternalID(t.internalID);if(n){if(this.state.tiles.update(n.id,t),n.id!==t.id||!e.sprite.bitmapEquals(n.bitmap,t.bitmap))for(const e of this.getAssets("tilemap"))e.data.tileset.tiles.some((e=>e.internalID===t.internalID))&&(e.data.tileset.tiles=e.data.tileset.tiles.map((e=>e.internalID===t.internalID?t:e)),this.updateTilemap(e.id,e.data));return t}return null}deleteTile(e){this.onChange(),this.state.tiles.removeByID(e)}getProjectTilesetJRes(){const t={};return this.state.tiles.serializeToJRes(t),this.state.tilemaps.serializeToJRes(t),t["*"]={mimeType:"image/x-mkcd-f4",dataEncoding:"base64",namespace:e.sprite.TILE_NAMESPACE},t}getProjectAssetsJRes(){const t={};return this.state.images.serializeToJRes(t),this.state.animations.serializeToJRes(t),this.state.songs.serializeToJRes(t),t["*"]={mimeType:"image/x-mkcd-f4",dataEncoding:"base64",namespace:e.sprite.IMAGES_NAMESPACE},t}getTilemap(e){return this.state.tilemaps.getByID(e)}updateTilemap(e,t){const n=this.state.tilemaps.getByID(e);if(n){this.onChange();const i=Object.assign(Object.assign({},n),{data:t});return this.state.tilemaps.update(e,i),i}return null}createNewTilemap(e,t,n=16,i=16){return this.createNewTilemapFromData(this.blankTilemap(t,n,i),e)}blankTilemap(t,n=16,i=16){const s=new e.sprite.Tilemap(n,i),r=new e.sprite.Bitmap(n,i),o={tileWidth:t,tiles:[this.getTransparency(t)]};return new e.sprite.TilemapData(s,o,r.data())}resolveTile(e){return this.lookupAsset("tile",e)}resolveProjectTileByInternalID(e){return this.state.tiles.getSnapshot((t=>t.internalID===e))[0]}resolveTileByBitmap(t){const n=e.sprite.base64EncodeBitmap(t);return this.state.tiles.getSnapshot((e=>e.jresData===n))[0]}getTransparency(t){const n=e.sprite.TILE_NAMESPACE+".transparency"+t;let i=this.state.tiles.getByID(n);if(!i){const s=new e.sprite.Bitmap(t,t).data();return i={internalID:this.getNewInternalId(),id:n,type:"tile",bitmap:s,jresData:e.sprite.base64EncodeBitmap(s),meta:{},isProjectTile:!0},this.state.tiles.add(i)}return i}createNewTilemapFromData(e,t){this.onChange();const n=this.generateNewIDInternal("tilemap",t||lf("level"));return this.state.tilemaps.add({internalID:this.getNewInternalId(),id:n,type:"tilemap",meta:{displayName:t||n},data:e}),[n,e]}cloneState(){return{revision:this.state.revision,images:this.state.images.clone(),tilemaps:this.state.tilemaps.clone(),animations:this.state.animations.clone(),tiles:this.state.tiles.clone(),songs:this.state.songs.clone()}}undo(){if(this.state.revision!==this.committedState.revision&&this.pushUndo(),this.undoStack.length){const e=this.undoStack.pop();this.state.tiles.applyDiff(e.tiles,!0),this.state.images.applyDiff(e.images,!0),this.state.tilemaps.applyDiff(e.tilemaps,!0),this.state.animations.applyDiff(e.animations,!0),this.state.songs.applyDiff(e.songs,!0),this.state.revision=e.beforeRevision,this.redoStack.push(e),this.committedState=this.cloneState(),this.needsRebuild=!0}}redo(){if(this.redoStack.length){const e=this.redoStack.pop();this.state.tiles.applyDiff(e.tiles),this.state.images.applyDiff(e.images),this.state.tilemaps.applyDiff(e.tilemaps),this.state.animations.applyDiff(e.animations),this.state.songs.applyDiff(e.songs),this.state.revision=e.afterRevision,this.undoStack.push(e),this.committedState=this.cloneState(),this.needsRebuild=!0}}pushUndo(){this.undoStack.length&&this.committedState.revision===this.state.revision||(this.redoStack=[],this.undoStack.push({beforeRevision:this.committedState.revision,afterRevision:this.state.revision,tiles:this.state.tiles.diff(this.committedState.tiles),images:this.state.images.diff(this.committedState.images),tilemaps:this.state.tilemaps.diff(this.committedState.tilemaps),animations:this.state.animations.diff(this.committedState.animations),songs:this.state.songs.diff(this.committedState.songs)}),this.committedState=this.cloneState(),this.cleanupTemporaryAssets())}revision(){return this.state.revision}encodeTilemap(t,n){const i=t.tilemap.data(),s=new Uint8ClampedArray(5+i.data.length+t.layers.data.length);return s[0]=t.tileset.tileWidth,s[1]=255&i.width,s[2]=i.width>>8&255,s[3]=255&i.height,s[4]=i.height>>8&255,s.set(i.data,5),s.set(t.layers.data,5+i.data.length),{id:n,mimeType:e.TILEMAP_MIME_TYPE,data:btoa(e.sprite.uint8ArrayToHex(s)),tileset:t.tileset.tiles.map((e=>e.id))}}forceUpdate(){this.onChange()}isNameTaken(e,t){const n=t=>y(this.state,e).isIDTaken(t)||y(this.gallery,e).isIDTaken(t),i=m(e,t),s=i&&i!==t;return n(t)||s&&n(i)}isAssetUsed(t,n,i){var s,r,o;if(((null===(r=null===(s=t.meta)||void 0===s?void 0:s.blockIDs)||void 0===r?void 0:r.filter((e=>!i||(null==i?void 0:i.indexOf(e))<0)))||[]).length>0)return!0;if("tile"==t.type)for(const e of this.getAssets("tilemap"))if(!((null==i?void 0:i.indexOf(e.id))>=0)&&e.data.tileset.tiles.some((e=>e.id===t.id)))return!0;if(n){const s=e.Util.escapeForRegex(f(t)),r=e.Util.escapeForRegex(null===(o=t.meta)||void 0===o?void 0:o.displayName)||"";let a;switch(t.type){case"tile":a=`myTiles.${s}|assets.tile\`${s}\``,r&&(a+=`|assets.tile\`${r}\``);break;case"tilemap":a=`tilemap\`${s}\``;break;case"animation":a=`assets.animation\`${s}\``,r&&(a+=`|assets.animation\`${r}\``);break;case"song":a=`assets.song\`${s}\``,r&&(a+=`|assets.song\`${r}\``);break;default:a=`assets.image\`${s}\``,r&&(a+=`|assets.image\`${r}\``)}const l=new RegExp(a,"gm");let c;switch(t.type){case"tile":c=`myTiles.${s}|assets.tile("""${s}""")`,r&&(c+=`|assets.tile("""${r}""")`);break;case"tilemap":c=`assets.tilemap("""${s}""")`;break;case"animation":c=`assets.animation("""${s}""")`,r&&(c+=`|assets.animation("""${r}""")`);break;case"song":c=`assets.song("""${s}""")`,r&&(c+=`|assets.song("""${r}""")`);break;default:c=`assets.image("""${s}""")`,r&&(c+=`|assets.image("""${r}""")`)}const u=new RegExp(c,"gm");for(let e of Object.keys(n)){if((null==i?void 0:i.indexOf(e))>=0)continue;const t=n[e];if(e.match(/((?!\.g).{2}|^.{0,1})\.ts$/i)){if(t.content.match(l))return!0}else if(e.endsWith(".py")&&t.content.match(u))return!0}}return!1}lookupAsset(e,t){return y(this.state,e).getByID(t)||y(this.gallery,e).getByID(t)}lookupAssetByName(e,t){return y(this.state,e).getByDisplayName(t)}getAssets(e){return y(this.state,e).getSnapshot()}getGalleryAssets(e){return y(this.gallery,e).getSnapshot()}lookupBlockAsset(e,t){return y(this.state,e).getSnapshot((e=>{var n,i;return-1!==(null===(i=null===(n=e.meta)||void 0===n?void 0:n.blockIDs)||void 0===i?void 0:i.indexOf(t))}))[0]}updateAsset(e){switch(this.onChange(),e.type){case"tile":return this.updateTile(e);default:return y(this.state,e.type).update(e.id,e)}}duplicateAsset(e,t){var n;this.onChange();const i=a(e),s=t||(null===(n=i.meta)||void 0===n?void 0:n.displayName);let r;switch(e.type){case"image":r=this.createNewProjectImage(i.bitmap,s);break;case"tile":r=this.createNewTile(i.bitmap,null,s);break;case"tilemap":const[t,n]=this.createNewTilemapFromData(i.data,s);r=this.getTilemap(t);break;case"animation":r=this.createNewAnimationFromData(i.frames,i.interval,s);break;case"song":r=this.createNewSong(e.song,s)}return r}removeAsset(e){this.onChange(),y(this.state,e.type).removeByID(e.id)}addChangeListener(e,t){y(this.state,e.type).addListener(e.internalID,t)}removeChangeListener(e,t){y(this.state,e).removeListener(t)}loadPackage(e){const t=e.sortedDeps();this.extensionTileSets=[];for(const e of t){const t="this"===e.id,n=this.readImages(e.parseJRes(),t);for(const i of n)i.meta.package=e.id,"tile"===i.type?t?this.state.tiles.add(i):this.gallery.tiles.add(i):"image"===i.type?t?this.state.images.add(i):this.gallery.images.add(i):"animation"===i.type?t?this.state.animations.add(i):this.gallery.animations.add(i):t?this.state.songs.add(i):this.gallery.songs.add(i)}for(const n of t){const t="this"===n.id;for(const s of i(n.parseJRes()))t?this.state.tilemaps.add({internalID:this.getNewInternalId(),type:"tilemap",id:s.id,meta:{displayName:s.displayName||s.id,package:e.id},data:o(s,(e=>this.resolveTile(e)))}):this.gallery.tilemaps.add({internalID:this.getNewInternalId(),type:"tilemap",id:s.id,meta:{displayName:s.displayName||s.id,package:e.id},data:o(s,(e=>this.gallery.tiles.getByID(e)))})}this.committedState=this.cloneState(),this.undoStack=[],this.redoStack=[]}loadTilemapJRes(t,n=!1,s=!1){t=e.inflateJRes(t);const r=this.readImages(t,!s).filter((e=>"tile"===e.type));let a={};if(s)for(const e of r)this.gallery.tiles.add(e);else for(const e of r){if(n){const t=this.resolveTileByBitmap(e.bitmap);if(t){a[e.id]=t.id;continue}}const t=this.createNewTile(e.bitmap,e.id,e.meta.displayName);t.id!==e.id&&(a[e.id]=t.id)}const l=s?this.gallery:this.state;for(const e of i(t))l.tilemaps.add({internalID:this.getNewInternalId(),type:"tilemap",id:e.id,meta:{displayName:e.displayName||e.id},data:o(e,(e=>(a[e]&&(e=a[e]),this.resolveTile(e))))})}loadAssetsJRes(t,n=!1){t=e.inflateJRes(t);const i=[],s=n?this.gallery:this.state;for(const n of Object.keys(t)){const r=t[n];if(r.tilemapTile)s.tiles.add(this.generateImage(r,"tile"));else if(r.mimeType===e.IMAGE_MIME_TYPE)s.images.add(this.generateImage(r,"image"));else if(r.mimeType===e.ANIMATION_MIME_TYPE){const[e,t]=this.generateAnimation(r);t?i.push(e):s.animations.add(e)}else r.mimeType===e.SONG_MIME_TYPE&&s.songs.add(this.generateSong(r))}for(const e of i)s.animations.add(this.inflateAnimation(e,s.images.getSnapshot()))}removeInactiveBlockAssets(e){function t(t){const n=t.getSnapshot((t=>{var n;return!t.meta.displayName&&(null===(n=t.meta.blockIDs)||void 0===n?void 0:n.some((t=>-1===e.indexOf(t))))})),i=[];for(const t of n)1===t.meta.blockIDs.length?i.push(t):(t.meta.blockIDs=t.meta.blockIDs.filter((t=>-1!==e.indexOf(t))),0===t.meta.blockIDs.length&&i.push(t));for(const e of i)t.removeByID(e.id)}t(this.state.images),t(this.state.tiles),t(this.state.tilemaps),t(this.state.animations),t(this.state.songs)}clone(){var e;const t=new n;return t.committedState=l(this.committedState),t.state=l(this.state),t.gallery=l(this.gallery),t.extensionTileSets=null===(e=this.extensionTileSets)||void 0===e?void 0:e.map((e=>Object.assign(Object.assign({},e),{tileSets:e.tileSets.map((e=>Object.assign(Object.assign({},e),{tiles:e.tiles.map((e=>a(e)))})))}))),t.needsRebuild=this.needsRebuild,t.nextID=this.nextID,t.nextInternalID=this.nextInternalID,t.undoStack=this.undoStack.map((e=>c(e))),t.redoStack=this.undoStack.map((e=>c(e))),t}generateImage(t,n){return{internalID:this.getNewInternalId(),type:n,id:t.id,meta:{displayName:t.displayName,tags:t.tags},jresData:t.data,bitmap:e.sprite.getBitmapFromJResURL(`data:${e.IMAGE_MIME_TYPE};base64,${t.data}`).data()}}generateSong(t){return{internalID:this.getNewInternalId(),type:"song",id:t.id,meta:{displayName:t.displayName,tags:t.tags},song:e.assets.music.decodeSongFromHex(t.data)}}generateAnimation(e){if("json"===e.dataEncoding){let t;try{t=JSON.parse(e.data)}catch(t){console.warn("could not parse json data of '"+e.id+"'")}return[{internalID:this.getNewInternalId(),type:"animation",meta:{displayName:e.displayName,tags:e.tags},id:e.id,frames:[],frameIds:t.frames,interval:100,flippedHorizontal:t.flippedHorizontal},!0]}return[Object.assign(Object.assign({},g(e)),{internalID:this.getNewInternalId()}),!1]}inflateAnimation(t,n){return t.frames=t.frameIds.map((e=>n.find((t=>t.id===e)).bitmap)),t.flippedHorizontal&&(t.frames=t.frames.map((t=>{const n=e.sprite.Bitmap.fromData(t),i=new e.sprite.Bitmap(t.width,t.height);for(let e=0;e<i.width;e++)for(let t=0;t<i.height;t++)i.set(e,t,n.get(n.width-e-1,t));return i.data()}))),t}generateNewID(t){switch(t){case"animation":return this.generateNewIDInternal("animation",e.sprite.ANIMATION_PREFIX,e.sprite.ANIMATION_NAMESPACE);case"image":return this.generateNewIDInternal("image",e.sprite.IMAGE_PREFIX,e.sprite.IMAGES_NAMESPACE);case"tile":return this.generateNewIDInternal("tile",e.sprite.TILE_PREFIX,e.sprite.TILE_NAMESPACE);case"tilemap":return this.generateNewIDInternal("tilemap",lf("level"));case"song":return this.generateNewIDInternal("song",e.sprite.SONG_PREFIX,e.sprite.SONG_NAMESPACE)}}generateNewIDInternal(e,t,n){t=t.replace(/\d+$/,"");const i=n?n+"."+t:t;let s=1;for(;this.isNameTaken(e,i+s);)++s;return i+s}onChange(){this.needsRebuild=!0,this.state.revision=this.nextID++}readImages(t,n=!1){const i=[],s=[];for(const r of Object.keys(t)){const o=t[r];if(o.tilemapTile){const e=this.generateImage(o,"tile");e.isProjectTile=n,i.push(e)}else if(o.mimeType===e.IMAGE_MIME_TYPE)i.push(this.generateImage(o,"image"));else if(o.mimeType===e.ANIMATION_MIME_TYPE){const[e,t]=this.generateAnimation(o);t?s.push(e):i.push(e)}else o.mimeType===e.SONG_MIME_TYPE&&i.push(this.generateSong(o))}for(const e of s)i.push(this.inflateAnimation(e,i));return i}cleanupTemporaryAssets(){const e=this.state.images.getSnapshot((e=>{var t;return!e.meta.displayName&&!(null===(t=e.meta.blockIDs)||void 0===t?void 0:t.length)}));for(const t of e)this.state.images.removeByID(t.id)}}function i(t){const n=[];for(const i of Object.keys(t)){const s=t[i];s.mimeType===e.TILEMAP_MIME_TYPE&&n.push(s)}return n}function s(e,t){return`\n helpers._registerFactory("${e}", function(name: string) {\n switch(helpers.stringTrim(name)) {\n`+t.map((e=>e.keys.filter((e=>!!e)).map((e=>` case "${e}":`)).join("\n")+`return ${e.expression};`)).join("\n")+"\n }\n return null;\n })\n"}function r(t){return e.sprite.Bitmap.fromData(t).copy().data()}function o(t,n){const i=atob(t.data),s=e.U.fromHex(i),r=s[1]|s[2]<<8,o=s[3]|s[4]<<8,a={tileWidth:s[0],tiles:t.tileset.map((e=>n&&n(e)||{id:e}))},l=s.slice(5,5+r*o),c=new e.sprite.Tilemap(r,o,0,0,new Uint8ClampedArray(l)),u=s.slice(5+l.length),d=new e.sprite.Bitmap(r,o,0,0,new Uint8ClampedArray(u)).data();return new e.sprite.TilemapData(c,a,d)}function a(t){switch(t.meta=Object.assign({},t.meta),t.type){case"tile":case"image":return Object.assign(Object.assign({},t),{bitmap:r(t.bitmap)});case"animation":return Object.assign(Object.assign({},t),{frames:t.frames.map((e=>r(e)))});case"tilemap":return Object.assign(Object.assign({},t),{data:t.data.cloneData()});case"song":return Object.assign(Object.assign({},t),{song:e.assets.music.cloneSong(t.song)})}}function l(e){return{revision:e.revision,tilemaps:e.tilemaps.clone(),images:e.images.clone(),animations:e.animations.clone(),songs:e.songs.clone(),tiles:e.tiles.clone()}}function c(e){return Object.assign(Object.assign({},e),{animations:u(e.animations),tiles:u(e.tiles),images:u(e.images),tilemaps:u(e.tilemaps),songs:u(e.songs)})}function u(e){return Object.assign(Object.assign({},e),{before:e.before.map((e=>a(e))),after:e.after.map((e=>a(e)))})}function d(t,n){const i=t.id.substr(t.id.lastIndexOf(".")+1),s=t.meta.tags;switch(t.type){case"image":if(n[i]=t.jresData,t.meta.displayName||(null==s?void 0:s.length)){const r={data:t.jresData,mimeType:e.IMAGE_MIME_TYPE};t.meta.displayName&&(r.displayName=t.meta.displayName),(null==s?void 0:s.length)&&(r.tags=s),n[i]=r}break;case"tile":const r={data:t.jresData,mimeType:e.IMAGE_MIME_TYPE,tilemapTile:!0,displayName:t.meta.displayName};(null==s?void 0:s.length)&&(r.tags=s),n[i]=r;break;case"tilemap":const o=function(t,n,i){const s=t.tilemap.data(),r=new Uint8ClampedArray(5+s.data.length+t.layers.data.length);return r[0]=t.tileset.tileWidth,r[1]=255&s.width,r[2]=s.width>>8&255,r[3]=255&s.height,r[4]=s.height>>8&255,r.set(s.data,5),r.set(t.layers.data,5+s.data.length),{id:n,mimeType:e.TILEMAP_MIME_TYPE,data:btoa(e.sprite.uint8ArrayToHex(r)),tileset:t.tileset.tiles.map((e=>e.id)),displayName:i}}(t.data,t.id,t.meta.displayName);n[o.id]=o;break;case"animation":n[i]=function(t){var n;const i={namespace:t.id.substr(0,t.id.lastIndexOf(".")),id:t.id.substr(t.id.lastIndexOf(".")+1),mimeType:e.ANIMATION_MIME_TYPE,data:e.sprite.encodeAnimationString(t.frames,t.interval),displayName:t.meta.displayName};(null===(n=t.meta.tags)||void 0===n?void 0:n.length)&&(i.tags=t.meta.tags);return i}(t);break;case"song":const a={data:e.assets.music.encodeSongToHex(t.song),mimeType:e.SONG_MIME_TYPE,displayName:t.meta.displayName,namespace:e.sprite.SONG_NAMESPACE+"."};(null==s?void 0:s.length)&&(a.tags=s),n[i]=a}}function h(t,n){if(t==n)return!0;if(t.id!==n.id||t.type!==n.type||!e.U.arrayEquals(t.meta.tags,n.meta.tags)||!e.U.arrayEquals(t.meta.blockIDs,n.meta.blockIDs)||t.meta.displayName!==n.meta.displayName)return!1;switch(t.type){case"image":case"tile":return e.sprite.bitmapEquals(t.bitmap,n.bitmap);case"animation":const i=n;return t.interval===i.interval&&e.U.arrayEquals(t.frames,i.frames,e.sprite.bitmapEquals);case"tilemap":return t.data.equals(n.data);case"song":return e.assets.music.songEquals(t.song,n.song)}}function p(e){const t=/^\s*(?:(?:assets\s*\.\s*(image|tile|animation|tilemap|song))|(tilemap))\s*(?:`|\(""")([^`"]+)(?:`|"""\))\s*$/m.exec(e);if(t){return{type:t[1]||t[2],name:t[3].trim()}}}function f(e){return m(e.type,e.id)}function m(t,n,i=!1){let s;switch(t){case"image":s=e.sprite.IMAGES_NAMESPACE+".";break;case"tile":s=e.sprite.TILE_NAMESPACE+".";break;case"tilemap":s="";break;case"animation":s=e.sprite.ANIMATION_NAMESPACE+".";break;case"song":s=e.sprite.SONG_NAMESPACE+"."}if(s)if(n.startsWith(s)){const e=n.substr(s.length);if(-1===e.indexOf("."))return e}else if(!i)return null;return n}function g(t){const n=atob(t.data),i=new Uint8ClampedArray(e.U.fromHex(n)),s=b(i,0),r=b(i,2),o=b(i,4),a=b(i,6),l=Math.ceil(r*o/2);let c=8;const u=[];for(let e=0;e<a;e++){const e=i.slice(c,c+l);u.push({x0:0,y0:0,width:r,height:o,data:e}),c+=l}let d=t.id;return d.startsWith(t.namespace)||(d=t.namespace+"."+d,d=d.replace(/\.\./g,".")),{type:"animation",internalID:0,id:d,interval:s,frames:u,meta:{displayName:t.displayName,tags:t.tags}}}function b(e,t){return e[t]|e[t+1]<<8}function y(e,t){switch(t){case"animation":return e.animations;case"image":return e.images;case"tile":return e.tiles;case"tilemap":return e.tilemaps;case"song":return e.songs}}e.TilemapProject=n,e.emitGalleryDeclarations=function(t,n){var i;const s=Object.keys(t);let r="";const a={},l={},c={},u=e=>{let n=t[e].namespace||t["*"].namespace;const i=t[e].id||e;return n&&(n.endsWith(".")&&(n=n.slice(0,n.length-1)),!i.startsWith(n+"."))?n+"."+i:i};t["*"]&&(c["*"]=Object.assign(Object.assign({},t["*"]),{namespace:n}));for(const e of s){if("*"===e)continue;const i=t[e],s=u(e);let r=ts.pxtc.escapeIdentifier(i.displayName||s.split(".").pop());if(a[r]){const e=r;let t=2;for(;a[r];)r=e+t,t++}a[r]=!0,l[s]=n+"."+r}for(const a of s){if("*"===a)continue;const s=t[a];let d,h,p=s.mimeType||(null===(i=t["*"])||void 0===i?void 0:i.mimeType);const f=l[u(a)].split(".").pop();let m=s.tags;if(m||(m=[],-1!==f.toLowerCase().indexOf("background")&&m.push("background"),-1!==f.toLowerCase().indexOf("dialog")&&m.push("dialog"),s.tilemapTile&&m.push("tile")),p===e.IMAGE_MIME_TYPE)h="image.ofBuffer(hex``)",d=s.tilemapTile?"images._tile":"images._image";else if(p===e.ANIMATION_MIME_TYPE){h=`[${g(s).frames.map((t=>e.sprite.bitmapToImageLiteral(e.sprite.Bitmap.fromData(t),"typescript"))).join(",")}]`}else if(p===e.TILEMAP_MIME_TYPE){const t=o(s);h=e.sprite.encodeTilemap(t,"typescript",l)}else p===e.SONG_MIME_TYPE&&(h=`hex\`${s.data}\``);r+=" //% fixedInstance jres whenUsed\n",d&&(r+=` //% blockIdentity=${d}\n`),m.length&&(r+=` //% tags="${m.join(" ")}"\n`),r+=` export const ${f} = ${h};\n`,"string"==typeof s?c[f]=s:(c[f]=Object.assign(Object.assign({},s),{id:l[u(a)],tags:m}),s.namespace&&(c[f].namespace=n,s.namespace.endsWith(".")&&(c[f].namespace+=".")),c[f].tileset&&(c[f].tileset=s.tileset.map((e=>l[e]||e))))}const d=lf("Auto-generated code. Do not edit.");return[c,`// ${d}\nnamespace ${n} {\n${r}\n}\n// ${d}\n`]},e.emitTilemapsFromJRes=function(t){const n=Object.keys(t);let i="";const r=[],a=[];for(const s of n){if("*"===s)continue;const n=t[s];if(n.tilemapTile){let e=s;-1!==e.indexOf(".")&&(e=e.split(".").slice(-1)[0]),i+=" //% fixedInstance jres blockIdentity=images._tile\n",i+=` export const ${e} = image.ofBuffer(hex\`\`);\n`,a.push({keys:[n.displayName,m("tile",s,!0)],expression:s})}if(n.mimeType===e.TILEMAP_MIME_TYPE){const t=o(n);r.push({keys:[n.displayName,m("tilemap",n.id)],expression:e.sprite.encodeTilemap(t,"typescript")})}}r.length&&(i+=s("tilemap",r)),a.length&&(i+=s("tile",a));const l=lf("Auto-generated code. Do not edit.");return`// ${l}\nnamespace ${e.sprite.TILE_NAMESPACE} {\n${i}\n}\n// ${l}\n`},e.emitProjectImages=function(t){const n=Object.keys(t);let i="";const r=[],o=[],a=[];for(const i of n){if("*"===i)continue;const n=t[i];if("string"==typeof n||n.mimeType===e.IMAGE_MIME_TYPE){let t,s=[m("image",i,!0)];"string"==typeof n?t=e.sprite.bitmapToImageLiteral(e.sprite.getBitmapFromJResURL(n),"typescript"):(t=e.sprite.bitmapToImageLiteral(e.sprite.getBitmapFromJResURL(n.data),"typescript"),s.push(n.displayName)),r.push({keys:s,expression:t})}else if(n.mimeType===e.ANIMATION_MIME_TYPE){const t=g(n);o.push({keys:[n.displayName,m("animation",i,!0)],expression:`[${t.frames.map((t=>e.sprite.bitmapToImageLiteral(e.sprite.Bitmap.fromData(t),"typescript"))).join(", ")}]`})}else n.mimeType===e.SONG_MIME_TYPE&&a.push({keys:[m("song",i,!0),n.displayName],expression:`hex\`${n.data}\``})}const l=lf("Auto-generated code. Do not edit.");return i+=s("image",r),i+=s("animation",o),i+=s("song",a),`// ${l}\nnamespace ${e.sprite.IMAGES_NAMESPACE} {\n${i}\n}\n// ${l}\n`},e.cloneAsset=a,e.assetEquals=h,e.validateAssetName=function(e){return!!e&&!/[\u0000-\u001f\u0021-\u002c\u002e\u002f\u003a-\u0040\u005b-\u005e\u0060\u007b-\u007f]/.test(e)},e.getTSReferenceForAsset=function(e,t=!1){var n;let i;if(i=(null===(n=e.meta)||void 0===n?void 0:n.displayName)?e.meta.displayName:f(e),!i)return"image"===e.type||"tile"===e.type?e.id:void 0;const s=t?'("""':"`",r=t?'""")':"`";switch(e.type){case"tile":return`assets.tile${s}${i}${r}`;case"image":return`assets.image${s}${i}${r}`;case"animation":return`assets.animation${s}${i}${r}`;case"tilemap":return`tilemap${s}${i}${r}`;case"song":return`assets.song${s}${i}${r}`}},e.parseAssetTSReference=p,e.lookupProjectAssetByTSReference=function(e,t){const n=p(e);if(n){const{type:e,name:i}=n;switch(e){case"tile":return t.lookupAssetByName("tile",i);case"image":return t.lookupAssetByName("image",i);case"tilemap":return t.lookupAssetByName("tilemap",i)||t.lookupAsset("tilemap",i);case"animation":return t.lookupAssetByName("animation",i);case"song":return t.lookupAssetByName("song",i)}}},e.getDefaultAssetDisplayName=function(e){switch(e){case"image":return lf("myImage");case"tile":return lf("myTile");case"tilemap":return lf("level");case"animation":return lf("myAnim");case"song":return lf("mySong");default:return lf("asset")}},e.getShortIDForAsset=f}(pxt||(pxt={})),function(e){!function(t){const n={};t.blockColors={loops:"#107c10",logic:"#006970",math:"#712672",variables:"#A80000",functions:"#005a9e",text:"#996600",arrays:"#A94400",advanced:"#3c3c3c",addpackage:"#717171",search:"#000",debug:"#e03030",default:"#dddddd",topblocks:"#aa8f00",recipes:"#717171"},t.blockIcons={loops:"",logic:"",math:"",variables:"",functions:"",text:"",arrays:"",advancedcollapsed:"",advancedexpanded:"",more:"",addpackage:"",search:"",debug:"",default:"",topblocks:"",recipes:""};let i="";function s(e){const t=function(e,t,n){let i=0,s=0,r=0;if(0==t)i=n,s=n,r=n;else{let o=Math.floor(e/60),a=e/60-o,l=n*(1-t),c=n*(1-t*a),u=n*(1-t*(1-a));switch(o){case 1:i=c,s=n,r=l;break;case 2:i=l,s=n,r=u;break;case 3:i=l,s=c,r=n;break;case 4:i=u,s=l,r=n;break;case 5:i=n,s=l,r=c;break;case 6:case 0:i=n,s=u,r=l}}return[Math.floor(i),Math.floor(s),Math.floor(r)]}(e,.45,165.75);return`#${r(t[0])}${r(t[1])}${r(t[2])}`}function r(e){const t=e.toString(16);return 1==t.length?"0"+t:t}function o(t){var i,s;return(null===(s=null===(i=e.appTarget)||void 0===i?void 0:i.appTheme)||void 0===s?void 0:s.adjustBlockContrast)?(n[t]||(n[t]=e.getWhiteContrastingBackground(t)),n[t]):t}t.appendToolboxIconCss=function(t,n){if(!(i.indexOf(t)>-1))if(1===n.length){const s=e.Util.unicodeToChar(n);i+=`\n .blocklyTreeIcon.${t}::before {\n content: "${s}";\n }\n `}else i+=`\n .blocklyTreeIcon.${t} {\n background-image: url("${e.Util.pathJoin(e.webConfig.commitCdnUrl,encodeURI(n))}")!important;\n width: 30px;\n height: 100%;\n background-size: 20px !important;\n background-repeat: no-repeat !important;\n background-position: 50% 50% !important;\n }\n `},t.getNamespaceColor=function(t){let n;return t=t.toLowerCase(),e.appTarget.appTheme.blockColors&&e.appTarget.appTheme.blockColors[t]?n=e.appTarget.appTheme.blockColors[t]:e.toolbox.blockColors[t]&&(n=e.toolbox.blockColors[t]),n?o(n):""},t.getNamespaceIcon=function(t){return t=t.toLowerCase(),e.appTarget.appTheme.blockIcons&&e.appTarget.appTheme.blockIcons[t]?e.appTarget.appTheme.blockIcons[t]:e.toolbox.blockIcons[t]?e.toolbox.blockIcons[t]:""},t.advancedTitle=function(){return e.Util.lf("{id:category}Advanced")},t.addPackageTitle=function(){return e.Util.lf("{id:category}Extensions")},t.recipesTitle=function(){return e.Util.lf("{id:category}Tutorials")},t.convertColor=function(e){var t;e=(t=e)?"0x"==t.substring(0,2)?"#"+t.substring(2):t:"#000000";const n=parseInt(e);return isNaN(n)?e:s(n)},t.hueToRgb=s,t.fadeColor=function(e,t,n){(e=e.replace(/[^0-9a-f]/gi,"")).length<6&&(e=e[0]+e[0]+e[1]+e[1]+e[2]+e[2]);let i="#";for(let s=0;s<3;s++){let r=parseInt(e.substr(2*s,2),16);r=Math.round(Math.min(Math.max(0,n?r+r*t:r-r*t),255));let o=r.toString(16);i+=("00"+o).substr(o.length)}return i},t.getAccessibleBackground=o}(e.toolbox||(e.toolbox={}))}(pxt||(pxt={})),function(e){!function(t){const n=/^##[^#](.*)$([\s\S]*?)(?=^##[^#]|$(?![\r\n]))/gim,i=/^###[^#](.*)$([\s\S]*?)(?=^###[^#]|$(?![\r\n]))/gim;function s(){return/``` *(sim|block|blocks|filterblocks|spy|ghost|typescript|ts|js|javascript|template|python|jres|assetjson|customts|simtheme|python-template|ts-template|typescript-template|js-template|javascript-template)\s*\n([\s\S]*?)\n```/gim}function r(t,i,s){let r=i||n,c=[];if(t.replace(r,(function(e,t,n){n=n.trim();let{header:i,hint:r}=function(e,t){let n,i=e=l(e);if(t){const t=/#+ ~ tutorialhint([\s\S]*)/i;i=e.replace(t,(function(e,t){return n=t,""}))}else{const t=/(^[\s\S]*?\S)\s*((```|\[?\!\[[\s\S]+?\]\(\S+?\)\]?)[\s\S]*)/im;let s=e.match(t);s&&s.length>2&&(i=s[1].trim(),n=s[2].trim())}return{header:i,hint:n}}(n,s&&s.explicitHints);const u=o("local",n),d=a("local",n);let h={title:t.match(/^\{.*\}$/)?void 0:t.replace(/@(fullscreen|unplugged|showdialog|showhint|tutorialCompleted|resetDiff)/gi,"").trim(),contentMd:n,headerContentMd:i,localBlockConfig:u,localValidationConfig:d};return/@(fullscreen|unplugged|showdialog|showhint)/i.test(t)&&(h.showHint=!0),/@(unplugged|showdialog)/i.test(t)&&(h.showDialog=!0),/@tutorialCompleted/.test(t)&&(h.tutorialCompleted=!0),/@resetDiff/.test(t)&&(h.resetDiff=!0),r&&(h.hintContentMd=r),c.push(h),""})),0!=t.indexOf("# Not found"))return c;e.debug("tutorial not found")}function o(e,t){let n={md:"",blocks:[]};const i=new RegExp(`\`\`\`\\s*blockconfig\\.${e}\\s*\\n([\\s\\S]*?)\\n\`\`\``,"gmi");return t.replace(i,((e,t)=>(n.md+=`${t}\n`,""))),n}function a(t,n){let i;const s=new RegExp(`\`\`\`\\s*validation\\.${t}\\s*\\n([\\s\\S]*?)\\n\`\`\``,"gmi");if(n.replace(s,((e,t)=>(i=t,""))),!i||""==i)return null;return{validatorsMetadata:e.getSectionsFromMarkdownMetadata(i).map((e=>({validatorType:e.header,properties:e.attributes})))}}function l(e){if(!e)return e;return e.replace(/```(filterblocks|package|ghost|config|template|jres|assetjson|simtheme|customts|blockconfig\.local|blockconfig\.global|validation\.local|validation\.global)\s*\n([\s\S]*?)\n```/gim,"").trim()}function c(t){if(!t)return;const n=JSON.parse(t);return{[e.TILEMAP_JRES]:n[e.TILEMAP_JRES],[e.TILEMAP_CODE]:n[e.TILEMAP_CODE],[e.IMAGES_JRES]:n[e.IMAGES_JRES],[e.IMAGES_CODE]:n[e.IMAGES_CODE]}}function u(t){const n=e.Util.jsonTryParse(t);if(!n)return;const i={};return n.theme&&(i.theme=n.theme),n.palette&&(i.palette=n.palette),i}t.parseTutorial=function(t){const{metadata:s,body:d}=function(t){const n=/### @(\S+) ([ \S]+)/gi,i={},s=t.replace(n,(function(e,t,n){try{i[t]=JSON.parse(n)}catch(e){i[t]=n}return""})),r=i;void 0!==r.explicitHints&&e.appTarget.appTheme&&e.appTarget.appTheme.tutorialExplicitHints&&(r.explicitHints=!0);return{metadata:r,body:s}}(t),{steps:h,activities:p}=function(e,t){if(t&&t.activities)return function(e,t){let s=[],o=[];return e.replace(n,(function(e,n,a){let l=o.length;o.push({name:n||lf("Activity {0}",l),step:s.length});let c=r(a,i,t);return c=c.map((e=>(e.activity=l,e))),s=s.concat(c),""})),{steps:s,activities:o}}(e,t);{let n=r(e,null,t);return(!n||n.length<1)&&(n=r(e,i,t)),{steps:n,activities:null}}}(d,s),f=function(e){let t=e.match(/^#[^#](.*)$/im);return t&&t.length>1?t[1].trim():null}(d);if(!h)return;const{code:m,templateCode:g,templateLanguage:b,editor:y,language:v,jres:w,assetJson:k,customTs:x,simThemeJson:A}=function(t){let n;const i=/``` *(sim|block|blocks|filterblocks|spy|ghost|typescript|ts|js|javascript|template|python|jres|assetjson|customts|simtheme|python-template|ts-template|typescript-template|js-template|javascript-template)\s*\n([\s\S]*?)\n```/gim;let s,r,o,a,l,c,u,d=[];return t.replace(/((?!.)\s)+/g,"\n").replace(i,(function(t,n,i){switch(n){case"block":case"blocks":case"blockconfig.local":case"blockconfig.global":case"filterblocks":if(!h(e.BLOCKS_PROJECT_NAME))return;break;case"spy":case"python":if(!h(e.PYTHON_PROJECT_NAME))return;"python"==n&&(a=n);break;case"typescript":case"ts":case"javascript":case"js":if(!h(e.JAVASCRIPT_PROJECT_NAME))return;break;case"template":r=i;break;case"python-template":if(!h(e.PYTHON_PROJECT_NAME))return;r=i,o="python",a="python";break;case"ts-template":case"typescript-template":case"js-template":case"javascript-template":if(!h(e.JAVASCRIPT_PROJECT_NAME))return;r=i,o="typescript";break;case"jres":s=i;break;case"assetjson":l=i;break;case"simtheme":u=i;break;case"customts":c=i,i=""}return d.push("python"==n?`\n${i}\n`:`{\n${i}\n}`),""})),n=n||e.BLOCKS_PROJECT_NAME,{code:d,templateCode:r,templateLanguage:o,editor:n,language:a,jres:s,assetJson:l,customTs:c,simThemeJson:u};function h(t){return n&&n!=t?(e.debug("tutorial ambiguous: contains snippets of different types"),!1):(n=t,!0)}}(d);(!0===s.diffs||!1!==s.diffs&&!0!==s.noDiffs&&(y==e.BLOCKS_PROJECT_NAME&&e.appTarget.appTheme.tutorialBlocksDiff||y!=e.BLOCKS_PROJECT_NAME&&e.appTarget.appTheme.tutorialTextDiff))&&function(e,t){let n;function i(e){const t={typescript:"diff",spy:"diffspy",blocks:"diffblocks",python:"diff"},i=/\s*(\/\/|#)\s*@highlight/gm;return e?e.replace(/```(typescript|spy|python|blocks|ghost|template)((?:.|[\r\n])+)```/,(function(e,s,r){const o=n,a=/^(template|ghost)$/.test(s),l=i.test(r);return r=r.replace(/^\n+/,"").replace(/\n+$/,""),l&&(r=r.replace(i,"")),n=r,!o||l||a?e:`\`\`\`${t[s]}\n${o}\n----------\n${r}\n\`\`\``})):e}e.forEach(((e,s)=>{if((e.resetDiff||t&&t.find((e=>e.step==s)))&&(n=void 0),e.hintContentMd){const t=i(e.hintContentMd);if(t&&t!=e.hintContentMd)return void(e.hintContentMd=t)}if(e.headerContentMd){const t=i(e.headerContentMd);if(t&&t!=e.headerContentMd)return void(e.headerContentMd=t)}}))}(h,p);const E=c(k),T=u(A),S=o("global",t),C=a("global",t);return h.forEach((e=>{e.contentMd=l(e.contentMd),e.headerContentMd=l(e.headerContentMd),e.hintContentMd=l(e.hintContentMd)})),{editor:y,title:f,steps:h,activities:p,code:m,templateCode:g,templateLanguage:b,metadata:s,language:v,jres:w,assetFiles:E,customTs:x,globalBlockConfig:S,globalValidationConfig:C,simTheme:T}},t.getMetadataRegex=s,t.highlight=function(e){let t=e.textContent;if(t=t.replace(/img\s*\(\s*"{3}[\s\da-f.#tngrpoyw]*"{3}\s*\)/g,'img(""" """)'),t=t.replace(/img\s*`[\s\da-f.#tngrpoyw]*`\s*/g,"img` `"),!/@highlight/.test(t))return void(e.textContent=t);e.textContent="";const n=t.split("\n");for(let t=0;t<n.length;++t){t>0&&t<n.length&&e.appendChild(document.createTextNode("\n"));let i=n[t];if(/@highlight/.test(i)){if(i=n[++t],void 0!==i){const t=document.createElement("span");t.className="highlight-line",t.textContent=i,e.appendChild(t)}}else e.appendChild(document.createTextNode(i))}},t.getTutorialOptions=function(t,n,i,s,r){var o;const a=e.tutorial.parseTutorial(t);if(!a)throw new Error(lf("Invalid tutorial format"));return{options:{tutorial:n,tutorialName:a.title||i,tutorialReportId:s,tutorialStep:0,tutorialReady:!0,tutorialHintCounter:0,tutorialStepInfo:a.steps,tutorialActivityInfo:a.activities,tutorialMd:t,tutorialCode:a.code,tutorialRecipe:!!r,templateCode:a.templateCode,templateLanguage:a.templateLanguage,autoexpandStep:!(null===(o=a.metadata)||void 0===o?void 0:o.autoexpandOff),metadata:a.metadata,language:a.language,jres:a.jres,assetFiles:a.assetFiles,customTs:a.customTs,globalBlockConfig:a.globalBlockConfig,globalValidationConfig:a.globalValidationConfig,simTheme:a.simTheme},editor:a.editor}},t.parseCachedTutorialInfo=function(t,n){let i=e.Util.jsonTryParse(t);return i?e.BrowserUtils.tutorialInfoDbAsync().then((e=>{if(n&&i[n]){const t=i[n];t.usedBlocks&&t.hash&&e.setWithHashAsync(n,t.snippetBlocks,t.hash,t.highlightBlocks,t.validateBlocks)}else for(let t of Object.keys(i)){const n=i[t];n.usedBlocks&&n.hash&&e.setWithHashAsync(t,n.snippetBlocks,n.hash,n.highlightBlocks,n.validateBlocks)}})).catch((e=>{})):Promise.resolve()},t.resolveLocalizedMarkdown=function(t,n,i){const s=(i||t.fileName||"README")+".md";let r;const[o,a,l]=e.Util.normalizeLanguageCode(e.Util.userLanguage());return r=o&&a&&l?n[`_locales/${o}/${s}`]||n[`_locales/${l}/${s}`]||n[`_locales/${a}/${s}`]:n[`_locales/${o}/${s}`],r=r||n[s],r},t.parseAssetJson=c,t.parseSimThemeJson=u,t.getTutorialHighlightedBlocks=async function(t){const n=await e.BrowserUtils.tutorialInfoDbAsync(),i=await n.getAsync(t.tutorial,t.tutorialCode);return null==i?void 0:i.highlightBlocks},t.getTutorialValidateBlocks=async function(t){const n=await e.BrowserUtils.tutorialInfoDbAsync(),i=await n.getAsync(t.tutorial,t.tutorialCode);return null==i?void 0:i.validateBlocks},t.getRequiredBlockCounts=function(e){if(!e)return;const t={},n=e["validate-exists"];return n&&n.forEach((e=>{t[e]=(t[e]||0)+1})),t},t.getTutorialStepHash=function(t){const{tutorialStepInfo:n,tutorialStep:i}=t,s=function(e){let t=[];return null==e||e.replace(/((?!.)\s)+/g,"\n").replace(/``` *(block|blocks)\s*\n([\s\S]*?)\n```/gim,(function(e,n,i){return t.push(`{\n${i}\n}`),""})),t}(n[i].hintContentMd);return e.BrowserUtils.getTutorialCodeHash(s)}}(e.tutorial||(e.tutorial={}))}(pxt||(pxt={})),function(e){!function(t){let n;t.flattenDiagnosticMessageText=function(e,t){if("string"==typeof e)return e;{let n=e,i="",s=0;for(;n;){if(s){i+=t;for(let e=0;e<s;e++)i+=" "}i+=n.messageText,s++,n=n.next}return i}},function(e){e[e.ES3=0]="ES3",e[e.ES5=1]="ES5",e[e.ES6=2]="ES6",e[e.ES2015=2]="ES2015",e[e.Latest=2]="Latest"}(n=t.ScriptTarget||(t.ScriptTarget={})),t.isIdentifierStart=function(e,t){return e>=65&&e<=90||e>=97&&e<=122||36===e||95===e||e>127&&a(e,t)},t.isIdentifierPart=function(e,t){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||36===e||95===e||e>127&&function(e,t){return t>=n.ES5?l(e,s):l(e,o)}(e,t)},t.reservedWords=["abstract","any","as","break","case","catch","class","continue","const","constructor","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","is","let","module","namespace","new","null","package","private","protected","public","require","global","return","set","static","super","switch","symbol","this","throw","true","try","type","typeof","var","void","while","with","yield","async","await","of","Math"],t.keywordTypes=["boolean","number","string"],t.escapeIdentifier=function(n){if(!n)return"_";let i=n.replace(/\s+/g,"_").replace(/[^a-zA-Z0-9_$]/g,(t=>e.pxtc.isIdentifierPart(t.charCodeAt(0),e.pxtc.ScriptTarget.ES5)?t:""));return i&&e.pxtc.isIdentifierStart(i.charCodeAt(0),e.pxtc.ScriptTarget.ES5)&&-1===t.reservedWords.indexOf(i)||(i="_"+i),i};const i=[170,170,181,181,186,186,192,214,216,246,248,705,710,721,736,740,748,748,750,750,880,884,886,887,890,893,902,902,904,906,908,908,910,929,931,1013,1015,1153,1162,1319,1329,1366,1369,1369,1377,1415,1488,1514,1520,1522,1568,1610,1646,1647,1649,1747,1749,1749,1765,1766,1774,1775,1786,1788,1791,1791,1808,1808,1810,1839,1869,1957,1969,1969,1994,2026,2036,2037,2042,2042,2048,2069,2074,2074,2084,2084,2088,2088,2112,2136,2208,2208,2210,2220,2308,2361,2365,2365,2384,2384,2392,2401,2417,2423,2425,2431,2437,2444,2447,2448,2451,2472,2474,2480,2482,2482,2486,2489,2493,2493,2510,2510,2524,2525,2527,2529,2544,2545,2565,2570,2575,2576,2579,2600,2602,2608,2610,2611,2613,2614,2616,2617,2649,2652,2654,2654,2674,2676,2693,2701,2703,2705,2707,2728,2730,2736,2738,2739,2741,2745,2749,2749,2768,2768,2784,2785,2821,2828,2831,2832,2835,2856,2858,2864,2866,2867,2869,2873,2877,2877,2908,2909,2911,2913,2929,2929,2947,2947,2949,2954,2958,2960,2962,2965,2969,2970,2972,2972,2974,2975,2979,2980,2984,2986,2990,3001,3024,3024,3077,3084,3086,3088,3090,3112,3114,3123,3125,3129,3133,3133,3160,3161,3168,3169,3205,3212,3214,3216,3218,3240,3242,3251,3253,3257,3261,3261,3294,3294,3296,3297,3313,3314,3333,3340,3342,3344,3346,3386,3389,3389,3406,3406,3424,3425,3450,3455,3461,3478,3482,3505,3507,3515,3517,3517,3520,3526,3585,3632,3634,3635,3648,3654,3713,3714,3716,3716,3719,3720,3722,3722,3725,3725,3732,3735,3737,3743,3745,3747,3749,3749,3751,3751,3754,3755,3757,3760,3762,3763,3773,3773,3776,3780,3782,3782,3804,3807,3840,3840,3904,3911,3913,3948,3976,3980,4096,4138,4159,4159,4176,4181,4186,4189,4193,4193,4197,4198,4206,4208,4213,4225,4238,4238,4256,4293,4295,4295,4301,4301,4304,4346,4348,4680,4682,4685,4688,4694,4696,4696,4698,4701,4704,4744,4746,4749,4752,4784,4786,4789,4792,4798,4800,4800,4802,4805,4808,4822,4824,4880,4882,4885,4888,4954,4992,5007,5024,5108,5121,5740,5743,5759,5761,5786,5792,5866,5870,5872,5888,5900,5902,5905,5920,5937,5952,5969,5984,5996,5998,6e3,6016,6067,6103,6103,6108,6108,6176,6263,6272,6312,6314,6314,6320,6389,6400,6428,6480,6509,6512,6516,6528,6571,6593,6599,6656,6678,6688,6740,6823,6823,6917,6963,6981,6987,7043,7072,7086,7087,7098,7141,7168,7203,7245,7247,7258,7293,7401,7404,7406,7409,7413,7414,7424,7615,7680,7957,7960,7965,7968,8005,8008,8013,8016,8023,8025,8025,8027,8027,8029,8029,8031,8061,8064,8116,8118,8124,8126,8126,8130,8132,8134,8140,8144,8147,8150,8155,8160,8172,8178,8180,8182,8188,8305,8305,8319,8319,8336,8348,8450,8450,8455,8455,8458,8467,8469,8469,8473,8477,8484,8484,8486,8486,8488,8488,8490,8493,8495,8505,8508,8511,8517,8521,8526,8526,8544,8584,11264,11310,11312,11358,11360,11492,11499,11502,11506,11507,11520,11557,11559,11559,11565,11565,11568,11623,11631,11631,11648,11670,11680,11686,11688,11694,11696,11702,11704,11710,11712,11718,11720,11726,11728,11734,11736,11742,11823,11823,12293,12295,12321,12329,12337,12341,12344,12348,12353,12438,12445,12447,12449,12538,12540,12543,12549,12589,12593,12686,12704,12730,12784,12799,13312,19893,19968,40908,40960,42124,42192,42237,42240,42508,42512,42527,42538,42539,42560,42606,42623,42647,42656,42735,42775,42783,42786,42888,42891,42894,42896,42899,42912,42922,43e3,43009,43011,43013,43015,43018,43020,43042,43072,43123,43138,43187,43250,43255,43259,43259,43274,43301,43312,43334,43360,43388,43396,43442,43471,43471,43520,43560,43584,43586,43588,43595,43616,43638,43642,43642,43648,43695,43697,43697,43701,43702,43705,43709,43712,43712,43714,43714,43739,43741,43744,43754,43762,43764,43777,43782,43785,43790,43793,43798,43808,43814,43816,43822,43968,44002,44032,55203,55216,55238,55243,55291,63744,64109,64112,64217,64256,64262,64275,64279,64285,64285,64287,64296,64298,64310,64312,64316,64318,64318,64320,64321,64323,64324,64326,64433,64467,64829,64848,64911,64914,64967,65008,65019,65136,65140,65142,65276,65313,65338,65345,65370,65382,65470,65474,65479,65482,65487,65490,65495,65498,65500],s=[170,170,181,181,186,186,192,214,216,246,248,705,710,721,736,740,748,748,750,750,768,884,886,887,890,893,902,902,904,906,908,908,910,929,931,1013,1015,1153,1155,1159,1162,1319,1329,1366,1369,1369,1377,1415,1425,1469,1471,1471,1473,1474,1476,1477,1479,1479,1488,1514,1520,1522,1552,1562,1568,1641,1646,1747,1749,1756,1759,1768,1770,1788,1791,1791,1808,1866,1869,1969,1984,2037,2042,2042,2048,2093,2112,2139,2208,2208,2210,2220,2276,2302,2304,2403,2406,2415,2417,2423,2425,2431,2433,2435,2437,2444,2447,2448,2451,2472,2474,2480,2482,2482,2486,2489,2492,2500,2503,2504,2507,2510,2519,2519,2524,2525,2527,2531,2534,2545,2561,2563,2565,2570,2575,2576,2579,2600,2602,2608,2610,2611,2613,2614,2616,2617,2620,2620,2622,2626,2631,2632,2635,2637,2641,2641,2649,2652,2654,2654,2662,2677,2689,2691,2693,2701,2703,2705,2707,2728,2730,2736,2738,2739,2741,2745,2748,2757,2759,2761,2763,2765,2768,2768,2784,2787,2790,2799,2817,2819,2821,2828,2831,2832,2835,2856,2858,2864,2866,2867,2869,2873,2876,2884,2887,2888,2891,2893,2902,2903,2908,2909,2911,2915,2918,2927,2929,2929,2946,2947,2949,2954,2958,2960,2962,2965,2969,2970,2972,2972,2974,2975,2979,2980,2984,2986,2990,3001,3006,3010,3014,3016,3018,3021,3024,3024,3031,3031,3046,3055,3073,3075,3077,3084,3086,3088,3090,3112,3114,3123,3125,3129,3133,3140,3142,3144,3146,3149,3157,3158,3160,3161,3168,3171,3174,3183,3202,3203,3205,3212,3214,3216,3218,3240,3242,3251,3253,3257,3260,3268,3270,3272,3274,3277,3285,3286,3294,3294,3296,3299,3302,3311,3313,3314,3330,3331,3333,3340,3342,3344,3346,3386,3389,3396,3398,3400,3402,3406,3415,3415,3424,3427,3430,3439,3450,3455,3458,3459,3461,3478,3482,3505,3507,3515,3517,3517,3520,3526,3530,3530,3535,3540,3542,3542,3544,3551,3570,3571,3585,3642,3648,3662,3664,3673,3713,3714,3716,3716,3719,3720,3722,3722,3725,3725,3732,3735,3737,3743,3745,3747,3749,3749,3751,3751,3754,3755,3757,3769,3771,3773,3776,3780,3782,3782,3784,3789,3792,3801,3804,3807,3840,3840,3864,3865,3872,3881,3893,3893,3895,3895,3897,3897,3902,3911,3913,3948,3953,3972,3974,3991,3993,4028,4038,4038,4096,4169,4176,4253,4256,4293,4295,4295,4301,4301,4304,4346,4348,4680,4682,4685,4688,4694,4696,4696,4698,4701,4704,4744,4746,4749,4752,4784,4786,4789,4792,4798,4800,4800,4802,4805,4808,4822,4824,4880,4882,4885,4888,4954,4957,4959,4992,5007,5024,5108,5121,5740,5743,5759,5761,5786,5792,5866,5870,5872,5888,5900,5902,5908,5920,5940,5952,5971,5984,5996,5998,6e3,6002,6003,6016,6099,6103,6103,6108,6109,6112,6121,6155,6157,6160,6169,6176,6263,6272,6314,6320,6389,6400,6428,6432,6443,6448,6459,6470,6509,6512,6516,6528,6571,6576,6601,6608,6617,6656,6683,6688,6750,6752,6780,6783,6793,6800,6809,6823,6823,6912,6987,6992,7001,7019,7027,7040,7155,7168,7223,7232,7241,7245,7293,7376,7378,7380,7414,7424,7654,7676,7957,7960,7965,7968,8005,8008,8013,8016,8023,8025,8025,8027,8027,8029,8029,8031,8061,8064,8116,8118,8124,8126,8126,8130,8132,8134,8140,8144,8147,8150,8155,8160,8172,8178,8180,8182,8188,8204,8205,8255,8256,8276,8276,8305,8305,8319,8319,8336,8348,8400,8412,8417,8417,8421,8432,8450,8450,8455,8455,8458,8467,8469,8469,8473,8477,8484,8484,8486,8486,8488,8488,8490,8493,8495,8505,8508,8511,8517,8521,8526,8526,8544,8584,11264,11310,11312,11358,11360,11492,11499,11507,11520,11557,11559,11559,11565,11565,11568,11623,11631,11631,11647,11670,11680,11686,11688,11694,11696,11702,11704,11710,11712,11718,11720,11726,11728,11734,11736,11742,11744,11775,11823,11823,12293,12295,12321,12335,12337,12341,12344,12348,12353,12438,12441,12442,12445,12447,12449,12538,12540,12543,12549,12589,12593,12686,12704,12730,12784,12799,13312,19893,19968,40908,40960,42124,42192,42237,42240,42508,42512,42539,42560,42607,42612,42621,42623,42647,42655,42737,42775,42783,42786,42888,42891,42894,42896,42899,42912,42922,43e3,43047,43072,43123,43136,43204,43216,43225,43232,43255,43259,43259,43264,43309,43312,43347,43360,43388,43392,43456,43471,43481,43520,43574,43584,43597,43600,43609,43616,43638,43642,43643,43648,43714,43739,43741,43744,43759,43762,43766,43777,43782,43785,43790,43793,43798,43808,43814,43816,43822,43968,44010,44012,44013,44016,44025,44032,55203,55216,55238,55243,55291,63744,64109,64112,64217,64256,64262,64275,64279,64285,64296,64298,64310,64312,64316,64318,64318,64320,64321,64323,64324,64326,64433,64467,64829,64848,64911,64914,64967,65008,65019,65024,65039,65056,65062,65075,65076,65101,65103,65136,65140,65142,65276,65296,65305,65313,65338,65343,65343,65345,65370,65382,65470,65474,65479,65482,65487,65490,65495,65498,65500],r=[170,170,181,181,186,186,192,214,216,246,248,543,546,563,592,685,688,696,699,705,720,721,736,740,750,750,890,890,902,902,904,906,908,908,910,929,931,974,976,983,986,1011,1024,1153,1164,1220,1223,1224,1227,1228,1232,1269,1272,1273,1329,1366,1369,1369,1377,1415,1488,1514,1520,1522,1569,1594,1600,1610,1649,1747,1749,1749,1765,1766,1786,1788,1808,1808,1810,1836,1920,1957,2309,2361,2365,2365,2384,2384,2392,2401,2437,2444,2447,2448,2451,2472,2474,2480,2482,2482,2486,2489,2524,2525,2527,2529,2544,2545,2565,2570,2575,2576,2579,2600,2602,2608,2610,2611,2613,2614,2616,2617,2649,2652,2654,2654,2674,2676,2693,2699,2701,2701,2703,2705,2707,2728,2730,2736,2738,2739,2741,2745,2749,2749,2768,2768,2784,2784,2821,2828,2831,2832,2835,2856,2858,2864,2866,2867,2870,2873,2877,2877,2908,2909,2911,2913,2949,2954,2958,2960,2962,2965,2969,2970,2972,2972,2974,2975,2979,2980,2984,2986,2990,2997,2999,3001,3077,3084,3086,3088,3090,3112,3114,3123,3125,3129,3168,3169,3205,3212,3214,3216,3218,3240,3242,3251,3253,3257,3294,3294,3296,3297,3333,3340,3342,3344,3346,3368,3370,3385,3424,3425,3461,3478,3482,3505,3507,3515,3517,3517,3520,3526,3585,3632,3634,3635,3648,3654,3713,3714,3716,3716,3719,3720,3722,3722,3725,3725,3732,3735,3737,3743,3745,3747,3749,3749,3751,3751,3754,3755,3757,3760,3762,3763,3773,3773,3776,3780,3782,3782,3804,3805,3840,3840,3904,3911,3913,3946,3976,3979,4096,4129,4131,4135,4137,4138,4176,4181,4256,4293,4304,4342,4352,4441,4447,4514,4520,4601,4608,4614,4616,4678,4680,4680,4682,4685,4688,4694,4696,4696,4698,4701,4704,4742,4744,4744,4746,4749,4752,4782,4784,4784,4786,4789,4792,4798,4800,4800,4802,4805,4808,4814,4816,4822,4824,4846,4848,4878,4880,4880,4882,4885,4888,4894,4896,4934,4936,4954,5024,5108,5121,5740,5743,5750,5761,5786,5792,5866,6016,6067,6176,6263,6272,6312,7680,7835,7840,7929,7936,7957,7960,7965,7968,8005,8008,8013,8016,8023,8025,8025,8027,8027,8029,8029,8031,8061,8064,8116,8118,8124,8126,8126,8130,8132,8134,8140,8144,8147,8150,8155,8160,8172,8178,8180,8182,8188,8319,8319,8450,8450,8455,8455,8458,8467,8469,8469,8473,8477,8484,8484,8486,8486,8488,8488,8490,8493,8495,8497,8499,8505,8544,8579,12293,12295,12321,12329,12337,12341,12344,12346,12353,12436,12445,12446,12449,12538,12540,12542,12549,12588,12593,12686,12704,12727,13312,19893,19968,40869,40960,42124,44032,55203,63744,64045,64256,64262,64275,64279,64285,64285,64287,64296,64298,64310,64312,64316,64318,64318,64320,64321,64323,64324,64326,64433,64467,64829,64848,64911,64914,64967,65008,65019,65136,65138,65140,65140,65142,65276,65313,65338,65345,65370,65382,65470,65474,65479,65482,65487,65490,65495,65498,65500],o=[170,170,181,181,186,186,192,214,216,246,248,543,546,563,592,685,688,696,699,705,720,721,736,740,750,750,768,846,864,866,890,890,902,902,904,906,908,908,910,929,931,974,976,983,986,1011,1024,1153,1155,1158,1164,1220,1223,1224,1227,1228,1232,1269,1272,1273,1329,1366,1369,1369,1377,1415,1425,1441,1443,1465,1467,1469,1471,1471,1473,1474,1476,1476,1488,1514,1520,1522,1569,1594,1600,1621,1632,1641,1648,1747,1749,1756,1759,1768,1770,1773,1776,1788,1808,1836,1840,1866,1920,1968,2305,2307,2309,2361,2364,2381,2384,2388,2392,2403,2406,2415,2433,2435,2437,2444,2447,2448,2451,2472,2474,2480,2482,2482,2486,2489,2492,2492,2494,2500,2503,2504,2507,2509,2519,2519,2524,2525,2527,2531,2534,2545,2562,2562,2565,2570,2575,2576,2579,2600,2602,2608,2610,2611,2613,2614,2616,2617,2620,2620,2622,2626,2631,2632,2635,2637,2649,2652,2654,2654,2662,2676,2689,2691,2693,2699,2701,2701,2703,2705,2707,2728,2730,2736,2738,2739,2741,2745,2748,2757,2759,2761,2763,2765,2768,2768,2784,2784,2790,2799,2817,2819,2821,2828,2831,2832,2835,2856,2858,2864,2866,2867,2870,2873,2876,2883,2887,2888,2891,2893,2902,2903,2908,2909,2911,2913,2918,2927,2946,2947,2949,2954,2958,2960,2962,2965,2969,2970,2972,2972,2974,2975,2979,2980,2984,2986,2990,2997,2999,3001,3006,3010,3014,3016,3018,3021,3031,3031,3047,3055,3073,3075,3077,3084,3086,3088,3090,3112,3114,3123,3125,3129,3134,3140,3142,3144,3146,3149,3157,3158,3168,3169,3174,3183,3202,3203,3205,3212,3214,3216,3218,3240,3242,3251,3253,3257,3262,3268,3270,3272,3274,3277,3285,3286,3294,3294,3296,3297,3302,3311,3330,3331,3333,3340,3342,3344,3346,3368,3370,3385,3390,3395,3398,3400,3402,3405,3415,3415,3424,3425,3430,3439,3458,3459,3461,3478,3482,3505,3507,3515,3517,3517,3520,3526,3530,3530,3535,3540,3542,3542,3544,3551,3570,3571,3585,3642,3648,3662,3664,3673,3713,3714,3716,3716,3719,3720,3722,3722,3725,3725,3732,3735,3737,3743,3745,3747,3749,3749,3751,3751,3754,3755,3757,3769,3771,3773,3776,3780,3782,3782,3784,3789,3792,3801,3804,3805,3840,3840,3864,3865,3872,3881,3893,3893,3895,3895,3897,3897,3902,3911,3913,3946,3953,3972,3974,3979,3984,3991,3993,4028,4038,4038,4096,4129,4131,4135,4137,4138,4140,4146,4150,4153,4160,4169,4176,4185,4256,4293,4304,4342,4352,4441,4447,4514,4520,4601,4608,4614,4616,4678,4680,4680,4682,4685,4688,4694,4696,4696,4698,4701,4704,4742,4744,4744,4746,4749,4752,4782,4784,4784,4786,4789,4792,4798,4800,4800,4802,4805,4808,4814,4816,4822,4824,4846,4848,4878,4880,4880,4882,4885,4888,4894,4896,4934,4936,4954,4969,4977,5024,5108,5121,5740,5743,5750,5761,5786,5792,5866,6016,6099,6112,6121,6160,6169,6176,6263,6272,6313,7680,7835,7840,7929,7936,7957,7960,7965,7968,8005,8008,8013,8016,8023,8025,8025,8027,8027,8029,8029,8031,8061,8064,8116,8118,8124,8126,8126,8130,8132,8134,8140,8144,8147,8150,8155,8160,8172,8178,8180,8182,8188,8255,8256,8319,8319,8400,8412,8417,8417,8450,8450,8455,8455,8458,8467,8469,8469,8473,8477,8484,8484,8486,8486,8488,8488,8490,8493,8495,8497,8499,8505,8544,8579,12293,12295,12321,12335,12337,12341,12344,12346,12353,12436,12441,12442,12445,12446,12449,12542,12549,12588,12593,12686,12704,12727,13312,19893,19968,40869,40960,42124,44032,55203,63744,64045,64256,64262,64275,64279,64285,64296,64298,64310,64312,64316,64318,64318,64320,64321,64323,64324,64326,64433,64467,64829,64848,64911,64914,64967,65008,65019,65056,65059,65075,65076,65101,65103,65136,65138,65140,65140,65142,65276,65296,65305,65313,65338,65343,65343,65345,65370,65381,65470,65474,65479,65482,65487,65490,65495,65498,65500];function a(e,t){return t>=n.ES5?l(e,i):l(e,r)}function l(e,t){if(e<t[0])return!1;let n,i=0,s=t.length;for(;i+1<s;){if(n=i+(s-i)/2,n-=n%2,t[n]<=e&&e<=t[n+1])return!0;e<t[n]?s=n:i=n+2}return!1}let c;t.isUnicodeIdentifierStart=a,function(e){e[e.Warning=0]="Warning",e[e.Error=1]="Error",e[e.Message=2]="Message"}(c=t.DiagnosticCategory||(t.DiagnosticCategory={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){function n(){return!!navigator&&!!navigator.bluetooth&&"TextDecoder"in window&&e.appTarget.appTheme.bluetoothUartConsole&&e.appTarget.appTheme.bluetoothUartFilters&&e.appTarget.appTheme.bluetoothUartFilters.length>0}function i(){return!!navigator&&!!navigator.bluetooth&&!!e.appTarget.appTheme.bluetoothPartialFlashing}t.isAvailable=function(){return n()||i()},t.hasConsole=n,t.hasPartialFlash=i,t.isValidUUID=function(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(e)};class s{constructor(e,t){this.connectionTimeout=2e4,this.connectPromise=void 0,this.id=e,this.aliveToken=t}debug(t){e.debug(`${this.id}: ${t}`)}alivePromise(e){return new Promise(((t,n)=>{this.aliveToken.isCancelled()&&n(new Error),e.then((e=>t(e)),(e=>n(e)))}))}cancelConnect(){this.connectPromise=void 0}createConnectPromise(){return Promise.resolve()}connectAsync(){return this.connectPromise||(this.connectPromise=this.alivePromise(this.createConnectPromise())),e.Util.promiseTimeout(this.connectionTimeout,this.connectPromise,"connection timeout").then((()=>this.aliveToken.throwIfCancelled())).catch((e=>{throw this.connectPromise=void 0,e}))}disconnect(){this.cancelConnect()}kill(){this.disconnect(),this.aliveToken.cancel()}}t.BLERemote=s;class r extends s{constructor(e,t,n){super(e,t.aliveToken),this.device=t,this.autoReconnect=n,this.autoReconnectDelay=1e3,this.disconnectOnAutoReconnect=!1,this.reconnectPromise=void 0,this.failedConnectionServicesVersion=-1,this.handleDisconnected=this.handleDisconnected.bind(this),this.device.device.addEventListener("gattserverdisconnected",this.handleDisconnected)}handleDisconnected(t){this.aliveToken.isCancelled()||(this.disconnect(),this.autoReconnect&&!this.reconnectPromise&&(this.reconnectPromise=e.U.delay(this.autoReconnectDelay).then((()=>this.exponentialBackoffConnectAsync(8,500))).finally((()=>this.reconnectPromise=void 0))))}exponentialBackoffConnectAsync(t,n){return this.debug("retry connect"),this.aliveToken.throwIfCancelled(),this.connectAsync().then((()=>{this.aliveToken.throwIfCancelled(),this.debug("reconnect success"),this.reconnectPromise=void 0})).catch((i=>(this.debug(`reconnect error ${i.message}`),this.aliveToken.throwIfCancelled(),this.device.isPaired?this.autoReconnect?0==t?(this.debug("give up, max tries"),void(this.reconnectPromise=void 0)):this.failedConnectionServicesVersion==this.device.servicesVersion?(this.debug("services haven't changed, giving up"),void(this.reconnectPromise=void 0)):(this.debug(`retry connect ${n}ms... (${t} tries left)`),this.device.connected&&(this.failedConnectionServicesVersion=this.device.servicesVersion),this.disconnectOnAutoReconnect&&this.device.disconnect(),e.U.delay(n).then((()=>this.exponentialBackoffConnectAsync(--t,1.8*n)))):(this.debug("autoreconnect disabled"),void(this.reconnectPromise=void 0)):(this.debug("give up, device unpaired"),void(this.reconnectPromise=void 0)))))}}t.BLEService=r;class o extends r{constructor(e,t,n,i){super(e,t,!0),this.device=t,this.serviceUUID=n,this.txCharacteristicUUID=i,this.handleValueChanged=this.handleValueChanged.bind(this)}createConnectPromise(){return this.debug("connecting"),this.device.connectAsync().then((()=>this.alivePromise(this.device.gatt.getPrimaryService(this.serviceUUID)))).then((e=>(this.debug("service connected"),this.service=e,this.alivePromise(this.service.getCharacteristic(this.txCharacteristicUUID))))).then((e=>(this.debug("tx characteristic connected"),this.txCharacteristic=e,this.txCharacteristic.addEventListener("characteristicvaluechanged",this.handleValueChanged),this.txCharacteristic.startNotifications()))).then((()=>{e.tickEvent("webble.connected",{id:this.id})}))}handlePacket(e){}handleValueChanged(e){const t=e.target.value;this.handlePacket(t)}disconnect(){if(super.disconnect(),this.txCharacteristic&&this.device&&this.device.connected)try{this.txCharacteristic.stopNotifications(),this.txCharacteristic.removeEventListener("characteristicvaluechanged",this.handleValueChanged)}catch(t){e.log(`${this.id}: error ${t.message}`)}this.service=void 0,this.txCharacteristic=void 0}}t.BLETXService=o;class a extends o{constructor(e){super("hf2",e,a.SERVICE_UUID,a.CHARACTERISTIC_TX_UUID),this.device=e}handlePacket(e){const t=e.getUint8(0);switch(192&t){case a.BLEHF2_FLAG_SERIAL_OUT:case a.BLEHF2_FLAG_SERIAL_ERR:const n=Math.min(e.byteLength-1,-193&t);let i="";for(let t=0;t<n;++t)i+=String.fromCharCode(e.getUint8(t+1));i&&window.postMessage({type:"serial",id:this.device.name||"hf2",data:i},"*")}}}a.SERVICE_UUID="b112f5e6-2679-30da-a26e-0273b6043849",a.CHARACTERISTIC_TX_UUID="b112f5e6-2679-30da-a26e-0273b604384a",a.BLEHF2_FLAG_SERIAL_OUT=128,a.BLEHF2_FLAG_SERIAL_ERR=192,t.HF2Service=a;class l extends o{constructor(e){super("uart",e,l.SERVICE_UUID,l.CHARACTERISTIC_TX_UUID),this.device=e}handlePacket(e){const t=(new window.TextDecoder).decode(e);t&&window.postMessage({type:"serial",id:this.device.name||"uart",data:t},"*")}}let c;l.SERVICE_UUID="6e400001-b5a3-f393-e0a9-e50e24dcca9e",l.CHARACTERISTIC_TX_UUID="6e400002-b5a3-f393-e0a9-e50e24dcca9e",t.UARTService=l,function(e){e[e.Idle=1]="Idle",e[e.StatusRequested=2]="StatusRequested",e[e.PairingModeRequested=4]="PairingModeRequested",e[e.RegionDALRequested=8]="RegionDALRequested",e[e.RegionMakeCodeRequested=16]="RegionMakeCodeRequested",e[e.Flash=32]="Flash",e[e.EndOfTransmision=64]="EndOfTransmision",e[e.USBFlashRequired=128]="USBFlashRequired"}(c||(c={}));class u extends r{constructor(e){super("partial flashing",e,!1),this.device=e,this.state=c.Idle,this.disconnectOnAutoReconnect=!0,this.handleCharacteristic=this.handleCharacteristic.bind(this)}clearFlashData(){this.version=0,this.mode=0,this.regions=[],this.chunkDelay=u.CHUNK_MIN_DELAY,this.hex=void 0,this.bin=void 0,this.magicOffset=void 0,this.dalHash=void 0,this.makeCodeHash=void 0,this.flashReject=void 0,this.flashResolve=void 0,this.flashOffset=void 0}createConnectPromise(){return this.debug("connecting to partial flash service"),this.device.connectAsync().then((()=>this.alivePromise(this.device.gatt.getPrimaryService(u.SERVICE_UUID)))).then((e=>(this.debug("connecting to characteristic"),this.alivePromise(e.getCharacteristic(u.CHARACTERISTIC_UUID))))).then((e=>(this.debug("starting notifications"),this.pfCharacteristic=e,this.pfCharacteristic.startNotifications(),this.pfCharacteristic.addEventListener("characteristicvaluechanged",this.handleCharacteristic),this.state==c.PairingModeRequested?(this.debug("checking pairing mode"),this.autoReconnect=!1,this.pfCharacteristic.writeValue(new Uint8Array([u.STATUS]))):Promise.resolve())))}disconnect(){if(super.disconnect(),this.flashPacketToken&&this.flashPacketToken.cancel(),this.pfCharacteristic&&this.device.connected)try{this.pfCharacteristic.stopNotifications(),this.pfCharacteristic.removeEventListener("characteristicvaluechanged",this.handleCharacteristic)}catch(t){e.log(`ble: partial flash disconnect error ${t.message}`)}this.pfCharacteristic=void 0}findMarker(e,t){if(!this.bin)return-1;for(;e+t.length<this.bin.length;e+=16){let n=!0;for(let i=0;i<t.length;++i)if(t[i]!=this.bin[e+i]){n=!1;break}if(n)return e}return-1}flashAsync(e){return this.hex?(this.debug("flashing already in progress"),Promise.resolve()):(this.device.pauseLog(),this.createFlashPromise(e).finally((()=>this.device.resumeLogOnDisconnection())))}createFlashPromise(t){if(this.hex)return this.debug("flashing already in progress"),Promise.resolve();this.clearFlashData(),this.hex=t;const n=ts.pxtc.UF2.newBlockFile();ts.pxtc.UF2.writeHex(n,this.hex.split(/\r?\n/));const i=e.appTarget.compile.flashUsableEnd;this.bin=ts.pxtc.UF2.toBin(e.U.stringToUint8Array(ts.pxtc.UF2.serializeFile(n)),i).buf,this.debug(`bin bytes ${this.bin.length}`),this.magicOffset=this.findMarker(0,u.MAGIC_MARKER),this.debug(`magic block ${this.magicOffset.toString(16)}`),this.magicOffset<0&&(this.debug("magic block not found, not a valid HEX file"),e.U.userError(lf("Invalid file"))),this.debug("bytes to flash "+(this.bin.length-this.magicOffset));const s=this.magicOffset+u.MAGIC_MARKER.length;return this.dalHash=e.Util.toHex(this.bin.slice(s,s+8)),this.makeCodeHash=e.Util.toHex(this.bin.slice(s+8,s+16)),this.debug(`DAL hash ${this.dalHash}`),this.debug(`MakeCode hash ${this.makeCodeHash}`),this.connectAsync().then((()=>new Promise(((e,t)=>(this.flashResolve=e,this.flashReject=t,this.debug("check service version"),this.state=c.StatusRequested,this.pfCharacteristic.writeValue(new Uint8Array([u.STATUS]))))))).then((()=>{}),(t=>{e.log(`pf: error ${t.message}`),this.clearFlashData()}))}checkStateTransition(e,t){return!!(this.state&t)||(this.debug(`flash cmd ${e} in state ${this.state.toString(16)} `),this.flashReject(new Error),this.clearFlashData(),!1)}handleCharacteristic(t){this.aliveToken.isCancelled()&&(this.flashReject(new Error),this.clearFlashData());const n=event.target.value,i=new Uint8Array(n.buffer),s=i[0];if(this.state!=c.Idle)switch(s){case u.STATUS:if(!this.checkStateTransition(s,c.StatusRequested|c.PairingModeRequested))return;this.version=i[1],this.mode=i[2],this.debug(`flash service version ${this.version} mode ${this.mode}`),this.debug("reading DAL region"),this.state=c.RegionDALRequested,this.pfCharacteristic.writeValue(new Uint8Array([u.REGION_INFO,u.REGION_DAL])).then((()=>{}));break;case u.REGION_INFO:if(!this.checkStateTransition(s,c.RegionDALRequested|c.RegionMakeCodeRequested))return;const t=this.regions[i[1]]={start:i[2]<<24|i[3]<<16|i[4]<<8|i[5],end:i[6]<<24|i[7]<<16|i[8]<<8|i[9],hash:e.Util.toHex(i.slice(10))};if(this.debug(`read region ${i[1]} start ${t.start.toString(16)} end ${t.end.toString(16)} hash ${t.hash}`),i[1]==u.REGION_DAL){if(t.hash!=this.dalHash)return e.tickEvent("webble.flash.DALrequired"),this.debug("DAL hash does not match, partial flashing not possible"),this.state=c.USBFlashRequired,this.flashReject(new Error("USB flashing required")),void this.clearFlashData();this.debug("DAL hash match, reading makecode region"),this.state=c.RegionMakeCodeRequested,this.pfCharacteristic.writeValue(new Uint8Array([u.REGION_INFO,u.REGION_MAKECODE])).then((()=>{}))}else if(i[1]==u.REGION_MAKECODE)if(t.start!=this.magicOffset&&(this.debug("magic offset and MakeCode region.start not matching"),e.U.userError(lf("Invalid file"))),t.hash==this.makeCodeHash)e.tickEvent("webble.flash.noop"),this.debug("MakeCode hash matches, same code!"),this.debug("restart application mode"),this.pfCharacteristic.writeValue(new Uint8Array([u.RESET,u.MODE_APPLICATION])).then((()=>{this.state=c.Idle,this.flashResolve(),this.clearFlashData()}));else{if(this.mode!=u.MODE_PAIRING)return this.debug("application mode, reset into pairing mode"),this.state=c.PairingModeRequested,this.autoReconnect=!0,void this.pfCharacteristic.writeValue(new Uint8Array([u.RESET,u.MODE_PAIRING])).then((()=>{}));this.flashOffset=t.start,this.flashPacketNumber=0,this.debug(`starting to flash from address ${this.flashOffset.toString(16)}`),this.flashNextPacket()}break;case u.FLASH_DATA:if(!this.checkStateTransition(s,c.Flash))return;switch(i[1]){case u.PACKET_OUT_OF_ORDER:this.debug("packet out of order"),this.flashPacketToken.cancel(),this.flashPacketNumber+=4,this.chunkDelay=Math.min(this.chunkDelay+10,u.CHUNK_MAX_DELAY),this.flashNextPacket();break;case u.PACKET_WRITTEN:this.chunkDelay=Math.max(this.chunkDelay-1,u.CHUNK_MIN_DELAY),this.flashOffset+=64,this.flashPacketNumber+=4,this.flashOffset>=this.bin.length?(this.debug("end transmission"),this.state=c.EndOfTransmision,this.pfCharacteristic.writeValue(new Uint8Array([u.END_OF_TRANSMISSION])).finally((()=>{this.flashResolve&&this.flashResolve(),this.clearFlashData()}))):this.flashNextPacket()}break;default:this.debug(`unknown message ${e.Util.toHex(i)}`),this.disconnect()}}flashNextPacket(){this.state=c.Flash,this.flashPacketToken=new e.Util.CancellationToken,this.flashPacketToken.startOperation();const t=this.bin.slice(this.flashOffset,this.flashOffset+64);this.debug(`flashing ${this.flashOffset.toString(16)} / ${this.bin.length.toString(16)} ${(this.flashOffset-this.magicOffset)/(this.bin.length-this.magicOffset)*100>>0}%`);let n=new Uint8Array(20);e.U.delay(this.chunkDelay).then((()=>{this.flashPacketToken.throwIfCancelled(),n[0]=u.FLASH_DATA,n[1]=this.flashOffset>>8&255,n[2]=this.flashOffset>>0&255,n[3]=this.flashPacketNumber;for(let e=0;e<16;e++)n[4+e]=t[e];return this.pfCharacteristic.writeValue(n)})).then((()=>e.U.delay(this.chunkDelay))).then((()=>{this.flashPacketToken.throwIfCancelled(),n[0]=u.FLASH_DATA,n[1]=this.flashOffset>>24&255,n[2]=this.flashOffset>>16&255,n[3]=this.flashPacketNumber+1;for(let e=0;e<16;e++)n[4+e]=t[16+e]||0;return this.pfCharacteristic.writeValue(n)})).then((()=>e.U.delay(this.chunkDelay))).then((()=>{this.flashPacketToken.throwIfCancelled(),n[0]=u.FLASH_DATA,n[1]=0,n[2]=0,n[3]=this.flashPacketNumber+2;for(let e=0;e<16;e++)n[4+e]=t[32+e]||0;return this.pfCharacteristic.writeValue(n)})).then((()=>e.U.delay(this.chunkDelay))).then((()=>{this.flashPacketToken.throwIfCancelled(),n[0]=u.FLASH_DATA,n[1]=0,n[2]=0,n[3]=this.flashPacketNumber+3;for(let e=0;e<16;e++)n[4+e]=t[48+e]||0;return this.pfCharacteristic.writeValue(n)})).then((()=>{const t=this.flashOffset,i=()=>e.U.delay(500).then((()=>{if(t!=this.flashOffset||this.flashPacketToken.isCancelled()||this.aliveToken.isCancelled()||this.state!=c.Flash)return Promise.resolve();this.debug("packet transfer deadlock, force restart"),n[0]=u.FLASH_DATA,n[1]=0,n[2]=0,n[3]=-1;for(let e=0;e<16;e++)n[4+e]=0;return this.pfCharacteristic.writeValue(n).then((()=>i()))}));i().catch((e=>{this.flashReject&&(this.flashReject(new Error("failed packet transfer")),this.clearFlashData())}))})).catch((()=>{this.flashPacketToken.resolveCancel()}))}}u.SERVICE_UUID="e97dd91d-251d-470a-a062-fa1922dfa9a8",u.CHARACTERISTIC_UUID="e97d3b10-251d-470a-a062-fa1922dfa9a8",u.REGION_INFO=0,u.FLASH_DATA=1,u.PACKET_OUT_OF_ORDER=170,u.PACKET_WRITTEN=255,u.END_OF_TRANSMISSION=2,u.STATUS=238,u.RESET=255,u.MODE_PAIRING=0,u.MODE_APPLICATION=1,u.REGION_SOFTDEVICE=0,u.REGION_DAL=1,u.REGION_MAKECODE=2,u.MAGIC_MARKER=e.Util.fromHex("708E3B92C615A841C49866C975EE5197"),u.CHUNK_MIN_DELAY=0,u.CHUNK_MAX_DELAY=75,t.PartialFlashingService=u;class d extends s{constructor(t){super("ble",new e.Util.CancellationToken),this.device=void 0,this.services=[],this.pendingResumeLogOnDisconnection=!1,this.servicesVersion=0,this.device=t,this.handleDisconnected=this.handleDisconnected.bind(this),this.handleServiceAdded=this.handleServiceAdded.bind(this),this.handleServiceChanged=this.handleServiceChanged.bind(this),this.handleServiceRemoved=this.handleServiceRemoved.bind(this),this.device.addEventListener("gattserverdisconnected",this.handleDisconnected),this.device.addEventListener("serviceadded",this.handleServiceAdded),this.device.addEventListener("servicechanged",this.handleServiceChanged),this.device.addEventListener("serviceremoved",this.handleServiceRemoved),n()&&(this.services.push(this.uartService=new l(this)),this.services.push(this.hf2Service=new a(this))),i()&&this.services.push(this.partialFlashingService=new u(this)),this.aliveToken.startOperation()}startServices(){this.services.filter((e=>e.autoReconnect)).forEach((e=>e.connectAsync().catch((()=>{}))))}pauseLog(){this.uartService&&(this.uartService.autoReconnect=!1,this.uartService.disconnect()),this.hf2Service&&(this.hf2Service.autoReconnect=!1,this.hf2Service.disconnect())}resumeLogOnDisconnection(){this.pendingResumeLogOnDisconnection=!0}resumeLog(){this.uartService&&(this.uartService.autoReconnect=!0,this.uartService.connectAsync().catch((()=>{}))),this.hf2Service&&(this.hf2Service.autoReconnect=!0,this.hf2Service.connectAsync().catch((()=>{})))}get isPaired(){return this===t.bleDevice}get name(){return this.device.name||"?"}get connected(){return this.device&&this.device.gatt&&this.device.gatt.connected}get gatt(){return this.device.gatt}createConnectPromise(){return this.debug("connecting gatt server"),this.alivePromise(this.device.gatt.connect().then((()=>this.debug("gatt server connected"))))}handleServiceAdded(e){this.debug("service added"),this.servicesVersion++}handleServiceRemoved(e){this.debug("service removed"),this.servicesVersion++}handleServiceChanged(e){this.debug("service changed"),this.servicesVersion++}handleDisconnected(t){this.debug("disconnected"),this.disconnect(),this.pendingResumeLogOnDisconnection&&(this.pendingResumeLogOnDisconnection=!1,e.U.delay(500).then((()=>this.resumeLog())))}disconnect(){if(super.disconnect(),this.services.forEach((e=>e.disconnect())),this.connected){this.debug("disconnect");try{this.device.gatt&&this.device.gatt.connected&&this.device.gatt.disconnect()}catch(e){this.debug(`gatt disconnect error ${e.message}`)}}}}function h(){if(t.bleDevice)return Promise.resolve();e.log("ble: requesting device");const s=[];return n()&&(s.push(l.SERVICE_UUID),s.push(a.SERVICE_UUID)),i()&&s.push(u.SERVICE_UUID),navigator.bluetooth.requestDevice({filters:e.appTarget.appTheme.bluetoothUartFilters,optionalServices:s}).then((n=>(e.log(`ble: received device ${n.name}`),t.bleDevice=new d(n),t.bleDevice.startServices(),t.bleDevice.connectAsync())))}t.BLEDevice=d,t.bleDevice=void 0,t.isPaired=function(){return!!t.bleDevice},t.pairAsync=function(){return t.bleDevice&&(t.bleDevice.kill(),t.bleDevice=void 0),h().catch((n=>{t.bleDevice&&t.bleDevice.aliveToken&&t.bleDevice.aliveToken.resolveCancel(),e.log(`ble: error ${n.message}`)}))},t.flashAsync=function(n,i){e.tickEvent("webble.flash");const s=n.outfiles[ts.pxtc.BINARY_HEX];return h().then((()=>t.bleDevice.partialFlashingService.flashAsync(s))).then((()=>e.tickEvent("webble.flash.success"))).catch((t=>{throw e.tickEvent("webble.fail.fail",{message:t.message}),t}))}}(e.webBluetooth||(e.webBluetooth={}))}(pxt||(pxt={})),function(e){!function(t){class n extends Error{constructor(e){super(e),this.message=e}}t.USBError=n;t.filters=[{classCode:255,subclassCode:42}];let i,s,r=!0;t.setFilters=function(e){r=!1,t.filters=e};class o{constructor(){this.ready=!1,this.connecting=!1,this.readLoopStarted=!1,this.onDeviceConnectionChanged=e=>{},this.onConnectionChanged=()=>{},this.onData=e=>{},this.onError=e=>{},this.onEvent=e=>{},this.enabled=!1,this.handleUSBConnected=this.handleUSBConnected.bind(this),this.handleUSBDisconnected=this.handleUSBDisconnected.bind(this)}enable(){var e,t;this.enabled||(this.enabled=!0,this.log("registering webusb events"),null===(e=navigator.usb)||void 0===e||e.addEventListener("disconnect",this.handleUSBDisconnected,!1),null===(t=navigator.usb)||void 0===t||t.addEventListener("connect",this.handleUSBConnected,!1))}disable(){var e,t;this.enabled&&(this.enabled=!1,this.log("unregistering webusb events"),null===(e=navigator.usb)||void 0===e||e.removeEventListener("disconnect",this.handleUSBDisconnected),null===(t=navigator.usb)||void 0===t||t.removeEventListener("connect",this.handleUSBConnected))}async disposeAsync(){this.disable()}handleUSBDisconnected(e){var t;this.log("device disconnected"),e.device==this.dev&&(this.log("clear device"),this.clearDev(),null===(t=this.onDeviceConnectionChanged)||void 0===t||t.call(this,!1))}handleUSBConnected(e){var t;const n=e.device;this.log(`device connected ${n.serialNumber}`),this.dev||this.connecting||(this.log("attach device"),null===(t=this.onDeviceConnectionChanged)||void 0===t||t.call(this,!0))}clearDev(){var e;this.dev&&(this.dev=null,this.epIn=null,this.epOut=null,null===(e=this.onConnectionChanged)||void 0===e||e.call(this))}error(t){throw new n(e.U.lf("USB error on device {0} ({1})",this.dev.productName,t))}log(t){e.debug("webusb: "+t)}async disconnectAsync(){if(this.ready=!1,this.dev){this.log("close device");try{await this.dev.close()}catch(e){}this.clearDev(),await e.U.delay(500)}}async forgetAsync(){var e;if(!(null===(e=this.dev)||void 0===e?void 0:e.forget))return!1;try{const e=this.dev;return await this.disconnectAsync(),await e.forget(),!0}catch(e){return!1}}async reconnectAsync(){this.log("reconnect"),this.setConnecting(!0);try{await this.disconnectAsync();const e=await a();await this.connectAsync(e)}finally{this.setConnecting(!1)}}setConnecting(e){var t;e!=this.connecting&&(this.connecting=e,null===(t=this.onConnectionChanged)||void 0===t||t.call(this))}isConnecting(){return this.connecting}isConnected(){return!!this.dev&&this.ready}async connectAsync(t){if(this.log(`trying to connect (${t.length} devices)`),0==t.length){const e=new Error("Device not found.");throw e.type="devicenotfound",e}this.setConnecting(!0);try{if(this.lastKnownDeviceSerialNumber){const n=t.find((e=>e.serialNumber===this.lastKnownDeviceSerialNumber));n?(this.log("last known device spotted"),t.splice(t.indexOf(n),1),t.unshift(n)):(this.log("delay for last known device"),await e.U.delay(2e3))}for(let e=0;e<t.length;++e){const n=t[e];this.dev=n,this.log(`connect device: ${n.manufacturerName} ${n.productName}`),this.log(`serial number: ${n.serialNumber} ${this.lastKnownDeviceSerialNumber===n.serialNumber?"(last known device)":""} `);try{return void await this.initAsync()}catch(e){this.dev=void 0,this.log(`connection failed, ${e.message}`)}}const n=new Error(e.U.lf("Device in use or not found."));throw n.type="devicelocked",n}finally{this.setConnecting(!1)}}async sendPacketAsync(t){if(!this.dev)throw new Error("Disconnected");if(e.Util.assert(t.length<=64),this.epOut){"ok"!=(await this.dev.transferOut(this.epOut.endpointNumber,t)).status&&this.error("USB OUT transfer failed")}else{"ok"!=(await this.dev.controlTransferOut({requestType:"class",recipient:"interface",request:9,value:512,index:this.iface.interfaceNumber},t)).status&&this.error("USB CTRL OUT transfer failed")}}async readLoop(){if(!this.readLoopStarted)for(this.readLoopStarted=!0,this.log("start read loop");;)if(this.ready)try{const t=await this.recvPacketAsync();t[0]?this.onData(t):await e.U.delay(500)}catch(t){this.dev&&this.onError(t),await e.U.delay(300)}else await e.U.delay(300)}async recvPacketAsync(e){const t=Date.now();for(;!e||Date.now()<t+e;){if(!this.dev)throw new Error("Disconnected");const e=await(this.epIn?this.dev.transferIn(this.epIn.endpointNumber,64):this.dev.controlTransferIn({requestType:"class",recipient:"interface",request:1,value:256,index:this.iface.interfaceNumber},64));"ok"!=e.status&&this.error("USB IN transfer failed");let t=new Uint8Array(e.data.buffer);if(0!=t.length)return t}this.error("USB IN timed out")}async initAsync(){var n;if(!this.dev)throw new Error("Disconnected");const i=this.dev;this.log("open device"),await i.open(),this.log("select configuration"),await i.selectConfiguration(1);this.log("got "+i.configurations[0].interfaces.length+" interfaces");const s=i.configurations[0].interfaces.filter((e=>{let n=e.alternates[0];for(let e of t.filters)if((null==e.classCode||n.interfaceClass===e.classCode)&&!(null!=e.subclassCode&&n.interfaceSubclass!==e.subclassCode||null!=e.protocolCode&&n.interfaceProtocol!==e.protocolCode)){if(0==n.endpoints.length)return!0;if(2==n.endpoints.length&&n.endpoints.every((e=>64==e.packetSize)))return!0}return!1}));let o=s[s.length-1];this.log(`${s.length} matching interfaces; picking ${o?"#"+o.interfaceNumber:"n/a"}`),o||this.error("cannot find supported USB interface"),this.altIface=o.alternates[0],this.iface=o,this.altIface.endpoints.length?(this.log("using dedicated endpoints"),this.epIn=this.altIface.endpoints.filter((e=>"in"==e.direction))[0],this.epOut=this.altIface.endpoints.filter((e=>"out"==e.direction))[0],e.Util.assert(64==this.epIn.packetSize),e.Util.assert(64==this.epOut.packetSize)):this.log("using ctrl pipe"),this.log("claim interface"),await i.claimInterface(o.interfaceNumber),this.log("device ready"),this.lastKnownDeviceSerialNumber=this.dev.serialNumber,this.ready=!0,r&&this.readLoop(),null===(n=this.onConnectionChanged)||void 0===n||n.call(this)}}async function a(){var t;e.log("webusb: get devices");try{return await(null===(t=navigator.usb)||void 0===t?void 0:t.getDevices())||[]}catch(t){return e.reportException(t),[]}}async function l(){var t,n;if(void 0!==s)return;if(e.debug("webusb: checking availability"),!(null===(n=null===(t=e.appTarget)||void 0===t?void 0:t.compile)||void 0===n?void 0:n.webUSB))return void(s=!1);const i=await c();if(i)switch(s=!1,e.tickEvent("webusb.off",{reason:i}),i){case"electron":e.debug("webusb: off, electron");break;case"notimpl":e.debug("webusb: off, not implemented by browser");break;case"oldwindows":e.debug("webusb: off, older windows version");break;case"security":e.debug("webusb: off, security exception")}else s=!0}async function c(){if(e.BrowserUtils.isElectron())return"electron";const t=navigator.usb;if(!t)return"notimpl";let n=/Windows NT (\d+\.\d+)/.exec(navigator.userAgent);if(n&&parseFloat(n[1])<6.3)return"oldwindows";try{await t.getDevices()}catch(e){return"security"}}function u(){return void 0===s&&(console.error("checkAvailableAsync not called"),l()),!!s}t.pairAsync=async function(){var e;try{return!!await(null===(e=navigator.usb)||void 0===e?void 0:e.requestDevice({filters:t.filters}))}catch(e){if("NotFoundError"==e.name)return;throw e}},t.tryGetDevicesAsync=a,t.mkWebUSBHIDPacketIOAsync=function(){return e.debug("packetio: mk webusb io"),i||(i=new o),i.enable(),Promise.resolve(i)},t.forgetDeviceAsync=async function(){return e.debug("packetio: forget webusb io"),!!i&&i.forgetAsync()},t.isEnabled=!1,t.setEnabled=function(e){u()||(e=!1),t.isEnabled=e},t.checkAvailableAsync=l,t.getReasonUnavailable=c,t.isAvailable=u}(e.usb||(e.usb={}))}(pxt||(pxt={})),function(e){!function(t){var n=e.Util;let i={};function s(e){let t={},i=0,s=new n.PromiseQueue,r=new Promise(((e,n)=>{t.ready=e}));s.enqueue("main",(()=>r));return{opAsync:function(n,r){return s.enqueue("main",(()=>new Promise(((s,o)=>{let a=""+i++;t[a]=e=>{e?e.errorMessage?o(new Error(e.errorMessage)):s(e):o(new Error("no response"))},e({id:a,op:n,arg:r})}))))},recvHandler:e=>{if(t.hasOwnProperty(e.id)){let n=t[e.id];delete t[e.id],n(e.result)}}}}function r(t){let n=new Worker(t),i=s((e=>n.postMessage(e)));return n.onmessage=t=>{e.perf.measureStart("webworker recvHandler"),i.recvHandler(t.data),e.perf.measureEnd("webworker recvHandler")},i}t.getWorker=function(e){let t=i[e];return t||(t=i[e]=r(e)),t},t.wrap=s,t.makeWebWorker=r,t.makeWebSocket=function(t,n=null){let i=new WebSocket(t),r=[],o=s((e=>{let t=JSON.stringify(e);r?r.push(t):i.send(t)}));return i.onmessage=e=>{let t=JSON.parse(e.data);n&&null==t.id?n(t):o.recvHandler(t)},i.onopen=t=>{e.debug("socket opened");for(let e of r)i.send(e);r=null},i.onclose=t=>{e.debug("socket closed")},i.onerror=t=>{e.debug("socket errored")},o}}(e.worker||(e.worker={}))}(pxt||(pxt={})),function(e){!function(t){function n(){t.apiKey||e.U.userError("YouTube API key missing")}function i(e){if(!e)return"";const t=e.medium||e.high||e.standard||e.default;return(null==t?void 0:t.url)||""}t.apiKey=void 0,t.playlistItemToCodeCard=function(e){return{name:e.snippet.title.replace(/[^-]*-/,"").trim(),description:(t=e.snippet.description,t.split(/\n\s+/,1)[0].trim()),youTubeId:e.snippet.resourceId.videoId,youTubePlaylistId:e.snippet.playlistId,imageUrl:i(e.snippet.thumbnails)};var t},t.playlistInfoAsync=function(i){n();const s=`https://www.googleapis.com/youtube/v3/playlists?part=snippet&id=${i}&key=${t.apiKey}`;return e.Util.httpGetJsonAsync(s).then((e=>e.items[0]))},t.listPlaylistVideosAsync=async function(i){n();let s,r=[];do{let n=`https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=${i}&key=${t.apiKey}`;s&&(n+=`&pageToken=${s}`);const o=await e.Util.httpGetJsonAsync(n);r=r.concat(o.items),s=o.nextPageToken}while(s);return e.options.debug&&e.debug(JSON.stringify(r,null,2)),r},t.watchUrl=function(e,t){let n;return e?(n=`https://www.youtube.com/watch?v=${e}`,t&&(n+=`&list=${t}`)):t&&(n=`https://www.youtube.com/playlist?list=${t}`),n}}(e.youtube||(e.youtube={}))}(pxt||(pxt={})),function(e){!function(e){!function(t){function n(e,...t){return e.replace(/{(\d+)}/g,((e,n)=>t[+n]))}t.debug=!1,t.lf=n;let i=u("opcode name doesn't match","<name>");class s{constructor(t,n,i,s,r){this.opcode=i,this.mask=s,this.is32bit=r,this.canBeShared=!1,e.assert((i&s)==i),this.ei=t,this.code=n.replace(/\s+/g," "),this.friendlyFmt=n.replace(/\$\w+/g,(e=>this.ei.encoders[e]?this.ei.encoders[e].pretty:e));let o=l(n);this.name=o[0],this.args=o.slice(1)}emit(t){let n=t.words;if(n[0]!=this.name)return i;let s=this.opcode,r=1,o=0,a=[],l=null,c=null,d=null;for(let i=0;i<this.args.length;++i){let h=this.args[i],p=n[r++];if("$"==h[0]){let i=this.ei.encoders[h],f=null;if(i.isRegister){if(f=this.ei.registerNo(p),null==f)return u("expecting register name",p);this.ei.isPush(this.opcode)?o++:this.ei.isPop(this.opcode)&&o--}else if(i.isImmediate){if(p=p.replace(/^#/,""),f=t.bin.parseOneInt(p),null==f)return u("expecting number",p);this.ei.isAddSP(this.opcode)?o=-f/this.ei.wordSize():this.ei.isSubSP(this.opcode)&&(o=f/this.ei.wordSize())}else if(i.isRegList){if("{"!=p)return u("expecting {",p);for(f=0;"}"!=n[r];){if(p=n[r++],!p)return u("expecting }",n[r-2]);let e=this.ei.registerNo(p);if(null==e)return u("expecting register name",p);if(f&1<<e)return u("duplicate register name",p);f|=1<<e,this.ei.isPush(this.opcode)?o++:this.ei.isPop(this.opcode)&&o--,","==n[r]&&r++}p=n[r++]}else if(i.isLabel){if(p=p.replace(/^#/,""),/^[+-]?\d+$/.test(p))f=parseInt(p,10),l="rel"+f;else if(/^0x[0-9a-fA-F]+$/.test(p))f=parseInt(p,16),l="abs"+f;else if(l=p,f=this.ei.getAddressFromLabel(t.bin,this,p,i.isWordAligned),null==f){if(t.bin.finalEmit)return u("unknown label",p);f=8}if(this.ei.is32bit(this)){c=f,d=p;continue}}else e.oops();if(null==f)return u("didn't understand it",p);if(a.push(f),f=i.encode(f),null==f)return u("argument out of range or mis-aligned",p);e.assert(0==(s&f)),s|=f}else if(h!=p)return u("expecting "+h,p)}return n[r]?u("trailing tokens",n[r]):this.ei.is32bit(this)?this.ei.emit32(s,c,t.bin.normalizeExternalLabel(d)):{stack:o,opcode:s,numArgs:a,labelName:t.bin.normalizeExternalLabel(l)}}toString(){return this.friendlyFmt}}t.Instruction=s;class r{constructor(e,t){this.bin=e,this.text=t}getOpExt(){return this.instruction?this.instruction.code:""}getOp(){return this.instruction?this.instruction.name:""}update(e){this.bin.peepOps++,(e=e.replace(/^\s*/,""))||this.bin.peepDel++,e&&(e+=" "),e=" "+e,this.text=e+"; WAS: "+this.text.trim(),this.instruction=null,this.numArgs=null,this.words=l(e)||[],0==this.words.length?this.type="empty":"@"==this.words[0][0]&&(this.type="directive")}}t.Line=r;class o{constructor(e,t){this.id=e,this.description=t,this.sizeAdj=0,this.users=[]}get size(){return this.endLocation-this.startLocation-this.sizeAdj}}class a{constructor(e){this.baseOffset=0,this.checkStack=!0,this.inlineMode=!1,this.normalizeExternalLabel=e=>e,this.currLineNo=0,this.scope="",this.scopeId=0,this.errors=[],this.labels={},this.equs={},this.stackpointers={},this.stack=0,this.commPtr=0,this.peepOps=0,this.peepDel=0,this.peepCounts={},this.stats="",this.throwOnError=!1,this.disablePeepHole=!1,this.stackAtLabel={},this.codeSizeStats=!1,this.labelToObject={},this.idToObject={},this.objSuspendStart=0,this.labelsToObjectDone=!1,this.currLine=new r(this,"<start>"),this.currLine.lineNo=0,this.ei=e,this.ei.file=this}emitShort(t){e.assert(0<=t&&t<=65535),this.buf.push(t)}emitOpCode(e){this.emitShort(e)}location(){return 2*this.buf.length}pc(){return this.location()+this.baseOffset}useLabel(t){if(!this.currObject||"."==t[0]||this.objSuspendStart)return;const n=e.U.lookup(this.labelToObject,t);n&&n!=this.currObject&&n.users.length<5&&n.users.indexOf(this.currObject)<0&&n.users.push(this.currObject)}parseOneInt(t){if(!t)return null;if(/^\d+$/.test(t))return parseInt(t,10);const i=t.indexOf("-");if(i>0)return this.parseOneInt(t.slice(0,i))-this.parseOneInt(t.slice(i+1));let s=1;if(t.indexOf("*")>=0){let e=null;for(;null!=(e=/^([^\*]*)\*(.*)$/.exec(t));){let n=this.parseOneInt(e[1]);if(null==n)return null;s*=n,t=e[2]}}if("-"==t[0]?(s*=-1,t=t.slice(1)):"+"==t[0]&&(t=t.slice(1)),/^\d+$/.test(t))return s*parseInt(t,10);if(e.U.endsWith(t,"|1"))return 1|this.parseOneInt(t.slice(0,t.length-2));if(e.U.endsWith(t,"-1"))return this.parseOneInt(t.slice(0,t.length-2))-1;if(e.U.endsWith(t,"+1"))return this.parseOneInt(t.slice(0,t.length-2))+1;let r=/(.*)>>(\d+)$/.exec(t);if(r){let e=this.parseOneInt(r[1]);return e&=~(-16777216&this.baseOffset),e>>parseInt(r[2])}let o=null;if("0"==t[0])if("x"==t[1]||"X"==t[1]){let e=/^0x([a-f0-9]+)$/i.exec(t);e&&(o=parseInt(e[1],16))}else if("b"==t[1]||"B"==t[1]){let e=/^0b([01]+)$/i.exec(t);e&&(o=parseInt(e[1],2))}if(t.indexOf("@")>=0){let i=/^(\w+)@(-?\d+)$/.exec(t);i&&(1!=s&&this.directiveError(n("multiplication not supported with saved stacks")),this.stackpointers.hasOwnProperty(i[1])?o=this.ei.wordSize()*this.ei.computeStackOffset(i[1],this.stack-this.stackpointers[i[1]]+parseInt(i[2])):this.directiveError(n("saved stack not found"))),i=/^(.*)@(hi|lo|fn)$/.exec(t),i&&this.looksLikeLabel(i[1])&&(o=this.lookupLabel(i[1],!0),null!=o&&("fn"==i[2]?o=this.ei.toFnPtr(o,this.baseOffset,i[1]):(o>>=1,0<=o&&o<=65535?"hi"==i[2]?o=o>>8&255:"lo"==i[2]?o&=255:e.oops():(this.directiveError(n("@hi/lo out of range")),o=null))))}return null==o&&this.looksLikeLabel(t)&&(o=this.lookupLabel(t,!0),null!=o&&1==this.ei.postProcessRelAddress(this,1)&&(o+=this.baseOffset)),null==o||isNaN(o)?null:o*s}looksLikeLabel(e){return!/^(r\d|pc|sp|lr)$/i.test(e)&&/^[\.a-zA-Z_][\.:\w+]*$/.test(e)}scopedName(e){return"."==e[0]&&this.scope?this.scope+"$"+e:e}lookupLabel(e,t=!1){this.useLabel(e);let i=null,s=this.scopedName(e);return this.labels.hasOwnProperty(s)?(i=this.labels[s],i=this.ei.postProcessRelAddress(this,i)):this.lookupExternalLabel&&(i=this.lookupExternalLabel(e),null!=i&&(i=this.ei.postProcessAbsAddress(this,i))),null==i&&this.equs.hasOwnProperty(s)&&(i=this.equs[s]),null==i&&t&&(this.finalEmit?this.directiveError(n("unknown label: {0}",e)):i=11111),i}align(t){for(e.assert(2==t||4==t||8==t||16==t);this.location()%t!=0;)this.emitOpCode(0)}pushError(e,t=""){let i={scope:this.scope,message:n(" -> Line {2} ('{1}'), error: {0}\n{3}",e,this.currLine.text,this.currLine.lineNo,t),lineNo:this.currLine.lineNo,line:this.currLine.text,coremsg:e,hints:t};if(this.errors.push(i),this.throwOnError)throw new Error(i.message)}directiveError(e){this.pushError(e)}emitString(e,t=!1){function i(e,t){return 255&(e.charCodeAt(t)||0)}let s,r=/^\s*([\w\.]+\s*:\s*)?.\w+\s+(".*")\s*$/.exec(e);if(r&&null!=(s=c(r[2])))if(this.align(2),t)for(let e=0;e<s.length;e++)this.emitShort(s.charCodeAt(e));else for(let e=0;e<s.length+1;e+=2)this.emitShort(i(s,e+1)<<8|i(s,e));else this.directiveError(n("expecting string"))}parseNumber(e){let t=this.parseOneInt(e.shift());return null==t?null:t}parseNumbers(e){e=e.slice(1);let t=[];for(;;){let i=this.parseNumber(e);if(null==i){this.directiveError(n("cannot parse number at '{0}'",e[0]));break}if(t.push(i),","!=e[0]){if(null==e[0])break;this.directiveError(n("expecting number, got '{0}'",e[0]));break}if(e.shift(),null==e[0])break}return t}emitSpace(e){let t=this.parseNumbers(e);if(1==t.length&&t.push(0),2!=t.length)this.directiveError(n("expecting one or two numbers"));else if(t[0]%2!=0)this.directiveError(n("only even space supported"));else{let e=255&t[1];e|=e<<8;for(let n=0;n<t[0];n+=2)this.emitShort(e)}}emitBytes(e){let t=this.parseNumbers(e);t.length%2!=0&&(this.directiveError(".bytes needs an even number of arguments"),t.push(0));for(let e=0;e<t.length;e+=2){let i=t[e],s=t[e+1];0<=i&&s<=255&&0<=s&&i<=255?this.emitShort(255&i|(255&s)<<8):this.directiveError(n("expecting uint8"))}}emitHex(e){e.slice(1).forEach((e=>{if(","!=e)if(e.length%4!=0)this.directiveError(".hex needs an even number of bytes");else if(/^[a-f0-9]+$/i.test(e))for(let t=0;t<e.length;t+=4){let n=parseInt(e.slice(t,t+4),16);n=(255&n)<<8|n>>8&255,this.emitShort(n)}else this.directiveError(".hex needs a hex number")}))}handleDirective(t){let i,s=t.words,r=()=>{2!=s.length&&this.directiveError(n("expecting one argument"))};switch(s[0]){case".object":if(this.codeSizeStats)if("PUSH"==s[1])this.objSuspendStart=this.location();else if("POP"==s[1])this.objSuspendStart&&(this.currObject.sizeAdj+=this.location()-this.objSuspendStart),this.objSuspendStart=0;else{if(this.currObject&&(this.currObject.endLocation=this.location()),this.currObject=e.U.lookup(this.idToObject,s[1]),!this.currObject){const e=t.text.replace(/^[^"]*/,"");let i=s[1];s.length>2&&(i=c(e.trim()),null==i&&this.directiveError(n("expecting string in .object"))),this.currObject=new o(s[1],i),this.idToObject[s[1]]=this.currObject}this.currObject.sizeAdj=0,this.currObject.startLocation=this.location()}else;break;case".ascii":case".asciz":case".string":this.emitString(t.text);break;case".utf16":this.emitString(t.text,!0);break;case".align":if(r(),i=this.parseOneInt(s[1]),null!=i){if(0==i)return;i<=4?this.align(1<<i):this.directiveError(n("expecting 1, 2, 3 or 4 (for 2, 4, 8, or 16 byte alignment)"))}else this.directiveError(n("expecting number"));break;case".balign":if(r(),i=this.parseOneInt(s[1]),null!=i){if(1==i)return;2==i||4==i||8==i||16==i?this.align(i):this.directiveError(n("expecting 2, 4, 8, or 16"))}else this.directiveError(n("expecting number"));break;case".p2align":r(),i=this.parseOneInt(s[1]),null!=i?this.align(1<<i):this.directiveError(n("expecting number"));break;case".byte":this.emitBytes(s);break;case".hex":this.emitHex(s);break;case".hword":case".short":case".2bytes":this.parseNumbers(s).forEach((e=>{-32768<=e&&e<=65535?this.emitShort(65535&e):this.directiveError(n("expecting int16"))}));break;case".word":case".4bytes":case".long":this.parseNumbers(s).forEach((e=>{-2147483648<=e&&e<=4294967295?(this.emitShort(65535&e),this.emitShort(e>>16&65535)):this.directiveError(n("expecting int32"))}));break;case".skip":case".space":this.emitSpace(s);break;case".set":case".equ":/^\w+$/.test(s[1])||this.directiveError(n("expecting name"));const a=this.parseNumbers(s.slice(","==s[2]||"="==s[2]?2:1));1!=a.length&&this.directiveError(n("expecting one value")),void 0!==this.equs[s[1]]&&this.equs[s[1]]!=a[0]&&this.directiveError(n("redefinition of {0}",s[1])),this.equs[s[1]]=a[0];break;case".startaddr":this.location()&&this.directiveError(n(".startaddr can be only be specified at the beginning of the file")),r(),this.baseOffset=this.parseOneInt(s[1]);break;case"@stackmark":r(),this.stackpointers[s[1]]=this.stack;break;case"@stackempty":this.checkStack&&(null==this.stackpointers[s[1]]?this.directiveError(n("no such saved stack")):this.stackpointers[s[1]]!=this.stack&&this.directiveError(n("stack mismatch")));break;case"@scope":this.scope=s[1]||"",this.currLineNo=this.scope?0:this.realCurrLineNo;break;case".syntax":case"@nostackcheck":this.checkStack=!1;break;case"@dummystack":r(),this.stack+=this.parseOneInt(s[1]);break;case".section":case".global":this.stackpointers={},this.stack=0,this.scope="$S"+this.scopeId++;break;case".comm":{s=s.filter((e=>","!=e)),s.shift();let e=this.parseOneInt(s[1]),t=0;if(t=s[2]?this.parseOneInt(s[2]):4,null==this.lookupLabel(s[0])){for(this.commPtr||(this.commPtr=this.lookupExternalLabel("_pxt_comm_base")||0,this.commPtr||this.directiveError(n("PXT_COMM_BASE not defined")));this.commPtr&t-1;)this.commPtr++;this.labels[this.scopedName(s[0])]=this.commPtr-this.baseOffset,this.commPtr+=e}break}case".file":case".text":case".cpu":case".fpu":case".eabi_attribute":case".code":case".thumb_func":case".type":case".fnstart":case".save":case".size":case".fnend":case".pad":case".globl":case".local":case"@":break;default:/^\.cfi_/.test(s[0])||this.directiveError(n("unknown directive"))}}handleOneInstruction(e,t){this.codeSizeStats&&e.ldlitLabel&&this.useLabel(e.ldlitLabel);let i=t.emit(e);return!i.error&&(this.stack+=i.stack,this.checkStack&&this.stack<0&&this.pushError(n("stack underflow")),e.location=this.location(),e.opcode=i.opcode,e.stack=i.stack,this.emitOpCode(i.opcode),null!=i.opcode2&&this.emitOpCode(i.opcode2),null!=i.opcode3&&this.emitOpCode(i.opcode3),e.instruction=t,e.numArgs=i.numArgs,!0)}handleInstruction(e){if(e.instruction&&this.handleOneInstruction(e,e.instruction))return;let t=e=>this.ei.instructions.hasOwnProperty(e)?this.ei.instructions[e]:[];if(!e.instruction){let n=t(e.words[0]);for(let t=0;t<n.length;++t)if(this.handleOneInstruction(e,n[t]))return}let i=e.words[0].toLowerCase().replace(/s$/,"").replace(/[^a-z]/g,""),s="",r=t(i).concat(t(i+"s"));r.length>0&&r.forEach((t=>{let i=t.emit(e);s+=n(" Maybe: {0} ({1} at '{2}')\n",t.toString(),i.error,i.errorAt)})),this.pushError(n("assembly error"),s)}buildLine(e,t){let n=e=>{let n=new r(this,e);return n.scope=this.scope,n.lineNo=this.currLineNo,t.push(n),n},i=n(e),s=l(i.text)||[];i.words=s;let o=s[0]||"";if(":"==o.charAt(o.length-1)){let t=/^([\.\w]+):$/.exec(s[0]);if(t){if(i.type="label",i.text=t[1]+":",i.words=[t[1]],!(s.length>1))return;s.shift(),i=n(e.replace(/^[^:]*:/,"")),i.words=s,o=s[0]||""}}let a=o.charAt(0);"."==a||"@"==a?(i.type="directive","@scope"==i.words[0]&&this.handleDirective(i)):0==i.words.length?i.type="empty":i.type="instruction"}prepLines(e){this.currLineNo=0,this.realCurrLineNo=0,this.lines=[],e.split(/\r?\n/).forEach((e=>{this.errors.length>10||(this.currLineNo++,this.realCurrLineNo++,this.buildLine(e,this.lines))}))}iterLines(){this.stack=0,this.buf=[],this.scopeId=0,this.lines.forEach((t=>{if(!(this.errors.length>10)&&(this.currLine=t,0!=t.words.length))if("label"==t.type){this.currObject&&!this.labelsToObjectDone&&"."!=t.words[0][0]&&(this.labelToObject[t.words[0]]=this.currObject);let i=this.scopedName(t.words[0]);if(this.prevLabel=i,this.finalEmit){null!=this.equs[i]&&this.directiveError(n(".equ redefined as label"));let t=this.labels[i];null==t&&e.oops(),0==this.errors.length&&t!=this.location()&&e.oops(`invalid location: ${this.location()} != ${t} at ${i}`),e.assert(this.errors.length>0||t==this.location()),this.reallyFinalEmit&&(this.stackAtLabel[i]=this.stack)}else this.labels.hasOwnProperty(i)?this.directiveError(n("label redefinition")):this.inlineMode&&/^_/.test(i)?this.directiveError(n("labels starting with '_' are reserved for the compiler")):this.labels[i]=this.location();t.location=this.location()}else"directive"==t.type?this.handleDirective(t):"instruction"==t.type?this.handleInstruction(t):"empty"==t.type||e.oops()})),this.labelsToObjectDone=!0,this.currObject=null}getSourceMap(){const e={};let t="",n=0,i=0,s=0;function r(){t&&i&&(e[t]||(e[t]=[]),e[t].push(n,i,s-i)),i=0,s=0}return this.lines.forEach(((e,o)=>{const a=/^; ([\w\/\.-]+)\(([\d]+),\d+\):/.exec(e.text);a&&(r(),t=a[1],n=parseInt(a[2])),"instruction"==e.type&&(i||(i=e.location),s=e.location)})),r(),e}getCodeSizeStats(){if(!this.codeSizeStats)return"";const t=e.U.values(this.idToObject);t.sort(((e,t)=>t.size-e.size));let n=";\n; Code size:\n;\n";for(const e of t)if(n+=`; ${(" "+e.size).slice(-6)} ${e.description} [${e.id}]\n`,e.users.length>=5)n+=`; by many, including ${e.users[0].description}\n`;else for(const t of e.users)n+=`; by ${t.description} [${t.id}]\n`;return n}getSource(e,i=1,s=0){let r=0,o=e=>{let t=this.labels[e]||r,n=t-r;return r=t,n},a=this.buf?this.location():0,l=o("_code_end"),c=o("_helpers_end"),u=o("_vtables_end"),d=o("_literals_end"),h=r,p=a+this.baseOffset&16777215;if(s&&p>s){const e=new Error(n("program too big by {0} bytes!",p-s));throw e.ksErrorCode=9283,e}let f=n("; total bytes: {0} ({1}% of {2}k flash with {3} free)",p,(100*p/(s=s||131072)).toFixed(1),(s/1024).toFixed(1),s-p),m=n("; generated code sizes (bytes): {0} (incl. {1} user, {2} helpers, {3} vtables, {4} lits); src size {5}\n",h,l,c,u,d,a-h)+n("; assembly: {0} lines; density: {1} bytes/stmt; ({2} stmts)\n",this.lines.length,Math.round(100*l/i)/100,i)+f+"\n"+this.stats+this.getCodeSizeStats()+"\n\n",g=!1;return this.lines.forEach(((n,i)=>{if("_stored_program"==n.words[0])return m+='_stored_program: .string "..."\n',void(g=!0);if(g)return void(g=!1);let s=n.text;if(e){if("@stackempty"==n.words[0]&&this.lines[i-1].text==n.text)return;if(s=s.replace(/; WAS: .*/,""),!s.trim())return}t.debug&&("label"!=n.type&&"instruction"!=n.type||(s+=` \t; 0x${(n.location+this.baseOffset).toString(16)}`)),m+=s+"\n"})),m}peepHole(){let e=this.lines.filter((e=>"empty"!=e.type));for(let t=0;t<e.length;++t){let n=e[t];if(/^user/.test(n.scope))continue;let i=e[t+1];if(!i)continue;let s=e[t+2];"instruction"==n.type&&this.ei.peephole(n,i,s)}}clearLabels(){this.labels={},this.commPtr=0}peepPass(t){this.disablePeepHole||(this.peepOps=0,this.peepDel=0,this.peepCounts={},this.peepHole(),this.throwOnError=!0,this.finalEmit=!1,this.clearLabels(),this.iterLines(),e.assert(!this.checkStack||0==this.stack),this.finalEmit=!0,this.reallyFinalEmit=t||0==this.peepOps,this.iterLines(),this.stats+=n("; peep hole pass: {0} instructions removed and {1} updated\n",this.peepDel,this.peepOps-this.peepDel))}getLabels(){return this.userLabelsCache||(this.userLabelsCache=e.U.mapMap(this.labels,((e,t)=>t+this.baseOffset))),this.userLabelsCache}emit(t){if(e.assert(null==this.buf),this.prepLines(t),this.errors.length>0)return;if(this.clearLabels(),this.iterLines(),this.checkStack&&0!=this.stack&&this.directiveError(n("stack misaligned at the end of the file")),this.errors.length>0)return;if(this.ei.expandLdlit(this),this.clearLabels(),this.iterLines(),this.finalEmit=!0,this.reallyFinalEmit=this.disablePeepHole,this.iterLines(),this.errors.length>0)return;for(let e=0;e<5&&(pxt.debug(`Peephole OPT, pass ${e}`),this.peepPass(5==e),0!=this.peepOps);++e);pxt.debug("emit done")}}t.File=a;t.VMFile=class extends a{constructor(e){super(e)}};function l(e){let t=[],n="";e:for(let i=0;i<e.length;++i)switch(e[i]){case"[":case"]":case"!":case"{":case"}":case",":n&&(t.push(n),n=""),t.push(e[i]);break;case" ":case"\t":case"\r":case"\n":n&&(t.push(n),n="");break;case";":break e;default:n+=e[i]}return n&&(t.push(n),n=""),t[0]?t:null}function c(e){e=e.replace(/\\\\/g,"\\B").replace(/\\(['\?])/g,((e,t)=>t)).replace(/\\[z0]/g,"\0").replace(/\\x([0-9a-f][0-9a-f])/gi,((e,t)=>"\\u00"+t)).replace(/\\B/g,"\\\\");try{return JSON.parse(e)}catch(e){return null}}function u(e,t){return{stack:null,opcode:null,error:e,errorAt:t}}function d(e){return e<0||e>65535?("0x"+e.toString(16)).toLowerCase():("0x"+("000"+e.toString(16)).slice(-4)).toLowerCase()}t.AbstractProcessor=class{constructor(){this.file=null,this.addEnc=(e,t,n)=>{let i={name:e,pretty:t,encode:n,isRegister:/^\$r\d/.test(e),isImmediate:/^\$i\d/.test(e),isRegList:/^\$rl\d/.test(e),isLabel:/^\$l[a-z]/.test(e)};return this.encoders[e]=i,i},this.inrange=(e,t,n)=>Math.floor(t)!=t||t<0||t>e?null:n,this.inminmax=(e,t,n,i)=>Math.floor(n)!=n||n<e||n>t?null:i,this.inseq=(e,t)=>{let n=e.indexOf(t);return n<0?null:n},this.inrangeSigned=(e,t,n)=>{if(Math.floor(t)!=t)return null;if(t<-(e+1))return null;if(t>e)return null;return n&(e<<1|1)},this.addInst=(e,t,n,i)=>{let r=new s(this,e,t,n,i);return this.instructions.hasOwnProperty(r.name)||(this.instructions[r.name]=[]),this.instructions[r.name].push(r),r},this.encoders={},this.instructions={}}toFnPtr(e,t,n){return e}wordSize(){return-1}computeStackOffset(e,t){return t}is32bit(e){return!1}emit32(e,t,n){return null}postProcessRelAddress(e,t){return t}postProcessAbsAddress(e,t){return t}peephole(e,t,n){}registerNo(e){return null}getAddressFromLabel(e,t,n,i=!1){return null}isPop(e){return!1}isPush(e){return!1}isAddSP(e){return!1}isSubSP(e){return!1}testAssembler(){e.assert(!1)}expandLdlit(e){}},t.emitErr=u,t.expectError=function(t,n){let i=new a(t);i.emit(n),0==i.errors.length&&e.oops("ASMTEST: expecting error for: "+n)},t.tohex=d,t.expect=function(t,n){let i=[],s=n.replace(/^([0-9a-fA-F]{4,8})\s/gm,((e,t)=>(i.push(parseInt(t.slice(0,4),16)),8==t.length&&i.push(parseInt(t.slice(4,8),16)),""))),r=new a(t);r.throwOnError=!0,r.disablePeepHole=!0,r.emit(s),r.errors.length>0&&(console.debug(r.errors[0].message),e.oops("ASMTEST: not expecting errors")),r.buf.length!=i.length&&e.oops("ASMTEST: wrong buf len");for(let t=0;t<i.length;++t)r.buf[t]!=i[t]&&e.oops("ASMTEST: wrong buf content at "+t+" , exp:"+d(i[t])+", got: "+d(r.buf[t]))}}(e.assembler||(e.assembler={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){var n=pxtc.Util;t.apiRoot=e.BrowserUtils.isLocalHost()||n.isNodeJS?"https://www.makecode.com/api/":"/api/",t.accessToken="",t.localToken="";let i=!0;function s(t){let i=new Error(n.lf("Cannot access {0} while offline",t));return i.isOffline=!0,e.U.delay(1e3).then((()=>Promise.reject(i)))}function r(n,i){return e.U.requestAsync({url:"/api/"+n,headers:{Authorization:t.localToken},method:i?"POST":"GET",data:i||void 0,allowHttpErrors:!0})}function o(){return e.webConfig&&!e.webConfig.isStatic&&!e.BrowserUtils.isLocalHost()&&!!e.webConfig.cdnUrl}function a(n){if(n=n.replace(/^\//,""),!o())return t.apiRoot+n;const i=new Date,s=i.getUTCFullYear()+("0"+(i.getUTCMonth()+1)).slice(-2)+("0"+i.getUTCDate()).slice(-2);return n.indexOf("?")<0?n+="?":n+="&",n+="cdn="+s,e.webConfig.cdnUrl+"/api/"+n}function l(e){return o()?(e.url=a(e.url),n.requestAsync(e).catch((t=>c(e,t)))):u(e)}function c(e,n){return 0==n.statusCode?(i&&(i=!1,t.onOffline()),s(e.url)):Promise.reject(n)}function u(i){var r;return i.url=(null===(r=e.webConfig)||void 0===r?void 0:r.isStatic)&&!i.forceLiveEndpoint?e.webConfig.relprefix+i.url:t.apiRoot+i.url,i.allowGzipPost=!0,t.isOnline()||e.BrowserUtils.isPxtElectron()?(i.headers||(i.headers={}),e.BrowserUtils.isLocalHost()?t.localToken&&(i.headers.Authorization=t.localToken):t.accessToken&&(i.headers["x-td-access-token"]=t.accessToken),n.requestAsync(i).catch((e=>c(i,e)))):s(i.url)}function d(){return navigator&&navigator.onLine}t.onOffline=()=>{},t.hasAccessToken=function(){return!!t.accessToken},t.localRequestAsync=r,t.useCdnApi=o,t.cdnApiUrl=a,t.apiRequestWithCdnAsync=l,t.privateRequestAsync=u,t.privateGetTextAsync=function(e,t){return u({url:e,headers:t}).then((e=>e.text))},t.privateGetAsync=function(e,t=!1){return u({url:e,forceLiveEndpoint:t}).then((e=>e.json))},t.downloadTargetConfigAsync=function(){if(!t.isOnline())return Promise.resolve(void 0);const n=e.appTarget.versions&&e.appTarget.versions.target,i=e.webConfig&&e.webConfig.isStatic?"targetconfig.json":`config/${e.appTarget.id}/targetconfig${n?`/v${n}`:""}`;return e.BrowserUtils.isLocalHost()?r(i).then((e=>e?e.json:void 0)):l({url:i}).then((e=>e.json))},t.downloadScriptFilesAsync=function(e){return u({url:e+"/text"+(e.startsWith("S")?`?time=${Date.now()}`:""),forceLiveEndpoint:!0}).then((e=>JSON.parse(e.text)))},t.downloadScriptMetaAsync=function(e){return u({url:e+(e.startsWith("S")?`?time=${Date.now()}`:""),forceLiveEndpoint:!0}).then((e=>JSON.parse(e.text).meta))},t.downloadBuiltSimJsInfoAsync=async function(t){const n=e.appTarget.versions&&e.appTarget.versions.target||"",i=e.U.stringifyQueryString(t+"/js",{v:"v"+n})+(t.startsWith("S")?`&time=${Date.now()}`:"");return(await u({url:i,forceLiveEndpoint:!0})).json},t.markdownAsync=async function(t,n,i){const s=e.BrowserUtils.isLocalHostDev()?0:36e5,a=24*s*7;n=n||e.Util.userLanguage();const c=await e.BrowserUtils.translationDbAsync(),d=await c.getAsync(n,t),h=async()=>{try{const i=await function(t,n,i){var s;const a=null===(s=e.webConfig)||void 0===s?void 0:s.isStatic,c=e.appTarget.versions&&e.appTarget.versions.target||"?";let d;if(a){d=t;const e=/\/?docs\//.test(d),n=/\.\w+$/.test(d);if(!e){const e="/"===d[0];d=`docs${e?"":"/"}${d}`}n||(d=`${d}.md`)}else d=`md/${e.appTarget.id}/${t.replace(/^\//,"")}?targetVersion=${encodeURIComponent(c)}`;"en"!=n&&(d+=`${a?"?":"&"}lang=${encodeURIComponent(n)}`);if(e.BrowserUtils.isLocalHost()&&!e.Util.liveLocalizationEnabled())return r(d).then((e=>404==e.statusCode?u({url:d,method:"GET"}).then((e=>({md:e.text,etag:e.headers.etag}))):{md:e.text,etag:void 0}));{const e=i&&!o()?{"If-None-Match":i}:void 0;return l({url:d,method:"GET",headers:e}).then((e=>({md:e.text,etag:e.headers.etag})))}}(t,n,null==d?void 0:d.etag);return!d||i.md&&d.md!==i.md?(await c.setAsync(n,t,i.etag,void 0,i.md),i.md):d.md}catch(e){if(i)throw e;return""}};if(d){const t=Date.now()-d.time,n=t>s;if(t>a)e.tickEvent("markdown.update.wait");else if(n&&(e.tickEvent("markdown.update.background"),h()),d.md)return d.md}return h()},t.privateDeleteAsync=function(e){return u({url:e,method:"DELETE"}).then((e=>e.json))},t.privatePostAsync=function(e,t,n=!1){return u({url:e,data:t||{},forceLiveEndpoint:n}).then((e=>e.json))},t.isLoggedIn=function(){return!!t.accessToken},t.isNavigatorOnline=d,t.isOnline=function(){return"undefined"!=typeof navigator&&d()&&(i=!0),i},t.getServiceUrl=function(){return t.apiRoot.replace(/\/api\/$/,"")},t.getUserId=function(){let e=/^0(\w+)\./.exec(t.accessToken);return e?e[1]:null},t.parseScriptId=function(t){var i;const s=e.appTarget;if(!t||!s.appTheme||!(null===(i=s.cloud)||void 0===i?void 0:i.sharing))return;let r=["makecode.com"];s.appTheme.embedUrl&&r.push(s.appTheme.embedUrl),s.appTheme.shareUrl&&r.push(s.appTheme.shareUrl),r=n.unique(r,(e=>e)).map((e=>n.escapeForRegex(n.stripUrlProtocol(e).replace(/\/$/,"")).toLowerCase()));const o=`(?:(?:https://)?(?:${r.join("|")})/)`,a=new RegExp(`^${o}?(?:v[0-9]+/)?(?:(?:api/oembed\\?url=.*%2F([^&#]*)&.*)|(?:/?([a-z0-9\\-_]+)(?:[#?&].*)?))$`,"i").exec(t.trim()),l=(null==a?void 0:a[1])||(null==a?void 0:a[2]);return/^(_.{12}|S?[0-9\-]{23})$/.test(l)?l:void 0}}(e.Cloud||(e.Cloud={}))}(pxt||(pxt={})),function(e){!function(e){e.f4EncodeImg=function(e,t,n,i){let s=[135,n,255&e,e>>8,255&t,t>>8,0,0].map(c).join(""),r=4,o=0,a=0,l=e=>{o|=e<<a,a==8-n?(s+=c(o),r++,o=0,a=0):a+=n};for(let s=0;s<e;++s){for(let e=0;e<t;++e)l(i(s,e));for(;0!=a;)l(0);if(n>1)for(;3&r;)l(0)}return s;function c(e){return("0"+e.toString(16)).slice(-2)}}}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){function t(e){let t="";switch(e){case 0:t="C5";break;case 1:t="B";break;case 2:t="A";break;case 3:t="G";break;case 4:t="F";break;case 5:t="E";break;case 6:t="D";break;case 7:t="C"}return t}function n(e){let t=-1;switch(e){case"C5":t=0;break;case"B":t=1;break;case"A":t=2;break;case"G":t=3;break;case"F":t=4;break;case"E":t=5;break;case"D":t=6;break;case"C":t=7}return t}e.MelodyArray=class{constructor(e){this.numCols=8,this.numRows=8,this.polyphonic=!1,e&&(this.tempo=e),this.resetMelody()}setTempo(e){this.tempo=e}getArray(){return this.melody}setArray(e){this.melody=e}getColor(e){return 0}getValue(e,t){return this.melody[e][t]}getWidth(){return this.numCols}getHeight(){return this.numRows}updateMelody(e,t){const n=!this.melody[e][t];if(n&&!this.polyphonic)for(let e=0;e<this.numRows;e++)this.melody[e][t]=!1;this.melody[e][t]=n}getStringRepresentation(){let e="",n=new Array(this.numCols),i=0;for(let e=0;e<this.numRows;e++){let s=0;n[e]=[];for(let i=0;i<this.numCols;i++)this.melody[i][e]&&(n[e].push(t(i)),s++);s>i&&(i=s)}if(0==i)return"- - - - - - - - ";for(let t=0;t<i;t++)for(let t=0;t<this.numCols;t++)n[t]&&n[t].length>0?e+=n[t].shift()+" ":e+="- ";return e}parseNotes(e){let t=(e=e.trim()).split(" ");for(let e=0;e<t.length;e++){for(let t=0;t<this.numRows;t++)this.melody[t][e]=!1;"-"!=t[e]&&(this.melody[n(t[e])][e]=!0)}}setPolyphonic(e){this.polyphonic=e}isPolyphonic(){return this.polyphonic}resetMelody(){this.melody=new Array(this.numCols);for(let e=0;e<this.numCols;e++)this.melody[e]=new Array(this.numRows).fill(!1)}},e.rowToNote=t,e.noteToRow=n,e.getColorClass=function(e){let t="melody-default";switch(e){case 0:t="melody-red";break;case 1:t="melody-orange";break;case 2:t="melody-yellow";break;case 3:t="melody-green";break;case 4:t="melody-teal";break;case 5:t="melody-blue";break;case 6:t="melody-purple";break;case 7:t="melody-violet"}return t}}(pxtmelody||(pxtmelody={})),function(e){function t(e,t,n){return function(e,t,n){if(t)for(const n of Object.keys(t))"className"===n?e.setAttribute("class",t[n]+""):e.setAttribute(n,t[n]+"");n&&e.addEventListener("click",n);return e}(document.createElement(e),t,n)}e.MelodyGallery=class{constructor(){this.value=null,this.visible=!1,this.timeouts=[],this.numSamples=e.SampleMelodies.length,this.containerDiv=document.createElement("div"),this.containerDiv.setAttribute("id","melody-editor-gallery-outer"),this.contentDiv=document.createElement("div"),this.contentDiv.setAttribute("id","melody-editor-gallery"),this.itemBackgroundColor="#DCDCDC",this.itemBorderColor="white",this.initStyles(),this.containerDiv.appendChild(this.contentDiv),this.containerDiv.style.display="none",this.contentDiv.addEventListener("animationend",(()=>{this.visible||(this.containerDiv.style.display="none")})),this.contentDiv.addEventListener("wheel",(e=>{e.stopPropagation()}),!0)}getElement(){return this.containerDiv}getValue(){return this.value}show(e){this.pending=e,this.containerDiv.style.display="block",this.buildDom(),this.visible=!0,pxt.BrowserUtils.removeClass(this.contentDiv,"hidden-above"),pxt.BrowserUtils.addClass(this.contentDiv,"shown")}hide(){this.visible=!1,pxt.BrowserUtils.removeClass(this.contentDiv,"shown"),pxt.BrowserUtils.addClass(this.contentDiv,"hidden-above"),this.value=null,this.stopMelody()}clearDomReferences(){this.contentDiv=null,this.containerDiv=null}layout(e,t,n){this.containerDiv.style.left=e+"px",this.containerDiv.style.top=t+"px",this.containerDiv.style.height=n+"px"}buildDom(){for(;this.contentDiv.firstChild;)this.contentDiv.removeChild(this.contentDiv.firstChild);const t=e.SampleMelodies;this.buttons=[];for(let e=0;e<t.length;e++)this.mkButton(t[e],e,"255px","45px")}initStyles(){const e=document.createElement("style");e.textContent="\n #melody-editor-gallery {\n margin-top: -100%;\n }\n\n #melody-editor-gallery.hidden-above {\n margin-top: -100%;\n animation: slide-up 0.2s 0s ease;\n }\n\n #melody-editor-gallery.shown {\n margin-top: 0px;\n animation: slide-down 0.2s 0s ease;\n }\n\n @keyframes slide-down {\n 0% {\n margin-top: -100%;\n }\n 100% {\n margin-top: 0px;\n }\n }\n\n @keyframes slide-up {\n 0% {\n margin-top: 0px;\n }\n 100% {\n margin-top: -100%;\n }\n }\n ",this.containerDiv.appendChild(e)}mkButton(e,n,i,s){const r=t("div",{className:"melody-gallery-button melody-editor-card",role:"menuitem",id:`:${n}`}),o=t("i",{className:"music icon melody-icon"}),a=t("div",{className:"melody-editor-text"});a.innerText=e.name;const l=this.createColorBlock(e),c=t("div",{className:"melody-editor-button left-button",role:"button",title:e.name},(()=>this.handleSelection(e)));c.appendChild(o),c.appendChild(a),c.appendChild(l),r.appendChild(c);const u=t("div",{className:"melody-editor-button right-button",role:"button",title:lf("Preview {0}",e.name)},(()=>this.togglePlay(e,n))),d=t("i",{className:"play icon"});this.buttons[n]=d,u.appendChild(d),r.appendChild(u),this.contentDiv.appendChild(r)}handleSelection(e){if(this.pending){const t=this.pending;this.pending=void 0,t(e.notes)}}playNote(e,t,n){let i=0;switch(e){case"C5":i=523;break;case"B":i=494;break;case"A":i=440;break;case"G":i=392;break;case"F":i=349;break;case"E":i=330;break;case"D":i=294;break;case"C":i=262}this.timeouts.push(setTimeout((()=>{pxt.AudioContextManager.tone(i)}),t*this.getDuration(n))),this.timeouts.push(setTimeout((()=>{pxt.AudioContextManager.stop()}),(t+1)*this.getDuration(n)))}getDuration(e){return 6e4/e}previewMelody(e){this.stopMelody();let t=e.notes.split(" ");for(let n=0;n<t.length;n++)this.playNote(t[n],n,e.tempo)}togglePlay(e,t){let n=this.buttons[t];pxt.BrowserUtils.containsClass(n,"play icon")?(this.resetPlayIcons(),pxt.BrowserUtils.removeClass(n,"play icon"),pxt.BrowserUtils.addClass(n,"stop icon"),this.previewMelody(e),this.timeouts.push(setTimeout((()=>{pxt.BrowserUtils.removeClass(n,"stop icon"),pxt.BrowserUtils.addClass(n,"play icon")}),e.notes.split(" ").length*this.getDuration(e.tempo)))):(pxt.BrowserUtils.removeClass(n,"stop icon"),pxt.BrowserUtils.addClass(n,"play icon"),this.stopMelody())}stopMelody(){for(;this.timeouts.length;)clearTimeout(this.timeouts.shift());pxt.AudioContextManager.stop()}resetPlayIcons(){for(let e=0;e<this.numSamples;e++){let t=this.buttons[e];if(pxt.BrowserUtils.containsClass(t,"stop icon")){pxt.BrowserUtils.removeClass(t,"stop icon"),pxt.BrowserUtils.addClass(t,"play icon");break}}}createColorBlock(t){let n=document.createElement("div");pxt.BrowserUtils.addClass(n,"melody-color-block");let i=t.notes.split(" ");for(let t=0;t<i.length;t++){let s=e.getColorClass(e.noteToRow(i[t])),r=document.createElement("div");0==t?pxt.BrowserUtils.addClass(r,"left-edge sliver "+s):t==i.length-1?pxt.BrowserUtils.addClass(r,"right-edge sliver "+s):pxt.BrowserUtils.addClass(r,"sliver "+s),n.appendChild(r)}return n}}}(pxtmelody||(pxtmelody={})),function(e){class t{constructor(e,t,n){this.name=e,this.notes=t,this.tempo=n}}e.MelodyInfo=t,e.SampleMelodies=[new t(lf("Scale"),"C5 B A G F E D C",120),new t(lf("Reverse"),"C D E F G A B C5",120),new t(lf("Mystery"),"E B C5 A B G A F",120),new t(lf("Gilroy"),"A F E F D G E F",120),new t(lf("Falling"),"C5 A B G A F G E",120),new t(lf("Hopeful"),"G B A G C5 B A B",120),new t(lf("Tokyo"),"B A G A G F A C5",120),new t(lf("Paris"),"G F G A - F E D",120),new t(lf("Rising"),"E D G F B A C5 B",120),new t(lf("Sitka"),"C5 G B A F A C5 B",120)]}(pxtmelody||(pxtmelody={})),function(e){!function(e){let t;e.makeFocusable=function(e){e.setAttribute("focusable","true"),e.setAttribute("tabindex","0")},e.enableKeyboardInteraction=function(e,t,n){t&&e.addEventListener("keydown",(e=>{const n="number"==typeof e.which?e.which:e.keyCode;32!==n&&13!==n||t()})),n&&e.addEventListener("keyup",(e=>{const t="number"==typeof e.which?e.which:e.keyCode;32!==t&&13!==t||n()}))},e.setAria=function(e,t,n){t&&!e.hasAttribute("role")&&e.setAttribute("role",t),n&&!e.hasAttribute("aria-label")&&e.setAttribute("aria-label",n)},e.setLiveContent=function(e){if(!t){let e="position: absolute !important;display: block;visibility: visible;overflow: hidden;width: 1px;height: 1px;margin: -1px;border: 0;padding: 0;clip: rect(0 0 0 0);";t=document.createElement("div"),t.setAttribute("role","status"),t.setAttribute("aria-live","polite"),t.setAttribute("aria-hidden","false"),t.setAttribute("style",e),document.body.appendChild(t)}t.textContent!==e&&(t.textContent=e)}}(e.accessibility||(e.accessibility={}))}(pxsim||(pxsim={})),function(e){const t="blue",n="red",i="orange";const s=e=>(e=>e.reduce(((e,t)=>e+(t?1:0)),0))(e)>0;function r(e,t){let n={};for(let t in e)n[t]=e[t];for(let e in t)n[e]=t[e];return n}function o(t){e.U.assert(!!t,"Invalid pin: "+t);const n=/^(\w+)\.\s*(?:[a-z]*)?([A-Z][A-Z\d_]+)$/.exec(t);return n?n[2]:void 0}function a(e){return"-Z"===e.orientation&&"male"===e.style}e.readPin=o;class l{constructor(t){this.availablePowerPins={top:{fiveVolt:e.mkRange(26,51).map((e=>({type:"breadboard",row:"+",col:`${e}`}))),threeVolt:e.mkRange(26,51).map((e=>({type:"breadboard",row:"+",col:`${e}`}))),ground:e.mkRange(26,51).map((e=>({type:"breadboard",row:"-",col:`${e}`})))},bottom:{fiveVolt:e.mkRange(1,26).map((e=>({type:"breadboard",row:"+",col:`${e}`}))),threeVolt:e.mkRange(1,26).map((e=>({type:"breadboard",row:"+",col:`${e}`}))),ground:e.mkRange(1,26).map((e=>({type:"breadboard",row:"-",col:`${e}`})))}},this.opts=t}allocPartIRs(e,t,n){let i=[];const s=(e,t,i,s)=>{let r=[];for(let t=0;t<e.numberOfPins;t++){let s,o=e.pinDefinitions[t];if("string"==typeof o.target)s=o.target;else{let e=o.target.pinInstantiationIdx;if(!i||void 0===i[e])return void console.log(`error: parts no pin found for PinInstantiationIdx: ${e}. (Is the part missing an ArgumentRole or "trackArgs=" annotations?)`);s=i[e]}let a=e.visual.pinLocations[t],l=n.yOffset+a.y,c=Math.round(l/e.visual.pinDistance),u=l-c*e.visual.pinDistance,d=n.xOffset+a.x,h=Math.round(d/e.visual.pinDistance),p={partRelativeRowIdx:c,partRelativeColIdx:h,xOffset:d-h*e.visual.pinDistance,yOffset:u};r.push({def:o,loc:a,target:s,bbFit:p})}return{name:t,def:e,pins:r,partParams:s||{},bbFit:n}},r=e.instantiations||[];return e.instantiation&&r.push(e.instantiation),r.forEach((n=>{if("singleton"===n.kind)i.push(s(e,t));else if("function"===n.kind){let r=n,a=r.fullyQualifiedName.split(","),l={};a.forEach((e=>{this.opts.fnArgs[e]&&this.opts.fnArgs[e].forEach((e=>{l[e]=1}))}));let c=Object.keys(l);if(!c||!c.length)return void console.log(`error: parts failed to read pin(s) from callsite for: ${a}`);c.forEach((n=>{const l=n.split(",");if(l.length!=r.argumentRoles.length)return void console.log(`error: parts mismatch between number of arguments at callsite (function name: ${a}) vs number of argument roles in part definition (part: ${t}).`);let c=[],u={};l.forEach(((e,t)=>{let n=r.argumentRoles[t];if(void 0!==n.partParameter&&(u[n.partParameter]=e),void 0!==n.pinInstantiationIdx){let t=n.pinInstantiationIdx,i=o(e);c[t]=i}})),i.push(s(e,t,c,u))}))}})),i.filter((e=>!!e))}computePartDimensions(t,n){let i=t.visual.pinLocations,s=t.pinDefinitions,o=t.numberOfPins;e.U.assert(i.length===o,`Mismatch between "numberOfPins" and length of "visual.pinLocations" for "${n}"`),e.U.assert(s.length===o,`Mismatch between "numberOfPins" and length of "pinDefinitions" for "${n}"`),e.U.assert(o>0,`Part "${n}" has no pins`);let a,l,c,u,d=i.map(((e,t)=>{return n={idx:t},i=e,o=s[t],r(r(n,i),o);var n,i,o})).filter((e=>"-Z"===e.orientation)),h=d.length>0,p=t.visual.pinDistance;if(h){let e=d[0],n=Math.ceil(e.x/p),i=Math.ceil(e.y/p);a=n*p-e.x,l=i*p-e.y,c=Math.ceil((a+t.visual.width)/p)+1,u=Math.ceil((l+t.visual.height)/p)+1}else c=Math.ceil(t.visual.width/p),u=Math.ceil(t.visual.height/p),a=c*p-t.visual.width,l=u*p-t.visual.height;return{xOffset:a,yOffset:l,rowCount:u,colCount:c}}allocColumns(t){let n=t.length;let i=e.visuals.BREADBOARD_MID_COLS-t.map((e=>e.colCount)).reduce(((e,t)=>e+t),0);i<=0&&console.log("Not enough breadboard space!");let s=Math.floor(i/(n-1+2)),r=i-s*(n-1),o=Math.floor(r/2),a=(Math.ceil(r/2),1+o);return t.map((e=>{let t=a;return a+=e.colCount+s,t}))}placeParts(t){const n=e.visuals.BREADBOARD_MID_ROWS+2;let i=this.allocColumns(t.map((e=>e.bbFit))),s=t.map((e=>{let t=n-e.bbFit.rowCount,i=Math.floor(t/2);return i>4&&(i=4),i<1&&(i=1),i}));return t.map(((e,t)=>{let n=s[t];return r({startColumnIdx:i[t],startRowIdx:n},e)}))}nextColor(){return(!this.availableWireColors||this.availableWireColors.length<=0)&&(this.availableWireColors=e.visuals.GPIO_WIRE_COLORS.map((e=>e))),this.availableWireColors.pop()}allocWireIRs(s){let o=[],l=s.pins.map(((r,l)=>{let c,u,d=r.target,h=s.startColumnIdx+r.bbFit.partRelativeColIdx,p=e.visuals.getColumnName(h),f=s.startRowIdx+r.bbFit.partRelativeRowIdx;if(f>=7&&(f-=2),a(r.def)){c={type:"breadboard",row:f<5?"j":"a",col:p,style:r.def.style}}else{c={type:"breadboard",row:e.visuals.getRowName(f),col:p,xOffset:r.bbFit.xOffset/s.def.visual.pinDistance,yOffset:r.bbFit.yOffset/s.def.visual.pinDistance,style:r.def.style}}return u="ground"===d?t:"threeVolt"===d?n:"fiveVolt"===d?i:"number"==typeof r.def.colorGroup?o[r.def.colorGroup]?o[r.def.colorGroup]:o[r.def.colorGroup]=this.nextColor():this.nextColor(),{start:c,end:d,color:u,pinIdx:l}}));return r(s,{wires:l})}allocLocation(t,n){if("ground"===t||"threeVolt"===t||"fiveVolt"==t){if("ground"===t&&this.powerUsage.singleGround){return{type:"dalboard",pin:this.getBoardGroundPin()}}if("threeVolt"===t&&this.powerUsage.singleThreeVolt){return{type:"dalboard",pin:this.getBoardThreeVoltPin()}}if("fiveVolt"===t&&this.powerUsage.singleFiveVolt){return{type:"dalboard",pin:this.getBoardFiveVoltPin()}}e.U.assert(!!n.referenceBBPin);let i=this.opts.getBBCoord(n.referenceBBPin),s=[this.availablePowerPins.top.ground[0]||this.availablePowerPins.top.threeVolt[0],this.availablePowerPins.bottom.ground[0]||this.availablePowerPins.bottom.threeVolt[0]].map((e=>this.opts.getBBCoord(e)));s[0]&&s[1]||console.debug(`No more available "${t}" locations!`);let r,o=0==e.visuals.findClosestCoordIdx(i,s);o?"ground"===t?r=this.availablePowerPins.top.ground:"threeVolt"===t?r=this.availablePowerPins.top.threeVolt:"fiveVolt"===t&&(r=this.availablePowerPins.top.fiveVolt):"ground"===t?r=this.availablePowerPins.bottom.ground:"threeVolt"===t?r=this.availablePowerPins.bottom.threeVolt:"fiveVolt"===t&&(r=this.availablePowerPins.bottom.fiveVolt);let a=r.map((e=>this.opts.getBBCoord(e))),l=e.visuals.findClosestCoordIdx(i,a),c=r[l];return o?(this.availablePowerPins.top.ground.splice(l,1),this.availablePowerPins.top.threeVolt.splice(l,1)):(this.availablePowerPins.bottom.ground.splice(l,1),this.availablePowerPins.bottom.threeVolt.splice(l,1)),c}if("breadboard"===t.type)return t;if("MOSI"===t||"MISO"===t||"SCK"===t){return this.opts.boardDef.spiPins||console.debug("No SPI pin mappings found!"),{type:"dalboard",pin:this.opts.boardDef.spiPins[t]}}if("SDA"===t||"SCL"===t){return this.opts.boardDef.i2cPins||console.debug("No I2C pin mappings found!"),{type:"dalboard",pin:this.opts.boardDef.i2cPins[t]}}{e.U.assert("string"==typeof t,"Unknown location type: "+t);let n=t,i=this.opts.boardDef.gpioPinMap[n]||n;return i?{type:"dalboard",pin:i}:void console.debug(`unknown pin location for ${n}`)}}getBoardGroundPin(){let e=this.opts.boardDef.groundPins&&this.opts.boardDef.groundPins[0]||null;return e||console.debug("No available ground pin on board!"),e}getBoardThreeVoltPin(){let e=this.opts.boardDef.threeVoltPins&&this.opts.boardDef.threeVoltPins[0]||null;return e||console.debug("No available 3.3V pin on board!"),e}getBoardFiveVoltPin(){let e=this.opts.boardDef.fiveVoltPins&&this.opts.boardDef.fiveVoltPins[0]||null;return e||console.debug("No available 5V pin on board!"),e}allocPowerWires(e){let s=this.getBoardGroundPin(),r=this.getBoardThreeVoltPin(),o=this.getBoardFiveVoltPin();const a={type:"breadboard",row:"-",col:"26"},l={type:"breadboard",row:"-",col:"1"},c={type:"breadboard",row:"-",col:"50"},u={type:"breadboard",row:"-",col:"25"};let d,h;this.opts.boardDef.attachPowerOnRight?(d=c,h=u):(d=a,h=l);let p=[],f=[],m=[];e.bottomGround&&e.topGround&&p.push({start:this.allocLocation("ground",{referenceBBPin:d}),end:this.allocLocation("ground",{referenceBBPin:h}),color:t}),e.topGround?p.push({start:this.allocLocation("ground",{referenceBBPin:d}),end:{type:"dalboard",pin:s},color:t}):e.bottomGround&&p.push({start:this.allocLocation("ground",{referenceBBPin:h}),end:{type:"dalboard",pin:s},color:t}),e.bottomThreeVolt&&e.bottomGround?f.push({start:this.allocLocation("threeVolt",{referenceBBPin:d}),end:this.allocLocation("threeVolt",{referenceBBPin:h}),color:n}):e.bottomFiveVolt&&e.bottomGround&&m.push({start:this.allocLocation("fiveVolt",{referenceBBPin:d}),end:this.allocLocation("fiveVolt",{referenceBBPin:h}),color:i}),e.topThreeVolt?f.push({start:this.allocLocation("threeVolt",{referenceBBPin:d}),end:{type:"dalboard",pin:r},color:n}):e.bottomThreeVolt&&f.push({start:this.allocLocation("threeVolt",{referenceBBPin:h}),end:{type:"dalboard",pin:r},color:i}),e.topFiveVolt&&!e.topThreeVolt?m.push({start:this.allocLocation("fiveVolt",{referenceBBPin:d}),end:{type:"dalboard",pin:o},color:n}):e.bottomFiveVolt&&!e.bottomThreeVolt&&m.push({start:this.allocLocation("fiveVolt",{referenceBBPin:h}),end:{type:"dalboard",pin:o},color:i});let g=[];p.length>0&&g.push({wireIndices:p.map(((e,t)=>t))});let b=p.length;return f.length>0&&g.push({wireIndices:f.map(((e,t)=>t+b))}),m.length>0&&g.push({wireIndices:f.map(((e,t)=>t+b+f.length))}),{wires:p.concat(f).concat(m),assembly:g}}allocWire(e){const t=[e.start,e.end],n=t.map((e=>"ground"===e||"threeVolt"===e||"fiveVolt"===e));let i=t.map(((e,t)=>n[t]?void 0:this.allocLocation(e,{})));if(i=i.map(((e,n)=>{if(e)return e;const s=i[1-n];return this.allocLocation(t[n],{referenceBBPin:s})})),i[0]&&i[1])return{start:i[0],end:i[1],color:e.color}}allocPart(t){let n=t.pins.filter((e=>a(e.def))).map((n=>{let i=t.startRowIdx+n.bbFit.partRelativeRowIdx;i>=7&&(i-=2);let s=e.visuals.getRowName(i),r=t.startColumnIdx+n.bbFit.partRelativeColIdx;return{type:"breadboard",row:s,col:e.visuals.getColumnName(r)}}));return{name:t.name,visual:t.def.visual,bbFit:t.bbFit,startColumnIdx:t.startColumnIdx,startRowIdx:t.startRowIdx,breadboardConnections:n,params:t.partParams,simulationBehavior:t.def.simulationBehavior}}allocAll(){let e=this.opts.partsList.map((e=>({name:e,def:this.opts.partDefs[e]}))).filter((e=>!!e.def));if(e.length>0){let t=e.map((e=>this.computePartDimensions(e.def,e.name))),n=[];e.forEach(((e,i)=>{let s=t[i],r=this.allocPartIRs(e.def,e.name,s);n=n.concat(r)}));const i=this.placeParts(n).map((e=>this.allocWireIRs(e))),r=i.map((e=>e.wires)).reduce(((e,t)=>e.concat(t)),[]).map((e=>function(e){let t=[e.start,e.end],n=t.map((e=>"ground"===e)),i=t.map((e=>"threeVolt"===e)),r=t.map((e=>"fiveVolt"===e)),o=t.map((e=>function(e){let t=!1;if("string"!=typeof e&&"breadboard"===e.type){let n=e.row;t=0<=["a","b","c","d","e"].indexOf(n)}return t}(e))),a=s(n),l=s(i),c=s(r),u=s(o);return{topGround:a&&!u,topThreeVolt:l&&!u,topFiveVolt:c&&!u,bottomGround:a&&u,bottomThreeVolt:l&&u,bottomFiveVolt:c&&u,singleGround:a,singleThreeVolt:l,singleFiveVolt:c}}(e)));this.powerUsage=function(e){const t=e.reduce(((e,t)=>({topGround:e.topGround||t.topGround,topThreeVolt:e.topThreeVolt||t.topThreeVolt,topFiveVolt:e.topFiveVolt||t.topFiveVolt,bottomGround:e.bottomGround||t.bottomGround,bottomThreeVolt:e.bottomThreeVolt||t.bottomThreeVolt,bottomFiveVolt:e.bottomFiveVolt||t.bottomFiveVolt,singleGround:t.singleGround?null===e.singleGround:e.singleGround,singleThreeVolt:t.singleThreeVolt?null===e.singleThreeVolt:e.singleThreeVolt,singleFiveVolt:t.singleFiveVolt?null===e.singleFiveVolt:e.singleFiveVolt})),{topGround:!1,topThreeVolt:!1,topFiveVolt:!1,bottomGround:!1,bottomThreeVolt:!1,bottomFiveVolt:!1,singleGround:null,singleThreeVolt:null,singleFiveVolt:null});return t.singleGround&&(t.topGround=t.bottomGround=!1),t.singleThreeVolt&&(t.topThreeVolt=t.bottomThreeVolt=!1),t.singleFiveVolt&&(t.topFiveVolt=t.bottomFiveVolt=!1),t}(r);const o=this.allocPowerWires(this.powerUsage),a=i.map(((e,t)=>{const n=this.allocPart(e),i=e.wires.map((e=>this.allocWire(e)));if(i.some((e=>!e)))return;const s=[];e.wires.forEach(((e,t)=>{s[e.pinIdx]=t}));return{part:n,wires:i,assembly:e.def.assembly.map((e=>({part:e.part,wireIndices:(e.pinIndices||[]).map((e=>s[e]))})))}})).filter((e=>!!e)),l=[o].concat(a).filter((e=>e.assembly&&e.assembly.length)),c=!l.some((e=>e.part&&e.part.breadboardConnections&&e.part.breadboardConnections.length>0||e.wires&&e.wires.some((e=>"breadboard"==e.end.type&&"croc"!=e.end.style||"breadboard"==e.start.type&&"croc"!=e.start.style))));return{partsAndWires:l,wires:[],parts:[],hideBreadboard:c}}return{partsAndWires:[],wires:[],parts:[]}}}e.allocateDefinitions=function(e){return new l(e).allocAll()}}(pxsim||(pxsim={})),function(e){!function(e){class t{constructor(e){this.seq=0,this.type=e}}e.Message=t;e.Response=class extends t{constructor(e,t){super("response"),this.request_seq=e.seq,this.command=e.command,t?(this.success=!1,this.message=t):this.success=!0}};class n extends t{constructor(e,t){super("event"),this.event=e,t&&(this.body=t)}}e.Event=n;e.Source=class{constructor(e,t,n=0,i,s){this.name=e,this.path=t,this.sourceReference=n,i&&(this.origin=i),s&&(this.adapterData=s)}};e.Scope=class{constructor(e,t,n=!1){this.name=e,this.variablesReference=t,this.expensive=n}};e.StackFrame=class{constructor(e,t,n,i=0,s=0){this.id=e,this.source=n,this.line=i,this.column=s,this.name=t}};e.Thread=class{constructor(e,t){this.id=e,this.name=t||"Thread #"+e}};e.Variable=class{constructor(e,t,n=0,i,s){this.name=e,this.value=t,this.variablesReference=n,"number"==typeof s&&(this.namedVariables=s),"number"==typeof i&&(this.indexedVariables=i)}};e.Breakpoint=class{constructor(e,t,n,i){this.verified=e;const s=this;"number"==typeof t&&(s.line=t),"number"==typeof n&&(s.column=n),i&&(s.source=i)}};e.Module=class{constructor(e,t){this.id=e,this.name=t}};e.CompletionItem=class{constructor(e,t,n=0){this.label=e,this.start=t,this.length=n}};e.StoppedEvent=class extends n{constructor(e,t,n=null){if(super("stopped"),this.body={reason:e,threadId:t},n){this.body.text=n}}};e.ContinuedEvent=class extends n{constructor(e,t){super("continued"),this.body={threadId:e},"boolean"==typeof t&&(this.body.allThreadsContinued=t)}};e.InitializedEvent=class extends n{constructor(){super("initialized")}};e.TerminatedEvent=class extends n{constructor(e){if(super("terminated"),"boolean"==typeof e){this.body={restart:e}}}};e.OutputEvent=class extends n{constructor(e,t="console",n){super("output"),this.body={category:t,output:e},void 0!==n&&(this.body.data=n)}};e.ThreadEvent=class extends n{constructor(e,t){super("thread"),this.body={reason:e,threadId:t}}};e.BreakpointEvent=class extends n{constructor(e,t){super("breakpoint"),this.body={reason:e,breakpoint:t}}};e.ModuleEvent=class extends n{constructor(e,t){super("module"),this.body={reason:e,module:t}}};class i{constructor(){this._pendingRequests={}}start(e){this._sequence=1,this.host=e,this.host.onData((e=>{if("request"===e.type)this.dispatchRequest(e);else if("response"===e.type){const t=e,n=this._pendingRequests[t.seq];n&&(delete this._pendingRequests[t.seq],n(t))}}))}stop(){this.host&&this.host.close()}sendEvent(e){this.send("event",e)}sendResponse(e){e.seq>0?console.error(`attempt to send more than one response for command ${e.command}`):this.send("response",e)}sendRequest(t,n,i,s){const r={command:t};if(n&&Object.keys(n).length>0&&(r.arguments=n),this.send("request",r),s){this._pendingRequests[r.seq]=s;const t=setTimeout((()=>{clearTimeout(t);const n=this._pendingRequests[r.seq];n&&(delete this._pendingRequests[r.seq],n(new e.Response(r,"timeout")))}),i)}}send(e,t){if(t.type=e,t.seq=this._sequence++,this.host){const e=JSON.stringify(t);this.host.send(e)}}dispatchRequest(e){}}e.ProtocolServer=i;class s extends i{constructor(){super(...arguments),this._debuggerLinesStartAt1=!1,this._debuggerColumnsStartAt1=!1,this._clientLinesStartAt1=!0,this._clientColumnsStartAt1=!0}shutdown(){}dispatchRequest(t){const n=new e.Response(t);try{if("initialize"===t.command){let e=t.arguments;if("boolean"==typeof e.linesStartAt1&&(this._clientLinesStartAt1=e.linesStartAt1),"boolean"==typeof e.columnsStartAt1&&(this._clientColumnsStartAt1=e.columnsStartAt1),"path"!==e.pathFormat)this.sendErrorResponse(n,2018,"debug adapter only supports native paths",null);else{const t=n;t.body={},this.initializeRequest(t,e)}}else"launch"===t.command?this.launchRequest(n,t.arguments):"attach"===t.command?this.attachRequest(n,t.arguments):"disconnect"===t.command?this.disconnectRequest(n,t.arguments):"setBreakpoints"===t.command?this.setBreakPointsRequest(n,t.arguments):"setFunctionBreakpoints"===t.command?this.setFunctionBreakPointsRequest(n,t.arguments):"setExceptionBreakpoints"===t.command?this.setExceptionBreakPointsRequest(n,t.arguments):"configurationDone"===t.command?this.configurationDoneRequest(n,t.arguments):"continue"===t.command?this.continueRequest(n,t.arguments):"next"===t.command?this.nextRequest(n,t.arguments):"stepIn"===t.command?this.stepInRequest(n,t.arguments):"stepOut"===t.command?this.stepOutRequest(n,t.arguments):"stepBack"===t.command?this.stepBackRequest(n,t.arguments):"restartFrame"===t.command?this.restartFrameRequest(n,t.arguments):"goto"===t.command?this.gotoRequest(n,t.arguments):"pause"===t.command?this.pauseRequest(n,t.arguments):"stackTrace"===t.command?this.stackTraceRequest(n,t.arguments):"scopes"===t.command?this.scopesRequest(n,t.arguments):"variables"===t.command?this.variablesRequest(n,t.arguments):"setVariable"===t.command?this.setVariableRequest(n,t.arguments):"source"===t.command?this.sourceRequest(n,t.arguments):"threads"===t.command?this.threadsRequest(n):"evaluate"===t.command?this.evaluateRequest(n,t.arguments):"stepInTargets"===t.command?this.stepInTargetsRequest(n,t.arguments):"gotoTargets"===t.command?this.gotoTargetsRequest(n,t.arguments):"completions"===t.command?this.completionsRequest(n,t.arguments):this.customRequest(t.command,n,t.arguments)}catch(e){this.sendErrorResponse(n,1104,"{_stack}",{_exception:e.message,_stack:e.stack})}}initializeRequest(e,t){e.body.supportsConditionalBreakpoints=!1,e.body.supportsHitConditionalBreakpoints=!1,e.body.supportsFunctionBreakpoints=!1,e.body.supportsConfigurationDoneRequest=!0,e.body.supportsEvaluateForHovers=!1,e.body.supportsStepBack=!1,e.body.supportsSetVariable=!1,e.body.supportsRestartFrame=!1,e.body.supportsStepInTargetsRequest=!1,e.body.supportsGotoTargetsRequest=!1,e.body.supportsCompletionsRequest=!1,this.sendResponse(e)}disconnectRequest(e,t){this.sendResponse(e),this.shutdown()}launchRequest(e,t){this.sendResponse(e)}attachRequest(e,t){this.sendResponse(e)}setBreakPointsRequest(e,t){this.sendResponse(e)}setFunctionBreakPointsRequest(e,t){this.sendResponse(e)}setExceptionBreakPointsRequest(e,t){this.sendResponse(e)}configurationDoneRequest(e,t){this.sendResponse(e)}continueRequest(e,t){this.sendResponse(e)}nextRequest(e,t){this.sendResponse(e)}stepInRequest(e,t){this.sendResponse(e)}stepOutRequest(e,t){this.sendResponse(e)}stepBackRequest(e,t){this.sendResponse(e)}restartFrameRequest(e,t){this.sendResponse(e)}gotoRequest(e,t){this.sendResponse(e)}pauseRequest(e,t){this.sendResponse(e)}sourceRequest(e,t){this.sendResponse(e)}threadsRequest(e){this.sendResponse(e)}stackTraceRequest(e,t){this.sendResponse(e)}scopesRequest(e,t){this.sendResponse(e)}variablesRequest(e,t){this.sendResponse(e)}setVariableRequest(e,t){this.sendResponse(e)}evaluateRequest(e,t){this.sendResponse(e)}stepInTargetsRequest(e,t){this.sendResponse(e)}gotoTargetsRequest(e,t){this.sendResponse(e)}completionsRequest(e,t){this.sendResponse(e)}customRequest(e,t,n){this.sendErrorResponse(t,1014,"unrecognized request",null)}sendErrorResponse(e,t,n,i){let r;"number"==typeof t?(r={id:t,format:n},i&&(r.variables=i),r.showUser=!0):r=t,e.success=!1,s.formatPII(r.format,!0,r.variables),e.body||(e.body={}),e.body.error=r,this.sendResponse(e)}convertClientLineToDebugger(e){return this._debuggerLinesStartAt1?this._clientLinesStartAt1?e:e+1:this._clientLinesStartAt1?e-1:e}convertDebuggerLineToClient(e){return this._debuggerLinesStartAt1?this._clientLinesStartAt1?e:e-1:this._clientLinesStartAt1?e+1:e}convertClientColumnToDebugger(e){return this._debuggerColumnsStartAt1?this._clientColumnsStartAt1?e:e+1:this._clientColumnsStartAt1?e-1:e}convertDebuggerColumnToClient(e){return this._debuggerColumnsStartAt1?this._clientColumnsStartAt1?e:e-1:this._clientColumnsStartAt1?e+1:e}convertClientPathToDebugger(e){return this._clientPathsAreURIs!=this._debuggerPathsAreURIs?this._clientPathsAreURIs?s.uri2path(e):s.path2uri(e):e}convertDebuggerPathToClient(e){return this._debuggerPathsAreURIs!=this._clientPathsAreURIs?this._debuggerPathsAreURIs?s.uri2path(e):s.path2uri(e):e}static path2uri(e){let t=e.replace(/\\/g,"/");return"/"!==t[0]&&(t="/"+t),encodeURI("file://"+t)}static uri2path(e){return e}static formatPII(e,t,n){return e.replace(s._formatPIIRegexp,(function(e,i){return t&&i.length>0&&"_"!==i[0]?e:n[i]&&n.hasOwnProperty(i)?n[i]:e}))}}s._formatPIIRegexp=/{([^}]+)}/g,e.DebugSession=s}(e.protocol||(e.protocol={}))}(pxsim||(pxsim={})),function(e){!function(e){e.injectPolyphils=function(){String.prototype.startsWith||Object.defineProperty(String.prototype,"startsWith",{value:function(e,t){return void 0!==e&&null!=e&&(t=!t||t<0?0:+t,this.substring(t,t+e.length)===e)}}),Array.prototype.fill||Object.defineProperty(Array.prototype,"fill",{writable:!0,enumerable:!0,value:function(e){if(null==this)throw new TypeError("this is null or not defined");let t=Object(this),n=t.length>>>0,i=arguments[1],s=i>>0,r=s<0?Math.max(n+s,0):Math.min(s,n),o=arguments[2],a=void 0===o?n:o>>0,l=a<0?Math.max(n+a,0):Math.min(a,n);for(;r<l;)t[r]=e,r++;return t}}),Array.prototype.find||Object.defineProperty(Array.prototype,"find",{writable:!0,enumerable:!0,value:function(e){if(null==this)throw new TypeError('"this" is null or not defined');let t=Object(this);const n=t.length>>>0;if("function"!=typeof e)throw new TypeError("predicate must be a function");const i=arguments[1];let s=0;for(;s<n;){const n=t[s];if(e.call(i,n,s,t))return n;s++}}}),Uint8Array.prototype.slice||Object.defineProperty(Uint8Array.prototype,"slice",{value:Array.prototype.slice,writable:!0,enumerable:!0}),Uint16Array.prototype.slice||Object.defineProperty(Uint16Array.prototype,"slice",{value:Array.prototype.slice,writable:!0,enumerable:!0}),Uint32Array.prototype.slice||Object.defineProperty(Uint32Array.prototype,"slice",{value:Array.prototype.slice,writable:!0,enumerable:!0}),Uint8Array.prototype.fill||Object.defineProperty(Uint8Array.prototype,"fill",{value:Array.prototype.fill,writable:!0,enumerable:!0}),Uint16Array.prototype.fill||Object.defineProperty(Uint16Array.prototype,"fill",{value:Array.prototype.fill,writable:!0,enumerable:!0}),Uint32Array.prototype.fill||Object.defineProperty(Uint32Array.prototype,"fill",{value:Array.prototype.fill,writable:!0,enumerable:!0}),Uint8Array.prototype.some||Object.defineProperty(Uint8Array.prototype,"some",{value:Array.prototype.some,writable:!0,enumerable:!0}),Uint16Array.prototype.some||Object.defineProperty(Uint16Array.prototype,"some",{value:Array.prototype.some,writable:!0,enumerable:!0}),Uint32Array.prototype.some||Object.defineProperty(Uint32Array.prototype,"some",{value:Array.prototype.some,writable:!0,enumerable:!0}),Uint8Array.prototype.reverse||Object.defineProperty(Uint8Array.prototype,"reverse",{value:Array.prototype.reverse,writable:!0,enumerable:!0}),Uint16Array.prototype.reverse||Object.defineProperty(Uint16Array.prototype,"reverse",{value:Array.prototype.reverse,writable:!0,enumerable:!0}),Uint32Array.prototype.reverse||Object.defineProperty(Uint32Array.prototype,"reverse",{value:Array.prototype.reverse,writable:!0,enumerable:!0}),Math.imul||(Math.imul=function(e,t){const n=65535&e,i=65535&t;return n*i+((e>>>16&65535)*i+n*(t>>>16&65535)<<16>>>0)|0}),"function"!=typeof Object.assign&&Object.defineProperty(Object,"assign",{value:function(e,t){"use strict";if(null==e)throw new TypeError("Cannot convert undefined or null to object");let n=Object(e);for(let e=1;e<arguments.length;e++){let t=arguments[e];if(null!=t)for(let e in t)Object.prototype.hasOwnProperty.call(t,e)&&(n[e]=t[e])}return n},writable:!0,configurable:!0}),Promise.prototype.finally||(Promise.prototype.finally=Promise.prototype.finally||{finally(e){const t=t=>Promise.resolve(e()).then(t);return this.then((e=>t((()=>e))),(e=>t((()=>Promise.reject(e)))))}}.finally)};function t(e){e=e.replace(/\\/g,"/");const t=[];return e.split("/").forEach((e=>{".."===e&&t.length?t.pop():e&&"."!==e&&t.push(e)})),t}e.Lazy=class{constructor(e){this._func=e,this._evaluated=!1}get value(){return this._evaluated||(this._value=this._func(),this._evaluated=!0),this._value}},e.getNormalizedParts=t,e.normalizePath=function(e){return t(e).join("/")},e.relativePath=function(e,n){const i=t(e),s=t(n);let r=0;for(;i[r]===s[r]&&(r++,r!==i.length&&r!==s.length););const o=i.slice(r),a=s.slice(r);for(let e=0;e<o.length;e++)a.unshift("..");return a.join("/")},e.pathJoin=function(...e){let t="";return e.forEach((e=>{e.replace(/\\/g,"/"),e.lastIndexOf("/")===e.length-1&&(e=e.slice(0,e.length-1)),t+="/"+e})),t},e.toArray=function(e){if(Array.isArray(e))return e;let t=[];for(let n=0;n<e.length;++n)t.push(e[n]);return t}}(e.util||(e.util={}))}(pxsim||(pxsim={})),function(e){e.getWarningMessage=function(t){let n={type:"debugger",subtype:"warning",breakpointIds:[],message:t},i=e.runtime.currFrame;for(;null!=i;)n.breakpointIds.push(i.lastBrkId),i=i.parent;return n};function t(t,n){switch(typeof t){case"string":case"number":case"boolean":return t;case"function":return{text:"(function)",type:"function"};case"undefined":return null;case"object":if(!t)return null;if(t instanceof e.RefObject){n&&(n[t.id]=t);let i=e.RefObject.toDebugString(t),s=i.startsWith("[")?"array":i;return{id:t.id,preview:i,hasFields:null!==t.fields||i.startsWith("["),type:s}}return t._width&&t._height?{text:t._width+"x"+t._height,type:"image"}:{text:"(object)",type:"object"};default:throw new Error}}function n(n,s,r,o,a=!1){return function(n,r){const l={};for(let e of Object.keys(n))/^__/.test(e)||!/___\d+$/.test(e)||o&&-1===o.indexOf(e)||(l[e]=t(n[e],s));if(n.fields&&r)for(let e of r)e=e.substring(e.lastIndexOf(".")+1),l[e]=t(i(n.vtable.iface[e],n),s);if(n.fields)for(let e of Object.keys(n.fields).filter((e=>a||!e.startsWith("_"))))l[e]=t(n.fields[e],s);else if(n instanceof e.RefMap)for(const e of n.data)l[e.key]=t(e.val,s);else Array.isArray(n.data)?n.data.forEach(((e,n)=>{l[n]=t(e,s)})):void 0!==n._width&&void 0!==n._height&&(l.width=n._width,l.height=n._height,a&&void 0!==n._bpp&&(l.isMono=1===n._bpp));return l}(n,r)}function i(e,t){let n={pc:0,arg0:t,fn:e,parent:{}};for(;n.fn;)n=n.fn(n);return n.retval}function s(e,i){let s=e.fn?e.fn.info:null;if(s){let r={thisParam:t(e.argL,i),params:[]};if(s.argumentNames){const n=s.argumentNames;r.params=n.map(((n,s)=>({name:n,value:t(e["arg"+s],i)})))}return{locals:n(e,i),funcInfo:s,breakpointId:e.lastBrkId,callLocationId:e.callLocIdx,arguments:r}}}e.BreakpointMap=class{constructor(e){this.fileMap={},this.idMap={},e.forEach((e=>{const[t,n]=e;this.fileMap[n.source.path]||(this.fileMap[n.source.path]=[]),this.fileMap[n.source.path].push(e),this.idMap[t]=n}));for(const e in this.fileMap){const t=this.fileMap[e];this.fileMap[e]=t.sort((([,e],[,t])=>e.line===t.line?t.endLine===e.endLine?e.column-t.column:t.endLine-e.endLine:e.line-t.line))}}getById(e){return this.idMap[e]}verifyBreakpoint(e,t){const n=this.fileMap[e];let i;if(n)for(const[e,s]of n)s.line<=t.line&&s.endLine>=t.line&&(i=[e,s]);return i?(i[1].verified=!0,i):[-1,{verified:!1}]}},e.dumpHeap=n,e.injectEnvironmentGlobals=function(n,i){const s=e.runtime.environmentGlobals;if(!Object.keys(s).length)return;const r=n.environmentGlobals={};Object.keys(s).forEach((n=>r[n]=t(e.runtime.environmentGlobals[n],i)))},e.getBreakpointMsg=function(t,i,r){const o={},a={type:"debugger",subtype:"breakpoint",breakpointId:i,globals:n(e.runtime.globals,o,void 0,r),stackframes:[]};for(;null!=t;){let e=s(t,o);e&&a.stackframes.push(e),t=t.parent}return{msg:a,heap:o}};class r extends e.protocol.DebugSession{constructor(t){super();let n={onDebuggerBreakpoint:e=>this.onDebuggerBreakpoint(e),onDebuggerWarning:e=>this.onDebuggerWarning(e),onDebuggerResume:()=>this.onDebuggerResume(),onStateChanged:e=>this.onStateChanged(e)};this.driver=new e.SimulatorDriver(t,n)}runCode(t,n,i,s,r){this.breakpoints=s,this.projectDir&&this.fixBreakpoints(),this.sendEvent(new e.protocol.InitializedEvent),this.driver.run(t,{parts:n,fnArgs:i,boardDefinition:r})}stopSimulator(e=!1){this.driver.stop(e)}initializeRequest(e,t){e.body.supportsConditionalBreakpoints=!1,e.body.supportsHitConditionalBreakpoints=!1,e.body.supportsFunctionBreakpoints=!1,e.body.supportsEvaluateForHovers=!1,e.body.supportsStepBack=!1,e.body.supportsSetVariable=!1,e.body.supportsRestartFrame=!1,e.body.supportsStepInTargetsRequest=!1,e.body.supportsGotoTargetsRequest=!1,e.body.supportsCompletionsRequest=!1,e.body.supportsConfigurationDoneRequest=!0,this.sendResponse(e)}disconnectRequest(e,t){this.sendResponse(e),this.shutdown()}launchRequest(t,n){this.projectDir||(this.projectDir=e.util.normalizePath(n.projectDir),this.breakpoints&&this.fixBreakpoints()),this.sendResponse(t)}setBreakPointsRequest(t,n){t.body={breakpoints:[]};const i=[];n.breakpoints.forEach((s=>{if(this.breakpoints){const[r,o]=this.breakpoints.verifyBreakpoint(e.util.relativePath(this.projectDir,n.source.path),s);t.body.breakpoints.push(o),o.verified&&i.push(r)}else t.body.breakpoints.push({verified:!1})})),this.driver.setBreakpoints(i),this.sendResponse(t)}continueRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.Resume),this.sendResponse(t)}nextRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.StepOver),this.sendResponse(t)}stepInRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.StepInto),this.sendResponse(t)}stepOutRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.StepOut),this.sendResponse(t)}pauseRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.Pause),this.sendResponse(t)}threadsRequest(e){e.body={threads:[{id:r.THREAD_ID,name:"main"}]},this.sendResponse(e)}stackTraceRequest(e,t){if(this.lastBreak){const t=this.state.getFrames();e.body={stackFrames:t}}this.sendResponse(e)}scopesRequest(e,t){this.state&&(e.body={scopes:this.state.getScopes(t.frameId)}),this.sendResponse(e)}variablesRequest(e,t){this.state&&(e.body={variables:this.state.getVariables(t.variablesReference)}),this.sendResponse(e)}onDebuggerBreakpoint(t){if(this.lastBreak=t,this.state=new o(this.lastBreak,this.breakpoints,this.projectDir),t.exceptionMessage){const n=t.exceptionMessage.replace(/___\d+/g,"");this.sendEvent(new e.protocol.StoppedEvent("exception",r.THREAD_ID,n))}else this.sendEvent(new e.protocol.StoppedEvent("breakpoint",r.THREAD_ID))}onDebuggerWarning(e){}onDebuggerResume(){this.sendEvent(new e.protocol.ContinuedEvent(r.THREAD_ID,!0))}onStateChanged(t){switch(t){case e.SimulatorState.Paused:break;case e.SimulatorState.Running:this.sendEvent(new e.protocol.ContinuedEvent(r.THREAD_ID,!0));break;case e.SimulatorState.Stopped:this.sendEvent(new e.protocol.TerminatedEvent)}}fixBreakpoints(){for(const t in this.breakpoints.idMap){const n=this.breakpoints.idMap[t];n.source.path=e.util.pathJoin(this.projectDir,n.source.path),n.line=this.convertDebuggerLineToClient(n.line),n.endLine=this.convertDebuggerLineToClient(n.endLine),n.column=this.convertDebuggerColumnToClient(n.column),n.endColumn=this.convertDebuggerColumnToClient(n.endColumn)}}}r.THREAD_ID=1,e.SimDebugSession=r;class o{constructor(e,t,n){this._message=e,this._map=t,this._dir=n,this._currentId=1,this._frames={},this._vars={};const i=this.nextId();this._vars[i]=this.getVariableValues(this._message.globals),this._globalScope={name:"Globals",variablesReference:i,expensive:!1}}getFrames(){return this._message.stackframes.map(((e,t)=>{const n=this._map.getById(e.breakpointId);if(n)return this._frames[e.breakpointId]=e,{id:e.breakpointId,name:e.funcInfo?e.funcInfo.functionName:0===t?"main":"anonymous",line:n.line,column:n.column,endLine:n.endLine,endColumn:n.endLine,source:n.source}})).filter((e=>!!e))}getScopes(e){const t=this._frames[e];if(t){const e=this.nextId();return this._vars[e]=this.getVariableValues(t.locals),[{name:"Locals",variablesReference:e,expensive:!1},this._globalScope]}return[this._globalScope]}getVariables(e){const t=this._vars[e];return t&&t.value||[]}getVariableValues(t){return new e.util.Lazy((()=>{const e=[];for(const n in t){const i=t[n];let s,r=0;null===i?s="null":void 0===i?s="undefined":"object"==typeof i?(s="(object)",r=this.nextId(),this._vars[r]=this.getVariableValues(i)):s=i.toString();const o=n.substr(0,n.lastIndexOf("___"));e.push({name:o,value:s,variablesReference:r})}return e}))}nextId(){return this._currentId++}}}(pxsim||(pxsim={})),function(e){let t,n;function i(e=0){function t(){try{window.print()}catch(e){}}e?setTimeout(t,e):t()}function s(e,t){r({type:"pxtsim",action:"event",tick:e,data:t})}function r(e){"undefined"!=typeof window&&window.parent&&window.parent!==window&&window.parent.postMessage(e,"*")}function o(){setInterval((()=>{e.Runtime.postMessage({type:"simulator",command:"reload"})}),3e3)}!function(e){let t;!function(e){e[e.Player=0]="Player",e[e.Reaction=1]="Reaction"}(t=e.IconType||(e.IconType={}))}(t=e.multiplayer||(e.multiplayer={})),e.print=i,function(t){function n(t){t.origin;let n=t.data||{},o=n.type;if(o)switch(o){case"run":l(n);break;case"instructions":e.instructions.renderInstructions(n);break;case"stop":a();break;case"mute":c(n.mute);break;case"stopsound":e.AudioContextManager.stopAll();break;case"print":i();break;case"recorder":!function(e){if(!r)return;switch(e.action){case"start":r.startRecording(e.width);break;case"stop":r.stopRecording()}}(n);break;case"screenshot":e.Runtime.postScreenshotAsync(n);break;case"custom":e.handleCustomMessage&&e.handleCustomMessage(n);break;case"pxteditor":break;case"debugger":r&&r.handleDebuggerMsg(n);break;case"simulator":let t=n;switch(t.command){case"focus":s("simulator.focus",{timestamp:t.timestamp});break;case"blur":s("simulator.blur",{timestamp:t.timestamp})}default:!function(e){if(!r||r.dead)return;r.board.receiveMessage(e)}(n)}}let r;function a(){r&&(r.kill(),r.board&&r.board.kill())}function l(t){a(),t.mute&&c(t.mute),t.localizedStrings&&e.localization.setLocalizedStrings(t.localizedStrings);const n=new e.Runtime(t);r=n,n.board.initAsync(t).then((()=>{n===r&&n.run((t=>{e.dumpLivePointers(),e.Runtime.postMessage({type:"toplevelcodefinished"})}))}))}function c(t){e.AudioContextManager.mute(t)}t.start=function(){window.addEventListener("message",n,!1),t.frameid=window.location.hash.slice(1),function(){if("serviceWorker"in navigator&&-1!==window.location.href.indexOf("---simulator")&&!e.U.isLocalHost()){const e=window.location.pathname,t=e.substring(1,e.indexOf("---"));navigator.serviceWorker.controller&&navigator.serviceWorker.addEventListener("message",(e=>{const n=e.data;n&&"serviceworker"===n.type&&"activated"===n.state&&n.ref===t&&o()}));const n=window.location.href.replace(/---simulator.*$/,"---simserviceworker");navigator.serviceWorker.register(n).then((function(e){console.log("Simulator ServiceWorker registration successful with scope: ",e.scope)}),(function(e){console.log("Simulator ServiceWorker registration failed: ",e)}))}}(),e.Runtime.postMessage({type:"ready",frameid:t.frameid})},t.stop=a,t.run=l}(n=e.Embed||(e.Embed={})),e.tickEvent=s,e.reportError=function(e,t,n){r({type:"pxtsim",action:"event",tick:"error",category:e,message:t,data:n})},e.reload=o}(pxsim||(pxsim={})),pxsim.util.injectPolyphils(),"undefined"!=typeof window&&window.addEventListener("load",(function(e){pxsim.Embed.start()})),function(e){!function(t){const n=e=>`${e}x`,i=.95,[s,r]=[816*i,1056*i],o=s-86.4,a=r-86.4,[l,c]=[1,1],u=24,d=o/c-48*c,h=`\n .instr-panel {\n margin: 20px;\n padding: 24px;\n border-width: 4px;\n border-color: gray;\n border-style: solid;\n border-radius: 20px;\n display: inline-block;\n width: ${d}px;\n height: ${a/l-48*l}px;\n position: relative;\n overflow: hidden;\n page-break-inside: avoid;\n }\n .board-svg {\n margin: 0 auto;\n display: block;\n position: absolute;\n bottom: 24px;\n left: ${(d-465)/2+u}px;\n }\n .panel-num-outer {\n position: absolute;\n left: -4px;\n top: -4px;\n width: 120px;\n height: 120px;\n border-width: 4px;\n border-style: solid;\n border-color: gray;\n border-radius: 20px 0 20px 0;\n }\n .panel-num {\n margin: 10px 0;\n text-align: center;\n font-size: 80px;\n }\n .cmp-div {\n display: inline-block;\n }\n .reqs-div {\n margin-left: 144px;\n margin-top: 5px;\n }\n .partslist-wire,\n .partslist-cmp {\n margin: 10px;\n }\n .partslist-wire {\n display: inline-block;\n }\n `;function p(t,n){let i=document.createElementNS("http://www.w3.org/2000/svg","svg"),s={l:0,t:0,w:0,h:0},r=document.createElementNS("http://www.w3.org/2000/svg","svg");i.appendChild(r),r.appendChild(t.el);let o={viewBox:`${t.x} ${t.y} ${t.w} ${t.h}`,preserveAspectRatio:"xMidYMid"};s.w=t.w,s.h=t.h;let a=e=>{s.h*=e,s.w*=e,o.width=s.w,o.height=s.h};n.cmpScale&&a(n.cmpScale),n.cmpWidth&&n.cmpWidth<s.w?a(n.cmpWidth/s.w):n.cmpHeight&&n.cmpHeight<s.h&&a(n.cmpHeight/s.h),e.svg.hydrate(r,o);let l=s.l,c=s.t,u=s.w,d=s.h,h=e=>{if(e<s.l){let t=s.l-e;s.l=e,s.w+=t}},p=e=>{let t=s.l+s.w;if(t<e){let n=e-t;s.w+=n}},f=e=>{if(e<s.t){let t=s.t-e;s.t=e,s.h+=t}},m=e=>{let t=s.t+s.h;if(t<e){let n=e-t;s.h+=n}},[g,b]=[-.3,.3];const y=[1.4,1];if(n&&n.top){let t=n.topSize,s=t/y[0],r=t/y[1],[o,a]=[l+u/2,c-3-r/2],d=e.visuals.mkTxt(o,a,t,0,n.top,g,b);e.U.addClass(d,"cmp-lbl"),i.appendChild(d);let m=s*n.top.length;f(a-r/2),h(o-m/2),p(o+m/2)}if(n&&n.bot){let t=n.botSize,s=t/y[0],r=t/y[1],[o,a]=[l+u/2,c+d+3+r/2],f=e.visuals.mkTxt(o,a,t,0,n.bot,g,b);e.U.addClass(f,"cmp-lbl"),i.appendChild(f);let v=s*n.bot.length;m(a+r/2),h(o-v/2),p(o+v/2)}if(n&&n.right){let t=n.rightSize,s=t/y[1],r=t/y[0]*n.right.length,[o,a]=[l+u+5+r/2,c+d/2],h=e.visuals.mkTxt(o,a,t,0,n.right,g,b);e.U.addClass(h,"cmp-lbl"),i.appendChild(h),f(a-s/2),p(o+r/2),m(a+s/2)}if(n&&n.left){let t=n.leftSize,s=t/y[1],r=t/y[0]*n.left.length,[o,a]=[l-5-r/2,c+d/2],u=e.visuals.mkTxt(o,a,t,0,n.left,g,b);e.U.addClass(u,"cmp-lbl"),i.appendChild(u),f(a-s/2),h(o-r/2),m(a+s/2)}let v={viewBox:`${s.l} ${s.t} ${s.w} ${s.h}`,width:1.7*s.w,height:1.7*s.h,preserveAspectRatio:"xMidYMid"};e.svg.hydrate(i,v);let w=document.createElement("div");return w.appendChild(i),w}function f(t,n){let i,s=e.runtime.board;if("wire"==t)i=e.visuals.mkWirePart([0,0],n.wireClr||"red",n.crocClips);else{let n=t;if("string"==typeof n.builtIn){i=(0,s.builtinPartVisuals[n.builtIn])([0,0])}else i=e.visuals.mkGenericPartSVG(n)}return p(i,n)}function m(t,n,i=!1){const s={state:e.runtime.board,boardDef:t.boardDef,forceBreadboardLayout:!0,forceBreadboardRender:t.allAlloc.requiresBreadboard,partDefs:t.cmpDefs,maxWidth:`${n}px`,fnArgs:t.fnArgs,wireframe:i,partsList:[]};let r=new e.visuals.BoardHost(e.visuals.mkBoardView({visual:s.boardDef.visual,boardDef:s.boardDef,wireframe:s.wireframe}),s),o=r.getView();return e.U.addClass(o,"board-svg"),r}function g(){let t=document.createElement("div");return e.U.addClass(t,"instr-panel"),t}function b(t){let i=g();var s;let r=p((s=t.boardDef,e.visuals.mkBoardView({visual:s.visual,boardDef:s}).getView()),{left:n(1),leftSize:30,cmpScale:.17});i.appendChild(r);let o=p(new e.visuals.Breadboard({}).getSVGAndSize(),{left:n(1),leftSize:30,cmpScale:.25});return i.appendChild(o),t.allCmps.forEach((t=>{let s=1;"buttonpair"===t.visual.builtIn&&(s=2);let r=f(t.visual,{left:n(s),leftSize:30,cmpScale:.3});e.U.addClass(r,"partslist-cmp"),i.appendChild(r)})),t.allWireColors.forEach((s=>{let r=t.colorToWires[s].length,o=t.boardDef.pinStyles[s]||"female",a=f("wire",{left:n(r),leftSize:20,wireClr:s,cmpScale:.23,crocClips:"croc"==o});e.U.addClass(a,"partslist-wire"),i.appendChild(a)})),i}function y(t,n){let i=g(),s=m(n,465,!0);!function(t,n,i){let s=t.getView();n>0&&e.U.addClass(s,"grayed");for(let s=0;s<=n;s++){let r=i.stepToCmps[s];r&&r.forEach((i=>{let r=t.addPart(i);s===n&&(i.breadboardConnections.forEach((e=>t.highlightBreadboardPin(e))),e.U.addClass(r.element,"notgrayed"))}));let o=i.stepToWires[s];o&&o.forEach((e=>{let i=t.addWire(e);i&&s===n&&("breadboard"==e.start.type?t.highlightBreadboardPin(e.start):t.highlightBoardPin(e.start.pin),"breadboard"==e.end.type?t.highlightBreadboardPin(e.end):t.highlightBoardPin(e.end.pin),t.highlightWire(i))}))}}(s,t,n),i.appendChild(s.getView());let r=document.createElement("div");e.U.addClass(r,"panel-num-outer"),e.U.addClass(r,"noselect"),i.appendChild(r);let o=document.createElement("div");e.U.addClass(o,"panel-num"),o.textContent=t+1+"",r.appendChild(o);let a=document.createElement("div");e.U.addClass(a,"reqs-div"),i.appendChild(a);let l=n.stepToWires[t]||[],c=e=>{if("breadboard"===e.type){let{row:t,col:n}=e;return`(${t},${n})`}return e.pin};return l.forEach((t=>{let i=!1;"dalboard"==t.end.type&&(i="croc"==n.boardDef.pinStyles[t.end.pin]);let s=f("wire",{top:c(t.end),topSize:10,bot:c(t.start),botSize:10,wireClr:t.color,cmpHeight:40,crocClips:i});e.U.addClass(s,"cmp-div"),a.appendChild(s)})),(n.stepToCmps[t]||[]).forEach((t=>{let n;n="buttonpair"===t.visual.builtIn?[t.breadboardConnections[0],t.breadboardConnections[2]]:[t.breadboardConnections[0]],n.forEach(((n,i)=>{let s;if(n){let{row:e,col:t}=n;s=`(${e},${t})`}else s="";let r=1.5;"buttonpair"===t.visual.builtIn&&(r*=.5);let o=f(t.visual,{top:s,topSize:10,cmpHeight:50,cmpScale:r});e.U.addClass(o,"cmp-div"),a.appendChild(o)}))})),i}function v(t,n){n.boardDef.pinStyles||(n.boardDef.pinStyles={}),n.configData&&e.setConfigData(n.configData.cfg,n.configData.cfgKey);const i={type:"run",code:"",boardDefinition:n.boardDef,partDefinitions:n.partDefinitions};e.runtime=new e.Runtime(i),e.runtime.board=null,e.initCurrentRuntime(i);let s=document.createElement("style");s.textContent+=h,document.head.appendChild(s);const r=n.partDefinitions;let o=new e.visuals.Breadboard({}),a=function(t){let n=e.allocateDefinitions(t),i=[],s=[],r=1;n.partsAndWires.forEach((e=>{let t=e.part,n=e.wires;e.assembly.forEach(((e,o)=>{e.part&&t&&(s[r+o]=[t]),e.wireIndices&&e.wireIndices.length>0&&n&&(i[r+o]=e.wireIndices.map((e=>n[e])))})),r+=e.assembly.length}));let o=r-1,a=n.partsAndWires.map((e=>e.part)).filter((e=>!!e)),l=n.partsAndWires.map((e=>e.wires||[])).reduce(((e,t)=>e.concat(t)),[]),c={},u=[];return l.forEach((e=>{c[e.color]||(c[e.color]=[],u.push(e.color)),c[e.color].push(e)})),{boardDef:t.boardDef,cmpDefs:t.partDefs,fnArgs:t.fnArgs,allAlloc:n,stepToWires:i,stepToCmps:s,allWires:l,allCmps:a,lastStep:o,colorToWires:c,allWireColors:u}}({boardDef:n.boardDef,partDefs:r,partsList:n.parts,fnArgs:n.fnArgs,getBBCoord:o.getCoord.bind(o)});a.allAlloc.requiresBreadboard=!0;!function(e){let t=document.getElementById("front-panel"),n=m(e,400,!1);n.addAll(e.allAlloc),t.appendChild(n.getView())}(a);let l=b(a);t.appendChild(l);for(let e=0;e<=a.lastStep;e++){let n=y(e,a);t.appendChild(n)}n.print&&e.print(2e3)}t.renderParts=v,t.renderInstructions=function(e){document.getElementById("proj-title").innerText=e.options.name||"",v(document.body,e.options)}}(e.instructions||(e.instructions={}))}(pxsim||(pxsim={})),function(e){function t(e,t="sim: check failed"){if(!e)throw new Error(t)}e.quiet=!1,e.check=t,e.title="";let n,i,s,r,o,a={},l={};e.getConfig=function(e){return l.hasOwnProperty(e+"")?l[e+""]:null},e.getConfigKey=function(e){return a.hasOwnProperty(e)?a[e]:null},e.getAllConfigKeys=function(){return Object.keys(a)},e.setConfigKey=function(e,t){a[e]=t},e.setConfig=function(e,t){l[e]=t},e.setConfigData=function(e,t){l=e,a=t},e.getConfigData=function(){return{cfg:l,cfgKey:a}},e.setTitle=function(t){e.title=t};class c{constructor(){e.runtime?this.id=e.runtime.registerLiveObject(this):this.id=0}destroy(){}scan(t){throw e.U.userError("scan not implemented")}gcKey(){throw e.U.userError("gcKey not implemented")}gcSize(){throw e.U.userError("gcSize not implemented")}gcIsStatic(){return!1}print(){e.runtime&&e.runtime.refCountingDebug&&console.log(`RefObject id:${this.id}`)}toDebugString(){return"(object)"}static toAny(e){return e&&e.toAny?e.toAny():e}static toDebugString(e){return null===e?"null":void 0===e?"undefined;":e.vtable&&e.vtable.name?"_Map"===e.vtable.name&&e instanceof f?"(object)":e.vtable.name:e.toDebugString?e.toDebugString():"string"==typeof e?JSON.stringify(e):e.toString()}}e.RefObject=c;class u{constructor(e,t,n){this.func=e,this.caps=t,this.args=n}}e.FnWrapper=u;class d extends c{constructor(){super(...arguments),this.fields={}}scan(e){for(let t of Object.keys(this.fields))e(t,this.fields[t])}gcKey(){return this.vtable.name}gcSize(){return this.vtable.numFields+1}destroy(){this.fields=null,this.vtable=null}print(){e.runtime&&e.runtime.refCountingDebug&&console.log(`RefRecord id:${this.id} (${this.vtable.name})`)}}e.RefRecord=d;class h extends c{constructor(){super(...arguments),this.fields=[]}scan(e){for(let t=0;t<this.fields.length;++t)e("_cap"+t,this.fields[t])}gcKey(){return e.functionName(this.func)}gcSize(){return this.fields.length+3}isRef(e){return t(0<=e&&e<this.fields.length),e<this.len}ldclo(e){return t(0<=(e>>=2)&&e<this.fields.length),this.fields[e]}destroy(){this.fields=null,this.func=null}print(){e.runtime&&e.runtime.refCountingDebug&&console.log(`RefAction id:${this.id} len:${this.fields.length}`)}}e.RefAction=h,function(t){t.seedAddRandom=function(e){},t.mkAction=function(e,t){let n=new h;n.len=e,n.func=t;for(let t=0;t<e;++t)n.fields.push(null);return n},t.runAction=function(t,n){let i=e.getResume();i(t instanceof h?new u(t.func,t.fields,n):new u(t,null,n))};let n={};t.dumpPerfCounters=function(){if(!e.runtime||!e.runtime.perfCounters)return;let t="calls,us,name\n";for(let n of e.runtime.perfCounters){n.lastFew.sort();const e=n.lastFew[n.lastFew.length>>1];t+=`${n.numstops},${n.value},${n.name},${e}\n`}!function(e){let t="";const i=(e,n)=>{t+=e.length>=n?e:(" "+e).slice(-n)},s=e=>i(""+Math.round(e),6),r=(e,n)=>{i(Math.round(n)+"",8),t+=" /",s(e),t+=" =",s(n/e)};for(let i of e.split(/\n/)){if(!i)continue;if(!/^\d/.test(i))continue;const e=i.split(/,/);let l=n[e[2]];l||(n[e[2]]=l={stops:0,us:0,meds:[]}),o=e[2],a=25,t+=o.length>=a?o:(o+" ").slice(0,a);const c=parseInt(e[0]),u=parseInt(e[1]);r(c,u),t+=" |",r(c-l.stops,u-l.us),t+=" ~";const d=parseInt(e[3]);s(d),l.meds.length>10&&l.meds.shift(),l.meds.push(d);const h=l.meds.slice();h.sort(((e,t)=>e-t));const p=h[h.length>>1];t+=" ~~",s(p),l.stops=c,l.us=u,t+="\n"}var o,a;console.log(t)}(t)}}(n=e.pxtcore||(e.pxtcore={}));class p extends c{constructor(){super(...arguments),this.v=void 0}scan(e){e("*",this.v)}gcKey(){return"LOC"}gcSize(){return 2}destroy(){}print(){e.runtime&&e.runtime.refCountingDebug&&console.log(`RefRefLocal id:${this.id} v:${this.v}`)}}e.RefRefLocal=p;class f extends c{constructor(){super(...arguments),this.vtable=e.mkMapVTable(),this.data=[]}scan(e){for(let t of this.data)e(t.key,t.val)}gcKey(){return"{...}"}gcSize(){return 2*this.data.length+4}findIdx(e){e+="";for(let t=0;t<this.data.length;++t)if(this.data[t].key==e)return t;return-1}destroy(){super.destroy();for(let e=0;e<this.data.length;++e)this.data[e].val=0;this.data=[]}print(){e.runtime&&e.runtime.refCountingDebug&&console.log(`RefMap id:${this.id} size:${this.data.length}`)}toAny(){const e={};return this.data.forEach((t=>{e[t.key]=c.toAny(t.val)})),e}}function m(){e.runtime&&e.runtime.dumpLivePointers()}e.RefMap=f,e.dumpLivePointers=m,function(e){e.toString=function(e){return null===e?"null":void 0===e?"undefined":e.toString()},e.toBoolDecr=function(e){return!!e},e.toBool=function(e){return!!e}}(i=e.numops||(e.numops={})),function(e){e.toInt=function(e){return 0|e},e.toFloat=function(e){return e},e.ignore=function(e){return e}}(s=e.langsupp||(e.langsupp={})),function(t){t.ptrOfLiteral=function(e){return e},t.debugMemLeaks=function(){m()},t.templateHash=function(){return 0},t.programHash=function(){return 0},t.programName=function(){return e.title},t.programSize=function(){return 0},t.afterProgramPage=function(){return 0},t.getConfig=function(t,n){let i=e.getConfig(t);return null==i?n:i},t.toInt=function(e){return e>>0},t.toUInt=function(e){return e>>>0},t.toDouble=function(e){return e},t.toFloat=function(e){return e},t.fromInt=function(e){return e},t.fromUInt=function(e){return e},t.fromDouble=function(e){return e},t.fromFloat=function(e){return e},t.fromBool=function(e){return!!e}}(n=e.pxtcore||(e.pxtcore={})),function(n){function i(e,t){if(t+="",e instanceof d){return e.fields[t]}let n=e.findIdx(t);if(!(n<0))return e.data[n].val}function s(e,t,n){if(t+="",e instanceof d){return void(e.fields[t]=n)}let i=e.findIdx(t);i<0?e.data.push({key:t,val:n}):e.data[i].val=n}n.toInt8=function(e){return(255&e)<<24>>24},n.toInt16=function(e){return(65535&e)<<16>>16},n.toInt32=function(e){return 0|e},n.toUInt32=function(e){return e>>>0},n.toUInt8=function(e){return 255&e},n.toUInt16=function(e){return 65535&e},n.nullFix=function(e){return null==e||!1===e?0:!0===e?1:e},n.nullCheck=function(t){null==t&&e.U.userError("Dereferencing null/undefined value.")},n.panic=function(t){e.U.userError("PANIC! Code "+t)},n.stringToBool=function(e){return e?1:0},n.ptrToBool=function(e){return e?1:0},n.emptyToNull=function(e){return""==e?0:e},n.ldlocRef=function(e){return e.v},n.stlocRef=function(e,t){e.v=t},n.mklocRef=function(){return new p},n.stclo=function(e,n,i){return t(0<=n&&n<e.fields.length),t(null===e.fields[n]),e.fields[n]=i,e},n.runtimeWarning=function(t){e.Runtime.postMessage(e.getWarningMessage(t))},n.mkMap=function(){return new f},n.mapGet=function(e,t){return i(e,n.mapKeyNames[t])},n.mapSet=function(e,t,i){return s(e,n.mapKeyNames[t],i)},n.mapGetByString=i,n.mapDeleteByString=function(e,t){e instanceof f||n.panic(923);let i=e.findIdx(t);return i>=0&&e.data.splice(i,1),!0},n.mapSetGeneric=s,n.mapGetGeneric=i,n.mapSetByString=s,n.keysOf=function(t){let n=new e.RefCollection;if(t instanceof f)for(let e of t.data)n.push(e.key);return n}}(r=e.pxtrt||(e.pxtrt={})),function(e){e.mkClassInstance=function(e){t(!!e.methods);let n=new d;return n.vtable=e,n},e.switch_eq=function(e,t){return e==t},e.typeOf=function(e){return typeof e}}(n=e.pxtcore||(e.pxtcore={})),function(t){t.panic=r.panic,t.pause=function(t){let n=e.getResume();e.runtime.schedule((()=>{n()}),t)},t.runInBackground=function(t){e.runtime.runFiberAsync(t)},t.forever=function(t){r.nullCheck(t),function n(){e.runtime.runFiberAsync(t).then((()=>e.U.delay(20))).then(n)}()}}(o=e.thread||(e.thread={}))}(pxsim||(pxsim={})),function(e){class t extends e.RefObject{constructor(){super(),this.data=[]}scan(e){for(let t=0;t<this.data.length;++t)e("["+t+"]",this.data[t])}gcKey(){return"[...]"}gcSize(){return this.data.length+2}toArray(){return this.data.slice(0)}toAny(){return this.data.map((t=>e.RefObject.toAny(t)))}toDebugString(){let t="[";for(let n=0;n<this.data.length;++n){n>0&&(t+=",");let i=e.RefObject.toDebugString(this.data[n]);if(t.length+i.length>100){0==n&&(t+=i.substr(0,100)),t+="...";break}t+=i}return t+="]",t}destroy(){let e=this.data;for(let t=0;t<e.length;++t)e[t]=0;this.data=[]}isValidIndex(e){return e>=0&&e<this.data.length}push(e){this.data.push(e)}pop(){return this.data.pop()}getLength(){return this.data.length}setLength(e){this.data.length=e}getAt(e){return this.data[e]}setAt(e,t){this.data[e]=t}insertAt(e,t){this.data.splice(e,0,t)}removeAt(e){return this.data.splice(e,1)[0]}indexOf(e,t){return this.data.indexOf(e,t)}print(){}}let n,i,s,r,o,a,l,c;e.RefCollection=t,function(n){function i(t,n){if(e.pxtrt.nullCheck(t),t.isValidIndex(n))return t.removeAt(n)}function s(t,n,i){return e.pxtrt.nullCheck(t),t.indexOf(n,i)}n.mk=function(){return new t},n.isArray=function(e){return e instanceof t},n.length=function(t){return e.pxtrt.nullCheck(t),t.getLength()},n.setLength=function(t,n){e.pxtrt.nullCheck(t),t.setLength(n)},n.push=function(t,n){e.pxtrt.nullCheck(t),t.push(n)},n.pop=function(t,n){return e.pxtrt.nullCheck(t),t.pop()},n.getAt=function(t,n){return e.pxtrt.nullCheck(t),t.getAt(n)},n.removeAt=i,n.insertAt=function(t,n,i){e.pxtrt.nullCheck(t),t.insertAt(n,i)},n.setAt=function(t,n,i){e.pxtrt.nullCheck(t),t.setAt(n,i)},n.indexOf=s,n.removeElement=function(t,n){e.pxtrt.nullCheck(t);let r=s(t,n,0);return r>=0?(i(t,r),1):0}}(n=e.Array_||(e.Array_={})),function(e){e.imul=Math.imul||function(e,t){const n=65535&e,i=65535&t;return n*i+((e>>>16&65535)*i+n*(t>>>16&65535)<<16>>>0)|0},e.idiv=function(e,t){return(0|e)/(0|t)|0},e.round=function(e){return Math.round(e)},e.roundWithPrecision=function(e,t){if((t|=0)<=0)return Math.round(e);if(0==e)return 0;let n=0;for(;0==n&&t<21;){const i=Math.pow(10,t++);n=Math.round(e*i+Number.EPSILON)/i}return n},e.ceil=function(e){return Math.ceil(e)},e.floor=function(e){return Math.floor(e)},e.sqrt=function(e){return Math.sqrt(e)},e.pow=function(e,t){return Math.pow(e,t)},e.clz32=function(e){return Math.clz32(e)},e.log=function(e){return Math.log(e)},e.log10=function(e){return Math.log10(e)},e.log2=function(e){return Math.log2(e)},e.exp=function(e){return Math.exp(e)},e.sin=function(e){return Math.sin(e)},e.sinh=function(e){return Math.sinh(e)},e.cos=function(e){return Math.cos(e)},e.cosh=function(e){return Math.cosh(e)},e.tan=function(e){return Math.tan(e)},e.tanh=function(e){return Math.tanh(e)},e.asin=function(e){return Math.asin(e)},e.asinh=function(e){return Math.asinh(e)},e.acos=function(e){return Math.acos(e)},e.acosh=function(e){return Math.acosh(e)},e.atan=function(e){return Math.atan(e)},e.atanh=function(e){return Math.atanh(e)},e.atan2=function(e,t){return Math.atan2(e,t)},e.trunc=function(e){return e>0?Math.floor(e):Math.ceil(e)},e.random=function(){return Math.random()},e.randomRange=function(e,t){if(e==t)return e;if(e>t){let n=e;e=t,t=n}return Math.floor(e)==e&&Math.floor(t)==t?e+Math.floor(Math.random()*(t-e+1)):e+Math.random()*(t-e)}}(i=e.Math_||(e.Math_={})),function(t){function n(t,n){return e.pxtrt.nullFix(t)==e.pxtrt.nullFix(n)}t.lt=function(e,t){return e<t},t.le=function(e,t){return e<=t},t.neq=function(e,t){return!n(e,t)},t.eq=n,t.eqDecr=function(t,n){return e.pxtrt.nullFix(t)==e.pxtrt.nullFix(n)},t.gt=function(e,t){return e>t},t.ge=function(e,t){return e>=t},t.div=function(e,t){return 0|Math.floor(e/t)},t.mod=function(e,t){return e%t},t.bnot=function(e){return~e},t.toString=function(e){return e+""}}(s=e.Number_||(e.Number_={})),function(e){e.adds=function(e,t){return e+t|0},e.subs=function(e,t){return e-t|0},e.divs=function(e,t){return 0|Math.floor(e/t)},e.muls=function(e,t){return i.imul(e,t)},e.ands=function(e,t){return e&t},e.orrs=function(e,t){return e|t},e.eors=function(e,t){return e^t},e.lsls=function(e,t){return e<<t},e.lsrs=function(e,t){return e>>>t},e.asrs=function(e,t){return e>>t},e.bnot=function(e){return~e},e.ignore=function(e){return e}}(r=e.thumb||(e.thumb={})),function(e){function t(e){return e<<16>>16}e.adds=function(e,n){return t(e+n)},e.subs=function(e,n){return t(e-n)},e.divs=function(e,n){return t(Math.floor(e/n))},e.muls=function(e,n){return t(i.imul(e,n))},e.ands=function(e,n){return t(e&n)},e.orrs=function(e,n){return t(e|n)},e.eors=function(e,n){return t(e^n)},e.lsls=function(e,n){return t(e<<n)},e.lsrs=function(e,t){return(65535&e)>>>t},e.asrs=function(e,n){return t(e>>n)},e.bnot=function(e){return~e},e.ignore=function(e){return e}}(o=e.avr||(e.avr={})),function(t){t.stringConv=function(t){const n=e.getResume();t instanceof e.RefRecord&&t.vtable.toStringMethod?e.runtime.runFiberAsync(t.vtable.toStringMethod,t).then((()=>{n(e.runtime.currFrame.retval+"")})):n(t+"")},t.mkEmpty=function(){return""},t.fromCharCode=function(e){return String.fromCharCode(e)},t.toNumber=function(e){return parseFloat(e)},t.concat=function(e,t){return e+t},t.substring=function(t,n,i){return e.pxtrt.nullCheck(t),t.slice(n,n+i)},t.equals=function(e,t){return e==t},t.compare=function(e,t){return e==t?0:e<t?-1:1},t.compareDecr=function(e,t){return e==t?0:e<t?-1:1},t.length=function(e){return e.length},t.substr=function(e,t,n){return e.substr(t,n)},t.charAt=function(e,t){return e.charAt(t)},t.charCodeAt=function(t,n){return e.pxtrt.nullCheck(t),function(t,n){return e.pxtrt.nullCheck(t),0<=n&&n<t.length}(t,n)?t.charCodeAt(n):0},t.indexOf=function(t,n,i){return e.pxtrt.nullCheck(t),null==n?-1:t.indexOf(n,i)},t.lastIndexOf=function(t,n,i){return e.pxtrt.nullCheck(t),null==n?-1:t.lastIndexOf(n,i)},t.includes=function(t,n,i){return e.pxtrt.nullCheck(t),null!=n&&t.includes(n,i)}}(a=e.String_||(e.String_={})),function(e){e.toString=function(e){return e?"true":"false"},e.bang=function(e){return!e}}(l=e.Boolean_||(e.Boolean_={}));class u extends e.RefObject{constructor(e){super(),this.data=e,this.isStatic=!1}scan(e){}gcKey(){return"Buffer"}gcSize(){return 2+(this.data.length+3>>2)}gcIsStatic(){return this.isStatic}print(){}toDebugString(){return c.toHex(this)}}e.RefBuffer=u,function(t){let n;function i(t){let i=function(t){switch(t){case n.Int8LE:return-1;case n.UInt8LE:return 1;case n.Int16LE:return-2;case n.UInt16LE:return 2;case n.Int32LE:return-4;case n.UInt32LE:return 4;case n.Int8BE:return-10;case n.UInt8BE:return 10;case n.Int16BE:return-20;case n.UInt16BE:return 20;case n.Int32BE:return-40;case n.UInt32BE:return 40;case n.Float32LE:return 4;case n.Float32BE:return 40;case n.Float64LE:return 8;case n.Float64BE:return 80;default:throw e.U.userError("bad format")}}(t),s=!1;i<0&&(s=!0,i=-i);let r=!1;return i>=10&&(r=!0,i/=10),{size:i,signed:s,swap:r,isFloat:t>=n.Float32LE}}function s(e){return new u(new Uint8Array(e))}function r(t,n){return e.pxtrt.nullCheck(t),0<=n&&n<t.data.length}function o(e,t){return r(e,t)?e.data[t]:0}function a(t){t.isStatic&&e.U.userError("Writing to read only buffer.")}function l(e,t,n){r(e,t)&&(a(e),e.data[t]=n)}function c(e,t,n=0,i=-1){n<0||n>e.data.length||(i<0&&(i=e.data.length),i=Math.min(i,e.data.length-n),a(e),e.data.fill(t,n,n+i))}function d(e,t,n,i,s){if(n.buffer===e.buffer)d(e,t,n.slice(i,i+s),0,s);else for(let r=0;r<s;++r)e[t+r]=n[i+r]}!function(e){e[e.Int8LE=1]="Int8LE",e[e.UInt8LE=2]="UInt8LE",e[e.Int16LE=3]="Int16LE",e[e.UInt16LE=4]="UInt16LE",e[e.Int32LE=5]="Int32LE",e[e.Int8BE=6]="Int8BE",e[e.UInt8BE=7]="UInt8BE",e[e.Int16BE=8]="Int16BE",e[e.UInt16BE=9]="UInt16BE",e[e.Int32BE=10]="Int32BE",e[e.UInt32LE=11]="UInt32LE",e[e.UInt32BE=12]="UInt32BE",e[e.Float32LE=13]="Float32LE",e[e.Float64LE=14]="Float64LE",e[e.Float32BE=15]="Float32BE",e[e.Float64BE=16]="Float64BE"}(n=t.NumberFormat||(t.NumberFormat={})),t.getNumber=function(e,t,n){let s=i(t);if(s.isFloat){let t=e.data.buffer.slice(n,n+s.size);if(s.swap){new Uint8Array(t).reverse()}return 4==s.size?new Float32Array(t)[0]:new Float64Array(t)[0]}let r=0;for(let t=0;t<s.size;++t){r<<=8;let i=s.swap?n+t:n+s.size-t-1;r|=e.data[i]}if(s.signed){let e=32-8*s.size;r=r<<e>>e}else r>>>=0;return r},t.setNumber=function(e,t,n,s){let r=i(t);if(r.isFloat){let t=new Uint8Array(r.size);4==r.size?new Float32Array(t.buffer)[0]=s:new Float64Array(t.buffer)[0]=s,r.swap&&t.reverse();for(let i=0;i<r.size;++i)e.data[n+i]=t[i]}else for(let t=0;t<r.size;++t){let i=r.swap?n+r.size-t-1:n+t;e.data[i]=255&s,s>>=8}},t.createBuffer=s,t.createBufferFromHex=function(e){let t=s(e.length>>1);for(let n=0;n<e.length;n+=2)t.data[n>>1]=parseInt(e.slice(n,n+2),16);return t.isStatic=!0,t},t.isReadOnly=function(e){return e.isStatic},t.getBytes=function(e){return e.data},t.getUint8=function(e,t){return o(e,t)},t.getByte=o,t.setUint8=function(e,t,n){l(e,t,n)},t.setByte=l,t.length=function(e){return e.data.length},t.fill=c,t.slice=function(e,t,n){return t=Math.min(e.data.length,t),n<0&&(n=e.data.length),n=Math.min(n,e.data.length-t),new u(e.data.slice(t,t+n))},t.toHex=function(e){const t="0123456789abcdef";let n="";for(let i=0;i<e.data.length;++i)n+=t[e.data[i]>>4],n+=t[15&e.data[i]];return n},t.toString=function(t){return e.U.fromUTF8Array(t.data)};const h=-2147483648;t.shift=function(e,t,n,i){i<0&&(i=e.data.length-n),n<0||n+i>e.data.length||n+i<n||0==i||0==t||t==h||0!=i&&0!=t&&t!=h&&(t<=-i||t>=i?c(e,0):(a(e),t<0?(t=-t,d(e.data,n+t,e.data,n,i-t),e.data.fill(0,n,n+t)):(i-=t,d(e.data,n,e.data,n+t,i),e.data.fill(0,n+i,n+i+t))))},t.rotate=function(e,t,n,i){if(i<0&&(i=e.data.length-n),n<0||n+i>e.data.length||n+i<n||0==i||0==t||t==h)return;a(e),t<0&&(t+=i<<8),(t%=i)<0&&(t+=i);let s=e.data,r=t,o=0,l=r,c=i;for(;o!=l;){let e=s[o+n];s[o+++n]=s[l+n],s[l+++n]=e,l==c?l=r:o==r&&(r=l)}},t.write=function(e,t,n,i=0,s=-1){s<0&&(s=n.data.length),i<0||t<0||t>e.data.length||(s=Math.min(n.data.length-i,e.data.length-t))<0||(a(e),d(e.data,t,n.data,i,s))}}(c=e.BufferMethods||(e.BufferMethods={}))}(pxsim||(pxsim={})),function(e){!function(t){t.createBufferFromUTF8=function(t){return new e.RefBuffer(e.U.toUTF8Array(t))}}(e.control||(e.control={}))}(pxsim||(pxsim={})),function(e){!function(e){let t={};e.setLocalizedStrings=function(e){t=e||{}};function n(e,t){return 0==t.length?e:e.replace(/\{([0-9]+)(\:[^\}]+)?\}/g,(function(e,n,r){let o=t[parseInt(n)],a="",l=/^:f(\d*)\.(\d+)/.exec(r);if(l){let e=parseInt(l[2]),t=parseInt(l[1])||0,n=/^0/.test(l[1])?"0":" ",i=o.toFixed(e);if(t>0&&e>0&&(t+=e+1),t>0)for(;i.length<t;)i=n+i;a=i}else a=":x"==r?"0x"+o.toString(16):void 0===o?"(undef)":null===o?"(null)":o.toString?o.toString():o+"";return":a"==r?/^\s*[euioah]/.test(a.toLowerCase())?a="an "+a:/^\s*[bcdfgjklmnpqrstvwxz]/.test(a.toLowerCase())&&(a="a "+a):":s"==r?a=1==o?"":"s":":q"==r?a=i(a):":jq"==r?a=s(a):":uri"==r?a=encodeURIComponent(a).replace(/'/g,"%27").replace(/"/g,"%22"):":url"==r?a=encodeURI(a).replace(/'/g,"%27").replace(/"/g,"%22"):":%"==r&&(a=(100*o).toFixed(1).toString()+"%"),a}))}function i(e){return e?e.replace(/([^\w .!?\-$])/g,(e=>"&#"+e.charCodeAt(0)+";")):e}function s(e){return e.replace(/[^\w .!?\-$]/g,(e=>{let t=e.charCodeAt(0).toString(16);return"\\u"+"0000".substr(0,4-t.length)+t}))}e.lf=function(e,...i){let s=t[e]||e;return s=s.replace(/^\{(id|loc):[^\}]+\}/g,""),n(s,i)},e.fmt_va=n,e.htmlEscape=i,e.jsStringQuote=s}(e.localization||(e.localization={}))}(pxsim||(pxsim={})),function(pxsim){const MIN_MESSAGE_WAIT_MS=200;let tracePauseMs=0,MessageListenerFlags,U,pxtcore;!function(e){e[e.MESSAGE_BUS_LISTENER_REENTRANT=8]="MESSAGE_BUS_LISTENER_REENTRANT",e[e.MESSAGE_BUS_LISTENER_QUEUE_IF_BUSY=16]="MESSAGE_BUS_LISTENER_QUEUE_IF_BUSY",e[e.MESSAGE_BUS_LISTENER_DROP_IF_BUSY=32]="MESSAGE_BUS_LISTENER_DROP_IF_BUSY",e[e.MESSAGE_BUS_LISTENER_IMMEDIATE=192]="MESSAGE_BUS_LISTENER_IMMEDIATE"}(MessageListenerFlags||(MessageListenerFlags={})),function(e){function t(e){return e.split(/\s+/).filter((e=>!!e))}function n(e){for(;e.firstChild;)e.removeChild(e.firstChild)}let i;e.containsClass=function(e,n){return t(n).every((t=>function(e,t){if(e.classList)return e.classList.contains(t);return!((e.className+"").split(/\s+/).indexOf(t)<0)}(e,t)))},e.addClass=function(e,n){t(n).forEach((t=>function(e,t){if(e.classList)e.classList.add(t);else{(e.className+"").split(/\s+/).indexOf(t)<0&&(e.className.baseVal+=" "+t)}}(e,t)))},e.removeClass=function(e,n){t(n).forEach((t=>function(e,t){e.classList?e.classList.remove(t):e.className.baseVal=(e.className+"").split(/\s+/).filter((e=>e!=t)).join(" ")}(e,t)))},e.remove=function(e){e.parentElement.removeChild(e)},e.removeChildren=n,e.clear=function(e){n(e)},e.assert=function(e,t="Assertion failed"){if(!e)throw new Error(t)},e.repeatMap=function(e,t){e=e||0;let n=[];for(let i=0;i<e;++i)n.push(t(i));return n},e.userError=function(e){let t=new Error(e);throw t.isUserError=!0,t},e.now=function(){return Date.now()},e.perfNowUs=function(){return i||(i="undefined"!=typeof performance?performance.now.bind(performance)||performance.moznow.bind(performance)||performance.msNow.bind(performance)||performance.webkitNow.bind(performance)||performance.oNow.bind(performance):Date.now),1e3*i()};const s=Promise.resolve();async function r(e,t,n){let i=0;const s=[],r=[];for(let o=0;o<e;o++){const e=(async()=>{for(;i<t.length;){const e=i++,s=t[e];r[e]=await n(s)}})();s.push(e)}try{await Promise.all(s)}catch(e){throw i=t.length,e}return r}function o(){return"undefined"!=typeof window&&!!window.pxtElectron}function a(){return"undefined"!=typeof window&&!!window.ipcRenderer}function l(){return o()||a()}function c(){try{return"undefined"!=typeof window&&/^http:\/\/(localhost|127\.0\.0\.1):\d+\//.test(window.location.href)&&!/nolocalhost=1/.test(window.location.href)}catch(e){return!1}}e.nextTick=function(e){s.then(e)},e.delay=async function(e,t){const n=await t;return await new Promise((t=>setTimeout((()=>t()),e))),n},e.throttle=function(e,t,n){let i;return function(){let s=this,r=arguments,o=function(){i=null,n||e.apply(s,r)},a=n&&!i;i||(i=setTimeout(o,t)),a&&e.apply(s,r)}},e.promiseMapAll=function(e,t){return Promise.all(e.map((e=>t(e))))},e.promiseMapAllSeries=function(e,t){return r(1,e,t)},e.promisePoolAsync=r,e.promiseTimeout=async function(e,t,n){let i,s;const r=new Promise(((t,r)=>{s=t,i=setTimeout((()=>{s=void 0,clearTimeout(i),r(n||`Promise timed out after ${e}ms`)}),e)}));return Promise.race([t,r]).then((e=>(s&&(clearTimeout(i),s()),e)))},e.stringToUint8Array=function(e){let t=e.length,n=new Uint8Array(t);for(let i=0;i<t;++i)n[i]=255&e.charCodeAt(i);return n},e.uint8ArrayToString=function(e){let t=e.length,n="";for(let i=0;i<t;++i)n+=String.fromCharCode(e[i]);return n},e.fromUTF8=function(e){if(!e)return"";let t="";for(let n=0;n<e.length;++n){let i=255&e.charCodeAt(n);t+=37==i||i>127?"%"+i.toString(16):e.charAt(n)}return decodeURIComponent(t)},e.toUTF8=function(e,t){let n="";if(!e)return n;for(let i=0;i<e.length;++i){let s=e.charCodeAt(i);if(s<=127)n+=e.charAt(i);else if(s<=2047)n+=String.fromCharCode(192|s>>6,128|63&s);else{if(!t&&55296<=s&&s<=56319){let t=e.charCodeAt(++i);isNaN(t)||(s=65536+(s-55296<<10)+(t-56320))}n+=s<=65535?String.fromCharCode(224|s>>12,128|s>>6&63,128|63&s):String.fromCharCode(240|s>>18,128|s>>12&63,128|s>>6&63,128|63&s)}}return n},e.toUTF8Array=function(e){return(new TextEncoder).encode(e)},e.fromUTF8Array=function(e){return(new TextDecoder).decode(e)},e.isPxtElectron=o,e.isIpcRenderer=a,e.isElectron=l,e.isLocalHost=c,e.isLocalHostDev=function(){return c()&&!l()},e.unique=function(e,t){let n=[],i={};return e.forEach((e=>{let s=t(e);i.hasOwnProperty(s)||(i[s]=null,n.push(e))})),n}}(U=pxsim.U||(pxsim.U={}));class BreakLoopException{}function getResume(){return pxsim.runtime.getResume()}pxsim.BreakLoopException=BreakLoopException,function(e){function t(e){let t=pxsim.runtime.currTryFrame();t||U.userError("unhandled exception: "+e);const n=t.handlerFrame;throw pxsim.runtime.currFrame=n,n.pc=t.handlerPC,n.tryFrame=t.parent,n.thrownValue=e,n.hasThrownValue=!0,new BreakLoopException}e.beginTry=function(e){pxsim.runtime.currFrame.tryFrame={parent:pxsim.runtime.currTryFrame(),handlerPC:e,handlerFrame:pxsim.runtime.currFrame}},e.endTry=function(){const e=pxsim.runtime.currFrame;e.tryFrame=e.tryFrame.parent},e.throwValue=t,e.getThrownValue=function(){const e=pxsim.runtime.currFrame;return U.assert(e.hasThrownValue),e.hasThrownValue=!1,e.thrownValue},e.endFinally=function(){const e=pxsim.runtime.currFrame;e.hasThrownValue&&(e.hasThrownValue=!1,t(e.thrownValue))}}(pxtcore=pxsim.pxtcore||(pxsim.pxtcore={})),pxsim.getResume=getResume;const SERIAL_BUFFER_LENGTH=16;class BaseBoard{constructor(){this.messageListeners=[],this.serialOutBuffer="",this.messages=[],this.lastSerialTime=0,this.debouncedPostAll=()=>{const e=Date.now();e-this.lastSerialTime>MIN_MESSAGE_WAIT_MS?(clearTimeout(this.serialTimeout),this.messages.length&&(Runtime.postMessage({type:"bulkserial",data:this.messages,id:pxsim.runtime.id,sim:!0}),this.messages=[],this.lastSerialTime=e)):this.serialTimeout=setTimeout(this.debouncedPostAll,50)},this.id=pxsim.Embed.frameid||"b"+Math.round(2147483647*Math.random()),this.bus=new pxsim.EventBus(pxsim.runtime,this)}updateView(){}receiveMessage(e){pxsim.runtime&&!pxsim.runtime.dead&&this.dispatchMessage(e)}dispatchMessage(e){for(const t of this.messageListeners)t(e)}addMessageListener(e){this.messageListeners.push(e)}get storedState(){return this.runOptions?(this.runOptions.storedState||(this.runOptions.storedState={}),this.runOptions.storedState):{}}initAsync(e){return this.runOptions=e,Promise.resolve()}setStoredState(e,t){null==t?delete this.storedState[e]:this.storedState[e]=t,Runtime.postMessage({type:"simulator",command:"setstate",stateKey:e,stateValue:t})}onDebuggerResume(){}screenshotAsync(e){return Promise.resolve(void 0)}kill(){}writeSerial(e){this.serialOutBuffer+=e,(/\n/.test(this.serialOutBuffer)||this.serialOutBuffer.length>SERIAL_BUFFER_LENGTH)&&(this.messages.push({time:Date.now(),data:this.serialOutBuffer}),this.debouncedPostAll(),this.serialOutBuffer="")}}pxsim.BaseBoard=BaseBoard;class CoreBoard extends BaseBoard{constructor(){super(),this.updateSubscribers=[],this.updateView=()=>{this.updateSubscribers.forEach((e=>e()))},this.builtinParts={},this.builtinVisuals={},this.builtinPartVisuals={}}kill(){super.kill(),pxsim.codal.music.__stopSoundExpressions(),pxsim.AudioContextManager.stopAll()}}pxsim.CoreBoard=CoreBoard;class BareBoard extends BaseBoard{}function initBareRuntime(){pxsim.runtime.board=new BareBoard;let e=pxsim;e.basic={pause:pxsim.thread.pause,showNumber:e=>{let t=getResume();console.log("SHOW NUMBER:",e),U.nextTick(t)}},e.serial={writeString:e=>pxsim.runtime.board.writeSerial(e)},e.pins={createBuffer:pxsim.BufferMethods.createBuffer},e.control={inBackground:pxsim.thread.runInBackground,createBuffer:pxsim.BufferMethods.createBuffer,dmesg:e=>console.log("DMESG: "+e),deviceDalVersion:()=>"sim",__log:(e,t)=>console.log("LOG: "+t.trim())}}let LogType;pxsim.initBareRuntime=initBareRuntime,function(e){e[e.UserSet=0]="UserSet",e[e.BackAdd=1]="BackAdd",e[e.BackRemove=2]="BackRemove"}(LogType||(LogType={}));class EventHandler{constructor(e,t){this.handler=e,this.flags=t,this.busy=0}async runAsync(e,t,n){const i=this.flags||MessageListenerFlags.MESSAGE_BUS_LISTENER_QUEUE_IF_BUSY;if(i!==MessageListenerFlags.MESSAGE_BUS_LISTENER_IMMEDIATE)return i===MessageListenerFlags.MESSAGE_BUS_LISTENER_QUEUE_IF_BUSY?this.runFiberAsync(e,t,n):void(i===MessageListenerFlags.MESSAGE_BUS_LISTENER_DROP_IF_BUSY&&this.busy||this.runFiberAsync(e,t,n));U.userError("MESSAGE_BUS_LISTENER_IMMEDIATE is not supported!")}async runFiberAsync(e,t,n){this.busy++,await t.runFiberAsync(this.handler,...n?n(e):[e]),this.busy--}}class EventQueue{constructor(e,t){this.runtime=e,this.valueToArgs=t,this.max=5,this.events=[],this.awaiters=[],this._handlers=[],this._addRemoveLog=[]}push(e,t){if(this.awaiters.length>0)if(t){const e=this.awaiters.shift();e&&e()}else{const e=this.awaiters.slice();this.awaiters=[],e.forEach((e=>e()))}return 0==this.handlers.length||this.events.length>this.max?Promise.resolve():(this.events.push(e),this.lock?Promise.resolve():this.poke())}async poke(){this.lock=!0;let e=this.events;this.events=[];for(const t of e)for(const e of this.handlers)await e.runAsync(t,this.runtime,this.valueToArgs);if(this.events.length>0)return this.poke();this.lock=!1;for(const e of this._addRemoveLog)e.log===LogType.BackAdd?this.addHandler(e.act,e.flags):e.log===LogType.BackRemove?this.removeHandler(e.act):this.setHandler(e.act,e.flags);this._addRemoveLog=[]}get handlers(){return this._handlers}setHandler(e,t=0){this.lock?this._addRemoveLog.push({act:e,log:LogType.UserSet,flags:t}):this._handlers=[new EventHandler(e,t)]}addHandler(e,t=0){this.lock?this._addRemoveLog.push({act:e,log:LogType.BackAdd,flags:t}):this._handlers.some((t=>t.handler===e))||this._handlers.push(new EventHandler(e,t))}removeHandler(e){if(this.lock)this._addRemoveLog.push({act:e,log:LogType.BackRemove,flags:0});else{let t=this._handlers.findIndex((t=>t.handler===e));-1!=t&&this._handlers.splice(t,1)}}addAwaiter(e){this.awaiters.push(e)}}function bind(e){const t=e.arg0,n=e.fn;return e=>{let i=0;for(;e.hasOwnProperty("arg"+i);)i++;const s=e;for(let e=i;e>0;e--)s["arg"+e]=s["arg"+(e-1)];return e.arg0=t,n(e)}}function _leave(e,t){return e.parent.retval=t,e.parent}function syntheticRefAction(e){return pxtcore.mkAction(0,(t=>_leave(t,e(t))))}pxsim.EventQueue=EventQueue,pxsim.initCurrentRuntime=void 0,pxsim.handleCustomMessage=void 0,pxsim.syntheticRefAction=syntheticRefAction;class TimeoutScheduled{constructor(e,t,n,i){this.id=e,this.fn=t,this.totalRuntime=n,this.timestampCall=i}}pxsim.TimeoutScheduled=TimeoutScheduled;class PausedTimeout{constructor(e,t){this.fn=e,this.timeRemaining=t}}function mkVTable(e){return{name:e.name,numFields:e.numFields,classNo:e.classNo,methods:e.methods,iface:e.iface,lastSubtypeNo:e.lastSubtypeNo,toStringMethod:e.toStringMethod,maxBgInstances:e.maxBgInstances}}pxsim.PausedTimeout=PausedTimeout,pxsim.mkVTable=mkVTable;let mapVTable=null;function mkMapVTable(){return mapVTable||(mapVTable=mkVTable({name:"_Map",numFields:0,classNo:0,lastSubtypeNo:0,methods:null})),mapVTable}function functionName(e){const t=e.info;return t?`${t.functionName} (${t.fileName}:${t.line+1}:${t.column+1})`:"()"}pxsim.mkMapVTable=mkMapVTable,pxsim.functionName=functionName;class Runtime{constructor(msg){this.numGlobals=1e3,this.dead=!1,this.running=!1,this.idleTimer=void 0,this.recording=!1,this.recordingTimer=0,this.recordingLastImageData=void 0,this.recordingWidth=void 0,this.startTime=0,this.startTimeUs=0,this.pausedTime=0,this.lastPauseTimestamp=0,this.globals={},this.environmentGlobals={},this.otherFrames=[],this.loopLock=null,this.loopLockWaitList=[],this.heapSnapshots=[],this.timeoutsScheduled=[],this.timeoutsPausedOnBreakpoint=[],this.pausedOnBreakpoint=!1,this.traceDisabled=!1,this.perfOffset=0,this.perfElapsed=0,this.perfStack=0,this.refCountingDebug=!1,this.refObjId=1,this.numDisplayUpdates=0,U.assert(!!pxsim.initCurrentRuntime),this.id=msg.id,this.refCountingDebug=!!msg.refCountingDebug;let threadId=0,breakpoints=null,currResume,dbgHeap,dbgResume,breakFrame=null,lastYield=Date.now(),userGlobals,__this=this;this.traceDisabled=!!msg.traceDisabled;const yieldDelay=void 0!==msg.yieldDelay?msg.yieldDelay:5,evalIface={runtime:this,oops:oops,doNothing:doNothing,pxsim:pxsim,globals:this.globals,setupYield:setupYield,maybeYield:maybeYield,setupDebugger:setupDebugger,isBreakFrame:isBreakFrame,breakpoint:breakpoint,trace:trace,checkStack:checkStack,leave:_leave,checkResumeConsumed:checkResumeConsumed,setupResume:setupResume,setupLambda:setupLambda,checkSubtype:checkSubtype,failedCast:failedCast,buildResume:buildResume,mkVTable:mkVTable,bind:bind,leaveAccessor:leaveAccessor};function oops(e){throw new Error("sim error: "+e)}function doNothing(e){return e.pc=-1,_leave(e,e.parent.retval)}function flushLoopLock(){for(;__this.loopLockWaitList.length>0&&!__this.loopLock;){__this.loopLockWaitList.shift()()}}let yieldReset=()=>{};function setupYield(e){yieldReset=e}function loopForSchedule(e){const t=new Object,n=e.pc;return __this.loopLock=t,__this.otherFrames.push(e),()=>{__this.dead||(U.assert(e.pc==n),U.assert(__this.loopLock===t),__this.loopLock=null,loop(e),flushLoopLock())}}function maybeYield(e,t,n){if(__this.pausedOnBreakpoint)return!1;__this.cleanScheduledExpired(),yieldReset();let i=Date.now();return i-lastYield>=20&&(lastYield=i,e.pc=t,e.r0=n,setTimeout(loopForSchedule(e),yieldDelay),!0)}function setupDebugger(e,t){return breakpoints=new Uint8Array(e),breakpoints[0]=msg.breakOnStart?1:0,userGlobals=t,breakpoints}function isBreakFrame(e){if(!breakFrame)return!0;for(let t=breakFrame;t;t=t.parent)if(t==e)return!0;return!1}function breakpoint(e,t,n,i){let s={};__this.loopLock=s,U.assert(!dbgResume),U.assert(!dbgHeap),e.pc=t,e.r0=i;const{msg:r,heap:o}=pxsim.getBreakpointMsg(e,n,userGlobals);return dbgHeap=o,pxsim.injectEnvironmentGlobals(r,o),Runtime.postMessage(r),breakpoints[0]=0,breakFrame=null,__this.pauseScheduled(),dbgResume=n=>{if(dbgResume=null,dbgHeap=null,__this.dead)return null;switch(__this.resumeAllPausedScheduled(),__this.board.onDebuggerResume(),pxsim.runtime=__this,U.assert(e.pc==t),breakpoints[0]=0,breakFrame=null,n.subtype){case"resume":break;case"stepover":breakpoints[0]=1,breakFrame=e;break;case"stepinto":breakpoints[0]=1;break;case"stepout":breakpoints[0]=1,breakFrame=e.parent||e}U.assert(__this.loopLock==s),__this.loopLock=null,__this.otherFrames.push(e),loop(e),flushLoopLock()},null}function trace(e,t,n,i){if(setupResume(t,n),"<main>"===i.functionName||"main.ts"===i.fileName){if(!pxsim.runtime.traceDisabled){const{msg:n}=pxsim.getBreakpointMsg(t,e,userGlobals);n.subtype="trace",Runtime.postMessage(n)}pxsim.thread.pause(tracePauseMs||1)}else pxsim.thread.pause(0);checkResumeConsumed()}function handleDebuggerMsg(e){switch(e.subtype){case"config":let t=e;if(t.setBreakpoints&&breakpoints){breakpoints.fill(0);for(let e of t.setBreakpoints)breakpoints[e]=1}break;case"traceConfig":tracePauseMs=e.interval;break;case"pause":breakpoints[0]=1,breakFrame=null;break;case"resume":case"stepover":case"stepinto":case"stepout":dbgResume&&dbgResume(e);break;case"variables":const n=e;let i;if(dbgHeap){const e=dbgHeap[n.variablesReference];void 0!==e&&(i=pxsim.dumpHeap(e,dbgHeap,n.fields,void 0,n.includeAll))}Runtime.postMessage({type:"debugger",subtype:"variables",req_seq:e.seq,variables:i})}}function removeFrame(e){const t=__this.otherFrames;for(let n=t.length-1;n>=0;--n)if(t[n]===e)return void t.splice(n,1);U.userError("frame cannot be removed!")}function loop(e){if(__this.dead)console.log("Runtime terminated");else{U.assert(!__this.loopLock),__this.perfStartRuntime(),removeFrame(e);try{for(pxsim.runtime=__this;e;)__this.currFrame=e,__this.currFrame.overwrittenPC=!1,e=e.fn(e),__this.maybeUpdateDisplay(),__this.currFrame.overwrittenPC&&(e=__this.currFrame);__this.perfStopRuntime()}catch(t){if(t instanceof BreakLoopException)return void U.nextTick(loopForSchedule(__this.currFrame));if(__this.perfStopRuntime(),__this.errorHandler)__this.errorHandler(t);else{console.error("Simulator crashed, no error handler",t.stack);const{msg:n,heap:i}=pxsim.getBreakpointMsg(e,e.lastBrkId,userGlobals);pxsim.injectEnvironmentGlobals(n,i),n.exceptionMessage=t.message,n.exceptionStack=t.stack,Runtime.postMessage(n),__this.postError&&__this.postError(t)}}}}function checkStack(e){e>100&&U.userError("Stack overflow")}function actionCall(e){return e.depth=e.parent.depth+1,checkStack(e.depth),e.pc=0,e}function setupTop(e){let t=setupTopCore(e);return setupResume(t,0),t}function setupTopCore(e){let t={parent:null,pc:0,depth:0,threadId:++threadId,fn:()=>(e&&e(t.retval),null)};return t}function topCall(e,t){U.assert(!!__this.board),U.assert(!__this.running),__this.setRunning(!0);let n={parent:setupTopCore(t),fn:e,depth:0,pc:0};__this.otherFrames=[n],loop(actionCall(n))}function checkResumeConsumed(){currResume&&oops("getResume() not called")}function setupResume(e,t){currResume=buildResume(e,t)}function leaveAccessor(e,t){if(e.stage2Call){const n={pc:0,fn:null,depth:e.depth,parent:e.parent};let i=1;for(;e.hasOwnProperty("arg"+i);)n["arg"+(i-1)]=e["arg"+i],i++;return setupLambda(n,t),n}return e.parent.retval=t,e.parent}function setupLambda(e,t,n){if(n){const t=e;for(let e=1;e<n;++e)t["arg"+(e-1)]=t["arg"+e];delete t["arg"+(n-1)]}t instanceof pxsim.RefAction?(e.fn=t.func,e.caps=t.fields):"function"==typeof t?e.fn=t:oops("calling non-function")}function checkSubtype(e,t){if(!e)return!1;const n=e.vtable;return t===n||n&&t.classNo<=n.classNo&&n.classNo<=t.lastSubtypeNo}function failedCast(e){pxsim.control&&pxsim.control.dmesgValue&&pxsim.control.dmesgValue(e),oops("failed cast on "+e)}function buildResume(e,t){currResume&&oops("already has resume"),e.pc=t;let n=Date.now();__this.otherFrames.push(e);let i=s=>{if(__this.dead)return;if(__this.loopLock)return void __this.loopLockWaitList.push((()=>i(s)));pxsim.runtime=__this;let r=Date.now();if(r-n>3&&(lastYield=r),U.assert(e.pc==t),s instanceof pxsim.FnWrapper){let t=s,n={parent:e,fn:t.func,lambdaArgs:t.args,pc:0,caps:t.caps,depth:e.depth+1},i={};return __this.loopLock=i,removeFrame(e),__this.otherFrames.push(n),U.nextTick((()=>{U.assert(__this.loopLock===i),__this.loopLock=null,loop(actionCall(n)),flushLoopLock()}))}return e.retval=s,loop(e)};return i}const entryPoint=msg.code&&eval(msg.code)(evalIface);this.run=e=>topCall(entryPoint,e),this.getResume=()=>{currResume||oops("noresume");let e=currResume;return currResume=null,e},this.setupTop=setupTop,this.handleDebuggerMsg=handleDebuggerMsg,this.entry=entryPoint,this.overwriteResume=e=>{currResume=null,e>=0&&(this.currFrame.pc=e),this.currFrame.overwrittenPC=!0},pxsim.runtime=this,pxsim.initCurrentRuntime(msg)}registerLiveObject(e){return this.refObjId++}runningTime(){return U.now()-this.startTime-this.pausedTime}runningTimeUs(){return 4294967295&U.perfNowUs()-this.startTimeUs>>0}runFiberAsync(e,t,n,i){return new Promise(((s,r)=>U.nextTick((()=>{pxsim.runtime=this,this.setupTop(s),pxtcore.runAction(e,[t,n,i])}))))}currTryFrame(){for(let e=this.currFrame;e;e=e.parent)if(e.tryFrame)return e.tryFrame;return null}traceObjects(){const e={};for(;this.heapSnapshots.length>2;)this.heapSnapshots.shift();const t={count:0,size:0,name:"TOTAL"},n={TOTAL:t};function i(t,n,s=null){if(!(n instanceof pxsim.RefObject))return;const r=n;if(r.gcIsStatic())return;const o=e[r.id];if(o)return void(s&&o.pointers.push([s,t]));const a={obj:r,path:null,pointers:[[s,t]]};e[r.id]=a,r.scan(((t,n)=>{n instanceof pxsim.RefObject&&!e[n.id]&&i(t,n,a)}))}this.heapSnapshots.push({visited:e,statsByType:n});for(let e of Object.keys(this.globals))i(e.replace(/___\d+$/,""),this.globals[e]);const s=this.otherFrames.slice();this.currFrame&&s.indexOf(this.currFrame)<0&&s.unshift(this.currFrame);for(const e of this.getThreads()){const t="Thread-"+this.rootFrame(e).threadId;for(let n=e;n;n=n.parent){const e=t+"."+functionName(n.fn);for(let t of Object.keys(n))if(/^(r0|arg\d+|.*___\d+)/.test(t)){const s=n[t];s instanceof pxsim.RefObject&&(t=t.replace(/___.*/,""),i(e+"."+t,s))}if(n.caps)for(let t of n.caps)i(e+".cap",t)}}const r=Object.keys(e).map((t=>e[t]));r.sort(((e,t)=>t.obj.gcSize()-e.obj.gcSize()));const o=e=>{if(null!=e.path)return;let t="";e.path="(cycle)";for(let[n,i]of e.pointers){if(null==n)return void(e.path=i);o(n);const s=n.path+"."+i;(!t||t.length>s.length)&&(t=s)}e.path=t};r.forEach(o);const a=[t];for(const e of r){const i=e.obj.gcSize(),s=e.obj.gcKey();n.hasOwnProperty(s)||a.push(n[s]={count:0,size:0,name:s});const r=n[s];r.size+=i,r.count++,t.size+=i,t.count++}a.sort(((e,t)=>e.size-t.size));let l="";const c=e=>(" "+e.toString()).slice(-7);for(const e of a)l+=c(4*e.size)+c(e.count)+" "+e.name+"\n";const u=e=>c(4*e.obj.gcSize())+" "+e.obj.gcKey()+" "+e.path,d=r.slice(0,20).map(u).join("\n");let h="";if(this.heapSnapshots.length>=3){const e=this.heapSnapshots[this.heapSnapshots.length-3].visited,t=this.heapSnapshots[this.heapSnapshots.length-2].visited,i=e=>e instanceof pxsim.RefRecord&&!!(e.vtable&&e.vtable.maxBgInstances&&n[e.gcKey()].count<=e.vtable.maxBgInstances);h=r.filter((n=>!e[n.obj.id]&&t[n.obj.id])).filter((e=>!i(e.obj))).map(u).join("\n")}return"Threads:\n"+this.threadInfo()+"\n\nSummary:\n"+l+"\n\nLarge Objects:\n"+d+"\n\nNew Objects:\n"+h}getThreads(){const e=this.otherFrames.slice();return this.currFrame&&e.indexOf(this.currFrame)<0&&e.unshift(this.currFrame),e}rootFrame(e){let t=e;for(;t.parent;)t=t.parent;return t}threadInfo(){const e=this.getThreads();let t="";for(let n of e){t+=`Thread ${this.rootFrame(n).threadId}:\n`;for(let e of pxsim.getBreakpointMsg(n,n.lastBrkId).msg.stackframes){let n=e.funcInfo;t+=` at ${n.functionName} (${n.fileName}:${n.line+1}:${n.column+1})\n`}t+="\n"}return t}static postMessage(e){e&&("undefined"!=typeof window&&window.parent&&window.parent.postMessage&&window.parent.postMessage(e,"*"),Runtime.messagePosted&&Runtime.messagePosted(e))}static async postScreenshotAsync(e){const t=pxsim.runtime&&pxsim.runtime.board;if(!t)return;const n=await t.screenshotAsync();Runtime.postMessage({type:"screenshot",data:n,delay:e&&e.delay})}static requestToggleRecording(){const e=pxsim.runtime;e&&Runtime.postMessage({type:"recorder",action:e.recording?"stop":"start"})}restart(){this.kill(),setTimeout((()=>pxsim.Runtime.postMessage({type:"simulator",command:"restart"})),500)}kill(){this.dead=!0,this.stopRecording(),this.stopIdle(),this.setRunning(!1)}updateDisplay(){this.board.updateView(),this.postFrame()}startRecording(e){!this.recording&&this.running&&(this.recording=!0,this.recordingTimer=setInterval((()=>this.postFrame()),66),this.recordingLastImageData=void 0,this.recordingWidth=e)}stopRecording(){this.recording&&(this.recordingTimer&&clearInterval(this.recordingTimer),this.recording=!1,this.recordingTimer=0,this.recordingLastImageData=void 0,this.recordingWidth=void 0)}postFrame(){if(!this.recording||!this.running)return;let e=pxsim.U.now();this.board.screenshotAsync(this.recordingWidth).then((t=>{this.recordingLastImageData&&isImageDataEqual(this.recordingLastImageData,t)||(this.recordingLastImageData=t,Runtime.postMessage({type:"screenshot",data:t,time:e}))}))}queueDisplayUpdate(){this.numDisplayUpdates++}maybeUpdateDisplay(){this.numDisplayUpdates&&(this.numDisplayUpdates=0,this.updateDisplay())}setRunning(e){this.running!=e&&(this.running=e,this.running?(this.startTime=U.now(),this.startTimeUs=U.perfNowUs(),Runtime.postMessage({type:"status",frameid:pxsim.Embed.frameid,runtimeid:this.id,state:"running"})):(this.stopRecording(),this.stopIdle(),Runtime.postMessage({type:"status",frameid:pxsim.Embed.frameid,runtimeid:this.id,state:"killed"})),this.stateChanged&&this.stateChanged())}dumpLivePointers(){}setupPerfCounters(e){e&&e.length&&(this.perfCounters=e.map((e=>new PerfCounter(e))))}perfStartRuntime(){0!==this.perfOffset?this.perfStack++:this.perfOffset=U.perfNowUs()-this.perfElapsed}perfStopRuntime(){this.perfStack?this.perfStack--:(this.perfElapsed=this.perfNow(),this.perfOffset=0)}perfNow(){return 0===this.perfOffset&&U.userError("bad time now"),U.perfNowUs()-this.perfOffset|0}startPerfCounter(e){if(!this.perfCounters)return;const t=this.perfCounters[e];t.start&&U.userError("startPerf"),t.start=this.perfNow()}stopPerfCounter(e){if(!this.perfCounters)return;const t=this.perfCounters[e];t.start||U.userError("stopPerf");const n=this.perfNow()-t.start;t.start=0,t.value+=n,t.numstops++;let i=t.lastFewPtr++;i>=t.lastFew.length&&(i=0,t.lastFewPtr=1),t.lastFew[i]=n}startIdle(){void 0===this.idleTimer&&(this.idleTimer=setInterval((()=>{if(!this.running||this.pausedOnBreakpoint)return;const e=this.board.bus;e&&e.queueIdle()}),20))}stopIdle(){void 0!==this.idleTimer&&(clearInterval(this.idleTimer),this.idleTimer=void 0)}schedule(e,t){if(t<=0&&(t=0),this.pausedOnBreakpoint)return this.timeoutsPausedOnBreakpoint.push(new PausedTimeout(e,t)),-1;const n=U.now(),i=new TimeoutScheduled(-1,e,t,n);return i.id=setTimeout((()=>{const t=this.timeoutsScheduled.indexOf(i);t>=0&&this.timeoutsScheduled.splice(t,1),e()}),t),this.timeoutsScheduled.push(i),i.id}pauseScheduled(){this.pausedOnBreakpoint=!0,this.timeoutsScheduled.forEach((e=>{clearTimeout(e.id);let t=U.now()-e.timestampCall,n=e.totalRuntime-t;n<=0&&(n=1),this.timeoutsPausedOnBreakpoint.push(new PausedTimeout(e.fn,n))})),this.lastPauseTimestamp=U.now(),this.timeoutsScheduled=[]}resumeAllPausedScheduled(){this.pausedOnBreakpoint=!1,this.timeoutsPausedOnBreakpoint.forEach((e=>{this.schedule(e.fn,e.timeRemaining)})),this.lastPauseTimestamp&&(this.pausedTime+=U.now()-this.lastPauseTimestamp,this.lastPauseTimestamp=0),this.timeoutsPausedOnBreakpoint=[]}cleanScheduledExpired(){let e=U.now();this.timeoutsScheduled=this.timeoutsScheduled.filter((t=>{let n=e-t.timestampCall;return t.totalRuntime>n}))}registerUserInteraction(){this.lastInteractionTime=Date.now(),this.thumbnailRecordingIntervalRef||this.lastThumbnailTime&&this.lastInteractionTime-this.lastThumbnailTime<1e3||(this.thumbnailFrames=[],this.thumbnailRecordingIntervalRef=setInterval((async()=>{const e=await this.board.screenshotAsync();this.thumbnailFrames.length&&isImageDataEqual(e,this.thumbnailFrames[this.thumbnailFrames.length-1])||(this.thumbnailFrames.push(e),(Date.now()-this.lastInteractionTime>1e4||this.thumbnailFrames.length>30)&&(clearInterval(this.thumbnailRecordingIntervalRef),this.thumbnailRecordingIntervalRef=void 0,this.lastThumbnailTime=Date.now(),Runtime.postMessage({type:"thumbnail",frames:this.thumbnailFrames})))}),66))}}function setParentMuteState(e){Runtime.postMessage({type:"setmutebuttonstate",state:e})}pxsim.Runtime=Runtime,pxsim.setParentMuteState=setParentMuteState;class PerfCounter{constructor(e){this.name=e,this.start=0,this.numstops=0,this.value=0,this.lastFew=new Uint32Array(32),this.lastFewPtr=0}}function isImageDataEqual(e,t){if(e.data.byteLength!==t.data.byteLength)return!1;const n=e.data.byteLength;let i=0;for(i=0;i<n&&e.data[i]==t.data[i];++i);return i===n}pxsim.PerfCounter=PerfCounter}(pxsim||(pxsim={})),function(e){let t,n;!function(e){e[e.Unloaded=0]="Unloaded",e[e.Stopped=1]="Stopped",e[e.Pending=2]="Pending",e[e.Starting=3]="Starting",e[e.Running=4]="Running",e[e.Paused=5]="Paused",e[e.Suspended=6]="Suspended"}(t=e.SimulatorState||(e.SimulatorState={})),function(e){e[e.StepInto=0]="StepInto",e[e.StepOver=1]="StepOver",e[e.StepOut=2]="StepOut",e[e.Resume=3]="Resume",e[e.Pause=4]="Pause"}(n=e.SimulatorDebuggerCommand||(e.SimulatorDebuggerCommand={}));const i="pxtdriver";e.SimulatorDriver=class{constructor(n,i={}){this.container=n,this.options=i,this.themes=["blue","red","green","yellow"],this.runId="",this.nextFrameId=0,this.frameCounter=0,this.traceInterval=0,this.breakpointsSet=!1,this._runOptions={},this.state=t.Unloaded,this._allowedOrigins=[],this.frameCleanupTimeout=void 0,this.debuggerSeq=1,this.debuggerResolvers={},this._allowedOrigins.push(window.location.origin),i.parentOrigin&&this._allowedOrigins.push(i.parentOrigin),this._allowedOrigins.push(this.getSimUrl().origin);const s=null==i?void 0:i.messageSimulators;s&&Object.keys(s).map((e=>s[e])).forEach((e=>{this._allowedOrigins.push(new URL(e.url).origin),e.localHostUrl&&this._allowedOrigins.push(new URL(e.localHostUrl).origin)})),this._allowedOrigins=e.U.unique(this._allowedOrigins,(e=>e))}isDebug(){return this._runOptions&&!!this._runOptions.debug}isTracing(){return this._runOptions&&!!this._runOptions.trace}hasParts(){return this._runOptions&&this._runOptions.parts&&!!this._runOptions.parts.length}setDirty(){this.state==e.SimulatorState.Running&&this.suspend()}setPending(){this.setState(t.Pending)}focus(){const e=this.simFrames()[0];e&&e.focus()}registerDependentEditor(e){e&&(this._dependentEditors||(this._dependentEditors=[]),this._dependentEditors.push(e))}dependentEditors(){return this._dependentEditors&&(this._dependentEditors=this._dependentEditors.filter((e=>!!e.parent)),this._dependentEditors.length||(this._dependentEditors=void 0)),this._dependentEditors}setStarting(){this.setState(t.Starting)}setHwDebugger(e){e?(this.hwdbg=e,this.setState(t.Running),this.container.style.opacity="0.3"):(delete this.container.style.opacity,this.hwdbg=null,this.setState(t.Running),this.stop())}handleHwDebuggerMsg(e){this.hwdbg&&this.handleMessage(e)}setThemes(t){e.U.assert(t&&t.length>0),this.themes=t}startRecording(e){this.simFrames()[0]&&this.postMessage({type:"recorder",action:"start",source:i,width:e})}stopRecording(){this.postMessage({type:"recorder",source:i,action:"stop"})}setFrameState(n){const i=n.nextElementSibling,s=i.nextElementSibling;switch(this.state){case t.Pending:case t.Starting:i.style.display="",i.className="",s.style.display="";break;case t.Stopped:case t.Suspended:e.U.addClass(n,this.state==t.Stopped||this._runOptions&&this._runOptions.autoRun?this.stoppedClass:this.invalidatedClass),this._runOptions&&this._runOptions.autoRun?i.style.display="none":(i.style.display="",i.className="videoplay xicon icon"),s.style.display="none",this.scheduleFrameCleanup();break;default:e.U.removeClass(n,this.stoppedClass),e.U.removeClass(n,this.invalidatedClass),i.style.display="none",s.style.display="none"}}setState(e){this.state!=e&&(this.state=e,this.freeze(this.state==t.Paused),this.simFrames().forEach((e=>this.setFrameState(e))),this.options.onStateChanged&&this.options.onStateChanged(this.state))}freeze(t){const n="pause-overlay";t?e.util.toArray(this.container.querySelectorAll("div.simframe")).forEach((e=>{if(e.querySelector(`div.${n}`))return;const t=document.createElement("div");t.className=n,t.onclick=e=>(e.preventDefault(),!1),e.appendChild(t)})):e.util.toArray(this.container.querySelectorAll(`div.simframe div.${n}`)).forEach((e=>e.parentElement.removeChild(e)))}simFrames(t=!1){let n=e.util.toArray(this.container.getElementsByTagName("iframe"));const i=this.loanedIFrame();return i&&!t&&n.unshift(i),n}getSimUrl(){var e,t;const n=this.options.simUrl||(null===(e=window.pxtConfig)||void 0===e?void 0:e.simUrl)||(null===(t=pxt.webConfig)||void 0===t?void 0:t.simUrl)||`${location.origin}/sim/simulator.html`;try{return new URL(n)}catch(e){return new URL(n,location.origin)}}postMessage(t,n,i){var s;if(this.hwdbg)return void this.hwdbg.postMessage(t);const r=this.dependentEditors();let o=this.simFrames();i&&(o=o.filter((e=>e.id===i)));let a=!1;const l=t;if(n&&(null==l?void 0:l.broadcast)){l.srcFrameIndex=this.simFrames().findIndex((e=>e.contentWindow===n));const i=!!(null===(s=this._currentRuntime)||void 0===s?void 0:s.single),c=window.parent&&window.parent!==window.window?window.parent:window.opener;if(c&&n!==c&&c.postMessage(t,"*"),!this.options.nestedEditorSim&&!(null==l?void 0:l.toParentIFrameOnly))if(r)r.forEach((e=>{n!==e&&e.postMessage(t,window.location.origin)}));else if(!i){const n="messagepacket"===t.type&&t.channel,i=n&&this.options.messageSimulators&&this.options.messageSimulators[n];if(i){let t=o.find((e=>e.dataset.messagechannel===n));if(t)t.dataset.runid!=this.runId&&this.startFrame(t);else{const s=(e.U.isLocalHost()&&/localhostmessagesims=1/i.test(window.location.href)&&i.localHostUrl||i.url).replace("$PARENT_ORIGIN$",encodeURIComponent(this.options.parentOrigin||"")).replace("$LANGUAGE$",encodeURIComponent(this.options.userLanguage));let r=this.createFrame(s);this.container.appendChild(r),t=r.firstElementChild,t.dataset.messagechannel=n,e.U.addClass(r,"simmsg"),e.U.addClass(r,"simmsg"+n),i.permanent&&(t.dataset.permanent="true"),this.startFrame(t),o=this.simFrames()}}else{a=!0;const e=o.filter((e=>!e.dataset.messagechannel));e.length<2?(this.container.appendChild(this.createFrame()),o=this.simFrames()):e[1].dataset.runid!=this.runId&&this.startFrame(e[1])}}}for(let e=0;e<o.length;++e){const i=o[e];if((!n||i.contentWindow!=n)&&(i.contentWindow&&(a?this.postDeferrableMessage(i,t):this.postMessageCore(i,t),"recorder"==t.type&&"start"==t.action)))break}}postDeferrableMessage(e,t){!e.dataset.loading?this.postMessageCore(e,t):(this.deferredMessages||(this.deferredMessages=[]),this.deferredMessages.push([e,t]))}postMessageCore(t,n){const i=e.U.isLocalHostDev()?"*":t.dataset.origin;t.contentWindow.postMessage(n,i)}setRunOptionQueryParams(e){var t,n;const i=new URL(e);if((null===(t=this._runOptions)||void 0===t?void 0:t.hideSimButtons)&&i.searchParams.set("hideSimButtons","1"),null===(n=this._runOptions)||void 0===n?void 0:n.queryParameters){const e=this._runOptions.queryParameters.split("&");for(const t of e){const[e,n]=t.split(/[:=]/);e&&n&&i.searchParams.set(e,n)}}return i.toString()}createFrame(n){var i;const s=document.createElement("div");s.className="simframe ui embed";const r=document.createElement("iframe");r.id="sim-frame-"+this.nextId(),r.title=e.localization.lf("Simulator"),r.allowFullscreen=!0,r.setAttribute("allow","autoplay;microphone"),r.setAttribute("sandbox","allow-same-origin allow-scripts"),r.className="no-select";let o=this.setRunOptionQueryParams(n||this.getSimUrl().toString());o+="#"+r.id,r.src=o,r.frameBorder="0",r.dataset.runid=this.runId,r.dataset.origin=new URL(o).origin||"*",r.dataset.loading="true",(null===(i=this._runOptions)||void 0===i?void 0:i.autofocus)&&r.setAttribute("autofocus","true"),s.appendChild(r);const a=document.createElement("i");a.className="videoplay xicon icon",a.style.display="none",a.onclick=e=>(e.preventDefault(),this.state!=t.Running&&this.state!=t.Starting&&(this.options.restart?this.options.restart():this.start()),r.focus(),!1),s.appendChild(a);const l=document.createElement("div");return l.className="ui active loader",a.style.display="none",s.appendChild(l),this._runOptions&&this.applyAspectRatioToFrame(r),s}preload(e,t){this.addEventListeners(),t&&(this._currentRuntime=void 0,this.container.textContent=""),this.simFrames().length||(this.container.appendChild(this.createFrame()),this.applyAspectRatio(e),this.setStarting())}stop(e=!1,n=!1){this.state!==t.Stopped&&this.state!==t.Unloaded&&(this.clearDebugger(),this.stopSound(),this.postMessage({type:"stop",source:i}),this.setState(n?t.Starting:t.Stopped)),e&&this.unload()}suspend(){this.stopSound(),this.postMessage({type:"stop",source:i}),this.setState(t.Suspended)}unload(){this.cancelFrameCleanup(),e.U.removeChildren(this.container),this.setState(t.Unloaded),this._runOptions=void 0,this._currentRuntime=void 0,this.runId=void 0,this.deferredMessages=void 0}mute(e){this._currentRuntime&&(this._currentRuntime.mute=e),this.postMessage({type:"mute",source:i,mute:e})}stopSound(){this.postMessage({type:"stopsound",source:i})}isLoanedSimulator(e){return!!this.loanedSimulator&&this.loanedIFrame()==e}loanSimulator(){return this.loanedSimulator||(this.loanedSimulator=this.container.firstElementChild||this.createFrame(),this.loanedSimulator.parentNode&&this.container.removeChild(this.loanedSimulator)),this.loanedSimulator}unloanSimulator(){this.loanedSimulator&&(this.loanedSimulator.parentNode&&this.loanedSimulator.parentNode.removeChild(this.loanedSimulator),this.container.insertBefore(this.loanedSimulator,this.container.firstElementChild),delete this.loanedSimulator)}loanedIFrame(){return this.loanedSimulator&&this.loanedSimulator.parentNode&&this.loanedSimulator.querySelector("iframe")}cancelFrameCleanup(){this.frameCleanupTimeout&&(clearTimeout(this.frameCleanupTimeout),this.frameCleanupTimeout=void 0)}scheduleFrameCleanup(){this.cancelFrameCleanup(),this.frameCleanupTimeout=setTimeout((()=>{this.frameCleanupTimeout=void 0,this.cleanupFrames()}),5e3)}applyAspectRatio(e){if(!e&&!this._runOptions)return;this.simFrames().forEach((t=>this.applyAspectRatioToFrame(t,e)))}applyAspectRatioToFrame(e,t){var n,i,s,r;let o=t;if(void 0===o){const t=parseFloat(e.dataset.aspectratio);isNaN(t)||(o=t)}if(void 0===o){const t=e.dataset.messagechannel;if(t){const e=null===(s=null===(i=null===(n=this.options)||void 0===n?void 0:n.messageSimulators)||void 0===i?void 0:i[t])||void 0===s?void 0:s.aspectRatio;e&&(o=e)}}void 0===o&&(o=(null===(r=this._runOptions)||void 0===r?void 0:r.aspectRatio)||1.22),e.parentElement.style.paddingBottom=100/o+"%"}cleanupFrames(){const e=this.simFrames(!0);e.shift(),e.filter((e=>!e.dataset.permanent)).forEach((e=>{this.state!=t.Stopped&&e.dataset.runid==this.runId||(this.options.removeElement?this.options.removeElement(e.parentElement):e.parentElement.remove())}))}hide(e){if(this.suspend(),!this.options.removeElement)return;const t=this.simFrames();t.forEach((t=>{this.options.removeElement(t.parentElement,e)})),0==t.length&&e&&e()}unhide(){if(!this.options.unhideElement)return;this.simFrames().forEach((e=>{this.options.unhideElement(e.parentElement)}))}setRunOptions(e={}){this._runOptions=e}run(e,t={}){this.setRunOptions(t),this.runId=this.nextId(),this._currentRuntime={type:"run",source:i,boardDefinition:t.boardDefinition,parts:t.parts,builtinParts:t.builtinParts,fnArgs:t.fnArgs,code:e,partDefinitions:t.partDefinitions,mute:t.mute,highContrast:t.highContrast,light:t.light,cdnUrl:t.cdnUrl,localizedStrings:t.localizedStrings,refCountingDebug:t.refCountingDebug,version:t.version,clickTrigger:t.clickTrigger,breakOnStart:t.breakOnStart,storedState:t.storedState,ipc:t.ipc,single:t.single,dependencies:t.dependencies,activePlayer:t.activePlayer,theme:t.theme},this.stopSound(),this.start()}restart(){this.stop(),this.cleanupFrames(),this.start()}areBreakpointsSet(){return this.breakpointsSet}start(){if(this.clearDebugger(),this.addEventListeners(),this.applyAspectRatio(),this.scheduleFrameCleanup(),!this._currentRuntime)return;this.breakpointsSet=!1;let e=this.simFrames()[0];if(e)this.startFrame(e);else{let t=this.createFrame();this.container.appendChild(t),e=t.firstElementChild}this.debuggingFrame=e.id,this.setState(t.Running),this.setTraceInterval(this.traceInterval)}startFrame(e){var t,n,i;if(!this._currentRuntime||!e.contentWindow)return!1;const s=JSON.parse(JSON.stringify(this._currentRuntime));s.frameCounter=++this.frameCounter;const r=(null===(t=this._runOptions)||void 0===t?void 0:t.mpRole)||(null===(i=null===(n=/[\&\?]mp=(server|client)/i.exec(window.location.href))||void 0===n?void 0:n[1])||void 0===i?void 0:i.toLowerCase());return s.options={theme:this.themes[this.nextFrameId++%this.themes.length],mpRole:r},s.id=`${s.options.theme}-${this.nextId()}`,e.dataset.runid=this.runId,e.dataset.runtimeid=s.id,e.id!==this.debuggingFrame&&(s.traceDisabled=!0,s.breakOnStart=!1),this.postMessageCore(e,s),this.traceInterval&&this.setTraceInterval(this.traceInterval),this.applyAspectRatioToFrame(e),this.setFrameState(e),!0}handleDeferredMessages(e){var t,n,i;e.dataset.loading&&(delete e.dataset.loading,null===(n=null===(t=this.deferredMessages)||void 0===t?void 0:t.filter((t=>t[0]===e)))||void 0===n||n.forEach((t=>{const[n,i]=t;this.postMessageCore(e,i)})),this.deferredMessages=null===(i=this.deferredMessages)||void 0===i?void 0:i.filter((t=>t[0]!==e)))}handleMessage(e,n){var i,s,r;switch(e.type||""){case"ready":{const t=e.frameid,n=document.getElementById(t);n&&((null===(i=this._runOptions)||void 0===i?void 0:i.autofocus)&&n.focus(),this.startFrame(n),this.options.revealElement&&this.options.revealElement(n),this.handleDeferredMessages(n)),this.options.onSimulatorReady&&this.options.onSimulatorReady();break}case"status":{const n=e.frameid,i=document.getElementById(n);if(i){const n=e;if(n.runtimeid==i.dataset.runtimeid)switch(n.state){case"running":this.setState(t.Running),this.handleDeferredMessages(i);break;case"killed":this.setState(t.Stopped)}}break}case"simulator":this.handleSimulatorCommand(e);break;case"serial":case"pxteditor":case"screenshot":case"custom":case"recorder":case"addextensions":break;case"aspectratio":{const t=e,n=t.frameid,i=document.getElementById(n);i&&(i.dataset.aspectratio=t.value+"",this.applyAspectRatioToFrame(i));break}case"debugger":this.handleDebuggerMessage(e);break;case"toplevelcodefinished":this.options.onTopLevelCodeEnd&&this.options.onTopLevelCodeEnd();break;case"setmutebuttonstate":null===(r=(s=this.options).onMuteButtonStateChange)||void 0===r||r.call(s,e.state);break;default:this.postMessage(e,n)}}addEventListeners(){this.listener||(this.listener=t=>{if(!this.hwdbg){if(e.U.isLocalHost());else if(this._allowedOrigins.indexOf(t.origin)<0)return;this.handleMessage(t.data,t.source)}},window.addEventListener("message",this.listener,!1))}removeEventListeners(){this.listener&&(window.removeEventListener("message",this.listener,!1),this.listener=void 0)}resume(e){let s;switch(e){case n.Resume:s="resume",this.setState(t.Running);break;case n.StepInto:s="stepinto",this.setState(t.Running);break;case n.StepOut:s="stepout",this.setState(t.Running);break;case n.StepOver:s="stepover",this.setState(t.Running);break;case n.Pause:s="pause";break;default:return void console.debug("unknown command")}this.postMessage({type:"debugger",subtype:s,source:i})}setBreakpoints(e){this.breakpointsSet=!0,this.postDebuggerMessage("config",{setBreakpoints:e},void 0,this.debuggingFrame)}setTraceInterval(e){this.traceInterval=e,this.postDebuggerMessage("traceConfig",{interval:e})}variablesAsync(e,t,n=!1){return this.postDebuggerMessageAsync("variables",{variablesReference:e,fields:t,includeAll:n},this.debuggingFrame).then((e=>e),(e=>{}))}handleSimulatorCommand(e){this.options.onSimulatorCommand&&this.options.onSimulatorCommand(e)}clearDebugger(){const e=new Error("Debugging cancelled");Object.keys(this.debuggerResolvers).forEach((t=>{const{reject:n}=this.debuggerResolvers[t];n(e)})),this.debuggerResolvers={},this.debuggerSeq++}handleDebuggerMessage(e){if("trace"!==e.subtype&&console.log("DBG-MSG",e.subtype,e),e.seq){const{resolve:t}=this.debuggerResolvers[e.seq];t&&t(e)}switch(e.subtype){case"warning":this.options.onDebuggerWarning&&this.options.onDebuggerWarning(e);break;case"breakpoint":{const i=e;if(this.state==t.Running){if(i.exceptionMessage)this.suspend();else{this.setState(t.Paused);this.simFrames(!0).length>1&&this.resume(n.Pause)}this.options.onDebuggerBreakpoint&&this.options.onDebuggerBreakpoint(i);let e=i.exceptionMessage+"\n";for(let t of i.stackframes){let n=t.funcInfo;e+=` at ${n.functionName} (${n.fileName}:${n.line+1}:${n.column+1})\n`}i.exceptionMessage&&console.error(e)}else console.error("debugger: trying to pause from "+this.state);break}case"trace":{const n=e;this.state==t.Running&&this.options.onTraceMessage&&this.options.onTraceMessage(n);break}default:const i=e.req_seq;if(i){const{resolve:t}=this.debuggerResolvers[i];t&&(delete this.debuggerResolvers[i],t(e))}}}postDebuggerMessageAsync(e,t={},n){return new Promise(((i,s)=>{const r=this.debuggerSeq++;this.debuggerResolvers[r.toString()]={resolve:i,reject:s},this.postDebuggerMessage(e,t,r,n)}))}postDebuggerMessage(e,t={},n,s){const r=JSON.parse(JSON.stringify(t));r.type="debugger",r.subtype=e,r.source=i,n&&(r.seq=n),this.postMessage(r,void 0,s)}nextId(){return this.nextFrameId+++(Math.random()+""+Math.random()).replace(/[^\d]/,"")}get stoppedClass(){return this.options&&this.options.stoppedClass||"grayscale"}get invalidatedClass(){return this.options&&this.options.invalidatedClass||"sepia"}}}(pxsim||(pxsim={})),function(e){e.mkRange=function(e,t){let n=[];for(;e<t;e++)n.push(e);return n};e.EventBus=class{constructor(e,t,n){this.runtime=e,this.board=t,this.valueToArgs=n,this.queues={},this.backgroundHandlerFlag=!1,this.nextNotifyEvent=1024,this.schedulerID=15,this.idleEventID=2,this.board.addMessageListener(this.handleMessage.bind(this))}handleMessage(e){if("eventbus"===e.type){const t=e;this.queue(t.id,t.eventid,t.value)}}setBackgroundHandlerFlag(){this.backgroundHandlerFlag=!0}setNotify(e,t){this.notifyID=e,this.notifyOneID=t}setIdle(e,t){this.schedulerID=e,this.idleEventID=t}start(t,n,i,s=!1){let r=(i?"back":"fore")+":"+t+":"+n;return!this.queues[r]&&s&&(this.queues[r]=new e.EventQueue(this.runtime,this.valueToArgs)),this.queues[r]}listen(e,t,n,i=0){e==this.schedulerID&&t==this.idleEventID&&this.runtime.startIdle();let s=this.start(e,t,this.backgroundHandlerFlag,!0);this.backgroundHandlerFlag?s.addHandler(n,i):s.setHandler(n,i),this.backgroundHandlerFlag=!1}removeBackgroundHandler(e){Object.keys(this.queues).forEach((t=>{t.startsWith("back:")&&this.queues[t].removeHandler(e)}))}getQueues(e,t,n){let i=[this.start(0,0,n)];return 0==e&&0==t||(t&&i.push(this.start(0,t,n)),e&&i.push(this.start(e,0,n)),e&&t&&i.push(this.start(e,t,n))),i}queue(t,n,i=null){if(e.runtime.pausedOnBreakpoint)return;const s=this.notifyID&&this.notifyOneID&&t==this.notifyOneID;s&&(t=this.notifyID);let r=this.getQueues(t,n,!0).concat(this.getQueues(t,n,!1));this.lastEventValue=n,this.lastEventTimestampUs=e.U.perfNowUs(),e.U.promiseMapAllSeries(r,(e=>e?e.push(i,s):Promise.resolve()))}queueIdle(){this.schedulerID&&this.idleEventID&&this.queue(this.schedulerID,this.idleEventID)}wait(e,t,n){this.start(e,t,!1,!0).addAwaiter(n)}getLastEventValue(){return this.lastEventValue}getLastEventTime(){return 4294967295&this.lastEventTimestampUs-e.runtime.startTimeUs}};let t;function n(){return"undefined"!=typeof window&&("ontouchstart"in window||navigator&&navigator.maxTouchPoints>0)}function i(){return"undefined"!=typeof window&&!!window.PointerEvent}e.AnimationQueue=class{constructor(e){this.runtime=e,this.queue=[],this.process=()=>{let t=this.queue[0];if(!t)return;if(this.runtime.dead)return;e=this.runtime;let n=t.frame();e.queueDisplayUpdate(),e.maybeUpdateDisplay(),!1===n?(this.queue.shift(),this.queue[0]&&(this.queue[0].setTimeoutHandle=setTimeout(this.process,this.queue[0].interval)),t.whenDone(!1)):t.setTimeoutHandle=setTimeout(this.process,t.interval)}}cancelAll(){let e=this.queue;this.queue=[];for(let t of e)t.whenDone(!0),t.setTimeoutHandle&&clearTimeout(t.setTimeoutHandle)}cancelCurrent(){let e=this.queue[0];e&&(this.queue.shift(),e.whenDone(!0),e.setTimeoutHandle&&clearTimeout(e.setTimeoutHandle))}enqueue(e){e.whenDone||(e.whenDone=()=>{}),this.queue.push(e),1==this.queue.length&&this.process()}executeAsync(t){return e.U.assert(!t.whenDone),new Promise(((e,n)=>{t.whenDone=e,this.enqueue(t)}))}},function(t){let n,i,s,r,o=0,a=!1;const l=[];let c,u=[];function d(){return n||(n=function(){if(window.AudioContext=window.AudioContext||window.webkitAudioContext,window.AudioContext)try{return new window.AudioContext}catch(e){}return}(),n&&(c=n.createGain(),c.connect(n.destination),c.gain.setValueAtTime(1,0))),n}function h(){E(0),o=0,r&&r.pause()}function p(e,t){e.gain.value&&e.gain.setTargetAtTime(0,d().currentTime,.015),setTimeout((()=>{e.disconnect(),t&&t.disconnect()}),450)}t.isAudioElementActive=function(){return!!s},t.mute=function(e){a=e;const t=d();e?c.gain.setTargetAtTime(0,t.currentTime,.015):c.gain.setTargetAtTime(1,t.currentTime,.015),!e&&t&&"suspended"===t.state&&t.resume()},t.isMuted=function(){return a},t.stopAll=function(){h(),x();for(const e of u)e()},t.stop=function(){h(),function(){if(s){try{p(s,i)}catch(e){}s=void 0,i=void 0}}()},t.onStopAll=function(e){u.push(e)},t.frequency=function(){return o};const f=[null,"triangle","sawtooth","sine"];let m,g,b=[],y=[];function v(e,t){let n,i=f[e];if(i){let e=d().createOscillator();return e.type=i,e.frequency.value=t,e}if(4==e)n=function(){if(!g){const e=131072;g=d().createBuffer(1,e,d().sampleRate);const t=g.getChannelData(0);let n=251771520;for(let i=0;i<e;i+=4)n^=n<<13,n^=n>>17,n^=n<<5,32768&n?(t[i]=1,t[i+1]=1,t[i+2]=-1,t[i+3]=-1):(t[i]=0,t[i+1]=0,t[i+2]=0,t[i+3]=0)}return g}();else if(5==e)n=function(){if(!m){const e=1e5;m=d().createBuffer(1,e,d().sampleRate);const t=m.getChannelData(0);let n=251771520;for(let i=0;i<e;i++)n^=n<<13,n^=n>>17,n^=n<<5,t[i]=(1023&n)/512-1}return m}();else if(11<=e&&e<=15)n=function(e){if(!y[e]){const t=1024,n=d().createBuffer(1,t,d().sampleRate),i=n.getChannelData(0);for(let n=0;n<t;n++)i[n]=n<e/100*t?1:-1;y[e]=n}return y[e]}(10*(e-10));else{if(!(16<=e&&e<=18))return null;n=function(e){if(!b[e]){const t=1024,n=d().createBuffer(1,t,d().sampleRate),i=n.getChannelData(0),s=[770763591,3356908179],r=[15,31,63];for(let n=0;n<t;n+=4){let t,o=n/4;o&=r[e-4],t=0!=(s[o>>5]&1<<(31&o)),t?(i[n]=1,i[n+1]=1,i[n+2]=-1,i[n+3]=-1):(i[n]=0,i[n+1]=0,i[n+2]=0,i[n+3]=0)}b[e]=n}return b[e]}(e-16+4)}let s=d().createBufferSource();s.buffer=n,s.loop=!0;return 4==e||16<=e&&e<=18?s.playbackRate.value=t/(d().sampleRate/4):5!=e&&(s.playbackRate.value=t/(d().sampleRate/1024)),s}class w{disconnectNodes(){this.gain?p(this.gain,this.generator):this.generator&&(this.generator.stop(),this.generator.disconnect()),this.gain=null,this.generator=null}remove(){const e=l.indexOf(this);e>=0&&l.splice(e,1),this.disconnectNodes()}}let k=1;function x(){for(null===t.soundEventCallback||void 0===t.soundEventCallback||t.soundEventCallback("muteallchannels"),k++;l.length;)l[0].remove()}function A(e,t){if(e<0)return;o=e;let n=d();if(n){t=Math.max(0,Math.min(1,t));try{i||(i=n.createOscillator(),s=n.createGain(),s.gain.value=0,i.type="triangle",i.connect(s),s.connect(c),i.start(0)),E(t)}catch(e){return i=void 0,void(s=void 0)}i.frequency.value=e,E(t)}}function E(e){(null==s?void 0:s.gain)&&s.gain.setTargetAtTime(e,n.currentTime,.015)}t.muteAllChannels=x,t.queuePlayInstructions=function(t,n){const i=k;e.U.delay(t).then((()=>i!=k?Promise.resolve():T(n.data)))},t.tone=A,t.setCurrentToneGain=E,t.playBufferAsync=function(e){return e?new Promise((t=>{function n(){t&&t(),t=void 0}const i="data:audio/wav;base64,"+window.btoa(function(e){let t=e.length,n="";for(let i=0;i<t;++i)n+=String.fromCharCode(e[i]);return n}(e.data));r=new Audio(i),a&&(r.volume=0),r.onended=()=>n(),r.onpause=()=>n(),r.onerror=()=>n(),r.play()})):Promise.resolve()};function T(n,i,s){return new Promise((async r=>{null===t.soundEventCallback||void 0===t.soundEventCallback||t.soundEventCallback("playinstructions",n);let o=!1,a=d(),u=new w;l.length>20&&l[0].remove(),l.push(u),u.gain=a.createGain(),u.gain.gain.value=1,u.gain.connect(c);const h={},p={};let f=a.currentTime,m=f,g=0,b=0;const y=(e,t)=>e/1024/4*(t?.5:1),k=()=>{if(!o){o=!0,u.disconnectNodes();for(const e of Object.keys(h))h[e].stop(),h[e].disconnect(),p[e].disconnect();r()}};for(let e=0;e<n.length;e+=12){const t=n[e],i=S(n,e+2),s=S(n,e+4)/1e3,r=S(n,e+6),o=S(n,e+8),l=S(n,e+10);if(b+=s,0===t){m+=s;continue}const c=11<=t&&t<=15;h[t]||(h[t]=v(t,i),p[t]=a.createGain(),p[t].gain.value=0,p[t].connect(u.gain),h[t].connect(p[t]),h[t].start()),g&&t!==g&&p[g].gain.setTargetAtTime(0,m,.015);const d=h[t],f=p[t];if(d instanceof OscillatorNode)d.frequency.setValueAtTime(i,m),d.frequency.linearRampToValueAtTime(l,m+s);else{4==t||16<=t&&t<=18?d.playbackRate.linearRampToValueAtTime(l/(a.sampleRate/4),m+s):5!=t&&d.playbackRate.linearRampToValueAtTime(l/(a.sampleRate/1024),m+s)}f.gain.setValueAtTime(y(r,c),m),f.gain.linearRampToValueAtTime(y(o,c),m+s),g=t,m+=s}if(u.gain.gain.setTargetAtTime(0,m,.015),i||s){const e=()=>{const t=a.currentTime;if(t>f+b)return;if(i&&i())return void k();const{frequency:r,volume:o}=function(e,t){let n=0;for(let i=0;i<t.length;i+=12){const s=S(t,i+2),r=S(t,i+4),o=S(t,i+6),a=S(t,i+8),l=S(t,i+10);if(n+r<e){n+=r;continue}const c=(e-n)/r;return{frequency:s+(l-s)*c,volume:o+(a-o)*c}}return{frequency:-1,volume:-1}}(1e3*(t-f),n);s&&s(r,o/1024),requestAnimationFrame(e)};requestAnimationFrame(e)}await e.U.delay(1e3*b),k()}))}function S(e,t){const n=new Uint8Array(2);return n[0]=e[t],n[1]=e[t+1],new Uint16Array(n.buffer)[0]}t.playPCMBufferStreamAsync=function(e,t,n=.3,i){return new Promise((s=>{let r=[],o=d().currentTime,a=!1;const u=new w;u.gain=d().createGain(),u.gain.gain.value=0,u.gain.gain.setValueAtTime(n,d().currentTime),u.gain.connect(c),l.length>20&&l[0].remove(),l.push(u);const h=()=>!!(i&&i()||!u.gain)&&(s&&s(),s=void 0,u.remove(),!0);function p(){for(;!a&&r.length<3&&!h();){const t=e();if(!t||!t.length){a=!0;break}f(t)}a&&0===r.length&&(u.remove(),s&&s(),s=void 0)}function f(e){if(h())return;const n=d().createBuffer(1,e.length,t);if(n.copyToChannel)n.copyToChannel(e,0);else{const t=n.getChannelData(0);for(let n=0;n<e.length;n++)t[n]=e[n]}const i=d().createBufferSource();r.push(i),i.connect(u.gain),i.buffer=n,i.addEventListener("ended",(()=>{r.shift().disconnect(),p()})),i.start(o),o+=n.duration}p()}))},t.playInstructionsAsync=T,t.sendMidiMessage=function(e){const t=e.data;if(!t.length)return;const n=t[0]>>4,i=15&t[0],s=t[1]||0,r=(o=s,440*Math.pow(2,(o-69)/12));var o;const a=t[2]||0;8==n||9==n&&0==a?h():9==n&&(A(r,1),9==i&&setTimeout((()=>h()),500))}}(t=e.AudioContextManager||(e.AudioContextManager={})),e.isTouchEnabled=n,e.hasPointerEvents=i,e.pointerEvents=i()?{up:"pointerup",down:["pointerdown"],move:"pointermove",enter:"pointerenter",leave:"pointerleave"}:n()?{up:"mouseup",down:["mousedown","touchstart"],move:"touchmove",enter:"touchenter",leave:"touchend"}:{up:"mouseup",down:["mousedown"],move:"mousemove",enter:"mouseenter",leave:"mouseleave"}}(pxsim||(pxsim={})),function(e){!function(t){function n(e,t){return n=>n*(t/e)}function i(e,t){let n=e[0]-t[0],i=e[1]-t[1];return n*n+i*i}t.translateEl=function(t,n){e.svg.hydrate(t,{transform:`translate(${n[0]} ${n[1]})`})},t.composeSVG=function(t){let[n,i]=[t.el1,t.el2];e.U.assert(0==n.x&&0==n.y&&0==i.x&&0==i.y,"el1 and el2 x,y offsets not supported");let s=(t,n,i)=>e.svg.hydrate(t,{x:n,y:i}),r=(t,n,i)=>e.svg.hydrate(t,{width:`${n}px`,height:`${i}px`}),o=t.scaleUnit2,a=t.scaleUnit2/t.scaleUnit1,l=n.w*a,c=n.h*a;r(n.el,l,c);let u=1*i.w,d=1*i.h;r(i.el,u,d);let[h,p,f,m]=t.margin,g=t.middleMargin,b=Math.max(l,u),y=p+(b-l)/2,v=h;s(n.el,y,v);let w=p+(b-u)/2,k=v+c+g;s(i.el,w,k);let x=[v,v+c,k,k+d],A=p+b+m,E=h+c+g+d+f,T=e.svg.elt("svg",{version:"1.0",viewBox:`0 0 ${A} ${E}`,class:"sim-bb"});((t,n,i)=>{n&&e.svg.hydrate(t,{width:n}),i&&e.svg.hydrate(t,{height:i})})(T,t.maxWidth,t.maxHeight),s(T,0,0);let S=e.svg.child(T,"g");return T.appendChild(n.el),T.appendChild(i.el),{under:S,over:e.svg.child(T,"g"),host:T,edges:x,scaleUnit:o,toHostCoord1:e=>{let[t,n]=e;return[t*a+y,n*a+v]},toHostCoord2:e=>{let[t,n]=e;return[1*t+w,1*n+k]}}},t.mkScaleFn=n,t.mkImageSVG=function(t){let i=n(t.imageUnitDist,t.targetUnitDist),s=i(t.width),r=i(t.height),o=e.svg.elt("image",{width:s,height:r});return o.setAttributeNS("http://www.w3.org/1999/xlink","href",`${t.image}`),{el:o,w:s,h:r,x:0,y:0}},t.findDistSqrd=i,t.findClosestCoordIdx=function(e,t){return t.map((t=>i(e,t))).reduce(((e,t,n,i)=>t<i[e]?n:e),0)},t.mkTxt=function(t,n,i,s,r,o,a){let l=e.svg.elt("text");a=a||.3;const c=(o=o||-.33333)*i*r.length,u=a*i;return e.svg.hydrate(l,{style:`font-size:${i}px;`,transform:`translate(${t} ${n}) rotate(${s}) translate(${c} ${u})`}),e.U.addClass(l,"noselect"),l.textContent=r,l},t.GPIO_WIRE_COLORS=["pink","orange","yellow","green","purple"],t.WIRE_COLOR_MAP={black:"#514f4d",white:"#fcfdfc",gray:"#acabab",purple:"#a772a1",blue:"#01a6e8",green:"#3cce73",yellow:"#ece600",orange:"#fdb262",red:"#f44f43",brown:"#c89764",pink:"#ff80fa"},t.mapWireColor=function(e){return t.WIRE_COLOR_MAP[e]||e},t.PIN_DIST=15,t.rgbToHsl=function(e){let t,n,i,[s,r,o]=e,[a,l,c]=[s/255,r/255,o/255],u=Math.min(a,l,c),d=Math.max(a,l,c),h=d-u,p=d+u;return i=p/2*100,0===h?n=t=0:(d===a?t=(l-c)/h%6*60:d===l?t=60*((c-a)/h+2):d===c&&(t=60*((a-l)/h+4)),n=i>50?h/(2-p)*100:h/p*100),[Math.floor(t),Math.floor(n),Math.floor(i)]}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){var t;!function(n){function i(e,n,i){let s={class:e,d:n};i&&(s.title=i);let r=t.elt("path");return t.hydrate(r,s),r}function s(e,n=!1){let i=t.elt("linearGradient");t.hydrate(i,{id:e,x1:"0%",y1:"0%",x2:n?"100%":"0%",y2:n?"0%":"100%"});t.child(i,"stop",{offset:"0%"}),t.child(i,"stop",{offset:"100%"}),t.child(i,"stop",{offset:"100%"}),t.child(i,"stop",{offset:"100%"});return i}function r(e){let n=t.elt("title");return n.textContent=e,n}n.parseString=function(e){return(new DOMParser).parseFromString(e,"image/svg+xml").getElementsByTagName("svg").item(0)},n.toDataUri=function(e){return"data:image/svg+xml,"+encodeURI(e)},n.cursorPoint=function(e,t,n){return e.x=null!=n.clientX?n.clientX:n.pageX,e.y=null!=n.clientY?n.clientY:n.pageY,e.matrixTransform(t.getScreenCTM().inverse())},n.rotateElement=function(e,t,n,i){e.setAttribute("transform",`translate(${t},${n}) rotate(${i+90}) translate(${-t},${-n})`)},n.hydrate=function(e,n){for(let i in n)"title"==i?t.title(e,n[i]):e.setAttributeNS(null,i,n[i])},n.elt=function(e,n){let i=document.createElementNS("http://www.w3.org/2000/svg",e);return n&&t.hydrate(i,n),i},n.child=function(e,n,i){let s=t.elt(n,i);return e.appendChild(s),s},n.mkPath=i,n.path=function(e,t,n,s){let r=i(t,n,s);return e.appendChild(r),r},n.fill=function(e,t){e.style.fill=t},n.filter=function(e,t){e.style.filter=t},n.fills=function(e,t){e.forEach((e=>e.style.fill=t))},n.isTouchEnabled=function(){return"undefined"!=typeof window&&("ontouchstart"in window||navigator.maxTouchPoints>0)},n.onClick=function(t,n){let i=!1;e.pointerEvents.down.forEach((e=>t.addEventListener(e,(e=>(i=!0,!0)),!1))),t.addEventListener(e.pointerEvents.up,(e=>!i||(i=!1,n(e),e.preventDefault(),!1)),!1)},n.buttonEvents=function(t,n,i,s,r){let o=!1;e.pointerEvents.down.forEach((e=>t.addEventListener(e,(e=>(o=!0,i&&i(e),!0)),!1))),t.addEventListener(e.pointerEvents.move,(e=>!o||(n&&n(e),e.preventDefault(),!1)),!1),t.addEventListener(e.pointerEvents.up,(e=>{o=!1,s&&s(e)}),!1),t.addEventListener(e.pointerEvents.leave,(e=>{o=!1,s&&s(e)}),!1),t.addEventListener("keydown",(e=>{o=!1,r&&r(e)}))},n.mkLinearGradient=s,n.linearGradient=function(e,t,n=!1){let i=s(t,n);return e.appendChild(i),i},n.setGradientColors=function(e,t,n){e&&(e.childNodes[0].style.stopColor=t,e.childNodes[1].style.stopColor=t,e.childNodes[2].style.stopColor=n,e.childNodes[3].style.stopColor=n)},n.setGradientValue=function(e,t){e.childNodes[1].getAttribute("offset")!=t&&(e.childNodes[1].setAttribute("offset",t),e.childNodes[2].setAttribute("offset",t))},n.animate=function(t,n){e.U.addClass(t,n);let i=t.parentElement;i&&(i.removeChild(t),i.appendChild(t))},n.mkTitle=r,n.title=function(e,t){let n=r(t);return e.appendChild(n),n},n.toHtmlColor=function(e){return`rgba(${e>>16&255}, ${e>>8&255}, ${255&e}, ${e>>24&1})`}}(t=e.svg||(e.svg={}))}(pxsim||(pxsim={})),function(e){!function(e){e.Metronome=class{constructor(){this.tickListeners=[],this.onTick=()=>{for(const e of this.tickListeners)e()}}initAsync(){return this.metronomeLoadPromise?this.metronomeLoadPromise:this.metronomeWorker?this.metronomeWorker:(this.metronomeLoadPromise=new Promise((e=>{this.metronomeWorker=new Worker("data:application/javascript,"+encodeURIComponent(t));const n=t=>{"ready"===t.data&&(e(this.metronomeWorker),this.metronomeWorker.removeEventListener("message",n),this.metronomeWorker.addEventListener("message",this.onTick))};this.metronomeWorker.addEventListener("message",n)})),this.metronomeLoadPromise)}stop(){this.postMessage({type:"stop"})}setInterval(e){this.currentInterval=e,this.postMessage({type:"set-interval",interval:e})}start(e){this.currentInterval=e,this.postMessage({type:"start",interval:e})}addTickListener(e){this.tickListeners.push(e)}removeTickListener(e){this.tickListeners=this.tickListeners.filter((t=>t!==e))}interval(){return this.currentInterval}dispose(){if(this.metronomeWorker)this.metronomeWorker.terminate(),this.metronomeWorker=void 0,this.metronomeLoadPromise=void 0,this.tickListeners=[],this.interval=void 0;else if(this.metronomeLoadPromise)return void this.metronomeLoadPromise.then((()=>this.dispose()))}postMessage(e){if(!this.metronomeWorker)throw new Error("initAsync not called on metronome");this.metronomeWorker.postMessage(e)}};const t='\n/**\n * Adpated from https://github.com/cwilso/metronome/\n */\n\nlet timerRef;\nlet interval;\n\naddEventListener("message", ev => {\n const message = ev.data;\n\n if (message.type === "start") {\n updateInterval(message.interval, true);\n }\n else if (message.type === "stop") {\n clearInterval(timerRef);\n timerRef = undefined;\n }\n else if (message.type === "set-interval") {\n updateInterval(message.interval, false);\n }\n})\n\npostMessage("ready");\n\nfunction updateInterval(interval, startIfStopped) {\n if (timerRef) {\n clearInterval(timerRef);\n startIfStopped = true;\n }\n interval = interval;\n\n if (startIfStopped) {\n timerRef = setInterval(() => postMessage("tick"), interval);\n }\n}\n'}(e.music||(e.music={}))}(pxsim||(pxsim={})),function(e){!function(e){!function(e){!function(e){e.chromaticInterval=[1,1.0417,1.125,1.2,1.25,1.3333,1.4063,1.5,1.6,1.6667,1.8,1.875],e.majorScaleInterval=[e.chromaticInterval[0],e.chromaticInterval[2],e.chromaticInterval[4],e.chromaticInterval[5],e.chromaticInterval[7],e.chromaticInterval[9],e.chromaticInterval[11]],e.minorScaleInterval=[e.chromaticInterval[0],e.chromaticInterval[2],e.chromaticInterval[3],e.chromaticInterval[5],e.chromaticInterval[7],e.chromaticInterval[8],e.chromaticInterval[10]],e.pentatonicScaleInterval=[e.chromaticInterval[0],e.chromaticInterval[2],e.chromaticInterval[4],e.chromaticInterval[7],e.chromaticInterval[9]],e.majorTriadInterval=[e.chromaticInterval[0],e.chromaticInterval[4],e.chromaticInterval[7]],e.minorTriadInterval=[e.chromaticInterval[0],e.chromaticInterval[3],e.chromaticInterval[7]],e.diminishedInterval=[e.chromaticInterval[0],e.chromaticInterval[3],e.chromaticInterval[6],e.chromaticInterval[9]],e.wholeToneInterval=[e.chromaticInterval[0],e.chromaticInterval[2],e.chromaticInterval[4],e.chromaticInterval[6],e.chromaticInterval[8],e.chromaticInterval[10]]}(e.MusicalIntervals||(e.MusicalIntervals={}))}(e.music||(e.music={}))}(e.codal||(e.codal={}))}(pxsim||(pxsim={})),function(e){!function(e){!function(e){!function(t){t.chromatic={interval:e.MusicalIntervals.chromaticInterval,length:12},t.majorScale={interval:e.MusicalIntervals.majorScaleInterval,length:7},t.minorScale={interval:e.MusicalIntervals.minorScaleInterval,length:7},t.pentatonicScale={interval:e.MusicalIntervals.pentatonicScaleInterval,length:5},t.majorTriad={interval:e.MusicalIntervals.majorTriadInterval,length:3},t.minorTriad={interval:e.MusicalIntervals.minorTriadInterval,length:3},t.diminished={interval:e.MusicalIntervals.diminishedInterval,length:4},t.wholeTone={interval:e.MusicalIntervals.wholeToneInterval,length:6},t.calculateFrequencyFromProgression=function(e,t,n){let i=Math.floor(n/t.length),s=n%t.length;return e*Math.pow(2,i)*t.interval[s]}}(e.MusicalProgressions||(e.MusicalProgressions={}))}(e.music||(e.music={}))}(e.codal||(e.codal={}))}(pxsim||(pxsim={})),function(e){!function(t){const n=[31,33,35,37,39,41,44,46,49,52,55,58,62,65,69,73,78,82,87,92,98,104,110,117,123,131,139,147,156,165,175,185,196,208,220,233,247,262,277,294,311,330,349,370,392,415,440,466,494,523,554,587,622,659,698,740,784,831,880,932,988,1047,1109,1175,1245,1319,1397,1480,1568,1661,1760,1865,1976,2093,2217,2349,2489,2637,2794,2960,3136,3322,3520,3729,3951,4186,4435,4699,4978,5274,5588,5920,6272,6645,7040,7459,7902];async function i(t,i,s,r,o=100){await e.AudioContextManager.playInstructionsAsync(e.music.renderInstrument(i,n[t],s,o),r)}async function s(t,n,i=100){await e.AudioContextManager.playInstructionsAsync(e.music.renderDrumInstrument(t,i),n)}function r(e,t,n){return 6e4/e/t*n}t.Sequencer=class{constructor(){this._currentTick=0,this._state="stop",this.listeners={},this.globalVolume=1024,this.trackVolumes=[],this.drumTrackVolumes=[],this.currentCancelToken={cancelled:!1},this.onTick=()=>{const e=this.currentCancelToken;for(let t=0;t<this.currentlyPlaying.tracks.length;t++){const n=this.currentlyPlaying.tracks[t];for(const o of n.notes)if(o.startTick===this._currentTick)for(const a of o.notes)n.drums?s(n.drums[a.note],(()=>e.cancelled),this.getDrumTrackVolume(t,a.note)):i(a.note,n.instrument,r(this.currentlyPlaying.beatsPerMinute,this.currentlyPlaying.ticksPerBeat,o.endTick-o.startTick),(()=>e.cancelled),this.getMelodicTrackVolume(t));else if(o.startTick>this._currentTick)break}this.fireEvent("tick"),this._currentTick++,this._currentTick>=this.maxTick()&&("loop"===this._state?(this._currentTick=0,this.fireEvent("looped")):this.stop(!0))}}async initAsync(){this.metronome?await this.metronome.initAsync():(this.metronome=new t.Metronome,await this.metronome.initAsync(),this.metronome.addTickListener(this.onTick))}dispose(){this.metronome&&this.metronome.dispose(),this.metronome=void 0,this.stop(),this.currentlyPlaying=void 0,this.listeners={}}state(){return this._state}currentTick(){return this._currentTick}currentTime(){return r(this.currentlyPlaying.beatsPerMinute,this.currentlyPlaying.ticksPerBeat,this.currentTick())}maxTick(){return this.currentlyPlaying?this.currentlyPlaying.measures*this.currentlyPlaying.beatsPerMeasure*this.currentlyPlaying.ticksPerBeat:0}duration(){return r(this.currentlyPlaying.beatsPerMinute,this.currentlyPlaying.ticksPerBeat,this.maxTick())}start(e,t){this.startFrom(e,t,0)}startFrom(e,t,n){"stop"!==this._state&&this.stop(),void 0!==t&&(this.shouldLoop=t),this._currentTick=null!=n?n:0,this.currentlyPlaying=e,this.metronome.start(r(e.beatsPerMinute,e.ticksPerBeat,1)),this._state=this.shouldLoop?"loop":"play",this.fireStateChange()}stop(e=!1){"stop"!==this._state&&(this._state="stop",this.metronome&&this.metronome.stop(),this.fireStateChange(),e||(this.currentCancelToken.cancelled=!0),this.currentCancelToken={cancelled:!1})}updateSong(e){this.currentlyPlaying=e,"stop"!==this._state&&this.metronome.setInterval(r(e.beatsPerMinute,e.ticksPerBeat,1))}setLooping(e){e&&"play"===this._state?(this._state="loop",this.fireStateChange()):e||"loop"!==this._state||(this._state="play",this.fireStateChange()),this.shouldLoop=e}addEventListener(e,t){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(t)}removeEventListener(e,t){this.listeners[e]&&(this.listeners[e]=this.listeners[e].filter((e=>e!==t)))}setVolume(e){this.globalVolume=Math.min(Math.max(e,0),1024)}setTrackVolume(e,t){for(t=Math.min(Math.max(t,0),1024);this.trackVolumes.length<e;)this.trackVolumes.push(1024);this.trackVolumes[e]=t}setDrumTrackVolume(e,t,n){for(n=Math.min(Math.max(n,0),1024);this.drumTrackVolumes.length<e;)this.drumTrackVolumes.push([]);for(;this.drumTrackVolumes[e].length<t;)this.drumTrackVolumes[e].push(1024);this.drumTrackVolumes[e][t]=n}getMelodicTrackVolume(e){let t=1024;return e<this.trackVolumes.length&&(t=this.trackVolumes[e]),this.globalVolume*(t/1024)}getDrumTrackVolume(e,t){const n=this.getMelodicTrackVolume(e);let i=1024;return e<this.drumTrackVolumes.length&&t<this.drumTrackVolumes[e].length&&(i=this.drumTrackVolumes[e][t]),n*(i/1024)}fireStateChange(){this.fireEvent(this._state),this.fireEvent("state-change")}fireEvent(e){if(this.listeners[e])for(const t of this.listeners[e])t()}},t.playNoteAsync=i,t.playDrumAsync=s,t.tickToMs=r}(e.music||(e.music={}))}(pxsim||(pxsim={})),function(e){!function(e){function t(e,t,n,r){var o,a;let l=0;return(null===(o=e.pitchEnvelope)||void 0===o?void 0:o.amplitude)&&(l+=i(e.pitchEnvelope,r,n)),(null===(a=e.pitchLFO)||void 0===a?void 0:a.amplitude)&&(l+=s(e.pitchLFO,r)),Math.max(t+l,0)}function n(e,t,n,r){var o;let a=0;return e.ampEnvelope.amplitude&&(a+=i(e.ampEnvelope,n,t)),(null===(o=e.ampLFO)||void 0===o?void 0:o.amplitude)&&(a+=s(e.ampLFO,n)),Math.max(Math.min(a,e.ampEnvelope.amplitude),0)/1024*r|0}function i(e,t,n){const i=e.sustain/1024*e.amplitude;if(t>n){if(t-n>e.release)return 0;if(t<e.attack){const i=e.amplitude/e.attack*n;return i-i/e.release*(t-n)}if(t<e.attack+e.decay){const s=e.amplitude-(e.amplitude-i)/e.decay*(n-e.attack);return s-s/e.release*(t-n)}return i-i/e.release*(t-n)}return t<e.attack?e.amplitude/e.attack*t:t<e.attack+e.decay?e.amplitude-(e.amplitude-i)/e.decay*(t-e.attack):i}function s(e,t){return Math.cos(t/1e3*e.frequency*2*Math.PI)*e.amplitude}function r(e,t,n,i,s,r,a,l){return n>0&&(e[t]=r,e[t+1]=0,o(e,t+2,a),o(e,t+4,n),o(e,t+6,255*i>>6),o(e,t+8,255*s>>6),o(e,t+10,l),t+=12),e[t]=0,t}function o(e,t,n){const i=new Uint8Array(2);new Uint16Array(i.buffer)[0]=0|n,e[t]=i[0],e[t+1]=i[1]}function a(e,t){const n=new Uint8Array(2);return n[0]=e[t],n[1]=e[t+1],new Uint16Array(n.buffer)[0]}function l(e,t){return{waveform:e[t],ampEnvelope:{attack:a(e,t+1),decay:a(e,t+3),sustain:a(e,t+5),release:a(e,t+7),amplitude:a(e,t+9)},pitchEnvelope:{attack:a(e,t+11),decay:a(e,t+13),sustain:a(e,t+15),release:a(e,t+17),amplitude:a(e,t+19)},ampLFO:{frequency:e[t+21],amplitude:a(e,22)},pitchLFO:{frequency:e[t+24],amplitude:a(e,25)},octave:e[t+27]}}function c(e,t){return e[t+1]?function(e,t){const n={id:e[t],instrument:{ampEnvelope:{attack:0,decay:0,sustain:0,release:0,amplitude:0},waveform:0},notes:[],drums:[]},i=a(e,t+2);let s=t+4;for(;s<t+4+i;)n.drums.push(u(e,s)),s+=5+7*n.drums[n.drums.length-1].steps.length;const r=a(e,s);s+=2;for(;s<t+4+i+r;)n.notes.push(d(e,s,0,!0)),s+=5+n.notes[n.notes.length-1].notes.length;return[n,s]}(e,t):function(e,t){const n={id:e[t],instrument:l(e,t+4),notes:[]},i=t+4+a(e,t+2),s=a(e,i);let r=i+2;for(;r<i+2+s;)n.notes.push(d(e,r,n.instrument.octave,!1)),r+=5+n.notes[n.notes.length-1].notes.length;return[n,r]}(e,t)}function u(e,t){const n={startFrequency:a(e,t+1),startVolume:a(e,t+3),steps:[]};for(let i=0;i<e[t];i++){const s=t+5+7*i;n.steps.push({waveform:e[s],frequency:a(e,s+1),volume:a(e,s+3),duration:a(e,s+5)})}return n}function d(e,t,n,i){const s={startTick:a(e,t),endTick:a(e,t+2),notes:[]};for(let r=0;r<e[t+4];r++)s.notes.push(h(e[t+5+r],n,i));return s}function h(e,t,n){const i=e>>6,s={note:n?e:(63&e)+12*(t-2),enharmonicSpelling:"normal"};return 1===i?s.enharmonicSpelling="flat":2===i&&(s.enharmonicSpelling="sharp"),s}e.renderInstrument=function(e,i,s,o){var a,l,c,u,d;const h=s+e.ampEnvelope.release,p=(null===(a=e.ampLFO)||void 0===a?void 0:a.amplitude)?Math.max(500/e.ampLFO.frequency,50):50,f=(null===(l=e.pitchLFO)||void 0===l?void 0:l.amplitude)?Math.max(500/e.pitchLFO.frequency,50):50;let m=[0],g=e.ampEnvelope.attack,b=(null===(c=e.pitchEnvelope)||void 0===c?void 0:c.amplitude)?e.pitchEnvelope.attack:h,y=(null===(u=e.pitchLFO)||void 0===u?void 0:u.amplitude)?f:h,v=(null===(d=e.ampLFO)||void 0===d?void 0:d.amplitude)?p:h,w=0;for(;w<h&&(g<=b&&g<=y&&g<=v?(w=g,m.push(g),g=w<e.ampEnvelope.attack+e.ampEnvelope.decay&&e.ampEnvelope.attack+e.ampEnvelope.decay<s?e.ampEnvelope.attack+e.ampEnvelope.decay:w<s?s:h):b<=y&&b<=v&&b<h?(w=b,m.push(b),b=w<e.pitchEnvelope.attack+e.pitchEnvelope.decay&&e.pitchEnvelope.attack+e.pitchEnvelope.decay<s?e.pitchEnvelope.attack+e.pitchEnvelope.decay:w<s?s:w<s+e.pitchEnvelope.release?Math.min(h,s+e.pitchEnvelope.release):h):y<=v&&y<h?(w=y,m.push(y),y+=f):v<h&&(w=v,m.push(v),v+=p),!(w>=h));){for(g<=w&&(g=w<e.ampEnvelope.attack+e.ampEnvelope.decay&&e.ampEnvelope.attack+e.ampEnvelope.decay<s?e.ampEnvelope.attack+e.ampEnvelope.decay:w<s?s:h),b<=w&&(b=w<e.pitchEnvelope.attack+e.pitchEnvelope.decay&&e.pitchEnvelope.attack+e.pitchEnvelope.decay<s?e.pitchEnvelope.attack+e.pitchEnvelope.decay:w<s?s:w<s+e.pitchEnvelope.release?Math.min(h,s+e.pitchEnvelope.release):h);v<=w;)v+=p;for(;y<=w;)y+=f}let k,x,A=0|n(e,s,0,o),E=0|t(e,i,s,0),T=0;const S=new Uint8Array(12*(m.length+1));for(let a=1;a<m.length;a++)m[a]-T<5||(k=0|n(e,s,m[a],o),x=0|t(e,i,s,m[a]),r(S,12*(a-1),m[a]-T|0,A,k,e.waveform,E,x),A=k,E=x),T=m[a];return r(S,12*m.length,10,A,0,e.waveform,E,E),S},e.renderDrumInstrument=function(e,t){let n=e.startVolume,i=e.startFrequency;const s=e=>e/1024*t;let o=new Uint8Array(12*(e.steps.length+1));for(let t=0;t<e.steps.length;t++)r(o,12*t,e.steps[t].duration,s(n),s(e.steps[t].volume),e.steps[t].waveform,i,e.steps[t].frequency),n=e.steps[t].volume,i=e.steps[t].frequency;return r(o,12*e.steps.length,10,s(n),0,e.steps[e.steps.length-1].waveform,i,i),o},e.decodeSong=function(e){const t={beatsPerMinute:a(e,1),beatsPerMeasure:e[3],ticksPerBeat:e[4],measures:e[5],tracks:[]};let n=7;for(;n<e.length;){const[i,s]=c(e,n);n=s,t.tracks.push(i)}return t}}(e.music||(e.music={}))}(pxsim||(pxsim={})),function(e){!function(e){!function(e){e.EMOJI_SYNTHESIZER_SAMPLE_RATE=44100,e.EMOJI_SYNTHESIZER_TONE_WIDTH_F=1024,e.EMOJI_SYNTHESIZER_TONE_WIDTH=1024,e.EMOJI_SYNTHESIZER_BUFFER_SIZE=512,e.EMOJI_SYNTHESIZER_TONE_EFFECT_PARAMETERS=2,e.EMOJI_SYNTHESIZER_TONE_EFFECTS=3,e.EMOJI_SYNTHESIZER_STATUS_ACTIVE=1,e.EMOJI_SYNTHESIZER_STATUS_OUTPUT_SILENCE_AS_EMPTY=2,e.EMOJI_SYNTHESIZER_STATUS_STOPPING=4;e.SoundEmojiSynthesizer=class{constructor(t,n=e.EMOJI_SYNTHESIZER_SAMPLE_RATE){this.samplesPerStep=[],this.status=0,this.effectPointer=0,this.position=0,this.bufferSize=e.EMOJI_SYNTHESIZER_BUFFER_SIZE,this.sampleRate=n,this.samplesToWrite=0,this.samplesWritten=0,this.sampleRange=1023,this.orMask=0,this.effectPointer=-1,this.volume=1}get effect(){return this.effectBuffer[this.effectPointer]}play(e){this.effectBuffer=e,this.effectPointer=-1,this.nextSoundEffect()}nextSoundEffect(){const t=null!=this.effect;if(this.status&e.EMOJI_SYNTHESIZER_STATUS_STOPPING&&(this.effectPointer=null,this.effectBuffer=[]),this.effect?this.effectPointer++:this.effectPointer=0,this.effectPointer>=this.effectBuffer.length&&(this.effectPointer=0,this.effect.duration>=0))return this.effectPointer=-1,this.effectBuffer=[],this.samplesWritten=0,this.samplesToWrite=0,this.position=0,t;this.samplesToWrite=this.determineSampleCount(this.effect.duration),this.frequency=this.effect.frequency,this.volume=this.effect.volume,this.samplesWritten=0;for(let t=0;t<e.EMOJI_SYNTHESIZER_TONE_EFFECTS;t++)this.effect.effects[t].step=0,this.effect.effects[t].steps=Math.max(this.effect.effects[t].steps,1),this.samplesPerStep[t]=Math.floor(this.samplesToWrite/this.effect.effects[t].steps);return!1}pull(){let t,n,i=!1;for(;!i;){if(this.samplesWritten==this.samplesToWrite||this.status&e.EMOJI_SYNTHESIZER_STATUS_STOPPING){let t=this.nextSoundEffect();(0==this.samplesToWrite||this.status&e.EMOJI_SYNTHESIZER_STATUS_STOPPING)&&(i=!0,(t||this.status&e.EMOJI_SYNTHESIZER_STATUS_STOPPING)&&(this.status&=~e.EMOJI_SYNTHESIZER_STATUS_STOPPING))}for(!(this.samplesWritten<this.samplesToWrite)&&this.status&e.EMOJI_SYNTHESIZER_STATUS_OUTPUT_SILENCE_AS_EMPTY||null!=t||(this.buffer=new Array(this.bufferSize),t=0,n=this.buffer.length);this.samplesWritten<this.samplesToWrite;){let i=e.EMOJI_SYNTHESIZER_TONE_WIDTH_F*this.frequency/this.sampleRate,s=this.sampleRange*this.volume/1024,r=512-512*s,o=[];for(let t=0;t<e.EMOJI_SYNTHESIZER_TONE_EFFECTS;t++)o[t]=this.samplesPerStep[t]*this.effect.effects[t].step,this.effect.effects[t].step==this.effect.effects[t].steps-1&&(o[t]=this.samplesToWrite);let a=o[0];for(let t=1;t<e.EMOJI_SYNTHESIZER_TONE_EFFECTS;t++)a=Math.min(a,o[t]);for(;this.samplesWritten<a;){if(t==n)return this.buffer;let o=this.effect.tone.tonePrint(this.effect.tone.parameter,Math.max(this.position,0));for(this.buffer[t]=o*s+r,t++,this.samplesWritten++,this.position+=i;this.position>e.EMOJI_SYNTHESIZER_TONE_WIDTH_F;)this.position-=e.EMOJI_SYNTHESIZER_TONE_WIDTH_F}for(let t=0;t<e.EMOJI_SYNTHESIZER_TONE_EFFECTS;t++)this.samplesWritten==o[t]&&this.effect.effects[t].step<this.effect.effects[t].steps&&(this.effect.effects[t].effect&&this.effect.effects[t].effect(this,this.effect.effects[t]),this.effect.effects[t].step++)}}if(null==t)this.buffer=[];else{const e=.5*this.sampleRange;for(;t<n;)this.buffer[t]=e,t++}return this.buffer}determineSampleCount(e){e<0&&(e=-e);const t=e/1e3;return Math.floor(this.sampleRate*t)}totalDuration(){let e=0;for(const t of this.effectBuffer)e+=t.duration;return e}}}(e.music||(e.music={}))}(e.codal||(e.codal={}))}(pxsim||(pxsim={})),function(e){!function(e){!function(e){!function(e){const t=[0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,3,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,11,11,12,13,13,14,15,16,16,17,18,19,20,21,22,22,23,24,25,26,27,28,29,30,32,33,34,35,36,37,38,40,41,42,43,45,46,47,49,50,51,53,54,56,57,58,60,61,63,64,66,68,69,71,72,74,76,77,79,81,82,84,86,87,89,91,93,95,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,141,143,145,147,149,152,154,156,158,161,163,165,167,170,172,175,177,179,182,184,187,189,191,194,196,199,201,204,206,209,211,214,216,219,222,224,227,229,232,235,237,240,243,245,248,251,253,256,259,262,264,267,270,273,275,278,281,284,287,289,292,295,298,301,304,307,309,312,315,318,321,324,327,330,333,336,339,342,345,348,351,354,357,360,363,366,369,372,375,378,381,384,387,390,393,396,399,402,405,408,411,414,417,420,424,427,430,433,436,439,442,445,448,452,455,458,461,464,467,470,473,477,480,483,486,489,492,495,498,502,505,508,511,514,517,520,524,527,530,533,536,539,542,545,549,552,555,558,561,564,567,570,574,577,580,583,586,589,592,595,598,602,605,608,611,614,617,620,623,626,629,632,635,638,641,644,647,650,653,656,659,662,665,668,671,674,677,680,683,686,689,692,695,698,701,704,707,710,713,715,718,721,724,727,730,733,735,738,741,744,747,749,752,755,758,760,763,766,769,771,774,777,779,782,785,787,790,793,795,798,800,803,806,808,811,813,816,818,821,823,826,828,831,833,835,838,840,843,845,847,850,852,855,857,859,861,864,866,868,870,873,875,877,879,881,884,886,888,890,892,894,896,898,900,902,904,906,908,910,912,914,916,918,920,922,924,926,927,929,931,933,935,936,938,940,941,943,945,946,948,950,951,953,954,956,958,959,961,962,964,965,966,968,969,971,972,973,975,976,977,979,980,981,982,984,985,986,987,988,989,990,992,993,994,995,996,997,998,999,1e3,1e3,1001,1002,1003,1004,1005,1006,1006,1007,1008,1009,1009,1010,1011,1011,1012,1013,1013,1014,1014,1015,1015,1016,1016,1017,1017,1018,1018,1019,1019,1019,1020,1020,1020,1021,1021,1021,1021,1022,1022,1022,1022,1022,1022,1022,1022,1022,1022,1023,1022];e.SineTone=function(e,n){let i=1024-(n|=0);return i<512&&(n=i),t[n]},e.SawtoothTone=function(e,t){return t},e.TriangleTone=function(e,t){return t<512?2*t:2*(1023-t)},e.NoiseTone=function(e,t){let n=e[0];return 0==n&&(n=7919),t*n&1023},e.SquareWaveTone=function(e,t){return t<512?1023:0}}(e.Synthesizer||(e.Synthesizer={}))}(e.music||(e.music={}))}(e.codal||(e.codal={}))}(pxsim||(pxsim={})),function(e){!function(e){!function(e){!function(t){t.noInterpolation=function(e,t){},t.linearInterpolation=function(e,t){let n=(t.parameter[0]-e.effect.frequency)/t.steps;e.frequency=e.effect.frequency+n*t.step},t.logarithmicInterpolation=function(e,t){e.frequency=e.effect.frequency+Math.log10(Math.max(t.step,.1))*(t.parameter[0]-e.effect.frequency)/1.95},t.curveInterpolation=function(e,t){e.frequency=Math.sin(3.12159*t.step/180)*(t.parameter[0]-e.effect.frequency)+e.effect.frequency},t.slowVibratoInterpolation=function(e,t){e.frequency=Math.sin(t.step/10)*t.parameter[0]+e.effect.frequency},t.warbleInterpolation=function(e,t){e.frequency=Math.sin(t.step)*(t.parameter[0]-e.effect.frequency)+e.effect.frequency},t.vibratoInterpolation=function(e,t){e.frequency=e.effect.frequency+Math.sin(t.step)*t.parameter[0]},t.exponentialRisingInterpolation=function(e,t){e.frequency=e.effect.frequency+Math.sin(.01745329*t.step)*t.parameter[0]},t.exponentialFallingInterpolation=function(e,t){e.frequency=e.effect.frequency+Math.cos(.01745329*t.step)*t.parameter[0]},t.appregrioAscending=function(t,n){t.frequency=e.MusicalProgressions.calculateFrequencyFromProgression(t.effect.frequency,n.parameter_p[0],n.step)},t.appregrioDescending=function(t,n){t.frequency=e.MusicalProgressions.calculateFrequencyFromProgression(t.effect.frequency,n.parameter_p[0],n.steps-n.step-1)},t.frequencyVibratoEffect=function(e,t){0!=t.step&&(t.step%2==0?e.frequency/=t.parameter[0]:e.frequency*=t.parameter[0])},t.volumeVibratoEffect=function(e,t){0!=t.step&&(t.step%2==0?e.volume/=t.parameter[0]:e.volume*=t.parameter[0])},t.adsrVolumeEffect=function(e,t){let n=.5*t.steps;if(t.step<=n){let i=(t.parameter[0]-e.effect.volume)/n;e.volume=e.effect.volume+t.step*i}else{let i=(t.parameter[1]-t.parameter[0])/n;e.volume=t.parameter[0]+(t.step-n)*i}},t.volumeRampEffect=function(e,t){let n=(t.parameter[0]-e.effect.volume)/t.steps;e.volume=e.effect.volume+t.step*n}}(e.SoundSynthesizerEffects||(e.SoundSynthesizerEffects={}))}(e.music||(e.music={}))}(e.codal||(e.codal={}))}(pxsim||(pxsim={})),function(e){!function(t){!function(t){let n,i,s;!function(e){e[e.Sine=0]="Sine",e[e.Sawtooth=1]="Sawtooth",e[e.Triangle=2]="Triangle",e[e.Square=3]="Square",e[e.Noise=4]="Noise"}(n=t.WaveShape||(t.WaveShape={})),function(e){e[e.None=0]="None",e[e.Linear=1]="Linear",e[e.Curve=2]="Curve",e[e.ExponentialRising=5]="ExponentialRising",e[e.ExponentialFalling=6]="ExponentialFalling",e[e.ArpeggioRisingMajor=8]="ArpeggioRisingMajor",e[e.ArpeggioRisingMinor=10]="ArpeggioRisingMinor",e[e.ArpeggioRisingDiminished=12]="ArpeggioRisingDiminished",e[e.ArpeggioRisingChromatic=14]="ArpeggioRisingChromatic",e[e.ArpeggioRisingWholeTone=16]="ArpeggioRisingWholeTone",e[e.ArpeggioFallingMajor=9]="ArpeggioFallingMajor",e[e.ArpeggioFallingMinor=11]="ArpeggioFallingMinor",e[e.ArpeggioFallingDiminished=13]="ArpeggioFallingDiminished",e[e.ArpeggioFallingChromatic=15]="ArpeggioFallingChromatic",e[e.ArpeggioFallingWholeTone=17]="ArpeggioFallingWholeTone",e[e.Logarithmic=18]="Logarithmic"}(i=t.InterpolationEffect||(t.InterpolationEffect={})),function(e){e[e.None=0]="None",e[e.Vibrato=1]="Vibrato",e[e.Tremolo=2]="Tremolo",e[e.Warble=3]="Warble"}(s=t.Effect||(t.Effect={}));class r{constructor(){this.src="000000000000000000000000000000000000000000000000000000000000000000000000"}get wave(){return this.getValue(0,1)}set wave(e){this.setValue(0,g(e,0,4),1)}get volume(){return this.getValue(1,4)}set volume(e){this.setValue(1,g(e,0,1023),4)}get frequency(){return this.getValue(5,4)}set frequency(e){this.setValue(5,e,4)}get duration(){return this.getValue(9,4)}set duration(e){this.setValue(9,e,4)}get shape(){return this.getValue(13,2)}set shape(e){this.setValue(13,e,2)}get endFrequency(){return this.getValue(18,4)}set endFrequency(e){this.setValue(18,e,4)}get endVolume(){return this.getValue(26,4)}set endVolume(e){this.setValue(26,g(e,0,1023),4)}get steps(){return this.getValue(30,4)}set steps(e){this.setValue(30,e,4)}get fx(){return this.getValue(34,2)}set fx(e){this.setValue(34,g(e,0,3),2)}get fxParam(){return this.getValue(36,4)}set fxParam(e){this.setValue(36,e,4)}get fxnSteps(){return this.getValue(40,4)}set fxnSteps(e){this.setValue(40,e,4)}get frequencyRandomness(){return this.getValue(44,4)}set frequencyRandomness(e){this.setValue(44,e,4)}get endFrequencyRandomness(){return this.getValue(48,4)}set endFrequencyRandomness(e){this.setValue(48,e,4)}get volumeRandomness(){return this.getValue(52,4)}set volumeRandomness(e){this.setValue(52,e,4)}get endVolumeRandomness(){return this.getValue(56,4)}set endVolumeRandomness(e){this.setValue(56,e,4)}get durationRandomness(){return this.getValue(60,4)}set durationRandomness(e){this.setValue(60,e,4)}get fxParamRandomness(){return this.getValue(64,4)}set fxParamRandomness(e){this.setValue(64,e,4)}get fxnStepsRandomness(){return this.getValue(68,4)}set fxnStepsRandomness(e){this.setValue(68,e,4)}copy(){const e=new r;return e.src=this.src.slice(0),e}setValue(e,t,n){t=g(0|t,0,Math.pow(10,n)-1),this.src=this.src.substr(0,e)+function(e,t){let n=e+"";for(;n.length<t;)n="0"+n;return n}(t,n)+this.src.substr(e+n)}getValue(e,t){return parseInt(this.src.substr(e,t))}}t.Sound=r;let o,a=!1,l={cancelled:!1};async function c(){if(o.length){a=!0;const e=o.shift();let t=l;try{e.onStarted(),await d(e.notes,(()=>t.cancelled)),t.cancelled?e.onCancelled():e.onFinished()}catch(t){e.onCancelled()}c()}else a=!1}function u(){o=[],l.cancelled=!0,l={cancelled:!1}}function d(n,i,s){const r=new t.SoundEmojiSynthesizer(0),o=function(e){const t=72,n=Math.floor((e.length+1)/(t+1)),i=n*(t+1)-1;if(e.length!=i)return[];const s=[];for(let i=0;i<n;++i){const n=i*t+i;if(n>0&&","!=e[n-1])return[];const r=m();if(!h(e.substr(n),r))return[];s.push(r)}return s}(n);r.play(o);let a=!1;return Promise.race([(l=r.totalDuration(),new Promise((e=>setTimeout(e,l)))).then((()=>{a=!0})),e.AudioContextManager.playPCMBufferStreamAsync((()=>{if(!r.effect)return;const e=r.pull();s&&s(r.frequency,r.volume);const t=new Float32Array(e.length);for(let n=0;n<e.length;n++)t[n]=(e[n]-512)/512;return t}),r.sampleRate,.03,(()=>a||i&&i()))]);var l}function h(e,n){let i=parseInt(e.substr(0,1)),s=parseInt(e.substr(1,4)),r=parseInt(e.substr(5,4)),o=parseInt(e.substr(9,4)),a=parseInt(e.substr(13,2)),l=parseInt(e.substr(18,4)),c=parseInt(e.substr(26,4)),u=parseInt(e.substr(30,4)),d=parseInt(e.substr(34,2)),h=parseInt(e.substr(36,4)),m=parseInt(e.substr(40,4));if(r=f(r,parseInt(e.substr(44,4))),l=f(l,parseInt(e.substr(48,4))),s=f(s,parseInt(e.substr(52,4))),c=f(c,parseInt(e.substr(56,4))),o=f(o,parseInt(e.substr(60,4))),h=f(h,parseInt(e.substr(64,4))),m=f(m,parseInt(e.substr(68,4))),-1==r||-1==l||-1==s||-1==c||-1==o||-1==h||-1==m)return!1;switch(i){case 0:n.tone.tonePrint=t.Synthesizer.SineTone;break;case 1:n.tone.tonePrint=t.Synthesizer.SawtoothTone;break;case 2:n.tone.tonePrint=t.Synthesizer.TriangleTone;break;case 3:n.tone.tonePrint=t.Synthesizer.SquareWaveTone;break;case 4:n.tone.tonePrint=t.Synthesizer.NoiseTone}switch(n.frequency=r,n.duration=o,n.effects[0].steps=u,a){case 0:n.effects[0].effect=t.SoundSynthesizerEffects.noInterpolation;break;case 1:n.effects[0].effect=t.SoundSynthesizerEffects.linearInterpolation,n.effects[0].parameter[0]=l;break;case 2:n.effects[0].effect=t.SoundSynthesizerEffects.curveInterpolation,n.effects[0].parameter[0]=l;break;case 5:n.effects[0].effect=t.SoundSynthesizerEffects.exponentialRisingInterpolation,n.effects[0].parameter[0]=l;break;case 6:n.effects[0].effect=t.SoundSynthesizerEffects.exponentialFallingInterpolation,n.effects[0].parameter[0]=l;break;case 8:case 10:case 12:case 14:case 16:n.effects[0].effect=t.SoundSynthesizerEffects.appregrioAscending;break;case 9:case 11:case 13:case 15:case 17:n.effects[0].effect=t.SoundSynthesizerEffects.appregrioDescending;break;case 18:n.effects[0].effect=t.SoundSynthesizerEffects.logarithmicInterpolation,n.effects[0].parameter[0]=l}switch(a){case 8:case 9:n.effects[0].parameter_p[0]=t.MusicalProgressions.majorScale;break;case 10:case 11:n.effects[0].parameter_p[0]=t.MusicalProgressions.minorScale;break;case 12:case 13:n.effects[0].parameter_p[0]=t.MusicalProgressions.diminished;break;case 14:case 15:n.effects[0].parameter_p[0]=t.MusicalProgressions.chromatic;break;case 16:case 17:n.effects[0].parameter_p[0]=t.MusicalProgressions.wholeTone}let g=p(0,s,1023)/1023,b=p(0,c,1023)/1023;n.volume=1*g,n.effects[1].effect=t.SoundSynthesizerEffects.volumeRampEffect,n.effects[1].steps=36,n.effects[1].parameter[0]=1*b;let y=Math.round(n.duration/1e4*m);switch(d){case 1:n.effects[2].steps=y,n.effects[2].effect=t.SoundSynthesizerEffects.frequencyVibratoEffect,n.effects[2].parameter[0]=h;break;case 2:n.effects[2].steps=y,n.effects[2].effect=t.SoundSynthesizerEffects.volumeVibratoEffect,n.effects[2].parameter[0]=h;break;case 3:n.effects[2].steps=y,n.effects[2].effect=t.SoundSynthesizerEffects.warbleInterpolation,n.effects[2].parameter[0]=h}return!0}function p(e,t,n){return Math.min(n,Math.max(e,t))}function f(e,t){if(e<0||t<0)return-1;const n=(i=2*t+1,Math.floor(Math.random()*i)-t);var i;return Math.abs(e+n)}function m(){const e={frequency:0,volume:1,duration:0,tone:{tonePrint:void 0,parameter:[0]},effects:[]};for(let n=0;n<t.EMOJI_SYNTHESIZER_TONE_EFFECTS;n++)e.effects.push({effect:void 0,step:0,steps:0,parameter:[],parameter_p:[]});return e}function g(e,t,n){return Math.min(Math.max(e,t),n)}t.isSoundExpPlaying=function(){return a},t.__playSoundExpression=function(t,n){o||(o=[]);const i=e.getResume(),s=new Promise(((e,s)=>{o.push({notes:t,onStarted:()=>{n||i()},onFinished:e,onCancelled:e})}));a||c(),n&&s.then(i)},t.clearSoundQueue=u,t.playSoundExpressionAsync=d,t.__stopSoundExpressions=function(){u(),e.AudioContextManager.stopAll()},t.parseSoundExpression=h}(t.music||(t.music={}))}(e.codal||(e.codal={}))}(pxsim||(pxsim={})),function(e){class t{constructor(e){this.id=e}}e.Button=t;e.ButtonPairState=class{constructor(e){this.props=e,this.usesButtonAB=!1,this.aBtn=new t(this.props.ID_BUTTON_A),this.bBtn=new t(this.props.ID_BUTTON_B),this.abBtn=new t(this.props.ID_BUTTON_AB),this.abBtn.virtual=!0}}}(pxsim||(pxsim={})),function(e){e.CompassState=class{constructor(){this.usesHeading=!1,this.heading=90}}}(pxsim||(pxsim={})),function(e){e.FileSystemState=class{constructor(){this.files={}}append(e,t){this.files[e]=(this.files[e]||"")+t}remove(e){delete this.files[e]}}}(pxsim||(pxsim={})),function(e){e.LightSensorState=class{constructor(){this.usesLightLevel=!1,this.lightLevel=128}}}(pxsim||(pxsim={})),function(e){!function(t){t.mkBoardView=e=>{const n=e.visual;return new t.GenericBoardSvg({visualDef:n,boardDef:e.boardDef,wireframe:e.wireframe})};t.BoardHost=class{constructor(n,i){this.parts=[],this.boardView=n,this.opts=i,i.boardDef.pinStyles||(i.boardDef.pinStyles={}),this.state=i.state;let s=i.partsList,r=0<s.length||i.forceBreadboardLayout;if(r){this.breadboard=new t.Breadboard({wireframe:i.wireframe});const n=i.boardDef.marginWhenBreadboarding||[0,0,40,0],o=t.composeSVG({el1:this.boardView.getView(),scaleUnit1:this.boardView.getPinDist(),el2:this.breadboard.getSVGAndSize(),scaleUnit2:this.breadboard.getPinDist(),margin:[n[0],n[1],20,n[3]],middleMargin:n[2],maxWidth:i.maxWidth,maxHeight:i.maxHeight}),a=o.under,l=o.over;this.view=o.host;const c=o.edges;this.fromMBCoord=o.toHostCoord1,this.fromBBCoord=o.toHostCoord2,this.partGroup=l,this.partOverGroup=e.svg.child(this.view,"g"),this.style=e.svg.child(this.view,"style",{}),this.defs=e.svg.child(this.view,"defs",{}),this.wireFactory=new t.WireFactory(a,l,c,this.style,this.getLocCoord.bind(this),this.getPinStyle.bind(this));const u=e.allocateDefinitions({boardDef:i.boardDef,partDefs:i.partDefs,fnArgs:i.fnArgs,getBBCoord:this.breadboard.getCoord.bind(this.breadboard),partsList:s});u.partsAndWires.length||i.forceBreadboardLayout?(this.addAll(u),u.requiresBreadboard||i.forceBreadboardRender?u.hideBreadboard&&this.breadboard&&this.breadboard.hide():r=!1):r=!1}if(!r){delete this.breadboard,delete this.wireFactory,delete this.partOverGroup,delete this.partGroup,delete this.style,delete this.defs,delete this.fromBBCoord,delete this.fromMBCoord;const t=this.boardView.getView().el;this.view=t,this.partGroup=e.svg.child(this.view,"g"),this.partOverGroup=e.svg.child(this.view,"g"),i.maxWidth&&e.svg.hydrate(this.view,{width:i.maxWidth}),i.maxHeight&&e.svg.hydrate(this.view,{height:i.maxHeight})}this.state.updateSubscribers.push((()=>this.updateState()))}highlightBoardPin(e){this.boardView.highlightPin(e)}removeEventListeners(){this.boardView.removeEventListeners&&this.boardView.removeEventListeners()}highlightBreadboardPin(e){this.breadboard.highlightLoc(e)}highlightWire(t){t.wires.forEach((t=>{e.U.addClass(t,"highlight"),t.style.visibility="visible"})),e.U.addClass(t.endG,"highlight")}getView(){return this.view}screenshotAsync(e){const t=this.view.classList.contains("sim")?this.view:this.view.querySelector(".sim"),n=t?t.cloneNode(!0):this.view.cloneNode(!0);n.setAttribute("width",n.viewBox.baseVal.width+""),n.setAttribute("height",n.viewBox.baseVal.height+"");const i=(new XMLSerializer).serializeToString(n),s="data:image/svg+xml,"+encodeURIComponent(i.replace(/\s+/g," ").replace(/"/g,"'"));return new Promise(((t,n)=>{const i=document.createElement("img");i.onload=()=>{const n=document.createElement("canvas");n.width=i.width,n.height=i.height,e>0?(n.width=e,n.height=i.height*e/i.width|0):n.width<200?(n.width*=2,n.height*=2):n.width>480&&(n.width/=2,n.height/=2);const s=n.getContext("2d");s.drawImage(i,0,0,n.width,n.height),t(s.getImageData(0,0,n.width,n.height))},i.onerror=e=>{console.log(e),t(void 0)},i.src=s}))}updateState(){this.parts.forEach((e=>e.updateState()))}getBBCoord(e){let t=this.breadboard.getCoord(e);return this.fromBBCoord(t)}getPinCoord(e){let t=this.boardView.getCoord(e);if(t)return this.fromMBCoord(t);console.error(`Unable to find coord for pin: ${e}`)}getLocCoord(e){let t;if("breadboard"===e.type){let n=e;t=this.getBBCoord(n)}else{let n=e.pin;t=this.getPinCoord(n)}return t||console.debug("Unknown location: "+name),t}getPinStyle(e){return"breadboard"==e.type?"female":this.opts.boardDef.pinStyles[e.pin]||"female"}addPart(n){let i=null;if(n.simulationBehavior){let e=n.simulationBehavior,t=this.state.builtinVisuals[e],s=this.state.builtinParts[e];i=t(),i.init(this.state.bus,s,this.view,n.params)}else{let e=n.visual;i=new t.GenericPart(e)}this.parts.push(i),this.partGroup.appendChild(i.element),i.overElement&&this.partOverGroup.appendChild(i.overElement),i.defs&&i.defs.forEach((e=>this.defs.appendChild(e))),this.style.textContent+=i.style||"";let s=n.startColumnIdx,r=n.startRowIdx,o={type:"breadboard",row:t.getRowName(r),col:t.getColumnName(s),xOffset:n.bbFit.xOffset/n.visual.pinDistance,yOffset:n.bbFit.yOffset/n.visual.pinDistance},a=this.getBBCoord(o);i.moveToCoord(a);let l=`sim-${n.name}-cmp`;return e.U.addClass(i.element,l),e.U.addClass(i.element,"sim-cmp"),i.updateTheme(),i.updateState(),i}addWire(e){return this.wireFactory.addWire(e.start,e.end,e.color)}addAll(e){e.partsAndWires.forEach((t=>{const n=t.wires,i=n&&n.every((e=>this.wireFactory.checkWire(e.start,e.end)));i&&n.forEach((t=>e.wires.push(this.addWire(t))));let s=t.part;!s||n&&!i||e.parts.push(this.addPart(s))})),e.requiresBreadboard=!!e.wires.length||!!e.parts.length}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){!function(t){const n=15,i="#DD4BA0",s=`\n /* bread board */\n .sim-bb-background {\n fill:#E0E0E0;\n }\n .sim-bb-pin {\n fill:#999;\n }\n .sim-bb-pin-hover {\n visibility: hidden;\n pointer-events: all;\n stroke-width: 7.5px;\n stroke: transparent;\n fill: #777;\n }\n .sim-bb-pin-hover:hover {\n visibility: visible;\n fill:#444;\n }\n .sim-bb-group-wire {\n stroke: #999;\n stroke-width: 3.75px;\n visibility: hidden;\n }\n .sim-bb-pin-group {\n pointer-events: all;\n }\n .sim-bb-label,\n .sim-bb-label-hover {\n font-family:"Lucida Console", Monaco, monospace;\n fill:#555;\n pointer-events: all;\n stroke-width: 0;\n cursor: default;\n }\n .sim-bb-label-hover {\n visibility: hidden;\n fill:#000;\n font-weight: bold;\n }\n .sim-bb-bar {\n stroke-width: 0;\n }\n .sim-bb-blue {\n fill:#1AA5D7;\n stroke:#1AA5D7\n }\n .sim-bb-red {\n fill:${i};\n stroke:${i};\n }\n .sim-bb-pin-group:hover .sim-bb-pin-hover,\n .sim-bb-pin-group:hover .sim-bb-group-wire,\n .sim-bb-pin-group:hover .sim-bb-label-hover {\n visibility: visible;\n }\n .sim-bb-pin-group:hover .sim-bb-label {\n visibility: hidden;\n }\n /* outline mode */\n .sim-bb-outline .sim-bb-background {\n stroke-width: ${n/7}px;\n fill: #FFF;\n stroke: #000;\n }\n .sim-bb-outline .sim-bb-mid-channel {\n fill: #FFF;\n stroke: #888;\n stroke-width: 2px;\n }\n /* grayed out */\n .grayed .sim-bb-background {\n stroke-width: 3px;\n }\n .grayed .sim-bb-red,\n .grayed .sim-bb-blue {\n fill: #BBB;\n }\n .grayed .sim-bb-bar {\n fill: #FFF;\n }\n .grayed .sim-bb-pin {\n fill: #000;\n stroke: #FFF;\n stroke-width: 3px;\n }\n .grayed .sim-bb-label {\n fill: none;\n }\n .grayed .sim-bb-background {\n stroke-width: 7.5px;\n stroke: #555;\n }\n .grayed .sim-bb-group-wire {\n stroke: #DDD;\n }\n .grayed .sim-bb-channel {\n visibility: hidden;\n }\n /* highlighted */\n .sim-bb-label.highlight {\n visibility: hidden;\n }\n .sim-bb-label-hover.highlight {\n visibility: visible;\n }\n .sim-bb-blue.highlight {\n fill:#1AA5D7;\n }\n .sim-bb-red.highlight {\n fill:${i};\n }\n .sim-bb-bar.highlight {\n stroke-width: 0px;\n }\n `;t.BREADBOARD_MID_ROWS=10,t.BREADBOARD_MID_COLS=30;const r=[4,4],o=t.BREADBOARD_MID_ROWS+r.length,a=25,l=[4,9,14,19],c=a+l.length,u=n*(t.BREADBOARD_MID_COLS+3),d=n*(o+4+5.5),h=2/3,p=d*h,f=.16666666666666669*d,m=(t.BREADBOARD_MID_COLS-1)*n,g=(u-m)/2,b=f+(p-(o-1)*n)/2,y=(c-1)*n,v=(u-y)/2,w=(f-15)/2,k=v,x=w+f+p,A=25.5,E=12,T=1.05,S=-90,C="abcdefghij".split("").reverse();function I(e){return`${e+1}`}function _(e){return C[e]}function P(t){let n=t.xOffset||0,i=t.yOffset||0,s=[],r=e.svg.elt("g"),o=t.colStartIdx||0,a=t.rowStartIdx||0,l=e=>e?e.slice(0,e.length):[],c=(e,t)=>{let n,i=0;for(;0<=(n=e.indexOf(t));)e.splice(n,1),i+=1;return i},u=0,d=l(t.rowIdxsWithGap);for(let h=0;h<t.rowCount;h++){let p=0,f=l(t.colIdxsWithGap),m=i+h*t.pinDist+u*t.pinDist,g=h+a;for(let i=0;i<t.colCount;i++){let a=n+i*t.pinDist+p*t.pinDist,l=i+o;const u=t=>(e.svg.hydrate(t.el,"circle"==t.el.tagName?{cx:a,cy:m}:{x:a-.5*t.w,y:m-.5*t.h}),r.appendChild(t.el),t.el);let d=u(t.mkPin()),h=u(t.mkHoverPin()),b=t.getRowName(g),y=t.getColName(l),v=t.getGroupName?t.getGroupName(g,l):null,w={el:d,hoverEl:h,cx:a,cy:m,row:b,col:y,group:v};s.push(w),p+=c(f,l)}u+=c(d,g)}return{g:r,allPins:s}}function U(){let t=e.svg.elt("rect");return e.svg.hydrate(t,{class:"sim-bb-pin",rx:2,ry:2,width:6,height:6}),{el:t,w:6,h:6,x:0,y:0}}function O(){let t=e.svg.elt("rect"),n=6*1.3;return e.svg.hydrate(t,{class:"sim-bb-pin-hover",rx:2,ry:2,width:n,height:n}),{el:t,w:n,h:n,x:0,y:0}}function N(n,i,s,r,o,a,l){let c=t.mkTxt(n,i,s,r,o);e.U.addClass(c,"sim-bb-label"),l&&l.forEach((t=>e.U.addClass(c,t)));let u=t.mkTxt(n,i,1.3*s,r,o);return e.U.addClass(u,"sim-bb-label-hover"),l&&l.forEach((t=>e.U.addClass(u,t))),{el:c,hoverEl:u,txt:o,group:a}}t.getColumnName=I,t.getRowName=_,t.mkGrid=P;t.Breadboard=class{constructor(t){this.allPins=[],this.allLabels=[],this.allPowerBars=[],this.rowColToPin={},this.rowColToLbls={},this.buildDom(),t.wireframe&&e.U.addClass(this.bb,"sim-bb-outline")}hide(){this.bb.style.display="none"}updateLocation(t,n){e.svg.hydrate(this.bb,{x:`${t}px`,y:`${n}px`})}getPin(e,t){let n=this.rowColToPin[e];if(!n)return null;let i=n[t];return i||null}getCoord(e){let{row:t,col:i,xOffset:s,yOffset:r}=e,o=this.getPin(t,i);if(!o)return null;let a=(s||0)*n,l=(r||0)*n;return[o.cx+a,o.cy+l]}getPinDist(){return n}buildDom(){this.bb=e.svg.elt("svg",{version:"1.0",viewBox:`0 0 ${u} ${d}`,class:"sim-bb",width:u+"px",height:d+"px"}),this.styleEl=e.svg.child(this.bb,"style",{}),this.styleEl.textContent+=s,this.defs=e.svg.child(this.bb,"defs",{}),e.svg.child(this.bb,"rect",{class:"sim-bb-background",width:u,height:d,rx:4.5,ry:4.5});let i="sim-bb-channel-grad",o=e.svg.elt("linearGradient");e.svg.hydrate(o,{id:i,x1:"0%",y1:"0%",x2:"0%",y2:"100%"}),this.defs.appendChild(o);e.svg.child(o,"stop",{offset:"0%",style:"stop-color: #AAA;"}),e.svg.child(o,"stop",{offset:"20%",style:"stop-color: #CCC;"}),e.svg.child(o,"stop",{offset:"80%",style:"stop-color: #CCC;"}),e.svg.child(o,"stop",{offset:"100%",style:"stop-color: #AAA;"});const c=(t,n,s)=>{let r=e.svg.child(this.bb,"rect",{class:`sim-bb-channel ${s||""}`,y:t-n/2,width:u,height:n});return r.setAttribute("fill",`url(#${i})`),r};c(f+p/2,15,"sim-bb-mid-channel"),c(f,.75,"sim-bb-sml-channel"),c(f+p,.75,"sim-bb-sml-channel");const h=(e,n)=>`${(e=>e<t.BREADBOARD_MID_ROWS/2?"b":"t")(e)}${I(n)}`,m=e=>0===e?"-":"+",C=(e,t)=>{let n=(e=>e<25?"b":"t")(t);return`${m(e)}${n}`};let R=P({xOffset:g,yOffset:b,rowCount:t.BREADBOARD_MID_ROWS,colCount:t.BREADBOARD_MID_COLS,pinDist:n,mkPin:U,mkHoverPin:O,getRowName:_,getColName:I,getGroupName:h,rowIdxsWithGap:r});R.g;this.allPins=this.allPins.concat(R.allPins);let M=P({xOffset:k,yOffset:x,rowCount:2,colCount:a,pinDist:n,mkPin:U,mkHoverPin:O,getRowName:m,getColName:I,getGroupName:C,colIdxsWithGap:l});M.g;this.allPins=this.allPins.concat(M.allPins);let D=P({xOffset:v,yOffset:w,rowCount:2,colCount:a,colStartIdx:a,pinDist:n,mkPin:U,mkHoverPin:O,getRowName:m,getColName:I,getGroupName:C,colIdxsWithGap:l.map((e=>e+a))});D.g;this.allPins=this.allPins.concat(D.allPins),this.allPins.forEach((t=>{let{el:n,row:i,col:s,hoverEl:r}=t,o=`(${i},${s})`;e.svg.hydrate(n,{title:o}),e.svg.hydrate(r,{title:o})})),this.allPins.forEach((e=>{let t=this.rowColToPin[e.row];t||(t=this.rowColToPin[e.row]={}),t[e.col]=e}));const L=(e,t,n,i,s,r)=>{let o=this.getCoord({type:"breadboard",row:e,col:t}),[a,l]=o;return N(a+n,l+i,10.5,-90,s,r)};for(let e=0;e<t.BREADBOARD_MID_COLS;e++){let n=I(e),i=0,s=L(_(i),n,0,-15,n,h(i,e));this.allLabels.push(s);let r=t.BREADBOARD_MID_ROWS-1,o=L(_(r),n,0,15,n,h(r,e));this.allLabels.push(o)}for(let e=0;e<t.BREADBOARD_MID_ROWS;e++){let n=_(e),i=L(n,I(0),-15,0,n);this.allLabels.push(i);let s=L(n,I(t.BREADBOARD_MID_COLS-1),15,0,n);this.allLabels.push(s)}let F=[N(13.05,f+p+E,30,S,"-",C(0,0),["sim-bb-blue"]),N(12,f+p+f-E,A,S,"+",C(1,0),["sim-bb-red"]),N(u-E+T,f+p+E,30,S,"-",C(0,24),["sim-bb-blue"]),N(u-E,f+p+f-E,A,S,"+",C(1,24),["sim-bb-red"])];this.allLabels=this.allLabels.concat(F);let B=[N(13.05,12,30,S,"-",C(0,a),["sim-bb-blue"]),N(12,f-E,A,S,"+",C(1,a),["sim-bb-red"]),N(u-E+T,12,30,S,"-",C(0,49),["sim-bb-blue"]),N(u-E,f-E,A,S,"+",C(1,49),["sim-bb-red"])];this.allLabels=this.allLabels.concat(B);let $={};this.allLabels.forEach((e=>{let{el:t,txt:n}=e;($[n]=$[n]||[]).push(e)}));this.allPins.forEach((e=>{let{row:t,col:n,group:i}=e,s=this.rowColToLbls[t]||(this.rowColToLbls[t]={}),r=s[n]||(s[n]=[]);if((e=>"-"===e.row||"+"===e.row)(e)){Number(n)<=a?F.filter((t=>t.group==e.group)).forEach((e=>r.push(e))):B.filter((t=>t.group==e.group)).forEach((e=>r.push(e)))}else{$[t].forEach((e=>r.push(e))),$[n].forEach((e=>r.push(e)))}}));const j=y+22.5,V=(j-y)/2,q=(t,n,i,s)=>{let r=e.svg.elt("rect");return e.svg.hydrate(r,{class:`sim-bb-bar ${s}`,x:t,y:n-1.5,width:j,height:3}),{el:r,group:i}};let H=[q(k-V,x-9,C(0,49),"sim-bb-blue"),q(k-V,x+n+9,C(1,49),"sim-bb-red"),q(v-V,w-9,C(0,0),"sim-bb-blue"),q(v-V,w+n+9,C(1,0),"sim-bb-red")];this.allPowerBars=this.allPowerBars.concat(H),this.allPowerBars.forEach((e=>this.bb.appendChild(e.el)));let G=this.allPins.map((e=>e.group)).filter(((e,t,n)=>n.indexOf(e)==t)),z=G.map((t=>e.svg.elt("g")));z.forEach((t=>e.U.addClass(t,"sim-bb-pin-group"))),z.forEach(((t,n)=>e.U.addClass(t,`group-${G[n]}`)));let W={};G.forEach(((e,t)=>W[e]=z[t]));let J={};this.allPins.forEach(((e,t)=>{let n=e.group;(J[n]||(J[n]=[])).push(e)})),G.forEach((t=>{let n=J[t],[i,s]=[n.map((e=>e.cx)),n.map((e=>e.cy))],r=e=>e.reduce(((e,t)=>e<t?e:t)),o=e=>e.reduce(((e,t)=>e>t?e:t)),[a,l,c,u]=[r(i),o(i),r(s),o(s)],d=e.svg.elt("rect"),h=Math.max(l-a,1e-4),p=Math.max(u-c,1e-4);e.svg.hydrate(d,{x:a,y:c,width:h,height:p}),e.U.addClass(d,"sim-bb-group-wire"),W[t].appendChild(d)})),this.allPins.forEach((e=>{let t=W[e.group];t.appendChild(e.el),t.appendChild(e.hoverEl)}));let Y=e.svg.elt("g");e.svg.hydrate(Y,{class:"sim-bb-group-misc"}),z.push(Y),this.allLabels.forEach((e=>{if(e.group){let t=W[e.group];t.appendChild(e.el),t.appendChild(e.hoverEl)}else Y.appendChild(e.el),Y.appendChild(e.hoverEl)})),z.forEach((e=>this.bb.appendChild(e)))}getSVGAndSize(){return{el:this.bb,y:0,x:0,w:u,h:d}}highlightLoc(t){let{row:n,col:i}=t,s=this.rowColToPin[n][i],{cx:r,cy:o}=s;this.rowColToLbls[n][i].forEach((t=>{e.U.addClass(t.el,"highlight"),e.U.addClass(t.hoverEl,"highlight")}))}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){!function(t){t.BOARD_SYTLE=`\n .noselect {\n -webkit-touch-callout: none; /* iOS Safari */\n -webkit-user-select: none; /* Chrome/Safari/Opera */\n -khtml-user-select: none; /* Konqueror */\n -moz-user-select: none; /* Firefox */\n -ms-user-select: none; /* Internet Explorer/Microsoft Edge */\n user-select: none; /* Non-prefixed version, currently\n not supported by any browser */\n }\n\n .sim-board-pin {\n fill:#999;\n stroke:#000;\n stroke-width:${t.PIN_DIST/3}px;\n }\n .sim-board-pin-lbl {\n fill: #333;\n }\n .gray-cover {\n fill:#FFF;\n opacity: 0.3;\n stroke-width:0;\n visibility: hidden;\n }\n .sim-board-pin-hover {\n visibility: hidden;\n pointer-events: all;\n stroke-width:${t.PIN_DIST/6}px;\n }\n .sim-board-pin-hover:hover {\n visibility: visible;\n }\n .sim-board-pin-lbl {\n visibility: hidden;\n }\n .sim-board-outline .sim-board-pin-lbl {\n visibility: visible;\n }\n .sim-board-pin-lbl {\n fill: #555;\n }\n .sim-board-pin-lbl-hover {\n fill: red;\n }\n .sim-board-outline .sim-board-pin-lbl-hover {\n fill: black;\n }\n .sim-board-pin-lbl,\n .sim-board-pin-lbl-hover {\n font-family:"Lucida Console", Monaco, monospace;\n pointer-events: all;\n stroke-width: 0;\n }\n .sim-board-pin-lbl-hover {\n visibility: hidden;\n }\n .sim-board-outline .sim-board-pin-hover:hover + .sim-board-pin-lbl,\n .sim-board-pin-lbl.highlight {\n visibility: hidden;\n }\n .sim-board-outline .sim-board-pin-hover:hover + * + .sim-board-pin-lbl-hover,\n .sim-board-pin-lbl-hover.highlight {\n visibility: visible;\n }\n /* Graying out */\n .grayed .sim-board-pin-lbl:not(.highlight) {\n fill: #AAA;\n }\n .grayed .sim-board-pin:not(.highlight) {\n fill:#BBB;\n stroke:#777;\n }\n .grayed .gray-cover {\n visibility: inherit;\n }\n .grayed .sim-cmp:not(.notgrayed) {\n opacity: 0.3;\n }\n /* Highlighting */\n .sim-board-pin-lbl.highlight {\n fill: #000;\n font-weight: bold;\n }\n .sim-board-pin.highlight {\n fill:#999;\n stroke:#000;\n }\n `;const n=.7*t.PIN_DIST,i=1.5*n,s=.66666*t.PIN_DIST,r=.66666*t.PIN_DIST+t.PIN_DIST/3;let o=0;t.GenericBoardSvg=class{constructor(a){this.props=a,this.allPins=[],this.allLabels=[],this.pinNmToLbl={},this.pinNmToPin={},this.id=o++;let l=a.visualDef,c=a.wireframe&&l.outlineImage?l.outlineImage:l.image,u=t.mkImageSVG({image:c,width:l.width,height:l.height,imageUnitDist:l.pinDist,targetUnitDist:t.PIN_DIST}),d=t.mkScaleFn(l.pinDist,t.PIN_DIST);this.width=u.w,this.height=u.h;let h=u.el;this.element=e.svg.elt("svg"),e.svg.hydrate(this.element,{version:"1.0",viewBox:`0 0 ${this.width} ${this.height}`,class:`sim sim-board-id-${this.id}`,x:"0px",y:"0px"}),a.wireframe&&e.U.addClass(this.element,"sim-board-outline"),this.style=e.svg.child(this.element,"style",{}),this.style.textContent+=t.BOARD_SYTLE,this.defs=e.svg.child(this.element,"defs",{}),this.g=e.svg.elt("g"),this.element.appendChild(this.g),this.g.appendChild(h),this.background=h,e.svg.hydrate(h,{class:"sim-board"});const p=()=>{let t=e.svg.elt("circle"),n=s;return e.svg.hydrate(t,{class:"sim-board-pin",r:n/2}),{el:t,w:n,h:n,x:0,y:0}},f=()=>{let t=e.svg.elt("circle"),n=r;return e.svg.hydrate(t,{class:"sim-board-pin-hover",r:n/2}),{el:t,w:n,h:n,x:0,y:0}},m=()=>{let t=e.svg.elt("rect"),n=s;return e.svg.hydrate(t,{class:"sim-board-pin",width:n,height:n}),{el:t,w:n,h:n,x:0,y:0}},g=()=>{let t=e.svg.elt("rect"),n=r;return e.svg.hydrate(t,{class:"sim-board-pin-hover",width:n,height:n}),{el:t,w:n,h:n,x:0,y:0}};let b=l.pinBlocks.map(((n,i)=>{let s=d(n.x)+t.PIN_DIST/2,r=d(n.y)+t.PIN_DIST/2,o=n.labels.length,a=t.mkGrid({xOffset:s,yOffset:r,rowCount:1,colCount:o,pinDist:t.PIN_DIST,mkPin:l.useCrocClips?p:m,mkHoverPin:l.useCrocClips?f:g,getRowName:()=>`${i+1}`,getColName:e=>n.labels[e],getGroupName:()=>n.labels.join(" ")});a.allPins,a.g;return e.U.addClass(a.g,"sim-board-pin-group"),a})),y=[];b.forEach(((e,t)=>e.allPins.forEach(((e,n)=>{this.allPins.push(e),y.push(l.pinBlocks[t])})))),this.allPins.forEach((t=>{let n=t.col;e.svg.hydrate(t.el,{title:n}),e.svg.hydrate(t.hoverEl,{title:n})})),this.allPins.forEach((e=>{this.pinNmToPin[e.col]=e}));const v=(e,n,i,s,r)=>{let o,a;if("below"===r){a=e,o=n+12+.25*i*s.length}else{a=e,o=n-11-.32*i*s.length}return t.mkTxt(a,o,i,-90,s)};this.allLabels=this.allPins.map(((t,s)=>{let r=y[s];return((t,s,r,o)=>{let a=v(t,s,n,r,o);e.U.addClass(a,"sim-board-pin-lbl");let l=v(t,s,i,r,o);return e.U.addClass(l,"sim-board-pin-lbl-hover"),{el:a,hoverEl:l,txt:r}})(t.cx,t.cy,t.col,r.labelPosition||"above")})),this.allPins.forEach(((e,t)=>{let n=this.allLabels[t];this.pinNmToLbl[e.col]=n})),this.allPins.forEach(((e,t)=>{let n=this.allLabels[t];this.g.appendChild(e.el),this.g.appendChild(e.hoverEl),this.g.appendChild(n.el),this.g.appendChild(n.hoverEl)}))}findPin(e){let t=this.pinNmToPin[e];return!t&&this.props.boardDef.gpioPinMap&&(e=this.props.boardDef.gpioPinMap[e])&&(t=this.pinNmToPin[e]),t}findPinLabel(e){let t=this.pinNmToLbl[e];return!t&&this.props.boardDef.gpioPinMap&&(e=this.props.boardDef.gpioPinMap[e])&&(t=this.pinNmToLbl[e]),t}getCoord(e){let t=this.findPin(e);return t?[t.cx,t.cy]:null}mkGrayCover(t,n,i,s){let r=e.svg.elt("rect");return e.svg.hydrate(r,{x:t,y:n,width:i,height:s,class:"gray-cover"}),r}getView(){return{el:this.element,w:this.width,h:this.height,x:0,y:0}}getPinDist(){return t.PIN_DIST}highlightPin(t){let n=this.findPinLabel(t),i=this.findPin(t);n&&i&&(e.U.addClass(n.el,"highlight"),e.U.addClass(n.hoverEl,"highlight"),e.U.addClass(i.el,"highlight"),e.U.addClass(i.hoverEl,"highlight"))}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){!function(t){function n(e){return t.mkImageSVG({image:e.image,width:e.width,height:e.height,imageUnitDist:e.pinDistance,targetUnitDist:t.PIN_DIST})}t.mkGenericPartSVG=n;t.GenericPart=class{constructor(t){this.style="",this.defs=[];let i=n(t).el;this.element=e.svg.elt("g"),this.element.appendChild(i)}moveToCoord(e){t.translateEl(this.element,e)}init(e,t,n){}updateState(){}updateTheme(){}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){!function(t){const n=t.PIN_DIST/2.5,i=.7;function s(e){return e.replace(/\#/g,"-").replace(/\(/g,"-").replace(/\)/g,"-").replace(/\,/g,"-").replace(/\./g,"-").replace(/\s/g,"")}let r;function o(t,n,i,s){const r=e=>`${e[0]}, ${e[1]}`;let[o,a]=t,[l,c]=n,u=c-a,d=[o,a+u*i],h=[l,c-u*i],p=e.svg.mkPath("sim-bb-wire",`M${r(t)} C${r(d)} ${r(h)} ${r(n)}`);return e.U.addClass(p,`wire-stroke-${s}`),p}function a(t,n,i){const s=e=>`${e[0]}, ${e[1]}`;let r=e.svg.mkPath("sim-bb-wire",`M${s(t)} L${s(n)}`);return e.U.addClass(r,`wire-stroke-${i}`),r}function l(i,s){const r=t.PIN_DIST/4;let o=e.svg.elt("circle"),a=i[0],l=i[1],c=n/2+r/2;return e.svg.hydrate(o,{cx:a,cy:l,r:c,class:"sim-bb-wire-end"}),e.U.addClass(o,`wire-fill-${s}`),o.style["stroke-width"]=`${r}px`,o}function c(n,i,s){let r=.24*t.PIN_DIST,o=10*r,a=2*r,l=6*r,c=r;const u=t.PIN_DIST/4;let[d,h]=n,p=i?-1:1,f=e.svg.elt("g"),m=e.svg.elt("rect"),g=o,b=a,y=d-b/2,v=h-g/2;e.svg.hydrate(m,{x:y,y:v,width:b,height:g,rx:.5,ry:.5,class:"sim-bb-wire-end"}),m.style["stroke-width"]=`${u}px`;let w=e.svg.elt("rect"),k=l,x=c,A=d-x/2,E=h+p*(g/2+k/2)-k/2;return e.svg.hydrate(w,{x:A,y:E,width:x,height:k,class:"sim-bb-wire-bare-end"}),w.style.fill="#bbb",f.appendChild(w),f.appendChild(m),{el:f,x:y-u,y:Math.min(v,E),w:b+2*u,h:g+k}}function u(n,i,s){let r=.24*t.PIN_DIST;const o=4*r,a=10*r,l=3.5*r,c=3.5*r,u=t.PIN_DIST/4;let[d,h]=n,p=i?-1:1,f=e.svg.elt("g"),m=e.svg.elt("polygon"),g=a,b=o,y=d-b/2,v=h-g/2;const w=i?.15:.3,k=i?.7:1-.7,x=i?.3:.15;e.svg.hydrate(m,{points:((...e)=>e.map((e=>(e=>`${e[0]},${e[1]}`)(e))).join(" "))([y+b*w,v],[y+b*(1-w),v],[y+b,v+g*k],[y+b*(1-x),v+g],[y+b*x,v+g],[y,v+g*k])}),e.svg.hydrate(m,{rx:.5,ry:.5,class:"sim-bb-wire-end"}),m.style["stroke-width"]=`${u}px`;let A=e.svg.elt("rect"),E=l,T=c,S=d-T/2,C=h+p*(g/2+E/2)-E/2;return e.svg.hydrate(A,{x:S,y:C,width:T,height:E,class:"sim-bb-wire-bare-end"}),f.appendChild(A),f.appendChild(m),{el:f,x:y-u,y:Math.min(v,C),w:b+2*u,h:g+E}}t.WIRES_CSS=`\n .sim-bb-wire {\n fill:none;\n stroke-linecap: round;\n stroke-width:${n}px;\n pointer-events: none;\n }\n .sim-bb-wire-end {\n stroke:#333;\n fill:#333;\n }\n .sim-bb-wire-bare-end {\n fill: #ccc;\n }\n .sim-bb-wire-hover {\n stroke-width: ${n}px;\n visibility: hidden;\n stroke-dasharray: ${t.PIN_DIST/10},${t.PIN_DIST/1.5};\n /*stroke-opacity: 0.4;*/\n }\n .grayed .sim-bb-wire-ends-g:not(.highlight) .sim-bb-wire-end {\n stroke: #777;\n fill: #777;\n }\n .grayed .sim-bb-wire:not(.highlight) {\n stroke: #CCC;\n }\n .sim-bb-wire-ends-g:hover .sim-bb-wire-end {\n stroke: red;\n fill: red;\n }\n .sim-bb-wire-ends-g:hover .sim-bb-wire-bare-end {\n stroke: #FFF;\n fill: #FFF;\n }\n `,function(e){e[e.BBJumper=0]="BBJumper",e[e.OpenJumper=1]="OpenJumper",e[e.Croc=2]="Croc"}(r=t.WireEndStyle||(t.WireEndStyle={})),t.mkWirePart=function(n,i,s=!1){let r,o=e.svg.elt("g"),[a,l]=n,d=[a-15,l-50],h=[a+15,l+50];i=t.mapWireColor(i),r=s?u(d,!0,i):c(d,!0,i);let p=function(t,n,i){const s=e=>`${e[0]}, ${e[1]}`;let[r,o]=t,[a,l]=n,c=l-o,u=[r,o+.8*c],d=[a,l-.8*c],h=e.svg.mkPath("sim-bb-wire",`M${s(t)} C${s(u)} ${s(d)} ${s(n)}`);return h.style.stroke=i,{el:h,x:Math.min(r,a),y:Math.min(o,l),w:Math.abs(r-a),h:Math.abs(o-l)}}(d,h,i),f=c(h,!1,i);o.appendChild(p.el),o.appendChild(r.el),o.appendChild(f.el);let m=Math.min(r.x,f.x),g=Math.max(r.x+r.w,f.x+f.w),b=Math.min(r.y,f.y);return{el:o,x:m,y:b,w:g-m,h:Math.max(r.y+r.h,f.y+f.h)-b}};t.WireFactory=class{constructor(e,n,i,s,r,o){this.nextWireId=0,this.styleEl=s,this.styleEl.textContent+=t.WIRES_CSS,this.underboard=e,this.overboard=n,this.boardEdges=i,this.getLocCoord=r,this.getPinStyle=o}indexOfMin(e){let t=0,n=e[0];for(let i=1;i<e.length;i++)e[i]<n&&(n=e[i],t=i);return t}closestEdgeIdx(e){let t=this.boardEdges.map((t=>Math.abs(e[1]-t)));return this.indexOfMin(t)}closestEdge(e){return this.boardEdges[this.closestEdgeIdx(e)]}drawWire(n,r,c){let u=[],d=e.svg.child(this.overboard,"g",{class:"sim-bb-wire-group"});const h=e=>{const n=t.PIN_DIST/2;let i,s=this.closestEdge(e);return i=s-e[1]<0?s-n:s+n,[e[0],i]};let p=this.nextWireId++,f=s(c),m=l(n,f),g=l(r,f),b=e.svg.child(d,"g",{class:"sim-bb-wire-ends-g"});b.appendChild(m),b.appendChild(g);let y=this.closestEdgeIdx(n),v=this.closestEdgeIdx(r);if(y==v){let e=a(n,r,f);d.appendChild(e),u.push(e)}else{let t,s,l=h(n),c=h(r),m=a(n,l,f),g=a(r,c,f);!(1!=y&&2!=y||1!=v&&2!=v)?(t=o(l,c,i,f),s=o(l,c,i,f)):(t=a(l,c,f),s=a(l,c,f)),e.U.addClass(s,"sim-bb-wire-hover"),d.appendChild(m),u.push(m),d.appendChild(g),u.push(g),this.underboard.appendChild(t),u.push(t),d.appendChild(s),u.push(s);let w=`sim-bb-wire-id-${p}`;const k=t=>e.U.addClass(t,w);k(b),k(s),this.styleEl.textContent+=`\n .${w}:hover ~ .${w}.sim-bb-wire-hover {\n visibility: visible;\n }`}let w=`\n .wire-stroke-${f} {\n stroke: ${t.mapWireColor(c)};\n }\n .wire-fill-${f} {\n fill: ${t.mapWireColor(c)};\n }\n `;return this.styleEl.textContent+=w,{endG:b,end1:m,end2:g,wires:u}}drawWireWithCrocs(n,r,c,d=!1){let h=[],p=e.svg.child(this.overboard,"g",{class:"sim-bb-wire-group"});const f=e=>{const n=t.PIN_DIST/2;let i,s=this.closestEdge(e);return i=s-e[1]<0?s-n:s+n,[e[0],i]};let m=this.nextWireId++,g=s(c),b=l(n,g),y=r,[v,w]=r;r=[v,w+40],[v,w]=r;let k,x=[v,w+-17];k=d?function(n,i,s){let r=.24*t.PIN_DIST,o=4*r,a=1.2*r,l=10*r,c=r;const u=t.PIN_DIST/4;let[d,h]=n,p=i?-1:1,f=e.svg.elt("g"),m=e.svg.elt("rect"),g=o,b=a,y=d-b/2,v=h+10-g/2;e.svg.hydrate(m,{x:y,y:v,width:b,height:g,rx:.5,ry:.5,class:"sim-bb-wire-end"}),m.style["stroke-width"]=`${u}px`;let w=e.svg.elt("rect"),k=l,x=c,A=d-x/2,E=h+10+p*(g/2+k/2)-k/2;return e.svg.hydrate(w,{x:A,y:E,width:x,height:k,class:"sim-bb-wire-bare-end"}),w.style.fill="#bbb",f.appendChild(w),f.appendChild(m),{el:f,x:y-u,y:Math.min(v,E),w:b+2*u,h:g+k}}(x,!0):u(x,!0);let A=k.el,E=e.svg.child(p,"g",{class:"sim-bb-wire-ends-g"});E.appendChild(b);let T=this.closestEdgeIdx(n),S=this.closestEdgeIdx(y);if(T==S){let e=a(n,r,g);p.appendChild(e),h.push(e)}else{let t,s,l=f(n),c=a(n,l,g);!(1!=T&&2!=T||1!=S&&2!=S)?(t=o(l,r,i,g),s=o(l,r,i,g)):(t=a(l,r,g),s=a(l,r,g)),e.U.addClass(s,"sim-bb-wire-hover"),p.appendChild(c),h.push(c),this.underboard.appendChild(t),h.push(t);let u=`sim-bb-wire-id-${m}`;const d=t=>e.U.addClass(t,u);d(E),d(s),this.styleEl.textContent+=`\n .${u}:hover ~ .${u}.sim-bb-wire-hover {\n visibility: visible;\n }`}E.appendChild(A);let C=`\n .wire-stroke-${g} {\n stroke: ${t.mapWireColor(c)};\n }\n .wire-fill-${g} {\n fill: ${t.mapWireColor(c)};\n }\n `;return this.styleEl.textContent+=C,{endG:E,end1:b,end2:A,wires:h}}checkWire(e,t){let n=this.getLocCoord(e),i=this.getLocCoord(t);return!!n&&!!i}addWire(e,t,n){let i=this.getLocCoord(e),s=this.getLocCoord(t);if(!i||!s)return void console.debug(`unable to allocate wire for ${e} or ${t}`);let r,o=this.getPinStyle(t);return r="dalboard"==t.type&&"croc"==o?this.drawWireWithCrocs(i,s,n):this.drawWire(i,s,n),r}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={}));