pxt-core 7.3.21 → 7.3.25
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.
- package/built/pxt.js +73 -39
- package/built/pxtblockly.js +1448 -1359
- package/built/pxtblocks.d.ts +4 -4
- package/built/pxtblocks.js +80 -35
- package/built/pxtlib.d.ts +6 -2
- package/built/pxtlib.js +73 -39
- package/built/target.js +1 -1
- package/built/web/blockly.css +1 -1
- package/built/web/main.js +1 -1
- package/built/web/pxtapp.js +1 -1
- package/built/web/pxtasseteditor.js +1 -1
- package/built/web/pxtblockly.js +1 -1
- package/built/web/pxtblocks.js +1 -1
- package/built/web/pxtembed.js +1 -1
- package/built/web/pxtlib.js +1 -1
- package/built/web/pxtworker.js +1 -1
- package/built/web/rtlblockly.css +1 -1
- package/built/web/rtlsemantic.css +1 -1
- package/built/web/semantic.css +1 -1
- package/built/web/skillmap/js/main.7ad07e3a.chunk.js +1 -0
- package/localtypings/blockly.d.ts +6555 -11288
- package/package.json +2 -2
- package/theme/blockly-core.less +13 -22
- package/theme/melodyeditor.less +2 -2
- package/theme/print.less +1 -1
- package/theme/toolbox.less +0 -1
- package/webapp/public/blockly/blockly_compressed.js +1286 -1269
- package/webapp/public/blockly/blocks_compressed.js +65 -47
- package/webapp/public/blockly/msg/js/en.js +17 -8
- package/webapp/public/blockly/msg/json/en.json +15 -6
- package/webapp/public/skillmap.html +1 -1
- package/built/web/skillmap/js/main.bdd63c80.chunk.js +0 -1
package/built/web/pxtworker.js
CHANGED
|
@@ -20,4 +20,4 @@ and limitations under the License.
|
|
|
20
20
|
* All Rights Reserved. Apache Software License 2.0
|
|
21
21
|
*
|
|
22
22
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
23
|
-
*/!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("Fuse",[],t):"object"==typeof exports?exports.Fuse=t():e.Fuse=t()}(this,(function(){return function(e){function t(r){if(n[r])return n[r].exports;var i=n[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,t),i.l=!0,i.exports}var n={};return t.m=e,t.c=n,t.i=function(e){return e},t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=8)}([function(e,t,n){e.exports=function(e){return"[object Array]"===Object.prototype.toString.call(e)}},function(e,t,n){var r=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),i=n(5),a=n(7),o=n(4),s=function(){function e(t,n){var r=n.location,i=void 0===r?0:r,a=n.distance,s=void 0===a?100:a,c=n.threshold,l=void 0===c?.6:c,u=n.maxPatternLength,d=void 0===u?32:u,p=n.isCaseSensitive,f=void 0!==p&&p,_=n.tokenSeparator,m=void 0===_?/ +/g:_,g=n.findAllMatches,h=void 0!==g&&g,y=n.minMatchCharLength,v=void 0===y?1:y;(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),this.options={location:i,distance:s,threshold:l,maxPatternLength:d,isCaseSensitive:f,tokenSeparator:m,findAllMatches:h,minMatchCharLength:v},this.pattern=this.options.isCaseSensitive?t:t.toLowerCase(),this.pattern.length<=d&&(this.patternAlphabet=o(this.pattern))}return r(e,[{key:"search",value:function(e){if(this.options.isCaseSensitive||(e=e.toLowerCase()),this.pattern===e)return{isMatch:!0,score:0,matchedIndices:[[0,e.length-1]]};var t=this.options,n=t.maxPatternLength,r=t.tokenSeparator;if(this.pattern.length>n)return i(e,this.pattern,r);var o=this.options,s=o.location,c=o.distance,l=o.threshold,u=o.findAllMatches,d=o.minMatchCharLength;return a(e,this.pattern,this.patternAlphabet,{location:s,distance:c,threshold:l,findAllMatches:u,minMatchCharLength:d})}}]),e}();e.exports=s},function(e,t,n){var r=n(0),i=function e(t,n,i){if(n){var a=n.indexOf("."),o=n,s=null;-1!==a&&(o=n.slice(0,a),s=n.slice(a+1));var c=t[o];if(null!=c)if(s||"string"!=typeof c&&"number"!=typeof c)if(r(c))for(var l=0,u=c.length;l<u;l+=1)e(c[l],s,i);else s&&e(c,s,i);else i.push(c.toString())}else i.push(t);return i};e.exports=function(e,t){return i(e,t,[])}},function(e,t,n){e.exports=function(){for(var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,n=[],r=-1,i=-1,a=0,o=e.length;a<o;a+=1){var s=e[a];s&&-1===r?r=a:s||-1===r||((i=a-1)-r+1>=t&&n.push([r,i]),r=-1)}return e[a-1]&&a-r>=t&&n.push([r,a-1]),n}},function(e,t,n){e.exports=function(e){for(var t={},n=e.length,r=0;r<n;r+=1)t[e.charAt(r)]=0;for(var i=0;i<n;i+=1)t[e.charAt(i)]|=1<<n-i-1;return t}},function(e,t,n){e.exports=function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:/ +/g,r=new RegExp(t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&").replace(n,"|")),i=e.match(r),a=!!i,o=[];if(a)for(var s=0,c=i.length;s<c;s+=1){var l=i[s];o.push([e.indexOf(l),l.length-1])}return{score:a?.5:1,isMatch:a,matchedIndices:o}}},function(e,t,n){e.exports=function(e,t){var n=t.errors,r=void 0===n?0:n,i=t.currentLocation,a=void 0===i?0:i,o=t.expectedLocation,s=void 0===o?0:o,c=t.distance,l=void 0===c?100:c,u=r/e.length,d=Math.abs(s-a);return l?u+d/l:d?1:u}},function(e,t,n){var r=n(6),i=n(3);e.exports=function(e,t,n,a){for(var o=a.location,s=void 0===o?0:o,c=a.distance,l=void 0===c?100:c,u=a.threshold,d=void 0===u?.6:u,p=a.findAllMatches,f=void 0!==p&&p,_=a.minMatchCharLength,m=void 0===_?1:_,g=s,h=e.length,y=d,v=e.indexOf(t,g),b=t.length,x=[],k=0;k<h;k+=1)x[k]=0;if(-1!==v){var S=r(t,{errors:0,currentLocation:v,expectedLocation:g,distance:l});if(y=Math.min(S,y),-1!==(v=e.lastIndexOf(t,g+b))){var T=r(t,{errors:0,currentLocation:v,expectedLocation:g,distance:l});y=Math.min(T,y)}}v=-1;for(var C=[],E=1,D=b+h,A=1<<b-1,N=0;N<b;N+=1){for(var w=0,I=D;w<I;)r(t,{errors:N,currentLocation:g+I,expectedLocation:g,distance:l})<=y?w=I:D=I,I=Math.floor((D-w)/2+w);D=I;var P=Math.max(1,g-I+1),O=f?h:Math.min(g+I,h)+b,F=Array(O+2);F[O+1]=(1<<N)-1;for(var L=O;L>=P;L-=1){var R=L-1,M=n[e.charAt(R)];if(M&&(x[R]=1),F[L]=(F[L+1]<<1|1)&M,0!==N&&(F[L]|=(C[L+1]|C[L])<<1|1|C[L+1]),F[L]&A&&(E=r(t,{errors:N,currentLocation:R,expectedLocation:g,distance:l}))<=y){if(y=E,(v=R)<=g)break;P=Math.max(1,2*g-v)}}if(r(t,{errors:N+1,currentLocation:g,expectedLocation:g,distance:l})>y)break;C=F}return{isMatch:v>=0,score:0===E?.001:E,matchedIndices:i(x,m)}}},function(e,t,n){var r=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),i=n(1),a=n(2),o=n(0),s=function(){function e(t,n){var r=n.location,i=void 0===r?0:r,o=n.distance,s=void 0===o?100:o,c=n.threshold,l=void 0===c?.6:c,u=n.maxPatternLength,d=void 0===u?32:u,p=n.caseSensitive,f=void 0!==p&&p,_=n.tokenSeparator,m=void 0===_?/ +/g:_,g=n.findAllMatches,h=void 0!==g&&g,y=n.minMatchCharLength,v=void 0===y?1:y,b=n.id,x=void 0===b?null:b,k=n.keys,S=void 0===k?[]:k,T=n.shouldSort,C=void 0===T||T,E=n.getFn,D=void 0===E?a:E,A=n.sortFn,N=void 0===A?function(e,t){return e.score-t.score}:A,w=n.tokenize,I=void 0!==w&&w,P=n.matchAllTokens,O=void 0!==P&&P,F=n.includeMatches,L=void 0!==F&&F,R=n.includeScore,M=void 0!==R&&R,U=n.verbose,B=void 0!==U&&U;(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),this.options={location:i,distance:s,threshold:l,maxPatternLength:d,isCaseSensitive:f,tokenSeparator:m,findAllMatches:h,minMatchCharLength:v,id:x,keys:S,includeMatches:L,includeScore:M,shouldSort:C,getFn:D,sortFn:N,verbose:B,tokenize:I,matchAllTokens:O},this.setCollection(t)}return r(e,[{key:"setCollection",value:function(e){return this.list=e,e}},{key:"search",value:function(e){this._log('---------\nSearch pattern: "'+e+'"');var t=this._prepareSearchers(e),n=t.tokenSearchers,r=t.fullSearcher,i=this._search(n,r),a=i.weights,o=i.results;return this._computeScore(a,o),this.options.shouldSort&&this._sort(o),this._format(o)}},{key:"_prepareSearchers",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",t=[];if(this.options.tokenize)for(var n=e.split(this.options.tokenSeparator),r=0,a=n.length;r<a;r+=1)t.push(new i(n[r],this.options));return{tokenSearchers:t,fullSearcher:new i(e,this.options)}}},{key:"_search",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments[1],n=this.list,r={},i=[];if("string"==typeof n[0]){for(var a=0,o=n.length;a<o;a+=1)this._analyze({key:"",value:n[a],record:a,index:a},{resultMap:r,results:i,tokenSearchers:e,fullSearcher:t});return{weights:null,results:i}}for(var s={},c=0,l=n.length;c<l;c+=1)for(var u=n[c],d=0,p=this.options.keys.length;d<p;d+=1){var f=this.options.keys[d];if("string"!=typeof f){if(s[f.name]={weight:1-f.weight||1},f.weight<=0||f.weight>1)throw new Error("Key weight has to be > 0 and <= 1");f=f.name}else s[f]={weight:1};this._analyze({key:f,value:this.options.getFn(u,f),record:u,index:c},{resultMap:r,results:i,tokenSearchers:e,fullSearcher:t})}return{weights:s,results:i}}},{key:"_analyze",value:function(e,t){var n=e.key,r=e.arrayIndex,i=void 0===r?-1:r,a=e.value,s=e.record,c=e.index,l=t.tokenSearchers,u=void 0===l?[]:l,d=t.fullSearcher,p=void 0===d?[]:d,f=t.resultMap,_=void 0===f?{}:f,m=t.results,g=void 0===m?[]:m;if(null!=a){var h=!1,y=-1,v=0;if("string"==typeof a){this._log("\nKey: "+(""===n?"-":n));var b=p.search(a);if(this._log('Full text: "'+a+'", score: '+b.score),this.options.tokenize){for(var x=a.split(this.options.tokenSeparator),k=[],S=0;S<u.length;S+=1){var T=u[S];this._log('\nPattern: "'+T.pattern+'"');for(var C=!1,E=0;E<x.length;E+=1){var D=x[E],A=T.search(D),N={};A.isMatch?(N[D]=A.score,h=!0,C=!0,k.push(A.score)):(N[D]=1,this.options.matchAllTokens||k.push(1)),this._log('Token: "'+D+'", score: '+N[D])}C&&(v+=1)}y=k[0];for(var w=k.length,I=1;I<w;I+=1)y+=k[I];y/=w,this._log("Token score average:",y)}var P=b.score;y>-1&&(P=(P+y)/2),this._log("Score average:",P);var O=!this.options.tokenize||!this.options.matchAllTokens||v>=u.length;if(this._log("\nCheck Matches: "+O),(h||b.isMatch)&&O){var F=_[c];F?F.output.push({key:n,arrayIndex:i,value:a,score:P,matchedIndices:b.matchedIndices}):(_[c]={item:s,output:[{key:n,arrayIndex:i,value:a,score:P,matchedIndices:b.matchedIndices}]},g.push(_[c]))}}else if(o(a))for(var L=0,R=a.length;L<R;L+=1)this._analyze({key:n,arrayIndex:L,value:a[L],record:s,index:c},{resultMap:_,results:g,tokenSearchers:u,fullSearcher:p})}}},{key:"_computeScore",value:function(e,t){this._log("\n\nComputing score:\n");for(var n=0,r=t.length;n<r;n+=1){for(var i=t[n].output,a=i.length,o=0,s=1,c=0;c<a;c+=1){var l=e?e[i[c].key].weight:1,u=(1===l?i[c].score:i[c].score||.001)*l;1!==l?s=Math.min(s,u):(i[c].nScore=u,o+=u)}t[n].score=1===s?o/a:s,this._log(t[n])}}},{key:"_sort",value:function(e){this._log("\n\nSorting...."),e.sort(this.options.sortFn)}},{key:"_format",value:function(e){var t=[];this._log("\n\nOutput:\n\n",JSON.stringify(e));var n=[];this.options.includeMatches&&n.push((function(e,t){var n=e.output;t.matches=[];for(var r=0,i=n.length;r<i;r+=1){var a=n[r];if(0!==a.matchedIndices.length){var o={indices:a.matchedIndices,value:a.value};a.key&&(o.key=a.key),a.hasOwnProperty("arrayIndex")&&a.arrayIndex>-1&&(o.arrayIndex=a.arrayIndex),t.matches.push(o)}}})),this.options.includeScore&&n.push((function(e,t){t.score=e.score}));for(var r=0,i=e.length;r<i;r+=1){var a=e[r];if(this.options.id&&(a.item=this.options.getFn(a.item,this.options.id)[0]),n.length){for(var o={item:a.item},s=0,c=n.length;s<c;s+=1)n[s](a,o);t.push(o)}else t.push(a.item)}return t}},{key:"_log",value:function(){var e;this.options.verbose&&(e=console).log.apply(e,arguments)}}]),e}();e.exports=s}])}));var e=function(){function t(e,t){postMessage({action:$e,cbn:t,result:e})}function n(e){var t=[];return t[e-1]=void 0,t}function r(e,t){return o(e[0]+t[0],e[1]+t[1])}function i(e,t){return function(e,t){var n;return n=t,0>t&&(n+=Ke),[n,e*Ke]}(~~Math.max(Math.min(e[1]/Ke,2147483647),-2147483648)&~~Math.max(Math.min(t[1]/Ke,2147483647),-2147483648),l(e)&l(t))}function a(e,t){var n,r;return e[0]==t[0]&&e[1]==t[1]?0:(n=0>e[1],r=0>t[1],n&&!r?-1:!n&&r?1:f(e,t)[1]<0?-1:1)}function o(e,t){var n,r;for(e%=0x10000000000000000,t=(t%=0x10000000000000000)-(n=t%Ke)+(r=Math.floor(e/Ke)*Ke),e=e-r+n;0>e;)e+=Ke,t-=Ke;for(;e>4294967295;)e-=Ke,t+=Ke;for(t%=0x10000000000000000;t>0x7fffffff00000000;)t-=0x10000000000000000;for(;-0x8000000000000000>t;)t+=0x10000000000000000;return[e,t]}function s(e,t){return e[0]==t[0]&&e[1]==t[1]}function c(e){return e>=0?[e,0]:[e+Ke,-Ke]}function l(e){return e[0]>=2147483648?~~Math.max(Math.min(e[0]-Ke,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,r,i,a;if(t&=63,s(e,Je))return t?qe:e;if(0>e[1])throw Error("Neg");return a=u(t),r=e[1]*a%0x10000000000000000,(r+=n=(i=e[0]*a)-i%Ke)>=0x8000000000000000&&(r-=0x10000000000000000),[i-=n,r]}function p(e,t){var n;return n=u(t&=63),o(Math.floor(e[0]/n),e[1]/n)}function f(e,t){return o(e[0]-t[0],e[1]-t[1])}function _(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,r){return e.Lc>=e.Yb?-1:(r=Math.min(r,e.Yb-e.Lc),x(e.Mc,e.Lc,t,n,r),e.Lc+=r,r)}function h(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 b(e,t,n,r){x(t,n,e.Mc,e.Yb,r),e.Yb+=r}function x(e,t,n,r,i){for(var a=0;i>a;++a)n[r+a]=e[t+a]}function k(t,n,r,i,o){var s,c;if(a(i,ze)<0)throw Error("invalid length "+i);for(t.Tb=i,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,s=W({})),s.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;b(t,e.fc,0,5)}(s,r),c=0;64>c;c+=8)v(r,255&l(p(i,c)));t.yb=(s.W=0,s.oc=n,s.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),pe(e.A,e.eb,e.fb),(e.ab!=e.wb||e.Hb!=e.n)&&(I(e.b,e.ab,4096,e.n,274),e.wb=e.ab,e.Hb=e.n)}(s),s.d.Ab=r,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=qe,e.xc=qe,e.E=-1,e.Jb=1,e.Oc=0}(e.d),Ne(e.C),Ne(e._),Ne(e.bb),Ne(e.hb),Ne(e.Ub),Ne(e.vc),Ne(e.Sb),function(e){var t,n=1<<e.u+e.I;for(t=0;n>t;++t)Ne(e.V[t].tb)}(e.A);for(var t=0;4>t;++t)Ne(e.K[t].G);oe(e.$,1<<e.Y),oe(e.i,1<<e.Y),Ne(e.S.G),e.N=0,e.jb=0,e.q=0,e.s=0}(s),Y(s),Q(s),s.$.rb=s.n+1-2,de(s.$,1<<s.Y),s.i.rb=s.n+1-2,de(s.i,1<<s.Y),s.g=qe,function(e,t){return e.cb=t,e.Z=null,e.zc=1,e}({},s))}function S(e,t,n){return e.Nb=h({}),k(e,_({},t),e.Nb,c(t.length),n),e}function T(e,t,n){var r,i,a,o,s="",l=[];for(i=0;5>i;++i){if(-1==(a=m(t)))throw Error("truncated input");l[i]=a<<24>>24}if(!function(e,t){var n,r,i,a,o,s,c;if(5>t.length)return 0;for(c=255&t[0],i=c%9,a=(s=~~(c/9))%5,o=~~(s/5),n=0,r=0;4>r;++r)n+=(255&t[1+r])<<8*r;return n>99999999||!function(e,t,n,r){if(t>8||n>4||r>4)return 0;V(e.gb,n,t);var i=1<<r;return K(e.Rb,i),K(e.sb,i),e.Dc=i-1,1}(e,i,a,o)?0:function(e,t){return 0>t?0:(e.Ob!=t&&(e.Ob=t,e.nb=Math.max(e.Ob,1),F(e.B,Math.max(e.nb,4096))),1)}(e,n)}(r=j({}),l))throw Error("corrupted input");for(i=0;64>i;i+=8){if(-1==(a=m(t)))throw Error("truncated input");1==(a=a.toString(16)).length&&(a="0"+a),s=a+""+s}/^0+$|^f+$/i.test(s)?e.Tb=ze:(o=parseInt(s,16),e.Tb=o>4294967295?ze:c(o)),e.yb=function(e,t,n,r){return e.e.Ab=t,M(e.B),e.B.cc=n,function(e){e.B.h=0,e.B.o=0,Ne(e.Gb),Ne(e.pb),Ne(e.Zb),Ne(e.Cb),Ne(e.Db),Ne(e.Eb),Ne(e.kc),function(e){var t,n;for(n=1<<e.u+e.I,t=0;n>t;++t)Ne(e.V[t].Ib)}(e.gb);for(var t=0;4>t;++t)Ne(e.kb[t].G);q(e.Rb),q(e.sb),Ne(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=r,e.g=qe,e.jc=0,function(e,t){return e.Z=t,e.cb=null,e.zc=1,e}({},e)}(r,t,n,e.Tb)}function C(e,t){return e.Nb=h({}),T(e,_({},t),e.Nb),e}function E(e,t){return e.c[e.f+e.o+t]}function D(e,t,n,r){var i,a;for(e.T&&e.o+t+r>e.h&&(r=e.h-(e.o+t)),++n,a=e.f+e.o+t,i=0;r>i&&e.c[a+i]==e.c[a+i-n];++i);return i}function A(e){return e.h-e.o}function N(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 w(e,t){e.f+=t,e.zb-=t,e.o-=t,e.h-=t}function I(e,t,r,i,a){var o,s;1073741567>t&&(e.Fc=16+(i>>1),function(e,t,r,i){var a;e.Bc=t,e._b=r,a=t+r+i,(null==e.c||e.Kb!=a)&&(e.c=null,e.Kb=a,e.c=n(e.Kb)),e.H=e.Kb-r}(e,t+r,i+a,256+~~((t+r+i+a)/2)),e.ob=i,o=t+1,e.p!=o&&(e.L=n(2*(e.p=o))),s=65536,e.qb&&(s=t-1,s|=s>>1,s|=s>>2,s|=s>>4,s|=s>>8,s>>=1,(s|=65535)>16777216&&(s>>=1),e.Ec=s,++s,s+=e.R),s!=e.rc&&(e.ub=n(e.rc=s)))}function P(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,r;for((r=e.f+e.o-e.Bc)>0&&--r,n=e.f+e.h-r,t=0;n>t;++t)e.c[t]=e.c[r+t];e.f-=r}(e),N(e))}(e),1073741823==e.o&&(t=e.o-e.p,O(e.L,2*e.p,t),O(e.ub,e.rc,t),w(e,t))}function O(e,t,n){var r,i;for(r=0;t>r;++r)n>=(i=e[r]||0)?i=0:i-=n,e[r]=i}function F(e,t){(null==e.Lb||e.M!=t)&&(e.Lb=n(t)),e.M=t,e.o=0,e.h=0}function L(e){var t=e.o-e.h;t&&(b(e.cc,e.Lb,e.h,t),e.o>=e.M&&(e.o=0),e.h=e.o)}function R(e,t){var n=e.o-t-1;return 0>n&&(n+=e.M),e.Lb[n]}function M(e){L(e),e.cc=null}function U(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,i){var o,u,d,p,_,m,g,h,y,v,b,x,k,S,T;if(t[0]=qe,n[0]=qe,i[0]=1,e.oc&&(e.b.cc=e.oc,function(e){e.f=0,e.o=0,e.h=0,e.T=0,N(e),e.k=0,w(e,-1)}(e.b),e.W=1,e.oc=null),!e.pc){if(e.pc=1,S=e.g,s(e.g,qe)){if(!A(e.b))return void X(e,l(e.g));re(e),k=l(e.g)&e.y,we(e.d,e.C,(e.l<<4)+k,0),e.l=B(e.l),d=E(e.b,-e.s),_e(fe(e.A,l(e.g),e.J),e.d,d),e.J=d,--e.s,e.g=r(e.g,Ve)}if(!A(e.b))return void X(e,l(e.g));for(;;){if(g=Z(e,l(e.g)),v=e.mb,k=l(e.g)&e.y,u=(e.l<<4)+k,1==g&&-1==v)we(e.d,e.C,u,0),d=E(e.b,-e.s),T=fe(e.A,l(e.g),e.J),7>e.l?_e(T,e.d,d):(y=E(e.b,-e.v[0]-1-e.s),me(T,e.d,y,d)),e.J=d,e.l=B(e.l);else{if(we(e.d,e.C,u,1),4>v){if(we(e.d,e.bb,e.l,1),v?(we(e.d,e.hb,e.l,1),1==v?we(e.d,e.Ub,e.l,0):(we(e.d,e.Ub,e.l,1),we(e.d,e.vc,e.l,v-2))):(we(e.d,e.hb,e.l,0),we(e.d,e._,u,1==g?0:1)),1==g?e.l=7>e.l?9:11:(ce(e.i,e.d,g-2,k),e.l=7>e.l?8:11),p=e.v[v],0!=v){for(m=v;m>=1;--m)e.v[m]=e.v[m-1];e.v[0]=p}}else{for(we(e.d,e.bb,e.l,0),e.l=7>e.l?7:10,ce(e.$,e.d,g-2,k),x=ae(v-=4),h=U(g),ke(e.K[h],e.d,x),x>=4&&(b=v-(o=(2|1&x)<<(_=(x>>1)-1)),14>x?Ee(e.Sb,o-x-1,e.d,_,b):(Ie(e.d,b>>4,_-4),Te(e.S,e.d,15&b),++e.Qb)),p=v,m=3;m>=1;--m)e.v[m]=e.v[m-1];e.v[0]=p,++e.Mb}e.J=E(e.b,g-1-e.s)}if(e.s-=g,e.g=r(e.g,c(g)),!e.s){if(e.Mb>=128&&Y(e),e.Qb>=16&&Q(e),t[0]=e.g,n[0]=Pe(e.d),!A(e.b))return void X(e,l(e.g));if(a(f(e.g,S),[4096,0])>=0)return e.pc=0,void(i[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){ie(e),e.d.Ab=null}(e.cb),e.zc=0)}(e):function(e){var t=function(e){var t,n,i,o,s,u;if(u=l(e.g)&e.Dc,Ae(e.e,e.Gb,(e.U<<4)+u)){if(Ae(e.e,e.Zb,e.U))i=0,Ae(e.e,e.Cb,e.U)?(Ae(e.e,e.Db,e.U)?(Ae(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):Ae(e.e,e.pb,(e.U<<4)+u)||(e.U=7>e.U?9:11,i=1),i||(i=z(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,i=2+z(e.Rb,e.e,u),e.U=7>e.U?7:10,(s=be(e.kb[U(i)],e.e))>=4){if(o=(s>>1)-1,e.ib=(2|1&s)<<o,14>s)e.ib+=function(e,t,n,r){var i,a,o=1,s=0;for(a=0;r>a;++a)i=Ae(n,e,t+o),o<<=1,o+=i,s|=i<<a;return s}(e.kc,e.ib-s-1,e.e,o);else if(e.ib+=function(e,t){var n,r,i=0;for(n=t;0!=n;--n)e.E>>>=1,r=e.Bb-e.E>>>31,e.Bb-=e.E&r-1,i=i<<1|1-r,-16777216&e.E||(e.Bb=e.Bb<<8|m(e.Ab),e.E<<=8);return i}(e.e,o-4)<<4,e.ib+=function(e,t){var n,r,i=1,a=0;for(r=0;e.F>r;++r)n=Ae(t,e.G,i),i<<=1,i+=n,a|=n<<r;return a}(e.Fb,e.e),0>e.ib)return-1==e.ib?1:-1}else e.ib=s;if(a(c(e.ib),e.g)>=0||e.ib>=e.nb)return-1;(function(e,t,n){var r=e.o-t-1;for(0>r&&(r+=e.M);0!=n;--n)r>=e.M&&(r=0),e.Lb[e.o++]=e.Lb[r++],e.o>=e.M&&L(e)})(e.B,e.ib,i),e.g=r(e.g,c(i)),e.jc=R(e.B,0)}else t=function(e,t,n){return e.V[((t&e.qc)<<e.u)+((255&n)>>>8-e.u)]}(e.gb,l(e.g),e.jc),e.jc=7>e.U?function(e,t){var n=1;do{n=n<<1|Ae(t,e.Ib,n)}while(256>n);return n<<24>>24}(t,e.e):function(e,t,n){var r,i,a=1;do{if(i=n>>7&1,n<<=1,r=Ae(t,e.Ib,(1+i<<8)+a),a=a<<1|r,i!=r){for(;256>a;)a=a<<1|Ae(t,e.Ib,a);break}}while(256>a);return a<<24>>24}(t,e.e,R(e.B,e.ib)),function(e,t){e.Lb[e.o++]=t,e.o>=e.M&&L(e)}(e.B,e.jc),e.U=B(e.U),e.g=r(e.g,Ve);return 0}(e.Z);if(-1==t)throw Error("corrupted input");e.Pb=ze,e.Pc=e.Z.g,(t||a(e.Z.Nc,qe)>=0&&a(e.Z.g,e.Z.Nc)>=0)&&(L(e.Z.B),M(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=J({}),e.sb=J({}),e.gb={};for(var t=0;4>t;++t)e.kb[t]=ve({},6);return e}function K(e,t){for(;t>e.O;++e.O)e.ec[e.O]=ve({},3),e.hc[e.O]=ve({},3)}function z(e,t,n){return Ae(t,e.wc,0)?8+(Ae(t,e.wc,1)?8+be(e.tc,t):be(e.hc[n],t)):be(e.ec[n],t)}function J(e){return e.wc=n(2),e.ec=n(16),e.hc=n(16),e.tc=ve({},8),e.O=0,e}function q(e){Ne(e.wc);for(var t=0;e.O>t;++t)Ne(e.ec[t].G),Ne(e.hc[t].G);Ne(e.tc.G)}function V(e,t,r){var i,a;if(null==e.V||e.u!=r||e.I!=t)for(e.I=t,e.qc=(1<<t)-1,e.u=r,a=1<<e.u+e.I,e.V=n(a),i=0;a>i;++i)e.V[i]=H({})}function H(e){return e.Ib=n(768),e}function G(e,t){var n,r,i,a;e.jb=t,i=e.a[t].r,r=e.a[t].j;do{e.a[t].t&&(ye(e.a[i]),e.a[i].r=i-1,e.a[t].Ac&&(e.a[i-1].t=0,e.a[i-1].r=e.a[t].r2,e.a[i-1].j=e.a[t].j2)),a=i,n=r,r=e.a[a].j,i=e.a[a].r,e.a[a].j=n,e.a[a].r=t,t=a}while(t>0);return e.mb=e.a[0].j,e.q=e.a[0].r}function W(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=xe({},4),e.$=le({}),e.i=le({}),e.A={},e.m=[],e.P=[],e.lb=[],e.nc=n(16),e.x=n(4),e.Q=n(4),e.Xb=[qe],e.uc=[qe],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]=xe({},6);return e}function Q(e){for(var t=0;16>t;++t)e.nc[t]=Ce(e.S,t);e.Qb=0}function Y(e){var t,n,r,i,a,o,s,c;for(i=4;128>i;++i)t=(2|1&(o=ae(i)))<<(r=(o>>1)-1),e.yc[i]=De(e.Sb,t-o-1,r,i-t);for(a=0;4>a;++a){for(n=e.K[a],s=a<<6,o=0;e.$b>o;++o)e.P[s+o]=Se(n,o);for(o=14;e.$b>o;++o)e.P[s+o]+=(o>>1)-1-4<<6;for(c=128*a,i=0;4>i;++i)e.lb[c+i]=e.P[s+i];for(;128>i;++i)e.lb[c+i]=e.P[s+ae(i)]+e.yc[i]}e.Mb=0}function X(e,t){ie(e),function(e,t){if(e.Gc){we(e.d,e.C,(e.l<<4)+t,1),we(e.d,e.bb,e.l,0),e.l=7>e.l?7:10,ce(e.$,e.d,0,t);var n=U(2);ke(e.K[n],e.d,63),Ie(e.d,67108863,26),Te(e.S,e.d,15)}}(e,t&e.y);for(var n=0;5>n;++n)Oe(e.d)}function Z(e,t){var n,r,i,a,o,s,c,l,u,d,p,f,_,m,g,h,y,v,b,x,k,S,T,C,N,w,I,P,O,F,L,R,M,U,$,j,K,z,J,q,V,H,W,Q;if(e.jb!=e.q)return _=e.a[e.q].r-e.q,e.mb=e.a[e.q].j,e.q=e.a[e.q].r,_;if(e.q=e.jb=0,e.N?(f=e.vb,e.N=0):f=re(e),w=e.D,2>(C=A(e.b)+1))return e.mb=-1,1;for(C>273&&(C=273),J=0,u=0;4>u;++u)e.x[u]=e.v[u],e.Q[u]=D(e.b,-1,e.x[u],273),e.Q[u]>e.Q[J]&&(J=u);if(e.Q[J]>=e.n)return e.mb=J,ne(e,(_=e.Q[J])-1),_;if(f>=e.n)return e.mb=e.m[w-1]+4,ne(e,f-1),f;if(c=E(e.b,-1),y=E(e.b,-e.v[0]-1-1),2>f&&c!=y&&2>e.Q[J])return e.mb=-1,1;if(e.a[0].Hc=e.l,M=t&e.y,e.a[1].z=We[e.C[(e.l<<4)+M]>>>2]+he(fe(e.A,t,e.J),e.l>=7,y,c),ye(e.a[1]),z=(v=We[2048-e.C[(e.l<<4)+M]>>>2])+We[2048-e.bb[e.l]>>>2],y==c&&(q=z+function(e,t,n){return We[e.hb[t]>>>2]+We[e._[(t<<4)+n]>>>2]}(e,e.l,M),e.a[1].z>q&&(e.a[1].z=q,function(e){e.j=0,e.t=0}(e.a[1]))),2>(p=f>=e.Q[J]?f:e.Q[J]))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=p;do{e.a[d--].z=268435455}while(d>=2);for(u=0;4>u;++u)if(!(2>(K=e.Q[u]))){$=z+te(e,u,e.l,M);do{a=$+ue(e.i,K-2,M),(F=e.a[K]).z>a&&(F.z=a,F.r=0,F.j=u,F.t=0)}while(--K>=2)}if(T=v+We[e.bb[e.l]>>>2],f>=(d=e.Q[0]>=2?e.Q[0]+1:2)){for(I=0;d>e.m[I];)I+=2;for(;a=T+ee(e,l=e.m[I+1],d,M),(F=e.a[d]).z>a&&(F.z=a,F.r=0,F.j=l+4,F.t=0),d!=e.m[I]||(I+=2)!=w;++d);}for(n=0;;){if(++n==p)return G(e,n);if(b=re(e),w=e.D,b>=e.n)return e.vb=b,e.N=1,G(e,n);if(++t,R=e.a[n].r,e.a[n].t?(--R,e.a[n].Ac?(H=e.a[e.a[n].r2].Hc,H=4>e.a[n].j2?7>H?8:11:7>H?7:10):H=e.a[R].Hc,H=B(H)):H=e.a[R].Hc,R==n-1?H=e.a[n].j?B(H):7>H?9:11:(e.a[n].t&&e.a[n].Ac?(R=e.a[n].r2,L=e.a[n].j2,H=7>H?8:11):H=4>(L=e.a[n].j)?7>H?8:11:7>H?7:10,O=e.a[R],4>L?L?1==L?(e.x[0]=O.ac,e.x[1]=O.bc,e.x[2]=O.dc,e.x[3]=O.lc):2==L?(e.x[0]=O.dc,e.x[1]=O.bc,e.x[2]=O.ac,e.x[3]=O.lc):(e.x[0]=O.lc,e.x[1]=O.bc,e.x[2]=O.ac,e.x[3]=O.dc):(e.x[0]=O.bc,e.x[1]=O.ac,e.x[2]=O.dc,e.x[3]=O.lc):(e.x[0]=L-4,e.x[1]=O.bc,e.x[2]=O.ac,e.x[3]=O.dc)),e.a[n].Hc=H,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],s=e.a[n].z,c=E(e.b,-1),y=E(e.b,-e.x[0]-1-1),M=t&e.y,r=s+We[e.C[(H<<4)+M]>>>2]+he(fe(e.A,t,E(e.b,-2)),H>=7,y,c),x=0,(k=e.a[n+1]).z>r&&(k.z=r,k.r=n,k.j=-1,k.t=0,x=1),z=(v=s+We[2048-e.C[(H<<4)+M]>>>2])+We[2048-e.bb[H]>>>2],y!=c||n>k.r&&!k.j||(q=z+(We[e.hb[H]>>>2]+We[e._[(H<<4)+M]>>>2]),k.z>=q&&(k.z=q,k.r=n,k.j=0,k.t=0,x=1)),!(2>(C=N=(N=A(e.b)+1)>4095-n?4095-n:N))){if(C>e.n&&(C=e.n),!x&&y!=c&&(Q=Math.min(N-1,e.n),(g=D(e.b,0,e.x[0],Q))>=2)){for(W=B(H),U=t+1&e.y,S=r+We[2048-e.C[(W<<4)+U]>>>2]+We[2048-e.bb[W]>>>2],P=n+1+g;P>p;)e.a[++p].z=268435455;a=S+(ue(e.i,g-2,U)+te(e,0,W,U)),(F=e.a[P]).z>a&&(F.z=a,F.r=n+1,F.j=0,F.t=1,F.Ac=0)}for(V=2,j=0;4>j;++j)if(!(2>(m=D(e.b,-1,e.x[j],C)))){h=m;do{for(;n+m>p;)e.a[++p].z=268435455;a=z+(ue(e.i,m-2,M)+te(e,j,H,M)),(F=e.a[n+m]).z>a&&(F.z=a,F.r=n,F.j=j,F.t=0)}while(--m>=2);if(m=h,j||(V=m+1),N>m&&(Q=Math.min(N-1-m,e.n),(g=D(e.b,m,e.x[j],Q))>=2)){for(W=7>H?8:11,U=t+m&e.y,i=z+(ue(e.i,m-2,M)+te(e,j,H,M))+We[e.C[(W<<4)+U]>>>2]+he(fe(e.A,t+m,E(e.b,m-1-1)),1,E(e.b,m-1-(e.x[j]+1)),E(e.b,m-1)),W=B(W),U=t+m+1&e.y,S=i+We[2048-e.C[(W<<4)+U]>>>2]+We[2048-e.bb[W]>>>2],P=m+1+g;n+P>p;)e.a[++p].z=268435455;a=S+(ue(e.i,g-2,U)+te(e,0,W,U)),(F=e.a[n+P]).z>a&&(F.z=a,F.r=n+m+1,F.j=0,F.t=1,F.Ac=1,F.r2=n,F.j2=j)}}if(b>C){for(b=C,w=0;b>e.m[w];w+=2);e.m[w]=b,w+=2}if(b>=V){for(T=v+We[e.bb[H]>>>2];n+b>p;)e.a[++p].z=268435455;for(I=0;V>e.m[I];)I+=2;for(m=V;;++m)if(a=T+ee(e,o=e.m[I+1],m,M),(F=e.a[n+m]).z>a&&(F.z=a,F.r=n,F.j=o+4,F.t=0),m==e.m[I]){if(N>m&&(Q=Math.min(N-1-m,e.n),(g=D(e.b,m,o,Q))>=2)){for(W=7>H?7:10,U=t+m&e.y,i=a+We[e.C[(W<<4)+U]>>>2]+he(fe(e.A,t+m,E(e.b,m-1-1)),1,E(e.b,m-(o+1)-1),E(e.b,m-1)),W=B(W),U=t+m+1&e.y,S=i+We[2048-e.C[(W<<4)+U]>>>2]+We[2048-e.bb[W]>>>2],P=m+1+g;n+P>p;)e.a[++p].z=268435455;a=S+(ue(e.i,g-2,U)+te(e,0,W,U)),(F=e.a[n+P]).z>a&&(F.z=a,F.r=n+m+1,F.j=0,F.t=1,F.Ac=1,F.r2=n,F.j2=o+4)}if((I+=2)==w)break}}}}}function ee(e,t,n,r){var i=U(n);return(128>t?e.lb[128*i+t]:e.P[(i<<6)+function(e){return 131072>e?Ge[e>>6]+12:134217728>e?Ge[e>>16]+32:Ge[e>>26]+52}(t)]+e.nc[15&t])+ue(e.$,n-2,r)}function te(e,t,n,r){var i;return t?(i=We[2048-e.hb[n]>>>2],1==t?i+=We[e.Ub[n]>>>2]:(i+=We[2048-e.Ub[n]>>>2],i+=Fe(e.vc[n],t-2))):(i=We[e.hb[n]>>>2],i+=We[2048-e._[(n<<4)+r]>>>2]),i}function ne(e,t){t>0&&(function(e,t){var n,r,i,a,o,s,c,l,u,d,p,f,_,m,g,h,y;do{if(e.h>=e.o+e.ob)f=e.ob;else if(f=e.h-e.o,e.xb>f){P(e);continue}for(_=e.o>e.p?e.o-e.p:0,r=e.f+e.o,e.qb?(s=1023&(y=He[255&e.c[r]]^255&e.c[r+1]),e.ub[s]=e.o,c=65535&(y^=(255&e.c[r+2])<<8),e.ub[1024+c]=e.o,l=(y^He[255&e.c[r+3]]<<5)&e.Ec):l=255&e.c[r]^(255&e.c[r+1])<<8,i=e.ub[e.R+l],e.ub[e.R+l]=e.o,g=1+(e.k<<1),h=e.k<<1,d=p=e.w,n=e.Fc;;){if(_>=i||0==n--){e.L[g]=e.L[h]=0;break}if(o=e.o-i,a=(e.k>=o?e.k-o:e.k-o+e.p)<<1,m=e.f+i,u=p>d?d:p,e.c[m+u]==e.c[r+u]){for(;++u!=f&&e.c[m+u]==e.c[r+u];);if(u==f){e.L[h]=e.L[a],e.L[g]=e.L[a+1];break}}(255&e.c[r+u])>(255&e.c[m+u])?(e.L[h]=i,h=a+1,i=e.L[h],p=u):(e.L[g]=i,g=a,i=e.L[g],d=u)}P(e)}while(0!=--t)}(e.b,t),e.s+=t)}function re(e){var t=0;return e.D=function(e,t){var n,r,i,a,o,s,c,l,u,d,p,f,_,m,g,h,y,v,b,x,k;if(e.h>=e.o+e.ob)m=e.ob;else if(m=e.h-e.o,e.xb>m)return P(e),0;for(y=0,g=e.o>e.p?e.o-e.p:0,r=e.f+e.o,h=1,l=0,u=0,e.qb?(l=1023&(k=He[255&e.c[r]]^255&e.c[r+1]),u=65535&(k^=(255&e.c[r+2])<<8),d=(k^He[255&e.c[r+3]]<<5)&e.Ec):d=255&e.c[r]^(255&e.c[r+1])<<8,i=e.ub[e.R+d]||0,e.qb&&(a=e.ub[l]||0,o=e.ub[1024+u]||0,e.ub[l]=e.o,e.ub[1024+u]=e.o,a>g&&e.c[e.f+a]==e.c[r]&&(t[y++]=h=2,t[y++]=e.o-a-1),o>g&&e.c[e.f+o]==e.c[r]&&(o==a&&(y-=2),t[y++]=h=3,t[y++]=e.o-o-1,a=o),0!=y&&a==i&&(y-=2,h=1)),e.ub[e.R+d]=e.o,b=1+(e.k<<1),x=e.k<<1,f=_=e.w,0!=e.w&&i>g&&e.c[e.f+i+e.w]!=e.c[r+e.w]&&(t[y++]=h=e.w,t[y++]=e.o-i-1),n=e.Fc;;){if(g>=i||0==n--){e.L[b]=e.L[x]=0;break}if(c=e.o-i,s=(e.k>=c?e.k-c:e.k-c+e.p)<<1,v=e.f+i,p=_>f?f:_,e.c[v+p]==e.c[r+p]){for(;++p!=m&&e.c[v+p]==e.c[r+p];);if(p>h&&(t[y++]=h=p,t[y++]=c-1,p==m)){e.L[x]=e.L[s],e.L[b]=e.L[s+1];break}}(255&e.c[r+p])>(255&e.c[v+p])?(e.L[x]=i,x=s+1,i=e.L[x],_=p):(e.L[b]=i,b=s,i=e.L[b],f=p)}return P(e),y}(e.b,e.m),e.D>0&&((t=e.m[e.D-2])==e.n&&(t+=D(e.b,t-1,e.m[e.D-1],273-t))),++e.s,t}function ie(e){e.b&&e.W&&(e.b.cc=null,e.W=0)}function ae(e){return 2048>e?Ge[e]:2097152>e?Ge[e>>10]+20:Ge[e>>20]+40}function oe(e,t){Ne(e.db);for(var n=0;t>n;++n)Ne(e.Vb[n].G),Ne(e.Wb[n].G);Ne(e.ic.G)}function se(e,t,n,r,i){var a,o,s,c,l;for(a=We[e.db[0]>>>2],s=(o=We[2048-e.db[0]>>>2])+We[e.db[1]>>>2],c=o+We[2048-e.db[1]>>>2],l=0,l=0;8>l;++l){if(l>=n)return;r[i+l]=a+Se(e.Vb[t],l)}for(;16>l;++l){if(l>=n)return;r[i+l]=s+Se(e.Wb[t],l-8)}for(;n>l;++l)r[i+l]=c+Se(e.ic,l-8-8)}function ce(e,t,n,r){(function(e,t,n,r){8>n?(we(t,e.db,0,0),ke(e.Vb[r],t,n)):(n-=8,we(t,e.db,0,1),8>n?(we(t,e.db,1,0),ke(e.Wb[r],t,n)):(we(t,e.db,1,1),ke(e.ic,t,n-8)))})(e,t,n,r),0==--e.sc[r]&&(se(e,r,e.rb,e.Cc,272*r),e.sc[r]=e.rb)}function le(e){return function(e){e.db=n(2),e.Vb=n(16),e.Wb=n(16),e.ic=xe({},8);for(var t=0;16>t;++t)e.Vb[t]=xe({},3),e.Wb[t]=xe({},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)se(e,n,e.rb,e.Cc,272*n),e.sc[n]=e.rb}function pe(e,t,r){var i,a;if(null==e.V||e.u!=r||e.I!=t)for(e.I=t,e.qc=(1<<t)-1,e.u=r,a=1<<e.u+e.I,e.V=n(a),i=0;a>i;++i)e.V[i]=ge({})}function fe(e,t,n){return e.V[((t&e.qc)<<e.u)+((255&n)>>>8-e.u)]}function _e(e,t,n){var r,i,a=1;for(i=7;i>=0;--i)r=n>>i&1,we(t,e.tb,a,r),a=a<<1|r}function me(e,t,n,r){var i,a,o,s,c=1,l=1;for(a=7;a>=0;--a)i=r>>a&1,s=l,c&&(s+=1+(o=n>>a&1)<<8,c=o==i),we(t,e.tb,s,i),l=l<<1|i}function ge(e){return e.tb=n(768),e}function he(e,t,n,r){var i,a,o=1,s=7,c=0;if(t)for(;s>=0;--s)if(a=n>>s&1,i=r>>s&1,c+=Fe(e.tb[(1+a<<8)+o],i),o=o<<1|i,a!=i){--s;break}for(;s>=0;--s)i=r>>s&1,c+=Fe(e.tb[o],i),o=o<<1|i;return c}function ye(e){e.j=-1,e.t=0}function ve(e,t){return e.F=t,e.G=n(1<<t),e}function be(e,t){var n,r=1;for(n=e.F;0!=n;--n)r=(r<<1)+Ae(t,e.G,r);return r-(1<<e.F)}function xe(e,t){return e.F=t,e.G=n(1<<t),e}function ke(e,t,n){var r,i,a=1;for(i=e.F;0!=i;)r=n>>>--i&1,we(t,e.G,a,r),a=a<<1|r}function Se(e,t){var n,r,i=1,a=0;for(r=e.F;0!=r;)n=t>>>--r&1,a+=Fe(e.G[i],n),i=(i<<1)+n;return a}function Te(e,t,n){var r,i,a=1;for(i=0;e.F>i;++i)r=1&n,we(t,e.G,a,r),a=a<<1|r,n>>=1}function Ce(e,t){var n,r,i=1,a=0;for(r=e.F;0!=r;--r)n=1&t,t>>>=1,a+=Fe(e.G[i],n),i=i<<1|n;return a}function Ee(e,t,n,r,i){var a,o,s=1;for(o=0;r>o;++o)we(n,e,t+s,a=1&i),s=s<<1|a,i>>=1}function De(e,t,n,r){var i,a,o=1,s=0;for(a=n;0!=a;--a)i=1&r,r>>>=1,s+=We[(2047&(e[t+o]-i^-i))>>>2],o=o<<1|i;return s}function Ae(e,t,n){var r,i=t[n];return(-2147483648^(r=(e.E>>>11)*i))>(-2147483648^e.Bb)?(e.E=r,t[n]=i+(2048-i>>>5)<<16>>16,-16777216&e.E||(e.Bb=e.Bb<<8|m(e.Ab),e.E<<=8),0):(e.E-=r,e.Bb-=r,t[n]=i-(i>>>5)<<16>>16,-16777216&e.E||(e.Bb=e.Bb<<8|m(e.Ab),e.E<<=8),1)}function Ne(e){for(var t=e.length-1;t>=0;--t)e[t]=1024}function we(e,t,n,a){var o,s=t[n];o=(e.E>>>11)*s,a?(e.xc=r(e.xc,i(c(o),[4294967295,0])),e.E-=o,t[n]=s-(s>>>5)<<16>>16):(e.E=o,t[n]=s+(2048-s>>>5)<<16>>16),-16777216&e.E||(e.E<<=8,Oe(e))}function Ie(e,t,n){for(var i=n-1;i>=0;--i)e.E>>>=1,1==(t>>>i&1)&&(e.xc=r(e.xc,c(e.E))),-16777216&e.E||(e.E<<=8,Oe(e))}function Pe(e){return r(r(c(e.Jb),e.mc),[4,0])}function Oe(e){var t,n=l(function(e,t){var n;return n=p(e,t&=63),0>e[1]&&(n=r(n,d([2,0],63-t))),n}(e.xc,32));if(0!=n||a(e.xc,[4278190080,0])<0){e.mc=r(e.mc,c(e.Jb)),t=e.Oc;do{v(e.Ab,t+n),t=255}while(0!=--e.Jb);e.Oc=l(e.xc)>>>24}++e.Jb,e.xc=d(i(e.xc,[16777215,0]),8)}function Fe(e,t){return We[(2047&(e-t^-t))>>>2]}function Le(e){for(var t,n,r,i=0,a=0,o=e.length,s=[],c=[];o>i;++i,++a){if(128&(t=255&e[i]))if(192==(224&t)){if(i+1>=o)return e;if(128!=(192&(n=255&e[++i])))return e;c[a]=(31&t)<<6|63&n}else{if(224!=(240&t))return e;if(i+2>=o)return e;if(128!=(192&(n=255&e[++i])))return e;if(128!=(192&(r=255&e[++i])))return e;c[a]=(15&t)<<12|(63&n)<<6|63&r}else{if(!t)return e;c[a]=t}16383==a&&(s.push(String.fromCharCode.apply(String,c)),a=-1)}return a>0&&(c.length=a,s.push(String.fromCharCode.apply(String,c))),s.join("")}function Re(e){var t,n,r,i=[],a=0,o=e.length;if("object"==typeof e)return e;for(function(e,t,n,r,i){var a;for(a=t;n>a;++a)r[i++]=e.charCodeAt(a)}(e,0,o,i,0),r=0;o>r;++r)(t=i[r])>=1&&127>=t?++a:a+=!t||t>=128&&2047>=t?2:3;for(n=[],a=0,r=0;o>r;++r)(t=i[r])>=1&&127>=t?n[a++]=t<<24>>24:!t||t>=128&&2047>=t?(n[a++]=(192|t>>6&31)<<24>>24,n[a++]=(128|63&t)<<24>>24):(n[a++]=(224|t>>12&15)<<24>>24,n[a++]=(128|t>>6&63)<<24>>24,n[a++]=(128|63&t)<<24>>24);return n}function Me(e){return e[1]+e[0]}var Ue=1,Be=2,$e=3,je="function"==typeof setImmediate?setImmediate:setTimeout,Ke=4294967296,ze=[4294967295,-Ke],Je=[0,-0x8000000000000000],qe=[0,0],Ve=[1,0],He=function(){var e,t,n,r=[];for(e=0;256>e;++e){for(n=e,t=0;8>t;++t)0!=(1&n)?n=n>>>1^-306674912:n>>>=1;r[e]=n}return r}(),Ge=function(){var e,t,n,r=2,i=[0,1];for(n=2;22>n;++n)for(t=1<<(n>>1)-1,e=0;t>e;++e,++r)i[r]=n<<24>>24;return i}(),We=function(){var e,t,n,r=[];for(t=8;t>=0;--t)for(e=1<<9-t,n=1<<9-t-1;e>n;++n)r[n]=(t<<6)+(e-n<<6>>>9-t-1);return r}(),Qe=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==Ue&&e.compress(t.gc.gc,t.gc.Rc,t.gc.cbn))}),{compress:function(e,n,r,i){var a,o,s={},c=void 0===r&&void 0===i;if("function"!=typeof r&&(o=r,r=i=0),i=i||function(e){return void 0!==o?t(e,o):void 0},r=r||function(e,t){return void 0!==o?postMessage({action:Ue,cbn:o,result:e,error:t}):void 0},c){for(s.c=S({},Re(e),Qe(n));$(s.c.yb););return y(s.c.Nb)}try{s.c=S({},Re(e),Qe(n)),i(0)}catch(e){return r(null,e)}je((function e(){try{for(var t,n=(new Date).getTime();$(s.c.yb);)if(a=Me(s.c.yb.Pb)/Me(s.c.Tb),(new Date).getTime()-n>200)return i(a),je(e,0),0;i(1),t=y(s.c.Nb),je(r.bind(null,t),0)}catch(e){r(null,e)}}),0)},decompress:function(e,n,r){var i,a,o,s,c={},l=void 0===n&&void 0===r;if("function"!=typeof n&&(a=n,n=r=0),r=r||function(e){return void 0!==a?t(o?e:-1,a):void 0},n=n||function(e,t){return void 0!==a?postMessage({action:Be,cbn:a,result:e,error:t}):void 0},l){for(c.d=C({},e);$(c.d.yb););return Le(y(c.d.Nb))}try{c.d=C({},e),s=Me(c.d.Tb),o=s>-1,r(0)}catch(e){return n(null,e)}je((function e(){try{for(var t,a=0,l=(new Date).getTime();$(c.d.yb);)if(++a%1e3==0&&(new Date).getTime()-l>200)return o&&(i=Me(c.d.yb.Z.g)/s,r(i)),je(e,0),0;r(1),t=Le(y(c.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.DOMPurify=t()}(this,(function(){function e(e){return function(t){for(var n=arguments.length,r=Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return p(e,t,r)}}function t(e){return function(){for(var t=arguments.length,n=Array(t),r=0;r<t;r++)n[r]=arguments[r];return f(e,n)}}function n(e,t){o&&o(e,null);for(var n=t.length;n--;){var r=t[n];if("string"==typeof r){var i=b(r);i!==r&&(s(t)||(t[n]=i),r=i)}e[r]=!0}return e}function r(e){var t={},n=void 0;for(n in e)p(a,e,[n])&&(t[n]=e[n]);return t}function i(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 a=Object.hasOwnProperty,o=Object.setPrototypeOf,s=Object.isFrozen,c=Object.keys,l=Object.freeze,u=Object.seal,d="undefined"!=typeof Reflect&&Reflect,p=d.apply,f=d.construct;p||(p=function(e,t,n){return e.apply(t,n)}),l||(l=function(e){return e}),u||(u=function(e){return e}),f||(f=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 _=e(Array.prototype.forEach),m=e(Array.prototype.indexOf),g=e(Array.prototype.join),h=e(Array.prototype.pop),y=e(Array.prototype.push),v=e(Array.prototype.slice),b=e(String.prototype.toLowerCase),x=e(String.prototype.match),k=e(String.prototype.replace),S=e(String.prototype.indexOf),T=e(String.prototype.trim),C=e(RegExp.prototype.test),E=t(RegExp),D=t(TypeError),A=l(["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"]),N=l(["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"]),w=l(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),I=l(["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"]),P=l(["#text"]),O=l(["accept","action","align","alt","autocomplete","background","bgcolor","border","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","coords","crossorigin","datetime","default","dir","disabled","download","enctype","face","for","headers","height","hidden","high","href","hreflang","id","integrity","ismap","label","lang","list","loop","low","max","maxlength","media","method","min","minlength","multiple","name","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","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","type","usemap","valign","value","width","xmlns"]),F=l(["accent-height","accumulate","additive","alignment-baseline","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","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","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","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"]),L=l(["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"]),R=l(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),M=u(/\{\{[\s\S]*|[\s\S]*\}\}/gm),U=u(/<%[\s\S]*|[\s\S]*%>/gm),B=u(/^data-[\-\w.\u00B7-\uFFFF]/),$=u(/^aria-[\-\w]+$/),j=u(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),K=u(/^(?:\w+script|data):/i),z=u(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205f\u3000]/g),J="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},q=function(){return"undefined"==typeof window?null:window},V=function(e,t){if("object"!==(void 0===e?"undefined":J(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 r="dompurify"+(n?"#"+n:"");try{return e.createPolicy(r,{createHTML:function(e){return e}})}catch(e){return console.warn("TrustedTypes policy "+r+" could not be created."),null}};return function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:q(),a=function(t){return e(t)};if(a.version="2.0.8",a.removed=[],!t||!t.document||9!==t.document.nodeType)return a.isSupported=!1,a;var o=t.document,s=!1,u=!1,d=t.document,p=t.DocumentFragment,f=t.HTMLTemplateElement,H=t.Node,G=t.NodeFilter,W=t.NamedNodeMap,Q=void 0===W?t.NamedNodeMap||t.MozNamedAttrMap:W,Y=t.Text,X=t.Comment,Z=t.DOMParser,ee=t.trustedTypes;if("function"==typeof f){var te=d.createElement("template");te.content&&te.content.ownerDocument&&(d=te.content.ownerDocument)}var ne=V(ee,o),re=ne?ne.createHTML(""):"",ie=d,ae=ie.implementation,oe=ie.createNodeIterator,se=ie.getElementsByTagName,ce=ie.createDocumentFragment,le=o.importNode,ue={};a.isSupported=ae&&void 0!==ae.createHTMLDocument&&9!==d.documentMode;var de=M,pe=U,fe=B,_e=$,me=K,ge=z,he=j,ye=null,ve=n({},[].concat(i(A),i(N),i(w),i(I),i(P))),be=null,xe=n({},[].concat(i(O),i(F),i(L),i(R))),ke=null,Se=null,Te=!0,Ce=!0,Ee=!1,De=!1,Ae=!1,Ne=!1,we=!1,Ie=!1,Pe=!1,Oe=!1,Fe=!1,Le=!1,Re=!0,Me=!0,Ue=!1,Be={},$e=n({},["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=n({},["audio","video","img","source","image"]),Ke=null,ze=n({},["alt","class","for","id","label","name","pattern","placeholder","summary","title","value","style","xmlns"]),Je=null,qe=d.createElement("form"),Ve=function(e){Je&&Je===e||(e&&"object"===(void 0===e?"undefined":J(e))||(e={}),ye="ALLOWED_TAGS"in e?n({},e.ALLOWED_TAGS):ve,be="ALLOWED_ATTR"in e?n({},e.ALLOWED_ATTR):xe,Ke="ADD_URI_SAFE_ATTR"in e?n(r(ze),e.ADD_URI_SAFE_ATTR):ze,ke="FORBID_TAGS"in e?n({},e.FORBID_TAGS):{},Se="FORBID_ATTR"in e?n({},e.FORBID_ATTR):{},Be="USE_PROFILES"in e&&e.USE_PROFILES,Te=!1!==e.ALLOW_ARIA_ATTR,Ce=!1!==e.ALLOW_DATA_ATTR,Ee=e.ALLOW_UNKNOWN_PROTOCOLS||!1,De=e.SAFE_FOR_JQUERY||!1,Ae=e.SAFE_FOR_TEMPLATES||!1,Ne=e.WHOLE_DOCUMENT||!1,Pe=e.RETURN_DOM||!1,Oe=e.RETURN_DOM_FRAGMENT||!1,Fe=e.RETURN_DOM_IMPORT||!1,Le=e.RETURN_TRUSTED_TYPE||!1,Ie=e.FORCE_BODY||!1,Re=!1!==e.SANITIZE_DOM,Me=!1!==e.KEEP_CONTENT,Ue=e.IN_PLACE||!1,he=e.ALLOWED_URI_REGEXP||he,Ae&&(Ce=!1),Oe&&(Pe=!0),Be&&(ye=n({},[].concat(i(P))),be=[],!0===Be.html&&(n(ye,A),n(be,O)),!0===Be.svg&&(n(ye,N),n(be,F),n(be,R)),!0===Be.svgFilters&&(n(ye,w),n(be,F),n(be,R)),!0===Be.mathMl&&(n(ye,I),n(be,L),n(be,R))),e.ADD_TAGS&&(ye===ve&&(ye=r(ye)),n(ye,e.ADD_TAGS)),e.ADD_ATTR&&(be===xe&&(be=r(be)),n(be,e.ADD_ATTR)),e.ADD_URI_SAFE_ATTR&&n(Ke,e.ADD_URI_SAFE_ATTR),Me&&(ye["#text"]=!0),Ne&&n(ye,["html","head","body"]),ye.table&&(n(ye,["tbody"]),delete ke.tbody),l&&l(e),Je=e)},He=function(e){y(a.removed,{element:e});try{e.parentNode.removeChild(e)}catch(t){e.outerHTML=re}},Ge=function(e,t){try{y(a.removed,{attribute:t.getAttributeNode(e),from:t})}catch(e){y(a.removed,{attribute:null,from:t})}t.removeAttribute(e)},We=function(e){var t=void 0,r=void 0;if(Ie)e="<remove></remove>"+e;else{var i=x(e,/^[\s]+/);r=i&&i[0]}var a=ne?ne.createHTML(e):e;if(s)try{t=(new Z).parseFromString(a,"text/html")}catch(e){}if(u&&n(ke,["title"]),!t||!t.documentElement){var o=(t=ae.createHTMLDocument("")).body;o.parentNode.removeChild(o.parentNode.firstElementChild),o.outerHTML=a}return e&&r&&t.body.insertBefore(d.createTextNode(r),t.body.childNodes[0]||null),se.call(t,Ne?"html":"body")[0]};a.isSupported&&(function(){try{We('<svg><p><textarea><img src="</textarea><img src=x abc=1//">').querySelector("svg img")&&(s=!0)}catch(e){}}(),function(){try{var e=We("<x/><title></title><img>");C(/<\/title/,e.querySelector("title").innerHTML)&&(u=!0)}catch(e){}}());var Qe=function(e){return oe.call(e.ownerDocument||e,e,G.SHOW_ELEMENT|G.SHOW_COMMENT|G.SHOW_TEXT,(function(){return G.FILTER_ACCEPT}),!1)},Ye=function(e){return!(e instanceof Y||e instanceof X||"string"==typeof e.nodeName&&"string"==typeof e.textContent&&"function"==typeof e.removeChild&&e.attributes instanceof Q&&"function"==typeof e.removeAttribute&&"function"==typeof e.setAttribute&&"string"==typeof e.namespaceURI)},Xe=function(e){return"object"===(void 0===H?"undefined":J(H))?e instanceof H:e&&"object"===(void 0===e?"undefined":J(e))&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName},Ze=function(e,t,n){ue[e]&&_(ue[e],(function(e){e.call(a,t,n,Je)}))},et=function(e){var t=void 0;if(Ze("beforeSanitizeElements",e,null),Ye(e))return He(e),!0;var n=b(e.nodeName);if(Ze("uponSanitizeElement",e,{tagName:n,allowedTags:ye}),("svg"===n||"math"===n)&&0!==e.querySelectorAll("p, br").length)return He(e),!0;if(!ye[n]||ke[n]){if(Me&&!$e[n]&&"function"==typeof e.insertAdjacentHTML)try{var r=e.innerHTML;e.insertAdjacentHTML("AfterEnd",ne?ne.createHTML(r):r)}catch(e){}return He(e),!0}return"noscript"===n&&C(/<\/noscript/i,e.innerHTML)||"noembed"===n&&C(/<\/noembed/i,e.innerHTML)?(He(e),!0):(!De||e.firstElementChild||e.content&&e.content.firstElementChild||!C(/</g,e.textContent)||(y(a.removed,{element:e.cloneNode()}),e.innerHTML?e.innerHTML=k(e.innerHTML,/</g,"<"):e.innerHTML=k(e.textContent,/</g,"<")),Ae&&3===e.nodeType&&(t=e.textContent,t=k(t,de," "),t=k(t,pe," "),e.textContent!==t&&(y(a.removed,{element:e.cloneNode()}),e.textContent=t)),Ze("afterSanitizeElements",e,null),!1)},tt=function(e,t,n){if(Re&&("id"===t||"name"===t)&&(n in d||n in qe))return!1;if(Ce&&C(fe,t));else if(Te&&C(_e,t));else{if(!be[t]||Se[t])return!1;if(Ke[t]);else if(C(he,k(n,ge,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==S(n,"data:")||!je[e])if(Ee&&!C(me,k(n,ge,"")));else if(n)return!1}return!0},nt=function(e){var t=void 0,n=void 0,r=void 0,i=void 0,o=void 0;Ze("beforeSanitizeAttributes",e,null);var s=e.attributes;if(s){var l={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:be};for(o=s.length;o--;){var u=t=s[o],d=u.name,p=u.namespaceURI;if(n=T(t.value),r=b(d),l.attrName=r,l.attrValue=n,l.keepAttr=!0,l.forceKeepAttr=void 0,Ze("uponSanitizeAttribute",e,l),n=l.attrValue,!l.forceKeepAttr){if("name"===r&&"IMG"===e.nodeName&&s.id)i=s.id,s=v(s,[]),Ge("id",e),Ge(d,e),m(s,i)>o&&e.setAttribute("id",i.value);else{if("INPUT"===e.nodeName&&"type"===r&&"file"===n&&l.keepAttr&&(be[r]||!Se[r]))continue;"id"===d&&e.setAttribute(d,""),Ge(d,e)}if(l.keepAttr)if(De&&C(/\/>/i,n))Ge(d,e);else if(C(/svg|math/i,e.namespaceURI)&&C(E("</("+g(c($e),"|")+")","i"),n))Ge(d,e);else{Ae&&(n=k(n,de," "),n=k(n,pe," "));var f=e.nodeName.toLowerCase();if(tt(f,r,n))try{p?e.setAttributeNS(p,d,n):e.setAttribute(d,n),h(a.removed)}catch(e){}}}}Ze("afterSanitizeAttributes",e,null)}},rt=function e(t){var n=void 0,r=Qe(t);for(Ze("beforeSanitizeShadowDOM",t,null);n=r.nextNode();)Ze("uponSanitizeShadowNode",n,null),et(n)||(n.content instanceof p&&e(n.content),nt(n));Ze("afterSanitizeShadowDOM",t,null)};return a.sanitize=function(e,n){var r=void 0,i=void 0,s=void 0,c=void 0,l=void 0;if(e||(e="\x3c!--\x3e"),"string"!=typeof e&&!Xe(e)){if("function"!=typeof e.toString)throw D("toString is not a function");if("string"!=typeof(e=e.toString()))throw D("dirty is not a string, aborting")}if(!a.isSupported){if("object"===J(t.toStaticHTML)||"function"==typeof t.toStaticHTML){if("string"==typeof e)return t.toStaticHTML(e);if(Xe(e))return t.toStaticHTML(e.outerHTML)}return e}if(we||Ve(n),a.removed=[],"string"==typeof e&&(Ue=!1),Ue);else if(e instanceof H)1===(i=(r=We("\x3c!--\x3e")).ownerDocument.importNode(e,!0)).nodeType&&"BODY"===i.nodeName||"HTML"===i.nodeName?r=i:r.appendChild(i);else{if(!Pe&&!Ae&&!Ne&&Le&&-1===e.indexOf("<"))return ne?ne.createHTML(e):e;if(!(r=We(e)))return Pe?null:re}r&&Ie&&He(r.firstChild);for(var u=Qe(Ue?e:r);s=u.nextNode();)3===s.nodeType&&s===c||et(s)||(s.content instanceof p&&rt(s.content),nt(s),c=s);if(c=null,Ue)return e;if(Pe){if(Oe)for(l=ce.call(r.ownerDocument);r.firstChild;)l.appendChild(r.firstChild);else l=r;return Fe&&(l=le.call(o,l,!0)),l}var d=Ne?r.outerHTML:r.innerHTML;return Ae&&(d=k(d,de," "),d=k(d,pe," ")),ne&&Le?ne.createHTML(d):d},a.setConfig=function(e){Ve(e),we=!0},a.clearConfig=function(){Je=null,we=!1},a.isValidAttribute=function(e,t,n){Je||Ve({});var r=b(e),i=b(t);return tt(r,i,n)},a.addHook=function(e,t){"function"==typeof t&&(ue[e]=ue[e]||[],y(ue[e],t))},a.removeHook=function(e){ue[e]&&h(ue[e])},a.removeHooks=function(e){ue[e]&&(ue[e]=[])},a.removeAllHooks=function(){ue={}},a}()})),pxt||(pxt={}),function(e){!function(t){const n={},r={};let i=!1;t.addDefaultProperties=function(e){Object.keys(e).forEach((t=>{"string"==typeof e[t]?n[t]=e[t]:r[t]=e[t]}))},t.enable=function(){if(!e.aiTrackException||!e.aiTrackEvent||i)return;i=!0,e.debug("setting up app insights");const t=e.tickEvent;e.tickEvent=function(i,a,o){if(t&&t(i,a,o),(null==o?void 0:o.interactiveConsent)&&e.setInteractiveConsent(!0),a){const t=Object.assign({},n)||{},o=Object.assign({},r)||{};Object.keys(a).forEach((e=>{"string"==typeof a[e]?t[e]=a[e]:"number"==typeof a[e]?o[e]=a[e]:t[e]=JSON.stringify(a[e]||"")})),e.aiTrackEvent(i,t,o)}else e.aiTrackEvent(i)};const a=e.reportException;e.reportException=function(t,n){a&&a(t,n);const r={target:e.appTarget.id,version:e.appTarget.versions.target};n&&e.Util.jsonMergeFrom(r,n),e.aiTrackException(t,"exception",r)};const o=e.reportError;e.reportError=function(t,n,r){o&&o(t,n,r);try{throw n}catch(i){const a={target:e.appTarget.id,version:e.appTarget.versions.target,category:t,message:n};r&&e.Util.jsonMergeFrom(a,r),e.aiTrackException(i,"error",a)}}}}(e.analytics||(e.analytics={}))}(pxt||(pxt={})),pxt||(pxt={}),function(e){!function(e){let t,n,r,i=0,a=!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 s(){t&&(r.gain.setTargetAtTime(0,t.currentTime,.015),i=0)}e.mute=function(e){t&&(a=e,s(),e&&n&&(n.disconnect(),r.disconnect(),n=void 0,r=void 0))},e.stop=s,e.frequency=function(){return i},e.tone=function(e){if(a)return;if(e<0)return;i=e;let s=o();if(s)try{n||(n=s.createOscillator(),n.type="triangle",r=s.createGain(),r.gain.value=0,r.connect(s.destination),n.connect(r),n.start(0)),n.frequency.linearRampToValueAtTime(e,t.currentTime),r.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",r="csrf-token",i="login-state",a="user-state";let o,s=!1;t.DEFAULT_USER_PREFERENCES=()=>({highContrast:!1,language:e.appTarget.appTheme.defaultLocale,reader:"",skillmap:{mapProgress:{},completedTags:{}},email:!1}),t.client=function(){return o};let c=0,l=0;t.AuthClient=class{constructor(){this.initialUserPreferences_=void 0,this.initialAuthCheck_=void 0,this.prefPatchOps=[],e.Util.assert(!o),o=this}async initAsync(){try{this.state$=await e.storage.shared.getAsync(n,a)}catch(e){}this.state$||(this.state$={}),this.setUserProfileAsync(this.state$.profile),this.setUserPreferencesAsync(this.state$.preferences)}async loginAsync(t,r,a){var o;if(!p()||!function(e){return d().filter((t=>t.id===e)).length>0}(t))return;a=null!=a?a:u;const s=this.getState();s.profile||await this.authCheckAsync();if((null===(o=s.profile)||void 0===o?void 0:o.idp)===t)return void e.debug(`loginAsync: Already signed into ${t}.`);this.clearState();const c={key:(Math.PI*Math.random()).toString(36).slice(2),callbackState:a,callbackPathname:window.location.pathname,idp:t};await e.storage.shared.setAsync(n,i,c);const l=e.Util.stringifyQueryString("/api/auth/login",{response_type:"token",provider:t,persistent:r,redirect_uri:`${window.location.origin}${window.location.pathname}?authcallback=1&state=${c.key}`}),f=await this.apiAsync(l);f.success?(e.tickEvent("auth.login.start",{provider:t}),window.location.href=f.resp.loginUrl):await this.onSignInFailed()}async logoutAsync(t){if(!p())return;e.tickEvent("auth.logout"),await this.apiAsync("/api/auth/logout"),await e.storage.shared.delAsync(n,r),this.clearState();const i=t?t.startsWith("#")?t:`#${t}`:"";e.BrowserUtils.hasWindow()&&(window.location.href=`${window.location.origin}${window.location.pathname}${i}`,location.reload())}async deleteProfileAsync(){var t;if(!await this.loggedInAsync())return;const i=null===(t=this.getState().profile)||void 0===t?void 0:t.id,a=await this.apiAsync("/api/user",null,"DELETE");if(a.err)await this.onApiError(a.err);else try{await e.storage.shared.delAsync(n,r);try{await this.onProfileDeleted(i)}catch(t){e.tickEvent("auth.profile.cloudToLocalFailed")}this.clearState()}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=this.getState();return Object.assign({},e.profile)}async userPreferencesAsync(){const e=this.getState();return Object.assign({},e.preferences)}async authCheckAsync(){var t;if(!p())return;if(!await e.storage.shared.getAsync(n,r))return;const i=this.getState();return(null===(t=i.profile)||void 0===t?void 0:t.id)?this.initialAuthCheck_||(this.initialAuthCheck_=Promise.resolve(i.profile)):this.initialAuthCheck_||(this.initialAuthCheck_=this.fetchUserAsync()),this.initialAuthCheck_}async loggedInAsync(){return await this.authCheckAsync(),this.hasUserId()}async updateUserProfileAsync(e){if(!await this.loggedInAsync())return!1;const t=this.getState(),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(t,n=!1){t=(t=Array.isArray(t)?t:[t]).filter((e=>!!e));const r=await this.userPreferencesAsync();if(!t.length)return{success:!0,res:r};if(ts.pxtc.jsonPatch.patchInPlace(r,t),await this.setUserPreferencesAsync(r),!await this.loggedInAsync())return{success:!0,res:r};t.forEach(((e,n)=>{this.prefPatchOps.some(((r,i)=>!!ts.pxtc.jsonPatch.opsAreEqual(r,e)&&(this.prefPatchOps[i]=e,t[n]=null,!0)))})),t.filter((e=>!!e)).forEach((e=>this.prefPatchOps.push(e))),clearTimeout(c);const i=async()=>{l=0;const t=this.prefPatchOps;this.prefPatchOps=[];const n=await this.apiAsync("/api/user/preferences",t,"PATCH");return n.success?(e.debug("Updating local user preferences w/ cloud data after result of POST"),this.setUserPreferencesAsync(n.resp)):e.reportError("identity","update preferences failed",n),{success:n.success,res:n.resp}};return n?await i():(l||(l=e.U.now()),1e4<e.U.now()-l?await i():(c=setTimeout(i,1e3),{success:!1,res:void 0}))}hasUserId(){var e;if(!p())return!1;return!!(null===(e=this.getState().profile)||void 0===e?void 0:e.id)}async fetchUserAsync(){var e;if(!p())return;const t=this.getState();if(null===(e=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=this.hasUserId();this.transformUserProfile(e);const n=this.hasUserId();this.onUserProfileChanged(),n&&!t?await this.onSignedIn():!n&&t&&await this.onSignedOut()}async setUserPreferencesAsync(e){var n;const r=null!==(n=this.getState().preferences)&&void 0!==n?n:t.DEFAULT_USER_PREFERENCES(),i=ts.pxtc.jsonPatch.diff(r,e);this.transformUserPreferences(Object.assign(Object.assign({},r),e)),await this.onUserPreferencesChanged(i)}async fetchUserPreferencesAsync(){if(!await this.loggedInAsync())return;const e=this.getState(),t=await this.apiAsync("/api/user/preferences");return t.success&&t.resp?(this.setUserPreferencesAsync(t.resp),e.preferences):void 0}transformUserProfile(e){this.state$=Object.assign(Object.assign({},this.state$),{profile:Object.assign({},e)}),this.saveState()}transformUserPreferences(e){this.state$=Object.assign(Object.assign({},this.state$),{preferences:Object.assign({},e)}),this.saveState()}getState(){return this.state$}saveState(){e.storage.shared.setAsync(n,a,this.state$).then((()=>{}))}clearState(){this.state$={},e.storage.shared.delAsync(n,a).then((()=>this.onStateCleared()))}async apiAsync(t,i,a){var o;const s={},c=await e.storage.shared.getAsync(n,r);return c&&(s.authorization=`mkcd ${c}`),s["x-pxt-target"]=null===(o=e.appTarget)||void 0===o?void 0:o.id,t=e.BrowserUtils.isLocalHostDev()?`https://staging.pxt.io${t}`:t,e.Util.requestAsync({url:t,headers:s,data:i,method:a||(i?"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 this.logoutAsync(),{statusCode:e.statusCode,err:e,resp:null,success:!1})))}};const u={hash:"",params:{}};function d(){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 p(){return!s&&!e.BrowserUtils.isPxtElectron()&&d().length>0}function f(e,t){return e.id===t.id&&e.sourceURL===t.sourceURL}t.loginCallbackAsync=async function(t){let a,o=Object.assign({},u);do{if(a=await e.storage.shared.getAsync(n,i),!a)return void e.debug("Auth state not found in storge.");await e.storage.shared.delAsync(n,i);const s=t.state;if(!s||a.key!==s)return void e.debug("Failed to get auth state for key");o=Object.assign(Object.assign({},u),a.callbackState);const c=t.error;if(c){const n=t.error_description;e.tickEvent("auth.login.error",{error:c,provider:a.idp}),e.log(`Auth failed: ${c}:${n}`),o=Object.assign({},u);break}const l=t.token;if(!l){e.debug("Missing authToken in auth callback.");break}await e.storage.shared.setAsync(n,r,l),e.tickEvent("auth.login.success",{provider:a.idp})}while(0);const s=o.hash.startsWith("#")?o.hash:`#${o.hash}`,c=e.Util.stringifyQueryString("",o.params),l=`${a.callbackPathname.startsWith("/")?a.callbackPathname:`/${a.callbackPathname}`}${s}${c}`;window.location.href=l},t.identityProviders=d,t.identityProvider=function(e){return d().filter((t=>t.id===e)).shift()},t.hasIdentity=p,t.enableAuth=function(e=!0){s=!e},t.userName=function(e){var t,n,r,i;return null!==(i=null!==(n=null===(t=null==e?void 0:e.idp)||void 0===t?void 0:t.displayName)&&void 0!==n?n:null===(r=null==e?void 0:e.idp)||void 0===r?void 0:r.username)&&void 0!==i?i:"??"},t.userInitials=function(t){const n=e.auth.userName(t);return ts.pxtc.Util.initials(n)},t.generateUserProfilePicDataUrl=function(t){var n,r;if(null===(r=null===(n=null==t?void 0:t.idp)||void 0===n?void 0:n.picture)||void 0===r?void 0:r.encoded){const n=window.URL||window.webkitURL;try{const r=e.Util.stringToUint8Array(atob(t.idp.picture.encoded)),i=new Blob([r],{type:t.idp.picture.mimeType});t.idp.picture.dataUrl=n.createObjectURL(i)}catch(e){}}},t.badgeEquals=f,t.hasBadge=function(e,t){return e.badges.some((e=>f(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",r={},i={},a=!1;function o(){return n}function s(e){const t=/^(\w{2})-(\w{2}$)/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 c(t,n){return 0==n.length?t:t.replace(/\{([0-9]+)(\:[^\}]+)?\}/g,(function(t,r,i){let a=n[parseInt(r)],o="",s=/^:f(\d*)\.(\d+)/.exec(i);if(s){let e=parseInt(s[2]),t=parseInt(s[1])||0,n=/^0/.test(s[1])?"0":" ",r=a.toFixed(e);if(t>0&&e>0&&(t+=e+1),t>0)for(;r.length<t;)r=n+r;o=r}else o=":x"==i?"0x"+a.toString(16):void 0===a?"(undef)":null===a?"(null)":a.toString?a.toString():a+"";return":a"==i?/^\s*[euioah]/.test(o.toLowerCase())?o="an "+o:/^\s*[bcdfgjklmnpqrstvwxz]/.test(o.toLowerCase())&&(o="a "+o):":s"==i?o=1==a?"":"s":":q"==i?o=e.htmlEscape(o):":jq"==i?o=e.jsStringQuote(o):":uri"==i?o=encodeURIComponent(o).replace(/'/g,"%27").replace(/"/g,"%22"):":url"==i?o=encodeURI(o).replace(/'/g,"%27").replace(/"/g,"%22"):":%"==i&&(o=(100*a).toFixed(1).toString()+"%"),o}))}e.enableLiveLocalizationUpdates=function(){a=!0},e.liveLocalizationEnabled=function(){return a},e.localeInfo=function(){return`${a?"live-":""}${o()}`},e.userLanguage=o,e.normalizeLanguageCode=s,e.setUserLanguage=function(e){n=s(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 r[e]||e},e.getLocalizedStrings=function(){return r},e.setLocalizedStrings=function(e){r=e},e.translationsCache=function(){return i},e.fmt_va=c,e.fmt=function(e,...t){return c(e,t)};const l={};e.dumpLocStats=function(){const e={};Object.keys(l).sort(((e,t)=>l[t]-l[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;l[t]=(l[t]||0)+1;let r=e._localize(t);return r=r.replace(/^\{(id|loc):[^\}]+\}/g,""),c(r,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 r=0;r<t.length;r++)if(null!=e(t[r],n[r]))return"Expected array value "+t[r]+" got "+n[r];return null}let r=Object.keys(t),i=Object.keys(t);if(r.length!=i.length)return"Expected "+r.length+" keys, got "+i.length;for(let i=0;i<r.length;i++){if(!Object.prototype.hasOwnProperty.call(n,r[i]))return"Missing key "+r[i];if(null!=e(t[r[i]],n[r[i]]))return"Expected value of "+r[i]+" to be "+t[r[i]]+", got "+n[r[i]]}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,ts,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,ts,pxt,pxt,pxt,pxt,ts,pxt,ts,pxtmelody,pxtmelody,pxtmelody,pxt,pxt,ts,ts,ts,ts,ts,ts,ts,ts,ts,ts,ts,pxt,pxt,ts,ts,ts,ts,ts,ts,ts,ts,ts,ts,ts,pxt,pxt,pxt,pxt,pxt,pxt,pxt;!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 r(e,t){if(t)for(let n=0;n<t.length;++n)e.push(t[n])}function i(e){let t=[];for(let n=0;n<e.length;++n)r(t,e[n]);return t}function a(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function o(e,t,n,r,i){void 0===r&&(r=0),void 0===i&&(i=n.length-r);for(let a=0;a<i;++a)e[t+a]=n[r+a]}function s(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 r=0;r<e.length;r++){let i=e[r];n=t[n^i]}return n}return e?function(e,t){let r;const i=new Uint8Array(e.length);for(let t=0;t<e.length;++t){const n=e.charCodeAt(t);i[t]=255&n}let a=0;for(let e=0;e<t;++e)r=n(i),a|=r<<8*e,i[0]=(i[0]+1)%255;return a}(e,2):0},n.bufferSerial=function(e,t="",n="?",r=255){for(let i=0;i<t.length;++i){const a=t[i];if(e[n]=(e[n]||"")+a,"\n"===a||e[n].length>r){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 r=new FileReader;r.onload=()=>t(r.result),r.onerror=e=>n(e),r.readAsDataURL(e)})):Promise.resolve(void 0)},n.fileReadAsBufferAsync=function(e){return e?new Promise(((t,n)=>{let r=new FileReader;r.onerror=e=>t(null),r.onload=e=>t(new Uint8Array(r.result)),r.readAsArrayBuffer(e)})):Promise.resolve(null)},n.fileReadAsTextAsync=function(e){return e?new Promise(((t,n)=>{let r=new FileReader;r.onerror=e=>t(null),r.onload=e=>t(r.result),r.readAsText(e)})):Promise.resolve(null)},n.repeatMap=function(e,t){e=e||0;let n=[];for(let r=0;r<e;++r)n.push(t(r));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 r=0;r<e.length;r++)if(!n(e[r],t[r]))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((r=>n[r]=t(r,e[r]))),n},n.values=function(e){return Object.keys(e||{}).map((t=>e[t]))},n.pushRange=r,n.concatArrayLike=function(e){return i(e)},n.concat=i,n.memcpy=o,n.uint8ArrayConcat=function(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)o(n,r,t),r+=t.length;return n},n.jsonTryParse=function(e){try{return JSON.parse(e)}catch(e){return}},n.jsonMergeFrom=function e(t,r){r&&Object.keys(r).forEach((i=>{a(t[i])&&a(r[i])?e(t[i],r[i]):t[i]=n.clone(r[i])}))},n.jsonCopyFrom=function(e,t){let r=n.clone(t);for(let n of Object.keys(t))e[n]=r[n]},n.jsonFlatten=function(e){let t={},r=(e,i)=>{if(null!==i&&"object"==typeof i){n.assert(!Array.isArray(i)),e&&(e+=".");for(let t of Object.keys(i))r(e+t,i[t])}else t[e]=i};return r("",e),t},n.jsonUnFlatten=function(e){let t={};for(let n of Object.keys(e)){let r=t,i=n.split(".");for(let t=0;t<i.length;++t){let a=i[t];t==i.length-1?r[a]=e[n]:("object"!=typeof r[a]&&(r[a]={}),r=r[a])}}return t},n.strcmp=s,n.stringMapEq=function(e,t){let n=Object.keys(e),r=Object.keys(t);if(n.length!=r.length)return!1;for(let r of n){if(!t.hasOwnProperty(r))return!1;if(e[r]!==t[r])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 r=t=>e[t]!=n[t],i=n=>e[n]!=t[n];let a="",o=0;for(;o<e.length;){let t=r(o),n=o;for(;n<e.length;){if(t&&i(n)){if(n-o>2){n--;break}t=!1}if(!t&&r(n))break;n++}a&&(a+="_"),a+=e.slice(o,n),o=n}return a.toUpperCase()===a?a:a.toLowerCase()},n.sortObjectFields=function(e){let t=Object.keys(e);t.sort(s);let n={};return t.forEach((t=>n[t]=e[t])),n},n.chopArray=function(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n},n.unique=function(e,t){let n=[],r={};return e.forEach((e=>{let i=t(e);r.hasOwnProperty(i)||(r[i]=null,n.push(e))})),n},n.groupBy=function(e,t){let n={};return e.forEach((e=>{let r=t(e);n.hasOwnProperty(r)||(n[r]=[]),n[r].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.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 c=Promise.resolve();async function l(e,t,n){let r=0;const i=[],a=[];for(let o=0;o<e;o++){const e=(async()=>{for(;r<t.length;){const e=r++,i=t[e];a[e]=await n(i)}})();i.push(e)}try{await Promise.all(i)}catch(e){throw r=t.length,e}return a}function u(e,t){const n={};return r=>{const i=e(r);return n.hasOwnProperty(i)?n[i]:n[i]=t(r)}}n.nextTick=function(e){c.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 l(1,e,t)},n.promisePoolAsync=l,n.memoizeString=function(e){return u((e=>e),e)},n.promiseTimeout=async function(e,t,n){let r,i;const a=new Promise(((t,a)=>{i=t,r=setTimeout((()=>{i=void 0,clearTimeout(r),a(n||`Promise timed out after ${e}ms`)}),e)}));return Promise.race([t,a]).then((e=>(i&&(clearTimeout(r),i()),e)))},n.defer=function(){let e,t,n,r=!1;return{resolve:function(n){r?pxt.debug("Deferred promise already resolved"):(t?t(n):e=e||new Promise((function(e){e(n)})),r=!0)},reject:function(t){r?pxt.debug("Deferred promise already resolved"):(n?n(t):e=e||new Promise((function(e,n){n(t)})),r=!0)},promise:new Promise((function(r,i){e?r(e):(t=r,n=i)}))}},n.memoize=u,n.debounce=function(e,t,n){let r;return function(){let i=this,a=arguments,o=function(){r=null,n||e.apply(i,a)},s=n&&!r;return clearTimeout(r),r=setTimeout(o,t),s&&e.apply(i,a),r}};function d(e){return e&&(e=e.replace(/\\/g,"/")),e}function p(e){return n.httpRequestCoreAsync(e).then((r=>{const i=r.statusCode;if((e.successCodes||[304,200,201,202]).indexOf(i)<0&&!e.allowHttpErrors){const t=n.lf("Bad HTTP status code: {0} at {1}; message: {2}",r.statusCode,e.url,(r.text||"").slice(0,500)),i=new Error(t);return i.statusCode=r.statusCode,Promise.reject(i)}return r.text&&/application\/json/.test(r.headers["content-type"])&&(r.json=t.U.jsonTryParse(r.text)),r}))}function f(e,t){let n="";if(!e)return n;for(let r=0;r<e.length;++r){let i=e.charCodeAt(r);if(i<=127)n+=e.charAt(r);else if(i<=2047)n+=String.fromCharCode(192|i>>6,128|63&i);else{if(!t&&55296<=i&&i<=56319){let t=e.charCodeAt(++r);isNaN(t)||(i=65536+(i-55296<<10)+(t-56320))}n+=i<=65535?String.fromCharCode(224|i>>12,128|i>>6&63,128|63&i):String.fromCharCode(240|i>>18,128|i>>12&63,128|i>>6&63,128|63&i)}}return n}n.AdaptiveDebouncer=class{constructor(e,t=300,n=2e3,r=2){this.func=e,this.minDelay=t,this.maxDelay=n,this.slowdownFactor=r,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 r;return function(){let i=this,a=arguments,o=function(){r=null,n||e.apply(i,a)},s=n&&!r;r||(r=setTimeout(o,t)),s&&e.apply(i,a)}},n.randomPermute=function(e){for(let t=0;t<e.length;++t){let n=m()%e.length,r=e[t];e[t]=e[n],e[n]=r}},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=p,n.httpGetTextAsync=function(e){return p({url:e}).then((e=>e.text))},n.httpGetJsonAsync=function(e){return p({url:e}).then((e=>e.json))},n.httpPostJsonAsync=function(e,t){return p({url:e,data:t||{}}).then((e=>e.json))},n.stringToUint8Array=function(e){let t=e.length,n=new Uint8Array(t);for(let r=0;r<t;++r)n[r]=255&e.charCodeAt(r);return n},n.uint8ArrayToString=function(e){let t=e.length,n="";for(let r=0;r<t;++r)n+=String.fromCharCode(e[r]);return n},n.fromUTF8=function(e){if(!e)return"";let t="";for(let n=0;n<e.length;++n){let r=255&e.charCodeAt(n);t+=37==r||r>127?"%"+r.toString(16):e.charAt(n)}return decodeURIComponent(t)},n.toUTF8=f,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,r)=>{let i=this.promises[e];i||(i=this.promises[e]=[]),i.push((()=>t().finally((()=>{i.shift(),0==i.length?delete this.promises[e]:i[0]()})).then(n,r))),1==i.length&&i[0]()}))}};function _(){return Date.now()}function m(){let e=new Uint8Array(4);return n.getRandomBuf(e),new Uint32Array(e.buffer)[0]}function g(e,t,n,r){function i(i){pxt.debug(`downloading translations for ${e} ${t} ${n||""}`);let a=pxt.BrowserUtils.isLocalHost()||pxt.webConfig.isStatic?"https://makecode.com/api/":"",o=`${a}translations?lang=${encodeURIComponent(e)}&filename=${encodeURIComponent(t)}&approved=true`;n&&(o+="&branch="+encodeURIComponent(n));const s={};return r&&!pxt.Cloud.useCdnApi()&&(s["If-None-Match"]=r),(a?p:pxt.Cloud.apiRequestWithCdnAsync)({url:o,headers:s}).then((a=>304==a.statusCode||200==a.statusCode?(r=a.headers.etag||"",pxt.BrowserUtils.translationDbAsync().then((o=>o.setAsync(e,t,n,r,a.json||i))).then((()=>a.json||i))):a.json),(e=>{console.log(`failed to load translations from ${o}`)}))}return pxt.BrowserUtils.translationDbAsync().then((r=>r.getAsync(e,t,n))).then((e=>{if(e){r=e.etag;return(Date.now()-e.time)/1e3>300&&i(e.strings),e.strings}return i()}))}function h(e){let[t,r]=n.normalizeLanguageCode(e),i=pxt.appTarget.appTheme;if(i&&i.availableLocales){if(i.availableLocales.indexOf(t)>-1)return!0;if(r&&i.availableLocales.indexOf(r)>-1)return!0}return!1}let y;function v(e,r,i,a,o,s,c){if(c=c||y.Editor,"en-US"===(i=n.normalizeLanguageCode(i)[0])||"en"===i)return Promise.resolve(void 0);let l,u,d=`${i}/${s}/${c}`;if(n.translationsCache()[d])return Promise.resolve(n.translationsCache()[d]);switch(c){case y.Editor:l=[{branch:a,staticName:"strings.json",path:"strings.json"},{branch:o,staticName:"target-strings.json",path:e+"/target-strings.json"}];break;case y.Sim:l=[{branch:o,staticName:"sim-strings.json",path:e+"/sim-strings.json"}];break;case y.Apis:l=[{branch:o,staticName:"bundled-strings.json",path:e+"/bundled-strings.json"}];break;case y.SkillMap:l=[{branch:o,staticName:"skillmap-strings.json",path:"/skillmap-strings.json"}]}function p(e){e&&(u||(u={}),Object.keys(e).filter((t=>!!e[t])).forEach((t=>u[t]=e[t])))}if(s){let s=0;return t.U.promiseMapAllSeries(l,(e=>g(i,e.path,e.branch).then(p,(e=>{console.log(e.message),++s})))).then((()=>(s&&(n.translationsCache()[d]=u),s!==l.length&&u?Promise.resolve(u):(pxt.tickEvent("translations.livetranslationsfailed"),v(e,r,i,a,o,!1,c)))))}return Promise.all(l.map((e=>n.httpGetJsonAsync(`${r}locales/${i}/${e.staticName}`).catch((e=>{}))))).then((e=>{let t={};e.forEach((e=>pxt.Util.jsonMergeFrom(t,e))),Object.keys(t).length&&(u=t,n.translationsCache()[d]=u)}),(e=>{console.error("failed to load localizations")})).then((()=>u))}function b(e){const t={};for(const n of Object.keys(e))t[n]=x(e[n]);return t}function x(e){var t;return{attributes:Object.assign({},e.attributes),parameters:null===(t=e.parameters)||void 0===t?void 0:t.map(k),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 k(e){var n,r;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(S),handlerParameters:null===(r=e.handlerParameters)||void 0===r?void 0:r.map(S),options:e.options?t.U.clone(e.options):void 0,isEnum:e.isEnum}}function S(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,r)=>{let i=e=>{e instanceof Error?r(e):n(e)};this.waiting.push(i),e>0&&t.U.delay(e).then((()=>{let e=this.waiting.indexOf(i);e>=0&&(this.waiting.splice(e,1),r(new Error("Timeout")))}))}))}},n.now=_,n.nowSeconds=function(){return Math.round(_()/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:"български"},bn:{englishName:"Bengali",localizedName:"বাংলা"},ca:{englishName:"Catalan",localizedName:"Català"},cs:{englishName:"Czech",localizedName:"Čeština"},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"},fr:{englishName:"French",localizedName:"Français"},"fr-CA":{englishName:"French (Canada)",localizedName:"Français (Canada)"},"gu-IN":{englishName:"Gujarati",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:"日本語"},kab:{englishName:"Kabyle",localizedName:"شئعم"},ko:{englishName:"Korean",localizedName:"한국어"},kmr:{englishName:"Kurmanji (Kurdish)",localizedName:"کورمانجی"},kn:{englishName:"Kannada",localizedName:"ಕನ್ನಡ"},lt:{englishName:"Lithuanian",localizedName:"Lietuvių"},lv:{englishName:"Latvian",localizedName:"Latviešu"},"ml-IN":{englishName:"Malayalam",localizedName:"മലയാളം"},mr:{englishName:"Marathi",localizedName:"मराठी"},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"},"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:"Русский"},"si-LK":{englishName:"Sinhala (Sri Lanka)",localizedName:"සිංහල (ශ්රී ලංකා)"},sk:{englishName:"Slovak",localizedName:"Slovenčina"},sl:{englishName:"Slovenian",localizedName:"Slovenski"},sr:{englishName:"Serbian",localizedName:"Srpski"},su:{englishName:"Sundanese",localizedName:"ᮘᮞ ᮞᮥᮔ᮪ᮓ"},"sv-SE":{englishName:"Swedish (Sweden)",localizedName:"Svenska (Sverige)"},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=h,n.updateLocalizationAsync=function(t){const{targetId:r,baseUrl:i,pxtBranch:a,targetBranch:o,force:s}=t;let{code:c}=t;if(c=n.normalizeLanguageCode(c)[0],"en-US"===c&&(c="en"),c===n.userLanguage()||!h(c)&&!s)return pxt.debug(`loc: ${c} (using built-in)`),Promise.resolve();pxt.debug(`loc: ${c}`);const l=pxt.Util.liveLocalizationEnabled();return v(r,i,c,a,o,l,e.pxtc.Util.TranslationsKind.Editor).then((t=>(t&&(n.setUserLanguage(c),n.setLocalizedStrings(t)),e.pxtc.Util.downloadTranslationsAsync(r,i,c,a,o,l,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.range=function(e){let t=[];for(let n=0;n<e;++n)t.push(n);return t},n.multipartPostAsync=function(e,t={},r=null,i=null){const a="--------------------------0461489f461126c5";let o="";Object.keys(t).forEach((e=>{return n=e,r=t[e],o+=a+"\r\n",o+='Content-Disposition: form-data; name="'+n+'"\r\n\r\n',void(o+=r+"\r\n");var n,r})),r&&function(e,t){const n=e.split("/").reverse()[0];o+=a+"\r\n",o+='Content-Disposition: form-data; name="files['+e+']"; filename="'+n+'"\r\n',o+="\r\n",o+=t+"\r\n"}(r,i),o+=a+"--\r\n";const s={url:e,method:"POST",headers:{"Content-Type":"multipart/form-data; boundary="+a.slice(2)},data:o};return n.httpRequestCoreAsync(s)},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(f(e))}`)},n.imageMagic=1496611453,n.imageHeaderSize=36,n.encodeBlobAsync=function(e,t){const r=n.imageHeaderSize+t.length,i=3*(e.width*e.height-1);let a=1;for(;a<4&&!(i*a>=8*r);)a++;let o=i*a>>3,s=r-o,c=0,l=e.width*e.height*4;if(s>0){const t=3*e.width;c=Math.ceil(s/t);const n=document.createElement("canvas");n.width=e.width,n.height=e.height+c;n.getContext("2d").drawImage(e,0,0),e=n}let u=pxt.HF2.encodeU32LE([n.imageMagic,t.length,c,0,0,0,0,0,0]);function d(e,t,n,r){let i=0,a=0,o=r[a++];const s=(1<<n)-1;let c=!0;for(;c;){let l=o>>i&s,u=8-i;if(u<=n){if(a>=r.length){if(0==u)break;c=!1}o=r[a++],l|=o<<u&s,i=n-u}else i+=n;e[t]=255&(e[t]&~s|l),3==(3&++t)&&(e[t++]=255)}return t}pxt.Util.assert(u.length==n.imageHeaderSize);const p=e.getContext("2d"),f=p.getImageData(0,0,e.width,e.height);d(f.data,0,1,[a]);let _=4;if(_=d(f.data,_,a,u),pxt.Util.assert(0==(3&_)),0==c)_=d(f.data,_,a,t);else{let e=o-u.length;_=d(f.data,_,a,t.slice(0,e)),_=d(f.data,l,8,t.slice(e))}for(_|=3;_<f.data.length;)f.data[_]=255,_+=4;return p.putImageData(f,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,r=1&t[0]|(1&t[1])<<1|(1&t[2])<<2;if(r>5||0==r)return Promise.reject(new Error(n.lf("Invalid encoded PNG format")));function i(e,n,r){let i=0,a=0,o=0;const s=(1<<n)-1;for(;a<r.length;)o|=(t[e++]&s)<<i,3==(3&e)&&e++,i+=n,i>=8&&(r[a++]=255&o,o>>=8,i-=8);return e}const a=new Uint8Array(pxt.Util.imageHeaderSize);let o=i(4,r,a);const s=pxt.HF2.decodeU32LE(a);if(s[0]!=pxt.Util.imageMagic)return Promise.reject(new Error(n.lf("Invalid magic in encoded PNG")));const c=new Uint8Array(s[1]),l=s[2];if(l>0){const t=(e.height-l)*e.width,n=new Uint8Array((3*(t-1)*r>>3)-pxt.Util.imageHeaderSize);i(o,r,n),c.set(n);const a=new Uint8Array(c.length-n.length);i(4*t,8,a),c.set(a,n.length)}else i(o,r,c);return c}))},n.parseQueryString=function(e){let t={};return e.replace(/\+/g," ").replace(/([^#?&=]+)=([^#?&=]*)/g,((e,n,r)=>(t[decodeURIComponent(n)]=decodeURIComponent(r),""))),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 r=e.bundleddirs;delete e.bundleddirs;const i=e.bundledpkgs;delete e.bundledpkgs;const a=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:b(n.byQName)}}}}if(r&&(o.bundleddirs=[...r]),i){o.bundledpkgs={};for(const e of Object.keys(i))o.bundledpkgs[e]=Object.assign({},i[e])}if(a){o.tutorialInfo={};for(const e of Object.keys(a)){const t=a[e];o.tutorialInfo[e]={hash:t.hash,usedBlocks:Object.assign({},t.usedBlocks),snippetBlocks:Object.assign({},t.snippetBlocks)}}}return o},n.cloneApis=b,n.cloneSymbolInfo=x,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,r)=>{let i,a=!1,o=e.Util.clone(t.headers)||{};i=new XMLHttpRequest,t.responseArrayBuffer&&(i.responseType="arraybuffer"),t.withCredentials&&(i.withCredentials=!0),i.onreadystatechange=()=>{if(!a&&4==i.readyState){a=!0;let e={statusCode:i.status,headers:{},buffer:i.responseBody||i.response,text:t.responseArrayBuffer?void 0:i.responseText};i.getAllResponseHeaders().split(/\r?\n/).forEach((t=>{let n=/^\s*([^:]+): (.*)/.exec(t);n&&(e.headers[n[1].toLowerCase()]=n[2])})),n(e)}};let s,c=t.data,l=t.method||(null==c?"GET":"POST");null==c?s=null:c instanceof Uint8Array?s=c:"object"==typeof c?(s=JSON.stringify(c),o["content-type"]="application/json; charset=utf8"):"string"==typeof c?s=c:e.Util.oops("bad data"),i.open(l,t.url),Object.keys(o).forEach((e=>{i.setRequestHeader(e,o[e])})),null==s?i.send():i.send(s)}))},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 r(e,t){return e>>>t|e<<32-t}function i(t,i){e.Util.assert(8==t.length),e.Util.assert(64==i.length);for(let e=16;e<64;++e){let t=r(i[e-15],7)^r(i[e-15],18)^i[e-15]>>>3,n=r(i[e-2],17)^r(i[e-2],19)^i[e-2]>>>10;i[e]=i[e-16]+t+i[e-7]+n|0}let a=t[0],o=t[1],s=t[2],c=t[3],l=t[4],u=t[5],d=t[6],p=t[7];for(let e=0;e<64;++e){let t=p+(r(l,6)^r(l,11)^r(l,25))+(l&u^~l&d)+n[e]+i[e]|0,f=a&o^a&s^o&s;p=d,d=u,u=l,l=c+t|0,c=s,s=o,o=a,a=t+((r(a,2)^r(a,13)^r(a,22))+f|0)|0}t[0]+=a,t[1]+=o,t[2]+=s,t[3]+=c,t[4]+=l,t[5]+=u,t[6]+=d,t[7]+=p}function a(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 r(e){let r=e.length-63;for(let a=0;a<r;a+=64){for(let t=0;t<16;t++){let r=(t<<2)+a;n[t]=e[r]<<24|e[r+1]<<16|e[r+2]<<8|e[r+3]}i(t,n)}}r(e);let a=64-(e.length+9)%64;64==a&&(a=0);let o=e.length-e.length%64,s=new Uint8Array(e.length-o+1+a+8),c=0;for(;o<e.length;)s[c++]=e[o++];for(s[c++]=128;a-- >0;)s[c++]=0;let l=8*e.length;for(c=s.length;l>0;)s[--c]=255&l,l>>=8;r(s);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=a(e.Util.toUTF8Array(t));return pxt.perf.measureEnd("sha256buffer"),n}t.sha256buffer=a,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]}},r={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 r(e,t){if(!Array.isArray(e))return t;const n=Number.parseFloat(t);return Number.isNaN(n)?t:n}return function e(t,i,a){if(!Object.is(t,i)){i=i||{},t=t||{};for(let e of Object.keys(t))if(!(e in i)){const i=r(t,e);n.remove.push({op:"remove",path:a.concat(i)})}for(const o of Object.keys(i)){const s=t[o],c=i[o],l=r(i,o);l in t?"object"!=typeof s&&"object"!=typeof c&&s!==c||typeof s!=typeof c||Array.isArray(s)!==Array.isArray(c)?n.replace.push({op:"replace",path:a.concat(l),value:c}):e(s,c,a.concat(l)):void 0!==i[l]&&(a.length&&n.add.push({op:"add",path:a,value:Array.isArray(i)?[]:{}}),n.add.push({op:"add",path:a.concat(l),value:c}))}}}(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 i of t){const t=i.path.slice(),a=t.pop();if(null==a)throw new Error("jsonPatch: missing last key");let o=e,s=t.shift();for(;null!=s;){if(!(s in o))throw new Error(`jsonPatch: missing parent element ${s}`);o=o[s],s=t.shift()}if(Array.isArray(o)&&"number"!=typeof a)throw new Error("jsonPatch: expected numeric index for array object");const c=Array.isArray(o)?r:n;"remove"===i.op?c.remove(o,a):"add"!==i.op||a in o?"replace"===i.op&&c.replace(o,a,i.value):c.add(o,a,i.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 r=Array.isArray(e),i=Array.isArray(t);if(r&&i){if(e.length!==t.length)return!1;for(let r=0;r<e.length;++r)if(!n(e[r],t[r]))return!1;return!0}if(r!==i)return!1;const a=Object.keys(e);if(a.length!==Object.keys(t).length)return!1;for(const r of a){if(!t.hasOwnProperty(r))return!1;if(!n(e[r],t[r]))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 r of t){console.log(r.comment);const t=e.pxtc.jsonPatch.diff(r.obja,r.objb);n(t,r.expected)?console.log("succeeded"):(console.error("FAILED"),console.log("got",t),console.log("exp",r.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 r of t){console.log(r.comment),e.pxtc.jsonPatch.patchInPlace(r.obj,r.patches);!n(r.obj,r.expected)||!r.validate||r.validate(r.obj)?console.log("succeeded"):r.expected&&(console.error("FAILED"),console.log("got",r.obj),console.log("exp",r.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,r,i,a={};function o(n,r){/^csv-/.test(n)?e.setAppTargetVariant(n.replace(/^csv-*/,"")):e.appTarget&&(a[n]=r,e.U.jsonCopyFrom(e.appTarget.compile.switches,a),e.U.jsonCopyFrom(t.compile.switches,a))}function s(){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,a),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;n&&n.yottaTarget&&!n.yottaBinary&&(n.yottaBinary="pxt-microbit-app-combined.hex");const r=e.appTarget.appTheme;r&&Object.keys(r).filter((e=>/(logo|hero)$/i.test(e)&&/^@cdnUrl@/.test(r[e]))).forEach((t=>r[t]=e.BrowserUtils.patchCdn(r[t])));const i=e.appTarget.simulator;if(i&&i.boardDefinition&&i.boardDefinition.visual){let t=i.boardDefinition.visual;t.image&&(t.image=e.BrowserUtils.patchCdn(t.image),t.outlineImage&&(t.outlineImage=e.BrowserUtils.patchCdn(t.outlineImage)))}if(Object.keys(e.appTarget.bundledpkgs).forEach((t=>{const n=e.appTarget.bundledpkgs[t],r=JSON.parse(n[e.CONFIG_NAME]);r.icon&&(r.icon=e.BrowserUtils.patchCdn(r.icon)),n[e.CONFIG_NAME]=e.Package.stringifyConfig(r)})),"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((r=>{if(new RegExp(r,"i").exec(n)){let n=t[r];n&&e.U.jsonMergeFrom(e.appTarget,n)}}))}}function c(n=!1){e.perf.measureStart("reloadAppTargetVariant");const r=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))}s(),!n&&e.onAppTargetChanged&&r!=JSON.stringify(e.appTarget)&&e.onAppTargetChanged(),e.perf.measureEnd("reloadAppTargetVariant")}function l(){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 u(){return i||(i=e.Cloud.downloadTargetConfigAsync().then((e=>e||{}),(e=>({})))),i}function d(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||{},s(),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],r=e.lastIndexOf("."),i=t.pyQName,a=n[e]={kind:Math.abs(t.kind||7),qName:e,namespace:e.slice(0,r<0?0:r),name:e.slice(r+1),pyQName:i,pyName:i?i.slice(i.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=a.attributes;o.paramDefl||(o.paramDefl={}),o.callingConvention||(o.callingConvention=0),o.paramHelp||(o.paramHelp={}),o.jsDoc||(o.jsDoc=""),o._name=a.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=r&&r[t];if(n)return n;if(!e.appTarget.simulator||!e.appTarget.simulator.dynamicBoardDefinition)return;r||(r={});const i=e.appTarget.bundledpkgs[t];if(!i)return;if(JSON.parse(i["pxt.json"]).core&&i["board.json"]){const n=JSON.parse(i["board.json"]);if(n&&n.visual&&n.visual.image){let a=n.visual.image;/^pkg:\/\//.test(a)&&(a=i[a.slice(6)]),r[t]=`data:image/svg+xml;base64,${ts.pxtc.encodeBase64(e.Util.toUTF8(a))}`}}return r[t]},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,r){if(console&&(console.error(`${t}: ${n}`),r))try{e.log(JSON.stringify(r,null,2))}catch(e){}},e.localWebConfig=l,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=l())},e.getEmbeddedScript=function(t){return e.U.lookup(e.appTarget.bundledpkgs||{},t)},e.targetConfigAsync=u,e.packagesConfigAsync=function(){return u().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.outputName=d,e.isOutputText=function(e=null){return d(e)==ts.pxtc.BINARY_HEX}}(pxt||(pxt={})),function(e){!function(t){const n="this";let r;function i(){if(r={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:"/blocks/math/random",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:"/blocks/math/random",category:"math",tooltip:e.Util.lf("an integer number")},math_whole_number:{name:e.Util.lf("{id:block}number"),url:"/blocks/math/random",category:"math",tooltip:e.Util.lf("a whole number")},math_number_minmax:{name:e.Util.lf("{id:block}number"),url:"/blocks/math/random",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"),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"),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:{}}},r[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")}},r[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")}},r[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")}},r[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.Util.isTranslationMode()){const t=Blockly.Msg;e.Util.values(r).filter((e=>e.block)).forEach((n=>{const r=Object.keys(n.block);n.translationIds=e.Util.values(n.block),r.forEach((r=>e.crowdin.inContextLoadAsync(n.block[r]).then((e=>{n.block[r]=e,/^[A-Z_]+$/.test(r)&&(t[r]=e)}))))}))}}t.MATH_FUNCTIONS={unary:["sqrt","sin","cos","tan"],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 r=t.replace(/(?:^|[^\\])([%$])\s+/g,"$1");return r!=t&&(n(`block has extra spaces: ${t}`),t=r),r=(t=r).replace(/([%$]\w+)\s*=\s*(\w+)/,"$1=$2"),r!=t&&(n(`block has space between %name and = : ${t}`),t=r),r=r.replace(/\s*\|\s*/g,"|"),r},t.compileInfo=function(e){const r={parameters:[],actualNameToParam:{},definitionNameToParam:{},handlerArgs:[]},i=(1==e.kind||2==e.kind)&&!e.attributes.defaultInstance,a=!!e.attributes._def,o=a?e.attributes._def.parameters.slice(0):void 0,s=a?o.length:e.parameters?e.parameters.length:0,c=t.builtinFunctionInfo[e.qName];a&&e.attributes._expandedDef&&o.push(...e.attributes._expandedDef.parameters);const l={},u=o?o.filter((e=>!e.ref||(l[e.name]=e,!1))):[];if(i&&a&&o.length){const t=l.this||o[0],i=t.name;let a;(!t.shadowBlockId||"variables_get"===t.shadowBlockId)&&(a=t.varName||e.attributes.paramDefl[i]||e.attributes.paramDefl.this),r.thisParameter={actualName:n,definitionName:i,shadowBlockId:t.shadowBlockId,type:e.namespace,defaultValue:a,fieldEditor:d(i,n),fieldOptions:p(i,n),shadowOptions:f(i,n)}}if(e.parameters){let t=i&&!l.this?1:0;e.parameters.forEach(((e,n)=>{let i;if(l[e.name]?i=l[e.name]:t<u.length&&(i=u[t],++t),i||!a){let n;e.options&&e.options.min&&e.options.max&&(n={min:e.options.min.value,max:e.options.max.value});const a=i?i.name:c?c.params[t++]:e.name,l=i&&("variables_get"===i.shadowBlockId||"lists_create_with"==i.shadowBlockId);r.parameters.push({actualName:e.name,type:e.type,defaultValue:l&&i.varName||e.default,definitionName:a,shadowBlockId:i&&i.shadowBlockId,isOptional:!!o&&o.indexOf(i)>=s,fieldEditor:d(a,e.name),fieldOptions:p(a,e.name),shadowOptions:f(a,e.name),range:n})}e.handlerParameters&&e.handlerParameters.forEach((e=>{r.handlerArgs.push({name:e.name,type:e.type,inBlockDef:!!o&&o.some((t=>t.ref&&t.name===e.name))})}))}))}return r.parameters.forEach((e=>{r.actualNameToParam[e.actualName]=e,r.definitionNameToParam[e.definitionName]=e})),r;function d(t,n){return e.attributes.paramFieldEditor&&(e.attributes.paramFieldEditor[t]||e.attributes.paramFieldEditor[n])}function p(t,n){return e.attributes.paramFieldEditorOptions&&(e.attributes.paramFieldEditorOptions[t]||e.attributes.paramFieldEditorOptions[n])}function f(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.reporterTypeForArgType=function(e){let t="argument_reporter_custom";return"boolean"!==e&&"number"!==e&&"string"!==e||(t=`argument_reporter_${e}`),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 r=n[1];return r&&(r=r.trim()),{n:e,ni:t,pre:r,p:n[2]}}))},t.blockDefinitions=function(){return r||i(),r},t.getBlockDefinition=function(e){return r||i(),r[e]}}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(t){function n(){return"undefined"!=typeof navigator}function r(){return n()&&/(Win32|Win64|WOW64)/i.test(navigator.platform)}function i(){return n()&&/mobi/i.test(navigator.userAgent)}function a(){return n()&&/Mac/i.test(navigator.platform)}function o(){return!!navigator&&/Linux/i.test(navigator.platform)}function s(){return n()&&/arm/i.test(navigator.platform)}function c(){return n()&&/Edge/i.test(navigator.userAgent)}function l(){return n()&&/Trident/i.test(navigator.userAgent)}function u(){return!c()&&!l()&&!!navigator&&(/Chrome/i.test(navigator.userAgent)||/Chromium/i.test(navigator.userAgent))}function d(){return!u()&&!c()&&!!navigator&&/(Macintosh|Safari|iPod|iPhone|iPad)/i.test(navigator.userAgent)}function p(){return!d()&&!!navigator&&(/Firefox/i.test(navigator.userAgent)||/Seamonkey/i.test(navigator.userAgent))}function f(){return n()&&/Opera|OPR/i.test(navigator.userAgent)}function _(){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 h(){return"undefined"!=typeof window&&!!window.pxtElectron}function y(){return"undefined"!=typeof window&&!!window.ipcRenderer}function v(){return h()||y()}function b(t){var n;try{return"undefined"!=typeof window&&/^http:\/\/(localhost|127\.0\.0\.1):\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 x(){return"undefined"!=typeof window&&!!window.PointerEvent}function k(){return r()?"windows":a()?"mac":o()&&s()?"rpi":o()?"linux":"unknown"}function S(){return c()?"edge":m()?"epiphany":_()?"midori":f()?"opera":l()?"ie":u()?"chrome":d()?"safari":p()?"firefox":"unknown"}function T(){if(!n())return null;let e=[];return f()&&(e=/(Opera|OPR)\/([0-9\.]+)/i.exec(navigator.userAgent)),m()?e=/Epiphany\/([0-9\.]+)/i.exec(navigator.userAgent):_()?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):c()?/Edge\/([0-9\.]+)/i.exec(navigator.userAgent):l()?/(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.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=r,t.isWindows10=function(){return n()&&/(Win32|Win64|WOW64)/i.test(navigator.platform)&&/Windows NT 10/i.test(navigator.userAgent)},t.isMobile=i,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=a,t.isLinux=o,t.isARM=s,t.isUwpEdge=function(){return"undefined"!=typeof window&&!!window.Windows},t.isEdge=c,t.isChromiumEdge=function(){return n()&&/Edg\//i.test(navigator.userAgent)},t.isIE=l,t.isChrome=u,t.isSafari=d,t.isFirefox=p,t.isOpera=f,t.isMidori=_,t.isEpiphany=m,t.isTouchEnabled=g,t.isPxtElectron=h,t.isIpcRenderer=y,t.isElectron=v,t.isWinRT=()=>!1,t.isLocalHost=b,t.isLocalHostDev=function(){return b()&&!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(){try{return/tutorialview=old/.test(window.location.href)}catch(e){return!1}},t.hasPointerEvents=x,t.hasSaveAs=function(){return c()||l()||p()},t.os=k,t.browser=S,t.browserVersion=T;let C=!1;function E(){return i()&&d()&&!/downloadWindowOpen=0/i.test(window.location.href)}function D(t,n,r){const a=E(),o=T(),s=parseInt(o||"0");if(a)r?r.location.href=t:window.open(t,"_self");else if(e.BrowserUtils.isSafari()&&(s<10||0==o.indexOf("10.0")||i())){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 r=atob(t.split(",")[1]),i=e.Util.stringToUint8Array(r),a=new Blob([i],{type:"img/png"});window.navigator.msSaveOrOpenBlob(a,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 A(t,n){let r="data";i()&&d()&&e.appTarget.appTheme.mobileSafariDownloadProtocol&&(r=e.appTarget.appTheme.mobileSafariDownloadProtocol);const a=/downloadProtocol=([a-z0-9:/?]+)/i.exec(window.location.href);a&&(r=a[1]);return r+":"+n+";base64,"+t}function N(t,n,r={}){var i;e.debug("trigger download");const{contentType:a="application/octet-stream",userContextWindow:o,onError:s,maintainObjectURL:c}=r,l=null===(i=window.URL)||void 0===i?void 0:i.createObjectURL,u=e.appTarget.appTheme.disableBlobObjectDownload;let d;try{if(l&&!u){const r=l(new Blob([e.Util.stringToUint8Array(atob(t))],{type:a}));D(r,n,o),c?d=r:window.setTimeout((()=>window.URL.revokeObjectURL(d)),0)}else d=A(t,n),D(d,n,o)}catch(t){s&&s(t),e.debug("saving failed")}return d}function w(e){const t=document.createElement("img");return new Promise(((n,r)=>{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 r=(null===(t=e.appTarget)||void 0===t?void 0:t.unsupportedBrowsers)||(null===(n=window.pxtTargetBundle)||void 0===n?void 0:n.unsupportedBrowsers);if(null==r?void 0:r.some((e=>e.id==S())))return!1;const i=T(),a=parseInt(i||"0"),l=u()&&a>=38,g=p()&&a>=31,h=c(),y=d()&&a>=9,v=f()&&u()&&a>=21;let b=l||g||h||y||v;const x=_()||o()&&s()&&m();return b=b&&!x,b=b||/anybrowser=(true|1)/.test(window.location.href),C||(e.log(`Browser: ${S()} ${i} on ${k()}`),b||e.tickEvent("browser.unsupported",{useragent:navigator.userAgent}),C=!0),b},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 N(ts.pxtc.encodeBase64(e),t,n)},t.browserDownloadText=function(t,n,r){return N(ts.pxtc.encodeBase64(e.Util.toUTF8(t)),n,r)},t.isBrowserDownloadInSameWindow=E,t.isBrowserDownloadWithinUserContext=function(){const e=T(),t=parseInt(e||"0");return i()&&d()&&t>=11||/downloadUserContext=1/i.test(window.location.href)},t.browserDownloadDataUri=D,t.browserDownloadUInt8Array=function(t,n,r){return N(ts.pxtc.encodeBase64(e.Util.uint8ArrayToString(t)),n,r)},t.toDownloadDataUri=A,t.browserDownloadBase64=N,t.loadImageAsync=w,t.loadCanvasAsync=function(e){return w(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");n.width=e.width*t,n.height=e.height*t;const r=n.getContext("2d");return r.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");n.width=e.width*t,n.height=e.height*t;const r=n.getContext("2d");return r.putImageData(e,0,0),r.imageSmoothingEnabled=!1,r.scale(t,t),r.drawImage(n,0,0),n.toDataURL("image/png")};const I=1e6;function P(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:r,height:i,pixelDensity:a=4,maxSize:o=I,text:s}=n||{};return new Promise(((n,c)=>{const l=new Image;l.onload=function(){const t=document.createElement("canvas"),c=t.getContext("2d");t.width=(r||l.width)*a,t.height=(i||l.height)*a,s&&(c.fillStyle="#fff",c.fillRect(0,0,t.width,t.height)),c.drawImage(l,0,0,r,i,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}`),c.drawImage(l,0,0,r,i,0,0,t.width,t.height),u=t.toDataURL("image/png");if(s){e.lzmaCompressAsync(s).then((r=>{const i=e.Util.encodeBlobAsync(t,r);n(i.toDataURL("image/png"))}))}else n(u)},l.onerror=t=>{e.reportError("png","png rendering failed"),n(void 0)},l.src=t}))},t.resolveCdnUrl=P,t.loadStyleAsync=function(t,n){n&&(t="rtl"+t);const r="style-"+t;if(document.getElementById(r))return Promise.resolve();const i=P(t),a=e.Util.toArray(document.head.getElementsByTagName("link")).filter((e=>e.getAttribute("href")==i))[0];return a?(a.id||(a.id=r),Promise.resolve()):new Promise(((e,t)=>{const n=document.createElement("link");n.href=i,n.rel="stylesheet",n.type="text/css",n.id=r,n.addEventListener("load",(()=>e())),n.addEventListener("error",(e=>t(e))),document.head.appendChild(n)}))};let O,F,L,R={};function M(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 U(){const e=n()&&window.navigator;return e&&e.storage&&e.storage.estimate?e.storage.estimate():Promise.resolve({})}t.loadScriptAsync=function(t){const n=P(t);let r=R[n];return r||(r=R[n]=new Promise(((t,r)=>{e.debug(`script: loading ${n}`);const i=document.createElement("script");i.type="text/javascript",i.addEventListener("load",(()=>t())),i.addEventListener("error",(e=>{delete R[n],r(e)})),i.src=n,i.async=!0,document.body.appendChild(i)}))),r},t.loadAjaxAsync=function(e){return new Promise(((t,n)=>{let r=new XMLHttpRequest;r.onreadystatechange=function(){r.readyState==XMLHttpRequest.DONE&&(200==r.status?t(r.responseText):n(r.status))},r.open("GET",e,!0),r.send()}))},t.loadBlocklyAsync=function(){if(!O){e.debug("blockly: delay load");let t=e.BrowserUtils.loadStyleAsync("blockly.css",ts.pxtc.Util.isUserLanguageRtl());"undefined"==typeof Blockly&&(t=t.then((()=>e.BrowserUtils.loadScriptAsync("pxtblockly.js")))),t=t.then((()=>{e.debug("blockly: loaded")})),O=t}return O},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 r=t.filter((t=>e.Util.endsWith(t.getAttribute("href"),"blockly.css")))[0];if(r){const t=r.getAttribute("data-rtl");t&&(e.debug(`swapping to ${t}`),r.setAttribute("href",t),r.removeAttribute("data-rtl"))}}},t.changeHash=function(e,t){"#"!=e.charAt(0)&&(e="#"+e),t?window.location.hash=e:window.history.replaceState("","",e)},t.urlJoin=M,t.joinURLs=function(...e){let t;if(e)for(let n=0;n<e.length;n++)t=M(t,e[n]);return t},t.storageEstimateAsync=U,t.scheduleStorageCleanup=n()&&navigator.storage&&navigator.storage.estimate?ts.pxtc.Util.throttle((function(){U().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"),z()):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((()=>K())).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,n){return`${e}|${t}|${n||"master"}`}get(e,t,n){return this.translations[this.key(e,t,n)]}getAsync(e,t,n){return Promise.resolve(this.get(e,t,n))}set(e,t,n,r,i,a,o){this.translations[this.key(e,t,n)]={etag:r,time:i,strings:a,md:o}}setAsync(t,n,r,i,a,o){return this.set(t,n,r,i,e.Util.now(),a),Promise.resolve()}clearAsync(){return this.translations={},Promise.resolve()}}class ${constructor(e,t,n,r){this.name=e,this.version=t,this.upgradeHandler=n,this.quotaExceededHandler=r}throwIfNotOpened(){if(!this._db)throw new Error("Database not opened; call IDBWrapper.openAsync() first")}errorHandler(t,n,r){console.error(new Error(`${this.name} IDBWrapper error for ${n}: ${t.message}`)),r(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 r=(window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB).deleteDatabase(e);r.onsuccess=()=>t(),r.onerror=()=>n(r.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,r)=>{const i=this.getObjectStore(e).get(t);i.onsuccess=()=>n(i.result),i.onerror=()=>this.errorHandler(i.error,"get",r)}))}getAllAsync(e){return new Promise(((t,n)=>{const r=this.getObjectStore(e).openCursor(),i=[];r.onsuccess=()=>{r.result?(i.push(r.result.value),r.result.continue()):t(i)},r.onerror=()=>this.errorHandler(r.error,"getAll",n)}))}setAsync(e,t){return new Promise(((n,r)=>{const i=this.getObjectStore(e,"readwrite");let a;a=void 0!==t.id&&null!==t.id?i.put(t):i.add(t),a.onsuccess=()=>n(),a.onerror=()=>this.errorHandler(a.error,"set",r)}))}deleteAsync(e,t){return new Promise(((n,r)=>{const i=this.getObjectStore(e,"readwrite").delete(t);i.onsuccess=()=>n(),i.onerror=()=>this.errorHandler(i.error,"delete",r)}))}deleteAllAsync(e){return new Promise(((t,n)=>{const r=this.getObjectStore(e,"readwrite").clear();r.onsuccess=()=>t(),r.onerror=()=>this.errorHandler(r.error,"deleteAll",n)}))}}t.IDBWrapper=$;class j{constructor(e){this.db=e,this.mem=new B}static dbName(){return`__pxt_translations_${e.appTarget.id||""}`}static createAsync(){function e(){const e=new $(j.dbName(),2,((e,t)=>{t.result.createObjectStore(j.TABLE,{keyPath:j.KEYPATH})}),(()=>{z().catch((e=>{}))}));return e.openAsync().then((()=>new j(e)))}return e().catch((t=>(console.log("db: failed to open database, try delete entire store..."),$.deleteDatabaseAsync(j.dbName()).then((()=>e())))))}getAsync(e,t,n){e=(e||"en-US").toLowerCase();const r=this.mem.key(e,t,n),i=this.mem.get(e,t,n);return i?Promise.resolve(i):this.db.getAsync(j.TABLE,r).then((r=>r?(this.mem.set(e,t,n,r.etag,r.time,r.strings),Promise.resolve(r)):Promise.resolve(void 0))).catch((e=>Promise.resolve(void 0)))}setAsync(n,r,i,a,o,s){n=(n||"en-US").toLowerCase();const c=this.mem.key(n,r,i);let l=e.Util.now();this.mem.set(n,r,i,a,l,o,s),o&&Object.keys(o).filter((e=>!o[e])).forEach((e=>delete o[e]));const u={id:c,etag:a,time:l,strings:o,md:s};return this.db.setAsync(j.TABLE,u).finally((()=>t.scheduleStorageCleanup())).catch((e=>(console.log(`db: set failed (${e.message}), recycling...`),this.clearAsync())))}clearAsync(){return this.db.deleteAllAsync(j.TABLE).then((()=>console.debug("db: all clean"))).catch((e=>{console.error("db: failed to delete all")}))}}function K(){return e.Util.isNodeJS?Promise.resolve(new B):(F||(F=j.createAsync().catch((()=>new B))),F)}function z(){function t(){const t=j.dbName();return $.deleteDatabaseAsync(t).then((()=>{F=void 0})).catch((n=>{e.log(`db: failed to delete ${t}`),F=void 0}))}return F?F.then((e=>e.clearAsync())).catch((e=>t().then())):t()}function J(t){const n=JSON.stringify(t)+e.appTarget.versions.pxt+"_"+e.appTarget.versions.target;return pxtc.U.sha256(n)}function q(e,t){return`${e}|${t||"master"}`}j.TABLE="files",j.KEYPATH="id",t.translationDbAsync=K,t.clearTranslationDbAsync=z,t.getTutorialCodeHash=J;class V{constructor(e){this.db=e}static dbName(){return`__pxt_tutorialinfo_${e.appTarget.id||""}`}static createAsync(){function t(){const t=new e.BrowserUtils.IDBWrapper(V.dbName(),2,((e,t)=>{t.result.createObjectStore(V.TABLE,{keyPath:V.KEYPATH})}),(()=>{e.BrowserUtils.IDBWrapper.deleteDatabaseAsync(V.dbName())}));return t.openAsync().then((()=>new V(t)))}return t().catch((n=>(console.log("db: failed to open tutorial info database, try delete entire store..."),e.BrowserUtils.IDBWrapper.deleteDatabaseAsync(V.dbName()).then((()=>t())))))}getAsync(t,n,r){const i=q(t,r),a=J(n);return this.db.getAsync(V.TABLE,i).then((t=>{if(t&&t.hash==a&&e.Util.now()-(t.time||0)<864e5)return t;this.db.deleteAsync(V.TABLE,i)}))}setAsync(t,n,r,i){e.perf.measureStart("tutorial info db setAsync");q(t,i);const a=J(r);return this.setWithHashAsync(t,n,a)}setWithHashAsync(t,n,r,i){e.perf.measureStart("tutorial info db setAsync");const a=q(t,i),o={};Object.keys(n).forEach((e=>{Object.keys(n[e]).forEach((t=>{o[t]=n[e][t]}))}));const s={id:a,time:e.Util.now(),hash:r,snippets:n,blocks:o};return this.db.setAsync(V.TABLE,s).then((()=>{e.perf.measureEnd("tutorial info db setAsync")}))}clearAsync(){return this.db.deleteAllAsync(V.TABLE).then((()=>console.debug("db: all clean"))).catch((e=>{console.error("db: failed to delete all")}))}}function H(e){return e.split(/\s+/).filter((e=>!!e))}function G(){const t=new RegExp(`${e.Util.escapeForRegex(e.Util.pxtLangCookieId)}=(.*?)(?:;|$)`).exec(document.cookie);return t&&t[1]||null}V.TABLE="info",V.KEYPATH="id",t.tutorialInfoDbAsync=function(){return L||(L=V.createAsync()),L},t.clearTutorialInfoDbAsync=function(){function t(){const t=V.dbName();return $.deleteDatabaseAsync(t).then((()=>{L=void 0})).catch((n=>{e.log(`db: failed to delete ${t}`),L=void 0}))}return L?L.then((e=>e.clearAsync())).catch((e=>t().then())):t()},t.pointerEvents=x()?{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,r,i){try{const e=window.screenLeft?window.screenLeft:window.screenX,a=window.screenTop?window.screenTop:window.screenY,o=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth,s=window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight,c=o/2-r/2+e,l=s/2-i/2+a,u=window.open(t,n,"width="+r+", height="+i+", top="+l+", left="+c);return u.focus&&u.focus(),u}catch(n){return e.tickEvent("pxt.popupError",{url:t,msg:n.message}),null}},t.containsClass=function(e,t){return H(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){H(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){H(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=G,t.setCookieLang=function(t,n=!1){if(e.Util.allLanguages[t]&&t!==G()){e.tickEvent("menu.lang.setcookielang",{lang:t,docs:`${n}`});const r=new Date;r.setTime(r.getTime()+24*e.Util.langCookieExpirationDays*60*60*1e3),document.cookie=`${e.Util.pxtLangCookieId}=${t}; expires=${r.toUTCString()}; path=/`}},t.cacheBustingUrl=function(e){return e?/[?&]rnd=/.test(e)?e:`${e}${e.indexOf("?")>0?"&":"?"}rnd=${Math.random()}`:e}}(e.BrowserUtils||(e.BrowserUtils={}))}(pxt||(pxt={})),function(e){!function(e){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("Saving project to the cloud..."),shortStatus:lf("saving..."),longStatus:lf("Saving to cloud..."),indicator:"*"}}}(e.cloud||(e.cloud={}))}(pxt||(pxt={})),function(e){!function(e){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(){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(((r,i)=>{try{t.decompress(n,((t,n)=>{n&&e.debug("lzma decompression failed"),r(n?void 0:t)}))}catch(t){t&&e.debug("lzma decompression failed"),r(void 0)}}))))},e.lzmaCompressAsync=function(n){return t().then((t=>new Promise(((r,i)=>{try{t.compress(n,7,((t,n)=>{n&&e.reportException(n),r(n?void 0:new Uint8Array(t))}))}catch(t){e.reportException(t),r(void 0)}}))))}}(pxt||(pxt={})),function(e){!function(t){var n=pxtc.Util;let r=n.lf;const i={"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 a(e="namespace"){let t="",n="",r=(r,i="")=>{n!=r&&(n&&(t+="}\n"),r&&(t+=i||e+" "+r+" {\n"),n=r)},i=" ";return{setNs:r,clear:()=>{t="",n=""},write:e=>{e.trim()?(e=e.trim().replace(/^\s*/gm,i).replace(/^(\s*)\*/gm,((e,t)=>t+" *")),t+=e+"\n"):t+="\n"},incrIndent:()=>{i+=" "},decrIndent:()=>{i=i.slice(4)},finish:()=>(r(""),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=a,t.parseCppInt=o;let s={};class c extends Error{constructor(e){super(e),this.isUserError=!0,this.message=e}}function l(e){if(!e)return"";let t="";for(let n=0;n<e.length;++n){let r=255&e[n];t+=37==r||r>127?"%"+r.toString(16):String.fromCharCode(r)}return decodeURIComponent(t)}function u(t){let n="",r=0;for(;r<t.length;r+=2)n=t[r]+t[r+1]+n;return e.Util.assert(r==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 r=0;r<t.length;++r)if(e[n+r]!=t[r])continue e;let r=e[n+8]|e[n+9]<<8,i=e[n+10]|e[n+11]<<8|e[n+12]<<16|e[n+13]<<24;n+=16;let a=n+r+i;if(a>e.length)continue;let o=e.slice(n,n+r),s=e.slice(n+r,a);return{meta:l(o),text:s}}return null}function p(t){function n(t){return e.debug(t),Promise.reject(new Error(t))}let r;if(e.HF2.read32(t,0)==ts.pxtc.UF2.UF2_MAGIC_START0){let e=ts.pxtc.UF2.toBin(t);e&&(r=d(e.buf))}if(1179403647==e.HF2.read32(t,0)&&(r=d(t)),58==t[0]){r=function(e){if(!e)return;let t,n=0,r=0,i=0,a=0;if(e.split(/\r?\n/).forEach((e=>{let o=/^:10....0[0E]41140E2FB82FA2BB(....)(....)(....)(....)(..)/.exec(e);if(o)n=parseInt(u(o[1]),16),r=parseInt(u(o[2]),16),i=n+r,t=new Uint8Array(i);else if(i>0){if(o=/^:10....0[0E](.*)(..)$/.exec(e),!o)return;let n=o[1];for(;i>0&&n.length>0;)t[a++]=parseInt(n[0]+n[1],16),n=n.slice(2),i--}})),!t||0!=i||a!=t.length)return;let o=new Uint8Array(n),s=new Uint8Array(r);for(let e=0;e<n;++e)o[e]=t[e];for(let e=0;e<r;++e)s[e]=t[n+e];return{meta:l(o),text:s}}(l(t)||"")}if(!r||!r.meta||!r.text)return n("This .hex file doesn't contain source.");let i=JSON.parse(r.meta);return i?"LZMA"==i.compression?e.lzmaDecompressAsync(r.text).then((t=>{if(!t)return null;let n=t.slice(0,i.headerSize||i.metaSize||0),r=t.slice(n.length);return n&&e.Util.jsonCopyFrom(i,JSON.parse(n)),{meta:i,source:r}})):i.compression?n(`Compression type ${i.compression} not supported.`):Promise.resolve({source:l(r.text)}):n("This .hex file is not valid.")}t.PkgConflictError=c,t.getExtensionInfo=function(t){const l={__appVariant:e.appTargetVariant||""},u="dal.d.ts";let d="/source/",p="",f=[];const _=t.sortedDeps(!0).sort(((e,t)=>"this"==e.id?1:"this"==t.id?-1:n.strcmp(e.id,t.id)));for(let t of _)t.disablesVariant(e.appTargetVariant)||t.resolvedDependencies().some((t=>t.disablesVariant(e.appTargetVariant)))?(p&&(p+=", "),p+=t.id,e.debug(`disable variant ${e.appTargetVariant} due to ${t.id}`)):(f.push(t),t.addSnapshot(l,[u,".h",".cpp"]));const m=JSON.stringify(l),g=s[m];if(g){e.debug("Using cached extinfo");const t=n.flatClone(g);return t.disabledDeps=p,t}e.debug("Generating new extinfo");const h=pxtc.emptyExtInfo();h.disabledDeps=p;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 b=!!y.platformioIni,x="codal"==y.buildEngine||"dockercodal"==y.buildEngine,k="dockermake"==y.buildEngine||"dockercross"==y.buildEngine,S="dockerespidf"==y.buildEngine,T=!(b||x||k||S),C=v.nativeType==pxtc.NATIVE_TYPE_VM;b?d="/src/":x||k?d="/pxtapp/":S&&(d="/main/");let E="// Configuration defines\n",D="\nPXT_SHIMS_BEGIN\n",A="",N="",w='#include "pxt.h"\n',I="",P=e=>I+=` ${F}(${O}): ${e}\n`,O=0,F="",L=a("namespace"),R=a("declare namespace"),M=a("declare namespace"),U="",B={},$={};const j={true:"1",false:"0",null:"0",NULL:"0"};function K(e){return e.trim().replace(/[\_\*]$/,"")}for(const t of f){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"))&&(h.generatedFiles["/"+e]=t.host().readFile(t,e))}let z=["0","false","PXT_UTF8"],J={};function q(e){return e.replace(/\/\/.*/,"").replace(/\/\*/,"")}v.switches.boxDebug&&(J.PXT_BOX_DEBUG=1),v.utf8&&(J.PXT_UTF8=1),v.switches.profile&&(J.PXT_PROFILE=1),v.switches.gcDebug&&(J.PXT_GC_DEBUG=1),v.switches.numFloat&&(J.PXT_USE_FLOAT=1),v.nativeType==pxtc.NATIVE_TYPE_VM&&(J.PXT_VM=1);let V=0,H=!1,G="",W="",Q="",Y=!1;function X(){R.setNs(""),R.write(""),R.write(""),(Q||W)&&(R.write(W),R.write(Q),Q="",W="")}function Z(e,t){let a;G="",W="",Q="",Y=!1;let s=-1;function c(){let e=G.replace(/Methods$/,"");return e==G?null:e}function l(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&&P("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 K(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,r,i)=>z.indexOf(n)>=0&&!J[n]?t+r.replace(/[^\n]/g,"")+i:e)),O=0,H=!1,V=0,M.setNs(""),R.setNs(""),e.split(/\r?\n/).forEach((e=>{++O;let d=q(e);!function(e){let t=q(e);if(H&&t.indexOf("}")>=0&&(H=!1,M.write("}")),!H)return;let r=/^\s*(\w+)\s*(=\s*(.*?))?,?\s*$/.exec(t);if(r){let e=r[1],i=r[3],a="";if(i){i=i.trim();let e=n.lookup(j,i);null!=e&&(a=" // "+i,i=e),V=o(i),null==V&&P("cannot determine value of "+t)}else V++,i=V+"";M.write(` ${K(e)} = ${i},${a}`)}else M.write(e)}(e);let p=/^\s*enum\s+(|class\s+|struct\s+)(\w+)\s*({|$)/.exec(d);var f,_;if(p&&(f=p[2],_=p[3],H=!0,V=-1,M.write(""),M.write(""),(Q||W)&&(M.write(W),M.write(Q),Q="",W=""),M.write(`declare const enum ${K(f)} ${_}`),B[f]=!0,t||(L.setNs(G),L.write(`enum ${p[2]} : int;`))),function(e){return!(!H&&(/^\s*\/\*\*/.test(e)?(Y=!0,W=e+"\n",/\*\//.test(e)&&(Y=!1),0):Y?(W+=e+"\n",/\*\//.test(e)&&(Y=!1),0):!/^\s*\/\/%/.test(e)||(Q+=e+"\n",0)))}(e))return;/^typedef.*;\s*$/.test(e)&&(L.setNs(G),L.write(e));let m=/^\s*namespace\s+(\w+)/.exec(e);if(m)if(G=m[1],c()){X();let e=c();R.setNs(G,`declare interface ${e} {`)}else(Q||W)&&(X(),R.setNs(K(G)),M.setNs(K(G)));else{if(m=/^PXT_ABI\((\w+)\)/.exec(e),m&&!C&&(D+=`PXT_FNPTR(::${m[1]}),\n`,N+=`extern "C" void ${m[1]}();\n`,h.functions.push({name:m[1],argsFmt:[],value:0})),m=/^\s*PXT_EXPORT\(([:\&\w]+)\)/.exec(e),m&&(h.vmPointers||(h.vmPointers=[]),h.vmPointers.push(m[1])),m=/^#define\s+PXT_COMM_BASE\s+([0-9a-fx]+)/.exec(e),m&&(h.commBase=parseInt(m[1])),m=/^\s*(\w+)([\*\&]*\s+[\*\&]*)(\w+)\s*\(([^\(\)]*)\)\s*(;\s*$|\{|$)/.exec(e),!Q||!m){if(m=/^\s*extern const (\w+) (\w+);/.exec(e),Q&&m){let e={name:G+"::"+m[2],argsFmt:[],value:null};return h.functions.push(e),C||(D+="PXT_FNPTR(&::"+e.name+"),\n"),void(Q="")}if(m=/^\s*(\w+)\s+(\w+)\s*;/.exec(e),Q&&m){let e=pxtc.parseCommentString(Q);e.indexedInstanceNS&&(a=e,R.setNs(e.indexedInstanceNS),s=0);let t=m[1],n=m[2];if(a)return Q=Q.trim(),Q+=` fixedInstance shim=${a.indexedInstanceShim}(${s++})`,R.write(""),R.write(W),R.write(Q),R.write(`const ${n}: ${l(t)};`),W="",void(Q="")}return Q&&e.trim()?(P("declaration not understood: "+e),Q="",void(W="")):void 0}{a=null;let e=pxtc.parseCommentString(Q);G||P("missing namespace declaration");let s=(m[1]+m[2]).replace(/\s+/g,""),d=m[3],p=m[4];Q=Q.trim().replace(/ \w+\.defl=\w+/g,"");let f=[u(s)],_=[],g=p.split(/,/).filter((e=>!!e)).map((t=>{let r=function(e,t){t=t.trim();let r=/(.*)=\s*(-?\w+)$/.exec(t),i="",a="";if(r&&(i=r[2],a="?",t=r[1].trim()),r=/^(.*?)(\w+)$/.exec(t),!r)return P("invalid argument: "+t),{name:"???",type:"int"};let s=r[2];e.paramDefl[s]&&(i=e.paramDefl[s],a="?");let c=i?n.lookup(j,i):null;return null!=c&&(i=c),i&&(null==o(i)&&P("Invalid default value (non-integer): "+i),Q+=` ${s}.defl=${i}`),{name:s+a,type:r[1]}}(e,t);return f.push(u(r.type)),_.push(r.type.replace(/ /g,"")),`${r.name}: ${l(r.type)}`})),y={name:G+"::"+d,argsFmt:f,value:null};if(W)if(R.setNs(K(G)),R.write(""),R.write(W),/ImageLiteral/.test(m[4])&&!/imageLiteral=/.test(Q)&&(Q+=" imageLiteral=1"),Q+=` shim=${y.name}`,R.write(Q),d=K(d),c()){let e=(g[0]||"").replace(/^.*:\s*/,"").trim();e.toLowerCase()!=c().toLowerCase()&&P(r("Invalid first argument; should be of type '{0}', but is '{1}'",c(),e)),g.shift(),0==g.length&&/\bproperty\b/.test(Q)?R.write(`${d}: ${l(s)};`):R.write(`${d}(${g.join(", ")}): ${l(s)};`)}else R.write(`function ${d}(${g.join(", ")}): ${l(s)};`);if(W="",Q="",t||(L.setNs(G),L.write(`${s} ${d}(${p});`)),h.functions.push(y),T)D+="(uint32_t)(void*)::"+y.name+",\n";else if(C){if(n.startsWith(y.name,"pxt::op_")||i[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,A+=`\nvoid ${n}(FiberContext *ctx) {\n`;const r=t.length;let i=[],a=!1,o="";for(let n=0;n<r;++n){const s=e.argsFmt[n+1],c=t[n];let l="I"==s?"toInt":"B"==s?"numops::toBool":"";const u=n==r-1?"ctx->r0":`ctx->sp[${r-n-2}]`;let d="";switch(c){case"TValue":case"TNumber":break;case"Action":l="asRefAction";break;case"String":l="convertToString",d="ctx, ",a=!0;break;default:l||(l="as"+c.replace(/\*/g,""))}o+=` ${c} a${n} = (${c}) ${l}(${d}${u});\n`,i.push("a"+n)}a&&(A+=" auto prevSP = ctx->sp;\n"),A+=o,a&&(A+=" if (panicCode) { ctx->sp = prevSP; return; }\n");const s=`::${e.name}(${i.join(", ")})`;return"V"==e.argsFmt[0]?(A+=` ${s};\n`,A+=" ctx->r0 = NULL;\n"):"I"==e.argsFmt[0]?A+=` ctx->r0 = fromInt(${s});\n`:"B"==e.argsFmt[0]?A+=` ctx->r0 = fromBool(${s});\n`:A+=` ctx->r0 = (TValue)${s};\n`,a&&(A+=" ctx->sp = prevSP;\n"),r>1&&(A+=` ctx->sp += ${r-1};\n`),A+="}\n",n}(y,_),t=y.argsFmt.length-1;D+=`{ "${y.name}", (OpFun)(void*)${e}, ${t} },\n`}}else D+="PXT_FNPTR(::"+y.name+"),\n"}}}))}const ee=n.clone(y.yottaConfig||{}),te={},ne={},re={};function ie(t){const i=t.config.platformio;i&&i.dependencies&&n.jsonCopyFrom(h.platformio.dependencies,i.dependencies),h.npmDependencies&&t.config.npmDependencies&&n.jsonCopyFrom(h.npmDependencies,t.config.npmDependencies);const a=t.config.codal;if(x&&a)for(const t of a.libraries||[]){const i=e.github.parseRepoId(t);i||n.userError(r("codal library {0} doesn't look like github repo",t));const a=e.github.stringifyRepo(i),o=n.lookup(re,i.project);o?e.github.stringifyRepo(o)!=a&&n.userError(r("conflict between codal libraries: {0} and {1}",e.github.stringifyRepo(o),a)):re[i.project]=i}const o=t.config.yotta;if(o){if(o.dependencies&&n.jsonCopyFrom(h.yotta.dependencies,o.dependencies),o.config){const e=n.jsonFlatten(o.config);for(const i of Object.keys(e)){const a=n.lookup(ne,i),o=e[i];if(!a||a.config.yotta.configIsJustDefaults)ne[i]=t,ee[i]=o;else if(ee[i]===o);else if(!t.parent.config.yotta||!t.parent.config.yotta.ignoreConflicts){let e=new c(r("conflict on yotta setting {0} between extensions {1} and {2}",i,t.id,a.id));throw e.pkg0=a,e.pkg1=t,e.settingName=i,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(T&&v.hasHex){let e=y;n.assert(!!e.yottaCorePackage),n.assert(!!e.githubCorePackage),n.assert(!!e.gittag);let t=e.githubCorePackage+"#"+y.gittag;h.yotta.dependencies[e.yottaCorePackage]=t}if(t){let e=!1;for(let i of f){I="",ie(i),i==t?(e=!0,R.clear(),M.clear()):n.assert(!e);const a=e=>n.endsWith(e,".h"),o=".cpp",s=i.getFiles().filter(a).concat(i.getFiles().filter((e=>!a(e))));for(let e of s){const t=a(e);if(t||n.endsWith(e,o)){let a=i.config.name+"/"+e;("base"==i.config.name||/^core($|---)/.test(i.config.name))&&t&&(a=e),t&&(w+=`#include "${T?d.slice(1):""}${a}"\n`);let o=i.readFile(e);null==o&&n.userError(r("C++ file {0} is missing in extension {1}.",e,i.config.name)),F=a,Z(o,t),h.extensionFiles[d+a]=o,0==i.level&&(h.onlyPublic=!1),i.verProtocol()&&"pub"!=i.verProtocol()&&"embed"!=i.verProtocol()&&(h.onlyPublic=!1)}if(n.endsWith(e,".c")||n.endsWith(e,".S")||n.endsWith(e,".s")){let t=i.readFile(e);h.extensionFiles[d+i.config.name+"/"+e.replace(/\.S$/,".s")]=t}}I&&(U+=r("Extension {0}:\n",i.id)+I)}e||(R.clear(),M.clear())}function ae(e){return Object.keys(h.extensionFiles).concat(Object.keys(h.generatedFiles)).filter((t=>n.endsWith(t,e))).map((e=>e.slice(1)))}U&&n.userError(U),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})),!T&&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(k){let e={name:"pxt-app",private:!0,dependencies:h.npmDependencies};h.generatedFiles["/package.json"]=JSON.stringify(e,null,4)+"\n"}else if(S){const e=n.concatArrayLike([ae(".c"),ae(".cpp"),ae(".s")]).map((e=>e.slice(d.length-1))).concat(["main.cpp"]);e.push("pointers.cpp"),h.generatedFiles[d+"CMakeLists.txt"]="idf_component_register(\n SRCS\n"+e.map((e=>` "${e}"\n`)).join("")+' INCLUDE_DIRS\n "."\n)\n'}else if(x){let t=y,r=n.clone(t.codalDefinitions)||{},i=t.codalTarget;"string"==typeof i&&(i+=".json");let a={target:i,definitions:r,config:r,application:"pxtapp",output_folder:"build",pxt_gitrepo:t.githubCorePackage,pxt_gittag:t.gittag,libraries:n.values(re).map((e=>({name:e.project,url:"https://github.com/"+e.fullName,branch:e.tag||"master",type:"git"})))};0==a.libraries.length&&delete a.libraries,n.iterMap(n.jsonFlatten(oe),((e,t)=>{e=e.replace(/^codal\./,"device.").toUpperCase().replace(/\./g,"_"),r[e]=t})),h.generatedFiles["/codal.json"]=JSON.stringify(a,null,4)+"\n",e.debug(`codal.json: ${h.generatedFiles["/codal.json"]}`)}else if(b){const e=y.platformioIni.slice();e.push("lib_deps ="),n.iterMap(h.platformio.dependencies,((t,n)=>{let r=/[@#\/]/.test(n)?n:t+"@"+n;e.push(" "+r)})),h.generatedFiles["/platformio.ini"]=e.join("\n")+"\n"}else{h.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:h.yotta.dependencies,targetDependencies:{},bin:"./source"};h.generatedFiles["/module.json"]=JSON.stringify(n,null,4)+"\n",e.debug(`module.json: ${h.generatedFiles["/module.json"]}`)}for(let e of Object.keys(J))E+=`#define ${e} ${J[e]}\n`;if(v.uf2Family&&(E+=`#define PXT_UF2_FAMILY ${v.uf2Family}\n`),h.generatedFiles[d+"pointers.cpp"]=w+L.finish()+N+A+D+"\nPXT_SHIMS_END\n",h.generatedFiles[d+"pxtconfig.h"]=E,e.debug(`pxtconfig.h: ${h.generatedFiles[d+"pxtconfig.h"]}`),T&&(h.generatedFiles["/config.json"]=JSON.stringify(oe,null,4)+"\n",e.debug(`yotta config.json: ${h.generatedFiles["/config.json"]}`)),h.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',h.generatedFiles["/Makefile"]){let e="",t=(t,n)=>{e+=`${t} = ${ae(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",h.generatedFiles["/Makefile.inc"]=e}h.generatedFiles["/functions.json"]=JSON.stringify(h.functions,null,1);let se=h.extensionFiles;n.jsonCopyFrom(se,h.generatedFiles);let ce={config:y.serviceId,tag:y.gittag,replaceFiles:se,dependencies:T?h.yotta.dependencies:null},le=JSON.stringify(ce);return h.sha=n.sha256(le),h.skipCloudBuild=!!y.skipCloudBuild,h.compileData=ts.pxtc.encodeBase64(n.toUTF8(le)),h.shimsDTS=R.finish(),h.enumsDTS=M.finish(),Object.keys(s).length>10&&(s={}),s[m]=h,h},t.unpackSourceFromHexFileAsync=function(t){if(t)return e.Util.fileReadAsBufferAsync(t).then((e=>p(new Uint8Array(e))))},t.unpackSourceFromHexAsync=p}(e.cpp||(e.cpp={}))}(pxt||(pxt={})),function(e){!function(t){const n={};let r,i={};function a(i){return n.hasOwnProperty(i.sha)||(n[i.sha]=function(n){let i="";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,r).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,r}(n).then((a=>a?(e.tickEvent("cppcompile.cachehit"),a):function(){if(r)return r;{let t=e.getOnlineCdnUrl();if(t)return r=Promise.resolve(t);const n=e.webConfig&&e.webConfig.isStatic;return r=e.Cloud.privateGetAsync("clientconfig",n).then((e=>e.primaryCdnUrl))}}().then((t=>(i=t+"/compile/"+n.sha,e.U.httpGetTextAsync(i+".hex")))).then((e=>e),(t=>e.Cloud.privatePostAsync("compile/extension",{data:n.compileData},!0).then((t=>new Promise(((n,r)=>{let a=0;const o=8e3,s=3e5,c=e.U.now(),l=()=>{if(a++,e.U.now()-c>s)return e.log("abandoning C++ build"),e.tickEvent("cppcompile.cancel",{retry:a}),n(null),null;let r=t.hex.replace(/\.hex/,".json");return e.log(`polling C++ build ${r} (attempt #${a})`),e.tickEvent("cppcompile.poll",{retry:a}),e.Util.httpGetJsonAsync(r).then((t=>{e.log(`build log ${r.replace(/\.json$/,".log")}`),e.tickEvent("cppcompile.done",{success:(null==t?void 0:t.success)?1:0,retry:a,duration:e.U.now()-c}),t.success?(e.log("fetching "+i+".hex"),n(e.U.httpGetTextAsync(i+".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(l,o),null)))};l()})))))).then((e=>(t.hideLoading(),{hex:e&&e.split(/\r?\n/)}))))).finally((()=>{t.hideLoading()}))}(i)),n[i.sha]}function o(t,n,r,i,a=10){return t.cacheStoreAsync(r,i).then((()=>t.cacheGetAsync(n))).then((i=>{let o;try{o=JSON.parse(i||"[]")}catch(e){console.error("invalid cache entry, clearing entry"),o=[]}o=o.filter((e=>e!=r)),o.unshift(r);let s=o.slice(a);return o=o.slice(0,a),e.U.promiseMapAll(s,(e=>t.cacheStoreAsync(e,"[]"))).then((()=>t.cacheStoreAsync(n,JSON.stringify(o))))}))}function s(e,t,n){return e.cacheGetAsync(t).then((r=>{let i;try{i=JSON.parse(r||"[]")}catch(n){return console.error("invalid cache entry, clearing entry"),e.cacheStoreAsync(t,"[]")}return i[0]!=n?(i=i.filter((e=>e!=n)),i.unshift(n),e.cacheStoreAsync(t,JSON.stringify(i))):null}))}t.showLoading=e=>{},t.hideLoading=()=>{},t.storeWithLimitAsync=o,t.recordGetAsync=s,t.getHexInfoAsync=function(t,n,r){if(!n.sha)return Promise.resolve(null);const c=i[n.sha];if(c)return Promise.resolve(c);e.debug("get hex info: "+n.sha);let l="hex-"+n.sha;return t.cacheGetAsync(l).then((r=>{let i;try{i=r?JSON.parse(r):null}catch(e){console.log("invalid cache entry, clearing entry"),i=null}return i&&i.hex?(e.debug("cache hit, size="+r.length),i.hex=function(t){let n=[];for(let r=0;r<t.length;r++){let i=/^([@!])(....)$/.exec(t[r]);if(!i){n.push(t[r]);continue}let a=parseInt(i[2],16),o=t[++r],s="";if("@"==i[1]){s="";let e=parseInt(o,16);for(;e-- >0;)s+="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"}else s=ts.pxtc.decodeBase64(o);e.Util.assert(s.length>0),e.Util.assert(s.length%16==0);for(let e=0;e<s.length;){let t=[16,a>>8&255,255&a,0];a+=16;for(let n=0;n<16;++n)t.push(s.charCodeAt(e++));let r=0;for(let e=0;e<t.length;++e)r+=t[e];t.push(255&-r);let i=":";for(let e=0;e<t.length;++e){let n=255&t[e];n<=15&&(i+="0"),i+=n.toString(16)}n.push(i.toUpperCase())}}return n}(i.hex),s(t,"hex-keys",l).then((()=>i))):a(n).then((e=>{let n=e.hex;e.hex=function(e){let t=[],n=0;for(let r=0;r<e.length;r+=n){let i=-1,a="";n=0;let o=!1;for(;n<500;){let s=/^:10(....)00(.{32})(..)$/.exec(e[r+n]);if(!s)break;let c=s[2],l=/^0+$/.test(c),u=parseInt(s[1],16);if(-1==i)o=l,t.push((o?"@":"!")+s[1]),i=u-16;else{if(l!=o)break;if(i+16!=u)break}o||(a+=c),i=u,n++}if(0==n)t.push(e[r]),n=1;else if(o)t.push(n.toString(16));else{let e="";for(let t=0;t<a.length;t+=2)e+=String.fromCharCode(parseInt(a.slice(t,t+2),16));t.push(ts.pxtc.encodeBase64(e))}}return t}(e.hex);let r=JSON.stringify(e);return e.hex=n,o(t,"hex-keys",l,r).then((()=>e))})).catch((t=>(e.reportException(t,{sha:n.sha}),Promise.resolve(null))))})).then((e=>(e&&(Object.keys(i).length>20&&(i={}),i[n.sha]=e),e)))}}(e.hexloader||(e.hexloader={}))}(pxt||(pxt={})),function(e){!function(t){function n(n,r,i={},a=null,o=null){if(t.testMode||n==t.TEST_KEY){const e={success:!0};return Promise.resolve({statusCode:200,headers:{},text:JSON.stringify(e),json:e})}return e.Util.multipartPostAsync(r,i,a,o)}function r(n,r,i,a,o){e.Util.assert(!!r&&!!i&&!!a);const s="https://api.crowdin.com/api/project/"+r+"/";return o=o||{},t.testMode?delete o.key:o.key=i,n&&(o.branch=n),s+a+"?"+Object.keys(o).map((e=>`${e}=${encodeURIComponent(o[e])}`)).join("&")}function i(e){let t=0;return function(){if(t++>10)throw new Error("Too many API calls for "+e)}}function a(t,s,c,l,u){return l=o(l),e.debug(`create directory ${t||""}/${l}`),u||(u=i(l)),n(c,r(t,s,c,"add-directory"),{json:"true",name:l}).then((n=>{if(e.debug(`crowdin resp: ${n.statusCode}`),200==n.statusCode||400==n.statusCode)return Promise.resolve();if(500==n.statusCode&&n.text){if(50===JSON.parse(n.text).error.code)return e.log("directory already exists"),Promise.resolve()}const r=n.json||JSON.parse(n.text)||{error:{}};if(404==n.statusCode&&17==r.error.code){e.log(`parent directory missing for ${l}`);const n=l.replace(/\/[^\/]+$/,"");if(n!=l)return a(t,s,c,n,u).then((()=>a(t,s,c,l,u)))}throw new Error(`cannot create directory ${t||""}/${l}: ${n.statusCode} ${JSON.stringify(r)}`)}))}function o(e){return e.replace(/\\/g,"/")}function s(e,t,n,r){const i=t.name,a=n?n+"/"+i:i;switch(t.fullName=a,t.branch=r||"",t.node_type){case"file":e.push(t);break;case"directory":(t.files||[]).forEach((t=>s(e,t,a,r)));break;case"branch":(t.files||[]).forEach((r=>s(e,r,n,t.name)))}}function c(t,n){const r=e.appTarget.versions.pxtCrowdinBranch||"",i=e.appTarget.versions.targetCrowdinBranch||"";let a=[];if(t.forEach((e=>s(a,e,""))),a=a.filter((e=>e.fullName.indexOf("/")<0?e.branch==r:e.branch==i)),n&&(a=a.filter((e=>0==e.fullName.indexOf(n)))),"core"!=e.appTarget.id){const t=e.appTarget.id+"/";a=a.filter((e=>e.fullName.indexOf("/")<0||e.fullName.substr(0,t.length)==t||e.fullName.indexOf("common-docs")>=0))}return a}function l(t,n){const i=r("",t,n,"info",{json:"true"});return e.Util.httpGetTextAsync(i).then((e=>JSON.parse(e)))}t.KEY_VARIABLE="CROWDIN_KEY",t.testMode=!1,t.TEST_KEY="!!!testmode!!!",t.setTestMode=function(){e.crowdin.testMode=!0,e.log("CROWDIN TEST MODE - files will NOT be uploaded")},t.downloadTranslationsAsync=function(t,n,i,a,s={}){const c=r(t,n,i,"info",{json:"true"}),l={};return a=o(a),e.Util.httpGetTextAsync(c).then((o=>{const c=JSON.parse(o);if(!c)throw new Error("info failed");let u=c.languages.filter((e=>"en"!=e.code));e.appTarget&&e.appTarget.appTheme&&e.appTarget.appTheme.availableLocales&&(u=u.filter((t=>e.appTarget.appTheme.availableLocales.indexOf(t.code)>-1))),e.log("languages: "+u.map((e=>e.code)).join(", "));const d=()=>{const o=u.pop();if(!o)return Promise.resolve();const c=r(t,n,i,"export-file",{file:a,language:o.code,export_translated_only:s.translatedOnly?"1":"0",export_approved_only:s.validatedOnly?"1":"0"});return e.log(`downloading ${o.name} - ${o.code} (${u.length} more)`),e.Util.httpGetTextAsync(c).then((t=>{try{const e=JSON.parse(t);e&&(l[o.code]=e)}catch(t){e.log(c+" "+t)}return d()})).then((()=>e.Util.delay(1e3)))};return d()})).then((()=>l))},t.createDirectoryAsync=a,t.uploadTranslationAsync=function t(s,c,l,u,d){e.Util.assert(!!c),e.Util.assert(!!l);const p=i(u=o(u));function f(){return _("update-file",{update_option:"update_as_unapproved"})}function _(i,o){return o.type="auto",o.json="",o.escape_quotes="0",p(),n(l,r(s,c,l,i),o,u,d).then((n=>function(n){const r=n.statusCode,i=e.Util.jsonTryParse(n.text)||{};if(e.debug(`upload result: ${r}`),404==r&&i.error&&8==i.error.code)return e.log(`create new translation file: ${u}`),_("add-file",{});if(404==r&&i.error&&17==i.error.code)return a(s,c,l,u.replace(/\/[^\/]+$/,""),p).then((()=>f()));if(!i.success&&i.error&&53==i.error.code)return e.log(`${u} being updated, waiting 5s and retry...`),e.U.delay(5e3).then((()=>t(s,c,l,u,d)));if(200==r||i.success)return Promise.resolve();throw new Error(`Error, upload translation: ${u}, ${r}, ${n.text}`)}(n)))}return f()},t.projectInfoAsync=l,t.listFilesAsync=function(t,n,r){return e.log(`crowdin: listing files under ${r}`),l(t,n).then((t=>{if(!t)throw new Error("info failed");let n=c(t.files,r);return e.debug(`crowdin: found ${n.length} under ${r}`),n.map((e=>({fullName:e.fullName,branch:e.branch||""})))}))},t.languageStatsAsync=function(t,n,i){const a=r("",t,n,"language-status",{language:i,json:"true"});return e.Util.httpGetJsonAsync(a).then((e=>c(e.files)))},t.inContextLoadAsync=function(t){const n=document.createElement("input");n.type="text",n.setAttribute("class","hidden"),n.value=t;let r=new Promise(((r,i)=>{const a=new MutationObserver((()=>{if(t==n.value)return;const i=e.Util.rlf(n.value);n.remove(),a.disconnect(),r(i)}));a.observe(n,{attributes:!0})}));return document.body.appendChild(n),r}}(e.crowdin||(e.crowdin={}))}(pxt||(pxt={})),function(e){!function(t){function n(e){return e?e.split(/\r?\n/):[]}function r(e,t,r={}){r.ignoreWhitespace&&(e=e.replace(/[\r\n]+$/,""),t=t.replace(/[\r\n]+$/,""));const i=n(e),a=n(t),o=Math.min(r.maxDiffSize||1024,i.length+a.length);if(0==o)return[];const s=i.length>65520?Uint32Array:Uint16Array,c={};let l=0;const u=p(i),d=p(a);function p(e){const t=new s(e.length);let n=0;for(let i of e)r.ignoreWhitespace&&(i=i.replace(/\s+$/g,"").replace(/^\s+/g,"")),c.hasOwnProperty(i)?t[n]=c[i]:(++l,t[n]=l,c[i]=l),n++;return t}const f=new s(2*o+1);let _=-1;for(let e=0;e<=o;e++)null!=T(e,f)&&(_=e);if(-1==_)return null;const m=[];let g=null;for(let e=0;e<=_;e++){const t=m.length?m[m.length-1].slice(0):new s(2*_+1);if(m.push(t),g=T(e,t),null!=g)break}const h=[];let y=g;for(let e=m.length-1;e>=0;e--){const t=m[e];let n=0,r=0;y==-e||y!=e&&t[o+y-1]<t[o+y+1]?(r=y+1,n=t[o+r]):(r=y-1,n=t[o+r]+1);let s=n-y;for(let e=t[o+y]-n-1;e>=0;--e)h.push(" "+a[s+e]);r==y-1?h.push("- "+i[n-1]):s>0&&h.push("+ "+a[s-1]),y=r}if(h.reverse(),r.context==1/0||r.full)return h;let v=1,b=1,x=0;const k=[],S=r.context||3;for(;x<h.length;){let e=x;for(;e<h.length&&" "==h[e][0];)e++;if(e==h.length)break;const t=e-S,n=t-x;n>0&&(v+=n,b+=n,x=t);const r=k.length,i=v,a=b;k.push("@@");let o=x,s=0;for(;o<h.length;){if(" "==h[o][0]){if(s++,s>2*S+2){o-=S+2;break}}else s=0;o++}for(;x<o;){k.push(h[x]);switch(h[x][0]){case"-":v++;break;case"+":b++;break;case" ":v++,b++}x++}k[r]=`@@ -${i},${v-i} +${a},${b-a} @@`}return k;function T(e,t){for(let n=-e;n<=e;n+=2){let r=0;r=n==-e||n!=e&&t[o+n-1]<t[o+n+1]?t[o+n+1]:t[o+n-1]+1;let i=r-n;for(;r<u.length&&i<d.length&&u[r]==d[i];)r++,i++;if(t[o+n]=r,r>=u.length&&i>=d.length)return n}return null}}function i(e){return n(e).map((e=>e.replace(/;\s*$/,""))).join("\n")}function a(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=r,t.diff3=function(t,i,a,o,s){const c=g(t),l=g(a);if(!c||!l)return;const u=n(t),d=n(a);let p=0,f=[],_=0,m=0;for(let t=0;t<c.length-1;)if(c[t]==_&&l[t]==m)f.push(u[_]),_++,m++,t++;else{let n=!0,r=!0,i=t;for(;i<c.length&&(c[i]!=_+i-t&&(n=!1),l[i]!=m+i-t&&(r=!1),null==c[i]||null==l[i]);)i++;if(e.U.assert(i<c.length),n)for(;m<l[i];)f.push(d[m++]);else if(r)for(;_<c[i];)f.push(u[_++]);else if(u.slice(_,c[i]).join("\n")==d.slice(m,l[i]).join("\n"))for(;_<c[i];)f.push(u[_++]);else{for(p++,f.push("<<<<<<< "+o);_<c[i];)f.push(u[_++]);for(f.push("=======");m<l[i];)f.push(d[m++]);f.push(">>>>>>> "+s)}t=i,_=c[i],m=l[i]}return{merged:f.join("\n"),numConflicts:p};function g(t){const n=r(i,t,{context:1/0});if(!n)return;const a=[];let o=0,s=0;for(let t of n)"+"==t[0]?o++:"-"==t[0]?(a[s]=null,s++):" "==t[0]?(a[s]=o,o++,s++):e.U.oops();return a.push(o+1),a}},t.removeTrailingSemiColumns=i,t.split=function(e,t){const n=e.split(/-{10,}/,2);if(n.length<2)return{fileA:e,fileB:void 0};let r=n[0].replace(/\n$/,""),a=n[1].replace(/^\n/,"");return t&&t.removeTrailingSemiColumns&&(r=i(r),a=i(a)),{fileA:r,fileB:a}},t.parseDiffMarker=a,t.render=function(t,n,i={}){const o=r(t,n,i);if(!o)return e.dom.el("div",null,pxtc.Util.lf("Too many differences to render diff."));const s={"@":"diff-marker"," ":"diff-unchanged","+":"diff-added","-":"diff-removed"};let c=0,l=0,u="";const d=e.dom.el("tbody"),p=e.dom.el("table",{class:"diffview "+(i.update?"update":"")},d);let f=null;return o.forEach(((t,n)=>{const p=a(t);p?(c=p.oldStart,l=p.newStart):("+"!=t[0]&&c++,"-"!=t[0]&&l++);const _=o[n+1]?o[n+1][0]:"",m=o[n+2]?o[n+2][0]:"",g=t.slice(2);let h=e.dom.el("code",null,g);if(f)h=f,f=null;else if(!("-"!=t[0]||" "!=u&&"@"!=u||"+"!=_||" "!=m&&"@"!=m&&""!=m)){const i=function(t,n){const i=r(t.split("").join("\n"),n.split("").join("\n"),{context:1/0});if(!i)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 a=[],o=[];for(let t=0;t<i.length;){let n=t;const r=i[t][0];for(;i[n]&&i[n][0]==r;)n++;const s=i.slice(t,n).map((e=>e.slice(2))).join("");" "==r?(a.push(e.dom.el("code",{class:"ch-common"},s)),o.push(e.dom.el("code",{class:"ch-common"},s))):"-"==r?a.push(e.dom.el("code",{class:"ch-removed"},s)):"+"==r?o.push(e.dom.el("code",{class:"ch-added"},s)):e.Util.oops(),t=n}return{a:e.dom.el("div",{class:"inline-diff"},a),b:e.dom.el("div",{class:"inline-diff"},o)}}(t.slice(2),o[n+1].slice(2));h=i.a,f=i.b}if(u=t[0],i.hideMarkerLine&&"@"==u||i.hideRemoved&&"-"==u)return;const y="@"==u,v=`${s[u]}`;d.appendChild(e.dom.el("tr",{class:v},[!i.hideLineNumbers&&e.dom.el("td",{class:"line-a","data-content":c}),!i.hideLineNumbers&&e.dom.el("td",{class:"line-b","data-content":l}),y&&e.dom.el("td",{colspan:2,class:"change"},e.dom.el("code",null,t)),!i.hideMarker&&!y&&e.dom.el("td",{class:"marker","data-content":u}),!y&&e.dom.el("td",{class:"change"},h)]))})),p},t.resolveMergeConflictMarker=function(t,n,r,i){let a=e.diff.toLines(t),o=n;for(;o<a.length&&!/^<<<<<<<[^<]/.test(a[o]);)o++;let s=o+1;for(;s<a.length&&!/^=======$/.test(a[s]);)s++;let c=s+1;for(;c<a.length&&!/^>>>>>>>[^>]/.test(a[c]);)c++;if(c>=a.length)return e.debug(`diff marker mistmatch: ${a.length} -> ${o} ${s} ${c}`),t;if(a[o]=void 0,a[s]=void 0,a[c]=void 0,!r)for(let e=o;e<=s;++e)a[e]=void 0;if(!i)for(let e=s;e<=c;++e)a[e]=void 0;return a.filter((e=>void 0!==e)).join("\n")},t.mergeDiff3Config=function(t,n,r){let i=e.Util.jsonTryParse(t),a=e.Util.jsonTryParse(n),o=e.Util.jsonTryParse(r);if(i&&!o)return t;if(!i)return r||n;if(!a&&o&&(a=o),!i||!a||!o)return;delete i.installedVersion,delete a.installedVersion,delete o.installedVersion;const s={},c=e.U.unique(Object.keys(a).concat(Object.keys(i)).concat(Object.keys(o)),(e=>e));for(const t of c){const n=i[t],r=a[t],c=o[t];if(JSON.stringify(n)==JSON.stringify(c))void 0!==n&&(s[t]=n);else switch(t){case"name":s[t]=l(n,r,c);break;case"version":s[t]=e.semver.strcmp(n,c)>0?n:c;break;case"languageRestriction":case"preferredEditor":case"targetVersion":s[t]=n;break;case"public":s[t]=n&&c;break;case"files":case"testFiles":{const e=u(n||[],r||[],c||[]);if(!e)return;s[t]=e.length?e:void 0;break}case"dependencies":case"testDependencies":{const e=d(n||{},r||{},c||{});if(Object.keys(e).length)return;s[t]=e;break}case"description":if(n&&!c)s[t]=n;else{if(n||!c)return;s[t]=c}break;default:return}}return e.Package.stringifyConfig(s);function l(e,t,n){return e==t?n:n==t?e:e==lf("Untitled")?n:e}function u(t,n,r){const i=[],a=e.U.unique(n.concat(t).concat(r),(e=>e));for(const e of a){const a=t.indexOf(e)>-1,o=r.indexOf(e)>-1,s=n.indexOf(e)>-1;a==o||o==s?a&&i.push(e):o&&i.push(e)}return i}function d(t,n,r){const i={},a=e.U.unique(Object.keys(n).concat(Object.keys(t)).concat(Object.keys(r)),(e=>e));for(const o of a){const a=t[o],s=r[o],c=n[o];if(a==s)a&&(i[o]=a);else{const t=e.github.parseRepoId(a),n=e.github.parseRepoId(s);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 r=e.semver.strcmp(t.tag,n.tag)>0?t.tag:n.tag;i[o]=`github:${t.owner}/${t.project}#${r}`}else s==c?a&&(i[o]=a):s&&(i[o]=s)}}return i}},t.hasMergeConflictMarker=function(e){return e&&/^(<<<<<<<[^<]|>>>>>>>[^>])/m.test(e)},t.reconstructConfig=function(t,n,r,i){let a={},o=r.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)))||(i.config.files.filter((e=>o.indexOf(e)<0)).forEach((e=>{o.push(e),n[e]=i.files[e]})),e.Util.jsonCopyFrom(a,i.config.dependencies)),Object.keys(a).length||(a[e.appTarget.corepkg]="*"),{name:"",files:o,dependencies:a,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 r=`${t=t.replace(/\/$/,"")}/tag/${n}.json`;return e.Util.httpGetJsonAsync(r).then((n=>{const r=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:r[e.posters[0].user_id].username,cardType:"forumUrl"})))}))}}(e.discourse||(e.discourse={}))}(pxt||(pxt={})),function(e){!function(t){var n=pxtc.Util;let r,i={},a={};const o="\x3c!-- @CMD@ @ARGS@ --\x3e";let s={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",tutorialCodeValidation:"\x3c!-- tutorialCodeValidation --\x3e"};function c(e,t,n){return e.split(t).join(n)}function l(e){return e=c(e,"&","&"),e=c(e,"<","<"),e=c(e,">",">"),e=c(e,'"',"""),e=c(e,"'","'")}function u(e){return e?l(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=l,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 p=e=>`<div class='ui negative message'>${l(e)}</div>`;function f(e){let t=n.clone(i),r=n.clone(a),o=n.clone(s),c={},l={},d=e.params,f=e.theme;e.boxes=t,e.macros=r,e.settings=o,e.html=e.html.replace(/<aside\s+([^<>]+)>([^]*?)<\/aside>/g,((e,n,i)=>{let a=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),s=a["data-name"]||a.id;return s?(/box/.test(a.class)?t[s]=i:/aside/.test(a.class)?t[s]=`\x3c!-- BEGIN-ASIDE ${s} --\x3e${i}\x3c!-- END-ASIDE --\x3e`:/setting/.test(a.class)?o[s]=i:/menu/.test(a.class)?c[s]=i:/toc/.test(a.class)?l[s]=i:r[s]=i,`\x3c!-- macro ${s} --\x3e`):p("id or data-name missing on macro")}));let _=(e,t)=>{let n=c.item,r={NAME:e.name};if(e.subitems)n=c["toc-dropdown"]?c["toc-dropdown"]:0==t?c["top-dropdown"]:c["inner-dropdown"],r.ITEMS=e.subitems.map((e=>_(e,t+1))).join("\n");else{if(/^-+$/.test(e.name)&&(n=c.divider),e.path&&!/^(https?:|\/)/.test(e.path))return p("Invalid link: "+e.path);r.LINK=e.path}return g(n,r,["ITEMS"])},m=[{name:lf("Docs"),href:"/docs"}];const h=e.TOC||f.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)};h.forEach(v);let b=(t,n)=>{let r=l.item,i={NAME:t.name};return t.path&&!/^(https?:|\/)/.test(t.path)?p("Invalid link: "+t.path):(/^\//.test(t.path)&&e.versionPath&&(t.path=`/${e.versionPath}${t.path}`),i.LINK=t.path,y.indexOf(t)>=0?(i.ACTIVE="active",i.EXPANDED="true",m.push({name:t.name,href:t.path})):i.EXPANDED="false",t.subitems&&t.subitems.length>0?(r=l["toc-dropdown"]?""!==t.name?l["toc-dropdown"]:l["toc-dropdown-noLink"]:0==n?""!==t.name?l["top-dropdown"]:l["top-dropdown-noHeading"]:1==n?l["inner-dropdown"]:l["nested-dropdown"],i.ITEMS=t.subitems.map((e=>b(e,n+1))).join("\n")):/^-+$/.test(t.name)&&(r=l.divider),g(r,i,["ITEMS"]))};d.menu=(f.docMenu||[]).map((e=>_(e,0))).join("\n"),d.TOC=h.map((e=>b(e,0))).join("\n"),f.appStoreID&&(d.appstoremeta=`<meta name="apple-itunes-app" content="app-id=${n.htmlEscape(f.appStoreID)}"/>`);let x="";m.length>1&&(x=`\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=x,f.boardName&&(d.boardname=u(f.boardName)),f.boardNickname&&(d.boardnickname=u(f.boardNickname)),f.driveDisplayName&&(d.drivename=u(f.driveDisplayName)),f.homeUrl&&(d.homeurl=u(f.homeUrl)),d.targetid=f.id||"???",d.targetname=f.name||"Microsoft MakeCode",d.docsheader=f.docsHeader||"Documentation",d.orgtitle="MakeCode";const k=f.docsLogo&&n.htmlEscape(f.docsLogo),S=(f.organizationWideLogo||f.organizationLogo)&&n.htmlEscape(f.organizationWideLogo||f.organizationLogo),T=f.organizationLogo&&n.htmlEscape(f.organizationLogo);d.targetlogo=k?`<img aria-hidden="true" role="presentation" class="ui ${f.logoWide?"small":"mini"} image" src="${k}" />`:"",d.orglogo=S?`<img aria-hidden="true" role="presentation" class="ui image" src="${S}" />`:"",d.orglogomobile=T?`<img aria-hidden="true" role="presentation" class="ui image" src="${T}" />`:"";let C=e.ghEditURLs||[];if(C.length){let e='<p style="margin-top:1em">\n',t=lf("Edit this page on GitHub");for(let n of C)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 E=`\n <a href="#maincontent" class="ui item link" tabindex="0" role="menuitem">${lf("Skip to main content")}</a>\n `;d.accMenu=E;const D=lf("Print this page"),A=`\n <button id="printbtn" class="circular ui icon right floated button hideprint" title="${D}" aria-label="${D}">\n <i class="icon print"></i>\n </button>\n `;d.printBtn=A;const N=`\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=N;const w=["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=w[0],d.searchBar2=w[1];let I="";f.accentColor&&(I+=`\n.ui.accent { color: ${f.accentColor}; }\n.ui.inverted.accent { background: ${f.accentColor}; }\n`),d.targetstyle=I,d.tocclass=f.lightToc?"lighttoc":"inverted";for(let e of Object.keys(f)){let t=f[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 _(e){e.image=function(e,t,n){let r='<img class="ui image" src="'+e+'" alt="'+n+'"';return t&&(r+=' title="'+t+'"'),r+=' loading="lazy"',r+=this.options.xhtml?"/>":">",r},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 r=/(.*)#([\w\-]+)\s*$/.exec(e),i="";return r?(e=r[1],i=r[2]):i=n.toLowerCase().replace(/[^\w]+/g,"-"),e&&(e=e.replace(/@(fullscreen|unplugged|showdialog|showhint)/gi,"")),(e=e.trim()).match(/^\{([\s\S]+)\}$/)&&(e=e.substr(1,e.length-2)),`<h${t} id="${this.options.headerPrefix}${i}">${e}</h${t}>`}}function m(e,t){return e.replace(/<!--\s*@(ifn?def)\s+(\w+)\s*-->([^]*?)<!--\s*@endif\s*-->/g,((e,n,r,i)=>"ifdef"==n&&t[r]||"ifndef"==n&&!t[r]?`\x3c!-- ${n} ${r} --\x3e${i}\x3c!-- endif --\x3e`:`\x3c!-- ${n} ${r} endif --\x3e`))}function g(e,t,r=[]){return e?e.replace(/@(\w+)@/g,((e,i)=>{let a=n.lookup(t,i)||"";return a+="",r.indexOf(i)<0&&(a=u(a)),a})):""}t.prepTemplate=f,t.setupRenderer=_,t.renderConditionalMacros=m,t.renderMarkdown=function(e){let i=!0;e.pubinfo||(i=!1,e.pubinfo={});let a=e.pubinfo;if(e.theme||(e.theme={}),delete e.pubinfo.private,a.time){let e=parseInt(a.time);a.timems||(a.timems=1e3*e+""),a.humantime||(a.humantime=n.isoTime(e))}a.name&&(a.dirname=a.name.replace(/[^A-Za-z0-9_]/g,"-"),a.title=a.name),i&&(a.JSON=JSON.stringify(a,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,a),e.locale&&(o=y(o,e.locale).text);let s={html:o,theme:e.theme,filepath:e.filepath,versionPath:e.versionPath,ghEditURLs:e.ghEditURLs,params:a,TOC:e.TOC};f(s),r||(r=t.requireMarked());let c=new r.Renderer;_(c);const l=c.link;c.link=function(e,t,n){const r=new RegExp("^[/#]").test(e),i=r?"":"_blank";r&&s.versionPath&&(e=`/${s.versionPath}${e}`);return l.call(c,e,t,n).replace(/^<a /,`<a ${i?`target="${i}"`:""} rel="nofollow noopener" `)};let h=t.requireDOMSanitizer();r.setOptions({renderer:c,gfm:!0,tables:!0,breaks:!1,pedantic:!1,sanitize:!0,sanitizer:h,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,r)=>{let i=a[r];return!i&&e.throwOnError&&n.userError(`unknown macro ${r}`),i||"unknown macro"}));let b=r(v);b=b.replace(/<br\s*\/>/gi,"<br/>"),b=b.replace(/(<img [^>]* src=")\/docs\/static\/([^">]+)"/g,((e,t,n)=>t+"/static/"+n+'"'));let x="",k=0;function S(e,t,n){let r=n;return e<=k&&(r=x+r,x="",k=0),r}if(b=b.replace(/<h(\d)[^>]+>\s*([~@])?\s*(.*?)<\/h\d>/g,((t,r,i,o)=>{let c=/^(\w+)\s+(.*)/.exec(o),l=c?c[1]:o,d=c?c[2]:"";if(d=u(d),l=u(l),r=parseInt(r),i){if("@"==i){let t=n.lookup(s.settings,l);if(null!=t)a[l]=d;else if(t=n.lookup(s.macros,l),null==t)return e.throwOnError&&n.userError(`Unknown command: @${l}`),p(`Unknown command: @${l}`);return S(r,0,g(t,{ARGS:d,CMD:l},["ARGS","CMD"]))}{if(!l){let e=x;return x="",e}let t=n.lookup(s.boxes,l);if(t){let e=t.split("@BODY@"),n=S(r,0,e[0].replace("@ARGS@",d));x=e[1];let i=t.match(/data-[^>\s]+/gi);return i&&i.indexOf("data-inferred")>=0&&(k=r),n}return e.throwOnError&&n.userError(`Unknown box: ~ ${l}`),p(`Unknown box: ~ ${l}`)}}return S(r,0,t)})),x&&(b+=x),!a.title){let e=/<h1[^<>]*>([^<>]+)<\/h1>/.exec(b);e&&(a.title=u(e[1]))}if(!a.description){let e=/<p>([^]+?)<\/p>/.exec(b);e&&(a.description=u(e[1]))}const T=/<div class="ui embed mdvid"[^<>]+?data-placeholder="([^"]+)"[^>]*\/?>/i.exec(b)||/<img class="ui [^"]*image" src="([^"]+)"[^>]*\/?>/i.exec(b);T&&(a.cardLogo=u(T[1])),a.twitter=u(e.theme.twitter||"@msmakecode");let C={main:""};b=b.replace(/<!-- BEGIN-ASIDE (\S+) -->([^]*?)<!-- END-ASIDE -->/g,((e,t,r)=>{let i=n.lookup(C,t);return C[t]=(i||"")+r,"\x3c!-- aside --\x3e"})),b=b.replace(/\n<\/code>/g,"</code>"),C.main=b,b="";for(let e of Object.keys(C))b+=(E=e+"-container",D=C[e],g(s.boxes[E]||"@BODY@",{BODY:D},["BODY"]));var E,D;a.body=b,a.name=a.title||"";for(let t of Object.keys(e.theme)){let n=e.theme[t];"string"==typeof n&&(a["theme_"+t]=n)}return s.finish()},t.embedUrl=function(e,t,n,r){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 r=`${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="${r}" allowfullscreen="allowfullscreen" frameborder="0" sandbox="allow-scripts allow-same-origin"></iframe></div>`};const h={b:1,strong:1,em:1};function y(e,t){const r={};function i(e){let i=/^(\s*)([^]*?)(\s*)$/.exec(e),a=i[2].replace(/\s+/g," ");if(""==a||/^((IE=edge,.*|width=device-width.*|(https?:\/\/|\/)[\w@\/\.]+|@[\-\w]+@|\{[^\{\}]+\}|[^a-zA-Z]*|( )+)\s*)+$/.test(a))return null;let o=n.lookup(t,a);return o?a=o:r[a]="",i[1]+a+i[3]}function a(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 r=t.replace(/^\//,"").toLowerCase();return 1===h[r]?"&llt;"+t+n+"&ggt;":e})))).replace(/(<([\/\w]+)([^<>]*)>)([^<>]+)/g,((e,t,n,r,o)=>{if("script"==n||"style"==n)return a(e);let s=i(a(o));return null==s?a(e):t+s}))).replace(/(<[^<>]*)(content|placeholder|alt|title)="([^"]+)"/g,((e,t,n,r)=>null==i(r)?e:t+n+'="'+r.replace(/"/g,"''")+'"'))).replace(/^<start>/g,""),missing:r}}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 b(e,t){let n=0,r=[{level:0,id:"",title:"",start:n,text:"",children:[]}],i=(e=e.replace(/\r/g,"")).split(/\n/),a={};for(let e of i){let i=/^\s*(#+)\s*(.*?)(#(\S+)\s*)?$/.exec(e),o=null;if(t&&i)if(i[4])if(a[i[4]])i=null;else{o=v(t,i[4]);let e=t=>{t.id&&(a[t.id]=!0),t.children.forEach(e)};o&&e(o)}else i=null;if(i){let a={level:t?1:i[1].length,title:i[2].trim(),id:i[4]||"",start:n,text:"",children:[]};if(o){e="";for(let t=0;t<o.level;++t)e+="#";e+=" ",e+=a.title||o.title,e+=" #"+a.id}for(;r[r.length-1].level>=a.level;)r.pop();r[r.length-1].children.push(a),r.push(a)}r[r.length-1].text+=e+"\n",n++}return r[0]}t.translate=y,t.buildTOC=function(n){if(!n)return null;const r=e.docs.requireMarked(),i=t.requireDOMSanitizer(),a={renderer:new r.Renderer,gfm:!0,tables:!1,breaks:!1,pedantic:!1,sanitize:!0,sanitizer:i,smartLists:!1,smartypants:!1};let o={name:"dummy",subitems:[]},s=[];s.push(o);let c=r.lexer(n,a),l=!1;c.forEach((e=>{switch(e.type){case"heading":e.depth;break;case"list_start":break;case"list_item_start":case"loose_item_start":l=!0;let t={name:"",path:"",subitems:[]};return void s.push(t);case"text":let n=s[s.length-1];e.text.indexOf("[")>=0?e.text.replace(/\[(.*?)\]\((.*?)\)/i,(function(e,t,r){n.name=t,n.path=r.replace(".md","")})):l&&(n.name=e.text);break;case"list_item_end":case"loose_item_end":let r=s.pop();s[s.length-1].subitems.push(r)}l=!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 x=!1;function k(e,t){if(x||function(){function e(e,t,n){let r=k(e,t).trim();if(r!=(n=n.trim()))throw console.log(`*** Template:\n${e}\n*** Input:\n${t}\n*** Expected:\n${n}\n*** Output:\n${r}`),new Error("augment docs test fail")}x=!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",r="\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",i="\n# @extends\n### #ex\nFoo\n#### Example 1\nEx1\n#### Example 2x #ex2\nEx2\n## See Also These! #also\nMy links\n",a="\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,r),e(t,i,a)}(),!t)return e;let r=b(e,null),i=b(t,r),a={},o={};for(let e of i.children)n.assert(0==e.children.length),n.assert(!!e.id),a[e.id]=e.text;let s=e=>{e.id&&void 0!==a[e.id]&&(o[e.id]=!0,e.text=a[e.id],e.children=[]),e.children.forEach(s)};s(r);let c="",l=e=>{c+=e.text,e.children.forEach(l)};l(r);let u="",d=i.text.replace(/^\s*#+\s*@extends.*/gm,"").replace(/^\s*\n/gm,"");d.trim()&&(u+=d.trim()+"\n");for(let e of i.children)o[e.id]||(u+=e.text);return u&&(c+="## Couldn't apply replacement logic to:\n"+u),c}t.augmentDocs=k}(e.docs||(e.docs={}))}(pxt||(pxt={})),function(e){!function(e){e.el=function(e,t,n){const r=document.createElement(e);return t&&Object.keys(t).forEach((e=>r.setAttribute(e,t[e]+""))),function e(t){Array.isArray(t)?t.forEach((t=>e(t))):"string"==typeof t?r.appendChild(document.createTextNode(t)):t instanceof HTMLElement&&r.appendChild(t)}(n),r}}(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 r(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 i(t){const n=/```jres\s+((.|\s)+?)\s*```/i.exec(t);if(n){const t=n[1],r=JSON.parse(t);return{jres:t,ts:e.emitTilemapsFromJRes(r)}}}function a(t){const n=/```assetjson\s+((.|\s)+?)\s*```/i.exec(t);return n?e.tutorial.parseAssetJson(n[1]):{}}function o(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,r)=>{if("flags"==n)t[n]=r.split(",");else if("otherAction"===n){const e=r.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]=r;return""})),!!Object.keys(t).length&&t})).filter((e=>!!e)),(null==n?void 0:n.length)?n:void 0)}function s(t){if(!t)return[];const n=[];let r,i=!1,a="";return t.split(/\r?\n/).forEach((t=>{if(/^## /.test(t))r=t.substr(2).trim();else if(/^(### ~ |```)codecard$/.test(t))i=!0;else if(/^(### ~|```)$/.test(t)){if(i=!1,r&&a){const t=o(a);(null==t?void 0:t.length)?n.push({name:r,cards:t}):e.log("invalid gallery format")}a="",r=void 0}else i&&(a+=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=r,t.parseJResFromMarkdown=i,t.parseTemplateProjectJSON=a,t.parseExampleMarkdown=function(t,o){if(!o)return;const s=/```(blocks?|typescript|python|spy|sim)\s+((.|\s)+?)\s*```/i.exec(o);if(!s)return;const c=n(o),l=s[1],u=s[2],d=r(o),p=i(o),f={name:t,filesOverride:{[e.MAIN_BLOCKS]:'<xml xmlns="http://www.w3.org/1999/xhtml"></xml>',["python"===s[1]?e.MAIN_PY:e.MAIN_TS]:u},dependencies:c,features:d,snippetType:l,source:u};return f.filesOverride=Object.assign(Object.assign({},f.filesOverride),a(o)),p&&(f.filesOverride[e.TILEMAP_JRES]=p.jres,f.filesOverride[e.TILEMAP_CODE]=p.ts),f},t.parseCodeCards=o,t.parseCodeCardsHtml=function(t){let n,r=[];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,r=/^\s*(\w+)\s*:\s*(.*)$/.exec(t);if(r){const e=r[1];n[e]=r[2].trim(),"flags"===e&&(n[e]=n[e].split(/,\s*/))}}))):"HR"==e.tagName&&(n&&r.push(n),n=void 0)})),n&&r.push(n),0===r.length&&"CODE"===t.tagName&&(r=e.Util.jsonTryParse(t.textContent)),!!(null==r?void 0:r.length)&&r},t.parseGalleryMardown=s,t.loadGalleryAsync=function(t){return e.Cloud.markdownAsync(t).then((e=>s(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 r=t.charAt(e);"}"==r||"#"==r||"$"==r?(n+="}",n+=String.fromCharCode(32^r.charCodeAt(0))):n+=r}let r=0;t=n;for(let e=0;e<t.length;++e)r=r+t.charCodeAt(e)&255;return n="$"+t+"#"+("0"+r.toString(16)).slice(-2),e.U.stringToUint8Array(n)}decodeResp(e){let t="";for(let n=0;n<e.length;++n){let r=e[n];if("}"==r)++n,t+=String.fromCharCode(32^e.charCodeAt(n));else if("*"==r){++n;let r=e.charCodeAt(n)-29,i=t.charAt(t.length-1);for(;r-- >0;)t+=i}else{if("#"==r){return 2==e.slice(n+1,n+3).length?(this.dataBuf=e.slice(n+3),t):null}t+=r}}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 r=this.buildCmd(t);return this.q.enqueue("one",(()=>null===n?this.io.sendPacketAsync(r).then((()=>null)):new Promise((i=>{this.onResponse=r=>{this.onResponse=null,this.trace&&e.log(`GDB: '${t}' -> '${r}'`),void 0===n||n(r)||this.error(`Invalid GDB command response: '${t}' -> '${r}'`),i(r)},this.io.sendPacketAsync(r)}))))}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 r="";return this.q.enqueue("one",(()=>new Promise((i=>{this.onResponse=n=>{var a;"OK"!=n&&"O"==n[0]?r+=(a=n.slice(1),e.U.uint8ArrayToString(e.U.fromHex(a))):("OK"!=n&&(r+=" - "+n),this.onResponse=null,this.trace&&e.log(`Final GDB: '${t}' -> '${r}'`),i(r))},this.io.sendPacketAsync(n)}))))}write32Async(t,n){let r=new Uint8Array(4);return e.HF2.write32(r,0,n),this.writeMemAsync(t,r)}writeMemAsync(t,n){const r=this.pktSize/2-10;return e.U.assert(n.length<r),this.sendCmdOKAsync("M"+t.toString(16)+","+n.length.toString(16)+":"+e.U.toHex(n)).then((e=>{console.log(e)}))}readMemAsync(t,n){const r=this.pktSize/2-6;if(n>r){const i=new Uint8Array(n),a=o=>{const s=Math.min(n-o,r);return 0==s?Promise.resolve(i):this.readMemAsync(t+o,s).then((t=>(e.U.memcpy(i,o,t),a(o+s))))};return a(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,r)=>(n[t]=r,";"))),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,r;return!!t.forceProxy||!e.U.isNodeJS&&!(null===(r=null===(n=null==e?void 0:e.appTarget)||void 0===n?void 0:n.cloud)||void 0===r?void 0:r.noGithubProxy)}t.token=null,t.forceProxy=!1;const r={};function i(n){var r;return n.method=null!==(r=n.method)&&void 0!==r?r:"GET",function r(i){var a;const o=e.U.clone(n);t.token&&(o.headers||(o.headers={}),o.url==I?o.headers.Authorization=`bearer ${t.token}`:(o.url=e.BrowserUtils.cacheBustingUrl(o.url),o.headers.Authorization=`token ${t.token}`));return o.allowHttpErrors=null!==(a=o.allowHttpErrors)&&void 0!==a&&a,e.U.requestAsync(o).catch((n=>{if(e.tickEvent("github.error",{statusCode:n.statusCode}),t.handleGithubNetworkError){if(t.handleGithubNetworkError(o,n))return r(!1)}throw n}))}(t.token)}function a(e){return i({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 s(t){e.log(`github proxy error: ${t.message}`),e.debug(t)}t.isOrgAsync=function(e){return i({url:`https://api.github.com/orgs/${e}`,method:"GET",allowHttpErrors:!0}).then((e=>200==e.statusCode))};class c{constructor(){this.configs={},this.packages={}}proxyWithCdnLoadPackageAsync(t,n){const r=`${t}/${n}`;let i=this.packages[r];if(i)return e.debug(`github cache ${t}/${n}/text`),Promise.resolve(i);const a=C(t);return o(A(a.slug,n,a.fileName,"text")).then((e=>this.packages[r]={files:e}))}cacheConfig(t,n){const r=e.Package.parseAndValidConfig(n);return this.configs[t]=r,e.U.clone(r)}async loadConfigAsync(t,r){r||(r="master");const i=`${t}/${r}`;let a=this.configs[i];if(a)return e.debug(`github cache ${t}/${r}/config`),e.U.clone(a);if(n())try{const n=await this.proxyWithCdnLoadPackageAsync(t,r);return this.cacheConfig(i,n.files[e.CONFIG_NAME])}catch(e){s(e)}const o=await u(t,r,e.CONFIG_NAME);return this.cacheConfig(i,o)}async loadPackageAsync(t,r){if(r||(r="master"),n())try{return await this.proxyWithCdnLoadPackageAsync(t,r).then((t=>e.U.clone(t)))}catch(e){s(e)}return await this.githubLoadPackageAsync(t,r)}githubLoadPackageAsync(t,n){return g(t,n).then((r=>{const i=`${t}/${r}`;let a=this.packages[i];return a?(e.debug(`github cache ${t}/${n}/text`),Promise.resolve(e.U.clone(a))):(e.log(`Downloading ${t}/${n} -> ${r}`),u(t,r,e.CONFIG_NAME).then((n=>{const a={files:{}};a.files[e.CONFIG_NAME]=n;const o=JSON.parse(n);return e.U.promiseMapAll(e.allPkgFiles(o).slice(1),(e=>u(t,r,e).then((t=>{a.files[e]=t})))).then((()=>(this.packages[i]=a,e.U.clone(a))))})))}))}}function l(t,n,a){return i({url:"https://api.github.com/repos/"+A(t.slug,"contents",t.fileName,a+"?ref="+n),method:"GET"}).then((n=>{const i=n.json;return r[t.slug]=!0,i&&"base64"==i.encoding&&null!=i.content?atob(i.content):e.U.httpGetTextAsync(i.download_url)}))}function u(t,n,i){const a=C(t);return r[a.slug]?l(a,n,i):e.U.requestAsync({url:"https://raw.githubusercontent.com/"+A(a.slug,n,a.fileName,i),allowHttpErrors:!0}).then((e=>200==e.statusCode?e.text:l(a,n,i)))}function d(e,t,n,r){return i({url:/^https:/.test(e)?e:"https://api.github.com/repos/"+e,headers:n,method:r||"POST",data:t,successCodes:[200,201,202,204]}).then((e=>e.json))}function p(e,t){let n=1;for(;e.refs[t+n];)n++;return t+n}async function f(e,t,n){return await d(e+"/git/refs",{ref:"refs/heads/"+t,sha:n}),t}function _(r,i="tags",o,s){const c=C(r),l=(u=o,!!t.forceProxy||!(t.token&&!u)&&n());var u;let d=null;const p=l?e.U.httpGetJsonAsync(e.BrowserUtils.cacheBustingUrl(`${e.Cloud.apiRoot}gh/${c.slug}/refs${s?"?nocache=1":""}`)).then((t=>{let n=Object.keys(t.refs).filter((t=>e.U.startsWith(t,"refs/"+i+"/"))).map((e=>({ref:e,object:{sha:t.refs[e]}})));return d=t.refs.HEAD,n})):a(`https://api.github.com/repos/${c.slug}/git/refs/${i}/?per_page=100`);let f=e=>e.replace(/^refs\/[^\/]+\//,"");return p.then((t=>{t.sort(((t,n)=>e.semver.strcmp(f(t.ref),f(n.ref))));let n={};for(let e of t)n[f(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?a(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=C(e);return a(`https://api.github.com/repos/${n.slug}/git/refs/tags/${t}`).then(m,(e=>a(`https://api.github.com/repos/${n.slug}/git/refs/heads/${t}`).then(m)))}function h(e,n="master"){return t.db.loadConfigAsync(e,n)}function y(n,r){const i=C(n);return i?S(i,r)?(e.tickEvent("github.download.banned"),e.log("Github repo is banned"),Promise.resolve(void 0)):t.db.loadPackageAsync(i.fullName,i.tag).then((t=>{const i=w(r,n);if(i){const r=e.Package.parseAndValidConfig(t.files[e.CONFIG_NAME]);r&&(e.log(`auto-disable ${i.join(",")} due to targetconfig entry for ${n}`),r.disablesVariants=i,t.files[e.CONFIG_NAME]=e.Package.stringifyConfig(r))}return t})):(e.log("Unknown GitHub syntax"),Promise.resolve(void 0))}let v;function b(t){return e.Cloud.cdnApiUrl(`gh/${t.fullName}/icon`)}function x(e,t){var n;if(!e)return;const r={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 r.status=k(r,null==t?void 0:t.config),r}function k(e,t){return e?S(e,t)?v.Banned:function(e,t){return!!function(e,t){return!(!e||!t)&&!!(e.owner&&t.approvedOrgs&&t.approvedOrgs.some((t=>t.toLowerCase()==e.owner.toLowerCase())))}(e,t)||!(!e||!t)&&!!(e.fullName&&t.approvedRepos&&t.approvedRepos.some((t=>t.toLowerCase()==e.fullName.toLowerCase())))}(e,t)?v.Approved:v.Unknown:v.Unknown}function S(e,t){return!!function(e,t){return!(!t||e&&e.owner&&(!t.bannedOrgs||!t.bannedOrgs.some((t=>t.toLowerCase()==e.owner.toLowerCase()))))}(e,t)||!!t&&(!e||!e.fullName||!(!t.bannedRepos||!t.bannedRepos.some((t=>t.toLowerCase()==e.fullName.toLowerCase()))))}async function T(t,r){const i=C(t);if(!i)return;const c=k(i,r);if(c==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)}))}(i,c)}catch(e){s(e)}return x(await a("https://api.github.com/repos/"+i.slug),{config:r,fullName:i.fullName,fileName:i.fileName,tag:i.tag})}function C(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 r=n[1],i=n[2];let a=n[4];const o=n[6],s=a&&/^tree\/([^\/]+\/)/.exec(a);return s&&(a=a.slice(s[0].length)),{owner:r,project:i,slug:A(r,i),fullName:A(r,i,a),tag:o,fileName:a}}function E(e){return!!e&&"github:"==e.slice(0,7)}function D(e){return e?"github:"+e.fullName.toLowerCase()+"#"+(e.tag||"master"):void 0}function A(...e){return e.filter((e=>!!e)).join("/")}function N(t,n){if(!t||!t.upgrades)return null;const r=C(n);return r?e.U.lookup(t.upgrades,r.fullName.toLowerCase()):null}function w(e,t){const n=N(e,t),r=/^dv:(.*)/.exec(n);if(r){const e=r[1].split(/,/);return e.some((e=>!/^\w+$/.test(e)))?null:e}return null}t.MemoryGithubDb=c,t.downloadTextAsync=u,t.db=new c,t.authenticatedUserAsync=function(){return t.token?a("https://api.github.com/user"):Promise.resolve(void 0)},t.getCommitsAsync=function(e,t){return a("https://api.github.com/repos/"+C(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 a("https://api.github.com/repos/"+C(e).slug+"/git/commits/"+t).then((e=>a(e.tree.url+"?recursive=1").then((t=>(e.tree=t,e)))))},t.createObjectAsync=function(e,t,n){return d(C(e).slug+"/git/"+t+"s",n).then((e=>e.sha))},t.postCommitComment=function(e,t,n,r,i){return d(`${C(e).slug}/commits/${t}/comments`,{body:n,path:r,position:i}).then((e=>e.id))},t.fastForwardAsync=async function(e,t,n){const r=C(e);return 200==(await i({url:`https://api.github.com/repos/${r.slug}/git/refs/heads/${t}`,method:"PATCH",allowHttpErrors:!0,data:{sha:n,force:!1}})).statusCode},t.putFileAsync=async function(t,n,r){const a=C(t);await i({url:`https://api.github.com/repos/${e.github.join(a.slug,"contents",a.fileName,n)}`,method:"PUT",allowHttpErrors:!0,data:{message:lf("Initialize empty repo"),content:btoa(e.U.toUTF8(r)),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,r,i){const a=await d(e+"/pulls",{title:r,body:i||lf("Automatically created from MakeCode."),head:n,base:t,maintainer_can_modify:!0});return null==a?void 0:a.html_url},t.mergeAsync=function(t,n,r,a){return i({url:`https://api.github.com/repos/${C(t).slug}/merges`,method:"POST",successCodes:[201,204,409],data:{base:n,head:r,commit_message:a}}).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 a("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 p(await _(e,"heads"),t)},t.createNewBranchAsync=f,t.forkRepoAsync=async function(t,n,r="pr-"){const i=C(t),a=x(await d(`${i.slug}/forks`,{}),{fullName:i.fullName,fileName:i.fileName}),o=Date.now()+3e5;let s=null;for(;!s&&Date.now()<o;){await e.U.delay(1e3);try{s=await _(a.slug,"heads")}catch(e){}}if(!s)throw new Error(lf("Timeout waiting for fork"));const c=p(s,r);return await f(a.slug,c,n),a.fullName+"#"+c},t.listRefsAsync=function(e,t="tags",n,r){return _(e,t,n,r).then((e=>Object.keys(e.refs)))},t.listRefsExtAsync=_,t.pkgConfigAsync=h,t.downloadPackageAsync=y,t.downloadLatestPackageAsync=async function(t){const n=await e.packagesConfigAsync(),r=await e.github.latestVersionAsync(t.slug,n),i=`${t.fullName}#${r}`;return await e.github.downloadPackageAsync(i,n),{version:`github:${i}`,config:await h(t.fullName,r)}},t.cacheProjectDependenciesAsync=async function(t){var n;const r=null===(n=Object.keys(t.dependencies))||void 0===n?void 0:n.filter((e=>E(t.dependencies[e])));if(r.length){const n=await e.packagesConfigAsync();await Promise.all(r.map((async e=>{const r=t.dependencies[e];if(!await y(r,n))throw new Error(lf("Cannot load extension {0} from {1}",e,r))})))}},function(e){e[e.Unknown=0]="Unknown",e[e.Approved=1]="Approved",e[e.Banned=2]="Banned"}(v=t.GitRepoStatus||(t.GitRepoStatus={})),t.listUserReposAsync=function(){return P('{\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: "master:pxt.json") {\n ... on Blob {\n text\n }\n }\n readme: object(expression: "master: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),r=t.readme&&t.readme.text;return!!n&&(n.supportedTargets?n.supportedTargets.indexOf(e.appTarget.id)>-1:r&&r.indexOf("PXT/"+e.appTarget.id)>-1)})).map((e=>x(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=>x(e)))},t.enablePagesAsync=async function(t){const n=C(t);let r;try{const e=await a(`https://api.github.com/repos/${n.slug}/pages`);e&&(r=e.html_url)}catch(e){}if(!r)try{r=(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(r){const n=await a(`https://api.github.com/repos/${t}`);if(n&&!n.homepage)try{await d(`https://api.github.com/repos/${t}`,{homepage:r},void 0,"PATCH")}catch(t){e.tickEvent("github.homepage.error")}}},t.repoIconUrl=function(e){if(e.status==v.Approved)return b(e)},t.mkRepoIconUrl=b,t.repoStatus=k,t.repoAsync=T,t.searchAsync=function(t,n){if(!n)return Promise.resolve([]);let r=t.split("|").map(C).filter((e=>!!e));return r.length>0?Promise.all(r.map((e=>T(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=>x(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=C,t.toGithubDependencyPath=function(e,t){let n="github:"+e;return t&&(n+="#"+t),n},t.isGithubId=E,t.stringifyRepo=D,t.normalizeRepoId=function(e){const t=C(e);if(t)return t.tag=t.tag||"master",D(t)},t.join=A,t.upgradedPackageReference=function(t,n){const r=N(t,n);if(!r)return null;const i=/^min:(.*)/.exec(r),a=i&&e.semver.tryParse(i[1]);if(a){const t=C(n),r=e.semver.tryParse(t.tag);return r&&e.semver.cmp(r,a)<0?(t.tag=i[1],e.debug(`upgrading ${n} to ${i[1]}`),D(t)):(r||e.log(`not upgrading ${n} - cannot parse version`),null)}return w(t,n)||e.log(`invalid upgrade rule: ${n} -> ${r}`),n},t.upgradedPackageId=function(e,t){const n=w(e,t);return n?t+"?dv="+n.join(","):t},t.latestVersionAsync=function(t,n,r,i){const a=C(t);return a?T(a.slug,n).then((t=>{if(t)return _(t.slug,"tags",r,i).then((r=>{let i=Object.keys(r.refs);i=e.semver.sortLatestTags(i);const o=e.appTarget.versions&&e.semver.tryParse(e.appTarget.versions.target);if(o&&n.releases&&n.releases["v"+o.major]){const r=n.releases["v"+o.major].map((t=>e.github.parseRepoId(t))).filter((e=>e&&e.fullName.toLowerCase()==a.fullName.toLowerCase()))[0];if(r){if(i.some((e=>e==r.tag)))return e.debug(`approved release ${r.fullName}#${r.tag} for v${o.major}`),Promise.resolve(r.tag);e.reportError("packages",`approved release ${r.fullName}#${r.tag} for v${o.major} not found anymore`,{repo:t.fullName})}}return i[0]?Promise.resolve(i[0]):r.head||g(t.slug,t.defaultBranch)}))})):Promise.resolve(null)},t.resolveMonoRepoVersions=function(n){n=e.Util.clone(n);const r={};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:i}=t;let a=r[i.slug];a||(a=r[i.slug]={tag:i.tag,deps:[]}),a.deps.push(t),e.semver.strcmp(a.tag,i.tag)<0&&(e.debug(`dep: resolve later monorepo tag to ${e.github.stringifyRepo(i)}`),a.tag=i.tag)})),e.U.values(r).forEach((t=>t.deps.forEach((r=>{r.ghid.tag!==t.tag&&(e.debug(`dep: ${e.github.stringifyRepo(r.ghid)} -> ${t.tag}`),r.ghid.tag=t.tag,n[r.id]=e.github.stringifyRepo(r.ghid))})))),n},t.GIT_JSON=".git.json";const I="https://api.github.com/graphql";function P(e){const t=JSON.stringify({query:e});return d(I,t)}t.lookupFile=function(e,t,n){if(!t)return null;const r=A(e.fileName,n);return t.tree.tree.find((e=>e.path==r))},t.ghGraphQLQueryAsync=P,t.findPRNumberforBranchAsync=function(e,t){const n=C(e);return P(`\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 a(`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 r(e,t,n){e[t+0]=n>>0&255,e[t+1]=n>>8&255}function i(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function a(e,t){return e[t]|e[t+1]<<8}function o(e){let t=new Uint8Array(4*e.length);for(let r=0;r<e.length;++r)n(t,4*r,e[r]);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=r,t.read32=i,t.read16=a,t.encodeU32LE=o,t.decodeU32LE=function(e){let t=[];for(let n=0;n<e.length;n+=4)t.push(i(e,n));return t};let s=!1;function c(t){s?e.log("HF2: "+t):e.debug("HF2: "+t)}t.enableLog=function(){s=!0};class l{constructor(n){var r;this.io=n,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===(r=e.appTarget.appTheme.downloadDialogTheme)||void 0===r?void 0:r.deviceIcon)||"usb",this.msgs=new e.U.PromiseBuffer,this.eventHandlers={},this.jacdacAvailable=!1,this.onSerial=(e,t)=>{},this.onCustomEvent=(e,t)=>{};let a=[];n.onDeviceConnectionChanged=e=>this.disconnectAsync().then((()=>e&&this.reconnectAsync())),n.onSerial=(e,t)=>this.onSerial(e,t),n.onData=r=>{let i=r[0]&t.HF2_FLAG_MASK,o=63&r[0],s=new Uint8Array(o);if(e.U.memcpy(s,0,r,1,o),i&t.HF2_FLAG_SERIAL_OUT)this.onSerial(s,i==t.HF2_FLAG_SERIAL_ERR);else if(a.push(s),i!=t.HF2_FLAG_CMDPKT_BODY){e.U.assert(i==t.HF2_FLAG_CMDPKT_LAST);let r=0;for(let e of a)r+=e.length;let o=new Uint8Array(r),s=0;for(let t of a)e.U.memcpy(o,s,t),s+=t.length;a=[],o[2]&t.HF2_STATUS_EVENT?n.onEvent(o):this.msgs.push(o)}},n.onEvent=t=>{let n=i(t,0),r=e.U.lookup(this.eventHandlers,n+"");r?r(t.slice(4)):c("unhandled event: "+n.toString(16))},n.onError=e=>{c("recv error: "+e.message),this.autoReconnect&&(this.autoReconnect=!1,this.reconnectAsync().then((()=>{this.autoReconnect=!0}),(e=>{c("reconnect error: "+e.message)})))},this.onEvent(t.HF2_EV_JDS_PACKET,(e=>{this.onCustomEvent(t.CUSTOM_EV_JACDAC,e)}))}resetState(){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,r){e.U.assert(!!(n&t.HF2_EV_MASK)),this.eventHandlers[n+""]=r}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"))}reconnectAsync(){return this.resetState(),c(`reconnect raw=${this.rawMode}`),this.io.reconnectAsync().then((()=>this.initAsync())).catch((t=>{if(this.reconnectTries<5)return this.reconnectTries++,c(`error ${t.message}; reconnecting attempt #${this.reconnectTries}`),e.U.delay(500).then((()=>this.reconnectAsync()));throw t}))}disconnectAsync(){return c("disconnect"),this.io.disconnectAsync()}error(e){return this.io.error(e)}talkAsync(i,o){if(this.io.talksAsync)return this.io.talksAsync([{cmd:i,data:o}]).then((e=>e[0]));let s=8;o&&(s+=o.length);let l=new Uint8Array(s),u=65535&++this.cmdSeq;n(l,0,i),r(l,4,u),r(l,6,0),o&&e.U.memcpy(l,8,o,0,o.length);let d=0,p=()=>this.msgs.shiftAsync(1e3).then((e=>{if(a(e,0)!=u){if(d<3)return d++,c(`message out of sync, (${u} vs ${a(e,0)}); will re-try`),p();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(l).then(p)}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 r=new Uint8Array(64),i=a=>{let o=e.length-a;if(o<=0)return Promise.resolve();o>63?(o=63,r[0]=t.HF2_FLAG_CMDPKT_BODY):r[0]=t.HF2_FLAG_CMDPKT_LAST,n&&(r[0]=1==n?t.HF2_FLAG_SERIAL_OUT:t.HF2_FLAG_SERIAL_ERR),r[0]|=o;for(let t=0;t<o;++t)r[t+1]=e[a+t];return this.io.sendPacketAsync(r).then((()=>i(a+o)))};return this.lock.enqueue("out",(()=>i(0)))}switchToBootloaderAsync(){return this.bootloaderMode?Promise.resolve():(c("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){c("reflash"),e.U.assert(e.appTarget.compile.useUF2);const n=t.outfiles[pxtc.BINARY_UF2],r=pxtc.UF2.parseFile(e.Util.stringToUint8Array(atob(n)));return this.flashing=!0,this.io.reconnectAsync().then((()=>this.flashAsync(r))).then((()=>e.U.delay(100))).finally((()=>this.flashing=!1)).then((()=>this.reconnectAsync()))}writeWordsAsync(n,r){return e.U.assert(r.length<=64),this.talkAsync(t.HF2_CMD_WRITE_WORDS,o([n,r.length].concat(r))).then((()=>{}))}readWordsAsync(r,i){let a=new Uint8Array(8);return n(a,0,r),n(a,4,i),e.U.assert(i<=64),this.talkAsync(t.HF2_CMD_READ_WORDS,a)}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(r){let i=Date.now(),a=0,o=i=>{if(i>=r.length)return Promise.resolve();let a=r[i],s=new Uint8Array(4+a.payloadSize);return n(s,0,a.targetAddr),e.U.memcpy(s,4,a.data,0,a.payloadSize),this.talkAsync(t.HF2_CMD_WRITE_FLASH_PAGE,s).then((()=>o(i+1)))};return this.switchToBootloaderAsync().then((()=>{let e=256*r.length;return c(`Starting flash (${Math.round(e/1024)}kB).`),a=Date.now(),this.pageSize>16384?r:u(r,((e,t)=>this.readWordsAsync(e,t)))})).then((e=>{if(e.length!=r.length){let t=256*(r=e).length;c(`Performing partial flash (${Math.round(t/1024)}kB).`)}})).then((()=>o(0))).then((()=>{let e=Date.now(),t=e-i,n=e-a;c(`Flashing done at ${Math.round(256*r.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?Promise.resolve():Promise.resolve().then((()=>this.talkAsync(t.HF2_CMD_BININFO))).then((e=>(this.bootloaderMode=e[0]==t.HF2_MODE_BOOTLOADER,this.pageSize=i(e,4),this.flashSize=i(e,8)*this.pageSize,this.maxMsgSize=i(e,12),this.familyID=i(e,16),c(`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,r)=>(n[t.replace(/-/g,"")]=r,""))),this.info=n;let r=/v(\d\S+)(\s+(\S+))?/.exec(this.info.Header);this.info.Parsed=r?{Version:r[1],Features:r[3]||""}:{Version:"?",Features:""},c(`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}))}}function u(t,n){if(!e.appTarget.compile.flashChecksumAddr)return Promise.resolve(t);let r=pxtc.UF2.readBytes(t,e.appTarget.compile.flashChecksumAddr,48),a=pxtc.parseChecksumBlock(r);return a?function(t){return e.appTarget.compile.flashChecksumAddr?t(e.appTarget.compile.flashChecksumAddr,12).then((n=>{let r=pxtc.parseChecksumBlock(n);return r?t(r.endMarkerPos,1).then((t=>i(t,0)!=r.endMarker?(e.log("end-marker mismatch"),null):r)):null})):Promise.resolve(null)}(n).then((e=>{if(!e)return t;let n=e.regions.filter((e=>a.regions.some((t=>e.checksum==t.checksum&&e.length==t.length&&e.start==t.start))));if(0==n.length)return t;c("skipping flash at: "+n.map((e=>`${pxtc.assembler.tohex(e.start)} (${e.length/1024}kB)`)).join(", "));let r=e=>n.some((t=>t.start<=e&&e<t.start+t.length));return t.filter((e=>!(r(e.targetAddr)&&r(e.targetAddr+e.payloadSize-1))))})):Promise.resolve(t)}t.Wrapper=l,t.mkHF2PacketIOWrapper=function(t){return e.debug("packetio: wrapper hf2"),new l(t)},t.onlyChangedBlocksAsync=u}(e.HF2||(e.HF2={}))}(pxt||(pxt={})),function(e){!function(t){var n=e.Util,r=e.HF2;const i=r.read32;let a,o,s,c,l,u,d,p,f=!1;function _(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 r=new Uint8Array(t);return e-=d.start,n.memcpy(r,0,d.buf,e,t),Promise.resolve(r)}let r=p.maxMsgSize-32;if(t>r){let i=[];for(;t>0;){let n=Math.min(r,t);i.push(g(e,n)),t-=n,e+=n}return Promise.all(i).then(n.uint8ArrayConcat)}return p.readWordsAsync(e,Math.ceil(t/4)).then((e=>e.length>t?e.slice(0,t):e))}function h(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 i=0;return g(t.ptr,56).then((a=>{i=r.read16(a,2);let o=a.length;return i==e.BuiltInType.BoxedString||i==e.BuiltInType.BoxedBuffer?o=r.read16(a,4)+6:i==e.BuiltInType.BoxedNumber&&(o=12),o>a.length?g(t.ptr+a.length,o-a.length).then((e=>n.uint8ArrayConcat([a,e]))):o<a.length?a.slice(0,o):a})).then((t=>i==e.BuiltInType.BoxedString?n.uint8ArrayToString(t.slice(6)):i==e.BuiltInType.BoxedBuffer?{type:"buffer",data:t.slice(6)}:i==e.BuiltInType.BoxedNumber?new Float64Array(t.buffer.slice(4))[0]:{type:"unknown",tag:i,refcnt:r.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(h(e[n]).then((t=>{e[n]=t})));return Promise.all(t).then((()=>{}))}function v(e){let t=a.breakpoints,n=t[0],r=1/0;for(let i of t){let t=e-i.binAddr;t>=0&&t<r&&(r=t,n=i)}return n}function b(e){if(f)return Promise.resolve();let i;return f=!0,T().then((t=>{let o=r.decodeU32LE(e)[0],c={};for(let e of a.procDebugInfo[0].locals){let i=t.globals,a=(()=>{switch(e.type){case"uint32":return r.read32(i,e.index);case"int32":return 0|r.read32(i,e.index);case"uint16":return r.read16(i,e.index);case"int16":return r.read16(i,e.index)<<16>>16;case"uint8":return i[e.index];case"int8":return i[e.index]<<24>>24;default:return null}})();null===a&&(n.assert(0==(3&e.index)),a=m(r.read32(i,e.index))),c[e.name]=a}return l=v(o),i={type:"debugger",subtype:"breakpoint",breakpointId:l.id,globals:c,stackframes:[]},s(),p.talkAsync(1888490768)})).then((e=>{!function(e,t){let r=l.binAddr,i=0,o=a.procDebugInfo.filter((e=>e.codeStartLoc<=r&&r<=e.codeEndLoc))[0];for(;o&&o!=a.procDebugInfo[0];){let a=v(r),s=n.clone(a);s.functionName=o.name,s.argumentNames=o.args&&o.args.map((e=>e.name)),t.stackframes.push({locals:{},funcInfo:s,breakpointId:a.id});let c=t.stackframes[t.stackframes.length-1],l=0;for(let t of o.locals)n.assert(t.index==l++),c.locals[t.name]=m(e[i++]);r=2147483646&e[i++];let d=u[r+""];for(let t of o.args)c.locals[t.name]=m(e[i+(o.args.length-1-t.index)]);if(!d)break;o=d.from,i+=d.stack-o.localsMark}}(r.decodeU32LE(e),i);let t=[i.globals].concat(i.stackframes.map((e=>e.locals)));return n.promiseMapAll(t,y)})).then((()=>t.postMessage(i)))}function x(){f=!1,o=new Promise(((e,t)=>{s=e}))}function k(e=!1){return Promise.resolve().then((()=>p.talkAsync(665147697,r.encodeU32LE([e?1:3])))).then(x)}function S(){return o||(o=Promise.resolve()),o}function T(){return(c?Promise.resolve(c):p.talkAsync(1409050336).then((e=>c={numGlobals:i(e,0),globalsPtr:i(e,4)}))).then((e=>p.readWordsAsync(e.globalsPtr,e.numGlobals))).then((e=>({staticState:c,globals:e})))}t.taggedUndefined=0,t.taggedNull=_(1),t.taggedFalse=_(2),t.taggedTrue=_(16),t.postMessage=e=>console.log(e),t.decodeValue=m,t.heapExpandAsync=h,t.heapExpandMapAsync=y,t.startDebugAsync=function(e,t){return p=t,p.onEvent(915601917,b),(f=!1,a=null,c=null,Promise.resolve()).then((()=>{a=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=a.outfiles[pxtc.BINARY_UF2],t=n.stringToUint8Array(atob(e));return d=pxtc.UF2.toBin(t),p.reflashAsync(a).then((()=>p.reconnectAsync()))})).then((()=>p.talkAsync(287358355).catch((e=>{})))).then((()=>n.delay(200))).then((()=>p.reconnectAsync())).then(x).then(S)},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":k(t)}},t.resumeAsync=k,t.waitForHaltAsync=S,t.getHwStateAsync=T}(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)),r=n.charCodeAt(0),i=n.charCodeAt(1),a=n.charCodeAt(2);if(135===r&&(r=224|n.charCodeAt(1),i=n.charCodeAt(2)|n.charCodeAt(3)<<8,a=n.charCodeAt(4)|n.charCodeAt(5)<<8,n=n.slice(4)),225!=r&&228!=r)return null;if(!this.palette){let t=e.appTarget.runtime.palette.map((function(e){const t=parseInt(e.replace(/#/,""),16);return[t>>0&255,t>>8&255,t>>16&255,255]}));t[0][3]=0,this.palette=new Uint8Array(4*t.length);for(let e=0;e<t.length;++e)this.palette[4*e+0]=t[e][0],this.palette[4*e+1]=t[e][1],this.palette[4*e+2]=t[e][2],this.palette[4*e+3]=t[e][3]}if(225==r)return this.genMonochrome(n,i,a);const o=(e.BrowserUtils.isEdge()||e.BrowserUtils.isIE())&&i<100&&a<100?3:1;return this.genColor(n,i,a,o)}genMonochrome(t,n,r){let i=n+3&-4,a=54+this.palette.length,o=a+i*r,s=new Uint8Array(o);s[0]=66,s[1]=77,e.HF2.write32(s,2,o),e.HF2.write32(s,10,a),e.HF2.write32(s,14,40),e.HF2.write32(s,18,n),e.HF2.write32(s,22,-r),e.HF2.write16(s,26,1),e.HF2.write16(s,28,8),e.HF2.write32(s,38,2835),e.HF2.write32(s,42,2835),e.HF2.write32(s,46,this.palette.length>>2),s.set(this.palette,54);let c=4,l=a,u=1,d=t.charCodeAt(c++);for(let e=0;e<n;++e){l=a+e;for(let e=0;e<r;++e)s[l]=d&u?1:0,l+=i,u<<=1,256==u&&(u=1,d=t.charCodeAt(c++))}return"data:image/bmp;base64,"+btoa(e.U.uint8ArrayToString(s))}genColor(t,n,r,i){const a=n*(i=Math.max(1,0|i)),o=r*i;let s=a<<2,c=138,l=c+s*o,u=new Uint8Array(l);u[0]=66,u[1]=77,e.HF2.write32(u,2,l),e.HF2.write32(u,10,c),e.HF2.write32(u,14,124),e.HF2.write32(u,18,a),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,p=c,f=!0;for(let e=0;e<a;e++){let n=!1;p=c+(e<<2);let a=d,l=t.charCodeAt(d++),_=n?(l>>4&15)<<2:(15&l)<<2;for(let e=0;e<o;e++)l&&(f=!1),u[p]=this.palette[_],u[p+1]=this.palette[_+1],u[p+2]=this.palette[_+2],u[p+3]=this.palette[_+3],p+=s,e%i==i-1&&(n&&(l=t.charCodeAt(d++)),n=!n,_=n?(l>>4&15)<<2:(15&l)<<2);if(f&&(u[141]=1),e%i==i-1)for(r%2||--d;3&d;)d++;else d=a}return"data:image/bmp;base64,"+btoa(e.U.uint8ArrayToString(u))}}}(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("Blocks preview")}\n\n${lf("This image shows the blocks code from the last commit in master.")}\n${lf("This image may take a few minutes to refresh.")}\n\n\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_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 },\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 }\n}',".github/workflows/makecode.yml":"name: MakeCode\n\non: [push]\n\njobs:\n build:\n\n runs-on: ubuntu-latest\n\n strategy:\n matrix:\n node-version: [14.x]\n\n steps:\n - uses: actions/checkout@v1\n - name: Use Node.js ${{ matrix.node-version }}\n uses: actions/setup-node@v1\n with:\n node-version: ${{ matrix.node-version }}\n - name: npm install\n run: |\n npm install -g pxt\n pxt target @TARGET@\n - name: build\n run: |\n pxt install\n pxt build --cloud\n env:\n CI: true\n",".github/workflows/cfg-check.yml":"name: Check pxt.json\n\non:\n push:\n branches:\n - 'master'\n - 'main'\n\njobs:\n check-cfg:\n runs-on: ubuntu-latest\n strategy:\n matrix:\n node-version: [14.x]\n steps:\n - uses: actions/checkout@v2\n - name: Use Node.js ${{ matrix.node-version }}\n uses: actions/setup-node@v1\n with:\n node-version: ${{ matrix.node-version }}\n - name: npm install\n run: |\n npm install -g pxt\n pxt target @TARGET@\n - name: Checkout current state\n run: |\n git checkout -- .\n git clean -fd\n - name: Fix files listed in config if necessary\n run: pxt checkpkgcfg\n - name: Create Pull Request\n uses: peter-evans/create-pull-request@v3\n continue-on-error: true\n with:\n title: 'Removing missing files from pxt.json'\n commit-message: 'Removing missing files from pxt.json'\n delete-branch: true\n",".vscode/tasks.json":'\n// A task runner that calls the MakeCode (PXT) compiler\n{\n "version": "2.0.0",\n "tasks": [{\n "label": "pxt deploy",\n "type": "shell",\n "command": "pxt deploy --local",\n "group": "build",\n "problemMatcher": [ "$tsc" ]\n }, {\n "label": "pxt build",\n "type": "shell",\n "command": "pxt build --local",\n "group": "build",\n "problemMatcher": [ "$tsc" ]\n }, {\n "label": "pxt install",\n "type": "shell",\n "command": "pxt install",\n "group": "build",\n "problemMatcher": [ "$tsc" ]\n }, {\n "label": "pxt clean",\n "type": "shell",\n "command": "pxt clean",\n "group": "test",\n "problemMatcher": [ "$tsc" ]\n }]\n}\n'},n=r();return n&&Object.keys(n).forEach((t=>e[t]=n[t])),e}function r(){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=r,t.TEMPLATE_PRJ="template",t.packageFiles=function(t){const r=e.appTarget.blocksprj||e.appTarget.tsprj,i=e.U.clone(r.config);delete i.installedVersion,delete i.additionalFilePath,delete i.additionalFilePaths,i.preferredEditor=i.files.find((e=>/\.blocks$/.test(e)))?e.BLOCKS_PROJECT_NAME:e.JAVASCRIPT_PROJECT_NAME,i.name=t,i.public=!0,i.version||(i.version="0.0.0");const a={},o=n();for(const e in o)a[e]=o[e];for(const e in r.files)"README.md"!=e&&(a[e]=r.files[e]);const s=Object.keys(a).filter((e=>/\.(blocks|md|ts|asm|cpp|h|py)$/.test(e)));return i.files=s.filter((e=>!/test/.test(e))),i.testFiles=s.filter((e=>/test/.test(e))),i.supportedTargets=[e.appTarget.id],a[e.CONFIG_NAME]=e.Package.stringifyConfig(i),a},t.packageFilesFixup=function(t,n){const r=JSON.parse(t[e.CONFIG_NAME]);n&&e.Util.jsonMergeFrom(r,n),e.webConfig&&(Object.keys(e.webConfig).forEach((t=>r[t.toLowerCase()]=e.webConfig[t])),r.platform=e.appTarget.platformid||e.appTarget.id,r.target=e.appTarget.id,r.docs=e.appTarget.appTheme.homeUrl||"./",r.homeurl=e.appTarget.appTheme.homeUrl||"???"),e.U.iterMap(t,((e,n)=>{n=n.replace(/@([A-Z]+)@/g,((e,t)=>r[t.toLowerCase()]||"")),t[e]=n}))}}(e.template||(e.template={}))}(pxt||(pxt={})),function(e){!function(t){let n,r;!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"}(r=t.GlueMode||(t.GlueMode={}));const i=["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 a(e){return"`"+e.replace(/[\\`${}]/g,(e=>"\\"+e))+"`"}function o(e){return e.length>20&&/\n/.test(e)?a(e):JSON.stringify(e)}function s(e,t,n){return{type:e,op:t,children:n}}function c(){return s(n.NewLine,"",[])}function l(e,t){return s(n.Prefix,e,t)}function u(e,t,r){return s(n.Infix,t,null==e?[r]:[e,r])}function d(e){return l(e,[])}function p(e){return s(n.Block,"",e)}function f(e){return l("",e)}function _(e,t=!1){const n=[];for(const r of e)t?(n.length>0&&n.push(d(",")),n.push(c())):n.length>0&&n.push(d(", ")),n.push(r);return t&&n.push(c()),f(n)}let m;t.backtickLit=a,t.stringLit=o,t.mkNode=s,t.mkNewLine=c,t.mkPrefix=l,t.mkPostfix=function(e,t){return s(n.Postfix,t,e)},t.mkInfix=u,t.mkText=d,t.mkBlock=p,t.mkGroup=f,t.mkStmt=function(...e){let t=e[e.length-1];return t&&t.type==n.Block||e.push(c()),f(e)},t.mkCommaSep=_,function(t){function n(e,t,n=!1,r=!1){return f(r?[u(t[0],".",d(e)),d("("),_(t.slice(1),n),d(")")]:[d(e),d("("),_(t,n),d(")")])}function r(e,t,r,i){return n(e+"."+t,r,i)}function i(t,n){return e.U.assert(2==n.length),u(n[0],t,n[1])}t.mkArrayLiteral=function(e,t){return f([d("["),_(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 f([u(t,".",d(e))])},t.mkCall=n,t.stdCall=function(e,t,r){return n(e,t,r)},t.extensionCall=function(e,t,r){return n(e,t,r,!0)},t.namespaceCall=r,t.mathCall=function(e,t){return r("Math",e,t,!1)},t.mkGlobalRef=function(e){return d(e)},t.mkSimpleCall=i,t.mkWhile=function(e,t){return f([d("while ("),e,d(")"),p(t)])},t.mkComment=function(e){return d("// "+e)},t.mkMultiComment=function(e){let t=[d("/**"),c()];return e.split("\n").forEach(((e,n,r)=>{e&&(t.push(d(" * "+e)),t.push(c()),n<r.length-1&&(t.push(d(" * ")),t.push(c())))})),f(t.concat([d(" */"),c()]))},t.mkAssign=function(e,t){return i("=",[e,t])},t.mkParenthesizedExpression=function(e){return y(h([e]).output)?e:f([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 h(t){let i=[],a={},o="",s="",c=[{}],l=0;function u(e){"string"==typeof e&&(l+=(e.match(/\n/g)||[]).length),o+=e}let p=f(t);return function t(r,i){if(r.type!=n.Infix){for(let e of r.children)t(e,-1);return}let a=[];function o(e){"P"==e[0]&&(e=e.slice(1)),a.push(d(e))}let s=e.U.lookup(g,r.op);if(null==s&&e.U.oops("bad infix op: "+r.op),s<i&&o("("),1==r.children.length)o(r.op),t(r.children[0],s),a.push(r.children[0]);else{let e,n=3!=s&&"**"!=r.op;t(r.children[0],n?s:s+.1),a.push(r.children[0]),e&&"number"!=e&&(o(": "),o(e)),"."==r.op?o("."):o(" "+r.op+" "),t(r.children[1],n?s+.1:s),a.push(r.children[1])}s<i&&o(")"),r.type=n.Prefix,r.op="",r.children=a}(p,-1),_(p),o||u("\n"),{output:o,sourceMap:i};function _(t){t.glueToBlock&&(h(),t.glueToBlock==r.WithSpace&&u(" "));let d=l,p=o.length;switch(t.type){case n.Infix:e.U.oops("no infix should be left");break;case n.NewLine:u("\n"+s);break;case n.Block:!function(t){let n=t.noFinalNewline?"":"\n";if(0==t.children.length)return void m(" {\n\t\n}"+n);let r=e.U.clone(c[c.length-1]||{});c.push(r),s+=" "," "!=o[o.length-1]&&m(" ");m("{\n");for(let e of t.children)_(e);s=s.slice(4),h(),m("\n}"+n),c.pop()}(t);break;case n.Prefix:t.canIndentInside?u(t.op.replace(/\n/g,"\n"+s+" ")):u(t.op),t.children.forEach(_);break;case n.Postfix:t.children.forEach(_),t.canIndentInside?u(t.op.replace(/\n/g,"\n"+s+" ")):u(t.op)}let f=l,g=Math.max(o.length,1);if(t.id)if(a[t.id]){const e=a[t.id];e.startLine=Math.min(e.startLine,d),e.endLine=Math.max(e.endLine,f),e.startPos=Math.min(e.startPos,p),e.endPos=Math.max(e.endPos,g)}else{const e={id:t.id,startLine:d,startPos:p,endLine:f,endPos:g};a[t.id]=e,i.push(e)}}function m(e){u(e.replace(/\n/g,"\n"+s))}function h(){o=o.replace(/\n *$/,(function(){return l--,""}))}}function y(e){if("("!==e[0]||")"!==e[e.length-1])return!1;let t=1;for(let n=1;n<e.length;n++){const r=e[n];if("("===r)t++;else if(")"===r&&(t--,0===t))return n===e.length-1}return!1}t.flattenNode=h,t.isReservedWord=function(e){return-1!==i.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";class r{constructor(e,t,n=0,r=0,i){this.width=e,this.height=t,this.x0=n,this.y0=r,this.width||(this.width=16),this.height||(this.height=16),this.buf=i||new Uint8ClampedArray(this.dataLength())}static fromData(e){return new r(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 r=this.coordToIndex(e,t);this.setCore(r,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,i=this.height){const a=new r(n,i);a.x0=e,a.y0=t;for(let r=0;r<n;r++)for(let n=0;n<i;n++)a.set(r,n,this.get(e+r,t+n));return a}apply(e,t=!1){let n;for(let r=0;r<e.width;r++)for(let i=0;i<e.height;i++)n=e.get(r,i),!n&&t||this.set(e.x0+r,e.y0+i,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 p(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=r;class i extends r{static fromData(e){return new i(e.width,e.height,e.x0,e.y0,e.data)}copy(e=0,t=0,n=this.width,r=this.height){const a=new i(n,r);a.x0=e,a.y0=t;for(let i=0;i<n;i++)for(let n=0;n<r;n++)a.set(i,n,this.get(e+i,t+n));return a}resize(e,t){return f(this,e,t)}getCore(e){return this.buf[e]}setCore(e,t){this.buf[e]=t}dataLength(){return this.width*this.height}}t.Tilemap=i;class a{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:r.fromData(e.bitmap).copy().data()})))},n=r.fromData(this.layers).copy().data();return new a(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=a;function o(e){return s(atob(e.slice(e.indexOf(",")+1)))}function s(t){let n=t.charCodeAt(0),r=t.charCodeAt(1),i=t.charCodeAt(2);135===n&&(n=224|t.charCodeAt(1),r=t.charCodeAt(2)|t.charCodeAt(3)<<8,i=t.charCodeAt(4)|t.charCodeAt(5)<<8,t=t.slice(4));const a=new e.sprite.Bitmap(r,i);let o=4;if(225===n){let e=1,n=t.charCodeAt(o++);for(let s=0;s<r;++s)for(let r=0;r<i;++r)a.set(s,r,n&e?1:0),e<<=1,256==e&&(e=1,n=t.charCodeAt(o++))}else for(let e=0;e<r;e++){for(let n=0;n<i;n+=2){let r=t.charCodeAt(o++);a.set(e,n,15&r),n!=i-1&&a.set(e,n+1,r>>4&15)}for(;3&o;)o++}return a}function c(e,t){!(e=(e=(e=e.replace(/[ `]|(?:`)|(?:	)|(?:hex)/g,"").trim()).replace(/^["`\(\)]*/,"").replace(/["`\(\)]*$/,"")).replace(/ /g,"\n"))&&t&&(e=t);const n=parseInt(e.substr(0,2),16)|parseInt(e.substr(2,2),16)<<8,r=parseInt(e.substr(4,2),16)|parseInt(e.substr(6,2),16)<<8,a=x(e.substring(8));return i.fromData({width:n,height:r,x0:0,y0:0,data:a})}function l(e){return`${d(e.width,2)}${d(e.height,2)}${k(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=_(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.transparency32":return t.getTransparency(32);default:return t.resolveTile(e)}}(e,t))):[]}function d(e,t){let n=e.toString(16);const r=t<<1;for(1&n.length&&(n="0"+n);n.length<r;)n+="0";return n}function p(e,t,n){const i=new r(t,n);return i.apply(e),i}function f(e,t,n){const r=new i(t,n);return r.apply(e),r}function _(e){const t=(e=(e=(e=e.replace(/[ `]|(?:`)|(?:	)|(?:img)/g,"").trim()).replace(/^["`\(\)]*/,"").replace(/["`\(\)]*$/,"")).replace(/ /g,"\n")).split("\n"),n=[];let i=0;for(let e=0;e<t.length;e++){const r=t[e],a=[];for(let e=0;e<r.length;e++)switch(r[e]){case"0":case".":a.push(0);break;case"1":case"#":a.push(1);break;case"2":case"T":a.push(2);break;case"3":case"t":a.push(3);break;case"4":case"N":a.push(4);break;case"5":case"n":a.push(5);break;case"6":case"G":a.push(6);break;case"7":case"g":a.push(7);break;case"8":a.push(8);break;case"9":a.push(9);break;case"a":case"A":case"R":a.push(10);break;case"b":case"B":case"P":a.push(11);break;case"c":case"C":case"p":a.push(12);break;case"d":case"D":case"O":a.push(13);break;case"e":case"E":case"Y":a.push(14);break;case"f":case"F":case"W":a.push(15);break;default:if(!/\s/.test(r[e]))return}a.length&&(n.push(a),i=Math.max(i,a.length))}const a=n.length,o=new r(i,a);for(let e=0;e<a;e++){const t=n[e];for(let n=0;n<i;n++)n<t.length?o.set(n,e,t[n]):o.set(n,e,0)}return o}function m(e){let t="";switch(e){case"python":t='img("""';break;default:t="img`"}return t}function g(e){let t="";switch(e){case"python":t+='""")';break;default:t+="`"}return t}function h(e,t){if(!e||0===e.height||0===e.width)return"";let r=m(t);if(e){const t=e.width*e.height>300?"":" ";for(let i=0;i<e.height;i++){r+="\n";for(let a=0;a<e.width;a++)r+=n[e.get(a,i)]+t}}return r+="\n",r+=g(t),r}function y(t,n){return e.sprite.Bitmap.fromData(t).equals(e.sprite.Bitmap.fromData(n))}function v(e){switch(e){case 8:return"TileScale.Eight";case 16:return"TileScale.Sixteen";case 32:return"TileScale.ThirtyTwo";default:return Math.floor(Math.log2(e)).toString()}}function b(e){switch(e=e.replace(/\s/g,"")){case"TileScale.Eight":return 8;case"TileScale.Sixteen":return 16;case"TileScale.ThirtyTwo":return 32;default:return Math.pow(2,parseInt(e))}}function x(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 k(e){const t="0123456789abcdef";let n="";for(let r=0;r<e.length;++r)n+=t[e[r]>>4],n+=t[15&e[r]];return n}function S(e,t,n){e[t]=255&n,e[t+1]=n>>8&255}function T(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[C(t),E(t),D(t)]}function C(e){return e>>16&255}function E(e){return e>>8&255}function D(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,r=n>>3,i=7&n;this.mask[r]|=1<<i}get(e,t){const n=e+this.width*t,r=n>>3,i=7&n;return this.mask[r]>>i&1}},t.encodeTilemap=function(e,t){return e?`tiles.createTilemap(${function(e){return e?`hex\`${l(e)}\``:"hex``"}(e.tilemap)}, ${h(r.fromData(e.layers),t)}, [${e.tileset.tiles.map((e=>function(e,t){return e.id}(e)))}], ${v(e.tileset.tileWidth)})`:"null"},t.decodeTilemap=function(t,n,r){if(!(t=e.Util.htmlUnescape(t).trim()).trim())return null;const i=(t=(t=t.substr(t.indexOf("(")+1)).substr(0,t.lastIndexOf(")"))).substr(0,t.indexOf(",")),o=(t=t.substr(i.length+1)).substr(0,t.indexOf(",")),s=(t=t.substr(o.length+1)).substr(0,t.lastIndexOf("]")+1),l=t=t.substr(s.length+1);return new a(c(i),{tiles:u(s,r),tileWidth:b(l)},_(o).data())},t.trimTilemapTileset=function(e){const t=e.tileset.tiles.slice(),n=e.tilemap,r={};r[t[0].id]=!0;for(let e=0;e<n.width;e++)for(let i=0;i<n.height;i++)r[t[n.get(e,i)].id]=!0;const i=e.editedTiles||[],a=t.filter((e=>r[e.id]||"*"===e.id.charAt(0)||-1!==i.indexOf(e.id)));if(a.length===t.length)return;const o=[];for(let e=0;e<t.length;e++)o.push(a.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=a},t.isEmptyTilemap=function(e){const t=e.tileset.tiles,n=e.tilemap,r=t[0].id;for(let e=0;e<n.width;e++)for(let i=0;i<n.height;i++)if(t[n.get(e,i)].id!==r)return!1;return!0},t.computeAverageColor=function(e,t){const n=t.map(T),r=[0,0,0];let i=0;for(let t=0;t<e.width;t++)for(let a=0;a<e.height;a++){const o=e.get(t,a);if(o){++i;const e=n[o];r[0]+=e[0],r[1]+=e[1],r[2]+=e[2]}}return i?"#"+function(e){let t="";for(let n=0;n<e.length;++n)t+=("0"+e[n].toString(16)).slice(-2);return t}(r.map((e=>Math.floor(e/i)))):"#00000000"},t.getBitmap=function(e,t){const n=e.apis.byQName[t];return n?o(n.attributes.jresURL):null},t.getBitmapFromJResURL=o,t.hexToBitmap=s,t.filterItems=function(e,t){const n=(t=t.filter((e=>!!e)).map((e=>e.toLowerCase()))).filter((e=>0!==e.indexOf("!"))),r=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 r.every((t=>!e.tags.some((e=>e===t))))}(e);var t}))},t.getGalleryItems=function(n,r){let i=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 r=e.byQName[t];return!(!r||!r.extendsTypes)&&r.extendsTypes.indexOf(n)>=0}(t,e.retType,n)))}(n.apis,r);return i=i.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))}))}(i),i.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=r.fromData(t),i=pxtc.f4EncodeImg(t.width,t.height,4,((e,t)=>n.get(e,t)));return btoa(e.U.uint8ArrayToString(x(i)))},t.tilemapLiteralToTilemap=c,t.hexEncodeTilemap=l,t.formatByte=d,t.resizeBitmap=p,t.resizeTilemap=f,t.imageLiteralToBitmap=_,t.encodeAnimationString=function(t,n){const r=t.map((e=>e.data)),i=new Uint8ClampedArray(8+r[0].length*r.length);S(i,0,n),S(i,2,t[0].width),S(i,4,t[0].height),S(i,6,t.length);let a=8;return r.forEach((e=>{i.set(e,a),a+=e.length})),btoa(e.sprite.uint8ArrayToHex(i))},t.addMissingTilemapTilesAndReferences=function(e,t){const n=e.getProjectTiles(t.data.tileset.tileWidth,!0);t.data.projectReferences=[];for(const r of n.tiles)t.data.tileset.tiles.some((e=>e.id===r.id))||t.data.tileset.tiles.push(r),e.isAssetUsed(r,null,[t.id])&&t.data.projectReferences.push(r.id)},t.updateTilemapReferencesFromResult=function(t,n){const r=n.data;if(r.deletedTiles)for(const e of r.deletedTiles)t.deleteTile(e);if(r.editedTiles)for(const e of r.editedTiles){const n=r.tileset.tiles.findIndex((t=>t.id===e)),i=r.tileset.tiles[n];i&&(r.tileset.tiles[n]=t.updateTile(i))}for(let e=0;e<r.tileset.tiles.length;e++){const n=r.tileset.tiles[e];n.jresData||(r.tileset.tiles[e]=t.resolveTile(n.id))}e.sprite.trimTilemapTileset(r)},t.imageLiteralFromDimensions=function(e,t,r,i){let a=m(i);const o=e*t>300?"":" ";for(let i=0;i<t;i++){a+="\n";for(let t=0;t<e;t++)a+=n[r]+o}return a+="\n",a+=g(i),a},t.bitmapToImageLiteral=h,t.bitmapEquals=y,t.tileWidthToTileScale=v,t.tileScaleToTileWidth=b,t.hexToUint8Array=x,t.uint8ArrayToHex=k,t.colorStringToRGB=T}(e.sprite||(e.sprite={}))}(pxt||(pxt={})),function(e){!function(t){!function(n){const r=new RegExp(`^\\s*${t.TILE_NAMESPACE}\\s*\\.\\s*${t.TILE_PREFIX}(\\d+)\\s*$`);class i{constructor(e,t,n){this.tilemap=e,this.tileset=t,this.layers=n,this.nextId=0}}function a(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=r.exec(e);if(n)return{data:null,projectId:Number(n[1])};return{data:null,qualifiedName:e}}(e))):[]}n.LegacyTilemapData=i,n.decodeTilemap=function(n,r){var o;if(!(null==(n=null===(o=e.Util.htmlUnescape(n))||void 0===o?void 0:o.trim())?void 0:n.trim()))return new i(new t.Tilemap(16,16),{tileWidth:16,tiles:[]},new t.Bitmap(16,16).data());const s=(n=(n=n.substr(n.indexOf("(")+1)).substr(0,n.lastIndexOf(")"))).substr(0,n.indexOf(",")),c=(n=n.substr(s.length+1)).substr(0,n.indexOf(",")),l=(n=n.substr(c.length+1)).substr(0,n.lastIndexOf("]")+1),u=n=n.substr(l.length+1);return new i(t.tilemapLiteralToTilemap(s),{tiles:a(l),tileWidth:t.tileScaleToTileWidth(u)},t.imageLiteralToBitmap(c).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 r{constructor(e){this.storageId=e}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 r=window.localStorage.key(n);0==r.indexOf(e)&&t.push(r)}t.forEach((e=>window.localStorage.removeItem(e)))}}function i(){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 a;function o(){if(a)return;const t=i();let o=!1;if(!e.shell.isSandboxMode())try{window.localStorage[t]="1";window.localStorage[t];o=!0}catch(e){}o?(a=new r(t),e.debug(`storage: local under ${t}`)):(a=new n,e.debug("storage: in memory"))}t.storageId=i,t.setLocal=function(e,t){o(),a.setItem(e,t)},t.getLocal=function(e){return o(),a.getItem(e)},t.removeLocal=function(e){o(),a.removeItem(e)},t.clearLocal=function(){o(),a.clear()}}(e.storage||(e.storage={}))}(pxt||(pxt={})),function(e){!function(t){!function(t){const n="http://localhost:3232/api/store/";function r(){return e.BrowserUtils.isLocalHostDev()&&!e.BrowserUtils.noSharedLocalStorage()}function i(){return e.BrowserUtils.isChromiumEdge()?"chromium-edge":e.BrowserUtils.browser()}t.getAsync=async function(t,a){if(r()){t+="-"+i();const r=await e.Util.requestAsync({url:`${n}${encodeURIComponent(t)}/${encodeURIComponent(a)}`,method:"GET",allowHttpErrors:!0});return r.json?r.json:r.text?r.text:void 0}{const n=e.storage.getLocal(`${t}:${a}`),r=e.Util.jsonTryParse(n);return r||n}},t.setAsync=async function(t,a,o){if(void 0===o)return void await e.storage.shared.delAsync(t,a);let s="";if(s="object"==typeof o?JSON.stringify(o):o.toString(),r()){t+="-"+i();const r={type:"object"==typeof o?"json":"text",val:s},c=JSON.stringify(r);await e.Util.requestAsync({url:`${n}${encodeURIComponent(t)}/${encodeURIComponent(a)}`,method:"POST",data:c})}else e.storage.setLocal(`${t}:${a}`,s)},t.delAsync=async function(t,a){r()?(t+="-"+i(),await e.Util.requestAsync({url:`${n}${encodeURIComponent(t)}/${encodeURIComponent(a)}`,method:"DELETE",allowHttpErrors:!0})):e.storage.removeLocal(`${t}:${a}`)}}(t.shared||(t.shared={}))}(e.storage||(e.storage={}))}(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,r){this.id=e,this._verspec=t,this.parent=n,this.level=-1,this.isLoaded=!1,this.ignoreTests=!1,this.cppOnly=!1,r&&(this.level=r.level+1),this.addedBy=[r]}static stringifyConfig(e){const n=e,r={};for(const e of t)n.hasOwnProperty(e)&&(r[e]=n[e]);for(const e of Object.keys(n))r.hasOwnProperty(e)||(r[e]=n[e]);return JSON.stringify(r,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 getConfigAsync(t,n,r){return Promise.resolve().then((()=>{if(e.github.isGithubId(r)){const t=e.github.parseRepoId(r);return e.packagesConfigAsync().then((n=>e.github.repoAsync(t.fullName,n))).then((n=>n?e.github.pkgConfigAsync(t.fullName,t.tag):null))}{const i=e.patching.upgradePackageReference(t,n,r),a=e.appTarget.bundledpkgs[i];return JSON.parse(a[e.CONFIG_NAME])}}))}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}commonDownloadAsync(){const t=this.verProtocol();if("pub"==t)return e.Cloud.downloadScriptFilesAsync(this.verArgument());if("github"==t)return e.packagesConfigAsync().then((t=>e.github.downloadPackageAsync(this.verArgument(),t))).then((e=>e.files));if("embed"==t){const t=e.getEmbeddedScript(this.verArgument());return Promise.resolve(t)}if("pkg"==t){const t=(this.parent||this).readFile(this.verArgument()),n=ts.pxtc.Util.jsonTryParse(t);return n||e.log(`unable to find ${this.verArgument()}`),Promise.resolve(n)}return Promise.resolve(null)}host(){return this.parent._host}readFile(e){return this.host().readFile(this,e)}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")&&r(JSON.parse(this.readFile(n)),t);return t}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 r=e.github.parseRepoId(this._verspec);if(r&&!r.tag&&this.parent){e.debug("dep: unbound github extensions, trying to resolve tag");const i=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)===r.slug)).map((e=>e.tag)))[0];i&&(r.tag=i,this.resolvedVersion=n=e.github.stringifyRepo(r),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(),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 r=null;const i=e.patching.computePatches(this.targetVersion(),"missingPackage");return i&&i.forEach((e=>{Object.keys(e.map).forEach((n=>{e.map[n]===t&&(r=new RegExp(n,"g"))}))})),r||(r=new RegExp(t+"\\.","g")),r.test(n)}upgradePackagesAsync(){return this.config||this.loadConfig(),e.packagesConfigAsync().then((t=>{let n=0,r={};return e.U.iterMap(this.config.dependencies,((i,a)=>{if(e.github.isGithubId(a)){const o=e.github.upgradedPackageReference(t,a);o&&o!=a&&(e.log(`upgrading dep ${i}: ${a} -> ${o}`),r[a]=o,this.config.dependencies[i]=o,n++)}})),n&&this.saveConfig(),n&&r}))}getMissingPackages(t,n){const r=e.patching.computePatches(this.targetVersion(),"missingPackage"),i={};return n&&r&&r.forEach((e=>{Object.keys(e.map).forEach((r=>{const a=new RegExp(r,"g"),o=e.map[r];n.replace(a,(e=>(t.dependencies[o]||(i[o]="*"),"")))}))})),i}findConflictsAsync(t,r){let i,a=[];return Promise.resolve().then((()=>"string"==typeof t?n.getConfigAsync(this.targetVersion(),t,r):Promise.resolve(t))).then((t=>{if(i=t,i){const t=i.yotta?e.U.jsonFlatten(i.yotta.config):null;this.parent.sortedDeps().forEach((n=>{if(i.core&&n.config.core&&i.name!=n.config.name){const t=new e.cpp.PkgConflictError(lf("conflict between core extensions {0} and {1}",i.name,n.id));return t.pkg0=n,void a.push(t)}let o=!1;if(t){const r=n.config||JSON.parse(n.readFile(e.CONFIG_NAME));if(!!r&&!!r.yotta&&!!n.config.yotta.config){const s=e.U.jsonFlatten(r.yotta.config);for(const c of Object.keys(t)){const l=s[c],u=i.yotta.configIsJustDefaults||r.yotta.configIsJustDefaults;if(s.hasOwnProperty(c)&&l!==t[c]&&!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}",c,i.name,n.id));t.pkg0=n,t.settingName=c,a.push(t),o=!0}}}}if(!o&&i.name===n.id&&n._verspec!==r&&!/^file:/.test(n._verspec)&&!/^file:/.test(r)){const t=/^github:/.test(n._verspec)&&e.github.parseRepoId(n._verspec),i=/^github:/.test(r)&&e.github.parseRepoId(r);if(!t||!i||t.fullName!==i.fullName||i.tag&&e.semver.strcmp(t.tag,i.tag)<0){const t=new e.cpp.PkgConflictError(lf("version mismatch for extension {0} (installed: {1}, installing: {2})",n.id,n._verspec,r));t.pkg0=n,t.isVersionConflict=!0,a.push(t)}}}))}return Object.keys(i.dependencies).reduce(((e,t)=>e.then((()=>this.findConflictsAsync(t,i.dependencies[t]))).then((e=>a.push.apply(a,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 a.forEach((a=>{n.push.apply(n,t(a.pkg0).map((t=>{const n=new e.cpp.PkgConflictError(a.isVersionConflict?lf("a dependency of {0} has a version mismatch with extension {1} (installed: {1}, installing: {2})",t.id,i.name,a.pkg0._verspec,r):lf("conflict on yotta setting {0} between extensions {1} and {2}",a.settingName,i.name,a.pkg0.id));return n.pkg0=t,n})))})),a.push.apply(a,n),a=a.filter(((e,t)=>{for(let n=0;n<t;++n)if(e.pkg0.id===a[n].pkg0.id)return!1;return!0})),a}))}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 r=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)!=r&&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,r)=>{("*"!=r||e.appTarget.bundledpkgs[t])&&(n[t]=r)})),t&&this.config.cppDependencies&&e.Util.jsonMergeFrom(n,this.config.cppDependencies),n}loadAsync(t=!1,r){if(this.isLoaded)return Promise.resolve();let i=Promise.resolve();0!=this.level||e.appTarget.multiVariants||e.setAppTargetVariant(null),this.isLoaded=!0;const a=this.readFile(e.CONFIG_NAME);null==a?t||e.U.userError("Package not installed: "+this.id+", did you forget to run `pxt install`?"):i=i.then((()=>this.parseConfig(a))),0!=this.level||t||(i=i.then((()=>this.upgradePackagesAsync().then((()=>{}))))),t&&(i=i.then((()=>this.downloadAsync()))),0==this.level&&t&&(i=i.then((()=>this.upgradePackagesAsync())).then((t=>t?(Object.keys(t).forEach((t=>e.tickEvent("package.doubleload",{extension:t}))),e.log("upgraded, downloading again"),e.debug(t),this.downloadAsync()):Promise.resolve()))),e.appTarget.simulator&&e.appTarget.simulator.dynamicBoardDefinition&&(0==this.level&&(i=i.then((()=>this.patchCorePackage()))),i=i.then((()=>{if(this.config.compileServiceVariant&&e.setAppTargetVariant(this.config.compileServiceVariant),this.config.files.indexOf("board.json")<0)return;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],r=this.readFile(t);return e.U.toDataUri(r,e.U.getMime(t))}return t},r=e.appTarget.simulator.boardDefinition;if("object"==typeof r.visual){let e=r.visual;e.image=n(e.image),e.outlineImage=n(e.outlineImage)}})));const o=(t,n)=>{var r;if(e.debug(`version spec mismatch: ${t._verspec} != ${n}`),/^github:/.test(t._verspec)&&/^github:/.test(n)){const i=e.github.parseRepoId(t._verspec),a=e.github.parseRepoId(n);if((null==i?void 0:i.slug)&&(null==i?void 0:i.slug)===(null==a?void 0:a.slug)){const o=(null==i?void 0:i.tag)||(null===(r=t.config)||void 0===r?void 0:r.version),s=e.semver.strcmp(o,a.tag);if(0==s)return void e.debug(`resolved version are ${o}`);if(s<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"))},s=async(r,i,a=!1)=>{r||(r=i.dependencies(a)),e.debug(`deps: ${i.id}->${Object.keys(r).join(", ")}`),r=e.github.resolveMonoRepoVersions(r),e.debug(`deps: resolved ${i.id}->${Object.keys(r).join(", ")}`);for(let s of Object.keys(r)){let c=r[s]||"*";e.debug(`dep: load ${i.id}.${s}${a?"++":""}: ${c}`),"hw"==s&&e.hwVariant&&(s="hw---"+e.hwVariant);let l=i.resolveDep(s);if(l){if(l.invalid()||l._verspec===c||o(l,c),l.invalid()){l.level=Math.min(l.level,i.level+1),l.addedBy.push(i);continue}a||(l.level=Math.min(l.level,i.level+1),l.addedBy.push(i))}else{let e=new n(s,c,i.parent,i);a&&(e.cppOnly=!0),i.parent.deps[s]=e,i.parent.deps[s.replace(/---.*/,"")]=e,await e.loadAsync(t)}}};return i.then((()=>s(null,this))).then((()=>{if(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)),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)return Promise.resolve(null);const n=this.getMissingPackages(this.config,t);let r=!1;return Object.keys(n).reduce(((t,i)=>t.then((()=>this.findConflictsAsync(i,n[i]))).then((t=>{if(t.length){const n=t.map((e=>e.pkg0.id)).join(", "),r=t.map((e=>e.settingName)).filter((e=>!!e)).join(", ");return e.log(`skipping missing package ${i} because it conflicts with the following packages: ${n} (conflicting settings: ${r})`),Promise.resolve(null)}{e.log(`adding missing package ${i}`),r=!0,this.config.dependencies[i]="*";const t={};return t[i]=n[i],s(t,this)}}))),Promise.resolve(null)).then((()=>(r&&(this.saveConfig(),this.validateConfig()),Promise.resolve(null))))}return Promise.resolve(null)})).then((()=>0!=this.level?Promise.resolve():Promise.all(e.U.values(this.parent.deps).map((e=>s(null,e,!0)))))).then((()=>{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 r=this.config.fileDependencies;return this.config.fileDependencies&&(t=t.filter((t=>{const i=r=>{if("!"==(r=r.trim())[0])return!i(r.slice(1));if(/^[\w-]+$/.test(r)){const e=this.parent.resolveDep(r);return!(!e||e.cppOnly)}const a=/^target:(\w+)$/.exec(r);return a?a[1]==e.appTarget.id||a[1]==e.appTarget.platformid:(n.depWarnings[r]||(n.depWarnings[r]=!0,e.log(`invalid dependency expression: ${r} in ${this.id}/${t}`)),!1)},a=e.U.lookup(r,t);return!a||!a.trim()||a.split("||").some((e=>e.split("&&").every(i)))}))),t}addSnapshot(t,n=[""]){for(let r of this.getFiles())n.some((t=>e.U.endsWith(r,t)))&&(t[this.id+"/"+r]=this.readFile(r));t[this.id+"/"+e.CONFIG_NAME]=this.readFile(e.CONFIG_NAME)}packageLocalizationStringsAsync(t){const n=e.appTarget.id,r=[this.config.name+"-jsdoc",this.config.name],i={},a=e.appTarget.appTheme||{};return this.config.skipLocalization?Promise.resolve(i):e.Util.liveLocalizationEnabled()&&"this"!=this.id&&e.appTarget.bundledpkgs[this.id]?(e.debug(`loading live translations for ${this.id}`),Promise.all(r.map((r=>e.Util.downloadLiveTranslationsAsync(t,`${n}/${r}-strings.json`,a.crowdinBranch).then((n=>{n&&Object.keys(n).length?e.Util.jsonMergeFrom(i,n):(e.tickEvent("translations.livetranslationsfailed",{filename:r}),e.Util.jsonMergeFrom(i,this.bundledStringsForFile(t,r)))})).catch((a=>{e.tickEvent("translations.livetranslationsfailed",{filename:r}),e.log(`error while downloading ${n}/${r}-strings.json`),e.Util.jsonMergeFrom(i,this.bundledStringsForFile(t,r))}))))).then((()=>i))):(r.map((e=>this.bundledStringsForFile(t,e))).filter((e=>!!e)).forEach((t=>e.Util.jsonMergeFrom(i,t))),Promise.resolve(i))}bundledStringsForFile(t,n){let r={},[i,a,o]=e.Util.normalizeLanguageCode(t);const s=this.config.files;let c=`_locales/${i}/${n}-strings.json`;return s.indexOf(c)>-1?r=JSON.parse(this.readFile(c)):o&&(c=`_locales/${o}/${n}-strings.json`,s.indexOf(c)>-1?r=JSON.parse(this.readFile(c)):a&&(c=`_locales/${a}/${n}-strings.json`,s.indexOf(c)>-1&&(r=JSON.parse(this.readFile(c))))),r}}n.depWarnings={},e.Package=n;function r(e,t={}){let n=e["*"]||{};for(let r of Object.keys(e)){if("*"==r)continue;let i=e[r];"string"==typeof i&&(i={data:i});let a=i.namespace||n.namespace||"";a&&(a+=".");let o=i.id||a+r,s=i.icon,c=i.mimeType||n.mimeType,l=i.dataEncoding||n.dataEncoding||"base64";s||"base64"!=l||"image/png"!=c&&"image/jpeg"!=c||(s="data:"+c+";base64,"+i.data),t[o]={id:o,data:i.data,dataEncoding:l,icon:s,namespace:a,mimeType:c,tilemapTile:i.tilemapTile,displayName:i.displayName,tileset:i.tileset}}return t}e.MainPackage=class extends n{constructor(e){super("this","file:.",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={},r=[];const i=e=>e.config?Object.keys(e.config.cppDependencies||{}).length:0,a=o=>{if(!o||e.U.lookup(n,o.id))return;n[o.id]=!0;const s=Object.keys(o.dependencies(t)).map((e=>this.resolveDep(e)));s.sort(((t,n)=>i(n)-i(t)||e.U.strcmp(t.id,n.id))),s.forEach(a),r.push(o.id)};return a(this),r.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((r=>{(e.U.startsWith(r,"{id:subcategory}")||e.U.startsWith(r,"{id:group}"))&&(t[r]||(t[r]=n[r]))})),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 r=(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 i=!1;const a=async n=>{const a={extinfo:null,target:null},o=e.appTargetVariant;n&&e.setAppTargetVariant(n,{temporary:!0});try{let s=e.cpp.getExtensionInfo(this);i||!s.shimsDTS&&!s.enumsDTS||(i=!0,s.shimsDTS&&r("shims.d.ts",s.shimsDTS),s.enumsDTS&&r("enums.d.ts",s.enumsDTS));const c=t.isNative?await this.host().getHexInfoAsync(s):null;s=e.U.flatClone(s),t.keepCppFiles||(delete s.compileData,delete s.generatedFiles,delete s.extensionFiles),s.hexinfo=c,a.extinfo=s,a.target=e.appTarget.compile}finally{n&&e.setAppTargetVariant(o,{temporary:!0})}return a};let o;await this.loadAsync(),n.bannedCategories=this.resolveBannedCategories(),n.target.preferredEditor=this.getPreferredEditor(),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 s=null;for(let t of o){s&&e.debug(`building for ${t}`);const r=await a(t),i=r.extinfo;i.appVariant=t,i.outputPrefix=1!=o.length&&t?t+"-":"",s?n.otherMultiVariants.push(r):(s=i,n.otherMultiVariants=[])}n.extinfo=s;if(!(e.appTarget.compile.shortPointers||"vm"==e.appTarget.compile.nativeType||this.config.binaryonly||!n.target.isNative)){const t=await this.filesToBePublishedAsync(!0),r=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}),i=JSON.stringify(t),a=await e.lzmaCompressAsync(r+i);a&&(n.embedMeta=JSON.stringify({compression:"LZMA",headerSize:r.length,textSize:i.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(a)))}for(const e of this.sortedDeps())for(const t of e.getFiles())if(/\.(ts|asm|py)$/.test(t)){let r=t;e.level>0&&(r="pxt_modules/"+e.id+"/"+t),n.sourceFiles.push(r),n.fileSystem[r]=e.readFile(t)}n.jres=this.getJRes();const c=e.appTarget.runtime&&e.appTarget.runtime.functionsOptions;return n.allowedArgumentTypes=c&&c.extraFunctionEditorTypes&&c.extraFunctionEditorTypes.map((e=>e.typeName)).concat("number","boolean","string"),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,r)=>{if(!r||/^(file|workspace):/.test(r)){r="*";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,r=e.github.stringifyRepo(n)}}catch(e){}t.dependencies[n]=r}})),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 r=this.prepareConfigToBePublished();n[e.CONFIG_NAME]=e.Package.stringifyConfig(r);for(let t of this.getFiles()){if(t==e.CONFIG_NAME)continue;let r=this.readFile(t);null==r&&e.U.userError("referenced file missing: "+t),n[t]=r}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((r=>{let i=r.readFile("pxtparts.json");if(i)try{let a=JSON.parse(i);Object.keys(a).forEach((i=>{if(t.indexOf(i)>=0){let t=n[i]=a[i];if("string"==typeof t.visual.image&&/\.svg$/i.test(t.visual.image)){let n=r.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=r,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,r,i,a,o,s=()=>{};function c(){if(o)return o;let t=Promise.resolve();if(n){e.debug("packetio: disconnect");const i=n;t=t.then((()=>i.disconnectAsync())).then((()=>i.io.disposeAsync())).catch((t=>{e.reportException(t)})).finally((()=>{r=void 0,n=void 0,o=void 0})),s&&(t=t.then((()=>s()))),o=t}return t}t.isActive=function(){return!!n},t.isConnected=function(){return!!n&&n.io.isConnected()},t.isConnecting=function(){return!!n&&n.io.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.disconnectAsync=c,t.configureEvents=function(e,t,r){s=e,i=t,a=r,n&&(n.io.onConnectionChanged=s,n.onSerial=i,n.onCustomEvent=r)},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)":"")),!r){let l=Promise.resolve();o&&(l=l.then((()=>c()))),r=l.then((()=>n?Promise.resolve(n):t.mkPacketIOAsync?(e.debug("packetio: new wrapper"),t.mkPacketIOAsync().then((e=>(e.onConnectionChanged=s,n=t.mkPacketIOWrapper(e),i&&(n.onSerial=i),a&&(n.onCustomEvent=a),s&&s(),n)))):(e.debug("packetio: not defined, skipping"),Promise.resolve(void 0)))).finally((()=>{r=void 0}))}return r}}(e.packetio||(e.packetio={}))}(pxt||(pxt={})),function(e){!function(t){t.computePatches=function(t,n){const r=e.appTarget.compile?e.appTarget.compile.patches:void 0;if(!r)return;const i=e.semver.tryParse(t||"0.0.0")||e.semver.tryParse("0.0.0");let a=[];return Object.keys(r).filter((t=>e.semver.inRange(t,i))).forEach((e=>a=a.concat(r[e]))),n&&(a=a.filter((e=>e.type==n))),a.length?a:void 0},t.upgradePackageReference=function(t,n,r){if("*"!=r)return n;const i=e.patching.computePatches(t,"package");let a=n;return i&&i.forEach((e=>{Object.keys(e.map).forEach((t=>{a==t&&(a=e.map[t])}))})),a},t.patchJavaScript=function(t,n){const r=e.patching.computePatches(t);let i=n;return r&&(r.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])}))})),r.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 r=new RegExp(`(^|[^_a-zA-Z0-9])${t}(\\s*\\.)`,"g");i=i.replace(r,`$1${e.map[t]}$2`)}))}))),i}}(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 r=t.major-n.major||t.minor-n.minor||t.patch-n.patch;if(r)return r;if(0==t.pre.length&&n.pre.length>0)return 1;if(t.pre.length>0&&0==n.pre.length)return-1;for(let i=0;i<t.pre.length+1;++i){let a=t.pre[i],o=n.pre[i];if(!a)return o?-1:0;if(!o)return 1;if(/^\d+$/.test(a)){if(!/^\d+$/.test(o))return-1;if(r=parseInt(a)-parseInt(o),r)return r}else{if(/^\d+$/.test(o))return 1;if(r=e.U.strcmp(a,o),r)return r}}return 0}return-1}return n?1:0}function r(t,n){let r=i(t)||i(n);return r||e.U.userError(e.U.lf("'{0}' doesn't look like a semantic version number",t)),r}function i(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 a(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,r){let a=i(t),o=i(r);return a||o?n(a,o):e.U.strcmp(t,r)}function s(e,t){let r=e.split(" - ");if(2!=r.length)return!1;let a=i(r[0]),o=i(r[1]);if(!a||!o)return!1;if(!t)return!0;const s=n(a,t),c=n(t,o);return s<=0&&c<0}t.cmp=n,t.parse=r,t.tryParse=i,t.normalize=function(e){return a(r(e))},t.stringify=a,t.majorCmp=function(e,t){let n=i(e),r=i(t);return n.major-r.major},t.strcmp=o,t.inRange=s,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 i=0;i<t.length;++i){let o=r(t[i]);console.log(t[i],o),e.U.assert(a(o)==t[i]);for(let a=0;a<t.length;++a){let s=n(o,r(t[a]));console.log(t[i],t[a],s),i<a?e.U.assert(s<0):i>a?e.U.assert(s>0):e.U.assert(0==s)}}const o=i("1.2.3");e.U.assert(s("0.1.2 - 2.2.3",o)),e.U.assert(s("1.2.3 - 2.2.3",o)),e.U.assert(!s("0.0.0 - 1.2.3",o)),e.U.assert(!s("1.2.4 - 4.2.3",o)),e.U.assert(!s("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 r=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 r=n.reduce(((t,n,r)=>e<n?t:r+1),0);return[r,t[r]-(n[r]-e)+1]},lineColToPos:(e,t)=>(n[e-1]||0)+t}},i={ts:r(t),py:r(n)},a=e=>e.endPos-e.startPos,o=(t,n)=>{const{startPos:r,endPos:i}=t;return e.filter((e=>e[n].startPos<=r&&i<=e[n].endPos))},s=(e,t)=>{const n=o(e,t);return n.reduce(((e,n)=>a(n[t])<a(e[t])?n:e),n[0])},c={ts:{allOverlaps:e=>o(e,"ts"),smallestOverlap:e=>s(e,"ts")},py:{allOverlaps:e=>o(e,"py"),smallestOverlap:e=>s(e,"py")}},l=(e,t)=>n=>{const[r,o]=(t=>[i[e].lineColToPos(t.line,t.column),t.length])(n),c=s({startPos:r,endPos:r+o},e);if(!c)return;const[l,u]=i[t].posToLineCol(c[t].startPos);return{fileName:`main.${t}`,start:c[t].startPos,length:a(c[t]),line:l,column:u}},u=l("ts","py"),d=l("py","ts");return{ts:Object.assign(Object.assign(Object.assign({},i.ts),c.ts),{locToLoc:u,getText:e=>t.substring(e.startPos,e.endPos)}),py:Object.assign(Object.assign(Object.assign({},i.py),c.py),{locToLoc:d,getText:e=>n.substring(e.startPos,e.endPos)})}},e.computeUsedParts=function(e,t){if(!e.usedSymbols||!pxt.appTarget.simulator||!pxt.appTarget.simulator.parts)return[];let n=[];if(Object.keys(e.usedSymbols).forEach((t=>{let r=e.usedSymbols[t];if(r&&r.attributes.parts){let e=r.attributes.parts;if(e){e.split(/[ ,]+/).forEach((e=>{0<e.length&&n.indexOf(e)<0&&n.push(e)}))}}})),t){const e=pxt.appTarget.simulator.boardDefinition.onboardComponents;e&&("ignorebuiltin"===t?n=n.filter((t=>-1===e.indexOf(t))):"onlybuiltin"===t&&(n=n.filter((t=>e.indexOf(t)>=0))))}return n.sort(),n=n.reverse(),n},e.buildSimJsInfo=function(t){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")}},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 r,o;let s=[];const c={},l={},u={},d={},p={};function f(t,n){const r="get"==t,i="set"==t,o="number"==n.retType,d=r?l:i?c:u,p=`${n.namespace}.${n.retType}`;let f=e.U.lookup(d,p);if(!f){const c=`@${t}@`;let l,u;if(n.attributes.blockCombineShadow){const t=n.attributes.blockCombineShadow,r=t.match(/^([^,.]*),?([^,.]*)$/);r&&3==r.length&&(l=r[1].trim(),u=r[2].trim(),0!=u.length||e.Util.endsWith(t,",")||(u=l,l=""))}const _=`${n.attributes.blockSetVariable||n.namespace.toLocaleLowerCase()}=${l||""}`,m=`value=${u||""}`;f=d[p]={attributes:{blockId:`${o?n.namespace:p}_blockCombine_${t}`,callingConvention:0,group:n.attributes.group,paramDefl:{},jsDoc:r?e.U.lf("Read value of a property on an object"):e.U.lf("Update value of property on an object")},name:c,namespace:n.namespace,fileName:n.fileName,qName:`${p}.${c}`,pkg:n.pkg,kind:2,parameters:[{name:"property",description:r?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:i?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,r?1:2),retType:r?n.retType:"void",combinedProperties:[]},f.attributes.block=r?e.U.lf("%{0} %property",_):i?e.U.lf("set %{0} %property to %{1}",_,m):e.U.lf("change %{0} %property by %{1}",_,m),a(f.attributes),pxt.Util.isTranslationMode()&&(f.attributes.translationId=f.attributes.block,f.attributes.block=r?`%${_} %property`:i?`set %${_} %property to %${m}`:`change %${_} %property by %${m}`,a(f.attributes),pxt.crowdin.inContextLoadAsync(f.attributes.translationId).then((e=>{f.attributes.block=e,a(f.attributes)}))),s.push(f)}f.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 r=n.attributes.kindNamespace||n.attributes.blockNamespace||n.namespace;if(p[r]){console.warn(`More than one block defined for kind ${r}`);continue}const i=[];if(t.byQName[r])for(const n of e.Util.values(t.byQName))n.namespace===r&&n.attributes.isKind&&i.push(n.name);p[r]={blockId:n.attributes.blockId,name:r,memberName:n.attributes.kindMemberName||r,initialMembers:i,promptHint:n.attributes.enumPromptHint||e.Util.lf("Create a new kind..."),createFunctionName:n.attributes.kindCreateFunction||"create"}}if(n.attributes.blockCombine)/@set/.test(n.name)||f("get",n),n.isReadOnly||("number"==n.retType&&f("change",n),f("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 s=null!==(o=null===(r=n.parameters)||void 0===r?void 0:r.filter((e=>!i(e))))&&void 0!==o?o:[];for(let e of s)t+=" %"+e.name;n.attributes.block=t,a(n.attributes)}s.push(n)}}for(let n of s){let r=e.U.lookup(t.byQName,n.namespace);if(!r)continue;let i=r.attributes,a=n.attributes;for(let e of["blockNamespace","color","blockGap"])void 0===a[e]&&i[e]&&(a[e]=i[e])}var _;return n&&((_=n).length&&(s=s.filter((e=>{let t=(e.attributes.blockNamespace||e.namespace).split(".")[0];return-1===_.indexOf(t)})))),{apis:t,blocks:s,blocksById:pxt.Util.toDictionary(s,(e=>e.attributes.blockId)),enumsByName:d,kindsByName:p}},e.tsSnippetToPySnippet=function(t,n){const r={true:"True",false:"False",null:"None"}[t];if(r)return r;if(n&&6==n.kind||!n&&t.includes(".")){const n=t.lastIndexOf("."),r=t.substr(0,n);let i=t.substr(n+1);return i=e.U.snakify(i).toUpperCase(),`${r}.${i}`}return t},e.apiLocalizationStrings={},e.localizeApisAsync=async function(n,r){const i=e.Util.userLanguage();if("en"==i)return Promise.resolve(t(n));const o=i.toLowerCase(),s=o+"|jsdoc",c=o+"|block",l=await r.localizationStringsAsync(i);e.apiLocalizationStrings&&e.Util.jsonMergeFrom(l,e.apiLocalizationStrings);const u=e.Util.values(n.byQName).filter((e=>e.attributes._translatedLanguageCode!==i));return await e.Util.promiseMapAll(u,(async t=>{var r,u,d;const p=t.attributes.useLoc||t.attributes.blockAliasFor,f=p&&n.byQName[p];t.attributes._untranslatedJsDoc&&(t.attributes.jsDoc=t.attributes._untranslatedJsDoc),t.attributes._untranslatedBlock&&(t.attributes.jsDoc=t.attributes._untranslatedBlock);const _=(e,n)=>{var r,i;return l[t.qName+e]||(null===(r=t.attributes.locs)||void 0===r?void 0:r[n])||f&&(l[f.qName+e]||(null===(i=f.attributes.locs)||void 0===i?void 0:i[n]))},m=_("",s);m&&(t.attributes._untranslatedJsDoc||(t.attributes._untranslatedJsDoc=t.attributes.jsDoc),t.attributes.jsDoc=m),null===(r=t.parameters)||void 0===r||r.forEach((e=>{const t=`|param|${e.name}`,n=_(t,o+t);n&&(e.description=n)}));const g=l["{id:category}"+e.Util.capitalize(t.qName)];let h=l[`${t.qName}|block`]||(null===(u=t.attributes.locs)||void 0===u?void 0:u[c]);if(!h&&f){const e=l[`${f.qName}|block`]||(null===(d=f.attributes.locs)||void 0===d?void 0:d[c]);t.attributes.block===(f.attributes._untranslatedBlock||f.attributes.block)&&e&&(h=e)}if(h&&pxt.Util.isTranslationMode()&&(t.attributes.translationId=h,h=await pxt.crowdin.inContextLoadAsync(h)),g)t.attributes.block?t.attributes.block=h||t.attributes.block:t.attributes.block=g,a(t.attributes);else if(t.attributes.block&&h){const e=pxt.blocks.compileInfo(t),n=t.attributes.block;if(t.attributes.block=pxt.blocks.normalizeBlock(h,(e=>{pxt.tickEvent("loc.normalized",{block:t.attributes.block,lang:i,error:e})})),t.attributes._untranslatedBlock||(t.attributes._untranslatedBlock=n),n!=t.attributes.block){a(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)return pxt.debug(`Parameter ${n.actualName} type or shadow block does not match after localization`),!1}return!0})(e,pxt.blocks.compileInfo(t))||(pxt.log(`block has non matching arguments: ${n} vs ${t.attributes.block}`),pxt.reportError("loc.errors","invalid translations",{block:t.attributes.blockId,lang:i}),t.attributes.block=n,a(t.attributes))}}else a(t.attributes);t.attributes._translatedLanguageCode=i})),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,r={functions:[],generatedFiles:{},extensionFiles:{},sha:"",compileData:"",shimsDTS:"",enumsDTS:"",onlyPublic:!0};return t?r.platformio={dependencies:{}}:n?r.npmDependencies={}:r.yotta={config:{},dependencies:{}},r};const n=["weight","imageLiteral","topblockWeight"],r=["advanced","handlerStatement","afterOnStart","optionalVariableArgs","blockHidden","constantShim","blockCombine","enumIsBitMask","enumIsHash","decompileIndirectFixedInstances","topblock","callInDebugger","duplicateShadowOnDrag","argsNullable"];function i(e){return"Action"===e.type||/^\([^\)]*\)\s*=>/.test(e.type)}function a(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,r=0;for(;r<e.length;r++){const i=e[r],a=r;let o;switch(i){case"*":case"_":const t=d((e=>e==i)),n="_"===i?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}:r=a;break;case"`":const s=p("`");if(void 0===s){r=a;break}o={kind:256,content:s};break;case"|":o={kind:32};break;case"\\":r<e.length-1&&(o={kind:16,content:e[1+r++]});break;case"[":const c=p("]");if(void 0!==c&&"("===e[1+r++]){const e=p(")");if(void 0!==e){o={kind:512,content:c,type:e};break}}r=a;break;case"$":case"%":const l=d((e=>/[a-zA-Z0-9_=]/.test(e)),!0).split("=");if(l.length>2){r=a;break}let u;if("("===e[r+1]){const e=r;++r,u=p(")"),u||(r=e)}o={kind:"$"===i?1024:64,content:l[0],type:l[1],name:u}}o?(n&&t.push({kind:128,content:n}),n=void 0,t.push(o)):n?n+=i:n=i}n&&t.push({kind:128,content:n});const i=[],a=[];let o=[],c=0,l="",u=[];for(let e=0;e<t.length;e++){const n=t[e].kind,r=o[o.length-1];if(15&n)if(m(t[e].content),n&c)if(r&n){o.pop(),c^=n;const e=r&c|n&c;e&&o.push(e)}else f();else c|=n,o.push(n);else 144&n?l+=t[e].content:1120&n&&_();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),i.push(n),a.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),i.push(n),a.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&&i.push({kind:"break"})}return _(),{parts:i,parameters:a};function d(t,n=!1){let i="";for(n&&r++;r<e.length&&t(e[r]);)i+=e[r],++r;return i&&r--,i}function p(t){const n=d((e=>e!==t),!0);if(e[r+1]===t)return++r,n}function f(){let e="",t=[];for(const n of u)s(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=[],c=0}function _(){for(m(),c&&f();u.length;){const e=u.shift();if(s(e))i.push(e);else{if(!e.content)continue;const t=[];10&e.styles&&t.push("bold"),5&e.styles&&t.push("italics"),i.push({kind:"label",text:e.content,style:t})}}}function m(e){u.push({content:l,styles:c,endingToken:e}),l=""}}function s(e){return!!e.kind}let c;e.parseCommentString=function(t){let i={paramDefl:{},callingConvention:0,_source:t},o=!0;for(;o;)o=!1,t=t.replace(/\/\/%[ \t]*([\w\.-]+)(=(("[^"\n]*")|'([^'\n]*)'|([^\s]*)))?/,((t,n,r,a,s,c,l)=>{let u=s?JSON.parse(s):r?s||c||l:"true";if(u||(u=""),e.U.startsWith(n,"block.loc."))i.locs||(i.locs={}),i.locs[n.slice("block.loc.".length).toLowerCase()+"|block"]=u;else if(e.U.startsWith(n,"jsdoc.loc."))i.locs||(i.locs={}),i.locs[n.slice("jsdoc.loc.".length).toLowerCase()+"|jsdoc"]=u;else if(e.U.contains(n,".loc.")){i.locs||(i.locs={});const e=n.slice(0,n.indexOf(".loc.")),t=n.slice(n.indexOf(".loc.")+".loc.".length);i.locs[t+"|param|"+e]=u}else if(e.U.endsWith(n,".defl"))u.indexOf(" ")>-1?i.paramDefl[n.slice(0,n.length-5)]=`"${u}"`:i.paramDefl[n.slice(0,n.length-5)]=u,i.explicitDefaults||(i.explicitDefaults=[]),i.explicitDefaults.push(n.slice(0,n.length-5));else if(e.U.endsWith(n,".shadow"))i._shadowOverrides||(i._shadowOverrides={}),i._shadowOverrides[n.slice(0,n.length-7)]=u;else if(e.U.endsWith(n,".fieldEditor"))i.paramFieldEditor||(i.paramFieldEditor={}),i.paramFieldEditor[n.slice(0,n.length-12)]=u;else if(e.U.contains(n,".fieldOptions.")){i.paramFieldEditorOptions||(i.paramFieldEditorOptions={});const e=n.slice(0,n.indexOf(".fieldOptions.")),t=n.slice(n.indexOf(".fieldOptions.")+14,n.length);i.paramFieldEditorOptions[e]||(i.paramFieldEditorOptions[e]={}),i.paramFieldEditorOptions[e][t]=u}else if(e.U.contains(n,".shadowOptions.")){i.paramShadowOptions||(i.paramShadowOptions={});const e=n.slice(0,n.indexOf(".shadowOptions.")),t=n.slice(n.indexOf(".shadowOptions.")+15,n.length);i.paramShadowOptions[e]||(i.paramShadowOptions[e]={}),i.paramShadowOptions[e][t]=u}else e.U.endsWith(n,".min")?(i.paramMin||(i.paramMin={}),i.paramMin[n.slice(0,n.length-4)]=u):e.U.endsWith(n,".max")?(i.paramMax||(i.paramMax={}),i.paramMax[n.slice(0,n.length-4)]=u):i[n]=u;return o=!0,"//% "}));for(let e of n)"string"==typeof i[e]&&(i[e]=parseInt(i[e]));for(let e of r)"string"==typeof i[e]&&(i[e]="true"==i[e]||"1"==i[e]);if(i.trackArgs&&(i.trackArgs=i.trackArgs.split(/[ ,]+/).map((e=>parseInt(e)||0))),i.enumInitialMembers&&(i.enumInitialMembers=i.enumInitialMembers.split(/[ ,]+/)),i.blockExternalInputs&&!i.inlineInputMode&&(i.inlineInputMode="external"),i.paramHelp={},i.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(i.paramHelp[t]=n,!i.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?i.paramDefl[t]=`"${e}"`:i.paramDefl[t]=e}}}return""})),i.jsDoc+=t,""))),i.jsDoc=i.jsDoc.trim(),i.async&&(i.callingConvention=1),i.promise&&(i.callingConvention=2),i.jres&&(i.whenUsed=!0),i.subcategories)try{i.subcategories=JSON.parse(i.subcategories)}catch(e){i.subcategories=void 0}if(i.groups)try{i.groups=JSON.parse(i.groups)}catch(e){i.groups=void 0}if(i.groupIcons)try{i.groupIcons=JSON.parse(i.groupIcons)}catch(e){i.groupIcons=void 0}if(i.groupHelp)try{i.groupHelp=JSON.parse(i.groupHelp)}catch(e){i.groupHelp=void 0}return a(i),i},e.parameterTypeIsArrowFunction=i,e.updateBlockDef=a,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 r=pxt.HF2.read32(e,t+4),i=pxt.HF2.read32(e,t+8);if(3&r)return pxt.log("invalid end marker position"),null;let a=1<<(255&i);if(a!=pxt.appTarget.compile.flashCodeAlign)return pxt.log("invalid page size: "+a),null;let o={magic:n,endMarkerPos:r,endMarker:i,regions:[]};for(let n=t+12;n<e.length-7;n+=8){let t={start:a*pxt.HF2.read16(e,n),length:a*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 r=e=>n[e]+(n[e+1]<<8)+(n[e+2]<<16)+(n[e+3]<<24)>>>0;if(!n||512!=n.length||r(0)!=t.UF2_MAGIC_START0||r(4)!=t.UF2_MAGIC_START1||r(n.length-4)!=t.UF2_MAGIC_END)return null;let i=r(8),a=r(16);a>476&&(a=256);let o=null,s=0,c=0;if(i&t.UF2_FLAG_FILE){let t=n.slice(32+a),i=t.indexOf(0);i>=0&&(t=t.slice(0,i)),o=e.U.fromUTF8Array(t),c=r(28)}return i&t.UF2_FLAG_FAMILY_ID_PRESENT&&(s=r(28)),{flags:i,targetAddr:r(12),payloadSize:a,blockNo:r(20),numBlocks:r(24),fileSize:c,familyId:s,data:n.slice(32,32+a),filename:o}}function r(e,t){return!!e&&(e.targetAddr<=t&&t<e.targetAddr+e.payloadSize)}function i(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 a(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)i(e.blocks[t],20,t),i(e.blocks[t],24,e.blocks.length),e.filename&&i(e.blocks[t],28,e.filesize)}function s(n,r,a,o=0){let c=n.currBlock,l=r>>8,u=256-(255&r);if(a.length>u){let e=new Uint8Array(a);for(s(n,r,e.slice(0,u));u<a.length;){let t=Math.min(u+256,a.length);s(n,r+u,e.slice(u,t)),u=t}return}if(l!=n.currPtr){c=null;for(let e=0;e<n.ptrs.length;++e)if(n.ptrs[e]==l){c=n.blocks[e];break}if(!c){c=new Uint8Array(512),n.filename?o|=t.UF2_FLAG_FILE:n.familyId&&(o|=t.UF2_FLAG_FAMILY_ID_PRESENT),i(c,0,t.UF2_MAGIC_START0),i(c,4,t.UF2_MAGIC_START1),i(c,8,o),i(c,12,l<<8),i(c,16,256),i(c,20,n.blocks.length),i(c,28,n.familyId),i(c,508,t.UF2_MAGIC_END);for(let e=32;e<288;++e)c[e]=255;n.filename&&e.U.memcpy(c,288,e.U.toUTF8Array(n.filename)),n.blocks.push(c),n.ptrs.push(l)}n.currPtr=l,n.currBlock=c}let d=32+(255&r);for(let e=0;e<a.length;++e)c[d+e]=a[e];n.filesize=Math.max(n.filesize,a.length+r)}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 r=0;r<e.length;r+=512){let i=n(e.slice(r,r+512));i&&t.push(i)}return t},t.toBin=function(e,t){if(e.length<512)return null;let r=-1,i=-1,a=[];for(let o=0;o<e.length;++o){let s=512*o,c=n(e.slice(s,s+512));if(!c)continue;if(t&&c.targetAddr+256>t)break;-1==r&&(r=c.targetAddr,i=r);let l=c.targetAddr-r;l<0||l%4||l>1048576||(l>0&&a.push(new Uint8Array(l)),a.push(e.slice(s+32,s+32+c.payloadSize)),r=c.targetAddr+c.payloadSize)}let o=0;for(let e of a)o+=e.length;if(0==o)return null;let s=new Uint8Array(o),c=0;for(let e of a)for(let t=0;t<e.length;++t)s[c++]=e[t];return{buf:s,start:i}},t.readBytes=function(e,t,n){let i,a=new Uint8Array(n);for(let o=0;o<n;++o,++t)r(i,t)||(i=e.filter((e=>r(e,t)))[0]),i&&(a[o]=i.data[t-i.targetAddr]);return a},t.newBlockFile=a,t.finalizeFile=o,t.concatFiles=function(t){for(let e of t)o(e),e.filename=null;let n=a();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 r of t.blocks)n+=e.Util.uint8ArrayToString(r);return n},t.readBytesFromFile=function t(n,r,i){let a,o=r>>8;if(o==n.currPtr)a=n.currBlock;else{for(let e=0;e<n.ptrs.length;++e)if(n.ptrs[e]==o){a=n.blocks[e];break}a&&(n.currPtr=o,n.currBlock=a)}if(!a)return null;let s=new Uint8Array(i),c=Math.min(i,256-(255&r));e.U.memcpy(s,0,a,32+(255&r),c);let l=i-c;if(l>0){let i=t(n,r+c,l);e.U.memcpy(s,c,i)}return s},t.writeBytes=s,t.writeHex=function(e,t){let n="0000";for(let r=0;r<t.length;++r){let i=/:02000004(....)/.exec(t[r]);if(i&&(n=i[1]),i=/^:..(....)00(.*)[0-9A-F][0-9A-F]$/.exec(t[r]),i){let t=parseInt(n+i[1],16),r=i[2],a=[];for(let e=0;e<r.length;e+=2)a.push(parseInt(r[e]+r[e+1],16));s(e,t,a)}}}}(c=e.UF2||(e.UF2={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){let n,r;!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={}));let i=!1,a=!1;function o(){if(void 0===r){if(e.BrowserUtils.hasWindow()){const t=/sandbox=1|#sandbox|#sandboxproject/i.test(window.location.href)||e.BrowserUtils.isIFrame(),o=/nosandbox=1/i.test(window.location.href),s=/controller=1/i.test(window.location.href)&&e.BrowserUtils.isIFrame(),c=/readonly=1/i.test(window.location.href),l=/editorlayout=(widget|sandbox|ide)/i.exec(window.location.href),u=/noproject=1/i.test(window.location.href);if(r=n.IDE,o?r=n.Widget:s?r=n.Controller:t&&(r=n.Sandbox),s&&c&&(i=!0),s&&u&&(a=!0),l)switch(l[1].toLowerCase()){case"widget":r=n.Widget;break;case"sandbox":r=n.Sandbox;break;case"ide":r=n.IDE}}else r=n.Sandbox;e.debug(`shell: layout type ${n[r]}, readonly ${c()}`)}}function s(){return o(),r==n.Sandbox}function c(){return!e.BrowserUtils.hasWindow()||s()&&!/[?&]edit=1/i.test(window.location.href)||l()&&i}function l(){return o(),r==n.Controller}t.layoutTypeClass=function(){return o(),e.shell.EditorLayoutType[r].toLowerCase()},t.isSandboxMode=s,t.isReadOnly=c,t.isNoProject=function(){return a},t.isControllerMode=l,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 r=t.result;e.oldVersion<1&&(r.createObjectStore(n.projectTable,{keyPath:n.projectKey}),r.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=>{var t;return null===(t=e)||void 0===t?void 0:t.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=>{var t;return null===(t=e)||void 0===t?void 0:t.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(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,r;!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"}(r=t.LengthUnit||(t.LengthUnit={}));class i{constructor(e){this.el=S(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=S("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=i;class a extends i{draw(e){const t=function(e){switch(e){case"text":return new d;case"circle":return new f;case"rect":return new p;case"line":return new _;case"polygon":return new h;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=a;t.SVG=class extends a{constructor(e){super("svg"),e&&e.appendChild(this.el)}define(e){return this.defs||(this.defs=new c(this.el)),e(this.defs),this}};class o extends a{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 c(this.el)}style(){return new l(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 s extends a{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=s;class c extends i{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 s;break;case"radialGradient":n=new x;break;case"linearGradient":n=new b;break;case"clipPath":n=new k;break;default:n=new i(e)}return n.id(t),this.el.appendChild(n.el),n}}t.DefsElement=c;class l extends i{constructor(e){super("style"),e.appendChild(this.el)}content(e){this.el.textContent=e}}t.StyleElement=l;class u extends a{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",C(e,t))}offset(e,t,n){return 0!==e&&this.setAttribute("dx",C(e,n)),0!==t&&this.setAttribute("dy",C(t,n)),this}anchor(e){return this.setAttribute("text-anchor",e)}}t.Text=d;class p extends u{constructor(){super("rect")}width(e,t=r.px){return this.setAttribute("width",C(e,t))}height(e,t=r.px){return this.setAttribute("height",C(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=r.px){return this.width(e,n),this.height(t,n),this}}t.Rect=p;class f 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=f;class _ extends u{constructor(){super("line")}at(e,t,n,r){return this.from(e,t),null!=n&&null!=r&&this.to(n,r),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=_;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 h extends m{constructor(){super("polygon")}}t.Polygon=h;class y extends u{constructor(){super("path"),this.d=new T}update(){return this.setAttribute("d",this.d.toAttribute())}path(e){return e(this.d),this.update()}}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=r.px){return this.setAttribute("width",C(e,t))}height(e,t=r.px){return this.setAttribute("height",C(e,t))}size(e,t,n=r.px){return this.width(e,n),this.height(t,n),this}};class v extends i{units(e){return this.setAttribute("gradientUnits",e===n.objectBoundingBox?"objectBoundingBox":"userSpaceOnUse")}stop(e,t,n){const r=S("stop");return r.setAttribute("offset",e+"%"),null!=t&&r.setAttribute("stop-color",t),null!=n&&r.setAttribute("stop-opacity",n),this.el.appendChild(r),this}}t.Gradient=v;class b 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=b;class x 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=x;class k extends a{constructor(){super("clipPath")}clipPathUnits(e){return e?this.setAttribute("clipPathUnits","objectBoundingBox"):this.setAttribute("clipPathUnits","userSpaceOnUse")}}function S(e){return document.createElementNS("http://www.w3.org/2000/svg",e)}t.ClipPath=k;class T{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,r,i,a){return this.op("C",e,t,n,r,i,a)}cCurveBy(e,t,n,r,i,a){return this.op("c",e,t,n,r,i,a)}qCurveTo(e,t,n,r){return this.op("Q",e,t,n,r)}qCurveBy(e,t,n,r){return this.op("q",e,t,n,r)}sCurveTo(e,t,n,r){return this.op("S",e,t,n,r)}sCurveBy(e,t,n,r){return this.op("s",e,t,n,r)}tCurveTo(e,t){return this.op("T",e,t)}tCurveBy(e,t){return this.op("t",e,t)}arcTo(e,t,n,r,i,a,o){return this.op("A",e,t,n,r?1:0,i?1:0,a,o)}arcBy(e,t,n,r,i,a,o){return this.op("a",e,t,n,r?1:0,i?1:0,a,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 C(e,t){switch(t){case r.em:return e+"em";case r.ex:return e+"ex";case r.px:return e+"px";case r.in:return e+"in";case r.cm:return e+"cm";case r.mm:return e+"mm";case r.pt:return e+"pt";case r.pc:return e+"pc";case r.percent:return e+"%";default:return e.toString()}}t.PathContext=T}(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,r){n()?e.addEventListener("pointerdown",r):t()?(e.addEventListener("mousedown",r),e.addEventListener("touchstart",r)):e.addEventListener("mousedown",r)},e.up=function(e,r){n()?e.addEventListener("pointerup",r):(t(),e.addEventListener("mouseup",r))},e.enter=function(e,r){n()?e.addEventListener("pointerover",(e=>{r(!!(1&e.buttons))})):t()?e.addEventListener("touchstart",(e=>{r(!0)})):e.addEventListener("mouseover",(e=>{r(!!(1&e.buttons))}))},e.leave=function(e,r){n()?e.addEventListener("pointerleave",r):t()?e.addEventListener("touchend",r):e.addEventListener("mouseleave",r)},e.move=function(e,r){n()?e.addEventListener("pointermove",r):t()?e.addEventListener("touchmove",r):e.addEventListener("mousemove",r)},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){e.IMAGE_MIME_TYPE="image/x-mkcd-f4",e.TILEMAP_MIME_TYPE="application/mkcd-tilemap",e.ANIMATION_MIME_TYPE="application/mkcd-animation";class t{constructor(){this.assets=[],this.takenNames={},this.listeners=[]}add(e){if(this.takenNames[e.id])return this.update(e.id,e);{const t=o(e);return this.takenNames[t.id]=!0,this.takenNames[u(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),o(t)}}getSnapshot(e){return e?this.assets.filter((t=>e(t))).map(o):this.assets.map(o)}update(e,t){let n;if(this.takenNames[e]){c(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[u(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&&o(t)}getByDisplayName(e){if(this.takenNames[e])for(const t of this.assets)if(t.meta.displayName===e||u(t)===e)return o(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)s(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 r of e.assets){n[r.internalID]=!0;const e=this.lookupByInternalID(r.internalID);e&&c(r,e)||(t.before.push(r),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 r=n?t.after:t.before,i=n?t.before:t.after;e.Util.assert(r.length===i.length);for(let e=0;e<r.length;e++)r[e]?(this.removeByInternalID(r[e].internalID),i[e]&&this.assets.push(i[e]),this.notifyListener(r[e].internalID)):(this.assets.push(i[e]),this.notifyListener(i[e].internalID));this.takenNames={};for(const t of this.assets)e.Util.assert(!this.takenNames[t.id]),this.takenNames[t.id]=!0,this.takenNames[u(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}}function n(t){const n=[];for(const r of Object.keys(t)){const i=t[r];i.mimeType===e.TILEMAP_MIME_TYPE&&n.push(i)}return n}function r(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 i(t){return e.sprite.Bitmap.fromData(t).copy().data()}function a(t,n){const r=atob(t.data),i=e.U.fromHex(r),a=i[1]|i[2]<<8,o=i[3]|i[4]<<8,s={tileWidth:i[0],tiles:t.tileset.map((e=>n&&n(e)||{id:e}))},c=i.slice(5,5+a*o),l=new e.sprite.Tilemap(a,o,0,0,new Uint8ClampedArray(c)),u=i.slice(5+c.length),d=new e.sprite.Bitmap(a,o,0,0,new Uint8ClampedArray(u)).data();return new e.sprite.TilemapData(l,s,d)}function o(e){switch(e.meta=Object.assign({},e.meta),e.type){case"tile":case"image":return Object.assign(Object.assign({},e),{bitmap:i(e.bitmap)});case"animation":return Object.assign(Object.assign({},e),{frames:e.frames.map((e=>i(e)))});case"tilemap":return Object.assign(Object.assign({},e),{data:e.data.cloneData()})}}function s(t,n){const r=t.id.substr(t.id.lastIndexOf(".")+1);switch(t.type){case"image":n[r]=t.jresData,t.meta.displayName&&(n[r]={data:t.jresData,mimeType:e.IMAGE_MIME_TYPE,displayName:t.meta.displayName});break;case"tile":n[r]={data:t.jresData,mimeType:e.IMAGE_MIME_TYPE,tilemapTile:!0,displayName:t.meta.displayName};break;case"tilemap":const i=function(t,n,r){const i=t.tilemap.data(),a=new Uint8ClampedArray(5+i.data.length+t.layers.data.length);return a[0]=t.tileset.tileWidth,a[1]=255&i.width,a[2]=i.width>>8&255,a[3]=255&i.height,a[4]=i.height>>8&255,a.set(i.data,5),a.set(t.layers.data,5+i.data.length),{id:n,mimeType:e.TILEMAP_MIME_TYPE,data:btoa(e.sprite.uint8ArrayToHex(a)),tileset:t.tileset.tiles.map((e=>e.id)),displayName:r}}(t.data,t.id,t.meta.displayName);n[i.id]=i;break;case"animation":n[r]=function(t){return{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}}(t)}}function c(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 r=n;return t.interval===r.interval&&e.U.arrayEquals(t.frames,r.frames,e.sprite.bitmapEquals);case"tilemap":return t.data.equals(n.data)}}function l(e){const t=/^\s*(?:(?:assets\s*\.\s*(image|tile|animation|tilemap))|(tilemap))\s*(?:`|\(""")([^`"]+)(?:`|"""\))\s*$/m.exec(e);if(t){return{type:t[1]||t[2],name:t[3].trim()}}}function u(e){return d(e.type,e.id)}function d(t,n,r=!1){let i;switch(t){case"image":i=e.sprite.IMAGES_NAMESPACE+".";break;case"tile":i=e.sprite.TILE_NAMESPACE+".";break;case"tilemap":i="";break;case"animation":i=e.sprite.ANIMATION_NAMESPACE+"."}if(i)if(n.startsWith(i)){const e=n.substr(i.length);if(-1===e.indexOf("."))return e}else if(!r)return null;return n}function p(t){const n=atob(t.data),r=new Uint8ClampedArray(e.U.fromHex(n)),i=f(r,0),a=f(r,2),o=f(r,4),s=f(r,6),c=Math.ceil(a*o/2);let l=8;const u=[];for(let e=0;e<s;e++){const e=r.slice(l,l+c);u.push({x0:0,y0:0,width:a,height:o,data:e}),l+=c}let d=t.id;return d.startsWith(t.namespace)||(d=t.namespace+"."+d,d=d.replace(/\.\./g,".")),{type:"animation",internalID:0,id:d,interval:i,frames:u,meta:{displayName:t.displayName}}}function f(e,t){return e[t]|e[t+1]<<8}e.TilemapProject=class{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},this.state={revision:this.nextID++,tilemaps:new t,tiles:new t,animations:new t,images:new t},this.gallery={revision:0,tilemaps:new t,tiles:new t,animations:new t,images:new t},this.undoStack=[],this.redoStack=[]}getNewInternalId(){return this.nextInternalID++}createNewImage(t=16,n=16){const r=this.generateNewID("image"),i=new e.sprite.Bitmap(t,n).data(),a={internalID:this.getNewInternalId(),id:r,type:"image",bitmap:i,meta:{},jresData:e.sprite.base64EncodeBitmap(i)};return this.state.images.add(a)}createNewAnimation(t=16,n=16){const r=this.generateNewID("animation"),i=new e.sprite.Bitmap(t,n).data(),a={internalID:this.getNewInternalId(),id:r,type:"animation",frames:[i],interval:500,meta:{}};return this.state.animations.add(a)}createNewAnimationFromData(e,t=500,n){const r=this.generateNewID("animation"),i={internalID:this.getNewInternalId(),id:r,type:"animation",frames:e,interval:t,meta:{displayName:n}};return this.state.animations.add(i)}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 r=this.state.tiles.getSnapshot((e=>e.bitmap.width===t));return 0===r.length?n?(this.createNewTile(new e.sprite.Bitmap(t,t).data()),this.getProjectTiles(t,!1)):null:{tileWidth:t,tiles:r}}createNewTile(t,n,r){this.onChange(),n&&!this.isNameTaken("tile",n)||(n=this.generateNewID("tile"));const i={internalID:this.getNewInternalId(),id:n,type:"tile",jresData:e.sprite.base64EncodeBitmap(t),bitmap:t,meta:{displayName:r},isProjectTile:!0};return this.state.tiles.add(i)}createNewProjectImage(t,n){this.onChange();const r={internalID:this.getNewInternalId(),id:this.generateNewID("image"),type:"image",jresData:e.sprite.base64EncodeBitmap(t),meta:{displayName:n},bitmap:t};return this.state.images.add(r)}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),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 r=Object.assign(Object.assign({},n),{data:t});return this.state.tilemaps.update(e,r),r}return null}createNewTilemap(e,t,n=16,r=16){return this.createNewTilemapFromData(this.blankTilemap(t,n,r),e)}blankTilemap(t,n=16,r=16){const i=new e.sprite.Tilemap(n,r),a=new e.sprite.Bitmap(n,r),o={tileWidth:t,tiles:[this.getTransparency(t)]};return new e.sprite.TilemapData(i,o,a.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 r=this.state.tiles.getByID(n);if(!r){const i=new e.sprite.Bitmap(t,t).data();return r={internalID:this.getNewInternalId(),id:n,type:"tile",bitmap:i,jresData:e.sprite.base64EncodeBitmap(i),meta:{},isProjectTile:!0},this.state.tiles.add(r)}return r}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: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()}}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.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.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)}),this.committedState=this.cloneState(),this.cleanupTemporaryAssets())}revision(){return this.state.revision}encodeTilemap(t,n){const r=t.tilemap.data(),i=new Uint8ClampedArray(5+r.data.length+t.layers.data.length);return i[0]=t.tileset.tileWidth,i[1]=255&r.width,i[2]=r.width>>8&255,i[3]=255&r.height,i[4]=r.height>>8&255,i.set(r.data,5),i.set(t.layers.data,5+r.data.length),{id:n,mimeType:e.TILEMAP_MIME_TYPE,data:btoa(e.sprite.uint8ArrayToHex(i)),tileset:t.tileset.tiles.map((e=>e.id))}}forceUpdate(){this.onChange()}isNameTaken(e,t){const n=t=>{switch(e){case"image":return this.state.images.isIDTaken(t)||this.gallery.images.isIDTaken(t);case"tile":return this.state.tiles.isIDTaken(t)||this.gallery.tiles.isIDTaken(t);case"tilemap":return this.state.tilemaps.isIDTaken(t)||this.gallery.tilemaps.isIDTaken(t);case"animation":return this.state.animations.isIDTaken(t)||this.gallery.animations.isIDTaken(t)}},r=d(e,t),i=r&&r!==t;return n(t)||i&&n(r)}isAssetUsed(t,n,r){var i,a,o;if(((null===(a=null===(i=t.meta)||void 0===i?void 0:i.blockIDs)||void 0===a?void 0:a.filter((e=>!r||(null==r?void 0:r.indexOf(e))<0)))||[]).length>0)return!0;if("tile"==t.type)for(const e of this.getAssets("tilemap"))if(!((null==r?void 0:r.indexOf(e.id))>=0)&&e.data.tileset.tiles.some((e=>e.id===t.id)))return!0;if(n){const i=e.Util.escapeForRegex(u(t)),a=e.Util.escapeForRegex(null===(o=t.meta)||void 0===o?void 0:o.displayName)||"";let s;switch(t.type){case"tile":s=`myTiles.${i}|assets.tile\`${i}\``,a&&(s+=`|assets.tile\`${a}\``);break;case"tilemap":s=`tilemap\`${i}\``;break;case"animation":s=`assets.animation\`${i}\``,a&&(s+=`|assets.animation\`${a}\``);break;default:s=`assets.image\`${i}\``,a&&(s+=`|assets.image\`${a}\``)}const c=new RegExp(s,"gm");let l;switch(t.type){case"tile":l=`myTiles.${i}|assets.tile("""${i}""")`,a&&(l+=`|assets.tile("""${a}""")`);break;case"tilemap":l=`assets.tilemap("""${i}""")`;break;case"animation":l=`assets.animation("""${i}""")`,a&&(l+=`|assets.animation("""${a}""")`);break;default:l=`assets.image("""${i}""")`,a&&(l+=`|assets.image("""${a}""")`)}const d=new RegExp(l,"gm");for(let e of Object.keys(n)){if((null==r?void 0:r.indexOf(e))>=0)continue;const t=n[e];if(e.match(/((?!\.g).{2}|^.{0,1})\.ts$/i)){if(t.content.match(c))return!0}else if(e.endsWith(".py")&&t.content.match(d))return!0}}return!1}lookupAsset(e,t){switch(e){case"image":return this.state.images.getByID(t)||this.gallery.images.getByID(t);case"tile":return this.state.tiles.getByID(t)||this.gallery.tiles.getByID(t);case"tilemap":return this.state.tilemaps.getByID(t)||this.gallery.tilemaps.getByID(t);case"animation":return this.state.animations.getByID(t)||this.gallery.animations.getByID(t)}}lookupAssetByName(e,t){switch(e){case"image":return this.state.images.getByDisplayName(t);case"tile":return this.state.tiles.getByDisplayName(t);case"tilemap":return this.state.tilemaps.getByDisplayName(t);case"animation":return this.state.animations.getByDisplayName(t)}}getAssets(e){switch(e){case"image":return this.state.images.getSnapshot();case"tile":return this.state.tiles.getSnapshot();case"tilemap":return this.state.tilemaps.getSnapshot();case"animation":return this.state.animations.getSnapshot()}}getGalleryAssets(e){switch(e){case"image":return this.gallery.images.getSnapshot();case"tile":return this.gallery.tiles.getSnapshot();case"tilemap":return this.gallery.tilemaps.getSnapshot();case"animation":return this.gallery.animations.getSnapshot()}}lookupBlockAsset(e,t){let n=e=>{var n,r;return-1!==(null===(r=null===(n=e.meta)||void 0===n?void 0:n.blockIDs)||void 0===r?void 0:r.indexOf(t))};switch(e){case"image":return this.state.images.getSnapshot(n)[0];case"tile":return this.state.tiles.getSnapshot(n)[0];case"tilemap":return this.state.tilemaps.getSnapshot(n)[0];case"animation":return this.state.animations.getSnapshot(n)[0]}}updateAsset(e){switch(this.onChange(),e.type){case"image":return this.state.images.update(e.id,e);case"tile":return this.updateTile(e);case"tilemap":return this.state.tilemaps.update(e.id,e);case"animation":return this.state.animations.update(e.id,e)}}duplicateAsset(e,t){var n;this.onChange();const r=o(e),i=t||(null===(n=r.meta)||void 0===n?void 0:n.displayName);let a;switch(e.type){case"image":a=this.createNewProjectImage(r.bitmap,i);break;case"tile":a=this.createNewTile(r.bitmap,null,i);break;case"tilemap":const[e,t]=this.createNewTilemapFromData(r.data,i);a=this.getTilemap(e);break;case"animation":a=this.createNewAnimationFromData(r.frames,r.interval,i)}return a}removeAsset(e){switch(this.onChange(),e.type){case"image":return this.state.images.removeByID(e.id);case"tile":return this.state.tiles.removeByID(e.id);case"tilemap":return this.state.tilemaps.removeByID(e.id);case"animation":return this.state.animations.removeByID(e.id)}}addChangeListener(e,t){switch(e.type){case"image":this.state.images.addListener(e.internalID,t);break;case"tile":this.state.tiles.addListener(e.internalID,t);break;case"tilemap":this.state.tilemaps.addListener(e.internalID,t);break;case"animation":this.state.animations.addListener(e.internalID,t)}}removeChangeListener(e,t){switch(e){case"image":this.state.images.removeListener(t);break;case"tile":this.state.tiles.removeListener(t);break;case"tilemap":this.state.tilemaps.removeListener(t);break;case"animation":this.state.animations.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 e of n)"tile"===e.type?t?this.state.tiles.add(e):this.gallery.tiles.add(e):"image"===e.type?t?this.state.images.add(e):this.gallery.images.add(e):t?this.state.animations.add(e):this.gallery.animations.add(e)}for(const t of n(e.parseJRes()))this.state.tilemaps.add({internalID:this.getNewInternalId(),type:"tilemap",id:t.id,meta:{displayName:t.displayName||t.id},data:a(t,(e=>this.resolveTile(e)))});this.committedState=this.cloneState(),this.undoStack=[],this.redoStack=[]}loadTilemapJRes(t,r=!1){t=e.inflateJRes(t);const i=this.readImages(t,!0).filter((e=>"tile"===e.type));let o={};for(const e of i){if(r){const t=this.resolveTileByBitmap(e.bitmap);if(t){o[e.id]=t.id;continue}}const t=this.createNewTile(e.bitmap,e.id,e.meta.displayName);t.id!==e.id&&(o[e.id]=t.id)}for(const e of n(t))this.state.tilemaps.add({internalID:this.getNewInternalId(),type:"tilemap",id:e.id,meta:{displayName:e.displayName||e.id},data:a(e,(e=>(o[e]&&(e=o[e]),this.resolveTile(e))))})}loadAssetsJRes(t){t=e.inflateJRes(t);const n=[];for(const r of Object.keys(t)){const i=t[r];if(i.tilemapTile)this.state.tiles.add(this.generateImage(i,"tile"));else if(i.mimeType===e.IMAGE_MIME_TYPE)this.state.images.add(this.generateImage(i,"image"));else if(i.mimeType===e.ANIMATION_MIME_TYPE){const[e,t]=this.generateAnimation(i);t?n.push(e):this.state.animations.add(e)}}for(const e of n)this.state.animations.add(this.inflateAnimation(e,this.state.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))))})),r=[];for(const t of n)1===t.meta.blockIDs.length?r.push(t):(t.meta.blockIDs=t.meta.blockIDs.filter((t=>-1!==e.indexOf(t))),0===t.meta.blockIDs.length&&r.push(t));for(const e of r)t.removeByID(e.id)}t(this.state.images),t(this.state.tiles),t(this.state.tilemaps),t(this.state.animations)}generateImage(t,n){return{internalID:this.getNewInternalId(),type:n,id:t.id,meta:{displayName:t.displayName},jresData:t.data,bitmap:e.sprite.getBitmapFromJResURL(`data:${e.IMAGE_MIME_TYPE};base64,${t.data}`).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},id:e.id,frames:[],frameIds:t.frames,interval:100,flippedHorizontal:t.flippedHorizontal},!0]}return[Object.assign(Object.assign({},p(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),r=new e.sprite.Bitmap(t.width,t.height);for(let e=0;e<r.width;e++)for(let t=0;t<r.height;t++)r.set(e,t,n.get(n.width-e-1,t));return r.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"))}}generateNewIDInternal(e,t,n){t=t.replace(/\d+$/,"");const r=n?n+"."+t:t;let i=1;for(;this.isNameTaken(e,r+i);)++i;return r+i}onChange(){this.needsRebuild=!0,this.state.revision=this.nextID++}readImages(t,n=!1){const r=[],i=[];for(const a of Object.keys(t)){const o=t[a];if(o.tilemapTile){const e=this.generateImage(o,"tile");e.isProjectTile=n,r.push(e)}else if(o.mimeType===e.IMAGE_MIME_TYPE)r.push(this.generateImage(o,"image"));else if(o.mimeType===e.ANIMATION_MIME_TYPE){const[e,t]=this.generateAnimation(o);t?i.push(e):r.push(e)}}for(const e of i)r.push(this.inflateAnimation(e,r));return r}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)}},e.emitTilemapsFromJRes=function(t){const n=Object.keys(t);let i="";const o=[],s=[];for(const r of n){if("*"===r)continue;const n=t[r];if(n.tilemapTile&&(i+=" //% fixedInstance jres blockIdentity=images._tile\n",i+=` export const ${r} = image.ofBuffer(hex\`\`);\n`,s.push({keys:[n.displayName,d("tile",r,!0)],expression:r})),n.mimeType===e.TILEMAP_MIME_TYPE){const t=a(n);o.push({keys:[n.displayName,d("tilemap",n.id)],expression:e.sprite.encodeTilemap(t,"typescript")})}}o.length&&(i+=r("tilemap",o)),s.length&&(i+=r("tile",s));const c=lf("Auto-generated code. Do not edit.");return`// ${c}\nnamespace ${e.sprite.TILE_NAMESPACE} {\n${i}\n}\n// ${c}\n`},e.emitProjectImages=function(t){const n=Object.keys(t);let i="";const a=[],o=[];for(const r of n){if("*"===r)continue;const n=t[r];if("string"==typeof n||n.mimeType===e.IMAGE_MIME_TYPE){let t,i=[d("image",r,!0)];"string"==typeof n?t=e.sprite.bitmapToImageLiteral(e.sprite.getBitmapFromJResURL(n),"typescript"):(t=e.sprite.bitmapToImageLiteral(e.sprite.getBitmapFromJResURL(n.data),"typescript"),i.push(n.displayName)),a.push({keys:i,expression:t})}else if(n.mimeType===e.ANIMATION_MIME_TYPE){const t=p(n);o.push({keys:[n.displayName,d("animation",r,!0)],expression:`[${t.frames.map((t=>e.sprite.bitmapToImageLiteral(e.sprite.Bitmap.fromData(t),"typescript"))).join(", ")}]`})}}const s=lf("Auto-generated code. Do not edit.");return i+=r("image",a),i+=r("animation",o),`// ${s}\nnamespace ${e.sprite.IMAGES_NAMESPACE} {\n${i}\n}\n// ${s}\n`},e.cloneAsset=o,e.assetEquals=c,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 r;if(r=(null===(n=e.meta)||void 0===n?void 0:n.displayName)?e.meta.displayName:u(e),!r)return"image"===e.type||"tile"===e.type?e.id:void 0;const i=t?'("""':"`",a=t?'""")':"`";switch(e.type){case"tile":return`assets.tile${i}${r}${a}`;case"image":return`assets.image${i}${r}${a}`;case"animation":return`assets.animation${i}${r}${a}`;case"tilemap":return`tilemap${i}${r}${a}`}},e.parseAssetTSReference=l,e.lookupProjectAssetByTSReference=function(e,t){const n=l(e);if(n){const{type:e,name:r}=n;switch(e){case"tile":return t.lookupAssetByName("tile",r);case"image":return t.lookupAssetByName("image",r);case"tilemap":return t.lookupAssetByName("tilemap",r)||t.lookupAsset("tilemap",r);case"animation":return t.lookupAssetByName("animation",r)}}},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");default:return lf("asset")}},e.getShortIDForAsset=u}(pxt||(pxt={})),function(e){!function(t){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 n="";function r(e){const t=function(e,t,n){let r=0,i=0,a=0;if(0==t)r=n,i=n,a=n;else{let o=Math.floor(e/60),s=e/60-o,c=n*(1-t),l=n*(1-t*s),u=n*(1-t*(1-s));switch(o){case 1:r=l,i=n,a=c;break;case 2:r=c,i=n,a=u;break;case 3:r=c,i=l,a=n;break;case 4:r=u,i=c,a=n;break;case 5:r=n,i=c,a=l;break;case 6:case 0:r=n,i=u,a=c}}return[Math.floor(r),Math.floor(i),Math.floor(a)]}(e,.45,165.75);return`#${i(t[0])}${i(t[1])}${i(t[2])}`}function i(e){const t=e.toString(16);return 1==t.length?"0"+t:t}t.appendToolboxIconCss=function(t,r){if(!(n.indexOf(t)>-1))if(1===r.length){const i=e.Util.unicodeToChar(r);n+=`\n .blocklyTreeIcon.${t}::before {\n content: "${i}";\n }\n `}else n+=`\n .blocklyTreeIcon.${t} {\n background-image: url("${e.Util.pathJoin(e.webConfig.commitCdnUrl,encodeURI(r))}")!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){return t=t.toLowerCase(),e.appTarget.appTheme.blockColors&&e.appTarget.appTheme.blockColors[t]?e.appTarget.appTheme.blockColors[t]:e.toolbox.blockColors[t]?e.toolbox.blockColors[t]:""},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:r(n)},t.hueToRgb=r,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 r="#";for(let i=0;i<3;i++){let a=parseInt(e.substr(2*i,2),16);a=Math.round(Math.min(Math.max(0,n?a+a*t:a-a*t),255));let o=a.toString(16);r+=("00"+o).substr(o.length)}return r}}(e.toolbox||(e.toolbox={}))}(pxt||(pxt={})),function(e){!function(t){const n=/^##[^#](.*)$([\s\S]*?)(?=^##[^#]|$(?![\r\n]))/gim,r=/^###[^#](.*)$([\s\S]*?)(?=^###[^#]|$(?![\r\n]))/gim;function i(){return/``` *(sim|block|blocks|filterblocks|spy|ghost|typescript|ts|js|javascript|template|python|jres|assetjson|customts|tutorialValidationRules|requiredTutorialBlock)\s*\n([\s\S]*?)\n```/gim}function a(t,r,i){let a=r||n,s=[];if(t.replace(a,(function(e,t,n){n=n.trim();let{header:r,hint:a,requiredBlocks:c}=function(e,t,n){let r,i,a=e=o(e);if(t){const t=/#+ ~ tutorialhint([\s\S]*)/i;a=e.replace(t,(function(e,t){return r=t,""}))}else{const t=/(^[\s\S]*?\S)\s*((```|\[?\!\[[\s\S]+?\]\(\S+?\)\]?)[\s\S]*)/im;let o=e.match(t);if(o&&o.length>2&&(a=o[1].trim(),r=o[2].trim(),n)){let e=o[2].trim();e=e.replace(/``` *(requiredTutorialBlock)\s*\n([\s\S]*?)\n```/gim,(function(e,t,n){return i=`{\n${n}\n}`,""})),r=e}}return{header:a,hint:r,requiredBlocks:i}}(n,i&&i.explicitHints,i.tutorialCodeValidation);let l={title:t.match(/^\{.*\}$/)?void 0:t.replace(/@(fullscreen|unplugged|showdialog|showhint|tutorialCompleted|resetDiff)/gi,"").trim(),contentMd:n,headerContentMd:r};return/@(fullscreen|unplugged|showdialog|showhint)/i.test(t)&&(l.showHint=!0),/@(unplugged|showdialog)/i.test(t)&&(l.showDialog=!0),/@tutorialCompleted/.test(t)&&(l.tutorialCompleted=!0),/@resetDiff/.test(t)&&(l.resetDiff=!0),a&&(l.hintContentMd=a),i.tutorialCodeValidation&&c&&(l.requiredBlockMd=c),s.push(l),""})),0!=t.indexOf("# Not found"))return s;e.debug("tutorial not found")}function o(e){if(!e)return e;return e.replace(/```(filterblocks|package|ghost|config|template|jres|assetjson|customts)\s*\n([\s\S]*?)\n```/gim,"").trim()}function s(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]}}t.parseTutorial=function(t){const{metadata:i,body:c}=function(t){const n=/### @(\S+) ([ \S]+)/gi,r={},i=t.replace(n,(function(e,t,n){try{r[t]=JSON.parse(n)}catch(e){r[t]=n}return""})),a=r;void 0!==a.explicitHints&&e.appTarget.appTheme&&e.appTarget.appTheme.tutorialExplicitHints&&(a.explicitHints=!0);return{metadata:a,body:i}}(t),{steps:l,activities:u}=function(e,t){if(t&&t.activities)return function(e,t){let i=[],o=[];return e.replace(n,(function(e,n,s){let c=o.length;o.push({name:n||lf("Activity {0}",c),step:i.length});let l=a(s,r,t);return l=l.map((e=>(e.activity=c,e))),i=i.concat(l),""})),{steps:i,activities:o}}(e,t);{let n=a(e,null,t);return(!n||n.length<1)&&(n=a(e,r,t)),{steps:n,activities:null}}}(c,i),d=function(e){let t=e.match(/^#[^#](.*)$/im);return t&&t.length>1?t[1].trim():null}(c);if(!l)return;const{code:p,templateCode:f,editor:_,language:m,jres:g,assetJson:h,customTs:y,tutorialValidationRulesStr:v}=function(t){let n;const r=/``` *(sim|block|blocks|filterblocks|spy|ghost|typescript|ts|js|javascript|template|python|jres|assetjson|customts|tutorialValidationRules|requiredTutorialBlock)\s*\n([\s\S]*?)\n```/gim;let i,a,o,s,c,l,u=[];return t.replace(/((?!.)\s)+/g,"\n").replace(r,(function(t,n,r){switch(n){case"block":case"blocks":case"requiredTutorialBlock":case"filterblocks":if(!d(e.BLOCKS_PROJECT_NAME))return;break;case"spy":case"python":if(!d(e.PYTHON_PROJECT_NAME))return;"python"==n&&(o=n);break;case"typescript":case"ts":case"javascript":case"js":if(!d(e.JAVASCRIPT_PROJECT_NAME))return;break;case"template":a=r;break;case"jres":i=r;break;case"assetjson":s=r;break;case"customts":c=r,r="";break;case"tutorialValidationRules":l=r}return u.push("python"==n?`\n${r}\n`:`{\n${r}\n}`),""})),n=n||e.BLOCKS_PROJECT_NAME,{code:u,templateCode:a,editor:n,language:o,jres:i,assetJson:s,customTs:c,tutorialValidationRulesStr:l};function d(t){return n&&n!=t?(e.debug("tutorial ambiguous: contains snippets of different types"),!1):(n=t,!0)}}(c);let b;i.tutorialCodeValidation&&(b=e.Util.jsonTryParse(v),function(t,n){const r=Object.keys(t);for(let i=0;i<r.length;i++){const a={ruleName:r[i],enabled:t[r[i]]?"true":"false",tutorial:n};e.tickEvent("tutorial.validation.setValidationRules",a)}}(b,d)),(!0===i.diffs||!1!==i.diffs&&!0!==i.noDiffs&&(_==e.BLOCKS_PROJECT_NAME&&e.appTarget.appTheme.tutorialBlocksDiff||_!=e.BLOCKS_PROJECT_NAME&&e.appTarget.appTheme.tutorialTextDiff))&&function(e,t){let n;function r(e){const t={typescript:"diff",spy:"diffspy",blocks:"diffblocks",python:"diff"},r=/\s*(\/\/|#)\s*@highlight/gm;return e?e.replace(/```(typescript|spy|python|blocks|ghost|template)((?:.|[\r\n])+)```/,(function(e,i,a){const o=n,s=/^(template|ghost)$/.test(i),c=r.test(a);return a=a.replace(/^\n+/,"").replace(/\n+$/,""),c&&(a=a.replace(r,"")),n=a,!o||c||s?e:`\`\`\`${t[i]}\n${o}\n----------\n${a}\n\`\`\``})):e}e.forEach(((e,i)=>{if((e.resetDiff||t&&t.find((e=>e.step==i)))&&(n=void 0),e.hintContentMd){const t=r(e.hintContentMd);if(t&&t!=e.hintContentMd)return void(e.hintContentMd=t)}if(e.headerContentMd){const t=r(e.headerContentMd);if(t&&t!=e.headerContentMd)return void(e.headerContentMd=t)}}))}(l,u);const x=s(h);return l.forEach((e=>{e.contentMd=o(e.contentMd),e.headerContentMd=o(e.headerContentMd),e.hintContentMd=o(e.hintContentMd),e.requiredBlockMd=o(e.requiredBlockMd)})),{editor:_,title:d,steps:l,activities:u,code:p,templateCode:f,metadata:i,language:m,jres:g,assetFiles:x,customTs:y,tutorialValidationRules:b}},t.getMetadataRegex=i,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 r=n[t];if(/@highlight/.test(r)){if(r=n[++t],void 0!==r){const t=document.createElement("span");t.className="highlight-line",t.textContent=r,e.appendChild(t)}}else e.appendChild(document.createTextNode(r))}},t.getTutorialOptions=function(t,n,r,i,a){var o;const s=e.tutorial.parseTutorial(t);if(!s)throw new Error(lf("Invalid tutorial format"));return{options:{tutorial:n,tutorialName:s.title||r,tutorialReportId:i,tutorialStep:0,tutorialReady:!0,tutorialHintCounter:0,tutorialStepInfo:s.steps,tutorialActivityInfo:s.activities,tutorialMd:t,tutorialCode:s.code,tutorialRecipe:!!a,templateCode:s.templateCode,autoexpandStep:!(null===(o=s.metadata)||void 0===o?void 0:o.autoexpandOff),metadata:s.metadata,language:s.language,jres:s.jres,assetFiles:s.assetFiles,customTs:s.customTs,tutorialValidationRules:s.tutorialValidationRules},editor:s.editor}},t.parseCachedTutorialInfo=function(t,n){let r=e.Util.jsonTryParse(t);return r?e.BrowserUtils.tutorialInfoDbAsync().then((e=>{if(n&&r[n]){const t=r[n];t.usedBlocks&&t.hash&&e.setWithHashAsync(n,t.snippetBlocks,t.hash)}else for(let t of Object.keys(r)){const n=r[t];n.usedBlocks&&n.hash&&e.setWithHashAsync(t,n.snippetBlocks,n.hash)}})).catch((e=>{})):Promise.resolve()},t.resolveLocalizedMarkdown=function(t,n,r){const i=(r||t.fileName||"README")+".md";let a;const[o,s,c]=e.Util.normalizeLanguageCode(e.Util.userLanguage());return a=o&&s&&c?n[`_locales/${o}/${i}`]||n[`_locales/${c}/${i}`]||n[`_locales/${s}/${i}`]:n[`_locales/${o}/${i}`],a=a||n[i],a},t.parseAssetJson=s}(e.tutorial||(e.tutorial={}))}(pxt||(pxt={})),function(e){!function(t){function n(t,n){const{tutorialStep:r}=t,i=t.tutorialStepInfo[r].requiredBlockMd,a=e.BrowserUtils.getTutorialCodeHash([i]);let o={};return null!=n&&(o=n[a]),o}function r(e,t,n){n.isStrict=!0;const r=Object.keys(e);let i=[],a=[];null!=t&&(i=Object.keys(t));let o=r.length>=i.length;const s=lf("These are the blocks you seem to be missing:");for(let n=0;n<i.length;n++){let r=i[n];(!e[r]||e[r]<t[r])&&(a.push(r),o=!1)}return n.ruleMessage=s,n.ruleStatus=o,n.blockIds=a,n}function i(e,t,n){const r=Object.keys(e),i=Object.keys(null!=t?t:{});let a=r.length>=i.length;for(let t=0;t<i.length;t++){if(!e[i[t]]){a=!1;break}}return n.ruleStatus=a,n}function a(e,t,n){n.isStrict=!0;Object.keys(e);let r=[],i=[];null!=t&&(r=Object.keys(t));let a=!0;const o=lf("You are required to have the following block:");for(let t=0;t<r.length;t++){let n=r[t];e[n]||(i.push(n),a=!1)}return n.ruleMessage=o,n.ruleStatus=a,n.blockIds=i,n}t.validate=async function(t,o,s){let c=function(e){let t=[];if(null!=e){const n=Object.keys(e);for(let r=0;r<n.length;r++){const i=n[r],a={ruleName:i,ruleTurnOn:e[i]};t.push(a)}}return t}(t.tutorialValidationRules);if(c.length>0&&o.length>0){const s=function(e){let t={};for(let n=0;n<e.length;n++)t[e[n]]||(t[e[n]]=0),t[e[n]]=t[e[n]]+1;return t}(o.map((e=>e.type))),{tutorialStepInfo:l,tutorialStep:u}=t,d=(l[u],await function(t,n){return e.BrowserUtils.tutorialInfoDbAsync().then((e=>e.getAsync(t.tutorial,t.tutorialCode).then((e=>(null==e?void 0:e.snippets)?Promise.resolve(e.snippets):Promise.resolve(void 0)))))}(t)),p=function(t,n){const{tutorialStepInfo:r,tutorialStep:i}=t,a=t.tutorialStepInfo[i].hintContentMd;let o="";null!=a&&a.replace(/((?!.)\s)+/g,"\n").replace(/``` *(block|blocks)\s*\n([\s\S]*?)\n```/gim,(function(e,t,n){return o=`{\n${n}\n}`,""}));const s=e.BrowserUtils.getTutorialCodeHash([o]);let c={};null!=n&&(c=n[s]);return c}(t,d);for(let e=0;e<c.length;e++){let o=c[e];const l=c[e].ruleName;if(c[e].ruleTurnOn)switch(l){case"exact":o=r(s,p,o);break;case"atleast":o=i(s,p,o);break;case"required":o=a(s,n(t,d),o)}}}return c}}(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,r="",i=0;for(;n;){if(i){r+=t;for(let e=0;e<i;e++)r+=" "}r+=n.messageText,i++,n=n.next}return r}},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&&s(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?c(e,i):c(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 r=n.replace(/\s+/g,"_").replace(/[^a-zA-Z0-9_$]/g,(t=>e.pxtc.isIdentifierPart(t.charCodeAt(0),e.pxtc.ScriptTarget.ES5)?t:""));return r&&e.pxtc.isIdentifierStart(r.charCodeAt(0),e.pxtc.ScriptTarget.ES5)&&-1===t.reservedWords.indexOf(r)||(r="_"+r),r};const r=[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],i=[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],a=[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 s(e,t){return t>=n.ES5?c(e,r):c(e,a)}function c(e,t){if(e<t[0])return!1;let n,r=0,i=t.length;for(;r+1<i;){if(n=r+(i-r)/2,n-=n%2,t[n]<=e&&e<=t[n+1])return!0;e<t[n]?i=n:r=n+2}return!1}let l;t.isUnicodeIdentifierStart=s,function(e){e[e.Warning=0]="Warning",e[e.Error=1]="Error",e[e.Message=2]="Message"}(l=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 r(){return!!navigator&&!!navigator.bluetooth&&!!e.appTarget.appTheme.bluetoothPartialFlashing}t.isAvailable=function(){return n()||r()},t.hasConsole=n,t.hasPartialFlash=r,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 i{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=i;class a extends i{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((r=>(this.debug(`reconnect error ${r.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=a;class o extends a{constructor(e,t,n,r){super(e,t,!0),this.device=t,this.serviceUUID=n,this.txCharacteristicUUID=r,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 s extends o{constructor(e){super("hf2",e,s.SERVICE_UUID,s.CHARACTERISTIC_TX_UUID),this.device=e}handlePacket(e){const t=e.getUint8(0);switch(192&t){case s.BLEHF2_FLAG_SERIAL_OUT:case s.BLEHF2_FLAG_SERIAL_ERR:const n=Math.min(e.byteLength-1,-193&t);let r="";for(let t=0;t<n;++t)r+=String.fromCharCode(e.getUint8(t+1));r&&window.postMessage({type:"serial",id:this.device.name||"hf2",data:r},"*")}}}s.SERVICE_UUID="b112f5e6-2679-30da-a26e-0273b6043849",s.CHARACTERISTIC_TX_UUID="b112f5e6-2679-30da-a26e-0273b604384a",s.BLEHF2_FLAG_SERIAL_OUT=128,s.BLEHF2_FLAG_SERIAL_ERR=192,t.HF2Service=s;class c extends o{constructor(e){super("uart",e,c.SERVICE_UUID,c.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 l;c.SERVICE_UUID="6e400001-b5a3-f393-e0a9-e50e24dcca9e",c.CHARACTERISTIC_TX_UUID="6e400002-b5a3-f393-e0a9-e50e24dcca9e",t.UARTService=c,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"}(l||(l={}));class u extends a{constructor(e){super("partial flashing",e,!1),this.device=e,this.state=l.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==l.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 r=0;r<t.length;++r)if(t[r]!=this.bin[e+r]){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 r=e.appTarget.compile.flashUsableEnd;this.bin=ts.pxtc.UF2.toBin(e.U.stringToUint8Array(ts.pxtc.UF2.serializeFile(n)),r).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 i=this.magicOffset+u.MAGIC_MARKER.length;return this.dalHash=e.Util.toHex(this.bin.slice(i,i+8)),this.makeCodeHash=e.Util.toHex(this.bin.slice(i+8,i+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=l.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,r=new Uint8Array(n.buffer),i=r[0];if(this.state!=l.Idle)switch(i){case u.STATUS:if(!this.checkStateTransition(i,l.StatusRequested|l.PairingModeRequested))return;this.version=r[1],this.mode=r[2],this.debug(`flash service version ${this.version} mode ${this.mode}`),this.debug("reading DAL region"),this.state=l.RegionDALRequested,this.pfCharacteristic.writeValue(new Uint8Array([u.REGION_INFO,u.REGION_DAL])).then((()=>{}));break;case u.REGION_INFO:if(!this.checkStateTransition(i,l.RegionDALRequested|l.RegionMakeCodeRequested))return;const t=this.regions[r[1]]={start:r[2]<<24|r[3]<<16|r[4]<<8|r[5],end:r[6]<<24|r[7]<<16|r[8]<<8|r[9],hash:e.Util.toHex(r.slice(10))};if(this.debug(`read region ${r[1]} start ${t.start.toString(16)} end ${t.end.toString(16)} hash ${t.hash}`),r[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=l.USBFlashRequired,this.flashReject(new Error("USB flashing required")),void this.clearFlashData();this.debug("DAL hash match, reading makecode region"),this.state=l.RegionMakeCodeRequested,this.pfCharacteristic.writeValue(new Uint8Array([u.REGION_INFO,u.REGION_MAKECODE])).then((()=>{}))}else if(r[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=l.Idle,this.flashResolve(),this.clearFlashData()}));else{if(this.mode!=u.MODE_PAIRING)return this.debug("application mode, reset into pairing mode"),this.state=l.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(i,l.Flash))return;switch(r[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=l.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(r)}`),this.disconnect()}}flashNextPacket(){this.state=l.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,r=()=>e.U.delay(500).then((()=>{if(t!=this.flashOffset||this.flashPacketToken.isCancelled()||this.aliveToken.isCancelled()||this.state!=l.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((()=>r()))}));r().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 i{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 c(this)),this.services.push(this.hf2Service=new s(this))),r()&&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 p(){if(t.bleDevice)return Promise.resolve();e.log("ble: requesting device");const i=[];return n()&&(i.push(c.SERVICE_UUID),i.push(s.SERVICE_UUID)),r()&&i.push(u.SERVICE_UUID),navigator.bluetooth.requestDevice({filters:e.appTarget.appTheme.bluetoothUartFilters,optionalServices:i}).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),p().catch((n=>{t.bleDevice&&t.bleDevice.aliveToken&&t.bleDevice.aliveToken.resolveCancel(),e.log(`ble: error ${n.message}`)}))},t.flashAsync=function(n,r){e.tickEvent("webble.flash");const i=n.outfiles[ts.pxtc.BINARY_HEX];return p().then((()=>t.bleDevice.partialFlashingService.flashAsync(i))).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 r,i,a=!0;t.setFilters=function(e){a=!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(){this.enabled||(this.enabled=!0,this.log("registering webusb events"),navigator.usb.addEventListener("disconnect",this.handleUSBDisconnected,!1),navigator.usb.addEventListener("connect",this.handleUSBConnected,!1))}disable(){this.enabled&&(this.enabled=!1,this.log("unregistering webusb events"),navigator.usb.removeEventListener("disconnect",this.handleUSBDisconnected),navigator.usb.removeEventListener("connect",this.handleUSBConnected))}disposeAsync(){return this.disable(),Promise.resolve()}handleUSBDisconnected(e){this.log("device disconnected"),e.device==this.dev&&(this.log("clear device"),this.clearDev(),this.onDeviceConnectionChanged&&this.onDeviceConnectionChanged(!1))}handleUSBConnected(e){const t=e.device;this.log(`device connected ${t.serialNumber}`),this.dev||this.connecting||(this.log("attach device"),this.onDeviceConnectionChanged&&this.onDeviceConnectionChanged(!0))}clearDev(){this.dev&&(this.dev=null,this.epIn=null,this.epOut=null,this.onConnectionChanged&&this.onConnectionChanged())}error(t){throw new n(e.U.lf("USB error on device {0} ({1})",this.dev.productName,t))}log(t){e.debug("webusb: "+t)}disconnectAsync(){return this.ready=!1,this.dev?(this.log("close device"),this.dev.close().catch((e=>{})).then((()=>(this.clearDev(),e.U.delay(500))))):Promise.resolve()}reconnectAsync(){return this.log("reconnect"),this.setConnecting(!0),this.disconnectAsync().then(s).then((e=>this.connectAsync(e))).finally((()=>this.setConnecting(!1)))}setConnecting(e){e!=this.connecting&&(this.connecting=e,this.onConnectionChanged&&this.onConnectionChanged())}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)}}sendPacketAsync(t){return this.dev?(e.Util.assert(t.length<=64),this.epOut?this.dev.transferOut(this.epOut.endpointNumber,t).then((e=>{"ok"!=e.status&&this.error("USB OUT transfer failed")})):this.dev.controlTransferOut({requestType:"class",recipient:"interface",request:9,value:512,index:this.iface.interfaceNumber},t).then((e=>{"ok"!=e.status&&this.error("USB CTRL OUT transfer failed")}))):Promise.reject(new Error("Disconnected"))}readLoop(){if(this.readLoopStarted)return;this.readLoopStarted=!0,this.log("start read loop");let t=()=>{this.ready?this.recvPacketAsync().then((n=>{n[0]?(this.onData(n),t()):e.U.delay(500).then(t)}),(n=>{this.dev&&this.onError(n),e.U.delay(300).then(t)})):e.U.delay(300).then(t)};t()}recvPacketAsync(){let e=e=>{"ok"!=e.status&&this.error("USB IN transfer failed");let t=new Uint8Array(e.data.buffer);return 0==t.length?this.recvPacketAsync():t};return this.dev?this.epIn?this.dev.transferIn(this.epIn.endpointNumber,64).then(e):this.dev.controlTransferIn({requestType:"class",recipient:"interface",request:1,value:256,index:this.iface.interfaceNumber},64).then(e):Promise.reject(new Error("Disconnected"))}initAsync(){if(!this.dev)return Promise.reject(new Error("Disconnected"));let n=this.dev;return this.log("open device"),n.open().then((()=>(this.log("select configuration"),n.selectConfiguration(1)))).then((()=>{this.log("got "+n.configurations[0].interfaces.length+" interfaces");const r=n.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 i=r[r.length-1];return this.log(`${r.length} matching interfaces; picking ${i?"#"+i.interfaceNumber:"n/a"}`),i||this.error("cannot find supported USB interface"),this.altIface=i.alternates[0],this.iface=i,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"),n.claimInterface(i.interfaceNumber)})).then((()=>{this.log("device ready"),this.lastKnownDeviceSerialNumber=this.dev.serialNumber,this.ready=!0,a&&this.readLoop(),this.onConnectionChanged&&this.onConnectionChanged()}))}}async function s(){e.log("webusb: get devices");try{return await navigator.usb.getDevices()||[]}catch(t){return e.reportException(t),[]}}async function c(){var t,n;if(void 0!==i)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(i=!1);if(e.BrowserUtils.isElectron()||e.BrowserUtils.isWinRT())return e.debug("webusb: off, electron or winrt"),e.tickEvent("webusb.off",{reason:"electronwinrt"}),void(i=!1);const r=navigator.usb;if(!r)return e.debug("webusb: off, not impl"),e.tickEvent("webusb.off",{reason:"notimpl"}),void(i=!1);let a=/Windows NT (\d+\.\d+)/.exec(navigator.userAgent);if(a&&parseFloat(a[1])<6.3)return e.debug("webusb: off, older windows version"),e.tickEvent("webusb.off",{reason:"oldwindows"}),void(i=!1);try{await r.getDevices()}catch(t){return e.debug("webusb: off, security exception"),e.tickEvent("webusb.off",{reason:"security"}),void(i=!1)}i=!0}function l(){return void 0===i&&(console.error("checkAvailableAsync not called"),c()),!!i}t.pairAsync=function(){return navigator.usb.requestDevice({filters:t.filters}).then((e=>!!e)).catch((e=>{if("NotFoundError"!=e.name)throw e}))},t.mkWebUSBHIDPacketIOAsync=function(){return e.debug("packetio: mk webusb io"),r||(r=new o),r.enable(),Promise.resolve(r)},t.isEnabled=!1,t.setEnabled=function(e){l()||(e=!1),t.isEnabled=e},t.checkAvailableAsync=c,t.isAvailable=l}(e.usb||(e.usb={}))}(pxt||(pxt={})),function(e){!function(t){var n=e.Util;let r={};function i(e){let t={},r=0,i=new n.PromiseQueue,a=new Promise(((e,n)=>{t.ready=e}));i.enqueue("main",(()=>a));return{opAsync:function(n,a){return i.enqueue("main",(()=>new Promise(((i,o)=>{let s=""+r++;t[s]=e=>{e?e.errorMessage?o(new Error(e.errorMessage)):i(e):o(new Error("no response"))},e({id:s,op:n,arg:a})}))))},recvHandler:e=>{if(t.hasOwnProperty(e.id)){let n=t[e.id];delete t[e.id],n(e.result)}}}}function a(t){let n=new Worker(t),r=i((e=>n.postMessage(e)));return n.onmessage=t=>{e.perf.measureStart("webworker recvHandler"),r.recvHandler(t.data),e.perf.measureEnd("webworker recvHandler")},r}t.getWorker=function(e){let t=r[e];return t||(t=r[e]=a(e)),t},t.wrap=i,t.makeWebWorker=a,t.makeWebSocket=function(t,n=null){let r=new WebSocket(t),a=[],o=i((e=>{let t=JSON.stringify(e);a?a.push(t):r.send(t)}));return r.onmessage=e=>{let t=JSON.parse(e.data);n&&null==t.id?n(t):o.recvHandler(t)},r.onopen=t=>{e.debug("socket opened");for(let e of a)r.send(e);a=null},r.onclose=t=>{e.debug("socket closed")},r.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 r(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:r(e.snippet.thumbnails)};var t},t.playlistInfoAsync=function(r){n();const i=`https://www.googleapis.com/youtube/v3/playlists?part=snippet&id=${r}&key=${t.apiKey}`;return e.Util.httpGetJsonAsync(i).then((e=>e.items[0]))},t.listPlaylistVideosAsync=async function(r){n();let i,a=[];do{let n=`https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=${r}&key=${t.apiKey}`;i&&(n+=`&pageToken=${i}`);const o=await e.Util.httpGetJsonAsync(n);a=a.concat(o.items),i=o.nextPageToken}while(i);return e.options.debug&&e.debug(JSON.stringify(a,null,2)),a},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 r=c("opcode name doesn't match","<name>");class i{constructor(t,n,r,i,a){this.opcode=r,this.mask=i,this.is32bit=a,this.canBeShared=!1,e.assert((r&i)==r),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=s(n);this.name=o[0],this.args=o.slice(1)}emit(t){let n=t.words;if(n[0]!=this.name)return r;let i=this.opcode,a=1,o=0,s=[],l=null,u=null,d=null;for(let r=0;r<this.args.length;++r){let p=this.args[r],f=n[a++];if("$"==p[0]){let r=this.ei.encoders[p],_=null;if(r.isRegister){if(_=this.ei.registerNo(f),null==_)return c("expecting register name",f);this.ei.isPush(this.opcode)?o++:this.ei.isPop(this.opcode)&&o--}else if(r.isImmediate){if(f=f.replace(/^#/,""),_=t.bin.parseOneInt(f),null==_)return c("expecting number",f);this.ei.isAddSP(this.opcode)?o=-_/this.ei.wordSize():this.ei.isSubSP(this.opcode)&&(o=_/this.ei.wordSize())}else if(r.isRegList){if("{"!=f)return c("expecting {",f);for(_=0;"}"!=n[a];){if(f=n[a++],!f)return c("expecting }",n[a-2]);let e=this.ei.registerNo(f);if(null==e)return c("expecting register name",f);if(_&1<<e)return c("duplicate register name",f);_|=1<<e,this.ei.isPush(this.opcode)?o++:this.ei.isPop(this.opcode)&&o--,","==n[a]&&a++}f=n[a++]}else if(r.isLabel){if(f=f.replace(/^#/,""),/^[+-]?\d+$/.test(f))_=parseInt(f,10),l="rel"+_;else if(/^0x[0-9a-fA-F]+$/.test(f))_=parseInt(f,16),l="abs"+_;else if(l=f,_=this.ei.getAddressFromLabel(t.bin,this,f,r.isWordAligned),null==_){if(t.bin.finalEmit)return c("unknown label",f);_=8}if(this.ei.is32bit(this)){u=_,d=f;continue}}else e.oops();if(null==_)return c("didn't understand it",f);if(s.push(_),_=r.encode(_),null==_)return c("argument out of range or mis-aligned",f);e.assert(0==(i&_)),i|=_}else if(p!=f)return c("expecting "+p,f)}return n[a]?c("trailing tokens",n[a]):this.ei.is32bit(this)?this.ei.emit32(i,u,t.bin.normalizeExternalLabel(d)):{stack:o,opcode:i,numArgs:s,labelName:t.bin.normalizeExternalLabel(l)}}toString(){return this.friendlyFmt}}t.Instruction=i;class a{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=s(e)||[],0==this.words.length?this.type="empty":"@"==this.words[0][0]&&(this.type="directive")}}t.Line=a;class o{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.currLine=new a(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}parseOneInt(t){if(!t)return null;if(/^\d+$/.test(t))return parseInt(t,10);const r=t.indexOf("-");if(r>0)return this.parseOneInt(t.slice(0,r))-this.parseOneInt(t.slice(r+1));let i=1;if(t.indexOf("*")>=0){let e=null;for(;null!=(e=/^([^\*]*)\*(.*)$/.exec(t));){let n=this.parseOneInt(e[1]);if(null==n)return null;i*=n,t=e[2]}}if("-"==t[0]?(i*=-1,t=t.slice(1)):"+"==t[0]&&(t=t.slice(1)),/^\d+$/.test(t))return i*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 a=/(.*)>>(\d+)$/.exec(t);if(a){let e=this.parseOneInt(a[1]);return e&=~(-16777216&this.baseOffset),e>>parseInt(a[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 r=/^(\w+)@(-?\d+)$/.exec(t);r&&(1!=i&&this.directiveError(n("multiplication not supported with saved stacks")),this.stackpointers.hasOwnProperty(r[1])?o=this.ei.wordSize()*this.ei.computeStackOffset(r[1],this.stack-this.stackpointers[r[1]]+parseInt(r[2])):this.directiveError(n("saved stack not found"))),r=/^(.*)@(hi|lo|fn)$/.exec(t),r&&this.looksLikeLabel(r[1])&&(o=this.lookupLabel(r[1],!0),null!=o&&("fn"==r[2]?o=this.ei.toFnPtr(o,this.baseOffset,r[1]):(o>>=1,0<=o&&o<=65535?"hi"==r[2]?o=o>>8&255:"lo"==r[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*i}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){let r=null,i=this.scopedName(e);return this.labels.hasOwnProperty(i)?(r=this.labels[i],r=this.ei.postProcessRelAddress(this,r)):this.lookupExternalLabel&&(r=this.lookupExternalLabel(e),null!=r&&(r=this.ei.postProcessAbsAddress(this,r))),null==r&&this.equs.hasOwnProperty(i)&&(r=this.equs[i]),null==r&&t&&(this.finalEmit?this.directiveError(n("unknown label: {0}",e)):r=11111),r}align(t){for(e.assert(2==t||4==t||8==t||16==t);this.location()%t!=0;)this.emitOpCode(0)}pushError(e,t=""){let r={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(r),this.throwOnError)throw new Error(r.message)}directiveError(e){this.pushError(e)}emitString(e,t=!1){function r(e,t){return 255&(e.charCodeAt(t)||0)}let i,a=/^\s*([\w\.]+\s*:\s*)?.\w+\s+(".*")\s*$/.exec(e);if(a&&null!=(i=function(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}}(a[2])))if(this.align(2),t)for(let e=0;e<i.length;e++)this.emitShort(i.charCodeAt(e));else for(let e=0;e<i.length+1;e+=2)this.emitShort(r(i,e+1)<<8|r(i,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 r=this.parseNumber(e);if(null==r){this.directiveError(n("cannot parse number at '{0}'",e[0]));break}if(t.push(r),","!=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 r=t[e],i=t[e+1];0<=r&&i<=255&&0<=i&&r<=255?this.emitShort(255&r|(255&i)<<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(e){let t,r=e.words,i=()=>{2!=r.length&&this.directiveError(n("expecting one argument"))};switch(r[0]){case".ascii":case".asciz":case".string":this.emitString(e.text);break;case".utf16":this.emitString(e.text,!0);break;case".align":if(i(),t=this.parseOneInt(r[1]),null!=t){if(0==t)return;t<=4?this.align(1<<t):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(i(),t=this.parseOneInt(r[1]),null!=t){if(1==t)return;2==t||4==t||8==t||16==t?this.align(t):this.directiveError(n("expecting 2, 4, 8, or 16"))}else this.directiveError(n("expecting number"));break;case".p2align":i(),t=this.parseOneInt(r[1]),null!=t?this.align(1<<t):this.directiveError(n("expecting number"));break;case".byte":this.emitBytes(r);break;case".hex":this.emitHex(r);break;case".hword":case".short":case".2bytes":this.parseNumbers(r).forEach((e=>{-32768<=e&&e<=65535?this.emitShort(65535&e):this.directiveError(n("expecting int16"))}));break;case".word":case".4bytes":case".long":this.parseNumbers(r).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(r);break;case".set":case".equ":/^\w+$/.test(r[1])||this.directiveError(n("expecting name"));const a=this.parseNumbers(r.slice(","==r[2]||"="==r[2]?2:1));1!=a.length&&this.directiveError(n("expecting one value")),void 0!==this.equs[r[1]]&&this.equs[r[1]]!=a[0]&&this.directiveError(n("redefinition of {0}",r[1])),this.equs[r[1]]=a[0];break;case".startaddr":this.location()&&this.directiveError(n(".startaddr can be only be specified at the beginning of the file")),i(),this.baseOffset=this.parseOneInt(r[1]);break;case"@stackmark":i(),this.stackpointers[r[1]]=this.stack;break;case"@stackempty":this.checkStack&&(null==this.stackpointers[r[1]]?this.directiveError(n("no such saved stack")):this.stackpointers[r[1]]!=this.stack&&this.directiveError(n("stack mismatch")));break;case"@scope":this.scope=r[1]||"",this.currLineNo=this.scope?0:this.realCurrLineNo;break;case".syntax":case"@nostackcheck":this.checkStack=!1;break;case"@dummystack":i(),this.stack+=this.parseOneInt(r[1]);break;case".section":case".global":this.stackpointers={},this.stack=0,this.scope="$S"+this.scopeId++;break;case".comm":{r=r.filter((e=>","!=e)),r.shift();let e=this.parseOneInt(r[1]),t=0;if(t=r[2]?this.parseOneInt(r[2]):4,null==this.lookupLabel(r[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(r[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(r[0])||this.directiveError(n("unknown directive"))}}handleOneInstruction(e,t){let r=t.emit(e);return!r.error&&(this.stack+=r.stack,this.checkStack&&this.stack<0&&this.pushError(n("stack underflow")),e.location=this.location(),e.opcode=r.opcode,e.stack=r.stack,this.emitOpCode(r.opcode),null!=r.opcode2&&this.emitOpCode(r.opcode2),null!=r.opcode3&&this.emitOpCode(r.opcode3),e.instruction=t,e.numArgs=r.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 r=e.words[0].toLowerCase().replace(/s$/,"").replace(/[^a-z]/g,""),i="",a=t(r).concat(t(r+"s"));a.length>0&&a.forEach((t=>{let r=t.emit(e);i+=n(" Maybe: {0} ({1} at '{2}')\n",t.toString(),r.error,r.errorAt)})),this.pushError(n("assembly error"),i)}buildLine(e,t){let n=e=>{let n=new a(this,e);return n.scope=this.scope,n.lineNo=this.currLineNo,t.push(n),n},r=n(e),i=s(r.text)||[];r.words=i;let o=i[0]||"";if(":"==o.charAt(o.length-1)){let t=/^([\.\w]+):$/.exec(i[0]);if(t){if(r.type="label",r.text=t[1]+":",r.words=[t[1]],!(i.length>1))return;i.shift(),r=n(e.replace(/^[^:]*:/,"")),r.words=i,o=i[0]||""}}let c=o.charAt(0);"."==c||"@"==c?(r.type="directive","@scope"==r.words[0]&&this.handleDirective(r)):0==r.words.length?r.type="empty":r.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){let r=this.scopedName(t.words[0]);if(this.prevLabel=r,this.finalEmit){null!=this.equs[r]&&this.directiveError(n(".equ redefined as label"));let t=this.labels[r];null==t&&e.oops(),0==this.errors.length&&t!=this.location()&&e.oops(`invalid location: ${this.location()} != ${t} at ${r}`),e.assert(this.errors.length>0||t==this.location()),this.reallyFinalEmit&&(this.stackAtLabel[r]=this.stack)}else this.labels.hasOwnProperty(r)?this.directiveError(n("label redefinition")):this.inlineMode&&/^_/.test(r)?this.directiveError(n("labels starting with '_' are reserved for the compiler")):this.labels[r]=this.location();t.location=this.location()}else"directive"==t.type?this.handleDirective(t):"instruction"==t.type?this.handleInstruction(t):"empty"==t.type||e.oops()}))}getSourceMap(){const e={};let t="",n=0,r=0,i=0;function a(){t&&r&&(e[t]||(e[t]=[]),e[t].push(n,r,i-r)),r=0,i=0}return this.lines.forEach(((e,o)=>{const s=/^; ([\w\/\.-]+)\(([\d]+),\d+\):/.exec(e.text);s&&(a(),t=s[1],n=parseInt(s[2])),"instruction"==e.type&&(r||(r=e.location),i=e.location)})),a(),e}getSource(r,i=1,a=0){let o=0,s=e=>{let t=this.labels[e]||o,n=t-o;return o=t,n},c=this.buf?this.location():0,l=s("_code_end"),u=s("_helpers_end"),d=s("_vtables_end"),p=s("_literals_end"),f=o,_=c+this.baseOffset&16777215;a&&_>a&&e.U.userError(n("program too big by {0} bytes!",_-a));let m=n("; total bytes: {0} ({1}% of {2}k flash with {3} free)",_,(100*_/(a=a||131072)).toFixed(1),(a/1024).toFixed(1),a-_),g=n("; generated code sizes (bytes): {0} (incl. {1} user, {2} helpers, {3} vtables, {4} lits); src size {5}\n",f,l,u,d,p,c-f)+n("; assembly: {0} lines; density: {1} bytes/stmt; ({2} stmts)\n",this.lines.length,Math.round(100*l/i)/100,i)+m+"\n"+this.stats+"\n\n",h=!1;return this.lines.forEach(((e,n)=>{if("_stored_program"==e.words[0])return g+='_stored_program: .string "..."\n',void(h=!0);if(h)return void(h=!1);let i=e.text;if(r){if("@stackempty"==e.words[0]&&this.lines[n-1].text==e.text)return;if(i=i.replace(/; WAS: .*/,""),!i.trim())return}t.debug&&("label"!=e.type&&"instruction"!=e.type||(i+=` \t; 0x${(e.location+this.baseOffset).toString(16)}`)),g+=i+"\n"})),g}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 r=e[t+1];if(!r)continue;let i=e[t+2];"instruction"==n.type&&this.ei.peephole(n,r,i)}}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=o;t.VMFile=class extends o{constructor(e){super(e)}};function s(e){let t=[],n="";e:for(let r=0;r<e.length;++r)switch(e[r]){case"[":case"]":case"!":case"{":case"}":case",":n&&(t.push(n),n=""),t.push(e[r]);break;case" ":case"\t":case"\r":case"\n":n&&(t.push(n),n="");break;case";":break e;default:n+=e[r]}return n&&(t.push(n),n=""),t[0]?t:null}function c(e,t){return{stack:null,opcode:null,error:e,errorAt:t}}function l(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 r={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]=r,r},this.inrange=(e,t,n)=>Math.floor(t)!=t||t<0||t>e?null:n,this.inminmax=(e,t,n,r)=>Math.floor(n)!=n||n<e||n>t?null:r,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,r)=>{let a=new i(this,e,t,n,r);return this.instructions.hasOwnProperty(a.name)||(this.instructions[a.name]=[]),this.instructions[a.name].push(a),a},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,r=!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=c,t.expectError=function(t,n){let r=new o(t);r.emit(n),0==r.errors.length&&e.oops("ASMTEST: expecting error for: "+n)},t.tohex=l,t.expect=function(t,n){let r=[],i=n.replace(/^([0-9a-fA-F]{4,8})\s/gm,((e,t)=>(r.push(parseInt(t.slice(0,4),16)),8==t.length&&r.push(parseInt(t.slice(4,8),16)),""))),a=new o(t);a.throwOnError=!0,a.disablePeepHole=!0,a.emit(i),a.errors.length>0&&(console.debug(a.errors[0].message),e.oops("ASMTEST: not expecting errors")),a.buf.length!=r.length&&e.oops("ASMTEST: wrong buf len");for(let t=0;t<r.length;++t)a.buf[t]!=r[t]&&e.oops("ASMTEST: wrong buf content at "+t+" , exp:"+l(r[t])+", got: "+l(a.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 r=!0;function i(t){let r=new Error(n.lf("Cannot access {0} while offline",t));return r.isOffline=!0,e.U.delay(1e3).then((()=>Promise.reject(r)))}function a(n,r){return e.U.requestAsync({url:"/api/"+n,headers:{Authorization:t.localToken},method:r?"POST":"GET",data:r||void 0,allowHttpErrors:!0})}function o(){return e.webConfig&&!e.webConfig.isStatic&&!e.BrowserUtils.isLocalHost()&&!!e.webConfig.cdnUrl}function s(n){if(n=n.replace(/^\//,""),!o())return t.apiRoot+n;const r=new Date,i=r.getUTCFullYear()+("0"+(r.getUTCMonth()+1)).slice(-2)+("0"+r.getUTCDate()).slice(-2);return n.indexOf("?")<0?n+="?":n+="&",n+="cdn="+i,e.webConfig.cdnUrl+"/api/"+n}function c(e){return o()?(e.url=s(e.url),n.requestAsync(e).catch((t=>l(e,t)))):u(e)}function l(e,n){return 0==n.statusCode?(r&&(r=!1,t.onOffline()),i(e.url)):Promise.reject(n)}function u(r){var a;return r.url=(null===(a=e.webConfig)||void 0===a?void 0:a.isStatic)&&!r.forceLiveEndpoint?e.webConfig.relprefix+r.url:t.apiRoot+r.url,r.allowGzipPost=!0,t.isOnline()||e.BrowserUtils.isPxtElectron()?(r.headers||(r.headers={}),e.BrowserUtils.isLocalHost()?t.localToken&&(r.headers.Authorization=t.localToken):t.accessToken&&(r.headers["x-td-access-token"]=t.accessToken),n.requestAsync(r).catch((e=>l(r,e)))):i(r.url)}function d(){return navigator&&navigator.onLine}t.onOffline=()=>{},t.hasAccessToken=function(){return!!t.accessToken},t.localRequestAsync=a,t.useCdnApi=o,t.cdnApiUrl=s,t.apiRequestWithCdnAsync=c,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,r=e.webConfig&&e.webConfig.isStatic?"targetconfig.json":`config/${e.appTarget.id}/targetconfig${n?`/v${n}`:""}`;return e.BrowserUtils.isLocalHost()?a(r).then((e=>e?e.json:void 0)):c({url:r}).then((e=>e.json))},t.downloadScriptFilesAsync=function(e){return u({url:e+"/text",forceLiveEndpoint:!0}).then((e=>JSON.parse(e.text)))},t.markdownAsync=async function(t,n){const r=e.BrowserUtils.isLocalHostDev()?0:36e5,i=24*r*7;n=n||e.Util.userLanguage();const s=await e.BrowserUtils.translationDbAsync(),l=await s.getAsync(n,t,""),d=async()=>{try{const r=await function(t,n,r){var i;const s=null===(i=e.webConfig)||void 0===i?void 0:i.isStatic,l=e.appTarget.versions&&e.appTarget.versions.target||"?";let d;if(s){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(l)}`;"en"!=n&&(d+=`${s?"?":"&"}lang=${encodeURIComponent(n)}`);if(e.BrowserUtils.isLocalHost()&&!e.Util.liveLocalizationEnabled())return a(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=r&&!o()?{"If-None-Match":r}:void 0;return c({url:d,method:"GET",headers:e}).then((e=>({md:e.text,etag:e.headers.etag})))}}(t,n,null==l?void 0:l.etag);return!l||r.md&&l.md!==r.md?(await s.setAsync(n,t,"",r.etag,void 0,r.md),r.md):l.md}catch(e){return""}};if(l){const t=Date.now()-l.time,n=t>r;if(t>i)e.tickEvent("markdown.update.wait");else if(n&&(e.tickEvent("markdown.update.background"),d()),l.md)return l.md}return d()},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()&&(r=!0),r},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){const r=e.appTarget;if(!(t&&r.appTheme&&r.cloud&&r.cloud.sharing))return;let i=["makecode.com"];r.appTheme.embedUrl&&i.push(r.appTheme.embedUrl),r.appTheme.shareUrl&&i.push(r.appTheme.shareUrl),i=n.unique(i,(e=>e)).map((e=>n.escapeForRegex(n.stripUrlProtocol(e).replace(/\/$/,"")).toLowerCase()));const a=`^((https://)?(?:${i.join("|")})/)?(?:v[0-9]+/)?(api/oembed?url=.*%2F([^&]*)&.*?|([a-z0-9-_]+))$`,o=new RegExp(a,"i").exec(t.trim()),s=o&&(!o[1]||i.indexOf(n.escapeForRegex(o[1].replace(/https:\/\//,"").replace(/\/$/,"")).toLowerCase())>=0)&&(o[3]||o[4])?o[3]?o[3]:o[4]:null;return s&&("_"==s[0]&&13==s.length||23==s.length&&/^[0-9\-]+$/.test(s))?s:void 0}}(e.Cloud||(e.Cloud={}))}(pxt||(pxt={})),function(e){!function(e){e.f4EncodeImg=function(e,t,n,r){let i=[135,n,255&e,e>>8,255&t,t>>8,0,0].map(l).join(""),a=4,o=0,s=0,c=e=>{o|=e<<s,s==8-n?(i+=l(o),a++,o=0,s=0):s+=n};for(let i=0;i<e;++i){for(let e=0;e<t;++e)c(r(i,e));for(;0!=s;)c(0);if(n>1)for(;3&a;)c(0)}return i;function l(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),r=0;for(let e=0;e<this.numRows;e++){let i=0;n[e]=[];for(let r=0;r<this.numCols;r++)this.melody[r][e]&&(n[e].push(t(r)),i++);i>r&&(r=i)}if(0==r)return"- - - - - - - - ";for(let t=0;t<r;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,r,i){const a=t("div",{className:"melody-gallery-button melody-editor-card",role:"menuitem",id:`:${n}`}),o=t("i",{className:"music icon melody-icon"}),s=t("div",{className:"melody-editor-text"});s.innerText=e.name;const c=this.createColorBlock(e),l=t("div",{className:"melody-editor-button left-button",role:"button",title:e.name},(()=>this.handleSelection(e)));l.appendChild(o),l.appendChild(s),l.appendChild(c),a.appendChild(l);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),a.appendChild(u),this.contentDiv.appendChild(a)}handleSelection(e){if(this.pending){const t=this.pending;this.pending=void 0,t(e.notes)}}playNote(e,t,n){let r=0;switch(e){case"C5":r=523;break;case"B":r=494;break;case"A":r=440;break;case"G":r=392;break;case"F":r=349;break;case"E":r=330;break;case"D":r=294;break;case"C":r=262}this.timeouts.push(setTimeout((()=>{pxt.AudioContextManager.tone(r)}),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 r=t.notes.split(" ");for(let t=0;t<r.length;t++){let i=e.getColorClass(e.noteToRow(r[t])),a=document.createElement("div");0==t?pxt.BrowserUtils.addClass(a,"left-edge sliver "+i):t==r.length-1?pxt.BrowserUtils.addClass(a,"right-edge sliver "+i):pxt.BrowserUtils.addClass(a,"sliver "+i),n.appendChild(a)}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){let t,n=!1;class r{constructor(e){this.db=e}loadAsync(n,r,i,a){if(!/^v\d+\.\d+\.\d+$/.test(r))return a(n,r);const o=`gh-${i}-${n}#${r}`;return t.cacheGet(o).then((i=>{if(i){const t=e.Util.jsonTryParse(i);if(t)return e.debug(`cache hit ${o}`),Promise.resolve(t)}return a(n,r).then((n=>n?(e.debug(`cached ${o}`),t.cacheSet(o,JSON.stringify(n)).then((()=>n))):n))}))}loadConfigAsync(e,t){return this.loadAsync(e,t,"pxt",((e,t)=>this.db.loadConfigAsync(e,t)))}loadPackageAsync(e,t){return this.loadAsync(e,t,"pkg",((e,t)=>this.db.loadPackageAsync(e,t)))}}class i{constructor(e){this.packageFiles=e}resolve(e,t){return""}readFile(t,n){const r="this"==t.id?n:"pxt_modules/"+t.id+"/"+n;return void 0!==this.packageFiles[r]?this.packageFiles[r]:e.appTarget.bundledpkgs[t.id]?e.appTarget.bundledpkgs[t.id][n]:null}writeFile(t,n,r){const i="this"==t.id?"":"pxt_modules/"+t.id+"/";e.debug(`write file ${i+n}`),this.packageFiles[i+n]=r}getHexInfoAsync(e){return Promise.resolve({hex:["SKIP"]})}cacheStoreAsync(e,n){return(null==t?void 0:t.cacheSet)?t.cacheSet(e,n):Promise.resolve()}cacheGetAsync(e){return(null==t?void 0:t.cacheGet)?t.cacheGet(e):Promise.resolve("")}downloadPackageAsync(r){return n?function(e){const n=null==t?void 0:t.pkgOverrideAsync;return(n?n(e.id):Promise.resolve(void 0)).then((t=>t||e.commonDownloadAsync()))}(r).then((t=>{t&&e.U.iterMap(t,((e,t)=>{this.writeFile(r,e,t)}))})):Promise.resolve()}resolveVersionAsync(e){return Promise.resolve("*")}}function a(t){if(t.target.preferredEditor==e.PYTHON_PROJECT_NAME){const n=e.U.clone(t);n.ast=!0,n.target.preferredEditor=e.JAVASCRIPT_PROJECT_NAME;for(let t of n.sourceFiles)e.U.endsWith(t,".py")&&(n.fileSystem[t.slice(0,-3)+".ts"]=" ");const r=pxtc.compile(n);t.apisInfo=pxtc.getApiInfo(r.ast,n.jres)}}function o(t,n){const r=new i(t),o=new e.MainPackage(r);return o.loadAsync().then((()=>{let e=o.getTargetOptions();return e.hasHex&&(e.isNative=n.native),o.getCompileOptionsAsync(e)})).then((e=>(s(o.targetVersion(),e),a(e),e)))}function s(t,n){if(t){e.debug(`applying TS patches relative to ${t}`);for(let r of Object.keys(n.fileSystem))if(-1==r.indexOf("/")&&e.U.endsWith(r,".ts")){const i=n.fileSystem[r],a=e.patching.patchJavaScript(t,i);i!=a&&(e.debug(`applying TS patch to ${r}`),n.fileSystem[r]=a)}}}e.SimpleHost=i,e.prepPythonOptions=a,e.simpleInstallPackagesAsync=function(t){const n=new i(t);return new e.MainPackage(n).loadAsync(!0)},e.simpleGetCompileOptionsAsync=o,e.simpleCompileAsync=function(e,t){return o(e,"boolean"==typeof t?{native:t}:t||{}).then((e=>pxtc.compile(e))).then((e=>(e.success||(e.errors=e.diagnostics.map(ts.pxtc.getDiagnosticString).join("")||"Unknown error."),e)))},e.patchTS=s,e.setupSimpleCompile=function(i){"undefined"==typeof global||global.btoa||(global.btoa=function(e){return Buffer.from(e,"binary").toString("base64")},global.atob=function(e){return Buffer.from(e,"base64").toString("binary")}),"undefined"!=typeof pxtTargetBundle&&(e.debug("setup app bundle"),e.setAppTarget(pxtTargetBundle)),i&&(t=i,n=!0,i.httpRequestAsync&&(e.Util.httpRequestCoreAsync=i.httpRequestAsync),e.github.forceProxy=!0,e.github.db=new r(new e.github.MemoryGithubDb)),e.debug("simple setup done")}}(pxt||(pxt={})),function(e){e.simshim=function(t,n){let r,i=ts.SyntaxKind,a=t.getTypeChecker(),o=e.cpp.nsWriter("declare namespace"),s="";for(let a of t.getSourceFiles()){if(n){let t=n(a.fileName);if(e.debug("SimShim[1]: "+t.dir),!e.U.endsWith(t.dir,"/sim")&&!e.U.startsWith(a.fileName,"sim/"))continue}else if(!e.U.startsWith(a.fileName,"sim/"))continue;e.debug("SimShim[2]: "+a.fileName);for(let e of a.statements){let t=e;e.kind==i.ModuleDeclaration&&"pxsim"==t.name.text&&(r=t,m(t.body))}}let c={};return c[e.appTarget.corepkg]=o.finish(),c;function l(e){let t;return ts.isExpression(e)&&(t=a.getContextualType(e)),t||(t=a.getTypeAtLocation(e)),t}function u(e){let t=a.typeToString(e,r,ts.TypeFormatFlags.UseFullyQualifiedType);switch(t=t.replace(/^pxsim\./,""),t){case"RefAction":return"() => void";case"RefBuffer":return"Buffer";default:return t}}function d(e){let t=pxtc.getComments(e);return/^\s*\/\/%/m.test(t)?t:null}function p(e){let t=d(e);if(!t)return;let n=e.name.getText(),r="//% shim=."+n,i=a.getTypeAtLocation(e);o.write(t),o.write(r),o.write(`public ${n}: ${u(i)};`),o.write("")}function f(e){let t=d(e);if(!t)return;a.getTypeAtLocation(e);let n=e.parameters.map((e=>e.name.getText()+": "+u(l(e))));o.write(t),o.write(`//% shim="new ${s}"`),o.write(`constructor(${n.join(", ")});`),o.write("")}function _(t,n=!1){let r=d(t);if(!r)return;let c=t.name.getText(),p=t.kind==i.MethodDeclaration||t.kind==i.GetAccessor||t.kind==i.SetAccessor,f="//% shim="+(p?"."+c:s+"::"+c),_=a.getSignatureFromDeclaration(t),m=a.getReturnTypeOfSignature(_),g=/Async$/.test(c),h=(y=m,pxtc.isObjectType(y)&&y.objectFlags&ts.ObjectFlags.Reference&&"Promise"==y.symbol.name?y.typeArguments[0]:null);var y;h?(f+=" promise",m=h,g||e.U.userError(`${s}::${c} should be called ${c}Async`)):g&&e.U.userError(`${s}::${c} doesn't return a promise`),e.debug("emitFun: "+c);let v=t.parameters.map((e=>`${e.name.getText()}${e.questionToken?"?":""}: ${u(l(e))}`)),b=c.replace(/Async$/,""),x=p?"public":"function",k=`(${v.join(", ")})`;t.kind==i.GetAccessor&&(x=n?"public":"readonly",k="",f+=" property"),p||o.setNs(s),o.write(r),o.write(f),o.write(`${x} ${b}${k}: ${u(m)};`),o.write("")}function m(e){switch(e.kind){case i.ModuleDeclaration:return function(e){let t=s;s&&(s+="."),s+=e.name.text,m(e.body),s=t}(e);case i.ModuleBlock:return e.statements.forEach(m);case i.FunctionDeclaration:return _(e);case i.ClassDeclaration:return function(e){let t=d(e);if(!t)return;o.setNs(s),o.write(t);let n=s;s&&(s+="."),s+=e.name.text;let r=n?"":"declare",a="";if(e.heritageClauses)for(let t of e.heritageClauses)t.token==i.ExtendsKeyword&&(a=" extends "+u(l(t.types[0])));o.write(`${r} class ${e.name.text}${a} {`),o.incrIndent();for(let t of e.members)switch(t.kind){case i.MethodDeclaration:_(t);break;case i.PropertyDeclaration:p(t);break;case i.Constructor:f(t);break;case i.GetAccessor:let n=e.members.some((e=>e.kind==i.SetAccessor&&e.name.getText()==t.name.getText()));_(t,n)}s=n,o.decrIndent(),o.write("}")}(e)}}}}(pxt||(pxt={})),function(e){!function(t){t.annotate=function(n,r,i){const a=t.target;t.target=i;let o=n.getSourceFiles().filter((e=>e.fileName===r))[0],s=n.getTypeChecker();function c(n,r,i=!1,a=null){let o=i||!(u(n).flags&e.TypeFlags.Void),c=a||l(n);if(n.expression&&c){let e=!1;switch(c.kind){case t.SK.PropertySignature:case t.SK.PropertyAssignment:case t.SK.PropertyDeclaration:t.isStatic(c)||(e=!0);break;case t.SK.Parameter:t.isCtorField(c)&&(e=!0);break;case t.SK.GetAccessor:case t.SK.SetAccessor:case t.SK.MethodDeclaration:case t.SK.MethodSignature:e=!0}if(e){const e=n.expression;e.kind===t.SK.PropertyAccessExpression?r.unshift(e.expression):r.unshift(n.expression)}}let d={decl:c,qName:c?t.getNodeFullName(s,c):"?",args:r,isExpression:o};t.pxtInfo(n).callInfo=d}function l(n){if(!n)return null;let r,i=s.getSymbolAtLocation(n);if(i&&(r=i.valueDeclaration,!r&&i.declarations)){let t=i.declarations[0];t&&t.kind==e.SyntaxKind.ImportEqualsDeclaration&&(i=s.getSymbolAtLocation(t.moduleReference),i&&(r=i.valueDeclaration))}if(!r&&n.kind==t.SK.PropertyAccessExpression){const e=n;r={kind:t.SK.PropertySignature,symbol:{isBogusSymbol:!0,name:e.name.getText()},name:e.name},t.pxtInfo(r).flags|=2}return r}function u(n){let r;const i=t.pxtInfo(n);return i.typeCache?i.typeCache:(e.isExpression(n)&&(r=s.getContextualType(n)),r||(r=s.getTypeAtLocation(n)),r?e.isStringLiteral(n)?r:t.checkType(r):r)}!function n(r){e.forEachChild(r,(r=>{switch(r.kind){case e.SyntaxKind.CallExpression:c(r,r.arguments.slice(0),null,l(r.expression));break;case e.SyntaxKind.PropertyAccessExpression:c(r,[]);break;case e.SyntaxKind.TaggedTemplateExpression:c(r,[r.template],!0,l(r.tag));break;case e.SyntaxKind.BinaryExpression:!function(n){const r=n.left,i=n.right;let a=u(n.left),o=u(n.right);n.operatorToken.kind!=t.SK.PlusToken&&n.operatorToken.kind!=t.SK.PlusEqualsToken||(t.isStringType(a)||t.isStringType(o)&&n.operatorToken.kind==t.SK.PlusToken)&&(t.pxtInfo(n).exprInfo={leftType:s.typeToString(a),rightType:s.typeToString(o)});switch(n.operatorToken.kind){case e.SyntaxKind.EqualsToken:case e.SyntaxKind.PlusEqualsToken:case e.SyntaxKind.MinusEqualsToken:if(r.kind==t.SK.PropertyAccessExpression){let n=l(r);n&&n.kind==t.SK.GetAccessor?(n=e.getDeclarationOfKind(n.symbol,t.SK.SetAccessor),c(r,[i],!1,n)):n&&(n.kind==t.SK.PropertySignature||n.kind==t.SK.PropertyAssignment||t.target&&t.target.switches.slowFields)&&c(r,[i])}}}(r);break;case e.SyntaxKind.Identifier:const n=l(r);if(n&&n.getSourceFile().fileName!==pxt.MAIN_TS&&n.kind==e.SyntaxKind.VariableDeclaration){const e=t.pxtInfo(r);e.flags|=4,e.commentAttrs||(e.commentAttrs=t.parseComments(n))}}n(r)}))}(o),t.target=a}}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){function t(e){let t='"';for(let n=0;n<e.length;++n){let r=255&e.charCodeAt(n),i=String.fromCharCode(r);t+="\\"==i||'"'==i?"\\"+i:"\n"==i?"\\n":r<=15?"\\x0"+r.toString(16):r<32||r>127?"\\x"+r.toString(16):i}return t+'"'}e.asmStringLiteral=t;function n(n){let r="pxt::string_inline_ascii_vt",i=e.target.utf8?e.U.toUTF8(n,!0):n,a="";if(i!==n)if(n.length>16){r="pxt::string_skiplist16_packed_vt";let o=[],s=0;for(let t=0;t+16<=n.length;t+=16)s+=e.U.toUTF8(n.slice(t,t+16),!0).length,o.push(s);a=`\n .short ${i.length}, ${n.length}\n .short ${o.map((e=>e.toString())).join(", ")}\n .string ${t(i)}\n`}else r="pxt::string_inline_utf8_vt";return a||(a=`\n .short ${i.length}\n .string ${t(i)}\n`),{vt:r,asm:a}}function r(e,t=""){return`\n .word ${e.length>>1}${t}\n .hex ${e}${e.length%4==0?"":"00"}\n `}e.AssemblerSnippets=class{nop(){return"TBD(nop)"}reg_gets_imm(e,t){return"TBD(reg_gets_imm)"}proc_setup(e,t){return"TBD(proc_setup)"}push_fixed(e){return"TBD(push_fixed)"}push_local(e){return"TBD(push_local)"}push_locals(e){return"TBD(push_locals)"}pop_fixed(e){return"TBD(pop_fixed)"}pop_locals(e){return"TBD(pop_locals)"}proc_return(){return"TBD(proc_return)"}debugger_stmt(e){return""}debugger_bkpt(e){return""}debugger_proc(e){return""}unconditional_branch(e){return"TBD(unconditional_branch)"}beq(e){return"TBD(beq)"}bne(e){return"TBD(bne)"}cmp(e,t){return"TBD(cmp)"}cmp_zero(e){return"TBD(cmp_zero)"}arithmetic(){return""}load_reg_src_off(e,t,n,r,i,a){return"TBD(load_reg_src_off)"}rt_call(e,t,n){return"TBD(rt_call)"}call_lbl(e,t){return"TBD(call_lbl)"}call_reg(e){return"TBD(call_reg)"}helper_prologue(){return"TBD(lambda_prologue)"}helper_epilogue(){return"TBD(lambda_epilogue)"}pop_clean(e){return"TBD"}load_ptr_full(e,t){return"TBD(load_ptr_full)"}emit_int(e,t){return"TBD(emit_int)"}obj_header(e){return`.word ${e}`}string_literal(e,t){const r=n(t);return`\n .balign 4\n ${e}: ${this.obj_header(r.vt)}\n ${r.asm}\n`}hex_literal(e,t){return`\n.balign ${/f{16}/i.test(t)?8:4}\n${e}: ${this.obj_header("pxt::buffer_vt")}\n${r(t)}\n`}},e.utf8AsmStringLiteral=n,e.hexLiteralAsm=r,e.numBytes=function(e){let t=0;for(let n=e;n>0;n>>>=8)t++;return t||1};e.ProctoAssembler=class{constructor(t,n,r){this.resText="",this.exprStack=[],this.calls=[],this.proc=null,this.baseStackSize=0,this.labelledHelpers={},this.write=t=>{this.resText+=e.asmline(t)},this.t=t,this.bin=n,this.proc=r,this.proc&&this.work()}emitHelpers(){this.emitLambdaTrampoline(),this.emitArrayMethods(),this.emitFieldMethods(),this.emitBindHelper()}redirectOutput(t){let n=this.write,r="";this.write=t=>r+=e.asmline(t);try{t()}finally{this.write=n}return r}stackSize(){return this.baseStackSize+this.exprStack.length}stackAlignmentNeeded(t=0){if(!e.target.stackAlign)return 0;let n=e.target.stackAlign-(this.stackSize()+t&e.target.stackAlign-1);return n==e.target.stackAlign?0:n}getAssembly(){return this.resText}work(){this.write(`\n;\n; Function ${this.proc.getFullName()}\n;\n`);let t=this.proc.label(),n=t+"_pre",r=t+"_bkpt",i=t+"_locals",a=t+"_end";this.write(`${n}:`),this.emitLambdaWrapper(this.proc.isRoot),this.write(".section code"),this.write(`${t}:`),this.proc.classInfo&&this.proc.info.thisParameter&&!e.target.switches.skipClassCheck&&!e.target.switches.noThisCheckOpt&&(this.write("mov r7, lr"),this.write("ldr r0, [sp, #0]"),this.emitInstanceOf(this.proc.classInfo,"validate"),this.write("mov lr, r7")),this.write(`\n${t}_nochk:\n @stackmark func\n @stackmark args\n`),this.proc.fillDebugInfo=t=>{let o=t.getLabels();this.proc.debugInfo={locals:(1==this.proc.seqNo?this.bin.globals:this.proc.locals).map((e=>e.getDebugInfo())),args:this.proc.args.map((e=>e.getDebugInfo())),name:this.proc.getName(),codeStartLoc:e.U.lookup(o,i),codeEndLoc:e.U.lookup(o,a),bkptLoc:e.U.lookup(o,r),localsMark:e.U.lookup(t.stackAtLabel,i),idx:this.proc.seqNo,calls:this.calls,size:e.U.lookup(o,a)+2-e.U.lookup(o,n)};for(let n of this.calls)n.addr=e.U.lookup(o,n.callLabel),n.stack=e.U.lookup(t.stackAtLabel,n.callLabel),n.callLabel=void 0;for(let n=0;n<this.proc.body.length;++n){let r=this.proc.body[n].breakpointInfo;if(r){let n=e.U.lookup(t.stackAtLabel,`__brkp_${r.id}`);n!==this.proc.debugInfo.localsMark&&(console.log(r),console.log(t.stackAtLabel),e.U.oops(`offset doesn't match: ${n} != ${this.proc.debugInfo.localsMark}`))}}},this.bin.options.breakpoints&&this.write(this.t.debugger_proc(r)),this.baseStackSize=1;let o=this.proc.locals.length;this.write("push {lr}"),this.write(".locals:\n"),this.proc.perfCounterNo&&(this.write(this.t.emit_int(this.proc.perfCounterNo,"r0")),this.write("bl pxt::startPerfCounter")),this.write(this.t.proc_setup(o)),this.baseStackSize+=o,this.write("@stackmark locals"),this.write(`${i}:`);for(let t=0;t<this.proc.body.length;++t){let n=this.proc.body[t];switch(n.stmtKind){case e.ir.SK.Expr:this.emitExpr(n.expr);break;case e.ir.SK.StackEmpty:if(this.exprStack.length>0){for(let e of this.proc.body.slice(t-4,t+1))console.log(`PREVSTMT ${e.toString().trim()}`);for(let e of this.exprStack)console.log(`EXPRSTACK ${e.currUses}/${e.totalUses} E: ${e.toString()}`);e.oops("stack should be empty")}this.write("@stackempty locals");break;case e.ir.SK.Jmp:this.emitJmp(n);break;case e.ir.SK.Label:this.write(n.lblName+":"),this.validateJmpStack(n);break;case e.ir.SK.Comment:this.write(`; ${n.expr.data}`);break;case e.ir.SK.Breakpoint:if(this.bin.options.breakpoints){let e=`__brkp_${n.breakpointInfo.id}`;n.breakpointInfo.isDebuggerStmt?this.write(this.t.debugger_stmt(e)):this.write(this.t.debugger_bkpt(e))}break;default:e.oops()}}e.assert(0<=o&&o<127),o>0&&this.write(this.t.pop_locals(o)),this.proc.perfCounterNo&&(this.write("mov r4, r0"),this.write(this.t.emit_int(this.proc.perfCounterNo,"r0")),this.write("bl pxt::stopPerfCounter"),this.write("mov r0, r4")),this.write(`${a}:`),this.write(this.t.proc_return()),this.write("@stackempty func"),this.write("@stackempty args"),this.write("; endfun")}mkLbl(e){let t=e+this.bin.lblNo++;return"_"!=t[0]&&(t="."+t),t}dumpStack(){let e="[";for(let t of this.exprStack)e+=t.sharingInfo()+": "+t.toString()+"; ";return e+="]",e}terminate(t){e.assert(t.exprKind==e.ir.EK.SharedRef);let n=t.args[0];e.U.assert(n.currUses!=n.totalUses),e.U.assert(this.exprStack[0]===n,"term at top");let r=1;for(;r<this.exprStack.length;){let e=this.exprStack[r];if(e.currUses!=e.totalUses)break;r++}return this.write(`@dummystack ${r}`),this.write(this.t.pop_locals(r)),r}validateJmpStack(t,n=0){let r=this.exprStack.length-n;null==t.lblStackSize?t.lblStackSize=r:t.lblStackSize!=r&&(console.log(t.lblStackSize,r),console.log(this.dumpStack()),e.U.oops("stack misaligned at: "+t.lblName))}emitJmp(t){let n=0;if(t.jmpMode==e.ir.JmpMode.Always)t.expr&&this.emitExpr(t.expr),t.terminateExpr&&(n=this.terminate(t.terminateExpr)),this.write(this.t.unconditional_branch(t.lblName)+" ; with expression");else{let r=this.mkLbl("jmpz");this.emitExpr(t.expr),(t.expr.exprKind!=e.ir.EK.RuntimeCall||"thumb::subs"!==t.expr.data&&!e.U.startsWith(t.expr.data,"_cmp_"))&&this.write(this.t.cmp_zero("r0")),t.jmpMode==e.ir.JmpMode.IfNotZero?this.write(this.t.beq(r)):this.write(this.t.bne(r)),t.terminateExpr&&(n=this.terminate(t.terminateExpr)),this.write(this.t.unconditional_branch(t.lblName)),this.write(r+":")}this.validateJmpStack(t.lbl,n)}clearStack(e=!1){let t=0;for(;this.exprStack.length>0&&this.exprStack[0].currUses==this.exprStack[0].totalUses;)t++,this.exprStack.shift();if(t&&this.write(this.t.pop_locals(t)),!e){let e=this.exprStack.filter((e=>e.currUses==e.totalUses&&-1!=e.irCurrUses));if(e.length>0){this.write(this.t.reg_gets_imm("r7",0));for(let t of e)t.irCurrUses=-1,this.write(this.loadFromExprStack("r7",t,0,!0))}}}emitExprInto(t,n){switch(t.exprKind){case e.ir.EK.NumberLiteral:"number"==typeof t.data?this.write(this.t.emit_int(t.data,n)):e.oops();break;case e.ir.EK.PointerLiteral:this.write(this.t.load_ptr_full(t.data,n));break;case e.ir.EK.SharedRef:let r=t.args[0];e.U.assert(!!r.currUses),e.U.assert(r.currUses<r.totalUses),r.currUses++;let i=this.exprStack.indexOf(r);if(e.U.assert(i>=0),0==i&&r.totalUses==r.currUses)this.write(this.t.pop_fixed([n])+` ; tmpref @${this.exprStack.length}`),this.exprStack.shift(),this.clearStack();else{let e=i.toString()+":"+this.exprStack.length;this.write(this.t.load_reg_src_off(n,"sp",e,!0)+" ; tmpref @"+(this.exprStack.length-i))}break;case e.ir.EK.CellRef:let a=t.data;if(a.isGlobal()){let e=this.bitSizeInfo(a.bitSize),t="#"+a.index;(e.needsSignExt||a.index>=e.immLimit)&&(this.write(this.t.emit_int(a.index,n)),t=n),this.write(this.t.load_reg_src_off("r7","r6","#0")),this.write(this.t.load_reg_src_off(n,"r7",t,!1,!1,e))}else{let[e,t,r]=this.cellref(a);this.write(this.t.load_reg_src_off(n,e,t,r))}break;default:e.oops()}}bitSizeInfo(t){let n={size:e.sizeOfBitSize(t),immLimit:128};return 1==n.size?n.immLimit=32:2==n.size&&(n.immLimit=64),1!=t&&3!=t||(n.needsSignExt=!0),n}emitExpr(t){switch(t.exprKind){case e.ir.EK.JmpValue:this.write("; jmp value (already in r0)");break;case e.ir.EK.Nop:this.write(this.t.nop());break;case e.ir.EK.FieldAccess:return this.emitExpr(t.args[0]),this.emitFieldAccess(t);case e.ir.EK.Store:return this.emitStore(t.args[0],t.args[1]);case e.ir.EK.RuntimeCall:return this.emitRtCall(t);case e.ir.EK.ProcCall:return this.emitProcCall(t);case e.ir.EK.SharedDef:return this.emitSharedDef(t);case e.ir.EK.Sequence:return t.args.forEach((e=>this.emitExpr(e))),this.clearStack();case e.ir.EK.InstanceOf:return this.emitExpr(t.args[0]),this.emitInstanceOf(t.data,t.jsInfo);default:return this.emitExprInto(t,"r0")}}emitFieldAccess(t,n=!1){let r=t.data,i=(n?"st":"ld")+"fld_"+r.classInfo.id+"_"+r.name;r.needsCheck&&!e.target.switches.skipClassCheck&&(this.emitInstanceOf(r.classInfo,"validate"),i+="_chk");let a=4*r.idx+4,o="#"+a;a>124&&(this.write(this.t.emit_int(a,"r3")),o="r3"),n?this.write(`str r1, [r0, ${o}]`):this.write(`ldr r0, [r0, ${o}]`)}writeFailBranch(){this.write(".fail:"),this.write("mov r1, lr"),this.write(this.t.callCPP("pxt::failedCast"))}emitClassCall(t){let n=t.virtualIndex+e.firstMethodOffset();this.write(this.t.emit_int(4*n,"r1"));let r=t.classInfo,i="";t.isThis&&(i+="_this"),this.emitLabelledHelper("classCall_"+r.id+i,(()=>{this.write("ldr r0, [sp, #0] ; ld-this"),this.loadVTable(),e.target.switches.skipClassCheck||t.isThis||this.checkSubtype(r),this.write("ldr r1, [r3, r1] ; ld-method"),this.write("bx r1 ; keep lr from caller"),this.writeFailBranch()}))}emitBindHelper(){this.write(`\n .section code\n _pxt_bind_helper:\n push {r0, r2}\n movs r0, #2\n ldlit r1, _pxt_bind_lit\n ${this.t.callCPP("pxt::mkAction")}\n pop {r1, r2}\n str r1, [r0, #12]\n str r2, [r0, #16]\n bx r4 ; return\n\n _pxt_bind_lit:\n ${this.t.obj_header("pxt::RefAction_vtable")}\n .short 0, 0 ; no captured vars\n .word .bindCode@fn\n .bindCode:\n ; r0-bind object, r4-#args\n cmp r4, #12\n bge .fail\n lsls r3, r4, #2\n ldlit r2, _pxt_copy_list\n ldr r1, [r2, r3]\n\n ldr r3, [r0, #12]\n ldr r2, [r0, #16]\n adds r4, r4, #1\n bx r1\n `),this.writeFailBranch(),this.write("_pxt_copy_list:"),this.write(e.U.range(12).map((e=>`.word _pxt_bind_${e}@fn`)).join("\n"));for(let e=0;e<12;e++){this.write(`\n _pxt_bind_${e}:\n sub sp, #4\n `);for(let t=0;t<e;++t)this.write(`ldr r1, [sp, #4*${t+1}]`),this.write(`str r1, [sp, #4*${t}]`);this.write(`\n push {r3} ; this-ptr\n mov r1, lr\n str r1, [sp, #4*${e+1}] ; store LR\n blx r2\n ldr r1, [sp, #4*${e+1}]\n add sp, #8\n bx r1\n `)}}ifaceCallCore(t,n,r=!1){this.write("\n ldr r2, [r3, #12] ; load mult\n movs r7, r2\n beq .objlit ; built-in types have mult=0\n muls r7, r1\n lsrs r7, r2\n lsls r7, r7, #1 ; r7 - hash offset\n ldr r3, [r3, #4] ; iface table\n adds r3, r3, r7\n ; r0-this, r1-method idx, r2-free, r3-hash entry, r4-num args, r7-free\n ");for(let t=0;t<e.vtLookups;++t)t>0&&this.write(" adds r3, #2"),this.write("\n ldrh r2, [r3, #0] ; r2-offset of descriptor\n ldrh r7, [r2, r3] ; r7-method idx\n cmp r7, r1\n beq .hit\n ");"get"==n?(this.write("movs r0, #0 ; undefined"),this.write("bx lr")):this.write("b .fail2"),this.write("\n .hit:\n adds r3, r3, r2 ; r3-descriptor\n ldr r2, [r3, #4]\n lsls r7, r2, #31\n beq .field\n ");const i=this.t.emit_int(t,"r4")+"\n bx r2";if("set"==n?this.write(`\n ; check for next descriptor\n ldrh r7, [r3, #8]\n cmp r7, r1\n bne .fail2 ; no setter!\n ldr r2, [r3, #12]\n ${i}\n `):(this.write("\n ; check if it's getter\n ldrh r7, [r3, #2]\n cmp r7, #1\n "),"get"==n?this.write(`\n bne .bind\n ${i}\n .bind:\n mov r4, lr\n bl _pxt_bind_helper\n `):this.write(`\n beq .doublecall\n ${i}\n .doublecall:\n ; call getter\n movs r4, #1\n push {r0, lr}\n blx r2\n pop {r1, r2}\n mov lr, r2\n b .moveArgs\n `)),r||(this.write(`\n .objlit:\n ldrh r2, [r3, #8]\n cmp r2, #${pxt.BuiltInType.RefMap}\n bne .fail\n mov r4, lr\n `),"set"==n&&this.write("ldr r2, [sp, #4] ; ld-val"),this.write(this.t.callCPP("set"==n?"pxtrt::mapSet":"pxtrt::mapGet")),n?this.write("bx r4"):(this.write("mov lr, r4"),this.write("b .moveArgs"))),this.write(".field:"),"set"==n?this.write("\n ldr r3, [sp, #4] ; ld-val\n str r3, [r0, r2] ; store field\n bx lr\n "):"get"==n?this.write("\n ldr r0, [r0, r2] ; load field\n bx lr\n "):this.write("\n ldr r0, [r0, r2] ; load field\n "),!n){this.write(".moveArgs:");for(let e=0;e<t;++e)e==t-1?this.write("movs r1, r0"):this.write(`ldr r1, [sp, #4*${e+1}]`),this.write(`str r1, [sp, #4*${e}]`);this.lambdaCall(t-1)}r&&this.write(".objlit:"),this.writeFailBranch(),this.write(`\n .fail2:\n ${this.t.callCPP("pxt::missingProperty")}\n `)}emitIfaceCall(t,n,r=""){e.U.assert(t.ifaceIndex>0),this.write(this.t.emit_int(t.ifaceIndex,"r1")),this.emitLabelledHelper("ifacecall"+n+"_"+r,(()=>{this.write("ldr r0, [sp, #0] ; ld-this"),this.loadVTable(),this.ifaceCallCore(n,r)}))}checkSubtype(e,t=".fail",n="r2"){e.classNo?(this.write(`ldrh ${n}, [r3, #8]`),this.write(`cmp ${n}, #${e.classNo}`),e.classNo==e.lastSubtypeNo?this.write(`bne ${t}`):(this.write(`blt ${t}`),this.write(`cmp ${n}, #${e.lastSubtypeNo}`),this.write(`bgt ${t}`))):this.write(`b ${t} ; always fails; class never instantiated`)}loadVTable(e="r2",t=".fail",n=".fail"){this.write(`lsls ${e}, r0, #30`),this.write(`bne ${t}`),this.write("cmp r0, #0"),this.write(`beq ${n}`),this.write("ldr r3, [r0, #0]"),this.write("; vtable in R3")}emitInstanceOf(t,n){let r="inst_"+t.id+"_"+n;this.emitLabelledHelper(r,(()=>{"validateNullable"==n?this.loadVTable("r2",".tagged",".undefined"):this.loadVTable("r2",".fail",".fail"),this.checkSubtype(t),"bool"==n?(this.write(`movs r0, #${e.taggedTrue}`),this.write("bx lr"),this.write(".fail:"),this.write(`movs r0, #${e.taggedFalse}`),this.write("bx lr")):"validate"==n?(this.write("bx lr"),this.writeFailBranch()):"validateNullable"==n?(this.write(".undefined:"),this.write("bx lr"),this.write(".tagged:"),this.write(`cmp r0, #${e.taggedNull} ; check for null`),this.write("bne .fail"),this.write("movs r0, #0"),this.write("bx lr"),this.writeFailBranch()):e.U.oops()}))}emitSharedDef(t){let n=t.args[0];if(e.U.assert(n.totalUses>=1),e.U.assert(0===n.currUses),n.currUses=1,1==n.totalUses)return this.emitExpr(n);this.emitExpr(n),this.exprStack.unshift(n),this.write(this.t.push_local("r0")+"; tmpstore @"+this.exprStack.length)}clearArgs(t,n){t.length,n.length;let r=t.concat(n);for(let t of r)0==t.currUses&&1==t.totalUses||(console.log(t.toString()),console.log(r.map((e=>e.toString()))),e.U.oops(`wrong uses: ${t.currUses} ${t.totalUses}`)),t.currUses=1;this.clearStack()}builtInClassNo(e){return{id:"builtin"+e,classNo:e,lastSubtypeNo:e}}emitBeginTry(e){this.emitExprInto(e.args[0],"r0"),this.write("bl _pxt_save_exception_state")}emitRtCall(t,n=null){let r=t.data;if("pxt::beginTry"==r)return this.emitBeginTry(t);let i=t.mask||{refMask:0},a=i.conversions||[],o=t.args.map(((e,t)=>({idx:t,expr:e,isSimple:e.isLiteral(),isRef:0!=(i.refMask&1<<t),conv:a.find((e=>e.argIdx==t))})));e.U.assert(o.length<=4);let s=!1;for(let t of e.U.reversed(o))t.expr.isPure()?t.isSimple||t.isRef||s&&!t.expr.isStateless()||(t.isSimple=!0):s=!0;for(let e of o)e.conv&&(e.isSimple=!1);let c=o.filter((e=>!e.isSimple));if(c.every((e=>e.expr.isPure()&&!e.isRef&&!e.conv))){for(let e of c)e.isSimple=!0;c=[]}let l=c[0],u=!0;if(1!=c.length||l.conv||l.isRef){for(let e of c)this.pushArg(e.expr);this.alignExprStack(0);let t=c.filter((e=>!!e.conv));if(t.length){const n=this.redirectOutput((()=>{let n=0;e.target.switches.inlineConversions||(this.t.stackAligned()?n+=2:n+=1);for(let r of t){if(e.isThumb()&&"pxt::toInt"==r.conv.method){this.write(this.loadFromExprStack("r0",r.expr,n)),this.write("asrs r0, r0, #1");let t=e.target.switches.inlineConversions?r.expr.getId():n;this.write("bcs .isint"+t),this.write("lsls r0, r0, #1"),this.alignedCall(r.conv.method,"",n),this.write(".isint"+t+":"),this.write(this.t.push_fixed(["r0"]))}else this.write(this.loadFromExprStack("r0",r.expr,n)),r.conv.refTag?e.target.switches.skipClassCheck||this.emitInstanceOf(this.builtInClassNo(r.conv.refTag),r.conv.refTagNullable?"validateNullable":"validate"):(this.alignedCall(r.conv.method,"",n),r.conv.returnsRef&&this.write(this.loadFromExprStack("r0",r.expr,n,!0))),this.write(this.t.push_fixed(["r0"]));n++}for(let r of e.U.reversed(t))n--,this.write(this.t.pop_fixed(["r"+r.idx]));for(let e of c)e.conv||this.write(this.loadFromExprStack("r"+e.idx,e.expr,n))}));e.target.switches.inlineConversions?this.write(n):this.emitHelper(this.t.helper_prologue()+n+this.t.helper_epilogue(),"conv")}else for(let e of c)this.write(this.loadFromExprStack("r"+e.idx,e.expr))}else this.emitExpr(l.expr),0!=l.idx&&this.write(this.t.mov("r"+l.idx,"r0")),u=!1;for(let e of o)e.isSimple&&this.emitExprInto(e.expr,"r"+e.idx);n?n():"langsupp::ignore"!=r&&this.alignedCall(r,"",0,!0),u&&this.clearArgs(c.filter((e=>!e.isRef)).map((e=>e.expr)),c.filter((e=>e.isRef)).map((e=>e.expr)))}alignedCall(t,n="",r=0,i=!1){(e.U.startsWith(t,"_cmp_")||e.U.startsWith(t,"_pxt_"))&&(i=!1),this.write(this.t.call_lbl(t,i,this.stackAlignmentNeeded(r))+n)}emitLabelledHelper(e,t){if(this.labelledHelpers[e])this.write(this.t.call_lbl(this.labelledHelpers[e]));else{let n=this.redirectOutput(t);this.emitHelper(n,e),this.labelledHelpers[e]=this.bin.codeHelpers[n]}}emitHelper(e,t="hlp"){if(!this.bin.codeHelpers[e]){let n=Object.keys(this.bin.codeHelpers).length;this.bin.codeHelpers[e]=`_${t}_${n}`}this.write(this.t.call_lbl(this.bin.codeHelpers[e]))}pushToExprStack(e){e.totalUses=1,e.currUses=0,this.exprStack.unshift(e)}pushArg(e){this.clearStack(!0);this.exprStack.length;this.emitExpr(e),this.clearStack(!0),this.write(this.t.push_local("r0")+" ; proc-arg"),this.pushToExprStack(e)}loadFromExprStack(t,n,r=0,i=!1){let a=this.exprStack.indexOf(n);return e.assert(a>=0),this.t.load_reg_src_off(t,"sp",(a+r).toString(),!0,i)+" ; estack\n"}pushDummy(){let t=e.ir.numlit(0);t.totalUses=1,t.currUses=1,this.exprStack.unshift(t)}alignExprStack(e){let t=this.stackAlignmentNeeded(e);if(t)for(let e=0;e<t;++e)this.write("push {r5} ; align"),this.pushDummy()}emitFieldMethods(){for(let t of["get","set"]){this.write(`\n .section code\n _pxt_map_${t}:\n `),this.loadVTable("r4"),this.checkSubtype(this.builtInClassNo(pxt.BuiltInType.RefMap),".notmap","r4"),this.write(this.t.callCPPPush("set"==t?"pxtrt::mapSetByString":"pxtrt::mapGetByString")),this.write(".notmap:");let n="set"==t?2:1,r=!1;this.write("mov r4, r3 ; save VT"),"set"==t?(e.target.stackAlign&&(r=!0,this.write("push {lr} ; align")),this.write("\n push {r0, r2, lr}\n mov r0, r1\n ")):this.write("\n push {r0, lr}\n mov r0, r1\n "),this.write("\n bl pxtrt::lookupMapKey\n mov r1, r0 ; put key index in r1\n ldr r0, [sp, #0] ; restore obj pointer\n mov r3, r4 ; restore vt\n bl .dowork\n "),this.write(this.t.pop_locals(n+(r?1:0))),this.write("pop {pc}"),this.write(".dowork:"),this.ifaceCallCore(n,t,!0)}}emitArrayMethod(t,n){this.write(`\n .section code\n _pxt_${n?"buffer":"array"}_${t}:\n `),this.loadVTable("r4");let r=this.builtInClassNo(n?pxt.BuiltInType.BoxedBuffer:pxt.BuiltInType.RefCollection);e.target.switches.skipClassCheck||this.checkSubtype(r,".fail","r4");const i=e.isStackMachine()||e.target.runtimeIsARM||n?"ldr":"ldrh";this.write(`\n asrs r1, r1, #1\n bcc .notint\n ${i} r4, [r0, #${n?4:8}]\n cmp r1, r4\n bhs .oob\n `);let a="r1";n?(a="#8",this.write("\n adds r4, r0, r1\n ")):this.write("\n lsls r1, r1, #2\n ldr r4, [r0, #4]\n ");let o=n?"b":"",s=n&&"get"==t?"lsls r0, r0, #1\nadds r0, #1":"";"set"==t?this.write(`\n str${o} r2, [r4, ${a}]\n bx lr\n `):this.write(`\n ldr${o} r0, [r4, ${a}]\n ${s}\n bx lr\n `),this.write(`\n .notint:\n lsls r1, r1, #1\n ${this.t.pushLR()}\n push {r0, r2}\n mov r0, r1\n ${this.t.callCPP("pxt::toInt")}\n mov r1, r0\n pop {r0, r2}\n .doop:\n ${this.t.callCPP(`Array_::${t}At`)}\n ${s}\n ${this.t.popPC()}\n `),this.writeFailBranch(),"get"==t?this.write(`\n .oob:\n movs r0, #${n?1:0} ; 0 or undefined\n bx lr\n `):this.write(`\n .oob:\n ${this.t.pushLR()}\n b .doop\n `)}emitArrayMethods(){for(let e of["get","set"])this.emitArrayMethod(e,!0),this.emitArrayMethod(e,!1)}emitLambdaTrampoline(){let t=e.target.stackAlign?"r3,":"";this.write(`\n .section code\n _pxt_lambda_trampoline:\n push {${t} r4, r5, r6, r7, lr}\n mov r4, r8\n mov r5, r9\n mov r6, r10\n mov r7, r11\n push {r4, r5, r6, r7} ; save high registers\n mov r4, r1\n mov r5, r2\n mov r6, r3\n mov r7, r0\n `),this.emitInstanceOf(this.builtInClassNo(pxt.BuiltInType.RefAction),"validate"),this.write(`\n mov r0, sp\n push {r4, r5, r6, r7} ; push args and the lambda\n mov r1, sp\n bl pxt::pushThreadContext\n mov r6, r0 ; save ctx or globals\n mov r5, r7 ; save lambda for closure\n mov r0, r5 ; also save lambda pointer in r0 - needed by pxt::bindMethod\n ldr r1, [r5, #8] ; ld fnptr\n movs r4, #3 ; 3 args\n blx r1 ; execute the actual lambda\n mov r7, r0 ; save result\n @dummystack 4\n add sp, #4*4 ; remove arguments and lambda\n mov r0, r6 ; or pop the thread context\n bl pxt::popThreadContext\n mov r0, r7 ; restore result\n pop {r4, r5, r6, r7} ; restore high registers\n mov r8, r4\n mov r9, r5\n mov r10, r6\n mov r11, r7\n pop {${t} r4, r5, r6, r7, pc}`),this.write(`\n .section code\n ; r0 - try frame\n ; r1 - handler PC\n _pxt_save_exception_state:\n push {r0, lr}\n ${this.t.callCPP("pxt::beginTry")}\n pop {r1, r4}\n str r1, [r0, #1*4] ; PC\n mov r1, sp\n str r1, [r0, #2*4] ; SP\n str r5, [r0, #3*4] ; lambda ptr\n bx r4\n `),this.write("\n .section code\n ; r0 - try frame\n ; r1 - thread context\n _pxt_restore_exception_state:\n mov r6, r1\n ldr r1, [r0, #2*4] ; SP\n mov sp, r1\n ldr r5, [r0, #3*4] ; lambda ptr\n ldr r1, [r0, #1*4] ; PC\n movs r0, #1\n orrs r1, r0\n bx r1\n "),this.write("\n .section code\n _pxt_stringConv:\n "),this.loadVTable(),this.checkSubtype(this.builtInClassNo(pxt.BuiltInType.BoxedString),".notstring"),this.write(`\n bx lr\n\n .notstring: ; no string, but vtable in r3\n ldr r7, [r3, #4*${e.firstMethodOffset()-1}]\n cmp r7, #0\n beq .fail\n push {r0, lr}\n movs r4, #1\n blx r7\n str r0, [sp, #0]\n b .numops\n\n .fail: ; not an object or no toString\n push {r0, lr}\n .numops:\n ${this.t.callCPP("numops::toString")}\n pop {r1}\n pop {pc}\n `)}emitProcCall(t){let n=[],r=null,i="",a=t.data;if(a.proc&&a.proc.inlineBody)return this.emitExpr(a.proc.inlineSelf(t.args));let o=-1==a.virtualIndex,s=!1;for(let r of e.U.reversed(t.args)){if(r.isPure()){if(!s||r.isStateless())continue}else s=!0;n.push(r)}if(n.reverse(),n.length<=1){let e=n[0];e&&(r=e,this.clearStack(!0),this.emitExpr(e),e==t.args[t.args.length-1]?i="r0":(i="r3",this.write(this.t.mov("r3","r0")))),n=[]}else for(let e of n)this.pushArg(e);this.alignExprStack(t.args.length);let c=["r1","r2","r3","r4"],l=[];if(n.length){let e=-1;for(let t of n)e=Math.max(this.exprStack.indexOf(t),e);if(e++,e<=c.length){c=c.slice(0,e),this.write(this.t.pop_fixed(c)),l=this.exprStack.splice(0,e);let t=[];for(let r=e-1;r>=0;--r)n.indexOf(l[r])<0&&(t.push(c[r]),this.exprStack.unshift(l[r]));t.length&&this.write(this.t.push_fixed(t))}else c=null,this.write(this.t.reg_gets_imm("r7",0))}let u=e.U.reversed(t.args);o&&u.unshift(u.pop());for(let t of u)if(n.indexOf(t)>=0){if(c)this.write(this.t.push_fixed([c[l.indexOf(t)]]));else{this.write(this.loadFromExprStack("r0",t)),this.write(this.t.push_local("r0")+" ; re-push"),this.write(this.loadFromExprStack("r7",t,1,!0));let n=this.exprStack.indexOf(t),r=e.ir.numlit(0);r.currUses=1,r.totalUses=1,this.exprStack[n]=r}this.exprStack.unshift(t)}else t===r?(this.write(this.t.push_local(i)+" ; the one arg"),this.pushToExprStack(t)):this.pushArg(t);let d=this.mkLbl("_proccall"),p=-1;if(o){let e=t.args.length-1;this.write(this.loadFromExprStack("r0",t.args[0])),this.emitLabelledHelper("lambda_call"+e,(()=>{this.lambdaCall(e),this.writeFailBranch()}))}else if(null!=a.virtualIndex||null!=a.ifaceIndex)null!=a.ifaceIndex?a.isSet?(e.assert(2==t.args.length),this.emitIfaceCall(a,t.args.length,"set")):this.emitIfaceCall(a,t.args.length,a.noArgs?"get":""):this.emitClassCall(a),this.write(d+":");else{let e=a.proc;p=e.seqNo,this.write(this.t.call_lbl(e.label()+(a.isThis?"_nochk":""))),this.write(d+":")}this.calls.push({procIndex:p,stack:0,addr:0,callLabel:d}),o&&t.args[0].isStateless()?this.clearArgs([t.args[0]],t.args.slice(1)):this.clearArgs([],t.args)}lambdaCall(t){this.write("; lambda call"),this.loadVTable(),e.target.switches.skipClassCheck||this.checkSubtype(this.builtInClassNo(pxt.BuiltInType.RefAction)),this.write(`\n movs r4, #${t}\n ldrh r1, [r0, #4]\n cmp r1, #0\n bne .pushR5\n ldr r1, [r0, #8]\n bx r1 ; keep lr from the caller\n .pushR5:\n sub sp, #8\n `);for(let e=0;e<t;++e)this.write(`ldr r1, [sp, #4*${e+2}]`),this.write(`str r1, [sp, #4*${e}]`);this.write(`\n str r5, [sp, #4*${t}]\n mov r1, lr\n str r1, [sp, #4*${t+1}]\n mov r5, r0\n ldr r7, [r5, #8]\n blx r7 ; exec actual lambda\n ldr r4, [sp, #4*${t+1}] ; restore what was in LR\n ldr r5, [sp, #4*${t}] ; restore lambda ctx\n `);for(let e=0;e<t;++e)this.write(`ldr r1, [sp, #4*${e}]`),this.write(`str r1, [sp, #4*${e+2}]`);this.write("\n add sp, #8\n bx r4\n "),this.write("; end lambda call")}emitStore(t,n){switch(t.exprKind){case e.ir.EK.CellRef:let r=t.data;if(this.emitExpr(n),r.isGlobal()){let e=this.bitSizeInfo(r.bitSize),t="#"+r.index;r.index>=e.immLimit&&(this.write(this.t.emit_int(r.index,"r1")),t="r1"),this.write(this.t.load_reg_src_off("r7","r6","#0")),this.write(this.t.load_reg_src_off("r0","r7",t,!1,!0,e))}else{let[e,t,n]=this.cellref(r);this.write(this.t.load_reg_src_off("r0",e,t,n,!0))}break;case e.ir.EK.FieldAccess:this.emitRtCall(e.ir.rtcall("dummy",[t.args[0],n]),(()=>this.emitFieldAccess(t,!0)));break;default:e.oops()}}cellref(t){if(t.isGlobal())throw e.oops();if(t.iscap){let n=t.index+3;return e.assert(0<=n&&n<32),["r5",n.toString(),!0]}if(t.isarg){return["sp","args@"+t.index.toString()+":"+this.baseStackSize,!1]}return["sp","locals@"+t.index,!1]}emitLambdaWrapper(e){if(this.write(""),this.write(".section code"),this.write(".balign 4"),e&&(this.proc.info.usedAsValue=!0),!this.proc.info.usedAsValue&&!this.proc.info.usedAsIface)return;this.proc.info.usedAsValue&&(this.write(this.proc.label()+"_Lit:"),this.write(this.t.obj_header("pxt::RefAction_vtable")),this.write(".short 0, 0 ; no captured vars"),this.write(`.word ${this.proc.label()}_args@fn`)),this.write(`${this.proc.label()}_args:`);let t=this.proc.args.length;if(0==t)return;this.write(`cmp r4, #${t}`),this.write(`bge ${this.proc.label()}_nochk`);let n=this.stackAlignmentNeeded(t+1),r=n?t+2:t+1;this.write("push {lr}"),this.emitLabelledHelper(`expand_args_${t}`,(()=>{this.write("movs r0, #0"),this.write("movs r1, #0"),n&&this.write("push {r0}");for(let e=t;e>0;e--)e!=t&&(this.write(`cmp r4, #${e}`),this.write(`blt .zero${e}`),this.write(`ldr r0, [sp, #${r-1}*4]`),this.write(`str r1, [sp, #${r-1}*4] ; clear existing`),this.write(`.zero${e}:`)),this.write("push {r0}");this.write("bx lr")})),this.write(`bl ${this.proc.label()}_nochk`);let i=t+(n?1:0);this.write(`@dummystack ${i}`),this.write(`add sp, #4*${i}`),this.write("pop {pc}")}emitCallRaw(t){let n=e.hexfile.lookupFunc(t);e.assert(!!n,"unimplemented raw function: "+t),this.alignedCall(t)}}}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){const t={"numops::adds":"+","numops::subs":"-","numops::div":"/","numops::mod":"%","numops::muls":"*","numops::ands":"&","numops::orrs":"|","numops::eors":"^","numops::bnot":"~","numops::lsls":"<<","numops::asrs":">>","numops::lsrs":">>>","numops::le":"<=","numops::lt":"<","numops::lt_bool":"<","numops::ge":">=","numops::gt":">","numops::eq":"==","pxt::eq_bool":"==","pxt::eqq_bool":"===","numops::eqq":"===","numops::neqq":"!==","numops::neq":"!="},n={"pxsim.Boolean_":"","pxsim.pxtcore":"","pxsim.String_":"","pxsim.ImageMethods":"","pxsim.Array_":"","pxsim.pxtrt":"","pxsim.numops":""},r={"pxsim.Array_.getAt":"","pxsim.Array_.length":"","pxsim.Array_.mk":"","pxsim.Array_.push":"","pxsim.Boolean_.bang":"","pxsim.String_.concat":"","pxsim.String_.stringConv":"","pxsim.numops.toBool":"","pxsim.numops.toBoolDecr":"","pxsim.pxtcore.mkAction":"","pxsim.pxtcore.mkClassInstance":"","pxsim.pxtrt.ldlocRef":"","pxsim.pxtrt.mapGetByString":"","pxsim.pxtrt.stclo":"","pxsim.pxtrt.stlocRef":""};function i(e){let t="";for(let n of Object.keys(e)){const r=n.replace(/\./g,"_");e[n]=r,t+=`const ${r} = ${n};\n`}return t}function a(e){"pxt."==(e=e.replace(/::/g,".")).slice(0,4)&&(e="pxtcore."+e.slice(4));const t="pxsim."+e;if(r.hasOwnProperty(t))return r[t];const i=t.lastIndexOf(".");if(i>0){const e=t.slice(0,i);if(n.hasOwnProperty(e))return n[e]+t.slice(i)}return t}e.isBuiltinSimOp=function(n){return!!e.U.lookup(t,n.replace(/\./g,"::"))},e.shimToJs=a;const o=["runtime","oops","doNothing","pxsim","globals","maybeYield","setupDebugger","isBreakFrame","breakpoint","trace","checkStack","leave","checkResumeConsumed","setupResume","setupLambda","checkSubtype","failedCast","buildResume","mkVTable","bind","leaveAccessor"];e.jsEmit=function(s){let c="(function (ectx) {\n'use strict';\n";for(let e of o)c+=`const ${e} = ectx.${e};\n`;c+="const __this = runtime;\n",c+="const pxtrt = pxsim.pxtrt;\n",c+="let yieldSteps = 1;\n",c+="ectx.setupYield(function() { yieldSteps = 100; })\n",c+="pxsim.setTitle("+JSON.stringify(s.getTitle())+");\n";let l={},u={};for(let e of s.res.configData||[])l[e.key+""]=e.value,u[e.name]=e.key;c+="pxsim.setConfigData("+JSON.stringify(l,null,1)+", "+JSON.stringify(u,null,1)+");\n",c+="pxtrt.mapKeyNames = "+JSON.stringify(s.ifaceMembers,null,1)+";\n";const d=s.setPerfCounters(["SysScreen"]);c+="__this.setupPerfCounters("+JSON.stringify(d,null,1)+");\n",c+=i(r),c+=i(n);let p=0,f=0;s.procs.forEach((n=>{let r;n.cachedJS?(r=n.cachedJS,p+=r.length):(r=function(n,r){if(r.cachedJS)return r.cachedJS;let i="",o=e=>{i+=e+"\n"},s=e=>{i+=" "+e+"\n"},c=e.ir.EK,l=[],u=0,d={},p="";o(`\nfunction ${r.label()}(s) {\nlet r0 = s.r0, step = s.pc;\ns.pc = -1;\n`),r.perfCounterNo&&o(`if (step == 0) __this.startPerfCounter(${r.perfCounterNo});\n`);o("\nwhile (true) {\nif (yieldSteps-- < 0 && maybeYield(s, step, r0) || runtime !== pxsim.runtime) return null;\nswitch (step) {\n case 0:\n"),r.locals.forEach((e=>{s(`${v(e)} = undefined;`)})),r.args.length&&(s("if (s.lambdaArgs) {"),r.args.forEach(((e,t)=>{s(` ${v(e)} = (s.lambdaArgs[${t}]);`)})),s(" s.lambdaArgs = null;"),s("}"));r.classInfo&&r.info.thisParameter&&(s("r0 = s.arg0;"),E(r.classInfo,"validate"));let f=0,_=[];for(let t of r.body)t.stmtKind==e.ir.SK.Label&&t.lblNumUses>0&&(t.lblId=++f);let m=0;for(let t of r.body){switch(t.stmtKind){case e.ir.SK.Expr:T(t.expr);break;case e.ir.SK.StackEmpty:P();break;case e.ir.SK.Jmp:let n=!1;for(let i=m+1;i<r.body.length&&r.body[i].stmtKind==e.ir.SK.Label;++i)if(t.lbl==r.body[i]){n=!0;break}b(t,n);break;case e.ir.SK.Label:t.lblNumUses>0&&o(` case ${t.lblId}:`);break;case e.ir.SK.Comment:o(`// ${t.expr.data}`);break;case e.ir.SK.Breakpoint:y(t);break;default:e.oops()}m++}P(),r.perfCounterNo&&o(`__this.stopPerfCounter(${r.perfCounterNo});\n`);r.isGetter()?s("return leaveAccessor(s, r0)"):s("return leave(s, r0)");o(" default: oops()"),o("} } }");let g=e.nodeLocationInfo(r.action);g.functionName=r.getName(),g.argumentNames=r.args&&r.args.map((e=>e.getName())),o(`${r.label()}.info = ${JSON.stringify(g)}`),r.isGetter()&&o(`${r.label()}.isGetter = true;`);r.isRoot&&o(`${r.label()}.continuations = [ ${_.join(",")} ]`);return o(h(r.label()+"_mk",r.label(),u,Object.keys(d))),o(p),r.cachedJS=i,i;function h(e,t,n,r){let i="";i+=`\nfunction ${e}(s) {\n checkStack(s.depth);\n return {\n parent: s, fn: ${t}, depth: s.depth + 1,\n pc: 0, retval: undefined, r0: undefined, overwrittenPC: false, lambdaArgs: null,\n`;for(let e=0;e<n;++e)i+=` tmp_${e}: undefined,\n`;for(let e of r)i+=` ${e}: undefined,\n`;return i+="} }\n",i}function y(e){let t,i=e.breakpointInfo.id;if(s(`s.lastBrkId = ${i};`),n.options.breakpoints){t=++f;let a=`return breakpoint(s, ${t}, ${i}, r0);`;e.breakpointInfo.isDebuggerStmt?s(a):(s(`if ((breakpoints[0] && isBreakFrame(s)) || breakpoints[${i}]) ${a}`),n.options.trace&&s(`else return trace(${i}, s, ${t}, ${r.label()}.info);`))}else{if(!n.options.trace)return;t=++f,s(`return trace(${i}, s, ${t}, ${r.label()}.info);`)}o(` case ${t}:`)}function v(e){if(e.isGlobal())return"globals."+e.uniqueName();if(e.iscap)return`s.caps[${e.index}]`;const t=e.uniqueName();return d[t]=!0,"s."+t}function b(t,n){if(t.lbl.lblNumUses==e.ir.lblNumUsesJmpNext||n)return e.assert(t.jmpMode==e.ir.JmpMode.Always),void(t.expr&&T(t.expr));e.assert(t.lbl.lblNumUses>0);let r=`{ step = ${t.lbl.lblId}; continue; }`;t.jmpMode==e.ir.JmpMode.Always?(t.expr&&T(t.expr),s(r)):(T(t.expr),t.jmpMode==e.ir.JmpMode.IfNotZero?s(`if (r0) ${r}`):s(`if (!r0) ${r}`))}function x(e){switch(e.exprKind){case c.NumberLiteral:case c.PointerLiteral:case c.SharedRef:case c.CellRef:return!0;default:return!1}}function k(e){return x(e)?S(e):(T(e),"r0")}function S(t){switch(t.exprKind){case c.NumberLiteral:if(!0===t.data)return"true";if(!1===t.data)return"false";if(null===t.data)return"null";if(void 0===t.data)return"undefined";if("number"==typeof t.data)return t.data+"";throw e.oops("invalid data: "+typeof t.data);case c.PointerLiteral:if(t.ptrlabel())return t.ptrlabel().lblId+"";if(null!=t.hexlit())return p+=`const ${t.data} = pxsim.BufferMethods.createBufferFromHex("${t.hexlit()}")\n`,t.data;if("string"==typeof t.jsInfo)return t.jsInfo;e.U.oops();case c.SharedRef:let n=t.args[0];e.U.assert(!!n.currUses),e.U.assert(n.currUses<n.totalUses),n.currUses++;let r=l.indexOf(n);return e.U.assert(r>=0),"s.tmp_"+r;case c.CellRef:return v(t.data);default:throw e.oops()}}function T(e){switch(e.exprKind){case c.JmpValue:s("// jmp value (already in r0)");break;case c.Nop:s("// nop");break;case c.FieldAccess:let t=e.data,n=t.shimName,r=k(e.args[0]);return n?void s(`r0 = ${r}${n};`):void s(`r0 = ${r}.fields["${t.name}"];`);case c.Store:return I(e.args[0],e.args[1]);case c.RuntimeCall:return A(e);case c.ProcCall:return N(e);case c.SharedDef:return D(e);case c.Sequence:return e.args.forEach(T);case c.InstanceOf:return T(e.args[0]),void E(e.data,e.jsInfo);default:s(`r0 = ${S(e)};`)}}function C(e,t="r0"){return`checkSubtype(${t}, ${`${e.id}_VT`})`}function E(t,n,r="r0"){"bool"==n?s(`r0 = ${C(t)};`):"validate"==n?s(`if (!${C(t,r)}) failedCast(${r});`):e.U.oops()}function D(t){let n=t.args[0];if(e.U.assert(n.totalUses>=1),e.U.assert(0===n.currUses),n.currUses=1,1==n.totalUses)return T(n);{const e=l.length;l.push(n);let t=k(n);"r0"!=t&&(t="r0 = "+t),s(`s.tmp_${e} = ${t};`)}}function A(n){let r=e.ir.flattenArgs(n.args);r.precomp.forEach(T);let i=n.data,c=r.flattened.map(S);if("langsupp::ignore"==i)return;let l="";if(l="."==i[0]?`${c[0]}${i}(${c.slice(1).join(", ")})`:"="==i[0]?`(${c[0]})${i.slice(1)} = (${c[1]})`:e.U.startsWith(i,"new ")?`new ${a(i.slice(4))}(${c.join(", ")})`:e.U.lookup(t,i)?2==c.length?`(${c[0]} ${e.U.lookup(t,i)} ${c[1]})`:`(${e.U.lookup(t,i)} ${c[0]})`:`${a(i)}(${c.join(", ")})`,0==n.callingConvention)s(`r0 = ${l};`);else{let e=++f;_.push(e),"String_::stringConv"==i&&s(`if ((${c[0]}) && (${c[0]}).vtable) {`),2==n.callingConvention?s(`(function(cb) { ${l}.then(cb) })(buildResume(s, ${e}));`):(s(`setupResume(s, ${e});`),s(`${l};`)),s("checkResumeConsumed();"),s("return;"),"String_::stringConv"==i&&s(`} else { s.retval = (${c[0]}) + ""; }`),o(` case ${e}:`),s("r0 = s.retval;")}}function N(t){const i=t.data,a=i.proc;if(a&&a.inlineBody)return T(a.inlineSelf(t.args));const c=e.ir.rtcall("<frame>",[]);c.totalUses=1,c.currUses=0;const u=l.length;l.push(c);const d=`s.tmp_${u}`,p=++f,_=-1==i.virtualIndex;if(a)s(`${d} = ${a.label()}_mk(s);`);else{let a="generic";null!=i.ifaceIndex?a="if_"+n.ifaceMembers[i.ifaceIndex]:_?a="lambda":null!=i.virtualIndex?a=i.classInfo.id+"_v"+i.virtualIndex:e.U.oops();const o=t.args.length;a+="_"+o+"_mk",n.recordHelper(r.usingCtx,a,(()=>{const t=e.U.range(o).map((e=>"arg"+e));return h(a,"null",5,t)})),s(`${d} = ${a}(s);`)}t.args.forEach(((e,t)=>{let n=`arg${t}`;_&&(n=0==t?"argL":"arg"+(t-1)),s(`${d}.${n} = ${k(e)};`)}));let m=`s.pc = ${p}; return ${d};`;if(null!=i.callLocationIndex&&(m=`s.callLocIdx = ${i.callLocationIndex}; ${m}`),null!=i.ifaceIndex){e.U.assert(null==a);const r=n.ifaceMembers[i.ifaceIndex];e.U.assert(!!r,`no name for ${i.ifaceIndex}`),s(`if (!${d}.arg0.vtable.iface) {`);let o=t.args.map(((e,t)=>`${d}.arg${t}`));o.splice(1,0,JSON.stringify(r));const c=`pxsim_pxtrt.map${i.isSet?"Set":"Get"}ByString`;i.noArgs?s(` s.retval = ${c}(${o.join(", ")});`):(e.U.assert(!i.isSet),s(` setupLambda(${d}, ${c}(${o.slice(0,2).join(", ")}), ${t.args.length});`),s(` ${m}`)),s("} else {"),s(` ${d}.fn = ${d}.arg0.vtable.iface["${i.isSet?"set/":""}${r}"];`);let l=`${d}.arg0.fields["${r}"]`;i.isSet?(s(` if (${d}.fn === null) { ${l} = ${d}.arg1; }`),s(` else if (${d}.fn === undefined) { failedCast(${d}.arg0) } `)):i.noArgs?(s(` if (${d}.fn == null) { s.retval = ${l}; }`),s(` else if (!${d}.fn.isGetter) { s.retval = bind(${d}); }`)):(s(` if (${d}.fn == null) { setupLambda(${d}, ${l}, ${t.args.length}); ${m} }`),s(` else if (${d}.fn.isGetter) { ${d}.stage2Call = true; ${m}; }`)),s(` else { ${m} }`),s("}"),m=""}else if(-1==i.virtualIndex)e.U.assert(null==a),s(`setupLambda(${d}, ${d}.argL);`);else if(null!=i.virtualIndex){e.U.assert(null==a),e.assert(i.virtualIndex>=0),E(i.classInfo,"validate",d+".arg0");const t=i.classInfo.vtable[i.virtualIndex];s(`${d}.fn = ${d}.arg0.vtable.methods.${t.getName()};`)}else e.U.assert(null!=a);m&&s(m),o(` case ${p}:`),s("r0 = s.retval;"),c.currUses=1}function w(t){switch(t){case 0:return"";case 1:return"pxtrt.toInt8";case 3:return"pxtrt.toInt16";case 5:return"pxtrt.toInt32";case 2:return"pxtrt.toUInt8";case 4:return"pxtrt.toUInt16";case 6:return"pxtrt.toUInt32";default:throw e.oops()}}function I(t,n){switch(t.exprKind){case c.CellRef:let r=t.data,i=k(n);s(`${v(r)} = ${w(r.bitSize)}(${i});`);break;case c.FieldAccess:let a=t.data,o=a.shimName;o||(o=`.fields["${a.name}"]`),T(e.ir.rtcall("="+o,[t.args[0],n]));break;default:e.oops()}}function P(){for(let t of l)t.totalUses!==t.currUses&&e.oops();u=Math.max(l.length,u),l=[]}}(s,n),f+=r.length),c+="\n"+r+"\n"})),c+=e.U.values(s.codeHelpers).join("\n")+"\n",s.usedClassInfos.forEach((t=>{c+=function(t){e.U.assert(void 0!==t.classNo),e.U.assert(void 0!==t.lastSubtypeNo);let n=parseInt(t.attrs.maxBgInstances);n||(n=null);let r=`const ${t.id}_VT = mkVTable({\n name: ${JSON.stringify(e.getName(t.decl))},\n numFields: ${t.allfields.length},\n classNo: ${t.classNo},\n lastSubtypeNo: ${t.lastSubtypeNo},\n maxBgInstances: ${n},\n methods: {\n`;for(let e of t.vtable)r+=` "${e.getName()}": ${e.label()},\n`;r+=" },\n",r+=" iface: {\n";for(let e of t.itable)r+=` "${e.name}": ${e.proc?e.proc.label():"null"},\n`,e.setProc?r+=` "set/${e.name}": ${e.setProc.label()},\n`:e.proc||(r+=` "set/${e.name}": null,\n`);return r+=" },\n",t.toStringMethod&&(r+=" toStringMethod: "+t.toStringMethod.label()+",\n"),r+="});\n",r}(t)})),s.res.breakpoints&&(c+=`\nconst breakpoints = setupDebugger(${s.res.breakpoints.length}, [${s.globals.filter((e=>e.isUserVariable)).map((e=>`"${e.uniqueName()}"`)).join(",")}])\n`),c+=`\nreturn ${s.procs[0]?s.procs[0].label():"null"}\n})\n`;const _=c.length,m=e=>(100*e/_).toFixed(2)+"%",g=`// total=${c.length} new=${m(f)} cached=${m(p)} other=${m(_-f-p)}\n`;s.writeFile(e.BINARY_JS,g+c)}}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){e.thumbCmpMap={"numops::lt":"_cmp_lt","numops::gt":"_cmp_gt","numops::le":"_cmp_le","numops::ge":"_cmp_ge","numops::eq":"_cmp_eq","numops::eqq":"_cmp_eqq","numops::neq":"_cmp_neq","numops::neqq":"_cmp_neqq"};const t={"numops::adds":"_numops_adds","numops::subs":"_numops_subs","numops::orrs":"_numops_orrs","numops::eors":"_numops_eors","numops::ands":"_numops_ands","numops::lsls":"_numops_lsls","numops::asrs":"_numops_asrs","numops::lsrs":"_numops_lsrs","pxt::toInt":"_numops_toInt","pxt::fromInt":"_numops_fromInt"};class n extends e.AssemblerSnippets{stackAligned(){return e.target.stackAlign&&e.target.stackAlign>1}pushLR(){return this.stackAligned()?"push {lr, r5} ; r5 for align":"push {lr}"}popPC(){return this.stackAligned()?"pop {pc, r5} ; r5 for align":"pop {pc}"}nop(){return"nop"}mov(e,t){return`mov ${e}, ${t}`}helper_ret(){return"bx r4"}reg_gets_imm(e,t){return`movs ${e}, #${t}`}push_fixed(e){return"push {"+e.join(", ")+"}"}pop_fixed(e){return"pop {"+e.join(", ")+"}"}proc_setup(e,t){let n="";if(e>0){n+=" movs r0, #0\n";for(let t=0;t<e;++t)n+=" push {r0} ;loc\n"}return n}proc_return(){return"pop {pc}"}debugger_stmt(t){return e.oops(),`\n @stackempty locals\n ldr r0, [r6, #0] ; debugger\n subs r0, r0, #4 ; debugger\n${t}:\n ldr r0, [r0, #0] ; debugger\n`}debugger_bkpt(t){return e.oops(),`\n @stackempty locals\n ldr r0, [r6, #0] ; brk\n${t}:\n ldr r0, [r0, #0] ; brk\n`}debugger_proc(t){return e.oops(),`\n ldr r0, [r6, #0] ; brk-entry\n ldr r0, [r0, #4] ; brk-entry\n${t}:`}push_local(e){return`push {${e}}`}push_locals(e){return`sub sp, #4*${e} ; push locals ${e} (align)`}pop_locals(e){return`add sp, #4*${e} ; pop locals ${e}`}unconditional_branch(e){return"bb "+e}beq(e){return"beq "+e}bne(e){return"bne "+e}cmp(e,t){return"cmp "+e+", "+t}cmp_zero(e){return"cmp "+e+", #0"}load_reg_src_off(e,t,n,r,i,a){n=n.replace(/:\d+$/,""),r&&(n=`#4*${n}`);let o="str",s="ldr";return a&&(32==a.immLimit?o="strb":64==a.immLimit&&(o="strh"),s=a.needsSignExt?o.replace("str","ldrs"):o.replace("str","ldr")),i?`${o} ${e}, [${t}, ${n}]`:`${s} ${e}, [${t}, ${n}]`}rt_call(e,t,n){return e+" "+t+", "+n}alignedCall(e,t){return t?`${this.push_locals(t)}\nbl ${e}\n${this.pop_locals(t)}`:"bl "+e}call_lbl(n,r,i){let a=e.U.lookup(t,n);return a&&(n=a,r=!1),!r&&n.indexOf("::")>0&&(r=!0),r?this.callCPP(n,i):this.alignedCall(n,i)}call_reg(e){return"blx "+e}helper_prologue(){return`\n @stackmark args\n ${this.pushLR()}\n`}helper_epilogue(){return`\n ${this.popPC()}\n @stackempty args\n`}load_ptr_full(t,n){return e.assert(!!t),`\n ldlit ${n}, ${t}\n`}load_vtable(e,t){return`ldr ${e}, [${t}, #0]`}lambda_init(){return"\n mov r5, r0\n mov r4, lr\n bl pxtrt::getGlobalsPtr\n mov r6, r0\n bx r4\n"}saveThreadStack(){return"mov r7, sp\n str r7, [r6, #4]\n"}restoreThreadStack(){return e.target.switches.gcDebug?"movs r7, #0\n str r7, [r6, #4]\n":""}callCPPPush(e){return this.pushLR()+"\n"+this.callCPP(e)+"\n"+this.popPC()+"\n"}callCPP(e,t){return this.saveThreadStack()+this.alignedCall(e,t)+"\n"+this.restoreThreadStack()}inline_decr(e){return`\n lsls r1, r0, #30\n bne .tag${e}\n bl _pxt_decr\n.tag${e}:\n`}arithmetic(){let t="";const n=e=>{let t=".boxed:\n";return t+=`\n ${this.pushLR()}\n push {r0, r1}\n ${this.saveThreadStack()}\n ${e}\n ${this.restoreThreadStack()}\n add sp, #8\n ${this.popPC()}\n `,t},r=e=>{t+=`\n_numops_${e}:\n @scope _numops_${e}\n lsls r2, r0, #31\n beq .boxed\n lsls r2, r1, #31\n beq .boxed\n`},i=e=>{t+=" blx lr\n",t+=n(`bl numops::${e}`)};for(let e of["adds","subs"])r(e),t+=`\n subs r2, r1, #1\n ${e} r2, r0, r2\n bvs .boxed\n movs r0, r2\n`,i(e);for(let e of["ands","orrs","eors"])r(e),t+=` ${e} r0, r1\n`,"eors"==e&&(t+=" adds r0, r0, #1\n"),i(e);for(let e of["lsls","lsrs","asrs"])r(e),t+="\n ; r3 := (r1 >> 1) & 0x1f\n lsls r3, r1, #26\n lsrs r3, r3, #27\n","asrs"==e?t+="\n asrs r0, r3\n movs r2, #1\n orrs r0, r2\n":(t+="lsrs"==e?"\n asrs r2, r0, #1\n lsrs r2, r3\n lsrs r3, r2, #30\n bne .boxed\n":"\n asrs r2, r0, #1\n lsls r2, r3\n lsrs r3, r2, #30\n beq .ok\n cmp r3, #3\n bne .boxed\n.ok:\n",t+="\n lsls r0, r2, #1\n adds r0, r0, #1\n"),i(e);t+=`\n@scope _numops_toInt\n_numops_toInt:\n asrs r0, r0, #1\n bcc .over\n blx lr\n.over:\n lsls r0, r0, #1\n ${this.callCPPPush("pxt::toInt")}\n\n_numops_fromInt:\n lsls r2, r0, #1\n asrs r1, r2, #1\n cmp r0, r1\n bne .over2\n adds r0, r2, #1\n blx lr\n.over2:\n ${this.callCPPPush("pxt::fromInt")}\n`;for(let r of Object.keys(e.thumbCmpMap))r=r.replace(/.*::/,""),t+=`\n.section code\n_cmp_${r}:\n lsls r2, r0, #31\n beq .boxed\n lsls r2, r1, #31\n beq .boxed\n subs r0, r1\n b${r.replace("qq","q").replace("neq","ne")} .true\n.false:\n movs r0, #0\n bx lr\n.true:\n movs r0, #1\n bx lr\n`,t+=n(`\n bl numops::${r}\n bl numops::toBoolDecr\n cmp r0, #0`);return t}emit_int(t,n){let r=!1;function i(t){e.assert(0<=t&&t<=255);let i="";return r?t&&(i=`adds ${n}, #${t}\n`):i=`movs ${n}, #${t}\n`,r=!0,i}function a(e=8){return`lsls ${n}, ${n}, #${e}\n`}e.assert(null!=t);let o=Math.floor(t),s=!1;o<0&&(s=!0,o=-o);let c=0;if(o>255){let t=o;for(;0==(1&t);)t>>>=1,c++;e.numBytes(t)<e.numBytes(o)?o=t:c=0}let l="";switch(e.numBytes(o)){case 4:l+=i(o>>>24&255),l+=a();case 3:l+=i(o>>>16&255),l+=a();case 2:l+=i(o>>>8&255),l+=a();case 1:l+=i(255&o);break;default:e.oops()}return c&&(l+=a(c)),s&&(l+=`negs ${n}, ${n}\n`),l.split("\n").length>4?`ldlit ${n}, ${Math.floor(t)}\n`:l}}e.ThumbSnippets=n}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){const n={"pxtrt::mapSetGeneric":"mapset","pxtrt::mapGetGeneric":"mapget"},r={};function i(e,n,r){const i=t.computeHashMultiplier(e.itable.map((e=>e.idx))),a=t.U.toArray(i.mapping);for(;3&a.length;)a.push(0);let o=`\n${c(e)}_start:\n .short ${8*e.allfields.length+8} ; size in bytes\n .byte ${pxt.ValTypeObject}, ${pxt.VTABLE_MAGIC} ; magic\n .short ${a.length} ; entries in iface hashmap\n .short ${e.lastSubtypeNo||e.classNo} ; last sub class-id\n .short ${e.classNo} ; class-id\n .short 0 ; reserved\n .word ${i.mult} ; hash-mult\n`;l()?o+="\n .word pxt::RefRecord_destroy\n .word pxt::RefRecord_print\n .word pxt::RefRecord_scan\n .word pxt::RefRecord_gcsize\n .word 0,0,0,0 ; keep in sync with VM_NUM_CPP_METHODS\n":o+="\n .word 0,0, 0,0, 0,0, 0,0 ; space for 4 (VM_NUM_CPP_METHODS) native methods\n",o+=`\n .balign 4\n${e.id}_IfaceVT:\n`;const s=a.length>>2;let u="",d=s,p={};for(let t of e.itable){p[t.idx+""]=d;const e=t.proc?t.proc.isGetter()?1:2:0;u+=` .short ${t.idx}, ${e} ; ${t.name}\n`,u+=` .word ${t.proc?t.proc.vtLabel()+"@fn":t.info}\n`,d+=1,t.setProc&&(u+=` .short ${t.idx}, 2 ; set ${t.name}\n`,u+=` .word ${t.setProc.vtLabel()}@fn\n`,d+=1)}u+=" .word 0, 0, 0, 0 ; the end\n",d+=1;for(let e=0;e<a.length;++e)r.itEntries++,a[e]&&r.itFullEntries++;return o+=" .short "+t.U.toArray(a).map(((e,t)=>p[e+""]||s)).join(", ")+"\n",o+=u,o+="\n",o}let a;function o(e){const t=e.getTime()/1e3;return`${t>>>0}, ${t/4294967296|0}`}!function(e){e[e.Invalid=0]="Invalid",e[e.InfoHeader=1]="InfoHeader",e[e.OpCodeMap=2]="OpCodeMap",e[e.NumberLiterals=3]="NumberLiterals",e[e.ConfigData=4]="ConfigData",e[e.IfaceMemberNames=5]="IfaceMemberNames",e[e.NumberBoxes=6]="NumberBoxes",e[e.Function=32]="Function",e[e.Literal=33]="Literal",e[e.VTable=34]="VTable"}(a||(a={}));let s={};function c(e){return e.classNo||(s[e.id]=e),e.id+"_VT"}function l(){return t.target.useESP}function u(e){return l()?`0xffffffff, ${e}`:`0xffffffff, 0xffffffff ; -> ${e}`}t.vmEmit=function(d,p){let f=`; VM start\n_img_start:\n${t.hexfile.hexPrelude()}\n`;s={};const _={dblText:[],dblBoxText:[],dbls:{},opcodeMap:{},opcodes:t.vm.opcodes.map((e=>"pxt::op_"+e.replace(/ .*/,"")))};for(_.opcodes.unshift(null);_.opcodes.length<128;)_.opcodes.push(null);let m=0;function g(e,t,n,r,i=0){if(f+=`\n; --- ${e}\n.section code\n .set ${e} = ${m}\n`,r)for(let e of r)f+=` .set ${e} = ${m}\n`;f+=`\n_start_${e}:\n .byte ${t}, 0x00\n .short ${i}\n .word _end_${e}-_start_${e}\n`,f+=n(),f+=`\n.balign 8\n_end_${e}:\n`,m++}const h=new Date(0);let y=t.U.toUTF8(p.name,!0);y.length>100&&(y=y.slice(0,100));let v=y.length+1;1&v&&v++;const b=128-v;g("_info",a.InfoHeader,(()=>`\n ; magic - \\0 added by assembler\n .string "\\nPXT64\\n"\n .hex 5471fe2b5e213768 ; magic\n .hex ${t.hexfile.hexTemplateHash()} ; hex template hash\n .hex 0000000000000000 ; @SRCHASH@\n .word ${d.globalsWords} ; num. globals\n .word ${d.nonPtrGlobals} ; non-ptr globals\n .word 0, 0 ; last usage time\n .word ${o(h)} ; installation time\n .word ${o(h)} ; publication time - TODO\n .word _img_end-_img_start ; total image size\n .space 60 ; reserved\n .string ${JSON.stringify(y)}\n .space ${b} ; pad to 128 bytes\n`)),d.procs.forEach((e=>{g(e.label(),a.Function,(()=>function(e,i,a){let o="";const s=e=>{o+=e+"\n"},d=e=>{o+=" "+e+"\n"},p=t.ir.EK;let f=[],_=[],m=!1,g=0,h=0;const y=8388607;pxt.options.debug&&console.log("EMIT",a.toString());v(),o="";for(let e of f)e.reset();return m=!0,t.U.assert(0==h),v(),o;function v(){s(`;\n; ${a.getFullName()}\n;`),d(".section code"),i.procs[0]==a&&s("; main"),d(`.word ${u("pxt::RefAction_vtable")}`),d(`.short 0, ${a.args.length} ; #args`),d(`.short ${a.captured.length}, 0 ; #cap`),d(".word .fnstart-_img_start, 0 ; func+possible padding"),g=a.locals.length+_.length,d(".fnstart:"),d(`pushmany ${g} ; incl. ${_.length} tmps`);for(let e of a.body)switch(e.stmtKind){case t.ir.SK.Expr:C(e.expr);break;case t.ir.SK.StackEmpty:N();for(let e of _)e&&t.oops(`uses: ${e.currUses}/${e.totalUses} ${e.toString()}`);break;case t.ir.SK.Jmp:b(e);break;case t.ir.SK.Label:s(`${e.lblName}:`);break;case t.ir.SK.Comment:s(`; ${e.expr.data}`);break;case t.ir.SK.Breakpoint:break;default:t.oops()}d(`ret ${a.args.length}, ${g}`)}function b(e){let n=e.lbl.lblName;e.jmpMode==t.ir.JmpMode.Always?(e.expr&&C(e.expr),d(`jmp ${n}`)):(C(e.expr),e.jmpMode==t.ir.JmpMode.IfNotZero?d(`jmpnz ${n}`):e.jmpMode==t.ir.JmpMode.IfZero?d(`jmpz ${n}`):t.oops())}function x(e){if(e.isGlobal())return t.U.assert(0==(3&e.index)),"glb "+(e.index>>2)+` ; ${e.getName()}`;if(e.iscap)return"cap "+e.index+` ; ${e.getName()}`;if(e.isarg){let n=a.args.length-e.index-1;return t.assert(n>=0,"arg#"+n),`loc ${h+g+2+n} ; ${e.getName()}`}{let n=e.index+_.length;return t.assert(!m||n<g,"cell#"+n),t.assert(n>=0,"cell#"+n),`loc ${h+n}`}}function k(n){const r=t.hexfile.lookupFunc(n);r||t.U.oops("missing function: "+n);let i=e.opcodeMap[r.name];null==i&&(i=e.opcodes.length,e.opcodes.push(r.name),e.opcodeMap[r.name]=i,r.value=i),d(`callrt ${n}`)}function S(e,n){"bool"==n?d(`checkinst ${c(e)}`):t.U.oops()}function T(n){switch(n.exprKind){case p.NumberLiteral:const r=t.taggedSpecial(n.data);if(null!=r)d(`ldspecial ${r} ; ${n.data}`);else{let r=n.data,i=0,a=0;const o=r<<1>>1!=r;if((0|r)==r){if(Math.abs(r)<=y)return void d(r<0?"ldintneg "+-r:`ldint ${r}`);i=(r<<1|1)>>>0,a=r<0?1:0}else{let e=new Float64Array(1);e[0]=r;let t=new Uint32Array(e.buffer);t[1]+=65536,i=t[0],a=t[1]}let s=i+","+a,c=t.U.lookup(e.dbls,s);if(null==c){if(c=e.dblText.length,e.dblText.push(`.word ${i}, ${a} ; ${c}: ${n.data}`),o){const t="pxt::number_vt";e.dblBoxText.push(`.word ${l()?t:`0xffffffff ; ${t}`}\n`);let n=new Float64Array(1);n[0]=r;let i=new Uint32Array(n.buffer);e.dblBoxText.push(`.word ${i[0]}, ${i[1]} ; ${r}\n`)}e.dbls[s]=c}d(`ldnumber ${c} ; ${n.data}`)}return;case p.PointerLiteral:return void d(`ldlit ${n.data}`);case p.SharedRef:let i=n.args[0];(!i.currUses||i.currUses>=i.totalUses)&&(console.log(i.sharingInfo()),t.U.assert(!1)),i.currUses++;let a=_.indexOf(i);return a<0&&(console.log(_,i),t.assert(!1)),d(`ldloc ${a+h}`+(i.currUses==i.totalUses?" ; LAST":"")),void N();case p.CellRef:return void d("ld"+x(n.data));case p.InstanceOf:C(n.args[0]),S(n.data,n.jsInfo);break;default:throw t.oops("kind: "+n.exprKind)}}function C(e){switch(e.exprKind){case p.JmpValue:d("; jmp value (already in r0)");break;case p.Nop:d("; nop");break;case p.FieldAccess:let t=e.data;C(e.args[0]),d(`ldfld ${t.idx}, ${c(t.classInfo)}`);break;case p.Store:return I(e.args[0],e.args[1]);case p.RuntimeCall:return A(e);case p.ProcCall:return w(e);case p.SharedDef:return E(e);case p.Sequence:return e.args.forEach(C);default:return T(e)}}function E(e){let n=e.args[0];if(t.U.assert(n.totalUses>=1),t.U.assert(0===n.currUses),n.currUses=1,f.push(n),1==n.totalUses)return C(n);{C(n);let e=-1;for(let t=0;t<_.length;++t)if(null==_[t]){e=t;break}e<0?(m&&(console.log(n,_),t.assert(!1,"missed tmp")),e=_.length,_.push(n)):_[e]=n,d(`stloc ${e+h}`)}}function D(){d("push"),h++}function A(e){let i=e.data;if("pxt::beginTry"==i)return void d(`try ${e.args[0].data}`);i=t.U.lookup(r,i)||i,N();let a=t.U.lookup(n,i),o=e.args,s=0;if("pxt::mkClassInstance"!=i){for(let e=0;e<o.length;++e)C(o[e]),e<o.length-1&&(D(),s++);"langsupp::ignore"==i?s&&d(`popmany ${s} ; ignore`):a?d(a):k(i),h-=s}else d(`newobj ${o[0].data}`)}function N(){for(let e=0;e<_.length;++e){let t=_[e];t&&t.currUses==t.totalUses&&(m||f.push(t),_[e]=null)}}function w(e){let n=e.data,r=n.proc;if(r&&r.inlineBody){const t=r.inlineSelf(e.args);return pxt.options.debug&&console.log("INLINE",e.toString(),"->",t.toString()),C(t)}let a=0;const o=e.args.slice(),s=-1==n.virtualIndex?o.shift():null;for(let e of o)C(e),D(),a++;let c=o.length;if(s)C(s),d(`callind ${c}`);else if(null!=n.ifaceIndex){let e=n.ifaceIndex+" ; ."+i.ifaceMembers[n.ifaceIndex];n.isSet?(d(`callset ${e}`),t.U.assert(2==c)):n.noArgs?(d(`callget ${e}`),t.U.assert(1==c)):d(`calliface ${c}, ${e}`)}else null!=n.virtualIndex?t.U.oops():d(`callproc ${r.label()}`);h-=a}function I(e,n){switch(e.exprKind){case p.CellRef:C(n);let r=e.data,i="st"+x(r);if(r.isGlobal()&&0!=r.bitSize){const e=t.sizeOfBitSize(r.bitSize)|(t.isBitSizeSigned(r.bitSize)?16:0);d("bitconv "+e)}d(i);break;case p.FieldAccess:let a=e.data;C(e.args[0]),D(),C(n),d(`stfld ${a.idx}, ${c(a.classInfo)}`),h--;break;default:t.oops()}}}(_,d,e)),[e.label()+"_Lit"])})),f+="_code_end:\n\n",f+="_helpers_end:\n\n",d.usedClassInfos.forEach((e=>{g(c(e),a.VTable,(()=>i(e,0,d)))})),t.U.values(s).forEach((e=>{e.itable=[],e.classNo=65520,g(c(e),a.VTable,(()=>i(e,0,d)))})),s={};let x=0;g("ifaceMemberNames",a.IfaceMemberNames,(()=>` .word ${d.ifaceMembers.length} ; num. entries\n`+d.ifaceMembers.map((e=>` .word ${d.emitString(e)} ; ${x++} .${e}`)).join("\n"))),f+="_vtables_end:\n\n",t.U.iterMap(d.hexlits,((e,n)=>{g(n,a.Literal,(()=>`.word ${u("pxt::buffer_vt")}\n`+t.hexLiteralAsm(e)),[],pxt.BuiltInType.BoxedBuffer)})),t.U.unique(d.ifaceMembers.concat(Object.keys(d.strings)),(e=>e)).forEach((e=>{const n=t.utf8AsmStringLiteral(e);let r=pxt.BuiltInType.BoxedString;"pxt::string_inline_ascii_vt"==n.vt?r=pxt.BuiltInType.BoxedString_ASCII:"pxt::string_skiplist16_packed_vt"==n.vt?r=pxt.BuiltInType.BoxedString_SkipList:"pxt::string_inline_utf8_vt"==n.vt?r=pxt.BuiltInType.BoxedString:t.oops("invalid vt");const i=`.word ${u(n.vt)}\n`+n.asm;g(d.strings[e],a.Literal,(()=>i),[],r)})),g("numberBoxes",a.NumberBoxes,(()=>_.dblBoxText.join("\n")+"\n.word 0, 0, 0 ; dummy entry to make sure not empty")),g("numberLiterals",a.NumberLiterals,(()=>_.dblText.join("\n")+"\n.word 0, 0 ; dummy entry to make sure not empty"));const k=d.res.configData||[];g("configData",a.ConfigData,(()=>k.map((e=>` .word ${e.key}, ${e.value} ; ${e.name}=${e.value}`)).join("\n")+"\n .word 0, 0"));let S=_.opcodes.map((e=>null==e?"":e)).join("\0")+"\0",T="";for(;S;){let e=S.slice(0,64);S=S.slice(64),1&e.length&&(e+="\0"),T+=".hex "+t.U.toHex(t.U.stringToUint8Array(e))+"\n"}g("opcodeMap",a.OpCodeMap,(()=>T)),f+="_literals_end:\n",f+="_img_end:\n",f+="\n; The end.\n",d.writeFile(t.BINARY_ASM,f);let C=t.assemble(p.target,d,f);const E=C.thumbFile.getSourceMap(),D=function(e){const n=[83,82,67,77,136,21,78,45,170,134,153,113,0,0,0,0];for(const r of Object.keys(e)){for(const e of t.U.stringToUint8Array(r))n.push(e);n.push(0);const a=e[r];let o=0,s=0;for(let e=0;e<a.length;e+=3)i(a[e]-o),i(a[e+1]-s>>1),i(a[e+2]>>1),o=a[e],s=a[e+1];n.push(255)}n.push(0),1&n.length&&n.push(0);const r=[];for(let e=0;e<n.length;e+=2)r.push(n[e]|n[e+1]<<8);return r;function i(e){if(0<=e&&e<240)n.push(e);else{let t=240;e<0&&(e=-e,t|=8);const r=n.length;n.push(null);let i=0;for(;0!=e;)n.push(255&e),e>>>=8,i++;n[r]=t|i}}}(E);C.src&&d.writeFile(t.BINARY_ASM,`; srcmap size: ${D.length<<1} bytes\n`+C.src);{let e="";for(let t of C.buf)e+=String.fromCharCode(255&t,t>>8);const n=t.U.sha256(e);for(let e=0;e<4;++e)C.buf[16+e]=parseInt(n.slice(4*e,4*e+4),16);E.__meta={name:p.name,programHash:C.buf[16]|C.buf[17]<<16}}if(d.writeFile(t.BINARY_SRCMAP,JSON.stringify(E)),pxt.options.debug){let e=C.thumbFile.peepCounts,t=Object.keys(e);t.sort(((t,n)=>e[n]-e[t]));for(let n of t.slice(0,50))console.log(`${n} ${e[n]}`)}if(C.buf){let n="";const r=C.buf;for(;15&r.length;)r.push(0);t.U.pushRange(r,D);for(let e of r)n+=String.fromCharCode(255&e,e>>8);if(n=e.pxtc.encodeBase64(n),l()){d.writeFile(t.BINARY_PXT64,n);const i=t.hexfile.patchHex(d,r,!1,!!t.target.useUF2)[0];d.writeFile(pxt.outputName(t.target),e.pxtc.encodeBase64(i))}else d.writeFile(pxt.outputName(t.target),n)}}}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){!function(n){let r,i;!function(e){e.DecompileLiterals="decompileLiterals",e.TaggedTemplate="taggedTemplate",e.DecompileIndirectFixedInstances="decompileIndirectFixedInstances",e.DecompileArgumentAsString="decompileArgumentAsString"}(r=n.DecompileParamKeys||(n.DecompileParamKeys={})),function(e){e[e.SingleLine=0]="SingleLine",e[e.MultiLine=1]="MultiLine"}(i=n.CommentKind||(n.CommentKind={})),n.FILE_TOO_LARGE_CODE=9266,n.DECOMPILER_ERROR=9267;const a=e.SyntaxKind,o=/^[^\f\n\r\t\v\u00a0\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]*$/,s=/^(?:Array<(.+)>)|(?:(.+)\[\])$/,c="math_number",l="math_number_minmax",u="math_integer",d="math_whole_number",p="text",f="logic_boolean",_={"+":{type:"math_arithmetic",op:"ADD"},"-":{type:"math_arithmetic",op:"MINUS"},"/":{type:"math_arithmetic",op:"DIVIDE"},"*":{type:"math_arithmetic",op:"MULTIPLY"},"**":{type:"math_arithmetic",op:"POWER"},"%":{type:"math_modulo",leftName:"DIVIDEND",rightName:"DIVISOR"},"<":{type:"logic_compare",op:"LT"},"<=":{type:"logic_compare",op:"LTE"},">":{type:"logic_compare",op:"GT"},">=":{type:"logic_compare",op:"GTE"},"==":{type:"logic_compare",op:"EQ"},"===":{type:"logic_compare",op:"EQ"},"!=":{type:"logic_compare",op:"NEQ"},"!==":{type:"logic_compare",op:"NEQ"},"&&":{type:"logic_operation",op:"AND"},"||":{type:"logic_operation",op:"OR"}},m=/^\s*\/\/\s*(.*)$/,g=/^\s*(?:(?:(?:\/\*\*?)|(?:\*))(?!\/))?\s*(.*?)(?:\*?\*\/)?$/;class h{constructor(e){this.renames=e,this.renames.sort(((e,t)=>e.span.start-t.span.start))}getRenamesInSpan(e,t){const n=[];for(const r of this.renames){if(r.span.start>t)break;r.span.start>=e&&n.push(r)}return n}getRenameForPosition(e){for(const t of this.renames){if(t.span.start>e)return;if(t.span.start===e)return t}}}function y(e,t,n=!0){if(1===e.length&&"x"!==e&&"y"!==e&&"z"!==e){const r=e.charCodeAt(0);if(r>=97&&r<=122){const e=r-97;for(let r=1;r<26;r++){const i=String.fromCharCode(97+(e+r)%26);if("x"!==i&&"y"!==i&&"z"!==i&&!t[i])return n&&(t[i]=!0),i}}}for(let r=2;;r++){const i=e+r;if(!t[i])return n&&(t[i]=!0),i}}let v;function b(n,i,o=!1,s=!1){switch(n.kind){case a.WhileStatement:case a.IfStatement:case a.Block:return;case a.ExpressionStatement:return b(n.expression,i,o,s);case a.VariableStatement:return function(e,t){for(const n of e.declarationList.declarations){const e=c(n,t);if(e)return e}return}(n,i);case a.CallExpression:return function(n,i,o=!1,s=!1){const c=t.pxtInfo(n).callInfo;if(!c)return t.Util.lf("Function call not supported in the blocks");const l=i.attrs(c);let u;e.isIdentifier(n.expression)&&(u=i.declaredFunctions[n.expression.text]);if(!o&&c.isExpression&&!u){if(!i.aliasBlocks[c.qName])return t.Util.lf("No output expressions as statements");c.decompilerBlockAlias=i.aliasBlocks[c.qName]}if("Math.pow"==c.qName)return;if(pxt.Util.startsWith(c.qName,"Math.")){if(R(c.qName.substring(5)))return}if(l.blockId===t.PAUSE_UNTIL_TYPE){const e=n.arguments[0];if(1===n.arguments.length&&y(e))return;return t.Util.lf("Predicates must be inline expressions that return a value")}const d=w(c,l);if(d&&!l.handlerStatement&&!s)return t.Util.lf("Events must be top level");if(!l.blockId||!l.block){const e=pxt.blocks.builtinFunctionInfo[c.qName];if(!e)return u?u.parameters.length!==c.args.length?t.Util.lf("Function calls in blocks must have the same number of arguments as the function definition"):void 0:t.Util.lf("Call statements must have a valid declared function");l.blockId=e.blockId}const p=O(c,i.blocks),f=i.blocks.apis.byQName[c.qName],_=pxt.blocks.compileInfo(f),m=_.parameters.length+(_.thisParameter?1:0);if(l.imageLiteral){if(c.args.length-m>1)return t.Util.lf("Function call has more arguments than are supported by its block");let e=n.arguments[0];if(e.kind!=a.StringLiteral&&e.kind!=a.NoSubstitutionTemplateLiteral)return t.Util.lf("Only string literals supported for image literals");const r=(e.text||"").replace(/\s+/g,""),i=l.imageLiteralRows||5,o=(l.imageLiteralColumns||5)*l.imageLiteral,s=o*i;return o*i!=r.length?t.Util.lf("Invalid image pattern ({0} expected vs {1} actual)",s,r.length):void 0}const g=c.args.length-m;if(g>0&&!h()){let e=g;if(d&&e--,l.defaultInstance&&e--,e>0)return t.Util.lf("Function call has more arguments than are supported by its block")}if(_.parameters.length||d){let e;const t=l.defaultInstance||!!_.thisParameter;if(p.forEach(((n,r)=>{e||t&&0===r||(t&&r--,e=v(n))})),e)return e}if(f){const e=i.blocks.apis.byQName[f.namespace];if(e&&e.attributes.fixedInstances&&!e.attributes.decompileIndirectFixedInstances&&c.args.length){const e=t.pxtInfo(c.args[0]).callInfo;if(!e||!i.attrs(e).fixedInstance)return t.Util.lf("Fixed instance APIs can only be called directly from the fixed instance")}}return;function h(){if(l.mutatePropertyEnum&&2===g&&c.args.length>=2){const e=c.args[c.args.length-2],t=c.args[c.args.length-1];if(e.kind===a.ArrayLiteralExpression&&P(t)){const n=[];if(!e.elements.some((e=>e.kind!==a.PropertyAccessExpression||e.expression.kind!==a.Identifier||(n.push(e.name.text),e.expression.text!==l.mutatePropertyEnum)))){const e=T(t);if(e){const t=e[0];return t.length===n.length&&!n.some((e=>-1===t.indexOf(e)))}}}}return!1}function y(e){if(e.kind!==a.FunctionExpression&&e.kind!==a.ArrowFunction)return!1;const n=e;if(function(e){switch(e.kind){case a.BinaryExpression:const n=e.operatorToken.kind;return n!=a.PlusEqualsToken&&n!=a.MinusEqualsToken&&n!=a.EqualsToken;case a.PrefixUnaryExpression:{let t=e.operator;return t!=a.PlusPlusToken&&t!=a.MinusMinusToken}case a.PostfixUnaryExpression:{let t=e.operator;return t!=a.PlusPlusToken&&t!=a.MinusMinusToken}case a.CallExpression:const r=t.pxtInfo(e).callInfo;return t.assert(!!r),r.isExpression;case a.ParenthesizedExpression:case a.NumericLiteral:case a.StringLiteral:case a.NoSubstitutionTemplateLiteral:case a.TrueKeyword:case a.FalseKeyword:case a.NullKeyword:case a.TaggedTemplateExpression:return!0;default:return!1}}(n.body))return!0;const r=n.body;if(1===r.statements.length){if(D(r.statements[0]).kind===a.ReturnStatement)return!0}return!1}function v(e){const n=D(e.value),o=e.info,s=e.param;if(o.isEnum){if(c(n))return;if(n.kind===a.CallExpression){const e=t.pxtInfo(n).callInfo,r=i.attrs(e);if(e&&"TD_ID"===r.shim&&e.args&&1===e.args.length){if(c(D(e.args[0])))return}}else if(n.kind===a.Identifier){const e=t.pxtInfo(n).commentAttrs;if(e&&e.enumIdentity)return}return t.Util.lf("Enum arguments may only be literal property access expressions")}if(I(n)&&(s.fieldEditor||s.shadowBlockId)){let e=!(!s.fieldOptions||!s.fieldOptions[r.DecompileLiterals]);if(!e&&s.shadowBlockId){const t=i.blocks.blocksById[s.shadowBlockId];if(t&&t.parameters&&t.parameters.length){const n=t.parameters[0].name;e=!t.attributes.paramFieldEditorOptions||!t.attributes.paramFieldEditorOptions[n]||!!t.attributes.paramFieldEditorOptions[n][r.DecompileLiterals]}else e=!0}if(!e)return t.Util.lf("Field editor does not support literal arguments")}else if(n.kind===a.TaggedTemplateExpression&&s.fieldEditor){let e=s.fieldOptions&&s.fieldOptions[r.TaggedTemplate];if(!e)return t.Util.lf("Tagged templates only supported in custom fields with param.fieldOptions.taggedTemplate set");const i=D(n.tag);if(i.kind!==a.Identifier)return t.Util.lf("Tagged template literals must use an identifier as the tag");if(i.getText().trim()!=e.trim())return t.Util.lf("Function only supports template literals with tag '{0}'",e);if(n.template.kind!==a.NoSubstitutionTemplateLiteral)return t.Util.lf("Tagged template literals cannot have substitutions")}else if(n.kind===a.ArrowFunction){const e=n;if(e.parameters.length)if("objectdestructuring"===l.mutate){const n=D(e.parameters[0]);if(n.kind===a.Parameter&&n.name.kind!==a.ObjectBindingPattern)return t.Util.lf("Object destructuring mutation callbacks can only have destructuring patters as arguments")}else for(const n of e.parameters)if(n.name.kind!==a.Identifier)return t.Util.lf("Only identifiers allowed as function arguments")}else if(i.blocks.apis.byQName[o.type]){if(i.blocks.apis.byQName[o.type].attributes.fixedInstances){if(L(s))return;if(s.shadowBlockId){const e=i.blocks.blocksById[s.shadowBlockId];if(e){const t=pxt.blocks.compileInfo(e);if(t.parameters&&L(t.parameters[0]))return}}const e=t.pxtInfo(n).callInfo;if(e&&i.attrs(e).fixedInstance)return;return t.Util.lf("Arguments of a fixed instance type must be a reference to a fixed instance declaration")}}return;function c(e){const t=o.type.split("."),n=[];for(;e.kind===a.PropertyAccessExpression;)n.unshift(e.name.text),e=e.expression;if(e.kind!==a.Identifier)return!1;n.unshift(e.text);for(let e=0;e<t.length;e++)if(t[e]!==n[e])return!1;return!0}}}(n,i,o,s);case a.VariableDeclaration:return c(n,i);case a.PostfixUnaryExpression:case a.PrefixUnaryExpression:return function(e){if(e.operand.kind!=a.Identifier)return t.Util.lf("-- and ++ may only be used on an identifier");if(e.operator!==a.PlusPlusToken&&e.operator!==a.MinusMinusToken)return t.Util.lf("Only ++ and -- supported as prefix or postfix unary operators in a statement");return}(n);case a.FunctionExpression:case a.ArrowFunction:return function(e,n){let r=!1;if(e.parameters.length){let i=E(e)[0];if(i&&t.pxtInfo(i).callInfo){let o=t.pxtInfo(i).callInfo;r="objectdestructuring"===n.attrs(o).mutate?e.parameters[0].name.kind!==a.ObjectBindingPattern:e.parameters.some((e=>e.name.kind!==a.Identifier))}}if(r)return t.Util.lf("Unsupported parameters in error function");return}(n,i);case a.BinaryExpression:return function(e,n){if(e.left.kind===a.ElementAccessExpression){if(e.operatorToken.kind!==a.EqualsToken)return t.Util.lf("Element access expressions may only be assigned to using the equals operator")}else{if(e.left.kind===a.PropertyAccessExpression)return e.operatorToken.kind!==a.EqualsToken&&e.operatorToken.kind!==a.PlusEqualsToken?t.Util.lf("Property access expressions may only be assigned to using the = and += operators"):C(e.left,n);if(e.left.kind!==a.Identifier)return t.Util.lf("This expression cannot be assigned to");switch(e.operatorToken.kind){case a.EqualsToken:return C(e.right,n);case a.PlusEqualsToken:case a.MinusEqualsToken:return;default:return t.Util.lf("Unsupported operator token in statement {0}",a[e.operatorToken.kind])}}return}(n,i);case a.ForStatement:return function(e){if(!e.initializer||!e.incrementor||!e.condition)return t.Util.lf("for loops must have an initializer, incrementor, and condition");if(e.initializer.kind!==a.VariableDeclarationList)return t.Util.lf("only variable declarations are permitted in for loop initializers");const n=e.initializer;if(!n.declarations)return t.Util.lf("for loop with out-of-scope variables not supported");if(1!=n.declarations.length)return t.Util.lf("for loop with multiple variables not supported");const r=n.declarations[0];if(r.initializer.kind!==a.NumericLiteral||"0"!==r.initializer.text)return t.Util.lf("for loop initializers must be initialized to 0");const i=r.name.text;if(!s(i))return t.Util.lf("for loop incrementors may only increment the variable declared in the initializer");if(e.condition.kind!==a.BinaryExpression)return t.Util.lf("for loop conditionals must be binary comparison operations");const o=e.condition;if(o.left.kind!==a.Identifier||o.left.text!==i)return t.Util.lf("left side of for loop conditional must be the variable declared in the initializer");if(o.operatorToken.kind!==a.LessThanToken&&o.operatorToken.kind!==a.LessThanEqualsToken)return t.Util.lf("for loop conditional operator must be either < or <=");return;function s(t){if(e.incrementor.kind===a.PostfixUnaryExpression||e.incrementor.kind===a.PrefixUnaryExpression){const n=e.incrementor;if(n.operator===a.PlusPlusToken&&n.operand.kind===a.Identifier)return n.operand.text===t}return!1}}(n);case a.ForOfStatement:return function(e){if(e.initializer.kind!==a.VariableDeclarationList)return t.Util.lf("only variable declarations are permitted in for of loop initializers");return}(n);case a.FunctionDeclaration:return function(e,n){if(!n)return t.Util.lf("Function declarations must be top level");if(e.parameters.length>0&&i.opts.allowedArgumentTypes)for(const n of e.parameters){if(n.initializer||n.questionToken)return t.Util.lf("Function parameters cannot be optional");const e=n.type?n.type.getText():void 0;if(!e)return t.Util.lf("Function parameters must declare a type");if(-1===i.opts.allowedArgumentTypes.indexOf($(e)))return t.Util.lf("Only types that can be added in blocks can be used for function arguments")}return}(n,s);case a.EnumDeclaration:return function(e,n){if(!n)return t.Util.lf("Enum declarations must be top level");const r=e.name.text;if(!i.blocks.enumsByName[r])return t.Util.lf("Enum declarations in user code must have a block");let o=!1;if(e.members.forEach((e=>{if(e.name.kind!==a.Identifier&&(o=!0),!o&&e.initializer){if(e.initializer.kind===a.NumericLiteral)return;if(e.initializer.kind===a.BinaryExpression){const t=e.initializer;if(t.operatorToken.kind===a.LessThanLessThanToken&&t.left.kind===a.NumericLiteral&&t.right.kind===a.NumericLiteral&&"1"==t.left.text)return}o=!0}})),o)return t.Util.lf("Invalid initializer for enum member");return}(n,s);case a.ModuleDeclaration:return function(e){const t=x(e,i);if(!t)return;return k(e)?t:void 0}(n);case a.ReturnStatement:return function(n){if(r(n))return;return t.Util.lf("Return statements can only be used within top-level function declarations");function r(t){const n=e.getEnclosingBlockScopeContainer(t);if(n)switch(n.kind){case a.SourceFile:case a.ArrowFunction:case a.FunctionExpression:return!1;case a.FunctionDeclaration:return n.parent&&n.parent.kind===a.SourceFile&&!b(n,i,!1,!0);default:return r(n)}return!1}}(n);case a.BreakStatement:case a.ContinueStatement:case a.DebuggerStatement:case a.EmptyStatement:return}return t.Util.lf("Unsupported statement in block: {0}",a[n.kind]);function c(e,n){let r;return e.name.kind!==a.Identifier?r=t.Util.lf("Variable declarations may not use binding patterns"):e.initializer?S(e)||(r=C(e.initializer,n)):r=t.Util.lf("Variable declarations must have an initializer"),r}}function x(n,r){if(!e.isModuleBlock(n.body))return t.Util.lf("Namespaces cannot be nested.");const i=r.blocks.kindsByName[n.name.text];if(!i)return t.Util.lf("Only namespaces with 'kind' blocks can be decompiled");const o=t.Util.lf("Namespaces may only contain valid 'kind' exports");for(const t of n.body.statements){if(j(t))return o;if(!e.isVariableStatement(t)||!t.declarationList.declarations)return o;{const n=1===t.declarationList.declarations.length,r=t.modifiers&&1===t.modifiers.length&&t.modifiers[0].kind===a.ExportKeyword,s=t.declarationList.flags&e.NodeFlags.Const;if(!(n&&r&&s))return o;{const n=t.declarationList.declarations[0];if(!n.initializer||!e.isCallExpression(n.initializer)||!e.isIdentifier(n.name))return o;const r=n.initializer;if(r.arguments.length)return o;if(e.isPropertyAccessExpression(r.expression)&&e.isIdentifier(r.expression.expression)){if(r.expression.expression.text!==i.name||r.expression.name.text!==i.createFunctionName)return o}else{if(!e.isIdentifier(r.expression))return o;if(r.expression.text!==i.createFunctionName)return o}}}}}function k(n){if(!e.isModuleBlock(n.body))return t.Util.lf("Namespaces cannot be nested.");if(n.name.text!==pxt.sprite.TILE_NAMESPACE)return t.Util.lf("Tileset namespace must be named myTiles");const r=t.Util.lf("The myTiles namespace can only export tile variables with image literal initializers and no duplicate ids"),i=t.Util.lf("Tileset members must have a blockIdentity comment and no other annotations"),o=new RegExp(`${pxt.sprite.TILE_PREFIX}(\\d+)`),s=[],c=/^\s*\/\/%\s*blockIdentity=[^\s]+\s*$/;for(const t of n.body.statements){const n=e.getLeadingCommentRangesOfNode(t,t.getSourceFile());if(!n||!n.length)return i;{const e=n.map((e=>t.getSourceFile().text.substr(e.pos,e.end-e.pos))).filter((e=>!!e));if(1!==e.length||!c.test(e[0]))return i}if(!e.isVariableStatement(t)||!t.declarationList.declarations)return r;{const n=1===t.declarationList.declarations.length,i=t.modifiers&&1===t.modifiers.length&&t.modifiers[0].kind===a.ExportKeyword,c=t.declarationList.flags&e.NodeFlags.Const;if(!(n&&i&&c))return r;{const n=t.declarationList.declarations[0];if(!n.initializer||!e.isTaggedTemplateExpression(n.initializer)||!e.isIdentifier(n.name))return r;const i=n.initializer;if(!e.isIdentifier(i.tag)||"img"!==i.tag.text)return r;const a=o.exec(n.name.text);if(!a||-1!==s.indexOf(a[1]))return r;s.push(a[1])}}}}function S(n){if(n.initializer){if(n.initializer.kind===e.SyntaxKind.NullKeyword||n.initializer.kind===e.SyntaxKind.FalseKeyword||function(e){return e.kind===a.ArrayLiteralExpression&&0===e.elements.length}(n.initializer))return!0;if(e.isStringOrNumericLiteral(n.initializer)){const e=n.initializer.getText();return"0"===e||A(e)}{const e=t.pxtInfo(n.initializer).callInfo;if(e&&e.isAutoCreate)return!0}}return!1}function T(e){if(1===e.parameters.length&&e.parameters[0].name.kind===a.ObjectBindingPattern){const n=e.parameters[0].name.elements,r={};return[n.map((e=>{if(t(e.propertyName)&&t(e.name)){const t=e.name.text;if(e.propertyName){const n=e.propertyName.text;return r[n]=t,n}return t}return""})),r]}return;function t(e){return!e||e.kind===a.Identifier}}function C(n,r){switch(n.kind){case a.NumericLiteral:case a.TrueKeyword:case a.FalseKeyword:case a.ExpressionStatement:case a.ArrayLiteralExpression:case a.ElementAccessExpression:return;case a.ParenthesizedExpression:return C(n.expression,r);case a.StringLiteral:case a.FirstTemplateToken:case a.NoSubstitutionTemplateLiteral:return function(e){const n=e.text;return o.test(n)?void 0:t.Util.lf("Only whitespace character allowed in string literals is space")}(n);case a.Identifier:const s=t.pxtInfo(n);return(i=n)&&i.kind===a.Identifier&&"undefined"===i.text?t.Util.lf("Undefined is not supported in blocks"):!N(n)||s.commentAttrs&&s.commentAttrs.blockIdentity&&s.commentAttrs.enumIdentity?void 0:t.Util.lf("Variable is declared in another file");case a.BinaryExpression:const c=n.operatorToken.getText();return _[c]?void 0:t.Util.lf("Could not find operator {0}",c);case a.PrefixUnaryExpression:const l=n.operator;return l===a.MinusToken||l===a.PlusToken||l===a.ExclamationToken?void 0:t.Util.lf("Unsupported prefix unary operator{0}",l);case a.PropertyAccessExpression:return function(n,r){const i=t.pxtInfo(n).callInfo;if(i){const o=r.attrs(i),s=r.compInfo(i);if(o.blockIdentity||"lists_length"===o.blockId||"text_length"===o.blockId)return;if(i.decl.kind===a.EnumMember){if(n.expression.kind===a.Identifier){const e=n.expression.text;if(r.declaredEnums[e])return}const[e,i]=E(n);let o=!0;if(e){const n=t.pxtInfo(e).callInfo;if(n&&n.args){const e=r.blocks.apis.byQName[n.qName],t=1==e.kind||2==e.kind;e&&n.args.forEach(((n,r)=>{if(n===i){e.parameters[t?r-1:r].isEnum&&(o=!1)}}))}}return o?t.Util.lf("Enum value without a corresponding block"):void 0}if(o.fixedInstance&&n.parent){if(n.parent.parent&&n.parent.kind===a.PropertyAccessExpression&&n.parent.parent.kind===a.CallExpression){if(n.parent.parent.expression===n.parent)return}else if(n.parent.kind===a.CallExpression&&n.parent.expression!==n)return}else{if(o.blockCombine||o.blockId&&s&&s.thisParameter)return C(n.expression,r);if(e.isIdentifier(n.expression)&&r.declaredKinds[n.expression.text]){const e=n.name.text,t=r.declaredKinds[n.expression.text];if(t&&(-1!==t.kindInfo.initialMembers.indexOf(e)||-1!==t.declaredNames.indexOf(e)))return}}}return t.Util.lf("No call info found")}(n,r);case a.CallExpression:return b(n,r,!0,void 0);case a.TaggedTemplateExpression:return function(e,n){const r=t.pxtInfo(e).callInfo;if(!r)return t.Util.lf("Invalid tagged template");const i=n.attrs(r);if(!i.blockIdentity)return t.Util.lf("Tagged template does not have blockIdentity set");const a=n.blocks.apis.byQName[i.blockIdentity];if(!a)return t.Util.lf("Could not find blockIdentity for tagged template");if(1!==pxt.blocks.compileInfo(a).parameters.length)return t.Util.lf("Tagged template functions must have 1 argument");return}(n,r)}var i;return t.Util.lf("Unsupported syntax kind for output expression block: {0}",a[n.kind])}function E(e){return e.parent?e.parent.kind===a.ParenthesizedExpression?E(e.parent):[e.parent,e]:[void 0,e]}function D(e){for(;e.kind===a.ParenthesizedExpression;)e=e.expression;return e}function A(e){return'""'===e||"''"===e||"``"===e}function N(e){return!!(4&t.pxtInfo(e).flags)}function w(e,n){if(n.blockId===t.PAUSE_UNTIL_TYPE)return!1;e.decl.parameters;return e.args.some(((e,t)=>e&&P(e)))}function I(e){if(!e)return!1;switch(e.kind){case a.ParenthesizedExpression:return I(e.expression);case a.ArrayLiteralExpression:const t=e;for(const e of t.elements)if(!I(e)&&e.kind!==a.TaggedTemplateExpression)return!1;return!0;case a.NumericLiteral:case a.StringLiteral:case a.NoSubstitutionTemplateLiteral:case a.TrueKeyword:case a.FalseKeyword:return!0;case a.PrefixUnaryExpression:const n=e;return(n.operator===a.PlusToken||n.operator===a.MinusToken)&&I(n.operand);default:return!1}}function P(e){return e.kind===a.ArrowFunction||e.kind===a.FunctionExpression}function O(e,t){const n=[],r=t.apis.byQName[e.qName];if(r){const i=t.apis.byQName[e.qName].attributes,a=pxt.blocks.compileInfo(r);pxt.blocks.builtinFunctionInfo[e.qName];let o=i.imageLiteral?1:0;a.thisParameter?n.push({value:D(e.args[0]),info:null,param:a.thisParameter}):i.defaultInstance&&n.push({value:D(e.args[0]),info:r.parameters[0],param:{definitionName:"__instance__",actualName:"this"}});const s=!(!a.thisParameter&&!i.defaultInstance);s&&o++;for(let t=o;t<e.args.length;t++)n.push({value:D(e.args[t]),info:r.parameters[s?t-1:t],param:a.parameters[t-o]})}return n}function F(e){return e.body.statements.map((e=>{const t=e.declarationList.declarations[0];return{name:t.name.text,initializer:t.initializer.getText()}}))}function L(e){return e&&e.fieldOptions&&e.fieldOptions[r.DecompileIndirectFixedInstances]}function R(e){return M(e)||U(e)||B(e)||-1!==pxt.blocks.MATH_FUNCTIONS.binary.indexOf(e)}function M(e){return-1!==pxt.blocks.MATH_FUNCTIONS.unary.indexOf(e)}function U(e){return-1!==pxt.blocks.MATH_FUNCTIONS.infix.indexOf(e)}function B(e){return-1!==pxt.blocks.ROUNDING_FUNCTIONS.indexOf(e)}function $(e){const t=s.exec(e);return t?`${t[1]||t[2]}[]`:e}function j(t){const n=e.getLeadingCommentRangesOfNode(t,t.getSourceFile());return!(!n||!n.length)}function K(t,n,r=!1){const a=[],o=t.getFullText();if(n&&n.length)for(const s of n){const n=e.getLineOfLocalPosition(t,s.end),c=e.getStartPositionOfLine(n+1,t)||o.length,l=e.getStartPositionOfLine(n+2,t)||o.length,u=!r&&!o.substr(c,l-c).trim();let d=o.substr(s.pos,s.end-s.pos);if(d&&(d=d.replace(/\r\n/g,"\n")),s.kind===e.SyntaxKind.SingleLineCommentTrivia){const e=m.exec(d);e?a.push({kind:i.SingleLine,text:e[1],start:s.pos,end:s.end,hasTrailingNewline:!!s.hasTrailingNewLine,followedByEmptyLine:u,isTrailingComment:r}):a.push({kind:i.SingleLine,text:"",start:s.pos,end:s.end,hasTrailingNewline:!!s.hasTrailingNewLine,followedByEmptyLine:u,isTrailingComment:r})}else{const e=d.split("\n").map((e=>{const t=g.exec(e);return t?t[1]:""}));a.push({kind:i.MultiLine,lines:e,start:s.pos,end:s.end,hasTrailingNewline:!!s.hasTrailingNewLine,followedByEmptyLine:u,isTrailingComment:r})}}return a}function z(e){let n="";for(const r of e)if(r.kind===i.SingleLine){if(r.text===t.ON_START_COMMENT||r.text===t.HANDLER_COMMENT)continue;n+=r.text.trim()+"\n"}else for(const e of r.lines)n+=e.trim()+"\n";return n.trim()}function J(e){const[t]=E(e);return!t||t.kind==a.SourceFile||(t.kind==a.ExpressionStatement?J(t):t.kind==a.VariableDeclarationList&&J(t.parent))}function q(t){const n=t.getFullText(),r=e.createScanner(t.languageVersion,!1,t.languageVariant,n,void 0,t.getFullStart());let i,o,s=[];for(;r.getTextPos()<t.end;){const c=r.scan();if(c===a.SingleLineCommentTrivia||c===a.MultiLineCommentTrivia){i=e.getLeadingCommentRanges(n,r.getTokenPos())||[],o=e.getTrailingCommentRanges(n,r.getTokenPos())||[],o=o.filter((e=>!i.some((t=>t.pos===e.pos)))),s.push(...K(t,i,!1)),s.push(...K(t,o,!0));for(const e of s)e.end>r.getTextPos()&&r.setTextPos(e.end)}}return s.sort(((e,t)=>e.start-t.start)),s}function V(e,t){let n;for(let r=0;r<t.length;r++)n=t[r],!n.owner&&n.start>=e.pos&&n.end<=e.end&&(n.owner=e)}n.RenameMap=h,n.buildRenameMap=function(n,r,{declarations:i,takenNames:a}={declarations:"variables",takenNames:{}}){let o=e.createLanguageService(new t.LSHost(n));const s=[];let c=(function t(n){e.forEachChild(n,(n=>{if(e.isDeclarationName(n)&&("all"===i||e.isVariableDeclaration(n.parent))){const e=n.getText();if(a[e]){const t=y(e,a),i=o.findRenameLocations(r.fileName,n.pos+1,!1,!1);i&&i.forEach((n=>{s.push({name:t,diff:t.length-e.length,span:n.textSpan})}))}else a[e]=!0}t(n)}))}(r),a);return[new h(s),c]},n.getNewName=y,function(e){e[e.None=0]="None",e[e.InBlocksOnly=1]="InBlocksOnly",e[e.InTextBlocks=2]="InTextBlocks"}(v||(v={})),n.decompileToBlocks=function(o,s,m,g){let h=0,y=s.statements;const P={blocksInfo:o,outfiles:{},diagnostics:[],success:!0,times:{}};m.generateSourceMap&&(P.blockSourceMap=[]);const L={blocks:o,declaredFunctions:{},declaredEnums:{},declaredKinds:{},functionParamIds:{},attrs:re,compInfo:function(e){const t=o.apis.byQName[e.qName];if(t)return pxt.blocks.compileInfo(t);return},localReporters:[],tileset:[],opts:m||{},aliasBlocks:{}};s.getFullText();let $="";const j=[],K={},H=[],G=[],W=(()=>{let e=0;return()=>""+e++})(),Q=o.apis.byQName;Object.keys(Q).forEach((e=>{const t=Q[e];t.attributes.blockAliasFor&&Q[t.attributes.blockAliasFor]&&(L.aliasBlocks[t.attributes.blockAliasFor]=t.qName)}));const Y=q(s),X=n=>{if(n.kind!==a.FunctionDeclaration||b(n,L,!1,!0))if(n.kind!==a.EnumDeclaration||b(n,L,!1,!0))if(e.isModuleDeclaration(n))if(x(n,L))k(n)||(L.tileset=F(n).map((({name:e,initializer:t})=>({projectId:parseInt(e.substr(pxt.sprite.TILE_PREFIX.length)),data:pxt.sprite.imageLiteralToBitmap(t).data()}))));else{const e=n.name.text,t=F(n);L.declaredKinds[e]&&L.declaredKinds[e].declaredNames.push(...t.map((({name:e})=>e)))}else n.kind===a.Block&&e.forEachChild(n,X);else{const e=n.name.text;L.declaredEnums[e]=!0,function(e){const n=[];return e.members.forEach((e=>{t.U.assert(e.name.kind===a.Identifier);const r=e.name.text;let i;if(e.initializer)if(e.initializer.kind===a.NumericLiteral)i=parseInt(e.initializer.text);else{const n=e.initializer;t.U.assert(n.left.kind===a.NumericLiteral),t.U.assert("1"===n.left.text),t.U.assert(n.operatorToken.kind===a.LessThanLessThanToken),t.U.assert(n.right.kind===a.NumericLiteral);i=1<<parseInt(n.right.text)}else i=0===n.length?0:n[n.length-1][1]+1;n.push([r,i])})),n}(n).forEach((([t,n])=>{j.push({name:n+t,type:e})}))}else L.declaredFunctions[Ge(n.name)]=n};Object.keys(o.kindsByName).forEach((e=>{const t=o.kindsByName[e];L.declaredKinds[e]={kindInfo:t,declaredNames:[]}})),e.forEachChild(s,X);const Z=()=>(Math.PI*Math.random()).toString(36).slice(2);let ee;Object.keys(L.declaredFunctions).forEach((e=>{L.functionParamIds[e]={},L.declaredFunctions[e].parameters.forEach((t=>{L.functionParamIds[e][t.name.getText()]=Z()+Z()}))})),Object.keys(L.declaredKinds).forEach((e=>{const t="KIND_"+e;L.declaredKinds[e].declaredNames.forEach((e=>j.push({name:e,type:t})))})),(j.length||L.tileset.length)&&(te("<variables>"),j.forEach((e=>{te(`<variable type="${t.U.htmlEscape(e.type)}">${t.U.htmlEscape(e.name)}</variable>`)})),L.tileset.forEach((e=>{te(`<variable type="${pxt.sprite.BLOCKLY_TILESET_TYPE}">${pxt.sprite.legacy.tileToBlocklyVariable(e)}</variable>`)})),te("</variables>"));try{ee=Je(y,void 0,!0,void 0,!m.snippetMode);for(const e of Y)e.owner||H.push({refId:W(),comment:[e]})}catch(r){if(!r.programTooLarge)return pxt.reportException(r),P.success=!1,P.diagnostics=t.patchUpDiagnostics([{file:s,start:s.getFullStart(),length:s.getFullWidth(),messageText:r.message,category:e.DiagnosticCategory.Error,code:n.DECOMPILER_ERROR}]),P;P.success=!1,P.diagnostics=t.patchUpDiagnostics([{file:s,start:s.getFullStart(),length:s.getFullWidth(),messageText:r.message,category:e.DiagnosticCategory.Error,code:n.FILE_TOO_LARGE_CODE}])}return ee?ue(ee):m.snippetMode||y.length||(he(e.pxtc.ON_START_TYPE,oe(e.pxtc.ON_START_TYPE,y[0])),ye()),H.forEach((e=>{!function(e){let n=0;const r=z(e.comment);if(r.trim()){const i=r.split("\n");i.forEach((e=>n=Math.max(n,e.length)));const a=Math.max(Math.min(10*n,480),160);te(`<comment h="${Math.max(Math.min(40*i.length,360),120)}" w="${a}" data="${t.U.htmlEscape(e.refId)}">`),te(t.U.htmlEscape(r)),te("</comment>")}}(e)})),P.outfiles[s.fileName.replace(/(\.blocks)?\.\w*$/i,"")+".blocks"]=`<xml xmlns="http://www.w3.org/1999/xhtml">\n${$}</xml>`,P;function te(e,t="\n"){$+=e+t}function ne(n,r){const i=r||`Language feature "${n.getFullText().trim()}"" not supported in blocks`,a=t.patchUpDiagnostics([{file:s,start:n.getFullStart(),length:n.getFullWidth(),messageText:i,category:e.DiagnosticCategory.Error,code:1001}]);pxt.debug(`decompilation error: ${i}`),t.U.pushRange(P.diagnostics,a),P.success=!1}function re(e){const n=o.apis.byQName[e.decompilerBlockAlias||e.qName];if(n){const e=n.attributes;if(!e.blockId||o.blocksById[e.blockId]||e.blockId===t.PAUSE_UNTIL_TYPE)return n.attributes}else if(e.decl){const n=t.parseComments(e.decl);if(n)return n}return{paramDefl:{},callingConvention:0}}function ie(){if(h++,h>1500){let e=new Error(t.Util.lf("Could not decompile because the script is too large"));throw e.programTooLarge=!0,e}}function ae(t,n){if(t==e.pxtc.ON_START_TYPE)return"xRRgvHNlG#rZ^u`HECiY";const r=function(){const e="!#$%()*+,-./:;=?@[]^_`{|}~ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=e.length,n=[];for(let r=0;r<20;r++)n[r]=e.charAt(Math.random()*t);return n.join("")}();if(n){const e=n.getFullStart();P.blockSourceMap.push({id:r,startPos:e,endPos:e+n.getFullWidth()})}return r}function oe(e,t){const n={kind:"statement",type:e};return P.blockSourceMap&&(n.id=ae(e,t)),n}function se(e,t){return{kind:"expr",type:e}}function ce(e,t,n,r){return(!n||n===c)&&r&&r.min&&r.max&&(n=l),{kind:"value",name:e,value:t,shadowType:n,shadowMutation:r}}function le(e){if(e.expression.kind==a.CallExpression){const n=e.expression,r=t.pxtInfo(n).callInfo;if(!r)return ne(e),!1;const i=re(r);return i.blockId&&!i.handlerStatement&&!r.isExpression&&w(r,i)}return!1}function ue(e){e&&(he(e.type,e),pe(e),void 0!==e.data&&te(`<data>${t.U.htmlEscape(e.data)}</data>`),e.handlers&&e.handlers.forEach(me),e.next&&(te("<next>"),ue(e.next),te("</next>")),void 0!==e.comment&&te(`<comment pinned="false">${t.U.htmlEscape(z(e.comment))}</comment>`),ye())}function de(e,t){te("<mutation ",""),Object.keys(e).forEach((t=>{void 0!==e[t]&&te(`${t}="${e[t]}" `,"")})),t?(te(">"),t.forEach((e=>{te(`<${e.nodeName} `,""),Object.keys(e.attributes).forEach((t=>{te(`${t}="${e.attributes[t]}" `,"")})),te("/>")})),te("</mutation>")):te("/>")}function pe(e){e.mutation&&de(e.mutation,e.mutationChildren),e.fields&&e.fields.forEach(_e),e.inputs&&e.inputs.forEach(fe)}function fe(e){te(`<value name="${e.name}">`);let t=!1;if("expr"===e.value.kind){const n=e.value;if(n.type===c&&e.shadowType===l&&(n.type=l,n.fields[0].name="SLIDER",n.mutation=e.shadowMutation),t=n.type===e.shadowType,!t)switch(n.type){case"math_number":case"math_number_minmax":case"math_integer":case"math_whole_number":case"logic_boolean":case"text":t=!e.shadowType}}if(t)ge(e.value,!0);else{if(void 0!==e.shadowType)switch(e.shadowType){case c:case u:case d:te(`<shadow type="${e.shadowType}"><field name="NUM">0</field></shadow>`);break;case l:te('<shadow type="math_number_minmax">'),e.shadowMutation&&de(e.shadowMutation),te('<field name="SLIDER">0</field></shadow>');break;case f:te('<shadow type="logic_boolean"><field name="BOOL">TRUE</field></shadow>');break;case p:te('<shadow type="text"><field name="TEXT"></field></shadow>');break;default:te(`<shadow type="${e.shadowType}"/>`)}ge(e.value)}te("</value>")}function _e(e){te(`<field name="${t.U.htmlEscape(e.name)}">${t.U.htmlEscape(e.value.toString())}</field>`)}function me(e){te(`<statement name="${t.U.htmlEscape(e.name)}">`),ue(e.statement),te("</statement>")}function ge(e,n=!1){if("text"===e.kind){te(e.value)}else{const r=e,i=n||r.isShadow,a=i?"shadow":"block";i||ie(),te(`<${a} ${r.id?`id="${r.id}" `:""}type="${t.U.htmlEscape(r.type)}">`),pe(r),te(`</${a}>`)}}function he(e,n){ie();te(`<block ${n&&n.id?`id="${n.id}" `:""}type="${t.U.htmlEscape(e)}">`)}function ye(){te("</block>")}function ve(e){if(C(e,L))return xe(e);switch(e.kind){case a.ExpressionStatement:case a.ParenthesizedExpression:return ve(e.expression);case a.Identifier:return function(e){if(N(e)){const n=t.pxtInfo(e);return Le(o.apis.byQName[n.commentAttrs.blockIdentity],n.commentAttrs.enumIdentity)}const n=Ge(e),r=e.text;let i=null;return L.localReporters.some((e=>{for(let t=0;t<e.length;++t)if(e[t].name===r)return i=e[t],!0;return!1})),i?Ie(n,i.type,!1):(Ve(n,v.InBlocksOnly),Ne("variables_get","VAR",n))}(e);case a.StringLiteral:case a.FirstTemplateToken:case a.NoSubstitutionTemplateLiteral:return De(e.text);case a.NumericLiteral:return Ee(e.text);case a.TrueKeyword:return Ae(!0);case a.FalseKeyword:return Ae(!1);case a.BinaryExpression:return function(e){const t=e.operatorToken.getText(),n=_[t];if(ke(e))return Te(e);const r=n.leftName||"A",i=n.rightName||"B";let a,o;"&&"===t||"||"===t?(a=Ue(r,e.left),o=Ue(i,e.right)):(a=Ce(r,e.left,c),o=Ce(i,e.right,c));const s=se(n.type);s.fields=[],n.op&&s.fields.push(Pe("OP",n.op));return s.inputs=[a,o],s}(e);case a.PrefixUnaryExpression:return function(e){switch(e.operator){case a.ExclamationToken:const t=se("logic_negate");return t.inputs=[Ue("BOOL",e.operand)],t;case a.PlusToken:return ve(e.operand);case a.MinusToken:return e.operand.kind==a.NumericLiteral?Ee("-"+e.operand.text):Oe(e.operand);default:ne(e)}return}(e);case a.PropertyAccessExpression:return Fe(e);case a.ArrayLiteralExpression:return function(e){const t=se("lists_create_with");return t.inputs=e.elements.map(((e,t)=>Ce("ADD"+t,e))),t.mutation={items:e.elements.length.toString()},t}(e);case a.ElementAccessExpression:return function(e){const t=se("lists_index_get");return t.inputs=[Ce("LIST",e.expression),Ce("INDEX",e.argumentExpression,c)],t}(e);case a.TaggedTemplateExpression:return function(e){const n=t.pxtInfo(e).callInfo;let i;const s=function(e){if(e.parent&&e.parent.kind===a.CallExpression){const n=e.parent,r=t.pxtInfo(n).callInfo,i=n.arguments.indexOf(e);if(r&&-1!==i){const e=o.apis.byQName[r.qName];if(e){const t=pxt.blocks.compileInfo(e);return t&&t.parameters[i]}}}return}(e);if(s&&s.shadowBlockId){const e=L.blocks.blocksById[s.shadowBlockId];e&&"TD_ID"===e.attributes.shim&&(i=e)}i||(i=L.blocks.apis.byQName[re(n).blockIdentity]);const c=pxt.blocks.compileInfo(i),l=se(i.attributes.blockId);let u;const d=c.parameters[0];u=d.fieldOptions&&d.fieldOptions[r.DecompileArgumentAsString]?e.getText():e.template.text;return l.fields=[Pe(d.actualName,u)],l}(e);case a.CallExpression:return Re(e,void 0,void 0,!0);default:ne(e,t.Util.lf("Unsupported syntax kind for output expression block: {0}",a[e.kind]))}}function be(e,t,n){if(g){const r=g.getRenamesInSpan(t,n);if(r.length){let n=0;r.forEach((r=>{const i=r.span.start+n-t,a=i+r.span.length;n+=r.diff,e=e.slice(0,i)+r.name+e.slice(a)}))}}return e}function xe(e){const n=be(e.getFullText(),e.getFullStart(),e.getEnd()).trim();return He(e),V(e,Y),Ne(t.TS_OUTPUT_TYPE,"EXPRESSION",n)}function ke(e){if(e.kind===a.BinaryExpression){const n=e;if("+"===n.operatorToken.getText()||n.operatorToken.kind==a.PlusEqualsToken){return!!t.pxtInfo(e).exprInfo}}return!1}function Se(e,t){ke(e)?(Se(e.left,t),Se(e.right,t)):t.push(e)}function Te(e){const t=[];Se(e,t);const n=[];for(let e=0;e<t.length;e++)(e>0||!A(t[e].getText()))&&n.push(Ce("ADD"+n.length,t[e],p));const r=se("text_join");return r.inputs=n,r.mutation={items:n.length.toString()},r}function Ce(e,t,n,r){let i;if(i="number"==typeof t?Ee(t.toString()):"boolean"==typeof t?Ae(t):"string"==typeof t?De(t):ve(t),"expr"==i.kind&&"math_number"==i.type){const e=i.fields[0].value;"math_integer"==n&&e%1==0&&(i.type="math_integer"),"math_whole_number"==n&&e%1==0&&e>0&&(i.type="math_whole_number")}return ce(e,i,n,r)}function Ee(e){return Ne("math_number","NUM",e)}function De(e){return Ne("text","TEXT",e)}function Ae(e){return Ne("logic_boolean","BOOL",e?"TRUE":"FALSE")}function Ne(e,t,n,r){const i=se(e);return i.fields=[Pe(t,n)],i.isShadow=r,i}function we(e,t){return ce(e,Ne("variables_get_reporter","VAR",t,!0),"variables_get_reporter")}function Ie(e,t,n){const r=pxt.blocks.reporterTypeForArgType(t),i=Ne(r,"VALUE",e,n);return"argument_reporter_custom"===r&&(i.mutation={typename:t}),i}function Pe(e,t){return{kind:"field",name:e,value:t}}function Oe(e){const t=se("math_arithmetic");return t.inputs=[Ce("A",0,c),Ce("B",e,c)],t.fields=[Pe("OP","MINUS")],t}function Fe(e,n=!1,r){let i=t.pxtInfo(e).callInfo;if(!i)return void ne(e);if(e.expression.kind===a.Identifier){const t=e.expression.text;if(L.declaredEnums[t]){const n=o.enumsByName[t];if(n&&n.blockId)return Ne(n.blockId,"MEMBER",e.name.text)}else if(L.declaredKinds[t]){return Ne(L.declaredKinds[t].kindInfo.blockId,"MEMBER",e.name.text)}}const s=re(i);if(r=s.blockId||r,s.blockCombine)return function(e,t){return je(e,t,null,"@get@")}(e,e);if("lists_length"===s.blockId||"text_length"===s.blockId){const n=se(t.U.htmlEscape(s.blockId));return n.inputs=[Ce("VALUE",e.expression)],n}let c=t.U.htmlEscape(s.blockId||i.qName);const[l]=E(e),u=l&&t.pxtInfo(l).callInfo;if(n||!r&&!s.blockIdentity||u&&u.qName===s.blockIdentity)return{kind:"text",value:c};s.enumval&&u&&s.useEnumVal&&(c=s.enumval);const d=L.compInfo(i);if(r&&d&&d.thisParameter){const n=se(r);return n.inputs=[Ce(t.U.htmlEscape(d.thisParameter.definitionName),e.expression,d.thisParameter.shadowBlockId)],n}return Le(s.blockIdentity?o.apis.byQName[s.blockIdentity]:o.blocksById[r],c)}function Le(e,n){let r=/(?:%|\$)([a-zA-Z0-9_]+)/.exec(e.attributes.block);const i=se(t.U.htmlEscape(e.attributes.blockId));return i.fields=[{kind:"field",name:t.U.htmlEscape(r[1]),value:n}],i}function Re(n,_,m,g=!1,h=!1){const y=n;let x,k=!1;const C=b(y,L,g,h);if(C)x=Me(y,void 0,C);else switch(y.kind){case a.Block:return Je(y.statements,_,h);case a.ExpressionStatement:return Re(y.expression,_,m||y,g,h);case a.VariableStatement:if(x=Je(y.declarationList.declarations,void 0,!1,m||y),!x)return A();k=!0;break;case a.FunctionExpression:case a.ArrowFunction:return function(e,t){return Re(e.body,t)}(y,_);case a.BinaryExpression:x=function(e){e.left.text;switch(e.operatorToken.kind){case a.EqualsToken:return e.left.kind===a.Identifier?Be(e,e.left,e.right):e.left.kind==a.PropertyAccessExpression?$e(e,e.left,e.right,"@set@"):function(e,t,n){const r=oe("lists_index_set",e);return r.inputs=[Ce("LIST",t.expression),Ce("INDEX",t.argumentExpression,c),Ce("VALUE",n)],r}(e,e.left,e.right);case a.PlusEqualsToken:if(ke(e)){const t=oe("variables_set",e),n=Ge(e.left);return Ve(n,v.InBlocksOnly),t.inputs=[ce("VALUE",Te(e),c)],t.fields=[Pe("VAR",n)],t}return e.left.kind==a.PropertyAccessExpression?$e(e,e.left,e.right,"@change@"):Be(e,e.left,e.right,!0);case a.MinusEqualsToken:const n=oe("variables_change",e);return n.inputs=[ce("VALUE",Oe(e.right),c)],n.fields=[Pe("VAR",Ge(e.left))],n;default:return void ne(e,t.Util.lf("Unsupported operator token in statement {0}",a[e.operatorToken.kind]))}}(y);break;case a.PostfixUnaryExpression:case a.PrefixUnaryExpression:x=function(e){const t=e.operator===a.PlusPlusToken;if(!t&&e.operator!==a.MinusMinusToken)return void ne(e);return Be(e,e.operand,t?1:-1,!0)}(y);break;case a.VariableDeclaration:const n=y;if(S(n))return function(e){G.push([Ge(e.name),e])}(n),A();x=function(e){if(function(e){if(e.name.kind!==a.Identifier)return ne(e,t.Util.lf("Variable declarations may not use binding patterns")),!1;if(!e.initializer)return ne(e,t.Util.lf("Variable declarations must have an initializer")),!1;return!0}(e))return Be(e,e.name,e.initializer);return}(y);break;case a.WhileStatement:x=function(e){const t=oe("device_while",e);return t.inputs=[Ue("COND",e.expression)],t.handlers=[{name:"DO",statement:Re(e.statement)}],t}(y);break;case a.IfStatement:x=function(e){let t=ze(e);const n=oe("controls_if",e);if(n.mutation={elseif:(t.ifStatements.length-1).toString(),else:t.elseStatement?"1":"0"},n.inputs=[],n.handlers=[],t.ifStatements.forEach(((e,t)=>{let r=Re(e.thenStatement);n.inputs.push(Ue("IF"+t,e.expression)),n.handlers.push({name:"DO"+t,statement:r})})),t.elseStatement){let e=Re(t.elseStatement);n.handlers.push({name:"ELSE",statement:e})}return n}(y);break;case a.ForStatement:x=function(t){const n=t.initializer,r=(n.declarations[0].name.text,t.condition),i=Ge(n.declarations[0].name);let o;if(r.operatorToken.kind!==a.LessThanToken||l(t.statement))if(o=oe("pxt_controls_for",t),o.fields=[],o.inputs=[],o.handlers=[],o.inputs=[we("VAR",i)],r.operatorToken.kind===a.LessThanToken){const e=D(r.right);if(e.kind===a.NumericLiteral){const t=Ee(parseFloat(e.text)-1+"");o.inputs.push(ce("TO",t,d))}else{const t=se("math_arithmetic");t.fields=[Pe("OP","MINUS")],t.inputs=[Ce("A",e,c),Ce("B",1,c)],o.inputs.push(ce("TO",t,d))}}else r.operatorToken.kind===a.LessThanEqualsToken&&o.inputs.push(Ce("TO",r.right,d));else o=oe("controls_repeat_ext",t),o.fields=[],o.inputs=[Ce("TIMES",r.right,d)],o.handlers=[];const s=Re(t.statement);return o.handlers=[{name:"DO",statement:s}],o;function l(t){return t.kind===a.Identifier&&Ge(t)===i||e.forEachChild(t,l)}}(y);break;case a.ForOfStatement:x=function(e){const t=Ge(e.initializer.declarations[0].name),n=oe("pxt_controls_for_of",e);n.inputs=[Ce("LIST",e.expression),we("VAR",t)];const r=Re(e.statement);return n.handlers=[{name:"DO",statement:r}],n}(y);break;case a.FunctionDeclaration:x=function(e){const t=Ge(e.name);L.localReporters.push(e.parameters.map((e=>({name:e.name.getText(),type:e.type.getText()}))));const n=Re(e.body);let r;L.localReporters.pop(),r=oe("function_definition",e),r.mutation={name:t},e.parameters&&(r.mutationChildren=[],e.parameters.forEach((e=>{const n=e.name.getText();r.mutationChildren.push({nodeName:"arg",attributes:{name:n,type:e.type.getText(),id:L.functionParamIds[t][n]}})})));return r.handlers=[{name:"STACK",statement:n}],r}(y);break;case a.CallExpression:x=function(n,i){const s=t.pxtInfo(n).callInfo,_=re(s);if("Math.pow"==s.qName){const e=se("math_arithmetic");return e.inputs=[ce("A",ve(n.arguments[0]),c),ce("B",ve(n.arguments[1]),c)],e.fields=[Pe("OP","POWER")],e}if(pxt.Util.startsWith(s.qName,"Math.")){const e=s.qName.substring(5);if(R(e)){let t;if(B(e))t=se("math_js_round");else{let n;t=se("math_js_op"),n=M(e)?"unary":U(e)?"infix":"binary",t.mutation={"op-type":n}}return t.inputs=s.args.map(((e,t)=>ce("ARG"+t,ve(e),"math_number"))),t.fields=[Pe("OP",e)],t}}if(_.blockId===t.PAUSE_UNTIL_TYPE){const e=oe(t.PAUSE_UNTIL_TYPE,n),r=n.arguments[0];let i;return i=r.body.kind===a.Block?r.body.statements[0].expression:r.body,e.inputs=[ce("PREDICATE",ve(i),"logic_boolean")],e}if(!_.blockId||!_.block){const e=pxt.blocks.builtinFunctionInfo[s.qName];if(!e){const e=Ge(n.expression);if(L.declaredFunctions[e]){let t,r=!0;if(s.isExpression){const[e]=E(n);r=e&&e.kind===a.ExpressionStatement}return t=oe(r?"function_call":"function_call_output",n),s.args.length&&(t.mutationChildren=[],t.inputs=[],L.declaredFunctions[e].parameters.forEach(((n,r)=>{const i=n.name.getText(),a=L.functionParamIds[e][i];t.mutationChildren.push({nodeName:"arg",attributes:{name:i,type:n.type.getText(),id:a}});const o=ce(a,ve(s.args[r]));t.inputs.push(o)}))),t.mutation={name:e},t}return Me(n)}_.blockId=e.blockId}if(_.imageLiteral)return function(e,n){let r=e.arguments[0];if(r.kind!=a.StringLiteral&&r.kind!=a.NoSubstitutionTemplateLiteral)return void ne(e);const i=re(n),o=oe(i.blockId,e);o.fields=[];const s=(r.text||"").replace(/\s+/g,""),c=(i.imageLiteralColumns||5)*i.imageLiteral,l=i.imageLiteralRows||5,u=c*l;if(u!=s.length)return void ne(e,t.Util.lf("Invalid image pattern ({0} expected vs {1} actual)",u,s.length));let d="";for(let e=0;e<l;++e){for(let t=0;t<c;++t)d+=/[#*1]/.test(s[e*c+t])?"#":".";d+="\n"}return o.fields.push(Pe("LEDS",`\`${d}\``)),o}(n,s);e.isFunctionLike(s.decl);const m=O(s,L.blocks),g=L.blocks.apis.byQName[s.decompilerBlockAlias||s.qName],h=pxt.blocks.compileInfo(g),y=i?se(_.blockId):oe(_.blockId,n),v=e=>(y.inputs||(y.inputs=[])).push(e),b=e=>(y.fields||(y.fields=[])).push(e);"Math.max"==s.qName&&b({kind:"field",name:"op",value:"max"});let x=0;m.forEach(((e,n)=>{let i,m=e.value;const g=e.param,k=e.info,S=h.parameters[h.thisParameter?n-1:n],C=S&&S.range;if(C){const e=C.min,t=C.max;i={min:e.toString(),max:t.toString()}}if(0===n&&_.defaultInstance){if(m.getText()===_.defaultInstance)return;y.mutation={showing:"true"}}if(_.mutatePropertyEnum&&n===s.args.length-2)return;let E;if(g&&g.isOptional&&++x,g&&g.shadowBlockId&&(E=o.blocksById[g.shadowBlockId]),m.kind===a.CallExpression){const e=t.pxtInfo(m).callInfo,n=e&&re(e);n&&"TD_ID"===n.shim&&k.isEnum&&(m=D(e.args[0]))}if(g&&k&&k.isEnum&&m.kind===a.Identifier)b(Pe(t.U.htmlEscape(g.definitionName),t.pxtInfo(m).commentAttrs.enumIdentity));else if(g&&g.fieldOptions&&g.fieldOptions[r.DecompileArgumentAsString])b(Pe(t.U.htmlEscape(g.definitionName),t.Util.htmlEscape(m.getText())));else switch(m.kind){case a.FunctionExpression:case a.ArrowFunction:m.body;const e=function(e){const n=T(e);if(n)return{callbackproperties:n[0].join(","),renamemap:t.Util.htmlEscape(JSON.stringify(n[1]))};return}(m);let x=!1;if(e)y.mutation=e;else{let e=m;const t=o.blocksById[_.blockId].parameters[h.thisParameter?n-1:n],r=(e,t)=>{"reporter"===_.draggableParameters?v(function(e,t,n){const r=pxt.blocks.reporterTypeForArgType(n);return ce(e,Ie(t,n,!0),r)}("HANDLER_DRAG_PARAM_"+e.name,t,e.type)):v(we("HANDLER_DRAG_PARAM_"+e.name,t))};if(e.parameters.length&&(_.optionalVariableArgs?(y.mutation={numargs:e.parameters.length.toString()},e.parameters.forEach(((e,t)=>{y.mutation["arg"+t]=e.name.text}))):e.parameters.forEach(((e,n)=>{const i=t.handlerParameters[n];_.draggableParameters?r(i,e.name.text):b(Pe("HANDLER_"+i.name,e.name.text))}))),_.draggableParameters){if(e.parameters.length<t.handlerParameters.length)for(let n=e.parameters.length;n<t.handlerParameters.length;n++){const e=t.handlerParameters[n];r(e,e.name)}"reporter"===_.draggableParameters&&(L.localReporters.push(t.handlerParameters),x=!0)}}const S=Re(m);(y.handlers||(y.handlers=[])).push({name:"HANDLER",statement:S}),x&&L.localReporters.pop();break;case a.PropertyAccessExpression:const C=t.pxtInfo(m).callInfo,D=t.U.htmlEscape(g.definitionName),A=re(C);E&&"TD_ID"===E.attributes.shim?v(ce(D,Fe(m,!1,g.shadowBlockId),g.shadowBlockId,i)):k&&k.isEnum||C&&(A.fixedInstance||A.blockIdentity===s.qName)?b(Pe(D,Fe(m,!0).value)):v(Ce(D,m,g.shadowBlockId,i));break;case a.BinaryExpression:if(g&&g.shadowOptions&&g.shadowOptions.toString){const e=m;if(e.operatorToken.kind===a.PlusToken&&function(e){if(e.kind===a.StringLiteral||e.kind===a.NoSubstitutionTemplateLiteral)return""===e.text;return!1}(e.left)){v(Ce(t.U.htmlEscape(g.definitionName),e.right,g.shadowBlockId||"text"));break}}v(Ce(t.U.htmlEscape(g.definitionName),m,g.shadowBlockId,i));break;default:let N;const w=t.U.htmlEscape(g.definitionName);let P=!0;if("Math.random"==s.qName)N=ce(w,function(e){switch(e.kind){case a.NumericLiteral:return Ee((parseInt(e.text)-1).toString());case a.BinaryExpression:const t=e;if(t.operatorToken.kind==a.PlusToken&&"1"==t.right.text)return ve(t.left);default:return ve(e)}}(m),c,i),P=!1;else if(I(m)){const e="text"==g.fieldEditor?m.text:m.getText(),n=g.shadowBlockId&&!function(e){switch(e){case c:case l:case u:case d:case p:case f:return!0;default:return!1}}(g.shadowBlockId);if(Ke(g)&&g.fieldOptions.onParentBlock)return void b(Pe(w,e));if(n){const n=function(e){if(o.blocksById[e]){const t=pxt.blocks.compileInfo(o.blocksById[e]);if(!t.thisParameter&&1===t.parameters.length)return t.parameters[0]}return}(g.shadowBlockId);if(n&&Ke(n)){const r=Ne(g.shadowBlockId,n.definitionName,e,!0);g.shadowOptions&&(r.mutation={customfield:t.Util.htmlEscape(JSON.stringify(g.shadowOptions))}),N=ce(w,r,g.shadowBlockId,i),P=!1}}}else if(m.kind===a.TaggedTemplateExpression&&g.fieldOptions&&g.fieldOptions[r.TaggedTemplate])return void b(Pe(w,t.Util.htmlEscape(m.getText())));P&&(N=Ce(w,m,g.shadowBlockId,i)),v(N)}})),x&&(y.mutation||(y.mutation={}),y.mutation._expanded=x.toString());return y}(y,g);break;case a.DebuggerStatement:x=function(e){return oe(t.TS_DEBUGGER_TYPE,e)}(y);break;case a.BreakStatement:x=function(e){return oe(t.TS_BREAK_TYPE,e)}(y);break;case a.ContinueStatement:x=function(e){return oe(t.TS_CONTINUE_TYPE,e)}(y);break;case a.EmptyStatement:x=void 0;break;case a.EnumDeclaration:case a.ModuleDeclaration:return V(y,Y),A();case a.ReturnStatement:x=function(e){const n=oe(t.TS_RETURN_STATEMENT_TYPE,e);e.expression?n.inputs=[ce("RETURN_VALUE",ve(e.expression),c)]:n.mutation={no_return_value:"true"};return n}(y);break;default:return void ne(y,_?t.Util.lf("Unsupported statement in block: {0}",a[y.kind]):t.Util.lf("Statement kind unsupported in blocks: {0}",a[y.kind]))}if(x){let e=x;for(;e.next;)e=e.next;e.next=A(),e.next&&(e.next.prev=e)}return k||function(t){let n,r=[];for(let e=0;e<Y.length&&(n=Y[e],!n.owner&&n.start>=t.pos&&n.end<=t.end&&(n.owner=t,n.ownerStatement=x,r.push(n)),!(n.start>t.end));e++);if(n&&n.isTrailingComment){const i=e.getLineAndCharacterOfPosition(s,t.end),a=e.getLineAndCharacterOfPosition(s,n.start);if(i.line===a.line){if(n.ownerStatement){n.ownerStatement.comment.splice(n.ownerStatement.comment.indexOf(n),1);for(const e of H)e.comment.splice(e.comment.indexOf(n),1)}n.owner=t,n.ownerStatement=x,r.push(n)}}if(r.length){const e=[];if(J(t)){let t=[];const n=[];r.forEach(((e,a)=>{let o=e.owner&&e.start<e.owner.getStart();e.kind===i.MultiLine&&o&&(t.length&&(n.push(t),t=[]),a!=r.length-1)?n.push([e]):(t.push(e),e.followedByEmptyLine&&o&&(n.push(t),t=[]))})),r=t,n.forEach((t=>{const n=W();e.push(n),H.push({comment:t,refId:n})}))}x&&(e.length&&(x.data?x.data+=";"+e.join(";"):x.data=e.join(";")),r&&r.length&&(x.comment?x.comment=x.comment.concat(r):x.comment=r))}}(m||y),x;function A(){if(_&&_.length)return Re(_.shift(),_,void 0,!1,h)}}function Me(e,n,r){m.errorOnGreyBlocks&&ne(e);const i=oe(t.TS_STATEMENT_TYPE,e);i.mutation={},He(e);let o=e.getText();o=be(o,e.getStart(),e.getEnd()),V(e,Y),n&&(o=n+o);const s=[];if(e.kind===a.VariableStatement)for(const t of e.declarationList.declarations)s.push(Ge(t.name));else e.kind===a.VariableDeclaration&&s.push(Ge(e.name));s.length&&(i.mutation.declaredvars=s.join(","));const c=o.split("\n");return i.mutation.numlines=c.length.toString(),r&&m.includeGreyBlockMessages&&(i.mutation.error=t.U.htmlEscape(r)),c.forEach(((e,n)=>{i.mutation[`line${n}`]=t.U.htmlEscape(e)})),i}function Ue(n,r){if(function(n){const r=D(n);switch(r.kind){case a.TrueKeyword:case a.FalseKeyword:case a.Identifier:case a.ElementAccessExpression:return;case a.BinaryExpression:return i(r);case a.CallExpression:return o(r);case a.PrefixUnaryExpression:if(r.operator===a.ExclamationToken)return;default:return t.Util.lf("Conditions must evaluate to booleans or identifiers")}function i(e){switch(e.operatorToken.kind){case a.EqualsEqualsToken:case a.EqualsEqualsEqualsToken:case a.ExclamationEqualsToken:case a.ExclamationEqualsEqualsToken:case a.LessThanToken:case a.LessThanEqualsToken:case a.GreaterThanToken:case a.GreaterThanEqualsToken:case a.AmpersandAmpersandToken:case a.BarBarToken:return;default:return t.Util.lf("Binary expressions in conditionals must evaluate to booleans")}}function o(n){const r=t.pxtInfo(n).callInfo;if(r){const t=L.blocks.apis.byQName[r.qName];if(t&&"boolean"==t.retType)return;if(e.isIdentifier(n.expression)&&L.declaredFunctions[n.expression.text])return}return t.Util.lf("Only functions that return booleans are allowed as conditions")}}(r)){return ce(n,xe(r),f)}return Ce(n,r,f)}function Be(e,t,n,r=!1,i=!1){const a=Ge(t);Ve(a,v.InBlocksOnly);const o=oe(r?"variables_change":"variables_set",e.parent||e);return o.inputs=[Ce("VALUE",n,c)],o.fields=[Pe("VAR",a)],o}function $e(e,t,n,r){return je(e,t,n,r)}function je(e,n,r,i){const a=t.pxtInfo(n).callInfo,o=L.blocks.apis.byQName[a?a.qName:""];if(!o||!o.attributes.blockCombine)return void ne(n);const s=`${o.namespace}.${o.retType}.${i}`,c=L.blocks.blocks.find((e=>e.qName==s)),l=r?oe(c.attributes.blockId,e):se(c.attributes.blockId),u=c.attributes._def.parameters;let d=a.qName;return c.combinedProperties&&c.combinedProperties.forEach((e=>{0===e.indexOf(a.qName)&&"@"===e.charAt(a.qName.length)&&(d=e)})),l.inputs=[Ce(u[0].name,n.expression)],l.fields=[Pe(u[1].name,d)],r&&l.inputs.push(Ce(u[2].name,r)),l}function Ke(e){return e&&e.fieldOptions&&e.fieldOptions[r.DecompileLiterals]}function ze(e){let t={ifStatements:[{expression:e.expression,thenStatement:e.thenStatement}],elseStatement:e.elseStatement};if(e.elseStatement&&e.elseStatement.kind==a.IfStatement){let n=ze(e.elseStatement);t.ifStatements=t.ifStatements.concat(n.ifStatements),t.elseStatement=n.elseStatement}return t}function Je(t,n,r=!1,i,o=!1){const s=[],c=n||[];for(let e=t.length-1;e>=0;e--){const n=t[e];(n.kind===a.FunctionDeclaration||n.kind==a.ExpressionStatement&&le(n))&&!b(n,L,!1,r)?s.unshift(n):c.unshift(n)}if(s.map((e=>Re(e,void 0,void 0,!1,r))).forEach(ue),c.length){const t=c.shift(),n=Re(t,c,i,!1,r);if(o){let r=n,i=t;if(G.forEach((([e,n])=>{if(K[e]===v.InBlocksOnly)return;let a;n.initializer;a=K[e]===v.InTextBlocks?Me(n,"let "):Be(t,n.name,n.initializer,!1,!0),a.next=r,r=a,i=n})),r){const t=oe(e.pxtc.ON_START_TYPE,i);return t.handlers=[{name:"HANDLER",statement:r}],t}qe(n)}return n}o&&qe(void 0)}function qe(t){m.alwaysEmitOnStart&&(he(e.pxtc.ON_START_TYPE,t),ye())}function Ve(e,t){K[e]!==v.InTextBlocks&&(K[e]=t)}function He(t){e.forEachChild(t,(e=>{e.kind===a.Identifier&&Ve(Ge(e),v.InTextBlocks),He(e)}))}function Ge(e){if(g){const t=g.getRenameForPosition(e.getStart());if(t)return t.name}return e.text}},n.getLeadingComments=function(t,n,r){return K(n,r||e.getLeadingCommentRangesOfNode(t,n))},n.getTrailingComments=function(t,n){return K(n,e.getTrailingCommentRanges(n.getFullText(),t.end))},n.getCommentsForStatement=function(e,t){let n,r=[];for(let i=0;i<t.length&&(n=t[i],!n.owner&&n.start>=e.pos&&n.end<=e.end&&(n.owner=e,r.push(n)),!(n.start>e.end));i++);return r},n.buildCommentMap=q}(t.decompiler||(t.decompiler={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){!function(e){function t(e,n){var r;switch(e){case"void":return"None";case"boolean":return"bool";case"string":return"str"}if(null===(r=n.byQName[e])||void 0===r?void 0:r.pyQName)return n.byQName[e].pyQName;const i=/^(?:Array<(.+)>)|(?:(.+)\[\])|(?:\[.+\])$/.exec(e);return i?`List[${t(i[1]||i[2],n)}]`:e}function n(e,t){return`\`\`\`${t?"python":"ts"}\n${e}\n\`\`\``}e.displayStringForSymbol=function(e,r,i){if(e){switch(e.kind){case 3:case 1:return function(e,r,i){let a="";3===e.kind?a+=r?"def ":"function ":a+="(method) ";a+=r?e.pyQName:e.qName;let o="";e.parameters&&e.parameters.length&&(o=e.parameters.map((e=>`${e.name}: ${r?e.pyTypeString:e.type}`)).join(", "));let s=e.retType||"void";r&&(s=t(s,i));return n(`${a}(${o}): ${s}`,r)}(e,r,i);case 6:case 7:return function(e,t){const r=t?e.pyQName:e.qName;if(6===e.kind)return n(`enum ${r}`,t);let i=`(enum member) ${r}`;e.attributes.enumval&&(i+=` = ${e.attributes.enumval}`);return n(i,!1)}(e,r);case 5:return function(e,t){return n(`namespace ${t?e.pyQName:e.qName}`,!1)}(e,r);case 9:return function(e,t){return n(`interface ${t?e.pyQName:e.qName}`,!1)}(e,r);case 8:return function(e,t){return n(`class ${t?e.pyQName:e.qName}`,t)}(e,r);case 4:return function(e,r,i){let a=r?e.pyQName:`let ${e.qName}`;if(e.retType){let o=e.retType;return r&&(o=t(o,i)),n(`${a}: ${o}`,r)}return n(a,r)}(e,r,i);case 2:return function(e,r,i){const a=`(property) ${r?e.pyQName:e.qName}`;if(e.retType){let o=e.retType;return r&&(o=t(o,i)),n(`${a}: ${o}`,!1)}return n(a,!1)}(e,r,i)}return`**${e.qName}**`}},e.displayStringForKeyword=function(e,t){return`\`\`\`${t?"py":"ts"}\n(keyword) ${e}\n\`\`\``}}(e.service||(e.service={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){!function(t){const n={r0:0,r1:1,r2:2,r3:3,r4:4,r5:5,r6:6,r7:7,r8:8,r9:9,r10:10,r11:10,r12:12,sp:13,r13:13,lr:14,r14:14,pc:15,r15:15};class r extends e.assembler.AbstractProcessor{constructor(){super(),this.addEnc("$r0","R0-7",(e=>this.inrange(7,e,e))),this.addEnc("$r1","R0-7",(e=>this.inrange(7,e,e<<3))),this.addEnc("$r2","R0-15",(e=>this.inrange(15,e,7&e|(8&e)<<4))),this.addEnc("$r3","R0-15",(e=>this.inrange(15,e,e<<3))),this.addEnc("$r4","R0-7",(e=>this.inrange(7,e,e<<6))),this.addEnc("$r5","R0-7",(e=>this.inrange(7,e,e<<8))),this.addEnc("$r01","R0-7",(e=>this.inrange(7,e,e|e<<3))),this.addEnc("$i0","#0-255",(e=>this.inrange(255,e,e))),this.addEnc("$i1","#0-1020",(e=>this.inrange(255,e/4,e>>2))),this.addEnc("$i2","#0-510",(e=>this.inrange(127,e/4,e>>2))),this.addEnc("$i3","#0-7",(e=>this.inrange(7,e,e<<6))),this.addEnc("$i4","#0-31",(e=>this.inrange(31,e,e<<6))),this.addEnc("$i5","#0-124",(e=>this.inrange(31,e/4,e>>2<<6))),this.addEnc("$i6","#1-32",(e=>0==e?null:32==e?0:this.inrange(31,e,e<<6))),this.addEnc("$i7","#0-62",(e=>this.inrange(31,e/2,e>>1<<6))),this.addEnc("$i32","#0-2^32",(e=>1)),this.addEnc("$rl0","{R0-7,...}",(e=>this.inrange(255,e,e))),this.addEnc("$rl1","{LR,R0-7,...}",(e=>16384&e?this.inrange(255,-16385&e,256|255&e):this.inrange(255,e,e))),this.addEnc("$rl2","{PC,R0-7,...}",(e=>32768&e?this.inrange(255,-32769&e,256|255&e):this.inrange(255,e,e))),this.addEnc("$la","LABEL",(e=>this.inrange(255,e/4,e>>2))).isWordAligned=!0,this.addEnc("$lb","LABEL",(e=>this.inrangeSigned(127,e/2,e>>1))),this.addEnc("$lb11","LABEL",(e=>this.inrangeSigned(1023,e/2,e>>1))),this.addInst("adcs $r0, $r1",16704,65472),this.addInst("add $r2, $r3",17408,65280),this.addInst("add $r5, pc, $i1",40960,63488),this.addInst("add $r5, sp, $i1",43008,63488),this.addInst("add sp, $i2",45056,65408).canBeShared=!0,this.addInst("adds $r0, $r1, $i3",7168,65024),this.addInst("adds $r0, $r1, $r4",6144,65024),this.addInst("adds $r01, $r4",6144,65024),this.addInst("adds $r5, $i0",12288,63488),this.addInst("adr $r5, $la",40960,63488),this.addInst("ands $r0, $r1",16384,65472),this.addInst("asrs $r0, $r1",16640,65472),this.addInst("asrs $r0, $r1, $i6",4096,63488),this.addInst("bics $r0, $r1",17280,65472),this.addInst("bkpt $i0",48640,65280),this.addInst("blx $r3",18304,65415),this.addInst("bx $r3",18176,65408),this.addInst("cmn $r0, $r1",17088,65472),this.addInst("cmp $r0, $r1",17024,65472),this.addInst("cmp $r2, $r3",17664,65280),this.addInst("cmp $r5, $i0",10240,63488),this.addInst("eors $r0, $r1",16448,65472),this.addInst("ldmia $r5!, $rl0",51200,63488),this.addInst("ldmia $r5, $rl0",51200,63488),this.addInst("ldr $r0, [$r1, $i5]",26624,63488),this.addInst("ldr $r0, [$r1, $r4]",22528,65024),this.addInst("ldr $r5, [pc, $i1]",18432,63488),this.addInst("ldr $r5, $la",18432,63488),this.addInst("ldr $r5, [sp, $i1]",38912,63488).canBeShared=!0,this.addInst("ldr $r5, [sp]",38912,63488).canBeShared=!0,this.addInst("ldrb $r0, [$r1, $i4]",30720,63488),this.addInst("ldrb $r0, [$r1, $r4]",23552,65024),this.addInst("ldrh $r0, [$r1, $i7]",34816,63488),this.addInst("ldrh $r0, [$r1, $r4]",23040,65024),this.addInst("ldrsb $r0, [$r1, $r4]",22016,65024),this.addInst("ldrsh $r0, [$r1, $r4]",24064,65024),this.addInst("lsls $r0, $r1",16512,65472),this.addInst("lsls $r0, $r1, $i4",0,63488),this.addInst("lsrs $r0, $r1",16576,65472),this.addInst("lsrs $r0, $r1, $i6",2048,63488),this.addInst("mov $r2, $r3",17920,65280),this.addInst("movs $r0, $r1",0,65472),this.addInst("movs $r5, $i0",8192,63488),this.addInst("muls $r0, $r1",17216,65472),this.addInst("mvns $r0, $r1",17344,65472),this.addInst("negs $r0, $r1",16960,65472),this.addInst("nop",18112,65535),this.addInst("orrs $r0, $r1",17152,65472),this.addInst("pop $rl2",48128,65024),this.addInst("push $rl1",46080,65024),this.addInst("rev $r0, $r1",47616,65472),this.addInst("rev16 $r0, $r1",47680,65472),this.addInst("revsh $r0, $r1",47808,65472),this.addInst("rors $r0, $r1",16832,65472),this.addInst("sbcs $r0, $r1",16768,65472),this.addInst("sev",48960,65535),this.addInst("stm $r5!, $rl0",49152,63488),this.addInst("stmia $r5!, $rl0",49152,63488),this.addInst("stmea $r5!, $rl0",49152,63488),this.addInst("str $r0, [$r1, $i5]",24576,63488).canBeShared=!0,this.addInst("str $r0, [$r1]",24576,63488).canBeShared=!0,this.addInst("str $r0, [$r1, $r4]",20480,65024),this.addInst("str $r5, [sp, $i1]",36864,63488).canBeShared=!0,this.addInst("str $r5, [sp]",36864,63488).canBeShared=!0,this.addInst("strb $r0, [$r1, $i4]",28672,63488),this.addInst("strb $r0, [$r1, $r4]",21504,65024),this.addInst("strh $r0, [$r1, $i7]",32768,63488),this.addInst("strh $r0, [$r1, $r4]",20992,65024),this.addInst("sub sp, $i2",45184,65408),this.addInst("subs $r0, $r1, $i3",7680,65024),this.addInst("subs $r0, $r1, $r4",6656,65024),this.addInst("subs $r01, $r4",6656,65024),this.addInst("subs $r5, $i0",14336,63488),this.addInst("svc $i0",57088,65280),this.addInst("sxtb $r0, $r1",45632,65472),this.addInst("sxth $r0, $r1",45568,65472),this.addInst("tst $r0, $r1",16896,65472),this.addInst("udf $i0",56832,65280),this.addInst("uxtb $r0, $r1",45760,65472),this.addInst("uxth $r0, $r1",45696,65472),this.addInst("wfe",48928,65535),this.addInst("wfi",48944,65535),this.addInst("yield",48912,65535),this.addInst("cpsid i",46706,65535),this.addInst("cpsie i",46690,65535),this.addInst("beq $lb",53248,65280),this.addInst("bne $lb",53504,65280),this.addInst("bcs $lb",53760,65280),this.addInst("bcc $lb",54016,65280),this.addInst("bmi $lb",54272,65280),this.addInst("bpl $lb",54528,65280),this.addInst("bvs $lb",54784,65280),this.addInst("bvc $lb",55040,65280),this.addInst("bhi $lb",55296,65280),this.addInst("bls $lb",55552,65280),this.addInst("bge $lb",55808,65280),this.addInst("blt $lb",56064,65280),this.addInst("bgt $lb",56320,65280),this.addInst("ble $lb",56576,65280),this.addInst("bhs $lb",53760,65280),this.addInst("blo $lb",54016,65280),this.addInst("b $lb11",57344,63488),this.addInst("bal $lb11",57344,63488),this.addInst("bl $lb",61440,63488,!0),this.addInst("bb $lb",57344,63488,!0),this.addInst("ldlit $r5, $i32",18432,63488)}toFnPtr(t,n,r){return e.target.runtimeIsARM&&/::/.test(r)?t+n&-2:t+n|1}wordSize(){return 4}is32bit(e){return"bl"==e.name||"bb"==e.name}postProcessAbsAddress(e,t){return t^=1,t-=e.baseOffset}emit32(t,n,r){let i=!!(n%2);i&&(n=n+1&-4);let a=n>>1;if(e.assert(null!=a),(0|a)!=a||!(-2097152<a&&a<2097152))return e.assembler.emitErr("jump out of range",r);let o=2047&a,s=a>>11&1023;return{opcode:4026531840&a?62464|s:61440|s,opcode2:i?59392|o:63488|o,stack:0,numArgs:[n],labelName:r}}expandLdlit(t){let n,r=!1,i=[],a={},o=1;for(let s=0;s<t.lines.length;++s){let c=t.lines[s];if(i.push(c),"instruction"==c.type&&c.instruction&&"ldlit"==c.instruction.name){if(!n){let e=c.location+900,i=s+1;for(;i<t.lines.length&&!(t.lines[i].location>e);++i){let e=t.lines[i].getOp();("b"==e||"bb"==e||"pop"==e&&"pc"==t.lines[i].words[2])&&(n=t.lines[i])}if(n)r=!1;else for(r=!0;--i>s;)if("instruction"==t.lines[i].type){n=t.lines[i];break}}let i=c.words[1],l="#"+c.words[3],u=e.U.lookup(a,l);u||(u="_ldlit_"+ ++o,a[l]=u),c.update(`ldr ${i}, ${u}`)}if(c===n){n=null;let e=[],s="_jmpwords_"+ ++o;r&&e.push("bb "+s),e.push(".balign 4");for(let t of Object.keys(a)){let n=a[t];e.push(n+": .word "+t.slice(1))}r&&e.push(s+":");for(let n of e){t.buildLine(n,i);let e=i[i.length-1];e.scope=c.scope,e.lineNo=c.lineNo}a={}}}t.lines=i}getAddressFromLabel(e,t,n,r=!1){let i=e.lookupLabel(n);if(null==i)return null;let a=e.location()+4;return r&&(a&=4294967292),i-a}isPop(e){return 48128==e}isPush(e){return 46080==e}isAddSP(e){return 45056==e}isSubSP(e){return 45184==e}peephole(t,n,r){let a=this.encoders.$lb11,o=this.encoders.$lb;function s(e,t){return null!=e.encode(t.numArgs[0]+8)&&null!=e.encode(t.numArgs[0]-8)&&null!=e.encode(t.numArgs[0])}let c=t.getOp(),l=!1;"bne"!=c&&"beq"!=c||("b"==n.getOp()&&0==t.numArgs[0]&&(l=!0),"bb"==n.getOp()&&2==t.numArgs[0]&&(l=!0)),"bb"==c&&s(a,t)?t.update("b "+t.words[1]):"b"==c&&-2==t.numArgs[0]?t.update(""):"bne"==c&&l&&s(o,n)?(t.update("beq "+n.words[1]),n.update("")):"beq"==c&&l&&s(o,n)?(t.update("bne "+n.words[1]),n.update("")):"push"!=c||16384!=t.numArgs[0]||"push"!=n.getOp()||16384&n.numArgs[0]?"pop"==c&&"pop"==n.getOp()&&32768==n.numArgs[0]?(t.update(t.text.replace("}",", pc}")),n.update("")):"push"==c&&"pop"==n.getOp()&&t.numArgs[0]==n.numArgs[0]?(e.assert(t.numArgs[0]>0),t.update(""),n.update("")):"push"==c&&"pop"==n.getOp()&&4==t.words.length&&4==n.words.length?(e.assert("{"==t.words[1]),t.update("mov "+n.words[2]+", "+t.words[2]),n.update("")):r&&"movs $r5, $i0"==t.getOpExt()&&"mov $r0, $r1"==n.getOpExt()&&t.numArgs[0]==n.numArgs[1]&&function(e,t){return!!("pop"==e.getOp()&&e.numArgs[0]&1<<t)}(r,t.numArgs[0])?(t.update("movs r"+n.numArgs[0]+", #"+t.numArgs[1]),n.update("")):"pop"==c&&i(t)>=0&&"push"==n.getOp()&&i(t)==i(n)?(t.update("ldr r"+i(t)+", [sp, #0]"),n.update("")):"push"==c&&"ldr $r5, [sp, $i1]"==n.getOpExt()&&i(t)==n.numArgs[0]&&0==n.numArgs[1]?n.update(""):r&&"push"==c&&i(t)>=0&&function(e,t){return"movs $r5, $i0"==e.getOpExt()&&e.numArgs[0]!=t}(n,i(t))&&"pop"==r.getOp()&&i(t)==i(r)&&(t.update(""),r.update("")):(t.update(n.text.replace("{","{lr, ")),n.update(""))}registerNo(e){if(!e)return null;e=e.toLowerCase();const t=n[e];return void 0===t?null:t}testAssembler(){e.assembler.expectError(this,"lsl r0, r0, #8"),e.assembler.expectError(this,"push {pc,lr}"),e.assembler.expectError(this,"push {r17}"),e.assembler.expectError(this,"mov r0, r1 foo"),e.assembler.expectError(this,"movs r14, #100"),e.assembler.expectError(this,"push {r0"),e.assembler.expectError(this,"push lr,r0}"),e.assembler.expectError(this,"pop {lr,r0}"),e.assembler.expectError(this,"b #+11"),e.assembler.expectError(this,"b #+102400"),e.assembler.expectError(this,"bne undefined_label"),e.assembler.expectError(this,".foobar"),e.assembler.expect(this,"0200 lsls r0, r0, #8\nb500 push {lr}\n2064 movs r0, #100 ; 0x64\nb401 push {r0}\nbc08 pop {r3}\nb501 push {r0, lr}\nbd20 pop {r5, pc}\nbc01 pop {r0}\n4770 bx lr\n0000 .balign 4\ne6c0 .word -72000\nfffe\n"),e.assembler.expect(this,"4291 cmp r1, r2\nd100 bne l6\ne000 b l8\n1840 l6: adds r0, r0, r1\n4718 l8: bx r3\n"),e.assembler.expect(this," @stackmark base\nb403 push {r0, r1}\n @stackmark locals\n9801 ldr r0, [sp, locals@1]\nb401 push {r0}\n9802 ldr r0, [sp, locals@1]\nbc01 pop {r0}\n @stackempty locals\n9901 ldr r1, [sp, locals@1]\n9102 str r1, [sp, base@0]\n @stackempty locals\nb002 add sp, #8\n @stackempty base\n"),e.assembler.expect(this,"b090 sub sp, #4*16\nb010 add sp, #4*16\n"),e.assembler.expect(this,'6261 .string "abc"\n0063 \n'),e.assembler.expect(this,'6261 .string "abcde"\n6463 \n0065 \n'),e.assembler.expect(this,"3042 adds r0, 0x42\n1c0d adds r5, r1, #0\nd100 bne #0\n2800 cmp r0, #0\n6b28 ldr r0, [r5, #48]\n0200 lsls r0, r0, #8\n2063 movs r0, 0x63\n4240 negs r0, r0\n46c0 nop\nb500 push {lr}\nb401 push {r0}\nb402 push {r1}\nb404 push {r2}\nb408 push {r3}\nb520 push {r5, lr}\nbd00 pop {pc}\nbc01 pop {r0}\nbc02 pop {r1}\nbc04 pop {r2}\nbc08 pop {r3}\nbd20 pop {r5, pc}\n9003 str r0, [sp, #4*3]\n")}}function i(t){e.assert("push"==t.getOp()||"pop"==t.getOp());let n=0,r=-1,i=t.numArgs[0];for(;i>0;)1&i&&(r=-1==r?n:-2),i>>=1,n++;return r>=0?r:-1}t.ThumbProcessor=r}(e.thumb||(e.thumb={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){!function(n){let r,i=t.Util;i.assert;!function(e){e[e.None=0]="None",e[e.NumberLiteral=1]="NumberLiteral",e[e.PointerLiteral=2]="PointerLiteral",e[e.RuntimeCall=3]="RuntimeCall",e[e.ProcCall=4]="ProcCall",e[e.SharedRef=5]="SharedRef",e[e.SharedDef=6]="SharedDef",e[e.FieldAccess=7]="FieldAccess",e[e.Store=8]="Store",e[e.CellRef=9]="CellRef",e[e.Sequence=10]="Sequence",e[e.JmpValue=11]="JmpValue",e[e.Nop=12]="Nop",e[e.InstanceOf=13]="InstanceOf"}(r=n.EK||(n.EK={}));let a,o,s=0;class c{isExpr(){return!1}isStmt(){return!1}getId(){return this._id||(this._id=++s),this._id}}n.Node=c;class l extends c{constructor(e,t,n){super(),this.exprKind=e,this.args=t,this.data=n,this.callingConvention=0}static clone(e){let t=new l(e.exprKind,e.args?e.args.slice(0):null,e.data);return e.jsInfo&&(t.jsInfo=e.jsInfo),e.totalUses&&(t.totalUses=e.totalUses,t.currUses=e.currUses),t.callingConvention=e.callingConvention,t.mask=e.mask,t.isStringLiteral=e.isStringLiteral,t}reset(){this.currUses=0,this.prevTotalUses&&(this.totalUses=this.prevTotalUses)}ptrlabel(){return this.jsInfo instanceof u?this.jsInfo:null}hexlit(){const e=this.jsInfo;return null!=e.hexlit?e.hexlit:null}isExpr(){return!0}isPure(){return this.isStateless()||this.exprKind==r.CellRef}isLiteral(){switch(this.exprKind){case r.NumberLiteral:case r.PointerLiteral:return!0;default:return!1}}isStateless(){switch(this.exprKind){case r.NumberLiteral:case r.PointerLiteral:case r.SharedRef:return!0;default:return!1}}sharingInfo(){let e=this,t=this.getId();return this.exprKind!=r.SharedRef&&this.exprKind!=r.SharedDef||(e=this.args[0],e?t=e.getId():e={currUses:"",totalUses:""}),`${e.currUses}/${e.totalUses} #${t}`}toString(){return d(this)}canUpdateCells(){switch(this.exprKind){case r.NumberLiteral:case r.PointerLiteral:case r.CellRef:case r.JmpValue:case r.SharedRef:case r.Nop:return!1;case r.SharedDef:case r.FieldAccess:case r.InstanceOf:return this.args[0].canUpdateCells();case r.RuntimeCall:case r.ProcCall:case r.Sequence:case r.Store:return!0;default:throw t.oops()}}}n.Expr=l,function(e){e[e.None=0]="None",e[e.Expr=1]="Expr",e[e.Label=2]="Label",e[e.Jmp=3]="Jmp",e[e.StackEmpty=4]="StackEmpty",e[e.Breakpoint=5]="Breakpoint",e[e.Comment=6]="Comment"}(a=n.SK||(n.SK={})),function(e){e[e.Always=1]="Always",e[e.IfZero=2]="IfZero",e[e.IfNotZero=3]="IfNotZero"}(o=n.JmpMode||(n.JmpMode={})),n.lblNumUsesJmpNext=-101;class u extends c{constructor(e,t){super(),this.stmtKind=e,this.expr=t}isStmt(){return!0}toString(){return d(this)}}function d(e){return function e(i){if(i.isExpr()){let n=i,a=n.args?n.args[0]:null;switch(n.exprKind){case r.NumberLiteral:case r.PointerLiteral:return n.data+"";case r.CellRef:return n.data.toString();case r.JmpValue:return"JMPVALUE";case r.Nop:return"NOP";case r.SharedRef:return`SHARED_REF(#${a.getId()})`;case r.SharedDef:return`SHARED_DEF(#${a.getId()} u(${a.totalUses}): ${e(a)})`;case r.FieldAccess:return`${e(a)}.${n.data.name}`;case r.RuntimeCall:return n.data+"("+n.args.map(e).join(", ")+")";case r.ProcCall:let i=n.data,o="";return o=null!=i.ifaceIndex?`IFACE@${i.ifaceIndex}`:null!=i.virtualIndex?`VTABLE@${i.virtualIndex}`:t.getDeclName(i.proc.action),o+"("+n.args.map(e).join(", ")+")";case r.Sequence:return"("+n.args.map(e).join("; ")+")";case r.InstanceOf:return"("+e(n.args[0])+" instanceof "+n.data.id+")";case r.Store:return`{ ${e(n.args[0])} := ${e(n.args[1])} }`;default:throw t.oops()}}else{let r=i,a=r.expr?e(r.expr):"{null}";switch(r.stmtKind){case n.SK.Expr:return" "+a+"\n";case n.SK.Jmp:let e=`goto ${r.lblName}\n`;switch(r.jmpMode){case o.Always:return r.expr?` { JMPVALUE := ${a} } ${e}`:" "+e;case o.IfZero:return` if (! ${a}) ${e}`;case o.IfNotZero:return` if (${a}) ${e}`;default:throw t.oops()}case n.SK.StackEmpty:return" ;\n";case n.SK.Breakpoint:return" // brk "+r.breakpointInfo.id+"\n";case n.SK.Comment:return" // "+r.expr.data+"\n";case n.SK.Label:return r.lblName+":\n";default:throw t.oops()}}}(e)}n.Stmt=u;class p{constructor(e,n,r){this.index=e,this.def=n,this.info=r,this.isarg=!1,this.iscap=!1,this._isLocal=!1,this._isGlobal=!1,this._debugType="?",this.isUserVariable=!1,this.bitSize=0,n&&(t.isInPxtModules(n)||(this.isUserVariable=!0),r&&t.setCellProps(this))}getName(){return t.getDeclName(this.def)}getDebugInfo(){return{name:this.getName(),type:this._debugType,index:this.index}}toString(){let e="";return this.def&&(e+=this.getName()||"?"),this.isarg&&(e="ARG "+e),"["+e+"]"}uniqueName(){return this.isarg?"arg"+this.index:this.getName().replace(/[^\w]/g,"_")+"___"+t.getNodeId(this.def)}isLocal(){return this._isLocal}isGlobal(){return this._isGlobal}loadCore(){return h(r.CellRef,null,this)}load(){let e=this.loadCore();return t.target.isNative&&!t.isStackMachine()&&0!=this.bitSize?6==this.bitSize?v("pxt::fromUInt",[e]):v("pxt::fromInt",[e]):this.isByRefLocal()?v("pxtrt::ldlocRef",[e]):e}isByRefLocal(){return this.isLocal()&&this.info.captured&&this.info.written}storeDirect(e){return h(r.Store,[this.loadCore(),e])}storeByRef(e){if(this.isByRefLocal())return v("pxtrt::stlocRef",[this.loadCore(),e]);if(t.target.isNative&&!t.isStackMachine()&&0!=this.bitSize){let t=6==this.bitSize?"pxt::toUInt":"pxt::toInt";return this.storeDirect(v(t,[e],1))}return this.storeDirect(e)}get isTemporary(){return!1}}n.Cell=p;class f extends p{constructor(e,t){super(e,null,null),this.index=e,this.owningProc=t,this.uid=f.unnamedCellCounter++}getName(){return"unnamed"+this.uid}uniqueName(){return this.getName()+"___U"+this.index}isByRefLocal(){return!1}get isTemporary(){return!0}}function _(e){const t=()=>{if(!e.args)return 0;let t=0;for(let n of e.args)t+=_(n);return e.mask&&e.mask.conversions&&(t+=4*e.mask.conversions.length),t};switch(e.exprKind){case r.NumberLiteral:return 2;case r.PointerLiteral:return 6;case r.RuntimeCall:return t()+2+2+4;case r.CellRef:return 2;case r.FieldAccess:return t()+(e.data.needsCheck?4:0)+2;case r.ProcCall:case r.SharedRef:case r.SharedDef:case r.Store:case r.Sequence:case r.JmpValue:case r.Nop:case r.InstanceOf:return 1e6;default:throw i.oops()}}function m(e){switch((e=l.clone(e)).exprKind){case r.PointerLiteral:case r.NumberLiteral:return e;case r.RuntimeCall:for(let t=0;t<e.args.length;++t)e.args[t]=m(e.args[t]);return e;case r.CellRef:const t=e.data;return t.repl?(t.replUses++,t.repl):e;case r.FieldAccess:return e.args[0]=m(e.args[0]),e;default:throw i.oops()}}f.unnamedCellCounter=0,n.UnnamedCell=f;function g(e,t){return new u(e,t)}function h(e,t,n){return new l(e,t,n)}function y(e,t){let n=h(r.PointerLiteral,null,e);return n.jsInfo=t,n}function v(e,t,n=0){let i=h(r.RuntimeCall,t,e);return n&&(i.mask={refMask:n}),i}function b(e,a=!1,o=!1){let s=!!a&&e.some((e=>e.canUpdateCells())),c=[];for(let t of i.reversed(e))t.isStateless()||(t.exprKind!=r.CellRef||s)&&(t.canUpdateCells()&&(s=!0),c.push(t));c.reverse(),t.isStackMachine()&&!o&&(c=[]);let l=[],u=e.map((e=>{if(c.indexOf(e)>=0){let t=e,i=e;return e.exprKind==r.SharedDef?(e.args[0].totalUses++,t=n.op(r.SharedRef,[e.args[0]])):(t=n.op(r.SharedRef,[e]),i=n.op(r.SharedDef,[e]),e.totalUses=2,e.currUses=0),l.push(i),t}return e}));return{precomp:l,flattened:u}}n.Procedure=class extends c{constructor(){super(...arguments),this.numArgs=0,this.info=null,this.seqNo=-1,this.isRoot=!1,this.locals=[],this.captured=[],this.args=[],this.parent=null,this.debugInfo=null,this.fillDebugInfo=null,this.classInfo=null,this.perfCounterName=null,this.perfCounterNo=0,this.body=[],this.lblNo=0,this.action=null,this.cachedJS=null,this.usingCtx=null}reset(){this.body=[],this.lblNo=0,this.locals=[],this.captured=[],this.args=[]}isGetter(){return this.action&&this.action.kind==e.SyntaxKind.GetAccessor}vtLabel(){return this.label()+(t.isStackMachine()?"":"_args")}label(){return t.getFunctionLabel(this.action)}toString(){return`\nPROC ${t.getDeclName(this.action)}\n${this.body.map((e=>e.toString())).join("")}\n`}emit(e){this.body.push(e)}emitExpr(e){this.emit(g(a.Expr,e))}mkLabel(e){let t=g(a.Label,null);return t.lblName="."+e+"_"+this.lblNo+++"_"+this.seqNo,t.lbl=t,t}emitLbl(e){this.emit(e)}emitLblDirect(e){let t=g(a.Label,null);t.lblName=e,t.lbl=t,this.emit(t)}getFullName(){let n=t.getDeclName(this.action);if(this.action){let t=e.pxtc.nodeLocationInfo(this.action);n=t.fileName.replace("pxt_modules/","")+"("+(t.line+1)+","+(t.column+1)+"): "+n}return n}getName(){return(this.action&&this.action.name?this.action.name.text:null)||"inline"}mkLocal(e,t){let n=new p(this.locals.length,e,t);return this.locals.push(n),n}mkLocalUnnamed(){let e=new f(this.locals.length,this);return this.locals.push(e),e}localIndex(e,t=!1){return this.captured.filter((t=>t.def==e))[0]||this.locals.filter((t=>t.def==e))[0]||(t?null:this.args.filter((t=>t.def==e))[0])}stackEmpty(){this.emit(g(a.StackEmpty,null))}emitJmpZ(e,t){this.emitJmp(e,t,o.IfZero)}emitJmp(e,t,n=o.Always,i=null){let s=g(a.Jmp,t);s.jmpMode=n,i&&i.exprKind==r.NumberLiteral&&(i=null),s.terminateExpr=i,"string"==typeof e?s.lblName=e:(s.lbl=e,s.lblName=s.lbl.lblName),this.emit(s)}inlineSelf(e){const{precomp:t,flattened:n}=b(e,!1,!0);i.assert(n.length==this.args.length),this.args.map(((e,t)=>{e.repl=n[t],e.replUses=0}));const a=m(this.inlineBody);return this.args.forEach(((e,t)=>{e.repl.exprKind==r.SharedRef&&(e.repl.args[0].prevTotalUses||(e.repl.args[0].prevTotalUses=e.repl.args[0].totalUses),e.repl.args[0].totalUses+=e.replUses-1),e.repl=null,e.replUses=0})),t.length?(t.push(a),h(r.Sequence,t)):a}resolve(){let e=(e,t)=>{if(e.args)for(let n=0;n<e.args.length;++n)e.args[n]=t(e.args[n])},a=t=>{switch(t.exprKind){case r.SharedDef:throw i.oops();case r.SharedRef:let e=t.args[0];if(e.totalUses)return e.totalUses--,t;{e.totalUses=-1,e.currUses=0,e.irCurrUses=0;let n=l.clone(t);return n.exprKind=r.SharedDef,n.args[0]=a(n.args[0]),n}}return e(t,a),t},o=t=>{if(t.exprKind==r.SharedRef)return t;switch(e(t,o),t.exprKind){case r.Sequence:t.args=t.args.filter(((e,n)=>n==t.args.length-1||!e.isPure()||(e.exprKind==r.SharedRef&&e.args[0].totalUses>0&&e.args[0].totalUses--,!1)))}return t},s=t=>{switch(t.exprKind){case r.SharedDef:let e=t.args[0];if(i.assert(e.totalUses<0,"arg.totalUses < 0"),i.assert(0===e.currUses,"arg.currUses === 0"),-1==e.totalUses)return s(e);e.totalUses=1;break;case r.SharedRef:return i.assert(t.args[0].totalUses>0,"e.args[0].totalUses > 0"),t.args[0].totalUses++,t;case r.PointerLiteral:const n=t.ptrlabel();n&&(n.lblNumUses||(n.lblNumUses=0),n.lblNumUses++)}return e(t,s),t},c=t=>{switch(t.exprKind){case r.SharedDef:e(t,c);case r.SharedRef:let n=t.args[0];return i.assert(n.totalUses>0,"arg.totalUses > 0"),1==n.totalUses?(i.assert(t.exprKind==r.SharedDef),n):(n.irCurrUses++,t);default:return e(t,c),t}};this.body=this.body.filter((e=>!e.expr||(e.expr=o(a(e.expr)),e.stmtKind!=n.SK.Expr||!e.expr.isPure())));let u=i.toDictionary(this.body.filter((e=>e.stmtKind==n.SK.Label)),(e=>e.lblName));for(let e=0;e<this.body.length;++e)this.body[e].stmtNo=e;for(let e of this.body)switch(e.expr&&(e.expr=s(e.expr)),e.stmtKind){case n.SK.Expr:break;case n.SK.Jmp:e.lbl=i.lookup(u,e.lblName),e.lbl||t.oops("missing label: "+e.lblName),e.lbl.lblNumUses?e.lbl.lblNumUses++:e.lbl.lblNumUses=1;break;case n.SK.StackEmpty:case n.SK.Label:case n.SK.Breakpoint:case n.SK.Comment:break;default:t.oops()}let d=[],p=null,f=!t.target.debugMode,m=null;for(let e of this.body)e.expr&&(e.expr=o(c(e.expr))),p&&p.lbl==e&&p.stmtKind==n.SK.Jmp&&e.stmtKind==n.SK.Label&&p.jmpMode==n.JmpMode.Always&&1==e.lblNumUses&&(e.lblNumUses=n.lblNumUsesJmpNext),p=e,e.stmtKind==n.SK.Breakpoint?d[e.breakpointInfo.id]=e.breakpointInfo:f&&(e.stmtKind==n.SK.Jmp?e.expr&&(m?f=!1:m=e.expr):e.stmtKind==n.SK.StackEmpty||(e.stmtKind==n.SK.Label?e.lblNumUses!=n.lblNumUsesJmpNext&&(f=!1):f=!1));if(f&&m){_(m)<=4*this.args.length+4+2+(t.target.isNative?4:30)&&(this.inlineBody=m)}pxt.options.debug&&pxt.debug(this.toString())}},n.iterExpr=function e(t,n){if(n(t),t.args)for(let r of t.args)e(r,n)},n.stmt=g,n.comment=function(e){return g(a.Comment,y(e,e))},n.op=h,n.numlit=function(e){return h(r.NumberLiteral,null,e)},n.shared=function(e){switch(e.exprKind){case r.SharedRef:e=e.args[0];break;case r.NumberLiteral:return e}return h(r.SharedRef,[e])},n.ptrlit=y,n.rtcall=v,n.rtcallMask=function(e,t,n,r){i.startsWith(e,"@nomask@")&&(e=e.slice(8),t=0);let a=v(e,r,t);return a.callingConvention=n,a},n.flattenArgs=b}(t.ir||(t.ir={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){class n{constructor(e,t){this.wave=e,this.id=t,this.flags=0,this.resetAll()}refresh(){this.flags&=-9,!this.proc||this.usedActions||N(this.proc.action)?this.proc&&!this.proc.cachedJS?this.resetEmit():this.usedNodes&&(this.flags|=32):this.resetEmit(),this.classInfo&&this.classInfo.reset()}resetEmit(){this.flags&=-41,this.proc&&this.proc.classInfo&&this.proc.classInfo.ctor==this.proc&&(this.proc.classInfo.ctor=null),this.functionInfo=null,this.variableInfo=null,this.classInfo=null,this.callInfo=null,this.proc=null,this.cell=null,this.exprInfo=null,this.usedNodes=null,this.usedActions=null}resetTSC(){this.flags&=16,this.typeCache=null,this.symbolCache=null,this.commentAttrs=null,this.valueOverride=null,this.declCache=void 0,this.fullName=null,this.constantFolded=void 0}resetAll(){this.resetTSC(),this.resetEmit()}}let r;function i(e){return e<<2|2}t.PxtNode=n,function(e){e[e.Enum=0]="Enum",e[e.Number=1]="Number",e[e.String=2]="String",e[e.Boolean=3]="Boolean",e[e.Unsupported=4]="Unsupported"}(r||(r={})),t.taggedUndefined=0,t.taggedNull=i(1),t.taggedFalse=i(2),t.taggedNaN=i(3),t.taggedTrue=i(16),t.thumbArithmeticInstr={adds:!0,subs:!0,muls:!0,ands:!0,orrs:!0,eors:!0,lsls:!0,asrs:!0,lsrs:!0},t.numberArithmeticInstr={div:!0,mod:!0,le:!0,lt:!0,ge:!0,gt:!0,eq:!0,neq:!0};const a={"Array_::getAt":{name:"_pxt_array_get",argsFmt:["T","T","T"],value:0},"Array_::setAt":{name:"_pxt_array_set",argsFmt:["T","T","T","T"],value:0},"BufferMethods::getByte":{name:"_pxt_buffer_get",argsFmt:["T","T","T"],value:0},"BufferMethods::setByte":{name:"_pxt_buffer_set",argsFmt:["T","T","T","I"],value:0},"pxtrt::mapGetGeneric":{name:"_pxt_map_get",argsFmt:["T","T","S"],value:0},"pxtrt::mapSetGeneric":{name:"_pxt_map_set",argsFmt:["T","T","S","T"],value:0}};let o=t.ir.EK;t.SK=e.SyntaxKind,t.numReservedGlobals=1;let s=0,c=1;function l(n){if(n.pxt)return!!(16&n.pxt.flags);const r=e.getSourceFileOfNode(n);return!!r&&t.isPxtModulesFilename(r.fileName)}function u(e){if(e.pxt){const n=e.pxt;return n.wave!=c&&(n.wave=c,t.compileOptions&&t.compileOptions.skipPxtModulesTSC&&16&n.flags?t.compileOptions.skipPxtModulesEmit?n.refresh():n.resetEmit():n.resetAll()),n}{const t=new n(c,++s);return l(e)&&(t.flags|=16),e.pxt=t,t}}function d(e){return u(e).id}function p(t){return t?e.SyntaxKind[t.kind]:"<null>"}function f(e,t,n=!1){let r=new Error(t);if(r.ksEmitterUserError=!0,r.ksErrorCode=e,n&&$)return M||(M=t,B=e),r;throw r}function _(){return t.target.isNative&&t.target.nativeType==t.NATIVE_TYPE_VM}function m(){return t.target.isNative&&t.target.nativeType!=t.NATIVE_TYPE_VM}function g(){return t.target.isNative&&t.target.nativeType==t.NATIVE_TYPE_THUMB}function h(e){return m()?t.ir.rtcall("pxt::fromInt",[e]):e}function y(e){return m()?t.ir.rtcall("pxt::fromBool",[e]):e}function v(e){switch(e){case 0:return t.target.shortPointers?2:4;case 1:return 1;case 3:return 2;case 5:return 4;case 2:return 1;case 4:return 2;case 6:return 4;default:throw t.oops()}}function b(e){switch(e){case 1:case 3:case 5:return!0;case 2:case 4:case 6:return!1;default:throw t.oops()}}function x(e){switch(e.kind){case t.SK.TemplateHead:case t.SK.TemplateMiddle:case t.SK.TemplateTail:case t.SK.StringLiteral:case t.SK.NoSubstitutionTemplateLiteral:return!0;default:return!1}}function k(e){return e&&e.modifiers&&e.modifiers.some((e=>e.kind==t.SK.StaticKeyword))}function S(e){return e.modifiers&&e.modifiers.some((e=>e.kind==t.SK.ReadonlyKeyword))}function T(e,t){return e.explicitDefaults?e.explicitDefaults.indexOf(t)<0?null:e.paramDefl[t]:null}function C(e){if(!e)return null;switch(e.kind){case t.SK.MethodDeclaration:return"";case t.SK.Constructor:return"new/";case t.SK.GetAccessor:return"get/";case t.SK.SetAccessor:return"set/";default:return null}}function E(e){return C(e)+q(e)}function D(e){return null!=C(e)}function A(e){return e?D(e)?e:A(e.parent):null}function N(e){let n=e,r=!1;for(;;)switch(n=n.parent,n||f(9229,U("cannot determine parent of {0}",p(e))),n.kind){case t.SK.MethodDeclaration:case t.SK.Constructor:case t.SK.GetAccessor:case t.SK.SetAccessor:case t.SK.FunctionDeclaration:case t.SK.ArrowFunction:case t.SK.FunctionExpression:return n;case t.SK.WhileStatement:case t.SK.DoStatement:case t.SK.ForInStatement:case t.SK.ForOfStatement:case t.SK.ForStatement:r=!0;break;case t.SK.SourceFile:return r?R:null}}function w(e){return"objectFlags"in e}function I(e){return!!e&&(e.kind==t.SK.VariableDeclaration||e.kind==t.SK.BindingElement&&I(e.parent.parent))}function P(e){return!!e&&(I(e)&&!N(e)||e.kind==t.SK.PropertyDeclaration&&k(e))}function O(e){return!!e&&(e.kind==t.SK.Parameter||e.kind==t.SK.BindingElement&&O(e.parent.parent))}t.isInPxtModules=l,t.pxtInfo=u,t.getNodeId=d,t.stringKind=p,t.isStackMachine=_,t.needsNumberConversions=m,t.isThumb=g,t.sizeOfBitSize=v,t.isBitSizeSigned=b,t.setCellProps=function(n){var r;if(n._isLocal=I(r=n.def)&&!P(r)||O(n.def),n._isGlobal=P(n.def),!n.def.isThisParameter){let r=ee(n.def);r.flags&e.TypeFlags.Void&&t.oops("void-typed variable, "+n.toString()),n.bitSize=function(e){if(!e||!e.type)return 0;if(!de(ee(e)))return 0;if(e.type.kind!=t.SK.TypeReference)return 0;switch(e.type.typeName.getText()){case"int8":return 1;case"int16":return 3;case"int32":return 5;case"uint8":return 2;case"uint16":return 4;case"uint32":return 6;default:return 0}}(n.def),0!=n.bitSize?n._debugType=(b(n.bitSize)?"int":"uint")+8*v(n.bitSize):ue(r)?n._debugType="string":r.flags&e.TypeFlags.NumberLike&&(n._debugType="number")}n.isLocal()&&0!=n.bitSize&&(n.bitSize=0,f(9256,U("bit sizes are not supported for locals and parameters")))},t.isStatic=k,t.isReadOnly=S,t.getExplicitDefault=T,t.isObjectType=w;class F{constructor(e,t){this.id=e,this.decl=t,this.baseClassInfo=null,this.allfields=[],this.methods={},this.attrs=J(t),this.reset()}reset(){this.vtable=null,this.itable=null}get isUsed(){return!!(8&u(this.decl).flags)}allMethods(){const e=[];for(let t of Object.keys(this.methods))for(let n of this.methods[t])e.push(n);return e}usedMethods(){const e=[];for(let t of Object.keys(this.methods))for(let n of this.methods[t]){8&u(n).flags&&e.push(n)}return e}}t.ClassInfo=F;let L,R,M,U=t.assembler.lf,B=0,$=0;function j(e,n){const r=u(n);return null==r.fullName&&(r.fullName=t.getFullName(e,n.symbol)),r.fullName}function K(n){n.kind==t.SK.VariableDeclaration&&(n=n.parent.parent);let r=t=>{const n=e.getSourceFileOfNode(t);if(!n)return"";const r=e.getLeadingCommentRangesOfNode(t,n);if(!r)return"";return r.map((e=>n.text.slice(e.pos,e.end))).join("\n")};return n.symbol&&n.symbol.declarations&&n.symbol.declarations.length>1?n.symbol.declarations.map(r).join("\n"):r(n)}function z(e){let n="";for(let t of e.declarations)n+=K(t);return t.parseCommentString(n)}function J(e){const n=e?u(e):null;if(!n||2&n.flags)return t.parseCommentString("");if(n.commentAttrs)return n.commentAttrs;let r=t.parseCommentString(K(e));return r._name=q(e),n.commentAttrs=r,r}function q(e){return e.name&&e.name.kind==t.SK.Identifier?e.name.text:"???"}function V(t){if(w(t)&&t.objectFlags&e.ObjectFlags.Reference){let e=t;if(e.typeArguments&&e.typeArguments.length)return e.target}return null}function H(t){return!!w(t)&&(t.objectFlags&e.ObjectFlags.Reference&&t.symbol&&"Array"==t.symbol.name)}function G(t){return!!w(t)&&(!!(t.objectFlags&e.ObjectFlags.Interface)||!!(t.objectFlags&e.ObjectFlags.Anonymous))}function W(t){return!!t.isThisType||!!w(t)&&!!(t.objectFlags&e.ObjectFlags.Class||t.symbol&&t.symbol.flags&e.SymbolFlags.Class)}function Q(e){let t=V(e);return W(t||e)}function Y(t,n=-1){return H(t)?t.typeArguments[0]:L.getIndexTypeOfType(t,e.IndexKind.Number)}function X(e){return e}function Z(e){return null===e?t.taggedNull:void 0===e?t.taggedUndefined:!1===e?t.taggedFalse:!0===e?t.taggedTrue:isNaN(e)?t.taggedNaN:null}function ee(t){let n;const r=u(t);if(r.typeCache)return r.typeCache;if(e.isExpression(t)&&(n=L.getContextualType(t)),!n)try{n=L.getTypeAtLocation(t)}catch(e){f(9203,U("Unknown type for expression"))}return n?(r.typeCache=n,n):n}function te(t){if(!(t.flags&e.TypeFlags.Union))return r.Unsupported;let n,i=!0;return t.types.forEach((t=>{if(void 0===n)t.flags&e.TypeFlags.NumberLike?n=r.Number:t.flags&e.TypeFlags.BooleanLike?n=r.Boolean:t.flags&e.TypeFlags.StringLike?n=r.String:t.flags&e.TypeFlags.EnumLike&&(n=r.Enum);else switch(n){case r.Number:i=i&&!!(t.flags&e.TypeFlags.NumberLike);break;case r.Boolean:i=i&&!!(t.flags&e.TypeFlags.BooleanLike);break;case r.String:i=i&&!!(t.flags&e.TypeFlags.StringLike);break;case r.Enum:i=i&&!!(t.flags&e.TypeFlags.EnumLike)}})),i?n:r.Unsupported}function ne(t){let n=L.getSignatureFromDeclaration(t);return!(L.getReturnTypeOfSignature(n).flags&e.TypeFlags.Void)}function re(e){return!(!e||!e.name)}function ie(e){if(!e)return"";switch(e.kind){case t.SK.ModuleBlock:return ie(e.parent);case t.SK.ClassDeclaration:case t.SK.ModuleDeclaration:return ie(e.parent)+e.name.text+".";default:return""}}function ae(e){let n=re(e)?e.name.text:null;if(!n){if(e.kind!=t.SK.Constructor){for(let t=e.parent;t;t=t.parent)if(re(t))return ae(t)+".inline";return"inline"}n="constructor"}return ie(e.parent)+n}function oe(e){return ae(e).replace(/[^\w]+/g,"_")}function se(e){return oe(e)+"__P"+d(e)}t.getNodeFullName=j,t.getComments=K,t.parseCommentsOnSymbol=z,t.parseComments=J,t.getName=q,t.checkType=X,t.taggedSpecial=Z,t.getDeclName=ae,t.getFunctionLabel=se;class ce{constructor(e){this.decl=e,this.capturedVars=[]}get isUsed(){return!!(8&u(this.decl).flags)}}function le(e,t,n){return!!(e.flags&t)||te(e)===n}function ue(t){return le(t,e.TypeFlags.String|e.TypeFlags.StringLiteral,r.String)}function de(t){return le(t,e.TypeFlags.Number|e.TypeFlags.NumberLiteral,r.Number)}t.FunctionAddInfo=ce,t.compileBinary=function(n,r,i,s){t.compilerHooks.preBinary&&t.compilerHooks.preBinary(n,r,i),t.target=r.target,t.compileOptions=r,t.target.debugMode=!!r.breakpoints;const b=e.createDiagnosticCollection();L=n.getTypeChecker();let C=t.U.cpuUs(),w=[],K=[],V={},X={},te=null,re=null,ie=!1,le=[];if(c++,r.target.isNative){if(!r.extinfo||!r.extinfo.hexinfo)return{diagnostics:[{file:n.getSourceFiles()[0],start:0,length:0,category:t.DiagnosticCategory.Error,code:9043,messageText:U("The hex file is not available, please connect to internet and try again.")}],emittedFiles:[],emitSkipped:!0};let e=r.extinfo,i=r.target;if(e&&e.disabledDeps){const t=(r.otherMultiVariants||[]).find((e=>e.extinfo&&!e.extinfo.disabledDeps));t&&(pxt.debug(`using alternative extinfo (due to ${e.disabledDeps})`),e=t.extinfo,i=t.target)}t.hexfile.setupFor(i,e||t.emptyExtInfo()),t.hexfile.setupInlineAssembly(r)}let me,ge=new pe;function he(){ge.reset(),me=null,i.breakpoints=[{id:0,isDebuggerStmt:!1,fileName:"bogus",start:0,length:0,line:0,column:0}],i.procCallLocations=[]}ge.res=i,ge.options=r,ge.target=r.target,r.computeUsedSymbols&&(i.usedSymbols={},i.usedArguments={});let ye=[];if(!r.forceEmit||0==i.diagnostics.length){let e=n.getSourceFiles().slice();const t=e.find((e=>e.fileName===pxt.MAIN_TS));t&&(e=e.filter((e=>e.fileName!==pxt.MAIN_TS)),e.push(t));const r=e.find((e=>e.fileName===pxt.TUTORIAL_CODE_STOP));r&&(e=e.filter((e=>e.fileName!==pxt.TUTORIAL_CODE_STOP)),e.push(r)),e.forEach((e=>{e.statements.forEach((e=>{ye.push(e)}))}))}let ve=n.getSourceFiles().filter((e=>t.Util.endsWith(e.fileName,s)))[0],be={kind:t.SK.FunctionDeclaration,parameters:[],name:{text:"<main>",pos:0,end:0},body:{kind:t.SK.Block,statements:ye},parent:ve,pos:0,end:0};R=be;const xe=u(be);for(xe.flags|=3,rt(be),w=[],he(),ie=!0,xn(be);kt(),!Ue(););!function(){let e=ge.globals.slice(0);e.forEach(((e,t)=>e.index=t));const n=e=>0==e?10:v(e);e.sort(((e,t)=>n(e.bitSize)-n(t.bitSize)||e.index-t.index));let r=4*t.numReservedGlobals,i=0;for(let t of e){const e=_()?0:t.bitSize;let n=v(e);for(;r&n-1;)r++;i||0!=e||(i=r),t.index=r,r+=n}ge.globalsWords=r+3>>2,ge.nonPtrGlobals=i?i>>2:ge.globalsWords}(),ie=!1,function(){for(let e of ge.usedClassInfos)Be(e);let e=Object.keys(ge.ifaceMemberMap);e.sort(t.U.strcmp),e.unshift(""),ge.emitString(""),ge.ifaceMembers=e,ge.ifaceMemberMap={};let n=0;for(let t of e)ge.ifaceMemberMap[t]=n++;for(let e of ge.usedClassInfos)for(let t of e.itable)t.idx=Oe(t.name);for(let e of ge.usedClassInfos)e.lastSubtypeNo=void 0,e.classNo=void 0;let r=pxt.BuiltInType.User0;const i=e=>{t.U.assert(!e.classNo),e.classNo=r++;for(let t of e.derivedClasses)t.isUsed&&i(t);e.lastSubtypeNo=r-1};for(let e of ge.usedClassInfos){let t=e;for(;t.baseClassInfo;)t=t.baseClassInfo;t.classNo||i(t)}}();let ke=t.U.cpuUs();i.times.pass0=ke-C;let Se=b.getDiagnostics();he(),ie=!1,ge.finalPass=!0,kn(be),t.U.assert(0==w.length),i.configData=[];for(let e of Object.keys(X))X["!"+e]||i.configData.push({name:e.replace(/^\!/,""),key:X[e].key,value:X[e].value});i.configData.sort(((e,t)=>e.key-t.key));let Te=t.U.cpuUs();if(i.times.pass1=Te-ke,yn(be,(function(){if(r.noEmit)return;ge.writeFile=(e,t)=>{i.outfiles[e]=t};for(let e of ge.procs)e.cachedJS&&!e.inlineBody||e.resolve();t.target.isNative&&(ge.procs=ge.procs.filter((e=>!(e.inlineBody&&!e.info.usedAsIface&&!e.info.usedAsValue))));r.target.isNative?(r.extinfo.yotta&&ge.writeFile("yotta.json",JSON.stringify(r.extinfo.yotta,null,2)),r.extinfo.platformio&&ge.writeFile("platformio.json",JSON.stringify(r.extinfo.platformio,null,2)),r.target.nativeType==t.NATIVE_TYPE_VM?t.vmEmit(ge,r):t.processorEmit(ge,r,i)):t.jsEmit(ge)})),i.times.passFinal=t.U.cpuUs()-Te,r.ast){let e=t.U.cpuUs();t.annotate(n,s,t.target),i.times.passAnnotate=t.U.cpuUs()-e}return t.compileOptions=null,0==Se.length&&(Se=b.getDiagnostics()),t.compilerHooks.postBinary&&t.compilerHooks.postBinary(n,r,i),{diagnostics:Se,emittedFiles:void 0,emitSkipped:!!r.noEmit};function Ce(t,n,r,i,a,o,s){b.add(e.createDiagnosticForNode(n,{code:r,message:i,key:i.replace(/^[a-zA-Z]+/g,"_"),category:t},a,o,s))}function Ee(e,n,r,i,a,o){Ce(t.DiagnosticCategory.Error,e,n,r,i,a,o)}function De(t,n,r=9202){if(n)return f(r,n);t||f(r,U("Sorry, this language feature is not supported"));let i=p(t),a=!1,o=null;switch(t.kind){case e.SyntaxKind.ForInStatement:i=U("for in loops");break;case e.SyntaxKind.ForOfStatement:i=U("for of loops"),a=!0;break;case e.SyntaxKind.PropertyAccessExpression:i=U("property access");break;case e.SyntaxKind.DeleteExpression:i=U("delete");break;case e.SyntaxKind.GetAccessor:i=U("get accessor method"),a=!0;break;case e.SyntaxKind.SetAccessor:i=U("set accessor method"),a=!0;break;case e.SyntaxKind.TaggedTemplateExpression:i=U("tagged templates");break;case e.SyntaxKind.SpreadElement:i=U("spread");break;case e.SyntaxKind.TryStatement:case e.SyntaxKind.CatchClause:case e.SyntaxKind.FinallyKeyword:case e.SyntaxKind.ThrowStatement:i=U("throwing and catching exceptions");break;case e.SyntaxKind.ClassExpression:i=U("class expressions"),o=U("declare a class as class C {} not let C = class {}")}let s="";return s=a?U("{0} not currently supported",i):U("{0} not supported",e.SyntaxKind[t.kind]),o&&(s+=" - "+o),f(r,s)}function Ae(e){return d(e)+""}function Ne(e){const t=u(e);return t.functionInfo||(t.functionInfo=new ce(e)),t.functionInfo}function we(e){const t=u(e);return t.variableInfo||(t.variableInfo={}),t.variableInfo}function Ie(e,t=!1){let n=we(e);t&&(n.written=!0);let r=N(e);if(null==r||r==me.action);else{let t=me.action;for(;t&&t!=r;){let n=Ne(t);n.capturedVars.indexOf(e)<0&&n.capturedVars.push(e),t=N(t)}n.captured=!0}}function Pe(e){const t=e(ge);return ie&&ge.recordAction(re,e),t}function Oe(e,n=!1){return Pe((r=>{n&&(t.U.lookup(r.explicitlyUsedIfaceMembers,e)||(t.U.assert(!r.finalPass),r.explicitlyUsedIfaceMembers[e]=!0));let i=t.U.lookup(r.ifaceMemberMap,e);return null!=i||(t.U.assert(!r.finalPass),i=r.ifaceMemberMap[e]=-1,r.emitString(e)),i}))}function Fe(t){t.flags&e.TypeFlags.Void&&f(9203,U("void-typed variables not supported"))}function Le(e){const n=u(e);Fe(ee(e)),n.cell||(n.cell=new t.ir.Cell(null,e,we(e))),ge.globals.indexOf(n.cell)<0&&ge.globals.push(n.cell)}function Re(e){if(P(e)){rt(e);const t=u(e);return t.cell||Le(e),t.cell}{let t=me.localIndex(e);return t||(ge.finalPass?f(9204,U("cannot locate identifer")):t=me.mkLocal(e,we(e))),t}}function Me(e){return e.kind==t.SK.MethodDeclaration&&0==e.parameters.length&&"toString"==q(e)}function Ue(){ie=!1;const e=ge.usedClassInfos.length;for(let e of ge.usedClassInfos){for(let r of e.allMethods()){const e=u(r),i=Ne(r);8&e.flags?i.virtualParent&&it(i.virtualParent.decl):(i.virtualParent&&i.virtualParent.isUsed||Me(r)||(n=q(r),null!=t.U.lookup(ge.explicitlyUsedIfaceMembers,n)))&&it(r)}const r=ht(e.decl);r&&it(r)}var n;return ie=!0,0==w.length&&e==ge.usedClassInfos.length}function Be(e){if(t.assert(e.isUsed,"inf.isUsed"),e.vtable)return e.vtable;let n=e.baseClassInfo?Be(e.baseClassInfo).slice(0):[];e.derivedClasses=[],e.baseClassInfo&&e.baseClassInfo.derivedClasses.push(e);for(let r of e.usedMethods()){ge.numMethods++;let i=Ne(r);const a=J(r);if(Me(r)&&!a.shim&&(e.toStringMethod=mt(r),e.toStringMethod.info.usedAsIface=!0),i.virtualParent){ge.numVirtMethods++;let e=E(r),a=!1,o=mt(r);t.U.assert(!!o);for(let t=0;t<n.length;++t)E(n[t].action)==e&&(n[t]=o,i.virtualIndex=t,a=!0);a||(i.virtualIndex=n.length,n.push(o))}}e.vtable=n,e.itable=[];const r={};for(let t of e.allfields){let n=q(t),i=Lt(e,t,!1);r[n]=!0,e.itable.push({name:n,info:(i.idx+1)*(_()?1:4),idx:Oe(n),proc:null})}for(let n=e;n;n=n.baseClassInfo)for(let r of n.usedMethods()){const n=q(r);if(J(r).shim)continue;const i=mt(r),a=e.itable.find((e=>e.name==n)),o=r.kind==t.SK.SetAccessor,s=r.kind==t.SK.GetAccessor;a?(o&&!a.setProc?a.setProc=i:s&&!a.proc&&(a.proc=i),a.info=0):e.itable.push({name:n,info:0,idx:Oe(n),proc:o?null:i,setProc:o?i:null}),i.info.usedAsIface=!0}return e.vtable}function $e(e){if(32&e.flags||16&e.flags&&t.compileOptions.skipPxtModulesEmit)throw i.needsFullRecompile=!0,f(9200,U("full recompile required"))}function je(e,n=null){n||(n=e.symbol.valueDeclaration);const r=u(n);if(!r.classInfo){const e=oe(n)+"__C"+d(n),i=new F(e,n);r.classInfo=i,i.attrs.autoCreate&&(V[i.attrs.autoCreate]=!0),i.baseClassInfo=function(e){if(e.heritageClauses)for(let n of e.heritageClauses)switch(n.token){case t.SK.ExtendsKeyword:if(!n.types||1!=n.types.length)throw f(9228,U("invalid extends clause"));let r=ee(n.types[0]);if(r&&W(r))return L.getTypeAtLocation(e),je(r);throw f(9228,U("cannot inherit from this type"));case t.SK.ImplementsKeyword:break;default:throw f(9228,U("invalid heritage clause"))}return null}(n);const a=i.baseClassInfo?t.U.toDictionary(i.baseClassInfo.allfields,(e=>q(e))):{},o=(e,t=i.baseClassInfo)=>t?t.methods[e]||o(e,t.baseClassInfo):null;for(let e of n.members)if(e.kind==t.SK.PropertyDeclaration){let n=e;k(n)||i.allfields.push(n);const r=q(n);(o(r)||t.U.lookup(a,r))&&Ee(n,9279,U("redefinition of '{0}' as field",r))}else if(e.kind==t.SK.Constructor)for(let t of e.parameters)fe(t)&&i.allfields.push(t);else if(D(e)){let n=Ne(e);n.parentClassInfo=i,n.isUsed&&yt(i);const r=q(e);i.methods.hasOwnProperty(r)||(i.methods[r]=[]),i.methods[r].push(e);const o=t.U.lookup(a,r);if(o){const e=u(o);64&e.flags||(e.flags|=64,8&e.flags&&Oe(r,!0),$e(e))}}i.baseClassInfo&&(i.allfields=i.baseClassInfo.allfields.concat(i.allfields),function(e){for(let n of e.allMethods()){let r=null;const i=E(n),a=q(n);for(let t=e.baseClassInfo;t;t=t.baseClassInfo)if(t.methods.hasOwnProperty(a))for(let e of t.methods[a])E(e)==i&&(r=e);if(r){let e=Ne(n),i=Ne(r);r.parameters.length!=n.parameters.length&&Ee(n,9255,U("the overriding method is currently required to have the same number of arguments as the base one")),e.virtualParent=i,i.virtualParent||($e(u(r)),i.virtualParent=i),t.assert(i.virtualParent==i,"pinf.virtualParent == pinf")}}}(i))}return r.classInfo}function Ke(e){if(!e)return!1;if(x(e))return!1;switch(e.kind){case t.SK.ArrayLiteralExpression:return e.elements.some(Ke);default:return null==zt(e)}}function ze(e){const t=Kt(e);if(t)return Wt(t.val);if(P(e)){if(J(e).shim)return ut(e,e,[])}let n=Re(e);return Ie(e),n.load()}function Je(e){J(e).shim&&f(9207,U("built-in functions cannot be yet used as values; did you forget ()?"));let n=Ne(e);return qe(n),n.location?n.location.load():(t.assert(!ge.finalPass||0==n.capturedVars.length,"!bin.finalPass || info.capturedVars.length == 0"),n.usedAsValue=!0,it(e),xt(e))}function qe(e){void 0===e.usedBeforeDecl?e.usedBeforeDecl=!0:ge.finalPass&&e.usedBeforeDecl&&e.capturedVars.length&&N(e.decl)&&!e.alreadyEmitted&&f(9278,U("function referenced before all variables it uses are defined"))}function Ve(e){const n=st(e),r=Kt(n);if(r)return Wt(r.val);if(n&&(I(n)||O(n)))return ze(n);if(n&&n.kind==t.SK.FunctionDeclaration)return Je(n);if("undefined"==e.text)return Wt(void 0);throw De(e,U("Unknown or undeclared identifier"),9235)}function He(e){let n=A(e);n||f(9208,U("'this' used outside of a method"));let r=Ne(n);return r.thisParameter||t.oops("no this"),ze(r.thisParameter)}function Ge(e){let n;if(""==e)n=t.ir.rtcall("String_::mkEmpty",[]);else{let r=function(e){return Pe((t=>t.emitString(e)))}(e);n=t.ir.ptrlit(r,JSON.stringify(e))}return n.isStringLiteral=!0,n}function We(e){let n=ct(e),r=vn(e);return t.target.isNative||x(e)?Ot(r,n):(r=t.ir.rtcallMask("String_::stringConv",1,1,[r]),Ot(r,!0))}function Qe(e){let n=0,r=(e,t)=>function(e){return x(e)&&""==e.text}(t)?e:(n++,Xt("String_::concat",[Ot(e,!0),We(t)],null)),i=u(We(e.head)).valueOverride;for(let t of e.templateSpans)i=r(i,t.expression),i=r(i,t.literal);return 0==n?Xt("String_::concat",[Ot(i,!0),Ot(t.ir.rtcall("String_::mkEmpty",[]),!1)],null):i}function Ye(e){let n=st(e);const r=Kt(n);if(r)return Wt(r.val);if(n.kind==t.SK.SetAccessor&&(n=Xe(n)),n.kind==t.SK.GetAccessor)return pt(e,e,[],null,n);if(n.kind==t.SK.EnumMember)throw f(9210,U("Cannot compute enum value"));if(n.kind==t.SK.PropertySignature||n.kind==t.SK.PropertyAssignment)return pt(e,e,[],null,n,e.expression);if(n.kind==t.SK.PropertyDeclaration||n.kind==t.SK.Parameter){if(k(n))return ze(n);if(Ze(n))return pt(e,e,[],null,n,e.expression);{let n=function(e){const n=ee(e.expression);if(Q(n)){const r=je(n);let i=e.expression.kind==t.SK.ThisKeyword;return t.target.switches.noThisCheckOpt&&(i=!1),Lt(r,Rt(r,e.name.text),!i)}throw De(e,U("bad field access"),9247)}(e);return t.ir.op(o.FieldAccess,[vn(e.expression)],n)}}if(D(n)||n.kind==t.SK.MethodSignature)throw f(9211,U("cannot use method as lambda; did you forget '()' ?"));if(n.kind==t.SK.FunctionDeclaration)return Je(n);if(I(n))return ze(n);throw De(e,U("Unknown property access for {0}",p(n)),9237)}function Xe(n){const r=e.getDeclarationOfKind(n.symbol,t.SK.GetAccessor);if(null==r)throw f(9281,U("setter currently requires a corresponding getter"));return r}function Ze(e){if(e.kind==t.SK.Parameter||e.kind==t.SK.PropertyDeclaration){const n=u(e);return!!t.target.switches.slowFields||!!(64&n.flags)}return!1}function et(t,n=null){let r=ee(t.expression),i={callingConvention:0,paramDefl:{}},a=null,o=!1;if(!n&&ue(r)?a="String_::charAt":H(r)?a=n?"Array_::setAt":"Array_::getAt":G(r)&&(i=z(r.symbol),a=n?i.indexerSet:i.indexerGet),!a&&r.flags&(e.TypeFlags.Any|e.TypeFlags.StructuredOrTypeVariable)&&(a=n?"pxtrt::mapSetGeneric":"pxtrt::mapGetGeneric",o=!0),a){if(o||Qt(t.argumentExpression)){return Xt(a,[t.expression,t.argumentExpression],i,n?[n]:[])}throw De(t,U("non-numeric indexer on {0}",a),9238)}throw De(t,U("unsupported indexer"),9239)}function tt(n){let i=function(e){return!!P(e)&&(!Ke(e.initializer)||!!J(e).whenUsed)}(n)||function(e){return e.kind==t.SK.FunctionDeclaration&&!N(e)||D(e)}(n)||e.isClassDeclaration(n);return!t.target.switches.noTreeShake&&(!(r.testMode&&i&&!l(n))&&i)}function nt(e){if(!tt(e))return!0;const t=u(e);return ge.finalPass?!!(8&t.flags):t==re}function rt(e){if(!e)return;const t=u(e);t.classInfo?yt(t.classInfo):(r.computeUsedSymbols&&e.symbol&&(i.usedSymbols[j(L,e)]=null),_()&&D(e)&&Oe(q(e),!0),at(e),8&t.flags||(t.flags|=8,tt(e)&&w.push(e)))}function it(e){rt(e)}function at(e){ie&&(re?re.usedNodes[Ae(e)]=e:t.U.oops("no using ctx for: "+q(e)))}function ot(t){if(!t)return null;const n=u(t);if(void 0!==n.declCache)return n.declCache;let r,i=L.getSymbolAtLocation(t);if(i&&(r=i.valueDeclaration,!r&&i.declarations)){let t=i.declarations[0];t&&t.kind==e.SyntaxKind.ImportEqualsDeclaration&&(i=L.getSymbolAtLocation(t.moduleReference),i&&(r=i.valueDeclaration))}return r}function st(e){let n=ot(e);if(rt(n),!n&&e&&e.kind==t.SK.PropertyAccessExpression){const r=e;n={kind:t.SK.PropertySignature,symbol:{isBogusSymbol:!0,name:r.name.getText()},name:r.name},u(n).flags|=2}return xe.declCache=n||null,n}function ct(e){return e.kind==t.SK.NullKeyword||e.kind==t.SK.NumericLiteral?!!e.isRefOverride:!x(e)}function lt(e){t.assert(e.length<=8,"args.length <= 8");let n=0;return e.forEach(((e,t)=>{ct(e)&&(n|=1<<t)})),n}function ut(n,i,a){let o=J(n),s=!(ee(i).flags&e.TypeFlags.Void),c=o.shim;if(c.indexOf("(")>=0){let e=/(.*)\((.*)\)$/.exec(c);if(e){a.length&&t.U.userError("no arguments expected");let s=[];if(e[2].replace(/\s/g,"")){for(let n of e[2].split(/,/)){let e=parseInt(n);isNaN(e)&&(e=Ht(i,n),null==e&&(e=qt(i,n)),null==e&&t.U.userError("invalid argument: "+n+" in "+c)),s.push(t.ir.numlit(e))}s.length>4&&t.U.userError("too many args")}return c=e[1],r.target.isNative&&t.hexfile.validateShim(ae(n),c,o,!0,s.map((e=>!0))),t.ir.rtcallMask(c,0,o.callingConvention,s)}}return"TD_NOOP"==c?(t.assert(!s,"!hasRet"),t.target.switches.profile&&"perfCounter"==o.shimArgument&&(a[0]&&a[0].kind==t.SK.StringLiteral&&(me.perfCounterName=a[0].text),me.perfCounterName||(me.perfCounterName=me.getFullName())),Wt(void 0)):"TD_ID"==c||"ENUM_GET"===c?(t.assert(1==a.length,"args.length == 1"),vn(a[0])):(r.target.shimRenames&&t.U.lookup(r.target.shimRenames,c)&&(c=r.target.shimRenames[c]),r.target.isNative&&t.hexfile.validateShim(ae(n),c,o,s,a.map(Qt)),Xt(c,a,o))}function dt(e,n,r){if(!e)return;let i=e.getParameters(),a=n.length;i.length>n.length&&i.slice(n.length).forEach((e=>{if(e.valueDeclaration&&e.valueDeclaration.kind==t.SK.Parameter){let i=e.valueDeclaration;if(i.initializer)(function(e){switch(e.kind){case t.SK.UndefinedKeyword:case t.SK.NullKeyword:case t.SK.TrueKeyword:case t.SK.FalseKeyword:case t.SK.NumericLiteral:return!0;case t.SK.PropertyAccessExpression:return vn(e).exprKind==o.NumberLiteral;default:return!1}})(i.initializer)||f(9212,U("only numbers, null, true and false supported as default arguments")),n.push(i.initializer);else{let e=T(r,q(i)),t=e?Wt(parseInt(e)):null;null==t&&(t=Wt(void 0)),n.push(Ot(t))}}else f(9213,U("unsupported default argument (shouldn't happen)"))}));for(let e=0;e<a;e++){let r=i[e];r&&r.valueDeclaration&&r.valueDeclaration.kind==t.SK.Parameter&&(n[e],r.valueDeclaration)}r.imageLiteral&&(x(n[0])||f(9214,U("Only image literals (string literals) supported here; {0}",p(n[0]))),n[0]=function(e){e||(e="0 0 0 0 0\n0 0 0 0 0\n0 0 0 0 0\n0 0 0 0 0\n0 0 0 0 0\n");let n=0,r=0,i=0,a="",o=0;e+="\n";for(let t=0;t<e.length;++t)switch(e[t]){case".":case"_":case"0":a+="0,",n++,o++;break;case"#":case"*":case"1":a+="255,",n++,o++;break;case"\t":case"\r":case" ":break;case"\n":n&&(0==r?r=n:n!=r&&f(9205,U("lines in image literal have to have the same width (got {0} and then {1} pixels)",r,n)),n=0,i++);break;default:f(9206,U("Only 0 . _ (off) and 1 # * (on) are allowed in image literals"))}let s="_img"+ge.lblNo++;o%2!=0&&(a+="0"),ge.otherLiterals.push(`\n.balign 4\n${s}: .short 0xffff\n .short ${r}, ${i}\n .byte ${a}\n`);let c="new pxsim.Image("+r+", ["+a+"])";return{kind:t.SK.NumericLiteral,imageLiteral:s,jsLit:c}}(n[0].text))}function pt(n,r,a,o,s=null,c=null){var l;s||(s=st(r));let u=!1,d=!1,p=!1;const m=n===r;if(s)switch(s.kind){case t.SK.PropertySignature:case t.SK.PropertyAssignment:case t.SK.PropertyDeclaration:case t.SK.MethodSignature:u=!0;break;case t.SK.Parameter:fe(s)&&(u=!0);break;case t.SK.GetAccessor:case t.SK.SetAccessor:case t.SK.MethodDeclaration:u=!0,d=!0,p=k(s);break;case t.SK.FunctionDeclaration:p=!0;break;case t.SK.ModuleDeclaration:break;default:s=null}else r.kind==t.SK.PropertyAccessExpression&&(u=!0);t.target.switches.slowMethods&&(d=!1);const g=J(s);let h=a.slice(0);if(u&&k(s)&&(u=!1),u&&!c&&r.kind==t.SK.PropertyAccessExpression&&(c=r.expression),i.usedArguments&&g.trackArgs){let e=c?[c].concat(h):h,n=g.trackArgs.map((t=>e[t])).map((e=>{let n=st(e);return!n||n.kind!=t.SK.EnumMember&&n.kind!=t.SK.VariableDeclaration?e&&e.kind==t.SK.StringLiteral?e.text:"*":j(L,n)})).join(","),r=j(L,s),a=i.usedArguments[r];a||(a=i.usedArguments[r]=[]),a.indexOf(n)<0&&a.push(n)}function y(){let e=gt(s,n,h.map((e=>vn(e)))),r=e.data;return h[0]&&r.proc&&r.proc.classInfo&&(r.isThis=h[0].kind==t.SK.ThisKeyword),e}if(dt(o,h,g),p){if(!Ne(s).location)return g.shim&&!At(s)?ut(s,n,h):(it(s),y())}if(r.kind==t.SK.SuperKeyword){let e=me.classInfo.baseClassInfo.ctor;for(let t=me.classInfo.baseClassInfo;t&&!e;t=t.baseClassInfo)e=t.ctor;if(!e&&ge.finalPass)throw f(9280,U("super() call requires an explicit constructor in base class"));let t=h.map((e=>vn(e)));return t.unshift(He(r)),ft(e,n,t)}if(u){if(t.U.assert(!k(s)),c?h.unshift(c):De(n,U("strange method call"),9241),!s){t.U.assert(r.kind==t.SK.PropertyAccessExpression);const e=r.name.text;return _t(h.map((e=>vn(e))),{ifaceIndex:Oe(e,!0),callLocationIndex:Tn(n),noArgs:m})}let i=Ne(s);if(i.parentClassInfo&&yt(i.parentClassInfo),it(s),c.kind==t.SK.SuperKeyword)return y();const a=!!i.virtualParent,o=!!_()||!!t.target.switches.slowMethods;if(a&&!o)return s.kind==t.SK.MethodDeclaration?t.U.assert(!m):s.kind==t.SK.GetAccessor||s.kind==t.SK.SetAccessor?t.U.assert(m):t.U.assert(!1),t.U.assert(!ge.finalPass||null!=i.virtualIndex,"!bin.finalPass || info.virtualIndex != null"),_t(h.map((e=>vn(e))),{classInfo:i.parentClassInfo,virtualIndex:i.virtualIndex,noArgs:m,isThis:h[0].kind==t.SK.ThisKeyword});if(g.shim&&!At(s))return ut(s,n,h);if(g.helper){let r,i=L.getSymbolsInScope(n,e.SymbolFlags.Module);for(let e of i)if("helpers"==e.name)for(let n of e.declarations||[e.valueDeclaration])if(n.kind==t.SK.ModuleDeclaration)for(let e of n.body.statements)(null===(l=e.symbol)||void 0===l?void 0:l.name)==g.helper&&(r=e);return r||f(9215,U("helpers.{0} not found",g.helper)),r.kind!=t.SK.FunctionDeclaration&&f(9216,U("helpers.{0} isn't a function",g.helper)),it(s=r),y()}return a||t.target.switches.slowMethods||!d?_t(h.map((e=>vn(e))),{ifaceIndex:Oe(q(s),!0),isSet:m&&2==h.length,callLocationIndex:Tn(n),noArgs:m}):(t.U.assert(s.kind!=t.SK.MethodSignature),y())}return s&&s.kind==t.SK.ModuleDeclaration&&("String"==q(s)?f(9219,U('to convert X to string use: X + ""')):f(9220,U("namespaces cannot be called directly"))),h.unshift(r),t.U.assert(!m),_t(h.map((e=>vn(e))),{virtualIndex:-1,callLocationIndex:Tn(n),noArgs:m})}function ft(e,n,r){t.U.assert(!ge.finalPass||!!e);let i={proc:e,callLocationIndex:Tn(n),virtualIndex:null,ifaceIndex:null};return t.ir.op(o.ProcCall,r,i)}function _t(e,n){return t.ir.op(o.ProcCall,e,n)}function mt(e){return u(e).proc}function gt(e,n,r){const i=mt(e);if(e.kind==t.SK.FunctionDeclaration){qe(Ne(e))}return t.assert(!!i||!ge.finalPass,"!!proc || !bin.finalPass"),ft(i,n,r)}function ht(e){return e.members.filter((e=>e.kind==t.SK.Constructor))[0]}function yt(e){if(at(e.decl),e.isUsed)return;u(e.decl).flags|=8,e.baseClassInfo&&yt(e.baseClassInfo),ge.usedClassInfos.push(e)}function vt(n){function i(e){return/^[0-9a-f]$/i.test(e)}let a=st(n.tag);if(!a)throw De(n,U("invalid tagged template"),9265);let o,s=J(a),c={decl:a,qName:a?j(L,a):"?",args:[n.template],isExpression:!0};function l(a){o=function(n,a){let o=te;if("_"==a[0]&&"_"==a[1]&&r.jres[a]&&(o=r.jres[a],a=""),""==a&&o){let n=/font\/x-mkcd-b(\d+)/.exec(o.mimeType);if(n)if(ge.finalPass){let e=parseInt(n[1]),r=atob(o.data),i=ge.usedChars,s="",c="";for(let t=0;t<r.length;t+=e){let n=r.charCodeAt(t)+(r.charCodeAt(t+1)<<8);(n<128||i[n>>5]&1<<(31&n))&&(s+=r.slice(t,t+e),c+=n+", ")}a=t.U.toHex(t.U.stringToUint8Array(s))}else a="aabbccdd";else o.dataEncoding&&"base64"!=o.dataEncoding?"hex"==o.dataEncoding?a=o.data:f(9271,U("invalid jres encoding '{0}' on '{1}'",o.dataEncoding,o.id)):a=t.U.toHex(t.U.stringToUint8Array(e.pxtc.decodeBase64(o.data)))}if(/^e[14]/i.test(a)&&n.parent&&n.parent.kind==t.SK.CallExpression&&"image.ofBuffer"==n.parent.expression.getText()){const e=/^e([14])(..)(..)..(.*)/i.exec(a);a=`870${e[1]}${e[2]}00${e[3]}000000${e[4]}`}let s="";for(let e=0;e<a.length;++e){let t=a[e];if(!i(t)){if(/^[\s\.]$/.test(t))continue;throw De(n,U("invalid character in hex literal '{0}'",t),9265)}i(a[e+1])&&(s+=t+a[e+1],e++)}if(t.target.isNative){const e=ge.emitHexLiteral(s.toLowerCase());return t.ir.ptrlit(e,e)}{const e="_hex"+Ae(n);return t.ir.ptrlit(e,{hexlit:s.toLowerCase()})}}(n,a(n.template.text))}if(u(n).callInfo=c,n.template.kind!=t.SK.NoSubstitutionTemplateLiteral)throw De(n,U("substitution not supported in hex literal",s.shim),9265);switch(s.shim){case"@hex":l((e=>e));break;case"@f4":l((function(e){if(!Array.isArray(s.groups))throw De(n,U("missing groups in @f4 literal"),9272);let r=[],i=[],a={},o=0;s.groups.forEach(((e,t)=>{for(let n of e)a[n]=t})),e+="\n";for(let c=0;c<e.length;++c){let l=e[c];switch(l){case" ":case"\t":break;case"\n":i.length>0&&(r.push(i),o=Math.max(i.length,o),i=[]);break;default:let e=t.U.lookup(a,l);if(null==e){if(2!=s.groups.length)throw De(n,U("invalid character in image literal: '{0}'",e),9273);e=1}i.push(e)}}let c=8;return s.groups.length<=2?c=1:s.groups.length<=16&&(c=4),t.f4EncodeImg(o,r.length,c,((e,t)=>r[t][e]||0))}));break;default:if(void 0===s.shim&&s.helper)return function(n,r){var i;let a,o=L.getSymbolsInScope(n,e.SymbolFlags.Module);for(let e of o)if("helpers"==e.name)for(let n of e.declarations||[e.valueDeclaration])if(n.kind==t.SK.ModuleDeclaration)for(let e of n.body.statements)(null===(i=e.symbol)||void 0===i?void 0:i.name)==r.helper&&(a=e);a||f(9215,U("helpers.{0} not found",r.helper));a.kind!=t.SK.FunctionDeclaration&&f(9216,U("helpers.{0} isn't a function",r.helper));const s=a;return it(s),gt(s,n,[Ge(n.text)])}(n.template,s);throw De(n,U("invalid shim '{0}' on tagged template",s.shim),9265)}return s.helper&&(o=t.ir.rtcall(s.helper,[o])),o}function bt(e){let n=e.parameters.slice(0);if(!k(e)&&D(e)){let r=Ne(e);r.thisParameter||(r.thisParameter={kind:t.SK.Parameter,name:{text:"this"},isThisParameter:!0,parent:e}),n.unshift(r.thisParameter)}return n}function xt(e,n=!1){let r=se(e);return t.ir.ptrlit(r+"_Lit",r)}function kt(){for(me=mt(be);w.length>0;){xn(w.pop())}}function St(){const e=le;if(e.length>0){le=[];for(let t of e){const e=me;try{Ct(t)}finally{me=e}}}}function Tt(e){ge.finalPass&&e.functionsToDefine&&t.U.pushRange(le,e.functionsToDefine)}function Ct(e){const n=Ne(e);let r=null;if(ge.finalPass){if(n.alreadyEmitted)return t.U.assert(n.usedBeforeDecl),null;n.alreadyEmitted=!0}let i=e.kind==t.SK.ArrowFunction||e.kind==t.SK.FunctionExpression,a=n.capturedVars.slice(0),s=a.map(((e,n)=>{let r=new t.ir.Cell(n,e,we(e));return r.iscap=!0,r}));void 0===n.usedBeforeDecl&&(n.usedBeforeDecl=!1),a.length>0?(t.assert(null!=N(e),"getEnclosingFunction(node) != null)"),r=t.ir.shared(t.ir.rtcall("pxt::mkAction",[t.ir.numlit(a.length),xt(e,!0)])),n.usedAsValue=!0,a.forEach(((e,n)=>{let i=me.localIndex(e);i||f(9223,U("cannot find captured value: {0}",L.symbolToString(e.symbol)));let a=i.loadCore();me.emitExpr(t.ir.rtcall("pxtrt::stclo",[r,t.ir.numlit(n),a]))})),e.kind==t.SK.FunctionDeclaration&&(n.location=me.mkLocal(e,we(e)),me.emitExpr(n.location.storeDirect(r)),r=null)):i&&(r=xt(e),n.usedAsValue=!0),t.assert(!!r==i,"!!lit == isExpression");let c=mt(e);if(c)me=c,me.reset();else{t.assert(!ge.finalPass,"!bin.finalPass");const r=u(e),i=new t.ir.Procedure;i.isRoot=!!(1&r.flags),i.action=e,i.info=n,r.proc=i,i.usingCtx=re,me=i,Pe((e=>e.addProc(i)))}me.captured=s;const l=[];if(e.parent.kind==t.SK.ClassDeclaration){let n=je(null,e.parent);if(me.classInfo?t.assert(me.classInfo==n,"proc.classInfo == classInfo"):me.classInfo=n,e.kind==t.SK.Constructor){if(n.baseClassInfo)for(let e of n.baseClassInfo.decl.members)e.kind==t.SK.Constructor&&it(e);n.ctor?t.assert(n.ctor==me,"classInfo.ctor == proc"):n.ctor=me;for(let e of n.allfields)if(e.kind==t.SK.PropertyDeclaration&&!k(e)){let t=e;t.initializer&&l.push(t)}}}const d=[],p=[];me.args=bt(e).map(((n,r)=>{n.name.kind===t.SK.ObjectBindingPattern&&d.push(n),e.kind==t.SK.Constructor&&fe(n)&&p.push(n);let i=new t.ir.Cell(r,n,we(n));return Tt(i.info),i.isarg=!0,i})),me.args.forEach((e=>{if(e.isByRefLocal()){let n=t.ir.shared(t.ir.rtcall("pxtrt::mklocRef",[]));me.emitExpr(t.ir.rtcall("pxtrt::stlocRef",[n,e.loadCore()],1)),me.emitExpr(e.storeDirect(n))}})),d.forEach((e=>mn(e)));for(let e of p){let r=Lt(me.classInfo,Rt(me.classInfo,q(e)),!1),i=t.ir.op(o.FieldAccess,[ze(n.thisParameter)],r);me.emitExpr(t.ir.op(o.Store,[i,ze(e)]))}for(let e of l){let r=Lt(me.classInfo,Rt(me.classInfo,q(e)),!1),i=t.ir.op(o.FieldAccess,[ze(n.thisParameter)],r);me.emitExpr(t.ir.op(o.Store,[i,vn(e.initializer)]))}if(St(),e.body.kind==t.SK.Block){if(kn(e.body),ne(me.action)){const n=me.body[me.body.length-1];n&&n.stmtKind==t.ir.SK.Jmp&&n.jmpMode==t.ir.JmpMode.Always||me.emitJmp(on(e).ret,Wt(void 0),t.ir.JmpMode.Always)}}else{let n=vn(e.body);me.emitJmp(on(e).ret,n,t.ir.JmpMode.Always)}me.emitLblDirect(on(e).ret),me.stackEmpty();let _=me.mkLabel("final");if(ne(me.action)?me.emitJmp(_):me.emitJmp(_,Wt(void 0)),me.emitLbl(_),n.capturedVars.length&&n.usedBeforeDecl&&e.kind==t.SK.FunctionDeclaration&&!ge.finalPass){n.capturedVars.sort(((e,t)=>t.pos-e.pos));const t=we(n.capturedVars[0]);t.functionsToDefine||(t.functionsToDefine=[]),t.functionsToDefine.push(e)}return t.assert(!ge.finalPass||0==w.length,"!bin.finalPass || usedWorkList.length == 0"),r}function Et(e){let n=t.ir.shared(e);return me.emitExpr(n),n}function Dt(){return Et(t.ir.op(o.JmpValue,[]))}function At(e){if(r.target.isNative)return!1;let n=e;return n.body&&(n.body.kind!=t.SK.Block||n.body.statements.length>0)}function Nt(n){if(!nt(n))return;if(32&u(n).flags)return;let i=J(n);if(null!=i.shim){if("@"==i.shim[0])return;if(r.target.isNative&&t.hexfile.validateShim(ae(n),i.shim,i,ne(n),bt(n).map((e=>_e(ee(e))))),!At(n))return}if(e.isInAmbientContext(n))return;if(!n.body)return;let a=null,o=me;try{a=Ct(n)}finally{me=o}return a}function wt(){}function It(e){let t=e;t.needsIRCache=!0,K.push(t)}function Pt(e,n=null){let r=K.length;return e.kind!=t.SK.PropertyAccessExpression&&e.kind!=t.SK.ElementAccessExpression||It(e.expression),n&&It(n),K.length==r?wt:()=>{for(let e=r;e<K.length;++e)K[e].cachedIR=null,K[e].needsIRCache=!1;K.splice(r,K.length-r)}}function Ot(e,n=!1){let r={kind:t.SK.NullKeyword,isRefOverride:n};return u(r).valueOverride=e,r}function Ft(e,n,r,i=null){let a=Pt(e),o=i?vn(i):Wt(1),s=t.ir.shared(vn(e)),c=t.ir.shared(Bt(n,s,o));return Mt(e,Ot(c,!0)),a(),r?s:c}function Lt(e,n,r=!0){k(n)&&t.U.oops("fieldIndex on static field: "+q(n));let i=J(n),a=e.allfields.indexOf(n);return a<0&&ge.finalPass&&t.U.oops("missing field"),{idx:a,name:q(n),isRef:!0,shimName:i.shim,classInfo:e,needsCheck:r}}function Rt(e,t){const n=e.allfields.filter((e=>e.name.text==t))[0];return n||f(9224,U("field {0} not found",t)),n}function Mt(n,r,i=!1){let a=st(n),s=P(a);if(n.kind==t.SK.Identifier||s)if(a&&(s||I(a)||O(a))){let e=Re(a);Ie(a,!0),me.emitExpr(e.storeByRef(vn(r)))}else De(n,U("bad target identifier"),9248);else if(n.kind==t.SK.PropertyAccessExpression){let i=st(n);if(!i||i.kind!=t.SK.GetAccessor&&i.kind!=t.SK.SetAccessor)if(i&&(i.kind==t.SK.PropertySignature||i.kind==t.SK.PropertyAssignment||Ze(i)))me.emitExpr(pt(n,n,[r],null,i));else{let e=vn(n);me.emitExpr(t.ir.op(o.Store,[e,vn(r)]))}else Xe(i),i=e.getDeclarationOfKind(i.symbol,t.SK.SetAccessor),i||De(n,U("setter not available"),9253),me.emitExpr(pt(n,n,[r],null,i))}else if(n.kind==t.SK.ElementAccessExpression)me.emitExpr(et(n,r));else if(n.kind==t.SK.ArrayLiteralExpression)if(r.kind==t.SK.ArrayLiteralExpression){const e=r.elements.map((e=>{const n=t.ir.shared(vn(e));return me.emitExpr(n),n}));n.elements.forEach(((t,n)=>{Mt(t,Ot(e[n]))}))}else{const e=t.ir.shared(vn(r));n.elements.forEach(((n,r)=>{Mt(n,Ot(Yt("Array_::getAt",[e,t.ir.numlit(r)])))}))}else De(n,U("bad assignment target"),9249)}function Ut(e){if(g())switch(e){case"numops::adds":case"numops::subs":case"numops::eors":case"numops::ands":case"numops::orrs":return"@nomask@"+e}if(_())switch(e){case"pxt::switch_eq":return"numops::eq"}return e}function Bt(e,t,n){return Yt(Ut(e),[t,n])}function $t(e){if(e.kind==t.SK.Identifier)return e.text;if(e.kind==t.SK.PropertyAccessExpression){const t=e,n=$t(t.expression);if(n)return n+"."+t.name.text}return null}function jt(e,t){if(!t)return null;const n=t.val;switch($t(e)){case"Math.floor":return{val:Math.floor(n)};case"Math.ceil":return{val:Math.ceil(n)};case"Math.round":return{val:Math.round(n)}}return null}function Kt(n){if(!n)return null;const r=u(n);if(void 0!==r.constantFolded)return r.constantFolded;if(I(n)&&n.parent.flags&e.NodeFlags.Const){const e=n;e.initializer&&(r.constantFolded=zt(e.initializer))}else if(n.kind==t.SK.EnumMember){const e=n,i=function(e){let n=J(e).enumval;if(!n){let t=L.getConstantValue(e);if(null==t)return null;n=t+""}return/^[+-]?\d+$/.test(n)||/^0x[A-Fa-f\d]{2,8}$/.test(n)?n:(t.U.userError("enumval only support number literals"),"0")}(e);if(null==i)r.constantFolded=zt(e.initializer);else{const e=parseInt(i);isNaN(e)||(r.constantFolded={val:e})}}else if(n.kind==t.SK.PropertyDeclaration&&k(n)&&S(n)){const e=n;r.constantFolded=zt(e.initializer)}return r.constantFolded}function zt(e){if(!e)return null;const n=u(e);if(void 0===n.constantFolded){n.constantFolded=null;const r=function(e){if(!e)return null;switch(e.kind){case t.SK.PrefixUnaryExpression:{const n=e,r=zt(n.operand);return function(e,n){if(!n)return null;const r=n.val;switch(e){case t.SK.PlusToken:return{val:+r};case t.SK.MinusToken:return{val:-r};case t.SK.TildeToken:return{val:~r};case t.SK.ExclamationToken:return{val:!r};default:return null}}(n.operator,r)}case t.SK.BinaryExpression:{const n=e,r=zt(n.left);if(!r)return null;const i=zt(n.right);return i?function(e,n,r){if(!n||!r)return null;const i=n.val,a=r.val;switch(e){case t.SK.PlusToken:return{val:i+a};case t.SK.MinusToken:return{val:i-a};case t.SK.SlashToken:return{val:i/a};case t.SK.PercentToken:return{val:i%a};case t.SK.AsteriskToken:return{val:i*a};case t.SK.AsteriskAsteriskToken:return{val:i**a};case t.SK.AmpersandToken:return{val:i&a};case t.SK.BarToken:return{val:i|a};case t.SK.CaretToken:return{val:i^a};case t.SK.LessThanLessThanToken:return{val:i<<a};case t.SK.GreaterThanGreaterThanToken:return{val:i>>a};case t.SK.GreaterThanGreaterThanGreaterThanToken:return{val:i>>>a};case t.SK.LessThanEqualsToken:return{val:i<=a};case t.SK.LessThanToken:return{val:i<a};case t.SK.GreaterThanEqualsToken:return{val:i>=a};case t.SK.GreaterThanToken:return{val:i>a};case t.SK.EqualsEqualsToken:return{val:i==a};case t.SK.EqualsEqualsEqualsToken:return{val:i===a};case t.SK.ExclamationEqualsEqualsToken:return{val:i!==a};case t.SK.ExclamationEqualsToken:return{val:i!=a};case t.SK.BarBarToken:return{val:i||a};case t.SK.AmpersandAmpersandToken:return{val:i&&a};default:return null}}(n.operatorToken.kind,r,i):null}case t.SK.NumericLiteral:{const t=parseFloat(e.text);return isNaN(t)?null:{val:t}}case t.SK.NullKeyword:return{val:null};case t.SK.TrueKeyword:return{val:!0};case t.SK.FalseKeyword:return{val:!1};case t.SK.UndefinedKeyword:return{val:void 0};case t.SK.CallExpression:{const t=e;return 1==t.arguments.length?jt(t.expression,zt(t.arguments[0])):null}case t.SK.PropertyAccessExpression:case t.SK.Identifier:return Kt(ot(e));case t.SK.AsExpression:return zt(e.expression);default:return null}}(e);n.constantFolded=r}return n.constantFolded}function Jt(e){let n=t.target.switches.boxDebug,r=null;if(n)try{t.target.switches.boxDebug=!1,r=vn(e)}finally{t.target.switches.boxDebug=n}else r=vn(e);let i=Gt(r);if(void 0===i)throw f(9267,U("a constant number-like expression is required here"));return i}function qt(e,t){let n=Vt(e,t,"userconfig");return null==n&&(n=Vt(e,t,"config")),n}function Vt(n,r,i){let a=L.getSymbolsInScope(n,e.SymbolFlags.Module).filter((e=>e.name==i&&!!e.valueDeclaration))[0];if(!a)return null;for(let e of a.valueDeclaration.body.statements)if(e.kind==t.SK.VariableStatement){let t=e;for(let e of t.declarationList.declarations)if(e.symbol.name==r)return Jt(e.initializer)}return null}function Ht(t,n){let r=L.getSymbolsInScope(t,e.SymbolFlags.Enum).filter((e=>"DAL"==e.name&&!!e.valueDeclaration))[0];if(!r)return null;let i=r.valueDeclaration.members.filter((e=>e.symbol.name==n))[0];return i?L.getConstantValue(i):null}function Gt(e){if(e.exprKind==t.ir.EK.NumberLiteral){let n=e.data;if(r.target.isNative&&!_()){if(n==t.taggedNull||n==t.taggedUndefined||n==t.taggedFalse)return 0;if(n==t.taggedTrue)return 1;if("number"==typeof n)return n>>1}else if("number"==typeof n)return n}else if(e.exprKind==t.ir.EK.RuntimeCall&&2==e.args.length){let t=Gt(e.args[0]),n=Gt(e.args[1]);if(void 0===t||void 0===n)return;switch(e.data){case"numops::orrs":return t|n;case"numops::adds":return t+n;default:return void console.log(e)}}}function Wt(e){if(r.target.isNative&&!_()){const r=Z(e);if(null!=r)return t.ir.numlit(r);if("number"==typeof e){if(n=e,!t.target.switches.boxDebug&&(0|n)==n&&-1073741824<=n&&n<=1073741823)return t.ir.numlit(e<<1|1);{let n=ge.emitDouble(e);return t.ir.ptrlit(n,JSON.stringify(e))}}throw t.U.oops("bad literal: "+e)}return t.ir.numlit(e);var n}function Qt(e){if(e.kind==t.SK.NullKeyword){let t=u(e).valueOverride;if(null!=t)return t.exprKind==o.NumberLiteral?!r.target.isNative||!!(1&t.data):t.exprKind==o.RuntimeCall&&"pxt::ptrOfLiteral"==t.data?t.args[0].exprKind==o.PointerLiteral&&!isNaN(parseFloat(t.args[0].jsInfo)):t.exprKind==o.PointerLiteral&&!isNaN(parseFloat(t.jsInfo))}return e.kind==t.SK.NumericLiteral||_e(ee(e))}function Yt(e,n){return t.ir.rtcallMask(e,(1<<n.length)-1,0,n)}function Xt(e,n,i,s=null){let c=[],l=t.hexfile.lookupFunc(e);if(g()){let n=t.U.lookup(a,e);n&&(l=n,e=n.name)}l&&(c=l.argsFmt),s&&(n=n.concat(s));let u=lt(n),d=[],p=n.map(((n,r)=>{let a=vn(n);if(!m())return a;let s=c[r+1],l=Qt(n);if(!s&&e.indexOf("::")<0&&(s=l?"I":"_"),s){if("_"==s[0]||"T"==s||"N"==s){let e=function(e){switch(e){case"_Buffer":return pxt.BuiltInType.BoxedBuffer;case"_Image":return t.target.imageRefTag||pxt.BuiltInType.RefImage;case"_Action":return pxt.BuiltInType.RefAction;case"_RefCollection":return pxt.BuiltInType.RefCollection;default:return null}}(s);return e&&d.push({argIdx:r,method:"_validate",refTag:e,refTagNullable:!!i.argsNullable}),a}if("I"==s)return a.exprKind==o.NumberLiteral&&"number"==typeof a.data?t.ir.numlit(a.data>>1):(d.push({argIdx:r,method:"pxt::toInt"}),a);if("B"==s)return u&=~(1<<r),an(n,a);if("S"==s)return a.isStringLiteral||(d.push({argIdx:r,method:"_pxt_stringConv",returnsRef:!0}),u|=1<<r),a;if("F"==s||"D"==s)return"D"==s&&t.U.oops("double arguments not yet supported"),l||t.U.userError("argsFmt=...F/D... but argument not a number in "+e),d.push({argIdx:r,method:"D"==s?"pxt::toDouble":"pxt::toFloat"}),a;throw t.U.oops("invalid format specifier: "+s)}throw t.U.userError("not enough args for "+e)})),f=t.ir.rtcallMask(e,u,i?i.callingConvention:0,p);if(f.mask||(f.mask={refMask:0}),f.mask.conversions=d,r.target.isNative){let e=c[0];"I"==e?f=h(f):"B"==e?f=y(f):"F"==e?f=function(e){return m()?t.ir.rtcall("pxt::fromFloat",[e]):e}(f):"D"==e&&(t.U.oops("double returns not yet supported"),f=function(e){return m()?t.ir.rtcall("pxt::fromDouble",[e]):e}(f))}return f}function Zt(n){ge.numStmts++;const a=t.assembler.debug||t.target.switches.size||t.target.sourceMap;let o=!!r.breakpoints;if(!a&&!o)return;const s=e.getSourceFileOfNode(n);if(r.justMyCode&&l(s)&&(o=!1),!a&&!o)return;let c=n.pos;for(;/^\s$/.exec(s.text[c]);)c++;for(;"/"==s.text[c]&&"/"==s.text[c+1];){for(;s.text[c]&&"\n"!=s.text[c];)c++;c++}const u=e.getLineAndCharacterOfPosition(s,c);if(a){let e=n.end;e-c>80&&(e=c+80);const r=s.text.slice(c,e).trim().replace(/\n[^]*/,"...");me.emit(t.ir.comment(`${s.fileName.replace(/pxt_modules\//,"")}(${u.line+1},${u.character+1}): ${r}`))}if(!o)return;const d=e.getLineAndCharacterOfPosition(s,n.end),p={id:i.breakpoints.length,isDebuggerStmt:n.kind==t.SK.DebuggerStatement,fileName:s.fileName,start:c,length:n.end-c,line:u.line,endLine:d.line,column:u.character,endColumn:d.character};i.breakpoints.push(p);const f=t.ir.stmt(t.ir.SK.Breakpoint,null);f.breakpointInfo=p,me.emit(f)}function en(e,n){switch(n){case t.SK.PlusToken:return"numops::adds";case t.SK.MinusToken:return"numops::subs";case t.SK.SlashToken:return"numops::div";case t.SK.PercentToken:return"numops::mod";case t.SK.AsteriskToken:return"numops::muls";case t.SK.AsteriskAsteriskToken:return"Math_::pow";case t.SK.AmpersandToken:return"numops::ands";case t.SK.BarToken:return"numops::orrs";case t.SK.CaretToken:return"numops::eors";case t.SK.LessThanLessThanToken:return"numops::lsls";case t.SK.GreaterThanGreaterThanToken:return"numops::asrs";case t.SK.GreaterThanGreaterThanGreaterThanToken:return"numops::lsrs";case t.SK.LessThanEqualsToken:return"numops::le";case t.SK.LessThanToken:return"numops::lt";case t.SK.GreaterThanEqualsToken:return"numops::ge";case t.SK.GreaterThanToken:return"numops::gt";case t.SK.EqualsEqualsToken:return"numops::eq";case t.SK.EqualsEqualsEqualsToken:return"numops::eqq";case t.SK.ExclamationEqualsEqualsToken:return"numops::neqq";case t.SK.ExclamationEqualsToken:return"numops::neq";default:return null}}function tn(e){if(e.operatorToken.kind==t.SK.EqualsToken)return function(e){let n=e.right;e.parent.kind==t.SK.ExpressionStatement&&(n=null);let r=Pt(e.left,n);Mt(e.left,e.right,!0);let i=n?vn(n):Wt(void 0);return r(),i}(e);const n=zt(e);if(n)return Wt(n.val);let r=null,i=null;e.operatorToken.kind!=t.SK.PlusToken&&e.operatorToken.kind!=t.SK.PlusEqualsToken||(r=ee(e.left),i=ee(e.right),(ue(r)||ue(i)&&e.operatorToken.kind==t.SK.PlusToken)&&(u(e).exprInfo={leftType:L.typeToString(r),rightType:L.typeToString(i)}));if(e.operatorToken.kind==t.SK.CommaToken){if(sn(e.left))return vn(e.right);{let n=cn(e.left);return t.ir.op(o.Sequence,[n,vn(e.right)])}}switch(e.operatorToken.kind){case t.SK.BarBarToken:case t.SK.AmpersandAmpersandToken:return function(e){let n=vn(e.left),r=(ue(ee(e.left)),me.mkLabel("lazy"));n=t.ir.shared(n);let i=t.ir.rtcall("numops::toBool",[n]),a=me.mkLabel("lazySkip"),o=e.operatorToken.kind==t.SK.BarBarToken?t.ir.JmpMode.IfZero:e.operatorToken.kind==t.SK.AmpersandAmpersandToken?t.ir.JmpMode.IfNotZero:t.U.oops();return me.emitJmp(a,i,o),me.emitJmp(r,n,t.ir.JmpMode.Always,n),me.emitLbl(a),me.emitExpr(Yt("langsupp::ignore",[n])),me.emitJmp(r,vn(e.right),t.ir.JmpMode.Always),me.emitLbl(r),Dt()}(e);case t.SK.InstanceOfKeyword:return function(e){let n=ee(e.right),r=Q(n)?st(e.right):null;r&&r.kind==t.SK.ClassDeclaration||f(9275,U("unsupported instanceof expression"));let i=je(n,r);yt(i);let a=t.ir.op(t.ir.EK.InstanceOf,[vn(e.left)],i);return a.jsInfo="bool",a}(e)}if(e.operatorToken.kind==t.SK.PlusToken&&(ue(r)||ue(i)))return Xt("String_::concat",[We(e.left),We(e.right)],null);if(e.operatorToken.kind==t.SK.PlusEqualsToken&&ue(r)){let n=Pt(e.left),r=t.ir.shared(Xt("String_::concat",[We(e.left),We(e.right)],null));return Mt(e.left,Ot(r)),n(),r}let a=function(e){switch(e){case t.SK.PlusEqualsToken:return t.SK.PlusToken;case t.SK.MinusEqualsToken:return t.SK.MinusToken;case t.SK.AsteriskEqualsToken:return t.SK.AsteriskToken;case t.SK.AsteriskAsteriskEqualsToken:return t.SK.AsteriskAsteriskToken;case t.SK.SlashEqualsToken:return t.SK.SlashToken;case t.SK.PercentEqualsToken:return t.SK.PercentToken;case t.SK.LessThanLessThanEqualsToken:return t.SK.LessThanLessThanToken;case t.SK.GreaterThanGreaterThanEqualsToken:return t.SK.GreaterThanGreaterThanToken;case t.SK.GreaterThanGreaterThanGreaterThanEqualsToken:return t.SK.GreaterThanGreaterThanGreaterThanToken;case t.SK.AmpersandEqualsToken:return t.SK.AmpersandToken;case t.SK.BarEqualsToken:return t.SK.BarToken;case t.SK.CaretEqualsToken:return t.SK.CaretToken;default:return t.SK.Unknown}}(e.operatorToken.kind),s=en(0,a||e.operatorToken.kind);return s||De(e.operatorToken,U("unsupported operator"),9250),a?Ft(e.left,s,!1,e.right):(n=>{n=Ut(n);let r=[e.left,e.right];return t.ir.rtcallMask(n,lt(r),0,r.map((e=>vn(e))))})(s)}function nn(e){e.statements.forEach(kn)}function rn(t){if(t.flags&e.NodeFlags.Let||t.flags&e.NodeFlags.Const)return!0;throw f(9260,U("variable needs to be defined using 'let' instead of 'var'"))}function an(e,n=null){if(!n&&g()&&e.kind==t.SK.BinaryExpression){let n=e,r=t.U.lookup(t.thumbCmpMap,en(0,n.operatorToken.kind));if(r)return t.ir.rtcall(r,[vn(n.left),vn(n.right)])}return n||(n=vn(e)),_()?n:t.ir.rtcall("numops::toBoolDecr",[n])}function on(e){let t=d(e);return{fortop:".fortop."+t,cont:".cont."+t,brk:".brk."+t,ret:".ret."+t}}function sn(e){if(!e)return!0;switch(e.kind){case t.SK.Identifier:case t.SK.StringLiteral:case t.SK.NumericLiteral:case t.SK.NullKeyword:return!0}return!1}function cn(e){return vn(e)}function ln(e){if(sn(e))return;Zt(e);let t=cn(e);me.emitExpr(t),me.stackEmpty()}function un(e=1){for(;e--;)me.emitExpr(Yt("pxt::endTry",[]))}function dn(){f(9282,U("jumps (return, break, continue) through finally blocks not supported yet"))}function pn(t){let n=0;if(t.kind==e.SyntaxKind.Block&&t.parent)if(t.parent.kind==e.SyntaxKind.CatchClause){t.parent.parent.finallyBlock&&(n++,dn())}else if(t.parent.kind==e.SyntaxKind.TryStatement){const e=t.parent;e.tryBlock==t&&(e.catchClause&&n++,e.finallyBlock&&(n++,dn()))}return n}function fn(e){switch(e.kind){case t.SK.WhileStatement:case t.SK.ForInStatement:case t.SK.ForOfStatement:case t.SK.ForStatement:case t.SK.DoStatement:return!0;default:return!1}}function _n(e,n,i){if(e.name.kind===t.SK.ObjectBindingPattern||e.name.kind==t.SK.ArrayBindingPattern)return n||(n=e.initializer?t.ir.shared(vn(e.initializer)):ze(e),i=e.initializer?ee(e.initializer):ee(e)),e.name.elements.forEach((e=>_n(e,n,i))),me.stackEmpty(),null;if(!nt(e))return null;if(Kt(e))return null;let a;if(P(e)?(Le(e),a=Re(e)):a=me.mkLocal(e,we(e)),Tt(a.info),a.isByRefLocal()&&me.emitExpr(a.storeDirect(t.ir.rtcall("pxtrt::mklocRef",[]))),Fe(ee(e)),e.kind===t.SK.BindingElement){Zt(e);let[t,r]=gn(e,n,i);me.emitExpr(a.storeByRef(t))}else if(e.initializer){if(Zt(e),P(e)){let n=J(e).jres;if(n){"true"==n&&(n=j(L,e));let i=t.U.lookup(r.jres||{},n);i?te=i:f(9270,U("resource '{0}' not found in any .jres file",n))}}e.initializer,me.emitExpr(a.storeByRef(vn(e.initializer))),te=null,me.stackEmpty()}else(function(e){for(;e;){if(fn(e))return!0;e=e.parent}return!1})(e)&&(Zt(e),me.emitExpr(a.storeByRef(Wt(void 0))),me.stackEmpty());return a}function mn(e){return _n(e,null,null)}function gn(e,n,r){const i=e.parent.parent;if(i.kind===t.SK.BindingElement){const e=gn(i,n,r);n=e[0],r=e[1]}if(e.parent.kind==t.SK.ArrayBindingPattern){const i=e.parent.elements.indexOf(e);e.dotDotDotToken&&f(9203,U("spread operator not supported yet"));const a=Y(r,i);return[Yt("Array_::getAt",[n,t.ir.numlit(i)]),a]}return function(e,n,r,i){const a=L.getPropertyOfType(r,i);t.U.assert(!!a,"field sym");const s=L.getTypeOfSymbolAtLocation(a,e);let c;if(Q(r)){const e=je(r);c=t.ir.op(o.FieldAccess,[n],Lt(e,Rt(e,i)))}else c=_t([n],{ifaceIndex:Oe(i,!0),callLocationIndex:Tn(e),noArgs:!0});return[c,s]}(e,n,r,(e.propertyName||e.name).text)}function hn(e){!function(e,n){const r=e=>{e&&e.kind==t.SK.ClassDeclaration&&f(9261,U("Interface with same name as a class not supported"))};if(r(n.symbol.valueDeclaration),n.symbol.declarations&&n.symbol.declarations.forEach(r),n.heritageClauses)for(let e of n.heritageClauses)switch(e.token){case t.SK.ExtendsKeyword:W(ee(e.types[0]))&&f(9262,U("Extending a class by an interface not supported."))}}(0,e);let n=J(e);n.autoCreate&&(V[n.autoCreate]=!0)}function yn(e,t){let n=M;$++;try{M=null;let r=t(e);return M&&f(B,M),M=n,$--,r}catch(t){return $--,M=null,Ee(e,t.ksErrorCode||9200,t.message),pxt.debug(t.stack),null}}function vn(e,n=!0){let r=e;if(n&&r.cachedIR)return r.cachedIR;let i=yn(r,bn)||Wt(void 0);return n&&r.needsIRCache?(r.cachedIR=t.ir.shared(i),r.cachedIR):i}function bn(n){let r=function(n){switch(n.kind){case t.SK.NullKeyword:let r=u(n).valueOverride;return r||Wt(null);case t.SK.TrueKeyword:return Wt(!0);case t.SK.FalseKeyword:return Wt(!1);case t.SK.TemplateHead:case t.SK.TemplateMiddle:case t.SK.TemplateTail:case t.SK.NumericLiteral:case t.SK.StringLiteral:case t.SK.NoSubstitutionTemplateLiteral:return function(e){if(e.kind==t.SK.NumericLiteral)return e.imageLiteral?t.ir.ptrlit(e.imageLiteral,e.jsLit):Wt(parseFloat(e.text));if(x(e))return Ge(e.text);throw t.oops()}(n);case t.SK.TaggedTemplateExpression:return vt(n);case t.SK.PropertyAccessExpression:return Ye(n);case t.SK.BinaryExpression:return tn(n);case t.SK.PrefixUnaryExpression:return function(e){const n=zt(e);if(n)return Wt(n.val);switch(e.operator){case t.SK.ExclamationToken:return y(t.ir.rtcall("Boolean_::bang",[an(e.operand)]));case t.SK.PlusPlusToken:return Ft(e.operand,"numops::adds",!1);case t.SK.MinusMinusToken:return Ft(e.operand,"numops::subs",!1);case t.SK.PlusToken:case t.SK.MinusToken:{let n=vn(e.operand),r=Gt(n);return null!=r?Wt(-r):e.operator==t.SK.MinusToken?Bt("numops::subs",Wt(0),n):Bt("numops::subs",n,Wt(0))}case t.SK.TildeToken:{let t=vn(e.operand),n=Gt(t);return null!=n?Wt(~n):Yt(Ut("numops::bnot"),[t])}default:throw De(e,U("unsupported prefix unary operation"),9245)}}(n);case t.SK.PostfixUnaryExpression:return function(e){if(de(ee(e.operand)))switch(e.operator){case t.SK.PlusPlusToken:return Ft(e.operand,"numops::adds",!0);case t.SK.MinusMinusToken:return Ft(e.operand,"numops::subs",!0)}throw De(e,U("unsupported postfix unary operation"),9246)}(n);case t.SK.ElementAccessExpression:return et(n);case t.SK.ParenthesizedExpression:return function(e){return vn(e.expression)}(n);case t.SK.TypeAssertionExpression:return function(e){return e.expression,vn(e.expression)}(n);case t.SK.ArrayLiteralExpression:return function(e){Y(ee(e));let n=t.ir.shared(t.ir.rtcall("Array_::mk",[]));for(let r of e.elements){let e=ct(r)?2:0;me.emitExpr(t.ir.rtcall("Array_::push",[n,vn(r)],e))}return n}(n);case t.SK.NewExpression:return function(e){let n=L.getTypeAtLocation(e);if(n&&H(n))throw t.oops();if(n&&Q(n)){let n,r=st(e.expression);r.kind!=t.SK.ClassDeclaration&&f(9221,U("new expression only supported on class types"));let i=je(ee(e),r);for(let e=i;e&&(n=ht(e.decl),!n);e=e.baseClassInfo);yt(i);let a=i.id+"_VT",o=t.ir.rtcall("pxt::mkClassInstance",[t.ir.ptrlit(a,a)]);if(n){o=Et(o),rt(n);let r=(e.arguments||[]).slice(0),i=J(n);dt(L.getResolvedSignature(e),r,i);let a=r.map((e=>vn(e)));return i.shim?t.ir.rtcall(i.shim,a):(a.unshift(o),me.emitExpr(gt(n,e,a)),o)}return e.arguments&&e.arguments.length&&f(9222,U("constructor with arguments not found")),o}throw De(e,U("unknown type for new"),9243)}(n);case t.SK.SuperKeyword:case t.SK.ThisKeyword:return He(n);case t.SK.CallExpression:return function(e){const t=L.getResolvedSignature(e);return pt(e,e.expression,e.arguments,t)}(n);case t.SK.FunctionExpression:case t.SK.ArrowFunction:return Nt(n);case t.SK.Identifier:return Ve(n);case t.SK.ConditionalExpression:return function(e){let n=me.mkLabel("condexprz"),r=me.mkLabel("condexprfin");return me.emitJmp(n,an(e.condition),t.ir.JmpMode.IfZero),me.emitJmp(r,vn(e.whenTrue),t.ir.JmpMode.Always),me.emitLbl(n),me.emitJmp(r,vn(e.whenFalse),t.ir.JmpMode.Always),me.emitLbl(r),Dt()}(n);case t.SK.AsExpression:return function(e){return e.expression,vn(e.expression)}(n);case t.SK.TemplateExpression:return Qe(n);case t.SK.ObjectLiteralExpression:return function(e){let n=t.ir.shared(t.ir.rtcall("pxtrt::mkMap",[]));return e.properties.forEach((e=>{let r,i;if(t.assert(!e.questionToken),e.kind==t.SK.ShorthandPropertyAssignment){const n=e;t.assert(!n.equalsToken&&!n.objectAssignmentInitializer),r=e.name.text;const a=L.getShorthandAssignmentValueSymbol(e),o=a&&a.valueDeclaration&&a.valueDeclaration.name;if(!o||o.kind!=t.SK.Identifier)throw De(e);i=Ve(o)}else{if(e.name.kind==t.SK.ComputedPropertyName){const t=e.name.expression;return void me.emitExpr(Xt("pxtrt::mapSetByString",[Ot(n,!0),t,e.initializer],null))}r=e.name.kind==t.SK.StringLiteral?e.name.text:e.name.getText(),i=vn(e.initializer)}const a=t.target.isNative?t.ir.numlit(Oe(r)):t.ir.ptrlit(null,JSON.stringify(r)),o=[n,a,i];me.emitExpr(t.ir.rtcall(t.target.isNative?"pxtrt::mapSet":"pxtrt::mapSetByString",o))})),n}(n);case t.SK.TypeOfExpression:return function(e){return Xt("pxt::typeOf",[e.expression],null)}(n);case e.SyntaxKind.DeleteExpression:return function(e){let n,r;if(e.expression.kind==t.SK.PropertyAccessExpression){const t=e.expression;n=t.expression,r=Ot(Ge(t.name.text))}else{if(e.expression.kind!=t.SK.ElementAccessExpression)throw f(9276,U("expression not supported as argument to 'delete'"));{const t=e.expression;n=t.expression,r=t.argumentExpression}}const i=ee(n);if(W(i))throw f(9277,U("'delete' not supported on class types"));if(H(i))throw f(9277,U("'delete' not supported on array"));return Xt("pxtrt::mapDeleteByString",[n,r],null)}(n);default:return De(n),null}}(n);if(r.isExpr())return r;throw new Error("expecting expression")}function xn(n){const r=u(n);if(r.usedNodes){ie=!1;for(let e of t.U.values(r.usedNodes))rt(e);for(let e of r.usedActions)e(ge);ie=!0}else P(n)||e.isClassDeclaration(n)?(ie=!1,re=r,re.usedNodes=null,re.usedActions=null,P(n)&&!Kt(n)&&Le(n),kn(n),ie=!0):(re=r,re.usedNodes={},re.usedActions=[],kn(n),re=null)}function kn(e){yn(e,Sn)}function Sn(n){switch(n.kind){case t.SK.SourceFile:return function(e){e.statements.forEach(kn)}(n);case t.SK.InterfaceDeclaration:return hn(n);case t.SK.VariableStatement:return function(n){function r(e){let n=t.U.lookup(X,e.name);if(n||(n=e,X[e.name]=n),n.value!=e.value)throw f(9269,U("conflicting values for config.{0}",e.name))}if(n.declarationList.flags&e.NodeFlags.Const){let e=n.parent&&n.parent.kind==t.SK.ModuleBlock?q(n.parent.parent):"?";if("config"==e||"userconfig"==e)for(let t of n.declarationList.declarations){let i=ae(t);if(!t.initializer)continue;let a=Jt(t.initializer),o=Ht(n,"CFG_"+i);if(null==o||0==o)throw f(9268,U("can't find DAL.CFG_{0}",i));"userconfig"==e&&(i="!"+i),r({name:i,key:o,value:a})}}e.isInAmbientContext(n)||(rn(n.declarationList),n.declarationList.declarations.forEach(kn))}(n);case t.SK.ModuleDeclaration:return function(e){kn(e.body)}(n);case t.SK.EnumDeclaration:return;case t.SK.FunctionDeclaration:case t.SK.Constructor:case t.SK.MethodDeclaration:return void Nt(n);case t.SK.ExpressionStatement:return function(e){ln(e.expression)}(n);case t.SK.Block:case t.SK.ModuleBlock:return nn(n);case t.SK.VariableDeclaration:return mn(n),void St();case t.SK.IfStatement:return function(e){Zt(e);let t=me.mkLabel("else");me.emitJmpZ(t,an(e.expression)),kn(e.thenStatement);let n=me.mkLabel("afterif");me.emitJmp(n),me.emitLbl(t),e.elseStatement&&kn(e.elseStatement),me.emitLbl(n)}(n);case t.SK.WhileStatement:return function(e){Zt(e);let t=on(e);me.emitLblDirect(t.cont),Zt(e.expression),me.emitJmpZ(t.brk,an(e.expression)),kn(e.statement),me.emitJmp(t.cont),me.emitLblDirect(t.brk)}(n);case t.SK.DoStatement:return function(e){Zt(e);let t=on(e);me.emitLblDirect(t.cont),kn(e.statement),Zt(e.expression),me.emitJmpZ(t.brk,an(e.expression)),me.emitJmp(t.cont),me.emitLblDirect(t.brk)}(n);case t.SK.ForStatement:return function(e){e.initializer&&e.initializer.kind==t.SK.VariableDeclarationList?(rn(e.initializer),e.initializer.declarations.forEach(kn)):ln(e.initializer),Zt(e);let n=on(e);me.emitLblDirect(n.fortop),e.condition&&(Zt(e.condition),me.emitJmpZ(n.brk,an(e.condition))),kn(e.statement),me.emitLblDirect(n.cont),ln(e.incrementor),me.emitJmp(n.fortop),me.emitLblDirect(n.brk)}(n);case t.SK.ForOfStatement:return function(e){if(!e.initializer||e.initializer.kind!=t.SK.VariableDeclarationList)return void De(e,"only a single variable may be used to iterate a collection");let n=e.initializer;if(1!=n.declarations.length)return void De(e,"only a single variable may be used to iterate a collection");rn(n);let r=ee(e.expression),i="",a="";if(ue(r))i="String_::charAt",a="String_::length";else{if(!H(r))return void De(e.expression,"cannot use for...of with this expression");i="Array_::getAt",a="Array_::length"}rt(n.declarations[0]);const o=mn(n.declarations[0]);t.U.assert(!!o||!ge.finalPass),me.stackEmpty();let s=me.mkLocalUnnamed();me.emitExpr(s.storeByRef(vn(e.expression)));let c=me.mkLocalUnnamed();me.emitExpr(c.storeByRef(Wt(0))),me.stackEmpty(),Zt(e);let l=on(e);me.emitLblDirect(l.fortop);let u=t.ir.rtcall(a,[s.loadCore()]),d=Bt("numops::lt_bool",c.load(),h(u));me.emitJmpZ(l.brk,d),o&&me.emitExpr(o.storeByRef(t.ir.rtcall(i,[s.loadCore(),(e=>m()?t.ir.rtcall("pxt::toInt",[e]):e)(c.loadCore())]))),St(),kn(e.statement),me.emitLblDirect(l.cont),me.emitExpr(c.storeByRef(Bt("numops::adds",c.load(),Wt(1)))),me.emitJmp(l.fortop),me.emitLblDirect(l.brk),me.emitExpr(s.storeByRef(Wt(void 0)))}(n);case t.SK.ContinueStatement:case t.SK.BreakStatement:return function(n){Zt(n);let r=n.label?n.label.text:null,i=n.kind==t.SK.BreakStatement,a=0,o=function n(o){return o?r&&o.kind==t.SK.LabeledStatement&&o.label.text==r?o.statement:o.kind==t.SK.SwitchStatement&&!r&&i||!r&&e.isIterationStatement(o,!1)?o:(a+=pn(o),n(o.parent)):null}(n);if(o){let r=on(o);un(a),n.kind==t.SK.ContinueStatement?e.isIterationStatement(o,!1)?me.emitJmp(r.cont):Ee(n,9231,U("continue on non-loop")):n.kind==t.SK.BreakStatement?me.emitJmp(r.brk):t.oops()}else Ee(n,9230,U("cannot find outer loop"))}(n);case t.SK.LabeledStatement:return function(e){let t=on(e.statement);kn(e.statement),me.emitLblDirect(t.brk)}(n);case t.SK.ReturnStatement:return function(e){Zt(e);let n=null;e.expression?n=vn(e.expression):ne(me.action)&&(n=Wt(void 0));let r=0;for(let t=e;t&&t!=me.action;t=t.parent)r+=pn(t);un(r),me.emitJmp(on(me.action).ret,n,t.ir.JmpMode.Always)}(n);case t.SK.ClassDeclaration:return function(e){const t=je(null,e);t.isUsed&&ge.usedClassInfos.indexOf(t)<0&&ge.usedClassInfos.push(t),e.members.forEach(kn)}(n);case t.SK.PropertyDeclaration:case t.SK.PropertyAssignment:return function(e){if(k(e))mn(e);else if(e.initializer){let t=je(ee(e.parent));ge.finalPass&&t.isUsed&&!t.ctor&&f(9209,U("class field initializers currently require an explicit constructor"))}}(n);case t.SK.SwitchStatement:return function(e){Zt(e);let n,r=on(e),i=t.ir.shared(vn(e.expression)),a=e.caseBlock.clauses.map((e=>{let r=me.mkLabel("switch");if(e.kind==t.SK.CaseClause){let n=e,a=vn(n.expression),o=ct(n.expression)?1:0,s=t.ir.rtcallMask(Ut("pxt::switch_eq"),o,0,[a,i]);me.emitJmp(r,s,t.ir.JmpMode.IfNotZero,i)}else e.kind==t.SK.DefaultClause?(t.assert(!n,"!defaultLabel"),n=r):t.oops();return r}));n?me.emitJmp(n,i):me.emitJmp(r.brk,i),e.caseBlock.clauses.forEach(((e,t)=>{me.emitLbl(a[t]),e.statements.forEach(kn)})),me.emitLblDirect(r.brk)}(n);case t.SK.TypeAliasDeclaration:return;case e.SyntaxKind.TryStatement:return function(e){const n=e=>Yt("pxt::beginTry",[t.ir.ptrlit(e.lblName,e)]);Zt(e);const r=me.mkLabel("catch");r.lblName="_catch_"+d(e);const i=me.mkLabel("finally");if(i.lblName="_finally_"+d(e),e.finallyBlock&&me.emitExpr(n(i)),e.catchClause&&me.emitExpr(n(r)),me.stackEmpty(),nn(e.tryBlock),me.stackEmpty(),e.catchClause){const t=me.mkLabel("catchend");un(),me.emitJmp(t),me.emitLbl(r);const n=e.catchClause.variableDeclaration;if(n){mn(n);const e=Re(n);me.emitExpr(e.storeByRef(Yt("pxt::getThrownValue",[])))}St(),nn(e.catchClause.block),me.emitLbl(t)}e.finallyBlock&&(un(),me.emitLbl(i),nn(e.finallyBlock),me.emitExpr(Yt("pxt::endFinally",[])))}(n);case e.SyntaxKind.ThrowStatement:return function(e){Zt(e),me.emitExpr(Yt("pxt::throwValue",[vn(e.expression)]))}(n);case t.SK.DebuggerStatement:return function(e){Zt(e)}(n);case t.SK.GetAccessor:case t.SK.SetAccessor:return function(e){Nt(e)}(n);case t.SK.ImportEqualsDeclaration:case t.SK.EmptyStatement:case t.SK.SemicolonClassElement:return;default:De(n)}}function Tn(e){return i.procCallLocations.push(t.nodeLocationInfo(e))-1}},t.isStringType=ue;class pe{constructor(){this.procs=[],this.globals=[],this.finalPass=!1,this.writeFile=(e,t)=>{},this.usedClassInfos=[],this.numStmts=1,this.commSize=0,this.itEntries=0,this.itFullEntries=0,this.numMethods=0,this.numVirtMethods=0,this.usedChars=new Uint32Array(2048),this.explicitlyUsedIfaceMembers={},this.ifaceMemberMap={},this.strings={},this.hexlits={},this.doubles={},this.otherLiterals=[],this.codeHelpers={},this.lblNo=0}reset(){this.lblNo=0,this.otherLiterals=[],this.strings={},this.hexlits={},this.doubles={},this.numStmts=0}getTitle(){const e=this.options.name||t.U.lf("Untitled");return e.length>=90?e.slice(0,87)+"...":e}addProc(e){t.assert(!this.finalPass,"!this.finalPass"),this.procs.push(e),e.seqNo=this.procs.length}recordHelper(e,t,n){const r=e=>{e.codeHelpers[t]||(e.codeHelpers[t]=n(e))};r(this),this.recordAction(e,r)}recordAction(e,n){e?e.usedActions&&e.usedActions.push(n):t.U.oops("no using ctx!")}emitLabelled(e,n,r){let i=t.U.lookup(n,e);if(null!=i)return i;let a=r+this.lblNo++;return n[e]=a,a}emitDouble(e){return this.emitLabelled(t.target.switches.numFloat?function(e){let n=new Float32Array(1);return n[0]=e,t.U.toHex(new Uint8Array(n.buffer))}(e):function(e){let n=new Float64Array(1);return n[0]=e,t.U.toHex(new Uint8Array(n.buffer))}(e),this.doubles,"_dbl")}emitString(e){if(!this.finalPass)for(let t=0;t<e.length;++t){const n=e.charCodeAt(t);n>=128&&(this.usedChars[n>>5]|=1<<(31&n))}return this.emitLabelled(e,this.strings,"_str")}emitHexLiteral(e){return this.emitLabelled(e,this.hexlits,"_hexlit")}setPerfCounters(e){if(!t.target.switches.profile)return[];const n=e.slice();return this.procs.forEach((e=>{e.perfCounterName&&(t.U.assert(t.target.switches.profile),e.perfCounterNo=n.length,n.push(e.perfCounterName))})),n}}function fe(e){if(!e.modifiers)return!1;if(e.parent.kind!=t.SK.Constructor)return!1;for(let n of e.modifiers)if(n.kind==t.SK.PrivateKeyword||n.kind==t.SK.PublicKeyword||n.kind==t.SK.ProtectedKeyword)return!0;return!1}function _e(t){return t.flags&e.TypeFlags.Union?t.types.every((e=>_e(e))):!!(t.flags&(e.TypeFlags.NumberLike|e.TypeFlags.EnumLike|e.TypeFlags.BooleanLike))}t.Binary=pe,t.isCtorField=fe}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(ts){var pxtc;(function(pxtc){function getTsCompilerOptions(e){let t=ts.getDefaultCompilerOptions();return t.target=ts.ScriptTarget.ES5,t.module=ts.ModuleKind.None,t.noImplicitAny=!0,t.noImplicitReturns=!0,t.allowUnreachableCode=!0,t}function nodeLocationInfo(e){let t=ts.getSourceFileOfNode(e);const n=e.getStart?e.getStart():e.pos,{line:r,character:i}=ts.getLineAndCharacterOfPosition(t,n),{line:a,character:o}=ts.getLineAndCharacterOfPosition(t,e.end);return{start:n,length:e.end-n,line:r,column:i,endLine:a,endColumn:o,fileName:t.fileName}}function patchUpDiagnostics(e,t=!1){t&&(e=e.filter((e=>5012!==e.code)));let n=e.filter((e=>1148==e.code));return n.length>0&&(e=n),e.map((e=>{if(!e.file){return{code:e.code,start:e.start,length:e.length,line:0,column:0,messageText:ts.flattenDiagnosticMessageText(e.messageText,"\n"),category:e.category,fileName:"?"}}const t=ts.getLineAndCharacterOfPosition(e.file,e.start);let n={code:e.code,start:e.start,length:e.length,line:t.line,column:t.character,messageText:ts.flattenDiagnosticMessageText(e.messageText,"\n"),category:e.category,fileName:e.file.fileName};return 1148==n.code&&(n.messageText=pxtc.Util.lf("all symbols in top-level scope are always exported; please use a namespace if you want to export only some")),n}))}function py2tsIfNecessary(e){if(e.target.preferredEditor==pxt.PYTHON_PROJECT_NAME){return pxtc.transpile.pyToTs(e)}}function mkCompileResult(){return{outfiles:{},diagnostics:[],success:!1,times:{}}}function storeGeneratedFiles(e,t){for(let n of e.generatedFiles||[])t.outfiles[n]=e.fileSystem[n]}function runConversionsAndStoreResults(e,t){const n=pxtc.U.cpuUs();t||(t=mkCompileResult());const r=py2tsIfNecessary(e);r&&(t=Object.assign(Object.assign({},t),{diagnostics:r.diagnostics,sourceMap:r.sourceMap,globalNames:r.globalNames})),storeGeneratedFiles(e,t),e.sourceFiles||(e.sourceFiles=Object.keys(e.fileSystem));const i=e.sourceFiles.indexOf(pxt.MAIN_TS);i>=0&&(e.sourceFiles.splice(i,1),e.sourceFiles.push(pxt.MAIN_TS));const a=e.sourceFiles.indexOf(pxt.TUTORIAL_CODE_STOP);return a>=0&&(e.sourceFiles.splice(a,1),e.sourceFiles.push(pxt.TUTORIAL_CODE_STOP)),t.times.conversions=pxtc.U.cpuUs()-n,t}function timesToMs(e){for(let t of Object.keys(e.times))e.times[t]=Math.round(e.times[t])/1e3}function buildProgram(e,t){let n={};for(let t in e.fileSystem)n[normalizePath(t)]=e.fileSystem[t];let r=getTsCompilerOptions(e),i={getSourceFile:(e,t,r)=>{e=normalizePath(e);let i="";return n.hasOwnProperty(e)?i=n[e]:r&&r("File not found: "+e),null==i&&(r("File not found: "+e),i=""),ts.createSourceFile(e,i,t,true)},fileExists:e=>(e=normalizePath(e),n.hasOwnProperty(e)),getCanonicalFileName:e=>e,getDefaultLibFileName:()=>"no-default-lib.d.ts",writeFile:(e,n,r,i)=>{t.outfiles[e]=n},getCurrentDirectory:()=>".",useCaseSensitiveFileNames:()=>!0,getNewLine:()=>"\n",readFile:e=>(e=normalizePath(e),n[e]||""),directoryExists:e=>!0,getDirectories:()=>[]},a=e.sourceFiles.filter((e=>pxtc.U.endsWith(e,".ts")));return ts.createProgram(a,r,i)}function isPxtModulesFilename(e){return pxtc.U.startsWith(e,"pxt_modules/")}function compile(opts,service){pxtc.compilerHooks||(pxtc.compilerHooks={},opts.target.compilerExtension&&eval(opts.target.compilerExtension)),pxtc.compilerHooks.init&&pxtc.compilerHooks.init(opts,service);let startTime=pxtc.U.cpuUs(),res=mkCompileResult(),program;if(service)storeGeneratedFiles(opts,res),program=service.getProgram();else{if(runConversionsAndStoreResults(opts,res),res.diagnostics.length>0)return res;program=buildProgram(opts,res)}const entryPoint=opts.sourceFiles.filter((e=>pxtc.U.endsWith(e,".ts"))).pop().replace(/.*\//,"");if(res.diagnostics=patchUpDiagnostics(program.getSyntacticDiagnostics(),opts.ignoreFileResolutionErrors),res.diagnostics.length>0)return opts.forceEmit&&(pxt.debug("syntactic errors, forcing emit"),pxtc.compileBinary(program,opts,res,entryPoint)),res;res.diagnostics=patchUpDiagnostics(program.getOptionsDiagnostics().concat(pxtc.Util.toArray(program.getGlobalDiagnostics())),opts.ignoreFileResolutionErrors);const semStart=pxtc.U.cpuUs();0==res.diagnostics.length&&(res.diagnostics=patchUpDiagnostics(program.getSemanticDiagnostics(),opts.ignoreFileResolutionErrors));const emitStart=pxtc.U.cpuUs();if(res.times["typescript-syn"]=semStart-startTime,res.times["typescript-sem"]=emitStart-semStart,res.times.typescript=emitStart-startTime,opts.ast&&(res.ast=program),opts.ast||opts.forceEmit||0==res.diagnostics.length){const e=pxtc.compileBinary(program,opts,res,entryPoint);res.times.compilebinary=pxtc.U.cpuUs()-emitStart,res.diagnostics=res.diagnostics.concat(patchUpDiagnostics(e.diagnostics))}0==res.diagnostics.length&&(res.success=!0);for(let e of opts.sourceFiles)pxtc.Util.startsWith(e,"built/")&&(res.outfiles[e.slice(6)]=opts.fileSystem[e]);return res.times.all=pxtc.U.cpuUs()-startTime,pxt.tickEvent("compile",res.times),res}function decompile(e,t,n,r=!1){let i=e.getSourceFile(n);pxtc.annotate(e,n,pxtc.target||pxt.appTarget&&pxt.appTarget.compile);const a=pxtc.getApiInfo(e,t.jres),o=pxtc.getBlocksInfo(a,t.bannedCategories),s={snippetMode:t.snippetMode||!1,alwaysEmitOnStart:t.alwaysDecompileOnStart,includeGreyBlockMessages:r,generateSourceMap:!!t.ast,allowedArgumentTypes:t.allowedArgumentTypes||["number","boolean","string"],errorOnGreyBlocks:!!t.errorOnGreyBlocks},[c,l]=pxtc.decompiler.buildRenameMap(e,i,{declarations:"variables",takenNames:{}});return pxtc.decompiler.decompileToBlocks(o,i,s,c)}function decompileSnippets(e,t,n=!1){const r=pxtc.getApiInfo(e,t.jres),i=pxtc.getBlocksInfo(r,t.bannedCategories),a=new pxtc.decompiler.RenameMap([]),o={snippetMode:t.snippetMode||!1,alwaysEmitOnStart:t.alwaysDecompileOnStart,includeGreyBlockMessages:n,generateSourceMap:!!t.ast,allowedArgumentTypes:t.allowedArgumentTypes||["number","boolean","string"],errorOnGreyBlocks:!!t.errorOnGreyBlocks};let s;const c=[];if(t.sourceTexts)for(let e=0;e<t.sourceTexts.length;e++){t.fileSystem[pxt.MAIN_TS]=t.sourceTexts[e],t.fileSystem[pxt.MAIN_BLOCKS]="";let n=getTSProgram(t,s);const r=n.getSourceFile(pxt.MAIN_TS),l=pxtc.decompiler.decompileToBlocks(i,r,o,a);c.push(l.outfiles[pxt.MAIN_BLOCKS]),s=n}return c}function getTSProgram(e,t){let n={},r={};for(let t in e.fileSystem)r[normalizePath(t)]=e.fileSystem[t];let i=getTsCompilerOptions(e),a={getSourceFile:(e,t,n)=>{e=normalizePath(e);let i="";return r.hasOwnProperty(e)?i=r[e]:n&&n("File not found: "+e),null==i&&(n("File not found: "+e),i=""),ts.createSourceFile(e,i,t,true)},fileExists:e=>(e=normalizePath(e),r.hasOwnProperty(e)),getCanonicalFileName:e=>e,getDefaultLibFileName:()=>"no-default-lib.d.ts",writeFile:(e,t,r,i)=>{n[e]=t},getCurrentDirectory:()=>".",useCaseSensitiveFileNames:()=>!0,getNewLine:()=>"\n",readFile:e=>(e=normalizePath(e),r[e]||""),directoryExists:e=>!0,getDirectories:()=>[]};e.sourceFiles||(e.sourceFiles=Object.keys(e.fileSystem));let o=e.sourceFiles.filter((e=>pxtc.U.endsWith(e,".ts"))),s=o.filter((e=>e!=pxt.MAIN_TS)),c=!1;o.length>s.length&&(o=s,o.push(pxt.MAIN_TS),c=!0);const l=o.indexOf(pxt.TUTORIAL_CODE_STOP);l>=0&&(o.splice(l,1),o.push(pxt.TUTORIAL_CODE_STOP));const u=ts.createProgram(o,i,a,t);return pxtc.annotate(u,pxt.MAIN_TS,pxtc.target||pxt.appTarget&&pxt.appTarget.compile),u}function normalizePath(e){e=e.replace(/\\/g,"/");const t=[];return e.split("/").forEach((e=>{".."===e&&t.length?t.pop():"."!==e&&t.push(e)})),t.join("/")}pxtc.getTsCompilerOptions=getTsCompilerOptions,pxtc.nodeLocationInfo=nodeLocationInfo,pxtc.patchUpDiagnostics=patchUpDiagnostics,pxtc.py2tsIfNecessary=py2tsIfNecessary,pxtc.storeGeneratedFiles=storeGeneratedFiles,pxtc.runConversionsAndStoreResults=runConversionsAndStoreResults,pxtc.timesToMs=timesToMs,pxtc.isPxtModulesFilename=isPxtModulesFilename,pxtc.compile=compile,pxtc.decompile=decompile,pxtc.decompileSnippets=decompileSnippets,pxtc.getTSProgram=getTSProgram})(pxtc=ts.pxtc||(ts.pxtc={}))}(ts||(ts={})),function(e){!function(t){const n=["type","offset","vaddr","paddr","filesz","memsz","flags","align"],r=e.HF2.read32,i=e.HF2.read16,a=4096;t.parse=function(t){1179403647!=r(t,0)&&e.U.userError("no magic"),1!=t[4]&&e.U.userError("not 32 bit"),1!=t[5]&&e.U.userError("not little endian"),1!=t[6]&&e.U.userError("bad version"),2!=i(t,16)&&e.U.userError("wrong object type"),40!=i(t,18)&&e.U.userError("not ARM");let o=r(t,28);r(t,32),0==o&&e.U.userError("expecting program headers");let s=i(t,42),c=i(t,44),l=e.U.range(c).map((e=>function(e){let i={},a=e;for(let a of n)i[a]=r(t,e),e+=4;let o=i;return o._filepos=a,o}(o+e*s))),u=t.length+1;for(;15&u;)u++;let d=0;for(let e of l)1==e.type&&(d=Math.max(d,e.vaddr+e.memsz));let p=(d+a-1&-4096)+(4095&u),f=-1;for(let e of l)4==e.type&&(f=e._filepos);return{imageMemStart:p,imageFileStart:u,phOffset:f,template:t}},t.patch=function(t,r){let i=new Uint8Array(t.imageFileStart+r.length);return i.fill(0),e.U.memcpy(i,0,t.template),e.U.memcpy(i,t.imageFileStart,r),function(t,r){let i=r._filepos;for(let a of n)e.HF2.write32(t,i,r[a]||0),i+=4}(i,{_filepos:t.phOffset,type:1,offset:t.imageFileStart,vaddr:t.imageMemStart,paddr:t.imageMemStart,filesz:r.length,memsz:r.length,flags:5,align:a}),i}}(e.elf||(e.elf={}))}(pxt||(pxt={})),function(e){!function(t){const n=e.HF2.read32,r=e.HF2.read16,i=[{name:"esp32",chipId:0,memmap:[{from:0,to:65536,id:"PADDING"},{from:1061158912,to:1065353216,id:"DROM"},{from:1065353216,to:1069547520,id:"EXTRAM_DATA"},{from:1073217536,to:1073225728,id:"RTC_DRAM"},{from:1073283072,to:1073741824,id:"BYTE_ACCESSIBLE"},{from:1073405952,to:1073741824,id:"DRAM"},{from:1073610752,to:1073741820,id:"DIRAM_DRAM"},{from:1073741824,to:1074200576,id:"IROM"},{from:1074200576,to:1074233344,id:"CACHE_PRO"},{from:1074233344,to:1074266112,id:"CACHE_APP"},{from:1074266112,to:1074397184,id:"IRAM"},{from:1074397184,to:1074528252,id:"DIRAM_IRAM"},{from:1074528256,to:1074536448,id:"RTC_IRAM"},{from:1074593792,to:1077936128,id:"IROM"},{from:1342177280,to:1342185472,id:"RTC_DATA"}]},{name:"esp32-s2",chipId:2,memmap:[{from:0,to:65536,id:"PADDING"},{from:1056964608,to:1073217536,id:"DROM"},{from:1062207488,to:1073217536,id:"EXTRAM_DATA"},{from:1073340416,to:1073348608,id:"RTC_DRAM"},{from:1073340416,to:1073741824,id:"BYTE_ACCESSIBLE"},{from:1073340416,to:1074208768,id:"MEM_INTERNAL"},{from:1073414144,to:1073741824,id:"DRAM"},{from:1073741824,to:1073848576,id:"IROM_MASK"},{from:1073872896,to:1074200576,id:"IRAM"},{from:1074200576,to:1074208768,id:"RTC_IRAM"},{from:1074266112,to:1082130432,id:"IROM"},{from:1342177280,to:1342185472,id:"RTC_DATA"}]},{name:"esp32-s3",chipId:4,memmap:[{from:0,to:65536,id:"PADDING"},{from:1006632960,to:1023410176,id:"DROM"},{from:1023410176,to:1040187392,id:"EXTRAM_DATA"},{from:1611653120,to:1611661312,id:"RTC_DRAM"},{from:1070104576,to:1070596096,id:"BYTE_ACCESSIBLE"},{from:1070104576,to:1077813248,id:"MEM_INTERNAL"},{from:1070104576,to:1070596096,id:"DRAM"},{from:1073741824,to:1073848576,id:"IROM_MASK"},{from:1077346304,to:1077805056,id:"IRAM"},{from:1611653120,to:1611661312,id:"RTC_IRAM"},{from:1107296256,to:1115684864,id:"IROM"},{from:1342177280,to:1342185472,id:"RTC_DATA"}]},{name:"esp32-c3",chipId:5,memmap:[{from:0,to:65536,id:"PADDING"},{from:1006632960,to:1015021568,id:"DROM"},{from:1070071808,to:1070465024,id:"DRAM"},{from:1070104576,to:1070596096,id:"BYTE_ACCESSIBLE"},{from:1072693248,to:1072824320,id:"DROM_MASK"},{from:1073741824,to:1074135040,id:"IROM_MASK"},{from:1107296256,to:1115684864,id:"IROM"},{from:1077395456,to:1077805056,id:"IRAM"},{from:1342177280,to:1342185472,id:"RTC_IRAM"},{from:1342177280,to:1342185472,id:"RTC_DRAM"},{from:1611653120,to:1611661312,id:"MEM_INTERNAL2"}]}];function a(t){return`0x${t.addr.toString(16)} 0x${t.data.length.toString(16)} bytes; ${t.isDROM?"drom ":""}${t.isMapped?"mapped ":""}${e.U.toHex(t.data.slice(0,20))}...`}function o(t){if(233!=t[0])throw new Error("ESP: invalid magic: "+t[0]);let a=24;const o=r(t,12),s=i.find((e=>e.chipId==o));if(!s)throw new Error("ESP: unknown chipid: "+o);const c={header:t.slice(0,a),chipName:s.name,segments:[]},l=t[1];for(let r=0;r<l;++r){const r=n(t,a),i=n(t,a+4);a+=8;const o=t.slice(a,a+i);if(o.length!=i)throw new Error("too short file");if(a+=i,u(r,"PADDING"))continue;const s=c.segments.filter((e=>e.addr+e.data.length==r))[0];s?s.data=e.U.uint8ArrayConcat([s.data,o]):c.segments.push({addr:r,isMapped:u(r,"DROM")||u(r,"IROM"),isDROM:u(r,"DROM"),data:o})}return c;function u(e,t){return s.memmap.some((n=>n.id==t&&n.from<=e&&e<=n.to))}}function s(t){const n=e.U.flatClone(t);return n.segments=n.segments.map(e.U.flatClone),n}t.toBuffer=function(t,n=!0){let r=(t=function(t){const n=65535;(t=s(t)).segments.sort(((e,t)=>e.addr-t.addr)),e.debug("esp padding:\n"+t.segments.map(a).join("\n")+"\n");const r=t.segments.filter((e=>e.isMapped)),i=t.segments.filter((e=>!e.isMapped));t.segments=[];let o=t.header.length;for(const t of r){const r=t.addr+t.data.length&n;if(r<36){const n=new Uint8Array(36-r);t.data=e.U.uint8ArrayConcat([t.data,n])}}for(;r.length>0;){let e=r[0];const i=c(e);if(i>0)e=l(i);else{if((o+8&n)!=(e.addr&n))throw new Error(`pad oops 0 ${o}+8 != ${e.addr} (mod mask)`);r.shift()}if(t.segments.push(e),o+=8+e.data.length,3&o)throw new Error("pad oops 1")}return t.segments=t.segments.concat(i),e.debug("esp padded:\n"+t.segments.map(a).join("\n")+"\n"),t;function c(e){let t=(e.addr-8&n)-o&n;return 0==t?0:(t-=8,t<0&&(t+=65536),t)}function l(e){if(!i.length||e<=8)return{addr:0,isMapped:!1,isDROM:!1,data:new Uint8Array(e)};const t=i[0],n={addr:t.addr,isMapped:t.isMapped,isDROM:t.isDROM,data:t.data.slice(0,e)};return t.data=t.data.slice(e),t.addr+=n.data.length,0==t.data.length&&i.shift(),n}}(t)).header.length;for(const e of t.segments)r+=8+e.data.length;r=r+16&-16;let i=new Uint8Array(r);i.set(t.header),i[1]=t.segments.length;let o=t.header.length,c=239;for(const n of t.segments){e.HF2.write32(i,o,n.addr),e.HF2.write32(i,o+4,n.data.length),i.set(n.data,o+8),o+=8+n.data.length;for(let e=0;e<n.data.length;++e)c^=n.data[e]}if(i[i.length-1]=c,n){i[23]=1;const t=ts.pxtc.BrowserImpl.sha256buffer(i);i=e.U.uint8ArrayConcat([i,e.U.fromHex(t)])}else i[23]=0;return i},t.parseBuffer=o,t.parseB64=function(t){return o(e.U.stringToUint8Array(atob(t.join(""))))},t.cloneStruct=s}(e.esp||(e.esp={}))}(pxt||(pxt={})),function(e){!function(t){let n;!function(e){e[e.None=0]="None",e[e.Whitespace=1]="Whitespace",e[e.Identifier=2]="Identifier",e[e.Keyword=3]="Keyword",e[e.Operator=4]="Operator",e[e.CommentLine=5]="CommentLine",e[e.CommentBlock=6]="CommentBlock",e[e.NewLine=7]="NewLine",e[e.Literal=8]="Literal",e[e.Tree=9]="Tree",e[e.Block=10]="Block",e[e.EOF=11]="EOF"}(n||(n={}));let r="";let i=e.SyntaxKind;function a(e){switch(e){case i.CommaToken:return 2;case i.EqualsToken:case i.PlusEqualsToken:case i.MinusEqualsToken:case i.AsteriskEqualsToken:case i.AsteriskAsteriskEqualsToken:case i.SlashEqualsToken:case i.PercentEqualsToken:case i.LessThanLessThanEqualsToken:case i.GreaterThanGreaterThanEqualsToken:case i.GreaterThanGreaterThanGreaterThanEqualsToken:case i.AmpersandEqualsToken:case i.BarEqualsToken:case i.CaretEqualsToken:return 5;case i.QuestionToken:case i.ColonToken:return 7;case i.BarBarToken:return 10;case i.AmpersandAmpersandToken:return 20;case i.BarToken:return 30;case i.CaretToken:return 40;case i.AmpersandToken:return 50;case i.EqualsEqualsToken:case i.ExclamationEqualsToken:case i.EqualsEqualsEqualsToken:case i.ExclamationEqualsEqualsToken:return 60;case i.LessThanToken:case i.GreaterThanToken:case i.LessThanEqualsToken:case i.GreaterThanEqualsToken:case i.InstanceOfKeyword:case i.InKeyword:case i.AsKeyword:return 70;case i.LessThanLessThanToken:case i.GreaterThanGreaterThanToken:case i.GreaterThanGreaterThanGreaterThanToken:return 80;case i.PlusToken:case i.MinusToken:return 90;case i.AsteriskToken:case i.SlashToken:case i.PercentToken:return 100;case i.AsteriskAsteriskToken:return 101;case i.DotToken:return 120;default:return 0}}function o(e){switch(e){case i.EndOfFileToken:return n.EOF;case i.SingleLineCommentTrivia:return n.CommentLine;case i.MultiLineCommentTrivia:return n.CommentBlock;case i.NewLineTrivia:return n.NewLine;case i.WhitespaceTrivia:return n.Whitespace;case i.ShebangTrivia:case i.ConflictMarkerTrivia:return n.CommentBlock;case i.NumericLiteral:case i.StringLiteral:case i.RegularExpressionLiteral:case i.NoSubstitutionTemplateLiteral:case i.TemplateHead:case i.TemplateMiddle:case i.TemplateTail:return n.Literal;case i.Identifier:return n.Identifier;default:return e<i.Identifier?n.Operator:n.Keyword}}function s(e,t){for(;e[t]&&e[t].kind==n.Whitespace;)t++;return t}function c(){return{kind:n.EOF,synKind:i.EndOfFileToken,pos:0,lineNo:0,text:""}}function l(e,t){return{kind:n.Whitespace,synKind:i.WhitespaceTrivia,pos:e.pos-t.length,lineNo:e.lineNo,text:t}}function u(e){return{kind:n.Block,synKind:i.OpenBraceToken,pos:e[0].pos,lineNo:e[0].lineNo,stmts:[{tokens:e}],text:"{",endToken:null}}function d(e){if(!e)return!1;switch(e.synKind){case i.IfKeyword:case i.ElseKeyword:case i.LetKeyword:case i.ConstKeyword:case i.VarKeyword:case i.DoKeyword:case i.WhileKeyword:case i.SwitchKeyword:case i.CaseKeyword:case i.DefaultKeyword:case i.ForKeyword:case i.ReturnKeyword:case i.BreakKeyword:case i.ContinueKeyword:case i.TryKeyword:case i.CatchKeyword:case i.FinallyKeyword:case i.DeleteKeyword:case i.FunctionKeyword:case i.ClassKeyword:case i.YieldKeyword:case i.DebuggerKeyword:return!0;default:return!1}}function p(e,r,o=null){let s,f=[],_=0,g=!1;for(e=e.concat([c()]);e[_].kind!=n.EOF;){let n=_;C(),t.Util.assert(_>n,`Error at ${e[_].text}`),h(e.slice(n,_))}return f;function h(e){if(r&&(e=m(e)),0==e.length)return;e.forEach(v),e=y(e);if(r&&f.length>0){let n=f[f.length-1].tokens[0].synKind,r=e[0].synKind;if(n==i.IfKeyword&&r==i.ElseKeyword||n==i.TryKeyword&&r==i.CatchKeyword||n==i.TryKeyword&&r==i.FinallyKeyword||n==i.CatchKeyword&&r==i.FinallyKeyword)return e.unshift(l(e[0]," ")),void t.Util.pushRange(f[f.length-1].tokens,e)}f.push({tokens:e})}function y(e){let t=[],r=0;for(;r<e.length;)if(e[r].blockSpanLength){let o=e.slice(r,r+e[r].blockSpanLength),s=!!o[0].blockSpanIsVirtual;delete o[0].blockSpanLength,delete o[0].blockSpanIsVirtual,r+=o.length,o=y(o),s?t.push((a=o,{kind:n.Tree,synKind:i.WhitespaceTrivia,pos:a[0].pos,lineNo:a[0].lineNo,children:a,endToken:null,text:""})):(t.push(l(o[0]," ")),t.push(u(m(o))))}else t.push(e[r++]);var a;return t}function v(e){if(e.kind==n.Tree){let n=e;n.children=t.Util.concat(p(n.children,!1,n).map((e=>e.tokens)))}}function b(t=!1){for(;;)switch(_++,e[_].kind){case n.Whitespace:case n.CommentBlock:case n.CommentLine:break;case n.NewLine:if(t)break;break;default:return}}function x(){for(;e[_].kind==n.Whitespace;)_++;e[_].kind==n.NewLine&&_++}function k(){for(;;)switch(_++,e[_].kind){case n.EOF:return;case n.Tree:if(e[_].synKind==i.OpenBraceToken)return _--,void T()}}function S(){t.Util.assert(e[_].synKind==i.OpenBraceToken);let r=e[_];t.Util.assert(r.kind==n.Tree);let a=e[_];a.stmts=p(r.children,!0,s),delete r.children,a.kind=n.Block,_++,g=!0}function T(){let t=_+1;b(),e[_].synKind==i.OpenBraceToken?(S(),x()):(C(),e[t].blockSpanLength=_-t)}function C(){for(;;){let c=e[_],l=_;if(s=c,g=!1,c.kind==n.EOF)return;if(r&&c.synKind==i.SemicolonToken)return _++,void x();if(c.synKind==i.EqualsGreaterThanToken){if(b(),e[_].synKind==i.OpenBraceToken){S();continue}{let t=_;C();let r=_;for(;e[r].kind==n.NewLine;)r--;return e[t].blockSpanLength=r-t,void(e[t].blockSpanIsVirtual=!0)}}if(r&&a(c.synKind)){let t=_;if(b(),!d(e[_]))continue;_=t}if(r&&c.kind==n.NewLine){if(b(),c=e[_],a(c.synKind)&&c.synKind!=i.PlusToken&&c.synKind!=i.MinusToken)continue;return void(_=l+1)}if(c.synKind==i.OpenBraceToken&&o&&o.synKind==i.ClassKeyword){let t=_-1;for(;t>=0&&e[t].kind==n.Whitespace;)t--;if(t<0||e[t].synKind!=i.EqualsToken)return _--,void T()}switch(t.Util.assert(l==_),c.synKind){case i.ForKeyword:case i.WhileKeyword:case i.IfKeyword:case i.CatchKeyword:if(b(),e[_].synKind!=i.OpenParenToken)continue;return void T();case i.DoKeyword:if(T(),_--,b(),e[_].synKind==i.WhileKeyword){_++;continue}return;case i.ElseKeyword:if(b(),e[_].synKind==i.IfKeyword)continue;return _=l,void T();case i.TryKeyword:case i.FinallyKeyword:return void T();case i.ClassKeyword:case i.NamespaceKeyword:case i.ModuleKeyword:case i.InterfaceKeyword:case i.FunctionKeyword:return void k()}t.Util.assert(!g,"forgot continue/return after expectBlock"),_++}}}function f(e){return e&&(e.kind==n.Whitespace||e.kind==n.NewLine)}function _(e){let t=[],r=!1;for(let i=0;i<e.length;++i)r&&(i=s(e,i)),e[i]&&(t.push(e[i]),r=e[i].kind==n.NewLine);return t}function m(e){for(e=e.slice(0);f(e[0]);)e.shift();for(;f(e[e.length-1]);)e.pop();return e}function g(e,t){if(t.synKind==i.NoSubstitutionTemplateLiteral&&/^`[\s\.#01]*`$/.test(t.text)){let n=t.text.slice(1,t.text.length-1).split("\n").map((e=>e.replace(/\s/g,""))).filter((e=>!!e));if(n.length<4||n.length>5)return;let r=Math.floor((Math.max(...n.map((e=>e.length)))+2)/5);r<=0&&(r=1);let i="`\n";for(let t=0;t<5;++t){let a=n[t]||"";for(;a.length<5*r;)a+=".";a=a.replace(/0/g,"."),a=a.replace(/1/g,"#"),a=a.replace(/...../g,(e=>"/"+e)),i+=e+a.replace(/./g,(e=>" "+e)).replace(/\//g," ").slice(3)+"\n"}i+=e+"`",t.text=i}}t.toStr=function e(t){return Array.isArray(t)?"[[ "+t.map(e).join(" ")+" ]]":"string"==typeof t.text?JSON.stringify(t.text):t+""},t.format=function(t,u){let d=function(t){r=t;let a=e.createScanner(e.ScriptTarget.Latest,!1,e.LanguageVariant.Standard,t,(e=>{let t=a.getTextPos();console.log("scanner error",t,e.message)})),s=[],c=0,l=-1;for(;;){let e=a.scan();if(e==i.CloseBraceToken&&c==l&&(l=-1,e=a.reScanTemplateToken()),e==i.SlashEqualsToken){let t=a.reScanSlashToken();t==i.RegularExpressionLiteral&&(e=t)}e==i.GreaterThanToken&&(e=a.reScanGreaterToken());let t={kind:o(e),synKind:e,lineNo:0,pos:a.getTokenPos(),text:a.getTokenText()};if(e==i.OpenBraceToken&&c++,e==i.CloseBraceToken&&--c<0&&(c=-1e7),s.push(t),e!=i.TemplateHead&&e!=i.TemplateMiddle||(l=c),t.kind==n.EOF)break}return{tokens:s,braceBalance:c}}(t).tokens;d=function(e,t){let r=[],a=!0,o=1;for(let c=0;c<e.length;++c){if(a){let a=c;if(c=s(e,c),e[c].kind==n.NewLine){let a=!1;t>=0&&e[c].pos>=t&&(t=-1,a=!0),r.push({text:"",kind:n.CommentLine,pos:e[c].pos,lineNo:o,synKind:i.SingleLineCommentTrivia,isCursor:a})}else c=a}r.push(e[c]),e[c].lineNo=o,e[c].kind==n.NewLine?(a=!0,o++):a=!1,t>=0&&e[c].pos>=t&&(t=-1)}return r}(d,u),d=function(e){let t=[];t.push({synKind:i.EndOfFileToken,token:{children:[]}});let r=(e,r)=>{let i=e;i.children=[],i.kind=n.Tree,t.push({synKind:r,token:i})};for(let a=0;a<e.length;++a){let o=e[a],s=t[t.length-1];switch(s.token.children.push(o),o.kind){case n.Operator:switch(o.synKind){case i.OpenBraceToken:case i.OpenParenToken:case i.OpenBracketToken:r(o,o.synKind+1);break;case i.CloseBraceToken:case i.CloseParenToken:case i.CloseBracketToken:for(s.token.children.pop();;){if(s=t.pop(),s.synKind==o.synKind){s.token.endToken=o;break}if(0==t.length||s.synKind==i.CloseBraceToken){t.push(s);break}}}}}return t[0].token.children}(d);let f=p(d,!0),m="",h="",y=-1,v=0;return f.forEach(k),f.forEach((e=>e.tokens.forEach(b))),-1==y&&(y=h.length),{formatted:h,pos:y};function b(e){if(e.kind==n.Tree){let t=e;e.synKind,i.OpenBraceToken,t.children.forEach(b)}else e.kind==n.Block&&e.stmts.forEach((e=>e.tokens.forEach(b)))}function x(e,t){if(v==e.lineNo)t();else{v=e.lineNo;let n=m;m+=" ",t(),m=n}}function k(e){let t=_(e.tokens);1!=t.length||t[0].isCursor||""!=t[0].text?(h+=m,x(t[0],(()=>{T(t)})),"\n"!=h[h.length-1]&&(h+="\n")):h+="\n"}function S(e){-1==y&&e.pos+e.text.length>=u&&(y=h.length+(u-e.pos)),h+=e.text}function T(e){e=function(e){let t=[],r=0,o=c();for(e=e.concat([c()]);r<e.length;){r=s(e,r);let c=e[r];if(c.kind==n.EOF)break;let d=s(e,r+1);if(c.kind==n.NewLine&&e[d].synKind==i.OpenBraceToken){r=d;continue}let p=!0,f=0==t.length?(u=c,{kind:n.NewLine,synKind:i.NewLineTrivia,pos:u.pos,lineNo:u.lineNo,text:"\n"}):t[t.length-1];switch(f.synKind){case i.ExclamationToken:case i.TildeToken:case i.DotToken:p=!1;break;case i.PlusToken:case i.MinusToken:case i.PlusPlusToken:case i.MinusMinusToken:f.isPrefix&&(p=!1)}switch(c.synKind){case i.DotToken:case i.CommaToken:case i.NewLineTrivia:case i.ColonToken:case i.SemicolonToken:case i.OpenBracketToken:p=!1;break;case i.PlusPlusToken:case i.MinusMinusToken:f.kind!=n.Tree&&f.kind!=n.Identifier&&f.kind!=n.Keyword||(p=!1);case i.PlusToken:case i.MinusToken:(o.kind==n.EOF||a(o.synKind)||o.synKind==i.SemicolonToken)&&(c.isPrefix=!0);break;case i.OpenParenToken:if(f.kind==n.Identifier&&(p=!1),f.kind==n.Keyword)switch(f.synKind){case i.IfKeyword:case i.ForKeyword:case i.WhileKeyword:case i.SwitchKeyword:case i.ReturnKeyword:case i.ThrowKeyword:case i.CatchKeyword:break;default:p=!1}}f.kind==n.NewLine&&(p=!1),p&&t.push(l(c," ")),t.push(c),c.kind!=n.NewLine&&(o=c),r++}var u;return t}(e);for(let t=0;t<e.length;++t){let r=e[t];switch(g(m,r),S(r),r.kind){case n.Tree:let i=r;x(r,(()=>{T(_(i.children))})),i.endToken&&S(i.endToken);break;case n.Block:let a=r;0==a.stmts.length?h+=" ":(h+="\n",a.stmts.forEach(k),h+=m.slice(4)),a.endToken?S(a.endToken):h+="}";break;case n.NewLine:if(e[t+1]&&e[t+1].kind==n.CommentLine&&""==e[t+1].text&&!e[t+1].isCursor)break;t==e.length-1?h+=m.slice(4):h+=m;break;case n.Whitespace:}}}}}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){let n;function r(e,n){if(!n.packedSource)return;let r=e.currPtr+4096&-256,i=new Uint8Array(256);for(let a=0;a<n.packedSource.length;a+=256){for(let e=0;e<256;++e)i[e]=n.packedSource.charCodeAt(a+e);t.UF2.writeBytes(e,r,i,t.UF2.UF2_FLAG_NOFLASH),r+=256}}!function(e){e.asmTotalSource="";let n={},i=[];let a={commBase:0,funcInfo:{},codeStartIdx:-1,codePaddingSize:0,sha:null,codeStartAddrPadded:void 0,hexlines:void 0,jmpStartAddr:void 0,jmpStartIdx:void 0,codeStartAddr:void 0,elfInfo:void 0,espInfo:void 0};function o(e){let n="",r=0;for(;r<e.length;r+=2)n=e[r]+e[r+1]+n;return t.assert(r==e.length),n}function s(e){if(!(e=e.replace(/^[\s:]/,"")))return[];let n=[];if(e.replace(/([a-f0-9][a-f0-9])/gi,(e=>(n.push(parseInt(e,16)),""))))throw t.oops("bad bytes "+e);return n}function c(e){return e.flashCodeAlign||1024}e.getCommBase=function(){return a.commBase},e.getStartAddress=function(){return a.codeStartAddrPadded},e.setupInlineAssembly=function(r){n={};let i=r.sourceFiles.filter((e=>t.U.endsWith(e,".asm")));e.asmTotalSource="";let a=0;for(let t of i){let i=r.fileSystem[t];i.replace(/^\s*(\w+):/gm,((e,t)=>(n[t]=!0,"")));let o=".section code\n@stackmark func\n@scope user"+a+++"\n"+i+"\n@stackempty func\n@scope\n";e.asmTotalSource+=o}},e.parseHexBytes=s,e.parseHexRecord=function(e){let t=s(e);return{len:t[0],addr:t[1]<<8|t[2],type:t[3],data:t.slice(4,t.length-1),checksum:t[t.length-1]}},e.flashCodeAlign=c;const l="0108010842424242010801083ed8e98d";function u(e){return a.funcInfo[e]}function d(){let e=a.sha?a.sha.slice(0,16):"";for(;e.length<16;)e+="0";return e.toUpperCase()}function p(e){let t=0,n=":";return e.forEach((e=>t+=e)),e.push(255&-t),e.forEach((e=>n+=("0"+e.toString(16)).slice(-2))),n.toUpperCase()}e.setupFor=function(e,n){if(a=i.find((e=>e.sha==n.sha)),a)return;a={commBase:0,funcInfo:{},codeStartIdx:-1,codePaddingSize:0,sha:null,codeStartAddrPadded:void 0,hexlines:void 0,jmpStartAddr:void 0,jmpStartIdx:void 0,codeStartAddr:void 0,elfInfo:void 0,espInfo:void 0},i.length>10&&(i=[]),i.push(a);let r=n.functions;a.commBase=n.commBase||0,a.sha=n.sha;const u=n.hexinfo.hex;if(a.hexlines=u,t.target.nativeType==t.NATIVE_TYPE_VM){a.codeStartAddr=0,a.codeStartAddrPadded=0,a.jmpStartAddr=-1,a.jmpStartIdx=-1;for(let e of r)a.funcInfo[e.name]=e,e.value=16777215;if(t.target.useESP){const e=pxt.esp.parseB64(u),r=t.U.fromHex(l),i=(e,t)=>{for(let n=0;n<r.length;++n)if(e[t+n]!=r[n])return!1;return!0},o=e.segments.filter((e=>e.isDROM));t.U.assert(1==o.length);let s=!1;const c=o[0];a.codeStartAddr=c.addr+c.data.length,a.codeStartAddrPadded=a.codeStartAddr+255&-256,a.codePaddingSize=a.codeStartAddrPadded-a.codeStartAddr,pxt.debug(`user code start: 0x${a.codeStartAddrPadded.toString(16)}; dromlen=${c.data.length} pad=${a.codePaddingSize}`);for(let e=0;e<c.data.length;e+=32)if(i(c.data,e)){s=!0,e+=r.length;const t=e;for(let t of n.vmPointers||[])"0"!=t&&(t=t.replace(/^&/,""),a.funcInfo[t]={name:t,argsFmt:[],value:pxt.HF2.read32(c.data,e)},e+=4);pxt.HF2.write32(c.data,t,a.codeStartAddrPadded);break}t.U.assert(s||0==(n.vmPointers||[]).length),a.espInfo=e,a.codeStartAddrPadded=0}return}if(u.length<=2){const e=t.U.fromHex(u[0]);if(e[2]<=2&&96==e[3]){const t=1610612736,n=4096,r=e.length+n-1&~(n-1);a.elfInfo={template:e,imageMemStart:t+r,imageFileStart:r,phOffset:-1e3}}else a.elfInfo=pxt.elf.parse(e);a.codeStartAddr=a.elfInfo.imageMemStart,a.codeStartAddrPadded=a.elfInfo.imageMemStart;let n=u[0].indexOf(l);return n<0&&t.oops("no jmp table in elf"),a.jmpStartAddr=n/2,a.jmpStartIdx=-1,h(u[0].slice(n+32,n+32+8*r.length+16)),void y()}!function(e){for(let n=0;n<e.length;++n)if("2"==e[n][8]){let r=/^:02....02(....)..$/.exec(e[n]);t.U.assert(!!r);let i=16*parseInt(r[1],16);t.U.assert(0==(65535&i)),e[n]=p([2,0,0,4,0,i>>16])}}(u);let d=0,f="0000",_=0,m=0;a.codeStartAddr=0;let g=()=>{if(!a.codeStartAddr){let n=s(u[m]),r=16-(_+n[0]&15)&15;if(r)if(15&n[2]){let e=_+n[0],t=[r,e>>8,255&e,0];for(let e=0;e<r;++e)t.push(0);m++,u.splice(m,0,p(t)),a.codeStartAddr=e+r}else{if(16!=n[0]){for(n.pop(),n[0]=16;n.length<20;)n.push(0);u[m]=p(n)}a.codeStartAddr=_+16}else a.codeStartAddr=_+n[0];a.codeStartIdx=m+1;const i=c(e);a.codeStartAddrPadded=(a.codeStartAddr&~(i-1))+i;const o=a.codeStartAddrPadded-a.codeStartAddr;t.assert(0==(15&o)),a.codePaddingSize=o}};for(;d<u.length;++d){let t=/:02000004(....)/.exec(u[d]);if(t&&(f=t[1]),t=/^:..(....)00/.exec(u[d]),t){let n=parseInt(f+t[1],16);!e.flashUsableEnd&&_&&n-_>65536&&g(),e.flashUsableEnd&&n>=e.flashUsableEnd&&g(),m=d,_=n}/^:00000001/.test(u[d])&&g(),t=/^:10....000108010842424242010801083ED8E98D/.exec(u[d]),t&&(a.jmpStartAddr=_,a.jmpStartIdx=d)}pxt.debug(`code start: ${a.codeStartAddrPadded}, jmptbl: ${a.jmpStartAddr}`),a.jmpStartAddr||t.oops("No hex start"),a.codeStartAddr||t.oops("No hex end"),a.funcInfo={};for(let e=a.jmpStartIdx+1;e<u.length;++e){let t=/^:..(....)00(.{4,})/.exec(u[e]);if(t&&(h(t[2]),0==r.length))break}return void y();function h(n){let i=e.shortPointers?4:8;for(;n.length>=i;){let s=n.slice(0,i),c=parseInt(o(s),16);n=n.slice(i);let l=r.shift();if(!l)break;a.funcInfo[l.name]=l,c||t.U.oops("No value for "+l.name+" / "+s),0==l.argsFmt.length?c^=1:e.runtimeIsARM||e.nativeType!=t.NATIVE_TYPE_THUMB||1&c||t.U.oops("Non-thumb addr for "+l.name+" / "+s),l.value=c}}function y(){r.length&&t.oops("premature EOF in hex file; missing: "+r.map((e=>e.name)).join(", "))}},e.validateShim=function(e,r,i,a,o){if("TD_ID"==r||"TD_NOOP"==r||"ENUM_GET"==r)return;if(t.U.lookup(n,r))return;let s=`${e}(...) (shim=${r})`,c=u(r);if(c){a?"V"==c.argsFmt[0]&&t.U.userError("expecting function for "+s):"V"!=c.argsFmt[0]&&t.U.userError("expecting procedure for "+s);for(let e=0;e<o.length;++e){c.argsFmt[e+1]||t.U.userError("excessive parameters passed to "+s)}o.length!=c.argsFmt.length-1&&t.U.userError(`not enough arguments for ${s} (got ${o.length}; fmt=${c.argsFmt.join(",")})`)}else t.U.userError("function not found: "+s)},e.lookupFunc=u,e.lookupFunctionAddr=function(e){if("_pxt_comm_base"==e)return a.commBase;let t=u(e);return t?t.value:null},e.hexTemplateHash=d,e.hexPrelude=function(){return` .startaddr 0x${a.codeStartAddrPadded.toString(16)}\n`},e.hexBytes=p,e.patchHex=function(e,n,i,s){let c=a.hexlines.slice(0,a.codeStartIdx);if(!e.target.useESP){let r=2*n.length+7>>3;t.assert(r<64e3,"program too large, bytes: "+2*n.length),n[17]=r,n[20]=e.commSize}let l=[];for(let e=0;e<a.codePaddingSize>>1;++e)l.push(0);n=l.concat(n);let u=0;function f(e,t){let n=[16,t>>8&255,255&t,0];for(let t=0;t<8;++t)n.push(255&(e[u]||0)),n.push((e[u]||0)>>>8),u++;return n}let _=[16912,0,65535&a.codeStartAddrPadded,a.codeStartAddrPadded>>>16],m=d();for(let e=0;e<4;++e)_.push(parseInt(o(m.slice(4*e,4*e+4)),16));let g=s?t.UF2.newBlockFile(t.target.uf2Family):null;if(a.elfInfo){let r=new Uint8Array(2*n.length);for(let e=0;e<n.length;++e)pxt.HF2.write16(r,2*e,n[e]);let i=pxt.elf.patch(a.elfInfo,r);for(let e=0;e<_.length;++e)pxt.HF2.write16(i,2*e+a.jmpStartAddr,_[e]);if(g&&!e.target.switches.rawELF){let n=e.options.name||"pxt";return n=n.replace(/[^a-zA-Z0-9\-\.]+/g,"_"),g.filename="Projects/"+n+".elf",t.UF2.writeBytes(g,0,i),[t.UF2.serializeFile(g)]}return[t.U.uint8ArrayToString(i)]}if(a.espInfo){const i=pxt.esp.cloneStruct(a.espInfo),o=i.segments.find((e=>e.isDROM));let s=o.data.length;const c=new Uint8Array(s+2*n.length+255&-256);c.set(o.data);for(let e=0;e<n.length;++e)pxt.HF2.write16(c,s,n[e]),s+=2;o.data=c;const l=pxt.esp.toBuffer(i);return g?(t.UF2.writeBytes(g,0,l),r(g,e),[t.UF2.serializeFile(g)]):[t.U.uint8ArrayToString(l)]}if(g){if(t.UF2.writeHex(g,c),t.UF2.writeBytes(g,a.jmpStartAddr,f(_,a.jmpStartIdx).slice(4)),e.checksumBlock){let n=[];for(let t of e.checksumBlock)n.push(255&t,t>>8);t.UF2.writeBytes(g,e.target.flashChecksumAddr,n)}}else c[a.jmpStartIdx]=p(f(_,a.jmpStartAddr)),e.checksumBlock&&t.U.oops("checksum block in HEX not implemented yet");u=0,i&&(c=[]);let h=a.codeStartAddr,y=h-16>>16;for(;u<n.length;)g?t.UF2.writeBytes(g,h,f(n,h).slice(4)):(h>>16!=y&&(y=h>>16,c.push(p([2,0,0,4,y>>8,255&y]))),c.push(p(f(n,h)))),h+=16;if(!i){let e=a.hexlines.slice(a.codeStartIdx);g?t.UF2.writeHex(g,e):t.Util.pushRange(c,e)}if(!g&&e.target.moveHexEof){for(;!c[c.length-1];)c.pop();":00000001FF"==c[c.length-1]&&c.pop()}if(e.packedSource)if(g)r(g,e);else{let t=0;for(let n=0;n<e.packedSource.length;n+=16){let r=[16,t>>8&255,255&t,14];for(let t=0;t<16;++t)r.push(255&(e.packedSource.charCodeAt(n+t)||0));c.push(p(r)),t+=16}}return!g&&e.target.moveHexEof&&c.push(":00000001FF"),g?[t.UF2.serializeFile(g)]:c}}(n=t.hexfile||(t.hexfile={})),t.hexDump=function(e,t=0){function n(e,t=8){let n=e.toString(16);for(;n.length<t;)n="0"+n;return n}let r="";for(let i=0;i<e.length;i+=16){r+=n(t+i)+": ";let a="";for(let t=0;t<16;t++){0==(3&t)&&(r+=" ");let o=e[i+t];null!=o?(r+=n(o,2)+" ",a+=32<=o&&o<127?String.fromCharCode(o):"."):r+=" "}r+=" "+a+"\n"}return r},t.asmline=function(e){return e.indexOf("\n")>=0?(e=e.replace(/^\s*/gm,"").replace(/^(.*)$/gm,((e,t)=>";"==t[0]&&" "==t[1]||/:\*$/.test(t)?t:" "+t)))+"\n":(/(^[\s;])|(:$)/.test(e)||(e=" "+e),e+"\n")},t.firstMethodOffset=function(){return 9};const i=[21078089,22513679,15655169,18636881,19658081,21486649,21919277,20041213,20548751,16180187,18361627,19338023,19772677,16506547,23530697,22998697,21225203,19815283,23679599,19822889,21136133,19540043,21837031,18095489,23924267,23434627,22582379,21584111,22615171,23403001,19640683,19998031,18460439,20105387,17595791,16482043,23199959,18881641,21578371,22765747,20170273,16547639,16434589,21435019,20226751,19506731,21454393,23224541,23431973,23745511];function a(e){let n=32;t.U.assert(t.U.unique(e,(e=>""+e)).length==e.length,"non unique");for(let r=2;;r<<=1){if(n--,r<e.length)continue;let a,o=-1,s=-1;for(let c of i){let i=c<<8|n,l=new Uint16Array(r+t.vtLookups+1);t.U.assert(0==(1&l.length));let u=0,d=[];for(let r of e){t.U.assert(r>0);let e=Math.imul(r,i)>>>n;d.push(e);let a=!1;for(let n=0;n<t.vtLookups;n++){if(!l[e+n]){a=!0,l[e+n]=r;break}u++}if(!a){u=-1;break}}(-1==o||o>u)&&(o=u,s=i,a=l)}if(o>=0)return{mult:s,mapping:a,size:r}}}function o(e,n,r){const i=a(e.itable.map((e=>e.idx)));let o=t.target.shortPointers?".short":".word",s=`\n .balign 4\n${e.id}_VT:\n .short ${4*e.allfields.length+4} ; size in bytes\n .byte ${pxt.ValTypeObject}, ${pxt.VTABLE_MAGIC} ; magic\n ${o} ${e.id}_IfaceVT\n .short ${e.classNo} ; class-id\n .short 0 ; reserved\n .word ${i.mult} ; hash-mult\n`,c=e=>{"0"!=e&&(e+="@fn"),s+=` ${o} ${e}\n`};c("pxt::RefRecord_destroy"),c("pxt::RefRecord_print"),c("pxt::RefRecord_scan"),c("pxt::RefRecord_gcsize");let l=e.toStringMethod;c(l?l.vtLabel():"0");for(let t of e.vtable)c(t.label()+"_nochk");s+=`\n .balign ${t.target.shortPointers?2:4}\n${e.id}_IfaceVT:\n`;const u=2*i.mapping.length;let d="",p=u,f={};for(let t of e.itable){f[t.idx+""]=p;const e=t.proc?t.proc.isGetter()?1:2:0;d+=` .short ${t.idx}, ${e} ; ${t.name}\n`,d+=` .word ${t.proc?t.proc.vtLabel()+"@fn":t.info}\n`,p+=8,t.setProc&&(d+=` .short ${t.idx}, 0 ; set ${t.name}\n`,d+=` .word ${t.setProc.vtLabel()}@fn\n`,p+=8)}d+=" .word 0, 0 ; the end\n",p+=8;let _=i.mapping;for(let e=0;e<_.length;++e)r.itEntries++,_[e]&&r.itFullEntries++;return s+=" .short "+t.U.toArray(_).map(((e,t)=>(f[e+""]||u)-2*t)).join(", ")+"\n",s+=d,s+="\n",s}t.vtLookups=3,t.computeHashMultiplier=a,t.vtableToAsm=o;const s=["GC"];function c(e,r){let i=`\n .short ${e.globalsWords} ; num. globals\n .short 0 ; patched with number of 64 bit words resulting from assembly\n .word _pxt_config_data\n .short 0 ; patched with comm section size\n .short ${e.nonPtrGlobals} ; number of globals that are not pointers (they come first)\n .word _pxt_iface_member_names\n .word _pxt_lambda_trampoline@fn\n .word _pxt_perf_counters\n .word _pxt_restore_exception_state@fn\n .word ${e.emitString(e.getTitle())} ; name\n`,a=null;a=new t.ThumbSnippets;const c=e.setPerfCounters(s);e.procs.forEach((n=>{let r=new t.ProctoAssembler(a,e,n);i+="\n"+r.getAssembly()+"\n"}));let l=new t.ProctoAssembler(a,e,null);l.emitHelpers(),i+="\n"+l.getAssembly()+"\n",i+=n.asmTotalSource,i+="_code_end:\n\n",t.U.iterMap(e.codeHelpers,((e,t)=>{i+=` .section code\n${t}:\n${e}\n`})),i+=a.arithmetic(),i+="_helpers_end:\n\n",e.usedClassInfos.forEach((t=>{i+=o(t,0,e)})),i+="\n.balign 4\n_pxt_iface_member_names:\n",i+=` .word ${e.ifaceMembers.length}\n`;let u=0;for(let t of e.ifaceMembers){let n=e.emitString(t);i+=` .word ${n} ; ${u++} .${t}\n`}i+=" .word 0\n",i+="_vtables_end:\n\n",i+="\n.balign 4\n_pxt_config_data:\n";const d=e.res.configData||[];for(let e of d)i+=` .word ${e.key}, ${e.value} ; ${e.name}=${e.value}\n`;i+=" .word 0\n\n",function(e,n){const r=t.U.unique(n.ifaceMembers.concat(Object.keys(n.strings)),(e=>e));for(let t of r)n.otherLiterals.push(e.string_literal(n.strings[t],t));for(let t of Object.keys(n.doubles)){let r=n.doubles[t];n.otherLiterals.push(`\n.balign 4\n${r}: ${e.obj_header("pxt::number_vt")}\n .hex ${t}\n`)}for(let t of Object.keys(n.hexlits))n.otherLiterals.push(e.hex_literal(n.hexlits[t],t)),n.otherLiterals.push()}(a,e),i+=e.otherLiterals.join(""),i+="\n.balign 4\n.section code\n_pxt_perf_counters:\n",i+=` .word ${c.length}\n`;let p="";for(let e=0;e<c.length;++e){let t=".perf"+e;i+=` .word ${t}\n`,p+=`${t}: .string ${JSON.stringify(c[e])}\n`}return i+=p,i+="_literals_end:\n",i}function l(e){let r;return r=e.nativeType==t.NATIVE_TYPE_VM?new t.assembler.VMFile(new t.vm.VmProcessor(e)):new t.assembler.File(new t.thumb.ThumbProcessor),r.ei.testAssembler(),e.switches.noPeepHole&&(r.disablePeepHole=!0),r.lookupExternalLabel=n.lookupFunctionAddr,r.normalizeExternalLabel=e=>{let t=n.lookupFunc(e);return t?t.name:e},r}function u(e){if(e.errors.length>0){let n="";throw e.errors.forEach((e=>{let r=/^user(\d+)/.exec(e.scope);if(r){parseInt(r[1]);n+=t.U.lf("At inline assembly:\n"),n+=e.message}})),n?(console.log(t.U.lf("errors in inline assembly")),console.log(n),new Error(e.errors[0].message)):new Error(e.errors[0].message)}}t.processorInlineAssemble=function(e,t){let n=l(e);n.disablePeepHole=!0,n.emit(t),u(n);let r=[];for(let e=0;e<n.buf.length;e+=2)r.push(((n.buf[e+1]||0)<<16|n.buf[e])>>>0);return r};function d(e,t,n){let r=l(e);return r.emit(n),n=`; Interface tables: ${t.itFullEntries}/${t.itEntries} (${Math.round(100*t.itFullEntries/t.itEntries)}%)\n; Virtual methods: ${t.numVirtMethods} / ${t.numMethods}\n`+r.getSource(!0,t.numStmts,e.flashEnd),u(r),{src:n,buf:r.buf,thumbFile:r}}function p(r,i,a,o){const s=a.extinfo.disabledDeps;r=s?`${n.hexPrelude()}\n; compilation disabled on this variant due to ${a.extinfo.disabledDeps}\n.hex 718E3B92C615A841C49866C975EE5197\n.string "${a.extinfo.disabledDeps}"`:`; start\n${n.hexPrelude()}\n .hex 708E3B92C615A841C49866C975EE5197 ; magic number\n .hex ${n.hexTemplateHash()} ; hex template hash\n .hex 873266330af9dbdb ; replaced in binary by program hash\n`+r,a.embedBlob&&(i.packedSource=function(e,n){let r=t.Util.toUTF8(e),i=(r.length,n.length,"A/¸/¢»");return i+=t.U.uint8ArrayToString([255&r.length,r.length>>8,255&n.length,n.length>>8,0,0,0,0]),i+=r,i+=n,i.length%2&&(i+="\0"),i}(a.embedMeta,e.pxtc.decodeBase64(a.embedBlob)),!i.target.noSourceInFlash&&i.packedSource.length<4e4&&(r+=function(e){let t="";for(let n=0;n<e.length;++n){let r=255&e.charCodeAt(n);t+=r<=15?"0"+r.toString(16):r.toString(16)}return`\n .balign 16\n_stored_program: .hex ${t}\n`}(i.packedSource),i.packedSource=null));const c=n.flashCodeAlign(a.target);if(!s&&a.target.flashChecksumAddr){let e=0;for(;c>1<<e;)e++;let t=parseInt(n.hexTemplateHash().slice(8,16),16);const i=n.getStartAddress()/c;t=4294967040&t|e;let o=0,s=i;a.target.flashChecksumAddr<n.getStartAddress()&&(o=Math.ceil((a.target.flashChecksumAddr+32)/c),s-=o),r+=`\n .balign 4\n__end_marker:\n .word ${t}\n\n; ------- this will get removed from the final binary ------\n__flash_checksums:\n .word 0x87eeb07c ; magic\n .word __end_marker ; end marker position\n .word ${t} ; end marker\n ; template region\n .short ${o}, ${s}\n .word 0x${n.hexTemplateHash().slice(0,8)}\n ; user region\n .short ${i}, 0xffff\n .hex 87326633 ; replaced later\n .word 0x0 ; terminator\n`}const l=a.extinfo.outputPrefix||"";i.writeFile(l+t.BINARY_ASM,r);const u=d(a.target,i,r);if(u.thumbFile.commPtr&&(i.commSize=u.thumbFile.commPtr-n.getCommBase()),u.src&&i.writeFile(l+t.BINARY_ASM,u.src),s)return void f();const p=o.configData||[];if(p.some((e=>"BOOTLOADER_BOARD_ID"==e.name))){let e="const uint32_t configData[] = {\n";e+=" 0x1e9e10f1, 0x20227a79, // magic\n",e+=` ${p.length}, 0, // num. entries; reserved\n`;for(let t of p)e+=` ${t.key}, 0x${t.value.toString(16)}, // ${t.name}\n`;e+=" 0, 0\n};\n",i.writeFile(l+"config.c",e)}if(u.buf){const e=u.buf;let n="";for(let t=0;t<e.length;++t)n+=String.fromCharCode(255&e[t],e[t]>>8);const r=t.U.sha256(n).slice(0,16),o=t.U.range(4).map((e=>parseInt(r.slice(2*e,2*e+2),16)));t.U.assert(12935==e[12]);for(let t=0;t<o.length;++t)e[12+t]=o[t];if(a.target.flashChecksumAddr){let n=u.thumbFile.lookupLabel("__flash_checksums")/2;t.U.assert(n==e.length-16);let r=e.slice(e.length-16);e.splice(e.length-16,16);let a=Math.ceil(2*e.length/c);t.U.assert(12935==r[r.length-4]),r[r.length-4]=o[0],r[r.length-3]=o[1],r[r.length-5]=a,i.checksumBlock=r}f()}if(!o.procDebugInfo){for(let e of o.breakpoints){let n=t.U.lookup(u.thumbFile.getLabels(),"__brkp_"+e.id);null!=n&&(e.binAddr=n)}for(let e of i.procs)e.fillDebugInfo(u.thumbFile);if(o.procDebugInfo=i.procs.map((e=>e.debugInfo)),i.target.switches.size){const n=[];for(const r of i.procs){const i=e.pxtc.nodeLocationInfo(r.action),a=[i.fileName.replace("pxt_modules/",""),t.getDeclName(r.action),r.debugInfo.size,"function",i.line+1];n.push(a.map((e=>`"${e}"`)).join(","))}n.sort(),n.unshift("filename,name,size,type,line"),i.writeFile(l+"size.csv",n.join("\n"))}}function f(){if(pxt.isOutputText(t.target)){const e=n.patchHex(i,u.buf,!1,!1).join("\r\n")+"\r\n";i.writeFile(l+pxt.outputName(t.target),e)}else{const r=e.pxtc.encodeBase64(n.patchHex(i,u.buf,!1,!!t.target.useUF2)[0]);i.writeFile(l+pxt.outputName(t.target),r)}}}t.assemble=d,t.processorEmit=function(e,r,i){const a=c(e),o=t.U.flatClone(r);n.setupFor(r.target,r.extinfo||t.emptyExtInfo()),p(a,e,r,i);const s=o.otherMultiVariants||[];if(s.length)try{for(let r of s){const s=t.U.flatClone(o);s.extinfo=r.extinfo,r.target.isNative=!0,s.target=r.target,n.setupFor(s.target,s.extinfo),p(a,e,s,i)}}finally{n.setupFor(o.target,o.extinfo)}},t.validateShim=n.validateShim}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){e.getHelpForKeyword=function(e,t){const n={abstract:null,any:null,as:null,break:null,case:null,catch:null,class:null,continue:null,const:null,constructor:null,debugger:null,declare:null,delete:null,do:null,else:null,enum:null,export:null,extends:null,false:lf("Represents the negative outcome of a logical expression"),finally:null,for:null,from:null,function:null,get:null,if:null,implements:null,in:null,instanceof:null,interface:null,is:null,let:null,namespace:null,new:null,null:null,private:null,protected:null,public:null,return:null,set:null,static:null,super:null,switch:null,this:null,throw:null,true:lf("Represents the positive outcome of a logical expression"),try:null,type:null,typeof:null,undefined:null,void:null,while:null,with:null,of:null};if(t){return{True:n.true,False:n.false,None:null,abs:null,all:null,any:null,ascii:null,bin:null,bool:null,bytearray:null,bytes:null,callable:null,chr:null,classmethod:null,compile:null,complex:null,copyright:null,credits:null,delattr:null,dict:null,dir:null,divmod:null,enumerate:null,eval:null,exec:null,exit:null,filter:null,float:null,format:null,frozenset:null,getattr:null,globals:null,hasattr:null,hash:null,help:null,hex:null,id:null,input:null,int:null,isinstance:null,issubclass:null,iter:null,len:null,license:null,list:null,locals:null,map:null,max:null,memoryview:null,min:null,next:null,object:null,oct:null,open:null,ord:null,pow:null,print:null,property:null,quit:null,range:null,repr:null,reversed:null,round:null,set:null,setattr:null,slice:null,sorted:null,staticmethod:null,str:null,sum:null,super:null,tuple:null,type:null,vars:null}[e]}return n[e]}}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){e.LSHost=class{constructor(e){this.p=e}getCompilationSettings(){const e=this.p.getCompilerOptions();return e.noLib=!0,e}getNewLine(){return"\n"}getScriptFileNames(){return this.p.getSourceFiles().map((e=>e.fileName))}getScriptVersion(e){return"0"}getScriptSnapshot(e){const t=this.p.getSourceFile(e);return{getLength:()=>t.getFullText().length,getText:()=>t.getFullText(),getChangeRange:()=>{}}}getCurrentDirectory(){return"."}getDefaultLibFileName(e){return""}useCaseSensitiveFileNames(){return!0}}}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){!function(n){function r(e){var t,r;const i=null===(r=null===(t=null==e?void 0:e.pxt)||void 0===t?void 0:t.callInfo)||void 0===r?void 0:r.qName;return n.lastApiInfo.apis.byQName[i]}function i(e,t,r){if(!e||t<0)return;let i=e.parameters[t];if(e.attributes._def){const a=e.attributes._def.parameters[t].shadowBlockId;if(a){const e=r.blocksById[a],t=n.lastApiInfo.apis.byQName[e.qName];"TD_ID"===t.attributes.shim&&1===t.parameters.length&&(i=t.parameters[0])}}return i}function a(r,i,a,o,s=!1){const c={};o.forEach((e=>{var t,n;let r=e.symbol.retType;if(s)if(7==e.symbol.kind)r=e.symbol.namespace;else if(4==e.symbol.kind){const i=null===(n=null===(t=e.symbol.attributes)||void 0===t?void 0:t.enumIdentity)||void 0===n?void 0:n.split(".");(null==i?void 0:i.length)>1&&(r=i[0])}c[r]=[...c[r]||[],e]}));const l=c[r]||[];let u=[];for(let r of l){const o=m(r.symbol,i,e.SymbolFlags.Enum);if(o){const e=a.getTypeOfSymbolAtLocation(o,i),r=t.getEnumMembers(a,e).map((e=>t.enumMemberToQName(a,e))).map((e=>n.lastApiInfo.apis.byQName[e]));u=[...u,...r]}}return[...l,...p(u,1)]}function o(t){return t.flags&e.SymbolFlags.Variable?4:t.flags&e.SymbolFlags.Class?8:t.flags&e.SymbolFlags.Enum?6:t.flags&e.SymbolFlags.EnumMember?7:t.flags&e.SymbolFlags.Method?1:t.flags&e.SymbolFlags.Module?5:t.flags&e.SymbolFlags.Property?2:0}function s(e){return{kind:0,name:e,pyName:e,qName:e,pyQName:e,namespace:"",attributes:{callingConvention:0,paramDefl:{}},fileName:pxt.MAIN_TS,parameters:[],retType:"any"}}function c(e,t){var n,r;let i=e.getName(),a=/(.*)\.(.*)/.exec(i),s=a?a[2]:i,c=a?a[1]:"",l=null!==(r=null===(n=t.getSymbol())||void 0===n?void 0:n.getName())&&void 0!==r?r:"any";return{kind:o(e),name:s,pyName:s,qName:i,pyQName:i,namespace:c,attributes:{callingConvention:0,paramDefl:{}},fileName:pxt.MAIN_TS,parameters:[],retType:l}}function l(e,t,n){if(e)return t.byQName[n.getFullyQualifiedName(e)]}function u(e,n){return e.weight!==n.weight?n.weight-e.weight:t.compareSymbols(e.symbol,n.symbol)}function d(e,t){return{symbol:e,weight:t}}function p(e,t){return e.map((e=>d(e,t)))}function f(t,n){var r;if(t.flags&e.TypeFlags.NumberLiteral)return"Number";if(t.flags&e.TypeFlags.StringLiteral)return"String";if(t.flags&e.TypeFlags.BooleanLiteral)return"Boolean";const i=n.typeToString(t);return null!==(r={number:"Number",string:"String",boolean:"Boolean"}[i])&&void 0!==r?r:i}function _(e,t){return"."===t.charAt(0)&&(t=t.substr(1)),e.substr(0,e.lastIndexOf(".")+1)+t}function m(e,t,r){const i=n.service&&n.service.getProgram().getTypeChecker();if(!i)return null;const a=i.getSymbolsInScope(t,r);for(let t of a)if(t.escapedName.toString()===e.qName)return t;return null}function g({symbol:e}){return!(/^__/.test(e.name)||/^__/.test(e.namespace)||e.attributes.hidden||e.attributes.deprecated||"TD_ID"==e.attributes.shim||e.attributes.blockAliasFor)}n.getCallSymbol=r,n.getParameter=i,n.getApisForTsType=a,n.getBasicKindDefault=function(e,n){switch(e){case t.SK.StringKeyword:return'""';case t.SK.NumberKeyword:return"0";case t.SK.BooleanKeyword:return n?"False":"false";case t.SK.ArrayType:return"[]";case t.SK.NullKeyword:return n?"None":"null";default:return}},n.tsSymbolToPxtSymbolKind=o,n.makePxtSymbolFromKeyword=s,n.makePxtSymbolFromTsSymbol=c,n.getPxtSymbolFromTsSymbol=l,n.compareCompletionSymbols=u,n.completionSymbol=d,n.completionSymbols=p,n.getNodeAndSymbolAtLocation=function(e,n,r,i){const a=e.getSourceFile(n),o=e.getTypeChecker(),s=t.findInnerMostNodeAtPosition(a,r);if(s){const e=o.getSymbolAtLocation(s);if(e){return[s,l(e,i,o)]}}return null},n.tsTypeToPxtTypeString=f,n.filenameWithExtension=_,n.getWordAtPosition=function(e,t){let n=t,r=t;for(;n>0&&i(n);)--n;for(;r<e.length-1&&i(r);)++r;return n!=r?{text:e.substring(n+1,r),start:n+1,end:r}:null;function i(t){const n=e.charCodeAt(t);return n>=65&&n<=90||n>=97&&n<=122}},n.getTsSymbolFromPxtSymbol=m,n.getDefaultEnumValue=function(e,r){const i=n.service&&n.service.getProgram().getTypeChecker(),a=t.getEnumMembers(i,e);for(const e of a)if(e.name.kind===t.SK.Identifier){const a=t.enumMemberToQName(i,e),o=n.lastApiInfo.apis.byQName[a];return o?o.attributes.alias?r&&o.attributes.pyAlias||o.attributes.alias:r?o.pyQName:o.qName:a}return"0"},n.getCompletions=function(o){var m,h;const{fileName:y,fileContent:v,position:b,wordStartPos:x,wordEndPos:k,runtime:S}=o;let T=v;v&&n.host.setFile(y,v);const C=_(y,"ts"),E={startPos:x,endPos:k},D=/\.py$/.test(y),A={entries:[],isMemberCompletion:!1,isNewIdentifierLocation:!0,isTypeLocation:!1,namespace:[]};let N=T.lastIndexOf("\n",b-1);N=Math.max(0,N);const w=T.substring(N+1,b),I=D?"#":"//";if(w.trim().startsWith(I))return A;let P=-1,O=-1;for(let e=b-1;e>=0;--e){if("."==T[e]){P=e;break}if(!/\w/.test(T[e]))break;-1==O&&(O=e)}P==b-1?T=T.slice(0,b)+"_"+T.slice(b):-1==O&&(T=T.slice(0,b)+"_"+T.slice(b),O=b);const F=-1!==P;A.isMemberCompletion=F;const L=F?T.slice(P+1,k):T.slice(x,k);F&&(O=P);const R={};let M=n.cloneCompileOpts(n.host.opts);M.fileSystem[y]=T,n.addApiInfo(M),M.syntaxInfo={position:O,type:A.isMemberCompletion?"memberCompletion":"identifierCompletion"};let U,B=[];if(D){const e=t.transpile.pyToTs(M);if(e.syntaxInfo&&e.syntaxInfo.symbols&&(B=p(e.syntaxInfo.symbols,1)),e.globalNames&&(n.lastGlobalNames=e.globalNames),!B.length&&e.globalNames&&(B=p(pxt.U.values(e.globalNames),1)),Object.keys(e.outfiles).forEach((t=>{t===C&&n.host.setFile(t,e.outfiles[t])})),e.sourceMap){const n=T,r=e.outfiles[C]||"",i=t.BuildSourceMapHelpers(e.sourceMap,r,n).py.smallestOverlap(E);i&&(U=i.ts.startPos)}!F&&B.length>50&&(B=B.filter((e=>(D?e.symbol.pyQName:e.symbol.qName).toLowerCase().indexOf(L.toLowerCase())>=0))),M.ast=!0;t.compile(M,n.service)}else{U=b,M.ast=!0,n.host.setOpts(M);n.runConversionsAndCompileUsingService()}const $=n.service.getProgram(),j=$.getSourceFile(C),K=$.getTypeChecker();let z=t.findInnerMostNodeAtPosition(j,U);if(t.decompiler.buildCommentMap(j).some((e=>e.start<=b&&b<=e.end)))return A;if(z){if([t.SK.StringLiteral,t.SK.FirstTemplateToken,t.SK.NoSubstitutionTemplateLiteral].some((e=>z.kind===e)))return A}A.namespace=t.getCurrentNamespaces(z);let J=!1;if(F){const e=t.findInnerMostNodeAtPosition(j,D?U:P-1);if(e){let t;const r=K.getSymbolAtLocation(e);if(t=(null===(m=null==r?void 0:r.members)||void 0===m?void 0:m.size)>0?K.getDeclaredTypeOfSymbol(r):r?K.getTypeOfSymbolAtLocation(r,e):K.getTypeAtLocation(e),t){const e=t.symbol?K.getFullyQualifiedName(t.symbol):f(t,K);if(e){B=t.getApparentProperties().map((t=>e+"."+t.getName())).map((e=>n.lastApiInfo.apis.byQName[e])).filter((e=>!!e)).map((e=>d(e,1))),J=!0}}}}const q=pxt.U.values(n.lastApiInfo.apis.byQName);if(0===B.length){B=p(q.filter((e=>(D?e.pyQName:e.qName).toLowerCase().indexOf(L.toLowerCase())>=0)),1)}if(!D&&!J){z=t.findInnerMostNodeAtPosition(j,x),z||(z=j.getSourceFile());let r=e.SymbolFlags.Variable,i=K.getSymbolsInScope(z,r),a=z.getText();"_"!==a&&(i=i.filter((e=>e.name.indexOf(a)>=0)));let o=i.map((e=>{let t=l(e,n.lastApiInfo.apis,K);if(!t){t=c(e,K.getTypeOfSymbolAtLocation(e,z))}return t})).filter((e=>!!e)).map((e=>d(e,1)));o.forEach((e=>e.weight+=5)),B=[...B,...o]}const V=t.getParentCallExpression(z);if(V){let e=t.findCurrentCallArgIdx(V,z,U);if(e>=0){const t=n.blocksInfoOp(n.lastApiInfo.apis,S.bannedCategories),o=r(V);if(o){e>=o.parameters.length&&(e=o.parameters.length-1);const n=i(o,e,t);if(n){a(n.type,V,K,B,n.isEnum).forEach((e=>e.weight=10))}}}}if(!F){let e;if(D){let t=pxt.py.keywords;e=Object.keys(t)}else e=[...ts.pxtc.reservedWords,...ts.pxtc.keywordTypes];let t=e.filter((e=>e.indexOf(L)>=0)).map(s).map((e=>d(e,0)));B=[...B,...t]}let H={};H=D&&n.lastGlobalNames?n.lastGlobalNames:n.lastApiInfo.apis.byQName,B.map((e=>!e.symbol.attributes.alias||F&&7===e.symbol.kind?e:d(n.lastApiInfo.apis.byQName[e.symbol.attributes.alias],e.weight))).filter(g).forEach((e=>{R[e.symbol.qName]=e})),B=pxt.Util.values(R).filter((e=>!!e&&!!e.symbol)),B.sort(u),o.light&&B.length>100&&(B=B.splice(0,100));const{bannedCategories:G,screenSize:W}=o.runtime,Q={takenNames:H,blocksInfo:n.blocksInfoOp(n.lastApiInfo.apis,G),screenSize:W,apis:n.lastApiInfo.apis,checker:null===(h=null===n.service||void 0===n.service?void 0:n.service.getProgram())||void 0===h?void 0:h.getTypeChecker()};return B.forEach((t=>function(t,r,i){const a=n.lastApiInfo.decls[t.qName];if(e.isFunctionLike(a)&&(t.snippetAddsDefinitions||r&&!t.pySnippet||!r&&!t.snippet)){const e=n.getSnippet(i,t,a,r),o=n.snippetStringify(e),s=n.snippetStringify(e,!0),c=n.snippetAddsDefinitions(e);r?(t.pySnippet=o,t.pySnippetWithMarkers=s):(t.snippet=o,t.snippetWithMarkers=s),t.snippetAddsDefinitions=c}}(t.symbol,D,Q))),A.entries=B.map((e=>e.symbol)),A}}(t.service||(t.service={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){let n=function(t){let n=i(t);e.sys.write(n)};function r(e){for(const t of e)n(t)}function i(n){let r;if(void 0!==n.file){let t=n;const{line:i,character:a}=e.getLineAndCharacterOfPosition(t.file,t.start),o=t.file.fileName;r=Object.assign({fileName:o,line:i,column:a},t)}else r=Object.assign({fileName:void 0,line:void 0,column:void 0},n);return function(n){let r="";n.fileName&&(r+=`${n.fileName}(${n.line+1},${n.column+1}): `);let i=e.sys?e.sys.newLine:"\n";const a=t.DiagnosticCategory[n.category].toLowerCase();return r+=`${a} TS${n.code}: ${t.flattenDiagnosticMessageText(n.messageText,i)}${i}`,r}(r)}function a(t,n){const r=e.createCompilerHost(n);return r.getDefaultLibFileName=()=>"node_modules/pxt-core/pxtcompiler/ext-typescript/lib/lib.d.ts",e.createProgram(t,n,r)}function o(e){let n=e.getSyntacticDiagnostics();return 0===n.length&&(n=e.getOptionsDiagnostics().concat(t.Util.toArray(e.getGlobalDiagnostics())),0===n.length&&(n=e.getSemanticDiagnostics())),n.slice(0)}t.getDiagnosticString=i,t.plainTscCompileDir=function(t){const i=e.parseCommandLine([]);let s=e.findConfigFile(t,e.sys.fileExists);const c=function(){let n=e.sys.readFile(s);const a=e.parseConfigFileTextToJson(s,n),o=a.config;if(!o)return r([a.error]),void e.sys.exit(e.ExitStatus.DiagnosticsPresent_OutputsSkipped);const c=e.parseJsonConfigFileContent(o,e.sys,t,i.options,s);if(c.errors.length>0)return r(c.errors),void e.sys.exit(e.ExitStatus.DiagnosticsPresent_OutputsSkipped);return c}();let l=a(c.fileNames,c.options);return o(l).forEach(n),l},t.plainTscCompileFiles=a,t.getProgramDiagnostics=o}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){function n(t){if(!t||!t.kind)return null;switch(t.kind){case e.SyntaxKind.StringKeyword:return"str";case e.SyntaxKind.NumberKeyword:return"number";case e.SyntaxKind.BooleanKeyword:return"bool";case e.SyntaxKind.VoidKeyword:return"None";case e.SyntaxKind.FunctionType:return function(e){let t=n(e.type);return`(${e.parameters.map((e=>e.type)).map(n).join(", ")}) -> ${t}`}(t);case e.SyntaxKind.ArrayType:return`List[${n(t.elementType)}]`;case e.SyntaxKind.TypeReference:{let e=t;return e.typeName&&e.typeName.getText?e.typeName.getText():""}case e.SyntaxKind.AnyKeyword:return"any";default:return pxt.tickEvent("depython.todo.tstypenodetopytype",{kind:t.kind}),""}}function r(t){if(!t||!t.flags)return null;switch(t.flags){case e.TypeFlags.String:return"str";case e.TypeFlags.Number:return"number";case e.TypeFlags.Boolean:return"bool";case e.TypeFlags.Void:return"None";case e.TypeFlags.Any:return"any";default:return pxt.tickEvent("depython.todo.tstypetopytype",{kind:t.flags}),""}}function i(i,a,o){function s(t,n,r=!1){let a=i.getTypeAtLocation(n);if(!a)return"None";r&&(a=a.getCallSignatures()[0].getReturnType());const o=i.typeToString(a,void 0,e.TypeFormatFlags.UseFullyQualifiedType);return/^\d/.test(o)?"number":"this"==o?l(i,a.symbol):o}let c=function(e){switch(e.kind){case t.SK.MethodDeclaration:case t.SK.MethodSignature:return 1;case t.SK.PropertyDeclaration:case t.SK.PropertySignature:case t.SK.GetAccessor:case t.SK.SetAccessor:return 2;case t.SK.Constructor:case t.SK.FunctionDeclaration:return 3;case t.SK.VariableDeclaration:return 4;case t.SK.ModuleDeclaration:return 5;case t.SK.EnumDeclaration:return 6;case t.SK.EnumMember:return 7;case t.SK.ClassDeclaration:return 8;case t.SK.InterfaceDeclaration:return 9;default:return 0}}(o);if(0!=c){let l=o,u=t.parseComments(l);if(u.weight<0)return null;let d,p=/^(.*)\.(.*)/.exec(a),f=3==c||1==c,_=null,m=null,g=e.getSourceFileOfNode(o);if(g){let e=/^pxt_modules\/([^\/]+)/.exec(g.fileName);e&&(_=e[1])}if(8==c||9==c){let e=o;if(d=[],e.heritageClauses)for(let t of e.heritageClauses)if(t.types)for(let e of t.types)d.push(s(0,e))}6!=c&&7!==c||(d||(d=[])).push("Number");let h={kind:c,qName:a,namespace:p?p[1]:"",name:p?p[2]:a,fileName:o.getSourceFile().fileName,attributes:u,pkg:_,pkgs:m,extendsTypes:d,retType:o.kind==e.SyntaxKind.Constructor?"void":5==c?"":s(l.type,l,f),parameters:f?t.Util.toArray(l.parameters).map(((a,o)=>{let c,l,d=t.getName(a),p=u.paramHelp[d]||"",f=u.paramMin&&u.paramMin[d],_=u.paramMax&&u.paramMax[d];/\beg\.?:\s*(.+)/.exec(p);if(a.type&&a.type.kind===t.SK.FunctionType){const n=i.getSignatureFromDeclaration(a.type).getParameters();"objectdestructuring"===u.mutate?(t.assert(n.length>0),c=i.getTypeAtLocation(n[0].valueDeclaration).getProperties().map((e=>({name:e.getName(),type:i.typeToString(i.getTypeOfSymbolAtLocation(e,n[0].valueDeclaration))})))):l=n.map(((t,n)=>({name:t.getName(),type:i.typeToString(i.getTypeOfSymbolAtLocation(t,a),void 0,e.TypeFormatFlags.UseFullyQualifiedType)})))}let m={};const g=i.getTypeAtLocation(a);let h=g&&!!(g.flags&(e.TypeFlags.Enum|e.TypeFlags.EnumLiteral));if(u.block&&u.paramShadowOptions){const e=[];u.block.replace(/%(\w+)/g,((t,n)=>(e.push(n),""))),u.paramShadowOptions[e[o]]&&(m.fieldEditorOptions={value:u.paramShadowOptions[e[o]]})}f&&(m.min={value:f}),_&&(m.max={value:_});const y=a.type&&n(a.type)||g&&r(g)||"unknown",v=a.initializer?a.initializer.getText():t.getExplicitDefault(u,d)||(a.questionToken?"undefined":void 0);return{name:d,description:p,type:s(a.type,a),pyTypeString:y,initializer:v,default:u.paramDefl[d],properties:c,handlerParameters:l,options:m,isEnum:h}})):null,snippet:e.isFunctionLike(o)?null:void 0};switch(h.kind){case 7:h.pyName=t.U.snakify(h.name).toUpperCase();break;case 4:case 1:case 2:case 3:h.pyName=t.U.snakify(h.name);break;case 6:case 8:case 9:case 5:default:h.pyName=h.name}return(o.kind===t.SK.GetAccessor||(o.kind===t.SK.PropertyDeclaration||o.kind===t.SK.PropertySignature)&&t.isReadonly(o))&&(h.isReadOnly=!0),h}return null}function a(e){return!!e.attributes.block&&!!e.attributes.blockId}let o;function s(e,n){function r(t){return-t(e)+t(n)}let i=r((e=>a(e)?1:-1));return i||(i=r((e=>e.namespace?-1:1)),i||(o||(o={},o[4]=100,o[5]=101,o[3]=99,o[2]=98,o[1]=97,o[8]=89,o[6]=81,o[7]=80),i=r((e=>o[e.kind]||0)),i||(i=r((e=>e.attributes.weight||50)),i||t.U.strcmp(e.name,n.name))))}function c(e,n,r=!1){const a={byQName:{},jres:n},o={},s=e.getTypeChecker(),c=e=>{var n,r;if(e.kind!=t.SK.VariableStatement){if(t.isExported(e)){if(!e.symbol)return void console.warn("no symbol",e);let c=l(s,e.symbol);e.kind==t.SK.SetAccessor&&(c+="@set"),o[c]=e;let u=i(s,c,e);if(u){let i=t.U.lookup(a.byQName,c);if(i)if(9==i.kind&&9!=u.kind)a.byQName[c+"@type"]=i;else if(9!=i.kind&&9==u.kind)a.byQName[c+"@type"]=u,u=i;else{const e=null===(n=i.attributes._source)||void 0===n?void 0:n.trim(),a=null===(r=u.attributes._source)||void 0===r?void 0:r.trim();let o=e+"\n"+a;e&&(null==a?void 0:a.indexOf(e))>=0?o=a:a&&(null==e?void 0:e.indexOf(a))>=0&&(o=e),u.attributes=t.parseCommentString(o),5===i.kind&&(u.pkgs=i.pkgs||[],i.pkg!==u.pkg&&(u.pkgs.find((e=>e===i.pkg))||u.pkgs.push(i.pkg))),i.extendsTypes&&(u.extendsTypes=u.extendsTypes||[],i.extendsTypes.forEach((e=>{-1===u.extendsTypes.indexOf(e)&&u.extendsTypes.push(e)})))}!e.parent||e.parent.kind!=t.SK.ClassDeclaration&&e.parent.kind!=t.SK.InterfaceDeclaration||t.isStatic(e)||(u.isInstance=!0),a.byQName[c]=u}}if(e.kind==t.SK.ModuleDeclaration){let n=e;if(n.body.kind==t.SK.ModuleBlock){n.body.statements.forEach(c)}else n.body.kind==t.SK.ModuleDeclaration&&c(n.body)}else if(e.kind==t.SK.InterfaceDeclaration){e.members.forEach(c)}else if(e.kind==t.SK.ClassDeclaration){e.members.forEach(c)}else if(e.kind==t.SK.EnumDeclaration){e.members.forEach(c)}}else{e.declarationList.declarations.forEach(c)}};for(let t of e.getSourceFiles())t.statements.forEach(c);let u=[];for(let e in a.byQName){let r=a.byQName[e];r.qName=e,r.attributes._source=null,r.extendsTypes&&r.extendsTypes.length&&u.push(r);let i=r.attributes.jres;if(i){"true"==i&&(i=e);let a=t.U.lookup(n||{},i);a&&a.icon&&!r.attributes.iconURL&&(r.attributes.iconURL=a.icon),a&&a.data&&!r.attributes.jresURL&&(r.attributes.jresURL="data:"+a.mimeType+";base64,"+a.data)}if(r.pyName){let e=t.U.lookup(t.ts2PyFunNameMap,r.qName);if(e&&e.n)r.pyQName=e.n,r.pySnippet=e.snippet,r.pySnippetName=e.n,r.pySnippetWithMarkers=void 0;else if(r.namespace){let e=a.byQName[r.namespace];e?r.pyQName=e.pyQName+"."+r.pyName:(pxt.log("namespace missing: "+r.namespace),r.pyQName=r.namespace+"."+r.pyName)}else r.pyQName=r.pyName}}let d={},p=e=>{if(t.U.lookup(d,e.qName))return;d[e.qName]=!0;let n={};n[e.qName]=!0;for(let t of e.extendsTypes||[]){n[t]=!0;let e=a.byQName[t];if(e){p(e);for(let t of e.extendsTypes)n[t]=!0}}e.extendsTypes=Object.keys(n)};return u.forEach(p),r&&delete a.byQName["Array.map"],{apis:a,decls:o}}function l(e,t){return t.isBogusSymbol?t.name:e.getFullyQualifiedName(t)}t.placeholderChar="◊",t.ts2PyFunNameMap={"Math.trunc":{n:"int",t:e.SyntaxKind.NumberKeyword,snippet:"int(0)"},"Math.min":{n:"min",t:e.SyntaxKind.NumberKeyword,snippet:"min(0, 0)"},"Math.max":{n:"max",t:e.SyntaxKind.NumberKeyword,snippet:"max(0, 0)"},"Math.abs":{n:"abs",t:e.SyntaxKind.NumberKeyword,snippet:"abs(0)"},"console.log":{n:"print",t:e.SyntaxKind.VoidKeyword,snippet:'print(":)")'},".length":{n:"len",t:e.SyntaxKind.NumberKeyword},".toLowerCase()":{n:"string.lower",t:e.SyntaxKind.StringKeyword},".toUpperCase()":{n:"string.upper",t:e.SyntaxKind.StringKeyword},".charCodeAt(0)":{n:"ord",t:e.SyntaxKind.NumberKeyword},"pins.createBuffer":{n:"bytearray",t:e.SyntaxKind.Unknown},"pins.createBufferFromArray":{n:"bytes",t:e.SyntaxKind.Unknown},"control.createBuffer":{n:"bytearray",t:e.SyntaxKind.Unknown},"control.createBufferFromArray":{n:"bytes",t:e.SyntaxKind.Unknown},"!!":{n:"bool",t:e.SyntaxKind.BooleanKeyword},"Array.indexOf":{n:"Array.index",t:e.SyntaxKind.Unknown},"Array.push":{n:"Array.append",t:e.SyntaxKind.Unknown},parseInt:{n:"int",t:e.SyntaxKind.NumberKeyword,snippet:'int("0")'},"_py.range":{n:"range",t:e.SyntaxKind.Unknown,snippet:"range(4)"}},t.emitPyTypeFromTypeNode=n,t.emitPyTypeFromTsType=r,t.genDocs=function(n,r,i={}){pxt.debug(`generating docs for ${n}`),pxt.debug(JSON.stringify(Object.keys(r.byQName),null,2));const a={},o=t.Util.values(r.byQName),c=o.filter((e=>7==e.kind)).sort(s),l={},u={},d={},p=t=>{if(i.locs&&t.qName&&!/^__/.test(t.name)){if(pxt.debug(`loc: ${t.qName}`),7!=t.kind){const n=e.pxtc.blocksCategory(t);n&&(u[`{id:category}${n}`]=n)}t.attributes.jsDoc&&(d[t.qName]=t.attributes.jsDoc),t.attributes.block&&(u[`${t.qName}|block`]=t.attributes.block),t.attributes.group&&(u[`{id:group}${t.attributes.group}`]=t.attributes.group),t.attributes.subcategory&&(u[`{id:subcategory}${t.attributes.subcategory}`]=t.attributes.subcategory),t.parameters&&t.parameters.filter((e=>!!e.description)).forEach((e=>{d[`${t.qName}|param|${e.name}`]=e.description}))}},f=(e,t)=>{if(!i.locs)return;const r={};Object.keys(e).sort().forEach((t=>r[t]=e[t])),a[n+t+"-strings.json"]=JSON.stringify(r,null,2)};for(const e of o){if(5==e.kind){if(!o.filter((t=>t.namespace==e.name&&!!t.attributes.jsDoc))[0])continue;e.attributes.block||(e.attributes.block=e.name)}p(e)}return i.locs&&c.forEach((e=>{e.attributes.block&&(u[`${e.qName}|block`]=e.attributes.block),e.attributes.jsDoc&&(u[e.qName]=e.attributes.jsDoc)})),f(u,""),f(d,"-jsdoc"),i.pxtsnippet&&(i.pxtsnippet.forEach((e=>function(e,t){const n=["label","title","hint","errorMessage"];t[e.label]=e.label,e.questions.forEach((e=>{n.forEach((n=>{e[n]&&(t[e[n]]=e[n])}))}))}(e,l))),f(l,"-snippet")),a},t.hasBlock=a,t.compareSymbols=s,t.getApiInfo=function(e,t,n=!1){return c(e,t,n).apis},t.internalGetApiInfo=c,t.getFullName=l}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){!function(n){let r,i,a={fileSystem:{},sourceFiles:[],target:{isNative:!1,hasHex:!1,switches:{}}};class o{constructor(){this.opts=a,this.fileVersions={},this.projectVer=0,this.pxtModulesOK=null}getProjectVersion(){return this.projectVer+""}setFile(e,t){this.opts.fileSystem[e]!=t&&(this.fileVersions[e]=(this.fileVersions[e]||0)+1,this.opts.fileSystem[e]=t,this.projectVer++)}reset(){this.setOpts(a),this.pxtModulesOK=null}setOpts(e){t.Util.iterMap(e.fileSystem,((e,t)=>{this.opts.fileSystem[e]!=t&&(this.fileVersions[e]=(this.fileVersions[e]||0)+1)})),this.opts=Object.assign(Object.assign({},e),{fileSystem:Object.assign({},e.fileSystem)}),this.projectVer++}getCompilationSettings(){return t.getTsCompilerOptions(this.opts)}getScriptFileNames(){return this.opts.sourceFiles.filter((e=>t.U.endsWith(e,".ts")))}getScriptVersion(e){return(this.fileVersions[e]||0).toString()}getScriptSnapshot(t){let n=this.opts.fileSystem[t];return null!=n?e.ScriptSnapshot.fromString(n):null}getNewLine(){return"\n"}getCurrentDirectory(){return"."}getDefaultLibFileName(e){return"no-default-lib.d.ts"}log(e){console.log("LOG",e)}trace(e){console.log("TRACE",e)}error(e){console.error("ERROR",e)}useCaseSensitiveFileNames(){return!0}}function s(e,r){return e?(n.lastLocBlocksInfo||(n.lastLocBlocksInfo=t.getBlocksInfo(e,r)),n.lastLocBlocksInfo):(n.lastBlocksInfo||(n.lastBlocksInfo=t.getBlocksInfo(n.lastApiInfo.apis,r)),n.lastBlocksInfo)}function c(e){return n.lastApiInfo||(n.lastApiInfo=t.internalGetApiInfo(n.service.getProgram(),e.jres)),n.lastApiInfo}function l(e){if(!e.apisInfo){const n=c(e);e.apisInfo=t.U.clone(n.apis)}}function u(e){let t=pxt.U.flatClone(e);return t.fileSystem=pxt.U.flatClone(t.fileSystem),t}n.blocksInfoOp=s,n.getLastApiInfo=c,n.addApiInfo=l,n.cloneCompileOpts=u,n.IsOpErr=function(e){return!!e.errorMessage};const d={reset:()=>{n.service=e.createLanguageService(n.host),n.lastApiInfo=void 0,n.lastGlobalNames=void 0,n.host.reset()},setOptions:e=>{n.host.setOpts(e.options)},syntaxInfo:e=>{var r,i,a;let o=e.fileContent;e.fileContent&&n.host.setFile(e.fileName,e.fileContent);let s=u(n.host.opts);s.fileSystem[e.fileName]=o,l(s),s.syntaxInfo={position:e.position,type:e.infoType};const d=s.target.preferredEditor==pxt.PYTHON_PROJECT_NAME,f="symbol"===s.syntaxInfo.type,_="signature"===s.syntaxInfo.type;if(d){let e=t.transpile.pyToTs(s);e.globalNames&&(n.lastGlobalNames=e.globalNames)}else{s.ast=!0,n.host.setOpts(s);p();const i=n.service.getProgram(),a=i.getSourceFile(e.fileName),o=i.getTypeChecker();if(f||_){let i=t.findInnerMostNodeAtPosition(a,e.position);if(i)if(f){const e=o.getSymbolAtLocation(i);if(e){let t=n.getPxtSymbolFromTsSymbol(e,s.apisInfo,o);s.syntaxInfo.symbols=[t],s.syntaxInfo.beginPos=i.getStart(),s.syntaxInfo.endPos=i.getEnd()}}else if(_){const n=null===(r=null==i?void 0:i.pxt)||void 0===r?void 0:r.callInfo;if(n){const r=s.apisInfo.byQName[n.qName];s.syntaxInfo.symbols=[r],s.syntaxInfo.beginPos=i.getStart(),s.syntaxInfo.endPos=i.getEnd();const a=t.getParentCallExpression(i);if(a){const n=t.findCurrentCallArgIdx(a,i,e.position);s.syntaxInfo.auxResult=n}}}}}if(f&&!(null===(i=s.syntaxInfo.symbols)||void 0===i?void 0:i.length)){const r=n.getWordAtPosition(e.fileContent,e.position);if(r)if(d&&"range"===r.text){const e=c(s).apis;e.byQName["_py.range"]&&(s.syntaxInfo.symbols=[e.byQName["_py.range"]],s.syntaxInfo.beginPos=r.start,s.syntaxInfo.endPos=r.end)}else{const e=t.getHelpForKeyword(r.text,d);e&&(s.syntaxInfo.auxResult={documentation:e,displayString:n.displayStringForKeyword(r.text,d)},s.syntaxInfo.beginPos=r.start,s.syntaxInfo.endPos=r.end)}}if(null===(a=s.syntaxInfo.symbols)||void 0===a?void 0:a.length){const e=c(s).apis;d&&(s.syntaxInfo.symbols=s.syntaxInfo.symbols.map((t=>e.byQName[t.qName]||t))),f&&(s.syntaxInfo.auxResult=s.syntaxInfo.symbols.map((t=>n.displayStringForSymbol(t,d,e))))}return s.syntaxInfo},getCompletions:e=>n.getCompletions(e),compile:e=>{n.host.setOpts(e.options);const r=p();return t.timesToMs(r),r},decompile:e=>(n.host.setOpts(e.options),t.decompile(n.service.getProgram(),e.options,e.fileName,!1)),pydecompile:e=>(n.host.setOpts(e.options),t.transpile.tsToPy(n.service.getProgram(),e.fileName)),decompileSnippets:e=>(n.host.setOpts(e.options),t.decompileSnippets(n.service.getProgram(),e.options,!1)),assemble:e=>({words:t.processorInlineAssemble(n.host.opts.target,e.fileContent)}),py2ts:e=>(l(e.options),t.transpile.pyToTs(e.options)),fileDiags:e=>t.patchUpDiagnostics(function(e){if(!/\.ts$/.test(e))return[];let t=n.service.getSyntacticDiagnostics(e);return t&&t.length||(t=n.service.getSemanticDiagnostics(e)),t||(t=[]),t}(e.fileName)),allDiags:()=>{let e=p();return t.timesToMs(e),n.host.opts.target.switches.time&&console.log("DIAG-TIME",e.times),e},format:e=>{const n=e.format;return t.format(n.input,n.pos)},apiInfo:()=>{if(n.lastBlocksInfo=void 0,r=void 0,n.host.opts!==a)return n.lastApiInfo=t.internalGetApiInfo(n.service.getProgram(),n.host.opts.jres),n.lastApiInfo.apis},snippet:t=>{const r=t.snippet;if(!n.lastApiInfo)return;const i=n.lastApiInfo.apis.byQName[r.qName],a=n.lastApiInfo.decls[r.qName];if(!i||!a||!e.isFunctionLike(a))return;const o=!!r.python;let c={};c=o&&n.lastGlobalNames?n.lastGlobalNames:n.lastApiInfo.apis.byQName;const{bannedCategories:l,screenSize:u}=t.runtime,{apis:d}=n.lastApiInfo,p={apis:d,blocksInfo:s(d,l),takenNames:c,bannedCategories:l,screenSize:u,checker:n.service&&n.service.getProgram().getTypeChecker()},f=n.getSnippet(p,i,a,o);return n.snippetStringify(f)},blocksInfo:e=>s(e,e.blocks&&e.blocks.bannedCategories),apiSearch:e=>{const t=e.search,i=s(t.localizedApis,e.blocks&&e.blocks.bannedCategories);t.localizedStrings&&pxt.Util.setLocalizedStrings(t.localizedStrings);const a=(e,t,n)=>{if(e)return"string"==typeof e?e:t?e[t]:Object.keys(e).map((t=>e[t])).join(" ")},o=e=>{var t;if(null===(t=e.attributes)||void 0===t?void 0:t._def){let t=[];const n=e.attributes._def,r=pxt.blocks.compileInfo(e);for(let e of n.parts)switch(e.kind){case"label":t.push(e.text);break;case"param":let n=r.definitionNameToParam[e.name];t.push((null==n?void 0:n.defaultValue)||e.varName||(null==n?void 0:n.actualName)||e.name)}return t.join(" ")}return e.attributes.block},c=e=>{var t;const n=null===(t=e.attributes)||void 0===t?void 0:t.paramHelp;return n&&Object.keys(n).map((e=>n[e])).join(" "),""};if(!n.builtinItems){n.builtinItems=[],n.blockDefinitions=pxt.blocks.blockDefinitions();for(const e in n.blockDefinitions){const t=n.blockDefinitions[e];if(t.operators)for(const r in t.operators){t.operators[r].forEach((i=>n.builtinItems.push({id:e,name:t.name,jsdoc:"string"==typeof t.tooltip?t.tooltip:t.tooltip[i],block:i,field:[r,i],builtinBlock:!0})))}else n.builtinItems.push({id:e,name:t.name,jsdoc:a(t.tooltip,t.tooltipSearch),block:a(t.block,t.blockTextSearch),builtinBlock:!0})}}let l;if(!r||t.subset){const e={};let a=[];t.subset&&(n.tbSubset=t.subset,a=n.builtinItems.filter((e=>!!n.tbSubset[e.id]))),n.tbSubset?l=i.blocks.filter((e=>!!n.tbSubset[e.attributes.blockId])):(l=i.blocks,a=n.builtinItems);let s=l.map((e=>({id:e.attributes.blockId,qName:e.qName,name:e.name,namespace:e.namespace,block:o(e),params:c(e),jsdoc:e.attributes.jsDoc,localizedCategory:n.tbSubset&&"string"==typeof n.tbSubset[e.attributes.blockId]?n.tbSubset[e.attributes.blockId]:void 0}))),u={};a.forEach((e=>u[e.id]=!0)),s=s.filter((e=>!(e.id in u)));let d=0;l.forEach((t=>{const n=e[t.qName]=(e=>{const t=e.attributes.weight||50,n=i.apis.byQName[e.namespace];return(1e3*(n&&n.attributes.weight||50)+t)*(n&&n.attributes.advanced||e.attributes.advanced?1:1e6)})(t);d=Math.max(d,n)})),s=s.concat(a);r=new Fuse(s,{shouldSort:!0,threshold:.6,location:0,distance:100,maxPatternLength:16,minMatchCharLength:2,findAllMatches:!1,caseSensitive:!1,keys:[{name:"name",weight:.3},{name:"namespace",weight:.1},{name:"localizedCategory",weight:.1},{name:"block",weight:.4375},{name:"params",weight:.0625},{name:"jsdoc",weight:.0625}],sortFn:function(t,n){const r=t.qName?1-e[t.item.qName]/d:1,i=n.qName?1-e[n.item.qName]/d:1;return t.score*(1+r/10)-n.score*(1+i/10)}})}return r.search(t.term).slice(0,7)},projectSearch:e=>{const t=e.projectSearch,n=t.headers;if(!i){i=new Fuse(n,{shouldSort:!0,threshold:.6,location:0,distance:100,maxPatternLength:16,minMatchCharLength:2,findAllMatches:!1,caseSensitive:!1,keys:[{name:"name",weight:.3}]})}return i.search(t.term)},projectSearchClear:()=>{i=void 0}};function p(){l(n.host.opts);const e=t.U.flatClone(n.host.opts.fileSystem);let r=t.runConversionsAndStoreResults(n.host.opts);(null==r?void 0:r.globalNames)&&(n.lastGlobalNames=r.globalNames);const i=n.host.opts.fileSystem;n.host.opts.fileSystem=e;for(let e of Object.keys(i))n.host.setFile(e,i[e]);if(0==r.diagnostics.length){n.host.opts.skipPxtModulesEmit=!1,n.host.opts.skipPxtModulesTSC=!1;const e=n.host.opts.target.isNative?"native":"js";!n.host.opts.target.switches.noIncr&&n.host.pxtModulesOK&&(n.host.opts.skipPxtModulesTSC=!0,n.host.opts.noEmit?n.host.opts.skipPxtModulesEmit=!0:n.host.opts.target.isNative?n.host.opts.skipPxtModulesEmit=!1:"js"!=n.host.pxtModulesOK||n.host.opts.breakpoints&&!n.host.opts.justMyCode||(n.host.opts.skipPxtModulesEmit=!0));let i=t.compile(n.host.opts,n.service);if(r=Object.assign({sourceMap:r.sourceMap},i),(r.needsFullRecompile||(!r.success||r.diagnostics.length)&&n.host.opts.clearIncrBuildAndRetryOnError)&&(pxt.debug("triggering full recompile"),pxt.tickEvent("compile.fullrecompile"),n.host.opts.skipPxtModulesEmit=!1,i=t.compile(n.host.opts,n.service),r=Object.assign({sourceMap:r.sourceMap},i)),r.diagnostics.every((e=>!t.isPxtModulesFilename(e.fileName)))&&(n.host.pxtModulesOK=e),r.ast){let e=t.internalGetApiInfo(r.ast);e&&(n.lastApiInfo=e)}}return r}n.runConversionsAndCompileUsingService=p,n.performOperation=function(t,r){n.service||(n.host=new o,n.service=e.createLanguageService(n.host));let i=null;if(d.hasOwnProperty(t))try{i=(0,d[t])(r)||{}}catch(e){i={errorMessage:e.stack}}else i={errorMessage:"No such operation: "+t};return i}}(t.service||(t.service={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){!function(n){function r(e){return"object"==typeof e&&void 0!==e.default}function i(e){return"object"==typeof e&&"number"==typeof e.length}function a(e,t=!1){const n={};let s=1;return function e(c){if(r(c)){if(t){if(o(c.default))return e(c.default);const t=a(c.default,!1);let r=n[t];if(r&&!c.isLiteral||(r=s,s++,n[t]=r),t.indexOf(".")>=0&&t.indexOf(" ")<0){let e=t.split(".");return e[e.length-1]="${"+r+":"+e[e.length-1]+"}",e.join(".")}return"${"+r+":"+t+"}"}return e(c.default)}return i(c)?c.map((t=>e(t))).join(""):c}(e)}function o(e){return!!r(e)||!!i(e)&&e.map(o).reduce(((e,t)=>e||t),!1)}function s(e){return e.attributes.shim&&"@"==e.attributes.shim[0]||e.attributes.pyConvertToTaggedTemplate}n.snippetStringify=a,n.snippetHasReplacementPoints=o,n.snippetAddsDefinitions=function e(t){return r(t)?t.isDefinition||e(t.default):!!i(t)&&t.map(e).reduce(((e,t)=>e||t),!1)},n.getSnippet=function r(i,o,c,l,u=0){var d;let{apis:p,takenNames:f,blocksInfo:_,screenSize:m,checker:g}=i;const h=pxt.py.INDENT,y=l?"python":"typescript";let v=o.namespace,b=!1,x=!1,k="",S=0,T=[];if(s(o))return l?`${o.name}(""" """)`:`${o.name}\`\``;let C="";C=c.kind==t.SK.Constructor?B(c.symbol)||c.parent.name.getText():B(c.symbol)||c.name.getText(),l&&(C=t.U.snakify(C));const E=o.attributes;if("TD_ID"===E.shim&&u&&c.parameters.length)return M(c.parameters[0]);const D=o,A=pxt.blocks.compileInfo(D),N=_.blocksById,w=(null===(d=E._def)||void 0===d?void 0:d.parameters.filter((e=>!!A.definitionNameToParam[e.name])).map((e=>A.definitionNameToParam[e.name].actualName)))||[],I=c.parameters?c.parameters.filter((e=>!e.initializer&&!e.questionToken||w.indexOf(e.name.getText())>=0)):[],P=I.map(M).map((e=>({default:e,isLiteral:!0})));if(D.attributes.block)if(D.attributes.defaultInstance)v=D.attributes.defaultInstance,l&&v&&(v=t.U.snakify(v));else if(D.namespace){const e=p.byQName[D.namespace];if(e.attributes.fixedInstances){let n,r=t.Util.values(p.byQName),i=function(e){return r.filter((e=>e.extendsTypes)).filter((t=>t.extendsTypes.reduce(((t,n)=>t||-1!=n.indexOf(e)),!1))).reduce(((e,t)=>e.concat(t.extendsTypes)),[])},a=r.filter((e=>4===e.kind&&e.attributes.fixedInstance));const o=a.filter((t=>t.retType==e.qName)).sort(((e,t)=>e.name.localeCompare(t.name)));if(o.length)n=o[0];else{n=a.filter((t=>-1!==i(e.qName).indexOf(t.retType))).sort(((e,t)=>e.name.localeCompare(t.name)))[0]}n?(v=`${$(n)}`,k=n.namespace):k=e.namespace,k&&(x=!0),b=!0}else if(1==D.kind||2==D.kind){if(A.thisParameter){let e;A.thisParameter.definitionName&&(e=A.thisParameter.definitionName,e=e[0].toUpperCase()+e.substring(1),e=`my${e}`),v=A.thisParameter.defaultValue||e,l&&v&&(v=t.U.snakify(v))}b=!0}else if(8===e.kind)return}const O=E&&(l?E.pySnippet:E.snippet);let F;if(O)F=[O];else if(F=[C],(null==P?void 0:P.length)||1==D.kind||3==D.kind||8==D.kind){const e=P.reduce(((e,t)=>[...e,e.length?", ":"",t]),[]);F=F.concat(["(",...e,")"])}let L=v?[v,".",...F]:F;if(L=x?[function(e){const t=e.indexOf(".");return t<0?e:e.substring(0,t)}(k),".",...L]:L,E&&E.blockSetVariable)if(l){L=[{default:R(t.U.snakify(E.blockSetVariable)),isDefinition:!0}," = ",...L]}else{L=["let ",{default:R(E.blockSetVariable),isDefinition:!0}," = ",...L]}return[T,L];function R(t){return f[t]?e.pxtc.decompiler.getNewName(t,f,!1):t}function M(a){var s;const c=a.type;if(!c)return l?"None":"null";const d=a.name.kind===t.SK.Identifier?a.name.text:void 0,f=null===(s=null==E?void 0:E.paramDefl)||void 0===s?void 0:s[d];if(f){let e;if(c.kind==t.SK.AnyKeyword){const n=f.toUpperCase();e=Number.isNaN(+n)?"FALSE"==n||"TRUE"==n?t.SK.BooleanKeyword:n.includes(".")?t.SK.EnumKeyword:t.SK.StringKeyword:t.SK.NumberKeyword}if(c.kind===t.SK.StringKeyword||e===t.SK.StringKeyword)return 0!=f.indexOf('"')?`"${f}"`:f;const r=null==g?void 0:g.getTypeAtLocation(a),i=n.getPxtSymbolFromTsSymbol(null==r?void 0:r.symbol,p,g);return(null==i?void 0:i.attributes.fixedInstances)&&l?pxt.Util.snakify(f):l?t.tsSnippetToPySnippet(f,i):f}let _=function(e){var t,n;const r=pxt.blocks.compileInfo(o),i=null===(t=r.parameters)||void 0===t?void 0:t.find((t=>t.actualName===e));if(!(null==i?void 0:i.shadowBlockId))return null;let a=N[i.shadowBlockId];if(!a)return null;const s=null===(n=a.attributes)||void 0===n?void 0:n.paramFieldEditor;if(!s)return null;const c=s[e];if(!c)return null;const l=a.attributes.paramFieldEditorOptions||{};switch(c){case"sprite":return function(e){const t={initColor:0,initWidth:16,initHeight:16};if(null==e?void 0:e.sizes){const n=e.sizes.split(";"),r=[];for(let e=0;e<n.length;e++){const t=n[e].split(",");if(2!==t.length)continue;let i=parseInt(t[0]),a=parseInt(t[1]);isNaN(i)||isNaN(a)||(i<0&&m&&(i=m.width),a<0&&m&&(a=m.height),r.push([i,a]))}r.length>0&&(t.initWidth=r[0][0],t.initHeight=r[0][1])}return t.initColor=n(null==e?void 0:e.initColor,t.initColor),t.initWidth=n(null==e?void 0:e.initWidth,t.initWidth),t.initHeight=n(null==e?void 0:e.initHeight,t.initHeight),pxt.sprite.imageLiteralFromDimensions(t.initWidth,t.initHeight,t.initColor,y);function n(e,t){const n=parseInt(e);return isNaN(n)?t:n}}(l[e])}return null}(d);if(_)return _;let h=function(e){let t=(E._shadowOverrides||{})[e];if(!t){const n=pxt.blocks.compileInfo(o);for(const r of n.parameters)if(r.actualName===e){t=r.shadowBlockId;break}}if(!t)return null;let n=N[t];if(!n)return null;if("TD_ID"===n.attributes.shim&&n.parameters.length){let e=n.parameters[0].type;n=p.byQName[e]||n}return n}(d);if(h){let s=n.getTsSymbolFromPxtSymbol(h,a,e.SymbolFlags.Enum);if(s){let e=g.getTypeOfSymbolAtLocation(s,a);if(e){let t=U(e);if(t)return t}}const c=h.attributes;if("KIND_GET"===c.shim&&c.blockId){const e=c.kindNamespace||o.namespace,n=t.Util.values(p.byQName).find((t=>t.namespace===e&&t.attributes.isKind));if(n)return l?n.pyQName:n.qName}if(u<3&&n.lastApiInfo.decls[h.qName]){let e=r(i,h,n.lastApiInfo.decls[h.qName],l,u+1);if(e)return e}}if(c.kind===t.SK.StringKeyword&&"leds"===d)return l?'"""\n. . . . .\n. . . . .\n. . # . .\n. . . . .\n. . . . .\n"""':"`\n. . . . .\n. . . . .\n. . # . .\n. . . . .\n. . . . .\n`";if(c.kind===t.SK.FunctionType){const e=c;let t=g?g.getSignatureFromDeclaration(e):void 0;return t?j(t,!0):K(d)}const v=n.getBasicKindDefault(c.kind,l);if(void 0!==v)return v;let b=g&&g.getTypeAtLocation(a);if(b){let e=U(b);if(e)return e}return l?"None":"null"}function U(r){if(r.symbol&&r.symbol.flags&e.SymbolFlags.Enum){return n.getDefaultEnumValue(r,l)}const i=n.getPxtSymbolFromTsSymbol(r.symbol,p,g);if(t.isObjectType(r)){const t=i&&i.attributes&&(l?i.attributes.pySnippet:i.attributes.snippet);if(t)return t;if(r.objectFlags&e.ObjectFlags.Anonymous){const t=g.getSignaturesOfType(r,e.SignatureKind.Call);return t&&t.length?j(t[0],!1):K()}}if(r.flags&e.TypeFlags.NumberLike)return"0";if(i&&i.attributes.fixedInstances){const e=function(e){return pxt.Util.values(p.byQName).filter((t=>4===t.kind&&t.attributes.fixedInstance&&function(e,t,n){if(t==n)return!0;let r=e.byQName[t];return!(!r||!r.extendsTypes)&&r.extendsTypes.indexOf(n)>=0}(p,t.retType,e.qName)))}(i);if(e.length){const t=e[0];return l?t.pyQName:t.qName}}}function B(e){if(g){const n=t.getFullName(g,e),r=p.byQName[n];if(r)return $(r)}}function $(e){return l?e.pyName:e.name}function j(n,r){let i="",o=g.getReturnTypeOfSignature(n);if(o.flags&e.TypeFlags.NumberLike?i="return 0":o.flags&e.TypeFlags.StringLike?i='return ""':o.flags&(e.TypeFlags.Boolean|e.TypeFlags.BooleanLiteral)&&(i=l?"return False":"return false"),l){let o;o=E.optionalVariableArgs?"()":`(${n.parameters.map((e=>e.name)).join(", ")})`;let s=C||"fn";S++>0&&(s+=S),r&&!/^on/i.test(s)&&(s="on"+pxt.Util.capitalize(s));const c=I.filter((t=>{const n=g&&g.getTypeAtLocation(t);return!!(n&&n.symbol&&n.symbol.flags&e.SymbolFlags.Enum)})).map((e=>{const t=a(M(e)).toLowerCase(),n=t.lastIndexOf(".");return-1!==n?t.substr(n+1):t})).join("_");return c&&(s+="_"+c),s=t.U.snakify(s),s=R(s),T=[...T,T.length?"\n":"","def ",{default:s,isDefinition:!0},o,`:\n${h}`,{default:i||"pass"},"\n"],{default:s}}{let t="()";if(!E.optionalVariableArgs){let r=e.mapToDisplayParts((t=>{g.getSymbolDisplayBuilder().buildSignatureDisplay(n,t,void 0,e.TypeFormatFlags.UseFullyQualifiedType)})),i=e.displayPartsToString(r);t=i.substr(0,i.lastIndexOf(":"))}return["function",t,` {\n${h}`,{default:i},"\n}"]}}function K(e){return l?(e=e||"fn",e=R(e=t.U.snakify(e)),T=[...T,T.length?"\n":"","def ",{default:e,isDefinition:!0},`():\n${h}`,{default:"pass"},"\n"],{default:e}):"function () {}"}},n.isTaggedTemplate=s}(t.service||(t.service={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){!function(e){const t=e=>`main.${e}`;e.pyToTs=function(e,n=t("py")){return pxt.py.py2ts(e)},e.tsToPy=function(e,n=t("ts")){return pxt.py.decompileToPython(e,n)}}(e.transpile||(e.transpile={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){let n;function r(e,t){if(!e)return;const i=t(e);if(i===n.Continue)return r(e.parent,t);if(i===n.Abort)return;if(i===n.Found)return e;return i}function i(t){return r(t,(t=>e.isModuleDeclaration(t)?n.Found:n.Continue))}t.getParentCallExpression=function(t){return r(t,(t=>e.isCallExpression(t)?n.Found:e.isBlock(t)?n.Abort:n.Continue))},t.findCurrentCallArgIdx=function(e,t,n){let r=e.arguments.map((e=>e===t)).indexOf(!0);if(r>=0)return r;if(!(e.arguments.pos<=n&&n<e.end))return-1;if(0===e.arguments.length)return 0;r=0;for(let t of e.arguments){if(!(t.end<=n))break;r++}return e.arguments.hasTrailingComma||(r=Math.max(0,r-1)),r},function(e){e[e.Found=0]="Found",e[e.Continue=1]="Continue",e[e.Abort=2]="Abort"}(n=t.TraverseCheck||(t.TraverseCheck={})),t.traverseUp=r,t.enumMemberToQName=function(e,n){if(n.name.kind===t.SK.Identifier)return e.getFullyQualifiedName(e.getSymbolAtLocation(n.name))},t.findInnerMostNodeAtPosition=function n(r,i){for(let t of r.getChildren()){if(t.kind>=e.SyntaxKind.FirstPunctuation&&t.kind<=e.SyntaxKind.LastPunctuation)continue;let r=t.getStart(),a=t.getEnd();if(r<=i&&i<a)return n(t,i)}return r&&r.kind===t.SK.SourceFile?null:r},t.getParentNamespace=i,t.getCurrentNamespaces=function e(t){if(!t)return[];let n=i(t);if(!n)return[];let r=n.name.getText();return[...e(n.parent),r]},t.getEnumMembers=function(e,n){if(e&&n.symbol&&n.symbol.declarations&&n.symbol.declarations.length)for(let e=0;e<n.symbol.declarations.length;e++){const r=n.symbol.declarations[e];if(r.kind===t.SK.EnumDeclaration){return r.members}}},t.isExported=function(e){if(e.modifiers&&e.modifiers.some((e=>e.kind==t.SK.PrivateKeyword||e.kind==t.SK.ProtectedKeyword)))return!1;let n=e.symbol;if(!n)return!1;for(;;){let e=n.parent;if(!e)break;n=e}let r=n.valueDeclaration||n.declarations[0];return r.kind==t.SK.VariableDeclaration&&(r=r.parent.parent),!(!r.parent||r.parent.kind!=t.SK.SourceFile)},t.isReadonly=function(e){return e.modifiers&&e.modifiers.some((e=>e.kind==t.SK.ReadonlyKeyword))}}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){!function(t){const n=e.assembler.emitErr,r=n("opcode name doesn't match","<name>");class i extends e.assembler.Instruction{constructor(e,t,n){super(e,t,n,n,!1)}emit(t){let i=t.words;if(i[0]!=this.name)return r;let a=this.opcode,o=1,s=[],c=null,l=null;for(let r=0;r<this.args.length;++r){let u=this.args[r],d=i[o++];if("$"==u[0]){let r=this.ei.encoders[u],i=null;if(r.isImmediate||r.isLabel){if(!d)return n("expecting number",d);if(d=d.replace(/^#/,""),i=t.bin.parseOneInt(d),null==i)return n("expecting number",d)}else e.oops();if(null==i)return n("didn't understand it",d);e.U.assert(i>=0),11111!=i&&"$lbl"==u&&(i-=t.bin.location()+2,i>>=1),s.push(i);const o=i;if(i=r.encode(i),null==i)return n(`argument (${o}) out of range or mis-aligned`,d);"$i3"==u?i=l|i<<6:"$i5"==u&&(i=l|i<<8),"$i2"==u||"$i4"==u?l=i:"$rt"==u?(11111!=i&&i>4096&&e.U.oops("label: "+d+" v="+i),a=32768|i,"callrt.p"==this.name&&(a|=8192)):t.isLong||i<0||i>255?(t.isLong=!0,"$lbl"==u&&(i-=1),a=i>>9&65535|49152,c=this.opcode+(i<<7)&65535):a=this.opcode+(i<<7)&65535}else if(u!=d)return n("expecting "+u,d)}return i[o]?n("trailing tokens",i[o]):{stack:0,opcode:a,opcode2:c,numArgs:s,labelName:t.bin.normalizeExternalLabel(null)}}}t.VmInstruction=i,t.withPush={},t.opcodes=["stloc $i1","ldloc $i1","stfld $i4, $i5","ldfld $i4, $i5","newobj $i1","ldcap $i1","bitconv $i1","stglb $i1","ldglb $i1","ldint $i1","ldintneg $i1","ldspecial $i1","ldnumber $i1","ldlit $i1","checkinst $i1","mapget","mapset","ret $i2, $i3","popmany $i1","pushmany $i1","callind $i1","callproc $i1","calliface $i2, $i3","callget $i1","callset $i1","jmp $lbl","jmpnz $lbl","jmpz $lbl","try $lbl","push","pop"];class a extends e.assembler.AbstractProcessor{constructor(e){super(),this.addEnc("$i1","#0-8388607",(e=>this.inrange(8388607,e,e))),this.addEnc("$i2","#0-31",(e=>this.inrange(31,e,e))),this.addEnc("$i3","#0-262143",(e=>this.inrange(262143,e,e))),this.addEnc("$i4","#0-255",(e=>this.inrange(255,e,e))),this.addEnc("$i5","#0-32767",(e=>this.inrange(32767,e,e))),this.addEnc("$lbl","LABEL",(e=>this.inminmax(-4194304,4194303,e,e))).isLabel=!0,this.addEnc("$rt","SHIM",(e=>this.inrange(8388607,e,e))).isLabel=!0;let n=1,r=!0;for(let e of t.opcodes.concat(["callrt $rt"])){let a=new i(this,e,n);this.instructions[a.name]=[a],(r||"callrt"==a.name)&&(t.withPush[a.name]=!0,a=new i(this,e.replace(/\w+/,(e=>e+".p")),64|n),this.instructions[a.name]=[a]),"mapset.p"==a.name&&(r=!1),n++}}testAssembler(){}postProcessRelAddress(e,t){return t}postProcessAbsAddress(e,t){return t}getAddressFromLabel(e,t,n,r=!1){let i=e.lookupLabel(n);return null==i?null:t.is32bit?i:i-(e.pc()+2)}toFnPtr(e,t){return e}wordSize(){return 8}peephole(e,n,r){let i=e.getOp(),a="";if(n){a=n.getOp();let e=i+";"+a,t=this.file.peepCounts;t[e]=(t[e]||0)+1}"stloc"==i&&"ldloc"==a&&e.numArgs[0]==n.numArgs[0]?(/LAST/.test(n.text)&&e.update(""),n.update("")):t.withPush[i]&&"push"==a&&(e.update(e.text.replace(/\w+/,(e=>e+".p"))),n.update(""))}}t.VmProcessor=a}(e.vm||(e.vm={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){let t;!function(e){e[e.NonLocal=0]="NonLocal",e[e.Global=1]="Global"}(t=e.VarModifier||(e.VarModifier={})),e.isIndex=function(e){return"Index"===e.kind},e.isSubscript=function(e){return"Subscript"===e.kind}}(e.py||(e.py={}))}(pxt||(pxt={})),function(e){!function(t){var n=e.blocks;let r,i,a,o,s,c,l,u,d,p,f=0,_=0,m=0,g="???";function h(e){return null==e}function y(e){return null!=e}function v(t){return e.tickEvent("python.todo.statement",{kind:t.kind}),n.mkStmt(n.mkText("TODO: "+t.kind))}function b(t){return e.tickEvent("python.todo.expression",{kind:t.kind}),n.mkText(" {TODO: "+t.kind+"} ")}const x=F({primType:"string"}),k=F({primType:"number"}),S=F({primType:"boolean"}),T=F({primType:"void"}),C=F({primType:"any"});let E;const D={str:x,string:x,number:k,bool:S,void:T,any:C};function A(e){switch(e){case ts.SyntaxKind.StringKeyword:return x;case ts.SyntaxKind.NumberKeyword:return k;case ts.SyntaxKind.BooleanKeyword:return S;case ts.SyntaxKind.VoidKeyword:return T;case ts.SyntaxKind.AnyKeyword:return C;default:return E}}function N(t){let n=e.U.flatClone(t);return delete n.pyAST,delete n.pyInstanceType,delete n.pyRetType,delete n.pySymbolType,delete n.moduleTypeMarker,delete n.declared,n.parameters&&(n.parameters=n.parameters.map((t=>(delete(t=e.U.flatClone(t)).pyType,t)))),n}function w(t){if("("==t[0]&&e.U.endsWith(t,")"))return w(t.slice(1,-1));const n=t.indexOf(" => ");if(n>0){const e=t.slice(n+4);if(-1==e.indexOf(")[]")){const r=w(e),i=t.slice(1,n-1);return R(r,(i?i.split(/, /):[]).map((e=>w(e.replace(/\w+\??: /,"")))))}}if(e.U.endsWith(t,"[]"))return L(w(t.slice(0,-2)));if("_py.Array"===t)return L(C);const r=e.U.lookup(D,t);if(r)return r;if(!!t&&!isNaN(t))return k;if("T"==t||"U"==t)return F({primType:"'"+t});if(t.indexOf("|")>=0){return F({primType:"@union",typeArgs:t.split("|").map((e=>e.trim())).map(w)})}let i=P(t+"@type")||P(t);return i?7==i.kind?k:8==i.kind||9==i.kind?i.pyInstanceType||F({classType:i}):6==i.kind?k:(W(null,9502,e.U.lf("'{0}' is not a type near '{1}'",t,g||"???")),F({primType:t})):(W(null,9501,e.U.lf("unknown type '{0}' near '{1}'",t,g||"???")),F({primType:t}))}function I(t){if(!t.pySymbolType){if(g=t.pyQName,t.parameters){pxtc.service.isTaggedTemplate(t)&&(t.parameters=[{name:"literal",description:"",type:"string",options:{}}]);for(let e of t.parameters)e.pyType||(e.pyType=w(e.type))}const n=t.pyRetType;if(he(t)?t.pyRetType=F({moduleType:t}):t.retType?t.pyRetType=w(t.retType):t.pyRetType||(e.U.oops("no type for: "+t.pyQName),t.pyRetType=F({})),n&&ee(t.pyAST,n,t.pyRetType),3==t.kind||1==t.kind){let n=t.parameters.map((e=>e.pyType));if(n.some(h))return W(null,9526,e.U.lf("function symbol is missing parameter types near '{1}'",g||"???")),F({});t.pySymbolType=R(t.pyRetType,n.filter(y))}else t.pySymbolType=t.pyRetType;8!=t.kind&&9!=t.kind||(t.pyInstanceType=F({classType:t})),g=void 0}return t.pySymbolType}function P(t){return e.U.lookup(i,t)||e.U.lookup(r,t)}function O(e){if(!e)return;let t=P(e);return t&&I(t),t}function F(t={}){let n=e.U.flatClone(t);return n.tid=++_,n}function L(e){return F({primType:"@array",typeArgs:[e]})}function R(e,t){return F({primType:"@fn"+t.length,typeArgs:[e].concat(t)})}function M(t){return!!e.U.startsWith(t.primType||"","@fn")}function U(t){return!!t.primType&&!e.U.startsWith(t.primType,"@")}function B(t){return!!e.U.startsWith(t.primType||"","@union")}function $(){return a.currFun||a.currClass||a.currModule}function j(){let e=$();for(;e&&e.parent;)e=e.parent;return e}function K(){return"main"==a.currModule.name&&!a.currFun&&!a.currClass}function z(t,n,r){const i=O(n);return i||W(t,9503,e.U.lf("No module named '{0}'",n)),i}function J(e,n,r,i){i||(i=$());let a=i.vars[e],o=null==a?void 0:a.symbol;if(!o){let n=V(i);n&&(n+=".");let s=n+e;o=!se(i)||r!==t.VarModifier.Global&&r!==t.VarModifier.NonLocal?se(i)?ae(4,e):oe(4,s):oe(4,e),a={symbol:o,modifier:r},i.vars[e]=a}for(let e of Object.keys(n))o[e]=n[e];return a}function q(e){return e.unifyWith?(e.unifyWith=q(e.unifyWith),e.unifyWith):e}function V(e){let t=e,n="";t.parent&&"FunctionDef"!==t.parent.kind&&"AsyncFunctionDef"!==t.parent.kind&&(n=V(t.parent),n?n+=".":n="");let r=e;return"Module"==e.kind&&"main"==r.name?"":r.name?n+r.name:n+"?"+e.kind}function H(t){let n=e.U.lookup(Ce,t);if(n)return n;for(let n of e.U.values(a.currModule.vars)){let r=n.symbol;if(r.isImport){if(r.expandsTo==t)return r.pyName||W(null,9553,lf("missing pyName")),r.pyName;if(r.isImport&&e.U.startsWith(t,(r.expandsTo||"")+"."))return r.pyName+t.slice(r.expandsTo.length)}}return t}function G(e){return(e=q(e)).primType?e.typeArgs&&"@array"==e.primType?G(e.typeArgs[0])+"[]":M(e)&&e.typeArgs?"("+e.typeArgs.slice(1).map((e=>"_: "+G(e))).join(", ")+") => "+G(e.typeArgs[0]):B(e)&&e.typeArgs?e.typeArgs.map(G).join(" | "):e.primType+"":e.classType&&e.classType.pyQName?H(e.classType.pyQName)+"":e.moduleType&&e.moduleType.pyQName?H(e.moduleType.pyQName)+"":"any"}function W(e,t,n){c.push(function(e,t,n,r){return e||(e=o),e&&a&&a.currModule?{fileName:s,start:e.startPos,length:e.endPos-e.startPos,line:void 0,column:void 0,code:n,category:t,messageText:r}:{fileName:s,start:0,length:0,line:void 0,column:void 0,code:n,category:t,messageText:r}}(e,pxtc.DiagnosticCategory.Error,t,n))}function Q(e){return e.primType?e.primType:e.classType?e.classType:e.moduleType?(e.moduleType.moduleTypeMarker||(e.moduleType.moduleTypeMarker={}),e.moduleType.moduleTypeMarker):null}function Y(e){return!Q(q(e))}function X(t,n,r){var i;(n=q(n)).classType!=r&&(Y(n)?n.classType=r:ee(t,n,(I(i=r),i.pyInstanceType||W(null,9527,e.U.lf("Instance type symbol '{0}' is missing pyInstanceType",i)),i.pyInstanceType)))}function Z(e,t){ee(e,ge(e),t)}function ee(t,n,r){if(n===r)return;if((n=q(n))===(r=q(r))||ie(n)||ie(r))return;if("any"===n.primType)return void(n.unifyWith=r);const i=Q(n),a=Q(r);if(i&&a)if(i===a){if(n.unifyWith=r,n.typeArgs&&r.typeArgs)for(let e=0;e<Math.min(n.typeArgs.length,r.typeArgs.length);++e)ee(t,n.typeArgs[e],r.typeArgs[e]);n.unifyWith=r}else!function(t,n,r){W(t,9500,e.U.lf("types not compatible: {0} and {1}",G(n),G(r)))}(t,n,r);else i&&!a?ee(t,r,n):(m++,n.unifyWith=r)}function te(e,t){const n=q(e),r=q(t);if(n===r)return!0;const i=Q(n),a=Q(r);if(i===a)return!0;if(i&&a){if(re(i)&&re(a)&&i.extendsTypes&&i.extendsTypes.length&&i.extendsTypes.some((e=>e===a.qName)))return!0;if(B(r)){for(let e of r.typeArgs||[])if(te(n,e))return!0;return!1}}return!1}function ne(e,t){const n=q(ge(e)),r=q(t);te(n,r)||(M(n)||M(r)||U(n)||U(r))&&ee(e,n,r)}function re(e){var t;return!!(null===(t=e)||void 0===t?void 0:t.name)}function ie(e){var t;return!!(null===(t=null==e?void 0:e.primType)||void 0===t?void 0:t.startsWith("'"))}function ae(e,t){let n=/(.*)\.(.*)/.exec(t),r=n?n[2]:t;return{kind:e,name:r,pyName:r,qName:t,pyQName:t,namespace:n?n[1]:"",attributes:{},pyRetType:F()}}function oe(t,n){let r=i[n];return r?(r.kind=t,r):(r=ae(t,n),r.pyQName||W(null,9527,e.U.lf("Symbol '{0}' is missing pyQName",n)),i[r.pyQName]=r,r)}function se(e){let t=e;for(;t;){if("FunctionDef"==t.kind)return!0;t=t.parent}return!1}function ce(t,n,r){if(!n.symInfo){let i=V(n);e.U.endsWith(i,".__init__")&&(i=i.slice(0,-9)+".__constructor"),se(r=r||$())?n.symInfo=ae(t,i):n.symInfo=oe(t,i);const a=n.symInfo;a.pyAST=n,a.pyName||W(null,9528,e.U.lf("Symbol '{0}' is missing pyName",a.qName||a.name)),r.vars[a.pyName]={symbol:a}}return n.symInfo}function le(t){let n=t.symInfo.qName;return e.U.values(i).filter((e=>e.namespace==n&&2==e.kind))}function ue(t,n,r=!1,i=!1){let a=t.pyQName+"."+n,o=O(a);if(o)return o;if(!i)for(let r of t.extendsTypes||[]){let i=O(r);if(i){i==t&&e.U.userError("field lookup loop on: "+i.qName+" / "+n);let r=ue(i,n,!0);if(r)return r}}if(!r&&t.pyAST&&"ClassDef"==t.pyAST.kind){let e=oe(2,a);return e.isInstance=!0,e}return null}function de(t,n,r=!1){const i=ge(t),o=function(e){let t=q(e);return[t.classType,...pe(t.primType),t.moduleType].filter(y)}(i);for(let c of o){let o=ue(c,n,r);if(o){return!!i.moduleType?o.isInstance&&W(null,9505,e.U.lf("the field '{0}' of '{1}' is not static",n,c.pyQName)):(o.isInstance||W(null,9504,e.U.lf("the field '{0}' of '{1}' is static",n,c.pyQName)),Be(s=t,"super")&&0==s.args.length?o.isProtected=!0:ze(t)&&(a.currClass||W(null,9529,e.U.lf("no class context found for {0}",o.pyQName)),o.namespace!=a.currClass.symInfo.qName&&(o.isProtected=!0))),o}}var s;return null}function pe(e){let t=[];return"@array"==e?t=[P("_py.Array"),P("Array")]:"string"==e&&(t=[P("_py.String"),P("String")]),t.filter((e=>!!e))}function fe(t){let n=$(),r=e.U.lookup(n.vars,t);if(r)return r;for(;n;){let r=e.U.lookup(n.vars,t);if(r)return r;do{n=n.parent}while(n&&"ClassDef"==n.kind)}return null}function _e(e){if(!e)return null;const t=e.indexOf(".");if(t>0){const n=fe(e.slice(0,t)),r=null==n?void 0:n.symbol;r&&r.pyQName!=r.pyName&&(e=r.pyQName+e.slice(t))}else{const t=fe(e);if(t)return t}let n=O(e);return n?{symbol:n}:void 0}function me(e){var t;return null===(t=_e(e))||void 0===t?void 0:t.symbol}function ge(e){return e.tsType?q(e.tsType):(e.tsType=F(),e.tsType)}function he(e){if(!e)return!1;switch(e.kind){case 5:case 9:case 8:case 6:return!0;default:return!1}}function ye(t){const n=e.U.flatClone(a);let r;try{r=t()}finally{a=n}return r}function ve(e,t){return 0==t.length?n.mkText(""):n.mkGroup([n.mkText("/* TODO: "+e+" "),n.mkGroup(t),n.mkText(" */"),n.mkNewLine()])}function be(e){let t=Ze(e.value);return e.arg?n.mkInfix(n.mkText(e.arg),"=",t):n.mkGroup([n.mkText("**"),t])}function xe(n){if(!n)return F();let r=Re(n);if(r){let t=P(r+"@type")||P(r);if(t){if(I(t),6==t.kind)return k;if(t.pyInstanceType)return t.pyInstanceType}else if(D[r])return D[r];W(n,9506,e.U.lf("cannot find type '{0}'",r))}else if(t.isSubscript(n)){if("List"===Re(n.value)&&t.isIndex(n.slice)){return L(xe(n.slice.value))}}return W(n,9507,e.U.lf("invalid type syntax")),F({})}const ke={Sub:1,Div:1,Pow:1,LShift:1,RShift:1,BitOr:1,BitXor:1,BitAnd:1,FloorDiv:1,Mult:1},Se={Add:"+",Sub:"-",Mult:"*",MatMult:"Math.matrixMult",Div:"/",Mod:"%",Pow:"**",LShift:"<<",RShift:">>",BitOr:"|",BitXor:"^",BitAnd:"&",FloorDiv:"Math.idiv",And:"&&",Or:"||",Eq:"==",NotEq:"!=",Lt:"<",LtE:"<=",Gt:">",GtE:">=",Is:"===",IsNot:"!==",In:"py.In",NotIn:"py.NotIn"},Te={Invert:"~",Not:"!",UAdd:"P+",USub:"P-"},Ce={"adafruit_bus_device.i2c_device.I2CDevice":"pins.I2CDevice"};function Ee(e){a.blockDepth++;const t=n.mkBlock(e.map(et));return a.blockDepth--,t}function De(e){e.vars||(e.vars={},e.parent=$(),e.blockDepth=a.blockDepth)}function Ae(e,t=!1){return"any"===G(e)?t?n.mkText(": any"):n.mkText(""):n.mkText(": "+G(e))}function Ne(e,t){try{return ye(t)}catch(t){return console.log(t),n.mkStmt(ve(`conversion failed for ${e.name||e.kind}`,[]))}}function we(e){if(!e||!e.pyAST)return!1;if("FunctionDef"!=e.pyAST.kind)return!1;const t=e.pyAST;return!(!t.callers||1!=t.callers.length)&&!t.callers[0].inCalledPosition}function Ie(t,r=!1){return Ne(t,(()=>{const i=!!a.currClass&&!a.currFun,o=K(),s=!!a.currFun;De(t);const c=me(V(t)),l=ce(i?1:3,t);if(!r&&(c&&c.declared===f&&W(t,9520,lf("Duplicate function declaration")),l.declared=f,we(l)))return n.mkText("");i&&(l.isInstance=!0),a.currFun=t;let u="",d=t.name;let p=[ve("decorators",t.decorator_list.filter((e=>"property"==Re(e)?(u="get",!1):"Attribute"!=e.kind||"setter"!=e.attr||"Name"!=e.value.kind||(d=e.value.id,u="set",!1))).map(Ze))];if(t.body.length>=1&&"Raise"==t.body[0].kind&&(t.alwaysThrows=!0),i)if(a.currClass||W(t,9531,lf("method '{0}' is missing current class context",l.pyQName)),l.pyRetType||W(t,9532,lf("method '{0}' is missing a return type",l.pyQName)),"__init__"==t.name)p.push(n.mkText("constructor")),X(t,l.pyRetType,a.currClass.symInfo);else{if("__get__"==d||"__set__"==d){let e=t.vars.value,n=null==e?void 0:e.symbol;if("__set__"==d&&n){let e=ue(a.currClass.symInfo,"__get__");e&&e.pyAST&&"FunctionDef"==e.pyAST.kind&&ee(t,n.pyRetType,e.pyRetType)}d=d.replace(/_/g,"")}u||(u="_"==d[0]?l.isProtected?"protected":"private":"public"),p.push(n.mkText(u+" "),Ue(d))}else e.U.assert(!u),"_"==t.name[0]||o||r||s?p.push(n.mkText("function "),Ue(d)):p.push(n.mkText("export function "),Ue(d));let _=t.returns?xe(t.returns):l.pyRetType;p.push(function(t,r){const i=t.args;i.kwonlyargs.length&&W(t,9517,e.U.lf("keyword-only arguments not supported yet"));let a=i.args.slice();if(r?("self"!=a[0].arg&&W(t,9518,e.U.lf("first argument of method has to be called 'self'")),a.shift()):a.some((e=>"self"==e.arg))&&W(t,9519,e.U.lf("non-methods cannot have an argument called 'self'")),!t.symInfo.parameters){let r=i.defaults.length-a.length;t.symInfo.parameters=a.map((a=>{a.annotation||W(t,9519,e.U.lf("Arg '{0}' missing annotation",a.arg));let o=xe(a.annotation),s="";return r>=0&&(s=n.flattenNode([Ze(i.defaults[r])]).output,ee(a,o,ge(i.defaults[r]))),r++,{name:a.arg,description:"",type:"",initializer:s,default:s,pyType:o}}))}let o=t.symInfo.parameters.map((r=>{let i=J(r.name,{isParam:!0}),a=null==i?void 0:i.symbol;r.pyType||W(t,9530,e.U.lf("parameter '{0}' missing pyType",r.name)),ee(t,I(a),r.pyType);let o=[Ue(r.name),Ae(r.pyType,!0)];return r.default&&o.push(n.mkText(" = "+r.default)),n.mkGroup(o)}));return i.vararg&&o.push(n.mkText("TODO *"+i.vararg.arg)),i.kwarg&&o.push(n.mkText("TODO **"+i.kwarg.arg)),n.H.mkParenthesizedExpression(n.mkCommaSep(o))}(t,i),_&&q(_)!=T?Ae(_):n.mkText("")),I(l);let m=t.body.map(et);if("__init__"==t.name){a.currClass||W(t,9533,lf("__init__ method '{0}' is missing current class context",l.pyQName));for(let e of le(a.currClass)){let t=e.pyAST;t&&t.value&&m.push(n.mkStmt(n.mkText(`this.${Le(e.pyName)} = `),Ze(t.value)))}}const g=it(t);p.push(n.mkBlock(g.concat(m)));let h=n.mkGroup(p);return r?p[p.length-1].noFinalNewline=!0:h=n.mkStmt(h),h}))}const Pe={FunctionDef:e=>Ie(e),ClassDef:t=>Ne(t,(()=>{De(t);const r=ce(8,t);e.U.assert(!a.currClass);let i=K();a.currClass=t,t.isNamespace=t.decorator_list.some((e=>"Name"==e.kind&&"namespace"==e.id));let o=t.isNamespace?[n.mkText("namespace "),Ue(t.name)]:[ve("keywords",t.keywords.map(be)),ve("decorators",t.decorator_list.map(Ze)),n.mkText(i?"class ":"export class "),Ue(t.name)];if(!t.isNamespace&&t.bases.length>0)if("Enum"==Re(t.bases[0]))t.isEnum=!0;else{o.push(n.mkText(" extends ")),o.push(n.mkCommaSep(t.bases.map(Ze)));let e=function(e){let t=me(Me(e));return t&&t.pyAST&&"ClassDef"==t.pyAST.kind?t.pyAST:null}(t.bases[0]);e&&(t.baseClass=e,r.extendsTypes=[e.symInfo.pyQName])}let s=Ee(t.body);o.push(s);let c=le(t).filter((e=>2==e.kind&&e.isInstance)).map((e=>(e.pyName&&e.pyRetType||W(t,9535,lf("field definition missing py name or ret type",e.qName)),e))).map((e=>n.mkStmt(function(e){return e.pyName&&"_"==e.pyName[0]?e.isProtected?n.mkText("protected "):n.mkText("private "):n.mkText("")}(e),Ue(e.pyName),Ae(e.pyRetType))));return s.children=c.concat(s.children),n.mkStmt(n.mkGroup(o))})),Return:e=>{if(e.value){let t=a.currFun;return t&&(t.symInfo.pyRetType||W(e,9536,lf("function '{0}' missing return type",t.symInfo.pyQName)),Z(e.value,t.symInfo.pyRetType)),n.mkStmt(n.mkText("return "),Ze(e.value))}return n.mkStmt(n.mkText("return"))},AugAssign:e=>{let t=Se[e.op];return t.length>3?n.mkStmt(n.mkInfix(Ze(e.target),"=",n.H.mkCall(t,[Ze(e.target),Ze(e.value)]))):n.mkStmt(Ze(e.target),n.mkText(" "+t+"= "),Ze(e.value))},Assign:e=>Oe(e),AnnAssign:e=>Oe(e),For:t=>{if(e.U.assert(0==t.orelse.length),t.target.forTargetEndPos=t.endPos,Be(t.iter,"range")){let e=t.iter,r=Ze(t.target),i=Ue(Me(t.target));Z(t.target,k);let a=1==e.args.length?n.mkText("0"):Ze(e.args[0]),o=Ze(e.args[1==e.args.length?0:1]);return n.mkStmt(n.mkText("for ("),n.mkInfix(r,"=",a),n.mkText("; "),n.mkInfix(i,"<",o),n.mkText("; "),e.args.length>=3?n.mkInfix(i,"+=",Ze(e.args[2])):n.mkPostfix([i],"++"),n.mkText(")"),Ee(t.body))}if(f>1){const e=ge(t.target);Z(t.iter,ge(t.iter)==x?e:L(e))}return n.mkStmt(n.mkText("for ("),Ze(t.target),n.mkText(" of "),Ze(t.iter),n.mkText(")"),Ee(t.body))},While:t=>(e.U.assert(0==t.orelse.length),n.mkStmt(n.mkText("while ("),Ze(t.test),n.mkText(")"),Ee(t.body))),If:t=>{let r=t=>{let i=[n.mkText("if ("),Ze(t.test),n.mkText(")"),Ee(t.body)];return t.orelse.length&&(i[i.length-1].noFinalNewline=!0,1==t.orelse.length&&"If"==t.orelse[0].kind?(i.push(n.mkText(" else ")),e.U.pushRange(i,r(t.orelse[0]))):i.push(n.mkText(" else"),Ee(t.orelse))),i};return n.mkStmt(n.mkGroup(r(t)))},With:t=>{if(1==t.items.length&&function(e,t){let n=ge(e);return!(!n.classType||n.classType.pyQName!=t)||G(n)==t}(t.items[0].context_expr,"pins.I2CDevice")){let r=t.items[0],i=[],a=Ze(r.context_expr);if(r.optional_vars){let e=Re(r.optional_vars);if(e){let o=J(e,{isLocal:!0}),s=null==o?void 0:o.symbol;e=Le(e),i.push(n.mkStmt(n.mkText("const "+e+" = "),a)),s.pyRetType||W(t,9537,lf("function '{0}' missing return type",s.pyQName)),Z(r.context_expr,s.pyRetType),a=n.mkText(e)}}return i.push(n.mkStmt(n.mkInfix(a,".",n.mkText("begin()")))),e.U.pushRange(i,t.body.map(et)),i.push(n.mkStmt(n.mkInfix(a,".",n.mkText("end()")))),n.mkGroup(i)}let r=[],i=t.items.map(((e,t)=>{let i="with"+t;if(e.optional_vars){let t=Me(e.optional_vars);J(t,{isLocal:!0}),i=Le(t)}return r.push(n.mkStmt(n.mkText(i+".end()"))),n.mkStmt(n.mkText("const "+i+" = "),n.mkInfix(Ze(e.context_expr),".",n.mkText("begin()")))}));return e.U.pushRange(i,t.body.map(et)),e.U.pushRange(i,r),n.mkBlock(i)},Raise:e=>{let t,r=e.exc||e.cause;if(!r)return n.mkStmt(n.mkText("throw"));if(r&&"Call"==r.kind){let e=r;1==e.args.length&&(t=Ze(e.args[0]))}return t||(t=n.mkGroup([n.mkText("`"),Ze(r),n.mkText("`")])),n.mkStmt(n.H.mkCall("control.fail",[t]))},Assert:e=>(e.msg||W(e,9537,lf("assert missing message")),n.mkStmt(n.H.mkCall("control.assert",[e.test,e.msg].filter((e=>!!e)).map(Ze)))),Import:e=>{for(let t of e.names)t.asname&&J(t.asname,{expandsTo:t.name}),z(e,t.name);return n.mkText("")},ImportFrom:e=>{let t=[];for(let r of e.names)if("*"==r.name)e.module||W(e,9538,lf("import missing module name")),J(e.module,{isImportStar:!0});else{let i=e.module+"."+r.name,a=O(i),o=r.asname||r.name;he(a)?(J(o,{isImport:a,expandsTo:i}),t.push(n.mkStmt(n.mkText(`import ${Le(o)} = ${i}`)))):J(o,{expandsTo:i})}return n.mkGroup(t)},ExprStmt:e=>{return"Str"==e.value.kind?((t=e.value.s).trim().split(/\n/).length<=1?t=t.trim():t+="\n",n.mkStmt(n.mkText("/** "+t+" */"))):n.mkStmt(Ze(e.value));var t},Pass:e=>n.mkStmt(n.mkText("")),Break:e=>n.mkStmt(n.mkText("break")),Continue:e=>n.mkStmt(n.mkText("continue")),Delete:t=>(W(t,9550,e.U.lf("delete statements are unsupported")),v(t)),Try:e=>{let t=[n.mkText("try"),Ee(e.body.concat(e.orelse))];for(let r of e.handlers)t.push(n.mkText("catch ("),r.name?Ue(r.name):n.mkText("_")),r.type&&t.push(n.mkText("/* instanceof "),Ze(r.type),n.mkText(" */")),t.push(n.mkText(")"),Ee(r.body));return e.finalbody.length&&t.push(n.mkText("finally"),Ee(e.finalbody)),n.mkStmt(n.mkGroup(t))},AsyncFunctionDef:t=>(W(t,9551,e.U.lf("async function definitions are unsupported")),v(t)),AsyncFor:t=>(W(t,9552,e.U.lf("async for statements are unsupported")),v(t)),AsyncWith:t=>(W(t,9553,e.U.lf("async with statements are unsupported")),v(t)),Global:r=>{const i=j();$();for(const n of r.names){e.U.lookup(i.vars,n)||W(r,9521,e.U.lf("No binding found for global variable"));J(n,{},t.VarModifier.Global).firstRefPos<r.startPos&&W(r,9522,e.U.lf("Variable referenced before global declaration"))}return n.mkStmt(n.mkText(""))},Nonlocal:r=>{const i=j(),a=$();for(const n of r.names){const o=rt(n,a);o&&o!==i&&o.vars[n].modifier!==t.VarModifier.Global||W(r,9523,e.U.lf("No binding found for nonlocal variable"));J(n,{},t.VarModifier.NonLocal).firstRefPos<r.startPos&&W(r,9524,e.U.lf("Variable referenced before nonlocal declaration"))}return n.mkStmt(n.mkText(""))}};function Oe(t){let r,i,o,s;if("Assign"===t.kind){if(1!=t.targets.length)return W(t,9553,e.U.lf("multi-target assignment statements are unsupported")),v(t);s=t.targets[0],o=t.value,r=null,i=null}else{if("AnnAssign"!==t.kind)return t;s=t.target,o=t.value||null,r=t.annotation,i=xe(r),Z(s,i)}let c,l="",u=!!o&&Be(o,"const"),d=Re(s)||"";if(K()||a.currClass||a.currFun||"_"==d[0]||(l="export "),d&&a.currClass&&!a.currFun){u=!(!o||!a.currClass.isNamespace);let e=ue(a.currClass.symInfo,d);if(e||W(t,9544,lf("cannot get class field")),0==f)return n.mkText("/* skip for now */");e.pyRetType||W(t,9539,lf("function '{0}' missing return type",e.pyQName)),Z(s,e.pyRetType),e.isInstance=!1,l=a.currClass.isNamespace?`export ${u?"const":"let"} `:"static "}if(!o)return W(t,9555,e.U.lf("unable to determine value of assignment")),v(t);if(Z(s,ge(o)),u)return J(Me(s),{}),/^static /.test(l)||/const/.test(l)||(l+="const "),n.mkStmt(n.mkText(l),n.mkInfix(Ze(s),"=",Ze(o)));if(!l&&"Tuple"==s.kind){let r=s,i=[n.mkText("let "),n.mkText("[")];if(r.elts.filter((e=>"Name"!==e.kind)).length)return W(t,9556,e.U.lf("non-trivial tuple assignment unsupported")),v(t);let a=r.elts.map((e=>e)).map((function(e){Ve(e,"identifierCompletion"),ge(e);We(e);return Fe(e,!0)}));return i.push(n.mkCommaSep(a)),i.push(n.mkText("]")),n.mkStmt(n.mkInfix(n.mkGroup(i),"=",Ze(o)))}if("Name"===s.kind){const e=$().vars[d],t=null==e?void 0:e.symbol;t&&4===t.kind&&void 0===e.modifier&&(void 0===e.firstAssignPos||e.firstAssignPos>s.startPos)&&(e.firstAssignPos=s.startPos,e.firstAssignDepth=a.blockDepth)}if(r&&i&&("NameConstant"===o.kind&&null===o.value||"List"===o.kind&&0===o.elts.length)){const e=G(i);c=n.mkInfix(Ze(s),":",n.mkText(e))}return c||(c=Ze(s)),n.mkStmt(n.mkText(l),n.mkInfix(c,"=",Ze(o)))}function Fe(e,t=!1){let r=e.id,i=_e(r),o=null==i?void 0:i.symbol,s=$().vars[r],c=null==s?void 0:s.symbol;return void 0===e.isdef&&(!o||4===o.kind&&o!==c?(a.currClass&&!a.currFun?(e.isdef=!1,i=J(r,{})):(e.isdef=!0,i=J(r,{isLocal:!0})),o=i.symbol):e.isdef=!1,e.symbolInfo=o,e.tsType||W(e,9540,lf("definition missing ts type")),o.pyRetType||W(e,9568,lf("missing py return type")),ee(e,e.tsType,o.pyRetType)),e.isdef&&at(i,$())&&(e.isdef=!1),Qe(i,e),e.isdef&&!t?n.mkGroup([n.mkText("let "),Ue(r)]):Ue(r)}function Le(e){return n.isReservedWord(e)?e+"_":e||e}function Re(e){if("Name"==e.kind){let t=e.id,n=fe(t),r=null==n?void 0:n.symbol;return r&&r.expandsTo?r.expandsTo:t}if("Attribute"==e.kind){let t=Re(e.value);if(t)return t+"."+e.attr}}function Me(e){let t=Re(e);return t||W(null,9542,lf("Cannot get name of unknown expression kind '{0}'",e.kind)),t}function Ue(e){return"self"==e?n.mkText("this"):n.mkText(Le(e))}function Be(e,t){if("Call"!=e.kind)return!1;return Re(e.func)===t}function $e(t,r,i){let a=Se[r];return e.U.assert(!!a),a.length>3?n.H.mkCall(a,[t,i]):n.mkInfix(t,a,i)}const je={memoryview:{n:"",t:E},const:{n:"",t:k},"micropython.const":{n:"",t:k}};const Ke=function(){let e={};return Object.keys(pxtc.ts2PyFunNameMap).forEach((t=>{let n=pxtc.ts2PyFunNameMap[t];if(n&&n.n){let r={n:t,t:A(n.t),scale:n.scale};e[n.n]=r}})),Object.keys(je).forEach((t=>{e[t]=je[t]})),e}();function ze(e){return"Name"==e.kind&&"self"==e.id}function Je(e){return e.type==n.NT.Prefix&&'"'==e.op[0]?n.mkText(n.backtickLit(JSON.parse(e.op))):e}function qe(e){return u&&e.startPos<=u.position&&u.position<=e.endPos}function Ve(e,t){f>100&&u&&null==d&&(u.type==t||"symbol"==u.type)&&qe(e)&&(d=e,p=$())}function He(e,t){if(t&&t.pyAST&&"FunctionDef"==t.pyAST.kind){let n=t.pyAST;n.callers||(n.callers=[]),n.callers.indexOf(e)<0&&n.callers.push(e)}}const Ge={BoolOp:e=>{let t=Ze(e.values[0]);for(let n=1;n<e.values.length;++n)t=$e(t,e.op,Ze(e.values[n]));return t},BinOp:e=>{let t=function(e){if("Mod"==e.op&&"Str"==e.left.kind&&("Tuple"==e.right.kind||"List"==e.right.kind)){let t=e.left.s,r=e.right.elts;r=r.slice();let i=[n.mkText("`")];return t.replace(/([^%]+)|(%[\d\.]*([a-zA-Z%]))/g,((e,t,a,o)=>{if(t)i.push(n.mkText(t.replace(/[`\\$]/g,(e=>"\\"+e))));else{let e=r.shift(),t=e?Ze(e):n.mkText("???");i.push(n.mkText("${"),t,n.mkText("}"))}return""})),i.push(n.mkText("`")),n.mkGroup(i)}return null}(e);if(t)return t;const r=Ze(e.left),i=Ze(e.right);return ct(e.left)&&ct(e.right)&&"Add"===e.op?n.H.extensionCall("concat",[r,i],!1):(t=$e(r,e.op,i),ke[e.op]&&(Z(e.left,k),Z(e.right,k),e.tsType||W(e,9570,lf("binary op missing ts type")),ee(e,e.tsType,k)),t)},UnaryOp:t=>{let r=Te[t.op];return e.U.assert(!!r),n.mkInfix(null,r,Ze(t.operand))},Lambda:t=>(W(t,9574,e.U.lf("lambda expressions are not supported yet")),b(t)),IfExp:e=>n.mkInfix(n.mkInfix(Ze(e.test),"?",Ze(e.body)),":",Ze(e.orelse)),Dict:e=>{a.blockDepth++;const t=e.keys.map(((t,r)=>{const i=e.values[r];return void 0===t?b(e):n.mkStmt(n.mkInfix(Ze(t),":",Ze(i)),n.mkText(","))})),r=n.mkBlock(t);return a.blockDepth--,r},Set:e=>b(e),ListComp:e=>b(e),SetComp:e=>b(e),DictComp:e=>b(e),GeneratorExp:e=>{if(1==e.generators.length&&"Comprehension"==e.generators[0].kind){let t=e.generators[0];if(0==t.ifs.length)return ye((()=>{let r=Me(t.target);return J(r,{isParam:!0}),n.mkInfix(Ze(t.iter),".",n.H.mkCall("map",[n.mkGroup([Ue(r),n.mkText(" => "),Ze(e.elt)])]))}))}return b(e)},Await:e=>b(e),Yield:e=>b(e),YieldFrom:e=>b(e),Compare:e=>{if(1==e.ops.length&&("In"==e.ops[0]||"NotIn"==e.ops[0])){q(ge(e.comparators[0]))==x&&Z(e.left,x);let t=n.mkInfix(Ze(e.comparators[0]),".",n.H.mkCall("indexOf",[Ze(e.left)]));return n.mkInfix(t,"In"==e.ops[0]?">=":"<",n.mkText("0"))}let t=$e(Ze(e.left),e.ops[0],Ze(e.comparators[0]));for(let n=1;n<e.ops.length;++n)t=$e(t,"And",$e(Ze(e.comparators[n-1]),e.ops[n],Ze(e.comparators[n])));return t},Call:t=>{t.func.inCalledPosition=!0;let r,i,o=Re(t.func),s=me(o),c=s&&8==s.kind,l=s,f="";if(c)l=me(s.pyQName+".__constructor");else if("Attribute"==t.func.kind){let e=t.func;i=e.value,r=ge(i),(r.classType||r.primType)&&(f=e.attr,l=de(i,f,!0),l&&(f=l.name))}let _=t.args.slice();if("super"==o&&0==_.length)return a.currClass&&a.currClass.baseClass&&(t.tsType||W(t,9543,lf("call expr missing ts type")),X(t,t.tsType,a.currClass.baseClass.symInfo)),n.mkText("super");if(Be(t,"int")&&1===_.length&&_[0]){const e=_[0],t=Ze(e),r=ge(e);if("string"===r.primType)return n.mkGroup([n.mkText("parseInt"),n.mkText("("),t,n.mkText(")")]);if("number"===r.primType)return n.mkGroup([n.mkInfix(n.mkText("Math"),".",n.mkText("trunc")),n.mkText("("),t,n.mkText(")")])}if(!l){let t=e.U.lookup(Ke,o);if(t&&(f=""),f&&(o=G(r)+"."+f,t=e.U.lookup(Ke,o),t||"@array"!=Q(q(r))||(o="Array."+f,t=e.U.lookup(Ke,o))),f="",t)if("."==t.n[0]&&_.length){if(i=_.shift(),r=ge(i),f=t.n.slice(1),l=de(i,f),l&&2==l.kind)return n.mkInfix(Ze(i),".",n.mkText(f))}else l=O(t.n)}if(Be(t,"str"))return ee(t,t.tsType,x),n.mkInfix(n.mkText('""'),"+",Ze(t.args[0]));l||W(t,9508,e.U.lf("can't find called function '{0}'",o));let m=l?l.parameters:null,g=[];if(m){for(_.length>m.length&&W(t,9510,e.U.lf("too many arguments in call to '{0}'",l.pyQName));_.length<m.length;)_.push(null);_=_.slice(0,m.length);for(let n of t.keywords){let t=m.findIndex((e=>e.name==n.arg));t<0?W(n,9511,e.U.lf("'{0}' doesn't have argument named '{1}'",l.pyQName,n.arg)):null!=_[t]?W(n,9512,e.U.lf("argument '{0} already specified in call to '{1}'",n.arg,l.pyQName)):_[t]=n.value}for(let e=_.length-1;e>=0&&(m[e].initializer&&null==_[e]);e--)_.pop();for(let r=0;r<_.length;++r){let i=_[r];if(null!=i||m[r].initializer)if(i){m[r].pyType||W(t,9545,lf("formal arg missing py type"));const e=m[r].pyType;"any"!==e.primType&&ne(i,e),"Name"==i.kind&&we(i.symbolInfo)?g.push(Ie(i.symbolInfo.pyAST,!0)):g.push(Ze(i))}else m[r].initializer||W(t,9547,lf("formal arg missing initializer")),g.push(n.mkText(m[r].initializer));else W(t,9513,e.U.lf("missing argument '{0}' in call to '{1}'",m[r].name,l.pyQName)),g.push(n.mkText("null"))}}else l&&W(t,9509,e.U.lf("calling non-function")),g=_.map(Ze);if(!d&&u&&"signature"==u.type&&qe(t)){d=t,p=$(),u.auxResult=0;for(let e=0;e<_.length;++e){u.auxResult=e;let t=_[e];if(!t)break;if(t.startPos<=u.position&&u.position<=t.endPos)break}}if(l)if(l.pyRetType||W(t,9549,lf("function missing pyRetType")),i&&ct(i)&&r?function(e,t,n){switch(t.qName){case"Array.pop":case"Array.removeAt":case"Array.shift":case"Array.find":case"Array.get":case"Array._pickRandom":Z(e,n.typeArgs[0]);break;case"Array.concat":case"Array.slice":case"Array.filter":case"Array.fill":Z(e,n);break;case"Array.reduce":if("Call"===e.kind&&e.args.length>1){const t=ge(e.args[1]);t&&Z(e,t)}break;case"Array.map":Z(e,L(C));break;default:Z(e,t.pyRetType)}}(t,l,r):Z(t,l.pyRetType),t.symbolInfo=l,l.attributes.py2tsOverride){const e=function(e){const t=new RegExp(/([^\$]*\()?([^\$\(]*)\$(\d)(?:(?:(?:=(\d+|'[a-zA-Z0-9_]*'|false|true|null|undefined))|(\?)|))/,"y"),n=[];let r,i=0;do{i=t.lastIndex,r=t.exec(e),r&&(r[1]&&n.push({kind:"text",text:r[1]}),n.push({kind:"arg",prefix:r[2],index:parseInt(r[3]),default:r[4],isOptional:!!r[5]}))}while(r);null!=i?n.push({kind:"text",text:e.substr(i)}):n.push({kind:"text",text:e});return{parts:n}}(l.attributes.py2tsOverride);if(e){f&&!i&&W(t,9550,lf("missing recv"));let r=function(e,t,r){const i=[];for(const r of e.parts)if("text"===r.kind)i.push(n.mkText(r.text));else if(t[r.index]||r.default)r.prefix&&i.push(n.mkText(r.prefix)),t[r.index]?i.push(t[r.index]):i.push(n.mkText(r.default));else if(!r.isOptional)return;if(r)return n.mkInfix(r,".",n.mkGroup(i));return n.mkGroup(i)}(e,g,f?Ze(i):void 0);return r||W(t,9555,lf("buildOverride failed unexpectedly")),r}}else if(l.attributes.pyHelper)return n.mkGroup([n.mkInfix(n.mkText("_py"),".",n.mkText(l.attributes.pyHelper)),n.mkText("("),n.mkCommaSep(i?[Ze(i)].concat(g):g),n.mkText(")")]);let h=f?n.mkInfix(Ze(i),".",n.mkText(f)):Ze(t.func),y=[h,n.mkText("("),n.mkCommaSep(g),n.mkText(")")];return l&&1==g.length&&pxtc.service.isTaggedTemplate(l)&&(y=[h,Je(g[0])]),c&&(s&&s.pyQName||W(t,9551,lf("missing namedSymbol or pyQName")),y[0]=n.mkText(H(s.pyQName)),y.unshift(n.mkText("new "))),n.mkGroup(y)},Num:e=>(e.tsType||W(e,9556,lf("tsType missing")),ee(e,e.tsType,k),n.mkText(e.ns)),Str:e=>(e.tsType||W(e,9557,lf("tsType missing")),ee(e,e.tsType,x),n.mkText(n.stringLit(e.s))),FormattedValue:e=>b(e),JoinedStr:e=>b(e),Bytes:t=>n.mkText(`hex\`${e.U.toHex(new Uint8Array(t.s))}\``),NameConstant:e=>(null!==e.value&&(e.tsType||W(e,9558,lf("tsType missing")),ee(e,e.tsType,S)),n.mkText(JSON.stringify(e.value))),Ellipsis:e=>b(e),Constant:e=>b(e),Attribute:t=>{let r=Ze(t.value),i=ge(t.value),a=de(t.value,t.attr),o=t.attr;if(Ve(t,"memberCompletion"),a)t.symbolInfo=a,He(t,a),t.tsType&&a.pyRetType||W(t,9559,lf("tsType or pyRetType missing")),ee(t,t.tsType,a.pyRetType),o=a.name;else if(i.moduleType){let n=O(i.moduleType.pyQName+"."+t.attr);n?(t.symbolInfo=n,He(t,n),Z(t,I(n)),o=n.name):W(t,9514,e.U.lf("module '{0}' has no attribute '{1}'",i.moduleType.pyQName,t.attr))}else f>2&&W(t,9515,e.U.lf("unknown object type; cannot lookup attribute '{0}'",t.attr));return n.mkInfix(r,".",n.mkText(Le(o)))},Subscript:e=>{if("Index"==e.slice.kind){const t=q(ge(e.value));if(ct(e.value)){Z(e,t.typeArgs[0])}else"string"===t.primType?Z(e,t):f>2&&Y(ge(e))&&Z(e,C);let r=e.slice.value;return f>2&&Y(ge(r))&&Z(r,k),n.mkGroup([Ze(e.value),n.mkText("["),Ze(r),n.mkText("]")])}if("Slice"==e.slice.kind){const t=ge(e.value);Z(e,t);let r=e.slice;if(r.step){const i="string"===(null==t?void 0:t.primType);return n.H.mkCall(i?"_py.stringSlice":"_py.slice",[Ze(e.value),r.lower?Ze(r.lower):n.mkText("null"),r.upper?Ze(r.upper):n.mkText("null"),Ze(r.step)])}return n.mkInfix(Ze(e.value),".",n.H.mkCall("slice",[r.lower?Ze(r.lower):n.mkText("0"),r.upper?Ze(r.upper):null].filter(y)))}return b(e)},Starred:e=>n.mkGroup([n.mkText("... "),Ze(e.value)]),Name:e=>{if(Ve(e,"identifierCompletion"),"self"==e.id&&a.currClass)return e.tsType||W(e,9560,lf("missing tsType")),X(e,e.tsType,a.currClass.symInfo),n.mkText("this");let t=We(e),r=null==t?void 0:t.symbol;if(r&&r.isImport)return Ue(r.name);if(Qe(t,e),e.ctx.indexOf("Load")>=0){if(!r)return Ue(Me(e));if(!(null==r?void 0:r.qName))return W(e,9561,lf("missing qName")),Ue("unknown");return Ue(r.qName.replace("@type",""))}return Fe(e)},List:Ye,Tuple:Ye};function We(t){let n=_e(t.id),r=null==n?void 0:n.symbol;if(!n){let r=e.U.lookup(Ke,t.id);r&&(n=_e(r.n))}if(n&&r){if(t.symbolInfo=r,t.tsType||W(t,9562,lf("missing tsType")),ee(t,t.tsType,I(r)),r.isImport)return n;He(t,r),t.forTargetEndPos&&n.forVariableEndPos!==t.forTargetEndPos&&(n.forVariableEndPos?n.lastRefPos=n.forVariableEndPos+1:n.forVariableEndPos=t.forTargetEndPos)}else f>0&&W(t,9516,e.U.lf("name '{0}' is not defined",t.id));return n}function Qe(e,n){if(e){if(e.modifier===t.VarModifier.Global){const t=j();t&&t.vars[e.symbol.name]&&(e=t.vars[e.symbol.name])}else if(e.modifier===t.VarModifier.NonLocal){const t=rt(e.symbol.name,$());t&&(e=t.vars[e.symbol.name])}(void 0===e.firstRefPos||e.firstRefPos>n.startPos)&&(e.firstRefPos=n.startPos),(void 0===e.lastRefPos||e.lastRefPos<n.startPos)&&(e.lastRefPos=n.startPos)}}function Ye(e){return e.tsType||W(e,9563,lf("missing tsType")),ee(e,e.tsType,L(e.elts[0]?ge(e.elts[0]):F())),n.mkGroup([n.mkText("["),n.mkCommaSep(e.elts.map(Ze)),n.mkText("]")])}function Xe(e){return`${e.startPos}:${e.endPos}`}function Ze(t){o=t;let n=Ge[t.kind];n||e.U.oops(t.kind+" - unknown expr"),ge(t);const r=n(t);return r.id=Xe(t),r}function et(t){o=t;let r=Pe[t.kind];r||e.U.oops(t.kind+" - unknown stmt");let i=(t._comments||[]).map((e=>e.value)),a=r(t);return i.length&&(a=n.mkGroup(i.map((e=>n.mkStmt(n.H.mkComment(e)))).concat(a))),a.id=Xe(t),a}function tt(e){return!e||(e.type==n.NT.Prefix&&""==e.op?e.children.every(tt):e.type==n.NT.NewLine)}function nt(e){const t=Ue(e.name),r=G(I(e));return n.mkStmt(n.mkGroup([n.mkText("let "),t,n.mkText(": "+r+";")]))}function rt(e,n){if(!n)return;const r=n.vars&&n.vars[e];return r&&r.modifier!=t.VarModifier.NonLocal?n:rt(e,n.parent)}function it(e){const t=[];let n;for(const r of Object.keys(e.vars))n=e.vars[r],at(n,e)&&t.push(nt(null==n?void 0:n.symbol));return t}function at(e,t){return!!(4===e.symbol.kind&&!e.symbol.isParam&&void 0===e.modifier&&(e.lastRefPos>e.forVariableEndPos||e.firstRefPos<e.firstAssignPos||e.firstAssignDepth>t.blockDepth)&&!(function(e){return"Module"===e.kind&&"main"===e.name}(t)&&0===e.firstAssignDepth))}function ot(t){if(e.U.assert("Module"==t.kind),t.tsBody)return;var r;a={currClass:void 0,currFun:void 0,currModule:r=t,blockDepth:0},s=r.tsFilename.replace(/\.ts$/,".py"),t.vars||(t.vars={});let i=it(t).concat(t.body.map(et));return i.every(tt)?void 0:"main"==t.name?i:[n.mkText("namespace "+t.name+" "),n.mkBlock(i)]}function st(e){f=e,c=[],m=0,o=void 0}function ct(e){const t=q(ge(e));return t&&"@array"===t.primType}t.py2ts=function(a){let o=[];const f={};c=[],e.U.assert(!!a.sourceFiles,"missing sourceFiles! Cannot convert py to ts");let _=a.sourceFiles.filter((t=>e.U.endsWith(t,".py")));if(0==_.length)return{outfiles:f,diagnostics:c,success:0===c.length,sourceMap:[]};let g=(e,t)=>e.substr(0,e.length-t.length),h=e.U.toDictionary(_,(e=>g(e,".py"))),y=a.sourceFiles.filter((t=>e.U.endsWith(t,".ts"))).filter((e=>g(e,".ts")in h));e.U.assert(!!a.apisInfo,"missing apisInfo! Cannot convert py to ts"),s=_[0],function(t,n){i={},r={};let a=e.U.toDictionary(n,(e=>e));for(let n of e.U.values(t.byQName)){if(a.hasOwnProperty(n.fileName))continue;let t=n;t.extendsTypes&&(t.extendsTypes=t.extendsTypes.filter((e=>e!=t.qName))),t.pyQName&&t.qName||W(null,9526,e.U.lf("Symbol '{0}' is missing qName for '{1}'",t.name,t.pyQName?"ts":"py")),r[t.pyQName]=t,r[t.qName]=t}E=w("Buffer")}(a.apisInfo,y),l=a,u=void 0,a.generatedFiles||(a.generatedFiles=[]);for(const t of _){let n=t,r=t.replace(/\.py$/,"").replace(/.*\//,""),i=a.fileSystem[t];try{s=t;let a=e.py.lex(i),l=e.py.parse(i,n,a);e.U.pushRange(c,l.diagnostics),o.push({kind:"Module",body:l.stmts,blockDepth:0,name:r,source:i,tsFilename:n.replace(/\.py$/,".ts")})}catch(e){console.log("Parse error",e)}}const v=c;for(let e=0;e<5;++e){st(e);for(let e of o)try{ot(e)}catch(e){console.log("Conv pass error",e)}if(0==m)break}st(1e3),d=void 0,u=a.syntaxInfo||{position:0,type:"symbol"};let b=[];for(let e of o)try{let t=ot(e);if(!t)continue;let r=n.flattenNode(t);function x(e){let t=e.id.split(":");if(2!=t.length)return;let n=t.map((e=>parseInt(e)));return{py:{startPos:n[0],endPos:n[1]},ts:{startPos:e.startPos,endPos:e.endPos}}}a.sourceFiles.push(e.tsFilename),a.generatedFiles.push(e.tsFilename),a.fileSystem[e.tsFilename]=r.output,f[e.tsFilename]=r.output,b=r.sourceMap.map(x).filter((e=>!!e))}catch(e){console.log("Conv error",e)}c=v.concat(c);let k={};const S=e.U.values(r).concat(e.U.values(i));let T=[];const C=e=>{if((e=>{switch(e.kind){case 6:case 7:case 4:case 3:case 5:return!0;case 2:case 1:return!e.isInstance;default:return!1}})(e)&&T.indexOf(e)<0){let t=N(e);k[t.qName||t.name]=t}};for(let t=p;t;t=t.parent)t&&t.vars&&e.U.values(t.vars).map((e=>e.symbol)).forEach(C);if(S.forEach(C),u&&d){if(d=d,u.beginPos=d.startPos,u.endPos=d.endPos,u.symbols||(u.symbols=[]),T=u.symbols.slice(),"memberCompletion"==u.type&&"Attribute"==d.kind){const e=ge(d.value);if(e.moduleType)for(let t of S)t.isInstance||t.namespace!=e.moduleType.qName||u.symbols.push(t);else if(e.classType||e.primType){const t=e.classType||pe(e.primType).reduce(((e,t)=>e||t),null);if(t){t.extendsTypes&&t.qName||W(null,9567,lf("missing extendsTypes or qName"));let e=t.extendsTypes.concat(t.qName);for(let t of S)t.isInstance&&e.indexOf(t.namespace)>=0&&u.symbols.push(t)}}}else if("identifierCompletion"==u.type)u.symbols=e.U.values(k);else{let e=d.symbolInfo;e&&u.symbols.push(e)}u.symbols=u.symbols.map(N)}let D=function(){for(let e of c)t.patchPosition(e,a.fileSystem[e.fileName]);return c}();return{outfiles:f,success:0===D.length,diagnostics:D,syntaxInfo:u,globalNames:k,sourceMap:b}}}(e.py||(e.py={}))}(pxt||(pxt={})),function(e){!function(t){let n;!function(e){e[e.Id=0]="Id",e[e.Op=1]="Op",e[e.Keyword=2]="Keyword",e[e.Number=3]="Number",e[e.String=4]="String",e[e.NewLine=5]="NewLine",e[e.Comment=6]="Comment",e[e.Indent=7]="Indent",e[e.Dedent=8]="Dedent",e[e.EOF=9]="EOF",e[e.Error=10]="Error"}(n=t.TokenType||(t.TokenType={})),t.keywords={False:!0,None:!0,True:!0,and:!0,as:!0,assert:!0,async:!0,await:!0,break:!0,class:!0,continue:!0,def:!0,del:!0,elif:!0,else:!0,except:!0,finally:!0,for:!0,from:!0,global:!0,if:!0,import:!0,in:!0,is:!0,lambda:!0,nonlocal:!0,not:!0,or:!0,pass:!0,raise:!0,return:!0,try:!0,while:!0,with:!0,yield:!0};let r,i,a=[];const o={"%":"Mod","&":"BitAnd","*":"Mult","**":"Pow","+":"Add","-":"Sub","/":"Div","//":"FloorDiv","<<":"LShift",">>":"RShift","@":"MatMult","^":"BitXor","|":"BitOr"},s={"!":"Bang","!=":"NotEq","(":"LParen",")":"RParen",",":"Comma","->":"Arrow",".":"Dot",":":"Colon",";":"Semicolon","<":"Lt","<=":"LtE","=":"Assign","==":"Eq",">":"Gt",">=":"GtE","[":"LSquare","]":"RSquare","{":"LBracket","}":"RBracket","~":"Invert"},c={b:/^[_0-1]$/,B:/^[_0-1]$/,o:/^[_0-7]$/,O:/^[_0-7]$/,x:/^[_0-9a-fA-F]$/,X:/^[_0-9a-fA-F]$/},l={b:2,B:2,o:8,O:8,x:16,X:16};let u,d,p=0,f=0;function _(e,t){let n=0,r=0;for(let i=0;i<e;++i)10==t.charCodeAt(i)&&(n++,r=i);return{line:n,column:e-r-1}}function m(e){switch(e.type){case n.Id:return`id(${e.value})`;case n.Op:return"'"+i[e.value]+"'";case n.Keyword:return e.value;case n.Number:return`num(${e.value})`;case n.String:return e.stringPrefix+JSON.stringify(e.value);case n.NewLine:return"<nl>";case n.Comment:return`/* ${e.value} */`;case n.Indent:return"indent"+e.value;case n.Dedent:return"dedent";case n.Error:return`[ERR: ${e.value}]`;case n.EOF:return"End of file";default:return"???"}}t.position=_,t.patchPosition=function(e,t){if(!e.start&&!e.length)return e.start=0,e.length=0,e.line=0,void(e.column=0);let n=_(e.start,t);e.line=n.line,e.column=n.column,e.length>0&&(n=_(e.start+e.length-1,t),e.endLine=n.line,e.endColumn=n.column+2)},t.tokenToString=m,t.friendlyTokenToString=function(e,t){let n=e.endPos-e.startPos,r="";return r=0==n?m(e):n>20?"`"+t.slice(e.startPos,e.startPos+20)+"`...":"`"+t.slice(e.startPos,e.endPos)+"`",r=r.replace(/\r/g,"").replace(/\n/g,"\\n").replace(/\t/g,"\\t"),r},t.tokensToString=function(e){let t="",r=0;for(let i of e){let e=m(i);r+e.length>70&&(r=0,t+="\n"),0!=r&&(t+=" "),t+=e,r+=e.length,i.type!=n.NewLine&&i.type!=n.Comment||(r=0,t+="\n")}return t},t.lex=function(_){for(0==a.length&&function(){const n={'"':k,"'":k,"#":E,"\\":C,".":A};r=e.U.clone(s);for(let e of Object.keys(o))r[e]=o[e],r[e+"="]=o[e]+"Assign";i={};for(let e of Object.keys(r))i[r[e]]=e;for(let e=0;e<128;++e)if(t.rx.isIdentifierStart(e))a[e]=h;else{let i=String.fromCharCode(e);if(n.hasOwnProperty(i))a[e]=n[i];else if(r.hasOwnProperty(i)){let t=!1,n=r[i];for(let e of Object.keys(r))e!=i&&e.startsWith(i)&&(t=!0);a[e]=t?()=>v(n):()=>y(n)}else t.rx.isSpace(e)?a[e]=()=>{}:13==e?a[e]=()=>{10==d.charCodeAt(p)&&p++,S()}:t.rx.isNewline(e)?a[e]=S:N(e)?a[e]=D:a[e]=w}}(),d=_,u=[],p=0,f=0,T();p<d.length;){f=p;const e=d.charCodeAt(p++);e<128?a[e]():t.rx.isIdentifierStart(e)?h():t.rx.isSpace(e)||(t.rx.isNewline(e)?S():w())}return f=p,S(),m(n.EOF,""),u;function m(e,t,n){let r={type:e,value:t,startPos:f,endPos:p,auxValue:n};return u.push(r),r}function g(e){m(n.Error,e)}function h(){for(;t.rx.isIdentifierChar(d.charCodeAt(p));)p++;let e=d.slice(f,p),r=d.charCodeAt(p);t.keywords.hasOwnProperty(e)?m(n.Keyword,e):34==r||39==r?x(e):m(n.Id,e)}function y(e){m(n.Op,e)}function v(e){let t=d.slice(f,p+1);if(2==t.length&&r.hasOwnProperty(t)){let n=d.slice(f,p+2);3==n.length&&r.hasOwnProperty(n)?(p+=2,e=r[n]):(p++,e=r[t])}y(e)}function b(e){switch(e){case 97:return 7;case 98:return 8;case 102:return 12;case 110:return 10;case 114:return 13;case 116:return 9;case 118:return 11;default:return 0}}function x(r){const i=d.charCodeAt(p++);let a=!1;d.charCodeAt(p)==i&&d.charCodeAt(p+1)==i&&(p+=2,a=!0);let o=(r=r.toLowerCase()).indexOf("r")>=0,s="",c="";for(;;){const n=d.charCodeAt(p++);if(n==i){if(!a)break;if(d.charCodeAt(p)==i&&d.charCodeAt(p+1)==i){p+=2;break}c+="\\"+String.fromCharCode(i),s+=String.fromCharCode(i)}else if(92==n){let n=d.charCodeAt(p++);if(13==n&&10==d.charCodeAt(p)&&(n=10,p++),34==n||39==n||92==n)o&&(c+="\\",s+="\\"),c+="\\"+String.fromCharCode(n),s+=String.fromCharCode(n);else if(!o&&b(n))c+="\\"+String.fromCharCode(n),s+=String.fromCharCode(b(n));else if(t.rx.isNewline(n))o&&(s+="\\"+String.fromCharCode(n),c+="\\\\",c+=10==n?"\\n":"\\u"+("0000"+n.toString(16)).slice(-4));else if(o||48!=n)if(o||117!=n&&120!=n)c+="\\\\"+String.fromCharCode(n),s+="\\"+String.fromCharCode(n);else{let t=117==n?4:2,r=d.slice(p,p+t);p+=t;let i=parseInt(r,16);isNaN(i)&&g(e.U.lf("invalid unicode or hex escape")),c+="\\"+String.fromCharCode(n)+r,s+=String.fromCharCode(i)}else c+="\\\\x00",s+="\0"}else{if(isNaN(n)){g(e.U.lf("end of file in a string"));break}if(t.rx.isNewline(n)&&!a){g(e.U.lf("new line in a string"));break}s+=String.fromCharCode(n),c+=String.fromCharCode(n)}}let l=m(n.String,s);l.quoted=c,l.stringPrefix=r}function k(){p--,x("")}function S(){m(n.NewLine,""),T()}function T(){let e=0;for(;;){const t=d.charCodeAt(p);if(9!=t){if(32!=t)break;e++,p++}else e=e+8&-8,p++}m(n.Indent,""+e)}function C(){let n=d.charCodeAt(p);t.rx.isNewline(n)?(p++,13==n&&10==d.charCodeAt(p)&&p++):g(e.U.lf("unexpected character after line continuation character"))}function E(){for(m(n.NewLine,"");p<d.length&&!t.rx.isNewline(d.charCodeAt(p));)p++;m(n.Comment,d.slice(f+1,p)),13==d.charCodeAt(p)&&10==d.charCodeAt(p+1)&&p++,p++,T()}function D(){let t=d[f],r="";if("0"==t){let i=d[p];const a=c[i];if(a){for(p++;;){const e=d[p];if(!a.test(e))break;r+=e,p++}if(r){let a=parseInt(r,l[i]);isNaN(a)&&g(e.U.lf("invalid number")),m(n.Number,t+i+r,a)}else g(e.U.lf("expecting numbers to follow 0b, 0o, 0x"));return}}let i=!1,a=!1,o=!1;for(p=f;;){const e=d.charCodeAt(p);if(!o||43!=e&&45!=e)if(o=!1,95==e||N(e));else if(a||i||46!=e){if(a||69!=e&&101!=e)break;a=!0,o=!0}else i=!0;else;r+=String.fromCharCode(e),p++}!i&&!a&&"0"==t&&r.length>1&&!/^0+/.test(r)&&g(e.U.lf("unexpected leading zero"));let s=parseFloat(r);isNaN(s)&&g(e.U.lf("invalid number")),m(n.Number,r,s)}function A(){N(d.charCodeAt(p))?D():m(n.Op,"Dot")}function N(e){return 48<=e&&e<=57}function w(){g(e.U.lf("invalid token"))}}}(e.py||(e.py={}))}(pxt||(pxt={})),function(e){!function(t){let n,r,i,a,o,s,c,l,u;function d(){return r[o]}function p(){for(;r[o];o++){let i=r[o];if(i.type!=t.TokenType.Comment){if(n>=0&&i.type==t.TokenType.Op)switch(i.value){case"LParen":case"LSquare":case"LBracket":n++;break;case"RParen":case"RSquare":case"RBracket":n--}if(i.type!=t.TokenType.Error){if(n>0){if(i.type==t.TokenType.NewLine||i.type==t.TokenType.Indent)continue}else if(i.type==t.TokenType.Indent){if(r[o+1].type==t.TokenType.NewLine){o++;continue}let n=parseInt(i.value),a=c[c.length-1];if(n==a)continue;if(n>a)return void c.push(n);{i.type=t.TokenType.Dedent;let a=0;for(;c.length;){let t=c[c.length-1];if(!(t>n)){for(t!=n&&_(9552,e.U.lf("inconsitent indentation"));a>1;)r.splice(o,0,i),a--;return}c.pop(),a++}}}return}_(9551,i.value)}else s.push(i)}}function f(){l=d(),l.type!=t.TokenType.EOF&&(o++,p())}function _(n,r){r||(r=e.U.lf("invalid syntax")),n||(n=9550);const o=d(),s={code:n,category:pxtc.DiagnosticCategory.Error,messageText:e.U.lf("{0} near {1}",r,t.friendlyTokenToString(o,i)),fileName:a,start:o.startPos,length:o.endPos?o.endPos-o.startPos:0,line:0,column:0};t.patchPosition(s,i),u.push(s),9572!=n&&u.length>100&&e.U.userError(e.U.lf("too many parse errors"))}function m(n,r){const i=d();(i.type==n&&i.value==r||(_(9553,e.U.lf("expecting {0}",t.tokenToString(function(e,t){return{type:e,value:t,startPos:0,endPos:0}}(n,r)))),i.type!=t.TokenType.NewLine))&&f()}function g(){m(t.TokenType.NewLine,"")}function h(e){m(t.TokenType.Keyword,e)}function y(e){m(t.TokenType.Op,e)}function v(){let e=d();return e.type==t.TokenType.Keyword?e.value:""}function b(){let e=d();return e.type==t.TokenType.Op?e.value:""}const x={if:function e(){let t=T("If");f(),t.test=V(),t.body=S(),"elif"==v()?t.orelse=[e()]:t.orelse=E();return C(t)},while:function(){let e=T("While");return h("while"),e.test=V(),e.body=S(),e.orelse=E(),C(e)},for:function(){let e=T("For");return h("for"),e.target=B(),$(e.target),h("in"),e.iter=U(),e.body=S(),e.orelse=E(),C(e)},try:function(){let e=T("Try");h("try"),e.body=S(),e.handlers=[];let t=!1;for(;"except"==v();){let n=T("ExceptHandler");e.handlers.push(n),f(),"Colon"!=b()?(t&&_(),n.type=V(),"as"==v()?(f(),n.name=ve()):n.name=void 0):(t=!0,n.type=void 0,n.name=void 0),n.body=S()}e.orelse=E(),0==e.handlers.length&&e.orelse.length&&_();"finally"==v()?(f(),e.finalbody=S()):e.finalbody=[];return C(e)},with:function(){let t=T("With");return h("with"),t.items=ge(e.U.lf("with item"),D),t.body=S(),C(t)},def:function(){let e=T("FunctionDef");h("def"),e.name=ve(),y("LParen"),e.args=J(!0),y("RParen"),e.returns=void 0,"Arrow"==b()&&(f(),e.returns=V());return e.body=S(),C(e)},class:function(){let e=T("ClassDef");if(h("class"),e.name=ve(),"LParen"==b()){let t=be();e.bases=t.args,e.keywords=t.keywords}else e.bases=[],e.keywords=[];return e.body=S(),C(e)}},k={del:function(){let t=T("Delete");return h("del"),t.targets=me(e.U.lf("expression"),oe),C(t)},pass:function(){let e=T("Pass");return h("pass"),C(e)},break:function(){let e=T("Break");return f(),C(e)},continue:function(){let e=T("Continue");return f(),C(e)},return:function(){let e=T("Return");f(),N()?e.value=void 0:e.value=U();return C(e)},raise:function(){let e=T("Raise");h("raise"),e.exc=void 0,e.cause=void 0,N()||(e.exc=V(),"from"==v()&&(f(),e.cause=V()));return C(e)},global:w,nonlocal:function(){let e=w();return e.kind="Nonlocal",e},import:function(){let t=T("Import");return f(),t.names=ge(e.U.lf("import name"),P),C(t)},from:function(){let n=T("ImportFrom");f(),n.level=F(),d().type==t.TokenType.Id?n.module=I():n.module=void 0;n.level||n.module||_();if(h("import"),"Mult"==b()){f();let e=T("Alias");e.name="*",n.names=[e]}else"LParen"==b()?(f(),n.names=me(e.U.lf("import name"),O),y("RParen")):n.names=me(e.U.lf("import name"),O);return C(n)},assert:function(){let e=T("Assert");f(),e.test=V(),"Comma"==b()?(f(),e.msg=V()):e.msg=void 0;return C(e)},yield:function(){d();if(f(),"from"==v()){let e=T("YieldFrom");return e.value=V(),A(C(e))}let e=T("Yield");N()||(e.value=U());return A(C(e))}};function S(){return y("Colon"),function(){if(d().type==t.TokenType.NewLine){let n;if(f(),d().type!=t.TokenType.Indent)_(9554,e.U.lf("expected an indented block")),n=z();else{const r=parseInt(d().value);for(f(),n=z();;){if(d().type==t.TokenType.Dedent){const e=isNaN(r)||parseInt(d().value)<r;if(f(),e)break}if(e.U.pushRange(n,z()),d().type==t.TokenType.EOF)break}}return n}return K()}()}function T(e,t){let n=t||d();return{startPos:n.startPos,endPos:n.endPos,kind:e}}function C(e){return e.endPos=l.endPos,e}function E(){return"else"==v()?(f(),S()):[]}function D(){let e=T("WithItem");return e.context_expr=V(),e.optional_vars=void 0,"as"==v()&&(f(),e.optional_vars=oe()),C(e)}function A(e){let t=T("ExprStmt");return t.startPos=e.startPos,t.endPos=e.endPos,t.value=e,t}function N(){let e=d();return e.type==t.TokenType.NewLine||e.type==t.TokenType.Op&&"Semicolon"==e.value}function w(){let e=T("Global");for(f(),e.names=[];e.names.push(ve()),"Comma"==b();)f();return C(e)}function I(){let e="";for(;;){if(e+=ve(),"Dot"!=b())return e;e+=".",f()}}function P(){let e=T("Alias");return e.name=I(),"as"==v()?(f(),e.asname=ve()):e.asname=void 0,C(e)}function O(){let e=T("Alias");return e.name=ve(),"as"==v()?(f(),e.asname=ve()):e.asname=void 0,C(e)}function F(){let e=0;for(;;)if("Dot"==b())e+=1,f();else{if("Ellipsis"!=b())return e;e+=3,f()}}function L(e,t){let n=T("Tuple",e);return n.elts=t,C(n)}function R(t){let n=d(),r=me(e.U.lf("expression"),t),i=r[0];return 1!=r.length?L(n,r):i}function M(){return R(ce)}function U(){return R(V)}function B(){return R(oe)}function $(e){if("Tuple"==e.kind){e.elts.forEach($)}else e.ctx="Store"}function j(){let n=e.U.lookup(k,v());return n?n():function(){let n=d(),r=M(),i=b();if("Assign"==i){let e=T("Assign");for(e.targets=[r];;){if(f(),r=M(),i=b(),"Assign"!=i){e.value=r;break}e.targets.push(r)}return e.targets.forEach($),C(e)}if("Colon"==i){let e=T("AnnAssign");return e.target=r,f(),e.annotation=V(),"Assign"==b()&&(f(),e.value=V()),e.simple=n.type==t.TokenType.Id&&"Name"==r.kind?1:0,$(e.target),C(e)}if(e.U.endsWith(i,"Assign")){let e=T("AugAssign");return e.target=r,e.op=i.replace("Assign",""),f(),e.value=U(),$(e.target),C(e)}if("Semicolon"==i||d().type==t.TokenType.NewLine){let e=T("ExprStmt");return e.value=r,C(e)}return _(9555,e.U.lf("unexpected token")),f(),null}()}function K(){let e=[j()];for(;"Semicolon"==b()&&(f(),d().type!=t.TokenType.NewLine);)e.push(j());return g(),e.filter((e=>!!e))}function z(){const r=u.length,i=d().type==t.TokenType.Indent;i&&(f(),_(9573,e.U.lf("unexpected indent")));let a=[];for(;"MatMult"==b();)f(),a.push(ke()),g();let o=v(),c=e.U.lookup(x,v()),p=[],m=s;if(s=[],"class"==o||"def"==o){let e=c();e.decorator_list=a,p=[e]}else a.length?_(9556,e.U.lf("decorators not allowed here")):p=c?[c()]:K();m.length&&p.length&&(p[0]._comments=m);if(u.length>r){for(n=-1;l.type!=t.TokenType.Dedent&&l.type!=t.TokenType.NewLine&&(f(),d().type!=t.TokenType.EOF););i&&d().type===t.TokenType.Dedent&&f(),n=0}return p}function J(n){let r=T("Arguments");for(r.args=[],r.defaults=[],r.kwonlyargs=[],r.kw_defaults=[],r.vararg=void 0;;){let n=b();if("Colon"==n||"RParen"==n)break;if("Mult"==n)r.vararg&&_(9557,e.U.lf("multiple *arg")),f(),d().type==t.TokenType.Id?r.vararg=i():r.vararg=void 0;else if("Pow"==n)r.kwarg&&_(9558,e.U.lf("multiple **arg")),f(),r.kwarg=i();else{r.kwarg&&_(9559,e.U.lf("arguments after **"));let t,n=i();"Assign"==b()&&(f(),t=V()),void 0!==r.vararg&&t?(r.kwonlyargs.push(n),r.kw_defaults.push(t)):(r.args.push(n),t?r.defaults.push(t):r.defaults.length&&_(9560,e.U.lf("non-default argument follows default argument")))}if("Comma"!=b())break;f()}return r.kwarg||(r.kwarg=void 0),r.vararg||(r.vararg=void 0),C(r);function i(){let e=T("Arg");return e.arg=ve(),e.annotation=void 0,n&&"Colon"==b()&&(f(),e.annotation=V()),e}}function q(e){let t=T("Lambda");return f(),t.args=J(!1),y("Colon"),t.body=e?le():V(),C(t)}function V(){if("lambda"==v())return q();let e=d(),t=W();if("if"==v()){let n=T("IfExp",e);return n.body=t,h("if"),n.test=W(),h("else"),n.orelse=V(),C(n)}return t}function H(e,t){let n=d(),r=t();if(v()==e){let i=T("BoolOp",n);for(i.op="or"==e?"Or":"And",i.values=[r];v()==e;)h(e),i.values.push(t());return C(i)}return r}function G(){return H("and",Q)}function W(){return H("or",G)}function Q(){if("not"==v()){let e=T("UnaryOp");return f(),e.op="Not",e.operand=Q(),C(e)}return function(){let e=d(),t=oe();if(!X())return t;let n=T("Compare",e);n.left=t,n.comparators=[],n.ops=[];for(;;){let e=X();if(!e)break;f(),"NotIn"==e?h("in"):"Is"==e&&"not"==v()&&(f(),e="IsNot"),n.ops.push(e),n.comparators.push(oe())}return C(n)}()}const Y={Lt:"Lt",Gt:"Gt",Eq:"Eq",GtE:"GtE",LtE:"LtE",NotEq:"NotEq",in:"In",not:"NotIn",is:"Is"};function X(){return Y[b()]||Y[v()]||null}const Z={Invert:"Invert",Sub:"USub",Add:"UAdd"};function ee(e,t){let n=d(),r=e();for(;;){let i=b();if(!(i&&t.indexOf(","+i+",")>=0))return r;{let t=T("BinOp",n);t.left=r,t.op=i,f(),t.right=e(),r=t}}}function te(){return ee(Se,",Mult,MatMult,Div,Mod,FloorDiv,")}function ne(){return ee(te,",Add,Sub,")}function re(){return ee(ne,",LShift,RShift,")}function ie(){return ee(re,",BitAnd,")}function ae(){return ee(ie,",BitXor,")}function oe(){return ee(ae,",BitOr,")}function se(){let t,n=d();if("Colon"!=b()&&(t=V()),"Colon"==b()){let e=T("Slice",n);e.lower=t,f();let r=b();return e.upper="Colon"!=r&&"Comma"!=r&&"RSquare"!=r?V():void 0,e.step=void 0,"Colon"==b()&&(f(),r=b(),"Comma"!=r&&"RSquare"!=r&&(e.step=V())),C(e)}{t||_(9570,e.U.lf("unable to parse lower subscript"));let n=T("Index");return n.value=t,C(n)}}function ce(){if("Mult"==b()){let e=T("Starred");return e.value=oe(),C(e)}return V()}function le(){return"lambda"==v()?q(!0):W()}function ue(){let e=[];for(;;){let t=T("Comprehension");for(t.is_async=0,e.push(t),h("for"),t.target=B(),$(t.target),h("in"),t.iter=W(),t.ifs=[];"if"==v();)f(),t.ifs.push(le());if("for"!=v())return e}}function de(){let t=d();if("Mult"==b()){let e=T("Starred");return f(),e.value=V(),C(e)}if("Pow"==b()){let e=T("Keyword");return f(),e.arg=void 0,e.value=V(),C(e)}let n=V();if("Assign"==b()){"Name"!=n.kind&&_(9561,e.U.lf("invalid keyword argument; did you mean ==?")),f();let r=T("Keyword",t);return r.arg=n.id||"???",r.value=V(),C(r)}if("for"==v()){let e=T("GeneratorExp",t);return e.elt=n,e.generators=ue(),C(e)}return n}function pe(){let e=T("NameConstant");return e.value=null,f(),C(e)}function fe(){let n=d();if(n.type==t.TokenType.Id){let e=T("Name");return f(),e.id=n.value,e.ctx="Load",C(e)}if(n.type==t.TokenType.Number){let e=T("Num");return f(),e.ns=n.value,e.n=n.auxValue,C(e)}if(n.type==t.TokenType.String){f();let r=n.value;for(;d().type==t.TokenType.String;)r+=d().value,f();if("b"==n.stringPrefix){let t=T("Bytes",n);return t.s=e.U.toArray(e.U.stringToUint8Array(r)),C(t)}{let e=T("Str",n);return e.s=r,C(e)}}if(n.type==t.TokenType.Keyword){if("None"==n.value||"True"==n.value||"False"==n.value){let e=T("NameConstant");return f(),e.value="True"==n.value||"False"!=n.value&&null,C(e)}return _(9564,e.U.lf("expecting atom")),pe()}if(n.type==t.TokenType.Op){let t=n.value;return"LParen"==t?ye("RParen","Tuple","GeneratorExp"):"LSquare"==t?ye("RSquare","List","ListComp"):"LBracket"==t?function(){let t=d();if(f(),"Pow"==b())return f(),r(void 0,oe());if("RBracket"==b()){let e=T("Dict",t);return f(),e.keys=[],e.values=[],C(e)}{let n=ce();return"Starred"!=n.kind&&"Colon"==b()?(f(),r(n,V())):function(n){if("for"==v()){"Starred"==n.kind&&_(9562,e.U.lf("iterable unpacking cannot be used in comprehension"));let r=T("SetComp",t);return r.elt=n,r.generators=ue(),C(r)}let r=T("Set",t);if(r.elts=[n],"Comma"==b()){let t=he("RBracket",e.U.lf("set element"),ce);r.elts=[n].concat(t)}else y("RBracket");return C(r)}(n)}function n(){if("Pow"==b())return f(),[null,oe()];{let e=V();return y("Colon"),[e,V()]}}function r(r,i){if("for"==v()){r||_(9563,e.U.lf("dict unpacking cannot be used in dict comprehension"));let n=T("DictComp",t);return n.key=r,n.value=i,n.generators=ue(),C(n)}let a=T("Dict",t);if(a.keys=[r],a.values=[i],"Comma"==b()){let t=he("RBracket",e.U.lf("dict element"),n);for(let e of t)e.length>=2&&e[0]&&e[1]&&(a.keys.push(e[0]),a.values.push(e[1]))}else y("RBracket");return C(a)}}():(_(9565,e.U.lf("unexpected operator")),pe())}return _(9566,e.U.lf("unexpected token")),pe()}function _e(){let n=b();return"RParen"==n||"RSquare"==n||"RBracket"==n||"Colon"==n||"Semicolon"==n||(!!e.U.endsWith(n,"Assign")||("in"==v()||d().type==t.TokenType.NewLine))}function me(t,n){let r=[];if(_e())return r;for(;;){r.push(n());let i="Comma"==b();if(i&&f(),_e())return r;if(!i)return _(9567,e.U.lf("expecting {0}",t)),r}}function ge(e,t){let n=[];for(;n.push(t()),"Comma"==b();)f();return n}function he(t,n,r){f();let i=[];if(b()!=t)for(;;){i.push(r());let a="Comma"==b();if(a&&f(),b()==t)break;if(!a){_(9568,e.U.lf("expecting {0}",n));break}}return y(t),i}function ye(t,n,r){let i=d();if(f(),b()==t){f();let e=T(n,i);return e.elts=[],C(e)}let a=ce();if("for"==v()){let e=T(r,i);return e.elt=a,e.generators=ue(),y(t),C(e)}if("Comma"==b()){let r=T(n,i);return f(),r.elts=me(e.U.lf("expression"),ce),r.elts.unshift(a),y(t),C(r)}if(y(t),"List"==n){let e=T(n,i);return e.elts=[a],C(e)}return a}function ve(){let n=d();return n.type!=t.TokenType.Id&&_(9569,e.U.lf("expecting identifier")),f(),n.value}function be(){let t=he("RParen",e.U.lf("argument"),de),n=[],r=[];for(let i of t)"Keyword"==i.kind?r.push(i):(r.length&&_(9570,e.U.lf("positional argument follows keyword argument")),n.push(i));return{args:n,keywords:r}}function xe(t,n){let r=b();if("LParen"==r){let e=T("Call",t);e.func=n;let r=be();return e.args=r.args,e.keywords=r.keywords,C(e)}if("LSquare"==r){let r=d(),i=T("Subscript",t);i.value=n;let a=he("RSquare",e.U.lf("subscript"),se);if(0==a.length)_(9571,e.U.lf("need non-empty index list"));else if(1==a.length)i.slice=a[0];else if(a.every((e=>"Index"==e.kind))){let e=a[0];e.value=L(r,a.map((e=>e.value))),i.slice=e}else{let e=T("ExtSlice",r);e.dims=a,i.slice=C(e)}return C(i)}if("Dot"==r){let e=T("Attribute",t);return e.value=n,f(),e.attr=ve(),C(e)}return n}function ke(){let e=d(),t=fe();for(;;){let n=xe(e,t);if(n===t)return t;t=n}}function Se(){if(Z[b()]){let e=T("UnaryOp");return e.op=Z[b()],f(),e.operand=Se(),C(e)}return function(){d();let e=ke();if("Pow"==b()){let t=T("BinOp");return f(),t.left=e,t.op="Pow",t.right=Se(),C(t)}return e}()}const Te={kind:1,id:2,n:3,s:4,func:5,key:6,elt:7,elts:8,keys:9,left:10,ops:11,comparators:12,names:13,items:14,test:15,targets:16,dims:17,context_expr:18,name:19,bases:20,type:21,inClass:22,target:23,annotation:24,simple:25,op:26,operand:27,right:28,values:29,iter:30,ifs:31,is_async:32,value:33,slice:34,attr:35,generators:36,args:37,keywords:38,body:39,handlers:40,orelse:41,finalbody:42,decorator_list:43,kwonlyargs:44,kw_defaults:45,defaults:46,arg:47},Ce={lineno:1,col_offset:1,startPos:1,endPos:1,kind:1},Ee={body:1,orelse:1,finalbody:1},De={_comments:1,ctx:1,ns:1};t.dump=function(t,n=!1){const r=(t,i)=>{if(Array.isArray(i)){let e="";for(let n=0;n<i.length;++n)n>0&&(e+=", "),e+=r(t,i[n]);return"["+e+"]"}if(!i||!i.kind)return JSON.stringify(i);let a="",o=Object.keys(i);o.sort(((t,n)=>(Te[t]||100)-(Te[n]||100)||e.U.strcmp(t,n)));for(let s of o)if(!(e.U.lookup(Ce,s)||n&&e.U.lookup(De,s)))if(a&&(a+=", "),a+=s+"=",Array.isArray(i[s])&&i[s].length&&e.U.lookup(Ee,s)){a+="[\n";let e=t+" ";for(let t of i[s])a+=e+r(e,t)+"\n";a+=t+"]"}else if("_comments"==s){a+="[\n";let e=t+" ";for(let t of i[s])a+=e+JSON.stringify(t.value)+"\n";a+=t+"]"}else a+=r(t,i[s]);return i.kind+"("+a+")"};let i="";for(let e of t)i+=r("",e)+"\n";return i},t.parse=function(f,m,g){i=f,a=m,r=g,n=0,o=0,s=[],c=[0],u=[];let h=[];try{if(l=r[0],p(),d().type!=t.TokenType.EOF)for(h=z();d().type!=t.TokenType.EOF;)e.U.pushRange(h,z())}catch(t){_(9572,e.U.lf("exception: {0}",t.message))}return{stmts:h,diagnostics:u}}}(e.py||(e.py={}))}(pxt||(pxt={})),function(e){!function(t){function n(e,t,n){const r={fileName:e.getSourceFile().fileName,start:e.getStart(),length:e.getEnd()-e.getStart(),line:void 0,column:void 0,code:t,category:pxtc.DiagnosticCategory.Error,messageText:n},i=new Error(n);throw i.pyDiagnostic=r,i}t.decompileToPython=function(r,i){let a={blocksInfo:void 0,outfiles:{},diagnostics:[],success:!0,times:{}};try{let o=function(r,i){const a=r.getTypeChecker(),o=(new ts.pxtc.LSHost(r),r.getSourceFile(i)),s=pxtc.decompiler.buildCommentMap(o),c=e.U.toSet(_(),(e=>e)),[l,u]=ts.pxtc.decompiler.buildRenameMap(r,o,{takenNames:c,declarations:"all"}),d=pxtc.getApiInfo(r),p=e.U.mapMap(d.byQName,((e,t)=>t.fileName==i?void 0:t)),f=t.computeScopeVariableLookup(o);return S(o);function _(){return["ArithmeticError","AssertionError","AttributeError","BaseException","BlockingIOError","BrokenPipeError","BufferError","BytesWarning","ChildProcessError","ConnectionAbortedError","ConnectionError","ConnectionRefusedError","ConnectionResetError","DeprecationWarning","EOFError","Ellipsis","EnvironmentError","Exception","False","FileExistsError","FileNotFoundError","FloatingPointError","FutureWarning","GeneratorExit","IOError","ImportError","ImportWarning","IndentationError","IndexError","InterruptedError","IsADirectoryError","KeyError","KeyboardInterrupt","LookupError","MemoryError","NameError","None","NotADirectoryError","NotImplemented","NotImplementedError","OSError","OverflowError","PendingDeprecationWarning","PermissionError","ProcessLookupError","RecursionError","ReferenceError","ResourceWarning","RuntimeError","RuntimeWarning","StopAsyncIteration","StopIteration","SyntaxError","SyntaxWarning","SystemError","SystemExit","TabError","TimeoutError","True","TypeError","UnboundLocalError","UnicodeDecodeError","UnicodeEncodeError","UnicodeError","UnicodeTranslateError","UnicodeWarning","UserWarning","ValueError","Warning","ZeroDivisionError","_","__build_class__","__debug__","__doc__","__import__","__loader__","__name__","__package__","__spec__","abs","all","any","ascii","bin","bool","bytearray","bytes","callable","chr","classmethod","compile","complex","copyright","credits","delattr","dict","dir","divmod","enumerate","eval","exec","exit","filter","float","format","frozenset","getattr","globals","hasattr","hash","help","hex","id","input","int","isinstance","issubclass","iter","len","license","list","locals","map","max","memoryview","min","next","object","oct","open","ord","pow","print","property","quit","range","repr","reversed","round","set","setattr","slice","sorted","staticmethod","str","sum","super","tuple","type","vars","zip",...Object.keys(e.py.keywords)]}function m(e){if(!e.getSourceFile())return null;let t=e.getText();return p[t]||null}function g(e){if(!e.getSourceFile())return null;let t=e.getText();const n=a.getSymbolAtLocation(e);n&&(t=a.getFullyQualifiedName(n));let r=p[t];if(r&&r.attributes.alias)return r.attributes.alias;if(r&&r.pyQName){if(r.isInstance){if(ts.isPropertyAccessExpression(e))return null;const t=new RegExp(`(?:^|.)${r.namespace}.(.+)`).exec(r.pyQName);if(t)return t[1]}return r.pyQName}return t in pxtc.ts2PyFunNameMap?pxtc.ts2PyFunNameMap[t].n:null}function h(t){let r=g(t);if(r)return r;if(!ts.isIdentifier(t))return e.tickEvent("depython.todo.advancedname"),n(t,3001,"Unsupported advanced name format: "+t.getText());let i=t.text;if(t.getSourceFile()){const e=l.getRenameForPosition(t.getStart());e&&(i=e.name)}return i}function y(e){return"string"!=typeof e&&(e=h(e)),u[e]?pxtc.decompiler.getNewName(e,u):(u[e]=!0,e)}function v(e,t){return 0!=(e.flags&t)}function b(e,t){return v(a.getTypeAtLocation(e),t)}function x(e){return b(e,ts.TypeFlags.StringLike)}function k(e){return b(e,ts.TypeFlags.NumberLike)}function S(e){let t=e.getChildren().map(T).reduce(((e,t)=>e.concat(t)),[]).reduce(((e,t)=>t||e[e.length-1]?[...e,t]:e),[]);return s.filter((e=>!e.owner)).forEach((e=>t.push(...C(e)))),t.join("\n")}function T(e){switch(e.kind){case ts.SyntaxKind.SyntaxList:return e._children.map(T).reduce(((e,t)=>e.concat(t)),[]);case ts.SyntaxKind.EndOfFileToken:case ts.SyntaxKind.OpenBraceToken:case ts.SyntaxKind.CloseBraceToken:return[];default:return E(e)}}function C(e){let t=[];if(e.kind===pxtc.decompiler.CommentKind.SingleLine)t.push("# "+e.text);else{t.push('"""');for(const n of e.lines)t.push(n);t.push('"""')}return t}function E(e){const t=D(e);return pxtc.decompiler.getCommentsForStatement(e,s).map(C).reduce(((e,t)=>e.concat(t)),[]).concat(t)}function D(t){return ts.isVariableStatement(t)?B(t):ts.isClassDeclaration(t)?$(t):ts.isEnumDeclaration(t)?j(t):ts.isExpressionStatement(t)?J(t):ts.isFunctionDeclaration(t)?V(t):ts.isIfStatement(t)?M(t):ts.isForStatement(t)?R(t):ts.isForOfStatement(t)?L(t):ts.isWhileStatement(t)?I(t):ts.isReturnStatement(t)?w(t):ts.isBlock(t)?q(t):ts.isTypeAliasDeclaration(t)?N(t):ts.isEmptyStatement(t)?[]:ts.isModuleDeclaration(t)?A(t):ts.isBreakStatement(t)?["break"]:ts.isContinueStatement(t)?["continue"]:(e.tickEvent("depython.todo.statement",{statement:t.kind}),n(t,3002,`Not supported in MakeCode Python: ${ts.SyntaxKind[t.kind]} (${t.kind})`))}function A(e){let n=h(e.name),r=e.body&&e.body.getChildren().map(T).reduce(((e,t)=>e.concat(t)),[]).map((e=>t.indent1(e)));return["@namespace",`class ${n}:`].concat(r||[])}function N(e){let t=pxtc.emitPyTypeFromTypeNode(e.type);return[`${h(e.name)} = ${t}`]}function w(e){if(!e.expression)return["return"];let[t,n]=ve(e.expression),r=Y("return ",t);return n.concat(r)}function I(e){let[t,n]=ve(e.expression),r=F(e.statement),i=Y("while ",t,":");return n.concat(i).concat(r)}function P(e){let t=Math.floor(Number(e));return t!==1/0&&String(t)===e}function O(e){if(!e.initializer)return null;if(e.initializer.kind!==ts.SyntaxKind.VariableDeclarationList)return null;let t=e.initializer;if(1!==t.declarations.length)return null;let n=t.declarations[0],r=h(n.name);if(!n.initializer||!he(n.initializer)||!k(n.initializer))return null;let[i,a]=ve(n.initializer);if(a.length)return null;let o=Q(i);if(!e.condition)return null;if(!ts.isBinaryExpression(e.condition))return null;if(!ts.isIdentifier(e.condition.left))return null;if(h(e.condition.left)!=r)return null;if(!k(e.condition.right))return null;let[s,c]=ve(e.condition.right);if(c.length)return null;let l=Q(s),u=l;if(e.condition.operatorToken.kind===ts.SyntaxKind.LessThanEqualsToken&&P(l))u=""+(Number(l)+1);else if(e.condition.operatorToken.kind!==ts.SyntaxKind.LessThanToken)return null;return e.incrementor&&(ts.isPostfixUnaryExpression(e.incrementor)||ts.isPrefixUnaryExpression(e.incrementor))?e.incrementor.operator!==ts.SyntaxKind.PlusPlusToken?null:o<u?{name:r,fromIncl:o,toExcl:u}:null:null}function F(e){let n=D(e).map(t.indent1);return n.length<1&&(n=[t.indent1("pass")]),n}function L(t){if(!ts.isVariableDeclarationList(t.initializer))return e.tickEvent("depython.todo.forof.complexexp"),n(t,3003,"Unsupported expression in for..of initializer: "+t.initializer.getText());let r=t.initializer.declarations.map((e=>h(e.name)));if(1!==r.length)return e.tickEvent("depython.todo.forof.multidecl"),n(t,3004,"Unsupported multiple declerations in for..of: "+t.initializer.getText());let i=r[0],[a,o]=ve(t.expression),s=o;s=s.concat(Y(`for ${i} in `,a,":"));let c=F(t.statement);return s=s.concat(c),s}function R(e){let n=O(e);if(n){let{name:t,fromIncl:r,toExcl:i}=n,a="0"===r?`for ${t} in range(${i}):`:`for ${t} in range(${r}, ${i}):`,o=F(e.statement);return[a].concat(o)}let r,i=[];if(e.initializer)if(ts.isVariableDeclarationList(e.initializer)){let t=e.initializer.declarations.map(G).reduce(((e,t)=>e.concat(t)),[]);i=i.concat(t)}else{let[t,n]=ve(e.initializer);i=i.concat(n).concat(t)}if(e.condition){let[t,n]=ve(e.condition);i=i.concat(n),r=Q(t)}else r="True";let a=`while ${r}:`;i.push(a);let o=D(e.statement).map(t.indent1);if(0!==o.length||e.incrementor||(o=[t.indent1("pass")]),i=i.concat(o),e.incrementor){let n=z(e.incrementor);if(n)i=i.concat(n.map(t.indent1));else{let[n,r]=ve(e.incrementor);i=i.concat(r).concat(n.map(t.indent1))}}return i}function M(e){let{supportStmts:t,ifStmt:n,rest:r}=U(e);return t.concat([n]).concat(r)}function U(e){let t=[],[n,r]=ve(e.expression);t=t.concat(r);let i=`if ${Q(n)}:`,a=[],o=F(e.thenStatement);if(a=a.concat(o),e.elseStatement)if(ts.isIfStatement(e.elseStatement)){let{supportStmts:n,ifStmt:r,rest:i}=U(e.elseStatement),o=`el${r}`;t=t.concat(n),a.push(o),a=a.concat(i)}else{a.push("else:");let t=F(e.elseStatement);a=a.concat(t)}return{supportStmts:t,ifStmt:i,rest:a}}function B(e){return e.declarationList.declarations.map(G).reduce(((e,t)=>e.concat(t)),[])}function $(t){return e.tickEvent("depython.todo.classes"),n(t,3016,"Unsupported: classes are not supported in Python right now.")}function j(r){let i=[];i.push(`class ${h(r.name)}(Enum):`);let a=r.members.every((e=>!!e.initializer)),o=!r.members.every((e=>!!e.initializer));if(!a&&!o)return e.tickEvent("depython.todo.enummix"),n(r,3005,"Unsupported enum decleration: has mixture of explicit and implicit initialization");if(a)return e.tickEvent("depython.todo.enuminit"),n(r,3006,"Unsupported: explicit enum initialization");let s=0;for(let e of r.members)i.push(t.indent1(`${h(e.name)} = ${s++}`));return i}function K(e){return!(!ts.isPrefixUnaryExpression(e)&&!ts.isPostfixUnaryExpression(e))&&(e.operator===ts.SyntaxKind.MinusMinusToken||e.operator===ts.SyntaxKind.PlusPlusToken)}function z(e){if(!K(e))return null;let[t,n]=ve(e.operand),r=e.operator===ts.SyntaxKind.MinusMinusToken?" -= 1":" += 1",i=n;return i.push(`${Q(t)}${r}`),i}function J(e){let t=z(e.expression);if(t)return t;const[n,r]=ve(e.expression);return r.length?["",...r,...n,""]:[...r,...n]}function q(e){return e.getChildren().map(T).reduce(((e,t)=>e.concat(t)),[])}function V(r,i,a,o){let s=[];r.kind!==ts.SyntaxKind.MethodDeclaration&&r.kind!==ts.SyntaxKind.Constructor||s.push("self");let c=(a?oe(r.parameters,a):r.parameters).map((e=>H(e,!o)));s=s.concat(c);let l,u=s.join(", "),d=[];if(i)l=i;else{if(!r.name)return e.tickEvent("depython.todo.anonymousfunc"),n(r,3012,"Unsupported: anonymous function decleration");l=h(r.name)}if(d.push(`def ${l}(${u}):`),!r.body)return e.tickEvent("depython.todo.funcwithoutbody"),n(r,3013,"Unsupported: function decleration without body");let p=[];if(ts.isBlock(r.body))p=q(r.body);else{let[e,t]=ve(r.body);p=p.concat(t),p.concat(e)}if(p.length){let e=f.getExplicitGlobals(r).map((e=>h(e)));e&&e.length&&p.unshift(`global ${e.join(", ")}`);let n=f.getExplicitNonlocals(r).map((e=>h(e)));n&&n.length&&p.unshift(`nonlocal ${n.join(", ")}`),d=d.concat(p.map(t.indent1))}else d.push(t.indent1("pass"));return d}function H(t,r=!0){let i=t.altName||h(t.name),a="";if(t.type&&r){let e=pxtc.emitPyTypeFromTypeNode(t.type);e&&-1===e.indexOf("(TODO")&&(a=`: ${e}`)}let o="";if(t.initializer){let[r,i]=ve(t.initializer);if(i.length)return e.tickEvent("depython.todo.complexinit"),n(t,3007,`Unsupported: complex expression in parameter default value not supported. Expression: ${t.initializer.getText()}`);o=` = ${Q(r)}`}return`${i}${a}${o}`}function G(e){let t=[],n=h(e.name);if(e.initializer){let r,[i,a]=ve(e.initializer);if(t=t.concat(a),e.type){r=`${n}: ${pxtc.emitPyTypeFromTypeNode(e.type)} = ${Q(i)}`}else r=`${n} = ${Q(i)}`;return t.push(r),t}return t}function W(e,t){return[[e],t||[]]}function Q(e,t="\n"){return e.join(t)}function Y(e="",t,n=""){return t[0]=e+t[0],t[t.length-1]=t[t.length-1]+n,t}function X(t,r){switch(t){case ts.SyntaxKind.BarBarToken:return"or";case ts.SyntaxKind.AmpersandAmpersandToken:return"and";case ts.SyntaxKind.ExclamationToken:return"not";case ts.SyntaxKind.LessThanToken:return"<";case ts.SyntaxKind.LessThanEqualsToken:return"<=";case ts.SyntaxKind.GreaterThanToken:return">";case ts.SyntaxKind.GreaterThanEqualsToken:return">=";case ts.SyntaxKind.EqualsEqualsEqualsToken:case ts.SyntaxKind.EqualsEqualsToken:return"==";case ts.SyntaxKind.ExclamationEqualsEqualsToken:case ts.SyntaxKind.ExclamationEqualsToken:return"!=";case ts.SyntaxKind.EqualsToken:return"=";case ts.SyntaxKind.PlusToken:return"+";case ts.SyntaxKind.MinusToken:return"-";case ts.SyntaxKind.AsteriskToken:return"*";case ts.SyntaxKind.PlusEqualsToken:return"+=";case ts.SyntaxKind.MinusEqualsToken:return"-=";case ts.SyntaxKind.PercentToken:return"%";case ts.SyntaxKind.SlashToken:return"/";case ts.SyntaxKind.PlusPlusToken:case ts.SyntaxKind.MinusMinusToken:return e.tickEvent("depython.todo.unsupportedop",{op:t}),n(r,3008,"Unsupported ++ and -- in an expression (not a statement or for loop)");case ts.SyntaxKind.AmpersandToken:return"&";case ts.SyntaxKind.CaretToken:return"^";case ts.SyntaxKind.LessThanLessThanToken:return"<<";case ts.SyntaxKind.GreaterThanGreaterThanToken:return">>";case ts.SyntaxKind.GreaterThanGreaterThanGreaterThanToken:return e.tickEvent("depython.todo.unsupportedop",{op:t}),n(r,3009,"Unsupported operator: >>>");case ts.SyntaxKind.AsteriskAsteriskToken:return"**";case ts.SyntaxKind.AsteriskAsteriskEqualsToken:return"**=";case ts.SyntaxKind.PercentEqualsToken:return"%=";case ts.SyntaxKind.AsteriskEqualsToken:return"*=";case ts.SyntaxKind.SlashEqualsToken:return"/=";default:return e.tickEvent("depython.todo.unsupportedop",{op:t}),n(r,3008,`Unsupported Python operator (code: ${t})`)}}function Z(e){let t=x(e.left),n=x(e.right),r=e.operatorToken.kind===ts.SyntaxKind.PlusToken&&(t||n),[i,a]=ve(e.left);r&&!t&&(i=Y("str(",i,")"));let o=X(e.operatorToken.kind,e),[s,c]=ve(e.right);r&&!n&&(s=Y("str(",s,")"));let l=a.concat(c);return[Y(Q(i)+" "+o+" ",s),l]}function ee(e){let t=g(e);if(t)return W(t);let[n,r]=ve(e.expression),i=h(e.name);return W("length"===i?`len(${Q(n)})`:`${Q(n)}.${i}`,r)}function te(e){if(ts.isPropertyAccessExpression(e)){let t=h(e.name),n=t.substr(t.lastIndexOf(".")+1);return ts.isIdentifier(e.expression)?[n]:te(e.expression).concat([n])}return ts.isIdentifier(e)?[h(e)]:[]}function ne(t,n,r,i){let o="";n&&(o=te(n).map(e.U.snakify).join("_"));let s=[];if(r&&r.length>1&&i&&i.length>1)for(let t=0;t<r.length&&t<i.length;t++){let n=i[t];if(v(a.getTypeAtLocation(n),ts.TypeFlags.EnumLike)){let t=te(n).map(e.U.snakify);s=s.concat(t)}}let c=s.join("_"),l="";o||c||!t||(l=h(t.name));let u=([o,c,l].filter((e=>e)).map(e.U.snakify).map((e=>e.toLowerCase())).join("_")||"my_callback").split("_");u.length>4&&(u=p(u));let d=e.U.toDictionary(["any","on","event"],(e=>e));for(;u.length>2;){let e=f(u,d);if(e.length==u.length)break;u=e}return u=["on",...u],u.join("_");function p(e){let t={},n=[];for(let r of e)r in t||(t[r]=!0,n.push(r));return n}function f(e,t){let n=[],r=!1;for(let i of e)!(i in t)||r?n.push(i):r=!0;return n}}function re(e){let n=e.join(", ");return n.length>60&&e.length>1?e.map(((n,r)=>{let i=","==n.charAt(n.length-1)?"":",";if(0==r){let e=n.split("\n");if(e.length>1){n=e.shift()+"\n"+t.indent1(e.join("\n"))}return n+i}return r==e.length-1?t.indent1(n):t.indent1(n+i)})):[n]}function ie(e,t,n,r,i){if((ts.isFunctionExpression(e)||ts.isArrowFunction(e))&&t&&t.type&&ts.isFunctionTypeNode(t.type)){let a;return se(e,ne(t,n,r,i),a,!0)}return ve(e)}function ae(t){let r=a.getTypeAtLocation(t.expression),i=a.typeToTypeNode(r),o=ts.createNodeArray([]);if(ts.isFunctionTypeNode(i)&&(o=i.parameters,t.arguments&&o.length<t.arguments.length))return e.tickEvent("depython.todo.argparammismatch",{kind:t.kind}),n(t,3010,"TODO: Unsupported call site where caller the arguments outnumber the callee parameters: "+t.getText());const s=m(t.expression);if(t.arguments&&s&&"TD_ID"==s.attributes.shim)return ve(t.arguments[0]);if(ts.isPropertyAccessExpression(t.expression)&&"toString"===t.expression.name.getText()){const[e,n]=ve(t.expression.expression);return[Y("str(",e,")"),n]}let[c,l]=ve(t.expression),u=Q(c),d=(t.arguments||ts.createNodeArray()).map(((e,n,r)=>ie(e,o[n],t.expression,o,r))),p=d.map((([e,t])=>t)).reduce(((e,t)=>e.concat(t)),l);if(0===u.indexOf("_py.py_")){if(d.length<=0)return e.tickEvent("depython.todo._pynoargs"),n(t,3014,"Unsupported: call expression has no arguments for _py.py_ fn");u=u.substr(7).split("_").filter(((e,t)=>0!==t)).join("_");return[Y(`${d.shift()[0]}.${u}(`,re(d.map((([e,t])=>e)).reduce(((e,t)=>e.concat(t)),[])),")"),p]}return[Y(`${u}(`,re(d.map((([e,t])=>e)).reduce(((e,t)=>e.concat(t)),[])),")"),p]}function oe(e,t){let n=[],r={};for(let i=0;i<Math.max(e.length,t.length);i++){let a;if(e[i])a=e[i],r[h(a.name)]=!0;else{a=t[i];let e=h(a.name);r[e]&&(e=pxtc.decompiler.getNewName(e,r),a=Object.assign({altName:e},t[i]))}n.push(a)}return ts.createNodeArray(n,!1)}function se(e,t,n,r){let i=e.name?h(e.name):y(t||"my_function");return W(i,V(e,i,n,r))}function ce(e){switch(e){case ts.SyntaxKind.ExclamationToken:return" ";case ts.SyntaxKind.PlusToken:case ts.SyntaxKind.MinusToken:return"";default:return" "}}function le(e){let t=X(e.operator,e),[n,r]=ve(e.operand);return W(`${t}${ce(e.operator)}${Q(n)}`,r)}function ue(e){let t=X(e.operator,e),[n,r]=ve(e.operand),i=ce(e.operator);return W(`${Q(n)}${i}${t}`,r)}function de(e){let t=e.elements.map(ve),n=t.map((([e,t])=>t)).reduce(((e,t)=>e.concat(t)),[]);return[Y("[",re(t.map((([e,t])=>e)).reduce(((e,t)=>e.concat(t)),[])),"]"),n]}function pe(t){if(!t.argumentExpression)return e.tickEvent("depython.todo.accesswithoutexp"),n(t,3015,"Unsupported: element access expression without an argument expression");let[r,i]=ve(t.expression),[a,o]=ve(t.argumentExpression),s=i.concat(o);return W(`${Q(r)}[${Q(a)}]`,s)}function fe(e){let[t,n]=ve(e.expression);return W(`(${Q(t)})`,n)}function _e(e){if(ts.isNoSubstitutionTemplateLiteral(e))return W(`"""\n${t.indent1(e.text.trim())}\n"""`);let[n,r]=ve(e.tag),[i,a]=ve(e.template),o=r.concat(a);return W(`${Q(n)}(${Q(i)})`,o)}function me(e){if("undefined"==e.text)return W("None");return W(h(e))}function ge(e,t){let n=e=>ge(e,t);return ts.isBinaryExpression(e)?n(e.left)&&n(e.right):ts.isPropertyAccessExpression(e)?n(e.expression):ts.isPrefixUnaryExpression(e)||ts.isPostfixUnaryExpression(e)?e.operator!==ts.SyntaxKind.PlusPlusToken&&e.operator!==ts.SyntaxKind.MinusMinusToken&&n(e.operand):ts.isParenthesizedExpression(e)?n(e.expression):ts.isArrayLiteralExpression(e)?e.elements.map(n).reduce(((e,t)=>e&&t),!0):ts.isElementAccessExpression(e)?n(e.expression)&&(!e.argumentExpression||n(e.argumentExpression)):t(e)}function he(e){return ge(e,(e=>{switch(e.kind){case ts.SyntaxKind.PropertyAccessExpression:case ts.SyntaxKind.BinaryExpression:case ts.SyntaxKind.ParenthesizedExpression:case ts.SyntaxKind.ArrayLiteralExpression:case ts.SyntaxKind.ElementAccessExpression:case ts.SyntaxKind.TrueKeyword:case ts.SyntaxKind.FalseKeyword:case ts.SyntaxKind.NullKeyword:case ts.SyntaxKind.UndefinedKeyword:case ts.SyntaxKind.NumericLiteral:case ts.SyntaxKind.StringLiteral:case ts.SyntaxKind.NoSubstitutionTemplateLiteral:return!0;case ts.SyntaxKind.CallExpression:case ts.SyntaxKind.NewExpression:case ts.SyntaxKind.FunctionExpression:case ts.SyntaxKind.ArrowFunction:case ts.SyntaxKind.Identifier:case ts.SyntaxKind.ThisKeyword:return!1;case ts.SyntaxKind.PrefixUnaryExpression:case ts.SyntaxKind.PostfixUnaryExpression:let t=e;return t.operator!==ts.SyntaxKind.PlusPlusToken&&t.operator!==ts.SyntaxKind.MinusMinusToken}return!1}))}function ye(e){let[t,n]=ve(e.condition),[r,i]=ve(e.whenTrue),[a,o]=ve(e.whenFalse),s=n.concat(i).concat(o);return W(`${r} if ${Q(t)} else ${Q(a)}`,s)}function ve(t){if(ts.isBinaryExpression(t))return Z(t);if(ts.isPropertyAccessExpression(t))return ee(t);if(ts.isCallExpression(t))return ae(t);if(ts.isNewExpression(t))return ae(t);if(ts.isFunctionExpression(t)||ts.isArrowFunction(t))return se(t);if(ts.isPrefixUnaryExpression(t))return le(t);if(ts.isPostfixUnaryExpression(t))return ue(t);if(ts.isParenthesizedExpression(t))return fe(t);if(ts.isArrayLiteralExpression(t))return de(t);if(ts.isElementAccessExpression(t))return pe(t);if(ts.isNoSubstitutionTemplateLiteral(t)||ts.isTaggedTemplateExpression(t))return _e(t);switch(t.kind){case ts.SyntaxKind.TrueKeyword:return W("True");case ts.SyntaxKind.FalseKeyword:return W("False");case ts.SyntaxKind.ThisKeyword:return W("self");case ts.SyntaxKind.NullKeyword:case ts.SyntaxKind.UndefinedKeyword:return W("None")}return ts.isIdentifier(t)?me(t):ts.isNumericLiteral(t)||ts.isStringLiteral(t)?W(t.getText()):ts.isConditionalExpression(t)?ye(t):(e.tickEvent("depython.todo.expression",{kind:t.kind}),n(t,3017,"Unsupported expression kind: "+t.kind))}}(r,i),s=i.replace(/(\.py)?\.\w*$/i,"")+".py";a.outfiles[s]=o}catch(t){t.pyDiagnostic?a.diagnostics=[t.pyDiagnostic]:e.reportException(t),a.success=!1}return a};function r(e){return n=>(n||"").split("\n").map((n=>`${t.INDENT.repeat(e)}${n}`)).join("\n")}t.INDENT=" ",t.indent=r,t.indent1=r(1)}(e.py||(e.py={}))}(pxt||(pxt={})),function(e){!function(e){!function(e){const t=/[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;e.isIdentifierStart=function(e){return ts.pxtc.isIdentifierStart(e,ts.pxtc.ScriptTarget.ES5)},e.isIdentifierChar=function(e){return ts.pxtc.isIdentifierPart(e,ts.pxtc.ScriptTarget.ES5)},e.isSpace=function(e){return!!(32===e||9===e||11===e||12===e||160===e||e>=5760&&t.test(String.fromCharCode(e)))},e.isNewline=function(e){return 10===e||13===e||(8232===e||8233===e)}}(e.rx||(e.rx={}))}(e.py||(e.py={}))}(pxt||(pxt={})),function(e){!function(e){function t(e){const t={refs:[],children:[],owner:void 0};return function e(r){var i;if(!r)return t;if(ts.isPropertyAccessOrQualifiedName(r))return t;if(ts.isIdentifier(r))return{refs:[{kind:"read",node:r,varName:r.text}],children:[],owner:void 0};if(ts.isVariableDeclaration(r)||ts.isParameter(r)){const t=e(r.initializer);return{refs:[...t.refs,{kind:"decl",node:r,varName:r.name.getText()}],children:t.children,owner:void 0}}if(ts.isPrefixUnaryExpression(r)||ts.isPostfixUnaryExpression(r)){const t=e(r.operand),i=r.operand.getText();return n(t,{refs:[{kind:"assign",node:r,varName:i}],children:[],owner:void 0})}if(function(e){const t=[ts.SyntaxKind.EqualsToken,ts.SyntaxKind.PlusEqualsToken,ts.SyntaxKind.MinusEqualsToken,ts.SyntaxKind.AsteriskEqualsToken,ts.SyntaxKind.AsteriskAsteriskEqualsToken,ts.SyntaxKind.SlashEqualsToken,ts.SyntaxKind.PercentEqualsToken,ts.SyntaxKind.LessThanLessThanEqualsToken,ts.SyntaxKind.GreaterThanGreaterThanEqualsToken,ts.SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken,ts.SyntaxKind.AmpersandEqualsToken,ts.SyntaxKind.BarEqualsToken,ts.SyntaxKind.CaretEqualsToken];return ts.isBinaryExpression(e)&&t.some((t=>e.operatorToken.kind===t))}(r)){const t=e(r.right);let i;r.operatorToken.kind!==ts.SyntaxKind.EqualsToken&&(i=e(r.left));const a=r.left.getText();return n(i,n(t,{refs:[{kind:"assign",node:r,varName:a}],children:[],owner:void 0}))}if(ts.isFunctionExpression(r)||ts.isArrowFunction(r)||ts.isFunctionDeclaration(r)||ts.isMethodDeclaration(r)){const a=null===(i=r.name)||void 0===i?void 0:i.getText();let o;a&&(o={kind:"decl",node:r,varName:a});const s=r.parameters.map((t=>e(t))).reduce(n,t),c=e(r.body),l=n(s,c);return l.owner=r,{refs:o?[o]:[],children:[l],owner:void 0}}return r.getChildren().map(e).reduce(n,t)}(e);function n(e,n){return e&&n?{refs:[...e.refs,...n.refs],children:[...e.children,...n.children],owner:e.owner||n.owner}:e||n||t}}function n(e,t,r=[]){const i=[],a=[],o=[],s=[],c={};for(const n of e.refs)"read"===n.kind||"assign"===n.kind?c[n.varName]?o.push(n):d(n)?a.push(n):t&&t[n.varName]?i.push(n):s.push(n):c[n.varName]=n;const l=t||c,u=t?[...r,c]:[];return{globalUsage:i,nonlocalUsage:a,localUsage:o,environmentUsage:s,children:e.children.map((e=>n(e,l,u))),owner:e.owner};function d(e){return r.map((t=>t[e.varName])).reduce(((e,t)=>t||e),void 0)}}function r(e){return`${e.kind}:${e.varName}`}e.computeScopeVariableLookup=function(e){const r=n(t(e)),i=new Map,a=new Map;return function e(t){const n=s((r=t,[...r.globalUsage,...r.environmentUsage].filter((e=>"assign"===e.kind)).map((e=>e))));var r;i.set(t.owner,n);const o=s(function(e){return e.nonlocalUsage.filter((e=>"assign"===e.kind)).map((e=>e))}(t));a.set(t.owner,o),t.children.forEach(e)}(r),{getExplicitGlobals:e=>i.get(e)||[],getExplicitNonlocals:e=>a.get(e)||[]};function o(e){let t=e.node.operand||e.node.left;return ts.isIdentifier(t)?t:void 0}function s(e){return e.map(o).filter((e=>!!e)).map((e=>e)).reduce(((e,t)=>e.find((e=>e.text===t.text))?e:[...e,t]),[])}},e.toStringVariableScopes=function(i){const a=t(i),o=n(a);return function t(n){return[n.refs.map(r).join(", "),...n.children.map(t).map((t=>t.map(e.indent1))).map((e=>["{",...e,"}"])).reduce(((e,t)=>[...e,...t]),[])]}(a).join("\n")+"\n\n\n"+function(t){return function t(n){const i=n.globalUsage.map(r).join(", "),a=n.nonlocalUsage.map(r).join(", "),o=n.localUsage.map(r).join(", "),s=n.environmentUsage.map(r).join(", ");return[i?"global "+i:"",a?"nonlocal "+a:"",o?"local "+o:"",s?"env "+s:"",...n.children.map(t).map((t=>t.map(e.indent1))).map((e=>["{",...e,"}"])).reduce(((e,t)=>[...e,...t]),[])].filter((e=>!!e))}(t).join("\n")}(o)}}(e.py||(e.py={}))}(pxt||(pxt={}));
|
|
23
|
+
*/!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("Fuse",[],t):"object"==typeof exports?exports.Fuse=t():e.Fuse=t()}(this,(function(){return function(e){function t(r){if(n[r])return n[r].exports;var i=n[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,t),i.l=!0,i.exports}var n={};return t.m=e,t.c=n,t.i=function(e){return e},t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=8)}([function(e,t,n){e.exports=function(e){return"[object Array]"===Object.prototype.toString.call(e)}},function(e,t,n){var r=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),i=n(5),a=n(7),o=n(4),s=function(){function e(t,n){var r=n.location,i=void 0===r?0:r,a=n.distance,s=void 0===a?100:a,c=n.threshold,l=void 0===c?.6:c,u=n.maxPatternLength,d=void 0===u?32:u,p=n.isCaseSensitive,f=void 0!==p&&p,_=n.tokenSeparator,m=void 0===_?/ +/g:_,g=n.findAllMatches,h=void 0!==g&&g,y=n.minMatchCharLength,v=void 0===y?1:y;(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),this.options={location:i,distance:s,threshold:l,maxPatternLength:d,isCaseSensitive:f,tokenSeparator:m,findAllMatches:h,minMatchCharLength:v},this.pattern=this.options.isCaseSensitive?t:t.toLowerCase(),this.pattern.length<=d&&(this.patternAlphabet=o(this.pattern))}return r(e,[{key:"search",value:function(e){if(this.options.isCaseSensitive||(e=e.toLowerCase()),this.pattern===e)return{isMatch:!0,score:0,matchedIndices:[[0,e.length-1]]};var t=this.options,n=t.maxPatternLength,r=t.tokenSeparator;if(this.pattern.length>n)return i(e,this.pattern,r);var o=this.options,s=o.location,c=o.distance,l=o.threshold,u=o.findAllMatches,d=o.minMatchCharLength;return a(e,this.pattern,this.patternAlphabet,{location:s,distance:c,threshold:l,findAllMatches:u,minMatchCharLength:d})}}]),e}();e.exports=s},function(e,t,n){var r=n(0),i=function e(t,n,i){if(n){var a=n.indexOf("."),o=n,s=null;-1!==a&&(o=n.slice(0,a),s=n.slice(a+1));var c=t[o];if(null!=c)if(s||"string"!=typeof c&&"number"!=typeof c)if(r(c))for(var l=0,u=c.length;l<u;l+=1)e(c[l],s,i);else s&&e(c,s,i);else i.push(c.toString())}else i.push(t);return i};e.exports=function(e,t){return i(e,t,[])}},function(e,t,n){e.exports=function(){for(var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,n=[],r=-1,i=-1,a=0,o=e.length;a<o;a+=1){var s=e[a];s&&-1===r?r=a:s||-1===r||((i=a-1)-r+1>=t&&n.push([r,i]),r=-1)}return e[a-1]&&a-r>=t&&n.push([r,a-1]),n}},function(e,t,n){e.exports=function(e){for(var t={},n=e.length,r=0;r<n;r+=1)t[e.charAt(r)]=0;for(var i=0;i<n;i+=1)t[e.charAt(i)]|=1<<n-i-1;return t}},function(e,t,n){e.exports=function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:/ +/g,r=new RegExp(t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&").replace(n,"|")),i=e.match(r),a=!!i,o=[];if(a)for(var s=0,c=i.length;s<c;s+=1){var l=i[s];o.push([e.indexOf(l),l.length-1])}return{score:a?.5:1,isMatch:a,matchedIndices:o}}},function(e,t,n){e.exports=function(e,t){var n=t.errors,r=void 0===n?0:n,i=t.currentLocation,a=void 0===i?0:i,o=t.expectedLocation,s=void 0===o?0:o,c=t.distance,l=void 0===c?100:c,u=r/e.length,d=Math.abs(s-a);return l?u+d/l:d?1:u}},function(e,t,n){var r=n(6),i=n(3);e.exports=function(e,t,n,a){for(var o=a.location,s=void 0===o?0:o,c=a.distance,l=void 0===c?100:c,u=a.threshold,d=void 0===u?.6:u,p=a.findAllMatches,f=void 0!==p&&p,_=a.minMatchCharLength,m=void 0===_?1:_,g=s,h=e.length,y=d,v=e.indexOf(t,g),b=t.length,x=[],k=0;k<h;k+=1)x[k]=0;if(-1!==v){var S=r(t,{errors:0,currentLocation:v,expectedLocation:g,distance:l});if(y=Math.min(S,y),-1!==(v=e.lastIndexOf(t,g+b))){var T=r(t,{errors:0,currentLocation:v,expectedLocation:g,distance:l});y=Math.min(T,y)}}v=-1;for(var C=[],E=1,D=b+h,A=1<<b-1,N=0;N<b;N+=1){for(var w=0,I=D;w<I;)r(t,{errors:N,currentLocation:g+I,expectedLocation:g,distance:l})<=y?w=I:D=I,I=Math.floor((D-w)/2+w);D=I;var P=Math.max(1,g-I+1),O=f?h:Math.min(g+I,h)+b,F=Array(O+2);F[O+1]=(1<<N)-1;for(var L=O;L>=P;L-=1){var R=L-1,M=n[e.charAt(R)];if(M&&(x[R]=1),F[L]=(F[L+1]<<1|1)&M,0!==N&&(F[L]|=(C[L+1]|C[L])<<1|1|C[L+1]),F[L]&A&&(E=r(t,{errors:N,currentLocation:R,expectedLocation:g,distance:l}))<=y){if(y=E,(v=R)<=g)break;P=Math.max(1,2*g-v)}}if(r(t,{errors:N+1,currentLocation:g,expectedLocation:g,distance:l})>y)break;C=F}return{isMatch:v>=0,score:0===E?.001:E,matchedIndices:i(x,m)}}},function(e,t,n){var r=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),i=n(1),a=n(2),o=n(0),s=function(){function e(t,n){var r=n.location,i=void 0===r?0:r,o=n.distance,s=void 0===o?100:o,c=n.threshold,l=void 0===c?.6:c,u=n.maxPatternLength,d=void 0===u?32:u,p=n.caseSensitive,f=void 0!==p&&p,_=n.tokenSeparator,m=void 0===_?/ +/g:_,g=n.findAllMatches,h=void 0!==g&&g,y=n.minMatchCharLength,v=void 0===y?1:y,b=n.id,x=void 0===b?null:b,k=n.keys,S=void 0===k?[]:k,T=n.shouldSort,C=void 0===T||T,E=n.getFn,D=void 0===E?a:E,A=n.sortFn,N=void 0===A?function(e,t){return e.score-t.score}:A,w=n.tokenize,I=void 0!==w&&w,P=n.matchAllTokens,O=void 0!==P&&P,F=n.includeMatches,L=void 0!==F&&F,R=n.includeScore,M=void 0!==R&&R,U=n.verbose,B=void 0!==U&&U;(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),this.options={location:i,distance:s,threshold:l,maxPatternLength:d,isCaseSensitive:f,tokenSeparator:m,findAllMatches:h,minMatchCharLength:v,id:x,keys:S,includeMatches:L,includeScore:M,shouldSort:C,getFn:D,sortFn:N,verbose:B,tokenize:I,matchAllTokens:O},this.setCollection(t)}return r(e,[{key:"setCollection",value:function(e){return this.list=e,e}},{key:"search",value:function(e){this._log('---------\nSearch pattern: "'+e+'"');var t=this._prepareSearchers(e),n=t.tokenSearchers,r=t.fullSearcher,i=this._search(n,r),a=i.weights,o=i.results;return this._computeScore(a,o),this.options.shouldSort&&this._sort(o),this._format(o)}},{key:"_prepareSearchers",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",t=[];if(this.options.tokenize)for(var n=e.split(this.options.tokenSeparator),r=0,a=n.length;r<a;r+=1)t.push(new i(n[r],this.options));return{tokenSearchers:t,fullSearcher:new i(e,this.options)}}},{key:"_search",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments[1],n=this.list,r={},i=[];if("string"==typeof n[0]){for(var a=0,o=n.length;a<o;a+=1)this._analyze({key:"",value:n[a],record:a,index:a},{resultMap:r,results:i,tokenSearchers:e,fullSearcher:t});return{weights:null,results:i}}for(var s={},c=0,l=n.length;c<l;c+=1)for(var u=n[c],d=0,p=this.options.keys.length;d<p;d+=1){var f=this.options.keys[d];if("string"!=typeof f){if(s[f.name]={weight:1-f.weight||1},f.weight<=0||f.weight>1)throw new Error("Key weight has to be > 0 and <= 1");f=f.name}else s[f]={weight:1};this._analyze({key:f,value:this.options.getFn(u,f),record:u,index:c},{resultMap:r,results:i,tokenSearchers:e,fullSearcher:t})}return{weights:s,results:i}}},{key:"_analyze",value:function(e,t){var n=e.key,r=e.arrayIndex,i=void 0===r?-1:r,a=e.value,s=e.record,c=e.index,l=t.tokenSearchers,u=void 0===l?[]:l,d=t.fullSearcher,p=void 0===d?[]:d,f=t.resultMap,_=void 0===f?{}:f,m=t.results,g=void 0===m?[]:m;if(null!=a){var h=!1,y=-1,v=0;if("string"==typeof a){this._log("\nKey: "+(""===n?"-":n));var b=p.search(a);if(this._log('Full text: "'+a+'", score: '+b.score),this.options.tokenize){for(var x=a.split(this.options.tokenSeparator),k=[],S=0;S<u.length;S+=1){var T=u[S];this._log('\nPattern: "'+T.pattern+'"');for(var C=!1,E=0;E<x.length;E+=1){var D=x[E],A=T.search(D),N={};A.isMatch?(N[D]=A.score,h=!0,C=!0,k.push(A.score)):(N[D]=1,this.options.matchAllTokens||k.push(1)),this._log('Token: "'+D+'", score: '+N[D])}C&&(v+=1)}y=k[0];for(var w=k.length,I=1;I<w;I+=1)y+=k[I];y/=w,this._log("Token score average:",y)}var P=b.score;y>-1&&(P=(P+y)/2),this._log("Score average:",P);var O=!this.options.tokenize||!this.options.matchAllTokens||v>=u.length;if(this._log("\nCheck Matches: "+O),(h||b.isMatch)&&O){var F=_[c];F?F.output.push({key:n,arrayIndex:i,value:a,score:P,matchedIndices:b.matchedIndices}):(_[c]={item:s,output:[{key:n,arrayIndex:i,value:a,score:P,matchedIndices:b.matchedIndices}]},g.push(_[c]))}}else if(o(a))for(var L=0,R=a.length;L<R;L+=1)this._analyze({key:n,arrayIndex:L,value:a[L],record:s,index:c},{resultMap:_,results:g,tokenSearchers:u,fullSearcher:p})}}},{key:"_computeScore",value:function(e,t){this._log("\n\nComputing score:\n");for(var n=0,r=t.length;n<r;n+=1){for(var i=t[n].output,a=i.length,o=0,s=1,c=0;c<a;c+=1){var l=e?e[i[c].key].weight:1,u=(1===l?i[c].score:i[c].score||.001)*l;1!==l?s=Math.min(s,u):(i[c].nScore=u,o+=u)}t[n].score=1===s?o/a:s,this._log(t[n])}}},{key:"_sort",value:function(e){this._log("\n\nSorting...."),e.sort(this.options.sortFn)}},{key:"_format",value:function(e){var t=[];this._log("\n\nOutput:\n\n",JSON.stringify(e));var n=[];this.options.includeMatches&&n.push((function(e,t){var n=e.output;t.matches=[];for(var r=0,i=n.length;r<i;r+=1){var a=n[r];if(0!==a.matchedIndices.length){var o={indices:a.matchedIndices,value:a.value};a.key&&(o.key=a.key),a.hasOwnProperty("arrayIndex")&&a.arrayIndex>-1&&(o.arrayIndex=a.arrayIndex),t.matches.push(o)}}})),this.options.includeScore&&n.push((function(e,t){t.score=e.score}));for(var r=0,i=e.length;r<i;r+=1){var a=e[r];if(this.options.id&&(a.item=this.options.getFn(a.item,this.options.id)[0]),n.length){for(var o={item:a.item},s=0,c=n.length;s<c;s+=1)n[s](a,o);t.push(o)}else t.push(a.item)}return t}},{key:"_log",value:function(){var e;this.options.verbose&&(e=console).log.apply(e,arguments)}}]),e}();e.exports=s}])}));var e=function(){function t(e,t){postMessage({action:$e,cbn:t,result:e})}function n(e){var t=[];return t[e-1]=void 0,t}function r(e,t){return o(e[0]+t[0],e[1]+t[1])}function i(e,t){return function(e,t){var n;return n=t,0>t&&(n+=Ke),[n,e*Ke]}(~~Math.max(Math.min(e[1]/Ke,2147483647),-2147483648)&~~Math.max(Math.min(t[1]/Ke,2147483647),-2147483648),l(e)&l(t))}function a(e,t){var n,r;return e[0]==t[0]&&e[1]==t[1]?0:(n=0>e[1],r=0>t[1],n&&!r?-1:!n&&r?1:f(e,t)[1]<0?-1:1)}function o(e,t){var n,r;for(e%=0x10000000000000000,t=(t%=0x10000000000000000)-(n=t%Ke)+(r=Math.floor(e/Ke)*Ke),e=e-r+n;0>e;)e+=Ke,t-=Ke;for(;e>4294967295;)e-=Ke,t+=Ke;for(t%=0x10000000000000000;t>0x7fffffff00000000;)t-=0x10000000000000000;for(;-0x8000000000000000>t;)t+=0x10000000000000000;return[e,t]}function s(e,t){return e[0]==t[0]&&e[1]==t[1]}function c(e){return e>=0?[e,0]:[e+Ke,-Ke]}function l(e){return e[0]>=2147483648?~~Math.max(Math.min(e[0]-Ke,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,r,i,a;if(t&=63,s(e,Je))return t?qe:e;if(0>e[1])throw Error("Neg");return a=u(t),r=e[1]*a%0x10000000000000000,(r+=n=(i=e[0]*a)-i%Ke)>=0x8000000000000000&&(r-=0x10000000000000000),[i-=n,r]}function p(e,t){var n;return n=u(t&=63),o(Math.floor(e[0]/n),e[1]/n)}function f(e,t){return o(e[0]-t[0],e[1]-t[1])}function _(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,r){return e.Lc>=e.Yb?-1:(r=Math.min(r,e.Yb-e.Lc),x(e.Mc,e.Lc,t,n,r),e.Lc+=r,r)}function h(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 b(e,t,n,r){x(t,n,e.Mc,e.Yb,r),e.Yb+=r}function x(e,t,n,r,i){for(var a=0;i>a;++a)n[r+a]=e[t+a]}function k(t,n,r,i,o){var s,c;if(a(i,ze)<0)throw Error("invalid length "+i);for(t.Tb=i,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,s=W({})),s.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;b(t,e.fc,0,5)}(s,r),c=0;64>c;c+=8)v(r,255&l(p(i,c)));t.yb=(s.W=0,s.oc=n,s.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),pe(e.A,e.eb,e.fb),(e.ab!=e.wb||e.Hb!=e.n)&&(I(e.b,e.ab,4096,e.n,274),e.wb=e.ab,e.Hb=e.n)}(s),s.d.Ab=r,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=qe,e.xc=qe,e.E=-1,e.Jb=1,e.Oc=0}(e.d),Ne(e.C),Ne(e._),Ne(e.bb),Ne(e.hb),Ne(e.Ub),Ne(e.vc),Ne(e.Sb),function(e){var t,n=1<<e.u+e.I;for(t=0;n>t;++t)Ne(e.V[t].tb)}(e.A);for(var t=0;4>t;++t)Ne(e.K[t].G);oe(e.$,1<<e.Y),oe(e.i,1<<e.Y),Ne(e.S.G),e.N=0,e.jb=0,e.q=0,e.s=0}(s),Y(s),Q(s),s.$.rb=s.n+1-2,de(s.$,1<<s.Y),s.i.rb=s.n+1-2,de(s.i,1<<s.Y),s.g=qe,function(e,t){return e.cb=t,e.Z=null,e.zc=1,e}({},s))}function S(e,t,n){return e.Nb=h({}),k(e,_({},t),e.Nb,c(t.length),n),e}function T(e,t,n){var r,i,a,o,s="",l=[];for(i=0;5>i;++i){if(-1==(a=m(t)))throw Error("truncated input");l[i]=a<<24>>24}if(!function(e,t){var n,r,i,a,o,s,c;if(5>t.length)return 0;for(c=255&t[0],i=c%9,a=(s=~~(c/9))%5,o=~~(s/5),n=0,r=0;4>r;++r)n+=(255&t[1+r])<<8*r;return n>99999999||!function(e,t,n,r){if(t>8||n>4||r>4)return 0;V(e.gb,n,t);var i=1<<r;return K(e.Rb,i),K(e.sb,i),e.Dc=i-1,1}(e,i,a,o)?0:function(e,t){return 0>t?0:(e.Ob!=t&&(e.Ob=t,e.nb=Math.max(e.Ob,1),F(e.B,Math.max(e.nb,4096))),1)}(e,n)}(r=j({}),l))throw Error("corrupted input");for(i=0;64>i;i+=8){if(-1==(a=m(t)))throw Error("truncated input");1==(a=a.toString(16)).length&&(a="0"+a),s=a+""+s}/^0+$|^f+$/i.test(s)?e.Tb=ze:(o=parseInt(s,16),e.Tb=o>4294967295?ze:c(o)),e.yb=function(e,t,n,r){return e.e.Ab=t,M(e.B),e.B.cc=n,function(e){e.B.h=0,e.B.o=0,Ne(e.Gb),Ne(e.pb),Ne(e.Zb),Ne(e.Cb),Ne(e.Db),Ne(e.Eb),Ne(e.kc),function(e){var t,n;for(n=1<<e.u+e.I,t=0;n>t;++t)Ne(e.V[t].Ib)}(e.gb);for(var t=0;4>t;++t)Ne(e.kb[t].G);q(e.Rb),q(e.sb),Ne(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=r,e.g=qe,e.jc=0,function(e,t){return e.Z=t,e.cb=null,e.zc=1,e}({},e)}(r,t,n,e.Tb)}function C(e,t){return e.Nb=h({}),T(e,_({},t),e.Nb),e}function E(e,t){return e.c[e.f+e.o+t]}function D(e,t,n,r){var i,a;for(e.T&&e.o+t+r>e.h&&(r=e.h-(e.o+t)),++n,a=e.f+e.o+t,i=0;r>i&&e.c[a+i]==e.c[a+i-n];++i);return i}function A(e){return e.h-e.o}function N(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 w(e,t){e.f+=t,e.zb-=t,e.o-=t,e.h-=t}function I(e,t,r,i,a){var o,s;1073741567>t&&(e.Fc=16+(i>>1),function(e,t,r,i){var a;e.Bc=t,e._b=r,a=t+r+i,(null==e.c||e.Kb!=a)&&(e.c=null,e.Kb=a,e.c=n(e.Kb)),e.H=e.Kb-r}(e,t+r,i+a,256+~~((t+r+i+a)/2)),e.ob=i,o=t+1,e.p!=o&&(e.L=n(2*(e.p=o))),s=65536,e.qb&&(s=t-1,s|=s>>1,s|=s>>2,s|=s>>4,s|=s>>8,s>>=1,(s|=65535)>16777216&&(s>>=1),e.Ec=s,++s,s+=e.R),s!=e.rc&&(e.ub=n(e.rc=s)))}function P(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,r;for((r=e.f+e.o-e.Bc)>0&&--r,n=e.f+e.h-r,t=0;n>t;++t)e.c[t]=e.c[r+t];e.f-=r}(e),N(e))}(e),1073741823==e.o&&(t=e.o-e.p,O(e.L,2*e.p,t),O(e.ub,e.rc,t),w(e,t))}function O(e,t,n){var r,i;for(r=0;t>r;++r)n>=(i=e[r]||0)?i=0:i-=n,e[r]=i}function F(e,t){(null==e.Lb||e.M!=t)&&(e.Lb=n(t)),e.M=t,e.o=0,e.h=0}function L(e){var t=e.o-e.h;t&&(b(e.cc,e.Lb,e.h,t),e.o>=e.M&&(e.o=0),e.h=e.o)}function R(e,t){var n=e.o-t-1;return 0>n&&(n+=e.M),e.Lb[n]}function M(e){L(e),e.cc=null}function U(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,i){var o,u,d,p,_,m,g,h,y,v,b,x,k,S,T;if(t[0]=qe,n[0]=qe,i[0]=1,e.oc&&(e.b.cc=e.oc,function(e){e.f=0,e.o=0,e.h=0,e.T=0,N(e),e.k=0,w(e,-1)}(e.b),e.W=1,e.oc=null),!e.pc){if(e.pc=1,S=e.g,s(e.g,qe)){if(!A(e.b))return void X(e,l(e.g));re(e),k=l(e.g)&e.y,we(e.d,e.C,(e.l<<4)+k,0),e.l=B(e.l),d=E(e.b,-e.s),_e(fe(e.A,l(e.g),e.J),e.d,d),e.J=d,--e.s,e.g=r(e.g,Ve)}if(!A(e.b))return void X(e,l(e.g));for(;;){if(g=Z(e,l(e.g)),v=e.mb,k=l(e.g)&e.y,u=(e.l<<4)+k,1==g&&-1==v)we(e.d,e.C,u,0),d=E(e.b,-e.s),T=fe(e.A,l(e.g),e.J),7>e.l?_e(T,e.d,d):(y=E(e.b,-e.v[0]-1-e.s),me(T,e.d,y,d)),e.J=d,e.l=B(e.l);else{if(we(e.d,e.C,u,1),4>v){if(we(e.d,e.bb,e.l,1),v?(we(e.d,e.hb,e.l,1),1==v?we(e.d,e.Ub,e.l,0):(we(e.d,e.Ub,e.l,1),we(e.d,e.vc,e.l,v-2))):(we(e.d,e.hb,e.l,0),we(e.d,e._,u,1==g?0:1)),1==g?e.l=7>e.l?9:11:(ce(e.i,e.d,g-2,k),e.l=7>e.l?8:11),p=e.v[v],0!=v){for(m=v;m>=1;--m)e.v[m]=e.v[m-1];e.v[0]=p}}else{for(we(e.d,e.bb,e.l,0),e.l=7>e.l?7:10,ce(e.$,e.d,g-2,k),x=ae(v-=4),h=U(g),ke(e.K[h],e.d,x),x>=4&&(b=v-(o=(2|1&x)<<(_=(x>>1)-1)),14>x?Ee(e.Sb,o-x-1,e.d,_,b):(Ie(e.d,b>>4,_-4),Te(e.S,e.d,15&b),++e.Qb)),p=v,m=3;m>=1;--m)e.v[m]=e.v[m-1];e.v[0]=p,++e.Mb}e.J=E(e.b,g-1-e.s)}if(e.s-=g,e.g=r(e.g,c(g)),!e.s){if(e.Mb>=128&&Y(e),e.Qb>=16&&Q(e),t[0]=e.g,n[0]=Pe(e.d),!A(e.b))return void X(e,l(e.g));if(a(f(e.g,S),[4096,0])>=0)return e.pc=0,void(i[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){ie(e),e.d.Ab=null}(e.cb),e.zc=0)}(e):function(e){var t=function(e){var t,n,i,o,s,u;if(u=l(e.g)&e.Dc,Ae(e.e,e.Gb,(e.U<<4)+u)){if(Ae(e.e,e.Zb,e.U))i=0,Ae(e.e,e.Cb,e.U)?(Ae(e.e,e.Db,e.U)?(Ae(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):Ae(e.e,e.pb,(e.U<<4)+u)||(e.U=7>e.U?9:11,i=1),i||(i=z(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,i=2+z(e.Rb,e.e,u),e.U=7>e.U?7:10,(s=be(e.kb[U(i)],e.e))>=4){if(o=(s>>1)-1,e.ib=(2|1&s)<<o,14>s)e.ib+=function(e,t,n,r){var i,a,o=1,s=0;for(a=0;r>a;++a)i=Ae(n,e,t+o),o<<=1,o+=i,s|=i<<a;return s}(e.kc,e.ib-s-1,e.e,o);else if(e.ib+=function(e,t){var n,r,i=0;for(n=t;0!=n;--n)e.E>>>=1,r=e.Bb-e.E>>>31,e.Bb-=e.E&r-1,i=i<<1|1-r,-16777216&e.E||(e.Bb=e.Bb<<8|m(e.Ab),e.E<<=8);return i}(e.e,o-4)<<4,e.ib+=function(e,t){var n,r,i=1,a=0;for(r=0;e.F>r;++r)n=Ae(t,e.G,i),i<<=1,i+=n,a|=n<<r;return a}(e.Fb,e.e),0>e.ib)return-1==e.ib?1:-1}else e.ib=s;if(a(c(e.ib),e.g)>=0||e.ib>=e.nb)return-1;(function(e,t,n){var r=e.o-t-1;for(0>r&&(r+=e.M);0!=n;--n)r>=e.M&&(r=0),e.Lb[e.o++]=e.Lb[r++],e.o>=e.M&&L(e)})(e.B,e.ib,i),e.g=r(e.g,c(i)),e.jc=R(e.B,0)}else t=function(e,t,n){return e.V[((t&e.qc)<<e.u)+((255&n)>>>8-e.u)]}(e.gb,l(e.g),e.jc),e.jc=7>e.U?function(e,t){var n=1;do{n=n<<1|Ae(t,e.Ib,n)}while(256>n);return n<<24>>24}(t,e.e):function(e,t,n){var r,i,a=1;do{if(i=n>>7&1,n<<=1,r=Ae(t,e.Ib,(1+i<<8)+a),a=a<<1|r,i!=r){for(;256>a;)a=a<<1|Ae(t,e.Ib,a);break}}while(256>a);return a<<24>>24}(t,e.e,R(e.B,e.ib)),function(e,t){e.Lb[e.o++]=t,e.o>=e.M&&L(e)}(e.B,e.jc),e.U=B(e.U),e.g=r(e.g,Ve);return 0}(e.Z);if(-1==t)throw Error("corrupted input");e.Pb=ze,e.Pc=e.Z.g,(t||a(e.Z.Nc,qe)>=0&&a(e.Z.g,e.Z.Nc)>=0)&&(L(e.Z.B),M(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=J({}),e.sb=J({}),e.gb={};for(var t=0;4>t;++t)e.kb[t]=ve({},6);return e}function K(e,t){for(;t>e.O;++e.O)e.ec[e.O]=ve({},3),e.hc[e.O]=ve({},3)}function z(e,t,n){return Ae(t,e.wc,0)?8+(Ae(t,e.wc,1)?8+be(e.tc,t):be(e.hc[n],t)):be(e.ec[n],t)}function J(e){return e.wc=n(2),e.ec=n(16),e.hc=n(16),e.tc=ve({},8),e.O=0,e}function q(e){Ne(e.wc);for(var t=0;e.O>t;++t)Ne(e.ec[t].G),Ne(e.hc[t].G);Ne(e.tc.G)}function V(e,t,r){var i,a;if(null==e.V||e.u!=r||e.I!=t)for(e.I=t,e.qc=(1<<t)-1,e.u=r,a=1<<e.u+e.I,e.V=n(a),i=0;a>i;++i)e.V[i]=H({})}function H(e){return e.Ib=n(768),e}function G(e,t){var n,r,i,a;e.jb=t,i=e.a[t].r,r=e.a[t].j;do{e.a[t].t&&(ye(e.a[i]),e.a[i].r=i-1,e.a[t].Ac&&(e.a[i-1].t=0,e.a[i-1].r=e.a[t].r2,e.a[i-1].j=e.a[t].j2)),a=i,n=r,r=e.a[a].j,i=e.a[a].r,e.a[a].j=n,e.a[a].r=t,t=a}while(t>0);return e.mb=e.a[0].j,e.q=e.a[0].r}function W(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=xe({},4),e.$=le({}),e.i=le({}),e.A={},e.m=[],e.P=[],e.lb=[],e.nc=n(16),e.x=n(4),e.Q=n(4),e.Xb=[qe],e.uc=[qe],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]=xe({},6);return e}function Q(e){for(var t=0;16>t;++t)e.nc[t]=Ce(e.S,t);e.Qb=0}function Y(e){var t,n,r,i,a,o,s,c;for(i=4;128>i;++i)t=(2|1&(o=ae(i)))<<(r=(o>>1)-1),e.yc[i]=De(e.Sb,t-o-1,r,i-t);for(a=0;4>a;++a){for(n=e.K[a],s=a<<6,o=0;e.$b>o;++o)e.P[s+o]=Se(n,o);for(o=14;e.$b>o;++o)e.P[s+o]+=(o>>1)-1-4<<6;for(c=128*a,i=0;4>i;++i)e.lb[c+i]=e.P[s+i];for(;128>i;++i)e.lb[c+i]=e.P[s+ae(i)]+e.yc[i]}e.Mb=0}function X(e,t){ie(e),function(e,t){if(e.Gc){we(e.d,e.C,(e.l<<4)+t,1),we(e.d,e.bb,e.l,0),e.l=7>e.l?7:10,ce(e.$,e.d,0,t);var n=U(2);ke(e.K[n],e.d,63),Ie(e.d,67108863,26),Te(e.S,e.d,15)}}(e,t&e.y);for(var n=0;5>n;++n)Oe(e.d)}function Z(e,t){var n,r,i,a,o,s,c,l,u,d,p,f,_,m,g,h,y,v,b,x,k,S,T,C,N,w,I,P,O,F,L,R,M,U,$,j,K,z,J,q,V,H,W,Q;if(e.jb!=e.q)return _=e.a[e.q].r-e.q,e.mb=e.a[e.q].j,e.q=e.a[e.q].r,_;if(e.q=e.jb=0,e.N?(f=e.vb,e.N=0):f=re(e),w=e.D,2>(C=A(e.b)+1))return e.mb=-1,1;for(C>273&&(C=273),J=0,u=0;4>u;++u)e.x[u]=e.v[u],e.Q[u]=D(e.b,-1,e.x[u],273),e.Q[u]>e.Q[J]&&(J=u);if(e.Q[J]>=e.n)return e.mb=J,ne(e,(_=e.Q[J])-1),_;if(f>=e.n)return e.mb=e.m[w-1]+4,ne(e,f-1),f;if(c=E(e.b,-1),y=E(e.b,-e.v[0]-1-1),2>f&&c!=y&&2>e.Q[J])return e.mb=-1,1;if(e.a[0].Hc=e.l,M=t&e.y,e.a[1].z=We[e.C[(e.l<<4)+M]>>>2]+he(fe(e.A,t,e.J),e.l>=7,y,c),ye(e.a[1]),z=(v=We[2048-e.C[(e.l<<4)+M]>>>2])+We[2048-e.bb[e.l]>>>2],y==c&&(q=z+function(e,t,n){return We[e.hb[t]>>>2]+We[e._[(t<<4)+n]>>>2]}(e,e.l,M),e.a[1].z>q&&(e.a[1].z=q,function(e){e.j=0,e.t=0}(e.a[1]))),2>(p=f>=e.Q[J]?f:e.Q[J]))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=p;do{e.a[d--].z=268435455}while(d>=2);for(u=0;4>u;++u)if(!(2>(K=e.Q[u]))){$=z+te(e,u,e.l,M);do{a=$+ue(e.i,K-2,M),(F=e.a[K]).z>a&&(F.z=a,F.r=0,F.j=u,F.t=0)}while(--K>=2)}if(T=v+We[e.bb[e.l]>>>2],f>=(d=e.Q[0]>=2?e.Q[0]+1:2)){for(I=0;d>e.m[I];)I+=2;for(;a=T+ee(e,l=e.m[I+1],d,M),(F=e.a[d]).z>a&&(F.z=a,F.r=0,F.j=l+4,F.t=0),d!=e.m[I]||(I+=2)!=w;++d);}for(n=0;;){if(++n==p)return G(e,n);if(b=re(e),w=e.D,b>=e.n)return e.vb=b,e.N=1,G(e,n);if(++t,R=e.a[n].r,e.a[n].t?(--R,e.a[n].Ac?(H=e.a[e.a[n].r2].Hc,H=4>e.a[n].j2?7>H?8:11:7>H?7:10):H=e.a[R].Hc,H=B(H)):H=e.a[R].Hc,R==n-1?H=e.a[n].j?B(H):7>H?9:11:(e.a[n].t&&e.a[n].Ac?(R=e.a[n].r2,L=e.a[n].j2,H=7>H?8:11):H=4>(L=e.a[n].j)?7>H?8:11:7>H?7:10,O=e.a[R],4>L?L?1==L?(e.x[0]=O.ac,e.x[1]=O.bc,e.x[2]=O.dc,e.x[3]=O.lc):2==L?(e.x[0]=O.dc,e.x[1]=O.bc,e.x[2]=O.ac,e.x[3]=O.lc):(e.x[0]=O.lc,e.x[1]=O.bc,e.x[2]=O.ac,e.x[3]=O.dc):(e.x[0]=O.bc,e.x[1]=O.ac,e.x[2]=O.dc,e.x[3]=O.lc):(e.x[0]=L-4,e.x[1]=O.bc,e.x[2]=O.ac,e.x[3]=O.dc)),e.a[n].Hc=H,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],s=e.a[n].z,c=E(e.b,-1),y=E(e.b,-e.x[0]-1-1),M=t&e.y,r=s+We[e.C[(H<<4)+M]>>>2]+he(fe(e.A,t,E(e.b,-2)),H>=7,y,c),x=0,(k=e.a[n+1]).z>r&&(k.z=r,k.r=n,k.j=-1,k.t=0,x=1),z=(v=s+We[2048-e.C[(H<<4)+M]>>>2])+We[2048-e.bb[H]>>>2],y!=c||n>k.r&&!k.j||(q=z+(We[e.hb[H]>>>2]+We[e._[(H<<4)+M]>>>2]),k.z>=q&&(k.z=q,k.r=n,k.j=0,k.t=0,x=1)),!(2>(C=N=(N=A(e.b)+1)>4095-n?4095-n:N))){if(C>e.n&&(C=e.n),!x&&y!=c&&(Q=Math.min(N-1,e.n),(g=D(e.b,0,e.x[0],Q))>=2)){for(W=B(H),U=t+1&e.y,S=r+We[2048-e.C[(W<<4)+U]>>>2]+We[2048-e.bb[W]>>>2],P=n+1+g;P>p;)e.a[++p].z=268435455;a=S+(ue(e.i,g-2,U)+te(e,0,W,U)),(F=e.a[P]).z>a&&(F.z=a,F.r=n+1,F.j=0,F.t=1,F.Ac=0)}for(V=2,j=0;4>j;++j)if(!(2>(m=D(e.b,-1,e.x[j],C)))){h=m;do{for(;n+m>p;)e.a[++p].z=268435455;a=z+(ue(e.i,m-2,M)+te(e,j,H,M)),(F=e.a[n+m]).z>a&&(F.z=a,F.r=n,F.j=j,F.t=0)}while(--m>=2);if(m=h,j||(V=m+1),N>m&&(Q=Math.min(N-1-m,e.n),(g=D(e.b,m,e.x[j],Q))>=2)){for(W=7>H?8:11,U=t+m&e.y,i=z+(ue(e.i,m-2,M)+te(e,j,H,M))+We[e.C[(W<<4)+U]>>>2]+he(fe(e.A,t+m,E(e.b,m-1-1)),1,E(e.b,m-1-(e.x[j]+1)),E(e.b,m-1)),W=B(W),U=t+m+1&e.y,S=i+We[2048-e.C[(W<<4)+U]>>>2]+We[2048-e.bb[W]>>>2],P=m+1+g;n+P>p;)e.a[++p].z=268435455;a=S+(ue(e.i,g-2,U)+te(e,0,W,U)),(F=e.a[n+P]).z>a&&(F.z=a,F.r=n+m+1,F.j=0,F.t=1,F.Ac=1,F.r2=n,F.j2=j)}}if(b>C){for(b=C,w=0;b>e.m[w];w+=2);e.m[w]=b,w+=2}if(b>=V){for(T=v+We[e.bb[H]>>>2];n+b>p;)e.a[++p].z=268435455;for(I=0;V>e.m[I];)I+=2;for(m=V;;++m)if(a=T+ee(e,o=e.m[I+1],m,M),(F=e.a[n+m]).z>a&&(F.z=a,F.r=n,F.j=o+4,F.t=0),m==e.m[I]){if(N>m&&(Q=Math.min(N-1-m,e.n),(g=D(e.b,m,o,Q))>=2)){for(W=7>H?7:10,U=t+m&e.y,i=a+We[e.C[(W<<4)+U]>>>2]+he(fe(e.A,t+m,E(e.b,m-1-1)),1,E(e.b,m-(o+1)-1),E(e.b,m-1)),W=B(W),U=t+m+1&e.y,S=i+We[2048-e.C[(W<<4)+U]>>>2]+We[2048-e.bb[W]>>>2],P=m+1+g;n+P>p;)e.a[++p].z=268435455;a=S+(ue(e.i,g-2,U)+te(e,0,W,U)),(F=e.a[n+P]).z>a&&(F.z=a,F.r=n+m+1,F.j=0,F.t=1,F.Ac=1,F.r2=n,F.j2=o+4)}if((I+=2)==w)break}}}}}function ee(e,t,n,r){var i=U(n);return(128>t?e.lb[128*i+t]:e.P[(i<<6)+function(e){return 131072>e?Ge[e>>6]+12:134217728>e?Ge[e>>16]+32:Ge[e>>26]+52}(t)]+e.nc[15&t])+ue(e.$,n-2,r)}function te(e,t,n,r){var i;return t?(i=We[2048-e.hb[n]>>>2],1==t?i+=We[e.Ub[n]>>>2]:(i+=We[2048-e.Ub[n]>>>2],i+=Fe(e.vc[n],t-2))):(i=We[e.hb[n]>>>2],i+=We[2048-e._[(n<<4)+r]>>>2]),i}function ne(e,t){t>0&&(function(e,t){var n,r,i,a,o,s,c,l,u,d,p,f,_,m,g,h,y;do{if(e.h>=e.o+e.ob)f=e.ob;else if(f=e.h-e.o,e.xb>f){P(e);continue}for(_=e.o>e.p?e.o-e.p:0,r=e.f+e.o,e.qb?(s=1023&(y=He[255&e.c[r]]^255&e.c[r+1]),e.ub[s]=e.o,c=65535&(y^=(255&e.c[r+2])<<8),e.ub[1024+c]=e.o,l=(y^He[255&e.c[r+3]]<<5)&e.Ec):l=255&e.c[r]^(255&e.c[r+1])<<8,i=e.ub[e.R+l],e.ub[e.R+l]=e.o,g=1+(e.k<<1),h=e.k<<1,d=p=e.w,n=e.Fc;;){if(_>=i||0==n--){e.L[g]=e.L[h]=0;break}if(o=e.o-i,a=(e.k>=o?e.k-o:e.k-o+e.p)<<1,m=e.f+i,u=p>d?d:p,e.c[m+u]==e.c[r+u]){for(;++u!=f&&e.c[m+u]==e.c[r+u];);if(u==f){e.L[h]=e.L[a],e.L[g]=e.L[a+1];break}}(255&e.c[r+u])>(255&e.c[m+u])?(e.L[h]=i,h=a+1,i=e.L[h],p=u):(e.L[g]=i,g=a,i=e.L[g],d=u)}P(e)}while(0!=--t)}(e.b,t),e.s+=t)}function re(e){var t=0;return e.D=function(e,t){var n,r,i,a,o,s,c,l,u,d,p,f,_,m,g,h,y,v,b,x,k;if(e.h>=e.o+e.ob)m=e.ob;else if(m=e.h-e.o,e.xb>m)return P(e),0;for(y=0,g=e.o>e.p?e.o-e.p:0,r=e.f+e.o,h=1,l=0,u=0,e.qb?(l=1023&(k=He[255&e.c[r]]^255&e.c[r+1]),u=65535&(k^=(255&e.c[r+2])<<8),d=(k^He[255&e.c[r+3]]<<5)&e.Ec):d=255&e.c[r]^(255&e.c[r+1])<<8,i=e.ub[e.R+d]||0,e.qb&&(a=e.ub[l]||0,o=e.ub[1024+u]||0,e.ub[l]=e.o,e.ub[1024+u]=e.o,a>g&&e.c[e.f+a]==e.c[r]&&(t[y++]=h=2,t[y++]=e.o-a-1),o>g&&e.c[e.f+o]==e.c[r]&&(o==a&&(y-=2),t[y++]=h=3,t[y++]=e.o-o-1,a=o),0!=y&&a==i&&(y-=2,h=1)),e.ub[e.R+d]=e.o,b=1+(e.k<<1),x=e.k<<1,f=_=e.w,0!=e.w&&i>g&&e.c[e.f+i+e.w]!=e.c[r+e.w]&&(t[y++]=h=e.w,t[y++]=e.o-i-1),n=e.Fc;;){if(g>=i||0==n--){e.L[b]=e.L[x]=0;break}if(c=e.o-i,s=(e.k>=c?e.k-c:e.k-c+e.p)<<1,v=e.f+i,p=_>f?f:_,e.c[v+p]==e.c[r+p]){for(;++p!=m&&e.c[v+p]==e.c[r+p];);if(p>h&&(t[y++]=h=p,t[y++]=c-1,p==m)){e.L[x]=e.L[s],e.L[b]=e.L[s+1];break}}(255&e.c[r+p])>(255&e.c[v+p])?(e.L[x]=i,x=s+1,i=e.L[x],_=p):(e.L[b]=i,b=s,i=e.L[b],f=p)}return P(e),y}(e.b,e.m),e.D>0&&((t=e.m[e.D-2])==e.n&&(t+=D(e.b,t-1,e.m[e.D-1],273-t))),++e.s,t}function ie(e){e.b&&e.W&&(e.b.cc=null,e.W=0)}function ae(e){return 2048>e?Ge[e]:2097152>e?Ge[e>>10]+20:Ge[e>>20]+40}function oe(e,t){Ne(e.db);for(var n=0;t>n;++n)Ne(e.Vb[n].G),Ne(e.Wb[n].G);Ne(e.ic.G)}function se(e,t,n,r,i){var a,o,s,c,l;for(a=We[e.db[0]>>>2],s=(o=We[2048-e.db[0]>>>2])+We[e.db[1]>>>2],c=o+We[2048-e.db[1]>>>2],l=0,l=0;8>l;++l){if(l>=n)return;r[i+l]=a+Se(e.Vb[t],l)}for(;16>l;++l){if(l>=n)return;r[i+l]=s+Se(e.Wb[t],l-8)}for(;n>l;++l)r[i+l]=c+Se(e.ic,l-8-8)}function ce(e,t,n,r){(function(e,t,n,r){8>n?(we(t,e.db,0,0),ke(e.Vb[r],t,n)):(n-=8,we(t,e.db,0,1),8>n?(we(t,e.db,1,0),ke(e.Wb[r],t,n)):(we(t,e.db,1,1),ke(e.ic,t,n-8)))})(e,t,n,r),0==--e.sc[r]&&(se(e,r,e.rb,e.Cc,272*r),e.sc[r]=e.rb)}function le(e){return function(e){e.db=n(2),e.Vb=n(16),e.Wb=n(16),e.ic=xe({},8);for(var t=0;16>t;++t)e.Vb[t]=xe({},3),e.Wb[t]=xe({},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)se(e,n,e.rb,e.Cc,272*n),e.sc[n]=e.rb}function pe(e,t,r){var i,a;if(null==e.V||e.u!=r||e.I!=t)for(e.I=t,e.qc=(1<<t)-1,e.u=r,a=1<<e.u+e.I,e.V=n(a),i=0;a>i;++i)e.V[i]=ge({})}function fe(e,t,n){return e.V[((t&e.qc)<<e.u)+((255&n)>>>8-e.u)]}function _e(e,t,n){var r,i,a=1;for(i=7;i>=0;--i)r=n>>i&1,we(t,e.tb,a,r),a=a<<1|r}function me(e,t,n,r){var i,a,o,s,c=1,l=1;for(a=7;a>=0;--a)i=r>>a&1,s=l,c&&(s+=1+(o=n>>a&1)<<8,c=o==i),we(t,e.tb,s,i),l=l<<1|i}function ge(e){return e.tb=n(768),e}function he(e,t,n,r){var i,a,o=1,s=7,c=0;if(t)for(;s>=0;--s)if(a=n>>s&1,i=r>>s&1,c+=Fe(e.tb[(1+a<<8)+o],i),o=o<<1|i,a!=i){--s;break}for(;s>=0;--s)i=r>>s&1,c+=Fe(e.tb[o],i),o=o<<1|i;return c}function ye(e){e.j=-1,e.t=0}function ve(e,t){return e.F=t,e.G=n(1<<t),e}function be(e,t){var n,r=1;for(n=e.F;0!=n;--n)r=(r<<1)+Ae(t,e.G,r);return r-(1<<e.F)}function xe(e,t){return e.F=t,e.G=n(1<<t),e}function ke(e,t,n){var r,i,a=1;for(i=e.F;0!=i;)r=n>>>--i&1,we(t,e.G,a,r),a=a<<1|r}function Se(e,t){var n,r,i=1,a=0;for(r=e.F;0!=r;)n=t>>>--r&1,a+=Fe(e.G[i],n),i=(i<<1)+n;return a}function Te(e,t,n){var r,i,a=1;for(i=0;e.F>i;++i)r=1&n,we(t,e.G,a,r),a=a<<1|r,n>>=1}function Ce(e,t){var n,r,i=1,a=0;for(r=e.F;0!=r;--r)n=1&t,t>>>=1,a+=Fe(e.G[i],n),i=i<<1|n;return a}function Ee(e,t,n,r,i){var a,o,s=1;for(o=0;r>o;++o)we(n,e,t+s,a=1&i),s=s<<1|a,i>>=1}function De(e,t,n,r){var i,a,o=1,s=0;for(a=n;0!=a;--a)i=1&r,r>>>=1,s+=We[(2047&(e[t+o]-i^-i))>>>2],o=o<<1|i;return s}function Ae(e,t,n){var r,i=t[n];return(-2147483648^(r=(e.E>>>11)*i))>(-2147483648^e.Bb)?(e.E=r,t[n]=i+(2048-i>>>5)<<16>>16,-16777216&e.E||(e.Bb=e.Bb<<8|m(e.Ab),e.E<<=8),0):(e.E-=r,e.Bb-=r,t[n]=i-(i>>>5)<<16>>16,-16777216&e.E||(e.Bb=e.Bb<<8|m(e.Ab),e.E<<=8),1)}function Ne(e){for(var t=e.length-1;t>=0;--t)e[t]=1024}function we(e,t,n,a){var o,s=t[n];o=(e.E>>>11)*s,a?(e.xc=r(e.xc,i(c(o),[4294967295,0])),e.E-=o,t[n]=s-(s>>>5)<<16>>16):(e.E=o,t[n]=s+(2048-s>>>5)<<16>>16),-16777216&e.E||(e.E<<=8,Oe(e))}function Ie(e,t,n){for(var i=n-1;i>=0;--i)e.E>>>=1,1==(t>>>i&1)&&(e.xc=r(e.xc,c(e.E))),-16777216&e.E||(e.E<<=8,Oe(e))}function Pe(e){return r(r(c(e.Jb),e.mc),[4,0])}function Oe(e){var t,n=l(function(e,t){var n;return n=p(e,t&=63),0>e[1]&&(n=r(n,d([2,0],63-t))),n}(e.xc,32));if(0!=n||a(e.xc,[4278190080,0])<0){e.mc=r(e.mc,c(e.Jb)),t=e.Oc;do{v(e.Ab,t+n),t=255}while(0!=--e.Jb);e.Oc=l(e.xc)>>>24}++e.Jb,e.xc=d(i(e.xc,[16777215,0]),8)}function Fe(e,t){return We[(2047&(e-t^-t))>>>2]}function Le(e){for(var t,n,r,i=0,a=0,o=e.length,s=[],c=[];o>i;++i,++a){if(128&(t=255&e[i]))if(192==(224&t)){if(i+1>=o)return e;if(128!=(192&(n=255&e[++i])))return e;c[a]=(31&t)<<6|63&n}else{if(224!=(240&t))return e;if(i+2>=o)return e;if(128!=(192&(n=255&e[++i])))return e;if(128!=(192&(r=255&e[++i])))return e;c[a]=(15&t)<<12|(63&n)<<6|63&r}else{if(!t)return e;c[a]=t}16383==a&&(s.push(String.fromCharCode.apply(String,c)),a=-1)}return a>0&&(c.length=a,s.push(String.fromCharCode.apply(String,c))),s.join("")}function Re(e){var t,n,r,i=[],a=0,o=e.length;if("object"==typeof e)return e;for(function(e,t,n,r,i){var a;for(a=t;n>a;++a)r[i++]=e.charCodeAt(a)}(e,0,o,i,0),r=0;o>r;++r)(t=i[r])>=1&&127>=t?++a:a+=!t||t>=128&&2047>=t?2:3;for(n=[],a=0,r=0;o>r;++r)(t=i[r])>=1&&127>=t?n[a++]=t<<24>>24:!t||t>=128&&2047>=t?(n[a++]=(192|t>>6&31)<<24>>24,n[a++]=(128|63&t)<<24>>24):(n[a++]=(224|t>>12&15)<<24>>24,n[a++]=(128|t>>6&63)<<24>>24,n[a++]=(128|63&t)<<24>>24);return n}function Me(e){return e[1]+e[0]}var Ue=1,Be=2,$e=3,je="function"==typeof setImmediate?setImmediate:setTimeout,Ke=4294967296,ze=[4294967295,-Ke],Je=[0,-0x8000000000000000],qe=[0,0],Ve=[1,0],He=function(){var e,t,n,r=[];for(e=0;256>e;++e){for(n=e,t=0;8>t;++t)0!=(1&n)?n=n>>>1^-306674912:n>>>=1;r[e]=n}return r}(),Ge=function(){var e,t,n,r=2,i=[0,1];for(n=2;22>n;++n)for(t=1<<(n>>1)-1,e=0;t>e;++e,++r)i[r]=n<<24>>24;return i}(),We=function(){var e,t,n,r=[];for(t=8;t>=0;--t)for(e=1<<9-t,n=1<<9-t-1;e>n;++n)r[n]=(t<<6)+(e-n<<6>>>9-t-1);return r}(),Qe=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==Ue&&e.compress(t.gc.gc,t.gc.Rc,t.gc.cbn))}),{compress:function(e,n,r,i){var a,o,s={},c=void 0===r&&void 0===i;if("function"!=typeof r&&(o=r,r=i=0),i=i||function(e){return void 0!==o?t(e,o):void 0},r=r||function(e,t){return void 0!==o?postMessage({action:Ue,cbn:o,result:e,error:t}):void 0},c){for(s.c=S({},Re(e),Qe(n));$(s.c.yb););return y(s.c.Nb)}try{s.c=S({},Re(e),Qe(n)),i(0)}catch(e){return r(null,e)}je((function e(){try{for(var t,n=(new Date).getTime();$(s.c.yb);)if(a=Me(s.c.yb.Pb)/Me(s.c.Tb),(new Date).getTime()-n>200)return i(a),je(e,0),0;i(1),t=y(s.c.Nb),je(r.bind(null,t),0)}catch(e){r(null,e)}}),0)},decompress:function(e,n,r){var i,a,o,s,c={},l=void 0===n&&void 0===r;if("function"!=typeof n&&(a=n,n=r=0),r=r||function(e){return void 0!==a?t(o?e:-1,a):void 0},n=n||function(e,t){return void 0!==a?postMessage({action:Be,cbn:a,result:e,error:t}):void 0},l){for(c.d=C({},e);$(c.d.yb););return Le(y(c.d.Nb))}try{c.d=C({},e),s=Me(c.d.Tb),o=s>-1,r(0)}catch(e){return n(null,e)}je((function e(){try{for(var t,a=0,l=(new Date).getTime();$(c.d.yb);)if(++a%1e3==0&&(new Date).getTime()-l>200)return o&&(i=Me(c.d.yb.Z.g)/s,r(i)),je(e,0),0;r(1),t=Le(y(c.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.DOMPurify=t()}(this,(function(){function e(e){return function(t){for(var n=arguments.length,r=Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return p(e,t,r)}}function t(e){return function(){for(var t=arguments.length,n=Array(t),r=0;r<t;r++)n[r]=arguments[r];return f(e,n)}}function n(e,t){o&&o(e,null);for(var n=t.length;n--;){var r=t[n];if("string"==typeof r){var i=b(r);i!==r&&(s(t)||(t[n]=i),r=i)}e[r]=!0}return e}function r(e){var t={},n=void 0;for(n in e)p(a,e,[n])&&(t[n]=e[n]);return t}function i(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 a=Object.hasOwnProperty,o=Object.setPrototypeOf,s=Object.isFrozen,c=Object.keys,l=Object.freeze,u=Object.seal,d="undefined"!=typeof Reflect&&Reflect,p=d.apply,f=d.construct;p||(p=function(e,t,n){return e.apply(t,n)}),l||(l=function(e){return e}),u||(u=function(e){return e}),f||(f=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 _=e(Array.prototype.forEach),m=e(Array.prototype.indexOf),g=e(Array.prototype.join),h=e(Array.prototype.pop),y=e(Array.prototype.push),v=e(Array.prototype.slice),b=e(String.prototype.toLowerCase),x=e(String.prototype.match),k=e(String.prototype.replace),S=e(String.prototype.indexOf),T=e(String.prototype.trim),C=e(RegExp.prototype.test),E=t(RegExp),D=t(TypeError),A=l(["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"]),N=l(["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"]),w=l(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),I=l(["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"]),P=l(["#text"]),O=l(["accept","action","align","alt","autocomplete","background","bgcolor","border","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","coords","crossorigin","datetime","default","dir","disabled","download","enctype","face","for","headers","height","hidden","high","href","hreflang","id","integrity","ismap","label","lang","list","loop","low","max","maxlength","media","method","min","minlength","multiple","name","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","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","type","usemap","valign","value","width","xmlns"]),F=l(["accent-height","accumulate","additive","alignment-baseline","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","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","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","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"]),L=l(["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"]),R=l(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),M=u(/\{\{[\s\S]*|[\s\S]*\}\}/gm),U=u(/<%[\s\S]*|[\s\S]*%>/gm),B=u(/^data-[\-\w.\u00B7-\uFFFF]/),$=u(/^aria-[\-\w]+$/),j=u(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),K=u(/^(?:\w+script|data):/i),z=u(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205f\u3000]/g),J="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},q=function(){return"undefined"==typeof window?null:window},V=function(e,t){if("object"!==(void 0===e?"undefined":J(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 r="dompurify"+(n?"#"+n:"");try{return e.createPolicy(r,{createHTML:function(e){return e}})}catch(e){return console.warn("TrustedTypes policy "+r+" could not be created."),null}};return function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:q(),a=function(t){return e(t)};if(a.version="2.0.8",a.removed=[],!t||!t.document||9!==t.document.nodeType)return a.isSupported=!1,a;var o=t.document,s=!1,u=!1,d=t.document,p=t.DocumentFragment,f=t.HTMLTemplateElement,H=t.Node,G=t.NodeFilter,W=t.NamedNodeMap,Q=void 0===W?t.NamedNodeMap||t.MozNamedAttrMap:W,Y=t.Text,X=t.Comment,Z=t.DOMParser,ee=t.trustedTypes;if("function"==typeof f){var te=d.createElement("template");te.content&&te.content.ownerDocument&&(d=te.content.ownerDocument)}var ne=V(ee,o),re=ne?ne.createHTML(""):"",ie=d,ae=ie.implementation,oe=ie.createNodeIterator,se=ie.getElementsByTagName,ce=ie.createDocumentFragment,le=o.importNode,ue={};a.isSupported=ae&&void 0!==ae.createHTMLDocument&&9!==d.documentMode;var de=M,pe=U,fe=B,_e=$,me=K,ge=z,he=j,ye=null,ve=n({},[].concat(i(A),i(N),i(w),i(I),i(P))),be=null,xe=n({},[].concat(i(O),i(F),i(L),i(R))),ke=null,Se=null,Te=!0,Ce=!0,Ee=!1,De=!1,Ae=!1,Ne=!1,we=!1,Ie=!1,Pe=!1,Oe=!1,Fe=!1,Le=!1,Re=!0,Me=!0,Ue=!1,Be={},$e=n({},["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=n({},["audio","video","img","source","image"]),Ke=null,ze=n({},["alt","class","for","id","label","name","pattern","placeholder","summary","title","value","style","xmlns"]),Je=null,qe=d.createElement("form"),Ve=function(e){Je&&Je===e||(e&&"object"===(void 0===e?"undefined":J(e))||(e={}),ye="ALLOWED_TAGS"in e?n({},e.ALLOWED_TAGS):ve,be="ALLOWED_ATTR"in e?n({},e.ALLOWED_ATTR):xe,Ke="ADD_URI_SAFE_ATTR"in e?n(r(ze),e.ADD_URI_SAFE_ATTR):ze,ke="FORBID_TAGS"in e?n({},e.FORBID_TAGS):{},Se="FORBID_ATTR"in e?n({},e.FORBID_ATTR):{},Be="USE_PROFILES"in e&&e.USE_PROFILES,Te=!1!==e.ALLOW_ARIA_ATTR,Ce=!1!==e.ALLOW_DATA_ATTR,Ee=e.ALLOW_UNKNOWN_PROTOCOLS||!1,De=e.SAFE_FOR_JQUERY||!1,Ae=e.SAFE_FOR_TEMPLATES||!1,Ne=e.WHOLE_DOCUMENT||!1,Pe=e.RETURN_DOM||!1,Oe=e.RETURN_DOM_FRAGMENT||!1,Fe=e.RETURN_DOM_IMPORT||!1,Le=e.RETURN_TRUSTED_TYPE||!1,Ie=e.FORCE_BODY||!1,Re=!1!==e.SANITIZE_DOM,Me=!1!==e.KEEP_CONTENT,Ue=e.IN_PLACE||!1,he=e.ALLOWED_URI_REGEXP||he,Ae&&(Ce=!1),Oe&&(Pe=!0),Be&&(ye=n({},[].concat(i(P))),be=[],!0===Be.html&&(n(ye,A),n(be,O)),!0===Be.svg&&(n(ye,N),n(be,F),n(be,R)),!0===Be.svgFilters&&(n(ye,w),n(be,F),n(be,R)),!0===Be.mathMl&&(n(ye,I),n(be,L),n(be,R))),e.ADD_TAGS&&(ye===ve&&(ye=r(ye)),n(ye,e.ADD_TAGS)),e.ADD_ATTR&&(be===xe&&(be=r(be)),n(be,e.ADD_ATTR)),e.ADD_URI_SAFE_ATTR&&n(Ke,e.ADD_URI_SAFE_ATTR),Me&&(ye["#text"]=!0),Ne&&n(ye,["html","head","body"]),ye.table&&(n(ye,["tbody"]),delete ke.tbody),l&&l(e),Je=e)},He=function(e){y(a.removed,{element:e});try{e.parentNode.removeChild(e)}catch(t){e.outerHTML=re}},Ge=function(e,t){try{y(a.removed,{attribute:t.getAttributeNode(e),from:t})}catch(e){y(a.removed,{attribute:null,from:t})}t.removeAttribute(e)},We=function(e){var t=void 0,r=void 0;if(Ie)e="<remove></remove>"+e;else{var i=x(e,/^[\s]+/);r=i&&i[0]}var a=ne?ne.createHTML(e):e;if(s)try{t=(new Z).parseFromString(a,"text/html")}catch(e){}if(u&&n(ke,["title"]),!t||!t.documentElement){var o=(t=ae.createHTMLDocument("")).body;o.parentNode.removeChild(o.parentNode.firstElementChild),o.outerHTML=a}return e&&r&&t.body.insertBefore(d.createTextNode(r),t.body.childNodes[0]||null),se.call(t,Ne?"html":"body")[0]};a.isSupported&&(function(){try{We('<svg><p><textarea><img src="</textarea><img src=x abc=1//">').querySelector("svg img")&&(s=!0)}catch(e){}}(),function(){try{var e=We("<x/><title></title><img>");C(/<\/title/,e.querySelector("title").innerHTML)&&(u=!0)}catch(e){}}());var Qe=function(e){return oe.call(e.ownerDocument||e,e,G.SHOW_ELEMENT|G.SHOW_COMMENT|G.SHOW_TEXT,(function(){return G.FILTER_ACCEPT}),!1)},Ye=function(e){return!(e instanceof Y||e instanceof X||"string"==typeof e.nodeName&&"string"==typeof e.textContent&&"function"==typeof e.removeChild&&e.attributes instanceof Q&&"function"==typeof e.removeAttribute&&"function"==typeof e.setAttribute&&"string"==typeof e.namespaceURI)},Xe=function(e){return"object"===(void 0===H?"undefined":J(H))?e instanceof H:e&&"object"===(void 0===e?"undefined":J(e))&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName},Ze=function(e,t,n){ue[e]&&_(ue[e],(function(e){e.call(a,t,n,Je)}))},et=function(e){var t=void 0;if(Ze("beforeSanitizeElements",e,null),Ye(e))return He(e),!0;var n=b(e.nodeName);if(Ze("uponSanitizeElement",e,{tagName:n,allowedTags:ye}),("svg"===n||"math"===n)&&0!==e.querySelectorAll("p, br").length)return He(e),!0;if(!ye[n]||ke[n]){if(Me&&!$e[n]&&"function"==typeof e.insertAdjacentHTML)try{var r=e.innerHTML;e.insertAdjacentHTML("AfterEnd",ne?ne.createHTML(r):r)}catch(e){}return He(e),!0}return"noscript"===n&&C(/<\/noscript/i,e.innerHTML)||"noembed"===n&&C(/<\/noembed/i,e.innerHTML)?(He(e),!0):(!De||e.firstElementChild||e.content&&e.content.firstElementChild||!C(/</g,e.textContent)||(y(a.removed,{element:e.cloneNode()}),e.innerHTML?e.innerHTML=k(e.innerHTML,/</g,"<"):e.innerHTML=k(e.textContent,/</g,"<")),Ae&&3===e.nodeType&&(t=e.textContent,t=k(t,de," "),t=k(t,pe," "),e.textContent!==t&&(y(a.removed,{element:e.cloneNode()}),e.textContent=t)),Ze("afterSanitizeElements",e,null),!1)},tt=function(e,t,n){if(Re&&("id"===t||"name"===t)&&(n in d||n in qe))return!1;if(Ce&&C(fe,t));else if(Te&&C(_e,t));else{if(!be[t]||Se[t])return!1;if(Ke[t]);else if(C(he,k(n,ge,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==S(n,"data:")||!je[e])if(Ee&&!C(me,k(n,ge,"")));else if(n)return!1}return!0},nt=function(e){var t=void 0,n=void 0,r=void 0,i=void 0,o=void 0;Ze("beforeSanitizeAttributes",e,null);var s=e.attributes;if(s){var l={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:be};for(o=s.length;o--;){var u=t=s[o],d=u.name,p=u.namespaceURI;if(n=T(t.value),r=b(d),l.attrName=r,l.attrValue=n,l.keepAttr=!0,l.forceKeepAttr=void 0,Ze("uponSanitizeAttribute",e,l),n=l.attrValue,!l.forceKeepAttr){if("name"===r&&"IMG"===e.nodeName&&s.id)i=s.id,s=v(s,[]),Ge("id",e),Ge(d,e),m(s,i)>o&&e.setAttribute("id",i.value);else{if("INPUT"===e.nodeName&&"type"===r&&"file"===n&&l.keepAttr&&(be[r]||!Se[r]))continue;"id"===d&&e.setAttribute(d,""),Ge(d,e)}if(l.keepAttr)if(De&&C(/\/>/i,n))Ge(d,e);else if(C(/svg|math/i,e.namespaceURI)&&C(E("</("+g(c($e),"|")+")","i"),n))Ge(d,e);else{Ae&&(n=k(n,de," "),n=k(n,pe," "));var f=e.nodeName.toLowerCase();if(tt(f,r,n))try{p?e.setAttributeNS(p,d,n):e.setAttribute(d,n),h(a.removed)}catch(e){}}}}Ze("afterSanitizeAttributes",e,null)}},rt=function e(t){var n=void 0,r=Qe(t);for(Ze("beforeSanitizeShadowDOM",t,null);n=r.nextNode();)Ze("uponSanitizeShadowNode",n,null),et(n)||(n.content instanceof p&&e(n.content),nt(n));Ze("afterSanitizeShadowDOM",t,null)};return a.sanitize=function(e,n){var r=void 0,i=void 0,s=void 0,c=void 0,l=void 0;if(e||(e="\x3c!--\x3e"),"string"!=typeof e&&!Xe(e)){if("function"!=typeof e.toString)throw D("toString is not a function");if("string"!=typeof(e=e.toString()))throw D("dirty is not a string, aborting")}if(!a.isSupported){if("object"===J(t.toStaticHTML)||"function"==typeof t.toStaticHTML){if("string"==typeof e)return t.toStaticHTML(e);if(Xe(e))return t.toStaticHTML(e.outerHTML)}return e}if(we||Ve(n),a.removed=[],"string"==typeof e&&(Ue=!1),Ue);else if(e instanceof H)1===(i=(r=We("\x3c!--\x3e")).ownerDocument.importNode(e,!0)).nodeType&&"BODY"===i.nodeName||"HTML"===i.nodeName?r=i:r.appendChild(i);else{if(!Pe&&!Ae&&!Ne&&Le&&-1===e.indexOf("<"))return ne?ne.createHTML(e):e;if(!(r=We(e)))return Pe?null:re}r&&Ie&&He(r.firstChild);for(var u=Qe(Ue?e:r);s=u.nextNode();)3===s.nodeType&&s===c||et(s)||(s.content instanceof p&&rt(s.content),nt(s),c=s);if(c=null,Ue)return e;if(Pe){if(Oe)for(l=ce.call(r.ownerDocument);r.firstChild;)l.appendChild(r.firstChild);else l=r;return Fe&&(l=le.call(o,l,!0)),l}var d=Ne?r.outerHTML:r.innerHTML;return Ae&&(d=k(d,de," "),d=k(d,pe," ")),ne&&Le?ne.createHTML(d):d},a.setConfig=function(e){Ve(e),we=!0},a.clearConfig=function(){Je=null,we=!1},a.isValidAttribute=function(e,t,n){Je||Ve({});var r=b(e),i=b(t);return tt(r,i,n)},a.addHook=function(e,t){"function"==typeof t&&(ue[e]=ue[e]||[],y(ue[e],t))},a.removeHook=function(e){ue[e]&&h(ue[e])},a.removeHooks=function(e){ue[e]&&(ue[e]=[])},a.removeAllHooks=function(){ue={}},a}()})),pxt||(pxt={}),function(e){!function(t){const n={},r={};let i=!1;t.addDefaultProperties=function(e){Object.keys(e).forEach((t=>{"string"==typeof e[t]?n[t]=e[t]:r[t]=e[t]}))},t.enable=function(){if(!e.aiTrackException||!e.aiTrackEvent||i)return;i=!0,e.debug("setting up app insights");const t=e.tickEvent;e.tickEvent=function(i,a,o){if(t&&t(i,a,o),(null==o?void 0:o.interactiveConsent)&&e.setInteractiveConsent(!0),a){const t=Object.assign({},n)||{},o=Object.assign({},r)||{};Object.keys(a).forEach((e=>{"string"==typeof a[e]?t[e]=a[e]:"number"==typeof a[e]?o[e]=a[e]:t[e]=JSON.stringify(a[e]||"")})),e.aiTrackEvent(i,t,o)}else e.aiTrackEvent(i)};const a=e.reportException;e.reportException=function(t,n){a&&a(t,n);const r={target:e.appTarget.id,version:e.appTarget.versions.target};n&&e.Util.jsonMergeFrom(r,n),e.aiTrackException(t,"exception",r)};const o=e.reportError;e.reportError=function(t,n,r){o&&o(t,n,r);try{throw n}catch(i){const a={target:e.appTarget.id,version:e.appTarget.versions.target,category:t,message:n};r&&e.Util.jsonMergeFrom(a,r),e.aiTrackException(i,"error",a)}}}}(e.analytics||(e.analytics={}))}(pxt||(pxt={})),pxt||(pxt={}),function(e){!function(e){let t,n,r,i=0,a=!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 s(){t&&(r.gain.setTargetAtTime(0,t.currentTime,.015),i=0)}e.mute=function(e){t&&(a=e,s(),e&&n&&(n.disconnect(),r.disconnect(),n=void 0,r=void 0))},e.stop=s,e.frequency=function(){return i},e.tone=function(e){if(a)return;if(e<0)return;i=e;let s=o();if(s)try{n||(n=s.createOscillator(),n.type="triangle",r=s.createGain(),r.gain.value=0,r.connect(s.destination),n.connect(r),n.start(0)),n.frequency.linearRampToValueAtTime(e,t.currentTime),r.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",r="csrf-token",i="login-state",a="user-state";let o,s=!1;t.DEFAULT_USER_PREFERENCES=()=>({highContrast:!1,language:e.appTarget.appTheme.defaultLocale,reader:"",skillmap:{mapProgress:{},completedTags:{}},email:!1}),t.client=function(){return o};let c=0,l=0;t.AuthClient=class{constructor(){this.initialUserPreferences_=void 0,this.initialAuthCheck_=void 0,this.patchQueue=[],e.Util.assert(!o),o=this}async initAsync(){try{this.state$=await e.storage.shared.getAsync(n,a)}catch(e){}this.state$||(this.state$={}),this.setUserProfileAsync(this.state$.profile),this.setUserPreferencesAsync(this.state$.preferences)}async loginAsync(t,r,a){var o;if(!p()||!function(e){return d().filter((t=>t.id===e)).length>0}(t))return;a=null!=a?a:u;const s=this.getState();s.profile||await this.authCheckAsync();if((null===(o=s.profile)||void 0===o?void 0:o.idp)===t)return void e.debug(`loginAsync: Already signed into ${t}.`);this.clearState();const c={key:(Math.PI*Math.random()).toString(36).slice(2),callbackState:a,callbackPathname:window.location.pathname,idp:t};await e.storage.shared.setAsync(n,i,c);const l=e.Util.stringifyQueryString("/api/auth/login",{response_type:"token",provider:t,persistent:r,redirect_uri:`${window.location.origin}${window.location.pathname}?authcallback=1&state=${c.key}`}),f=await this.apiAsync(l);f.success?(e.tickEvent("auth.login.start",{provider:t}),window.location.href=f.resp.loginUrl):await this.onSignInFailed()}async logoutAsync(t){if(!p())return;e.tickEvent("auth.logout"),await this.apiAsync("/api/auth/logout"),await e.storage.shared.delAsync(n,r),this.clearState();const i=t?t.startsWith("#")?t:`#${t}`:"";e.BrowserUtils.hasWindow()&&(window.location.href=`${window.location.origin}${window.location.pathname}${i}`,location.reload())}async deleteProfileAsync(){var t;if(!await this.loggedInAsync())return;const i=null===(t=this.getState().profile)||void 0===t?void 0:t.id,a=await this.apiAsync("/api/user",null,"DELETE");if(a.err)await this.onApiError(a.err);else try{await e.storage.shared.delAsync(n,r);try{await this.onProfileDeleted(i)}catch(t){e.tickEvent("auth.profile.cloudToLocalFailed")}this.clearState()}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=this.getState();return Object.assign({},e.profile)}async userPreferencesAsync(){const e=this.getState();return Object.assign({},e.preferences)}async authCheckAsync(){var t;if(!p())return;if(!await e.storage.shared.getAsync(n,r))return;const i=this.getState();return(null===(t=i.profile)||void 0===t?void 0:t.id)?this.initialAuthCheck_||(this.initialAuthCheck_=Promise.resolve(i.profile)):this.initialAuthCheck_||(this.initialAuthCheck_=this.fetchUserAsync()),this.initialAuthCheck_}async loggedInAsync(){return await this.authCheckAsync(),this.hasUserId()}async updateUserProfileAsync(e){if(!await this.loggedInAsync())return!1;const t=this.getState(),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(t,n={}){const r=async()=>({success:!0,res:await this.userPreferencesAsync()});if(!(t=(t=Array.isArray(t)?t:[t]).filter((e=>!!e))).length)return await r();const i=(t,n,r)=>{const i=e.U.deepCopy(t);ts.pxtc.jsonPatch.patchInPlace(i,n);let a=ts.pxtc.jsonPatch.diff(t,i);return a.length&&r&&(a=a.filter(r)),a},a=await this.userPreferencesAsync(),o=i(a,t,n.filter);if(!o.length)return await r();if(ts.pxtc.jsonPatch.patchInPlace(a,o),await this.setUserPreferencesAsync(a),!await this.loggedInAsync())return await r();this.patchQueue.push({ops:t,filter:n.filter}),clearTimeout(c);const s=async()=>{if(l=0,!this.patchQueue.length)return await r();const t=await this.apiAsync("/api/user/preferences");if(!t.success)return e.reportError("identity","failed to fetch preferences for patch",t),{success:!1,res:void 0};const n=e.U.deepCopy(t.resp),a=this.patchQueue;this.patchQueue=[],a.forEach((e=>{const t=i(n,e.ops,e.filter);ts.pxtc.jsonPatch.patchInPlace(n,t)}));const o=pxtc.jsonPatch.diff(t.resp,n),s=await this.apiAsync("/api/user/preferences",o,"PATCH");return s.success?this.setUserPreferencesAsync(s.resp):e.reportError("identity","failed to patch preferences",s),{success:s.success,res:s.resp}};return n.immediate?await s():(l||(l=e.U.now()),1e4<e.U.now()-l?await s():(c=setTimeout(s,1e3),{success:!1,res:void 0}))}hasUserId(){var e;if(!p())return!1;return!!(null===(e=this.getState().profile)||void 0===e?void 0:e.id)}async fetchUserAsync(){var e;if(!p())return;const t=this.getState();if(null===(e=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=this.hasUserId();this.transformUserProfile(e);const n=this.hasUserId();this.onUserProfileChanged(),n&&!t?await this.onSignedIn():!n&&t&&await this.onSignedOut()}async setUserPreferencesAsync(e){var n;const r=null!==(n=this.getState().preferences)&&void 0!==n?n:t.DEFAULT_USER_PREFERENCES(),i=ts.pxtc.jsonPatch.diff(r,e);this.transformUserPreferences(Object.assign(Object.assign({},r),e)),await this.onUserPreferencesChanged(i)}async fetchUserPreferencesAsync(){if(!await this.loggedInAsync())return;const e=this.getState(),t=await this.apiAsync("/api/user/preferences");return t.success&&t.resp?(this.setUserPreferencesAsync(t.resp),e.preferences):void 0}transformUserProfile(e){this.state$=Object.assign(Object.assign({},this.state$),{profile:Object.assign({},e)}),this.saveState()}transformUserPreferences(e){this.state$=Object.assign(Object.assign({},this.state$),{preferences:Object.assign({},e)}),this.saveState()}getState(){return this.state$}saveState(){e.storage.shared.setAsync(n,a,this.state$).then((()=>{}))}clearState(){this.state$={},e.storage.shared.delAsync(n,a).then((()=>this.onStateCleared()))}async apiAsync(t,i,a){var o;const s={},c=await e.storage.shared.getAsync(n,r);return c&&(s.authorization=`mkcd ${c}`),s["x-pxt-target"]=null===(o=e.appTarget)||void 0===o?void 0:o.id,t=e.BrowserUtils.isLocalHostDev()?`https://staging.pxt.io${t}`:t,e.Util.requestAsync({url:t,headers:s,data:i,method:a||(i?"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 this.logoutAsync(),{statusCode:e.statusCode,err:e,resp:null,success:!1})))}};const u={hash:"",params:{}};function d(){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 p(){return!s&&!e.BrowserUtils.isPxtElectron()&&d().length>0}function f(e,t){return e.id===t.id&&e.sourceURL===t.sourceURL}t.loginCallbackAsync=async function(t){let a,o=Object.assign({},u);do{if(a=await e.storage.shared.getAsync(n,i),!a)return void e.debug("Auth state not found in storge.");await e.storage.shared.delAsync(n,i);const s=t.state;if(!s||a.key!==s)return void e.debug("Failed to get auth state for key");o=Object.assign(Object.assign({},u),a.callbackState);const c=t.error;if(c){const n=t.error_description;e.tickEvent("auth.login.error",{error:c,provider:a.idp}),e.log(`Auth failed: ${c}:${n}`),o=Object.assign({},u);break}const l=t.token;if(!l){e.debug("Missing authToken in auth callback.");break}await e.storage.shared.setAsync(n,r,l),e.tickEvent("auth.login.success",{provider:a.idp})}while(0);const s=o.hash.startsWith("#")?o.hash:`#${o.hash}`,c=e.Util.stringifyQueryString("",o.params),l=`${a.callbackPathname.startsWith("/")?a.callbackPathname:`/${a.callbackPathname}`}${s}${c}`;window.location.href=l},t.identityProviders=d,t.identityProvider=function(e){return d().filter((t=>t.id===e)).shift()},t.hasIdentity=p,t.enableAuth=function(e=!0){s=!e},t.userName=function(e){var t,n,r,i;return null!==(i=null!==(n=null===(t=null==e?void 0:e.idp)||void 0===t?void 0:t.displayName)&&void 0!==n?n:null===(r=null==e?void 0:e.idp)||void 0===r?void 0:r.username)&&void 0!==i?i:"??"},t.userInitials=function(t){const n=e.auth.userName(t);return ts.pxtc.Util.initials(n)},t.generateUserProfilePicDataUrl=function(t){var n,r;if(null===(r=null===(n=null==t?void 0:t.idp)||void 0===n?void 0:n.picture)||void 0===r?void 0:r.encoded){const n=window.URL||window.webkitURL;try{const r=e.Util.stringToUint8Array(atob(t.idp.picture.encoded)),i=new Blob([r],{type:t.idp.picture.mimeType});t.idp.picture.dataUrl=n.createObjectURL(i)}catch(e){}}},t.badgeEquals=f,t.hasBadge=function(e,t){return e.badges.some((e=>f(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",r={},i={},a=!1;function o(){return n}function s(e){const t=/^(\w{2})-(\w{2}$)/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 c(t,n){return 0==n.length?t:t.replace(/\{([0-9]+)(\:[^\}]+)?\}/g,(function(t,r,i){let a=n[parseInt(r)],o="",s=/^:f(\d*)\.(\d+)/.exec(i);if(s){let e=parseInt(s[2]),t=parseInt(s[1])||0,n=/^0/.test(s[1])?"0":" ",r=a.toFixed(e);if(t>0&&e>0&&(t+=e+1),t>0)for(;r.length<t;)r=n+r;o=r}else o=":x"==i?"0x"+a.toString(16):void 0===a?"(undef)":null===a?"(null)":a.toString?a.toString():a+"";return":a"==i?/^\s*[euioah]/.test(o.toLowerCase())?o="an "+o:/^\s*[bcdfgjklmnpqrstvwxz]/.test(o.toLowerCase())&&(o="a "+o):":s"==i?o=1==a?"":"s":":q"==i?o=e.htmlEscape(o):":jq"==i?o=e.jsStringQuote(o):":uri"==i?o=encodeURIComponent(o).replace(/'/g,"%27").replace(/"/g,"%22"):":url"==i?o=encodeURI(o).replace(/'/g,"%27").replace(/"/g,"%22"):":%"==i&&(o=(100*a).toFixed(1).toString()+"%"),o}))}e.enableLiveLocalizationUpdates=function(){a=!0},e.liveLocalizationEnabled=function(){return a},e.localeInfo=function(){return`${a?"live-":""}${o()}`},e.userLanguage=o,e.normalizeLanguageCode=s,e.setUserLanguage=function(e){n=s(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 r[e]||e},e.getLocalizedStrings=function(){return r},e.setLocalizedStrings=function(e){r=e},e.translationsCache=function(){return i},e.fmt_va=c,e.fmt=function(e,...t){return c(e,t)};const l={};e.dumpLocStats=function(){const e={};Object.keys(l).sort(((e,t)=>l[t]-l[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;l[t]=(l[t]||0)+1;let r=e._localize(t);return r=r.replace(/^\{(id|loc):[^\}]+\}/g,""),c(r,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 r=0;r<t.length;r++)if(null!=e(t[r],n[r]))return"Expected array value "+t[r]+" got "+n[r];return null}let r=Object.keys(t),i=Object.keys(t);if(r.length!=i.length)return"Expected "+r.length+" keys, got "+i.length;for(let i=0;i<r.length;i++){if(!Object.prototype.hasOwnProperty.call(n,r[i]))return"Missing key "+r[i];if(null!=e(t[r[i]],n[r[i]]))return"Expected value of "+r[i]+" to be "+t[r[i]]+", got "+n[r[i]]}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,ts,pxt,pxt,pxt,pxt,pxt,pxt,pxt,pxt,ts,pxt,pxt,pxt,pxt,ts,pxt,ts,pxtmelody,pxtmelody,pxtmelody,pxt,pxt,ts,ts,ts,ts,ts,ts,ts,ts,ts,ts,ts,pxt,pxt,ts,ts,ts,ts,ts,ts,ts,ts,ts,ts,ts,pxt,pxt,pxt,pxt,pxt,pxt,pxt;!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 r(e,t){if(t)for(let n=0;n<t.length;++n)e.push(t[n])}function i(e){let t=[];for(let n=0;n<e.length;++n)r(t,e[n]);return t}function a(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function o(e,t,n,r,i){void 0===r&&(r=0),void 0===i&&(i=n.length-r);for(let a=0;a<i;++a)e[t+a]=n[r+a]}function s(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 r=0;r<e.length;r++){let i=e[r];n=t[n^i]}return n}return e?function(e,t){let r;const i=new Uint8Array(e.length);for(let t=0;t<e.length;++t){const n=e.charCodeAt(t);i[t]=255&n}let a=0;for(let e=0;e<t;++e)r=n(i),a|=r<<8*e,i[0]=(i[0]+1)%255;return a}(e,2):0},n.bufferSerial=function(e,t="",n="?",r=255){for(let i=0;i<t.length;++i){const a=t[i];if(e[n]=(e[n]||"")+a,"\n"===a||e[n].length>r){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 r=new FileReader;r.onload=()=>t(r.result),r.onerror=e=>n(e),r.readAsDataURL(e)})):Promise.resolve(void 0)},n.fileReadAsBufferAsync=function(e){return e?new Promise(((t,n)=>{let r=new FileReader;r.onerror=e=>t(null),r.onload=e=>t(new Uint8Array(r.result)),r.readAsArrayBuffer(e)})):Promise.resolve(null)},n.fileReadAsTextAsync=function(e){return e?new Promise(((t,n)=>{let r=new FileReader;r.onerror=e=>t(null),r.onload=e=>t(r.result),r.readAsText(e)})):Promise.resolve(null)},n.repeatMap=function(e,t){e=e||0;let n=[];for(let r=0;r<e;++r)n.push(t(r));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 r=0;r<e.length;r++)if(!n(e[r],t[r]))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((r=>n[r]=t(r,e[r]))),n},n.values=function(e){return Object.keys(e||{}).map((t=>e[t]))},n.pushRange=r,n.concatArrayLike=function(e){return i(e)},n.concat=i,n.memcpy=o,n.uint8ArrayConcat=function(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)o(n,r,t),r+=t.length;return n},n.jsonTryParse=function(e){try{return JSON.parse(e)}catch(e){return}},n.jsonMergeFrom=function e(t,r){r&&Object.keys(r).forEach((i=>{a(t[i])&&a(r[i])?e(t[i],r[i]):t[i]=n.clone(r[i])}))},n.jsonCopyFrom=function(e,t){let r=n.clone(t);for(let n of Object.keys(t))e[n]=r[n]},n.jsonFlatten=function(e){let t={},r=(e,i)=>{if(null!==i&&"object"==typeof i){n.assert(!Array.isArray(i)),e&&(e+=".");for(let t of Object.keys(i))r(e+t,i[t])}else t[e]=i};return r("",e),t},n.jsonUnFlatten=function(e){let t={};for(let n of Object.keys(e)){let r=t,i=n.split(".");for(let t=0;t<i.length;++t){let a=i[t];t==i.length-1?r[a]=e[n]:("object"!=typeof r[a]&&(r[a]={}),r=r[a])}}return t},n.strcmp=s,n.stringMapEq=function(e,t){let n=Object.keys(e),r=Object.keys(t);if(n.length!=r.length)return!1;for(let r of n){if(!t.hasOwnProperty(r))return!1;if(e[r]!==t[r])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 r=t=>e[t]!=n[t],i=n=>e[n]!=t[n];let a="",o=0;for(;o<e.length;){let t=r(o),n=o;for(;n<e.length;){if(t&&i(n)){if(n-o>2){n--;break}t=!1}if(!t&&r(n))break;n++}a&&(a+="_"),a+=e.slice(o,n),o=n}return a.toUpperCase()===a?a:a.toLowerCase()},n.sortObjectFields=function(e){let t=Object.keys(e);t.sort(s);let n={};return t.forEach((t=>n[t]=e[t])),n},n.chopArray=function(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n},n.unique=function(e,t){let n=[],r={};return e.forEach((e=>{let i=t(e);r.hasOwnProperty(i)||(r[i]=null,n.push(e))})),n},n.groupBy=function(e,t){let n={};return e.forEach((e=>{let r=t(e);n.hasOwnProperty(r)||(n[r]=[]),n[r].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 r in t){const i=t[r];n[r]=e(i)}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 c=Promise.resolve();async function l(e,t,n){let r=0;const i=[],a=[];for(let o=0;o<e;o++){const e=(async()=>{for(;r<t.length;){const e=r++,i=t[e];a[e]=await n(i)}})();i.push(e)}try{await Promise.all(i)}catch(e){throw r=t.length,e}return a}function u(e,t){const n={};return r=>{const i=e(r);return n.hasOwnProperty(i)?n[i]:n[i]=t(r)}}n.nextTick=function(e){c.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 l(1,e,t)},n.promisePoolAsync=l,n.memoizeString=function(e){return u((e=>e),e)},n.promiseTimeout=async function(e,t,n){let r,i;const a=new Promise(((t,a)=>{i=t,r=setTimeout((()=>{i=void 0,clearTimeout(r),a(n||`Promise timed out after ${e}ms`)}),e)}));return Promise.race([t,a]).then((e=>(i&&(clearTimeout(r),i()),e)))},n.defer=function(){let e,t,n,r=!1;return{resolve:function(n){r?pxt.debug("Deferred promise already resolved"):(t?t(n):e=e||new Promise((function(e){e(n)})),r=!0)},reject:function(t){r?pxt.debug("Deferred promise already resolved"):(n?n(t):e=e||new Promise((function(e,n){n(t)})),r=!0)},promise:new Promise((function(r,i){e?r(e):(t=r,n=i)}))}},n.memoize=u,n.debounce=function(e,t,n){let r;return function(){let i=this,a=arguments,o=function(){r=null,n||e.apply(i,a)},s=n&&!r;return clearTimeout(r),r=setTimeout(o,t),s&&e.apply(i,a),r}};function d(e){return e&&(e=e.replace(/\\/g,"/")),e}function p(e){return n.httpRequestCoreAsync(e).then((r=>{const i=r.statusCode;if((e.successCodes||[304,200,201,202]).indexOf(i)<0&&!e.allowHttpErrors){const t=n.lf("Bad HTTP status code: {0} at {1}; message: {2}",r.statusCode,e.url,(r.text||"").slice(0,500)),i=new Error(t);return i.statusCode=r.statusCode,Promise.reject(i)}return r.text&&/application\/json/.test(r.headers["content-type"])&&(r.json=t.U.jsonTryParse(r.text)),r}))}function f(e,t){let n="";if(!e)return n;for(let r=0;r<e.length;++r){let i=e.charCodeAt(r);if(i<=127)n+=e.charAt(r);else if(i<=2047)n+=String.fromCharCode(192|i>>6,128|63&i);else{if(!t&&55296<=i&&i<=56319){let t=e.charCodeAt(++r);isNaN(t)||(i=65536+(i-55296<<10)+(t-56320))}n+=i<=65535?String.fromCharCode(224|i>>12,128|i>>6&63,128|63&i):String.fromCharCode(240|i>>18,128|i>>12&63,128|i>>6&63,128|63&i)}}return n}n.AdaptiveDebouncer=class{constructor(e,t=300,n=2e3,r=2){this.func=e,this.minDelay=t,this.maxDelay=n,this.slowdownFactor=r,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 r;return function(){let i=this,a=arguments,o=function(){r=null,n||e.apply(i,a)},s=n&&!r;r||(r=setTimeout(o,t)),s&&e.apply(i,a)}},n.randomPermute=function(e){for(let t=0;t<e.length;++t){let n=m()%e.length,r=e[t];e[t]=e[n],e[n]=r}},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=p,n.httpGetTextAsync=function(e){return p({url:e}).then((e=>e.text))},n.httpGetJsonAsync=function(e){return p({url:e}).then((e=>e.json))},n.httpPostJsonAsync=function(e,t){return p({url:e,data:t||{}}).then((e=>e.json))},n.stringToUint8Array=function(e){let t=e.length,n=new Uint8Array(t);for(let r=0;r<t;++r)n[r]=255&e.charCodeAt(r);return n},n.uint8ArrayToString=function(e){let t=e.length,n="";for(let r=0;r<t;++r)n+=String.fromCharCode(e[r]);return n},n.fromUTF8=function(e){if(!e)return"";let t="";for(let n=0;n<e.length;++n){let r=255&e.charCodeAt(n);t+=37==r||r>127?"%"+r.toString(16):e.charAt(n)}return decodeURIComponent(t)},n.toUTF8=f,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,r)=>{let i=this.promises[e];i||(i=this.promises[e]=[]),i.push((()=>t().finally((()=>{i.shift(),0==i.length?delete this.promises[e]:i[0]()})).then(n,r))),1==i.length&&i[0]()}))}};function _(){return Date.now()}function m(){let e=new Uint8Array(4);return n.getRandomBuf(e),new Uint32Array(e.buffer)[0]}function g(e,t,n,r){function i(i){pxt.debug(`downloading translations for ${e} ${t} ${n||""}`);let a=pxt.BrowserUtils.isLocalHost()||pxt.webConfig.isStatic?"https://makecode.com/api/":"",o=`${a}translations?lang=${encodeURIComponent(e)}&filename=${encodeURIComponent(t)}&approved=true`;n&&(o+="&branch="+encodeURIComponent(n));const s={};return r&&!pxt.Cloud.useCdnApi()&&(s["If-None-Match"]=r),(a?p:pxt.Cloud.apiRequestWithCdnAsync)({url:o,headers:s}).then((a=>304==a.statusCode||200==a.statusCode?(r=a.headers.etag||"",pxt.BrowserUtils.translationDbAsync().then((o=>o.setAsync(e,t,n,r,a.json||i))).then((()=>a.json||i))):a.json),(e=>{console.log(`failed to load translations from ${o}`)}))}return pxt.BrowserUtils.translationDbAsync().then((r=>r.getAsync(e,t,n))).then((e=>{if(e){r=e.etag;return(Date.now()-e.time)/1e3>300&&i(e.strings),e.strings}return i()}))}function h(e){let[t,r]=n.normalizeLanguageCode(e),i=pxt.appTarget.appTheme;if(i&&i.availableLocales){if(i.availableLocales.indexOf(t)>-1)return!0;if(r&&i.availableLocales.indexOf(r)>-1)return!0}return!1}let y;function v(e,r,i,a,o,s,c){if(c=c||y.Editor,"en-US"===(i=n.normalizeLanguageCode(i)[0])||"en"===i)return Promise.resolve(void 0);let l,u,d=`${i}/${s}/${c}`;if(n.translationsCache()[d])return Promise.resolve(n.translationsCache()[d]);switch(c){case y.Editor:l=[{branch:a,staticName:"strings.json",path:"strings.json"},{branch:o,staticName:"target-strings.json",path:e+"/target-strings.json"}];break;case y.Sim:l=[{branch:o,staticName:"sim-strings.json",path:e+"/sim-strings.json"}];break;case y.Apis:l=[{branch:o,staticName:"bundled-strings.json",path:e+"/bundled-strings.json"}];break;case y.SkillMap:l=[{branch:o,staticName:"skillmap-strings.json",path:"/skillmap-strings.json"}]}function p(e){e&&(u||(u={}),Object.keys(e).filter((t=>!!e[t])).forEach((t=>u[t]=e[t])))}if(s){let s=0;return t.U.promiseMapAllSeries(l,(e=>g(i,e.path,e.branch).then(p,(e=>{console.log(e.message),++s})))).then((()=>(s&&(n.translationsCache()[d]=u),s!==l.length&&u?Promise.resolve(u):(pxt.tickEvent("translations.livetranslationsfailed"),v(e,r,i,a,o,!1,c)))))}return Promise.all(l.map((e=>n.httpGetJsonAsync(`${r}locales/${i}/${e.staticName}`).catch((e=>{}))))).then((e=>{let t={};e.forEach((e=>pxt.Util.jsonMergeFrom(t,e))),Object.keys(t).length&&(u=t,n.translationsCache()[d]=u)}),(e=>{console.error("failed to load localizations")})).then((()=>u))}function b(e){const t={};for(const n of Object.keys(e))t[n]=x(e[n]);return t}function x(e){var t;return{attributes:Object.assign({},e.attributes),parameters:null===(t=e.parameters)||void 0===t?void 0:t.map(k),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 k(e){var n,r;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(S),handlerParameters:null===(r=e.handlerParameters)||void 0===r?void 0:r.map(S),options:e.options?t.U.clone(e.options):void 0,isEnum:e.isEnum}}function S(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,r)=>{let i=e=>{e instanceof Error?r(e):n(e)};this.waiting.push(i),e>0&&t.U.delay(e).then((()=>{let e=this.waiting.indexOf(i);e>=0&&(this.waiting.splice(e,1),r(new Error("Timeout")))}))}))}},n.now=_,n.nowSeconds=function(){return Math.round(_()/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:"български"},bn:{englishName:"Bengali",localizedName:"বাংলা"},ca:{englishName:"Catalan",localizedName:"Català"},cs:{englishName:"Czech",localizedName:"Čeština"},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"},fr:{englishName:"French",localizedName:"Français"},"fr-CA":{englishName:"French (Canada)",localizedName:"Français (Canada)"},"gu-IN":{englishName:"Gujarati",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:"日本語"},kab:{englishName:"Kabyle",localizedName:"شئعم"},ko:{englishName:"Korean",localizedName:"한국어"},kmr:{englishName:"Kurmanji (Kurdish)",localizedName:"کورمانجی"},kn:{englishName:"Kannada",localizedName:"ಕನ್ನಡ"},lt:{englishName:"Lithuanian",localizedName:"Lietuvių"},lv:{englishName:"Latvian",localizedName:"Latviešu"},"ml-IN":{englishName:"Malayalam",localizedName:"മലയാളം"},mr:{englishName:"Marathi",localizedName:"मराठी"},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"},"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:"Русский"},"si-LK":{englishName:"Sinhala (Sri Lanka)",localizedName:"සිංහල (ශ්රී ලංකා)"},sk:{englishName:"Slovak",localizedName:"Slovenčina"},sl:{englishName:"Slovenian",localizedName:"Slovenski"},sr:{englishName:"Serbian",localizedName:"Srpski"},su:{englishName:"Sundanese",localizedName:"ᮘᮞ ᮞᮥᮔ᮪ᮓ"},"sv-SE":{englishName:"Swedish (Sweden)",localizedName:"Svenska (Sverige)"},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=h,n.updateLocalizationAsync=function(t){const{targetId:r,baseUrl:i,pxtBranch:a,targetBranch:o,force:s}=t;let{code:c}=t;if(c=n.normalizeLanguageCode(c)[0],"en-US"===c&&(c="en"),c===n.userLanguage()||!h(c)&&!s)return pxt.debug(`loc: ${c} (using built-in)`),Promise.resolve();pxt.debug(`loc: ${c}`);const l=pxt.Util.liveLocalizationEnabled();return v(r,i,c,a,o,l,e.pxtc.Util.TranslationsKind.Editor).then((t=>(t&&(n.setUserLanguage(c),n.setLocalizedStrings(t)),e.pxtc.Util.downloadTranslationsAsync(r,i,c,a,o,l,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.range=function(e){let t=[];for(let n=0;n<e;++n)t.push(n);return t},n.multipartPostAsync=function(e,t={},r=null,i=null){const a="--------------------------0461489f461126c5";let o="";Object.keys(t).forEach((e=>{return n=e,r=t[e],o+=a+"\r\n",o+='Content-Disposition: form-data; name="'+n+'"\r\n\r\n',void(o+=r+"\r\n");var n,r})),r&&function(e,t){const n=e.split("/").reverse()[0];o+=a+"\r\n",o+='Content-Disposition: form-data; name="files['+e+']"; filename="'+n+'"\r\n',o+="\r\n",o+=t+"\r\n"}(r,i),o+=a+"--\r\n";const s={url:e,method:"POST",headers:{"Content-Type":"multipart/form-data; boundary="+a.slice(2)},data:o};return n.httpRequestCoreAsync(s)},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(f(e))}`)},n.imageMagic=1496611453,n.imageHeaderSize=36,n.encodeBlobAsync=function(e,t){const r=n.imageHeaderSize+t.length,i=3*(e.width*e.height-1);let a=1;for(;a<4&&!(i*a>=8*r);)a++;let o=i*a>>3,s=r-o,c=0,l=e.width*e.height*4;if(s>0){const t=3*e.width;c=Math.ceil(s/t);const n=document.createElement("canvas");n.width=e.width,n.height=e.height+c;n.getContext("2d").drawImage(e,0,0),e=n}let u=pxt.HF2.encodeU32LE([n.imageMagic,t.length,c,0,0,0,0,0,0]);function d(e,t,n,r){let i=0,a=0,o=r[a++];const s=(1<<n)-1;let c=!0;for(;c;){let l=o>>i&s,u=8-i;if(u<=n){if(a>=r.length){if(0==u)break;c=!1}o=r[a++],l|=o<<u&s,i=n-u}else i+=n;e[t]=255&(e[t]&~s|l),3==(3&++t)&&(e[t++]=255)}return t}pxt.Util.assert(u.length==n.imageHeaderSize);const p=e.getContext("2d"),f=p.getImageData(0,0,e.width,e.height);d(f.data,0,1,[a]);let _=4;if(_=d(f.data,_,a,u),pxt.Util.assert(0==(3&_)),0==c)_=d(f.data,_,a,t);else{let e=o-u.length;_=d(f.data,_,a,t.slice(0,e)),_=d(f.data,l,8,t.slice(e))}for(_|=3;_<f.data.length;)f.data[_]=255,_+=4;return p.putImageData(f,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,r=1&t[0]|(1&t[1])<<1|(1&t[2])<<2;if(r>5||0==r)return Promise.reject(new Error(n.lf("Invalid encoded PNG format")));function i(e,n,r){let i=0,a=0,o=0;const s=(1<<n)-1;for(;a<r.length;)o|=(t[e++]&s)<<i,3==(3&e)&&e++,i+=n,i>=8&&(r[a++]=255&o,o>>=8,i-=8);return e}const a=new Uint8Array(pxt.Util.imageHeaderSize);let o=i(4,r,a);const s=pxt.HF2.decodeU32LE(a);if(s[0]!=pxt.Util.imageMagic)return Promise.reject(new Error(n.lf("Invalid magic in encoded PNG")));const c=new Uint8Array(s[1]),l=s[2];if(l>0){const t=(e.height-l)*e.width,n=new Uint8Array((3*(t-1)*r>>3)-pxt.Util.imageHeaderSize);i(o,r,n),c.set(n);const a=new Uint8Array(c.length-n.length);i(4*t,8,a),c.set(a,n.length)}else i(o,r,c);return c}))},n.parseQueryString=function(e){let t={};return e.replace(/\+/g," ").replace(/([^#?&=]+)=([^#?&=]*)/g,((e,n,r)=>(t[decodeURIComponent(n)]=decodeURIComponent(r),""))),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 r=e.bundleddirs;delete e.bundleddirs;const i=e.bundledpkgs;delete e.bundledpkgs;const a=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:b(n.byQName)}}}}if(r&&(o.bundleddirs=[...r]),i){o.bundledpkgs={};for(const e of Object.keys(i))o.bundledpkgs[e]=Object.assign({},i[e])}if(a){o.tutorialInfo={};for(const e of Object.keys(a)){const t=a[e];o.tutorialInfo[e]={hash:t.hash,usedBlocks:Object.assign({},t.usedBlocks),snippetBlocks:Object.assign({},t.snippetBlocks)}}}return o},n.cloneApis=b,n.cloneSymbolInfo=x,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,r)=>{let i,a=!1,o=e.Util.clone(t.headers)||{};i=new XMLHttpRequest,t.responseArrayBuffer&&(i.responseType="arraybuffer"),t.withCredentials&&(i.withCredentials=!0),i.onreadystatechange=()=>{if(!a&&4==i.readyState){a=!0;let e={statusCode:i.status,headers:{},buffer:i.responseBody||i.response,text:t.responseArrayBuffer?void 0:i.responseText};i.getAllResponseHeaders().split(/\r?\n/).forEach((t=>{let n=/^\s*([^:]+): (.*)/.exec(t);n&&(e.headers[n[1].toLowerCase()]=n[2])})),n(e)}};let s,c=t.data,l=t.method||(null==c?"GET":"POST");null==c?s=null:c instanceof Uint8Array?s=c:"object"==typeof c?(s=JSON.stringify(c),o["content-type"]="application/json; charset=utf8"):"string"==typeof c?s=c:e.Util.oops("bad data"),i.open(l,t.url),Object.keys(o).forEach((e=>{i.setRequestHeader(e,o[e])})),null==s?i.send():i.send(s)}))},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 r(e,t){return e>>>t|e<<32-t}function i(t,i){e.Util.assert(8==t.length),e.Util.assert(64==i.length);for(let e=16;e<64;++e){let t=r(i[e-15],7)^r(i[e-15],18)^i[e-15]>>>3,n=r(i[e-2],17)^r(i[e-2],19)^i[e-2]>>>10;i[e]=i[e-16]+t+i[e-7]+n|0}let a=t[0],o=t[1],s=t[2],c=t[3],l=t[4],u=t[5],d=t[6],p=t[7];for(let e=0;e<64;++e){let t=p+(r(l,6)^r(l,11)^r(l,25))+(l&u^~l&d)+n[e]+i[e]|0,f=a&o^a&s^o&s;p=d,d=u,u=l,l=c+t|0,c=s,s=o,o=a,a=t+((r(a,2)^r(a,13)^r(a,22))+f|0)|0}t[0]+=a,t[1]+=o,t[2]+=s,t[3]+=c,t[4]+=l,t[5]+=u,t[6]+=d,t[7]+=p}function a(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 r(e){let r=e.length-63;for(let a=0;a<r;a+=64){for(let t=0;t<16;t++){let r=(t<<2)+a;n[t]=e[r]<<24|e[r+1]<<16|e[r+2]<<8|e[r+3]}i(t,n)}}r(e);let a=64-(e.length+9)%64;64==a&&(a=0);let o=e.length-e.length%64,s=new Uint8Array(e.length-o+1+a+8),c=0;for(;o<e.length;)s[c++]=e[o++];for(s[c++]=128;a-- >0;)s[c++]=0;let l=8*e.length;for(c=s.length;l>0;)s[--c]=255&l,l>>=8;r(s);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=a(e.Util.toUTF8Array(t));return pxt.perf.measureEnd("sha256buffer"),n}t.sha256buffer=a,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]}},r={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 r(e,t){if(!Array.isArray(e))return t;const n=Number.parseFloat(t);return Number.isNaN(n)?t:n}return function e(t,i,a){if(!Object.is(t,i)){i=i||{},t=t||{};for(let e of Object.keys(t))if(!(e in i)){const i=r(t,e);n.remove.push({op:"remove",path:a.concat(i)})}for(const o of Object.keys(i)){const s=t[o],c=i[o],l=r(i,o);l in t?"object"!=typeof s&&"object"!=typeof c&&s!==c||typeof s!=typeof c||Array.isArray(s)!==Array.isArray(c)?n.replace.push({op:"replace",path:a.concat(l),value:c}):e(s,c,a.concat(l)):void 0!==i[l]&&(a.length&&n.add.push({op:"add",path:a,value:Array.isArray(i)?[]:{}}),n.add.push({op:"add",path:a.concat(l),value:c}))}}}(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 i of t){const t=i.path.slice(),a=t.pop();if(null==a)throw new Error("jsonPatch: missing last key");let o=e,s=t.shift();for(;null!=s;){if(!(s in o))throw new Error(`jsonPatch: missing parent element ${s}`);o=o[s],s=t.shift()}if(Array.isArray(o)&&"number"!=typeof a)throw new Error("jsonPatch: expected numeric index for array object");const c=Array.isArray(o)?r:n;"remove"===i.op?c.remove(o,a):"add"!==i.op||a in o?"replace"===i.op&&c.replace(o,a,i.value):c.add(o,a,i.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 r=Array.isArray(e),i=Array.isArray(t);if(r&&i){if(e.length!==t.length)return!1;for(let r=0;r<e.length;++r)if(!n(e[r],t[r]))return!1;return!0}if(r!==i)return!1;const a=Object.keys(e);if(a.length!==Object.keys(t).length)return!1;for(const r of a){if(!t.hasOwnProperty(r))return!1;if(!n(e[r],t[r]))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 r of t){console.log(r.comment);const t=e.pxtc.jsonPatch.diff(r.obja,r.objb);n(t,r.expected)?console.log("succeeded"):(console.error("FAILED"),console.log("got",t),console.log("exp",r.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 r of t){console.log(r.comment),e.pxtc.jsonPatch.patchInPlace(r.obj,r.patches);!n(r.obj,r.expected)||!r.validate||r.validate(r.obj)?console.log("succeeded"):r.expected&&(console.error("FAILED"),console.log("got",r.obj),console.log("exp",r.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,r,i,a={};function o(n,r){/^csv-/.test(n)?e.setAppTargetVariant(n.replace(/^csv-*/,"")):e.appTarget&&(a[n]=r,e.U.jsonCopyFrom(e.appTarget.compile.switches,a),e.U.jsonCopyFrom(t.compile.switches,a))}function s(){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,a),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;n&&n.yottaTarget&&!n.yottaBinary&&(n.yottaBinary="pxt-microbit-app-combined.hex");const r=e.appTarget.appTheme;r&&Object.keys(r).filter((e=>/(logo|hero)$/i.test(e)&&/^@cdnUrl@/.test(r[e]))).forEach((t=>r[t]=e.BrowserUtils.patchCdn(r[t])));const i=e.appTarget.simulator;if(i&&i.boardDefinition&&i.boardDefinition.visual){let t=i.boardDefinition.visual;t.image&&(t.image=e.BrowserUtils.patchCdn(t.image),t.outlineImage&&(t.outlineImage=e.BrowserUtils.patchCdn(t.outlineImage)))}if(Object.keys(e.appTarget.bundledpkgs).forEach((t=>{const n=e.appTarget.bundledpkgs[t],r=JSON.parse(n[e.CONFIG_NAME]);r.icon&&(r.icon=e.BrowserUtils.patchCdn(r.icon)),n[e.CONFIG_NAME]=e.Package.stringifyConfig(r)})),"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((r=>{if(new RegExp(r,"i").exec(n)){let n=t[r];n&&e.U.jsonMergeFrom(e.appTarget,n)}}))}}function c(n=!1){e.perf.measureStart("reloadAppTargetVariant");const r=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))}s(),!n&&e.onAppTargetChanged&&r!=JSON.stringify(e.appTarget)&&e.onAppTargetChanged(),e.perf.measureEnd("reloadAppTargetVariant")}function l(){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 u(){return i||(i=e.Cloud.downloadTargetConfigAsync().then((e=>e||{}),(e=>({})))),i}function d(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||{},s(),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],r=e.lastIndexOf("."),i=t.pyQName,a=n[e]={kind:Math.abs(t.kind||7),qName:e,namespace:e.slice(0,r<0?0:r),name:e.slice(r+1),pyQName:i,pyName:i?i.slice(i.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=a.attributes;o.paramDefl||(o.paramDefl={}),o.callingConvention||(o.callingConvention=0),o.paramHelp||(o.paramHelp={}),o.jsDoc||(o.jsDoc=""),o._name=a.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=r&&r[t];if(n)return n;if(!e.appTarget.simulator||!e.appTarget.simulator.dynamicBoardDefinition)return;r||(r={});const i=e.appTarget.bundledpkgs[t];if(!i)return;if(JSON.parse(i["pxt.json"]).core&&i["board.json"]){const n=JSON.parse(i["board.json"]);if(n&&n.visual&&n.visual.image){let a=n.visual.image;/^pkg:\/\//.test(a)&&(a=i[a.slice(6)]),r[t]=`data:image/svg+xml;base64,${ts.pxtc.encodeBase64(e.Util.toUTF8(a))}`}}return r[t]},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,r){if(console&&(console.error(`${t}: ${n}`),r))try{e.log(JSON.stringify(r,null,2))}catch(e){}},e.localWebConfig=l,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=l())},e.getEmbeddedScript=function(t){return e.U.lookup(e.appTarget.bundledpkgs||{},t)},e.targetConfigAsync=u,e.packagesConfigAsync=function(){return u().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.outputName=d,e.isOutputText=function(e=null){return d(e)==ts.pxtc.BINARY_HEX}}(pxt||(pxt={})),function(e){!function(t){const n="this";let r;function i(){if(r={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:"/blocks/math/random",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:"/blocks/math/random",category:"math",tooltip:e.Util.lf("an integer number")},math_whole_number:{name:e.Util.lf("{id:block}number"),url:"/blocks/math/random",category:"math",tooltip:e.Util.lf("a whole number")},math_number_minmax:{name:e.Util.lf("{id:block}number"),url:"/blocks/math/random",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"),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"),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:{}}},r[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")}},r[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")}},r[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")}},r[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.Util.isTranslationMode()){const t=Blockly.Msg;e.Util.values(r).filter((e=>e.block)).forEach((n=>{const r=Object.keys(n.block);n.translationIds=e.Util.values(n.block),r.forEach((r=>e.crowdin.inContextLoadAsync(n.block[r]).then((e=>{n.block[r]=e,/^[A-Z_]+$/.test(r)&&(t[r]=e)}))))}))}}t.MATH_FUNCTIONS={unary:["sqrt","sin","cos","tan"],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 r=t.replace(/(?:^|[^\\])([%$])\s+/g,"$1");return r!=t&&(n(`block has extra spaces: ${t}`),t=r),r=(t=r).replace(/([%$]\w+)\s*=\s*(\w+)/,"$1=$2"),r!=t&&(n(`block has space between %name and = : ${t}`),t=r),r=r.replace(/\s*\|\s*/g,"|"),r},t.compileInfo=function(e){const r={parameters:[],actualNameToParam:{},definitionNameToParam:{},handlerArgs:[]},i=(1==e.kind||2==e.kind)&&!e.attributes.defaultInstance,a=!!e.attributes._def,o=a?e.attributes._def.parameters.slice(0):void 0,s=a?o.length:e.parameters?e.parameters.length:0,c=t.builtinFunctionInfo[e.qName];a&&e.attributes._expandedDef&&o.push(...e.attributes._expandedDef.parameters);const l={},u=o?o.filter((e=>!e.ref||(l[e.name]=e,!1))):[];if(i&&a&&o.length){const t=l.this||o[0],i=t.name;let a;(!t.shadowBlockId||"variables_get"===t.shadowBlockId)&&(a=t.varName||e.attributes.paramDefl[i]||e.attributes.paramDefl.this),r.thisParameter={actualName:n,definitionName:i,shadowBlockId:t.shadowBlockId,type:e.namespace,defaultValue:a,fieldEditor:d(i,n),fieldOptions:p(i,n),shadowOptions:f(i,n)}}if(e.parameters){let t=i&&!l.this?1:0;e.parameters.forEach(((e,n)=>{let i;if(l[e.name]?i=l[e.name]:t<u.length&&(i=u[t],++t),i||!a){let n;e.options&&e.options.min&&e.options.max&&(n={min:e.options.min.value,max:e.options.max.value});const a=i?i.name:c?c.params[t++]:e.name,l=i&&("variables_get"===i.shadowBlockId||"lists_create_with"==i.shadowBlockId);r.parameters.push({actualName:e.name,type:e.type,defaultValue:l&&i.varName||e.default,definitionName:a,shadowBlockId:i&&i.shadowBlockId,isOptional:!!o&&o.indexOf(i)>=s,fieldEditor:d(a,e.name),fieldOptions:p(a,e.name),shadowOptions:f(a,e.name),range:n})}e.handlerParameters&&e.handlerParameters.forEach((e=>{r.handlerArgs.push({name:e.name,type:e.type,inBlockDef:!!o&&o.some((t=>t.ref&&t.name===e.name))})}))}))}return r.parameters.forEach((e=>{r.actualNameToParam[e.actualName]=e,r.definitionNameToParam[e.definitionName]=e})),r;function d(t,n){return e.attributes.paramFieldEditor&&(e.attributes.paramFieldEditor[t]||e.attributes.paramFieldEditor[n])}function p(t,n){return e.attributes.paramFieldEditorOptions&&(e.attributes.paramFieldEditorOptions[t]||e.attributes.paramFieldEditorOptions[n])}function f(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.reporterTypeForArgType=function(e){let t="argument_reporter_custom";return"boolean"!==e&&"number"!==e&&"string"!==e||(t=`argument_reporter_${e}`),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 r=n[1];return r&&(r=r.trim()),{n:e,ni:t,pre:r,p:n[2]}}))},t.blockDefinitions=function(){return r||i(),r},t.getBlockDefinition=function(e){return r||i(),r[e]}}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(t){function n(){return"undefined"!=typeof navigator}function r(){return n()&&/(Win32|Win64|WOW64)/i.test(navigator.platform)}function i(){return n()&&/mobi/i.test(navigator.userAgent)}function a(){return n()&&/Mac/i.test(navigator.platform)}function o(){return!!navigator&&/Linux/i.test(navigator.platform)}function s(){return n()&&/arm/i.test(navigator.platform)}function c(){return n()&&/Edge/i.test(navigator.userAgent)}function l(){return n()&&/Trident/i.test(navigator.userAgent)}function u(){return!c()&&!l()&&!!navigator&&(/Chrome/i.test(navigator.userAgent)||/Chromium/i.test(navigator.userAgent))}function d(){return!u()&&!c()&&!!navigator&&/(Macintosh|Safari|iPod|iPhone|iPad)/i.test(navigator.userAgent)}function p(){return!d()&&!!navigator&&(/Firefox/i.test(navigator.userAgent)||/Seamonkey/i.test(navigator.userAgent))}function f(){return n()&&/Opera|OPR/i.test(navigator.userAgent)}function _(){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 h(){return"undefined"!=typeof window&&!!window.pxtElectron}function y(){return"undefined"!=typeof window&&!!window.ipcRenderer}function v(){return h()||y()}function b(t){var n;try{return"undefined"!=typeof window&&/^http:\/\/(localhost|127\.0\.0\.1):\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 x(){return"undefined"!=typeof window&&!!window.PointerEvent}function k(){return r()?"windows":a()?"mac":o()&&s()?"rpi":o()?"linux":"unknown"}function S(){return c()?"edge":m()?"epiphany":_()?"midori":f()?"opera":l()?"ie":u()?"chrome":d()?"safari":p()?"firefox":"unknown"}function T(){if(!n())return null;let e=[];return f()&&(e=/(Opera|OPR)\/([0-9\.]+)/i.exec(navigator.userAgent)),m()?e=/Epiphany\/([0-9\.]+)/i.exec(navigator.userAgent):_()?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):c()?/Edge\/([0-9\.]+)/i.exec(navigator.userAgent):l()?/(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.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=r,t.isWindows10=function(){return n()&&/(Win32|Win64|WOW64)/i.test(navigator.platform)&&/Windows NT 10/i.test(navigator.userAgent)},t.isMobile=i,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=a,t.isLinux=o,t.isARM=s,t.isUwpEdge=function(){return"undefined"!=typeof window&&!!window.Windows},t.isEdge=c,t.isChromiumEdge=function(){return n()&&/Edg\//i.test(navigator.userAgent)},t.isIE=l,t.isChrome=u,t.isSafari=d,t.isFirefox=p,t.isOpera=f,t.isMidori=_,t.isEpiphany=m,t.isTouchEnabled=g,t.isPxtElectron=h,t.isIpcRenderer=y,t.isElectron=v,t.isWinRT=()=>!1,t.isLocalHost=b,t.isLocalHostDev=function(){return b()&&!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(){try{return/tutorialview=old/.test(window.location.href)}catch(e){return!1}},t.hasPointerEvents=x,t.hasSaveAs=function(){return c()||l()||p()},t.os=k,t.browser=S,t.browserVersion=T;let C=!1;function E(){return i()&&d()&&!/downloadWindowOpen=0/i.test(window.location.href)}function D(t,n,r){const a=E(),o=T(),s=parseInt(o||"0");if(a)r?r.location.href=t:window.open(t,"_self");else if(e.BrowserUtils.isSafari()&&(s<10||0==o.indexOf("10.0")||i())){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 r=atob(t.split(",")[1]),i=e.Util.stringToUint8Array(r),a=new Blob([i],{type:"img/png"});window.navigator.msSaveOrOpenBlob(a,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 A(t,n){let r="data";i()&&d()&&e.appTarget.appTheme.mobileSafariDownloadProtocol&&(r=e.appTarget.appTheme.mobileSafariDownloadProtocol);const a=/downloadProtocol=([a-z0-9:/?]+)/i.exec(window.location.href);a&&(r=a[1]);return r+":"+n+";base64,"+t}function N(t,n,r={}){var i;e.debug("trigger download");const{contentType:a="application/octet-stream",userContextWindow:o,onError:s,maintainObjectURL:c}=r,l=null===(i=window.URL)||void 0===i?void 0:i.createObjectURL,u=e.appTarget.appTheme.disableBlobObjectDownload;let d;try{if(l&&!u){const r=l(new Blob([e.Util.stringToUint8Array(atob(t))],{type:a}));D(r,n,o),c?d=r:window.setTimeout((()=>window.URL.revokeObjectURL(d)),0)}else d=A(t,n),D(d,n,o)}catch(t){s&&s(t),e.debug("saving failed")}return d}function w(e){const t=document.createElement("img");return new Promise(((n,r)=>{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 r=(null===(t=e.appTarget)||void 0===t?void 0:t.unsupportedBrowsers)||(null===(n=window.pxtTargetBundle)||void 0===n?void 0:n.unsupportedBrowsers);if(null==r?void 0:r.some((e=>e.id==S())))return!1;const i=T(),a=parseInt(i||"0"),l=u()&&a>=38,g=p()&&a>=31,h=c(),y=d()&&a>=9,v=f()&&u()&&a>=21;let b=l||g||h||y||v;const x=_()||o()&&s()&&m();return b=b&&!x,b=b||/anybrowser=(true|1)/.test(window.location.href),C||(e.log(`Browser: ${S()} ${i} on ${k()}`),b||e.tickEvent("browser.unsupported",{useragent:navigator.userAgent}),C=!0),b},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 N(ts.pxtc.encodeBase64(e),t,n)},t.browserDownloadText=function(t,n,r){return N(ts.pxtc.encodeBase64(e.Util.toUTF8(t)),n,r)},t.isBrowserDownloadInSameWindow=E,t.isBrowserDownloadWithinUserContext=function(){const e=T(),t=parseInt(e||"0");return i()&&d()&&t>=11||/downloadUserContext=1/i.test(window.location.href)},t.browserDownloadDataUri=D,t.browserDownloadUInt8Array=function(t,n,r){return N(ts.pxtc.encodeBase64(e.Util.uint8ArrayToString(t)),n,r)},t.toDownloadDataUri=A,t.browserDownloadBase64=N,t.loadImageAsync=w,t.loadCanvasAsync=function(e){return w(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");n.width=e.width*t,n.height=e.height*t;const r=n.getContext("2d");return r.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");n.width=e.width*t,n.height=e.height*t;const r=n.getContext("2d");return r.putImageData(e,0,0),r.imageSmoothingEnabled=!1,r.scale(t,t),r.drawImage(n,0,0),n.toDataURL("image/png")};const I=1e6;function P(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:r,height:i,pixelDensity:a=4,maxSize:o=I,text:s}=n||{};return new Promise(((n,c)=>{const l=new Image;l.onload=function(){const t=document.createElement("canvas"),c=t.getContext("2d");t.width=(r||l.width)*a,t.height=(i||l.height)*a,s&&(c.fillStyle="#fff",c.fillRect(0,0,t.width,t.height)),c.drawImage(l,0,0,r,i,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}`),c.drawImage(l,0,0,r,i,0,0,t.width,t.height),u=t.toDataURL("image/png");if(s){e.lzmaCompressAsync(s).then((r=>{const i=e.Util.encodeBlobAsync(t,r);n(i.toDataURL("image/png"))}))}else n(u)},l.onerror=t=>{e.reportError("png","png rendering failed"),n(void 0)},l.src=t}))},t.resolveCdnUrl=P,t.loadStyleAsync=function(t,n){n&&(t="rtl"+t);const r="style-"+t;if(document.getElementById(r))return Promise.resolve();const i=P(t),a=e.Util.toArray(document.head.getElementsByTagName("link")).filter((e=>e.getAttribute("href")==i))[0];return a?(a.id||(a.id=r),Promise.resolve()):new Promise(((e,t)=>{const n=document.createElement("link");n.href=i,n.rel="stylesheet",n.type="text/css",n.id=r,n.addEventListener("load",(()=>e())),n.addEventListener("error",(e=>t(e))),document.head.appendChild(n)}))};let O,F,L,R={};function M(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 U(){const e=n()&&window.navigator;return e&&e.storage&&e.storage.estimate?e.storage.estimate():Promise.resolve({})}t.loadScriptAsync=function(t){const n=P(t);let r=R[n];return r||(r=R[n]=new Promise(((t,r)=>{e.debug(`script: loading ${n}`);const i=document.createElement("script");i.type="text/javascript",i.addEventListener("load",(()=>t())),i.addEventListener("error",(e=>{delete R[n],r(e)})),i.src=n,i.async=!0,document.body.appendChild(i)}))),r},t.loadAjaxAsync=function(e){return new Promise(((t,n)=>{let r=new XMLHttpRequest;r.onreadystatechange=function(){r.readyState==XMLHttpRequest.DONE&&(200==r.status?t(r.responseText):n(r.status))},r.open("GET",e,!0),r.send()}))},t.loadBlocklyAsync=function(){if(!O){e.debug("blockly: delay load");let t=e.BrowserUtils.loadStyleAsync("blockly.css",ts.pxtc.Util.isUserLanguageRtl());"undefined"==typeof Blockly&&(t=t.then((()=>e.BrowserUtils.loadScriptAsync("pxtblockly.js")))),t=t.then((()=>{e.debug("blockly: loaded")})),O=t}return O},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 r=t.filter((t=>e.Util.endsWith(t.getAttribute("href"),"blockly.css")))[0];if(r){const t=r.getAttribute("data-rtl");t&&(e.debug(`swapping to ${t}`),r.setAttribute("href",t),r.removeAttribute("data-rtl"))}}},t.changeHash=function(e,t){"#"!=e.charAt(0)&&(e="#"+e),t?window.location.hash=e:window.history.replaceState("","",e)},t.urlJoin=M,t.joinURLs=function(...e){let t;if(e)for(let n=0;n<e.length;n++)t=M(t,e[n]);return t},t.storageEstimateAsync=U,t.scheduleStorageCleanup=n()&&navigator.storage&&navigator.storage.estimate?ts.pxtc.Util.throttle((function(){U().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"),z()):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((()=>K())).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,n){return`${e}|${t}|${n||"master"}`}get(e,t,n){return this.translations[this.key(e,t,n)]}getAsync(e,t,n){return Promise.resolve(this.get(e,t,n))}set(e,t,n,r,i,a,o){this.translations[this.key(e,t,n)]={etag:r,time:i,strings:a,md:o}}setAsync(t,n,r,i,a,o){return this.set(t,n,r,i,e.Util.now(),a),Promise.resolve()}clearAsync(){return this.translations={},Promise.resolve()}}class ${constructor(e,t,n,r){this.name=e,this.version=t,this.upgradeHandler=n,this.quotaExceededHandler=r}throwIfNotOpened(){if(!this._db)throw new Error("Database not opened; call IDBWrapper.openAsync() first")}errorHandler(t,n,r){console.error(new Error(`${this.name} IDBWrapper error for ${n}: ${t.message}`)),r(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 r=(window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB).deleteDatabase(e);r.onsuccess=()=>t(),r.onerror=()=>n(r.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,r)=>{const i=this.getObjectStore(e).get(t);i.onsuccess=()=>n(i.result),i.onerror=()=>this.errorHandler(i.error,"get",r)}))}getAllAsync(e){return new Promise(((t,n)=>{const r=this.getObjectStore(e).openCursor(),i=[];r.onsuccess=()=>{r.result?(i.push(r.result.value),r.result.continue()):t(i)},r.onerror=()=>this.errorHandler(r.error,"getAll",n)}))}setAsync(e,t){return new Promise(((n,r)=>{const i=this.getObjectStore(e,"readwrite");let a;a=void 0!==t.id&&null!==t.id?i.put(t):i.add(t),a.onsuccess=()=>n(),a.onerror=()=>this.errorHandler(a.error,"set",r)}))}deleteAsync(e,t){return new Promise(((n,r)=>{const i=this.getObjectStore(e,"readwrite").delete(t);i.onsuccess=()=>n(),i.onerror=()=>this.errorHandler(i.error,"delete",r)}))}deleteAllAsync(e){return new Promise(((t,n)=>{const r=this.getObjectStore(e,"readwrite").clear();r.onsuccess=()=>t(),r.onerror=()=>this.errorHandler(r.error,"deleteAll",n)}))}}t.IDBWrapper=$;class j{constructor(e){this.db=e,this.mem=new B}static dbName(){return`__pxt_translations_${e.appTarget.id||""}`}static createAsync(){function e(){const e=new $(j.dbName(),2,((e,t)=>{t.result.createObjectStore(j.TABLE,{keyPath:j.KEYPATH})}),(()=>{z().catch((e=>{}))}));return e.openAsync().then((()=>new j(e)))}return e().catch((t=>(console.log("db: failed to open database, try delete entire store..."),$.deleteDatabaseAsync(j.dbName()).then((()=>e())))))}getAsync(e,t,n){e=(e||"en-US").toLowerCase();const r=this.mem.key(e,t,n),i=this.mem.get(e,t,n);return i?Promise.resolve(i):this.db.getAsync(j.TABLE,r).then((r=>r?(this.mem.set(e,t,n,r.etag,r.time,r.strings),Promise.resolve(r)):Promise.resolve(void 0))).catch((e=>Promise.resolve(void 0)))}setAsync(n,r,i,a,o,s){n=(n||"en-US").toLowerCase();const c=this.mem.key(n,r,i);let l=e.Util.now();this.mem.set(n,r,i,a,l,o,s),o&&Object.keys(o).filter((e=>!o[e])).forEach((e=>delete o[e]));const u={id:c,etag:a,time:l,strings:o,md:s};return this.db.setAsync(j.TABLE,u).finally((()=>t.scheduleStorageCleanup())).catch((e=>(console.log(`db: set failed (${e.message}), recycling...`),this.clearAsync())))}clearAsync(){return this.db.deleteAllAsync(j.TABLE).then((()=>console.debug("db: all clean"))).catch((e=>{console.error("db: failed to delete all")}))}}function K(){return e.Util.isNodeJS?Promise.resolve(new B):(F||(F=j.createAsync().catch((()=>new B))),F)}function z(){function t(){const t=j.dbName();return $.deleteDatabaseAsync(t).then((()=>{F=void 0})).catch((n=>{e.log(`db: failed to delete ${t}`),F=void 0}))}return F?F.then((e=>e.clearAsync())).catch((e=>t().then())):t()}function J(t){const n=JSON.stringify(t)+e.appTarget.versions.pxt+"_"+e.appTarget.versions.target;return pxtc.U.sha256(n)}function q(e,t){return`${e}|${t||"master"}`}j.TABLE="files",j.KEYPATH="id",t.translationDbAsync=K,t.clearTranslationDbAsync=z,t.getTutorialCodeHash=J;class V{constructor(e){this.db=e}static dbName(){return`__pxt_tutorialinfo_${e.appTarget.id||""}`}static createAsync(){function t(){const t=new e.BrowserUtils.IDBWrapper(V.dbName(),2,((e,t)=>{t.result.createObjectStore(V.TABLE,{keyPath:V.KEYPATH})}),(()=>{e.BrowserUtils.IDBWrapper.deleteDatabaseAsync(V.dbName())}));return t.openAsync().then((()=>new V(t)))}return t().catch((n=>(console.log("db: failed to open tutorial info database, try delete entire store..."),e.BrowserUtils.IDBWrapper.deleteDatabaseAsync(V.dbName()).then((()=>t())))))}getAsync(t,n,r){const i=q(t,r),a=J(n);return this.db.getAsync(V.TABLE,i).then((t=>{if(t&&t.hash==a&&e.Util.now()-(t.time||0)<864e5)return t;this.db.deleteAsync(V.TABLE,i)}))}setAsync(t,n,r,i){e.perf.measureStart("tutorial info db setAsync");q(t,i);const a=J(r);return this.setWithHashAsync(t,n,a)}setWithHashAsync(t,n,r,i){e.perf.measureStart("tutorial info db setAsync");const a=q(t,i),o={};Object.keys(n).forEach((e=>{Object.keys(n[e]).forEach((t=>{o[t]=n[e][t]}))}));const s={id:a,time:e.Util.now(),hash:r,snippets:n,blocks:o};return this.db.setAsync(V.TABLE,s).then((()=>{e.perf.measureEnd("tutorial info db setAsync")}))}clearAsync(){return this.db.deleteAllAsync(V.TABLE).then((()=>console.debug("db: all clean"))).catch((e=>{console.error("db: failed to delete all")}))}}function H(e){return e.split(/\s+/).filter((e=>!!e))}function G(){const t=new RegExp(`${e.Util.escapeForRegex(e.Util.pxtLangCookieId)}=(.*?)(?:;|$)`).exec(document.cookie);return t&&t[1]||null}V.TABLE="info",V.KEYPATH="id",t.tutorialInfoDbAsync=function(){return L||(L=V.createAsync()),L},t.clearTutorialInfoDbAsync=function(){function t(){const t=V.dbName();return $.deleteDatabaseAsync(t).then((()=>{L=void 0})).catch((n=>{e.log(`db: failed to delete ${t}`),L=void 0}))}return L?L.then((e=>e.clearAsync())).catch((e=>t().then())):t()},t.pointerEvents=x()?{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,r,i){try{const e=window.screenLeft?window.screenLeft:window.screenX,a=window.screenTop?window.screenTop:window.screenY,o=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth,s=window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight,c=o/2-r/2+e,l=s/2-i/2+a,u=window.open(t,n,"width="+r+", height="+i+", top="+l+", left="+c);return u.focus&&u.focus(),u}catch(n){return e.tickEvent("pxt.popupError",{url:t,msg:n.message}),null}},t.containsClass=function(e,t){return H(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){H(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){H(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=G,t.setCookieLang=function(t,n=!1){if(e.Util.allLanguages[t]&&t!==G()){e.tickEvent("menu.lang.setcookielang",{lang:t,docs:`${n}`});const r=new Date;r.setTime(r.getTime()+24*e.Util.langCookieExpirationDays*60*60*1e3),document.cookie=`${e.Util.pxtLangCookieId}=${t}; expires=${r.toUTCString()}; path=/`}},t.cacheBustingUrl=function(e){return e?/[?&]rnd=/.test(e)?e:`${e}${e.indexOf("?")>0?"&":"?"}rnd=${Math.random()}`:e}}(e.BrowserUtils||(e.BrowserUtils={}))}(pxt||(pxt={})),function(e){!function(e){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("Saving project to the cloud..."),shortStatus:lf("saving..."),longStatus:lf("Saving to cloud..."),indicator:"*"}}}(e.cloud||(e.cloud={}))}(pxt||(pxt={})),function(e){!function(e){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(){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(((r,i)=>{try{t.decompress(n,((t,n)=>{n&&e.debug("lzma decompression failed"),r(n?void 0:t)}))}catch(t){t&&e.debug("lzma decompression failed"),r(void 0)}}))))},e.lzmaCompressAsync=function(n){return t().then((t=>new Promise(((r,i)=>{try{t.compress(n,7,((t,n)=>{n&&e.reportException(n),r(n?void 0:new Uint8Array(t))}))}catch(t){e.reportException(t),r(void 0)}}))))}}(pxt||(pxt={})),function(e){!function(t){var n=pxtc.Util;let r=n.lf;const i={"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 a(e="namespace"){let t="",n="",r=(r,i="")=>{n!=r&&(n&&(t+="}\n"),r&&(t+=i||e+" "+r+" {\n"),n=r)},i=" ";return{setNs:r,clear:()=>{t="",n=""},write:e=>{e.trim()?(e=e.trim().replace(/^\s*/gm,i).replace(/^(\s*)\*/gm,((e,t)=>t+" *")),t+=e+"\n"):t+="\n"},incrIndent:()=>{i+=" "},decrIndent:()=>{i=i.slice(4)},finish:()=>(r(""),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=a,t.parseCppInt=o;let s={};class c extends Error{constructor(e){super(e),this.isUserError=!0,this.message=e}}function l(e){if(!e)return"";let t="";for(let n=0;n<e.length;++n){let r=255&e[n];t+=37==r||r>127?"%"+r.toString(16):String.fromCharCode(r)}return decodeURIComponent(t)}function u(t){let n="",r=0;for(;r<t.length;r+=2)n=t[r]+t[r+1]+n;return e.Util.assert(r==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 r=0;r<t.length;++r)if(e[n+r]!=t[r])continue e;let r=e[n+8]|e[n+9]<<8,i=e[n+10]|e[n+11]<<8|e[n+12]<<16|e[n+13]<<24;n+=16;let a=n+r+i;if(a>e.length)continue;let o=e.slice(n,n+r),s=e.slice(n+r,a);return{meta:l(o),text:s}}return null}function p(t){function n(t){return e.debug(t),Promise.reject(new Error(t))}let r;if(e.HF2.read32(t,0)==ts.pxtc.UF2.UF2_MAGIC_START0){let e=ts.pxtc.UF2.toBin(t);e&&(r=d(e.buf))}if(1179403647==e.HF2.read32(t,0)&&(r=d(t)),58==t[0]){r=function(e){if(!e)return;let t,n=0,r=0,i=0,a=0;if(e.split(/\r?\n/).forEach((e=>{let o=/^:10....0[0E]41140E2FB82FA2BB(....)(....)(....)(....)(..)/.exec(e);if(o)n=parseInt(u(o[1]),16),r=parseInt(u(o[2]),16),i=n+r,t=new Uint8Array(i);else if(i>0){if(o=/^:10....0[0E](.*)(..)$/.exec(e),!o)return;let n=o[1];for(;i>0&&n.length>0;)t[a++]=parseInt(n[0]+n[1],16),n=n.slice(2),i--}})),!t||0!=i||a!=t.length)return;let o=new Uint8Array(n),s=new Uint8Array(r);for(let e=0;e<n;++e)o[e]=t[e];for(let e=0;e<r;++e)s[e]=t[n+e];return{meta:l(o),text:s}}(l(t)||"")}if(!r||!r.meta||!r.text)return n("This .hex file doesn't contain source.");let i=JSON.parse(r.meta);return i?"LZMA"==i.compression?e.lzmaDecompressAsync(r.text).then((t=>{if(!t)return null;let n=t.slice(0,i.headerSize||i.metaSize||0),r=t.slice(n.length);return n&&e.Util.jsonCopyFrom(i,JSON.parse(n)),{meta:i,source:r}})):i.compression?n(`Compression type ${i.compression} not supported.`):Promise.resolve({source:l(r.text)}):n("This .hex file is not valid.")}t.PkgConflictError=c,t.getExtensionInfo=function(t){const l={__appVariant:e.appTargetVariant||""},u="dal.d.ts";let d="/source/",p="",f=[];const _=t.sortedDeps(!0).sort(((e,t)=>"this"==e.id?1:"this"==t.id?-1:n.strcmp(e.id,t.id)));for(let t of _)t.disablesVariant(e.appTargetVariant)||t.resolvedDependencies().some((t=>t.disablesVariant(e.appTargetVariant)))?(p&&(p+=", "),p+=t.id,e.debug(`disable variant ${e.appTargetVariant} due to ${t.id}`)):(f.push(t),t.addSnapshot(l,[u,".h",".cpp"]));const m=JSON.stringify(l),g=s[m];if(g){e.debug("Using cached extinfo");const t=n.flatClone(g);return t.disabledDeps=p,t}e.debug("Generating new extinfo");const h=pxtc.emptyExtInfo();h.disabledDeps=p;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 b=!!y.platformioIni,x="codal"==y.buildEngine||"dockercodal"==y.buildEngine,k="dockermake"==y.buildEngine||"dockercross"==y.buildEngine,S="dockerespidf"==y.buildEngine,T=!(b||x||k||S),C=v.nativeType==pxtc.NATIVE_TYPE_VM;b?d="/src/":x||k?d="/pxtapp/":S&&(d="/main/");let E="// Configuration defines\n",D="\nPXT_SHIMS_BEGIN\n",A="",N="",w='#include "pxt.h"\n',I="",P=e=>I+=` ${F}(${O}): ${e}\n`,O=0,F="",L=a("namespace"),R=a("declare namespace"),M=a("declare namespace"),U="",B={},$={};const j={true:"1",false:"0",null:"0",NULL:"0"};function K(e){return e.trim().replace(/[\_\*]$/,"")}for(const t of f){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"))&&(h.generatedFiles["/"+e]=t.host().readFile(t,e))}let z=["0","false","PXT_UTF8"],J={};function q(e){return e.replace(/\/\/.*/,"").replace(/\/\*/,"")}v.switches.boxDebug&&(J.PXT_BOX_DEBUG=1),v.utf8&&(J.PXT_UTF8=1),v.switches.profile&&(J.PXT_PROFILE=1),v.switches.gcDebug&&(J.PXT_GC_DEBUG=1),v.switches.numFloat&&(J.PXT_USE_FLOAT=1),v.nativeType==pxtc.NATIVE_TYPE_VM&&(J.PXT_VM=1);let V=0,H=!1,G="",W="",Q="",Y=!1;function X(){R.setNs(""),R.write(""),R.write(""),(Q||W)&&(R.write(W),R.write(Q),Q="",W="")}function Z(e,t){let a;G="",W="",Q="",Y=!1;let s=-1;function c(){let e=G.replace(/Methods$/,"");return e==G?null:e}function l(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&&P("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 K(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,r,i)=>z.indexOf(n)>=0&&!J[n]?t+r.replace(/[^\n]/g,"")+i:e)),O=0,H=!1,V=0,M.setNs(""),R.setNs(""),e.split(/\r?\n/).forEach((e=>{++O;let d=q(e);!function(e){let t=q(e);if(H&&t.indexOf("}")>=0&&(H=!1,M.write("}")),!H)return;let r=/^\s*(\w+)\s*(=\s*(.*?))?,?\s*$/.exec(t);if(r){let e=r[1],i=r[3],a="";if(i){i=i.trim();let e=n.lookup(j,i);null!=e&&(a=" // "+i,i=e),V=o(i),null==V&&P("cannot determine value of "+t)}else V++,i=V+"";M.write(` ${K(e)} = ${i},${a}`)}else M.write(e)}(e);let p=/^\s*enum\s+(|class\s+|struct\s+)(\w+)\s*({|$)/.exec(d);var f,_;if(p&&(f=p[2],_=p[3],H=!0,V=-1,M.write(""),M.write(""),(Q||W)&&(M.write(W),M.write(Q),Q="",W=""),M.write(`declare const enum ${K(f)} ${_}`),B[f]=!0,t||(L.setNs(G),L.write(`enum ${p[2]} : int;`))),function(e){return!(!H&&(/^\s*\/\*\*/.test(e)?(Y=!0,W=e+"\n",/\*\//.test(e)&&(Y=!1),0):Y?(W+=e+"\n",/\*\//.test(e)&&(Y=!1),0):!/^\s*\/\/%/.test(e)||(Q+=e+"\n",0)))}(e))return;/^typedef.*;\s*$/.test(e)&&(L.setNs(G),L.write(e));let m=/^\s*namespace\s+(\w+)/.exec(e);if(m)if(G=m[1],c()){X();let e=c();R.setNs(G,`declare interface ${e} {`)}else(Q||W)&&(X(),R.setNs(K(G)),M.setNs(K(G)));else{if(m=/^PXT_ABI\((\w+)\)/.exec(e),m&&!C&&(D+=`PXT_FNPTR(::${m[1]}),\n`,N+=`extern "C" void ${m[1]}();\n`,h.functions.push({name:m[1],argsFmt:[],value:0})),m=/^\s*PXT_EXPORT\(([:\&\w]+)\)/.exec(e),m&&(h.vmPointers||(h.vmPointers=[]),h.vmPointers.push(m[1])),m=/^#define\s+PXT_COMM_BASE\s+([0-9a-fx]+)/.exec(e),m&&(h.commBase=parseInt(m[1])),m=/^\s*(\w+)([\*\&]*\s+[\*\&]*)(\w+)\s*\(([^\(\)]*)\)\s*(;\s*$|\{|$)/.exec(e),!Q||!m){if(m=/^\s*extern const (\w+) (\w+);/.exec(e),Q&&m){let e={name:G+"::"+m[2],argsFmt:[],value:null};return h.functions.push(e),C||(D+="PXT_FNPTR(&::"+e.name+"),\n"),void(Q="")}if(m=/^\s*(\w+)\s+(\w+)\s*;/.exec(e),Q&&m){let e=pxtc.parseCommentString(Q);e.indexedInstanceNS&&(a=e,R.setNs(e.indexedInstanceNS),s=0);let t=m[1],n=m[2];if(a)return Q=Q.trim(),Q+=` fixedInstance shim=${a.indexedInstanceShim}(${s++})`,R.write(""),R.write(W),R.write(Q),R.write(`const ${n}: ${l(t)};`),W="",void(Q="")}return Q&&e.trim()?(P("declaration not understood: "+e),Q="",void(W="")):void 0}{a=null;let e=pxtc.parseCommentString(Q);G||P("missing namespace declaration");let s=(m[1]+m[2]).replace(/\s+/g,""),d=m[3],p=m[4];Q=Q.trim().replace(/ \w+\.defl=\w+/g,"");let f=[u(s)],_=[],g=p.split(/,/).filter((e=>!!e)).map((t=>{let r=function(e,t){t=t.trim();let r=/(.*)=\s*(-?\w+)$/.exec(t),i="",a="";if(r&&(i=r[2],a="?",t=r[1].trim()),r=/^(.*?)(\w+)$/.exec(t),!r)return P("invalid argument: "+t),{name:"???",type:"int"};let s=r[2];e.paramDefl[s]&&(i=e.paramDefl[s],a="?");let c=i?n.lookup(j,i):null;return null!=c&&(i=c),i&&(null==o(i)&&P("Invalid default value (non-integer): "+i),Q+=` ${s}.defl=${i}`),{name:s+a,type:r[1]}}(e,t);return f.push(u(r.type)),_.push(r.type.replace(/ /g,"")),`${r.name}: ${l(r.type)}`})),y={name:G+"::"+d,argsFmt:f,value:null};if(W)if(R.setNs(K(G)),R.write(""),R.write(W),/ImageLiteral/.test(m[4])&&!/imageLiteral=/.test(Q)&&(Q+=" imageLiteral=1"),Q+=` shim=${y.name}`,R.write(Q),d=K(d),c()){let e=(g[0]||"").replace(/^.*:\s*/,"").trim();e.toLowerCase()!=c().toLowerCase()&&P(r("Invalid first argument; should be of type '{0}', but is '{1}'",c(),e)),g.shift(),0==g.length&&/\bproperty\b/.test(Q)?R.write(`${d}: ${l(s)};`):R.write(`${d}(${g.join(", ")}): ${l(s)};`)}else R.write(`function ${d}(${g.join(", ")}): ${l(s)};`);if(W="",Q="",t||(L.setNs(G),L.write(`${s} ${d}(${p});`)),h.functions.push(y),T)D+="(uint32_t)(void*)::"+y.name+",\n";else if(C){if(n.startsWith(y.name,"pxt::op_")||i[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,A+=`\nvoid ${n}(FiberContext *ctx) {\n`;const r=t.length;let i=[],a=!1,o="";for(let n=0;n<r;++n){const s=e.argsFmt[n+1],c=t[n];let l="I"==s?"toInt":"B"==s?"numops::toBool":"";const u=n==r-1?"ctx->r0":`ctx->sp[${r-n-2}]`;let d="";switch(c){case"TValue":case"TNumber":break;case"Action":l="asRefAction";break;case"String":l="convertToString",d="ctx, ",a=!0;break;default:l||(l="as"+c.replace(/\*/g,""))}o+=` ${c} a${n} = (${c}) ${l}(${d}${u});\n`,i.push("a"+n)}a&&(A+=" auto prevSP = ctx->sp;\n"),A+=o,a&&(A+=" if (panicCode) { ctx->sp = prevSP; return; }\n");const s=`::${e.name}(${i.join(", ")})`;return"V"==e.argsFmt[0]?(A+=` ${s};\n`,A+=" ctx->r0 = NULL;\n"):"I"==e.argsFmt[0]?A+=` ctx->r0 = fromInt(${s});\n`:"B"==e.argsFmt[0]?A+=` ctx->r0 = fromBool(${s});\n`:A+=` ctx->r0 = (TValue)${s};\n`,a&&(A+=" ctx->sp = prevSP;\n"),r>1&&(A+=` ctx->sp += ${r-1};\n`),A+="}\n",n}(y,_),t=y.argsFmt.length-1;D+=`{ "${y.name}", (OpFun)(void*)${e}, ${t} },\n`}}else D+="PXT_FNPTR(::"+y.name+"),\n"}}}))}const ee=n.clone(y.yottaConfig||{}),te={},ne={},re={};function ie(t){const i=t.config.platformio;i&&i.dependencies&&n.jsonCopyFrom(h.platformio.dependencies,i.dependencies),h.npmDependencies&&t.config.npmDependencies&&n.jsonCopyFrom(h.npmDependencies,t.config.npmDependencies);const a=t.config.codal;if(x&&a)for(const t of a.libraries||[]){const i=e.github.parseRepoId(t);i||n.userError(r("codal library {0} doesn't look like github repo",t));const a=e.github.stringifyRepo(i),o=n.lookup(re,i.project);o?e.github.stringifyRepo(o)!=a&&n.userError(r("conflict between codal libraries: {0} and {1}",e.github.stringifyRepo(o),a)):re[i.project]=i}const o=t.config.yotta;if(o){if(o.dependencies&&n.jsonCopyFrom(h.yotta.dependencies,o.dependencies),o.config){const e=n.jsonFlatten(o.config);for(const i of Object.keys(e)){const a=n.lookup(ne,i),o=e[i];if(!a||a.config.yotta.configIsJustDefaults)ne[i]=t,ee[i]=o;else if(ee[i]===o);else if(!t.parent.config.yotta||!t.parent.config.yotta.ignoreConflicts){let e=new c(r("conflict on yotta setting {0} between extensions {1} and {2}",i,t.id,a.id));throw e.pkg0=a,e.pkg1=t,e.settingName=i,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(T&&v.hasHex){let e=y;n.assert(!!e.yottaCorePackage),n.assert(!!e.githubCorePackage),n.assert(!!e.gittag);let t=e.githubCorePackage+"#"+y.gittag;h.yotta.dependencies[e.yottaCorePackage]=t}if(t){let e=!1;for(let i of f){I="",ie(i),i==t?(e=!0,R.clear(),M.clear()):n.assert(!e);const a=e=>n.endsWith(e,".h"),o=".cpp",s=i.getFiles().filter(a).concat(i.getFiles().filter((e=>!a(e))));for(let e of s){const t=a(e);if(t||n.endsWith(e,o)){let a=i.config.name+"/"+e;("base"==i.config.name||/^core($|---)/.test(i.config.name))&&t&&(a=e),t&&(w+=`#include "${T?d.slice(1):""}${a}"\n`);let o=i.readFile(e);null==o&&n.userError(r("C++ file {0} is missing in extension {1}.",e,i.config.name)),F=a,Z(o,t),h.extensionFiles[d+a]=o,0==i.level&&(h.onlyPublic=!1),i.verProtocol()&&"pub"!=i.verProtocol()&&"embed"!=i.verProtocol()&&(h.onlyPublic=!1)}if(n.endsWith(e,".c")||n.endsWith(e,".S")||n.endsWith(e,".s")){let t=i.readFile(e);h.extensionFiles[d+i.config.name+"/"+e.replace(/\.S$/,".s")]=t}}I&&(U+=r("Extension {0}:\n",i.id)+I)}e||(R.clear(),M.clear())}function ae(e){return Object.keys(h.extensionFiles).concat(Object.keys(h.generatedFiles)).filter((t=>n.endsWith(t,e))).map((e=>e.slice(1)))}U&&n.userError(U),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})),!T&&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(k){let e={name:"pxt-app",private:!0,dependencies:h.npmDependencies};h.generatedFiles["/package.json"]=JSON.stringify(e,null,4)+"\n"}else if(S){const e=n.concatArrayLike([ae(".c"),ae(".cpp"),ae(".s")]).map((e=>e.slice(d.length-1))).concat(["main.cpp"]);e.push("pointers.cpp"),h.generatedFiles[d+"CMakeLists.txt"]="idf_component_register(\n SRCS\n"+e.map((e=>` "${e}"\n`)).join("")+' INCLUDE_DIRS\n "."\n)\n'}else if(x){let t=y,r=n.clone(t.codalDefinitions)||{},i=t.codalTarget;"string"==typeof i&&(i+=".json");let a={target:i,definitions:r,config:r,application:"pxtapp",output_folder:"build",pxt_gitrepo:t.githubCorePackage,pxt_gittag:t.gittag,libraries:n.values(re).map((e=>({name:e.project,url:"https://github.com/"+e.fullName,branch:e.tag||"master",type:"git"})))};0==a.libraries.length&&delete a.libraries,n.iterMap(n.jsonFlatten(oe),((e,t)=>{e=e.replace(/^codal\./,"device.").toUpperCase().replace(/\./g,"_"),r[e]=t})),h.generatedFiles["/codal.json"]=JSON.stringify(a,null,4)+"\n",e.debug(`codal.json: ${h.generatedFiles["/codal.json"]}`)}else if(b){const e=y.platformioIni.slice();e.push("lib_deps ="),n.iterMap(h.platformio.dependencies,((t,n)=>{let r=/[@#\/]/.test(n)?n:t+"@"+n;e.push(" "+r)})),h.generatedFiles["/platformio.ini"]=e.join("\n")+"\n"}else{h.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:h.yotta.dependencies,targetDependencies:{},bin:"./source"};h.generatedFiles["/module.json"]=JSON.stringify(n,null,4)+"\n",e.debug(`module.json: ${h.generatedFiles["/module.json"]}`)}for(let e of Object.keys(J))E+=`#define ${e} ${J[e]}\n`;if(v.uf2Family&&(E+=`#define PXT_UF2_FAMILY ${v.uf2Family}\n`),h.generatedFiles[d+"pointers.cpp"]=w+L.finish()+N+A+D+"\nPXT_SHIMS_END\n",h.generatedFiles[d+"pxtconfig.h"]=E,e.debug(`pxtconfig.h: ${h.generatedFiles[d+"pxtconfig.h"]}`),T&&(h.generatedFiles["/config.json"]=JSON.stringify(oe,null,4)+"\n",e.debug(`yotta config.json: ${h.generatedFiles["/config.json"]}`)),h.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',h.generatedFiles["/Makefile"]){let e="",t=(t,n)=>{e+=`${t} = ${ae(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",h.generatedFiles["/Makefile.inc"]=e}h.generatedFiles["/functions.json"]=JSON.stringify(h.functions,null,1);let se=h.extensionFiles;n.jsonCopyFrom(se,h.generatedFiles);let ce={config:y.serviceId,tag:y.gittag,replaceFiles:se,dependencies:T?h.yotta.dependencies:null},le=JSON.stringify(ce);return h.sha=n.sha256(le),h.skipCloudBuild=!!y.skipCloudBuild,h.compileData=ts.pxtc.encodeBase64(n.toUTF8(le)),h.shimsDTS=R.finish(),h.enumsDTS=M.finish(),Object.keys(s).length>10&&(s={}),s[m]=h,h},t.unpackSourceFromHexFileAsync=function(t){if(t)return e.Util.fileReadAsBufferAsync(t).then((e=>p(new Uint8Array(e))))},t.unpackSourceFromHexAsync=p}(e.cpp||(e.cpp={}))}(pxt||(pxt={})),function(e){!function(t){const n={};let r,i={};function a(i){return n.hasOwnProperty(i.sha)||(n[i.sha]=function(n){let i="";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,r).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,r}(n).then((a=>a?(e.tickEvent("cppcompile.cachehit"),a):function(){if(r)return r;{let t=e.getOnlineCdnUrl();if(t)return r=Promise.resolve(t);const n=e.webConfig&&e.webConfig.isStatic;return r=e.Cloud.privateGetAsync("clientconfig",n).then((e=>e.primaryCdnUrl))}}().then((t=>(i=t+"/compile/"+n.sha,e.U.httpGetTextAsync(i+".hex")))).then((e=>e),(t=>e.Cloud.privatePostAsync("compile/extension",{data:n.compileData},!0).then((t=>new Promise(((n,r)=>{let a=0;const o=8e3,s=3e5,c=e.U.now(),l=()=>{if(a++,e.U.now()-c>s)return e.log("abandoning C++ build"),e.tickEvent("cppcompile.cancel",{retry:a}),n(null),null;let r=t.hex.replace(/\.hex/,".json");return e.log(`polling C++ build ${r} (attempt #${a})`),e.tickEvent("cppcompile.poll",{retry:a}),e.Util.httpGetJsonAsync(r).then((t=>{e.log(`build log ${r.replace(/\.json$/,".log")}`),e.tickEvent("cppcompile.done",{success:(null==t?void 0:t.success)?1:0,retry:a,duration:e.U.now()-c}),t.success?(e.log("fetching "+i+".hex"),n(e.U.httpGetTextAsync(i+".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(l,o),null)))};l()})))))).then((e=>(t.hideLoading(),{hex:e&&e.split(/\r?\n/)}))))).finally((()=>{t.hideLoading()}))}(i)),n[i.sha]}function o(t,n,r,i,a=10){return t.cacheStoreAsync(r,i).then((()=>t.cacheGetAsync(n))).then((i=>{let o;try{o=JSON.parse(i||"[]")}catch(e){console.error("invalid cache entry, clearing entry"),o=[]}o=o.filter((e=>e!=r)),o.unshift(r);let s=o.slice(a);return o=o.slice(0,a),e.U.promiseMapAll(s,(e=>t.cacheStoreAsync(e,"[]"))).then((()=>t.cacheStoreAsync(n,JSON.stringify(o))))}))}function s(e,t,n){return e.cacheGetAsync(t).then((r=>{let i;try{i=JSON.parse(r||"[]")}catch(n){return console.error("invalid cache entry, clearing entry"),e.cacheStoreAsync(t,"[]")}return i[0]!=n?(i=i.filter((e=>e!=n)),i.unshift(n),e.cacheStoreAsync(t,JSON.stringify(i))):null}))}t.showLoading=e=>{},t.hideLoading=()=>{},t.storeWithLimitAsync=o,t.recordGetAsync=s,t.getHexInfoAsync=function(t,n,r){if(!n.sha)return Promise.resolve(null);const c=i[n.sha];if(c)return Promise.resolve(c);e.debug("get hex info: "+n.sha);let l="hex-"+n.sha;return t.cacheGetAsync(l).then((r=>{let i;try{i=r?JSON.parse(r):null}catch(e){console.log("invalid cache entry, clearing entry"),i=null}return i&&i.hex?(e.debug("cache hit, size="+r.length),i.hex=function(t){let n=[];for(let r=0;r<t.length;r++){let i=/^([@!])(....)$/.exec(t[r]);if(!i){n.push(t[r]);continue}let a=parseInt(i[2],16),o=t[++r],s="";if("@"==i[1]){s="";let e=parseInt(o,16);for(;e-- >0;)s+="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"}else s=ts.pxtc.decodeBase64(o);e.Util.assert(s.length>0),e.Util.assert(s.length%16==0);for(let e=0;e<s.length;){let t=[16,a>>8&255,255&a,0];a+=16;for(let n=0;n<16;++n)t.push(s.charCodeAt(e++));let r=0;for(let e=0;e<t.length;++e)r+=t[e];t.push(255&-r);let i=":";for(let e=0;e<t.length;++e){let n=255&t[e];n<=15&&(i+="0"),i+=n.toString(16)}n.push(i.toUpperCase())}}return n}(i.hex),s(t,"hex-keys",l).then((()=>i))):a(n).then((e=>{let n=e.hex;e.hex=function(e){let t=[],n=0;for(let r=0;r<e.length;r+=n){let i=-1,a="";n=0;let o=!1;for(;n<500;){let s=/^:10(....)00(.{32})(..)$/.exec(e[r+n]);if(!s)break;let c=s[2],l=/^0+$/.test(c),u=parseInt(s[1],16);if(-1==i)o=l,t.push((o?"@":"!")+s[1]),i=u-16;else{if(l!=o)break;if(i+16!=u)break}o||(a+=c),i=u,n++}if(0==n)t.push(e[r]),n=1;else if(o)t.push(n.toString(16));else{let e="";for(let t=0;t<a.length;t+=2)e+=String.fromCharCode(parseInt(a.slice(t,t+2),16));t.push(ts.pxtc.encodeBase64(e))}}return t}(e.hex);let r=JSON.stringify(e);return e.hex=n,o(t,"hex-keys",l,r).then((()=>e))})).catch((t=>(e.reportException(t,{sha:n.sha}),Promise.resolve(null))))})).then((e=>(e&&(Object.keys(i).length>20&&(i={}),i[n.sha]=e),e)))}}(e.hexloader||(e.hexloader={}))}(pxt||(pxt={})),function(e){!function(t){function n(n,r,i={},a=null,o=null){if(t.testMode||n==t.TEST_KEY){const e={success:!0};return Promise.resolve({statusCode:200,headers:{},text:JSON.stringify(e),json:e})}return e.Util.multipartPostAsync(r,i,a,o)}function r(n,r,i,a,o){e.Util.assert(!!r&&!!i&&!!a);const s="https://api.crowdin.com/api/project/"+r+"/";return o=o||{},t.testMode?delete o.key:o.key=i,n&&(o.branch=n),s+a+"?"+Object.keys(o).map((e=>`${e}=${encodeURIComponent(o[e])}`)).join("&")}function i(e){let t=0;return function(){if(t++>10)throw new Error("Too many API calls for "+e)}}function a(t,s,c,l,u){return l=o(l),e.debug(`create directory ${t||""}/${l}`),u||(u=i(l)),n(c,r(t,s,c,"add-directory"),{json:"true",name:l}).then((n=>{if(e.debug(`crowdin resp: ${n.statusCode}`),200==n.statusCode||400==n.statusCode)return Promise.resolve();if(500==n.statusCode&&n.text){if(50===JSON.parse(n.text).error.code)return e.log("directory already exists"),Promise.resolve()}const r=n.json||JSON.parse(n.text)||{error:{}};if(404==n.statusCode&&17==r.error.code){e.log(`parent directory missing for ${l}`);const n=l.replace(/\/[^\/]+$/,"");if(n!=l)return a(t,s,c,n,u).then((()=>a(t,s,c,l,u)))}throw new Error(`cannot create directory ${t||""}/${l}: ${n.statusCode} ${JSON.stringify(r)}`)}))}function o(e){return e.replace(/\\/g,"/")}function s(e,t,n,r){const i=t.name,a=n?n+"/"+i:i;switch(t.fullName=a,t.branch=r||"",t.node_type){case"file":e.push(t);break;case"directory":(t.files||[]).forEach((t=>s(e,t,a,r)));break;case"branch":(t.files||[]).forEach((r=>s(e,r,n,t.name)))}}function c(t,n){const r=e.appTarget.versions.pxtCrowdinBranch||"",i=e.appTarget.versions.targetCrowdinBranch||"";let a=[];if(t.forEach((e=>s(a,e,""))),a=a.filter((e=>e.fullName.indexOf("/")<0?e.branch==r:e.branch==i)),n&&(a=a.filter((e=>0==e.fullName.indexOf(n)))),"core"!=e.appTarget.id){const t=e.appTarget.id+"/";a=a.filter((e=>e.fullName.indexOf("/")<0||e.fullName.substr(0,t.length)==t||e.fullName.indexOf("common-docs")>=0))}return a}function l(t,n){const i=r("",t,n,"info",{json:"true"});return e.Util.httpGetTextAsync(i).then((e=>JSON.parse(e)))}t.KEY_VARIABLE="CROWDIN_KEY",t.testMode=!1,t.TEST_KEY="!!!testmode!!!",t.setTestMode=function(){e.crowdin.testMode=!0,e.log("CROWDIN TEST MODE - files will NOT be uploaded")},t.downloadTranslationsAsync=function(t,n,i,a,s={}){const c=r(t,n,i,"info",{json:"true"}),l={};return a=o(a),e.Util.httpGetTextAsync(c).then((o=>{const c=JSON.parse(o);if(!c)throw new Error("info failed");let u=c.languages.filter((e=>"en"!=e.code));e.appTarget&&e.appTarget.appTheme&&e.appTarget.appTheme.availableLocales&&(u=u.filter((t=>e.appTarget.appTheme.availableLocales.indexOf(t.code)>-1))),e.log("languages: "+u.map((e=>e.code)).join(", "));const d=()=>{const o=u.pop();if(!o)return Promise.resolve();const c=r(t,n,i,"export-file",{file:a,language:o.code,export_translated_only:s.translatedOnly?"1":"0",export_approved_only:s.validatedOnly?"1":"0"});return e.log(`downloading ${o.name} - ${o.code} (${u.length} more)`),e.Util.httpGetTextAsync(c).then((t=>{try{const e=JSON.parse(t);e&&(l[o.code]=e)}catch(t){e.log(c+" "+t)}return d()})).then((()=>e.Util.delay(1e3)))};return d()})).then((()=>l))},t.createDirectoryAsync=a,t.uploadTranslationAsync=function t(s,c,l,u,d){e.Util.assert(!!c),e.Util.assert(!!l);const p=i(u=o(u));function f(){return _("update-file",{update_option:"update_as_unapproved"})}function _(i,o){return o.type="auto",o.json="",o.escape_quotes="0",p(),n(l,r(s,c,l,i),o,u,d).then((n=>function(n){const r=n.statusCode,i=e.Util.jsonTryParse(n.text)||{};if(e.debug(`upload result: ${r}`),404==r&&i.error&&8==i.error.code)return e.log(`create new translation file: ${u}`),_("add-file",{});if(404==r&&i.error&&17==i.error.code)return a(s,c,l,u.replace(/\/[^\/]+$/,""),p).then((()=>f()));if(!i.success&&i.error&&53==i.error.code)return e.log(`${u} being updated, waiting 5s and retry...`),e.U.delay(5e3).then((()=>t(s,c,l,u,d)));if(200==r||i.success)return Promise.resolve();throw new Error(`Error, upload translation: ${u}, ${r}, ${n.text}`)}(n)))}return f()},t.projectInfoAsync=l,t.listFilesAsync=function(t,n,r){return e.log(`crowdin: listing files under ${r}`),l(t,n).then((t=>{if(!t)throw new Error("info failed");let n=c(t.files,r);return e.debug(`crowdin: found ${n.length} under ${r}`),n.map((e=>({fullName:e.fullName,branch:e.branch||""})))}))},t.languageStatsAsync=function(t,n,i){const a=r("",t,n,"language-status",{language:i,json:"true"});return e.Util.httpGetJsonAsync(a).then((e=>c(e.files)))},t.inContextLoadAsync=function(t){const n=document.createElement("input");n.type="text",n.setAttribute("class","hidden"),n.value=t;let r=new Promise(((r,i)=>{const a=new MutationObserver((()=>{if(t==n.value)return;const i=e.Util.rlf(n.value);n.remove(),a.disconnect(),r(i)}));a.observe(n,{attributes:!0})}));return document.body.appendChild(n),r}}(e.crowdin||(e.crowdin={}))}(pxt||(pxt={})),function(e){!function(t){function n(e){return e?e.split(/\r?\n/):[]}function r(e,t,r={}){r.ignoreWhitespace&&(e=e.replace(/[\r\n]+$/,""),t=t.replace(/[\r\n]+$/,""));const i=n(e),a=n(t),o=Math.min(r.maxDiffSize||1024,i.length+a.length);if(0==o)return[];const s=i.length>65520?Uint32Array:Uint16Array,c={};let l=0;const u=p(i),d=p(a);function p(e){const t=new s(e.length);let n=0;for(let i of e)r.ignoreWhitespace&&(i=i.replace(/\s+$/g,"").replace(/^\s+/g,"")),c.hasOwnProperty(i)?t[n]=c[i]:(++l,t[n]=l,c[i]=l),n++;return t}const f=new s(2*o+1);let _=-1;for(let e=0;e<=o;e++)null!=T(e,f)&&(_=e);if(-1==_)return null;const m=[];let g=null;for(let e=0;e<=_;e++){const t=m.length?m[m.length-1].slice(0):new s(2*_+1);if(m.push(t),g=T(e,t),null!=g)break}const h=[];let y=g;for(let e=m.length-1;e>=0;e--){const t=m[e];let n=0,r=0;y==-e||y!=e&&t[o+y-1]<t[o+y+1]?(r=y+1,n=t[o+r]):(r=y-1,n=t[o+r]+1);let s=n-y;for(let e=t[o+y]-n-1;e>=0;--e)h.push(" "+a[s+e]);r==y-1?h.push("- "+i[n-1]):s>0&&h.push("+ "+a[s-1]),y=r}if(h.reverse(),r.context==1/0||r.full)return h;let v=1,b=1,x=0;const k=[],S=r.context||3;for(;x<h.length;){let e=x;for(;e<h.length&&" "==h[e][0];)e++;if(e==h.length)break;const t=e-S,n=t-x;n>0&&(v+=n,b+=n,x=t);const r=k.length,i=v,a=b;k.push("@@");let o=x,s=0;for(;o<h.length;){if(" "==h[o][0]){if(s++,s>2*S+2){o-=S+2;break}}else s=0;o++}for(;x<o;){k.push(h[x]);switch(h[x][0]){case"-":v++;break;case"+":b++;break;case" ":v++,b++}x++}k[r]=`@@ -${i},${v-i} +${a},${b-a} @@`}return k;function T(e,t){for(let n=-e;n<=e;n+=2){let r=0;r=n==-e||n!=e&&t[o+n-1]<t[o+n+1]?t[o+n+1]:t[o+n-1]+1;let i=r-n;for(;r<u.length&&i<d.length&&u[r]==d[i];)r++,i++;if(t[o+n]=r,r>=u.length&&i>=d.length)return n}return null}}function i(e){return n(e).map((e=>e.replace(/;\s*$/,""))).join("\n")}function a(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=r,t.diff3=function(t,i,a,o,s){const c=g(t),l=g(a);if(!c||!l)return;const u=n(t),d=n(a);let p=0,f=[],_=0,m=0;for(let t=0;t<c.length-1;)if(c[t]==_&&l[t]==m)f.push(u[_]),_++,m++,t++;else{let n=!0,r=!0,i=t;for(;i<c.length&&(c[i]!=_+i-t&&(n=!1),l[i]!=m+i-t&&(r=!1),null==c[i]||null==l[i]);)i++;if(e.U.assert(i<c.length),n)for(;m<l[i];)f.push(d[m++]);else if(r)for(;_<c[i];)f.push(u[_++]);else if(u.slice(_,c[i]).join("\n")==d.slice(m,l[i]).join("\n"))for(;_<c[i];)f.push(u[_++]);else{for(p++,f.push("<<<<<<< "+o);_<c[i];)f.push(u[_++]);for(f.push("=======");m<l[i];)f.push(d[m++]);f.push(">>>>>>> "+s)}t=i,_=c[i],m=l[i]}return{merged:f.join("\n"),numConflicts:p};function g(t){const n=r(i,t,{context:1/0});if(!n)return;const a=[];let o=0,s=0;for(let t of n)"+"==t[0]?o++:"-"==t[0]?(a[s]=null,s++):" "==t[0]?(a[s]=o,o++,s++):e.U.oops();return a.push(o+1),a}},t.removeTrailingSemiColumns=i,t.split=function(e,t){const n=e.split(/-{10,}/,2);if(n.length<2)return{fileA:e,fileB:void 0};let r=n[0].replace(/\n$/,""),a=n[1].replace(/^\n/,"");return t&&t.removeTrailingSemiColumns&&(r=i(r),a=i(a)),{fileA:r,fileB:a}},t.parseDiffMarker=a,t.render=function(t,n,i={}){const o=r(t,n,i);if(!o)return e.dom.el("div",null,pxtc.Util.lf("Too many differences to render diff."));const s={"@":"diff-marker"," ":"diff-unchanged","+":"diff-added","-":"diff-removed"};let c=0,l=0,u="";const d=e.dom.el("tbody"),p=e.dom.el("table",{class:"diffview "+(i.update?"update":"")},d);let f=null;return o.forEach(((t,n)=>{const p=a(t);p?(c=p.oldStart,l=p.newStart):("+"!=t[0]&&c++,"-"!=t[0]&&l++);const _=o[n+1]?o[n+1][0]:"",m=o[n+2]?o[n+2][0]:"",g=t.slice(2);let h=e.dom.el("code",null,g);if(f)h=f,f=null;else if(!("-"!=t[0]||" "!=u&&"@"!=u||"+"!=_||" "!=m&&"@"!=m&&""!=m)){const i=function(t,n){const i=r(t.split("").join("\n"),n.split("").join("\n"),{context:1/0});if(!i)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 a=[],o=[];for(let t=0;t<i.length;){let n=t;const r=i[t][0];for(;i[n]&&i[n][0]==r;)n++;const s=i.slice(t,n).map((e=>e.slice(2))).join("");" "==r?(a.push(e.dom.el("code",{class:"ch-common"},s)),o.push(e.dom.el("code",{class:"ch-common"},s))):"-"==r?a.push(e.dom.el("code",{class:"ch-removed"},s)):"+"==r?o.push(e.dom.el("code",{class:"ch-added"},s)):e.Util.oops(),t=n}return{a:e.dom.el("div",{class:"inline-diff"},a),b:e.dom.el("div",{class:"inline-diff"},o)}}(t.slice(2),o[n+1].slice(2));h=i.a,f=i.b}if(u=t[0],i.hideMarkerLine&&"@"==u||i.hideRemoved&&"-"==u)return;const y="@"==u,v=`${s[u]}`;d.appendChild(e.dom.el("tr",{class:v},[!i.hideLineNumbers&&e.dom.el("td",{class:"line-a","data-content":c}),!i.hideLineNumbers&&e.dom.el("td",{class:"line-b","data-content":l}),y&&e.dom.el("td",{colspan:2,class:"change"},e.dom.el("code",null,t)),!i.hideMarker&&!y&&e.dom.el("td",{class:"marker","data-content":u}),!y&&e.dom.el("td",{class:"change"},h)]))})),p},t.resolveMergeConflictMarker=function(t,n,r,i){let a=e.diff.toLines(t),o=n;for(;o<a.length&&!/^<<<<<<<[^<]/.test(a[o]);)o++;let s=o+1;for(;s<a.length&&!/^=======$/.test(a[s]);)s++;let c=s+1;for(;c<a.length&&!/^>>>>>>>[^>]/.test(a[c]);)c++;if(c>=a.length)return e.debug(`diff marker mistmatch: ${a.length} -> ${o} ${s} ${c}`),t;if(a[o]=void 0,a[s]=void 0,a[c]=void 0,!r)for(let e=o;e<=s;++e)a[e]=void 0;if(!i)for(let e=s;e<=c;++e)a[e]=void 0;return a.filter((e=>void 0!==e)).join("\n")},t.mergeDiff3Config=function(t,n,r){let i=e.Util.jsonTryParse(t),a=e.Util.jsonTryParse(n),o=e.Util.jsonTryParse(r);if(i&&!o)return t;if(!i)return r||n;if(!a&&o&&(a=o),!i||!a||!o)return;delete i.installedVersion,delete a.installedVersion,delete o.installedVersion;const s={},c=e.U.unique(Object.keys(a).concat(Object.keys(i)).concat(Object.keys(o)),(e=>e));for(const t of c){const n=i[t],r=a[t],c=o[t];if(JSON.stringify(n)==JSON.stringify(c))void 0!==n&&(s[t]=n);else switch(t){case"name":s[t]=l(n,r,c);break;case"version":s[t]=e.semver.strcmp(n,c)>0?n:c;break;case"languageRestriction":case"preferredEditor":case"targetVersion":s[t]=n;break;case"public":s[t]=n&&c;break;case"files":case"testFiles":{const e=u(n||[],r||[],c||[]);if(!e)return;s[t]=e.length?e:void 0;break}case"dependencies":case"testDependencies":{const e=d(n||{},r||{},c||{});if(Object.keys(e).length)return;s[t]=e;break}case"description":if(n&&!c)s[t]=n;else{if(n||!c)return;s[t]=c}break;default:return}}return e.Package.stringifyConfig(s);function l(e,t,n){return e==t?n:n==t?e:e==lf("Untitled")?n:e}function u(t,n,r){const i=[],a=e.U.unique(n.concat(t).concat(r),(e=>e));for(const e of a){const a=t.indexOf(e)>-1,o=r.indexOf(e)>-1,s=n.indexOf(e)>-1;a==o||o==s?a&&i.push(e):o&&i.push(e)}return i}function d(t,n,r){const i={},a=e.U.unique(Object.keys(n).concat(Object.keys(t)).concat(Object.keys(r)),(e=>e));for(const o of a){const a=t[o],s=r[o],c=n[o];if(a==s)a&&(i[o]=a);else{const t=e.github.parseRepoId(a),n=e.github.parseRepoId(s);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 r=e.semver.strcmp(t.tag,n.tag)>0?t.tag:n.tag;i[o]=`github:${t.owner}/${t.project}#${r}`}else s==c?a&&(i[o]=a):s&&(i[o]=s)}}return i}},t.hasMergeConflictMarker=function(e){return e&&/^(<<<<<<<[^<]|>>>>>>>[^>])/m.test(e)},t.reconstructConfig=function(t,n,r,i){let a={},o=r.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)))||(i.config.files.filter((e=>o.indexOf(e)<0)).forEach((e=>{o.push(e),n[e]=i.files[e]})),e.Util.jsonCopyFrom(a,i.config.dependencies)),Object.keys(a).length||(a[e.appTarget.corepkg]="*"),{name:"",files:o,dependencies:a,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 r=`${t=t.replace(/\/$/,"")}/tag/${n}.json`;return e.Util.httpGetJsonAsync(r).then((n=>{const r=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:r[e.posters[0].user_id].username,cardType:"forumUrl"})))}))}}(e.discourse||(e.discourse={}))}(pxt||(pxt={})),function(e){!function(t){var n=pxtc.Util;let r,i={},a={};const o="\x3c!-- @CMD@ @ARGS@ --\x3e";let s={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",tutorialCodeValidation:"\x3c!-- tutorialCodeValidation --\x3e"};function c(e,t,n){return e.split(t).join(n)}function l(e){return e=c(e,"&","&"),e=c(e,"<","<"),e=c(e,">",">"),e=c(e,'"',"""),e=c(e,"'","'")}function u(e){return e?l(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=l,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 p=e=>`<div class='ui negative message'>${l(e)}</div>`;function f(e){let t=n.clone(i),r=n.clone(a),o=n.clone(s),c={},l={},d=e.params,f=e.theme;e.boxes=t,e.macros=r,e.settings=o,e.html=e.html.replace(/<aside\s+([^<>]+)>([^]*?)<\/aside>/g,((e,n,i)=>{let a=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),s=a["data-name"]||a.id;return s?(/box/.test(a.class)?t[s]=i:/aside/.test(a.class)?t[s]=`\x3c!-- BEGIN-ASIDE ${s} --\x3e${i}\x3c!-- END-ASIDE --\x3e`:/setting/.test(a.class)?o[s]=i:/menu/.test(a.class)?c[s]=i:/toc/.test(a.class)?l[s]=i:r[s]=i,`\x3c!-- macro ${s} --\x3e`):p("id or data-name missing on macro")}));let _=(e,t)=>{let n=c.item,r={NAME:e.name};if(e.subitems)n=c["toc-dropdown"]?c["toc-dropdown"]:0==t?c["top-dropdown"]:c["inner-dropdown"],r.ITEMS=e.subitems.map((e=>_(e,t+1))).join("\n");else{if(/^-+$/.test(e.name)&&(n=c.divider),e.path&&!/^(https?:|\/)/.test(e.path))return p("Invalid link: "+e.path);r.LINK=e.path}return g(n,r,["ITEMS"])},m=[{name:lf("Docs"),href:"/docs"}];const h=e.TOC||f.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)};h.forEach(v);let b=(t,n)=>{let r=l.item,i={NAME:t.name};return t.path&&!/^(https?:|\/)/.test(t.path)?p("Invalid link: "+t.path):(/^\//.test(t.path)&&e.versionPath&&(t.path=`/${e.versionPath}${t.path}`),i.LINK=t.path,y.indexOf(t)>=0?(i.ACTIVE="active",i.EXPANDED="true",m.push({name:t.name,href:t.path})):i.EXPANDED="false",t.subitems&&t.subitems.length>0?(r=l["toc-dropdown"]?""!==t.name?l["toc-dropdown"]:l["toc-dropdown-noLink"]:0==n?""!==t.name?l["top-dropdown"]:l["top-dropdown-noHeading"]:1==n?l["inner-dropdown"]:l["nested-dropdown"],i.ITEMS=t.subitems.map((e=>b(e,n+1))).join("\n")):/^-+$/.test(t.name)&&(r=l.divider),g(r,i,["ITEMS"]))};d.menu=(f.docMenu||[]).map((e=>_(e,0))).join("\n"),d.TOC=h.map((e=>b(e,0))).join("\n"),f.appStoreID&&(d.appstoremeta=`<meta name="apple-itunes-app" content="app-id=${n.htmlEscape(f.appStoreID)}"/>`);let x="";m.length>1&&(x=`\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=x,f.boardName&&(d.boardname=u(f.boardName)),f.boardNickname&&(d.boardnickname=u(f.boardNickname)),f.driveDisplayName&&(d.drivename=u(f.driveDisplayName)),f.homeUrl&&(d.homeurl=u(f.homeUrl)),d.targetid=f.id||"???",d.targetname=f.name||"Microsoft MakeCode",d.docsheader=f.docsHeader||"Documentation",d.orgtitle="MakeCode";const k=f.docsLogo&&n.htmlEscape(f.docsLogo),S=(f.organizationWideLogo||f.organizationLogo)&&n.htmlEscape(f.organizationWideLogo||f.organizationLogo),T=f.organizationLogo&&n.htmlEscape(f.organizationLogo);d.targetlogo=k?`<img aria-hidden="true" role="presentation" class="ui ${f.logoWide?"small":"mini"} image" src="${k}" />`:"",d.orglogo=S?`<img aria-hidden="true" role="presentation" class="ui image" src="${S}" />`:"",d.orglogomobile=T?`<img aria-hidden="true" role="presentation" class="ui image" src="${T}" />`:"";let C=e.ghEditURLs||[];if(C.length){let e='<p style="margin-top:1em">\n',t=lf("Edit this page on GitHub");for(let n of C)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 E=`\n <a href="#maincontent" class="ui item link" tabindex="0" role="menuitem">${lf("Skip to main content")}</a>\n `;d.accMenu=E;const D=lf("Print this page"),A=`\n <button id="printbtn" class="circular ui icon right floated button hideprint" title="${D}" aria-label="${D}">\n <i class="icon print"></i>\n </button>\n `;d.printBtn=A;const N=`\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=N;const w=["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=w[0],d.searchBar2=w[1];let I="";f.accentColor&&(I+=`\n.ui.accent { color: ${f.accentColor}; }\n.ui.inverted.accent { background: ${f.accentColor}; }\n`),d.targetstyle=I,d.tocclass=f.lightToc?"lighttoc":"inverted";for(let e of Object.keys(f)){let t=f[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 _(e){e.image=function(e,t,n){let r='<img class="ui image" src="'+e+'" alt="'+n+'"';return t&&(r+=' title="'+t+'"'),r+=' loading="lazy"',r+=this.options.xhtml?"/>":">",r},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 r=/(.*)#([\w\-]+)\s*$/.exec(e),i="";return r?(e=r[1],i=r[2]):i=n.toLowerCase().replace(/[^\w]+/g,"-"),e&&(e=e.replace(/@(fullscreen|unplugged|showdialog|showhint)/gi,"")),(e=e.trim()).match(/^\{([\s\S]+)\}$/)&&(e=e.substr(1,e.length-2)),`<h${t} id="${this.options.headerPrefix}${i}">${e}</h${t}>`}}function m(e,t){return e.replace(/<!--\s*@(ifn?def)\s+(\w+)\s*-->([^]*?)<!--\s*@endif\s*-->/g,((e,n,r,i)=>"ifdef"==n&&t[r]||"ifndef"==n&&!t[r]?`\x3c!-- ${n} ${r} --\x3e${i}\x3c!-- endif --\x3e`:`\x3c!-- ${n} ${r} endif --\x3e`))}function g(e,t,r=[]){return e?e.replace(/@(\w+)@/g,((e,i)=>{let a=n.lookup(t,i)||"";return a+="",r.indexOf(i)<0&&(a=u(a)),a})):""}t.prepTemplate=f,t.setupRenderer=_,t.renderConditionalMacros=m,t.renderMarkdown=function(e){let i=!0;e.pubinfo||(i=!1,e.pubinfo={});let a=e.pubinfo;if(e.theme||(e.theme={}),delete e.pubinfo.private,a.time){let e=parseInt(a.time);a.timems||(a.timems=1e3*e+""),a.humantime||(a.humantime=n.isoTime(e))}a.name&&(a.dirname=a.name.replace(/[^A-Za-z0-9_]/g,"-"),a.title=a.name),i&&(a.JSON=JSON.stringify(a,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,a),e.locale&&(o=y(o,e.locale).text);let s={html:o,theme:e.theme,filepath:e.filepath,versionPath:e.versionPath,ghEditURLs:e.ghEditURLs,params:a,TOC:e.TOC};f(s),r||(r=t.requireMarked());let c=new r.Renderer;_(c);const l=c.link;c.link=function(e,t,n){const r=new RegExp("^[/#]").test(e),i=r?"":"_blank";r&&s.versionPath&&(e=`/${s.versionPath}${e}`);return l.call(c,e,t,n).replace(/^<a /,`<a ${i?`target="${i}"`:""} rel="nofollow noopener" `)};let h=t.requireDOMSanitizer();r.setOptions({renderer:c,gfm:!0,tables:!0,breaks:!1,pedantic:!1,sanitize:!0,sanitizer:h,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,r)=>{let i=a[r];return!i&&e.throwOnError&&n.userError(`unknown macro ${r}`),i||"unknown macro"}));let b=r(v);b=b.replace(/<br\s*\/>/gi,"<br/>"),b=b.replace(/(<img [^>]* src=")\/docs\/static\/([^">]+)"/g,((e,t,n)=>t+"/static/"+n+'"'));let x="",k=0;function S(e,t,n){let r=n;return e<=k&&(r=x+r,x="",k=0),r}if(b=b.replace(/<h(\d)[^>]+>\s*([~@])?\s*(.*?)<\/h\d>/g,((t,r,i,o)=>{let c=/^(\w+)\s+(.*)/.exec(o),l=c?c[1]:o,d=c?c[2]:"";if(d=u(d),l=u(l),r=parseInt(r),i){if("@"==i){let t=n.lookup(s.settings,l);if(null!=t)a[l]=d;else if(t=n.lookup(s.macros,l),null==t)return e.throwOnError&&n.userError(`Unknown command: @${l}`),p(`Unknown command: @${l}`);return S(r,0,g(t,{ARGS:d,CMD:l},["ARGS","CMD"]))}{if(!l){let e=x;return x="",e}let t=n.lookup(s.boxes,l);if(t){let e=t.split("@BODY@"),n=S(r,0,e[0].replace("@ARGS@",d));x=e[1];let i=t.match(/data-[^>\s]+/gi);return i&&i.indexOf("data-inferred")>=0&&(k=r),n}return e.throwOnError&&n.userError(`Unknown box: ~ ${l}`),p(`Unknown box: ~ ${l}`)}}return S(r,0,t)})),x&&(b+=x),!a.title){let e=/<h1[^<>]*>([^<>]+)<\/h1>/.exec(b);e&&(a.title=u(e[1]))}if(!a.description){let e=/<p>([^]+?)<\/p>/.exec(b);e&&(a.description=u(e[1]))}const T=/<div class="ui embed mdvid"[^<>]+?data-placeholder="([^"]+)"[^>]*\/?>/i.exec(b)||/<img class="ui [^"]*image" src="([^"]+)"[^>]*\/?>/i.exec(b);T&&(a.cardLogo=u(T[1])),a.twitter=u(e.theme.twitter||"@msmakecode");let C={main:""};b=b.replace(/<!-- BEGIN-ASIDE (\S+) -->([^]*?)<!-- END-ASIDE -->/g,((e,t,r)=>{let i=n.lookup(C,t);return C[t]=(i||"")+r,"\x3c!-- aside --\x3e"})),b=b.replace(/\n<\/code>/g,"</code>"),C.main=b,b="";for(let e of Object.keys(C))b+=(E=e+"-container",D=C[e],g(s.boxes[E]||"@BODY@",{BODY:D},["BODY"]));var E,D;a.body=b,a.name=a.title||"";for(let t of Object.keys(e.theme)){let n=e.theme[t];"string"==typeof n&&(a["theme_"+t]=n)}return s.finish()},t.embedUrl=function(e,t,n,r){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 r=`${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="${r}" allowfullscreen="allowfullscreen" frameborder="0" sandbox="allow-scripts allow-same-origin"></iframe></div>`};const h={b:1,strong:1,em:1};function y(e,t){const r={};function i(e){let i=/^(\s*)([^]*?)(\s*)$/.exec(e),a=i[2].replace(/\s+/g," ");if(""==a||/^((IE=edge,.*|width=device-width.*|(https?:\/\/|\/)[\w@\/\.]+|@[\-\w]+@|\{[^\{\}]+\}|[^a-zA-Z]*|( )+)\s*)+$/.test(a))return null;let o=n.lookup(t,a);return o?a=o:r[a]="",i[1]+a+i[3]}function a(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 r=t.replace(/^\//,"").toLowerCase();return 1===h[r]?"&llt;"+t+n+"&ggt;":e})))).replace(/(<([\/\w]+)([^<>]*)>)([^<>]+)/g,((e,t,n,r,o)=>{if("script"==n||"style"==n)return a(e);let s=i(a(o));return null==s?a(e):t+s}))).replace(/(<[^<>]*)(content|placeholder|alt|title)="([^"]+)"/g,((e,t,n,r)=>null==i(r)?e:t+n+'="'+r.replace(/"/g,"''")+'"'))).replace(/^<start>/g,""),missing:r}}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 b(e,t){let n=0,r=[{level:0,id:"",title:"",start:n,text:"",children:[]}],i=(e=e.replace(/\r/g,"")).split(/\n/),a={};for(let e of i){let i=/^\s*(#+)\s*(.*?)(#(\S+)\s*)?$/.exec(e),o=null;if(t&&i)if(i[4])if(a[i[4]])i=null;else{o=v(t,i[4]);let e=t=>{t.id&&(a[t.id]=!0),t.children.forEach(e)};o&&e(o)}else i=null;if(i){let a={level:t?1:i[1].length,title:i[2].trim(),id:i[4]||"",start:n,text:"",children:[]};if(o){e="";for(let t=0;t<o.level;++t)e+="#";e+=" ",e+=a.title||o.title,e+=" #"+a.id}for(;r[r.length-1].level>=a.level;)r.pop();r[r.length-1].children.push(a),r.push(a)}r[r.length-1].text+=e+"\n",n++}return r[0]}t.translate=y,t.buildTOC=function(n){if(!n)return null;const r=e.docs.requireMarked(),i=t.requireDOMSanitizer(),a={renderer:new r.Renderer,gfm:!0,tables:!1,breaks:!1,pedantic:!1,sanitize:!0,sanitizer:i,smartLists:!1,smartypants:!1};let o={name:"dummy",subitems:[]},s=[];s.push(o);let c=r.lexer(n,a),l=!1;c.forEach((e=>{switch(e.type){case"heading":e.depth;break;case"list_start":break;case"list_item_start":case"loose_item_start":l=!0;let t={name:"",path:"",subitems:[]};return void s.push(t);case"text":let n=s[s.length-1];e.text.indexOf("[")>=0?e.text.replace(/\[(.*?)\]\((.*?)\)/i,(function(e,t,r){n.name=t,n.path=r.replace(".md","")})):l&&(n.name=e.text);break;case"list_item_end":case"loose_item_end":let r=s.pop();s[s.length-1].subitems.push(r)}l=!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 x=!1;function k(e,t){if(x||function(){function e(e,t,n){let r=k(e,t).trim();if(r!=(n=n.trim()))throw console.log(`*** Template:\n${e}\n*** Input:\n${t}\n*** Expected:\n${n}\n*** Output:\n${r}`),new Error("augment docs test fail")}x=!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",r="\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",i="\n# @extends\n### #ex\nFoo\n#### Example 1\nEx1\n#### Example 2x #ex2\nEx2\n## See Also These! #also\nMy links\n",a="\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,r),e(t,i,a)}(),!t)return e;let r=b(e,null),i=b(t,r),a={},o={};for(let e of i.children)n.assert(0==e.children.length),n.assert(!!e.id),a[e.id]=e.text;let s=e=>{e.id&&void 0!==a[e.id]&&(o[e.id]=!0,e.text=a[e.id],e.children=[]),e.children.forEach(s)};s(r);let c="",l=e=>{c+=e.text,e.children.forEach(l)};l(r);let u="",d=i.text.replace(/^\s*#+\s*@extends.*/gm,"").replace(/^\s*\n/gm,"");d.trim()&&(u+=d.trim()+"\n");for(let e of i.children)o[e.id]||(u+=e.text);return u&&(c+="## Couldn't apply replacement logic to:\n"+u),c}t.augmentDocs=k}(e.docs||(e.docs={}))}(pxt||(pxt={})),function(e){!function(e){e.el=function(e,t,n){const r=document.createElement(e);return t&&Object.keys(t).forEach((e=>r.setAttribute(e,t[e]+""))),function e(t){Array.isArray(t)?t.forEach((t=>e(t))):"string"==typeof t?r.appendChild(document.createTextNode(t)):t instanceof HTMLElement&&r.appendChild(t)}(n),r}}(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 r(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 i(t){const n=/```jres\s+((.|\s)+?)\s*```/i.exec(t);if(n){const t=n[1],r=JSON.parse(t);return{jres:t,ts:e.emitTilemapsFromJRes(r)}}}function a(t){const n=/```assetjson\s+((.|\s)+?)\s*```/i.exec(t);return n?e.tutorial.parseAssetJson(n[1]):{}}function o(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,r)=>{if("flags"==n)t[n]=r.split(",");else if("otherAction"===n){const e=r.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]=r;return""})),!!Object.keys(t).length&&t})).filter((e=>!!e)),(null==n?void 0:n.length)?n:void 0)}function s(t){if(!t)return[];const n=[];let r,i=!1,a="";return t.split(/\r?\n/).forEach((t=>{if(/^## /.test(t))r=t.substr(2).trim();else if(/^(### ~ |```)codecard$/.test(t))i=!0;else if(/^(### ~|```)$/.test(t)){if(i=!1,r&&a){const t=o(a);(null==t?void 0:t.length)?n.push({name:r,cards:t}):e.log("invalid gallery format")}a="",r=void 0}else i&&(a+=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=r,t.parseJResFromMarkdown=i,t.parseTemplateProjectJSON=a,t.parseExampleMarkdown=function(t,o){if(!o)return;const s=/```(blocks?|typescript|python|spy|sim)\s+((.|\s)+?)\s*```/i.exec(o);if(!s)return;const c=n(o),l=s[1],u=s[2],d=r(o),p=i(o),f={name:t,filesOverride:{[e.MAIN_BLOCKS]:'<xml xmlns="http://www.w3.org/1999/xhtml"></xml>',["python"===s[1]?e.MAIN_PY:e.MAIN_TS]:u},dependencies:c,features:d,snippetType:l,source:u};return f.filesOverride=Object.assign(Object.assign({},f.filesOverride),a(o)),p&&(f.filesOverride[e.TILEMAP_JRES]=p.jres,f.filesOverride[e.TILEMAP_CODE]=p.ts),f},t.parseCodeCards=o,t.parseCodeCardsHtml=function(t){let n,r=[];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,r=/^\s*(\w+)\s*:\s*(.*)$/.exec(t);if(r){const e=r[1];n[e]=r[2].trim(),"flags"===e&&(n[e]=n[e].split(/,\s*/))}}))):"HR"==e.tagName&&(n&&r.push(n),n=void 0)})),n&&r.push(n),0===r.length&&"CODE"===t.tagName&&(r=e.Util.jsonTryParse(t.textContent)),!!(null==r?void 0:r.length)&&r},t.parseGalleryMardown=s,t.loadGalleryAsync=function(t){return e.Cloud.markdownAsync(t).then((e=>s(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 r=t.charAt(e);"}"==r||"#"==r||"$"==r?(n+="}",n+=String.fromCharCode(32^r.charCodeAt(0))):n+=r}let r=0;t=n;for(let e=0;e<t.length;++e)r=r+t.charCodeAt(e)&255;return n="$"+t+"#"+("0"+r.toString(16)).slice(-2),e.U.stringToUint8Array(n)}decodeResp(e){let t="";for(let n=0;n<e.length;++n){let r=e[n];if("}"==r)++n,t+=String.fromCharCode(32^e.charCodeAt(n));else if("*"==r){++n;let r=e.charCodeAt(n)-29,i=t.charAt(t.length-1);for(;r-- >0;)t+=i}else{if("#"==r){return 2==e.slice(n+1,n+3).length?(this.dataBuf=e.slice(n+3),t):null}t+=r}}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 r=this.buildCmd(t);return this.q.enqueue("one",(()=>null===n?this.io.sendPacketAsync(r).then((()=>null)):new Promise((i=>{this.onResponse=r=>{this.onResponse=null,this.trace&&e.log(`GDB: '${t}' -> '${r}'`),void 0===n||n(r)||this.error(`Invalid GDB command response: '${t}' -> '${r}'`),i(r)},this.io.sendPacketAsync(r)}))))}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 r="";return this.q.enqueue("one",(()=>new Promise((i=>{this.onResponse=n=>{var a;"OK"!=n&&"O"==n[0]?r+=(a=n.slice(1),e.U.uint8ArrayToString(e.U.fromHex(a))):("OK"!=n&&(r+=" - "+n),this.onResponse=null,this.trace&&e.log(`Final GDB: '${t}' -> '${r}'`),i(r))},this.io.sendPacketAsync(n)}))))}write32Async(t,n){let r=new Uint8Array(4);return e.HF2.write32(r,0,n),this.writeMemAsync(t,r)}writeMemAsync(t,n){const r=this.pktSize/2-10;return e.U.assert(n.length<r),this.sendCmdOKAsync("M"+t.toString(16)+","+n.length.toString(16)+":"+e.U.toHex(n)).then((e=>{console.log(e)}))}readMemAsync(t,n){const r=this.pktSize/2-6;if(n>r){const i=new Uint8Array(n),a=o=>{const s=Math.min(n-o,r);return 0==s?Promise.resolve(i):this.readMemAsync(t+o,s).then((t=>(e.U.memcpy(i,o,t),a(o+s))))};return a(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,r)=>(n[t]=r,";"))),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,r;return!!t.forceProxy||!e.U.isNodeJS&&!(null===(r=null===(n=null==e?void 0:e.appTarget)||void 0===n?void 0:n.cloud)||void 0===r?void 0:r.noGithubProxy)}t.token=null,t.forceProxy=!1;const r={};function i(n){var r;return n.method=null!==(r=n.method)&&void 0!==r?r:"GET",function r(i){var a;const o=e.U.clone(n);t.token&&(o.headers||(o.headers={}),o.url==I?o.headers.Authorization=`bearer ${t.token}`:(o.url=e.BrowserUtils.cacheBustingUrl(o.url),o.headers.Authorization=`token ${t.token}`));return o.allowHttpErrors=null!==(a=o.allowHttpErrors)&&void 0!==a&&a,e.U.requestAsync(o).catch((n=>{if(e.tickEvent("github.error",{statusCode:n.statusCode}),t.handleGithubNetworkError){if(t.handleGithubNetworkError(o,n))return r(!1)}throw n}))}(t.token)}function a(e){return i({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 s(t){e.log(`github proxy error: ${t.message}`),e.debug(t)}t.isOrgAsync=function(e){return i({url:`https://api.github.com/orgs/${e}`,method:"GET",allowHttpErrors:!0}).then((e=>200==e.statusCode))};class c{constructor(){this.configs={},this.packages={}}proxyWithCdnLoadPackageAsync(t,n){const r=`${t}/${n}`;let i=this.packages[r];if(i)return e.debug(`github cache ${t}/${n}/text`),Promise.resolve(i);const a=C(t);return o(A(a.slug,n,a.fileName,"text")).then((e=>this.packages[r]={files:e}))}cacheConfig(t,n){const r=e.Package.parseAndValidConfig(n);return this.configs[t]=r,e.U.clone(r)}async loadConfigAsync(t,r){r||(r="master");const i=`${t}/${r}`;let a=this.configs[i];if(a)return e.debug(`github cache ${t}/${r}/config`),e.U.clone(a);if(n())try{const n=await this.proxyWithCdnLoadPackageAsync(t,r);return this.cacheConfig(i,n.files[e.CONFIG_NAME])}catch(e){s(e)}const o=await u(t,r,e.CONFIG_NAME);return this.cacheConfig(i,o)}async loadPackageAsync(t,r){if(r||(r="master"),n())try{return await this.proxyWithCdnLoadPackageAsync(t,r).then((t=>e.U.clone(t)))}catch(e){s(e)}return await this.githubLoadPackageAsync(t,r)}githubLoadPackageAsync(t,n){return g(t,n).then((r=>{const i=`${t}/${r}`;let a=this.packages[i];return a?(e.debug(`github cache ${t}/${n}/text`),Promise.resolve(e.U.clone(a))):(e.log(`Downloading ${t}/${n} -> ${r}`),u(t,r,e.CONFIG_NAME).then((n=>{const a={files:{}};a.files[e.CONFIG_NAME]=n;const o=JSON.parse(n);return e.U.promiseMapAll(e.allPkgFiles(o).slice(1),(e=>u(t,r,e).then((t=>{a.files[e]=t})))).then((()=>(this.packages[i]=a,e.U.clone(a))))})))}))}}function l(t,n,a){return i({url:"https://api.github.com/repos/"+A(t.slug,"contents",t.fileName,a+"?ref="+n),method:"GET"}).then((n=>{const i=n.json;return r[t.slug]=!0,i&&"base64"==i.encoding&&null!=i.content?atob(i.content):e.U.httpGetTextAsync(i.download_url)}))}function u(t,n,i){const a=C(t);return r[a.slug]?l(a,n,i):e.U.requestAsync({url:"https://raw.githubusercontent.com/"+A(a.slug,n,a.fileName,i),allowHttpErrors:!0}).then((e=>200==e.statusCode?e.text:l(a,n,i)))}function d(e,t,n,r){return i({url:/^https:/.test(e)?e:"https://api.github.com/repos/"+e,headers:n,method:r||"POST",data:t,successCodes:[200,201,202,204]}).then((e=>e.json))}function p(e,t){let n=1;for(;e.refs[t+n];)n++;return t+n}async function f(e,t,n){return await d(e+"/git/refs",{ref:"refs/heads/"+t,sha:n}),t}function _(r,i="tags",o,s){const c=C(r),l=(u=o,!!t.forceProxy||!(t.token&&!u)&&n());var u;let d=null;const p=l?e.U.httpGetJsonAsync(e.BrowserUtils.cacheBustingUrl(`${e.Cloud.apiRoot}gh/${c.slug}/refs${s?"?nocache=1":""}`)).then((t=>{let n=Object.keys(t.refs).filter((t=>e.U.startsWith(t,"refs/"+i+"/"))).map((e=>({ref:e,object:{sha:t.refs[e]}})));return d=t.refs.HEAD,n})):a(`https://api.github.com/repos/${c.slug}/git/refs/${i}/?per_page=100`);let f=e=>e.replace(/^refs\/[^\/]+\//,"");return p.then((t=>{t.sort(((t,n)=>e.semver.strcmp(f(t.ref),f(n.ref))));let n={};for(let e of t)n[f(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?a(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=C(e);return a(`https://api.github.com/repos/${n.slug}/git/refs/tags/${t}`).then(m,(e=>a(`https://api.github.com/repos/${n.slug}/git/refs/heads/${t}`).then(m)))}function h(e,n="master"){return t.db.loadConfigAsync(e,n)}function y(n,r){const i=C(n);return i?S(i,r)?(e.tickEvent("github.download.banned"),e.log("Github repo is banned"),Promise.resolve(void 0)):t.db.loadPackageAsync(i.fullName,i.tag).then((t=>{const i=w(r,n);if(i){const r=e.Package.parseAndValidConfig(t.files[e.CONFIG_NAME]);r&&(e.log(`auto-disable ${i.join(",")} due to targetconfig entry for ${n}`),r.disablesVariants=i,t.files[e.CONFIG_NAME]=e.Package.stringifyConfig(r))}return t})):(e.log("Unknown GitHub syntax"),Promise.resolve(void 0))}let v;function b(t){return e.Cloud.cdnApiUrl(`gh/${t.fullName}/icon`)}function x(e,t){var n;if(!e)return;const r={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 r.status=k(r,null==t?void 0:t.config),r}function k(e,t){return e?S(e,t)?v.Banned:function(e,t){return!!function(e,t){return!(!e||!t)&&!!(e.owner&&t.approvedOrgs&&t.approvedOrgs.some((t=>t.toLowerCase()==e.owner.toLowerCase())))}(e,t)||!(!e||!t)&&!!(e.fullName&&t.approvedRepos&&t.approvedRepos.some((t=>t.toLowerCase()==e.fullName.toLowerCase())))}(e,t)?v.Approved:v.Unknown:v.Unknown}function S(e,t){return!!function(e,t){return!(!t||e&&e.owner&&(!t.bannedOrgs||!t.bannedOrgs.some((t=>t.toLowerCase()==e.owner.toLowerCase()))))}(e,t)||!!t&&(!e||!e.fullName||!(!t.bannedRepos||!t.bannedRepos.some((t=>t.toLowerCase()==e.fullName.toLowerCase()))))}async function T(t,r){const i=C(t);if(!i)return;const c=k(i,r);if(c==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)}))}(i,c)}catch(e){s(e)}return x(await a("https://api.github.com/repos/"+i.slug),{config:r,fullName:i.fullName,fileName:i.fileName,tag:i.tag})}function C(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 r=n[1],i=n[2];let a=n[4];const o=n[6],s=a&&/^tree\/([^\/]+\/)/.exec(a);return s&&(a=a.slice(s[0].length)),{owner:r,project:i,slug:A(r,i),fullName:A(r,i,a),tag:o,fileName:a}}function E(e){return!!e&&"github:"==e.slice(0,7)}function D(e){return e?"github:"+e.fullName.toLowerCase()+"#"+(e.tag||"master"):void 0}function A(...e){return e.filter((e=>!!e)).join("/")}function N(t,n){if(!t||!t.upgrades)return null;const r=C(n);return r?e.U.lookup(t.upgrades,r.fullName.toLowerCase()):null}function w(e,t){const n=N(e,t),r=/^dv:(.*)/.exec(n);if(r){const e=r[1].split(/,/);return e.some((e=>!/^\w+$/.test(e)))?null:e}return null}t.MemoryGithubDb=c,t.downloadTextAsync=u,t.db=new c,t.authenticatedUserAsync=function(){return t.token?a("https://api.github.com/user"):Promise.resolve(void 0)},t.getCommitsAsync=function(e,t){return a("https://api.github.com/repos/"+C(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 a("https://api.github.com/repos/"+C(e).slug+"/git/commits/"+t).then((e=>a(e.tree.url+"?recursive=1").then((t=>(e.tree=t,e)))))},t.createObjectAsync=function(e,t,n){return d(C(e).slug+"/git/"+t+"s",n).then((e=>e.sha))},t.postCommitComment=function(e,t,n,r,i){return d(`${C(e).slug}/commits/${t}/comments`,{body:n,path:r,position:i}).then((e=>e.id))},t.fastForwardAsync=async function(e,t,n){const r=C(e);return 200==(await i({url:`https://api.github.com/repos/${r.slug}/git/refs/heads/${t}`,method:"PATCH",allowHttpErrors:!0,data:{sha:n,force:!1}})).statusCode},t.putFileAsync=async function(t,n,r){const a=C(t);await i({url:`https://api.github.com/repos/${e.github.join(a.slug,"contents",a.fileName,n)}`,method:"PUT",allowHttpErrors:!0,data:{message:lf("Initialize empty repo"),content:btoa(e.U.toUTF8(r)),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,r,i){const a=await d(e+"/pulls",{title:r,body:i||lf("Automatically created from MakeCode."),head:n,base:t,maintainer_can_modify:!0});return null==a?void 0:a.html_url},t.mergeAsync=function(t,n,r,a){return i({url:`https://api.github.com/repos/${C(t).slug}/merges`,method:"POST",successCodes:[201,204,409],data:{base:n,head:r,commit_message:a}}).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 a("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 p(await _(e,"heads"),t)},t.createNewBranchAsync=f,t.forkRepoAsync=async function(t,n,r="pr-"){const i=C(t),a=x(await d(`${i.slug}/forks`,{}),{fullName:i.fullName,fileName:i.fileName}),o=Date.now()+3e5;let s=null;for(;!s&&Date.now()<o;){await e.U.delay(1e3);try{s=await _(a.slug,"heads")}catch(e){}}if(!s)throw new Error(lf("Timeout waiting for fork"));const c=p(s,r);return await f(a.slug,c,n),a.fullName+"#"+c},t.listRefsAsync=function(e,t="tags",n,r){return _(e,t,n,r).then((e=>Object.keys(e.refs)))},t.listRefsExtAsync=_,t.pkgConfigAsync=h,t.downloadPackageAsync=y,t.downloadLatestPackageAsync=async function(t){const n=await e.packagesConfigAsync(),r=await e.github.latestVersionAsync(t.slug,n),i=`${t.fullName}#${r}`;return await e.github.downloadPackageAsync(i,n),{version:`github:${i}`,config:await h(t.fullName,r)}},t.cacheProjectDependenciesAsync=async function(t){var n;const r=null===(n=Object.keys(t.dependencies))||void 0===n?void 0:n.filter((e=>E(t.dependencies[e])));if(r.length){const n=await e.packagesConfigAsync();await Promise.all(r.map((async e=>{const r=t.dependencies[e];if(!await y(r,n))throw new Error(lf("Cannot load extension {0} from {1}",e,r))})))}},function(e){e[e.Unknown=0]="Unknown",e[e.Approved=1]="Approved",e[e.Banned=2]="Banned"}(v=t.GitRepoStatus||(t.GitRepoStatus={})),t.listUserReposAsync=function(){return P('{\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: "master:pxt.json") {\n ... on Blob {\n text\n }\n }\n readme: object(expression: "master: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),r=t.readme&&t.readme.text;return!!n&&(n.supportedTargets?n.supportedTargets.indexOf(e.appTarget.id)>-1:r&&r.indexOf("PXT/"+e.appTarget.id)>-1)})).map((e=>x(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=>x(e)))},t.enablePagesAsync=async function(t){const n=C(t);let r;try{const e=await a(`https://api.github.com/repos/${n.slug}/pages`);e&&(r=e.html_url)}catch(e){}if(!r)try{r=(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(r){const n=await a(`https://api.github.com/repos/${t}`);if(n&&!n.homepage)try{await d(`https://api.github.com/repos/${t}`,{homepage:r},void 0,"PATCH")}catch(t){e.tickEvent("github.homepage.error")}}},t.repoIconUrl=function(e){if(e.status==v.Approved)return b(e)},t.mkRepoIconUrl=b,t.repoStatus=k,t.repoAsync=T,t.searchAsync=function(t,n){if(!n)return Promise.resolve([]);let r=t.split("|").map(C).filter((e=>!!e));return r.length>0?Promise.all(r.map((e=>T(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=>x(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=C,t.toGithubDependencyPath=function(e,t){let n="github:"+e;return t&&(n+="#"+t),n},t.isGithubId=E,t.stringifyRepo=D,t.normalizeRepoId=function(e){const t=C(e);if(t)return t.tag=t.tag||"master",D(t)},t.join=A,t.upgradedPackageReference=function(t,n){const r=N(t,n);if(!r)return null;const i=/^min:(.*)/.exec(r),a=i&&e.semver.tryParse(i[1]);if(a){const t=C(n),r=e.semver.tryParse(t.tag);return r&&e.semver.cmp(r,a)<0?(t.tag=i[1],e.debug(`upgrading ${n} to ${i[1]}`),D(t)):(r||e.log(`not upgrading ${n} - cannot parse version`),null)}return w(t,n)||e.log(`invalid upgrade rule: ${n} -> ${r}`),n},t.upgradedPackageId=function(e,t){const n=w(e,t);return n?t+"?dv="+n.join(","):t},t.latestVersionAsync=function(t,n,r,i){const a=C(t);return a?T(a.slug,n).then((t=>{if(t)return _(t.slug,"tags",r,i).then((r=>{let i=Object.keys(r.refs);i=e.semver.sortLatestTags(i);const o=e.appTarget.versions&&e.semver.tryParse(e.appTarget.versions.target);if(o&&n.releases&&n.releases["v"+o.major]){const r=n.releases["v"+o.major].map((t=>e.github.parseRepoId(t))).filter((e=>e&&e.fullName.toLowerCase()==a.fullName.toLowerCase()))[0];if(r){if(i.some((e=>e==r.tag)))return e.debug(`approved release ${r.fullName}#${r.tag} for v${o.major}`),Promise.resolve(r.tag);e.reportError("packages",`approved release ${r.fullName}#${r.tag} for v${o.major} not found anymore`,{repo:t.fullName})}}return i[0]?Promise.resolve(i[0]):r.head||g(t.slug,t.defaultBranch)}))})):Promise.resolve(null)},t.resolveMonoRepoVersions=function(n){n=e.Util.clone(n);const r={};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:i}=t;let a=r[i.slug];a||(a=r[i.slug]={tag:i.tag,deps:[]}),a.deps.push(t),e.semver.strcmp(a.tag,i.tag)<0&&(e.debug(`dep: resolve later monorepo tag to ${e.github.stringifyRepo(i)}`),a.tag=i.tag)})),e.U.values(r).forEach((t=>t.deps.forEach((r=>{r.ghid.tag!==t.tag&&(e.debug(`dep: ${e.github.stringifyRepo(r.ghid)} -> ${t.tag}`),r.ghid.tag=t.tag,n[r.id]=e.github.stringifyRepo(r.ghid))})))),n},t.GIT_JSON=".git.json";const I="https://api.github.com/graphql";function P(e){const t=JSON.stringify({query:e});return d(I,t)}t.lookupFile=function(e,t,n){if(!t)return null;const r=A(e.fileName,n);return t.tree.tree.find((e=>e.path==r))},t.ghGraphQLQueryAsync=P,t.findPRNumberforBranchAsync=function(e,t){const n=C(e);return P(`\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 a(`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 r(e,t,n){e[t+0]=n>>0&255,e[t+1]=n>>8&255}function i(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function a(e,t){return e[t]|e[t+1]<<8}function o(e){let t=new Uint8Array(4*e.length);for(let r=0;r<e.length;++r)n(t,4*r,e[r]);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=r,t.read32=i,t.read16=a,t.encodeU32LE=o,t.decodeU32LE=function(e){let t=[];for(let n=0;n<e.length;n+=4)t.push(i(e,n));return t};let s=!1;function c(t){s?e.log("HF2: "+t):e.debug("HF2: "+t)}t.enableLog=function(){s=!0};class l{constructor(n){var r;this.io=n,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===(r=e.appTarget.appTheme.downloadDialogTheme)||void 0===r?void 0:r.deviceIcon)||"usb",this.msgs=new e.U.PromiseBuffer,this.eventHandlers={},this.jacdacAvailable=!1,this.onSerial=(e,t)=>{},this.onCustomEvent=(e,t)=>{};let a=[];n.onDeviceConnectionChanged=e=>this.disconnectAsync().then((()=>e&&this.reconnectAsync())),n.onSerial=(e,t)=>this.onSerial(e,t),n.onData=r=>{let i=r[0]&t.HF2_FLAG_MASK,o=63&r[0],s=new Uint8Array(o);if(e.U.memcpy(s,0,r,1,o),i&t.HF2_FLAG_SERIAL_OUT)this.onSerial(s,i==t.HF2_FLAG_SERIAL_ERR);else if(a.push(s),i!=t.HF2_FLAG_CMDPKT_BODY){e.U.assert(i==t.HF2_FLAG_CMDPKT_LAST);let r=0;for(let e of a)r+=e.length;let o=new Uint8Array(r),s=0;for(let t of a)e.U.memcpy(o,s,t),s+=t.length;a=[],o[2]&t.HF2_STATUS_EVENT?n.onEvent(o):this.msgs.push(o)}},n.onEvent=t=>{let n=i(t,0),r=e.U.lookup(this.eventHandlers,n+"");r?r(t.slice(4)):c("unhandled event: "+n.toString(16))},n.onError=e=>{c("recv error: "+e.message),this.autoReconnect&&(this.autoReconnect=!1,this.reconnectAsync().then((()=>{this.autoReconnect=!0}),(e=>{c("reconnect error: "+e.message)})))},this.onEvent(t.HF2_EV_JDS_PACKET,(e=>{this.onCustomEvent(t.CUSTOM_EV_JACDAC,e)}))}resetState(){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,r){e.U.assert(!!(n&t.HF2_EV_MASK)),this.eventHandlers[n+""]=r}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"))}reconnectAsync(){return this.resetState(),c(`reconnect raw=${this.rawMode}`),this.io.reconnectAsync().then((()=>this.initAsync())).catch((t=>{if(this.reconnectTries<5)return this.reconnectTries++,c(`error ${t.message}; reconnecting attempt #${this.reconnectTries}`),e.U.delay(500).then((()=>this.reconnectAsync()));throw t}))}disconnectAsync(){return c("disconnect"),this.io.disconnectAsync()}error(e){return this.io.error(e)}talkAsync(i,o){if(this.io.talksAsync)return this.io.talksAsync([{cmd:i,data:o}]).then((e=>e[0]));let s=8;o&&(s+=o.length);let l=new Uint8Array(s),u=65535&++this.cmdSeq;n(l,0,i),r(l,4,u),r(l,6,0),o&&e.U.memcpy(l,8,o,0,o.length);let d=0,p=()=>this.msgs.shiftAsync(1e3).then((e=>{if(a(e,0)!=u){if(d<3)return d++,c(`message out of sync, (${u} vs ${a(e,0)}); will re-try`),p();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(l).then(p)}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 r=new Uint8Array(64),i=a=>{let o=e.length-a;if(o<=0)return Promise.resolve();o>63?(o=63,r[0]=t.HF2_FLAG_CMDPKT_BODY):r[0]=t.HF2_FLAG_CMDPKT_LAST,n&&(r[0]=1==n?t.HF2_FLAG_SERIAL_OUT:t.HF2_FLAG_SERIAL_ERR),r[0]|=o;for(let t=0;t<o;++t)r[t+1]=e[a+t];return this.io.sendPacketAsync(r).then((()=>i(a+o)))};return this.lock.enqueue("out",(()=>i(0)))}switchToBootloaderAsync(){return this.bootloaderMode?Promise.resolve():(c("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){c("reflash"),e.U.assert(e.appTarget.compile.useUF2);const n=t.outfiles[pxtc.BINARY_UF2],r=pxtc.UF2.parseFile(e.Util.stringToUint8Array(atob(n)));return this.flashing=!0,this.io.reconnectAsync().then((()=>this.flashAsync(r))).then((()=>e.U.delay(100))).finally((()=>this.flashing=!1)).then((()=>this.reconnectAsync()))}writeWordsAsync(n,r){return e.U.assert(r.length<=64),this.talkAsync(t.HF2_CMD_WRITE_WORDS,o([n,r.length].concat(r))).then((()=>{}))}readWordsAsync(r,i){let a=new Uint8Array(8);return n(a,0,r),n(a,4,i),e.U.assert(i<=64),this.talkAsync(t.HF2_CMD_READ_WORDS,a)}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(r){let i=Date.now(),a=0,o=i=>{if(i>=r.length)return Promise.resolve();let a=r[i],s=new Uint8Array(4+a.payloadSize);return n(s,0,a.targetAddr),e.U.memcpy(s,4,a.data,0,a.payloadSize),this.talkAsync(t.HF2_CMD_WRITE_FLASH_PAGE,s).then((()=>o(i+1)))};return this.switchToBootloaderAsync().then((()=>{let e=256*r.length;return c(`Starting flash (${Math.round(e/1024)}kB).`),a=Date.now(),this.pageSize>16384?r:u(r,((e,t)=>this.readWordsAsync(e,t)))})).then((e=>{if(e.length!=r.length){let t=256*(r=e).length;c(`Performing partial flash (${Math.round(t/1024)}kB).`)}})).then((()=>o(0))).then((()=>{let e=Date.now(),t=e-i,n=e-a;c(`Flashing done at ${Math.round(256*r.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?Promise.resolve():Promise.resolve().then((()=>this.talkAsync(t.HF2_CMD_BININFO))).then((e=>(this.bootloaderMode=e[0]==t.HF2_MODE_BOOTLOADER,this.pageSize=i(e,4),this.flashSize=i(e,8)*this.pageSize,this.maxMsgSize=i(e,12),this.familyID=i(e,16),c(`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,r)=>(n[t.replace(/-/g,"")]=r,""))),this.info=n;let r=/v(\d\S+)(\s+(\S+))?/.exec(this.info.Header);this.info.Parsed=r?{Version:r[1],Features:r[3]||""}:{Version:"?",Features:""},c(`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}))}}function u(t,n){if(!e.appTarget.compile.flashChecksumAddr)return Promise.resolve(t);let r=pxtc.UF2.readBytes(t,e.appTarget.compile.flashChecksumAddr,48),a=pxtc.parseChecksumBlock(r);return a?function(t){return e.appTarget.compile.flashChecksumAddr?t(e.appTarget.compile.flashChecksumAddr,12).then((n=>{let r=pxtc.parseChecksumBlock(n);return r?t(r.endMarkerPos,1).then((t=>i(t,0)!=r.endMarker?(e.log("end-marker mismatch"),null):r)):null})):Promise.resolve(null)}(n).then((e=>{if(!e)return t;let n=e.regions.filter((e=>a.regions.some((t=>e.checksum==t.checksum&&e.length==t.length&&e.start==t.start))));if(0==n.length)return t;c("skipping flash at: "+n.map((e=>`${pxtc.assembler.tohex(e.start)} (${e.length/1024}kB)`)).join(", "));let r=e=>n.some((t=>t.start<=e&&e<t.start+t.length));return t.filter((e=>!(r(e.targetAddr)&&r(e.targetAddr+e.payloadSize-1))))})):Promise.resolve(t)}t.Wrapper=l,t.mkHF2PacketIOWrapper=function(t){return e.debug("packetio: wrapper hf2"),new l(t)},t.onlyChangedBlocksAsync=u}(e.HF2||(e.HF2={}))}(pxt||(pxt={})),function(e){!function(t){var n=e.Util,r=e.HF2;const i=r.read32;let a,o,s,c,l,u,d,p,f=!1;function _(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 r=new Uint8Array(t);return e-=d.start,n.memcpy(r,0,d.buf,e,t),Promise.resolve(r)}let r=p.maxMsgSize-32;if(t>r){let i=[];for(;t>0;){let n=Math.min(r,t);i.push(g(e,n)),t-=n,e+=n}return Promise.all(i).then(n.uint8ArrayConcat)}return p.readWordsAsync(e,Math.ceil(t/4)).then((e=>e.length>t?e.slice(0,t):e))}function h(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 i=0;return g(t.ptr,56).then((a=>{i=r.read16(a,2);let o=a.length;return i==e.BuiltInType.BoxedString||i==e.BuiltInType.BoxedBuffer?o=r.read16(a,4)+6:i==e.BuiltInType.BoxedNumber&&(o=12),o>a.length?g(t.ptr+a.length,o-a.length).then((e=>n.uint8ArrayConcat([a,e]))):o<a.length?a.slice(0,o):a})).then((t=>i==e.BuiltInType.BoxedString?n.uint8ArrayToString(t.slice(6)):i==e.BuiltInType.BoxedBuffer?{type:"buffer",data:t.slice(6)}:i==e.BuiltInType.BoxedNumber?new Float64Array(t.buffer.slice(4))[0]:{type:"unknown",tag:i,refcnt:r.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(h(e[n]).then((t=>{e[n]=t})));return Promise.all(t).then((()=>{}))}function v(e){let t=a.breakpoints,n=t[0],r=1/0;for(let i of t){let t=e-i.binAddr;t>=0&&t<r&&(r=t,n=i)}return n}function b(e){if(f)return Promise.resolve();let i;return f=!0,T().then((t=>{let o=r.decodeU32LE(e)[0],c={};for(let e of a.procDebugInfo[0].locals){let i=t.globals,a=(()=>{switch(e.type){case"uint32":return r.read32(i,e.index);case"int32":return 0|r.read32(i,e.index);case"uint16":return r.read16(i,e.index);case"int16":return r.read16(i,e.index)<<16>>16;case"uint8":return i[e.index];case"int8":return i[e.index]<<24>>24;default:return null}})();null===a&&(n.assert(0==(3&e.index)),a=m(r.read32(i,e.index))),c[e.name]=a}return l=v(o),i={type:"debugger",subtype:"breakpoint",breakpointId:l.id,globals:c,stackframes:[]},s(),p.talkAsync(1888490768)})).then((e=>{!function(e,t){let r=l.binAddr,i=0,o=a.procDebugInfo.filter((e=>e.codeStartLoc<=r&&r<=e.codeEndLoc))[0];for(;o&&o!=a.procDebugInfo[0];){let a=v(r),s=n.clone(a);s.functionName=o.name,s.argumentNames=o.args&&o.args.map((e=>e.name)),t.stackframes.push({locals:{},funcInfo:s,breakpointId:a.id});let c=t.stackframes[t.stackframes.length-1],l=0;for(let t of o.locals)n.assert(t.index==l++),c.locals[t.name]=m(e[i++]);r=2147483646&e[i++];let d=u[r+""];for(let t of o.args)c.locals[t.name]=m(e[i+(o.args.length-1-t.index)]);if(!d)break;o=d.from,i+=d.stack-o.localsMark}}(r.decodeU32LE(e),i);let t=[i.globals].concat(i.stackframes.map((e=>e.locals)));return n.promiseMapAll(t,y)})).then((()=>t.postMessage(i)))}function x(){f=!1,o=new Promise(((e,t)=>{s=e}))}function k(e=!1){return Promise.resolve().then((()=>p.talkAsync(665147697,r.encodeU32LE([e?1:3])))).then(x)}function S(){return o||(o=Promise.resolve()),o}function T(){return(c?Promise.resolve(c):p.talkAsync(1409050336).then((e=>c={numGlobals:i(e,0),globalsPtr:i(e,4)}))).then((e=>p.readWordsAsync(e.globalsPtr,e.numGlobals))).then((e=>({staticState:c,globals:e})))}t.taggedUndefined=0,t.taggedNull=_(1),t.taggedFalse=_(2),t.taggedTrue=_(16),t.postMessage=e=>console.log(e),t.decodeValue=m,t.heapExpandAsync=h,t.heapExpandMapAsync=y,t.startDebugAsync=function(e,t){return p=t,p.onEvent(915601917,b),(f=!1,a=null,c=null,Promise.resolve()).then((()=>{a=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=a.outfiles[pxtc.BINARY_UF2],t=n.stringToUint8Array(atob(e));return d=pxtc.UF2.toBin(t),p.reflashAsync(a).then((()=>p.reconnectAsync()))})).then((()=>p.talkAsync(287358355).catch((e=>{})))).then((()=>n.delay(200))).then((()=>p.reconnectAsync())).then(x).then(S)},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":k(t)}},t.resumeAsync=k,t.waitForHaltAsync=S,t.getHwStateAsync=T}(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)),r=n.charCodeAt(0),i=n.charCodeAt(1),a=n.charCodeAt(2);if(135===r&&(r=224|n.charCodeAt(1),i=n.charCodeAt(2)|n.charCodeAt(3)<<8,a=n.charCodeAt(4)|n.charCodeAt(5)<<8,n=n.slice(4)),225!=r&&228!=r)return null;if(!this.palette){let t=e.appTarget.runtime.palette.map((function(e){const t=parseInt(e.replace(/#/,""),16);return[t>>0&255,t>>8&255,t>>16&255,255]}));t[0][3]=0,this.palette=new Uint8Array(4*t.length);for(let e=0;e<t.length;++e)this.palette[4*e+0]=t[e][0],this.palette[4*e+1]=t[e][1],this.palette[4*e+2]=t[e][2],this.palette[4*e+3]=t[e][3]}if(225==r)return this.genMonochrome(n,i,a);const o=(e.BrowserUtils.isEdge()||e.BrowserUtils.isIE())&&i<100&&a<100?3:1;return this.genColor(n,i,a,o)}genMonochrome(t,n,r){let i=n+3&-4,a=54+this.palette.length,o=a+i*r,s=new Uint8Array(o);s[0]=66,s[1]=77,e.HF2.write32(s,2,o),e.HF2.write32(s,10,a),e.HF2.write32(s,14,40),e.HF2.write32(s,18,n),e.HF2.write32(s,22,-r),e.HF2.write16(s,26,1),e.HF2.write16(s,28,8),e.HF2.write32(s,38,2835),e.HF2.write32(s,42,2835),e.HF2.write32(s,46,this.palette.length>>2),s.set(this.palette,54);let c=4,l=a,u=1,d=t.charCodeAt(c++);for(let e=0;e<n;++e){l=a+e;for(let e=0;e<r;++e)s[l]=d&u?1:0,l+=i,u<<=1,256==u&&(u=1,d=t.charCodeAt(c++))}return"data:image/bmp;base64,"+btoa(e.U.uint8ArrayToString(s))}genColor(t,n,r,i){const a=n*(i=Math.max(1,0|i)),o=r*i;let s=a<<2,c=138,l=c+s*o,u=new Uint8Array(l);u[0]=66,u[1]=77,e.HF2.write32(u,2,l),e.HF2.write32(u,10,c),e.HF2.write32(u,14,124),e.HF2.write32(u,18,a),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,p=c,f=!0;for(let e=0;e<a;e++){let n=!1;p=c+(e<<2);let a=d,l=t.charCodeAt(d++),_=n?(l>>4&15)<<2:(15&l)<<2;for(let e=0;e<o;e++)l&&(f=!1),u[p]=this.palette[_],u[p+1]=this.palette[_+1],u[p+2]=this.palette[_+2],u[p+3]=this.palette[_+3],p+=s,e%i==i-1&&(n&&(l=t.charCodeAt(d++)),n=!n,_=n?(l>>4&15)<<2:(15&l)<<2);if(f&&(u[141]=1),e%i==i-1)for(r%2||--d;3&d;)d++;else d=a}return"data:image/bmp;base64,"+btoa(e.U.uint8ArrayToString(u))}}}(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("Blocks preview")}\n\n${lf("This image shows the blocks code from the last commit in master.")}\n${lf("This image may take a few minutes to refresh.")}\n\n\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_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 },\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 }\n}',".github/workflows/makecode.yml":"name: MakeCode\n\non: [push]\n\njobs:\n build:\n\n runs-on: ubuntu-latest\n\n strategy:\n matrix:\n node-version: [14.x]\n\n steps:\n - uses: actions/checkout@v1\n - name: Use Node.js ${{ matrix.node-version }}\n uses: actions/setup-node@v1\n with:\n node-version: ${{ matrix.node-version }}\n - name: npm install\n run: |\n npm install -g pxt\n pxt target @TARGET@\n - name: build\n run: |\n pxt install\n pxt build --cloud\n env:\n CI: true\n",".github/workflows/cfg-check.yml":"name: Check pxt.json\n\non:\n push:\n branches:\n - 'master'\n - 'main'\n\njobs:\n check-cfg:\n runs-on: ubuntu-latest\n strategy:\n matrix:\n node-version: [14.x]\n steps:\n - uses: actions/checkout@v2\n - name: Use Node.js ${{ matrix.node-version }}\n uses: actions/setup-node@v1\n with:\n node-version: ${{ matrix.node-version }}\n - name: npm install\n run: |\n npm install -g pxt\n pxt target @TARGET@\n - name: Checkout current state\n run: |\n git checkout -- .\n git clean -fd\n - name: Fix files listed in config if necessary\n run: pxt checkpkgcfg\n - name: Create Pull Request\n uses: peter-evans/create-pull-request@v3\n continue-on-error: true\n with:\n title: 'Removing missing files from pxt.json'\n commit-message: 'Removing missing files from pxt.json'\n delete-branch: true\n",".vscode/tasks.json":'\n// A task runner that calls the MakeCode (PXT) compiler\n{\n "version": "2.0.0",\n "tasks": [{\n "label": "pxt deploy",\n "type": "shell",\n "command": "pxt deploy --local",\n "group": "build",\n "problemMatcher": [ "$tsc" ]\n }, {\n "label": "pxt build",\n "type": "shell",\n "command": "pxt build --local",\n "group": "build",\n "problemMatcher": [ "$tsc" ]\n }, {\n "label": "pxt install",\n "type": "shell",\n "command": "pxt install",\n "group": "build",\n "problemMatcher": [ "$tsc" ]\n }, {\n "label": "pxt clean",\n "type": "shell",\n "command": "pxt clean",\n "group": "test",\n "problemMatcher": [ "$tsc" ]\n }]\n}\n'},n=r();return n&&Object.keys(n).forEach((t=>e[t]=n[t])),e}function r(){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=r,t.TEMPLATE_PRJ="template",t.packageFiles=function(t){const r=e.appTarget.blocksprj||e.appTarget.tsprj,i=e.U.clone(r.config);delete i.installedVersion,delete i.additionalFilePath,delete i.additionalFilePaths,i.preferredEditor=i.files.find((e=>/\.blocks$/.test(e)))?e.BLOCKS_PROJECT_NAME:e.JAVASCRIPT_PROJECT_NAME,i.name=t,i.public=!0,i.version||(i.version="0.0.0");const a={},o=n();for(const e in o)a[e]=o[e];for(const e in r.files)"README.md"!=e&&(a[e]=r.files[e]);const s=Object.keys(a).filter((e=>/\.(blocks|md|ts|asm|cpp|h|py)$/.test(e)));return i.files=s.filter((e=>!/test/.test(e))),i.testFiles=s.filter((e=>/test/.test(e))),i.supportedTargets=[e.appTarget.id],a[e.CONFIG_NAME]=e.Package.stringifyConfig(i),a},t.packageFilesFixup=function(t,n){const r=JSON.parse(t[e.CONFIG_NAME]);n&&e.Util.jsonMergeFrom(r,n),e.webConfig&&(Object.keys(e.webConfig).forEach((t=>r[t.toLowerCase()]=e.webConfig[t])),r.platform=e.appTarget.platformid||e.appTarget.id,r.target=e.appTarget.id,r.docs=e.appTarget.appTheme.homeUrl||"./",r.homeurl=e.appTarget.appTheme.homeUrl||"???"),e.U.iterMap(t,((e,n)=>{n=n.replace(/@([A-Z]+)@/g,((e,t)=>r[t.toLowerCase()]||"")),t[e]=n}))}}(e.template||(e.template={}))}(pxt||(pxt={})),function(e){!function(t){let n,r;!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"}(r=t.GlueMode||(t.GlueMode={}));const i=["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 a(e){return"`"+e.replace(/[\\`${}]/g,(e=>"\\"+e))+"`"}function o(e){return e.length>20&&/\n/.test(e)?a(e):JSON.stringify(e)}function s(e,t,n){return{type:e,op:t,children:n}}function c(){return s(n.NewLine,"",[])}function l(e,t){return s(n.Prefix,e,t)}function u(e,t,r){return s(n.Infix,t,null==e?[r]:[e,r])}function d(e){return l(e,[])}function p(e){return s(n.Block,"",e)}function f(e){return l("",e)}function _(e,t=!1){const n=[];for(const r of e)t?(n.length>0&&n.push(d(",")),n.push(c())):n.length>0&&n.push(d(", ")),n.push(r);return t&&n.push(c()),f(n)}let m;t.backtickLit=a,t.stringLit=o,t.mkNode=s,t.mkNewLine=c,t.mkPrefix=l,t.mkPostfix=function(e,t){return s(n.Postfix,t,e)},t.mkInfix=u,t.mkText=d,t.mkBlock=p,t.mkGroup=f,t.mkStmt=function(...e){let t=e[e.length-1];return t&&t.type==n.Block||e.push(c()),f(e)},t.mkCommaSep=_,function(t){function n(e,t,n=!1,r=!1){return f(r?[u(t[0],".",d(e)),d("("),_(t.slice(1),n),d(")")]:[d(e),d("("),_(t,n),d(")")])}function r(e,t,r,i){return n(e+"."+t,r,i)}function i(t,n){return e.U.assert(2==n.length),u(n[0],t,n[1])}t.mkArrayLiteral=function(e,t){return f([d("["),_(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 f([u(t,".",d(e))])},t.mkCall=n,t.stdCall=function(e,t,r){return n(e,t,r)},t.extensionCall=function(e,t,r){return n(e,t,r,!0)},t.namespaceCall=r,t.mathCall=function(e,t){return r("Math",e,t,!1)},t.mkGlobalRef=function(e){return d(e)},t.mkSimpleCall=i,t.mkWhile=function(e,t){return f([d("while ("),e,d(")"),p(t)])},t.mkComment=function(e){return d("// "+e)},t.mkMultiComment=function(e){let t=[d("/**"),c()];return e.split("\n").forEach(((e,n,r)=>{e&&(t.push(d(" * "+e)),t.push(c()),n<r.length-1&&(t.push(d(" * ")),t.push(c())))})),f(t.concat([d(" */"),c()]))},t.mkAssign=function(e,t){return i("=",[e,t])},t.mkParenthesizedExpression=function(e){return y(h([e]).output)?e:f([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 h(t){let i=[],a={},o="",s="",c=[{}],l=0;function u(e){"string"==typeof e&&(l+=(e.match(/\n/g)||[]).length),o+=e}let p=f(t);return function t(r,i){if(r.type!=n.Infix){for(let e of r.children)t(e,-1);return}let a=[];function o(e){"P"==e[0]&&(e=e.slice(1)),a.push(d(e))}let s=e.U.lookup(g,r.op);if(null==s&&e.U.oops("bad infix op: "+r.op),s<i&&o("("),1==r.children.length)o(r.op),t(r.children[0],s),a.push(r.children[0]);else{let e,n=3!=s&&"**"!=r.op;t(r.children[0],n?s:s+.1),a.push(r.children[0]),e&&"number"!=e&&(o(": "),o(e)),"."==r.op?o("."):o(" "+r.op+" "),t(r.children[1],n?s+.1:s),a.push(r.children[1])}s<i&&o(")"),r.type=n.Prefix,r.op="",r.children=a}(p,-1),_(p),o||u("\n"),{output:o,sourceMap:i};function _(t){t.glueToBlock&&(h(),t.glueToBlock==r.WithSpace&&u(" "));let d=l,p=o.length;switch(t.type){case n.Infix:e.U.oops("no infix should be left");break;case n.NewLine:u("\n"+s);break;case n.Block:!function(t){let n=t.noFinalNewline?"":"\n";if(0==t.children.length)return void m(" {\n\t\n}"+n);let r=e.U.clone(c[c.length-1]||{});c.push(r),s+=" "," "!=o[o.length-1]&&m(" ");m("{\n");for(let e of t.children)_(e);s=s.slice(4),h(),m("\n}"+n),c.pop()}(t);break;case n.Prefix:t.canIndentInside?u(t.op.replace(/\n/g,"\n"+s+" ")):u(t.op),t.children.forEach(_);break;case n.Postfix:t.children.forEach(_),t.canIndentInside?u(t.op.replace(/\n/g,"\n"+s+" ")):u(t.op)}let f=l,g=Math.max(o.length,1);if(t.id)if(a[t.id]){const e=a[t.id];e.startLine=Math.min(e.startLine,d),e.endLine=Math.max(e.endLine,f),e.startPos=Math.min(e.startPos,p),e.endPos=Math.max(e.endPos,g)}else{const e={id:t.id,startLine:d,startPos:p,endLine:f,endPos:g};a[t.id]=e,i.push(e)}}function m(e){u(e.replace(/\n/g,"\n"+s))}function h(){o=o.replace(/\n *$/,(function(){return l--,""}))}}function y(e){if("("!==e[0]||")"!==e[e.length-1])return!1;let t=1;for(let n=1;n<e.length;n++){const r=e[n];if("("===r)t++;else if(")"===r&&(t--,0===t))return n===e.length-1}return!1}t.flattenNode=h,t.isReservedWord=function(e){return-1!==i.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";class r{constructor(e,t,n=0,r=0,i){this.width=e,this.height=t,this.x0=n,this.y0=r,this.width||(this.width=16),this.height||(this.height=16),this.buf=i||new Uint8ClampedArray(this.dataLength())}static fromData(e){return new r(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 r=this.coordToIndex(e,t);this.setCore(r,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,i=this.height){const a=new r(n,i);a.x0=e,a.y0=t;for(let r=0;r<n;r++)for(let n=0;n<i;n++)a.set(r,n,this.get(e+r,t+n));return a}apply(e,t=!1){let n;for(let r=0;r<e.width;r++)for(let i=0;i<e.height;i++)n=e.get(r,i),!n&&t||this.set(e.x0+r,e.y0+i,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 p(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=r;class i extends r{static fromData(e){return new i(e.width,e.height,e.x0,e.y0,e.data)}copy(e=0,t=0,n=this.width,r=this.height){const a=new i(n,r);a.x0=e,a.y0=t;for(let i=0;i<n;i++)for(let n=0;n<r;n++)a.set(i,n,this.get(e+i,t+n));return a}resize(e,t){return f(this,e,t)}getCore(e){return this.buf[e]}setCore(e,t){this.buf[e]=t}dataLength(){return this.width*this.height}}t.Tilemap=i;class a{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:r.fromData(e.bitmap).copy().data()})))},n=r.fromData(this.layers).copy().data();return new a(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=a;function o(e){return s(atob(e.slice(e.indexOf(",")+1)))}function s(t){let n=t.charCodeAt(0),r=t.charCodeAt(1),i=t.charCodeAt(2);135===n&&(n=224|t.charCodeAt(1),r=t.charCodeAt(2)|t.charCodeAt(3)<<8,i=t.charCodeAt(4)|t.charCodeAt(5)<<8,t=t.slice(4));const a=new e.sprite.Bitmap(r,i);let o=4;if(225===n){let e=1,n=t.charCodeAt(o++);for(let s=0;s<r;++s)for(let r=0;r<i;++r)a.set(s,r,n&e?1:0),e<<=1,256==e&&(e=1,n=t.charCodeAt(o++))}else for(let e=0;e<r;e++){for(let n=0;n<i;n+=2){let r=t.charCodeAt(o++);a.set(e,n,15&r),n!=i-1&&a.set(e,n+1,r>>4&15)}for(;3&o;)o++}return a}function c(e,t){!(e=(e=(e=e.replace(/[ `]|(?:`)|(?:	)|(?:hex)/g,"").trim()).replace(/^["`\(\)]*/,"").replace(/["`\(\)]*$/,"")).replace(/ /g,"\n"))&&t&&(e=t);const n=parseInt(e.substr(0,2),16)|parseInt(e.substr(2,2),16)<<8,r=parseInt(e.substr(4,2),16)|parseInt(e.substr(6,2),16)<<8,a=x(e.substring(8));return i.fromData({width:n,height:r,x0:0,y0:0,data:a})}function l(e){return`${d(e.width,2)}${d(e.height,2)}${k(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=_(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.transparency32":return t.getTransparency(32);default:return t.resolveTile(e)}}(e,t))):[]}function d(e,t){let n=e.toString(16);const r=t<<1;for(1&n.length&&(n="0"+n);n.length<r;)n+="0";return n}function p(e,t,n){const i=new r(t,n);return i.apply(e),i}function f(e,t,n){const r=new i(t,n);return r.apply(e),r}function _(e){const t=(e=(e=(e=e.replace(/[ `]|(?:`)|(?:	)|(?:img)/g,"").trim()).replace(/^["`\(\)]*/,"").replace(/["`\(\)]*$/,"")).replace(/ /g,"\n")).split("\n"),n=[];let i=0;for(let e=0;e<t.length;e++){const r=t[e],a=[];for(let e=0;e<r.length;e++)switch(r[e]){case"0":case".":a.push(0);break;case"1":case"#":a.push(1);break;case"2":case"T":a.push(2);break;case"3":case"t":a.push(3);break;case"4":case"N":a.push(4);break;case"5":case"n":a.push(5);break;case"6":case"G":a.push(6);break;case"7":case"g":a.push(7);break;case"8":a.push(8);break;case"9":a.push(9);break;case"a":case"A":case"R":a.push(10);break;case"b":case"B":case"P":a.push(11);break;case"c":case"C":case"p":a.push(12);break;case"d":case"D":case"O":a.push(13);break;case"e":case"E":case"Y":a.push(14);break;case"f":case"F":case"W":a.push(15);break;default:if(!/\s/.test(r[e]))return}a.length&&(n.push(a),i=Math.max(i,a.length))}const a=n.length,o=new r(i,a);for(let e=0;e<a;e++){const t=n[e];for(let n=0;n<i;n++)n<t.length?o.set(n,e,t[n]):o.set(n,e,0)}return o}function m(e){let t="";switch(e){case"python":t='img("""';break;default:t="img`"}return t}function g(e){let t="";switch(e){case"python":t+='""")';break;default:t+="`"}return t}function h(e,t){if(!e||0===e.height||0===e.width)return"";let r=m(t);if(e){const t=e.width*e.height>300?"":" ";for(let i=0;i<e.height;i++){r+="\n";for(let a=0;a<e.width;a++)r+=n[e.get(a,i)]+t}}return r+="\n",r+=g(t),r}function y(t,n){return e.sprite.Bitmap.fromData(t).equals(e.sprite.Bitmap.fromData(n))}function v(e){switch(e){case 8:return"TileScale.Eight";case 16:return"TileScale.Sixteen";case 32:return"TileScale.ThirtyTwo";default:return Math.floor(Math.log2(e)).toString()}}function b(e){switch(e=e.replace(/\s/g,"")){case"TileScale.Eight":return 8;case"TileScale.Sixteen":return 16;case"TileScale.ThirtyTwo":return 32;default:return Math.pow(2,parseInt(e))}}function x(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 k(e){const t="0123456789abcdef";let n="";for(let r=0;r<e.length;++r)n+=t[e[r]>>4],n+=t[15&e[r]];return n}function S(e,t,n){e[t]=255&n,e[t+1]=n>>8&255}function T(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[C(t),E(t),D(t)]}function C(e){return e>>16&255}function E(e){return e>>8&255}function D(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,r=n>>3,i=7&n;this.mask[r]|=1<<i}get(e,t){const n=e+this.width*t,r=n>>3,i=7&n;return this.mask[r]>>i&1}},t.encodeTilemap=function(e,t){return e?`tiles.createTilemap(${function(e){return e?`hex\`${l(e)}\``:"hex``"}(e.tilemap)}, ${h(r.fromData(e.layers),t)}, [${e.tileset.tiles.map((e=>function(e,t){return e.id}(e)))}], ${v(e.tileset.tileWidth)})`:"null"},t.decodeTilemap=function(t,n,r){if(!(t=e.Util.htmlUnescape(t).trim()).trim())return null;const i=(t=(t=t.substr(t.indexOf("(")+1)).substr(0,t.lastIndexOf(")"))).substr(0,t.indexOf(",")),o=(t=t.substr(i.length+1)).substr(0,t.indexOf(",")),s=(t=t.substr(o.length+1)).substr(0,t.lastIndexOf("]")+1),l=t=t.substr(s.length+1);return new a(c(i),{tiles:u(s,r),tileWidth:b(l)},_(o).data())},t.trimTilemapTileset=function(e){const t=e.tileset.tiles.slice(),n=e.tilemap,r={};r[t[0].id]=!0;for(let e=0;e<n.width;e++)for(let i=0;i<n.height;i++)r[t[n.get(e,i)].id]=!0;const i=e.editedTiles||[],a=t.filter((e=>r[e.id]||"*"===e.id.charAt(0)||-1!==i.indexOf(e.id)));if(a.length===t.length)return;const o=[];for(let e=0;e<t.length;e++)o.push(a.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=a},t.isEmptyTilemap=function(e){const t=e.tileset.tiles,n=e.tilemap,r=t[0].id;for(let e=0;e<n.width;e++)for(let i=0;i<n.height;i++)if(t[n.get(e,i)].id!==r)return!1;return!0},t.computeAverageColor=function(e,t){const n=t.map(T),r=[0,0,0];let i=0;for(let t=0;t<e.width;t++)for(let a=0;a<e.height;a++){const o=e.get(t,a);if(o){++i;const e=n[o];r[0]+=e[0],r[1]+=e[1],r[2]+=e[2]}}return i?"#"+function(e){let t="";for(let n=0;n<e.length;++n)t+=("0"+e[n].toString(16)).slice(-2);return t}(r.map((e=>Math.floor(e/i)))):"#00000000"},t.getBitmap=function(e,t){const n=e.apis.byQName[t];return n?o(n.attributes.jresURL):null},t.getBitmapFromJResURL=o,t.hexToBitmap=s,t.filterItems=function(e,t){const n=(t=t.filter((e=>!!e)).map((e=>e.toLowerCase()))).filter((e=>0!==e.indexOf("!"))),r=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 r.every((t=>!e.tags.some((e=>e===t))))}(e);var t}))},t.getGalleryItems=function(n,r){let i=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 r=e.byQName[t];return!(!r||!r.extendsTypes)&&r.extendsTypes.indexOf(n)>=0}(t,e.retType,n)))}(n.apis,r);return i=i.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))}))}(i),i.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=r.fromData(t),i=pxtc.f4EncodeImg(t.width,t.height,4,((e,t)=>n.get(e,t)));return btoa(e.U.uint8ArrayToString(x(i)))},t.tilemapLiteralToTilemap=c,t.hexEncodeTilemap=l,t.formatByte=d,t.resizeBitmap=p,t.resizeTilemap=f,t.imageLiteralToBitmap=_,t.encodeAnimationString=function(t,n){const r=t.map((e=>e.data)),i=new Uint8ClampedArray(8+r[0].length*r.length);S(i,0,n),S(i,2,t[0].width),S(i,4,t[0].height),S(i,6,t.length);let a=8;return r.forEach((e=>{i.set(e,a),a+=e.length})),btoa(e.sprite.uint8ArrayToHex(i))},t.addMissingTilemapTilesAndReferences=function(e,t){const n=e.getProjectTiles(t.data.tileset.tileWidth,!0);t.data.projectReferences=[];for(const r of n.tiles)t.data.tileset.tiles.some((e=>e.id===r.id))||t.data.tileset.tiles.push(r),e.isAssetUsed(r,null,[t.id])&&t.data.projectReferences.push(r.id)},t.updateTilemapReferencesFromResult=function(t,n){const r=n.data;if(r.deletedTiles)for(const e of r.deletedTiles)t.deleteTile(e);if(r.editedTiles)for(const e of r.editedTiles){const n=r.tileset.tiles.findIndex((t=>t.id===e)),i=r.tileset.tiles[n];i&&(r.tileset.tiles[n]=t.updateTile(i))}for(let e=0;e<r.tileset.tiles.length;e++){const n=r.tileset.tiles[e];n.jresData||(r.tileset.tiles[e]=t.resolveTile(n.id))}e.sprite.trimTilemapTileset(r)},t.imageLiteralFromDimensions=function(e,t,r,i){let a=m(i);const o=e*t>300?"":" ";for(let i=0;i<t;i++){a+="\n";for(let t=0;t<e;t++)a+=n[r]+o}return a+="\n",a+=g(i),a},t.bitmapToImageLiteral=h,t.bitmapEquals=y,t.tileWidthToTileScale=v,t.tileScaleToTileWidth=b,t.hexToUint8Array=x,t.uint8ArrayToHex=k,t.colorStringToRGB=T}(e.sprite||(e.sprite={}))}(pxt||(pxt={})),function(e){!function(t){!function(n){const r=new RegExp(`^\\s*${t.TILE_NAMESPACE}\\s*\\.\\s*${t.TILE_PREFIX}(\\d+)\\s*$`);class i{constructor(e,t,n){this.tilemap=e,this.tileset=t,this.layers=n,this.nextId=0}}function a(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=r.exec(e);if(n)return{data:null,projectId:Number(n[1])};return{data:null,qualifiedName:e}}(e))):[]}n.LegacyTilemapData=i,n.decodeTilemap=function(n,r){var o;if(!(null==(n=null===(o=e.Util.htmlUnescape(n))||void 0===o?void 0:o.trim())?void 0:n.trim()))return new i(new t.Tilemap(16,16),{tileWidth:16,tiles:[]},new t.Bitmap(16,16).data());const s=(n=(n=n.substr(n.indexOf("(")+1)).substr(0,n.lastIndexOf(")"))).substr(0,n.indexOf(",")),c=(n=n.substr(s.length+1)).substr(0,n.indexOf(",")),l=(n=n.substr(c.length+1)).substr(0,n.lastIndexOf("]")+1),u=n=n.substr(l.length+1);return new i(t.tilemapLiteralToTilemap(s),{tiles:a(l),tileWidth:t.tileScaleToTileWidth(u)},t.imageLiteralToBitmap(c).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 r{constructor(e){this.storageId=e}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 r=window.localStorage.key(n);0==r.indexOf(e)&&t.push(r)}t.forEach((e=>window.localStorage.removeItem(e)))}}function i(){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 a;function o(){if(a)return;const t=i();let o=!1;if(!e.shell.isSandboxMode())try{window.localStorage[t]="1";window.localStorage[t];o=!0}catch(e){}o?(a=new r(t),e.debug(`storage: local under ${t}`)):(a=new n,e.debug("storage: in memory"))}t.storageId=i,t.setLocal=function(e,t){o(),a.setItem(e,t)},t.getLocal=function(e){return o(),a.getItem(e)},t.removeLocal=function(e){o(),a.removeItem(e)},t.clearLocal=function(){o(),a.clear()}}(e.storage||(e.storage={}))}(pxt||(pxt={})),function(e){!function(t){!function(t){const n="http://localhost:3232/api/store/";function r(){return e.BrowserUtils.isLocalHostDev()&&!e.BrowserUtils.noSharedLocalStorage()}function i(){return e.BrowserUtils.isChromiumEdge()?"chromium-edge":e.BrowserUtils.browser()}t.getAsync=async function(t,a){if(r()){t+="-"+i();const r=await e.Util.requestAsync({url:`${n}${encodeURIComponent(t)}/${encodeURIComponent(a)}`,method:"GET",allowHttpErrors:!0});return r.json?r.json:r.text?r.text:void 0}{const n=e.storage.getLocal(`${t}:${a}`),r=e.Util.jsonTryParse(n);return r||n}},t.setAsync=async function(t,a,o){if(void 0===o)return void await e.storage.shared.delAsync(t,a);let s="";if(s="object"==typeof o?JSON.stringify(o):o.toString(),r()){t+="-"+i();const r={type:"object"==typeof o?"json":"text",val:s},c=JSON.stringify(r);await e.Util.requestAsync({url:`${n}${encodeURIComponent(t)}/${encodeURIComponent(a)}`,method:"POST",data:c})}else e.storage.setLocal(`${t}:${a}`,s)},t.delAsync=async function(t,a){r()?(t+="-"+i(),await e.Util.requestAsync({url:`${n}${encodeURIComponent(t)}/${encodeURIComponent(a)}`,method:"DELETE",allowHttpErrors:!0})):e.storage.removeLocal(`${t}:${a}`)}}(t.shared||(t.shared={}))}(e.storage||(e.storage={}))}(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,r){this.id=e,this._verspec=t,this.parent=n,this.level=-1,this.isLoaded=!1,this.ignoreTests=!1,this.cppOnly=!1,r&&(this.level=r.level+1),this.addedBy=[r]}static stringifyConfig(e){const n=e,r={};for(const e of t)n.hasOwnProperty(e)&&(r[e]=n[e]);for(const e of Object.keys(n))r.hasOwnProperty(e)||(r[e]=n[e]);return JSON.stringify(r,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 getConfigAsync(t,n,r){return Promise.resolve().then((()=>{if(e.github.isGithubId(r)){const t=e.github.parseRepoId(r);return e.packagesConfigAsync().then((n=>e.github.repoAsync(t.fullName,n))).then((n=>n?e.github.pkgConfigAsync(t.fullName,t.tag):null))}{const i=e.patching.upgradePackageReference(t,n,r),a=e.appTarget.bundledpkgs[i];return JSON.parse(a[e.CONFIG_NAME])}}))}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}commonDownloadAsync(){const t=this.verProtocol();if("pub"==t)return e.Cloud.downloadScriptFilesAsync(this.verArgument());if("github"==t)return e.packagesConfigAsync().then((t=>e.github.downloadPackageAsync(this.verArgument(),t))).then((e=>e.files));if("embed"==t){const t=e.getEmbeddedScript(this.verArgument());return Promise.resolve(t)}if("pkg"==t){const t=(this.parent||this).readFile(this.verArgument()),n=ts.pxtc.Util.jsonTryParse(t);return n||e.log(`unable to find ${this.verArgument()}`),Promise.resolve(n)}return Promise.resolve(null)}host(){return this.parent._host}readFile(e){return this.host().readFile(this,e)}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")&&r(JSON.parse(this.readFile(n)),t);return t}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 r=e.github.parseRepoId(this._verspec);if(r&&!r.tag&&this.parent){e.debug("dep: unbound github extensions, trying to resolve tag");const i=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)===r.slug)).map((e=>e.tag)))[0];i&&(r.tag=i,this.resolvedVersion=n=e.github.stringifyRepo(r),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(),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 r=null;const i=e.patching.computePatches(this.targetVersion(),"missingPackage");return i&&i.forEach((e=>{Object.keys(e.map).forEach((n=>{e.map[n]===t&&(r=new RegExp(n,"g"))}))})),r||(r=new RegExp(t+"\\.","g")),r.test(n)}upgradePackagesAsync(){return this.config||this.loadConfig(),e.packagesConfigAsync().then((t=>{let n=0,r={};return e.U.iterMap(this.config.dependencies,((i,a)=>{if(e.github.isGithubId(a)){const o=e.github.upgradedPackageReference(t,a);o&&o!=a&&(e.log(`upgrading dep ${i}: ${a} -> ${o}`),r[a]=o,this.config.dependencies[i]=o,n++)}})),n&&this.saveConfig(),n&&r}))}getMissingPackages(t,n){const r=e.patching.computePatches(this.targetVersion(),"missingPackage"),i={};return n&&r&&r.forEach((e=>{Object.keys(e.map).forEach((r=>{const a=new RegExp(r,"g"),o=e.map[r];n.replace(a,(e=>(t.dependencies[o]||(i[o]="*"),"")))}))})),i}findConflictsAsync(t,r){let i,a=[];return Promise.resolve().then((()=>"string"==typeof t?n.getConfigAsync(this.targetVersion(),t,r):Promise.resolve(t))).then((t=>{if(i=t,i){const t=i.yotta?e.U.jsonFlatten(i.yotta.config):null;this.parent.sortedDeps().forEach((n=>{if(i.core&&n.config.core&&i.name!=n.config.name){const t=new e.cpp.PkgConflictError(lf("conflict between core extensions {0} and {1}",i.name,n.id));return t.pkg0=n,void a.push(t)}let o=!1;if(t){const r=n.config||JSON.parse(n.readFile(e.CONFIG_NAME));if(!!r&&!!r.yotta&&!!n.config.yotta.config){const s=e.U.jsonFlatten(r.yotta.config);for(const c of Object.keys(t)){const l=s[c],u=i.yotta.configIsJustDefaults||r.yotta.configIsJustDefaults;if(s.hasOwnProperty(c)&&l!==t[c]&&!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}",c,i.name,n.id));t.pkg0=n,t.settingName=c,a.push(t),o=!0}}}}if(!o&&i.name===n.id&&n._verspec!==r&&!/^file:/.test(n._verspec)&&!/^file:/.test(r)){const t=/^github:/.test(n._verspec)&&e.github.parseRepoId(n._verspec),i=/^github:/.test(r)&&e.github.parseRepoId(r);if(!t||!i||t.fullName!==i.fullName||i.tag&&e.semver.strcmp(t.tag,i.tag)<0){const t=new e.cpp.PkgConflictError(lf("version mismatch for extension {0} (installed: {1}, installing: {2})",n.id,n._verspec,r));t.pkg0=n,t.isVersionConflict=!0,a.push(t)}}}))}return Object.keys(i.dependencies).reduce(((e,t)=>e.then((()=>this.findConflictsAsync(t,i.dependencies[t]))).then((e=>a.push.apply(a,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 a.forEach((a=>{n.push.apply(n,t(a.pkg0).map((t=>{const n=new e.cpp.PkgConflictError(a.isVersionConflict?lf("a dependency of {0} has a version mismatch with extension {1} (installed: {1}, installing: {2})",t.id,i.name,a.pkg0._verspec,r):lf("conflict on yotta setting {0} between extensions {1} and {2}",a.settingName,i.name,a.pkg0.id));return n.pkg0=t,n})))})),a.push.apply(a,n),a=a.filter(((e,t)=>{for(let n=0;n<t;++n)if(e.pkg0.id===a[n].pkg0.id)return!1;return!0})),a}))}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 r=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)!=r&&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,r)=>{("*"!=r||e.appTarget.bundledpkgs[t])&&(n[t]=r)})),t&&this.config.cppDependencies&&e.Util.jsonMergeFrom(n,this.config.cppDependencies),n}loadAsync(t=!1,r){if(this.isLoaded)return Promise.resolve();let i=Promise.resolve();0!=this.level||e.appTarget.multiVariants||e.setAppTargetVariant(null),this.isLoaded=!0;const a=this.readFile(e.CONFIG_NAME);null==a?t||e.U.userError("Package not installed: "+this.id+", did you forget to run `pxt install`?"):i=i.then((()=>this.parseConfig(a))),0!=this.level||t||(i=i.then((()=>this.upgradePackagesAsync().then((()=>{}))))),t&&(i=i.then((()=>this.downloadAsync()))),0==this.level&&t&&(i=i.then((()=>this.upgradePackagesAsync())).then((t=>t?(Object.keys(t).forEach((t=>e.tickEvent("package.doubleload",{extension:t}))),e.log("upgraded, downloading again"),e.debug(t),this.downloadAsync()):Promise.resolve()))),e.appTarget.simulator&&e.appTarget.simulator.dynamicBoardDefinition&&(0==this.level&&(i=i.then((()=>this.patchCorePackage()))),i=i.then((()=>{if(this.config.compileServiceVariant&&e.setAppTargetVariant(this.config.compileServiceVariant),this.config.files.indexOf("board.json")<0)return;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],r=this.readFile(t);return e.U.toDataUri(r,e.U.getMime(t))}return t},r=e.appTarget.simulator.boardDefinition;if("object"==typeof r.visual){let e=r.visual;e.image=n(e.image),e.outlineImage=n(e.outlineImage)}})));const o=(t,n)=>{var r;if(e.debug(`version spec mismatch: ${t._verspec} != ${n}`),/^github:/.test(t._verspec)&&/^github:/.test(n)){const i=e.github.parseRepoId(t._verspec),a=e.github.parseRepoId(n);if((null==i?void 0:i.slug)&&(null==i?void 0:i.slug)===(null==a?void 0:a.slug)){const o=(null==i?void 0:i.tag)||(null===(r=t.config)||void 0===r?void 0:r.version),s=e.semver.strcmp(o,a.tag);if(0==s)return void e.debug(`resolved version are ${o}`);if(s<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"))},s=async(r,i,a=!1)=>{r||(r=i.dependencies(a)),e.debug(`deps: ${i.id}->${Object.keys(r).join(", ")}`),r=e.github.resolveMonoRepoVersions(r),e.debug(`deps: resolved ${i.id}->${Object.keys(r).join(", ")}`);for(let s of Object.keys(r)){let c=r[s]||"*";e.debug(`dep: load ${i.id}.${s}${a?"++":""}: ${c}`),"hw"==s&&e.hwVariant&&(s="hw---"+e.hwVariant);let l=i.resolveDep(s);if(l){if(l.invalid()||l._verspec===c||o(l,c),l.invalid()){l.level=Math.min(l.level,i.level+1),l.addedBy.push(i);continue}a||(l.level=Math.min(l.level,i.level+1),l.addedBy.push(i))}else{let e=new n(s,c,i.parent,i);a&&(e.cppOnly=!0),i.parent.deps[s]=e,i.parent.deps[s.replace(/---.*/,"")]=e,await e.loadAsync(t)}}};return i.then((()=>s(null,this))).then((()=>{if(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)),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)return Promise.resolve(null);const n=this.getMissingPackages(this.config,t);let r=!1;return Object.keys(n).reduce(((t,i)=>t.then((()=>this.findConflictsAsync(i,n[i]))).then((t=>{if(t.length){const n=t.map((e=>e.pkg0.id)).join(", "),r=t.map((e=>e.settingName)).filter((e=>!!e)).join(", ");return e.log(`skipping missing package ${i} because it conflicts with the following packages: ${n} (conflicting settings: ${r})`),Promise.resolve(null)}{e.log(`adding missing package ${i}`),r=!0,this.config.dependencies[i]="*";const t={};return t[i]=n[i],s(t,this)}}))),Promise.resolve(null)).then((()=>(r&&(this.saveConfig(),this.validateConfig()),Promise.resolve(null))))}return Promise.resolve(null)})).then((()=>0!=this.level?Promise.resolve():Promise.all(e.U.values(this.parent.deps).map((e=>s(null,e,!0)))))).then((()=>{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 r=this.config.fileDependencies;return this.config.fileDependencies&&(t=t.filter((t=>{const i=r=>{if("!"==(r=r.trim())[0])return!i(r.slice(1));if(/^[\w-]+$/.test(r)){const e=this.parent.resolveDep(r);return!(!e||e.cppOnly)}const a=/^target:(\w+)$/.exec(r);return a?a[1]==e.appTarget.id||a[1]==e.appTarget.platformid:(n.depWarnings[r]||(n.depWarnings[r]=!0,e.log(`invalid dependency expression: ${r} in ${this.id}/${t}`)),!1)},a=e.U.lookup(r,t);return!a||!a.trim()||a.split("||").some((e=>e.split("&&").every(i)))}))),t}addSnapshot(t,n=[""]){for(let r of this.getFiles())n.some((t=>e.U.endsWith(r,t)))&&(t[this.id+"/"+r]=this.readFile(r));t[this.id+"/"+e.CONFIG_NAME]=this.readFile(e.CONFIG_NAME)}packageLocalizationStringsAsync(t){const n=e.appTarget.id,r=[this.config.name+"-jsdoc",this.config.name],i={},a=e.appTarget.appTheme||{};return this.config.skipLocalization?Promise.resolve(i):e.Util.liveLocalizationEnabled()&&"this"!=this.id&&e.appTarget.bundledpkgs[this.id]?(e.debug(`loading live translations for ${this.id}`),Promise.all(r.map((r=>e.Util.downloadLiveTranslationsAsync(t,`${n}/${r}-strings.json`,a.crowdinBranch).then((n=>{n&&Object.keys(n).length?e.Util.jsonMergeFrom(i,n):(e.tickEvent("translations.livetranslationsfailed",{filename:r}),e.Util.jsonMergeFrom(i,this.bundledStringsForFile(t,r)))})).catch((a=>{e.tickEvent("translations.livetranslationsfailed",{filename:r}),e.log(`error while downloading ${n}/${r}-strings.json`),e.Util.jsonMergeFrom(i,this.bundledStringsForFile(t,r))}))))).then((()=>i))):(r.map((e=>this.bundledStringsForFile(t,e))).filter((e=>!!e)).forEach((t=>e.Util.jsonMergeFrom(i,t))),Promise.resolve(i))}bundledStringsForFile(t,n){let r={},[i,a,o]=e.Util.normalizeLanguageCode(t);const s=this.config.files;let c=`_locales/${i}/${n}-strings.json`;return s.indexOf(c)>-1?r=JSON.parse(this.readFile(c)):o&&(c=`_locales/${o}/${n}-strings.json`,s.indexOf(c)>-1?r=JSON.parse(this.readFile(c)):a&&(c=`_locales/${a}/${n}-strings.json`,s.indexOf(c)>-1&&(r=JSON.parse(this.readFile(c))))),r}}n.depWarnings={},e.Package=n;function r(e,t={}){let n=e["*"]||{};for(let r of Object.keys(e)){if("*"==r)continue;let i=e[r];"string"==typeof i&&(i={data:i});let a=i.namespace||n.namespace||"";a&&(a+=".");let o=i.id||a+r,s=i.icon,c=i.mimeType||n.mimeType,l=i.dataEncoding||n.dataEncoding||"base64";s||"base64"!=l||"image/png"!=c&&"image/jpeg"!=c||(s="data:"+c+";base64,"+i.data),t[o]={id:o,data:i.data,dataEncoding:l,icon:s,namespace:a,mimeType:c,tilemapTile:i.tilemapTile,displayName:i.displayName,tileset:i.tileset}}return t}e.MainPackage=class extends n{constructor(e){super("this","file:.",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={},r=[];const i=e=>e.config?Object.keys(e.config.cppDependencies||{}).length:0,a=o=>{if(!o||e.U.lookup(n,o.id))return;n[o.id]=!0;const s=Object.keys(o.dependencies(t)).map((e=>this.resolveDep(e)));s.sort(((t,n)=>i(n)-i(t)||e.U.strcmp(t.id,n.id))),s.forEach(a),r.push(o.id)};return a(this),r.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((r=>{(e.U.startsWith(r,"{id:subcategory}")||e.U.startsWith(r,"{id:group}"))&&(t[r]||(t[r]=n[r]))})),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 r=(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 i=!1;const a=async n=>{const a={extinfo:null,target:null},o=e.appTargetVariant;n&&e.setAppTargetVariant(n,{temporary:!0});try{let s=e.cpp.getExtensionInfo(this);i||!s.shimsDTS&&!s.enumsDTS||(i=!0,s.shimsDTS&&r("shims.d.ts",s.shimsDTS),s.enumsDTS&&r("enums.d.ts",s.enumsDTS));const c=t.isNative?await this.host().getHexInfoAsync(s):null;s=e.U.flatClone(s),t.keepCppFiles||(delete s.compileData,delete s.generatedFiles,delete s.extensionFiles),s.hexinfo=c,a.extinfo=s,a.target=e.appTarget.compile}finally{n&&e.setAppTargetVariant(o,{temporary:!0})}return a};let o;await this.loadAsync(),n.bannedCategories=this.resolveBannedCategories(),n.target.preferredEditor=this.getPreferredEditor(),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 s=null;for(let t of o){s&&e.debug(`building for ${t}`);const r=await a(t),i=r.extinfo;i.appVariant=t,i.outputPrefix=1!=o.length&&t?t+"-":"",s?n.otherMultiVariants.push(r):(s=i,n.otherMultiVariants=[])}n.extinfo=s;if(!(e.appTarget.compile.shortPointers||"vm"==e.appTarget.compile.nativeType||this.config.binaryonly||!n.target.isNative)){const t=await this.filesToBePublishedAsync(!0),r=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}),i=JSON.stringify(t),a=await e.lzmaCompressAsync(r+i);a&&(n.embedMeta=JSON.stringify({compression:"LZMA",headerSize:r.length,textSize:i.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(a)))}for(const e of this.sortedDeps())for(const t of e.getFiles())if(/\.(ts|asm|py)$/.test(t)){let r=t;e.level>0&&(r="pxt_modules/"+e.id+"/"+t),n.sourceFiles.push(r),n.fileSystem[r]=e.readFile(t)}n.jres=this.getJRes();const c=e.appTarget.runtime&&e.appTarget.runtime.functionsOptions;return n.allowedArgumentTypes=c&&c.extraFunctionEditorTypes&&c.extraFunctionEditorTypes.map((e=>e.typeName)).concat("number","boolean","string"),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,r)=>{if(!r||/^(file|workspace):/.test(r)){r="*";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,r=e.github.stringifyRepo(n)}}catch(e){}t.dependencies[n]=r}})),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 r=this.prepareConfigToBePublished();n[e.CONFIG_NAME]=e.Package.stringifyConfig(r);for(let t of this.getFiles()){if(t==e.CONFIG_NAME)continue;let r=this.readFile(t);null==r&&e.U.userError("referenced file missing: "+t),n[t]=r}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((r=>{let i=r.readFile("pxtparts.json");if(i)try{let a=JSON.parse(i);Object.keys(a).forEach((i=>{if(t.indexOf(i)>=0){let t=n[i]=a[i];if("string"==typeof t.visual.image&&/\.svg$/i.test(t.visual.image)){let n=r.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=r,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,r,i,a,o,s=()=>{};function c(){if(o)return o;let t=Promise.resolve();if(n){e.debug("packetio: disconnect");const i=n;t=t.then((()=>i.disconnectAsync())).then((()=>i.io.disposeAsync())).catch((t=>{e.reportException(t)})).finally((()=>{r=void 0,n=void 0,o=void 0})),s&&(t=t.then((()=>s()))),o=t}return t}t.isActive=function(){return!!n},t.isConnected=function(){return!!n&&n.io.isConnected()},t.isConnecting=function(){return!!n&&n.io.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.disconnectAsync=c,t.configureEvents=function(e,t,r){s=e,i=t,a=r,n&&(n.io.onConnectionChanged=s,n.onSerial=i,n.onCustomEvent=r)},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)":"")),!r){let l=Promise.resolve();o&&(l=l.then((()=>c()))),r=l.then((()=>n?Promise.resolve(n):t.mkPacketIOAsync?(e.debug("packetio: new wrapper"),t.mkPacketIOAsync().then((e=>(e.onConnectionChanged=s,n=t.mkPacketIOWrapper(e),i&&(n.onSerial=i),a&&(n.onCustomEvent=a),s&&s(),n)))):(e.debug("packetio: not defined, skipping"),Promise.resolve(void 0)))).finally((()=>{r=void 0}))}return r}}(e.packetio||(e.packetio={}))}(pxt||(pxt={})),function(e){!function(t){t.computePatches=function(t,n){const r=e.appTarget.compile?e.appTarget.compile.patches:void 0;if(!r)return;const i=e.semver.tryParse(t||"0.0.0")||e.semver.tryParse("0.0.0");let a=[];return Object.keys(r).filter((t=>e.semver.inRange(t,i))).forEach((e=>a=a.concat(r[e]))),n&&(a=a.filter((e=>e.type==n))),a.length?a:void 0},t.upgradePackageReference=function(t,n,r){if("*"!=r)return n;const i=e.patching.computePatches(t,"package");let a=n;return i&&i.forEach((e=>{Object.keys(e.map).forEach((t=>{a==t&&(a=e.map[t])}))})),a},t.patchJavaScript=function(t,n){const r=e.patching.computePatches(t);let i=n;return r&&(r.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])}))})),r.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 r=new RegExp(`(^|[^_a-zA-Z0-9])${t}(\\s*\\.)`,"g");i=i.replace(r,`$1${e.map[t]}$2`)}))}))),i}}(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 r=t.major-n.major||t.minor-n.minor||t.patch-n.patch;if(r)return r;if(0==t.pre.length&&n.pre.length>0)return 1;if(t.pre.length>0&&0==n.pre.length)return-1;for(let i=0;i<t.pre.length+1;++i){let a=t.pre[i],o=n.pre[i];if(!a)return o?-1:0;if(!o)return 1;if(/^\d+$/.test(a)){if(!/^\d+$/.test(o))return-1;if(r=parseInt(a)-parseInt(o),r)return r}else{if(/^\d+$/.test(o))return 1;if(r=e.U.strcmp(a,o),r)return r}}return 0}return-1}return n?1:0}function r(t,n){let r=i(t)||i(n);return r||e.U.userError(e.U.lf("'{0}' doesn't look like a semantic version number",t)),r}function i(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 a(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,r){let a=i(t),o=i(r);return a||o?n(a,o):e.U.strcmp(t,r)}function s(e,t){let r=e.split(" - ");if(2!=r.length)return!1;let a=i(r[0]),o=i(r[1]);if(!a||!o)return!1;if(!t)return!0;const s=n(a,t),c=n(t,o);return s<=0&&c<0}t.cmp=n,t.parse=r,t.tryParse=i,t.normalize=function(e){return a(r(e))},t.stringify=a,t.majorCmp=function(e,t){let n=i(e),r=i(t);return n.major-r.major},t.strcmp=o,t.inRange=s,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 i=0;i<t.length;++i){let o=r(t[i]);console.log(t[i],o),e.U.assert(a(o)==t[i]);for(let a=0;a<t.length;++a){let s=n(o,r(t[a]));console.log(t[i],t[a],s),i<a?e.U.assert(s<0):i>a?e.U.assert(s>0):e.U.assert(0==s)}}const o=i("1.2.3");e.U.assert(s("0.1.2 - 2.2.3",o)),e.U.assert(s("1.2.3 - 2.2.3",o)),e.U.assert(!s("0.0.0 - 1.2.3",o)),e.U.assert(!s("1.2.4 - 4.2.3",o)),e.U.assert(!s("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 r=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 r=n.reduce(((t,n,r)=>e<n?t:r+1),0);return[r,t[r]-(n[r]-e)+1]},lineColToPos:(e,t)=>(n[e-1]||0)+t}},i={ts:r(t),py:r(n)},a=e=>e.endPos-e.startPos,o=(t,n)=>{const{startPos:r,endPos:i}=t;return e.filter((e=>e[n].startPos<=r&&i<=e[n].endPos))},s=(e,t)=>{const n=o(e,t);return n.reduce(((e,n)=>a(n[t])<a(e[t])?n:e),n[0])},c={ts:{allOverlaps:e=>o(e,"ts"),smallestOverlap:e=>s(e,"ts")},py:{allOverlaps:e=>o(e,"py"),smallestOverlap:e=>s(e,"py")}},l=(e,t)=>n=>{const[r,o]=(t=>[i[e].lineColToPos(t.line,t.column),t.length])(n),c=s({startPos:r,endPos:r+o},e);if(!c)return;const[l,u]=i[t].posToLineCol(c[t].startPos);return{fileName:`main.${t}`,start:c[t].startPos,length:a(c[t]),line:l,column:u}},u=l("ts","py"),d=l("py","ts");return{ts:Object.assign(Object.assign(Object.assign({},i.ts),c.ts),{locToLoc:u,getText:e=>t.substring(e.startPos,e.endPos)}),py:Object.assign(Object.assign(Object.assign({},i.py),c.py),{locToLoc:d,getText:e=>n.substring(e.startPos,e.endPos)})}},e.computeUsedParts=function(e,t){if(!e.usedSymbols||!pxt.appTarget.simulator||!pxt.appTarget.simulator.parts)return[];let n=[];if(Object.keys(e.usedSymbols).forEach((t=>{let r=e.usedSymbols[t];if(r&&r.attributes.parts){let e=r.attributes.parts;if(e){e.split(/[ ,]+/).forEach((e=>{0<e.length&&n.indexOf(e)<0&&n.push(e)}))}}})),t){const e=pxt.appTarget.simulator.boardDefinition.onboardComponents;e&&("ignorebuiltin"===t?n=n.filter((t=>-1===e.indexOf(t))):"onlybuiltin"===t&&(n=n.filter((t=>e.indexOf(t)>=0))))}return n.sort(),n=n.reverse(),n},e.buildSimJsInfo=function(t){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")}},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 r,o;let s=[];const c={},l={},u={},d={},p={};function f(t,n){const r="get"==t,i="set"==t,o="number"==n.retType,d=r?l:i?c:u,p=`${n.namespace}.${n.retType}`;let f=e.U.lookup(d,p);if(!f){const c=`@${t}@`;let l,u;if(n.attributes.blockCombineShadow){const t=n.attributes.blockCombineShadow,r=t.match(/^([^,.]*),?([^,.]*)$/);r&&3==r.length&&(l=r[1].trim(),u=r[2].trim(),0!=u.length||e.Util.endsWith(t,",")||(u=l,l=""))}const _=`${n.attributes.blockSetVariable||n.namespace.toLocaleLowerCase()}=${l||""}`,m=`value=${u||""}`;f=d[p]={attributes:{blockId:`${o?n.namespace:p}_blockCombine_${t}`,callingConvention:0,group:n.attributes.group,paramDefl:{},jsDoc:r?e.U.lf("Read value of a property on an object"):e.U.lf("Update value of property on an object")},name:c,namespace:n.namespace,fileName:n.fileName,qName:`${p}.${c}`,pkg:n.pkg,kind:2,parameters:[{name:"property",description:r?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:i?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,r?1:2),retType:r?n.retType:"void",combinedProperties:[]},f.attributes.block=r?e.U.lf("%{0} %property",_):i?e.U.lf("set %{0} %property to %{1}",_,m):e.U.lf("change %{0} %property by %{1}",_,m),a(f.attributes),pxt.Util.isTranslationMode()&&(f.attributes.translationId=f.attributes.block,f.attributes.block=r?`%${_} %property`:i?`set %${_} %property to %${m}`:`change %${_} %property by %${m}`,a(f.attributes),pxt.crowdin.inContextLoadAsync(f.attributes.translationId).then((e=>{f.attributes.block=e,a(f.attributes)}))),s.push(f)}f.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 r=n.attributes.kindNamespace||n.attributes.blockNamespace||n.namespace;if(p[r]){console.warn(`More than one block defined for kind ${r}`);continue}const i=[];if(t.byQName[r])for(const n of e.Util.values(t.byQName))n.namespace===r&&n.attributes.isKind&&i.push(n.name);p[r]={blockId:n.attributes.blockId,name:r,memberName:n.attributes.kindMemberName||r,initialMembers:i,promptHint:n.attributes.enumPromptHint||e.Util.lf("Create a new kind..."),createFunctionName:n.attributes.kindCreateFunction||"create"}}if(n.attributes.blockCombine)/@set/.test(n.name)||f("get",n),n.isReadOnly||("number"==n.retType&&f("change",n),f("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 s=null!==(o=null===(r=n.parameters)||void 0===r?void 0:r.filter((e=>!i(e))))&&void 0!==o?o:[];for(let e of s)t+=" %"+e.name;n.attributes.block=t,a(n.attributes)}s.push(n)}}for(let n of s){let r=e.U.lookup(t.byQName,n.namespace);if(!r)continue;let i=r.attributes,a=n.attributes;for(let e of["blockNamespace","color","blockGap"])void 0===a[e]&&i[e]&&(a[e]=i[e])}var _;return n&&((_=n).length&&(s=s.filter((e=>{let t=(e.attributes.blockNamespace||e.namespace).split(".")[0];return-1===_.indexOf(t)})))),{apis:t,blocks:s,blocksById:pxt.Util.toDictionary(s,(e=>e.attributes.blockId)),enumsByName:d,kindsByName:p}},e.tsSnippetToPySnippet=function(t,n){const r={true:"True",false:"False",null:"None"}[t];if(r)return r;if(n&&6==n.kind||!n&&t.includes(".")){const n=t.lastIndexOf("."),r=t.substr(0,n);let i=t.substr(n+1);return i=e.U.snakify(i).toUpperCase(),`${r}.${i}`}return t},e.apiLocalizationStrings={},e.localizeApisAsync=async function(n,r){const i=e.Util.userLanguage();if("en"==i)return Promise.resolve(t(n));const o=i.toLowerCase(),s=o+"|jsdoc",c=o+"|block",l=await r.localizationStringsAsync(i);e.apiLocalizationStrings&&e.Util.jsonMergeFrom(l,e.apiLocalizationStrings);const u=e.Util.values(n.byQName).filter((e=>e.attributes._translatedLanguageCode!==i));return await e.Util.promiseMapAll(u,(async t=>{var r,u,d;const p=t.attributes.useLoc||t.attributes.blockAliasFor,f=p&&n.byQName[p];t.attributes._untranslatedJsDoc&&(t.attributes.jsDoc=t.attributes._untranslatedJsDoc),t.attributes._untranslatedBlock&&(t.attributes.jsDoc=t.attributes._untranslatedBlock);const _=(e,n)=>{var r,i;return l[t.qName+e]||(null===(r=t.attributes.locs)||void 0===r?void 0:r[n])||f&&(l[f.qName+e]||(null===(i=f.attributes.locs)||void 0===i?void 0:i[n]))},m=_("",s);m&&(t.attributes._untranslatedJsDoc||(t.attributes._untranslatedJsDoc=t.attributes.jsDoc),t.attributes.jsDoc=m),null===(r=t.parameters)||void 0===r||r.forEach((e=>{const t=`|param|${e.name}`,n=_(t,o+t);n&&(e.description=n)}));const g=l["{id:category}"+e.Util.capitalize(t.qName)];let h=l[`${t.qName}|block`]||(null===(u=t.attributes.locs)||void 0===u?void 0:u[c]);if(!h&&f){const e=l[`${f.qName}|block`]||(null===(d=f.attributes.locs)||void 0===d?void 0:d[c]);t.attributes.block===(f.attributes._untranslatedBlock||f.attributes.block)&&e&&(h=e)}if(h&&pxt.Util.isTranslationMode()&&(t.attributes.translationId=h,h=await pxt.crowdin.inContextLoadAsync(h)),g)t.attributes.block?t.attributes.block=h||t.attributes.block:t.attributes.block=g,a(t.attributes);else if(t.attributes.block&&h){const e=pxt.blocks.compileInfo(t),n=t.attributes.block;if(t.attributes.block=pxt.blocks.normalizeBlock(h,(e=>{pxt.tickEvent("loc.normalized",{block:t.attributes.block,lang:i,error:e})})),t.attributes._untranslatedBlock||(t.attributes._untranslatedBlock=n),n!=t.attributes.block){a(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)return pxt.debug(`Parameter ${n.actualName} type or shadow block does not match after localization`),!1}return!0})(e,pxt.blocks.compileInfo(t))||(pxt.log(`block has non matching arguments: ${n} vs ${t.attributes.block}`),pxt.reportError("loc.errors","invalid translations",{block:t.attributes.blockId,lang:i}),t.attributes.block=n,a(t.attributes))}}else a(t.attributes);t.attributes._translatedLanguageCode=i})),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,r={functions:[],generatedFiles:{},extensionFiles:{},sha:"",compileData:"",shimsDTS:"",enumsDTS:"",onlyPublic:!0};return t?r.platformio={dependencies:{}}:n?r.npmDependencies={}:r.yotta={config:{},dependencies:{}},r};const n=["weight","imageLiteral","topblockWeight"],r=["advanced","handlerStatement","afterOnStart","optionalVariableArgs","blockHidden","constantShim","blockCombine","enumIsBitMask","enumIsHash","decompileIndirectFixedInstances","topblock","callInDebugger","duplicateShadowOnDrag","argsNullable"];function i(e){return"Action"===e.type||/^\([^\)]*\)\s*=>/.test(e.type)}function a(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,r=0;for(;r<e.length;r++){const i=e[r],a=r;let o;switch(i){case"*":case"_":const t=d((e=>e==i)),n="_"===i?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}:r=a;break;case"`":const s=p("`");if(void 0===s){r=a;break}o={kind:256,content:s};break;case"|":o={kind:32};break;case"\\":r<e.length-1&&(o={kind:16,content:e[1+r++]});break;case"[":const c=p("]");if(void 0!==c&&"("===e[1+r++]){const e=p(")");if(void 0!==e){o={kind:512,content:c,type:e};break}}r=a;break;case"$":case"%":const l=d((e=>/[a-zA-Z0-9_=]/.test(e)),!0).split("=");if(l.length>2){r=a;break}let u;if("("===e[r+1]){const e=r;++r,u=p(")"),u||(r=e)}o={kind:"$"===i?1024:64,content:l[0],type:l[1],name:u}}o?(n&&t.push({kind:128,content:n}),n=void 0,t.push(o)):n?n+=i:n=i}n&&t.push({kind:128,content:n});const i=[],a=[];let o=[],c=0,l="",u=[];for(let e=0;e<t.length;e++){const n=t[e].kind,r=o[o.length-1];if(15&n)if(m(t[e].content),n&c)if(r&n){o.pop(),c^=n;const e=r&c|n&c;e&&o.push(e)}else f();else c|=n,o.push(n);else 144&n?l+=t[e].content:1120&n&&_();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),i.push(n),a.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),i.push(n),a.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&&i.push({kind:"break"})}return _(),{parts:i,parameters:a};function d(t,n=!1){let i="";for(n&&r++;r<e.length&&t(e[r]);)i+=e[r],++r;return i&&r--,i}function p(t){const n=d((e=>e!==t),!0);if(e[r+1]===t)return++r,n}function f(){let e="",t=[];for(const n of u)s(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=[],c=0}function _(){for(m(),c&&f();u.length;){const e=u.shift();if(s(e))i.push(e);else{if(!e.content)continue;const t=[];10&e.styles&&t.push("bold"),5&e.styles&&t.push("italics"),i.push({kind:"label",text:e.content,style:t})}}}function m(e){u.push({content:l,styles:c,endingToken:e}),l=""}}function s(e){return!!e.kind}let c;e.parseCommentString=function(t){let i={paramDefl:{},callingConvention:0,_source:t},o=!0;for(;o;)o=!1,t=t.replace(/\/\/%[ \t]*([\w\.-]+)(=(("[^"\n]*")|'([^'\n]*)'|([^\s]*)))?/,((t,n,r,a,s,c,l)=>{let u=s?JSON.parse(s):r?s||c||l:"true";if(u||(u=""),e.U.startsWith(n,"block.loc."))i.locs||(i.locs={}),i.locs[n.slice("block.loc.".length).toLowerCase()+"|block"]=u;else if(e.U.startsWith(n,"jsdoc.loc."))i.locs||(i.locs={}),i.locs[n.slice("jsdoc.loc.".length).toLowerCase()+"|jsdoc"]=u;else if(e.U.contains(n,".loc.")){i.locs||(i.locs={});const e=n.slice(0,n.indexOf(".loc.")),t=n.slice(n.indexOf(".loc.")+".loc.".length);i.locs[t+"|param|"+e]=u}else if(e.U.endsWith(n,".defl"))u.indexOf(" ")>-1?i.paramDefl[n.slice(0,n.length-5)]=`"${u}"`:i.paramDefl[n.slice(0,n.length-5)]=u,i.explicitDefaults||(i.explicitDefaults=[]),i.explicitDefaults.push(n.slice(0,n.length-5));else if(e.U.endsWith(n,".shadow"))i._shadowOverrides||(i._shadowOverrides={}),i._shadowOverrides[n.slice(0,n.length-7)]=u;else if(e.U.endsWith(n,".fieldEditor"))i.paramFieldEditor||(i.paramFieldEditor={}),i.paramFieldEditor[n.slice(0,n.length-12)]=u;else if(e.U.contains(n,".fieldOptions.")){i.paramFieldEditorOptions||(i.paramFieldEditorOptions={});const e=n.slice(0,n.indexOf(".fieldOptions.")),t=n.slice(n.indexOf(".fieldOptions.")+14,n.length);i.paramFieldEditorOptions[e]||(i.paramFieldEditorOptions[e]={}),i.paramFieldEditorOptions[e][t]=u}else if(e.U.contains(n,".shadowOptions.")){i.paramShadowOptions||(i.paramShadowOptions={});const e=n.slice(0,n.indexOf(".shadowOptions.")),t=n.slice(n.indexOf(".shadowOptions.")+15,n.length);i.paramShadowOptions[e]||(i.paramShadowOptions[e]={}),i.paramShadowOptions[e][t]=u}else e.U.endsWith(n,".min")?(i.paramMin||(i.paramMin={}),i.paramMin[n.slice(0,n.length-4)]=u):e.U.endsWith(n,".max")?(i.paramMax||(i.paramMax={}),i.paramMax[n.slice(0,n.length-4)]=u):i[n]=u;return o=!0,"//% "}));for(let e of n)"string"==typeof i[e]&&(i[e]=parseInt(i[e]));for(let e of r)"string"==typeof i[e]&&(i[e]="true"==i[e]||"1"==i[e]);if(i.trackArgs&&(i.trackArgs=i.trackArgs.split(/[ ,]+/).map((e=>parseInt(e)||0))),i.enumInitialMembers&&(i.enumInitialMembers=i.enumInitialMembers.split(/[ ,]+/)),i.blockExternalInputs&&!i.inlineInputMode&&(i.inlineInputMode="external"),i.paramHelp={},i.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(i.paramHelp[t]=n,!i.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?i.paramDefl[t]=`"${e}"`:i.paramDefl[t]=e}}}return""})),i.jsDoc+=t,""))),i.jsDoc=i.jsDoc.trim(),i.async&&(i.callingConvention=1),i.promise&&(i.callingConvention=2),i.jres&&(i.whenUsed=!0),i.subcategories)try{i.subcategories=JSON.parse(i.subcategories)}catch(e){i.subcategories=void 0}if(i.groups)try{i.groups=JSON.parse(i.groups)}catch(e){i.groups=void 0}if(i.groupIcons)try{i.groupIcons=JSON.parse(i.groupIcons)}catch(e){i.groupIcons=void 0}if(i.groupHelp)try{i.groupHelp=JSON.parse(i.groupHelp)}catch(e){i.groupHelp=void 0}return a(i),i},e.parameterTypeIsArrowFunction=i,e.updateBlockDef=a,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 r=pxt.HF2.read32(e,t+4),i=pxt.HF2.read32(e,t+8);if(3&r)return pxt.log("invalid end marker position"),null;let a=1<<(255&i);if(a!=pxt.appTarget.compile.flashCodeAlign)return pxt.log("invalid page size: "+a),null;let o={magic:n,endMarkerPos:r,endMarker:i,regions:[]};for(let n=t+12;n<e.length-7;n+=8){let t={start:a*pxt.HF2.read16(e,n),length:a*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 r=e=>n[e]+(n[e+1]<<8)+(n[e+2]<<16)+(n[e+3]<<24)>>>0;if(!n||512!=n.length||r(0)!=t.UF2_MAGIC_START0||r(4)!=t.UF2_MAGIC_START1||r(n.length-4)!=t.UF2_MAGIC_END)return null;let i=r(8),a=r(16);a>476&&(a=256);let o=null,s=0,c=0;if(i&t.UF2_FLAG_FILE){let t=n.slice(32+a),i=t.indexOf(0);i>=0&&(t=t.slice(0,i)),o=e.U.fromUTF8Array(t),c=r(28)}return i&t.UF2_FLAG_FAMILY_ID_PRESENT&&(s=r(28)),{flags:i,targetAddr:r(12),payloadSize:a,blockNo:r(20),numBlocks:r(24),fileSize:c,familyId:s,data:n.slice(32,32+a),filename:o}}function r(e,t){return!!e&&(e.targetAddr<=t&&t<e.targetAddr+e.payloadSize)}function i(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 a(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)i(e.blocks[t],20,t),i(e.blocks[t],24,e.blocks.length),e.filename&&i(e.blocks[t],28,e.filesize)}function s(n,r,a,o=0){let c=n.currBlock,l=r>>8,u=256-(255&r);if(a.length>u){let e=new Uint8Array(a);for(s(n,r,e.slice(0,u));u<a.length;){let t=Math.min(u+256,a.length);s(n,r+u,e.slice(u,t)),u=t}return}if(l!=n.currPtr){c=null;for(let e=0;e<n.ptrs.length;++e)if(n.ptrs[e]==l){c=n.blocks[e];break}if(!c){c=new Uint8Array(512),n.filename?o|=t.UF2_FLAG_FILE:n.familyId&&(o|=t.UF2_FLAG_FAMILY_ID_PRESENT),i(c,0,t.UF2_MAGIC_START0),i(c,4,t.UF2_MAGIC_START1),i(c,8,o),i(c,12,l<<8),i(c,16,256),i(c,20,n.blocks.length),i(c,28,n.familyId),i(c,508,t.UF2_MAGIC_END);for(let e=32;e<288;++e)c[e]=255;n.filename&&e.U.memcpy(c,288,e.U.toUTF8Array(n.filename)),n.blocks.push(c),n.ptrs.push(l)}n.currPtr=l,n.currBlock=c}let d=32+(255&r);for(let e=0;e<a.length;++e)c[d+e]=a[e];n.filesize=Math.max(n.filesize,a.length+r)}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 r=0;r<e.length;r+=512){let i=n(e.slice(r,r+512));i&&t.push(i)}return t},t.toBin=function(e,t){if(e.length<512)return null;let r=-1,i=-1,a=[];for(let o=0;o<e.length;++o){let s=512*o,c=n(e.slice(s,s+512));if(!c)continue;if(t&&c.targetAddr+256>t)break;-1==r&&(r=c.targetAddr,i=r);let l=c.targetAddr-r;l<0||l%4||l>1048576||(l>0&&a.push(new Uint8Array(l)),a.push(e.slice(s+32,s+32+c.payloadSize)),r=c.targetAddr+c.payloadSize)}let o=0;for(let e of a)o+=e.length;if(0==o)return null;let s=new Uint8Array(o),c=0;for(let e of a)for(let t=0;t<e.length;++t)s[c++]=e[t];return{buf:s,start:i}},t.readBytes=function(e,t,n){let i,a=new Uint8Array(n);for(let o=0;o<n;++o,++t)r(i,t)||(i=e.filter((e=>r(e,t)))[0]),i&&(a[o]=i.data[t-i.targetAddr]);return a},t.newBlockFile=a,t.finalizeFile=o,t.concatFiles=function(t){for(let e of t)o(e),e.filename=null;let n=a();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 r of t.blocks)n+=e.Util.uint8ArrayToString(r);return n},t.readBytesFromFile=function t(n,r,i){let a,o=r>>8;if(o==n.currPtr)a=n.currBlock;else{for(let e=0;e<n.ptrs.length;++e)if(n.ptrs[e]==o){a=n.blocks[e];break}a&&(n.currPtr=o,n.currBlock=a)}if(!a)return null;let s=new Uint8Array(i),c=Math.min(i,256-(255&r));e.U.memcpy(s,0,a,32+(255&r),c);let l=i-c;if(l>0){let i=t(n,r+c,l);e.U.memcpy(s,c,i)}return s},t.writeBytes=s,t.writeHex=function(e,t){let n="0000";for(let r=0;r<t.length;++r){let i=/:02000004(....)/.exec(t[r]);if(i&&(n=i[1]),i=/^:..(....)00(.*)[0-9A-F][0-9A-F]$/.exec(t[r]),i){let t=parseInt(n+i[1],16),r=i[2],a=[];for(let e=0;e<r.length;e+=2)a.push(parseInt(r[e]+r[e+1],16));s(e,t,a)}}}}(c=e.UF2||(e.UF2={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){let n,r;!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={}));let i=!1,a=!1;function o(){if(void 0===r){if(e.BrowserUtils.hasWindow()){const t=/sandbox=1|#sandbox|#sandboxproject/i.test(window.location.href)||e.BrowserUtils.isIFrame(),o=/nosandbox=1/i.test(window.location.href),s=/controller=1/i.test(window.location.href)&&e.BrowserUtils.isIFrame(),c=/readonly=1/i.test(window.location.href),l=/editorlayout=(widget|sandbox|ide)/i.exec(window.location.href),u=/noproject=1/i.test(window.location.href);if(r=n.IDE,o?r=n.Widget:s?r=n.Controller:t&&(r=n.Sandbox),s&&c&&(i=!0),s&&u&&(a=!0),l)switch(l[1].toLowerCase()){case"widget":r=n.Widget;break;case"sandbox":r=n.Sandbox;break;case"ide":r=n.IDE}}else r=n.Sandbox;e.debug(`shell: layout type ${n[r]}, readonly ${c()}`)}}function s(){return o(),r==n.Sandbox}function c(){return!e.BrowserUtils.hasWindow()||s()&&!/[?&]edit=1/i.test(window.location.href)||l()&&i}function l(){return o(),r==n.Controller}t.layoutTypeClass=function(){return o(),e.shell.EditorLayoutType[r].toLowerCase()},t.isSandboxMode=s,t.isReadOnly=c,t.isNoProject=function(){return a},t.isControllerMode=l,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 r=t.result;e.oldVersion<1&&(r.createObjectStore(n.projectTable,{keyPath:n.projectKey}),r.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=>{var t;return null===(t=e)||void 0===t?void 0:t.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=>{var t;return null===(t=e)||void 0===t?void 0:t.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(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,r;!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"}(r=t.LengthUnit||(t.LengthUnit={}));class i{constructor(e){this.el=S(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=S("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=i;class a extends i{draw(e){const t=function(e){switch(e){case"text":return new d;case"circle":return new f;case"rect":return new p;case"line":return new _;case"polygon":return new h;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=a;t.SVG=class extends a{constructor(e){super("svg"),e&&e.appendChild(this.el)}define(e){return this.defs||(this.defs=new c(this.el)),e(this.defs),this}};class o extends a{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 c(this.el)}style(){return new l(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 s extends a{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=s;class c extends i{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 s;break;case"radialGradient":n=new x;break;case"linearGradient":n=new b;break;case"clipPath":n=new k;break;default:n=new i(e)}return n.id(t),this.el.appendChild(n.el),n}}t.DefsElement=c;class l extends i{constructor(e){super("style"),e.appendChild(this.el)}content(e){this.el.textContent=e}}t.StyleElement=l;class u extends a{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",C(e,t))}offset(e,t,n){return 0!==e&&this.setAttribute("dx",C(e,n)),0!==t&&this.setAttribute("dy",C(t,n)),this}anchor(e){return this.setAttribute("text-anchor",e)}}t.Text=d;class p extends u{constructor(){super("rect")}width(e,t=r.px){return this.setAttribute("width",C(e,t))}height(e,t=r.px){return this.setAttribute("height",C(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=r.px){return this.width(e,n),this.height(t,n),this}}t.Rect=p;class f 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=f;class _ extends u{constructor(){super("line")}at(e,t,n,r){return this.from(e,t),null!=n&&null!=r&&this.to(n,r),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=_;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 h extends m{constructor(){super("polygon")}}t.Polygon=h;class y extends u{constructor(){super("path"),this.d=new T}update(){return this.setAttribute("d",this.d.toAttribute())}path(e){return e(this.d),this.update()}}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=r.px){return this.setAttribute("width",C(e,t))}height(e,t=r.px){return this.setAttribute("height",C(e,t))}size(e,t,n=r.px){return this.width(e,n),this.height(t,n),this}};class v extends i{units(e){return this.setAttribute("gradientUnits",e===n.objectBoundingBox?"objectBoundingBox":"userSpaceOnUse")}stop(e,t,n){const r=S("stop");return r.setAttribute("offset",e+"%"),null!=t&&r.setAttribute("stop-color",t),null!=n&&r.setAttribute("stop-opacity",n),this.el.appendChild(r),this}}t.Gradient=v;class b 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=b;class x 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=x;class k extends a{constructor(){super("clipPath")}clipPathUnits(e){return e?this.setAttribute("clipPathUnits","objectBoundingBox"):this.setAttribute("clipPathUnits","userSpaceOnUse")}}function S(e){return document.createElementNS("http://www.w3.org/2000/svg",e)}t.ClipPath=k;class T{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,r,i,a){return this.op("C",e,t,n,r,i,a)}cCurveBy(e,t,n,r,i,a){return this.op("c",e,t,n,r,i,a)}qCurveTo(e,t,n,r){return this.op("Q",e,t,n,r)}qCurveBy(e,t,n,r){return this.op("q",e,t,n,r)}sCurveTo(e,t,n,r){return this.op("S",e,t,n,r)}sCurveBy(e,t,n,r){return this.op("s",e,t,n,r)}tCurveTo(e,t){return this.op("T",e,t)}tCurveBy(e,t){return this.op("t",e,t)}arcTo(e,t,n,r,i,a,o){return this.op("A",e,t,n,r?1:0,i?1:0,a,o)}arcBy(e,t,n,r,i,a,o){return this.op("a",e,t,n,r?1:0,i?1:0,a,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 C(e,t){switch(t){case r.em:return e+"em";case r.ex:return e+"ex";case r.px:return e+"px";case r.in:return e+"in";case r.cm:return e+"cm";case r.mm:return e+"mm";case r.pt:return e+"pt";case r.pc:return e+"pc";case r.percent:return e+"%";default:return e.toString()}}t.PathContext=T}(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,r){n()?e.addEventListener("pointerdown",r):t()?(e.addEventListener("mousedown",r),e.addEventListener("touchstart",r)):e.addEventListener("mousedown",r)},e.up=function(e,r){n()?e.addEventListener("pointerup",r):(t(),e.addEventListener("mouseup",r))},e.enter=function(e,r){n()?e.addEventListener("pointerover",(e=>{r(!!(1&e.buttons))})):t()?e.addEventListener("touchstart",(e=>{r(!0)})):e.addEventListener("mouseover",(e=>{r(!!(1&e.buttons))}))},e.leave=function(e,r){n()?e.addEventListener("pointerleave",r):t()?e.addEventListener("touchend",r):e.addEventListener("mouseleave",r)},e.move=function(e,r){n()?e.addEventListener("pointermove",r):t()?e.addEventListener("touchmove",r):e.addEventListener("mousemove",r)},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){e.IMAGE_MIME_TYPE="image/x-mkcd-f4",e.TILEMAP_MIME_TYPE="application/mkcd-tilemap",e.ANIMATION_MIME_TYPE="application/mkcd-animation";class t{constructor(){this.assets=[],this.takenNames={},this.listeners=[]}add(e){if(this.takenNames[e.id])return this.update(e.id,e);{const t=o(e);return this.takenNames[t.id]=!0,this.takenNames[u(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),o(t)}}getSnapshot(e){return e?this.assets.filter((t=>e(t))).map(o):this.assets.map(o)}update(e,t){let n;if(this.takenNames[e]){c(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[u(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&&o(t)}getByDisplayName(e){if(this.takenNames[e])for(const t of this.assets)if(t.meta.displayName===e||u(t)===e)return o(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)s(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 r of e.assets){n[r.internalID]=!0;const e=this.lookupByInternalID(r.internalID);e&&c(r,e)||(t.before.push(r),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 r=n?t.after:t.before,i=n?t.before:t.after;e.Util.assert(r.length===i.length);for(let e=0;e<r.length;e++)r[e]?(this.removeByInternalID(r[e].internalID),i[e]&&this.assets.push(i[e]),this.notifyListener(r[e].internalID)):(this.assets.push(i[e]),this.notifyListener(i[e].internalID));this.takenNames={};for(const t of this.assets)e.Util.assert(!this.takenNames[t.id]),this.takenNames[t.id]=!0,this.takenNames[u(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}}function n(t){const n=[];for(const r of Object.keys(t)){const i=t[r];i.mimeType===e.TILEMAP_MIME_TYPE&&n.push(i)}return n}function r(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 i(t){return e.sprite.Bitmap.fromData(t).copy().data()}function a(t,n){const r=atob(t.data),i=e.U.fromHex(r),a=i[1]|i[2]<<8,o=i[3]|i[4]<<8,s={tileWidth:i[0],tiles:t.tileset.map((e=>n&&n(e)||{id:e}))},c=i.slice(5,5+a*o),l=new e.sprite.Tilemap(a,o,0,0,new Uint8ClampedArray(c)),u=i.slice(5+c.length),d=new e.sprite.Bitmap(a,o,0,0,new Uint8ClampedArray(u)).data();return new e.sprite.TilemapData(l,s,d)}function o(e){switch(e.meta=Object.assign({},e.meta),e.type){case"tile":case"image":return Object.assign(Object.assign({},e),{bitmap:i(e.bitmap)});case"animation":return Object.assign(Object.assign({},e),{frames:e.frames.map((e=>i(e)))});case"tilemap":return Object.assign(Object.assign({},e),{data:e.data.cloneData()})}}function s(t,n){const r=t.id.substr(t.id.lastIndexOf(".")+1);switch(t.type){case"image":n[r]=t.jresData,t.meta.displayName&&(n[r]={data:t.jresData,mimeType:e.IMAGE_MIME_TYPE,displayName:t.meta.displayName});break;case"tile":n[r]={data:t.jresData,mimeType:e.IMAGE_MIME_TYPE,tilemapTile:!0,displayName:t.meta.displayName};break;case"tilemap":const i=function(t,n,r){const i=t.tilemap.data(),a=new Uint8ClampedArray(5+i.data.length+t.layers.data.length);return a[0]=t.tileset.tileWidth,a[1]=255&i.width,a[2]=i.width>>8&255,a[3]=255&i.height,a[4]=i.height>>8&255,a.set(i.data,5),a.set(t.layers.data,5+i.data.length),{id:n,mimeType:e.TILEMAP_MIME_TYPE,data:btoa(e.sprite.uint8ArrayToHex(a)),tileset:t.tileset.tiles.map((e=>e.id)),displayName:r}}(t.data,t.id,t.meta.displayName);n[i.id]=i;break;case"animation":n[r]=function(t){return{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}}(t)}}function c(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 r=n;return t.interval===r.interval&&e.U.arrayEquals(t.frames,r.frames,e.sprite.bitmapEquals);case"tilemap":return t.data.equals(n.data)}}function l(e){const t=/^\s*(?:(?:assets\s*\.\s*(image|tile|animation|tilemap))|(tilemap))\s*(?:`|\(""")([^`"]+)(?:`|"""\))\s*$/m.exec(e);if(t){return{type:t[1]||t[2],name:t[3].trim()}}}function u(e){return d(e.type,e.id)}function d(t,n,r=!1){let i;switch(t){case"image":i=e.sprite.IMAGES_NAMESPACE+".";break;case"tile":i=e.sprite.TILE_NAMESPACE+".";break;case"tilemap":i="";break;case"animation":i=e.sprite.ANIMATION_NAMESPACE+"."}if(i)if(n.startsWith(i)){const e=n.substr(i.length);if(-1===e.indexOf("."))return e}else if(!r)return null;return n}function p(t){const n=atob(t.data),r=new Uint8ClampedArray(e.U.fromHex(n)),i=f(r,0),a=f(r,2),o=f(r,4),s=f(r,6),c=Math.ceil(a*o/2);let l=8;const u=[];for(let e=0;e<s;e++){const e=r.slice(l,l+c);u.push({x0:0,y0:0,width:a,height:o,data:e}),l+=c}let d=t.id;return d.startsWith(t.namespace)||(d=t.namespace+"."+d,d=d.replace(/\.\./g,".")),{type:"animation",internalID:0,id:d,interval:i,frames:u,meta:{displayName:t.displayName}}}function f(e,t){return e[t]|e[t+1]<<8}e.TilemapProject=class{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},this.state={revision:this.nextID++,tilemaps:new t,tiles:new t,animations:new t,images:new t},this.gallery={revision:0,tilemaps:new t,tiles:new t,animations:new t,images:new t},this.undoStack=[],this.redoStack=[]}getNewInternalId(){return this.nextInternalID++}createNewImage(t=16,n=16){const r=this.generateNewID("image"),i=new e.sprite.Bitmap(t,n).data(),a={internalID:this.getNewInternalId(),id:r,type:"image",bitmap:i,meta:{},jresData:e.sprite.base64EncodeBitmap(i)};return this.state.images.add(a)}createNewAnimation(t=16,n=16){const r=this.generateNewID("animation"),i=new e.sprite.Bitmap(t,n).data(),a={internalID:this.getNewInternalId(),id:r,type:"animation",frames:[i],interval:500,meta:{}};return this.state.animations.add(a)}createNewAnimationFromData(e,t=500,n){const r=this.generateNewID("animation"),i={internalID:this.getNewInternalId(),id:r,type:"animation",frames:e,interval:t,meta:{displayName:n}};return this.state.animations.add(i)}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 r=this.state.tiles.getSnapshot((e=>e.bitmap.width===t));return 0===r.length?n?(this.createNewTile(new e.sprite.Bitmap(t,t).data()),this.getProjectTiles(t,!1)):null:{tileWidth:t,tiles:r}}createNewTile(t,n,r){this.onChange(),n&&!this.isNameTaken("tile",n)||(n=this.generateNewID("tile"));const i={internalID:this.getNewInternalId(),id:n,type:"tile",jresData:e.sprite.base64EncodeBitmap(t),bitmap:t,meta:{displayName:r},isProjectTile:!0};return this.state.tiles.add(i)}createNewProjectImage(t,n){this.onChange();const r={internalID:this.getNewInternalId(),id:this.generateNewID("image"),type:"image",jresData:e.sprite.base64EncodeBitmap(t),meta:{displayName:n},bitmap:t};return this.state.images.add(r)}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),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 r=Object.assign(Object.assign({},n),{data:t});return this.state.tilemaps.update(e,r),r}return null}createNewTilemap(e,t,n=16,r=16){return this.createNewTilemapFromData(this.blankTilemap(t,n,r),e)}blankTilemap(t,n=16,r=16){const i=new e.sprite.Tilemap(n,r),a=new e.sprite.Bitmap(n,r),o={tileWidth:t,tiles:[this.getTransparency(t)]};return new e.sprite.TilemapData(i,o,a.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 r=this.state.tiles.getByID(n);if(!r){const i=new e.sprite.Bitmap(t,t).data();return r={internalID:this.getNewInternalId(),id:n,type:"tile",bitmap:i,jresData:e.sprite.base64EncodeBitmap(i),meta:{},isProjectTile:!0},this.state.tiles.add(r)}return r}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: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()}}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.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.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)}),this.committedState=this.cloneState(),this.cleanupTemporaryAssets())}revision(){return this.state.revision}encodeTilemap(t,n){const r=t.tilemap.data(),i=new Uint8ClampedArray(5+r.data.length+t.layers.data.length);return i[0]=t.tileset.tileWidth,i[1]=255&r.width,i[2]=r.width>>8&255,i[3]=255&r.height,i[4]=r.height>>8&255,i.set(r.data,5),i.set(t.layers.data,5+r.data.length),{id:n,mimeType:e.TILEMAP_MIME_TYPE,data:btoa(e.sprite.uint8ArrayToHex(i)),tileset:t.tileset.tiles.map((e=>e.id))}}forceUpdate(){this.onChange()}isNameTaken(e,t){const n=t=>{switch(e){case"image":return this.state.images.isIDTaken(t)||this.gallery.images.isIDTaken(t);case"tile":return this.state.tiles.isIDTaken(t)||this.gallery.tiles.isIDTaken(t);case"tilemap":return this.state.tilemaps.isIDTaken(t)||this.gallery.tilemaps.isIDTaken(t);case"animation":return this.state.animations.isIDTaken(t)||this.gallery.animations.isIDTaken(t)}},r=d(e,t),i=r&&r!==t;return n(t)||i&&n(r)}isAssetUsed(t,n,r){var i,a,o;if(((null===(a=null===(i=t.meta)||void 0===i?void 0:i.blockIDs)||void 0===a?void 0:a.filter((e=>!r||(null==r?void 0:r.indexOf(e))<0)))||[]).length>0)return!0;if("tile"==t.type)for(const e of this.getAssets("tilemap"))if(!((null==r?void 0:r.indexOf(e.id))>=0)&&e.data.tileset.tiles.some((e=>e.id===t.id)))return!0;if(n){const i=e.Util.escapeForRegex(u(t)),a=e.Util.escapeForRegex(null===(o=t.meta)||void 0===o?void 0:o.displayName)||"";let s;switch(t.type){case"tile":s=`myTiles.${i}|assets.tile\`${i}\``,a&&(s+=`|assets.tile\`${a}\``);break;case"tilemap":s=`tilemap\`${i}\``;break;case"animation":s=`assets.animation\`${i}\``,a&&(s+=`|assets.animation\`${a}\``);break;default:s=`assets.image\`${i}\``,a&&(s+=`|assets.image\`${a}\``)}const c=new RegExp(s,"gm");let l;switch(t.type){case"tile":l=`myTiles.${i}|assets.tile("""${i}""")`,a&&(l+=`|assets.tile("""${a}""")`);break;case"tilemap":l=`assets.tilemap("""${i}""")`;break;case"animation":l=`assets.animation("""${i}""")`,a&&(l+=`|assets.animation("""${a}""")`);break;default:l=`assets.image("""${i}""")`,a&&(l+=`|assets.image("""${a}""")`)}const d=new RegExp(l,"gm");for(let e of Object.keys(n)){if((null==r?void 0:r.indexOf(e))>=0)continue;const t=n[e];if(e.match(/((?!\.g).{2}|^.{0,1})\.ts$/i)){if(t.content.match(c))return!0}else if(e.endsWith(".py")&&t.content.match(d))return!0}}return!1}lookupAsset(e,t){switch(e){case"image":return this.state.images.getByID(t)||this.gallery.images.getByID(t);case"tile":return this.state.tiles.getByID(t)||this.gallery.tiles.getByID(t);case"tilemap":return this.state.tilemaps.getByID(t)||this.gallery.tilemaps.getByID(t);case"animation":return this.state.animations.getByID(t)||this.gallery.animations.getByID(t)}}lookupAssetByName(e,t){switch(e){case"image":return this.state.images.getByDisplayName(t);case"tile":return this.state.tiles.getByDisplayName(t);case"tilemap":return this.state.tilemaps.getByDisplayName(t);case"animation":return this.state.animations.getByDisplayName(t)}}getAssets(e){switch(e){case"image":return this.state.images.getSnapshot();case"tile":return this.state.tiles.getSnapshot();case"tilemap":return this.state.tilemaps.getSnapshot();case"animation":return this.state.animations.getSnapshot()}}getGalleryAssets(e){switch(e){case"image":return this.gallery.images.getSnapshot();case"tile":return this.gallery.tiles.getSnapshot();case"tilemap":return this.gallery.tilemaps.getSnapshot();case"animation":return this.gallery.animations.getSnapshot()}}lookupBlockAsset(e,t){let n=e=>{var n,r;return-1!==(null===(r=null===(n=e.meta)||void 0===n?void 0:n.blockIDs)||void 0===r?void 0:r.indexOf(t))};switch(e){case"image":return this.state.images.getSnapshot(n)[0];case"tile":return this.state.tiles.getSnapshot(n)[0];case"tilemap":return this.state.tilemaps.getSnapshot(n)[0];case"animation":return this.state.animations.getSnapshot(n)[0]}}updateAsset(e){switch(this.onChange(),e.type){case"image":return this.state.images.update(e.id,e);case"tile":return this.updateTile(e);case"tilemap":return this.state.tilemaps.update(e.id,e);case"animation":return this.state.animations.update(e.id,e)}}duplicateAsset(e,t){var n;this.onChange();const r=o(e),i=t||(null===(n=r.meta)||void 0===n?void 0:n.displayName);let a;switch(e.type){case"image":a=this.createNewProjectImage(r.bitmap,i);break;case"tile":a=this.createNewTile(r.bitmap,null,i);break;case"tilemap":const[e,t]=this.createNewTilemapFromData(r.data,i);a=this.getTilemap(e);break;case"animation":a=this.createNewAnimationFromData(r.frames,r.interval,i)}return a}removeAsset(e){switch(this.onChange(),e.type){case"image":return this.state.images.removeByID(e.id);case"tile":return this.state.tiles.removeByID(e.id);case"tilemap":return this.state.tilemaps.removeByID(e.id);case"animation":return this.state.animations.removeByID(e.id)}}addChangeListener(e,t){switch(e.type){case"image":this.state.images.addListener(e.internalID,t);break;case"tile":this.state.tiles.addListener(e.internalID,t);break;case"tilemap":this.state.tilemaps.addListener(e.internalID,t);break;case"animation":this.state.animations.addListener(e.internalID,t)}}removeChangeListener(e,t){switch(e){case"image":this.state.images.removeListener(t);break;case"tile":this.state.tiles.removeListener(t);break;case"tilemap":this.state.tilemaps.removeListener(t);break;case"animation":this.state.animations.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 e of n)"tile"===e.type?t?this.state.tiles.add(e):this.gallery.tiles.add(e):"image"===e.type?t?this.state.images.add(e):this.gallery.images.add(e):t?this.state.animations.add(e):this.gallery.animations.add(e)}for(const t of n(e.parseJRes()))this.state.tilemaps.add({internalID:this.getNewInternalId(),type:"tilemap",id:t.id,meta:{displayName:t.displayName||t.id},data:a(t,(e=>this.resolveTile(e)))});this.committedState=this.cloneState(),this.undoStack=[],this.redoStack=[]}loadTilemapJRes(t,r=!1){t=e.inflateJRes(t);const i=this.readImages(t,!0).filter((e=>"tile"===e.type));let o={};for(const e of i){if(r){const t=this.resolveTileByBitmap(e.bitmap);if(t){o[e.id]=t.id;continue}}const t=this.createNewTile(e.bitmap,e.id,e.meta.displayName);t.id!==e.id&&(o[e.id]=t.id)}for(const e of n(t))this.state.tilemaps.add({internalID:this.getNewInternalId(),type:"tilemap",id:e.id,meta:{displayName:e.displayName||e.id},data:a(e,(e=>(o[e]&&(e=o[e]),this.resolveTile(e))))})}loadAssetsJRes(t){t=e.inflateJRes(t);const n=[];for(const r of Object.keys(t)){const i=t[r];if(i.tilemapTile)this.state.tiles.add(this.generateImage(i,"tile"));else if(i.mimeType===e.IMAGE_MIME_TYPE)this.state.images.add(this.generateImage(i,"image"));else if(i.mimeType===e.ANIMATION_MIME_TYPE){const[e,t]=this.generateAnimation(i);t?n.push(e):this.state.animations.add(e)}}for(const e of n)this.state.animations.add(this.inflateAnimation(e,this.state.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))))})),r=[];for(const t of n)1===t.meta.blockIDs.length?r.push(t):(t.meta.blockIDs=t.meta.blockIDs.filter((t=>-1!==e.indexOf(t))),0===t.meta.blockIDs.length&&r.push(t));for(const e of r)t.removeByID(e.id)}t(this.state.images),t(this.state.tiles),t(this.state.tilemaps),t(this.state.animations)}generateImage(t,n){return{internalID:this.getNewInternalId(),type:n,id:t.id,meta:{displayName:t.displayName},jresData:t.data,bitmap:e.sprite.getBitmapFromJResURL(`data:${e.IMAGE_MIME_TYPE};base64,${t.data}`).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},id:e.id,frames:[],frameIds:t.frames,interval:100,flippedHorizontal:t.flippedHorizontal},!0]}return[Object.assign(Object.assign({},p(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),r=new e.sprite.Bitmap(t.width,t.height);for(let e=0;e<r.width;e++)for(let t=0;t<r.height;t++)r.set(e,t,n.get(n.width-e-1,t));return r.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"))}}generateNewIDInternal(e,t,n){t=t.replace(/\d+$/,"");const r=n?n+"."+t:t;let i=1;for(;this.isNameTaken(e,r+i);)++i;return r+i}onChange(){this.needsRebuild=!0,this.state.revision=this.nextID++}readImages(t,n=!1){const r=[],i=[];for(const a of Object.keys(t)){const o=t[a];if(o.tilemapTile){const e=this.generateImage(o,"tile");e.isProjectTile=n,r.push(e)}else if(o.mimeType===e.IMAGE_MIME_TYPE)r.push(this.generateImage(o,"image"));else if(o.mimeType===e.ANIMATION_MIME_TYPE){const[e,t]=this.generateAnimation(o);t?i.push(e):r.push(e)}}for(const e of i)r.push(this.inflateAnimation(e,r));return r}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)}},e.emitTilemapsFromJRes=function(t){const n=Object.keys(t);let i="";const o=[],s=[];for(const r of n){if("*"===r)continue;const n=t[r];if(n.tilemapTile&&(i+=" //% fixedInstance jres blockIdentity=images._tile\n",i+=` export const ${r} = image.ofBuffer(hex\`\`);\n`,s.push({keys:[n.displayName,d("tile",r,!0)],expression:r})),n.mimeType===e.TILEMAP_MIME_TYPE){const t=a(n);o.push({keys:[n.displayName,d("tilemap",n.id)],expression:e.sprite.encodeTilemap(t,"typescript")})}}o.length&&(i+=r("tilemap",o)),s.length&&(i+=r("tile",s));const c=lf("Auto-generated code. Do not edit.");return`// ${c}\nnamespace ${e.sprite.TILE_NAMESPACE} {\n${i}\n}\n// ${c}\n`},e.emitProjectImages=function(t){const n=Object.keys(t);let i="";const a=[],o=[];for(const r of n){if("*"===r)continue;const n=t[r];if("string"==typeof n||n.mimeType===e.IMAGE_MIME_TYPE){let t,i=[d("image",r,!0)];"string"==typeof n?t=e.sprite.bitmapToImageLiteral(e.sprite.getBitmapFromJResURL(n),"typescript"):(t=e.sprite.bitmapToImageLiteral(e.sprite.getBitmapFromJResURL(n.data),"typescript"),i.push(n.displayName)),a.push({keys:i,expression:t})}else if(n.mimeType===e.ANIMATION_MIME_TYPE){const t=p(n);o.push({keys:[n.displayName,d("animation",r,!0)],expression:`[${t.frames.map((t=>e.sprite.bitmapToImageLiteral(e.sprite.Bitmap.fromData(t),"typescript"))).join(", ")}]`})}}const s=lf("Auto-generated code. Do not edit.");return i+=r("image",a),i+=r("animation",o),`// ${s}\nnamespace ${e.sprite.IMAGES_NAMESPACE} {\n${i}\n}\n// ${s}\n`},e.cloneAsset=o,e.assetEquals=c,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 r;if(r=(null===(n=e.meta)||void 0===n?void 0:n.displayName)?e.meta.displayName:u(e),!r)return"image"===e.type||"tile"===e.type?e.id:void 0;const i=t?'("""':"`",a=t?'""")':"`";switch(e.type){case"tile":return`assets.tile${i}${r}${a}`;case"image":return`assets.image${i}${r}${a}`;case"animation":return`assets.animation${i}${r}${a}`;case"tilemap":return`tilemap${i}${r}${a}`}},e.parseAssetTSReference=l,e.lookupProjectAssetByTSReference=function(e,t){const n=l(e);if(n){const{type:e,name:r}=n;switch(e){case"tile":return t.lookupAssetByName("tile",r);case"image":return t.lookupAssetByName("image",r);case"tilemap":return t.lookupAssetByName("tilemap",r)||t.lookupAsset("tilemap",r);case"animation":return t.lookupAssetByName("animation",r)}}},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");default:return lf("asset")}},e.getShortIDForAsset=u}(pxt||(pxt={})),function(e){!function(t){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 n="";function r(e){const t=function(e,t,n){let r=0,i=0,a=0;if(0==t)r=n,i=n,a=n;else{let o=Math.floor(e/60),s=e/60-o,c=n*(1-t),l=n*(1-t*s),u=n*(1-t*(1-s));switch(o){case 1:r=l,i=n,a=c;break;case 2:r=c,i=n,a=u;break;case 3:r=c,i=l,a=n;break;case 4:r=u,i=c,a=n;break;case 5:r=n,i=c,a=l;break;case 6:case 0:r=n,i=u,a=c}}return[Math.floor(r),Math.floor(i),Math.floor(a)]}(e,.45,165.75);return`#${i(t[0])}${i(t[1])}${i(t[2])}`}function i(e){const t=e.toString(16);return 1==t.length?"0"+t:t}t.appendToolboxIconCss=function(t,r){if(!(n.indexOf(t)>-1))if(1===r.length){const i=e.Util.unicodeToChar(r);n+=`\n .blocklyTreeIcon.${t}::before {\n content: "${i}";\n }\n `}else n+=`\n .blocklyTreeIcon.${t} {\n background-image: url("${e.Util.pathJoin(e.webConfig.commitCdnUrl,encodeURI(r))}")!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){return t=t.toLowerCase(),e.appTarget.appTheme.blockColors&&e.appTarget.appTheme.blockColors[t]?e.appTarget.appTheme.blockColors[t]:e.toolbox.blockColors[t]?e.toolbox.blockColors[t]:""},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:r(n)},t.hueToRgb=r,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 r="#";for(let i=0;i<3;i++){let a=parseInt(e.substr(2*i,2),16);a=Math.round(Math.min(Math.max(0,n?a+a*t:a-a*t),255));let o=a.toString(16);r+=("00"+o).substr(o.length)}return r}}(e.toolbox||(e.toolbox={}))}(pxt||(pxt={})),function(e){!function(t){const n=/^##[^#](.*)$([\s\S]*?)(?=^##[^#]|$(?![\r\n]))/gim,r=/^###[^#](.*)$([\s\S]*?)(?=^###[^#]|$(?![\r\n]))/gim;function i(){return/``` *(sim|block|blocks|filterblocks|spy|ghost|typescript|ts|js|javascript|template|python|jres|assetjson|customts|tutorialValidationRules|requiredTutorialBlock)\s*\n([\s\S]*?)\n```/gim}function a(t,r,i){let a=r||n,s=[];if(t.replace(a,(function(e,t,n){n=n.trim();let{header:r,hint:a,requiredBlocks:c}=function(e,t,n){let r,i,a=e=o(e);if(t){const t=/#+ ~ tutorialhint([\s\S]*)/i;a=e.replace(t,(function(e,t){return r=t,""}))}else{const t=/(^[\s\S]*?\S)\s*((```|\[?\!\[[\s\S]+?\]\(\S+?\)\]?)[\s\S]*)/im;let o=e.match(t);if(o&&o.length>2&&(a=o[1].trim(),r=o[2].trim(),n)){let e=o[2].trim();e=e.replace(/``` *(requiredTutorialBlock)\s*\n([\s\S]*?)\n```/gim,(function(e,t,n){return i=`{\n${n}\n}`,""})),r=e}}return{header:a,hint:r,requiredBlocks:i}}(n,i&&i.explicitHints,i.tutorialCodeValidation);let l={title:t.match(/^\{.*\}$/)?void 0:t.replace(/@(fullscreen|unplugged|showdialog|showhint|tutorialCompleted|resetDiff)/gi,"").trim(),contentMd:n,headerContentMd:r};return/@(fullscreen|unplugged|showdialog|showhint)/i.test(t)&&(l.showHint=!0),/@(unplugged|showdialog)/i.test(t)&&(l.showDialog=!0),/@tutorialCompleted/.test(t)&&(l.tutorialCompleted=!0),/@resetDiff/.test(t)&&(l.resetDiff=!0),a&&(l.hintContentMd=a),i.tutorialCodeValidation&&c&&(l.requiredBlockMd=c),s.push(l),""})),0!=t.indexOf("# Not found"))return s;e.debug("tutorial not found")}function o(e){if(!e)return e;return e.replace(/```(filterblocks|package|ghost|config|template|jres|assetjson|customts)\s*\n([\s\S]*?)\n```/gim,"").trim()}function s(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]}}t.parseTutorial=function(t){const{metadata:i,body:c}=function(t){const n=/### @(\S+) ([ \S]+)/gi,r={},i=t.replace(n,(function(e,t,n){try{r[t]=JSON.parse(n)}catch(e){r[t]=n}return""})),a=r;void 0!==a.explicitHints&&e.appTarget.appTheme&&e.appTarget.appTheme.tutorialExplicitHints&&(a.explicitHints=!0);return{metadata:a,body:i}}(t),{steps:l,activities:u}=function(e,t){if(t&&t.activities)return function(e,t){let i=[],o=[];return e.replace(n,(function(e,n,s){let c=o.length;o.push({name:n||lf("Activity {0}",c),step:i.length});let l=a(s,r,t);return l=l.map((e=>(e.activity=c,e))),i=i.concat(l),""})),{steps:i,activities:o}}(e,t);{let n=a(e,null,t);return(!n||n.length<1)&&(n=a(e,r,t)),{steps:n,activities:null}}}(c,i),d=function(e){let t=e.match(/^#[^#](.*)$/im);return t&&t.length>1?t[1].trim():null}(c);if(!l)return;const{code:p,templateCode:f,editor:_,language:m,jres:g,assetJson:h,customTs:y,tutorialValidationRulesStr:v}=function(t){let n;const r=/``` *(sim|block|blocks|filterblocks|spy|ghost|typescript|ts|js|javascript|template|python|jres|assetjson|customts|tutorialValidationRules|requiredTutorialBlock)\s*\n([\s\S]*?)\n```/gim;let i,a,o,s,c,l,u=[];return t.replace(/((?!.)\s)+/g,"\n").replace(r,(function(t,n,r){switch(n){case"block":case"blocks":case"requiredTutorialBlock":case"filterblocks":if(!d(e.BLOCKS_PROJECT_NAME))return;break;case"spy":case"python":if(!d(e.PYTHON_PROJECT_NAME))return;"python"==n&&(o=n);break;case"typescript":case"ts":case"javascript":case"js":if(!d(e.JAVASCRIPT_PROJECT_NAME))return;break;case"template":a=r;break;case"jres":i=r;break;case"assetjson":s=r;break;case"customts":c=r,r="";break;case"tutorialValidationRules":l=r}return u.push("python"==n?`\n${r}\n`:`{\n${r}\n}`),""})),n=n||e.BLOCKS_PROJECT_NAME,{code:u,templateCode:a,editor:n,language:o,jres:i,assetJson:s,customTs:c,tutorialValidationRulesStr:l};function d(t){return n&&n!=t?(e.debug("tutorial ambiguous: contains snippets of different types"),!1):(n=t,!0)}}(c);let b;i.tutorialCodeValidation&&(b=e.Util.jsonTryParse(v),function(t,n){const r=Object.keys(t);for(let i=0;i<r.length;i++){const a={ruleName:r[i],enabled:t[r[i]]?"true":"false",tutorial:n};e.tickEvent("tutorial.validation.setValidationRules",a)}}(b,d)),(!0===i.diffs||!1!==i.diffs&&!0!==i.noDiffs&&(_==e.BLOCKS_PROJECT_NAME&&e.appTarget.appTheme.tutorialBlocksDiff||_!=e.BLOCKS_PROJECT_NAME&&e.appTarget.appTheme.tutorialTextDiff))&&function(e,t){let n;function r(e){const t={typescript:"diff",spy:"diffspy",blocks:"diffblocks",python:"diff"},r=/\s*(\/\/|#)\s*@highlight/gm;return e?e.replace(/```(typescript|spy|python|blocks|ghost|template)((?:.|[\r\n])+)```/,(function(e,i,a){const o=n,s=/^(template|ghost)$/.test(i),c=r.test(a);return a=a.replace(/^\n+/,"").replace(/\n+$/,""),c&&(a=a.replace(r,"")),n=a,!o||c||s?e:`\`\`\`${t[i]}\n${o}\n----------\n${a}\n\`\`\``})):e}e.forEach(((e,i)=>{if((e.resetDiff||t&&t.find((e=>e.step==i)))&&(n=void 0),e.hintContentMd){const t=r(e.hintContentMd);if(t&&t!=e.hintContentMd)return void(e.hintContentMd=t)}if(e.headerContentMd){const t=r(e.headerContentMd);if(t&&t!=e.headerContentMd)return void(e.headerContentMd=t)}}))}(l,u);const x=s(h);return l.forEach((e=>{e.contentMd=o(e.contentMd),e.headerContentMd=o(e.headerContentMd),e.hintContentMd=o(e.hintContentMd),e.requiredBlockMd=o(e.requiredBlockMd)})),{editor:_,title:d,steps:l,activities:u,code:p,templateCode:f,metadata:i,language:m,jres:g,assetFiles:x,customTs:y,tutorialValidationRules:b}},t.getMetadataRegex=i,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 r=n[t];if(/@highlight/.test(r)){if(r=n[++t],void 0!==r){const t=document.createElement("span");t.className="highlight-line",t.textContent=r,e.appendChild(t)}}else e.appendChild(document.createTextNode(r))}},t.getTutorialOptions=function(t,n,r,i,a){var o;const s=e.tutorial.parseTutorial(t);if(!s)throw new Error(lf("Invalid tutorial format"));return{options:{tutorial:n,tutorialName:s.title||r,tutorialReportId:i,tutorialStep:0,tutorialReady:!0,tutorialHintCounter:0,tutorialStepInfo:s.steps,tutorialActivityInfo:s.activities,tutorialMd:t,tutorialCode:s.code,tutorialRecipe:!!a,templateCode:s.templateCode,autoexpandStep:!(null===(o=s.metadata)||void 0===o?void 0:o.autoexpandOff),metadata:s.metadata,language:s.language,jres:s.jres,assetFiles:s.assetFiles,customTs:s.customTs,tutorialValidationRules:s.tutorialValidationRules},editor:s.editor}},t.parseCachedTutorialInfo=function(t,n){let r=e.Util.jsonTryParse(t);return r?e.BrowserUtils.tutorialInfoDbAsync().then((e=>{if(n&&r[n]){const t=r[n];t.usedBlocks&&t.hash&&e.setWithHashAsync(n,t.snippetBlocks,t.hash)}else for(let t of Object.keys(r)){const n=r[t];n.usedBlocks&&n.hash&&e.setWithHashAsync(t,n.snippetBlocks,n.hash)}})).catch((e=>{})):Promise.resolve()},t.resolveLocalizedMarkdown=function(t,n,r){const i=(r||t.fileName||"README")+".md";let a;const[o,s,c]=e.Util.normalizeLanguageCode(e.Util.userLanguage());return a=o&&s&&c?n[`_locales/${o}/${i}`]||n[`_locales/${c}/${i}`]||n[`_locales/${s}/${i}`]:n[`_locales/${o}/${i}`],a=a||n[i],a},t.parseAssetJson=s}(e.tutorial||(e.tutorial={}))}(pxt||(pxt={})),function(e){!function(t){function n(t,n){const{tutorialStep:r}=t,i=t.tutorialStepInfo[r].requiredBlockMd,a=e.BrowserUtils.getTutorialCodeHash([i]);let o={};return null!=n&&(o=n[a]),o}function r(e,t,n){n.isStrict=!0;const r=Object.keys(e);let i=[],a=[];null!=t&&(i=Object.keys(t));let o=r.length>=i.length;const s=lf("These are the blocks you seem to be missing:");for(let n=0;n<i.length;n++){let r=i[n];(!e[r]||e[r]<t[r])&&(a.push(r),o=!1)}return n.ruleMessage=s,n.ruleStatus=o,n.blockIds=a,n}function i(e,t,n){const r=Object.keys(e),i=Object.keys(null!=t?t:{});let a=r.length>=i.length;for(let t=0;t<i.length;t++){if(!e[i[t]]){a=!1;break}}return n.ruleStatus=a,n}function a(e,t,n){n.isStrict=!0;Object.keys(e);let r=[],i=[];null!=t&&(r=Object.keys(t));let a=!0;const o=lf("You are required to have the following block:");for(let t=0;t<r.length;t++){let n=r[t];e[n]||(i.push(n),a=!1)}return n.ruleMessage=o,n.ruleStatus=a,n.blockIds=i,n}t.validate=async function(t,o,s){let c=function(e){let t=[];if(null!=e){const n=Object.keys(e);for(let r=0;r<n.length;r++){const i=n[r],a={ruleName:i,ruleTurnOn:e[i]};t.push(a)}}return t}(t.tutorialValidationRules);if(c.length>0&&o.length>0){const s=function(e){let t={};for(let n=0;n<e.length;n++)t[e[n]]||(t[e[n]]=0),t[e[n]]=t[e[n]]+1;return t}(o.map((e=>e.type))),{tutorialStepInfo:l,tutorialStep:u}=t,d=(l[u],await function(t,n){return e.BrowserUtils.tutorialInfoDbAsync().then((e=>e.getAsync(t.tutorial,t.tutorialCode).then((e=>(null==e?void 0:e.snippets)?Promise.resolve(e.snippets):Promise.resolve(void 0)))))}(t)),p=function(t,n){const{tutorialStepInfo:r,tutorialStep:i}=t,a=t.tutorialStepInfo[i].hintContentMd;let o="";null!=a&&a.replace(/((?!.)\s)+/g,"\n").replace(/``` *(block|blocks)\s*\n([\s\S]*?)\n```/gim,(function(e,t,n){return o=`{\n${n}\n}`,""}));const s=e.BrowserUtils.getTutorialCodeHash([o]);let c={};null!=n&&(c=n[s]);return c}(t,d);for(let e=0;e<c.length;e++){let o=c[e];const l=c[e].ruleName;if(c[e].ruleTurnOn)switch(l){case"exact":o=r(s,p,o);break;case"atleast":o=i(s,p,o);break;case"required":o=a(s,n(t,d),o)}}}return c}}(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,r="",i=0;for(;n;){if(i){r+=t;for(let e=0;e<i;e++)r+=" "}r+=n.messageText,i++,n=n.next}return r}},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&&s(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?c(e,i):c(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 r=n.replace(/\s+/g,"_").replace(/[^a-zA-Z0-9_$]/g,(t=>e.pxtc.isIdentifierPart(t.charCodeAt(0),e.pxtc.ScriptTarget.ES5)?t:""));return r&&e.pxtc.isIdentifierStart(r.charCodeAt(0),e.pxtc.ScriptTarget.ES5)&&-1===t.reservedWords.indexOf(r)||(r="_"+r),r};const r=[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],i=[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],a=[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 s(e,t){return t>=n.ES5?c(e,r):c(e,a)}function c(e,t){if(e<t[0])return!1;let n,r=0,i=t.length;for(;r+1<i;){if(n=r+(i-r)/2,n-=n%2,t[n]<=e&&e<=t[n+1])return!0;e<t[n]?i=n:r=n+2}return!1}let l;t.isUnicodeIdentifierStart=s,function(e){e[e.Warning=0]="Warning",e[e.Error=1]="Error",e[e.Message=2]="Message"}(l=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 r(){return!!navigator&&!!navigator.bluetooth&&!!e.appTarget.appTheme.bluetoothPartialFlashing}t.isAvailable=function(){return n()||r()},t.hasConsole=n,t.hasPartialFlash=r,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 i{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=i;class a extends i{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((r=>(this.debug(`reconnect error ${r.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=a;class o extends a{constructor(e,t,n,r){super(e,t,!0),this.device=t,this.serviceUUID=n,this.txCharacteristicUUID=r,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 s extends o{constructor(e){super("hf2",e,s.SERVICE_UUID,s.CHARACTERISTIC_TX_UUID),this.device=e}handlePacket(e){const t=e.getUint8(0);switch(192&t){case s.BLEHF2_FLAG_SERIAL_OUT:case s.BLEHF2_FLAG_SERIAL_ERR:const n=Math.min(e.byteLength-1,-193&t);let r="";for(let t=0;t<n;++t)r+=String.fromCharCode(e.getUint8(t+1));r&&window.postMessage({type:"serial",id:this.device.name||"hf2",data:r},"*")}}}s.SERVICE_UUID="b112f5e6-2679-30da-a26e-0273b6043849",s.CHARACTERISTIC_TX_UUID="b112f5e6-2679-30da-a26e-0273b604384a",s.BLEHF2_FLAG_SERIAL_OUT=128,s.BLEHF2_FLAG_SERIAL_ERR=192,t.HF2Service=s;class c extends o{constructor(e){super("uart",e,c.SERVICE_UUID,c.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 l;c.SERVICE_UUID="6e400001-b5a3-f393-e0a9-e50e24dcca9e",c.CHARACTERISTIC_TX_UUID="6e400002-b5a3-f393-e0a9-e50e24dcca9e",t.UARTService=c,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"}(l||(l={}));class u extends a{constructor(e){super("partial flashing",e,!1),this.device=e,this.state=l.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==l.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 r=0;r<t.length;++r)if(t[r]!=this.bin[e+r]){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 r=e.appTarget.compile.flashUsableEnd;this.bin=ts.pxtc.UF2.toBin(e.U.stringToUint8Array(ts.pxtc.UF2.serializeFile(n)),r).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 i=this.magicOffset+u.MAGIC_MARKER.length;return this.dalHash=e.Util.toHex(this.bin.slice(i,i+8)),this.makeCodeHash=e.Util.toHex(this.bin.slice(i+8,i+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=l.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,r=new Uint8Array(n.buffer),i=r[0];if(this.state!=l.Idle)switch(i){case u.STATUS:if(!this.checkStateTransition(i,l.StatusRequested|l.PairingModeRequested))return;this.version=r[1],this.mode=r[2],this.debug(`flash service version ${this.version} mode ${this.mode}`),this.debug("reading DAL region"),this.state=l.RegionDALRequested,this.pfCharacteristic.writeValue(new Uint8Array([u.REGION_INFO,u.REGION_DAL])).then((()=>{}));break;case u.REGION_INFO:if(!this.checkStateTransition(i,l.RegionDALRequested|l.RegionMakeCodeRequested))return;const t=this.regions[r[1]]={start:r[2]<<24|r[3]<<16|r[4]<<8|r[5],end:r[6]<<24|r[7]<<16|r[8]<<8|r[9],hash:e.Util.toHex(r.slice(10))};if(this.debug(`read region ${r[1]} start ${t.start.toString(16)} end ${t.end.toString(16)} hash ${t.hash}`),r[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=l.USBFlashRequired,this.flashReject(new Error("USB flashing required")),void this.clearFlashData();this.debug("DAL hash match, reading makecode region"),this.state=l.RegionMakeCodeRequested,this.pfCharacteristic.writeValue(new Uint8Array([u.REGION_INFO,u.REGION_MAKECODE])).then((()=>{}))}else if(r[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=l.Idle,this.flashResolve(),this.clearFlashData()}));else{if(this.mode!=u.MODE_PAIRING)return this.debug("application mode, reset into pairing mode"),this.state=l.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(i,l.Flash))return;switch(r[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=l.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(r)}`),this.disconnect()}}flashNextPacket(){this.state=l.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,r=()=>e.U.delay(500).then((()=>{if(t!=this.flashOffset||this.flashPacketToken.isCancelled()||this.aliveToken.isCancelled()||this.state!=l.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((()=>r()))}));r().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 i{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 c(this)),this.services.push(this.hf2Service=new s(this))),r()&&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 p(){if(t.bleDevice)return Promise.resolve();e.log("ble: requesting device");const i=[];return n()&&(i.push(c.SERVICE_UUID),i.push(s.SERVICE_UUID)),r()&&i.push(u.SERVICE_UUID),navigator.bluetooth.requestDevice({filters:e.appTarget.appTheme.bluetoothUartFilters,optionalServices:i}).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),p().catch((n=>{t.bleDevice&&t.bleDevice.aliveToken&&t.bleDevice.aliveToken.resolveCancel(),e.log(`ble: error ${n.message}`)}))},t.flashAsync=function(n,r){e.tickEvent("webble.flash");const i=n.outfiles[ts.pxtc.BINARY_HEX];return p().then((()=>t.bleDevice.partialFlashingService.flashAsync(i))).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 r,i,a=!0;t.setFilters=function(e){a=!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(){this.enabled||(this.enabled=!0,this.log("registering webusb events"),navigator.usb.addEventListener("disconnect",this.handleUSBDisconnected,!1),navigator.usb.addEventListener("connect",this.handleUSBConnected,!1))}disable(){this.enabled&&(this.enabled=!1,this.log("unregistering webusb events"),navigator.usb.removeEventListener("disconnect",this.handleUSBDisconnected),navigator.usb.removeEventListener("connect",this.handleUSBConnected))}disposeAsync(){return this.disable(),Promise.resolve()}handleUSBDisconnected(e){this.log("device disconnected"),e.device==this.dev&&(this.log("clear device"),this.clearDev(),this.onDeviceConnectionChanged&&this.onDeviceConnectionChanged(!1))}handleUSBConnected(e){const t=e.device;this.log(`device connected ${t.serialNumber}`),this.dev||this.connecting||(this.log("attach device"),this.onDeviceConnectionChanged&&this.onDeviceConnectionChanged(!0))}clearDev(){this.dev&&(this.dev=null,this.epIn=null,this.epOut=null,this.onConnectionChanged&&this.onConnectionChanged())}error(t){throw new n(e.U.lf("USB error on device {0} ({1})",this.dev.productName,t))}log(t){e.debug("webusb: "+t)}disconnectAsync(){return this.ready=!1,this.dev?(this.log("close device"),this.dev.close().catch((e=>{})).then((()=>(this.clearDev(),e.U.delay(500))))):Promise.resolve()}reconnectAsync(){return this.log("reconnect"),this.setConnecting(!0),this.disconnectAsync().then(s).then((e=>this.connectAsync(e))).finally((()=>this.setConnecting(!1)))}setConnecting(e){e!=this.connecting&&(this.connecting=e,this.onConnectionChanged&&this.onConnectionChanged())}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)}}sendPacketAsync(t){return this.dev?(e.Util.assert(t.length<=64),this.epOut?this.dev.transferOut(this.epOut.endpointNumber,t).then((e=>{"ok"!=e.status&&this.error("USB OUT transfer failed")})):this.dev.controlTransferOut({requestType:"class",recipient:"interface",request:9,value:512,index:this.iface.interfaceNumber},t).then((e=>{"ok"!=e.status&&this.error("USB CTRL OUT transfer failed")}))):Promise.reject(new Error("Disconnected"))}readLoop(){if(this.readLoopStarted)return;this.readLoopStarted=!0,this.log("start read loop");let t=()=>{this.ready?this.recvPacketAsync().then((n=>{n[0]?(this.onData(n),t()):e.U.delay(500).then(t)}),(n=>{this.dev&&this.onError(n),e.U.delay(300).then(t)})):e.U.delay(300).then(t)};t()}recvPacketAsync(){let e=e=>{"ok"!=e.status&&this.error("USB IN transfer failed");let t=new Uint8Array(e.data.buffer);return 0==t.length?this.recvPacketAsync():t};return this.dev?this.epIn?this.dev.transferIn(this.epIn.endpointNumber,64).then(e):this.dev.controlTransferIn({requestType:"class",recipient:"interface",request:1,value:256,index:this.iface.interfaceNumber},64).then(e):Promise.reject(new Error("Disconnected"))}initAsync(){if(!this.dev)return Promise.reject(new Error("Disconnected"));let n=this.dev;return this.log("open device"),n.open().then((()=>(this.log("select configuration"),n.selectConfiguration(1)))).then((()=>{this.log("got "+n.configurations[0].interfaces.length+" interfaces");const r=n.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 i=r[r.length-1];return this.log(`${r.length} matching interfaces; picking ${i?"#"+i.interfaceNumber:"n/a"}`),i||this.error("cannot find supported USB interface"),this.altIface=i.alternates[0],this.iface=i,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"),n.claimInterface(i.interfaceNumber)})).then((()=>{this.log("device ready"),this.lastKnownDeviceSerialNumber=this.dev.serialNumber,this.ready=!0,a&&this.readLoop(),this.onConnectionChanged&&this.onConnectionChanged()}))}}async function s(){e.log("webusb: get devices");try{return await navigator.usb.getDevices()||[]}catch(t){return e.reportException(t),[]}}async function c(){var t,n;if(void 0!==i)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(i=!1);if(e.BrowserUtils.isElectron()||e.BrowserUtils.isWinRT())return e.debug("webusb: off, electron or winrt"),e.tickEvent("webusb.off",{reason:"electronwinrt"}),void(i=!1);const r=navigator.usb;if(!r)return e.debug("webusb: off, not impl"),e.tickEvent("webusb.off",{reason:"notimpl"}),void(i=!1);let a=/Windows NT (\d+\.\d+)/.exec(navigator.userAgent);if(a&&parseFloat(a[1])<6.3)return e.debug("webusb: off, older windows version"),e.tickEvent("webusb.off",{reason:"oldwindows"}),void(i=!1);try{await r.getDevices()}catch(t){return e.debug("webusb: off, security exception"),e.tickEvent("webusb.off",{reason:"security"}),void(i=!1)}i=!0}function l(){return void 0===i&&(console.error("checkAvailableAsync not called"),c()),!!i}t.pairAsync=function(){return navigator.usb.requestDevice({filters:t.filters}).then((e=>!!e)).catch((e=>{if("NotFoundError"!=e.name)throw e}))},t.mkWebUSBHIDPacketIOAsync=function(){return e.debug("packetio: mk webusb io"),r||(r=new o),r.enable(),Promise.resolve(r)},t.isEnabled=!1,t.setEnabled=function(e){l()||(e=!1),t.isEnabled=e},t.checkAvailableAsync=c,t.isAvailable=l}(e.usb||(e.usb={}))}(pxt||(pxt={})),function(e){!function(t){var n=e.Util;let r={};function i(e){let t={},r=0,i=new n.PromiseQueue,a=new Promise(((e,n)=>{t.ready=e}));i.enqueue("main",(()=>a));return{opAsync:function(n,a){return i.enqueue("main",(()=>new Promise(((i,o)=>{let s=""+r++;t[s]=e=>{e?e.errorMessage?o(new Error(e.errorMessage)):i(e):o(new Error("no response"))},e({id:s,op:n,arg:a})}))))},recvHandler:e=>{if(t.hasOwnProperty(e.id)){let n=t[e.id];delete t[e.id],n(e.result)}}}}function a(t){let n=new Worker(t),r=i((e=>n.postMessage(e)));return n.onmessage=t=>{e.perf.measureStart("webworker recvHandler"),r.recvHandler(t.data),e.perf.measureEnd("webworker recvHandler")},r}t.getWorker=function(e){let t=r[e];return t||(t=r[e]=a(e)),t},t.wrap=i,t.makeWebWorker=a,t.makeWebSocket=function(t,n=null){let r=new WebSocket(t),a=[],o=i((e=>{let t=JSON.stringify(e);a?a.push(t):r.send(t)}));return r.onmessage=e=>{let t=JSON.parse(e.data);n&&null==t.id?n(t):o.recvHandler(t)},r.onopen=t=>{e.debug("socket opened");for(let e of a)r.send(e);a=null},r.onclose=t=>{e.debug("socket closed")},r.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 r(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:r(e.snippet.thumbnails)};var t},t.playlistInfoAsync=function(r){n();const i=`https://www.googleapis.com/youtube/v3/playlists?part=snippet&id=${r}&key=${t.apiKey}`;return e.Util.httpGetJsonAsync(i).then((e=>e.items[0]))},t.listPlaylistVideosAsync=async function(r){n();let i,a=[];do{let n=`https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=${r}&key=${t.apiKey}`;i&&(n+=`&pageToken=${i}`);const o=await e.Util.httpGetJsonAsync(n);a=a.concat(o.items),i=o.nextPageToken}while(i);return e.options.debug&&e.debug(JSON.stringify(a,null,2)),a},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 r=c("opcode name doesn't match","<name>");class i{constructor(t,n,r,i,a){this.opcode=r,this.mask=i,this.is32bit=a,this.canBeShared=!1,e.assert((r&i)==r),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=s(n);this.name=o[0],this.args=o.slice(1)}emit(t){let n=t.words;if(n[0]!=this.name)return r;let i=this.opcode,a=1,o=0,s=[],l=null,u=null,d=null;for(let r=0;r<this.args.length;++r){let p=this.args[r],f=n[a++];if("$"==p[0]){let r=this.ei.encoders[p],_=null;if(r.isRegister){if(_=this.ei.registerNo(f),null==_)return c("expecting register name",f);this.ei.isPush(this.opcode)?o++:this.ei.isPop(this.opcode)&&o--}else if(r.isImmediate){if(f=f.replace(/^#/,""),_=t.bin.parseOneInt(f),null==_)return c("expecting number",f);this.ei.isAddSP(this.opcode)?o=-_/this.ei.wordSize():this.ei.isSubSP(this.opcode)&&(o=_/this.ei.wordSize())}else if(r.isRegList){if("{"!=f)return c("expecting {",f);for(_=0;"}"!=n[a];){if(f=n[a++],!f)return c("expecting }",n[a-2]);let e=this.ei.registerNo(f);if(null==e)return c("expecting register name",f);if(_&1<<e)return c("duplicate register name",f);_|=1<<e,this.ei.isPush(this.opcode)?o++:this.ei.isPop(this.opcode)&&o--,","==n[a]&&a++}f=n[a++]}else if(r.isLabel){if(f=f.replace(/^#/,""),/^[+-]?\d+$/.test(f))_=parseInt(f,10),l="rel"+_;else if(/^0x[0-9a-fA-F]+$/.test(f))_=parseInt(f,16),l="abs"+_;else if(l=f,_=this.ei.getAddressFromLabel(t.bin,this,f,r.isWordAligned),null==_){if(t.bin.finalEmit)return c("unknown label",f);_=8}if(this.ei.is32bit(this)){u=_,d=f;continue}}else e.oops();if(null==_)return c("didn't understand it",f);if(s.push(_),_=r.encode(_),null==_)return c("argument out of range or mis-aligned",f);e.assert(0==(i&_)),i|=_}else if(p!=f)return c("expecting "+p,f)}return n[a]?c("trailing tokens",n[a]):this.ei.is32bit(this)?this.ei.emit32(i,u,t.bin.normalizeExternalLabel(d)):{stack:o,opcode:i,numArgs:s,labelName:t.bin.normalizeExternalLabel(l)}}toString(){return this.friendlyFmt}}t.Instruction=i;class a{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=s(e)||[],0==this.words.length?this.type="empty":"@"==this.words[0][0]&&(this.type="directive")}}t.Line=a;class o{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.currLine=new a(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}parseOneInt(t){if(!t)return null;if(/^\d+$/.test(t))return parseInt(t,10);const r=t.indexOf("-");if(r>0)return this.parseOneInt(t.slice(0,r))-this.parseOneInt(t.slice(r+1));let i=1;if(t.indexOf("*")>=0){let e=null;for(;null!=(e=/^([^\*]*)\*(.*)$/.exec(t));){let n=this.parseOneInt(e[1]);if(null==n)return null;i*=n,t=e[2]}}if("-"==t[0]?(i*=-1,t=t.slice(1)):"+"==t[0]&&(t=t.slice(1)),/^\d+$/.test(t))return i*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 a=/(.*)>>(\d+)$/.exec(t);if(a){let e=this.parseOneInt(a[1]);return e&=~(-16777216&this.baseOffset),e>>parseInt(a[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 r=/^(\w+)@(-?\d+)$/.exec(t);r&&(1!=i&&this.directiveError(n("multiplication not supported with saved stacks")),this.stackpointers.hasOwnProperty(r[1])?o=this.ei.wordSize()*this.ei.computeStackOffset(r[1],this.stack-this.stackpointers[r[1]]+parseInt(r[2])):this.directiveError(n("saved stack not found"))),r=/^(.*)@(hi|lo|fn)$/.exec(t),r&&this.looksLikeLabel(r[1])&&(o=this.lookupLabel(r[1],!0),null!=o&&("fn"==r[2]?o=this.ei.toFnPtr(o,this.baseOffset,r[1]):(o>>=1,0<=o&&o<=65535?"hi"==r[2]?o=o>>8&255:"lo"==r[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*i}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){let r=null,i=this.scopedName(e);return this.labels.hasOwnProperty(i)?(r=this.labels[i],r=this.ei.postProcessRelAddress(this,r)):this.lookupExternalLabel&&(r=this.lookupExternalLabel(e),null!=r&&(r=this.ei.postProcessAbsAddress(this,r))),null==r&&this.equs.hasOwnProperty(i)&&(r=this.equs[i]),null==r&&t&&(this.finalEmit?this.directiveError(n("unknown label: {0}",e)):r=11111),r}align(t){for(e.assert(2==t||4==t||8==t||16==t);this.location()%t!=0;)this.emitOpCode(0)}pushError(e,t=""){let r={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(r),this.throwOnError)throw new Error(r.message)}directiveError(e){this.pushError(e)}emitString(e,t=!1){function r(e,t){return 255&(e.charCodeAt(t)||0)}let i,a=/^\s*([\w\.]+\s*:\s*)?.\w+\s+(".*")\s*$/.exec(e);if(a&&null!=(i=function(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}}(a[2])))if(this.align(2),t)for(let e=0;e<i.length;e++)this.emitShort(i.charCodeAt(e));else for(let e=0;e<i.length+1;e+=2)this.emitShort(r(i,e+1)<<8|r(i,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 r=this.parseNumber(e);if(null==r){this.directiveError(n("cannot parse number at '{0}'",e[0]));break}if(t.push(r),","!=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 r=t[e],i=t[e+1];0<=r&&i<=255&&0<=i&&r<=255?this.emitShort(255&r|(255&i)<<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(e){let t,r=e.words,i=()=>{2!=r.length&&this.directiveError(n("expecting one argument"))};switch(r[0]){case".ascii":case".asciz":case".string":this.emitString(e.text);break;case".utf16":this.emitString(e.text,!0);break;case".align":if(i(),t=this.parseOneInt(r[1]),null!=t){if(0==t)return;t<=4?this.align(1<<t):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(i(),t=this.parseOneInt(r[1]),null!=t){if(1==t)return;2==t||4==t||8==t||16==t?this.align(t):this.directiveError(n("expecting 2, 4, 8, or 16"))}else this.directiveError(n("expecting number"));break;case".p2align":i(),t=this.parseOneInt(r[1]),null!=t?this.align(1<<t):this.directiveError(n("expecting number"));break;case".byte":this.emitBytes(r);break;case".hex":this.emitHex(r);break;case".hword":case".short":case".2bytes":this.parseNumbers(r).forEach((e=>{-32768<=e&&e<=65535?this.emitShort(65535&e):this.directiveError(n("expecting int16"))}));break;case".word":case".4bytes":case".long":this.parseNumbers(r).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(r);break;case".set":case".equ":/^\w+$/.test(r[1])||this.directiveError(n("expecting name"));const a=this.parseNumbers(r.slice(","==r[2]||"="==r[2]?2:1));1!=a.length&&this.directiveError(n("expecting one value")),void 0!==this.equs[r[1]]&&this.equs[r[1]]!=a[0]&&this.directiveError(n("redefinition of {0}",r[1])),this.equs[r[1]]=a[0];break;case".startaddr":this.location()&&this.directiveError(n(".startaddr can be only be specified at the beginning of the file")),i(),this.baseOffset=this.parseOneInt(r[1]);break;case"@stackmark":i(),this.stackpointers[r[1]]=this.stack;break;case"@stackempty":this.checkStack&&(null==this.stackpointers[r[1]]?this.directiveError(n("no such saved stack")):this.stackpointers[r[1]]!=this.stack&&this.directiveError(n("stack mismatch")));break;case"@scope":this.scope=r[1]||"",this.currLineNo=this.scope?0:this.realCurrLineNo;break;case".syntax":case"@nostackcheck":this.checkStack=!1;break;case"@dummystack":i(),this.stack+=this.parseOneInt(r[1]);break;case".section":case".global":this.stackpointers={},this.stack=0,this.scope="$S"+this.scopeId++;break;case".comm":{r=r.filter((e=>","!=e)),r.shift();let e=this.parseOneInt(r[1]),t=0;if(t=r[2]?this.parseOneInt(r[2]):4,null==this.lookupLabel(r[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(r[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(r[0])||this.directiveError(n("unknown directive"))}}handleOneInstruction(e,t){let r=t.emit(e);return!r.error&&(this.stack+=r.stack,this.checkStack&&this.stack<0&&this.pushError(n("stack underflow")),e.location=this.location(),e.opcode=r.opcode,e.stack=r.stack,this.emitOpCode(r.opcode),null!=r.opcode2&&this.emitOpCode(r.opcode2),null!=r.opcode3&&this.emitOpCode(r.opcode3),e.instruction=t,e.numArgs=r.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 r=e.words[0].toLowerCase().replace(/s$/,"").replace(/[^a-z]/g,""),i="",a=t(r).concat(t(r+"s"));a.length>0&&a.forEach((t=>{let r=t.emit(e);i+=n(" Maybe: {0} ({1} at '{2}')\n",t.toString(),r.error,r.errorAt)})),this.pushError(n("assembly error"),i)}buildLine(e,t){let n=e=>{let n=new a(this,e);return n.scope=this.scope,n.lineNo=this.currLineNo,t.push(n),n},r=n(e),i=s(r.text)||[];r.words=i;let o=i[0]||"";if(":"==o.charAt(o.length-1)){let t=/^([\.\w]+):$/.exec(i[0]);if(t){if(r.type="label",r.text=t[1]+":",r.words=[t[1]],!(i.length>1))return;i.shift(),r=n(e.replace(/^[^:]*:/,"")),r.words=i,o=i[0]||""}}let c=o.charAt(0);"."==c||"@"==c?(r.type="directive","@scope"==r.words[0]&&this.handleDirective(r)):0==r.words.length?r.type="empty":r.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){let r=this.scopedName(t.words[0]);if(this.prevLabel=r,this.finalEmit){null!=this.equs[r]&&this.directiveError(n(".equ redefined as label"));let t=this.labels[r];null==t&&e.oops(),0==this.errors.length&&t!=this.location()&&e.oops(`invalid location: ${this.location()} != ${t} at ${r}`),e.assert(this.errors.length>0||t==this.location()),this.reallyFinalEmit&&(this.stackAtLabel[r]=this.stack)}else this.labels.hasOwnProperty(r)?this.directiveError(n("label redefinition")):this.inlineMode&&/^_/.test(r)?this.directiveError(n("labels starting with '_' are reserved for the compiler")):this.labels[r]=this.location();t.location=this.location()}else"directive"==t.type?this.handleDirective(t):"instruction"==t.type?this.handleInstruction(t):"empty"==t.type||e.oops()}))}getSourceMap(){const e={};let t="",n=0,r=0,i=0;function a(){t&&r&&(e[t]||(e[t]=[]),e[t].push(n,r,i-r)),r=0,i=0}return this.lines.forEach(((e,o)=>{const s=/^; ([\w\/\.-]+)\(([\d]+),\d+\):/.exec(e.text);s&&(a(),t=s[1],n=parseInt(s[2])),"instruction"==e.type&&(r||(r=e.location),i=e.location)})),a(),e}getSource(r,i=1,a=0){let o=0,s=e=>{let t=this.labels[e]||o,n=t-o;return o=t,n},c=this.buf?this.location():0,l=s("_code_end"),u=s("_helpers_end"),d=s("_vtables_end"),p=s("_literals_end"),f=o,_=c+this.baseOffset&16777215;a&&_>a&&e.U.userError(n("program too big by {0} bytes!",_-a));let m=n("; total bytes: {0} ({1}% of {2}k flash with {3} free)",_,(100*_/(a=a||131072)).toFixed(1),(a/1024).toFixed(1),a-_),g=n("; generated code sizes (bytes): {0} (incl. {1} user, {2} helpers, {3} vtables, {4} lits); src size {5}\n",f,l,u,d,p,c-f)+n("; assembly: {0} lines; density: {1} bytes/stmt; ({2} stmts)\n",this.lines.length,Math.round(100*l/i)/100,i)+m+"\n"+this.stats+"\n\n",h=!1;return this.lines.forEach(((e,n)=>{if("_stored_program"==e.words[0])return g+='_stored_program: .string "..."\n',void(h=!0);if(h)return void(h=!1);let i=e.text;if(r){if("@stackempty"==e.words[0]&&this.lines[n-1].text==e.text)return;if(i=i.replace(/; WAS: .*/,""),!i.trim())return}t.debug&&("label"!=e.type&&"instruction"!=e.type||(i+=` \t; 0x${(e.location+this.baseOffset).toString(16)}`)),g+=i+"\n"})),g}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 r=e[t+1];if(!r)continue;let i=e[t+2];"instruction"==n.type&&this.ei.peephole(n,r,i)}}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=o;t.VMFile=class extends o{constructor(e){super(e)}};function s(e){let t=[],n="";e:for(let r=0;r<e.length;++r)switch(e[r]){case"[":case"]":case"!":case"{":case"}":case",":n&&(t.push(n),n=""),t.push(e[r]);break;case" ":case"\t":case"\r":case"\n":n&&(t.push(n),n="");break;case";":break e;default:n+=e[r]}return n&&(t.push(n),n=""),t[0]?t:null}function c(e,t){return{stack:null,opcode:null,error:e,errorAt:t}}function l(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 r={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]=r,r},this.inrange=(e,t,n)=>Math.floor(t)!=t||t<0||t>e?null:n,this.inminmax=(e,t,n,r)=>Math.floor(n)!=n||n<e||n>t?null:r,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,r)=>{let a=new i(this,e,t,n,r);return this.instructions.hasOwnProperty(a.name)||(this.instructions[a.name]=[]),this.instructions[a.name].push(a),a},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,r=!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=c,t.expectError=function(t,n){let r=new o(t);r.emit(n),0==r.errors.length&&e.oops("ASMTEST: expecting error for: "+n)},t.tohex=l,t.expect=function(t,n){let r=[],i=n.replace(/^([0-9a-fA-F]{4,8})\s/gm,((e,t)=>(r.push(parseInt(t.slice(0,4),16)),8==t.length&&r.push(parseInt(t.slice(4,8),16)),""))),a=new o(t);a.throwOnError=!0,a.disablePeepHole=!0,a.emit(i),a.errors.length>0&&(console.debug(a.errors[0].message),e.oops("ASMTEST: not expecting errors")),a.buf.length!=r.length&&e.oops("ASMTEST: wrong buf len");for(let t=0;t<r.length;++t)a.buf[t]!=r[t]&&e.oops("ASMTEST: wrong buf content at "+t+" , exp:"+l(r[t])+", got: "+l(a.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 r=!0;function i(t){let r=new Error(n.lf("Cannot access {0} while offline",t));return r.isOffline=!0,e.U.delay(1e3).then((()=>Promise.reject(r)))}function a(n,r){return e.U.requestAsync({url:"/api/"+n,headers:{Authorization:t.localToken},method:r?"POST":"GET",data:r||void 0,allowHttpErrors:!0})}function o(){return e.webConfig&&!e.webConfig.isStatic&&!e.BrowserUtils.isLocalHost()&&!!e.webConfig.cdnUrl}function s(n){if(n=n.replace(/^\//,""),!o())return t.apiRoot+n;const r=new Date,i=r.getUTCFullYear()+("0"+(r.getUTCMonth()+1)).slice(-2)+("0"+r.getUTCDate()).slice(-2);return n.indexOf("?")<0?n+="?":n+="&",n+="cdn="+i,e.webConfig.cdnUrl+"/api/"+n}function c(e){return o()?(e.url=s(e.url),n.requestAsync(e).catch((t=>l(e,t)))):u(e)}function l(e,n){return 0==n.statusCode?(r&&(r=!1,t.onOffline()),i(e.url)):Promise.reject(n)}function u(r){var a;return r.url=(null===(a=e.webConfig)||void 0===a?void 0:a.isStatic)&&!r.forceLiveEndpoint?e.webConfig.relprefix+r.url:t.apiRoot+r.url,r.allowGzipPost=!0,t.isOnline()||e.BrowserUtils.isPxtElectron()?(r.headers||(r.headers={}),e.BrowserUtils.isLocalHost()?t.localToken&&(r.headers.Authorization=t.localToken):t.accessToken&&(r.headers["x-td-access-token"]=t.accessToken),n.requestAsync(r).catch((e=>l(r,e)))):i(r.url)}function d(){return navigator&&navigator.onLine}t.onOffline=()=>{},t.hasAccessToken=function(){return!!t.accessToken},t.localRequestAsync=a,t.useCdnApi=o,t.cdnApiUrl=s,t.apiRequestWithCdnAsync=c,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,r=e.webConfig&&e.webConfig.isStatic?"targetconfig.json":`config/${e.appTarget.id}/targetconfig${n?`/v${n}`:""}`;return e.BrowserUtils.isLocalHost()?a(r).then((e=>e?e.json:void 0)):c({url:r}).then((e=>e.json))},t.downloadScriptFilesAsync=function(e){return u({url:e+"/text",forceLiveEndpoint:!0}).then((e=>JSON.parse(e.text)))},t.markdownAsync=async function(t,n){const r=e.BrowserUtils.isLocalHostDev()?0:36e5,i=24*r*7;n=n||e.Util.userLanguage();const s=await e.BrowserUtils.translationDbAsync(),l=await s.getAsync(n,t,""),d=async()=>{try{const r=await function(t,n,r){var i;const s=null===(i=e.webConfig)||void 0===i?void 0:i.isStatic,l=e.appTarget.versions&&e.appTarget.versions.target||"?";let d;if(s){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(l)}`;"en"!=n&&(d+=`${s?"?":"&"}lang=${encodeURIComponent(n)}`);if(e.BrowserUtils.isLocalHost()&&!e.Util.liveLocalizationEnabled())return a(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=r&&!o()?{"If-None-Match":r}:void 0;return c({url:d,method:"GET",headers:e}).then((e=>({md:e.text,etag:e.headers.etag})))}}(t,n,null==l?void 0:l.etag);return!l||r.md&&l.md!==r.md?(await s.setAsync(n,t,"",r.etag,void 0,r.md),r.md):l.md}catch(e){return""}};if(l){const t=Date.now()-l.time,n=t>r;if(t>i)e.tickEvent("markdown.update.wait");else if(n&&(e.tickEvent("markdown.update.background"),d()),l.md)return l.md}return d()},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()&&(r=!0),r},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){const r=e.appTarget;if(!(t&&r.appTheme&&r.cloud&&r.cloud.sharing))return;let i=["makecode.com"];r.appTheme.embedUrl&&i.push(r.appTheme.embedUrl),r.appTheme.shareUrl&&i.push(r.appTheme.shareUrl),i=n.unique(i,(e=>e)).map((e=>n.escapeForRegex(n.stripUrlProtocol(e).replace(/\/$/,"")).toLowerCase()));const a=`^((https://)?(?:${i.join("|")})/)?(?:v[0-9]+/)?(api/oembed?url=.*%2F([^&]*)&.*?|([a-z0-9-_]+))$`,o=new RegExp(a,"i").exec(t.trim()),s=o&&(!o[1]||i.indexOf(n.escapeForRegex(o[1].replace(/https:\/\//,"").replace(/\/$/,"")).toLowerCase())>=0)&&(o[3]||o[4])?o[3]?o[3]:o[4]:null;return s&&("_"==s[0]&&13==s.length||23==s.length&&/^[0-9\-]+$/.test(s))?s:void 0}}(e.Cloud||(e.Cloud={}))}(pxt||(pxt={})),function(e){!function(e){e.f4EncodeImg=function(e,t,n,r){let i=[135,n,255&e,e>>8,255&t,t>>8,0,0].map(l).join(""),a=4,o=0,s=0,c=e=>{o|=e<<s,s==8-n?(i+=l(o),a++,o=0,s=0):s+=n};for(let i=0;i<e;++i){for(let e=0;e<t;++e)c(r(i,e));for(;0!=s;)c(0);if(n>1)for(;3&a;)c(0)}return i;function l(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),r=0;for(let e=0;e<this.numRows;e++){let i=0;n[e]=[];for(let r=0;r<this.numCols;r++)this.melody[r][e]&&(n[e].push(t(r)),i++);i>r&&(r=i)}if(0==r)return"- - - - - - - - ";for(let t=0;t<r;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,r,i){const a=t("div",{className:"melody-gallery-button melody-editor-card",role:"menuitem",id:`:${n}`}),o=t("i",{className:"music icon melody-icon"}),s=t("div",{className:"melody-editor-text"});s.innerText=e.name;const c=this.createColorBlock(e),l=t("div",{className:"melody-editor-button left-button",role:"button",title:e.name},(()=>this.handleSelection(e)));l.appendChild(o),l.appendChild(s),l.appendChild(c),a.appendChild(l);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),a.appendChild(u),this.contentDiv.appendChild(a)}handleSelection(e){if(this.pending){const t=this.pending;this.pending=void 0,t(e.notes)}}playNote(e,t,n){let r=0;switch(e){case"C5":r=523;break;case"B":r=494;break;case"A":r=440;break;case"G":r=392;break;case"F":r=349;break;case"E":r=330;break;case"D":r=294;break;case"C":r=262}this.timeouts.push(setTimeout((()=>{pxt.AudioContextManager.tone(r)}),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 r=t.notes.split(" ");for(let t=0;t<r.length;t++){let i=e.getColorClass(e.noteToRow(r[t])),a=document.createElement("div");0==t?pxt.BrowserUtils.addClass(a,"left-edge sliver "+i):t==r.length-1?pxt.BrowserUtils.addClass(a,"right-edge sliver "+i):pxt.BrowserUtils.addClass(a,"sliver "+i),n.appendChild(a)}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){let t,n=!1;class r{constructor(e){this.db=e}loadAsync(n,r,i,a){if(!/^v\d+\.\d+\.\d+$/.test(r))return a(n,r);const o=`gh-${i}-${n}#${r}`;return t.cacheGet(o).then((i=>{if(i){const t=e.Util.jsonTryParse(i);if(t)return e.debug(`cache hit ${o}`),Promise.resolve(t)}return a(n,r).then((n=>n?(e.debug(`cached ${o}`),t.cacheSet(o,JSON.stringify(n)).then((()=>n))):n))}))}loadConfigAsync(e,t){return this.loadAsync(e,t,"pxt",((e,t)=>this.db.loadConfigAsync(e,t)))}loadPackageAsync(e,t){return this.loadAsync(e,t,"pkg",((e,t)=>this.db.loadPackageAsync(e,t)))}}class i{constructor(e){this.packageFiles=e}resolve(e,t){return""}readFile(t,n){const r="this"==t.id?n:"pxt_modules/"+t.id+"/"+n;return void 0!==this.packageFiles[r]?this.packageFiles[r]:e.appTarget.bundledpkgs[t.id]?e.appTarget.bundledpkgs[t.id][n]:null}writeFile(t,n,r){const i="this"==t.id?"":"pxt_modules/"+t.id+"/";e.debug(`write file ${i+n}`),this.packageFiles[i+n]=r}getHexInfoAsync(e){return Promise.resolve({hex:["SKIP"]})}cacheStoreAsync(e,n){return(null==t?void 0:t.cacheSet)?t.cacheSet(e,n):Promise.resolve()}cacheGetAsync(e){return(null==t?void 0:t.cacheGet)?t.cacheGet(e):Promise.resolve("")}downloadPackageAsync(r){return n?function(e){const n=null==t?void 0:t.pkgOverrideAsync;return(n?n(e.id):Promise.resolve(void 0)).then((t=>t||e.commonDownloadAsync()))}(r).then((t=>{t&&e.U.iterMap(t,((e,t)=>{this.writeFile(r,e,t)}))})):Promise.resolve()}resolveVersionAsync(e){return Promise.resolve("*")}}function a(t){if(t.target.preferredEditor==e.PYTHON_PROJECT_NAME){const n=e.U.clone(t);n.ast=!0,n.target.preferredEditor=e.JAVASCRIPT_PROJECT_NAME;for(let t of n.sourceFiles)e.U.endsWith(t,".py")&&(n.fileSystem[t.slice(0,-3)+".ts"]=" ");const r=pxtc.compile(n);t.apisInfo=pxtc.getApiInfo(r.ast,n.jres)}}function o(t,n){const r=new i(t),o=new e.MainPackage(r);return o.loadAsync().then((()=>{let e=o.getTargetOptions();return e.hasHex&&(e.isNative=n.native),o.getCompileOptionsAsync(e)})).then((e=>(s(o.targetVersion(),e),a(e),e)))}function s(t,n){if(t){e.debug(`applying TS patches relative to ${t}`);for(let r of Object.keys(n.fileSystem))if(-1==r.indexOf("/")&&e.U.endsWith(r,".ts")){const i=n.fileSystem[r],a=e.patching.patchJavaScript(t,i);i!=a&&(e.debug(`applying TS patch to ${r}`),n.fileSystem[r]=a)}}}e.SimpleHost=i,e.prepPythonOptions=a,e.simpleInstallPackagesAsync=function(t){const n=new i(t);return new e.MainPackage(n).loadAsync(!0)},e.simpleGetCompileOptionsAsync=o,e.simpleCompileAsync=function(e,t){return o(e,"boolean"==typeof t?{native:t}:t||{}).then((e=>pxtc.compile(e))).then((e=>(e.success||(e.errors=e.diagnostics.map(ts.pxtc.getDiagnosticString).join("")||"Unknown error."),e)))},e.patchTS=s,e.setupSimpleCompile=function(i){"undefined"==typeof global||global.btoa||(global.btoa=function(e){return Buffer.from(e,"binary").toString("base64")},global.atob=function(e){return Buffer.from(e,"base64").toString("binary")}),"undefined"!=typeof pxtTargetBundle&&(e.debug("setup app bundle"),e.setAppTarget(pxtTargetBundle)),i&&(t=i,n=!0,i.httpRequestAsync&&(e.Util.httpRequestCoreAsync=i.httpRequestAsync),e.github.forceProxy=!0,e.github.db=new r(new e.github.MemoryGithubDb)),e.debug("simple setup done")}}(pxt||(pxt={})),function(e){e.simshim=function(t,n){let r,i=ts.SyntaxKind,a=t.getTypeChecker(),o=e.cpp.nsWriter("declare namespace"),s="";for(let a of t.getSourceFiles()){if(n){let t=n(a.fileName);if(e.debug("SimShim[1]: "+t.dir),!e.U.endsWith(t.dir,"/sim")&&!e.U.startsWith(a.fileName,"sim/"))continue}else if(!e.U.startsWith(a.fileName,"sim/"))continue;e.debug("SimShim[2]: "+a.fileName);for(let e of a.statements){let t=e;e.kind==i.ModuleDeclaration&&"pxsim"==t.name.text&&(r=t,m(t.body))}}let c={};return c[e.appTarget.corepkg]=o.finish(),c;function l(e){let t;return ts.isExpression(e)&&(t=a.getContextualType(e)),t||(t=a.getTypeAtLocation(e)),t}function u(e){let t=a.typeToString(e,r,ts.TypeFormatFlags.UseFullyQualifiedType);switch(t=t.replace(/^pxsim\./,""),t){case"RefAction":return"() => void";case"RefBuffer":return"Buffer";default:return t}}function d(e){let t=pxtc.getComments(e);return/^\s*\/\/%/m.test(t)?t:null}function p(e){let t=d(e);if(!t)return;let n=e.name.getText(),r="//% shim=."+n,i=a.getTypeAtLocation(e);o.write(t),o.write(r),o.write(`public ${n}: ${u(i)};`),o.write("")}function f(e){let t=d(e);if(!t)return;a.getTypeAtLocation(e);let n=e.parameters.map((e=>e.name.getText()+": "+u(l(e))));o.write(t),o.write(`//% shim="new ${s}"`),o.write(`constructor(${n.join(", ")});`),o.write("")}function _(t,n=!1){let r=d(t);if(!r)return;let c=t.name.getText(),p=t.kind==i.MethodDeclaration||t.kind==i.GetAccessor||t.kind==i.SetAccessor,f="//% shim="+(p?"."+c:s+"::"+c),_=a.getSignatureFromDeclaration(t),m=a.getReturnTypeOfSignature(_),g=/Async$/.test(c),h=(y=m,pxtc.isObjectType(y)&&y.objectFlags&ts.ObjectFlags.Reference&&"Promise"==y.symbol.name?y.typeArguments[0]:null);var y;h?(f+=" promise",m=h,g||e.U.userError(`${s}::${c} should be called ${c}Async`)):g&&e.U.userError(`${s}::${c} doesn't return a promise`),e.debug("emitFun: "+c);let v=t.parameters.map((e=>`${e.name.getText()}${e.questionToken?"?":""}: ${u(l(e))}`)),b=c.replace(/Async$/,""),x=p?"public":"function",k=`(${v.join(", ")})`;t.kind==i.GetAccessor&&(x=n?"public":"readonly",k="",f+=" property"),p||o.setNs(s),o.write(r),o.write(f),o.write(`${x} ${b}${k}: ${u(m)};`),o.write("")}function m(e){switch(e.kind){case i.ModuleDeclaration:return function(e){let t=s;s&&(s+="."),s+=e.name.text,m(e.body),s=t}(e);case i.ModuleBlock:return e.statements.forEach(m);case i.FunctionDeclaration:return _(e);case i.ClassDeclaration:return function(e){let t=d(e);if(!t)return;o.setNs(s),o.write(t);let n=s;s&&(s+="."),s+=e.name.text;let r=n?"":"declare",a="";if(e.heritageClauses)for(let t of e.heritageClauses)t.token==i.ExtendsKeyword&&(a=" extends "+u(l(t.types[0])));o.write(`${r} class ${e.name.text}${a} {`),o.incrIndent();for(let t of e.members)switch(t.kind){case i.MethodDeclaration:_(t);break;case i.PropertyDeclaration:p(t);break;case i.Constructor:f(t);break;case i.GetAccessor:let n=e.members.some((e=>e.kind==i.SetAccessor&&e.name.getText()==t.name.getText()));_(t,n)}s=n,o.decrIndent(),o.write("}")}(e)}}}}(pxt||(pxt={})),function(e){!function(t){t.annotate=function(n,r,i){const a=t.target;t.target=i;let o=n.getSourceFiles().filter((e=>e.fileName===r))[0],s=n.getTypeChecker();function c(n,r,i=!1,a=null){let o=i||!(u(n).flags&e.TypeFlags.Void),c=a||l(n);if(n.expression&&c){let e=!1;switch(c.kind){case t.SK.PropertySignature:case t.SK.PropertyAssignment:case t.SK.PropertyDeclaration:t.isStatic(c)||(e=!0);break;case t.SK.Parameter:t.isCtorField(c)&&(e=!0);break;case t.SK.GetAccessor:case t.SK.SetAccessor:case t.SK.MethodDeclaration:case t.SK.MethodSignature:e=!0}if(e){const e=n.expression;e.kind===t.SK.PropertyAccessExpression?r.unshift(e.expression):r.unshift(n.expression)}}let d={decl:c,qName:c?t.getNodeFullName(s,c):"?",args:r,isExpression:o};t.pxtInfo(n).callInfo=d}function l(n){if(!n)return null;let r,i=s.getSymbolAtLocation(n);if(i&&(r=i.valueDeclaration,!r&&i.declarations)){let t=i.declarations[0];t&&t.kind==e.SyntaxKind.ImportEqualsDeclaration&&(i=s.getSymbolAtLocation(t.moduleReference),i&&(r=i.valueDeclaration))}if(!r&&n.kind==t.SK.PropertyAccessExpression){const e=n;r={kind:t.SK.PropertySignature,symbol:{isBogusSymbol:!0,name:e.name.getText()},name:e.name},t.pxtInfo(r).flags|=2}return r}function u(n){let r;const i=t.pxtInfo(n);return i.typeCache?i.typeCache:(e.isExpression(n)&&(r=s.getContextualType(n)),r||(r=s.getTypeAtLocation(n)),r?e.isStringLiteral(n)?r:t.checkType(r):r)}!function n(r){e.forEachChild(r,(r=>{switch(r.kind){case e.SyntaxKind.CallExpression:c(r,r.arguments.slice(0),null,l(r.expression));break;case e.SyntaxKind.PropertyAccessExpression:c(r,[]);break;case e.SyntaxKind.TaggedTemplateExpression:c(r,[r.template],!0,l(r.tag));break;case e.SyntaxKind.BinaryExpression:!function(n){const r=n.left,i=n.right;let a=u(n.left),o=u(n.right);n.operatorToken.kind!=t.SK.PlusToken&&n.operatorToken.kind!=t.SK.PlusEqualsToken||(t.isStringType(a)||t.isStringType(o)&&n.operatorToken.kind==t.SK.PlusToken)&&(t.pxtInfo(n).exprInfo={leftType:s.typeToString(a),rightType:s.typeToString(o)});switch(n.operatorToken.kind){case e.SyntaxKind.EqualsToken:case e.SyntaxKind.PlusEqualsToken:case e.SyntaxKind.MinusEqualsToken:if(r.kind==t.SK.PropertyAccessExpression){let n=l(r);n&&n.kind==t.SK.GetAccessor?(n=e.getDeclarationOfKind(n.symbol,t.SK.SetAccessor),c(r,[i],!1,n)):n&&(n.kind==t.SK.PropertySignature||n.kind==t.SK.PropertyAssignment||t.target&&t.target.switches.slowFields)&&c(r,[i])}}}(r);break;case e.SyntaxKind.Identifier:const n=l(r);if(n&&n.getSourceFile().fileName!==pxt.MAIN_TS&&n.kind==e.SyntaxKind.VariableDeclaration){const e=t.pxtInfo(r);e.flags|=4,e.commentAttrs||(e.commentAttrs=t.parseComments(n))}}n(r)}))}(o),t.target=a}}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){function t(e){let t='"';for(let n=0;n<e.length;++n){let r=255&e.charCodeAt(n),i=String.fromCharCode(r);t+="\\"==i||'"'==i?"\\"+i:"\n"==i?"\\n":r<=15?"\\x0"+r.toString(16):r<32||r>127?"\\x"+r.toString(16):i}return t+'"'}e.asmStringLiteral=t;function n(n){let r="pxt::string_inline_ascii_vt",i=e.target.utf8?e.U.toUTF8(n,!0):n,a="";if(i!==n)if(n.length>16){r="pxt::string_skiplist16_packed_vt";let o=[],s=0;for(let t=0;t+16<=n.length;t+=16)s+=e.U.toUTF8(n.slice(t,t+16),!0).length,o.push(s);a=`\n .short ${i.length}, ${n.length}\n .short ${o.map((e=>e.toString())).join(", ")}\n .string ${t(i)}\n`}else r="pxt::string_inline_utf8_vt";return a||(a=`\n .short ${i.length}\n .string ${t(i)}\n`),{vt:r,asm:a}}function r(e,t=""){return`\n .word ${e.length>>1}${t}\n .hex ${e}${e.length%4==0?"":"00"}\n `}e.AssemblerSnippets=class{nop(){return"TBD(nop)"}reg_gets_imm(e,t){return"TBD(reg_gets_imm)"}proc_setup(e,t){return"TBD(proc_setup)"}push_fixed(e){return"TBD(push_fixed)"}push_local(e){return"TBD(push_local)"}push_locals(e){return"TBD(push_locals)"}pop_fixed(e){return"TBD(pop_fixed)"}pop_locals(e){return"TBD(pop_locals)"}proc_return(){return"TBD(proc_return)"}debugger_stmt(e){return""}debugger_bkpt(e){return""}debugger_proc(e){return""}unconditional_branch(e){return"TBD(unconditional_branch)"}beq(e){return"TBD(beq)"}bne(e){return"TBD(bne)"}cmp(e,t){return"TBD(cmp)"}cmp_zero(e){return"TBD(cmp_zero)"}arithmetic(){return""}load_reg_src_off(e,t,n,r,i,a){return"TBD(load_reg_src_off)"}rt_call(e,t,n){return"TBD(rt_call)"}call_lbl(e,t){return"TBD(call_lbl)"}call_reg(e){return"TBD(call_reg)"}helper_prologue(){return"TBD(lambda_prologue)"}helper_epilogue(){return"TBD(lambda_epilogue)"}pop_clean(e){return"TBD"}load_ptr_full(e,t){return"TBD(load_ptr_full)"}emit_int(e,t){return"TBD(emit_int)"}obj_header(e){return`.word ${e}`}string_literal(e,t){const r=n(t);return`\n .balign 4\n ${e}: ${this.obj_header(r.vt)}\n ${r.asm}\n`}hex_literal(e,t){return`\n.balign ${/f{16}/i.test(t)?8:4}\n${e}: ${this.obj_header("pxt::buffer_vt")}\n${r(t)}\n`}},e.utf8AsmStringLiteral=n,e.hexLiteralAsm=r,e.numBytes=function(e){let t=0;for(let n=e;n>0;n>>>=8)t++;return t||1};e.ProctoAssembler=class{constructor(t,n,r){this.resText="",this.exprStack=[],this.calls=[],this.proc=null,this.baseStackSize=0,this.labelledHelpers={},this.write=t=>{this.resText+=e.asmline(t)},this.t=t,this.bin=n,this.proc=r,this.proc&&this.work()}emitHelpers(){this.emitLambdaTrampoline(),this.emitArrayMethods(),this.emitFieldMethods(),this.emitBindHelper()}redirectOutput(t){let n=this.write,r="";this.write=t=>r+=e.asmline(t);try{t()}finally{this.write=n}return r}stackSize(){return this.baseStackSize+this.exprStack.length}stackAlignmentNeeded(t=0){if(!e.target.stackAlign)return 0;let n=e.target.stackAlign-(this.stackSize()+t&e.target.stackAlign-1);return n==e.target.stackAlign?0:n}getAssembly(){return this.resText}work(){this.write(`\n;\n; Function ${this.proc.getFullName()}\n;\n`);let t=this.proc.label(),n=t+"_pre",r=t+"_bkpt",i=t+"_locals",a=t+"_end";this.write(`${n}:`),this.emitLambdaWrapper(this.proc.isRoot),this.write(".section code"),this.write(`${t}:`),this.proc.classInfo&&this.proc.info.thisParameter&&!e.target.switches.skipClassCheck&&!e.target.switches.noThisCheckOpt&&(this.write("mov r7, lr"),this.write("ldr r0, [sp, #0]"),this.emitInstanceOf(this.proc.classInfo,"validate"),this.write("mov lr, r7")),this.write(`\n${t}_nochk:\n @stackmark func\n @stackmark args\n`),this.proc.fillDebugInfo=t=>{let o=t.getLabels();this.proc.debugInfo={locals:(1==this.proc.seqNo?this.bin.globals:this.proc.locals).map((e=>e.getDebugInfo())),args:this.proc.args.map((e=>e.getDebugInfo())),name:this.proc.getName(),codeStartLoc:e.U.lookup(o,i),codeEndLoc:e.U.lookup(o,a),bkptLoc:e.U.lookup(o,r),localsMark:e.U.lookup(t.stackAtLabel,i),idx:this.proc.seqNo,calls:this.calls,size:e.U.lookup(o,a)+2-e.U.lookup(o,n)};for(let n of this.calls)n.addr=e.U.lookup(o,n.callLabel),n.stack=e.U.lookup(t.stackAtLabel,n.callLabel),n.callLabel=void 0;for(let n=0;n<this.proc.body.length;++n){let r=this.proc.body[n].breakpointInfo;if(r){let n=e.U.lookup(t.stackAtLabel,`__brkp_${r.id}`);n!==this.proc.debugInfo.localsMark&&(console.log(r),console.log(t.stackAtLabel),e.U.oops(`offset doesn't match: ${n} != ${this.proc.debugInfo.localsMark}`))}}},this.bin.options.breakpoints&&this.write(this.t.debugger_proc(r)),this.baseStackSize=1;let o=this.proc.locals.length;this.write("push {lr}"),this.write(".locals:\n"),this.proc.perfCounterNo&&(this.write(this.t.emit_int(this.proc.perfCounterNo,"r0")),this.write("bl pxt::startPerfCounter")),this.write(this.t.proc_setup(o)),this.baseStackSize+=o,this.write("@stackmark locals"),this.write(`${i}:`);for(let t=0;t<this.proc.body.length;++t){let n=this.proc.body[t];switch(n.stmtKind){case e.ir.SK.Expr:this.emitExpr(n.expr);break;case e.ir.SK.StackEmpty:if(this.exprStack.length>0){for(let e of this.proc.body.slice(t-4,t+1))console.log(`PREVSTMT ${e.toString().trim()}`);for(let e of this.exprStack)console.log(`EXPRSTACK ${e.currUses}/${e.totalUses} E: ${e.toString()}`);e.oops("stack should be empty")}this.write("@stackempty locals");break;case e.ir.SK.Jmp:this.emitJmp(n);break;case e.ir.SK.Label:this.write(n.lblName+":"),this.validateJmpStack(n);break;case e.ir.SK.Comment:this.write(`; ${n.expr.data}`);break;case e.ir.SK.Breakpoint:if(this.bin.options.breakpoints){let e=`__brkp_${n.breakpointInfo.id}`;n.breakpointInfo.isDebuggerStmt?this.write(this.t.debugger_stmt(e)):this.write(this.t.debugger_bkpt(e))}break;default:e.oops()}}e.assert(0<=o&&o<127),o>0&&this.write(this.t.pop_locals(o)),this.proc.perfCounterNo&&(this.write("mov r4, r0"),this.write(this.t.emit_int(this.proc.perfCounterNo,"r0")),this.write("bl pxt::stopPerfCounter"),this.write("mov r0, r4")),this.write(`${a}:`),this.write(this.t.proc_return()),this.write("@stackempty func"),this.write("@stackempty args"),this.write("; endfun")}mkLbl(e){let t=e+this.bin.lblNo++;return"_"!=t[0]&&(t="."+t),t}dumpStack(){let e="[";for(let t of this.exprStack)e+=t.sharingInfo()+": "+t.toString()+"; ";return e+="]",e}terminate(t){e.assert(t.exprKind==e.ir.EK.SharedRef);let n=t.args[0];e.U.assert(n.currUses!=n.totalUses),e.U.assert(this.exprStack[0]===n,"term at top");let r=1;for(;r<this.exprStack.length;){let e=this.exprStack[r];if(e.currUses!=e.totalUses)break;r++}return this.write(`@dummystack ${r}`),this.write(this.t.pop_locals(r)),r}validateJmpStack(t,n=0){let r=this.exprStack.length-n;null==t.lblStackSize?t.lblStackSize=r:t.lblStackSize!=r&&(console.log(t.lblStackSize,r),console.log(this.dumpStack()),e.U.oops("stack misaligned at: "+t.lblName))}emitJmp(t){let n=0;if(t.jmpMode==e.ir.JmpMode.Always)t.expr&&this.emitExpr(t.expr),t.terminateExpr&&(n=this.terminate(t.terminateExpr)),this.write(this.t.unconditional_branch(t.lblName)+" ; with expression");else{let r=this.mkLbl("jmpz");this.emitExpr(t.expr),(t.expr.exprKind!=e.ir.EK.RuntimeCall||"thumb::subs"!==t.expr.data&&!e.U.startsWith(t.expr.data,"_cmp_"))&&this.write(this.t.cmp_zero("r0")),t.jmpMode==e.ir.JmpMode.IfNotZero?this.write(this.t.beq(r)):this.write(this.t.bne(r)),t.terminateExpr&&(n=this.terminate(t.terminateExpr)),this.write(this.t.unconditional_branch(t.lblName)),this.write(r+":")}this.validateJmpStack(t.lbl,n)}clearStack(e=!1){let t=0;for(;this.exprStack.length>0&&this.exprStack[0].currUses==this.exprStack[0].totalUses;)t++,this.exprStack.shift();if(t&&this.write(this.t.pop_locals(t)),!e){let e=this.exprStack.filter((e=>e.currUses==e.totalUses&&-1!=e.irCurrUses));if(e.length>0){this.write(this.t.reg_gets_imm("r7",0));for(let t of e)t.irCurrUses=-1,this.write(this.loadFromExprStack("r7",t,0,!0))}}}emitExprInto(t,n){switch(t.exprKind){case e.ir.EK.NumberLiteral:"number"==typeof t.data?this.write(this.t.emit_int(t.data,n)):e.oops();break;case e.ir.EK.PointerLiteral:this.write(this.t.load_ptr_full(t.data,n));break;case e.ir.EK.SharedRef:let r=t.args[0];e.U.assert(!!r.currUses),e.U.assert(r.currUses<r.totalUses),r.currUses++;let i=this.exprStack.indexOf(r);if(e.U.assert(i>=0),0==i&&r.totalUses==r.currUses)this.write(this.t.pop_fixed([n])+` ; tmpref @${this.exprStack.length}`),this.exprStack.shift(),this.clearStack();else{let e=i.toString()+":"+this.exprStack.length;this.write(this.t.load_reg_src_off(n,"sp",e,!0)+" ; tmpref @"+(this.exprStack.length-i))}break;case e.ir.EK.CellRef:let a=t.data;if(a.isGlobal()){let e=this.bitSizeInfo(a.bitSize),t="#"+a.index;(e.needsSignExt||a.index>=e.immLimit)&&(this.write(this.t.emit_int(a.index,n)),t=n),this.write(this.t.load_reg_src_off("r7","r6","#0")),this.write(this.t.load_reg_src_off(n,"r7",t,!1,!1,e))}else{let[e,t,r]=this.cellref(a);this.write(this.t.load_reg_src_off(n,e,t,r))}break;default:e.oops()}}bitSizeInfo(t){let n={size:e.sizeOfBitSize(t),immLimit:128};return 1==n.size?n.immLimit=32:2==n.size&&(n.immLimit=64),1!=t&&3!=t||(n.needsSignExt=!0),n}emitExpr(t){switch(t.exprKind){case e.ir.EK.JmpValue:this.write("; jmp value (already in r0)");break;case e.ir.EK.Nop:this.write(this.t.nop());break;case e.ir.EK.FieldAccess:return this.emitExpr(t.args[0]),this.emitFieldAccess(t);case e.ir.EK.Store:return this.emitStore(t.args[0],t.args[1]);case e.ir.EK.RuntimeCall:return this.emitRtCall(t);case e.ir.EK.ProcCall:return this.emitProcCall(t);case e.ir.EK.SharedDef:return this.emitSharedDef(t);case e.ir.EK.Sequence:return t.args.forEach((e=>this.emitExpr(e))),this.clearStack();case e.ir.EK.InstanceOf:return this.emitExpr(t.args[0]),this.emitInstanceOf(t.data,t.jsInfo);default:return this.emitExprInto(t,"r0")}}emitFieldAccess(t,n=!1){let r=t.data,i=(n?"st":"ld")+"fld_"+r.classInfo.id+"_"+r.name;r.needsCheck&&!e.target.switches.skipClassCheck&&(this.emitInstanceOf(r.classInfo,"validate"),i+="_chk");let a=4*r.idx+4,o="#"+a;a>124&&(this.write(this.t.emit_int(a,"r3")),o="r3"),n?this.write(`str r1, [r0, ${o}]`):this.write(`ldr r0, [r0, ${o}]`)}writeFailBranch(){this.write(".fail:"),this.write("mov r1, lr"),this.write(this.t.callCPP("pxt::failedCast"))}emitClassCall(t){let n=t.virtualIndex+e.firstMethodOffset();this.write(this.t.emit_int(4*n,"r1"));let r=t.classInfo,i="";t.isThis&&(i+="_this"),this.emitLabelledHelper("classCall_"+r.id+i,(()=>{this.write("ldr r0, [sp, #0] ; ld-this"),this.loadVTable(),e.target.switches.skipClassCheck||t.isThis||this.checkSubtype(r),this.write("ldr r1, [r3, r1] ; ld-method"),this.write("bx r1 ; keep lr from caller"),this.writeFailBranch()}))}emitBindHelper(){this.write(`\n .section code\n _pxt_bind_helper:\n push {r0, r2}\n movs r0, #2\n ldlit r1, _pxt_bind_lit\n ${this.t.callCPP("pxt::mkAction")}\n pop {r1, r2}\n str r1, [r0, #12]\n str r2, [r0, #16]\n bx r4 ; return\n\n _pxt_bind_lit:\n ${this.t.obj_header("pxt::RefAction_vtable")}\n .short 0, 0 ; no captured vars\n .word .bindCode@fn\n .bindCode:\n ; r0-bind object, r4-#args\n cmp r4, #12\n bge .fail\n lsls r3, r4, #2\n ldlit r2, _pxt_copy_list\n ldr r1, [r2, r3]\n\n ldr r3, [r0, #12]\n ldr r2, [r0, #16]\n adds r4, r4, #1\n bx r1\n `),this.writeFailBranch(),this.write("_pxt_copy_list:"),this.write(e.U.range(12).map((e=>`.word _pxt_bind_${e}@fn`)).join("\n"));for(let e=0;e<12;e++){this.write(`\n _pxt_bind_${e}:\n sub sp, #4\n `);for(let t=0;t<e;++t)this.write(`ldr r1, [sp, #4*${t+1}]`),this.write(`str r1, [sp, #4*${t}]`);this.write(`\n push {r3} ; this-ptr\n mov r1, lr\n str r1, [sp, #4*${e+1}] ; store LR\n blx r2\n ldr r1, [sp, #4*${e+1}]\n add sp, #8\n bx r1\n `)}}ifaceCallCore(t,n,r=!1){this.write("\n ldr r2, [r3, #12] ; load mult\n movs r7, r2\n beq .objlit ; built-in types have mult=0\n muls r7, r1\n lsrs r7, r2\n lsls r7, r7, #1 ; r7 - hash offset\n ldr r3, [r3, #4] ; iface table\n adds r3, r3, r7\n ; r0-this, r1-method idx, r2-free, r3-hash entry, r4-num args, r7-free\n ");for(let t=0;t<e.vtLookups;++t)t>0&&this.write(" adds r3, #2"),this.write("\n ldrh r2, [r3, #0] ; r2-offset of descriptor\n ldrh r7, [r2, r3] ; r7-method idx\n cmp r7, r1\n beq .hit\n ");"get"==n?(this.write("movs r0, #0 ; undefined"),this.write("bx lr")):this.write("b .fail2"),this.write("\n .hit:\n adds r3, r3, r2 ; r3-descriptor\n ldr r2, [r3, #4]\n lsls r7, r2, #31\n beq .field\n ");const i=this.t.emit_int(t,"r4")+"\n bx r2";if("set"==n?this.write(`\n ; check for next descriptor\n ldrh r7, [r3, #8]\n cmp r7, r1\n bne .fail2 ; no setter!\n ldr r2, [r3, #12]\n ${i}\n `):(this.write("\n ; check if it's getter\n ldrh r7, [r3, #2]\n cmp r7, #1\n "),"get"==n?this.write(`\n bne .bind\n ${i}\n .bind:\n mov r4, lr\n bl _pxt_bind_helper\n `):this.write(`\n beq .doublecall\n ${i}\n .doublecall:\n ; call getter\n movs r4, #1\n push {r0, lr}\n blx r2\n pop {r1, r2}\n mov lr, r2\n b .moveArgs\n `)),r||(this.write(`\n .objlit:\n ldrh r2, [r3, #8]\n cmp r2, #${pxt.BuiltInType.RefMap}\n bne .fail\n mov r4, lr\n `),"set"==n&&this.write("ldr r2, [sp, #4] ; ld-val"),this.write(this.t.callCPP("set"==n?"pxtrt::mapSet":"pxtrt::mapGet")),n?this.write("bx r4"):(this.write("mov lr, r4"),this.write("b .moveArgs"))),this.write(".field:"),"set"==n?this.write("\n ldr r3, [sp, #4] ; ld-val\n str r3, [r0, r2] ; store field\n bx lr\n "):"get"==n?this.write("\n ldr r0, [r0, r2] ; load field\n bx lr\n "):this.write("\n ldr r0, [r0, r2] ; load field\n "),!n){this.write(".moveArgs:");for(let e=0;e<t;++e)e==t-1?this.write("movs r1, r0"):this.write(`ldr r1, [sp, #4*${e+1}]`),this.write(`str r1, [sp, #4*${e}]`);this.lambdaCall(t-1)}r&&this.write(".objlit:"),this.writeFailBranch(),this.write(`\n .fail2:\n ${this.t.callCPP("pxt::missingProperty")}\n `)}emitIfaceCall(t,n,r=""){e.U.assert(t.ifaceIndex>0),this.write(this.t.emit_int(t.ifaceIndex,"r1")),this.emitLabelledHelper("ifacecall"+n+"_"+r,(()=>{this.write("ldr r0, [sp, #0] ; ld-this"),this.loadVTable(),this.ifaceCallCore(n,r)}))}checkSubtype(e,t=".fail",n="r2"){e.classNo?(this.write(`ldrh ${n}, [r3, #8]`),this.write(`cmp ${n}, #${e.classNo}`),e.classNo==e.lastSubtypeNo?this.write(`bne ${t}`):(this.write(`blt ${t}`),this.write(`cmp ${n}, #${e.lastSubtypeNo}`),this.write(`bgt ${t}`))):this.write(`b ${t} ; always fails; class never instantiated`)}loadVTable(e="r2",t=".fail",n=".fail"){this.write(`lsls ${e}, r0, #30`),this.write(`bne ${t}`),this.write("cmp r0, #0"),this.write(`beq ${n}`),this.write("ldr r3, [r0, #0]"),this.write("; vtable in R3")}emitInstanceOf(t,n){let r="inst_"+t.id+"_"+n;this.emitLabelledHelper(r,(()=>{"validateNullable"==n?this.loadVTable("r2",".tagged",".undefined"):this.loadVTable("r2",".fail",".fail"),this.checkSubtype(t),"bool"==n?(this.write(`movs r0, #${e.taggedTrue}`),this.write("bx lr"),this.write(".fail:"),this.write(`movs r0, #${e.taggedFalse}`),this.write("bx lr")):"validate"==n?(this.write("bx lr"),this.writeFailBranch()):"validateNullable"==n?(this.write(".undefined:"),this.write("bx lr"),this.write(".tagged:"),this.write(`cmp r0, #${e.taggedNull} ; check for null`),this.write("bne .fail"),this.write("movs r0, #0"),this.write("bx lr"),this.writeFailBranch()):e.U.oops()}))}emitSharedDef(t){let n=t.args[0];if(e.U.assert(n.totalUses>=1),e.U.assert(0===n.currUses),n.currUses=1,1==n.totalUses)return this.emitExpr(n);this.emitExpr(n),this.exprStack.unshift(n),this.write(this.t.push_local("r0")+"; tmpstore @"+this.exprStack.length)}clearArgs(t,n){t.length,n.length;let r=t.concat(n);for(let t of r)0==t.currUses&&1==t.totalUses||(console.log(t.toString()),console.log(r.map((e=>e.toString()))),e.U.oops(`wrong uses: ${t.currUses} ${t.totalUses}`)),t.currUses=1;this.clearStack()}builtInClassNo(e){return{id:"builtin"+e,classNo:e,lastSubtypeNo:e}}emitBeginTry(e){this.emitExprInto(e.args[0],"r0"),this.write("bl _pxt_save_exception_state")}emitRtCall(t,n=null){let r=t.data;if("pxt::beginTry"==r)return this.emitBeginTry(t);let i=t.mask||{refMask:0},a=i.conversions||[],o=t.args.map(((e,t)=>({idx:t,expr:e,isSimple:e.isLiteral(),isRef:0!=(i.refMask&1<<t),conv:a.find((e=>e.argIdx==t))})));e.U.assert(o.length<=4);let s=!1;for(let t of e.U.reversed(o))t.expr.isPure()?t.isSimple||t.isRef||s&&!t.expr.isStateless()||(t.isSimple=!0):s=!0;for(let e of o)e.conv&&(e.isSimple=!1);let c=o.filter((e=>!e.isSimple));if(c.every((e=>e.expr.isPure()&&!e.isRef&&!e.conv))){for(let e of c)e.isSimple=!0;c=[]}let l=c[0],u=!0;if(1!=c.length||l.conv||l.isRef){for(let e of c)this.pushArg(e.expr);this.alignExprStack(0);let t=c.filter((e=>!!e.conv));if(t.length){const n=this.redirectOutput((()=>{let n=0;e.target.switches.inlineConversions||(this.t.stackAligned()?n+=2:n+=1);for(let r of t){if(e.isThumb()&&"pxt::toInt"==r.conv.method){this.write(this.loadFromExprStack("r0",r.expr,n)),this.write("asrs r0, r0, #1");let t=e.target.switches.inlineConversions?r.expr.getId():n;this.write("bcs .isint"+t),this.write("lsls r0, r0, #1"),this.alignedCall(r.conv.method,"",n),this.write(".isint"+t+":"),this.write(this.t.push_fixed(["r0"]))}else this.write(this.loadFromExprStack("r0",r.expr,n)),r.conv.refTag?e.target.switches.skipClassCheck||this.emitInstanceOf(this.builtInClassNo(r.conv.refTag),r.conv.refTagNullable?"validateNullable":"validate"):(this.alignedCall(r.conv.method,"",n),r.conv.returnsRef&&this.write(this.loadFromExprStack("r0",r.expr,n,!0))),this.write(this.t.push_fixed(["r0"]));n++}for(let r of e.U.reversed(t))n--,this.write(this.t.pop_fixed(["r"+r.idx]));for(let e of c)e.conv||this.write(this.loadFromExprStack("r"+e.idx,e.expr,n))}));e.target.switches.inlineConversions?this.write(n):this.emitHelper(this.t.helper_prologue()+n+this.t.helper_epilogue(),"conv")}else for(let e of c)this.write(this.loadFromExprStack("r"+e.idx,e.expr))}else this.emitExpr(l.expr),0!=l.idx&&this.write(this.t.mov("r"+l.idx,"r0")),u=!1;for(let e of o)e.isSimple&&this.emitExprInto(e.expr,"r"+e.idx);n?n():"langsupp::ignore"!=r&&this.alignedCall(r,"",0,!0),u&&this.clearArgs(c.filter((e=>!e.isRef)).map((e=>e.expr)),c.filter((e=>e.isRef)).map((e=>e.expr)))}alignedCall(t,n="",r=0,i=!1){(e.U.startsWith(t,"_cmp_")||e.U.startsWith(t,"_pxt_"))&&(i=!1),this.write(this.t.call_lbl(t,i,this.stackAlignmentNeeded(r))+n)}emitLabelledHelper(e,t){if(this.labelledHelpers[e])this.write(this.t.call_lbl(this.labelledHelpers[e]));else{let n=this.redirectOutput(t);this.emitHelper(n,e),this.labelledHelpers[e]=this.bin.codeHelpers[n]}}emitHelper(e,t="hlp"){if(!this.bin.codeHelpers[e]){let n=Object.keys(this.bin.codeHelpers).length;this.bin.codeHelpers[e]=`_${t}_${n}`}this.write(this.t.call_lbl(this.bin.codeHelpers[e]))}pushToExprStack(e){e.totalUses=1,e.currUses=0,this.exprStack.unshift(e)}pushArg(e){this.clearStack(!0);this.exprStack.length;this.emitExpr(e),this.clearStack(!0),this.write(this.t.push_local("r0")+" ; proc-arg"),this.pushToExprStack(e)}loadFromExprStack(t,n,r=0,i=!1){let a=this.exprStack.indexOf(n);return e.assert(a>=0),this.t.load_reg_src_off(t,"sp",(a+r).toString(),!0,i)+" ; estack\n"}pushDummy(){let t=e.ir.numlit(0);t.totalUses=1,t.currUses=1,this.exprStack.unshift(t)}alignExprStack(e){let t=this.stackAlignmentNeeded(e);if(t)for(let e=0;e<t;++e)this.write("push {r5} ; align"),this.pushDummy()}emitFieldMethods(){for(let t of["get","set"]){this.write(`\n .section code\n _pxt_map_${t}:\n `),this.loadVTable("r4"),this.checkSubtype(this.builtInClassNo(pxt.BuiltInType.RefMap),".notmap","r4"),this.write(this.t.callCPPPush("set"==t?"pxtrt::mapSetByString":"pxtrt::mapGetByString")),this.write(".notmap:");let n="set"==t?2:1,r=!1;this.write("mov r4, r3 ; save VT"),"set"==t?(e.target.stackAlign&&(r=!0,this.write("push {lr} ; align")),this.write("\n push {r0, r2, lr}\n mov r0, r1\n ")):this.write("\n push {r0, lr}\n mov r0, r1\n "),this.write("\n bl pxtrt::lookupMapKey\n mov r1, r0 ; put key index in r1\n ldr r0, [sp, #0] ; restore obj pointer\n mov r3, r4 ; restore vt\n bl .dowork\n "),this.write(this.t.pop_locals(n+(r?1:0))),this.write("pop {pc}"),this.write(".dowork:"),this.ifaceCallCore(n,t,!0)}}emitArrayMethod(t,n){this.write(`\n .section code\n _pxt_${n?"buffer":"array"}_${t}:\n `),this.loadVTable("r4");let r=this.builtInClassNo(n?pxt.BuiltInType.BoxedBuffer:pxt.BuiltInType.RefCollection);e.target.switches.skipClassCheck||this.checkSubtype(r,".fail","r4");const i=e.isStackMachine()||e.target.runtimeIsARM||n?"ldr":"ldrh";this.write(`\n asrs r1, r1, #1\n bcc .notint\n ${i} r4, [r0, #${n?4:8}]\n cmp r1, r4\n bhs .oob\n `);let a="r1";n?(a="#8",this.write("\n adds r4, r0, r1\n ")):this.write("\n lsls r1, r1, #2\n ldr r4, [r0, #4]\n ");let o=n?"b":"",s=n&&"get"==t?"lsls r0, r0, #1\nadds r0, #1":"";"set"==t?this.write(`\n str${o} r2, [r4, ${a}]\n bx lr\n `):this.write(`\n ldr${o} r0, [r4, ${a}]\n ${s}\n bx lr\n `),this.write(`\n .notint:\n lsls r1, r1, #1\n ${this.t.pushLR()}\n push {r0, r2}\n mov r0, r1\n ${this.t.callCPP("pxt::toInt")}\n mov r1, r0\n pop {r0, r2}\n .doop:\n ${this.t.callCPP(`Array_::${t}At`)}\n ${s}\n ${this.t.popPC()}\n `),this.writeFailBranch(),"get"==t?this.write(`\n .oob:\n movs r0, #${n?1:0} ; 0 or undefined\n bx lr\n `):this.write(`\n .oob:\n ${this.t.pushLR()}\n b .doop\n `)}emitArrayMethods(){for(let e of["get","set"])this.emitArrayMethod(e,!0),this.emitArrayMethod(e,!1)}emitLambdaTrampoline(){let t=e.target.stackAlign?"r3,":"";this.write(`\n .section code\n _pxt_lambda_trampoline:\n push {${t} r4, r5, r6, r7, lr}\n mov r4, r8\n mov r5, r9\n mov r6, r10\n mov r7, r11\n push {r4, r5, r6, r7} ; save high registers\n mov r4, r1\n mov r5, r2\n mov r6, r3\n mov r7, r0\n `),this.emitInstanceOf(this.builtInClassNo(pxt.BuiltInType.RefAction),"validate"),this.write(`\n mov r0, sp\n push {r4, r5, r6, r7} ; push args and the lambda\n mov r1, sp\n bl pxt::pushThreadContext\n mov r6, r0 ; save ctx or globals\n mov r5, r7 ; save lambda for closure\n mov r0, r5 ; also save lambda pointer in r0 - needed by pxt::bindMethod\n ldr r1, [r5, #8] ; ld fnptr\n movs r4, #3 ; 3 args\n blx r1 ; execute the actual lambda\n mov r7, r0 ; save result\n @dummystack 4\n add sp, #4*4 ; remove arguments and lambda\n mov r0, r6 ; or pop the thread context\n bl pxt::popThreadContext\n mov r0, r7 ; restore result\n pop {r4, r5, r6, r7} ; restore high registers\n mov r8, r4\n mov r9, r5\n mov r10, r6\n mov r11, r7\n pop {${t} r4, r5, r6, r7, pc}`),this.write(`\n .section code\n ; r0 - try frame\n ; r1 - handler PC\n _pxt_save_exception_state:\n push {r0, lr}\n ${this.t.callCPP("pxt::beginTry")}\n pop {r1, r4}\n str r1, [r0, #1*4] ; PC\n mov r1, sp\n str r1, [r0, #2*4] ; SP\n str r5, [r0, #3*4] ; lambda ptr\n bx r4\n `),this.write("\n .section code\n ; r0 - try frame\n ; r1 - thread context\n _pxt_restore_exception_state:\n mov r6, r1\n ldr r1, [r0, #2*4] ; SP\n mov sp, r1\n ldr r5, [r0, #3*4] ; lambda ptr\n ldr r1, [r0, #1*4] ; PC\n movs r0, #1\n orrs r1, r0\n bx r1\n "),this.write("\n .section code\n _pxt_stringConv:\n "),this.loadVTable(),this.checkSubtype(this.builtInClassNo(pxt.BuiltInType.BoxedString),".notstring"),this.write(`\n bx lr\n\n .notstring: ; no string, but vtable in r3\n ldr r7, [r3, #4*${e.firstMethodOffset()-1}]\n cmp r7, #0\n beq .fail\n push {r0, lr}\n movs r4, #1\n blx r7\n str r0, [sp, #0]\n b .numops\n\n .fail: ; not an object or no toString\n push {r0, lr}\n .numops:\n ${this.t.callCPP("numops::toString")}\n pop {r1}\n pop {pc}\n `)}emitProcCall(t){let n=[],r=null,i="",a=t.data;if(a.proc&&a.proc.inlineBody)return this.emitExpr(a.proc.inlineSelf(t.args));let o=-1==a.virtualIndex,s=!1;for(let r of e.U.reversed(t.args)){if(r.isPure()){if(!s||r.isStateless())continue}else s=!0;n.push(r)}if(n.reverse(),n.length<=1){let e=n[0];e&&(r=e,this.clearStack(!0),this.emitExpr(e),e==t.args[t.args.length-1]?i="r0":(i="r3",this.write(this.t.mov("r3","r0")))),n=[]}else for(let e of n)this.pushArg(e);this.alignExprStack(t.args.length);let c=["r1","r2","r3","r4"],l=[];if(n.length){let e=-1;for(let t of n)e=Math.max(this.exprStack.indexOf(t),e);if(e++,e<=c.length){c=c.slice(0,e),this.write(this.t.pop_fixed(c)),l=this.exprStack.splice(0,e);let t=[];for(let r=e-1;r>=0;--r)n.indexOf(l[r])<0&&(t.push(c[r]),this.exprStack.unshift(l[r]));t.length&&this.write(this.t.push_fixed(t))}else c=null,this.write(this.t.reg_gets_imm("r7",0))}let u=e.U.reversed(t.args);o&&u.unshift(u.pop());for(let t of u)if(n.indexOf(t)>=0){if(c)this.write(this.t.push_fixed([c[l.indexOf(t)]]));else{this.write(this.loadFromExprStack("r0",t)),this.write(this.t.push_local("r0")+" ; re-push"),this.write(this.loadFromExprStack("r7",t,1,!0));let n=this.exprStack.indexOf(t),r=e.ir.numlit(0);r.currUses=1,r.totalUses=1,this.exprStack[n]=r}this.exprStack.unshift(t)}else t===r?(this.write(this.t.push_local(i)+" ; the one arg"),this.pushToExprStack(t)):this.pushArg(t);let d=this.mkLbl("_proccall"),p=-1;if(o){let e=t.args.length-1;this.write(this.loadFromExprStack("r0",t.args[0])),this.emitLabelledHelper("lambda_call"+e,(()=>{this.lambdaCall(e),this.writeFailBranch()}))}else if(null!=a.virtualIndex||null!=a.ifaceIndex)null!=a.ifaceIndex?a.isSet?(e.assert(2==t.args.length),this.emitIfaceCall(a,t.args.length,"set")):this.emitIfaceCall(a,t.args.length,a.noArgs?"get":""):this.emitClassCall(a),this.write(d+":");else{let e=a.proc;p=e.seqNo,this.write(this.t.call_lbl(e.label()+(a.isThis?"_nochk":""))),this.write(d+":")}this.calls.push({procIndex:p,stack:0,addr:0,callLabel:d}),o&&t.args[0].isStateless()?this.clearArgs([t.args[0]],t.args.slice(1)):this.clearArgs([],t.args)}lambdaCall(t){this.write("; lambda call"),this.loadVTable(),e.target.switches.skipClassCheck||this.checkSubtype(this.builtInClassNo(pxt.BuiltInType.RefAction)),this.write(`\n movs r4, #${t}\n ldrh r1, [r0, #4]\n cmp r1, #0\n bne .pushR5\n ldr r1, [r0, #8]\n bx r1 ; keep lr from the caller\n .pushR5:\n sub sp, #8\n `);for(let e=0;e<t;++e)this.write(`ldr r1, [sp, #4*${e+2}]`),this.write(`str r1, [sp, #4*${e}]`);this.write(`\n str r5, [sp, #4*${t}]\n mov r1, lr\n str r1, [sp, #4*${t+1}]\n mov r5, r0\n ldr r7, [r5, #8]\n blx r7 ; exec actual lambda\n ldr r4, [sp, #4*${t+1}] ; restore what was in LR\n ldr r5, [sp, #4*${t}] ; restore lambda ctx\n `);for(let e=0;e<t;++e)this.write(`ldr r1, [sp, #4*${e}]`),this.write(`str r1, [sp, #4*${e+2}]`);this.write("\n add sp, #8\n bx r4\n "),this.write("; end lambda call")}emitStore(t,n){switch(t.exprKind){case e.ir.EK.CellRef:let r=t.data;if(this.emitExpr(n),r.isGlobal()){let e=this.bitSizeInfo(r.bitSize),t="#"+r.index;r.index>=e.immLimit&&(this.write(this.t.emit_int(r.index,"r1")),t="r1"),this.write(this.t.load_reg_src_off("r7","r6","#0")),this.write(this.t.load_reg_src_off("r0","r7",t,!1,!0,e))}else{let[e,t,n]=this.cellref(r);this.write(this.t.load_reg_src_off("r0",e,t,n,!0))}break;case e.ir.EK.FieldAccess:this.emitRtCall(e.ir.rtcall("dummy",[t.args[0],n]),(()=>this.emitFieldAccess(t,!0)));break;default:e.oops()}}cellref(t){if(t.isGlobal())throw e.oops();if(t.iscap){let n=t.index+3;return e.assert(0<=n&&n<32),["r5",n.toString(),!0]}if(t.isarg){return["sp","args@"+t.index.toString()+":"+this.baseStackSize,!1]}return["sp","locals@"+t.index,!1]}emitLambdaWrapper(e){if(this.write(""),this.write(".section code"),this.write(".balign 4"),e&&(this.proc.info.usedAsValue=!0),!this.proc.info.usedAsValue&&!this.proc.info.usedAsIface)return;this.proc.info.usedAsValue&&(this.write(this.proc.label()+"_Lit:"),this.write(this.t.obj_header("pxt::RefAction_vtable")),this.write(".short 0, 0 ; no captured vars"),this.write(`.word ${this.proc.label()}_args@fn`)),this.write(`${this.proc.label()}_args:`);let t=this.proc.args.length;if(0==t)return;this.write(`cmp r4, #${t}`),this.write(`bge ${this.proc.label()}_nochk`);let n=this.stackAlignmentNeeded(t+1),r=n?t+2:t+1;this.write("push {lr}"),this.emitLabelledHelper(`expand_args_${t}`,(()=>{this.write("movs r0, #0"),this.write("movs r1, #0"),n&&this.write("push {r0}");for(let e=t;e>0;e--)e!=t&&(this.write(`cmp r4, #${e}`),this.write(`blt .zero${e}`),this.write(`ldr r0, [sp, #${r-1}*4]`),this.write(`str r1, [sp, #${r-1}*4] ; clear existing`),this.write(`.zero${e}:`)),this.write("push {r0}");this.write("bx lr")})),this.write(`bl ${this.proc.label()}_nochk`);let i=t+(n?1:0);this.write(`@dummystack ${i}`),this.write(`add sp, #4*${i}`),this.write("pop {pc}")}emitCallRaw(t){let n=e.hexfile.lookupFunc(t);e.assert(!!n,"unimplemented raw function: "+t),this.alignedCall(t)}}}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){const t={"numops::adds":"+","numops::subs":"-","numops::div":"/","numops::mod":"%","numops::muls":"*","numops::ands":"&","numops::orrs":"|","numops::eors":"^","numops::bnot":"~","numops::lsls":"<<","numops::asrs":">>","numops::lsrs":">>>","numops::le":"<=","numops::lt":"<","numops::lt_bool":"<","numops::ge":">=","numops::gt":">","numops::eq":"==","pxt::eq_bool":"==","pxt::eqq_bool":"===","numops::eqq":"===","numops::neqq":"!==","numops::neq":"!="},n={"pxsim.Boolean_":"","pxsim.pxtcore":"","pxsim.String_":"","pxsim.ImageMethods":"","pxsim.Array_":"","pxsim.pxtrt":"","pxsim.numops":""},r={"pxsim.Array_.getAt":"","pxsim.Array_.length":"","pxsim.Array_.mk":"","pxsim.Array_.push":"","pxsim.Boolean_.bang":"","pxsim.String_.concat":"","pxsim.String_.stringConv":"","pxsim.numops.toBool":"","pxsim.numops.toBoolDecr":"","pxsim.pxtcore.mkAction":"","pxsim.pxtcore.mkClassInstance":"","pxsim.pxtrt.ldlocRef":"","pxsim.pxtrt.mapGetByString":"","pxsim.pxtrt.stclo":"","pxsim.pxtrt.stlocRef":""};function i(e){let t="";for(let n of Object.keys(e)){const r=n.replace(/\./g,"_");e[n]=r,t+=`const ${r} = ${n};\n`}return t}function a(e){"pxt."==(e=e.replace(/::/g,".")).slice(0,4)&&(e="pxtcore."+e.slice(4));const t="pxsim."+e;if(r.hasOwnProperty(t))return r[t];const i=t.lastIndexOf(".");if(i>0){const e=t.slice(0,i);if(n.hasOwnProperty(e))return n[e]+t.slice(i)}return t}e.isBuiltinSimOp=function(n){return!!e.U.lookup(t,n.replace(/\./g,"::"))},e.shimToJs=a;const o=["runtime","oops","doNothing","pxsim","globals","maybeYield","setupDebugger","isBreakFrame","breakpoint","trace","checkStack","leave","checkResumeConsumed","setupResume","setupLambda","checkSubtype","failedCast","buildResume","mkVTable","bind","leaveAccessor"];e.jsEmit=function(s){let c="(function (ectx) {\n'use strict';\n";for(let e of o)c+=`const ${e} = ectx.${e};\n`;c+="const __this = runtime;\n",c+="const pxtrt = pxsim.pxtrt;\n",c+="let yieldSteps = 1;\n",c+="ectx.setupYield(function() { yieldSteps = 100; })\n",c+="pxsim.setTitle("+JSON.stringify(s.getTitle())+");\n";let l={},u={};for(let e of s.res.configData||[])l[e.key+""]=e.value,u[e.name]=e.key;c+="pxsim.setConfigData("+JSON.stringify(l,null,1)+", "+JSON.stringify(u,null,1)+");\n",c+="pxtrt.mapKeyNames = "+JSON.stringify(s.ifaceMembers,null,1)+";\n";const d=s.setPerfCounters(["SysScreen"]);c+="__this.setupPerfCounters("+JSON.stringify(d,null,1)+");\n",c+=i(r),c+=i(n);let p=0,f=0;s.procs.forEach((n=>{let r;n.cachedJS?(r=n.cachedJS,p+=r.length):(r=function(n,r){if(r.cachedJS)return r.cachedJS;let i="",o=e=>{i+=e+"\n"},s=e=>{i+=" "+e+"\n"},c=e.ir.EK,l=[],u=0,d={},p="";o(`\nfunction ${r.label()}(s) {\nlet r0 = s.r0, step = s.pc;\ns.pc = -1;\n`),r.perfCounterNo&&o(`if (step == 0) __this.startPerfCounter(${r.perfCounterNo});\n`);o("\nwhile (true) {\nif (yieldSteps-- < 0 && maybeYield(s, step, r0) || runtime !== pxsim.runtime) return null;\nswitch (step) {\n case 0:\n"),r.locals.forEach((e=>{s(`${v(e)} = undefined;`)})),r.args.length&&(s("if (s.lambdaArgs) {"),r.args.forEach(((e,t)=>{s(` ${v(e)} = (s.lambdaArgs[${t}]);`)})),s(" s.lambdaArgs = null;"),s("}"));r.classInfo&&r.info.thisParameter&&(s("r0 = s.arg0;"),E(r.classInfo,"validate"));let f=0,_=[];for(let t of r.body)t.stmtKind==e.ir.SK.Label&&t.lblNumUses>0&&(t.lblId=++f);let m=0;for(let t of r.body){switch(t.stmtKind){case e.ir.SK.Expr:T(t.expr);break;case e.ir.SK.StackEmpty:P();break;case e.ir.SK.Jmp:let n=!1;for(let i=m+1;i<r.body.length&&r.body[i].stmtKind==e.ir.SK.Label;++i)if(t.lbl==r.body[i]){n=!0;break}b(t,n);break;case e.ir.SK.Label:t.lblNumUses>0&&o(` case ${t.lblId}:`);break;case e.ir.SK.Comment:o(`// ${t.expr.data}`);break;case e.ir.SK.Breakpoint:y(t);break;default:e.oops()}m++}P(),r.perfCounterNo&&o(`__this.stopPerfCounter(${r.perfCounterNo});\n`);r.isGetter()?s("return leaveAccessor(s, r0)"):s("return leave(s, r0)");o(" default: oops()"),o("} } }");let g=e.nodeLocationInfo(r.action);g.functionName=r.getName(),g.argumentNames=r.args&&r.args.map((e=>e.getName())),o(`${r.label()}.info = ${JSON.stringify(g)}`),r.isGetter()&&o(`${r.label()}.isGetter = true;`);r.isRoot&&o(`${r.label()}.continuations = [ ${_.join(",")} ]`);return o(h(r.label()+"_mk",r.label(),u,Object.keys(d))),o(p),r.cachedJS=i,i;function h(e,t,n,r){let i="";i+=`\nfunction ${e}(s) {\n checkStack(s.depth);\n return {\n parent: s, fn: ${t}, depth: s.depth + 1,\n pc: 0, retval: undefined, r0: undefined, overwrittenPC: false, lambdaArgs: null,\n`;for(let e=0;e<n;++e)i+=` tmp_${e}: undefined,\n`;for(let e of r)i+=` ${e}: undefined,\n`;return i+="} }\n",i}function y(e){let t,i=e.breakpointInfo.id;if(s(`s.lastBrkId = ${i};`),n.options.breakpoints){t=++f;let a=`return breakpoint(s, ${t}, ${i}, r0);`;e.breakpointInfo.isDebuggerStmt?s(a):(s(`if ((breakpoints[0] && isBreakFrame(s)) || breakpoints[${i}]) ${a}`),n.options.trace&&s(`else return trace(${i}, s, ${t}, ${r.label()}.info);`))}else{if(!n.options.trace)return;t=++f,s(`return trace(${i}, s, ${t}, ${r.label()}.info);`)}o(` case ${t}:`)}function v(e){if(e.isGlobal())return"globals."+e.uniqueName();if(e.iscap)return`s.caps[${e.index}]`;const t=e.uniqueName();return d[t]=!0,"s."+t}function b(t,n){if(t.lbl.lblNumUses==e.ir.lblNumUsesJmpNext||n)return e.assert(t.jmpMode==e.ir.JmpMode.Always),void(t.expr&&T(t.expr));e.assert(t.lbl.lblNumUses>0);let r=`{ step = ${t.lbl.lblId}; continue; }`;t.jmpMode==e.ir.JmpMode.Always?(t.expr&&T(t.expr),s(r)):(T(t.expr),t.jmpMode==e.ir.JmpMode.IfNotZero?s(`if (r0) ${r}`):s(`if (!r0) ${r}`))}function x(e){switch(e.exprKind){case c.NumberLiteral:case c.PointerLiteral:case c.SharedRef:case c.CellRef:return!0;default:return!1}}function k(e){return x(e)?S(e):(T(e),"r0")}function S(t){switch(t.exprKind){case c.NumberLiteral:if(!0===t.data)return"true";if(!1===t.data)return"false";if(null===t.data)return"null";if(void 0===t.data)return"undefined";if("number"==typeof t.data)return t.data+"";throw e.oops("invalid data: "+typeof t.data);case c.PointerLiteral:if(t.ptrlabel())return t.ptrlabel().lblId+"";if(null!=t.hexlit())return p+=`const ${t.data} = pxsim.BufferMethods.createBufferFromHex("${t.hexlit()}")\n`,t.data;if("string"==typeof t.jsInfo)return t.jsInfo;e.U.oops();case c.SharedRef:let n=t.args[0];e.U.assert(!!n.currUses),e.U.assert(n.currUses<n.totalUses),n.currUses++;let r=l.indexOf(n);return e.U.assert(r>=0),"s.tmp_"+r;case c.CellRef:return v(t.data);default:throw e.oops()}}function T(e){switch(e.exprKind){case c.JmpValue:s("// jmp value (already in r0)");break;case c.Nop:s("// nop");break;case c.FieldAccess:let t=e.data,n=t.shimName,r=k(e.args[0]);return n?void s(`r0 = ${r}${n};`):void s(`r0 = ${r}.fields["${t.name}"];`);case c.Store:return I(e.args[0],e.args[1]);case c.RuntimeCall:return A(e);case c.ProcCall:return N(e);case c.SharedDef:return D(e);case c.Sequence:return e.args.forEach(T);case c.InstanceOf:return T(e.args[0]),void E(e.data,e.jsInfo);default:s(`r0 = ${S(e)};`)}}function C(e,t="r0"){return`checkSubtype(${t}, ${`${e.id}_VT`})`}function E(t,n,r="r0"){"bool"==n?s(`r0 = ${C(t)};`):"validate"==n?s(`if (!${C(t,r)}) failedCast(${r});`):e.U.oops()}function D(t){let n=t.args[0];if(e.U.assert(n.totalUses>=1),e.U.assert(0===n.currUses),n.currUses=1,1==n.totalUses)return T(n);{const e=l.length;l.push(n);let t=k(n);"r0"!=t&&(t="r0 = "+t),s(`s.tmp_${e} = ${t};`)}}function A(n){let r=e.ir.flattenArgs(n.args);r.precomp.forEach(T);let i=n.data,c=r.flattened.map(S);if("langsupp::ignore"==i)return;let l="";if(l="."==i[0]?`${c[0]}${i}(${c.slice(1).join(", ")})`:"="==i[0]?`(${c[0]})${i.slice(1)} = (${c[1]})`:e.U.startsWith(i,"new ")?`new ${a(i.slice(4))}(${c.join(", ")})`:e.U.lookup(t,i)?2==c.length?`(${c[0]} ${e.U.lookup(t,i)} ${c[1]})`:`(${e.U.lookup(t,i)} ${c[0]})`:`${a(i)}(${c.join(", ")})`,0==n.callingConvention)s(`r0 = ${l};`);else{let e=++f;_.push(e),"String_::stringConv"==i&&s(`if ((${c[0]}) && (${c[0]}).vtable) {`),2==n.callingConvention?s(`(function(cb) { ${l}.then(cb) })(buildResume(s, ${e}));`):(s(`setupResume(s, ${e});`),s(`${l};`)),s("checkResumeConsumed();"),s("return;"),"String_::stringConv"==i&&s(`} else { s.retval = (${c[0]}) + ""; }`),o(` case ${e}:`),s("r0 = s.retval;")}}function N(t){const i=t.data,a=i.proc;if(a&&a.inlineBody)return T(a.inlineSelf(t.args));const c=e.ir.rtcall("<frame>",[]);c.totalUses=1,c.currUses=0;const u=l.length;l.push(c);const d=`s.tmp_${u}`,p=++f,_=-1==i.virtualIndex;if(a)s(`${d} = ${a.label()}_mk(s);`);else{let a="generic";null!=i.ifaceIndex?a="if_"+n.ifaceMembers[i.ifaceIndex]:_?a="lambda":null!=i.virtualIndex?a=i.classInfo.id+"_v"+i.virtualIndex:e.U.oops();const o=t.args.length;a+="_"+o+"_mk",n.recordHelper(r.usingCtx,a,(()=>{const t=e.U.range(o).map((e=>"arg"+e));return h(a,"null",5,t)})),s(`${d} = ${a}(s);`)}t.args.forEach(((e,t)=>{let n=`arg${t}`;_&&(n=0==t?"argL":"arg"+(t-1)),s(`${d}.${n} = ${k(e)};`)}));let m=`s.pc = ${p}; return ${d};`;if(null!=i.callLocationIndex&&(m=`s.callLocIdx = ${i.callLocationIndex}; ${m}`),null!=i.ifaceIndex){e.U.assert(null==a);const r=n.ifaceMembers[i.ifaceIndex];e.U.assert(!!r,`no name for ${i.ifaceIndex}`),s(`if (!${d}.arg0.vtable.iface) {`);let o=t.args.map(((e,t)=>`${d}.arg${t}`));o.splice(1,0,JSON.stringify(r));const c=`pxsim_pxtrt.map${i.isSet?"Set":"Get"}ByString`;i.noArgs?s(` s.retval = ${c}(${o.join(", ")});`):(e.U.assert(!i.isSet),s(` setupLambda(${d}, ${c}(${o.slice(0,2).join(", ")}), ${t.args.length});`),s(` ${m}`)),s("} else {"),s(` ${d}.fn = ${d}.arg0.vtable.iface["${i.isSet?"set/":""}${r}"];`);let l=`${d}.arg0.fields["${r}"]`;i.isSet?(s(` if (${d}.fn === null) { ${l} = ${d}.arg1; }`),s(` else if (${d}.fn === undefined) { failedCast(${d}.arg0) } `)):i.noArgs?(s(` if (${d}.fn == null) { s.retval = ${l}; }`),s(` else if (!${d}.fn.isGetter) { s.retval = bind(${d}); }`)):(s(` if (${d}.fn == null) { setupLambda(${d}, ${l}, ${t.args.length}); ${m} }`),s(` else if (${d}.fn.isGetter) { ${d}.stage2Call = true; ${m}; }`)),s(` else { ${m} }`),s("}"),m=""}else if(-1==i.virtualIndex)e.U.assert(null==a),s(`setupLambda(${d}, ${d}.argL);`);else if(null!=i.virtualIndex){e.U.assert(null==a),e.assert(i.virtualIndex>=0),E(i.classInfo,"validate",d+".arg0");const t=i.classInfo.vtable[i.virtualIndex];s(`${d}.fn = ${d}.arg0.vtable.methods.${t.getName()};`)}else e.U.assert(null!=a);m&&s(m),o(` case ${p}:`),s("r0 = s.retval;"),c.currUses=1}function w(t){switch(t){case 0:return"";case 1:return"pxtrt.toInt8";case 3:return"pxtrt.toInt16";case 5:return"pxtrt.toInt32";case 2:return"pxtrt.toUInt8";case 4:return"pxtrt.toUInt16";case 6:return"pxtrt.toUInt32";default:throw e.oops()}}function I(t,n){switch(t.exprKind){case c.CellRef:let r=t.data,i=k(n);s(`${v(r)} = ${w(r.bitSize)}(${i});`);break;case c.FieldAccess:let a=t.data,o=a.shimName;o||(o=`.fields["${a.name}"]`),T(e.ir.rtcall("="+o,[t.args[0],n]));break;default:e.oops()}}function P(){for(let t of l)t.totalUses!==t.currUses&&e.oops();u=Math.max(l.length,u),l=[]}}(s,n),f+=r.length),c+="\n"+r+"\n"})),c+=e.U.values(s.codeHelpers).join("\n")+"\n",s.usedClassInfos.forEach((t=>{c+=function(t){e.U.assert(void 0!==t.classNo),e.U.assert(void 0!==t.lastSubtypeNo);let n=parseInt(t.attrs.maxBgInstances);n||(n=null);let r=`const ${t.id}_VT = mkVTable({\n name: ${JSON.stringify(e.getName(t.decl))},\n numFields: ${t.allfields.length},\n classNo: ${t.classNo},\n lastSubtypeNo: ${t.lastSubtypeNo},\n maxBgInstances: ${n},\n methods: {\n`;for(let e of t.vtable)r+=` "${e.getName()}": ${e.label()},\n`;r+=" },\n",r+=" iface: {\n";for(let e of t.itable)r+=` "${e.name}": ${e.proc?e.proc.label():"null"},\n`,e.setProc?r+=` "set/${e.name}": ${e.setProc.label()},\n`:e.proc||(r+=` "set/${e.name}": null,\n`);return r+=" },\n",t.toStringMethod&&(r+=" toStringMethod: "+t.toStringMethod.label()+",\n"),r+="});\n",r}(t)})),s.res.breakpoints&&(c+=`\nconst breakpoints = setupDebugger(${s.res.breakpoints.length}, [${s.globals.filter((e=>e.isUserVariable)).map((e=>`"${e.uniqueName()}"`)).join(",")}])\n`),c+=`\nreturn ${s.procs[0]?s.procs[0].label():"null"}\n})\n`;const _=c.length,m=e=>(100*e/_).toFixed(2)+"%",g=`// total=${c.length} new=${m(f)} cached=${m(p)} other=${m(_-f-p)}\n`;s.writeFile(e.BINARY_JS,g+c)}}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){e.thumbCmpMap={"numops::lt":"_cmp_lt","numops::gt":"_cmp_gt","numops::le":"_cmp_le","numops::ge":"_cmp_ge","numops::eq":"_cmp_eq","numops::eqq":"_cmp_eqq","numops::neq":"_cmp_neq","numops::neqq":"_cmp_neqq"};const t={"numops::adds":"_numops_adds","numops::subs":"_numops_subs","numops::orrs":"_numops_orrs","numops::eors":"_numops_eors","numops::ands":"_numops_ands","numops::lsls":"_numops_lsls","numops::asrs":"_numops_asrs","numops::lsrs":"_numops_lsrs","pxt::toInt":"_numops_toInt","pxt::fromInt":"_numops_fromInt"};class n extends e.AssemblerSnippets{stackAligned(){return e.target.stackAlign&&e.target.stackAlign>1}pushLR(){return this.stackAligned()?"push {lr, r5} ; r5 for align":"push {lr}"}popPC(){return this.stackAligned()?"pop {pc, r5} ; r5 for align":"pop {pc}"}nop(){return"nop"}mov(e,t){return`mov ${e}, ${t}`}helper_ret(){return"bx r4"}reg_gets_imm(e,t){return`movs ${e}, #${t}`}push_fixed(e){return"push {"+e.join(", ")+"}"}pop_fixed(e){return"pop {"+e.join(", ")+"}"}proc_setup(e,t){let n="";if(e>0){n+=" movs r0, #0\n";for(let t=0;t<e;++t)n+=" push {r0} ;loc\n"}return n}proc_return(){return"pop {pc}"}debugger_stmt(t){return e.oops(),`\n @stackempty locals\n ldr r0, [r6, #0] ; debugger\n subs r0, r0, #4 ; debugger\n${t}:\n ldr r0, [r0, #0] ; debugger\n`}debugger_bkpt(t){return e.oops(),`\n @stackempty locals\n ldr r0, [r6, #0] ; brk\n${t}:\n ldr r0, [r0, #0] ; brk\n`}debugger_proc(t){return e.oops(),`\n ldr r0, [r6, #0] ; brk-entry\n ldr r0, [r0, #4] ; brk-entry\n${t}:`}push_local(e){return`push {${e}}`}push_locals(e){return`sub sp, #4*${e} ; push locals ${e} (align)`}pop_locals(e){return`add sp, #4*${e} ; pop locals ${e}`}unconditional_branch(e){return"bb "+e}beq(e){return"beq "+e}bne(e){return"bne "+e}cmp(e,t){return"cmp "+e+", "+t}cmp_zero(e){return"cmp "+e+", #0"}load_reg_src_off(e,t,n,r,i,a){n=n.replace(/:\d+$/,""),r&&(n=`#4*${n}`);let o="str",s="ldr";return a&&(32==a.immLimit?o="strb":64==a.immLimit&&(o="strh"),s=a.needsSignExt?o.replace("str","ldrs"):o.replace("str","ldr")),i?`${o} ${e}, [${t}, ${n}]`:`${s} ${e}, [${t}, ${n}]`}rt_call(e,t,n){return e+" "+t+", "+n}alignedCall(e,t){return t?`${this.push_locals(t)}\nbl ${e}\n${this.pop_locals(t)}`:"bl "+e}call_lbl(n,r,i){let a=e.U.lookup(t,n);return a&&(n=a,r=!1),!r&&n.indexOf("::")>0&&(r=!0),r?this.callCPP(n,i):this.alignedCall(n,i)}call_reg(e){return"blx "+e}helper_prologue(){return`\n @stackmark args\n ${this.pushLR()}\n`}helper_epilogue(){return`\n ${this.popPC()}\n @stackempty args\n`}load_ptr_full(t,n){return e.assert(!!t),`\n ldlit ${n}, ${t}\n`}load_vtable(e,t){return`ldr ${e}, [${t}, #0]`}lambda_init(){return"\n mov r5, r0\n mov r4, lr\n bl pxtrt::getGlobalsPtr\n mov r6, r0\n bx r4\n"}saveThreadStack(){return"mov r7, sp\n str r7, [r6, #4]\n"}restoreThreadStack(){return e.target.switches.gcDebug?"movs r7, #0\n str r7, [r6, #4]\n":""}callCPPPush(e){return this.pushLR()+"\n"+this.callCPP(e)+"\n"+this.popPC()+"\n"}callCPP(e,t){return this.saveThreadStack()+this.alignedCall(e,t)+"\n"+this.restoreThreadStack()}inline_decr(e){return`\n lsls r1, r0, #30\n bne .tag${e}\n bl _pxt_decr\n.tag${e}:\n`}arithmetic(){let t="";const n=e=>{let t=".boxed:\n";return t+=`\n ${this.pushLR()}\n push {r0, r1}\n ${this.saveThreadStack()}\n ${e}\n ${this.restoreThreadStack()}\n add sp, #8\n ${this.popPC()}\n `,t},r=e=>{t+=`\n_numops_${e}:\n @scope _numops_${e}\n lsls r2, r0, #31\n beq .boxed\n lsls r2, r1, #31\n beq .boxed\n`},i=e=>{t+=" blx lr\n",t+=n(`bl numops::${e}`)};for(let e of["adds","subs"])r(e),t+=`\n subs r2, r1, #1\n ${e} r2, r0, r2\n bvs .boxed\n movs r0, r2\n`,i(e);for(let e of["ands","orrs","eors"])r(e),t+=` ${e} r0, r1\n`,"eors"==e&&(t+=" adds r0, r0, #1\n"),i(e);for(let e of["lsls","lsrs","asrs"])r(e),t+="\n ; r3 := (r1 >> 1) & 0x1f\n lsls r3, r1, #26\n lsrs r3, r3, #27\n","asrs"==e?t+="\n asrs r0, r3\n movs r2, #1\n orrs r0, r2\n":(t+="lsrs"==e?"\n asrs r2, r0, #1\n lsrs r2, r3\n lsrs r3, r2, #30\n bne .boxed\n":"\n asrs r2, r0, #1\n lsls r2, r3\n lsrs r3, r2, #30\n beq .ok\n cmp r3, #3\n bne .boxed\n.ok:\n",t+="\n lsls r0, r2, #1\n adds r0, r0, #1\n"),i(e);t+=`\n@scope _numops_toInt\n_numops_toInt:\n asrs r0, r0, #1\n bcc .over\n blx lr\n.over:\n lsls r0, r0, #1\n ${this.callCPPPush("pxt::toInt")}\n\n_numops_fromInt:\n lsls r2, r0, #1\n asrs r1, r2, #1\n cmp r0, r1\n bne .over2\n adds r0, r2, #1\n blx lr\n.over2:\n ${this.callCPPPush("pxt::fromInt")}\n`;for(let r of Object.keys(e.thumbCmpMap))r=r.replace(/.*::/,""),t+=`\n.section code\n_cmp_${r}:\n lsls r2, r0, #31\n beq .boxed\n lsls r2, r1, #31\n beq .boxed\n subs r0, r1\n b${r.replace("qq","q").replace("neq","ne")} .true\n.false:\n movs r0, #0\n bx lr\n.true:\n movs r0, #1\n bx lr\n`,t+=n(`\n bl numops::${r}\n bl numops::toBoolDecr\n cmp r0, #0`);return t}emit_int(t,n){let r=!1;function i(t){e.assert(0<=t&&t<=255);let i="";return r?t&&(i=`adds ${n}, #${t}\n`):i=`movs ${n}, #${t}\n`,r=!0,i}function a(e=8){return`lsls ${n}, ${n}, #${e}\n`}e.assert(null!=t);let o=Math.floor(t),s=!1;o<0&&(s=!0,o=-o);let c=0;if(o>255){let t=o;for(;0==(1&t);)t>>>=1,c++;e.numBytes(t)<e.numBytes(o)?o=t:c=0}let l="";switch(e.numBytes(o)){case 4:l+=i(o>>>24&255),l+=a();case 3:l+=i(o>>>16&255),l+=a();case 2:l+=i(o>>>8&255),l+=a();case 1:l+=i(255&o);break;default:e.oops()}return c&&(l+=a(c)),s&&(l+=`negs ${n}, ${n}\n`),l.split("\n").length>4?`ldlit ${n}, ${Math.floor(t)}\n`:l}}e.ThumbSnippets=n}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){const n={"pxtrt::mapSetGeneric":"mapset","pxtrt::mapGetGeneric":"mapget"},r={};function i(e,n,r){const i=t.computeHashMultiplier(e.itable.map((e=>e.idx))),a=t.U.toArray(i.mapping);for(;3&a.length;)a.push(0);let o=`\n${c(e)}_start:\n .short ${8*e.allfields.length+8} ; size in bytes\n .byte ${pxt.ValTypeObject}, ${pxt.VTABLE_MAGIC} ; magic\n .short ${a.length} ; entries in iface hashmap\n .short ${e.lastSubtypeNo||e.classNo} ; last sub class-id\n .short ${e.classNo} ; class-id\n .short 0 ; reserved\n .word ${i.mult} ; hash-mult\n`;l()?o+="\n .word pxt::RefRecord_destroy\n .word pxt::RefRecord_print\n .word pxt::RefRecord_scan\n .word pxt::RefRecord_gcsize\n .word 0,0,0,0 ; keep in sync with VM_NUM_CPP_METHODS\n":o+="\n .word 0,0, 0,0, 0,0, 0,0 ; space for 4 (VM_NUM_CPP_METHODS) native methods\n",o+=`\n .balign 4\n${e.id}_IfaceVT:\n`;const s=a.length>>2;let u="",d=s,p={};for(let t of e.itable){p[t.idx+""]=d;const e=t.proc?t.proc.isGetter()?1:2:0;u+=` .short ${t.idx}, ${e} ; ${t.name}\n`,u+=` .word ${t.proc?t.proc.vtLabel()+"@fn":t.info}\n`,d+=1,t.setProc&&(u+=` .short ${t.idx}, 2 ; set ${t.name}\n`,u+=` .word ${t.setProc.vtLabel()}@fn\n`,d+=1)}u+=" .word 0, 0, 0, 0 ; the end\n",d+=1;for(let e=0;e<a.length;++e)r.itEntries++,a[e]&&r.itFullEntries++;return o+=" .short "+t.U.toArray(a).map(((e,t)=>p[e+""]||s)).join(", ")+"\n",o+=u,o+="\n",o}let a;function o(e){const t=e.getTime()/1e3;return`${t>>>0}, ${t/4294967296|0}`}!function(e){e[e.Invalid=0]="Invalid",e[e.InfoHeader=1]="InfoHeader",e[e.OpCodeMap=2]="OpCodeMap",e[e.NumberLiterals=3]="NumberLiterals",e[e.ConfigData=4]="ConfigData",e[e.IfaceMemberNames=5]="IfaceMemberNames",e[e.NumberBoxes=6]="NumberBoxes",e[e.Function=32]="Function",e[e.Literal=33]="Literal",e[e.VTable=34]="VTable"}(a||(a={}));let s={};function c(e){return e.classNo||(s[e.id]=e),e.id+"_VT"}function l(){return t.target.useESP}function u(e){return l()?`0xffffffff, ${e}`:`0xffffffff, 0xffffffff ; -> ${e}`}t.vmEmit=function(d,p){let f=`; VM start\n_img_start:\n${t.hexfile.hexPrelude()}\n`;s={};const _={dblText:[],dblBoxText:[],dbls:{},opcodeMap:{},opcodes:t.vm.opcodes.map((e=>"pxt::op_"+e.replace(/ .*/,"")))};for(_.opcodes.unshift(null);_.opcodes.length<128;)_.opcodes.push(null);let m=0;function g(e,t,n,r,i=0){if(f+=`\n; --- ${e}\n.section code\n .set ${e} = ${m}\n`,r)for(let e of r)f+=` .set ${e} = ${m}\n`;f+=`\n_start_${e}:\n .byte ${t}, 0x00\n .short ${i}\n .word _end_${e}-_start_${e}\n`,f+=n(),f+=`\n.balign 8\n_end_${e}:\n`,m++}const h=new Date(0);let y=t.U.toUTF8(p.name,!0);y.length>100&&(y=y.slice(0,100));let v=y.length+1;1&v&&v++;const b=128-v;g("_info",a.InfoHeader,(()=>`\n ; magic - \\0 added by assembler\n .string "\\nPXT64\\n"\n .hex 5471fe2b5e213768 ; magic\n .hex ${t.hexfile.hexTemplateHash()} ; hex template hash\n .hex 0000000000000000 ; @SRCHASH@\n .word ${d.globalsWords} ; num. globals\n .word ${d.nonPtrGlobals} ; non-ptr globals\n .word 0, 0 ; last usage time\n .word ${o(h)} ; installation time\n .word ${o(h)} ; publication time - TODO\n .word _img_end-_img_start ; total image size\n .space 60 ; reserved\n .string ${JSON.stringify(y)}\n .space ${b} ; pad to 128 bytes\n`)),d.procs.forEach((e=>{g(e.label(),a.Function,(()=>function(e,i,a){let o="";const s=e=>{o+=e+"\n"},d=e=>{o+=" "+e+"\n"},p=t.ir.EK;let f=[],_=[],m=!1,g=0,h=0;const y=8388607;pxt.options.debug&&console.log("EMIT",a.toString());v(),o="";for(let e of f)e.reset();return m=!0,t.U.assert(0==h),v(),o;function v(){s(`;\n; ${a.getFullName()}\n;`),d(".section code"),i.procs[0]==a&&s("; main"),d(`.word ${u("pxt::RefAction_vtable")}`),d(`.short 0, ${a.args.length} ; #args`),d(`.short ${a.captured.length}, 0 ; #cap`),d(".word .fnstart-_img_start, 0 ; func+possible padding"),g=a.locals.length+_.length,d(".fnstart:"),d(`pushmany ${g} ; incl. ${_.length} tmps`);for(let e of a.body)switch(e.stmtKind){case t.ir.SK.Expr:C(e.expr);break;case t.ir.SK.StackEmpty:N();for(let e of _)e&&t.oops(`uses: ${e.currUses}/${e.totalUses} ${e.toString()}`);break;case t.ir.SK.Jmp:b(e);break;case t.ir.SK.Label:s(`${e.lblName}:`);break;case t.ir.SK.Comment:s(`; ${e.expr.data}`);break;case t.ir.SK.Breakpoint:break;default:t.oops()}d(`ret ${a.args.length}, ${g}`)}function b(e){let n=e.lbl.lblName;e.jmpMode==t.ir.JmpMode.Always?(e.expr&&C(e.expr),d(`jmp ${n}`)):(C(e.expr),e.jmpMode==t.ir.JmpMode.IfNotZero?d(`jmpnz ${n}`):e.jmpMode==t.ir.JmpMode.IfZero?d(`jmpz ${n}`):t.oops())}function x(e){if(e.isGlobal())return t.U.assert(0==(3&e.index)),"glb "+(e.index>>2)+` ; ${e.getName()}`;if(e.iscap)return"cap "+e.index+` ; ${e.getName()}`;if(e.isarg){let n=a.args.length-e.index-1;return t.assert(n>=0,"arg#"+n),`loc ${h+g+2+n} ; ${e.getName()}`}{let n=e.index+_.length;return t.assert(!m||n<g,"cell#"+n),t.assert(n>=0,"cell#"+n),`loc ${h+n}`}}function k(n){const r=t.hexfile.lookupFunc(n);r||t.U.oops("missing function: "+n);let i=e.opcodeMap[r.name];null==i&&(i=e.opcodes.length,e.opcodes.push(r.name),e.opcodeMap[r.name]=i,r.value=i),d(`callrt ${n}`)}function S(e,n){"bool"==n?d(`checkinst ${c(e)}`):t.U.oops()}function T(n){switch(n.exprKind){case p.NumberLiteral:const r=t.taggedSpecial(n.data);if(null!=r)d(`ldspecial ${r} ; ${n.data}`);else{let r=n.data,i=0,a=0;const o=r<<1>>1!=r;if((0|r)==r){if(Math.abs(r)<=y)return void d(r<0?"ldintneg "+-r:`ldint ${r}`);i=(r<<1|1)>>>0,a=r<0?1:0}else{let e=new Float64Array(1);e[0]=r;let t=new Uint32Array(e.buffer);t[1]+=65536,i=t[0],a=t[1]}let s=i+","+a,c=t.U.lookup(e.dbls,s);if(null==c){if(c=e.dblText.length,e.dblText.push(`.word ${i}, ${a} ; ${c}: ${n.data}`),o){const t="pxt::number_vt";e.dblBoxText.push(`.word ${l()?t:`0xffffffff ; ${t}`}\n`);let n=new Float64Array(1);n[0]=r;let i=new Uint32Array(n.buffer);e.dblBoxText.push(`.word ${i[0]}, ${i[1]} ; ${r}\n`)}e.dbls[s]=c}d(`ldnumber ${c} ; ${n.data}`)}return;case p.PointerLiteral:return void d(`ldlit ${n.data}`);case p.SharedRef:let i=n.args[0];(!i.currUses||i.currUses>=i.totalUses)&&(console.log(i.sharingInfo()),t.U.assert(!1)),i.currUses++;let a=_.indexOf(i);return a<0&&(console.log(_,i),t.assert(!1)),d(`ldloc ${a+h}`+(i.currUses==i.totalUses?" ; LAST":"")),void N();case p.CellRef:return void d("ld"+x(n.data));case p.InstanceOf:C(n.args[0]),S(n.data,n.jsInfo);break;default:throw t.oops("kind: "+n.exprKind)}}function C(e){switch(e.exprKind){case p.JmpValue:d("; jmp value (already in r0)");break;case p.Nop:d("; nop");break;case p.FieldAccess:let t=e.data;C(e.args[0]),d(`ldfld ${t.idx}, ${c(t.classInfo)}`);break;case p.Store:return I(e.args[0],e.args[1]);case p.RuntimeCall:return A(e);case p.ProcCall:return w(e);case p.SharedDef:return E(e);case p.Sequence:return e.args.forEach(C);default:return T(e)}}function E(e){let n=e.args[0];if(t.U.assert(n.totalUses>=1),t.U.assert(0===n.currUses),n.currUses=1,f.push(n),1==n.totalUses)return C(n);{C(n);let e=-1;for(let t=0;t<_.length;++t)if(null==_[t]){e=t;break}e<0?(m&&(console.log(n,_),t.assert(!1,"missed tmp")),e=_.length,_.push(n)):_[e]=n,d(`stloc ${e+h}`)}}function D(){d("push"),h++}function A(e){let i=e.data;if("pxt::beginTry"==i)return void d(`try ${e.args[0].data}`);i=t.U.lookup(r,i)||i,N();let a=t.U.lookup(n,i),o=e.args,s=0;if("pxt::mkClassInstance"!=i){for(let e=0;e<o.length;++e)C(o[e]),e<o.length-1&&(D(),s++);"langsupp::ignore"==i?s&&d(`popmany ${s} ; ignore`):a?d(a):k(i),h-=s}else d(`newobj ${o[0].data}`)}function N(){for(let e=0;e<_.length;++e){let t=_[e];t&&t.currUses==t.totalUses&&(m||f.push(t),_[e]=null)}}function w(e){let n=e.data,r=n.proc;if(r&&r.inlineBody){const t=r.inlineSelf(e.args);return pxt.options.debug&&console.log("INLINE",e.toString(),"->",t.toString()),C(t)}let a=0;const o=e.args.slice(),s=-1==n.virtualIndex?o.shift():null;for(let e of o)C(e),D(),a++;let c=o.length;if(s)C(s),d(`callind ${c}`);else if(null!=n.ifaceIndex){let e=n.ifaceIndex+" ; ."+i.ifaceMembers[n.ifaceIndex];n.isSet?(d(`callset ${e}`),t.U.assert(2==c)):n.noArgs?(d(`callget ${e}`),t.U.assert(1==c)):d(`calliface ${c}, ${e}`)}else null!=n.virtualIndex?t.U.oops():d(`callproc ${r.label()}`);h-=a}function I(e,n){switch(e.exprKind){case p.CellRef:C(n);let r=e.data,i="st"+x(r);if(r.isGlobal()&&0!=r.bitSize){const e=t.sizeOfBitSize(r.bitSize)|(t.isBitSizeSigned(r.bitSize)?16:0);d("bitconv "+e)}d(i);break;case p.FieldAccess:let a=e.data;C(e.args[0]),D(),C(n),d(`stfld ${a.idx}, ${c(a.classInfo)}`),h--;break;default:t.oops()}}}(_,d,e)),[e.label()+"_Lit"])})),f+="_code_end:\n\n",f+="_helpers_end:\n\n",d.usedClassInfos.forEach((e=>{g(c(e),a.VTable,(()=>i(e,0,d)))})),t.U.values(s).forEach((e=>{e.itable=[],e.classNo=65520,g(c(e),a.VTable,(()=>i(e,0,d)))})),s={};let x=0;g("ifaceMemberNames",a.IfaceMemberNames,(()=>` .word ${d.ifaceMembers.length} ; num. entries\n`+d.ifaceMembers.map((e=>` .word ${d.emitString(e)} ; ${x++} .${e}`)).join("\n"))),f+="_vtables_end:\n\n",t.U.iterMap(d.hexlits,((e,n)=>{g(n,a.Literal,(()=>`.word ${u("pxt::buffer_vt")}\n`+t.hexLiteralAsm(e)),[],pxt.BuiltInType.BoxedBuffer)})),t.U.unique(d.ifaceMembers.concat(Object.keys(d.strings)),(e=>e)).forEach((e=>{const n=t.utf8AsmStringLiteral(e);let r=pxt.BuiltInType.BoxedString;"pxt::string_inline_ascii_vt"==n.vt?r=pxt.BuiltInType.BoxedString_ASCII:"pxt::string_skiplist16_packed_vt"==n.vt?r=pxt.BuiltInType.BoxedString_SkipList:"pxt::string_inline_utf8_vt"==n.vt?r=pxt.BuiltInType.BoxedString:t.oops("invalid vt");const i=`.word ${u(n.vt)}\n`+n.asm;g(d.strings[e],a.Literal,(()=>i),[],r)})),g("numberBoxes",a.NumberBoxes,(()=>_.dblBoxText.join("\n")+"\n.word 0, 0, 0 ; dummy entry to make sure not empty")),g("numberLiterals",a.NumberLiterals,(()=>_.dblText.join("\n")+"\n.word 0, 0 ; dummy entry to make sure not empty"));const k=d.res.configData||[];g("configData",a.ConfigData,(()=>k.map((e=>` .word ${e.key}, ${e.value} ; ${e.name}=${e.value}`)).join("\n")+"\n .word 0, 0"));let S=_.opcodes.map((e=>null==e?"":e)).join("\0")+"\0",T="";for(;S;){let e=S.slice(0,64);S=S.slice(64),1&e.length&&(e+="\0"),T+=".hex "+t.U.toHex(t.U.stringToUint8Array(e))+"\n"}g("opcodeMap",a.OpCodeMap,(()=>T)),f+="_literals_end:\n",f+="_img_end:\n",f+="\n; The end.\n",d.writeFile(t.BINARY_ASM,f);let C=t.assemble(p.target,d,f);const E=C.thumbFile.getSourceMap(),D=function(e){const n=[83,82,67,77,136,21,78,45,170,134,153,113,0,0,0,0];for(const r of Object.keys(e)){for(const e of t.U.stringToUint8Array(r))n.push(e);n.push(0);const a=e[r];let o=0,s=0;for(let e=0;e<a.length;e+=3)i(a[e]-o),i(a[e+1]-s>>1),i(a[e+2]>>1),o=a[e],s=a[e+1];n.push(255)}n.push(0),1&n.length&&n.push(0);const r=[];for(let e=0;e<n.length;e+=2)r.push(n[e]|n[e+1]<<8);return r;function i(e){if(0<=e&&e<240)n.push(e);else{let t=240;e<0&&(e=-e,t|=8);const r=n.length;n.push(null);let i=0;for(;0!=e;)n.push(255&e),e>>>=8,i++;n[r]=t|i}}}(E);C.src&&d.writeFile(t.BINARY_ASM,`; srcmap size: ${D.length<<1} bytes\n`+C.src);{let e="";for(let t of C.buf)e+=String.fromCharCode(255&t,t>>8);const n=t.U.sha256(e);for(let e=0;e<4;++e)C.buf[16+e]=parseInt(n.slice(4*e,4*e+4),16);E.__meta={name:p.name,programHash:C.buf[16]|C.buf[17]<<16}}if(d.writeFile(t.BINARY_SRCMAP,JSON.stringify(E)),pxt.options.debug){let e=C.thumbFile.peepCounts,t=Object.keys(e);t.sort(((t,n)=>e[n]-e[t]));for(let n of t.slice(0,50))console.log(`${n} ${e[n]}`)}if(C.buf){let n="";const r=C.buf;for(;15&r.length;)r.push(0);t.U.pushRange(r,D);for(let e of r)n+=String.fromCharCode(255&e,e>>8);if(n=e.pxtc.encodeBase64(n),l()){d.writeFile(t.BINARY_PXT64,n);const i=t.hexfile.patchHex(d,r,!1,!!t.target.useUF2)[0];d.writeFile(pxt.outputName(t.target),e.pxtc.encodeBase64(i))}else d.writeFile(pxt.outputName(t.target),n)}}}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){!function(n){let r,i;!function(e){e.DecompileLiterals="decompileLiterals",e.TaggedTemplate="taggedTemplate",e.DecompileIndirectFixedInstances="decompileIndirectFixedInstances",e.DecompileArgumentAsString="decompileArgumentAsString"}(r=n.DecompileParamKeys||(n.DecompileParamKeys={})),function(e){e[e.SingleLine=0]="SingleLine",e[e.MultiLine=1]="MultiLine"}(i=n.CommentKind||(n.CommentKind={})),n.FILE_TOO_LARGE_CODE=9266,n.DECOMPILER_ERROR=9267;const a=e.SyntaxKind,o=/^[^\f\n\r\t\v\u00a0\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]*$/,s=/^(?:Array<(.+)>)|(?:(.+)\[\])$/,c="math_number",l="math_number_minmax",u="math_integer",d="math_whole_number",p="text",f="logic_boolean",_={"+":{type:"math_arithmetic",op:"ADD"},"-":{type:"math_arithmetic",op:"MINUS"},"/":{type:"math_arithmetic",op:"DIVIDE"},"*":{type:"math_arithmetic",op:"MULTIPLY"},"**":{type:"math_arithmetic",op:"POWER"},"%":{type:"math_modulo",leftName:"DIVIDEND",rightName:"DIVISOR"},"<":{type:"logic_compare",op:"LT"},"<=":{type:"logic_compare",op:"LTE"},">":{type:"logic_compare",op:"GT"},">=":{type:"logic_compare",op:"GTE"},"==":{type:"logic_compare",op:"EQ"},"===":{type:"logic_compare",op:"EQ"},"!=":{type:"logic_compare",op:"NEQ"},"!==":{type:"logic_compare",op:"NEQ"},"&&":{type:"logic_operation",op:"AND"},"||":{type:"logic_operation",op:"OR"}},m=/^\s*\/\/\s*(.*)$/,g=/^\s*(?:(?:(?:\/\*\*?)|(?:\*))(?!\/))?\s*(.*?)(?:\*?\*\/)?$/;class h{constructor(e){this.renames=e,this.renames.sort(((e,t)=>e.span.start-t.span.start))}getRenamesInSpan(e,t){const n=[];for(const r of this.renames){if(r.span.start>t)break;r.span.start>=e&&n.push(r)}return n}getRenameForPosition(e){for(const t of this.renames){if(t.span.start>e)return;if(t.span.start===e)return t}}}function y(e,t,n=!0){if(1===e.length&&"x"!==e&&"y"!==e&&"z"!==e){const r=e.charCodeAt(0);if(r>=97&&r<=122){const e=r-97;for(let r=1;r<26;r++){const i=String.fromCharCode(97+(e+r)%26);if("x"!==i&&"y"!==i&&"z"!==i&&!t[i])return n&&(t[i]=!0),i}}}for(let r=2;;r++){const i=e+r;if(!t[i])return n&&(t[i]=!0),i}}let v;function b(n,i,o=!1,s=!1){switch(n.kind){case a.WhileStatement:case a.IfStatement:case a.Block:return;case a.ExpressionStatement:return b(n.expression,i,o,s);case a.VariableStatement:return function(e,t){for(const n of e.declarationList.declarations){const e=c(n,t);if(e)return e}return}(n,i);case a.CallExpression:return function(n,i,o=!1,s=!1){const c=t.pxtInfo(n).callInfo;if(!c)return t.Util.lf("Function call not supported in the blocks");const l=i.attrs(c);let u;e.isIdentifier(n.expression)&&(u=i.declaredFunctions[n.expression.text]);if(!o&&c.isExpression&&!u){if(!i.aliasBlocks[c.qName])return t.Util.lf("No output expressions as statements");c.decompilerBlockAlias=i.aliasBlocks[c.qName]}if("Math.pow"==c.qName)return;if(pxt.Util.startsWith(c.qName,"Math.")){if(R(c.qName.substring(5)))return}if(l.blockId===t.PAUSE_UNTIL_TYPE){const e=n.arguments[0];if(1===n.arguments.length&&y(e))return;return t.Util.lf("Predicates must be inline expressions that return a value")}const d=w(c,l);if(d&&!l.handlerStatement&&!s)return t.Util.lf("Events must be top level");if(!l.blockId||!l.block){const e=pxt.blocks.builtinFunctionInfo[c.qName];if(!e)return u?u.parameters.length!==c.args.length?t.Util.lf("Function calls in blocks must have the same number of arguments as the function definition"):void 0:t.Util.lf("Call statements must have a valid declared function");l.blockId=e.blockId}const p=O(c,i.blocks),f=i.blocks.apis.byQName[c.qName],_=pxt.blocks.compileInfo(f),m=_.parameters.length+(_.thisParameter?1:0);if(l.imageLiteral){if(c.args.length-m>1)return t.Util.lf("Function call has more arguments than are supported by its block");let e=n.arguments[0];if(e.kind!=a.StringLiteral&&e.kind!=a.NoSubstitutionTemplateLiteral)return t.Util.lf("Only string literals supported for image literals");const r=(e.text||"").replace(/\s+/g,""),i=l.imageLiteralRows||5,o=(l.imageLiteralColumns||5)*l.imageLiteral,s=o*i;return o*i!=r.length?t.Util.lf("Invalid image pattern ({0} expected vs {1} actual)",s,r.length):void 0}const g=c.args.length-m;if(g>0&&!h()){let e=g;if(d&&e--,l.defaultInstance&&e--,e>0)return t.Util.lf("Function call has more arguments than are supported by its block")}if(_.parameters.length||d){let e;const t=l.defaultInstance||!!_.thisParameter;if(p.forEach(((n,r)=>{e||t&&0===r||(t&&r--,e=v(n))})),e)return e}if(f){const e=i.blocks.apis.byQName[f.namespace];if(e&&e.attributes.fixedInstances&&!e.attributes.decompileIndirectFixedInstances&&c.args.length){const e=t.pxtInfo(c.args[0]).callInfo;if(!e||!i.attrs(e).fixedInstance)return t.Util.lf("Fixed instance APIs can only be called directly from the fixed instance")}}return;function h(){if(l.mutatePropertyEnum&&2===g&&c.args.length>=2){const e=c.args[c.args.length-2],t=c.args[c.args.length-1];if(e.kind===a.ArrayLiteralExpression&&P(t)){const n=[];if(!e.elements.some((e=>e.kind!==a.PropertyAccessExpression||e.expression.kind!==a.Identifier||(n.push(e.name.text),e.expression.text!==l.mutatePropertyEnum)))){const e=T(t);if(e){const t=e[0];return t.length===n.length&&!n.some((e=>-1===t.indexOf(e)))}}}}return!1}function y(e){if(e.kind!==a.FunctionExpression&&e.kind!==a.ArrowFunction)return!1;const n=e;if(function(e){switch(e.kind){case a.BinaryExpression:const n=e.operatorToken.kind;return n!=a.PlusEqualsToken&&n!=a.MinusEqualsToken&&n!=a.EqualsToken;case a.PrefixUnaryExpression:{let t=e.operator;return t!=a.PlusPlusToken&&t!=a.MinusMinusToken}case a.PostfixUnaryExpression:{let t=e.operator;return t!=a.PlusPlusToken&&t!=a.MinusMinusToken}case a.CallExpression:const r=t.pxtInfo(e).callInfo;return t.assert(!!r),r.isExpression;case a.ParenthesizedExpression:case a.NumericLiteral:case a.StringLiteral:case a.NoSubstitutionTemplateLiteral:case a.TrueKeyword:case a.FalseKeyword:case a.NullKeyword:case a.TaggedTemplateExpression:return!0;default:return!1}}(n.body))return!0;const r=n.body;if(1===r.statements.length){if(D(r.statements[0]).kind===a.ReturnStatement)return!0}return!1}function v(e){const n=D(e.value),o=e.info,s=e.param;if(o.isEnum){if(c(n))return;if(n.kind===a.CallExpression){const e=t.pxtInfo(n).callInfo,r=i.attrs(e);if(e&&"TD_ID"===r.shim&&e.args&&1===e.args.length){if(c(D(e.args[0])))return}}else if(n.kind===a.Identifier){const e=t.pxtInfo(n).commentAttrs;if(e&&e.enumIdentity)return}return t.Util.lf("Enum arguments may only be literal property access expressions")}if(I(n)&&(s.fieldEditor||s.shadowBlockId)){let e=!(!s.fieldOptions||!s.fieldOptions[r.DecompileLiterals]);if(!e&&s.shadowBlockId){const t=i.blocks.blocksById[s.shadowBlockId];if(t&&t.parameters&&t.parameters.length){const n=t.parameters[0].name;e=!t.attributes.paramFieldEditorOptions||!t.attributes.paramFieldEditorOptions[n]||!!t.attributes.paramFieldEditorOptions[n][r.DecompileLiterals]}else e=!0}if(!e)return t.Util.lf("Field editor does not support literal arguments")}else if(n.kind===a.TaggedTemplateExpression&&s.fieldEditor){let e=s.fieldOptions&&s.fieldOptions[r.TaggedTemplate];if(!e)return t.Util.lf("Tagged templates only supported in custom fields with param.fieldOptions.taggedTemplate set");const i=D(n.tag);if(i.kind!==a.Identifier)return t.Util.lf("Tagged template literals must use an identifier as the tag");if(i.getText().trim()!=e.trim())return t.Util.lf("Function only supports template literals with tag '{0}'",e);if(n.template.kind!==a.NoSubstitutionTemplateLiteral)return t.Util.lf("Tagged template literals cannot have substitutions")}else if(n.kind===a.ArrowFunction){const e=n;if(e.parameters.length)if("objectdestructuring"===l.mutate){const n=D(e.parameters[0]);if(n.kind===a.Parameter&&n.name.kind!==a.ObjectBindingPattern)return t.Util.lf("Object destructuring mutation callbacks can only have destructuring patters as arguments")}else for(const n of e.parameters)if(n.name.kind!==a.Identifier)return t.Util.lf("Only identifiers allowed as function arguments")}else if(i.blocks.apis.byQName[o.type]){if(i.blocks.apis.byQName[o.type].attributes.fixedInstances){if(L(s))return;if(s.shadowBlockId){const e=i.blocks.blocksById[s.shadowBlockId];if(e){const t=pxt.blocks.compileInfo(e);if(t.parameters&&L(t.parameters[0]))return}}const e=t.pxtInfo(n).callInfo;if(e&&i.attrs(e).fixedInstance)return;return t.Util.lf("Arguments of a fixed instance type must be a reference to a fixed instance declaration")}}return;function c(e){const t=o.type.split("."),n=[];for(;e.kind===a.PropertyAccessExpression;)n.unshift(e.name.text),e=e.expression;if(e.kind!==a.Identifier)return!1;n.unshift(e.text);for(let e=0;e<t.length;e++)if(t[e]!==n[e])return!1;return!0}}}(n,i,o,s);case a.VariableDeclaration:return c(n,i);case a.PostfixUnaryExpression:case a.PrefixUnaryExpression:return function(e){if(e.operand.kind!=a.Identifier)return t.Util.lf("-- and ++ may only be used on an identifier");if(e.operator!==a.PlusPlusToken&&e.operator!==a.MinusMinusToken)return t.Util.lf("Only ++ and -- supported as prefix or postfix unary operators in a statement");return}(n);case a.FunctionExpression:case a.ArrowFunction:return function(e,n){let r=!1;if(e.parameters.length){let i=E(e)[0];if(i&&t.pxtInfo(i).callInfo){let o=t.pxtInfo(i).callInfo;r="objectdestructuring"===n.attrs(o).mutate?e.parameters[0].name.kind!==a.ObjectBindingPattern:e.parameters.some((e=>e.name.kind!==a.Identifier))}}if(r)return t.Util.lf("Unsupported parameters in error function");return}(n,i);case a.BinaryExpression:return function(e,n){if(e.left.kind===a.ElementAccessExpression){if(e.operatorToken.kind!==a.EqualsToken)return t.Util.lf("Element access expressions may only be assigned to using the equals operator")}else{if(e.left.kind===a.PropertyAccessExpression)return e.operatorToken.kind!==a.EqualsToken&&e.operatorToken.kind!==a.PlusEqualsToken?t.Util.lf("Property access expressions may only be assigned to using the = and += operators"):C(e.left,n);if(e.left.kind!==a.Identifier)return t.Util.lf("This expression cannot be assigned to");switch(e.operatorToken.kind){case a.EqualsToken:return C(e.right,n);case a.PlusEqualsToken:case a.MinusEqualsToken:return;default:return t.Util.lf("Unsupported operator token in statement {0}",a[e.operatorToken.kind])}}return}(n,i);case a.ForStatement:return function(e){if(!e.initializer||!e.incrementor||!e.condition)return t.Util.lf("for loops must have an initializer, incrementor, and condition");if(e.initializer.kind!==a.VariableDeclarationList)return t.Util.lf("only variable declarations are permitted in for loop initializers");const n=e.initializer;if(!n.declarations)return t.Util.lf("for loop with out-of-scope variables not supported");if(1!=n.declarations.length)return t.Util.lf("for loop with multiple variables not supported");const r=n.declarations[0];if(r.initializer.kind!==a.NumericLiteral||"0"!==r.initializer.text)return t.Util.lf("for loop initializers must be initialized to 0");const i=r.name.text;if(!s(i))return t.Util.lf("for loop incrementors may only increment the variable declared in the initializer");if(e.condition.kind!==a.BinaryExpression)return t.Util.lf("for loop conditionals must be binary comparison operations");const o=e.condition;if(o.left.kind!==a.Identifier||o.left.text!==i)return t.Util.lf("left side of for loop conditional must be the variable declared in the initializer");if(o.operatorToken.kind!==a.LessThanToken&&o.operatorToken.kind!==a.LessThanEqualsToken)return t.Util.lf("for loop conditional operator must be either < or <=");return;function s(t){if(e.incrementor.kind===a.PostfixUnaryExpression||e.incrementor.kind===a.PrefixUnaryExpression){const n=e.incrementor;if(n.operator===a.PlusPlusToken&&n.operand.kind===a.Identifier)return n.operand.text===t}return!1}}(n);case a.ForOfStatement:return function(e){if(e.initializer.kind!==a.VariableDeclarationList)return t.Util.lf("only variable declarations are permitted in for of loop initializers");return}(n);case a.FunctionDeclaration:return function(e,n){if(!n)return t.Util.lf("Function declarations must be top level");if(e.parameters.length>0&&i.opts.allowedArgumentTypes)for(const n of e.parameters){if(n.initializer||n.questionToken)return t.Util.lf("Function parameters cannot be optional");const e=n.type?n.type.getText():void 0;if(!e)return t.Util.lf("Function parameters must declare a type");if(-1===i.opts.allowedArgumentTypes.indexOf($(e)))return t.Util.lf("Only types that can be added in blocks can be used for function arguments")}return}(n,s);case a.EnumDeclaration:return function(e,n){if(!n)return t.Util.lf("Enum declarations must be top level");const r=e.name.text;if(!i.blocks.enumsByName[r])return t.Util.lf("Enum declarations in user code must have a block");let o=!1;if(e.members.forEach((e=>{if(e.name.kind!==a.Identifier&&(o=!0),!o&&e.initializer){if(e.initializer.kind===a.NumericLiteral)return;if(e.initializer.kind===a.BinaryExpression){const t=e.initializer;if(t.operatorToken.kind===a.LessThanLessThanToken&&t.left.kind===a.NumericLiteral&&t.right.kind===a.NumericLiteral&&"1"==t.left.text)return}o=!0}})),o)return t.Util.lf("Invalid initializer for enum member");return}(n,s);case a.ModuleDeclaration:return function(e){const t=x(e,i);if(!t)return;return k(e)?t:void 0}(n);case a.ReturnStatement:return function(n){if(r(n))return;return t.Util.lf("Return statements can only be used within top-level function declarations");function r(t){const n=e.getEnclosingBlockScopeContainer(t);if(n)switch(n.kind){case a.SourceFile:case a.ArrowFunction:case a.FunctionExpression:return!1;case a.FunctionDeclaration:return n.parent&&n.parent.kind===a.SourceFile&&!b(n,i,!1,!0);default:return r(n)}return!1}}(n);case a.BreakStatement:case a.ContinueStatement:case a.DebuggerStatement:case a.EmptyStatement:return}return t.Util.lf("Unsupported statement in block: {0}",a[n.kind]);function c(e,n){let r;return e.name.kind!==a.Identifier?r=t.Util.lf("Variable declarations may not use binding patterns"):e.initializer?S(e)||(r=C(e.initializer,n)):r=t.Util.lf("Variable declarations must have an initializer"),r}}function x(n,r){if(!e.isModuleBlock(n.body))return t.Util.lf("Namespaces cannot be nested.");const i=r.blocks.kindsByName[n.name.text];if(!i)return t.Util.lf("Only namespaces with 'kind' blocks can be decompiled");const o=t.Util.lf("Namespaces may only contain valid 'kind' exports");for(const t of n.body.statements){if(j(t))return o;if(!e.isVariableStatement(t)||!t.declarationList.declarations)return o;{const n=1===t.declarationList.declarations.length,r=t.modifiers&&1===t.modifiers.length&&t.modifiers[0].kind===a.ExportKeyword,s=t.declarationList.flags&e.NodeFlags.Const;if(!(n&&r&&s))return o;{const n=t.declarationList.declarations[0];if(!n.initializer||!e.isCallExpression(n.initializer)||!e.isIdentifier(n.name))return o;const r=n.initializer;if(r.arguments.length)return o;if(e.isPropertyAccessExpression(r.expression)&&e.isIdentifier(r.expression.expression)){if(r.expression.expression.text!==i.name||r.expression.name.text!==i.createFunctionName)return o}else{if(!e.isIdentifier(r.expression))return o;if(r.expression.text!==i.createFunctionName)return o}}}}}function k(n){if(!e.isModuleBlock(n.body))return t.Util.lf("Namespaces cannot be nested.");if(n.name.text!==pxt.sprite.TILE_NAMESPACE)return t.Util.lf("Tileset namespace must be named myTiles");const r=t.Util.lf("The myTiles namespace can only export tile variables with image literal initializers and no duplicate ids"),i=t.Util.lf("Tileset members must have a blockIdentity comment and no other annotations"),o=new RegExp(`${pxt.sprite.TILE_PREFIX}(\\d+)`),s=[],c=/^\s*\/\/%\s*blockIdentity=[^\s]+\s*$/;for(const t of n.body.statements){const n=e.getLeadingCommentRangesOfNode(t,t.getSourceFile());if(!n||!n.length)return i;{const e=n.map((e=>t.getSourceFile().text.substr(e.pos,e.end-e.pos))).filter((e=>!!e));if(1!==e.length||!c.test(e[0]))return i}if(!e.isVariableStatement(t)||!t.declarationList.declarations)return r;{const n=1===t.declarationList.declarations.length,i=t.modifiers&&1===t.modifiers.length&&t.modifiers[0].kind===a.ExportKeyword,c=t.declarationList.flags&e.NodeFlags.Const;if(!(n&&i&&c))return r;{const n=t.declarationList.declarations[0];if(!n.initializer||!e.isTaggedTemplateExpression(n.initializer)||!e.isIdentifier(n.name))return r;const i=n.initializer;if(!e.isIdentifier(i.tag)||"img"!==i.tag.text)return r;const a=o.exec(n.name.text);if(!a||-1!==s.indexOf(a[1]))return r;s.push(a[1])}}}}function S(n){if(n.initializer){if(n.initializer.kind===e.SyntaxKind.NullKeyword||n.initializer.kind===e.SyntaxKind.FalseKeyword||function(e){return e.kind===a.ArrayLiteralExpression&&0===e.elements.length}(n.initializer))return!0;if(e.isStringOrNumericLiteral(n.initializer)){const e=n.initializer.getText();return"0"===e||A(e)}{const e=t.pxtInfo(n.initializer).callInfo;if(e&&e.isAutoCreate)return!0}}return!1}function T(e){if(1===e.parameters.length&&e.parameters[0].name.kind===a.ObjectBindingPattern){const n=e.parameters[0].name.elements,r={};return[n.map((e=>{if(t(e.propertyName)&&t(e.name)){const t=e.name.text;if(e.propertyName){const n=e.propertyName.text;return r[n]=t,n}return t}return""})),r]}return;function t(e){return!e||e.kind===a.Identifier}}function C(n,r){switch(n.kind){case a.NumericLiteral:case a.TrueKeyword:case a.FalseKeyword:case a.ExpressionStatement:case a.ArrayLiteralExpression:case a.ElementAccessExpression:return;case a.ParenthesizedExpression:return C(n.expression,r);case a.StringLiteral:case a.FirstTemplateToken:case a.NoSubstitutionTemplateLiteral:return function(e){const n=e.text;return o.test(n)?void 0:t.Util.lf("Only whitespace character allowed in string literals is space")}(n);case a.Identifier:const s=t.pxtInfo(n);return(i=n)&&i.kind===a.Identifier&&"undefined"===i.text?t.Util.lf("Undefined is not supported in blocks"):!N(n)||s.commentAttrs&&s.commentAttrs.blockIdentity&&s.commentAttrs.enumIdentity?void 0:t.Util.lf("Variable is declared in another file");case a.BinaryExpression:const c=n.operatorToken.getText();return _[c]?void 0:t.Util.lf("Could not find operator {0}",c);case a.PrefixUnaryExpression:const l=n.operator;return l===a.MinusToken||l===a.PlusToken||l===a.ExclamationToken?void 0:t.Util.lf("Unsupported prefix unary operator{0}",l);case a.PropertyAccessExpression:return function(n,r){const i=t.pxtInfo(n).callInfo;if(i){const o=r.attrs(i),s=r.compInfo(i);if(o.blockIdentity||"lists_length"===o.blockId||"text_length"===o.blockId)return;if(i.decl.kind===a.EnumMember){if(n.expression.kind===a.Identifier){const e=n.expression.text;if(r.declaredEnums[e])return}const[e,i]=E(n);let o=!0;if(e){const n=t.pxtInfo(e).callInfo;if(n&&n.args){const e=r.blocks.apis.byQName[n.qName],t=1==e.kind||2==e.kind;e&&n.args.forEach(((n,r)=>{if(n===i){e.parameters[t?r-1:r].isEnum&&(o=!1)}}))}}return o?t.Util.lf("Enum value without a corresponding block"):void 0}if(o.fixedInstance&&n.parent){if(n.parent.parent&&n.parent.kind===a.PropertyAccessExpression&&n.parent.parent.kind===a.CallExpression){if(n.parent.parent.expression===n.parent)return}else if(n.parent.kind===a.CallExpression&&n.parent.expression!==n)return}else{if(o.blockCombine||o.blockId&&s&&s.thisParameter)return C(n.expression,r);if(e.isIdentifier(n.expression)&&r.declaredKinds[n.expression.text]){const e=n.name.text,t=r.declaredKinds[n.expression.text];if(t&&(-1!==t.kindInfo.initialMembers.indexOf(e)||-1!==t.declaredNames.indexOf(e)))return}}}return t.Util.lf("No call info found")}(n,r);case a.CallExpression:return b(n,r,!0,void 0);case a.TaggedTemplateExpression:return function(e,n){const r=t.pxtInfo(e).callInfo;if(!r)return t.Util.lf("Invalid tagged template");const i=n.attrs(r);if(!i.blockIdentity)return t.Util.lf("Tagged template does not have blockIdentity set");const a=n.blocks.apis.byQName[i.blockIdentity];if(!a)return t.Util.lf("Could not find blockIdentity for tagged template");if(1!==pxt.blocks.compileInfo(a).parameters.length)return t.Util.lf("Tagged template functions must have 1 argument");return}(n,r)}var i;return t.Util.lf("Unsupported syntax kind for output expression block: {0}",a[n.kind])}function E(e){return e.parent?e.parent.kind===a.ParenthesizedExpression?E(e.parent):[e.parent,e]:[void 0,e]}function D(e){for(;e.kind===a.ParenthesizedExpression;)e=e.expression;return e}function A(e){return'""'===e||"''"===e||"``"===e}function N(e){return!!(4&t.pxtInfo(e).flags)}function w(e,n){if(n.blockId===t.PAUSE_UNTIL_TYPE)return!1;e.decl.parameters;return e.args.some(((e,t)=>e&&P(e)))}function I(e){if(!e)return!1;switch(e.kind){case a.ParenthesizedExpression:return I(e.expression);case a.ArrayLiteralExpression:const t=e;for(const e of t.elements)if(!I(e)&&e.kind!==a.TaggedTemplateExpression)return!1;return!0;case a.NumericLiteral:case a.StringLiteral:case a.NoSubstitutionTemplateLiteral:case a.TrueKeyword:case a.FalseKeyword:return!0;case a.PrefixUnaryExpression:const n=e;return(n.operator===a.PlusToken||n.operator===a.MinusToken)&&I(n.operand);default:return!1}}function P(e){return e.kind===a.ArrowFunction||e.kind===a.FunctionExpression}function O(e,t){const n=[],r=t.apis.byQName[e.qName];if(r){const i=t.apis.byQName[e.qName].attributes,a=pxt.blocks.compileInfo(r);pxt.blocks.builtinFunctionInfo[e.qName];let o=i.imageLiteral?1:0;a.thisParameter?n.push({value:D(e.args[0]),info:null,param:a.thisParameter}):i.defaultInstance&&n.push({value:D(e.args[0]),info:r.parameters[0],param:{definitionName:"__instance__",actualName:"this"}});const s=!(!a.thisParameter&&!i.defaultInstance);s&&o++;for(let t=o;t<e.args.length;t++)n.push({value:D(e.args[t]),info:r.parameters[s?t-1:t],param:a.parameters[t-o]})}return n}function F(e){return e.body.statements.map((e=>{const t=e.declarationList.declarations[0];return{name:t.name.text,initializer:t.initializer.getText()}}))}function L(e){return e&&e.fieldOptions&&e.fieldOptions[r.DecompileIndirectFixedInstances]}function R(e){return M(e)||U(e)||B(e)||-1!==pxt.blocks.MATH_FUNCTIONS.binary.indexOf(e)}function M(e){return-1!==pxt.blocks.MATH_FUNCTIONS.unary.indexOf(e)}function U(e){return-1!==pxt.blocks.MATH_FUNCTIONS.infix.indexOf(e)}function B(e){return-1!==pxt.blocks.ROUNDING_FUNCTIONS.indexOf(e)}function $(e){const t=s.exec(e);return t?`${t[1]||t[2]}[]`:e}function j(t){const n=e.getLeadingCommentRangesOfNode(t,t.getSourceFile());return!(!n||!n.length)}function K(t,n,r=!1){const a=[],o=t.getFullText();if(n&&n.length)for(const s of n){const n=e.getLineOfLocalPosition(t,s.end),c=e.getStartPositionOfLine(n+1,t)||o.length,l=e.getStartPositionOfLine(n+2,t)||o.length,u=!r&&!o.substr(c,l-c).trim();let d=o.substr(s.pos,s.end-s.pos);if(d&&(d=d.replace(/\r\n/g,"\n")),s.kind===e.SyntaxKind.SingleLineCommentTrivia){const e=m.exec(d);e?a.push({kind:i.SingleLine,text:e[1],start:s.pos,end:s.end,hasTrailingNewline:!!s.hasTrailingNewLine,followedByEmptyLine:u,isTrailingComment:r}):a.push({kind:i.SingleLine,text:"",start:s.pos,end:s.end,hasTrailingNewline:!!s.hasTrailingNewLine,followedByEmptyLine:u,isTrailingComment:r})}else{const e=d.split("\n").map((e=>{const t=g.exec(e);return t?t[1]:""}));a.push({kind:i.MultiLine,lines:e,start:s.pos,end:s.end,hasTrailingNewline:!!s.hasTrailingNewLine,followedByEmptyLine:u,isTrailingComment:r})}}return a}function z(e){let n="";for(const r of e)if(r.kind===i.SingleLine){if(r.text===t.ON_START_COMMENT||r.text===t.HANDLER_COMMENT)continue;n+=r.text.trim()+"\n"}else for(const e of r.lines)n+=e.trim()+"\n";return n.trim()}function J(e){const[t]=E(e);return!t||t.kind==a.SourceFile||(t.kind==a.ExpressionStatement?J(t):t.kind==a.VariableDeclarationList&&J(t.parent))}function q(t){const n=t.getFullText(),r=e.createScanner(t.languageVersion,!1,t.languageVariant,n,void 0,t.getFullStart());let i,o,s=[];for(;r.getTextPos()<t.end;){const c=r.scan();if(c===a.SingleLineCommentTrivia||c===a.MultiLineCommentTrivia){i=e.getLeadingCommentRanges(n,r.getTokenPos())||[],o=e.getTrailingCommentRanges(n,r.getTokenPos())||[],o=o.filter((e=>!i.some((t=>t.pos===e.pos)))),s.push(...K(t,i,!1)),s.push(...K(t,o,!0));for(const e of s)e.end>r.getTextPos()&&r.setTextPos(e.end)}}return s.sort(((e,t)=>e.start-t.start)),s}function V(e,t){let n;for(let r=0;r<t.length;r++)n=t[r],!n.owner&&n.start>=e.pos&&n.end<=e.end&&(n.owner=e)}n.RenameMap=h,n.buildRenameMap=function(n,r,{declarations:i,takenNames:a}={declarations:"variables",takenNames:{}}){let o=e.createLanguageService(new t.LSHost(n));const s=[];let c=(function t(n){e.forEachChild(n,(n=>{if(e.isDeclarationName(n)&&("all"===i||e.isVariableDeclaration(n.parent))){const e=n.getText();if(a[e]){const t=y(e,a),i=o.findRenameLocations(r.fileName,n.pos+1,!1,!1);i&&i.forEach((n=>{s.push({name:t,diff:t.length-e.length,span:n.textSpan})}))}else a[e]=!0}t(n)}))}(r),a);return[new h(s),c]},n.getNewName=y,function(e){e[e.None=0]="None",e[e.InBlocksOnly=1]="InBlocksOnly",e[e.InTextBlocks=2]="InTextBlocks"}(v||(v={})),n.decompileToBlocks=function(o,s,m,g){let h=0,y=s.statements;const P={blocksInfo:o,outfiles:{},diagnostics:[],success:!0,times:{}};m.generateSourceMap&&(P.blockSourceMap=[]);const L={blocks:o,declaredFunctions:{},declaredEnums:{},declaredKinds:{},functionParamIds:{},attrs:re,compInfo:function(e){const t=o.apis.byQName[e.qName];if(t)return pxt.blocks.compileInfo(t);return},localReporters:[],tileset:[],opts:m||{},aliasBlocks:{}};s.getFullText();let $="";const j=[],K={},H=[],G=[],W=(()=>{let e=0;return()=>""+e++})(),Q=o.apis.byQName;Object.keys(Q).forEach((e=>{const t=Q[e];t.attributes.blockAliasFor&&Q[t.attributes.blockAliasFor]&&(L.aliasBlocks[t.attributes.blockAliasFor]=t.qName)}));const Y=q(s),X=n=>{if(n.kind!==a.FunctionDeclaration||b(n,L,!1,!0))if(n.kind!==a.EnumDeclaration||b(n,L,!1,!0))if(e.isModuleDeclaration(n))if(x(n,L))k(n)||(L.tileset=F(n).map((({name:e,initializer:t})=>({projectId:parseInt(e.substr(pxt.sprite.TILE_PREFIX.length)),data:pxt.sprite.imageLiteralToBitmap(t).data()}))));else{const e=n.name.text,t=F(n);L.declaredKinds[e]&&L.declaredKinds[e].declaredNames.push(...t.map((({name:e})=>e)))}else n.kind===a.Block&&e.forEachChild(n,X);else{const e=n.name.text;L.declaredEnums[e]=!0,function(e){const n=[];return e.members.forEach((e=>{t.U.assert(e.name.kind===a.Identifier);const r=e.name.text;let i;if(e.initializer)if(e.initializer.kind===a.NumericLiteral)i=parseInt(e.initializer.text);else{const n=e.initializer;t.U.assert(n.left.kind===a.NumericLiteral),t.U.assert("1"===n.left.text),t.U.assert(n.operatorToken.kind===a.LessThanLessThanToken),t.U.assert(n.right.kind===a.NumericLiteral);i=1<<parseInt(n.right.text)}else i=0===n.length?0:n[n.length-1][1]+1;n.push([r,i])})),n}(n).forEach((([t,n])=>{j.push({name:n+t,type:e})}))}else L.declaredFunctions[Ge(n.name)]=n};Object.keys(o.kindsByName).forEach((e=>{const t=o.kindsByName[e];L.declaredKinds[e]={kindInfo:t,declaredNames:[]}})),e.forEachChild(s,X);const Z=()=>(Math.PI*Math.random()).toString(36).slice(2);let ee;Object.keys(L.declaredFunctions).forEach((e=>{L.functionParamIds[e]={},L.declaredFunctions[e].parameters.forEach((t=>{L.functionParamIds[e][t.name.getText()]=Z()+Z()}))})),Object.keys(L.declaredKinds).forEach((e=>{const t="KIND_"+e;L.declaredKinds[e].declaredNames.forEach((e=>j.push({name:e,type:t})))})),(j.length||L.tileset.length)&&(te("<variables>"),j.forEach((e=>{te(`<variable type="${t.U.htmlEscape(e.type)}">${t.U.htmlEscape(e.name)}</variable>`)})),L.tileset.forEach((e=>{te(`<variable type="${pxt.sprite.BLOCKLY_TILESET_TYPE}">${pxt.sprite.legacy.tileToBlocklyVariable(e)}</variable>`)})),te("</variables>"));try{ee=Je(y,void 0,!0,void 0,!m.snippetMode);for(const e of Y)e.owner||H.push({refId:W(),comment:[e]})}catch(r){if(!r.programTooLarge)return pxt.reportException(r),P.success=!1,P.diagnostics=t.patchUpDiagnostics([{file:s,start:s.getFullStart(),length:s.getFullWidth(),messageText:r.message,category:e.DiagnosticCategory.Error,code:n.DECOMPILER_ERROR}]),P;P.success=!1,P.diagnostics=t.patchUpDiagnostics([{file:s,start:s.getFullStart(),length:s.getFullWidth(),messageText:r.message,category:e.DiagnosticCategory.Error,code:n.FILE_TOO_LARGE_CODE}])}return ee?ue(ee):m.snippetMode||y.length||(he(e.pxtc.ON_START_TYPE,oe(e.pxtc.ON_START_TYPE,y[0])),ye()),H.forEach((e=>{!function(e){let n=0;const r=z(e.comment);if(r.trim()){const i=r.split("\n");i.forEach((e=>n=Math.max(n,e.length)));const a=Math.max(Math.min(10*n,480),160);te(`<comment h="${Math.max(Math.min(40*i.length,360),120)}" w="${a}" data="${t.U.htmlEscape(e.refId)}">`),te(t.U.htmlEscape(r)),te("</comment>")}}(e)})),P.outfiles[s.fileName.replace(/(\.blocks)?\.\w*$/i,"")+".blocks"]=`<xml xmlns="http://www.w3.org/1999/xhtml">\n${$}</xml>`,P;function te(e,t="\n"){$+=e+t}function ne(n,r){const i=r||`Language feature "${n.getFullText().trim()}"" not supported in blocks`,a=t.patchUpDiagnostics([{file:s,start:n.getFullStart(),length:n.getFullWidth(),messageText:i,category:e.DiagnosticCategory.Error,code:1001}]);pxt.debug(`decompilation error: ${i}`),t.U.pushRange(P.diagnostics,a),P.success=!1}function re(e){const n=o.apis.byQName[e.decompilerBlockAlias||e.qName];if(n){const e=n.attributes;if(!e.blockId||o.blocksById[e.blockId]||e.blockId===t.PAUSE_UNTIL_TYPE)return n.attributes}else if(e.decl){const n=t.parseComments(e.decl);if(n)return n}return{paramDefl:{},callingConvention:0}}function ie(){if(h++,h>1500){let e=new Error(t.Util.lf("Could not decompile because the script is too large"));throw e.programTooLarge=!0,e}}function ae(t,n){if(t==e.pxtc.ON_START_TYPE)return"xRRgvHNlG#rZ^u`HECiY";const r=function(){const e="!#$%()*+,-./:;=?@[]^_`{|}~ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=e.length,n=[];for(let r=0;r<20;r++)n[r]=e.charAt(Math.random()*t);return n.join("")}();if(n){const e=n.getFullStart();P.blockSourceMap.push({id:r,startPos:e,endPos:e+n.getFullWidth()})}return r}function oe(e,t){const n={kind:"statement",type:e};return P.blockSourceMap&&(n.id=ae(e,t)),n}function se(e,t){return{kind:"expr",type:e}}function ce(e,t,n,r){return(!n||n===c)&&r&&r.min&&r.max&&(n=l),{kind:"value",name:e,value:t,shadowType:n,shadowMutation:r}}function le(e){if(e.expression.kind==a.CallExpression){const n=e.expression,r=t.pxtInfo(n).callInfo;if(!r)return ne(e),!1;const i=re(r);return i.blockId&&!i.handlerStatement&&!r.isExpression&&w(r,i)}return!1}function ue(e){e&&(he(e.type,e),pe(e),void 0!==e.data&&te(`<data>${t.U.htmlEscape(e.data)}</data>`),e.handlers&&e.handlers.forEach(me),e.next&&(te("<next>"),ue(e.next),te("</next>")),void 0!==e.comment&&te(`<comment pinned="false">${t.U.htmlEscape(z(e.comment))}</comment>`),ye())}function de(e,t){te("<mutation ",""),Object.keys(e).forEach((t=>{void 0!==e[t]&&te(`${t}="${e[t]}" `,"")})),t?(te(">"),t.forEach((e=>{te(`<${e.nodeName} `,""),Object.keys(e.attributes).forEach((t=>{te(`${t}="${e.attributes[t]}" `,"")})),te("/>")})),te("</mutation>")):te("/>")}function pe(e){e.mutation&&de(e.mutation,e.mutationChildren),e.fields&&e.fields.forEach(_e),e.inputs&&e.inputs.forEach(fe)}function fe(e){te(`<value name="${e.name}">`);let t=!1;if("expr"===e.value.kind){const n=e.value;if(n.type===c&&e.shadowType===l&&(n.type=l,n.fields[0].name="SLIDER",n.mutation=e.shadowMutation),t=n.type===e.shadowType,!t)switch(n.type){case"math_number":case"math_number_minmax":case"math_integer":case"math_whole_number":case"logic_boolean":case"text":t=!e.shadowType}}if(t)ge(e.value,!0);else{if(void 0!==e.shadowType)switch(e.shadowType){case c:case u:case d:te(`<shadow type="${e.shadowType}"><field name="NUM">0</field></shadow>`);break;case l:te('<shadow type="math_number_minmax">'),e.shadowMutation&&de(e.shadowMutation),te('<field name="SLIDER">0</field></shadow>');break;case f:te('<shadow type="logic_boolean"><field name="BOOL">TRUE</field></shadow>');break;case p:te('<shadow type="text"><field name="TEXT"></field></shadow>');break;default:te(`<shadow type="${e.shadowType}"/>`)}ge(e.value)}te("</value>")}function _e(e){te(`<field name="${t.U.htmlEscape(e.name)}">${t.U.htmlEscape(e.value.toString())}</field>`)}function me(e){te(`<statement name="${t.U.htmlEscape(e.name)}">`),ue(e.statement),te("</statement>")}function ge(e,n=!1){if("text"===e.kind){te(e.value)}else{const r=e,i=n||r.isShadow,a=i?"shadow":"block";i||ie(),te(`<${a} ${r.id?`id="${r.id}" `:""}type="${t.U.htmlEscape(r.type)}">`),pe(r),te(`</${a}>`)}}function he(e,n){ie();te(`<block ${n&&n.id?`id="${n.id}" `:""}type="${t.U.htmlEscape(e)}">`)}function ye(){te("</block>")}function ve(e){if(C(e,L))return xe(e);switch(e.kind){case a.ExpressionStatement:case a.ParenthesizedExpression:return ve(e.expression);case a.Identifier:return function(e){if(N(e)){const n=t.pxtInfo(e);return Le(o.apis.byQName[n.commentAttrs.blockIdentity],n.commentAttrs.enumIdentity)}const n=Ge(e),r=e.text;let i=null;return L.localReporters.some((e=>{for(let t=0;t<e.length;++t)if(e[t].name===r)return i=e[t],!0;return!1})),i?Ie(n,i.type,!1):(Ve(n,v.InBlocksOnly),Ne("variables_get","VAR",n))}(e);case a.StringLiteral:case a.FirstTemplateToken:case a.NoSubstitutionTemplateLiteral:return De(e.text);case a.NumericLiteral:return Ee(e.text);case a.TrueKeyword:return Ae(!0);case a.FalseKeyword:return Ae(!1);case a.BinaryExpression:return function(e){const t=e.operatorToken.getText(),n=_[t];if(ke(e))return Te(e);const r=n.leftName||"A",i=n.rightName||"B";let a,o;"&&"===t||"||"===t?(a=Ue(r,e.left),o=Ue(i,e.right)):(a=Ce(r,e.left,c),o=Ce(i,e.right,c));const s=se(n.type);s.fields=[],n.op&&s.fields.push(Pe("OP",n.op));return s.inputs=[a,o],s}(e);case a.PrefixUnaryExpression:return function(e){switch(e.operator){case a.ExclamationToken:const t=se("logic_negate");return t.inputs=[Ue("BOOL",e.operand)],t;case a.PlusToken:return ve(e.operand);case a.MinusToken:return e.operand.kind==a.NumericLiteral?Ee("-"+e.operand.text):Oe(e.operand);default:ne(e)}return}(e);case a.PropertyAccessExpression:return Fe(e);case a.ArrayLiteralExpression:return function(e){const t=se("lists_create_with");return t.inputs=e.elements.map(((e,t)=>Ce("ADD"+t,e))),t.mutation={items:e.elements.length.toString()},t}(e);case a.ElementAccessExpression:return function(e){const t=se("lists_index_get");return t.inputs=[Ce("LIST",e.expression),Ce("INDEX",e.argumentExpression,c)],t}(e);case a.TaggedTemplateExpression:return function(e){const n=t.pxtInfo(e).callInfo;let i;const s=function(e){if(e.parent&&e.parent.kind===a.CallExpression){const n=e.parent,r=t.pxtInfo(n).callInfo,i=n.arguments.indexOf(e);if(r&&-1!==i){const e=o.apis.byQName[r.qName];if(e){const t=pxt.blocks.compileInfo(e);return t&&t.parameters[i]}}}return}(e);if(s&&s.shadowBlockId){const e=L.blocks.blocksById[s.shadowBlockId];e&&"TD_ID"===e.attributes.shim&&(i=e)}i||(i=L.blocks.apis.byQName[re(n).blockIdentity]);const c=pxt.blocks.compileInfo(i),l=se(i.attributes.blockId);let u;const d=c.parameters[0];u=d.fieldOptions&&d.fieldOptions[r.DecompileArgumentAsString]?e.getText():e.template.text;return l.fields=[Pe(d.actualName,u)],l}(e);case a.CallExpression:return Re(e,void 0,void 0,!0);default:ne(e,t.Util.lf("Unsupported syntax kind for output expression block: {0}",a[e.kind]))}}function be(e,t,n){if(g){const r=g.getRenamesInSpan(t,n);if(r.length){let n=0;r.forEach((r=>{const i=r.span.start+n-t,a=i+r.span.length;n+=r.diff,e=e.slice(0,i)+r.name+e.slice(a)}))}}return e}function xe(e){const n=be(e.getFullText(),e.getFullStart(),e.getEnd()).trim();return He(e),V(e,Y),Ne(t.TS_OUTPUT_TYPE,"EXPRESSION",n)}function ke(e){if(e.kind===a.BinaryExpression){const n=e;if("+"===n.operatorToken.getText()||n.operatorToken.kind==a.PlusEqualsToken){return!!t.pxtInfo(e).exprInfo}}return!1}function Se(e,t){ke(e)?(Se(e.left,t),Se(e.right,t)):t.push(e)}function Te(e){const t=[];Se(e,t);const n=[];for(let e=0;e<t.length;e++)(e>0||!A(t[e].getText()))&&n.push(Ce("ADD"+n.length,t[e],p));const r=se("text_join");return r.inputs=n,r.mutation={items:n.length.toString()},r}function Ce(e,t,n,r){let i;if(i="number"==typeof t?Ee(t.toString()):"boolean"==typeof t?Ae(t):"string"==typeof t?De(t):ve(t),"expr"==i.kind&&"math_number"==i.type){const e=i.fields[0].value;"math_integer"==n&&e%1==0&&(i.type="math_integer"),"math_whole_number"==n&&e%1==0&&e>0&&(i.type="math_whole_number")}return ce(e,i,n,r)}function Ee(e){return Ne("math_number","NUM",e)}function De(e){return Ne("text","TEXT",e)}function Ae(e){return Ne("logic_boolean","BOOL",e?"TRUE":"FALSE")}function Ne(e,t,n,r){const i=se(e);return i.fields=[Pe(t,n)],i.isShadow=r,i}function we(e,t){return ce(e,Ne("variables_get_reporter","VAR",t,!0),"variables_get_reporter")}function Ie(e,t,n){const r=pxt.blocks.reporterTypeForArgType(t),i=Ne(r,"VALUE",e,n);return"argument_reporter_custom"===r&&(i.mutation={typename:t}),i}function Pe(e,t){return{kind:"field",name:e,value:t}}function Oe(e){const t=se("math_arithmetic");return t.inputs=[Ce("A",0,c),Ce("B",e,c)],t.fields=[Pe("OP","MINUS")],t}function Fe(e,n=!1,r){let i=t.pxtInfo(e).callInfo;if(!i)return void ne(e);if(e.expression.kind===a.Identifier){const t=e.expression.text;if(L.declaredEnums[t]){const n=o.enumsByName[t];if(n&&n.blockId)return Ne(n.blockId,"MEMBER",e.name.text)}else if(L.declaredKinds[t]){return Ne(L.declaredKinds[t].kindInfo.blockId,"MEMBER",e.name.text)}}const s=re(i);if(r=s.blockId||r,s.blockCombine)return function(e,t){return je(e,t,null,"@get@")}(e,e);if("lists_length"===s.blockId||"text_length"===s.blockId){const n=se(t.U.htmlEscape(s.blockId));return n.inputs=[Ce("VALUE",e.expression)],n}let c=t.U.htmlEscape(s.blockId||i.qName);const[l]=E(e),u=l&&t.pxtInfo(l).callInfo;if(n||!r&&!s.blockIdentity||u&&u.qName===s.blockIdentity)return{kind:"text",value:c};s.enumval&&u&&s.useEnumVal&&(c=s.enumval);const d=L.compInfo(i);if(r&&d&&d.thisParameter){const n=se(r);return n.inputs=[Ce(t.U.htmlEscape(d.thisParameter.definitionName),e.expression,d.thisParameter.shadowBlockId)],n}return Le(s.blockIdentity?o.apis.byQName[s.blockIdentity]:o.blocksById[r],c)}function Le(e,n){let r=/(?:%|\$)([a-zA-Z0-9_]+)/.exec(e.attributes.block);const i=se(t.U.htmlEscape(e.attributes.blockId));return i.fields=[{kind:"field",name:t.U.htmlEscape(r[1]),value:n}],i}function Re(n,_,m,g=!1,h=!1){const y=n;let x,k=!1;const C=b(y,L,g,h);if(C)x=Me(y,void 0,C);else switch(y.kind){case a.Block:return Je(y.statements,_,h);case a.ExpressionStatement:return Re(y.expression,_,m||y,g,h);case a.VariableStatement:if(x=Je(y.declarationList.declarations,void 0,!1,m||y),!x)return A();k=!0;break;case a.FunctionExpression:case a.ArrowFunction:return function(e,t){return Re(e.body,t)}(y,_);case a.BinaryExpression:x=function(e){e.left.text;switch(e.operatorToken.kind){case a.EqualsToken:return e.left.kind===a.Identifier?Be(e,e.left,e.right):e.left.kind==a.PropertyAccessExpression?$e(e,e.left,e.right,"@set@"):function(e,t,n){const r=oe("lists_index_set",e);return r.inputs=[Ce("LIST",t.expression),Ce("INDEX",t.argumentExpression,c),Ce("VALUE",n)],r}(e,e.left,e.right);case a.PlusEqualsToken:if(ke(e)){const t=oe("variables_set",e),n=Ge(e.left);return Ve(n,v.InBlocksOnly),t.inputs=[ce("VALUE",Te(e),c)],t.fields=[Pe("VAR",n)],t}return e.left.kind==a.PropertyAccessExpression?$e(e,e.left,e.right,"@change@"):Be(e,e.left,e.right,!0);case a.MinusEqualsToken:const n=oe("variables_change",e);return n.inputs=[ce("VALUE",Oe(e.right),c)],n.fields=[Pe("VAR",Ge(e.left))],n;default:return void ne(e,t.Util.lf("Unsupported operator token in statement {0}",a[e.operatorToken.kind]))}}(y);break;case a.PostfixUnaryExpression:case a.PrefixUnaryExpression:x=function(e){const t=e.operator===a.PlusPlusToken;if(!t&&e.operator!==a.MinusMinusToken)return void ne(e);return Be(e,e.operand,t?1:-1,!0)}(y);break;case a.VariableDeclaration:const n=y;if(S(n))return function(e){G.push([Ge(e.name),e])}(n),A();x=function(e){if(function(e){if(e.name.kind!==a.Identifier)return ne(e,t.Util.lf("Variable declarations may not use binding patterns")),!1;if(!e.initializer)return ne(e,t.Util.lf("Variable declarations must have an initializer")),!1;return!0}(e))return Be(e,e.name,e.initializer);return}(y);break;case a.WhileStatement:x=function(e){const t=oe("device_while",e);return t.inputs=[Ue("COND",e.expression)],t.handlers=[{name:"DO",statement:Re(e.statement)}],t}(y);break;case a.IfStatement:x=function(e){let t=ze(e);const n=oe("controls_if",e);if(n.mutation={elseif:(t.ifStatements.length-1).toString(),else:t.elseStatement?"1":"0"},n.inputs=[],n.handlers=[],t.ifStatements.forEach(((e,t)=>{let r=Re(e.thenStatement);n.inputs.push(Ue("IF"+t,e.expression)),n.handlers.push({name:"DO"+t,statement:r})})),t.elseStatement){let e=Re(t.elseStatement);n.handlers.push({name:"ELSE",statement:e})}return n}(y);break;case a.ForStatement:x=function(t){const n=t.initializer,r=(n.declarations[0].name.text,t.condition),i=Ge(n.declarations[0].name);let o;if(r.operatorToken.kind!==a.LessThanToken||l(t.statement))if(o=oe("pxt_controls_for",t),o.fields=[],o.inputs=[],o.handlers=[],o.inputs=[we("VAR",i)],r.operatorToken.kind===a.LessThanToken){const e=D(r.right);if(e.kind===a.NumericLiteral){const t=Ee(parseFloat(e.text)-1+"");o.inputs.push(ce("TO",t,d))}else{const t=se("math_arithmetic");t.fields=[Pe("OP","MINUS")],t.inputs=[Ce("A",e,c),Ce("B",1,c)],o.inputs.push(ce("TO",t,d))}}else r.operatorToken.kind===a.LessThanEqualsToken&&o.inputs.push(Ce("TO",r.right,d));else o=oe("controls_repeat_ext",t),o.fields=[],o.inputs=[Ce("TIMES",r.right,d)],o.handlers=[];const s=Re(t.statement);return o.handlers=[{name:"DO",statement:s}],o;function l(t){return t.kind===a.Identifier&&Ge(t)===i||e.forEachChild(t,l)}}(y);break;case a.ForOfStatement:x=function(e){const t=Ge(e.initializer.declarations[0].name),n=oe("pxt_controls_for_of",e);n.inputs=[Ce("LIST",e.expression),we("VAR",t)];const r=Re(e.statement);return n.handlers=[{name:"DO",statement:r}],n}(y);break;case a.FunctionDeclaration:x=function(e){const t=Ge(e.name);L.localReporters.push(e.parameters.map((e=>({name:e.name.getText(),type:e.type.getText()}))));const n=Re(e.body);let r;L.localReporters.pop(),r=oe("function_definition",e),r.mutation={name:t},e.parameters&&(r.mutationChildren=[],e.parameters.forEach((e=>{const n=e.name.getText();r.mutationChildren.push({nodeName:"arg",attributes:{name:n,type:e.type.getText(),id:L.functionParamIds[t][n]}})})));return r.handlers=[{name:"STACK",statement:n}],r}(y);break;case a.CallExpression:x=function(n,i){const s=t.pxtInfo(n).callInfo,_=re(s);if("Math.pow"==s.qName){const e=se("math_arithmetic");return e.inputs=[ce("A",ve(n.arguments[0]),c),ce("B",ve(n.arguments[1]),c)],e.fields=[Pe("OP","POWER")],e}if(pxt.Util.startsWith(s.qName,"Math.")){const e=s.qName.substring(5);if(R(e)){let t;if(B(e))t=se("math_js_round");else{let n;t=se("math_js_op"),n=M(e)?"unary":U(e)?"infix":"binary",t.mutation={"op-type":n}}return t.inputs=s.args.map(((e,t)=>ce("ARG"+t,ve(e),"math_number"))),t.fields=[Pe("OP",e)],t}}if(_.blockId===t.PAUSE_UNTIL_TYPE){const e=oe(t.PAUSE_UNTIL_TYPE,n),r=n.arguments[0];let i;return i=r.body.kind===a.Block?r.body.statements[0].expression:r.body,e.inputs=[ce("PREDICATE",ve(i),"logic_boolean")],e}if(!_.blockId||!_.block){const e=pxt.blocks.builtinFunctionInfo[s.qName];if(!e){const e=Ge(n.expression);if(L.declaredFunctions[e]){let t,r=!0;if(s.isExpression){const[e]=E(n);r=e&&e.kind===a.ExpressionStatement}return t=oe(r?"function_call":"function_call_output",n),s.args.length&&(t.mutationChildren=[],t.inputs=[],L.declaredFunctions[e].parameters.forEach(((n,r)=>{const i=n.name.getText(),a=L.functionParamIds[e][i];t.mutationChildren.push({nodeName:"arg",attributes:{name:i,type:n.type.getText(),id:a}});const o=ce(a,ve(s.args[r]));t.inputs.push(o)}))),t.mutation={name:e},t}return Me(n)}_.blockId=e.blockId}if(_.imageLiteral)return function(e,n){let r=e.arguments[0];if(r.kind!=a.StringLiteral&&r.kind!=a.NoSubstitutionTemplateLiteral)return void ne(e);const i=re(n),o=oe(i.blockId,e);o.fields=[];const s=(r.text||"").replace(/\s+/g,""),c=(i.imageLiteralColumns||5)*i.imageLiteral,l=i.imageLiteralRows||5,u=c*l;if(u!=s.length)return void ne(e,t.Util.lf("Invalid image pattern ({0} expected vs {1} actual)",u,s.length));let d="";for(let e=0;e<l;++e){for(let t=0;t<c;++t)d+=/[#*1]/.test(s[e*c+t])?"#":".";d+="\n"}return o.fields.push(Pe("LEDS",`\`${d}\``)),o}(n,s);e.isFunctionLike(s.decl);const m=O(s,L.blocks),g=L.blocks.apis.byQName[s.decompilerBlockAlias||s.qName],h=pxt.blocks.compileInfo(g),y=i?se(_.blockId):oe(_.blockId,n),v=e=>(y.inputs||(y.inputs=[])).push(e),b=e=>(y.fields||(y.fields=[])).push(e);"Math.max"==s.qName&&b({kind:"field",name:"op",value:"max"});let x=0;m.forEach(((e,n)=>{let i,m=e.value;const g=e.param,k=e.info,S=h.parameters[h.thisParameter?n-1:n],C=S&&S.range;if(C){const e=C.min,t=C.max;i={min:e.toString(),max:t.toString()}}if(0===n&&_.defaultInstance){if(m.getText()===_.defaultInstance)return;y.mutation={showing:"true"}}if(_.mutatePropertyEnum&&n===s.args.length-2)return;let E;if(g&&g.isOptional&&++x,g&&g.shadowBlockId&&(E=o.blocksById[g.shadowBlockId]),m.kind===a.CallExpression){const e=t.pxtInfo(m).callInfo,n=e&&re(e);n&&"TD_ID"===n.shim&&k.isEnum&&(m=D(e.args[0]))}if(g&&k&&k.isEnum&&m.kind===a.Identifier)b(Pe(t.U.htmlEscape(g.definitionName),t.pxtInfo(m).commentAttrs.enumIdentity));else if(g&&g.fieldOptions&&g.fieldOptions[r.DecompileArgumentAsString])b(Pe(t.U.htmlEscape(g.definitionName),t.Util.htmlEscape(m.getText())));else switch(m.kind){case a.FunctionExpression:case a.ArrowFunction:m.body;const e=function(e){const n=T(e);if(n)return{callbackproperties:n[0].join(","),renamemap:t.Util.htmlEscape(JSON.stringify(n[1]))};return}(m);let x=!1;if(e)y.mutation=e;else{let e=m;const t=o.blocksById[_.blockId].parameters[h.thisParameter?n-1:n],r=(e,t)=>{"reporter"===_.draggableParameters?v(function(e,t,n){const r=pxt.blocks.reporterTypeForArgType(n);return ce(e,Ie(t,n,!0),r)}("HANDLER_DRAG_PARAM_"+e.name,t,e.type)):v(we("HANDLER_DRAG_PARAM_"+e.name,t))};if(e.parameters.length&&(_.optionalVariableArgs?(y.mutation={numargs:e.parameters.length.toString()},e.parameters.forEach(((e,t)=>{y.mutation["arg"+t]=e.name.text}))):e.parameters.forEach(((e,n)=>{const i=t.handlerParameters[n];_.draggableParameters?r(i,e.name.text):b(Pe("HANDLER_"+i.name,e.name.text))}))),_.draggableParameters){if(e.parameters.length<t.handlerParameters.length)for(let n=e.parameters.length;n<t.handlerParameters.length;n++){const e=t.handlerParameters[n];r(e,e.name)}"reporter"===_.draggableParameters&&(L.localReporters.push(t.handlerParameters),x=!0)}}const S=Re(m);(y.handlers||(y.handlers=[])).push({name:"HANDLER",statement:S}),x&&L.localReporters.pop();break;case a.PropertyAccessExpression:const C=t.pxtInfo(m).callInfo,D=t.U.htmlEscape(g.definitionName),A=re(C);E&&"TD_ID"===E.attributes.shim?v(ce(D,Fe(m,!1,g.shadowBlockId),g.shadowBlockId,i)):k&&k.isEnum||C&&(A.fixedInstance||A.blockIdentity===s.qName)?b(Pe(D,Fe(m,!0).value)):v(Ce(D,m,g.shadowBlockId,i));break;case a.BinaryExpression:if(g&&g.shadowOptions&&g.shadowOptions.toString){const e=m;if(e.operatorToken.kind===a.PlusToken&&function(e){if(e.kind===a.StringLiteral||e.kind===a.NoSubstitutionTemplateLiteral)return""===e.text;return!1}(e.left)){v(Ce(t.U.htmlEscape(g.definitionName),e.right,g.shadowBlockId||"text"));break}}v(Ce(t.U.htmlEscape(g.definitionName),m,g.shadowBlockId,i));break;default:let N;const w=t.U.htmlEscape(g.definitionName);let P=!0;if("Math.random"==s.qName)N=ce(w,function(e){switch(e.kind){case a.NumericLiteral:return Ee((parseInt(e.text)-1).toString());case a.BinaryExpression:const t=e;if(t.operatorToken.kind==a.PlusToken&&"1"==t.right.text)return ve(t.left);default:return ve(e)}}(m),c,i),P=!1;else if(I(m)){const e="text"==g.fieldEditor?m.text:m.getText(),n=g.shadowBlockId&&!function(e){switch(e){case c:case l:case u:case d:case p:case f:return!0;default:return!1}}(g.shadowBlockId);if(Ke(g)&&g.fieldOptions.onParentBlock)return void b(Pe(w,e));if(n){const n=function(e){if(o.blocksById[e]){const t=pxt.blocks.compileInfo(o.blocksById[e]);if(!t.thisParameter&&1===t.parameters.length)return t.parameters[0]}return}(g.shadowBlockId);if(n&&Ke(n)){const r=Ne(g.shadowBlockId,n.definitionName,e,!0);g.shadowOptions&&(r.mutation={customfield:t.Util.htmlEscape(JSON.stringify(g.shadowOptions))}),N=ce(w,r,g.shadowBlockId,i),P=!1}}}else if(m.kind===a.TaggedTemplateExpression&&g.fieldOptions&&g.fieldOptions[r.TaggedTemplate])return void b(Pe(w,t.Util.htmlEscape(m.getText())));P&&(N=Ce(w,m,g.shadowBlockId,i)),v(N)}})),x&&(y.mutation||(y.mutation={}),y.mutation._expanded=x.toString());return y}(y,g);break;case a.DebuggerStatement:x=function(e){return oe(t.TS_DEBUGGER_TYPE,e)}(y);break;case a.BreakStatement:x=function(e){return oe(t.TS_BREAK_TYPE,e)}(y);break;case a.ContinueStatement:x=function(e){return oe(t.TS_CONTINUE_TYPE,e)}(y);break;case a.EmptyStatement:x=void 0;break;case a.EnumDeclaration:case a.ModuleDeclaration:return V(y,Y),A();case a.ReturnStatement:x=function(e){const n=oe(t.TS_RETURN_STATEMENT_TYPE,e);e.expression?n.inputs=[ce("RETURN_VALUE",ve(e.expression),c)]:n.mutation={no_return_value:"true"};return n}(y);break;default:return void ne(y,_?t.Util.lf("Unsupported statement in block: {0}",a[y.kind]):t.Util.lf("Statement kind unsupported in blocks: {0}",a[y.kind]))}if(x){let e=x;for(;e.next;)e=e.next;e.next=A(),e.next&&(e.next.prev=e)}return k||function(t){let n,r=[];for(let e=0;e<Y.length&&(n=Y[e],!n.owner&&n.start>=t.pos&&n.end<=t.end&&(n.owner=t,n.ownerStatement=x,r.push(n)),!(n.start>t.end));e++);if(n&&n.isTrailingComment){const i=e.getLineAndCharacterOfPosition(s,t.end),a=e.getLineAndCharacterOfPosition(s,n.start);if(i.line===a.line){if(n.ownerStatement){n.ownerStatement.comment.splice(n.ownerStatement.comment.indexOf(n),1);for(const e of H)e.comment.splice(e.comment.indexOf(n),1)}n.owner=t,n.ownerStatement=x,r.push(n)}}if(r.length){const e=[];if(J(t)){let t=[];const n=[];r.forEach(((e,a)=>{let o=e.owner&&e.start<e.owner.getStart();e.kind===i.MultiLine&&o&&(t.length&&(n.push(t),t=[]),a!=r.length-1)?n.push([e]):(t.push(e),e.followedByEmptyLine&&o&&(n.push(t),t=[]))})),r=t,n.forEach((t=>{const n=W();e.push(n),H.push({comment:t,refId:n})}))}x&&(e.length&&(x.data?x.data+=";"+e.join(";"):x.data=e.join(";")),r&&r.length&&(x.comment?x.comment=x.comment.concat(r):x.comment=r))}}(m||y),x;function A(){if(_&&_.length)return Re(_.shift(),_,void 0,!1,h)}}function Me(e,n,r){m.errorOnGreyBlocks&&ne(e);const i=oe(t.TS_STATEMENT_TYPE,e);i.mutation={},He(e);let o=e.getText();o=be(o,e.getStart(),e.getEnd()),V(e,Y),n&&(o=n+o);const s=[];if(e.kind===a.VariableStatement)for(const t of e.declarationList.declarations)s.push(Ge(t.name));else e.kind===a.VariableDeclaration&&s.push(Ge(e.name));s.length&&(i.mutation.declaredvars=s.join(","));const c=o.split("\n");return i.mutation.numlines=c.length.toString(),r&&m.includeGreyBlockMessages&&(i.mutation.error=t.U.htmlEscape(r)),c.forEach(((e,n)=>{i.mutation[`line${n}`]=t.U.htmlEscape(e)})),i}function Ue(n,r){if(function(n){const r=D(n);switch(r.kind){case a.TrueKeyword:case a.FalseKeyword:case a.Identifier:case a.ElementAccessExpression:return;case a.BinaryExpression:return i(r);case a.CallExpression:return o(r);case a.PrefixUnaryExpression:if(r.operator===a.ExclamationToken)return;default:return t.Util.lf("Conditions must evaluate to booleans or identifiers")}function i(e){switch(e.operatorToken.kind){case a.EqualsEqualsToken:case a.EqualsEqualsEqualsToken:case a.ExclamationEqualsToken:case a.ExclamationEqualsEqualsToken:case a.LessThanToken:case a.LessThanEqualsToken:case a.GreaterThanToken:case a.GreaterThanEqualsToken:case a.AmpersandAmpersandToken:case a.BarBarToken:return;default:return t.Util.lf("Binary expressions in conditionals must evaluate to booleans")}}function o(n){const r=t.pxtInfo(n).callInfo;if(r){const t=L.blocks.apis.byQName[r.qName];if(t&&"boolean"==t.retType)return;if(e.isIdentifier(n.expression)&&L.declaredFunctions[n.expression.text])return}return t.Util.lf("Only functions that return booleans are allowed as conditions")}}(r)){return ce(n,xe(r),f)}return Ce(n,r,f)}function Be(e,t,n,r=!1,i=!1){const a=Ge(t);Ve(a,v.InBlocksOnly);const o=oe(r?"variables_change":"variables_set",e.parent||e);return o.inputs=[Ce("VALUE",n,c)],o.fields=[Pe("VAR",a)],o}function $e(e,t,n,r){return je(e,t,n,r)}function je(e,n,r,i){const a=t.pxtInfo(n).callInfo,o=L.blocks.apis.byQName[a?a.qName:""];if(!o||!o.attributes.blockCombine)return void ne(n);const s=`${o.namespace}.${o.retType}.${i}`,c=L.blocks.blocks.find((e=>e.qName==s)),l=r?oe(c.attributes.blockId,e):se(c.attributes.blockId),u=c.attributes._def.parameters;let d=a.qName;return c.combinedProperties&&c.combinedProperties.forEach((e=>{0===e.indexOf(a.qName)&&"@"===e.charAt(a.qName.length)&&(d=e)})),l.inputs=[Ce(u[0].name,n.expression)],l.fields=[Pe(u[1].name,d)],r&&l.inputs.push(Ce(u[2].name,r)),l}function Ke(e){return e&&e.fieldOptions&&e.fieldOptions[r.DecompileLiterals]}function ze(e){let t={ifStatements:[{expression:e.expression,thenStatement:e.thenStatement}],elseStatement:e.elseStatement};if(e.elseStatement&&e.elseStatement.kind==a.IfStatement){let n=ze(e.elseStatement);t.ifStatements=t.ifStatements.concat(n.ifStatements),t.elseStatement=n.elseStatement}return t}function Je(t,n,r=!1,i,o=!1){const s=[],c=n||[];for(let e=t.length-1;e>=0;e--){const n=t[e];(n.kind===a.FunctionDeclaration||n.kind==a.ExpressionStatement&&le(n))&&!b(n,L,!1,r)?s.unshift(n):c.unshift(n)}if(s.map((e=>Re(e,void 0,void 0,!1,r))).forEach(ue),c.length){const t=c.shift(),n=Re(t,c,i,!1,r);if(o){let r=n,i=t;if(G.forEach((([e,n])=>{if(K[e]===v.InBlocksOnly)return;let a;n.initializer;a=K[e]===v.InTextBlocks?Me(n,"let "):Be(t,n.name,n.initializer,!1,!0),a.next=r,r=a,i=n})),r){const t=oe(e.pxtc.ON_START_TYPE,i);return t.handlers=[{name:"HANDLER",statement:r}],t}qe(n)}return n}o&&qe(void 0)}function qe(t){m.alwaysEmitOnStart&&(he(e.pxtc.ON_START_TYPE,t),ye())}function Ve(e,t){K[e]!==v.InTextBlocks&&(K[e]=t)}function He(t){e.forEachChild(t,(e=>{e.kind===a.Identifier&&Ve(Ge(e),v.InTextBlocks),He(e)}))}function Ge(e){if(g){const t=g.getRenameForPosition(e.getStart());if(t)return t.name}return e.text}},n.getLeadingComments=function(t,n,r){return K(n,r||e.getLeadingCommentRangesOfNode(t,n))},n.getTrailingComments=function(t,n){return K(n,e.getTrailingCommentRanges(n.getFullText(),t.end))},n.getCommentsForStatement=function(e,t){let n,r=[];for(let i=0;i<t.length&&(n=t[i],!n.owner&&n.start>=e.pos&&n.end<=e.end&&(n.owner=e,r.push(n)),!(n.start>e.end));i++);return r},n.buildCommentMap=q}(t.decompiler||(t.decompiler={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){!function(e){function t(e,n){var r;switch(e){case"void":return"None";case"boolean":return"bool";case"string":return"str"}if(null===(r=n.byQName[e])||void 0===r?void 0:r.pyQName)return n.byQName[e].pyQName;const i=/^(?:Array<(.+)>)|(?:(.+)\[\])|(?:\[.+\])$/.exec(e);return i?`List[${t(i[1]||i[2],n)}]`:e}function n(e,t){return`\`\`\`${t?"python":"ts"}\n${e}\n\`\`\``}e.displayStringForSymbol=function(e,r,i){if(e){switch(e.kind){case 3:case 1:return function(e,r,i){let a="";3===e.kind?a+=r?"def ":"function ":a+="(method) ";a+=r?e.pyQName:e.qName;let o="";e.parameters&&e.parameters.length&&(o=e.parameters.map((e=>`${e.name}: ${r?e.pyTypeString:e.type}`)).join(", "));let s=e.retType||"void";r&&(s=t(s,i));return n(`${a}(${o}): ${s}`,r)}(e,r,i);case 6:case 7:return function(e,t){const r=t?e.pyQName:e.qName;if(6===e.kind)return n(`enum ${r}`,t);let i=`(enum member) ${r}`;e.attributes.enumval&&(i+=` = ${e.attributes.enumval}`);return n(i,!1)}(e,r);case 5:return function(e,t){return n(`namespace ${t?e.pyQName:e.qName}`,!1)}(e,r);case 9:return function(e,t){return n(`interface ${t?e.pyQName:e.qName}`,!1)}(e,r);case 8:return function(e,t){return n(`class ${t?e.pyQName:e.qName}`,t)}(e,r);case 4:return function(e,r,i){let a=r?e.pyQName:`let ${e.qName}`;if(e.retType){let o=e.retType;return r&&(o=t(o,i)),n(`${a}: ${o}`,r)}return n(a,r)}(e,r,i);case 2:return function(e,r,i){const a=`(property) ${r?e.pyQName:e.qName}`;if(e.retType){let o=e.retType;return r&&(o=t(o,i)),n(`${a}: ${o}`,!1)}return n(a,!1)}(e,r,i)}return`**${e.qName}**`}},e.displayStringForKeyword=function(e,t){return`\`\`\`${t?"py":"ts"}\n(keyword) ${e}\n\`\`\``}}(e.service||(e.service={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){!function(t){const n={r0:0,r1:1,r2:2,r3:3,r4:4,r5:5,r6:6,r7:7,r8:8,r9:9,r10:10,r11:10,r12:12,sp:13,r13:13,lr:14,r14:14,pc:15,r15:15};class r extends e.assembler.AbstractProcessor{constructor(){super(),this.addEnc("$r0","R0-7",(e=>this.inrange(7,e,e))),this.addEnc("$r1","R0-7",(e=>this.inrange(7,e,e<<3))),this.addEnc("$r2","R0-15",(e=>this.inrange(15,e,7&e|(8&e)<<4))),this.addEnc("$r3","R0-15",(e=>this.inrange(15,e,e<<3))),this.addEnc("$r4","R0-7",(e=>this.inrange(7,e,e<<6))),this.addEnc("$r5","R0-7",(e=>this.inrange(7,e,e<<8))),this.addEnc("$r01","R0-7",(e=>this.inrange(7,e,e|e<<3))),this.addEnc("$i0","#0-255",(e=>this.inrange(255,e,e))),this.addEnc("$i1","#0-1020",(e=>this.inrange(255,e/4,e>>2))),this.addEnc("$i2","#0-510",(e=>this.inrange(127,e/4,e>>2))),this.addEnc("$i3","#0-7",(e=>this.inrange(7,e,e<<6))),this.addEnc("$i4","#0-31",(e=>this.inrange(31,e,e<<6))),this.addEnc("$i5","#0-124",(e=>this.inrange(31,e/4,e>>2<<6))),this.addEnc("$i6","#1-32",(e=>0==e?null:32==e?0:this.inrange(31,e,e<<6))),this.addEnc("$i7","#0-62",(e=>this.inrange(31,e/2,e>>1<<6))),this.addEnc("$i32","#0-2^32",(e=>1)),this.addEnc("$rl0","{R0-7,...}",(e=>this.inrange(255,e,e))),this.addEnc("$rl1","{LR,R0-7,...}",(e=>16384&e?this.inrange(255,-16385&e,256|255&e):this.inrange(255,e,e))),this.addEnc("$rl2","{PC,R0-7,...}",(e=>32768&e?this.inrange(255,-32769&e,256|255&e):this.inrange(255,e,e))),this.addEnc("$la","LABEL",(e=>this.inrange(255,e/4,e>>2))).isWordAligned=!0,this.addEnc("$lb","LABEL",(e=>this.inrangeSigned(127,e/2,e>>1))),this.addEnc("$lb11","LABEL",(e=>this.inrangeSigned(1023,e/2,e>>1))),this.addInst("adcs $r0, $r1",16704,65472),this.addInst("add $r2, $r3",17408,65280),this.addInst("add $r5, pc, $i1",40960,63488),this.addInst("add $r5, sp, $i1",43008,63488),this.addInst("add sp, $i2",45056,65408).canBeShared=!0,this.addInst("adds $r0, $r1, $i3",7168,65024),this.addInst("adds $r0, $r1, $r4",6144,65024),this.addInst("adds $r01, $r4",6144,65024),this.addInst("adds $r5, $i0",12288,63488),this.addInst("adr $r5, $la",40960,63488),this.addInst("ands $r0, $r1",16384,65472),this.addInst("asrs $r0, $r1",16640,65472),this.addInst("asrs $r0, $r1, $i6",4096,63488),this.addInst("bics $r0, $r1",17280,65472),this.addInst("bkpt $i0",48640,65280),this.addInst("blx $r3",18304,65415),this.addInst("bx $r3",18176,65408),this.addInst("cmn $r0, $r1",17088,65472),this.addInst("cmp $r0, $r1",17024,65472),this.addInst("cmp $r2, $r3",17664,65280),this.addInst("cmp $r5, $i0",10240,63488),this.addInst("eors $r0, $r1",16448,65472),this.addInst("ldmia $r5!, $rl0",51200,63488),this.addInst("ldmia $r5, $rl0",51200,63488),this.addInst("ldr $r0, [$r1, $i5]",26624,63488),this.addInst("ldr $r0, [$r1, $r4]",22528,65024),this.addInst("ldr $r5, [pc, $i1]",18432,63488),this.addInst("ldr $r5, $la",18432,63488),this.addInst("ldr $r5, [sp, $i1]",38912,63488).canBeShared=!0,this.addInst("ldr $r5, [sp]",38912,63488).canBeShared=!0,this.addInst("ldrb $r0, [$r1, $i4]",30720,63488),this.addInst("ldrb $r0, [$r1, $r4]",23552,65024),this.addInst("ldrh $r0, [$r1, $i7]",34816,63488),this.addInst("ldrh $r0, [$r1, $r4]",23040,65024),this.addInst("ldrsb $r0, [$r1, $r4]",22016,65024),this.addInst("ldrsh $r0, [$r1, $r4]",24064,65024),this.addInst("lsls $r0, $r1",16512,65472),this.addInst("lsls $r0, $r1, $i4",0,63488),this.addInst("lsrs $r0, $r1",16576,65472),this.addInst("lsrs $r0, $r1, $i6",2048,63488),this.addInst("mov $r2, $r3",17920,65280),this.addInst("movs $r0, $r1",0,65472),this.addInst("movs $r5, $i0",8192,63488),this.addInst("muls $r0, $r1",17216,65472),this.addInst("mvns $r0, $r1",17344,65472),this.addInst("negs $r0, $r1",16960,65472),this.addInst("nop",18112,65535),this.addInst("orrs $r0, $r1",17152,65472),this.addInst("pop $rl2",48128,65024),this.addInst("push $rl1",46080,65024),this.addInst("rev $r0, $r1",47616,65472),this.addInst("rev16 $r0, $r1",47680,65472),this.addInst("revsh $r0, $r1",47808,65472),this.addInst("rors $r0, $r1",16832,65472),this.addInst("sbcs $r0, $r1",16768,65472),this.addInst("sev",48960,65535),this.addInst("stm $r5!, $rl0",49152,63488),this.addInst("stmia $r5!, $rl0",49152,63488),this.addInst("stmea $r5!, $rl0",49152,63488),this.addInst("str $r0, [$r1, $i5]",24576,63488).canBeShared=!0,this.addInst("str $r0, [$r1]",24576,63488).canBeShared=!0,this.addInst("str $r0, [$r1, $r4]",20480,65024),this.addInst("str $r5, [sp, $i1]",36864,63488).canBeShared=!0,this.addInst("str $r5, [sp]",36864,63488).canBeShared=!0,this.addInst("strb $r0, [$r1, $i4]",28672,63488),this.addInst("strb $r0, [$r1, $r4]",21504,65024),this.addInst("strh $r0, [$r1, $i7]",32768,63488),this.addInst("strh $r0, [$r1, $r4]",20992,65024),this.addInst("sub sp, $i2",45184,65408),this.addInst("subs $r0, $r1, $i3",7680,65024),this.addInst("subs $r0, $r1, $r4",6656,65024),this.addInst("subs $r01, $r4",6656,65024),this.addInst("subs $r5, $i0",14336,63488),this.addInst("svc $i0",57088,65280),this.addInst("sxtb $r0, $r1",45632,65472),this.addInst("sxth $r0, $r1",45568,65472),this.addInst("tst $r0, $r1",16896,65472),this.addInst("udf $i0",56832,65280),this.addInst("uxtb $r0, $r1",45760,65472),this.addInst("uxth $r0, $r1",45696,65472),this.addInst("wfe",48928,65535),this.addInst("wfi",48944,65535),this.addInst("yield",48912,65535),this.addInst("cpsid i",46706,65535),this.addInst("cpsie i",46690,65535),this.addInst("beq $lb",53248,65280),this.addInst("bne $lb",53504,65280),this.addInst("bcs $lb",53760,65280),this.addInst("bcc $lb",54016,65280),this.addInst("bmi $lb",54272,65280),this.addInst("bpl $lb",54528,65280),this.addInst("bvs $lb",54784,65280),this.addInst("bvc $lb",55040,65280),this.addInst("bhi $lb",55296,65280),this.addInst("bls $lb",55552,65280),this.addInst("bge $lb",55808,65280),this.addInst("blt $lb",56064,65280),this.addInst("bgt $lb",56320,65280),this.addInst("ble $lb",56576,65280),this.addInst("bhs $lb",53760,65280),this.addInst("blo $lb",54016,65280),this.addInst("b $lb11",57344,63488),this.addInst("bal $lb11",57344,63488),this.addInst("bl $lb",61440,63488,!0),this.addInst("bb $lb",57344,63488,!0),this.addInst("ldlit $r5, $i32",18432,63488)}toFnPtr(t,n,r){return e.target.runtimeIsARM&&/::/.test(r)?t+n&-2:t+n|1}wordSize(){return 4}is32bit(e){return"bl"==e.name||"bb"==e.name}postProcessAbsAddress(e,t){return t^=1,t-=e.baseOffset}emit32(t,n,r){let i=!!(n%2);i&&(n=n+1&-4);let a=n>>1;if(e.assert(null!=a),(0|a)!=a||!(-2097152<a&&a<2097152))return e.assembler.emitErr("jump out of range",r);let o=2047&a,s=a>>11&1023;return{opcode:4026531840&a?62464|s:61440|s,opcode2:i?59392|o:63488|o,stack:0,numArgs:[n],labelName:r}}expandLdlit(t){let n,r=!1,i=[],a={},o=1;for(let s=0;s<t.lines.length;++s){let c=t.lines[s];if(i.push(c),"instruction"==c.type&&c.instruction&&"ldlit"==c.instruction.name){if(!n){let e=c.location+900,i=s+1;for(;i<t.lines.length&&!(t.lines[i].location>e);++i){let e=t.lines[i].getOp();("b"==e||"bb"==e||"pop"==e&&"pc"==t.lines[i].words[2])&&(n=t.lines[i])}if(n)r=!1;else for(r=!0;--i>s;)if("instruction"==t.lines[i].type){n=t.lines[i];break}}let i=c.words[1],l="#"+c.words[3],u=e.U.lookup(a,l);u||(u="_ldlit_"+ ++o,a[l]=u),c.update(`ldr ${i}, ${u}`)}if(c===n){n=null;let e=[],s="_jmpwords_"+ ++o;r&&e.push("bb "+s),e.push(".balign 4");for(let t of Object.keys(a)){let n=a[t];e.push(n+": .word "+t.slice(1))}r&&e.push(s+":");for(let n of e){t.buildLine(n,i);let e=i[i.length-1];e.scope=c.scope,e.lineNo=c.lineNo}a={}}}t.lines=i}getAddressFromLabel(e,t,n,r=!1){let i=e.lookupLabel(n);if(null==i)return null;let a=e.location()+4;return r&&(a&=4294967292),i-a}isPop(e){return 48128==e}isPush(e){return 46080==e}isAddSP(e){return 45056==e}isSubSP(e){return 45184==e}peephole(t,n,r){let a=this.encoders.$lb11,o=this.encoders.$lb;function s(e,t){return null!=e.encode(t.numArgs[0]+8)&&null!=e.encode(t.numArgs[0]-8)&&null!=e.encode(t.numArgs[0])}let c=t.getOp(),l=!1;"bne"!=c&&"beq"!=c||("b"==n.getOp()&&0==t.numArgs[0]&&(l=!0),"bb"==n.getOp()&&2==t.numArgs[0]&&(l=!0)),"bb"==c&&s(a,t)?t.update("b "+t.words[1]):"b"==c&&-2==t.numArgs[0]?t.update(""):"bne"==c&&l&&s(o,n)?(t.update("beq "+n.words[1]),n.update("")):"beq"==c&&l&&s(o,n)?(t.update("bne "+n.words[1]),n.update("")):"push"!=c||16384!=t.numArgs[0]||"push"!=n.getOp()||16384&n.numArgs[0]?"pop"==c&&"pop"==n.getOp()&&32768==n.numArgs[0]?(t.update(t.text.replace("}",", pc}")),n.update("")):"push"==c&&"pop"==n.getOp()&&t.numArgs[0]==n.numArgs[0]?(e.assert(t.numArgs[0]>0),t.update(""),n.update("")):"push"==c&&"pop"==n.getOp()&&4==t.words.length&&4==n.words.length?(e.assert("{"==t.words[1]),t.update("mov "+n.words[2]+", "+t.words[2]),n.update("")):r&&"movs $r5, $i0"==t.getOpExt()&&"mov $r0, $r1"==n.getOpExt()&&t.numArgs[0]==n.numArgs[1]&&function(e,t){return!!("pop"==e.getOp()&&e.numArgs[0]&1<<t)}(r,t.numArgs[0])?(t.update("movs r"+n.numArgs[0]+", #"+t.numArgs[1]),n.update("")):"pop"==c&&i(t)>=0&&"push"==n.getOp()&&i(t)==i(n)?(t.update("ldr r"+i(t)+", [sp, #0]"),n.update("")):"push"==c&&"ldr $r5, [sp, $i1]"==n.getOpExt()&&i(t)==n.numArgs[0]&&0==n.numArgs[1]?n.update(""):r&&"push"==c&&i(t)>=0&&function(e,t){return"movs $r5, $i0"==e.getOpExt()&&e.numArgs[0]!=t}(n,i(t))&&"pop"==r.getOp()&&i(t)==i(r)&&(t.update(""),r.update("")):(t.update(n.text.replace("{","{lr, ")),n.update(""))}registerNo(e){if(!e)return null;e=e.toLowerCase();const t=n[e];return void 0===t?null:t}testAssembler(){e.assembler.expectError(this,"lsl r0, r0, #8"),e.assembler.expectError(this,"push {pc,lr}"),e.assembler.expectError(this,"push {r17}"),e.assembler.expectError(this,"mov r0, r1 foo"),e.assembler.expectError(this,"movs r14, #100"),e.assembler.expectError(this,"push {r0"),e.assembler.expectError(this,"push lr,r0}"),e.assembler.expectError(this,"pop {lr,r0}"),e.assembler.expectError(this,"b #+11"),e.assembler.expectError(this,"b #+102400"),e.assembler.expectError(this,"bne undefined_label"),e.assembler.expectError(this,".foobar"),e.assembler.expect(this,"0200 lsls r0, r0, #8\nb500 push {lr}\n2064 movs r0, #100 ; 0x64\nb401 push {r0}\nbc08 pop {r3}\nb501 push {r0, lr}\nbd20 pop {r5, pc}\nbc01 pop {r0}\n4770 bx lr\n0000 .balign 4\ne6c0 .word -72000\nfffe\n"),e.assembler.expect(this,"4291 cmp r1, r2\nd100 bne l6\ne000 b l8\n1840 l6: adds r0, r0, r1\n4718 l8: bx r3\n"),e.assembler.expect(this," @stackmark base\nb403 push {r0, r1}\n @stackmark locals\n9801 ldr r0, [sp, locals@1]\nb401 push {r0}\n9802 ldr r0, [sp, locals@1]\nbc01 pop {r0}\n @stackempty locals\n9901 ldr r1, [sp, locals@1]\n9102 str r1, [sp, base@0]\n @stackempty locals\nb002 add sp, #8\n @stackempty base\n"),e.assembler.expect(this,"b090 sub sp, #4*16\nb010 add sp, #4*16\n"),e.assembler.expect(this,'6261 .string "abc"\n0063 \n'),e.assembler.expect(this,'6261 .string "abcde"\n6463 \n0065 \n'),e.assembler.expect(this,"3042 adds r0, 0x42\n1c0d adds r5, r1, #0\nd100 bne #0\n2800 cmp r0, #0\n6b28 ldr r0, [r5, #48]\n0200 lsls r0, r0, #8\n2063 movs r0, 0x63\n4240 negs r0, r0\n46c0 nop\nb500 push {lr}\nb401 push {r0}\nb402 push {r1}\nb404 push {r2}\nb408 push {r3}\nb520 push {r5, lr}\nbd00 pop {pc}\nbc01 pop {r0}\nbc02 pop {r1}\nbc04 pop {r2}\nbc08 pop {r3}\nbd20 pop {r5, pc}\n9003 str r0, [sp, #4*3]\n")}}function i(t){e.assert("push"==t.getOp()||"pop"==t.getOp());let n=0,r=-1,i=t.numArgs[0];for(;i>0;)1&i&&(r=-1==r?n:-2),i>>=1,n++;return r>=0?r:-1}t.ThumbProcessor=r}(e.thumb||(e.thumb={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){!function(n){let r,i=t.Util;i.assert;!function(e){e[e.None=0]="None",e[e.NumberLiteral=1]="NumberLiteral",e[e.PointerLiteral=2]="PointerLiteral",e[e.RuntimeCall=3]="RuntimeCall",e[e.ProcCall=4]="ProcCall",e[e.SharedRef=5]="SharedRef",e[e.SharedDef=6]="SharedDef",e[e.FieldAccess=7]="FieldAccess",e[e.Store=8]="Store",e[e.CellRef=9]="CellRef",e[e.Sequence=10]="Sequence",e[e.JmpValue=11]="JmpValue",e[e.Nop=12]="Nop",e[e.InstanceOf=13]="InstanceOf"}(r=n.EK||(n.EK={}));let a,o,s=0;class c{isExpr(){return!1}isStmt(){return!1}getId(){return this._id||(this._id=++s),this._id}}n.Node=c;class l extends c{constructor(e,t,n){super(),this.exprKind=e,this.args=t,this.data=n,this.callingConvention=0}static clone(e){let t=new l(e.exprKind,e.args?e.args.slice(0):null,e.data);return e.jsInfo&&(t.jsInfo=e.jsInfo),e.totalUses&&(t.totalUses=e.totalUses,t.currUses=e.currUses),t.callingConvention=e.callingConvention,t.mask=e.mask,t.isStringLiteral=e.isStringLiteral,t}reset(){this.currUses=0,this.prevTotalUses&&(this.totalUses=this.prevTotalUses)}ptrlabel(){return this.jsInfo instanceof u?this.jsInfo:null}hexlit(){const e=this.jsInfo;return null!=e.hexlit?e.hexlit:null}isExpr(){return!0}isPure(){return this.isStateless()||this.exprKind==r.CellRef}isLiteral(){switch(this.exprKind){case r.NumberLiteral:case r.PointerLiteral:return!0;default:return!1}}isStateless(){switch(this.exprKind){case r.NumberLiteral:case r.PointerLiteral:case r.SharedRef:return!0;default:return!1}}sharingInfo(){let e=this,t=this.getId();return this.exprKind!=r.SharedRef&&this.exprKind!=r.SharedDef||(e=this.args[0],e?t=e.getId():e={currUses:"",totalUses:""}),`${e.currUses}/${e.totalUses} #${t}`}toString(){return d(this)}canUpdateCells(){switch(this.exprKind){case r.NumberLiteral:case r.PointerLiteral:case r.CellRef:case r.JmpValue:case r.SharedRef:case r.Nop:return!1;case r.SharedDef:case r.FieldAccess:case r.InstanceOf:return this.args[0].canUpdateCells();case r.RuntimeCall:case r.ProcCall:case r.Sequence:case r.Store:return!0;default:throw t.oops()}}}n.Expr=l,function(e){e[e.None=0]="None",e[e.Expr=1]="Expr",e[e.Label=2]="Label",e[e.Jmp=3]="Jmp",e[e.StackEmpty=4]="StackEmpty",e[e.Breakpoint=5]="Breakpoint",e[e.Comment=6]="Comment"}(a=n.SK||(n.SK={})),function(e){e[e.Always=1]="Always",e[e.IfZero=2]="IfZero",e[e.IfNotZero=3]="IfNotZero"}(o=n.JmpMode||(n.JmpMode={})),n.lblNumUsesJmpNext=-101;class u extends c{constructor(e,t){super(),this.stmtKind=e,this.expr=t}isStmt(){return!0}toString(){return d(this)}}function d(e){return function e(i){if(i.isExpr()){let n=i,a=n.args?n.args[0]:null;switch(n.exprKind){case r.NumberLiteral:case r.PointerLiteral:return n.data+"";case r.CellRef:return n.data.toString();case r.JmpValue:return"JMPVALUE";case r.Nop:return"NOP";case r.SharedRef:return`SHARED_REF(#${a.getId()})`;case r.SharedDef:return`SHARED_DEF(#${a.getId()} u(${a.totalUses}): ${e(a)})`;case r.FieldAccess:return`${e(a)}.${n.data.name}`;case r.RuntimeCall:return n.data+"("+n.args.map(e).join(", ")+")";case r.ProcCall:let i=n.data,o="";return o=null!=i.ifaceIndex?`IFACE@${i.ifaceIndex}`:null!=i.virtualIndex?`VTABLE@${i.virtualIndex}`:t.getDeclName(i.proc.action),o+"("+n.args.map(e).join(", ")+")";case r.Sequence:return"("+n.args.map(e).join("; ")+")";case r.InstanceOf:return"("+e(n.args[0])+" instanceof "+n.data.id+")";case r.Store:return`{ ${e(n.args[0])} := ${e(n.args[1])} }`;default:throw t.oops()}}else{let r=i,a=r.expr?e(r.expr):"{null}";switch(r.stmtKind){case n.SK.Expr:return" "+a+"\n";case n.SK.Jmp:let e=`goto ${r.lblName}\n`;switch(r.jmpMode){case o.Always:return r.expr?` { JMPVALUE := ${a} } ${e}`:" "+e;case o.IfZero:return` if (! ${a}) ${e}`;case o.IfNotZero:return` if (${a}) ${e}`;default:throw t.oops()}case n.SK.StackEmpty:return" ;\n";case n.SK.Breakpoint:return" // brk "+r.breakpointInfo.id+"\n";case n.SK.Comment:return" // "+r.expr.data+"\n";case n.SK.Label:return r.lblName+":\n";default:throw t.oops()}}}(e)}n.Stmt=u;class p{constructor(e,n,r){this.index=e,this.def=n,this.info=r,this.isarg=!1,this.iscap=!1,this._isLocal=!1,this._isGlobal=!1,this._debugType="?",this.isUserVariable=!1,this.bitSize=0,n&&(t.isInPxtModules(n)||(this.isUserVariable=!0),r&&t.setCellProps(this))}getName(){return t.getDeclName(this.def)}getDebugInfo(){return{name:this.getName(),type:this._debugType,index:this.index}}toString(){let e="";return this.def&&(e+=this.getName()||"?"),this.isarg&&(e="ARG "+e),"["+e+"]"}uniqueName(){return this.isarg?"arg"+this.index:this.getName().replace(/[^\w]/g,"_")+"___"+t.getNodeId(this.def)}isLocal(){return this._isLocal}isGlobal(){return this._isGlobal}loadCore(){return h(r.CellRef,null,this)}load(){let e=this.loadCore();return t.target.isNative&&!t.isStackMachine()&&0!=this.bitSize?6==this.bitSize?v("pxt::fromUInt",[e]):v("pxt::fromInt",[e]):this.isByRefLocal()?v("pxtrt::ldlocRef",[e]):e}isByRefLocal(){return this.isLocal()&&this.info.captured&&this.info.written}storeDirect(e){return h(r.Store,[this.loadCore(),e])}storeByRef(e){if(this.isByRefLocal())return v("pxtrt::stlocRef",[this.loadCore(),e]);if(t.target.isNative&&!t.isStackMachine()&&0!=this.bitSize){let t=6==this.bitSize?"pxt::toUInt":"pxt::toInt";return this.storeDirect(v(t,[e],1))}return this.storeDirect(e)}get isTemporary(){return!1}}n.Cell=p;class f extends p{constructor(e,t){super(e,null,null),this.index=e,this.owningProc=t,this.uid=f.unnamedCellCounter++}getName(){return"unnamed"+this.uid}uniqueName(){return this.getName()+"___U"+this.index}isByRefLocal(){return!1}get isTemporary(){return!0}}function _(e){const t=()=>{if(!e.args)return 0;let t=0;for(let n of e.args)t+=_(n);return e.mask&&e.mask.conversions&&(t+=4*e.mask.conversions.length),t};switch(e.exprKind){case r.NumberLiteral:return 2;case r.PointerLiteral:return 6;case r.RuntimeCall:return t()+2+2+4;case r.CellRef:return 2;case r.FieldAccess:return t()+(e.data.needsCheck?4:0)+2;case r.ProcCall:case r.SharedRef:case r.SharedDef:case r.Store:case r.Sequence:case r.JmpValue:case r.Nop:case r.InstanceOf:return 1e6;default:throw i.oops()}}function m(e){switch((e=l.clone(e)).exprKind){case r.PointerLiteral:case r.NumberLiteral:return e;case r.RuntimeCall:for(let t=0;t<e.args.length;++t)e.args[t]=m(e.args[t]);return e;case r.CellRef:const t=e.data;return t.repl?(t.replUses++,t.repl):e;case r.FieldAccess:return e.args[0]=m(e.args[0]),e;default:throw i.oops()}}f.unnamedCellCounter=0,n.UnnamedCell=f;function g(e,t){return new u(e,t)}function h(e,t,n){return new l(e,t,n)}function y(e,t){let n=h(r.PointerLiteral,null,e);return n.jsInfo=t,n}function v(e,t,n=0){let i=h(r.RuntimeCall,t,e);return n&&(i.mask={refMask:n}),i}function b(e,a=!1,o=!1){let s=!!a&&e.some((e=>e.canUpdateCells())),c=[];for(let t of i.reversed(e))t.isStateless()||(t.exprKind!=r.CellRef||s)&&(t.canUpdateCells()&&(s=!0),c.push(t));c.reverse(),t.isStackMachine()&&!o&&(c=[]);let l=[],u=e.map((e=>{if(c.indexOf(e)>=0){let t=e,i=e;return e.exprKind==r.SharedDef?(e.args[0].totalUses++,t=n.op(r.SharedRef,[e.args[0]])):(t=n.op(r.SharedRef,[e]),i=n.op(r.SharedDef,[e]),e.totalUses=2,e.currUses=0),l.push(i),t}return e}));return{precomp:l,flattened:u}}n.Procedure=class extends c{constructor(){super(...arguments),this.numArgs=0,this.info=null,this.seqNo=-1,this.isRoot=!1,this.locals=[],this.captured=[],this.args=[],this.parent=null,this.debugInfo=null,this.fillDebugInfo=null,this.classInfo=null,this.perfCounterName=null,this.perfCounterNo=0,this.body=[],this.lblNo=0,this.action=null,this.cachedJS=null,this.usingCtx=null}reset(){this.body=[],this.lblNo=0,this.locals=[],this.captured=[],this.args=[]}isGetter(){return this.action&&this.action.kind==e.SyntaxKind.GetAccessor}vtLabel(){return this.label()+(t.isStackMachine()?"":"_args")}label(){return t.getFunctionLabel(this.action)}toString(){return`\nPROC ${t.getDeclName(this.action)}\n${this.body.map((e=>e.toString())).join("")}\n`}emit(e){this.body.push(e)}emitExpr(e){this.emit(g(a.Expr,e))}mkLabel(e){let t=g(a.Label,null);return t.lblName="."+e+"_"+this.lblNo+++"_"+this.seqNo,t.lbl=t,t}emitLbl(e){this.emit(e)}emitLblDirect(e){let t=g(a.Label,null);t.lblName=e,t.lbl=t,this.emit(t)}getFullName(){let n=t.getDeclName(this.action);if(this.action){let t=e.pxtc.nodeLocationInfo(this.action);n=t.fileName.replace("pxt_modules/","")+"("+(t.line+1)+","+(t.column+1)+"): "+n}return n}getName(){return(this.action&&this.action.name?this.action.name.text:null)||"inline"}mkLocal(e,t){let n=new p(this.locals.length,e,t);return this.locals.push(n),n}mkLocalUnnamed(){let e=new f(this.locals.length,this);return this.locals.push(e),e}localIndex(e,t=!1){return this.captured.filter((t=>t.def==e))[0]||this.locals.filter((t=>t.def==e))[0]||(t?null:this.args.filter((t=>t.def==e))[0])}stackEmpty(){this.emit(g(a.StackEmpty,null))}emitJmpZ(e,t){this.emitJmp(e,t,o.IfZero)}emitJmp(e,t,n=o.Always,i=null){let s=g(a.Jmp,t);s.jmpMode=n,i&&i.exprKind==r.NumberLiteral&&(i=null),s.terminateExpr=i,"string"==typeof e?s.lblName=e:(s.lbl=e,s.lblName=s.lbl.lblName),this.emit(s)}inlineSelf(e){const{precomp:t,flattened:n}=b(e,!1,!0);i.assert(n.length==this.args.length),this.args.map(((e,t)=>{e.repl=n[t],e.replUses=0}));const a=m(this.inlineBody);return this.args.forEach(((e,t)=>{e.repl.exprKind==r.SharedRef&&(e.repl.args[0].prevTotalUses||(e.repl.args[0].prevTotalUses=e.repl.args[0].totalUses),e.repl.args[0].totalUses+=e.replUses-1),e.repl=null,e.replUses=0})),t.length?(t.push(a),h(r.Sequence,t)):a}resolve(){let e=(e,t)=>{if(e.args)for(let n=0;n<e.args.length;++n)e.args[n]=t(e.args[n])},a=t=>{switch(t.exprKind){case r.SharedDef:throw i.oops();case r.SharedRef:let e=t.args[0];if(e.totalUses)return e.totalUses--,t;{e.totalUses=-1,e.currUses=0,e.irCurrUses=0;let n=l.clone(t);return n.exprKind=r.SharedDef,n.args[0]=a(n.args[0]),n}}return e(t,a),t},o=t=>{if(t.exprKind==r.SharedRef)return t;switch(e(t,o),t.exprKind){case r.Sequence:t.args=t.args.filter(((e,n)=>n==t.args.length-1||!e.isPure()||(e.exprKind==r.SharedRef&&e.args[0].totalUses>0&&e.args[0].totalUses--,!1)))}return t},s=t=>{switch(t.exprKind){case r.SharedDef:let e=t.args[0];if(i.assert(e.totalUses<0,"arg.totalUses < 0"),i.assert(0===e.currUses,"arg.currUses === 0"),-1==e.totalUses)return s(e);e.totalUses=1;break;case r.SharedRef:return i.assert(t.args[0].totalUses>0,"e.args[0].totalUses > 0"),t.args[0].totalUses++,t;case r.PointerLiteral:const n=t.ptrlabel();n&&(n.lblNumUses||(n.lblNumUses=0),n.lblNumUses++)}return e(t,s),t},c=t=>{switch(t.exprKind){case r.SharedDef:e(t,c);case r.SharedRef:let n=t.args[0];return i.assert(n.totalUses>0,"arg.totalUses > 0"),1==n.totalUses?(i.assert(t.exprKind==r.SharedDef),n):(n.irCurrUses++,t);default:return e(t,c),t}};this.body=this.body.filter((e=>!e.expr||(e.expr=o(a(e.expr)),e.stmtKind!=n.SK.Expr||!e.expr.isPure())));let u=i.toDictionary(this.body.filter((e=>e.stmtKind==n.SK.Label)),(e=>e.lblName));for(let e=0;e<this.body.length;++e)this.body[e].stmtNo=e;for(let e of this.body)switch(e.expr&&(e.expr=s(e.expr)),e.stmtKind){case n.SK.Expr:break;case n.SK.Jmp:e.lbl=i.lookup(u,e.lblName),e.lbl||t.oops("missing label: "+e.lblName),e.lbl.lblNumUses?e.lbl.lblNumUses++:e.lbl.lblNumUses=1;break;case n.SK.StackEmpty:case n.SK.Label:case n.SK.Breakpoint:case n.SK.Comment:break;default:t.oops()}let d=[],p=null,f=!t.target.debugMode,m=null;for(let e of this.body)e.expr&&(e.expr=o(c(e.expr))),p&&p.lbl==e&&p.stmtKind==n.SK.Jmp&&e.stmtKind==n.SK.Label&&p.jmpMode==n.JmpMode.Always&&1==e.lblNumUses&&(e.lblNumUses=n.lblNumUsesJmpNext),p=e,e.stmtKind==n.SK.Breakpoint?d[e.breakpointInfo.id]=e.breakpointInfo:f&&(e.stmtKind==n.SK.Jmp?e.expr&&(m?f=!1:m=e.expr):e.stmtKind==n.SK.StackEmpty||(e.stmtKind==n.SK.Label?e.lblNumUses!=n.lblNumUsesJmpNext&&(f=!1):f=!1));if(f&&m){_(m)<=4*this.args.length+4+2+(t.target.isNative?4:30)&&(this.inlineBody=m)}pxt.options.debug&&pxt.debug(this.toString())}},n.iterExpr=function e(t,n){if(n(t),t.args)for(let r of t.args)e(r,n)},n.stmt=g,n.comment=function(e){return g(a.Comment,y(e,e))},n.op=h,n.numlit=function(e){return h(r.NumberLiteral,null,e)},n.shared=function(e){switch(e.exprKind){case r.SharedRef:e=e.args[0];break;case r.NumberLiteral:return e}return h(r.SharedRef,[e])},n.ptrlit=y,n.rtcall=v,n.rtcallMask=function(e,t,n,r){i.startsWith(e,"@nomask@")&&(e=e.slice(8),t=0);let a=v(e,r,t);return a.callingConvention=n,a},n.flattenArgs=b}(t.ir||(t.ir={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){class n{constructor(e,t){this.wave=e,this.id=t,this.flags=0,this.resetAll()}refresh(){this.flags&=-9,!this.proc||this.usedActions||N(this.proc.action)?this.proc&&!this.proc.cachedJS?this.resetEmit():this.usedNodes&&(this.flags|=32):this.resetEmit(),this.classInfo&&this.classInfo.reset()}resetEmit(){this.flags&=-41,this.proc&&this.proc.classInfo&&this.proc.classInfo.ctor==this.proc&&(this.proc.classInfo.ctor=null),this.functionInfo=null,this.variableInfo=null,this.classInfo=null,this.callInfo=null,this.proc=null,this.cell=null,this.exprInfo=null,this.usedNodes=null,this.usedActions=null}resetTSC(){this.flags&=16,this.typeCache=null,this.symbolCache=null,this.commentAttrs=null,this.valueOverride=null,this.declCache=void 0,this.fullName=null,this.constantFolded=void 0}resetAll(){this.resetTSC(),this.resetEmit()}}let r;function i(e){return e<<2|2}t.PxtNode=n,function(e){e[e.Enum=0]="Enum",e[e.Number=1]="Number",e[e.String=2]="String",e[e.Boolean=3]="Boolean",e[e.Unsupported=4]="Unsupported"}(r||(r={})),t.taggedUndefined=0,t.taggedNull=i(1),t.taggedFalse=i(2),t.taggedNaN=i(3),t.taggedTrue=i(16),t.thumbArithmeticInstr={adds:!0,subs:!0,muls:!0,ands:!0,orrs:!0,eors:!0,lsls:!0,asrs:!0,lsrs:!0},t.numberArithmeticInstr={div:!0,mod:!0,le:!0,lt:!0,ge:!0,gt:!0,eq:!0,neq:!0};const a={"Array_::getAt":{name:"_pxt_array_get",argsFmt:["T","T","T"],value:0},"Array_::setAt":{name:"_pxt_array_set",argsFmt:["T","T","T","T"],value:0},"BufferMethods::getByte":{name:"_pxt_buffer_get",argsFmt:["T","T","T"],value:0},"BufferMethods::setByte":{name:"_pxt_buffer_set",argsFmt:["T","T","T","I"],value:0},"pxtrt::mapGetGeneric":{name:"_pxt_map_get",argsFmt:["T","T","S"],value:0},"pxtrt::mapSetGeneric":{name:"_pxt_map_set",argsFmt:["T","T","S","T"],value:0}};let o=t.ir.EK;t.SK=e.SyntaxKind,t.numReservedGlobals=1;let s=0,c=1;function l(n){if(n.pxt)return!!(16&n.pxt.flags);const r=e.getSourceFileOfNode(n);return!!r&&t.isPxtModulesFilename(r.fileName)}function u(e){if(e.pxt){const n=e.pxt;return n.wave!=c&&(n.wave=c,t.compileOptions&&t.compileOptions.skipPxtModulesTSC&&16&n.flags?t.compileOptions.skipPxtModulesEmit?n.refresh():n.resetEmit():n.resetAll()),n}{const t=new n(c,++s);return l(e)&&(t.flags|=16),e.pxt=t,t}}function d(e){return u(e).id}function p(t){return t?e.SyntaxKind[t.kind]:"<null>"}function f(e,t,n=!1){let r=new Error(t);if(r.ksEmitterUserError=!0,r.ksErrorCode=e,n&&$)return M||(M=t,B=e),r;throw r}function _(){return t.target.isNative&&t.target.nativeType==t.NATIVE_TYPE_VM}function m(){return t.target.isNative&&t.target.nativeType!=t.NATIVE_TYPE_VM}function g(){return t.target.isNative&&t.target.nativeType==t.NATIVE_TYPE_THUMB}function h(e){return m()?t.ir.rtcall("pxt::fromInt",[e]):e}function y(e){return m()?t.ir.rtcall("pxt::fromBool",[e]):e}function v(e){switch(e){case 0:return t.target.shortPointers?2:4;case 1:return 1;case 3:return 2;case 5:return 4;case 2:return 1;case 4:return 2;case 6:return 4;default:throw t.oops()}}function b(e){switch(e){case 1:case 3:case 5:return!0;case 2:case 4:case 6:return!1;default:throw t.oops()}}function x(e){switch(e.kind){case t.SK.TemplateHead:case t.SK.TemplateMiddle:case t.SK.TemplateTail:case t.SK.StringLiteral:case t.SK.NoSubstitutionTemplateLiteral:return!0;default:return!1}}function k(e){return e&&e.modifiers&&e.modifiers.some((e=>e.kind==t.SK.StaticKeyword))}function S(e){return e.modifiers&&e.modifiers.some((e=>e.kind==t.SK.ReadonlyKeyword))}function T(e,t){return e.explicitDefaults?e.explicitDefaults.indexOf(t)<0?null:e.paramDefl[t]:null}function C(e){if(!e)return null;switch(e.kind){case t.SK.MethodDeclaration:return"";case t.SK.Constructor:return"new/";case t.SK.GetAccessor:return"get/";case t.SK.SetAccessor:return"set/";default:return null}}function E(e){return C(e)+q(e)}function D(e){return null!=C(e)}function A(e){return e?D(e)?e:A(e.parent):null}function N(e){let n=e,r=!1;for(;;)switch(n=n.parent,n||f(9229,U("cannot determine parent of {0}",p(e))),n.kind){case t.SK.MethodDeclaration:case t.SK.Constructor:case t.SK.GetAccessor:case t.SK.SetAccessor:case t.SK.FunctionDeclaration:case t.SK.ArrowFunction:case t.SK.FunctionExpression:return n;case t.SK.WhileStatement:case t.SK.DoStatement:case t.SK.ForInStatement:case t.SK.ForOfStatement:case t.SK.ForStatement:r=!0;break;case t.SK.SourceFile:return r?R:null}}function w(e){return"objectFlags"in e}function I(e){return!!e&&(e.kind==t.SK.VariableDeclaration||e.kind==t.SK.BindingElement&&I(e.parent.parent))}function P(e){return!!e&&(I(e)&&!N(e)||e.kind==t.SK.PropertyDeclaration&&k(e))}function O(e){return!!e&&(e.kind==t.SK.Parameter||e.kind==t.SK.BindingElement&&O(e.parent.parent))}t.isInPxtModules=l,t.pxtInfo=u,t.getNodeId=d,t.stringKind=p,t.isStackMachine=_,t.needsNumberConversions=m,t.isThumb=g,t.sizeOfBitSize=v,t.isBitSizeSigned=b,t.setCellProps=function(n){var r;if(n._isLocal=I(r=n.def)&&!P(r)||O(n.def),n._isGlobal=P(n.def),!n.def.isThisParameter){let r=ee(n.def);r.flags&e.TypeFlags.Void&&t.oops("void-typed variable, "+n.toString()),n.bitSize=function(e){if(!e||!e.type)return 0;if(!de(ee(e)))return 0;if(e.type.kind!=t.SK.TypeReference)return 0;switch(e.type.typeName.getText()){case"int8":return 1;case"int16":return 3;case"int32":return 5;case"uint8":return 2;case"uint16":return 4;case"uint32":return 6;default:return 0}}(n.def),0!=n.bitSize?n._debugType=(b(n.bitSize)?"int":"uint")+8*v(n.bitSize):ue(r)?n._debugType="string":r.flags&e.TypeFlags.NumberLike&&(n._debugType="number")}n.isLocal()&&0!=n.bitSize&&(n.bitSize=0,f(9256,U("bit sizes are not supported for locals and parameters")))},t.isStatic=k,t.isReadOnly=S,t.getExplicitDefault=T,t.isObjectType=w;class F{constructor(e,t){this.id=e,this.decl=t,this.baseClassInfo=null,this.allfields=[],this.methods={},this.attrs=J(t),this.reset()}reset(){this.vtable=null,this.itable=null}get isUsed(){return!!(8&u(this.decl).flags)}allMethods(){const e=[];for(let t of Object.keys(this.methods))for(let n of this.methods[t])e.push(n);return e}usedMethods(){const e=[];for(let t of Object.keys(this.methods))for(let n of this.methods[t]){8&u(n).flags&&e.push(n)}return e}}t.ClassInfo=F;let L,R,M,U=t.assembler.lf,B=0,$=0;function j(e,n){const r=u(n);return null==r.fullName&&(r.fullName=t.getFullName(e,n.symbol)),r.fullName}function K(n){n.kind==t.SK.VariableDeclaration&&(n=n.parent.parent);let r=t=>{const n=e.getSourceFileOfNode(t);if(!n)return"";const r=e.getLeadingCommentRangesOfNode(t,n);if(!r)return"";return r.map((e=>n.text.slice(e.pos,e.end))).join("\n")};return n.symbol&&n.symbol.declarations&&n.symbol.declarations.length>1?n.symbol.declarations.map(r).join("\n"):r(n)}function z(e){let n="";for(let t of e.declarations)n+=K(t);return t.parseCommentString(n)}function J(e){const n=e?u(e):null;if(!n||2&n.flags)return t.parseCommentString("");if(n.commentAttrs)return n.commentAttrs;let r=t.parseCommentString(K(e));return r._name=q(e),n.commentAttrs=r,r}function q(e){return e.name&&e.name.kind==t.SK.Identifier?e.name.text:"???"}function V(t){if(w(t)&&t.objectFlags&e.ObjectFlags.Reference){let e=t;if(e.typeArguments&&e.typeArguments.length)return e.target}return null}function H(t){return!!w(t)&&(t.objectFlags&e.ObjectFlags.Reference&&t.symbol&&"Array"==t.symbol.name)}function G(t){return!!w(t)&&(!!(t.objectFlags&e.ObjectFlags.Interface)||!!(t.objectFlags&e.ObjectFlags.Anonymous))}function W(t){return!!t.isThisType||!!w(t)&&!!(t.objectFlags&e.ObjectFlags.Class||t.symbol&&t.symbol.flags&e.SymbolFlags.Class)}function Q(e){let t=V(e);return W(t||e)}function Y(t,n=-1){return H(t)?t.typeArguments[0]:L.getIndexTypeOfType(t,e.IndexKind.Number)}function X(e){return e}function Z(e){return null===e?t.taggedNull:void 0===e?t.taggedUndefined:!1===e?t.taggedFalse:!0===e?t.taggedTrue:isNaN(e)?t.taggedNaN:null}function ee(t){let n;const r=u(t);if(r.typeCache)return r.typeCache;if(e.isExpression(t)&&(n=L.getContextualType(t)),!n)try{n=L.getTypeAtLocation(t)}catch(e){f(9203,U("Unknown type for expression"))}return n?(r.typeCache=n,n):n}function te(t){if(!(t.flags&e.TypeFlags.Union))return r.Unsupported;let n,i=!0;return t.types.forEach((t=>{if(void 0===n)t.flags&e.TypeFlags.NumberLike?n=r.Number:t.flags&e.TypeFlags.BooleanLike?n=r.Boolean:t.flags&e.TypeFlags.StringLike?n=r.String:t.flags&e.TypeFlags.EnumLike&&(n=r.Enum);else switch(n){case r.Number:i=i&&!!(t.flags&e.TypeFlags.NumberLike);break;case r.Boolean:i=i&&!!(t.flags&e.TypeFlags.BooleanLike);break;case r.String:i=i&&!!(t.flags&e.TypeFlags.StringLike);break;case r.Enum:i=i&&!!(t.flags&e.TypeFlags.EnumLike)}})),i?n:r.Unsupported}function ne(t){let n=L.getSignatureFromDeclaration(t);return!(L.getReturnTypeOfSignature(n).flags&e.TypeFlags.Void)}function re(e){return!(!e||!e.name)}function ie(e){if(!e)return"";switch(e.kind){case t.SK.ModuleBlock:return ie(e.parent);case t.SK.ClassDeclaration:case t.SK.ModuleDeclaration:return ie(e.parent)+e.name.text+".";default:return""}}function ae(e){let n=re(e)?e.name.text:null;if(!n){if(e.kind!=t.SK.Constructor){for(let t=e.parent;t;t=t.parent)if(re(t))return ae(t)+".inline";return"inline"}n="constructor"}return ie(e.parent)+n}function oe(e){return ae(e).replace(/[^\w]+/g,"_")}function se(e){return oe(e)+"__P"+d(e)}t.getNodeFullName=j,t.getComments=K,t.parseCommentsOnSymbol=z,t.parseComments=J,t.getName=q,t.checkType=X,t.taggedSpecial=Z,t.getDeclName=ae,t.getFunctionLabel=se;class ce{constructor(e){this.decl=e,this.capturedVars=[]}get isUsed(){return!!(8&u(this.decl).flags)}}function le(e,t,n){return!!(e.flags&t)||te(e)===n}function ue(t){return le(t,e.TypeFlags.String|e.TypeFlags.StringLiteral,r.String)}function de(t){return le(t,e.TypeFlags.Number|e.TypeFlags.NumberLiteral,r.Number)}t.FunctionAddInfo=ce,t.compileBinary=function(n,r,i,s){t.compilerHooks.preBinary&&t.compilerHooks.preBinary(n,r,i),t.target=r.target,t.compileOptions=r,t.target.debugMode=!!r.breakpoints;const b=e.createDiagnosticCollection();L=n.getTypeChecker();let C=t.U.cpuUs(),w=[],K=[],V={},X={},te=null,re=null,ie=!1,le=[];if(c++,r.target.isNative){if(!r.extinfo||!r.extinfo.hexinfo)return{diagnostics:[{file:n.getSourceFiles()[0],start:0,length:0,category:t.DiagnosticCategory.Error,code:9043,messageText:U("The hex file is not available, please connect to internet and try again.")}],emittedFiles:[],emitSkipped:!0};let e=r.extinfo,i=r.target;if(e&&e.disabledDeps){const t=(r.otherMultiVariants||[]).find((e=>e.extinfo&&!e.extinfo.disabledDeps));t&&(pxt.debug(`using alternative extinfo (due to ${e.disabledDeps})`),e=t.extinfo,i=t.target)}t.hexfile.setupFor(i,e||t.emptyExtInfo()),t.hexfile.setupInlineAssembly(r)}let me,ge=new pe;function he(){ge.reset(),me=null,i.breakpoints=[{id:0,isDebuggerStmt:!1,fileName:"bogus",start:0,length:0,line:0,column:0}],i.procCallLocations=[]}ge.res=i,ge.options=r,ge.target=r.target,r.computeUsedSymbols&&(i.usedSymbols={},i.usedArguments={});let ye=[];if(!r.forceEmit||0==i.diagnostics.length){let e=n.getSourceFiles().slice();const t=e.find((e=>e.fileName===pxt.MAIN_TS));t&&(e=e.filter((e=>e.fileName!==pxt.MAIN_TS)),e.push(t));const r=e.find((e=>e.fileName===pxt.TUTORIAL_CODE_STOP));r&&(e=e.filter((e=>e.fileName!==pxt.TUTORIAL_CODE_STOP)),e.push(r)),e.forEach((e=>{e.statements.forEach((e=>{ye.push(e)}))}))}let ve=n.getSourceFiles().filter((e=>t.Util.endsWith(e.fileName,s)))[0],be={kind:t.SK.FunctionDeclaration,parameters:[],name:{text:"<main>",pos:0,end:0},body:{kind:t.SK.Block,statements:ye},parent:ve,pos:0,end:0};R=be;const xe=u(be);for(xe.flags|=3,rt(be),w=[],he(),ie=!0,xn(be);kt(),!Ue(););!function(){let e=ge.globals.slice(0);e.forEach(((e,t)=>e.index=t));const n=e=>0==e?10:v(e);e.sort(((e,t)=>n(e.bitSize)-n(t.bitSize)||e.index-t.index));let r=4*t.numReservedGlobals,i=0;for(let t of e){const e=_()?0:t.bitSize;let n=v(e);for(;r&n-1;)r++;i||0!=e||(i=r),t.index=r,r+=n}ge.globalsWords=r+3>>2,ge.nonPtrGlobals=i?i>>2:ge.globalsWords}(),ie=!1,function(){for(let e of ge.usedClassInfos)Be(e);let e=Object.keys(ge.ifaceMemberMap);e.sort(t.U.strcmp),e.unshift(""),ge.emitString(""),ge.ifaceMembers=e,ge.ifaceMemberMap={};let n=0;for(let t of e)ge.ifaceMemberMap[t]=n++;for(let e of ge.usedClassInfos)for(let t of e.itable)t.idx=Oe(t.name);for(let e of ge.usedClassInfos)e.lastSubtypeNo=void 0,e.classNo=void 0;let r=pxt.BuiltInType.User0;const i=e=>{t.U.assert(!e.classNo),e.classNo=r++;for(let t of e.derivedClasses)t.isUsed&&i(t);e.lastSubtypeNo=r-1};for(let e of ge.usedClassInfos){let t=e;for(;t.baseClassInfo;)t=t.baseClassInfo;t.classNo||i(t)}}();let ke=t.U.cpuUs();i.times.pass0=ke-C;let Se=b.getDiagnostics();he(),ie=!1,ge.finalPass=!0,kn(be),t.U.assert(0==w.length),i.configData=[];for(let e of Object.keys(X))X["!"+e]||i.configData.push({name:e.replace(/^\!/,""),key:X[e].key,value:X[e].value});i.configData.sort(((e,t)=>e.key-t.key));let Te=t.U.cpuUs();if(i.times.pass1=Te-ke,yn(be,(function(){if(r.noEmit)return;ge.writeFile=(e,t)=>{i.outfiles[e]=t};for(let e of ge.procs)e.cachedJS&&!e.inlineBody||e.resolve();t.target.isNative&&(ge.procs=ge.procs.filter((e=>!(e.inlineBody&&!e.info.usedAsIface&&!e.info.usedAsValue))));r.target.isNative?(r.extinfo.yotta&&ge.writeFile("yotta.json",JSON.stringify(r.extinfo.yotta,null,2)),r.extinfo.platformio&&ge.writeFile("platformio.json",JSON.stringify(r.extinfo.platformio,null,2)),r.target.nativeType==t.NATIVE_TYPE_VM?t.vmEmit(ge,r):t.processorEmit(ge,r,i)):t.jsEmit(ge)})),i.times.passFinal=t.U.cpuUs()-Te,r.ast){let e=t.U.cpuUs();t.annotate(n,s,t.target),i.times.passAnnotate=t.U.cpuUs()-e}return t.compileOptions=null,0==Se.length&&(Se=b.getDiagnostics()),t.compilerHooks.postBinary&&t.compilerHooks.postBinary(n,r,i),{diagnostics:Se,emittedFiles:void 0,emitSkipped:!!r.noEmit};function Ce(t,n,r,i,a,o,s){b.add(e.createDiagnosticForNode(n,{code:r,message:i,key:i.replace(/^[a-zA-Z]+/g,"_"),category:t},a,o,s))}function Ee(e,n,r,i,a,o){Ce(t.DiagnosticCategory.Error,e,n,r,i,a,o)}function De(t,n,r=9202){if(n)return f(r,n);t||f(r,U("Sorry, this language feature is not supported"));let i=p(t),a=!1,o=null;switch(t.kind){case e.SyntaxKind.ForInStatement:i=U("for in loops");break;case e.SyntaxKind.ForOfStatement:i=U("for of loops"),a=!0;break;case e.SyntaxKind.PropertyAccessExpression:i=U("property access");break;case e.SyntaxKind.DeleteExpression:i=U("delete");break;case e.SyntaxKind.GetAccessor:i=U("get accessor method"),a=!0;break;case e.SyntaxKind.SetAccessor:i=U("set accessor method"),a=!0;break;case e.SyntaxKind.TaggedTemplateExpression:i=U("tagged templates");break;case e.SyntaxKind.SpreadElement:i=U("spread");break;case e.SyntaxKind.TryStatement:case e.SyntaxKind.CatchClause:case e.SyntaxKind.FinallyKeyword:case e.SyntaxKind.ThrowStatement:i=U("throwing and catching exceptions");break;case e.SyntaxKind.ClassExpression:i=U("class expressions"),o=U("declare a class as class C {} not let C = class {}")}let s="";return s=a?U("{0} not currently supported",i):U("{0} not supported",e.SyntaxKind[t.kind]),o&&(s+=" - "+o),f(r,s)}function Ae(e){return d(e)+""}function Ne(e){const t=u(e);return t.functionInfo||(t.functionInfo=new ce(e)),t.functionInfo}function we(e){const t=u(e);return t.variableInfo||(t.variableInfo={}),t.variableInfo}function Ie(e,t=!1){let n=we(e);t&&(n.written=!0);let r=N(e);if(null==r||r==me.action);else{let t=me.action;for(;t&&t!=r;){let n=Ne(t);n.capturedVars.indexOf(e)<0&&n.capturedVars.push(e),t=N(t)}n.captured=!0}}function Pe(e){const t=e(ge);return ie&&ge.recordAction(re,e),t}function Oe(e,n=!1){return Pe((r=>{n&&(t.U.lookup(r.explicitlyUsedIfaceMembers,e)||(t.U.assert(!r.finalPass),r.explicitlyUsedIfaceMembers[e]=!0));let i=t.U.lookup(r.ifaceMemberMap,e);return null!=i||(t.U.assert(!r.finalPass),i=r.ifaceMemberMap[e]=-1,r.emitString(e)),i}))}function Fe(t){t.flags&e.TypeFlags.Void&&f(9203,U("void-typed variables not supported"))}function Le(e){const n=u(e);Fe(ee(e)),n.cell||(n.cell=new t.ir.Cell(null,e,we(e))),ge.globals.indexOf(n.cell)<0&&ge.globals.push(n.cell)}function Re(e){if(P(e)){rt(e);const t=u(e);return t.cell||Le(e),t.cell}{let t=me.localIndex(e);return t||(ge.finalPass?f(9204,U("cannot locate identifer")):t=me.mkLocal(e,we(e))),t}}function Me(e){return e.kind==t.SK.MethodDeclaration&&0==e.parameters.length&&"toString"==q(e)}function Ue(){ie=!1;const e=ge.usedClassInfos.length;for(let e of ge.usedClassInfos){for(let r of e.allMethods()){const e=u(r),i=Ne(r);8&e.flags?i.virtualParent&&it(i.virtualParent.decl):(i.virtualParent&&i.virtualParent.isUsed||Me(r)||(n=q(r),null!=t.U.lookup(ge.explicitlyUsedIfaceMembers,n)))&&it(r)}const r=ht(e.decl);r&&it(r)}var n;return ie=!0,0==w.length&&e==ge.usedClassInfos.length}function Be(e){if(t.assert(e.isUsed,"inf.isUsed"),e.vtable)return e.vtable;let n=e.baseClassInfo?Be(e.baseClassInfo).slice(0):[];e.derivedClasses=[],e.baseClassInfo&&e.baseClassInfo.derivedClasses.push(e);for(let r of e.usedMethods()){ge.numMethods++;let i=Ne(r);const a=J(r);if(Me(r)&&!a.shim&&(e.toStringMethod=mt(r),e.toStringMethod.info.usedAsIface=!0),i.virtualParent){ge.numVirtMethods++;let e=E(r),a=!1,o=mt(r);t.U.assert(!!o);for(let t=0;t<n.length;++t)E(n[t].action)==e&&(n[t]=o,i.virtualIndex=t,a=!0);a||(i.virtualIndex=n.length,n.push(o))}}e.vtable=n,e.itable=[];const r={};for(let t of e.allfields){let n=q(t),i=Lt(e,t,!1);r[n]=!0,e.itable.push({name:n,info:(i.idx+1)*(_()?1:4),idx:Oe(n),proc:null})}for(let n=e;n;n=n.baseClassInfo)for(let r of n.usedMethods()){const n=q(r);if(J(r).shim)continue;const i=mt(r),a=e.itable.find((e=>e.name==n)),o=r.kind==t.SK.SetAccessor,s=r.kind==t.SK.GetAccessor;a?(o&&!a.setProc?a.setProc=i:s&&!a.proc&&(a.proc=i),a.info=0):e.itable.push({name:n,info:0,idx:Oe(n),proc:o?null:i,setProc:o?i:null}),i.info.usedAsIface=!0}return e.vtable}function $e(e){if(32&e.flags||16&e.flags&&t.compileOptions.skipPxtModulesEmit)throw i.needsFullRecompile=!0,f(9200,U("full recompile required"))}function je(e,n=null){n||(n=e.symbol.valueDeclaration);const r=u(n);if(!r.classInfo){const e=oe(n)+"__C"+d(n),i=new F(e,n);r.classInfo=i,i.attrs.autoCreate&&(V[i.attrs.autoCreate]=!0),i.baseClassInfo=function(e){if(e.heritageClauses)for(let n of e.heritageClauses)switch(n.token){case t.SK.ExtendsKeyword:if(!n.types||1!=n.types.length)throw f(9228,U("invalid extends clause"));let r=ee(n.types[0]);if(r&&W(r))return L.getTypeAtLocation(e),je(r);throw f(9228,U("cannot inherit from this type"));case t.SK.ImplementsKeyword:break;default:throw f(9228,U("invalid heritage clause"))}return null}(n);const a=i.baseClassInfo?t.U.toDictionary(i.baseClassInfo.allfields,(e=>q(e))):{},o=(e,t=i.baseClassInfo)=>t?t.methods[e]||o(e,t.baseClassInfo):null;for(let e of n.members)if(e.kind==t.SK.PropertyDeclaration){let n=e;k(n)||i.allfields.push(n);const r=q(n);(o(r)||t.U.lookup(a,r))&&Ee(n,9279,U("redefinition of '{0}' as field",r))}else if(e.kind==t.SK.Constructor)for(let t of e.parameters)fe(t)&&i.allfields.push(t);else if(D(e)){let n=Ne(e);n.parentClassInfo=i,n.isUsed&&yt(i);const r=q(e);i.methods.hasOwnProperty(r)||(i.methods[r]=[]),i.methods[r].push(e);const o=t.U.lookup(a,r);if(o){const e=u(o);64&e.flags||(e.flags|=64,8&e.flags&&Oe(r,!0),$e(e))}}i.baseClassInfo&&(i.allfields=i.baseClassInfo.allfields.concat(i.allfields),function(e){for(let n of e.allMethods()){let r=null;const i=E(n),a=q(n);for(let t=e.baseClassInfo;t;t=t.baseClassInfo)if(t.methods.hasOwnProperty(a))for(let e of t.methods[a])E(e)==i&&(r=e);if(r){let e=Ne(n),i=Ne(r);r.parameters.length!=n.parameters.length&&Ee(n,9255,U("the overriding method is currently required to have the same number of arguments as the base one")),e.virtualParent=i,i.virtualParent||($e(u(r)),i.virtualParent=i),t.assert(i.virtualParent==i,"pinf.virtualParent == pinf")}}}(i))}return r.classInfo}function Ke(e){if(!e)return!1;if(x(e))return!1;switch(e.kind){case t.SK.ArrayLiteralExpression:return e.elements.some(Ke);default:return null==zt(e)}}function ze(e){const t=Kt(e);if(t)return Wt(t.val);if(P(e)){if(J(e).shim)return ut(e,e,[])}let n=Re(e);return Ie(e),n.load()}function Je(e){J(e).shim&&f(9207,U("built-in functions cannot be yet used as values; did you forget ()?"));let n=Ne(e);return qe(n),n.location?n.location.load():(t.assert(!ge.finalPass||0==n.capturedVars.length,"!bin.finalPass || info.capturedVars.length == 0"),n.usedAsValue=!0,it(e),xt(e))}function qe(e){void 0===e.usedBeforeDecl?e.usedBeforeDecl=!0:ge.finalPass&&e.usedBeforeDecl&&e.capturedVars.length&&N(e.decl)&&!e.alreadyEmitted&&f(9278,U("function referenced before all variables it uses are defined"))}function Ve(e){const n=st(e),r=Kt(n);if(r)return Wt(r.val);if(n&&(I(n)||O(n)))return ze(n);if(n&&n.kind==t.SK.FunctionDeclaration)return Je(n);if("undefined"==e.text)return Wt(void 0);throw De(e,U("Unknown or undeclared identifier"),9235)}function He(e){let n=A(e);n||f(9208,U("'this' used outside of a method"));let r=Ne(n);return r.thisParameter||t.oops("no this"),ze(r.thisParameter)}function Ge(e){let n;if(""==e)n=t.ir.rtcall("String_::mkEmpty",[]);else{let r=function(e){return Pe((t=>t.emitString(e)))}(e);n=t.ir.ptrlit(r,JSON.stringify(e))}return n.isStringLiteral=!0,n}function We(e){let n=ct(e),r=vn(e);return t.target.isNative||x(e)?Ot(r,n):(r=t.ir.rtcallMask("String_::stringConv",1,1,[r]),Ot(r,!0))}function Qe(e){let n=0,r=(e,t)=>function(e){return x(e)&&""==e.text}(t)?e:(n++,Xt("String_::concat",[Ot(e,!0),We(t)],null)),i=u(We(e.head)).valueOverride;for(let t of e.templateSpans)i=r(i,t.expression),i=r(i,t.literal);return 0==n?Xt("String_::concat",[Ot(i,!0),Ot(t.ir.rtcall("String_::mkEmpty",[]),!1)],null):i}function Ye(e){let n=st(e);const r=Kt(n);if(r)return Wt(r.val);if(n.kind==t.SK.SetAccessor&&(n=Xe(n)),n.kind==t.SK.GetAccessor)return pt(e,e,[],null,n);if(n.kind==t.SK.EnumMember)throw f(9210,U("Cannot compute enum value"));if(n.kind==t.SK.PropertySignature||n.kind==t.SK.PropertyAssignment)return pt(e,e,[],null,n,e.expression);if(n.kind==t.SK.PropertyDeclaration||n.kind==t.SK.Parameter){if(k(n))return ze(n);if(Ze(n))return pt(e,e,[],null,n,e.expression);{let n=function(e){const n=ee(e.expression);if(Q(n)){const r=je(n);let i=e.expression.kind==t.SK.ThisKeyword;return t.target.switches.noThisCheckOpt&&(i=!1),Lt(r,Rt(r,e.name.text),!i)}throw De(e,U("bad field access"),9247)}(e);return t.ir.op(o.FieldAccess,[vn(e.expression)],n)}}if(D(n)||n.kind==t.SK.MethodSignature)throw f(9211,U("cannot use method as lambda; did you forget '()' ?"));if(n.kind==t.SK.FunctionDeclaration)return Je(n);if(I(n))return ze(n);throw De(e,U("Unknown property access for {0}",p(n)),9237)}function Xe(n){const r=e.getDeclarationOfKind(n.symbol,t.SK.GetAccessor);if(null==r)throw f(9281,U("setter currently requires a corresponding getter"));return r}function Ze(e){if(e.kind==t.SK.Parameter||e.kind==t.SK.PropertyDeclaration){const n=u(e);return!!t.target.switches.slowFields||!!(64&n.flags)}return!1}function et(t,n=null){let r=ee(t.expression),i={callingConvention:0,paramDefl:{}},a=null,o=!1;if(!n&&ue(r)?a="String_::charAt":H(r)?a=n?"Array_::setAt":"Array_::getAt":G(r)&&(i=z(r.symbol),a=n?i.indexerSet:i.indexerGet),!a&&r.flags&(e.TypeFlags.Any|e.TypeFlags.StructuredOrTypeVariable)&&(a=n?"pxtrt::mapSetGeneric":"pxtrt::mapGetGeneric",o=!0),a){if(o||Qt(t.argumentExpression)){return Xt(a,[t.expression,t.argumentExpression],i,n?[n]:[])}throw De(t,U("non-numeric indexer on {0}",a),9238)}throw De(t,U("unsupported indexer"),9239)}function tt(n){let i=function(e){return!!P(e)&&(!Ke(e.initializer)||!!J(e).whenUsed)}(n)||function(e){return e.kind==t.SK.FunctionDeclaration&&!N(e)||D(e)}(n)||e.isClassDeclaration(n);return!t.target.switches.noTreeShake&&(!(r.testMode&&i&&!l(n))&&i)}function nt(e){if(!tt(e))return!0;const t=u(e);return ge.finalPass?!!(8&t.flags):t==re}function rt(e){if(!e)return;const t=u(e);t.classInfo?yt(t.classInfo):(r.computeUsedSymbols&&e.symbol&&(i.usedSymbols[j(L,e)]=null),_()&&D(e)&&Oe(q(e),!0),at(e),8&t.flags||(t.flags|=8,tt(e)&&w.push(e)))}function it(e){rt(e)}function at(e){ie&&(re?re.usedNodes[Ae(e)]=e:t.U.oops("no using ctx for: "+q(e)))}function ot(t){if(!t)return null;const n=u(t);if(void 0!==n.declCache)return n.declCache;let r,i=L.getSymbolAtLocation(t);if(i&&(r=i.valueDeclaration,!r&&i.declarations)){let t=i.declarations[0];t&&t.kind==e.SyntaxKind.ImportEqualsDeclaration&&(i=L.getSymbolAtLocation(t.moduleReference),i&&(r=i.valueDeclaration))}return r}function st(e){let n=ot(e);if(rt(n),!n&&e&&e.kind==t.SK.PropertyAccessExpression){const r=e;n={kind:t.SK.PropertySignature,symbol:{isBogusSymbol:!0,name:r.name.getText()},name:r.name},u(n).flags|=2}return xe.declCache=n||null,n}function ct(e){return e.kind==t.SK.NullKeyword||e.kind==t.SK.NumericLiteral?!!e.isRefOverride:!x(e)}function lt(e){t.assert(e.length<=8,"args.length <= 8");let n=0;return e.forEach(((e,t)=>{ct(e)&&(n|=1<<t)})),n}function ut(n,i,a){let o=J(n),s=!(ee(i).flags&e.TypeFlags.Void),c=o.shim;if(c.indexOf("(")>=0){let e=/(.*)\((.*)\)$/.exec(c);if(e){a.length&&t.U.userError("no arguments expected");let s=[];if(e[2].replace(/\s/g,"")){for(let n of e[2].split(/,/)){let e=parseInt(n);isNaN(e)&&(e=Ht(i,n),null==e&&(e=qt(i,n)),null==e&&t.U.userError("invalid argument: "+n+" in "+c)),s.push(t.ir.numlit(e))}s.length>4&&t.U.userError("too many args")}return c=e[1],r.target.isNative&&t.hexfile.validateShim(ae(n),c,o,!0,s.map((e=>!0))),t.ir.rtcallMask(c,0,o.callingConvention,s)}}return"TD_NOOP"==c?(t.assert(!s,"!hasRet"),t.target.switches.profile&&"perfCounter"==o.shimArgument&&(a[0]&&a[0].kind==t.SK.StringLiteral&&(me.perfCounterName=a[0].text),me.perfCounterName||(me.perfCounterName=me.getFullName())),Wt(void 0)):"TD_ID"==c||"ENUM_GET"===c?(t.assert(1==a.length,"args.length == 1"),vn(a[0])):(r.target.shimRenames&&t.U.lookup(r.target.shimRenames,c)&&(c=r.target.shimRenames[c]),r.target.isNative&&t.hexfile.validateShim(ae(n),c,o,s,a.map(Qt)),Xt(c,a,o))}function dt(e,n,r){if(!e)return;let i=e.getParameters(),a=n.length;i.length>n.length&&i.slice(n.length).forEach((e=>{if(e.valueDeclaration&&e.valueDeclaration.kind==t.SK.Parameter){let i=e.valueDeclaration;if(i.initializer)(function(e){switch(e.kind){case t.SK.UndefinedKeyword:case t.SK.NullKeyword:case t.SK.TrueKeyword:case t.SK.FalseKeyword:case t.SK.NumericLiteral:return!0;case t.SK.PropertyAccessExpression:return vn(e).exprKind==o.NumberLiteral;default:return!1}})(i.initializer)||f(9212,U("only numbers, null, true and false supported as default arguments")),n.push(i.initializer);else{let e=T(r,q(i)),t=e?Wt(parseInt(e)):null;null==t&&(t=Wt(void 0)),n.push(Ot(t))}}else f(9213,U("unsupported default argument (shouldn't happen)"))}));for(let e=0;e<a;e++){let r=i[e];r&&r.valueDeclaration&&r.valueDeclaration.kind==t.SK.Parameter&&(n[e],r.valueDeclaration)}r.imageLiteral&&(x(n[0])||f(9214,U("Only image literals (string literals) supported here; {0}",p(n[0]))),n[0]=function(e){e||(e="0 0 0 0 0\n0 0 0 0 0\n0 0 0 0 0\n0 0 0 0 0\n0 0 0 0 0\n");let n=0,r=0,i=0,a="",o=0;e+="\n";for(let t=0;t<e.length;++t)switch(e[t]){case".":case"_":case"0":a+="0,",n++,o++;break;case"#":case"*":case"1":a+="255,",n++,o++;break;case"\t":case"\r":case" ":break;case"\n":n&&(0==r?r=n:n!=r&&f(9205,U("lines in image literal have to have the same width (got {0} and then {1} pixels)",r,n)),n=0,i++);break;default:f(9206,U("Only 0 . _ (off) and 1 # * (on) are allowed in image literals"))}let s="_img"+ge.lblNo++;o%2!=0&&(a+="0"),ge.otherLiterals.push(`\n.balign 4\n${s}: .short 0xffff\n .short ${r}, ${i}\n .byte ${a}\n`);let c="new pxsim.Image("+r+", ["+a+"])";return{kind:t.SK.NumericLiteral,imageLiteral:s,jsLit:c}}(n[0].text))}function pt(n,r,a,o,s=null,c=null){var l;s||(s=st(r));let u=!1,d=!1,p=!1;const m=n===r;if(s)switch(s.kind){case t.SK.PropertySignature:case t.SK.PropertyAssignment:case t.SK.PropertyDeclaration:case t.SK.MethodSignature:u=!0;break;case t.SK.Parameter:fe(s)&&(u=!0);break;case t.SK.GetAccessor:case t.SK.SetAccessor:case t.SK.MethodDeclaration:u=!0,d=!0,p=k(s);break;case t.SK.FunctionDeclaration:p=!0;break;case t.SK.ModuleDeclaration:break;default:s=null}else r.kind==t.SK.PropertyAccessExpression&&(u=!0);t.target.switches.slowMethods&&(d=!1);const g=J(s);let h=a.slice(0);if(u&&k(s)&&(u=!1),u&&!c&&r.kind==t.SK.PropertyAccessExpression&&(c=r.expression),i.usedArguments&&g.trackArgs){let e=c?[c].concat(h):h,n=g.trackArgs.map((t=>e[t])).map((e=>{let n=st(e);return!n||n.kind!=t.SK.EnumMember&&n.kind!=t.SK.VariableDeclaration?e&&e.kind==t.SK.StringLiteral?e.text:"*":j(L,n)})).join(","),r=j(L,s),a=i.usedArguments[r];a||(a=i.usedArguments[r]=[]),a.indexOf(n)<0&&a.push(n)}function y(){let e=gt(s,n,h.map((e=>vn(e)))),r=e.data;return h[0]&&r.proc&&r.proc.classInfo&&(r.isThis=h[0].kind==t.SK.ThisKeyword),e}if(dt(o,h,g),p){if(!Ne(s).location)return g.shim&&!At(s)?ut(s,n,h):(it(s),y())}if(r.kind==t.SK.SuperKeyword){let e=me.classInfo.baseClassInfo.ctor;for(let t=me.classInfo.baseClassInfo;t&&!e;t=t.baseClassInfo)e=t.ctor;if(!e&&ge.finalPass)throw f(9280,U("super() call requires an explicit constructor in base class"));let t=h.map((e=>vn(e)));return t.unshift(He(r)),ft(e,n,t)}if(u){if(t.U.assert(!k(s)),c?h.unshift(c):De(n,U("strange method call"),9241),!s){t.U.assert(r.kind==t.SK.PropertyAccessExpression);const e=r.name.text;return _t(h.map((e=>vn(e))),{ifaceIndex:Oe(e,!0),callLocationIndex:Tn(n),noArgs:m})}let i=Ne(s);if(i.parentClassInfo&&yt(i.parentClassInfo),it(s),c.kind==t.SK.SuperKeyword)return y();const a=!!i.virtualParent,o=!!_()||!!t.target.switches.slowMethods;if(a&&!o)return s.kind==t.SK.MethodDeclaration?t.U.assert(!m):s.kind==t.SK.GetAccessor||s.kind==t.SK.SetAccessor?t.U.assert(m):t.U.assert(!1),t.U.assert(!ge.finalPass||null!=i.virtualIndex,"!bin.finalPass || info.virtualIndex != null"),_t(h.map((e=>vn(e))),{classInfo:i.parentClassInfo,virtualIndex:i.virtualIndex,noArgs:m,isThis:h[0].kind==t.SK.ThisKeyword});if(g.shim&&!At(s))return ut(s,n,h);if(g.helper){let r,i=L.getSymbolsInScope(n,e.SymbolFlags.Module);for(let e of i)if("helpers"==e.name)for(let n of e.declarations||[e.valueDeclaration])if(n.kind==t.SK.ModuleDeclaration)for(let e of n.body.statements)(null===(l=e.symbol)||void 0===l?void 0:l.name)==g.helper&&(r=e);return r||f(9215,U("helpers.{0} not found",g.helper)),r.kind!=t.SK.FunctionDeclaration&&f(9216,U("helpers.{0} isn't a function",g.helper)),it(s=r),y()}return a||t.target.switches.slowMethods||!d?_t(h.map((e=>vn(e))),{ifaceIndex:Oe(q(s),!0),isSet:m&&2==h.length,callLocationIndex:Tn(n),noArgs:m}):(t.U.assert(s.kind!=t.SK.MethodSignature),y())}return s&&s.kind==t.SK.ModuleDeclaration&&("String"==q(s)?f(9219,U('to convert X to string use: X + ""')):f(9220,U("namespaces cannot be called directly"))),h.unshift(r),t.U.assert(!m),_t(h.map((e=>vn(e))),{virtualIndex:-1,callLocationIndex:Tn(n),noArgs:m})}function ft(e,n,r){t.U.assert(!ge.finalPass||!!e);let i={proc:e,callLocationIndex:Tn(n),virtualIndex:null,ifaceIndex:null};return t.ir.op(o.ProcCall,r,i)}function _t(e,n){return t.ir.op(o.ProcCall,e,n)}function mt(e){return u(e).proc}function gt(e,n,r){const i=mt(e);if(e.kind==t.SK.FunctionDeclaration){qe(Ne(e))}return t.assert(!!i||!ge.finalPass,"!!proc || !bin.finalPass"),ft(i,n,r)}function ht(e){return e.members.filter((e=>e.kind==t.SK.Constructor))[0]}function yt(e){if(at(e.decl),e.isUsed)return;u(e.decl).flags|=8,e.baseClassInfo&&yt(e.baseClassInfo),ge.usedClassInfos.push(e)}function vt(n){function i(e){return/^[0-9a-f]$/i.test(e)}let a=st(n.tag);if(!a)throw De(n,U("invalid tagged template"),9265);let o,s=J(a),c={decl:a,qName:a?j(L,a):"?",args:[n.template],isExpression:!0};function l(a){o=function(n,a){let o=te;if("_"==a[0]&&"_"==a[1]&&r.jres[a]&&(o=r.jres[a],a=""),""==a&&o){let n=/font\/x-mkcd-b(\d+)/.exec(o.mimeType);if(n)if(ge.finalPass){let e=parseInt(n[1]),r=atob(o.data),i=ge.usedChars,s="",c="";for(let t=0;t<r.length;t+=e){let n=r.charCodeAt(t)+(r.charCodeAt(t+1)<<8);(n<128||i[n>>5]&1<<(31&n))&&(s+=r.slice(t,t+e),c+=n+", ")}a=t.U.toHex(t.U.stringToUint8Array(s))}else a="aabbccdd";else o.dataEncoding&&"base64"!=o.dataEncoding?"hex"==o.dataEncoding?a=o.data:f(9271,U("invalid jres encoding '{0}' on '{1}'",o.dataEncoding,o.id)):a=t.U.toHex(t.U.stringToUint8Array(e.pxtc.decodeBase64(o.data)))}if(/^e[14]/i.test(a)&&n.parent&&n.parent.kind==t.SK.CallExpression&&"image.ofBuffer"==n.parent.expression.getText()){const e=/^e([14])(..)(..)..(.*)/i.exec(a);a=`870${e[1]}${e[2]}00${e[3]}000000${e[4]}`}let s="";for(let e=0;e<a.length;++e){let t=a[e];if(!i(t)){if(/^[\s\.]$/.test(t))continue;throw De(n,U("invalid character in hex literal '{0}'",t),9265)}i(a[e+1])&&(s+=t+a[e+1],e++)}if(t.target.isNative){const e=ge.emitHexLiteral(s.toLowerCase());return t.ir.ptrlit(e,e)}{const e="_hex"+Ae(n);return t.ir.ptrlit(e,{hexlit:s.toLowerCase()})}}(n,a(n.template.text))}if(u(n).callInfo=c,n.template.kind!=t.SK.NoSubstitutionTemplateLiteral)throw De(n,U("substitution not supported in hex literal",s.shim),9265);switch(s.shim){case"@hex":l((e=>e));break;case"@f4":l((function(e){if(!Array.isArray(s.groups))throw De(n,U("missing groups in @f4 literal"),9272);let r=[],i=[],a={},o=0;s.groups.forEach(((e,t)=>{for(let n of e)a[n]=t})),e+="\n";for(let c=0;c<e.length;++c){let l=e[c];switch(l){case" ":case"\t":break;case"\n":i.length>0&&(r.push(i),o=Math.max(i.length,o),i=[]);break;default:let e=t.U.lookup(a,l);if(null==e){if(2!=s.groups.length)throw De(n,U("invalid character in image literal: '{0}'",e),9273);e=1}i.push(e)}}let c=8;return s.groups.length<=2?c=1:s.groups.length<=16&&(c=4),t.f4EncodeImg(o,r.length,c,((e,t)=>r[t][e]||0))}));break;default:if(void 0===s.shim&&s.helper)return function(n,r){var i;let a,o=L.getSymbolsInScope(n,e.SymbolFlags.Module);for(let e of o)if("helpers"==e.name)for(let n of e.declarations||[e.valueDeclaration])if(n.kind==t.SK.ModuleDeclaration)for(let e of n.body.statements)(null===(i=e.symbol)||void 0===i?void 0:i.name)==r.helper&&(a=e);a||f(9215,U("helpers.{0} not found",r.helper));a.kind!=t.SK.FunctionDeclaration&&f(9216,U("helpers.{0} isn't a function",r.helper));const s=a;return it(s),gt(s,n,[Ge(n.text)])}(n.template,s);throw De(n,U("invalid shim '{0}' on tagged template",s.shim),9265)}return s.helper&&(o=t.ir.rtcall(s.helper,[o])),o}function bt(e){let n=e.parameters.slice(0);if(!k(e)&&D(e)){let r=Ne(e);r.thisParameter||(r.thisParameter={kind:t.SK.Parameter,name:{text:"this"},isThisParameter:!0,parent:e}),n.unshift(r.thisParameter)}return n}function xt(e,n=!1){let r=se(e);return t.ir.ptrlit(r+"_Lit",r)}function kt(){for(me=mt(be);w.length>0;){xn(w.pop())}}function St(){const e=le;if(e.length>0){le=[];for(let t of e){const e=me;try{Ct(t)}finally{me=e}}}}function Tt(e){ge.finalPass&&e.functionsToDefine&&t.U.pushRange(le,e.functionsToDefine)}function Ct(e){const n=Ne(e);let r=null;if(ge.finalPass){if(n.alreadyEmitted)return t.U.assert(n.usedBeforeDecl),null;n.alreadyEmitted=!0}let i=e.kind==t.SK.ArrowFunction||e.kind==t.SK.FunctionExpression,a=n.capturedVars.slice(0),s=a.map(((e,n)=>{let r=new t.ir.Cell(n,e,we(e));return r.iscap=!0,r}));void 0===n.usedBeforeDecl&&(n.usedBeforeDecl=!1),a.length>0?(t.assert(null!=N(e),"getEnclosingFunction(node) != null)"),r=t.ir.shared(t.ir.rtcall("pxt::mkAction",[t.ir.numlit(a.length),xt(e,!0)])),n.usedAsValue=!0,a.forEach(((e,n)=>{let i=me.localIndex(e);i||f(9223,U("cannot find captured value: {0}",L.symbolToString(e.symbol)));let a=i.loadCore();me.emitExpr(t.ir.rtcall("pxtrt::stclo",[r,t.ir.numlit(n),a]))})),e.kind==t.SK.FunctionDeclaration&&(n.location=me.mkLocal(e,we(e)),me.emitExpr(n.location.storeDirect(r)),r=null)):i&&(r=xt(e),n.usedAsValue=!0),t.assert(!!r==i,"!!lit == isExpression");let c=mt(e);if(c)me=c,me.reset();else{t.assert(!ge.finalPass,"!bin.finalPass");const r=u(e),i=new t.ir.Procedure;i.isRoot=!!(1&r.flags),i.action=e,i.info=n,r.proc=i,i.usingCtx=re,me=i,Pe((e=>e.addProc(i)))}me.captured=s;const l=[];if(e.parent.kind==t.SK.ClassDeclaration){let n=je(null,e.parent);if(me.classInfo?t.assert(me.classInfo==n,"proc.classInfo == classInfo"):me.classInfo=n,e.kind==t.SK.Constructor){if(n.baseClassInfo)for(let e of n.baseClassInfo.decl.members)e.kind==t.SK.Constructor&&it(e);n.ctor?t.assert(n.ctor==me,"classInfo.ctor == proc"):n.ctor=me;for(let e of n.allfields)if(e.kind==t.SK.PropertyDeclaration&&!k(e)){let t=e;t.initializer&&l.push(t)}}}const d=[],p=[];me.args=bt(e).map(((n,r)=>{n.name.kind===t.SK.ObjectBindingPattern&&d.push(n),e.kind==t.SK.Constructor&&fe(n)&&p.push(n);let i=new t.ir.Cell(r,n,we(n));return Tt(i.info),i.isarg=!0,i})),me.args.forEach((e=>{if(e.isByRefLocal()){let n=t.ir.shared(t.ir.rtcall("pxtrt::mklocRef",[]));me.emitExpr(t.ir.rtcall("pxtrt::stlocRef",[n,e.loadCore()],1)),me.emitExpr(e.storeDirect(n))}})),d.forEach((e=>mn(e)));for(let e of p){let r=Lt(me.classInfo,Rt(me.classInfo,q(e)),!1),i=t.ir.op(o.FieldAccess,[ze(n.thisParameter)],r);me.emitExpr(t.ir.op(o.Store,[i,ze(e)]))}for(let e of l){let r=Lt(me.classInfo,Rt(me.classInfo,q(e)),!1),i=t.ir.op(o.FieldAccess,[ze(n.thisParameter)],r);me.emitExpr(t.ir.op(o.Store,[i,vn(e.initializer)]))}if(St(),e.body.kind==t.SK.Block){if(kn(e.body),ne(me.action)){const n=me.body[me.body.length-1];n&&n.stmtKind==t.ir.SK.Jmp&&n.jmpMode==t.ir.JmpMode.Always||me.emitJmp(on(e).ret,Wt(void 0),t.ir.JmpMode.Always)}}else{let n=vn(e.body);me.emitJmp(on(e).ret,n,t.ir.JmpMode.Always)}me.emitLblDirect(on(e).ret),me.stackEmpty();let _=me.mkLabel("final");if(ne(me.action)?me.emitJmp(_):me.emitJmp(_,Wt(void 0)),me.emitLbl(_),n.capturedVars.length&&n.usedBeforeDecl&&e.kind==t.SK.FunctionDeclaration&&!ge.finalPass){n.capturedVars.sort(((e,t)=>t.pos-e.pos));const t=we(n.capturedVars[0]);t.functionsToDefine||(t.functionsToDefine=[]),t.functionsToDefine.push(e)}return t.assert(!ge.finalPass||0==w.length,"!bin.finalPass || usedWorkList.length == 0"),r}function Et(e){let n=t.ir.shared(e);return me.emitExpr(n),n}function Dt(){return Et(t.ir.op(o.JmpValue,[]))}function At(e){if(r.target.isNative)return!1;let n=e;return n.body&&(n.body.kind!=t.SK.Block||n.body.statements.length>0)}function Nt(n){if(!nt(n))return;if(32&u(n).flags)return;let i=J(n);if(null!=i.shim){if("@"==i.shim[0])return;if(r.target.isNative&&t.hexfile.validateShim(ae(n),i.shim,i,ne(n),bt(n).map((e=>_e(ee(e))))),!At(n))return}if(e.isInAmbientContext(n))return;if(!n.body)return;let a=null,o=me;try{a=Ct(n)}finally{me=o}return a}function wt(){}function It(e){let t=e;t.needsIRCache=!0,K.push(t)}function Pt(e,n=null){let r=K.length;return e.kind!=t.SK.PropertyAccessExpression&&e.kind!=t.SK.ElementAccessExpression||It(e.expression),n&&It(n),K.length==r?wt:()=>{for(let e=r;e<K.length;++e)K[e].cachedIR=null,K[e].needsIRCache=!1;K.splice(r,K.length-r)}}function Ot(e,n=!1){let r={kind:t.SK.NullKeyword,isRefOverride:n};return u(r).valueOverride=e,r}function Ft(e,n,r,i=null){let a=Pt(e),o=i?vn(i):Wt(1),s=t.ir.shared(vn(e)),c=t.ir.shared(Bt(n,s,o));return Mt(e,Ot(c,!0)),a(),r?s:c}function Lt(e,n,r=!0){k(n)&&t.U.oops("fieldIndex on static field: "+q(n));let i=J(n),a=e.allfields.indexOf(n);return a<0&&ge.finalPass&&t.U.oops("missing field"),{idx:a,name:q(n),isRef:!0,shimName:i.shim,classInfo:e,needsCheck:r}}function Rt(e,t){const n=e.allfields.filter((e=>e.name.text==t))[0];return n||f(9224,U("field {0} not found",t)),n}function Mt(n,r,i=!1){let a=st(n),s=P(a);if(n.kind==t.SK.Identifier||s)if(a&&(s||I(a)||O(a))){let e=Re(a);Ie(a,!0),me.emitExpr(e.storeByRef(vn(r)))}else De(n,U("bad target identifier"),9248);else if(n.kind==t.SK.PropertyAccessExpression){let i=st(n);if(!i||i.kind!=t.SK.GetAccessor&&i.kind!=t.SK.SetAccessor)if(i&&(i.kind==t.SK.PropertySignature||i.kind==t.SK.PropertyAssignment||Ze(i)))me.emitExpr(pt(n,n,[r],null,i));else{let e=vn(n);me.emitExpr(t.ir.op(o.Store,[e,vn(r)]))}else Xe(i),i=e.getDeclarationOfKind(i.symbol,t.SK.SetAccessor),i||De(n,U("setter not available"),9253),me.emitExpr(pt(n,n,[r],null,i))}else if(n.kind==t.SK.ElementAccessExpression)me.emitExpr(et(n,r));else if(n.kind==t.SK.ArrayLiteralExpression)if(r.kind==t.SK.ArrayLiteralExpression){const e=r.elements.map((e=>{const n=t.ir.shared(vn(e));return me.emitExpr(n),n}));n.elements.forEach(((t,n)=>{Mt(t,Ot(e[n]))}))}else{const e=t.ir.shared(vn(r));n.elements.forEach(((n,r)=>{Mt(n,Ot(Yt("Array_::getAt",[e,t.ir.numlit(r)])))}))}else De(n,U("bad assignment target"),9249)}function Ut(e){if(g())switch(e){case"numops::adds":case"numops::subs":case"numops::eors":case"numops::ands":case"numops::orrs":return"@nomask@"+e}if(_())switch(e){case"pxt::switch_eq":return"numops::eq"}return e}function Bt(e,t,n){return Yt(Ut(e),[t,n])}function $t(e){if(e.kind==t.SK.Identifier)return e.text;if(e.kind==t.SK.PropertyAccessExpression){const t=e,n=$t(t.expression);if(n)return n+"."+t.name.text}return null}function jt(e,t){if(!t)return null;const n=t.val;switch($t(e)){case"Math.floor":return{val:Math.floor(n)};case"Math.ceil":return{val:Math.ceil(n)};case"Math.round":return{val:Math.round(n)}}return null}function Kt(n){if(!n)return null;const r=u(n);if(void 0!==r.constantFolded)return r.constantFolded;if(I(n)&&n.parent.flags&e.NodeFlags.Const){const e=n;e.initializer&&(r.constantFolded=zt(e.initializer))}else if(n.kind==t.SK.EnumMember){const e=n,i=function(e){let n=J(e).enumval;if(!n){let t=L.getConstantValue(e);if(null==t)return null;n=t+""}return/^[+-]?\d+$/.test(n)||/^0x[A-Fa-f\d]{2,8}$/.test(n)?n:(t.U.userError("enumval only support number literals"),"0")}(e);if(null==i)r.constantFolded=zt(e.initializer);else{const e=parseInt(i);isNaN(e)||(r.constantFolded={val:e})}}else if(n.kind==t.SK.PropertyDeclaration&&k(n)&&S(n)){const e=n;r.constantFolded=zt(e.initializer)}return r.constantFolded}function zt(e){if(!e)return null;const n=u(e);if(void 0===n.constantFolded){n.constantFolded=null;const r=function(e){if(!e)return null;switch(e.kind){case t.SK.PrefixUnaryExpression:{const n=e,r=zt(n.operand);return function(e,n){if(!n)return null;const r=n.val;switch(e){case t.SK.PlusToken:return{val:+r};case t.SK.MinusToken:return{val:-r};case t.SK.TildeToken:return{val:~r};case t.SK.ExclamationToken:return{val:!r};default:return null}}(n.operator,r)}case t.SK.BinaryExpression:{const n=e,r=zt(n.left);if(!r)return null;const i=zt(n.right);return i?function(e,n,r){if(!n||!r)return null;const i=n.val,a=r.val;switch(e){case t.SK.PlusToken:return{val:i+a};case t.SK.MinusToken:return{val:i-a};case t.SK.SlashToken:return{val:i/a};case t.SK.PercentToken:return{val:i%a};case t.SK.AsteriskToken:return{val:i*a};case t.SK.AsteriskAsteriskToken:return{val:i**a};case t.SK.AmpersandToken:return{val:i&a};case t.SK.BarToken:return{val:i|a};case t.SK.CaretToken:return{val:i^a};case t.SK.LessThanLessThanToken:return{val:i<<a};case t.SK.GreaterThanGreaterThanToken:return{val:i>>a};case t.SK.GreaterThanGreaterThanGreaterThanToken:return{val:i>>>a};case t.SK.LessThanEqualsToken:return{val:i<=a};case t.SK.LessThanToken:return{val:i<a};case t.SK.GreaterThanEqualsToken:return{val:i>=a};case t.SK.GreaterThanToken:return{val:i>a};case t.SK.EqualsEqualsToken:return{val:i==a};case t.SK.EqualsEqualsEqualsToken:return{val:i===a};case t.SK.ExclamationEqualsEqualsToken:return{val:i!==a};case t.SK.ExclamationEqualsToken:return{val:i!=a};case t.SK.BarBarToken:return{val:i||a};case t.SK.AmpersandAmpersandToken:return{val:i&&a};default:return null}}(n.operatorToken.kind,r,i):null}case t.SK.NumericLiteral:{const t=parseFloat(e.text);return isNaN(t)?null:{val:t}}case t.SK.NullKeyword:return{val:null};case t.SK.TrueKeyword:return{val:!0};case t.SK.FalseKeyword:return{val:!1};case t.SK.UndefinedKeyword:return{val:void 0};case t.SK.CallExpression:{const t=e;return 1==t.arguments.length?jt(t.expression,zt(t.arguments[0])):null}case t.SK.PropertyAccessExpression:case t.SK.Identifier:return Kt(ot(e));case t.SK.AsExpression:return zt(e.expression);default:return null}}(e);n.constantFolded=r}return n.constantFolded}function Jt(e){let n=t.target.switches.boxDebug,r=null;if(n)try{t.target.switches.boxDebug=!1,r=vn(e)}finally{t.target.switches.boxDebug=n}else r=vn(e);let i=Gt(r);if(void 0===i)throw f(9267,U("a constant number-like expression is required here"));return i}function qt(e,t){let n=Vt(e,t,"userconfig");return null==n&&(n=Vt(e,t,"config")),n}function Vt(n,r,i){let a=L.getSymbolsInScope(n,e.SymbolFlags.Module).filter((e=>e.name==i&&!!e.valueDeclaration))[0];if(!a)return null;for(let e of a.valueDeclaration.body.statements)if(e.kind==t.SK.VariableStatement){let t=e;for(let e of t.declarationList.declarations)if(e.symbol.name==r)return Jt(e.initializer)}return null}function Ht(t,n){let r=L.getSymbolsInScope(t,e.SymbolFlags.Enum).filter((e=>"DAL"==e.name&&!!e.valueDeclaration))[0];if(!r)return null;let i=r.valueDeclaration.members.filter((e=>e.symbol.name==n))[0];return i?L.getConstantValue(i):null}function Gt(e){if(e.exprKind==t.ir.EK.NumberLiteral){let n=e.data;if(r.target.isNative&&!_()){if(n==t.taggedNull||n==t.taggedUndefined||n==t.taggedFalse)return 0;if(n==t.taggedTrue)return 1;if("number"==typeof n)return n>>1}else if("number"==typeof n)return n}else if(e.exprKind==t.ir.EK.RuntimeCall&&2==e.args.length){let t=Gt(e.args[0]),n=Gt(e.args[1]);if(void 0===t||void 0===n)return;switch(e.data){case"numops::orrs":return t|n;case"numops::adds":return t+n;default:return void console.log(e)}}}function Wt(e){if(r.target.isNative&&!_()){const r=Z(e);if(null!=r)return t.ir.numlit(r);if("number"==typeof e){if(n=e,!t.target.switches.boxDebug&&(0|n)==n&&-1073741824<=n&&n<=1073741823)return t.ir.numlit(e<<1|1);{let n=ge.emitDouble(e);return t.ir.ptrlit(n,JSON.stringify(e))}}throw t.U.oops("bad literal: "+e)}return t.ir.numlit(e);var n}function Qt(e){if(e.kind==t.SK.NullKeyword){let t=u(e).valueOverride;if(null!=t)return t.exprKind==o.NumberLiteral?!r.target.isNative||!!(1&t.data):t.exprKind==o.RuntimeCall&&"pxt::ptrOfLiteral"==t.data?t.args[0].exprKind==o.PointerLiteral&&!isNaN(parseFloat(t.args[0].jsInfo)):t.exprKind==o.PointerLiteral&&!isNaN(parseFloat(t.jsInfo))}return e.kind==t.SK.NumericLiteral||_e(ee(e))}function Yt(e,n){return t.ir.rtcallMask(e,(1<<n.length)-1,0,n)}function Xt(e,n,i,s=null){let c=[],l=t.hexfile.lookupFunc(e);if(g()){let n=t.U.lookup(a,e);n&&(l=n,e=n.name)}l&&(c=l.argsFmt),s&&(n=n.concat(s));let u=lt(n),d=[],p=n.map(((n,r)=>{let a=vn(n);if(!m())return a;let s=c[r+1],l=Qt(n);if(!s&&e.indexOf("::")<0&&(s=l?"I":"_"),s){if("_"==s[0]||"T"==s||"N"==s){let e=function(e){switch(e){case"_Buffer":return pxt.BuiltInType.BoxedBuffer;case"_Image":return t.target.imageRefTag||pxt.BuiltInType.RefImage;case"_Action":return pxt.BuiltInType.RefAction;case"_RefCollection":return pxt.BuiltInType.RefCollection;default:return null}}(s);return e&&d.push({argIdx:r,method:"_validate",refTag:e,refTagNullable:!!i.argsNullable}),a}if("I"==s)return a.exprKind==o.NumberLiteral&&"number"==typeof a.data?t.ir.numlit(a.data>>1):(d.push({argIdx:r,method:"pxt::toInt"}),a);if("B"==s)return u&=~(1<<r),an(n,a);if("S"==s)return a.isStringLiteral||(d.push({argIdx:r,method:"_pxt_stringConv",returnsRef:!0}),u|=1<<r),a;if("F"==s||"D"==s)return"D"==s&&t.U.oops("double arguments not yet supported"),l||t.U.userError("argsFmt=...F/D... but argument not a number in "+e),d.push({argIdx:r,method:"D"==s?"pxt::toDouble":"pxt::toFloat"}),a;throw t.U.oops("invalid format specifier: "+s)}throw t.U.userError("not enough args for "+e)})),f=t.ir.rtcallMask(e,u,i?i.callingConvention:0,p);if(f.mask||(f.mask={refMask:0}),f.mask.conversions=d,r.target.isNative){let e=c[0];"I"==e?f=h(f):"B"==e?f=y(f):"F"==e?f=function(e){return m()?t.ir.rtcall("pxt::fromFloat",[e]):e}(f):"D"==e&&(t.U.oops("double returns not yet supported"),f=function(e){return m()?t.ir.rtcall("pxt::fromDouble",[e]):e}(f))}return f}function Zt(n){ge.numStmts++;const a=t.assembler.debug||t.target.switches.size||t.target.sourceMap;let o=!!r.breakpoints;if(!a&&!o)return;const s=e.getSourceFileOfNode(n);if(r.justMyCode&&l(s)&&(o=!1),!a&&!o)return;let c=n.pos;for(;/^\s$/.exec(s.text[c]);)c++;for(;"/"==s.text[c]&&"/"==s.text[c+1];){for(;s.text[c]&&"\n"!=s.text[c];)c++;c++}const u=e.getLineAndCharacterOfPosition(s,c);if(a){let e=n.end;e-c>80&&(e=c+80);const r=s.text.slice(c,e).trim().replace(/\n[^]*/,"...");me.emit(t.ir.comment(`${s.fileName.replace(/pxt_modules\//,"")}(${u.line+1},${u.character+1}): ${r}`))}if(!o)return;const d=e.getLineAndCharacterOfPosition(s,n.end),p={id:i.breakpoints.length,isDebuggerStmt:n.kind==t.SK.DebuggerStatement,fileName:s.fileName,start:c,length:n.end-c,line:u.line,endLine:d.line,column:u.character,endColumn:d.character};i.breakpoints.push(p);const f=t.ir.stmt(t.ir.SK.Breakpoint,null);f.breakpointInfo=p,me.emit(f)}function en(e,n){switch(n){case t.SK.PlusToken:return"numops::adds";case t.SK.MinusToken:return"numops::subs";case t.SK.SlashToken:return"numops::div";case t.SK.PercentToken:return"numops::mod";case t.SK.AsteriskToken:return"numops::muls";case t.SK.AsteriskAsteriskToken:return"Math_::pow";case t.SK.AmpersandToken:return"numops::ands";case t.SK.BarToken:return"numops::orrs";case t.SK.CaretToken:return"numops::eors";case t.SK.LessThanLessThanToken:return"numops::lsls";case t.SK.GreaterThanGreaterThanToken:return"numops::asrs";case t.SK.GreaterThanGreaterThanGreaterThanToken:return"numops::lsrs";case t.SK.LessThanEqualsToken:return"numops::le";case t.SK.LessThanToken:return"numops::lt";case t.SK.GreaterThanEqualsToken:return"numops::ge";case t.SK.GreaterThanToken:return"numops::gt";case t.SK.EqualsEqualsToken:return"numops::eq";case t.SK.EqualsEqualsEqualsToken:return"numops::eqq";case t.SK.ExclamationEqualsEqualsToken:return"numops::neqq";case t.SK.ExclamationEqualsToken:return"numops::neq";default:return null}}function tn(e){if(e.operatorToken.kind==t.SK.EqualsToken)return function(e){let n=e.right;e.parent.kind==t.SK.ExpressionStatement&&(n=null);let r=Pt(e.left,n);Mt(e.left,e.right,!0);let i=n?vn(n):Wt(void 0);return r(),i}(e);const n=zt(e);if(n)return Wt(n.val);let r=null,i=null;e.operatorToken.kind!=t.SK.PlusToken&&e.operatorToken.kind!=t.SK.PlusEqualsToken||(r=ee(e.left),i=ee(e.right),(ue(r)||ue(i)&&e.operatorToken.kind==t.SK.PlusToken)&&(u(e).exprInfo={leftType:L.typeToString(r),rightType:L.typeToString(i)}));if(e.operatorToken.kind==t.SK.CommaToken){if(sn(e.left))return vn(e.right);{let n=cn(e.left);return t.ir.op(o.Sequence,[n,vn(e.right)])}}switch(e.operatorToken.kind){case t.SK.BarBarToken:case t.SK.AmpersandAmpersandToken:return function(e){let n=vn(e.left),r=(ue(ee(e.left)),me.mkLabel("lazy"));n=t.ir.shared(n);let i=t.ir.rtcall("numops::toBool",[n]),a=me.mkLabel("lazySkip"),o=e.operatorToken.kind==t.SK.BarBarToken?t.ir.JmpMode.IfZero:e.operatorToken.kind==t.SK.AmpersandAmpersandToken?t.ir.JmpMode.IfNotZero:t.U.oops();return me.emitJmp(a,i,o),me.emitJmp(r,n,t.ir.JmpMode.Always,n),me.emitLbl(a),me.emitExpr(Yt("langsupp::ignore",[n])),me.emitJmp(r,vn(e.right),t.ir.JmpMode.Always),me.emitLbl(r),Dt()}(e);case t.SK.InstanceOfKeyword:return function(e){let n=ee(e.right),r=Q(n)?st(e.right):null;r&&r.kind==t.SK.ClassDeclaration||f(9275,U("unsupported instanceof expression"));let i=je(n,r);yt(i);let a=t.ir.op(t.ir.EK.InstanceOf,[vn(e.left)],i);return a.jsInfo="bool",a}(e)}if(e.operatorToken.kind==t.SK.PlusToken&&(ue(r)||ue(i)))return Xt("String_::concat",[We(e.left),We(e.right)],null);if(e.operatorToken.kind==t.SK.PlusEqualsToken&&ue(r)){let n=Pt(e.left),r=t.ir.shared(Xt("String_::concat",[We(e.left),We(e.right)],null));return Mt(e.left,Ot(r)),n(),r}let a=function(e){switch(e){case t.SK.PlusEqualsToken:return t.SK.PlusToken;case t.SK.MinusEqualsToken:return t.SK.MinusToken;case t.SK.AsteriskEqualsToken:return t.SK.AsteriskToken;case t.SK.AsteriskAsteriskEqualsToken:return t.SK.AsteriskAsteriskToken;case t.SK.SlashEqualsToken:return t.SK.SlashToken;case t.SK.PercentEqualsToken:return t.SK.PercentToken;case t.SK.LessThanLessThanEqualsToken:return t.SK.LessThanLessThanToken;case t.SK.GreaterThanGreaterThanEqualsToken:return t.SK.GreaterThanGreaterThanToken;case t.SK.GreaterThanGreaterThanGreaterThanEqualsToken:return t.SK.GreaterThanGreaterThanGreaterThanToken;case t.SK.AmpersandEqualsToken:return t.SK.AmpersandToken;case t.SK.BarEqualsToken:return t.SK.BarToken;case t.SK.CaretEqualsToken:return t.SK.CaretToken;default:return t.SK.Unknown}}(e.operatorToken.kind),s=en(0,a||e.operatorToken.kind);return s||De(e.operatorToken,U("unsupported operator"),9250),a?Ft(e.left,s,!1,e.right):(n=>{n=Ut(n);let r=[e.left,e.right];return t.ir.rtcallMask(n,lt(r),0,r.map((e=>vn(e))))})(s)}function nn(e){e.statements.forEach(kn)}function rn(t){if(t.flags&e.NodeFlags.Let||t.flags&e.NodeFlags.Const)return!0;throw f(9260,U("variable needs to be defined using 'let' instead of 'var'"))}function an(e,n=null){if(!n&&g()&&e.kind==t.SK.BinaryExpression){let n=e,r=t.U.lookup(t.thumbCmpMap,en(0,n.operatorToken.kind));if(r)return t.ir.rtcall(r,[vn(n.left),vn(n.right)])}return n||(n=vn(e)),_()?n:t.ir.rtcall("numops::toBoolDecr",[n])}function on(e){let t=d(e);return{fortop:".fortop."+t,cont:".cont."+t,brk:".brk."+t,ret:".ret."+t}}function sn(e){if(!e)return!0;switch(e.kind){case t.SK.Identifier:case t.SK.StringLiteral:case t.SK.NumericLiteral:case t.SK.NullKeyword:return!0}return!1}function cn(e){return vn(e)}function ln(e){if(sn(e))return;Zt(e);let t=cn(e);me.emitExpr(t),me.stackEmpty()}function un(e=1){for(;e--;)me.emitExpr(Yt("pxt::endTry",[]))}function dn(){f(9282,U("jumps (return, break, continue) through finally blocks not supported yet"))}function pn(t){let n=0;if(t.kind==e.SyntaxKind.Block&&t.parent)if(t.parent.kind==e.SyntaxKind.CatchClause){t.parent.parent.finallyBlock&&(n++,dn())}else if(t.parent.kind==e.SyntaxKind.TryStatement){const e=t.parent;e.tryBlock==t&&(e.catchClause&&n++,e.finallyBlock&&(n++,dn()))}return n}function fn(e){switch(e.kind){case t.SK.WhileStatement:case t.SK.ForInStatement:case t.SK.ForOfStatement:case t.SK.ForStatement:case t.SK.DoStatement:return!0;default:return!1}}function _n(e,n,i){if(e.name.kind===t.SK.ObjectBindingPattern||e.name.kind==t.SK.ArrayBindingPattern)return n||(n=e.initializer?t.ir.shared(vn(e.initializer)):ze(e),i=e.initializer?ee(e.initializer):ee(e)),e.name.elements.forEach((e=>_n(e,n,i))),me.stackEmpty(),null;if(!nt(e))return null;if(Kt(e))return null;let a;if(P(e)?(Le(e),a=Re(e)):a=me.mkLocal(e,we(e)),Tt(a.info),a.isByRefLocal()&&me.emitExpr(a.storeDirect(t.ir.rtcall("pxtrt::mklocRef",[]))),Fe(ee(e)),e.kind===t.SK.BindingElement){Zt(e);let[t,r]=gn(e,n,i);me.emitExpr(a.storeByRef(t))}else if(e.initializer){if(Zt(e),P(e)){let n=J(e).jres;if(n){"true"==n&&(n=j(L,e));let i=t.U.lookup(r.jres||{},n);i?te=i:f(9270,U("resource '{0}' not found in any .jres file",n))}}e.initializer,me.emitExpr(a.storeByRef(vn(e.initializer))),te=null,me.stackEmpty()}else(function(e){for(;e;){if(fn(e))return!0;e=e.parent}return!1})(e)&&(Zt(e),me.emitExpr(a.storeByRef(Wt(void 0))),me.stackEmpty());return a}function mn(e){return _n(e,null,null)}function gn(e,n,r){const i=e.parent.parent;if(i.kind===t.SK.BindingElement){const e=gn(i,n,r);n=e[0],r=e[1]}if(e.parent.kind==t.SK.ArrayBindingPattern){const i=e.parent.elements.indexOf(e);e.dotDotDotToken&&f(9203,U("spread operator not supported yet"));const a=Y(r,i);return[Yt("Array_::getAt",[n,t.ir.numlit(i)]),a]}return function(e,n,r,i){const a=L.getPropertyOfType(r,i);t.U.assert(!!a,"field sym");const s=L.getTypeOfSymbolAtLocation(a,e);let c;if(Q(r)){const e=je(r);c=t.ir.op(o.FieldAccess,[n],Lt(e,Rt(e,i)))}else c=_t([n],{ifaceIndex:Oe(i,!0),callLocationIndex:Tn(e),noArgs:!0});return[c,s]}(e,n,r,(e.propertyName||e.name).text)}function hn(e){!function(e,n){const r=e=>{e&&e.kind==t.SK.ClassDeclaration&&f(9261,U("Interface with same name as a class not supported"))};if(r(n.symbol.valueDeclaration),n.symbol.declarations&&n.symbol.declarations.forEach(r),n.heritageClauses)for(let e of n.heritageClauses)switch(e.token){case t.SK.ExtendsKeyword:W(ee(e.types[0]))&&f(9262,U("Extending a class by an interface not supported."))}}(0,e);let n=J(e);n.autoCreate&&(V[n.autoCreate]=!0)}function yn(e,t){let n=M;$++;try{M=null;let r=t(e);return M&&f(B,M),M=n,$--,r}catch(t){return $--,M=null,Ee(e,t.ksErrorCode||9200,t.message),pxt.debug(t.stack),null}}function vn(e,n=!0){let r=e;if(n&&r.cachedIR)return r.cachedIR;let i=yn(r,bn)||Wt(void 0);return n&&r.needsIRCache?(r.cachedIR=t.ir.shared(i),r.cachedIR):i}function bn(n){let r=function(n){switch(n.kind){case t.SK.NullKeyword:let r=u(n).valueOverride;return r||Wt(null);case t.SK.TrueKeyword:return Wt(!0);case t.SK.FalseKeyword:return Wt(!1);case t.SK.TemplateHead:case t.SK.TemplateMiddle:case t.SK.TemplateTail:case t.SK.NumericLiteral:case t.SK.StringLiteral:case t.SK.NoSubstitutionTemplateLiteral:return function(e){if(e.kind==t.SK.NumericLiteral)return e.imageLiteral?t.ir.ptrlit(e.imageLiteral,e.jsLit):Wt(parseFloat(e.text));if(x(e))return Ge(e.text);throw t.oops()}(n);case t.SK.TaggedTemplateExpression:return vt(n);case t.SK.PropertyAccessExpression:return Ye(n);case t.SK.BinaryExpression:return tn(n);case t.SK.PrefixUnaryExpression:return function(e){const n=zt(e);if(n)return Wt(n.val);switch(e.operator){case t.SK.ExclamationToken:return y(t.ir.rtcall("Boolean_::bang",[an(e.operand)]));case t.SK.PlusPlusToken:return Ft(e.operand,"numops::adds",!1);case t.SK.MinusMinusToken:return Ft(e.operand,"numops::subs",!1);case t.SK.PlusToken:case t.SK.MinusToken:{let n=vn(e.operand),r=Gt(n);return null!=r?Wt(-r):e.operator==t.SK.MinusToken?Bt("numops::subs",Wt(0),n):Bt("numops::subs",n,Wt(0))}case t.SK.TildeToken:{let t=vn(e.operand),n=Gt(t);return null!=n?Wt(~n):Yt(Ut("numops::bnot"),[t])}default:throw De(e,U("unsupported prefix unary operation"),9245)}}(n);case t.SK.PostfixUnaryExpression:return function(e){if(de(ee(e.operand)))switch(e.operator){case t.SK.PlusPlusToken:return Ft(e.operand,"numops::adds",!0);case t.SK.MinusMinusToken:return Ft(e.operand,"numops::subs",!0)}throw De(e,U("unsupported postfix unary operation"),9246)}(n);case t.SK.ElementAccessExpression:return et(n);case t.SK.ParenthesizedExpression:return function(e){return vn(e.expression)}(n);case t.SK.TypeAssertionExpression:return function(e){return e.expression,vn(e.expression)}(n);case t.SK.ArrayLiteralExpression:return function(e){Y(ee(e));let n=t.ir.shared(t.ir.rtcall("Array_::mk",[]));for(let r of e.elements){let e=ct(r)?2:0;me.emitExpr(t.ir.rtcall("Array_::push",[n,vn(r)],e))}return n}(n);case t.SK.NewExpression:return function(e){let n=L.getTypeAtLocation(e);if(n&&H(n))throw t.oops();if(n&&Q(n)){let n,r=st(e.expression);r.kind!=t.SK.ClassDeclaration&&f(9221,U("new expression only supported on class types"));let i=je(ee(e),r);for(let e=i;e&&(n=ht(e.decl),!n);e=e.baseClassInfo);yt(i);let a=i.id+"_VT",o=t.ir.rtcall("pxt::mkClassInstance",[t.ir.ptrlit(a,a)]);if(n){o=Et(o),rt(n);let r=(e.arguments||[]).slice(0),i=J(n);dt(L.getResolvedSignature(e),r,i);let a=r.map((e=>vn(e)));return i.shim?t.ir.rtcall(i.shim,a):(a.unshift(o),me.emitExpr(gt(n,e,a)),o)}return e.arguments&&e.arguments.length&&f(9222,U("constructor with arguments not found")),o}throw De(e,U("unknown type for new"),9243)}(n);case t.SK.SuperKeyword:case t.SK.ThisKeyword:return He(n);case t.SK.CallExpression:return function(e){const t=L.getResolvedSignature(e);return pt(e,e.expression,e.arguments,t)}(n);case t.SK.FunctionExpression:case t.SK.ArrowFunction:return Nt(n);case t.SK.Identifier:return Ve(n);case t.SK.ConditionalExpression:return function(e){let n=me.mkLabel("condexprz"),r=me.mkLabel("condexprfin");return me.emitJmp(n,an(e.condition),t.ir.JmpMode.IfZero),me.emitJmp(r,vn(e.whenTrue),t.ir.JmpMode.Always),me.emitLbl(n),me.emitJmp(r,vn(e.whenFalse),t.ir.JmpMode.Always),me.emitLbl(r),Dt()}(n);case t.SK.AsExpression:return function(e){return e.expression,vn(e.expression)}(n);case t.SK.TemplateExpression:return Qe(n);case t.SK.ObjectLiteralExpression:return function(e){let n=t.ir.shared(t.ir.rtcall("pxtrt::mkMap",[]));return e.properties.forEach((e=>{let r,i;if(t.assert(!e.questionToken),e.kind==t.SK.ShorthandPropertyAssignment){const n=e;t.assert(!n.equalsToken&&!n.objectAssignmentInitializer),r=e.name.text;const a=L.getShorthandAssignmentValueSymbol(e),o=a&&a.valueDeclaration&&a.valueDeclaration.name;if(!o||o.kind!=t.SK.Identifier)throw De(e);i=Ve(o)}else{if(e.name.kind==t.SK.ComputedPropertyName){const t=e.name.expression;return void me.emitExpr(Xt("pxtrt::mapSetByString",[Ot(n,!0),t,e.initializer],null))}r=e.name.kind==t.SK.StringLiteral?e.name.text:e.name.getText(),i=vn(e.initializer)}const a=t.target.isNative?t.ir.numlit(Oe(r)):t.ir.ptrlit(null,JSON.stringify(r)),o=[n,a,i];me.emitExpr(t.ir.rtcall(t.target.isNative?"pxtrt::mapSet":"pxtrt::mapSetByString",o))})),n}(n);case t.SK.TypeOfExpression:return function(e){return Xt("pxt::typeOf",[e.expression],null)}(n);case e.SyntaxKind.DeleteExpression:return function(e){let n,r;if(e.expression.kind==t.SK.PropertyAccessExpression){const t=e.expression;n=t.expression,r=Ot(Ge(t.name.text))}else{if(e.expression.kind!=t.SK.ElementAccessExpression)throw f(9276,U("expression not supported as argument to 'delete'"));{const t=e.expression;n=t.expression,r=t.argumentExpression}}const i=ee(n);if(W(i))throw f(9277,U("'delete' not supported on class types"));if(H(i))throw f(9277,U("'delete' not supported on array"));return Xt("pxtrt::mapDeleteByString",[n,r],null)}(n);default:return De(n),null}}(n);if(r.isExpr())return r;throw new Error("expecting expression")}function xn(n){const r=u(n);if(r.usedNodes){ie=!1;for(let e of t.U.values(r.usedNodes))rt(e);for(let e of r.usedActions)e(ge);ie=!0}else P(n)||e.isClassDeclaration(n)?(ie=!1,re=r,re.usedNodes=null,re.usedActions=null,P(n)&&!Kt(n)&&Le(n),kn(n),ie=!0):(re=r,re.usedNodes={},re.usedActions=[],kn(n),re=null)}function kn(e){yn(e,Sn)}function Sn(n){switch(n.kind){case t.SK.SourceFile:return function(e){e.statements.forEach(kn)}(n);case t.SK.InterfaceDeclaration:return hn(n);case t.SK.VariableStatement:return function(n){function r(e){let n=t.U.lookup(X,e.name);if(n||(n=e,X[e.name]=n),n.value!=e.value)throw f(9269,U("conflicting values for config.{0}",e.name))}if(n.declarationList.flags&e.NodeFlags.Const){let e=n.parent&&n.parent.kind==t.SK.ModuleBlock?q(n.parent.parent):"?";if("config"==e||"userconfig"==e)for(let t of n.declarationList.declarations){let i=ae(t);if(!t.initializer)continue;let a=Jt(t.initializer),o=Ht(n,"CFG_"+i);if(null==o||0==o)throw f(9268,U("can't find DAL.CFG_{0}",i));"userconfig"==e&&(i="!"+i),r({name:i,key:o,value:a})}}e.isInAmbientContext(n)||(rn(n.declarationList),n.declarationList.declarations.forEach(kn))}(n);case t.SK.ModuleDeclaration:return function(e){kn(e.body)}(n);case t.SK.EnumDeclaration:return;case t.SK.FunctionDeclaration:case t.SK.Constructor:case t.SK.MethodDeclaration:return void Nt(n);case t.SK.ExpressionStatement:return function(e){ln(e.expression)}(n);case t.SK.Block:case t.SK.ModuleBlock:return nn(n);case t.SK.VariableDeclaration:return mn(n),void St();case t.SK.IfStatement:return function(e){Zt(e);let t=me.mkLabel("else");me.emitJmpZ(t,an(e.expression)),kn(e.thenStatement);let n=me.mkLabel("afterif");me.emitJmp(n),me.emitLbl(t),e.elseStatement&&kn(e.elseStatement),me.emitLbl(n)}(n);case t.SK.WhileStatement:return function(e){Zt(e);let t=on(e);me.emitLblDirect(t.cont),Zt(e.expression),me.emitJmpZ(t.brk,an(e.expression)),kn(e.statement),me.emitJmp(t.cont),me.emitLblDirect(t.brk)}(n);case t.SK.DoStatement:return function(e){Zt(e);let t=on(e);me.emitLblDirect(t.cont),kn(e.statement),Zt(e.expression),me.emitJmpZ(t.brk,an(e.expression)),me.emitJmp(t.cont),me.emitLblDirect(t.brk)}(n);case t.SK.ForStatement:return function(e){e.initializer&&e.initializer.kind==t.SK.VariableDeclarationList?(rn(e.initializer),e.initializer.declarations.forEach(kn)):ln(e.initializer),Zt(e);let n=on(e);me.emitLblDirect(n.fortop),e.condition&&(Zt(e.condition),me.emitJmpZ(n.brk,an(e.condition))),kn(e.statement),me.emitLblDirect(n.cont),ln(e.incrementor),me.emitJmp(n.fortop),me.emitLblDirect(n.brk)}(n);case t.SK.ForOfStatement:return function(e){if(!e.initializer||e.initializer.kind!=t.SK.VariableDeclarationList)return void De(e,"only a single variable may be used to iterate a collection");let n=e.initializer;if(1!=n.declarations.length)return void De(e,"only a single variable may be used to iterate a collection");rn(n);let r=ee(e.expression),i="",a="";if(ue(r))i="String_::charAt",a="String_::length";else{if(!H(r))return void De(e.expression,"cannot use for...of with this expression");i="Array_::getAt",a="Array_::length"}rt(n.declarations[0]);const o=mn(n.declarations[0]);t.U.assert(!!o||!ge.finalPass),me.stackEmpty();let s=me.mkLocalUnnamed();me.emitExpr(s.storeByRef(vn(e.expression)));let c=me.mkLocalUnnamed();me.emitExpr(c.storeByRef(Wt(0))),me.stackEmpty(),Zt(e);let l=on(e);me.emitLblDirect(l.fortop);let u=t.ir.rtcall(a,[s.loadCore()]),d=Bt("numops::lt_bool",c.load(),h(u));me.emitJmpZ(l.brk,d),o&&me.emitExpr(o.storeByRef(t.ir.rtcall(i,[s.loadCore(),(e=>m()?t.ir.rtcall("pxt::toInt",[e]):e)(c.loadCore())]))),St(),kn(e.statement),me.emitLblDirect(l.cont),me.emitExpr(c.storeByRef(Bt("numops::adds",c.load(),Wt(1)))),me.emitJmp(l.fortop),me.emitLblDirect(l.brk),me.emitExpr(s.storeByRef(Wt(void 0)))}(n);case t.SK.ContinueStatement:case t.SK.BreakStatement:return function(n){Zt(n);let r=n.label?n.label.text:null,i=n.kind==t.SK.BreakStatement,a=0,o=function n(o){return o?r&&o.kind==t.SK.LabeledStatement&&o.label.text==r?o.statement:o.kind==t.SK.SwitchStatement&&!r&&i||!r&&e.isIterationStatement(o,!1)?o:(a+=pn(o),n(o.parent)):null}(n);if(o){let r=on(o);un(a),n.kind==t.SK.ContinueStatement?e.isIterationStatement(o,!1)?me.emitJmp(r.cont):Ee(n,9231,U("continue on non-loop")):n.kind==t.SK.BreakStatement?me.emitJmp(r.brk):t.oops()}else Ee(n,9230,U("cannot find outer loop"))}(n);case t.SK.LabeledStatement:return function(e){let t=on(e.statement);kn(e.statement),me.emitLblDirect(t.brk)}(n);case t.SK.ReturnStatement:return function(e){Zt(e);let n=null;e.expression?n=vn(e.expression):ne(me.action)&&(n=Wt(void 0));let r=0;for(let t=e;t&&t!=me.action;t=t.parent)r+=pn(t);un(r),me.emitJmp(on(me.action).ret,n,t.ir.JmpMode.Always)}(n);case t.SK.ClassDeclaration:return function(e){const t=je(null,e);t.isUsed&&ge.usedClassInfos.indexOf(t)<0&&ge.usedClassInfos.push(t),e.members.forEach(kn)}(n);case t.SK.PropertyDeclaration:case t.SK.PropertyAssignment:return function(e){if(k(e))mn(e);else if(e.initializer){let t=je(ee(e.parent));ge.finalPass&&t.isUsed&&!t.ctor&&f(9209,U("class field initializers currently require an explicit constructor"))}}(n);case t.SK.SwitchStatement:return function(e){Zt(e);let n,r=on(e),i=t.ir.shared(vn(e.expression)),a=e.caseBlock.clauses.map((e=>{let r=me.mkLabel("switch");if(e.kind==t.SK.CaseClause){let n=e,a=vn(n.expression),o=ct(n.expression)?1:0,s=t.ir.rtcallMask(Ut("pxt::switch_eq"),o,0,[a,i]);me.emitJmp(r,s,t.ir.JmpMode.IfNotZero,i)}else e.kind==t.SK.DefaultClause?(t.assert(!n,"!defaultLabel"),n=r):t.oops();return r}));n?me.emitJmp(n,i):me.emitJmp(r.brk,i),e.caseBlock.clauses.forEach(((e,t)=>{me.emitLbl(a[t]),e.statements.forEach(kn)})),me.emitLblDirect(r.brk)}(n);case t.SK.TypeAliasDeclaration:return;case e.SyntaxKind.TryStatement:return function(e){const n=e=>Yt("pxt::beginTry",[t.ir.ptrlit(e.lblName,e)]);Zt(e);const r=me.mkLabel("catch");r.lblName="_catch_"+d(e);const i=me.mkLabel("finally");if(i.lblName="_finally_"+d(e),e.finallyBlock&&me.emitExpr(n(i)),e.catchClause&&me.emitExpr(n(r)),me.stackEmpty(),nn(e.tryBlock),me.stackEmpty(),e.catchClause){const t=me.mkLabel("catchend");un(),me.emitJmp(t),me.emitLbl(r);const n=e.catchClause.variableDeclaration;if(n){mn(n);const e=Re(n);me.emitExpr(e.storeByRef(Yt("pxt::getThrownValue",[])))}St(),nn(e.catchClause.block),me.emitLbl(t)}e.finallyBlock&&(un(),me.emitLbl(i),nn(e.finallyBlock),me.emitExpr(Yt("pxt::endFinally",[])))}(n);case e.SyntaxKind.ThrowStatement:return function(e){Zt(e),me.emitExpr(Yt("pxt::throwValue",[vn(e.expression)]))}(n);case t.SK.DebuggerStatement:return function(e){Zt(e)}(n);case t.SK.GetAccessor:case t.SK.SetAccessor:return function(e){Nt(e)}(n);case t.SK.ImportEqualsDeclaration:case t.SK.EmptyStatement:case t.SK.SemicolonClassElement:return;default:De(n)}}function Tn(e){return i.procCallLocations.push(t.nodeLocationInfo(e))-1}},t.isStringType=ue;class pe{constructor(){this.procs=[],this.globals=[],this.finalPass=!1,this.writeFile=(e,t)=>{},this.usedClassInfos=[],this.numStmts=1,this.commSize=0,this.itEntries=0,this.itFullEntries=0,this.numMethods=0,this.numVirtMethods=0,this.usedChars=new Uint32Array(2048),this.explicitlyUsedIfaceMembers={},this.ifaceMemberMap={},this.strings={},this.hexlits={},this.doubles={},this.otherLiterals=[],this.codeHelpers={},this.lblNo=0}reset(){this.lblNo=0,this.otherLiterals=[],this.strings={},this.hexlits={},this.doubles={},this.numStmts=0}getTitle(){const e=this.options.name||t.U.lf("Untitled");return e.length>=90?e.slice(0,87)+"...":e}addProc(e){t.assert(!this.finalPass,"!this.finalPass"),this.procs.push(e),e.seqNo=this.procs.length}recordHelper(e,t,n){const r=e=>{e.codeHelpers[t]||(e.codeHelpers[t]=n(e))};r(this),this.recordAction(e,r)}recordAction(e,n){e?e.usedActions&&e.usedActions.push(n):t.U.oops("no using ctx!")}emitLabelled(e,n,r){let i=t.U.lookup(n,e);if(null!=i)return i;let a=r+this.lblNo++;return n[e]=a,a}emitDouble(e){return this.emitLabelled(t.target.switches.numFloat?function(e){let n=new Float32Array(1);return n[0]=e,t.U.toHex(new Uint8Array(n.buffer))}(e):function(e){let n=new Float64Array(1);return n[0]=e,t.U.toHex(new Uint8Array(n.buffer))}(e),this.doubles,"_dbl")}emitString(e){if(!this.finalPass)for(let t=0;t<e.length;++t){const n=e.charCodeAt(t);n>=128&&(this.usedChars[n>>5]|=1<<(31&n))}return this.emitLabelled(e,this.strings,"_str")}emitHexLiteral(e){return this.emitLabelled(e,this.hexlits,"_hexlit")}setPerfCounters(e){if(!t.target.switches.profile)return[];const n=e.slice();return this.procs.forEach((e=>{e.perfCounterName&&(t.U.assert(t.target.switches.profile),e.perfCounterNo=n.length,n.push(e.perfCounterName))})),n}}function fe(e){if(!e.modifiers)return!1;if(e.parent.kind!=t.SK.Constructor)return!1;for(let n of e.modifiers)if(n.kind==t.SK.PrivateKeyword||n.kind==t.SK.PublicKeyword||n.kind==t.SK.ProtectedKeyword)return!0;return!1}function _e(t){return t.flags&e.TypeFlags.Union?t.types.every((e=>_e(e))):!!(t.flags&(e.TypeFlags.NumberLike|e.TypeFlags.EnumLike|e.TypeFlags.BooleanLike))}t.Binary=pe,t.isCtorField=fe}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(ts){var pxtc;(function(pxtc){function getTsCompilerOptions(e){let t=ts.getDefaultCompilerOptions();return t.target=ts.ScriptTarget.ES5,t.module=ts.ModuleKind.None,t.noImplicitAny=!0,t.noImplicitReturns=!0,t.allowUnreachableCode=!0,t}function nodeLocationInfo(e){let t=ts.getSourceFileOfNode(e);const n=e.getStart?e.getStart():e.pos,{line:r,character:i}=ts.getLineAndCharacterOfPosition(t,n),{line:a,character:o}=ts.getLineAndCharacterOfPosition(t,e.end);return{start:n,length:e.end-n,line:r,column:i,endLine:a,endColumn:o,fileName:t.fileName}}function patchUpDiagnostics(e,t=!1){t&&(e=e.filter((e=>5012!==e.code)));let n=e.filter((e=>1148==e.code));return n.length>0&&(e=n),e.map((e=>{if(!e.file){return{code:e.code,start:e.start,length:e.length,line:0,column:0,messageText:ts.flattenDiagnosticMessageText(e.messageText,"\n"),category:e.category,fileName:"?"}}const t=ts.getLineAndCharacterOfPosition(e.file,e.start);let n={code:e.code,start:e.start,length:e.length,line:t.line,column:t.character,messageText:ts.flattenDiagnosticMessageText(e.messageText,"\n"),category:e.category,fileName:e.file.fileName};return 1148==n.code&&(n.messageText=pxtc.Util.lf("all symbols in top-level scope are always exported; please use a namespace if you want to export only some")),n}))}function py2tsIfNecessary(e){if(e.target.preferredEditor==pxt.PYTHON_PROJECT_NAME){return pxtc.transpile.pyToTs(e)}}function mkCompileResult(){return{outfiles:{},diagnostics:[],success:!1,times:{}}}function storeGeneratedFiles(e,t){for(let n of e.generatedFiles||[])t.outfiles[n]=e.fileSystem[n]}function runConversionsAndStoreResults(e,t){const n=pxtc.U.cpuUs();t||(t=mkCompileResult());const r=py2tsIfNecessary(e);r&&(t=Object.assign(Object.assign({},t),{diagnostics:r.diagnostics,sourceMap:r.sourceMap,globalNames:r.globalNames})),storeGeneratedFiles(e,t),e.sourceFiles||(e.sourceFiles=Object.keys(e.fileSystem));const i=e.sourceFiles.indexOf(pxt.MAIN_TS);i>=0&&(e.sourceFiles.splice(i,1),e.sourceFiles.push(pxt.MAIN_TS));const a=e.sourceFiles.indexOf(pxt.TUTORIAL_CODE_STOP);return a>=0&&(e.sourceFiles.splice(a,1),e.sourceFiles.push(pxt.TUTORIAL_CODE_STOP)),t.times.conversions=pxtc.U.cpuUs()-n,t}function timesToMs(e){for(let t of Object.keys(e.times))e.times[t]=Math.round(e.times[t])/1e3}function buildProgram(e,t){let n={};for(let t in e.fileSystem)n[normalizePath(t)]=e.fileSystem[t];let r=getTsCompilerOptions(e),i={getSourceFile:(e,t,r)=>{e=normalizePath(e);let i="";return n.hasOwnProperty(e)?i=n[e]:r&&r("File not found: "+e),null==i&&(r("File not found: "+e),i=""),ts.createSourceFile(e,i,t,true)},fileExists:e=>(e=normalizePath(e),n.hasOwnProperty(e)),getCanonicalFileName:e=>e,getDefaultLibFileName:()=>"no-default-lib.d.ts",writeFile:(e,n,r,i)=>{t.outfiles[e]=n},getCurrentDirectory:()=>".",useCaseSensitiveFileNames:()=>!0,getNewLine:()=>"\n",readFile:e=>(e=normalizePath(e),n[e]||""),directoryExists:e=>!0,getDirectories:()=>[]},a=e.sourceFiles.filter((e=>pxtc.U.endsWith(e,".ts")));return ts.createProgram(a,r,i)}function isPxtModulesFilename(e){return pxtc.U.startsWith(e,"pxt_modules/")}function compile(opts,service){pxtc.compilerHooks||(pxtc.compilerHooks={},opts.target.compilerExtension&&eval(opts.target.compilerExtension)),pxtc.compilerHooks.init&&pxtc.compilerHooks.init(opts,service);let startTime=pxtc.U.cpuUs(),res=mkCompileResult(),program;if(service)storeGeneratedFiles(opts,res),program=service.getProgram();else{if(runConversionsAndStoreResults(opts,res),res.diagnostics.length>0)return res;program=buildProgram(opts,res)}const entryPoint=opts.sourceFiles.filter((e=>pxtc.U.endsWith(e,".ts"))).pop().replace(/.*\//,"");if(res.diagnostics=patchUpDiagnostics(program.getSyntacticDiagnostics(),opts.ignoreFileResolutionErrors),res.diagnostics.length>0)return opts.forceEmit&&(pxt.debug("syntactic errors, forcing emit"),pxtc.compileBinary(program,opts,res,entryPoint)),res;res.diagnostics=patchUpDiagnostics(program.getOptionsDiagnostics().concat(pxtc.Util.toArray(program.getGlobalDiagnostics())),opts.ignoreFileResolutionErrors);const semStart=pxtc.U.cpuUs();0==res.diagnostics.length&&(res.diagnostics=patchUpDiagnostics(program.getSemanticDiagnostics(),opts.ignoreFileResolutionErrors));const emitStart=pxtc.U.cpuUs();if(res.times["typescript-syn"]=semStart-startTime,res.times["typescript-sem"]=emitStart-semStart,res.times.typescript=emitStart-startTime,opts.ast&&(res.ast=program),opts.ast||opts.forceEmit||0==res.diagnostics.length){const e=pxtc.compileBinary(program,opts,res,entryPoint);res.times.compilebinary=pxtc.U.cpuUs()-emitStart,res.diagnostics=res.diagnostics.concat(patchUpDiagnostics(e.diagnostics))}0==res.diagnostics.length&&(res.success=!0);for(let e of opts.sourceFiles)pxtc.Util.startsWith(e,"built/")&&(res.outfiles[e.slice(6)]=opts.fileSystem[e]);return res.times.all=pxtc.U.cpuUs()-startTime,pxt.tickEvent("compile",res.times),res}function decompile(e,t,n,r=!1){let i=e.getSourceFile(n);pxtc.annotate(e,n,pxtc.target||pxt.appTarget&&pxt.appTarget.compile);const a=pxtc.getApiInfo(e,t.jres),o=pxtc.getBlocksInfo(a,t.bannedCategories),s={snippetMode:t.snippetMode||!1,alwaysEmitOnStart:t.alwaysDecompileOnStart,includeGreyBlockMessages:r,generateSourceMap:!!t.ast,allowedArgumentTypes:t.allowedArgumentTypes||["number","boolean","string"],errorOnGreyBlocks:!!t.errorOnGreyBlocks},[c,l]=pxtc.decompiler.buildRenameMap(e,i,{declarations:"variables",takenNames:{}});return pxtc.decompiler.decompileToBlocks(o,i,s,c)}function decompileSnippets(e,t,n=!1){const r=pxtc.getApiInfo(e,t.jres),i=pxtc.getBlocksInfo(r,t.bannedCategories),a=new pxtc.decompiler.RenameMap([]),o={snippetMode:t.snippetMode||!1,alwaysEmitOnStart:t.alwaysDecompileOnStart,includeGreyBlockMessages:n,generateSourceMap:!!t.ast,allowedArgumentTypes:t.allowedArgumentTypes||["number","boolean","string"],errorOnGreyBlocks:!!t.errorOnGreyBlocks};let s;const c=[];if(t.sourceTexts)for(let e=0;e<t.sourceTexts.length;e++){t.fileSystem[pxt.MAIN_TS]=t.sourceTexts[e],t.fileSystem[pxt.MAIN_BLOCKS]="";let n=getTSProgram(t,s);const r=n.getSourceFile(pxt.MAIN_TS),l=pxtc.decompiler.decompileToBlocks(i,r,o,a);c.push(l.outfiles[pxt.MAIN_BLOCKS]),s=n}return c}function getTSProgram(e,t){let n={},r={};for(let t in e.fileSystem)r[normalizePath(t)]=e.fileSystem[t];let i=getTsCompilerOptions(e),a={getSourceFile:(e,t,n)=>{e=normalizePath(e);let i="";return r.hasOwnProperty(e)?i=r[e]:n&&n("File not found: "+e),null==i&&(n("File not found: "+e),i=""),ts.createSourceFile(e,i,t,true)},fileExists:e=>(e=normalizePath(e),r.hasOwnProperty(e)),getCanonicalFileName:e=>e,getDefaultLibFileName:()=>"no-default-lib.d.ts",writeFile:(e,t,r,i)=>{n[e]=t},getCurrentDirectory:()=>".",useCaseSensitiveFileNames:()=>!0,getNewLine:()=>"\n",readFile:e=>(e=normalizePath(e),r[e]||""),directoryExists:e=>!0,getDirectories:()=>[]};e.sourceFiles||(e.sourceFiles=Object.keys(e.fileSystem));let o=e.sourceFiles.filter((e=>pxtc.U.endsWith(e,".ts"))),s=o.filter((e=>e!=pxt.MAIN_TS)),c=!1;o.length>s.length&&(o=s,o.push(pxt.MAIN_TS),c=!0);const l=o.indexOf(pxt.TUTORIAL_CODE_STOP);l>=0&&(o.splice(l,1),o.push(pxt.TUTORIAL_CODE_STOP));const u=ts.createProgram(o,i,a,t);return pxtc.annotate(u,pxt.MAIN_TS,pxtc.target||pxt.appTarget&&pxt.appTarget.compile),u}function normalizePath(e){e=e.replace(/\\/g,"/");const t=[];return e.split("/").forEach((e=>{".."===e&&t.length?t.pop():"."!==e&&t.push(e)})),t.join("/")}pxtc.getTsCompilerOptions=getTsCompilerOptions,pxtc.nodeLocationInfo=nodeLocationInfo,pxtc.patchUpDiagnostics=patchUpDiagnostics,pxtc.py2tsIfNecessary=py2tsIfNecessary,pxtc.storeGeneratedFiles=storeGeneratedFiles,pxtc.runConversionsAndStoreResults=runConversionsAndStoreResults,pxtc.timesToMs=timesToMs,pxtc.isPxtModulesFilename=isPxtModulesFilename,pxtc.compile=compile,pxtc.decompile=decompile,pxtc.decompileSnippets=decompileSnippets,pxtc.getTSProgram=getTSProgram})(pxtc=ts.pxtc||(ts.pxtc={}))}(ts||(ts={})),function(e){!function(t){const n=["type","offset","vaddr","paddr","filesz","memsz","flags","align"],r=e.HF2.read32,i=e.HF2.read16,a=4096;t.parse=function(t){1179403647!=r(t,0)&&e.U.userError("no magic"),1!=t[4]&&e.U.userError("not 32 bit"),1!=t[5]&&e.U.userError("not little endian"),1!=t[6]&&e.U.userError("bad version"),2!=i(t,16)&&e.U.userError("wrong object type"),40!=i(t,18)&&e.U.userError("not ARM");let o=r(t,28);r(t,32),0==o&&e.U.userError("expecting program headers");let s=i(t,42),c=i(t,44),l=e.U.range(c).map((e=>function(e){let i={},a=e;for(let a of n)i[a]=r(t,e),e+=4;let o=i;return o._filepos=a,o}(o+e*s))),u=t.length+1;for(;15&u;)u++;let d=0;for(let e of l)1==e.type&&(d=Math.max(d,e.vaddr+e.memsz));let p=(d+a-1&-4096)+(4095&u),f=-1;for(let e of l)4==e.type&&(f=e._filepos);return{imageMemStart:p,imageFileStart:u,phOffset:f,template:t}},t.patch=function(t,r){let i=new Uint8Array(t.imageFileStart+r.length);return i.fill(0),e.U.memcpy(i,0,t.template),e.U.memcpy(i,t.imageFileStart,r),function(t,r){let i=r._filepos;for(let a of n)e.HF2.write32(t,i,r[a]||0),i+=4}(i,{_filepos:t.phOffset,type:1,offset:t.imageFileStart,vaddr:t.imageMemStart,paddr:t.imageMemStart,filesz:r.length,memsz:r.length,flags:5,align:a}),i}}(e.elf||(e.elf={}))}(pxt||(pxt={})),function(e){!function(t){const n=e.HF2.read32,r=e.HF2.read16,i=[{name:"esp32",chipId:0,memmap:[{from:0,to:65536,id:"PADDING"},{from:1061158912,to:1065353216,id:"DROM"},{from:1065353216,to:1069547520,id:"EXTRAM_DATA"},{from:1073217536,to:1073225728,id:"RTC_DRAM"},{from:1073283072,to:1073741824,id:"BYTE_ACCESSIBLE"},{from:1073405952,to:1073741824,id:"DRAM"},{from:1073610752,to:1073741820,id:"DIRAM_DRAM"},{from:1073741824,to:1074200576,id:"IROM"},{from:1074200576,to:1074233344,id:"CACHE_PRO"},{from:1074233344,to:1074266112,id:"CACHE_APP"},{from:1074266112,to:1074397184,id:"IRAM"},{from:1074397184,to:1074528252,id:"DIRAM_IRAM"},{from:1074528256,to:1074536448,id:"RTC_IRAM"},{from:1074593792,to:1077936128,id:"IROM"},{from:1342177280,to:1342185472,id:"RTC_DATA"}]},{name:"esp32-s2",chipId:2,memmap:[{from:0,to:65536,id:"PADDING"},{from:1056964608,to:1073217536,id:"DROM"},{from:1062207488,to:1073217536,id:"EXTRAM_DATA"},{from:1073340416,to:1073348608,id:"RTC_DRAM"},{from:1073340416,to:1073741824,id:"BYTE_ACCESSIBLE"},{from:1073340416,to:1074208768,id:"MEM_INTERNAL"},{from:1073414144,to:1073741824,id:"DRAM"},{from:1073741824,to:1073848576,id:"IROM_MASK"},{from:1073872896,to:1074200576,id:"IRAM"},{from:1074200576,to:1074208768,id:"RTC_IRAM"},{from:1074266112,to:1082130432,id:"IROM"},{from:1342177280,to:1342185472,id:"RTC_DATA"}]},{name:"esp32-s3",chipId:4,memmap:[{from:0,to:65536,id:"PADDING"},{from:1006632960,to:1023410176,id:"DROM"},{from:1023410176,to:1040187392,id:"EXTRAM_DATA"},{from:1611653120,to:1611661312,id:"RTC_DRAM"},{from:1070104576,to:1070596096,id:"BYTE_ACCESSIBLE"},{from:1070104576,to:1077813248,id:"MEM_INTERNAL"},{from:1070104576,to:1070596096,id:"DRAM"},{from:1073741824,to:1073848576,id:"IROM_MASK"},{from:1077346304,to:1077805056,id:"IRAM"},{from:1611653120,to:1611661312,id:"RTC_IRAM"},{from:1107296256,to:1115684864,id:"IROM"},{from:1342177280,to:1342185472,id:"RTC_DATA"}]},{name:"esp32-c3",chipId:5,memmap:[{from:0,to:65536,id:"PADDING"},{from:1006632960,to:1015021568,id:"DROM"},{from:1070071808,to:1070465024,id:"DRAM"},{from:1070104576,to:1070596096,id:"BYTE_ACCESSIBLE"},{from:1072693248,to:1072824320,id:"DROM_MASK"},{from:1073741824,to:1074135040,id:"IROM_MASK"},{from:1107296256,to:1115684864,id:"IROM"},{from:1077395456,to:1077805056,id:"IRAM"},{from:1342177280,to:1342185472,id:"RTC_IRAM"},{from:1342177280,to:1342185472,id:"RTC_DRAM"},{from:1611653120,to:1611661312,id:"MEM_INTERNAL2"}]}];function a(t){return`0x${t.addr.toString(16)} 0x${t.data.length.toString(16)} bytes; ${t.isDROM?"drom ":""}${t.isMapped?"mapped ":""}${e.U.toHex(t.data.slice(0,20))}...`}function o(t){if(233!=t[0])throw new Error("ESP: invalid magic: "+t[0]);let a=24;const o=r(t,12),s=i.find((e=>e.chipId==o));if(!s)throw new Error("ESP: unknown chipid: "+o);const c={header:t.slice(0,a),chipName:s.name,segments:[]},l=t[1];for(let r=0;r<l;++r){const r=n(t,a),i=n(t,a+4);a+=8;const o=t.slice(a,a+i);if(o.length!=i)throw new Error("too short file");if(a+=i,u(r,"PADDING"))continue;const s=c.segments.filter((e=>e.addr+e.data.length==r))[0];s?s.data=e.U.uint8ArrayConcat([s.data,o]):c.segments.push({addr:r,isMapped:u(r,"DROM")||u(r,"IROM"),isDROM:u(r,"DROM"),data:o})}return c;function u(e,t){return s.memmap.some((n=>n.id==t&&n.from<=e&&e<=n.to))}}function s(t){const n=e.U.flatClone(t);return n.segments=n.segments.map(e.U.flatClone),n}t.toBuffer=function(t,n=!0){let r=(t=function(t){const n=65535;(t=s(t)).segments.sort(((e,t)=>e.addr-t.addr)),e.debug("esp padding:\n"+t.segments.map(a).join("\n")+"\n");const r=t.segments.filter((e=>e.isMapped)),i=t.segments.filter((e=>!e.isMapped));t.segments=[];let o=t.header.length;for(const t of r){const r=t.addr+t.data.length&n;if(r<36){const n=new Uint8Array(36-r);t.data=e.U.uint8ArrayConcat([t.data,n])}}for(;r.length>0;){let e=r[0];const i=c(e);if(i>0)e=l(i);else{if((o+8&n)!=(e.addr&n))throw new Error(`pad oops 0 ${o}+8 != ${e.addr} (mod mask)`);r.shift()}if(t.segments.push(e),o+=8+e.data.length,3&o)throw new Error("pad oops 1")}return t.segments=t.segments.concat(i),e.debug("esp padded:\n"+t.segments.map(a).join("\n")+"\n"),t;function c(e){let t=(e.addr-8&n)-o&n;return 0==t?0:(t-=8,t<0&&(t+=65536),t)}function l(e){if(!i.length||e<=8)return{addr:0,isMapped:!1,isDROM:!1,data:new Uint8Array(e)};const t=i[0],n={addr:t.addr,isMapped:t.isMapped,isDROM:t.isDROM,data:t.data.slice(0,e)};return t.data=t.data.slice(e),t.addr+=n.data.length,0==t.data.length&&i.shift(),n}}(t)).header.length;for(const e of t.segments)r+=8+e.data.length;r=r+16&-16;let i=new Uint8Array(r);i.set(t.header),i[1]=t.segments.length;let o=t.header.length,c=239;for(const n of t.segments){e.HF2.write32(i,o,n.addr),e.HF2.write32(i,o+4,n.data.length),i.set(n.data,o+8),o+=8+n.data.length;for(let e=0;e<n.data.length;++e)c^=n.data[e]}if(i[i.length-1]=c,n){i[23]=1;const t=ts.pxtc.BrowserImpl.sha256buffer(i);i=e.U.uint8ArrayConcat([i,e.U.fromHex(t)])}else i[23]=0;return i},t.parseBuffer=o,t.parseB64=function(t){return o(e.U.stringToUint8Array(atob(t.join(""))))},t.cloneStruct=s}(e.esp||(e.esp={}))}(pxt||(pxt={})),function(e){!function(t){let n;!function(e){e[e.None=0]="None",e[e.Whitespace=1]="Whitespace",e[e.Identifier=2]="Identifier",e[e.Keyword=3]="Keyword",e[e.Operator=4]="Operator",e[e.CommentLine=5]="CommentLine",e[e.CommentBlock=6]="CommentBlock",e[e.NewLine=7]="NewLine",e[e.Literal=8]="Literal",e[e.Tree=9]="Tree",e[e.Block=10]="Block",e[e.EOF=11]="EOF"}(n||(n={}));let r="";let i=e.SyntaxKind;function a(e){switch(e){case i.CommaToken:return 2;case i.EqualsToken:case i.PlusEqualsToken:case i.MinusEqualsToken:case i.AsteriskEqualsToken:case i.AsteriskAsteriskEqualsToken:case i.SlashEqualsToken:case i.PercentEqualsToken:case i.LessThanLessThanEqualsToken:case i.GreaterThanGreaterThanEqualsToken:case i.GreaterThanGreaterThanGreaterThanEqualsToken:case i.AmpersandEqualsToken:case i.BarEqualsToken:case i.CaretEqualsToken:return 5;case i.QuestionToken:case i.ColonToken:return 7;case i.BarBarToken:return 10;case i.AmpersandAmpersandToken:return 20;case i.BarToken:return 30;case i.CaretToken:return 40;case i.AmpersandToken:return 50;case i.EqualsEqualsToken:case i.ExclamationEqualsToken:case i.EqualsEqualsEqualsToken:case i.ExclamationEqualsEqualsToken:return 60;case i.LessThanToken:case i.GreaterThanToken:case i.LessThanEqualsToken:case i.GreaterThanEqualsToken:case i.InstanceOfKeyword:case i.InKeyword:case i.AsKeyword:return 70;case i.LessThanLessThanToken:case i.GreaterThanGreaterThanToken:case i.GreaterThanGreaterThanGreaterThanToken:return 80;case i.PlusToken:case i.MinusToken:return 90;case i.AsteriskToken:case i.SlashToken:case i.PercentToken:return 100;case i.AsteriskAsteriskToken:return 101;case i.DotToken:return 120;default:return 0}}function o(e){switch(e){case i.EndOfFileToken:return n.EOF;case i.SingleLineCommentTrivia:return n.CommentLine;case i.MultiLineCommentTrivia:return n.CommentBlock;case i.NewLineTrivia:return n.NewLine;case i.WhitespaceTrivia:return n.Whitespace;case i.ShebangTrivia:case i.ConflictMarkerTrivia:return n.CommentBlock;case i.NumericLiteral:case i.StringLiteral:case i.RegularExpressionLiteral:case i.NoSubstitutionTemplateLiteral:case i.TemplateHead:case i.TemplateMiddle:case i.TemplateTail:return n.Literal;case i.Identifier:return n.Identifier;default:return e<i.Identifier?n.Operator:n.Keyword}}function s(e,t){for(;e[t]&&e[t].kind==n.Whitespace;)t++;return t}function c(){return{kind:n.EOF,synKind:i.EndOfFileToken,pos:0,lineNo:0,text:""}}function l(e,t){return{kind:n.Whitespace,synKind:i.WhitespaceTrivia,pos:e.pos-t.length,lineNo:e.lineNo,text:t}}function u(e){return{kind:n.Block,synKind:i.OpenBraceToken,pos:e[0].pos,lineNo:e[0].lineNo,stmts:[{tokens:e}],text:"{",endToken:null}}function d(e){if(!e)return!1;switch(e.synKind){case i.IfKeyword:case i.ElseKeyword:case i.LetKeyword:case i.ConstKeyword:case i.VarKeyword:case i.DoKeyword:case i.WhileKeyword:case i.SwitchKeyword:case i.CaseKeyword:case i.DefaultKeyword:case i.ForKeyword:case i.ReturnKeyword:case i.BreakKeyword:case i.ContinueKeyword:case i.TryKeyword:case i.CatchKeyword:case i.FinallyKeyword:case i.DeleteKeyword:case i.FunctionKeyword:case i.ClassKeyword:case i.YieldKeyword:case i.DebuggerKeyword:return!0;default:return!1}}function p(e,r,o=null){let s,f=[],_=0,g=!1;for(e=e.concat([c()]);e[_].kind!=n.EOF;){let n=_;C(),t.Util.assert(_>n,`Error at ${e[_].text}`),h(e.slice(n,_))}return f;function h(e){if(r&&(e=m(e)),0==e.length)return;e.forEach(v),e=y(e);if(r&&f.length>0){let n=f[f.length-1].tokens[0].synKind,r=e[0].synKind;if(n==i.IfKeyword&&r==i.ElseKeyword||n==i.TryKeyword&&r==i.CatchKeyword||n==i.TryKeyword&&r==i.FinallyKeyword||n==i.CatchKeyword&&r==i.FinallyKeyword)return e.unshift(l(e[0]," ")),void t.Util.pushRange(f[f.length-1].tokens,e)}f.push({tokens:e})}function y(e){let t=[],r=0;for(;r<e.length;)if(e[r].blockSpanLength){let o=e.slice(r,r+e[r].blockSpanLength),s=!!o[0].blockSpanIsVirtual;delete o[0].blockSpanLength,delete o[0].blockSpanIsVirtual,r+=o.length,o=y(o),s?t.push((a=o,{kind:n.Tree,synKind:i.WhitespaceTrivia,pos:a[0].pos,lineNo:a[0].lineNo,children:a,endToken:null,text:""})):(t.push(l(o[0]," ")),t.push(u(m(o))))}else t.push(e[r++]);var a;return t}function v(e){if(e.kind==n.Tree){let n=e;n.children=t.Util.concat(p(n.children,!1,n).map((e=>e.tokens)))}}function b(t=!1){for(;;)switch(_++,e[_].kind){case n.Whitespace:case n.CommentBlock:case n.CommentLine:break;case n.NewLine:if(t)break;break;default:return}}function x(){for(;e[_].kind==n.Whitespace;)_++;e[_].kind==n.NewLine&&_++}function k(){for(;;)switch(_++,e[_].kind){case n.EOF:return;case n.Tree:if(e[_].synKind==i.OpenBraceToken)return _--,void T()}}function S(){t.Util.assert(e[_].synKind==i.OpenBraceToken);let r=e[_];t.Util.assert(r.kind==n.Tree);let a=e[_];a.stmts=p(r.children,!0,s),delete r.children,a.kind=n.Block,_++,g=!0}function T(){let t=_+1;b(),e[_].synKind==i.OpenBraceToken?(S(),x()):(C(),e[t].blockSpanLength=_-t)}function C(){for(;;){let c=e[_],l=_;if(s=c,g=!1,c.kind==n.EOF)return;if(r&&c.synKind==i.SemicolonToken)return _++,void x();if(c.synKind==i.EqualsGreaterThanToken){if(b(),e[_].synKind==i.OpenBraceToken){S();continue}{let t=_;C();let r=_;for(;e[r].kind==n.NewLine;)r--;return e[t].blockSpanLength=r-t,void(e[t].blockSpanIsVirtual=!0)}}if(r&&a(c.synKind)){let t=_;if(b(),!d(e[_]))continue;_=t}if(r&&c.kind==n.NewLine){if(b(),c=e[_],a(c.synKind)&&c.synKind!=i.PlusToken&&c.synKind!=i.MinusToken)continue;return void(_=l+1)}if(c.synKind==i.OpenBraceToken&&o&&o.synKind==i.ClassKeyword){let t=_-1;for(;t>=0&&e[t].kind==n.Whitespace;)t--;if(t<0||e[t].synKind!=i.EqualsToken)return _--,void T()}switch(t.Util.assert(l==_),c.synKind){case i.ForKeyword:case i.WhileKeyword:case i.IfKeyword:case i.CatchKeyword:if(b(),e[_].synKind!=i.OpenParenToken)continue;return void T();case i.DoKeyword:if(T(),_--,b(),e[_].synKind==i.WhileKeyword){_++;continue}return;case i.ElseKeyword:if(b(),e[_].synKind==i.IfKeyword)continue;return _=l,void T();case i.TryKeyword:case i.FinallyKeyword:return void T();case i.ClassKeyword:case i.NamespaceKeyword:case i.ModuleKeyword:case i.InterfaceKeyword:case i.FunctionKeyword:return void k()}t.Util.assert(!g,"forgot continue/return after expectBlock"),_++}}}function f(e){return e&&(e.kind==n.Whitespace||e.kind==n.NewLine)}function _(e){let t=[],r=!1;for(let i=0;i<e.length;++i)r&&(i=s(e,i)),e[i]&&(t.push(e[i]),r=e[i].kind==n.NewLine);return t}function m(e){for(e=e.slice(0);f(e[0]);)e.shift();for(;f(e[e.length-1]);)e.pop();return e}function g(e,t){if(t.synKind==i.NoSubstitutionTemplateLiteral&&/^`[\s\.#01]*`$/.test(t.text)){let n=t.text.slice(1,t.text.length-1).split("\n").map((e=>e.replace(/\s/g,""))).filter((e=>!!e));if(n.length<4||n.length>5)return;let r=Math.floor((Math.max(...n.map((e=>e.length)))+2)/5);r<=0&&(r=1);let i="`\n";for(let t=0;t<5;++t){let a=n[t]||"";for(;a.length<5*r;)a+=".";a=a.replace(/0/g,"."),a=a.replace(/1/g,"#"),a=a.replace(/...../g,(e=>"/"+e)),i+=e+a.replace(/./g,(e=>" "+e)).replace(/\//g," ").slice(3)+"\n"}i+=e+"`",t.text=i}}t.toStr=function e(t){return Array.isArray(t)?"[[ "+t.map(e).join(" ")+" ]]":"string"==typeof t.text?JSON.stringify(t.text):t+""},t.format=function(t,u){let d=function(t){r=t;let a=e.createScanner(e.ScriptTarget.Latest,!1,e.LanguageVariant.Standard,t,(e=>{let t=a.getTextPos();console.log("scanner error",t,e.message)})),s=[],c=0,l=-1;for(;;){let e=a.scan();if(e==i.CloseBraceToken&&c==l&&(l=-1,e=a.reScanTemplateToken()),e==i.SlashEqualsToken){let t=a.reScanSlashToken();t==i.RegularExpressionLiteral&&(e=t)}e==i.GreaterThanToken&&(e=a.reScanGreaterToken());let t={kind:o(e),synKind:e,lineNo:0,pos:a.getTokenPos(),text:a.getTokenText()};if(e==i.OpenBraceToken&&c++,e==i.CloseBraceToken&&--c<0&&(c=-1e7),s.push(t),e!=i.TemplateHead&&e!=i.TemplateMiddle||(l=c),t.kind==n.EOF)break}return{tokens:s,braceBalance:c}}(t).tokens;d=function(e,t){let r=[],a=!0,o=1;for(let c=0;c<e.length;++c){if(a){let a=c;if(c=s(e,c),e[c].kind==n.NewLine){let a=!1;t>=0&&e[c].pos>=t&&(t=-1,a=!0),r.push({text:"",kind:n.CommentLine,pos:e[c].pos,lineNo:o,synKind:i.SingleLineCommentTrivia,isCursor:a})}else c=a}r.push(e[c]),e[c].lineNo=o,e[c].kind==n.NewLine?(a=!0,o++):a=!1,t>=0&&e[c].pos>=t&&(t=-1)}return r}(d,u),d=function(e){let t=[];t.push({synKind:i.EndOfFileToken,token:{children:[]}});let r=(e,r)=>{let i=e;i.children=[],i.kind=n.Tree,t.push({synKind:r,token:i})};for(let a=0;a<e.length;++a){let o=e[a],s=t[t.length-1];switch(s.token.children.push(o),o.kind){case n.Operator:switch(o.synKind){case i.OpenBraceToken:case i.OpenParenToken:case i.OpenBracketToken:r(o,o.synKind+1);break;case i.CloseBraceToken:case i.CloseParenToken:case i.CloseBracketToken:for(s.token.children.pop();;){if(s=t.pop(),s.synKind==o.synKind){s.token.endToken=o;break}if(0==t.length||s.synKind==i.CloseBraceToken){t.push(s);break}}}}}return t[0].token.children}(d);let f=p(d,!0),m="",h="",y=-1,v=0;return f.forEach(k),f.forEach((e=>e.tokens.forEach(b))),-1==y&&(y=h.length),{formatted:h,pos:y};function b(e){if(e.kind==n.Tree){let t=e;e.synKind,i.OpenBraceToken,t.children.forEach(b)}else e.kind==n.Block&&e.stmts.forEach((e=>e.tokens.forEach(b)))}function x(e,t){if(v==e.lineNo)t();else{v=e.lineNo;let n=m;m+=" ",t(),m=n}}function k(e){let t=_(e.tokens);1!=t.length||t[0].isCursor||""!=t[0].text?(h+=m,x(t[0],(()=>{T(t)})),"\n"!=h[h.length-1]&&(h+="\n")):h+="\n"}function S(e){-1==y&&e.pos+e.text.length>=u&&(y=h.length+(u-e.pos)),h+=e.text}function T(e){e=function(e){let t=[],r=0,o=c();for(e=e.concat([c()]);r<e.length;){r=s(e,r);let c=e[r];if(c.kind==n.EOF)break;let d=s(e,r+1);if(c.kind==n.NewLine&&e[d].synKind==i.OpenBraceToken){r=d;continue}let p=!0,f=0==t.length?(u=c,{kind:n.NewLine,synKind:i.NewLineTrivia,pos:u.pos,lineNo:u.lineNo,text:"\n"}):t[t.length-1];switch(f.synKind){case i.ExclamationToken:case i.TildeToken:case i.DotToken:p=!1;break;case i.PlusToken:case i.MinusToken:case i.PlusPlusToken:case i.MinusMinusToken:f.isPrefix&&(p=!1)}switch(c.synKind){case i.DotToken:case i.CommaToken:case i.NewLineTrivia:case i.ColonToken:case i.SemicolonToken:case i.OpenBracketToken:p=!1;break;case i.PlusPlusToken:case i.MinusMinusToken:f.kind!=n.Tree&&f.kind!=n.Identifier&&f.kind!=n.Keyword||(p=!1);case i.PlusToken:case i.MinusToken:(o.kind==n.EOF||a(o.synKind)||o.synKind==i.SemicolonToken)&&(c.isPrefix=!0);break;case i.OpenParenToken:if(f.kind==n.Identifier&&(p=!1),f.kind==n.Keyword)switch(f.synKind){case i.IfKeyword:case i.ForKeyword:case i.WhileKeyword:case i.SwitchKeyword:case i.ReturnKeyword:case i.ThrowKeyword:case i.CatchKeyword:break;default:p=!1}}f.kind==n.NewLine&&(p=!1),p&&t.push(l(c," ")),t.push(c),c.kind!=n.NewLine&&(o=c),r++}var u;return t}(e);for(let t=0;t<e.length;++t){let r=e[t];switch(g(m,r),S(r),r.kind){case n.Tree:let i=r;x(r,(()=>{T(_(i.children))})),i.endToken&&S(i.endToken);break;case n.Block:let a=r;0==a.stmts.length?h+=" ":(h+="\n",a.stmts.forEach(k),h+=m.slice(4)),a.endToken?S(a.endToken):h+="}";break;case n.NewLine:if(e[t+1]&&e[t+1].kind==n.CommentLine&&""==e[t+1].text&&!e[t+1].isCursor)break;t==e.length-1?h+=m.slice(4):h+=m;break;case n.Whitespace:}}}}}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){let n;function r(e,n){if(!n.packedSource)return;let r=e.currPtr+4096&-256,i=new Uint8Array(256);for(let a=0;a<n.packedSource.length;a+=256){for(let e=0;e<256;++e)i[e]=n.packedSource.charCodeAt(a+e);t.UF2.writeBytes(e,r,i,t.UF2.UF2_FLAG_NOFLASH),r+=256}}!function(e){e.asmTotalSource="";let n={},i=[];let a={commBase:0,funcInfo:{},codeStartIdx:-1,codePaddingSize:0,sha:null,codeStartAddrPadded:void 0,hexlines:void 0,jmpStartAddr:void 0,jmpStartIdx:void 0,codeStartAddr:void 0,elfInfo:void 0,espInfo:void 0};function o(e){let n="",r=0;for(;r<e.length;r+=2)n=e[r]+e[r+1]+n;return t.assert(r==e.length),n}function s(e){if(!(e=e.replace(/^[\s:]/,"")))return[];let n=[];if(e.replace(/([a-f0-9][a-f0-9])/gi,(e=>(n.push(parseInt(e,16)),""))))throw t.oops("bad bytes "+e);return n}function c(e){return e.flashCodeAlign||1024}e.getCommBase=function(){return a.commBase},e.getStartAddress=function(){return a.codeStartAddrPadded},e.setupInlineAssembly=function(r){n={};let i=r.sourceFiles.filter((e=>t.U.endsWith(e,".asm")));e.asmTotalSource="";let a=0;for(let t of i){let i=r.fileSystem[t];i.replace(/^\s*(\w+):/gm,((e,t)=>(n[t]=!0,"")));let o=".section code\n@stackmark func\n@scope user"+a+++"\n"+i+"\n@stackempty func\n@scope\n";e.asmTotalSource+=o}},e.parseHexBytes=s,e.parseHexRecord=function(e){let t=s(e);return{len:t[0],addr:t[1]<<8|t[2],type:t[3],data:t.slice(4,t.length-1),checksum:t[t.length-1]}},e.flashCodeAlign=c;const l="0108010842424242010801083ed8e98d";function u(e){return a.funcInfo[e]}function d(){let e=a.sha?a.sha.slice(0,16):"";for(;e.length<16;)e+="0";return e.toUpperCase()}function p(e){let t=0,n=":";return e.forEach((e=>t+=e)),e.push(255&-t),e.forEach((e=>n+=("0"+e.toString(16)).slice(-2))),n.toUpperCase()}e.setupFor=function(e,n){if(a=i.find((e=>e.sha==n.sha)),a)return;a={commBase:0,funcInfo:{},codeStartIdx:-1,codePaddingSize:0,sha:null,codeStartAddrPadded:void 0,hexlines:void 0,jmpStartAddr:void 0,jmpStartIdx:void 0,codeStartAddr:void 0,elfInfo:void 0,espInfo:void 0},i.length>10&&(i=[]),i.push(a);let r=n.functions;a.commBase=n.commBase||0,a.sha=n.sha;const u=n.hexinfo.hex;if(a.hexlines=u,t.target.nativeType==t.NATIVE_TYPE_VM){a.codeStartAddr=0,a.codeStartAddrPadded=0,a.jmpStartAddr=-1,a.jmpStartIdx=-1;for(let e of r)a.funcInfo[e.name]=e,e.value=16777215;if(t.target.useESP){const e=pxt.esp.parseB64(u),r=t.U.fromHex(l),i=(e,t)=>{for(let n=0;n<r.length;++n)if(e[t+n]!=r[n])return!1;return!0},o=e.segments.filter((e=>e.isDROM));t.U.assert(1==o.length);let s=!1;const c=o[0];a.codeStartAddr=c.addr+c.data.length,a.codeStartAddrPadded=a.codeStartAddr+255&-256,a.codePaddingSize=a.codeStartAddrPadded-a.codeStartAddr,pxt.debug(`user code start: 0x${a.codeStartAddrPadded.toString(16)}; dromlen=${c.data.length} pad=${a.codePaddingSize}`);for(let e=0;e<c.data.length;e+=32)if(i(c.data,e)){s=!0,e+=r.length;const t=e;for(let t of n.vmPointers||[])"0"!=t&&(t=t.replace(/^&/,""),a.funcInfo[t]={name:t,argsFmt:[],value:pxt.HF2.read32(c.data,e)},e+=4);pxt.HF2.write32(c.data,t,a.codeStartAddrPadded);break}t.U.assert(s||0==(n.vmPointers||[]).length),a.espInfo=e,a.codeStartAddrPadded=0}return}if(u.length<=2){const e=t.U.fromHex(u[0]);if(e[2]<=2&&96==e[3]){const t=1610612736,n=4096,r=e.length+n-1&~(n-1);a.elfInfo={template:e,imageMemStart:t+r,imageFileStart:r,phOffset:-1e3}}else a.elfInfo=pxt.elf.parse(e);a.codeStartAddr=a.elfInfo.imageMemStart,a.codeStartAddrPadded=a.elfInfo.imageMemStart;let n=u[0].indexOf(l);return n<0&&t.oops("no jmp table in elf"),a.jmpStartAddr=n/2,a.jmpStartIdx=-1,h(u[0].slice(n+32,n+32+8*r.length+16)),void y()}!function(e){for(let n=0;n<e.length;++n)if("2"==e[n][8]){let r=/^:02....02(....)..$/.exec(e[n]);t.U.assert(!!r);let i=16*parseInt(r[1],16);t.U.assert(0==(65535&i)),e[n]=p([2,0,0,4,0,i>>16])}}(u);let d=0,f="0000",_=0,m=0;a.codeStartAddr=0;let g=()=>{if(!a.codeStartAddr){let n=s(u[m]),r=16-(_+n[0]&15)&15;if(r)if(15&n[2]){let e=_+n[0],t=[r,e>>8,255&e,0];for(let e=0;e<r;++e)t.push(0);m++,u.splice(m,0,p(t)),a.codeStartAddr=e+r}else{if(16!=n[0]){for(n.pop(),n[0]=16;n.length<20;)n.push(0);u[m]=p(n)}a.codeStartAddr=_+16}else a.codeStartAddr=_+n[0];a.codeStartIdx=m+1;const i=c(e);a.codeStartAddrPadded=(a.codeStartAddr&~(i-1))+i;const o=a.codeStartAddrPadded-a.codeStartAddr;t.assert(0==(15&o)),a.codePaddingSize=o}};for(;d<u.length;++d){let t=/:02000004(....)/.exec(u[d]);if(t&&(f=t[1]),t=/^:..(....)00/.exec(u[d]),t){let n=parseInt(f+t[1],16);!e.flashUsableEnd&&_&&n-_>65536&&g(),e.flashUsableEnd&&n>=e.flashUsableEnd&&g(),m=d,_=n}/^:00000001/.test(u[d])&&g(),t=/^:10....000108010842424242010801083ED8E98D/.exec(u[d]),t&&(a.jmpStartAddr=_,a.jmpStartIdx=d)}pxt.debug(`code start: ${a.codeStartAddrPadded}, jmptbl: ${a.jmpStartAddr}`),a.jmpStartAddr||t.oops("No hex start"),a.codeStartAddr||t.oops("No hex end"),a.funcInfo={};for(let e=a.jmpStartIdx+1;e<u.length;++e){let t=/^:..(....)00(.{4,})/.exec(u[e]);if(t&&(h(t[2]),0==r.length))break}return void y();function h(n){let i=e.shortPointers?4:8;for(;n.length>=i;){let s=n.slice(0,i),c=parseInt(o(s),16);n=n.slice(i);let l=r.shift();if(!l)break;a.funcInfo[l.name]=l,c||t.U.oops("No value for "+l.name+" / "+s),0==l.argsFmt.length?c^=1:e.runtimeIsARM||e.nativeType!=t.NATIVE_TYPE_THUMB||1&c||t.U.oops("Non-thumb addr for "+l.name+" / "+s),l.value=c}}function y(){r.length&&t.oops("premature EOF in hex file; missing: "+r.map((e=>e.name)).join(", "))}},e.validateShim=function(e,r,i,a,o){if("TD_ID"==r||"TD_NOOP"==r||"ENUM_GET"==r)return;if(t.U.lookup(n,r))return;let s=`${e}(...) (shim=${r})`,c=u(r);if(c){a?"V"==c.argsFmt[0]&&t.U.userError("expecting function for "+s):"V"!=c.argsFmt[0]&&t.U.userError("expecting procedure for "+s);for(let e=0;e<o.length;++e){c.argsFmt[e+1]||t.U.userError("excessive parameters passed to "+s)}o.length!=c.argsFmt.length-1&&t.U.userError(`not enough arguments for ${s} (got ${o.length}; fmt=${c.argsFmt.join(",")})`)}else t.U.userError("function not found: "+s)},e.lookupFunc=u,e.lookupFunctionAddr=function(e){if("_pxt_comm_base"==e)return a.commBase;let t=u(e);return t?t.value:null},e.hexTemplateHash=d,e.hexPrelude=function(){return` .startaddr 0x${a.codeStartAddrPadded.toString(16)}\n`},e.hexBytes=p,e.patchHex=function(e,n,i,s){let c=a.hexlines.slice(0,a.codeStartIdx);if(!e.target.useESP){let r=2*n.length+7>>3;t.assert(r<64e3,"program too large, bytes: "+2*n.length),n[17]=r,n[20]=e.commSize}let l=[];for(let e=0;e<a.codePaddingSize>>1;++e)l.push(0);n=l.concat(n);let u=0;function f(e,t){let n=[16,t>>8&255,255&t,0];for(let t=0;t<8;++t)n.push(255&(e[u]||0)),n.push((e[u]||0)>>>8),u++;return n}let _=[16912,0,65535&a.codeStartAddrPadded,a.codeStartAddrPadded>>>16],m=d();for(let e=0;e<4;++e)_.push(parseInt(o(m.slice(4*e,4*e+4)),16));let g=s?t.UF2.newBlockFile(t.target.uf2Family):null;if(a.elfInfo){let r=new Uint8Array(2*n.length);for(let e=0;e<n.length;++e)pxt.HF2.write16(r,2*e,n[e]);let i=pxt.elf.patch(a.elfInfo,r);for(let e=0;e<_.length;++e)pxt.HF2.write16(i,2*e+a.jmpStartAddr,_[e]);if(g&&!e.target.switches.rawELF){let n=e.options.name||"pxt";return n=n.replace(/[^a-zA-Z0-9\-\.]+/g,"_"),g.filename="Projects/"+n+".elf",t.UF2.writeBytes(g,0,i),[t.UF2.serializeFile(g)]}return[t.U.uint8ArrayToString(i)]}if(a.espInfo){const i=pxt.esp.cloneStruct(a.espInfo),o=i.segments.find((e=>e.isDROM));let s=o.data.length;const c=new Uint8Array(s+2*n.length+255&-256);c.set(o.data);for(let e=0;e<n.length;++e)pxt.HF2.write16(c,s,n[e]),s+=2;o.data=c;const l=pxt.esp.toBuffer(i);return g?(t.UF2.writeBytes(g,0,l),r(g,e),[t.UF2.serializeFile(g)]):[t.U.uint8ArrayToString(l)]}if(g){if(t.UF2.writeHex(g,c),t.UF2.writeBytes(g,a.jmpStartAddr,f(_,a.jmpStartIdx).slice(4)),e.checksumBlock){let n=[];for(let t of e.checksumBlock)n.push(255&t,t>>8);t.UF2.writeBytes(g,e.target.flashChecksumAddr,n)}}else c[a.jmpStartIdx]=p(f(_,a.jmpStartAddr)),e.checksumBlock&&t.U.oops("checksum block in HEX not implemented yet");u=0,i&&(c=[]);let h=a.codeStartAddr,y=h-16>>16;for(;u<n.length;)g?t.UF2.writeBytes(g,h,f(n,h).slice(4)):(h>>16!=y&&(y=h>>16,c.push(p([2,0,0,4,y>>8,255&y]))),c.push(p(f(n,h)))),h+=16;if(!i){let e=a.hexlines.slice(a.codeStartIdx);g?t.UF2.writeHex(g,e):t.Util.pushRange(c,e)}if(!g&&e.target.moveHexEof){for(;!c[c.length-1];)c.pop();":00000001FF"==c[c.length-1]&&c.pop()}if(e.packedSource)if(g)r(g,e);else{let t=0;for(let n=0;n<e.packedSource.length;n+=16){let r=[16,t>>8&255,255&t,14];for(let t=0;t<16;++t)r.push(255&(e.packedSource.charCodeAt(n+t)||0));c.push(p(r)),t+=16}}return!g&&e.target.moveHexEof&&c.push(":00000001FF"),g?[t.UF2.serializeFile(g)]:c}}(n=t.hexfile||(t.hexfile={})),t.hexDump=function(e,t=0){function n(e,t=8){let n=e.toString(16);for(;n.length<t;)n="0"+n;return n}let r="";for(let i=0;i<e.length;i+=16){r+=n(t+i)+": ";let a="";for(let t=0;t<16;t++){0==(3&t)&&(r+=" ");let o=e[i+t];null!=o?(r+=n(o,2)+" ",a+=32<=o&&o<127?String.fromCharCode(o):"."):r+=" "}r+=" "+a+"\n"}return r},t.asmline=function(e){return e.indexOf("\n")>=0?(e=e.replace(/^\s*/gm,"").replace(/^(.*)$/gm,((e,t)=>";"==t[0]&&" "==t[1]||/:\*$/.test(t)?t:" "+t)))+"\n":(/(^[\s;])|(:$)/.test(e)||(e=" "+e),e+"\n")},t.firstMethodOffset=function(){return 9};const i=[21078089,22513679,15655169,18636881,19658081,21486649,21919277,20041213,20548751,16180187,18361627,19338023,19772677,16506547,23530697,22998697,21225203,19815283,23679599,19822889,21136133,19540043,21837031,18095489,23924267,23434627,22582379,21584111,22615171,23403001,19640683,19998031,18460439,20105387,17595791,16482043,23199959,18881641,21578371,22765747,20170273,16547639,16434589,21435019,20226751,19506731,21454393,23224541,23431973,23745511];function a(e){let n=32;t.U.assert(t.U.unique(e,(e=>""+e)).length==e.length,"non unique");for(let r=2;;r<<=1){if(n--,r<e.length)continue;let a,o=-1,s=-1;for(let c of i){let i=c<<8|n,l=new Uint16Array(r+t.vtLookups+1);t.U.assert(0==(1&l.length));let u=0,d=[];for(let r of e){t.U.assert(r>0);let e=Math.imul(r,i)>>>n;d.push(e);let a=!1;for(let n=0;n<t.vtLookups;n++){if(!l[e+n]){a=!0,l[e+n]=r;break}u++}if(!a){u=-1;break}}(-1==o||o>u)&&(o=u,s=i,a=l)}if(o>=0)return{mult:s,mapping:a,size:r}}}function o(e,n,r){const i=a(e.itable.map((e=>e.idx)));let o=t.target.shortPointers?".short":".word",s=`\n .balign 4\n${e.id}_VT:\n .short ${4*e.allfields.length+4} ; size in bytes\n .byte ${pxt.ValTypeObject}, ${pxt.VTABLE_MAGIC} ; magic\n ${o} ${e.id}_IfaceVT\n .short ${e.classNo} ; class-id\n .short 0 ; reserved\n .word ${i.mult} ; hash-mult\n`,c=e=>{"0"!=e&&(e+="@fn"),s+=` ${o} ${e}\n`};c("pxt::RefRecord_destroy"),c("pxt::RefRecord_print"),c("pxt::RefRecord_scan"),c("pxt::RefRecord_gcsize");let l=e.toStringMethod;c(l?l.vtLabel():"0");for(let t of e.vtable)c(t.label()+"_nochk");s+=`\n .balign ${t.target.shortPointers?2:4}\n${e.id}_IfaceVT:\n`;const u=2*i.mapping.length;let d="",p=u,f={};for(let t of e.itable){f[t.idx+""]=p;const e=t.proc?t.proc.isGetter()?1:2:0;d+=` .short ${t.idx}, ${e} ; ${t.name}\n`,d+=` .word ${t.proc?t.proc.vtLabel()+"@fn":t.info}\n`,p+=8,t.setProc&&(d+=` .short ${t.idx}, 0 ; set ${t.name}\n`,d+=` .word ${t.setProc.vtLabel()}@fn\n`,p+=8)}d+=" .word 0, 0 ; the end\n",p+=8;let _=i.mapping;for(let e=0;e<_.length;++e)r.itEntries++,_[e]&&r.itFullEntries++;return s+=" .short "+t.U.toArray(_).map(((e,t)=>(f[e+""]||u)-2*t)).join(", ")+"\n",s+=d,s+="\n",s}t.vtLookups=3,t.computeHashMultiplier=a,t.vtableToAsm=o;const s=["GC"];function c(e,r){let i=`\n .short ${e.globalsWords} ; num. globals\n .short 0 ; patched with number of 64 bit words resulting from assembly\n .word _pxt_config_data\n .short 0 ; patched with comm section size\n .short ${e.nonPtrGlobals} ; number of globals that are not pointers (they come first)\n .word _pxt_iface_member_names\n .word _pxt_lambda_trampoline@fn\n .word _pxt_perf_counters\n .word _pxt_restore_exception_state@fn\n .word ${e.emitString(e.getTitle())} ; name\n`,a=null;a=new t.ThumbSnippets;const c=e.setPerfCounters(s);e.procs.forEach((n=>{let r=new t.ProctoAssembler(a,e,n);i+="\n"+r.getAssembly()+"\n"}));let l=new t.ProctoAssembler(a,e,null);l.emitHelpers(),i+="\n"+l.getAssembly()+"\n",i+=n.asmTotalSource,i+="_code_end:\n\n",t.U.iterMap(e.codeHelpers,((e,t)=>{i+=` .section code\n${t}:\n${e}\n`})),i+=a.arithmetic(),i+="_helpers_end:\n\n",e.usedClassInfos.forEach((t=>{i+=o(t,0,e)})),i+="\n.balign 4\n_pxt_iface_member_names:\n",i+=` .word ${e.ifaceMembers.length}\n`;let u=0;for(let t of e.ifaceMembers){let n=e.emitString(t);i+=` .word ${n} ; ${u++} .${t}\n`}i+=" .word 0\n",i+="_vtables_end:\n\n",i+="\n.balign 4\n_pxt_config_data:\n";const d=e.res.configData||[];for(let e of d)i+=` .word ${e.key}, ${e.value} ; ${e.name}=${e.value}\n`;i+=" .word 0\n\n",function(e,n){const r=t.U.unique(n.ifaceMembers.concat(Object.keys(n.strings)),(e=>e));for(let t of r)n.otherLiterals.push(e.string_literal(n.strings[t],t));for(let t of Object.keys(n.doubles)){let r=n.doubles[t];n.otherLiterals.push(`\n.balign 4\n${r}: ${e.obj_header("pxt::number_vt")}\n .hex ${t}\n`)}for(let t of Object.keys(n.hexlits))n.otherLiterals.push(e.hex_literal(n.hexlits[t],t)),n.otherLiterals.push()}(a,e),i+=e.otherLiterals.join(""),i+="\n.balign 4\n.section code\n_pxt_perf_counters:\n",i+=` .word ${c.length}\n`;let p="";for(let e=0;e<c.length;++e){let t=".perf"+e;i+=` .word ${t}\n`,p+=`${t}: .string ${JSON.stringify(c[e])}\n`}return i+=p,i+="_literals_end:\n",i}function l(e){let r;return r=e.nativeType==t.NATIVE_TYPE_VM?new t.assembler.VMFile(new t.vm.VmProcessor(e)):new t.assembler.File(new t.thumb.ThumbProcessor),r.ei.testAssembler(),e.switches.noPeepHole&&(r.disablePeepHole=!0),r.lookupExternalLabel=n.lookupFunctionAddr,r.normalizeExternalLabel=e=>{let t=n.lookupFunc(e);return t?t.name:e},r}function u(e){if(e.errors.length>0){let n="";throw e.errors.forEach((e=>{let r=/^user(\d+)/.exec(e.scope);if(r){parseInt(r[1]);n+=t.U.lf("At inline assembly:\n"),n+=e.message}})),n?(console.log(t.U.lf("errors in inline assembly")),console.log(n),new Error(e.errors[0].message)):new Error(e.errors[0].message)}}t.processorInlineAssemble=function(e,t){let n=l(e);n.disablePeepHole=!0,n.emit(t),u(n);let r=[];for(let e=0;e<n.buf.length;e+=2)r.push(((n.buf[e+1]||0)<<16|n.buf[e])>>>0);return r};function d(e,t,n){let r=l(e);return r.emit(n),n=`; Interface tables: ${t.itFullEntries}/${t.itEntries} (${Math.round(100*t.itFullEntries/t.itEntries)}%)\n; Virtual methods: ${t.numVirtMethods} / ${t.numMethods}\n`+r.getSource(!0,t.numStmts,e.flashEnd),u(r),{src:n,buf:r.buf,thumbFile:r}}function p(r,i,a,o){const s=a.extinfo.disabledDeps;r=s?`${n.hexPrelude()}\n; compilation disabled on this variant due to ${a.extinfo.disabledDeps}\n.hex 718E3B92C615A841C49866C975EE5197\n.string "${a.extinfo.disabledDeps}"`:`; start\n${n.hexPrelude()}\n .hex 708E3B92C615A841C49866C975EE5197 ; magic number\n .hex ${n.hexTemplateHash()} ; hex template hash\n .hex 873266330af9dbdb ; replaced in binary by program hash\n`+r,a.embedBlob&&(i.packedSource=function(e,n){let r=t.Util.toUTF8(e),i=(r.length,n.length,"A/¸/¢»");return i+=t.U.uint8ArrayToString([255&r.length,r.length>>8,255&n.length,n.length>>8,0,0,0,0]),i+=r,i+=n,i.length%2&&(i+="\0"),i}(a.embedMeta,e.pxtc.decodeBase64(a.embedBlob)),!i.target.noSourceInFlash&&i.packedSource.length<4e4&&(r+=function(e){let t="";for(let n=0;n<e.length;++n){let r=255&e.charCodeAt(n);t+=r<=15?"0"+r.toString(16):r.toString(16)}return`\n .balign 16\n_stored_program: .hex ${t}\n`}(i.packedSource),i.packedSource=null));const c=n.flashCodeAlign(a.target);if(!s&&a.target.flashChecksumAddr){let e=0;for(;c>1<<e;)e++;let t=parseInt(n.hexTemplateHash().slice(8,16),16);const i=n.getStartAddress()/c;t=4294967040&t|e;let o=0,s=i;a.target.flashChecksumAddr<n.getStartAddress()&&(o=Math.ceil((a.target.flashChecksumAddr+32)/c),s-=o),r+=`\n .balign 4\n__end_marker:\n .word ${t}\n\n; ------- this will get removed from the final binary ------\n__flash_checksums:\n .word 0x87eeb07c ; magic\n .word __end_marker ; end marker position\n .word ${t} ; end marker\n ; template region\n .short ${o}, ${s}\n .word 0x${n.hexTemplateHash().slice(0,8)}\n ; user region\n .short ${i}, 0xffff\n .hex 87326633 ; replaced later\n .word 0x0 ; terminator\n`}const l=a.extinfo.outputPrefix||"";i.writeFile(l+t.BINARY_ASM,r);const u=d(a.target,i,r);if(u.thumbFile.commPtr&&(i.commSize=u.thumbFile.commPtr-n.getCommBase()),u.src&&i.writeFile(l+t.BINARY_ASM,u.src),s)return void f();const p=o.configData||[];if(p.some((e=>"BOOTLOADER_BOARD_ID"==e.name))){let e="const uint32_t configData[] = {\n";e+=" 0x1e9e10f1, 0x20227a79, // magic\n",e+=` ${p.length}, 0, // num. entries; reserved\n`;for(let t of p)e+=` ${t.key}, 0x${t.value.toString(16)}, // ${t.name}\n`;e+=" 0, 0\n};\n",i.writeFile(l+"config.c",e)}if(u.buf){const e=u.buf;let n="";for(let t=0;t<e.length;++t)n+=String.fromCharCode(255&e[t],e[t]>>8);const r=t.U.sha256(n).slice(0,16),o=t.U.range(4).map((e=>parseInt(r.slice(2*e,2*e+2),16)));t.U.assert(12935==e[12]);for(let t=0;t<o.length;++t)e[12+t]=o[t];if(a.target.flashChecksumAddr){let n=u.thumbFile.lookupLabel("__flash_checksums")/2;t.U.assert(n==e.length-16);let r=e.slice(e.length-16);e.splice(e.length-16,16);let a=Math.ceil(2*e.length/c);t.U.assert(12935==r[r.length-4]),r[r.length-4]=o[0],r[r.length-3]=o[1],r[r.length-5]=a,i.checksumBlock=r}f()}if(!o.procDebugInfo){for(let e of o.breakpoints){let n=t.U.lookup(u.thumbFile.getLabels(),"__brkp_"+e.id);null!=n&&(e.binAddr=n)}for(let e of i.procs)e.fillDebugInfo(u.thumbFile);if(o.procDebugInfo=i.procs.map((e=>e.debugInfo)),i.target.switches.size){const n=[];for(const r of i.procs){const i=e.pxtc.nodeLocationInfo(r.action),a=[i.fileName.replace("pxt_modules/",""),t.getDeclName(r.action),r.debugInfo.size,"function",i.line+1];n.push(a.map((e=>`"${e}"`)).join(","))}n.sort(),n.unshift("filename,name,size,type,line"),i.writeFile(l+"size.csv",n.join("\n"))}}function f(){if(pxt.isOutputText(t.target)){const e=n.patchHex(i,u.buf,!1,!1).join("\r\n")+"\r\n";i.writeFile(l+pxt.outputName(t.target),e)}else{const r=e.pxtc.encodeBase64(n.patchHex(i,u.buf,!1,!!t.target.useUF2)[0]);i.writeFile(l+pxt.outputName(t.target),r)}}}t.assemble=d,t.processorEmit=function(e,r,i){const a=c(e),o=t.U.flatClone(r);n.setupFor(r.target,r.extinfo||t.emptyExtInfo()),p(a,e,r,i);const s=o.otherMultiVariants||[];if(s.length)try{for(let r of s){const s=t.U.flatClone(o);s.extinfo=r.extinfo,r.target.isNative=!0,s.target=r.target,n.setupFor(s.target,s.extinfo),p(a,e,s,i)}}finally{n.setupFor(o.target,o.extinfo)}},t.validateShim=n.validateShim}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){e.getHelpForKeyword=function(e,t){const n={abstract:null,any:null,as:null,break:null,case:null,catch:null,class:null,continue:null,const:null,constructor:null,debugger:null,declare:null,delete:null,do:null,else:null,enum:null,export:null,extends:null,false:lf("Represents the negative outcome of a logical expression"),finally:null,for:null,from:null,function:null,get:null,if:null,implements:null,in:null,instanceof:null,interface:null,is:null,let:null,namespace:null,new:null,null:null,private:null,protected:null,public:null,return:null,set:null,static:null,super:null,switch:null,this:null,throw:null,true:lf("Represents the positive outcome of a logical expression"),try:null,type:null,typeof:null,undefined:null,void:null,while:null,with:null,of:null};if(t){return{True:n.true,False:n.false,None:null,abs:null,all:null,any:null,ascii:null,bin:null,bool:null,bytearray:null,bytes:null,callable:null,chr:null,classmethod:null,compile:null,complex:null,copyright:null,credits:null,delattr:null,dict:null,dir:null,divmod:null,enumerate:null,eval:null,exec:null,exit:null,filter:null,float:null,format:null,frozenset:null,getattr:null,globals:null,hasattr:null,hash:null,help:null,hex:null,id:null,input:null,int:null,isinstance:null,issubclass:null,iter:null,len:null,license:null,list:null,locals:null,map:null,max:null,memoryview:null,min:null,next:null,object:null,oct:null,open:null,ord:null,pow:null,print:null,property:null,quit:null,range:null,repr:null,reversed:null,round:null,set:null,setattr:null,slice:null,sorted:null,staticmethod:null,str:null,sum:null,super:null,tuple:null,type:null,vars:null}[e]}return n[e]}}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){e.LSHost=class{constructor(e){this.p=e}getCompilationSettings(){const e=this.p.getCompilerOptions();return e.noLib=!0,e}getNewLine(){return"\n"}getScriptFileNames(){return this.p.getSourceFiles().map((e=>e.fileName))}getScriptVersion(e){return"0"}getScriptSnapshot(e){const t=this.p.getSourceFile(e);return{getLength:()=>t.getFullText().length,getText:()=>t.getFullText(),getChangeRange:()=>{}}}getCurrentDirectory(){return"."}getDefaultLibFileName(e){return""}useCaseSensitiveFileNames(){return!0}}}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){!function(n){function r(e){var t,r;const i=null===(r=null===(t=null==e?void 0:e.pxt)||void 0===t?void 0:t.callInfo)||void 0===r?void 0:r.qName;return n.lastApiInfo.apis.byQName[i]}function i(e,t,r){if(!e||t<0)return;let i=e.parameters[t];if(e.attributes._def){const a=e.attributes._def.parameters[t].shadowBlockId;if(a){const e=r.blocksById[a],t=n.lastApiInfo.apis.byQName[e.qName];"TD_ID"===t.attributes.shim&&1===t.parameters.length&&(i=t.parameters[0])}}return i}function a(r,i,a,o,s=!1){const c={};o.forEach((e=>{var t,n;let r=e.symbol.retType;if(s)if(7==e.symbol.kind)r=e.symbol.namespace;else if(4==e.symbol.kind){const i=null===(n=null===(t=e.symbol.attributes)||void 0===t?void 0:t.enumIdentity)||void 0===n?void 0:n.split(".");(null==i?void 0:i.length)>1&&(r=i[0])}c[r]=[...c[r]||[],e]}));const l=c[r]||[];let u=[];for(let r of l){const o=m(r.symbol,i,e.SymbolFlags.Enum);if(o){const e=a.getTypeOfSymbolAtLocation(o,i),r=t.getEnumMembers(a,e).map((e=>t.enumMemberToQName(a,e))).map((e=>n.lastApiInfo.apis.byQName[e]));u=[...u,...r]}}return[...l,...p(u,1)]}function o(t){return t.flags&e.SymbolFlags.Variable?4:t.flags&e.SymbolFlags.Class?8:t.flags&e.SymbolFlags.Enum?6:t.flags&e.SymbolFlags.EnumMember?7:t.flags&e.SymbolFlags.Method?1:t.flags&e.SymbolFlags.Module?5:t.flags&e.SymbolFlags.Property?2:0}function s(e){return{kind:0,name:e,pyName:e,qName:e,pyQName:e,namespace:"",attributes:{callingConvention:0,paramDefl:{}},fileName:pxt.MAIN_TS,parameters:[],retType:"any"}}function c(e,t){var n,r;let i=e.getName(),a=/(.*)\.(.*)/.exec(i),s=a?a[2]:i,c=a?a[1]:"",l=null!==(r=null===(n=t.getSymbol())||void 0===n?void 0:n.getName())&&void 0!==r?r:"any";return{kind:o(e),name:s,pyName:s,qName:i,pyQName:i,namespace:c,attributes:{callingConvention:0,paramDefl:{}},fileName:pxt.MAIN_TS,parameters:[],retType:l}}function l(e,t,n){if(e)return t.byQName[n.getFullyQualifiedName(e)]}function u(e,n){return e.weight!==n.weight?n.weight-e.weight:t.compareSymbols(e.symbol,n.symbol)}function d(e,t){return{symbol:e,weight:t}}function p(e,t){return e.map((e=>d(e,t)))}function f(t,n){var r;if(t.flags&e.TypeFlags.NumberLiteral)return"Number";if(t.flags&e.TypeFlags.StringLiteral)return"String";if(t.flags&e.TypeFlags.BooleanLiteral)return"Boolean";const i=n.typeToString(t);return null!==(r={number:"Number",string:"String",boolean:"Boolean"}[i])&&void 0!==r?r:i}function _(e,t){return"."===t.charAt(0)&&(t=t.substr(1)),e.substr(0,e.lastIndexOf(".")+1)+t}function m(e,t,r){const i=n.service&&n.service.getProgram().getTypeChecker();if(!i)return null;const a=i.getSymbolsInScope(t,r);for(let t of a)if(t.escapedName.toString()===e.qName)return t;return null}function g({symbol:e}){return!(/^__/.test(e.name)||/^__/.test(e.namespace)||e.attributes.hidden||e.attributes.deprecated||"TD_ID"==e.attributes.shim||e.attributes.blockAliasFor)}n.getCallSymbol=r,n.getParameter=i,n.getApisForTsType=a,n.getBasicKindDefault=function(e,n){switch(e){case t.SK.StringKeyword:return'""';case t.SK.NumberKeyword:return"0";case t.SK.BooleanKeyword:return n?"False":"false";case t.SK.ArrayType:return"[]";case t.SK.NullKeyword:return n?"None":"null";default:return}},n.tsSymbolToPxtSymbolKind=o,n.makePxtSymbolFromKeyword=s,n.makePxtSymbolFromTsSymbol=c,n.getPxtSymbolFromTsSymbol=l,n.compareCompletionSymbols=u,n.completionSymbol=d,n.completionSymbols=p,n.getNodeAndSymbolAtLocation=function(e,n,r,i){const a=e.getSourceFile(n),o=e.getTypeChecker(),s=t.findInnerMostNodeAtPosition(a,r);if(s){const e=o.getSymbolAtLocation(s);if(e){return[s,l(e,i,o)]}}return null},n.tsTypeToPxtTypeString=f,n.filenameWithExtension=_,n.getWordAtPosition=function(e,t){let n=t,r=t;for(;n>0&&i(n);)--n;for(;r<e.length-1&&i(r);)++r;return n!=r?{text:e.substring(n+1,r),start:n+1,end:r}:null;function i(t){const n=e.charCodeAt(t);return n>=65&&n<=90||n>=97&&n<=122}},n.getTsSymbolFromPxtSymbol=m,n.getDefaultEnumValue=function(e,r){const i=n.service&&n.service.getProgram().getTypeChecker(),a=t.getEnumMembers(i,e);for(const e of a)if(e.name.kind===t.SK.Identifier){const a=t.enumMemberToQName(i,e),o=n.lastApiInfo.apis.byQName[a];return o?o.attributes.alias?r&&o.attributes.pyAlias||o.attributes.alias:r?o.pyQName:o.qName:a}return"0"},n.getCompletions=function(o){var m,h;const{fileName:y,fileContent:v,position:b,wordStartPos:x,wordEndPos:k,runtime:S}=o;let T=v;v&&n.host.setFile(y,v);const C=_(y,"ts"),E={startPos:x,endPos:k},D=/\.py$/.test(y),A={entries:[],isMemberCompletion:!1,isNewIdentifierLocation:!0,isTypeLocation:!1,namespace:[]};let N=T.lastIndexOf("\n",b-1);N=Math.max(0,N);const w=T.substring(N+1,b),I=D?"#":"//";if(w.trim().startsWith(I))return A;let P=-1,O=-1;for(let e=b-1;e>=0;--e){if("."==T[e]){P=e;break}if(!/\w/.test(T[e]))break;-1==O&&(O=e)}P==b-1?T=T.slice(0,b)+"_"+T.slice(b):-1==O&&(T=T.slice(0,b)+"_"+T.slice(b),O=b);const F=-1!==P;A.isMemberCompletion=F;const L=F?T.slice(P+1,k):T.slice(x,k);F&&(O=P);const R={};let M=n.cloneCompileOpts(n.host.opts);M.fileSystem[y]=T,n.addApiInfo(M),M.syntaxInfo={position:O,type:A.isMemberCompletion?"memberCompletion":"identifierCompletion"};let U,B=[];if(D){const e=t.transpile.pyToTs(M);if(e.syntaxInfo&&e.syntaxInfo.symbols&&(B=p(e.syntaxInfo.symbols,1)),e.globalNames&&(n.lastGlobalNames=e.globalNames),!B.length&&e.globalNames&&(B=p(pxt.U.values(e.globalNames),1)),Object.keys(e.outfiles).forEach((t=>{t===C&&n.host.setFile(t,e.outfiles[t])})),e.sourceMap){const n=T,r=e.outfiles[C]||"",i=t.BuildSourceMapHelpers(e.sourceMap,r,n).py.smallestOverlap(E);i&&(U=i.ts.startPos)}!F&&B.length>50&&(B=B.filter((e=>(D?e.symbol.pyQName:e.symbol.qName).toLowerCase().indexOf(L.toLowerCase())>=0))),M.ast=!0;t.compile(M,n.service)}else{U=b,M.ast=!0,n.host.setOpts(M);n.runConversionsAndCompileUsingService()}const $=n.service.getProgram(),j=$.getSourceFile(C),K=$.getTypeChecker();let z=t.findInnerMostNodeAtPosition(j,U);if(t.decompiler.buildCommentMap(j).some((e=>e.start<=b&&b<=e.end)))return A;if(z){if([t.SK.StringLiteral,t.SK.FirstTemplateToken,t.SK.NoSubstitutionTemplateLiteral].some((e=>z.kind===e)))return A}A.namespace=t.getCurrentNamespaces(z);let J=!1;if(F){const e=t.findInnerMostNodeAtPosition(j,D?U:P-1);if(e){let t;const r=K.getSymbolAtLocation(e);if(t=(null===(m=null==r?void 0:r.members)||void 0===m?void 0:m.size)>0?K.getDeclaredTypeOfSymbol(r):r?K.getTypeOfSymbolAtLocation(r,e):K.getTypeAtLocation(e),t){const e=t.symbol?K.getFullyQualifiedName(t.symbol):f(t,K);if(e){B=t.getApparentProperties().map((t=>e+"."+t.getName())).map((e=>n.lastApiInfo.apis.byQName[e])).filter((e=>!!e)).map((e=>d(e,1))),J=!0}}}}const q=pxt.U.values(n.lastApiInfo.apis.byQName);if(0===B.length){B=p(q.filter((e=>(D?e.pyQName:e.qName).toLowerCase().indexOf(L.toLowerCase())>=0)),1)}if(!D&&!J){z=t.findInnerMostNodeAtPosition(j,x),z||(z=j.getSourceFile());let r=e.SymbolFlags.Variable,i=K.getSymbolsInScope(z,r),a=z.getText();"_"!==a&&(i=i.filter((e=>e.name.indexOf(a)>=0)));let o=i.map((e=>{let t=l(e,n.lastApiInfo.apis,K);if(!t){t=c(e,K.getTypeOfSymbolAtLocation(e,z))}return t})).filter((e=>!!e)).map((e=>d(e,1)));o.forEach((e=>e.weight+=5)),B=[...B,...o]}const V=t.getParentCallExpression(z);if(V){let e=t.findCurrentCallArgIdx(V,z,U);if(e>=0){const t=n.blocksInfoOp(n.lastApiInfo.apis,S.bannedCategories),o=r(V);if(o){e>=o.parameters.length&&(e=o.parameters.length-1);const n=i(o,e,t);if(n){a(n.type,V,K,B,n.isEnum).forEach((e=>e.weight=10))}}}}if(!F){let e;if(D){let t=pxt.py.keywords;e=Object.keys(t)}else e=[...ts.pxtc.reservedWords,...ts.pxtc.keywordTypes];let t=e.filter((e=>e.indexOf(L)>=0)).map(s).map((e=>d(e,0)));B=[...B,...t]}let H={};H=D&&n.lastGlobalNames?n.lastGlobalNames:n.lastApiInfo.apis.byQName,B.map((e=>!e.symbol.attributes.alias||F&&7===e.symbol.kind?e:d(n.lastApiInfo.apis.byQName[e.symbol.attributes.alias],e.weight))).filter(g).forEach((e=>{R[e.symbol.qName]=e})),B=pxt.Util.values(R).filter((e=>!!e&&!!e.symbol)),B.sort(u),o.light&&B.length>100&&(B=B.splice(0,100));const{bannedCategories:G,screenSize:W}=o.runtime,Q={takenNames:H,blocksInfo:n.blocksInfoOp(n.lastApiInfo.apis,G),screenSize:W,apis:n.lastApiInfo.apis,checker:null===(h=null===n.service||void 0===n.service?void 0:n.service.getProgram())||void 0===h?void 0:h.getTypeChecker()};return B.forEach((t=>function(t,r,i){const a=n.lastApiInfo.decls[t.qName];if(e.isFunctionLike(a)&&(t.snippetAddsDefinitions||r&&!t.pySnippet||!r&&!t.snippet)){const e=n.getSnippet(i,t,a,r),o=n.snippetStringify(e),s=n.snippetStringify(e,!0),c=n.snippetAddsDefinitions(e);r?(t.pySnippet=o,t.pySnippetWithMarkers=s):(t.snippet=o,t.snippetWithMarkers=s),t.snippetAddsDefinitions=c}}(t.symbol,D,Q))),A.entries=B.map((e=>e.symbol)),A}}(t.service||(t.service={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){let n=function(t){let n=i(t);e.sys.write(n)};function r(e){for(const t of e)n(t)}function i(n){let r;if(void 0!==n.file){let t=n;const{line:i,character:a}=e.getLineAndCharacterOfPosition(t.file,t.start),o=t.file.fileName;r=Object.assign({fileName:o,line:i,column:a},t)}else r=Object.assign({fileName:void 0,line:void 0,column:void 0},n);return function(n){let r="";n.fileName&&(r+=`${n.fileName}(${n.line+1},${n.column+1}): `);let i=e.sys?e.sys.newLine:"\n";const a=t.DiagnosticCategory[n.category].toLowerCase();return r+=`${a} TS${n.code}: ${t.flattenDiagnosticMessageText(n.messageText,i)}${i}`,r}(r)}function a(t,n){const r=e.createCompilerHost(n);return r.getDefaultLibFileName=()=>"node_modules/pxt-core/pxtcompiler/ext-typescript/lib/lib.d.ts",e.createProgram(t,n,r)}function o(e){let n=e.getSyntacticDiagnostics();return 0===n.length&&(n=e.getOptionsDiagnostics().concat(t.Util.toArray(e.getGlobalDiagnostics())),0===n.length&&(n=e.getSemanticDiagnostics())),n.slice(0)}t.getDiagnosticString=i,t.plainTscCompileDir=function(t){const i=e.parseCommandLine([]);let s=e.findConfigFile(t,e.sys.fileExists);const c=function(){let n=e.sys.readFile(s);const a=e.parseConfigFileTextToJson(s,n),o=a.config;if(!o)return r([a.error]),void e.sys.exit(e.ExitStatus.DiagnosticsPresent_OutputsSkipped);const c=e.parseJsonConfigFileContent(o,e.sys,t,i.options,s);if(c.errors.length>0)return r(c.errors),void e.sys.exit(e.ExitStatus.DiagnosticsPresent_OutputsSkipped);return c}();let l=a(c.fileNames,c.options);return o(l).forEach(n),l},t.plainTscCompileFiles=a,t.getProgramDiagnostics=o}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){function n(t){if(!t||!t.kind)return null;switch(t.kind){case e.SyntaxKind.StringKeyword:return"str";case e.SyntaxKind.NumberKeyword:return"number";case e.SyntaxKind.BooleanKeyword:return"bool";case e.SyntaxKind.VoidKeyword:return"None";case e.SyntaxKind.FunctionType:return function(e){let t=n(e.type);return`(${e.parameters.map((e=>e.type)).map(n).join(", ")}) -> ${t}`}(t);case e.SyntaxKind.ArrayType:return`List[${n(t.elementType)}]`;case e.SyntaxKind.TypeReference:{let e=t;return e.typeName&&e.typeName.getText?e.typeName.getText():""}case e.SyntaxKind.AnyKeyword:return"any";default:return pxt.tickEvent("depython.todo.tstypenodetopytype",{kind:t.kind}),""}}function r(t){if(!t||!t.flags)return null;switch(t.flags){case e.TypeFlags.String:return"str";case e.TypeFlags.Number:return"number";case e.TypeFlags.Boolean:return"bool";case e.TypeFlags.Void:return"None";case e.TypeFlags.Any:return"any";default:return pxt.tickEvent("depython.todo.tstypetopytype",{kind:t.flags}),""}}function i(i,a,o){function s(t,n,r=!1){let a=i.getTypeAtLocation(n);if(!a)return"None";r&&(a=a.getCallSignatures()[0].getReturnType());const o=i.typeToString(a,void 0,e.TypeFormatFlags.UseFullyQualifiedType);return/^\d/.test(o)?"number":"this"==o?l(i,a.symbol):o}let c=function(e){switch(e.kind){case t.SK.MethodDeclaration:case t.SK.MethodSignature:return 1;case t.SK.PropertyDeclaration:case t.SK.PropertySignature:case t.SK.GetAccessor:case t.SK.SetAccessor:return 2;case t.SK.Constructor:case t.SK.FunctionDeclaration:return 3;case t.SK.VariableDeclaration:return 4;case t.SK.ModuleDeclaration:return 5;case t.SK.EnumDeclaration:return 6;case t.SK.EnumMember:return 7;case t.SK.ClassDeclaration:return 8;case t.SK.InterfaceDeclaration:return 9;default:return 0}}(o);if(0!=c){let l=o,u=t.parseComments(l);if(u.weight<0)return null;let d,p=/^(.*)\.(.*)/.exec(a),f=3==c||1==c,_=null,m=null,g=e.getSourceFileOfNode(o);if(g){let e=/^pxt_modules\/([^\/]+)/.exec(g.fileName);e&&(_=e[1])}if(8==c||9==c){let e=o;if(d=[],e.heritageClauses)for(let t of e.heritageClauses)if(t.types)for(let e of t.types)d.push(s(0,e))}6!=c&&7!==c||(d||(d=[])).push("Number");let h={kind:c,qName:a,namespace:p?p[1]:"",name:p?p[2]:a,fileName:o.getSourceFile().fileName,attributes:u,pkg:_,pkgs:m,extendsTypes:d,retType:o.kind==e.SyntaxKind.Constructor?"void":5==c?"":s(l.type,l,f),parameters:f?t.Util.toArray(l.parameters).map(((a,o)=>{let c,l,d=t.getName(a),p=u.paramHelp[d]||"",f=u.paramMin&&u.paramMin[d],_=u.paramMax&&u.paramMax[d];/\beg\.?:\s*(.+)/.exec(p);if(a.type&&a.type.kind===t.SK.FunctionType){const n=i.getSignatureFromDeclaration(a.type).getParameters();"objectdestructuring"===u.mutate?(t.assert(n.length>0),c=i.getTypeAtLocation(n[0].valueDeclaration).getProperties().map((e=>({name:e.getName(),type:i.typeToString(i.getTypeOfSymbolAtLocation(e,n[0].valueDeclaration))})))):l=n.map(((t,n)=>({name:t.getName(),type:i.typeToString(i.getTypeOfSymbolAtLocation(t,a),void 0,e.TypeFormatFlags.UseFullyQualifiedType)})))}let m={};const g=i.getTypeAtLocation(a);let h=g&&!!(g.flags&(e.TypeFlags.Enum|e.TypeFlags.EnumLiteral));if(u.block&&u.paramShadowOptions){const e=[];u.block.replace(/%(\w+)/g,((t,n)=>(e.push(n),""))),u.paramShadowOptions[e[o]]&&(m.fieldEditorOptions={value:u.paramShadowOptions[e[o]]})}f&&(m.min={value:f}),_&&(m.max={value:_});const y=a.type&&n(a.type)||g&&r(g)||"unknown",v=a.initializer?a.initializer.getText():t.getExplicitDefault(u,d)||(a.questionToken?"undefined":void 0);return{name:d,description:p,type:s(a.type,a),pyTypeString:y,initializer:v,default:u.paramDefl[d],properties:c,handlerParameters:l,options:m,isEnum:h}})):null,snippet:e.isFunctionLike(o)?null:void 0};switch(h.kind){case 7:h.pyName=t.U.snakify(h.name).toUpperCase();break;case 4:case 1:case 2:case 3:h.pyName=t.U.snakify(h.name);break;case 6:case 8:case 9:case 5:default:h.pyName=h.name}return(o.kind===t.SK.GetAccessor||(o.kind===t.SK.PropertyDeclaration||o.kind===t.SK.PropertySignature)&&t.isReadonly(o))&&(h.isReadOnly=!0),h}return null}function a(e){return!!e.attributes.block&&!!e.attributes.blockId}let o;function s(e,n){function r(t){return-t(e)+t(n)}let i=r((e=>a(e)?1:-1));return i||(i=r((e=>e.namespace?-1:1)),i||(o||(o={},o[4]=100,o[5]=101,o[3]=99,o[2]=98,o[1]=97,o[8]=89,o[6]=81,o[7]=80),i=r((e=>o[e.kind]||0)),i||(i=r((e=>e.attributes.weight||50)),i||t.U.strcmp(e.name,n.name))))}function c(e,n,r=!1){const a={byQName:{},jres:n},o={},s=e.getTypeChecker(),c=e=>{var n,r;if(e.kind!=t.SK.VariableStatement){if(t.isExported(e)){if(!e.symbol)return void console.warn("no symbol",e);let c=l(s,e.symbol);e.kind==t.SK.SetAccessor&&(c+="@set"),o[c]=e;let u=i(s,c,e);if(u){let i=t.U.lookup(a.byQName,c);if(i)if(9==i.kind&&9!=u.kind)a.byQName[c+"@type"]=i;else if(9!=i.kind&&9==u.kind)a.byQName[c+"@type"]=u,u=i;else{const e=null===(n=i.attributes._source)||void 0===n?void 0:n.trim(),a=null===(r=u.attributes._source)||void 0===r?void 0:r.trim();let o=e+"\n"+a;e&&(null==a?void 0:a.indexOf(e))>=0?o=a:a&&(null==e?void 0:e.indexOf(a))>=0&&(o=e),u.attributes=t.parseCommentString(o),5===i.kind&&(u.pkgs=i.pkgs||[],i.pkg!==u.pkg&&(u.pkgs.find((e=>e===i.pkg))||u.pkgs.push(i.pkg))),i.extendsTypes&&(u.extendsTypes=u.extendsTypes||[],i.extendsTypes.forEach((e=>{-1===u.extendsTypes.indexOf(e)&&u.extendsTypes.push(e)})))}!e.parent||e.parent.kind!=t.SK.ClassDeclaration&&e.parent.kind!=t.SK.InterfaceDeclaration||t.isStatic(e)||(u.isInstance=!0),a.byQName[c]=u}}if(e.kind==t.SK.ModuleDeclaration){let n=e;if(n.body.kind==t.SK.ModuleBlock){n.body.statements.forEach(c)}else n.body.kind==t.SK.ModuleDeclaration&&c(n.body)}else if(e.kind==t.SK.InterfaceDeclaration){e.members.forEach(c)}else if(e.kind==t.SK.ClassDeclaration){e.members.forEach(c)}else if(e.kind==t.SK.EnumDeclaration){e.members.forEach(c)}}else{e.declarationList.declarations.forEach(c)}};for(let t of e.getSourceFiles())t.statements.forEach(c);let u=[];for(let e in a.byQName){let r=a.byQName[e];r.qName=e,r.attributes._source=null,r.extendsTypes&&r.extendsTypes.length&&u.push(r);let i=r.attributes.jres;if(i){"true"==i&&(i=e);let a=t.U.lookup(n||{},i);a&&a.icon&&!r.attributes.iconURL&&(r.attributes.iconURL=a.icon),a&&a.data&&!r.attributes.jresURL&&(r.attributes.jresURL="data:"+a.mimeType+";base64,"+a.data)}if(r.pyName){let e=t.U.lookup(t.ts2PyFunNameMap,r.qName);if(e&&e.n)r.pyQName=e.n,r.pySnippet=e.snippet,r.pySnippetName=e.n,r.pySnippetWithMarkers=void 0;else if(r.namespace){let e=a.byQName[r.namespace];e?r.pyQName=e.pyQName+"."+r.pyName:(pxt.log("namespace missing: "+r.namespace),r.pyQName=r.namespace+"."+r.pyName)}else r.pyQName=r.pyName}}let d={},p=e=>{if(t.U.lookup(d,e.qName))return;d[e.qName]=!0;let n={};n[e.qName]=!0;for(let t of e.extendsTypes||[]){n[t]=!0;let e=a.byQName[t];if(e){p(e);for(let t of e.extendsTypes)n[t]=!0}}e.extendsTypes=Object.keys(n)};return u.forEach(p),r&&delete a.byQName["Array.map"],{apis:a,decls:o}}function l(e,t){return t.isBogusSymbol?t.name:e.getFullyQualifiedName(t)}t.placeholderChar="◊",t.ts2PyFunNameMap={"Math.trunc":{n:"int",t:e.SyntaxKind.NumberKeyword,snippet:"int(0)"},"Math.min":{n:"min",t:e.SyntaxKind.NumberKeyword,snippet:"min(0, 0)"},"Math.max":{n:"max",t:e.SyntaxKind.NumberKeyword,snippet:"max(0, 0)"},"Math.abs":{n:"abs",t:e.SyntaxKind.NumberKeyword,snippet:"abs(0)"},"console.log":{n:"print",t:e.SyntaxKind.VoidKeyword,snippet:'print(":)")'},".length":{n:"len",t:e.SyntaxKind.NumberKeyword},".toLowerCase()":{n:"string.lower",t:e.SyntaxKind.StringKeyword},".toUpperCase()":{n:"string.upper",t:e.SyntaxKind.StringKeyword},".charCodeAt(0)":{n:"ord",t:e.SyntaxKind.NumberKeyword},"pins.createBuffer":{n:"bytearray",t:e.SyntaxKind.Unknown},"pins.createBufferFromArray":{n:"bytes",t:e.SyntaxKind.Unknown},"control.createBuffer":{n:"bytearray",t:e.SyntaxKind.Unknown},"control.createBufferFromArray":{n:"bytes",t:e.SyntaxKind.Unknown},"!!":{n:"bool",t:e.SyntaxKind.BooleanKeyword},"Array.indexOf":{n:"Array.index",t:e.SyntaxKind.Unknown},"Array.push":{n:"Array.append",t:e.SyntaxKind.Unknown},parseInt:{n:"int",t:e.SyntaxKind.NumberKeyword,snippet:'int("0")'},"_py.range":{n:"range",t:e.SyntaxKind.Unknown,snippet:"range(4)"}},t.emitPyTypeFromTypeNode=n,t.emitPyTypeFromTsType=r,t.genDocs=function(n,r,i={}){pxt.debug(`generating docs for ${n}`),pxt.debug(JSON.stringify(Object.keys(r.byQName),null,2));const a={},o=t.Util.values(r.byQName),c=o.filter((e=>7==e.kind)).sort(s),l={},u={},d={},p=t=>{if(i.locs&&t.qName&&!/^__/.test(t.name)){if(pxt.debug(`loc: ${t.qName}`),7!=t.kind){const n=e.pxtc.blocksCategory(t);n&&(u[`{id:category}${n}`]=n)}t.attributes.jsDoc&&(d[t.qName]=t.attributes.jsDoc),t.attributes.block&&(u[`${t.qName}|block`]=t.attributes.block),t.attributes.group&&(u[`{id:group}${t.attributes.group}`]=t.attributes.group),t.attributes.subcategory&&(u[`{id:subcategory}${t.attributes.subcategory}`]=t.attributes.subcategory),t.parameters&&t.parameters.filter((e=>!!e.description)).forEach((e=>{d[`${t.qName}|param|${e.name}`]=e.description}))}},f=(e,t)=>{if(!i.locs)return;const r={};Object.keys(e).sort().forEach((t=>r[t]=e[t])),a[n+t+"-strings.json"]=JSON.stringify(r,null,2)};for(const e of o){if(5==e.kind){if(!o.filter((t=>t.namespace==e.name&&!!t.attributes.jsDoc))[0])continue;e.attributes.block||(e.attributes.block=e.name)}p(e)}return i.locs&&c.forEach((e=>{e.attributes.block&&(u[`${e.qName}|block`]=e.attributes.block),e.attributes.jsDoc&&(u[e.qName]=e.attributes.jsDoc)})),f(u,""),f(d,"-jsdoc"),i.pxtsnippet&&(i.pxtsnippet.forEach((e=>function(e,t){const n=["label","title","hint","errorMessage"];t[e.label]=e.label,e.questions.forEach((e=>{n.forEach((n=>{e[n]&&(t[e[n]]=e[n])}))}))}(e,l))),f(l,"-snippet")),a},t.hasBlock=a,t.compareSymbols=s,t.getApiInfo=function(e,t,n=!1){return c(e,t,n).apis},t.internalGetApiInfo=c,t.getFullName=l}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){!function(n){let r,i,a={fileSystem:{},sourceFiles:[],target:{isNative:!1,hasHex:!1,switches:{}}};class o{constructor(){this.opts=a,this.fileVersions={},this.projectVer=0,this.pxtModulesOK=null}getProjectVersion(){return this.projectVer+""}setFile(e,t){this.opts.fileSystem[e]!=t&&(this.fileVersions[e]=(this.fileVersions[e]||0)+1,this.opts.fileSystem[e]=t,this.projectVer++)}reset(){this.setOpts(a),this.pxtModulesOK=null}setOpts(e){t.Util.iterMap(e.fileSystem,((e,t)=>{this.opts.fileSystem[e]!=t&&(this.fileVersions[e]=(this.fileVersions[e]||0)+1)})),this.opts=Object.assign(Object.assign({},e),{fileSystem:Object.assign({},e.fileSystem)}),this.projectVer++}getCompilationSettings(){return t.getTsCompilerOptions(this.opts)}getScriptFileNames(){return this.opts.sourceFiles.filter((e=>t.U.endsWith(e,".ts")))}getScriptVersion(e){return(this.fileVersions[e]||0).toString()}getScriptSnapshot(t){let n=this.opts.fileSystem[t];return null!=n?e.ScriptSnapshot.fromString(n):null}getNewLine(){return"\n"}getCurrentDirectory(){return"."}getDefaultLibFileName(e){return"no-default-lib.d.ts"}log(e){console.log("LOG",e)}trace(e){console.log("TRACE",e)}error(e){console.error("ERROR",e)}useCaseSensitiveFileNames(){return!0}}function s(e,r){return e?(n.lastLocBlocksInfo||(n.lastLocBlocksInfo=t.getBlocksInfo(e,r)),n.lastLocBlocksInfo):(n.lastBlocksInfo||(n.lastBlocksInfo=t.getBlocksInfo(n.lastApiInfo.apis,r)),n.lastBlocksInfo)}function c(e){return n.lastApiInfo||(n.lastApiInfo=t.internalGetApiInfo(n.service.getProgram(),e.jres)),n.lastApiInfo}function l(e){if(!e.apisInfo){const n=c(e);e.apisInfo=t.U.clone(n.apis)}}function u(e){let t=pxt.U.flatClone(e);return t.fileSystem=pxt.U.flatClone(t.fileSystem),t}n.blocksInfoOp=s,n.getLastApiInfo=c,n.addApiInfo=l,n.cloneCompileOpts=u,n.IsOpErr=function(e){return!!e.errorMessage};const d={reset:()=>{n.service=e.createLanguageService(n.host),n.lastApiInfo=void 0,n.lastGlobalNames=void 0,n.host.reset()},setOptions:e=>{n.host.setOpts(e.options)},syntaxInfo:e=>{var r,i,a;let o=e.fileContent;e.fileContent&&n.host.setFile(e.fileName,e.fileContent);let s=u(n.host.opts);s.fileSystem[e.fileName]=o,l(s),s.syntaxInfo={position:e.position,type:e.infoType};const d=s.target.preferredEditor==pxt.PYTHON_PROJECT_NAME,f="symbol"===s.syntaxInfo.type,_="signature"===s.syntaxInfo.type;if(d){let e=t.transpile.pyToTs(s);e.globalNames&&(n.lastGlobalNames=e.globalNames)}else{s.ast=!0,n.host.setOpts(s);p();const i=n.service.getProgram(),a=i.getSourceFile(e.fileName),o=i.getTypeChecker();if(f||_){let i=t.findInnerMostNodeAtPosition(a,e.position);if(i)if(f){const e=o.getSymbolAtLocation(i);if(e){let t=n.getPxtSymbolFromTsSymbol(e,s.apisInfo,o);s.syntaxInfo.symbols=[t],s.syntaxInfo.beginPos=i.getStart(),s.syntaxInfo.endPos=i.getEnd()}}else if(_){const n=null===(r=null==i?void 0:i.pxt)||void 0===r?void 0:r.callInfo;if(n){const r=s.apisInfo.byQName[n.qName];s.syntaxInfo.symbols=[r],s.syntaxInfo.beginPos=i.getStart(),s.syntaxInfo.endPos=i.getEnd();const a=t.getParentCallExpression(i);if(a){const n=t.findCurrentCallArgIdx(a,i,e.position);s.syntaxInfo.auxResult=n}}}}}if(f&&!(null===(i=s.syntaxInfo.symbols)||void 0===i?void 0:i.length)){const r=n.getWordAtPosition(e.fileContent,e.position);if(r)if(d&&"range"===r.text){const e=c(s).apis;e.byQName["_py.range"]&&(s.syntaxInfo.symbols=[e.byQName["_py.range"]],s.syntaxInfo.beginPos=r.start,s.syntaxInfo.endPos=r.end)}else{const e=t.getHelpForKeyword(r.text,d);e&&(s.syntaxInfo.auxResult={documentation:e,displayString:n.displayStringForKeyword(r.text,d)},s.syntaxInfo.beginPos=r.start,s.syntaxInfo.endPos=r.end)}}if(null===(a=s.syntaxInfo.symbols)||void 0===a?void 0:a.length){const e=c(s).apis;d&&(s.syntaxInfo.symbols=s.syntaxInfo.symbols.map((t=>e.byQName[t.qName]||t))),f&&(s.syntaxInfo.auxResult=s.syntaxInfo.symbols.map((t=>n.displayStringForSymbol(t,d,e))))}return s.syntaxInfo},getCompletions:e=>n.getCompletions(e),compile:e=>{n.host.setOpts(e.options);const r=p();return t.timesToMs(r),r},decompile:e=>(n.host.setOpts(e.options),t.decompile(n.service.getProgram(),e.options,e.fileName,!1)),pydecompile:e=>(n.host.setOpts(e.options),t.transpile.tsToPy(n.service.getProgram(),e.fileName)),decompileSnippets:e=>(n.host.setOpts(e.options),t.decompileSnippets(n.service.getProgram(),e.options,!1)),assemble:e=>({words:t.processorInlineAssemble(n.host.opts.target,e.fileContent)}),py2ts:e=>(l(e.options),t.transpile.pyToTs(e.options)),fileDiags:e=>t.patchUpDiagnostics(function(e){if(!/\.ts$/.test(e))return[];let t=n.service.getSyntacticDiagnostics(e);return t&&t.length||(t=n.service.getSemanticDiagnostics(e)),t||(t=[]),t}(e.fileName)),allDiags:()=>{let e=p();return t.timesToMs(e),n.host.opts.target.switches.time&&console.log("DIAG-TIME",e.times),e},format:e=>{const n=e.format;return t.format(n.input,n.pos)},apiInfo:()=>{if(n.lastBlocksInfo=void 0,r=void 0,n.host.opts!==a)return n.lastApiInfo=t.internalGetApiInfo(n.service.getProgram(),n.host.opts.jres),n.lastApiInfo.apis},snippet:t=>{const r=t.snippet;if(!n.lastApiInfo)return;const i=n.lastApiInfo.apis.byQName[r.qName],a=n.lastApiInfo.decls[r.qName];if(!i||!a||!e.isFunctionLike(a))return;const o=!!r.python;let c={};c=o&&n.lastGlobalNames?n.lastGlobalNames:n.lastApiInfo.apis.byQName;const{bannedCategories:l,screenSize:u}=t.runtime,{apis:d}=n.lastApiInfo,p={apis:d,blocksInfo:s(d,l),takenNames:c,bannedCategories:l,screenSize:u,checker:n.service&&n.service.getProgram().getTypeChecker()},f=n.getSnippet(p,i,a,o);return n.snippetStringify(f)},blocksInfo:e=>s(e,e.blocks&&e.blocks.bannedCategories),apiSearch:e=>{const t=e.search,i=s(t.localizedApis,e.blocks&&e.blocks.bannedCategories);t.localizedStrings&&pxt.Util.setLocalizedStrings(t.localizedStrings);const a=(e,t,n)=>{if(e)return"string"==typeof e?e:t?e[t]:Object.keys(e).map((t=>e[t])).join(" ")},o=e=>{var t;if(null===(t=e.attributes)||void 0===t?void 0:t._def){let t=[];const n=e.attributes._def,r=pxt.blocks.compileInfo(e);for(let e of n.parts)switch(e.kind){case"label":t.push(e.text);break;case"param":let n=r.definitionNameToParam[e.name];t.push((null==n?void 0:n.defaultValue)||e.varName||(null==n?void 0:n.actualName)||e.name)}return t.join(" ")}return e.attributes.block},c=e=>{var t;const n=null===(t=e.attributes)||void 0===t?void 0:t.paramHelp;return n&&Object.keys(n).map((e=>n[e])).join(" "),""};if(!n.builtinItems){n.builtinItems=[],n.blockDefinitions=pxt.blocks.blockDefinitions();for(const e in n.blockDefinitions){const t=n.blockDefinitions[e];if(t.operators)for(const r in t.operators){t.operators[r].forEach((i=>n.builtinItems.push({id:e,name:t.name,jsdoc:"string"==typeof t.tooltip?t.tooltip:t.tooltip[i],block:i,field:[r,i],builtinBlock:!0})))}else n.builtinItems.push({id:e,name:t.name,jsdoc:a(t.tooltip,t.tooltipSearch),block:a(t.block,t.blockTextSearch),builtinBlock:!0})}}let l;if(!r||t.subset){const e={};let a=[];t.subset&&(n.tbSubset=t.subset,a=n.builtinItems.filter((e=>!!n.tbSubset[e.id]))),n.tbSubset?l=i.blocks.filter((e=>!!n.tbSubset[e.attributes.blockId])):(l=i.blocks,a=n.builtinItems);let s=l.map((e=>({id:e.attributes.blockId,qName:e.qName,name:e.name,namespace:e.namespace,block:o(e),params:c(e),jsdoc:e.attributes.jsDoc,localizedCategory:n.tbSubset&&"string"==typeof n.tbSubset[e.attributes.blockId]?n.tbSubset[e.attributes.blockId]:void 0}))),u={};a.forEach((e=>u[e.id]=!0)),s=s.filter((e=>!(e.id in u)));let d=0;l.forEach((t=>{const n=e[t.qName]=(e=>{const t=e.attributes.weight||50,n=i.apis.byQName[e.namespace];return(1e3*(n&&n.attributes.weight||50)+t)*(n&&n.attributes.advanced||e.attributes.advanced?1:1e6)})(t);d=Math.max(d,n)})),s=s.concat(a);r=new Fuse(s,{shouldSort:!0,threshold:.6,location:0,distance:100,maxPatternLength:16,minMatchCharLength:2,findAllMatches:!1,caseSensitive:!1,keys:[{name:"name",weight:.3},{name:"namespace",weight:.1},{name:"localizedCategory",weight:.1},{name:"block",weight:.4375},{name:"params",weight:.0625},{name:"jsdoc",weight:.0625}],sortFn:function(t,n){const r=t.qName?1-e[t.item.qName]/d:1,i=n.qName?1-e[n.item.qName]/d:1;return t.score*(1+r/10)-n.score*(1+i/10)}})}return r.search(t.term).slice(0,7)},projectSearch:e=>{const t=e.projectSearch,n=t.headers;if(!i){i=new Fuse(n,{shouldSort:!0,threshold:.6,location:0,distance:100,maxPatternLength:16,minMatchCharLength:2,findAllMatches:!1,caseSensitive:!1,keys:[{name:"name",weight:.3}]})}return i.search(t.term)},projectSearchClear:()=>{i=void 0}};function p(){l(n.host.opts);const e=t.U.flatClone(n.host.opts.fileSystem);let r=t.runConversionsAndStoreResults(n.host.opts);(null==r?void 0:r.globalNames)&&(n.lastGlobalNames=r.globalNames);const i=n.host.opts.fileSystem;n.host.opts.fileSystem=e;for(let e of Object.keys(i))n.host.setFile(e,i[e]);if(0==r.diagnostics.length){n.host.opts.skipPxtModulesEmit=!1,n.host.opts.skipPxtModulesTSC=!1;const e=n.host.opts.target.isNative?"native":"js";!n.host.opts.target.switches.noIncr&&n.host.pxtModulesOK&&(n.host.opts.skipPxtModulesTSC=!0,n.host.opts.noEmit?n.host.opts.skipPxtModulesEmit=!0:n.host.opts.target.isNative?n.host.opts.skipPxtModulesEmit=!1:"js"!=n.host.pxtModulesOK||n.host.opts.breakpoints&&!n.host.opts.justMyCode||(n.host.opts.skipPxtModulesEmit=!0));let i=t.compile(n.host.opts,n.service);if(r=Object.assign({sourceMap:r.sourceMap},i),(r.needsFullRecompile||(!r.success||r.diagnostics.length)&&n.host.opts.clearIncrBuildAndRetryOnError)&&(pxt.debug("triggering full recompile"),pxt.tickEvent("compile.fullrecompile"),n.host.opts.skipPxtModulesEmit=!1,i=t.compile(n.host.opts,n.service),r=Object.assign({sourceMap:r.sourceMap},i)),r.diagnostics.every((e=>!t.isPxtModulesFilename(e.fileName)))&&(n.host.pxtModulesOK=e),r.ast){let e=t.internalGetApiInfo(r.ast);e&&(n.lastApiInfo=e)}}return r}n.runConversionsAndCompileUsingService=p,n.performOperation=function(t,r){n.service||(n.host=new o,n.service=e.createLanguageService(n.host));let i=null;if(d.hasOwnProperty(t))try{i=(0,d[t])(r)||{}}catch(e){i={errorMessage:e.stack}}else i={errorMessage:"No such operation: "+t};return i}}(t.service||(t.service={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){!function(n){function r(e){return"object"==typeof e&&void 0!==e.default}function i(e){return"object"==typeof e&&"number"==typeof e.length}function a(e,t=!1){const n={};let s=1;return function e(c){if(r(c)){if(t){if(o(c.default))return e(c.default);const t=a(c.default,!1);let r=n[t];if(r&&!c.isLiteral||(r=s,s++,n[t]=r),t.indexOf(".")>=0&&t.indexOf(" ")<0){let e=t.split(".");return e[e.length-1]="${"+r+":"+e[e.length-1]+"}",e.join(".")}return"${"+r+":"+t+"}"}return e(c.default)}return i(c)?c.map((t=>e(t))).join(""):c}(e)}function o(e){return!!r(e)||!!i(e)&&e.map(o).reduce(((e,t)=>e||t),!1)}function s(e){return e.attributes.shim&&"@"==e.attributes.shim[0]||e.attributes.pyConvertToTaggedTemplate}n.snippetStringify=a,n.snippetHasReplacementPoints=o,n.snippetAddsDefinitions=function e(t){return r(t)?t.isDefinition||e(t.default):!!i(t)&&t.map(e).reduce(((e,t)=>e||t),!1)},n.getSnippet=function r(i,o,c,l,u=0){var d;let{apis:p,takenNames:f,blocksInfo:_,screenSize:m,checker:g}=i;const h=pxt.py.INDENT,y=l?"python":"typescript";let v=o.namespace,b=!1,x=!1,k="",S=0,T=[];if(s(o))return l?`${o.name}(""" """)`:`${o.name}\`\``;let C="";C=c.kind==t.SK.Constructor?B(c.symbol)||c.parent.name.getText():B(c.symbol)||c.name.getText(),l&&(C=t.U.snakify(C));const E=o.attributes;if("TD_ID"===E.shim&&u&&c.parameters.length)return M(c.parameters[0]);const D=o,A=pxt.blocks.compileInfo(D),N=_.blocksById,w=(null===(d=E._def)||void 0===d?void 0:d.parameters.filter((e=>!!A.definitionNameToParam[e.name])).map((e=>A.definitionNameToParam[e.name].actualName)))||[],I=c.parameters?c.parameters.filter((e=>!e.initializer&&!e.questionToken||w.indexOf(e.name.getText())>=0)):[],P=I.map(M).map((e=>({default:e,isLiteral:!0})));if(D.attributes.block)if(D.attributes.defaultInstance)v=D.attributes.defaultInstance,l&&v&&(v=t.U.snakify(v));else if(D.namespace){const e=p.byQName[D.namespace];if(e.attributes.fixedInstances){let n,r=t.Util.values(p.byQName),i=function(e){return r.filter((e=>e.extendsTypes)).filter((t=>t.extendsTypes.reduce(((t,n)=>t||-1!=n.indexOf(e)),!1))).reduce(((e,t)=>e.concat(t.extendsTypes)),[])},a=r.filter((e=>4===e.kind&&e.attributes.fixedInstance));const o=a.filter((t=>t.retType==e.qName)).sort(((e,t)=>e.name.localeCompare(t.name)));if(o.length)n=o[0];else{n=a.filter((t=>-1!==i(e.qName).indexOf(t.retType))).sort(((e,t)=>e.name.localeCompare(t.name)))[0]}n?(v=`${$(n)}`,k=n.namespace):k=e.namespace,k&&(x=!0),b=!0}else if(1==D.kind||2==D.kind){if(A.thisParameter){let e;A.thisParameter.definitionName&&(e=A.thisParameter.definitionName,e=e[0].toUpperCase()+e.substring(1),e=`my${e}`),v=A.thisParameter.defaultValue||e,l&&v&&(v=t.U.snakify(v))}b=!0}else if(8===e.kind)return}const O=E&&(l?E.pySnippet:E.snippet);let F;if(O)F=[O];else if(F=[C],(null==P?void 0:P.length)||1==D.kind||3==D.kind||8==D.kind){const e=P.reduce(((e,t)=>[...e,e.length?", ":"",t]),[]);F=F.concat(["(",...e,")"])}let L=v?[v,".",...F]:F;if(L=x?[function(e){const t=e.indexOf(".");return t<0?e:e.substring(0,t)}(k),".",...L]:L,E&&E.blockSetVariable)if(l){L=[{default:R(t.U.snakify(E.blockSetVariable)),isDefinition:!0}," = ",...L]}else{L=["let ",{default:R(E.blockSetVariable),isDefinition:!0}," = ",...L]}return[T,L];function R(t){return f[t]?e.pxtc.decompiler.getNewName(t,f,!1):t}function M(a){var s;const c=a.type;if(!c)return l?"None":"null";const d=a.name.kind===t.SK.Identifier?a.name.text:void 0,f=null===(s=null==E?void 0:E.paramDefl)||void 0===s?void 0:s[d];if(f){let e;if(c.kind==t.SK.AnyKeyword){const n=f.toUpperCase();e=Number.isNaN(+n)?"FALSE"==n||"TRUE"==n?t.SK.BooleanKeyword:n.includes(".")?t.SK.EnumKeyword:t.SK.StringKeyword:t.SK.NumberKeyword}if(c.kind===t.SK.StringKeyword||e===t.SK.StringKeyword)return 0!=f.indexOf('"')?`"${f}"`:f;const r=null==g?void 0:g.getTypeAtLocation(a),i=n.getPxtSymbolFromTsSymbol(null==r?void 0:r.symbol,p,g);return(null==i?void 0:i.attributes.fixedInstances)&&l?pxt.Util.snakify(f):l?t.tsSnippetToPySnippet(f,i):f}let _=function(e){var t,n;const r=pxt.blocks.compileInfo(o),i=null===(t=r.parameters)||void 0===t?void 0:t.find((t=>t.actualName===e));if(!(null==i?void 0:i.shadowBlockId))return null;let a=N[i.shadowBlockId];if(!a)return null;const s=null===(n=a.attributes)||void 0===n?void 0:n.paramFieldEditor;if(!s)return null;const c=s[e];if(!c)return null;const l=a.attributes.paramFieldEditorOptions||{};switch(c){case"sprite":return function(e){const t={initColor:0,initWidth:16,initHeight:16};if(null==e?void 0:e.sizes){const n=e.sizes.split(";"),r=[];for(let e=0;e<n.length;e++){const t=n[e].split(",");if(2!==t.length)continue;let i=parseInt(t[0]),a=parseInt(t[1]);isNaN(i)||isNaN(a)||(i<0&&m&&(i=m.width),a<0&&m&&(a=m.height),r.push([i,a]))}r.length>0&&(t.initWidth=r[0][0],t.initHeight=r[0][1])}return t.initColor=n(null==e?void 0:e.initColor,t.initColor),t.initWidth=n(null==e?void 0:e.initWidth,t.initWidth),t.initHeight=n(null==e?void 0:e.initHeight,t.initHeight),pxt.sprite.imageLiteralFromDimensions(t.initWidth,t.initHeight,t.initColor,y);function n(e,t){const n=parseInt(e);return isNaN(n)?t:n}}(l[e])}return null}(d);if(_)return _;let h=function(e){let t=(E._shadowOverrides||{})[e];if(!t){const n=pxt.blocks.compileInfo(o);for(const r of n.parameters)if(r.actualName===e){t=r.shadowBlockId;break}}if(!t)return null;let n=N[t];if(!n)return null;if("TD_ID"===n.attributes.shim&&n.parameters.length){let e=n.parameters[0].type;n=p.byQName[e]||n}return n}(d);if(h){let s=n.getTsSymbolFromPxtSymbol(h,a,e.SymbolFlags.Enum);if(s){let e=g.getTypeOfSymbolAtLocation(s,a);if(e){let t=U(e);if(t)return t}}const c=h.attributes;if("KIND_GET"===c.shim&&c.blockId){const e=c.kindNamespace||o.namespace,n=t.Util.values(p.byQName).find((t=>t.namespace===e&&t.attributes.isKind));if(n)return l?n.pyQName:n.qName}if(u<3&&n.lastApiInfo.decls[h.qName]){let e=r(i,h,n.lastApiInfo.decls[h.qName],l,u+1);if(e)return e}}if(c.kind===t.SK.StringKeyword&&"leds"===d)return l?'"""\n. . . . .\n. . . . .\n. . # . .\n. . . . .\n. . . . .\n"""':"`\n. . . . .\n. . . . .\n. . # . .\n. . . . .\n. . . . .\n`";if(c.kind===t.SK.FunctionType){const e=c;let t=g?g.getSignatureFromDeclaration(e):void 0;return t?j(t,!0):K(d)}const v=n.getBasicKindDefault(c.kind,l);if(void 0!==v)return v;let b=g&&g.getTypeAtLocation(a);if(b){let e=U(b);if(e)return e}return l?"None":"null"}function U(r){if(r.symbol&&r.symbol.flags&e.SymbolFlags.Enum){return n.getDefaultEnumValue(r,l)}const i=n.getPxtSymbolFromTsSymbol(r.symbol,p,g);if(t.isObjectType(r)){const t=i&&i.attributes&&(l?i.attributes.pySnippet:i.attributes.snippet);if(t)return t;if(r.objectFlags&e.ObjectFlags.Anonymous){const t=g.getSignaturesOfType(r,e.SignatureKind.Call);return t&&t.length?j(t[0],!1):K()}}if(r.flags&e.TypeFlags.NumberLike)return"0";if(i&&i.attributes.fixedInstances){const e=function(e){return pxt.Util.values(p.byQName).filter((t=>4===t.kind&&t.attributes.fixedInstance&&function(e,t,n){if(t==n)return!0;let r=e.byQName[t];return!(!r||!r.extendsTypes)&&r.extendsTypes.indexOf(n)>=0}(p,t.retType,e.qName)))}(i);if(e.length){const t=e[0];return l?t.pyQName:t.qName}}}function B(e){if(g){const n=t.getFullName(g,e),r=p.byQName[n];if(r)return $(r)}}function $(e){return l?e.pyName:e.name}function j(n,r){let i="",o=g.getReturnTypeOfSignature(n);if(o.flags&e.TypeFlags.NumberLike?i="return 0":o.flags&e.TypeFlags.StringLike?i='return ""':o.flags&(e.TypeFlags.Boolean|e.TypeFlags.BooleanLiteral)&&(i=l?"return False":"return false"),l){let o;o=E.optionalVariableArgs?"()":`(${n.parameters.map((e=>e.name)).join(", ")})`;let s=C||"fn";S++>0&&(s+=S),r&&!/^on/i.test(s)&&(s="on"+pxt.Util.capitalize(s));const c=I.filter((t=>{const n=g&&g.getTypeAtLocation(t);return!!(n&&n.symbol&&n.symbol.flags&e.SymbolFlags.Enum)})).map((e=>{const t=a(M(e)).toLowerCase(),n=t.lastIndexOf(".");return-1!==n?t.substr(n+1):t})).join("_");return c&&(s+="_"+c),s=t.U.snakify(s),s=R(s),T=[...T,T.length?"\n":"","def ",{default:s,isDefinition:!0},o,`:\n${h}`,{default:i||"pass"},"\n"],{default:s}}{let t="()";if(!E.optionalVariableArgs){let r=e.mapToDisplayParts((t=>{g.getSymbolDisplayBuilder().buildSignatureDisplay(n,t,void 0,e.TypeFormatFlags.UseFullyQualifiedType)})),i=e.displayPartsToString(r);t=i.substr(0,i.lastIndexOf(":"))}return["function",t,` {\n${h}`,{default:i},"\n}"]}}function K(e){return l?(e=e||"fn",e=R(e=t.U.snakify(e)),T=[...T,T.length?"\n":"","def ",{default:e,isDefinition:!0},`():\n${h}`,{default:"pass"},"\n"],{default:e}):"function () {}"}},n.isTaggedTemplate=s}(t.service||(t.service={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){!function(e){const t=e=>`main.${e}`;e.pyToTs=function(e,n=t("py")){return pxt.py.py2ts(e)},e.tsToPy=function(e,n=t("ts")){return pxt.py.decompileToPython(e,n)}}(e.transpile||(e.transpile={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){let n;function r(e,t){if(!e)return;const i=t(e);if(i===n.Continue)return r(e.parent,t);if(i===n.Abort)return;if(i===n.Found)return e;return i}function i(t){return r(t,(t=>e.isModuleDeclaration(t)?n.Found:n.Continue))}t.getParentCallExpression=function(t){return r(t,(t=>e.isCallExpression(t)?n.Found:e.isBlock(t)?n.Abort:n.Continue))},t.findCurrentCallArgIdx=function(e,t,n){let r=e.arguments.map((e=>e===t)).indexOf(!0);if(r>=0)return r;if(!(e.arguments.pos<=n&&n<e.end))return-1;if(0===e.arguments.length)return 0;r=0;for(let t of e.arguments){if(!(t.end<=n))break;r++}return e.arguments.hasTrailingComma||(r=Math.max(0,r-1)),r},function(e){e[e.Found=0]="Found",e[e.Continue=1]="Continue",e[e.Abort=2]="Abort"}(n=t.TraverseCheck||(t.TraverseCheck={})),t.traverseUp=r,t.enumMemberToQName=function(e,n){if(n.name.kind===t.SK.Identifier)return e.getFullyQualifiedName(e.getSymbolAtLocation(n.name))},t.findInnerMostNodeAtPosition=function n(r,i){for(let t of r.getChildren()){if(t.kind>=e.SyntaxKind.FirstPunctuation&&t.kind<=e.SyntaxKind.LastPunctuation)continue;let r=t.getStart(),a=t.getEnd();if(r<=i&&i<a)return n(t,i)}return r&&r.kind===t.SK.SourceFile?null:r},t.getParentNamespace=i,t.getCurrentNamespaces=function e(t){if(!t)return[];let n=i(t);if(!n)return[];let r=n.name.getText();return[...e(n.parent),r]},t.getEnumMembers=function(e,n){if(e&&n.symbol&&n.symbol.declarations&&n.symbol.declarations.length)for(let e=0;e<n.symbol.declarations.length;e++){const r=n.symbol.declarations[e];if(r.kind===t.SK.EnumDeclaration){return r.members}}},t.isExported=function(e){if(e.modifiers&&e.modifiers.some((e=>e.kind==t.SK.PrivateKeyword||e.kind==t.SK.ProtectedKeyword)))return!1;let n=e.symbol;if(!n)return!1;for(;;){let e=n.parent;if(!e)break;n=e}let r=n.valueDeclaration||n.declarations[0];return r.kind==t.SK.VariableDeclaration&&(r=r.parent.parent),!(!r.parent||r.parent.kind!=t.SK.SourceFile)},t.isReadonly=function(e){return e.modifiers&&e.modifiers.some((e=>e.kind==t.SK.ReadonlyKeyword))}}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){!function(t){const n=e.assembler.emitErr,r=n("opcode name doesn't match","<name>");class i extends e.assembler.Instruction{constructor(e,t,n){super(e,t,n,n,!1)}emit(t){let i=t.words;if(i[0]!=this.name)return r;let a=this.opcode,o=1,s=[],c=null,l=null;for(let r=0;r<this.args.length;++r){let u=this.args[r],d=i[o++];if("$"==u[0]){let r=this.ei.encoders[u],i=null;if(r.isImmediate||r.isLabel){if(!d)return n("expecting number",d);if(d=d.replace(/^#/,""),i=t.bin.parseOneInt(d),null==i)return n("expecting number",d)}else e.oops();if(null==i)return n("didn't understand it",d);e.U.assert(i>=0),11111!=i&&"$lbl"==u&&(i-=t.bin.location()+2,i>>=1),s.push(i);const o=i;if(i=r.encode(i),null==i)return n(`argument (${o}) out of range or mis-aligned`,d);"$i3"==u?i=l|i<<6:"$i5"==u&&(i=l|i<<8),"$i2"==u||"$i4"==u?l=i:"$rt"==u?(11111!=i&&i>4096&&e.U.oops("label: "+d+" v="+i),a=32768|i,"callrt.p"==this.name&&(a|=8192)):t.isLong||i<0||i>255?(t.isLong=!0,"$lbl"==u&&(i-=1),a=i>>9&65535|49152,c=this.opcode+(i<<7)&65535):a=this.opcode+(i<<7)&65535}else if(u!=d)return n("expecting "+u,d)}return i[o]?n("trailing tokens",i[o]):{stack:0,opcode:a,opcode2:c,numArgs:s,labelName:t.bin.normalizeExternalLabel(null)}}}t.VmInstruction=i,t.withPush={},t.opcodes=["stloc $i1","ldloc $i1","stfld $i4, $i5","ldfld $i4, $i5","newobj $i1","ldcap $i1","bitconv $i1","stglb $i1","ldglb $i1","ldint $i1","ldintneg $i1","ldspecial $i1","ldnumber $i1","ldlit $i1","checkinst $i1","mapget","mapset","ret $i2, $i3","popmany $i1","pushmany $i1","callind $i1","callproc $i1","calliface $i2, $i3","callget $i1","callset $i1","jmp $lbl","jmpnz $lbl","jmpz $lbl","try $lbl","push","pop"];class a extends e.assembler.AbstractProcessor{constructor(e){super(),this.addEnc("$i1","#0-8388607",(e=>this.inrange(8388607,e,e))),this.addEnc("$i2","#0-31",(e=>this.inrange(31,e,e))),this.addEnc("$i3","#0-262143",(e=>this.inrange(262143,e,e))),this.addEnc("$i4","#0-255",(e=>this.inrange(255,e,e))),this.addEnc("$i5","#0-32767",(e=>this.inrange(32767,e,e))),this.addEnc("$lbl","LABEL",(e=>this.inminmax(-4194304,4194303,e,e))).isLabel=!0,this.addEnc("$rt","SHIM",(e=>this.inrange(8388607,e,e))).isLabel=!0;let n=1,r=!0;for(let e of t.opcodes.concat(["callrt $rt"])){let a=new i(this,e,n);this.instructions[a.name]=[a],(r||"callrt"==a.name)&&(t.withPush[a.name]=!0,a=new i(this,e.replace(/\w+/,(e=>e+".p")),64|n),this.instructions[a.name]=[a]),"mapset.p"==a.name&&(r=!1),n++}}testAssembler(){}postProcessRelAddress(e,t){return t}postProcessAbsAddress(e,t){return t}getAddressFromLabel(e,t,n,r=!1){let i=e.lookupLabel(n);return null==i?null:t.is32bit?i:i-(e.pc()+2)}toFnPtr(e,t){return e}wordSize(){return 8}peephole(e,n,r){let i=e.getOp(),a="";if(n){a=n.getOp();let e=i+";"+a,t=this.file.peepCounts;t[e]=(t[e]||0)+1}"stloc"==i&&"ldloc"==a&&e.numArgs[0]==n.numArgs[0]?(/LAST/.test(n.text)&&e.update(""),n.update("")):t.withPush[i]&&"push"==a&&(e.update(e.text.replace(/\w+/,(e=>e+".p"))),n.update(""))}}t.VmProcessor=a}(e.vm||(e.vm={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){let t;!function(e){e[e.NonLocal=0]="NonLocal",e[e.Global=1]="Global"}(t=e.VarModifier||(e.VarModifier={})),e.isIndex=function(e){return"Index"===e.kind},e.isSubscript=function(e){return"Subscript"===e.kind}}(e.py||(e.py={}))}(pxt||(pxt={})),function(e){!function(t){var n=e.blocks;let r,i,a,o,s,c,l,u,d,p,f=0,_=0,m=0,g="???";function h(e){return null==e}function y(e){return null!=e}function v(t){return e.tickEvent("python.todo.statement",{kind:t.kind}),n.mkStmt(n.mkText("TODO: "+t.kind))}function b(t){return e.tickEvent("python.todo.expression",{kind:t.kind}),n.mkText(" {TODO: "+t.kind+"} ")}const x=F({primType:"string"}),k=F({primType:"number"}),S=F({primType:"boolean"}),T=F({primType:"void"}),C=F({primType:"any"});let E;const D={str:x,string:x,number:k,bool:S,void:T,any:C};function A(e){switch(e){case ts.SyntaxKind.StringKeyword:return x;case ts.SyntaxKind.NumberKeyword:return k;case ts.SyntaxKind.BooleanKeyword:return S;case ts.SyntaxKind.VoidKeyword:return T;case ts.SyntaxKind.AnyKeyword:return C;default:return E}}function N(t){let n=e.U.flatClone(t);return delete n.pyAST,delete n.pyInstanceType,delete n.pyRetType,delete n.pySymbolType,delete n.moduleTypeMarker,delete n.declared,n.parameters&&(n.parameters=n.parameters.map((t=>(delete(t=e.U.flatClone(t)).pyType,t)))),n}function w(t){if("("==t[0]&&e.U.endsWith(t,")"))return w(t.slice(1,-1));const n=t.indexOf(" => ");if(n>0){const e=t.slice(n+4);if(-1==e.indexOf(")[]")){const r=w(e),i=t.slice(1,n-1);return R(r,(i?i.split(/, /):[]).map((e=>w(e.replace(/\w+\??: /,"")))))}}if(e.U.endsWith(t,"[]"))return L(w(t.slice(0,-2)));if("_py.Array"===t)return L(C);const r=e.U.lookup(D,t);if(r)return r;if(!!t&&!isNaN(t))return k;if("T"==t||"U"==t)return F({primType:"'"+t});if(t.indexOf("|")>=0){return F({primType:"@union",typeArgs:t.split("|").map((e=>e.trim())).map(w)})}let i=P(t+"@type")||P(t);return i?7==i.kind?k:8==i.kind||9==i.kind?i.pyInstanceType||F({classType:i}):6==i.kind?k:(W(null,9502,e.U.lf("'{0}' is not a type near '{1}'",t,g||"???")),F({primType:t})):(W(null,9501,e.U.lf("unknown type '{0}' near '{1}'",t,g||"???")),F({primType:t}))}function I(t){if(!t.pySymbolType){if(g=t.pyQName,t.parameters){pxtc.service.isTaggedTemplate(t)&&(t.parameters=[{name:"literal",description:"",type:"string",options:{}}]);for(let e of t.parameters)e.pyType||(e.pyType=w(e.type))}const n=t.pyRetType;if(he(t)?t.pyRetType=F({moduleType:t}):t.retType?t.pyRetType=w(t.retType):t.pyRetType||(e.U.oops("no type for: "+t.pyQName),t.pyRetType=F({})),n&&ee(t.pyAST,n,t.pyRetType),3==t.kind||1==t.kind){let n=t.parameters.map((e=>e.pyType));if(n.some(h))return W(null,9526,e.U.lf("function symbol is missing parameter types near '{1}'",g||"???")),F({});t.pySymbolType=R(t.pyRetType,n.filter(y))}else t.pySymbolType=t.pyRetType;8!=t.kind&&9!=t.kind||(t.pyInstanceType=F({classType:t})),g=void 0}return t.pySymbolType}function P(t){return e.U.lookup(i,t)||e.U.lookup(r,t)}function O(e){if(!e)return;let t=P(e);return t&&I(t),t}function F(t={}){let n=e.U.flatClone(t);return n.tid=++_,n}function L(e){return F({primType:"@array",typeArgs:[e]})}function R(e,t){return F({primType:"@fn"+t.length,typeArgs:[e].concat(t)})}function M(t){return!!e.U.startsWith(t.primType||"","@fn")}function U(t){return!!t.primType&&!e.U.startsWith(t.primType,"@")}function B(t){return!!e.U.startsWith(t.primType||"","@union")}function $(){return a.currFun||a.currClass||a.currModule}function j(){let e=$();for(;e&&e.parent;)e=e.parent;return e}function K(){return"main"==a.currModule.name&&!a.currFun&&!a.currClass}function z(t,n,r){const i=O(n);return i||W(t,9503,e.U.lf("No module named '{0}'",n)),i}function J(e,n,r,i){i||(i=$());let a=i.vars[e],o=null==a?void 0:a.symbol;if(!o){let n=V(i);n&&(n+=".");let s=n+e;o=!se(i)||r!==t.VarModifier.Global&&r!==t.VarModifier.NonLocal?se(i)?ae(4,e):oe(4,s):oe(4,e),a={symbol:o,modifier:r},i.vars[e]=a}for(let e of Object.keys(n))o[e]=n[e];return a}function q(e){return e.unifyWith?(e.unifyWith=q(e.unifyWith),e.unifyWith):e}function V(e){let t=e,n="";t.parent&&"FunctionDef"!==t.parent.kind&&"AsyncFunctionDef"!==t.parent.kind&&(n=V(t.parent),n?n+=".":n="");let r=e;return"Module"==e.kind&&"main"==r.name?"":r.name?n+r.name:n+"?"+e.kind}function H(t){let n=e.U.lookup(Ce,t);if(n)return n;for(let n of e.U.values(a.currModule.vars)){let r=n.symbol;if(r.isImport){if(r.expandsTo==t)return r.pyName||W(null,9553,lf("missing pyName")),r.pyName;if(r.isImport&&e.U.startsWith(t,(r.expandsTo||"")+"."))return r.pyName+t.slice(r.expandsTo.length)}}return t}function G(e){return(e=q(e)).primType?e.typeArgs&&"@array"==e.primType?G(e.typeArgs[0])+"[]":M(e)&&e.typeArgs?"("+e.typeArgs.slice(1).map((e=>"_: "+G(e))).join(", ")+") => "+G(e.typeArgs[0]):B(e)&&e.typeArgs?e.typeArgs.map(G).join(" | "):e.primType+"":e.classType&&e.classType.pyQName?H(e.classType.pyQName)+"":e.moduleType&&e.moduleType.pyQName?H(e.moduleType.pyQName)+"":"any"}function W(e,t,n){c.push(function(e,t,n,r){return e||(e=o),e&&a&&a.currModule?{fileName:s,start:e.startPos,length:e.endPos-e.startPos,line:void 0,column:void 0,code:n,category:t,messageText:r}:{fileName:s,start:0,length:0,line:void 0,column:void 0,code:n,category:t,messageText:r}}(e,pxtc.DiagnosticCategory.Error,t,n))}function Q(e){return e.primType?e.primType:e.classType?e.classType:e.moduleType?(e.moduleType.moduleTypeMarker||(e.moduleType.moduleTypeMarker={}),e.moduleType.moduleTypeMarker):null}function Y(e){return!Q(q(e))}function X(t,n,r){var i;(n=q(n)).classType!=r&&(Y(n)?n.classType=r:ee(t,n,(I(i=r),i.pyInstanceType||W(null,9527,e.U.lf("Instance type symbol '{0}' is missing pyInstanceType",i)),i.pyInstanceType)))}function Z(e,t){ee(e,ge(e),t)}function ee(t,n,r){if(n===r)return;if((n=q(n))===(r=q(r))||ie(n)||ie(r))return;if("any"===n.primType)return void(n.unifyWith=r);const i=Q(n),a=Q(r);if(i&&a)if(i===a){if(n.unifyWith=r,n.typeArgs&&r.typeArgs)for(let e=0;e<Math.min(n.typeArgs.length,r.typeArgs.length);++e)ee(t,n.typeArgs[e],r.typeArgs[e]);n.unifyWith=r}else!function(t,n,r){W(t,9500,e.U.lf("types not compatible: {0} and {1}",G(n),G(r)))}(t,n,r);else i&&!a?ee(t,r,n):(m++,n.unifyWith=r)}function te(e,t){const n=q(e),r=q(t);if(n===r)return!0;const i=Q(n),a=Q(r);if(i===a)return!0;if(i&&a){if(re(i)&&re(a)&&i.extendsTypes&&i.extendsTypes.length&&i.extendsTypes.some((e=>e===a.qName)))return!0;if(B(r)){for(let e of r.typeArgs||[])if(te(n,e))return!0;return!1}}return!1}function ne(e,t){const n=q(ge(e)),r=q(t);te(n,r)||(M(n)||M(r)||U(n)||U(r))&&ee(e,n,r)}function re(e){var t;return!!(null===(t=e)||void 0===t?void 0:t.name)}function ie(e){var t;return!!(null===(t=null==e?void 0:e.primType)||void 0===t?void 0:t.startsWith("'"))}function ae(e,t){let n=/(.*)\.(.*)/.exec(t),r=n?n[2]:t;return{kind:e,name:r,pyName:r,qName:t,pyQName:t,namespace:n?n[1]:"",attributes:{},pyRetType:F()}}function oe(t,n){let r=i[n];return r?(r.kind=t,r):(r=ae(t,n),r.pyQName||W(null,9527,e.U.lf("Symbol '{0}' is missing pyQName",n)),i[r.pyQName]=r,r)}function se(e){let t=e;for(;t;){if("FunctionDef"==t.kind)return!0;t=t.parent}return!1}function ce(t,n,r){if(!n.symInfo){let i=V(n);e.U.endsWith(i,".__init__")&&(i=i.slice(0,-9)+".__constructor"),se(r=r||$())?n.symInfo=ae(t,i):n.symInfo=oe(t,i);const a=n.symInfo;a.pyAST=n,a.pyName||W(null,9528,e.U.lf("Symbol '{0}' is missing pyName",a.qName||a.name)),r.vars[a.pyName]={symbol:a}}return n.symInfo}function le(t){let n=t.symInfo.qName;return e.U.values(i).filter((e=>e.namespace==n&&2==e.kind))}function ue(t,n,r=!1,i=!1){let a=t.pyQName+"."+n,o=O(a);if(o)return o;if(!i)for(let r of t.extendsTypes||[]){let i=O(r);if(i){i==t&&e.U.userError("field lookup loop on: "+i.qName+" / "+n);let r=ue(i,n,!0);if(r)return r}}if(!r&&t.pyAST&&"ClassDef"==t.pyAST.kind){let e=oe(2,a);return e.isInstance=!0,e}return null}function de(t,n,r=!1){const i=ge(t),o=function(e){let t=q(e);return[t.classType,...pe(t.primType),t.moduleType].filter(y)}(i);for(let c of o){let o=ue(c,n,r);if(o){return!!i.moduleType?o.isInstance&&W(null,9505,e.U.lf("the field '{0}' of '{1}' is not static",n,c.pyQName)):(o.isInstance||W(null,9504,e.U.lf("the field '{0}' of '{1}' is static",n,c.pyQName)),Be(s=t,"super")&&0==s.args.length?o.isProtected=!0:ze(t)&&(a.currClass||W(null,9529,e.U.lf("no class context found for {0}",o.pyQName)),o.namespace!=a.currClass.symInfo.qName&&(o.isProtected=!0))),o}}var s;return null}function pe(e){let t=[];return"@array"==e?t=[P("_py.Array"),P("Array")]:"string"==e&&(t=[P("_py.String"),P("String")]),t.filter((e=>!!e))}function fe(t){let n=$(),r=e.U.lookup(n.vars,t);if(r)return r;for(;n;){let r=e.U.lookup(n.vars,t);if(r)return r;do{n=n.parent}while(n&&"ClassDef"==n.kind)}return null}function _e(e){if(!e)return null;const t=e.indexOf(".");if(t>0){const n=fe(e.slice(0,t)),r=null==n?void 0:n.symbol;r&&r.pyQName!=r.pyName&&(e=r.pyQName+e.slice(t))}else{const t=fe(e);if(t)return t}let n=O(e);return n?{symbol:n}:void 0}function me(e){var t;return null===(t=_e(e))||void 0===t?void 0:t.symbol}function ge(e){return e.tsType?q(e.tsType):(e.tsType=F(),e.tsType)}function he(e){if(!e)return!1;switch(e.kind){case 5:case 9:case 8:case 6:return!0;default:return!1}}function ye(t){const n=e.U.flatClone(a);let r;try{r=t()}finally{a=n}return r}function ve(e,t){return 0==t.length?n.mkText(""):n.mkGroup([n.mkText("/* TODO: "+e+" "),n.mkGroup(t),n.mkText(" */"),n.mkNewLine()])}function be(e){let t=Ze(e.value);return e.arg?n.mkInfix(n.mkText(e.arg),"=",t):n.mkGroup([n.mkText("**"),t])}function xe(n){if(!n)return F();let r=Re(n);if(r){let t=P(r+"@type")||P(r);if(t){if(I(t),6==t.kind)return k;if(t.pyInstanceType)return t.pyInstanceType}else if(D[r])return D[r];W(n,9506,e.U.lf("cannot find type '{0}'",r))}else if(t.isSubscript(n)){if("List"===Re(n.value)&&t.isIndex(n.slice)){return L(xe(n.slice.value))}}return W(n,9507,e.U.lf("invalid type syntax")),F({})}const ke={Sub:1,Div:1,Pow:1,LShift:1,RShift:1,BitOr:1,BitXor:1,BitAnd:1,FloorDiv:1,Mult:1},Se={Add:"+",Sub:"-",Mult:"*",MatMult:"Math.matrixMult",Div:"/",Mod:"%",Pow:"**",LShift:"<<",RShift:">>",BitOr:"|",BitXor:"^",BitAnd:"&",FloorDiv:"Math.idiv",And:"&&",Or:"||",Eq:"==",NotEq:"!=",Lt:"<",LtE:"<=",Gt:">",GtE:">=",Is:"===",IsNot:"!==",In:"py.In",NotIn:"py.NotIn"},Te={Invert:"~",Not:"!",UAdd:"P+",USub:"P-"},Ce={"adafruit_bus_device.i2c_device.I2CDevice":"pins.I2CDevice"};function Ee(e){a.blockDepth++;const t=n.mkBlock(e.map(et));return a.blockDepth--,t}function De(e){e.vars||(e.vars={},e.parent=$(),e.blockDepth=a.blockDepth)}function Ae(e,t=!1){return"any"===G(e)?t?n.mkText(": any"):n.mkText(""):n.mkText(": "+G(e))}function Ne(e,t){try{return ye(t)}catch(t){return console.log(t),n.mkStmt(ve(`conversion failed for ${e.name||e.kind}`,[]))}}function we(e){if(!e||!e.pyAST)return!1;if("FunctionDef"!=e.pyAST.kind)return!1;const t=e.pyAST;return!(!t.callers||1!=t.callers.length)&&!t.callers[0].inCalledPosition}function Ie(t,r=!1){return Ne(t,(()=>{const i=!!a.currClass&&!a.currFun,o=K(),s=!!a.currFun;De(t);const c=me(V(t)),l=ce(i?1:3,t);if(!r&&(c&&c.declared===f&&W(t,9520,lf("Duplicate function declaration")),l.declared=f,we(l)))return n.mkText("");i&&(l.isInstance=!0),a.currFun=t;let u="",d=t.name;let p=[ve("decorators",t.decorator_list.filter((e=>"property"==Re(e)?(u="get",!1):"Attribute"!=e.kind||"setter"!=e.attr||"Name"!=e.value.kind||(d=e.value.id,u="set",!1))).map(Ze))];if(t.body.length>=1&&"Raise"==t.body[0].kind&&(t.alwaysThrows=!0),i)if(a.currClass||W(t,9531,lf("method '{0}' is missing current class context",l.pyQName)),l.pyRetType||W(t,9532,lf("method '{0}' is missing a return type",l.pyQName)),"__init__"==t.name)p.push(n.mkText("constructor")),X(t,l.pyRetType,a.currClass.symInfo);else{if("__get__"==d||"__set__"==d){let e=t.vars.value,n=null==e?void 0:e.symbol;if("__set__"==d&&n){let e=ue(a.currClass.symInfo,"__get__");e&&e.pyAST&&"FunctionDef"==e.pyAST.kind&&ee(t,n.pyRetType,e.pyRetType)}d=d.replace(/_/g,"")}u||(u="_"==d[0]?l.isProtected?"protected":"private":"public"),p.push(n.mkText(u+" "),Ue(d))}else e.U.assert(!u),"_"==t.name[0]||o||r||s?p.push(n.mkText("function "),Ue(d)):p.push(n.mkText("export function "),Ue(d));let _=t.returns?xe(t.returns):l.pyRetType;p.push(function(t,r){const i=t.args;i.kwonlyargs.length&&W(t,9517,e.U.lf("keyword-only arguments not supported yet"));let a=i.args.slice();if(r?("self"!=a[0].arg&&W(t,9518,e.U.lf("first argument of method has to be called 'self'")),a.shift()):a.some((e=>"self"==e.arg))&&W(t,9519,e.U.lf("non-methods cannot have an argument called 'self'")),!t.symInfo.parameters){let r=i.defaults.length-a.length;t.symInfo.parameters=a.map((a=>{a.annotation||W(t,9519,e.U.lf("Arg '{0}' missing annotation",a.arg));let o=xe(a.annotation),s="";return r>=0&&(s=n.flattenNode([Ze(i.defaults[r])]).output,ee(a,o,ge(i.defaults[r]))),r++,{name:a.arg,description:"",type:"",initializer:s,default:s,pyType:o}}))}let o=t.symInfo.parameters.map((r=>{let i=J(r.name,{isParam:!0}),a=null==i?void 0:i.symbol;r.pyType||W(t,9530,e.U.lf("parameter '{0}' missing pyType",r.name)),ee(t,I(a),r.pyType);let o=[Ue(r.name),Ae(r.pyType,!0)];return r.default&&o.push(n.mkText(" = "+r.default)),n.mkGroup(o)}));return i.vararg&&o.push(n.mkText("TODO *"+i.vararg.arg)),i.kwarg&&o.push(n.mkText("TODO **"+i.kwarg.arg)),n.H.mkParenthesizedExpression(n.mkCommaSep(o))}(t,i),_&&q(_)!=T?Ae(_):n.mkText("")),I(l);let m=t.body.map(et);if("__init__"==t.name){a.currClass||W(t,9533,lf("__init__ method '{0}' is missing current class context",l.pyQName));for(let e of le(a.currClass)){let t=e.pyAST;t&&t.value&&m.push(n.mkStmt(n.mkText(`this.${Le(e.pyName)} = `),Ze(t.value)))}}const g=it(t);p.push(n.mkBlock(g.concat(m)));let h=n.mkGroup(p);return r?p[p.length-1].noFinalNewline=!0:h=n.mkStmt(h),h}))}const Pe={FunctionDef:e=>Ie(e),ClassDef:t=>Ne(t,(()=>{De(t);const r=ce(8,t);e.U.assert(!a.currClass);let i=K();a.currClass=t,t.isNamespace=t.decorator_list.some((e=>"Name"==e.kind&&"namespace"==e.id));let o=t.isNamespace?[n.mkText("namespace "),Ue(t.name)]:[ve("keywords",t.keywords.map(be)),ve("decorators",t.decorator_list.map(Ze)),n.mkText(i?"class ":"export class "),Ue(t.name)];if(!t.isNamespace&&t.bases.length>0)if("Enum"==Re(t.bases[0]))t.isEnum=!0;else{o.push(n.mkText(" extends ")),o.push(n.mkCommaSep(t.bases.map(Ze)));let e=function(e){let t=me(Me(e));return t&&t.pyAST&&"ClassDef"==t.pyAST.kind?t.pyAST:null}(t.bases[0]);e&&(t.baseClass=e,r.extendsTypes=[e.symInfo.pyQName])}let s=Ee(t.body);o.push(s);let c=le(t).filter((e=>2==e.kind&&e.isInstance)).map((e=>(e.pyName&&e.pyRetType||W(t,9535,lf("field definition missing py name or ret type",e.qName)),e))).map((e=>n.mkStmt(function(e){return e.pyName&&"_"==e.pyName[0]?e.isProtected?n.mkText("protected "):n.mkText("private "):n.mkText("")}(e),Ue(e.pyName),Ae(e.pyRetType))));return s.children=c.concat(s.children),n.mkStmt(n.mkGroup(o))})),Return:e=>{if(e.value){let t=a.currFun;return t&&(t.symInfo.pyRetType||W(e,9536,lf("function '{0}' missing return type",t.symInfo.pyQName)),Z(e.value,t.symInfo.pyRetType)),n.mkStmt(n.mkText("return "),Ze(e.value))}return n.mkStmt(n.mkText("return"))},AugAssign:e=>{let t=Se[e.op];return t.length>3?n.mkStmt(n.mkInfix(Ze(e.target),"=",n.H.mkCall(t,[Ze(e.target),Ze(e.value)]))):n.mkStmt(Ze(e.target),n.mkText(" "+t+"= "),Ze(e.value))},Assign:e=>Oe(e),AnnAssign:e=>Oe(e),For:t=>{if(e.U.assert(0==t.orelse.length),t.target.forTargetEndPos=t.endPos,Be(t.iter,"range")){let e=t.iter,r=Ze(t.target),i=Ue(Me(t.target));Z(t.target,k);let a=1==e.args.length?n.mkText("0"):Ze(e.args[0]),o=Ze(e.args[1==e.args.length?0:1]);return n.mkStmt(n.mkText("for ("),n.mkInfix(r,"=",a),n.mkText("; "),n.mkInfix(i,"<",o),n.mkText("; "),e.args.length>=3?n.mkInfix(i,"+=",Ze(e.args[2])):n.mkPostfix([i],"++"),n.mkText(")"),Ee(t.body))}if(f>1){const e=ge(t.target);Z(t.iter,ge(t.iter)==x?e:L(e))}return n.mkStmt(n.mkText("for ("),Ze(t.target),n.mkText(" of "),Ze(t.iter),n.mkText(")"),Ee(t.body))},While:t=>(e.U.assert(0==t.orelse.length),n.mkStmt(n.mkText("while ("),Ze(t.test),n.mkText(")"),Ee(t.body))),If:t=>{let r=t=>{let i=[n.mkText("if ("),Ze(t.test),n.mkText(")"),Ee(t.body)];return t.orelse.length&&(i[i.length-1].noFinalNewline=!0,1==t.orelse.length&&"If"==t.orelse[0].kind?(i.push(n.mkText(" else ")),e.U.pushRange(i,r(t.orelse[0]))):i.push(n.mkText(" else"),Ee(t.orelse))),i};return n.mkStmt(n.mkGroup(r(t)))},With:t=>{if(1==t.items.length&&function(e,t){let n=ge(e);return!(!n.classType||n.classType.pyQName!=t)||G(n)==t}(t.items[0].context_expr,"pins.I2CDevice")){let r=t.items[0],i=[],a=Ze(r.context_expr);if(r.optional_vars){let e=Re(r.optional_vars);if(e){let o=J(e,{isLocal:!0}),s=null==o?void 0:o.symbol;e=Le(e),i.push(n.mkStmt(n.mkText("const "+e+" = "),a)),s.pyRetType||W(t,9537,lf("function '{0}' missing return type",s.pyQName)),Z(r.context_expr,s.pyRetType),a=n.mkText(e)}}return i.push(n.mkStmt(n.mkInfix(a,".",n.mkText("begin()")))),e.U.pushRange(i,t.body.map(et)),i.push(n.mkStmt(n.mkInfix(a,".",n.mkText("end()")))),n.mkGroup(i)}let r=[],i=t.items.map(((e,t)=>{let i="with"+t;if(e.optional_vars){let t=Me(e.optional_vars);J(t,{isLocal:!0}),i=Le(t)}return r.push(n.mkStmt(n.mkText(i+".end()"))),n.mkStmt(n.mkText("const "+i+" = "),n.mkInfix(Ze(e.context_expr),".",n.mkText("begin()")))}));return e.U.pushRange(i,t.body.map(et)),e.U.pushRange(i,r),n.mkBlock(i)},Raise:e=>{let t,r=e.exc||e.cause;if(!r)return n.mkStmt(n.mkText("throw"));if(r&&"Call"==r.kind){let e=r;1==e.args.length&&(t=Ze(e.args[0]))}return t||(t=n.mkGroup([n.mkText("`"),Ze(r),n.mkText("`")])),n.mkStmt(n.H.mkCall("control.fail",[t]))},Assert:e=>(e.msg||W(e,9537,lf("assert missing message")),n.mkStmt(n.H.mkCall("control.assert",[e.test,e.msg].filter((e=>!!e)).map(Ze)))),Import:e=>{for(let t of e.names)t.asname&&J(t.asname,{expandsTo:t.name}),z(e,t.name);return n.mkText("")},ImportFrom:e=>{let t=[];for(let r of e.names)if("*"==r.name)e.module||W(e,9538,lf("import missing module name")),J(e.module,{isImportStar:!0});else{let i=e.module+"."+r.name,a=O(i),o=r.asname||r.name;he(a)?(J(o,{isImport:a,expandsTo:i}),t.push(n.mkStmt(n.mkText(`import ${Le(o)} = ${i}`)))):J(o,{expandsTo:i})}return n.mkGroup(t)},ExprStmt:e=>{return"Str"==e.value.kind?((t=e.value.s).trim().split(/\n/).length<=1?t=t.trim():t+="\n",n.mkStmt(n.mkText("/** "+t+" */"))):n.mkStmt(Ze(e.value));var t},Pass:e=>n.mkStmt(n.mkText("")),Break:e=>n.mkStmt(n.mkText("break")),Continue:e=>n.mkStmt(n.mkText("continue")),Delete:t=>(W(t,9550,e.U.lf("delete statements are unsupported")),v(t)),Try:e=>{let t=[n.mkText("try"),Ee(e.body.concat(e.orelse))];for(let r of e.handlers)t.push(n.mkText("catch ("),r.name?Ue(r.name):n.mkText("_")),r.type&&t.push(n.mkText("/* instanceof "),Ze(r.type),n.mkText(" */")),t.push(n.mkText(")"),Ee(r.body));return e.finalbody.length&&t.push(n.mkText("finally"),Ee(e.finalbody)),n.mkStmt(n.mkGroup(t))},AsyncFunctionDef:t=>(W(t,9551,e.U.lf("async function definitions are unsupported")),v(t)),AsyncFor:t=>(W(t,9552,e.U.lf("async for statements are unsupported")),v(t)),AsyncWith:t=>(W(t,9553,e.U.lf("async with statements are unsupported")),v(t)),Global:r=>{const i=j();$();for(const n of r.names){e.U.lookup(i.vars,n)||W(r,9521,e.U.lf("No binding found for global variable"));J(n,{},t.VarModifier.Global).firstRefPos<r.startPos&&W(r,9522,e.U.lf("Variable referenced before global declaration"))}return n.mkStmt(n.mkText(""))},Nonlocal:r=>{const i=j(),a=$();for(const n of r.names){const o=rt(n,a);o&&o!==i&&o.vars[n].modifier!==t.VarModifier.Global||W(r,9523,e.U.lf("No binding found for nonlocal variable"));J(n,{},t.VarModifier.NonLocal).firstRefPos<r.startPos&&W(r,9524,e.U.lf("Variable referenced before nonlocal declaration"))}return n.mkStmt(n.mkText(""))}};function Oe(t){let r,i,o,s;if("Assign"===t.kind){if(1!=t.targets.length)return W(t,9553,e.U.lf("multi-target assignment statements are unsupported")),v(t);s=t.targets[0],o=t.value,r=null,i=null}else{if("AnnAssign"!==t.kind)return t;s=t.target,o=t.value||null,r=t.annotation,i=xe(r),Z(s,i)}let c,l="",u=!!o&&Be(o,"const"),d=Re(s)||"";if(K()||a.currClass||a.currFun||"_"==d[0]||(l="export "),d&&a.currClass&&!a.currFun){u=!(!o||!a.currClass.isNamespace);let e=ue(a.currClass.symInfo,d);if(e||W(t,9544,lf("cannot get class field")),0==f)return n.mkText("/* skip for now */");e.pyRetType||W(t,9539,lf("function '{0}' missing return type",e.pyQName)),Z(s,e.pyRetType),e.isInstance=!1,l=a.currClass.isNamespace?`export ${u?"const":"let"} `:"static "}if(!o)return W(t,9555,e.U.lf("unable to determine value of assignment")),v(t);if(Z(s,ge(o)),u)return J(Me(s),{}),/^static /.test(l)||/const/.test(l)||(l+="const "),n.mkStmt(n.mkText(l),n.mkInfix(Ze(s),"=",Ze(o)));if(!l&&"Tuple"==s.kind){let r=s,i=[n.mkText("let "),n.mkText("[")];if(r.elts.filter((e=>"Name"!==e.kind)).length)return W(t,9556,e.U.lf("non-trivial tuple assignment unsupported")),v(t);let a=r.elts.map((e=>e)).map((function(e){Ve(e,"identifierCompletion"),ge(e);We(e);return Fe(e,!0)}));return i.push(n.mkCommaSep(a)),i.push(n.mkText("]")),n.mkStmt(n.mkInfix(n.mkGroup(i),"=",Ze(o)))}if("Name"===s.kind){const e=$().vars[d],t=null==e?void 0:e.symbol;t&&4===t.kind&&void 0===e.modifier&&(void 0===e.firstAssignPos||e.firstAssignPos>s.startPos)&&(e.firstAssignPos=s.startPos,e.firstAssignDepth=a.blockDepth)}if(r&&i&&("NameConstant"===o.kind&&null===o.value||"List"===o.kind&&0===o.elts.length)){const e=G(i);c=n.mkInfix(Ze(s),":",n.mkText(e))}return c||(c=Ze(s)),n.mkStmt(n.mkText(l),n.mkInfix(c,"=",Ze(o)))}function Fe(e,t=!1){let r=e.id,i=_e(r),o=null==i?void 0:i.symbol,s=$().vars[r],c=null==s?void 0:s.symbol;return void 0===e.isdef&&(!o||4===o.kind&&o!==c?(a.currClass&&!a.currFun?(e.isdef=!1,i=J(r,{})):(e.isdef=!0,i=J(r,{isLocal:!0})),o=i.symbol):e.isdef=!1,e.symbolInfo=o,e.tsType||W(e,9540,lf("definition missing ts type")),o.pyRetType||W(e,9568,lf("missing py return type")),ee(e,e.tsType,o.pyRetType)),e.isdef&&at(i,$())&&(e.isdef=!1),Qe(i,e),e.isdef&&!t?n.mkGroup([n.mkText("let "),Ue(r)]):Ue(r)}function Le(e){return n.isReservedWord(e)?e+"_":e||e}function Re(e){if("Name"==e.kind){let t=e.id,n=fe(t),r=null==n?void 0:n.symbol;return r&&r.expandsTo?r.expandsTo:t}if("Attribute"==e.kind){let t=Re(e.value);if(t)return t+"."+e.attr}}function Me(e){let t=Re(e);return t||W(null,9542,lf("Cannot get name of unknown expression kind '{0}'",e.kind)),t}function Ue(e){return"self"==e?n.mkText("this"):n.mkText(Le(e))}function Be(e,t){if("Call"!=e.kind)return!1;return Re(e.func)===t}function $e(t,r,i){let a=Se[r];return e.U.assert(!!a),a.length>3?n.H.mkCall(a,[t,i]):n.mkInfix(t,a,i)}const je={memoryview:{n:"",t:E},const:{n:"",t:k},"micropython.const":{n:"",t:k}};const Ke=function(){let e={};return Object.keys(pxtc.ts2PyFunNameMap).forEach((t=>{let n=pxtc.ts2PyFunNameMap[t];if(n&&n.n){let r={n:t,t:A(n.t),scale:n.scale};e[n.n]=r}})),Object.keys(je).forEach((t=>{e[t]=je[t]})),e}();function ze(e){return"Name"==e.kind&&"self"==e.id}function Je(e){return e.type==n.NT.Prefix&&'"'==e.op[0]?n.mkText(n.backtickLit(JSON.parse(e.op))):e}function qe(e){return u&&e.startPos<=u.position&&u.position<=e.endPos}function Ve(e,t){f>100&&u&&null==d&&(u.type==t||"symbol"==u.type)&&qe(e)&&(d=e,p=$())}function He(e,t){if(t&&t.pyAST&&"FunctionDef"==t.pyAST.kind){let n=t.pyAST;n.callers||(n.callers=[]),n.callers.indexOf(e)<0&&n.callers.push(e)}}const Ge={BoolOp:e=>{let t=Ze(e.values[0]);for(let n=1;n<e.values.length;++n)t=$e(t,e.op,Ze(e.values[n]));return t},BinOp:e=>{let t=function(e){if("Mod"==e.op&&"Str"==e.left.kind&&("Tuple"==e.right.kind||"List"==e.right.kind)){let t=e.left.s,r=e.right.elts;r=r.slice();let i=[n.mkText("`")];return t.replace(/([^%]+)|(%[\d\.]*([a-zA-Z%]))/g,((e,t,a,o)=>{if(t)i.push(n.mkText(t.replace(/[`\\$]/g,(e=>"\\"+e))));else{let e=r.shift(),t=e?Ze(e):n.mkText("???");i.push(n.mkText("${"),t,n.mkText("}"))}return""})),i.push(n.mkText("`")),n.mkGroup(i)}return null}(e);if(t)return t;const r=Ze(e.left),i=Ze(e.right);return ct(e.left)&&ct(e.right)&&"Add"===e.op?n.H.extensionCall("concat",[r,i],!1):(t=$e(r,e.op,i),ke[e.op]&&(Z(e.left,k),Z(e.right,k),e.tsType||W(e,9570,lf("binary op missing ts type")),ee(e,e.tsType,k)),t)},UnaryOp:t=>{let r=Te[t.op];return e.U.assert(!!r),n.mkInfix(null,r,Ze(t.operand))},Lambda:t=>(W(t,9574,e.U.lf("lambda expressions are not supported yet")),b(t)),IfExp:e=>n.mkInfix(n.mkInfix(Ze(e.test),"?",Ze(e.body)),":",Ze(e.orelse)),Dict:e=>{a.blockDepth++;const t=e.keys.map(((t,r)=>{const i=e.values[r];return void 0===t?b(e):n.mkStmt(n.mkInfix(Ze(t),":",Ze(i)),n.mkText(","))})),r=n.mkBlock(t);return a.blockDepth--,r},Set:e=>b(e),ListComp:e=>b(e),SetComp:e=>b(e),DictComp:e=>b(e),GeneratorExp:e=>{if(1==e.generators.length&&"Comprehension"==e.generators[0].kind){let t=e.generators[0];if(0==t.ifs.length)return ye((()=>{let r=Me(t.target);return J(r,{isParam:!0}),n.mkInfix(Ze(t.iter),".",n.H.mkCall("map",[n.mkGroup([Ue(r),n.mkText(" => "),Ze(e.elt)])]))}))}return b(e)},Await:e=>b(e),Yield:e=>b(e),YieldFrom:e=>b(e),Compare:e=>{if(1==e.ops.length&&("In"==e.ops[0]||"NotIn"==e.ops[0])){q(ge(e.comparators[0]))==x&&Z(e.left,x);let t=n.mkInfix(Ze(e.comparators[0]),".",n.H.mkCall("indexOf",[Ze(e.left)]));return n.mkInfix(t,"In"==e.ops[0]?">=":"<",n.mkText("0"))}let t=$e(Ze(e.left),e.ops[0],Ze(e.comparators[0]));for(let n=1;n<e.ops.length;++n)t=$e(t,"And",$e(Ze(e.comparators[n-1]),e.ops[n],Ze(e.comparators[n])));return t},Call:t=>{t.func.inCalledPosition=!0;let r,i,o=Re(t.func),s=me(o),c=s&&8==s.kind,l=s,f="";if(c)l=me(s.pyQName+".__constructor");else if("Attribute"==t.func.kind){let e=t.func;i=e.value,r=ge(i),(r.classType||r.primType)&&(f=e.attr,l=de(i,f,!0),l&&(f=l.name))}let _=t.args.slice();if("super"==o&&0==_.length)return a.currClass&&a.currClass.baseClass&&(t.tsType||W(t,9543,lf("call expr missing ts type")),X(t,t.tsType,a.currClass.baseClass.symInfo)),n.mkText("super");if(Be(t,"int")&&1===_.length&&_[0]){const e=_[0],t=Ze(e),r=ge(e);if("string"===r.primType)return n.mkGroup([n.mkText("parseInt"),n.mkText("("),t,n.mkText(")")]);if("number"===r.primType)return n.mkGroup([n.mkInfix(n.mkText("Math"),".",n.mkText("trunc")),n.mkText("("),t,n.mkText(")")])}if(!l){let t=e.U.lookup(Ke,o);if(t&&(f=""),f&&(o=G(r)+"."+f,t=e.U.lookup(Ke,o),t||"@array"!=Q(q(r))||(o="Array."+f,t=e.U.lookup(Ke,o))),f="",t)if("."==t.n[0]&&_.length){if(i=_.shift(),r=ge(i),f=t.n.slice(1),l=de(i,f),l&&2==l.kind)return n.mkInfix(Ze(i),".",n.mkText(f))}else l=O(t.n)}if(Be(t,"str"))return ee(t,t.tsType,x),n.mkInfix(n.mkText('""'),"+",Ze(t.args[0]));l||W(t,9508,e.U.lf("can't find called function '{0}'",o));let m=l?l.parameters:null,g=[];if(m){for(_.length>m.length&&W(t,9510,e.U.lf("too many arguments in call to '{0}'",l.pyQName));_.length<m.length;)_.push(null);_=_.slice(0,m.length);for(let n of t.keywords){let t=m.findIndex((e=>e.name==n.arg));t<0?W(n,9511,e.U.lf("'{0}' doesn't have argument named '{1}'",l.pyQName,n.arg)):null!=_[t]?W(n,9512,e.U.lf("argument '{0} already specified in call to '{1}'",n.arg,l.pyQName)):_[t]=n.value}for(let e=_.length-1;e>=0&&(m[e].initializer&&null==_[e]);e--)_.pop();for(let r=0;r<_.length;++r){let i=_[r];if(null!=i||m[r].initializer)if(i){m[r].pyType||W(t,9545,lf("formal arg missing py type"));const e=m[r].pyType;"any"!==e.primType&&ne(i,e),"Name"==i.kind&&we(i.symbolInfo)?g.push(Ie(i.symbolInfo.pyAST,!0)):g.push(Ze(i))}else m[r].initializer||W(t,9547,lf("formal arg missing initializer")),g.push(n.mkText(m[r].initializer));else W(t,9513,e.U.lf("missing argument '{0}' in call to '{1}'",m[r].name,l.pyQName)),g.push(n.mkText("null"))}}else l&&W(t,9509,e.U.lf("calling non-function")),g=_.map(Ze);if(!d&&u&&"signature"==u.type&&qe(t)){d=t,p=$(),u.auxResult=0;for(let e=0;e<_.length;++e){u.auxResult=e;let t=_[e];if(!t)break;if(t.startPos<=u.position&&u.position<=t.endPos)break}}if(l)if(l.pyRetType||W(t,9549,lf("function missing pyRetType")),i&&ct(i)&&r?function(e,t,n){switch(t.qName){case"Array.pop":case"Array.removeAt":case"Array.shift":case"Array.find":case"Array.get":case"Array._pickRandom":Z(e,n.typeArgs[0]);break;case"Array.concat":case"Array.slice":case"Array.filter":case"Array.fill":Z(e,n);break;case"Array.reduce":if("Call"===e.kind&&e.args.length>1){const t=ge(e.args[1]);t&&Z(e,t)}break;case"Array.map":Z(e,L(C));break;default:Z(e,t.pyRetType)}}(t,l,r):Z(t,l.pyRetType),t.symbolInfo=l,l.attributes.py2tsOverride){const e=function(e){const t=new RegExp(/([^\$]*\()?([^\$\(]*)\$(\d)(?:(?:(?:=(\d+|'[a-zA-Z0-9_]*'|false|true|null|undefined))|(\?)|))/,"y"),n=[];let r,i=0;do{i=t.lastIndex,r=t.exec(e),r&&(r[1]&&n.push({kind:"text",text:r[1]}),n.push({kind:"arg",prefix:r[2],index:parseInt(r[3]),default:r[4],isOptional:!!r[5]}))}while(r);null!=i?n.push({kind:"text",text:e.substr(i)}):n.push({kind:"text",text:e});return{parts:n}}(l.attributes.py2tsOverride);if(e){f&&!i&&W(t,9550,lf("missing recv"));let r=function(e,t,r){const i=[];for(const r of e.parts)if("text"===r.kind)i.push(n.mkText(r.text));else if(t[r.index]||r.default)r.prefix&&i.push(n.mkText(r.prefix)),t[r.index]?i.push(t[r.index]):i.push(n.mkText(r.default));else if(!r.isOptional)return;if(r)return n.mkInfix(r,".",n.mkGroup(i));return n.mkGroup(i)}(e,g,f?Ze(i):void 0);return r||W(t,9555,lf("buildOverride failed unexpectedly")),r}}else if(l.attributes.pyHelper)return n.mkGroup([n.mkInfix(n.mkText("_py"),".",n.mkText(l.attributes.pyHelper)),n.mkText("("),n.mkCommaSep(i?[Ze(i)].concat(g):g),n.mkText(")")]);let h=f?n.mkInfix(Ze(i),".",n.mkText(f)):Ze(t.func),y=[h,n.mkText("("),n.mkCommaSep(g),n.mkText(")")];return l&&1==g.length&&pxtc.service.isTaggedTemplate(l)&&(y=[h,Je(g[0])]),c&&(s&&s.pyQName||W(t,9551,lf("missing namedSymbol or pyQName")),y[0]=n.mkText(H(s.pyQName)),y.unshift(n.mkText("new "))),n.mkGroup(y)},Num:e=>(e.tsType||W(e,9556,lf("tsType missing")),ee(e,e.tsType,k),n.mkText(e.ns)),Str:e=>(e.tsType||W(e,9557,lf("tsType missing")),ee(e,e.tsType,x),n.mkText(n.stringLit(e.s))),FormattedValue:e=>b(e),JoinedStr:e=>b(e),Bytes:t=>n.mkText(`hex\`${e.U.toHex(new Uint8Array(t.s))}\``),NameConstant:e=>(null!==e.value&&(e.tsType||W(e,9558,lf("tsType missing")),ee(e,e.tsType,S)),n.mkText(JSON.stringify(e.value))),Ellipsis:e=>b(e),Constant:e=>b(e),Attribute:t=>{let r=Ze(t.value),i=ge(t.value),a=de(t.value,t.attr),o=t.attr;if(Ve(t,"memberCompletion"),a)t.symbolInfo=a,He(t,a),t.tsType&&a.pyRetType||W(t,9559,lf("tsType or pyRetType missing")),ee(t,t.tsType,a.pyRetType),o=a.name;else if(i.moduleType){let n=O(i.moduleType.pyQName+"."+t.attr);n?(t.symbolInfo=n,He(t,n),Z(t,I(n)),o=n.name):W(t,9514,e.U.lf("module '{0}' has no attribute '{1}'",i.moduleType.pyQName,t.attr))}else f>2&&W(t,9515,e.U.lf("unknown object type; cannot lookup attribute '{0}'",t.attr));return n.mkInfix(r,".",n.mkText(Le(o)))},Subscript:e=>{if("Index"==e.slice.kind){const t=q(ge(e.value));if(ct(e.value)){Z(e,t.typeArgs[0])}else"string"===t.primType?Z(e,t):f>2&&Y(ge(e))&&Z(e,C);let r=e.slice.value;return f>2&&Y(ge(r))&&Z(r,k),n.mkGroup([Ze(e.value),n.mkText("["),Ze(r),n.mkText("]")])}if("Slice"==e.slice.kind){const t=ge(e.value);Z(e,t);let r=e.slice;if(r.step){const i="string"===(null==t?void 0:t.primType);return n.H.mkCall(i?"_py.stringSlice":"_py.slice",[Ze(e.value),r.lower?Ze(r.lower):n.mkText("null"),r.upper?Ze(r.upper):n.mkText("null"),Ze(r.step)])}return n.mkInfix(Ze(e.value),".",n.H.mkCall("slice",[r.lower?Ze(r.lower):n.mkText("0"),r.upper?Ze(r.upper):null].filter(y)))}return b(e)},Starred:e=>n.mkGroup([n.mkText("... "),Ze(e.value)]),Name:e=>{if(Ve(e,"identifierCompletion"),"self"==e.id&&a.currClass)return e.tsType||W(e,9560,lf("missing tsType")),X(e,e.tsType,a.currClass.symInfo),n.mkText("this");let t=We(e),r=null==t?void 0:t.symbol;if(r&&r.isImport)return Ue(r.name);if(Qe(t,e),e.ctx.indexOf("Load")>=0){if(!r)return Ue(Me(e));if(!(null==r?void 0:r.qName))return W(e,9561,lf("missing qName")),Ue("unknown");return Ue(r.qName.replace("@type",""))}return Fe(e)},List:Ye,Tuple:Ye};function We(t){let n=_e(t.id),r=null==n?void 0:n.symbol;if(!n){let r=e.U.lookup(Ke,t.id);r&&(n=_e(r.n))}if(n&&r){if(t.symbolInfo=r,t.tsType||W(t,9562,lf("missing tsType")),ee(t,t.tsType,I(r)),r.isImport)return n;He(t,r),t.forTargetEndPos&&n.forVariableEndPos!==t.forTargetEndPos&&(n.forVariableEndPos?n.lastRefPos=n.forVariableEndPos+1:n.forVariableEndPos=t.forTargetEndPos)}else f>0&&W(t,9516,e.U.lf("name '{0}' is not defined",t.id));return n}function Qe(e,n){if(e){if(e.modifier===t.VarModifier.Global){const t=j();t&&t.vars[e.symbol.name]&&(e=t.vars[e.symbol.name])}else if(e.modifier===t.VarModifier.NonLocal){const t=rt(e.symbol.name,$());t&&(e=t.vars[e.symbol.name])}(void 0===e.firstRefPos||e.firstRefPos>n.startPos)&&(e.firstRefPos=n.startPos),(void 0===e.lastRefPos||e.lastRefPos<n.startPos)&&(e.lastRefPos=n.startPos)}}function Ye(e){return e.tsType||W(e,9563,lf("missing tsType")),ee(e,e.tsType,L(e.elts[0]?ge(e.elts[0]):F())),n.mkGroup([n.mkText("["),n.mkCommaSep(e.elts.map(Ze)),n.mkText("]")])}function Xe(e){return`${e.startPos}:${e.endPos}`}function Ze(t){o=t;let n=Ge[t.kind];n||e.U.oops(t.kind+" - unknown expr"),ge(t);const r=n(t);return r.id=Xe(t),r}function et(t){o=t;let r=Pe[t.kind];r||e.U.oops(t.kind+" - unknown stmt");let i=(t._comments||[]).map((e=>e.value)),a=r(t);return i.length&&(a=n.mkGroup(i.map((e=>n.mkStmt(n.H.mkComment(e)))).concat(a))),a.id=Xe(t),a}function tt(e){return!e||(e.type==n.NT.Prefix&&""==e.op?e.children.every(tt):e.type==n.NT.NewLine)}function nt(e){const t=Ue(e.name),r=G(I(e));return n.mkStmt(n.mkGroup([n.mkText("let "),t,n.mkText(": "+r+";")]))}function rt(e,n){if(!n)return;const r=n.vars&&n.vars[e];return r&&r.modifier!=t.VarModifier.NonLocal?n:rt(e,n.parent)}function it(e){const t=[];let n;for(const r of Object.keys(e.vars))n=e.vars[r],at(n,e)&&t.push(nt(null==n?void 0:n.symbol));return t}function at(e,t){return!!(4===e.symbol.kind&&!e.symbol.isParam&&void 0===e.modifier&&(e.lastRefPos>e.forVariableEndPos||e.firstRefPos<e.firstAssignPos||e.firstAssignDepth>t.blockDepth)&&!(function(e){return"Module"===e.kind&&"main"===e.name}(t)&&0===e.firstAssignDepth))}function ot(t){if(e.U.assert("Module"==t.kind),t.tsBody)return;var r;a={currClass:void 0,currFun:void 0,currModule:r=t,blockDepth:0},s=r.tsFilename.replace(/\.ts$/,".py"),t.vars||(t.vars={});let i=it(t).concat(t.body.map(et));return i.every(tt)?void 0:"main"==t.name?i:[n.mkText("namespace "+t.name+" "),n.mkBlock(i)]}function st(e){f=e,c=[],m=0,o=void 0}function ct(e){const t=q(ge(e));return t&&"@array"===t.primType}t.py2ts=function(a){let o=[];const f={};c=[],e.U.assert(!!a.sourceFiles,"missing sourceFiles! Cannot convert py to ts");let _=a.sourceFiles.filter((t=>e.U.endsWith(t,".py")));if(0==_.length)return{outfiles:f,diagnostics:c,success:0===c.length,sourceMap:[]};let g=(e,t)=>e.substr(0,e.length-t.length),h=e.U.toDictionary(_,(e=>g(e,".py"))),y=a.sourceFiles.filter((t=>e.U.endsWith(t,".ts"))).filter((e=>g(e,".ts")in h));e.U.assert(!!a.apisInfo,"missing apisInfo! Cannot convert py to ts"),s=_[0],function(t,n){i={},r={};let a=e.U.toDictionary(n,(e=>e));for(let n of e.U.values(t.byQName)){if(a.hasOwnProperty(n.fileName))continue;let t=n;t.extendsTypes&&(t.extendsTypes=t.extendsTypes.filter((e=>e!=t.qName))),t.pyQName&&t.qName||W(null,9526,e.U.lf("Symbol '{0}' is missing qName for '{1}'",t.name,t.pyQName?"ts":"py")),r[t.pyQName]=t,r[t.qName]=t}E=w("Buffer")}(a.apisInfo,y),l=a,u=void 0,a.generatedFiles||(a.generatedFiles=[]);for(const t of _){let n=t,r=t.replace(/\.py$/,"").replace(/.*\//,""),i=a.fileSystem[t];try{s=t;let a=e.py.lex(i),l=e.py.parse(i,n,a);e.U.pushRange(c,l.diagnostics),o.push({kind:"Module",body:l.stmts,blockDepth:0,name:r,source:i,tsFilename:n.replace(/\.py$/,".ts")})}catch(e){console.log("Parse error",e)}}const v=c;for(let e=0;e<5;++e){st(e);for(let e of o)try{ot(e)}catch(e){console.log("Conv pass error",e)}if(0==m)break}st(1e3),d=void 0,u=a.syntaxInfo||{position:0,type:"symbol"};let b=[];for(let e of o)try{let t=ot(e);if(!t)continue;let r=n.flattenNode(t);function x(e){let t=e.id.split(":");if(2!=t.length)return;let n=t.map((e=>parseInt(e)));return{py:{startPos:n[0],endPos:n[1]},ts:{startPos:e.startPos,endPos:e.endPos}}}a.sourceFiles.push(e.tsFilename),a.generatedFiles.push(e.tsFilename),a.fileSystem[e.tsFilename]=r.output,f[e.tsFilename]=r.output,b=r.sourceMap.map(x).filter((e=>!!e))}catch(e){console.log("Conv error",e)}c=v.concat(c);let k={};const S=e.U.values(r).concat(e.U.values(i));let T=[];const C=e=>{if((e=>{switch(e.kind){case 6:case 7:case 4:case 3:case 5:return!0;case 2:case 1:return!e.isInstance;default:return!1}})(e)&&T.indexOf(e)<0){let t=N(e);k[t.qName||t.name]=t}};for(let t=p;t;t=t.parent)t&&t.vars&&e.U.values(t.vars).map((e=>e.symbol)).forEach(C);if(S.forEach(C),u&&d){if(d=d,u.beginPos=d.startPos,u.endPos=d.endPos,u.symbols||(u.symbols=[]),T=u.symbols.slice(),"memberCompletion"==u.type&&"Attribute"==d.kind){const e=ge(d.value);if(e.moduleType)for(let t of S)t.isInstance||t.namespace!=e.moduleType.qName||u.symbols.push(t);else if(e.classType||e.primType){const t=e.classType||pe(e.primType).reduce(((e,t)=>e||t),null);if(t){t.extendsTypes&&t.qName||W(null,9567,lf("missing extendsTypes or qName"));let e=t.extendsTypes.concat(t.qName);for(let t of S)t.isInstance&&e.indexOf(t.namespace)>=0&&u.symbols.push(t)}}}else if("identifierCompletion"==u.type)u.symbols=e.U.values(k);else{let e=d.symbolInfo;e&&u.symbols.push(e)}u.symbols=u.symbols.map(N)}let D=function(){for(let e of c)t.patchPosition(e,a.fileSystem[e.fileName]);return c}();return{outfiles:f,success:0===D.length,diagnostics:D,syntaxInfo:u,globalNames:k,sourceMap:b}}}(e.py||(e.py={}))}(pxt||(pxt={})),function(e){!function(t){let n;!function(e){e[e.Id=0]="Id",e[e.Op=1]="Op",e[e.Keyword=2]="Keyword",e[e.Number=3]="Number",e[e.String=4]="String",e[e.NewLine=5]="NewLine",e[e.Comment=6]="Comment",e[e.Indent=7]="Indent",e[e.Dedent=8]="Dedent",e[e.EOF=9]="EOF",e[e.Error=10]="Error"}(n=t.TokenType||(t.TokenType={})),t.keywords={False:!0,None:!0,True:!0,and:!0,as:!0,assert:!0,async:!0,await:!0,break:!0,class:!0,continue:!0,def:!0,del:!0,elif:!0,else:!0,except:!0,finally:!0,for:!0,from:!0,global:!0,if:!0,import:!0,in:!0,is:!0,lambda:!0,nonlocal:!0,not:!0,or:!0,pass:!0,raise:!0,return:!0,try:!0,while:!0,with:!0,yield:!0};let r,i,a=[];const o={"%":"Mod","&":"BitAnd","*":"Mult","**":"Pow","+":"Add","-":"Sub","/":"Div","//":"FloorDiv","<<":"LShift",">>":"RShift","@":"MatMult","^":"BitXor","|":"BitOr"},s={"!":"Bang","!=":"NotEq","(":"LParen",")":"RParen",",":"Comma","->":"Arrow",".":"Dot",":":"Colon",";":"Semicolon","<":"Lt","<=":"LtE","=":"Assign","==":"Eq",">":"Gt",">=":"GtE","[":"LSquare","]":"RSquare","{":"LBracket","}":"RBracket","~":"Invert"},c={b:/^[_0-1]$/,B:/^[_0-1]$/,o:/^[_0-7]$/,O:/^[_0-7]$/,x:/^[_0-9a-fA-F]$/,X:/^[_0-9a-fA-F]$/},l={b:2,B:2,o:8,O:8,x:16,X:16};let u,d,p=0,f=0;function _(e,t){let n=0,r=0;for(let i=0;i<e;++i)10==t.charCodeAt(i)&&(n++,r=i);return{line:n,column:e-r-1}}function m(e){switch(e.type){case n.Id:return`id(${e.value})`;case n.Op:return"'"+i[e.value]+"'";case n.Keyword:return e.value;case n.Number:return`num(${e.value})`;case n.String:return e.stringPrefix+JSON.stringify(e.value);case n.NewLine:return"<nl>";case n.Comment:return`/* ${e.value} */`;case n.Indent:return"indent"+e.value;case n.Dedent:return"dedent";case n.Error:return`[ERR: ${e.value}]`;case n.EOF:return"End of file";default:return"???"}}t.position=_,t.patchPosition=function(e,t){if(!e.start&&!e.length)return e.start=0,e.length=0,e.line=0,void(e.column=0);let n=_(e.start,t);e.line=n.line,e.column=n.column,e.length>0&&(n=_(e.start+e.length-1,t),e.endLine=n.line,e.endColumn=n.column+2)},t.tokenToString=m,t.friendlyTokenToString=function(e,t){let n=e.endPos-e.startPos,r="";return r=0==n?m(e):n>20?"`"+t.slice(e.startPos,e.startPos+20)+"`...":"`"+t.slice(e.startPos,e.endPos)+"`",r=r.replace(/\r/g,"").replace(/\n/g,"\\n").replace(/\t/g,"\\t"),r},t.tokensToString=function(e){let t="",r=0;for(let i of e){let e=m(i);r+e.length>70&&(r=0,t+="\n"),0!=r&&(t+=" "),t+=e,r+=e.length,i.type!=n.NewLine&&i.type!=n.Comment||(r=0,t+="\n")}return t},t.lex=function(_){for(0==a.length&&function(){const n={'"':k,"'":k,"#":E,"\\":C,".":A};r=e.U.clone(s);for(let e of Object.keys(o))r[e]=o[e],r[e+"="]=o[e]+"Assign";i={};for(let e of Object.keys(r))i[r[e]]=e;for(let e=0;e<128;++e)if(t.rx.isIdentifierStart(e))a[e]=h;else{let i=String.fromCharCode(e);if(n.hasOwnProperty(i))a[e]=n[i];else if(r.hasOwnProperty(i)){let t=!1,n=r[i];for(let e of Object.keys(r))e!=i&&e.startsWith(i)&&(t=!0);a[e]=t?()=>v(n):()=>y(n)}else t.rx.isSpace(e)?a[e]=()=>{}:13==e?a[e]=()=>{10==d.charCodeAt(p)&&p++,S()}:t.rx.isNewline(e)?a[e]=S:N(e)?a[e]=D:a[e]=w}}(),d=_,u=[],p=0,f=0,T();p<d.length;){f=p;const e=d.charCodeAt(p++);e<128?a[e]():t.rx.isIdentifierStart(e)?h():t.rx.isSpace(e)||(t.rx.isNewline(e)?S():w())}return f=p,S(),m(n.EOF,""),u;function m(e,t,n){let r={type:e,value:t,startPos:f,endPos:p,auxValue:n};return u.push(r),r}function g(e){m(n.Error,e)}function h(){for(;t.rx.isIdentifierChar(d.charCodeAt(p));)p++;let e=d.slice(f,p),r=d.charCodeAt(p);t.keywords.hasOwnProperty(e)?m(n.Keyword,e):34==r||39==r?x(e):m(n.Id,e)}function y(e){m(n.Op,e)}function v(e){let t=d.slice(f,p+1);if(2==t.length&&r.hasOwnProperty(t)){let n=d.slice(f,p+2);3==n.length&&r.hasOwnProperty(n)?(p+=2,e=r[n]):(p++,e=r[t])}y(e)}function b(e){switch(e){case 97:return 7;case 98:return 8;case 102:return 12;case 110:return 10;case 114:return 13;case 116:return 9;case 118:return 11;default:return 0}}function x(r){const i=d.charCodeAt(p++);let a=!1;d.charCodeAt(p)==i&&d.charCodeAt(p+1)==i&&(p+=2,a=!0);let o=(r=r.toLowerCase()).indexOf("r")>=0,s="",c="";for(;;){const n=d.charCodeAt(p++);if(n==i){if(!a)break;if(d.charCodeAt(p)==i&&d.charCodeAt(p+1)==i){p+=2;break}c+="\\"+String.fromCharCode(i),s+=String.fromCharCode(i)}else if(92==n){let n=d.charCodeAt(p++);if(13==n&&10==d.charCodeAt(p)&&(n=10,p++),34==n||39==n||92==n)o&&(c+="\\",s+="\\"),c+="\\"+String.fromCharCode(n),s+=String.fromCharCode(n);else if(!o&&b(n))c+="\\"+String.fromCharCode(n),s+=String.fromCharCode(b(n));else if(t.rx.isNewline(n))o&&(s+="\\"+String.fromCharCode(n),c+="\\\\",c+=10==n?"\\n":"\\u"+("0000"+n.toString(16)).slice(-4));else if(o||48!=n)if(o||117!=n&&120!=n)c+="\\\\"+String.fromCharCode(n),s+="\\"+String.fromCharCode(n);else{let t=117==n?4:2,r=d.slice(p,p+t);p+=t;let i=parseInt(r,16);isNaN(i)&&g(e.U.lf("invalid unicode or hex escape")),c+="\\"+String.fromCharCode(n)+r,s+=String.fromCharCode(i)}else c+="\\\\x00",s+="\0"}else{if(isNaN(n)){g(e.U.lf("end of file in a string"));break}if(t.rx.isNewline(n)&&!a){g(e.U.lf("new line in a string"));break}s+=String.fromCharCode(n),c+=String.fromCharCode(n)}}let l=m(n.String,s);l.quoted=c,l.stringPrefix=r}function k(){p--,x("")}function S(){m(n.NewLine,""),T()}function T(){let e=0;for(;;){const t=d.charCodeAt(p);if(9!=t){if(32!=t)break;e++,p++}else e=e+8&-8,p++}m(n.Indent,""+e)}function C(){let n=d.charCodeAt(p);t.rx.isNewline(n)?(p++,13==n&&10==d.charCodeAt(p)&&p++):g(e.U.lf("unexpected character after line continuation character"))}function E(){for(m(n.NewLine,"");p<d.length&&!t.rx.isNewline(d.charCodeAt(p));)p++;m(n.Comment,d.slice(f+1,p)),13==d.charCodeAt(p)&&10==d.charCodeAt(p+1)&&p++,p++,T()}function D(){let t=d[f],r="";if("0"==t){let i=d[p];const a=c[i];if(a){for(p++;;){const e=d[p];if(!a.test(e))break;r+=e,p++}if(r){let a=parseInt(r,l[i]);isNaN(a)&&g(e.U.lf("invalid number")),m(n.Number,t+i+r,a)}else g(e.U.lf("expecting numbers to follow 0b, 0o, 0x"));return}}let i=!1,a=!1,o=!1;for(p=f;;){const e=d.charCodeAt(p);if(!o||43!=e&&45!=e)if(o=!1,95==e||N(e));else if(a||i||46!=e){if(a||69!=e&&101!=e)break;a=!0,o=!0}else i=!0;else;r+=String.fromCharCode(e),p++}!i&&!a&&"0"==t&&r.length>1&&!/^0+/.test(r)&&g(e.U.lf("unexpected leading zero"));let s=parseFloat(r);isNaN(s)&&g(e.U.lf("invalid number")),m(n.Number,r,s)}function A(){N(d.charCodeAt(p))?D():m(n.Op,"Dot")}function N(e){return 48<=e&&e<=57}function w(){g(e.U.lf("invalid token"))}}}(e.py||(e.py={}))}(pxt||(pxt={})),function(e){!function(t){let n,r,i,a,o,s,c,l,u;function d(){return r[o]}function p(){for(;r[o];o++){let i=r[o];if(i.type!=t.TokenType.Comment){if(n>=0&&i.type==t.TokenType.Op)switch(i.value){case"LParen":case"LSquare":case"LBracket":n++;break;case"RParen":case"RSquare":case"RBracket":n--}if(i.type!=t.TokenType.Error){if(n>0){if(i.type==t.TokenType.NewLine||i.type==t.TokenType.Indent)continue}else if(i.type==t.TokenType.Indent){if(r[o+1].type==t.TokenType.NewLine){o++;continue}let n=parseInt(i.value),a=c[c.length-1];if(n==a)continue;if(n>a)return void c.push(n);{i.type=t.TokenType.Dedent;let a=0;for(;c.length;){let t=c[c.length-1];if(!(t>n)){for(t!=n&&_(9552,e.U.lf("inconsitent indentation"));a>1;)r.splice(o,0,i),a--;return}c.pop(),a++}}}return}_(9551,i.value)}else s.push(i)}}function f(){l=d(),l.type!=t.TokenType.EOF&&(o++,p())}function _(n,r){r||(r=e.U.lf("invalid syntax")),n||(n=9550);const o=d(),s={code:n,category:pxtc.DiagnosticCategory.Error,messageText:e.U.lf("{0} near {1}",r,t.friendlyTokenToString(o,i)),fileName:a,start:o.startPos,length:o.endPos?o.endPos-o.startPos:0,line:0,column:0};t.patchPosition(s,i),u.push(s),9572!=n&&u.length>100&&e.U.userError(e.U.lf("too many parse errors"))}function m(n,r){const i=d();(i.type==n&&i.value==r||(_(9553,e.U.lf("expecting {0}",t.tokenToString(function(e,t){return{type:e,value:t,startPos:0,endPos:0}}(n,r)))),i.type!=t.TokenType.NewLine))&&f()}function g(){m(t.TokenType.NewLine,"")}function h(e){m(t.TokenType.Keyword,e)}function y(e){m(t.TokenType.Op,e)}function v(){let e=d();return e.type==t.TokenType.Keyword?e.value:""}function b(){let e=d();return e.type==t.TokenType.Op?e.value:""}const x={if:function e(){let t=T("If");f(),t.test=V(),t.body=S(),"elif"==v()?t.orelse=[e()]:t.orelse=E();return C(t)},while:function(){let e=T("While");return h("while"),e.test=V(),e.body=S(),e.orelse=E(),C(e)},for:function(){let e=T("For");return h("for"),e.target=B(),$(e.target),h("in"),e.iter=U(),e.body=S(),e.orelse=E(),C(e)},try:function(){let e=T("Try");h("try"),e.body=S(),e.handlers=[];let t=!1;for(;"except"==v();){let n=T("ExceptHandler");e.handlers.push(n),f(),"Colon"!=b()?(t&&_(),n.type=V(),"as"==v()?(f(),n.name=ve()):n.name=void 0):(t=!0,n.type=void 0,n.name=void 0),n.body=S()}e.orelse=E(),0==e.handlers.length&&e.orelse.length&&_();"finally"==v()?(f(),e.finalbody=S()):e.finalbody=[];return C(e)},with:function(){let t=T("With");return h("with"),t.items=ge(e.U.lf("with item"),D),t.body=S(),C(t)},def:function(){let e=T("FunctionDef");h("def"),e.name=ve(),y("LParen"),e.args=J(!0),y("RParen"),e.returns=void 0,"Arrow"==b()&&(f(),e.returns=V());return e.body=S(),C(e)},class:function(){let e=T("ClassDef");if(h("class"),e.name=ve(),"LParen"==b()){let t=be();e.bases=t.args,e.keywords=t.keywords}else e.bases=[],e.keywords=[];return e.body=S(),C(e)}},k={del:function(){let t=T("Delete");return h("del"),t.targets=me(e.U.lf("expression"),oe),C(t)},pass:function(){let e=T("Pass");return h("pass"),C(e)},break:function(){let e=T("Break");return f(),C(e)},continue:function(){let e=T("Continue");return f(),C(e)},return:function(){let e=T("Return");f(),N()?e.value=void 0:e.value=U();return C(e)},raise:function(){let e=T("Raise");h("raise"),e.exc=void 0,e.cause=void 0,N()||(e.exc=V(),"from"==v()&&(f(),e.cause=V()));return C(e)},global:w,nonlocal:function(){let e=w();return e.kind="Nonlocal",e},import:function(){let t=T("Import");return f(),t.names=ge(e.U.lf("import name"),P),C(t)},from:function(){let n=T("ImportFrom");f(),n.level=F(),d().type==t.TokenType.Id?n.module=I():n.module=void 0;n.level||n.module||_();if(h("import"),"Mult"==b()){f();let e=T("Alias");e.name="*",n.names=[e]}else"LParen"==b()?(f(),n.names=me(e.U.lf("import name"),O),y("RParen")):n.names=me(e.U.lf("import name"),O);return C(n)},assert:function(){let e=T("Assert");f(),e.test=V(),"Comma"==b()?(f(),e.msg=V()):e.msg=void 0;return C(e)},yield:function(){d();if(f(),"from"==v()){let e=T("YieldFrom");return e.value=V(),A(C(e))}let e=T("Yield");N()||(e.value=U());return A(C(e))}};function S(){return y("Colon"),function(){if(d().type==t.TokenType.NewLine){let n;if(f(),d().type!=t.TokenType.Indent)_(9554,e.U.lf("expected an indented block")),n=z();else{const r=parseInt(d().value);for(f(),n=z();;){if(d().type==t.TokenType.Dedent){const e=isNaN(r)||parseInt(d().value)<r;if(f(),e)break}if(e.U.pushRange(n,z()),d().type==t.TokenType.EOF)break}}return n}return K()}()}function T(e,t){let n=t||d();return{startPos:n.startPos,endPos:n.endPos,kind:e}}function C(e){return e.endPos=l.endPos,e}function E(){return"else"==v()?(f(),S()):[]}function D(){let e=T("WithItem");return e.context_expr=V(),e.optional_vars=void 0,"as"==v()&&(f(),e.optional_vars=oe()),C(e)}function A(e){let t=T("ExprStmt");return t.startPos=e.startPos,t.endPos=e.endPos,t.value=e,t}function N(){let e=d();return e.type==t.TokenType.NewLine||e.type==t.TokenType.Op&&"Semicolon"==e.value}function w(){let e=T("Global");for(f(),e.names=[];e.names.push(ve()),"Comma"==b();)f();return C(e)}function I(){let e="";for(;;){if(e+=ve(),"Dot"!=b())return e;e+=".",f()}}function P(){let e=T("Alias");return e.name=I(),"as"==v()?(f(),e.asname=ve()):e.asname=void 0,C(e)}function O(){let e=T("Alias");return e.name=ve(),"as"==v()?(f(),e.asname=ve()):e.asname=void 0,C(e)}function F(){let e=0;for(;;)if("Dot"==b())e+=1,f();else{if("Ellipsis"!=b())return e;e+=3,f()}}function L(e,t){let n=T("Tuple",e);return n.elts=t,C(n)}function R(t){let n=d(),r=me(e.U.lf("expression"),t),i=r[0];return 1!=r.length?L(n,r):i}function M(){return R(ce)}function U(){return R(V)}function B(){return R(oe)}function $(e){if("Tuple"==e.kind){e.elts.forEach($)}else e.ctx="Store"}function j(){let n=e.U.lookup(k,v());return n?n():function(){let n=d(),r=M(),i=b();if("Assign"==i){let e=T("Assign");for(e.targets=[r];;){if(f(),r=M(),i=b(),"Assign"!=i){e.value=r;break}e.targets.push(r)}return e.targets.forEach($),C(e)}if("Colon"==i){let e=T("AnnAssign");return e.target=r,f(),e.annotation=V(),"Assign"==b()&&(f(),e.value=V()),e.simple=n.type==t.TokenType.Id&&"Name"==r.kind?1:0,$(e.target),C(e)}if(e.U.endsWith(i,"Assign")){let e=T("AugAssign");return e.target=r,e.op=i.replace("Assign",""),f(),e.value=U(),$(e.target),C(e)}if("Semicolon"==i||d().type==t.TokenType.NewLine){let e=T("ExprStmt");return e.value=r,C(e)}return _(9555,e.U.lf("unexpected token")),f(),null}()}function K(){let e=[j()];for(;"Semicolon"==b()&&(f(),d().type!=t.TokenType.NewLine);)e.push(j());return g(),e.filter((e=>!!e))}function z(){const r=u.length,i=d().type==t.TokenType.Indent;i&&(f(),_(9573,e.U.lf("unexpected indent")));let a=[];for(;"MatMult"==b();)f(),a.push(ke()),g();let o=v(),c=e.U.lookup(x,v()),p=[],m=s;if(s=[],"class"==o||"def"==o){let e=c();e.decorator_list=a,p=[e]}else a.length?_(9556,e.U.lf("decorators not allowed here")):p=c?[c()]:K();m.length&&p.length&&(p[0]._comments=m);if(u.length>r){for(n=-1;l.type!=t.TokenType.Dedent&&l.type!=t.TokenType.NewLine&&(f(),d().type!=t.TokenType.EOF););i&&d().type===t.TokenType.Dedent&&f(),n=0}return p}function J(n){let r=T("Arguments");for(r.args=[],r.defaults=[],r.kwonlyargs=[],r.kw_defaults=[],r.vararg=void 0;;){let n=b();if("Colon"==n||"RParen"==n)break;if("Mult"==n)r.vararg&&_(9557,e.U.lf("multiple *arg")),f(),d().type==t.TokenType.Id?r.vararg=i():r.vararg=void 0;else if("Pow"==n)r.kwarg&&_(9558,e.U.lf("multiple **arg")),f(),r.kwarg=i();else{r.kwarg&&_(9559,e.U.lf("arguments after **"));let t,n=i();"Assign"==b()&&(f(),t=V()),void 0!==r.vararg&&t?(r.kwonlyargs.push(n),r.kw_defaults.push(t)):(r.args.push(n),t?r.defaults.push(t):r.defaults.length&&_(9560,e.U.lf("non-default argument follows default argument")))}if("Comma"!=b())break;f()}return r.kwarg||(r.kwarg=void 0),r.vararg||(r.vararg=void 0),C(r);function i(){let e=T("Arg");return e.arg=ve(),e.annotation=void 0,n&&"Colon"==b()&&(f(),e.annotation=V()),e}}function q(e){let t=T("Lambda");return f(),t.args=J(!1),y("Colon"),t.body=e?le():V(),C(t)}function V(){if("lambda"==v())return q();let e=d(),t=W();if("if"==v()){let n=T("IfExp",e);return n.body=t,h("if"),n.test=W(),h("else"),n.orelse=V(),C(n)}return t}function H(e,t){let n=d(),r=t();if(v()==e){let i=T("BoolOp",n);for(i.op="or"==e?"Or":"And",i.values=[r];v()==e;)h(e),i.values.push(t());return C(i)}return r}function G(){return H("and",Q)}function W(){return H("or",G)}function Q(){if("not"==v()){let e=T("UnaryOp");return f(),e.op="Not",e.operand=Q(),C(e)}return function(){let e=d(),t=oe();if(!X())return t;let n=T("Compare",e);n.left=t,n.comparators=[],n.ops=[];for(;;){let e=X();if(!e)break;f(),"NotIn"==e?h("in"):"Is"==e&&"not"==v()&&(f(),e="IsNot"),n.ops.push(e),n.comparators.push(oe())}return C(n)}()}const Y={Lt:"Lt",Gt:"Gt",Eq:"Eq",GtE:"GtE",LtE:"LtE",NotEq:"NotEq",in:"In",not:"NotIn",is:"Is"};function X(){return Y[b()]||Y[v()]||null}const Z={Invert:"Invert",Sub:"USub",Add:"UAdd"};function ee(e,t){let n=d(),r=e();for(;;){let i=b();if(!(i&&t.indexOf(","+i+",")>=0))return r;{let t=T("BinOp",n);t.left=r,t.op=i,f(),t.right=e(),r=t}}}function te(){return ee(Se,",Mult,MatMult,Div,Mod,FloorDiv,")}function ne(){return ee(te,",Add,Sub,")}function re(){return ee(ne,",LShift,RShift,")}function ie(){return ee(re,",BitAnd,")}function ae(){return ee(ie,",BitXor,")}function oe(){return ee(ae,",BitOr,")}function se(){let t,n=d();if("Colon"!=b()&&(t=V()),"Colon"==b()){let e=T("Slice",n);e.lower=t,f();let r=b();return e.upper="Colon"!=r&&"Comma"!=r&&"RSquare"!=r?V():void 0,e.step=void 0,"Colon"==b()&&(f(),r=b(),"Comma"!=r&&"RSquare"!=r&&(e.step=V())),C(e)}{t||_(9570,e.U.lf("unable to parse lower subscript"));let n=T("Index");return n.value=t,C(n)}}function ce(){if("Mult"==b()){let e=T("Starred");return e.value=oe(),C(e)}return V()}function le(){return"lambda"==v()?q(!0):W()}function ue(){let e=[];for(;;){let t=T("Comprehension");for(t.is_async=0,e.push(t),h("for"),t.target=B(),$(t.target),h("in"),t.iter=W(),t.ifs=[];"if"==v();)f(),t.ifs.push(le());if("for"!=v())return e}}function de(){let t=d();if("Mult"==b()){let e=T("Starred");return f(),e.value=V(),C(e)}if("Pow"==b()){let e=T("Keyword");return f(),e.arg=void 0,e.value=V(),C(e)}let n=V();if("Assign"==b()){"Name"!=n.kind&&_(9561,e.U.lf("invalid keyword argument; did you mean ==?")),f();let r=T("Keyword",t);return r.arg=n.id||"???",r.value=V(),C(r)}if("for"==v()){let e=T("GeneratorExp",t);return e.elt=n,e.generators=ue(),C(e)}return n}function pe(){let e=T("NameConstant");return e.value=null,f(),C(e)}function fe(){let n=d();if(n.type==t.TokenType.Id){let e=T("Name");return f(),e.id=n.value,e.ctx="Load",C(e)}if(n.type==t.TokenType.Number){let e=T("Num");return f(),e.ns=n.value,e.n=n.auxValue,C(e)}if(n.type==t.TokenType.String){f();let r=n.value;for(;d().type==t.TokenType.String;)r+=d().value,f();if("b"==n.stringPrefix){let t=T("Bytes",n);return t.s=e.U.toArray(e.U.stringToUint8Array(r)),C(t)}{let e=T("Str",n);return e.s=r,C(e)}}if(n.type==t.TokenType.Keyword){if("None"==n.value||"True"==n.value||"False"==n.value){let e=T("NameConstant");return f(),e.value="True"==n.value||"False"!=n.value&&null,C(e)}return _(9564,e.U.lf("expecting atom")),pe()}if(n.type==t.TokenType.Op){let t=n.value;return"LParen"==t?ye("RParen","Tuple","GeneratorExp"):"LSquare"==t?ye("RSquare","List","ListComp"):"LBracket"==t?function(){let t=d();if(f(),"Pow"==b())return f(),r(void 0,oe());if("RBracket"==b()){let e=T("Dict",t);return f(),e.keys=[],e.values=[],C(e)}{let n=ce();return"Starred"!=n.kind&&"Colon"==b()?(f(),r(n,V())):function(n){if("for"==v()){"Starred"==n.kind&&_(9562,e.U.lf("iterable unpacking cannot be used in comprehension"));let r=T("SetComp",t);return r.elt=n,r.generators=ue(),C(r)}let r=T("Set",t);if(r.elts=[n],"Comma"==b()){let t=he("RBracket",e.U.lf("set element"),ce);r.elts=[n].concat(t)}else y("RBracket");return C(r)}(n)}function n(){if("Pow"==b())return f(),[null,oe()];{let e=V();return y("Colon"),[e,V()]}}function r(r,i){if("for"==v()){r||_(9563,e.U.lf("dict unpacking cannot be used in dict comprehension"));let n=T("DictComp",t);return n.key=r,n.value=i,n.generators=ue(),C(n)}let a=T("Dict",t);if(a.keys=[r],a.values=[i],"Comma"==b()){let t=he("RBracket",e.U.lf("dict element"),n);for(let e of t)e.length>=2&&e[0]&&e[1]&&(a.keys.push(e[0]),a.values.push(e[1]))}else y("RBracket");return C(a)}}():(_(9565,e.U.lf("unexpected operator")),pe())}return _(9566,e.U.lf("unexpected token")),pe()}function _e(){let n=b();return"RParen"==n||"RSquare"==n||"RBracket"==n||"Colon"==n||"Semicolon"==n||(!!e.U.endsWith(n,"Assign")||("in"==v()||d().type==t.TokenType.NewLine))}function me(t,n){let r=[];if(_e())return r;for(;;){r.push(n());let i="Comma"==b();if(i&&f(),_e())return r;if(!i)return _(9567,e.U.lf("expecting {0}",t)),r}}function ge(e,t){let n=[];for(;n.push(t()),"Comma"==b();)f();return n}function he(t,n,r){f();let i=[];if(b()!=t)for(;;){i.push(r());let a="Comma"==b();if(a&&f(),b()==t)break;if(!a){_(9568,e.U.lf("expecting {0}",n));break}}return y(t),i}function ye(t,n,r){let i=d();if(f(),b()==t){f();let e=T(n,i);return e.elts=[],C(e)}let a=ce();if("for"==v()){let e=T(r,i);return e.elt=a,e.generators=ue(),y(t),C(e)}if("Comma"==b()){let r=T(n,i);return f(),r.elts=me(e.U.lf("expression"),ce),r.elts.unshift(a),y(t),C(r)}if(y(t),"List"==n){let e=T(n,i);return e.elts=[a],C(e)}return a}function ve(){let n=d();return n.type!=t.TokenType.Id&&_(9569,e.U.lf("expecting identifier")),f(),n.value}function be(){let t=he("RParen",e.U.lf("argument"),de),n=[],r=[];for(let i of t)"Keyword"==i.kind?r.push(i):(r.length&&_(9570,e.U.lf("positional argument follows keyword argument")),n.push(i));return{args:n,keywords:r}}function xe(t,n){let r=b();if("LParen"==r){let e=T("Call",t);e.func=n;let r=be();return e.args=r.args,e.keywords=r.keywords,C(e)}if("LSquare"==r){let r=d(),i=T("Subscript",t);i.value=n;let a=he("RSquare",e.U.lf("subscript"),se);if(0==a.length)_(9571,e.U.lf("need non-empty index list"));else if(1==a.length)i.slice=a[0];else if(a.every((e=>"Index"==e.kind))){let e=a[0];e.value=L(r,a.map((e=>e.value))),i.slice=e}else{let e=T("ExtSlice",r);e.dims=a,i.slice=C(e)}return C(i)}if("Dot"==r){let e=T("Attribute",t);return e.value=n,f(),e.attr=ve(),C(e)}return n}function ke(){let e=d(),t=fe();for(;;){let n=xe(e,t);if(n===t)return t;t=n}}function Se(){if(Z[b()]){let e=T("UnaryOp");return e.op=Z[b()],f(),e.operand=Se(),C(e)}return function(){d();let e=ke();if("Pow"==b()){let t=T("BinOp");return f(),t.left=e,t.op="Pow",t.right=Se(),C(t)}return e}()}const Te={kind:1,id:2,n:3,s:4,func:5,key:6,elt:7,elts:8,keys:9,left:10,ops:11,comparators:12,names:13,items:14,test:15,targets:16,dims:17,context_expr:18,name:19,bases:20,type:21,inClass:22,target:23,annotation:24,simple:25,op:26,operand:27,right:28,values:29,iter:30,ifs:31,is_async:32,value:33,slice:34,attr:35,generators:36,args:37,keywords:38,body:39,handlers:40,orelse:41,finalbody:42,decorator_list:43,kwonlyargs:44,kw_defaults:45,defaults:46,arg:47},Ce={lineno:1,col_offset:1,startPos:1,endPos:1,kind:1},Ee={body:1,orelse:1,finalbody:1},De={_comments:1,ctx:1,ns:1};t.dump=function(t,n=!1){const r=(t,i)=>{if(Array.isArray(i)){let e="";for(let n=0;n<i.length;++n)n>0&&(e+=", "),e+=r(t,i[n]);return"["+e+"]"}if(!i||!i.kind)return JSON.stringify(i);let a="",o=Object.keys(i);o.sort(((t,n)=>(Te[t]||100)-(Te[n]||100)||e.U.strcmp(t,n)));for(let s of o)if(!(e.U.lookup(Ce,s)||n&&e.U.lookup(De,s)))if(a&&(a+=", "),a+=s+"=",Array.isArray(i[s])&&i[s].length&&e.U.lookup(Ee,s)){a+="[\n";let e=t+" ";for(let t of i[s])a+=e+r(e,t)+"\n";a+=t+"]"}else if("_comments"==s){a+="[\n";let e=t+" ";for(let t of i[s])a+=e+JSON.stringify(t.value)+"\n";a+=t+"]"}else a+=r(t,i[s]);return i.kind+"("+a+")"};let i="";for(let e of t)i+=r("",e)+"\n";return i},t.parse=function(f,m,g){i=f,a=m,r=g,n=0,o=0,s=[],c=[0],u=[];let h=[];try{if(l=r[0],p(),d().type!=t.TokenType.EOF)for(h=z();d().type!=t.TokenType.EOF;)e.U.pushRange(h,z())}catch(t){_(9572,e.U.lf("exception: {0}",t.message))}return{stmts:h,diagnostics:u}}}(e.py||(e.py={}))}(pxt||(pxt={})),function(e){!function(t){function n(e,t,n){const r={fileName:e.getSourceFile().fileName,start:e.getStart(),length:e.getEnd()-e.getStart(),line:void 0,column:void 0,code:t,category:pxtc.DiagnosticCategory.Error,messageText:n},i=new Error(n);throw i.pyDiagnostic=r,i}t.decompileToPython=function(r,i){let a={blocksInfo:void 0,outfiles:{},diagnostics:[],success:!0,times:{}};try{let o=function(r,i){const a=r.getTypeChecker(),o=(new ts.pxtc.LSHost(r),r.getSourceFile(i)),s=pxtc.decompiler.buildCommentMap(o),c=e.U.toSet(_(),(e=>e)),[l,u]=ts.pxtc.decompiler.buildRenameMap(r,o,{takenNames:c,declarations:"all"}),d=pxtc.getApiInfo(r),p=e.U.mapMap(d.byQName,((e,t)=>t.fileName==i?void 0:t)),f=t.computeScopeVariableLookup(o);return S(o);function _(){return["ArithmeticError","AssertionError","AttributeError","BaseException","BlockingIOError","BrokenPipeError","BufferError","BytesWarning","ChildProcessError","ConnectionAbortedError","ConnectionError","ConnectionRefusedError","ConnectionResetError","DeprecationWarning","EOFError","Ellipsis","EnvironmentError","Exception","False","FileExistsError","FileNotFoundError","FloatingPointError","FutureWarning","GeneratorExit","IOError","ImportError","ImportWarning","IndentationError","IndexError","InterruptedError","IsADirectoryError","KeyError","KeyboardInterrupt","LookupError","MemoryError","NameError","None","NotADirectoryError","NotImplemented","NotImplementedError","OSError","OverflowError","PendingDeprecationWarning","PermissionError","ProcessLookupError","RecursionError","ReferenceError","ResourceWarning","RuntimeError","RuntimeWarning","StopAsyncIteration","StopIteration","SyntaxError","SyntaxWarning","SystemError","SystemExit","TabError","TimeoutError","True","TypeError","UnboundLocalError","UnicodeDecodeError","UnicodeEncodeError","UnicodeError","UnicodeTranslateError","UnicodeWarning","UserWarning","ValueError","Warning","ZeroDivisionError","_","__build_class__","__debug__","__doc__","__import__","__loader__","__name__","__package__","__spec__","abs","all","any","ascii","bin","bool","bytearray","bytes","callable","chr","classmethod","compile","complex","copyright","credits","delattr","dict","dir","divmod","enumerate","eval","exec","exit","filter","float","format","frozenset","getattr","globals","hasattr","hash","help","hex","id","input","int","isinstance","issubclass","iter","len","license","list","locals","map","max","memoryview","min","next","object","oct","open","ord","pow","print","property","quit","range","repr","reversed","round","set","setattr","slice","sorted","staticmethod","str","sum","super","tuple","type","vars","zip",...Object.keys(e.py.keywords)]}function m(e){if(!e.getSourceFile())return null;let t=e.getText();return p[t]||null}function g(e){if(!e.getSourceFile())return null;let t=e.getText();const n=a.getSymbolAtLocation(e);n&&(t=a.getFullyQualifiedName(n));let r=p[t];if(r&&r.attributes.alias)return r.attributes.alias;if(r&&r.pyQName){if(r.isInstance){if(ts.isPropertyAccessExpression(e))return null;const t=new RegExp(`(?:^|.)${r.namespace}.(.+)`).exec(r.pyQName);if(t)return t[1]}return r.pyQName}return t in pxtc.ts2PyFunNameMap?pxtc.ts2PyFunNameMap[t].n:null}function h(t){let r=g(t);if(r)return r;if(!ts.isIdentifier(t))return e.tickEvent("depython.todo.advancedname"),n(t,3001,"Unsupported advanced name format: "+t.getText());let i=t.text;if(t.getSourceFile()){const e=l.getRenameForPosition(t.getStart());e&&(i=e.name)}return i}function y(e){return"string"!=typeof e&&(e=h(e)),u[e]?pxtc.decompiler.getNewName(e,u):(u[e]=!0,e)}function v(e,t){return 0!=(e.flags&t)}function b(e,t){return v(a.getTypeAtLocation(e),t)}function x(e){return b(e,ts.TypeFlags.StringLike)}function k(e){return b(e,ts.TypeFlags.NumberLike)}function S(e){let t=e.getChildren().map(T).reduce(((e,t)=>e.concat(t)),[]).reduce(((e,t)=>t||e[e.length-1]?[...e,t]:e),[]);return s.filter((e=>!e.owner)).forEach((e=>t.push(...C(e)))),t.join("\n")}function T(e){switch(e.kind){case ts.SyntaxKind.SyntaxList:return e._children.map(T).reduce(((e,t)=>e.concat(t)),[]);case ts.SyntaxKind.EndOfFileToken:case ts.SyntaxKind.OpenBraceToken:case ts.SyntaxKind.CloseBraceToken:return[];default:return E(e)}}function C(e){let t=[];if(e.kind===pxtc.decompiler.CommentKind.SingleLine)t.push("# "+e.text);else{t.push('"""');for(const n of e.lines)t.push(n);t.push('"""')}return t}function E(e){const t=D(e);return pxtc.decompiler.getCommentsForStatement(e,s).map(C).reduce(((e,t)=>e.concat(t)),[]).concat(t)}function D(t){return ts.isVariableStatement(t)?B(t):ts.isClassDeclaration(t)?$(t):ts.isEnumDeclaration(t)?j(t):ts.isExpressionStatement(t)?J(t):ts.isFunctionDeclaration(t)?V(t):ts.isIfStatement(t)?M(t):ts.isForStatement(t)?R(t):ts.isForOfStatement(t)?L(t):ts.isWhileStatement(t)?I(t):ts.isReturnStatement(t)?w(t):ts.isBlock(t)?q(t):ts.isTypeAliasDeclaration(t)?N(t):ts.isEmptyStatement(t)?[]:ts.isModuleDeclaration(t)?A(t):ts.isBreakStatement(t)?["break"]:ts.isContinueStatement(t)?["continue"]:(e.tickEvent("depython.todo.statement",{statement:t.kind}),n(t,3002,`Not supported in MakeCode Python: ${ts.SyntaxKind[t.kind]} (${t.kind})`))}function A(e){let n=h(e.name),r=e.body&&e.body.getChildren().map(T).reduce(((e,t)=>e.concat(t)),[]).map((e=>t.indent1(e)));return["@namespace",`class ${n}:`].concat(r||[])}function N(e){let t=pxtc.emitPyTypeFromTypeNode(e.type);return[`${h(e.name)} = ${t}`]}function w(e){if(!e.expression)return["return"];let[t,n]=ve(e.expression),r=Y("return ",t);return n.concat(r)}function I(e){let[t,n]=ve(e.expression),r=F(e.statement),i=Y("while ",t,":");return n.concat(i).concat(r)}function P(e){let t=Math.floor(Number(e));return t!==1/0&&String(t)===e}function O(e){if(!e.initializer)return null;if(e.initializer.kind!==ts.SyntaxKind.VariableDeclarationList)return null;let t=e.initializer;if(1!==t.declarations.length)return null;let n=t.declarations[0],r=h(n.name);if(!n.initializer||!he(n.initializer)||!k(n.initializer))return null;let[i,a]=ve(n.initializer);if(a.length)return null;let o=Q(i);if(!e.condition)return null;if(!ts.isBinaryExpression(e.condition))return null;if(!ts.isIdentifier(e.condition.left))return null;if(h(e.condition.left)!=r)return null;if(!k(e.condition.right))return null;let[s,c]=ve(e.condition.right);if(c.length)return null;let l=Q(s),u=l;if(e.condition.operatorToken.kind===ts.SyntaxKind.LessThanEqualsToken&&P(l))u=""+(Number(l)+1);else if(e.condition.operatorToken.kind!==ts.SyntaxKind.LessThanToken)return null;return e.incrementor&&(ts.isPostfixUnaryExpression(e.incrementor)||ts.isPrefixUnaryExpression(e.incrementor))?e.incrementor.operator!==ts.SyntaxKind.PlusPlusToken?null:o<u?{name:r,fromIncl:o,toExcl:u}:null:null}function F(e){let n=D(e).map(t.indent1);return n.length<1&&(n=[t.indent1("pass")]),n}function L(t){if(!ts.isVariableDeclarationList(t.initializer))return e.tickEvent("depython.todo.forof.complexexp"),n(t,3003,"Unsupported expression in for..of initializer: "+t.initializer.getText());let r=t.initializer.declarations.map((e=>h(e.name)));if(1!==r.length)return e.tickEvent("depython.todo.forof.multidecl"),n(t,3004,"Unsupported multiple declerations in for..of: "+t.initializer.getText());let i=r[0],[a,o]=ve(t.expression),s=o;s=s.concat(Y(`for ${i} in `,a,":"));let c=F(t.statement);return s=s.concat(c),s}function R(e){let n=O(e);if(n){let{name:t,fromIncl:r,toExcl:i}=n,a="0"===r?`for ${t} in range(${i}):`:`for ${t} in range(${r}, ${i}):`,o=F(e.statement);return[a].concat(o)}let r,i=[];if(e.initializer)if(ts.isVariableDeclarationList(e.initializer)){let t=e.initializer.declarations.map(G).reduce(((e,t)=>e.concat(t)),[]);i=i.concat(t)}else{let[t,n]=ve(e.initializer);i=i.concat(n).concat(t)}if(e.condition){let[t,n]=ve(e.condition);i=i.concat(n),r=Q(t)}else r="True";let a=`while ${r}:`;i.push(a);let o=D(e.statement).map(t.indent1);if(0!==o.length||e.incrementor||(o=[t.indent1("pass")]),i=i.concat(o),e.incrementor){let n=z(e.incrementor);if(n)i=i.concat(n.map(t.indent1));else{let[n,r]=ve(e.incrementor);i=i.concat(r).concat(n.map(t.indent1))}}return i}function M(e){let{supportStmts:t,ifStmt:n,rest:r}=U(e);return t.concat([n]).concat(r)}function U(e){let t=[],[n,r]=ve(e.expression);t=t.concat(r);let i=`if ${Q(n)}:`,a=[],o=F(e.thenStatement);if(a=a.concat(o),e.elseStatement)if(ts.isIfStatement(e.elseStatement)){let{supportStmts:n,ifStmt:r,rest:i}=U(e.elseStatement),o=`el${r}`;t=t.concat(n),a.push(o),a=a.concat(i)}else{a.push("else:");let t=F(e.elseStatement);a=a.concat(t)}return{supportStmts:t,ifStmt:i,rest:a}}function B(e){return e.declarationList.declarations.map(G).reduce(((e,t)=>e.concat(t)),[])}function $(t){return e.tickEvent("depython.todo.classes"),n(t,3016,"Unsupported: classes are not supported in Python right now.")}function j(r){let i=[];i.push(`class ${h(r.name)}(Enum):`);let a=r.members.every((e=>!!e.initializer)),o=!r.members.every((e=>!!e.initializer));if(!a&&!o)return e.tickEvent("depython.todo.enummix"),n(r,3005,"Unsupported enum decleration: has mixture of explicit and implicit initialization");if(a)return e.tickEvent("depython.todo.enuminit"),n(r,3006,"Unsupported: explicit enum initialization");let s=0;for(let e of r.members)i.push(t.indent1(`${h(e.name)} = ${s++}`));return i}function K(e){return!(!ts.isPrefixUnaryExpression(e)&&!ts.isPostfixUnaryExpression(e))&&(e.operator===ts.SyntaxKind.MinusMinusToken||e.operator===ts.SyntaxKind.PlusPlusToken)}function z(e){if(!K(e))return null;let[t,n]=ve(e.operand),r=e.operator===ts.SyntaxKind.MinusMinusToken?" -= 1":" += 1",i=n;return i.push(`${Q(t)}${r}`),i}function J(e){let t=z(e.expression);if(t)return t;const[n,r]=ve(e.expression);return r.length?["",...r,...n,""]:[...r,...n]}function q(e){return e.getChildren().map(T).reduce(((e,t)=>e.concat(t)),[])}function V(r,i,a,o){let s=[];r.kind!==ts.SyntaxKind.MethodDeclaration&&r.kind!==ts.SyntaxKind.Constructor||s.push("self");let c=(a?oe(r.parameters,a):r.parameters).map((e=>H(e,!o)));s=s.concat(c);let l,u=s.join(", "),d=[];if(i)l=i;else{if(!r.name)return e.tickEvent("depython.todo.anonymousfunc"),n(r,3012,"Unsupported: anonymous function decleration");l=h(r.name)}if(d.push(`def ${l}(${u}):`),!r.body)return e.tickEvent("depython.todo.funcwithoutbody"),n(r,3013,"Unsupported: function decleration without body");let p=[];if(ts.isBlock(r.body))p=q(r.body);else{let[e,t]=ve(r.body);p=p.concat(t),p.concat(e)}if(p.length){let e=f.getExplicitGlobals(r).map((e=>h(e)));e&&e.length&&p.unshift(`global ${e.join(", ")}`);let n=f.getExplicitNonlocals(r).map((e=>h(e)));n&&n.length&&p.unshift(`nonlocal ${n.join(", ")}`),d=d.concat(p.map(t.indent1))}else d.push(t.indent1("pass"));return d}function H(t,r=!0){let i=t.altName||h(t.name),a="";if(t.type&&r){let e=pxtc.emitPyTypeFromTypeNode(t.type);e&&-1===e.indexOf("(TODO")&&(a=`: ${e}`)}let o="";if(t.initializer){let[r,i]=ve(t.initializer);if(i.length)return e.tickEvent("depython.todo.complexinit"),n(t,3007,`Unsupported: complex expression in parameter default value not supported. Expression: ${t.initializer.getText()}`);o=` = ${Q(r)}`}return`${i}${a}${o}`}function G(e){let t=[],n=h(e.name);if(e.initializer){let r,[i,a]=ve(e.initializer);if(t=t.concat(a),e.type){r=`${n}: ${pxtc.emitPyTypeFromTypeNode(e.type)} = ${Q(i)}`}else r=`${n} = ${Q(i)}`;return t.push(r),t}return t}function W(e,t){return[[e],t||[]]}function Q(e,t="\n"){return e.join(t)}function Y(e="",t,n=""){return t[0]=e+t[0],t[t.length-1]=t[t.length-1]+n,t}function X(t,r){switch(t){case ts.SyntaxKind.BarBarToken:return"or";case ts.SyntaxKind.AmpersandAmpersandToken:return"and";case ts.SyntaxKind.ExclamationToken:return"not";case ts.SyntaxKind.LessThanToken:return"<";case ts.SyntaxKind.LessThanEqualsToken:return"<=";case ts.SyntaxKind.GreaterThanToken:return">";case ts.SyntaxKind.GreaterThanEqualsToken:return">=";case ts.SyntaxKind.EqualsEqualsEqualsToken:case ts.SyntaxKind.EqualsEqualsToken:return"==";case ts.SyntaxKind.ExclamationEqualsEqualsToken:case ts.SyntaxKind.ExclamationEqualsToken:return"!=";case ts.SyntaxKind.EqualsToken:return"=";case ts.SyntaxKind.PlusToken:return"+";case ts.SyntaxKind.MinusToken:return"-";case ts.SyntaxKind.AsteriskToken:return"*";case ts.SyntaxKind.PlusEqualsToken:return"+=";case ts.SyntaxKind.MinusEqualsToken:return"-=";case ts.SyntaxKind.PercentToken:return"%";case ts.SyntaxKind.SlashToken:return"/";case ts.SyntaxKind.PlusPlusToken:case ts.SyntaxKind.MinusMinusToken:return e.tickEvent("depython.todo.unsupportedop",{op:t}),n(r,3008,"Unsupported ++ and -- in an expression (not a statement or for loop)");case ts.SyntaxKind.AmpersandToken:return"&";case ts.SyntaxKind.CaretToken:return"^";case ts.SyntaxKind.LessThanLessThanToken:return"<<";case ts.SyntaxKind.GreaterThanGreaterThanToken:return">>";case ts.SyntaxKind.GreaterThanGreaterThanGreaterThanToken:return e.tickEvent("depython.todo.unsupportedop",{op:t}),n(r,3009,"Unsupported operator: >>>");case ts.SyntaxKind.AsteriskAsteriskToken:return"**";case ts.SyntaxKind.AsteriskAsteriskEqualsToken:return"**=";case ts.SyntaxKind.PercentEqualsToken:return"%=";case ts.SyntaxKind.AsteriskEqualsToken:return"*=";case ts.SyntaxKind.SlashEqualsToken:return"/=";default:return e.tickEvent("depython.todo.unsupportedop",{op:t}),n(r,3008,`Unsupported Python operator (code: ${t})`)}}function Z(e){let t=x(e.left),n=x(e.right),r=e.operatorToken.kind===ts.SyntaxKind.PlusToken&&(t||n),[i,a]=ve(e.left);r&&!t&&(i=Y("str(",i,")"));let o=X(e.operatorToken.kind,e),[s,c]=ve(e.right);r&&!n&&(s=Y("str(",s,")"));let l=a.concat(c);return[Y(Q(i)+" "+o+" ",s),l]}function ee(e){let t=g(e);if(t)return W(t);let[n,r]=ve(e.expression),i=h(e.name);return W("length"===i?`len(${Q(n)})`:`${Q(n)}.${i}`,r)}function te(e){if(ts.isPropertyAccessExpression(e)){let t=h(e.name),n=t.substr(t.lastIndexOf(".")+1);return ts.isIdentifier(e.expression)?[n]:te(e.expression).concat([n])}return ts.isIdentifier(e)?[h(e)]:[]}function ne(t,n,r,i){let o="";n&&(o=te(n).map(e.U.snakify).join("_"));let s=[];if(r&&r.length>1&&i&&i.length>1)for(let t=0;t<r.length&&t<i.length;t++){let n=i[t];if(v(a.getTypeAtLocation(n),ts.TypeFlags.EnumLike)){let t=te(n).map(e.U.snakify);s=s.concat(t)}}let c=s.join("_"),l="";o||c||!t||(l=h(t.name));let u=([o,c,l].filter((e=>e)).map(e.U.snakify).map((e=>e.toLowerCase())).join("_")||"my_callback").split("_");u.length>4&&(u=p(u));let d=e.U.toDictionary(["any","on","event"],(e=>e));for(;u.length>2;){let e=f(u,d);if(e.length==u.length)break;u=e}return u=["on",...u],u.join("_");function p(e){let t={},n=[];for(let r of e)r in t||(t[r]=!0,n.push(r));return n}function f(e,t){let n=[],r=!1;for(let i of e)!(i in t)||r?n.push(i):r=!0;return n}}function re(e){let n=e.join(", ");return n.length>60&&e.length>1?e.map(((n,r)=>{let i=","==n.charAt(n.length-1)?"":",";if(0==r){let e=n.split("\n");if(e.length>1){n=e.shift()+"\n"+t.indent1(e.join("\n"))}return n+i}return r==e.length-1?t.indent1(n):t.indent1(n+i)})):[n]}function ie(e,t,n,r,i){if((ts.isFunctionExpression(e)||ts.isArrowFunction(e))&&t&&t.type&&ts.isFunctionTypeNode(t.type)){let a;return se(e,ne(t,n,r,i),a,!0)}return ve(e)}function ae(t){let r=a.getTypeAtLocation(t.expression),i=a.typeToTypeNode(r),o=ts.createNodeArray([]);if(ts.isFunctionTypeNode(i)&&(o=i.parameters,t.arguments&&o.length<t.arguments.length))return e.tickEvent("depython.todo.argparammismatch",{kind:t.kind}),n(t,3010,"TODO: Unsupported call site where caller the arguments outnumber the callee parameters: "+t.getText());const s=m(t.expression);if(t.arguments&&s&&"TD_ID"==s.attributes.shim)return ve(t.arguments[0]);if(ts.isPropertyAccessExpression(t.expression)&&"toString"===t.expression.name.getText()){const[e,n]=ve(t.expression.expression);return[Y("str(",e,")"),n]}let[c,l]=ve(t.expression),u=Q(c),d=(t.arguments||ts.createNodeArray()).map(((e,n,r)=>ie(e,o[n],t.expression,o,r))),p=d.map((([e,t])=>t)).reduce(((e,t)=>e.concat(t)),l);if(0===u.indexOf("_py.py_")){if(d.length<=0)return e.tickEvent("depython.todo._pynoargs"),n(t,3014,"Unsupported: call expression has no arguments for _py.py_ fn");u=u.substr(7).split("_").filter(((e,t)=>0!==t)).join("_");return[Y(`${d.shift()[0]}.${u}(`,re(d.map((([e,t])=>e)).reduce(((e,t)=>e.concat(t)),[])),")"),p]}return[Y(`${u}(`,re(d.map((([e,t])=>e)).reduce(((e,t)=>e.concat(t)),[])),")"),p]}function oe(e,t){let n=[],r={};for(let i=0;i<Math.max(e.length,t.length);i++){let a;if(e[i])a=e[i],r[h(a.name)]=!0;else{a=t[i];let e=h(a.name);r[e]&&(e=pxtc.decompiler.getNewName(e,r),a=Object.assign({altName:e},t[i]))}n.push(a)}return ts.createNodeArray(n,!1)}function se(e,t,n,r){let i=e.name?h(e.name):y(t||"my_function");return W(i,V(e,i,n,r))}function ce(e){switch(e){case ts.SyntaxKind.ExclamationToken:return" ";case ts.SyntaxKind.PlusToken:case ts.SyntaxKind.MinusToken:return"";default:return" "}}function le(e){let t=X(e.operator,e),[n,r]=ve(e.operand);return W(`${t}${ce(e.operator)}${Q(n)}`,r)}function ue(e){let t=X(e.operator,e),[n,r]=ve(e.operand),i=ce(e.operator);return W(`${Q(n)}${i}${t}`,r)}function de(e){let t=e.elements.map(ve),n=t.map((([e,t])=>t)).reduce(((e,t)=>e.concat(t)),[]);return[Y("[",re(t.map((([e,t])=>e)).reduce(((e,t)=>e.concat(t)),[])),"]"),n]}function pe(t){if(!t.argumentExpression)return e.tickEvent("depython.todo.accesswithoutexp"),n(t,3015,"Unsupported: element access expression without an argument expression");let[r,i]=ve(t.expression),[a,o]=ve(t.argumentExpression),s=i.concat(o);return W(`${Q(r)}[${Q(a)}]`,s)}function fe(e){let[t,n]=ve(e.expression);return W(`(${Q(t)})`,n)}function _e(e){if(ts.isNoSubstitutionTemplateLiteral(e))return W(`"""\n${t.indent1(e.text.trim())}\n"""`);let[n,r]=ve(e.tag),[i,a]=ve(e.template),o=r.concat(a);return W(`${Q(n)}(${Q(i)})`,o)}function me(e){if("undefined"==e.text)return W("None");return W(h(e))}function ge(e,t){let n=e=>ge(e,t);return ts.isBinaryExpression(e)?n(e.left)&&n(e.right):ts.isPropertyAccessExpression(e)?n(e.expression):ts.isPrefixUnaryExpression(e)||ts.isPostfixUnaryExpression(e)?e.operator!==ts.SyntaxKind.PlusPlusToken&&e.operator!==ts.SyntaxKind.MinusMinusToken&&n(e.operand):ts.isParenthesizedExpression(e)?n(e.expression):ts.isArrayLiteralExpression(e)?e.elements.map(n).reduce(((e,t)=>e&&t),!0):ts.isElementAccessExpression(e)?n(e.expression)&&(!e.argumentExpression||n(e.argumentExpression)):t(e)}function he(e){return ge(e,(e=>{switch(e.kind){case ts.SyntaxKind.PropertyAccessExpression:case ts.SyntaxKind.BinaryExpression:case ts.SyntaxKind.ParenthesizedExpression:case ts.SyntaxKind.ArrayLiteralExpression:case ts.SyntaxKind.ElementAccessExpression:case ts.SyntaxKind.TrueKeyword:case ts.SyntaxKind.FalseKeyword:case ts.SyntaxKind.NullKeyword:case ts.SyntaxKind.UndefinedKeyword:case ts.SyntaxKind.NumericLiteral:case ts.SyntaxKind.StringLiteral:case ts.SyntaxKind.NoSubstitutionTemplateLiteral:return!0;case ts.SyntaxKind.CallExpression:case ts.SyntaxKind.NewExpression:case ts.SyntaxKind.FunctionExpression:case ts.SyntaxKind.ArrowFunction:case ts.SyntaxKind.Identifier:case ts.SyntaxKind.ThisKeyword:return!1;case ts.SyntaxKind.PrefixUnaryExpression:case ts.SyntaxKind.PostfixUnaryExpression:let t=e;return t.operator!==ts.SyntaxKind.PlusPlusToken&&t.operator!==ts.SyntaxKind.MinusMinusToken}return!1}))}function ye(e){let[t,n]=ve(e.condition),[r,i]=ve(e.whenTrue),[a,o]=ve(e.whenFalse),s=n.concat(i).concat(o);return W(`${r} if ${Q(t)} else ${Q(a)}`,s)}function ve(t){if(ts.isBinaryExpression(t))return Z(t);if(ts.isPropertyAccessExpression(t))return ee(t);if(ts.isCallExpression(t))return ae(t);if(ts.isNewExpression(t))return ae(t);if(ts.isFunctionExpression(t)||ts.isArrowFunction(t))return se(t);if(ts.isPrefixUnaryExpression(t))return le(t);if(ts.isPostfixUnaryExpression(t))return ue(t);if(ts.isParenthesizedExpression(t))return fe(t);if(ts.isArrayLiteralExpression(t))return de(t);if(ts.isElementAccessExpression(t))return pe(t);if(ts.isNoSubstitutionTemplateLiteral(t)||ts.isTaggedTemplateExpression(t))return _e(t);switch(t.kind){case ts.SyntaxKind.TrueKeyword:return W("True");case ts.SyntaxKind.FalseKeyword:return W("False");case ts.SyntaxKind.ThisKeyword:return W("self");case ts.SyntaxKind.NullKeyword:case ts.SyntaxKind.UndefinedKeyword:return W("None")}return ts.isIdentifier(t)?me(t):ts.isNumericLiteral(t)||ts.isStringLiteral(t)?W(t.getText()):ts.isConditionalExpression(t)?ye(t):(e.tickEvent("depython.todo.expression",{kind:t.kind}),n(t,3017,"Unsupported expression kind: "+t.kind))}}(r,i),s=i.replace(/(\.py)?\.\w*$/i,"")+".py";a.outfiles[s]=o}catch(t){t.pyDiagnostic?a.diagnostics=[t.pyDiagnostic]:e.reportException(t),a.success=!1}return a};function r(e){return n=>(n||"").split("\n").map((n=>`${t.INDENT.repeat(e)}${n}`)).join("\n")}t.INDENT=" ",t.indent=r,t.indent1=r(1)}(e.py||(e.py={}))}(pxt||(pxt={})),function(e){!function(e){!function(e){const t=/[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;e.isIdentifierStart=function(e){return ts.pxtc.isIdentifierStart(e,ts.pxtc.ScriptTarget.ES5)},e.isIdentifierChar=function(e){return ts.pxtc.isIdentifierPart(e,ts.pxtc.ScriptTarget.ES5)},e.isSpace=function(e){return!!(32===e||9===e||11===e||12===e||160===e||e>=5760&&t.test(String.fromCharCode(e)))},e.isNewline=function(e){return 10===e||13===e||(8232===e||8233===e)}}(e.rx||(e.rx={}))}(e.py||(e.py={}))}(pxt||(pxt={})),function(e){!function(e){function t(e){const t={refs:[],children:[],owner:void 0};return function e(r){var i;if(!r)return t;if(ts.isPropertyAccessOrQualifiedName(r))return t;if(ts.isIdentifier(r))return{refs:[{kind:"read",node:r,varName:r.text}],children:[],owner:void 0};if(ts.isVariableDeclaration(r)||ts.isParameter(r)){const t=e(r.initializer);return{refs:[...t.refs,{kind:"decl",node:r,varName:r.name.getText()}],children:t.children,owner:void 0}}if(ts.isPrefixUnaryExpression(r)||ts.isPostfixUnaryExpression(r)){const t=e(r.operand),i=r.operand.getText();return n(t,{refs:[{kind:"assign",node:r,varName:i}],children:[],owner:void 0})}if(function(e){const t=[ts.SyntaxKind.EqualsToken,ts.SyntaxKind.PlusEqualsToken,ts.SyntaxKind.MinusEqualsToken,ts.SyntaxKind.AsteriskEqualsToken,ts.SyntaxKind.AsteriskAsteriskEqualsToken,ts.SyntaxKind.SlashEqualsToken,ts.SyntaxKind.PercentEqualsToken,ts.SyntaxKind.LessThanLessThanEqualsToken,ts.SyntaxKind.GreaterThanGreaterThanEqualsToken,ts.SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken,ts.SyntaxKind.AmpersandEqualsToken,ts.SyntaxKind.BarEqualsToken,ts.SyntaxKind.CaretEqualsToken];return ts.isBinaryExpression(e)&&t.some((t=>e.operatorToken.kind===t))}(r)){const t=e(r.right);let i;r.operatorToken.kind!==ts.SyntaxKind.EqualsToken&&(i=e(r.left));const a=r.left.getText();return n(i,n(t,{refs:[{kind:"assign",node:r,varName:a}],children:[],owner:void 0}))}if(ts.isFunctionExpression(r)||ts.isArrowFunction(r)||ts.isFunctionDeclaration(r)||ts.isMethodDeclaration(r)){const a=null===(i=r.name)||void 0===i?void 0:i.getText();let o;a&&(o={kind:"decl",node:r,varName:a});const s=r.parameters.map((t=>e(t))).reduce(n,t),c=e(r.body),l=n(s,c);return l.owner=r,{refs:o?[o]:[],children:[l],owner:void 0}}return r.getChildren().map(e).reduce(n,t)}(e);function n(e,n){return e&&n?{refs:[...e.refs,...n.refs],children:[...e.children,...n.children],owner:e.owner||n.owner}:e||n||t}}function n(e,t,r=[]){const i=[],a=[],o=[],s=[],c={};for(const n of e.refs)"read"===n.kind||"assign"===n.kind?c[n.varName]?o.push(n):d(n)?a.push(n):t&&t[n.varName]?i.push(n):s.push(n):c[n.varName]=n;const l=t||c,u=t?[...r,c]:[];return{globalUsage:i,nonlocalUsage:a,localUsage:o,environmentUsage:s,children:e.children.map((e=>n(e,l,u))),owner:e.owner};function d(e){return r.map((t=>t[e.varName])).reduce(((e,t)=>t||e),void 0)}}function r(e){return`${e.kind}:${e.varName}`}e.computeScopeVariableLookup=function(e){const r=n(t(e)),i=new Map,a=new Map;return function e(t){const n=s((r=t,[...r.globalUsage,...r.environmentUsage].filter((e=>"assign"===e.kind)).map((e=>e))));var r;i.set(t.owner,n);const o=s(function(e){return e.nonlocalUsage.filter((e=>"assign"===e.kind)).map((e=>e))}(t));a.set(t.owner,o),t.children.forEach(e)}(r),{getExplicitGlobals:e=>i.get(e)||[],getExplicitNonlocals:e=>a.get(e)||[]};function o(e){let t=e.node.operand||e.node.left;return ts.isIdentifier(t)?t:void 0}function s(e){return e.map(o).filter((e=>!!e)).map((e=>e)).reduce(((e,t)=>e.find((e=>e.text===t.text))?e:[...e,t]),[])}},e.toStringVariableScopes=function(i){const a=t(i),o=n(a);return function t(n){return[n.refs.map(r).join(", "),...n.children.map(t).map((t=>t.map(e.indent1))).map((e=>["{",...e,"}"])).reduce(((e,t)=>[...e,...t]),[])]}(a).join("\n")+"\n\n\n"+function(t){return function t(n){const i=n.globalUsage.map(r).join(", "),a=n.nonlocalUsage.map(r).join(", "),o=n.localUsage.map(r).join(", "),s=n.environmentUsage.map(r).join(", ");return[i?"global "+i:"",a?"nonlocal "+a:"",o?"local "+o:"",s?"env "+s:"",...n.children.map(t).map((t=>t.map(e.indent1))).map((e=>["{",...e,"}"])).reduce(((e,t)=>[...e,...t]),[])].filter((e=>!!e))}(t).join("\n")}(o)}}(e.py||(e.py={}))}(pxt||(pxt={}));
|