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/pxtlib.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
pxt||(pxt={}),function(e){!function(t){const n={},i={};let s=!1;t.addDefaultProperties=function(e){Object.keys(e).forEach((t=>{"string"==typeof e[t]?n[t]=e[t]:i[t]=e[t]}))},t.enable=function(){if(!e.aiTrackException||!e.aiTrackEvent||s)return;s=!0,e.debug("setting up app insights");const t=e.tickEvent;e.tickEvent=function(s,r,a){if(t&&t(s,r,a),(null==a?void 0:a.interactiveConsent)&&e.setInteractiveConsent(!0),r){const t=Object.assign({},n)||{},a=Object.assign({},i)||{};Object.keys(r).forEach((e=>{"string"==typeof r[e]?t[e]=r[e]:"number"==typeof r[e]?a[e]=r[e]:t[e]=JSON.stringify(r[e]||"")})),e.aiTrackEvent(s,t,a)}else e.aiTrackEvent(s)};const r=e.reportException;e.reportException=function(t,n){r&&r(t,n);const i={target:e.appTarget.id,version:e.appTarget.versions.target};n&&e.Util.jsonMergeFrom(i,n),e.aiTrackException(t,"exception",i)};const a=e.reportError;e.reportError=function(t,n,i){a&&a(t,n,i);try{throw n}catch(s){const r={target:e.appTarget.id,version:e.appTarget.versions.target,category:t,message:n};i&&e.Util.jsonMergeFrom(r,i),e.aiTrackException(s,"error",r)}}}}(e.analytics||(e.analytics={}))}(pxt||(pxt={})),pxt||(pxt={}),function(e){!function(e){let t,n,i,s=0,r=!1;function a(){return t||(t=function(){if(window.AudioContext=window.AudioContext||window.webkitAudioContext,window.AudioContext)try{return new window.AudioContext}catch(e){}return}()),t}function o(){t&&(i.gain.setTargetAtTime(0,t.currentTime,.015),s=0)}e.mute=function(e){t&&(r=e,o(),e&&n&&(n.disconnect(),i.disconnect(),n=void 0,i=void 0))},e.stop=o,e.frequency=function(){return s},e.tone=function(e){if(r)return;if(e<0)return;s=e;let o=a();if(o)try{n||(n=o.createOscillator(),n.type="triangle",i=o.createGain(),i.gain.value=0,i.connect(o.destination),n.connect(i),n.start(0)),n.frequency.linearRampToValueAtTime(e,t.currentTime),i.gain.setTargetAtTime(.2,t.currentTime,.015)}catch(e){return void(n=void 0)}}}(e.AudioContextManager||(e.AudioContextManager={}))}(pxt||(pxt={})),function(e){!function(t){const n="auth",i="csrf-token",s="login-state",r="user-state";let a,o=!1;t.DEFAULT_USER_PREFERENCES=()=>({highContrast:!1,language:e.appTarget.appTheme.defaultLocale,reader:"",skillmap:{mapProgress:{},completedTags:{}},email:!1}),t.client=function(){return a};let l=0,c=0;t.AuthClient=class{constructor(){this.initialUserPreferences_=void 0,this.initialAuthCheck_=void 0,this.prefPatchOps=[],e.Util.assert(!a),a=this}async initAsync(){try{this.state$=await e.storage.shared.getAsync(n,r)}catch(e){}this.state$||(this.state$={}),this.setUserProfileAsync(this.state$.profile),this.setUserPreferencesAsync(this.state$.preferences)}async loginAsync(t,i,r){var a;if(!h()||!function(e){return d().filter((t=>t.id===e)).length>0}(t))return;r=null!=r?r:u;const o=this.getState();o.profile||await this.authCheckAsync();if((null===(a=o.profile)||void 0===a?void 0:a.idp)===t)return void e.debug(`loginAsync: Already signed into ${t}.`);this.clearState();const l={key:(Math.PI*Math.random()).toString(36).slice(2),callbackState:r,callbackPathname:window.location.pathname,idp:t};await e.storage.shared.setAsync(n,s,l);const c=e.Util.stringifyQueryString("/api/auth/login",{response_type:"token",provider:t,persistent:i,redirect_uri:`${window.location.origin}${window.location.pathname}?authcallback=1&state=${l.key}`}),p=await this.apiAsync(c);p.success?(e.tickEvent("auth.login.start",{provider:t}),window.location.href=p.resp.loginUrl):await this.onSignInFailed()}async logoutAsync(t){if(!h())return;e.tickEvent("auth.logout"),await this.apiAsync("/api/auth/logout"),await e.storage.shared.delAsync(n,i),this.clearState();const s=t?t.startsWith("#")?t:`#${t}`:"";e.BrowserUtils.hasWindow()&&(window.location.href=`${window.location.origin}${window.location.pathname}${s}`,location.reload())}async deleteProfileAsync(){var t;if(!await this.loggedInAsync())return;const s=null===(t=this.getState().profile)||void 0===t?void 0:t.id,r=await this.apiAsync("/api/user",null,"DELETE");if(r.err)await this.onApiError(r.err);else try{await e.storage.shared.delAsync(n,i);try{await this.onProfileDeleted(s)}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(!h())return;if(!await e.storage.shared.getAsync(n,i))return;const s=this.getState();return(null===(t=s.profile)||void 0===t?void 0:t.id)?this.initialAuthCheck_||(this.initialAuthCheck_=Promise.resolve(s.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 i=await this.userPreferencesAsync();if(!t.length)return{success:!0,res:i};if(ts.pxtc.jsonPatch.patchInPlace(i,t),await this.setUserPreferencesAsync(i),!await this.loggedInAsync())return{success:!0,res:i};t.forEach(((e,n)=>{this.prefPatchOps.some(((i,s)=>!!ts.pxtc.jsonPatch.opsAreEqual(i,e)&&(this.prefPatchOps[s]=e,t[n]=null,!0)))})),t.filter((e=>!!e)).forEach((e=>this.prefPatchOps.push(e))),clearTimeout(l);const s=async()=>{c=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 s():(c||(c=e.U.now()),1e4<e.U.now()-c?await s():(l=setTimeout(s,1e3),{success:!1,res:void 0}))}hasUserId(){var e;if(!h())return!1;return!!(null===(e=this.getState().profile)||void 0===e?void 0:e.id)}async fetchUserAsync(){var e;if(!h())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 i=null!==(n=this.getState().preferences)&&void 0!==n?n:t.DEFAULT_USER_PREFERENCES(),s=ts.pxtc.jsonPatch.diff(i,e);this.transformUserPreferences(Object.assign(Object.assign({},i),e)),await this.onUserPreferencesChanged(s)}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,r,this.state$).then((()=>{}))}clearState(){this.state$={},e.storage.shared.delAsync(n,r).then((()=>this.onStateCleared()))}async apiAsync(t,s,r){var a;const o={},l=await e.storage.shared.getAsync(n,i);return l&&(o.authorization=`mkcd ${l}`),o["x-pxt-target"]=null===(a=e.appTarget)||void 0===a?void 0:a.id,t=e.BrowserUtils.isLocalHostDev()?`https://staging.pxt.io${t}`:t,e.Util.requestAsync({url:t,headers:o,data:s,method:r||(s?"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 h(){return!o&&!e.BrowserUtils.isPxtElectron()&&d().length>0}function p(e,t){return e.id===t.id&&e.sourceURL===t.sourceURL}t.loginCallbackAsync=async function(t){let r,a=Object.assign({},u);do{if(r=await e.storage.shared.getAsync(n,s),!r)return void e.debug("Auth state not found in storge.");await e.storage.shared.delAsync(n,s);const o=t.state;if(!o||r.key!==o)return void e.debug("Failed to get auth state for key");a=Object.assign(Object.assign({},u),r.callbackState);const l=t.error;if(l){const n=t.error_description;e.tickEvent("auth.login.error",{error:l,provider:r.idp}),e.log(`Auth failed: ${l}:${n}`),a=Object.assign({},u);break}const c=t.token;if(!c){e.debug("Missing authToken in auth callback.");break}await e.storage.shared.setAsync(n,i,c),e.tickEvent("auth.login.success",{provider:r.idp})}while(0);const o=a.hash.startsWith("#")?a.hash:`#${a.hash}`,l=e.Util.stringifyQueryString("",a.params),c=`${r.callbackPathname.startsWith("/")?r.callbackPathname:`/${r.callbackPathname}`}${o}${l}`;window.location.href=c},t.identityProviders=d,t.identityProvider=function(e){return d().filter((t=>t.id===e)).shift()},t.hasIdentity=h,t.enableAuth=function(e=!0){o=!e},t.userName=function(e){var t,n,i,s;return null!==(s=null!==(n=null===(t=null==e?void 0:e.idp)||void 0===t?void 0:t.displayName)&&void 0!==n?n:null===(i=null==e?void 0:e.idp)||void 0===i?void 0:i.username)&&void 0!==s?s:"??"},t.userInitials=function(t){const n=e.auth.userName(t);return ts.pxtc.Util.initials(n)},t.generateUserProfilePicDataUrl=function(t){var n,i;if(null===(i=null===(n=null==t?void 0:t.idp)||void 0===n?void 0:n.picture)||void 0===i?void 0:i.encoded){const n=window.URL||window.webkitURL;try{const i=e.Util.stringToUint8Array(atob(t.idp.picture.encoded)),s=new Blob([i],{type:t.idp.picture.mimeType});t.idp.picture.dataUrl=n.createObjectURL(s)}catch(e){}}},t.badgeEquals=p,t.hasBadge=function(e,t){return e.badges.some((e=>p(e,t)))}}(e.auth||(e.auth={}))}(pxt||(pxt={})),function(e){e.tickEvent=function(e){}}(pxt||(pxt={})),function(e){!function(e){e.__dummy=42}(e.pxtc||(e.pxtc={}))}(ts||(ts={}));var pxtc=ts.pxtc;!function(e){!function(e){!function(e){function t(e){return e.replace(/[^\w .!?\-$]/g,(e=>{let t=e.charCodeAt(0).toString(16);return"\\u"+"0000".substr(0,4-t.length)+t}))}e.assert=function(e,t="Assertion failed"){if(!e)throw new Error(t)},e.flatClone=function(e){if(null==e)return null;let t={};return Object.keys(e).forEach((n=>{t[n]=e[n]})),t},e.clone=function(e){return null==e?null:JSON.parse(JSON.stringify(e))},e.htmlEscape=function(e){return e?e.replace(/([^\w .!?\-$])/g,(e=>"&#"+e.charCodeAt(0)+";")):e},e.htmlUnescape=function(e){return e?e.replace(/(&#\d+;)/g,(e=>String.fromCharCode(Number(e.substr(2,e.length-3))))):e},e.jsStringQuote=t,e.jsStringLiteral=function(e){return'"'+t(e)+'"'},e.initials=function(e){if(/^\w+@/.test(e)){return e.match(/^\w\w/).shift().toUpperCase()}{const t=e.match(/\b\w/g)||[];return((t.shift()||"")+(t.pop()||"")).toUpperCase()}};let n="en",i={},s={},r=!1;function a(){return n}function o(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 l(t,n){return 0==n.length?t:t.replace(/\{([0-9]+)(\:[^\}]+)?\}/g,(function(t,i,s){let r=n[parseInt(i)],a="",o=/^:f(\d*)\.(\d+)/.exec(s);if(o){let e=parseInt(o[2]),t=parseInt(o[1])||0,n=/^0/.test(o[1])?"0":" ",i=r.toFixed(e);if(t>0&&e>0&&(t+=e+1),t>0)for(;i.length<t;)i=n+i;a=i}else a=":x"==s?"0x"+r.toString(16):void 0===r?"(undef)":null===r?"(null)":r.toString?r.toString():r+"";return":a"==s?/^\s*[euioah]/.test(a.toLowerCase())?a="an "+a:/^\s*[bcdfgjklmnpqrstvwxz]/.test(a.toLowerCase())&&(a="a "+a):":s"==s?a=1==r?"":"s":":q"==s?a=e.htmlEscape(a):":jq"==s?a=e.jsStringQuote(a):":uri"==s?a=encodeURIComponent(a).replace(/'/g,"%27").replace(/"/g,"%22"):":url"==s?a=encodeURI(a).replace(/'/g,"%27").replace(/"/g,"%22"):":%"==s&&(a=(100*r).toFixed(1).toString()+"%"),a}))}e.enableLiveLocalizationUpdates=function(){r=!0},e.liveLocalizationEnabled=function(){return r},e.localeInfo=function(){return`${r?"live-":""}${a()}`},e.userLanguage=a,e.normalizeLanguageCode=o,e.setUserLanguage=function(e){n=o(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 a()==e.TRANSLATION_LOCALE},e._localize=function(e){return i[e]||e},e.getLocalizedStrings=function(){return i},e.setLocalizedStrings=function(e){i=e},e.translationsCache=function(){return s},e.fmt_va=l,e.fmt=function(e,...t){return l(e,t)};const c={};e.dumpLocStats=function(){const e={};Object.keys(c).sort(((e,t)=>c[t]-c[e])).forEach((t=>e[t]=t)),console.log("prioritized list of strings:"),console.log(JSON.stringify(e,null,2))};function u(t,n){if(!t)return t;c[t]=(c[t]||0)+1;let i=e._localize(t);return i=i.replace(/^\{(id|loc):[^\}]+\}/g,""),l(i,n)}e.lf_va=u,e.lf=function(e,...t){return u(e,t)},e.rlf=function(e,...t){return u(e,t)},e.lookup=function(e,t){return e.hasOwnProperty(t)?e[t]:null},e.isoTime=function(t){let n=new Date(1e3*t);return e.fmt("{0}-{1:f02.0}-{2:f02.0} {3:f02.0}:{4:f02.0}:{5:f02.0}",n.getFullYear(),n.getMonth()+1,n.getDate(),n.getHours(),n.getMinutes(),n.getSeconds())},e.userError=function(e){let t=new Error(e);throw t.isUserError=!0,t},e.deq=function e(t,n){if(t===n)return null;if(!t||!n)return"Null value";if("object"==typeof t&&"object"==typeof n){if(Array.isArray(t)){if(!Array.isArray(n))return"Expected array";if(t.length!=n.length)return"Expected array of length "+t.length+", got "+n.length;for(let i=0;i<t.length;i++)if(null!=e(t[i],n[i]))return"Expected array value "+t[i]+" got "+n[i];return null}let i=Object.keys(t),s=Object.keys(t);if(i.length!=s.length)return"Expected "+i.length+" keys, got "+s.length;for(let s=0;s<i.length;s++){if(!Object.prototype.hasOwnProperty.call(n,i[s]))return"Missing key "+i[s];if(null!=e(t[i[s]],n[i[s]]))return"Expected value of "+i[s]+" to be "+t[i[s]]+", got "+n[i[s]]}return null}return"Unable to compare "+t+", "+n}}(e.Util||(e.Util={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={}));const lf=ts.pxtc.Util.lf;var pxt,ts,pxtmelody;!function(e){!function(e){e.decodeBase64=function(e){return atob(e)},e.encodeBase64=function(e){return btoa(e)}}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){!function(n){function i(e,t){if(t)for(let n=0;n<t.length;++n)e.push(t[n])}function s(e){let t=[];for(let n=0;n<e.length;++n)i(t,e[n]);return t}function r(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function a(e,t,n,i,s){void 0===i&&(i=0),void 0===s&&(s=n.length-i);for(let r=0;r<s;++r)e[t+r]=n[i+r]}function o(e,t){return e==t?0:e<t?-1:1}n.CancellationToken=class{constructor(){this.pending=!1,this.cancelled=!1}startOperation(){this.pending=!0}isRunning(){return this.pending}onProgress(e){this.progressHandler=e}reportProgress(e,t){this.progressHandler&&this.progressHandler(e,t)}cancel(){this.cancelled=!0,this.pending=!1}cancelAsync(){return this.cancelled||!this.pending?(this.cancelled=!0,this.pending=!1,Promise.resolve()):(this.cancelled=!0,this.deferred=new Promise((e=>{this.resolve=e})),this.deferred)}isCancelled(){return this.cancelled}throwIfCancelled(){if(this.isCancelled())throw new Error}resolveCancel(){this.pending=!1,this.deferred&&(this.resolve(),this.deferred=void 0,this.resolve=void 0)}},n.codalHash16=function(e){const t=[251,175,119,215,81,14,79,191,103,49,181,143,186,157,0,232,31,32,55,60,152,58,17,237,174,70,160,144,220,90,57,223,59,3,18,140,111,166,203,196,134,243,124,95,222,179,197,65,180,48,36,15,107,46,233,130,165,30,123,161,209,23,97,16,40,91,219,61,100,10,210,109,250,127,22,138,29,108,244,67,207,9,178,204,74,98,126,249,167,116,34,77,193,200,121,5,20,113,71,35,128,13,182,94,25,226,227,199,75,27,41,245,230,224,43,225,177,26,155,150,212,142,218,115,241,73,88,105,39,114,62,255,192,201,145,214,168,158,221,148,154,122,12,84,82,163,44,139,228,236,205,242,217,11,187,146,159,64,86,239,195,42,106,198,118,112,184,172,87,2,173,117,176,229,247,253,137,185,99,164,102,147,45,66,231,52,141,211,194,206,246,238,56,110,78,248,63,240,189,93,92,51,53,183,19,171,72,50,33,104,101,69,8,252,83,120,76,135,85,54,202,125,188,213,96,235,136,208,162,129,190,132,156,38,47,1,7,254,24,4,216,131,89,21,28,133,37,153,149,80,170,68,6,169,234,151];function n(e){let n=0;for(let i=0;i<e.length;i++){let s=e[i];n=t[n^s]}return n}return e?function(e,t){let i;const s=new Uint8Array(e.length);for(let t=0;t<e.length;++t){const n=e.charCodeAt(t);s[t]=255&n}let r=0;for(let e=0;e<t;++e)i=n(s),r|=i<<8*e,s[0]=(s[0]+1)%255;return r}(e,2):0},n.bufferSerial=function(e,t="",n="?",i=255){for(let s=0;s<t.length;++s){const r=t[s];if(e[n]=(e[n]||"")+r,"\n"===r||e[n].length>i){let t=e[n];e[n]="",window.postMessage({type:"serial",id:n,data:t},"*")}}},n.blobReadAsDataURL=function(e){return e?new Promise(((t,n)=>{const i=new FileReader;i.onload=()=>t(i.result),i.onerror=e=>n(e),i.readAsDataURL(e)})):Promise.resolve(void 0)},n.fileReadAsBufferAsync=function(e){return e?new Promise(((t,n)=>{let i=new FileReader;i.onerror=e=>t(null),i.onload=e=>t(new Uint8Array(i.result)),i.readAsArrayBuffer(e)})):Promise.resolve(null)},n.fileReadAsTextAsync=function(e){return e?new Promise(((t,n)=>{let i=new FileReader;i.onerror=e=>t(null),i.onload=e=>t(i.result),i.readAsText(e)})):Promise.resolve(null)},n.repeatMap=function(e,t){e=e||0;let n=[];for(let i=0;i<e;++i)n.push(t(i));return n},n.listsEqual=function(e,t){if(!e||!t||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0},n.oops=function(e="OOPS"){throw new Error(e)},n.reversed=function(e){return(e=e.slice(0)).reverse(),e},n.arrayEquals=function(e,t,n=((e,t)=>e===t)){if(e==t)return!0;if(!e&&t||!t&&e||e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!n(e[i],t[i]))return!1;return!0},n.iterMap=function(e,t){Object.keys(e).forEach((n=>t(n,e[n])))},n.mapMap=function(e,t){let n={};return Object.keys(e).forEach((i=>n[i]=t(i,e[i]))),n},n.values=function(e){return Object.keys(e||{}).map((t=>e[t]))},n.pushRange=i,n.concatArrayLike=function(e){return s(e)},n.concat=s,n.memcpy=a,n.uint8ArrayConcat=function(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),i=0;for(let t of e)a(n,i,t),i+=t.length;return n},n.jsonTryParse=function(e){try{return JSON.parse(e)}catch(e){return}},n.jsonMergeFrom=function e(t,i){i&&Object.keys(i).forEach((s=>{r(t[s])&&r(i[s])?e(t[s],i[s]):t[s]=n.clone(i[s])}))},n.jsonCopyFrom=function(e,t){let i=n.clone(t);for(let n of Object.keys(t))e[n]=i[n]},n.jsonFlatten=function(e){let t={},i=(e,s)=>{if(null!==s&&"object"==typeof s){n.assert(!Array.isArray(s)),e&&(e+=".");for(let t of Object.keys(s))i(e+t,s[t])}else t[e]=s};return i("",e),t},n.jsonUnFlatten=function(e){let t={};for(let n of Object.keys(e)){let i=t,s=n.split(".");for(let t=0;t<s.length;++t){let r=s[t];t==s.length-1?i[r]=e[n]:("object"!=typeof i[r]&&(i[r]={}),i=i[r])}}return t},n.strcmp=o,n.stringMapEq=function(e,t){let n=Object.keys(e),i=Object.keys(t);if(n.length!=i.length)return!1;for(let i of n){if(!t.hasOwnProperty(i))return!1;if(e[i]!==t[i])return!1}return!0},n.endsWith=function(e,t){return!(e.length<t.length)&&(0==t.length||e.slice(-t.length)==t)},n.startsWith=function(e,t){return!(e.length<t.length)&&(0==t.length||e.slice(0,t.length)==t)},n.contains=function(e,t){return!(e.length<t.length)&&(0==t.length||e.indexOf(t)>-1)},n.replaceAll=function(e,t,n){return t?e.split(t).join(n):e},n.snakify=function(e){const t=e.toUpperCase(),n=e.toLowerCase();if(e==t||e==n)return e;if(e.lastIndexOf("_")>0)return e;const i=t=>e[t]!=n[t],s=n=>e[n]!=t[n];let r="",a=0;for(;a<e.length;){let t=i(a),n=a;for(;n<e.length;){if(t&&s(n)){if(n-a>2){n--;break}t=!1}if(!t&&i(n))break;n++}r&&(r+="_"),r+=e.slice(a,n),a=n}return r.toUpperCase()===r?r:r.toLowerCase()},n.sortObjectFields=function(e){let t=Object.keys(e);t.sort(o);let n={};return t.forEach((t=>n[t]=e[t])),n},n.chopArray=function(e,t){let n=[];for(let i=0;i<e.length;i+=t)n.push(e.slice(i,i+t));return n},n.unique=function(e,t){let n=[],i={};return e.forEach((e=>{let s=t(e);i.hasOwnProperty(s)||(i[s]=null,n.push(e))})),n},n.groupBy=function(e,t){let n={};return e.forEach((e=>{let i=t(e);n.hasOwnProperty(i)||(n[i]=[]),n[i].push(e)})),n},n.toDictionary=function(e,t){let n={};return e.forEach((e=>{n[t(e)]=e})),n},n.toSet=function(e,t){let n={};return e.forEach((e=>{n[t(e)]=!0})),n},n.toArray=function(e){if(Array.isArray(e))return e;let t=[];if(!e)return t;for(let n=0;n<e.length;++n)t.push(e[n]);return t},n.indexOfMatching=function(e,t){for(let n=0;n<e.length;++n)if(t(e[n]))return n;return-1};const l=Promise.resolve();async function c(e,t,n){let i=0;const s=[],r=[];for(let a=0;a<e;a++){const e=(async()=>{for(;i<t.length;){const e=i++,s=t[e];r[e]=await n(s)}})();s.push(e)}try{await Promise.all(s)}catch(e){throw i=t.length,e}return r}function u(e,t){const n={};return i=>{const s=e(i);return n.hasOwnProperty(s)?n[s]:n[s]=t(i)}}n.nextTick=function(e){l.then(e)},n.delay=async function(e,t){const n=await t;return await new Promise((t=>setTimeout((()=>t()),e))),n},n.promiseMapAll=function(e,t){return Promise.all(e.map((e=>t(e))))},n.promiseMapAllSeries=function(e,t){return c(1,e,t)},n.promisePoolAsync=c,n.memoizeString=function(e){return u((e=>e),e)},n.promiseTimeout=async function(e,t,n){let i,s;const r=new Promise(((t,r)=>{s=t,i=setTimeout((()=>{s=void 0,clearTimeout(i),r(n||`Promise timed out after ${e}ms`)}),e)}));return Promise.race([t,r]).then((e=>(s&&(clearTimeout(i),s()),e)))},n.defer=function(){let e,t,n,i=!1;return{resolve:function(n){i?pxt.debug("Deferred promise already resolved"):(t?t(n):e=e||new Promise((function(e){e(n)})),i=!0)},reject:function(t){i?pxt.debug("Deferred promise already resolved"):(n?n(t):e=e||new Promise((function(e,n){n(t)})),i=!0)},promise:new Promise((function(i,s){e?i(e):(t=i,n=s)}))}},n.memoize=u,n.debounce=function(e,t,n){let i;return function(){let s=this,r=arguments,a=function(){i=null,n||e.apply(s,r)},o=n&&!i;return clearTimeout(i),i=setTimeout(a,t),o&&e.apply(s,r),i}};function d(e){return e&&(e=e.replace(/\\/g,"/")),e}function h(e){return n.httpRequestCoreAsync(e).then((i=>{const s=i.statusCode;if((e.successCodes||[304,200,201,202]).indexOf(s)<0&&!e.allowHttpErrors){const t=n.lf("Bad HTTP status code: {0} at {1}; message: {2}",i.statusCode,e.url,(i.text||"").slice(0,500)),s=new Error(t);return s.statusCode=i.statusCode,Promise.reject(s)}return i.text&&/application\/json/.test(i.headers["content-type"])&&(i.json=t.U.jsonTryParse(i.text)),i}))}function p(e,t){let n="";if(!e)return n;for(let i=0;i<e.length;++i){let s=e.charCodeAt(i);if(s<=127)n+=e.charAt(i);else if(s<=2047)n+=String.fromCharCode(192|s>>6,128|63&s);else{if(!t&&55296<=s&&s<=56319){let t=e.charCodeAt(++i);isNaN(t)||(s=65536+(s-55296<<10)+(t-56320))}n+=s<=65535?String.fromCharCode(224|s>>12,128|s>>6&63,128|63&s):String.fromCharCode(240|s>>18,128|s>>12&63,128|s>>6&63,128|63&s)}}return n}n.AdaptiveDebouncer=class{constructor(e,t=300,n=2e3,i=2){this.func=e,this.minDelay=t,this.maxDelay=n,this.slowdownFactor=i,this.lastPoke=0,this.recentGaps=[],this.wrapped=()=>{this.timeout=null,this.func()}}poke(){const e=Date.now();if(this.lastPoke){const t=e-this.lastPoke;if(t<10)return;for(t<4e3&&this.recentGaps.push(t);this.recentGaps.length>10;)this.recentGaps.shift()}this.lastPoke=e}trigger(){let e=this.maxDelay;if(this.lastPoke){const t=this.recentGaps.slice();t.sort();const n=t[t.length>>1]||1;e=Math.min(Math.max(n*this.slowdownFactor|0,this.minDelay),this.maxDelay);e-=Date.now()-this.lastPoke,e<0&&(e=0),this.lastPoke=null}clearTimeout(this.timeout),this.timeout=setTimeout(this.wrapped,e)}},n.throttle=function(e,t,n){let i;return function(){let s=this,r=arguments,a=function(){i=null,n||e.apply(s,r)},o=n&&!i;i||(i=setTimeout(a,t)),o&&e.apply(s,r)}},n.randomPermute=function(e){for(let t=0;t<e.length;++t){let n=g()%e.length,i=e[t];e[t]=e[n],e[n]=i}},n.randomPick=function(e){return 0==e.length?null:e[g()%e.length]},n.timeSince=function(e){let t=(Date.now()-(e*=1e3))/1e3;return isNaN(t)?"":t<-30?(t=-t,t<60?n.lf("in a few seconds"):t<120?n.lf("in a minute"):t<3600?n.lf("in {0} minute{0:s}",Math.floor(t/60)):t<7200?n.lf("in an hour"):t<86400?n.lf("in {0} hour{0:s}",Math.floor(t/60/60)):t<2592e3?n.lf("in {0} day{0:s}",Math.floor(t/60/60/24)):t<31536e3?n.lf("in {0} month{0:s}",Math.floor(t/60/60/24/30)):n.lf("in {0} year{0:s}",Math.floor(t/60/60/24/365))):t<0?n.lf("now"):t<10?n.lf("a few seconds ago"):t<60?n.lf("{0} second{0:s} ago",Math.floor(t)):t<120?n.lf("a minute ago"):t<3600?n.lf("{0} minute{0:s} ago",Math.floor(t/60)):t<7200?n.lf("an hour ago"):t<86400?n.lf("{0} hour{0:s} ago",Math.floor(t/60/60)):t<2592e3?n.lf("{0} day{0:s} ago",Math.floor(t/60/60/24)):t<31536e3?n.lf("{0} month{0:s} ago",Math.floor(t/60/60/24/30)):n.lf("{0} year{0:s} ago",Math.floor(t/60/60/24/365))},n.unicodeToChar=function(e){return e.replace(/\\u([\d\w]{4})/gi,(function(e,t){return String.fromCharCode(parseInt(t,16))}))},n.escapeForRegex=function(e){return null==e?void 0:e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},n.stripUrlProtocol=function(e){return null==e?void 0:e.replace(/.*?:\/\//g,"")},n.normalizePath=d,n.pathJoin=function(e,t){if(d(e),d(t),e||t)return e?t?("/"!==e.charAt(e.length-1)&&(e+="/"),"/"==t.charAt(0)&&(t=t.substring(1)),e+t):e:t},n.isNodeJS="undefined"==typeof window,n.requestAsync=h,n.httpGetTextAsync=function(e){return h({url:e}).then((e=>e.text))},n.httpGetJsonAsync=function(e){return h({url:e}).then((e=>e.json))},n.httpPostJsonAsync=function(e,t){return h({url:e,data:t||{}}).then((e=>e.json))},n.stringToUint8Array=function(e){let t=e.length,n=new Uint8Array(t);for(let i=0;i<t;++i)n[i]=255&e.charCodeAt(i);return n},n.uint8ArrayToString=function(e){let t=e.length,n="";for(let i=0;i<t;++i)n+=String.fromCharCode(e[i]);return n},n.fromUTF8=function(e){if(!e)return"";let t="";for(let n=0;n<e.length;++n){let i=255&e.charCodeAt(n);t+=37==i||i>127?"%"+i.toString(16):e.charAt(n)}return decodeURIComponent(t)},n.toUTF8=p,n.toHex=function(e){let t="";for(let n=0;n<e.length;++n)t+=("0"+e[n].toString(16)).slice(-2);return t},n.fromHex=function(e){let t=new Uint8Array(e.length>>1);for(let n=0;n<e.length;n+=2)t[n>>1]=parseInt(e.slice(n,n+2),16);return t};n.PromiseQueue=class{constructor(){this.promises={}}enqueue(e,t){return new Promise(((n,i)=>{let s=this.promises[e];s||(s=this.promises[e]=[]),s.push((()=>t().finally((()=>{s.shift(),0==s.length?delete this.promises[e]:s[0]()})).then(n,i))),1==s.length&&s[0]()}))}};function f(){return Date.now()}function g(){let e=new Uint8Array(4);return n.getRandomBuf(e),new Uint32Array(e.buffer)[0]}function m(e,t,n,i){function s(s){pxt.debug(`downloading translations for ${e} ${t} ${n||""}`);let r=pxt.BrowserUtils.isLocalHost()||pxt.webConfig.isStatic?"https://makecode.com/api/":"",a=`${r}translations?lang=${encodeURIComponent(e)}&filename=${encodeURIComponent(t)}&approved=true`;n&&(a+="&branch="+encodeURIComponent(n));const o={};return i&&!pxt.Cloud.useCdnApi()&&(o["If-None-Match"]=i),(r?h:pxt.Cloud.apiRequestWithCdnAsync)({url:a,headers:o}).then((r=>304==r.statusCode||200==r.statusCode?(i=r.headers.etag||"",pxt.BrowserUtils.translationDbAsync().then((a=>a.setAsync(e,t,n,i,r.json||s))).then((()=>r.json||s))):r.json),(e=>{console.log(`failed to load translations from ${a}`)}))}return pxt.BrowserUtils.translationDbAsync().then((i=>i.getAsync(e,t,n))).then((e=>{if(e){i=e.etag;return(Date.now()-e.time)/1e3>300&&s(e.strings),e.strings}return s()}))}function b(e){let[t,i]=n.normalizeLanguageCode(e),s=pxt.appTarget.appTheme;if(s&&s.availableLocales){if(s.availableLocales.indexOf(t)>-1)return!0;if(i&&s.availableLocales.indexOf(i)>-1)return!0}return!1}let y;function v(e,i,s,r,a,o,l){if(l=l||y.Editor,"en-US"===(s=n.normalizeLanguageCode(s)[0])||"en"===s)return Promise.resolve(void 0);let c,u,d=`${s}/${o}/${l}`;if(n.translationsCache()[d])return Promise.resolve(n.translationsCache()[d]);switch(l){case y.Editor:c=[{branch:r,staticName:"strings.json",path:"strings.json"},{branch:a,staticName:"target-strings.json",path:e+"/target-strings.json"}];break;case y.Sim:c=[{branch:a,staticName:"sim-strings.json",path:e+"/sim-strings.json"}];break;case y.Apis:c=[{branch:a,staticName:"bundled-strings.json",path:e+"/bundled-strings.json"}];break;case y.SkillMap:c=[{branch:a,staticName:"skillmap-strings.json",path:"/skillmap-strings.json"}]}function h(e){e&&(u||(u={}),Object.keys(e).filter((t=>!!e[t])).forEach((t=>u[t]=e[t])))}if(o){let o=0;return t.U.promiseMapAllSeries(c,(e=>m(s,e.path,e.branch).then(h,(e=>{console.log(e.message),++o})))).then((()=>(o&&(n.translationsCache()[d]=u),o!==c.length&&u?Promise.resolve(u):(pxt.tickEvent("translations.livetranslationsfailed"),v(e,i,s,r,a,!1,l)))))}return Promise.all(c.map((e=>n.httpGetJsonAsync(`${i}locales/${s}/${e.staticName}`).catch((e=>{}))))).then((e=>{let t={};e.forEach((e=>pxt.Util.jsonMergeFrom(t,e))),Object.keys(t).length&&(u=t,n.translationsCache()[d]=u)}),(e=>{console.error("failed to load localizations")})).then((()=>u))}function w(e){const t={};for(const n of Object.keys(e))t[n]=k(e[n]);return t}function k(e){var t;return{attributes:Object.assign({},e.attributes),parameters:null===(t=e.parameters)||void 0===t?void 0:t.map(A),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 A(e){var n,i;return{name:e.name,description:e.description,type:e.type,pyTypeString:e.pyTypeString,initializer:e.initializer,default:e.default,properties:null===(n=e.properties)||void 0===n?void 0:n.map(x),handlerParameters:null===(i=e.handlerParameters)||void 0===i?void 0:i.map(x),options:e.options?t.U.clone(e.options):void 0,isEnum:e.isEnum}}function x(e){return{name:e.name,type:e.type}}n.PromiseBuffer=class{constructor(){this.waiting=[],this.available=[]}drain(){for(let e of this.waiting)e(new Error("Promise Buffer Reset"));this.waiting=[],this.available=[]}pushError(e){this.push(e)}push(e){let t=this.waiting.shift();t?t(e):this.available.push(e)}shiftAsync(e=0){if(this.available.length>0){let e=this.available.shift();return e instanceof Error?Promise.reject(e):Promise.resolve(e)}return new Promise(((n,i)=>{let s=e=>{e instanceof Error?i(e):n(e)};this.waiting.push(s),e>0&&t.U.delay(e).then((()=>{let e=this.waiting.indexOf(s);e>=0&&(this.waiting.splice(e,1),i(new Error("Timeout")))}))}))}},n.now=f,n.nowSeconds=function(){return Math.round(f()/1e3)},n.timeout=function(e){return new Promise((t=>setTimeout((()=>t()),e)))},n.cpuUs=()=>{const e="undefined"!=typeof performance?performance.now.bind(performance)||performance.moznow.bind(performance)||performance.msNow.bind(performance)||performance.webkitNow.bind(performance)||performance.oNow.bind(performance):Date.now;return n.cpuUs=()=>1e3*e(),n.cpuUs()},n.getMime=function(e){let t=/\.([a-zA-Z0-9]+)$/.exec(e);if(!t)return"application/octet-stream";switch(t[1].toLowerCase()){case"txt":return"text/plain";case"html":case"htm":return"text/html";case"css":return"text/css";case"js":return"application/javascript";case"jpg":case"jpeg":return"image/jpeg";case"png":return"image/png";case"ico":return"image/x-icon";case"manifest":return"text/cache-manifest";case"webmanifest":return"application/manifest+json";case"json":return"application/json";case"svg":return"image/svg+xml";case"eot":return"application/vnd.ms-fontobject";case"ttf":return"font/ttf";case"woff":return"application/font-woff";case"woff2":return"application/font-woff2";case"md":return"text/markdown";case"xml":return"application/xml";case"m4a":return"audio/m4a";case"mp3":return"audio/mp3";default:return"application/octet-stream"}},n.randomUint32=g,n.guidGen=function(){function e(){return(65536|g()).toString(16).slice(-4)}return e()+e()+"-"+e()+"-4"+e().slice(-3)+"-"+e()+"-"+e()+e()+e()},n.downloadLiveTranslationsAsync=m,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=b,n.updateLocalizationAsync=function(t){const{targetId:i,baseUrl:s,pxtBranch:r,targetBranch:a,force:o}=t;let{code:l}=t;if(l=n.normalizeLanguageCode(l)[0],"en-US"===l&&(l="en"),l===n.userLanguage()||!b(l)&&!o)return pxt.debug(`loc: ${l} (using built-in)`),Promise.resolve();pxt.debug(`loc: ${l}`);const c=pxt.Util.liveLocalizationEnabled();return v(i,s,l,r,a,c,e.pxtc.Util.TranslationsKind.Editor).then((t=>(t&&(n.setUserLanguage(l),n.setLocalizedStrings(t)),e.pxtc.Util.downloadTranslationsAsync(i,s,l,r,a,c,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={},i=null,s=null){const r="--------------------------0461489f461126c5";let a="";Object.keys(t).forEach((e=>{return n=e,i=t[e],a+=r+"\r\n",a+='Content-Disposition: form-data; name="'+n+'"\r\n\r\n',void(a+=i+"\r\n");var n,i})),i&&function(e,t){const n=e.split("/").reverse()[0];a+=r+"\r\n",a+='Content-Disposition: form-data; name="files['+e+']"; filename="'+n+'"\r\n',a+="\r\n",a+=t+"\r\n"}(i,s),a+=r+"--\r\n";const o={url:e,method:"POST",headers:{"Content-Type":"multipart/form-data; boundary="+r.slice(2)},data:a};return n.httpRequestCoreAsync(o)},n.toDataUri=function(e,n){return/^https?:/i.test(e)||/^data:/i.test(e)?e:(n||/^<svg/i.test(e)&&(n="image/svg+xml"),/xml|svg/.test(n)?`data:${n},${encodeURIComponent(e)}`:`data:${n||"image/png"};base64,${t.encodeBase64(p(e))}`)},n.imageMagic=1496611453,n.imageHeaderSize=36,n.encodeBlobAsync=function(e,t){const i=n.imageHeaderSize+t.length,s=3*(e.width*e.height-1);let r=1;for(;r<4&&!(s*r>=8*i);)r++;let a=s*r>>3,o=i-a,l=0,c=e.width*e.height*4;if(o>0){const t=3*e.width;l=Math.ceil(o/t);const n=document.createElement("canvas");n.width=e.width,n.height=e.height+l;n.getContext("2d").drawImage(e,0,0),e=n}let u=pxt.HF2.encodeU32LE([n.imageMagic,t.length,l,0,0,0,0,0,0]);function d(e,t,n,i){let s=0,r=0,a=i[r++];const o=(1<<n)-1;let l=!0;for(;l;){let c=a>>s&o,u=8-s;if(u<=n){if(r>=i.length){if(0==u)break;l=!1}a=i[r++],c|=a<<u&o,s=n-u}else s+=n;e[t]=255&(e[t]&~o|c),3==(3&++t)&&(e[t++]=255)}return t}pxt.Util.assert(u.length==n.imageHeaderSize);const h=e.getContext("2d"),p=h.getImageData(0,0,e.width,e.height);d(p.data,0,1,[r]);let f=4;if(f=d(p.data,f,r,u),pxt.Util.assert(0==(3&f)),0==l)f=d(p.data,f,r,t);else{let e=a-u.length;f=d(p.data,f,r,t.slice(0,e)),f=d(p.data,c,8,t.slice(e))}for(f|=3;f<p.data.length;)p.data[f]=255,f+=4;return h.putImageData(p,0,0),e},n.decodeBlobAsync=function(e){return pxt.BrowserUtils.loadCanvasAsync(e).then((e=>{const t=e.getContext("2d").getImageData(0,0,e.width,e.height).data,i=1&t[0]|(1&t[1])<<1|(1&t[2])<<2;if(i>5||0==i)return Promise.reject(new Error(n.lf("Invalid encoded PNG format")));function s(e,n,i){let s=0,r=0,a=0;const o=(1<<n)-1;for(;r<i.length;)a|=(t[e++]&o)<<s,3==(3&e)&&e++,s+=n,s>=8&&(i[r++]=255&a,a>>=8,s-=8);return e}const r=new Uint8Array(pxt.Util.imageHeaderSize);let a=s(4,i,r);const o=pxt.HF2.decodeU32LE(r);if(o[0]!=pxt.Util.imageMagic)return Promise.reject(new Error(n.lf("Invalid magic in encoded PNG")));const l=new Uint8Array(o[1]),c=o[2];if(c>0){const t=(e.height-c)*e.width,n=new Uint8Array((3*(t-1)*i>>3)-pxt.Util.imageHeaderSize);s(a,i,n),l.set(n);const r=new Uint8Array(l.length-n.length);s(4*t,8,r),l.set(r,n.length)}else s(a,i,l);return l}))},n.parseQueryString=function(e){let t={};return e.replace(/\+/g," ").replace(/([^#?&=]+)=([^#?&=]*)/g,((e,n,i)=>(t[decodeURIComponent(n)]=decodeURIComponent(i),""))),t},n.stringifyQueryString=function(e,t){for(let n of Object.keys(t))e.indexOf("?")>=0?e+="&":e+="?",e+=encodeURIComponent(n)+"="+encodeURIComponent(t[n]);return e},n.cloneTargetBundle=function(e){const t=(e=Object.assign({},e)).apiInfo;delete e.apiInfo;const i=e.bundleddirs;delete e.bundleddirs;const s=e.bundledpkgs;delete e.bundledpkgs;const r=e.tutorialInfo;delete e.tutorialInfo;const a=n.clone(e);if(t){a.apiInfo={};for(const e of Object.keys(t)){const n=t[e].apis;a.apiInfo[e]={sha:t[e].sha,apis:{jres:Object.assign({},n.jres),byQName:w(n.byQName)}}}}if(i&&(a.bundleddirs=[...i]),s){a.bundledpkgs={};for(const e of Object.keys(s))a.bundledpkgs[e]=Object.assign({},s[e])}if(r){a.tutorialInfo={};for(const e of Object.keys(r)){const t=r[e];a.tutorialInfo[e]={hash:t.hash,usedBlocks:Object.assign({},t.usedBlocks),snippetBlocks:Object.assign({},t.snippetBlocks)}}}return a},n.cloneApis=w,n.cloneSymbolInfo=k,n.toUTF8Array=function(e){return(new TextEncoder).encode(e)},n.fromUTF8Array=function(e){return(new TextDecoder).decode(e)}}(t.Util||(t.Util={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){!function(t){e.Util.httpRequestCoreAsync=function(t){return new Promise(((n,i)=>{let s,r=!1,a=e.Util.clone(t.headers)||{};s=new XMLHttpRequest,t.responseArrayBuffer&&(s.responseType="arraybuffer"),t.withCredentials&&(s.withCredentials=!0),s.onreadystatechange=()=>{if(!r&&4==s.readyState){r=!0;let e={statusCode:s.status,headers:{},buffer:s.responseBody||s.response,text:t.responseArrayBuffer?void 0:s.responseText};s.getAllResponseHeaders().split(/\r?\n/).forEach((t=>{let n=/^\s*([^:]+): (.*)/.exec(t);n&&(e.headers[n[1].toLowerCase()]=n[2])})),n(e)}};let o,l=t.data,c=t.method||(null==l?"GET":"POST");null==l?o=null:l instanceof Uint8Array?o=l:"object"==typeof l?(o=JSON.stringify(l),a["content-type"]="application/json; charset=utf8"):"string"==typeof l?o=l:e.Util.oops("bad data"),s.open(c,t.url),Object.keys(a).forEach((e=>{s.setRequestHeader(e,a[e])})),null==o?s.send():s.send(o)}))},e.Util.sha256=a,e.Util.getRandomBuf=e=>{if(window.crypto)window.crypto.getRandomValues(e);else for(let t=0;t<e.length;++t)e[t]=Math.floor(255*Math.random())};const n=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function i(e,t){return e>>>t|e<<32-t}function s(t,s){e.Util.assert(8==t.length),e.Util.assert(64==s.length);for(let e=16;e<64;++e){let t=i(s[e-15],7)^i(s[e-15],18)^s[e-15]>>>3,n=i(s[e-2],17)^i(s[e-2],19)^s[e-2]>>>10;s[e]=s[e-16]+t+s[e-7]+n|0}let r=t[0],a=t[1],o=t[2],l=t[3],c=t[4],u=t[5],d=t[6],h=t[7];for(let e=0;e<64;++e){let t=h+(i(c,6)^i(c,11)^i(c,25))+(c&u^~c&d)+n[e]+s[e]|0,p=r&a^r&o^a&o;h=d,d=u,u=c,c=l+t|0,l=o,o=a,a=r,r=t+((i(r,2)^i(r,13)^i(r,22))+p|0)|0}t[0]+=r,t[1]+=a,t[2]+=o,t[3]+=l,t[4]+=c,t[5]+=u,t[6]+=d,t[7]+=h}function r(e){let t=new Uint32Array(8);t[0]=1779033703,t[1]=3144134277,t[2]=1013904242,t[3]=2773480762,t[4]=1359893119,t[5]=2600822924,t[6]=528734635,t[7]=1541459225;let n=new Uint32Array(64);function i(e){let i=e.length-63;for(let r=0;r<i;r+=64){for(let t=0;t<16;t++){let i=(t<<2)+r;n[t]=e[i]<<24|e[i+1]<<16|e[i+2]<<8|e[i+3]}s(t,n)}}i(e);let r=64-(e.length+9)%64;64==r&&(r=0);let a=e.length-e.length%64,o=new Uint8Array(e.length-a+1+r+8),l=0;for(;a<e.length;)o[l++]=e[a++];for(o[l++]=128;r-- >0;)o[l++]=0;let c=8*e.length;for(l=o.length;c>0;)o[--l]=255&c,c>>=8;i(o);let u="";for(let e=0;e<t.length;++e)u+=("000000000"+t[e].toString(16)).slice(-8);return u.toLowerCase()}function a(t){pxt.perf.measureStart("sha256buffer");const n=r(e.Util.toUTF8Array(t));return pxt.perf.measureEnd("sha256buffer"),n}t.sha256buffer=r,t.sha256string=a}(e.BrowserImpl||(e.BrowserImpl={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){!function(t){const n={add:(e,t,n)=>{if("object"!=typeof e)throw new Error("jsonPatch: expected object type");if(t in e)throw new Error(`jsonPatch: object already contains key ${t}`);e[t]=n},replace:(e,t,n)=>{if("object"!=typeof e)throw new Error("jsonPatch: expected object type");e[t]=n},remove:(e,t)=>{if("object"!=typeof e)throw new Error("jsonPatch: expected object type");delete e[t]}},i={add:(e,t,n)=>{if(!Array.isArray(e))throw new Error("jsonPatch: expected array type");if(t in e)throw new Error(`jsonPatch: key ${t} already exists in array`);"number"!=typeof t||t!==Math.floor(t)?e[t]=n:e.splice(t,0,n)},replace:(e,t,n)=>{if(!Array.isArray(e))throw new Error("jsonPatch: expected array type");"number"!=typeof t||t!==Math.floor(t)?e[t]=n:e.splice(t,1,n)},remove:(e,t)=>{if(!Array.isArray(e))throw new Error("jsonPatch: expected array type");"number"!=typeof t||t!==Math.floor(t)?delete e[t]:e.splice(t,1)}};t.diff=function(e,t){const n={add:[],remove:[],replace:[]};function i(e,t){if(!Array.isArray(e))return t;const n=Number.parseFloat(t);return Number.isNaN(n)?t:n}return function e(t,s,r){if(!Object.is(t,s)){s=s||{},t=t||{};for(let e of Object.keys(t))if(!(e in s)){const s=i(t,e);n.remove.push({op:"remove",path:r.concat(s)})}for(const a of Object.keys(s)){const o=t[a],l=s[a],c=i(s,a);c in t?"object"!=typeof o&&"object"!=typeof l&&o!==l||typeof o!=typeof l||Array.isArray(o)!==Array.isArray(l)?n.replace.push({op:"replace",path:r.concat(c),value:l}):e(o,l,r.concat(c)):void 0!==s[c]&&(r.length&&n.add.push({op:"add",path:r,value:Array.isArray(s)?[]:{}}),n.add.push({op:"add",path:r.concat(c),value:l}))}}}(e,t,[]),[...n.remove.reverse(),...n.replace,...n.add.sort(((e,t)=>e.path.length-t.path.length))]},t.patchInPlace=function(e,t){if(!e||"object"!=typeof e)throw new Error("jsonPatch: Must be an object or an array.");for(const s of t){const t=s.path.slice(),r=t.pop();if(null==r)throw new Error("jsonPatch: missing last key");let a=e,o=t.shift();for(;null!=o;){if(!(o in a))throw new Error(`jsonPatch: missing parent element ${o}`);a=a[o],o=t.shift()}if(Array.isArray(a)&&"number"!=typeof r)throw new Error("jsonPatch: expected numeric index for array object");const l=Array.isArray(a)?i:n;"remove"===s.op?l.remove(a,r):"add"!==s.op||r in a?"replace"===s.op&&l.replace(a,r,s.value):l.add(a,r,s.value)}},t.opsAreEqual=function(t,n){return t.op===n.op&&e.U.arrayEquals(t.path,n.path)}}(e.jsonPatch||(e.jsonPatch={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){!function(t){!function(t){function n(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){const i=Array.isArray(e),s=Array.isArray(t);if(i&&s){if(e.length!==t.length)return!1;for(let i=0;i<e.length;++i)if(!n(e[i],t[i]))return!1;return!0}if(i!==s)return!1;const r=Object.keys(e);if(r.length!==Object.keys(t).length)return!1;for(const i of r){if(!t.hasOwnProperty(i))return!1;if(!n(e[i],t[i]))return!1}return!0}return e!=e&&t!=t}t.diffTests=function(){const t=[{comment:"test 1",obja:{a:4,b:5},objb:{a:3,b:5},expected:[{op:"replace",path:["a"],value:3}]},{comment:"test 2",obja:{a:3,b:5},objb:{a:4,c:5},expected:[{op:"remove",path:["b"]},{op:"replace",path:["a"],value:4},{op:"add",path:["c"],value:5}]},{comment:"test 3",obja:{a:4,b:[1,2,3]},objb:{a:3,b:[1,2,4]},expected:[{op:"replace",path:["a"],value:3},{op:"replace",path:["b",2],value:4}]},{comment:"test 4",obja:{a:3,b:[1,2,4]},objb:{a:3,b:[1,2,4,5]},expected:[{op:"add",path:["b"],value:[]},{op:"add",path:["b",3],value:5}]},{comment:"test 5",obja:{a:4,b:{c:3}},objb:{a:4,b:{c:4}},expected:[{op:"replace",path:["b","c"],value:4}]},{comment:"test 6",obja:{a:4,b:{c:4}},objb:{a:5,b:{d:4}},expected:[{op:"remove",path:["b","c"]},{op:"replace",path:["a"],value:5},{op:"add",path:["b"],value:{}},{op:"add",path:["b","d"],value:4}]},{comment:"test 7",obja:{a:4,b:[2,"foo"]},objb:{a:4,b:[2,"foo",["this","that"]]},expected:[{op:"add",path:["b"],value:[]},{op:"add",path:["b",2],value:["this","that"]}]}];for(const i of t){console.log(i.comment);const t=e.pxtc.jsonPatch.diff(i.obja,i.objb);n(t,i.expected)?console.log("succeeded"):(console.error("FAILED"),console.log("got",t),console.log("exp",i.expected))}},t.patchTests=function(){const t=[{comment:"test 1",obj:{a:"foo",b:[4,11]},patches:[{op:"remove",path:["b"]},{op:"replace",path:["a"],value:4},{op:"add",path:["c"],value:5}],expected:{a:4,c:5}},{comment:"test 2",obj:{a:4,b:[1,2,3]},patches:[{op:"replace",path:["a"],value:3},{op:"replace",path:["b",2],value:4},{op:"add",path:["b",3],value:9}],expected:{a:3,b:[1,2,4,9]}},{comment:"test 3",obj:{a:4,b:{c:3}},patches:[{op:"replace",path:["a"],value:5},{op:"remove",path:["b","c"]},{op:"add",path:["b","d"],value:4}],expected:{a:5,b:{d:4}}},{comment:"test 4",obj:{a:4},patches:[{op:"add",path:["b"],value:[]},{op:"add",path:["b",0],value:"foo"},{op:"add",path:["b",1],value:"bar"}],expected:{a:4,b:["foo","bar"]},validate:e=>e.b&&e.b.forEach}];for(const i of t){console.log(i.comment),e.pxtc.jsonPatch.patchInPlace(i.obj,i.patches);!n(i.obj,i.expected)||!i.validate||i.validate(i.obj)?console.log("succeeded"):i.expected&&(console.error("FAILED"),console.log("got",i.obj),console.log("exp",i.expected))}}}(t.tests||(t.tests={}))}(t.jsonPatch||(t.jsonPatch={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){e.perf||(e.perf={})}(pxt||(pxt={})),pxt.perf.report||(pxt.perf.report=()=>{}),pxt.perf.recordMilestone||(pxt.perf.recordMilestone=()=>{}),pxt.perf.measureStart||(pxt.perf.measureStart=()=>{}),pxt.perf.measureEnd||(pxt.perf.measureEnd=()=>{}),function(e){let t;e.U=pxtc.Util,e.Util=pxtc.Util;let n,i,s,r={};function a(n,i){/^csv-/.test(n)?e.setAppTargetVariant(n.replace(/^csv-*/,"")):e.appTarget&&(r[n]=i,e.U.jsonCopyFrom(e.appTarget.compile.switches,r),e.U.jsonCopyFrom(t.compile.switches,r))}function o(){let t=e.appTarget.compile;t||(t=e.appTarget.compile={isNative:!1,hasHex:!1,switches:{}}),t.hasHex&&(t.nativeType||(t.nativeType=pxtc.NATIVE_TYPE_THUMB)),t.switches||(t.switches={}),t.nativeType==pxtc.NATIVE_TYPE_VM&&(t.sourceMap=!0),e.U.jsonCopyFrom(t.switches,r),t.jsRefCounting=!1,t.useUF2||t.useELF||null!=t.noSourceInFlash||(t.noSourceInFlash=!0),void 0===t.utf8&&(t.utf8=!0),e.appTarget.appTheme||(e.appTarget.appTheme={}),e.appTarget.appTheme.embedUrl||(e.appTarget.appTheme.embedUrl=e.appTarget.appTheme.homeUrl);let n=e.appTarget.compileService;n&&n.yottaTarget&&!n.yottaBinary&&(n.yottaBinary="pxt-microbit-app-combined.hex");const i=e.appTarget.appTheme;i&&Object.keys(i).filter((e=>/(logo|hero)$/i.test(e)&&/^@cdnUrl@/.test(i[e]))).forEach((t=>i[t]=e.BrowserUtils.patchCdn(i[t])));const s=e.appTarget.simulator;if(s&&s.boardDefinition&&s.boardDefinition.visual){let t=s.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],i=JSON.parse(n[e.CONFIG_NAME]);i.icon&&(i.icon=e.BrowserUtils.patchCdn(i.icon)),n[e.CONFIG_NAME]=e.Package.stringifyConfig(i)})),"undefined"!=typeof window){const t={"lockededitor=1":{appTheme:{lockedEditor:!0}},"hidemenu=1":{appTheme:{hideMenuBar:!0}}};e.appTarget.queryVariants&&e.Util.jsonCopyFrom(t,e.appTarget.queryVariants);const n=window.location.href;Object.keys(t).forEach((i=>{if(new RegExp(i,"i").exec(n)){let n=t[i];n&&e.U.jsonMergeFrom(e.appTarget,n)}}))}}function l(n=!1){e.perf.measureStart("reloadAppTargetVariant");const i=n?"":JSON.stringify(e.appTarget);if(e.appTarget=e.U.cloneTargetBundle(t),e.appTargetVariant){const t=e.appTarget.variants&&e.appTarget.variants[e.appTargetVariant];t?e.U.jsonMergeFrom(e.appTarget,t):e.U.userError(lf("Variant '{0}' not defined in pxtarget.json",e.appTargetVariant))}o(),!n&&e.onAppTargetChanged&&i!=JSON.stringify(e.appTarget)&&e.onAppTargetChanged(),e.perf.measureEnd("reloadAppTargetVariant")}function c(){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 s||(s=e.Cloud.downloadTargetConfigAsync().then((e=>e||{}),(e=>({})))),s}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||{},o(),t=e.U.cloneTargetBundle(e.appTarget)},e.setBundledApiInfo=function(e){for(const t of Object.keys(e)){const n=e[t].apis.byQName;for(const e of Object.keys(n)){const t=n[e],i=e.lastIndexOf("."),s=t.pyQName,r=n[e]={kind:Math.abs(t.kind||7),qName:e,namespace:e.slice(0,i<0?0:i),name:e.slice(i+1),pyQName:s,pyName:s?s.slice(s.lastIndexOf(".")+1):void 0,fileName:"",attributes:t.attributes||{},retType:t.retType||"void",parameters:t.parameters?t.parameters.map((e=>({name:e.name,description:e.description||"",type:e.type||"number",initializer:e.initializer,default:e.default,options:e.options||{},isEnum:!!e.isEnum,handlerParameters:e.handlerParameters}))):null,extendsTypes:t.extendsTypes,snippet:t.kind&&t.kind<0?null:void 0,isInstance:!!t.isInstance,isReadOnly:!!t.isReadOnly},a=r.attributes;a.paramDefl||(a.paramDefl={}),a.callingConvention||(a.callingConvention=0),a.paramHelp||(a.paramHelp={}),a.jsDoc||(a.jsDoc=""),a._name=r.name.replace(/@.*/,"")}}n=e},e.getBundledApiInfo=function(){return n},e.savedAppTheme=function(){return t?t.appTheme:void 0},e.setCompileSwitch=a,e.setCompileSwitches=function(e){if(e)for(let t of e.split(/[\s,;:]+/))t&&("-"==t[0]?a(t.slice(1),!1):a(t,!0))},e.bundledSvg=function(t){if(!t)return;let n=i&&i[t];if(n)return n;if(!e.appTarget.simulator||!e.appTarget.simulator.dynamicBoardDefinition)return;i||(i={});const s=e.appTarget.bundledpkgs[t];if(!s)return;if(JSON.parse(s["pxt.json"]).core&&s["board.json"]){const n=JSON.parse(s["board.json"]);if(n&&n.visual&&n.visual.image){let r=n.visual.image;/^pkg:\/\//.test(r)&&(r=s[r.slice(6)]),i[t]=`data:image/svg+xml;base64,${ts.pxtc.encodeBase64(e.Util.toUTF8(r))}`}}return i[t]},e.reloadAppTargetVariant=l,e.setAppTargetVariant=function(t,n={}){e.debug(`app variant: ${t}`),(n.force||e.appTargetVariant!==t&&(e.appTargetVariant||t))&&(e.appTargetVariant=t,l(n.temporary))},e.setHwVariant=function(t,n){t=t.replace(/.*---/,""),/^[\w\-]+$/.test(t)?(e.hwVariant=t,e.hwName=n||t):(e.hwVariant=null,e.hwName=null),e.debug(`hwVariant: ${e.hwVariant} (${e.hwName})`)},e.hasHwVariants=function(){return!!e.appTarget.variants&&Object.keys(e.appTarget.bundledpkgs).some((e=>/^hw---/.test(e)))},e.getHwVariants=function(){return e.appTarget.variants?Object.keys(e.appTarget.bundledpkgs).filter((e=>/^hw---/.test(e))).map((t=>JSON.parse(e.appTarget.bundledpkgs[t][e.CONFIG_NAME]))).filter((t=>!!e.appTarget.appTheme.experimentalHw||!t.experimentalHw)):[]},e.options={},e.debug="undefined"!=typeof console&&console.debug?t=>{e.options.debug&&console.debug(t)}:()=>{},e.log="undefined"!=typeof console&&console.log?e=>{console.log(e)}:()=>{},e.reportException=function(e,t){if(console&&(console.error(e),t))try{console.log(t)}catch(e){}},e.reportError=function(t,n,i){if(console&&(console.error(`${t}: ${n}`),i))try{e.log(JSON.stringify(i,null,2))}catch(e){}},e.localWebConfig=c,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=c())},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 i;function s(){if(i={device_while:{name:e.Util.lf("a loop that repeats while the condition is true"),tooltip:e.Util.lf("Run the same sequence of actions while the condition is met."),url:"/blocks/loops/while",category:"loops",block:{message0:e.Util.lf("while %1"),appendField:e.Util.lf("{id:while}do")}},pxt_controls_for:{name:e.Util.lf("a loop that repeats the number of times you say"),tooltip:e.Util.lf("Have the variable '{0}' take on the values from 0 to the end number, counting by 1, and do the specified blocks."),url:"blocks/loops/for",category:"loops",block:{message0:e.Util.lf("for %1 from 0 to %2"),variable:e.Util.lf("{id:var}index"),appendField:e.Util.lf("{id:for}do")}},controls_simple_for:{name:e.Util.lf("a loop that repeats the number of times you say"),tooltip:e.Util.lf("Have the variable '{0}' take on the values from 0 to the end number, counting by 1, and do the specified blocks."),url:"blocks/loops/for",category:"loops",block:{message0:e.Util.lf("for %1 from 0 to %2"),variable:e.Util.lf("{id:var}index"),appendField:e.Util.lf("{id:for}do")}},pxt_controls_for_of:{name:e.Util.lf("a loop that repeats for each value in an array"),tooltip:e.Util.lf("Have the variable '{0}' take the value of each item in the array one by one, and do the specified blocks."),url:"blocks/loops/for-of",category:"loops",block:{message0:e.Util.lf("for element %1 of %2"),variable:e.Util.lf("{id:var}value"),appendField:e.Util.lf("{id:for_of}do")}},controls_for_of:{name:e.Util.lf("a loop that repeats for each value in an array"),tooltip:e.Util.lf("Have the variable '{0}' take the value of each item in the array one by one, and do the specified blocks."),url:"blocks/loops/for-of",category:"loops",block:{message0:e.Util.lf("for element %1 of %2"),variable:e.Util.lf("{id:var}value"),appendField:e.Util.lf("{id:for_of}do")}},math_op2:{name:e.Util.lf("minimum or maximum of 2 numbers"),tooltip:{min:e.Util.lf("smaller value of 2 numbers"),max:e.Util.lf("larger value of 2 numbers")},url:"/blocks/math",operators:{op:["min","max"]},category:"math"},math_op3:{name:e.Util.lf("absolute number"),tooltip:e.Util.lf("absolute value of a number"),url:"/reference/math",category:"math",block:{message0:e.Util.lf("absolute of %1")}},math_number:{name:e.Util.lf("{id:block}number"),url:"/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:{}}},i[pxtc.ON_START_TYPE]={name:e.Util.lf("on start event"),tooltip:e.Util.lf("Run code when the program starts"),url:"/blocks/on-start",category:"loops",block:{message0:e.Util.lf("on start %1 %2")}},i[pxtc.PAUSE_UNTIL_TYPE]={name:e.Util.lf("pause until"),tooltip:e.Util.lf("Pause execution of code until the given boolean expression is true"),url:"/blocks/pause-until",category:"loops",block:{message0:e.Util.lf("pause until %1")}},i[pxtc.TS_BREAK_TYPE]={name:e.Util.lf("break"),tooltip:e.Util.lf("Break out of the current loop or switch"),url:"/blocks/loops/break",category:"loops",block:{message0:e.Util.lf("break")}},i[pxtc.TS_CONTINUE_TYPE]={name:e.Util.lf("continue"),tooltip:e.Util.lf("Skip current iteration and continues with the next iteration in the loop"),url:"/blocks/loops/continue",category:"loops",block:{message0:e.Util.lf("continue")}},e.Util.isTranslationMode()){const t=Blockly.Msg;e.Util.values(i).filter((e=>e.block)).forEach((n=>{const i=Object.keys(n.block);n.translationIds=e.Util.values(n.block),i.forEach((i=>e.crowdin.inContextLoadAsync(n.block[i]).then((e=>{n.block[i]=e,/^[A-Z_]+$/.test(i)&&(t[i]=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 i=t.replace(/(?:^|[^\\])([%$])\s+/g,"$1");return i!=t&&(n(`block has extra spaces: ${t}`),t=i),i=(t=i).replace(/([%$]\w+)\s*=\s*(\w+)/,"$1=$2"),i!=t&&(n(`block has space between %name and = : ${t}`),t=i),i=i.replace(/\s*\|\s*/g,"|"),i},t.compileInfo=function(e){const i={parameters:[],actualNameToParam:{},definitionNameToParam:{},handlerArgs:[]},s=(1==e.kind||2==e.kind)&&!e.attributes.defaultInstance,r=!!e.attributes._def,a=r?e.attributes._def.parameters.slice(0):void 0,o=r?a.length:e.parameters?e.parameters.length:0,l=t.builtinFunctionInfo[e.qName];r&&e.attributes._expandedDef&&a.push(...e.attributes._expandedDef.parameters);const c={},u=a?a.filter((e=>!e.ref||(c[e.name]=e,!1))):[];if(s&&r&&a.length){const t=c.this||a[0],s=t.name;let r;(!t.shadowBlockId||"variables_get"===t.shadowBlockId)&&(r=t.varName||e.attributes.paramDefl[s]||e.attributes.paramDefl.this),i.thisParameter={actualName:n,definitionName:s,shadowBlockId:t.shadowBlockId,type:e.namespace,defaultValue:r,fieldEditor:d(s,n),fieldOptions:h(s,n),shadowOptions:p(s,n)}}if(e.parameters){let t=s&&!c.this?1:0;e.parameters.forEach(((e,n)=>{let s;if(c[e.name]?s=c[e.name]:t<u.length&&(s=u[t],++t),s||!r){let n;e.options&&e.options.min&&e.options.max&&(n={min:e.options.min.value,max:e.options.max.value});const r=s?s.name:l?l.params[t++]:e.name,c=s&&("variables_get"===s.shadowBlockId||"lists_create_with"==s.shadowBlockId);i.parameters.push({actualName:e.name,type:e.type,defaultValue:c&&s.varName||e.default,definitionName:r,shadowBlockId:s&&s.shadowBlockId,isOptional:!!a&&a.indexOf(s)>=o,fieldEditor:d(r,e.name),fieldOptions:h(r,e.name),shadowOptions:p(r,e.name),range:n})}e.handlerParameters&&e.handlerParameters.forEach((e=>{i.handlerArgs.push({name:e.name,type:e.type,inBlockDef:!!a&&a.some((t=>t.ref&&t.name===e.name))})}))}))}return i.parameters.forEach((e=>{i.actualNameToParam[e.actualName]=e,i.definitionNameToParam[e.definitionName]=e})),i;function d(t,n){return e.attributes.paramFieldEditor&&(e.attributes.paramFieldEditor[t]||e.attributes.paramFieldEditor[n])}function h(t,n){return e.attributes.paramFieldEditorOptions&&(e.attributes.paramFieldEditorOptions[t]||e.attributes.paramFieldEditorOptions[n])}function p(t,n){return e.attributes.paramShadowOptions&&(e.attributes.paramShadowOptions[t]||e.attributes.paramShadowOptions[n])}},t.hasHandler=function(e){return e.parameters&&e.parameters.some((e=>{var t,n;return"() => void"==e.type||"Action"==e.type||!!(null===(t=e.properties)||void 0===t?void 0:t.length)||!!(null===(n=e.handlerParameters)||void 0===n?void 0:n.length)}))},t.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 i=n[1];return i&&(i=i.trim()),{n:e,ni:t,pre:i,p:n[2]}}))},t.blockDefinitions=function(){return i||s(),i},t.getBlockDefinition=function(e){return i||s(),i[e]}}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(t){function n(){return"undefined"!=typeof navigator}function i(){return n()&&/(Win32|Win64|WOW64)/i.test(navigator.platform)}function s(){return n()&&/mobi/i.test(navigator.userAgent)}function r(){return n()&&/Mac/i.test(navigator.platform)}function a(){return!!navigator&&/Linux/i.test(navigator.platform)}function o(){return n()&&/arm/i.test(navigator.platform)}function l(){return n()&&/Edge/i.test(navigator.userAgent)}function c(){return n()&&/Trident/i.test(navigator.userAgent)}function u(){return!l()&&!c()&&!!navigator&&(/Chrome/i.test(navigator.userAgent)||/Chromium/i.test(navigator.userAgent))}function d(){return!u()&&!l()&&!!navigator&&/(Macintosh|Safari|iPod|iPhone|iPad)/i.test(navigator.userAgent)}function h(){return!d()&&!!navigator&&(/Firefox/i.test(navigator.userAgent)||/Seamonkey/i.test(navigator.userAgent))}function p(){return n()&&/Opera|OPR/i.test(navigator.userAgent)}function f(){return n()&&/Midori/i.test(navigator.userAgent)}function g(){return n()&&/Epiphany/i.test(navigator.userAgent)}function m(){return"undefined"!=typeof window&&("ontouchstart"in window||navigator&&navigator.maxTouchPoints>0)}function b(){return"undefined"!=typeof window&&!!window.pxtElectron}function y(){return"undefined"!=typeof window&&!!window.ipcRenderer}function v(){return b()||y()}function w(t){var n;try{return"undefined"!=typeof window&&/^http:\/\/(localhost|127\.0\.0\.1):\d+\//.test(window.location.href)&&(t||!/nolocalhost=1/.test(window.location.href))&&!(null===(n=null==e?void 0:e.webConfig)||void 0===n?void 0:n.isStatic)}catch(e){return!1}}function k(){return"undefined"!=typeof window&&!!window.PointerEvent}function A(){return i()?"windows":r()?"mac":a()&&o()?"rpi":a()?"linux":"unknown"}function x(){return l()?"edge":g()?"epiphany":f()?"midori":p()?"opera":c()?"ie":u()?"chrome":d()?"safari":h()?"firefox":"unknown"}function T(){if(!n())return null;let e=[];return p()&&(e=/(Opera|OPR)\/([0-9\.]+)/i.exec(navigator.userAgent)),g()?e=/Epiphany\/([0-9\.]+)/i.exec(navigator.userAgent):f()?e=/Midori\/([0-9\.]+)/i.exec(navigator.userAgent):d()?(e=/Version\/([0-9\.]+)/i.exec(navigator.userAgent),e||(e=/(Macintosh|iPod( touch)?|iPhone|iPad); (CPU|Intel).*?OS (X )?(\d+)/i.exec(navigator.userAgent))):e=u()?/(Chrome|Chromium)\/([0-9\.]+)/i.exec(navigator.userAgent):l()?/Edge\/([0-9\.]+)/i.exec(navigator.userAgent):c()?/(MSIE |rv:)([0-9\.]+)/i.exec(navigator.userAgent):/(Firefox|Seamonkey)\/([0-9\.]+)/i.exec(navigator.userAgent),e&&0!=e.length?e[e.length-1]:null}t.isIFrame=function(){try{return window&&window.self!==window.top}catch(e){return!0}},t.hasNavigator=n,t.hasWindow=function(){return"undefined"!=typeof window},t.isWindows=i,t.isWindows10=function(){return n()&&/(Win32|Win64|WOW64)/i.test(navigator.platform)&&/Windows NT 10/i.test(navigator.userAgent)},t.isMobile=s,t.isIOS=function(){return n()&&(/iPad|iPhone|iPod/.test(navigator.userAgent)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1)},t.isAndroid=function(){return n()&&/android/i.test(navigator.userAgent)},t.isMac=r,t.isLinux=a,t.isARM=o,t.isUwpEdge=function(){return"undefined"!=typeof window&&!!window.Windows},t.isEdge=l,t.isChromiumEdge=function(){return n()&&/Edg\//i.test(navigator.userAgent)},t.isIE=c,t.isChrome=u,t.isSafari=d,t.isFirefox=h,t.isOpera=p,t.isMidori=f,t.isEpiphany=g,t.isTouchEnabled=m,t.isPxtElectron=b,t.isIpcRenderer=y,t.isElectron=v,t.isWinRT=()=>!1,t.isLocalHost=w,t.isLocalHostDev=function(){return w()&&!v()},t.isSkillmapEditor=function(){try{return/skill(?:s?)Map=1/.test(window.location.href)}catch(e){return!1}},t.isTabletSize=function(){return(null===window||void 0===window?void 0:window.innerWidth)<e.BREAKPOINT_TABLET},t.isComputerSize=function(){return(null===window||void 0===window?void 0:window.innerWidth)>=e.BREAKPOINT_TABLET},t.noSharedLocalStorage=function(){try{return/nosharedlocalstorage/i.test(window.location.href)}catch(e){return!1}},t.useOldTutorialLayout=function(){try{return/tutorialview=old/.test(window.location.href)}catch(e){return!1}},t.hasPointerEvents=k,t.hasSaveAs=function(){return l()||c()||h()},t.os=A,t.browser=x,t.browserVersion=T;let E=!1;function C(){return s()&&d()&&!/downloadWindowOpen=0/i.test(window.location.href)}function I(t,n,i){const r=C(),a=T(),o=parseInt(a||"0");if(r)i?i.location.href=t:window.open(t,"_self");else if(e.BrowserUtils.isSafari()&&(o<10||0==a.indexOf("10.0")||s())){let n=document.getElementById("downloader");n||(e.debug("injecting downloader iframe"),n=document.createElement("iframe"),n.id="downloader",n.style.position="absolute",n.style.right="0",n.style.bottom="0",n.style.zIndex="-1",n.style.width="1px",n.style.height="1px",document.body.appendChild(n)),n.src=t}else if(/^data:/i.test(t)&&(e.BrowserUtils.isEdge()||e.BrowserUtils.isIE())){let i=atob(t.split(",")[1]),s=e.Util.stringToUint8Array(i),r=new Blob([s],{type:"img/png"});window.navigator.msSaveOrOpenBlob(r,n)}else{let e=window.document.createElement("a");"string"==typeof e.download?(e.href=t,e.download=n,document.body.appendChild(e),e.click(),document.body.removeChild(e)):document.location.href=t}}function U(t,n){let i="data";s()&&d()&&e.appTarget.appTheme.mobileSafariDownloadProtocol&&(i=e.appTarget.appTheme.mobileSafariDownloadProtocol);const r=/downloadProtocol=([a-z0-9:/?]+)/i.exec(window.location.href);r&&(i=r[1]);return i+":"+n+";base64,"+t}function S(t,n,i={}){var s;e.debug("trigger download");const{contentType:r="application/octet-stream",userContextWindow:a,onError:o,maintainObjectURL:l}=i,c=null===(s=window.URL)||void 0===s?void 0:s.createObjectURL,u=e.appTarget.appTheme.disableBlobObjectDownload;let d;try{if(c&&!u){const i=c(new Blob([e.Util.stringToUint8Array(atob(t))],{type:r}));I(i,n,a),l?d=i:window.setTimeout((()=>window.URL.revokeObjectURL(d)),0)}else d=U(t,n),I(d,n,a)}catch(t){o&&o(t),e.debug("saving failed")}return d}function N(e){const t=document.createElement("img");return new Promise(((n,i)=>{t.onload=()=>n(t),t.onerror=()=>n(void 0),t.crossOrigin="anonymous",t.src=e}))}t.isBrowserSupported=function(){var t,n;if(!navigator)return!0;if(/bot|crawler|spider|crawling/i.test(navigator.userAgent))return!0;const i=(null===(t=e.appTarget)||void 0===t?void 0:t.unsupportedBrowsers)||(null===(n=window.pxtTargetBundle)||void 0===n?void 0:n.unsupportedBrowsers);if(null==i?void 0:i.some((e=>e.id==x())))return!1;const s=T(),r=parseInt(s||"0"),c=u()&&r>=38,m=h()&&r>=31,b=l(),y=d()&&r>=9,v=p()&&u()&&r>=21;let w=c||m||b||y||v;const k=f()||a()&&o()&&g();return w=w&&!k,w=w||/anybrowser=(true|1)/.test(window.location.href),E||(e.log(`Browser: ${x()} ${s} on ${A()}`),w||e.tickEvent("browser.unsupported",{useragent:navigator.userAgent}),E=!0),w},t.devicePixelRatio=function(){if("undefined"==typeof window||!window.screen)return 1;const e=window.screen.systemXDPI,t=window.screen.logicalXDPI;return void 0!==e&&void 0!==t&&e>t?e/t:window&&void 0!==window.devicePixelRatio?window.devicePixelRatio:1},t.browserDownloadBinText=function(e,t,n){return S(ts.pxtc.encodeBase64(e),t,n)},t.browserDownloadText=function(t,n,i){return S(ts.pxtc.encodeBase64(e.Util.toUTF8(t)),n,i)},t.isBrowserDownloadInSameWindow=C,t.isBrowserDownloadWithinUserContext=function(){const e=T(),t=parseInt(e||"0");return s()&&d()&&t>=11||/downloadUserContext=1/i.test(window.location.href)},t.browserDownloadDataUri=I,t.browserDownloadUInt8Array=function(t,n,i){return S(ts.pxtc.encodeBase64(e.Util.uint8ArrayToString(t)),n,i)},t.toDownloadDataUri=U,t.browserDownloadBase64=S,t.loadImageAsync=N,t.loadCanvasAsync=function(e){return N(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 i=n.getContext("2d");return i.putImageData(e,0,0),i.imageSmoothingEnabled=!1,i.scale(t,t),i.drawImage(n,0,0),i.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 i=n.getContext("2d");return i.putImageData(e,0,0),i.imageSmoothingEnabled=!1,i.scale(t,t),i.drawImage(n,0,0),n.toDataURL("image/png")};const P=1e6;function _(t){if(/^https?:\/\//i.test(t))return t;const n=(window.MonacoPaths||{})[t];return n||(e.U.startsWith(t,e.webConfig.commitCdnUrl)?t:e.webConfig.commitCdnUrl+t)}t.encodeToPngAsync=function(t,n){const{width:i,height:s,pixelDensity:r=4,maxSize:a=P,text:o}=n||{};return new Promise(((n,l)=>{const c=new Image;c.onload=function(){const t=document.createElement("canvas"),l=t.getContext("2d");t.width=(i||c.width)*r,t.height=(s||c.height)*r,o&&(l.fillStyle="#fff",l.fillRect(0,0,t.width,t.height)),l.drawImage(c,0,0,i,s,0,0,t.width,t.height);let u=t.toDataURL("image/png");for(;u.length>a;)t.width=t.width/2>>0,t.height=t.height/2>>0,e.debug(`screenshot size ${u.length}b, shrinking to ${t.width}x${t.height}`),l.drawImage(c,0,0,i,s,0,0,t.width,t.height),u=t.toDataURL("image/png");if(o){e.lzmaCompressAsync(o).then((i=>{const s=e.Util.encodeBlobAsync(t,i);n(s.toDataURL("image/png"))}))}else n(u)},c.onerror=t=>{e.reportError("png","png rendering failed"),n(void 0)},c.src=t}))},t.resolveCdnUrl=_,t.loadStyleAsync=function(t,n){n&&(t="rtl"+t);const i="style-"+t;if(document.getElementById(i))return Promise.resolve();const s=_(t),r=e.Util.toArray(document.head.getElementsByTagName("link")).filter((e=>e.getAttribute("href")==s))[0];return r?(r.id||(r.id=i),Promise.resolve()):new Promise(((e,t)=>{const n=document.createElement("link");n.href=s,n.rel="stylesheet",n.type="text/css",n.id=i,n.addEventListener("load",(()=>e())),n.addEventListener("error",(e=>t(e))),document.head.appendChild(n)}))};let O,D,$,L={};function R(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 M(){const e=n()&&window.navigator;return e&&e.storage&&e.storage.estimate?e.storage.estimate():Promise.resolve({})}t.loadScriptAsync=function(t){const n=_(t);let i=L[n];return i||(i=L[n]=new Promise(((t,i)=>{e.debug(`script: loading ${n}`);const s=document.createElement("script");s.type="text/javascript",s.addEventListener("load",(()=>t())),s.addEventListener("error",(e=>{delete L[n],i(e)})),s.src=n,s.async=!0,document.body.appendChild(s)}))),i},t.loadAjaxAsync=function(e){return new Promise(((t,n)=>{let i=new XMLHttpRequest;i.onreadystatechange=function(){i.readyState==XMLHttpRequest.DONE&&(200==i.status?t(i.responseText):n(i.status))},i.open("GET",e,!0),i.send()}))},t.loadBlocklyAsync=function(){if(!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 i=t.filter((t=>e.Util.endsWith(t.getAttribute("href"),"blockly.css")))[0];if(i){const t=i.getAttribute("data-rtl");t&&(e.debug(`swapping to ${t}`),i.setAttribute("href",t),i.removeAttribute("data-rtl"))}}},t.changeHash=function(e,t){"#"!=e.charAt(0)&&(e="#"+e),t?window.location.hash=e:window.history.replaceState("","",e)},t.urlJoin=R,t.joinURLs=function(...e){let t;if(e)for(let n=0;n<e.length;n++)t=R(t,e[n]);return t},t.storageEstimateAsync=M,t.scheduleStorageCleanup=n()&&navigator.storage&&navigator.storage.estimate?ts.pxtc.Util.throttle((function(){M().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"),G()):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((()=>H())).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 j{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,i,s,r,a){this.translations[this.key(e,t,n)]={etag:i,time:s,strings:r,md:a}}setAsync(t,n,i,s,r,a){return this.set(t,n,i,s,e.Util.now(),r),Promise.resolve()}clearAsync(){return this.translations={},Promise.resolve()}}class F{constructor(e,t,n,i){this.name=e,this.version=t,this.upgradeHandler=n,this.quotaExceededHandler=i}throwIfNotOpened(){if(!this._db)throw new Error("Database not opened; call IDBWrapper.openAsync() first")}errorHandler(t,n,i){console.error(new Error(`${this.name} IDBWrapper error for ${n}: ${t.message}`)),i(t),"QuotaExceededError"==t.name&&(e.log("storage quota exceeded..."),e.tickEvent("storage.quotaexceedederror"),this.quotaExceededHandler&&this.quotaExceededHandler())}getObjectStore(e,t="readonly"){this.throwIfNotOpened();return this._db.transaction([e],t).objectStore(e)}static deleteDatabaseAsync(e){return new Promise(((t,n)=>{const i=(window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB).deleteDatabase(e);i.onsuccess=()=>t(),i.onerror=()=>n(i.error)}))}openAsync(){return new Promise(((e,t)=>{const n=(window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB).open(this.name,this.version);n.onsuccess=()=>{this._db=n.result,e()},n.onerror=()=>this.errorHandler(n.error,"open",t),n.onupgradeneeded=e=>this.upgradeHandler(e,n)}))}getAsync(e,t){return new Promise(((n,i)=>{const s=this.getObjectStore(e).get(t);s.onsuccess=()=>n(s.result),s.onerror=()=>this.errorHandler(s.error,"get",i)}))}getAllAsync(e){return new Promise(((t,n)=>{const i=this.getObjectStore(e).openCursor(),s=[];i.onsuccess=()=>{i.result?(s.push(i.result.value),i.result.continue()):t(s)},i.onerror=()=>this.errorHandler(i.error,"getAll",n)}))}setAsync(e,t){return new Promise(((n,i)=>{const s=this.getObjectStore(e,"readwrite");let r;r=void 0!==t.id&&null!==t.id?s.put(t):s.add(t),r.onsuccess=()=>n(),r.onerror=()=>this.errorHandler(r.error,"set",i)}))}deleteAsync(e,t){return new Promise(((n,i)=>{const s=this.getObjectStore(e,"readwrite").delete(t);s.onsuccess=()=>n(),s.onerror=()=>this.errorHandler(s.error,"delete",i)}))}deleteAllAsync(e){return new Promise(((t,n)=>{const i=this.getObjectStore(e,"readwrite").clear();i.onsuccess=()=>t(),i.onerror=()=>this.errorHandler(i.error,"deleteAll",n)}))}}t.IDBWrapper=F;class B{constructor(e){this.db=e,this.mem=new j}static dbName(){return`__pxt_translations_${e.appTarget.id||""}`}static createAsync(){function e(){const e=new F(B.dbName(),2,((e,t)=>{t.result.createObjectStore(B.TABLE,{keyPath:B.KEYPATH})}),(()=>{G().catch((e=>{}))}));return e.openAsync().then((()=>new B(e)))}return e().catch((t=>(console.log("db: failed to open database, try delete entire store..."),F.deleteDatabaseAsync(B.dbName()).then((()=>e())))))}getAsync(e,t,n){e=(e||"en-US").toLowerCase();const i=this.mem.key(e,t,n),s=this.mem.get(e,t,n);return s?Promise.resolve(s):this.db.getAsync(B.TABLE,i).then((i=>i?(this.mem.set(e,t,n,i.etag,i.time,i.strings),Promise.resolve(i)):Promise.resolve(void 0))).catch((e=>Promise.resolve(void 0)))}setAsync(n,i,s,r,a,o){n=(n||"en-US").toLowerCase();const l=this.mem.key(n,i,s);let c=e.Util.now();this.mem.set(n,i,s,r,c,a,o),a&&Object.keys(a).filter((e=>!a[e])).forEach((e=>delete a[e]));const u={id:l,etag:r,time:c,strings:a,md:o};return this.db.setAsync(B.TABLE,u).finally((()=>t.scheduleStorageCleanup())).catch((e=>(console.log(`db: set failed (${e.message}), recycling...`),this.clearAsync())))}clearAsync(){return this.db.deleteAllAsync(B.TABLE).then((()=>console.debug("db: all clean"))).catch((e=>{console.error("db: failed to delete all")}))}}function H(){return e.Util.isNodeJS?Promise.resolve(new j):(D||(D=B.createAsync().catch((()=>new j))),D)}function G(){function t(){const t=B.dbName();return F.deleteDatabaseAsync(t).then((()=>{D=void 0})).catch((n=>{e.log(`db: failed to delete ${t}`),D=void 0}))}return D?D.then((e=>e.clearAsync())).catch((e=>t().then())):t()}function z(t){const n=JSON.stringify(t)+e.appTarget.versions.pxt+"_"+e.appTarget.versions.target;return pxtc.U.sha256(n)}function V(e,t){return`${e}|${t||"master"}`}B.TABLE="files",B.KEYPATH="id",t.translationDbAsync=H,t.clearTranslationDbAsync=G,t.getTutorialCodeHash=z;class J{constructor(e){this.db=e}static dbName(){return`__pxt_tutorialinfo_${e.appTarget.id||""}`}static createAsync(){function t(){const t=new e.BrowserUtils.IDBWrapper(J.dbName(),2,((e,t)=>{t.result.createObjectStore(J.TABLE,{keyPath:J.KEYPATH})}),(()=>{e.BrowserUtils.IDBWrapper.deleteDatabaseAsync(J.dbName())}));return t.openAsync().then((()=>new J(t)))}return t().catch((n=>(console.log("db: failed to open tutorial info database, try delete entire store..."),e.BrowserUtils.IDBWrapper.deleteDatabaseAsync(J.dbName()).then((()=>t())))))}getAsync(t,n,i){const s=V(t,i),r=z(n);return this.db.getAsync(J.TABLE,s).then((t=>{if(t&&t.hash==r&&e.Util.now()-(t.time||0)<864e5)return t;this.db.deleteAsync(J.TABLE,s)}))}setAsync(t,n,i,s){e.perf.measureStart("tutorial info db setAsync");V(t,s);const r=z(i);return this.setWithHashAsync(t,n,r)}setWithHashAsync(t,n,i,s){e.perf.measureStart("tutorial info db setAsync");const r=V(t,s),a={};Object.keys(n).forEach((e=>{Object.keys(n[e]).forEach((t=>{a[t]=n[e][t]}))}));const o={id:r,time:e.Util.now(),hash:i,snippets:n,blocks:a};return this.db.setAsync(J.TABLE,o).then((()=>{e.perf.measureEnd("tutorial info db setAsync")}))}clearAsync(){return this.db.deleteAllAsync(J.TABLE).then((()=>console.debug("db: all clean"))).catch((e=>{console.error("db: failed to delete all")}))}}function q(e){return e.split(/\s+/).filter((e=>!!e))}function W(){const t=new RegExp(`${e.Util.escapeForRegex(e.Util.pxtLangCookieId)}=(.*?)(?:;|$)`).exec(document.cookie);return t&&t[1]||null}J.TABLE="info",J.KEYPATH="id",t.tutorialInfoDbAsync=function(){return $||($=J.createAsync()),$},t.clearTutorialInfoDbAsync=function(){function t(){const t=J.dbName();return F.deleteDatabaseAsync(t).then((()=>{$=void 0})).catch((n=>{e.log(`db: failed to delete ${t}`),$=void 0}))}return $?$.then((e=>e.clearAsync())).catch((e=>t().then())):t()},t.pointerEvents=k()?{up:"pointerup",down:["pointerdown"],move:"pointermove",enter:"pointerenter",leave:"pointerleave"}:m()?{up:"mouseup",down:["mousedown","touchstart"],move:"touchmove",enter:"touchenter",leave:"touchend"}:{up:"mouseup",down:["mousedown"],move:"mousemove",enter:"mouseenter",leave:"mouseleave"},t.getPageX=function(e){return"pageX"in e?e.pageX:e.changedTouches[0].pageX},t.getPageY=function(e){return"pageY"in e?e.pageY:e.changedTouches[0].pageY},t.getClientX=function(e){return"clientX"in e?e.clientX:e.changedTouches[0].clientX},t.getClientY=function(e){return"clientY"in e?e.clientY:e.changedTouches[0].clientY},t.popupWindow=function(t,n,i,s){try{const e=window.screenLeft?window.screenLeft:window.screenX,r=window.screenTop?window.screenTop:window.screenY,a=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth,o=window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight,l=a/2-i/2+e,c=o/2-s/2+r,u=window.open(t,n,"width="+i+", height="+s+", top="+c+", left="+l);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 q(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){q(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){q(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=W,t.setCookieLang=function(t,n=!1){if(e.Util.allLanguages[t]&&t!==W()){e.tickEvent("menu.lang.setcookielang",{lang:t,docs:`${n}`});const i=new Date;i.setTime(i.getTime()+24*e.Util.langCookieExpirationDays*60*60*1e3),document.cookie=`${e.Util.pxtLangCookieId}=${t}; expires=${i.toUTCString()}; path=/`}},t.cacheBustingUrl=function(e){return e?/[?&]rnd=/.test(e)?e:`${e}${e.indexOf("?")>0?"&":"?"}rnd=${Math.random()}`:e}}(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(((i,s)=>{try{t.decompress(n,((t,n)=>{n&&e.debug("lzma decompression failed"),i(n?void 0:t)}))}catch(t){t&&e.debug("lzma decompression failed"),i(void 0)}}))))},e.lzmaCompressAsync=function(n){return t().then((t=>new Promise(((i,s)=>{try{t.compress(n,7,((t,n)=>{n&&e.reportException(n),i(n?void 0:new Uint8Array(t))}))}catch(t){e.reportException(t),i(void 0)}}))))}}(pxt||(pxt={})),function(e){!function(t){var n=pxtc.Util;let i=n.lf;const s={"pxt::mkAction":1,"pxt::dumpPerfCounters":1,"pxt::deepSleep":1,"pxt::getConfig":1,"pxtrt::mkMap":1,"pxtrt::mapSet":1,"pxtrt::stclo":1,"pxtrt::mklocRef":1,"pxtrt::stlocRef":1,"pxtrt::ldlocRef":1,"pxtrt::panic":1};function r(e="namespace"){let t="",n="",i=(i,s="")=>{n!=i&&(n&&(t+="}\n"),i&&(t+=s||e+" "+i+" {\n"),n=i)},s=" ";return{setNs:i,clear:()=>{t="",n=""},write:e=>{e.trim()?(e=e.trim().replace(/^\s*/gm,s).replace(/^(\s*)\*/gm,((e,t)=>t+" *")),t+=e+"\n"):t+="\n"},incrIndent:()=>{s+=" "},decrIndent:()=>{s=s.slice(4)},finish:()=>(i(""),t)}}function a(e){if(!e)return null;e=e.trim();let t=/^\((.*)\)/.exec(e);return t&&(e=t[1]),/^-?(\d+|0[xX][0-9a-fA-F]+)$/.test(e)?parseInt(e):null}t.nsWriter=r,t.parseCppInt=a;let o={};class l extends Error{constructor(e){super(e),this.isUserError=!0,this.message=e}}function c(e){if(!e)return"";let t="";for(let n=0;n<e.length;++n){let i=255&e[n];t+=37==i||i>127?"%"+i.toString(16):String.fromCharCode(i)}return decodeURIComponent(t)}function u(t){let n="",i=0;for(;i<t.length;i+=2)n=t[i]+t[i+1]+n;return e.Util.assert(i==t.length),n}function d(e){let t=[65,20,14,47,184,47,162,187];e:for(let n=0;n<e.length;n+=16){if(e[n]!=t[0])continue;for(let i=0;i<t.length;++i)if(e[n+i]!=t[i])continue e;let i=e[n+8]|e[n+9]<<8,s=e[n+10]|e[n+11]<<8|e[n+12]<<16|e[n+13]<<24;n+=16;let r=n+i+s;if(r>e.length)continue;let a=e.slice(n,n+i),o=e.slice(n+i,r);return{meta:c(a),text:o}}return null}function h(t){function n(t){return e.debug(t),Promise.reject(new Error(t))}let i;if(e.HF2.read32(t,0)==ts.pxtc.UF2.UF2_MAGIC_START0){let e=ts.pxtc.UF2.toBin(t);e&&(i=d(e.buf))}if(1179403647==e.HF2.read32(t,0)&&(i=d(t)),58==t[0]){i=function(e){if(!e)return;let t,n=0,i=0,s=0,r=0;if(e.split(/\r?\n/).forEach((e=>{let a=/^:10....0[0E]41140E2FB82FA2BB(....)(....)(....)(....)(..)/.exec(e);if(a)n=parseInt(u(a[1]),16),i=parseInt(u(a[2]),16),s=n+i,t=new Uint8Array(s);else if(s>0){if(a=/^:10....0[0E](.*)(..)$/.exec(e),!a)return;let n=a[1];for(;s>0&&n.length>0;)t[r++]=parseInt(n[0]+n[1],16),n=n.slice(2),s--}})),!t||0!=s||r!=t.length)return;let a=new Uint8Array(n),o=new Uint8Array(i);for(let e=0;e<n;++e)a[e]=t[e];for(let e=0;e<i;++e)o[e]=t[n+e];return{meta:c(a),text:o}}(c(t)||"")}if(!i||!i.meta||!i.text)return n("This .hex file doesn't contain source.");let s=JSON.parse(i.meta);return s?"LZMA"==s.compression?e.lzmaDecompressAsync(i.text).then((t=>{if(!t)return null;let n=t.slice(0,s.headerSize||s.metaSize||0),i=t.slice(n.length);return n&&e.Util.jsonCopyFrom(s,JSON.parse(n)),{meta:s,source:i}})):s.compression?n(`Compression type ${s.compression} not supported.`):Promise.resolve({source:c(i.text)}):n("This .hex file is not valid.")}t.PkgConflictError=l,t.getExtensionInfo=function(t){const c={__appVariant:e.appTargetVariant||""},u="dal.d.ts";let d="/source/",h="",p=[];const f=t.sortedDeps(!0).sort(((e,t)=>"this"==e.id?1:"this"==t.id?-1:n.strcmp(e.id,t.id)));for(let t of f)t.disablesVariant(e.appTargetVariant)||t.resolvedDependencies().some((t=>t.disablesVariant(e.appTargetVariant)))?(h&&(h+=", "),h+=t.id,e.debug(`disable variant ${e.appTargetVariant} due to ${t.id}`)):(p.push(t),t.addSnapshot(c,[u,".h",".cpp"]));const g=JSON.stringify(c),m=o[g];if(m){e.debug("Using cached extinfo");const t=n.flatClone(m);return t.disabledDeps=h,t}e.debug("Generating new extinfo");const b=pxtc.emptyExtInfo();b.disabledDeps=h;let y=e.appTarget.compileService;y||(y={gittag:"none",serviceId:"nocompile"}),y=n.clone(y);let v=t.getTargetOptions();v||(v={isNative:!1,hasHex:!1,switches:{}});const w=!!y.platformioIni,k="codal"==y.buildEngine||"dockercodal"==y.buildEngine,A="dockermake"==y.buildEngine||"dockercross"==y.buildEngine,x="dockerespidf"==y.buildEngine,T=!(w||k||A||x),E=v.nativeType==pxtc.NATIVE_TYPE_VM;w?d="/src/":k||A?d="/pxtapp/":x&&(d="/main/");let C="// Configuration defines\n",I="\nPXT_SHIMS_BEGIN\n",U="",S="",N='#include "pxt.h"\n',P="",_=e=>P+=` ${D}(${O}): ${e}\n`,O=0,D="",$=r("namespace"),L=r("declare namespace"),R=r("declare namespace"),M="",j={},F={};const B={true:"1",false:"0",null:"0",NULL:"0"};function H(e){return e.trim().replace(/[\_\*]$/,"")}for(const t of p){if(t.getFiles().indexOf(u)>=0){const n=t.host().readFile(t,u);e.Util.assert(!!n,`dal.d.ts not found in ${t.id}`),n.split(/\r?\n/).forEach((e=>{let t=/^\s*(\w+) = (.*),/.exec(e);t&&(B[t[1]]=t[2])}))}for(const e of t.getFiles())(["Makefile","sdkconfig.defaults","CMakeLists.txt"].indexOf(e)>=0||n.endsWith(e,".mk"))&&(b.generatedFiles["/"+e]=t.host().readFile(t,e))}let G=["0","false","PXT_UTF8"],z={};function V(e){return e.replace(/\/\/.*/,"").replace(/\/\*/,"")}v.switches.boxDebug&&(z.PXT_BOX_DEBUG=1),v.utf8&&(z.PXT_UTF8=1),v.switches.profile&&(z.PXT_PROFILE=1),v.switches.gcDebug&&(z.PXT_GC_DEBUG=1),v.switches.numFloat&&(z.PXT_USE_FLOAT=1),v.nativeType==pxtc.NATIVE_TYPE_VM&&(z.PXT_VM=1);let J=0,q=!1,W="",Y="",K="",X=!1;function Q(){L.setNs(""),L.write(""),L.write(""),(K||Y)&&(L.write(Y),L.write(K),K="",Y="")}function Z(e,t){let r;W="",Y="",K="",X=!1;let o=-1;function l(){let e=W.replace(/Methods$/,"");return e==W?null:e}function c(e){switch(e.replace(/\s+/g,"")){case"void":return"void";case"int32_t":case"int":return"int32";case"uint32_t":case"unsigned":return"uint32";case"TNumber":case"float":case"double":return"number";case"uint16_t":return"uint16";case"int16_t":case"short":return"int16";case"uint8_t":case"byte":return"uint8";case"int8_t":case"sbyte":return"int8";case"bool":return v.shortPointers&&_("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 H(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(j,e)?"I":"_"+e.replace(/[\*_]+$/,"")}}e=e.replace(/^(\s*#\s*if\s+(\w+)\s*$)([^]*?)(^\s*#\s*(elif|else|endif)\s*$)/gm,((e,t,n,i,s)=>G.indexOf(n)>=0&&!z[n]?t+i.replace(/[^\n]/g,"")+s:e)),O=0,q=!1,J=0,R.setNs(""),L.setNs(""),e.split(/\r?\n/).forEach((e=>{++O;let d=V(e);!function(e){let t=V(e);if(q&&t.indexOf("}")>=0&&(q=!1,R.write("}")),!q)return;let i=/^\s*(\w+)\s*(=\s*(.*?))?,?\s*$/.exec(t);if(i){let e=i[1],s=i[3],r="";if(s){s=s.trim();let e=n.lookup(B,s);null!=e&&(r=" // "+s,s=e),J=a(s),null==J&&_("cannot determine value of "+t)}else J++,s=J+"";R.write(` ${H(e)} = ${s},${r}`)}else R.write(e)}(e);let h=/^\s*enum\s+(|class\s+|struct\s+)(\w+)\s*({|$)/.exec(d);var p,f;if(h&&(p=h[2],f=h[3],q=!0,J=-1,R.write(""),R.write(""),(K||Y)&&(R.write(Y),R.write(K),K="",Y=""),R.write(`declare const enum ${H(p)} ${f}`),j[p]=!0,t||($.setNs(W),$.write(`enum ${h[2]} : int;`))),function(e){return!(!q&&(/^\s*\/\*\*/.test(e)?(X=!0,Y=e+"\n",/\*\//.test(e)&&(X=!1),0):X?(Y+=e+"\n",/\*\//.test(e)&&(X=!1),0):!/^\s*\/\/%/.test(e)||(K+=e+"\n",0)))}(e))return;/^typedef.*;\s*$/.test(e)&&($.setNs(W),$.write(e));let g=/^\s*namespace\s+(\w+)/.exec(e);if(g)if(W=g[1],l()){Q();let e=l();L.setNs(W,`declare interface ${e} {`)}else(K||Y)&&(Q(),L.setNs(H(W)),R.setNs(H(W)));else{if(g=/^PXT_ABI\((\w+)\)/.exec(e),g&&!E&&(I+=`PXT_FNPTR(::${g[1]}),\n`,S+=`extern "C" void ${g[1]}();\n`,b.functions.push({name:g[1],argsFmt:[],value:0})),g=/^\s*PXT_EXPORT\(([:\&\w]+)\)/.exec(e),g&&(b.vmPointers||(b.vmPointers=[]),b.vmPointers.push(g[1])),g=/^#define\s+PXT_COMM_BASE\s+([0-9a-fx]+)/.exec(e),g&&(b.commBase=parseInt(g[1])),g=/^\s*(\w+)([\*\&]*\s+[\*\&]*)(\w+)\s*\(([^\(\)]*)\)\s*(;\s*$|\{|$)/.exec(e),!K||!g){if(g=/^\s*extern const (\w+) (\w+);/.exec(e),K&&g){let e={name:W+"::"+g[2],argsFmt:[],value:null};return b.functions.push(e),E||(I+="PXT_FNPTR(&::"+e.name+"),\n"),void(K="")}if(g=/^\s*(\w+)\s+(\w+)\s*;/.exec(e),K&&g){let e=pxtc.parseCommentString(K);e.indexedInstanceNS&&(r=e,L.setNs(e.indexedInstanceNS),o=0);let t=g[1],n=g[2];if(r)return K=K.trim(),K+=` fixedInstance shim=${r.indexedInstanceShim}(${o++})`,L.write(""),L.write(Y),L.write(K),L.write(`const ${n}: ${c(t)};`),Y="",void(K="")}return K&&e.trim()?(_("declaration not understood: "+e),K="",void(Y="")):void 0}{r=null;let e=pxtc.parseCommentString(K);W||_("missing namespace declaration");let o=(g[1]+g[2]).replace(/\s+/g,""),d=g[3],h=g[4];K=K.trim().replace(/ \w+\.defl=\w+/g,"");let p=[u(o)],f=[],m=h.split(/,/).filter((e=>!!e)).map((t=>{let i=function(e,t){t=t.trim();let i=/(.*)=\s*(-?\w+)$/.exec(t),s="",r="";if(i&&(s=i[2],r="?",t=i[1].trim()),i=/^(.*?)(\w+)$/.exec(t),!i)return _("invalid argument: "+t),{name:"???",type:"int"};let o=i[2];e.paramDefl[o]&&(s=e.paramDefl[o],r="?");let l=s?n.lookup(B,s):null;return null!=l&&(s=l),s&&(null==a(s)&&_("Invalid default value (non-integer): "+s),K+=` ${o}.defl=${s}`),{name:o+r,type:i[1]}}(e,t);return p.push(u(i.type)),f.push(i.type.replace(/ /g,"")),`${i.name}: ${c(i.type)}`})),y={name:W+"::"+d,argsFmt:p,value:null};if(Y)if(L.setNs(H(W)),L.write(""),L.write(Y),/ImageLiteral/.test(g[4])&&!/imageLiteral=/.test(K)&&(K+=" imageLiteral=1"),K+=` shim=${y.name}`,L.write(K),d=H(d),l()){let e=(m[0]||"").replace(/^.*:\s*/,"").trim();e.toLowerCase()!=l().toLowerCase()&&_(i("Invalid first argument; should be of type '{0}', but is '{1}'",l(),e)),m.shift(),0==m.length&&/\bproperty\b/.test(K)?L.write(`${d}: ${c(o)};`):L.write(`${d}(${m.join(", ")}): ${c(o)};`)}else L.write(`function ${d}(${m.join(", ")}): ${c(o)};`);if(Y="",K="",t||($.setNs(W),$.write(`${o} ${d}(${h});`)),b.functions.push(y),T)I+="(uint32_t)(void*)::"+y.name+",\n";else if(E){if(n.startsWith(y.name,"pxt::op_")||s[y.name]||e.expose||!n.startsWith(y.name,"pxt::")&&!n.startsWith(y.name,"pxtrt::")){const e=function(e,t){if("FiberContext*"==t[0])return"::"+e.name;let n="_wrp_"+e.name.replace(/:/g,"_");if(F[e.name])return n;F[e.name]=!0,U+=`\nvoid ${n}(FiberContext *ctx) {\n`;const i=t.length;let s=[],r=!1,a="";for(let n=0;n<i;++n){const o=e.argsFmt[n+1],l=t[n];let c="I"==o?"toInt":"B"==o?"numops::toBool":"";const u=n==i-1?"ctx->r0":`ctx->sp[${i-n-2}]`;let d="";switch(l){case"TValue":case"TNumber":break;case"Action":c="asRefAction";break;case"String":c="convertToString",d="ctx, ",r=!0;break;default:c||(c="as"+l.replace(/\*/g,""))}a+=` ${l} a${n} = (${l}) ${c}(${d}${u});\n`,s.push("a"+n)}r&&(U+=" auto prevSP = ctx->sp;\n"),U+=a,r&&(U+=" if (panicCode) { ctx->sp = prevSP; return; }\n");const o=`::${e.name}(${s.join(", ")})`;return"V"==e.argsFmt[0]?(U+=` ${o};\n`,U+=" ctx->r0 = NULL;\n"):"I"==e.argsFmt[0]?U+=` ctx->r0 = fromInt(${o});\n`:"B"==e.argsFmt[0]?U+=` ctx->r0 = fromBool(${o});\n`:U+=` ctx->r0 = (TValue)${o};\n`,r&&(U+=" ctx->sp = prevSP;\n"),i>1&&(U+=` ctx->sp += ${i-1};\n`),U+="}\n",n}(y,f),t=y.argsFmt.length-1;I+=`{ "${y.name}", (OpFun)(void*)${e}, ${t} },\n`}}else I+="PXT_FNPTR(::"+y.name+"),\n"}}}))}const ee=n.clone(y.yottaConfig||{}),te={},ne={},ie={};function se(t){const s=t.config.platformio;s&&s.dependencies&&n.jsonCopyFrom(b.platformio.dependencies,s.dependencies),b.npmDependencies&&t.config.npmDependencies&&n.jsonCopyFrom(b.npmDependencies,t.config.npmDependencies);const r=t.config.codal;if(k&&r)for(const t of r.libraries||[]){const s=e.github.parseRepoId(t);s||n.userError(i("codal library {0} doesn't look like github repo",t));const r=e.github.stringifyRepo(s),a=n.lookup(ie,s.project);a?e.github.stringifyRepo(a)!=r&&n.userError(i("conflict between codal libraries: {0} and {1}",e.github.stringifyRepo(a),r)):ie[s.project]=s}const a=t.config.yotta;if(a){if(a.dependencies&&n.jsonCopyFrom(b.yotta.dependencies,a.dependencies),a.config){const e=n.jsonFlatten(a.config);for(const s of Object.keys(e)){const r=n.lookup(ne,s),a=e[s];if(!r||r.config.yotta.configIsJustDefaults)ne[s]=t,ee[s]=a;else if(ee[s]===a);else if(!t.parent.config.yotta||!t.parent.config.yotta.ignoreConflicts){let e=new l(i("conflict on yotta setting {0} between extensions {1} and {2}",s,t.id,r.id));throw e.pkg0=r,e.pkg1=t,e.settingName=s,e}}}if(a.optionalConfig){const e=n.jsonFlatten(a.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;b.yotta.dependencies[e.yottaCorePackage]=t}if(t){let e=!1;for(let s of p){P="",se(s),s==t?(e=!0,L.clear(),R.clear()):n.assert(!e);const r=e=>n.endsWith(e,".h"),a=".cpp",o=s.getFiles().filter(r).concat(s.getFiles().filter((e=>!r(e))));for(let e of o){const t=r(e);if(t||n.endsWith(e,a)){let r=s.config.name+"/"+e;("base"==s.config.name||/^core($|---)/.test(s.config.name))&&t&&(r=e),t&&(N+=`#include "${T?d.slice(1):""}${r}"\n`);let a=s.readFile(e);null==a&&n.userError(i("C++ file {0} is missing in extension {1}.",e,s.config.name)),D=r,Z(a,t),b.extensionFiles[d+r]=a,0==s.level&&(b.onlyPublic=!1),s.verProtocol()&&"pub"!=s.verProtocol()&&"embed"!=s.verProtocol()&&(b.onlyPublic=!1)}if(n.endsWith(e,".c")||n.endsWith(e,".S")||n.endsWith(e,".s")){let t=s.readFile(e);b.extensionFiles[d+s.config.name+"/"+e.replace(/\.S$/,".s")]=t}}P&&(M+=i("Extension {0}:\n",s.id)+P)}e||(L.clear(),R.clear())}function re(e){return Object.keys(b.extensionFiles).concat(Object.keys(b.generatedFiles)).filter((t=>n.endsWith(t,e))).map((e=>e.slice(1)))}M&&n.userError(M),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 ae=n.jsonUnFlatten(te);if(A){let e={name:"pxt-app",private:!0,dependencies:b.npmDependencies};b.generatedFiles["/package.json"]=JSON.stringify(e,null,4)+"\n"}else if(x){const e=n.concatArrayLike([re(".c"),re(".cpp"),re(".s")]).map((e=>e.slice(d.length-1))).concat(["main.cpp"]);e.push("pointers.cpp"),b.generatedFiles[d+"CMakeLists.txt"]="idf_component_register(\n SRCS\n"+e.map((e=>` "${e}"\n`)).join("")+' INCLUDE_DIRS\n "."\n)\n'}else if(k){let t=y,i=n.clone(t.codalDefinitions)||{},s=t.codalTarget;"string"==typeof s&&(s+=".json");let r={target:s,definitions:i,config:i,application:"pxtapp",output_folder:"build",pxt_gitrepo:t.githubCorePackage,pxt_gittag:t.gittag,libraries:n.values(ie).map((e=>({name:e.project,url:"https://github.com/"+e.fullName,branch:e.tag||"master",type:"git"})))};0==r.libraries.length&&delete r.libraries,n.iterMap(n.jsonFlatten(ae),((e,t)=>{e=e.replace(/^codal\./,"device.").toUpperCase().replace(/\./g,"_"),i[e]=t})),b.generatedFiles["/codal.json"]=JSON.stringify(r,null,4)+"\n",e.debug(`codal.json: ${b.generatedFiles["/codal.json"]}`)}else if(w){const e=y.platformioIni.slice();e.push("lib_deps ="),n.iterMap(b.platformio.dependencies,((t,n)=>{let i=/[@#\/]/.test(n)?n:t+"@"+n;e.push(" "+i)})),b.generatedFiles["/platformio.ini"]=e.join("\n")+"\n"}else{b.yotta.config=ae;let t="pxt-app";y.yottaBinary&&(t=y.yottaBinary.replace(/-combined/,"").replace(/\.hex$/,""));let n={name:t,version:"0.0.0",description:"Auto-generated. Do not edit.",license:"n/a",dependencies:b.yotta.dependencies,targetDependencies:{},bin:"./source"};b.generatedFiles["/module.json"]=JSON.stringify(n,null,4)+"\n",e.debug(`module.json: ${b.generatedFiles["/module.json"]}`)}for(let e of Object.keys(z))C+=`#define ${e} ${z[e]}\n`;if(v.uf2Family&&(C+=`#define PXT_UF2_FAMILY ${v.uf2Family}\n`),b.generatedFiles[d+"pointers.cpp"]=N+$.finish()+S+U+I+"\nPXT_SHIMS_END\n",b.generatedFiles[d+"pxtconfig.h"]=C,e.debug(`pxtconfig.h: ${b.generatedFiles[d+"pxtconfig.h"]}`),T&&(b.generatedFiles["/config.json"]=JSON.stringify(ae,null,4)+"\n",e.debug(`yotta config.json: ${b.generatedFiles["/config.json"]}`)),b.generatedFiles[d+"main.cpp"]='\n#include "pxt.h"\n#ifdef PXT_MAIN\nPXT_MAIN\n#else\nint main() {\n uBit.init();\n pxt::start();\n release_fiber();\n return 0; // your program will never reach this line.\n}\n#endif\n',b.generatedFiles["/Makefile"]){let e="",t=(t,n)=>{e+=`${t} = ${re(n).join(" ")}\n`};t("PXT_C",".c"),t("PXT_CPP",".cpp"),t("PXT_S",".s"),t("PXT_HEADERS",".h"),e+="PXT_SOURCES := $(PXT_C) $(PXT_S) $(PXT_CPP)\n",e+="PXT_OBJS := $(addprefix bld/, $(PXT_C:.c=.o) $(PXT_S:.s=.o) $(PXT_CPP:.cpp=.o))\n",b.generatedFiles["/Makefile.inc"]=e}b.generatedFiles["/functions.json"]=JSON.stringify(b.functions,null,1);let oe=b.extensionFiles;n.jsonCopyFrom(oe,b.generatedFiles);let le={config:y.serviceId,tag:y.gittag,replaceFiles:oe,dependencies:T?b.yotta.dependencies:null},ce=JSON.stringify(le);return b.sha=n.sha256(ce),b.skipCloudBuild=!!y.skipCloudBuild,b.compileData=ts.pxtc.encodeBase64(n.toUTF8(ce)),b.shimsDTS=L.finish(),b.enumsDTS=R.finish(),Object.keys(o).length>10&&(o={}),o[g]=b,b},t.unpackSourceFromHexFileAsync=function(t){if(t)return e.Util.fileReadAsBufferAsync(t).then((e=>h(new Uint8Array(e))))},t.unpackSourceFromHexAsync=h}(e.cpp||(e.cpp={}))}(pxt||(pxt={})),function(e){!function(t){const n={};let i,s={};function r(s){return n.hasOwnProperty(s.sha)||(n[s.sha]=function(n){let s="";return t.showLoading(e.U.lf("Compiling (this may take a minute)...")),e.tickEvent("cppcompile.start"),function(t){if(t.skipCloudBuild)return Promise.resolve({hex:["SKIP"]});if(e.webConfig&&e.webConfig.isStatic)return e.Util.requestAsync({url:`${e.webConfig.cdnUrl}hexcache/${t.sha}.hex`}).then((t=>{if(t.text){const e={enums:[],functions:[],hex:t.text.split(/\r?\n/)};return Promise.resolve(e)}return e.log("Hex info not found in bundled hex cache"),Promise.resolve()})).catch((t=>(e.log("Error fetching hex info from bundled hex cache"),Promise.resolve())));if(!e.Cloud.localToken||!window||!e.BrowserUtils.isLocalHost())return Promise.resolve(void 0);return(n="compile/"+t.sha,e.Cloud.localRequestAsync(n,i).then((e=>e.json))).then((e=>e&&!e.notInOfflineCache&&e.hex?(e.hex=e.hex.split(/\r?\n/),e):Promise.resolve(void 0))).catch((e=>Promise.resolve(void 0)));var n,i}(n).then((r=>r?(e.tickEvent("cppcompile.cachehit"),r):function(){if(i)return i;{let t=e.getOnlineCdnUrl();if(t)return i=Promise.resolve(t);const n=e.webConfig&&e.webConfig.isStatic;return i=e.Cloud.privateGetAsync("clientconfig",n).then((e=>e.primaryCdnUrl))}}().then((t=>(s=t+"/compile/"+n.sha,e.U.httpGetTextAsync(s+".hex")))).then((e=>e),(t=>e.Cloud.privatePostAsync("compile/extension",{data:n.compileData},!0).then((t=>new Promise(((n,i)=>{let r=0;const a=8e3,o=3e5,l=e.U.now(),c=()=>{if(r++,e.U.now()-l>o)return e.log("abandoning C++ build"),e.tickEvent("cppcompile.cancel",{retry:r}),n(null),null;let i=t.hex.replace(/\.hex/,".json");return e.log(`polling C++ build ${i} (attempt #${r})`),e.tickEvent("cppcompile.poll",{retry:r}),e.Util.httpGetJsonAsync(i).then((t=>{e.log(`build log ${i.replace(/\.json$/,".log")}`),e.tickEvent("cppcompile.done",{success:(null==t?void 0:t.success)?1:0,retry:r,duration:e.U.now()-l}),t.success?(e.log("fetching "+s+".hex"),n(e.U.httpGetTextAsync(s+".hex"))):(e.log("build failed"),t.mbedresponse&&t.mbedresponse.result&&t.mbedresponse.result.exception&&e.log(t.mbedresponse.result.exception),n(null))}),(t=>(e.log(`waiting ${a/1e3|0}s for C++ build...`),setTimeout(c,a),null)))};c()})))))).then((e=>(t.hideLoading(),{hex:e&&e.split(/\r?\n/)}))))).finally((()=>{t.hideLoading()}))}(s)),n[s.sha]}function a(t,n,i,s,r=10){return t.cacheStoreAsync(i,s).then((()=>t.cacheGetAsync(n))).then((s=>{let a;try{a=JSON.parse(s||"[]")}catch(e){console.error("invalid cache entry, clearing entry"),a=[]}a=a.filter((e=>e!=i)),a.unshift(i);let o=a.slice(r);return a=a.slice(0,r),e.U.promiseMapAll(o,(e=>t.cacheStoreAsync(e,"[]"))).then((()=>t.cacheStoreAsync(n,JSON.stringify(a))))}))}function o(e,t,n){return e.cacheGetAsync(t).then((i=>{let s;try{s=JSON.parse(i||"[]")}catch(n){return console.error("invalid cache entry, clearing entry"),e.cacheStoreAsync(t,"[]")}return s[0]!=n?(s=s.filter((e=>e!=n)),s.unshift(n),e.cacheStoreAsync(t,JSON.stringify(s))):null}))}t.showLoading=e=>{},t.hideLoading=()=>{},t.storeWithLimitAsync=a,t.recordGetAsync=o,t.getHexInfoAsync=function(t,n,i){if(!n.sha)return Promise.resolve(null);const l=s[n.sha];if(l)return Promise.resolve(l);e.debug("get hex info: "+n.sha);let c="hex-"+n.sha;return t.cacheGetAsync(c).then((i=>{let s;try{s=i?JSON.parse(i):null}catch(e){console.log("invalid cache entry, clearing entry"),s=null}return s&&s.hex?(e.debug("cache hit, size="+i.length),s.hex=function(t){let n=[];for(let i=0;i<t.length;i++){let s=/^([@!])(....)$/.exec(t[i]);if(!s){n.push(t[i]);continue}let r=parseInt(s[2],16),a=t[++i],o="";if("@"==s[1]){o="";let e=parseInt(a,16);for(;e-- >0;)o+="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"}else o=ts.pxtc.decodeBase64(a);e.Util.assert(o.length>0),e.Util.assert(o.length%16==0);for(let e=0;e<o.length;){let t=[16,r>>8&255,255&r,0];r+=16;for(let n=0;n<16;++n)t.push(o.charCodeAt(e++));let i=0;for(let e=0;e<t.length;++e)i+=t[e];t.push(255&-i);let s=":";for(let e=0;e<t.length;++e){let n=255&t[e];n<=15&&(s+="0"),s+=n.toString(16)}n.push(s.toUpperCase())}}return n}(s.hex),o(t,"hex-keys",c).then((()=>s))):r(n).then((e=>{let n=e.hex;e.hex=function(e){let t=[],n=0;for(let i=0;i<e.length;i+=n){let s=-1,r="";n=0;let a=!1;for(;n<500;){let o=/^:10(....)00(.{32})(..)$/.exec(e[i+n]);if(!o)break;let l=o[2],c=/^0+$/.test(l),u=parseInt(o[1],16);if(-1==s)a=c,t.push((a?"@":"!")+o[1]),s=u-16;else{if(c!=a)break;if(s+16!=u)break}a||(r+=l),s=u,n++}if(0==n)t.push(e[i]),n=1;else if(a)t.push(n.toString(16));else{let e="";for(let t=0;t<r.length;t+=2)e+=String.fromCharCode(parseInt(r.slice(t,t+2),16));t.push(ts.pxtc.encodeBase64(e))}}return t}(e.hex);let i=JSON.stringify(e);return e.hex=n,a(t,"hex-keys",c,i).then((()=>e))})).catch((t=>(e.reportException(t,{sha:n.sha}),Promise.resolve(null))))})).then((e=>(e&&(Object.keys(s).length>20&&(s={}),s[n.sha]=e),e)))}}(e.hexloader||(e.hexloader={}))}(pxt||(pxt={})),function(e){!function(t){function n(n,i,s={},r=null,a=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(i,s,r,a)}function i(n,i,s,r,a){e.Util.assert(!!i&&!!s&&!!r);const o="https://api.crowdin.com/api/project/"+i+"/";return a=a||{},t.testMode?delete a.key:a.key=s,n&&(a.branch=n),o+r+"?"+Object.keys(a).map((e=>`${e}=${encodeURIComponent(a[e])}`)).join("&")}function s(e){let t=0;return function(){if(t++>10)throw new Error("Too many API calls for "+e)}}function r(t,o,l,c,u){return c=a(c),e.debug(`create directory ${t||""}/${c}`),u||(u=s(c)),n(l,i(t,o,l,"add-directory"),{json:"true",name:c}).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 i=n.json||JSON.parse(n.text)||{error:{}};if(404==n.statusCode&&17==i.error.code){e.log(`parent directory missing for ${c}`);const n=c.replace(/\/[^\/]+$/,"");if(n!=c)return r(t,o,l,n,u).then((()=>r(t,o,l,c,u)))}throw new Error(`cannot create directory ${t||""}/${c}: ${n.statusCode} ${JSON.stringify(i)}`)}))}function a(e){return e.replace(/\\/g,"/")}function o(e,t,n,i){const s=t.name,r=n?n+"/"+s:s;switch(t.fullName=r,t.branch=i||"",t.node_type){case"file":e.push(t);break;case"directory":(t.files||[]).forEach((t=>o(e,t,r,i)));break;case"branch":(t.files||[]).forEach((i=>o(e,i,n,t.name)))}}function l(t,n){const i=e.appTarget.versions.pxtCrowdinBranch||"",s=e.appTarget.versions.targetCrowdinBranch||"";let r=[];if(t.forEach((e=>o(r,e,""))),r=r.filter((e=>e.fullName.indexOf("/")<0?e.branch==i:e.branch==s)),n&&(r=r.filter((e=>0==e.fullName.indexOf(n)))),"core"!=e.appTarget.id){const t=e.appTarget.id+"/";r=r.filter((e=>e.fullName.indexOf("/")<0||e.fullName.substr(0,t.length)==t||e.fullName.indexOf("common-docs")>=0))}return r}function c(t,n){const s=i("",t,n,"info",{json:"true"});return e.Util.httpGetTextAsync(s).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,s,r,o={}){const l=i(t,n,s,"info",{json:"true"}),c={};return r=a(r),e.Util.httpGetTextAsync(l).then((a=>{const l=JSON.parse(a);if(!l)throw new Error("info failed");let u=l.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 a=u.pop();if(!a)return Promise.resolve();const l=i(t,n,s,"export-file",{file:r,language:a.code,export_translated_only:o.translatedOnly?"1":"0",export_approved_only:o.validatedOnly?"1":"0"});return e.log(`downloading ${a.name} - ${a.code} (${u.length} more)`),e.Util.httpGetTextAsync(l).then((t=>{try{const e=JSON.parse(t);e&&(c[a.code]=e)}catch(t){e.log(l+" "+t)}return d()})).then((()=>e.Util.delay(1e3)))};return d()})).then((()=>c))},t.createDirectoryAsync=r,t.uploadTranslationAsync=function t(o,l,c,u,d){e.Util.assert(!!l),e.Util.assert(!!c);const h=s(u=a(u));function p(){return f("update-file",{update_option:"update_as_unapproved"})}function f(s,a){return a.type="auto",a.json="",a.escape_quotes="0",h(),n(c,i(o,l,c,s),a,u,d).then((n=>function(n){const i=n.statusCode,s=e.Util.jsonTryParse(n.text)||{};if(e.debug(`upload result: ${i}`),404==i&&s.error&&8==s.error.code)return e.log(`create new translation file: ${u}`),f("add-file",{});if(404==i&&s.error&&17==s.error.code)return r(o,l,c,u.replace(/\/[^\/]+$/,""),h).then((()=>p()));if(!s.success&&s.error&&53==s.error.code)return e.log(`${u} being updated, waiting 5s and retry...`),e.U.delay(5e3).then((()=>t(o,l,c,u,d)));if(200==i||s.success)return Promise.resolve();throw new Error(`Error, upload translation: ${u}, ${i}, ${n.text}`)}(n)))}return p()},t.projectInfoAsync=c,t.listFilesAsync=function(t,n,i){return e.log(`crowdin: listing files under ${i}`),c(t,n).then((t=>{if(!t)throw new Error("info failed");let n=l(t.files,i);return e.debug(`crowdin: found ${n.length} under ${i}`),n.map((e=>({fullName:e.fullName,branch:e.branch||""})))}))},t.languageStatsAsync=function(t,n,s){const r=i("",t,n,"language-status",{language:s,json:"true"});return e.Util.httpGetJsonAsync(r).then((e=>l(e.files)))},t.inContextLoadAsync=function(t){const n=document.createElement("input");n.type="text",n.setAttribute("class","hidden"),n.value=t;let i=new Promise(((i,s)=>{const r=new MutationObserver((()=>{if(t==n.value)return;const s=e.Util.rlf(n.value);n.remove(),r.disconnect(),i(s)}));r.observe(n,{attributes:!0})}));return document.body.appendChild(n),i}}(e.crowdin||(e.crowdin={}))}(pxt||(pxt={})),function(e){!function(t){function n(e){return e?e.split(/\r?\n/):[]}function i(e,t,i={}){i.ignoreWhitespace&&(e=e.replace(/[\r\n]+$/,""),t=t.replace(/[\r\n]+$/,""));const s=n(e),r=n(t),a=Math.min(i.maxDiffSize||1024,s.length+r.length);if(0==a)return[];const o=s.length>65520?Uint32Array:Uint16Array,l={};let c=0;const u=h(s),d=h(r);function h(e){const t=new o(e.length);let n=0;for(let s of e)i.ignoreWhitespace&&(s=s.replace(/\s+$/g,"").replace(/^\s+/g,"")),l.hasOwnProperty(s)?t[n]=l[s]:(++c,t[n]=c,l[s]=c),n++;return t}const p=new o(2*a+1);let f=-1;for(let e=0;e<=a;e++)null!=T(e,p)&&(f=e);if(-1==f)return null;const g=[];let m=null;for(let e=0;e<=f;e++){const t=g.length?g[g.length-1].slice(0):new o(2*f+1);if(g.push(t),m=T(e,t),null!=m)break}const b=[];let y=m;for(let e=g.length-1;e>=0;e--){const t=g[e];let n=0,i=0;y==-e||y!=e&&t[a+y-1]<t[a+y+1]?(i=y+1,n=t[a+i]):(i=y-1,n=t[a+i]+1);let o=n-y;for(let e=t[a+y]-n-1;e>=0;--e)b.push(" "+r[o+e]);i==y-1?b.push("- "+s[n-1]):o>0&&b.push("+ "+r[o-1]),y=i}if(b.reverse(),i.context==1/0||i.full)return b;let v=1,w=1,k=0;const A=[],x=i.context||3;for(;k<b.length;){let e=k;for(;e<b.length&&" "==b[e][0];)e++;if(e==b.length)break;const t=e-x,n=t-k;n>0&&(v+=n,w+=n,k=t);const i=A.length,s=v,r=w;A.push("@@");let a=k,o=0;for(;a<b.length;){if(" "==b[a][0]){if(o++,o>2*x+2){a-=x+2;break}}else o=0;a++}for(;k<a;){A.push(b[k]);switch(b[k][0]){case"-":v++;break;case"+":w++;break;case" ":v++,w++}k++}A[i]=`@@ -${s},${v-s} +${r},${w-r} @@`}return A;function T(e,t){for(let n=-e;n<=e;n+=2){let i=0;i=n==-e||n!=e&&t[a+n-1]<t[a+n+1]?t[a+n+1]:t[a+n-1]+1;let s=i-n;for(;i<u.length&&s<d.length&&u[i]==d[s];)i++,s++;if(t[a+n]=i,i>=u.length&&s>=d.length)return n}return null}}function s(e){return n(e).map((e=>e.replace(/;\s*$/,""))).join("\n")}function r(e){const t=/^@@ -(\d+),(\d+) \+(\d+),(\d+)/.exec(e);return t&&{oldStart:parseInt(t[1])-1,oldLength:parseInt(t[2]),newStart:parseInt(t[3])-1,newLength:parseInt(t[4])}}t.toLines=n,t.compute=i,t.diff3=function(t,s,r,a,o){const l=m(t),c=m(r);if(!l||!c)return;const u=n(t),d=n(r);let h=0,p=[],f=0,g=0;for(let t=0;t<l.length-1;)if(l[t]==f&&c[t]==g)p.push(u[f]),f++,g++,t++;else{let n=!0,i=!0,s=t;for(;s<l.length&&(l[s]!=f+s-t&&(n=!1),c[s]!=g+s-t&&(i=!1),null==l[s]||null==c[s]);)s++;if(e.U.assert(s<l.length),n)for(;g<c[s];)p.push(d[g++]);else if(i)for(;f<l[s];)p.push(u[f++]);else if(u.slice(f,l[s]).join("\n")==d.slice(g,c[s]).join("\n"))for(;f<l[s];)p.push(u[f++]);else{for(h++,p.push("<<<<<<< "+a);f<l[s];)p.push(u[f++]);for(p.push("=======");g<c[s];)p.push(d[g++]);p.push(">>>>>>> "+o)}t=s,f=l[s],g=c[s]}return{merged:p.join("\n"),numConflicts:h};function m(t){const n=i(s,t,{context:1/0});if(!n)return;const r=[];let a=0,o=0;for(let t of n)"+"==t[0]?a++:"-"==t[0]?(r[o]=null,o++):" "==t[0]?(r[o]=a,a++,o++):e.U.oops();return r.push(a+1),r}},t.removeTrailingSemiColumns=s,t.split=function(e,t){const n=e.split(/-{10,}/,2);if(n.length<2)return{fileA:e,fileB:void 0};let i=n[0].replace(/\n$/,""),r=n[1].replace(/^\n/,"");return t&&t.removeTrailingSemiColumns&&(i=s(i),r=s(r)),{fileA:i,fileB:r}},t.parseDiffMarker=r,t.render=function(t,n,s={}){const a=i(t,n,s);if(!a)return e.dom.el("div",null,pxtc.Util.lf("Too many differences to render diff."));const o={"@":"diff-marker"," ":"diff-unchanged","+":"diff-added","-":"diff-removed"};let l=0,c=0,u="";const d=e.dom.el("tbody"),h=e.dom.el("table",{class:"diffview "+(s.update?"update":"")},d);let p=null;return a.forEach(((t,n)=>{const h=r(t);h?(l=h.oldStart,c=h.newStart):("+"!=t[0]&&l++,"-"!=t[0]&&c++);const f=a[n+1]?a[n+1][0]:"",g=a[n+2]?a[n+2][0]:"",m=t.slice(2);let b=e.dom.el("code",null,m);if(p)b=p,p=null;else if(!("-"!=t[0]||" "!=u&&"@"!=u||"+"!=f||" "!=g&&"@"!=g&&""!=g)){const s=function(t,n){const s=i(t.split("").join("\n"),n.split("").join("\n"),{context:1/0});if(!s)return{a:e.dom.el("div",{class:"inline-diff"},e.dom.el("code",null,t)),b:e.dom.el("div",{class:"inline-diff"},e.dom.el("code",null,n))};const r=[],a=[];for(let t=0;t<s.length;){let n=t;const i=s[t][0];for(;s[n]&&s[n][0]==i;)n++;const o=s.slice(t,n).map((e=>e.slice(2))).join("");" "==i?(r.push(e.dom.el("code",{class:"ch-common"},o)),a.push(e.dom.el("code",{class:"ch-common"},o))):"-"==i?r.push(e.dom.el("code",{class:"ch-removed"},o)):"+"==i?a.push(e.dom.el("code",{class:"ch-added"},o)):e.Util.oops(),t=n}return{a:e.dom.el("div",{class:"inline-diff"},r),b:e.dom.el("div",{class:"inline-diff"},a)}}(t.slice(2),a[n+1].slice(2));b=s.a,p=s.b}if(u=t[0],s.hideMarkerLine&&"@"==u||s.hideRemoved&&"-"==u)return;const y="@"==u,v=`${o[u]}`;d.appendChild(e.dom.el("tr",{class:v},[!s.hideLineNumbers&&e.dom.el("td",{class:"line-a","data-content":l}),!s.hideLineNumbers&&e.dom.el("td",{class:"line-b","data-content":c}),y&&e.dom.el("td",{colspan:2,class:"change"},e.dom.el("code",null,t)),!s.hideMarker&&!y&&e.dom.el("td",{class:"marker","data-content":u}),!y&&e.dom.el("td",{class:"change"},b)]))})),h},t.resolveMergeConflictMarker=function(t,n,i,s){let r=e.diff.toLines(t),a=n;for(;a<r.length&&!/^<<<<<<<[^<]/.test(r[a]);)a++;let o=a+1;for(;o<r.length&&!/^=======$/.test(r[o]);)o++;let l=o+1;for(;l<r.length&&!/^>>>>>>>[^>]/.test(r[l]);)l++;if(l>=r.length)return e.debug(`diff marker mistmatch: ${r.length} -> ${a} ${o} ${l}`),t;if(r[a]=void 0,r[o]=void 0,r[l]=void 0,!i)for(let e=a;e<=o;++e)r[e]=void 0;if(!s)for(let e=o;e<=l;++e)r[e]=void 0;return r.filter((e=>void 0!==e)).join("\n")},t.mergeDiff3Config=function(t,n,i){let s=e.Util.jsonTryParse(t),r=e.Util.jsonTryParse(n),a=e.Util.jsonTryParse(i);if(s&&!a)return t;if(!s)return i||n;if(!r&&a&&(r=a),!s||!r||!a)return;delete s.installedVersion,delete r.installedVersion,delete a.installedVersion;const o={},l=e.U.unique(Object.keys(r).concat(Object.keys(s)).concat(Object.keys(a)),(e=>e));for(const t of l){const n=s[t],i=r[t],l=a[t];if(JSON.stringify(n)==JSON.stringify(l))void 0!==n&&(o[t]=n);else switch(t){case"name":o[t]=c(n,i,l);break;case"version":o[t]=e.semver.strcmp(n,l)>0?n:l;break;case"languageRestriction":case"preferredEditor":case"targetVersion":o[t]=n;break;case"public":o[t]=n&&l;break;case"files":case"testFiles":{const e=u(n||[],i||[],l||[]);if(!e)return;o[t]=e.length?e:void 0;break}case"dependencies":case"testDependencies":{const e=d(n||{},i||{},l||{});if(Object.keys(e).length)return;o[t]=e;break}case"description":if(n&&!l)o[t]=n;else{if(n||!l)return;o[t]=l}break;default:return}}return e.Package.stringifyConfig(o);function c(e,t,n){return e==t?n:n==t?e:e==lf("Untitled")?n:e}function u(t,n,i){const s=[],r=e.U.unique(n.concat(t).concat(i),(e=>e));for(const e of r){const r=t.indexOf(e)>-1,a=i.indexOf(e)>-1,o=n.indexOf(e)>-1;r==a||a==o?r&&s.push(e):a&&s.push(e)}return s}function d(t,n,i){const s={},r=e.U.unique(Object.keys(n).concat(Object.keys(t)).concat(Object.keys(i)),(e=>e));for(const a of r){const r=t[a],o=i[a],l=n[a];if(r==o)r&&(s[a]=r);else{const t=e.github.parseRepoId(r),n=e.github.parseRepoId(o);if(t&&n&&e.semver.tryParse(t.tag)&&e.semver.tryParse(n.tag)&&t.owner&&t.project&&t.owner==n.owner&&t.project==n.project){const i=e.semver.strcmp(t.tag,n.tag)>0?t.tag:n.tag;s[a]=`github:${t.owner}/${t.project}#${i}`}else o==l?r&&(s[a]=r):o&&(s[a]=o)}}return s}},t.hasMergeConflictMarker=function(e){return e&&/^(<<<<<<<[^<]|>>>>>>>[^>])/m.test(e)},t.reconstructConfig=function(t,n,i,s){let r={},a=i.tree.tree.map((e=>e.path)).filter((e=>/\.(ts|blocks|md|jres|asm|json)$/.test(e))).filter((t=>t!=e.CONFIG_NAME));return t.fileName&&(a=a.filter((e=>0===e.indexOf(t.fileName))).map((e=>e.slice(t.fileName.length+1)))),a.find((e=>/\.ts$/.test(e)))||(s.config.files.filter((e=>a.indexOf(e)<0)).forEach((e=>{a.push(e),n[e]=s.files[e]})),e.Util.jsonCopyFrom(r,s.config.dependencies)),Object.keys(r).length||(r[e.appTarget.corepkg]="*"),{name:"",files:a,dependencies:r,preferredEditor:a.find((e=>/.blocks$/.test(e)))?e.BLOCKS_PROJECT_NAME:e.JAVASCRIPT_PROJECT_NAME}}}(e.diff||(e.diff={}))}(pxt||(pxt={})),function(e){!function(t){t.extractSharedIdFromPostUrl=function(t){return e.Util.httpGetJsonAsync(t+".json").then((t=>t.post_stream&&t.post_stream.posts&&t.post_stream.posts[0]&&t.post_stream.posts[0].link_counts.map((t=>e.Cloud.parseScriptId(t.url))).filter((e=>!!e))[0]))},t.topicsByTag=function(t,n){const i=`${t=t.replace(/\/$/,"")}/tag/${n}.json`;return e.Util.httpGetJsonAsync(i).then((n=>{const i=e.Util.toDictionary(n.users,(e=>e.id.toString()));return n.topic_list.topics.map((e=>({id:e.id,title:e.title,url:`${t}/t/${e.slug}/${e.id}`,imageUrl:e.image_url,author:i[e.posters[0].user_id].username,cardType:"forumUrl"})))}))}}(e.discourse||(e.discourse={}))}(pxt||(pxt={})),function(e){!function(t){var n=pxtc.Util;let i,s={},r={};const a="\x3c!-- @CMD@ @ARGS@ --\x3e";let o={parent:a,short:a,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 l(e,t,n){return e.split(t).join(n)}function c(e){return e=l(e,"&","&"),e=l(e,"<","<"),e=l(e,">",">"),e=l(e,'"',"""),e=l(e,"'","'")}function u(e){return e?c(e.replace(/\&([#a-z0-9A-Z]+);/g,((e,t)=>{switch(t){case"amp":return"&";case"lt":return"<";case"gt":return">";case"quot":return'"';default:return"#"==t[0]?String.fromCharCode(parseInt(t.slice(1))):e}}))):e}t.htmlQuote=c,t.html2Quote=u;const d=[{rx:/^vimeo\.com\/(\d+)/i,cmd:"### @vimeo $1"},{rx:/^(www\.youtube\.com\/watch\?v=|youtu\.be\/)([\w\-]+(\#t=([0-9]+m[0-9]+s|[0-9]+m|[0-9]+s))?)/i,cmd:"### @youtube $2"}];t.requireMarked=()=>"undefined"!=typeof marked?marked:"undefined"!=typeof require?require("marked"):void 0,t.requireDOMSanitizer=()=>"undefined"!=typeof DOMPurify?DOMPurify.sanitize:"undefined"!=typeof require?require("DOMPurify").sanitize:void 0;const h=e=>`<div class='ui negative message'>${c(e)}</div>`;function p(e){let t=n.clone(s),i=n.clone(r),a=n.clone(o),l={},c={},d=e.params,p=e.theme;e.boxes=t,e.macros=i,e.settings=a,e.html=e.html.replace(/<aside\s+([^<>]+)>([^]*?)<\/aside>/g,((e,n,s)=>{let r=function(e){let t={};for(;e.trim();){let n=/\s*([^=\s]+)=("([^"]*)"|'([^']*)'|(\S*))/.exec(e);if(n){let e=n[3]||n[4]||n[5]||"";t[n[1].toLowerCase()]=e}else n=/^\s*(\S+)/.exec(e),t[n[1]]="true";e=e.slice(n[0].length)}return t}(n),o=r["data-name"]||r.id;return o?(/box/.test(r.class)?t[o]=s:/aside/.test(r.class)?t[o]=`\x3c!-- BEGIN-ASIDE ${o} --\x3e${s}\x3c!-- END-ASIDE --\x3e`:/setting/.test(r.class)?a[o]=s:/menu/.test(r.class)?l[o]=s:/toc/.test(r.class)?c[o]=s:i[o]=s,`\x3c!-- macro ${o} --\x3e`):h("id or data-name missing on macro")}));let f=(e,t)=>{let n=l.item,i={NAME:e.name};if(e.subitems)n=l["toc-dropdown"]?l["toc-dropdown"]:0==t?l["top-dropdown"]:l["inner-dropdown"],i.ITEMS=e.subitems.map((e=>f(e,t+1))).join("\n");else{if(/^-+$/.test(e.name)&&(n=l.divider),e.path&&!/^(https?:|\/)/.test(e.path))return h("Invalid link: "+e.path);i.LINK=e.path}return m(n,i,["ITEMS"])},g=[{name:lf("Docs"),href:"/docs"}];const b=e.TOC||p.TOC||[];let y=[],v=t=>{for(let e of t.subitems||[])if(v(e))return y.push(t),!0;return!(!e.filepath||!t.path||0!=e.filepath.indexOf(t.path))&&(y.push(t),!0)};b.forEach(v);let w=(t,n)=>{let i=c.item,s={NAME:t.name};return t.path&&!/^(https?:|\/)/.test(t.path)?h("Invalid link: "+t.path):(/^\//.test(t.path)&&e.versionPath&&(t.path=`/${e.versionPath}${t.path}`),s.LINK=t.path,y.indexOf(t)>=0?(s.ACTIVE="active",s.EXPANDED="true",g.push({name:t.name,href:t.path})):s.EXPANDED="false",t.subitems&&t.subitems.length>0?(i=c["toc-dropdown"]?""!==t.name?c["toc-dropdown"]:c["toc-dropdown-noLink"]:0==n?""!==t.name?c["top-dropdown"]:c["top-dropdown-noHeading"]:1==n?c["inner-dropdown"]:c["nested-dropdown"],s.ITEMS=t.subitems.map((e=>w(e,n+1))).join("\n")):/^-+$/.test(t.name)&&(i=c.divider),m(i,s,["ITEMS"]))};d.menu=(p.docMenu||[]).map((e=>f(e,0))).join("\n"),d.TOC=b.map((e=>w(e,0))).join("\n"),p.appStoreID&&(d.appstoremeta=`<meta name="apple-itunes-app" content="app-id=${n.htmlEscape(p.appStoreID)}"/>`);let k="";g.length>1&&(k=`\n <nav class="ui breadcrumb" aria-label="${lf("Breadcrumb")}">\n ${g.map(((e,t)=>`<a class="${t==g.length-1?"active":""} section"\n href="${u(e.href)}" aria-current="${t==g.length-1?"page":""}">${u(e.name)}</a>`)).join('<i class="right chevron icon divider"></i>')}\n </nav>`),d.breadcrumb=k,p.boardName&&(d.boardname=u(p.boardName)),p.boardNickname&&(d.boardnickname=u(p.boardNickname)),p.driveDisplayName&&(d.drivename=u(p.driveDisplayName)),p.homeUrl&&(d.homeurl=u(p.homeUrl)),d.targetid=p.id||"???",d.targetname=p.name||"Microsoft MakeCode",d.docsheader=p.docsHeader||"Documentation",d.orgtitle="MakeCode";const A=p.docsLogo&&n.htmlEscape(p.docsLogo),x=(p.organizationWideLogo||p.organizationLogo)&&n.htmlEscape(p.organizationWideLogo||p.organizationLogo),T=p.organizationLogo&&n.htmlEscape(p.organizationLogo);d.targetlogo=A?`<img aria-hidden="true" role="presentation" class="ui ${p.logoWide?"small":"mini"} image" src="${A}" />`:"",d.orglogo=x?`<img aria-hidden="true" role="presentation" class="ui image" src="${x}" />`:"",d.orglogomobile=T?`<img aria-hidden="true" role="presentation" class="ui image" src="${T}" />`:"";let E=e.ghEditURLs||[];if(E.length){let e='<p style="margin-top:1em">\n',t=lf("Edit this page on GitHub");for(let n of E)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 C=`\n <a href="#maincontent" class="ui item link" tabindex="0" role="menuitem">${lf("Skip to main content")}</a>\n `;d.accMenu=C;const I=lf("Print this page"),U=`\n <button id="printbtn" class="circular ui icon right floated button hideprint" title="${I}" aria-label="${I}">\n <i class="icon print"></i>\n </button>\n `;d.printBtn=U;const S=`\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=S;const N=["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=N[0],d.searchBar2=N[1];let P="";p.accentColor&&(P+=`\n.ui.accent { color: ${p.accentColor}; }\n.ui.inverted.accent { background: ${p.accentColor}; }\n`),d.targetstyle=P,d.tocclass=p.lightToc?"lighttoc":"inverted";for(let e of Object.keys(p)){let t=p[e];void 0===d[e]&&"string"==typeof t&&(d[e]=t)}e.finish=()=>m(e.html,d,["body","menu","accMenu","TOC","prev","next","printBtn","breadcrumb","targetlogo","orglogo","orglogomobile","github","JSON","appstoremeta","sidebarToggle","searchBar1","searchBar2"])}function f(e){e.image=function(e,t,n){let i='<img class="ui image" src="'+e+'" alt="'+n+'"';return t&&(i+=' title="'+t+'"'),i+=' loading="lazy"',i+=this.options.xhtml?"/>":">",i},e.listitem=function(e){const t=/^\s*\[( |x)\]/i.exec(e);return t?`<li class="${" "==t[1]?"unchecked":"checked"}">`+e.slice(t[0].length)+"</li>\n":"<li>"+e+"</li>\n"},e.heading=function(e,t,n){let i=/(.*)#([\w\-]+)\s*$/.exec(e),s="";return i?(e=i[1],s=i[2]):s=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}${s}">${e}</h${t}>`}}function g(e,t){return e.replace(/<!--\s*@(ifn?def)\s+(\w+)\s*-->([^]*?)<!--\s*@endif\s*-->/g,((e,n,i,s)=>"ifdef"==n&&t[i]||"ifndef"==n&&!t[i]?`\x3c!-- ${n} ${i} --\x3e${s}\x3c!-- endif --\x3e`:`\x3c!-- ${n} ${i} endif --\x3e`))}function m(e,t,i=[]){return e?e.replace(/@(\w+)@/g,((e,s)=>{let r=n.lookup(t,s)||"";return r+="",i.indexOf(s)<0&&(r=u(r)),r})):""}t.prepTemplate=p,t.setupRenderer=f,t.renderConditionalMacros=g,t.renderMarkdown=function(e){let s=!0;e.pubinfo||(s=!1,e.pubinfo={});let r=e.pubinfo;if(e.theme||(e.theme={}),delete e.pubinfo.private,r.time){let e=parseInt(r.time);r.timems||(r.timems=1e3*e+""),r.humantime||(r.humantime=n.isoTime(e))}r.name&&(r.dirname=r.name.replace(/[^A-Za-z0-9_]/g,"-"),r.title=r.name),s&&(r.JSON=JSON.stringify(r,null,4).replace(/</g,"\\u003c"));let a=e.template;a=a.replace(/<!--\s*@include\s+(\S+)\s*-->/g,((t,n)=>"\x3c!-- include "+n+" --\x3e\n"+((e.theme.htmlDocIncludes||{})[n]||"")+"\n\x3c!-- end include --\x3e\n")),a=g(a,r),e.locale&&(a=y(a,e.locale).text);let o={html:a,theme:e.theme,filepath:e.filepath,versionPath:e.versionPath,ghEditURLs:e.ghEditURLs,params:r,TOC:e.TOC};p(o),i||(i=t.requireMarked());let l=new i.Renderer;f(l);const c=l.link;l.link=function(e,t,n){const i=new RegExp("^[/#]").test(e),s=i?"":"_blank";i&&o.versionPath&&(e=`/${o.versionPath}${e}`);return c.call(l,e,t,n).replace(/^<a /,`<a ${s?`target="${s}"`:""} rel="nofollow noopener" `)};let b=t.requireDOMSanitizer();i.setOptions({renderer:l,gfm:!0,tables:!0,breaks:!1,pedantic:!1,sanitize:!0,sanitizer:b,smartLists:!0,smartypants:!0});let v=e.markdown;e.repo&&(v+=`\n\`\`\`package\n${e.repo.name.replace(/^pxt-/,"")}=github:${e.repo.fullName}#${e.repo.tag||"master"}\n\`\`\`\n`),v=v.replace(/^\s*https?:\/\/(\S+)\s*$/gm,((e,t)=>{for(let e of d){let n=e.rx.exec(t);if(n)return e.cmd.replace(/\$(\d+)/g,((e,t)=>n[parseInt(t)]||""))+"\n"}return e})),v=v.replace(/@([a-z]+)@/gi,((t,i)=>{let s=r[i];return!s&&e.throwOnError&&n.userError(`unknown macro ${i}`),s||"unknown macro"}));let w=i(v);w=w.replace(/<br\s*\/>/gi,"<br/>"),w=w.replace(/(<img [^>]* src=")\/docs\/static\/([^">]+)"/g,((e,t,n)=>t+"/static/"+n+'"'));let k="",A=0;function x(e,t,n){let i=n;return e<=A&&(i=k+i,k="",A=0),i}if(w=w.replace(/<h(\d)[^>]+>\s*([~@])?\s*(.*?)<\/h\d>/g,((t,i,s,a)=>{let l=/^(\w+)\s+(.*)/.exec(a),c=l?l[1]:a,d=l?l[2]:"";if(d=u(d),c=u(c),i=parseInt(i),s){if("@"==s){let t=n.lookup(o.settings,c);if(null!=t)r[c]=d;else if(t=n.lookup(o.macros,c),null==t)return e.throwOnError&&n.userError(`Unknown command: @${c}`),h(`Unknown command: @${c}`);return x(i,0,m(t,{ARGS:d,CMD:c},["ARGS","CMD"]))}{if(!c){let e=k;return k="",e}let t=n.lookup(o.boxes,c);if(t){let e=t.split("@BODY@"),n=x(i,0,e[0].replace("@ARGS@",d));k=e[1];let s=t.match(/data-[^>\s]+/gi);return s&&s.indexOf("data-inferred")>=0&&(A=i),n}return e.throwOnError&&n.userError(`Unknown box: ~ ${c}`),h(`Unknown box: ~ ${c}`)}}return x(i,0,t)})),k&&(w+=k),!r.title){let e=/<h1[^<>]*>([^<>]+)<\/h1>/.exec(w);e&&(r.title=u(e[1]))}if(!r.description){let e=/<p>([^]+?)<\/p>/.exec(w);e&&(r.description=u(e[1]))}const T=/<div class="ui embed mdvid"[^<>]+?data-placeholder="([^"]+)"[^>]*\/?>/i.exec(w)||/<img class="ui [^"]*image" src="([^"]+)"[^>]*\/?>/i.exec(w);T&&(r.cardLogo=u(T[1])),r.twitter=u(e.theme.twitter||"@msmakecode");let E={main:""};w=w.replace(/<!-- BEGIN-ASIDE (\S+) -->([^]*?)<!-- END-ASIDE -->/g,((e,t,i)=>{let s=n.lookup(E,t);return E[t]=(s||"")+i,"\x3c!-- aside --\x3e"})),w=w.replace(/\n<\/code>/g,"</code>"),E.main=w,w="";for(let e of Object.keys(E))w+=(C=e+"-container",I=E[e],m(o.boxes[C]||"@BODY@",{BODY:I},["BODY"]));var C,I;r.body=w,r.name=r.title||"";for(let t of Object.keys(e.theme)){let n=e.theme[t];"string"==typeof n&&(r["theme_"+t]=n)}return o.finish()},t.embedUrl=function(e,t,n,i){return`<div style="position:relative;height:0;padding-bottom:70%;overflow:hidden;"><iframe style="position:absolute;top:0;left:0;width:100%;height:100%;" src="${`${e}#${t}:${n}`}" frameborder="0" sandbox="allow-popups allow-forms allow-scripts allow-same-origin"></iframe></div>`},t.runUrl=function(e,t,n){return`<div style="position:relative;height:0;padding-bottom:${t};overflow:hidden;"><iframe style="position:absolute;top:0;left:0;width:100%;height:100%;" src="${e}?id=${encodeURIComponent(n)}" allowfullscreen="allowfullscreen" sandbox="allow-popups allow-forms allow-scripts allow-same-origin" frameborder="0"></iframe></div>`},t.codeEmbedUrl=function(e,t,n){const i=`${e}---codeembed#pub:${t}`;return`<div style="position:relative;height:calc(${n=Math.ceil(n||300)}px + 5em);width:100%;overflow:hidden;"><iframe style="position:absolute;top:0;left:0;width:100%;height:100%;" src="${i}" allowfullscreen="allowfullscreen" frameborder="0" sandbox="allow-scripts allow-same-origin"></iframe></div>`};const b={b:1,strong:1,em:1};function y(e,t){const i={};function s(e){let s=/^(\s*)([^]*?)(\s*)$/.exec(e),r=s[2].replace(/\s+/g," ");if(""==r||/^((IE=edge,.*|width=device-width.*|(https?:\/\/|\/)[\w@\/\.]+|@[\-\w]+@|\{[^\{\}]+\}|[^a-zA-Z]*|( )+)\s*)+$/.test(r))return null;let a=n.lookup(t,r);return a?r=a:i[r]="",s[1]+r+s[3]}function r(e){return e.replace(/&llt;/g,"<").replace(/&ggt;/g,">")}return{text:e=(e=(e=(e="<start>"+(e=e.replace(/<([\/\w]+)([^<>]*)>/g,((e,t,n)=>{let i=t.replace(/^\//,"").toLowerCase();return 1===b[i]?"&llt;"+t+n+"&ggt;":e})))).replace(/(<([\/\w]+)([^<>]*)>)([^<>]+)/g,((e,t,n,i,a)=>{if("script"==n||"style"==n)return r(e);let o=s(r(a));return null==o?r(e):t+o}))).replace(/(<[^<>]*)(content|placeholder|alt|title)="([^"]+)"/g,((e,t,n,i)=>null==s(i)?e:t+n+'="'+i.replace(/"/g,"''")+'"'))).replace(/^<start>/g,""),missing:i}}function v(e,t){if(e.id==t)return e;for(let n of e.children){let e=v(n,t);if(e)return e}return null}function w(e,t){let n=0,i=[{level:0,id:"",title:"",start:n,text:"",children:[]}],s=(e=e.replace(/\r/g,"")).split(/\n/),r={};for(let e of s){let s=/^\s*(#+)\s*(.*?)(#(\S+)\s*)?$/.exec(e),a=null;if(t&&s)if(s[4])if(r[s[4]])s=null;else{a=v(t,s[4]);let e=t=>{t.id&&(r[t.id]=!0),t.children.forEach(e)};a&&e(a)}else s=null;if(s){let r={level:t?1:s[1].length,title:s[2].trim(),id:s[4]||"",start:n,text:"",children:[]};if(a){e="";for(let t=0;t<a.level;++t)e+="#";e+=" ",e+=r.title||a.title,e+=" #"+r.id}for(;i[i.length-1].level>=r.level;)i.pop();i[i.length-1].children.push(r),i.push(r)}i[i.length-1].text+=e+"\n",n++}return i[0]}t.translate=y,t.buildTOC=function(n){if(!n)return null;const i=e.docs.requireMarked(),s=t.requireDOMSanitizer(),r={renderer:new i.Renderer,gfm:!0,tables:!1,breaks:!1,pedantic:!1,sanitize:!0,sanitizer:s,smartLists:!1,smartypants:!1};let a={name:"dummy",subitems:[]},o=[];o.push(a);let l=i.lexer(n,r),c=!1;l.forEach((e=>{switch(e.type){case"heading":e.depth;break;case"list_start":break;case"list_item_start":case"loose_item_start":c=!0;let t={name:"",path:"",subitems:[]};return void o.push(t);case"text":let n=o[o.length-1];e.text.indexOf("[")>=0?e.text.replace(/\[(.*?)\]\((.*?)\)/i,(function(e,t,i){n.name=t,n.path=i.replace(".md","")})):c&&(n.name=e.text);break;case"list_item_end":case"loose_item_end":let i=o.pop();o[o.length-1].subitems.push(i)}c=!1}));let u=a.subitems;return u&&0!=u.length?u:null},t.visitTOC=function(e,t){e.forEach((function(e){t(e),e.subitems&&e.subitems.forEach(t)}))};let k=!1;function A(e,t){if(k||function(){function e(e,t,n){let i=A(e,t).trim();if(i!=(n=n.trim()))throw console.log(`*** Template:\n${e}\n*** Input:\n${t}\n*** Expected:\n${n}\n*** Output:\n${i}`),new Error("augment docs test fail")}k=!0;let t="\n# T0\n## Examples #ex\n### Example 1\nTEx1\n### Example 2 #ex2\nTEx2\n### Example 3\nTEx3\n\n## See also #also\nTAlso\n",n="\n# @extends\n# #ex2\nMy example\n## See Also These! #also\nMy links\n",i="\n# T0\n## Examples #ex\n### Example 1\nTEx1\n### Example 2 #ex2\nMy example\n### Example 3\nTEx3\n\n## See Also These! #also\nMy links\n",s="\n# @extends\n### #ex\nFoo\n#### Example 1\nEx1\n#### Example 2x #ex2\nEx2\n## See Also These! #also\nMy links\n",r="\n# T0\n## Examples #ex\nFoo\n#### Example 1\nEx1\n#### Example 2x #ex2\nEx2\n## See Also These! #also\nMy links\n";e(t,"",t),e(t," ",t),e(t,n,i),e(t,s,r)}(),!t)return e;let i=w(e,null),s=w(t,i),r={},a={};for(let e of s.children)n.assert(0==e.children.length),n.assert(!!e.id),r[e.id]=e.text;let o=e=>{e.id&&void 0!==r[e.id]&&(a[e.id]=!0,e.text=r[e.id],e.children=[]),e.children.forEach(o)};o(i);let l="",c=e=>{l+=e.text,e.children.forEach(c)};c(i);let u="",d=s.text.replace(/^\s*#+\s*@extends.*/gm,"").replace(/^\s*\n/gm,"");d.trim()&&(u+=d.trim()+"\n");for(let e of s.children)a[e.id]||(u+=e.text);return u&&(l+="## Couldn't apply replacement logic to:\n"+u),l}t.augmentDocs=A}(e.docs||(e.docs={}))}(pxt||(pxt={})),function(e){!function(e){e.el=function(e,t,n){const i=document.createElement(e);return t&&Object.keys(t).forEach((e=>i.setAttribute(e,t[e]+""))),function e(t){Array.isArray(t)?t.forEach((t=>e(t))):"string"==typeof t?i.appendChild(document.createTextNode(t)):t instanceof HTMLElement&&i.appendChild(t)}(n),i}}(e.dom||(e.dom={}))}(pxt||(pxt={})),function(e){!function(t){function n(e){const t=/```package\s+((.|\s)+?)\s*```/i.exec(e);let n;return t&&(n={},t[1].split("\n").map((e=>e.replace(/\s*/g,""))).filter((e=>!!e)).map((e=>e.split("="))).forEach((e=>n[e[0]]=e[1]||"*"))),n}function i(e){const t=/```config\s+((.|\s)+?)\s*```/i.exec(e);let n=[];return t&&t[1].split("\n").map((e=>e.replace(/\s*/g,""))).filter((e=>!!e)).map((e=>e.split("="))).filter((e=>"feature"==e[0]&&!!e[1])).forEach((e=>n.push(e[1]))),n.length?n:void 0}function s(t){const n=/```jres\s+((.|\s)+?)\s*```/i.exec(t);if(n){const t=n[1],i=JSON.parse(t);return{jres:t,ts:e.emitTilemapsFromJRes(i)}}}function r(t){const n=/```assetjson\s+((.|\s)+?)\s*```/i.exec(t);return n?e.tutorial.parseAssetJson(n[1]):{}}function a(t){let n=e.Util.jsonTryParse(t);return n&&!Array.isArray(n)&&(n=[n]),(null==n?void 0:n.length)?n:(n=t.split(/^---$/gm).filter((e=>!!e)).map((e=>{let t={};return e.replace(/^\s*(?:-|\*)\s+(\w+)\s*:\s*(.*)$/gm,((e,n,i)=>{if("flags"==n)t[n]=i.split(",");else if("otherAction"===n){const e=i.split(",").map((e=>null==e?void 0:e.trim()));(t.otherActions||(t.otherActions=[])).push({url:e[0],editor:e[1],cardType:e[2]})}else t[n]=i;return""})),!!Object.keys(t).length&&t})).filter((e=>!!e)),(null==n?void 0:n.length)?n:void 0)}function o(t){if(!t)return[];const n=[];let i,s=!1,r="";return t.split(/\r?\n/).forEach((t=>{if(/^## /.test(t))i=t.substr(2).trim();else if(/^(### ~ |```)codecard$/.test(t))s=!0;else if(/^(### ~|```)$/.test(t)){if(s=!1,i&&r){const t=a(r);(null==t?void 0:t.length)?n.push({name:i,cards:t}):e.log("invalid gallery format")}r="",i=void 0}else s&&(r+=t+"\n")})),n.forEach((t=>t.cards.forEach((t=>{if(t.otherActions&&!t.otherActions.length&&("tutorial"==t.cardType||"example"==t.cardType)){const n=["js"];e.appTarget.appTheme.python&&n.unshift("py"),t.otherActions=n.map((e=>({url:t.url,cardType:t.cardType,editor:e})))}})))),n}t.parsePackagesFromMarkdown=n,t.parseFeaturesFromMarkdown=i,t.parseJResFromMarkdown=s,t.parseTemplateProjectJSON=r,t.parseExampleMarkdown=function(t,a){if(!a)return;const o=/```(blocks?|typescript|python|spy|sim)\s+((.|\s)+?)\s*```/i.exec(a);if(!o)return;const l=n(a),c=o[1],u=o[2],d=i(a),h=s(a),p={name:t,filesOverride:{[e.MAIN_BLOCKS]:'<xml xmlns="http://www.w3.org/1999/xhtml"></xml>',["python"===o[1]?e.MAIN_PY:e.MAIN_TS]:u},dependencies:l,features:d,snippetType:c,source:u};return p.filesOverride=Object.assign(Object.assign({},p.filesOverride),r(a)),h&&(p.filesOverride[e.TILEMAP_JRES]=h.jres,p.filesOverride[e.TILEMAP_CODE]=h.ts),p},t.parseCodeCards=a,t.parseCodeCardsHtml=function(t){let n,i=[];return Array.from(t.children).forEach((e=>{"UL"===e.tagName||"OL"===e.tagName?(n||(n={}),Array.from(e.querySelectorAll("li")).forEach((e=>{const t=e.innerText,i=/^\s*(\w+)\s*:\s*(.*)$/.exec(t);if(i){const e=i[1];n[e]=i[2].trim(),"flags"===e&&(n[e]=n[e].split(/,\s*/))}}))):"HR"==e.tagName&&(n&&i.push(n),n=void 0)})),n&&i.push(n),0===i.length&&"CODE"===t.tagName&&(i=e.Util.jsonTryParse(t.textContent)),!!(null==i?void 0:i.length)&&i},t.parseGalleryMardown=o,t.loadGalleryAsync=function(t){return e.Cloud.markdownAsync(t).then((e=>o(e)))},t.codeCardsToMarkdown=function(e){return`### ~ codecard\n\n${(e||[]).map((e=>Object.keys(e).filter((t=>!!e[t])).map((t=>"otherActions"===t?e[t].map((e=>`* otherAction: ${e.url}, ${e.editor||""}, ${e.cardType||""}`)).join("\n"):`* ${t}: ${e[t]}`)).join("\n"))).join("\n\n---\n\n")}\n\n### ~\n`}}(e.gallery||(e.gallery={}))}(pxt||(pxt={})),function(e){e.GDBServer=class{constructor(t){this.io=t,this.q=new e.U.PromiseQueue,this.dataBuf="",this.numSent=0,this.pktSize=400,this.trace=!1,this.bmpMode=!0,this.targetInfo="",this.onEvent=e=>{},this.io.onData=e=>this.onData(e)}onData(t){for(this.dataBuf+=e.U.uint8ArrayToString(t);this.dataBuf.length>0;){let e=this.dataBuf[0];if("+"==e)this.dataBuf=this.dataBuf.slice(1);else if("$"==e||"%"==e){let t=this.decodeResp(this.dataBuf.slice(1));if(null==t)break;"$"==e?(this.io.sendPacketAsync(this.buildCmd("+")),this.onResponse?this.onResponse(t):this.numSent>0&&this.io.error("unexpected response: "+t)):this.onEvent(t)}else this.io.error("invalid character: "+e)}}buildCmd(t){if("+"==t)return e.U.stringToUint8Array(t);let n="";for(let e=0;e<t.length;++e){let i=t.charAt(e);"}"==i||"#"==i||"$"==i?(n+="}",n+=String.fromCharCode(32^i.charCodeAt(0))):n+=i}let i=0;t=n;for(let e=0;e<t.length;++e)i=i+t.charCodeAt(e)&255;return n="$"+t+"#"+("0"+i.toString(16)).slice(-2),e.U.stringToUint8Array(n)}decodeResp(e){let t="";for(let n=0;n<e.length;++n){let i=e[n];if("}"==i)++n,t+=String.fromCharCode(32^e.charCodeAt(n));else if("*"==i){++n;let i=e.charCodeAt(n)-29,s=t.charAt(t.length-1);for(;i-- >0;)t+=s}else{if("#"==i){return 2==e.slice(n+1,n+3).length?(this.dataBuf=e.slice(n+3),t):null}t+=i}}return null}sendCmdOKAsync(e){return this.sendCmdAsync(e,(e=>"OK"==e))}error(e){this.io.error(e),this.io.disconnectAsync()}sendCmdAsync(t,n){this.numSent++;const i=this.buildCmd(t);return this.q.enqueue("one",(()=>null===n?this.io.sendPacketAsync(i).then((()=>null)):new Promise((s=>{this.onResponse=i=>{this.onResponse=null,this.trace&&e.log(`GDB: '${t}' -> '${i}'`),void 0===n||n(i)||this.error(`Invalid GDB command response: '${t}' -> '${i}'`),s(i)},this.io.sendPacketAsync(i)}))))}sendRCmdAsync(t){return this.sendMCmdAsync("qRcmd,"+(n=t,e.U.toHex(e.U.stringToUint8Array(n))));var n}sendMCmdAsync(t){this.numSent++;const n=this.buildCmd(t);let i="";return this.q.enqueue("one",(()=>new Promise((s=>{this.onResponse=n=>{var r;"OK"!=n&&"O"==n[0]?i+=(r=n.slice(1),e.U.uint8ArrayToString(e.U.fromHex(r))):("OK"!=n&&(i+=" - "+n),this.onResponse=null,this.trace&&e.log(`Final GDB: '${t}' -> '${i}'`),s(i))},this.io.sendPacketAsync(n)}))))}write32Async(t,n){let i=new Uint8Array(4);return e.HF2.write32(i,0,n),this.writeMemAsync(t,i)}writeMemAsync(t,n){const i=this.pktSize/2-10;return e.U.assert(n.length<i),this.sendCmdOKAsync("M"+t.toString(16)+","+n.length.toString(16)+":"+e.U.toHex(n)).then((e=>{console.log(e)}))}readMemAsync(t,n){const i=this.pktSize/2-6;if(n>i){const s=new Uint8Array(n),r=a=>{const o=Math.min(n-a,i);return 0==o?Promise.resolve(s):this.readMemAsync(t+a,o).then((t=>(e.U.memcpy(s,a,t),r(a+o))))};return r(0)}return this.sendCmdAsync("m"+t.toString(16)+","+n.toString(16)).then((t=>e.U.fromHex(t)))}initBMPAsync(){return Promise.resolve().then((()=>this.sendRCmdAsync("swdp_scan"))).then((e=>(this.targetInfo=e,this.sendCmdAsync("vAttach;1",(e=>"T"==e[0]))))).then((()=>{}))}initAsync(){return e.U.delay(1e3).then((()=>this.sendCmdAsync("!"))).then((()=>this.sendCmdAsync("qSupported"))).then((t=>{let n={};return t=(t=";"+t+";").replace(/;([^;]+)[=:]([^:;]+)/g,((e,t,i)=>(n[t]=i,";"))),this.pktSize=parseInt(n.PacketSize)||1024,e.log("GDB-server caps: "+JSON.stringify(n)+" "+t.replace(/;+/g,";")),this.bmpMode?this.initBMPAsync():this.sendCmdAsync("c").then((()=>{}))}))}}}(pxt||(pxt={})),function(e){!function(t){function n(){var n,i;return!!t.forceProxy||!e.U.isNodeJS&&!(null===(i=null===(n=null==e?void 0:e.appTarget)||void 0===n?void 0:n.cloud)||void 0===i?void 0:i.noGithubProxy)}t.token=null,t.forceProxy=!1;const i={};function s(n){var i;return n.method=null!==(i=n.method)&&void 0!==i?i:"GET",function i(s){var r;const a=e.U.clone(n);t.token&&(a.headers||(a.headers={}),a.url==P?a.headers.Authorization=`bearer ${t.token}`:(a.url=e.BrowserUtils.cacheBustingUrl(a.url),a.headers.Authorization=`token ${t.token}`));return a.allowHttpErrors=null!==(r=a.allowHttpErrors)&&void 0!==r&&r,e.U.requestAsync(a).catch((n=>{if(e.tickEvent("github.error",{statusCode:n.statusCode}),t.handleGithubNetworkError){if(t.handleGithubNetworkError(a,n))return i(!1)}throw n}))}(t.token)}function r(e){return s({url:e,method:"GET"}).then((e=>e.json))}function a(t){return e.Cloud.apiRequestWithCdnAsync({url:"gh/"+t,forceLiveEndpoint:!0}).then((e=>e.json))}function o(t){e.log(`github proxy error: ${t.message}`),e.debug(t)}t.isOrgAsync=function(e){return s({url:`https://api.github.com/orgs/${e}`,method:"GET",allowHttpErrors:!0}).then((e=>200==e.statusCode))};class l{constructor(){this.configs={},this.packages={}}proxyWithCdnLoadPackageAsync(t,n){const i=`${t}/${n}`;let s=this.packages[i];if(s)return e.debug(`github cache ${t}/${n}/text`),Promise.resolve(s);const r=E(t);return a(U(r.slug,n,r.fileName,"text")).then((e=>this.packages[i]={files:e}))}cacheConfig(t,n){const i=e.Package.parseAndValidConfig(n);return this.configs[t]=i,e.U.clone(i)}async loadConfigAsync(t,i){i||(i="master");const s=`${t}/${i}`;let r=this.configs[s];if(r)return e.debug(`github cache ${t}/${i}/config`),e.U.clone(r);if(n())try{const n=await this.proxyWithCdnLoadPackageAsync(t,i);return this.cacheConfig(s,n.files[e.CONFIG_NAME])}catch(e){o(e)}const a=await u(t,i,e.CONFIG_NAME);return this.cacheConfig(s,a)}async loadPackageAsync(t,i){if(i||(i="master"),n())try{return await this.proxyWithCdnLoadPackageAsync(t,i).then((t=>e.U.clone(t)))}catch(e){o(e)}return await this.githubLoadPackageAsync(t,i)}githubLoadPackageAsync(t,n){return m(t,n).then((i=>{const s=`${t}/${i}`;let r=this.packages[s];return r?(e.debug(`github cache ${t}/${n}/text`),Promise.resolve(e.U.clone(r))):(e.log(`Downloading ${t}/${n} -> ${i}`),u(t,i,e.CONFIG_NAME).then((n=>{const r={files:{}};r.files[e.CONFIG_NAME]=n;const a=JSON.parse(n);return e.U.promiseMapAll(e.allPkgFiles(a).slice(1),(e=>u(t,i,e).then((t=>{r.files[e]=t})))).then((()=>(this.packages[s]=r,e.U.clone(r))))})))}))}}function c(t,n,r){return s({url:"https://api.github.com/repos/"+U(t.slug,"contents",t.fileName,r+"?ref="+n),method:"GET"}).then((n=>{const s=n.json;return i[t.slug]=!0,s&&"base64"==s.encoding&&null!=s.content?atob(s.content):e.U.httpGetTextAsync(s.download_url)}))}function u(t,n,s){const r=E(t);return i[r.slug]?c(r,n,s):e.U.requestAsync({url:"https://raw.githubusercontent.com/"+U(r.slug,n,r.fileName,s),allowHttpErrors:!0}).then((e=>200==e.statusCode?e.text:c(r,n,s)))}function d(e,t,n,i){return s({url:/^https:/.test(e)?e:"https://api.github.com/repos/"+e,headers:n,method:i||"POST",data:t,successCodes:[200,201,202,204]}).then((e=>e.json))}function h(e,t){let n=1;for(;e.refs[t+n];)n++;return t+n}async function p(e,t,n){return await d(e+"/git/refs",{ref:"refs/heads/"+t,sha:n}),t}function f(i,s="tags",a,o){const l=E(i),c=(u=a,!!t.forceProxy||!(t.token&&!u)&&n());var u;let d=null;const h=c?e.U.httpGetJsonAsync(e.BrowserUtils.cacheBustingUrl(`${e.Cloud.apiRoot}gh/${l.slug}/refs${o?"?nocache=1":""}`)).then((t=>{let n=Object.keys(t.refs).filter((t=>e.U.startsWith(t,"refs/"+s+"/"))).map((e=>({ref:e,object:{sha:t.refs[e]}})));return d=t.refs.HEAD,n})):r(`https://api.github.com/repos/${l.slug}/git/refs/${s}/?per_page=100`);let p=e=>e.replace(/^refs\/[^\/]+\//,"");return h.then((t=>{t.sort(((t,n)=>e.semver.strcmp(p(t.ref),p(n.ref))));let n={};for(let e of t)n[p(e.ref)]=e.object.sha;return{refs:n,head:d}}),(e=>404==e.statusCode?{refs:{}}:Promise.reject(e)))}function g(e){return"commit"==e.object.type?Promise.resolve(e.object.sha):"tag"==e.object.type?r(e.object.url).then((e=>"commit"==e.object.type?e.object.sha:Promise.reject(new Error("Bad type (2nd order) "+e.object.type)))):Promise.reject(new Error("Bad type "+e.object.type))}function m(e,t){if(/^[a-f0-9]{40}$/.test(t))return Promise.resolve(t);const n=E(e);return r(`https://api.github.com/repos/${n.slug}/git/refs/tags/${t}`).then(g,(e=>r(`https://api.github.com/repos/${n.slug}/git/refs/heads/${t}`).then(g)))}function b(e,n="master"){return t.db.loadConfigAsync(e,n)}function y(n,i){const s=E(n);return s?x(s,i)?(e.tickEvent("github.download.banned"),e.log("Github repo is banned"),Promise.resolve(void 0)):t.db.loadPackageAsync(s.fullName,s.tag).then((t=>{const s=N(i,n);if(s){const i=e.Package.parseAndValidConfig(t.files[e.CONFIG_NAME]);i&&(e.log(`auto-disable ${s.join(",")} due to targetconfig entry for ${n}`),i.disablesVariants=s,t.files[e.CONFIG_NAME]=e.Package.stringifyConfig(i))}return t})):(e.log("Unknown GitHub syntax"),Promise.resolve(void 0))}let v;function w(t){return e.Cloud.cdnApiUrl(`gh/${t.fullName}/icon`)}function k(e,t){var n;if(!e)return;const i={owner:e.owner.login.toLowerCase(),slug:e.full_name.toLowerCase(),fullName:((null==t?void 0:t.fullName)||e.full_name).toLowerCase(),fileName:null===(n=null==t?void 0:t.fileName)||void 0===n?void 0:n.toLocaleLowerCase(),name:e.name,description:e.description,defaultBranch:e.default_branch,tag:null==t?void 0:t.tag,updatedAt:Math.round(new Date(e.updated_at).getTime()/1e3),fork:e.fork,private:e.private};return i.status=A(i,null==t?void 0:t.config),i}function A(e,t){return e?x(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 x(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,i){const s=E(t);if(!s)return;const l=A(s,i);if(l==v.Banned)return;if(n())try{return await function(t,n){return a(t.slug).then((e=>{if(e)return{github:!0,owner:t.owner,fullName:t.fullName,fileName:t.fileName,slug:t.slug,name:t.fileName?`${e.name}-${t.fileName}`:e.name,description:e.description,defaultBranch:e.defaultBranch||"master",tag:t.tag,status:n}})).catch((t=>{e.reportException(t)}))}(s,l)}catch(e){o(e)}return k(await r("https://api.github.com/repos/"+s.slug),{config:i,fullName:s.fullName,fileName:s.fileName,tag:s.tag})}function E(e){if(!e)return;e=(e=e.trim()).replace(/\/$/,"");const t=/^https:\/\/([^./#]+)\.github\.io\/([^/#]+)\/?$/i.exec(e);t&&(e=`github:${t[1]}/${t[2]}`),e=(e=(e=e.replace(/^github:/i,"")).replace(/^https:\/\/github\.com\//i,"")).replace(/\.git\b/i,"");const n=/^([^#\/:]+)\/([^#\/:]+)(\/([^#]+))?(#([^\/:]*))?$/.exec(e);if(!n)return;const i=n[1],s=n[2];let r=n[4];const a=n[6],o=r&&/^tree\/([^\/]+\/)/.exec(r);return o&&(r=r.slice(o[0].length)),{owner:i,project:s,slug:U(i,s),fullName:U(i,s,r),tag:a,fileName:r}}function C(e){return!!e&&"github:"==e.slice(0,7)}function I(e){return e?"github:"+e.fullName.toLowerCase()+"#"+(e.tag||"master"):void 0}function U(...e){return e.filter((e=>!!e)).join("/")}function S(t,n){if(!t||!t.upgrades)return null;const i=E(n);return i?e.U.lookup(t.upgrades,i.fullName.toLowerCase()):null}function N(e,t){const n=S(e,t),i=/^dv:(.*)/.exec(n);if(i){const e=i[1].split(/,/);return e.some((e=>!/^\w+$/.test(e)))?null:e}return null}t.MemoryGithubDb=l,t.downloadTextAsync=u,t.db=new l,t.authenticatedUserAsync=function(){return t.token?r("https://api.github.com/user"):Promise.resolve(void 0)},t.getCommitsAsync=function(e,t){return r("https://api.github.com/repos/"+E(e).slug+"/commits?sha="+t).then((e=>e.map((e=>{const t=e.commit;return t.url=e.url,t.sha=e.sha,t}))))},t.getCommitAsync=function(e,t){return r("https://api.github.com/repos/"+E(e).slug+"/git/commits/"+t).then((e=>r(e.tree.url+"?recursive=1").then((t=>(e.tree=t,e)))))},t.createObjectAsync=function(e,t,n){return d(E(e).slug+"/git/"+t+"s",n).then((e=>e.sha))},t.postCommitComment=function(e,t,n,i,s){return d(`${E(e).slug}/commits/${t}/comments`,{body:n,path:i,position:s}).then((e=>e.id))},t.fastForwardAsync=async function(e,t,n){const i=E(e);return 200==(await s({url:`https://api.github.com/repos/${i.slug}/git/refs/heads/${t}`,method:"PATCH",allowHttpErrors:!0,data:{sha:n,force:!1}})).statusCode},t.putFileAsync=async function(t,n,i){const r=E(t);await s({url:`https://api.github.com/repos/${e.github.join(r.slug,"contents",r.fileName,n)}`,method:"PUT",allowHttpErrors:!0,data:{message:lf("Initialize empty repo"),content:btoa(e.U.toUTF8(i)),branch:"master"},successCodes:[201]})},t.createTagAsync=async function(e,t,n){await d(e+"/git/refs",{ref:"refs/tags/"+t,sha:n})},t.createReleaseAsync=async function(e,t,n){await d(e+"/releases",{tag_name:t,target_commitish:n,name:t,draft:!1,prerelease:!1})},t.createPRFromBranchAsync=async function(e,t,n,i,s){const r=await d(e+"/pulls",{title:i,body:s||lf("Automatically created from MakeCode."),head:n,base:t,maintainer_can_modify:!0});return null==r?void 0:r.html_url},t.mergeAsync=function(t,n,i,r){return s({url:`https://api.github.com/repos/${E(t).slug}/merges`,method:"POST",successCodes:[201,204,409],data:{base:n,head:i,commit_message:r}}).then((n=>{if(201==n.statusCode||204==n.statusCode)return n.json.sha;if(409==n.statusCode)return null;throw e.U.userError(lf("Cannot merge in github.com/{1}; code: {2}",t,n.statusCode))}))},t.getRefAsync=function(e,t){return r("https://api.github.com/repos/"+e+"/git/refs/heads/"+(t=t||"master")).then(g).catch((e=>{404!=e.statusCode&&Promise.reject(e)}))},t.getNewBranchNameAsync=async function(e,t="patch-"){return h(await f(e,"heads"),t)},t.createNewBranchAsync=p,t.forkRepoAsync=async function(t,n,i="pr-"){const s=E(t),r=k(await d(`${s.slug}/forks`,{}),{fullName:s.fullName,fileName:s.fileName}),a=Date.now()+3e5;let o=null;for(;!o&&Date.now()<a;){await e.U.delay(1e3);try{o=await f(r.slug,"heads")}catch(e){}}if(!o)throw new Error(lf("Timeout waiting for fork"));const l=h(o,i);return await p(r.slug,l,n),r.fullName+"#"+l},t.listRefsAsync=function(e,t="tags",n,i){return f(e,t,n,i).then((e=>Object.keys(e.refs)))},t.listRefsExtAsync=f,t.pkgConfigAsync=b,t.downloadPackageAsync=y,t.downloadLatestPackageAsync=async function(t){const n=await e.packagesConfigAsync(),i=await e.github.latestVersionAsync(t.slug,n),s=`${t.fullName}#${i}`;return await e.github.downloadPackageAsync(s,n),{version:`github:${s}`,config:await b(t.fullName,i)}},t.cacheProjectDependenciesAsync=async function(t){var n;const i=null===(n=Object.keys(t.dependencies))||void 0===n?void 0:n.filter((e=>C(t.dependencies[e])));if(i.length){const n=await e.packagesConfigAsync();await Promise.all(i.map((async e=>{const i=t.dependencies[e];if(!await y(i,n))throw new Error(lf("Cannot load extension {0} from {1}",e,i))})))}},function(e){e[e.Unknown=0]="Unknown",e[e.Approved=1]="Approved",e[e.Banned=2]="Banned"}(v=t.GitRepoStatus||(t.GitRepoStatus={})),t.listUserReposAsync=function(){return _('{\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),i=t.readme&&t.readme.text;return!!n&&(n.supportedTargets?n.supportedTargets.indexOf(e.appTarget.id)>-1:i&&i.indexOf("PXT/"+e.appTarget.id)>-1)})).map((e=>k(e,{fullName:e.full_name})))))},t.createRepoAsync=function(e,t,n){return d("https://api.github.com/user/repos",{name:e,description:t,private:!!n,has_issues:!0,has_projects:!1,has_wiki:!1,allow_rebase_merge:!1,allow_merge_commit:!0,delete_branch_on_merge:!1}).then((e=>k(e)))},t.enablePagesAsync=async function(t){const n=E(t);let i;try{const e=await r(`https://api.github.com/repos/${n.slug}/pages`);e&&(i=e.html_url)}catch(e){}if(!i)try{i=(await d(`https://api.github.com/repos/${n.slug}/pages`,{source:{branch:"master",path:"/"}},{Accept:"application/vnd.github.switcheroo-preview+json"})).html_url}catch(t){e.tickEvent("github.pages.error"),e.reportException(t)}if(i){const n=await r(`https://api.github.com/repos/${t}`);if(n&&!n.homepage)try{await d(`https://api.github.com/repos/${t}`,{homepage:i},void 0,"PATCH")}catch(t){e.tickEvent("github.homepage.error")}}},t.repoIconUrl=function(e){if(e.status==v.Approved)return w(e)},t.mkRepoIconUrl=w,t.repoStatus=A,t.repoAsync=T,t.searchAsync=function(t,n){if(!n)return Promise.resolve([]);let i=t.split("|").map(E).filter((e=>!!e));return i.length>0?Promise.all(i.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=>k(e,{config:n,fullName:e.full_name}))).filter((e=>e.status==v.Approved||n.allowUnapproved&&e.status==v.Unknown)).filter((t=>!e.appTarget.appTheme.githubUrl||`https://github.com/${t.fullName}`!=e.appTarget.appTheme.githubUrl.toLowerCase())))).catch((e=>[]))},t.parseRepoId=E,t.toGithubDependencyPath=function(e,t){let n="github:"+e;return t&&(n+="#"+t),n},t.isGithubId=C,t.stringifyRepo=I,t.normalizeRepoId=function(e){const t=E(e);if(t)return t.tag=t.tag||"master",I(t)},t.join=U,t.upgradedPackageReference=function(t,n){const i=S(t,n);if(!i)return null;const s=/^min:(.*)/.exec(i),r=s&&e.semver.tryParse(s[1]);if(r){const t=E(n),i=e.semver.tryParse(t.tag);return i&&e.semver.cmp(i,r)<0?(t.tag=s[1],e.debug(`upgrading ${n} to ${s[1]}`),I(t)):(i||e.log(`not upgrading ${n} - cannot parse version`),null)}return N(t,n)||e.log(`invalid upgrade rule: ${n} -> ${i}`),n},t.upgradedPackageId=function(e,t){const n=N(e,t);return n?t+"?dv="+n.join(","):t},t.latestVersionAsync=function(t,n,i,s){const r=E(t);return r?T(r.slug,n).then((t=>{if(t)return f(t.slug,"tags",i,s).then((i=>{let s=Object.keys(i.refs);s=e.semver.sortLatestTags(s);const a=e.appTarget.versions&&e.semver.tryParse(e.appTarget.versions.target);if(a&&n.releases&&n.releases["v"+a.major]){const i=n.releases["v"+a.major].map((t=>e.github.parseRepoId(t))).filter((e=>e&&e.fullName.toLowerCase()==r.fullName.toLowerCase()))[0];if(i){if(s.some((e=>e==i.tag)))return e.debug(`approved release ${i.fullName}#${i.tag} for v${a.major}`),Promise.resolve(i.tag);e.reportError("packages",`approved release ${i.fullName}#${i.tag} for v${a.major} not found anymore`,{repo:t.fullName})}}return s[0]?Promise.resolve(s[0]):i.head||m(t.slug,t.defaultBranch)}))})):Promise.resolve(null)},t.resolveMonoRepoVersions=function(n){n=e.Util.clone(n);const i={};return Object.keys(n).map((e=>({id:e,ghid:t.parseRepoId(n[e])}))).filter((e=>{var t;return null===(t=e.ghid)||void 0===t?void 0:t.tag})).forEach((t=>{const{id:n,ghid:s}=t;let r=i[s.slug];r||(r=i[s.slug]={tag:s.tag,deps:[]}),r.deps.push(t),e.semver.strcmp(r.tag,s.tag)<0&&(e.debug(`dep: resolve later monorepo tag to ${e.github.stringifyRepo(s)}`),r.tag=s.tag)})),e.U.values(i).forEach((t=>t.deps.forEach((i=>{i.ghid.tag!==t.tag&&(e.debug(`dep: ${e.github.stringifyRepo(i.ghid)} -> ${t.tag}`),i.ghid.tag=t.tag,n[i.id]=e.github.stringifyRepo(i.ghid))})))),n},t.GIT_JSON=".git.json";const P="https://api.github.com/graphql";function _(e){const t=JSON.stringify({query:e});return d(P,t)}t.lookupFile=function(e,t,n){if(!t)return null;const i=U(e.fileName,n);return t.tree.tree.find((e=>e.path==i))},t.ghGraphQLQueryAsync=_,t.findPRNumberforBranchAsync=function(e,t){const n=E(e);return _(`\n{\n repository(owner: ${JSON.stringify(n.owner)}, name: ${JSON.stringify(n.project)}) {\n pullRequests(last: 1, states: [OPEN, MERGED], headRefName: ${JSON.stringify(t)}) {\n edges {\n node {\n number\n state\n mergeable\n baseRefName\n url\n isDraft\n }\n }\n }\n }\n}\n`).then((e=>{const t=e.data.repository.pullRequests.edges[0];if(t&&t.node){const e=t.node;return{number:e.number,mergeable:e.mergeable,state:e.state,title:e.title,url:e.url,base:e.baseRefName}}return{number:-1}}))},t.getPagesStatusAsync=function(e){return r(`https://api.github.com/repos/${e}/pages`).catch((e=>({status:null})))}}(e.github||(e.github={}))}(pxt||(pxt={})),function(e){let t;e.REFCNT_FLASH="0xfffe",e.VTABLE_MAGIC=249,e.ValTypeObject=4,function(e){e[e.BoxedString=1]="BoxedString",e[e.BoxedNumber=2]="BoxedNumber",e[e.BoxedBuffer=3]="BoxedBuffer",e[e.RefAction=4]="RefAction",e[e.RefImage=5]="RefImage",e[e.RefCollection=6]="RefCollection",e[e.RefRefLocal=7]="RefRefLocal",e[e.RefMap=8]="RefMap",e[e.RefMImage=9]="RefMImage",e[e.MMap=10]="MMap",e[e.BoxedString_SkipList=11]="BoxedString_SkipList",e[e.BoxedString_ASCII=12]="BoxedString_ASCII",e[e.ZPin=13]="ZPin",e[e.User0=16]="User0"}(t=e.BuiltInType||(e.BuiltInType={}))}(pxt||(pxt={})),function(e){!function(t){function n(e,t,n){e[t+0]=n>>0&255,e[t+1]=n>>8&255,e[t+2]=n>>16&255,e[t+3]=n>>24&255}function i(e,t,n){e[t+0]=n>>0&255,e[t+1]=n>>8&255}function s(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function r(e,t){return e[t]|e[t+1]<<8}function a(e){let t=new Uint8Array(4*e.length);for(let i=0;i<e.length;++i)n(t,4*i,e[i]);return t}t.HF2_CMD_BININFO=1,t.HF2_MODE_BOOTLOADER=1,t.HF2_MODE_USERSPACE=2,t.HF2_CMD_INFO=2,t.HF2_CMD_RESET_INTO_APP=3,t.HF2_CMD_RESET_INTO_BOOTLOADER=4,t.HF2_CMD_START_FLASH=5,t.HF2_CMD_WRITE_FLASH_PAGE=6,t.HF2_CMD_CHKSUM_PAGES=7,t.HF2_CMD_READ_WORDS=8,t.HF2_CMD_WRITE_WORDS=9,t.HF2_CMD_DMESG=16,t.HF2_FLAG_SERIAL_OUT=128,t.HF2_FLAG_SERIAL_ERR=192,t.HF2_FLAG_CMDPKT_LAST=64,t.HF2_FLAG_CMDPKT_BODY=0,t.HF2_FLAG_MASK=192,t.HF2_SIZE_MASK=63,t.HF2_STATUS_OK=0,t.HF2_STATUS_INVALID_CMD=1,t.HF2_STATUS_EXEC_ERR=2,t.HF2_STATUS_EVENT=128,t.HF2_CMD_JDS_CONFIG=32,t.HF2_CMD_JDS_SEND=33,t.HF2_EV_JDS_PACKET=8388640,t.CUSTOM_EV_JACDAC="jacdac",t.HF2_EV_MASK=8388608,t.write32=n,t.write16=i,t.read32=s,t.read16=r,t.encodeU32LE=a,t.decodeU32LE=function(e){let t=[];for(let n=0;n<e.length;n+=4)t.push(s(e,n));return t};let o=!1;function l(t){o?e.log("HF2: "+t):e.debug("HF2: "+t)}t.enableLog=function(){o=!0};class c{constructor(n){var i;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===(i=e.appTarget.appTheme.downloadDialogTheme)||void 0===i?void 0:i.deviceIcon)||"usb",this.msgs=new e.U.PromiseBuffer,this.eventHandlers={},this.jacdacAvailable=!1,this.onSerial=(e,t)=>{},this.onCustomEvent=(e,t)=>{};let r=[];n.onDeviceConnectionChanged=e=>this.disconnectAsync().then((()=>e&&this.reconnectAsync())),n.onSerial=(e,t)=>this.onSerial(e,t),n.onData=i=>{let s=i[0]&t.HF2_FLAG_MASK,a=63&i[0],o=new Uint8Array(a);if(e.U.memcpy(o,0,i,1,a),s&t.HF2_FLAG_SERIAL_OUT)this.onSerial(o,s==t.HF2_FLAG_SERIAL_ERR);else if(r.push(o),s!=t.HF2_FLAG_CMDPKT_BODY){e.U.assert(s==t.HF2_FLAG_CMDPKT_LAST);let i=0;for(let e of r)i+=e.length;let a=new Uint8Array(i),o=0;for(let t of r)e.U.memcpy(a,o,t),o+=t.length;r=[],a[2]&t.HF2_STATUS_EVENT?n.onEvent(a):this.msgs.push(a)}},n.onEvent=t=>{let n=s(t,0),i=e.U.lookup(this.eventHandlers,n+"");i?i(t.slice(4)):l("unhandled event: "+n.toString(16))},n.onError=e=>{l("recv error: "+e.message),this.autoReconnect&&(this.autoReconnect=!1,this.reconnectAsync().then((()=>{this.autoReconnect=!0}),(e=>{l("reconnect error: "+e.message)})))},this.onEvent(t.HF2_EV_JDS_PACKET,(e=>{this.onCustomEvent(t.CUSTOM_EV_JACDAC,e)}))}resetState(){this.lock=new e.U.PromiseQueue,this.info=null,this.infoRaw=null,this.pageSize=null,this.flashSize=null,this.maxMsgSize=63,this.bootloaderMode=!1,this.msgs.drain()}onEvent(n,i){e.U.assert(!!(n&t.HF2_EV_MASK)),this.eventHandlers[n+""]=i}sendCustomEventAsync(e,n){return e==t.CUSTOM_EV_JACDAC?this.jacdacAvailable?this.talkAsync(t.HF2_CMD_JDS_SEND,n).then((()=>{})):Promise.resolve():Promise.reject(new Error("invalid custom event type"))}reconnectAsync(){return this.resetState(),l(`reconnect raw=${this.rawMode}`),this.io.reconnectAsync().then((()=>this.initAsync())).catch((t=>{if(this.reconnectTries<5)return this.reconnectTries++,l(`error ${t.message}; reconnecting attempt #${this.reconnectTries}`),e.U.delay(500).then((()=>this.reconnectAsync()));throw t}))}disconnectAsync(){return l("disconnect"),this.io.disconnectAsync()}error(e){return this.io.error(e)}talkAsync(s,a){if(this.io.talksAsync)return this.io.talksAsync([{cmd:s,data:a}]).then((e=>e[0]));let o=8;a&&(o+=a.length);let c=new Uint8Array(o),u=65535&++this.cmdSeq;n(c,0,s),i(c,4,u),i(c,6,0),a&&e.U.memcpy(c,8,a,0,a.length);let d=0,h=()=>this.msgs.shiftAsync(1e3).then((e=>{if(r(e,0)!=u){if(d<3)return d++,l(`message out of sync, (${u} vs ${r(e,0)}); will re-try`),h();this.error("out of sync")}let n="";switch(e[3]&&(n="; info="+e[3]),e[2]){case t.HF2_STATUS_OK:return e.slice(4);case t.HF2_STATUS_INVALID_CMD:this.error("invalid command"+n);break;case t.HF2_STATUS_EXEC_ERR:this.error("execution error"+n);break;default:this.error("error "+e[2]+n)}return null}));return this.sendMsgAsync(c).then(h)}sendMsgAsync(e){return this.sendMsgCoreAsync(e)}sendSerialAsync(e,t=!1){return this.io.sendSerialAsync?this.io.sendSerialAsync(e,t):this.sendMsgCoreAsync(e,t?2:1)}sendMsgCoreAsync(e,n=0){let i=new Uint8Array(64),s=r=>{let a=e.length-r;if(a<=0)return Promise.resolve();a>63?(a=63,i[0]=t.HF2_FLAG_CMDPKT_BODY):i[0]=t.HF2_FLAG_CMDPKT_LAST,n&&(i[0]=1==n?t.HF2_FLAG_SERIAL_OUT:t.HF2_FLAG_SERIAL_ERR),i[0]|=a;for(let t=0;t<a;++t)i[t+1]=e[r+t];return this.io.sendPacketAsync(i).then((()=>s(r+a)))};return this.lock.enqueue("out",(()=>s(0)))}switchToBootloaderAsync(){return this.bootloaderMode?Promise.resolve():(l("Switching into bootloader mode"),this.io.isSwitchingToBootloader&&this.io.isSwitchingToBootloader(),this.maybeReconnectAsync().then((()=>this.talkAsync(t.HF2_CMD_START_FLASH).then((()=>{}),(e=>this.talkAsync(t.HF2_CMD_RESET_INTO_BOOTLOADER).then((()=>{}),(e=>{})).then((()=>this.reconnectAsync().catch((e=>{throw"devicenotfound"===e.type&&(e.type="repairbootloader"),e})))))))).then((()=>this.initAsync())).then((()=>{this.bootloaderMode||this.error("cannot switch into bootloader mode")})))}isFlashing(){return!!this.flashing}reflashAsync(t){l("reflash"),e.U.assert(e.appTarget.compile.useUF2);const n=t.outfiles[pxtc.BINARY_UF2],i=pxtc.UF2.parseFile(e.Util.stringToUint8Array(atob(n)));return this.flashing=!0,this.io.reconnectAsync().then((()=>this.flashAsync(i))).then((()=>e.U.delay(100))).finally((()=>this.flashing=!1)).then((()=>this.reconnectAsync()))}writeWordsAsync(n,i){return e.U.assert(i.length<=64),this.talkAsync(t.HF2_CMD_WRITE_WORDS,a([n,i.length].concat(i))).then((()=>{}))}readWordsAsync(i,s){let r=new Uint8Array(8);return n(r,0,i),n(r,4,s),e.U.assert(s<=64),this.talkAsync(t.HF2_CMD_READ_WORDS,r)}pingAsync(){return this.rawMode?Promise.resolve():this.talkAsync(t.HF2_CMD_BININFO).then((e=>{}))}maybeReconnectAsync(){return this.pingAsync().catch((e=>this.reconnectAsync().then((()=>this.pingAsync()))))}flashAsync(i){let s=Date.now(),r=0,a=s=>{if(s>=i.length)return Promise.resolve();let r=i[s],o=new Uint8Array(4+r.payloadSize);return n(o,0,r.targetAddr),e.U.memcpy(o,4,r.data,0,r.payloadSize),this.talkAsync(t.HF2_CMD_WRITE_FLASH_PAGE,o).then((()=>a(s+1)))};return this.switchToBootloaderAsync().then((()=>{let e=256*i.length;return l(`Starting flash (${Math.round(e/1024)}kB).`),r=Date.now(),this.pageSize>16384?i:u(i,((e,t)=>this.readWordsAsync(e,t)))})).then((e=>{if(e.length!=i.length){let t=256*(i=e).length;l(`Performing partial flash (${Math.round(t/1024)}kB).`)}})).then((()=>a(0))).then((()=>{let e=Date.now(),t=e-s,n=e-r;l(`Flashing done at ${Math.round(256*i.length/n*1e3/1024)} kB/s in ${t}ms (reset ${t-n}ms). Resetting.`)})).then((()=>this.talkAsync(t.HF2_CMD_RESET_INTO_APP).catch((e=>{})))).then((()=>{}))}initAsync(){return this.rawMode?Promise.resolve():Promise.resolve().then((()=>this.talkAsync(t.HF2_CMD_BININFO))).then((e=>(this.bootloaderMode=e[0]==t.HF2_MODE_BOOTLOADER,this.pageSize=s(e,4),this.flashSize=s(e,8)*this.pageSize,this.maxMsgSize=s(e,12),this.familyID=s(e,16),l(`Connected; msgSize ${this.maxMsgSize}B; flash ${this.flashSize/1024}kB; ${this.bootloaderMode?"bootloader":"application"} mode; family=0x${this.familyID.toString(16)}`),this.talkAsync(t.HF2_CMD_INFO)))).then((t=>{this.infoRaw=e.Util.fromUTF8Array(t),e.debug("Info: "+this.infoRaw);let n={};("Header: "+this.infoRaw).replace(/^([\w\-]+):\s*([^\n\r]*)/gm,((e,t,i)=>(n[t.replace(/-/g,"")]=i,""))),this.info=n;let i=/v(\d\S+)(\s+(\S+))?/.exec(this.info.Header);this.info.Parsed=i?{Version:i[1],Features:i[3]||""}:{Version:"?",Features:""},l(`Board-ID: ${this.info.BoardID} v${this.info.Parsed.Version} f${this.info.Parsed.Features}`)})).then((()=>this.talkAsync(t.HF2_CMD_JDS_CONFIG,new Uint8Array([1])).then((()=>{this.jacdacAvailable=!0}),(e=>{this.jacdacAvailable=!1})))).then((()=>{this.reconnectTries=0}))}}function u(t,n){if(!e.appTarget.compile.flashChecksumAddr)return Promise.resolve(t);let i=pxtc.UF2.readBytes(t,e.appTarget.compile.flashChecksumAddr,48),r=pxtc.parseChecksumBlock(i);return r?function(t){return e.appTarget.compile.flashChecksumAddr?t(e.appTarget.compile.flashChecksumAddr,12).then((n=>{let i=pxtc.parseChecksumBlock(n);return i?t(i.endMarkerPos,1).then((t=>s(t,0)!=i.endMarker?(e.log("end-marker mismatch"),null):i)):null})):Promise.resolve(null)}(n).then((e=>{if(!e)return t;let n=e.regions.filter((e=>r.regions.some((t=>e.checksum==t.checksum&&e.length==t.length&&e.start==t.start))));if(0==n.length)return t;l("skipping flash at: "+n.map((e=>`${pxtc.assembler.tohex(e.start)} (${e.length/1024}kB)`)).join(", "));let i=e=>n.some((t=>t.start<=e&&e<t.start+t.length));return t.filter((e=>!(i(e.targetAddr)&&i(e.targetAddr+e.payloadSize-1))))})):Promise.resolve(t)}t.Wrapper=c,t.mkHF2PacketIOWrapper=function(t){return e.debug("packetio: wrapper hf2"),new c(t)},t.onlyChangedBlocksAsync=u}(e.HF2||(e.HF2={}))}(pxt||(pxt={})),function(e){!function(t){var n=e.Util,i=e.HF2;const s=i.read32;let r,a,o,l,c,u,d,h,p=!1;function f(e){return e<<2|2}function g(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 m(e,t){if(n.assert(!(3&e)),n.assert(e>=0),e<2097152){let i=new Uint8Array(t);return e-=d.start,n.memcpy(i,0,d.buf,e,t),Promise.resolve(i)}let i=h.maxMsgSize-32;if(t>i){let s=[];for(;t>0;){let n=Math.min(i,t);s.push(m(e,n)),t-=n,e+=n}return Promise.all(s).then(n.uint8ArrayConcat)}return h.readWordsAsync(e,Math.ceil(t/4)).then((e=>e.length>t?e.slice(0,t):e))}function b(t){if("object"!=typeof t||!t)return Promise.resolve(t);if("number"==typeof t.ptr){if(3&t.ptr)return Promise.resolve({unalignedPtr:t.ptr});let s=0;return m(t.ptr,56).then((r=>{s=i.read16(r,2);let a=r.length;return s==e.BuiltInType.BoxedString||s==e.BuiltInType.BoxedBuffer?a=i.read16(r,4)+6:s==e.BuiltInType.BoxedNumber&&(a=12),a>r.length?m(t.ptr+r.length,a-r.length).then((e=>n.uint8ArrayConcat([r,e]))):a<r.length?r.slice(0,a):r})).then((t=>s==e.BuiltInType.BoxedString?n.uint8ArrayToString(t.slice(6)):s==e.BuiltInType.BoxedBuffer?{type:"buffer",data:t.slice(6)}:s==e.BuiltInType.BoxedNumber?new Float64Array(t.buffer.slice(4))[0]:{type:"unknown",tag:s,refcnt:i.read16(t,0),data:t.slice(4)}))}return Promise.resolve(t)}function y(e){let t=[];for(let n of Object.keys(e))t.push(b(e[n]).then((t=>{e[n]=t})));return Promise.all(t).then((()=>{}))}function v(e){let t=r.breakpoints,n=t[0],i=1/0;for(let s of t){let t=e-s.binAddr;t>=0&&t<i&&(i=t,n=s)}return n}function w(e){if(p)return Promise.resolve();let s;return p=!0,T().then((t=>{let a=i.decodeU32LE(e)[0],l={};for(let e of r.procDebugInfo[0].locals){let s=t.globals,r=(()=>{switch(e.type){case"uint32":return i.read32(s,e.index);case"int32":return 0|i.read32(s,e.index);case"uint16":return i.read16(s,e.index);case"int16":return i.read16(s,e.index)<<16>>16;case"uint8":return s[e.index];case"int8":return s[e.index]<<24>>24;default:return null}})();null===r&&(n.assert(0==(3&e.index)),r=g(i.read32(s,e.index))),l[e.name]=r}return c=v(a),s={type:"debugger",subtype:"breakpoint",breakpointId:c.id,globals:l,stackframes:[]},o(),h.talkAsync(1888490768)})).then((e=>{!function(e,t){let i=c.binAddr,s=0,a=r.procDebugInfo.filter((e=>e.codeStartLoc<=i&&i<=e.codeEndLoc))[0];for(;a&&a!=r.procDebugInfo[0];){let r=v(i),o=n.clone(r);o.functionName=a.name,o.argumentNames=a.args&&a.args.map((e=>e.name)),t.stackframes.push({locals:{},funcInfo:o,breakpointId:r.id});let l=t.stackframes[t.stackframes.length-1],c=0;for(let t of a.locals)n.assert(t.index==c++),l.locals[t.name]=g(e[s++]);i=2147483646&e[s++];let d=u[i+""];for(let t of a.args)l.locals[t.name]=g(e[s+(a.args.length-1-t.index)]);if(!d)break;a=d.from,s+=d.stack-a.localsMark}}(i.decodeU32LE(e),s);let t=[s.globals].concat(s.stackframes.map((e=>e.locals)));return n.promiseMapAll(t,y)})).then((()=>t.postMessage(s)))}function k(){p=!1,a=new Promise(((e,t)=>{o=e}))}function A(e=!1){return Promise.resolve().then((()=>h.talkAsync(665147697,i.encodeU32LE([e?1:3])))).then(k)}function x(){return a||(a=Promise.resolve()),a}function T(){return(l?Promise.resolve(l):h.talkAsync(1409050336).then((e=>l={numGlobals:s(e,0),globalsPtr:s(e,4)}))).then((e=>h.readWordsAsync(e.globalsPtr,e.numGlobals))).then((e=>({staticState:l,globals:e})))}t.taggedUndefined=0,t.taggedNull=f(1),t.taggedFalse=f(2),t.taggedTrue=f(16),t.postMessage=e=>console.log(e),t.decodeValue=g,t.heapExpandAsync=b,t.heapExpandMapAsync=y,t.startDebugAsync=function(e,t){return h=t,h.onEvent(915601917,w),(p=!1,r=null,l=null,Promise.resolve()).then((()=>{r=e,u={};let t=[];for(let n of e.procDebugInfo)t[n.idx]=n;for(let n of e.procDebugInfo)for(let e of n.calls)u[e.addr+""]={from:n,to:t[e.procIndex],stack:e.stack}})).then((()=>{let e=r.outfiles[pxtc.BINARY_UF2],t=n.stringToUint8Array(atob(e));return d=pxtc.UF2.toBin(t),h.reflashAsync(r).then((()=>h.reconnectAsync()))})).then((()=>h.talkAsync(287358355).catch((e=>{})))).then((()=>n.delay(200))).then((()=>h.reconnectAsync())).then(k).then(x)},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":A(t)}},t.resumeAsync=A,t.waitForHaltAsync=x,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)),i=n.charCodeAt(0),s=n.charCodeAt(1),r=n.charCodeAt(2);if(135===i&&(i=224|n.charCodeAt(1),s=n.charCodeAt(2)|n.charCodeAt(3)<<8,r=n.charCodeAt(4)|n.charCodeAt(5)<<8,n=n.slice(4)),225!=i&&228!=i)return null;if(!this.palette){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==i)return this.genMonochrome(n,s,r);const a=(e.BrowserUtils.isEdge()||e.BrowserUtils.isIE())&&s<100&&r<100?3:1;return this.genColor(n,s,r,a)}genMonochrome(t,n,i){let s=n+3&-4,r=54+this.palette.length,a=r+s*i,o=new Uint8Array(a);o[0]=66,o[1]=77,e.HF2.write32(o,2,a),e.HF2.write32(o,10,r),e.HF2.write32(o,14,40),e.HF2.write32(o,18,n),e.HF2.write32(o,22,-i),e.HF2.write16(o,26,1),e.HF2.write16(o,28,8),e.HF2.write32(o,38,2835),e.HF2.write32(o,42,2835),e.HF2.write32(o,46,this.palette.length>>2),o.set(this.palette,54);let l=4,c=r,u=1,d=t.charCodeAt(l++);for(let e=0;e<n;++e){c=r+e;for(let e=0;e<i;++e)o[c]=d&u?1:0,c+=s,u<<=1,256==u&&(u=1,d=t.charCodeAt(l++))}return"data:image/bmp;base64,"+btoa(e.U.uint8ArrayToString(o))}genColor(t,n,i,s){const r=n*(s=Math.max(1,0|s)),a=i*s;let o=r<<2,l=138,c=l+o*a,u=new Uint8Array(c);u[0]=66,u[1]=77,e.HF2.write32(u,2,c),e.HF2.write32(u,10,l),e.HF2.write32(u,14,124),e.HF2.write32(u,18,r),e.HF2.write32(u,22,-a),e.HF2.write16(u,26,1),e.HF2.write16(u,28,32),e.HF2.write16(u,30,3),e.HF2.write32(u,38,2835),e.HF2.write32(u,42,2835),e.HF2.write32(u,54,16711680),e.HF2.write32(u,58,65280),e.HF2.write32(u,62,255),e.HF2.write32(u,66,4278190080),u[70]=66,u[71]=71,u[72]=82,u[73]=115;let d=4,h=l,p=!0;for(let e=0;e<r;e++){let n=!1;h=l+(e<<2);let r=d,c=t.charCodeAt(d++),f=n?(c>>4&15)<<2:(15&c)<<2;for(let e=0;e<a;e++)c&&(p=!1),u[h]=this.palette[f],u[h+1]=this.palette[f+1],u[h+2]=this.palette[f+2],u[h+3]=this.palette[f+3],h+=o,e%s==s-1&&(n&&(c=t.charCodeAt(d++)),n=!n,f=n?(c>>4&15)<<2:(15&c)<<2);if(p&&(u[141]=1),e%s==s-1)for(i%2||--d;3&d;)d++;else d=r}return"data:image/bmp;base64,"+btoa(e.U.uint8ArrayToString(u))}}}(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=i();return n&&Object.keys(n).forEach((t=>e[t]=n[t])),e}function i(){const t=e.appTarget.bundledpkgs[e.template.TEMPLATE_PRJ];if(t){const n=e.Util.clone(t);return delete n[e.CONFIG_NAME],n}}t.TS_CONFIG='{\n "compilerOptions": {\n "target": "ES5",\n "noImplicitAny": true,\n "outDir": "built",\n "rootDir": "."\n },\n "exclude": ["pxt_modules/**/*test.ts"]\n}\n',t.defaultFiles=n,t.targetTemplateFiles=i,t.TEMPLATE_PRJ="template",t.packageFiles=function(t){const i=e.appTarget.blocksprj||e.appTarget.tsprj,s=e.U.clone(i.config);delete s.installedVersion,delete s.additionalFilePath,delete s.additionalFilePaths,s.preferredEditor=s.files.find((e=>/\.blocks$/.test(e)))?e.BLOCKS_PROJECT_NAME:e.JAVASCRIPT_PROJECT_NAME,s.name=t,s.public=!0,s.version||(s.version="0.0.0");const r={},a=n();for(const e in a)r[e]=a[e];for(const e in i.files)"README.md"!=e&&(r[e]=i.files[e]);const o=Object.keys(r).filter((e=>/\.(blocks|md|ts|asm|cpp|h|py)$/.test(e)));return s.files=o.filter((e=>!/test/.test(e))),s.testFiles=o.filter((e=>/test/.test(e))),s.supportedTargets=[e.appTarget.id],r[e.CONFIG_NAME]=e.Package.stringifyConfig(s),r},t.packageFilesFixup=function(t,n){const i=JSON.parse(t[e.CONFIG_NAME]);n&&e.Util.jsonMergeFrom(i,n),e.webConfig&&(Object.keys(e.webConfig).forEach((t=>i[t.toLowerCase()]=e.webConfig[t])),i.platform=e.appTarget.platformid||e.appTarget.id,i.target=e.appTarget.id,i.docs=e.appTarget.appTheme.homeUrl||"./",i.homeurl=e.appTarget.appTheme.homeUrl||"???"),e.U.iterMap(t,((e,n)=>{n=n.replace(/@([A-Z]+)@/g,((e,t)=>i[t.toLowerCase()]||"")),t[e]=n}))}}(e.template||(e.template={}))}(pxt||(pxt={})),function(e){!function(t){let n,i;!function(e){e[e.Prefix=0]="Prefix",e[e.Postfix=1]="Postfix",e[e.Infix=2]="Infix",e[e.Block=3]="Block",e[e.NewLine=4]="NewLine"}(n=t.NT||(t.NT={})),function(e){e[e.None=0]="None",e[e.WithSpace=1]="WithSpace",e[e.NoSpace=2]="NoSpace"}(i=t.GlueMode||(t.GlueMode={}));const s=["break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","import","in","instanceof","new","null","return","super","switch","this","throw","true","try","typeof","var","void","while","with"];function r(e){return"`"+e.replace(/[\\`${}]/g,(e=>"\\"+e))+"`"}function a(e){return e.length>20&&/\n/.test(e)?r(e):JSON.stringify(e)}function o(e,t,n){return{type:e,op:t,children:n}}function l(){return o(n.NewLine,"",[])}function c(e,t){return o(n.Prefix,e,t)}function u(e,t,i){return o(n.Infix,t,null==e?[i]:[e,i])}function d(e){return c(e,[])}function h(e){return o(n.Block,"",e)}function p(e){return c("",e)}function f(e,t=!1){const n=[];for(const i of e)t?(n.length>0&&n.push(d(",")),n.push(l())):n.length>0&&n.push(d(", ")),n.push(i);return t&&n.push(l()),p(n)}let g;t.backtickLit=r,t.stringLit=a,t.mkNode=o,t.mkNewLine=l,t.mkPrefix=c,t.mkPostfix=function(e,t){return o(n.Postfix,t,e)},t.mkInfix=u,t.mkText=d,t.mkBlock=h,t.mkGroup=p,t.mkStmt=function(...e){let t=e[e.length-1];return t&&t.type==n.Block||e.push(l()),p(e)},t.mkCommaSep=f,function(t){function n(e,t,n=!1,i=!1){return p(i?[u(t[0],".",d(e)),d("("),f(t.slice(1),n),d(")")]:[d(e),d("("),f(t,n),d(")")])}function i(e,t,i,s){return n(e+"."+t,i,s)}function s(t,n){return e.U.assert(2==n.length),u(n[0],t,n[1])}t.mkArrayLiteral=function(e,t){return p([d("["),f(e,t),d("]")])},t.mkNumberLiteral=function(e){return d(e.toString())},t.mkBooleanLiteral=function(e){return d(e?"true":"false")},t.mkStringLiteral=function(e){return d(a(e))},t.mkPropertyAccess=function(e,t){return p([u(t,".",d(e))])},t.mkCall=n,t.stdCall=function(e,t,i){return n(e,t,i)},t.extensionCall=function(e,t,i){return n(e,t,i,!0)},t.namespaceCall=i,t.mathCall=function(e,t){return i("Math",e,t,!1)},t.mkGlobalRef=function(e){return d(e)},t.mkSimpleCall=s,t.mkWhile=function(e,t){return p([d("while ("),e,d(")"),h(t)])},t.mkComment=function(e){return d("// "+e)},t.mkMultiComment=function(e){let t=[d("/**"),l()];return e.split("\n").forEach(((e,n,i)=>{e&&(t.push(d(" * "+e)),t.push(l()),n<i.length-1&&(t.push(d(" * ")),t.push(l())))})),p(t.concat([d(" */"),l()]))},t.mkAssign=function(e,t){return s("=",[e,t])},t.mkParenthesizedExpression=function(e){return y(b([e]).output)?e:p([d("("),e,d(")")])}}(g=t.Helpers||(t.Helpers={})),t.H=g;const m={"=":3,"+=":3,"-=":3,"?":4,":":4,"||":5,"&&":6,"|":7,"^":8,"&":9,"==":10,"!=":10,"===":10,"!==":10,"<":11,">":11,"<=":11,">=":11,">>":12,">>>":12,"<<":12,"+":13,"-":13,"*":14,"/":14,"%":14,"**":15,"!":16,"~":16,"P-":16,"P+":16,"++":16,"--":16,".":18};function b(t){let s=[],r={},a="",o="",l=[{}],c=0;function u(e){"string"==typeof e&&(c+=(e.match(/\n/g)||[]).length),a+=e}let h=p(t);return function t(i,s){if(i.type!=n.Infix){for(let e of i.children)t(e,-1);return}let r=[];function a(e){"P"==e[0]&&(e=e.slice(1)),r.push(d(e))}let o=e.U.lookup(m,i.op);if(null==o&&e.U.oops("bad infix op: "+i.op),o<s&&a("("),1==i.children.length)a(i.op),t(i.children[0],o),r.push(i.children[0]);else{let e,n=3!=o&&"**"!=i.op;t(i.children[0],n?o:o+.1),r.push(i.children[0]),e&&"number"!=e&&(a(": "),a(e)),"."==i.op?a("."):a(" "+i.op+" "),t(i.children[1],n?o+.1:o),r.push(i.children[1])}o<s&&a(")"),i.type=n.Prefix,i.op="",i.children=r}(h,-1),f(h),a||u("\n"),{output:a,sourceMap:s};function f(t){t.glueToBlock&&(b(),t.glueToBlock==i.WithSpace&&u(" "));let d=c,h=a.length;switch(t.type){case n.Infix:e.U.oops("no infix should be left");break;case n.NewLine:u("\n"+o);break;case n.Block:!function(t){let n=t.noFinalNewline?"":"\n";if(0==t.children.length)return void g(" {\n\t\n}"+n);let i=e.U.clone(l[l.length-1]||{});l.push(i),o+=" "," "!=a[a.length-1]&&g(" ");g("{\n");for(let e of t.children)f(e);o=o.slice(4),b(),g("\n}"+n),l.pop()}(t);break;case n.Prefix:t.canIndentInside?u(t.op.replace(/\n/g,"\n"+o+" ")):u(t.op),t.children.forEach(f);break;case n.Postfix:t.children.forEach(f),t.canIndentInside?u(t.op.replace(/\n/g,"\n"+o+" ")):u(t.op)}let p=c,m=Math.max(a.length,1);if(t.id)if(r[t.id]){const e=r[t.id];e.startLine=Math.min(e.startLine,d),e.endLine=Math.max(e.endLine,p),e.startPos=Math.min(e.startPos,h),e.endPos=Math.max(e.endPos,m)}else{const e={id:t.id,startLine:d,startPos:h,endLine:p,endPos:m};r[t.id]=e,s.push(e)}}function g(e){u(e.replace(/\n/g,"\n"+o))}function b(){a=a.replace(/\n *$/,(function(){return c--,""}))}}function y(e){if("("!==e[0]||")"!==e[e.length-1])return!1;let t=1;for(let n=1;n<e.length;n++){const i=e[n];if("("===i)t++;else if(")"===i&&(t--,0===t))return n===e.length-1}return!1}t.flattenNode=b,t.isReservedWord=function(e){return-1!==s.indexOf(e)},t.isParenthesized=y}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(t){const n=[".","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];t.BLOCKLY_TILESET_TYPE="BLOCKLY_TILESET_TYPE",t.TILE_PREFIX="tile",t.TILE_NAMESPACE="myTiles",t.IMAGES_NAMESPACE="myImages",t.IMAGE_PREFIX="image",t.ANIMATION_NAMESPACE="myAnimations",t.ANIMATION_PREFIX="anim";class i{constructor(e,t,n=0,i=0,s){this.width=e,this.height=t,this.x0=n,this.y0=i,this.width||(this.width=16),this.height||(this.height=16),this.buf=s||new Uint8ClampedArray(this.dataLength())}static fromData(e){return new i(e.width,e.height,e.x0,e.y0,e.data)}set(e,t,n){if(e<this.width&&t<this.height&&e>=0&&t>=0){const i=this.coordToIndex(e,t);this.setCore(i,n)}}get(e,t){if(e<this.width&&t<this.height&&e>=0&&t>=0){const n=this.coordToIndex(e,t);return this.getCore(n)}return 0}copy(e=0,t=0,n=this.width,s=this.height){const r=new i(n,s);r.x0=e,r.y0=t;for(let i=0;i<n;i++)for(let n=0;n<s;n++)r.set(i,n,this.get(e+i,t+n));return r}apply(e,t=!1){let n;for(let i=0;i<e.width;i++)for(let s=0;s<e.height;s++)n=e.get(i,s),!n&&t||this.set(e.x0+i,e.y0+s,n)}equals(e){if(this.width===e.width&&this.height===e.height&&this.x0===e.x0&&this.y0===e.y0&&this.buf.length===e.buf.length){for(let t=0;t<this.buf.length;t++)if(this.buf[t]!==e.buf[t])return!1;return!0}return!1}data(){return{width:this.width,height:this.height,x0:this.x0,y0:this.y0,data:this.buf}}resize(e,t){return h(this,e,t)}coordToIndex(e,t){return e+t*this.width}getCore(e){const t=Math.floor(e/2);return e%2==0?15&this.buf[t]:(240&this.buf[t])>>4}setCore(e,t){const n=Math.floor(e/2);this.buf[n]=e%2==0?240&this.buf[n]|15&t:15&this.buf[n]|(15&t)<<4}dataLength(){return Math.ceil(this.width*this.height/2)}}t.Bitmap=i;class s extends i{static fromData(e){return new s(e.width,e.height,e.x0,e.y0,e.data)}copy(e=0,t=0,n=this.width,i=this.height){const r=new s(n,i);r.x0=e,r.y0=t;for(let s=0;s<n;s++)for(let n=0;n<i;n++)r.set(s,n,this.get(e+s,t+n));return r}resize(e,t){return p(this,e,t)}getCore(e){return this.buf[e]}setCore(e,t){this.buf[e]=t}dataLength(){return this.width*this.height}}t.Tilemap=s;class r{constructor(e,t,n){this.tilemap=e,this.tileset=t,this.layers=n,this.nextId=0}cloneData(){const e=this.tilemap.copy(),t={tileWidth:this.tileset.tileWidth,tiles:this.tileset.tiles.map((e=>Object.assign(Object.assign({},e),{bitmap:i.fromData(e.bitmap).copy().data()})))},n=i.fromData(this.layers).copy().data();return new r(e,t,n)}equals(t){if(!this.tilemap.equals(t.tilemap)||this.tileset.tileWidth!=t.tileset.tileWidth||this.tileset.tiles.length!=t.tileset.tiles.length||!y(this.layers,t.layers))return!1;for(let n=0;n<this.tileset.tiles.length;n++)if(!e.assetEquals(this.tileset.tiles[n],t.tileset.tiles[n]))return!1;return!0}}t.TilemapData=r;function a(e){return o(atob(e.slice(e.indexOf(",")+1)))}function o(t){let n=t.charCodeAt(0),i=t.charCodeAt(1),s=t.charCodeAt(2);135===n&&(n=224|t.charCodeAt(1),i=t.charCodeAt(2)|t.charCodeAt(3)<<8,s=t.charCodeAt(4)|t.charCodeAt(5)<<8,t=t.slice(4));const r=new e.sprite.Bitmap(i,s);let a=4;if(225===n){let e=1,n=t.charCodeAt(a++);for(let o=0;o<i;++o)for(let i=0;i<s;++i)r.set(o,i,n&e?1:0),e<<=1,256==e&&(e=1,n=t.charCodeAt(a++))}else for(let e=0;e<i;e++){for(let n=0;n<s;n+=2){let i=t.charCodeAt(a++);r.set(e,n,15&i),n!=s-1&&r.set(e,n+1,i>>4&15)}for(;3&a;)a++}return r}function l(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,i=parseInt(e.substr(4,2),16)|parseInt(e.substr(6,2),16)<<8,r=k(e.substring(8));return s.fromData({width:n,height:i,x0:0,y0:0,data:r})}function c(e){return`${d(e.width,2)}${d(e.height,2)}${A(e.data().data)}`}function u(e,t){return(e=e.replace(/[\[\]]/g,""))?e.split(",").filter((e=>!!e.trim())).map((e=>function(e,t){if(0===(e=e.trim()).indexOf("img")){const n=f(e);return t.createNewTile(n.data())}switch(e){case"myTiles.tile0":case"myTiles.transparency16":return t.getTransparency(16);case"myTiles.transparency8":return t.getTransparency(8);case"myTiles.transparency32":return t.getTransparency(32);default:return t.resolveTile(e)}}(e,t))):[]}function d(e,t){let n=e.toString(16);const i=t<<1;for(1&n.length&&(n="0"+n);n.length<i;)n+="0";return n}function h(e,t,n){const s=new i(t,n);return s.apply(e),s}function p(e,t,n){const i=new s(t,n);return i.apply(e),i}function f(e){const t=(e=(e=(e=e.replace(/[ `]|(?:`)|(?:	)|(?:img)/g,"").trim()).replace(/^["`\(\)]*/,"").replace(/["`\(\)]*$/,"")).replace(/ /g,"\n")).split("\n"),n=[];let s=0;for(let e=0;e<t.length;e++){const i=t[e],r=[];for(let e=0;e<i.length;e++)switch(i[e]){case"0":case".":r.push(0);break;case"1":case"#":r.push(1);break;case"2":case"T":r.push(2);break;case"3":case"t":r.push(3);break;case"4":case"N":r.push(4);break;case"5":case"n":r.push(5);break;case"6":case"G":r.push(6);break;case"7":case"g":r.push(7);break;case"8":r.push(8);break;case"9":r.push(9);break;case"a":case"A":case"R":r.push(10);break;case"b":case"B":case"P":r.push(11);break;case"c":case"C":case"p":r.push(12);break;case"d":case"D":case"O":r.push(13);break;case"e":case"E":case"Y":r.push(14);break;case"f":case"F":case"W":r.push(15);break;default:if(!/\s/.test(i[e]))return}r.length&&(n.push(r),s=Math.max(s,r.length))}const r=n.length,a=new i(s,r);for(let e=0;e<r;e++){const t=n[e];for(let n=0;n<s;n++)n<t.length?a.set(n,e,t[n]):a.set(n,e,0)}return a}function g(e){let t="";switch(e){case"python":t='img("""';break;default:t="img`"}return t}function m(e){let t="";switch(e){case"python":t+='""")';break;default:t+="`"}return t}function b(e,t){if(!e||0===e.height||0===e.width)return"";let i=g(t);if(e){const t=e.width*e.height>300?"":" ";for(let s=0;s<e.height;s++){i+="\n";for(let r=0;r<e.width;r++)i+=n[e.get(r,s)]+t}}return i+="\n",i+=m(t),i}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 w(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 k(e){let t=new Uint8ClampedArray(e.length>>1);for(let n=0;n<e.length;n+=2)t[n>>1]=parseInt(e.slice(n,n+2),16);return t}function A(e){const t="0123456789abcdef";let n="";for(let i=0;i<e.length;++i)n+=t[e[i]>>4],n+=t[15&e[i]];return n}function x(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[E(t),C(t),I(t)]}function E(e){return e>>16&255}function C(e){return e>>8&255}function I(e){return 255&e}t.Bitmask=class{constructor(e,t){this.width=e,this.height=t,this.mask=new Uint8Array(Math.ceil(e*t/8))}set(e,t){const n=e+this.width*t,i=n>>3,s=7&n;this.mask[i]|=1<<s}get(e,t){const n=e+this.width*t,i=n>>3,s=7&n;return this.mask[i]>>s&1}},t.encodeTilemap=function(e,t){return e?`tiles.createTilemap(${function(e){return e?`hex\`${c(e)}\``:"hex``"}(e.tilemap)}, ${b(i.fromData(e.layers),t)}, [${e.tileset.tiles.map((e=>function(e,t){return e.id}(e)))}], ${v(e.tileset.tileWidth)})`:"null"},t.decodeTilemap=function(t,n,i){if(!(t=e.Util.htmlUnescape(t).trim()).trim())return null;const s=(t=(t=t.substr(t.indexOf("(")+1)).substr(0,t.lastIndexOf(")"))).substr(0,t.indexOf(",")),a=(t=t.substr(s.length+1)).substr(0,t.indexOf(",")),o=(t=t.substr(a.length+1)).substr(0,t.lastIndexOf("]")+1),c=t=t.substr(o.length+1);return new r(l(s),{tiles:u(o,i),tileWidth:w(c)},f(a).data())},t.trimTilemapTileset=function(e){const t=e.tileset.tiles.slice(),n=e.tilemap,i={};i[t[0].id]=!0;for(let e=0;e<n.width;e++)for(let s=0;s<n.height;s++)i[t[n.get(e,s)].id]=!0;const s=e.editedTiles||[],r=t.filter((e=>i[e.id]||"*"===e.id.charAt(0)||-1!==s.indexOf(e.id)));if(r.length===t.length)return;const a=[];for(let e=0;e<t.length;e++)a.push(r.indexOf(t[e]));for(let e=0;e<n.width;e++)for(let t=0;t<n.height;t++)n.set(e,t,a[n.get(e,t)]);e.tileset.tiles=r},t.isEmptyTilemap=function(e){const t=e.tileset.tiles,n=e.tilemap,i=t[0].id;for(let e=0;e<n.width;e++)for(let s=0;s<n.height;s++)if(t[n.get(e,s)].id!==i)return!1;return!0},t.computeAverageColor=function(e,t){const n=t.map(T),i=[0,0,0];let s=0;for(let t=0;t<e.width;t++)for(let r=0;r<e.height;r++){const a=e.get(t,r);if(a){++s;const e=n[a];i[0]+=e[0],i[1]+=e[1],i[2]+=e[2]}}return s?"#"+function(e){let t="";for(let n=0;n<e.length;++n)t+=("0"+e[n].toString(16)).slice(-2);return t}(i.map((e=>Math.floor(e/s)))):"#00000000"},t.getBitmap=function(e,t){const n=e.apis.byQName[t];return n?a(n.attributes.jresURL):null},t.getBitmapFromJResURL=a,t.hexToBitmap=o,t.filterItems=function(e,t){const n=(t=t.filter((e=>!!e)).map((e=>e.toLowerCase()))).filter((e=>0!==e.indexOf("!"))),i=t.filter((e=>0===e.indexOf("!")&&e.length>1)).map((e=>e.substring(1)));return e.filter((e=>{return t=e,n.every((e=>{const n=`?${e}`;return t.tags.some((t=>t===e||t===n))}))&&function(e){return i.every((t=>!e.tags.some((e=>e===t))))}(e);var t}))},t.getGalleryItems=function(n,i){let s=function(t,n){return e.Util.values(t.byQName).filter((e=>4===e.kind&&e.attributes.fixedInstance&&function(e,t,n){if(t==n)return!0;let i=e.byQName[t];return!(!i||!i.extendsTypes)&&i.extendsTypes.indexOf(n)>=0}(t,e.retType,n)))}(n.apis,i);return s=s.filter((e=>e.namespace!=t.TILE_NAMESPACE)),function(t){const n=new e.ImageConverter;t.forEach((e=>{e.attributes.jresURL&&!e.attributes.iconURL&&0==e.attributes.jresURL.indexOf("data:image/x-mkcd-f")&&(e.attributes.iconURL=n.convert(e.attributes.jresURL))}))}(s),s.map((t=>{const n=(t.attributes.tags||"").split(" ").filter((e=>!!e)).map((t=>e.Util.startsWith(t,"category-")?t:t.toLowerCase()));return{qName:t.qName,src:t.attributes.iconURL,alt:t.qName,tags:n}}))},t.base64EncodeBitmap=function(t){const n=i.fromData(t),s=pxtc.f4EncodeImg(t.width,t.height,4,((e,t)=>n.get(e,t)));return btoa(e.U.uint8ArrayToString(k(s)))},t.tilemapLiteralToTilemap=l,t.hexEncodeTilemap=c,t.formatByte=d,t.resizeBitmap=h,t.resizeTilemap=p,t.imageLiteralToBitmap=f,t.encodeAnimationString=function(t,n){const i=t.map((e=>e.data)),s=new Uint8ClampedArray(8+i[0].length*i.length);x(s,0,n),x(s,2,t[0].width),x(s,4,t[0].height),x(s,6,t.length);let r=8;return i.forEach((e=>{s.set(e,r),r+=e.length})),btoa(e.sprite.uint8ArrayToHex(s))},t.addMissingTilemapTilesAndReferences=function(e,t){const n=e.getProjectTiles(t.data.tileset.tileWidth,!0);t.data.projectReferences=[];for(const i of n.tiles)t.data.tileset.tiles.some((e=>e.id===i.id))||t.data.tileset.tiles.push(i),e.isAssetUsed(i,null,[t.id])&&t.data.projectReferences.push(i.id)},t.updateTilemapReferencesFromResult=function(t,n){const i=n.data;if(i.deletedTiles)for(const e of i.deletedTiles)t.deleteTile(e);if(i.editedTiles)for(const e of i.editedTiles){const n=i.tileset.tiles.findIndex((t=>t.id===e)),s=i.tileset.tiles[n];s&&(i.tileset.tiles[n]=t.updateTile(s))}for(let e=0;e<i.tileset.tiles.length;e++){const n=i.tileset.tiles[e];n.jresData||(i.tileset.tiles[e]=t.resolveTile(n.id))}e.sprite.trimTilemapTileset(i)},t.imageLiteralFromDimensions=function(e,t,i,s){let r=g(s);const a=e*t>300?"":" ";for(let s=0;s<t;s++){r+="\n";for(let t=0;t<e;t++)r+=n[i]+a}return r+="\n",r+=m(s),r},t.bitmapToImageLiteral=b,t.bitmapEquals=y,t.tileWidthToTileScale=v,t.tileScaleToTileWidth=w,t.hexToUint8Array=k,t.uint8ArrayToHex=A,t.colorStringToRGB=T}(e.sprite||(e.sprite={}))}(pxt||(pxt={})),function(e){!function(t){!function(n){const i=new RegExp(`^\\s*${t.TILE_NAMESPACE}\\s*\\.\\s*${t.TILE_PREFIX}(\\d+)\\s*$`);class s{constructor(e,t,n){this.tilemap=e,this.tileset=t,this.layers=n,this.nextId=0}}function r(e){return(e=e.replace(/[\[\]]/g,""))?e.split(",").filter((e=>!!e.trim())).map((e=>function(e){if(0===(e=e.trim()).indexOf("img")){return{data:t.imageLiteralToBitmap(e).data()}}const n=i.exec(e);if(n)return{data:null,projectId:Number(n[1])};return{data:null,qualifiedName:e}}(e))):[]}n.LegacyTilemapData=s,n.decodeTilemap=function(n,i){var a;if(!(null==(n=null===(a=e.Util.htmlUnescape(n))||void 0===a?void 0:a.trim())?void 0:n.trim()))return new s(new t.Tilemap(16,16),{tileWidth:16,tiles:[]},new t.Bitmap(16,16).data());const o=(n=(n=n.substr(n.indexOf("(")+1)).substr(0,n.lastIndexOf(")"))).substr(0,n.indexOf(",")),l=(n=n.substr(o.length+1)).substr(0,n.indexOf(",")),c=(n=n.substr(l.length+1)).substr(0,n.lastIndexOf("]")+1),u=n=n.substr(c.length+1);return new s(t.tilemapLiteralToTilemap(o),{tiles:r(c),tileWidth:t.tileScaleToTileWidth(u)},t.imageLiteralToBitmap(l).data())},n.tileToBlocklyVariable=function(e){return`${e.projectId};${e.data.width};${e.data.height};${pxtc.Util.toHex(e.data.data)}`},n.blocklyVariableToTile=function(e){const t=e.split(";");return 4!==t.length?null:{projectId:parseInt(t[0]),data:{width:parseInt(t[1]),height:parseInt(t[2]),data:new Uint8ClampedArray(pxtc.Util.fromHex(t[3])),x0:0,y0:0}}}}(t.legacy||(t.legacy={}))}(e.sprite||(e.sprite={}))}(pxt||(pxt={})),function(e){!function(t){class n{constructor(){this.items={}}removeItem(e){delete this.items[e]}getItem(e){return this.items[e]}setItem(e,t){this.items[e]=t}clear(){this.items={}}}class i{constructor(e){this.storageId=e}targetKey(e){return this.storageId+"/"+e}removeItem(e){window.localStorage.removeItem(this.targetKey(e))}getItem(e){return window.localStorage[this.targetKey(e)]}setItem(e,t){window.localStorage[this.targetKey(e)]=t}clear(){let e=this.targetKey(""),t=[];for(let n=0;n<window.localStorage.length;++n){let i=window.localStorage.key(n);0==i.indexOf(e)&&t.push(i)}t.forEach((e=>window.localStorage.removeItem(e)))}}function s(){if(e.appTarget)return e.appTarget.id;const t=window.pxtConfig;if(t)return t.targetId;const n=window.pxtTargetBundle;return n?n.id:""}let r;function a(){if(r)return;const t=s();let a=!1;if(!e.shell.isSandboxMode())try{window.localStorage[t]="1";window.localStorage[t];a=!0}catch(e){}a?(r=new i(t),e.debug(`storage: local under ${t}`)):(r=new n,e.debug("storage: in memory"))}t.storageId=s,t.setLocal=function(e,t){a(),r.setItem(e,t)},t.getLocal=function(e){return a(),r.getItem(e)},t.removeLocal=function(e){a(),r.removeItem(e)},t.clearLocal=function(){a(),r.clear()}}(e.storage||(e.storage={}))}(pxt||(pxt={})),function(e){!function(t){!function(t){const n="http://localhost:3232/api/store/";function i(){return e.BrowserUtils.isLocalHostDev()&&!e.BrowserUtils.noSharedLocalStorage()}function s(){return e.BrowserUtils.isChromiumEdge()?"chromium-edge":e.BrowserUtils.browser()}t.getAsync=async function(t,r){if(i()){t+="-"+s();const i=await e.Util.requestAsync({url:`${n}${encodeURIComponent(t)}/${encodeURIComponent(r)}`,method:"GET",allowHttpErrors:!0});return i.json?i.json:i.text?i.text:void 0}{const n=e.storage.getLocal(`${t}:${r}`),i=e.Util.jsonTryParse(n);return i||n}},t.setAsync=async function(t,r,a){if(void 0===a)return void await e.storage.shared.delAsync(t,r);let o="";if(o="object"==typeof a?JSON.stringify(a):a.toString(),i()){t+="-"+s();const i={type:"object"==typeof a?"json":"text",val:o},l=JSON.stringify(i);await e.Util.requestAsync({url:`${n}${encodeURIComponent(t)}/${encodeURIComponent(r)}`,method:"POST",data:l})}else e.storage.setLocal(`${t}:${r}`,o)},t.delAsync=async function(t,r){i()?(t+="-"+s(),await e.Util.requestAsync({url:`${n}${encodeURIComponent(t)}/${encodeURIComponent(r)}`,method:"DELETE",allowHttpErrors:!0})):e.storage.removeLocal(`${t}:${r}`)}}(t.shared||(t.shared={}))}(e.storage||(e.storage={}))}(pxt||(pxt={})),function(e){const t=["name","version","description","license","dependencies","files","testFiles","testDependencies","fileDependencies","public","targetVersions","supportedTargets","preferredEditor","languageRestriction","additionalFilePath","additionalFilePaths"];class n{constructor(e,t,n,i){this.id=e,this._verspec=t,this.parent=n,this.level=-1,this.isLoaded=!1,this.ignoreTests=!1,this.cppOnly=!1,i&&(this.level=i.level+1),this.addedBy=[i]}static stringifyConfig(e){const n=e,i={};for(const e of t)n.hasOwnProperty(e)&&(i[e]=n[e]);for(const e of Object.keys(n))i.hasOwnProperty(e)||(i[e]=n[e]);return JSON.stringify(i,null,4)+"\n"}static parseAndValidConfig(t){const n=e.Util.jsonTryParse(t);return n&&void 0!==n.name&&"string"==typeof n.name&&n.files&&Array.isArray(n.files)&&n.files.every((e=>"string"==typeof e))&&n.dependencies&&Object.keys(n.dependencies).every((e=>"string"==typeof n.dependencies[e]))&&n}static getConfigAsync(t,n,i){return Promise.resolve().then((()=>{if(e.github.isGithubId(i)){const t=e.github.parseRepoId(i);return e.packagesConfigAsync().then((n=>e.github.repoAsync(t.fullName,n))).then((n=>n?e.github.pkgConfigAsync(t.fullName,t.tag):null))}{const s=e.patching.upgradePackageReference(t,n,i),r=e.appTarget.bundledpkgs[s];return JSON.parse(r[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")&&i(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 i=e.github.parseRepoId(this._verspec);if(i&&!i.tag&&this.parent){e.debug("dep: unbound github extensions, trying to resolve tag");const s=e.semver.sortLatestTags(e.Util.values((null===(t=this.parent)||void 0===t?void 0:t.deps)||{}).map((t=>e.github.parseRepoId(t.version()))).filter((e=>(null==e?void 0:e.slug)===i.slug)).map((e=>e.tag)))[0];s&&(i.tag=s,this.resolvedVersion=n=e.github.stringifyRepo(i),e.debug(`dep: github patched ${this._verspec} to ${n}`))}}}else this.configureAsInvalidPackage(lf("version not specified for {0}",this.id)),n=this._verspec;return Promise.resolve(n)}downloadAsync(){return this.resolveVersionAsync().then((t=>{if(this.invalid())e.debug(`skip download of invalid package ${this.id}`);else if(/^embed:/.test(t)||this.installedVersion!=t)return e.debug("downloading "+t),this.host().downloadPackageAsync(this).then((()=>{this.loadConfig(),e.debug(`installed ${this.id} /${t}`)}))}))}loadConfig(){if(0!=this.level&&this.invalid())return;const t=this.readFile(e.CONFIG_NAME);t||e.U.userError(`extension ${this.id} is missing ${e.CONFIG_NAME}`),this.parseConfig(t),0!=this.level&&(this.installedVersion=this.version()),this.saveConfig()}validateConfig(){this.config.dependencies||e.U.userError("Missing dependencies in config of: "+this.id),Array.isArray(this.config.files)||e.U.userError("Missing files in config of: "+this.id),"string"==typeof this.config.name&&this.config.name||(this.config.name=lf("Untitled")),this.config.targetVersions&&this.config.targetVersions.target&&this.config.targetVersions.targetId===e.appTarget.id&&e.appTarget.versions&&e.semver.majorCmp(this.config.targetVersions.target,e.appTarget.versions.target)>0&&e.U.userError(lf("{0} requires target version {1} (you are running {2})",this.config.name,this.config.targetVersions.target,e.appTarget.versions.target))}isPackageInUse(t,n=this.readFile(e.MAIN_TS)){let i=null;const s=e.patching.computePatches(this.targetVersion(),"missingPackage");return s&&s.forEach((e=>{Object.keys(e.map).forEach((n=>{e.map[n]===t&&(i=new RegExp(n,"g"))}))})),i||(i=new RegExp(t+"\\.","g")),i.test(n)}upgradePackagesAsync(){return this.config||this.loadConfig(),e.packagesConfigAsync().then((t=>{let n=0,i={};return e.U.iterMap(this.config.dependencies,((s,r)=>{if(e.github.isGithubId(r)){const a=e.github.upgradedPackageReference(t,r);a&&a!=r&&(e.log(`upgrading dep ${s}: ${r} -> ${a}`),i[r]=a,this.config.dependencies[s]=a,n++)}})),n&&this.saveConfig(),n&&i}))}getMissingPackages(t,n){const i=e.patching.computePatches(this.targetVersion(),"missingPackage"),s={};return n&&i&&i.forEach((e=>{Object.keys(e.map).forEach((i=>{const r=new RegExp(i,"g"),a=e.map[i];n.replace(r,(e=>(t.dependencies[a]||(s[a]="*"),"")))}))})),s}findConflictsAsync(t,i){let s,r=[];return Promise.resolve().then((()=>"string"==typeof t?n.getConfigAsync(this.targetVersion(),t,i):Promise.resolve(t))).then((t=>{if(s=t,s){const t=s.yotta?e.U.jsonFlatten(s.yotta.config):null;this.parent.sortedDeps().forEach((n=>{if(s.core&&n.config.core&&s.name!=n.config.name){const t=new e.cpp.PkgConflictError(lf("conflict between core extensions {0} and {1}",s.name,n.id));return t.pkg0=n,void r.push(t)}let a=!1;if(t){const i=n.config||JSON.parse(n.readFile(e.CONFIG_NAME));if(!!i&&!!i.yotta&&!!n.config.yotta.config){const o=e.U.jsonFlatten(i.yotta.config);for(const l of Object.keys(t)){const c=o[l],u=s.yotta.configIsJustDefaults||i.yotta.configIsJustDefaults;if(o.hasOwnProperty(l)&&c!==t[l]&&!u&&(!n.parent.config.yotta||!n.parent.config.yotta.ignoreConflicts)){const t=new e.cpp.PkgConflictError(lf("conflict on yotta setting {0} between extensions {1} and {2}",l,s.name,n.id));t.pkg0=n,t.settingName=l,r.push(t),a=!0}}}}if(!a&&s.name===n.id&&n._verspec!==i&&!/^file:/.test(n._verspec)&&!/^file:/.test(i)){const t=/^github:/.test(n._verspec)&&e.github.parseRepoId(n._verspec),s=/^github:/.test(i)&&e.github.parseRepoId(i);if(!t||!s||t.fullName!==s.fullName||s.tag&&e.semver.strcmp(t.tag,s.tag)<0){const t=new e.cpp.PkgConflictError(lf("version mismatch for extension {0} (installed: {1}, installing: {2})",n.id,n._verspec,i));t.pkg0=n,t.isVersionConflict=!0,r.push(t)}}}))}return Object.keys(s.dependencies).reduce(((e,t)=>e.then((()=>this.findConflictsAsync(t,s.dependencies[t]))).then((e=>r.push.apply(r,e)))),Promise.resolve())})).then((()=>{const t=e=>{const n=[];return e.addedBy.forEach((e=>{e.id!==this.id&&(n.push.apply(t(e)),n.push(e))})),n},n=[];return r.forEach((r=>{n.push.apply(n,t(r.pkg0).map((t=>{const n=new e.cpp.PkgConflictError(r.isVersionConflict?lf("a dependency of {0} has a version mismatch with extension {1} (installed: {1}, installing: {2})",t.id,s.name,r.pkg0._verspec,i):lf("conflict on yotta setting {0} between extensions {1} and {2}",r.settingName,s.name,r.pkg0.id));return n.pkg0=t,n})))})),r.push.apply(r,n),r=r.filter(((e,t)=>{for(let n=0;n<t;++n)if(e.pkg0.id===r[n].pkg0.id)return!1;return!0})),r}))}configureAsInvalidPackage(t){e.log(`invalid package ${this.id}: ${t}`),this._verspec="invalid:"+this.id,this.config={name:this.id,description:t,dependencies:{},files:[]}}parseConfig(t,n){try{const e=JSON.parse(t);this.config=e}catch(t){this.configureAsInvalidPackage(lf("Syntax error in pxt.json")),e.tickEvent("package.invalidConfigEncountered")}const i=JSON.stringify(this.config);for(const t in this.config.dependencies){const n=e.patching.upgradePackageReference(this.targetVersion(),t,this.config.dependencies[t]);n!=t&&(delete this.config.dependencies[t],n&&(this.config.dependencies[n]="*"))}n&&(this.config.targetVersions={target:n}),JSON.stringify(this.config)!=i&&this.saveConfig(),this.validateConfig()}patchCorePackage(){e.Util.assert(e.appTarget.simulator&&e.appTarget.simulator.dynamicBoardDefinition),e.Util.assert(0==this.level);const t=Object.keys(this.config.dependencies).filter((t=>!!t&&(t==e.BLOCKS_PROJECT_NAME||t==e.JAVASCRIPT_PROJECT_NAME||JSON.parse((e.appTarget.bundledpkgs[t]||{})[e.CONFIG_NAME]||"{}").core)));if(0==t.length){const t=e.Package.corePackages();t.length&&this.config.dependencies[t[0].name]}else t.length>1&&(t.pop(),t.forEach((t=>{e.log(`removing core package ${t}`),delete this.config.dependencies[t]})))}resolvedDependencies(){return Object.keys(this.dependencies()).map((e=>this.resolveDep(e)))}dependencies(t=!1){if(!this.config)return{};const n=e.Util.clone(this.config.dependencies||{});return 0==this.level&&this.config.testDependencies&&e.Util.iterMap(this.config.testDependencies,((t,i)=>{("*"!=i||e.appTarget.bundledpkgs[t])&&(n[t]=i)})),t&&this.config.cppDependencies&&e.Util.jsonMergeFrom(n,this.config.cppDependencies),n}loadAsync(t=!1,i){if(this.isLoaded)return Promise.resolve();let s=Promise.resolve();0!=this.level||e.appTarget.multiVariants||e.setAppTargetVariant(null),this.isLoaded=!0;const r=this.readFile(e.CONFIG_NAME);null==r?t||e.U.userError("Package not installed: "+this.id+", did you forget to run `pxt install`?"):s=s.then((()=>this.parseConfig(r))),0!=this.level||t||(s=s.then((()=>this.upgradePackagesAsync().then((()=>{}))))),t&&(s=s.then((()=>this.downloadAsync()))),0==this.level&&t&&(s=s.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&&(s=s.then((()=>this.patchCorePackage()))),s=s.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],i=this.readFile(t);return e.U.toDataUri(i,e.U.getMime(t))}return t},i=e.appTarget.simulator.boardDefinition;if("object"==typeof i.visual){let e=i.visual;e.image=n(e.image),e.outlineImage=n(e.outlineImage)}})));const a=(t,n)=>{var i;if(e.debug(`version spec mismatch: ${t._verspec} != ${n}`),/^github:/.test(t._verspec)&&/^github:/.test(n)){const s=e.github.parseRepoId(t._verspec),r=e.github.parseRepoId(n);if((null==s?void 0:s.slug)&&(null==s?void 0:s.slug)===(null==r?void 0:r.slug)){const a=(null==s?void 0:s.tag)||(null===(i=t.config)||void 0===i?void 0:i.version),o=e.semver.strcmp(a,r.tag);if(0==o)return void e.debug(`resolved version are ${a}`);if(o<0)return void e.debug(`auto-upgraded ${n} to ${a}`)}}/^file:/.test(t._verspec)||/^file:/.test(n)?e.debug("ignore file: mismatch issues"):t.configureAsInvalidPackage(lf("version mismatch"))},o=async(i,s,r=!1)=>{i||(i=s.dependencies(r)),e.debug(`deps: ${s.id}->${Object.keys(i).join(", ")}`),i=e.github.resolveMonoRepoVersions(i),e.debug(`deps: resolved ${s.id}->${Object.keys(i).join(", ")}`);for(let o of Object.keys(i)){let l=i[o]||"*";e.debug(`dep: load ${s.id}.${o}${r?"++":""}: ${l}`),"hw"==o&&e.hwVariant&&(o="hw---"+e.hwVariant);let c=s.resolveDep(o);if(c){if(c.invalid()||c._verspec===l||a(c,l),c.invalid()){c.level=Math.min(c.level,s.level+1),c.addedBy.push(s);continue}r||(c.level=Math.min(c.level,s.level+1),c.addedBy.push(s))}else{let e=new n(o,l,s.parent,s);r&&(e.cppOnly=!0),s.parent.deps[o]=e,s.parent.deps[o.replace(/---.*/,"")]=e,await e.loadAsync(t)}}};return s.then((()=>o(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 i=!1;return Object.keys(n).reduce(((t,s)=>t.then((()=>this.findConflictsAsync(s,n[s]))).then((t=>{if(t.length){const n=t.map((e=>e.pkg0.id)).join(", "),i=t.map((e=>e.settingName)).filter((e=>!!e)).join(", ");return e.log(`skipping missing package ${s} because it conflicts with the following packages: ${n} (conflicting settings: ${i})`),Promise.resolve(null)}{e.log(`adding missing package ${s}`),i=!0,this.config.dependencies[s]="*";const t={};return t[s]=n[s],o(t,this)}}))),Promise.resolve(null)).then((()=>(i&&(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=>o(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 i=this.config.fileDependencies;return this.config.fileDependencies&&(t=t.filter((t=>{const s=i=>{if("!"==(i=i.trim())[0])return!s(i.slice(1));if(/^[\w-]+$/.test(i)){const e=this.parent.resolveDep(i);return!(!e||e.cppOnly)}const r=/^target:(\w+)$/.exec(i);return r?r[1]==e.appTarget.id||r[1]==e.appTarget.platformid:(n.depWarnings[i]||(n.depWarnings[i]=!0,e.log(`invalid dependency expression: ${i} in ${this.id}/${t}`)),!1)},r=e.U.lookup(i,t);return!r||!r.trim()||r.split("||").some((e=>e.split("&&").every(s)))}))),t}addSnapshot(t,n=[""]){for(let i of this.getFiles())n.some((t=>e.U.endsWith(i,t)))&&(t[this.id+"/"+i]=this.readFile(i));t[this.id+"/"+e.CONFIG_NAME]=this.readFile(e.CONFIG_NAME)}packageLocalizationStringsAsync(t){const n=e.appTarget.id,i=[this.config.name+"-jsdoc",this.config.name],s={},r=e.appTarget.appTheme||{};return this.config.skipLocalization?Promise.resolve(s):e.Util.liveLocalizationEnabled()&&"this"!=this.id&&e.appTarget.bundledpkgs[this.id]?(e.debug(`loading live translations for ${this.id}`),Promise.all(i.map((i=>e.Util.downloadLiveTranslationsAsync(t,`${n}/${i}-strings.json`,r.crowdinBranch).then((n=>{n&&Object.keys(n).length?e.Util.jsonMergeFrom(s,n):(e.tickEvent("translations.livetranslationsfailed",{filename:i}),e.Util.jsonMergeFrom(s,this.bundledStringsForFile(t,i)))})).catch((r=>{e.tickEvent("translations.livetranslationsfailed",{filename:i}),e.log(`error while downloading ${n}/${i}-strings.json`),e.Util.jsonMergeFrom(s,this.bundledStringsForFile(t,i))}))))).then((()=>s))):(i.map((e=>this.bundledStringsForFile(t,e))).filter((e=>!!e)).forEach((t=>e.Util.jsonMergeFrom(s,t))),Promise.resolve(s))}bundledStringsForFile(t,n){let i={},[s,r,a]=e.Util.normalizeLanguageCode(t);const o=this.config.files;let l=`_locales/${s}/${n}-strings.json`;return o.indexOf(l)>-1?i=JSON.parse(this.readFile(l)):a&&(l=`_locales/${a}/${n}-strings.json`,o.indexOf(l)>-1?i=JSON.parse(this.readFile(l)):r&&(l=`_locales/${r}/${n}-strings.json`,o.indexOf(l)>-1&&(i=JSON.parse(this.readFile(l))))),i}}n.depWarnings={},e.Package=n;function i(e,t={}){let n=e["*"]||{};for(let i of Object.keys(e)){if("*"==i)continue;let s=e[i];"string"==typeof s&&(s={data:s});let r=s.namespace||n.namespace||"";r&&(r+=".");let a=s.id||r+i,o=s.icon,l=s.mimeType||n.mimeType,c=s.dataEncoding||n.dataEncoding||"base64";o||"base64"!=c||"image/png"!=l&&"image/jpeg"!=l||(o="data:"+l+";base64,"+s.data),t[a]={id:a,data:s.data,dataEncoding:c,icon:o,namespace:r,mimeType:l,tilemapTile:s.tilemapTile,displayName:s.displayName,tileset:s.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={},i=[];const s=e=>e.config?Object.keys(e.config.cppDependencies||{}).length:0,r=a=>{if(!a||e.U.lookup(n,a.id))return;n[a.id]=!0;const o=Object.keys(a.dependencies(t)).map((e=>this.resolveDep(e)));o.sort(((t,n)=>s(n)-s(t)||e.U.strcmp(t.id,n.id))),o.forEach(r),i.push(a.id)};return r(this),i.map((e=>this.resolveDep(e)))}localizationStringsAsync(t){const n={};return Promise.all(e.Util.values(this.deps).map((e=>e.packageLocalizationStringsAsync(t).then((e=>{e&&Object.keys(e).forEach((t=>{n[t]||(n[t]=e[t])}))}))))).then((()=>{const t=e.U.getLocalizedStrings();return Object.keys(n).forEach((i=>{(e.U.startsWith(i,"{id:subcategory}")||e.U.startsWith(i,"{id:group}"))&&(t[i]||(t[i]=n[i]))})),e.U.setLocalizedStrings(t),Promise.resolve(n)}))}getTargetOptions(){let t=e.U.clone(e.appTarget.compile);return e.U.assert(!!t),t.utf8||this.sortedDeps(!0).forEach((n=>{n.config&&n.config.utf8&&(e.debug("forcing utf8 mode: pkg="+n.id),t.utf8=!0)})),t}getJRes(){if(!this._jres){this._jres={};for(const e of this.sortedDeps())e.parseJRes(this._jres);const t=(e.appTarget.runtime&&e.appTarget.runtime.palette?e.appTarget.runtime.palette:["#000000","#ffffff"]).map((e=>("000000"+parseInt(e.replace(/#/,""),16).toString(16)).slice(-6))).join("");this._jres.__palette={id:"__palette",data:t,dataEncoding:"hex",mimeType:"application/x-palette"}}return this._jres}updateJRes(){this._jres&&this.parseJRes(this._jres)}resolveBannedCategories(){if(void 0!==this._resolvedBannedCategories)return this._resolvedBannedCategories;let t=[];return e.appTarget&&e.appTarget.runtime&&e.appTarget.runtime.bannedCategories&&e.appTarget.runtime.bannedCategories.length&&(t=e.appTarget.runtime.bannedCategories.slice(),Object.keys(this.deps).map((e=>this.deps[e])).filter((e=>!!e)).map((t=>e.Util.jsonTryParse(t.readFile(e.CONFIG_NAME)))).filter((e=>e&&e.requiredCategories)).forEach((e=>e.requiredCategories.forEach((e=>{const n=t.indexOf(e);n>-1&&t.splice(n,1)})))),this._resolvedBannedCategories=t),this._resolvedBannedCategories=t,this._resolvedBannedCategories.length||(this._resolvedBannedCategories=null),this._resolvedBannedCategories}async getCompileOptionsAsync(t=this.getTargetOptions()){let n={sourceFiles:[],fileSystem:{},target:t,name:this.config?this.config.name:""};const i=(t,n)=>{this.config.files.indexOf(t)<0&&e.U.userError(lf("please add '{0}' to \"files\" in {1}",t,e.CONFIG_NAME)),n="// Auto-generated. Do not edit.\n"+n+"\n// Auto-generated. Do not edit. Really.\n",this.host().readFile(this,t,!0)!==n&&(e.debug(`updating ${t} (size=${n.length})...`),this.host().writeFile(this,t,n,!0))};let s=!1;const r=async n=>{const r={extinfo:null,target:null},a=e.appTargetVariant;n&&e.setAppTargetVariant(n,{temporary:!0});try{let o=e.cpp.getExtensionInfo(this);s||!o.shimsDTS&&!o.enumsDTS||(s=!0,o.shimsDTS&&i("shims.d.ts",o.shimsDTS),o.enumsDTS&&i("enums.d.ts",o.enumsDTS));const l=t.isNative?await this.host().getHexInfoAsync(o):null;o=e.U.flatClone(o),t.keepCppFiles||(delete o.compileData,delete o.generatedFiles,delete o.extensionFiles),o.hexinfo=l,r.extinfo=o,r.target=e.appTarget.compile}finally{n&&e.setAppTargetVariant(a,{temporary:!0})}return r};let a;await this.loadAsync(),n.bannedCategories=this.resolveBannedCategories(),n.target.preferredEditor=this.getPreferredEditor(),e.debug(`building: ${this.sortedDeps().map((e=>e.config.name)).join(", ")}`),a=e.appTarget.multiVariants?e.appTargetVariant?[e.appTargetVariant]:e.appTarget.alwaysMultiVariant||e.appTarget.compile.switches.multiVariant?e.appTarget.multiVariants:[e.appTarget.multiVariants[0]]:[null];let o=null;for(let t of a){o&&e.debug(`building for ${t}`);const i=await r(t),s=i.extinfo;s.appVariant=t,s.outputPrefix=1!=a.length&&t?t+"-":"",o?n.otherMultiVariants.push(i):(o=s,n.otherMultiVariants=[])}n.extinfo=o;if(!(e.appTarget.compile.shortPointers||"vm"==e.appTarget.compile.nativeType||this.config.binaryonly||!n.target.isNative)){const t=await this.filesToBePublishedAsync(!0),i=JSON.stringify({name:this.config.name,comment:this.config.description,status:"unpublished",scriptId:this.installedVersion,cloudId:e.CLOUD_ID+e.appTarget.id,editor:this.getPreferredEditor(),targetVersions:e.appTarget.versions}),s=JSON.stringify(t),r=await e.lzmaCompressAsync(i+s);r&&(n.embedMeta=JSON.stringify({compression:"LZMA",headerSize:i.length,textSize:s.length,name:this.config.name,eURL:e.appTarget.appTheme.embedUrl,eVER:e.appTarget.versions?e.appTarget.versions.target:"",pxtTarget:e.appTarget.id}),n.embedBlob=ts.pxtc.encodeBase64(e.U.uint8ArrayToString(r)))}for(const e of this.sortedDeps())for(const t of e.getFiles())if(/\.(ts|asm|py)$/.test(t)){let i=t;e.level>0&&(i="pxt_modules/"+e.id+"/"+t),n.sourceFiles.push(i),n.fileSystem[i]=e.readFile(t)}n.jres=this.getJRes();const l=e.appTarget.runtime&&e.appTarget.runtime.functionsOptions;return n.allowedArgumentTypes=l&&l.extraFunctionEditorTypes&&l.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,i)=>{if(!i||/^(file|workspace):/.test(i)){i="*";try{const t=this.resolveDep(n).readGitJson();if(t&&t.repo){let n=e.github.parseRepoId(t.repo);n.tag=t.commit.tag||t.commit.sha,i=e.github.stringifyRepo(n)}}catch(e){}t.dependencies[n]=i}})),t}filesToBePublishedAsync(t=!1){const n={};return this.loadAsync().then((()=>{t||this.config.public||e.U.userError('Only packages with "public":true can be published');const i=this.prepareConfigToBePublished();n[e.CONFIG_NAME]=e.Package.stringifyConfig(i);for(let t of this.getFiles()){if(t==e.CONFIG_NAME)continue;let i=this.readFile(t);null==i&&e.U.userError("referenced file missing: "+t),n[t]=i}return e.U.sortObjectFields(n)}))}saveToJsonAsync(){return this.filesToBePublishedAsync(!0).then((t=>({meta:{cloudId:e.CLOUD_ID+e.appTarget.id,targetVersions:e.appTarget.versions,editor:this.getPreferredEditor(),name:this.config.name},source:JSON.stringify(t,null,2)})))}compressToFileAsync(){return this.saveToJsonAsync().then((t=>e.lzmaCompressAsync(JSON.stringify(t,null,2))))}computePartDefinitions(t){if(!t||!t.length)return{};let n={};return this.sortedDeps().forEach((i=>{let s=i.readFile("pxtparts.json");if(s)try{let r=JSON.parse(s);Object.keys(r).forEach((s=>{if(t.indexOf(s)>=0){let t=n[s]=r[s];if("string"==typeof t.visual.image&&/\.svg$/i.test(t.visual.image)){let n=i.readFile(t.visual.image);n||e.reportError("parts","invalid part definition",{error:`missing visual ${t.visual.image}`}),/^data:image\/svg\+xml/.test(n)||(n="data:image/svg+xml,"+encodeURIComponent(n)),t.visual.image=n}}}))}catch(t){e.reportError("parts","invalid pxtparts.json file")}})),n}},e.inflateJRes=i,e.allPkgFiles=function(t){return[e.CONFIG_NAME].concat(t.files||[]).concat(t.testFiles||[])},e.isPkgBeta=function(e){return e&&/\bbeta\b/.test(e.description)}}(pxt||(pxt={})),function(e){!function(t){let n,i,s,r,a,o=()=>{};function l(){if(a)return a;let t=Promise.resolve();if(n){e.debug("packetio: disconnect");const s=n;t=t.then((()=>s.disconnectAsync())).then((()=>s.io.disposeAsync())).catch((t=>{e.reportException(t)})).finally((()=>{i=void 0,n=void 0,a=void 0})),o&&(t=t.then((()=>o()))),a=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=l,t.configureEvents=function(e,t,i){o=e,s=t,r=i,n&&(n.io.onConnectionChanged=o,n.onSerial=s,n.onCustomEvent=i)},t.sendCustomEventAsync=function(e,t){return n?n.sendCustomEventAsync(e,t):Promise.resolve()},t.initAsync=function(a=!1){if(e.debug("packetio: init "+(a?"(force)":"")),!i){let c=Promise.resolve();a&&(c=c.then((()=>l()))),i=c.then((()=>n?Promise.resolve(n):t.mkPacketIOAsync?(e.debug("packetio: new wrapper"),t.mkPacketIOAsync().then((e=>(e.onConnectionChanged=o,n=t.mkPacketIOWrapper(e),s&&(n.onSerial=s),r&&(n.onCustomEvent=r),o&&o(),n)))):(e.debug("packetio: not defined, skipping"),Promise.resolve(void 0)))).finally((()=>{i=void 0}))}return i}}(e.packetio||(e.packetio={}))}(pxt||(pxt={})),function(e){!function(t){t.computePatches=function(t,n){const i=e.appTarget.compile?e.appTarget.compile.patches:void 0;if(!i)return;const s=e.semver.tryParse(t||"0.0.0")||e.semver.tryParse("0.0.0");let r=[];return Object.keys(i).filter((t=>e.semver.inRange(t,s))).forEach((e=>r=r.concat(i[e]))),n&&(r=r.filter((e=>e.type==n))),r.length?r:void 0},t.upgradePackageReference=function(t,n,i){if("*"!=i)return n;const s=e.patching.computePatches(t,"package");let r=n;return s&&s.forEach((e=>{Object.keys(e.map).forEach((t=>{r==t&&(r=e.map[t])}))})),r},t.patchJavaScript=function(t,n){const i=e.patching.computePatches(t);let s=n;return i&&(i.filter((e=>"api"===e.type)).forEach((e=>{Object.keys(e.map).forEach((t=>{const n=new RegExp(t,"g");s=s.replace(n,e.map[t])}))})),i.filter((e=>"userenum"===e.type)).forEach((e=>{Object.keys(e.map).forEach((t=>{const n=new RegExp("enum\\s+"+t+"\\s*{","gm");s=s.replace(n,`enum ${e.map[t]} {`);const i=new RegExp(`(^|[^_a-zA-Z0-9])${t}(\\s*\\.)`,"g");s=s.replace(i,`$1${e.map[t]}$2`)}))}))),s}}(e.patching||(e.patching={}))}(pxt||(pxt={})),function(e){e.react||(e.react={})}(pxt||(pxt={})),function(e){!function(t){function n(t,n){if(t){if(n){let i=t.major-n.major||t.minor-n.minor||t.patch-n.patch;if(i)return i;if(0==t.pre.length&&n.pre.length>0)return 1;if(t.pre.length>0&&0==n.pre.length)return-1;for(let s=0;s<t.pre.length+1;++s){let r=t.pre[s],a=n.pre[s];if(!r)return a?-1:0;if(!a)return 1;if(/^\d+$/.test(r)){if(!/^\d+$/.test(a))return-1;if(i=parseInt(r)-parseInt(a),i)return i}else{if(/^\d+$/.test(a))return 1;if(i=e.U.strcmp(r,a),i)return i}}return 0}return-1}return n?1:0}function i(t,n){let i=s(t)||s(n);return i||e.U.userError(e.U.lf("'{0}' doesn't look like a semantic version number",t)),i}function s(e){if(!e)return null;if("*"===e)return{major:Number.MAX_SAFE_INTEGER,minor:Number.MAX_SAFE_INTEGER,patch:Number.MAX_SAFE_INTEGER,pre:[],build:[]};/^v\d/i.test(e)&&(e=e.slice(1));let t=/^(\d+)\.(\d+)\.(\d+)(-([0-9a-zA-Z\-\.]+))?(\+([0-9a-zA-Z\-\.]+))?$/.exec(e);return t?{major:parseInt(t[1]),minor:parseInt(t[2]),patch:parseInt(t[3]),pre:t[5]?t[5].split("."):[],build:t[7]?t[7].split("."):[]}:null}function r(e){let t=e.major+"."+e.minor+"."+e.patch;return e.pre.length&&(t+="-"+e.pre.join(".")),e.build.length&&(t+="+"+e.build.join(".")),t}function a(t,i){let r=s(t),a=s(i);return r||a?n(r,a):e.U.strcmp(t,i)}function o(e,t){let i=e.split(" - ");if(2!=i.length)return!1;let r=s(i[0]),a=s(i[1]);if(!r||!a)return!1;if(!t)return!0;const o=n(r,t),l=n(t,a);return o<=0&&l<0}t.cmp=n,t.parse=i,t.tryParse=s,t.normalize=function(e){return r(i(e))},t.stringify=r,t.majorCmp=function(e,t){let n=s(e),i=s(t);return n.major-i.major},t.strcmp=a,t.inRange=o,t.sortLatestTags=function(e){const n=e.filter((e=>!!t.tryParse(e)));return n.sort(a),n.reverse(),n},t.test=function(){console.log("Test semver");let t=["0.9.0","1.0.0-0.3.7","1.0.0-alpha","1.0.0-alpha.1","1.0.0-alpha.beta","1.0.0-beta","1.0.0-beta.2","1.0.0-beta.11","1.0.0-rc.1","1.0.0-x.7.z.92","1.0.0","1.0.1","1.9.0","1.10.0","1.11.0"];for(let s=0;s<t.length;++s){let a=i(t[s]);console.log(t[s],a),e.U.assert(r(a)==t[s]);for(let r=0;r<t.length;++r){let o=n(a,i(t[r]));console.log(t[s],t[r],o),s<r?e.U.assert(o<0):s>r?e.U.assert(o>0):e.U.assert(0==o)}}const a=s("1.2.3");e.U.assert(o("0.1.2 - 2.2.3",a)),e.U.assert(o("1.2.3 - 2.2.3",a)),e.U.assert(!o("0.0.0 - 1.2.3",a)),e.U.assert(!o("1.2.4 - 4.2.3",a)),e.U.assert(!o("0.0.0 - 0.0.1",a))}}(e.semver||(e.semver={}))}(pxt||(pxt={})),function(e){!function(e){function t(t){return e.Util.values(t.byQName).filter((e=>e.attributes.block&&/^{[^:]+:[^}]+}/.test(e.attributes.block))).forEach((e=>{e.attributes.block=e.attributes.block.replace(/^{[^:]+:[^}]+}/,"")})),t}e.assert=e.Util.assert,e.oops=e.Util.oops,e.U=e.Util,e.ON_START_TYPE="pxt-on-start",e.ON_START_COMMENT="on start",e.HANDLER_COMMENT="code goes here",e.TS_STATEMENT_TYPE="typescript_statement",e.TS_DEBUGGER_TYPE="debugger_keyword",e.TS_BREAK_TYPE="break_keyword",e.TS_CONTINUE_TYPE="continue_keyword",e.TS_OUTPUT_TYPE="typescript_expression",e.TS_RETURN_STATEMENT_TYPE="function_return",e.PAUSE_UNTIL_TYPE="pxt_pause_until",e.COLLAPSED_BLOCK="pxt_collapsed_block",e.FUNCTION_DEFINITION_TYPE="function_definition",e.BINARY_JS="binary.js",e.BINARY_ASM="binary.asm",e.BINARY_HEX="binary.hex",e.BINARY_UF2="binary.uf2",e.BINARY_ELF="binary.elf",e.BINARY_PXT64="binary.pxt64",e.BINARY_ESP="binary.bin",e.BINARY_SRCMAP="binary.srcmap",e.NATIVE_TYPE_THUMB="thumb",e.NATIVE_TYPE_VM="vm",e.BuildSourceMapHelpers=function(e,t,n){const i=e=>{const t=e.split("\n").map((e=>e.length)),n=t.reduce((({lens:e,sum:t},n)=>({lens:[...e,t+n+1],sum:t+n+1})),{lens:[],sum:0}).lens;return{posToLineCol:e=>{const i=n.reduce(((t,n,i)=>e<n?t:i+1),0);return[i,t[i]-(n[i]-e)+1]},lineColToPos:(e,t)=>(n[e-1]||0)+t}},s={ts:i(t),py:i(n)},r=e=>e.endPos-e.startPos,a=(t,n)=>{const{startPos:i,endPos:s}=t;return e.filter((e=>e[n].startPos<=i&&s<=e[n].endPos))},o=(e,t)=>{const n=a(e,t);return n.reduce(((e,n)=>r(n[t])<r(e[t])?n:e),n[0])},l={ts:{allOverlaps:e=>a(e,"ts"),smallestOverlap:e=>o(e,"ts")},py:{allOverlaps:e=>a(e,"py"),smallestOverlap:e=>o(e,"py")}},c=(e,t)=>n=>{const[i,a]=(t=>[s[e].lineColToPos(t.line,t.column),t.length])(n),l=o({startPos:i,endPos:i+a},e);if(!l)return;const[c,u]=s[t].posToLineCol(l[t].startPos);return{fileName:`main.${t}`,start:l[t].startPos,length:r(l[t]),line:c,column:u}},u=c("ts","py"),d=c("py","ts");return{ts:Object.assign(Object.assign(Object.assign({},s.ts),l.ts),{locToLoc:u,getText:e=>t.substring(e.startPos,e.endPos)}),py:Object.assign(Object.assign(Object.assign({},s.py),l.py),{locToLoc:d,getText:e=>n.substring(e.startPos,e.endPos)})}},e.computeUsedParts=function(e,t){if(!e.usedSymbols||!pxt.appTarget.simulator||!pxt.appTarget.simulator.parts)return[];let n=[];if(Object.keys(e.usedSymbols).forEach((t=>{let i=e.usedSymbols[t];if(i&&i.attributes.parts){let e=i.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 i,a;let o=[];const l={},c={},u={},d={},h={};function p(t,n){const i="get"==t,s="set"==t,a="number"==n.retType,d=i?c:s?l:u,h=`${n.namespace}.${n.retType}`;let p=e.U.lookup(d,h);if(!p){const l=`@${t}@`;let c,u;if(n.attributes.blockCombineShadow){const t=n.attributes.blockCombineShadow,i=t.match(/^([^,.]*),?([^,.]*)$/);i&&3==i.length&&(c=i[1].trim(),u=i[2].trim(),0!=u.length||e.Util.endsWith(t,",")||(u=c,c=""))}const f=`${n.attributes.blockSetVariable||n.namespace.toLocaleLowerCase()}=${c||""}`,g=`value=${u||""}`;p=d[h]={attributes:{blockId:`${a?n.namespace:h}_blockCombine_${t}`,callingConvention:0,group:n.attributes.group,paramDefl:{},jsDoc:i?e.U.lf("Read value of a property on an object"):e.U.lf("Update value of property on an object")},name:l,namespace:n.namespace,fileName:n.fileName,qName:`${h}.${l}`,pkg:n.pkg,kind:2,parameters:[{name:"property",description:i?e.U.lf("the name of the property to read"):e.U.lf("the name of the property to change"),isEnum:!0,type:"@combined@"},{name:"value",description:s?e.U.lf("the new value of the property"):e.U.lf("the amount by which to change the property"),type:n.retType}].slice(0,i?1:2),retType:i?n.retType:"void",combinedProperties:[]},p.attributes.block=i?e.U.lf("%{0} %property",f):s?e.U.lf("set %{0} %property to %{1}",f,g):e.U.lf("change %{0} %property by %{1}",f,g),r(p.attributes),pxt.Util.isTranslationMode()&&(p.attributes.translationId=p.attributes.block,p.attributes.block=i?`%${f} %property`:s?`set %${f} %property to %${g}`:`change %${f} %property by %${g}`,r(p.attributes),pxt.crowdin.inContextLoadAsync(p.attributes.translationId).then((e=>{p.attributes.block=e,r(p.attributes)}))),o.push(p)}p.combinedProperties.push(n.qName)}for(let n of e.Util.values(t.byQName)){if("ENUM_GET"===n.attributes.shim&&n.attributes.enumName&&n.attributes.blockId){let e=!1;if(d[n.attributes.enumName]&&(console.warn(`Enum block ${n.attributes.blockId} trying to overwrite enum ${n.attributes.enumName}`),e=!0),n.attributes.enumMemberName||(console.warn(`Enum block ${n.attributes.blockId} should specify enumMemberName`),e=!0),n.attributes.enumPromptHint||(console.warn(`Enum block ${n.attributes.blockId} should specify enumPromptHint`),e=!0),n.attributes.enumInitialMembers&&n.attributes.enumInitialMembers.length||(console.warn(`Enum block ${n.attributes.blockId} should specify enumInitialMembers`),e=!0),e)continue;const t=parseInt(n.attributes.enumStartValue);d[n.attributes.enumName]={blockId:n.attributes.blockId,name:n.attributes.enumName,memberName:n.attributes.enumMemberName,firstValue:isNaN(t)?void 0:t,isBitMask:n.attributes.enumIsBitMask,isHash:n.attributes.enumIsHash,initialMembers:n.attributes.enumInitialMembers,promptHint:n.attributes.enumPromptHint}}if("KIND_GET"===n.attributes.shim&&n.attributes.blockId){const i=n.attributes.kindNamespace||n.attributes.blockNamespace||n.namespace;if(h[i]){console.warn(`More than one block defined for kind ${i}`);continue}const s=[];if(t.byQName[i])for(const n of e.Util.values(t.byQName))n.namespace===i&&n.attributes.isKind&&s.push(n.name);h[i]={blockId:n.attributes.blockId,name:i,memberName:n.attributes.kindMemberName||i,initialMembers:s,promptHint:n.attributes.enumPromptHint||e.Util.lf("Create a new kind..."),createFunctionName:n.attributes.kindCreateFunction||"create"}}if(n.attributes.blockCombine)/@set/.test(n.name)||p("get",n),n.isReadOnly||("number"==n.retType&&p("change",n),p("set",n));else if(n.attributes.block&&!n.attributes.fixedInstance&&7!=n.kind&&5!=n.kind&&9!=n.kind&&8!=n.kind){if(n.attributes.blockId||(n.attributes.blockId=n.qName.replace(/\./g,"_")),"true"==n.attributes.block){let t=e.U.uncapitalize(n.name);1!=n.kind&&2!=n.kind||(t+=" %"+n.namespace.toLowerCase());const o=null!==(a=null===(i=n.parameters)||void 0===i?void 0:i.filter((e=>!s(e))))&&void 0!==a?a:[];for(let e of o)t+=" %"+e.name;n.attributes.block=t,r(n.attributes)}o.push(n)}}for(let n of o){let i=e.U.lookup(t.byQName,n.namespace);if(!i)continue;let s=i.attributes,r=n.attributes;for(let e of["blockNamespace","color","blockGap"])void 0===r[e]&&s[e]&&(r[e]=s[e])}var f;return n&&((f=n).length&&(o=o.filter((e=>{let t=(e.attributes.blockNamespace||e.namespace).split(".")[0];return-1===f.indexOf(t)})))),{apis:t,blocks:o,blocksById:pxt.Util.toDictionary(o,(e=>e.attributes.blockId)),enumsByName:d,kindsByName:h}},e.tsSnippetToPySnippet=function(t,n){const i={true:"True",false:"False",null:"None"}[t];if(i)return i;if(n&&6==n.kind||!n&&t.includes(".")){const n=t.lastIndexOf("."),i=t.substr(0,n);let s=t.substr(n+1);return s=e.U.snakify(s).toUpperCase(),`${i}.${s}`}return t},e.apiLocalizationStrings={},e.localizeApisAsync=async function(n,i){const s=e.Util.userLanguage();if("en"==s)return Promise.resolve(t(n));const a=s.toLowerCase(),o=a+"|jsdoc",l=a+"|block",c=await i.localizationStringsAsync(s);e.apiLocalizationStrings&&e.Util.jsonMergeFrom(c,e.apiLocalizationStrings);const u=e.Util.values(n.byQName).filter((e=>e.attributes._translatedLanguageCode!==s));return await e.Util.promiseMapAll(u,(async t=>{var i,u,d;const h=t.attributes.useLoc||t.attributes.blockAliasFor,p=h&&n.byQName[h];t.attributes._untranslatedJsDoc&&(t.attributes.jsDoc=t.attributes._untranslatedJsDoc),t.attributes._untranslatedBlock&&(t.attributes.jsDoc=t.attributes._untranslatedBlock);const f=(e,n)=>{var i,s;return c[t.qName+e]||(null===(i=t.attributes.locs)||void 0===i?void 0:i[n])||p&&(c[p.qName+e]||(null===(s=p.attributes.locs)||void 0===s?void 0:s[n]))},g=f("",o);g&&(t.attributes._untranslatedJsDoc||(t.attributes._untranslatedJsDoc=t.attributes.jsDoc),t.attributes.jsDoc=g),null===(i=t.parameters)||void 0===i||i.forEach((e=>{const t=`|param|${e.name}`,n=f(t,a+t);n&&(e.description=n)}));const m=c["{id:category}"+e.Util.capitalize(t.qName)];let b=c[`${t.qName}|block`]||(null===(u=t.attributes.locs)||void 0===u?void 0:u[l]);if(!b&&p){const e=c[`${p.qName}|block`]||(null===(d=p.attributes.locs)||void 0===d?void 0:d[l]);t.attributes.block===(p.attributes._untranslatedBlock||p.attributes.block)&&e&&(b=e)}if(b&&pxt.Util.isTranslationMode()&&(t.attributes.translationId=b,b=await pxt.crowdin.inContextLoadAsync(b)),m)t.attributes.block?t.attributes.block=b||t.attributes.block:t.attributes.block=m,r(t.attributes);else if(t.attributes.block&&b){const e=pxt.blocks.compileInfo(t),n=t.attributes.block;if(t.attributes.block=pxt.blocks.normalizeBlock(b,(e=>{pxt.tickEvent("loc.normalized",{block:t.attributes.block,lang:s,error:e})})),t.attributes._untranslatedBlock||(t.attributes._untranslatedBlock=n),n!=t.attributes.block){r(t.attributes);(function(e,t){if(e.parameters.length!=t.parameters.length)return pxt.debug("Localized block has extra or missing parameters"),!1;for(const n of e.parameters){const e=t.actualNameToParam[n.actualName];if(!e||n.type!=e.type||n.shadowBlockId!=e.shadowBlockId)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:s}),t.attributes.block=n,r(t.attributes))}}else r(t.attributes);t.attributes._translatedLanguageCode=s})),t(n)},e.emptyExtInfo=function(){let e=pxt.appTarget.compileService;e||(e={});const t=!!e.platformioIni,n="dockermake"==e.buildEngine||"dockercross"==e.buildEngine||"dockerespidf"==e.buildEngine,i={functions:[],generatedFiles:{},extensionFiles:{},sha:"",compileData:"",shimsDTS:"",enumsDTS:"",onlyPublic:!0};return t?i.platformio={dependencies:{}}:n?i.npmDependencies={}:i.yotta={config:{},dependencies:{}},i};const n=["weight","imageLiteral","topblockWeight"],i=["advanced","handlerStatement","afterOnStart","optionalVariableArgs","blockHidden","constantShim","blockCombine","enumIsBitMask","enumIsHash","decompileIndirectFixedInstances","topblock","callInDebugger","duplicateShadowOnDrag","argsNullable"];function s(e){return"Action"===e.type||/^\([^\)]*\)\s*=>/.test(e.type)}function r(e){if(e.block){const n=e.block.split("||");e._def=t(a(n[0])),e._def||pxt.debug("Unable to parse block def for id: "+e.blockId),n[1]&&(e._expandedDef=t(a(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 a(e){const t=[];let n,i=0;for(;i<e.length;i++){const s=e[i],r=i;let a;switch(s){case"*":case"_":const t=d((e=>e==s)),n="_"===s?2:0;1===t.length?a={kind:1<<n,content:t}:2===t.length?a={kind:2<<n,content:t}:3===t.length?a={kind:3<<n,content:t}:i=r;break;case"`":const o=h("`");if(void 0===o){i=r;break}a={kind:256,content:o};break;case"|":a={kind:32};break;case"\\":i<e.length-1&&(a={kind:16,content:e[1+i++]});break;case"[":const l=h("]");if(void 0!==l&&"("===e[1+i++]){const e=h(")");if(void 0!==e){a={kind:512,content:l,type:e};break}}i=r;break;case"$":case"%":const c=d((e=>/[a-zA-Z0-9_=]/.test(e)),!0).split("=");if(c.length>2){i=r;break}let u;if("("===e[i+1]){const e=i;++i,u=h(")"),u||(i=e)}a={kind:"$"===s?1024:64,content:c[0],type:c[1],name:u}}a?(n&&t.push({kind:128,content:n}),n=void 0,t.push(a)):n?n+=s:n=s}n&&t.push({kind:128,content:n});const s=[],r=[];let a=[],l=0,c="",u=[];for(let e=0;e<t.length;e++){const n=t[e].kind,i=a[a.length-1];if(15&n)if(g(t[e].content),n&l)if(i&n){a.pop(),l^=n;const e=i&l|n&l;e&&a.push(e)}else p();else l|=n,a.push(n);else 144&n?c+=t[e].content:1120&n&&f();if(64==n){const n={kind:"param",name:t[e].content,shadowBlockId:t[e].type,ref:!1};t[e].name&&(n.varName=t[e].name),s.push(n),r.push(n)}else if(1024==n){const n={kind:"param",name:t[e].content,shadowBlockId:t[e].type,ref:!0};t[e].name&&(n.varName=t[e].name),s.push(n),r.push(n)}else 256==n?(g(),u.push({kind:"image",uri:t[e].content})):512==n?(g(),u.push({kind:"label",text:t[e].content,cssClass:t[e].type})):32==n&&s.push({kind:"break"})}return f(),{parts:s,parameters:r};function d(t,n=!1){let s="";for(n&&i++;i<e.length&&t(e[i]);)s+=e[i],++i;return s&&i--,s}function h(t){const n=d((e=>e!==t),!0);if(e[i+1]===t)return++i,n}function p(){let e="",t=[];for(const n of u)o(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}),a=[],l=0}function f(){for(g(),l&&p();u.length;){const e=u.shift();if(o(e))s.push(e);else{if(!e.content)continue;const t=[];10&e.styles&&t.push("bold"),5&e.styles&&t.push("italics"),s.push({kind:"label",text:e.content,style:t})}}}function g(e){u.push({content:c,styles:l,endingToken:e}),c=""}}function o(e){return!!e.kind}let l;e.parseCommentString=function(t){let s={paramDefl:{},callingConvention:0,_source:t},a=!0;for(;a;)a=!1,t=t.replace(/\/\/%[ \t]*([\w\.-]+)(=(("[^"\n]*")|'([^'\n]*)'|([^\s]*)))?/,((t,n,i,r,o,l,c)=>{let u=o?JSON.parse(o):i?o||l||c:"true";if(u||(u=""),e.U.startsWith(n,"block.loc."))s.locs||(s.locs={}),s.locs[n.slice("block.loc.".length).toLowerCase()+"|block"]=u;else if(e.U.startsWith(n,"jsdoc.loc."))s.locs||(s.locs={}),s.locs[n.slice("jsdoc.loc.".length).toLowerCase()+"|jsdoc"]=u;else if(e.U.contains(n,".loc.")){s.locs||(s.locs={});const e=n.slice(0,n.indexOf(".loc.")),t=n.slice(n.indexOf(".loc.")+".loc.".length);s.locs[t+"|param|"+e]=u}else if(e.U.endsWith(n,".defl"))u.indexOf(" ")>-1?s.paramDefl[n.slice(0,n.length-5)]=`"${u}"`:s.paramDefl[n.slice(0,n.length-5)]=u,s.explicitDefaults||(s.explicitDefaults=[]),s.explicitDefaults.push(n.slice(0,n.length-5));else if(e.U.endsWith(n,".shadow"))s._shadowOverrides||(s._shadowOverrides={}),s._shadowOverrides[n.slice(0,n.length-7)]=u;else if(e.U.endsWith(n,".fieldEditor"))s.paramFieldEditor||(s.paramFieldEditor={}),s.paramFieldEditor[n.slice(0,n.length-12)]=u;else if(e.U.contains(n,".fieldOptions.")){s.paramFieldEditorOptions||(s.paramFieldEditorOptions={});const e=n.slice(0,n.indexOf(".fieldOptions.")),t=n.slice(n.indexOf(".fieldOptions.")+14,n.length);s.paramFieldEditorOptions[e]||(s.paramFieldEditorOptions[e]={}),s.paramFieldEditorOptions[e][t]=u}else if(e.U.contains(n,".shadowOptions.")){s.paramShadowOptions||(s.paramShadowOptions={});const e=n.slice(0,n.indexOf(".shadowOptions.")),t=n.slice(n.indexOf(".shadowOptions.")+15,n.length);s.paramShadowOptions[e]||(s.paramShadowOptions[e]={}),s.paramShadowOptions[e][t]=u}else e.U.endsWith(n,".min")?(s.paramMin||(s.paramMin={}),s.paramMin[n.slice(0,n.length-4)]=u):e.U.endsWith(n,".max")?(s.paramMax||(s.paramMax={}),s.paramMax[n.slice(0,n.length-4)]=u):s[n]=u;return a=!0,"//% "}));for(let e of n)"string"==typeof s[e]&&(s[e]=parseInt(s[e]));for(let e of i)"string"==typeof s[e]&&(s[e]="true"==s[e]||"1"==s[e]);if(s.trackArgs&&(s.trackArgs=s.trackArgs.split(/[ ,]+/).map((e=>parseInt(e)||0))),s.enumInitialMembers&&(s.enumInitialMembers=s.enumInitialMembers.split(/[ ,]+/)),s.blockExternalInputs&&!s.inlineInputMode&&(s.inlineInputMode="external"),s.paramHelp={},s.jsDoc="",t=t.replace(/\/\*\*([^]*?)\*\//g,((e,t)=>(t=(t=t.replace(/\n\s*(\*\s*)?/g,"\n")).replace(/^\s*@param\s+(\w+)\s+(.*)$/gm,((e,t,n)=>{if(s.paramHelp[t]=n,!s.paramDefl[t]){let e=/\beg\.?:\s*(.+)/.exec(n);if(e&&e[1]){let n=/(?:"([^"]*)")|(?:'([^']*)')|(?:([^\s,]+))/g.exec(e[1]);if(n){let e=n[1]||n[2]||n[3];e||(e=""),e.indexOf(" ")>-1?s.paramDefl[t]=`"${e}"`:s.paramDefl[t]=e}}}return""})),s.jsDoc+=t,""))),s.jsDoc=s.jsDoc.trim(),s.async&&(s.callingConvention=1),s.promise&&(s.callingConvention=2),s.jres&&(s.whenUsed=!0),s.subcategories)try{s.subcategories=JSON.parse(s.subcategories)}catch(e){s.subcategories=void 0}if(s.groups)try{s.groups=JSON.parse(s.groups)}catch(e){s.groups=void 0}if(s.groupIcons)try{s.groupIcons=JSON.parse(s.groupIcons)}catch(e){s.groupIcons=void 0}if(s.groupHelp)try{s.groupHelp=JSON.parse(s.groupHelp)}catch(e){s.groupHelp=void 0}return r(s),s},e.parameterTypeIsArrowFunction=s,e.updateBlockDef=r,e.parseBlockDefinition=a,e.parseChecksumBlock=function(e,t=0){let n=pxt.HF2.read32(e,t);if(133083260!=(2147483647&n))return pxt.log("no checksum block magic"),null;let i=pxt.HF2.read32(e,t+4),s=pxt.HF2.read32(e,t+8);if(3&i)return pxt.log("invalid end marker position"),null;let r=1<<(255&s);if(r!=pxt.appTarget.compile.flashCodeAlign)return pxt.log("invalid page size: "+r),null;let a={magic:n,endMarkerPos:i,endMarker:s,regions:[]};for(let n=t+12;n<e.length-7;n+=8){let t={start:r*pxt.HF2.read16(e,n),length:r*pxt.HF2.read16(e,n+2),checksum:pxt.HF2.read32(e,n+4)};if(!t.length||!t.checksum)break;a.regions.push(t)}return a},function(t){function n(n){let i=e=>n[e]+(n[e+1]<<8)+(n[e+2]<<16)+(n[e+3]<<24)>>>0;if(!n||512!=n.length||i(0)!=t.UF2_MAGIC_START0||i(4)!=t.UF2_MAGIC_START1||i(n.length-4)!=t.UF2_MAGIC_END)return null;let s=i(8),r=i(16);r>476&&(r=256);let a=null,o=0,l=0;if(s&t.UF2_FLAG_FILE){let t=n.slice(32+r),s=t.indexOf(0);s>=0&&(t=t.slice(0,s)),a=e.U.fromUTF8Array(t),l=i(28)}return s&t.UF2_FLAG_FAMILY_ID_PRESENT&&(o=i(28)),{flags:s,targetAddr:i(12),payloadSize:r,blockNo:i(20),numBlocks:i(24),fileSize:l,familyId:o,data:n.slice(32,32+r),filename:a}}function i(e,t){return!!e&&(e.targetAddr<=t&&t<e.targetAddr+e.payloadSize)}function s(e,t,n){e[t]=255&n,e[t+1]=n>>8&255,e[t+2]=n>>16&255,e[t+3]=n>>24&255}function r(e){return"string"==typeof e&&(e=parseInt(e)),{currBlock:null,currPtr:-1,blocks:[],ptrs:[],filesize:0,familyId:e||0}}function a(e){for(let t=0;t<e.blocks.length;++t)s(e.blocks[t],20,t),s(e.blocks[t],24,e.blocks.length),e.filename&&s(e.blocks[t],28,e.filesize)}function o(n,i,r,a=0){let l=n.currBlock,c=i>>8,u=256-(255&i);if(r.length>u){let e=new Uint8Array(r);for(o(n,i,e.slice(0,u));u<r.length;){let t=Math.min(u+256,r.length);o(n,i+u,e.slice(u,t)),u=t}return}if(c!=n.currPtr){l=null;for(let e=0;e<n.ptrs.length;++e)if(n.ptrs[e]==c){l=n.blocks[e];break}if(!l){l=new Uint8Array(512),n.filename?a|=t.UF2_FLAG_FILE:n.familyId&&(a|=t.UF2_FLAG_FAMILY_ID_PRESENT),s(l,0,t.UF2_MAGIC_START0),s(l,4,t.UF2_MAGIC_START1),s(l,8,a),s(l,12,c<<8),s(l,16,256),s(l,20,n.blocks.length),s(l,28,n.familyId),s(l,508,t.UF2_MAGIC_END);for(let e=32;e<288;++e)l[e]=255;n.filename&&e.U.memcpy(l,288,e.U.toUTF8Array(n.filename)),n.blocks.push(l),n.ptrs.push(c)}n.currPtr=c,n.currBlock=l}let d=32+(255&i);for(let e=0;e<r.length;++e)l[d+e]=r[e];n.filesize=Math.max(n.filesize,r.length+i)}t.UF2_MAGIC_START0=171066965,t.UF2_MAGIC_START1=2656915799,t.UF2_MAGIC_END=179400496,t.UF2_FLAG_NONE=0,t.UF2_FLAG_NOFLASH=1,t.UF2_FLAG_FILE=4096,t.UF2_FLAG_FAMILY_ID_PRESENT=8192,t.parseBlock=n,t.parseFile=function(e){let t=[];for(let i=0;i<e.length;i+=512){let s=n(e.slice(i,i+512));s&&t.push(s)}return t},t.toBin=function(e,t){if(e.length<512)return null;let i=-1,s=-1,r=[];for(let a=0;a<e.length;++a){let o=512*a,l=n(e.slice(o,o+512));if(!l)continue;if(t&&l.targetAddr+256>t)break;-1==i&&(i=l.targetAddr,s=i);let c=l.targetAddr-i;c<0||c%4||c>1048576||(c>0&&r.push(new Uint8Array(c)),r.push(e.slice(o+32,o+32+l.payloadSize)),i=l.targetAddr+l.payloadSize)}let a=0;for(let e of r)a+=e.length;if(0==a)return null;let o=new Uint8Array(a),l=0;for(let e of r)for(let t=0;t<e.length;++t)o[l++]=e[t];return{buf:o,start:s}},t.readBytes=function(e,t,n){let s,r=new Uint8Array(n);for(let a=0;a<n;++a,++t)i(s,t)||(s=e.filter((e=>i(e,t)))[0]),s&&(r[a]=s.data[t-s.targetAddr]);return r},t.newBlockFile=r,t.finalizeFile=a,t.concatFiles=function(t){for(let e of t)a(e),e.filename=null;let n=r();n.blocks=e.U.concat(t.map((e=>e.blocks)));for(let e of t)e.blocks=[];return n},t.serializeFile=function(t){a(t);let n="";for(let i of t.blocks)n+=e.Util.uint8ArrayToString(i);return n},t.readBytesFromFile=function t(n,i,s){let r,a=i>>8;if(a==n.currPtr)r=n.currBlock;else{for(let e=0;e<n.ptrs.length;++e)if(n.ptrs[e]==a){r=n.blocks[e];break}r&&(n.currPtr=a,n.currBlock=r)}if(!r)return null;let o=new Uint8Array(s),l=Math.min(s,256-(255&i));e.U.memcpy(o,0,r,32+(255&i),l);let c=s-l;if(c>0){let s=t(n,i+l,c);e.U.memcpy(o,l,s)}return o},t.writeBytes=o,t.writeHex=function(e,t){let n="0000";for(let i=0;i<t.length;++i){let s=/:02000004(....)/.exec(t[i]);if(s&&(n=s[1]),s=/^:..(....)00(.*)[0-9A-F][0-9A-F]$/.exec(t[i]),s){let t=parseInt(n+s[1],16),i=s[2],r=[];for(let e=0;e<i.length;e+=2)r.push(parseInt(i[e]+i[e+1],16));o(e,t,r)}}}}(l=e.UF2||(e.UF2={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){let n,i;!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 s=!1,r=!1;function a(){if(void 0===i){if(e.BrowserUtils.hasWindow()){const t=/sandbox=1|#sandbox|#sandboxproject/i.test(window.location.href)||e.BrowserUtils.isIFrame(),a=/nosandbox=1/i.test(window.location.href),o=/controller=1/i.test(window.location.href)&&e.BrowserUtils.isIFrame(),l=/readonly=1/i.test(window.location.href),c=/editorlayout=(widget|sandbox|ide)/i.exec(window.location.href),u=/noproject=1/i.test(window.location.href);if(i=n.IDE,a?i=n.Widget:o?i=n.Controller:t&&(i=n.Sandbox),o&&l&&(s=!0),o&&u&&(r=!0),c)switch(c[1].toLowerCase()){case"widget":i=n.Widget;break;case"sandbox":i=n.Sandbox;break;case"ide":i=n.IDE}}else i=n.Sandbox;e.debug(`shell: layout type ${n[i]}, readonly ${l()}`)}}function o(){return a(),i==n.Sandbox}function l(){return!e.BrowserUtils.hasWindow()||o()&&!/[?&]edit=1/i.test(window.location.href)||c()&&s}function c(){return a(),i==n.Controller}t.layoutTypeClass=function(){return a(),e.shell.EditorLayoutType[i].toLowerCase()},t.isSandboxMode=o,t.isReadOnly=l,t.isNoProject=function(){return r},t.isControllerMode=c,t.isPyLangPref=function(){return"py"==e.storage.getLocal("editorlangpref")},t.getEditorLanguagePref=function(){return e.storage.getLocal("editorlangpref")},t.setEditorLanguagePref=function(t){t.match(/prj$/)&&(t=t.replace(/prj$/,"")),e.storage.setLocal("editorlangpref",t)},t.getToolboxAnimation=function(){return e.storage.getLocal("toolboxanimation")},t.setToolboxAnimation=function(){e.storage.setLocal("toolboxanimation","1")}}(e.shell||(e.shell={}))}(pxt||(pxt={})),function(e){!function(t){t.USER_VERSION="0.0.1";class n{constructor(){this.db=new e.BrowserUtils.IDBWrapper(n.databaseName,n.version,((e,t)=>{const i=t.result;e.oldVersion<1&&(i.createObjectStore(n.projectTable,{keyPath:n.projectKey}),i.createObjectStore(n.userTable,{keyPath:n.userKey}))}))}initAsync(){return this.db.openAsync()}getAllProjectsAsync(){return this.db.getAllAsync(n.projectTable).then((e=>e.map((e=>e.project)).filter((e=>!e.deleted))))}deleteProjectAsync(e){return this.getProjectAsync(e).then((e=>{e.deleted=!0,this.saveProjectAsync(e)}))}getProjectAsync(e){return this.db.getAsync(n.projectTable,e).then((e=>{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,i;!function(e){e[e.userSpaceOnUse=0]="userSpaceOnUse",e[e.objectBoundingBox=1]="objectBoundingBox"}(n=t.PatternUnits||(t.PatternUnits={})),function(e){e[e.em=0]="em",e[e.ex=1]="ex",e[e.px=2]="px",e[e.in=3]="in",e[e.cm=4]="cm",e[e.mm=5]="mm",e[e.pt=6]="pt",e[e.pc=7]="pc",e[e.percent=8]="percent"}(i=t.LengthUnit||(t.LengthUnit={}));class s{constructor(e){this.el=x(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=x("title"),this.el.firstChild?this.el.insertBefore(this.titleElement,this.el.firstChild):this.el.appendChild(this.titleElement)),this.titleElement.textContent=e}setVisible(e){return this.setAttribute("visibility",e?"visible":"hidden")}}t.BaseElement=s;class r extends s{draw(e){const t=function(e){switch(e){case"text":return new d;case"circle":return new p;case"rect":return new h;case"line":return new f;case"polygon":return new b;case"polyline":return new m;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 a;return this.el.appendChild(e.el),e}appendChild(e){this.el.appendChild(e.el)}onDown(e){return t.events.down(this.el,e),this}onUp(e){return t.events.up(this.el,e),this}onMove(e){return t.events.move(this.el,e),this}onEnter(e){return t.events.enter(this.el,e),this}onLeave(e){return t.events.leave(this.el,e),this}onClick(e){return t.events.click(this.el,e),this}}t.DrawContext=r;t.SVG=class extends r{constructor(e){super("svg"),e&&e.appendChild(this.el)}define(e){return this.defs||(this.defs=new l(this.el)),e(this.defs),this}};class a extends r{constructor(e){super("g"),e&&e.appendChild(this.el)}translate(e,t){return this.left=e,this.top=t,this.updateTransform()}scale(e){return this.scaleFactor=e,this.updateTransform()}def(){return new l(this.el)}style(){return new c(this.el)}updateTransform(){let e="";return null!=this.left&&(e+=`translate(${this.left} ${this.top})`),null!=this.scaleFactor&&(e+=` scale(${this.scaleFactor})`),this.setAttribute("transform",e),this}}t.Group=a;class o extends r{constructor(){super("pattern")}units(e){return this.setAttribute("patternUnits",e===n.objectBoundingBox?"objectBoundingBox":"userSpaceOnUse")}contentUnits(e){return this.setAttribute("patternContentUnits",e===n.objectBoundingBox?"objectBoundingBox":"userSpaceOnUse")}size(e,t){return this.setAttribute("width",e),this.setAttribute("height",t),this}}t.Pattern=o;class l extends s{constructor(e){super("defs"),e.appendChild(this.el)}create(e,t){let n;switch(e){case"path":n=new y;break;case"pattern":n=new o;break;case"radialGradient":n=new k;break;case"linearGradient":n=new w;break;case"clipPath":n=new A;break;default:n=new s(e)}return n.id(t),this.el.appendChild(n.el),n}}t.DefsElement=l;class c extends s{constructor(e){super("style"),e.appendChild(this.el)}content(e){this.el.textContent=e}}t.StyleElement=c;class u extends r{at(e,t){return this.setAttribute("x",e),this.setAttribute("y",t),this}moveTo(e,t){return this.at(e,t)}fill(e,t){return this.setAttribute("fill",e),null!=t&&this.opacity(t),this}opacity(e){return this.setAttribute("fill-opacity",e)}stroke(e,t){return this.setAttribute("stroke",e),null!=t&&this.strokeWidth(t),this}strokeWidth(e){return this.setAttribute("stroke-width",e)}strokeOpacity(e){return this.setAttribute("stroke-opacity",e)}clipPath(e){return this.setAttribute("clip-path",e)}}t.Drawable=u;class d extends u{constructor(e){super("text"),null!=e&&this.text(e)}text(e){return this.el.textContent=e,this}fontFamily(e){return this.setAttribute("font-family",e)}fontSize(e,t){return this.setAttribute("font-size",E(e,t))}offset(e,t,n){return 0!==e&&this.setAttribute("dx",E(e,n)),0!==t&&this.setAttribute("dy",E(t,n)),this}anchor(e){return this.setAttribute("text-anchor",e)}}t.Text=d;class h extends u{constructor(){super("rect")}width(e,t=i.px){return this.setAttribute("width",E(e,t))}height(e,t=i.px){return this.setAttribute("height",E(e,t))}corner(e){return this.corners(e,e)}corners(e,t){return this.setAttribute("rx",e),this.setAttribute("ry",t),this}size(e,t,n=i.px){return this.width(e,n),this.height(t,n),this}}t.Rect=h;class p extends u{constructor(){super("circle")}at(e,t){return this.setAttribute("cx",e),this.setAttribute("cy",t),this}radius(e){return this.setAttribute("r",e)}}t.Circle=p;class f extends u{constructor(){super("line")}at(e,t,n,i){return this.from(e,t),null!=n&&null!=i&&this.to(n,i),this}from(e,t){return this.setAttribute("x1",e),this.setAttribute("y1",t),this}to(e,t){return this.setAttribute("x2",e),this.setAttribute("y2",t),this}}t.Line=f;class g 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=g;class m extends g{constructor(){super("polyline")}}t.Polyline=m;class b extends g{constructor(){super("polygon")}}t.Polygon=b;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=i.px){return this.setAttribute("width",E(e,t))}height(e,t=i.px){return this.setAttribute("height",E(e,t))}size(e,t,n=i.px){return this.width(e,n),this.height(t,n),this}};class v extends s{units(e){return this.setAttribute("gradientUnits",e===n.objectBoundingBox?"objectBoundingBox":"userSpaceOnUse")}stop(e,t,n){const i=x("stop");return i.setAttribute("offset",e+"%"),null!=t&&i.setAttribute("stop-color",t),null!=n&&i.setAttribute("stop-opacity",n),this.el.appendChild(i),this}}t.Gradient=v;class w extends v{constructor(){super("linearGradient")}start(e,t){return this.setAttribute("x1",e),this.setAttribute("y1",t),this}end(e,t){return this.setAttribute("x2",e),this.setAttribute("y2",t),this}}t.LinearGradient=w;class k extends v{constructor(){super("radialGradient")}center(e,t){return this.setAttribute("cx",e),this.setAttribute("cy",t),this}focus(e,t,n){return this.setAttribute("fx",e),this.setAttribute("fy",t),this.setAttribute("fr",n),this}radius(e){return this.setAttribute("r",e)}}t.RadialGradient=k;class A extends r{constructor(){super("clipPath")}clipPathUnits(e){return e?this.setAttribute("clipPathUnits","objectBoundingBox"):this.setAttribute("clipPathUnits","userSpaceOnUse")}}function x(e){return document.createElementNS("http://www.w3.org/2000/svg",e)}t.ClipPath=A;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,i,s,r){return this.op("C",e,t,n,i,s,r)}cCurveBy(e,t,n,i,s,r){return this.op("c",e,t,n,i,s,r)}qCurveTo(e,t,n,i){return this.op("Q",e,t,n,i)}qCurveBy(e,t,n,i){return this.op("q",e,t,n,i)}sCurveTo(e,t,n,i){return this.op("S",e,t,n,i)}sCurveBy(e,t,n,i){return this.op("s",e,t,n,i)}tCurveTo(e,t){return this.op("T",e,t)}tCurveBy(e,t){return this.op("t",e,t)}arcTo(e,t,n,i,s,r,a){return this.op("A",e,t,n,i?1:0,s?1:0,r,a)}arcBy(e,t,n,i,s,r,a){return this.op("a",e,t,n,i?1:0,s?1:0,r,a)}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 E(e,t){switch(t){case i.em:return e+"em";case i.ex:return e+"ex";case i.px:return e+"px";case i.in:return e+"in";case i.cm:return e+"cm";case i.mm:return e+"mm";case i.pt:return e+"pt";case i.pc:return e+"pc";case i.percent:return e+"%";default:return e.toString()}}t.PathContext=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,i){n()?e.addEventListener("pointerdown",i):t()?(e.addEventListener("mousedown",i),e.addEventListener("touchstart",i)):e.addEventListener("mousedown",i)},e.up=function(e,i){n()?e.addEventListener("pointerup",i):(t(),e.addEventListener("mouseup",i))},e.enter=function(e,i){n()?e.addEventListener("pointerover",(e=>{i(!!(1&e.buttons))})):t()?e.addEventListener("touchstart",(e=>{i(!0)})):e.addEventListener("mouseover",(e=>{i(!!(1&e.buttons))}))},e.leave=function(e,i){n()?e.addEventListener("pointerleave",i):t()?e.addEventListener("touchend",i):e.addEventListener("mouseleave",i)},e.move=function(e,i){n()?e.addEventListener("pointermove",i):t()?e.addEventListener("touchmove",i):e.addEventListener("mousemove",i)},e.click=function(e,t){e.addEventListener("click",t)}}(e.events||(e.events={}))}(e.svgUtil||(e.svgUtil={}))}(pxt||(pxt={})),function(e){!function(e){!function(t){class n extends e.Text{at(e,t){return this.cx=e,this.cy=t,this.rePosition(),this}text(e,t=12){return super.text(e),this.fontSizePixels=t,this.setAttribute("font-size",t+"px"),this.rePosition(),this}rePosition(){null!=this.cx&&null!=this.cy&&null!=this.fontSizePixels&&(this.setAttribute("x",this.cx),this.setAttribute("y",this.cy),this.setAttribute("text-anchor","middle"),this.setAttribute("alignment-baseline","middle"))}}t.CenteredText=n}(e.helpers||(e.helpers={}))}(e.svgUtil||(e.svgUtil={}))}(pxt||(pxt={})),function(e){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=a(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),a(t)}}getSnapshot(e){return e?this.assets.filter((t=>e(t))).map(a):this.assets.map(a)}update(e,t){let n;if(this.takenNames[e]){l(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&&a(t)}getByDisplayName(e){if(this.takenNames[e])for(const t of this.assets)if(t.meta.displayName===e||u(t)===e)return a(t)}isIDTaken(e){return!!this.takenNames[e]}clone(){const e=new t;return e.assets=this.getSnapshot(),e.takenNames=Object.assign({},this.takenNames),e}serializeToJRes(e={}){for(const t of this.assets)o(t,e);return e}addListener(e,t){this.listeners.push({internalID:e,callback:t})}removeListener(e){this.listeners=this.listeners.filter((t=>t.callback!==e))}diff(e){let t={before:[],after:[]},n={};for(const i of e.assets){n[i.internalID]=!0;const e=this.lookupByInternalID(i.internalID);e&&l(i,e)||(t.before.push(i),t.after.push(e))}for(const e of this.assets.filter((e=>!n[e.internalID])))t.before.push(null),t.after.push(e);return t}applyDiff(t,n=!1){const i=n?t.after:t.before,s=n?t.before:t.after;e.Util.assert(i.length===s.length);for(let e=0;e<i.length;e++)i[e]?(this.removeByInternalID(i[e].internalID),s[e]&&this.assets.push(s[e]),this.notifyListener(i[e].internalID)):(this.assets.push(s[e]),this.notifyListener(s[e].internalID));this.takenNames={};for(const t of this.assets)e.Util.assert(!this.takenNames[t.id]),this.takenNames[t.id]=!0,this.takenNames[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 i of Object.keys(t)){const s=t[i];s.mimeType===e.TILEMAP_MIME_TYPE&&n.push(s)}return n}function i(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 s(t){return e.sprite.Bitmap.fromData(t).copy().data()}function r(t,n){const i=atob(t.data),s=e.U.fromHex(i),r=s[1]|s[2]<<8,a=s[3]|s[4]<<8,o={tileWidth:s[0],tiles:t.tileset.map((e=>n&&n(e)||{id:e}))},l=s.slice(5,5+r*a),c=new e.sprite.Tilemap(r,a,0,0,new Uint8ClampedArray(l)),u=s.slice(5+l.length),d=new e.sprite.Bitmap(r,a,0,0,new Uint8ClampedArray(u)).data();return new e.sprite.TilemapData(c,o,d)}function a(e){switch(e.meta=Object.assign({},e.meta),e.type){case"tile":case"image":return Object.assign(Object.assign({},e),{bitmap:s(e.bitmap)});case"animation":return Object.assign(Object.assign({},e),{frames:e.frames.map((e=>s(e)))});case"tilemap":return Object.assign(Object.assign({},e),{data:e.data.cloneData()})}}function o(t,n){const i=t.id.substr(t.id.lastIndexOf(".")+1);switch(t.type){case"image":n[i]=t.jresData,t.meta.displayName&&(n[i]={data:t.jresData,mimeType:e.IMAGE_MIME_TYPE,displayName:t.meta.displayName});break;case"tile":n[i]={data:t.jresData,mimeType:e.IMAGE_MIME_TYPE,tilemapTile:!0,displayName:t.meta.displayName};break;case"tilemap":const s=function(t,n,i){const s=t.tilemap.data(),r=new Uint8ClampedArray(5+s.data.length+t.layers.data.length);return r[0]=t.tileset.tileWidth,r[1]=255&s.width,r[2]=s.width>>8&255,r[3]=255&s.height,r[4]=s.height>>8&255,r.set(s.data,5),r.set(t.layers.data,5+s.data.length),{id:n,mimeType:e.TILEMAP_MIME_TYPE,data:btoa(e.sprite.uint8ArrayToHex(r)),tileset:t.tileset.tiles.map((e=>e.id)),displayName:i}}(t.data,t.id,t.meta.displayName);n[s.id]=s;break;case"animation":n[i]=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 l(t,n){if(t==n)return!0;if(t.id!==n.id||t.type!==n.type||!e.U.arrayEquals(t.meta.tags,n.meta.tags)||!e.U.arrayEquals(t.meta.blockIDs,n.meta.blockIDs)||t.meta.displayName!==n.meta.displayName)return!1;switch(t.type){case"image":case"tile":return e.sprite.bitmapEquals(t.bitmap,n.bitmap);case"animation":const i=n;return t.interval===i.interval&&e.U.arrayEquals(t.frames,i.frames,e.sprite.bitmapEquals);case"tilemap":return t.data.equals(n.data)}}function c(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,i=!1){let s;switch(t){case"image":s=e.sprite.IMAGES_NAMESPACE+".";break;case"tile":s=e.sprite.TILE_NAMESPACE+".";break;case"tilemap":s="";break;case"animation":s=e.sprite.ANIMATION_NAMESPACE+"."}if(s)if(n.startsWith(s)){const e=n.substr(s.length);if(-1===e.indexOf("."))return e}else if(!i)return null;return n}function h(t){const n=atob(t.data),i=new Uint8ClampedArray(e.U.fromHex(n)),s=p(i,0),r=p(i,2),a=p(i,4),o=p(i,6),l=Math.ceil(r*a/2);let c=8;const u=[];for(let e=0;e<o;e++){const e=i.slice(c,c+l);u.push({x0:0,y0:0,width:r,height:a,data:e}),c+=l}let d=t.id;return d.startsWith(t.namespace)||(d=t.namespace+"."+d,d=d.replace(/\.\./g,".")),{type:"animation",internalID:0,id:d,interval:s,frames:u,meta:{displayName:t.displayName}}}function p(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 i=this.generateNewID("image"),s=new e.sprite.Bitmap(t,n).data(),r={internalID:this.getNewInternalId(),id:i,type:"image",bitmap:s,meta:{},jresData:e.sprite.base64EncodeBitmap(s)};return this.state.images.add(r)}createNewAnimation(t=16,n=16){const i=this.generateNewID("animation"),s=new e.sprite.Bitmap(t,n).data(),r={internalID:this.getNewInternalId(),id:i,type:"animation",frames:[s],interval:500,meta:{}};return this.state.animations.add(r)}createNewAnimationFromData(e,t=500,n){const i=this.generateNewID("animation"),s={internalID:this.getNewInternalId(),id:i,type:"animation",frames:e,interval:t,meta:{displayName:n}};return this.state.animations.add(s)}getGalleryTiles(e){return this.extensionTileSets?this.extensionTileSets.map((t=>t.tileSets.find((t=>t.tileWidth===e)))).filter((e=>null==e?void 0:e.tiles.length)):null}getProjectImages(){return this.state.images.getSnapshot()}getProjectTiles(t,n){const i=this.state.tiles.getSnapshot((e=>e.bitmap.width===t));return 0===i.length?n?(this.createNewTile(new e.sprite.Bitmap(t,t).data()),this.getProjectTiles(t,!1)):null:{tileWidth:t,tiles:i}}createNewTile(t,n,i){this.onChange(),n&&!this.isNameTaken("tile",n)||(n=this.generateNewID("tile"));const s={internalID:this.getNewInternalId(),id:n,type:"tile",jresData:e.sprite.base64EncodeBitmap(t),bitmap:t,meta:{displayName:i},isProjectTile:!0};return this.state.tiles.add(s)}createNewProjectImage(t,n){this.onChange();const i={internalID:this.getNewInternalId(),id:this.generateNewID("image"),type:"image",jresData:e.sprite.base64EncodeBitmap(t),meta:{displayName:n},bitmap:t};return this.state.images.add(i)}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 i=Object.assign(Object.assign({},n),{data:t});return this.state.tilemaps.update(e,i),i}return null}createNewTilemap(e,t,n=16,i=16){return this.createNewTilemapFromData(this.blankTilemap(t,n,i),e)}blankTilemap(t,n=16,i=16){const s=new e.sprite.Tilemap(n,i),r=new e.sprite.Bitmap(n,i),a={tileWidth:t,tiles:[this.getTransparency(t)]};return new e.sprite.TilemapData(s,a,r.data())}resolveTile(e){return this.lookupAsset("tile",e)}resolveProjectTileByInternalID(e){return this.state.tiles.getSnapshot((t=>t.internalID===e))[0]}resolveTileByBitmap(t){const n=e.sprite.base64EncodeBitmap(t);return this.state.tiles.getSnapshot((e=>e.jresData===n))[0]}getTransparency(t){const n=e.sprite.TILE_NAMESPACE+".transparency"+t;let i=this.state.tiles.getByID(n);if(!i){const s=new e.sprite.Bitmap(t,t).data();return i={internalID:this.getNewInternalId(),id:n,type:"tile",bitmap:s,jresData:e.sprite.base64EncodeBitmap(s),meta:{},isProjectTile:!0},this.state.tiles.add(i)}return i}createNewTilemapFromData(e,t){this.onChange();const n=this.generateNewIDInternal("tilemap",t||lf("level"));return this.state.tilemaps.add({internalID:this.getNewInternalId(),id:n,type:"tilemap",meta:{displayName: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 i=t.tilemap.data(),s=new Uint8ClampedArray(5+i.data.length+t.layers.data.length);return s[0]=t.tileset.tileWidth,s[1]=255&i.width,s[2]=i.width>>8&255,s[3]=255&i.height,s[4]=i.height>>8&255,s.set(i.data,5),s.set(t.layers.data,5+i.data.length),{id:n,mimeType:e.TILEMAP_MIME_TYPE,data:btoa(e.sprite.uint8ArrayToHex(s)),tileset:t.tileset.tiles.map((e=>e.id))}}forceUpdate(){this.onChange()}isNameTaken(e,t){const n=t=>{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)}},i=d(e,t),s=i&&i!==t;return n(t)||s&&n(i)}isAssetUsed(t,n,i){var s,r,a;if(((null===(r=null===(s=t.meta)||void 0===s?void 0:s.blockIDs)||void 0===r?void 0:r.filter((e=>!i||(null==i?void 0:i.indexOf(e))<0)))||[]).length>0)return!0;if("tile"==t.type)for(const e of this.getAssets("tilemap"))if(!((null==i?void 0:i.indexOf(e.id))>=0)&&e.data.tileset.tiles.some((e=>e.id===t.id)))return!0;if(n){const s=e.Util.escapeForRegex(u(t)),r=e.Util.escapeForRegex(null===(a=t.meta)||void 0===a?void 0:a.displayName)||"";let o;switch(t.type){case"tile":o=`myTiles.${s}|assets.tile\`${s}\``,r&&(o+=`|assets.tile\`${r}\``);break;case"tilemap":o=`tilemap\`${s}\``;break;case"animation":o=`assets.animation\`${s}\``,r&&(o+=`|assets.animation\`${r}\``);break;default:o=`assets.image\`${s}\``,r&&(o+=`|assets.image\`${r}\``)}const l=new RegExp(o,"gm");let c;switch(t.type){case"tile":c=`myTiles.${s}|assets.tile("""${s}""")`,r&&(c+=`|assets.tile("""${r}""")`);break;case"tilemap":c=`assets.tilemap("""${s}""")`;break;case"animation":c=`assets.animation("""${s}""")`,r&&(c+=`|assets.animation("""${r}""")`);break;default:c=`assets.image("""${s}""")`,r&&(c+=`|assets.image("""${r}""")`)}const d=new RegExp(c,"gm");for(let e of Object.keys(n)){if((null==i?void 0:i.indexOf(e))>=0)continue;const t=n[e];if(e.match(/((?!\.g).{2}|^.{0,1})\.ts$/i)){if(t.content.match(l))return!0}else if(e.endsWith(".py")&&t.content.match(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,i;return-1!==(null===(i=null===(n=e.meta)||void 0===n?void 0:n.blockIDs)||void 0===i?void 0:i.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 i=a(e),s=t||(null===(n=i.meta)||void 0===n?void 0:n.displayName);let r;switch(e.type){case"image":r=this.createNewProjectImage(i.bitmap,s);break;case"tile":r=this.createNewTile(i.bitmap,null,s);break;case"tilemap":const[e,t]=this.createNewTilemapFromData(i.data,s);r=this.getTilemap(e);break;case"animation":r=this.createNewAnimationFromData(i.frames,i.interval,s)}return r}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:r(t,(e=>this.resolveTile(e)))});this.committedState=this.cloneState(),this.undoStack=[],this.redoStack=[]}loadTilemapJRes(t,i=!1){t=e.inflateJRes(t);const s=this.readImages(t,!0).filter((e=>"tile"===e.type));let a={};for(const e of s){if(i){const t=this.resolveTileByBitmap(e.bitmap);if(t){a[e.id]=t.id;continue}}const t=this.createNewTile(e.bitmap,e.id,e.meta.displayName);t.id!==e.id&&(a[e.id]=t.id)}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:r(e,(e=>(a[e]&&(e=a[e]),this.resolveTile(e))))})}loadAssetsJRes(t){t=e.inflateJRes(t);const n=[];for(const i of Object.keys(t)){const s=t[i];if(s.tilemapTile)this.state.tiles.add(this.generateImage(s,"tile"));else if(s.mimeType===e.IMAGE_MIME_TYPE)this.state.images.add(this.generateImage(s,"image"));else if(s.mimeType===e.ANIMATION_MIME_TYPE){const[e,t]=this.generateAnimation(s);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))))})),i=[];for(const t of n)1===t.meta.blockIDs.length?i.push(t):(t.meta.blockIDs=t.meta.blockIDs.filter((t=>-1!==e.indexOf(t))),0===t.meta.blockIDs.length&&i.push(t));for(const e of i)t.removeByID(e.id)}t(this.state.images),t(this.state.tiles),t(this.state.tilemaps),t(this.state.animations)}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({},h(e)),{internalID:this.getNewInternalId()}),!1]}inflateAnimation(t,n){return t.frames=t.frameIds.map((e=>n.find((t=>t.id===e)).bitmap)),t.flippedHorizontal&&(t.frames=t.frames.map((t=>{const n=e.sprite.Bitmap.fromData(t),i=new e.sprite.Bitmap(t.width,t.height);for(let e=0;e<i.width;e++)for(let t=0;t<i.height;t++)i.set(e,t,n.get(n.width-e-1,t));return i.data()}))),t}generateNewID(t){switch(t){case"animation":return this.generateNewIDInternal("animation",e.sprite.ANIMATION_PREFIX,e.sprite.ANIMATION_NAMESPACE);case"image":return this.generateNewIDInternal("image",e.sprite.IMAGE_PREFIX,e.sprite.IMAGES_NAMESPACE);case"tile":return this.generateNewIDInternal("tile",e.sprite.TILE_PREFIX,e.sprite.TILE_NAMESPACE);case"tilemap":return this.generateNewIDInternal("tilemap",lf("level"))}}generateNewIDInternal(e,t,n){t=t.replace(/\d+$/,"");const i=n?n+"."+t:t;let s=1;for(;this.isNameTaken(e,i+s);)++s;return i+s}onChange(){this.needsRebuild=!0,this.state.revision=this.nextID++}readImages(t,n=!1){const i=[],s=[];for(const r of Object.keys(t)){const a=t[r];if(a.tilemapTile){const e=this.generateImage(a,"tile");e.isProjectTile=n,i.push(e)}else if(a.mimeType===e.IMAGE_MIME_TYPE)i.push(this.generateImage(a,"image"));else if(a.mimeType===e.ANIMATION_MIME_TYPE){const[e,t]=this.generateAnimation(a);t?s.push(e):i.push(e)}}for(const e of s)i.push(this.inflateAnimation(e,i));return i}cleanupTemporaryAssets(){const e=this.state.images.getSnapshot((e=>{var t;return!e.meta.displayName&&!(null===(t=e.meta.blockIDs)||void 0===t?void 0:t.length)}));for(const t of e)this.state.images.removeByID(t.id)}},e.emitTilemapsFromJRes=function(t){const n=Object.keys(t);let s="";const a=[],o=[];for(const i of n){if("*"===i)continue;const n=t[i];if(n.tilemapTile&&(s+=" //% fixedInstance jres blockIdentity=images._tile\n",s+=` export const ${i} = image.ofBuffer(hex\`\`);\n`,o.push({keys:[n.displayName,d("tile",i,!0)],expression:i})),n.mimeType===e.TILEMAP_MIME_TYPE){const t=r(n);a.push({keys:[n.displayName,d("tilemap",n.id)],expression:e.sprite.encodeTilemap(t,"typescript")})}}a.length&&(s+=i("tilemap",a)),o.length&&(s+=i("tile",o));const l=lf("Auto-generated code. Do not edit.");return`// ${l}\nnamespace ${e.sprite.TILE_NAMESPACE} {\n${s}\n}\n// ${l}\n`},e.emitProjectImages=function(t){const n=Object.keys(t);let s="";const r=[],a=[];for(const i of n){if("*"===i)continue;const n=t[i];if("string"==typeof n||n.mimeType===e.IMAGE_MIME_TYPE){let t,s=[d("image",i,!0)];"string"==typeof n?t=e.sprite.bitmapToImageLiteral(e.sprite.getBitmapFromJResURL(n),"typescript"):(t=e.sprite.bitmapToImageLiteral(e.sprite.getBitmapFromJResURL(n.data),"typescript"),s.push(n.displayName)),r.push({keys:s,expression:t})}else if(n.mimeType===e.ANIMATION_MIME_TYPE){const t=h(n);a.push({keys:[n.displayName,d("animation",i,!0)],expression:`[${t.frames.map((t=>e.sprite.bitmapToImageLiteral(e.sprite.Bitmap.fromData(t),"typescript"))).join(", ")}]`})}}const o=lf("Auto-generated code. Do not edit.");return s+=i("image",r),s+=i("animation",a),`// ${o}\nnamespace ${e.sprite.IMAGES_NAMESPACE} {\n${s}\n}\n// ${o}\n`},e.cloneAsset=a,e.assetEquals=l,e.validateAssetName=function(e){return!!e&&!/[\u0000-\u001f\u0021-\u002c\u002e\u002f\u003a-\u0040\u005b-\u005e\u0060\u007b-\u007f]/.test(e)},e.getTSReferenceForAsset=function(e,t=!1){var n;let i;if(i=(null===(n=e.meta)||void 0===n?void 0:n.displayName)?e.meta.displayName:u(e),!i)return"image"===e.type||"tile"===e.type?e.id:void 0;const s=t?'("""':"`",r=t?'""")':"`";switch(e.type){case"tile":return`assets.tile${s}${i}${r}`;case"image":return`assets.image${s}${i}${r}`;case"animation":return`assets.animation${s}${i}${r}`;case"tilemap":return`tilemap${s}${i}${r}`}},e.parseAssetTSReference=c,e.lookupProjectAssetByTSReference=function(e,t){const n=c(e);if(n){const{type:e,name:i}=n;switch(e){case"tile":return t.lookupAssetByName("tile",i);case"image":return t.lookupAssetByName("image",i);case"tilemap":return t.lookupAssetByName("tilemap",i)||t.lookupAsset("tilemap",i);case"animation":return t.lookupAssetByName("animation",i)}}},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 i(e){const t=function(e,t,n){let i=0,s=0,r=0;if(0==t)i=n,s=n,r=n;else{let a=Math.floor(e/60),o=e/60-a,l=n*(1-t),c=n*(1-t*o),u=n*(1-t*(1-o));switch(a){case 1:i=c,s=n,r=l;break;case 2:i=l,s=n,r=u;break;case 3:i=l,s=c,r=n;break;case 4:i=u,s=l,r=n;break;case 5:i=n,s=l,r=c;break;case 6:case 0:i=n,s=u,r=l}}return[Math.floor(i),Math.floor(s),Math.floor(r)]}(e,.45,165.75);return`#${s(t[0])}${s(t[1])}${s(t[2])}`}function s(e){const t=e.toString(16);return 1==t.length?"0"+t:t}t.appendToolboxIconCss=function(t,i){if(!(n.indexOf(t)>-1))if(1===i.length){const s=e.Util.unicodeToChar(i);n+=`\n .blocklyTreeIcon.${t}::before {\n content: "${s}";\n }\n `}else n+=`\n .blocklyTreeIcon.${t} {\n background-image: url("${e.Util.pathJoin(e.webConfig.commitCdnUrl,encodeURI(i))}")!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:i(n)},t.hueToRgb=i,t.fadeColor=function(e,t,n){(e=e.replace(/[^0-9a-f]/gi,"")).length<6&&(e=e[0]+e[0]+e[1]+e[1]+e[2]+e[2]);let i="#";for(let s=0;s<3;s++){let r=parseInt(e.substr(2*s,2),16);r=Math.round(Math.min(Math.max(0,n?r+r*t:r-r*t),255));let a=r.toString(16);i+=("00"+a).substr(a.length)}return i}}(e.toolbox||(e.toolbox={}))}(pxt||(pxt={})),function(e){!function(t){const n=/^##[^#](.*)$([\s\S]*?)(?=^##[^#]|$(?![\r\n]))/gim,i=/^###[^#](.*)$([\s\S]*?)(?=^###[^#]|$(?![\r\n]))/gim;function s(){return/``` *(sim|block|blocks|filterblocks|spy|ghost|typescript|ts|js|javascript|template|python|jres|assetjson|customts|tutorialValidationRules|requiredTutorialBlock)\s*\n([\s\S]*?)\n```/gim}function r(t,i,s){let r=i||n,o=[];if(t.replace(r,(function(e,t,n){n=n.trim();let{header:i,hint:r,requiredBlocks:l}=function(e,t,n){let i,s,r=e=a(e);if(t){const t=/#+ ~ tutorialhint([\s\S]*)/i;r=e.replace(t,(function(e,t){return i=t,""}))}else{const t=/(^[\s\S]*?\S)\s*((```|\[?\!\[[\s\S]+?\]\(\S+?\)\]?)[\s\S]*)/im;let a=e.match(t);if(a&&a.length>2&&(r=a[1].trim(),i=a[2].trim(),n)){let e=a[2].trim();e=e.replace(/``` *(requiredTutorialBlock)\s*\n([\s\S]*?)\n```/gim,(function(e,t,n){return s=`{\n${n}\n}`,""})),i=e}}return{header:r,hint:i,requiredBlocks:s}}(n,s&&s.explicitHints,s.tutorialCodeValidation);let c={title:t.match(/^\{.*\}$/)?void 0:t.replace(/@(fullscreen|unplugged|showdialog|showhint|tutorialCompleted|resetDiff)/gi,"").trim(),contentMd:n,headerContentMd:i};return/@(fullscreen|unplugged|showdialog|showhint)/i.test(t)&&(c.showHint=!0),/@(unplugged|showdialog)/i.test(t)&&(c.showDialog=!0),/@tutorialCompleted/.test(t)&&(c.tutorialCompleted=!0),/@resetDiff/.test(t)&&(c.resetDiff=!0),r&&(c.hintContentMd=r),s.tutorialCodeValidation&&l&&(c.requiredBlockMd=l),o.push(c),""})),0!=t.indexOf("# Not found"))return o;e.debug("tutorial not found")}function a(e){if(!e)return e;return e.replace(/```(filterblocks|package|ghost|config|template|jres|assetjson|customts)\s*\n([\s\S]*?)\n```/gim,"").trim()}function o(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:s,body:l}=function(t){const n=/### @(\S+) ([ \S]+)/gi,i={},s=t.replace(n,(function(e,t,n){try{i[t]=JSON.parse(n)}catch(e){i[t]=n}return""})),r=i;void 0!==r.explicitHints&&e.appTarget.appTheme&&e.appTarget.appTheme.tutorialExplicitHints&&(r.explicitHints=!0);return{metadata:r,body:s}}(t),{steps:c,activities:u}=function(e,t){if(t&&t.activities)return function(e,t){let s=[],a=[];return e.replace(n,(function(e,n,o){let l=a.length;a.push({name:n||lf("Activity {0}",l),step:s.length});let c=r(o,i,t);return c=c.map((e=>(e.activity=l,e))),s=s.concat(c),""})),{steps:s,activities:a}}(e,t);{let n=r(e,null,t);return(!n||n.length<1)&&(n=r(e,i,t)),{steps:n,activities:null}}}(l,s),d=function(e){let t=e.match(/^#[^#](.*)$/im);return t&&t.length>1?t[1].trim():null}(l);if(!c)return;const{code:h,templateCode:p,editor:f,language:g,jres:m,assetJson:b,customTs:y,tutorialValidationRulesStr:v}=function(t){let n;const i=/``` *(sim|block|blocks|filterblocks|spy|ghost|typescript|ts|js|javascript|template|python|jres|assetjson|customts|tutorialValidationRules|requiredTutorialBlock)\s*\n([\s\S]*?)\n```/gim;let s,r,a,o,l,c,u=[];return t.replace(/((?!.)\s)+/g,"\n").replace(i,(function(t,n,i){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&&(a=n);break;case"typescript":case"ts":case"javascript":case"js":if(!d(e.JAVASCRIPT_PROJECT_NAME))return;break;case"template":r=i;break;case"jres":s=i;break;case"assetjson":o=i;break;case"customts":l=i,i="";break;case"tutorialValidationRules":c=i}return u.push("python"==n?`\n${i}\n`:`{\n${i}\n}`),""})),n=n||e.BLOCKS_PROJECT_NAME,{code:u,templateCode:r,editor:n,language:a,jres:s,assetJson:o,customTs:l,tutorialValidationRulesStr:c};function d(t){return n&&n!=t?(e.debug("tutorial ambiguous: contains snippets of different types"),!1):(n=t,!0)}}(l);let w;s.tutorialCodeValidation&&(w=e.Util.jsonTryParse(v),function(t,n){const i=Object.keys(t);for(let s=0;s<i.length;s++){const r={ruleName:i[s],enabled:t[i[s]]?"true":"false",tutorial:n};e.tickEvent("tutorial.validation.setValidationRules",r)}}(w,d)),(!0===s.diffs||!1!==s.diffs&&!0!==s.noDiffs&&(f==e.BLOCKS_PROJECT_NAME&&e.appTarget.appTheme.tutorialBlocksDiff||f!=e.BLOCKS_PROJECT_NAME&&e.appTarget.appTheme.tutorialTextDiff))&&function(e,t){let n;function i(e){const t={typescript:"diff",spy:"diffspy",blocks:"diffblocks",python:"diff"},i=/\s*(\/\/|#)\s*@highlight/gm;return e?e.replace(/```(typescript|spy|python|blocks|ghost|template)((?:.|[\r\n])+)```/,(function(e,s,r){const a=n,o=/^(template|ghost)$/.test(s),l=i.test(r);return r=r.replace(/^\n+/,"").replace(/\n+$/,""),l&&(r=r.replace(i,"")),n=r,!a||l||o?e:`\`\`\`${t[s]}\n${a}\n----------\n${r}\n\`\`\``})):e}e.forEach(((e,s)=>{if((e.resetDiff||t&&t.find((e=>e.step==s)))&&(n=void 0),e.hintContentMd){const t=i(e.hintContentMd);if(t&&t!=e.hintContentMd)return void(e.hintContentMd=t)}if(e.headerContentMd){const t=i(e.headerContentMd);if(t&&t!=e.headerContentMd)return void(e.headerContentMd=t)}}))}(c,u);const k=o(b);return c.forEach((e=>{e.contentMd=a(e.contentMd),e.headerContentMd=a(e.headerContentMd),e.hintContentMd=a(e.hintContentMd),e.requiredBlockMd=a(e.requiredBlockMd)})),{editor:f,title:d,steps:c,activities:u,code:h,templateCode:p,metadata:s,language:g,jres:m,assetFiles:k,customTs:y,tutorialValidationRules:w}},t.getMetadataRegex=s,t.highlight=function(e){let t=e.textContent;if(t=t.replace(/img\s*\(\s*"{3}[\s\da-f.#tngrpoyw]*"{3}\s*\)/g,'img(""" """)'),t=t.replace(/img\s*`[\s\da-f.#tngrpoyw]*`\s*/g,"img` `"),!/@highlight/.test(t))return void(e.textContent=t);e.textContent="";const n=t.split("\n");for(let t=0;t<n.length;++t){t>0&&t<n.length&&e.appendChild(document.createTextNode("\n"));let i=n[t];if(/@highlight/.test(i)){if(i=n[++t],void 0!==i){const t=document.createElement("span");t.className="highlight-line",t.textContent=i,e.appendChild(t)}}else e.appendChild(document.createTextNode(i))}},t.getTutorialOptions=function(t,n,i,s,r){var a;const o=e.tutorial.parseTutorial(t);if(!o)throw new Error(lf("Invalid tutorial format"));return{options:{tutorial:n,tutorialName:o.title||i,tutorialReportId:s,tutorialStep:0,tutorialReady:!0,tutorialHintCounter:0,tutorialStepInfo:o.steps,tutorialActivityInfo:o.activities,tutorialMd:t,tutorialCode:o.code,tutorialRecipe:!!r,templateCode:o.templateCode,autoexpandStep:!(null===(a=o.metadata)||void 0===a?void 0:a.autoexpandOff),metadata:o.metadata,language:o.language,jres:o.jres,assetFiles:o.assetFiles,customTs:o.customTs,tutorialValidationRules:o.tutorialValidationRules},editor:o.editor}},t.parseCachedTutorialInfo=function(t,n){let i=e.Util.jsonTryParse(t);return i?e.BrowserUtils.tutorialInfoDbAsync().then((e=>{if(n&&i[n]){const t=i[n];t.usedBlocks&&t.hash&&e.setWithHashAsync(n,t.snippetBlocks,t.hash)}else for(let t of Object.keys(i)){const n=i[t];n.usedBlocks&&n.hash&&e.setWithHashAsync(t,n.snippetBlocks,n.hash)}})).catch((e=>{})):Promise.resolve()},t.resolveLocalizedMarkdown=function(t,n,i){const s=(i||t.fileName||"README")+".md";let r;const[a,o,l]=e.Util.normalizeLanguageCode(e.Util.userLanguage());return r=a&&o&&l?n[`_locales/${a}/${s}`]||n[`_locales/${l}/${s}`]||n[`_locales/${o}/${s}`]:n[`_locales/${a}/${s}`],r=r||n[s],r},t.parseAssetJson=o}(e.tutorial||(e.tutorial={}))}(pxt||(pxt={})),function(e){!function(t){function n(t,n){const{tutorialStep:i}=t,s=t.tutorialStepInfo[i].requiredBlockMd,r=e.BrowserUtils.getTutorialCodeHash([s]);let a={};return null!=n&&(a=n[r]),a}function i(e,t,n){n.isStrict=!0;const i=Object.keys(e);let s=[],r=[];null!=t&&(s=Object.keys(t));let a=i.length>=s.length;const o=lf("These are the blocks you seem to be missing:");for(let n=0;n<s.length;n++){let i=s[n];(!e[i]||e[i]<t[i])&&(r.push(i),a=!1)}return n.ruleMessage=o,n.ruleStatus=a,n.blockIds=r,n}function s(e,t,n){const i=Object.keys(e),s=Object.keys(null!=t?t:{});let r=i.length>=s.length;for(let t=0;t<s.length;t++){if(!e[s[t]]){r=!1;break}}return n.ruleStatus=r,n}function r(e,t,n){n.isStrict=!0;Object.keys(e);let i=[],s=[];null!=t&&(i=Object.keys(t));let r=!0;const a=lf("You are required to have the following block:");for(let t=0;t<i.length;t++){let n=i[t];e[n]||(s.push(n),r=!1)}return n.ruleMessage=a,n.ruleStatus=r,n.blockIds=s,n}t.validate=async function(t,a,o){let l=function(e){let t=[];if(null!=e){const n=Object.keys(e);for(let i=0;i<n.length;i++){const s=n[i],r={ruleName:s,ruleTurnOn:e[s]};t.push(r)}}return t}(t.tutorialValidationRules);if(l.length>0&&a.length>0){const o=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}(a.map((e=>e.type))),{tutorialStepInfo:c,tutorialStep:u}=t,d=(c[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)),h=function(t,n){const{tutorialStepInfo:i,tutorialStep:s}=t,r=t.tutorialStepInfo[s].hintContentMd;let a="";null!=r&&r.replace(/((?!.)\s)+/g,"\n").replace(/``` *(block|blocks)\s*\n([\s\S]*?)\n```/gim,(function(e,t,n){return a=`{\n${n}\n}`,""}));const o=e.BrowserUtils.getTutorialCodeHash([a]);let l={};null!=n&&(l=n[o]);return l}(t,d);for(let e=0;e<l.length;e++){let a=l[e];const c=l[e].ruleName;if(l[e].ruleTurnOn)switch(c){case"exact":a=i(o,h,a);break;case"atleast":a=s(o,h,a);break;case"required":a=r(o,n(t,d),a)}}}return l}}(e.tutorial||(e.tutorial={}))}(pxt||(pxt={})),function(e){!function(t){let n;t.flattenDiagnosticMessageText=function(e,t){if("string"==typeof e)return e;{let n=e,i="",s=0;for(;n;){if(s){i+=t;for(let e=0;e<s;e++)i+=" "}i+=n.messageText,s++,n=n.next}return i}},function(e){e[e.ES3=0]="ES3",e[e.ES5=1]="ES5",e[e.ES6=2]="ES6",e[e.ES2015=2]="ES2015",e[e.Latest=2]="Latest"}(n=t.ScriptTarget||(t.ScriptTarget={})),t.isIdentifierStart=function(e,t){return e>=65&&e<=90||e>=97&&e<=122||36===e||95===e||e>127&&o(e,t)},t.isIdentifierPart=function(e,t){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||36===e||95===e||e>127&&function(e,t){return t>=n.ES5?l(e,s):l(e,a)}(e,t)},t.reservedWords=["abstract","any","as","break","case","catch","class","continue","const","constructor","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","is","let","module","namespace","new","null","package","private","protected","public","require","global","return","set","static","super","switch","symbol","this","throw","true","try","type","typeof","var","void","while","with","yield","async","await","of","Math"],t.keywordTypes=["boolean","number","string"],t.escapeIdentifier=function(n){if(!n)return"_";let i=n.replace(/\s+/g,"_").replace(/[^a-zA-Z0-9_$]/g,(t=>e.pxtc.isIdentifierPart(t.charCodeAt(0),e.pxtc.ScriptTarget.ES5)?t:""));return i&&e.pxtc.isIdentifierStart(i.charCodeAt(0),e.pxtc.ScriptTarget.ES5)&&-1===t.reservedWords.indexOf(i)||(i="_"+i),i};const i=[170,170,181,181,186,186,192,214,216,246,248,705,710,721,736,740,748,748,750,750,880,884,886,887,890,893,902,902,904,906,908,908,910,929,931,1013,1015,1153,1162,1319,1329,1366,1369,1369,1377,1415,1488,1514,1520,1522,1568,1610,1646,1647,1649,1747,1749,1749,1765,1766,1774,1775,1786,1788,1791,1791,1808,1808,1810,1839,1869,1957,1969,1969,1994,2026,2036,2037,2042,2042,2048,2069,2074,2074,2084,2084,2088,2088,2112,2136,2208,2208,2210,2220,2308,2361,2365,2365,2384,2384,2392,2401,2417,2423,2425,2431,2437,2444,2447,2448,2451,2472,2474,2480,2482,2482,2486,2489,2493,2493,2510,2510,2524,2525,2527,2529,2544,2545,2565,2570,2575,2576,2579,2600,2602,2608,2610,2611,2613,2614,2616,2617,2649,2652,2654,2654,2674,2676,2693,2701,2703,2705,2707,2728,2730,2736,2738,2739,2741,2745,2749,2749,2768,2768,2784,2785,2821,2828,2831,2832,2835,2856,2858,2864,2866,2867,2869,2873,2877,2877,2908,2909,2911,2913,2929,2929,2947,2947,2949,2954,2958,2960,2962,2965,2969,2970,2972,2972,2974,2975,2979,2980,2984,2986,2990,3001,3024,3024,3077,3084,3086,3088,3090,3112,3114,3123,3125,3129,3133,3133,3160,3161,3168,3169,3205,3212,3214,3216,3218,3240,3242,3251,3253,3257,3261,3261,3294,3294,3296,3297,3313,3314,3333,3340,3342,3344,3346,3386,3389,3389,3406,3406,3424,3425,3450,3455,3461,3478,3482,3505,3507,3515,3517,3517,3520,3526,3585,3632,3634,3635,3648,3654,3713,3714,3716,3716,3719,3720,3722,3722,3725,3725,3732,3735,3737,3743,3745,3747,3749,3749,3751,3751,3754,3755,3757,3760,3762,3763,3773,3773,3776,3780,3782,3782,3804,3807,3840,3840,3904,3911,3913,3948,3976,3980,4096,4138,4159,4159,4176,4181,4186,4189,4193,4193,4197,4198,4206,4208,4213,4225,4238,4238,4256,4293,4295,4295,4301,4301,4304,4346,4348,4680,4682,4685,4688,4694,4696,4696,4698,4701,4704,4744,4746,4749,4752,4784,4786,4789,4792,4798,4800,4800,4802,4805,4808,4822,4824,4880,4882,4885,4888,4954,4992,5007,5024,5108,5121,5740,5743,5759,5761,5786,5792,5866,5870,5872,5888,5900,5902,5905,5920,5937,5952,5969,5984,5996,5998,6e3,6016,6067,6103,6103,6108,6108,6176,6263,6272,6312,6314,6314,6320,6389,6400,6428,6480,6509,6512,6516,6528,6571,6593,6599,6656,6678,6688,6740,6823,6823,6917,6963,6981,6987,7043,7072,7086,7087,7098,7141,7168,7203,7245,7247,7258,7293,7401,7404,7406,7409,7413,7414,7424,7615,7680,7957,7960,7965,7968,8005,8008,8013,8016,8023,8025,8025,8027,8027,8029,8029,8031,8061,8064,8116,8118,8124,8126,8126,8130,8132,8134,8140,8144,8147,8150,8155,8160,8172,8178,8180,8182,8188,8305,8305,8319,8319,8336,8348,8450,8450,8455,8455,8458,8467,8469,8469,8473,8477,8484,8484,8486,8486,8488,8488,8490,8493,8495,8505,8508,8511,8517,8521,8526,8526,8544,8584,11264,11310,11312,11358,11360,11492,11499,11502,11506,11507,11520,11557,11559,11559,11565,11565,11568,11623,11631,11631,11648,11670,11680,11686,11688,11694,11696,11702,11704,11710,11712,11718,11720,11726,11728,11734,11736,11742,11823,11823,12293,12295,12321,12329,12337,12341,12344,12348,12353,12438,12445,12447,12449,12538,12540,12543,12549,12589,12593,12686,12704,12730,12784,12799,13312,19893,19968,40908,40960,42124,42192,42237,42240,42508,42512,42527,42538,42539,42560,42606,42623,42647,42656,42735,42775,42783,42786,42888,42891,42894,42896,42899,42912,42922,43e3,43009,43011,43013,43015,43018,43020,43042,43072,43123,43138,43187,43250,43255,43259,43259,43274,43301,43312,43334,43360,43388,43396,43442,43471,43471,43520,43560,43584,43586,43588,43595,43616,43638,43642,43642,43648,43695,43697,43697,43701,43702,43705,43709,43712,43712,43714,43714,43739,43741,43744,43754,43762,43764,43777,43782,43785,43790,43793,43798,43808,43814,43816,43822,43968,44002,44032,55203,55216,55238,55243,55291,63744,64109,64112,64217,64256,64262,64275,64279,64285,64285,64287,64296,64298,64310,64312,64316,64318,64318,64320,64321,64323,64324,64326,64433,64467,64829,64848,64911,64914,64967,65008,65019,65136,65140,65142,65276,65313,65338,65345,65370,65382,65470,65474,65479,65482,65487,65490,65495,65498,65500],s=[170,170,181,181,186,186,192,214,216,246,248,705,710,721,736,740,748,748,750,750,768,884,886,887,890,893,902,902,904,906,908,908,910,929,931,1013,1015,1153,1155,1159,1162,1319,1329,1366,1369,1369,1377,1415,1425,1469,1471,1471,1473,1474,1476,1477,1479,1479,1488,1514,1520,1522,1552,1562,1568,1641,1646,1747,1749,1756,1759,1768,1770,1788,1791,1791,1808,1866,1869,1969,1984,2037,2042,2042,2048,2093,2112,2139,2208,2208,2210,2220,2276,2302,2304,2403,2406,2415,2417,2423,2425,2431,2433,2435,2437,2444,2447,2448,2451,2472,2474,2480,2482,2482,2486,2489,2492,2500,2503,2504,2507,2510,2519,2519,2524,2525,2527,2531,2534,2545,2561,2563,2565,2570,2575,2576,2579,2600,2602,2608,2610,2611,2613,2614,2616,2617,2620,2620,2622,2626,2631,2632,2635,2637,2641,2641,2649,2652,2654,2654,2662,2677,2689,2691,2693,2701,2703,2705,2707,2728,2730,2736,2738,2739,2741,2745,2748,2757,2759,2761,2763,2765,2768,2768,2784,2787,2790,2799,2817,2819,2821,2828,2831,2832,2835,2856,2858,2864,2866,2867,2869,2873,2876,2884,2887,2888,2891,2893,2902,2903,2908,2909,2911,2915,2918,2927,2929,2929,2946,2947,2949,2954,2958,2960,2962,2965,2969,2970,2972,2972,2974,2975,2979,2980,2984,2986,2990,3001,3006,3010,3014,3016,3018,3021,3024,3024,3031,3031,3046,3055,3073,3075,3077,3084,3086,3088,3090,3112,3114,3123,3125,3129,3133,3140,3142,3144,3146,3149,3157,3158,3160,3161,3168,3171,3174,3183,3202,3203,3205,3212,3214,3216,3218,3240,3242,3251,3253,3257,3260,3268,3270,3272,3274,3277,3285,3286,3294,3294,3296,3299,3302,3311,3313,3314,3330,3331,3333,3340,3342,3344,3346,3386,3389,3396,3398,3400,3402,3406,3415,3415,3424,3427,3430,3439,3450,3455,3458,3459,3461,3478,3482,3505,3507,3515,3517,3517,3520,3526,3530,3530,3535,3540,3542,3542,3544,3551,3570,3571,3585,3642,3648,3662,3664,3673,3713,3714,3716,3716,3719,3720,3722,3722,3725,3725,3732,3735,3737,3743,3745,3747,3749,3749,3751,3751,3754,3755,3757,3769,3771,3773,3776,3780,3782,3782,3784,3789,3792,3801,3804,3807,3840,3840,3864,3865,3872,3881,3893,3893,3895,3895,3897,3897,3902,3911,3913,3948,3953,3972,3974,3991,3993,4028,4038,4038,4096,4169,4176,4253,4256,4293,4295,4295,4301,4301,4304,4346,4348,4680,4682,4685,4688,4694,4696,4696,4698,4701,4704,4744,4746,4749,4752,4784,4786,4789,4792,4798,4800,4800,4802,4805,4808,4822,4824,4880,4882,4885,4888,4954,4957,4959,4992,5007,5024,5108,5121,5740,5743,5759,5761,5786,5792,5866,5870,5872,5888,5900,5902,5908,5920,5940,5952,5971,5984,5996,5998,6e3,6002,6003,6016,6099,6103,6103,6108,6109,6112,6121,6155,6157,6160,6169,6176,6263,6272,6314,6320,6389,6400,6428,6432,6443,6448,6459,6470,6509,6512,6516,6528,6571,6576,6601,6608,6617,6656,6683,6688,6750,6752,6780,6783,6793,6800,6809,6823,6823,6912,6987,6992,7001,7019,7027,7040,7155,7168,7223,7232,7241,7245,7293,7376,7378,7380,7414,7424,7654,7676,7957,7960,7965,7968,8005,8008,8013,8016,8023,8025,8025,8027,8027,8029,8029,8031,8061,8064,8116,8118,8124,8126,8126,8130,8132,8134,8140,8144,8147,8150,8155,8160,8172,8178,8180,8182,8188,8204,8205,8255,8256,8276,8276,8305,8305,8319,8319,8336,8348,8400,8412,8417,8417,8421,8432,8450,8450,8455,8455,8458,8467,8469,8469,8473,8477,8484,8484,8486,8486,8488,8488,8490,8493,8495,8505,8508,8511,8517,8521,8526,8526,8544,8584,11264,11310,11312,11358,11360,11492,11499,11507,11520,11557,11559,11559,11565,11565,11568,11623,11631,11631,11647,11670,11680,11686,11688,11694,11696,11702,11704,11710,11712,11718,11720,11726,11728,11734,11736,11742,11744,11775,11823,11823,12293,12295,12321,12335,12337,12341,12344,12348,12353,12438,12441,12442,12445,12447,12449,12538,12540,12543,12549,12589,12593,12686,12704,12730,12784,12799,13312,19893,19968,40908,40960,42124,42192,42237,42240,42508,42512,42539,42560,42607,42612,42621,42623,42647,42655,42737,42775,42783,42786,42888,42891,42894,42896,42899,42912,42922,43e3,43047,43072,43123,43136,43204,43216,43225,43232,43255,43259,43259,43264,43309,43312,43347,43360,43388,43392,43456,43471,43481,43520,43574,43584,43597,43600,43609,43616,43638,43642,43643,43648,43714,43739,43741,43744,43759,43762,43766,43777,43782,43785,43790,43793,43798,43808,43814,43816,43822,43968,44010,44012,44013,44016,44025,44032,55203,55216,55238,55243,55291,63744,64109,64112,64217,64256,64262,64275,64279,64285,64296,64298,64310,64312,64316,64318,64318,64320,64321,64323,64324,64326,64433,64467,64829,64848,64911,64914,64967,65008,65019,65024,65039,65056,65062,65075,65076,65101,65103,65136,65140,65142,65276,65296,65305,65313,65338,65343,65343,65345,65370,65382,65470,65474,65479,65482,65487,65490,65495,65498,65500],r=[170,170,181,181,186,186,192,214,216,246,248,543,546,563,592,685,688,696,699,705,720,721,736,740,750,750,890,890,902,902,904,906,908,908,910,929,931,974,976,983,986,1011,1024,1153,1164,1220,1223,1224,1227,1228,1232,1269,1272,1273,1329,1366,1369,1369,1377,1415,1488,1514,1520,1522,1569,1594,1600,1610,1649,1747,1749,1749,1765,1766,1786,1788,1808,1808,1810,1836,1920,1957,2309,2361,2365,2365,2384,2384,2392,2401,2437,2444,2447,2448,2451,2472,2474,2480,2482,2482,2486,2489,2524,2525,2527,2529,2544,2545,2565,2570,2575,2576,2579,2600,2602,2608,2610,2611,2613,2614,2616,2617,2649,2652,2654,2654,2674,2676,2693,2699,2701,2701,2703,2705,2707,2728,2730,2736,2738,2739,2741,2745,2749,2749,2768,2768,2784,2784,2821,2828,2831,2832,2835,2856,2858,2864,2866,2867,2870,2873,2877,2877,2908,2909,2911,2913,2949,2954,2958,2960,2962,2965,2969,2970,2972,2972,2974,2975,2979,2980,2984,2986,2990,2997,2999,3001,3077,3084,3086,3088,3090,3112,3114,3123,3125,3129,3168,3169,3205,3212,3214,3216,3218,3240,3242,3251,3253,3257,3294,3294,3296,3297,3333,3340,3342,3344,3346,3368,3370,3385,3424,3425,3461,3478,3482,3505,3507,3515,3517,3517,3520,3526,3585,3632,3634,3635,3648,3654,3713,3714,3716,3716,3719,3720,3722,3722,3725,3725,3732,3735,3737,3743,3745,3747,3749,3749,3751,3751,3754,3755,3757,3760,3762,3763,3773,3773,3776,3780,3782,3782,3804,3805,3840,3840,3904,3911,3913,3946,3976,3979,4096,4129,4131,4135,4137,4138,4176,4181,4256,4293,4304,4342,4352,4441,4447,4514,4520,4601,4608,4614,4616,4678,4680,4680,4682,4685,4688,4694,4696,4696,4698,4701,4704,4742,4744,4744,4746,4749,4752,4782,4784,4784,4786,4789,4792,4798,4800,4800,4802,4805,4808,4814,4816,4822,4824,4846,4848,4878,4880,4880,4882,4885,4888,4894,4896,4934,4936,4954,5024,5108,5121,5740,5743,5750,5761,5786,5792,5866,6016,6067,6176,6263,6272,6312,7680,7835,7840,7929,7936,7957,7960,7965,7968,8005,8008,8013,8016,8023,8025,8025,8027,8027,8029,8029,8031,8061,8064,8116,8118,8124,8126,8126,8130,8132,8134,8140,8144,8147,8150,8155,8160,8172,8178,8180,8182,8188,8319,8319,8450,8450,8455,8455,8458,8467,8469,8469,8473,8477,8484,8484,8486,8486,8488,8488,8490,8493,8495,8497,8499,8505,8544,8579,12293,12295,12321,12329,12337,12341,12344,12346,12353,12436,12445,12446,12449,12538,12540,12542,12549,12588,12593,12686,12704,12727,13312,19893,19968,40869,40960,42124,44032,55203,63744,64045,64256,64262,64275,64279,64285,64285,64287,64296,64298,64310,64312,64316,64318,64318,64320,64321,64323,64324,64326,64433,64467,64829,64848,64911,64914,64967,65008,65019,65136,65138,65140,65140,65142,65276,65313,65338,65345,65370,65382,65470,65474,65479,65482,65487,65490,65495,65498,65500],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,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 o(e,t){return t>=n.ES5?l(e,i):l(e,r)}function l(e,t){if(e<t[0])return!1;let n,i=0,s=t.length;for(;i+1<s;){if(n=i+(s-i)/2,n-=n%2,t[n]<=e&&e<=t[n+1])return!0;e<t[n]?s=n:i=n+2}return!1}let c;t.isUnicodeIdentifierStart=o,function(e){e[e.Warning=0]="Warning",e[e.Error=1]="Error",e[e.Message=2]="Message"}(c=t.DiagnosticCategory||(t.DiagnosticCategory={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){function n(){return!!navigator&&!!navigator.bluetooth&&"TextDecoder"in window&&e.appTarget.appTheme.bluetoothUartConsole&&e.appTarget.appTheme.bluetoothUartFilters&&e.appTarget.appTheme.bluetoothUartFilters.length>0}function i(){return!!navigator&&!!navigator.bluetooth&&!!e.appTarget.appTheme.bluetoothPartialFlashing}t.isAvailable=function(){return n()||i()},t.hasConsole=n,t.hasPartialFlash=i,t.isValidUUID=function(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(e)};class s{constructor(e,t){this.connectionTimeout=2e4,this.connectPromise=void 0,this.id=e,this.aliveToken=t}debug(t){e.debug(`${this.id}: ${t}`)}alivePromise(e){return new Promise(((t,n)=>{this.aliveToken.isCancelled()&&n(new Error),e.then((e=>t(e)),(e=>n(e)))}))}cancelConnect(){this.connectPromise=void 0}createConnectPromise(){return Promise.resolve()}connectAsync(){return this.connectPromise||(this.connectPromise=this.alivePromise(this.createConnectPromise())),e.Util.promiseTimeout(this.connectionTimeout,this.connectPromise,"connection timeout").then((()=>this.aliveToken.throwIfCancelled())).catch((e=>{throw this.connectPromise=void 0,e}))}disconnect(){this.cancelConnect()}kill(){this.disconnect(),this.aliveToken.cancel()}}t.BLERemote=s;class r extends s{constructor(e,t,n){super(e,t.aliveToken),this.device=t,this.autoReconnect=n,this.autoReconnectDelay=1e3,this.disconnectOnAutoReconnect=!1,this.reconnectPromise=void 0,this.failedConnectionServicesVersion=-1,this.handleDisconnected=this.handleDisconnected.bind(this),this.device.device.addEventListener("gattserverdisconnected",this.handleDisconnected)}handleDisconnected(t){this.aliveToken.isCancelled()||(this.disconnect(),this.autoReconnect&&!this.reconnectPromise&&(this.reconnectPromise=e.U.delay(this.autoReconnectDelay).then((()=>this.exponentialBackoffConnectAsync(8,500))).finally((()=>this.reconnectPromise=void 0))))}exponentialBackoffConnectAsync(t,n){return this.debug("retry connect"),this.aliveToken.throwIfCancelled(),this.connectAsync().then((()=>{this.aliveToken.throwIfCancelled(),this.debug("reconnect success"),this.reconnectPromise=void 0})).catch((i=>(this.debug(`reconnect error ${i.message}`),this.aliveToken.throwIfCancelled(),this.device.isPaired?this.autoReconnect?0==t?(this.debug("give up, max tries"),void(this.reconnectPromise=void 0)):this.failedConnectionServicesVersion==this.device.servicesVersion?(this.debug("services haven't changed, giving up"),void(this.reconnectPromise=void 0)):(this.debug(`retry connect ${n}ms... (${t} tries left)`),this.device.connected&&(this.failedConnectionServicesVersion=this.device.servicesVersion),this.disconnectOnAutoReconnect&&this.device.disconnect(),e.U.delay(n).then((()=>this.exponentialBackoffConnectAsync(--t,1.8*n)))):(this.debug("autoreconnect disabled"),void(this.reconnectPromise=void 0)):(this.debug("give up, device unpaired"),void(this.reconnectPromise=void 0)))))}}t.BLEService=r;class a extends r{constructor(e,t,n,i){super(e,t,!0),this.device=t,this.serviceUUID=n,this.txCharacteristicUUID=i,this.handleValueChanged=this.handleValueChanged.bind(this)}createConnectPromise(){return this.debug("connecting"),this.device.connectAsync().then((()=>this.alivePromise(this.device.gatt.getPrimaryService(this.serviceUUID)))).then((e=>(this.debug("service connected"),this.service=e,this.alivePromise(this.service.getCharacteristic(this.txCharacteristicUUID))))).then((e=>(this.debug("tx characteristic connected"),this.txCharacteristic=e,this.txCharacteristic.addEventListener("characteristicvaluechanged",this.handleValueChanged),this.txCharacteristic.startNotifications()))).then((()=>{e.tickEvent("webble.connected",{id:this.id})}))}handlePacket(e){}handleValueChanged(e){const t=e.target.value;this.handlePacket(t)}disconnect(){if(super.disconnect(),this.txCharacteristic&&this.device&&this.device.connected)try{this.txCharacteristic.stopNotifications(),this.txCharacteristic.removeEventListener("characteristicvaluechanged",this.handleValueChanged)}catch(t){e.log(`${this.id}: error ${t.message}`)}this.service=void 0,this.txCharacteristic=void 0}}t.BLETXService=a;class o extends a{constructor(e){super("hf2",e,o.SERVICE_UUID,o.CHARACTERISTIC_TX_UUID),this.device=e}handlePacket(e){const t=e.getUint8(0);switch(192&t){case o.BLEHF2_FLAG_SERIAL_OUT:case o.BLEHF2_FLAG_SERIAL_ERR:const n=Math.min(e.byteLength-1,-193&t);let i="";for(let t=0;t<n;++t)i+=String.fromCharCode(e.getUint8(t+1));i&&window.postMessage({type:"serial",id:this.device.name||"hf2",data:i},"*")}}}o.SERVICE_UUID="b112f5e6-2679-30da-a26e-0273b6043849",o.CHARACTERISTIC_TX_UUID="b112f5e6-2679-30da-a26e-0273b604384a",o.BLEHF2_FLAG_SERIAL_OUT=128,o.BLEHF2_FLAG_SERIAL_ERR=192,t.HF2Service=o;class l extends a{constructor(e){super("uart",e,l.SERVICE_UUID,l.CHARACTERISTIC_TX_UUID),this.device=e}handlePacket(e){const t=(new window.TextDecoder).decode(e);t&&window.postMessage({type:"serial",id:this.device.name||"uart",data:t},"*")}}let c;l.SERVICE_UUID="6e400001-b5a3-f393-e0a9-e50e24dcca9e",l.CHARACTERISTIC_TX_UUID="6e400002-b5a3-f393-e0a9-e50e24dcca9e",t.UARTService=l,function(e){e[e.Idle=1]="Idle",e[e.StatusRequested=2]="StatusRequested",e[e.PairingModeRequested=4]="PairingModeRequested",e[e.RegionDALRequested=8]="RegionDALRequested",e[e.RegionMakeCodeRequested=16]="RegionMakeCodeRequested",e[e.Flash=32]="Flash",e[e.EndOfTransmision=64]="EndOfTransmision",e[e.USBFlashRequired=128]="USBFlashRequired"}(c||(c={}));class u extends r{constructor(e){super("partial flashing",e,!1),this.device=e,this.state=c.Idle,this.disconnectOnAutoReconnect=!0,this.handleCharacteristic=this.handleCharacteristic.bind(this)}clearFlashData(){this.version=0,this.mode=0,this.regions=[],this.chunkDelay=u.CHUNK_MIN_DELAY,this.hex=void 0,this.bin=void 0,this.magicOffset=void 0,this.dalHash=void 0,this.makeCodeHash=void 0,this.flashReject=void 0,this.flashResolve=void 0,this.flashOffset=void 0}createConnectPromise(){return this.debug("connecting to partial flash service"),this.device.connectAsync().then((()=>this.alivePromise(this.device.gatt.getPrimaryService(u.SERVICE_UUID)))).then((e=>(this.debug("connecting to characteristic"),this.alivePromise(e.getCharacteristic(u.CHARACTERISTIC_UUID))))).then((e=>(this.debug("starting notifications"),this.pfCharacteristic=e,this.pfCharacteristic.startNotifications(),this.pfCharacteristic.addEventListener("characteristicvaluechanged",this.handleCharacteristic),this.state==c.PairingModeRequested?(this.debug("checking pairing mode"),this.autoReconnect=!1,this.pfCharacteristic.writeValue(new Uint8Array([u.STATUS]))):Promise.resolve())))}disconnect(){if(super.disconnect(),this.flashPacketToken&&this.flashPacketToken.cancel(),this.pfCharacteristic&&this.device.connected)try{this.pfCharacteristic.stopNotifications(),this.pfCharacteristic.removeEventListener("characteristicvaluechanged",this.handleCharacteristic)}catch(t){e.log(`ble: partial flash disconnect error ${t.message}`)}this.pfCharacteristic=void 0}findMarker(e,t){if(!this.bin)return-1;for(;e+t.length<this.bin.length;e+=16){let n=!0;for(let i=0;i<t.length;++i)if(t[i]!=this.bin[e+i]){n=!1;break}if(n)return e}return-1}flashAsync(e){return this.hex?(this.debug("flashing already in progress"),Promise.resolve()):(this.device.pauseLog(),this.createFlashPromise(e).finally((()=>this.device.resumeLogOnDisconnection())))}createFlashPromise(t){if(this.hex)return this.debug("flashing already in progress"),Promise.resolve();this.clearFlashData(),this.hex=t;const n=ts.pxtc.UF2.newBlockFile();ts.pxtc.UF2.writeHex(n,this.hex.split(/\r?\n/));const i=e.appTarget.compile.flashUsableEnd;this.bin=ts.pxtc.UF2.toBin(e.U.stringToUint8Array(ts.pxtc.UF2.serializeFile(n)),i).buf,this.debug(`bin bytes ${this.bin.length}`),this.magicOffset=this.findMarker(0,u.MAGIC_MARKER),this.debug(`magic block ${this.magicOffset.toString(16)}`),this.magicOffset<0&&(this.debug("magic block not found, not a valid HEX file"),e.U.userError(lf("Invalid file"))),this.debug("bytes to flash "+(this.bin.length-this.magicOffset));const s=this.magicOffset+u.MAGIC_MARKER.length;return this.dalHash=e.Util.toHex(this.bin.slice(s,s+8)),this.makeCodeHash=e.Util.toHex(this.bin.slice(s+8,s+16)),this.debug(`DAL hash ${this.dalHash}`),this.debug(`MakeCode hash ${this.makeCodeHash}`),this.connectAsync().then((()=>new Promise(((e,t)=>(this.flashResolve=e,this.flashReject=t,this.debug("check service version"),this.state=c.StatusRequested,this.pfCharacteristic.writeValue(new Uint8Array([u.STATUS]))))))).then((()=>{}),(t=>{e.log(`pf: error ${t.message}`),this.clearFlashData()}))}checkStateTransition(e,t){return!!(this.state&t)||(this.debug(`flash cmd ${e} in state ${this.state.toString(16)} `),this.flashReject(new Error),this.clearFlashData(),!1)}handleCharacteristic(t){this.aliveToken.isCancelled()&&(this.flashReject(new Error),this.clearFlashData());const n=event.target.value,i=new Uint8Array(n.buffer),s=i[0];if(this.state!=c.Idle)switch(s){case u.STATUS:if(!this.checkStateTransition(s,c.StatusRequested|c.PairingModeRequested))return;this.version=i[1],this.mode=i[2],this.debug(`flash service version ${this.version} mode ${this.mode}`),this.debug("reading DAL region"),this.state=c.RegionDALRequested,this.pfCharacteristic.writeValue(new Uint8Array([u.REGION_INFO,u.REGION_DAL])).then((()=>{}));break;case u.REGION_INFO:if(!this.checkStateTransition(s,c.RegionDALRequested|c.RegionMakeCodeRequested))return;const t=this.regions[i[1]]={start:i[2]<<24|i[3]<<16|i[4]<<8|i[5],end:i[6]<<24|i[7]<<16|i[8]<<8|i[9],hash:e.Util.toHex(i.slice(10))};if(this.debug(`read region ${i[1]} start ${t.start.toString(16)} end ${t.end.toString(16)} hash ${t.hash}`),i[1]==u.REGION_DAL){if(t.hash!=this.dalHash)return e.tickEvent("webble.flash.DALrequired"),this.debug("DAL hash does not match, partial flashing not possible"),this.state=c.USBFlashRequired,this.flashReject(new Error("USB flashing required")),void this.clearFlashData();this.debug("DAL hash match, reading makecode region"),this.state=c.RegionMakeCodeRequested,this.pfCharacteristic.writeValue(new Uint8Array([u.REGION_INFO,u.REGION_MAKECODE])).then((()=>{}))}else if(i[1]==u.REGION_MAKECODE)if(t.start!=this.magicOffset&&(this.debug("magic offset and MakeCode region.start not matching"),e.U.userError(lf("Invalid file"))),t.hash==this.makeCodeHash)e.tickEvent("webble.flash.noop"),this.debug("MakeCode hash matches, same code!"),this.debug("restart application mode"),this.pfCharacteristic.writeValue(new Uint8Array([u.RESET,u.MODE_APPLICATION])).then((()=>{this.state=c.Idle,this.flashResolve(),this.clearFlashData()}));else{if(this.mode!=u.MODE_PAIRING)return this.debug("application mode, reset into pairing mode"),this.state=c.PairingModeRequested,this.autoReconnect=!0,void this.pfCharacteristic.writeValue(new Uint8Array([u.RESET,u.MODE_PAIRING])).then((()=>{}));this.flashOffset=t.start,this.flashPacketNumber=0,this.debug(`starting to flash from address ${this.flashOffset.toString(16)}`),this.flashNextPacket()}break;case u.FLASH_DATA:if(!this.checkStateTransition(s,c.Flash))return;switch(i[1]){case u.PACKET_OUT_OF_ORDER:this.debug("packet out of order"),this.flashPacketToken.cancel(),this.flashPacketNumber+=4,this.chunkDelay=Math.min(this.chunkDelay+10,u.CHUNK_MAX_DELAY),this.flashNextPacket();break;case u.PACKET_WRITTEN:this.chunkDelay=Math.max(this.chunkDelay-1,u.CHUNK_MIN_DELAY),this.flashOffset+=64,this.flashPacketNumber+=4,this.flashOffset>=this.bin.length?(this.debug("end transmission"),this.state=c.EndOfTransmision,this.pfCharacteristic.writeValue(new Uint8Array([u.END_OF_TRANSMISSION])).finally((()=>{this.flashResolve&&this.flashResolve(),this.clearFlashData()}))):this.flashNextPacket()}break;default:this.debug(`unknown message ${e.Util.toHex(i)}`),this.disconnect()}}flashNextPacket(){this.state=c.Flash,this.flashPacketToken=new e.Util.CancellationToken,this.flashPacketToken.startOperation();const t=this.bin.slice(this.flashOffset,this.flashOffset+64);this.debug(`flashing ${this.flashOffset.toString(16)} / ${this.bin.length.toString(16)} ${(this.flashOffset-this.magicOffset)/(this.bin.length-this.magicOffset)*100>>0}%`);let n=new Uint8Array(20);e.U.delay(this.chunkDelay).then((()=>{this.flashPacketToken.throwIfCancelled(),n[0]=u.FLASH_DATA,n[1]=this.flashOffset>>8&255,n[2]=this.flashOffset>>0&255,n[3]=this.flashPacketNumber;for(let e=0;e<16;e++)n[4+e]=t[e];return this.pfCharacteristic.writeValue(n)})).then((()=>e.U.delay(this.chunkDelay))).then((()=>{this.flashPacketToken.throwIfCancelled(),n[0]=u.FLASH_DATA,n[1]=this.flashOffset>>24&255,n[2]=this.flashOffset>>16&255,n[3]=this.flashPacketNumber+1;for(let e=0;e<16;e++)n[4+e]=t[16+e]||0;return this.pfCharacteristic.writeValue(n)})).then((()=>e.U.delay(this.chunkDelay))).then((()=>{this.flashPacketToken.throwIfCancelled(),n[0]=u.FLASH_DATA,n[1]=0,n[2]=0,n[3]=this.flashPacketNumber+2;for(let e=0;e<16;e++)n[4+e]=t[32+e]||0;return this.pfCharacteristic.writeValue(n)})).then((()=>e.U.delay(this.chunkDelay))).then((()=>{this.flashPacketToken.throwIfCancelled(),n[0]=u.FLASH_DATA,n[1]=0,n[2]=0,n[3]=this.flashPacketNumber+3;for(let e=0;e<16;e++)n[4+e]=t[48+e]||0;return this.pfCharacteristic.writeValue(n)})).then((()=>{const t=this.flashOffset,i=()=>e.U.delay(500).then((()=>{if(t!=this.flashOffset||this.flashPacketToken.isCancelled()||this.aliveToken.isCancelled()||this.state!=c.Flash)return Promise.resolve();this.debug("packet transfer deadlock, force restart"),n[0]=u.FLASH_DATA,n[1]=0,n[2]=0,n[3]=-1;for(let e=0;e<16;e++)n[4+e]=0;return this.pfCharacteristic.writeValue(n).then((()=>i()))}));i().catch((e=>{this.flashReject&&(this.flashReject(new Error("failed packet transfer")),this.clearFlashData())}))})).catch((()=>{this.flashPacketToken.resolveCancel()}))}}u.SERVICE_UUID="e97dd91d-251d-470a-a062-fa1922dfa9a8",u.CHARACTERISTIC_UUID="e97d3b10-251d-470a-a062-fa1922dfa9a8",u.REGION_INFO=0,u.FLASH_DATA=1,u.PACKET_OUT_OF_ORDER=170,u.PACKET_WRITTEN=255,u.END_OF_TRANSMISSION=2,u.STATUS=238,u.RESET=255,u.MODE_PAIRING=0,u.MODE_APPLICATION=1,u.REGION_SOFTDEVICE=0,u.REGION_DAL=1,u.REGION_MAKECODE=2,u.MAGIC_MARKER=e.Util.fromHex("708E3B92C615A841C49866C975EE5197"),u.CHUNK_MIN_DELAY=0,u.CHUNK_MAX_DELAY=75,t.PartialFlashingService=u;class d extends s{constructor(t){super("ble",new e.Util.CancellationToken),this.device=void 0,this.services=[],this.pendingResumeLogOnDisconnection=!1,this.servicesVersion=0,this.device=t,this.handleDisconnected=this.handleDisconnected.bind(this),this.handleServiceAdded=this.handleServiceAdded.bind(this),this.handleServiceChanged=this.handleServiceChanged.bind(this),this.handleServiceRemoved=this.handleServiceRemoved.bind(this),this.device.addEventListener("gattserverdisconnected",this.handleDisconnected),this.device.addEventListener("serviceadded",this.handleServiceAdded),this.device.addEventListener("servicechanged",this.handleServiceChanged),this.device.addEventListener("serviceremoved",this.handleServiceRemoved),n()&&(this.services.push(this.uartService=new l(this)),this.services.push(this.hf2Service=new o(this))),i()&&this.services.push(this.partialFlashingService=new u(this)),this.aliveToken.startOperation()}startServices(){this.services.filter((e=>e.autoReconnect)).forEach((e=>e.connectAsync().catch((()=>{}))))}pauseLog(){this.uartService&&(this.uartService.autoReconnect=!1,this.uartService.disconnect()),this.hf2Service&&(this.hf2Service.autoReconnect=!1,this.hf2Service.disconnect())}resumeLogOnDisconnection(){this.pendingResumeLogOnDisconnection=!0}resumeLog(){this.uartService&&(this.uartService.autoReconnect=!0,this.uartService.connectAsync().catch((()=>{}))),this.hf2Service&&(this.hf2Service.autoReconnect=!0,this.hf2Service.connectAsync().catch((()=>{})))}get isPaired(){return this===t.bleDevice}get name(){return this.device.name||"?"}get connected(){return this.device&&this.device.gatt&&this.device.gatt.connected}get gatt(){return this.device.gatt}createConnectPromise(){return this.debug("connecting gatt server"),this.alivePromise(this.device.gatt.connect().then((()=>this.debug("gatt server connected"))))}handleServiceAdded(e){this.debug("service added"),this.servicesVersion++}handleServiceRemoved(e){this.debug("service removed"),this.servicesVersion++}handleServiceChanged(e){this.debug("service changed"),this.servicesVersion++}handleDisconnected(t){this.debug("disconnected"),this.disconnect(),this.pendingResumeLogOnDisconnection&&(this.pendingResumeLogOnDisconnection=!1,e.U.delay(500).then((()=>this.resumeLog())))}disconnect(){if(super.disconnect(),this.services.forEach((e=>e.disconnect())),this.connected){this.debug("disconnect");try{this.device.gatt&&this.device.gatt.connected&&this.device.gatt.disconnect()}catch(e){this.debug(`gatt disconnect error ${e.message}`)}}}}function h(){if(t.bleDevice)return Promise.resolve();e.log("ble: requesting device");const s=[];return n()&&(s.push(l.SERVICE_UUID),s.push(o.SERVICE_UUID)),i()&&s.push(u.SERVICE_UUID),navigator.bluetooth.requestDevice({filters:e.appTarget.appTheme.bluetoothUartFilters,optionalServices:s}).then((n=>(e.log(`ble: received device ${n.name}`),t.bleDevice=new d(n),t.bleDevice.startServices(),t.bleDevice.connectAsync())))}t.BLEDevice=d,t.bleDevice=void 0,t.isPaired=function(){return!!t.bleDevice},t.pairAsync=function(){return t.bleDevice&&(t.bleDevice.kill(),t.bleDevice=void 0),h().catch((n=>{t.bleDevice&&t.bleDevice.aliveToken&&t.bleDevice.aliveToken.resolveCancel(),e.log(`ble: error ${n.message}`)}))},t.flashAsync=function(n,i){e.tickEvent("webble.flash");const s=n.outfiles[ts.pxtc.BINARY_HEX];return h().then((()=>t.bleDevice.partialFlashingService.flashAsync(s))).then((()=>e.tickEvent("webble.flash.success"))).catch((t=>{throw e.tickEvent("webble.fail.fail",{message:t.message}),t}))}}(e.webBluetooth||(e.webBluetooth={}))}(pxt||(pxt={})),function(e){!function(t){class n extends Error{constructor(e){super(e),this.message=e}}t.USBError=n;t.filters=[{classCode:255,subclassCode:42}];let i,s,r=!0;t.setFilters=function(e){r=!1,t.filters=e};class a{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(o).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 i=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 s=i[i.length-1];return this.log(`${i.length} matching interfaces; picking ${s?"#"+s.interfaceNumber:"n/a"}`),s||this.error("cannot find supported USB interface"),this.altIface=s.alternates[0],this.iface=s,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(s.interfaceNumber)})).then((()=>{this.log("device ready"),this.lastKnownDeviceSerialNumber=this.dev.serialNumber,this.ready=!0,r&&this.readLoop(),this.onConnectionChanged&&this.onConnectionChanged()}))}}async function o(){e.log("webusb: get devices");try{return await navigator.usb.getDevices()||[]}catch(t){return e.reportException(t),[]}}async function l(){var t,n;if(void 0!==s)return;if(e.debug("webusb: checking availability"),!(null===(n=null===(t=e.appTarget)||void 0===t?void 0:t.compile)||void 0===n?void 0:n.webUSB))return void(s=!1);if(e.BrowserUtils.isElectron()||e.BrowserUtils.isWinRT())return e.debug("webusb: off, electron or winrt"),e.tickEvent("webusb.off",{reason:"electronwinrt"}),void(s=!1);const i=navigator.usb;if(!i)return e.debug("webusb: off, not impl"),e.tickEvent("webusb.off",{reason:"notimpl"}),void(s=!1);let r=/Windows NT (\d+\.\d+)/.exec(navigator.userAgent);if(r&&parseFloat(r[1])<6.3)return e.debug("webusb: off, older windows version"),e.tickEvent("webusb.off",{reason:"oldwindows"}),void(s=!1);try{await i.getDevices()}catch(t){return e.debug("webusb: off, security exception"),e.tickEvent("webusb.off",{reason:"security"}),void(s=!1)}s=!0}function c(){return void 0===s&&(console.error("checkAvailableAsync not called"),l()),!!s}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"),i||(i=new a),i.enable(),Promise.resolve(i)},t.isEnabled=!1,t.setEnabled=function(e){c()||(e=!1),t.isEnabled=e},t.checkAvailableAsync=l,t.isAvailable=c}(e.usb||(e.usb={}))}(pxt||(pxt={})),function(e){!function(t){var n=e.Util;let i={};function s(e){let t={},i=0,s=new n.PromiseQueue,r=new Promise(((e,n)=>{t.ready=e}));s.enqueue("main",(()=>r));return{opAsync:function(n,r){return s.enqueue("main",(()=>new Promise(((s,a)=>{let o=""+i++;t[o]=e=>{e?e.errorMessage?a(new Error(e.errorMessage)):s(e):a(new Error("no response"))},e({id:o,op:n,arg:r})}))))},recvHandler:e=>{if(t.hasOwnProperty(e.id)){let n=t[e.id];delete t[e.id],n(e.result)}}}}function r(t){let n=new Worker(t),i=s((e=>n.postMessage(e)));return n.onmessage=t=>{e.perf.measureStart("webworker recvHandler"),i.recvHandler(t.data),e.perf.measureEnd("webworker recvHandler")},i}t.getWorker=function(e){let t=i[e];return t||(t=i[e]=r(e)),t},t.wrap=s,t.makeWebWorker=r,t.makeWebSocket=function(t,n=null){let i=new WebSocket(t),r=[],a=s((e=>{let t=JSON.stringify(e);r?r.push(t):i.send(t)}));return i.onmessage=e=>{let t=JSON.parse(e.data);n&&null==t.id?n(t):a.recvHandler(t)},i.onopen=t=>{e.debug("socket opened");for(let e of r)i.send(e);r=null},i.onclose=t=>{e.debug("socket closed")},i.onerror=t=>{e.debug("socket errored")},a}}(e.worker||(e.worker={}))}(pxt||(pxt={})),function(e){!function(t){function n(){t.apiKey||e.U.userError("YouTube API key missing")}function i(e){if(!e)return"";const t=e.medium||e.high||e.standard||e.default;return(null==t?void 0:t.url)||""}t.apiKey=void 0,t.playlistItemToCodeCard=function(e){return{name:e.snippet.title.replace(/[^-]*-/,"").trim(),description:(t=e.snippet.description,t.split(/\n\s+/,1)[0].trim()),youTubeId:e.snippet.resourceId.videoId,youTubePlaylistId:e.snippet.playlistId,imageUrl:i(e.snippet.thumbnails)};var t},t.playlistInfoAsync=function(i){n();const s=`https://www.googleapis.com/youtube/v3/playlists?part=snippet&id=${i}&key=${t.apiKey}`;return e.Util.httpGetJsonAsync(s).then((e=>e.items[0]))},t.listPlaylistVideosAsync=async function(i){n();let s,r=[];do{let n=`https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=${i}&key=${t.apiKey}`;s&&(n+=`&pageToken=${s}`);const a=await e.Util.httpGetJsonAsync(n);r=r.concat(a.items),s=a.nextPageToken}while(s);return e.options.debug&&e.debug(JSON.stringify(r,null,2)),r},t.watchUrl=function(e,t){let n;return e?(n=`https://www.youtube.com/watch?v=${e}`,t&&(n+=`&list=${t}`)):t&&(n=`https://www.youtube.com/playlist?list=${t}`),n}}(e.youtube||(e.youtube={}))}(pxt||(pxt={})),function(e){!function(e){!function(t){function n(e,...t){return e.replace(/{(\d+)}/g,((e,n)=>t[+n]))}t.debug=!1,t.lf=n;let i=l("opcode name doesn't match","<name>");class s{constructor(t,n,i,s,r){this.opcode=i,this.mask=s,this.is32bit=r,this.canBeShared=!1,e.assert((i&s)==i),this.ei=t,this.code=n.replace(/\s+/g," "),this.friendlyFmt=n.replace(/\$\w+/g,(e=>this.ei.encoders[e]?this.ei.encoders[e].pretty:e));let a=o(n);this.name=a[0],this.args=a.slice(1)}emit(t){let n=t.words;if(n[0]!=this.name)return i;let s=this.opcode,r=1,a=0,o=[],c=null,u=null,d=null;for(let i=0;i<this.args.length;++i){let h=this.args[i],p=n[r++];if("$"==h[0]){let i=this.ei.encoders[h],f=null;if(i.isRegister){if(f=this.ei.registerNo(p),null==f)return l("expecting register name",p);this.ei.isPush(this.opcode)?a++:this.ei.isPop(this.opcode)&&a--}else if(i.isImmediate){if(p=p.replace(/^#/,""),f=t.bin.parseOneInt(p),null==f)return l("expecting number",p);this.ei.isAddSP(this.opcode)?a=-f/this.ei.wordSize():this.ei.isSubSP(this.opcode)&&(a=f/this.ei.wordSize())}else if(i.isRegList){if("{"!=p)return l("expecting {",p);for(f=0;"}"!=n[r];){if(p=n[r++],!p)return l("expecting }",n[r-2]);let e=this.ei.registerNo(p);if(null==e)return l("expecting register name",p);if(f&1<<e)return l("duplicate register name",p);f|=1<<e,this.ei.isPush(this.opcode)?a++:this.ei.isPop(this.opcode)&&a--,","==n[r]&&r++}p=n[r++]}else if(i.isLabel){if(p=p.replace(/^#/,""),/^[+-]?\d+$/.test(p))f=parseInt(p,10),c="rel"+f;else if(/^0x[0-9a-fA-F]+$/.test(p))f=parseInt(p,16),c="abs"+f;else if(c=p,f=this.ei.getAddressFromLabel(t.bin,this,p,i.isWordAligned),null==f){if(t.bin.finalEmit)return l("unknown label",p);f=8}if(this.ei.is32bit(this)){u=f,d=p;continue}}else e.oops();if(null==f)return l("didn't understand it",p);if(o.push(f),f=i.encode(f),null==f)return l("argument out of range or mis-aligned",p);e.assert(0==(s&f)),s|=f}else if(h!=p)return l("expecting "+h,p)}return n[r]?l("trailing tokens",n[r]):this.ei.is32bit(this)?this.ei.emit32(s,u,t.bin.normalizeExternalLabel(d)):{stack:a,opcode:s,numArgs:o,labelName:t.bin.normalizeExternalLabel(c)}}toString(){return this.friendlyFmt}}t.Instruction=s;class r{constructor(e,t){this.bin=e,this.text=t}getOpExt(){return this.instruction?this.instruction.code:""}getOp(){return this.instruction?this.instruction.name:""}update(e){this.bin.peepOps++,(e=e.replace(/^\s*/,""))||this.bin.peepDel++,e&&(e+=" "),e=" "+e,this.text=e+"; WAS: "+this.text.trim(),this.instruction=null,this.numArgs=null,this.words=o(e)||[],0==this.words.length?this.type="empty":"@"==this.words[0][0]&&(this.type="directive")}}t.Line=r;class a{constructor(e){this.baseOffset=0,this.checkStack=!0,this.inlineMode=!1,this.normalizeExternalLabel=e=>e,this.currLineNo=0,this.scope="",this.scopeId=0,this.errors=[],this.labels={},this.equs={},this.stackpointers={},this.stack=0,this.commPtr=0,this.peepOps=0,this.peepDel=0,this.peepCounts={},this.stats="",this.throwOnError=!1,this.disablePeepHole=!1,this.stackAtLabel={},this.currLine=new r(this,"<start>"),this.currLine.lineNo=0,this.ei=e,this.ei.file=this}emitShort(t){e.assert(0<=t&&t<=65535),this.buf.push(t)}emitOpCode(e){this.emitShort(e)}location(){return 2*this.buf.length}pc(){return this.location()+this.baseOffset}parseOneInt(t){if(!t)return null;if(/^\d+$/.test(t))return parseInt(t,10);const i=t.indexOf("-");if(i>0)return this.parseOneInt(t.slice(0,i))-this.parseOneInt(t.slice(i+1));let s=1;if(t.indexOf("*")>=0){let e=null;for(;null!=(e=/^([^\*]*)\*(.*)$/.exec(t));){let n=this.parseOneInt(e[1]);if(null==n)return null;s*=n,t=e[2]}}if("-"==t[0]?(s*=-1,t=t.slice(1)):"+"==t[0]&&(t=t.slice(1)),/^\d+$/.test(t))return s*parseInt(t,10);if(e.U.endsWith(t,"|1"))return 1|this.parseOneInt(t.slice(0,t.length-2));if(e.U.endsWith(t,"-1"))return this.parseOneInt(t.slice(0,t.length-2))-1;if(e.U.endsWith(t,"+1"))return this.parseOneInt(t.slice(0,t.length-2))+1;let r=/(.*)>>(\d+)$/.exec(t);if(r){let e=this.parseOneInt(r[1]);return e&=~(-16777216&this.baseOffset),e>>parseInt(r[2])}let a=null;if("0"==t[0])if("x"==t[1]||"X"==t[1]){let e=/^0x([a-f0-9]+)$/i.exec(t);e&&(a=parseInt(e[1],16))}else if("b"==t[1]||"B"==t[1]){let e=/^0b([01]+)$/i.exec(t);e&&(a=parseInt(e[1],2))}if(t.indexOf("@")>=0){let i=/^(\w+)@(-?\d+)$/.exec(t);i&&(1!=s&&this.directiveError(n("multiplication not supported with saved stacks")),this.stackpointers.hasOwnProperty(i[1])?a=this.ei.wordSize()*this.ei.computeStackOffset(i[1],this.stack-this.stackpointers[i[1]]+parseInt(i[2])):this.directiveError(n("saved stack not found"))),i=/^(.*)@(hi|lo|fn)$/.exec(t),i&&this.looksLikeLabel(i[1])&&(a=this.lookupLabel(i[1],!0),null!=a&&("fn"==i[2]?a=this.ei.toFnPtr(a,this.baseOffset,i[1]):(a>>=1,0<=a&&a<=65535?"hi"==i[2]?a=a>>8&255:"lo"==i[2]?a&=255:e.oops():(this.directiveError(n("@hi/lo out of range")),a=null))))}return null==a&&this.looksLikeLabel(t)&&(a=this.lookupLabel(t,!0),null!=a&&1==this.ei.postProcessRelAddress(this,1)&&(a+=this.baseOffset)),null==a||isNaN(a)?null:a*s}looksLikeLabel(e){return!/^(r\d|pc|sp|lr)$/i.test(e)&&/^[\.a-zA-Z_][\.:\w+]*$/.test(e)}scopedName(e){return"."==e[0]&&this.scope?this.scope+"$"+e:e}lookupLabel(e,t=!1){let i=null,s=this.scopedName(e);return this.labels.hasOwnProperty(s)?(i=this.labels[s],i=this.ei.postProcessRelAddress(this,i)):this.lookupExternalLabel&&(i=this.lookupExternalLabel(e),null!=i&&(i=this.ei.postProcessAbsAddress(this,i))),null==i&&this.equs.hasOwnProperty(s)&&(i=this.equs[s]),null==i&&t&&(this.finalEmit?this.directiveError(n("unknown label: {0}",e)):i=11111),i}align(t){for(e.assert(2==t||4==t||8==t||16==t);this.location()%t!=0;)this.emitOpCode(0)}pushError(e,t=""){let i={scope:this.scope,message:n(" -> Line {2} ('{1}'), error: {0}\n{3}",e,this.currLine.text,this.currLine.lineNo,t),lineNo:this.currLine.lineNo,line:this.currLine.text,coremsg:e,hints:t};if(this.errors.push(i),this.throwOnError)throw new Error(i.message)}directiveError(e){this.pushError(e)}emitString(e,t=!1){function i(e,t){return 255&(e.charCodeAt(t)||0)}let s,r=/^\s*([\w\.]+\s*:\s*)?.\w+\s+(".*")\s*$/.exec(e);if(r&&null!=(s=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}}(r[2])))if(this.align(2),t)for(let e=0;e<s.length;e++)this.emitShort(s.charCodeAt(e));else for(let e=0;e<s.length+1;e+=2)this.emitShort(i(s,e+1)<<8|i(s,e));else this.directiveError(n("expecting string"))}parseNumber(e){let t=this.parseOneInt(e.shift());return null==t?null:t}parseNumbers(e){e=e.slice(1);let t=[];for(;;){let i=this.parseNumber(e);if(null==i){this.directiveError(n("cannot parse number at '{0}'",e[0]));break}if(t.push(i),","!=e[0]){if(null==e[0])break;this.directiveError(n("expecting number, got '{0}'",e[0]));break}if(e.shift(),null==e[0])break}return t}emitSpace(e){let t=this.parseNumbers(e);if(1==t.length&&t.push(0),2!=t.length)this.directiveError(n("expecting one or two numbers"));else if(t[0]%2!=0)this.directiveError(n("only even space supported"));else{let e=255&t[1];e|=e<<8;for(let n=0;n<t[0];n+=2)this.emitShort(e)}}emitBytes(e){let t=this.parseNumbers(e);t.length%2!=0&&(this.directiveError(".bytes needs an even number of arguments"),t.push(0));for(let e=0;e<t.length;e+=2){let i=t[e],s=t[e+1];0<=i&&s<=255&&0<=s&&i<=255?this.emitShort(255&i|(255&s)<<8):this.directiveError(n("expecting uint8"))}}emitHex(e){e.slice(1).forEach((e=>{if(","!=e)if(e.length%4!=0)this.directiveError(".hex needs an even number of bytes");else if(/^[a-f0-9]+$/i.test(e))for(let t=0;t<e.length;t+=4){let n=parseInt(e.slice(t,t+4),16);n=(255&n)<<8|n>>8&255,this.emitShort(n)}else this.directiveError(".hex needs a hex number")}))}handleDirective(e){let t,i=e.words,s=()=>{2!=i.length&&this.directiveError(n("expecting one argument"))};switch(i[0]){case".ascii":case".asciz":case".string":this.emitString(e.text);break;case".utf16":this.emitString(e.text,!0);break;case".align":if(s(),t=this.parseOneInt(i[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(s(),t=this.parseOneInt(i[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":s(),t=this.parseOneInt(i[1]),null!=t?this.align(1<<t):this.directiveError(n("expecting number"));break;case".byte":this.emitBytes(i);break;case".hex":this.emitHex(i);break;case".hword":case".short":case".2bytes":this.parseNumbers(i).forEach((e=>{-32768<=e&&e<=65535?this.emitShort(65535&e):this.directiveError(n("expecting int16"))}));break;case".word":case".4bytes":case".long":this.parseNumbers(i).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(i);break;case".set":case".equ":/^\w+$/.test(i[1])||this.directiveError(n("expecting name"));const r=this.parseNumbers(i.slice(","==i[2]||"="==i[2]?2:1));1!=r.length&&this.directiveError(n("expecting one value")),void 0!==this.equs[i[1]]&&this.equs[i[1]]!=r[0]&&this.directiveError(n("redefinition of {0}",i[1])),this.equs[i[1]]=r[0];break;case".startaddr":this.location()&&this.directiveError(n(".startaddr can be only be specified at the beginning of the file")),s(),this.baseOffset=this.parseOneInt(i[1]);break;case"@stackmark":s(),this.stackpointers[i[1]]=this.stack;break;case"@stackempty":this.checkStack&&(null==this.stackpointers[i[1]]?this.directiveError(n("no such saved stack")):this.stackpointers[i[1]]!=this.stack&&this.directiveError(n("stack mismatch")));break;case"@scope":this.scope=i[1]||"",this.currLineNo=this.scope?0:this.realCurrLineNo;break;case".syntax":case"@nostackcheck":this.checkStack=!1;break;case"@dummystack":s(),this.stack+=this.parseOneInt(i[1]);break;case".section":case".global":this.stackpointers={},this.stack=0,this.scope="$S"+this.scopeId++;break;case".comm":{i=i.filter((e=>","!=e)),i.shift();let e=this.parseOneInt(i[1]),t=0;if(t=i[2]?this.parseOneInt(i[2]):4,null==this.lookupLabel(i[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(i[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(i[0])||this.directiveError(n("unknown directive"))}}handleOneInstruction(e,t){let i=t.emit(e);return!i.error&&(this.stack+=i.stack,this.checkStack&&this.stack<0&&this.pushError(n("stack underflow")),e.location=this.location(),e.opcode=i.opcode,e.stack=i.stack,this.emitOpCode(i.opcode),null!=i.opcode2&&this.emitOpCode(i.opcode2),null!=i.opcode3&&this.emitOpCode(i.opcode3),e.instruction=t,e.numArgs=i.numArgs,!0)}handleInstruction(e){if(e.instruction&&this.handleOneInstruction(e,e.instruction))return;let t=e=>this.ei.instructions.hasOwnProperty(e)?this.ei.instructions[e]:[];if(!e.instruction){let n=t(e.words[0]);for(let t=0;t<n.length;++t)if(this.handleOneInstruction(e,n[t]))return}let i=e.words[0].toLowerCase().replace(/s$/,"").replace(/[^a-z]/g,""),s="",r=t(i).concat(t(i+"s"));r.length>0&&r.forEach((t=>{let i=t.emit(e);s+=n(" Maybe: {0} ({1} at '{2}')\n",t.toString(),i.error,i.errorAt)})),this.pushError(n("assembly error"),s)}buildLine(e,t){let n=e=>{let n=new r(this,e);return n.scope=this.scope,n.lineNo=this.currLineNo,t.push(n),n},i=n(e),s=o(i.text)||[];i.words=s;let a=s[0]||"";if(":"==a.charAt(a.length-1)){let t=/^([\.\w]+):$/.exec(s[0]);if(t){if(i.type="label",i.text=t[1]+":",i.words=[t[1]],!(s.length>1))return;s.shift(),i=n(e.replace(/^[^:]*:/,"")),i.words=s,a=s[0]||""}}let l=a.charAt(0);"."==l||"@"==l?(i.type="directive","@scope"==i.words[0]&&this.handleDirective(i)):0==i.words.length?i.type="empty":i.type="instruction"}prepLines(e){this.currLineNo=0,this.realCurrLineNo=0,this.lines=[],e.split(/\r?\n/).forEach((e=>{this.errors.length>10||(this.currLineNo++,this.realCurrLineNo++,this.buildLine(e,this.lines))}))}iterLines(){this.stack=0,this.buf=[],this.scopeId=0,this.lines.forEach((t=>{if(!(this.errors.length>10)&&(this.currLine=t,0!=t.words.length))if("label"==t.type){let i=this.scopedName(t.words[0]);if(this.prevLabel=i,this.finalEmit){null!=this.equs[i]&&this.directiveError(n(".equ redefined as label"));let t=this.labels[i];null==t&&e.oops(),0==this.errors.length&&t!=this.location()&&e.oops(`invalid location: ${this.location()} != ${t} at ${i}`),e.assert(this.errors.length>0||t==this.location()),this.reallyFinalEmit&&(this.stackAtLabel[i]=this.stack)}else this.labels.hasOwnProperty(i)?this.directiveError(n("label redefinition")):this.inlineMode&&/^_/.test(i)?this.directiveError(n("labels starting with '_' are reserved for the compiler")):this.labels[i]=this.location();t.location=this.location()}else"directive"==t.type?this.handleDirective(t):"instruction"==t.type?this.handleInstruction(t):"empty"==t.type||e.oops()}))}getSourceMap(){const e={};let t="",n=0,i=0,s=0;function r(){t&&i&&(e[t]||(e[t]=[]),e[t].push(n,i,s-i)),i=0,s=0}return this.lines.forEach(((e,a)=>{const o=/^; ([\w\/\.-]+)\(([\d]+),\d+\):/.exec(e.text);o&&(r(),t=o[1],n=parseInt(o[2])),"instruction"==e.type&&(i||(i=e.location),s=e.location)})),r(),e}getSource(i,s=1,r=0){let a=0,o=e=>{let t=this.labels[e]||a,n=t-a;return a=t,n},l=this.buf?this.location():0,c=o("_code_end"),u=o("_helpers_end"),d=o("_vtables_end"),h=o("_literals_end"),p=a,f=l+this.baseOffset&16777215;r&&f>r&&e.U.userError(n("program too big by {0} bytes!",f-r));let g=n("; total bytes: {0} ({1}% of {2}k flash with {3} free)",f,(100*f/(r=r||131072)).toFixed(1),(r/1024).toFixed(1),r-f),m=n("; generated code sizes (bytes): {0} (incl. {1} user, {2} helpers, {3} vtables, {4} lits); src size {5}\n",p,c,u,d,h,l-p)+n("; assembly: {0} lines; density: {1} bytes/stmt; ({2} stmts)\n",this.lines.length,Math.round(100*c/s)/100,s)+g+"\n"+this.stats+"\n\n",b=!1;return this.lines.forEach(((e,n)=>{if("_stored_program"==e.words[0])return m+='_stored_program: .string "..."\n',void(b=!0);if(b)return void(b=!1);let s=e.text;if(i){if("@stackempty"==e.words[0]&&this.lines[n-1].text==e.text)return;if(s=s.replace(/; WAS: .*/,""),!s.trim())return}t.debug&&("label"!=e.type&&"instruction"!=e.type||(s+=` \t; 0x${(e.location+this.baseOffset).toString(16)}`)),m+=s+"\n"})),m}peepHole(){let e=this.lines.filter((e=>"empty"!=e.type));for(let t=0;t<e.length;++t){let n=e[t];if(/^user/.test(n.scope))continue;let i=e[t+1];if(!i)continue;let s=e[t+2];"instruction"==n.type&&this.ei.peephole(n,i,s)}}clearLabels(){this.labels={},this.commPtr=0}peepPass(t){this.disablePeepHole||(this.peepOps=0,this.peepDel=0,this.peepCounts={},this.peepHole(),this.throwOnError=!0,this.finalEmit=!1,this.clearLabels(),this.iterLines(),e.assert(!this.checkStack||0==this.stack),this.finalEmit=!0,this.reallyFinalEmit=t||0==this.peepOps,this.iterLines(),this.stats+=n("; peep hole pass: {0} instructions removed and {1} updated\n",this.peepDel,this.peepOps-this.peepDel))}getLabels(){return this.userLabelsCache||(this.userLabelsCache=e.U.mapMap(this.labels,((e,t)=>t+this.baseOffset))),this.userLabelsCache}emit(t){if(e.assert(null==this.buf),this.prepLines(t),this.errors.length>0)return;if(this.clearLabels(),this.iterLines(),this.checkStack&&0!=this.stack&&this.directiveError(n("stack misaligned at the end of the file")),this.errors.length>0)return;if(this.ei.expandLdlit(this),this.clearLabels(),this.iterLines(),this.finalEmit=!0,this.reallyFinalEmit=this.disablePeepHole,this.iterLines(),this.errors.length>0)return;for(let e=0;e<5&&(pxt.debug(`Peephole OPT, pass ${e}`),this.peepPass(5==e),0!=this.peepOps);++e);pxt.debug("emit done")}}t.File=a;t.VMFile=class extends a{constructor(e){super(e)}};function o(e){let t=[],n="";e:for(let i=0;i<e.length;++i)switch(e[i]){case"[":case"]":case"!":case"{":case"}":case",":n&&(t.push(n),n=""),t.push(e[i]);break;case" ":case"\t":case"\r":case"\n":n&&(t.push(n),n="");break;case";":break e;default:n+=e[i]}return n&&(t.push(n),n=""),t[0]?t:null}function l(e,t){return{stack:null,opcode:null,error:e,errorAt:t}}function c(e){return e<0||e>65535?("0x"+e.toString(16)).toLowerCase():("0x"+("000"+e.toString(16)).slice(-4)).toLowerCase()}t.AbstractProcessor=class{constructor(){this.file=null,this.addEnc=(e,t,n)=>{let i={name:e,pretty:t,encode:n,isRegister:/^\$r\d/.test(e),isImmediate:/^\$i\d/.test(e),isRegList:/^\$rl\d/.test(e),isLabel:/^\$l[a-z]/.test(e)};return this.encoders[e]=i,i},this.inrange=(e,t,n)=>Math.floor(t)!=t||t<0||t>e?null:n,this.inminmax=(e,t,n,i)=>Math.floor(n)!=n||n<e||n>t?null:i,this.inseq=(e,t)=>{let n=e.indexOf(t);return n<0?null:n},this.inrangeSigned=(e,t,n)=>{if(Math.floor(t)!=t)return null;if(t<-(e+1))return null;if(t>e)return null;return n&(e<<1|1)},this.addInst=(e,t,n,i)=>{let r=new s(this,e,t,n,i);return this.instructions.hasOwnProperty(r.name)||(this.instructions[r.name]=[]),this.instructions[r.name].push(r),r},this.encoders={},this.instructions={}}toFnPtr(e,t,n){return e}wordSize(){return-1}computeStackOffset(e,t){return t}is32bit(e){return!1}emit32(e,t,n){return null}postProcessRelAddress(e,t){return t}postProcessAbsAddress(e,t){return t}peephole(e,t,n){}registerNo(e){return null}getAddressFromLabel(e,t,n,i=!1){return null}isPop(e){return!1}isPush(e){return!1}isAddSP(e){return!1}isSubSP(e){return!1}testAssembler(){e.assert(!1)}expandLdlit(e){}},t.emitErr=l,t.expectError=function(t,n){let i=new a(t);i.emit(n),0==i.errors.length&&e.oops("ASMTEST: expecting error for: "+n)},t.tohex=c,t.expect=function(t,n){let i=[],s=n.replace(/^([0-9a-fA-F]{4,8})\s/gm,((e,t)=>(i.push(parseInt(t.slice(0,4),16)),8==t.length&&i.push(parseInt(t.slice(4,8),16)),""))),r=new a(t);r.throwOnError=!0,r.disablePeepHole=!0,r.emit(s),r.errors.length>0&&(console.debug(r.errors[0].message),e.oops("ASMTEST: not expecting errors")),r.buf.length!=i.length&&e.oops("ASMTEST: wrong buf len");for(let t=0;t<i.length;++t)r.buf[t]!=i[t]&&e.oops("ASMTEST: wrong buf content at "+t+" , exp:"+c(i[t])+", got: "+c(r.buf[t]))}}(e.assembler||(e.assembler={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){var n=pxtc.Util;t.apiRoot=e.BrowserUtils.isLocalHost()||n.isNodeJS?"https://www.makecode.com/api/":"/api/",t.accessToken="",t.localToken="";let i=!0;function s(t){let i=new Error(n.lf("Cannot access {0} while offline",t));return i.isOffline=!0,e.U.delay(1e3).then((()=>Promise.reject(i)))}function r(n,i){return e.U.requestAsync({url:"/api/"+n,headers:{Authorization:t.localToken},method:i?"POST":"GET",data:i||void 0,allowHttpErrors:!0})}function a(){return e.webConfig&&!e.webConfig.isStatic&&!e.BrowserUtils.isLocalHost()&&!!e.webConfig.cdnUrl}function o(n){if(n=n.replace(/^\//,""),!a())return t.apiRoot+n;const i=new Date,s=i.getUTCFullYear()+("0"+(i.getUTCMonth()+1)).slice(-2)+("0"+i.getUTCDate()).slice(-2);return n.indexOf("?")<0?n+="?":n+="&",n+="cdn="+s,e.webConfig.cdnUrl+"/api/"+n}function l(e){return a()?(e.url=o(e.url),n.requestAsync(e).catch((t=>c(e,t)))):u(e)}function c(e,n){return 0==n.statusCode?(i&&(i=!1,t.onOffline()),s(e.url)):Promise.reject(n)}function u(i){var r;return i.url=(null===(r=e.webConfig)||void 0===r?void 0:r.isStatic)&&!i.forceLiveEndpoint?e.webConfig.relprefix+i.url:t.apiRoot+i.url,i.allowGzipPost=!0,t.isOnline()||e.BrowserUtils.isPxtElectron()?(i.headers||(i.headers={}),e.BrowserUtils.isLocalHost()?t.localToken&&(i.headers.Authorization=t.localToken):t.accessToken&&(i.headers["x-td-access-token"]=t.accessToken),n.requestAsync(i).catch((e=>c(i,e)))):s(i.url)}function d(){return navigator&&navigator.onLine}t.onOffline=()=>{},t.hasAccessToken=function(){return!!t.accessToken},t.localRequestAsync=r,t.useCdnApi=a,t.cdnApiUrl=o,t.apiRequestWithCdnAsync=l,t.privateRequestAsync=u,t.privateGetTextAsync=function(e,t){return u({url:e,headers:t}).then((e=>e.text))},t.privateGetAsync=function(e,t=!1){return u({url:e,forceLiveEndpoint:t}).then((e=>e.json))},t.downloadTargetConfigAsync=function(){if(!t.isOnline())return Promise.resolve(void 0);const n=e.appTarget.versions&&e.appTarget.versions.target,i=e.webConfig&&e.webConfig.isStatic?"targetconfig.json":`config/${e.appTarget.id}/targetconfig${n?`/v${n}`:""}`;return e.BrowserUtils.isLocalHost()?r(i).then((e=>e?e.json:void 0)):l({url:i}).then((e=>e.json))},t.downloadScriptFilesAsync=function(e){return u({url:e+"/text",forceLiveEndpoint:!0}).then((e=>JSON.parse(e.text)))},t.markdownAsync=async function(t,n){const i=e.BrowserUtils.isLocalHostDev()?0:36e5,s=24*i*7;n=n||e.Util.userLanguage();const o=await e.BrowserUtils.translationDbAsync(),c=await o.getAsync(n,t,""),d=async()=>{try{const i=await function(t,n,i){var s;const o=null===(s=e.webConfig)||void 0===s?void 0:s.isStatic,c=e.appTarget.versions&&e.appTarget.versions.target||"?";let d;if(o){d=t;const e=/\/?docs\//.test(d),n=/\.\w+$/.test(d);if(!e){const e="/"===d[0];d=`docs${e?"":"/"}${d}`}n||(d=`${d}.md`)}else d=`md/${e.appTarget.id}/${t.replace(/^\//,"")}?targetVersion=${encodeURIComponent(c)}`;"en"!=n&&(d+=`${o?"?":"&"}lang=${encodeURIComponent(n)}`);if(e.BrowserUtils.isLocalHost()&&!e.Util.liveLocalizationEnabled())return r(d).then((e=>404==e.statusCode?u({url:d,method:"GET"}).then((e=>({md:e.text,etag:e.headers.etag}))):{md:e.text,etag:void 0}));{const e=i&&!a()?{"If-None-Match":i}:void 0;return l({url:d,method:"GET",headers:e}).then((e=>({md:e.text,etag:e.headers.etag})))}}(t,n,null==c?void 0:c.etag);return!c||i.md&&c.md!==i.md?(await o.setAsync(n,t,"",i.etag,void 0,i.md),i.md):c.md}catch(e){return""}};if(c){const t=Date.now()-c.time,n=t>i;if(t>s)e.tickEvent("markdown.update.wait");else if(n&&(e.tickEvent("markdown.update.background"),d()),c.md)return c.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()&&(i=!0),i},t.getServiceUrl=function(){return t.apiRoot.replace(/\/api\/$/,"")},t.getUserId=function(){let e=/^0(\w+)\./.exec(t.accessToken);return e?e[1]:null},t.parseScriptId=function(t){const i=e.appTarget;if(!(t&&i.appTheme&&i.cloud&&i.cloud.sharing))return;let s=["makecode.com"];i.appTheme.embedUrl&&s.push(i.appTheme.embedUrl),i.appTheme.shareUrl&&s.push(i.appTheme.shareUrl),s=n.unique(s,(e=>e)).map((e=>n.escapeForRegex(n.stripUrlProtocol(e).replace(/\/$/,"")).toLowerCase()));const r=`^((https://)?(?:${s.join("|")})/)?(?:v[0-9]+/)?(api/oembed?url=.*%2F([^&]*)&.*?|([a-z0-9-_]+))$`,a=new RegExp(r,"i").exec(t.trim()),o=a&&(!a[1]||s.indexOf(n.escapeForRegex(a[1].replace(/https:\/\//,"").replace(/\/$/,"")).toLowerCase())>=0)&&(a[3]||a[4])?a[3]?a[3]:a[4]:null;return o&&("_"==o[0]&&13==o.length||23==o.length&&/^[0-9\-]+$/.test(o))?o:void 0}}(e.Cloud||(e.Cloud={}))}(pxt||(pxt={})),function(e){!function(e){e.f4EncodeImg=function(e,t,n,i){let s=[135,n,255&e,e>>8,255&t,t>>8,0,0].map(c).join(""),r=4,a=0,o=0,l=e=>{a|=e<<o,o==8-n?(s+=c(a),r++,a=0,o=0):o+=n};for(let s=0;s<e;++s){for(let e=0;e<t;++e)l(i(s,e));for(;0!=o;)l(0);if(n>1)for(;3&r;)l(0)}return s;function c(e){return("0"+e.toString(16)).slice(-2)}}}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){function t(e){let t="";switch(e){case 0:t="C5";break;case 1:t="B";break;case 2:t="A";break;case 3:t="G";break;case 4:t="F";break;case 5:t="E";break;case 6:t="D";break;case 7:t="C"}return t}function n(e){let t=-1;switch(e){case"C5":t=0;break;case"B":t=1;break;case"A":t=2;break;case"G":t=3;break;case"F":t=4;break;case"E":t=5;break;case"D":t=6;break;case"C":t=7}return t}e.MelodyArray=class{constructor(e){this.numCols=8,this.numRows=8,this.polyphonic=!1,e&&(this.tempo=e),this.resetMelody()}setTempo(e){this.tempo=e}getArray(){return this.melody}setArray(e){this.melody=e}getColor(e){return 0}getValue(e,t){return this.melody[e][t]}getWidth(){return this.numCols}getHeight(){return this.numRows}updateMelody(e,t){const n=!this.melody[e][t];if(n&&!this.polyphonic)for(let e=0;e<this.numRows;e++)this.melody[e][t]=!1;this.melody[e][t]=n}getStringRepresentation(){let e="",n=new Array(this.numCols),i=0;for(let e=0;e<this.numRows;e++){let s=0;n[e]=[];for(let i=0;i<this.numCols;i++)this.melody[i][e]&&(n[e].push(t(i)),s++);s>i&&(i=s)}if(0==i)return"- - - - - - - - ";for(let t=0;t<i;t++)for(let t=0;t<this.numCols;t++)n[t]&&n[t].length>0?e+=n[t].shift()+" ":e+="- ";return e}parseNotes(e){let t=(e=e.trim()).split(" ");for(let e=0;e<t.length;e++){for(let t=0;t<this.numRows;t++)this.melody[t][e]=!1;"-"!=t[e]&&(this.melody[n(t[e])][e]=!0)}}setPolyphonic(e){this.polyphonic=e}isPolyphonic(){return this.polyphonic}resetMelody(){this.melody=new Array(this.numCols);for(let e=0;e<this.numCols;e++)this.melody[e]=new Array(this.numRows).fill(!1)}},e.rowToNote=t,e.noteToRow=n,e.getColorClass=function(e){let t="melody-default";switch(e){case 0:t="melody-red";break;case 1:t="melody-orange";break;case 2:t="melody-yellow";break;case 3:t="melody-green";break;case 4:t="melody-teal";break;case 5:t="melody-blue";break;case 6:t="melody-purple";break;case 7:t="melody-violet"}return t}}(pxtmelody||(pxtmelody={})),function(e){function t(e,t,n){return function(e,t,n){if(t)for(const n of Object.keys(t))"className"===n?e.setAttribute("class",t[n]+""):e.setAttribute(n,t[n]+"");n&&e.addEventListener("click",n);return e}(document.createElement(e),t,n)}e.MelodyGallery=class{constructor(){this.value=null,this.visible=!1,this.timeouts=[],this.numSamples=e.SampleMelodies.length,this.containerDiv=document.createElement("div"),this.containerDiv.setAttribute("id","melody-editor-gallery-outer"),this.contentDiv=document.createElement("div"),this.contentDiv.setAttribute("id","melody-editor-gallery"),this.itemBackgroundColor="#DCDCDC",this.itemBorderColor="white",this.initStyles(),this.containerDiv.appendChild(this.contentDiv),this.containerDiv.style.display="none",this.contentDiv.addEventListener("animationend",(()=>{this.visible||(this.containerDiv.style.display="none")})),this.contentDiv.addEventListener("wheel",(e=>{e.stopPropagation()}),!0)}getElement(){return this.containerDiv}getValue(){return this.value}show(e){this.pending=e,this.containerDiv.style.display="block",this.buildDom(),this.visible=!0,pxt.BrowserUtils.removeClass(this.contentDiv,"hidden-above"),pxt.BrowserUtils.addClass(this.contentDiv,"shown")}hide(){this.visible=!1,pxt.BrowserUtils.removeClass(this.contentDiv,"shown"),pxt.BrowserUtils.addClass(this.contentDiv,"hidden-above"),this.value=null,this.stopMelody()}clearDomReferences(){this.contentDiv=null,this.containerDiv=null}layout(e,t,n){this.containerDiv.style.left=e+"px",this.containerDiv.style.top=t+"px",this.containerDiv.style.height=n+"px"}buildDom(){for(;this.contentDiv.firstChild;)this.contentDiv.removeChild(this.contentDiv.firstChild);const t=e.SampleMelodies;this.buttons=[];for(let e=0;e<t.length;e++)this.mkButton(t[e],e,"255px","45px")}initStyles(){const e=document.createElement("style");e.textContent="\n #melody-editor-gallery {\n margin-top: -100%;\n }\n\n #melody-editor-gallery.hidden-above {\n margin-top: -100%;\n animation: slide-up 0.2s 0s ease;\n }\n\n #melody-editor-gallery.shown {\n margin-top: 0px;\n animation: slide-down 0.2s 0s ease;\n }\n\n @keyframes slide-down {\n 0% {\n margin-top: -100%;\n }\n 100% {\n margin-top: 0px;\n }\n }\n\n @keyframes slide-up {\n 0% {\n margin-top: 0px;\n }\n 100% {\n margin-top: -100%;\n }\n }\n ",this.containerDiv.appendChild(e)}mkButton(e,n,i,s){const r=t("div",{className:"melody-gallery-button melody-editor-card",role:"menuitem",id:`:${n}`}),a=t("i",{className:"music icon melody-icon"}),o=t("div",{className:"melody-editor-text"});o.innerText=e.name;const l=this.createColorBlock(e),c=t("div",{className:"melody-editor-button left-button",role:"button",title:e.name},(()=>this.handleSelection(e)));c.appendChild(a),c.appendChild(o),c.appendChild(l),r.appendChild(c);const u=t("div",{className:"melody-editor-button right-button",role:"button",title:lf("Preview {0}",e.name)},(()=>this.togglePlay(e,n))),d=t("i",{className:"play icon"});this.buttons[n]=d,u.appendChild(d),r.appendChild(u),this.contentDiv.appendChild(r)}handleSelection(e){if(this.pending){const t=this.pending;this.pending=void 0,t(e.notes)}}playNote(e,t,n){let i=0;switch(e){case"C5":i=523;break;case"B":i=494;break;case"A":i=440;break;case"G":i=392;break;case"F":i=349;break;case"E":i=330;break;case"D":i=294;break;case"C":i=262}this.timeouts.push(setTimeout((()=>{pxt.AudioContextManager.tone(i)}),t*this.getDuration(n))),this.timeouts.push(setTimeout((()=>{pxt.AudioContextManager.stop()}),(t+1)*this.getDuration(n)))}getDuration(e){return 6e4/e}previewMelody(e){this.stopMelody();let t=e.notes.split(" ");for(let n=0;n<t.length;n++)this.playNote(t[n],n,e.tempo)}togglePlay(e,t){let n=this.buttons[t];pxt.BrowserUtils.containsClass(n,"play icon")?(this.resetPlayIcons(),pxt.BrowserUtils.removeClass(n,"play icon"),pxt.BrowserUtils.addClass(n,"stop icon"),this.previewMelody(e),this.timeouts.push(setTimeout((()=>{pxt.BrowserUtils.removeClass(n,"stop icon"),pxt.BrowserUtils.addClass(n,"play icon")}),e.notes.split(" ").length*this.getDuration(e.tempo)))):(pxt.BrowserUtils.removeClass(n,"stop icon"),pxt.BrowserUtils.addClass(n,"play icon"),this.stopMelody())}stopMelody(){for(;this.timeouts.length;)clearTimeout(this.timeouts.shift());pxt.AudioContextManager.stop()}resetPlayIcons(){for(let e=0;e<this.numSamples;e++){let t=this.buttons[e];if(pxt.BrowserUtils.containsClass(t,"stop icon")){pxt.BrowserUtils.removeClass(t,"stop icon"),pxt.BrowserUtils.addClass(t,"play icon");break}}}createColorBlock(t){let n=document.createElement("div");pxt.BrowserUtils.addClass(n,"melody-color-block");let i=t.notes.split(" ");for(let t=0;t<i.length;t++){let s=e.getColorClass(e.noteToRow(i[t])),r=document.createElement("div");0==t?pxt.BrowserUtils.addClass(r,"left-edge sliver "+s):t==i.length-1?pxt.BrowserUtils.addClass(r,"right-edge sliver "+s):pxt.BrowserUtils.addClass(r,"sliver "+s),n.appendChild(r)}return n}}}(pxtmelody||(pxtmelody={})),function(e){class t{constructor(e,t,n){this.name=e,this.notes=t,this.tempo=n}}e.MelodyInfo=t,e.SampleMelodies=[new t(lf("Scale"),"C5 B A G F E D C",120),new t(lf("Reverse"),"C D E F G A B C5",120),new t(lf("Mystery"),"E B C5 A B G A F",120),new t(lf("Gilroy"),"A F E F D G E F",120),new t(lf("Falling"),"C5 A B G A F G E",120),new t(lf("Hopeful"),"G B A G C5 B A B",120),new t(lf("Tokyo"),"B A G A G F A C5",120),new t(lf("Paris"),"G F G A - F E D",120),new t(lf("Rising"),"E D G F B A C5 B",120),new t(lf("Sitka"),"C5 G B A F A C5 B",120)]}(pxtmelody||(pxtmelody={}));
|
|
1
|
+
pxt||(pxt={}),function(e){!function(t){const n={},i={};let s=!1;t.addDefaultProperties=function(e){Object.keys(e).forEach((t=>{"string"==typeof e[t]?n[t]=e[t]:i[t]=e[t]}))},t.enable=function(){if(!e.aiTrackException||!e.aiTrackEvent||s)return;s=!0,e.debug("setting up app insights");const t=e.tickEvent;e.tickEvent=function(s,r,a){if(t&&t(s,r,a),(null==a?void 0:a.interactiveConsent)&&e.setInteractiveConsent(!0),r){const t=Object.assign({},n)||{},a=Object.assign({},i)||{};Object.keys(r).forEach((e=>{"string"==typeof r[e]?t[e]=r[e]:"number"==typeof r[e]?a[e]=r[e]:t[e]=JSON.stringify(r[e]||"")})),e.aiTrackEvent(s,t,a)}else e.aiTrackEvent(s)};const r=e.reportException;e.reportException=function(t,n){r&&r(t,n);const i={target:e.appTarget.id,version:e.appTarget.versions.target};n&&e.Util.jsonMergeFrom(i,n),e.aiTrackException(t,"exception",i)};const a=e.reportError;e.reportError=function(t,n,i){a&&a(t,n,i);try{throw n}catch(s){const r={target:e.appTarget.id,version:e.appTarget.versions.target,category:t,message:n};i&&e.Util.jsonMergeFrom(r,i),e.aiTrackException(s,"error",r)}}}}(e.analytics||(e.analytics={}))}(pxt||(pxt={})),pxt||(pxt={}),function(e){!function(e){let t,n,i,s=0,r=!1;function a(){return t||(t=function(){if(window.AudioContext=window.AudioContext||window.webkitAudioContext,window.AudioContext)try{return new window.AudioContext}catch(e){}return}()),t}function o(){t&&(i.gain.setTargetAtTime(0,t.currentTime,.015),s=0)}e.mute=function(e){t&&(r=e,o(),e&&n&&(n.disconnect(),i.disconnect(),n=void 0,i=void 0))},e.stop=o,e.frequency=function(){return s},e.tone=function(e){if(r)return;if(e<0)return;s=e;let o=a();if(o)try{n||(n=o.createOscillator(),n.type="triangle",i=o.createGain(),i.gain.value=0,i.connect(o.destination),n.connect(i),n.start(0)),n.frequency.linearRampToValueAtTime(e,t.currentTime),i.gain.setTargetAtTime(.2,t.currentTime,.015)}catch(e){return void(n=void 0)}}}(e.AudioContextManager||(e.AudioContextManager={}))}(pxt||(pxt={})),function(e){!function(t){const n="auth",i="csrf-token",s="login-state",r="user-state";let a,o=!1;t.DEFAULT_USER_PREFERENCES=()=>({highContrast:!1,language:e.appTarget.appTheme.defaultLocale,reader:"",skillmap:{mapProgress:{},completedTags:{}},email:!1}),t.client=function(){return a};let l=0,c=0;t.AuthClient=class{constructor(){this.initialUserPreferences_=void 0,this.initialAuthCheck_=void 0,this.patchQueue=[],e.Util.assert(!a),a=this}async initAsync(){try{this.state$=await e.storage.shared.getAsync(n,r)}catch(e){}this.state$||(this.state$={}),this.setUserProfileAsync(this.state$.profile),this.setUserPreferencesAsync(this.state$.preferences)}async loginAsync(t,i,r){var a;if(!h()||!function(e){return d().filter((t=>t.id===e)).length>0}(t))return;r=null!=r?r:u;const o=this.getState();o.profile||await this.authCheckAsync();if((null===(a=o.profile)||void 0===a?void 0:a.idp)===t)return void e.debug(`loginAsync: Already signed into ${t}.`);this.clearState();const l={key:(Math.PI*Math.random()).toString(36).slice(2),callbackState:r,callbackPathname:window.location.pathname,idp:t};await e.storage.shared.setAsync(n,s,l);const c=e.Util.stringifyQueryString("/api/auth/login",{response_type:"token",provider:t,persistent:i,redirect_uri:`${window.location.origin}${window.location.pathname}?authcallback=1&state=${l.key}`}),p=await this.apiAsync(c);p.success?(e.tickEvent("auth.login.start",{provider:t}),window.location.href=p.resp.loginUrl):await this.onSignInFailed()}async logoutAsync(t){if(!h())return;e.tickEvent("auth.logout"),await this.apiAsync("/api/auth/logout"),await e.storage.shared.delAsync(n,i),this.clearState();const s=t?t.startsWith("#")?t:`#${t}`:"";e.BrowserUtils.hasWindow()&&(window.location.href=`${window.location.origin}${window.location.pathname}${s}`,location.reload())}async deleteProfileAsync(){var t;if(!await this.loggedInAsync())return;const s=null===(t=this.getState().profile)||void 0===t?void 0:t.id,r=await this.apiAsync("/api/user",null,"DELETE");if(r.err)await this.onApiError(r.err);else try{await e.storage.shared.delAsync(n,i);try{await this.onProfileDeleted(s)}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(!h())return;if(!await e.storage.shared.getAsync(n,i))return;const s=this.getState();return(null===(t=s.profile)||void 0===t?void 0:t.id)?this.initialAuthCheck_||(this.initialAuthCheck_=Promise.resolve(s.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 i=async()=>({success:!0,res:await this.userPreferencesAsync()});if(!(t=(t=Array.isArray(t)?t:[t]).filter((e=>!!e))).length)return await i();const s=(t,n,i)=>{const s=e.U.deepCopy(t);ts.pxtc.jsonPatch.patchInPlace(s,n);let r=ts.pxtc.jsonPatch.diff(t,s);return r.length&&i&&(r=r.filter(i)),r},r=await this.userPreferencesAsync(),a=s(r,t,n.filter);if(!a.length)return await i();if(ts.pxtc.jsonPatch.patchInPlace(r,a),await this.setUserPreferencesAsync(r),!await this.loggedInAsync())return await i();this.patchQueue.push({ops:t,filter:n.filter}),clearTimeout(l);const o=async()=>{if(c=0,!this.patchQueue.length)return await i();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),r=this.patchQueue;this.patchQueue=[],r.forEach((e=>{const t=s(n,e.ops,e.filter);ts.pxtc.jsonPatch.patchInPlace(n,t)}));const a=pxtc.jsonPatch.diff(t.resp,n),o=await this.apiAsync("/api/user/preferences",a,"PATCH");return o.success?this.setUserPreferencesAsync(o.resp):e.reportError("identity","failed to patch preferences",o),{success:o.success,res:o.resp}};return n.immediate?await o():(c||(c=e.U.now()),1e4<e.U.now()-c?await o():(l=setTimeout(o,1e3),{success:!1,res:void 0}))}hasUserId(){var e;if(!h())return!1;return!!(null===(e=this.getState().profile)||void 0===e?void 0:e.id)}async fetchUserAsync(){var e;if(!h())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 i=null!==(n=this.getState().preferences)&&void 0!==n?n:t.DEFAULT_USER_PREFERENCES(),s=ts.pxtc.jsonPatch.diff(i,e);this.transformUserPreferences(Object.assign(Object.assign({},i),e)),await this.onUserPreferencesChanged(s)}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,r,this.state$).then((()=>{}))}clearState(){this.state$={},e.storage.shared.delAsync(n,r).then((()=>this.onStateCleared()))}async apiAsync(t,s,r){var a;const o={},l=await e.storage.shared.getAsync(n,i);return l&&(o.authorization=`mkcd ${l}`),o["x-pxt-target"]=null===(a=e.appTarget)||void 0===a?void 0:a.id,t=e.BrowserUtils.isLocalHostDev()?`https://staging.pxt.io${t}`:t,e.Util.requestAsync({url:t,headers:o,data:s,method:r||(s?"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 h(){return!o&&!e.BrowserUtils.isPxtElectron()&&d().length>0}function p(e,t){return e.id===t.id&&e.sourceURL===t.sourceURL}t.loginCallbackAsync=async function(t){let r,a=Object.assign({},u);do{if(r=await e.storage.shared.getAsync(n,s),!r)return void e.debug("Auth state not found in storge.");await e.storage.shared.delAsync(n,s);const o=t.state;if(!o||r.key!==o)return void e.debug("Failed to get auth state for key");a=Object.assign(Object.assign({},u),r.callbackState);const l=t.error;if(l){const n=t.error_description;e.tickEvent("auth.login.error",{error:l,provider:r.idp}),e.log(`Auth failed: ${l}:${n}`),a=Object.assign({},u);break}const c=t.token;if(!c){e.debug("Missing authToken in auth callback.");break}await e.storage.shared.setAsync(n,i,c),e.tickEvent("auth.login.success",{provider:r.idp})}while(0);const o=a.hash.startsWith("#")?a.hash:`#${a.hash}`,l=e.Util.stringifyQueryString("",a.params),c=`${r.callbackPathname.startsWith("/")?r.callbackPathname:`/${r.callbackPathname}`}${o}${l}`;window.location.href=c},t.identityProviders=d,t.identityProvider=function(e){return d().filter((t=>t.id===e)).shift()},t.hasIdentity=h,t.enableAuth=function(e=!0){o=!e},t.userName=function(e){var t,n,i,s;return null!==(s=null!==(n=null===(t=null==e?void 0:e.idp)||void 0===t?void 0:t.displayName)&&void 0!==n?n:null===(i=null==e?void 0:e.idp)||void 0===i?void 0:i.username)&&void 0!==s?s:"??"},t.userInitials=function(t){const n=e.auth.userName(t);return ts.pxtc.Util.initials(n)},t.generateUserProfilePicDataUrl=function(t){var n,i;if(null===(i=null===(n=null==t?void 0:t.idp)||void 0===n?void 0:n.picture)||void 0===i?void 0:i.encoded){const n=window.URL||window.webkitURL;try{const i=e.Util.stringToUint8Array(atob(t.idp.picture.encoded)),s=new Blob([i],{type:t.idp.picture.mimeType});t.idp.picture.dataUrl=n.createObjectURL(s)}catch(e){}}},t.badgeEquals=p,t.hasBadge=function(e,t){return e.badges.some((e=>p(e,t)))}}(e.auth||(e.auth={}))}(pxt||(pxt={})),function(e){e.tickEvent=function(e){}}(pxt||(pxt={})),function(e){!function(e){e.__dummy=42}(e.pxtc||(e.pxtc={}))}(ts||(ts={}));var pxtc=ts.pxtc;!function(e){!function(e){!function(e){function t(e){return e.replace(/[^\w .!?\-$]/g,(e=>{let t=e.charCodeAt(0).toString(16);return"\\u"+"0000".substr(0,4-t.length)+t}))}e.assert=function(e,t="Assertion failed"){if(!e)throw new Error(t)},e.flatClone=function(e){if(null==e)return null;let t={};return Object.keys(e).forEach((n=>{t[n]=e[n]})),t},e.clone=function(e){return null==e?null:JSON.parse(JSON.stringify(e))},e.htmlEscape=function(e){return e?e.replace(/([^\w .!?\-$])/g,(e=>"&#"+e.charCodeAt(0)+";")):e},e.htmlUnescape=function(e){return e?e.replace(/(&#\d+;)/g,(e=>String.fromCharCode(Number(e.substr(2,e.length-3))))):e},e.jsStringQuote=t,e.jsStringLiteral=function(e){return'"'+t(e)+'"'},e.initials=function(e){if(/^\w+@/.test(e)){return e.match(/^\w\w/).shift().toUpperCase()}{const t=e.match(/\b\w/g)||[];return((t.shift()||"")+(t.pop()||"")).toUpperCase()}};let n="en",i={},s={},r=!1;function a(){return n}function o(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 l(t,n){return 0==n.length?t:t.replace(/\{([0-9]+)(\:[^\}]+)?\}/g,(function(t,i,s){let r=n[parseInt(i)],a="",o=/^:f(\d*)\.(\d+)/.exec(s);if(o){let e=parseInt(o[2]),t=parseInt(o[1])||0,n=/^0/.test(o[1])?"0":" ",i=r.toFixed(e);if(t>0&&e>0&&(t+=e+1),t>0)for(;i.length<t;)i=n+i;a=i}else a=":x"==s?"0x"+r.toString(16):void 0===r?"(undef)":null===r?"(null)":r.toString?r.toString():r+"";return":a"==s?/^\s*[euioah]/.test(a.toLowerCase())?a="an "+a:/^\s*[bcdfgjklmnpqrstvwxz]/.test(a.toLowerCase())&&(a="a "+a):":s"==s?a=1==r?"":"s":":q"==s?a=e.htmlEscape(a):":jq"==s?a=e.jsStringQuote(a):":uri"==s?a=encodeURIComponent(a).replace(/'/g,"%27").replace(/"/g,"%22"):":url"==s?a=encodeURI(a).replace(/'/g,"%27").replace(/"/g,"%22"):":%"==s&&(a=(100*r).toFixed(1).toString()+"%"),a}))}e.enableLiveLocalizationUpdates=function(){r=!0},e.liveLocalizationEnabled=function(){return r},e.localeInfo=function(){return`${r?"live-":""}${a()}`},e.userLanguage=a,e.normalizeLanguageCode=o,e.setUserLanguage=function(e){n=o(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 a()==e.TRANSLATION_LOCALE},e._localize=function(e){return i[e]||e},e.getLocalizedStrings=function(){return i},e.setLocalizedStrings=function(e){i=e},e.translationsCache=function(){return s},e.fmt_va=l,e.fmt=function(e,...t){return l(e,t)};const c={};e.dumpLocStats=function(){const e={};Object.keys(c).sort(((e,t)=>c[t]-c[e])).forEach((t=>e[t]=t)),console.log("prioritized list of strings:"),console.log(JSON.stringify(e,null,2))};function u(t,n){if(!t)return t;c[t]=(c[t]||0)+1;let i=e._localize(t);return i=i.replace(/^\{(id|loc):[^\}]+\}/g,""),l(i,n)}e.lf_va=u,e.lf=function(e,...t){return u(e,t)},e.rlf=function(e,...t){return u(e,t)},e.lookup=function(e,t){return e.hasOwnProperty(t)?e[t]:null},e.isoTime=function(t){let n=new Date(1e3*t);return e.fmt("{0}-{1:f02.0}-{2:f02.0} {3:f02.0}:{4:f02.0}:{5:f02.0}",n.getFullYear(),n.getMonth()+1,n.getDate(),n.getHours(),n.getMinutes(),n.getSeconds())},e.userError=function(e){let t=new Error(e);throw t.isUserError=!0,t},e.deq=function e(t,n){if(t===n)return null;if(!t||!n)return"Null value";if("object"==typeof t&&"object"==typeof n){if(Array.isArray(t)){if(!Array.isArray(n))return"Expected array";if(t.length!=n.length)return"Expected array of length "+t.length+", got "+n.length;for(let i=0;i<t.length;i++)if(null!=e(t[i],n[i]))return"Expected array value "+t[i]+" got "+n[i];return null}let i=Object.keys(t),s=Object.keys(t);if(i.length!=s.length)return"Expected "+i.length+" keys, got "+s.length;for(let s=0;s<i.length;s++){if(!Object.prototype.hasOwnProperty.call(n,i[s]))return"Missing key "+i[s];if(null!=e(t[i[s]],n[i[s]]))return"Expected value of "+i[s]+" to be "+t[i[s]]+", got "+n[i[s]]}return null}return"Unable to compare "+t+", "+n}}(e.Util||(e.Util={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={}));const lf=ts.pxtc.Util.lf;var pxt,ts,pxtmelody;!function(e){!function(e){e.decodeBase64=function(e){return atob(e)},e.encodeBase64=function(e){return btoa(e)}}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){!function(n){function i(e,t){if(t)for(let n=0;n<t.length;++n)e.push(t[n])}function s(e){let t=[];for(let n=0;n<e.length;++n)i(t,e[n]);return t}function r(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function a(e,t,n,i,s){void 0===i&&(i=0),void 0===s&&(s=n.length-i);for(let r=0;r<s;++r)e[t+r]=n[i+r]}function o(e,t){return e==t?0:e<t?-1:1}n.CancellationToken=class{constructor(){this.pending=!1,this.cancelled=!1}startOperation(){this.pending=!0}isRunning(){return this.pending}onProgress(e){this.progressHandler=e}reportProgress(e,t){this.progressHandler&&this.progressHandler(e,t)}cancel(){this.cancelled=!0,this.pending=!1}cancelAsync(){return this.cancelled||!this.pending?(this.cancelled=!0,this.pending=!1,Promise.resolve()):(this.cancelled=!0,this.deferred=new Promise((e=>{this.resolve=e})),this.deferred)}isCancelled(){return this.cancelled}throwIfCancelled(){if(this.isCancelled())throw new Error}resolveCancel(){this.pending=!1,this.deferred&&(this.resolve(),this.deferred=void 0,this.resolve=void 0)}},n.codalHash16=function(e){const t=[251,175,119,215,81,14,79,191,103,49,181,143,186,157,0,232,31,32,55,60,152,58,17,237,174,70,160,144,220,90,57,223,59,3,18,140,111,166,203,196,134,243,124,95,222,179,197,65,180,48,36,15,107,46,233,130,165,30,123,161,209,23,97,16,40,91,219,61,100,10,210,109,250,127,22,138,29,108,244,67,207,9,178,204,74,98,126,249,167,116,34,77,193,200,121,5,20,113,71,35,128,13,182,94,25,226,227,199,75,27,41,245,230,224,43,225,177,26,155,150,212,142,218,115,241,73,88,105,39,114,62,255,192,201,145,214,168,158,221,148,154,122,12,84,82,163,44,139,228,236,205,242,217,11,187,146,159,64,86,239,195,42,106,198,118,112,184,172,87,2,173,117,176,229,247,253,137,185,99,164,102,147,45,66,231,52,141,211,194,206,246,238,56,110,78,248,63,240,189,93,92,51,53,183,19,171,72,50,33,104,101,69,8,252,83,120,76,135,85,54,202,125,188,213,96,235,136,208,162,129,190,132,156,38,47,1,7,254,24,4,216,131,89,21,28,133,37,153,149,80,170,68,6,169,234,151];function n(e){let n=0;for(let i=0;i<e.length;i++){let s=e[i];n=t[n^s]}return n}return e?function(e,t){let i;const s=new Uint8Array(e.length);for(let t=0;t<e.length;++t){const n=e.charCodeAt(t);s[t]=255&n}let r=0;for(let e=0;e<t;++e)i=n(s),r|=i<<8*e,s[0]=(s[0]+1)%255;return r}(e,2):0},n.bufferSerial=function(e,t="",n="?",i=255){for(let s=0;s<t.length;++s){const r=t[s];if(e[n]=(e[n]||"")+r,"\n"===r||e[n].length>i){let t=e[n];e[n]="",window.postMessage({type:"serial",id:n,data:t},"*")}}},n.blobReadAsDataURL=function(e){return e?new Promise(((t,n)=>{const i=new FileReader;i.onload=()=>t(i.result),i.onerror=e=>n(e),i.readAsDataURL(e)})):Promise.resolve(void 0)},n.fileReadAsBufferAsync=function(e){return e?new Promise(((t,n)=>{let i=new FileReader;i.onerror=e=>t(null),i.onload=e=>t(new Uint8Array(i.result)),i.readAsArrayBuffer(e)})):Promise.resolve(null)},n.fileReadAsTextAsync=function(e){return e?new Promise(((t,n)=>{let i=new FileReader;i.onerror=e=>t(null),i.onload=e=>t(i.result),i.readAsText(e)})):Promise.resolve(null)},n.repeatMap=function(e,t){e=e||0;let n=[];for(let i=0;i<e;++i)n.push(t(i));return n},n.listsEqual=function(e,t){if(!e||!t||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0},n.oops=function(e="OOPS"){throw new Error(e)},n.reversed=function(e){return(e=e.slice(0)).reverse(),e},n.arrayEquals=function(e,t,n=((e,t)=>e===t)){if(e==t)return!0;if(!e&&t||!t&&e||e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!n(e[i],t[i]))return!1;return!0},n.iterMap=function(e,t){Object.keys(e).forEach((n=>t(n,e[n])))},n.mapMap=function(e,t){let n={};return Object.keys(e).forEach((i=>n[i]=t(i,e[i]))),n},n.values=function(e){return Object.keys(e||{}).map((t=>e[t]))},n.pushRange=i,n.concatArrayLike=function(e){return s(e)},n.concat=s,n.memcpy=a,n.uint8ArrayConcat=function(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),i=0;for(let t of e)a(n,i,t),i+=t.length;return n},n.jsonTryParse=function(e){try{return JSON.parse(e)}catch(e){return}},n.jsonMergeFrom=function e(t,i){i&&Object.keys(i).forEach((s=>{r(t[s])&&r(i[s])?e(t[s],i[s]):t[s]=n.clone(i[s])}))},n.jsonCopyFrom=function(e,t){let i=n.clone(t);for(let n of Object.keys(t))e[n]=i[n]},n.jsonFlatten=function(e){let t={},i=(e,s)=>{if(null!==s&&"object"==typeof s){n.assert(!Array.isArray(s)),e&&(e+=".");for(let t of Object.keys(s))i(e+t,s[t])}else t[e]=s};return i("",e),t},n.jsonUnFlatten=function(e){let t={};for(let n of Object.keys(e)){let i=t,s=n.split(".");for(let t=0;t<s.length;++t){let r=s[t];t==s.length-1?i[r]=e[n]:("object"!=typeof i[r]&&(i[r]={}),i=i[r])}}return t},n.strcmp=o,n.stringMapEq=function(e,t){let n=Object.keys(e),i=Object.keys(t);if(n.length!=i.length)return!1;for(let i of n){if(!t.hasOwnProperty(i))return!1;if(e[i]!==t[i])return!1}return!0},n.endsWith=function(e,t){return!(e.length<t.length)&&(0==t.length||e.slice(-t.length)==t)},n.startsWith=function(e,t){return!(e.length<t.length)&&(0==t.length||e.slice(0,t.length)==t)},n.contains=function(e,t){return!(e.length<t.length)&&(0==t.length||e.indexOf(t)>-1)},n.replaceAll=function(e,t,n){return t?e.split(t).join(n):e},n.snakify=function(e){const t=e.toUpperCase(),n=e.toLowerCase();if(e==t||e==n)return e;if(e.lastIndexOf("_")>0)return e;const i=t=>e[t]!=n[t],s=n=>e[n]!=t[n];let r="",a=0;for(;a<e.length;){let t=i(a),n=a;for(;n<e.length;){if(t&&s(n)){if(n-a>2){n--;break}t=!1}if(!t&&i(n))break;n++}r&&(r+="_"),r+=e.slice(a,n),a=n}return r.toUpperCase()===r?r:r.toLowerCase()},n.sortObjectFields=function(e){let t=Object.keys(e);t.sort(o);let n={};return t.forEach((t=>n[t]=e[t])),n},n.chopArray=function(e,t){let n=[];for(let i=0;i<e.length;i+=t)n.push(e.slice(i,i+t));return n},n.unique=function(e,t){let n=[],i={};return e.forEach((e=>{let s=t(e);i.hasOwnProperty(s)||(i[s]=null,n.push(e))})),n},n.groupBy=function(e,t){let n={};return e.forEach((e=>{let i=t(e);n.hasOwnProperty(i)||(n[i]=[]),n[i].push(e)})),n},n.toDictionary=function(e,t){let n={};return e.forEach((e=>{n[t(e)]=e})),n},n.toSet=function(e,t){let n={};return e.forEach((e=>{n[t(e)]=!0})),n},n.deepCopy=function e(t){if("object"!=typeof t||null===t)return t;const n=Array.isArray(t)?[]:{};for(const i in t){const s=t[i];n[i]=e(s)}return n},n.toArray=function(e){if(Array.isArray(e))return e;let t=[];if(!e)return t;for(let n=0;n<e.length;++n)t.push(e[n]);return t},n.indexOfMatching=function(e,t){for(let n=0;n<e.length;++n)if(t(e[n]))return n;return-1};const l=Promise.resolve();async function c(e,t,n){let i=0;const s=[],r=[];for(let a=0;a<e;a++){const e=(async()=>{for(;i<t.length;){const e=i++,s=t[e];r[e]=await n(s)}})();s.push(e)}try{await Promise.all(s)}catch(e){throw i=t.length,e}return r}function u(e,t){const n={};return i=>{const s=e(i);return n.hasOwnProperty(s)?n[s]:n[s]=t(i)}}n.nextTick=function(e){l.then(e)},n.delay=async function(e,t){const n=await t;return await new Promise((t=>setTimeout((()=>t()),e))),n},n.promiseMapAll=function(e,t){return Promise.all(e.map((e=>t(e))))},n.promiseMapAllSeries=function(e,t){return c(1,e,t)},n.promisePoolAsync=c,n.memoizeString=function(e){return u((e=>e),e)},n.promiseTimeout=async function(e,t,n){let i,s;const r=new Promise(((t,r)=>{s=t,i=setTimeout((()=>{s=void 0,clearTimeout(i),r(n||`Promise timed out after ${e}ms`)}),e)}));return Promise.race([t,r]).then((e=>(s&&(clearTimeout(i),s()),e)))},n.defer=function(){let e,t,n,i=!1;return{resolve:function(n){i?pxt.debug("Deferred promise already resolved"):(t?t(n):e=e||new Promise((function(e){e(n)})),i=!0)},reject:function(t){i?pxt.debug("Deferred promise already resolved"):(n?n(t):e=e||new Promise((function(e,n){n(t)})),i=!0)},promise:new Promise((function(i,s){e?i(e):(t=i,n=s)}))}},n.memoize=u,n.debounce=function(e,t,n){let i;return function(){let s=this,r=arguments,a=function(){i=null,n||e.apply(s,r)},o=n&&!i;return clearTimeout(i),i=setTimeout(a,t),o&&e.apply(s,r),i}};function d(e){return e&&(e=e.replace(/\\/g,"/")),e}function h(e){return n.httpRequestCoreAsync(e).then((i=>{const s=i.statusCode;if((e.successCodes||[304,200,201,202]).indexOf(s)<0&&!e.allowHttpErrors){const t=n.lf("Bad HTTP status code: {0} at {1}; message: {2}",i.statusCode,e.url,(i.text||"").slice(0,500)),s=new Error(t);return s.statusCode=i.statusCode,Promise.reject(s)}return i.text&&/application\/json/.test(i.headers["content-type"])&&(i.json=t.U.jsonTryParse(i.text)),i}))}function p(e,t){let n="";if(!e)return n;for(let i=0;i<e.length;++i){let s=e.charCodeAt(i);if(s<=127)n+=e.charAt(i);else if(s<=2047)n+=String.fromCharCode(192|s>>6,128|63&s);else{if(!t&&55296<=s&&s<=56319){let t=e.charCodeAt(++i);isNaN(t)||(s=65536+(s-55296<<10)+(t-56320))}n+=s<=65535?String.fromCharCode(224|s>>12,128|s>>6&63,128|63&s):String.fromCharCode(240|s>>18,128|s>>12&63,128|s>>6&63,128|63&s)}}return n}n.AdaptiveDebouncer=class{constructor(e,t=300,n=2e3,i=2){this.func=e,this.minDelay=t,this.maxDelay=n,this.slowdownFactor=i,this.lastPoke=0,this.recentGaps=[],this.wrapped=()=>{this.timeout=null,this.func()}}poke(){const e=Date.now();if(this.lastPoke){const t=e-this.lastPoke;if(t<10)return;for(t<4e3&&this.recentGaps.push(t);this.recentGaps.length>10;)this.recentGaps.shift()}this.lastPoke=e}trigger(){let e=this.maxDelay;if(this.lastPoke){const t=this.recentGaps.slice();t.sort();const n=t[t.length>>1]||1;e=Math.min(Math.max(n*this.slowdownFactor|0,this.minDelay),this.maxDelay);e-=Date.now()-this.lastPoke,e<0&&(e=0),this.lastPoke=null}clearTimeout(this.timeout),this.timeout=setTimeout(this.wrapped,e)}},n.throttle=function(e,t,n){let i;return function(){let s=this,r=arguments,a=function(){i=null,n||e.apply(s,r)},o=n&&!i;i||(i=setTimeout(a,t)),o&&e.apply(s,r)}},n.randomPermute=function(e){for(let t=0;t<e.length;++t){let n=g()%e.length,i=e[t];e[t]=e[n],e[n]=i}},n.randomPick=function(e){return 0==e.length?null:e[g()%e.length]},n.timeSince=function(e){let t=(Date.now()-(e*=1e3))/1e3;return isNaN(t)?"":t<-30?(t=-t,t<60?n.lf("in a few seconds"):t<120?n.lf("in a minute"):t<3600?n.lf("in {0} minute{0:s}",Math.floor(t/60)):t<7200?n.lf("in an hour"):t<86400?n.lf("in {0} hour{0:s}",Math.floor(t/60/60)):t<2592e3?n.lf("in {0} day{0:s}",Math.floor(t/60/60/24)):t<31536e3?n.lf("in {0} month{0:s}",Math.floor(t/60/60/24/30)):n.lf("in {0} year{0:s}",Math.floor(t/60/60/24/365))):t<0?n.lf("now"):t<10?n.lf("a few seconds ago"):t<60?n.lf("{0} second{0:s} ago",Math.floor(t)):t<120?n.lf("a minute ago"):t<3600?n.lf("{0} minute{0:s} ago",Math.floor(t/60)):t<7200?n.lf("an hour ago"):t<86400?n.lf("{0} hour{0:s} ago",Math.floor(t/60/60)):t<2592e3?n.lf("{0} day{0:s} ago",Math.floor(t/60/60/24)):t<31536e3?n.lf("{0} month{0:s} ago",Math.floor(t/60/60/24/30)):n.lf("{0} year{0:s} ago",Math.floor(t/60/60/24/365))},n.unicodeToChar=function(e){return e.replace(/\\u([\d\w]{4})/gi,(function(e,t){return String.fromCharCode(parseInt(t,16))}))},n.escapeForRegex=function(e){return null==e?void 0:e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},n.stripUrlProtocol=function(e){return null==e?void 0:e.replace(/.*?:\/\//g,"")},n.normalizePath=d,n.pathJoin=function(e,t){if(d(e),d(t),e||t)return e?t?("/"!==e.charAt(e.length-1)&&(e+="/"),"/"==t.charAt(0)&&(t=t.substring(1)),e+t):e:t},n.isNodeJS="undefined"==typeof window,n.requestAsync=h,n.httpGetTextAsync=function(e){return h({url:e}).then((e=>e.text))},n.httpGetJsonAsync=function(e){return h({url:e}).then((e=>e.json))},n.httpPostJsonAsync=function(e,t){return h({url:e,data:t||{}}).then((e=>e.json))},n.stringToUint8Array=function(e){let t=e.length,n=new Uint8Array(t);for(let i=0;i<t;++i)n[i]=255&e.charCodeAt(i);return n},n.uint8ArrayToString=function(e){let t=e.length,n="";for(let i=0;i<t;++i)n+=String.fromCharCode(e[i]);return n},n.fromUTF8=function(e){if(!e)return"";let t="";for(let n=0;n<e.length;++n){let i=255&e.charCodeAt(n);t+=37==i||i>127?"%"+i.toString(16):e.charAt(n)}return decodeURIComponent(t)},n.toUTF8=p,n.toHex=function(e){let t="";for(let n=0;n<e.length;++n)t+=("0"+e[n].toString(16)).slice(-2);return t},n.fromHex=function(e){let t=new Uint8Array(e.length>>1);for(let n=0;n<e.length;n+=2)t[n>>1]=parseInt(e.slice(n,n+2),16);return t};n.PromiseQueue=class{constructor(){this.promises={}}enqueue(e,t){return new Promise(((n,i)=>{let s=this.promises[e];s||(s=this.promises[e]=[]),s.push((()=>t().finally((()=>{s.shift(),0==s.length?delete this.promises[e]:s[0]()})).then(n,i))),1==s.length&&s[0]()}))}};function f(){return Date.now()}function g(){let e=new Uint8Array(4);return n.getRandomBuf(e),new Uint32Array(e.buffer)[0]}function m(e,t,n,i){function s(s){pxt.debug(`downloading translations for ${e} ${t} ${n||""}`);let r=pxt.BrowserUtils.isLocalHost()||pxt.webConfig.isStatic?"https://makecode.com/api/":"",a=`${r}translations?lang=${encodeURIComponent(e)}&filename=${encodeURIComponent(t)}&approved=true`;n&&(a+="&branch="+encodeURIComponent(n));const o={};return i&&!pxt.Cloud.useCdnApi()&&(o["If-None-Match"]=i),(r?h:pxt.Cloud.apiRequestWithCdnAsync)({url:a,headers:o}).then((r=>304==r.statusCode||200==r.statusCode?(i=r.headers.etag||"",pxt.BrowserUtils.translationDbAsync().then((a=>a.setAsync(e,t,n,i,r.json||s))).then((()=>r.json||s))):r.json),(e=>{console.log(`failed to load translations from ${a}`)}))}return pxt.BrowserUtils.translationDbAsync().then((i=>i.getAsync(e,t,n))).then((e=>{if(e){i=e.etag;return(Date.now()-e.time)/1e3>300&&s(e.strings),e.strings}return s()}))}function b(e){let[t,i]=n.normalizeLanguageCode(e),s=pxt.appTarget.appTheme;if(s&&s.availableLocales){if(s.availableLocales.indexOf(t)>-1)return!0;if(i&&s.availableLocales.indexOf(i)>-1)return!0}return!1}let y;function v(e,i,s,r,a,o,l){if(l=l||y.Editor,"en-US"===(s=n.normalizeLanguageCode(s)[0])||"en"===s)return Promise.resolve(void 0);let c,u,d=`${s}/${o}/${l}`;if(n.translationsCache()[d])return Promise.resolve(n.translationsCache()[d]);switch(l){case y.Editor:c=[{branch:r,staticName:"strings.json",path:"strings.json"},{branch:a,staticName:"target-strings.json",path:e+"/target-strings.json"}];break;case y.Sim:c=[{branch:a,staticName:"sim-strings.json",path:e+"/sim-strings.json"}];break;case y.Apis:c=[{branch:a,staticName:"bundled-strings.json",path:e+"/bundled-strings.json"}];break;case y.SkillMap:c=[{branch:a,staticName:"skillmap-strings.json",path:"/skillmap-strings.json"}]}function h(e){e&&(u||(u={}),Object.keys(e).filter((t=>!!e[t])).forEach((t=>u[t]=e[t])))}if(o){let o=0;return t.U.promiseMapAllSeries(c,(e=>m(s,e.path,e.branch).then(h,(e=>{console.log(e.message),++o})))).then((()=>(o&&(n.translationsCache()[d]=u),o!==c.length&&u?Promise.resolve(u):(pxt.tickEvent("translations.livetranslationsfailed"),v(e,i,s,r,a,!1,l)))))}return Promise.all(c.map((e=>n.httpGetJsonAsync(`${i}locales/${s}/${e.staticName}`).catch((e=>{}))))).then((e=>{let t={};e.forEach((e=>pxt.Util.jsonMergeFrom(t,e))),Object.keys(t).length&&(u=t,n.translationsCache()[d]=u)}),(e=>{console.error("failed to load localizations")})).then((()=>u))}function w(e){const t={};for(const n of Object.keys(e))t[n]=k(e[n]);return t}function k(e){var t;return{attributes:Object.assign({},e.attributes),parameters:null===(t=e.parameters)||void 0===t?void 0:t.map(A),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 A(e){var n,i;return{name:e.name,description:e.description,type:e.type,pyTypeString:e.pyTypeString,initializer:e.initializer,default:e.default,properties:null===(n=e.properties)||void 0===n?void 0:n.map(x),handlerParameters:null===(i=e.handlerParameters)||void 0===i?void 0:i.map(x),options:e.options?t.U.clone(e.options):void 0,isEnum:e.isEnum}}function x(e){return{name:e.name,type:e.type}}n.PromiseBuffer=class{constructor(){this.waiting=[],this.available=[]}drain(){for(let e of this.waiting)e(new Error("Promise Buffer Reset"));this.waiting=[],this.available=[]}pushError(e){this.push(e)}push(e){let t=this.waiting.shift();t?t(e):this.available.push(e)}shiftAsync(e=0){if(this.available.length>0){let e=this.available.shift();return e instanceof Error?Promise.reject(e):Promise.resolve(e)}return new Promise(((n,i)=>{let s=e=>{e instanceof Error?i(e):n(e)};this.waiting.push(s),e>0&&t.U.delay(e).then((()=>{let e=this.waiting.indexOf(s);e>=0&&(this.waiting.splice(e,1),i(new Error("Timeout")))}))}))}},n.now=f,n.nowSeconds=function(){return Math.round(f()/1e3)},n.timeout=function(e){return new Promise((t=>setTimeout((()=>t()),e)))},n.cpuUs=()=>{const e="undefined"!=typeof performance?performance.now.bind(performance)||performance.moznow.bind(performance)||performance.msNow.bind(performance)||performance.webkitNow.bind(performance)||performance.oNow.bind(performance):Date.now;return n.cpuUs=()=>1e3*e(),n.cpuUs()},n.getMime=function(e){let t=/\.([a-zA-Z0-9]+)$/.exec(e);if(!t)return"application/octet-stream";switch(t[1].toLowerCase()){case"txt":return"text/plain";case"html":case"htm":return"text/html";case"css":return"text/css";case"js":return"application/javascript";case"jpg":case"jpeg":return"image/jpeg";case"png":return"image/png";case"ico":return"image/x-icon";case"manifest":return"text/cache-manifest";case"webmanifest":return"application/manifest+json";case"json":return"application/json";case"svg":return"image/svg+xml";case"eot":return"application/vnd.ms-fontobject";case"ttf":return"font/ttf";case"woff":return"application/font-woff";case"woff2":return"application/font-woff2";case"md":return"text/markdown";case"xml":return"application/xml";case"m4a":return"audio/m4a";case"mp3":return"audio/mp3";default:return"application/octet-stream"}},n.randomUint32=g,n.guidGen=function(){function e(){return(65536|g()).toString(16).slice(-4)}return e()+e()+"-"+e()+"-4"+e().slice(-3)+"-"+e()+"-"+e()+e()+e()},n.downloadLiveTranslationsAsync=m,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=b,n.updateLocalizationAsync=function(t){const{targetId:i,baseUrl:s,pxtBranch:r,targetBranch:a,force:o}=t;let{code:l}=t;if(l=n.normalizeLanguageCode(l)[0],"en-US"===l&&(l="en"),l===n.userLanguage()||!b(l)&&!o)return pxt.debug(`loc: ${l} (using built-in)`),Promise.resolve();pxt.debug(`loc: ${l}`);const c=pxt.Util.liveLocalizationEnabled();return v(i,s,l,r,a,c,e.pxtc.Util.TranslationsKind.Editor).then((t=>(t&&(n.setUserLanguage(l),n.setLocalizedStrings(t)),e.pxtc.Util.downloadTranslationsAsync(i,s,l,r,a,c,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={},i=null,s=null){const r="--------------------------0461489f461126c5";let a="";Object.keys(t).forEach((e=>{return n=e,i=t[e],a+=r+"\r\n",a+='Content-Disposition: form-data; name="'+n+'"\r\n\r\n',void(a+=i+"\r\n");var n,i})),i&&function(e,t){const n=e.split("/").reverse()[0];a+=r+"\r\n",a+='Content-Disposition: form-data; name="files['+e+']"; filename="'+n+'"\r\n',a+="\r\n",a+=t+"\r\n"}(i,s),a+=r+"--\r\n";const o={url:e,method:"POST",headers:{"Content-Type":"multipart/form-data; boundary="+r.slice(2)},data:a};return n.httpRequestCoreAsync(o)},n.toDataUri=function(e,n){return/^https?:/i.test(e)||/^data:/i.test(e)?e:(n||/^<svg/i.test(e)&&(n="image/svg+xml"),/xml|svg/.test(n)?`data:${n},${encodeURIComponent(e)}`:`data:${n||"image/png"};base64,${t.encodeBase64(p(e))}`)},n.imageMagic=1496611453,n.imageHeaderSize=36,n.encodeBlobAsync=function(e,t){const i=n.imageHeaderSize+t.length,s=3*(e.width*e.height-1);let r=1;for(;r<4&&!(s*r>=8*i);)r++;let a=s*r>>3,o=i-a,l=0,c=e.width*e.height*4;if(o>0){const t=3*e.width;l=Math.ceil(o/t);const n=document.createElement("canvas");n.width=e.width,n.height=e.height+l;n.getContext("2d").drawImage(e,0,0),e=n}let u=pxt.HF2.encodeU32LE([n.imageMagic,t.length,l,0,0,0,0,0,0]);function d(e,t,n,i){let s=0,r=0,a=i[r++];const o=(1<<n)-1;let l=!0;for(;l;){let c=a>>s&o,u=8-s;if(u<=n){if(r>=i.length){if(0==u)break;l=!1}a=i[r++],c|=a<<u&o,s=n-u}else s+=n;e[t]=255&(e[t]&~o|c),3==(3&++t)&&(e[t++]=255)}return t}pxt.Util.assert(u.length==n.imageHeaderSize);const h=e.getContext("2d"),p=h.getImageData(0,0,e.width,e.height);d(p.data,0,1,[r]);let f=4;if(f=d(p.data,f,r,u),pxt.Util.assert(0==(3&f)),0==l)f=d(p.data,f,r,t);else{let e=a-u.length;f=d(p.data,f,r,t.slice(0,e)),f=d(p.data,c,8,t.slice(e))}for(f|=3;f<p.data.length;)p.data[f]=255,f+=4;return h.putImageData(p,0,0),e},n.decodeBlobAsync=function(e){return pxt.BrowserUtils.loadCanvasAsync(e).then((e=>{const t=e.getContext("2d").getImageData(0,0,e.width,e.height).data,i=1&t[0]|(1&t[1])<<1|(1&t[2])<<2;if(i>5||0==i)return Promise.reject(new Error(n.lf("Invalid encoded PNG format")));function s(e,n,i){let s=0,r=0,a=0;const o=(1<<n)-1;for(;r<i.length;)a|=(t[e++]&o)<<s,3==(3&e)&&e++,s+=n,s>=8&&(i[r++]=255&a,a>>=8,s-=8);return e}const r=new Uint8Array(pxt.Util.imageHeaderSize);let a=s(4,i,r);const o=pxt.HF2.decodeU32LE(r);if(o[0]!=pxt.Util.imageMagic)return Promise.reject(new Error(n.lf("Invalid magic in encoded PNG")));const l=new Uint8Array(o[1]),c=o[2];if(c>0){const t=(e.height-c)*e.width,n=new Uint8Array((3*(t-1)*i>>3)-pxt.Util.imageHeaderSize);s(a,i,n),l.set(n);const r=new Uint8Array(l.length-n.length);s(4*t,8,r),l.set(r,n.length)}else s(a,i,l);return l}))},n.parseQueryString=function(e){let t={};return e.replace(/\+/g," ").replace(/([^#?&=]+)=([^#?&=]*)/g,((e,n,i)=>(t[decodeURIComponent(n)]=decodeURIComponent(i),""))),t},n.stringifyQueryString=function(e,t){for(let n of Object.keys(t))e.indexOf("?")>=0?e+="&":e+="?",e+=encodeURIComponent(n)+"="+encodeURIComponent(t[n]);return e},n.cloneTargetBundle=function(e){const t=(e=Object.assign({},e)).apiInfo;delete e.apiInfo;const i=e.bundleddirs;delete e.bundleddirs;const s=e.bundledpkgs;delete e.bundledpkgs;const r=e.tutorialInfo;delete e.tutorialInfo;const a=n.clone(e);if(t){a.apiInfo={};for(const e of Object.keys(t)){const n=t[e].apis;a.apiInfo[e]={sha:t[e].sha,apis:{jres:Object.assign({},n.jres),byQName:w(n.byQName)}}}}if(i&&(a.bundleddirs=[...i]),s){a.bundledpkgs={};for(const e of Object.keys(s))a.bundledpkgs[e]=Object.assign({},s[e])}if(r){a.tutorialInfo={};for(const e of Object.keys(r)){const t=r[e];a.tutorialInfo[e]={hash:t.hash,usedBlocks:Object.assign({},t.usedBlocks),snippetBlocks:Object.assign({},t.snippetBlocks)}}}return a},n.cloneApis=w,n.cloneSymbolInfo=k,n.toUTF8Array=function(e){return(new TextEncoder).encode(e)},n.fromUTF8Array=function(e){return(new TextDecoder).decode(e)}}(t.Util||(t.Util={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){!function(t){e.Util.httpRequestCoreAsync=function(t){return new Promise(((n,i)=>{let s,r=!1,a=e.Util.clone(t.headers)||{};s=new XMLHttpRequest,t.responseArrayBuffer&&(s.responseType="arraybuffer"),t.withCredentials&&(s.withCredentials=!0),s.onreadystatechange=()=>{if(!r&&4==s.readyState){r=!0;let e={statusCode:s.status,headers:{},buffer:s.responseBody||s.response,text:t.responseArrayBuffer?void 0:s.responseText};s.getAllResponseHeaders().split(/\r?\n/).forEach((t=>{let n=/^\s*([^:]+): (.*)/.exec(t);n&&(e.headers[n[1].toLowerCase()]=n[2])})),n(e)}};let o,l=t.data,c=t.method||(null==l?"GET":"POST");null==l?o=null:l instanceof Uint8Array?o=l:"object"==typeof l?(o=JSON.stringify(l),a["content-type"]="application/json; charset=utf8"):"string"==typeof l?o=l:e.Util.oops("bad data"),s.open(c,t.url),Object.keys(a).forEach((e=>{s.setRequestHeader(e,a[e])})),null==o?s.send():s.send(o)}))},e.Util.sha256=a,e.Util.getRandomBuf=e=>{if(window.crypto)window.crypto.getRandomValues(e);else for(let t=0;t<e.length;++t)e[t]=Math.floor(255*Math.random())};const n=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function i(e,t){return e>>>t|e<<32-t}function s(t,s){e.Util.assert(8==t.length),e.Util.assert(64==s.length);for(let e=16;e<64;++e){let t=i(s[e-15],7)^i(s[e-15],18)^s[e-15]>>>3,n=i(s[e-2],17)^i(s[e-2],19)^s[e-2]>>>10;s[e]=s[e-16]+t+s[e-7]+n|0}let r=t[0],a=t[1],o=t[2],l=t[3],c=t[4],u=t[5],d=t[6],h=t[7];for(let e=0;e<64;++e){let t=h+(i(c,6)^i(c,11)^i(c,25))+(c&u^~c&d)+n[e]+s[e]|0,p=r&a^r&o^a&o;h=d,d=u,u=c,c=l+t|0,l=o,o=a,a=r,r=t+((i(r,2)^i(r,13)^i(r,22))+p|0)|0}t[0]+=r,t[1]+=a,t[2]+=o,t[3]+=l,t[4]+=c,t[5]+=u,t[6]+=d,t[7]+=h}function r(e){let t=new Uint32Array(8);t[0]=1779033703,t[1]=3144134277,t[2]=1013904242,t[3]=2773480762,t[4]=1359893119,t[5]=2600822924,t[6]=528734635,t[7]=1541459225;let n=new Uint32Array(64);function i(e){let i=e.length-63;for(let r=0;r<i;r+=64){for(let t=0;t<16;t++){let i=(t<<2)+r;n[t]=e[i]<<24|e[i+1]<<16|e[i+2]<<8|e[i+3]}s(t,n)}}i(e);let r=64-(e.length+9)%64;64==r&&(r=0);let a=e.length-e.length%64,o=new Uint8Array(e.length-a+1+r+8),l=0;for(;a<e.length;)o[l++]=e[a++];for(o[l++]=128;r-- >0;)o[l++]=0;let c=8*e.length;for(l=o.length;c>0;)o[--l]=255&c,c>>=8;i(o);let u="";for(let e=0;e<t.length;++e)u+=("000000000"+t[e].toString(16)).slice(-8);return u.toLowerCase()}function a(t){pxt.perf.measureStart("sha256buffer");const n=r(e.Util.toUTF8Array(t));return pxt.perf.measureEnd("sha256buffer"),n}t.sha256buffer=r,t.sha256string=a}(e.BrowserImpl||(e.BrowserImpl={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){!function(t){const n={add:(e,t,n)=>{if("object"!=typeof e)throw new Error("jsonPatch: expected object type");if(t in e)throw new Error(`jsonPatch: object already contains key ${t}`);e[t]=n},replace:(e,t,n)=>{if("object"!=typeof e)throw new Error("jsonPatch: expected object type");e[t]=n},remove:(e,t)=>{if("object"!=typeof e)throw new Error("jsonPatch: expected object type");delete e[t]}},i={add:(e,t,n)=>{if(!Array.isArray(e))throw new Error("jsonPatch: expected array type");if(t in e)throw new Error(`jsonPatch: key ${t} already exists in array`);"number"!=typeof t||t!==Math.floor(t)?e[t]=n:e.splice(t,0,n)},replace:(e,t,n)=>{if(!Array.isArray(e))throw new Error("jsonPatch: expected array type");"number"!=typeof t||t!==Math.floor(t)?e[t]=n:e.splice(t,1,n)},remove:(e,t)=>{if(!Array.isArray(e))throw new Error("jsonPatch: expected array type");"number"!=typeof t||t!==Math.floor(t)?delete e[t]:e.splice(t,1)}};t.diff=function(e,t){const n={add:[],remove:[],replace:[]};function i(e,t){if(!Array.isArray(e))return t;const n=Number.parseFloat(t);return Number.isNaN(n)?t:n}return function e(t,s,r){if(!Object.is(t,s)){s=s||{},t=t||{};for(let e of Object.keys(t))if(!(e in s)){const s=i(t,e);n.remove.push({op:"remove",path:r.concat(s)})}for(const a of Object.keys(s)){const o=t[a],l=s[a],c=i(s,a);c in t?"object"!=typeof o&&"object"!=typeof l&&o!==l||typeof o!=typeof l||Array.isArray(o)!==Array.isArray(l)?n.replace.push({op:"replace",path:r.concat(c),value:l}):e(o,l,r.concat(c)):void 0!==s[c]&&(r.length&&n.add.push({op:"add",path:r,value:Array.isArray(s)?[]:{}}),n.add.push({op:"add",path:r.concat(c),value:l}))}}}(e,t,[]),[...n.remove.reverse(),...n.replace,...n.add.sort(((e,t)=>e.path.length-t.path.length))]},t.patchInPlace=function(e,t){if(!e||"object"!=typeof e)throw new Error("jsonPatch: Must be an object or an array.");for(const s of t){const t=s.path.slice(),r=t.pop();if(null==r)throw new Error("jsonPatch: missing last key");let a=e,o=t.shift();for(;null!=o;){if(!(o in a))throw new Error(`jsonPatch: missing parent element ${o}`);a=a[o],o=t.shift()}if(Array.isArray(a)&&"number"!=typeof r)throw new Error("jsonPatch: expected numeric index for array object");const l=Array.isArray(a)?i:n;"remove"===s.op?l.remove(a,r):"add"!==s.op||r in a?"replace"===s.op&&l.replace(a,r,s.value):l.add(a,r,s.value)}},t.opsAreEqual=function(t,n){return t.op===n.op&&e.U.arrayEquals(t.path,n.path)}}(e.jsonPatch||(e.jsonPatch={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){!function(t){!function(t){function n(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){const i=Array.isArray(e),s=Array.isArray(t);if(i&&s){if(e.length!==t.length)return!1;for(let i=0;i<e.length;++i)if(!n(e[i],t[i]))return!1;return!0}if(i!==s)return!1;const r=Object.keys(e);if(r.length!==Object.keys(t).length)return!1;for(const i of r){if(!t.hasOwnProperty(i))return!1;if(!n(e[i],t[i]))return!1}return!0}return e!=e&&t!=t}t.diffTests=function(){const t=[{comment:"test 1",obja:{a:4,b:5},objb:{a:3,b:5},expected:[{op:"replace",path:["a"],value:3}]},{comment:"test 2",obja:{a:3,b:5},objb:{a:4,c:5},expected:[{op:"remove",path:["b"]},{op:"replace",path:["a"],value:4},{op:"add",path:["c"],value:5}]},{comment:"test 3",obja:{a:4,b:[1,2,3]},objb:{a:3,b:[1,2,4]},expected:[{op:"replace",path:["a"],value:3},{op:"replace",path:["b",2],value:4}]},{comment:"test 4",obja:{a:3,b:[1,2,4]},objb:{a:3,b:[1,2,4,5]},expected:[{op:"add",path:["b"],value:[]},{op:"add",path:["b",3],value:5}]},{comment:"test 5",obja:{a:4,b:{c:3}},objb:{a:4,b:{c:4}},expected:[{op:"replace",path:["b","c"],value:4}]},{comment:"test 6",obja:{a:4,b:{c:4}},objb:{a:5,b:{d:4}},expected:[{op:"remove",path:["b","c"]},{op:"replace",path:["a"],value:5},{op:"add",path:["b"],value:{}},{op:"add",path:["b","d"],value:4}]},{comment:"test 7",obja:{a:4,b:[2,"foo"]},objb:{a:4,b:[2,"foo",["this","that"]]},expected:[{op:"add",path:["b"],value:[]},{op:"add",path:["b",2],value:["this","that"]}]}];for(const i of t){console.log(i.comment);const t=e.pxtc.jsonPatch.diff(i.obja,i.objb);n(t,i.expected)?console.log("succeeded"):(console.error("FAILED"),console.log("got",t),console.log("exp",i.expected))}},t.patchTests=function(){const t=[{comment:"test 1",obj:{a:"foo",b:[4,11]},patches:[{op:"remove",path:["b"]},{op:"replace",path:["a"],value:4},{op:"add",path:["c"],value:5}],expected:{a:4,c:5}},{comment:"test 2",obj:{a:4,b:[1,2,3]},patches:[{op:"replace",path:["a"],value:3},{op:"replace",path:["b",2],value:4},{op:"add",path:["b",3],value:9}],expected:{a:3,b:[1,2,4,9]}},{comment:"test 3",obj:{a:4,b:{c:3}},patches:[{op:"replace",path:["a"],value:5},{op:"remove",path:["b","c"]},{op:"add",path:["b","d"],value:4}],expected:{a:5,b:{d:4}}},{comment:"test 4",obj:{a:4},patches:[{op:"add",path:["b"],value:[]},{op:"add",path:["b",0],value:"foo"},{op:"add",path:["b",1],value:"bar"}],expected:{a:4,b:["foo","bar"]},validate:e=>e.b&&e.b.forEach}];for(const i of t){console.log(i.comment),e.pxtc.jsonPatch.patchInPlace(i.obj,i.patches);!n(i.obj,i.expected)||!i.validate||i.validate(i.obj)?console.log("succeeded"):i.expected&&(console.error("FAILED"),console.log("got",i.obj),console.log("exp",i.expected))}}}(t.tests||(t.tests={}))}(t.jsonPatch||(t.jsonPatch={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){e.perf||(e.perf={})}(pxt||(pxt={})),pxt.perf.report||(pxt.perf.report=()=>{}),pxt.perf.recordMilestone||(pxt.perf.recordMilestone=()=>{}),pxt.perf.measureStart||(pxt.perf.measureStart=()=>{}),pxt.perf.measureEnd||(pxt.perf.measureEnd=()=>{}),function(e){let t;e.U=pxtc.Util,e.Util=pxtc.Util;let n,i,s,r={};function a(n,i){/^csv-/.test(n)?e.setAppTargetVariant(n.replace(/^csv-*/,"")):e.appTarget&&(r[n]=i,e.U.jsonCopyFrom(e.appTarget.compile.switches,r),e.U.jsonCopyFrom(t.compile.switches,r))}function o(){let t=e.appTarget.compile;t||(t=e.appTarget.compile={isNative:!1,hasHex:!1,switches:{}}),t.hasHex&&(t.nativeType||(t.nativeType=pxtc.NATIVE_TYPE_THUMB)),t.switches||(t.switches={}),t.nativeType==pxtc.NATIVE_TYPE_VM&&(t.sourceMap=!0),e.U.jsonCopyFrom(t.switches,r),t.jsRefCounting=!1,t.useUF2||t.useELF||null!=t.noSourceInFlash||(t.noSourceInFlash=!0),void 0===t.utf8&&(t.utf8=!0),e.appTarget.appTheme||(e.appTarget.appTheme={}),e.appTarget.appTheme.embedUrl||(e.appTarget.appTheme.embedUrl=e.appTarget.appTheme.homeUrl);let n=e.appTarget.compileService;n&&n.yottaTarget&&!n.yottaBinary&&(n.yottaBinary="pxt-microbit-app-combined.hex");const i=e.appTarget.appTheme;i&&Object.keys(i).filter((e=>/(logo|hero)$/i.test(e)&&/^@cdnUrl@/.test(i[e]))).forEach((t=>i[t]=e.BrowserUtils.patchCdn(i[t])));const s=e.appTarget.simulator;if(s&&s.boardDefinition&&s.boardDefinition.visual){let t=s.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],i=JSON.parse(n[e.CONFIG_NAME]);i.icon&&(i.icon=e.BrowserUtils.patchCdn(i.icon)),n[e.CONFIG_NAME]=e.Package.stringifyConfig(i)})),"undefined"!=typeof window){const t={"lockededitor=1":{appTheme:{lockedEditor:!0}},"hidemenu=1":{appTheme:{hideMenuBar:!0}}};e.appTarget.queryVariants&&e.Util.jsonCopyFrom(t,e.appTarget.queryVariants);const n=window.location.href;Object.keys(t).forEach((i=>{if(new RegExp(i,"i").exec(n)){let n=t[i];n&&e.U.jsonMergeFrom(e.appTarget,n)}}))}}function l(n=!1){e.perf.measureStart("reloadAppTargetVariant");const i=n?"":JSON.stringify(e.appTarget);if(e.appTarget=e.U.cloneTargetBundle(t),e.appTargetVariant){const t=e.appTarget.variants&&e.appTarget.variants[e.appTargetVariant];t?e.U.jsonMergeFrom(e.appTarget,t):e.U.userError(lf("Variant '{0}' not defined in pxtarget.json",e.appTargetVariant))}o(),!n&&e.onAppTargetChanged&&i!=JSON.stringify(e.appTarget)&&e.onAppTargetChanged(),e.perf.measureEnd("reloadAppTargetVariant")}function c(){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 s||(s=e.Cloud.downloadTargetConfigAsync().then((e=>e||{}),(e=>({})))),s}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||{},o(),t=e.U.cloneTargetBundle(e.appTarget)},e.setBundledApiInfo=function(e){for(const t of Object.keys(e)){const n=e[t].apis.byQName;for(const e of Object.keys(n)){const t=n[e],i=e.lastIndexOf("."),s=t.pyQName,r=n[e]={kind:Math.abs(t.kind||7),qName:e,namespace:e.slice(0,i<0?0:i),name:e.slice(i+1),pyQName:s,pyName:s?s.slice(s.lastIndexOf(".")+1):void 0,fileName:"",attributes:t.attributes||{},retType:t.retType||"void",parameters:t.parameters?t.parameters.map((e=>({name:e.name,description:e.description||"",type:e.type||"number",initializer:e.initializer,default:e.default,options:e.options||{},isEnum:!!e.isEnum,handlerParameters:e.handlerParameters}))):null,extendsTypes:t.extendsTypes,snippet:t.kind&&t.kind<0?null:void 0,isInstance:!!t.isInstance,isReadOnly:!!t.isReadOnly},a=r.attributes;a.paramDefl||(a.paramDefl={}),a.callingConvention||(a.callingConvention=0),a.paramHelp||(a.paramHelp={}),a.jsDoc||(a.jsDoc=""),a._name=r.name.replace(/@.*/,"")}}n=e},e.getBundledApiInfo=function(){return n},e.savedAppTheme=function(){return t?t.appTheme:void 0},e.setCompileSwitch=a,e.setCompileSwitches=function(e){if(e)for(let t of e.split(/[\s,;:]+/))t&&("-"==t[0]?a(t.slice(1),!1):a(t,!0))},e.bundledSvg=function(t){if(!t)return;let n=i&&i[t];if(n)return n;if(!e.appTarget.simulator||!e.appTarget.simulator.dynamicBoardDefinition)return;i||(i={});const s=e.appTarget.bundledpkgs[t];if(!s)return;if(JSON.parse(s["pxt.json"]).core&&s["board.json"]){const n=JSON.parse(s["board.json"]);if(n&&n.visual&&n.visual.image){let r=n.visual.image;/^pkg:\/\//.test(r)&&(r=s[r.slice(6)]),i[t]=`data:image/svg+xml;base64,${ts.pxtc.encodeBase64(e.Util.toUTF8(r))}`}}return i[t]},e.reloadAppTargetVariant=l,e.setAppTargetVariant=function(t,n={}){e.debug(`app variant: ${t}`),(n.force||e.appTargetVariant!==t&&(e.appTargetVariant||t))&&(e.appTargetVariant=t,l(n.temporary))},e.setHwVariant=function(t,n){t=t.replace(/.*---/,""),/^[\w\-]+$/.test(t)?(e.hwVariant=t,e.hwName=n||t):(e.hwVariant=null,e.hwName=null),e.debug(`hwVariant: ${e.hwVariant} (${e.hwName})`)},e.hasHwVariants=function(){return!!e.appTarget.variants&&Object.keys(e.appTarget.bundledpkgs).some((e=>/^hw---/.test(e)))},e.getHwVariants=function(){return e.appTarget.variants?Object.keys(e.appTarget.bundledpkgs).filter((e=>/^hw---/.test(e))).map((t=>JSON.parse(e.appTarget.bundledpkgs[t][e.CONFIG_NAME]))).filter((t=>!!e.appTarget.appTheme.experimentalHw||!t.experimentalHw)):[]},e.options={},e.debug="undefined"!=typeof console&&console.debug?t=>{e.options.debug&&console.debug(t)}:()=>{},e.log="undefined"!=typeof console&&console.log?e=>{console.log(e)}:()=>{},e.reportException=function(e,t){if(console&&(console.error(e),t))try{console.log(t)}catch(e){}},e.reportError=function(t,n,i){if(console&&(console.error(`${t}: ${n}`),i))try{e.log(JSON.stringify(i,null,2))}catch(e){}},e.localWebConfig=c,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=c())},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 i;function s(){if(i={device_while:{name:e.Util.lf("a loop that repeats while the condition is true"),tooltip:e.Util.lf("Run the same sequence of actions while the condition is met."),url:"/blocks/loops/while",category:"loops",block:{message0:e.Util.lf("while %1"),appendField:e.Util.lf("{id:while}do")}},pxt_controls_for:{name:e.Util.lf("a loop that repeats the number of times you say"),tooltip:e.Util.lf("Have the variable '{0}' take on the values from 0 to the end number, counting by 1, and do the specified blocks."),url:"blocks/loops/for",category:"loops",block:{message0:e.Util.lf("for %1 from 0 to %2"),variable:e.Util.lf("{id:var}index"),appendField:e.Util.lf("{id:for}do")}},controls_simple_for:{name:e.Util.lf("a loop that repeats the number of times you say"),tooltip:e.Util.lf("Have the variable '{0}' take on the values from 0 to the end number, counting by 1, and do the specified blocks."),url:"blocks/loops/for",category:"loops",block:{message0:e.Util.lf("for %1 from 0 to %2"),variable:e.Util.lf("{id:var}index"),appendField:e.Util.lf("{id:for}do")}},pxt_controls_for_of:{name:e.Util.lf("a loop that repeats for each value in an array"),tooltip:e.Util.lf("Have the variable '{0}' take the value of each item in the array one by one, and do the specified blocks."),url:"blocks/loops/for-of",category:"loops",block:{message0:e.Util.lf("for element %1 of %2"),variable:e.Util.lf("{id:var}value"),appendField:e.Util.lf("{id:for_of}do")}},controls_for_of:{name:e.Util.lf("a loop that repeats for each value in an array"),tooltip:e.Util.lf("Have the variable '{0}' take the value of each item in the array one by one, and do the specified blocks."),url:"blocks/loops/for-of",category:"loops",block:{message0:e.Util.lf("for element %1 of %2"),variable:e.Util.lf("{id:var}value"),appendField:e.Util.lf("{id:for_of}do")}},math_op2:{name:e.Util.lf("minimum or maximum of 2 numbers"),tooltip:{min:e.Util.lf("smaller value of 2 numbers"),max:e.Util.lf("larger value of 2 numbers")},url:"/blocks/math",operators:{op:["min","max"]},category:"math"},math_op3:{name:e.Util.lf("absolute number"),tooltip:e.Util.lf("absolute value of a number"),url:"/reference/math",category:"math",block:{message0:e.Util.lf("absolute of %1")}},math_number:{name:e.Util.lf("{id:block}number"),url:"/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:{}}},i[pxtc.ON_START_TYPE]={name:e.Util.lf("on start event"),tooltip:e.Util.lf("Run code when the program starts"),url:"/blocks/on-start",category:"loops",block:{message0:e.Util.lf("on start %1 %2")}},i[pxtc.PAUSE_UNTIL_TYPE]={name:e.Util.lf("pause until"),tooltip:e.Util.lf("Pause execution of code until the given boolean expression is true"),url:"/blocks/pause-until",category:"loops",block:{message0:e.Util.lf("pause until %1")}},i[pxtc.TS_BREAK_TYPE]={name:e.Util.lf("break"),tooltip:e.Util.lf("Break out of the current loop or switch"),url:"/blocks/loops/break",category:"loops",block:{message0:e.Util.lf("break")}},i[pxtc.TS_CONTINUE_TYPE]={name:e.Util.lf("continue"),tooltip:e.Util.lf("Skip current iteration and continues with the next iteration in the loop"),url:"/blocks/loops/continue",category:"loops",block:{message0:e.Util.lf("continue")}},e.Util.isTranslationMode()){const t=Blockly.Msg;e.Util.values(i).filter((e=>e.block)).forEach((n=>{const i=Object.keys(n.block);n.translationIds=e.Util.values(n.block),i.forEach((i=>e.crowdin.inContextLoadAsync(n.block[i]).then((e=>{n.block[i]=e,/^[A-Z_]+$/.test(i)&&(t[i]=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 i=t.replace(/(?:^|[^\\])([%$])\s+/g,"$1");return i!=t&&(n(`block has extra spaces: ${t}`),t=i),i=(t=i).replace(/([%$]\w+)\s*=\s*(\w+)/,"$1=$2"),i!=t&&(n(`block has space between %name and = : ${t}`),t=i),i=i.replace(/\s*\|\s*/g,"|"),i},t.compileInfo=function(e){const i={parameters:[],actualNameToParam:{},definitionNameToParam:{},handlerArgs:[]},s=(1==e.kind||2==e.kind)&&!e.attributes.defaultInstance,r=!!e.attributes._def,a=r?e.attributes._def.parameters.slice(0):void 0,o=r?a.length:e.parameters?e.parameters.length:0,l=t.builtinFunctionInfo[e.qName];r&&e.attributes._expandedDef&&a.push(...e.attributes._expandedDef.parameters);const c={},u=a?a.filter((e=>!e.ref||(c[e.name]=e,!1))):[];if(s&&r&&a.length){const t=c.this||a[0],s=t.name;let r;(!t.shadowBlockId||"variables_get"===t.shadowBlockId)&&(r=t.varName||e.attributes.paramDefl[s]||e.attributes.paramDefl.this),i.thisParameter={actualName:n,definitionName:s,shadowBlockId:t.shadowBlockId,type:e.namespace,defaultValue:r,fieldEditor:d(s,n),fieldOptions:h(s,n),shadowOptions:p(s,n)}}if(e.parameters){let t=s&&!c.this?1:0;e.parameters.forEach(((e,n)=>{let s;if(c[e.name]?s=c[e.name]:t<u.length&&(s=u[t],++t),s||!r){let n;e.options&&e.options.min&&e.options.max&&(n={min:e.options.min.value,max:e.options.max.value});const r=s?s.name:l?l.params[t++]:e.name,c=s&&("variables_get"===s.shadowBlockId||"lists_create_with"==s.shadowBlockId);i.parameters.push({actualName:e.name,type:e.type,defaultValue:c&&s.varName||e.default,definitionName:r,shadowBlockId:s&&s.shadowBlockId,isOptional:!!a&&a.indexOf(s)>=o,fieldEditor:d(r,e.name),fieldOptions:h(r,e.name),shadowOptions:p(r,e.name),range:n})}e.handlerParameters&&e.handlerParameters.forEach((e=>{i.handlerArgs.push({name:e.name,type:e.type,inBlockDef:!!a&&a.some((t=>t.ref&&t.name===e.name))})}))}))}return i.parameters.forEach((e=>{i.actualNameToParam[e.actualName]=e,i.definitionNameToParam[e.definitionName]=e})),i;function d(t,n){return e.attributes.paramFieldEditor&&(e.attributes.paramFieldEditor[t]||e.attributes.paramFieldEditor[n])}function h(t,n){return e.attributes.paramFieldEditorOptions&&(e.attributes.paramFieldEditorOptions[t]||e.attributes.paramFieldEditorOptions[n])}function p(t,n){return e.attributes.paramShadowOptions&&(e.attributes.paramShadowOptions[t]||e.attributes.paramShadowOptions[n])}},t.hasHandler=function(e){return e.parameters&&e.parameters.some((e=>{var t,n;return"() => void"==e.type||"Action"==e.type||!!(null===(t=e.properties)||void 0===t?void 0:t.length)||!!(null===(n=e.handlerParameters)||void 0===n?void 0:n.length)}))},t.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 i=n[1];return i&&(i=i.trim()),{n:e,ni:t,pre:i,p:n[2]}}))},t.blockDefinitions=function(){return i||s(),i},t.getBlockDefinition=function(e){return i||s(),i[e]}}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(t){function n(){return"undefined"!=typeof navigator}function i(){return n()&&/(Win32|Win64|WOW64)/i.test(navigator.platform)}function s(){return n()&&/mobi/i.test(navigator.userAgent)}function r(){return n()&&/Mac/i.test(navigator.platform)}function a(){return!!navigator&&/Linux/i.test(navigator.platform)}function o(){return n()&&/arm/i.test(navigator.platform)}function l(){return n()&&/Edge/i.test(navigator.userAgent)}function c(){return n()&&/Trident/i.test(navigator.userAgent)}function u(){return!l()&&!c()&&!!navigator&&(/Chrome/i.test(navigator.userAgent)||/Chromium/i.test(navigator.userAgent))}function d(){return!u()&&!l()&&!!navigator&&/(Macintosh|Safari|iPod|iPhone|iPad)/i.test(navigator.userAgent)}function h(){return!d()&&!!navigator&&(/Firefox/i.test(navigator.userAgent)||/Seamonkey/i.test(navigator.userAgent))}function p(){return n()&&/Opera|OPR/i.test(navigator.userAgent)}function f(){return n()&&/Midori/i.test(navigator.userAgent)}function g(){return n()&&/Epiphany/i.test(navigator.userAgent)}function m(){return"undefined"!=typeof window&&("ontouchstart"in window||navigator&&navigator.maxTouchPoints>0)}function b(){return"undefined"!=typeof window&&!!window.pxtElectron}function y(){return"undefined"!=typeof window&&!!window.ipcRenderer}function v(){return b()||y()}function w(t){var n;try{return"undefined"!=typeof window&&/^http:\/\/(localhost|127\.0\.0\.1):\d+\//.test(window.location.href)&&(t||!/nolocalhost=1/.test(window.location.href))&&!(null===(n=null==e?void 0:e.webConfig)||void 0===n?void 0:n.isStatic)}catch(e){return!1}}function k(){return"undefined"!=typeof window&&!!window.PointerEvent}function A(){return i()?"windows":r()?"mac":a()&&o()?"rpi":a()?"linux":"unknown"}function x(){return l()?"edge":g()?"epiphany":f()?"midori":p()?"opera":c()?"ie":u()?"chrome":d()?"safari":h()?"firefox":"unknown"}function T(){if(!n())return null;let e=[];return p()&&(e=/(Opera|OPR)\/([0-9\.]+)/i.exec(navigator.userAgent)),g()?e=/Epiphany\/([0-9\.]+)/i.exec(navigator.userAgent):f()?e=/Midori\/([0-9\.]+)/i.exec(navigator.userAgent):d()?(e=/Version\/([0-9\.]+)/i.exec(navigator.userAgent),e||(e=/(Macintosh|iPod( touch)?|iPhone|iPad); (CPU|Intel).*?OS (X )?(\d+)/i.exec(navigator.userAgent))):e=u()?/(Chrome|Chromium)\/([0-9\.]+)/i.exec(navigator.userAgent):l()?/Edge\/([0-9\.]+)/i.exec(navigator.userAgent):c()?/(MSIE |rv:)([0-9\.]+)/i.exec(navigator.userAgent):/(Firefox|Seamonkey)\/([0-9\.]+)/i.exec(navigator.userAgent),e&&0!=e.length?e[e.length-1]:null}t.isIFrame=function(){try{return window&&window.self!==window.top}catch(e){return!0}},t.hasNavigator=n,t.hasWindow=function(){return"undefined"!=typeof window},t.isWindows=i,t.isWindows10=function(){return n()&&/(Win32|Win64|WOW64)/i.test(navigator.platform)&&/Windows NT 10/i.test(navigator.userAgent)},t.isMobile=s,t.isIOS=function(){return n()&&(/iPad|iPhone|iPod/.test(navigator.userAgent)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1)},t.isAndroid=function(){return n()&&/android/i.test(navigator.userAgent)},t.isMac=r,t.isLinux=a,t.isARM=o,t.isUwpEdge=function(){return"undefined"!=typeof window&&!!window.Windows},t.isEdge=l,t.isChromiumEdge=function(){return n()&&/Edg\//i.test(navigator.userAgent)},t.isIE=c,t.isChrome=u,t.isSafari=d,t.isFirefox=h,t.isOpera=p,t.isMidori=f,t.isEpiphany=g,t.isTouchEnabled=m,t.isPxtElectron=b,t.isIpcRenderer=y,t.isElectron=v,t.isWinRT=()=>!1,t.isLocalHost=w,t.isLocalHostDev=function(){return w()&&!v()},t.isSkillmapEditor=function(){try{return/skill(?:s?)Map=1/.test(window.location.href)}catch(e){return!1}},t.isTabletSize=function(){return(null===window||void 0===window?void 0:window.innerWidth)<e.BREAKPOINT_TABLET},t.isComputerSize=function(){return(null===window||void 0===window?void 0:window.innerWidth)>=e.BREAKPOINT_TABLET},t.noSharedLocalStorage=function(){try{return/nosharedlocalstorage/i.test(window.location.href)}catch(e){return!1}},t.useOldTutorialLayout=function(){try{return/tutorialview=old/.test(window.location.href)}catch(e){return!1}},t.hasPointerEvents=k,t.hasSaveAs=function(){return l()||c()||h()},t.os=A,t.browser=x,t.browserVersion=T;let E=!1;function C(){return s()&&d()&&!/downloadWindowOpen=0/i.test(window.location.href)}function I(t,n,i){const r=C(),a=T(),o=parseInt(a||"0");if(r)i?i.location.href=t:window.open(t,"_self");else if(e.BrowserUtils.isSafari()&&(o<10||0==a.indexOf("10.0")||s())){let n=document.getElementById("downloader");n||(e.debug("injecting downloader iframe"),n=document.createElement("iframe"),n.id="downloader",n.style.position="absolute",n.style.right="0",n.style.bottom="0",n.style.zIndex="-1",n.style.width="1px",n.style.height="1px",document.body.appendChild(n)),n.src=t}else if(/^data:/i.test(t)&&(e.BrowserUtils.isEdge()||e.BrowserUtils.isIE())){let i=atob(t.split(",")[1]),s=e.Util.stringToUint8Array(i),r=new Blob([s],{type:"img/png"});window.navigator.msSaveOrOpenBlob(r,n)}else{let e=window.document.createElement("a");"string"==typeof e.download?(e.href=t,e.download=n,document.body.appendChild(e),e.click(),document.body.removeChild(e)):document.location.href=t}}function U(t,n){let i="data";s()&&d()&&e.appTarget.appTheme.mobileSafariDownloadProtocol&&(i=e.appTarget.appTheme.mobileSafariDownloadProtocol);const r=/downloadProtocol=([a-z0-9:/?]+)/i.exec(window.location.href);r&&(i=r[1]);return i+":"+n+";base64,"+t}function S(t,n,i={}){var s;e.debug("trigger download");const{contentType:r="application/octet-stream",userContextWindow:a,onError:o,maintainObjectURL:l}=i,c=null===(s=window.URL)||void 0===s?void 0:s.createObjectURL,u=e.appTarget.appTheme.disableBlobObjectDownload;let d;try{if(c&&!u){const i=c(new Blob([e.Util.stringToUint8Array(atob(t))],{type:r}));I(i,n,a),l?d=i:window.setTimeout((()=>window.URL.revokeObjectURL(d)),0)}else d=U(t,n),I(d,n,a)}catch(t){o&&o(t),e.debug("saving failed")}return d}function N(e){const t=document.createElement("img");return new Promise(((n,i)=>{t.onload=()=>n(t),t.onerror=()=>n(void 0),t.crossOrigin="anonymous",t.src=e}))}t.isBrowserSupported=function(){var t,n;if(!navigator)return!0;if(/bot|crawler|spider|crawling/i.test(navigator.userAgent))return!0;const i=(null===(t=e.appTarget)||void 0===t?void 0:t.unsupportedBrowsers)||(null===(n=window.pxtTargetBundle)||void 0===n?void 0:n.unsupportedBrowsers);if(null==i?void 0:i.some((e=>e.id==x())))return!1;const s=T(),r=parseInt(s||"0"),c=u()&&r>=38,m=h()&&r>=31,b=l(),y=d()&&r>=9,v=p()&&u()&&r>=21;let w=c||m||b||y||v;const k=f()||a()&&o()&&g();return w=w&&!k,w=w||/anybrowser=(true|1)/.test(window.location.href),E||(e.log(`Browser: ${x()} ${s} on ${A()}`),w||e.tickEvent("browser.unsupported",{useragent:navigator.userAgent}),E=!0),w},t.devicePixelRatio=function(){if("undefined"==typeof window||!window.screen)return 1;const e=window.screen.systemXDPI,t=window.screen.logicalXDPI;return void 0!==e&&void 0!==t&&e>t?e/t:window&&void 0!==window.devicePixelRatio?window.devicePixelRatio:1},t.browserDownloadBinText=function(e,t,n){return S(ts.pxtc.encodeBase64(e),t,n)},t.browserDownloadText=function(t,n,i){return S(ts.pxtc.encodeBase64(e.Util.toUTF8(t)),n,i)},t.isBrowserDownloadInSameWindow=C,t.isBrowserDownloadWithinUserContext=function(){const e=T(),t=parseInt(e||"0");return s()&&d()&&t>=11||/downloadUserContext=1/i.test(window.location.href)},t.browserDownloadDataUri=I,t.browserDownloadUInt8Array=function(t,n,i){return S(ts.pxtc.encodeBase64(e.Util.uint8ArrayToString(t)),n,i)},t.toDownloadDataUri=U,t.browserDownloadBase64=S,t.loadImageAsync=N,t.loadCanvasAsync=function(e){return N(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 i=n.getContext("2d");return i.putImageData(e,0,0),i.imageSmoothingEnabled=!1,i.scale(t,t),i.drawImage(n,0,0),i.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 i=n.getContext("2d");return i.putImageData(e,0,0),i.imageSmoothingEnabled=!1,i.scale(t,t),i.drawImage(n,0,0),n.toDataURL("image/png")};const P=1e6;function _(t){if(/^https?:\/\//i.test(t))return t;const n=(window.MonacoPaths||{})[t];return n||(e.U.startsWith(t,e.webConfig.commitCdnUrl)?t:e.webConfig.commitCdnUrl+t)}t.encodeToPngAsync=function(t,n){const{width:i,height:s,pixelDensity:r=4,maxSize:a=P,text:o}=n||{};return new Promise(((n,l)=>{const c=new Image;c.onload=function(){const t=document.createElement("canvas"),l=t.getContext("2d");t.width=(i||c.width)*r,t.height=(s||c.height)*r,o&&(l.fillStyle="#fff",l.fillRect(0,0,t.width,t.height)),l.drawImage(c,0,0,i,s,0,0,t.width,t.height);let u=t.toDataURL("image/png");for(;u.length>a;)t.width=t.width/2>>0,t.height=t.height/2>>0,e.debug(`screenshot size ${u.length}b, shrinking to ${t.width}x${t.height}`),l.drawImage(c,0,0,i,s,0,0,t.width,t.height),u=t.toDataURL("image/png");if(o){e.lzmaCompressAsync(o).then((i=>{const s=e.Util.encodeBlobAsync(t,i);n(s.toDataURL("image/png"))}))}else n(u)},c.onerror=t=>{e.reportError("png","png rendering failed"),n(void 0)},c.src=t}))},t.resolveCdnUrl=_,t.loadStyleAsync=function(t,n){n&&(t="rtl"+t);const i="style-"+t;if(document.getElementById(i))return Promise.resolve();const s=_(t),r=e.Util.toArray(document.head.getElementsByTagName("link")).filter((e=>e.getAttribute("href")==s))[0];return r?(r.id||(r.id=i),Promise.resolve()):new Promise(((e,t)=>{const n=document.createElement("link");n.href=s,n.rel="stylesheet",n.type="text/css",n.id=i,n.addEventListener("load",(()=>e())),n.addEventListener("error",(e=>t(e))),document.head.appendChild(n)}))};let O,D,$,L={};function R(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 M(){const e=n()&&window.navigator;return e&&e.storage&&e.storage.estimate?e.storage.estimate():Promise.resolve({})}t.loadScriptAsync=function(t){const n=_(t);let i=L[n];return i||(i=L[n]=new Promise(((t,i)=>{e.debug(`script: loading ${n}`);const s=document.createElement("script");s.type="text/javascript",s.addEventListener("load",(()=>t())),s.addEventListener("error",(e=>{delete L[n],i(e)})),s.src=n,s.async=!0,document.body.appendChild(s)}))),i},t.loadAjaxAsync=function(e){return new Promise(((t,n)=>{let i=new XMLHttpRequest;i.onreadystatechange=function(){i.readyState==XMLHttpRequest.DONE&&(200==i.status?t(i.responseText):n(i.status))},i.open("GET",e,!0),i.send()}))},t.loadBlocklyAsync=function(){if(!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 i=t.filter((t=>e.Util.endsWith(t.getAttribute("href"),"blockly.css")))[0];if(i){const t=i.getAttribute("data-rtl");t&&(e.debug(`swapping to ${t}`),i.setAttribute("href",t),i.removeAttribute("data-rtl"))}}},t.changeHash=function(e,t){"#"!=e.charAt(0)&&(e="#"+e),t?window.location.hash=e:window.history.replaceState("","",e)},t.urlJoin=R,t.joinURLs=function(...e){let t;if(e)for(let n=0;n<e.length;n++)t=R(t,e[n]);return t},t.storageEstimateAsync=M,t.scheduleStorageCleanup=n()&&navigator.storage&&navigator.storage.estimate?ts.pxtc.Util.throttle((function(){M().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"),G()):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((()=>H())).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 j{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,i,s,r,a){this.translations[this.key(e,t,n)]={etag:i,time:s,strings:r,md:a}}setAsync(t,n,i,s,r,a){return this.set(t,n,i,s,e.Util.now(),r),Promise.resolve()}clearAsync(){return this.translations={},Promise.resolve()}}class F{constructor(e,t,n,i){this.name=e,this.version=t,this.upgradeHandler=n,this.quotaExceededHandler=i}throwIfNotOpened(){if(!this._db)throw new Error("Database not opened; call IDBWrapper.openAsync() first")}errorHandler(t,n,i){console.error(new Error(`${this.name} IDBWrapper error for ${n}: ${t.message}`)),i(t),"QuotaExceededError"==t.name&&(e.log("storage quota exceeded..."),e.tickEvent("storage.quotaexceedederror"),this.quotaExceededHandler&&this.quotaExceededHandler())}getObjectStore(e,t="readonly"){this.throwIfNotOpened();return this._db.transaction([e],t).objectStore(e)}static deleteDatabaseAsync(e){return new Promise(((t,n)=>{const i=(window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB).deleteDatabase(e);i.onsuccess=()=>t(),i.onerror=()=>n(i.error)}))}openAsync(){return new Promise(((e,t)=>{const n=(window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB).open(this.name,this.version);n.onsuccess=()=>{this._db=n.result,e()},n.onerror=()=>this.errorHandler(n.error,"open",t),n.onupgradeneeded=e=>this.upgradeHandler(e,n)}))}getAsync(e,t){return new Promise(((n,i)=>{const s=this.getObjectStore(e).get(t);s.onsuccess=()=>n(s.result),s.onerror=()=>this.errorHandler(s.error,"get",i)}))}getAllAsync(e){return new Promise(((t,n)=>{const i=this.getObjectStore(e).openCursor(),s=[];i.onsuccess=()=>{i.result?(s.push(i.result.value),i.result.continue()):t(s)},i.onerror=()=>this.errorHandler(i.error,"getAll",n)}))}setAsync(e,t){return new Promise(((n,i)=>{const s=this.getObjectStore(e,"readwrite");let r;r=void 0!==t.id&&null!==t.id?s.put(t):s.add(t),r.onsuccess=()=>n(),r.onerror=()=>this.errorHandler(r.error,"set",i)}))}deleteAsync(e,t){return new Promise(((n,i)=>{const s=this.getObjectStore(e,"readwrite").delete(t);s.onsuccess=()=>n(),s.onerror=()=>this.errorHandler(s.error,"delete",i)}))}deleteAllAsync(e){return new Promise(((t,n)=>{const i=this.getObjectStore(e,"readwrite").clear();i.onsuccess=()=>t(),i.onerror=()=>this.errorHandler(i.error,"deleteAll",n)}))}}t.IDBWrapper=F;class B{constructor(e){this.db=e,this.mem=new j}static dbName(){return`__pxt_translations_${e.appTarget.id||""}`}static createAsync(){function e(){const e=new F(B.dbName(),2,((e,t)=>{t.result.createObjectStore(B.TABLE,{keyPath:B.KEYPATH})}),(()=>{G().catch((e=>{}))}));return e.openAsync().then((()=>new B(e)))}return e().catch((t=>(console.log("db: failed to open database, try delete entire store..."),F.deleteDatabaseAsync(B.dbName()).then((()=>e())))))}getAsync(e,t,n){e=(e||"en-US").toLowerCase();const i=this.mem.key(e,t,n),s=this.mem.get(e,t,n);return s?Promise.resolve(s):this.db.getAsync(B.TABLE,i).then((i=>i?(this.mem.set(e,t,n,i.etag,i.time,i.strings),Promise.resolve(i)):Promise.resolve(void 0))).catch((e=>Promise.resolve(void 0)))}setAsync(n,i,s,r,a,o){n=(n||"en-US").toLowerCase();const l=this.mem.key(n,i,s);let c=e.Util.now();this.mem.set(n,i,s,r,c,a,o),a&&Object.keys(a).filter((e=>!a[e])).forEach((e=>delete a[e]));const u={id:l,etag:r,time:c,strings:a,md:o};return this.db.setAsync(B.TABLE,u).finally((()=>t.scheduleStorageCleanup())).catch((e=>(console.log(`db: set failed (${e.message}), recycling...`),this.clearAsync())))}clearAsync(){return this.db.deleteAllAsync(B.TABLE).then((()=>console.debug("db: all clean"))).catch((e=>{console.error("db: failed to delete all")}))}}function H(){return e.Util.isNodeJS?Promise.resolve(new j):(D||(D=B.createAsync().catch((()=>new j))),D)}function G(){function t(){const t=B.dbName();return F.deleteDatabaseAsync(t).then((()=>{D=void 0})).catch((n=>{e.log(`db: failed to delete ${t}`),D=void 0}))}return D?D.then((e=>e.clearAsync())).catch((e=>t().then())):t()}function z(t){const n=JSON.stringify(t)+e.appTarget.versions.pxt+"_"+e.appTarget.versions.target;return pxtc.U.sha256(n)}function V(e,t){return`${e}|${t||"master"}`}B.TABLE="files",B.KEYPATH="id",t.translationDbAsync=H,t.clearTranslationDbAsync=G,t.getTutorialCodeHash=z;class J{constructor(e){this.db=e}static dbName(){return`__pxt_tutorialinfo_${e.appTarget.id||""}`}static createAsync(){function t(){const t=new e.BrowserUtils.IDBWrapper(J.dbName(),2,((e,t)=>{t.result.createObjectStore(J.TABLE,{keyPath:J.KEYPATH})}),(()=>{e.BrowserUtils.IDBWrapper.deleteDatabaseAsync(J.dbName())}));return t.openAsync().then((()=>new J(t)))}return t().catch((n=>(console.log("db: failed to open tutorial info database, try delete entire store..."),e.BrowserUtils.IDBWrapper.deleteDatabaseAsync(J.dbName()).then((()=>t())))))}getAsync(t,n,i){const s=V(t,i),r=z(n);return this.db.getAsync(J.TABLE,s).then((t=>{if(t&&t.hash==r&&e.Util.now()-(t.time||0)<864e5)return t;this.db.deleteAsync(J.TABLE,s)}))}setAsync(t,n,i,s){e.perf.measureStart("tutorial info db setAsync");V(t,s);const r=z(i);return this.setWithHashAsync(t,n,r)}setWithHashAsync(t,n,i,s){e.perf.measureStart("tutorial info db setAsync");const r=V(t,s),a={};Object.keys(n).forEach((e=>{Object.keys(n[e]).forEach((t=>{a[t]=n[e][t]}))}));const o={id:r,time:e.Util.now(),hash:i,snippets:n,blocks:a};return this.db.setAsync(J.TABLE,o).then((()=>{e.perf.measureEnd("tutorial info db setAsync")}))}clearAsync(){return this.db.deleteAllAsync(J.TABLE).then((()=>console.debug("db: all clean"))).catch((e=>{console.error("db: failed to delete all")}))}}function q(e){return e.split(/\s+/).filter((e=>!!e))}function W(){const t=new RegExp(`${e.Util.escapeForRegex(e.Util.pxtLangCookieId)}=(.*?)(?:;|$)`).exec(document.cookie);return t&&t[1]||null}J.TABLE="info",J.KEYPATH="id",t.tutorialInfoDbAsync=function(){return $||($=J.createAsync()),$},t.clearTutorialInfoDbAsync=function(){function t(){const t=J.dbName();return F.deleteDatabaseAsync(t).then((()=>{$=void 0})).catch((n=>{e.log(`db: failed to delete ${t}`),$=void 0}))}return $?$.then((e=>e.clearAsync())).catch((e=>t().then())):t()},t.pointerEvents=k()?{up:"pointerup",down:["pointerdown"],move:"pointermove",enter:"pointerenter",leave:"pointerleave"}:m()?{up:"mouseup",down:["mousedown","touchstart"],move:"touchmove",enter:"touchenter",leave:"touchend"}:{up:"mouseup",down:["mousedown"],move:"mousemove",enter:"mouseenter",leave:"mouseleave"},t.getPageX=function(e){return"pageX"in e?e.pageX:e.changedTouches[0].pageX},t.getPageY=function(e){return"pageY"in e?e.pageY:e.changedTouches[0].pageY},t.getClientX=function(e){return"clientX"in e?e.clientX:e.changedTouches[0].clientX},t.getClientY=function(e){return"clientY"in e?e.clientY:e.changedTouches[0].clientY},t.popupWindow=function(t,n,i,s){try{const e=window.screenLeft?window.screenLeft:window.screenX,r=window.screenTop?window.screenTop:window.screenY,a=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth,o=window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight,l=a/2-i/2+e,c=o/2-s/2+r,u=window.open(t,n,"width="+i+", height="+s+", top="+c+", left="+l);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 q(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){q(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){q(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=W,t.setCookieLang=function(t,n=!1){if(e.Util.allLanguages[t]&&t!==W()){e.tickEvent("menu.lang.setcookielang",{lang:t,docs:`${n}`});const i=new Date;i.setTime(i.getTime()+24*e.Util.langCookieExpirationDays*60*60*1e3),document.cookie=`${e.Util.pxtLangCookieId}=${t}; expires=${i.toUTCString()}; path=/`}},t.cacheBustingUrl=function(e){return e?/[?&]rnd=/.test(e)?e:`${e}${e.indexOf("?")>0?"&":"?"}rnd=${Math.random()}`:e}}(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(((i,s)=>{try{t.decompress(n,((t,n)=>{n&&e.debug("lzma decompression failed"),i(n?void 0:t)}))}catch(t){t&&e.debug("lzma decompression failed"),i(void 0)}}))))},e.lzmaCompressAsync=function(n){return t().then((t=>new Promise(((i,s)=>{try{t.compress(n,7,((t,n)=>{n&&e.reportException(n),i(n?void 0:new Uint8Array(t))}))}catch(t){e.reportException(t),i(void 0)}}))))}}(pxt||(pxt={})),function(e){!function(t){var n=pxtc.Util;let i=n.lf;const s={"pxt::mkAction":1,"pxt::dumpPerfCounters":1,"pxt::deepSleep":1,"pxt::getConfig":1,"pxtrt::mkMap":1,"pxtrt::mapSet":1,"pxtrt::stclo":1,"pxtrt::mklocRef":1,"pxtrt::stlocRef":1,"pxtrt::ldlocRef":1,"pxtrt::panic":1};function r(e="namespace"){let t="",n="",i=(i,s="")=>{n!=i&&(n&&(t+="}\n"),i&&(t+=s||e+" "+i+" {\n"),n=i)},s=" ";return{setNs:i,clear:()=>{t="",n=""},write:e=>{e.trim()?(e=e.trim().replace(/^\s*/gm,s).replace(/^(\s*)\*/gm,((e,t)=>t+" *")),t+=e+"\n"):t+="\n"},incrIndent:()=>{s+=" "},decrIndent:()=>{s=s.slice(4)},finish:()=>(i(""),t)}}function a(e){if(!e)return null;e=e.trim();let t=/^\((.*)\)/.exec(e);return t&&(e=t[1]),/^-?(\d+|0[xX][0-9a-fA-F]+)$/.test(e)?parseInt(e):null}t.nsWriter=r,t.parseCppInt=a;let o={};class l extends Error{constructor(e){super(e),this.isUserError=!0,this.message=e}}function c(e){if(!e)return"";let t="";for(let n=0;n<e.length;++n){let i=255&e[n];t+=37==i||i>127?"%"+i.toString(16):String.fromCharCode(i)}return decodeURIComponent(t)}function u(t){let n="",i=0;for(;i<t.length;i+=2)n=t[i]+t[i+1]+n;return e.Util.assert(i==t.length),n}function d(e){let t=[65,20,14,47,184,47,162,187];e:for(let n=0;n<e.length;n+=16){if(e[n]!=t[0])continue;for(let i=0;i<t.length;++i)if(e[n+i]!=t[i])continue e;let i=e[n+8]|e[n+9]<<8,s=e[n+10]|e[n+11]<<8|e[n+12]<<16|e[n+13]<<24;n+=16;let r=n+i+s;if(r>e.length)continue;let a=e.slice(n,n+i),o=e.slice(n+i,r);return{meta:c(a),text:o}}return null}function h(t){function n(t){return e.debug(t),Promise.reject(new Error(t))}let i;if(e.HF2.read32(t,0)==ts.pxtc.UF2.UF2_MAGIC_START0){let e=ts.pxtc.UF2.toBin(t);e&&(i=d(e.buf))}if(1179403647==e.HF2.read32(t,0)&&(i=d(t)),58==t[0]){i=function(e){if(!e)return;let t,n=0,i=0,s=0,r=0;if(e.split(/\r?\n/).forEach((e=>{let a=/^:10....0[0E]41140E2FB82FA2BB(....)(....)(....)(....)(..)/.exec(e);if(a)n=parseInt(u(a[1]),16),i=parseInt(u(a[2]),16),s=n+i,t=new Uint8Array(s);else if(s>0){if(a=/^:10....0[0E](.*)(..)$/.exec(e),!a)return;let n=a[1];for(;s>0&&n.length>0;)t[r++]=parseInt(n[0]+n[1],16),n=n.slice(2),s--}})),!t||0!=s||r!=t.length)return;let a=new Uint8Array(n),o=new Uint8Array(i);for(let e=0;e<n;++e)a[e]=t[e];for(let e=0;e<i;++e)o[e]=t[n+e];return{meta:c(a),text:o}}(c(t)||"")}if(!i||!i.meta||!i.text)return n("This .hex file doesn't contain source.");let s=JSON.parse(i.meta);return s?"LZMA"==s.compression?e.lzmaDecompressAsync(i.text).then((t=>{if(!t)return null;let n=t.slice(0,s.headerSize||s.metaSize||0),i=t.slice(n.length);return n&&e.Util.jsonCopyFrom(s,JSON.parse(n)),{meta:s,source:i}})):s.compression?n(`Compression type ${s.compression} not supported.`):Promise.resolve({source:c(i.text)}):n("This .hex file is not valid.")}t.PkgConflictError=l,t.getExtensionInfo=function(t){const c={__appVariant:e.appTargetVariant||""},u="dal.d.ts";let d="/source/",h="",p=[];const f=t.sortedDeps(!0).sort(((e,t)=>"this"==e.id?1:"this"==t.id?-1:n.strcmp(e.id,t.id)));for(let t of f)t.disablesVariant(e.appTargetVariant)||t.resolvedDependencies().some((t=>t.disablesVariant(e.appTargetVariant)))?(h&&(h+=", "),h+=t.id,e.debug(`disable variant ${e.appTargetVariant} due to ${t.id}`)):(p.push(t),t.addSnapshot(c,[u,".h",".cpp"]));const g=JSON.stringify(c),m=o[g];if(m){e.debug("Using cached extinfo");const t=n.flatClone(m);return t.disabledDeps=h,t}e.debug("Generating new extinfo");const b=pxtc.emptyExtInfo();b.disabledDeps=h;let y=e.appTarget.compileService;y||(y={gittag:"none",serviceId:"nocompile"}),y=n.clone(y);let v=t.getTargetOptions();v||(v={isNative:!1,hasHex:!1,switches:{}});const w=!!y.platformioIni,k="codal"==y.buildEngine||"dockercodal"==y.buildEngine,A="dockermake"==y.buildEngine||"dockercross"==y.buildEngine,x="dockerespidf"==y.buildEngine,T=!(w||k||A||x),E=v.nativeType==pxtc.NATIVE_TYPE_VM;w?d="/src/":k||A?d="/pxtapp/":x&&(d="/main/");let C="// Configuration defines\n",I="\nPXT_SHIMS_BEGIN\n",U="",S="",N='#include "pxt.h"\n',P="",_=e=>P+=` ${D}(${O}): ${e}\n`,O=0,D="",$=r("namespace"),L=r("declare namespace"),R=r("declare namespace"),M="",j={},F={};const B={true:"1",false:"0",null:"0",NULL:"0"};function H(e){return e.trim().replace(/[\_\*]$/,"")}for(const t of p){if(t.getFiles().indexOf(u)>=0){const n=t.host().readFile(t,u);e.Util.assert(!!n,`dal.d.ts not found in ${t.id}`),n.split(/\r?\n/).forEach((e=>{let t=/^\s*(\w+) = (.*),/.exec(e);t&&(B[t[1]]=t[2])}))}for(const e of t.getFiles())(["Makefile","sdkconfig.defaults","CMakeLists.txt"].indexOf(e)>=0||n.endsWith(e,".mk"))&&(b.generatedFiles["/"+e]=t.host().readFile(t,e))}let G=["0","false","PXT_UTF8"],z={};function V(e){return e.replace(/\/\/.*/,"").replace(/\/\*/,"")}v.switches.boxDebug&&(z.PXT_BOX_DEBUG=1),v.utf8&&(z.PXT_UTF8=1),v.switches.profile&&(z.PXT_PROFILE=1),v.switches.gcDebug&&(z.PXT_GC_DEBUG=1),v.switches.numFloat&&(z.PXT_USE_FLOAT=1),v.nativeType==pxtc.NATIVE_TYPE_VM&&(z.PXT_VM=1);let J=0,q=!1,W="",Y="",K="",X=!1;function Q(){L.setNs(""),L.write(""),L.write(""),(K||Y)&&(L.write(Y),L.write(K),K="",Y="")}function Z(e,t){let r;W="",Y="",K="",X=!1;let o=-1;function l(){let e=W.replace(/Methods$/,"");return e==W?null:e}function c(e){switch(e.replace(/\s+/g,"")){case"void":return"void";case"int32_t":case"int":return"int32";case"uint32_t":case"unsigned":return"uint32";case"TNumber":case"float":case"double":return"number";case"uint16_t":return"uint16";case"int16_t":case"short":return"int16";case"uint8_t":case"byte":return"uint8";case"int8_t":case"sbyte":return"int8";case"bool":return v.shortPointers&&_("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 H(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(j,e)?"I":"_"+e.replace(/[\*_]+$/,"")}}e=e.replace(/^(\s*#\s*if\s+(\w+)\s*$)([^]*?)(^\s*#\s*(elif|else|endif)\s*$)/gm,((e,t,n,i,s)=>G.indexOf(n)>=0&&!z[n]?t+i.replace(/[^\n]/g,"")+s:e)),O=0,q=!1,J=0,R.setNs(""),L.setNs(""),e.split(/\r?\n/).forEach((e=>{++O;let d=V(e);!function(e){let t=V(e);if(q&&t.indexOf("}")>=0&&(q=!1,R.write("}")),!q)return;let i=/^\s*(\w+)\s*(=\s*(.*?))?,?\s*$/.exec(t);if(i){let e=i[1],s=i[3],r="";if(s){s=s.trim();let e=n.lookup(B,s);null!=e&&(r=" // "+s,s=e),J=a(s),null==J&&_("cannot determine value of "+t)}else J++,s=J+"";R.write(` ${H(e)} = ${s},${r}`)}else R.write(e)}(e);let h=/^\s*enum\s+(|class\s+|struct\s+)(\w+)\s*({|$)/.exec(d);var p,f;if(h&&(p=h[2],f=h[3],q=!0,J=-1,R.write(""),R.write(""),(K||Y)&&(R.write(Y),R.write(K),K="",Y=""),R.write(`declare const enum ${H(p)} ${f}`),j[p]=!0,t||($.setNs(W),$.write(`enum ${h[2]} : int;`))),function(e){return!(!q&&(/^\s*\/\*\*/.test(e)?(X=!0,Y=e+"\n",/\*\//.test(e)&&(X=!1),0):X?(Y+=e+"\n",/\*\//.test(e)&&(X=!1),0):!/^\s*\/\/%/.test(e)||(K+=e+"\n",0)))}(e))return;/^typedef.*;\s*$/.test(e)&&($.setNs(W),$.write(e));let g=/^\s*namespace\s+(\w+)/.exec(e);if(g)if(W=g[1],l()){Q();let e=l();L.setNs(W,`declare interface ${e} {`)}else(K||Y)&&(Q(),L.setNs(H(W)),R.setNs(H(W)));else{if(g=/^PXT_ABI\((\w+)\)/.exec(e),g&&!E&&(I+=`PXT_FNPTR(::${g[1]}),\n`,S+=`extern "C" void ${g[1]}();\n`,b.functions.push({name:g[1],argsFmt:[],value:0})),g=/^\s*PXT_EXPORT\(([:\&\w]+)\)/.exec(e),g&&(b.vmPointers||(b.vmPointers=[]),b.vmPointers.push(g[1])),g=/^#define\s+PXT_COMM_BASE\s+([0-9a-fx]+)/.exec(e),g&&(b.commBase=parseInt(g[1])),g=/^\s*(\w+)([\*\&]*\s+[\*\&]*)(\w+)\s*\(([^\(\)]*)\)\s*(;\s*$|\{|$)/.exec(e),!K||!g){if(g=/^\s*extern const (\w+) (\w+);/.exec(e),K&&g){let e={name:W+"::"+g[2],argsFmt:[],value:null};return b.functions.push(e),E||(I+="PXT_FNPTR(&::"+e.name+"),\n"),void(K="")}if(g=/^\s*(\w+)\s+(\w+)\s*;/.exec(e),K&&g){let e=pxtc.parseCommentString(K);e.indexedInstanceNS&&(r=e,L.setNs(e.indexedInstanceNS),o=0);let t=g[1],n=g[2];if(r)return K=K.trim(),K+=` fixedInstance shim=${r.indexedInstanceShim}(${o++})`,L.write(""),L.write(Y),L.write(K),L.write(`const ${n}: ${c(t)};`),Y="",void(K="")}return K&&e.trim()?(_("declaration not understood: "+e),K="",void(Y="")):void 0}{r=null;let e=pxtc.parseCommentString(K);W||_("missing namespace declaration");let o=(g[1]+g[2]).replace(/\s+/g,""),d=g[3],h=g[4];K=K.trim().replace(/ \w+\.defl=\w+/g,"");let p=[u(o)],f=[],m=h.split(/,/).filter((e=>!!e)).map((t=>{let i=function(e,t){t=t.trim();let i=/(.*)=\s*(-?\w+)$/.exec(t),s="",r="";if(i&&(s=i[2],r="?",t=i[1].trim()),i=/^(.*?)(\w+)$/.exec(t),!i)return _("invalid argument: "+t),{name:"???",type:"int"};let o=i[2];e.paramDefl[o]&&(s=e.paramDefl[o],r="?");let l=s?n.lookup(B,s):null;return null!=l&&(s=l),s&&(null==a(s)&&_("Invalid default value (non-integer): "+s),K+=` ${o}.defl=${s}`),{name:o+r,type:i[1]}}(e,t);return p.push(u(i.type)),f.push(i.type.replace(/ /g,"")),`${i.name}: ${c(i.type)}`})),y={name:W+"::"+d,argsFmt:p,value:null};if(Y)if(L.setNs(H(W)),L.write(""),L.write(Y),/ImageLiteral/.test(g[4])&&!/imageLiteral=/.test(K)&&(K+=" imageLiteral=1"),K+=` shim=${y.name}`,L.write(K),d=H(d),l()){let e=(m[0]||"").replace(/^.*:\s*/,"").trim();e.toLowerCase()!=l().toLowerCase()&&_(i("Invalid first argument; should be of type '{0}', but is '{1}'",l(),e)),m.shift(),0==m.length&&/\bproperty\b/.test(K)?L.write(`${d}: ${c(o)};`):L.write(`${d}(${m.join(", ")}): ${c(o)};`)}else L.write(`function ${d}(${m.join(", ")}): ${c(o)};`);if(Y="",K="",t||($.setNs(W),$.write(`${o} ${d}(${h});`)),b.functions.push(y),T)I+="(uint32_t)(void*)::"+y.name+",\n";else if(E){if(n.startsWith(y.name,"pxt::op_")||s[y.name]||e.expose||!n.startsWith(y.name,"pxt::")&&!n.startsWith(y.name,"pxtrt::")){const e=function(e,t){if("FiberContext*"==t[0])return"::"+e.name;let n="_wrp_"+e.name.replace(/:/g,"_");if(F[e.name])return n;F[e.name]=!0,U+=`\nvoid ${n}(FiberContext *ctx) {\n`;const i=t.length;let s=[],r=!1,a="";for(let n=0;n<i;++n){const o=e.argsFmt[n+1],l=t[n];let c="I"==o?"toInt":"B"==o?"numops::toBool":"";const u=n==i-1?"ctx->r0":`ctx->sp[${i-n-2}]`;let d="";switch(l){case"TValue":case"TNumber":break;case"Action":c="asRefAction";break;case"String":c="convertToString",d="ctx, ",r=!0;break;default:c||(c="as"+l.replace(/\*/g,""))}a+=` ${l} a${n} = (${l}) ${c}(${d}${u});\n`,s.push("a"+n)}r&&(U+=" auto prevSP = ctx->sp;\n"),U+=a,r&&(U+=" if (panicCode) { ctx->sp = prevSP; return; }\n");const o=`::${e.name}(${s.join(", ")})`;return"V"==e.argsFmt[0]?(U+=` ${o};\n`,U+=" ctx->r0 = NULL;\n"):"I"==e.argsFmt[0]?U+=` ctx->r0 = fromInt(${o});\n`:"B"==e.argsFmt[0]?U+=` ctx->r0 = fromBool(${o});\n`:U+=` ctx->r0 = (TValue)${o};\n`,r&&(U+=" ctx->sp = prevSP;\n"),i>1&&(U+=` ctx->sp += ${i-1};\n`),U+="}\n",n}(y,f),t=y.argsFmt.length-1;I+=`{ "${y.name}", (OpFun)(void*)${e}, ${t} },\n`}}else I+="PXT_FNPTR(::"+y.name+"),\n"}}}))}const ee=n.clone(y.yottaConfig||{}),te={},ne={},ie={};function se(t){const s=t.config.platformio;s&&s.dependencies&&n.jsonCopyFrom(b.platformio.dependencies,s.dependencies),b.npmDependencies&&t.config.npmDependencies&&n.jsonCopyFrom(b.npmDependencies,t.config.npmDependencies);const r=t.config.codal;if(k&&r)for(const t of r.libraries||[]){const s=e.github.parseRepoId(t);s||n.userError(i("codal library {0} doesn't look like github repo",t));const r=e.github.stringifyRepo(s),a=n.lookup(ie,s.project);a?e.github.stringifyRepo(a)!=r&&n.userError(i("conflict between codal libraries: {0} and {1}",e.github.stringifyRepo(a),r)):ie[s.project]=s}const a=t.config.yotta;if(a){if(a.dependencies&&n.jsonCopyFrom(b.yotta.dependencies,a.dependencies),a.config){const e=n.jsonFlatten(a.config);for(const s of Object.keys(e)){const r=n.lookup(ne,s),a=e[s];if(!r||r.config.yotta.configIsJustDefaults)ne[s]=t,ee[s]=a;else if(ee[s]===a);else if(!t.parent.config.yotta||!t.parent.config.yotta.ignoreConflicts){let e=new l(i("conflict on yotta setting {0} between extensions {1} and {2}",s,t.id,r.id));throw e.pkg0=r,e.pkg1=t,e.settingName=s,e}}}if(a.optionalConfig){const e=n.jsonFlatten(a.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;b.yotta.dependencies[e.yottaCorePackage]=t}if(t){let e=!1;for(let s of p){P="",se(s),s==t?(e=!0,L.clear(),R.clear()):n.assert(!e);const r=e=>n.endsWith(e,".h"),a=".cpp",o=s.getFiles().filter(r).concat(s.getFiles().filter((e=>!r(e))));for(let e of o){const t=r(e);if(t||n.endsWith(e,a)){let r=s.config.name+"/"+e;("base"==s.config.name||/^core($|---)/.test(s.config.name))&&t&&(r=e),t&&(N+=`#include "${T?d.slice(1):""}${r}"\n`);let a=s.readFile(e);null==a&&n.userError(i("C++ file {0} is missing in extension {1}.",e,s.config.name)),D=r,Z(a,t),b.extensionFiles[d+r]=a,0==s.level&&(b.onlyPublic=!1),s.verProtocol()&&"pub"!=s.verProtocol()&&"embed"!=s.verProtocol()&&(b.onlyPublic=!1)}if(n.endsWith(e,".c")||n.endsWith(e,".S")||n.endsWith(e,".s")){let t=s.readFile(e);b.extensionFiles[d+s.config.name+"/"+e.replace(/\.S$/,".s")]=t}}P&&(M+=i("Extension {0}:\n",s.id)+P)}e||(L.clear(),R.clear())}function re(e){return Object.keys(b.extensionFiles).concat(Object.keys(b.generatedFiles)).filter((t=>n.endsWith(t,e))).map((e=>e.slice(1)))}M&&n.userError(M),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 ae=n.jsonUnFlatten(te);if(A){let e={name:"pxt-app",private:!0,dependencies:b.npmDependencies};b.generatedFiles["/package.json"]=JSON.stringify(e,null,4)+"\n"}else if(x){const e=n.concatArrayLike([re(".c"),re(".cpp"),re(".s")]).map((e=>e.slice(d.length-1))).concat(["main.cpp"]);e.push("pointers.cpp"),b.generatedFiles[d+"CMakeLists.txt"]="idf_component_register(\n SRCS\n"+e.map((e=>` "${e}"\n`)).join("")+' INCLUDE_DIRS\n "."\n)\n'}else if(k){let t=y,i=n.clone(t.codalDefinitions)||{},s=t.codalTarget;"string"==typeof s&&(s+=".json");let r={target:s,definitions:i,config:i,application:"pxtapp",output_folder:"build",pxt_gitrepo:t.githubCorePackage,pxt_gittag:t.gittag,libraries:n.values(ie).map((e=>({name:e.project,url:"https://github.com/"+e.fullName,branch:e.tag||"master",type:"git"})))};0==r.libraries.length&&delete r.libraries,n.iterMap(n.jsonFlatten(ae),((e,t)=>{e=e.replace(/^codal\./,"device.").toUpperCase().replace(/\./g,"_"),i[e]=t})),b.generatedFiles["/codal.json"]=JSON.stringify(r,null,4)+"\n",e.debug(`codal.json: ${b.generatedFiles["/codal.json"]}`)}else if(w){const e=y.platformioIni.slice();e.push("lib_deps ="),n.iterMap(b.platformio.dependencies,((t,n)=>{let i=/[@#\/]/.test(n)?n:t+"@"+n;e.push(" "+i)})),b.generatedFiles["/platformio.ini"]=e.join("\n")+"\n"}else{b.yotta.config=ae;let t="pxt-app";y.yottaBinary&&(t=y.yottaBinary.replace(/-combined/,"").replace(/\.hex$/,""));let n={name:t,version:"0.0.0",description:"Auto-generated. Do not edit.",license:"n/a",dependencies:b.yotta.dependencies,targetDependencies:{},bin:"./source"};b.generatedFiles["/module.json"]=JSON.stringify(n,null,4)+"\n",e.debug(`module.json: ${b.generatedFiles["/module.json"]}`)}for(let e of Object.keys(z))C+=`#define ${e} ${z[e]}\n`;if(v.uf2Family&&(C+=`#define PXT_UF2_FAMILY ${v.uf2Family}\n`),b.generatedFiles[d+"pointers.cpp"]=N+$.finish()+S+U+I+"\nPXT_SHIMS_END\n",b.generatedFiles[d+"pxtconfig.h"]=C,e.debug(`pxtconfig.h: ${b.generatedFiles[d+"pxtconfig.h"]}`),T&&(b.generatedFiles["/config.json"]=JSON.stringify(ae,null,4)+"\n",e.debug(`yotta config.json: ${b.generatedFiles["/config.json"]}`)),b.generatedFiles[d+"main.cpp"]='\n#include "pxt.h"\n#ifdef PXT_MAIN\nPXT_MAIN\n#else\nint main() {\n uBit.init();\n pxt::start();\n release_fiber();\n return 0; // your program will never reach this line.\n}\n#endif\n',b.generatedFiles["/Makefile"]){let e="",t=(t,n)=>{e+=`${t} = ${re(n).join(" ")}\n`};t("PXT_C",".c"),t("PXT_CPP",".cpp"),t("PXT_S",".s"),t("PXT_HEADERS",".h"),e+="PXT_SOURCES := $(PXT_C) $(PXT_S) $(PXT_CPP)\n",e+="PXT_OBJS := $(addprefix bld/, $(PXT_C:.c=.o) $(PXT_S:.s=.o) $(PXT_CPP:.cpp=.o))\n",b.generatedFiles["/Makefile.inc"]=e}b.generatedFiles["/functions.json"]=JSON.stringify(b.functions,null,1);let oe=b.extensionFiles;n.jsonCopyFrom(oe,b.generatedFiles);let le={config:y.serviceId,tag:y.gittag,replaceFiles:oe,dependencies:T?b.yotta.dependencies:null},ce=JSON.stringify(le);return b.sha=n.sha256(ce),b.skipCloudBuild=!!y.skipCloudBuild,b.compileData=ts.pxtc.encodeBase64(n.toUTF8(ce)),b.shimsDTS=L.finish(),b.enumsDTS=R.finish(),Object.keys(o).length>10&&(o={}),o[g]=b,b},t.unpackSourceFromHexFileAsync=function(t){if(t)return e.Util.fileReadAsBufferAsync(t).then((e=>h(new Uint8Array(e))))},t.unpackSourceFromHexAsync=h}(e.cpp||(e.cpp={}))}(pxt||(pxt={})),function(e){!function(t){const n={};let i,s={};function r(s){return n.hasOwnProperty(s.sha)||(n[s.sha]=function(n){let s="";return t.showLoading(e.U.lf("Compiling (this may take a minute)...")),e.tickEvent("cppcompile.start"),function(t){if(t.skipCloudBuild)return Promise.resolve({hex:["SKIP"]});if(e.webConfig&&e.webConfig.isStatic)return e.Util.requestAsync({url:`${e.webConfig.cdnUrl}hexcache/${t.sha}.hex`}).then((t=>{if(t.text){const e={enums:[],functions:[],hex:t.text.split(/\r?\n/)};return Promise.resolve(e)}return e.log("Hex info not found in bundled hex cache"),Promise.resolve()})).catch((t=>(e.log("Error fetching hex info from bundled hex cache"),Promise.resolve())));if(!e.Cloud.localToken||!window||!e.BrowserUtils.isLocalHost())return Promise.resolve(void 0);return(n="compile/"+t.sha,e.Cloud.localRequestAsync(n,i).then((e=>e.json))).then((e=>e&&!e.notInOfflineCache&&e.hex?(e.hex=e.hex.split(/\r?\n/),e):Promise.resolve(void 0))).catch((e=>Promise.resolve(void 0)));var n,i}(n).then((r=>r?(e.tickEvent("cppcompile.cachehit"),r):function(){if(i)return i;{let t=e.getOnlineCdnUrl();if(t)return i=Promise.resolve(t);const n=e.webConfig&&e.webConfig.isStatic;return i=e.Cloud.privateGetAsync("clientconfig",n).then((e=>e.primaryCdnUrl))}}().then((t=>(s=t+"/compile/"+n.sha,e.U.httpGetTextAsync(s+".hex")))).then((e=>e),(t=>e.Cloud.privatePostAsync("compile/extension",{data:n.compileData},!0).then((t=>new Promise(((n,i)=>{let r=0;const a=8e3,o=3e5,l=e.U.now(),c=()=>{if(r++,e.U.now()-l>o)return e.log("abandoning C++ build"),e.tickEvent("cppcompile.cancel",{retry:r}),n(null),null;let i=t.hex.replace(/\.hex/,".json");return e.log(`polling C++ build ${i} (attempt #${r})`),e.tickEvent("cppcompile.poll",{retry:r}),e.Util.httpGetJsonAsync(i).then((t=>{e.log(`build log ${i.replace(/\.json$/,".log")}`),e.tickEvent("cppcompile.done",{success:(null==t?void 0:t.success)?1:0,retry:r,duration:e.U.now()-l}),t.success?(e.log("fetching "+s+".hex"),n(e.U.httpGetTextAsync(s+".hex"))):(e.log("build failed"),t.mbedresponse&&t.mbedresponse.result&&t.mbedresponse.result.exception&&e.log(t.mbedresponse.result.exception),n(null))}),(t=>(e.log(`waiting ${a/1e3|0}s for C++ build...`),setTimeout(c,a),null)))};c()})))))).then((e=>(t.hideLoading(),{hex:e&&e.split(/\r?\n/)}))))).finally((()=>{t.hideLoading()}))}(s)),n[s.sha]}function a(t,n,i,s,r=10){return t.cacheStoreAsync(i,s).then((()=>t.cacheGetAsync(n))).then((s=>{let a;try{a=JSON.parse(s||"[]")}catch(e){console.error("invalid cache entry, clearing entry"),a=[]}a=a.filter((e=>e!=i)),a.unshift(i);let o=a.slice(r);return a=a.slice(0,r),e.U.promiseMapAll(o,(e=>t.cacheStoreAsync(e,"[]"))).then((()=>t.cacheStoreAsync(n,JSON.stringify(a))))}))}function o(e,t,n){return e.cacheGetAsync(t).then((i=>{let s;try{s=JSON.parse(i||"[]")}catch(n){return console.error("invalid cache entry, clearing entry"),e.cacheStoreAsync(t,"[]")}return s[0]!=n?(s=s.filter((e=>e!=n)),s.unshift(n),e.cacheStoreAsync(t,JSON.stringify(s))):null}))}t.showLoading=e=>{},t.hideLoading=()=>{},t.storeWithLimitAsync=a,t.recordGetAsync=o,t.getHexInfoAsync=function(t,n,i){if(!n.sha)return Promise.resolve(null);const l=s[n.sha];if(l)return Promise.resolve(l);e.debug("get hex info: "+n.sha);let c="hex-"+n.sha;return t.cacheGetAsync(c).then((i=>{let s;try{s=i?JSON.parse(i):null}catch(e){console.log("invalid cache entry, clearing entry"),s=null}return s&&s.hex?(e.debug("cache hit, size="+i.length),s.hex=function(t){let n=[];for(let i=0;i<t.length;i++){let s=/^([@!])(....)$/.exec(t[i]);if(!s){n.push(t[i]);continue}let r=parseInt(s[2],16),a=t[++i],o="";if("@"==s[1]){o="";let e=parseInt(a,16);for(;e-- >0;)o+="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"}else o=ts.pxtc.decodeBase64(a);e.Util.assert(o.length>0),e.Util.assert(o.length%16==0);for(let e=0;e<o.length;){let t=[16,r>>8&255,255&r,0];r+=16;for(let n=0;n<16;++n)t.push(o.charCodeAt(e++));let i=0;for(let e=0;e<t.length;++e)i+=t[e];t.push(255&-i);let s=":";for(let e=0;e<t.length;++e){let n=255&t[e];n<=15&&(s+="0"),s+=n.toString(16)}n.push(s.toUpperCase())}}return n}(s.hex),o(t,"hex-keys",c).then((()=>s))):r(n).then((e=>{let n=e.hex;e.hex=function(e){let t=[],n=0;for(let i=0;i<e.length;i+=n){let s=-1,r="";n=0;let a=!1;for(;n<500;){let o=/^:10(....)00(.{32})(..)$/.exec(e[i+n]);if(!o)break;let l=o[2],c=/^0+$/.test(l),u=parseInt(o[1],16);if(-1==s)a=c,t.push((a?"@":"!")+o[1]),s=u-16;else{if(c!=a)break;if(s+16!=u)break}a||(r+=l),s=u,n++}if(0==n)t.push(e[i]),n=1;else if(a)t.push(n.toString(16));else{let e="";for(let t=0;t<r.length;t+=2)e+=String.fromCharCode(parseInt(r.slice(t,t+2),16));t.push(ts.pxtc.encodeBase64(e))}}return t}(e.hex);let i=JSON.stringify(e);return e.hex=n,a(t,"hex-keys",c,i).then((()=>e))})).catch((t=>(e.reportException(t,{sha:n.sha}),Promise.resolve(null))))})).then((e=>(e&&(Object.keys(s).length>20&&(s={}),s[n.sha]=e),e)))}}(e.hexloader||(e.hexloader={}))}(pxt||(pxt={})),function(e){!function(t){function n(n,i,s={},r=null,a=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(i,s,r,a)}function i(n,i,s,r,a){e.Util.assert(!!i&&!!s&&!!r);const o="https://api.crowdin.com/api/project/"+i+"/";return a=a||{},t.testMode?delete a.key:a.key=s,n&&(a.branch=n),o+r+"?"+Object.keys(a).map((e=>`${e}=${encodeURIComponent(a[e])}`)).join("&")}function s(e){let t=0;return function(){if(t++>10)throw new Error("Too many API calls for "+e)}}function r(t,o,l,c,u){return c=a(c),e.debug(`create directory ${t||""}/${c}`),u||(u=s(c)),n(l,i(t,o,l,"add-directory"),{json:"true",name:c}).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 i=n.json||JSON.parse(n.text)||{error:{}};if(404==n.statusCode&&17==i.error.code){e.log(`parent directory missing for ${c}`);const n=c.replace(/\/[^\/]+$/,"");if(n!=c)return r(t,o,l,n,u).then((()=>r(t,o,l,c,u)))}throw new Error(`cannot create directory ${t||""}/${c}: ${n.statusCode} ${JSON.stringify(i)}`)}))}function a(e){return e.replace(/\\/g,"/")}function o(e,t,n,i){const s=t.name,r=n?n+"/"+s:s;switch(t.fullName=r,t.branch=i||"",t.node_type){case"file":e.push(t);break;case"directory":(t.files||[]).forEach((t=>o(e,t,r,i)));break;case"branch":(t.files||[]).forEach((i=>o(e,i,n,t.name)))}}function l(t,n){const i=e.appTarget.versions.pxtCrowdinBranch||"",s=e.appTarget.versions.targetCrowdinBranch||"";let r=[];if(t.forEach((e=>o(r,e,""))),r=r.filter((e=>e.fullName.indexOf("/")<0?e.branch==i:e.branch==s)),n&&(r=r.filter((e=>0==e.fullName.indexOf(n)))),"core"!=e.appTarget.id){const t=e.appTarget.id+"/";r=r.filter((e=>e.fullName.indexOf("/")<0||e.fullName.substr(0,t.length)==t||e.fullName.indexOf("common-docs")>=0))}return r}function c(t,n){const s=i("",t,n,"info",{json:"true"});return e.Util.httpGetTextAsync(s).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,s,r,o={}){const l=i(t,n,s,"info",{json:"true"}),c={};return r=a(r),e.Util.httpGetTextAsync(l).then((a=>{const l=JSON.parse(a);if(!l)throw new Error("info failed");let u=l.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 a=u.pop();if(!a)return Promise.resolve();const l=i(t,n,s,"export-file",{file:r,language:a.code,export_translated_only:o.translatedOnly?"1":"0",export_approved_only:o.validatedOnly?"1":"0"});return e.log(`downloading ${a.name} - ${a.code} (${u.length} more)`),e.Util.httpGetTextAsync(l).then((t=>{try{const e=JSON.parse(t);e&&(c[a.code]=e)}catch(t){e.log(l+" "+t)}return d()})).then((()=>e.Util.delay(1e3)))};return d()})).then((()=>c))},t.createDirectoryAsync=r,t.uploadTranslationAsync=function t(o,l,c,u,d){e.Util.assert(!!l),e.Util.assert(!!c);const h=s(u=a(u));function p(){return f("update-file",{update_option:"update_as_unapproved"})}function f(s,a){return a.type="auto",a.json="",a.escape_quotes="0",h(),n(c,i(o,l,c,s),a,u,d).then((n=>function(n){const i=n.statusCode,s=e.Util.jsonTryParse(n.text)||{};if(e.debug(`upload result: ${i}`),404==i&&s.error&&8==s.error.code)return e.log(`create new translation file: ${u}`),f("add-file",{});if(404==i&&s.error&&17==s.error.code)return r(o,l,c,u.replace(/\/[^\/]+$/,""),h).then((()=>p()));if(!s.success&&s.error&&53==s.error.code)return e.log(`${u} being updated, waiting 5s and retry...`),e.U.delay(5e3).then((()=>t(o,l,c,u,d)));if(200==i||s.success)return Promise.resolve();throw new Error(`Error, upload translation: ${u}, ${i}, ${n.text}`)}(n)))}return p()},t.projectInfoAsync=c,t.listFilesAsync=function(t,n,i){return e.log(`crowdin: listing files under ${i}`),c(t,n).then((t=>{if(!t)throw new Error("info failed");let n=l(t.files,i);return e.debug(`crowdin: found ${n.length} under ${i}`),n.map((e=>({fullName:e.fullName,branch:e.branch||""})))}))},t.languageStatsAsync=function(t,n,s){const r=i("",t,n,"language-status",{language:s,json:"true"});return e.Util.httpGetJsonAsync(r).then((e=>l(e.files)))},t.inContextLoadAsync=function(t){const n=document.createElement("input");n.type="text",n.setAttribute("class","hidden"),n.value=t;let i=new Promise(((i,s)=>{const r=new MutationObserver((()=>{if(t==n.value)return;const s=e.Util.rlf(n.value);n.remove(),r.disconnect(),i(s)}));r.observe(n,{attributes:!0})}));return document.body.appendChild(n),i}}(e.crowdin||(e.crowdin={}))}(pxt||(pxt={})),function(e){!function(t){function n(e){return e?e.split(/\r?\n/):[]}function i(e,t,i={}){i.ignoreWhitespace&&(e=e.replace(/[\r\n]+$/,""),t=t.replace(/[\r\n]+$/,""));const s=n(e),r=n(t),a=Math.min(i.maxDiffSize||1024,s.length+r.length);if(0==a)return[];const o=s.length>65520?Uint32Array:Uint16Array,l={};let c=0;const u=h(s),d=h(r);function h(e){const t=new o(e.length);let n=0;for(let s of e)i.ignoreWhitespace&&(s=s.replace(/\s+$/g,"").replace(/^\s+/g,"")),l.hasOwnProperty(s)?t[n]=l[s]:(++c,t[n]=c,l[s]=c),n++;return t}const p=new o(2*a+1);let f=-1;for(let e=0;e<=a;e++)null!=T(e,p)&&(f=e);if(-1==f)return null;const g=[];let m=null;for(let e=0;e<=f;e++){const t=g.length?g[g.length-1].slice(0):new o(2*f+1);if(g.push(t),m=T(e,t),null!=m)break}const b=[];let y=m;for(let e=g.length-1;e>=0;e--){const t=g[e];let n=0,i=0;y==-e||y!=e&&t[a+y-1]<t[a+y+1]?(i=y+1,n=t[a+i]):(i=y-1,n=t[a+i]+1);let o=n-y;for(let e=t[a+y]-n-1;e>=0;--e)b.push(" "+r[o+e]);i==y-1?b.push("- "+s[n-1]):o>0&&b.push("+ "+r[o-1]),y=i}if(b.reverse(),i.context==1/0||i.full)return b;let v=1,w=1,k=0;const A=[],x=i.context||3;for(;k<b.length;){let e=k;for(;e<b.length&&" "==b[e][0];)e++;if(e==b.length)break;const t=e-x,n=t-k;n>0&&(v+=n,w+=n,k=t);const i=A.length,s=v,r=w;A.push("@@");let a=k,o=0;for(;a<b.length;){if(" "==b[a][0]){if(o++,o>2*x+2){a-=x+2;break}}else o=0;a++}for(;k<a;){A.push(b[k]);switch(b[k][0]){case"-":v++;break;case"+":w++;break;case" ":v++,w++}k++}A[i]=`@@ -${s},${v-s} +${r},${w-r} @@`}return A;function T(e,t){for(let n=-e;n<=e;n+=2){let i=0;i=n==-e||n!=e&&t[a+n-1]<t[a+n+1]?t[a+n+1]:t[a+n-1]+1;let s=i-n;for(;i<u.length&&s<d.length&&u[i]==d[s];)i++,s++;if(t[a+n]=i,i>=u.length&&s>=d.length)return n}return null}}function s(e){return n(e).map((e=>e.replace(/;\s*$/,""))).join("\n")}function r(e){const t=/^@@ -(\d+),(\d+) \+(\d+),(\d+)/.exec(e);return t&&{oldStart:parseInt(t[1])-1,oldLength:parseInt(t[2]),newStart:parseInt(t[3])-1,newLength:parseInt(t[4])}}t.toLines=n,t.compute=i,t.diff3=function(t,s,r,a,o){const l=m(t),c=m(r);if(!l||!c)return;const u=n(t),d=n(r);let h=0,p=[],f=0,g=0;for(let t=0;t<l.length-1;)if(l[t]==f&&c[t]==g)p.push(u[f]),f++,g++,t++;else{let n=!0,i=!0,s=t;for(;s<l.length&&(l[s]!=f+s-t&&(n=!1),c[s]!=g+s-t&&(i=!1),null==l[s]||null==c[s]);)s++;if(e.U.assert(s<l.length),n)for(;g<c[s];)p.push(d[g++]);else if(i)for(;f<l[s];)p.push(u[f++]);else if(u.slice(f,l[s]).join("\n")==d.slice(g,c[s]).join("\n"))for(;f<l[s];)p.push(u[f++]);else{for(h++,p.push("<<<<<<< "+a);f<l[s];)p.push(u[f++]);for(p.push("=======");g<c[s];)p.push(d[g++]);p.push(">>>>>>> "+o)}t=s,f=l[s],g=c[s]}return{merged:p.join("\n"),numConflicts:h};function m(t){const n=i(s,t,{context:1/0});if(!n)return;const r=[];let a=0,o=0;for(let t of n)"+"==t[0]?a++:"-"==t[0]?(r[o]=null,o++):" "==t[0]?(r[o]=a,a++,o++):e.U.oops();return r.push(a+1),r}},t.removeTrailingSemiColumns=s,t.split=function(e,t){const n=e.split(/-{10,}/,2);if(n.length<2)return{fileA:e,fileB:void 0};let i=n[0].replace(/\n$/,""),r=n[1].replace(/^\n/,"");return t&&t.removeTrailingSemiColumns&&(i=s(i),r=s(r)),{fileA:i,fileB:r}},t.parseDiffMarker=r,t.render=function(t,n,s={}){const a=i(t,n,s);if(!a)return e.dom.el("div",null,pxtc.Util.lf("Too many differences to render diff."));const o={"@":"diff-marker"," ":"diff-unchanged","+":"diff-added","-":"diff-removed"};let l=0,c=0,u="";const d=e.dom.el("tbody"),h=e.dom.el("table",{class:"diffview "+(s.update?"update":"")},d);let p=null;return a.forEach(((t,n)=>{const h=r(t);h?(l=h.oldStart,c=h.newStart):("+"!=t[0]&&l++,"-"!=t[0]&&c++);const f=a[n+1]?a[n+1][0]:"",g=a[n+2]?a[n+2][0]:"",m=t.slice(2);let b=e.dom.el("code",null,m);if(p)b=p,p=null;else if(!("-"!=t[0]||" "!=u&&"@"!=u||"+"!=f||" "!=g&&"@"!=g&&""!=g)){const s=function(t,n){const s=i(t.split("").join("\n"),n.split("").join("\n"),{context:1/0});if(!s)return{a:e.dom.el("div",{class:"inline-diff"},e.dom.el("code",null,t)),b:e.dom.el("div",{class:"inline-diff"},e.dom.el("code",null,n))};const r=[],a=[];for(let t=0;t<s.length;){let n=t;const i=s[t][0];for(;s[n]&&s[n][0]==i;)n++;const o=s.slice(t,n).map((e=>e.slice(2))).join("");" "==i?(r.push(e.dom.el("code",{class:"ch-common"},o)),a.push(e.dom.el("code",{class:"ch-common"},o))):"-"==i?r.push(e.dom.el("code",{class:"ch-removed"},o)):"+"==i?a.push(e.dom.el("code",{class:"ch-added"},o)):e.Util.oops(),t=n}return{a:e.dom.el("div",{class:"inline-diff"},r),b:e.dom.el("div",{class:"inline-diff"},a)}}(t.slice(2),a[n+1].slice(2));b=s.a,p=s.b}if(u=t[0],s.hideMarkerLine&&"@"==u||s.hideRemoved&&"-"==u)return;const y="@"==u,v=`${o[u]}`;d.appendChild(e.dom.el("tr",{class:v},[!s.hideLineNumbers&&e.dom.el("td",{class:"line-a","data-content":l}),!s.hideLineNumbers&&e.dom.el("td",{class:"line-b","data-content":c}),y&&e.dom.el("td",{colspan:2,class:"change"},e.dom.el("code",null,t)),!s.hideMarker&&!y&&e.dom.el("td",{class:"marker","data-content":u}),!y&&e.dom.el("td",{class:"change"},b)]))})),h},t.resolveMergeConflictMarker=function(t,n,i,s){let r=e.diff.toLines(t),a=n;for(;a<r.length&&!/^<<<<<<<[^<]/.test(r[a]);)a++;let o=a+1;for(;o<r.length&&!/^=======$/.test(r[o]);)o++;let l=o+1;for(;l<r.length&&!/^>>>>>>>[^>]/.test(r[l]);)l++;if(l>=r.length)return e.debug(`diff marker mistmatch: ${r.length} -> ${a} ${o} ${l}`),t;if(r[a]=void 0,r[o]=void 0,r[l]=void 0,!i)for(let e=a;e<=o;++e)r[e]=void 0;if(!s)for(let e=o;e<=l;++e)r[e]=void 0;return r.filter((e=>void 0!==e)).join("\n")},t.mergeDiff3Config=function(t,n,i){let s=e.Util.jsonTryParse(t),r=e.Util.jsonTryParse(n),a=e.Util.jsonTryParse(i);if(s&&!a)return t;if(!s)return i||n;if(!r&&a&&(r=a),!s||!r||!a)return;delete s.installedVersion,delete r.installedVersion,delete a.installedVersion;const o={},l=e.U.unique(Object.keys(r).concat(Object.keys(s)).concat(Object.keys(a)),(e=>e));for(const t of l){const n=s[t],i=r[t],l=a[t];if(JSON.stringify(n)==JSON.stringify(l))void 0!==n&&(o[t]=n);else switch(t){case"name":o[t]=c(n,i,l);break;case"version":o[t]=e.semver.strcmp(n,l)>0?n:l;break;case"languageRestriction":case"preferredEditor":case"targetVersion":o[t]=n;break;case"public":o[t]=n&&l;break;case"files":case"testFiles":{const e=u(n||[],i||[],l||[]);if(!e)return;o[t]=e.length?e:void 0;break}case"dependencies":case"testDependencies":{const e=d(n||{},i||{},l||{});if(Object.keys(e).length)return;o[t]=e;break}case"description":if(n&&!l)o[t]=n;else{if(n||!l)return;o[t]=l}break;default:return}}return e.Package.stringifyConfig(o);function c(e,t,n){return e==t?n:n==t?e:e==lf("Untitled")?n:e}function u(t,n,i){const s=[],r=e.U.unique(n.concat(t).concat(i),(e=>e));for(const e of r){const r=t.indexOf(e)>-1,a=i.indexOf(e)>-1,o=n.indexOf(e)>-1;r==a||a==o?r&&s.push(e):a&&s.push(e)}return s}function d(t,n,i){const s={},r=e.U.unique(Object.keys(n).concat(Object.keys(t)).concat(Object.keys(i)),(e=>e));for(const a of r){const r=t[a],o=i[a],l=n[a];if(r==o)r&&(s[a]=r);else{const t=e.github.parseRepoId(r),n=e.github.parseRepoId(o);if(t&&n&&e.semver.tryParse(t.tag)&&e.semver.tryParse(n.tag)&&t.owner&&t.project&&t.owner==n.owner&&t.project==n.project){const i=e.semver.strcmp(t.tag,n.tag)>0?t.tag:n.tag;s[a]=`github:${t.owner}/${t.project}#${i}`}else o==l?r&&(s[a]=r):o&&(s[a]=o)}}return s}},t.hasMergeConflictMarker=function(e){return e&&/^(<<<<<<<[^<]|>>>>>>>[^>])/m.test(e)},t.reconstructConfig=function(t,n,i,s){let r={},a=i.tree.tree.map((e=>e.path)).filter((e=>/\.(ts|blocks|md|jres|asm|json)$/.test(e))).filter((t=>t!=e.CONFIG_NAME));return t.fileName&&(a=a.filter((e=>0===e.indexOf(t.fileName))).map((e=>e.slice(t.fileName.length+1)))),a.find((e=>/\.ts$/.test(e)))||(s.config.files.filter((e=>a.indexOf(e)<0)).forEach((e=>{a.push(e),n[e]=s.files[e]})),e.Util.jsonCopyFrom(r,s.config.dependencies)),Object.keys(r).length||(r[e.appTarget.corepkg]="*"),{name:"",files:a,dependencies:r,preferredEditor:a.find((e=>/.blocks$/.test(e)))?e.BLOCKS_PROJECT_NAME:e.JAVASCRIPT_PROJECT_NAME}}}(e.diff||(e.diff={}))}(pxt||(pxt={})),function(e){!function(t){t.extractSharedIdFromPostUrl=function(t){return e.Util.httpGetJsonAsync(t+".json").then((t=>t.post_stream&&t.post_stream.posts&&t.post_stream.posts[0]&&t.post_stream.posts[0].link_counts.map((t=>e.Cloud.parseScriptId(t.url))).filter((e=>!!e))[0]))},t.topicsByTag=function(t,n){const i=`${t=t.replace(/\/$/,"")}/tag/${n}.json`;return e.Util.httpGetJsonAsync(i).then((n=>{const i=e.Util.toDictionary(n.users,(e=>e.id.toString()));return n.topic_list.topics.map((e=>({id:e.id,title:e.title,url:`${t}/t/${e.slug}/${e.id}`,imageUrl:e.image_url,author:i[e.posters[0].user_id].username,cardType:"forumUrl"})))}))}}(e.discourse||(e.discourse={}))}(pxt||(pxt={})),function(e){!function(t){var n=pxtc.Util;let i,s={},r={};const a="\x3c!-- @CMD@ @ARGS@ --\x3e";let o={parent:a,short:a,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 l(e,t,n){return e.split(t).join(n)}function c(e){return e=l(e,"&","&"),e=l(e,"<","<"),e=l(e,">",">"),e=l(e,'"',"""),e=l(e,"'","'")}function u(e){return e?c(e.replace(/\&([#a-z0-9A-Z]+);/g,((e,t)=>{switch(t){case"amp":return"&";case"lt":return"<";case"gt":return">";case"quot":return'"';default:return"#"==t[0]?String.fromCharCode(parseInt(t.slice(1))):e}}))):e}t.htmlQuote=c,t.html2Quote=u;const d=[{rx:/^vimeo\.com\/(\d+)/i,cmd:"### @vimeo $1"},{rx:/^(www\.youtube\.com\/watch\?v=|youtu\.be\/)([\w\-]+(\#t=([0-9]+m[0-9]+s|[0-9]+m|[0-9]+s))?)/i,cmd:"### @youtube $2"}];t.requireMarked=()=>"undefined"!=typeof marked?marked:"undefined"!=typeof require?require("marked"):void 0,t.requireDOMSanitizer=()=>"undefined"!=typeof DOMPurify?DOMPurify.sanitize:"undefined"!=typeof require?require("DOMPurify").sanitize:void 0;const h=e=>`<div class='ui negative message'>${c(e)}</div>`;function p(e){let t=n.clone(s),i=n.clone(r),a=n.clone(o),l={},c={},d=e.params,p=e.theme;e.boxes=t,e.macros=i,e.settings=a,e.html=e.html.replace(/<aside\s+([^<>]+)>([^]*?)<\/aside>/g,((e,n,s)=>{let r=function(e){let t={};for(;e.trim();){let n=/\s*([^=\s]+)=("([^"]*)"|'([^']*)'|(\S*))/.exec(e);if(n){let e=n[3]||n[4]||n[5]||"";t[n[1].toLowerCase()]=e}else n=/^\s*(\S+)/.exec(e),t[n[1]]="true";e=e.slice(n[0].length)}return t}(n),o=r["data-name"]||r.id;return o?(/box/.test(r.class)?t[o]=s:/aside/.test(r.class)?t[o]=`\x3c!-- BEGIN-ASIDE ${o} --\x3e${s}\x3c!-- END-ASIDE --\x3e`:/setting/.test(r.class)?a[o]=s:/menu/.test(r.class)?l[o]=s:/toc/.test(r.class)?c[o]=s:i[o]=s,`\x3c!-- macro ${o} --\x3e`):h("id or data-name missing on macro")}));let f=(e,t)=>{let n=l.item,i={NAME:e.name};if(e.subitems)n=l["toc-dropdown"]?l["toc-dropdown"]:0==t?l["top-dropdown"]:l["inner-dropdown"],i.ITEMS=e.subitems.map((e=>f(e,t+1))).join("\n");else{if(/^-+$/.test(e.name)&&(n=l.divider),e.path&&!/^(https?:|\/)/.test(e.path))return h("Invalid link: "+e.path);i.LINK=e.path}return m(n,i,["ITEMS"])},g=[{name:lf("Docs"),href:"/docs"}];const b=e.TOC||p.TOC||[];let y=[],v=t=>{for(let e of t.subitems||[])if(v(e))return y.push(t),!0;return!(!e.filepath||!t.path||0!=e.filepath.indexOf(t.path))&&(y.push(t),!0)};b.forEach(v);let w=(t,n)=>{let i=c.item,s={NAME:t.name};return t.path&&!/^(https?:|\/)/.test(t.path)?h("Invalid link: "+t.path):(/^\//.test(t.path)&&e.versionPath&&(t.path=`/${e.versionPath}${t.path}`),s.LINK=t.path,y.indexOf(t)>=0?(s.ACTIVE="active",s.EXPANDED="true",g.push({name:t.name,href:t.path})):s.EXPANDED="false",t.subitems&&t.subitems.length>0?(i=c["toc-dropdown"]?""!==t.name?c["toc-dropdown"]:c["toc-dropdown-noLink"]:0==n?""!==t.name?c["top-dropdown"]:c["top-dropdown-noHeading"]:1==n?c["inner-dropdown"]:c["nested-dropdown"],s.ITEMS=t.subitems.map((e=>w(e,n+1))).join("\n")):/^-+$/.test(t.name)&&(i=c.divider),m(i,s,["ITEMS"]))};d.menu=(p.docMenu||[]).map((e=>f(e,0))).join("\n"),d.TOC=b.map((e=>w(e,0))).join("\n"),p.appStoreID&&(d.appstoremeta=`<meta name="apple-itunes-app" content="app-id=${n.htmlEscape(p.appStoreID)}"/>`);let k="";g.length>1&&(k=`\n <nav class="ui breadcrumb" aria-label="${lf("Breadcrumb")}">\n ${g.map(((e,t)=>`<a class="${t==g.length-1?"active":""} section"\n href="${u(e.href)}" aria-current="${t==g.length-1?"page":""}">${u(e.name)}</a>`)).join('<i class="right chevron icon divider"></i>')}\n </nav>`),d.breadcrumb=k,p.boardName&&(d.boardname=u(p.boardName)),p.boardNickname&&(d.boardnickname=u(p.boardNickname)),p.driveDisplayName&&(d.drivename=u(p.driveDisplayName)),p.homeUrl&&(d.homeurl=u(p.homeUrl)),d.targetid=p.id||"???",d.targetname=p.name||"Microsoft MakeCode",d.docsheader=p.docsHeader||"Documentation",d.orgtitle="MakeCode";const A=p.docsLogo&&n.htmlEscape(p.docsLogo),x=(p.organizationWideLogo||p.organizationLogo)&&n.htmlEscape(p.organizationWideLogo||p.organizationLogo),T=p.organizationLogo&&n.htmlEscape(p.organizationLogo);d.targetlogo=A?`<img aria-hidden="true" role="presentation" class="ui ${p.logoWide?"small":"mini"} image" src="${A}" />`:"",d.orglogo=x?`<img aria-hidden="true" role="presentation" class="ui image" src="${x}" />`:"",d.orglogomobile=T?`<img aria-hidden="true" role="presentation" class="ui image" src="${T}" />`:"";let E=e.ghEditURLs||[];if(E.length){let e='<p style="margin-top:1em">\n',t=lf("Edit this page on GitHub");for(let n of E)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 C=`\n <a href="#maincontent" class="ui item link" tabindex="0" role="menuitem">${lf("Skip to main content")}</a>\n `;d.accMenu=C;const I=lf("Print this page"),U=`\n <button id="printbtn" class="circular ui icon right floated button hideprint" title="${I}" aria-label="${I}">\n <i class="icon print"></i>\n </button>\n `;d.printBtn=U;const S=`\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=S;const N=["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=N[0],d.searchBar2=N[1];let P="";p.accentColor&&(P+=`\n.ui.accent { color: ${p.accentColor}; }\n.ui.inverted.accent { background: ${p.accentColor}; }\n`),d.targetstyle=P,d.tocclass=p.lightToc?"lighttoc":"inverted";for(let e of Object.keys(p)){let t=p[e];void 0===d[e]&&"string"==typeof t&&(d[e]=t)}e.finish=()=>m(e.html,d,["body","menu","accMenu","TOC","prev","next","printBtn","breadcrumb","targetlogo","orglogo","orglogomobile","github","JSON","appstoremeta","sidebarToggle","searchBar1","searchBar2"])}function f(e){e.image=function(e,t,n){let i='<img class="ui image" src="'+e+'" alt="'+n+'"';return t&&(i+=' title="'+t+'"'),i+=' loading="lazy"',i+=this.options.xhtml?"/>":">",i},e.listitem=function(e){const t=/^\s*\[( |x)\]/i.exec(e);return t?`<li class="${" "==t[1]?"unchecked":"checked"}">`+e.slice(t[0].length)+"</li>\n":"<li>"+e+"</li>\n"},e.heading=function(e,t,n){let i=/(.*)#([\w\-]+)\s*$/.exec(e),s="";return i?(e=i[1],s=i[2]):s=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}${s}">${e}</h${t}>`}}function g(e,t){return e.replace(/<!--\s*@(ifn?def)\s+(\w+)\s*-->([^]*?)<!--\s*@endif\s*-->/g,((e,n,i,s)=>"ifdef"==n&&t[i]||"ifndef"==n&&!t[i]?`\x3c!-- ${n} ${i} --\x3e${s}\x3c!-- endif --\x3e`:`\x3c!-- ${n} ${i} endif --\x3e`))}function m(e,t,i=[]){return e?e.replace(/@(\w+)@/g,((e,s)=>{let r=n.lookup(t,s)||"";return r+="",i.indexOf(s)<0&&(r=u(r)),r})):""}t.prepTemplate=p,t.setupRenderer=f,t.renderConditionalMacros=g,t.renderMarkdown=function(e){let s=!0;e.pubinfo||(s=!1,e.pubinfo={});let r=e.pubinfo;if(e.theme||(e.theme={}),delete e.pubinfo.private,r.time){let e=parseInt(r.time);r.timems||(r.timems=1e3*e+""),r.humantime||(r.humantime=n.isoTime(e))}r.name&&(r.dirname=r.name.replace(/[^A-Za-z0-9_]/g,"-"),r.title=r.name),s&&(r.JSON=JSON.stringify(r,null,4).replace(/</g,"\\u003c"));let a=e.template;a=a.replace(/<!--\s*@include\s+(\S+)\s*-->/g,((t,n)=>"\x3c!-- include "+n+" --\x3e\n"+((e.theme.htmlDocIncludes||{})[n]||"")+"\n\x3c!-- end include --\x3e\n")),a=g(a,r),e.locale&&(a=y(a,e.locale).text);let o={html:a,theme:e.theme,filepath:e.filepath,versionPath:e.versionPath,ghEditURLs:e.ghEditURLs,params:r,TOC:e.TOC};p(o),i||(i=t.requireMarked());let l=new i.Renderer;f(l);const c=l.link;l.link=function(e,t,n){const i=new RegExp("^[/#]").test(e),s=i?"":"_blank";i&&o.versionPath&&(e=`/${o.versionPath}${e}`);return c.call(l,e,t,n).replace(/^<a /,`<a ${s?`target="${s}"`:""} rel="nofollow noopener" `)};let b=t.requireDOMSanitizer();i.setOptions({renderer:l,gfm:!0,tables:!0,breaks:!1,pedantic:!1,sanitize:!0,sanitizer:b,smartLists:!0,smartypants:!0});let v=e.markdown;e.repo&&(v+=`\n\`\`\`package\n${e.repo.name.replace(/^pxt-/,"")}=github:${e.repo.fullName}#${e.repo.tag||"master"}\n\`\`\`\n`),v=v.replace(/^\s*https?:\/\/(\S+)\s*$/gm,((e,t)=>{for(let e of d){let n=e.rx.exec(t);if(n)return e.cmd.replace(/\$(\d+)/g,((e,t)=>n[parseInt(t)]||""))+"\n"}return e})),v=v.replace(/@([a-z]+)@/gi,((t,i)=>{let s=r[i];return!s&&e.throwOnError&&n.userError(`unknown macro ${i}`),s||"unknown macro"}));let w=i(v);w=w.replace(/<br\s*\/>/gi,"<br/>"),w=w.replace(/(<img [^>]* src=")\/docs\/static\/([^">]+)"/g,((e,t,n)=>t+"/static/"+n+'"'));let k="",A=0;function x(e,t,n){let i=n;return e<=A&&(i=k+i,k="",A=0),i}if(w=w.replace(/<h(\d)[^>]+>\s*([~@])?\s*(.*?)<\/h\d>/g,((t,i,s,a)=>{let l=/^(\w+)\s+(.*)/.exec(a),c=l?l[1]:a,d=l?l[2]:"";if(d=u(d),c=u(c),i=parseInt(i),s){if("@"==s){let t=n.lookup(o.settings,c);if(null!=t)r[c]=d;else if(t=n.lookup(o.macros,c),null==t)return e.throwOnError&&n.userError(`Unknown command: @${c}`),h(`Unknown command: @${c}`);return x(i,0,m(t,{ARGS:d,CMD:c},["ARGS","CMD"]))}{if(!c){let e=k;return k="",e}let t=n.lookup(o.boxes,c);if(t){let e=t.split("@BODY@"),n=x(i,0,e[0].replace("@ARGS@",d));k=e[1];let s=t.match(/data-[^>\s]+/gi);return s&&s.indexOf("data-inferred")>=0&&(A=i),n}return e.throwOnError&&n.userError(`Unknown box: ~ ${c}`),h(`Unknown box: ~ ${c}`)}}return x(i,0,t)})),k&&(w+=k),!r.title){let e=/<h1[^<>]*>([^<>]+)<\/h1>/.exec(w);e&&(r.title=u(e[1]))}if(!r.description){let e=/<p>([^]+?)<\/p>/.exec(w);e&&(r.description=u(e[1]))}const T=/<div class="ui embed mdvid"[^<>]+?data-placeholder="([^"]+)"[^>]*\/?>/i.exec(w)||/<img class="ui [^"]*image" src="([^"]+)"[^>]*\/?>/i.exec(w);T&&(r.cardLogo=u(T[1])),r.twitter=u(e.theme.twitter||"@msmakecode");let E={main:""};w=w.replace(/<!-- BEGIN-ASIDE (\S+) -->([^]*?)<!-- END-ASIDE -->/g,((e,t,i)=>{let s=n.lookup(E,t);return E[t]=(s||"")+i,"\x3c!-- aside --\x3e"})),w=w.replace(/\n<\/code>/g,"</code>"),E.main=w,w="";for(let e of Object.keys(E))w+=(C=e+"-container",I=E[e],m(o.boxes[C]||"@BODY@",{BODY:I},["BODY"]));var C,I;r.body=w,r.name=r.title||"";for(let t of Object.keys(e.theme)){let n=e.theme[t];"string"==typeof n&&(r["theme_"+t]=n)}return o.finish()},t.embedUrl=function(e,t,n,i){return`<div style="position:relative;height:0;padding-bottom:70%;overflow:hidden;"><iframe style="position:absolute;top:0;left:0;width:100%;height:100%;" src="${`${e}#${t}:${n}`}" frameborder="0" sandbox="allow-popups allow-forms allow-scripts allow-same-origin"></iframe></div>`},t.runUrl=function(e,t,n){return`<div style="position:relative;height:0;padding-bottom:${t};overflow:hidden;"><iframe style="position:absolute;top:0;left:0;width:100%;height:100%;" src="${e}?id=${encodeURIComponent(n)}" allowfullscreen="allowfullscreen" sandbox="allow-popups allow-forms allow-scripts allow-same-origin" frameborder="0"></iframe></div>`},t.codeEmbedUrl=function(e,t,n){const i=`${e}---codeembed#pub:${t}`;return`<div style="position:relative;height:calc(${n=Math.ceil(n||300)}px + 5em);width:100%;overflow:hidden;"><iframe style="position:absolute;top:0;left:0;width:100%;height:100%;" src="${i}" allowfullscreen="allowfullscreen" frameborder="0" sandbox="allow-scripts allow-same-origin"></iframe></div>`};const b={b:1,strong:1,em:1};function y(e,t){const i={};function s(e){let s=/^(\s*)([^]*?)(\s*)$/.exec(e),r=s[2].replace(/\s+/g," ");if(""==r||/^((IE=edge,.*|width=device-width.*|(https?:\/\/|\/)[\w@\/\.]+|@[\-\w]+@|\{[^\{\}]+\}|[^a-zA-Z]*|( )+)\s*)+$/.test(r))return null;let a=n.lookup(t,r);return a?r=a:i[r]="",s[1]+r+s[3]}function r(e){return e.replace(/&llt;/g,"<").replace(/&ggt;/g,">")}return{text:e=(e=(e=(e="<start>"+(e=e.replace(/<([\/\w]+)([^<>]*)>/g,((e,t,n)=>{let i=t.replace(/^\//,"").toLowerCase();return 1===b[i]?"&llt;"+t+n+"&ggt;":e})))).replace(/(<([\/\w]+)([^<>]*)>)([^<>]+)/g,((e,t,n,i,a)=>{if("script"==n||"style"==n)return r(e);let o=s(r(a));return null==o?r(e):t+o}))).replace(/(<[^<>]*)(content|placeholder|alt|title)="([^"]+)"/g,((e,t,n,i)=>null==s(i)?e:t+n+'="'+i.replace(/"/g,"''")+'"'))).replace(/^<start>/g,""),missing:i}}function v(e,t){if(e.id==t)return e;for(let n of e.children){let e=v(n,t);if(e)return e}return null}function w(e,t){let n=0,i=[{level:0,id:"",title:"",start:n,text:"",children:[]}],s=(e=e.replace(/\r/g,"")).split(/\n/),r={};for(let e of s){let s=/^\s*(#+)\s*(.*?)(#(\S+)\s*)?$/.exec(e),a=null;if(t&&s)if(s[4])if(r[s[4]])s=null;else{a=v(t,s[4]);let e=t=>{t.id&&(r[t.id]=!0),t.children.forEach(e)};a&&e(a)}else s=null;if(s){let r={level:t?1:s[1].length,title:s[2].trim(),id:s[4]||"",start:n,text:"",children:[]};if(a){e="";for(let t=0;t<a.level;++t)e+="#";e+=" ",e+=r.title||a.title,e+=" #"+r.id}for(;i[i.length-1].level>=r.level;)i.pop();i[i.length-1].children.push(r),i.push(r)}i[i.length-1].text+=e+"\n",n++}return i[0]}t.translate=y,t.buildTOC=function(n){if(!n)return null;const i=e.docs.requireMarked(),s=t.requireDOMSanitizer(),r={renderer:new i.Renderer,gfm:!0,tables:!1,breaks:!1,pedantic:!1,sanitize:!0,sanitizer:s,smartLists:!1,smartypants:!1};let a={name:"dummy",subitems:[]},o=[];o.push(a);let l=i.lexer(n,r),c=!1;l.forEach((e=>{switch(e.type){case"heading":e.depth;break;case"list_start":break;case"list_item_start":case"loose_item_start":c=!0;let t={name:"",path:"",subitems:[]};return void o.push(t);case"text":let n=o[o.length-1];e.text.indexOf("[")>=0?e.text.replace(/\[(.*?)\]\((.*?)\)/i,(function(e,t,i){n.name=t,n.path=i.replace(".md","")})):c&&(n.name=e.text);break;case"list_item_end":case"loose_item_end":let i=o.pop();o[o.length-1].subitems.push(i)}c=!1}));let u=a.subitems;return u&&0!=u.length?u:null},t.visitTOC=function(e,t){e.forEach((function(e){t(e),e.subitems&&e.subitems.forEach(t)}))};let k=!1;function A(e,t){if(k||function(){function e(e,t,n){let i=A(e,t).trim();if(i!=(n=n.trim()))throw console.log(`*** Template:\n${e}\n*** Input:\n${t}\n*** Expected:\n${n}\n*** Output:\n${i}`),new Error("augment docs test fail")}k=!0;let t="\n# T0\n## Examples #ex\n### Example 1\nTEx1\n### Example 2 #ex2\nTEx2\n### Example 3\nTEx3\n\n## See also #also\nTAlso\n",n="\n# @extends\n# #ex2\nMy example\n## See Also These! #also\nMy links\n",i="\n# T0\n## Examples #ex\n### Example 1\nTEx1\n### Example 2 #ex2\nMy example\n### Example 3\nTEx3\n\n## See Also These! #also\nMy links\n",s="\n# @extends\n### #ex\nFoo\n#### Example 1\nEx1\n#### Example 2x #ex2\nEx2\n## See Also These! #also\nMy links\n",r="\n# T0\n## Examples #ex\nFoo\n#### Example 1\nEx1\n#### Example 2x #ex2\nEx2\n## See Also These! #also\nMy links\n";e(t,"",t),e(t," ",t),e(t,n,i),e(t,s,r)}(),!t)return e;let i=w(e,null),s=w(t,i),r={},a={};for(let e of s.children)n.assert(0==e.children.length),n.assert(!!e.id),r[e.id]=e.text;let o=e=>{e.id&&void 0!==r[e.id]&&(a[e.id]=!0,e.text=r[e.id],e.children=[]),e.children.forEach(o)};o(i);let l="",c=e=>{l+=e.text,e.children.forEach(c)};c(i);let u="",d=s.text.replace(/^\s*#+\s*@extends.*/gm,"").replace(/^\s*\n/gm,"");d.trim()&&(u+=d.trim()+"\n");for(let e of s.children)a[e.id]||(u+=e.text);return u&&(l+="## Couldn't apply replacement logic to:\n"+u),l}t.augmentDocs=A}(e.docs||(e.docs={}))}(pxt||(pxt={})),function(e){!function(e){e.el=function(e,t,n){const i=document.createElement(e);return t&&Object.keys(t).forEach((e=>i.setAttribute(e,t[e]+""))),function e(t){Array.isArray(t)?t.forEach((t=>e(t))):"string"==typeof t?i.appendChild(document.createTextNode(t)):t instanceof HTMLElement&&i.appendChild(t)}(n),i}}(e.dom||(e.dom={}))}(pxt||(pxt={})),function(e){!function(t){function n(e){const t=/```package\s+((.|\s)+?)\s*```/i.exec(e);let n;return t&&(n={},t[1].split("\n").map((e=>e.replace(/\s*/g,""))).filter((e=>!!e)).map((e=>e.split("="))).forEach((e=>n[e[0]]=e[1]||"*"))),n}function i(e){const t=/```config\s+((.|\s)+?)\s*```/i.exec(e);let n=[];return t&&t[1].split("\n").map((e=>e.replace(/\s*/g,""))).filter((e=>!!e)).map((e=>e.split("="))).filter((e=>"feature"==e[0]&&!!e[1])).forEach((e=>n.push(e[1]))),n.length?n:void 0}function s(t){const n=/```jres\s+((.|\s)+?)\s*```/i.exec(t);if(n){const t=n[1],i=JSON.parse(t);return{jres:t,ts:e.emitTilemapsFromJRes(i)}}}function r(t){const n=/```assetjson\s+((.|\s)+?)\s*```/i.exec(t);return n?e.tutorial.parseAssetJson(n[1]):{}}function a(t){let n=e.Util.jsonTryParse(t);return n&&!Array.isArray(n)&&(n=[n]),(null==n?void 0:n.length)?n:(n=t.split(/^---$/gm).filter((e=>!!e)).map((e=>{let t={};return e.replace(/^\s*(?:-|\*)\s+(\w+)\s*:\s*(.*)$/gm,((e,n,i)=>{if("flags"==n)t[n]=i.split(",");else if("otherAction"===n){const e=i.split(",").map((e=>null==e?void 0:e.trim()));(t.otherActions||(t.otherActions=[])).push({url:e[0],editor:e[1],cardType:e[2]})}else t[n]=i;return""})),!!Object.keys(t).length&&t})).filter((e=>!!e)),(null==n?void 0:n.length)?n:void 0)}function o(t){if(!t)return[];const n=[];let i,s=!1,r="";return t.split(/\r?\n/).forEach((t=>{if(/^## /.test(t))i=t.substr(2).trim();else if(/^(### ~ |```)codecard$/.test(t))s=!0;else if(/^(### ~|```)$/.test(t)){if(s=!1,i&&r){const t=a(r);(null==t?void 0:t.length)?n.push({name:i,cards:t}):e.log("invalid gallery format")}r="",i=void 0}else s&&(r+=t+"\n")})),n.forEach((t=>t.cards.forEach((t=>{if(t.otherActions&&!t.otherActions.length&&("tutorial"==t.cardType||"example"==t.cardType)){const n=["js"];e.appTarget.appTheme.python&&n.unshift("py"),t.otherActions=n.map((e=>({url:t.url,cardType:t.cardType,editor:e})))}})))),n}t.parsePackagesFromMarkdown=n,t.parseFeaturesFromMarkdown=i,t.parseJResFromMarkdown=s,t.parseTemplateProjectJSON=r,t.parseExampleMarkdown=function(t,a){if(!a)return;const o=/```(blocks?|typescript|python|spy|sim)\s+((.|\s)+?)\s*```/i.exec(a);if(!o)return;const l=n(a),c=o[1],u=o[2],d=i(a),h=s(a),p={name:t,filesOverride:{[e.MAIN_BLOCKS]:'<xml xmlns="http://www.w3.org/1999/xhtml"></xml>',["python"===o[1]?e.MAIN_PY:e.MAIN_TS]:u},dependencies:l,features:d,snippetType:c,source:u};return p.filesOverride=Object.assign(Object.assign({},p.filesOverride),r(a)),h&&(p.filesOverride[e.TILEMAP_JRES]=h.jres,p.filesOverride[e.TILEMAP_CODE]=h.ts),p},t.parseCodeCards=a,t.parseCodeCardsHtml=function(t){let n,i=[];return Array.from(t.children).forEach((e=>{"UL"===e.tagName||"OL"===e.tagName?(n||(n={}),Array.from(e.querySelectorAll("li")).forEach((e=>{const t=e.innerText,i=/^\s*(\w+)\s*:\s*(.*)$/.exec(t);if(i){const e=i[1];n[e]=i[2].trim(),"flags"===e&&(n[e]=n[e].split(/,\s*/))}}))):"HR"==e.tagName&&(n&&i.push(n),n=void 0)})),n&&i.push(n),0===i.length&&"CODE"===t.tagName&&(i=e.Util.jsonTryParse(t.textContent)),!!(null==i?void 0:i.length)&&i},t.parseGalleryMardown=o,t.loadGalleryAsync=function(t){return e.Cloud.markdownAsync(t).then((e=>o(e)))},t.codeCardsToMarkdown=function(e){return`### ~ codecard\n\n${(e||[]).map((e=>Object.keys(e).filter((t=>!!e[t])).map((t=>"otherActions"===t?e[t].map((e=>`* otherAction: ${e.url}, ${e.editor||""}, ${e.cardType||""}`)).join("\n"):`* ${t}: ${e[t]}`)).join("\n"))).join("\n\n---\n\n")}\n\n### ~\n`}}(e.gallery||(e.gallery={}))}(pxt||(pxt={})),function(e){e.GDBServer=class{constructor(t){this.io=t,this.q=new e.U.PromiseQueue,this.dataBuf="",this.numSent=0,this.pktSize=400,this.trace=!1,this.bmpMode=!0,this.targetInfo="",this.onEvent=e=>{},this.io.onData=e=>this.onData(e)}onData(t){for(this.dataBuf+=e.U.uint8ArrayToString(t);this.dataBuf.length>0;){let e=this.dataBuf[0];if("+"==e)this.dataBuf=this.dataBuf.slice(1);else if("$"==e||"%"==e){let t=this.decodeResp(this.dataBuf.slice(1));if(null==t)break;"$"==e?(this.io.sendPacketAsync(this.buildCmd("+")),this.onResponse?this.onResponse(t):this.numSent>0&&this.io.error("unexpected response: "+t)):this.onEvent(t)}else this.io.error("invalid character: "+e)}}buildCmd(t){if("+"==t)return e.U.stringToUint8Array(t);let n="";for(let e=0;e<t.length;++e){let i=t.charAt(e);"}"==i||"#"==i||"$"==i?(n+="}",n+=String.fromCharCode(32^i.charCodeAt(0))):n+=i}let i=0;t=n;for(let e=0;e<t.length;++e)i=i+t.charCodeAt(e)&255;return n="$"+t+"#"+("0"+i.toString(16)).slice(-2),e.U.stringToUint8Array(n)}decodeResp(e){let t="";for(let n=0;n<e.length;++n){let i=e[n];if("}"==i)++n,t+=String.fromCharCode(32^e.charCodeAt(n));else if("*"==i){++n;let i=e.charCodeAt(n)-29,s=t.charAt(t.length-1);for(;i-- >0;)t+=s}else{if("#"==i){return 2==e.slice(n+1,n+3).length?(this.dataBuf=e.slice(n+3),t):null}t+=i}}return null}sendCmdOKAsync(e){return this.sendCmdAsync(e,(e=>"OK"==e))}error(e){this.io.error(e),this.io.disconnectAsync()}sendCmdAsync(t,n){this.numSent++;const i=this.buildCmd(t);return this.q.enqueue("one",(()=>null===n?this.io.sendPacketAsync(i).then((()=>null)):new Promise((s=>{this.onResponse=i=>{this.onResponse=null,this.trace&&e.log(`GDB: '${t}' -> '${i}'`),void 0===n||n(i)||this.error(`Invalid GDB command response: '${t}' -> '${i}'`),s(i)},this.io.sendPacketAsync(i)}))))}sendRCmdAsync(t){return this.sendMCmdAsync("qRcmd,"+(n=t,e.U.toHex(e.U.stringToUint8Array(n))));var n}sendMCmdAsync(t){this.numSent++;const n=this.buildCmd(t);let i="";return this.q.enqueue("one",(()=>new Promise((s=>{this.onResponse=n=>{var r;"OK"!=n&&"O"==n[0]?i+=(r=n.slice(1),e.U.uint8ArrayToString(e.U.fromHex(r))):("OK"!=n&&(i+=" - "+n),this.onResponse=null,this.trace&&e.log(`Final GDB: '${t}' -> '${i}'`),s(i))},this.io.sendPacketAsync(n)}))))}write32Async(t,n){let i=new Uint8Array(4);return e.HF2.write32(i,0,n),this.writeMemAsync(t,i)}writeMemAsync(t,n){const i=this.pktSize/2-10;return e.U.assert(n.length<i),this.sendCmdOKAsync("M"+t.toString(16)+","+n.length.toString(16)+":"+e.U.toHex(n)).then((e=>{console.log(e)}))}readMemAsync(t,n){const i=this.pktSize/2-6;if(n>i){const s=new Uint8Array(n),r=a=>{const o=Math.min(n-a,i);return 0==o?Promise.resolve(s):this.readMemAsync(t+a,o).then((t=>(e.U.memcpy(s,a,t),r(a+o))))};return r(0)}return this.sendCmdAsync("m"+t.toString(16)+","+n.toString(16)).then((t=>e.U.fromHex(t)))}initBMPAsync(){return Promise.resolve().then((()=>this.sendRCmdAsync("swdp_scan"))).then((e=>(this.targetInfo=e,this.sendCmdAsync("vAttach;1",(e=>"T"==e[0]))))).then((()=>{}))}initAsync(){return e.U.delay(1e3).then((()=>this.sendCmdAsync("!"))).then((()=>this.sendCmdAsync("qSupported"))).then((t=>{let n={};return t=(t=";"+t+";").replace(/;([^;]+)[=:]([^:;]+)/g,((e,t,i)=>(n[t]=i,";"))),this.pktSize=parseInt(n.PacketSize)||1024,e.log("GDB-server caps: "+JSON.stringify(n)+" "+t.replace(/;+/g,";")),this.bmpMode?this.initBMPAsync():this.sendCmdAsync("c").then((()=>{}))}))}}}(pxt||(pxt={})),function(e){!function(t){function n(){var n,i;return!!t.forceProxy||!e.U.isNodeJS&&!(null===(i=null===(n=null==e?void 0:e.appTarget)||void 0===n?void 0:n.cloud)||void 0===i?void 0:i.noGithubProxy)}t.token=null,t.forceProxy=!1;const i={};function s(n){var i;return n.method=null!==(i=n.method)&&void 0!==i?i:"GET",function i(s){var r;const a=e.U.clone(n);t.token&&(a.headers||(a.headers={}),a.url==P?a.headers.Authorization=`bearer ${t.token}`:(a.url=e.BrowserUtils.cacheBustingUrl(a.url),a.headers.Authorization=`token ${t.token}`));return a.allowHttpErrors=null!==(r=a.allowHttpErrors)&&void 0!==r&&r,e.U.requestAsync(a).catch((n=>{if(e.tickEvent("github.error",{statusCode:n.statusCode}),t.handleGithubNetworkError){if(t.handleGithubNetworkError(a,n))return i(!1)}throw n}))}(t.token)}function r(e){return s({url:e,method:"GET"}).then((e=>e.json))}function a(t){return e.Cloud.apiRequestWithCdnAsync({url:"gh/"+t,forceLiveEndpoint:!0}).then((e=>e.json))}function o(t){e.log(`github proxy error: ${t.message}`),e.debug(t)}t.isOrgAsync=function(e){return s({url:`https://api.github.com/orgs/${e}`,method:"GET",allowHttpErrors:!0}).then((e=>200==e.statusCode))};class l{constructor(){this.configs={},this.packages={}}proxyWithCdnLoadPackageAsync(t,n){const i=`${t}/${n}`;let s=this.packages[i];if(s)return e.debug(`github cache ${t}/${n}/text`),Promise.resolve(s);const r=E(t);return a(U(r.slug,n,r.fileName,"text")).then((e=>this.packages[i]={files:e}))}cacheConfig(t,n){const i=e.Package.parseAndValidConfig(n);return this.configs[t]=i,e.U.clone(i)}async loadConfigAsync(t,i){i||(i="master");const s=`${t}/${i}`;let r=this.configs[s];if(r)return e.debug(`github cache ${t}/${i}/config`),e.U.clone(r);if(n())try{const n=await this.proxyWithCdnLoadPackageAsync(t,i);return this.cacheConfig(s,n.files[e.CONFIG_NAME])}catch(e){o(e)}const a=await u(t,i,e.CONFIG_NAME);return this.cacheConfig(s,a)}async loadPackageAsync(t,i){if(i||(i="master"),n())try{return await this.proxyWithCdnLoadPackageAsync(t,i).then((t=>e.U.clone(t)))}catch(e){o(e)}return await this.githubLoadPackageAsync(t,i)}githubLoadPackageAsync(t,n){return m(t,n).then((i=>{const s=`${t}/${i}`;let r=this.packages[s];return r?(e.debug(`github cache ${t}/${n}/text`),Promise.resolve(e.U.clone(r))):(e.log(`Downloading ${t}/${n} -> ${i}`),u(t,i,e.CONFIG_NAME).then((n=>{const r={files:{}};r.files[e.CONFIG_NAME]=n;const a=JSON.parse(n);return e.U.promiseMapAll(e.allPkgFiles(a).slice(1),(e=>u(t,i,e).then((t=>{r.files[e]=t})))).then((()=>(this.packages[s]=r,e.U.clone(r))))})))}))}}function c(t,n,r){return s({url:"https://api.github.com/repos/"+U(t.slug,"contents",t.fileName,r+"?ref="+n),method:"GET"}).then((n=>{const s=n.json;return i[t.slug]=!0,s&&"base64"==s.encoding&&null!=s.content?atob(s.content):e.U.httpGetTextAsync(s.download_url)}))}function u(t,n,s){const r=E(t);return i[r.slug]?c(r,n,s):e.U.requestAsync({url:"https://raw.githubusercontent.com/"+U(r.slug,n,r.fileName,s),allowHttpErrors:!0}).then((e=>200==e.statusCode?e.text:c(r,n,s)))}function d(e,t,n,i){return s({url:/^https:/.test(e)?e:"https://api.github.com/repos/"+e,headers:n,method:i||"POST",data:t,successCodes:[200,201,202,204]}).then((e=>e.json))}function h(e,t){let n=1;for(;e.refs[t+n];)n++;return t+n}async function p(e,t,n){return await d(e+"/git/refs",{ref:"refs/heads/"+t,sha:n}),t}function f(i,s="tags",a,o){const l=E(i),c=(u=a,!!t.forceProxy||!(t.token&&!u)&&n());var u;let d=null;const h=c?e.U.httpGetJsonAsync(e.BrowserUtils.cacheBustingUrl(`${e.Cloud.apiRoot}gh/${l.slug}/refs${o?"?nocache=1":""}`)).then((t=>{let n=Object.keys(t.refs).filter((t=>e.U.startsWith(t,"refs/"+s+"/"))).map((e=>({ref:e,object:{sha:t.refs[e]}})));return d=t.refs.HEAD,n})):r(`https://api.github.com/repos/${l.slug}/git/refs/${s}/?per_page=100`);let p=e=>e.replace(/^refs\/[^\/]+\//,"");return h.then((t=>{t.sort(((t,n)=>e.semver.strcmp(p(t.ref),p(n.ref))));let n={};for(let e of t)n[p(e.ref)]=e.object.sha;return{refs:n,head:d}}),(e=>404==e.statusCode?{refs:{}}:Promise.reject(e)))}function g(e){return"commit"==e.object.type?Promise.resolve(e.object.sha):"tag"==e.object.type?r(e.object.url).then((e=>"commit"==e.object.type?e.object.sha:Promise.reject(new Error("Bad type (2nd order) "+e.object.type)))):Promise.reject(new Error("Bad type "+e.object.type))}function m(e,t){if(/^[a-f0-9]{40}$/.test(t))return Promise.resolve(t);const n=E(e);return r(`https://api.github.com/repos/${n.slug}/git/refs/tags/${t}`).then(g,(e=>r(`https://api.github.com/repos/${n.slug}/git/refs/heads/${t}`).then(g)))}function b(e,n="master"){return t.db.loadConfigAsync(e,n)}function y(n,i){const s=E(n);return s?x(s,i)?(e.tickEvent("github.download.banned"),e.log("Github repo is banned"),Promise.resolve(void 0)):t.db.loadPackageAsync(s.fullName,s.tag).then((t=>{const s=N(i,n);if(s){const i=e.Package.parseAndValidConfig(t.files[e.CONFIG_NAME]);i&&(e.log(`auto-disable ${s.join(",")} due to targetconfig entry for ${n}`),i.disablesVariants=s,t.files[e.CONFIG_NAME]=e.Package.stringifyConfig(i))}return t})):(e.log("Unknown GitHub syntax"),Promise.resolve(void 0))}let v;function w(t){return e.Cloud.cdnApiUrl(`gh/${t.fullName}/icon`)}function k(e,t){var n;if(!e)return;const i={owner:e.owner.login.toLowerCase(),slug:e.full_name.toLowerCase(),fullName:((null==t?void 0:t.fullName)||e.full_name).toLowerCase(),fileName:null===(n=null==t?void 0:t.fileName)||void 0===n?void 0:n.toLocaleLowerCase(),name:e.name,description:e.description,defaultBranch:e.default_branch,tag:null==t?void 0:t.tag,updatedAt:Math.round(new Date(e.updated_at).getTime()/1e3),fork:e.fork,private:e.private};return i.status=A(i,null==t?void 0:t.config),i}function A(e,t){return e?x(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 x(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,i){const s=E(t);if(!s)return;const l=A(s,i);if(l==v.Banned)return;if(n())try{return await function(t,n){return a(t.slug).then((e=>{if(e)return{github:!0,owner:t.owner,fullName:t.fullName,fileName:t.fileName,slug:t.slug,name:t.fileName?`${e.name}-${t.fileName}`:e.name,description:e.description,defaultBranch:e.defaultBranch||"master",tag:t.tag,status:n}})).catch((t=>{e.reportException(t)}))}(s,l)}catch(e){o(e)}return k(await r("https://api.github.com/repos/"+s.slug),{config:i,fullName:s.fullName,fileName:s.fileName,tag:s.tag})}function E(e){if(!e)return;e=(e=e.trim()).replace(/\/$/,"");const t=/^https:\/\/([^./#]+)\.github\.io\/([^/#]+)\/?$/i.exec(e);t&&(e=`github:${t[1]}/${t[2]}`),e=(e=(e=e.replace(/^github:/i,"")).replace(/^https:\/\/github\.com\//i,"")).replace(/\.git\b/i,"");const n=/^([^#\/:]+)\/([^#\/:]+)(\/([^#]+))?(#([^\/:]*))?$/.exec(e);if(!n)return;const i=n[1],s=n[2];let r=n[4];const a=n[6],o=r&&/^tree\/([^\/]+\/)/.exec(r);return o&&(r=r.slice(o[0].length)),{owner:i,project:s,slug:U(i,s),fullName:U(i,s,r),tag:a,fileName:r}}function C(e){return!!e&&"github:"==e.slice(0,7)}function I(e){return e?"github:"+e.fullName.toLowerCase()+"#"+(e.tag||"master"):void 0}function U(...e){return e.filter((e=>!!e)).join("/")}function S(t,n){if(!t||!t.upgrades)return null;const i=E(n);return i?e.U.lookup(t.upgrades,i.fullName.toLowerCase()):null}function N(e,t){const n=S(e,t),i=/^dv:(.*)/.exec(n);if(i){const e=i[1].split(/,/);return e.some((e=>!/^\w+$/.test(e)))?null:e}return null}t.MemoryGithubDb=l,t.downloadTextAsync=u,t.db=new l,t.authenticatedUserAsync=function(){return t.token?r("https://api.github.com/user"):Promise.resolve(void 0)},t.getCommitsAsync=function(e,t){return r("https://api.github.com/repos/"+E(e).slug+"/commits?sha="+t).then((e=>e.map((e=>{const t=e.commit;return t.url=e.url,t.sha=e.sha,t}))))},t.getCommitAsync=function(e,t){return r("https://api.github.com/repos/"+E(e).slug+"/git/commits/"+t).then((e=>r(e.tree.url+"?recursive=1").then((t=>(e.tree=t,e)))))},t.createObjectAsync=function(e,t,n){return d(E(e).slug+"/git/"+t+"s",n).then((e=>e.sha))},t.postCommitComment=function(e,t,n,i,s){return d(`${E(e).slug}/commits/${t}/comments`,{body:n,path:i,position:s}).then((e=>e.id))},t.fastForwardAsync=async function(e,t,n){const i=E(e);return 200==(await s({url:`https://api.github.com/repos/${i.slug}/git/refs/heads/${t}`,method:"PATCH",allowHttpErrors:!0,data:{sha:n,force:!1}})).statusCode},t.putFileAsync=async function(t,n,i){const r=E(t);await s({url:`https://api.github.com/repos/${e.github.join(r.slug,"contents",r.fileName,n)}`,method:"PUT",allowHttpErrors:!0,data:{message:lf("Initialize empty repo"),content:btoa(e.U.toUTF8(i)),branch:"master"},successCodes:[201]})},t.createTagAsync=async function(e,t,n){await d(e+"/git/refs",{ref:"refs/tags/"+t,sha:n})},t.createReleaseAsync=async function(e,t,n){await d(e+"/releases",{tag_name:t,target_commitish:n,name:t,draft:!1,prerelease:!1})},t.createPRFromBranchAsync=async function(e,t,n,i,s){const r=await d(e+"/pulls",{title:i,body:s||lf("Automatically created from MakeCode."),head:n,base:t,maintainer_can_modify:!0});return null==r?void 0:r.html_url},t.mergeAsync=function(t,n,i,r){return s({url:`https://api.github.com/repos/${E(t).slug}/merges`,method:"POST",successCodes:[201,204,409],data:{base:n,head:i,commit_message:r}}).then((n=>{if(201==n.statusCode||204==n.statusCode)return n.json.sha;if(409==n.statusCode)return null;throw e.U.userError(lf("Cannot merge in github.com/{1}; code: {2}",t,n.statusCode))}))},t.getRefAsync=function(e,t){return r("https://api.github.com/repos/"+e+"/git/refs/heads/"+(t=t||"master")).then(g).catch((e=>{404!=e.statusCode&&Promise.reject(e)}))},t.getNewBranchNameAsync=async function(e,t="patch-"){return h(await f(e,"heads"),t)},t.createNewBranchAsync=p,t.forkRepoAsync=async function(t,n,i="pr-"){const s=E(t),r=k(await d(`${s.slug}/forks`,{}),{fullName:s.fullName,fileName:s.fileName}),a=Date.now()+3e5;let o=null;for(;!o&&Date.now()<a;){await e.U.delay(1e3);try{o=await f(r.slug,"heads")}catch(e){}}if(!o)throw new Error(lf("Timeout waiting for fork"));const l=h(o,i);return await p(r.slug,l,n),r.fullName+"#"+l},t.listRefsAsync=function(e,t="tags",n,i){return f(e,t,n,i).then((e=>Object.keys(e.refs)))},t.listRefsExtAsync=f,t.pkgConfigAsync=b,t.downloadPackageAsync=y,t.downloadLatestPackageAsync=async function(t){const n=await e.packagesConfigAsync(),i=await e.github.latestVersionAsync(t.slug,n),s=`${t.fullName}#${i}`;return await e.github.downloadPackageAsync(s,n),{version:`github:${s}`,config:await b(t.fullName,i)}},t.cacheProjectDependenciesAsync=async function(t){var n;const i=null===(n=Object.keys(t.dependencies))||void 0===n?void 0:n.filter((e=>C(t.dependencies[e])));if(i.length){const n=await e.packagesConfigAsync();await Promise.all(i.map((async e=>{const i=t.dependencies[e];if(!await y(i,n))throw new Error(lf("Cannot load extension {0} from {1}",e,i))})))}},function(e){e[e.Unknown=0]="Unknown",e[e.Approved=1]="Approved",e[e.Banned=2]="Banned"}(v=t.GitRepoStatus||(t.GitRepoStatus={})),t.listUserReposAsync=function(){return _('{\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),i=t.readme&&t.readme.text;return!!n&&(n.supportedTargets?n.supportedTargets.indexOf(e.appTarget.id)>-1:i&&i.indexOf("PXT/"+e.appTarget.id)>-1)})).map((e=>k(e,{fullName:e.full_name})))))},t.createRepoAsync=function(e,t,n){return d("https://api.github.com/user/repos",{name:e,description:t,private:!!n,has_issues:!0,has_projects:!1,has_wiki:!1,allow_rebase_merge:!1,allow_merge_commit:!0,delete_branch_on_merge:!1}).then((e=>k(e)))},t.enablePagesAsync=async function(t){const n=E(t);let i;try{const e=await r(`https://api.github.com/repos/${n.slug}/pages`);e&&(i=e.html_url)}catch(e){}if(!i)try{i=(await d(`https://api.github.com/repos/${n.slug}/pages`,{source:{branch:"master",path:"/"}},{Accept:"application/vnd.github.switcheroo-preview+json"})).html_url}catch(t){e.tickEvent("github.pages.error"),e.reportException(t)}if(i){const n=await r(`https://api.github.com/repos/${t}`);if(n&&!n.homepage)try{await d(`https://api.github.com/repos/${t}`,{homepage:i},void 0,"PATCH")}catch(t){e.tickEvent("github.homepage.error")}}},t.repoIconUrl=function(e){if(e.status==v.Approved)return w(e)},t.mkRepoIconUrl=w,t.repoStatus=A,t.repoAsync=T,t.searchAsync=function(t,n){if(!n)return Promise.resolve([]);let i=t.split("|").map(E).filter((e=>!!e));return i.length>0?Promise.all(i.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=>k(e,{config:n,fullName:e.full_name}))).filter((e=>e.status==v.Approved||n.allowUnapproved&&e.status==v.Unknown)).filter((t=>!e.appTarget.appTheme.githubUrl||`https://github.com/${t.fullName}`!=e.appTarget.appTheme.githubUrl.toLowerCase())))).catch((e=>[]))},t.parseRepoId=E,t.toGithubDependencyPath=function(e,t){let n="github:"+e;return t&&(n+="#"+t),n},t.isGithubId=C,t.stringifyRepo=I,t.normalizeRepoId=function(e){const t=E(e);if(t)return t.tag=t.tag||"master",I(t)},t.join=U,t.upgradedPackageReference=function(t,n){const i=S(t,n);if(!i)return null;const s=/^min:(.*)/.exec(i),r=s&&e.semver.tryParse(s[1]);if(r){const t=E(n),i=e.semver.tryParse(t.tag);return i&&e.semver.cmp(i,r)<0?(t.tag=s[1],e.debug(`upgrading ${n} to ${s[1]}`),I(t)):(i||e.log(`not upgrading ${n} - cannot parse version`),null)}return N(t,n)||e.log(`invalid upgrade rule: ${n} -> ${i}`),n},t.upgradedPackageId=function(e,t){const n=N(e,t);return n?t+"?dv="+n.join(","):t},t.latestVersionAsync=function(t,n,i,s){const r=E(t);return r?T(r.slug,n).then((t=>{if(t)return f(t.slug,"tags",i,s).then((i=>{let s=Object.keys(i.refs);s=e.semver.sortLatestTags(s);const a=e.appTarget.versions&&e.semver.tryParse(e.appTarget.versions.target);if(a&&n.releases&&n.releases["v"+a.major]){const i=n.releases["v"+a.major].map((t=>e.github.parseRepoId(t))).filter((e=>e&&e.fullName.toLowerCase()==r.fullName.toLowerCase()))[0];if(i){if(s.some((e=>e==i.tag)))return e.debug(`approved release ${i.fullName}#${i.tag} for v${a.major}`),Promise.resolve(i.tag);e.reportError("packages",`approved release ${i.fullName}#${i.tag} for v${a.major} not found anymore`,{repo:t.fullName})}}return s[0]?Promise.resolve(s[0]):i.head||m(t.slug,t.defaultBranch)}))})):Promise.resolve(null)},t.resolveMonoRepoVersions=function(n){n=e.Util.clone(n);const i={};return Object.keys(n).map((e=>({id:e,ghid:t.parseRepoId(n[e])}))).filter((e=>{var t;return null===(t=e.ghid)||void 0===t?void 0:t.tag})).forEach((t=>{const{id:n,ghid:s}=t;let r=i[s.slug];r||(r=i[s.slug]={tag:s.tag,deps:[]}),r.deps.push(t),e.semver.strcmp(r.tag,s.tag)<0&&(e.debug(`dep: resolve later monorepo tag to ${e.github.stringifyRepo(s)}`),r.tag=s.tag)})),e.U.values(i).forEach((t=>t.deps.forEach((i=>{i.ghid.tag!==t.tag&&(e.debug(`dep: ${e.github.stringifyRepo(i.ghid)} -> ${t.tag}`),i.ghid.tag=t.tag,n[i.id]=e.github.stringifyRepo(i.ghid))})))),n},t.GIT_JSON=".git.json";const P="https://api.github.com/graphql";function _(e){const t=JSON.stringify({query:e});return d(P,t)}t.lookupFile=function(e,t,n){if(!t)return null;const i=U(e.fileName,n);return t.tree.tree.find((e=>e.path==i))},t.ghGraphQLQueryAsync=_,t.findPRNumberforBranchAsync=function(e,t){const n=E(e);return _(`\n{\n repository(owner: ${JSON.stringify(n.owner)}, name: ${JSON.stringify(n.project)}) {\n pullRequests(last: 1, states: [OPEN, MERGED], headRefName: ${JSON.stringify(t)}) {\n edges {\n node {\n number\n state\n mergeable\n baseRefName\n url\n isDraft\n }\n }\n }\n }\n}\n`).then((e=>{const t=e.data.repository.pullRequests.edges[0];if(t&&t.node){const e=t.node;return{number:e.number,mergeable:e.mergeable,state:e.state,title:e.title,url:e.url,base:e.baseRefName}}return{number:-1}}))},t.getPagesStatusAsync=function(e){return r(`https://api.github.com/repos/${e}/pages`).catch((e=>({status:null})))}}(e.github||(e.github={}))}(pxt||(pxt={})),function(e){let t;e.REFCNT_FLASH="0xfffe",e.VTABLE_MAGIC=249,e.ValTypeObject=4,function(e){e[e.BoxedString=1]="BoxedString",e[e.BoxedNumber=2]="BoxedNumber",e[e.BoxedBuffer=3]="BoxedBuffer",e[e.RefAction=4]="RefAction",e[e.RefImage=5]="RefImage",e[e.RefCollection=6]="RefCollection",e[e.RefRefLocal=7]="RefRefLocal",e[e.RefMap=8]="RefMap",e[e.RefMImage=9]="RefMImage",e[e.MMap=10]="MMap",e[e.BoxedString_SkipList=11]="BoxedString_SkipList",e[e.BoxedString_ASCII=12]="BoxedString_ASCII",e[e.ZPin=13]="ZPin",e[e.User0=16]="User0"}(t=e.BuiltInType||(e.BuiltInType={}))}(pxt||(pxt={})),function(e){!function(t){function n(e,t,n){e[t+0]=n>>0&255,e[t+1]=n>>8&255,e[t+2]=n>>16&255,e[t+3]=n>>24&255}function i(e,t,n){e[t+0]=n>>0&255,e[t+1]=n>>8&255}function s(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function r(e,t){return e[t]|e[t+1]<<8}function a(e){let t=new Uint8Array(4*e.length);for(let i=0;i<e.length;++i)n(t,4*i,e[i]);return t}t.HF2_CMD_BININFO=1,t.HF2_MODE_BOOTLOADER=1,t.HF2_MODE_USERSPACE=2,t.HF2_CMD_INFO=2,t.HF2_CMD_RESET_INTO_APP=3,t.HF2_CMD_RESET_INTO_BOOTLOADER=4,t.HF2_CMD_START_FLASH=5,t.HF2_CMD_WRITE_FLASH_PAGE=6,t.HF2_CMD_CHKSUM_PAGES=7,t.HF2_CMD_READ_WORDS=8,t.HF2_CMD_WRITE_WORDS=9,t.HF2_CMD_DMESG=16,t.HF2_FLAG_SERIAL_OUT=128,t.HF2_FLAG_SERIAL_ERR=192,t.HF2_FLAG_CMDPKT_LAST=64,t.HF2_FLAG_CMDPKT_BODY=0,t.HF2_FLAG_MASK=192,t.HF2_SIZE_MASK=63,t.HF2_STATUS_OK=0,t.HF2_STATUS_INVALID_CMD=1,t.HF2_STATUS_EXEC_ERR=2,t.HF2_STATUS_EVENT=128,t.HF2_CMD_JDS_CONFIG=32,t.HF2_CMD_JDS_SEND=33,t.HF2_EV_JDS_PACKET=8388640,t.CUSTOM_EV_JACDAC="jacdac",t.HF2_EV_MASK=8388608,t.write32=n,t.write16=i,t.read32=s,t.read16=r,t.encodeU32LE=a,t.decodeU32LE=function(e){let t=[];for(let n=0;n<e.length;n+=4)t.push(s(e,n));return t};let o=!1;function l(t){o?e.log("HF2: "+t):e.debug("HF2: "+t)}t.enableLog=function(){o=!0};class c{constructor(n){var i;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===(i=e.appTarget.appTheme.downloadDialogTheme)||void 0===i?void 0:i.deviceIcon)||"usb",this.msgs=new e.U.PromiseBuffer,this.eventHandlers={},this.jacdacAvailable=!1,this.onSerial=(e,t)=>{},this.onCustomEvent=(e,t)=>{};let r=[];n.onDeviceConnectionChanged=e=>this.disconnectAsync().then((()=>e&&this.reconnectAsync())),n.onSerial=(e,t)=>this.onSerial(e,t),n.onData=i=>{let s=i[0]&t.HF2_FLAG_MASK,a=63&i[0],o=new Uint8Array(a);if(e.U.memcpy(o,0,i,1,a),s&t.HF2_FLAG_SERIAL_OUT)this.onSerial(o,s==t.HF2_FLAG_SERIAL_ERR);else if(r.push(o),s!=t.HF2_FLAG_CMDPKT_BODY){e.U.assert(s==t.HF2_FLAG_CMDPKT_LAST);let i=0;for(let e of r)i+=e.length;let a=new Uint8Array(i),o=0;for(let t of r)e.U.memcpy(a,o,t),o+=t.length;r=[],a[2]&t.HF2_STATUS_EVENT?n.onEvent(a):this.msgs.push(a)}},n.onEvent=t=>{let n=s(t,0),i=e.U.lookup(this.eventHandlers,n+"");i?i(t.slice(4)):l("unhandled event: "+n.toString(16))},n.onError=e=>{l("recv error: "+e.message),this.autoReconnect&&(this.autoReconnect=!1,this.reconnectAsync().then((()=>{this.autoReconnect=!0}),(e=>{l("reconnect error: "+e.message)})))},this.onEvent(t.HF2_EV_JDS_PACKET,(e=>{this.onCustomEvent(t.CUSTOM_EV_JACDAC,e)}))}resetState(){this.lock=new e.U.PromiseQueue,this.info=null,this.infoRaw=null,this.pageSize=null,this.flashSize=null,this.maxMsgSize=63,this.bootloaderMode=!1,this.msgs.drain()}onEvent(n,i){e.U.assert(!!(n&t.HF2_EV_MASK)),this.eventHandlers[n+""]=i}sendCustomEventAsync(e,n){return e==t.CUSTOM_EV_JACDAC?this.jacdacAvailable?this.talkAsync(t.HF2_CMD_JDS_SEND,n).then((()=>{})):Promise.resolve():Promise.reject(new Error("invalid custom event type"))}reconnectAsync(){return this.resetState(),l(`reconnect raw=${this.rawMode}`),this.io.reconnectAsync().then((()=>this.initAsync())).catch((t=>{if(this.reconnectTries<5)return this.reconnectTries++,l(`error ${t.message}; reconnecting attempt #${this.reconnectTries}`),e.U.delay(500).then((()=>this.reconnectAsync()));throw t}))}disconnectAsync(){return l("disconnect"),this.io.disconnectAsync()}error(e){return this.io.error(e)}talkAsync(s,a){if(this.io.talksAsync)return this.io.talksAsync([{cmd:s,data:a}]).then((e=>e[0]));let o=8;a&&(o+=a.length);let c=new Uint8Array(o),u=65535&++this.cmdSeq;n(c,0,s),i(c,4,u),i(c,6,0),a&&e.U.memcpy(c,8,a,0,a.length);let d=0,h=()=>this.msgs.shiftAsync(1e3).then((e=>{if(r(e,0)!=u){if(d<3)return d++,l(`message out of sync, (${u} vs ${r(e,0)}); will re-try`),h();this.error("out of sync")}let n="";switch(e[3]&&(n="; info="+e[3]),e[2]){case t.HF2_STATUS_OK:return e.slice(4);case t.HF2_STATUS_INVALID_CMD:this.error("invalid command"+n);break;case t.HF2_STATUS_EXEC_ERR:this.error("execution error"+n);break;default:this.error("error "+e[2]+n)}return null}));return this.sendMsgAsync(c).then(h)}sendMsgAsync(e){return this.sendMsgCoreAsync(e)}sendSerialAsync(e,t=!1){return this.io.sendSerialAsync?this.io.sendSerialAsync(e,t):this.sendMsgCoreAsync(e,t?2:1)}sendMsgCoreAsync(e,n=0){let i=new Uint8Array(64),s=r=>{let a=e.length-r;if(a<=0)return Promise.resolve();a>63?(a=63,i[0]=t.HF2_FLAG_CMDPKT_BODY):i[0]=t.HF2_FLAG_CMDPKT_LAST,n&&(i[0]=1==n?t.HF2_FLAG_SERIAL_OUT:t.HF2_FLAG_SERIAL_ERR),i[0]|=a;for(let t=0;t<a;++t)i[t+1]=e[r+t];return this.io.sendPacketAsync(i).then((()=>s(r+a)))};return this.lock.enqueue("out",(()=>s(0)))}switchToBootloaderAsync(){return this.bootloaderMode?Promise.resolve():(l("Switching into bootloader mode"),this.io.isSwitchingToBootloader&&this.io.isSwitchingToBootloader(),this.maybeReconnectAsync().then((()=>this.talkAsync(t.HF2_CMD_START_FLASH).then((()=>{}),(e=>this.talkAsync(t.HF2_CMD_RESET_INTO_BOOTLOADER).then((()=>{}),(e=>{})).then((()=>this.reconnectAsync().catch((e=>{throw"devicenotfound"===e.type&&(e.type="repairbootloader"),e})))))))).then((()=>this.initAsync())).then((()=>{this.bootloaderMode||this.error("cannot switch into bootloader mode")})))}isFlashing(){return!!this.flashing}reflashAsync(t){l("reflash"),e.U.assert(e.appTarget.compile.useUF2);const n=t.outfiles[pxtc.BINARY_UF2],i=pxtc.UF2.parseFile(e.Util.stringToUint8Array(atob(n)));return this.flashing=!0,this.io.reconnectAsync().then((()=>this.flashAsync(i))).then((()=>e.U.delay(100))).finally((()=>this.flashing=!1)).then((()=>this.reconnectAsync()))}writeWordsAsync(n,i){return e.U.assert(i.length<=64),this.talkAsync(t.HF2_CMD_WRITE_WORDS,a([n,i.length].concat(i))).then((()=>{}))}readWordsAsync(i,s){let r=new Uint8Array(8);return n(r,0,i),n(r,4,s),e.U.assert(s<=64),this.talkAsync(t.HF2_CMD_READ_WORDS,r)}pingAsync(){return this.rawMode?Promise.resolve():this.talkAsync(t.HF2_CMD_BININFO).then((e=>{}))}maybeReconnectAsync(){return this.pingAsync().catch((e=>this.reconnectAsync().then((()=>this.pingAsync()))))}flashAsync(i){let s=Date.now(),r=0,a=s=>{if(s>=i.length)return Promise.resolve();let r=i[s],o=new Uint8Array(4+r.payloadSize);return n(o,0,r.targetAddr),e.U.memcpy(o,4,r.data,0,r.payloadSize),this.talkAsync(t.HF2_CMD_WRITE_FLASH_PAGE,o).then((()=>a(s+1)))};return this.switchToBootloaderAsync().then((()=>{let e=256*i.length;return l(`Starting flash (${Math.round(e/1024)}kB).`),r=Date.now(),this.pageSize>16384?i:u(i,((e,t)=>this.readWordsAsync(e,t)))})).then((e=>{if(e.length!=i.length){let t=256*(i=e).length;l(`Performing partial flash (${Math.round(t/1024)}kB).`)}})).then((()=>a(0))).then((()=>{let e=Date.now(),t=e-s,n=e-r;l(`Flashing done at ${Math.round(256*i.length/n*1e3/1024)} kB/s in ${t}ms (reset ${t-n}ms). Resetting.`)})).then((()=>this.talkAsync(t.HF2_CMD_RESET_INTO_APP).catch((e=>{})))).then((()=>{}))}initAsync(){return this.rawMode?Promise.resolve():Promise.resolve().then((()=>this.talkAsync(t.HF2_CMD_BININFO))).then((e=>(this.bootloaderMode=e[0]==t.HF2_MODE_BOOTLOADER,this.pageSize=s(e,4),this.flashSize=s(e,8)*this.pageSize,this.maxMsgSize=s(e,12),this.familyID=s(e,16),l(`Connected; msgSize ${this.maxMsgSize}B; flash ${this.flashSize/1024}kB; ${this.bootloaderMode?"bootloader":"application"} mode; family=0x${this.familyID.toString(16)}`),this.talkAsync(t.HF2_CMD_INFO)))).then((t=>{this.infoRaw=e.Util.fromUTF8Array(t),e.debug("Info: "+this.infoRaw);let n={};("Header: "+this.infoRaw).replace(/^([\w\-]+):\s*([^\n\r]*)/gm,((e,t,i)=>(n[t.replace(/-/g,"")]=i,""))),this.info=n;let i=/v(\d\S+)(\s+(\S+))?/.exec(this.info.Header);this.info.Parsed=i?{Version:i[1],Features:i[3]||""}:{Version:"?",Features:""},l(`Board-ID: ${this.info.BoardID} v${this.info.Parsed.Version} f${this.info.Parsed.Features}`)})).then((()=>this.talkAsync(t.HF2_CMD_JDS_CONFIG,new Uint8Array([1])).then((()=>{this.jacdacAvailable=!0}),(e=>{this.jacdacAvailable=!1})))).then((()=>{this.reconnectTries=0}))}}function u(t,n){if(!e.appTarget.compile.flashChecksumAddr)return Promise.resolve(t);let i=pxtc.UF2.readBytes(t,e.appTarget.compile.flashChecksumAddr,48),r=pxtc.parseChecksumBlock(i);return r?function(t){return e.appTarget.compile.flashChecksumAddr?t(e.appTarget.compile.flashChecksumAddr,12).then((n=>{let i=pxtc.parseChecksumBlock(n);return i?t(i.endMarkerPos,1).then((t=>s(t,0)!=i.endMarker?(e.log("end-marker mismatch"),null):i)):null})):Promise.resolve(null)}(n).then((e=>{if(!e)return t;let n=e.regions.filter((e=>r.regions.some((t=>e.checksum==t.checksum&&e.length==t.length&&e.start==t.start))));if(0==n.length)return t;l("skipping flash at: "+n.map((e=>`${pxtc.assembler.tohex(e.start)} (${e.length/1024}kB)`)).join(", "));let i=e=>n.some((t=>t.start<=e&&e<t.start+t.length));return t.filter((e=>!(i(e.targetAddr)&&i(e.targetAddr+e.payloadSize-1))))})):Promise.resolve(t)}t.Wrapper=c,t.mkHF2PacketIOWrapper=function(t){return e.debug("packetio: wrapper hf2"),new c(t)},t.onlyChangedBlocksAsync=u}(e.HF2||(e.HF2={}))}(pxt||(pxt={})),function(e){!function(t){var n=e.Util,i=e.HF2;const s=i.read32;let r,a,o,l,c,u,d,h,p=!1;function f(e){return e<<2|2}function g(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 m(e,t){if(n.assert(!(3&e)),n.assert(e>=0),e<2097152){let i=new Uint8Array(t);return e-=d.start,n.memcpy(i,0,d.buf,e,t),Promise.resolve(i)}let i=h.maxMsgSize-32;if(t>i){let s=[];for(;t>0;){let n=Math.min(i,t);s.push(m(e,n)),t-=n,e+=n}return Promise.all(s).then(n.uint8ArrayConcat)}return h.readWordsAsync(e,Math.ceil(t/4)).then((e=>e.length>t?e.slice(0,t):e))}function b(t){if("object"!=typeof t||!t)return Promise.resolve(t);if("number"==typeof t.ptr){if(3&t.ptr)return Promise.resolve({unalignedPtr:t.ptr});let s=0;return m(t.ptr,56).then((r=>{s=i.read16(r,2);let a=r.length;return s==e.BuiltInType.BoxedString||s==e.BuiltInType.BoxedBuffer?a=i.read16(r,4)+6:s==e.BuiltInType.BoxedNumber&&(a=12),a>r.length?m(t.ptr+r.length,a-r.length).then((e=>n.uint8ArrayConcat([r,e]))):a<r.length?r.slice(0,a):r})).then((t=>s==e.BuiltInType.BoxedString?n.uint8ArrayToString(t.slice(6)):s==e.BuiltInType.BoxedBuffer?{type:"buffer",data:t.slice(6)}:s==e.BuiltInType.BoxedNumber?new Float64Array(t.buffer.slice(4))[0]:{type:"unknown",tag:s,refcnt:i.read16(t,0),data:t.slice(4)}))}return Promise.resolve(t)}function y(e){let t=[];for(let n of Object.keys(e))t.push(b(e[n]).then((t=>{e[n]=t})));return Promise.all(t).then((()=>{}))}function v(e){let t=r.breakpoints,n=t[0],i=1/0;for(let s of t){let t=e-s.binAddr;t>=0&&t<i&&(i=t,n=s)}return n}function w(e){if(p)return Promise.resolve();let s;return p=!0,T().then((t=>{let a=i.decodeU32LE(e)[0],l={};for(let e of r.procDebugInfo[0].locals){let s=t.globals,r=(()=>{switch(e.type){case"uint32":return i.read32(s,e.index);case"int32":return 0|i.read32(s,e.index);case"uint16":return i.read16(s,e.index);case"int16":return i.read16(s,e.index)<<16>>16;case"uint8":return s[e.index];case"int8":return s[e.index]<<24>>24;default:return null}})();null===r&&(n.assert(0==(3&e.index)),r=g(i.read32(s,e.index))),l[e.name]=r}return c=v(a),s={type:"debugger",subtype:"breakpoint",breakpointId:c.id,globals:l,stackframes:[]},o(),h.talkAsync(1888490768)})).then((e=>{!function(e,t){let i=c.binAddr,s=0,a=r.procDebugInfo.filter((e=>e.codeStartLoc<=i&&i<=e.codeEndLoc))[0];for(;a&&a!=r.procDebugInfo[0];){let r=v(i),o=n.clone(r);o.functionName=a.name,o.argumentNames=a.args&&a.args.map((e=>e.name)),t.stackframes.push({locals:{},funcInfo:o,breakpointId:r.id});let l=t.stackframes[t.stackframes.length-1],c=0;for(let t of a.locals)n.assert(t.index==c++),l.locals[t.name]=g(e[s++]);i=2147483646&e[s++];let d=u[i+""];for(let t of a.args)l.locals[t.name]=g(e[s+(a.args.length-1-t.index)]);if(!d)break;a=d.from,s+=d.stack-a.localsMark}}(i.decodeU32LE(e),s);let t=[s.globals].concat(s.stackframes.map((e=>e.locals)));return n.promiseMapAll(t,y)})).then((()=>t.postMessage(s)))}function k(){p=!1,a=new Promise(((e,t)=>{o=e}))}function A(e=!1){return Promise.resolve().then((()=>h.talkAsync(665147697,i.encodeU32LE([e?1:3])))).then(k)}function x(){return a||(a=Promise.resolve()),a}function T(){return(l?Promise.resolve(l):h.talkAsync(1409050336).then((e=>l={numGlobals:s(e,0),globalsPtr:s(e,4)}))).then((e=>h.readWordsAsync(e.globalsPtr,e.numGlobals))).then((e=>({staticState:l,globals:e})))}t.taggedUndefined=0,t.taggedNull=f(1),t.taggedFalse=f(2),t.taggedTrue=f(16),t.postMessage=e=>console.log(e),t.decodeValue=g,t.heapExpandAsync=b,t.heapExpandMapAsync=y,t.startDebugAsync=function(e,t){return h=t,h.onEvent(915601917,w),(p=!1,r=null,l=null,Promise.resolve()).then((()=>{r=e,u={};let t=[];for(let n of e.procDebugInfo)t[n.idx]=n;for(let n of e.procDebugInfo)for(let e of n.calls)u[e.addr+""]={from:n,to:t[e.procIndex],stack:e.stack}})).then((()=>{let e=r.outfiles[pxtc.BINARY_UF2],t=n.stringToUint8Array(atob(e));return d=pxtc.UF2.toBin(t),h.reflashAsync(r).then((()=>h.reconnectAsync()))})).then((()=>h.talkAsync(287358355).catch((e=>{})))).then((()=>n.delay(200))).then((()=>h.reconnectAsync())).then(k).then(x)},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":A(t)}},t.resumeAsync=A,t.waitForHaltAsync=x,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)),i=n.charCodeAt(0),s=n.charCodeAt(1),r=n.charCodeAt(2);if(135===i&&(i=224|n.charCodeAt(1),s=n.charCodeAt(2)|n.charCodeAt(3)<<8,r=n.charCodeAt(4)|n.charCodeAt(5)<<8,n=n.slice(4)),225!=i&&228!=i)return null;if(!this.palette){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==i)return this.genMonochrome(n,s,r);const a=(e.BrowserUtils.isEdge()||e.BrowserUtils.isIE())&&s<100&&r<100?3:1;return this.genColor(n,s,r,a)}genMonochrome(t,n,i){let s=n+3&-4,r=54+this.palette.length,a=r+s*i,o=new Uint8Array(a);o[0]=66,o[1]=77,e.HF2.write32(o,2,a),e.HF2.write32(o,10,r),e.HF2.write32(o,14,40),e.HF2.write32(o,18,n),e.HF2.write32(o,22,-i),e.HF2.write16(o,26,1),e.HF2.write16(o,28,8),e.HF2.write32(o,38,2835),e.HF2.write32(o,42,2835),e.HF2.write32(o,46,this.palette.length>>2),o.set(this.palette,54);let l=4,c=r,u=1,d=t.charCodeAt(l++);for(let e=0;e<n;++e){c=r+e;for(let e=0;e<i;++e)o[c]=d&u?1:0,c+=s,u<<=1,256==u&&(u=1,d=t.charCodeAt(l++))}return"data:image/bmp;base64,"+btoa(e.U.uint8ArrayToString(o))}genColor(t,n,i,s){const r=n*(s=Math.max(1,0|s)),a=i*s;let o=r<<2,l=138,c=l+o*a,u=new Uint8Array(c);u[0]=66,u[1]=77,e.HF2.write32(u,2,c),e.HF2.write32(u,10,l),e.HF2.write32(u,14,124),e.HF2.write32(u,18,r),e.HF2.write32(u,22,-a),e.HF2.write16(u,26,1),e.HF2.write16(u,28,32),e.HF2.write16(u,30,3),e.HF2.write32(u,38,2835),e.HF2.write32(u,42,2835),e.HF2.write32(u,54,16711680),e.HF2.write32(u,58,65280),e.HF2.write32(u,62,255),e.HF2.write32(u,66,4278190080),u[70]=66,u[71]=71,u[72]=82,u[73]=115;let d=4,h=l,p=!0;for(let e=0;e<r;e++){let n=!1;h=l+(e<<2);let r=d,c=t.charCodeAt(d++),f=n?(c>>4&15)<<2:(15&c)<<2;for(let e=0;e<a;e++)c&&(p=!1),u[h]=this.palette[f],u[h+1]=this.palette[f+1],u[h+2]=this.palette[f+2],u[h+3]=this.palette[f+3],h+=o,e%s==s-1&&(n&&(c=t.charCodeAt(d++)),n=!n,f=n?(c>>4&15)<<2:(15&c)<<2);if(p&&(u[141]=1),e%s==s-1)for(i%2||--d;3&d;)d++;else d=r}return"data:image/bmp;base64,"+btoa(e.U.uint8ArrayToString(u))}}}(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=i();return n&&Object.keys(n).forEach((t=>e[t]=n[t])),e}function i(){const t=e.appTarget.bundledpkgs[e.template.TEMPLATE_PRJ];if(t){const n=e.Util.clone(t);return delete n[e.CONFIG_NAME],n}}t.TS_CONFIG='{\n "compilerOptions": {\n "target": "ES5",\n "noImplicitAny": true,\n "outDir": "built",\n "rootDir": "."\n },\n "exclude": ["pxt_modules/**/*test.ts"]\n}\n',t.defaultFiles=n,t.targetTemplateFiles=i,t.TEMPLATE_PRJ="template",t.packageFiles=function(t){const i=e.appTarget.blocksprj||e.appTarget.tsprj,s=e.U.clone(i.config);delete s.installedVersion,delete s.additionalFilePath,delete s.additionalFilePaths,s.preferredEditor=s.files.find((e=>/\.blocks$/.test(e)))?e.BLOCKS_PROJECT_NAME:e.JAVASCRIPT_PROJECT_NAME,s.name=t,s.public=!0,s.version||(s.version="0.0.0");const r={},a=n();for(const e in a)r[e]=a[e];for(const e in i.files)"README.md"!=e&&(r[e]=i.files[e]);const o=Object.keys(r).filter((e=>/\.(blocks|md|ts|asm|cpp|h|py)$/.test(e)));return s.files=o.filter((e=>!/test/.test(e))),s.testFiles=o.filter((e=>/test/.test(e))),s.supportedTargets=[e.appTarget.id],r[e.CONFIG_NAME]=e.Package.stringifyConfig(s),r},t.packageFilesFixup=function(t,n){const i=JSON.parse(t[e.CONFIG_NAME]);n&&e.Util.jsonMergeFrom(i,n),e.webConfig&&(Object.keys(e.webConfig).forEach((t=>i[t.toLowerCase()]=e.webConfig[t])),i.platform=e.appTarget.platformid||e.appTarget.id,i.target=e.appTarget.id,i.docs=e.appTarget.appTheme.homeUrl||"./",i.homeurl=e.appTarget.appTheme.homeUrl||"???"),e.U.iterMap(t,((e,n)=>{n=n.replace(/@([A-Z]+)@/g,((e,t)=>i[t.toLowerCase()]||"")),t[e]=n}))}}(e.template||(e.template={}))}(pxt||(pxt={})),function(e){!function(t){let n,i;!function(e){e[e.Prefix=0]="Prefix",e[e.Postfix=1]="Postfix",e[e.Infix=2]="Infix",e[e.Block=3]="Block",e[e.NewLine=4]="NewLine"}(n=t.NT||(t.NT={})),function(e){e[e.None=0]="None",e[e.WithSpace=1]="WithSpace",e[e.NoSpace=2]="NoSpace"}(i=t.GlueMode||(t.GlueMode={}));const s=["break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","import","in","instanceof","new","null","return","super","switch","this","throw","true","try","typeof","var","void","while","with"];function r(e){return"`"+e.replace(/[\\`${}]/g,(e=>"\\"+e))+"`"}function a(e){return e.length>20&&/\n/.test(e)?r(e):JSON.stringify(e)}function o(e,t,n){return{type:e,op:t,children:n}}function l(){return o(n.NewLine,"",[])}function c(e,t){return o(n.Prefix,e,t)}function u(e,t,i){return o(n.Infix,t,null==e?[i]:[e,i])}function d(e){return c(e,[])}function h(e){return o(n.Block,"",e)}function p(e){return c("",e)}function f(e,t=!1){const n=[];for(const i of e)t?(n.length>0&&n.push(d(",")),n.push(l())):n.length>0&&n.push(d(", ")),n.push(i);return t&&n.push(l()),p(n)}let g;t.backtickLit=r,t.stringLit=a,t.mkNode=o,t.mkNewLine=l,t.mkPrefix=c,t.mkPostfix=function(e,t){return o(n.Postfix,t,e)},t.mkInfix=u,t.mkText=d,t.mkBlock=h,t.mkGroup=p,t.mkStmt=function(...e){let t=e[e.length-1];return t&&t.type==n.Block||e.push(l()),p(e)},t.mkCommaSep=f,function(t){function n(e,t,n=!1,i=!1){return p(i?[u(t[0],".",d(e)),d("("),f(t.slice(1),n),d(")")]:[d(e),d("("),f(t,n),d(")")])}function i(e,t,i,s){return n(e+"."+t,i,s)}function s(t,n){return e.U.assert(2==n.length),u(n[0],t,n[1])}t.mkArrayLiteral=function(e,t){return p([d("["),f(e,t),d("]")])},t.mkNumberLiteral=function(e){return d(e.toString())},t.mkBooleanLiteral=function(e){return d(e?"true":"false")},t.mkStringLiteral=function(e){return d(a(e))},t.mkPropertyAccess=function(e,t){return p([u(t,".",d(e))])},t.mkCall=n,t.stdCall=function(e,t,i){return n(e,t,i)},t.extensionCall=function(e,t,i){return n(e,t,i,!0)},t.namespaceCall=i,t.mathCall=function(e,t){return i("Math",e,t,!1)},t.mkGlobalRef=function(e){return d(e)},t.mkSimpleCall=s,t.mkWhile=function(e,t){return p([d("while ("),e,d(")"),h(t)])},t.mkComment=function(e){return d("// "+e)},t.mkMultiComment=function(e){let t=[d("/**"),l()];return e.split("\n").forEach(((e,n,i)=>{e&&(t.push(d(" * "+e)),t.push(l()),n<i.length-1&&(t.push(d(" * ")),t.push(l())))})),p(t.concat([d(" */"),l()]))},t.mkAssign=function(e,t){return s("=",[e,t])},t.mkParenthesizedExpression=function(e){return y(b([e]).output)?e:p([d("("),e,d(")")])}}(g=t.Helpers||(t.Helpers={})),t.H=g;const m={"=":3,"+=":3,"-=":3,"?":4,":":4,"||":5,"&&":6,"|":7,"^":8,"&":9,"==":10,"!=":10,"===":10,"!==":10,"<":11,">":11,"<=":11,">=":11,">>":12,">>>":12,"<<":12,"+":13,"-":13,"*":14,"/":14,"%":14,"**":15,"!":16,"~":16,"P-":16,"P+":16,"++":16,"--":16,".":18};function b(t){let s=[],r={},a="",o="",l=[{}],c=0;function u(e){"string"==typeof e&&(c+=(e.match(/\n/g)||[]).length),a+=e}let h=p(t);return function t(i,s){if(i.type!=n.Infix){for(let e of i.children)t(e,-1);return}let r=[];function a(e){"P"==e[0]&&(e=e.slice(1)),r.push(d(e))}let o=e.U.lookup(m,i.op);if(null==o&&e.U.oops("bad infix op: "+i.op),o<s&&a("("),1==i.children.length)a(i.op),t(i.children[0],o),r.push(i.children[0]);else{let e,n=3!=o&&"**"!=i.op;t(i.children[0],n?o:o+.1),r.push(i.children[0]),e&&"number"!=e&&(a(": "),a(e)),"."==i.op?a("."):a(" "+i.op+" "),t(i.children[1],n?o+.1:o),r.push(i.children[1])}o<s&&a(")"),i.type=n.Prefix,i.op="",i.children=r}(h,-1),f(h),a||u("\n"),{output:a,sourceMap:s};function f(t){t.glueToBlock&&(b(),t.glueToBlock==i.WithSpace&&u(" "));let d=c,h=a.length;switch(t.type){case n.Infix:e.U.oops("no infix should be left");break;case n.NewLine:u("\n"+o);break;case n.Block:!function(t){let n=t.noFinalNewline?"":"\n";if(0==t.children.length)return void g(" {\n\t\n}"+n);let i=e.U.clone(l[l.length-1]||{});l.push(i),o+=" "," "!=a[a.length-1]&&g(" ");g("{\n");for(let e of t.children)f(e);o=o.slice(4),b(),g("\n}"+n),l.pop()}(t);break;case n.Prefix:t.canIndentInside?u(t.op.replace(/\n/g,"\n"+o+" ")):u(t.op),t.children.forEach(f);break;case n.Postfix:t.children.forEach(f),t.canIndentInside?u(t.op.replace(/\n/g,"\n"+o+" ")):u(t.op)}let p=c,m=Math.max(a.length,1);if(t.id)if(r[t.id]){const e=r[t.id];e.startLine=Math.min(e.startLine,d),e.endLine=Math.max(e.endLine,p),e.startPos=Math.min(e.startPos,h),e.endPos=Math.max(e.endPos,m)}else{const e={id:t.id,startLine:d,startPos:h,endLine:p,endPos:m};r[t.id]=e,s.push(e)}}function g(e){u(e.replace(/\n/g,"\n"+o))}function b(){a=a.replace(/\n *$/,(function(){return c--,""}))}}function y(e){if("("!==e[0]||")"!==e[e.length-1])return!1;let t=1;for(let n=1;n<e.length;n++){const i=e[n];if("("===i)t++;else if(")"===i&&(t--,0===t))return n===e.length-1}return!1}t.flattenNode=b,t.isReservedWord=function(e){return-1!==s.indexOf(e)},t.isParenthesized=y}(e.blocks||(e.blocks={}))}(pxt||(pxt={})),function(e){!function(t){const n=[".","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];t.BLOCKLY_TILESET_TYPE="BLOCKLY_TILESET_TYPE",t.TILE_PREFIX="tile",t.TILE_NAMESPACE="myTiles",t.IMAGES_NAMESPACE="myImages",t.IMAGE_PREFIX="image",t.ANIMATION_NAMESPACE="myAnimations",t.ANIMATION_PREFIX="anim";class i{constructor(e,t,n=0,i=0,s){this.width=e,this.height=t,this.x0=n,this.y0=i,this.width||(this.width=16),this.height||(this.height=16),this.buf=s||new Uint8ClampedArray(this.dataLength())}static fromData(e){return new i(e.width,e.height,e.x0,e.y0,e.data)}set(e,t,n){if(e<this.width&&t<this.height&&e>=0&&t>=0){const i=this.coordToIndex(e,t);this.setCore(i,n)}}get(e,t){if(e<this.width&&t<this.height&&e>=0&&t>=0){const n=this.coordToIndex(e,t);return this.getCore(n)}return 0}copy(e=0,t=0,n=this.width,s=this.height){const r=new i(n,s);r.x0=e,r.y0=t;for(let i=0;i<n;i++)for(let n=0;n<s;n++)r.set(i,n,this.get(e+i,t+n));return r}apply(e,t=!1){let n;for(let i=0;i<e.width;i++)for(let s=0;s<e.height;s++)n=e.get(i,s),!n&&t||this.set(e.x0+i,e.y0+s,n)}equals(e){if(this.width===e.width&&this.height===e.height&&this.x0===e.x0&&this.y0===e.y0&&this.buf.length===e.buf.length){for(let t=0;t<this.buf.length;t++)if(this.buf[t]!==e.buf[t])return!1;return!0}return!1}data(){return{width:this.width,height:this.height,x0:this.x0,y0:this.y0,data:this.buf}}resize(e,t){return h(this,e,t)}coordToIndex(e,t){return e+t*this.width}getCore(e){const t=Math.floor(e/2);return e%2==0?15&this.buf[t]:(240&this.buf[t])>>4}setCore(e,t){const n=Math.floor(e/2);this.buf[n]=e%2==0?240&this.buf[n]|15&t:15&this.buf[n]|(15&t)<<4}dataLength(){return Math.ceil(this.width*this.height/2)}}t.Bitmap=i;class s extends i{static fromData(e){return new s(e.width,e.height,e.x0,e.y0,e.data)}copy(e=0,t=0,n=this.width,i=this.height){const r=new s(n,i);r.x0=e,r.y0=t;for(let s=0;s<n;s++)for(let n=0;n<i;n++)r.set(s,n,this.get(e+s,t+n));return r}resize(e,t){return p(this,e,t)}getCore(e){return this.buf[e]}setCore(e,t){this.buf[e]=t}dataLength(){return this.width*this.height}}t.Tilemap=s;class r{constructor(e,t,n){this.tilemap=e,this.tileset=t,this.layers=n,this.nextId=0}cloneData(){const e=this.tilemap.copy(),t={tileWidth:this.tileset.tileWidth,tiles:this.tileset.tiles.map((e=>Object.assign(Object.assign({},e),{bitmap:i.fromData(e.bitmap).copy().data()})))},n=i.fromData(this.layers).copy().data();return new r(e,t,n)}equals(t){if(!this.tilemap.equals(t.tilemap)||this.tileset.tileWidth!=t.tileset.tileWidth||this.tileset.tiles.length!=t.tileset.tiles.length||!y(this.layers,t.layers))return!1;for(let n=0;n<this.tileset.tiles.length;n++)if(!e.assetEquals(this.tileset.tiles[n],t.tileset.tiles[n]))return!1;return!0}}t.TilemapData=r;function a(e){return o(atob(e.slice(e.indexOf(",")+1)))}function o(t){let n=t.charCodeAt(0),i=t.charCodeAt(1),s=t.charCodeAt(2);135===n&&(n=224|t.charCodeAt(1),i=t.charCodeAt(2)|t.charCodeAt(3)<<8,s=t.charCodeAt(4)|t.charCodeAt(5)<<8,t=t.slice(4));const r=new e.sprite.Bitmap(i,s);let a=4;if(225===n){let e=1,n=t.charCodeAt(a++);for(let o=0;o<i;++o)for(let i=0;i<s;++i)r.set(o,i,n&e?1:0),e<<=1,256==e&&(e=1,n=t.charCodeAt(a++))}else for(let e=0;e<i;e++){for(let n=0;n<s;n+=2){let i=t.charCodeAt(a++);r.set(e,n,15&i),n!=s-1&&r.set(e,n+1,i>>4&15)}for(;3&a;)a++}return r}function l(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,i=parseInt(e.substr(4,2),16)|parseInt(e.substr(6,2),16)<<8,r=k(e.substring(8));return s.fromData({width:n,height:i,x0:0,y0:0,data:r})}function c(e){return`${d(e.width,2)}${d(e.height,2)}${A(e.data().data)}`}function u(e,t){return(e=e.replace(/[\[\]]/g,""))?e.split(",").filter((e=>!!e.trim())).map((e=>function(e,t){if(0===(e=e.trim()).indexOf("img")){const n=f(e);return t.createNewTile(n.data())}switch(e){case"myTiles.tile0":case"myTiles.transparency16":return t.getTransparency(16);case"myTiles.transparency8":return t.getTransparency(8);case"myTiles.transparency32":return t.getTransparency(32);default:return t.resolveTile(e)}}(e,t))):[]}function d(e,t){let n=e.toString(16);const i=t<<1;for(1&n.length&&(n="0"+n);n.length<i;)n+="0";return n}function h(e,t,n){const s=new i(t,n);return s.apply(e),s}function p(e,t,n){const i=new s(t,n);return i.apply(e),i}function f(e){const t=(e=(e=(e=e.replace(/[ `]|(?:`)|(?:	)|(?:img)/g,"").trim()).replace(/^["`\(\)]*/,"").replace(/["`\(\)]*$/,"")).replace(/ /g,"\n")).split("\n"),n=[];let s=0;for(let e=0;e<t.length;e++){const i=t[e],r=[];for(let e=0;e<i.length;e++)switch(i[e]){case"0":case".":r.push(0);break;case"1":case"#":r.push(1);break;case"2":case"T":r.push(2);break;case"3":case"t":r.push(3);break;case"4":case"N":r.push(4);break;case"5":case"n":r.push(5);break;case"6":case"G":r.push(6);break;case"7":case"g":r.push(7);break;case"8":r.push(8);break;case"9":r.push(9);break;case"a":case"A":case"R":r.push(10);break;case"b":case"B":case"P":r.push(11);break;case"c":case"C":case"p":r.push(12);break;case"d":case"D":case"O":r.push(13);break;case"e":case"E":case"Y":r.push(14);break;case"f":case"F":case"W":r.push(15);break;default:if(!/\s/.test(i[e]))return}r.length&&(n.push(r),s=Math.max(s,r.length))}const r=n.length,a=new i(s,r);for(let e=0;e<r;e++){const t=n[e];for(let n=0;n<s;n++)n<t.length?a.set(n,e,t[n]):a.set(n,e,0)}return a}function g(e){let t="";switch(e){case"python":t='img("""';break;default:t="img`"}return t}function m(e){let t="";switch(e){case"python":t+='""")';break;default:t+="`"}return t}function b(e,t){if(!e||0===e.height||0===e.width)return"";let i=g(t);if(e){const t=e.width*e.height>300?"":" ";for(let s=0;s<e.height;s++){i+="\n";for(let r=0;r<e.width;r++)i+=n[e.get(r,s)]+t}}return i+="\n",i+=m(t),i}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 w(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 k(e){let t=new Uint8ClampedArray(e.length>>1);for(let n=0;n<e.length;n+=2)t[n>>1]=parseInt(e.slice(n,n+2),16);return t}function A(e){const t="0123456789abcdef";let n="";for(let i=0;i<e.length;++i)n+=t[e[i]>>4],n+=t[15&e[i]];return n}function x(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[E(t),C(t),I(t)]}function E(e){return e>>16&255}function C(e){return e>>8&255}function I(e){return 255&e}t.Bitmask=class{constructor(e,t){this.width=e,this.height=t,this.mask=new Uint8Array(Math.ceil(e*t/8))}set(e,t){const n=e+this.width*t,i=n>>3,s=7&n;this.mask[i]|=1<<s}get(e,t){const n=e+this.width*t,i=n>>3,s=7&n;return this.mask[i]>>s&1}},t.encodeTilemap=function(e,t){return e?`tiles.createTilemap(${function(e){return e?`hex\`${c(e)}\``:"hex``"}(e.tilemap)}, ${b(i.fromData(e.layers),t)}, [${e.tileset.tiles.map((e=>function(e,t){return e.id}(e)))}], ${v(e.tileset.tileWidth)})`:"null"},t.decodeTilemap=function(t,n,i){if(!(t=e.Util.htmlUnescape(t).trim()).trim())return null;const s=(t=(t=t.substr(t.indexOf("(")+1)).substr(0,t.lastIndexOf(")"))).substr(0,t.indexOf(",")),a=(t=t.substr(s.length+1)).substr(0,t.indexOf(",")),o=(t=t.substr(a.length+1)).substr(0,t.lastIndexOf("]")+1),c=t=t.substr(o.length+1);return new r(l(s),{tiles:u(o,i),tileWidth:w(c)},f(a).data())},t.trimTilemapTileset=function(e){const t=e.tileset.tiles.slice(),n=e.tilemap,i={};i[t[0].id]=!0;for(let e=0;e<n.width;e++)for(let s=0;s<n.height;s++)i[t[n.get(e,s)].id]=!0;const s=e.editedTiles||[],r=t.filter((e=>i[e.id]||"*"===e.id.charAt(0)||-1!==s.indexOf(e.id)));if(r.length===t.length)return;const a=[];for(let e=0;e<t.length;e++)a.push(r.indexOf(t[e]));for(let e=0;e<n.width;e++)for(let t=0;t<n.height;t++)n.set(e,t,a[n.get(e,t)]);e.tileset.tiles=r},t.isEmptyTilemap=function(e){const t=e.tileset.tiles,n=e.tilemap,i=t[0].id;for(let e=0;e<n.width;e++)for(let s=0;s<n.height;s++)if(t[n.get(e,s)].id!==i)return!1;return!0},t.computeAverageColor=function(e,t){const n=t.map(T),i=[0,0,0];let s=0;for(let t=0;t<e.width;t++)for(let r=0;r<e.height;r++){const a=e.get(t,r);if(a){++s;const e=n[a];i[0]+=e[0],i[1]+=e[1],i[2]+=e[2]}}return s?"#"+function(e){let t="";for(let n=0;n<e.length;++n)t+=("0"+e[n].toString(16)).slice(-2);return t}(i.map((e=>Math.floor(e/s)))):"#00000000"},t.getBitmap=function(e,t){const n=e.apis.byQName[t];return n?a(n.attributes.jresURL):null},t.getBitmapFromJResURL=a,t.hexToBitmap=o,t.filterItems=function(e,t){const n=(t=t.filter((e=>!!e)).map((e=>e.toLowerCase()))).filter((e=>0!==e.indexOf("!"))),i=t.filter((e=>0===e.indexOf("!")&&e.length>1)).map((e=>e.substring(1)));return e.filter((e=>{return t=e,n.every((e=>{const n=`?${e}`;return t.tags.some((t=>t===e||t===n))}))&&function(e){return i.every((t=>!e.tags.some((e=>e===t))))}(e);var t}))},t.getGalleryItems=function(n,i){let s=function(t,n){return e.Util.values(t.byQName).filter((e=>4===e.kind&&e.attributes.fixedInstance&&function(e,t,n){if(t==n)return!0;let i=e.byQName[t];return!(!i||!i.extendsTypes)&&i.extendsTypes.indexOf(n)>=0}(t,e.retType,n)))}(n.apis,i);return s=s.filter((e=>e.namespace!=t.TILE_NAMESPACE)),function(t){const n=new e.ImageConverter;t.forEach((e=>{e.attributes.jresURL&&!e.attributes.iconURL&&0==e.attributes.jresURL.indexOf("data:image/x-mkcd-f")&&(e.attributes.iconURL=n.convert(e.attributes.jresURL))}))}(s),s.map((t=>{const n=(t.attributes.tags||"").split(" ").filter((e=>!!e)).map((t=>e.Util.startsWith(t,"category-")?t:t.toLowerCase()));return{qName:t.qName,src:t.attributes.iconURL,alt:t.qName,tags:n}}))},t.base64EncodeBitmap=function(t){const n=i.fromData(t),s=pxtc.f4EncodeImg(t.width,t.height,4,((e,t)=>n.get(e,t)));return btoa(e.U.uint8ArrayToString(k(s)))},t.tilemapLiteralToTilemap=l,t.hexEncodeTilemap=c,t.formatByte=d,t.resizeBitmap=h,t.resizeTilemap=p,t.imageLiteralToBitmap=f,t.encodeAnimationString=function(t,n){const i=t.map((e=>e.data)),s=new Uint8ClampedArray(8+i[0].length*i.length);x(s,0,n),x(s,2,t[0].width),x(s,4,t[0].height),x(s,6,t.length);let r=8;return i.forEach((e=>{s.set(e,r),r+=e.length})),btoa(e.sprite.uint8ArrayToHex(s))},t.addMissingTilemapTilesAndReferences=function(e,t){const n=e.getProjectTiles(t.data.tileset.tileWidth,!0);t.data.projectReferences=[];for(const i of n.tiles)t.data.tileset.tiles.some((e=>e.id===i.id))||t.data.tileset.tiles.push(i),e.isAssetUsed(i,null,[t.id])&&t.data.projectReferences.push(i.id)},t.updateTilemapReferencesFromResult=function(t,n){const i=n.data;if(i.deletedTiles)for(const e of i.deletedTiles)t.deleteTile(e);if(i.editedTiles)for(const e of i.editedTiles){const n=i.tileset.tiles.findIndex((t=>t.id===e)),s=i.tileset.tiles[n];s&&(i.tileset.tiles[n]=t.updateTile(s))}for(let e=0;e<i.tileset.tiles.length;e++){const n=i.tileset.tiles[e];n.jresData||(i.tileset.tiles[e]=t.resolveTile(n.id))}e.sprite.trimTilemapTileset(i)},t.imageLiteralFromDimensions=function(e,t,i,s){let r=g(s);const a=e*t>300?"":" ";for(let s=0;s<t;s++){r+="\n";for(let t=0;t<e;t++)r+=n[i]+a}return r+="\n",r+=m(s),r},t.bitmapToImageLiteral=b,t.bitmapEquals=y,t.tileWidthToTileScale=v,t.tileScaleToTileWidth=w,t.hexToUint8Array=k,t.uint8ArrayToHex=A,t.colorStringToRGB=T}(e.sprite||(e.sprite={}))}(pxt||(pxt={})),function(e){!function(t){!function(n){const i=new RegExp(`^\\s*${t.TILE_NAMESPACE}\\s*\\.\\s*${t.TILE_PREFIX}(\\d+)\\s*$`);class s{constructor(e,t,n){this.tilemap=e,this.tileset=t,this.layers=n,this.nextId=0}}function r(e){return(e=e.replace(/[\[\]]/g,""))?e.split(",").filter((e=>!!e.trim())).map((e=>function(e){if(0===(e=e.trim()).indexOf("img")){return{data:t.imageLiteralToBitmap(e).data()}}const n=i.exec(e);if(n)return{data:null,projectId:Number(n[1])};return{data:null,qualifiedName:e}}(e))):[]}n.LegacyTilemapData=s,n.decodeTilemap=function(n,i){var a;if(!(null==(n=null===(a=e.Util.htmlUnescape(n))||void 0===a?void 0:a.trim())?void 0:n.trim()))return new s(new t.Tilemap(16,16),{tileWidth:16,tiles:[]},new t.Bitmap(16,16).data());const o=(n=(n=n.substr(n.indexOf("(")+1)).substr(0,n.lastIndexOf(")"))).substr(0,n.indexOf(",")),l=(n=n.substr(o.length+1)).substr(0,n.indexOf(",")),c=(n=n.substr(l.length+1)).substr(0,n.lastIndexOf("]")+1),u=n=n.substr(c.length+1);return new s(t.tilemapLiteralToTilemap(o),{tiles:r(c),tileWidth:t.tileScaleToTileWidth(u)},t.imageLiteralToBitmap(l).data())},n.tileToBlocklyVariable=function(e){return`${e.projectId};${e.data.width};${e.data.height};${pxtc.Util.toHex(e.data.data)}`},n.blocklyVariableToTile=function(e){const t=e.split(";");return 4!==t.length?null:{projectId:parseInt(t[0]),data:{width:parseInt(t[1]),height:parseInt(t[2]),data:new Uint8ClampedArray(pxtc.Util.fromHex(t[3])),x0:0,y0:0}}}}(t.legacy||(t.legacy={}))}(e.sprite||(e.sprite={}))}(pxt||(pxt={})),function(e){!function(t){class n{constructor(){this.items={}}removeItem(e){delete this.items[e]}getItem(e){return this.items[e]}setItem(e,t){this.items[e]=t}clear(){this.items={}}}class i{constructor(e){this.storageId=e}targetKey(e){return this.storageId+"/"+e}removeItem(e){window.localStorage.removeItem(this.targetKey(e))}getItem(e){return window.localStorage[this.targetKey(e)]}setItem(e,t){window.localStorage[this.targetKey(e)]=t}clear(){let e=this.targetKey(""),t=[];for(let n=0;n<window.localStorage.length;++n){let i=window.localStorage.key(n);0==i.indexOf(e)&&t.push(i)}t.forEach((e=>window.localStorage.removeItem(e)))}}function s(){if(e.appTarget)return e.appTarget.id;const t=window.pxtConfig;if(t)return t.targetId;const n=window.pxtTargetBundle;return n?n.id:""}let r;function a(){if(r)return;const t=s();let a=!1;if(!e.shell.isSandboxMode())try{window.localStorage[t]="1";window.localStorage[t];a=!0}catch(e){}a?(r=new i(t),e.debug(`storage: local under ${t}`)):(r=new n,e.debug("storage: in memory"))}t.storageId=s,t.setLocal=function(e,t){a(),r.setItem(e,t)},t.getLocal=function(e){return a(),r.getItem(e)},t.removeLocal=function(e){a(),r.removeItem(e)},t.clearLocal=function(){a(),r.clear()}}(e.storage||(e.storage={}))}(pxt||(pxt={})),function(e){!function(t){!function(t){const n="http://localhost:3232/api/store/";function i(){return e.BrowserUtils.isLocalHostDev()&&!e.BrowserUtils.noSharedLocalStorage()}function s(){return e.BrowserUtils.isChromiumEdge()?"chromium-edge":e.BrowserUtils.browser()}t.getAsync=async function(t,r){if(i()){t+="-"+s();const i=await e.Util.requestAsync({url:`${n}${encodeURIComponent(t)}/${encodeURIComponent(r)}`,method:"GET",allowHttpErrors:!0});return i.json?i.json:i.text?i.text:void 0}{const n=e.storage.getLocal(`${t}:${r}`),i=e.Util.jsonTryParse(n);return i||n}},t.setAsync=async function(t,r,a){if(void 0===a)return void await e.storage.shared.delAsync(t,r);let o="";if(o="object"==typeof a?JSON.stringify(a):a.toString(),i()){t+="-"+s();const i={type:"object"==typeof a?"json":"text",val:o},l=JSON.stringify(i);await e.Util.requestAsync({url:`${n}${encodeURIComponent(t)}/${encodeURIComponent(r)}`,method:"POST",data:l})}else e.storage.setLocal(`${t}:${r}`,o)},t.delAsync=async function(t,r){i()?(t+="-"+s(),await e.Util.requestAsync({url:`${n}${encodeURIComponent(t)}/${encodeURIComponent(r)}`,method:"DELETE",allowHttpErrors:!0})):e.storage.removeLocal(`${t}:${r}`)}}(t.shared||(t.shared={}))}(e.storage||(e.storage={}))}(pxt||(pxt={})),function(e){const t=["name","version","description","license","dependencies","files","testFiles","testDependencies","fileDependencies","public","targetVersions","supportedTargets","preferredEditor","languageRestriction","additionalFilePath","additionalFilePaths"];class n{constructor(e,t,n,i){this.id=e,this._verspec=t,this.parent=n,this.level=-1,this.isLoaded=!1,this.ignoreTests=!1,this.cppOnly=!1,i&&(this.level=i.level+1),this.addedBy=[i]}static stringifyConfig(e){const n=e,i={};for(const e of t)n.hasOwnProperty(e)&&(i[e]=n[e]);for(const e of Object.keys(n))i.hasOwnProperty(e)||(i[e]=n[e]);return JSON.stringify(i,null,4)+"\n"}static parseAndValidConfig(t){const n=e.Util.jsonTryParse(t);return n&&void 0!==n.name&&"string"==typeof n.name&&n.files&&Array.isArray(n.files)&&n.files.every((e=>"string"==typeof e))&&n.dependencies&&Object.keys(n.dependencies).every((e=>"string"==typeof n.dependencies[e]))&&n}static getConfigAsync(t,n,i){return Promise.resolve().then((()=>{if(e.github.isGithubId(i)){const t=e.github.parseRepoId(i);return e.packagesConfigAsync().then((n=>e.github.repoAsync(t.fullName,n))).then((n=>n?e.github.pkgConfigAsync(t.fullName,t.tag):null))}{const s=e.patching.upgradePackageReference(t,n,i),r=e.appTarget.bundledpkgs[s];return JSON.parse(r[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")&&i(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 i=e.github.parseRepoId(this._verspec);if(i&&!i.tag&&this.parent){e.debug("dep: unbound github extensions, trying to resolve tag");const s=e.semver.sortLatestTags(e.Util.values((null===(t=this.parent)||void 0===t?void 0:t.deps)||{}).map((t=>e.github.parseRepoId(t.version()))).filter((e=>(null==e?void 0:e.slug)===i.slug)).map((e=>e.tag)))[0];s&&(i.tag=s,this.resolvedVersion=n=e.github.stringifyRepo(i),e.debug(`dep: github patched ${this._verspec} to ${n}`))}}}else this.configureAsInvalidPackage(lf("version not specified for {0}",this.id)),n=this._verspec;return Promise.resolve(n)}downloadAsync(){return this.resolveVersionAsync().then((t=>{if(this.invalid())e.debug(`skip download of invalid package ${this.id}`);else if(/^embed:/.test(t)||this.installedVersion!=t)return e.debug("downloading "+t),this.host().downloadPackageAsync(this).then((()=>{this.loadConfig(),e.debug(`installed ${this.id} /${t}`)}))}))}loadConfig(){if(0!=this.level&&this.invalid())return;const t=this.readFile(e.CONFIG_NAME);t||e.U.userError(`extension ${this.id} is missing ${e.CONFIG_NAME}`),this.parseConfig(t),0!=this.level&&(this.installedVersion=this.version()),this.saveConfig()}validateConfig(){this.config.dependencies||e.U.userError("Missing dependencies in config of: "+this.id),Array.isArray(this.config.files)||e.U.userError("Missing files in config of: "+this.id),"string"==typeof this.config.name&&this.config.name||(this.config.name=lf("Untitled")),this.config.targetVersions&&this.config.targetVersions.target&&this.config.targetVersions.targetId===e.appTarget.id&&e.appTarget.versions&&e.semver.majorCmp(this.config.targetVersions.target,e.appTarget.versions.target)>0&&e.U.userError(lf("{0} requires target version {1} (you are running {2})",this.config.name,this.config.targetVersions.target,e.appTarget.versions.target))}isPackageInUse(t,n=this.readFile(e.MAIN_TS)){let i=null;const s=e.patching.computePatches(this.targetVersion(),"missingPackage");return s&&s.forEach((e=>{Object.keys(e.map).forEach((n=>{e.map[n]===t&&(i=new RegExp(n,"g"))}))})),i||(i=new RegExp(t+"\\.","g")),i.test(n)}upgradePackagesAsync(){return this.config||this.loadConfig(),e.packagesConfigAsync().then((t=>{let n=0,i={};return e.U.iterMap(this.config.dependencies,((s,r)=>{if(e.github.isGithubId(r)){const a=e.github.upgradedPackageReference(t,r);a&&a!=r&&(e.log(`upgrading dep ${s}: ${r} -> ${a}`),i[r]=a,this.config.dependencies[s]=a,n++)}})),n&&this.saveConfig(),n&&i}))}getMissingPackages(t,n){const i=e.patching.computePatches(this.targetVersion(),"missingPackage"),s={};return n&&i&&i.forEach((e=>{Object.keys(e.map).forEach((i=>{const r=new RegExp(i,"g"),a=e.map[i];n.replace(r,(e=>(t.dependencies[a]||(s[a]="*"),"")))}))})),s}findConflictsAsync(t,i){let s,r=[];return Promise.resolve().then((()=>"string"==typeof t?n.getConfigAsync(this.targetVersion(),t,i):Promise.resolve(t))).then((t=>{if(s=t,s){const t=s.yotta?e.U.jsonFlatten(s.yotta.config):null;this.parent.sortedDeps().forEach((n=>{if(s.core&&n.config.core&&s.name!=n.config.name){const t=new e.cpp.PkgConflictError(lf("conflict between core extensions {0} and {1}",s.name,n.id));return t.pkg0=n,void r.push(t)}let a=!1;if(t){const i=n.config||JSON.parse(n.readFile(e.CONFIG_NAME));if(!!i&&!!i.yotta&&!!n.config.yotta.config){const o=e.U.jsonFlatten(i.yotta.config);for(const l of Object.keys(t)){const c=o[l],u=s.yotta.configIsJustDefaults||i.yotta.configIsJustDefaults;if(o.hasOwnProperty(l)&&c!==t[l]&&!u&&(!n.parent.config.yotta||!n.parent.config.yotta.ignoreConflicts)){const t=new e.cpp.PkgConflictError(lf("conflict on yotta setting {0} between extensions {1} and {2}",l,s.name,n.id));t.pkg0=n,t.settingName=l,r.push(t),a=!0}}}}if(!a&&s.name===n.id&&n._verspec!==i&&!/^file:/.test(n._verspec)&&!/^file:/.test(i)){const t=/^github:/.test(n._verspec)&&e.github.parseRepoId(n._verspec),s=/^github:/.test(i)&&e.github.parseRepoId(i);if(!t||!s||t.fullName!==s.fullName||s.tag&&e.semver.strcmp(t.tag,s.tag)<0){const t=new e.cpp.PkgConflictError(lf("version mismatch for extension {0} (installed: {1}, installing: {2})",n.id,n._verspec,i));t.pkg0=n,t.isVersionConflict=!0,r.push(t)}}}))}return Object.keys(s.dependencies).reduce(((e,t)=>e.then((()=>this.findConflictsAsync(t,s.dependencies[t]))).then((e=>r.push.apply(r,e)))),Promise.resolve())})).then((()=>{const t=e=>{const n=[];return e.addedBy.forEach((e=>{e.id!==this.id&&(n.push.apply(t(e)),n.push(e))})),n},n=[];return r.forEach((r=>{n.push.apply(n,t(r.pkg0).map((t=>{const n=new e.cpp.PkgConflictError(r.isVersionConflict?lf("a dependency of {0} has a version mismatch with extension {1} (installed: {1}, installing: {2})",t.id,s.name,r.pkg0._verspec,i):lf("conflict on yotta setting {0} between extensions {1} and {2}",r.settingName,s.name,r.pkg0.id));return n.pkg0=t,n})))})),r.push.apply(r,n),r=r.filter(((e,t)=>{for(let n=0;n<t;++n)if(e.pkg0.id===r[n].pkg0.id)return!1;return!0})),r}))}configureAsInvalidPackage(t){e.log(`invalid package ${this.id}: ${t}`),this._verspec="invalid:"+this.id,this.config={name:this.id,description:t,dependencies:{},files:[]}}parseConfig(t,n){try{const e=JSON.parse(t);this.config=e}catch(t){this.configureAsInvalidPackage(lf("Syntax error in pxt.json")),e.tickEvent("package.invalidConfigEncountered")}const i=JSON.stringify(this.config);for(const t in this.config.dependencies){const n=e.patching.upgradePackageReference(this.targetVersion(),t,this.config.dependencies[t]);n!=t&&(delete this.config.dependencies[t],n&&(this.config.dependencies[n]="*"))}n&&(this.config.targetVersions={target:n}),JSON.stringify(this.config)!=i&&this.saveConfig(),this.validateConfig()}patchCorePackage(){e.Util.assert(e.appTarget.simulator&&e.appTarget.simulator.dynamicBoardDefinition),e.Util.assert(0==this.level);const t=Object.keys(this.config.dependencies).filter((t=>!!t&&(t==e.BLOCKS_PROJECT_NAME||t==e.JAVASCRIPT_PROJECT_NAME||JSON.parse((e.appTarget.bundledpkgs[t]||{})[e.CONFIG_NAME]||"{}").core)));if(0==t.length){const t=e.Package.corePackages();t.length&&this.config.dependencies[t[0].name]}else t.length>1&&(t.pop(),t.forEach((t=>{e.log(`removing core package ${t}`),delete this.config.dependencies[t]})))}resolvedDependencies(){return Object.keys(this.dependencies()).map((e=>this.resolveDep(e)))}dependencies(t=!1){if(!this.config)return{};const n=e.Util.clone(this.config.dependencies||{});return 0==this.level&&this.config.testDependencies&&e.Util.iterMap(this.config.testDependencies,((t,i)=>{("*"!=i||e.appTarget.bundledpkgs[t])&&(n[t]=i)})),t&&this.config.cppDependencies&&e.Util.jsonMergeFrom(n,this.config.cppDependencies),n}loadAsync(t=!1,i){if(this.isLoaded)return Promise.resolve();let s=Promise.resolve();0!=this.level||e.appTarget.multiVariants||e.setAppTargetVariant(null),this.isLoaded=!0;const r=this.readFile(e.CONFIG_NAME);null==r?t||e.U.userError("Package not installed: "+this.id+", did you forget to run `pxt install`?"):s=s.then((()=>this.parseConfig(r))),0!=this.level||t||(s=s.then((()=>this.upgradePackagesAsync().then((()=>{}))))),t&&(s=s.then((()=>this.downloadAsync()))),0==this.level&&t&&(s=s.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&&(s=s.then((()=>this.patchCorePackage()))),s=s.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],i=this.readFile(t);return e.U.toDataUri(i,e.U.getMime(t))}return t},i=e.appTarget.simulator.boardDefinition;if("object"==typeof i.visual){let e=i.visual;e.image=n(e.image),e.outlineImage=n(e.outlineImage)}})));const a=(t,n)=>{var i;if(e.debug(`version spec mismatch: ${t._verspec} != ${n}`),/^github:/.test(t._verspec)&&/^github:/.test(n)){const s=e.github.parseRepoId(t._verspec),r=e.github.parseRepoId(n);if((null==s?void 0:s.slug)&&(null==s?void 0:s.slug)===(null==r?void 0:r.slug)){const a=(null==s?void 0:s.tag)||(null===(i=t.config)||void 0===i?void 0:i.version),o=e.semver.strcmp(a,r.tag);if(0==o)return void e.debug(`resolved version are ${a}`);if(o<0)return void e.debug(`auto-upgraded ${n} to ${a}`)}}/^file:/.test(t._verspec)||/^file:/.test(n)?e.debug("ignore file: mismatch issues"):t.configureAsInvalidPackage(lf("version mismatch"))},o=async(i,s,r=!1)=>{i||(i=s.dependencies(r)),e.debug(`deps: ${s.id}->${Object.keys(i).join(", ")}`),i=e.github.resolveMonoRepoVersions(i),e.debug(`deps: resolved ${s.id}->${Object.keys(i).join(", ")}`);for(let o of Object.keys(i)){let l=i[o]||"*";e.debug(`dep: load ${s.id}.${o}${r?"++":""}: ${l}`),"hw"==o&&e.hwVariant&&(o="hw---"+e.hwVariant);let c=s.resolveDep(o);if(c){if(c.invalid()||c._verspec===l||a(c,l),c.invalid()){c.level=Math.min(c.level,s.level+1),c.addedBy.push(s);continue}r||(c.level=Math.min(c.level,s.level+1),c.addedBy.push(s))}else{let e=new n(o,l,s.parent,s);r&&(e.cppOnly=!0),s.parent.deps[o]=e,s.parent.deps[o.replace(/---.*/,"")]=e,await e.loadAsync(t)}}};return s.then((()=>o(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 i=!1;return Object.keys(n).reduce(((t,s)=>t.then((()=>this.findConflictsAsync(s,n[s]))).then((t=>{if(t.length){const n=t.map((e=>e.pkg0.id)).join(", "),i=t.map((e=>e.settingName)).filter((e=>!!e)).join(", ");return e.log(`skipping missing package ${s} because it conflicts with the following packages: ${n} (conflicting settings: ${i})`),Promise.resolve(null)}{e.log(`adding missing package ${s}`),i=!0,this.config.dependencies[s]="*";const t={};return t[s]=n[s],o(t,this)}}))),Promise.resolve(null)).then((()=>(i&&(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=>o(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 i=this.config.fileDependencies;return this.config.fileDependencies&&(t=t.filter((t=>{const s=i=>{if("!"==(i=i.trim())[0])return!s(i.slice(1));if(/^[\w-]+$/.test(i)){const e=this.parent.resolveDep(i);return!(!e||e.cppOnly)}const r=/^target:(\w+)$/.exec(i);return r?r[1]==e.appTarget.id||r[1]==e.appTarget.platformid:(n.depWarnings[i]||(n.depWarnings[i]=!0,e.log(`invalid dependency expression: ${i} in ${this.id}/${t}`)),!1)},r=e.U.lookup(i,t);return!r||!r.trim()||r.split("||").some((e=>e.split("&&").every(s)))}))),t}addSnapshot(t,n=[""]){for(let i of this.getFiles())n.some((t=>e.U.endsWith(i,t)))&&(t[this.id+"/"+i]=this.readFile(i));t[this.id+"/"+e.CONFIG_NAME]=this.readFile(e.CONFIG_NAME)}packageLocalizationStringsAsync(t){const n=e.appTarget.id,i=[this.config.name+"-jsdoc",this.config.name],s={},r=e.appTarget.appTheme||{};return this.config.skipLocalization?Promise.resolve(s):e.Util.liveLocalizationEnabled()&&"this"!=this.id&&e.appTarget.bundledpkgs[this.id]?(e.debug(`loading live translations for ${this.id}`),Promise.all(i.map((i=>e.Util.downloadLiveTranslationsAsync(t,`${n}/${i}-strings.json`,r.crowdinBranch).then((n=>{n&&Object.keys(n).length?e.Util.jsonMergeFrom(s,n):(e.tickEvent("translations.livetranslationsfailed",{filename:i}),e.Util.jsonMergeFrom(s,this.bundledStringsForFile(t,i)))})).catch((r=>{e.tickEvent("translations.livetranslationsfailed",{filename:i}),e.log(`error while downloading ${n}/${i}-strings.json`),e.Util.jsonMergeFrom(s,this.bundledStringsForFile(t,i))}))))).then((()=>s))):(i.map((e=>this.bundledStringsForFile(t,e))).filter((e=>!!e)).forEach((t=>e.Util.jsonMergeFrom(s,t))),Promise.resolve(s))}bundledStringsForFile(t,n){let i={},[s,r,a]=e.Util.normalizeLanguageCode(t);const o=this.config.files;let l=`_locales/${s}/${n}-strings.json`;return o.indexOf(l)>-1?i=JSON.parse(this.readFile(l)):a&&(l=`_locales/${a}/${n}-strings.json`,o.indexOf(l)>-1?i=JSON.parse(this.readFile(l)):r&&(l=`_locales/${r}/${n}-strings.json`,o.indexOf(l)>-1&&(i=JSON.parse(this.readFile(l))))),i}}n.depWarnings={},e.Package=n;function i(e,t={}){let n=e["*"]||{};for(let i of Object.keys(e)){if("*"==i)continue;let s=e[i];"string"==typeof s&&(s={data:s});let r=s.namespace||n.namespace||"";r&&(r+=".");let a=s.id||r+i,o=s.icon,l=s.mimeType||n.mimeType,c=s.dataEncoding||n.dataEncoding||"base64";o||"base64"!=c||"image/png"!=l&&"image/jpeg"!=l||(o="data:"+l+";base64,"+s.data),t[a]={id:a,data:s.data,dataEncoding:c,icon:o,namespace:r,mimeType:l,tilemapTile:s.tilemapTile,displayName:s.displayName,tileset:s.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={},i=[];const s=e=>e.config?Object.keys(e.config.cppDependencies||{}).length:0,r=a=>{if(!a||e.U.lookup(n,a.id))return;n[a.id]=!0;const o=Object.keys(a.dependencies(t)).map((e=>this.resolveDep(e)));o.sort(((t,n)=>s(n)-s(t)||e.U.strcmp(t.id,n.id))),o.forEach(r),i.push(a.id)};return r(this),i.map((e=>this.resolveDep(e)))}localizationStringsAsync(t){const n={};return Promise.all(e.Util.values(this.deps).map((e=>e.packageLocalizationStringsAsync(t).then((e=>{e&&Object.keys(e).forEach((t=>{n[t]||(n[t]=e[t])}))}))))).then((()=>{const t=e.U.getLocalizedStrings();return Object.keys(n).forEach((i=>{(e.U.startsWith(i,"{id:subcategory}")||e.U.startsWith(i,"{id:group}"))&&(t[i]||(t[i]=n[i]))})),e.U.setLocalizedStrings(t),Promise.resolve(n)}))}getTargetOptions(){let t=e.U.clone(e.appTarget.compile);return e.U.assert(!!t),t.utf8||this.sortedDeps(!0).forEach((n=>{n.config&&n.config.utf8&&(e.debug("forcing utf8 mode: pkg="+n.id),t.utf8=!0)})),t}getJRes(){if(!this._jres){this._jres={};for(const e of this.sortedDeps())e.parseJRes(this._jres);const t=(e.appTarget.runtime&&e.appTarget.runtime.palette?e.appTarget.runtime.palette:["#000000","#ffffff"]).map((e=>("000000"+parseInt(e.replace(/#/,""),16).toString(16)).slice(-6))).join("");this._jres.__palette={id:"__palette",data:t,dataEncoding:"hex",mimeType:"application/x-palette"}}return this._jres}updateJRes(){this._jres&&this.parseJRes(this._jres)}resolveBannedCategories(){if(void 0!==this._resolvedBannedCategories)return this._resolvedBannedCategories;let t=[];return e.appTarget&&e.appTarget.runtime&&e.appTarget.runtime.bannedCategories&&e.appTarget.runtime.bannedCategories.length&&(t=e.appTarget.runtime.bannedCategories.slice(),Object.keys(this.deps).map((e=>this.deps[e])).filter((e=>!!e)).map((t=>e.Util.jsonTryParse(t.readFile(e.CONFIG_NAME)))).filter((e=>e&&e.requiredCategories)).forEach((e=>e.requiredCategories.forEach((e=>{const n=t.indexOf(e);n>-1&&t.splice(n,1)})))),this._resolvedBannedCategories=t),this._resolvedBannedCategories=t,this._resolvedBannedCategories.length||(this._resolvedBannedCategories=null),this._resolvedBannedCategories}async getCompileOptionsAsync(t=this.getTargetOptions()){let n={sourceFiles:[],fileSystem:{},target:t,name:this.config?this.config.name:""};const i=(t,n)=>{this.config.files.indexOf(t)<0&&e.U.userError(lf("please add '{0}' to \"files\" in {1}",t,e.CONFIG_NAME)),n="// Auto-generated. Do not edit.\n"+n+"\n// Auto-generated. Do not edit. Really.\n",this.host().readFile(this,t,!0)!==n&&(e.debug(`updating ${t} (size=${n.length})...`),this.host().writeFile(this,t,n,!0))};let s=!1;const r=async n=>{const r={extinfo:null,target:null},a=e.appTargetVariant;n&&e.setAppTargetVariant(n,{temporary:!0});try{let o=e.cpp.getExtensionInfo(this);s||!o.shimsDTS&&!o.enumsDTS||(s=!0,o.shimsDTS&&i("shims.d.ts",o.shimsDTS),o.enumsDTS&&i("enums.d.ts",o.enumsDTS));const l=t.isNative?await this.host().getHexInfoAsync(o):null;o=e.U.flatClone(o),t.keepCppFiles||(delete o.compileData,delete o.generatedFiles,delete o.extensionFiles),o.hexinfo=l,r.extinfo=o,r.target=e.appTarget.compile}finally{n&&e.setAppTargetVariant(a,{temporary:!0})}return r};let a;await this.loadAsync(),n.bannedCategories=this.resolveBannedCategories(),n.target.preferredEditor=this.getPreferredEditor(),e.debug(`building: ${this.sortedDeps().map((e=>e.config.name)).join(", ")}`),a=e.appTarget.multiVariants?e.appTargetVariant?[e.appTargetVariant]:e.appTarget.alwaysMultiVariant||e.appTarget.compile.switches.multiVariant?e.appTarget.multiVariants:[e.appTarget.multiVariants[0]]:[null];let o=null;for(let t of a){o&&e.debug(`building for ${t}`);const i=await r(t),s=i.extinfo;s.appVariant=t,s.outputPrefix=1!=a.length&&t?t+"-":"",o?n.otherMultiVariants.push(i):(o=s,n.otherMultiVariants=[])}n.extinfo=o;if(!(e.appTarget.compile.shortPointers||"vm"==e.appTarget.compile.nativeType||this.config.binaryonly||!n.target.isNative)){const t=await this.filesToBePublishedAsync(!0),i=JSON.stringify({name:this.config.name,comment:this.config.description,status:"unpublished",scriptId:this.installedVersion,cloudId:e.CLOUD_ID+e.appTarget.id,editor:this.getPreferredEditor(),targetVersions:e.appTarget.versions}),s=JSON.stringify(t),r=await e.lzmaCompressAsync(i+s);r&&(n.embedMeta=JSON.stringify({compression:"LZMA",headerSize:i.length,textSize:s.length,name:this.config.name,eURL:e.appTarget.appTheme.embedUrl,eVER:e.appTarget.versions?e.appTarget.versions.target:"",pxtTarget:e.appTarget.id}),n.embedBlob=ts.pxtc.encodeBase64(e.U.uint8ArrayToString(r)))}for(const e of this.sortedDeps())for(const t of e.getFiles())if(/\.(ts|asm|py)$/.test(t)){let i=t;e.level>0&&(i="pxt_modules/"+e.id+"/"+t),n.sourceFiles.push(i),n.fileSystem[i]=e.readFile(t)}n.jres=this.getJRes();const l=e.appTarget.runtime&&e.appTarget.runtime.functionsOptions;return n.allowedArgumentTypes=l&&l.extraFunctionEditorTypes&&l.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,i)=>{if(!i||/^(file|workspace):/.test(i)){i="*";try{const t=this.resolveDep(n).readGitJson();if(t&&t.repo){let n=e.github.parseRepoId(t.repo);n.tag=t.commit.tag||t.commit.sha,i=e.github.stringifyRepo(n)}}catch(e){}t.dependencies[n]=i}})),t}filesToBePublishedAsync(t=!1){const n={};return this.loadAsync().then((()=>{t||this.config.public||e.U.userError('Only packages with "public":true can be published');const i=this.prepareConfigToBePublished();n[e.CONFIG_NAME]=e.Package.stringifyConfig(i);for(let t of this.getFiles()){if(t==e.CONFIG_NAME)continue;let i=this.readFile(t);null==i&&e.U.userError("referenced file missing: "+t),n[t]=i}return e.U.sortObjectFields(n)}))}saveToJsonAsync(){return this.filesToBePublishedAsync(!0).then((t=>({meta:{cloudId:e.CLOUD_ID+e.appTarget.id,targetVersions:e.appTarget.versions,editor:this.getPreferredEditor(),name:this.config.name},source:JSON.stringify(t,null,2)})))}compressToFileAsync(){return this.saveToJsonAsync().then((t=>e.lzmaCompressAsync(JSON.stringify(t,null,2))))}computePartDefinitions(t){if(!t||!t.length)return{};let n={};return this.sortedDeps().forEach((i=>{let s=i.readFile("pxtparts.json");if(s)try{let r=JSON.parse(s);Object.keys(r).forEach((s=>{if(t.indexOf(s)>=0){let t=n[s]=r[s];if("string"==typeof t.visual.image&&/\.svg$/i.test(t.visual.image)){let n=i.readFile(t.visual.image);n||e.reportError("parts","invalid part definition",{error:`missing visual ${t.visual.image}`}),/^data:image\/svg\+xml/.test(n)||(n="data:image/svg+xml,"+encodeURIComponent(n)),t.visual.image=n}}}))}catch(t){e.reportError("parts","invalid pxtparts.json file")}})),n}},e.inflateJRes=i,e.allPkgFiles=function(t){return[e.CONFIG_NAME].concat(t.files||[]).concat(t.testFiles||[])},e.isPkgBeta=function(e){return e&&/\bbeta\b/.test(e.description)}}(pxt||(pxt={})),function(e){!function(t){let n,i,s,r,a,o=()=>{};function l(){if(a)return a;let t=Promise.resolve();if(n){e.debug("packetio: disconnect");const s=n;t=t.then((()=>s.disconnectAsync())).then((()=>s.io.disposeAsync())).catch((t=>{e.reportException(t)})).finally((()=>{i=void 0,n=void 0,a=void 0})),o&&(t=t.then((()=>o()))),a=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=l,t.configureEvents=function(e,t,i){o=e,s=t,r=i,n&&(n.io.onConnectionChanged=o,n.onSerial=s,n.onCustomEvent=i)},t.sendCustomEventAsync=function(e,t){return n?n.sendCustomEventAsync(e,t):Promise.resolve()},t.initAsync=function(a=!1){if(e.debug("packetio: init "+(a?"(force)":"")),!i){let c=Promise.resolve();a&&(c=c.then((()=>l()))),i=c.then((()=>n?Promise.resolve(n):t.mkPacketIOAsync?(e.debug("packetio: new wrapper"),t.mkPacketIOAsync().then((e=>(e.onConnectionChanged=o,n=t.mkPacketIOWrapper(e),s&&(n.onSerial=s),r&&(n.onCustomEvent=r),o&&o(),n)))):(e.debug("packetio: not defined, skipping"),Promise.resolve(void 0)))).finally((()=>{i=void 0}))}return i}}(e.packetio||(e.packetio={}))}(pxt||(pxt={})),function(e){!function(t){t.computePatches=function(t,n){const i=e.appTarget.compile?e.appTarget.compile.patches:void 0;if(!i)return;const s=e.semver.tryParse(t||"0.0.0")||e.semver.tryParse("0.0.0");let r=[];return Object.keys(i).filter((t=>e.semver.inRange(t,s))).forEach((e=>r=r.concat(i[e]))),n&&(r=r.filter((e=>e.type==n))),r.length?r:void 0},t.upgradePackageReference=function(t,n,i){if("*"!=i)return n;const s=e.patching.computePatches(t,"package");let r=n;return s&&s.forEach((e=>{Object.keys(e.map).forEach((t=>{r==t&&(r=e.map[t])}))})),r},t.patchJavaScript=function(t,n){const i=e.patching.computePatches(t);let s=n;return i&&(i.filter((e=>"api"===e.type)).forEach((e=>{Object.keys(e.map).forEach((t=>{const n=new RegExp(t,"g");s=s.replace(n,e.map[t])}))})),i.filter((e=>"userenum"===e.type)).forEach((e=>{Object.keys(e.map).forEach((t=>{const n=new RegExp("enum\\s+"+t+"\\s*{","gm");s=s.replace(n,`enum ${e.map[t]} {`);const i=new RegExp(`(^|[^_a-zA-Z0-9])${t}(\\s*\\.)`,"g");s=s.replace(i,`$1${e.map[t]}$2`)}))}))),s}}(e.patching||(e.patching={}))}(pxt||(pxt={})),function(e){e.react||(e.react={})}(pxt||(pxt={})),function(e){!function(t){function n(t,n){if(t){if(n){let i=t.major-n.major||t.minor-n.minor||t.patch-n.patch;if(i)return i;if(0==t.pre.length&&n.pre.length>0)return 1;if(t.pre.length>0&&0==n.pre.length)return-1;for(let s=0;s<t.pre.length+1;++s){let r=t.pre[s],a=n.pre[s];if(!r)return a?-1:0;if(!a)return 1;if(/^\d+$/.test(r)){if(!/^\d+$/.test(a))return-1;if(i=parseInt(r)-parseInt(a),i)return i}else{if(/^\d+$/.test(a))return 1;if(i=e.U.strcmp(r,a),i)return i}}return 0}return-1}return n?1:0}function i(t,n){let i=s(t)||s(n);return i||e.U.userError(e.U.lf("'{0}' doesn't look like a semantic version number",t)),i}function s(e){if(!e)return null;if("*"===e)return{major:Number.MAX_SAFE_INTEGER,minor:Number.MAX_SAFE_INTEGER,patch:Number.MAX_SAFE_INTEGER,pre:[],build:[]};/^v\d/i.test(e)&&(e=e.slice(1));let t=/^(\d+)\.(\d+)\.(\d+)(-([0-9a-zA-Z\-\.]+))?(\+([0-9a-zA-Z\-\.]+))?$/.exec(e);return t?{major:parseInt(t[1]),minor:parseInt(t[2]),patch:parseInt(t[3]),pre:t[5]?t[5].split("."):[],build:t[7]?t[7].split("."):[]}:null}function r(e){let t=e.major+"."+e.minor+"."+e.patch;return e.pre.length&&(t+="-"+e.pre.join(".")),e.build.length&&(t+="+"+e.build.join(".")),t}function a(t,i){let r=s(t),a=s(i);return r||a?n(r,a):e.U.strcmp(t,i)}function o(e,t){let i=e.split(" - ");if(2!=i.length)return!1;let r=s(i[0]),a=s(i[1]);if(!r||!a)return!1;if(!t)return!0;const o=n(r,t),l=n(t,a);return o<=0&&l<0}t.cmp=n,t.parse=i,t.tryParse=s,t.normalize=function(e){return r(i(e))},t.stringify=r,t.majorCmp=function(e,t){let n=s(e),i=s(t);return n.major-i.major},t.strcmp=a,t.inRange=o,t.sortLatestTags=function(e){const n=e.filter((e=>!!t.tryParse(e)));return n.sort(a),n.reverse(),n},t.test=function(){console.log("Test semver");let t=["0.9.0","1.0.0-0.3.7","1.0.0-alpha","1.0.0-alpha.1","1.0.0-alpha.beta","1.0.0-beta","1.0.0-beta.2","1.0.0-beta.11","1.0.0-rc.1","1.0.0-x.7.z.92","1.0.0","1.0.1","1.9.0","1.10.0","1.11.0"];for(let s=0;s<t.length;++s){let a=i(t[s]);console.log(t[s],a),e.U.assert(r(a)==t[s]);for(let r=0;r<t.length;++r){let o=n(a,i(t[r]));console.log(t[s],t[r],o),s<r?e.U.assert(o<0):s>r?e.U.assert(o>0):e.U.assert(0==o)}}const a=s("1.2.3");e.U.assert(o("0.1.2 - 2.2.3",a)),e.U.assert(o("1.2.3 - 2.2.3",a)),e.U.assert(!o("0.0.0 - 1.2.3",a)),e.U.assert(!o("1.2.4 - 4.2.3",a)),e.U.assert(!o("0.0.0 - 0.0.1",a))}}(e.semver||(e.semver={}))}(pxt||(pxt={})),function(e){!function(e){function t(t){return e.Util.values(t.byQName).filter((e=>e.attributes.block&&/^{[^:]+:[^}]+}/.test(e.attributes.block))).forEach((e=>{e.attributes.block=e.attributes.block.replace(/^{[^:]+:[^}]+}/,"")})),t}e.assert=e.Util.assert,e.oops=e.Util.oops,e.U=e.Util,e.ON_START_TYPE="pxt-on-start",e.ON_START_COMMENT="on start",e.HANDLER_COMMENT="code goes here",e.TS_STATEMENT_TYPE="typescript_statement",e.TS_DEBUGGER_TYPE="debugger_keyword",e.TS_BREAK_TYPE="break_keyword",e.TS_CONTINUE_TYPE="continue_keyword",e.TS_OUTPUT_TYPE="typescript_expression",e.TS_RETURN_STATEMENT_TYPE="function_return",e.PAUSE_UNTIL_TYPE="pxt_pause_until",e.COLLAPSED_BLOCK="pxt_collapsed_block",e.FUNCTION_DEFINITION_TYPE="function_definition",e.BINARY_JS="binary.js",e.BINARY_ASM="binary.asm",e.BINARY_HEX="binary.hex",e.BINARY_UF2="binary.uf2",e.BINARY_ELF="binary.elf",e.BINARY_PXT64="binary.pxt64",e.BINARY_ESP="binary.bin",e.BINARY_SRCMAP="binary.srcmap",e.NATIVE_TYPE_THUMB="thumb",e.NATIVE_TYPE_VM="vm",e.BuildSourceMapHelpers=function(e,t,n){const i=e=>{const t=e.split("\n").map((e=>e.length)),n=t.reduce((({lens:e,sum:t},n)=>({lens:[...e,t+n+1],sum:t+n+1})),{lens:[],sum:0}).lens;return{posToLineCol:e=>{const i=n.reduce(((t,n,i)=>e<n?t:i+1),0);return[i,t[i]-(n[i]-e)+1]},lineColToPos:(e,t)=>(n[e-1]||0)+t}},s={ts:i(t),py:i(n)},r=e=>e.endPos-e.startPos,a=(t,n)=>{const{startPos:i,endPos:s}=t;return e.filter((e=>e[n].startPos<=i&&s<=e[n].endPos))},o=(e,t)=>{const n=a(e,t);return n.reduce(((e,n)=>r(n[t])<r(e[t])?n:e),n[0])},l={ts:{allOverlaps:e=>a(e,"ts"),smallestOverlap:e=>o(e,"ts")},py:{allOverlaps:e=>a(e,"py"),smallestOverlap:e=>o(e,"py")}},c=(e,t)=>n=>{const[i,a]=(t=>[s[e].lineColToPos(t.line,t.column),t.length])(n),l=o({startPos:i,endPos:i+a},e);if(!l)return;const[c,u]=s[t].posToLineCol(l[t].startPos);return{fileName:`main.${t}`,start:l[t].startPos,length:r(l[t]),line:c,column:u}},u=c("ts","py"),d=c("py","ts");return{ts:Object.assign(Object.assign(Object.assign({},s.ts),l.ts),{locToLoc:u,getText:e=>t.substring(e.startPos,e.endPos)}),py:Object.assign(Object.assign(Object.assign({},s.py),l.py),{locToLoc:d,getText:e=>n.substring(e.startPos,e.endPos)})}},e.computeUsedParts=function(e,t){if(!e.usedSymbols||!pxt.appTarget.simulator||!pxt.appTarget.simulator.parts)return[];let n=[];if(Object.keys(e.usedSymbols).forEach((t=>{let i=e.usedSymbols[t];if(i&&i.attributes.parts){let e=i.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 i,a;let o=[];const l={},c={},u={},d={},h={};function p(t,n){const i="get"==t,s="set"==t,a="number"==n.retType,d=i?c:s?l:u,h=`${n.namespace}.${n.retType}`;let p=e.U.lookup(d,h);if(!p){const l=`@${t}@`;let c,u;if(n.attributes.blockCombineShadow){const t=n.attributes.blockCombineShadow,i=t.match(/^([^,.]*),?([^,.]*)$/);i&&3==i.length&&(c=i[1].trim(),u=i[2].trim(),0!=u.length||e.Util.endsWith(t,",")||(u=c,c=""))}const f=`${n.attributes.blockSetVariable||n.namespace.toLocaleLowerCase()}=${c||""}`,g=`value=${u||""}`;p=d[h]={attributes:{blockId:`${a?n.namespace:h}_blockCombine_${t}`,callingConvention:0,group:n.attributes.group,paramDefl:{},jsDoc:i?e.U.lf("Read value of a property on an object"):e.U.lf("Update value of property on an object")},name:l,namespace:n.namespace,fileName:n.fileName,qName:`${h}.${l}`,pkg:n.pkg,kind:2,parameters:[{name:"property",description:i?e.U.lf("the name of the property to read"):e.U.lf("the name of the property to change"),isEnum:!0,type:"@combined@"},{name:"value",description:s?e.U.lf("the new value of the property"):e.U.lf("the amount by which to change the property"),type:n.retType}].slice(0,i?1:2),retType:i?n.retType:"void",combinedProperties:[]},p.attributes.block=i?e.U.lf("%{0} %property",f):s?e.U.lf("set %{0} %property to %{1}",f,g):e.U.lf("change %{0} %property by %{1}",f,g),r(p.attributes),pxt.Util.isTranslationMode()&&(p.attributes.translationId=p.attributes.block,p.attributes.block=i?`%${f} %property`:s?`set %${f} %property to %${g}`:`change %${f} %property by %${g}`,r(p.attributes),pxt.crowdin.inContextLoadAsync(p.attributes.translationId).then((e=>{p.attributes.block=e,r(p.attributes)}))),o.push(p)}p.combinedProperties.push(n.qName)}for(let n of e.Util.values(t.byQName)){if("ENUM_GET"===n.attributes.shim&&n.attributes.enumName&&n.attributes.blockId){let e=!1;if(d[n.attributes.enumName]&&(console.warn(`Enum block ${n.attributes.blockId} trying to overwrite enum ${n.attributes.enumName}`),e=!0),n.attributes.enumMemberName||(console.warn(`Enum block ${n.attributes.blockId} should specify enumMemberName`),e=!0),n.attributes.enumPromptHint||(console.warn(`Enum block ${n.attributes.blockId} should specify enumPromptHint`),e=!0),n.attributes.enumInitialMembers&&n.attributes.enumInitialMembers.length||(console.warn(`Enum block ${n.attributes.blockId} should specify enumInitialMembers`),e=!0),e)continue;const t=parseInt(n.attributes.enumStartValue);d[n.attributes.enumName]={blockId:n.attributes.blockId,name:n.attributes.enumName,memberName:n.attributes.enumMemberName,firstValue:isNaN(t)?void 0:t,isBitMask:n.attributes.enumIsBitMask,isHash:n.attributes.enumIsHash,initialMembers:n.attributes.enumInitialMembers,promptHint:n.attributes.enumPromptHint}}if("KIND_GET"===n.attributes.shim&&n.attributes.blockId){const i=n.attributes.kindNamespace||n.attributes.blockNamespace||n.namespace;if(h[i]){console.warn(`More than one block defined for kind ${i}`);continue}const s=[];if(t.byQName[i])for(const n of e.Util.values(t.byQName))n.namespace===i&&n.attributes.isKind&&s.push(n.name);h[i]={blockId:n.attributes.blockId,name:i,memberName:n.attributes.kindMemberName||i,initialMembers:s,promptHint:n.attributes.enumPromptHint||e.Util.lf("Create a new kind..."),createFunctionName:n.attributes.kindCreateFunction||"create"}}if(n.attributes.blockCombine)/@set/.test(n.name)||p("get",n),n.isReadOnly||("number"==n.retType&&p("change",n),p("set",n));else if(n.attributes.block&&!n.attributes.fixedInstance&&7!=n.kind&&5!=n.kind&&9!=n.kind&&8!=n.kind){if(n.attributes.blockId||(n.attributes.blockId=n.qName.replace(/\./g,"_")),"true"==n.attributes.block){let t=e.U.uncapitalize(n.name);1!=n.kind&&2!=n.kind||(t+=" %"+n.namespace.toLowerCase());const o=null!==(a=null===(i=n.parameters)||void 0===i?void 0:i.filter((e=>!s(e))))&&void 0!==a?a:[];for(let e of o)t+=" %"+e.name;n.attributes.block=t,r(n.attributes)}o.push(n)}}for(let n of o){let i=e.U.lookup(t.byQName,n.namespace);if(!i)continue;let s=i.attributes,r=n.attributes;for(let e of["blockNamespace","color","blockGap"])void 0===r[e]&&s[e]&&(r[e]=s[e])}var f;return n&&((f=n).length&&(o=o.filter((e=>{let t=(e.attributes.blockNamespace||e.namespace).split(".")[0];return-1===f.indexOf(t)})))),{apis:t,blocks:o,blocksById:pxt.Util.toDictionary(o,(e=>e.attributes.blockId)),enumsByName:d,kindsByName:h}},e.tsSnippetToPySnippet=function(t,n){const i={true:"True",false:"False",null:"None"}[t];if(i)return i;if(n&&6==n.kind||!n&&t.includes(".")){const n=t.lastIndexOf("."),i=t.substr(0,n);let s=t.substr(n+1);return s=e.U.snakify(s).toUpperCase(),`${i}.${s}`}return t},e.apiLocalizationStrings={},e.localizeApisAsync=async function(n,i){const s=e.Util.userLanguage();if("en"==s)return Promise.resolve(t(n));const a=s.toLowerCase(),o=a+"|jsdoc",l=a+"|block",c=await i.localizationStringsAsync(s);e.apiLocalizationStrings&&e.Util.jsonMergeFrom(c,e.apiLocalizationStrings);const u=e.Util.values(n.byQName).filter((e=>e.attributes._translatedLanguageCode!==s));return await e.Util.promiseMapAll(u,(async t=>{var i,u,d;const h=t.attributes.useLoc||t.attributes.blockAliasFor,p=h&&n.byQName[h];t.attributes._untranslatedJsDoc&&(t.attributes.jsDoc=t.attributes._untranslatedJsDoc),t.attributes._untranslatedBlock&&(t.attributes.jsDoc=t.attributes._untranslatedBlock);const f=(e,n)=>{var i,s;return c[t.qName+e]||(null===(i=t.attributes.locs)||void 0===i?void 0:i[n])||p&&(c[p.qName+e]||(null===(s=p.attributes.locs)||void 0===s?void 0:s[n]))},g=f("",o);g&&(t.attributes._untranslatedJsDoc||(t.attributes._untranslatedJsDoc=t.attributes.jsDoc),t.attributes.jsDoc=g),null===(i=t.parameters)||void 0===i||i.forEach((e=>{const t=`|param|${e.name}`,n=f(t,a+t);n&&(e.description=n)}));const m=c["{id:category}"+e.Util.capitalize(t.qName)];let b=c[`${t.qName}|block`]||(null===(u=t.attributes.locs)||void 0===u?void 0:u[l]);if(!b&&p){const e=c[`${p.qName}|block`]||(null===(d=p.attributes.locs)||void 0===d?void 0:d[l]);t.attributes.block===(p.attributes._untranslatedBlock||p.attributes.block)&&e&&(b=e)}if(b&&pxt.Util.isTranslationMode()&&(t.attributes.translationId=b,b=await pxt.crowdin.inContextLoadAsync(b)),m)t.attributes.block?t.attributes.block=b||t.attributes.block:t.attributes.block=m,r(t.attributes);else if(t.attributes.block&&b){const e=pxt.blocks.compileInfo(t),n=t.attributes.block;if(t.attributes.block=pxt.blocks.normalizeBlock(b,(e=>{pxt.tickEvent("loc.normalized",{block:t.attributes.block,lang:s,error:e})})),t.attributes._untranslatedBlock||(t.attributes._untranslatedBlock=n),n!=t.attributes.block){r(t.attributes);(function(e,t){if(e.parameters.length!=t.parameters.length)return pxt.debug("Localized block has extra or missing parameters"),!1;for(const n of e.parameters){const e=t.actualNameToParam[n.actualName];if(!e||n.type!=e.type||n.shadowBlockId!=e.shadowBlockId)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:s}),t.attributes.block=n,r(t.attributes))}}else r(t.attributes);t.attributes._translatedLanguageCode=s})),t(n)},e.emptyExtInfo=function(){let e=pxt.appTarget.compileService;e||(e={});const t=!!e.platformioIni,n="dockermake"==e.buildEngine||"dockercross"==e.buildEngine||"dockerespidf"==e.buildEngine,i={functions:[],generatedFiles:{},extensionFiles:{},sha:"",compileData:"",shimsDTS:"",enumsDTS:"",onlyPublic:!0};return t?i.platformio={dependencies:{}}:n?i.npmDependencies={}:i.yotta={config:{},dependencies:{}},i};const n=["weight","imageLiteral","topblockWeight"],i=["advanced","handlerStatement","afterOnStart","optionalVariableArgs","blockHidden","constantShim","blockCombine","enumIsBitMask","enumIsHash","decompileIndirectFixedInstances","topblock","callInDebugger","duplicateShadowOnDrag","argsNullable"];function s(e){return"Action"===e.type||/^\([^\)]*\)\s*=>/.test(e.type)}function r(e){if(e.block){const n=e.block.split("||");e._def=t(a(n[0])),e._def||pxt.debug("Unable to parse block def for id: "+e.blockId),n[1]&&(e._expandedDef=t(a(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 a(e){const t=[];let n,i=0;for(;i<e.length;i++){const s=e[i],r=i;let a;switch(s){case"*":case"_":const t=d((e=>e==s)),n="_"===s?2:0;1===t.length?a={kind:1<<n,content:t}:2===t.length?a={kind:2<<n,content:t}:3===t.length?a={kind:3<<n,content:t}:i=r;break;case"`":const o=h("`");if(void 0===o){i=r;break}a={kind:256,content:o};break;case"|":a={kind:32};break;case"\\":i<e.length-1&&(a={kind:16,content:e[1+i++]});break;case"[":const l=h("]");if(void 0!==l&&"("===e[1+i++]){const e=h(")");if(void 0!==e){a={kind:512,content:l,type:e};break}}i=r;break;case"$":case"%":const c=d((e=>/[a-zA-Z0-9_=]/.test(e)),!0).split("=");if(c.length>2){i=r;break}let u;if("("===e[i+1]){const e=i;++i,u=h(")"),u||(i=e)}a={kind:"$"===s?1024:64,content:c[0],type:c[1],name:u}}a?(n&&t.push({kind:128,content:n}),n=void 0,t.push(a)):n?n+=s:n=s}n&&t.push({kind:128,content:n});const s=[],r=[];let a=[],l=0,c="",u=[];for(let e=0;e<t.length;e++){const n=t[e].kind,i=a[a.length-1];if(15&n)if(g(t[e].content),n&l)if(i&n){a.pop(),l^=n;const e=i&l|n&l;e&&a.push(e)}else p();else l|=n,a.push(n);else 144&n?c+=t[e].content:1120&n&&f();if(64==n){const n={kind:"param",name:t[e].content,shadowBlockId:t[e].type,ref:!1};t[e].name&&(n.varName=t[e].name),s.push(n),r.push(n)}else if(1024==n){const n={kind:"param",name:t[e].content,shadowBlockId:t[e].type,ref:!0};t[e].name&&(n.varName=t[e].name),s.push(n),r.push(n)}else 256==n?(g(),u.push({kind:"image",uri:t[e].content})):512==n?(g(),u.push({kind:"label",text:t[e].content,cssClass:t[e].type})):32==n&&s.push({kind:"break"})}return f(),{parts:s,parameters:r};function d(t,n=!1){let s="";for(n&&i++;i<e.length&&t(e[i]);)s+=e[i],++i;return s&&i--,s}function h(t){const n=d((e=>e!==t),!0);if(e[i+1]===t)return++i,n}function p(){let e="",t=[];for(const n of u)o(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}),a=[],l=0}function f(){for(g(),l&&p();u.length;){const e=u.shift();if(o(e))s.push(e);else{if(!e.content)continue;const t=[];10&e.styles&&t.push("bold"),5&e.styles&&t.push("italics"),s.push({kind:"label",text:e.content,style:t})}}}function g(e){u.push({content:c,styles:l,endingToken:e}),c=""}}function o(e){return!!e.kind}let l;e.parseCommentString=function(t){let s={paramDefl:{},callingConvention:0,_source:t},a=!0;for(;a;)a=!1,t=t.replace(/\/\/%[ \t]*([\w\.-]+)(=(("[^"\n]*")|'([^'\n]*)'|([^\s]*)))?/,((t,n,i,r,o,l,c)=>{let u=o?JSON.parse(o):i?o||l||c:"true";if(u||(u=""),e.U.startsWith(n,"block.loc."))s.locs||(s.locs={}),s.locs[n.slice("block.loc.".length).toLowerCase()+"|block"]=u;else if(e.U.startsWith(n,"jsdoc.loc."))s.locs||(s.locs={}),s.locs[n.slice("jsdoc.loc.".length).toLowerCase()+"|jsdoc"]=u;else if(e.U.contains(n,".loc.")){s.locs||(s.locs={});const e=n.slice(0,n.indexOf(".loc.")),t=n.slice(n.indexOf(".loc.")+".loc.".length);s.locs[t+"|param|"+e]=u}else if(e.U.endsWith(n,".defl"))u.indexOf(" ")>-1?s.paramDefl[n.slice(0,n.length-5)]=`"${u}"`:s.paramDefl[n.slice(0,n.length-5)]=u,s.explicitDefaults||(s.explicitDefaults=[]),s.explicitDefaults.push(n.slice(0,n.length-5));else if(e.U.endsWith(n,".shadow"))s._shadowOverrides||(s._shadowOverrides={}),s._shadowOverrides[n.slice(0,n.length-7)]=u;else if(e.U.endsWith(n,".fieldEditor"))s.paramFieldEditor||(s.paramFieldEditor={}),s.paramFieldEditor[n.slice(0,n.length-12)]=u;else if(e.U.contains(n,".fieldOptions.")){s.paramFieldEditorOptions||(s.paramFieldEditorOptions={});const e=n.slice(0,n.indexOf(".fieldOptions.")),t=n.slice(n.indexOf(".fieldOptions.")+14,n.length);s.paramFieldEditorOptions[e]||(s.paramFieldEditorOptions[e]={}),s.paramFieldEditorOptions[e][t]=u}else if(e.U.contains(n,".shadowOptions.")){s.paramShadowOptions||(s.paramShadowOptions={});const e=n.slice(0,n.indexOf(".shadowOptions.")),t=n.slice(n.indexOf(".shadowOptions.")+15,n.length);s.paramShadowOptions[e]||(s.paramShadowOptions[e]={}),s.paramShadowOptions[e][t]=u}else e.U.endsWith(n,".min")?(s.paramMin||(s.paramMin={}),s.paramMin[n.slice(0,n.length-4)]=u):e.U.endsWith(n,".max")?(s.paramMax||(s.paramMax={}),s.paramMax[n.slice(0,n.length-4)]=u):s[n]=u;return a=!0,"//% "}));for(let e of n)"string"==typeof s[e]&&(s[e]=parseInt(s[e]));for(let e of i)"string"==typeof s[e]&&(s[e]="true"==s[e]||"1"==s[e]);if(s.trackArgs&&(s.trackArgs=s.trackArgs.split(/[ ,]+/).map((e=>parseInt(e)||0))),s.enumInitialMembers&&(s.enumInitialMembers=s.enumInitialMembers.split(/[ ,]+/)),s.blockExternalInputs&&!s.inlineInputMode&&(s.inlineInputMode="external"),s.paramHelp={},s.jsDoc="",t=t.replace(/\/\*\*([^]*?)\*\//g,((e,t)=>(t=(t=t.replace(/\n\s*(\*\s*)?/g,"\n")).replace(/^\s*@param\s+(\w+)\s+(.*)$/gm,((e,t,n)=>{if(s.paramHelp[t]=n,!s.paramDefl[t]){let e=/\beg\.?:\s*(.+)/.exec(n);if(e&&e[1]){let n=/(?:"([^"]*)")|(?:'([^']*)')|(?:([^\s,]+))/g.exec(e[1]);if(n){let e=n[1]||n[2]||n[3];e||(e=""),e.indexOf(" ")>-1?s.paramDefl[t]=`"${e}"`:s.paramDefl[t]=e}}}return""})),s.jsDoc+=t,""))),s.jsDoc=s.jsDoc.trim(),s.async&&(s.callingConvention=1),s.promise&&(s.callingConvention=2),s.jres&&(s.whenUsed=!0),s.subcategories)try{s.subcategories=JSON.parse(s.subcategories)}catch(e){s.subcategories=void 0}if(s.groups)try{s.groups=JSON.parse(s.groups)}catch(e){s.groups=void 0}if(s.groupIcons)try{s.groupIcons=JSON.parse(s.groupIcons)}catch(e){s.groupIcons=void 0}if(s.groupHelp)try{s.groupHelp=JSON.parse(s.groupHelp)}catch(e){s.groupHelp=void 0}return r(s),s},e.parameterTypeIsArrowFunction=s,e.updateBlockDef=r,e.parseBlockDefinition=a,e.parseChecksumBlock=function(e,t=0){let n=pxt.HF2.read32(e,t);if(133083260!=(2147483647&n))return pxt.log("no checksum block magic"),null;let i=pxt.HF2.read32(e,t+4),s=pxt.HF2.read32(e,t+8);if(3&i)return pxt.log("invalid end marker position"),null;let r=1<<(255&s);if(r!=pxt.appTarget.compile.flashCodeAlign)return pxt.log("invalid page size: "+r),null;let a={magic:n,endMarkerPos:i,endMarker:s,regions:[]};for(let n=t+12;n<e.length-7;n+=8){let t={start:r*pxt.HF2.read16(e,n),length:r*pxt.HF2.read16(e,n+2),checksum:pxt.HF2.read32(e,n+4)};if(!t.length||!t.checksum)break;a.regions.push(t)}return a},function(t){function n(n){let i=e=>n[e]+(n[e+1]<<8)+(n[e+2]<<16)+(n[e+3]<<24)>>>0;if(!n||512!=n.length||i(0)!=t.UF2_MAGIC_START0||i(4)!=t.UF2_MAGIC_START1||i(n.length-4)!=t.UF2_MAGIC_END)return null;let s=i(8),r=i(16);r>476&&(r=256);let a=null,o=0,l=0;if(s&t.UF2_FLAG_FILE){let t=n.slice(32+r),s=t.indexOf(0);s>=0&&(t=t.slice(0,s)),a=e.U.fromUTF8Array(t),l=i(28)}return s&t.UF2_FLAG_FAMILY_ID_PRESENT&&(o=i(28)),{flags:s,targetAddr:i(12),payloadSize:r,blockNo:i(20),numBlocks:i(24),fileSize:l,familyId:o,data:n.slice(32,32+r),filename:a}}function i(e,t){return!!e&&(e.targetAddr<=t&&t<e.targetAddr+e.payloadSize)}function s(e,t,n){e[t]=255&n,e[t+1]=n>>8&255,e[t+2]=n>>16&255,e[t+3]=n>>24&255}function r(e){return"string"==typeof e&&(e=parseInt(e)),{currBlock:null,currPtr:-1,blocks:[],ptrs:[],filesize:0,familyId:e||0}}function a(e){for(let t=0;t<e.blocks.length;++t)s(e.blocks[t],20,t),s(e.blocks[t],24,e.blocks.length),e.filename&&s(e.blocks[t],28,e.filesize)}function o(n,i,r,a=0){let l=n.currBlock,c=i>>8,u=256-(255&i);if(r.length>u){let e=new Uint8Array(r);for(o(n,i,e.slice(0,u));u<r.length;){let t=Math.min(u+256,r.length);o(n,i+u,e.slice(u,t)),u=t}return}if(c!=n.currPtr){l=null;for(let e=0;e<n.ptrs.length;++e)if(n.ptrs[e]==c){l=n.blocks[e];break}if(!l){l=new Uint8Array(512),n.filename?a|=t.UF2_FLAG_FILE:n.familyId&&(a|=t.UF2_FLAG_FAMILY_ID_PRESENT),s(l,0,t.UF2_MAGIC_START0),s(l,4,t.UF2_MAGIC_START1),s(l,8,a),s(l,12,c<<8),s(l,16,256),s(l,20,n.blocks.length),s(l,28,n.familyId),s(l,508,t.UF2_MAGIC_END);for(let e=32;e<288;++e)l[e]=255;n.filename&&e.U.memcpy(l,288,e.U.toUTF8Array(n.filename)),n.blocks.push(l),n.ptrs.push(c)}n.currPtr=c,n.currBlock=l}let d=32+(255&i);for(let e=0;e<r.length;++e)l[d+e]=r[e];n.filesize=Math.max(n.filesize,r.length+i)}t.UF2_MAGIC_START0=171066965,t.UF2_MAGIC_START1=2656915799,t.UF2_MAGIC_END=179400496,t.UF2_FLAG_NONE=0,t.UF2_FLAG_NOFLASH=1,t.UF2_FLAG_FILE=4096,t.UF2_FLAG_FAMILY_ID_PRESENT=8192,t.parseBlock=n,t.parseFile=function(e){let t=[];for(let i=0;i<e.length;i+=512){let s=n(e.slice(i,i+512));s&&t.push(s)}return t},t.toBin=function(e,t){if(e.length<512)return null;let i=-1,s=-1,r=[];for(let a=0;a<e.length;++a){let o=512*a,l=n(e.slice(o,o+512));if(!l)continue;if(t&&l.targetAddr+256>t)break;-1==i&&(i=l.targetAddr,s=i);let c=l.targetAddr-i;c<0||c%4||c>1048576||(c>0&&r.push(new Uint8Array(c)),r.push(e.slice(o+32,o+32+l.payloadSize)),i=l.targetAddr+l.payloadSize)}let a=0;for(let e of r)a+=e.length;if(0==a)return null;let o=new Uint8Array(a),l=0;for(let e of r)for(let t=0;t<e.length;++t)o[l++]=e[t];return{buf:o,start:s}},t.readBytes=function(e,t,n){let s,r=new Uint8Array(n);for(let a=0;a<n;++a,++t)i(s,t)||(s=e.filter((e=>i(e,t)))[0]),s&&(r[a]=s.data[t-s.targetAddr]);return r},t.newBlockFile=r,t.finalizeFile=a,t.concatFiles=function(t){for(let e of t)a(e),e.filename=null;let n=r();n.blocks=e.U.concat(t.map((e=>e.blocks)));for(let e of t)e.blocks=[];return n},t.serializeFile=function(t){a(t);let n="";for(let i of t.blocks)n+=e.Util.uint8ArrayToString(i);return n},t.readBytesFromFile=function t(n,i,s){let r,a=i>>8;if(a==n.currPtr)r=n.currBlock;else{for(let e=0;e<n.ptrs.length;++e)if(n.ptrs[e]==a){r=n.blocks[e];break}r&&(n.currPtr=a,n.currBlock=r)}if(!r)return null;let o=new Uint8Array(s),l=Math.min(s,256-(255&i));e.U.memcpy(o,0,r,32+(255&i),l);let c=s-l;if(c>0){let s=t(n,i+l,c);e.U.memcpy(o,l,s)}return o},t.writeBytes=o,t.writeHex=function(e,t){let n="0000";for(let i=0;i<t.length;++i){let s=/:02000004(....)/.exec(t[i]);if(s&&(n=s[1]),s=/^:..(....)00(.*)[0-9A-F][0-9A-F]$/.exec(t[i]),s){let t=parseInt(n+s[1],16),i=s[2],r=[];for(let e=0;e<i.length;e+=2)r.push(parseInt(i[e]+i[e+1],16));o(e,t,r)}}}}(l=e.UF2||(e.UF2={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){let n,i;!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 s=!1,r=!1;function a(){if(void 0===i){if(e.BrowserUtils.hasWindow()){const t=/sandbox=1|#sandbox|#sandboxproject/i.test(window.location.href)||e.BrowserUtils.isIFrame(),a=/nosandbox=1/i.test(window.location.href),o=/controller=1/i.test(window.location.href)&&e.BrowserUtils.isIFrame(),l=/readonly=1/i.test(window.location.href),c=/editorlayout=(widget|sandbox|ide)/i.exec(window.location.href),u=/noproject=1/i.test(window.location.href);if(i=n.IDE,a?i=n.Widget:o?i=n.Controller:t&&(i=n.Sandbox),o&&l&&(s=!0),o&&u&&(r=!0),c)switch(c[1].toLowerCase()){case"widget":i=n.Widget;break;case"sandbox":i=n.Sandbox;break;case"ide":i=n.IDE}}else i=n.Sandbox;e.debug(`shell: layout type ${n[i]}, readonly ${l()}`)}}function o(){return a(),i==n.Sandbox}function l(){return!e.BrowserUtils.hasWindow()||o()&&!/[?&]edit=1/i.test(window.location.href)||c()&&s}function c(){return a(),i==n.Controller}t.layoutTypeClass=function(){return a(),e.shell.EditorLayoutType[i].toLowerCase()},t.isSandboxMode=o,t.isReadOnly=l,t.isNoProject=function(){return r},t.isControllerMode=c,t.isPyLangPref=function(){return"py"==e.storage.getLocal("editorlangpref")},t.getEditorLanguagePref=function(){return e.storage.getLocal("editorlangpref")},t.setEditorLanguagePref=function(t){t.match(/prj$/)&&(t=t.replace(/prj$/,"")),e.storage.setLocal("editorlangpref",t)},t.getToolboxAnimation=function(){return e.storage.getLocal("toolboxanimation")},t.setToolboxAnimation=function(){e.storage.setLocal("toolboxanimation","1")}}(e.shell||(e.shell={}))}(pxt||(pxt={})),function(e){!function(t){t.USER_VERSION="0.0.1";class n{constructor(){this.db=new e.BrowserUtils.IDBWrapper(n.databaseName,n.version,((e,t)=>{const i=t.result;e.oldVersion<1&&(i.createObjectStore(n.projectTable,{keyPath:n.projectKey}),i.createObjectStore(n.userTable,{keyPath:n.userKey}))}))}initAsync(){return this.db.openAsync()}getAllProjectsAsync(){return this.db.getAllAsync(n.projectTable).then((e=>e.map((e=>e.project)).filter((e=>!e.deleted))))}deleteProjectAsync(e){return this.getProjectAsync(e).then((e=>{e.deleted=!0,this.saveProjectAsync(e)}))}getProjectAsync(e){return this.db.getAsync(n.projectTable,e).then((e=>{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,i;!function(e){e[e.userSpaceOnUse=0]="userSpaceOnUse",e[e.objectBoundingBox=1]="objectBoundingBox"}(n=t.PatternUnits||(t.PatternUnits={})),function(e){e[e.em=0]="em",e[e.ex=1]="ex",e[e.px=2]="px",e[e.in=3]="in",e[e.cm=4]="cm",e[e.mm=5]="mm",e[e.pt=6]="pt",e[e.pc=7]="pc",e[e.percent=8]="percent"}(i=t.LengthUnit||(t.LengthUnit={}));class s{constructor(e){this.el=x(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=x("title"),this.el.firstChild?this.el.insertBefore(this.titleElement,this.el.firstChild):this.el.appendChild(this.titleElement)),this.titleElement.textContent=e}setVisible(e){return this.setAttribute("visibility",e?"visible":"hidden")}}t.BaseElement=s;class r extends s{draw(e){const t=function(e){switch(e){case"text":return new d;case"circle":return new p;case"rect":return new h;case"line":return new f;case"polygon":return new b;case"polyline":return new m;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 a;return this.el.appendChild(e.el),e}appendChild(e){this.el.appendChild(e.el)}onDown(e){return t.events.down(this.el,e),this}onUp(e){return t.events.up(this.el,e),this}onMove(e){return t.events.move(this.el,e),this}onEnter(e){return t.events.enter(this.el,e),this}onLeave(e){return t.events.leave(this.el,e),this}onClick(e){return t.events.click(this.el,e),this}}t.DrawContext=r;t.SVG=class extends r{constructor(e){super("svg"),e&&e.appendChild(this.el)}define(e){return this.defs||(this.defs=new l(this.el)),e(this.defs),this}};class a extends r{constructor(e){super("g"),e&&e.appendChild(this.el)}translate(e,t){return this.left=e,this.top=t,this.updateTransform()}scale(e){return this.scaleFactor=e,this.updateTransform()}def(){return new l(this.el)}style(){return new c(this.el)}updateTransform(){let e="";return null!=this.left&&(e+=`translate(${this.left} ${this.top})`),null!=this.scaleFactor&&(e+=` scale(${this.scaleFactor})`),this.setAttribute("transform",e),this}}t.Group=a;class o extends r{constructor(){super("pattern")}units(e){return this.setAttribute("patternUnits",e===n.objectBoundingBox?"objectBoundingBox":"userSpaceOnUse")}contentUnits(e){return this.setAttribute("patternContentUnits",e===n.objectBoundingBox?"objectBoundingBox":"userSpaceOnUse")}size(e,t){return this.setAttribute("width",e),this.setAttribute("height",t),this}}t.Pattern=o;class l extends s{constructor(e){super("defs"),e.appendChild(this.el)}create(e,t){let n;switch(e){case"path":n=new y;break;case"pattern":n=new o;break;case"radialGradient":n=new k;break;case"linearGradient":n=new w;break;case"clipPath":n=new A;break;default:n=new s(e)}return n.id(t),this.el.appendChild(n.el),n}}t.DefsElement=l;class c extends s{constructor(e){super("style"),e.appendChild(this.el)}content(e){this.el.textContent=e}}t.StyleElement=c;class u extends r{at(e,t){return this.setAttribute("x",e),this.setAttribute("y",t),this}moveTo(e,t){return this.at(e,t)}fill(e,t){return this.setAttribute("fill",e),null!=t&&this.opacity(t),this}opacity(e){return this.setAttribute("fill-opacity",e)}stroke(e,t){return this.setAttribute("stroke",e),null!=t&&this.strokeWidth(t),this}strokeWidth(e){return this.setAttribute("stroke-width",e)}strokeOpacity(e){return this.setAttribute("stroke-opacity",e)}clipPath(e){return this.setAttribute("clip-path",e)}}t.Drawable=u;class d extends u{constructor(e){super("text"),null!=e&&this.text(e)}text(e){return this.el.textContent=e,this}fontFamily(e){return this.setAttribute("font-family",e)}fontSize(e,t){return this.setAttribute("font-size",E(e,t))}offset(e,t,n){return 0!==e&&this.setAttribute("dx",E(e,n)),0!==t&&this.setAttribute("dy",E(t,n)),this}anchor(e){return this.setAttribute("text-anchor",e)}}t.Text=d;class h extends u{constructor(){super("rect")}width(e,t=i.px){return this.setAttribute("width",E(e,t))}height(e,t=i.px){return this.setAttribute("height",E(e,t))}corner(e){return this.corners(e,e)}corners(e,t){return this.setAttribute("rx",e),this.setAttribute("ry",t),this}size(e,t,n=i.px){return this.width(e,n),this.height(t,n),this}}t.Rect=h;class p extends u{constructor(){super("circle")}at(e,t){return this.setAttribute("cx",e),this.setAttribute("cy",t),this}radius(e){return this.setAttribute("r",e)}}t.Circle=p;class f extends u{constructor(){super("line")}at(e,t,n,i){return this.from(e,t),null!=n&&null!=i&&this.to(n,i),this}from(e,t){return this.setAttribute("x1",e),this.setAttribute("y1",t),this}to(e,t){return this.setAttribute("x2",e),this.setAttribute("y2",t),this}}t.Line=f;class g 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=g;class m extends g{constructor(){super("polyline")}}t.Polyline=m;class b extends g{constructor(){super("polygon")}}t.Polygon=b;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=i.px){return this.setAttribute("width",E(e,t))}height(e,t=i.px){return this.setAttribute("height",E(e,t))}size(e,t,n=i.px){return this.width(e,n),this.height(t,n),this}};class v extends s{units(e){return this.setAttribute("gradientUnits",e===n.objectBoundingBox?"objectBoundingBox":"userSpaceOnUse")}stop(e,t,n){const i=x("stop");return i.setAttribute("offset",e+"%"),null!=t&&i.setAttribute("stop-color",t),null!=n&&i.setAttribute("stop-opacity",n),this.el.appendChild(i),this}}t.Gradient=v;class w extends v{constructor(){super("linearGradient")}start(e,t){return this.setAttribute("x1",e),this.setAttribute("y1",t),this}end(e,t){return this.setAttribute("x2",e),this.setAttribute("y2",t),this}}t.LinearGradient=w;class k extends v{constructor(){super("radialGradient")}center(e,t){return this.setAttribute("cx",e),this.setAttribute("cy",t),this}focus(e,t,n){return this.setAttribute("fx",e),this.setAttribute("fy",t),this.setAttribute("fr",n),this}radius(e){return this.setAttribute("r",e)}}t.RadialGradient=k;class A extends r{constructor(){super("clipPath")}clipPathUnits(e){return e?this.setAttribute("clipPathUnits","objectBoundingBox"):this.setAttribute("clipPathUnits","userSpaceOnUse")}}function x(e){return document.createElementNS("http://www.w3.org/2000/svg",e)}t.ClipPath=A;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,i,s,r){return this.op("C",e,t,n,i,s,r)}cCurveBy(e,t,n,i,s,r){return this.op("c",e,t,n,i,s,r)}qCurveTo(e,t,n,i){return this.op("Q",e,t,n,i)}qCurveBy(e,t,n,i){return this.op("q",e,t,n,i)}sCurveTo(e,t,n,i){return this.op("S",e,t,n,i)}sCurveBy(e,t,n,i){return this.op("s",e,t,n,i)}tCurveTo(e,t){return this.op("T",e,t)}tCurveBy(e,t){return this.op("t",e,t)}arcTo(e,t,n,i,s,r,a){return this.op("A",e,t,n,i?1:0,s?1:0,r,a)}arcBy(e,t,n,i,s,r,a){return this.op("a",e,t,n,i?1:0,s?1:0,r,a)}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 E(e,t){switch(t){case i.em:return e+"em";case i.ex:return e+"ex";case i.px:return e+"px";case i.in:return e+"in";case i.cm:return e+"cm";case i.mm:return e+"mm";case i.pt:return e+"pt";case i.pc:return e+"pc";case i.percent:return e+"%";default:return e.toString()}}t.PathContext=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,i){n()?e.addEventListener("pointerdown",i):t()?(e.addEventListener("mousedown",i),e.addEventListener("touchstart",i)):e.addEventListener("mousedown",i)},e.up=function(e,i){n()?e.addEventListener("pointerup",i):(t(),e.addEventListener("mouseup",i))},e.enter=function(e,i){n()?e.addEventListener("pointerover",(e=>{i(!!(1&e.buttons))})):t()?e.addEventListener("touchstart",(e=>{i(!0)})):e.addEventListener("mouseover",(e=>{i(!!(1&e.buttons))}))},e.leave=function(e,i){n()?e.addEventListener("pointerleave",i):t()?e.addEventListener("touchend",i):e.addEventListener("mouseleave",i)},e.move=function(e,i){n()?e.addEventListener("pointermove",i):t()?e.addEventListener("touchmove",i):e.addEventListener("mousemove",i)},e.click=function(e,t){e.addEventListener("click",t)}}(e.events||(e.events={}))}(e.svgUtil||(e.svgUtil={}))}(pxt||(pxt={})),function(e){!function(e){!function(t){class n extends e.Text{at(e,t){return this.cx=e,this.cy=t,this.rePosition(),this}text(e,t=12){return super.text(e),this.fontSizePixels=t,this.setAttribute("font-size",t+"px"),this.rePosition(),this}rePosition(){null!=this.cx&&null!=this.cy&&null!=this.fontSizePixels&&(this.setAttribute("x",this.cx),this.setAttribute("y",this.cy),this.setAttribute("text-anchor","middle"),this.setAttribute("alignment-baseline","middle"))}}t.CenteredText=n}(e.helpers||(e.helpers={}))}(e.svgUtil||(e.svgUtil={}))}(pxt||(pxt={})),function(e){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=a(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),a(t)}}getSnapshot(e){return e?this.assets.filter((t=>e(t))).map(a):this.assets.map(a)}update(e,t){let n;if(this.takenNames[e]){l(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&&a(t)}getByDisplayName(e){if(this.takenNames[e])for(const t of this.assets)if(t.meta.displayName===e||u(t)===e)return a(t)}isIDTaken(e){return!!this.takenNames[e]}clone(){const e=new t;return e.assets=this.getSnapshot(),e.takenNames=Object.assign({},this.takenNames),e}serializeToJRes(e={}){for(const t of this.assets)o(t,e);return e}addListener(e,t){this.listeners.push({internalID:e,callback:t})}removeListener(e){this.listeners=this.listeners.filter((t=>t.callback!==e))}diff(e){let t={before:[],after:[]},n={};for(const i of e.assets){n[i.internalID]=!0;const e=this.lookupByInternalID(i.internalID);e&&l(i,e)||(t.before.push(i),t.after.push(e))}for(const e of this.assets.filter((e=>!n[e.internalID])))t.before.push(null),t.after.push(e);return t}applyDiff(t,n=!1){const i=n?t.after:t.before,s=n?t.before:t.after;e.Util.assert(i.length===s.length);for(let e=0;e<i.length;e++)i[e]?(this.removeByInternalID(i[e].internalID),s[e]&&this.assets.push(s[e]),this.notifyListener(i[e].internalID)):(this.assets.push(s[e]),this.notifyListener(s[e].internalID));this.takenNames={};for(const t of this.assets)e.Util.assert(!this.takenNames[t.id]),this.takenNames[t.id]=!0,this.takenNames[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 i of Object.keys(t)){const s=t[i];s.mimeType===e.TILEMAP_MIME_TYPE&&n.push(s)}return n}function i(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 s(t){return e.sprite.Bitmap.fromData(t).copy().data()}function r(t,n){const i=atob(t.data),s=e.U.fromHex(i),r=s[1]|s[2]<<8,a=s[3]|s[4]<<8,o={tileWidth:s[0],tiles:t.tileset.map((e=>n&&n(e)||{id:e}))},l=s.slice(5,5+r*a),c=new e.sprite.Tilemap(r,a,0,0,new Uint8ClampedArray(l)),u=s.slice(5+l.length),d=new e.sprite.Bitmap(r,a,0,0,new Uint8ClampedArray(u)).data();return new e.sprite.TilemapData(c,o,d)}function a(e){switch(e.meta=Object.assign({},e.meta),e.type){case"tile":case"image":return Object.assign(Object.assign({},e),{bitmap:s(e.bitmap)});case"animation":return Object.assign(Object.assign({},e),{frames:e.frames.map((e=>s(e)))});case"tilemap":return Object.assign(Object.assign({},e),{data:e.data.cloneData()})}}function o(t,n){const i=t.id.substr(t.id.lastIndexOf(".")+1);switch(t.type){case"image":n[i]=t.jresData,t.meta.displayName&&(n[i]={data:t.jresData,mimeType:e.IMAGE_MIME_TYPE,displayName:t.meta.displayName});break;case"tile":n[i]={data:t.jresData,mimeType:e.IMAGE_MIME_TYPE,tilemapTile:!0,displayName:t.meta.displayName};break;case"tilemap":const s=function(t,n,i){const s=t.tilemap.data(),r=new Uint8ClampedArray(5+s.data.length+t.layers.data.length);return r[0]=t.tileset.tileWidth,r[1]=255&s.width,r[2]=s.width>>8&255,r[3]=255&s.height,r[4]=s.height>>8&255,r.set(s.data,5),r.set(t.layers.data,5+s.data.length),{id:n,mimeType:e.TILEMAP_MIME_TYPE,data:btoa(e.sprite.uint8ArrayToHex(r)),tileset:t.tileset.tiles.map((e=>e.id)),displayName:i}}(t.data,t.id,t.meta.displayName);n[s.id]=s;break;case"animation":n[i]=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 l(t,n){if(t==n)return!0;if(t.id!==n.id||t.type!==n.type||!e.U.arrayEquals(t.meta.tags,n.meta.tags)||!e.U.arrayEquals(t.meta.blockIDs,n.meta.blockIDs)||t.meta.displayName!==n.meta.displayName)return!1;switch(t.type){case"image":case"tile":return e.sprite.bitmapEquals(t.bitmap,n.bitmap);case"animation":const i=n;return t.interval===i.interval&&e.U.arrayEquals(t.frames,i.frames,e.sprite.bitmapEquals);case"tilemap":return t.data.equals(n.data)}}function c(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,i=!1){let s;switch(t){case"image":s=e.sprite.IMAGES_NAMESPACE+".";break;case"tile":s=e.sprite.TILE_NAMESPACE+".";break;case"tilemap":s="";break;case"animation":s=e.sprite.ANIMATION_NAMESPACE+"."}if(s)if(n.startsWith(s)){const e=n.substr(s.length);if(-1===e.indexOf("."))return e}else if(!i)return null;return n}function h(t){const n=atob(t.data),i=new Uint8ClampedArray(e.U.fromHex(n)),s=p(i,0),r=p(i,2),a=p(i,4),o=p(i,6),l=Math.ceil(r*a/2);let c=8;const u=[];for(let e=0;e<o;e++){const e=i.slice(c,c+l);u.push({x0:0,y0:0,width:r,height:a,data:e}),c+=l}let d=t.id;return d.startsWith(t.namespace)||(d=t.namespace+"."+d,d=d.replace(/\.\./g,".")),{type:"animation",internalID:0,id:d,interval:s,frames:u,meta:{displayName:t.displayName}}}function p(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 i=this.generateNewID("image"),s=new e.sprite.Bitmap(t,n).data(),r={internalID:this.getNewInternalId(),id:i,type:"image",bitmap:s,meta:{},jresData:e.sprite.base64EncodeBitmap(s)};return this.state.images.add(r)}createNewAnimation(t=16,n=16){const i=this.generateNewID("animation"),s=new e.sprite.Bitmap(t,n).data(),r={internalID:this.getNewInternalId(),id:i,type:"animation",frames:[s],interval:500,meta:{}};return this.state.animations.add(r)}createNewAnimationFromData(e,t=500,n){const i=this.generateNewID("animation"),s={internalID:this.getNewInternalId(),id:i,type:"animation",frames:e,interval:t,meta:{displayName:n}};return this.state.animations.add(s)}getGalleryTiles(e){return this.extensionTileSets?this.extensionTileSets.map((t=>t.tileSets.find((t=>t.tileWidth===e)))).filter((e=>null==e?void 0:e.tiles.length)):null}getProjectImages(){return this.state.images.getSnapshot()}getProjectTiles(t,n){const i=this.state.tiles.getSnapshot((e=>e.bitmap.width===t));return 0===i.length?n?(this.createNewTile(new e.sprite.Bitmap(t,t).data()),this.getProjectTiles(t,!1)):null:{tileWidth:t,tiles:i}}createNewTile(t,n,i){this.onChange(),n&&!this.isNameTaken("tile",n)||(n=this.generateNewID("tile"));const s={internalID:this.getNewInternalId(),id:n,type:"tile",jresData:e.sprite.base64EncodeBitmap(t),bitmap:t,meta:{displayName:i},isProjectTile:!0};return this.state.tiles.add(s)}createNewProjectImage(t,n){this.onChange();const i={internalID:this.getNewInternalId(),id:this.generateNewID("image"),type:"image",jresData:e.sprite.base64EncodeBitmap(t),meta:{displayName:n},bitmap:t};return this.state.images.add(i)}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 i=Object.assign(Object.assign({},n),{data:t});return this.state.tilemaps.update(e,i),i}return null}createNewTilemap(e,t,n=16,i=16){return this.createNewTilemapFromData(this.blankTilemap(t,n,i),e)}blankTilemap(t,n=16,i=16){const s=new e.sprite.Tilemap(n,i),r=new e.sprite.Bitmap(n,i),a={tileWidth:t,tiles:[this.getTransparency(t)]};return new e.sprite.TilemapData(s,a,r.data())}resolveTile(e){return this.lookupAsset("tile",e)}resolveProjectTileByInternalID(e){return this.state.tiles.getSnapshot((t=>t.internalID===e))[0]}resolveTileByBitmap(t){const n=e.sprite.base64EncodeBitmap(t);return this.state.tiles.getSnapshot((e=>e.jresData===n))[0]}getTransparency(t){const n=e.sprite.TILE_NAMESPACE+".transparency"+t;let i=this.state.tiles.getByID(n);if(!i){const s=new e.sprite.Bitmap(t,t).data();return i={internalID:this.getNewInternalId(),id:n,type:"tile",bitmap:s,jresData:e.sprite.base64EncodeBitmap(s),meta:{},isProjectTile:!0},this.state.tiles.add(i)}return i}createNewTilemapFromData(e,t){this.onChange();const n=this.generateNewIDInternal("tilemap",t||lf("level"));return this.state.tilemaps.add({internalID:this.getNewInternalId(),id:n,type:"tilemap",meta:{displayName: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 i=t.tilemap.data(),s=new Uint8ClampedArray(5+i.data.length+t.layers.data.length);return s[0]=t.tileset.tileWidth,s[1]=255&i.width,s[2]=i.width>>8&255,s[3]=255&i.height,s[4]=i.height>>8&255,s.set(i.data,5),s.set(t.layers.data,5+i.data.length),{id:n,mimeType:e.TILEMAP_MIME_TYPE,data:btoa(e.sprite.uint8ArrayToHex(s)),tileset:t.tileset.tiles.map((e=>e.id))}}forceUpdate(){this.onChange()}isNameTaken(e,t){const n=t=>{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)}},i=d(e,t),s=i&&i!==t;return n(t)||s&&n(i)}isAssetUsed(t,n,i){var s,r,a;if(((null===(r=null===(s=t.meta)||void 0===s?void 0:s.blockIDs)||void 0===r?void 0:r.filter((e=>!i||(null==i?void 0:i.indexOf(e))<0)))||[]).length>0)return!0;if("tile"==t.type)for(const e of this.getAssets("tilemap"))if(!((null==i?void 0:i.indexOf(e.id))>=0)&&e.data.tileset.tiles.some((e=>e.id===t.id)))return!0;if(n){const s=e.Util.escapeForRegex(u(t)),r=e.Util.escapeForRegex(null===(a=t.meta)||void 0===a?void 0:a.displayName)||"";let o;switch(t.type){case"tile":o=`myTiles.${s}|assets.tile\`${s}\``,r&&(o+=`|assets.tile\`${r}\``);break;case"tilemap":o=`tilemap\`${s}\``;break;case"animation":o=`assets.animation\`${s}\``,r&&(o+=`|assets.animation\`${r}\``);break;default:o=`assets.image\`${s}\``,r&&(o+=`|assets.image\`${r}\``)}const l=new RegExp(o,"gm");let c;switch(t.type){case"tile":c=`myTiles.${s}|assets.tile("""${s}""")`,r&&(c+=`|assets.tile("""${r}""")`);break;case"tilemap":c=`assets.tilemap("""${s}""")`;break;case"animation":c=`assets.animation("""${s}""")`,r&&(c+=`|assets.animation("""${r}""")`);break;default:c=`assets.image("""${s}""")`,r&&(c+=`|assets.image("""${r}""")`)}const d=new RegExp(c,"gm");for(let e of Object.keys(n)){if((null==i?void 0:i.indexOf(e))>=0)continue;const t=n[e];if(e.match(/((?!\.g).{2}|^.{0,1})\.ts$/i)){if(t.content.match(l))return!0}else if(e.endsWith(".py")&&t.content.match(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,i;return-1!==(null===(i=null===(n=e.meta)||void 0===n?void 0:n.blockIDs)||void 0===i?void 0:i.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 i=a(e),s=t||(null===(n=i.meta)||void 0===n?void 0:n.displayName);let r;switch(e.type){case"image":r=this.createNewProjectImage(i.bitmap,s);break;case"tile":r=this.createNewTile(i.bitmap,null,s);break;case"tilemap":const[e,t]=this.createNewTilemapFromData(i.data,s);r=this.getTilemap(e);break;case"animation":r=this.createNewAnimationFromData(i.frames,i.interval,s)}return r}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:r(t,(e=>this.resolveTile(e)))});this.committedState=this.cloneState(),this.undoStack=[],this.redoStack=[]}loadTilemapJRes(t,i=!1){t=e.inflateJRes(t);const s=this.readImages(t,!0).filter((e=>"tile"===e.type));let a={};for(const e of s){if(i){const t=this.resolveTileByBitmap(e.bitmap);if(t){a[e.id]=t.id;continue}}const t=this.createNewTile(e.bitmap,e.id,e.meta.displayName);t.id!==e.id&&(a[e.id]=t.id)}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:r(e,(e=>(a[e]&&(e=a[e]),this.resolveTile(e))))})}loadAssetsJRes(t){t=e.inflateJRes(t);const n=[];for(const i of Object.keys(t)){const s=t[i];if(s.tilemapTile)this.state.tiles.add(this.generateImage(s,"tile"));else if(s.mimeType===e.IMAGE_MIME_TYPE)this.state.images.add(this.generateImage(s,"image"));else if(s.mimeType===e.ANIMATION_MIME_TYPE){const[e,t]=this.generateAnimation(s);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))))})),i=[];for(const t of n)1===t.meta.blockIDs.length?i.push(t):(t.meta.blockIDs=t.meta.blockIDs.filter((t=>-1!==e.indexOf(t))),0===t.meta.blockIDs.length&&i.push(t));for(const e of i)t.removeByID(e.id)}t(this.state.images),t(this.state.tiles),t(this.state.tilemaps),t(this.state.animations)}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({},h(e)),{internalID:this.getNewInternalId()}),!1]}inflateAnimation(t,n){return t.frames=t.frameIds.map((e=>n.find((t=>t.id===e)).bitmap)),t.flippedHorizontal&&(t.frames=t.frames.map((t=>{const n=e.sprite.Bitmap.fromData(t),i=new e.sprite.Bitmap(t.width,t.height);for(let e=0;e<i.width;e++)for(let t=0;t<i.height;t++)i.set(e,t,n.get(n.width-e-1,t));return i.data()}))),t}generateNewID(t){switch(t){case"animation":return this.generateNewIDInternal("animation",e.sprite.ANIMATION_PREFIX,e.sprite.ANIMATION_NAMESPACE);case"image":return this.generateNewIDInternal("image",e.sprite.IMAGE_PREFIX,e.sprite.IMAGES_NAMESPACE);case"tile":return this.generateNewIDInternal("tile",e.sprite.TILE_PREFIX,e.sprite.TILE_NAMESPACE);case"tilemap":return this.generateNewIDInternal("tilemap",lf("level"))}}generateNewIDInternal(e,t,n){t=t.replace(/\d+$/,"");const i=n?n+"."+t:t;let s=1;for(;this.isNameTaken(e,i+s);)++s;return i+s}onChange(){this.needsRebuild=!0,this.state.revision=this.nextID++}readImages(t,n=!1){const i=[],s=[];for(const r of Object.keys(t)){const a=t[r];if(a.tilemapTile){const e=this.generateImage(a,"tile");e.isProjectTile=n,i.push(e)}else if(a.mimeType===e.IMAGE_MIME_TYPE)i.push(this.generateImage(a,"image"));else if(a.mimeType===e.ANIMATION_MIME_TYPE){const[e,t]=this.generateAnimation(a);t?s.push(e):i.push(e)}}for(const e of s)i.push(this.inflateAnimation(e,i));return i}cleanupTemporaryAssets(){const e=this.state.images.getSnapshot((e=>{var t;return!e.meta.displayName&&!(null===(t=e.meta.blockIDs)||void 0===t?void 0:t.length)}));for(const t of e)this.state.images.removeByID(t.id)}},e.emitTilemapsFromJRes=function(t){const n=Object.keys(t);let s="";const a=[],o=[];for(const i of n){if("*"===i)continue;const n=t[i];if(n.tilemapTile&&(s+=" //% fixedInstance jres blockIdentity=images._tile\n",s+=` export const ${i} = image.ofBuffer(hex\`\`);\n`,o.push({keys:[n.displayName,d("tile",i,!0)],expression:i})),n.mimeType===e.TILEMAP_MIME_TYPE){const t=r(n);a.push({keys:[n.displayName,d("tilemap",n.id)],expression:e.sprite.encodeTilemap(t,"typescript")})}}a.length&&(s+=i("tilemap",a)),o.length&&(s+=i("tile",o));const l=lf("Auto-generated code. Do not edit.");return`// ${l}\nnamespace ${e.sprite.TILE_NAMESPACE} {\n${s}\n}\n// ${l}\n`},e.emitProjectImages=function(t){const n=Object.keys(t);let s="";const r=[],a=[];for(const i of n){if("*"===i)continue;const n=t[i];if("string"==typeof n||n.mimeType===e.IMAGE_MIME_TYPE){let t,s=[d("image",i,!0)];"string"==typeof n?t=e.sprite.bitmapToImageLiteral(e.sprite.getBitmapFromJResURL(n),"typescript"):(t=e.sprite.bitmapToImageLiteral(e.sprite.getBitmapFromJResURL(n.data),"typescript"),s.push(n.displayName)),r.push({keys:s,expression:t})}else if(n.mimeType===e.ANIMATION_MIME_TYPE){const t=h(n);a.push({keys:[n.displayName,d("animation",i,!0)],expression:`[${t.frames.map((t=>e.sprite.bitmapToImageLiteral(e.sprite.Bitmap.fromData(t),"typescript"))).join(", ")}]`})}}const o=lf("Auto-generated code. Do not edit.");return s+=i("image",r),s+=i("animation",a),`// ${o}\nnamespace ${e.sprite.IMAGES_NAMESPACE} {\n${s}\n}\n// ${o}\n`},e.cloneAsset=a,e.assetEquals=l,e.validateAssetName=function(e){return!!e&&!/[\u0000-\u001f\u0021-\u002c\u002e\u002f\u003a-\u0040\u005b-\u005e\u0060\u007b-\u007f]/.test(e)},e.getTSReferenceForAsset=function(e,t=!1){var n;let i;if(i=(null===(n=e.meta)||void 0===n?void 0:n.displayName)?e.meta.displayName:u(e),!i)return"image"===e.type||"tile"===e.type?e.id:void 0;const s=t?'("""':"`",r=t?'""")':"`";switch(e.type){case"tile":return`assets.tile${s}${i}${r}`;case"image":return`assets.image${s}${i}${r}`;case"animation":return`assets.animation${s}${i}${r}`;case"tilemap":return`tilemap${s}${i}${r}`}},e.parseAssetTSReference=c,e.lookupProjectAssetByTSReference=function(e,t){const n=c(e);if(n){const{type:e,name:i}=n;switch(e){case"tile":return t.lookupAssetByName("tile",i);case"image":return t.lookupAssetByName("image",i);case"tilemap":return t.lookupAssetByName("tilemap",i)||t.lookupAsset("tilemap",i);case"animation":return t.lookupAssetByName("animation",i)}}},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 i(e){const t=function(e,t,n){let i=0,s=0,r=0;if(0==t)i=n,s=n,r=n;else{let a=Math.floor(e/60),o=e/60-a,l=n*(1-t),c=n*(1-t*o),u=n*(1-t*(1-o));switch(a){case 1:i=c,s=n,r=l;break;case 2:i=l,s=n,r=u;break;case 3:i=l,s=c,r=n;break;case 4:i=u,s=l,r=n;break;case 5:i=n,s=l,r=c;break;case 6:case 0:i=n,s=u,r=l}}return[Math.floor(i),Math.floor(s),Math.floor(r)]}(e,.45,165.75);return`#${s(t[0])}${s(t[1])}${s(t[2])}`}function s(e){const t=e.toString(16);return 1==t.length?"0"+t:t}t.appendToolboxIconCss=function(t,i){if(!(n.indexOf(t)>-1))if(1===i.length){const s=e.Util.unicodeToChar(i);n+=`\n .blocklyTreeIcon.${t}::before {\n content: "${s}";\n }\n `}else n+=`\n .blocklyTreeIcon.${t} {\n background-image: url("${e.Util.pathJoin(e.webConfig.commitCdnUrl,encodeURI(i))}")!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:i(n)},t.hueToRgb=i,t.fadeColor=function(e,t,n){(e=e.replace(/[^0-9a-f]/gi,"")).length<6&&(e=e[0]+e[0]+e[1]+e[1]+e[2]+e[2]);let i="#";for(let s=0;s<3;s++){let r=parseInt(e.substr(2*s,2),16);r=Math.round(Math.min(Math.max(0,n?r+r*t:r-r*t),255));let a=r.toString(16);i+=("00"+a).substr(a.length)}return i}}(e.toolbox||(e.toolbox={}))}(pxt||(pxt={})),function(e){!function(t){const n=/^##[^#](.*)$([\s\S]*?)(?=^##[^#]|$(?![\r\n]))/gim,i=/^###[^#](.*)$([\s\S]*?)(?=^###[^#]|$(?![\r\n]))/gim;function s(){return/``` *(sim|block|blocks|filterblocks|spy|ghost|typescript|ts|js|javascript|template|python|jres|assetjson|customts|tutorialValidationRules|requiredTutorialBlock)\s*\n([\s\S]*?)\n```/gim}function r(t,i,s){let r=i||n,o=[];if(t.replace(r,(function(e,t,n){n=n.trim();let{header:i,hint:r,requiredBlocks:l}=function(e,t,n){let i,s,r=e=a(e);if(t){const t=/#+ ~ tutorialhint([\s\S]*)/i;r=e.replace(t,(function(e,t){return i=t,""}))}else{const t=/(^[\s\S]*?\S)\s*((```|\[?\!\[[\s\S]+?\]\(\S+?\)\]?)[\s\S]*)/im;let a=e.match(t);if(a&&a.length>2&&(r=a[1].trim(),i=a[2].trim(),n)){let e=a[2].trim();e=e.replace(/``` *(requiredTutorialBlock)\s*\n([\s\S]*?)\n```/gim,(function(e,t,n){return s=`{\n${n}\n}`,""})),i=e}}return{header:r,hint:i,requiredBlocks:s}}(n,s&&s.explicitHints,s.tutorialCodeValidation);let c={title:t.match(/^\{.*\}$/)?void 0:t.replace(/@(fullscreen|unplugged|showdialog|showhint|tutorialCompleted|resetDiff)/gi,"").trim(),contentMd:n,headerContentMd:i};return/@(fullscreen|unplugged|showdialog|showhint)/i.test(t)&&(c.showHint=!0),/@(unplugged|showdialog)/i.test(t)&&(c.showDialog=!0),/@tutorialCompleted/.test(t)&&(c.tutorialCompleted=!0),/@resetDiff/.test(t)&&(c.resetDiff=!0),r&&(c.hintContentMd=r),s.tutorialCodeValidation&&l&&(c.requiredBlockMd=l),o.push(c),""})),0!=t.indexOf("# Not found"))return o;e.debug("tutorial not found")}function a(e){if(!e)return e;return e.replace(/```(filterblocks|package|ghost|config|template|jres|assetjson|customts)\s*\n([\s\S]*?)\n```/gim,"").trim()}function o(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:s,body:l}=function(t){const n=/### @(\S+) ([ \S]+)/gi,i={},s=t.replace(n,(function(e,t,n){try{i[t]=JSON.parse(n)}catch(e){i[t]=n}return""})),r=i;void 0!==r.explicitHints&&e.appTarget.appTheme&&e.appTarget.appTheme.tutorialExplicitHints&&(r.explicitHints=!0);return{metadata:r,body:s}}(t),{steps:c,activities:u}=function(e,t){if(t&&t.activities)return function(e,t){let s=[],a=[];return e.replace(n,(function(e,n,o){let l=a.length;a.push({name:n||lf("Activity {0}",l),step:s.length});let c=r(o,i,t);return c=c.map((e=>(e.activity=l,e))),s=s.concat(c),""})),{steps:s,activities:a}}(e,t);{let n=r(e,null,t);return(!n||n.length<1)&&(n=r(e,i,t)),{steps:n,activities:null}}}(l,s),d=function(e){let t=e.match(/^#[^#](.*)$/im);return t&&t.length>1?t[1].trim():null}(l);if(!c)return;const{code:h,templateCode:p,editor:f,language:g,jres:m,assetJson:b,customTs:y,tutorialValidationRulesStr:v}=function(t){let n;const i=/``` *(sim|block|blocks|filterblocks|spy|ghost|typescript|ts|js|javascript|template|python|jres|assetjson|customts|tutorialValidationRules|requiredTutorialBlock)\s*\n([\s\S]*?)\n```/gim;let s,r,a,o,l,c,u=[];return t.replace(/((?!.)\s)+/g,"\n").replace(i,(function(t,n,i){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&&(a=n);break;case"typescript":case"ts":case"javascript":case"js":if(!d(e.JAVASCRIPT_PROJECT_NAME))return;break;case"template":r=i;break;case"jres":s=i;break;case"assetjson":o=i;break;case"customts":l=i,i="";break;case"tutorialValidationRules":c=i}return u.push("python"==n?`\n${i}\n`:`{\n${i}\n}`),""})),n=n||e.BLOCKS_PROJECT_NAME,{code:u,templateCode:r,editor:n,language:a,jres:s,assetJson:o,customTs:l,tutorialValidationRulesStr:c};function d(t){return n&&n!=t?(e.debug("tutorial ambiguous: contains snippets of different types"),!1):(n=t,!0)}}(l);let w;s.tutorialCodeValidation&&(w=e.Util.jsonTryParse(v),function(t,n){const i=Object.keys(t);for(let s=0;s<i.length;s++){const r={ruleName:i[s],enabled:t[i[s]]?"true":"false",tutorial:n};e.tickEvent("tutorial.validation.setValidationRules",r)}}(w,d)),(!0===s.diffs||!1!==s.diffs&&!0!==s.noDiffs&&(f==e.BLOCKS_PROJECT_NAME&&e.appTarget.appTheme.tutorialBlocksDiff||f!=e.BLOCKS_PROJECT_NAME&&e.appTarget.appTheme.tutorialTextDiff))&&function(e,t){let n;function i(e){const t={typescript:"diff",spy:"diffspy",blocks:"diffblocks",python:"diff"},i=/\s*(\/\/|#)\s*@highlight/gm;return e?e.replace(/```(typescript|spy|python|blocks|ghost|template)((?:.|[\r\n])+)```/,(function(e,s,r){const a=n,o=/^(template|ghost)$/.test(s),l=i.test(r);return r=r.replace(/^\n+/,"").replace(/\n+$/,""),l&&(r=r.replace(i,"")),n=r,!a||l||o?e:`\`\`\`${t[s]}\n${a}\n----------\n${r}\n\`\`\``})):e}e.forEach(((e,s)=>{if((e.resetDiff||t&&t.find((e=>e.step==s)))&&(n=void 0),e.hintContentMd){const t=i(e.hintContentMd);if(t&&t!=e.hintContentMd)return void(e.hintContentMd=t)}if(e.headerContentMd){const t=i(e.headerContentMd);if(t&&t!=e.headerContentMd)return void(e.headerContentMd=t)}}))}(c,u);const k=o(b);return c.forEach((e=>{e.contentMd=a(e.contentMd),e.headerContentMd=a(e.headerContentMd),e.hintContentMd=a(e.hintContentMd),e.requiredBlockMd=a(e.requiredBlockMd)})),{editor:f,title:d,steps:c,activities:u,code:h,templateCode:p,metadata:s,language:g,jres:m,assetFiles:k,customTs:y,tutorialValidationRules:w}},t.getMetadataRegex=s,t.highlight=function(e){let t=e.textContent;if(t=t.replace(/img\s*\(\s*"{3}[\s\da-f.#tngrpoyw]*"{3}\s*\)/g,'img(""" """)'),t=t.replace(/img\s*`[\s\da-f.#tngrpoyw]*`\s*/g,"img` `"),!/@highlight/.test(t))return void(e.textContent=t);e.textContent="";const n=t.split("\n");for(let t=0;t<n.length;++t){t>0&&t<n.length&&e.appendChild(document.createTextNode("\n"));let i=n[t];if(/@highlight/.test(i)){if(i=n[++t],void 0!==i){const t=document.createElement("span");t.className="highlight-line",t.textContent=i,e.appendChild(t)}}else e.appendChild(document.createTextNode(i))}},t.getTutorialOptions=function(t,n,i,s,r){var a;const o=e.tutorial.parseTutorial(t);if(!o)throw new Error(lf("Invalid tutorial format"));return{options:{tutorial:n,tutorialName:o.title||i,tutorialReportId:s,tutorialStep:0,tutorialReady:!0,tutorialHintCounter:0,tutorialStepInfo:o.steps,tutorialActivityInfo:o.activities,tutorialMd:t,tutorialCode:o.code,tutorialRecipe:!!r,templateCode:o.templateCode,autoexpandStep:!(null===(a=o.metadata)||void 0===a?void 0:a.autoexpandOff),metadata:o.metadata,language:o.language,jres:o.jres,assetFiles:o.assetFiles,customTs:o.customTs,tutorialValidationRules:o.tutorialValidationRules},editor:o.editor}},t.parseCachedTutorialInfo=function(t,n){let i=e.Util.jsonTryParse(t);return i?e.BrowserUtils.tutorialInfoDbAsync().then((e=>{if(n&&i[n]){const t=i[n];t.usedBlocks&&t.hash&&e.setWithHashAsync(n,t.snippetBlocks,t.hash)}else for(let t of Object.keys(i)){const n=i[t];n.usedBlocks&&n.hash&&e.setWithHashAsync(t,n.snippetBlocks,n.hash)}})).catch((e=>{})):Promise.resolve()},t.resolveLocalizedMarkdown=function(t,n,i){const s=(i||t.fileName||"README")+".md";let r;const[a,o,l]=e.Util.normalizeLanguageCode(e.Util.userLanguage());return r=a&&o&&l?n[`_locales/${a}/${s}`]||n[`_locales/${l}/${s}`]||n[`_locales/${o}/${s}`]:n[`_locales/${a}/${s}`],r=r||n[s],r},t.parseAssetJson=o}(e.tutorial||(e.tutorial={}))}(pxt||(pxt={})),function(e){!function(t){function n(t,n){const{tutorialStep:i}=t,s=t.tutorialStepInfo[i].requiredBlockMd,r=e.BrowserUtils.getTutorialCodeHash([s]);let a={};return null!=n&&(a=n[r]),a}function i(e,t,n){n.isStrict=!0;const i=Object.keys(e);let s=[],r=[];null!=t&&(s=Object.keys(t));let a=i.length>=s.length;const o=lf("These are the blocks you seem to be missing:");for(let n=0;n<s.length;n++){let i=s[n];(!e[i]||e[i]<t[i])&&(r.push(i),a=!1)}return n.ruleMessage=o,n.ruleStatus=a,n.blockIds=r,n}function s(e,t,n){const i=Object.keys(e),s=Object.keys(null!=t?t:{});let r=i.length>=s.length;for(let t=0;t<s.length;t++){if(!e[s[t]]){r=!1;break}}return n.ruleStatus=r,n}function r(e,t,n){n.isStrict=!0;Object.keys(e);let i=[],s=[];null!=t&&(i=Object.keys(t));let r=!0;const a=lf("You are required to have the following block:");for(let t=0;t<i.length;t++){let n=i[t];e[n]||(s.push(n),r=!1)}return n.ruleMessage=a,n.ruleStatus=r,n.blockIds=s,n}t.validate=async function(t,a,o){let l=function(e){let t=[];if(null!=e){const n=Object.keys(e);for(let i=0;i<n.length;i++){const s=n[i],r={ruleName:s,ruleTurnOn:e[s]};t.push(r)}}return t}(t.tutorialValidationRules);if(l.length>0&&a.length>0){const o=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}(a.map((e=>e.type))),{tutorialStepInfo:c,tutorialStep:u}=t,d=(c[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)),h=function(t,n){const{tutorialStepInfo:i,tutorialStep:s}=t,r=t.tutorialStepInfo[s].hintContentMd;let a="";null!=r&&r.replace(/((?!.)\s)+/g,"\n").replace(/``` *(block|blocks)\s*\n([\s\S]*?)\n```/gim,(function(e,t,n){return a=`{\n${n}\n}`,""}));const o=e.BrowserUtils.getTutorialCodeHash([a]);let l={};null!=n&&(l=n[o]);return l}(t,d);for(let e=0;e<l.length;e++){let a=l[e];const c=l[e].ruleName;if(l[e].ruleTurnOn)switch(c){case"exact":a=i(o,h,a);break;case"atleast":a=s(o,h,a);break;case"required":a=r(o,n(t,d),a)}}}return l}}(e.tutorial||(e.tutorial={}))}(pxt||(pxt={})),function(e){!function(t){let n;t.flattenDiagnosticMessageText=function(e,t){if("string"==typeof e)return e;{let n=e,i="",s=0;for(;n;){if(s){i+=t;for(let e=0;e<s;e++)i+=" "}i+=n.messageText,s++,n=n.next}return i}},function(e){e[e.ES3=0]="ES3",e[e.ES5=1]="ES5",e[e.ES6=2]="ES6",e[e.ES2015=2]="ES2015",e[e.Latest=2]="Latest"}(n=t.ScriptTarget||(t.ScriptTarget={})),t.isIdentifierStart=function(e,t){return e>=65&&e<=90||e>=97&&e<=122||36===e||95===e||e>127&&o(e,t)},t.isIdentifierPart=function(e,t){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||36===e||95===e||e>127&&function(e,t){return t>=n.ES5?l(e,s):l(e,a)}(e,t)},t.reservedWords=["abstract","any","as","break","case","catch","class","continue","const","constructor","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","is","let","module","namespace","new","null","package","private","protected","public","require","global","return","set","static","super","switch","symbol","this","throw","true","try","type","typeof","var","void","while","with","yield","async","await","of","Math"],t.keywordTypes=["boolean","number","string"],t.escapeIdentifier=function(n){if(!n)return"_";let i=n.replace(/\s+/g,"_").replace(/[^a-zA-Z0-9_$]/g,(t=>e.pxtc.isIdentifierPart(t.charCodeAt(0),e.pxtc.ScriptTarget.ES5)?t:""));return i&&e.pxtc.isIdentifierStart(i.charCodeAt(0),e.pxtc.ScriptTarget.ES5)&&-1===t.reservedWords.indexOf(i)||(i="_"+i),i};const i=[170,170,181,181,186,186,192,214,216,246,248,705,710,721,736,740,748,748,750,750,880,884,886,887,890,893,902,902,904,906,908,908,910,929,931,1013,1015,1153,1162,1319,1329,1366,1369,1369,1377,1415,1488,1514,1520,1522,1568,1610,1646,1647,1649,1747,1749,1749,1765,1766,1774,1775,1786,1788,1791,1791,1808,1808,1810,1839,1869,1957,1969,1969,1994,2026,2036,2037,2042,2042,2048,2069,2074,2074,2084,2084,2088,2088,2112,2136,2208,2208,2210,2220,2308,2361,2365,2365,2384,2384,2392,2401,2417,2423,2425,2431,2437,2444,2447,2448,2451,2472,2474,2480,2482,2482,2486,2489,2493,2493,2510,2510,2524,2525,2527,2529,2544,2545,2565,2570,2575,2576,2579,2600,2602,2608,2610,2611,2613,2614,2616,2617,2649,2652,2654,2654,2674,2676,2693,2701,2703,2705,2707,2728,2730,2736,2738,2739,2741,2745,2749,2749,2768,2768,2784,2785,2821,2828,2831,2832,2835,2856,2858,2864,2866,2867,2869,2873,2877,2877,2908,2909,2911,2913,2929,2929,2947,2947,2949,2954,2958,2960,2962,2965,2969,2970,2972,2972,2974,2975,2979,2980,2984,2986,2990,3001,3024,3024,3077,3084,3086,3088,3090,3112,3114,3123,3125,3129,3133,3133,3160,3161,3168,3169,3205,3212,3214,3216,3218,3240,3242,3251,3253,3257,3261,3261,3294,3294,3296,3297,3313,3314,3333,3340,3342,3344,3346,3386,3389,3389,3406,3406,3424,3425,3450,3455,3461,3478,3482,3505,3507,3515,3517,3517,3520,3526,3585,3632,3634,3635,3648,3654,3713,3714,3716,3716,3719,3720,3722,3722,3725,3725,3732,3735,3737,3743,3745,3747,3749,3749,3751,3751,3754,3755,3757,3760,3762,3763,3773,3773,3776,3780,3782,3782,3804,3807,3840,3840,3904,3911,3913,3948,3976,3980,4096,4138,4159,4159,4176,4181,4186,4189,4193,4193,4197,4198,4206,4208,4213,4225,4238,4238,4256,4293,4295,4295,4301,4301,4304,4346,4348,4680,4682,4685,4688,4694,4696,4696,4698,4701,4704,4744,4746,4749,4752,4784,4786,4789,4792,4798,4800,4800,4802,4805,4808,4822,4824,4880,4882,4885,4888,4954,4992,5007,5024,5108,5121,5740,5743,5759,5761,5786,5792,5866,5870,5872,5888,5900,5902,5905,5920,5937,5952,5969,5984,5996,5998,6e3,6016,6067,6103,6103,6108,6108,6176,6263,6272,6312,6314,6314,6320,6389,6400,6428,6480,6509,6512,6516,6528,6571,6593,6599,6656,6678,6688,6740,6823,6823,6917,6963,6981,6987,7043,7072,7086,7087,7098,7141,7168,7203,7245,7247,7258,7293,7401,7404,7406,7409,7413,7414,7424,7615,7680,7957,7960,7965,7968,8005,8008,8013,8016,8023,8025,8025,8027,8027,8029,8029,8031,8061,8064,8116,8118,8124,8126,8126,8130,8132,8134,8140,8144,8147,8150,8155,8160,8172,8178,8180,8182,8188,8305,8305,8319,8319,8336,8348,8450,8450,8455,8455,8458,8467,8469,8469,8473,8477,8484,8484,8486,8486,8488,8488,8490,8493,8495,8505,8508,8511,8517,8521,8526,8526,8544,8584,11264,11310,11312,11358,11360,11492,11499,11502,11506,11507,11520,11557,11559,11559,11565,11565,11568,11623,11631,11631,11648,11670,11680,11686,11688,11694,11696,11702,11704,11710,11712,11718,11720,11726,11728,11734,11736,11742,11823,11823,12293,12295,12321,12329,12337,12341,12344,12348,12353,12438,12445,12447,12449,12538,12540,12543,12549,12589,12593,12686,12704,12730,12784,12799,13312,19893,19968,40908,40960,42124,42192,42237,42240,42508,42512,42527,42538,42539,42560,42606,42623,42647,42656,42735,42775,42783,42786,42888,42891,42894,42896,42899,42912,42922,43e3,43009,43011,43013,43015,43018,43020,43042,43072,43123,43138,43187,43250,43255,43259,43259,43274,43301,43312,43334,43360,43388,43396,43442,43471,43471,43520,43560,43584,43586,43588,43595,43616,43638,43642,43642,43648,43695,43697,43697,43701,43702,43705,43709,43712,43712,43714,43714,43739,43741,43744,43754,43762,43764,43777,43782,43785,43790,43793,43798,43808,43814,43816,43822,43968,44002,44032,55203,55216,55238,55243,55291,63744,64109,64112,64217,64256,64262,64275,64279,64285,64285,64287,64296,64298,64310,64312,64316,64318,64318,64320,64321,64323,64324,64326,64433,64467,64829,64848,64911,64914,64967,65008,65019,65136,65140,65142,65276,65313,65338,65345,65370,65382,65470,65474,65479,65482,65487,65490,65495,65498,65500],s=[170,170,181,181,186,186,192,214,216,246,248,705,710,721,736,740,748,748,750,750,768,884,886,887,890,893,902,902,904,906,908,908,910,929,931,1013,1015,1153,1155,1159,1162,1319,1329,1366,1369,1369,1377,1415,1425,1469,1471,1471,1473,1474,1476,1477,1479,1479,1488,1514,1520,1522,1552,1562,1568,1641,1646,1747,1749,1756,1759,1768,1770,1788,1791,1791,1808,1866,1869,1969,1984,2037,2042,2042,2048,2093,2112,2139,2208,2208,2210,2220,2276,2302,2304,2403,2406,2415,2417,2423,2425,2431,2433,2435,2437,2444,2447,2448,2451,2472,2474,2480,2482,2482,2486,2489,2492,2500,2503,2504,2507,2510,2519,2519,2524,2525,2527,2531,2534,2545,2561,2563,2565,2570,2575,2576,2579,2600,2602,2608,2610,2611,2613,2614,2616,2617,2620,2620,2622,2626,2631,2632,2635,2637,2641,2641,2649,2652,2654,2654,2662,2677,2689,2691,2693,2701,2703,2705,2707,2728,2730,2736,2738,2739,2741,2745,2748,2757,2759,2761,2763,2765,2768,2768,2784,2787,2790,2799,2817,2819,2821,2828,2831,2832,2835,2856,2858,2864,2866,2867,2869,2873,2876,2884,2887,2888,2891,2893,2902,2903,2908,2909,2911,2915,2918,2927,2929,2929,2946,2947,2949,2954,2958,2960,2962,2965,2969,2970,2972,2972,2974,2975,2979,2980,2984,2986,2990,3001,3006,3010,3014,3016,3018,3021,3024,3024,3031,3031,3046,3055,3073,3075,3077,3084,3086,3088,3090,3112,3114,3123,3125,3129,3133,3140,3142,3144,3146,3149,3157,3158,3160,3161,3168,3171,3174,3183,3202,3203,3205,3212,3214,3216,3218,3240,3242,3251,3253,3257,3260,3268,3270,3272,3274,3277,3285,3286,3294,3294,3296,3299,3302,3311,3313,3314,3330,3331,3333,3340,3342,3344,3346,3386,3389,3396,3398,3400,3402,3406,3415,3415,3424,3427,3430,3439,3450,3455,3458,3459,3461,3478,3482,3505,3507,3515,3517,3517,3520,3526,3530,3530,3535,3540,3542,3542,3544,3551,3570,3571,3585,3642,3648,3662,3664,3673,3713,3714,3716,3716,3719,3720,3722,3722,3725,3725,3732,3735,3737,3743,3745,3747,3749,3749,3751,3751,3754,3755,3757,3769,3771,3773,3776,3780,3782,3782,3784,3789,3792,3801,3804,3807,3840,3840,3864,3865,3872,3881,3893,3893,3895,3895,3897,3897,3902,3911,3913,3948,3953,3972,3974,3991,3993,4028,4038,4038,4096,4169,4176,4253,4256,4293,4295,4295,4301,4301,4304,4346,4348,4680,4682,4685,4688,4694,4696,4696,4698,4701,4704,4744,4746,4749,4752,4784,4786,4789,4792,4798,4800,4800,4802,4805,4808,4822,4824,4880,4882,4885,4888,4954,4957,4959,4992,5007,5024,5108,5121,5740,5743,5759,5761,5786,5792,5866,5870,5872,5888,5900,5902,5908,5920,5940,5952,5971,5984,5996,5998,6e3,6002,6003,6016,6099,6103,6103,6108,6109,6112,6121,6155,6157,6160,6169,6176,6263,6272,6314,6320,6389,6400,6428,6432,6443,6448,6459,6470,6509,6512,6516,6528,6571,6576,6601,6608,6617,6656,6683,6688,6750,6752,6780,6783,6793,6800,6809,6823,6823,6912,6987,6992,7001,7019,7027,7040,7155,7168,7223,7232,7241,7245,7293,7376,7378,7380,7414,7424,7654,7676,7957,7960,7965,7968,8005,8008,8013,8016,8023,8025,8025,8027,8027,8029,8029,8031,8061,8064,8116,8118,8124,8126,8126,8130,8132,8134,8140,8144,8147,8150,8155,8160,8172,8178,8180,8182,8188,8204,8205,8255,8256,8276,8276,8305,8305,8319,8319,8336,8348,8400,8412,8417,8417,8421,8432,8450,8450,8455,8455,8458,8467,8469,8469,8473,8477,8484,8484,8486,8486,8488,8488,8490,8493,8495,8505,8508,8511,8517,8521,8526,8526,8544,8584,11264,11310,11312,11358,11360,11492,11499,11507,11520,11557,11559,11559,11565,11565,11568,11623,11631,11631,11647,11670,11680,11686,11688,11694,11696,11702,11704,11710,11712,11718,11720,11726,11728,11734,11736,11742,11744,11775,11823,11823,12293,12295,12321,12335,12337,12341,12344,12348,12353,12438,12441,12442,12445,12447,12449,12538,12540,12543,12549,12589,12593,12686,12704,12730,12784,12799,13312,19893,19968,40908,40960,42124,42192,42237,42240,42508,42512,42539,42560,42607,42612,42621,42623,42647,42655,42737,42775,42783,42786,42888,42891,42894,42896,42899,42912,42922,43e3,43047,43072,43123,43136,43204,43216,43225,43232,43255,43259,43259,43264,43309,43312,43347,43360,43388,43392,43456,43471,43481,43520,43574,43584,43597,43600,43609,43616,43638,43642,43643,43648,43714,43739,43741,43744,43759,43762,43766,43777,43782,43785,43790,43793,43798,43808,43814,43816,43822,43968,44010,44012,44013,44016,44025,44032,55203,55216,55238,55243,55291,63744,64109,64112,64217,64256,64262,64275,64279,64285,64296,64298,64310,64312,64316,64318,64318,64320,64321,64323,64324,64326,64433,64467,64829,64848,64911,64914,64967,65008,65019,65024,65039,65056,65062,65075,65076,65101,65103,65136,65140,65142,65276,65296,65305,65313,65338,65343,65343,65345,65370,65382,65470,65474,65479,65482,65487,65490,65495,65498,65500],r=[170,170,181,181,186,186,192,214,216,246,248,543,546,563,592,685,688,696,699,705,720,721,736,740,750,750,890,890,902,902,904,906,908,908,910,929,931,974,976,983,986,1011,1024,1153,1164,1220,1223,1224,1227,1228,1232,1269,1272,1273,1329,1366,1369,1369,1377,1415,1488,1514,1520,1522,1569,1594,1600,1610,1649,1747,1749,1749,1765,1766,1786,1788,1808,1808,1810,1836,1920,1957,2309,2361,2365,2365,2384,2384,2392,2401,2437,2444,2447,2448,2451,2472,2474,2480,2482,2482,2486,2489,2524,2525,2527,2529,2544,2545,2565,2570,2575,2576,2579,2600,2602,2608,2610,2611,2613,2614,2616,2617,2649,2652,2654,2654,2674,2676,2693,2699,2701,2701,2703,2705,2707,2728,2730,2736,2738,2739,2741,2745,2749,2749,2768,2768,2784,2784,2821,2828,2831,2832,2835,2856,2858,2864,2866,2867,2870,2873,2877,2877,2908,2909,2911,2913,2949,2954,2958,2960,2962,2965,2969,2970,2972,2972,2974,2975,2979,2980,2984,2986,2990,2997,2999,3001,3077,3084,3086,3088,3090,3112,3114,3123,3125,3129,3168,3169,3205,3212,3214,3216,3218,3240,3242,3251,3253,3257,3294,3294,3296,3297,3333,3340,3342,3344,3346,3368,3370,3385,3424,3425,3461,3478,3482,3505,3507,3515,3517,3517,3520,3526,3585,3632,3634,3635,3648,3654,3713,3714,3716,3716,3719,3720,3722,3722,3725,3725,3732,3735,3737,3743,3745,3747,3749,3749,3751,3751,3754,3755,3757,3760,3762,3763,3773,3773,3776,3780,3782,3782,3804,3805,3840,3840,3904,3911,3913,3946,3976,3979,4096,4129,4131,4135,4137,4138,4176,4181,4256,4293,4304,4342,4352,4441,4447,4514,4520,4601,4608,4614,4616,4678,4680,4680,4682,4685,4688,4694,4696,4696,4698,4701,4704,4742,4744,4744,4746,4749,4752,4782,4784,4784,4786,4789,4792,4798,4800,4800,4802,4805,4808,4814,4816,4822,4824,4846,4848,4878,4880,4880,4882,4885,4888,4894,4896,4934,4936,4954,5024,5108,5121,5740,5743,5750,5761,5786,5792,5866,6016,6067,6176,6263,6272,6312,7680,7835,7840,7929,7936,7957,7960,7965,7968,8005,8008,8013,8016,8023,8025,8025,8027,8027,8029,8029,8031,8061,8064,8116,8118,8124,8126,8126,8130,8132,8134,8140,8144,8147,8150,8155,8160,8172,8178,8180,8182,8188,8319,8319,8450,8450,8455,8455,8458,8467,8469,8469,8473,8477,8484,8484,8486,8486,8488,8488,8490,8493,8495,8497,8499,8505,8544,8579,12293,12295,12321,12329,12337,12341,12344,12346,12353,12436,12445,12446,12449,12538,12540,12542,12549,12588,12593,12686,12704,12727,13312,19893,19968,40869,40960,42124,44032,55203,63744,64045,64256,64262,64275,64279,64285,64285,64287,64296,64298,64310,64312,64316,64318,64318,64320,64321,64323,64324,64326,64433,64467,64829,64848,64911,64914,64967,65008,65019,65136,65138,65140,65140,65142,65276,65313,65338,65345,65370,65382,65470,65474,65479,65482,65487,65490,65495,65498,65500],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,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 o(e,t){return t>=n.ES5?l(e,i):l(e,r)}function l(e,t){if(e<t[0])return!1;let n,i=0,s=t.length;for(;i+1<s;){if(n=i+(s-i)/2,n-=n%2,t[n]<=e&&e<=t[n+1])return!0;e<t[n]?s=n:i=n+2}return!1}let c;t.isUnicodeIdentifierStart=o,function(e){e[e.Warning=0]="Warning",e[e.Error=1]="Error",e[e.Message=2]="Message"}(c=t.DiagnosticCategory||(t.DiagnosticCategory={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){function n(){return!!navigator&&!!navigator.bluetooth&&"TextDecoder"in window&&e.appTarget.appTheme.bluetoothUartConsole&&e.appTarget.appTheme.bluetoothUartFilters&&e.appTarget.appTheme.bluetoothUartFilters.length>0}function i(){return!!navigator&&!!navigator.bluetooth&&!!e.appTarget.appTheme.bluetoothPartialFlashing}t.isAvailable=function(){return n()||i()},t.hasConsole=n,t.hasPartialFlash=i,t.isValidUUID=function(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(e)};class s{constructor(e,t){this.connectionTimeout=2e4,this.connectPromise=void 0,this.id=e,this.aliveToken=t}debug(t){e.debug(`${this.id}: ${t}`)}alivePromise(e){return new Promise(((t,n)=>{this.aliveToken.isCancelled()&&n(new Error),e.then((e=>t(e)),(e=>n(e)))}))}cancelConnect(){this.connectPromise=void 0}createConnectPromise(){return Promise.resolve()}connectAsync(){return this.connectPromise||(this.connectPromise=this.alivePromise(this.createConnectPromise())),e.Util.promiseTimeout(this.connectionTimeout,this.connectPromise,"connection timeout").then((()=>this.aliveToken.throwIfCancelled())).catch((e=>{throw this.connectPromise=void 0,e}))}disconnect(){this.cancelConnect()}kill(){this.disconnect(),this.aliveToken.cancel()}}t.BLERemote=s;class r extends s{constructor(e,t,n){super(e,t.aliveToken),this.device=t,this.autoReconnect=n,this.autoReconnectDelay=1e3,this.disconnectOnAutoReconnect=!1,this.reconnectPromise=void 0,this.failedConnectionServicesVersion=-1,this.handleDisconnected=this.handleDisconnected.bind(this),this.device.device.addEventListener("gattserverdisconnected",this.handleDisconnected)}handleDisconnected(t){this.aliveToken.isCancelled()||(this.disconnect(),this.autoReconnect&&!this.reconnectPromise&&(this.reconnectPromise=e.U.delay(this.autoReconnectDelay).then((()=>this.exponentialBackoffConnectAsync(8,500))).finally((()=>this.reconnectPromise=void 0))))}exponentialBackoffConnectAsync(t,n){return this.debug("retry connect"),this.aliveToken.throwIfCancelled(),this.connectAsync().then((()=>{this.aliveToken.throwIfCancelled(),this.debug("reconnect success"),this.reconnectPromise=void 0})).catch((i=>(this.debug(`reconnect error ${i.message}`),this.aliveToken.throwIfCancelled(),this.device.isPaired?this.autoReconnect?0==t?(this.debug("give up, max tries"),void(this.reconnectPromise=void 0)):this.failedConnectionServicesVersion==this.device.servicesVersion?(this.debug("services haven't changed, giving up"),void(this.reconnectPromise=void 0)):(this.debug(`retry connect ${n}ms... (${t} tries left)`),this.device.connected&&(this.failedConnectionServicesVersion=this.device.servicesVersion),this.disconnectOnAutoReconnect&&this.device.disconnect(),e.U.delay(n).then((()=>this.exponentialBackoffConnectAsync(--t,1.8*n)))):(this.debug("autoreconnect disabled"),void(this.reconnectPromise=void 0)):(this.debug("give up, device unpaired"),void(this.reconnectPromise=void 0)))))}}t.BLEService=r;class a extends r{constructor(e,t,n,i){super(e,t,!0),this.device=t,this.serviceUUID=n,this.txCharacteristicUUID=i,this.handleValueChanged=this.handleValueChanged.bind(this)}createConnectPromise(){return this.debug("connecting"),this.device.connectAsync().then((()=>this.alivePromise(this.device.gatt.getPrimaryService(this.serviceUUID)))).then((e=>(this.debug("service connected"),this.service=e,this.alivePromise(this.service.getCharacteristic(this.txCharacteristicUUID))))).then((e=>(this.debug("tx characteristic connected"),this.txCharacteristic=e,this.txCharacteristic.addEventListener("characteristicvaluechanged",this.handleValueChanged),this.txCharacteristic.startNotifications()))).then((()=>{e.tickEvent("webble.connected",{id:this.id})}))}handlePacket(e){}handleValueChanged(e){const t=e.target.value;this.handlePacket(t)}disconnect(){if(super.disconnect(),this.txCharacteristic&&this.device&&this.device.connected)try{this.txCharacteristic.stopNotifications(),this.txCharacteristic.removeEventListener("characteristicvaluechanged",this.handleValueChanged)}catch(t){e.log(`${this.id}: error ${t.message}`)}this.service=void 0,this.txCharacteristic=void 0}}t.BLETXService=a;class o extends a{constructor(e){super("hf2",e,o.SERVICE_UUID,o.CHARACTERISTIC_TX_UUID),this.device=e}handlePacket(e){const t=e.getUint8(0);switch(192&t){case o.BLEHF2_FLAG_SERIAL_OUT:case o.BLEHF2_FLAG_SERIAL_ERR:const n=Math.min(e.byteLength-1,-193&t);let i="";for(let t=0;t<n;++t)i+=String.fromCharCode(e.getUint8(t+1));i&&window.postMessage({type:"serial",id:this.device.name||"hf2",data:i},"*")}}}o.SERVICE_UUID="b112f5e6-2679-30da-a26e-0273b6043849",o.CHARACTERISTIC_TX_UUID="b112f5e6-2679-30da-a26e-0273b604384a",o.BLEHF2_FLAG_SERIAL_OUT=128,o.BLEHF2_FLAG_SERIAL_ERR=192,t.HF2Service=o;class l extends a{constructor(e){super("uart",e,l.SERVICE_UUID,l.CHARACTERISTIC_TX_UUID),this.device=e}handlePacket(e){const t=(new window.TextDecoder).decode(e);t&&window.postMessage({type:"serial",id:this.device.name||"uart",data:t},"*")}}let c;l.SERVICE_UUID="6e400001-b5a3-f393-e0a9-e50e24dcca9e",l.CHARACTERISTIC_TX_UUID="6e400002-b5a3-f393-e0a9-e50e24dcca9e",t.UARTService=l,function(e){e[e.Idle=1]="Idle",e[e.StatusRequested=2]="StatusRequested",e[e.PairingModeRequested=4]="PairingModeRequested",e[e.RegionDALRequested=8]="RegionDALRequested",e[e.RegionMakeCodeRequested=16]="RegionMakeCodeRequested",e[e.Flash=32]="Flash",e[e.EndOfTransmision=64]="EndOfTransmision",e[e.USBFlashRequired=128]="USBFlashRequired"}(c||(c={}));class u extends r{constructor(e){super("partial flashing",e,!1),this.device=e,this.state=c.Idle,this.disconnectOnAutoReconnect=!0,this.handleCharacteristic=this.handleCharacteristic.bind(this)}clearFlashData(){this.version=0,this.mode=0,this.regions=[],this.chunkDelay=u.CHUNK_MIN_DELAY,this.hex=void 0,this.bin=void 0,this.magicOffset=void 0,this.dalHash=void 0,this.makeCodeHash=void 0,this.flashReject=void 0,this.flashResolve=void 0,this.flashOffset=void 0}createConnectPromise(){return this.debug("connecting to partial flash service"),this.device.connectAsync().then((()=>this.alivePromise(this.device.gatt.getPrimaryService(u.SERVICE_UUID)))).then((e=>(this.debug("connecting to characteristic"),this.alivePromise(e.getCharacteristic(u.CHARACTERISTIC_UUID))))).then((e=>(this.debug("starting notifications"),this.pfCharacteristic=e,this.pfCharacteristic.startNotifications(),this.pfCharacteristic.addEventListener("characteristicvaluechanged",this.handleCharacteristic),this.state==c.PairingModeRequested?(this.debug("checking pairing mode"),this.autoReconnect=!1,this.pfCharacteristic.writeValue(new Uint8Array([u.STATUS]))):Promise.resolve())))}disconnect(){if(super.disconnect(),this.flashPacketToken&&this.flashPacketToken.cancel(),this.pfCharacteristic&&this.device.connected)try{this.pfCharacteristic.stopNotifications(),this.pfCharacteristic.removeEventListener("characteristicvaluechanged",this.handleCharacteristic)}catch(t){e.log(`ble: partial flash disconnect error ${t.message}`)}this.pfCharacteristic=void 0}findMarker(e,t){if(!this.bin)return-1;for(;e+t.length<this.bin.length;e+=16){let n=!0;for(let i=0;i<t.length;++i)if(t[i]!=this.bin[e+i]){n=!1;break}if(n)return e}return-1}flashAsync(e){return this.hex?(this.debug("flashing already in progress"),Promise.resolve()):(this.device.pauseLog(),this.createFlashPromise(e).finally((()=>this.device.resumeLogOnDisconnection())))}createFlashPromise(t){if(this.hex)return this.debug("flashing already in progress"),Promise.resolve();this.clearFlashData(),this.hex=t;const n=ts.pxtc.UF2.newBlockFile();ts.pxtc.UF2.writeHex(n,this.hex.split(/\r?\n/));const i=e.appTarget.compile.flashUsableEnd;this.bin=ts.pxtc.UF2.toBin(e.U.stringToUint8Array(ts.pxtc.UF2.serializeFile(n)),i).buf,this.debug(`bin bytes ${this.bin.length}`),this.magicOffset=this.findMarker(0,u.MAGIC_MARKER),this.debug(`magic block ${this.magicOffset.toString(16)}`),this.magicOffset<0&&(this.debug("magic block not found, not a valid HEX file"),e.U.userError(lf("Invalid file"))),this.debug("bytes to flash "+(this.bin.length-this.magicOffset));const s=this.magicOffset+u.MAGIC_MARKER.length;return this.dalHash=e.Util.toHex(this.bin.slice(s,s+8)),this.makeCodeHash=e.Util.toHex(this.bin.slice(s+8,s+16)),this.debug(`DAL hash ${this.dalHash}`),this.debug(`MakeCode hash ${this.makeCodeHash}`),this.connectAsync().then((()=>new Promise(((e,t)=>(this.flashResolve=e,this.flashReject=t,this.debug("check service version"),this.state=c.StatusRequested,this.pfCharacteristic.writeValue(new Uint8Array([u.STATUS]))))))).then((()=>{}),(t=>{e.log(`pf: error ${t.message}`),this.clearFlashData()}))}checkStateTransition(e,t){return!!(this.state&t)||(this.debug(`flash cmd ${e} in state ${this.state.toString(16)} `),this.flashReject(new Error),this.clearFlashData(),!1)}handleCharacteristic(t){this.aliveToken.isCancelled()&&(this.flashReject(new Error),this.clearFlashData());const n=event.target.value,i=new Uint8Array(n.buffer),s=i[0];if(this.state!=c.Idle)switch(s){case u.STATUS:if(!this.checkStateTransition(s,c.StatusRequested|c.PairingModeRequested))return;this.version=i[1],this.mode=i[2],this.debug(`flash service version ${this.version} mode ${this.mode}`),this.debug("reading DAL region"),this.state=c.RegionDALRequested,this.pfCharacteristic.writeValue(new Uint8Array([u.REGION_INFO,u.REGION_DAL])).then((()=>{}));break;case u.REGION_INFO:if(!this.checkStateTransition(s,c.RegionDALRequested|c.RegionMakeCodeRequested))return;const t=this.regions[i[1]]={start:i[2]<<24|i[3]<<16|i[4]<<8|i[5],end:i[6]<<24|i[7]<<16|i[8]<<8|i[9],hash:e.Util.toHex(i.slice(10))};if(this.debug(`read region ${i[1]} start ${t.start.toString(16)} end ${t.end.toString(16)} hash ${t.hash}`),i[1]==u.REGION_DAL){if(t.hash!=this.dalHash)return e.tickEvent("webble.flash.DALrequired"),this.debug("DAL hash does not match, partial flashing not possible"),this.state=c.USBFlashRequired,this.flashReject(new Error("USB flashing required")),void this.clearFlashData();this.debug("DAL hash match, reading makecode region"),this.state=c.RegionMakeCodeRequested,this.pfCharacteristic.writeValue(new Uint8Array([u.REGION_INFO,u.REGION_MAKECODE])).then((()=>{}))}else if(i[1]==u.REGION_MAKECODE)if(t.start!=this.magicOffset&&(this.debug("magic offset and MakeCode region.start not matching"),e.U.userError(lf("Invalid file"))),t.hash==this.makeCodeHash)e.tickEvent("webble.flash.noop"),this.debug("MakeCode hash matches, same code!"),this.debug("restart application mode"),this.pfCharacteristic.writeValue(new Uint8Array([u.RESET,u.MODE_APPLICATION])).then((()=>{this.state=c.Idle,this.flashResolve(),this.clearFlashData()}));else{if(this.mode!=u.MODE_PAIRING)return this.debug("application mode, reset into pairing mode"),this.state=c.PairingModeRequested,this.autoReconnect=!0,void this.pfCharacteristic.writeValue(new Uint8Array([u.RESET,u.MODE_PAIRING])).then((()=>{}));this.flashOffset=t.start,this.flashPacketNumber=0,this.debug(`starting to flash from address ${this.flashOffset.toString(16)}`),this.flashNextPacket()}break;case u.FLASH_DATA:if(!this.checkStateTransition(s,c.Flash))return;switch(i[1]){case u.PACKET_OUT_OF_ORDER:this.debug("packet out of order"),this.flashPacketToken.cancel(),this.flashPacketNumber+=4,this.chunkDelay=Math.min(this.chunkDelay+10,u.CHUNK_MAX_DELAY),this.flashNextPacket();break;case u.PACKET_WRITTEN:this.chunkDelay=Math.max(this.chunkDelay-1,u.CHUNK_MIN_DELAY),this.flashOffset+=64,this.flashPacketNumber+=4,this.flashOffset>=this.bin.length?(this.debug("end transmission"),this.state=c.EndOfTransmision,this.pfCharacteristic.writeValue(new Uint8Array([u.END_OF_TRANSMISSION])).finally((()=>{this.flashResolve&&this.flashResolve(),this.clearFlashData()}))):this.flashNextPacket()}break;default:this.debug(`unknown message ${e.Util.toHex(i)}`),this.disconnect()}}flashNextPacket(){this.state=c.Flash,this.flashPacketToken=new e.Util.CancellationToken,this.flashPacketToken.startOperation();const t=this.bin.slice(this.flashOffset,this.flashOffset+64);this.debug(`flashing ${this.flashOffset.toString(16)} / ${this.bin.length.toString(16)} ${(this.flashOffset-this.magicOffset)/(this.bin.length-this.magicOffset)*100>>0}%`);let n=new Uint8Array(20);e.U.delay(this.chunkDelay).then((()=>{this.flashPacketToken.throwIfCancelled(),n[0]=u.FLASH_DATA,n[1]=this.flashOffset>>8&255,n[2]=this.flashOffset>>0&255,n[3]=this.flashPacketNumber;for(let e=0;e<16;e++)n[4+e]=t[e];return this.pfCharacteristic.writeValue(n)})).then((()=>e.U.delay(this.chunkDelay))).then((()=>{this.flashPacketToken.throwIfCancelled(),n[0]=u.FLASH_DATA,n[1]=this.flashOffset>>24&255,n[2]=this.flashOffset>>16&255,n[3]=this.flashPacketNumber+1;for(let e=0;e<16;e++)n[4+e]=t[16+e]||0;return this.pfCharacteristic.writeValue(n)})).then((()=>e.U.delay(this.chunkDelay))).then((()=>{this.flashPacketToken.throwIfCancelled(),n[0]=u.FLASH_DATA,n[1]=0,n[2]=0,n[3]=this.flashPacketNumber+2;for(let e=0;e<16;e++)n[4+e]=t[32+e]||0;return this.pfCharacteristic.writeValue(n)})).then((()=>e.U.delay(this.chunkDelay))).then((()=>{this.flashPacketToken.throwIfCancelled(),n[0]=u.FLASH_DATA,n[1]=0,n[2]=0,n[3]=this.flashPacketNumber+3;for(let e=0;e<16;e++)n[4+e]=t[48+e]||0;return this.pfCharacteristic.writeValue(n)})).then((()=>{const t=this.flashOffset,i=()=>e.U.delay(500).then((()=>{if(t!=this.flashOffset||this.flashPacketToken.isCancelled()||this.aliveToken.isCancelled()||this.state!=c.Flash)return Promise.resolve();this.debug("packet transfer deadlock, force restart"),n[0]=u.FLASH_DATA,n[1]=0,n[2]=0,n[3]=-1;for(let e=0;e<16;e++)n[4+e]=0;return this.pfCharacteristic.writeValue(n).then((()=>i()))}));i().catch((e=>{this.flashReject&&(this.flashReject(new Error("failed packet transfer")),this.clearFlashData())}))})).catch((()=>{this.flashPacketToken.resolveCancel()}))}}u.SERVICE_UUID="e97dd91d-251d-470a-a062-fa1922dfa9a8",u.CHARACTERISTIC_UUID="e97d3b10-251d-470a-a062-fa1922dfa9a8",u.REGION_INFO=0,u.FLASH_DATA=1,u.PACKET_OUT_OF_ORDER=170,u.PACKET_WRITTEN=255,u.END_OF_TRANSMISSION=2,u.STATUS=238,u.RESET=255,u.MODE_PAIRING=0,u.MODE_APPLICATION=1,u.REGION_SOFTDEVICE=0,u.REGION_DAL=1,u.REGION_MAKECODE=2,u.MAGIC_MARKER=e.Util.fromHex("708E3B92C615A841C49866C975EE5197"),u.CHUNK_MIN_DELAY=0,u.CHUNK_MAX_DELAY=75,t.PartialFlashingService=u;class d extends s{constructor(t){super("ble",new e.Util.CancellationToken),this.device=void 0,this.services=[],this.pendingResumeLogOnDisconnection=!1,this.servicesVersion=0,this.device=t,this.handleDisconnected=this.handleDisconnected.bind(this),this.handleServiceAdded=this.handleServiceAdded.bind(this),this.handleServiceChanged=this.handleServiceChanged.bind(this),this.handleServiceRemoved=this.handleServiceRemoved.bind(this),this.device.addEventListener("gattserverdisconnected",this.handleDisconnected),this.device.addEventListener("serviceadded",this.handleServiceAdded),this.device.addEventListener("servicechanged",this.handleServiceChanged),this.device.addEventListener("serviceremoved",this.handleServiceRemoved),n()&&(this.services.push(this.uartService=new l(this)),this.services.push(this.hf2Service=new o(this))),i()&&this.services.push(this.partialFlashingService=new u(this)),this.aliveToken.startOperation()}startServices(){this.services.filter((e=>e.autoReconnect)).forEach((e=>e.connectAsync().catch((()=>{}))))}pauseLog(){this.uartService&&(this.uartService.autoReconnect=!1,this.uartService.disconnect()),this.hf2Service&&(this.hf2Service.autoReconnect=!1,this.hf2Service.disconnect())}resumeLogOnDisconnection(){this.pendingResumeLogOnDisconnection=!0}resumeLog(){this.uartService&&(this.uartService.autoReconnect=!0,this.uartService.connectAsync().catch((()=>{}))),this.hf2Service&&(this.hf2Service.autoReconnect=!0,this.hf2Service.connectAsync().catch((()=>{})))}get isPaired(){return this===t.bleDevice}get name(){return this.device.name||"?"}get connected(){return this.device&&this.device.gatt&&this.device.gatt.connected}get gatt(){return this.device.gatt}createConnectPromise(){return this.debug("connecting gatt server"),this.alivePromise(this.device.gatt.connect().then((()=>this.debug("gatt server connected"))))}handleServiceAdded(e){this.debug("service added"),this.servicesVersion++}handleServiceRemoved(e){this.debug("service removed"),this.servicesVersion++}handleServiceChanged(e){this.debug("service changed"),this.servicesVersion++}handleDisconnected(t){this.debug("disconnected"),this.disconnect(),this.pendingResumeLogOnDisconnection&&(this.pendingResumeLogOnDisconnection=!1,e.U.delay(500).then((()=>this.resumeLog())))}disconnect(){if(super.disconnect(),this.services.forEach((e=>e.disconnect())),this.connected){this.debug("disconnect");try{this.device.gatt&&this.device.gatt.connected&&this.device.gatt.disconnect()}catch(e){this.debug(`gatt disconnect error ${e.message}`)}}}}function h(){if(t.bleDevice)return Promise.resolve();e.log("ble: requesting device");const s=[];return n()&&(s.push(l.SERVICE_UUID),s.push(o.SERVICE_UUID)),i()&&s.push(u.SERVICE_UUID),navigator.bluetooth.requestDevice({filters:e.appTarget.appTheme.bluetoothUartFilters,optionalServices:s}).then((n=>(e.log(`ble: received device ${n.name}`),t.bleDevice=new d(n),t.bleDevice.startServices(),t.bleDevice.connectAsync())))}t.BLEDevice=d,t.bleDevice=void 0,t.isPaired=function(){return!!t.bleDevice},t.pairAsync=function(){return t.bleDevice&&(t.bleDevice.kill(),t.bleDevice=void 0),h().catch((n=>{t.bleDevice&&t.bleDevice.aliveToken&&t.bleDevice.aliveToken.resolveCancel(),e.log(`ble: error ${n.message}`)}))},t.flashAsync=function(n,i){e.tickEvent("webble.flash");const s=n.outfiles[ts.pxtc.BINARY_HEX];return h().then((()=>t.bleDevice.partialFlashingService.flashAsync(s))).then((()=>e.tickEvent("webble.flash.success"))).catch((t=>{throw e.tickEvent("webble.fail.fail",{message:t.message}),t}))}}(e.webBluetooth||(e.webBluetooth={}))}(pxt||(pxt={})),function(e){!function(t){class n extends Error{constructor(e){super(e),this.message=e}}t.USBError=n;t.filters=[{classCode:255,subclassCode:42}];let i,s,r=!0;t.setFilters=function(e){r=!1,t.filters=e};class a{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(o).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 i=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 s=i[i.length-1];return this.log(`${i.length} matching interfaces; picking ${s?"#"+s.interfaceNumber:"n/a"}`),s||this.error("cannot find supported USB interface"),this.altIface=s.alternates[0],this.iface=s,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(s.interfaceNumber)})).then((()=>{this.log("device ready"),this.lastKnownDeviceSerialNumber=this.dev.serialNumber,this.ready=!0,r&&this.readLoop(),this.onConnectionChanged&&this.onConnectionChanged()}))}}async function o(){e.log("webusb: get devices");try{return await navigator.usb.getDevices()||[]}catch(t){return e.reportException(t),[]}}async function l(){var t,n;if(void 0!==s)return;if(e.debug("webusb: checking availability"),!(null===(n=null===(t=e.appTarget)||void 0===t?void 0:t.compile)||void 0===n?void 0:n.webUSB))return void(s=!1);if(e.BrowserUtils.isElectron()||e.BrowserUtils.isWinRT())return e.debug("webusb: off, electron or winrt"),e.tickEvent("webusb.off",{reason:"electronwinrt"}),void(s=!1);const i=navigator.usb;if(!i)return e.debug("webusb: off, not impl"),e.tickEvent("webusb.off",{reason:"notimpl"}),void(s=!1);let r=/Windows NT (\d+\.\d+)/.exec(navigator.userAgent);if(r&&parseFloat(r[1])<6.3)return e.debug("webusb: off, older windows version"),e.tickEvent("webusb.off",{reason:"oldwindows"}),void(s=!1);try{await i.getDevices()}catch(t){return e.debug("webusb: off, security exception"),e.tickEvent("webusb.off",{reason:"security"}),void(s=!1)}s=!0}function c(){return void 0===s&&(console.error("checkAvailableAsync not called"),l()),!!s}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"),i||(i=new a),i.enable(),Promise.resolve(i)},t.isEnabled=!1,t.setEnabled=function(e){c()||(e=!1),t.isEnabled=e},t.checkAvailableAsync=l,t.isAvailable=c}(e.usb||(e.usb={}))}(pxt||(pxt={})),function(e){!function(t){var n=e.Util;let i={};function s(e){let t={},i=0,s=new n.PromiseQueue,r=new Promise(((e,n)=>{t.ready=e}));s.enqueue("main",(()=>r));return{opAsync:function(n,r){return s.enqueue("main",(()=>new Promise(((s,a)=>{let o=""+i++;t[o]=e=>{e?e.errorMessage?a(new Error(e.errorMessage)):s(e):a(new Error("no response"))},e({id:o,op:n,arg:r})}))))},recvHandler:e=>{if(t.hasOwnProperty(e.id)){let n=t[e.id];delete t[e.id],n(e.result)}}}}function r(t){let n=new Worker(t),i=s((e=>n.postMessage(e)));return n.onmessage=t=>{e.perf.measureStart("webworker recvHandler"),i.recvHandler(t.data),e.perf.measureEnd("webworker recvHandler")},i}t.getWorker=function(e){let t=i[e];return t||(t=i[e]=r(e)),t},t.wrap=s,t.makeWebWorker=r,t.makeWebSocket=function(t,n=null){let i=new WebSocket(t),r=[],a=s((e=>{let t=JSON.stringify(e);r?r.push(t):i.send(t)}));return i.onmessage=e=>{let t=JSON.parse(e.data);n&&null==t.id?n(t):a.recvHandler(t)},i.onopen=t=>{e.debug("socket opened");for(let e of r)i.send(e);r=null},i.onclose=t=>{e.debug("socket closed")},i.onerror=t=>{e.debug("socket errored")},a}}(e.worker||(e.worker={}))}(pxt||(pxt={})),function(e){!function(t){function n(){t.apiKey||e.U.userError("YouTube API key missing")}function i(e){if(!e)return"";const t=e.medium||e.high||e.standard||e.default;return(null==t?void 0:t.url)||""}t.apiKey=void 0,t.playlistItemToCodeCard=function(e){return{name:e.snippet.title.replace(/[^-]*-/,"").trim(),description:(t=e.snippet.description,t.split(/\n\s+/,1)[0].trim()),youTubeId:e.snippet.resourceId.videoId,youTubePlaylistId:e.snippet.playlistId,imageUrl:i(e.snippet.thumbnails)};var t},t.playlistInfoAsync=function(i){n();const s=`https://www.googleapis.com/youtube/v3/playlists?part=snippet&id=${i}&key=${t.apiKey}`;return e.Util.httpGetJsonAsync(s).then((e=>e.items[0]))},t.listPlaylistVideosAsync=async function(i){n();let s,r=[];do{let n=`https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=${i}&key=${t.apiKey}`;s&&(n+=`&pageToken=${s}`);const a=await e.Util.httpGetJsonAsync(n);r=r.concat(a.items),s=a.nextPageToken}while(s);return e.options.debug&&e.debug(JSON.stringify(r,null,2)),r},t.watchUrl=function(e,t){let n;return e?(n=`https://www.youtube.com/watch?v=${e}`,t&&(n+=`&list=${t}`)):t&&(n=`https://www.youtube.com/playlist?list=${t}`),n}}(e.youtube||(e.youtube={}))}(pxt||(pxt={})),function(e){!function(e){!function(t){function n(e,...t){return e.replace(/{(\d+)}/g,((e,n)=>t[+n]))}t.debug=!1,t.lf=n;let i=l("opcode name doesn't match","<name>");class s{constructor(t,n,i,s,r){this.opcode=i,this.mask=s,this.is32bit=r,this.canBeShared=!1,e.assert((i&s)==i),this.ei=t,this.code=n.replace(/\s+/g," "),this.friendlyFmt=n.replace(/\$\w+/g,(e=>this.ei.encoders[e]?this.ei.encoders[e].pretty:e));let a=o(n);this.name=a[0],this.args=a.slice(1)}emit(t){let n=t.words;if(n[0]!=this.name)return i;let s=this.opcode,r=1,a=0,o=[],c=null,u=null,d=null;for(let i=0;i<this.args.length;++i){let h=this.args[i],p=n[r++];if("$"==h[0]){let i=this.ei.encoders[h],f=null;if(i.isRegister){if(f=this.ei.registerNo(p),null==f)return l("expecting register name",p);this.ei.isPush(this.opcode)?a++:this.ei.isPop(this.opcode)&&a--}else if(i.isImmediate){if(p=p.replace(/^#/,""),f=t.bin.parseOneInt(p),null==f)return l("expecting number",p);this.ei.isAddSP(this.opcode)?a=-f/this.ei.wordSize():this.ei.isSubSP(this.opcode)&&(a=f/this.ei.wordSize())}else if(i.isRegList){if("{"!=p)return l("expecting {",p);for(f=0;"}"!=n[r];){if(p=n[r++],!p)return l("expecting }",n[r-2]);let e=this.ei.registerNo(p);if(null==e)return l("expecting register name",p);if(f&1<<e)return l("duplicate register name",p);f|=1<<e,this.ei.isPush(this.opcode)?a++:this.ei.isPop(this.opcode)&&a--,","==n[r]&&r++}p=n[r++]}else if(i.isLabel){if(p=p.replace(/^#/,""),/^[+-]?\d+$/.test(p))f=parseInt(p,10),c="rel"+f;else if(/^0x[0-9a-fA-F]+$/.test(p))f=parseInt(p,16),c="abs"+f;else if(c=p,f=this.ei.getAddressFromLabel(t.bin,this,p,i.isWordAligned),null==f){if(t.bin.finalEmit)return l("unknown label",p);f=8}if(this.ei.is32bit(this)){u=f,d=p;continue}}else e.oops();if(null==f)return l("didn't understand it",p);if(o.push(f),f=i.encode(f),null==f)return l("argument out of range or mis-aligned",p);e.assert(0==(s&f)),s|=f}else if(h!=p)return l("expecting "+h,p)}return n[r]?l("trailing tokens",n[r]):this.ei.is32bit(this)?this.ei.emit32(s,u,t.bin.normalizeExternalLabel(d)):{stack:a,opcode:s,numArgs:o,labelName:t.bin.normalizeExternalLabel(c)}}toString(){return this.friendlyFmt}}t.Instruction=s;class r{constructor(e,t){this.bin=e,this.text=t}getOpExt(){return this.instruction?this.instruction.code:""}getOp(){return this.instruction?this.instruction.name:""}update(e){this.bin.peepOps++,(e=e.replace(/^\s*/,""))||this.bin.peepDel++,e&&(e+=" "),e=" "+e,this.text=e+"; WAS: "+this.text.trim(),this.instruction=null,this.numArgs=null,this.words=o(e)||[],0==this.words.length?this.type="empty":"@"==this.words[0][0]&&(this.type="directive")}}t.Line=r;class a{constructor(e){this.baseOffset=0,this.checkStack=!0,this.inlineMode=!1,this.normalizeExternalLabel=e=>e,this.currLineNo=0,this.scope="",this.scopeId=0,this.errors=[],this.labels={},this.equs={},this.stackpointers={},this.stack=0,this.commPtr=0,this.peepOps=0,this.peepDel=0,this.peepCounts={},this.stats="",this.throwOnError=!1,this.disablePeepHole=!1,this.stackAtLabel={},this.currLine=new r(this,"<start>"),this.currLine.lineNo=0,this.ei=e,this.ei.file=this}emitShort(t){e.assert(0<=t&&t<=65535),this.buf.push(t)}emitOpCode(e){this.emitShort(e)}location(){return 2*this.buf.length}pc(){return this.location()+this.baseOffset}parseOneInt(t){if(!t)return null;if(/^\d+$/.test(t))return parseInt(t,10);const i=t.indexOf("-");if(i>0)return this.parseOneInt(t.slice(0,i))-this.parseOneInt(t.slice(i+1));let s=1;if(t.indexOf("*")>=0){let e=null;for(;null!=(e=/^([^\*]*)\*(.*)$/.exec(t));){let n=this.parseOneInt(e[1]);if(null==n)return null;s*=n,t=e[2]}}if("-"==t[0]?(s*=-1,t=t.slice(1)):"+"==t[0]&&(t=t.slice(1)),/^\d+$/.test(t))return s*parseInt(t,10);if(e.U.endsWith(t,"|1"))return 1|this.parseOneInt(t.slice(0,t.length-2));if(e.U.endsWith(t,"-1"))return this.parseOneInt(t.slice(0,t.length-2))-1;if(e.U.endsWith(t,"+1"))return this.parseOneInt(t.slice(0,t.length-2))+1;let r=/(.*)>>(\d+)$/.exec(t);if(r){let e=this.parseOneInt(r[1]);return e&=~(-16777216&this.baseOffset),e>>parseInt(r[2])}let a=null;if("0"==t[0])if("x"==t[1]||"X"==t[1]){let e=/^0x([a-f0-9]+)$/i.exec(t);e&&(a=parseInt(e[1],16))}else if("b"==t[1]||"B"==t[1]){let e=/^0b([01]+)$/i.exec(t);e&&(a=parseInt(e[1],2))}if(t.indexOf("@")>=0){let i=/^(\w+)@(-?\d+)$/.exec(t);i&&(1!=s&&this.directiveError(n("multiplication not supported with saved stacks")),this.stackpointers.hasOwnProperty(i[1])?a=this.ei.wordSize()*this.ei.computeStackOffset(i[1],this.stack-this.stackpointers[i[1]]+parseInt(i[2])):this.directiveError(n("saved stack not found"))),i=/^(.*)@(hi|lo|fn)$/.exec(t),i&&this.looksLikeLabel(i[1])&&(a=this.lookupLabel(i[1],!0),null!=a&&("fn"==i[2]?a=this.ei.toFnPtr(a,this.baseOffset,i[1]):(a>>=1,0<=a&&a<=65535?"hi"==i[2]?a=a>>8&255:"lo"==i[2]?a&=255:e.oops():(this.directiveError(n("@hi/lo out of range")),a=null))))}return null==a&&this.looksLikeLabel(t)&&(a=this.lookupLabel(t,!0),null!=a&&1==this.ei.postProcessRelAddress(this,1)&&(a+=this.baseOffset)),null==a||isNaN(a)?null:a*s}looksLikeLabel(e){return!/^(r\d|pc|sp|lr)$/i.test(e)&&/^[\.a-zA-Z_][\.:\w+]*$/.test(e)}scopedName(e){return"."==e[0]&&this.scope?this.scope+"$"+e:e}lookupLabel(e,t=!1){let i=null,s=this.scopedName(e);return this.labels.hasOwnProperty(s)?(i=this.labels[s],i=this.ei.postProcessRelAddress(this,i)):this.lookupExternalLabel&&(i=this.lookupExternalLabel(e),null!=i&&(i=this.ei.postProcessAbsAddress(this,i))),null==i&&this.equs.hasOwnProperty(s)&&(i=this.equs[s]),null==i&&t&&(this.finalEmit?this.directiveError(n("unknown label: {0}",e)):i=11111),i}align(t){for(e.assert(2==t||4==t||8==t||16==t);this.location()%t!=0;)this.emitOpCode(0)}pushError(e,t=""){let i={scope:this.scope,message:n(" -> Line {2} ('{1}'), error: {0}\n{3}",e,this.currLine.text,this.currLine.lineNo,t),lineNo:this.currLine.lineNo,line:this.currLine.text,coremsg:e,hints:t};if(this.errors.push(i),this.throwOnError)throw new Error(i.message)}directiveError(e){this.pushError(e)}emitString(e,t=!1){function i(e,t){return 255&(e.charCodeAt(t)||0)}let s,r=/^\s*([\w\.]+\s*:\s*)?.\w+\s+(".*")\s*$/.exec(e);if(r&&null!=(s=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}}(r[2])))if(this.align(2),t)for(let e=0;e<s.length;e++)this.emitShort(s.charCodeAt(e));else for(let e=0;e<s.length+1;e+=2)this.emitShort(i(s,e+1)<<8|i(s,e));else this.directiveError(n("expecting string"))}parseNumber(e){let t=this.parseOneInt(e.shift());return null==t?null:t}parseNumbers(e){e=e.slice(1);let t=[];for(;;){let i=this.parseNumber(e);if(null==i){this.directiveError(n("cannot parse number at '{0}'",e[0]));break}if(t.push(i),","!=e[0]){if(null==e[0])break;this.directiveError(n("expecting number, got '{0}'",e[0]));break}if(e.shift(),null==e[0])break}return t}emitSpace(e){let t=this.parseNumbers(e);if(1==t.length&&t.push(0),2!=t.length)this.directiveError(n("expecting one or two numbers"));else if(t[0]%2!=0)this.directiveError(n("only even space supported"));else{let e=255&t[1];e|=e<<8;for(let n=0;n<t[0];n+=2)this.emitShort(e)}}emitBytes(e){let t=this.parseNumbers(e);t.length%2!=0&&(this.directiveError(".bytes needs an even number of arguments"),t.push(0));for(let e=0;e<t.length;e+=2){let i=t[e],s=t[e+1];0<=i&&s<=255&&0<=s&&i<=255?this.emitShort(255&i|(255&s)<<8):this.directiveError(n("expecting uint8"))}}emitHex(e){e.slice(1).forEach((e=>{if(","!=e)if(e.length%4!=0)this.directiveError(".hex needs an even number of bytes");else if(/^[a-f0-9]+$/i.test(e))for(let t=0;t<e.length;t+=4){let n=parseInt(e.slice(t,t+4),16);n=(255&n)<<8|n>>8&255,this.emitShort(n)}else this.directiveError(".hex needs a hex number")}))}handleDirective(e){let t,i=e.words,s=()=>{2!=i.length&&this.directiveError(n("expecting one argument"))};switch(i[0]){case".ascii":case".asciz":case".string":this.emitString(e.text);break;case".utf16":this.emitString(e.text,!0);break;case".align":if(s(),t=this.parseOneInt(i[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(s(),t=this.parseOneInt(i[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":s(),t=this.parseOneInt(i[1]),null!=t?this.align(1<<t):this.directiveError(n("expecting number"));break;case".byte":this.emitBytes(i);break;case".hex":this.emitHex(i);break;case".hword":case".short":case".2bytes":this.parseNumbers(i).forEach((e=>{-32768<=e&&e<=65535?this.emitShort(65535&e):this.directiveError(n("expecting int16"))}));break;case".word":case".4bytes":case".long":this.parseNumbers(i).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(i);break;case".set":case".equ":/^\w+$/.test(i[1])||this.directiveError(n("expecting name"));const r=this.parseNumbers(i.slice(","==i[2]||"="==i[2]?2:1));1!=r.length&&this.directiveError(n("expecting one value")),void 0!==this.equs[i[1]]&&this.equs[i[1]]!=r[0]&&this.directiveError(n("redefinition of {0}",i[1])),this.equs[i[1]]=r[0];break;case".startaddr":this.location()&&this.directiveError(n(".startaddr can be only be specified at the beginning of the file")),s(),this.baseOffset=this.parseOneInt(i[1]);break;case"@stackmark":s(),this.stackpointers[i[1]]=this.stack;break;case"@stackempty":this.checkStack&&(null==this.stackpointers[i[1]]?this.directiveError(n("no such saved stack")):this.stackpointers[i[1]]!=this.stack&&this.directiveError(n("stack mismatch")));break;case"@scope":this.scope=i[1]||"",this.currLineNo=this.scope?0:this.realCurrLineNo;break;case".syntax":case"@nostackcheck":this.checkStack=!1;break;case"@dummystack":s(),this.stack+=this.parseOneInt(i[1]);break;case".section":case".global":this.stackpointers={},this.stack=0,this.scope="$S"+this.scopeId++;break;case".comm":{i=i.filter((e=>","!=e)),i.shift();let e=this.parseOneInt(i[1]),t=0;if(t=i[2]?this.parseOneInt(i[2]):4,null==this.lookupLabel(i[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(i[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(i[0])||this.directiveError(n("unknown directive"))}}handleOneInstruction(e,t){let i=t.emit(e);return!i.error&&(this.stack+=i.stack,this.checkStack&&this.stack<0&&this.pushError(n("stack underflow")),e.location=this.location(),e.opcode=i.opcode,e.stack=i.stack,this.emitOpCode(i.opcode),null!=i.opcode2&&this.emitOpCode(i.opcode2),null!=i.opcode3&&this.emitOpCode(i.opcode3),e.instruction=t,e.numArgs=i.numArgs,!0)}handleInstruction(e){if(e.instruction&&this.handleOneInstruction(e,e.instruction))return;let t=e=>this.ei.instructions.hasOwnProperty(e)?this.ei.instructions[e]:[];if(!e.instruction){let n=t(e.words[0]);for(let t=0;t<n.length;++t)if(this.handleOneInstruction(e,n[t]))return}let i=e.words[0].toLowerCase().replace(/s$/,"").replace(/[^a-z]/g,""),s="",r=t(i).concat(t(i+"s"));r.length>0&&r.forEach((t=>{let i=t.emit(e);s+=n(" Maybe: {0} ({1} at '{2}')\n",t.toString(),i.error,i.errorAt)})),this.pushError(n("assembly error"),s)}buildLine(e,t){let n=e=>{let n=new r(this,e);return n.scope=this.scope,n.lineNo=this.currLineNo,t.push(n),n},i=n(e),s=o(i.text)||[];i.words=s;let a=s[0]||"";if(":"==a.charAt(a.length-1)){let t=/^([\.\w]+):$/.exec(s[0]);if(t){if(i.type="label",i.text=t[1]+":",i.words=[t[1]],!(s.length>1))return;s.shift(),i=n(e.replace(/^[^:]*:/,"")),i.words=s,a=s[0]||""}}let l=a.charAt(0);"."==l||"@"==l?(i.type="directive","@scope"==i.words[0]&&this.handleDirective(i)):0==i.words.length?i.type="empty":i.type="instruction"}prepLines(e){this.currLineNo=0,this.realCurrLineNo=0,this.lines=[],e.split(/\r?\n/).forEach((e=>{this.errors.length>10||(this.currLineNo++,this.realCurrLineNo++,this.buildLine(e,this.lines))}))}iterLines(){this.stack=0,this.buf=[],this.scopeId=0,this.lines.forEach((t=>{if(!(this.errors.length>10)&&(this.currLine=t,0!=t.words.length))if("label"==t.type){let i=this.scopedName(t.words[0]);if(this.prevLabel=i,this.finalEmit){null!=this.equs[i]&&this.directiveError(n(".equ redefined as label"));let t=this.labels[i];null==t&&e.oops(),0==this.errors.length&&t!=this.location()&&e.oops(`invalid location: ${this.location()} != ${t} at ${i}`),e.assert(this.errors.length>0||t==this.location()),this.reallyFinalEmit&&(this.stackAtLabel[i]=this.stack)}else this.labels.hasOwnProperty(i)?this.directiveError(n("label redefinition")):this.inlineMode&&/^_/.test(i)?this.directiveError(n("labels starting with '_' are reserved for the compiler")):this.labels[i]=this.location();t.location=this.location()}else"directive"==t.type?this.handleDirective(t):"instruction"==t.type?this.handleInstruction(t):"empty"==t.type||e.oops()}))}getSourceMap(){const e={};let t="",n=0,i=0,s=0;function r(){t&&i&&(e[t]||(e[t]=[]),e[t].push(n,i,s-i)),i=0,s=0}return this.lines.forEach(((e,a)=>{const o=/^; ([\w\/\.-]+)\(([\d]+),\d+\):/.exec(e.text);o&&(r(),t=o[1],n=parseInt(o[2])),"instruction"==e.type&&(i||(i=e.location),s=e.location)})),r(),e}getSource(i,s=1,r=0){let a=0,o=e=>{let t=this.labels[e]||a,n=t-a;return a=t,n},l=this.buf?this.location():0,c=o("_code_end"),u=o("_helpers_end"),d=o("_vtables_end"),h=o("_literals_end"),p=a,f=l+this.baseOffset&16777215;r&&f>r&&e.U.userError(n("program too big by {0} bytes!",f-r));let g=n("; total bytes: {0} ({1}% of {2}k flash with {3} free)",f,(100*f/(r=r||131072)).toFixed(1),(r/1024).toFixed(1),r-f),m=n("; generated code sizes (bytes): {0} (incl. {1} user, {2} helpers, {3} vtables, {4} lits); src size {5}\n",p,c,u,d,h,l-p)+n("; assembly: {0} lines; density: {1} bytes/stmt; ({2} stmts)\n",this.lines.length,Math.round(100*c/s)/100,s)+g+"\n"+this.stats+"\n\n",b=!1;return this.lines.forEach(((e,n)=>{if("_stored_program"==e.words[0])return m+='_stored_program: .string "..."\n',void(b=!0);if(b)return void(b=!1);let s=e.text;if(i){if("@stackempty"==e.words[0]&&this.lines[n-1].text==e.text)return;if(s=s.replace(/; WAS: .*/,""),!s.trim())return}t.debug&&("label"!=e.type&&"instruction"!=e.type||(s+=` \t; 0x${(e.location+this.baseOffset).toString(16)}`)),m+=s+"\n"})),m}peepHole(){let e=this.lines.filter((e=>"empty"!=e.type));for(let t=0;t<e.length;++t){let n=e[t];if(/^user/.test(n.scope))continue;let i=e[t+1];if(!i)continue;let s=e[t+2];"instruction"==n.type&&this.ei.peephole(n,i,s)}}clearLabels(){this.labels={},this.commPtr=0}peepPass(t){this.disablePeepHole||(this.peepOps=0,this.peepDel=0,this.peepCounts={},this.peepHole(),this.throwOnError=!0,this.finalEmit=!1,this.clearLabels(),this.iterLines(),e.assert(!this.checkStack||0==this.stack),this.finalEmit=!0,this.reallyFinalEmit=t||0==this.peepOps,this.iterLines(),this.stats+=n("; peep hole pass: {0} instructions removed and {1} updated\n",this.peepDel,this.peepOps-this.peepDel))}getLabels(){return this.userLabelsCache||(this.userLabelsCache=e.U.mapMap(this.labels,((e,t)=>t+this.baseOffset))),this.userLabelsCache}emit(t){if(e.assert(null==this.buf),this.prepLines(t),this.errors.length>0)return;if(this.clearLabels(),this.iterLines(),this.checkStack&&0!=this.stack&&this.directiveError(n("stack misaligned at the end of the file")),this.errors.length>0)return;if(this.ei.expandLdlit(this),this.clearLabels(),this.iterLines(),this.finalEmit=!0,this.reallyFinalEmit=this.disablePeepHole,this.iterLines(),this.errors.length>0)return;for(let e=0;e<5&&(pxt.debug(`Peephole OPT, pass ${e}`),this.peepPass(5==e),0!=this.peepOps);++e);pxt.debug("emit done")}}t.File=a;t.VMFile=class extends a{constructor(e){super(e)}};function o(e){let t=[],n="";e:for(let i=0;i<e.length;++i)switch(e[i]){case"[":case"]":case"!":case"{":case"}":case",":n&&(t.push(n),n=""),t.push(e[i]);break;case" ":case"\t":case"\r":case"\n":n&&(t.push(n),n="");break;case";":break e;default:n+=e[i]}return n&&(t.push(n),n=""),t[0]?t:null}function l(e,t){return{stack:null,opcode:null,error:e,errorAt:t}}function c(e){return e<0||e>65535?("0x"+e.toString(16)).toLowerCase():("0x"+("000"+e.toString(16)).slice(-4)).toLowerCase()}t.AbstractProcessor=class{constructor(){this.file=null,this.addEnc=(e,t,n)=>{let i={name:e,pretty:t,encode:n,isRegister:/^\$r\d/.test(e),isImmediate:/^\$i\d/.test(e),isRegList:/^\$rl\d/.test(e),isLabel:/^\$l[a-z]/.test(e)};return this.encoders[e]=i,i},this.inrange=(e,t,n)=>Math.floor(t)!=t||t<0||t>e?null:n,this.inminmax=(e,t,n,i)=>Math.floor(n)!=n||n<e||n>t?null:i,this.inseq=(e,t)=>{let n=e.indexOf(t);return n<0?null:n},this.inrangeSigned=(e,t,n)=>{if(Math.floor(t)!=t)return null;if(t<-(e+1))return null;if(t>e)return null;return n&(e<<1|1)},this.addInst=(e,t,n,i)=>{let r=new s(this,e,t,n,i);return this.instructions.hasOwnProperty(r.name)||(this.instructions[r.name]=[]),this.instructions[r.name].push(r),r},this.encoders={},this.instructions={}}toFnPtr(e,t,n){return e}wordSize(){return-1}computeStackOffset(e,t){return t}is32bit(e){return!1}emit32(e,t,n){return null}postProcessRelAddress(e,t){return t}postProcessAbsAddress(e,t){return t}peephole(e,t,n){}registerNo(e){return null}getAddressFromLabel(e,t,n,i=!1){return null}isPop(e){return!1}isPush(e){return!1}isAddSP(e){return!1}isSubSP(e){return!1}testAssembler(){e.assert(!1)}expandLdlit(e){}},t.emitErr=l,t.expectError=function(t,n){let i=new a(t);i.emit(n),0==i.errors.length&&e.oops("ASMTEST: expecting error for: "+n)},t.tohex=c,t.expect=function(t,n){let i=[],s=n.replace(/^([0-9a-fA-F]{4,8})\s/gm,((e,t)=>(i.push(parseInt(t.slice(0,4),16)),8==t.length&&i.push(parseInt(t.slice(4,8),16)),""))),r=new a(t);r.throwOnError=!0,r.disablePeepHole=!0,r.emit(s),r.errors.length>0&&(console.debug(r.errors[0].message),e.oops("ASMTEST: not expecting errors")),r.buf.length!=i.length&&e.oops("ASMTEST: wrong buf len");for(let t=0;t<i.length;++t)r.buf[t]!=i[t]&&e.oops("ASMTEST: wrong buf content at "+t+" , exp:"+c(i[t])+", got: "+c(r.buf[t]))}}(e.assembler||(e.assembler={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){var n=pxtc.Util;t.apiRoot=e.BrowserUtils.isLocalHost()||n.isNodeJS?"https://www.makecode.com/api/":"/api/",t.accessToken="",t.localToken="";let i=!0;function s(t){let i=new Error(n.lf("Cannot access {0} while offline",t));return i.isOffline=!0,e.U.delay(1e3).then((()=>Promise.reject(i)))}function r(n,i){return e.U.requestAsync({url:"/api/"+n,headers:{Authorization:t.localToken},method:i?"POST":"GET",data:i||void 0,allowHttpErrors:!0})}function a(){return e.webConfig&&!e.webConfig.isStatic&&!e.BrowserUtils.isLocalHost()&&!!e.webConfig.cdnUrl}function o(n){if(n=n.replace(/^\//,""),!a())return t.apiRoot+n;const i=new Date,s=i.getUTCFullYear()+("0"+(i.getUTCMonth()+1)).slice(-2)+("0"+i.getUTCDate()).slice(-2);return n.indexOf("?")<0?n+="?":n+="&",n+="cdn="+s,e.webConfig.cdnUrl+"/api/"+n}function l(e){return a()?(e.url=o(e.url),n.requestAsync(e).catch((t=>c(e,t)))):u(e)}function c(e,n){return 0==n.statusCode?(i&&(i=!1,t.onOffline()),s(e.url)):Promise.reject(n)}function u(i){var r;return i.url=(null===(r=e.webConfig)||void 0===r?void 0:r.isStatic)&&!i.forceLiveEndpoint?e.webConfig.relprefix+i.url:t.apiRoot+i.url,i.allowGzipPost=!0,t.isOnline()||e.BrowserUtils.isPxtElectron()?(i.headers||(i.headers={}),e.BrowserUtils.isLocalHost()?t.localToken&&(i.headers.Authorization=t.localToken):t.accessToken&&(i.headers["x-td-access-token"]=t.accessToken),n.requestAsync(i).catch((e=>c(i,e)))):s(i.url)}function d(){return navigator&&navigator.onLine}t.onOffline=()=>{},t.hasAccessToken=function(){return!!t.accessToken},t.localRequestAsync=r,t.useCdnApi=a,t.cdnApiUrl=o,t.apiRequestWithCdnAsync=l,t.privateRequestAsync=u,t.privateGetTextAsync=function(e,t){return u({url:e,headers:t}).then((e=>e.text))},t.privateGetAsync=function(e,t=!1){return u({url:e,forceLiveEndpoint:t}).then((e=>e.json))},t.downloadTargetConfigAsync=function(){if(!t.isOnline())return Promise.resolve(void 0);const n=e.appTarget.versions&&e.appTarget.versions.target,i=e.webConfig&&e.webConfig.isStatic?"targetconfig.json":`config/${e.appTarget.id}/targetconfig${n?`/v${n}`:""}`;return e.BrowserUtils.isLocalHost()?r(i).then((e=>e?e.json:void 0)):l({url:i}).then((e=>e.json))},t.downloadScriptFilesAsync=function(e){return u({url:e+"/text",forceLiveEndpoint:!0}).then((e=>JSON.parse(e.text)))},t.markdownAsync=async function(t,n){const i=e.BrowserUtils.isLocalHostDev()?0:36e5,s=24*i*7;n=n||e.Util.userLanguage();const o=await e.BrowserUtils.translationDbAsync(),c=await o.getAsync(n,t,""),d=async()=>{try{const i=await function(t,n,i){var s;const o=null===(s=e.webConfig)||void 0===s?void 0:s.isStatic,c=e.appTarget.versions&&e.appTarget.versions.target||"?";let d;if(o){d=t;const e=/\/?docs\//.test(d),n=/\.\w+$/.test(d);if(!e){const e="/"===d[0];d=`docs${e?"":"/"}${d}`}n||(d=`${d}.md`)}else d=`md/${e.appTarget.id}/${t.replace(/^\//,"")}?targetVersion=${encodeURIComponent(c)}`;"en"!=n&&(d+=`${o?"?":"&"}lang=${encodeURIComponent(n)}`);if(e.BrowserUtils.isLocalHost()&&!e.Util.liveLocalizationEnabled())return r(d).then((e=>404==e.statusCode?u({url:d,method:"GET"}).then((e=>({md:e.text,etag:e.headers.etag}))):{md:e.text,etag:void 0}));{const e=i&&!a()?{"If-None-Match":i}:void 0;return l({url:d,method:"GET",headers:e}).then((e=>({md:e.text,etag:e.headers.etag})))}}(t,n,null==c?void 0:c.etag);return!c||i.md&&c.md!==i.md?(await o.setAsync(n,t,"",i.etag,void 0,i.md),i.md):c.md}catch(e){return""}};if(c){const t=Date.now()-c.time,n=t>i;if(t>s)e.tickEvent("markdown.update.wait");else if(n&&(e.tickEvent("markdown.update.background"),d()),c.md)return c.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()&&(i=!0),i},t.getServiceUrl=function(){return t.apiRoot.replace(/\/api\/$/,"")},t.getUserId=function(){let e=/^0(\w+)\./.exec(t.accessToken);return e?e[1]:null},t.parseScriptId=function(t){const i=e.appTarget;if(!(t&&i.appTheme&&i.cloud&&i.cloud.sharing))return;let s=["makecode.com"];i.appTheme.embedUrl&&s.push(i.appTheme.embedUrl),i.appTheme.shareUrl&&s.push(i.appTheme.shareUrl),s=n.unique(s,(e=>e)).map((e=>n.escapeForRegex(n.stripUrlProtocol(e).replace(/\/$/,"")).toLowerCase()));const r=`^((https://)?(?:${s.join("|")})/)?(?:v[0-9]+/)?(api/oembed?url=.*%2F([^&]*)&.*?|([a-z0-9-_]+))$`,a=new RegExp(r,"i").exec(t.trim()),o=a&&(!a[1]||s.indexOf(n.escapeForRegex(a[1].replace(/https:\/\//,"").replace(/\/$/,"")).toLowerCase())>=0)&&(a[3]||a[4])?a[3]?a[3]:a[4]:null;return o&&("_"==o[0]&&13==o.length||23==o.length&&/^[0-9\-]+$/.test(o))?o:void 0}}(e.Cloud||(e.Cloud={}))}(pxt||(pxt={})),function(e){!function(e){e.f4EncodeImg=function(e,t,n,i){let s=[135,n,255&e,e>>8,255&t,t>>8,0,0].map(c).join(""),r=4,a=0,o=0,l=e=>{a|=e<<o,o==8-n?(s+=c(a),r++,a=0,o=0):o+=n};for(let s=0;s<e;++s){for(let e=0;e<t;++e)l(i(s,e));for(;0!=o;)l(0);if(n>1)for(;3&r;)l(0)}return s;function c(e){return("0"+e.toString(16)).slice(-2)}}}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){function t(e){let t="";switch(e){case 0:t="C5";break;case 1:t="B";break;case 2:t="A";break;case 3:t="G";break;case 4:t="F";break;case 5:t="E";break;case 6:t="D";break;case 7:t="C"}return t}function n(e){let t=-1;switch(e){case"C5":t=0;break;case"B":t=1;break;case"A":t=2;break;case"G":t=3;break;case"F":t=4;break;case"E":t=5;break;case"D":t=6;break;case"C":t=7}return t}e.MelodyArray=class{constructor(e){this.numCols=8,this.numRows=8,this.polyphonic=!1,e&&(this.tempo=e),this.resetMelody()}setTempo(e){this.tempo=e}getArray(){return this.melody}setArray(e){this.melody=e}getColor(e){return 0}getValue(e,t){return this.melody[e][t]}getWidth(){return this.numCols}getHeight(){return this.numRows}updateMelody(e,t){const n=!this.melody[e][t];if(n&&!this.polyphonic)for(let e=0;e<this.numRows;e++)this.melody[e][t]=!1;this.melody[e][t]=n}getStringRepresentation(){let e="",n=new Array(this.numCols),i=0;for(let e=0;e<this.numRows;e++){let s=0;n[e]=[];for(let i=0;i<this.numCols;i++)this.melody[i][e]&&(n[e].push(t(i)),s++);s>i&&(i=s)}if(0==i)return"- - - - - - - - ";for(let t=0;t<i;t++)for(let t=0;t<this.numCols;t++)n[t]&&n[t].length>0?e+=n[t].shift()+" ":e+="- ";return e}parseNotes(e){let t=(e=e.trim()).split(" ");for(let e=0;e<t.length;e++){for(let t=0;t<this.numRows;t++)this.melody[t][e]=!1;"-"!=t[e]&&(this.melody[n(t[e])][e]=!0)}}setPolyphonic(e){this.polyphonic=e}isPolyphonic(){return this.polyphonic}resetMelody(){this.melody=new Array(this.numCols);for(let e=0;e<this.numCols;e++)this.melody[e]=new Array(this.numRows).fill(!1)}},e.rowToNote=t,e.noteToRow=n,e.getColorClass=function(e){let t="melody-default";switch(e){case 0:t="melody-red";break;case 1:t="melody-orange";break;case 2:t="melody-yellow";break;case 3:t="melody-green";break;case 4:t="melody-teal";break;case 5:t="melody-blue";break;case 6:t="melody-purple";break;case 7:t="melody-violet"}return t}}(pxtmelody||(pxtmelody={})),function(e){function t(e,t,n){return function(e,t,n){if(t)for(const n of Object.keys(t))"className"===n?e.setAttribute("class",t[n]+""):e.setAttribute(n,t[n]+"");n&&e.addEventListener("click",n);return e}(document.createElement(e),t,n)}e.MelodyGallery=class{constructor(){this.value=null,this.visible=!1,this.timeouts=[],this.numSamples=e.SampleMelodies.length,this.containerDiv=document.createElement("div"),this.containerDiv.setAttribute("id","melody-editor-gallery-outer"),this.contentDiv=document.createElement("div"),this.contentDiv.setAttribute("id","melody-editor-gallery"),this.itemBackgroundColor="#DCDCDC",this.itemBorderColor="white",this.initStyles(),this.containerDiv.appendChild(this.contentDiv),this.containerDiv.style.display="none",this.contentDiv.addEventListener("animationend",(()=>{this.visible||(this.containerDiv.style.display="none")})),this.contentDiv.addEventListener("wheel",(e=>{e.stopPropagation()}),!0)}getElement(){return this.containerDiv}getValue(){return this.value}show(e){this.pending=e,this.containerDiv.style.display="block",this.buildDom(),this.visible=!0,pxt.BrowserUtils.removeClass(this.contentDiv,"hidden-above"),pxt.BrowserUtils.addClass(this.contentDiv,"shown")}hide(){this.visible=!1,pxt.BrowserUtils.removeClass(this.contentDiv,"shown"),pxt.BrowserUtils.addClass(this.contentDiv,"hidden-above"),this.value=null,this.stopMelody()}clearDomReferences(){this.contentDiv=null,this.containerDiv=null}layout(e,t,n){this.containerDiv.style.left=e+"px",this.containerDiv.style.top=t+"px",this.containerDiv.style.height=n+"px"}buildDom(){for(;this.contentDiv.firstChild;)this.contentDiv.removeChild(this.contentDiv.firstChild);const t=e.SampleMelodies;this.buttons=[];for(let e=0;e<t.length;e++)this.mkButton(t[e],e,"255px","45px")}initStyles(){const e=document.createElement("style");e.textContent="\n #melody-editor-gallery {\n margin-top: -100%;\n }\n\n #melody-editor-gallery.hidden-above {\n margin-top: -100%;\n animation: slide-up 0.2s 0s ease;\n }\n\n #melody-editor-gallery.shown {\n margin-top: 0px;\n animation: slide-down 0.2s 0s ease;\n }\n\n @keyframes slide-down {\n 0% {\n margin-top: -100%;\n }\n 100% {\n margin-top: 0px;\n }\n }\n\n @keyframes slide-up {\n 0% {\n margin-top: 0px;\n }\n 100% {\n margin-top: -100%;\n }\n }\n ",this.containerDiv.appendChild(e)}mkButton(e,n,i,s){const r=t("div",{className:"melody-gallery-button melody-editor-card",role:"menuitem",id:`:${n}`}),a=t("i",{className:"music icon melody-icon"}),o=t("div",{className:"melody-editor-text"});o.innerText=e.name;const l=this.createColorBlock(e),c=t("div",{className:"melody-editor-button left-button",role:"button",title:e.name},(()=>this.handleSelection(e)));c.appendChild(a),c.appendChild(o),c.appendChild(l),r.appendChild(c);const u=t("div",{className:"melody-editor-button right-button",role:"button",title:lf("Preview {0}",e.name)},(()=>this.togglePlay(e,n))),d=t("i",{className:"play icon"});this.buttons[n]=d,u.appendChild(d),r.appendChild(u),this.contentDiv.appendChild(r)}handleSelection(e){if(this.pending){const t=this.pending;this.pending=void 0,t(e.notes)}}playNote(e,t,n){let i=0;switch(e){case"C5":i=523;break;case"B":i=494;break;case"A":i=440;break;case"G":i=392;break;case"F":i=349;break;case"E":i=330;break;case"D":i=294;break;case"C":i=262}this.timeouts.push(setTimeout((()=>{pxt.AudioContextManager.tone(i)}),t*this.getDuration(n))),this.timeouts.push(setTimeout((()=>{pxt.AudioContextManager.stop()}),(t+1)*this.getDuration(n)))}getDuration(e){return 6e4/e}previewMelody(e){this.stopMelody();let t=e.notes.split(" ");for(let n=0;n<t.length;n++)this.playNote(t[n],n,e.tempo)}togglePlay(e,t){let n=this.buttons[t];pxt.BrowserUtils.containsClass(n,"play icon")?(this.resetPlayIcons(),pxt.BrowserUtils.removeClass(n,"play icon"),pxt.BrowserUtils.addClass(n,"stop icon"),this.previewMelody(e),this.timeouts.push(setTimeout((()=>{pxt.BrowserUtils.removeClass(n,"stop icon"),pxt.BrowserUtils.addClass(n,"play icon")}),e.notes.split(" ").length*this.getDuration(e.tempo)))):(pxt.BrowserUtils.removeClass(n,"stop icon"),pxt.BrowserUtils.addClass(n,"play icon"),this.stopMelody())}stopMelody(){for(;this.timeouts.length;)clearTimeout(this.timeouts.shift());pxt.AudioContextManager.stop()}resetPlayIcons(){for(let e=0;e<this.numSamples;e++){let t=this.buttons[e];if(pxt.BrowserUtils.containsClass(t,"stop icon")){pxt.BrowserUtils.removeClass(t,"stop icon"),pxt.BrowserUtils.addClass(t,"play icon");break}}}createColorBlock(t){let n=document.createElement("div");pxt.BrowserUtils.addClass(n,"melody-color-block");let i=t.notes.split(" ");for(let t=0;t<i.length;t++){let s=e.getColorClass(e.noteToRow(i[t])),r=document.createElement("div");0==t?pxt.BrowserUtils.addClass(r,"left-edge sliver "+s):t==i.length-1?pxt.BrowserUtils.addClass(r,"right-edge sliver "+s):pxt.BrowserUtils.addClass(r,"sliver "+s),n.appendChild(r)}return n}}}(pxtmelody||(pxtmelody={})),function(e){class t{constructor(e,t,n){this.name=e,this.notes=t,this.tempo=n}}e.MelodyInfo=t,e.SampleMelodies=[new t(lf("Scale"),"C5 B A G F E D C",120),new t(lf("Reverse"),"C D E F G A B C5",120),new t(lf("Mystery"),"E B C5 A B G A F",120),new t(lf("Gilroy"),"A F E F D G E F",120),new t(lf("Falling"),"C5 A B G A F G E",120),new t(lf("Hopeful"),"G B A G C5 B A B",120),new t(lf("Tokyo"),"B A G A G F A C5",120),new t(lf("Paris"),"G F G A - F E D",120),new t(lf("Rising"),"E D G F B A C5 B",120),new t(lf("Sitka"),"C5 G B A F A C5 B",120)]}(pxtmelody||(pxtmelody={}));
|