pxt-core 12.2.32 → 12.2.34
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/backendutils.js +1 -1
- package/built/pxt.js +1 -1
- package/built/pxtlib.js +1 -1
- package/built/target.js +1 -1
- package/built/targetlight.js +1 -1
- package/built/web/main.js +1 -1
- package/built/web/pxtapp.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/react-common-authcode.css +1 -1
- package/built/web/react-common-multiplayer.css +1 -1
- package/built/web/react-common-skillmap.css +1 -1
- package/built/web/rtlreact-common-authcode.css +1 -1
- package/built/web/rtlreact-common-multiplayer.css +1 -1
- package/built/web/rtlreact-common-skillmap.css +1 -1
- package/built/web/rtlsemantic.css +5 -5
- package/built/web/semantic.css +5 -5
- package/localtypings/pxteditor.d.ts +1 -1
- package/package.json +1 -1
package/built/web/pxtlib.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
pxt||(pxt={}),function(e){!function(t){const n={},i={};let s,r=!1;function a(e){Object.keys(e).forEach(t=>{"string"==typeof e[t]?n[t]=e[t]:i[t]=e[t]})}!function(e){e[e.Off=0]="Off",e[e.Short=1]="Short",e[e.Verbose=2]="Verbose"}(s=t.ConsoleTickOptions||(t.ConsoleTickOptions={})),t.consoleTicks=s.Off,t.addDefaultProperties=a,t.enable=function(o){if(!e.aiTrackException||!e.aiTrackEvent||r)return;r=!0,"string"==typeof o&&0!=o.length||(o="en"),a({lang:o}),e.debug("setting up app insights");const l=e.tickEvent;e.tickEvent=function(r,a,o){if(a=e.Util.cleanData(a),t.consoleTicks!=s.Off){const n=t.consoleTicks==s.Short?"":`${(new Date).toLocaleTimeString(void 0,{hour12:!1})} - Tick - `,i=`${r} ${a?JSON.stringify(a):"<no data>"} ${o?JSON.stringify(o):"<no opts>"}`;e.log(n+i)}if(l&&l(r,a,o),(null==o?void 0:o.interactiveConsent)&&e.setInteractiveConsent(!0),a){const t=Object.assign({},n),s=Object.assign({},i);Object.keys(a).forEach(e=>{"string"==typeof a[e]?t[e]=a[e]:"number"==typeof a[e]?s[e]=a[e]:t[e]=JSON.stringify(a[e]||"")}),e.aiTrackEvent(r,t,s)}else e.aiTrackEvent(r)};const c=e.reportException;e.reportException=function(t,n){n=e.Util.cleanData(n),c&&c(t,n);const i={target:e.appTarget.id,version:e.appTarget.versions.target};n&&e.Util.jsonMergeFrom(i,n),e.aiTrackException(t,"exception",i)};const u=e.reportError;e.reportError=function(t,n,i){i=e.Util.cleanData(i),u&&u(t,n,i);try{throw n}catch(s){const r={target:e.appTarget.id,version:e.appTarget.versions.target,category:t,message:n};i&&e.Util.jsonMergeFrom(r,i),e.aiTrackException(s,"error",r)}}},t.trackPerformanceReport=function(){if(e.perf.perfReportLogged)return;const t=e.perf.report();if(t){const{durations:n,milestones:i}=t;e.tickEvent("performance.milestones",i),e.tickEvent("performance.durations",n)}}}(e.analytics||(e.analytics={}))}(pxt||(pxt={})),pxt||(pxt={}),function(e){!function(e){let t,n,i,s=0,r=!1;function 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(isNaN(e)||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",a="interactive-login-until";let o,l=!1;t.DEFAULT_USER_PREFERENCES=()=>({language:e.appTarget.appTheme.defaultLocale,highContrast:!1,accessibleBlocks:!1,colorThemeIds:{},reader:"",skillmap:{mapProgress:{},completedTags:{}},email:!1}),t.client=function(){if(!l)return o};let c=0,u=0;async function d(t,i){return i?await e.storage.shared.setAsync(n,t,i):await e.storage.shared.delAsync(n,t)}async function h(t){try{return await e.storage.shared.getAsync(n,t)}catch(e){return}}async function p(){const e=await h(i);return t.cachedHasAuthToken=!!e,e}async function f(e){return t.cachedHasAuthToken=!!e,await d(i,e)}async function m(){return!!await p()}async function g(){return t.cachedHasAuthToken=!1,await d(i,void 0)}async function b(){let i;try{i=await e.storage.shared.getAsync(n,r)}catch(e){i={}}return t.cachedUserState=i,i}async function y(i){return t.cachedUserState=Object.assign({},i),await e.storage.shared.setAsync(n,r,i)}async function v(){return t.cachedUserState=void 0,await e.storage.shared.delAsync(n,r)}async function w(t){var n;const i={};return(t=t||await p())&&(i.authorization=`mkcd ${t}`),i["x-pxt-target"]=null===(n=e.appTarget)||void 0===n?void 0:n.id,i}t.cachedHasAuthToken=!1,t.getAuthTokenAsync=p,t.hasAuthTokenAsync=m,t.getUserStateAsync=b,t.getAuthHeadersAsync=w;class A{constructor(){this.initialUserPreferences_=void 0,this.initialAuthCheck_=void 0,this.patchQueue=[],o=this}async initAsync(){const e=await b();this.setUserProfileAsync(null==e?void 0:e.profile),this.setUserPreferencesAsync(null==e?void 0:e.preferences)}async loginAsync(t,i,r=void 0){if(!x()||!function(e){return T().filter(t=>t.id===e).length>0}(t))return;r=null!=r?r:k,this.clearAuthStateAsync();const o={key:(Math.PI*Math.random()).toString(36).slice(2),callbackState:r,callbackPathname:window.location.pathname,idp:t,persistent:i},l=(parseInt(await h(a))||0)>Date.now(),c=e.Util.stringifyQueryString("/api/auth/login",{response_type:"token",provider:t,persistent:i,redirect_uri:`${window.location.origin}${window.location.pathname}?authcallback=1&state=${o.key}`,prompt:l?"select_account":"silent"}),u=await this.apiAsync(c);if(u.success)o.authCodeVerifier=u.resp.authCodeVerifier,await e.storage.shared.setAsync(n,s,o),e.tickEvent("auth.login.start",{provider:t}),window.location.href=u.resp.loginUrl;else try{await this.onSignInFailed()}catch(e){}}async logoutAsync(e){if(x()){await A.staticLogoutAsync(e);try{await this.onStateCleared()}catch(e){}try{await this.onSignedOut()}catch(e){}}}static async staticLogoutAsync(t){if(!x())return;e.tickEvent("auth.logout"),await d(a,(Date.now()+6e4).toString()),t=t?t.startsWith("#")?t:`#${t}`:"";const n=`${window.location.origin}${window.location.pathname}${window.location.search}${t}`;let i="";try{const t=e.Util.stringifyQueryString("/api/auth/logout",{redirect_uri:n,authcallback:"1"}),s=await A.staticApiAsync(t);s.success&&(i=s.resp.logoutUrl)}catch(e){}await g(),await v(),e.BrowserUtils.hasWindow()&&(i?window.location.href=i:(window.location.href=n,location.reload()))}async deleteProfileAsync(){var t;if(!await this.loggedInAsync())return;const n=await b(),i=null===(t=null==n?void 0:n.profile)||void 0===t?void 0:t.id,s=await this.apiAsync("/api/user",null,"DELETE");if(s.err)try{await this.onApiError(s.err)}catch(e){}else try{await this.clearAuthStateAsync();try{await this.onProfileDeleted(i)}catch(e){}}finally{e.tickEvent("auth.profile.deleted")}}async initialUserPreferencesAsync(){if(await this.loggedInAsync())return this.initialUserPreferences_||(this.initialUserPreferences_=this.fetchUserPreferencesAsync()),this.initialUserPreferences_}async userProfileAsync(){if(!await this.loggedInAsync())return;const e=await b();return Object.assign({},e.profile)}async userPreferencesAsync(){const e=await b();return Object.assign({},e.preferences)}async authCheckAsync(){var e;if(!x())return;if(!await m())return;const t=await b();return(null===(e=null==t?void 0:t.profile)||void 0===e?void 0:e.id)?this.initialAuthCheck_||(this.initialAuthCheck_=Promise.resolve(t.profile)):this.initialAuthCheck_||(this.initialAuthCheck_=this.fetchUserAsync()),this.initialAuthCheck_}async loggedInAsync(){return!!await this.authCheckAsync()&&await this.hasUserIdAsync()}async updateUserProfileAsync(e){if(!await this.loggedInAsync())return!1;const t=await b(),n=await this.apiAsync("/api/user/profile",{id:t.profile.id,username:e.username,avatarUrl:e.avatarUrl});return n.success&&await this.setUserProfileAsync(n.resp),n.success}async patchUserPreferencesAsync(n,i={}){const s=async()=>({success:!0,res:await this.userPreferencesAsync()});if(!(n=(n=Array.isArray(n)?n:[n]).filter(e=>!!e)).length)return await s();const r=(t,n,i)=>{const s=e.U.deepCopy(t);ts.pxtc.jsonPatch.patchInPlace(s,n);let r=ts.pxtc.jsonPatch.diff(t,s);return r.length&&i&&(r=r.filter(i)),r},a=await this.userPreferencesAsync(),o=r(a,n,i.filter);if(!o.length)return await s();if(ts.pxtc.jsonPatch.patchInPlace(a,o),await this.setUserPreferencesAsync(a),!await this.loggedInAsync())return await s();this.patchQueue.push({ops:n,filter:i.filter}),clearTimeout(c);const l=async()=>{if(u=0,!this.patchQueue.length)return await s();const n=await this.apiAsync("/api/user/preferences");if(!n.success)return e.reportError("identity","failed to fetch preferences for patch",n),{success:!1,res:void 0};const i=e.U.deepCopy(n.resp)||t.DEFAULT_USER_PREFERENCES(),a=this.patchQueue;this.patchQueue=[],a.forEach(e=>{const t=r(i,e.ops,e.filter);ts.pxtc.jsonPatch.patchInPlace(i,t)});const o=pxtc.jsonPatch.diff(n.resp,i),l=await this.apiAsync("/api/user/preferences",o,"PATCH");return l.success?this.setUserPreferencesAsync(l.resp):e.reportError("identity","failed to patch preferences",l),{success:l.success,res:l.resp}};return i.immediate?await l():(u||(u=e.U.now()),1e4<e.U.now()-u?await l():(c=setTimeout(l,1e3),{success:!1,res:void 0}))}async hasUserIdAsync(){var e;if(!x())return!1;if(!await m())return;const t=await b();return!!(null===(e=null==t?void 0:t.profile)||void 0===e?void 0:e.id)}async fetchUserAsync(){var e;if(!x())return;if(!await m())return;const t=await b();if(null===(e=null==t?void 0:t.profile)||void 0===e?void 0:e.id)return t.profile;const n=await this.apiAsync("/api/user/profile");if(n.success){const e=n.resp;return await this.setUserProfileAsync(e),e}}async setUserProfileAsync(e){const t=await this.hasUserIdAsync();await this.transformUserProfileAsync(e);const n=await this.hasUserIdAsync();try{await this.onUserProfileChanged()}catch(e){}if(n&&!t)try{await this.onSignedIn()}catch(e){}else if(!n&&t)try{await this.onSignedOut()}catch(e){}}async setUserPreferencesAsync(e){var n;const i=await b(),s=null!==(n=null==i?void 0:i.preferences)&&void 0!==n?n:t.DEFAULT_USER_PREFERENCES(),r=ts.pxtc.jsonPatch.diff(s,e),a=await this.transformUserPreferencesAsync(Object.assign(Object.assign({},s),e));try{await this.onUserPreferencesChanged(r)}catch(e){}return a}async fetchUserPreferencesAsync(){if(!await this.loggedInAsync())return;await b();const e=await this.apiAsync("/api/user/preferences");if(e.success&&e.resp){return this.setUserPreferencesAsync(e.resp)}}async transformUserProfileAsync(e){let t=await b();return t=Object.assign(Object.assign({},t),{profile:Object.assign({},e)}),await y(t),t.profile}async transformUserPreferencesAsync(e){let t=await b();return t=Object.assign(Object.assign({},t),{preferences:Object.assign({},e)}),await y(t),t.preferences}async clearAuthStateAsync(){await g(),await v();try{await this.onStateCleared()}catch(e){}}async apiAsync(e,t,n,i){return await A.staticApiAsync(e,t,n,i)}static async staticApiAsync(t,n,i,s){const r=await w(s);return t=e.BrowserUtils.isLocalHostDev()?`${e.cloud.DEV_BACKEND}${t}`:t,e.Util.requestAsync({url:t,headers:r,data:n,method:i||(n?"POST":"GET"),withCredentials:!0}).then(e=>({statusCode:e.statusCode,resp:e.json,success:2===Math.floor(e.statusCode/100),err:null})).catch(async e=>(/logout/.test(t)||401!=e.statusCode||await A.staticLogoutAsync(),{statusCode:e.statusCode,err:e,resp:null,success:!1}))}}t.AuthClient=A;const k={hash:"",params:{}};function T(){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 x(){return!l&&!e.BrowserUtils.isPxtElectron()&&T().length>0}function E(e,t){return e.id===t.id&&e.sourceURL===t.sourceURL}t.loginCallbackAsync=async function(t){let i,r=Object.assign({},k);do{if(i=await e.storage.shared.getAsync(n,s),!i)return void e.debug("Auth state not found in storge.");await e.storage.shared.delAsync(n,s);const o=t.state;if(!o||i.key!==o)return void e.debug("Failed to get auth state for key");r=Object.assign(Object.assign({},k),i.callbackState);const l=t.error;if(l){const n=t.error_description;e.tickEvent("auth.login.error",{error:l,provider:i.idp}),e.log(`Auth failed: ${l}:${n}`),r=Object.assign({},k);break}const c=t.token;if(!c){e.debug("Missing authToken in auth callback.");break}if(i.authCodeVerifier){const t=e.Util.stringifyQueryString("/api/otac/check",{persistent:i.persistent});await A.staticApiAsync(t,null,null,i.authCodeVerifier)}await f(c),await d(a,void 0),e.tickEvent("auth.login.success",{provider:i.idp})}while(0);const o=r.hash.startsWith("#")?r.hash:`#${r.hash}`,l=e.Util.stringifyQueryString("",r.params),c=`${i.callbackPathname.startsWith("/")?i.callbackPathname:`/${i.callbackPathname}`}${l}${o}`;window.location.href=c},t.identityProviders=T,t.identityProvider=function(e){return T().filter(t=>t.id===e).shift()},t.hasIdentity=x,t.enableAuth=function(e=!0){l=!e},t.userName=function(e){var t,n,i,s;return null!==(s=null!==(n=null===(t=null==e?void 0:e.idp)||void 0===t?void 0:t.displayName)&&void 0!==n?n:null===(i=null==e?void 0:e.idp)||void 0===i?void 0:i.username)&&void 0!==s?s:"??"},t.identityProviderId=function(e){var t;return null===(t=null==e?void 0:e.idp)||void 0===t?void 0:t.provider},t.firstName=function(t){const n=e.auth.userName(t);return(null==n?void 0:n.split(" ").shift())||n},t.userInitials=function(t){const n=e.auth.userName(t);return ts.pxtc.Util.initials(n)},t.generateUserProfilePicDataUrl=function(t){var n,i;if(null===(i=null===(n=null==t?void 0:t.idp)||void 0===n?void 0:n.picture)||void 0===i?void 0:i.encoded){const n=window.URL||window.webkitURL;try{const i=e.Util.stringToUint8Array(atob(t.idp.picture.encoded)),s=new Blob([i],{type:t.idp.picture.mimeType});t.idp.picture.dataUrl=n.createObjectURL(s)}catch(e){}}},t.badgeEquals=E,t.hasBadge=function(e,t){return e.badges.some(e=>E(e,t))}}(e.auth||(e.auth={}))}(pxt||(pxt={})),function(e){e.tickEvent=function(e){}}(pxt||(pxt={})),function(e){let t;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Log=1]="Log",e[e.Warning=2]="Warning",e[e.Error=3]="Error"}(t=e.LogLevel||(e.LogLevel={}));class n{constructor(){this.setLogLevel(t.Info)}setLogLevel(e){this.logLevel=e}getLogLevel(){return this.logLevel}info(...e){this.shouldLog(t.Info)&&(null===console||void 0===console?void 0:console.info)&&console.info.call(null,...e)}log(...e){this.shouldLog(t.Log)&&(null===console||void 0===console?void 0:console.log)&&console.log.call(null,...e)}debug(...e){this.shouldLog(t.Debug)&&(null===console||void 0===console?void 0:console.debug)&&console.debug.call(null,...e)}error(...e){this.shouldLog(t.Error)&&(null===console||void 0===console?void 0:console.error)&&console.error.call(null,...e)}warn(...e){this.shouldLog(t.Warning)&&(null===console||void 0===console?void 0:console.warn)&&console.warn.call(null,...e)}shouldLog(e){return e>=this.logLevel}}e.ConsoleLogger=n;let i=new n;e.info=function(...e){i.info(...e)},e.log=function(...e){i.log(...e)},e.debug=function(...e){i.debug(...e)},e.error=function(...e){i.error(...e)},e.warn=function(...e){i.warn(...e)},e.setLogger=function(e){const t=null==i?void 0:i.getLogLevel();i=e,void 0!==t&&i.setLogLevel(t)},e.setLogLevel=function(e){i.setLogLevel(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 .!?\-$])/gu,e=>"&#"+e.codePointAt(0)+";"):e},e.htmlUnescape=function(e){return e?e.replace(/(&#\d+;)/g,e=>String.fromCodePoint(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,3})-(\w{2,4}$)/i.exec(e);return t&&t[1]&&t[2]?[`${t[1].toLowerCase()}-${t[2].toUpperCase()}`,t[1].toLowerCase(),`${t[1].toLowerCase()}-${t[2].toLowerCase()}`]:[(e||"en").toLowerCase()]}function l(){return a()==e.TRANSLATION_LOCALE}function c(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=l,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=c,e.fmt=function(e,...t){return c(e,t)};const u={};e.dumpLocStats=function(){const e={};Object.keys(u).sort((e,t)=>u[t]-u[e]).forEach(t=>e[t]=t),pxt.log("prioritized list of strings:"),pxt.log(JSON.stringify(e,null,2))};function d(t,n){if(!t)return t;u[t]=(u[t]||0)+1;let i=e._localize(t);return i=i.replace(/^\{(id|loc):[^\}]+\}/g,""),c(i,n)}e.lf_va=d,e.lf=function(e,...t){return d(e,t)},e.rlf=function(e,...t){return d(e,t)},e.blf=function(e){return l()?e:d(e,[])},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.deepEqual=function e(t,n){if(t===n)return!0;if(t&&n&&"object"==typeof t&&"object"==typeof n){const i=Array.isArray(t),s=Array.isArray(n);if(i&&s){if(t.length!==n.length)return!1;for(let i=0;i<t.length;++i)if(!e(t[i],n[i]))return!1;return!0}if(i!==s)return!1;const r=Object.keys(t);if(r.length!==Object.keys(n).length)return!1;for(const i of r){if(!n.hasOwnProperty(i))return!1;if(!e(t[i],n[i]))return!1}return!0}return t!=t&&n!=n}}(e.Util||(e.Util={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={}));const lf=ts.pxtc.Util.lf;var Measurements,pxt,ts;!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.sanitizeFileName=function(e){return e.replace(/[()\\\/.,?*^:<>!;'#$%^&|"@+=«»°{}\[\]¾½¼³²¦¬¤¢£~¯¸`±\x00-\x1F]/g,"").trim().replace(/\s+/g,"-")},n.repeatMap=function(e,t){e=e||0;let n=[];for(let i=0;i<e;++i)n.push(t(i));return n},n.listsEqual=function(e,t){if(!e||!t||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0},n.oops=function(e="OOPS"){throw new Error(e)},n.reversed=function(e){return(e=e.slice(0)).reverse(),e},n.arrayEquals=function(e,t,n=(e,t)=>e===t){if(e==t)return!0;if(!e&&t||!t&&e||e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!n(e[i],t[i]))return!1;return!0},n.iterMap=function(e,t){Object.keys(e).forEach(n=>t(n,e[n]))},n.mapMap=function(e,t){let n={};return Object.keys(e).forEach(i=>n[i]=t(i,e[i])),n},n.values=function(e){return Object.keys(e||{}).map(t=>e[t])},n.pushRange=i,n.concatArrayLike=function(e){return s(e)},n.concat=s,n.memcpy=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=n&&!i;return clearTimeout(i),i=setTimeout(function(){i=null,n||e.apply(s,r)},t),a&&e.apply(s,r),i}};function d(e){return e&&(e=e.replace(/\\/g,"/")),e}function h(e){const i={url:`${encodeURI(e.url.replace(/[?#].*/,"..."))}`,method:`${e.method||"GET"}`};return pxt.perf.measureStart(Measurements.NetworkRequest),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}).then(e=>{const t=e.headers["content-length"];if(t)i.sizeInBytes=`${t}`;else if(e.text&&pxt.perf.isEnabled()){const t=(new TextEncoder).encode(e.text);i.sizeInBytes=t.length+""}return i.statusCode=`${e.statusCode}`,e}).finally(()=>{pxt.perf.measureEnd(Measurements.NetworkRequest,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=n&&!i;i||(i=setTimeout(function(){i=null,n||e.apply(s,r)},t)),a&&e.apply(s,r)}},n.randomPermute=function(e){for(let t=0;t<e.length;++t){let n=m()%e.length,i=e[t];e[t]=e[n],e[n]=i}},n.randomPick=function(e){return 0==e.length?null:e[m()%e.length]},n.timeSince=function(e){let t=(Date.now()-(e*=1e3))/1e3;return isNaN(t)?"":t<-30?(t=-t,t<60?n.lf("in a few seconds"):t<120?n.lf("in a minute"):t<3600?n.lf("in {0} minute{0:s}",Math.floor(t/60)):t<7200?n.lf("in an hour"):t<86400?n.lf("in {0} hour{0:s}",Math.floor(t/60/60)):t<2592e3?n.lf("in {0} day{0:s}",Math.floor(t/60/60/24)):t<31536e3?n.lf("in {0} month{0:s}",Math.floor(t/60/60/24/30)):n.lf("in {0} year{0:s}",Math.floor(t/60/60/24/365))):t<0?n.lf("now"):t<10?n.lf("a few seconds ago"):t<60?n.lf("{0} second{0:s} ago",Math.floor(t)):t<120?n.lf("a minute ago"):t<3600?n.lf("{0} minute{0:s} ago",Math.floor(t/60)):t<7200?n.lf("an hour ago"):t<86400?n.lf("{0} hour{0:s} ago",Math.floor(t/60/60)):t<2592e3?n.lf("{0} day{0:s} ago",Math.floor(t/60/60/24)):t<31536e3?n.lf("{0} month{0:s} ago",Math.floor(t/60/60/24/30)):n.lf("{0} year{0:s} ago",Math.floor(t/60/60/24/365))},n.unicodeToChar=function(e){return e.replace(/\\u([\d\w]{4})/gi,function(e,t){return String.fromCharCode(parseInt(t,16))})},n.escapeForRegex=function(e){return null==e?void 0:e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},n.stripUrlProtocol=function(e){return null==e?void 0:e.replace(/.*?:\/\//g,"")},n.normalizePath=d,n.pathJoin=function(e,t){if(d(e),d(t),e||t)return e?t?("/"!==e.charAt(e.length-1)&&(e+="/"),"/"==t.charAt(0)&&(t=t.substring(1)),e+t):e:t},n.isNodeJS="undefined"==typeof window,n.requestAsync=h,n.httpGetTextAsync=function(e){return h({url:e}).then(e=>e.text)},n.httpGetJsonAsync=function(e){return h({url:e}).then(e=>e.json)},n.httpPostJsonAsync=function(e,t){return h({url:e,data:t||{}}).then(e=>e.json)},n.stringToUint8Array=function(e){let t=e.length,n=new Uint8Array(t);for(let i=0;i<t;++i)n[i]=255&e.charCodeAt(i);return n},n.uint8ArrayToString=function(e){let t=e.length,n="";for(let i=0;i<t;++i)n+=String.fromCharCode(e[i]);return n},n.fromUTF8=function(e){if(!e)return"";let t="";for(let n=0;n<e.length;++n){let i=255&e.charCodeAt(n);t+=37==i||i>127?"%"+i.toString(16):e.charAt(n)}return decodeURIComponent(t)},n.toUTF8=p,n.toHex=function(e){let t="";for(let n=0;n<e.length;++n)t+=("0"+e[n].toString(16)).slice(-2);return t},n.fromHex=function(e){let t=new Uint8Array(e.length>>1);for(let n=0;n<e.length;n+=2)t[n>>1]=parseInt(e.slice(n,n+2),16);return t};n.PromiseQueue=class{constructor(){this.promises={}}enqueue(e,t){return new Promise((n,i)=>{let s=this.promises[e];s||(s=this.promises[e]=[]),s.push(()=>t().finally(()=>{s.shift(),0==s.length?delete this.promises[e]:s[0]()}).then(n,i)),1==s.length&&s[0]()})}};function f(){return Date.now()}function m(){let e=new Uint8Array(4);return n.getRandomBuf(e),new Uint32Array(e.buffer)[0]}function g(e,t,n){function i(i){pxt.debug(`downloading translations for ${e} ${t}`);let s=pxt.BrowserUtils.isLocalHost()||pxt.webConfig.isStatic?"https://makecode.com/api/":"",r=`${s}translations?lang=${encodeURIComponent(e)}&filename=${encodeURIComponent(t)}&approved=true`;const a={};return n&&!pxt.Cloud.useCdnApi()&&(a["If-None-Match"]=n),(s?h:pxt.Cloud.apiRequestWithCdnAsync)({url:r,headers:a}).then(s=>304==s.statusCode||200==s.statusCode?(n=s.headers.etag||"",pxt.BrowserUtils.translationDbAsync().then(r=>r.setAsync(e,t,n,s.json||i)).then(()=>s.json||i)):s.json,e=>{pxt.log(`failed to load translations from ${r}`)})}return pxt.BrowserUtils.translationDbAsync().then(n=>n.getAsync(e,t)).then(e=>{if(e){n=e.etag;return(Date.now()-e.time)/1e3>300&&i(e.strings),e.strings}return i()})}function b(e){let[t,i]=n.normalizeLanguageCode(e),s=pxt.appTarget.appTheme;if(s&&s.availableLocales){if(s.availableLocales.indexOf(t)>-1)return!0;if(i&&s.availableLocales.indexOf(i)>-1)return!0}return!1}let y;function v(e,i,s,r,a){if(a=a||y.Editor,"en-US"===(s=n.normalizeLanguageCode(s)[0])||"en"===s)return Promise.resolve(void 0);let o,l,c=`${s}/${r}/${a}`;if(n.translationsCache()[c])return Promise.resolve(n.translationsCache()[c]);switch(a){case y.Editor:o=[{staticName:"strings.json",path:"strings.json"},{staticName:"target-strings.json",path:e+"/target-strings.json"}];break;case y.Sim:o=[{staticName:"sim-strings.json",path:e+"/sim-strings.json"}];break;case y.Apis:o=[{staticName:"bundled-strings.json",path:e+"/bundled-strings.json"}];break;case y.SkillMap:o=[{staticName:"skillmap-strings.json",path:"/skillmap-strings.json"}]}function u(e){e&&(l||(l={}),Object.keys(e).filter(t=>!!e[t]).forEach(t=>l[t]=e[t]))}if(r){let r=0;return t.U.promiseMapAllSeries(o,e=>g(s,e.path).then(u,e=>{pxt.log(e.message),++r})).then(()=>(r&&(n.translationsCache()[c]=l),r!==o.length&&l?Promise.resolve(l):(pxt.tickEvent("translations.livetranslationsfailed"),v(e,i,s,!1,a))))}return Promise.all(o.map(e=>n.httpGetJsonAsync(`${i}locales/${s}/${e.staticName}`).catch(e=>{}))).then(e=>{let t={};e.forEach(e=>pxt.Util.jsonMergeFrom(t,e)),Object.keys(t).length&&(l=t,n.translationsCache()[c]=l)},e=>{pxt.error("failed to load localizations")}).then(()=>l)}function w(e){const t={};for(const n of Object.keys(e))t[n]=A(e[n]);return t}function A(e){var t;return{attributes:Object.assign({},e.attributes),parameters:null===(t=e.parameters)||void 0===t?void 0:t.map(k),extendsTypes:e.extendsTypes?[...e.extendsTypes]:void 0,pkgs:e.pkgs?[...e.pkgs]:void 0,combinedProperties:e.combinedProperties?[...e.combinedProperties]:void 0,name:e.name,namespace:e.namespace,fileName:e.fileName,kind:e.kind,retType:e.retType,isInstance:e.isInstance,isContextual:e.isContextual,qName:e.qName,pkg:e.pkg,snippet:e.snippet,snippetName:e.snippetName,snippetWithMarkers:e.snippetWithMarkers,pySnippet:e.pySnippet,pySnippetName:e.pySnippetName,pySnippetWithMarkers:e.pySnippetWithMarkers,blockFields:e.blockFields,isReadOnly:e.isReadOnly,pyName:e.pyName,pyQName:e.pyQName,snippetAddsDefinitions:e.snippetAddsDefinitions}}function k(e){var n,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(T),handlerParameters:null===(i=e.handlerParameters)||void 0===i?void 0:i.map(T),options:e.options?t.U.clone(e.options):void 0,isEnum:e.isEnum}}function T(e){return{name:e.name,type:e.type}}function x(e){if(!e)return e;const t=[{label:"Google API Key",regex:/AIza[A-Za-z0-9_\\\-]{35}/},{label:"Slack Token",regex:/xox[pbar]\-[A-Za-z0-9]/},{label:"GitHub Token",regex:/(gh[psuro]_[a-zA-Z0-9]{36}|github_pat_[a-zA-Z0-9]{22}_[a-zA-Z0-9]{59})/},{label:"Generic Secret",regex:/\b(token|signature|password|passwd|pwd|android:value)[^a-zA-Z0-9]{0,200}/i},{label:"CLI Credentials",regex:/((login|psexec|(certutil|psexec)\.exe).{1,50}(\s-u(ser(name)?)?\s+.{3,100})?\s-(admin|user|vm|root)?p(ass(word)?)?\s+["']?[^$\-\/\s]|(^|[\s\r\n\\])net(\.exe)?.{1,5}(user\s+|share\s+\/user:| user -? secrets ? set) \s + [^ $\s \/])/},{label:"JWT Token",regex:/\beyJ[A-Za-z0-9_\-]+?\.[A-Za-z0-9_\-]+?\.[A-Za-z0-9_\-]+?\b/},{label:"Email",regex:/\b[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,63}\b/i}];for(const n of t)if(n.regex.test(e))return`<REDACTED: ${n.label}>`;return e}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.runWithBackoffAsync=async function(e,t,n,i,s,r,a=1.5){let o=n;const l=Date.now();for(;Date.now()-l<s;){const n=await e();if(t(n))return n;await pxt.Util.timeout(o),o=Math.min(o*a,i)}throw new Error(r)},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";case"wasm":return"application/wasm";default:return"application/octet-stream"}},n.randomUint32=m,n.guidGen=function(){function e(){return(65536|m()).toString(16).slice(-4)}return e()+e()+"-"+e()+"-4"+e().slice(-3)+"-"+e()+"-"+e()+e()+e()},n.downloadLiveTranslationsAsync=g,n.pxtLangCookieId="PXT_LANG",n.langCookieExpirationDays=30,n.allLanguages={af:{englishName:"Afrikaans",localizedName:"Afrikaans"},ar:{englishName:"Arabic",localizedName:"العربية"},az:{englishName:"Azerbaijani",localizedName:"آذربایجان دیلی"},bg:{englishName:"Bulgarian",localizedName:"български"},bi:{englishName:"Bislama",localizedName:"Bislama"},bn:{englishName:"Bengali",localizedName:"বাংলা"},ca:{englishName:"Catalan",localizedName:"Català"},cs:{englishName:"Czech",localizedName:"Čeština"},cy:{englishName:"Welsh",localizedName:"Cymraeg"},da:{englishName:"Danish",localizedName:"Dansk"},de:{englishName:"German",localizedName:"Deutsch"},el:{englishName:"Greek",localizedName:"Ελληνικά"},en:{englishName:"English",localizedName:"English"},"es-ES":{englishName:"Spanish (Spain)",localizedName:"Español (España)"},"es-MX":{englishName:"Spanish (Mexico)",localizedName:"Español (México)"},et:{englishName:"Estonian",localizedName:"Eesti"},eu:{englishName:"Basque",localizedName:"Euskara"},fa:{englishName:"Persian",localizedName:"فارسی"},fi:{englishName:"Finnish",localizedName:"Suomi"},fil:{englishName:"Filipino",localizedName:"Filipino"},fo:{englishName:"Faroese",localizedName:"føroyskt"},fr:{englishName:"French",localizedName:"Français"},"fr-CA":{englishName:"French (Canada)",localizedName:"Français (Canada)"},"ga-IE":{englishName:"Irish",localizedName:"Gaeilge"},gl:{englishName:"Galician",localizedName:"galego"},gn:{englishName:"Guarani",localizedName:"Avañe'ẽ"},"gu-IN":{englishName:"Gujarati",localizedName:"ગુજરાતી"},haw:{englishName:"Hawaiian",localizedName:"ʻŌlelo Hawaiʻi"},hi:{englishName:"Hindi",localizedName:"हिन्दी"},he:{englishName:"Hebrew",localizedName:"עברית"},hr:{englishName:"Croatian",localizedName:"Hrvatski"},hu:{englishName:"Hungarian",localizedName:"Magyar"},"hy-AM":{englishName:"Armenian (Armenia)",localizedName:"Հայերէն (Հայաստան)"},id:{englishName:"Indonesian",localizedName:"Bahasa Indonesia"},is:{englishName:"Icelandic",localizedName:"Íslenska"},it:{englishName:"Italian",localizedName:"Italiano"},ja:{englishName:"Japanese",localizedName:"日本語"},"ja-HIRA":{englishName:"Hiragana",localizedName:"にほんご"},ka:{englishName:"Georgian",localizedName:"ქართული"},kab:{englishName:"Kabyle",localizedName:"شئعم"},kk:{englishName:"Kazakh",localizedName:"қазақ тілі"},km:{englishName:"Khmer",localizedName:"ខ្មែរ"},kmr:{englishName:"Kurmanji (Kurdish)",localizedName:"کورمانجی"},kn:{englishName:"Kannada",localizedName:"ಕನ್ನಡ"},ko:{englishName:"Korean",localizedName:"한국어"},lt:{englishName:"Lithuanian",localizedName:"Lietuvių"},lv:{englishName:"Latvian",localizedName:"Latviešu"},"ml-IN":{englishName:"Malayalam",localizedName:"മലയാളം"},mr:{englishName:"Marathi",localizedName:"मराठी"},ms:{englishName:"Malay",localizedName:"Melayu"},nl:{englishName:"Dutch",localizedName:"Nederlands"},no:{englishName:"Norwegian",localizedName:"Norsk"},nb:{englishName:"Norwegian Bokmal",localizedName:"Norsk bokmål"},"nn-NO":{englishName:"Norwegian Nynorsk",localizedName:"Norsk nynorsk"},"pa-IN":{englishName:"Punjabi",localizedName:"ਪੰਜਾਬੀ"},pl:{englishName:"Polish",localizedName:"Polski"},ps:{englishName:"Pashto",localizedName:"پښتو"},"pt-BR":{englishName:"Portuguese (Brazil)",localizedName:"Português (Brasil)"},"pt-PT":{englishName:"Portuguese (Portugal)",localizedName:"Português (Portugal)"},ro:{englishName:"Romanian",localizedName:"Română"},ru:{englishName:"Russian",localizedName:"Русский"},sat:{englishName:"Santali",localizedName:"ᱥᱚᱸᱴᱚᱞᱤ"},"si-LK":{englishName:"Sinhala",localizedName:"සිංහල"},sk:{englishName:"Slovak",localizedName:"Slovenčina"},sl:{englishName:"Slovenian",localizedName:"Slovenski"},sq:{englishName:"Albanian",localizedName:"shqip"},sr:{englishName:"Serbian (Cyrillic)",localizedName:"Srpski"},su:{englishName:"Sundanese",localizedName:"ᮘᮞ ᮞᮥᮔ᮪ᮓ"},"sv-SE":{englishName:"Swedish",localizedName:"Svenska"},sw:{englishName:"Swahili",localizedName:"Kiswahili"},"sw-TZ":{englishName:"Swahili (Tanzania)",localizedName:"Kiswahili (Tanzania)"},ta:{englishName:"Tamil",localizedName:"தமிழ்"},te:{englishName:"Telugu",localizedName:"తెలుగు"},th:{englishName:"Thai",localizedName:"ภาษาไทย"},tl:{englishName:"Tagalog",localizedName:"ᜏᜒᜃᜅ᜔ ᜆᜄᜎᜓᜄ᜔"},tr:{englishName:"Turkish",localizedName:"Türkçe"},uk:{englishName:"Ukrainian",localizedName:"Українська"},"ur-IN":{englishName:"Urdu (India)",localizedName:"اردو (ہندوستان)"},"ur-PK":{englishName:"Urdu (Pakistan)",localizedName:"اردو (پاکستان)"},vi:{englishName:"Vietnamese",localizedName:"Tiếng việt"},"zh-CN":{englishName:"Chinese (Simplified)",localizedName:"中文(简体)"},"zh-TW":{englishName:"Chinese (Traditional)",localizedName:"中文(繁體)"}},n.isLocaleEnabled=b,n.updateLocalizationAsync=function(t){const{targetId:i,baseUrl:s,force:r}=t;let{code:a}=t;if(a=n.normalizeLanguageCode(a)[0],"en-US"===a&&(a="en"),a===n.userLanguage()||!b(a)&&!r)return pxt.debug(`loc: ${a} (using built-in)`),Promise.resolve();pxt.debug(`loc: ${a}`);const o=pxt.Util.liveLocalizationEnabled();return v(i,s,a,o,e.pxtc.Util.TranslationsKind.Editor).then(t=>{var r;return t&&(n.setUserLanguage(a),null===(r=pxt.analytics)||void 0===r||r.addDefaultProperties({lang:a}),n.setLocalizedStrings(t)),e.pxtc.Util.downloadTranslationsAsync(i,s,a,o,e.pxtc.Util.TranslationsKind.Apis).then(t=>{t&&(e.pxtc.apiLocalizationStrings=t)})})},function(e){e[e.Editor=0]="Editor",e[e.Sim=1]="Sim",e[e.Apis=2]="Apis",e[e.SkillMap=3]="SkillMap"}(y=n.TranslationsKind||(n.TranslationsKind={})),n.downloadTranslationsAsync=v,n.capitalize=function(e){return e?e[0].toLocaleUpperCase()+e.slice(1):e},n.uncapitalize=function(e){return(e||"").split(/(?=[A-Z])/g).join(" ").toLowerCase()},n.camelCaseToLowercaseWithSpaces=function(e){return e.replace(/([A-Z])/gm," $1").toLocaleLowerCase().trim()},n.snakeCaseToLowercaseWithSpaces=function(e){return e.replace(/_/g," ").toLocaleLowerCase().trim()},n.range=function(e){let t=[];for(let n=0;n<e;++n)t.push(n);return t},n.multipartPostAsync=function(e,t={},i=null,s=null){const r="--------------------------0461489f461126c5";let 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&~++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(!(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&~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),highlightBlocks:Object.assign({},t.highlightBlocks),validateBlocks:Object.assign({},t.validateBlocks)}}}return a},n.cloneApis=w,n.cloneSymbolInfo=A,n.toUTF8Array=function(e){return(new TextEncoder).encode(e)},n.fromUTF8Array=function(e){return(new TextDecoder).decode(e)},n.getHomeUrl=function(){var e,t,n;let i=null===(e=pxt.webConfig)||void 0===e?void 0:e.relprefix.substr(0,pxt.webConfig.relprefix.length-3);return pxt.appTarget.appTheme.homeUrl&&i?((null===(t=pxt.appTarget.appTheme.homeUrl)||void 0===t?void 0:t.lastIndexOf("/"))===(null===(n=pxt.appTarget.appTheme.homeUrl)||void 0===n?void 0:n.length)-1&&(i=i.substr(1)),pxt.appTarget.appTheme.homeUrl+i):pxt.appTarget.appTheme.homeUrl},n.isExperienceSupported=function(e){var t,n,i,s;const r=null===(i=null===(n=null===(t=pxt.appTarget)||void 0===t?void 0:t.appTheme)||void 0===n?void 0:n.supportedExperiences)||void 0===i?void 0:i.map(e=>e.toLocaleLowerCase()),a=e.toLocaleLowerCase();return null!==(s=null==r?void 0:r.includes(a))&&void 0!==s&&s},n.ocvEnabled=function(){var e,t,n,i;return(null===(t=null===(e=pxt.webConfig)||void 0===e?void 0:e.ocv)||void 0===t?void 0:t.appId)&&(null===(i=null===(n=pxt.webConfig)||void 0===n?void 0:n.ocv)||void 0===i?void 0:i.iframeEndpoint)},n.bresenhamLine=function(e,t,n,i,s){const r=n-e,a=i-t;if(0===r){const n=a>=0?i:t;for(let r=a>=0?t:i;r<=n;r++)s(e,r);return}const o=r>0?1:-1,l=a>0?1:-1,c=Math.abs(a/r);let u=0,d=t;for(let t=e;o>0?t<=n:t>=n;t+=o)for(s(t,d),u+=c;u>=.5;)(l>0?d<=i:d>=i)&&s(t,d),d+=l,u-=1},n.isFeatureEnabled=function(e){var t,n;const i=null===(n=null===(t=pxt.appTarget.appTheme)||void 0===t?void 0:t.enabledFeatures)||void 0===n?void 0:n[e];if(!i)return!1;let s=!0;const r=pxt.Cloud.getRegion()?pxt.Cloud.getRegion().toUpperCase():void 0;return i.includeRegions&&(s=r&&i.includeRegions.some(e=>e.toUpperCase()==r)),s&&i.excludeRegions&&(s=r&&!i.excludeRegions.some(e=>e.toUpperCase()==r)),s},n.cleanData=function(e){if(!e)return e;let t;if("string"==typeof e)t=x(e);else if("object"==typeof e){t={};for(const[n,i]of Object.entries(e))t[n]="string"==typeof i?x(i):i}else t=e;return t}}(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(Measurements.Sha256Buffer);const n=r(e.Util.toUTF8Array(t));return pxt.perf.measureEnd(Measurements.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(n){var i;(i=n.tests||(n.tests={})).diffTests=function(){const n=[{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 n){pxt.log(i.comment);const n=e.pxtc.jsonPatch.diff(i.obja,i.objb);t.U.deepEqual(n,i.expected)?pxt.log("succeeded"):(pxt.error("FAILED"),pxt.log("got",n),pxt.log("exp",i.expected))}},i.patchTests=function(){const n=[{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 n)pxt.log(i.comment),e.pxtc.jsonPatch.patchInPlace(i.obj,i.patches),t.U.deepEqual(i.obj,i.expected)&&i.validate&&!i.validate(i.obj)?i.expected&&(pxt.error("FAILED"),pxt.log("got",i.obj),pxt.log("exp",i.expected)):pxt.log("succeeded")}}(t.jsonPatch||(t.jsonPatch={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){e.perf||(e.perf={})}(pxt||(pxt={})),pxt.perf.isEnabled||(pxt.perf.isEnabled=()=>!1),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(e,t,n){if(Array.isArray(e))return e.map(e=>o(e,t,n));if(e&&"object"==typeof e){for(const i of Object.keys(e))e[i]=o(e[i],t,n);return e}return"string"==typeof e&&t.test(e)?n(e):e}function l(){let t=e.appTarget.compile;t||(t=e.appTarget.compile={isNative:!1,hasHex:!1,switches:{}}),t.hasHex&&(t.nativeType||(t.nativeType=pxtc.NATIVE_TYPE_THUMB)),t.switches||(t.switches={}),t.nativeType==pxtc.NATIVE_TYPE_VM&&(t.sourceMap=!0),e.U.jsonCopyFrom(t.switches,r),t.jsRefCounting=!1,t.useUF2||t.useELF||null!=t.noSourceInFlash||(t.noSourceInFlash=!0),void 0===t.utf8&&(t.utf8=!0),e.appTarget.appTheme||(e.appTarget.appTheme={}),e.appTarget.appTheme.embedUrl||(e.appTarget.appTheme.embedUrl=e.appTarget.appTheme.homeUrl);let n=e.appTarget.compileService;if(n&&n.yottaTarget&&!n.yottaBinary&&(n.yottaBinary="pxt-microbit-app-combined.hex"),e.appTarget=o(e.appTarget,/^@cdnUrl@/i,t=>e.BrowserUtils.patchCdn(t)),e.appTarget.bundledpkgs&&Object.keys(e.appTarget.bundledpkgs).forEach(t=>{const n=e.appTarget.bundledpkgs[t],i=JSON.parse(n[e.CONFIG_NAME]);i.icon&&(i.icon=e.BrowserUtils.patchCdn(i.icon)),n[e.CONFIG_NAME]=e.Package.stringifyConfig(i)}),"undefined"!=typeof window){const t={"lockededitor=1":{appTheme:{lockedEditor:!0}},"hidemenu=1":{appTheme:{hideMenuBar:!0}}};e.appTarget.queryVariants&&e.Util.jsonCopyFrom(t,e.appTarget.queryVariants);const n=window.location.href;Object.keys(t).forEach(i=>{if(new RegExp(i,"i").exec(n)){let n=t[i];n&&e.U.jsonMergeFrom(e.appTarget,n)}})}}function c(n=!1){e.perf.measureStart(Measurements.ReloadAppTargetVariant);const i=n?"":JSON.stringify(e.appTarget);if(e.appTarget=e.U.cloneTargetBundle(t),e.appTargetVariant){const t=e.appTarget.variants&&e.appTarget.variants[e.appTargetVariant];t?e.U.jsonMergeFrom(e.appTarget,t):e.U.userError(lf("Variant '{0}' not defined in pxtarget.json",e.appTargetVariant))}l(),!n&&e.onAppTargetChanged&&i!=JSON.stringify(e.appTarget)&&e.onAppTargetChanged(),e.perf.measureEnd(Measurements.ReloadAppTargetVariant)}function u(){return{relprefix:"/--",workerjs:"/worker.js",monacoworkerjs:"/monacoworker.js",gifworkerjs:"/gifjs/gif.worker.js",serviceworkerjs:"/serviceworker.js",typeScriptWorkerJs:"/tsworker.js",pxtVersion:"local",pxtRelId:"localRelId",pxtCdnUrl:"/cdn/",commitCdnUrl:"/cdn/",blobCdnUrl:"/blb/",cdnUrl:"/cdn/",targetUrl:"",targetVersion:"local",targetRelId:"",targetId:e.appTarget?e.appTarget.id:"",simUrl:"/sim/simulator.html",simserviceworkerUrl:"/simulatorserviceworker.js",simworkerconfigUrl:"/sim/workerConfig.js",partsUrl:"/sim/siminstructions.html"}}function d(){return s||(s=e.Cloud.downloadTargetConfigAsync().then(e=>e||{},e=>({}))),s}function h(t=null){return t||(t=e.appTarget.compile),t.nativeType==ts.pxtc.NATIVE_TYPE_VM?t.useESP?t.useUF2?ts.pxtc.BINARY_UF2:ts.pxtc.BINARY_ESP:ts.pxtc.BINARY_PXT64:t.useUF2&&!t.switches.rawELF?ts.pxtc.BINARY_UF2:t.useELF?ts.pxtc.BINARY_ELF:ts.pxtc.BINARY_HEX}e.setAppTarget=function(n){e.appTarget=n||{},l(),t=e.U.cloneTargetBundle(e.appTarget)},e.setBundledApiInfo=function(e){for(const t of Object.keys(e)){const n=e[t].apis.byQName;for(const e of Object.keys(n)){const t=n[e],i=e.lastIndexOf("."),s=t.pyQName,r=n[e]={kind:Math.abs(t.kind||7),qName:e,namespace:e.slice(0,i<0?0:i),name:e.slice(i+1),pyQName:s,pyName:s?s.slice(s.lastIndexOf(".")+1):void 0,fileName:"",attributes:t.attributes||{},retType:t.retType||"void",parameters:t.parameters?t.parameters.map(e=>({name:e.name,description:e.description||"",type:e.type||"number",initializer:e.initializer,default:e.default,options:e.options||{},isEnum:!!e.isEnum,handlerParameters:e.handlerParameters})):null,extendsTypes:t.extendsTypes,snippet:t.kind&&t.kind<0?null:void 0,isInstance:!!t.isInstance,isReadOnly:!!t.isReadOnly},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.replaceStringsInJsonBlob=o,e.reloadAppTargetVariant=c,e.setAppTargetVariant=function(t,n={}){e.debug(`app variant: ${t}`),(n.force||e.appTargetVariant!==t&&(e.appTargetVariant||t))&&(e.appTargetVariant=t,c(n.temporary))},e.setHwVariant=function(t,n){t=t.replace(/.*---/,""),/^[\w\-]+$/.test(t)?(e.hwVariant=t,e.hwName=n||t):(e.hwVariant=null,e.hwName=null),e.debug(`hwVariant: ${e.hwVariant} (${e.hwName})`)},e.hasHwVariants=function(){return!!e.appTarget.variants&&Object.keys(e.appTarget.bundledpkgs).some(e=>/^hw---/.test(e))},e.getHwVariants=function(){return e.appTarget.variants?Object.keys(e.appTarget.bundledpkgs).filter(e=>/^hw---/.test(e)).map(t=>JSON.parse(e.appTarget.bundledpkgs[t][e.CONFIG_NAME])).filter(t=>!!e.appTarget.appTheme.experimentalHw||!t.experimentalHw):[]},e.getActiveHwVariant=function(){return e.hwVariant},e.options={},e.reportException=function(t,n){if(e.error(t),n)try{e.error(n)}catch(t){}},e.reportError=function(t,n,i){if(e.error(`${t}: ${n}`),i)try{e.log(JSON.stringify(i,null,2))}catch(e){}},e.localWebConfig=u,e.getOnlineCdnUrl=function(){if(!e.webConfig)return null;let t=/^(https:\/\/[^\/]+)/.exec(e.webConfig.commitCdnUrl);return t?t[1]:null},e.setupWebConfig=function(t){t?e.webConfig=t:e.webConfig||(e.webConfig=u())},e.getEmbeddedScript=function(t){return e.U.lookup(e.appTarget.bundledpkgs||{},t)},e.targetConfigAsync=d,e.packagesConfigAsync=function(){return d().then(e=>e?e.packages:void 0)},e.CONFIG_NAME="pxt.json",e.SIMSTATE_JSON=".simstate.json",e.SERIAL_EDITOR_FILE="serial.txt",e.README_FILE="README.md",e.GITIGNORE_FILE=".gitignore",e.ASSETS_FILE="assets.json",e.CLOUD_ID="pxt/",e.BLOCKS_PROJECT_NAME="blocksprj",e.JAVASCRIPT_PROJECT_NAME="tsprj",e.PYTHON_PROJECT_NAME="pyprj",e.MAIN_BLOCKS="main.blocks",e.MAIN_TS="main.ts",e.MAIN_PY="main.py",e.DEFAULT_GROUP_NAME="other",e.TILEMAP_CODE="tilemap.g.ts",e.TILEMAP_JRES="tilemap.g.jres",e.IMAGES_CODE="images.g.ts",e.IMAGES_JRES="images.g.jres",e.TUTORIAL_CODE_START="_onCodeStart.ts",e.TUTORIAL_CODE_STOP="_onCodeStop.ts",e.TUTORIAL_INFO_FILE="tutorial-info-cache.json",e.TUTORIAL_CUSTOM_TS="tutorial.custom.ts",e.BREAKPOINT_TABLET=991,e.PALETTES_FILE="_palettes.json",e.HISTORY_FILE="_history",e.MAX_DESCRIPTION_LENGTH=5e3,e.outputName=h,e.isOutputText=function(e=null){return h(e)==ts.pxtc.BINARY_HEX}}(pxt||(pxt={})),function(e){!function(t){const n="this";let i;function s(){if(i={device_while:{name:e.Util.lf("a loop that repeats while the condition is true"),tooltip:e.Util.lf("Run the same sequence of actions while the condition is met."),url:"/blocks/loops/while",category:"loops",block:{message0:e.Util.blf("while %1"),appendField:e.Util.blf("{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.blf("for %1 from 0 to %2"),variable:e.Util.blf("{id:var}index"),appendField:e.Util.blf("{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.blf("for %1 from 0 to %2"),variable:e.Util.blf("{id:var}index"),appendField:e.Util.blf("{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.blf("for element %1 of %2"),variable:e.Util.blf("{id:var}value"),appendField:e.Util.blf("{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.blf("for element %1 of %2"),variable:e.Util.blf("{id:var}value"),appendField:e.Util.blf("{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"]},block:{message0:e.Util.blf("%1 of %2 and %3"),optionMin:e.Util.blf("{id:op}min"),optionMax:e.Util.blf("{id:op}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.blf("absolute of %1")}},math_number:{name:e.Util.lf("{id:block}number"),url:"/types/number",category:"math",tooltip:e.appTarget&&e.appTarget.compile?e.Util.lf("a decimal number"):e.Util.lf("an integer number")},math_integer:{name:e.Util.lf("{id:block}number"),url:"/types/number",category:"math",tooltip:e.Util.lf("an integer number")},math_whole_number:{name:e.Util.lf("{id:block}number"),url:"/types/number",category:"math",tooltip:e.Util.lf("a whole number")},math_number_minmax:{name:e.Util.lf("{id:block}number"),url:"/blocks/math",category:"math"},math_arithmetic:{name:e.Util.lf("arithmetic operation"),url:"/blocks/math",tooltip:{ADD:e.Util.lf("Return the sum of the two numbers."),MINUS:e.Util.lf("Return the difference of the two numbers."),MULTIPLY:e.Util.lf("Return the product of the two numbers."),DIVIDE:e.Util.lf("Return the quotient of the two numbers."),POWER:e.Util.lf("Return the first number raised to the power of the second number.")},operators:{OP:["ADD","MINUS","MULTIPLY","DIVIDE","POWER"]},category:"math",block:{MATH_ADDITION_SYMBOL:e.Util.blf("{id:op}+"),MATH_SUBTRACTION_SYMBOL:e.Util.blf("{id:op}-"),MATH_MULTIPLICATION_SYMBOL:e.Util.blf("{id:op}×"),MATH_DIVISION_SYMBOL:e.Util.blf("{id:op}/"),MATH_POWER_SYMBOL:e.Util.blf("{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.blf("remainder of %1 / %2")}},math_js_op:{name:e.Util.lf("math function"),tooltip:{sqrt:e.Util.lf("Returns the square root of the argument"),sin:e.Util.lf("Returns the sine of the argument"),cos:e.Util.lf("Returns the cosine of the argument"),acos:e.Util.lf("Returns the arccosine of the argument"),asine:e.Util.lf("Returns the arcsine of the argument"),tan:e.Util.lf("Returns the tangent of the argument"),atan2:e.Util.lf("Returns the arctangent of the quotient of the two arguments"),idiv:e.Util.lf("Returns the integer portion of the division operation on the two arguments"),imul:e.Util.lf("Returns the integer portion of the multiplication operation on the two arguments")},url:"/blocks/math",operators:{OP:["sqrt","sin","cos","tan","atan2","idiv","imul"]},category:"math",block:{sqrt:e.Util.blf("{id:op}square root"),sin:e.Util.blf("{id:op}sin"),cos:e.Util.blf("{id:op}cos"),asin:e.Util.blf("{id:op}asin"),acos:e.Util.blf("{id:op}acos"),tan:e.Util.blf("{id:op}tan"),atan2:e.Util.blf("{id:op}atan2"),idiv:e.Util.blf("{id:op}integer /"),imul:e.Util.blf("{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.blf("{id:op}round"),ceil:e.Util.blf("{id:op}ceiling"),floor:e.Util.blf("{id:op}floor"),trunc:e.Util.blf("{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.blf("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.blf("repeat %1 times"),CONTROLS_REPEAT_INPUT_DO:e.Util.blf("{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.blf("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.blf("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.blf("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.blf("{id:logic}if"),CONTROLS_IF_MSG_THEN:e.Util.blf("{id:logic}then"),CONTROLS_IF_MSG_ELSE:e.Util.blf("{id:logic}else"),CONTROLS_IF_MSG_ELSEIF:e.Util.blf("{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.blf("empty array"),LISTS_CREATE_WITH_INPUT_WITH:e.Util.blf("array of"),LISTS_CREATE_WITH_CONTAINER_TITLE_ADD:e.Util.blf("array"),LISTS_CREATE_WITH_ITEM_TITLE:e.Util.blf("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.blf("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.blf("%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.blf("%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.blf("{id:op}and"),LOGIC_OPERATION_OR:e.Util.blf("{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.blf("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.blf("{id:boolean}true"),LOGIC_BOOLEAN_FALSE:e.Util.blf("{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.blf("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.blf("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.blf("function"),PROCEDURE_ALREADY_EXISTS:e.Util.blf("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.blf("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.blf("return %1"),message_no_value:e.Util.blf("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.blf("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.blf("call"),FUNCTIONS_GO_TO_DEFINITION_OPTION:e.Util.blf("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.blf("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.blf("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.blf("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.blf("continue")}},e.Util.isTranslationMode())for(const t of Object.keys(i)){const n=i[t];if(n.block){n.translationIds=Object.values(n.block).map(t=>e.U.rlf(t));for(const t of Object.keys(n.block))n.block[t]=e.U.fmt_va(n.block[t].replace(/^\{(id|loc):[^\}]+\}/g,""),[])}}if(e.blocks.showBlockIdInTooltip)for(const e of Object.keys(i)){const t=i[e].tooltip;if("object"==typeof t&&null!==t)for(const n in t)t.hasOwnProperty(n)&&(i[e].tooltip[n]=`${t[n]} (id: ${e})`);else i[e].tooltip=`${i[e].tooltip} (id: ${e})`}}t.showBlockIdInTooltip=!1,t.requirePxtBlockly=()=>{},t.requireBlockly=()=>{},t.registerFieldEditor=()=>{},t.MATH_FUNCTIONS={unary:["sqrt","sin","cos","tan","asin","acos"],binary:["atan2"],infix:["idiv","imul"]},t.ROUNDING_FUNCTIONS=["round","ceil","floor","trunc"],t.builtinFunctionInfo={"Math.abs":{blockId:"math_op3",params:["x"]},"Math.min":{blockId:"math_op2",params:["x","y"]},"Math.max":{blockId:"math_op2",params:["x","y"]}},t.normalizeBlock=function(t,n=e.log){if(!t)return t;let i=t.replace(/(?:^|[^\\])([%$])\s+/g,"$1");return i!=t&&(n(`block has extra spaces: ${t}`),t=i),i=(t=i).replace(/([%$]\w+)\s*=\s*(\w+)/,"$1=$2"),i!=t&&(n(`block has space between %name and = : ${t}`),t=i),i=i.replace(/\s*\|\s*/g,"|"),i},t.compileInfo=function(e){var i;const s={parameters:[],actualNameToParam:{},definitionNameToParam:{},handlerArgs:[]};let r=!(1!=e.kind&&2!=e.kind||e.attributes.defaultInstance||e.isStatic);"boolean"!=typeof e.isInstance||(null===(i=e.attributes)||void 0===i?void 0:i.defaultInstance)||(r=e.isInstance);const a=!!e.attributes._def,o=a?e.attributes._def.parameters.slice(0):void 0,l=a?o.length:e.parameters?e.parameters.length:0,c=t.builtinFunctionInfo[e.qName];a&&e.attributes._expandedDef&&o.push(...e.attributes._expandedDef.parameters);const u={},d=o?o.filter(e=>!e.ref||(u[e.name]=e,!1)):[];if(r&&a&&o.length){const t=u[n]||o[0],i=t.name,r=!t.shadowBlockId||"variables_get"===t.shadowBlockId;let a=e.attributes.paramDefl[i]||e.attributes.paramDefl.this;r&&(a=t.varName||a),s.thisParameter={actualName:n,definitionName:i,shadowBlockId:t.shadowBlockId,type:e.namespace,defaultValue:a,definitionIndex:o.indexOf(t),fieldEditor:h(i,n),fieldOptions:p(i,n),shadowOptions:f(i,n)}}if(e.parameters){let t=r&&!u[n]?1:0;e.parameters.forEach((n,i)=>{let r;if(u[n.name]?r=u[n.name]:t<d.length&&(r=d[t],++t),r||!a){let e;n.options&&n.options.min&&n.options.max&&(e={min:n.options.min.value,max:n.options.max.value});const a=r?r.name:c?c.params[t++]:n.name,u=r&&("variables_get"===r.shadowBlockId||"lists_create_with"==r.shadowBlockId);s.parameters.push({actualName:n.name,type:n.type,defaultValue:u&&r.varName||n.default,definitionName:a,definitionIndex:r?o.indexOf(r):i,shadowBlockId:r&&r.shadowBlockId,isOptional:!!o&&o.indexOf(r)>=l,fieldEditor:h(a,n.name),fieldOptions:p(a,n.name),shadowOptions:f(a,n.name),range:e})}n.handlerParameters&&n.handlerParameters.forEach(t=>{s.handlerArgs.push({name:t.name,type:t.type,inBlockDef:!!o&&o.some(e=>e.ref&&e.name===t.name),localizationKey:`${e.qName}|handlerParam|${t.name}`})})})}return s.parameters.forEach(e=>{s.actualNameToParam[e.actualName]=e,s.definitionNameToParam[e.definitionName]=e}),s;function h(t,n){return e.attributes.paramFieldEditor&&(e.attributes.paramFieldEditor[t]||e.attributes.paramFieldEditor[n])}function p(t,n){return e.attributes.paramFieldEditorOptions&&(e.attributes.paramFieldEditorOptions[t]||e.attributes.paramFieldEditorOptions[n])}function f(t,n){return e.attributes.paramShadowOptions&&(e.attributes.paramShadowOptions[t]||e.attributes.paramShadowOptions[n])}},t.hasHandler=function(e){return e.parameters&&e.parameters.some(e=>{var t,n;return"() => void"==e.type||"Action"==e.type||!!(null===(t=e.properties)||void 0===t?void 0:t.length)||!!(null===(n=e.handlerParameters)||void 0===n?void 0:n.length)})},t.getHelpUrl=function(t){var n,i,s;let r=t.attributes.help;if((null===(n=t.attributes.blockId)||void 0===n?void 0:n.endsWith("_blockCombine_get"))?r=t.attributes.blockCombineGetHelp||r:(null===(i=t.attributes.blockId)||void 0===i?void 0:i.endsWith("_blockCombine_set"))?r=t.attributes.blockCombineSetHelp||r:(null===(s=t.attributes.blockId)||void 0===s?void 0:s.endsWith("_blockCombine_change"))&&(r=t.attributes.blockCombineChangeHelp||r),r){const e=r.replace(/^\//,"");if(/^github:/.test(e))return e;if("none"!==e)return"/reference/"+e}else if(t.pkg&&!e.appTarget.bundledpkgs[t.pkg]){let e=t.qName.toLowerCase().split(".");return e[0]==t.pkg&&e.shift(),`/pkg/${t.pkg}#${encodeURIComponent(e.join("-"))}`}},t.reporterTypeForArgType=function(e){let t="argument_reporter_custom";return"boolean"!==e&&"number"!==e&&"string"!==e||(t=`argument_reporter_${e}`),/^(?:Array<(?:.+)>)|(?:(?:.+)\[\])$/.test(e)&&(t="argument_reporter_array"),t},t.defaultIconForArgType=function(e=""){switch(e){case"number":return"calculator";case"string":return"text width";case"boolean":return"random";case"Array":return"list";default:return"align justify"}},t.parseFields=function(e){return e.split("|").map((e,t)=>{let n=/([^%]*)\s*%([a-zA-Z0-9_]+)/.exec(e);if(!n)return{n:e,ni:t};let i=n[1];return i&&(i=i.trim()),{n:e,ni:t,pre:i,p:n[2]}})},t.blockDefinitions=function(){return i||s(),i},t.getBlockDefinition=function(e){return i||s(),i[e]}}(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 m(){return n()&&/Epiphany/i.test(navigator.userAgent)}function g(){return"undefined"!=typeof window&&("ontouchstart"in window||navigator&&navigator.maxTouchPoints>0)}function b(){return"undefined"!=typeof window&&!!window.pxtElectron}function y(){return"undefined"!=typeof window&&!!window.ipcRenderer}function v(){return b()||y()}function w(t){var n;try{return"undefined"!=typeof window&&/^https?:\/\/(?:localhost|127\.0\.0\.1|192\.168\.\d{1,3}\.\d{1,3}|[a-zA-Z0-9.-]+\.local):\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 A(){return"undefined"!=typeof window&&!!window.PointerEvent}function k(){return i()?"windows":r()?"mac":a()&&o()?"rpi":a()?"linux":"unknown"}function T(){return l()?"edge":m()?"epiphany":f()?"midori":p()?"opera":c()?"ie":u()?"chrome":d()?"safari":h()?"firefox":"unknown"}function x(){if(!n())return null;let e=[];return p()&&(e=/(Opera|OPR)\/([0-9\.]+)/i.exec(navigator.userAgent)),m()?e=/Epiphany\/([0-9\.]+)/i.exec(navigator.userAgent):f()?e=/Midori\/([0-9\.]+)/i.exec(navigator.userAgent):d()?(e=/Version\/([0-9\.]+)/i.exec(navigator.userAgent),e||(e=/(Macintosh|iPod( touch)?|iPhone|iPad); (CPU|Intel).*?OS (X )?(\d+)/i.exec(navigator.userAgent))):e=u()?/(Chrome|Chromium)\/([0-9\.]+)/i.exec(navigator.userAgent):l()?/Edge\/([0-9\.]+)/i.exec(navigator.userAgent):c()?/(MSIE |rv:)([0-9\.]+)/i.exec(navigator.userAgent):/(Firefox|Seamonkey)\/([0-9\.]+)/i.exec(navigator.userAgent),e&&0!=e.length?e[e.length-1]:null}t.isDocumentVisible=function(){return"undefined"!=typeof window&&"visible"===document.visibilityState},t.isIFrame=function(){try{return window&&window.self!==window.top}catch(e){return!0}},t.hasNavigator=n,t.hasWindow=function(){return"undefined"!=typeof window},t.isWindows=i,t.isWindows10=function(){return n()&&/(Win32|Win64|WOW64)/i.test(navigator.platform)&&/Windows NT 10/i.test(navigator.userAgent)},t.isMobile=s,t.isIOS=function(){return n()&&(/iPad|iPhone|iPod/.test(navigator.userAgent)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1)},t.isAndroid=function(){return n()&&/android/i.test(navigator.userAgent)},t.isMac=r,t.isLinux=a,t.isARM=o,t.isEdge=l,t.isChromiumEdge=function(){return n()&&/Edg\//i.test(navigator.userAgent)},t.isIE=c,t.isChrome=u,t.isSafari=d,t.isFirefox=h,t.isOpera=p,t.isMidori=f,t.isEpiphany=m,t.isTouchEnabled=g,t.isPxtElectron=b,t.isIpcRenderer=y,t.isElectron=v,t.isWinRT=()=>"undefined"!=typeof Windows,t.isLocalHost=w,t.isLocalHostDev=function(){return w()&&!v()},t.isSkillmapEditor=function(){try{return/skill(?:s?)map=1/i.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.isInGame=function(){return!!/inGame=1/i.exec(window.location.href)},t.hasFileAccess=function(){const t=e.appTarget.appTheme.disableFileAccessinMaciOs&&(e.BrowserUtils.isMac()||e.BrowserUtils.isIOS()),n=e.appTarget.appTheme.disableFileAccessinAndroid&&e.BrowserUtils.isAndroid();return!t&&!n},t.noSharedLocalStorage=function(){try{return/nosharedlocalstorage/i.test(window.location.href)}catch(e){return!1}},t.useOldTutorialLayout=function(){var t,n;if(null===(n=null===(t=e.appTarget)||void 0===t?void 0:t.appTheme)||void 0===n?void 0:n.legacyTutorial)return!0;try{return/tutorialview=old/.test(window.location.href)}catch(e){return!1}},t.hasPointerEvents=A,t.os=k,t.browser=T,t.browserVersion=x;let E=!1;function C(){return s()&&d()&&!/downloadWindowOpen=0/i.test(window.location.href)}function I(t,n,i){const r=C(),a=x(),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 S(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 N(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=S(t,n),I(d,n,a)}catch(t){o&&o(t),e.debug("saving failed")}return d}function U(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==T()))return!1;const s=x(),r=parseInt(s||"0"),c=u()&&r>=38,g=h()&&r>=31,b=l(),y=d()&&r>=9,v=p()&&u()&&r>=21;let w=c||g||b||y||v;const A=f()||a()&&o()&&m();return w=w&&!A,w=w||/anybrowser=(true|1)/.test(window.location.href),E||(e.log(`Browser: ${T()} ${s} on ${k()}`),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 N(ts.pxtc.encodeBase64(e),t,n)},t.browserDownloadText=function(t,n,i){return N(ts.pxtc.encodeBase64(e.Util.toUTF8(t)),n,i)},t.isBrowserDownloadInSameWindow=C,t.isBrowserDownloadWithinUserContext=function(){const e=x(),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 N(ts.pxtc.encodeBase64(e.Util.uint8ArrayToString(t)),n,i)},t.toDownloadDataUri=S,t.browserDownloadBase64=N,t.loadImageAsync=U,t.loadCanvasAsync=function(e){return U(e).then(e=>{const t=document.createElement("canvas");t.width=e.width,t.height=e.height;return t.getContext("2d").drawImage(e,0,0),t})},t.scaleImageData=function(e,t){const n=document.createElement("canvas"),i=document.createElement("canvas");n.width=e.width,n.height=e.height,i.width=e.width*t,i.height=e.height*t;const s=n.getContext("2d"),r=i.getContext("2d");return s.putImageData(e,0,0),r.imageSmoothingEnabled=!1,r.scale(t,t),r.drawImage(n,0,0),r.getImageData(0,0,e.width*t,e.height*t)},t.imageDataToPNG=function(e,t=1){if(!e)return;const n=document.createElement("canvas"),i=document.createElement("canvas");n.width=e.width,n.height=e.height,i.width=e.width*t,i.height=e.height*t;const s=n.getContext("2d"),r=i.getContext("2d");return s.putImageData(e,0,0),r.imageSmoothingEnabled=!1,r.scale(t,t),r.drawImage(n,0,0),i.toDataURL("image/png")};const O=1e7;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=O,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)};try{const e=new URL(t);"http:"!==e.protocol&&"https:"!==e.protocol||e.host===window.location.host||c.setAttribute("crossOrigin","anonymous")}catch(e){}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 P,L,D,$={};function M(e,t){if(!e)return t;if(!t)return e;return(e.indexOf("/")==e.length-1?e.substring(0,e.length-1):e)+"/"+(0==t.indexOf("/")?t.substring(1):t)}function R(){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=$[n];return i||(i=$[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 $[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(!P){e.debug("blockly: delay load");let t=e.BrowserUtils.loadStyleAsync("blockly.css",ts.pxtc.Util.isUserLanguageRtl());t=t.then(()=>{e.debug("blockly: loaded")}),P=t}return P},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=M,t.joinURLs=function(...e){let t;if(e)for(let n=0;n<e.length;n++)t=M(t,e[n]);return t},t.storageEstimateAsync=R,t.scheduleStorageCleanup=n()&&navigator.storage&&navigator.storage.estimate?ts.pxtc.Util.throttle(function(){R().then(t=>(e.debug(`storage estimate: ${t.usage/t.quota*100|0}%, ${t.usage/1e6|0}/${t.quota/1e6|0}Mb`),t.quota&&t.usage&&t.quota>1e6&&t.usage/t.quota>.9?(e.log("quota usage exceeded, clearing translations"),e.tickEvent("storage.cleanup"),z()):Promise.resolve())).catch(t=>{e.reportException(t)})},1e4,!1):()=>{},t.stressTranslationsAsync=function t(){let n="...";for(let e=0;e<16;++e)n+=n+Math.random();return e.log(`adding entry ${2*n.length} bytes`),e.U.delay(1).then(()=>G()).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){return`${e}|${t}|master`}get(e,t){return this.translations[this.key(e,t)]}getAsync(e,t){return Promise.resolve(this.get(e,t))}set(e,t,n,i,s,r){this.translations[this.key(e,t)]={etag:n,time:i,strings:s,md:r}}setAsync(t,n,i,s,r){return this.set(t,n,i,e.Util.now(),s),Promise.resolve()}clearAsync(){return this.translations={},Promise.resolve()}}class F{constructor(e,t,n,i,s=!1){this.name=e,this.version=t,this.upgradeHandler=n,this.quotaExceededHandler=i,this.skipErrorLog=s}throwIfNotOpened(){if(!this._db)throw new Error("Database not opened; call IDBWrapper.openAsync() first")}errorHandler(t,n,i){this.skipErrorLog?i(t):(e.error(new Error(`${this.name} IDBWrapper error for ${n}: ${t.message}`)),i(t),"QuotaExceededError"==t.name&&(e.log("storage quota exceeded..."),e.tickEvent("storage.quotaexceedederror"),this.quotaExceededHandler&&this.quotaExceededHandler()))}getObjectStore(e,t="readonly"){this.throwIfNotOpened();return this._db.transaction([e],t).objectStore(e)}static deleteDatabaseAsync(e){return new Promise((t,n)=>{const i=(window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB).deleteDatabase(e);i.onsuccess=()=>t(),i.onerror=()=>n(i.error)})}openAsync(){return new Promise((e,t)=>{const n=(window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB).open(this.name,this.version);n.onsuccess=()=>{this._db=n.result,e()},n.onerror=()=>this.errorHandler(n.error,"open",t),n.onupgradeneeded=e=>this.upgradeHandler(e,n)})}getAsync(e,t){return new Promise((n,i)=>{const s=this.getObjectStore(e).get(t);s.onsuccess=()=>n(s.result),s.onerror=()=>this.errorHandler(s.error,"get",i)})}getAllAsync(e){return new Promise((t,n)=>{const i=this.getObjectStore(e).openCursor(),s=[];i.onsuccess=()=>{i.result?(s.push(i.result.value),i.result.continue()):t(s)},i.onerror=()=>this.errorHandler(i.error,"getAll",n)})}setAsync(e,t){return new Promise((n,i)=>{const s=this.getObjectStore(e,"readwrite");let r;r=void 0!==t.id&&null!==t.id?s.put(t):s.add(t),r.onsuccess=()=>n(),r.onerror=()=>this.errorHandler(r.error,"set",i)})}deleteAsync(e,t){return new Promise((n,i)=>{const s=this.getObjectStore(e,"readwrite").delete(t);s.onsuccess=()=>n(),s.onerror=()=>this.errorHandler(s.error,"delete",i)})}deleteAllAsync(e){return new Promise((t,n)=>{const i=this.getObjectStore(e,"readwrite").clear();i.onsuccess=()=>t(),i.onerror=()=>this.errorHandler(i.error,"deleteAll",n)})}getObjectStoreWrapper(e){return new B(this,e)}}t.IDBWrapper=F;class B{constructor(e,t){this.db=e,this.storeName=t}getAsync(e){return this.db.getAsync(this.storeName,e)}getAllAsync(){return this.db.getAllAsync(this.storeName)}setAsync(e){return this.db.setAsync(this.storeName,e)}async deleteAsync(e){await this.db.deleteAsync(this.storeName,e)}async deleteAllAsync(){await this.db.deleteAllAsync(this.storeName)}}t.IDBObjectStoreWrapper=B;class H{constructor(e){this.db=e,this.mem=new j}static dbName(){return`__pxt_translations_${e.appTarget.id||""}`}static createAsync(){function t(){const e=new F(H.dbName(),2,(e,t)=>{t.result.createObjectStore(H.TABLE,{keyPath:H.KEYPATH})},()=>{z().catch(e=>{})});return e.openAsync().then(()=>new H(e))}return t().catch(n=>(e.log("db: failed to open database, try delete entire store..."),F.deleteDatabaseAsync(H.dbName()).then(()=>t())))}getAsync(e,t){e=(e||"en-US").toLowerCase();const n=this.mem.key(e,t),i=this.mem.get(e,t);return i?Promise.resolve(i):this.db.getAsync(H.TABLE,n).then(n=>n?(this.mem.set(e,t,n.etag,n.time,n.strings),Promise.resolve(n)):Promise.resolve(void 0)).catch(e=>Promise.resolve(void 0))}setAsync(n,i,s,r,a){n=(n||"en-US").toLowerCase();const o=this.mem.key(n,i);let l=e.Util.now();this.mem.set(n,i,s,l,r,a),r&&Object.keys(r).filter(e=>!r[e]).forEach(e=>delete r[e]);const c={id:o,etag:s,time:l,strings:r,md:a};return this.db.setAsync(H.TABLE,c).finally(()=>t.scheduleStorageCleanup()).catch(t=>(e.log(`db: set failed (${t.message}), recycling...`),this.clearAsync()))}clearAsync(){return this.db.deleteAllAsync(H.TABLE).then(()=>e.debug("db: all clean")).catch(t=>{e.error("db: failed to delete all")})}}function G(){return e.Util.isNodeJS?Promise.resolve(new j):(L||(L=H.createAsync().catch(()=>new j)),L)}function z(){function t(){const t=H.dbName();return F.deleteDatabaseAsync(t).then(()=>{L=void 0}).catch(n=>{e.log(`db: failed to delete ${t}`),L=void 0})}return L?L.then(e=>e.clearAsync()).catch(e=>t().then()):t()}function q(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"}`}H.TABLE="files",H.KEYPATH="id",t.translationDbAsync=G,t.clearTranslationDbAsync=z,t.getTutorialCodeHash=q;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=>(e.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=q(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,r,a){e.perf.measureStart(Measurements.TutorialInfoDbSetAsync);V(t,a);const o=q(i);return this.setWithHashAsync(t,n,o,s,r)}setWithHashAsync(t,n,i,s,r,a){e.perf.measureStart(Measurements.TutorialInfoDbSetAsync);const o=V(t,a),l={};Object.keys(n).forEach(e=>{Object.keys(n[e]).forEach(t=>{l[t]=n[e][t]})});const c={id:o,time:e.Util.now(),hash:i,snippets:n,blocks:l,highlightBlocks:s,validateBlocks:r};return this.db.setAsync(J.TABLE,c).then(()=>{e.perf.measureEnd(Measurements.TutorialInfoDbSetAsync)})}clearAsync(){return this.db.deleteAllAsync(J.TABLE).then(()=>e.debug("db: all clean")).catch(t=>{e.error("db: failed to delete all")})}}function W(e){return e.split(/\s+/).filter(e=>!!e)}function K(){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 D||(D=J.createAsync()),D},t.clearTutorialInfoDbAsync=function(){function t(){const t=J.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()},t.pointerEvents=A()?{up:"pointerup",down:["pointerdown"],move:"pointermove",enter:"pointerenter",leave:"pointerleave"}:g()?{up:"mouseup",down:["mousedown","touchstart"],move:"touchmove",enter:"touchenter",leave:"touchend"}:{up:"mouseup",down:["mousedown"],move:"mousemove",enter:"mouseenter",leave:"mouseleave"},t.getPageX=function(e){return"pageX"in e?e.pageX:e.changedTouches[0].pageX},t.getPageY=function(e){return"pageY"in e?e.pageY:e.changedTouches[0].pageY},t.getClientX=function(e){return"clientX"in e?e.clientX:e.changedTouches[0].clientX},t.getClientY=function(e){return"clientY"in e?e.clientY:e.changedTouches[0].clientY},t.popupWindow=function(t,n,i,s){try{const r=window.screenLeft?window.screenLeft:window.screenX,a=window.screenTop?window.screenTop:window.screenY,o=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth,l=window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight,c="width="+i+", height="+s+", top="+(l/2-s/2+a)+", left="+(o/2-i/2+r),u=window.open(t,n,e.BrowserUtils.isIpcRenderer()?void 0:c);return u.focus&&u.focus(),u}catch(t){return e.tickEvent("pxt.popupError",{msg:t.message}),null}},t.containsClass=function(e,t){return W(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){W(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){W(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=K,t.setCookieLang=function(t,n=!1){if(e.Util.allLanguages[t]&&t!==K()){e.tickEvent("menu.lang.setcookielang",{lang:t,docs:`${n}`});const i=new Date;i.setTime(i.getTime()+24*e.Util.langCookieExpirationDays*60*60*1e3),document.cookie=`${e.Util.pxtLangCookieId}=${t}; expires=${i.toUTCString()}; path=/`}},t.cacheBustingUrl=function(e){return e?/[?&]rnd=/.test(e)?e:`${e}${e.indexOf("?")>0?"&":"?"}rnd=${Math.random()}`:e},t.appendUrlQueryParams=function(e,t){const n=[];for(const[e,i]of t.entries())n.push(`${encodeURIComponent(e)}=${encodeURIComponent(i)}`);return n.length&&(-1!==e.indexOf("?")?e+="&"+n.join("&"):e+="?"+n.join("&")),e},t.legacyCopyText=function(t){t.focus(),t.setSelectionRange(0,9999);try{const t=document.execCommand("copy");return e.debug("copy: "+t),!!t}catch(e){return!1}},t.setApplicationTheme=function(e){const t=document.body,n=t.classList;for(let e=0;e<n.length;e++)/^theme-/.test(n[e])&&t.classList.remove(n[e]);e&&t.classList.add(`theme-${e}`)},t.isElement=function(e){return e.nodeType===Node.ELEMENT_NODE}}(e.BrowserUtils||(e.BrowserUtils={}))}(pxt||(pxt={})),function(e){!function(e){const t="https://staging.pxt.io";e.DEV_BACKEND=t,e.DEV_REGION="US",e.devBackendType=function(){return"https://makecode.com"===e.DEV_BACKEND?"prod":e.DEV_BACKEND===t?"staging":"http://localhost:8080"===e.DEV_BACKEND?"localhost":"prod"},e.cloudStatus={none:{value:"none"},synced:{value:"synced",icon:"cloud-saved-b",tooltip:lf("Project saved to cloud"),shortStatus:lf("saved"),longStatus:lf("Saved to cloud"),indicator:""},justSynced:{value:"justSynced",icon:"cloud-saved-b",tooltip:lf("Project saved to cloud"),shortStatus:lf("saved!"),longStatus:lf("Saved to cloud!"),indicator:""},offline:{value:"offline",icon:"cloud-error-b",tooltip:lf("Unable to connect to cloud"),shortStatus:lf("offline"),longStatus:lf("Offline"),indicator:lf("offline")},syncing:{value:"syncing",icon:"cloud-saving-b",tooltip:lf("Saving project to cloud..."),shortStatus:lf("saving..."),longStatus:lf("Saving to cloud..."),indicator:lf("syncing...")},conflict:{value:"conflict",icon:"cloud-error-b",tooltip:lf("Project was edited in two places and the changes conflict"),shortStatus:lf("conflict!"),longStatus:lf("Project has a conflict!"),indicator:"!"},localEdits:{value:"localEdits",icon:"cloud-saving-b",tooltip:lf("Project has local changes and will save to cloud soon."),shortStatus:"",longStatus:"",indicator:"*"}}}(e.cloud||(e.cloud={}))}(pxt||(pxt={})),function(e){!function(e){let t;!function(e){e[e.Failed=0]="Failed",e[e.Success=1]="Success",e[e.UserRejected=2]="UserRejected"}(t=e.WebUSBPairResult||(e.WebUSBPairResult={})),e.deployCoreAsync=void 0,e.deployFallbackAsync=void 0,e.hasDeployFn=()=>e.deployCoreAsync||e.deployFallbackAsync,e.deployAsync=(t,n)=>(e.deployCoreAsync||e.deployFallbackAsync)(t,n),e.patchCompileResultAsync=void 0,e.browserDownloadAsync=void 0,e.saveOnlyAsync=void 0,e.renderBrowserDownloadInstructions=void 0,e.renderUsbPairDialog=void 0,e.renderIncompatibleHardwareDialog=void 0,e.showUploadInstructionsAsync=void 0,e.saveProjectAsync=void 0,e.electronDeployAsync=void 0,e.electronFileDeployAsync=void 0,e.webUsbPairDialogAsync=void 0,e.onTutorialCompleted=void 0,e.perfMeasurementThresholdMs=void 0,e.onPerfMilestone=void 0,e.onPerfMeasurement=void 0,e.workspaceLoadedAsync=void 0,e.getDownloadMenuItems=void 0,e.notifyProjectCompiled=void 0,e.notifyProjectSaved=void 0,e.onDownloadButtonClick=void 0,e.getDefaultProjectName=void 0,e.onMarkdownActivityLoad=void 0}(e.commands||(e.commands={}))}(pxt||(pxt={})),function(e){function t(t){const n=e.toolbox.convertColor(t),i=parseInt(n.slice(1,3),16)/255,s=parseInt(n.slice(3,5),16)/255,r=parseInt(n.slice(5,7),16)/255;return.2126*(i<=.03928?i/12.92:Math.pow((i+.055)/1.055,2.4))+.7152*(s<=.03928?s/12.92:Math.pow((s+.055)/1.055,2.4))+.0722*(r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4))}function n(e,n){return(t(e)+.05)/(t(n)+.05)}function i(e){const t=(1-Math.abs(2*e.l-1))*e.s,n=e.h/60,i=t*(1-Math.abs(n%2-1));let r;void 0===e.h?r=[0,0,0]:n<=1?r=[t,i,0]:n<=2?r=[i,t,0]:n<=3?r=[0,t,i]:n<=4?r=[0,i,t]:n<=5?r=[i,0,t]:n<=6&&(r=[t,0,i]);let a=e.l-.5*t;return o=Math.round(255*(r[0]+a)),l=Math.round(255*(r[1]+a)),c=Math.round(255*(r[2]+a)),"#"+s(o)+s(l)+s(c);var o,l,c}function s(e){return("0"+e.toString(16)).slice(-2)}e.getWhiteContrastingBackground=function(t){if(n("#ffffff",t)>=4.5)return t;const s=function(t){const n=e.toolbox.convertColor(t),i=parseInt(n.slice(1,3),16)/255,s=parseInt(n.slice(3,5),16)/255,r=parseInt(n.slice(5,7),16)/255,a=Math.max(Math.max(i,s),r),o=Math.min(Math.min(i,s),r),l=a-o;let c;0===l?c=0:a===i?c=((s-r)/l%6+6)%6:a===s?c=(r-i)/l+2:a===r&&(c=(i-s)/l+4);let u=(o+a)/2,d=0===l?0:l/(1-Math.abs(2*u-1));return{h:60*c,s:d,l:u}}(t);let r=s.l-.05;for(;r>0;){const e=i({h:s.h,s:s.s,l:r});if(n("#ffffff",e)>=4.5)return e;r-=.05}return e.warn(`Couldn't find a contrasting background for color ${t}`),t},e.contrastRatio=n}(pxt||(pxt={})),function(e){e.TutorialInfoDbSetAsync="tutorial info db setAsync",e.ReloadAppTargetVariant="reloadAppTargetVariant",e.Sha256Buffer="sha256buffer",e.WebworkerRecvHandler="webworker recvHandler",e.NetworkRequest="network.request"}(Measurements||(Measurements={})),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 m=JSON.stringify(c),g=o[m];if(g){e.debug("Using cached extinfo");const t=n.flatClone(g);return t.disabledDeps=h,t}e.debug("Generating new extinfo");const b=pxtc.emptyExtInfo();b.disabledDeps=h;let y=e.appTarget.compileService;y||(y={gittag:"none",serviceId:"nocompile"}),y=n.clone(y);let v=t.getTargetOptions();v||(v={isNative:!1,hasHex:!1,switches:{}});const w=!!y.platformioIni,A="codal"==y.buildEngine||"dockercodal"==y.buildEngine,k="dockermake"==y.buildEngine||"dockercross"==y.buildEngine,T="dockerespidf"==y.buildEngine,x=!(w||A||k||T),E=v.nativeType==pxtc.NATIVE_TYPE_VM;w?d="/src/":A||k?d="/pxtapp/":T&&(d="/main/");let C="// Configuration defines\n",I="\nPXT_SHIMS_BEGIN\n",S="",N="",U='#include "pxt.h"\n',O="",_=e=>O+=` ${L}(${P}): ${e}\n`,P=0,L="",D=r("namespace"),$=r("declare namespace"),M=r("declare namespace"),R="",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,`${u} 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 q(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 V=0,J=!1,W="",K="",Y="",X=!1;function Q(){$.setNs(""),$.write(""),$.write(""),(Y||K)&&($.write(K),$.write(Y),Y="",K="")}function Z(e,t){let r;W="",K="",Y="",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":case"ImageLiteral_":return"T";case"bool":return"B";case"double":return"D";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),P=0,J=!1,V=0,M.setNs(""),$.setNs(""),e.split(/\r?\n/).forEach(e=>{++P;let d=q(e);!function(e){let t=q(e);if(J&&t.indexOf("}")>=0&&(J=!1,M.write("}")),!J)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),V=a(s),null==V&&_("cannot determine value of "+t)}else V++,s=V+"";M.write(` ${H(e)} = ${s},${r}`)}else M.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],J=!0,V=-1,M.write(""),M.write(""),(Y||K)&&(M.write(K),M.write(Y),Y="",K=""),M.write(`declare const enum ${H(p)} ${f}`),j[p]=!0,t||(D.setNs(W),D.write(`enum ${h[2]} : int;`))),function(e){return!(!J&&(/^\s*\/\*\*/.test(e)?(X=!0,K=e+"\n",/\*\//.test(e)&&(X=!1),0):X?(K+=e+"\n",/\*\//.test(e)&&(X=!1),0):!/^\s*\/\/%/.test(e)||(Y+=e+"\n",0)))}(e))return;/^typedef.*;\s*$/.test(e)&&(D.setNs(W),D.write(e));let m=/^\s*namespace\s+(\w+)/.exec(e);if(!m){if(m=/^PXT_ABI\((\w+)\)/.exec(e),m&&!E&&(I+=`PXT_FNPTR(::${m[1]}),\n`,N+=`extern "C" void ${m[1]}();\n`,b.functions.push({name:m[1],argsFmt:[],value:0})),m=/^\s*PXT_EXPORT\(([:\&\w]+)\)/.exec(e),m&&(b.vmPointers||(b.vmPointers=[]),b.vmPointers.push(m[1])),m=/^#define\s+PXT_COMM_BASE\s+([0-9a-fx]+)/.exec(e),m&&(b.commBase=parseInt(m[1])),m=/^\s*(\w+)([\*\&]*\s+[\*\&]*)(\w+)\s*\(([^\(\)]*)\)\s*(;\s*$|\{|$)/.exec(e),Y&&m){r=null;let e=pxtc.parseCommentString(Y);W||_("missing namespace declaration");let o=(m[1]+m[2]).replace(/\s+/g,""),d=m[3],h=m[4];Y=Y.trim().replace(/ \w+\.defl=\w+/g,"");let p=[u(o)],f=[],g=h.split(/,/).filter(e=>!!e).map(t=>{let i=function(e,t){t=t.trim();let i=/(.*)=\s*(-?\w+)$/.exec(t),s="",r="";if(i&&(s=i[2],r="?",t=i[1].trim()),i=/^(.*?)(\w+)$/.exec(t),!i)return _("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),Y+=` ${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(K)if($.setNs(H(W)),$.write(""),$.write(K),/ImageLiteral/.test(m[4])&&!/imageLiteral=/.test(Y)&&(Y+=" imageLiteral=1"),Y+=` shim=${y.name}`,$.write(Y),d=H(d),l()){let e=(g[0]||"").replace(/^.*:\s*/,"").trim();e.toLowerCase()!=l().toLowerCase()&&_(i("Invalid first argument; should be of type '{0}', but is '{1}'",l(),e)),g.shift(),0==g.length&&/\bproperty\b/.test(Y)?$.write(`${d}: ${c(o)};`):$.write(`${d}(${g.join(", ")}): ${c(o)};`)}else $.write(`function ${d}(${g.join(", ")}): ${c(o)};`);if(K="",Y="",t||(D.setNs(W),D.write(`${o} ${d}(${h});`)),b.functions.push(y),x)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,S+=`\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&&(S+=" auto prevSP = ctx->sp;\n"),S+=a,r&&(S+=" if (panicCode) { ctx->sp = prevSP; return; }\n");const o=`::${e.name}(${s.join(", ")})`;return"V"==e.argsFmt[0]?(S+=` ${o};\n`,S+=" ctx->r0 = NULL;\n"):"I"==e.argsFmt[0]?S+=` ctx->r0 = fromInt(${o});\n`:"B"==e.argsFmt[0]?S+=` ctx->r0 = fromBool(${o});\n`:S+=` ctx->r0 = (TValue)${o};\n`,r&&(S+=" ctx->sp = prevSP;\n"),i>1&&(S+=` ctx->sp += ${i-1};\n`),S+="}\n",n}(y,f),t=y.argsFmt.length-1;I+=`{ "${y.name}", (OpFun)(void*)${e}, ${t} },\n`}}else I+="PXT_FNPTR(::"+y.name+"),\n";return}if(m=/^\s*extern const (\w+) (\w+);/.exec(e),Y&&m){let e={name:W+"::"+m[2],argsFmt:[],value:null};return b.functions.push(e),E||(I+="PXT_FNPTR(&::"+e.name+"),\n"),void(Y="")}if(m=/^\s*(\w+)\s+(\w+)\s*;/.exec(e),Y&&m){let e=pxtc.parseCommentString(Y);e.indexedInstanceNS&&(r=e,$.setNs(e.indexedInstanceNS),o=0);let t=m[1],n=m[2];if(r)return Y=Y.trim(),Y+=` fixedInstance shim=${r.indexedInstanceShim}(${o++})`,$.write(""),$.write(K),$.write(Y),$.write(`const ${n}: ${c(t)};`),K="",void(Y="")}return Y&&e.trim()?(_("declaration not understood: "+e),Y="",void(K="")):void 0}if(W=m[1],l()){Q();let e=l();$.setNs(W,`declare interface ${e} {`)}else(Y||K)&&(Q(),$.setNs(H(W)),M.setNs(H(W)))})}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(A&&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(x&&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){O="",se(s),s==t?(e=!0,$.clear(),M.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&&(U+=`#include "${x?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)),L=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}}O&&(R+=i("Extension {0}:\n",s.id)+O)}e||($.clear(),M.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))}R&&n.userError(R),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}),!x&&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(k){let e={name:"pxt-app",private:!0,dependencies:b.npmDependencies};b.generatedFiles["/package.json"]=JSON.stringify(e,null,4)+"\n"}else if(T){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(A){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"]}`),b.codal=r}else if(w){const e=y.platformioIni.slice();e.push("lib_deps ="),n.iterMap(b.platformio.dependencies,(t,n)=>{let i=/[@#\/]/.test(n)?n:t+"@"+n;e.push(" "+i)}),b.generatedFiles["/platformio.ini"]=e.join("\n")+"\n"}else{b.yotta.config=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"]=U+D.finish()+N+S+I+"\nPXT_SHIMS_END\n",b.generatedFiles[d+"pxtconfig.h"]=C,e.debug(`pxtconfig.h: ${b.generatedFiles[d+"pxtconfig.h"]}`),x&&(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:x?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=$.finish(),b.enumsDTS=M.finish(),Object.keys(o).length>10&&(o={}),o[m]=b,b},t.unpackSourceFromHexFileAsync=function(t){if(t)return e.Util.fileReadAsBufferAsync(t).then(e=>h(new Uint8Array(e)))},t.unpackSourceFromHexAsync=h}(e.cpp||(e.cpp={}))}(pxt||(pxt={})),function(e){!function(t){const n={};let i,s={};function r(s){return n.hasOwnProperty(s.sha)||(n[s.sha]=function(n){let s="";return t.showLoading(e.U.lf("Compiling (this may take a minute)...")),e.tickEvent("cppcompile.start"),function(t){if(t.skipCloudBuild)return Promise.resolve({hex:["SKIP"]});if(e.webConfig&&e.webConfig.isStatic)return e.Util.requestAsync({url:`${e.webConfig.cdnUrl}hexcache/${t.sha}.hex`}).then(t=>{if(t.text){const e={enums:[],functions:[],hex:t.text.split(/\r?\n/)};return Promise.resolve(e)}return e.log("Hex info not found in bundled hex cache"),Promise.resolve()}).catch(t=>(e.log("Error fetching hex info from bundled hex cache"),Promise.resolve()));if(!e.Cloud.localToken||!window||!e.BrowserUtils.isLocalHost())return Promise.resolve(void 0);return(n="compile/"+t.sha,e.Cloud.localRequestAsync(n,i).then(e=>e.json)).then(e=>e&&!e.notInOfflineCache&&e.hex?(e.hex=e.hex.split(/\r?\n/),e):Promise.resolve(void 0)).catch(e=>Promise.resolve(void 0));var n,i}(n).then(r=>r?(e.tickEvent("cppcompile.cachehit"),r):function(){if(i)return i;{let t=e.getOnlineCdnUrl();if(t)return i=Promise.resolve(t);const n=e.webConfig&&e.webConfig.isStatic;return i=e.Cloud.privateGetAsync("clientconfig",n).then(e=>e.primaryCdnUrl)}}().then(t=>(s=t+"/compile/"+n.sha,e.U.httpGetTextAsync(s+".hex"))).then(e=>e,t=>e.Cloud.privatePostAsync("compile/extension",{data:n.compileData},!0).then(t=>new Promise((n,i)=>{let r=0;const 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(t){e.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(t,n,i){return t.cacheGetAsync(n).then(s=>{let r;try{r=JSON.parse(s||"[]")}catch(i){return e.error("invalid cache entry, clearing entry"),t.cacheStoreAsync(n,"[]")}return r[0]!=i?(r=r.filter(e=>e!=i),r.unshift(i),t.cacheStoreAsync(n,JSON.stringify(r))):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(t){e.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){t.KEY_VARIABLE="CROWDIN_KEY",t.testMode=!1,t.setTestMode=function(){e.crowdin.testMode=!0,e.log("CROWDIN TEST MODE - files will NOT be uploaded")},t.inContextLoadAsync=function(t){const n=document.createElement("input");n.type="text",n.setAttribute("class","hidden"),n.value=t;let i=new Promise((i,s)=>{const r=new MutationObserver(()=>{if(t==n.value)return;const s=e.Util.rlf(n.value);n.remove(),r.disconnect(),i(s)});r.observe(n,{attributes:!0})});return document.body.appendChild(n),i}}(e.crowdin||(e.crowdin={}))}(pxt||(pxt={})),function(e){!function(t){function n(e,t){if(!e)return[];if(t){const t=[];let n=0;for(let i=0;i<e.length;i++){"\n"===e.charAt(i)&&(t.push(e.substring(n,i+1)),n=i+1)}return t.push(e.substring(n)),t}return e.split(/\r?\n/)}let i;function s(e,t,s={}){s.ignoreWhitespace&&(e=e.replace(/[\r\n]+$/,""),t=t.replace(/[\r\n]+$/,""));const r=n(e,!0),a=n(t,!0),o=Math.min(s.maxDiffSize||1024,r.length+a.length);if(0==o)return[];const l=r.length>65520?Uint32Array:Uint16Array,c={};let u=0;const d=p(r),h=p(a);function p(e){const t=new l(e.length);let n=0;for(let i of e)s.ignoreWhitespace&&(i=i.replace(/\s+$/g,"").replace(/^\s+/g,"")),c.hasOwnProperty(i)?t[n]=c[i]:(++u,t[n]=u,c[i]=u),n++;return t}const f=new l(2*o+1);let m=-1;for(let e=0;e<=o;e++)null!=w(e,f)&&(m=e);if(-1==m)return null;const g=[];let b=null;for(let e=0;e<=m;e++){const t=g.length?g[g.length-1].slice(0):new l(2*m+1);if(g.push(t),b=w(e,t),null!=b)break}const y=[];let v=b;for(let e=g.length-1;e>=0;e--){const t=g[e];let n=0,s=0;v==-e||v!=e&&t[o+v-1]<t[o+v+1]?(s=v+1,n=t[o+s]):(s=v-1,n=t[o+s]+1);let l=n-v;for(let e=t[o+v]-n-1;e>=0;--e)y.push([i.Unchanged,a[l+e]]);s==v-1?y.push([i.Deleted,r[n-1]]):l>0&&y.push([i.Added,a[l-1]]),v=s}return y.reverse(),y;function w(e,t){for(let n=-e;n<=e;n+=2){let i=0;i=n==-e||n!=e&&t[o+n-1]<t[o+n+1]?t[o+n+1]:t[o+n-1]+1;let s=i-n;for(;i<d.length&&s<h.length&&d[i]==h[s];)i++,s++;if(t[o+n]=i,i>=d.length&&s>=h.length)return n}return null}}function r(e,t,n={}){const r=s(e,t,n);if(n.context==1/0||n.full)return r.map(a);let o=1,l=1,c=0;const u=[],d=n.context||3;for(;c<r.length;){let e=c;for(;e<r.length&&r[e][0]===i.Unchanged;)e++;if(e==r.length)break;const t=e-d,n=t-c;n>0&&(o+=n,l+=n,c=t);const s=u.length,h=o,p=l;u.push("@@");let f=c,m=0;for(;f<r.length;){if(r[f][0]===i.Unchanged){if(m++,m>2*d+2){f-=d+2;break}}else m=0;f++}for(;c<f;){u.push(a(r[c]));switch(r[c][0]){case i.Deleted:o++;break;case i.Added:l++;break;case i.Unchanged:o++,l++}c++}u[s]=`@@ -${h},${o-h} +${p},${l-p} @@`}return u}function a([e,t]){let n;return n=e===i.Added?"+ ":e===i.Deleted?"- ":" ",n+t.replace(/\r?\n/,"")}function o(e){return n(e).map(e=>e.replace(/;\s*$/,"")).join("\n")}function l(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,function(e){e[e.Added=1]="Added",e[e.Deleted=-1]="Deleted",e[e.Unchanged=0]="Unchanged"}(i||(i={})),t.compute=s,t.computeFormattedDiff=r,t.computePatch=function(e,t){const n=s(e,t,{full:!0,maxDiffSize:2048});if(!n)return[{start1:0,length1:e.length,diffs:[[i.Added,t]]}];const r=function(e){const t=[];let n="",s="",r="",a=i.Unchanged;const o=()=>{t.push({start1:n.length,length1:r.length,diffs:[[i.Added,s]]}),n+=s,s="",r=""};for(let t=0;t<e.length;t++){const[l,c]=e[t];l==i.Unchanged?(a!==i.Unchanged&&o(),n+=c):l===i.Added?s+=c:l===i.Deleted&&(a===i.Added&&o(),r+=c),a=l}return a!==i.Unchanged&&o(),t}(n);return r},t.applyPatch=function(e,t){let n=e;for(const e of t){const t=e.diffs.filter(e=>e[0]!==i.Deleted).map(e=>e[1]).join("");n=n.substring(0,e.start1)+t+n.substring(e.start1+e.length1)}return n},t.diff3=function(t,r,a,o,l){const c=b(t),u=b(a);if(!c||!u)return;const d=n(t),h=n(a);let p=0,f=[],m=0,g=0;for(let t=0;t<c.length-1;)if(c[t]==m&&u[t]==g)f.push(d[m]),m++,g++,t++;else{let n=!0,i=!0,s=t;for(;s<c.length&&(c[s]!=m+s-t&&(n=!1),u[s]!=g+s-t&&(i=!1),null==c[s]||null==u[s]);)s++;if(e.U.assert(s<c.length),n)for(;g<u[s];)f.push(h[g++]);else if(i)for(;m<c[s];)f.push(d[m++]);else if(d.slice(m,c[s]).join("\n")==h.slice(g,u[s]).join("\n"))for(;m<c[s];)f.push(d[m++]);else{for(p++,f.push("<<<<<<< "+o);m<c[s];)f.push(d[m++]);for(f.push("=======");g<u[s];)f.push(h[g++]);f.push(">>>>>>> "+l)}t=s,m=c[s],g=u[s]}return{merged:f.join("\n"),numConflicts:p};function b(t){const n=s(r,t,{context:1/0});if(!n)return;const a=[];let o=0,l=0;for(let t of n)t[0]==i.Added?o++:t[0]==i.Deleted?(a[l]=null,l++):t[0]==i.Unchanged?(a[l]=o,o++,l++):e.U.oops();return a.push(o+1),a}},t.removeTrailingSemiColumns=o,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$/,""),s=n[1].replace(/^\n/,"");return t&&t.removeTrailingSemiColumns&&(i=o(i),s=o(s)),{fileA:i,fileB:s}},t.parseDiffMarker=l,t.render=function(t,n,i={}){const s=r(t,n,i);if(!s)return e.dom.el("div",null,pxtc.Util.lf("Too many differences to render diff."));const a={"@":"diff-marker"," ":"diff-unchanged","+":"diff-added","-":"diff-removed"};let o=0,c=0,u="";const d=e.dom.el("tbody"),h=e.dom.el("table",{class:"diffview "+(i.update?"update":"")},d);let p=null;return s.forEach((t,n)=>{const h=l(t);h?(o=h.oldStart,c=h.newStart):("+"!=t[0]&&o++,"-"!=t[0]&&c++);const f=s[n+1]?s[n+1][0]:"",m=s[n+2]?s[n+2][0]:"",g=t.slice(2);let b=e.dom.el("code",null,g);if(p)b=p,p=null;else if(!("-"!=t[0]||" "!=u&&"@"!=u||"+"!=f||" "!=m&&"@"!=m&&""!=m)){const i=function(t,n){const i=r(t.split("").join("\n"),n.split("").join("\n"),{context:1/0});if(!i)return{a:e.dom.el("div",{class:"inline-diff"},e.dom.el("code",null,t)),b:e.dom.el("div",{class:"inline-diff"},e.dom.el("code",null,n))};const s=[],a=[];for(let t=0;t<i.length;){let n=t;const r=i[t][0];for(;i[n]&&i[n][0]==r;)n++;const o=i.slice(t,n).map(e=>e.slice(2)).join("");" "==r?(s.push(e.dom.el("code",{class:"ch-common"},o)),a.push(e.dom.el("code",{class:"ch-common"},o))):"-"==r?s.push(e.dom.el("code",{class:"ch-removed"},o)):"+"==r?a.push(e.dom.el("code",{class:"ch-added"},o)):e.Util.oops(),t=n}return{a:e.dom.el("div",{class:"inline-diff"},s),b:e.dom.el("div",{class:"inline-diff"},a)}}(t.slice(2),s[n+1].slice(2));b=i.a,p=i.b}if(u=t[0],i.hideMarkerLine&&"@"==u||i.hideRemoved&&"-"==u)return;const y="@"==u,v=`${a[u]}`;d.appendChild(e.dom.el("tr",{class:v},[!i.hideLineNumbers&&e.dom.el("td",{class:"line-a","data-content":o}),!i.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)),!i.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",hideToolbox:"\x3c!-- hideToolbox --\x3e",hideIteration:"\x3c!-- iter --\x3e",codeStart:"\x3c!-- start --\x3e",codeStop:"\x3c!-- stop --\x3e",autoOpen:"\x3c!-- autoOpen --\x3e",autoexpandOff:"\x3c!-- autoexpandOff --\x3e",preferredEditor:"\x3c!-- preferredEditor --\x3e"};function l(e,t,n){return e.split(t).join(n)}function c(e){return e=l(e,"&","&"),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=()=>{const e=null===globalThis||void 0===globalThis?void 0:globalThis.marked;if(e)return e;if("undefined"==typeof require)return;const t=e=>{var t;try{const n=require(e);return(null==n?void 0:n.marked)?n.marked:(null===(t=null==n?void 0:n.default)||void 0===t?void 0:t.marked)?n.default.marked:(null==n?void 0:n.default)?n.default:n}catch(e){return}};return t("marked/lib/marked.umd.js")||t("marked")},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 g(n,i,["ITEMS"])},m=[{name:lf("Docs"),href:"/docs"}];const b=e.TOC||p.TOC||[];let y=[],v=t=>{for(let e of t.subitems||[])if(v(e))return y.push(t),!0;return!(!e.filepath||!t.path||e.filepath!=t.path)&&(y.push(t),!0)};b.forEach(v);let w=(t,n)=>{let i=c.item,s={NAME:t.name};return t.path&&!/^(https?:|\/)/.test(t.path)?h("Invalid link: "+t.path):(/^\//.test(t.path)&&e.versionPath&&(t.path=`/${e.versionPath}${t.path}`),s.LINK=t.path,y.indexOf(t)>=0?(s.ACTIVE="active",s.EXPANDED="true",m.push({name:t.name,href:t.path})):s.EXPANDED="false",t.subitems&&t.subitems.length>0?(i=c["toc-dropdown"]?""!==t.name?c["toc-dropdown"]:c["toc-dropdown-noLink"]:0==n?""!==t.name?c["top-dropdown"]:c["top-dropdown-noHeading"]:1==n?c["inner-dropdown"]:c["nested-dropdown"],s.ITEMS=t.subitems.map(e=>w(e,n+1)).join("\n")):/^-+$/.test(t.name)&&(i=c.divider),g(i,s,["ITEMS"]))};d.menu=(p.docMenu||[]).map(e=>f(e,0)).join("\n"),d.TOC=b.map(e=>w(e,0)).join("\n"),p.appStoreID&&(d.appstoremeta=`<meta name="apple-itunes-app" content="app-id=${n.htmlEscape(p.appStoreID)}"/>`);let A="";m.length>1&&(A=`\n <nav class="ui breadcrumb" aria-label="${lf("Breadcrumb")}">\n ${m.map((e,t)=>`<a class="${t==m.length-1?"active":""} section"\n href="${u(e.href)}" aria-current="${t==m.length-1?"page":""}">${u(e.name)}</a>`).join('<i class="right chevron icon divider"></i>')}\n </nav>`),d.breadcrumb=A,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 k=p.docsLogo&&n.htmlEscape(p.docsLogo),T=(p.organizationWideLogo||p.organizationLogo)&&n.htmlEscape(p.organizationWideLogo||p.organizationLogo),x=p.organizationLogo&&n.htmlEscape(p.organizationLogo);d.targetlogo=k?`<img aria-hidden="true" role="presentation" class="ui ${p.logoWide?"small":"mini"} image" src="${k}" />`:"",d.orglogo=T?`<img aria-hidden="true" role="presentation" class="ui image" src="${T}" />`:"",d.orglogomobile=x?`<img aria-hidden="true" role="presentation" class="ui image" src="${x}" />`:"";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"),S=`\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=S;const N=`\n <a id="togglesidebar" class="launch icon item" tabindex="0" title="Side menu" aria-label="${lf("Side menu")}" role="menuitem" aria-expanded="false">\n <i class="content icon"></i>\n </a>\n `;d.sidebarToggle=N;const U=["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=U[0],d.searchBar2=U[1];let O="";p.accentColor&&(O+=`\n.ui.accent { color: ${p.accentColor}; }\n.ui.inverted.accent { background: ${p.accentColor}; }\n`),d.targetstyle=O,d.tocclass=p.lightToc?"lighttoc":"inverted";for(let e of Object.keys(p)){let t=p[e];void 0===d[e]&&"string"==typeof t&&(d[e]=t)}e.finish=()=>g(e.html,d,["body","menu","accMenu","TOC","prev","next","printBtn","breadcrumb","targetlogo","orglogo","orglogomobile","github","JSON","appstoremeta","sidebarToggle","searchBar1","searchBar2"])}function f(e,t={}){e.image=function(e){var t;const n=e.href||"",i=e.title||"",s=e.text||"";if(n.startsWith("youtube:")){const e=n.split(":").pop();return`<div class="tutorial-video-embed" data-youtube="${encodeURIComponent(e)}" title="${s}"></div>`}{let e=`<img class="ui image" src="${n}" alt="${s}"`;return i&&(e+=` title="${i}"`),e+=' loading="lazy"',e+=(null===(t=this.options)||void 0===t?void 0:t.xhtml)?"/>":">",e}},e.listitem=function(e){const t=this.parser.parse(e.tokens,!!e.loose);return e.task?`<li class="${e.checked?"checked":"unchecked"}">${t}</li>\n`:`<li>${t}</li>\n`},e.heading=function(e){var t;let n=this.parser.parseInline(e.tokens).trim(),i="";const s=/(.*)#([\w\-]+)\s*$/.exec(e.text||"");s&&(i=s[2],n=n.replace(/#([\w\-]+)\s*$/,"").trim()),n=n.replace(/@(fullscreen|unplugged|showdialog|showhint)/gi,"").trim();const r=n.match(/\{([\s\S]+)\}/);if(r&&(n=r[1].trim()),!i){i=(e=>{let t;do{t=e,e=e.replace(/<[^>]+>/g,"")}while(e!==t);return e})(n).toLowerCase().replace(/[^\w]+/g,"-")}const a=(null===(t=this.options)||void 0===t?void 0:t.headerPrefix)||"";return`<h${e.depth} id="${a}${i}">${n}</h${e.depth}>`},e.code=function(e){const t=c(("string"==typeof(null==e?void 0:e.lang)?e.lang.trim():"").toLowerCase()),n="string"==typeof(null==e?void 0:e.text)?e.text:"";return`<pre><code${t?` class="lang-${t}"`:""}>${!1!==(null==e?void 0:e.escaped)?n:c(n)}</code></pre>`};const n=null==t?void 0:t.versionPath,i=e.link?e.link.bind(e):void 0;e.link=function(e){const t=e.href||"",s=/^[/#]/.test(t),r=s&&n?`/${n}${t}`:t,a=Object.assign(Object.assign({},e),{href:r}),o=i?i(a):`<a href="${a.href}">${this.parser.parseInline(a.tokens||[])}</a>`,l=[];s||l.push('target="_blank"'),l.push('rel="nofollow noopener"');const c=l.join(" ");return o.replace(/^<a /,`<a ${c} `)}}function m(e,t){return e.replace(/<!--\s*@(ifn?def)\s+(\w+)\s*-->([^]*?)<!--\s*@endif\s*-->/g,(e,n,i,s)=>"ifdef"==n&&t[i]||"ifndef"==n&&!t[i]?`\x3c!-- ${n} ${i} --\x3e${s}\x3c!-- endif --\x3e`:`\x3c!-- ${n} ${i} endif --\x3e`)}function g(e,t,i=[]){return e?e.replace(/@(\w+)@/g,(e,s)=>{let r=n.lookup(t,s)||"";return r+="",i.indexOf(s)<0&&(r=u(r)),r}):""}t.prepTemplate=p,t.setupRenderer=f,t.renderConditionalMacros=m,t.renderMarkdown=function(e){let s=!0;e.pubinfo||(s=!1,e.pubinfo={});let r=e.pubinfo;if(e.theme||(e.theme={}),delete e.pubinfo.private,r.time){let e=parseInt(r.time);r.timems||(r.timems=1e3*e+""),r.humantime||(r.humantime=n.isoTime(e))}r.name&&(r.dirname=r.name.replace(/[^A-Za-z0-9_]/g,"-"),r.title=r.name),s&&(r.JSON=JSON.stringify(r,null,4).replace(/</g,"\\u003c"));let 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=m(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};if(p(o),i||(i=t.requireMarked()),!i)return o.finish?o.finish():o.html;const l=new i.Renderer;f(l,{versionPath:o.versionPath});let c=t.requireDOMSanitizer();i.setOptions({renderer:l,async:!1,gfm:!0,tables:!0,breaks:!1,pedantic:!1});let b=e.markdown;e.repo&&(b+=`\n\`\`\`package\n${e.repo.name.replace(/^pxt-/,"")}=github:${e.repo.fullName}#${e.repo.tag||"master"}\n\`\`\`\n`),b=b.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}),b=b.replace(/@([a-z]+)@/gi,(t,i)=>{let s=r[i];return!s&&e.throwOnError&&n.userError(`unknown macro ${i}`),s||"unknown macro"});let v=i.parse(b);const w=(e,t="")=>"string"==typeof e?e:e&&"function"==typeof e.toString?e.toString():t;let A=v;c&&(A=c(v)),v=w(A,w(v,"")),v=v.replace(/<br\s*\/>/gi,"<br/>"),v=v.replace(/(<img [^>]* src=")\/docs\/static\/([^">]+)"/g,(e,t,n)=>t+"/static/"+n+'"');let k="",T=0;function x(e,t,n){let i=n;return e<=T&&(i=k+i,k="",T=0),i}if(v=v.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]:"";d=u(d),c=u(c);const p=parseInt(i,10);if(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(p,0,g(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(p,0,e[0].replace("@ARGS@",d));k=e[1];let i=t.match(/data-[^>\s]+/gi);return i&&i.indexOf("data-inferred")>=0&&(T=p),n}return e.throwOnError&&n.userError(`Unknown box: ~ ${c}`),h(`Unknown box: ~ ${c}`)}}return x(p,0,t)}),k&&(v+=k),!r.title){let e=/<h1[^<>]*>([^<>]+)<\/h1>/.exec(v);e&&(r.title=u(e[1]))}if(!r.description){let e=/<p>([^]+?)<\/p>/.exec(v);e&&(r.description=u(e[1]))}const E=/<div class="ui embed mdvid"[^<>]+?data-placeholder="([^"]+)"[^>]*\/?>/i.exec(v)||/<img class="ui [^"]*image" src="([^"]+)"[^>]*\/?>/i.exec(v);E&&(r.cardLogo=u(E[1])),r.twitter=u(e.theme.twitter||"@msmakecode");let C={main:""};v=v.replace(/<!-- BEGIN-ASIDE (\S+) -->([^]*?)<!-- END-ASIDE -->/g,(e,t,i)=>{let s=n.lookup(C,t);return C[t]=(s||"")+i,"\x3c!-- aside --\x3e"}),v=v.replace(/\n<\/code>/g,"</code>"),C.main=v;let I=(e,t)=>g(o.boxes[e]||"@BODY@",{BODY:t},["BODY"]);v="";for(let e of Object.keys(C))v+=I(e+"-container",C[e]);r.body=v,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(t){if(!t)return null;const n=e.docs.requireMarked();if(!n)return null;const i={renderer:new n.Renderer,gfm:!0,tables:!1,breaks:!1,pedantic:!1,smartLists:!1,smartypants:!1},s=n.lexer(t,i),r=e=>(e||"").replace(/\.md$/i,""),a=e=>{if(!e)return"";if("string"==typeof e.text)return e.text.trim();if(e.tokens&&e.tokens.length)for(const t of e.tokens){const e=a(t);if(e)return e}return""},o=e=>{const t={name:"",path:"",subitems:[]};let n="";const i=e=>{if(e)for(const s of e)if(s)switch(s.type){case"link":t.name||(t.name=(s.text||"").trim()),t.path||(t.path=r(s.href));break;case"text":case"codespan":case"strong":case"em":case"paragraph":s.tokens&&s.tokens.length?i(s.tokens):n||"string"!=typeof s.text||(n=s.text.trim());break;default:s.tokens&&s.tokens.length&&i(s.tokens)}};return i(null==e?void 0:e.tokens),t.name||(n=n||a(e),n||"string"!=typeof(null==e?void 0:e.text)||(n=e.text.split(/\n/)[0].trim()),t.name=n||""),t.path=r(t.path),t},l=(e,t)=>{if(e&&e.length)for(const n of e){const e=o(n),i=((null==n?void 0:n.tokens)||[]).filter(e=>"list"===(null==e?void 0:e.type));for(const t of i)l((null==t?void 0:t.items)||[],e.subitems);(e.name||e.subitems.length)&&t.push(e)}},c=[];for(const e of s)"list"===(null==e?void 0:e.type)&&Array.isArray(e.items)&&l(e.items,c);const u=e=>e.filter(e=>!!e.name||e.subitems&&e.subitems.length).map(e=>({name:e.name,path:e.path,subitems:e.subitems?u(e.subitems):[]}));let d=u(c);return d.length?d:null},t.visitTOC=function(e,t){e.forEach(function(e){t(e),e.subitems&&e.subitems.forEach(t)})};let A=!1;function k(t,i){if(A||function(){function t(t,n,i){let s=k(t,n).trim();if(s!=(i=i.trim()))throw e.log(`*** Template:\n${t}\n*** Input:\n${n}\n*** Expected:\n${i}\n*** Output:\n${s}`),new Error("augment docs test fail")}A=!0;let n="\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",i="\n# @extends\n# #ex2\nMy example\n## See Also These! #also\nMy links\n",s="\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",r="\n# @extends\n### #ex\nFoo\n#### Example 1\nEx1\n#### Example 2x #ex2\nEx2\n## See Also These! #also\nMy links\n",a="\n# T0\n## Examples #ex\nFoo\n#### Example 1\nEx1\n#### Example 2x #ex2\nEx2\n## See Also These! #also\nMy links\n";t(n,"",n),t(n," ",n),t(n,i,s),t(n,r,a)}(),!i)return t;let s=w(t,null),r=w(i,s),a={},o={};for(let e of r.children)n.assert(0==e.children.length),n.assert(!!e.id),a[e.id]=e.text;let l=e=>{e.id&&void 0!==a[e.id]&&(o[e.id]=!0,e.text=a[e.id],e.children=[]),e.children.forEach(l)};l(s);let c="",u=e=>{c+=e.text,e.children.forEach(u)};u(s);let d="",h=r.text.replace(/^\s*#+\s*@extends.*/gm,"").replace(/^\s*\n/gm,"");h.trim()&&(d+=h.trim()+"\n");for(let e of r.children)o[e.id]||(d+=e.text);return d&&(c+="## Couldn't apply replacement logic to:\n"+d),c}t.augmentDocs=k,t.hydrateYouTubeEmbeds=function(t,n){var i,s;for(const r of t.querySelectorAll(".tutorial-video-embed[data-youtube]")){const t=decodeURIComponent(r.getAttribute("data-youtube")),a=document.createElement("iframe");a.className="yt-embed";const o=`https://www.youtube-nocookie.com/embed/${t}`;let l=null!==(s=null===(i=e.appTarget.appTheme)||void 0===i?void 0:i.defaultLocale)&&void 0!==s?s:"en",c=new URL(o);n&&e.tickEvent("video.loaded",{player:"youtube",url:o}),c.searchParams.append("hl",l),c.searchParams.append("rel","0"),c.searchParams.append("modestbranding","1"),c.searchParams.append("autoplay","0"),c.searchParams.append("showinfo","0"),a.setAttribute("src",c.toString()),a.setAttribute("title",r.getAttribute("title")||""),a.setAttribute("frameborder","0"),a.setAttribute("allowFullScreen","true"),a.setAttribute("allow","autoplay; picture-in-picture"),a.setAttribute("sandbox","allow-same-origin allow-scripts"),r.textContent="",r.appendChild(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){const n=/```simtheme\s+([\s\S]*?)```/i.exec(t);return n?e.tutorial.parseSimThemeJson(n[1]):{}}function o(t){let n=e.Util.jsonTryParse(t);return n&&!Array.isArray(n)&&(n=[n]),(null==n?void 0:n.length)?n:(n=t.split(/^---$/gm).filter(e=>!!e).map(e=>{let t={};return e.replace(/^\s*(?:-|\*)\s+(\w+)\s*:\s*(.*)$/gm,(e,n,i)=>{if("flags"==n)t[n]=i.split(",");else if("otherAction"===n){const e=i.split(",").map(e=>null==e?void 0:e.trim());(t.otherActions||(t.otherActions=[])).push({url:e[0],editor:e[1],cardType:e[2]})}else t[n]=i;return""}),!!Object.keys(t).length&&t}).filter(e=>!!e),(null==n?void 0:n.length)?n:void 0)}function l(t){if(!t)return[];const n=[];let i,s=!1,r="";return t.split(/\r?\n/).forEach(t=>{if(/^## /.test(t))i=t.substr(2).trim();else if(/^(### ~ |```)codecard$/.test(t))s=!0;else if(/^(### ~|```)$/.test(t)){if(s=!1,i&&r){const t=o(r);(null==t?void 0:t.length)?n.push({name:i,cards:t}):e.log("invalid gallery format")}r="",i=void 0}else s&&(r+=t+"\n")}),n.forEach(t=>t.cards.forEach(t=>{if(t.otherActions&&!t.otherActions.length&&("tutorial"==t.cardType||"example"==t.cardType)){const n=["js"];e.appTarget.appTheme.python&&n.unshift("py"),t.otherActions=n.map(e=>({url:t.url,cardType:t.cardType,editor:e}))}})),n}t.parsePackagesFromMarkdown=n,t.parseFeaturesFromMarkdown=i,t.parseJResFromMarkdown=s,t.parseTemplateProjectJSON=r,t.parseSimThemeJSON=a,t.parseExampleMarkdown=function(t,o){if(!o)return;const l=/```(blocks?|typescript|python|spy|sim)\s+((.|\s)+?)\s*```/i.exec(o);if(!l)return;const c=n(o),u=l[1],d=l[2],h=i(o),p=s(o),f=a(o),m={name:t,filesOverride:{[e.MAIN_BLOCKS]:'<xml xmlns="http://www.w3.org/1999/xhtml"></xml>',["python"===l[1]?e.MAIN_PY:e.MAIN_TS]:d},dependencies:c,features:h,snippetType:u,source:d,simTheme:f};return m.filesOverride=Object.assign(Object.assign({},m.filesOverride),r(o)),p&&(m.filesOverride[e.TILEMAP_JRES]=p.jres,m.filesOverride[e.TILEMAP_CODE]=p.ts),m},t.parseCodeCards=o,t.parseCodeCardsHtml=function(t){let n,i=[];return Array.from(t.children).forEach(e=>{"UL"===e.tagName||"OL"===e.tagName?(n||(n={}),Array.from(e.querySelectorAll("li")).forEach(e=>{const t=e.innerText,i=/^\s*(\w+)\s*:\s*(.*)$/.exec(t);if(i){const e=i[1];n[e]=i[2].trim(),"flags"===e&&(n[e]=n[e].split(/,\s*/))}})):"HR"==e.tagName&&(n&&i.push(n),n=void 0)}),n&&i.push(n),0===i.length&&"CODE"===t.tagName&&(i=e.Util.jsonTryParse(t.textContent)),!!(null==i?void 0:i.length)&&i},t.parseGalleryMardown=l,t.loadGalleryAsync=function(t){return e.Cloud.markdownAsync(t).then(e=>l(e))},t.codeCardsToMarkdown=function(e){return`### ~ codecard\n\n${(e||[]).map(e=>Object.keys(e).filter(t=>!!e[t]).map(t=>"otherActions"===t?e[t].map(e=>`* otherAction: ${e.url}, ${e.editor||""}, ${e.cardType||""}`).join("\n"):`* ${t}: ${e[t]}`).join("\n")).join("\n\n---\n\n")}\n\n### ~\n`}}(e.gallery||(e.gallery={}))}(pxt||(pxt={})),function(e){e.GDBServer=class{constructor(t){this.io=t,this.q=new e.U.PromiseQueue,this.dataBuf="",this.numSent=0,this.pktSize=400,this.trace=!1,this.bmpMode=!0,this.targetInfo="",this.onEvent=e=>{},this.io.onData=e=>this.onData(e)}onData(t){for(this.dataBuf+=e.U.uint8ArrayToString(t);this.dataBuf.length>0;){let e=this.dataBuf[0];if("+"==e)this.dataBuf=this.dataBuf.slice(1);else if("$"==e||"%"==e){let t=this.decodeResp(this.dataBuf.slice(1));if(null==t)break;"$"==e?(this.io.sendPacketAsync(this.buildCmd("+")),this.onResponse?this.onResponse(t):this.numSent>0&&this.io.error("unexpected response: "+t)):this.onEvent(t)}else this.io.error("invalid character: "+e)}}buildCmd(t){if("+"==t)return e.U.stringToUint8Array(t);let n="";for(let e=0;e<t.length;++e){let i=t.charAt(e);"}"==i||"#"==i||"$"==i?(n+="}",n+=String.fromCharCode(32^i.charCodeAt(0))):n+=i}let i=0;t=n;for(let e=0;e<t.length;++e)i=i+t.charCodeAt(e)&255;return n="$"+t+"#"+("0"+i.toString(16)).slice(-2),e.U.stringToUint8Array(n)}decodeResp(e){let t="";for(let n=0;n<e.length;++n){let i=e[n];if("}"==i)++n,t+=String.fromCharCode(32^e.charCodeAt(n));else if("*"==i){++n;let i=e.charCodeAt(n)-29,s=t.charAt(t.length-1);for(;i-- >0;)t+=s}else{if("#"==i){return 2==e.slice(n+1,n+3).length?(this.dataBuf=e.slice(n+3),t):null}t+=i}}return null}sendCmdOKAsync(e){return this.sendCmdAsync(e,e=>"OK"==e)}error(e){this.io.error(e),this.io.disconnectAsync()}sendCmdAsync(t,n){this.numSent++;const i=this.buildCmd(t);return this.q.enqueue("one",()=>null===n?this.io.sendPacketAsync(i).then(()=>null):new Promise(s=>{this.onResponse=i=>{this.onResponse=null,this.trace&&e.log(`GDB: '${t}' -> '${i}'`),void 0===n||n(i)||this.error(`Invalid GDB command response: '${t}' -> '${i}'`),s(i)},this.io.sendPacketAsync(i)}))}sendRCmdAsync(t){return this.sendMCmdAsync("qRcmd,"+(n=t,e.U.toHex(e.U.stringToUint8Array(n))));var n}sendMCmdAsync(t){this.numSent++;const n=this.buildCmd(t);let i="";return this.q.enqueue("one",()=>new Promise(s=>{this.onResponse=n=>{var r;"OK"!=n&&"O"==n[0]?i+=(r=n.slice(1),e.U.uint8ArrayToString(e.U.fromHex(r))):("OK"!=n&&(i+=" - "+n),this.onResponse=null,this.trace&&e.log(`Final GDB: '${t}' -> '${i}'`),s(i))},this.io.sendPacketAsync(n)}))}write32Async(t,n){let i=new Uint8Array(4);return e.HF2.write32(i,0,n),this.writeMemAsync(t,i)}writeMemAsync(t,n){const i=this.pktSize/2-10;return e.U.assert(n.length<i),this.sendCmdOKAsync("M"+t.toString(16)+","+n.length.toString(16)+":"+e.U.toHex(n)).then(t=>{e.log(t)})}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)}function i(e){return!!t.forceProxy||!(t.token&&!e)&&n()}t.token=null,t.forceProxy=!1;const s=["microsoft"];t.shouldUseProxyForRepo=function(e){if(!t.token)return i();const n=S(e);if(!n)return i();const r=n.owner.toLowerCase();return!!s.some(e=>e===r)||i()};const r={};function a(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==D?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 o(e){return a({url:e,method:"GET"}).then(e=>e.json)}function l(t){return e.Cloud.apiRequestWithCdnAsync({url:"gh/"+t,forceLiveEndpoint:!0}).then(e=>e.json)}function c(t){e.log(`github proxy error: ${t.message}`),e.debug(t)}t.isOrgAsync=function(e){return a({url:`https://api.github.com/orgs/${e}`,method:"GET",allowHttpErrors:!0}).then(e=>200==e.statusCode)};class u{constructor(){this.latestVersions={},this.configs={},this.packages={}}proxyWithCdnLoadPackageAsync(t,n){const i=`${t}/${n}`;let s=this.packages[i];if(s)return e.debug(`github cache ${t}/${n}/text`),Promise.resolve(s);const r=S(t);return l(O(r.slug,n,r.fileName,"text")).then(e=>this.packages[i]={files:e})}cacheConfig(t,n){const i=e.Package.parseAndValidConfig(n);return this.configs[t]=i,e.U.clone(i)}async loadConfigAsync(t,i){i||(e.debug("dep: default to master branch"),i="master");const s=`${t}/${i}`;let r=this.configs[s];if(r)return e.debug(`github cache ${t}/${i}/config`),e.U.clone(r);if(n())try{const n=await this.proxyWithCdnLoadPackageAsync(t,i);return this.cacheConfig(s,n.files[e.CONFIG_NAME])}catch(e){c(e)}const a=await h(t,i,e.CONFIG_NAME);return this.cacheConfig(s,a)}async latestVersionAsync(t,n){let i=this.latestVersions[t];return i||(e.debug(`dep: resolve latest version of ${t}`),this.latestVersions[t]=i=await e.github.latestVersionAsync(t,n,!0,!1)),i}async loadPackageAsync(t,i){if(i||(e.debug("load pkg: default to master branch"),i="master"),n())try{return await this.proxyWithCdnLoadPackageAsync(t,i).then(t=>e.U.clone(t))}catch(e){c(e)}return await this.githubLoadPackageAsync(t,i)}githubLoadPackageAsync(t,n){return v(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}`),h(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=>h(t,i,e).then(t=>{r.files[e]=t})).then(()=>(this.packages[s]=r,e.U.clone(r)))}))})}async loadTutorialMarkdown(t,n){t=M(t);const i=(await p(t,n)).resp,s=i.markdown;return e.Util.assert("object"==typeof s),await this.cacheReposAsync(i),s.repo}async cacheReposAsync(e){if("object"==typeof e.markdown){const t=e.markdown;this.cacheRepo(t.repo)}for(const t of e.dependencies)this.cacheRepo(t)}cacheRepo(e){let t=e.repo;e.subPath&&(t+="/"+e.subPath);let n=t;n+="/"+e.sha,this.packages[n]={files:e.files},e.latestVersion&&this.cacheLatestVersion(t,e.latestVersion);const i=e.files["pxt.json"];if(i){const t=n+"/"+(e.version||"master");this.cacheConfig(n,i),this.cacheConfig(t,i)}}cacheLatestVersion(e,t){this.latestVersions[e]=t}}function d(t,n,i){return a({url:"https://api.github.com/repos/"+O(t.slug,"contents",t.fileName,i+"?ref="+n),method:"GET"}).then(n=>{const i=n.json;return r[t.slug]=!0,i&&"base64"==i.encoding&&null!=i.content?e.Util.fromUTF8(atob(i.content)):e.U.httpGetTextAsync(i.download_url)})}function h(t,n,i){const s=S(t);return r[s.slug]?d(s,n,i):e.U.requestAsync({url:"https://raw.githubusercontent.com/"+O(s.slug,n,s.fileName,i),allowHttpErrors:!0}).then(e=>200==e.statusCode?e.text:d(s,n,i))}async function p(t,n,i,s){let r=e.Cloud.apiRequestWithCdnAsync;const a=new URLSearchParams;n&&a.set("ref",n),i&&(a.set("noCache","1"),r=e.Cloud.privateRequestAsync);let o=`ghtutorial/${t}`;o=e.BrowserUtils.appendUrlQueryParams(o,a);const l=s?{"If-None-Match":s}:void 0,c=await r({url:o,method:"GET",headers:l});let u;return u=304===c.statusCode?void 0:c.json,{resp:u,etag:c.headers.etag}}function f(e,t,n,i){return a({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 m(e,t){let n=1;for(;e.refs[t+n];)n++;return t+n}async function g(e,t,n){return await f(e+"/git/refs",{ref:"refs/heads/"+t,sha:n}),t}function b(t,n="tags",s,r){const a=S(t),l=i(s);let c=null;const u=l?e.U.httpGetJsonAsync(e.BrowserUtils.cacheBustingUrl(`${e.Cloud.apiRoot}gh/${a.slug}/refs${r?"?nocache=1":""}`)).then(t=>{let i=Object.keys(t.refs).filter(t=>e.U.startsWith(t,"refs/"+n+"/")).map(e=>({ref:e,object:{sha:t.refs[e]}}));return c=t.refs.HEAD,i}):o(`https://api.github.com/repos/${a.slug}/git/refs/${n}/?per_page=100`);let d=e=>e.replace(/^refs\/[^\/]+\//,"");return u.then(t=>{t.sort((t,n)=>e.semver.strcmp(d(t.ref),d(n.ref)));let n={};for(let e of t)n[d(e.ref)]=e.object.sha;return{refs:n,head:c}},e=>404==e.statusCode?{refs:{}}:Promise.reject(e))}function y(e){return"commit"==e.object.type?Promise.resolve(e.object.sha):"tag"==e.object.type?o(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 v(e,t){if(/^[a-f0-9]{40}$/.test(t))return Promise.resolve(t);const n=S(e);return o(`https://api.github.com/repos/${n.slug}/git/refs/tags/${t}`).then(y,e=>o(`https://api.github.com/repos/${n.slug}/git/refs/heads/${t}`).then(y))}async function w(e,n,i){return n||(n=await t.db.latestVersionAsync(e,i)),await t.db.loadConfigAsync(e,n)}async function A(n,i){const s=S(n);if(!s)return void e.log("Unknown GitHub syntax");if(C(s,i))return e.tickEvent("github.download.banned"),void e.log("Github repo is banned");s.tag||(s.tag=await t.db.latestVersionAsync(s.slug,i));const r=await t.db.loadPackageAsync(s.fullName,s.tag),a=P(i,n);if(a){const t=e.Package.parseAndValidConfig(r.files[e.CONFIG_NAME]);t&&(e.log(`auto-disable ${a.join(",")} due to targetconfig entry for ${n}`),t.disablesVariants=a,r.files[e.CONFIG_NAME]=e.Package.stringifyConfig(t))}return r}let k;function T(t){return e.Cloud.cdnApiUrl(`gh/${t.fullName}/icon`)}function x(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=E(i,null==t?void 0:t.config),i}function E(e,t){return e?C(e,t)?k.Banned:function(e,t){var n,i;if(function(e,t){return!(!e||!t)&&!!(e.owner&&t.approvedOrgs&&t.approvedOrgs.some(t=>t.toLowerCase()==e.owner.toLowerCase()))}(e,t))return!0;const s=null===(n=null==e?void 0:e.fullName)||void 0===n?void 0:n.toLowerCase(),r=null===(i=null==e?void 0:e.slug)||void 0===i?void 0:i.toLowerCase();return!(!(null==t?void 0:t.approvedRepoLib)||!s&&!r)&&!(!t.approvedRepoLib[s]&&!t.approvedRepoLib[r])}(e,t)?k.Approved:k.Unknown:k.Unknown}function C(e,t){var n,i;if(function(e,t){return!(!t||e&&e.owner&&(!t.bannedOrgs||!t.bannedOrgs.some(t=>t.toLowerCase()==e.owner.toLowerCase())))}(e,t))return!0;if(!t)return!1;if(!e)return!0;const s=null===(n=e.fullName)||void 0===n?void 0:n.toLowerCase(),r=null===(i=e.slug)||void 0===i?void 0:i.toLowerCase();return!(!t.bannedRepos||!t.bannedRepos.some(e=>e&&(e.toLowerCase()==s||e.toLowerCase()==r)))}async function I(t,i){const s=S(t);if(!s)return;const r=E(s,i);if(r==k.Banned)return;if(n())try{return await function(t,n){return l(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,displayName:e.displayName,description:e.description,defaultBranch:e.defaultBranch||"master",tag:t.tag,status:n}}).catch(t=>{e.reportException(t)})}(s,r)}catch(e){c(e)}return x(await o("https://api.github.com/repos/"+s.slug),{config:i,fullName:s.fullName,fileName:s.fileName,tag:s.tag})}function S(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:O(i,s),fullName:O(i,s,r),tag:a,fileName:r}}function N(e){return!!e&&"github:"==e.slice(0,7)}function U(e,t=!1){return e?"github:"+(t?e.fullName:e.fullName.toLowerCase())+(e.tag?`#${e.tag}`:""):void 0}function O(...e){return e.filter(e=>!!e).join("/")}function _(t,n){var i;if(!t)return null;const s=S(n);if(!s)return null;t.approvedRepoLib;return t.approvedRepoLib&&(null===(i=e.U.lookup(t.approvedRepoLib,s.slug.toLowerCase()))||void 0===i?void 0:i.upgrades)}function P(e,t){const n=_(e,t)||[];if(!n)return null;for(const e of n){const t=/^dv:(.*)/.exec(e);if(t){const e=t[1].split(/,/);return e.some(e=>!/^\w+$/.test(e))?null:e}}return null}function L(t,n,i,s){const r=S(t);return r?I(r.slug,n).then(t=>{if(t)return b(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||v(t.slug,t.defaultBranch)})}):Promise.resolve(null)}t.MemoryGithubDb=u,t.downloadTextAsync=h,t.downloadMarkdownTutorialInfoAsync=p,t.downloadTutorialMarkdownAsync=async function(e,n){return t.db.loadTutorialMarkdown(e,n)},t.db=new u,t.authenticatedUserAsync=function(){return t.token?o("https://api.github.com/user"):Promise.resolve(void 0)},t.getCommitsAsync=function(e,t){return o("https://api.github.com/repos/"+S(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 o("https://api.github.com/repos/"+S(e).slug+"/git/commits/"+t).then(e=>o(e.tree.url+"?recursive=1").then(t=>(e.tree=t,e)))},t.createObjectAsync=function(e,t,n){return f(S(e).slug+"/git/"+t+"s",n).then(e=>e.sha)},t.postCommitComment=function(e,t,n,i,s){return f(`${S(e).slug}/commits/${t}/comments`,{body:n,path:i,position:s}).then(e=>e.id)},t.fastForwardAsync=async function(e,t,n){const i=S(e);return 200==(await a({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 s=S(t);await a({url:`https://api.github.com/repos/${e.github.join(s.slug,"contents",s.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 f(e+"/git/refs",{ref:"refs/tags/"+t,sha:n})},t.createReleaseAsync=async function(e,t,n){await f(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 f(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,s){return a({url:`https://api.github.com/repos/${S(t).slug}/merges`,method:"POST",successCodes:[201,204,409],data:{base:n,head:i,commit_message:s}}).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 o("https://api.github.com/repos/"+e+"/git/refs/heads/"+(t=t||"master")).then(y).catch(e=>{404!=e.statusCode&&Promise.reject(e)})},t.getNewBranchNameAsync=async function(e,t="patch-"){return m(await b(e,"heads"),t)},t.createNewBranchAsync=g,t.forkRepoAsync=async function(t,n,i="pr-"){const s=S(t),r=x(await f(`${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 b(r.slug,"heads")}catch(e){}}if(!o)throw new Error(lf("Timeout waiting for fork"));const l=m(o,i);return await g(r.slug,l,n),r.fullName+"#"+l},t.listRefsAsync=function(e,t="tags",n,i){return b(e,t,n,i).then(e=>Object.keys(e.refs))},t.listRefsExtAsync=b,t.pkgConfigAsync=w,t.downloadPackageAsync=A,t.downloadLatestPackageAsync=async function(t,n,i){const s=await e.packagesConfigAsync(),r=await e.github.latestVersionAsync(t.slug,s,n,i),a=`${t.fullName}#${r}`;return await e.github.downloadPackageAsync(a,s),{version:`github:${a}`,config:await w(t.fullName,r,s)}},t.cacheProjectDependenciesAsync=async function(t){var n;const i=null===(n=Object.keys(t.dependencies))||void 0===n?void 0:n.filter(e=>N(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 A(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"}(k=t.GitRepoStatus||(t.GitRepoStatus={})),t.isDefaultBranch=function(e,t){return t&&t.defaultBranch?e===t.defaultBranch:/^(main|master)$/.test(e)},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: "HEAD:pxt.json") {\n ... on Blob {\n text\n }\n }\n readme: object(expression: "HEAD:README.md") {\n ... on Blob {\n text\n }\n }\n }\n }\n }\n}').then(t=>t.data.viewer.repositories.nodes.filter(e=>e.pxtjson).filter(t=>{t.default_branch=t.defaultBranchRef.name;const n=e.Package.parseAndValidConfig(t.pxtjson&&t.pxtjson.text),i=t.readme&&t.readme.text;return!!n&&(n.supportedTargets?n.supportedTargets.indexOf(e.appTarget.id)>-1:i&&i.indexOf("PXT/"+e.appTarget.id)>-1)}).map(e=>x(e,{fullName:e.full_name})))},t.createRepoAsync=function(e,t,n){return f("https://api.github.com/user/repos",{name:e,description:t,private:!!n,has_issues:!0,has_projects:!1,has_wiki:!1,allow_rebase_merge:!1,allow_merge_commit:!0,delete_branch_on_merge:!1}).then(e=>x(e))},t.enablePagesAsync=async function(t){const n=S(t);let i;try{const e=await o(`https://api.github.com/repos/${n.slug}/pages`);e&&(i=e.html_url)}catch(e){}if(!i)try{i=(await f(`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 o(`https://api.github.com/repos/${t}`);if(n&&!n.homepage)try{await f(`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==k.Approved)return T(e)},t.mkRepoIconUrl=T,t.repoStatus=E,t.isRepoHidden=function(e,t){var n,i;if(!e||!t)return!0;const s=null===(n=e.fullName)||void 0===n?void 0:n.toLowerCase(),r=null===(i=e.slug)||void 0===i?void 0:i.toLowerCase(),a=t.approvedRepoLib[s]||t.approvedRepoLib[r];return!(!a||!a.hidden)},t.repoAsync=I,t.searchAsync=function(t,n){if(!n)return Promise.resolve([]);let i=t.split("|").map(S).filter(e=>!!e);return i.length>0?Promise.all(i.map(e=>I(e.fullName,n))).then(e=>e.filter(e=>e&&e.status!=k.Banned)):e.U.httpGetJsonAsync(`${e.Cloud.apiRoot}ghsearch/${e.appTarget.id}/${e.appTarget.platformid||e.appTarget.id}?q=${encodeURIComponent(t)}`).then(t=>t.items.map(e=>x(e,{config:n,fullName:e.full_name})).filter(e=>e.status==k.Approved||n.allowUnapproved&&e.status==k.Unknown).filter(t=>!e.appTarget.appTheme.githubUrl||`https://github.com/${t.fullName}`!=e.appTarget.appTheme.githubUrl.toLowerCase())).catch(e=>[])},t.parseRepoId=S,t.toGithubDependencyPath=function(e,t){let n="github:"+e;return t&&(n+="#"+t),n},t.isGithubId=N,t.stringifyRepo=U,t.normalizeRepoId=function(e,t){const n=S(e);if(n)return!n.tag&&t&&(n.tag=t),U(n)},t.join=O,t.upgradedPackageReferenceAsync=async function t(n,i){const s=_(n,i);if(!s)return null;for(const r of s){const s=/^move:(.*)$/.exec(r);if(s){const r=S(s[1]);if(r){r.tag||(r.tag=await L(s[1],n));const a=S(i);!r.fileName&&a.fileName&&(r.fileName=a.fileName,r.fullName=O(r.owner,r.project,r.fileName));const o=U(r);e.debug(`upgrading ${i} to ${o}}`);const l=await t(n,o);return l||o}e.log(`cannot parse move target: ${s[1]}`)}const a=/^min:(.*)/.exec(r),o=a&&e.semver.tryParse(a[1]);if(o){const t=S(i),n=e.semver.tryParse(t.tag);return n&&e.semver.cmp(n,o)<0?(t.tag=a[1],e.debug(`upgrading ${i} to ${a[1]}`),U(t)):(n||e.log(`not upgrading ${i} - cannot parse version`),null)}P(n,i)||e.log(`invalid upgrade rule: ${i} -> ${r}`)}return i},t.upgradedPackageId=function(e,t){const n=P(e,t);return n?t+"?dv="+n.join(","):t},t.latestVersionAsync=L,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 D="https://api.github.com/graphql";function $(e){const t=JSON.stringify({query:e});return f(D,t)}function M(e){if(/^github\:/i.test(e)&&(e=e.slice(7)),/^https?\:/i.test(e)){e=new URL(e).pathname.slice(1);const t=/^((?:[^\/]+\/){2})blob\/[^\/]+\/(.*)\.md$/.exec(e);t&&(e=t[1]+t[2])}return e}t.lookupFile=function(e,t,n){if(!t)return null;const i=O(e.fileName,n);return t.tree.tree.find(e=>e.path==i)},t.ghGraphQLQueryAsync=$,t.findPRNumberforBranchAsync=function(e,t){const n=S(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 o(`https://api.github.com/repos/${e}/pages`).catch(e=>({status:null}))},t.normalizeTutorialPath=M}(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]=255&n,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]=255&n,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.initialized=!1,this.cmdSeq=e.U.randomUint32(),this.lock=new e.U.PromiseQueue,this.flashing=!1,this.rawMode=!1,this.maxMsgSize=63,this.bootloaderMode=!1,this.reconnectTries=0,this.autoReconnect=!1,this.icon=(null===(i=e.appTarget.appTheme.downloadDialogTheme)||void 0===i?void 0:i.deviceIcon)||"usb",this.msgs=new e.U.PromiseBuffer,this.eventHandlers={},this.jacdacAvailable=!1,this.onSerial=(e,t)=>{},this.onCustomEvent=(e,t)=>{},this.onConnectionChanged=()=>{};let r=[];n.onDeviceConnectionChanged=e=>this.disconnectAsync().then(()=>e&&this.reconnectAsync()),n.onSerial=(e,t)=>this.onSerial(e,t),n.onData=i=>{let s=i[0]&t.HF2_FLAG_MASK,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.initialized=!1,this.lock=new e.U.PromiseQueue,this.info=null,this.infoRaw=null,this.pageSize=null,this.flashSize=null,this.maxMsgSize=63,this.bootloaderMode=!1,this.msgs.drain()}onEvent(n,i){e.U.assert(!!(n&t.HF2_EV_MASK)),this.eventHandlers[n+""]=i}sendCustomEventAsync(e,n){return e==t.CUSTOM_EV_JACDAC?this.jacdacAvailable?this.talkAsync(t.HF2_CMD_JDS_SEND,n).then(()=>{}):Promise.resolve():Promise.reject(new Error("invalid custom event type"))}isConnected(){return this.io.isConnected()&&this.initialized}isConnecting(){return this.io.isConnecting()||this.io.isConnected()&&!this.initialized}reconnectAsync(){return this.resetState(),l(`reconnect raw=${this.rawMode}`),this.io.reconnectAsync().then(()=>this.initAsync()).catch(t=>{if(this.reconnectTries<5)return this.reconnectTries++,l(`error ${t.message}; reconnecting attempt #${this.reconnectTries}`),e.U.delay(500).then(()=>this.reconnectAsync());throw t})}disconnectAsync(){return l("disconnect"),this.io.disconnectAsync()}error(e){return this.io.error(e)}talkAsync(s,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?(this.initialized=!0,Promise.resolve()):Promise.resolve().then(()=>this.talkAsync(t.HF2_CMD_BININFO)).then(e=>(this.bootloaderMode=e[0]==t.HF2_MODE_BOOTLOADER,this.pageSize=s(e,4),this.flashSize=s(e,8)*this.pageSize,this.maxMsgSize=s(e,12),this.familyID=s(e,16),l(`Connected; msgSize ${this.maxMsgSize}B; flash ${this.flashSize/1024}kB; ${this.bootloaderMode?"bootloader":"application"} mode; family=0x${this.familyID.toString(16)}`),this.talkAsync(t.HF2_CMD_INFO))).then(t=>{this.infoRaw=e.Util.fromUTF8Array(t),e.debug("Info: "+this.infoRaw);let n={};("Header: "+this.infoRaw).replace(/^([\w\-]+):\s*([^\n\r]*)/gm,(e,t,i)=>(n[t.replace(/-/g,"")]=i,"")),this.info=n;let i=/v(\d\S+)(\s+(\S+))?/.exec(this.info.Header);this.info.Parsed=i?{Version:i[1],Features:i[3]||""}:{Version:"?",Features:""},l(`Board-ID: ${this.info.BoardID} v${this.info.Parsed.Version} f${this.info.Parsed.Features}`)}).then(()=>this.talkAsync(t.HF2_CMD_JDS_CONFIG,new Uint8Array([1])).then(()=>{this.jacdacAvailable=!0},e=>{this.jacdacAvailable=!1})).then(()=>{this.reconnectTries=0,this.initialized=!0,this.io.onConnectionChanged()})}}function u(t,n){if(!e.appTarget.compile.flashChecksumAddr)return Promise.resolve(t);let i=pxtc.UF2.readBytes(t,e.appTarget.compile.flashChecksumAddr,48),r=pxtc.parseChecksumBlock(i);return r?function(t){return e.appTarget.compile.flashChecksumAddr?t(e.appTarget.compile.flashChecksumAddr,12).then(n=>{let i=pxtc.parseChecksumBlock(n);return i?t(i.endMarkerPos,1).then(t=>s(t,0)!=i.endMarker?(e.log("end-marker mismatch"),null):i):null}):Promise.resolve(null)}(n).then(e=>{if(!e)return t;let n=e.regions.filter(e=>r.regions.some(t=>e.checksum==t.checksum&&e.length==t.length&&e.start==t.start));if(0==n.length)return t;l("skipping flash at: "+n.map(e=>`${pxtc.assembler.tohex(e.start)} (${e.length/1024}kB)`).join(", "));let i=e=>n.some(t=>t.start<=e&&e<t.start+t.length);return t.filter(e=>!(i(e.targetAddr)&&i(e.targetAddr+e.payloadSize-1)))}):Promise.resolve(t)}t.Wrapper=c,t.mkHF2PacketIOWrapper=function(t){return e.debug("packetio: wrapper hf2"),new c(t)},t.onlyChangedBlocksAsync=u}(e.HF2||(e.HF2={}))}(pxt||(pxt={})),function(e){!function(t){var n=e.Util,i=e.HF2;const s=i.read32;let r,a,o,l,c,u,d,h,p=!1;function f(e){return e<<2|2}function m(e){return 1&e?e>>1:0!=e?2&e?e==t.taggedNull?null:e!=t.taggedFalse&&(e==t.taggedTrue||{tagged:e>>2}):{ptr:e}:void 0}function g(e,t){if(n.assert(!(3&e)),n.assert(e>=0),e<2097152){let i=new Uint8Array(t);return e-=d.start,n.memcpy(i,0,d.buf,e,t),Promise.resolve(i)}let i=h.maxMsgSize-32;if(t>i){let s=[];for(;t>0;){let n=Math.min(i,t);s.push(g(e,n)),t-=n,e+=n}return Promise.all(s).then(n.uint8ArrayConcat)}return h.readWordsAsync(e,Math.ceil(t/4)).then(e=>e.length>t?e.slice(0,t):e)}function b(t){if("object"!=typeof t||!t)return Promise.resolve(t);if("number"==typeof t.ptr){if(3&t.ptr)return Promise.resolve({unalignedPtr:t.ptr});let s=0;return g(t.ptr,56).then(r=>{s=i.read16(r,2);let 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?g(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,x().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(!(3&e.index)),r=m(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]=m(e[s++]);i=2147483646&e[s++];let d=u[i+""];for(let t of a.args)l.locals[t.name]=m(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 A(){p=!1,a=new Promise((e,t)=>{o=e})}function k(e=!1){return Promise.resolve().then(()=>h.talkAsync(665147697,i.encodeU32LE([e?1:3]))).then(A)}function T(){return a||(a=Promise.resolve()),a}function x(){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=t=>e.log(t),t.decodeValue=m,t.heapExpandAsync=b,t.heapExpandMapAsync=y,t.startDebugAsync=function(e,t){return h=t,h.onEvent(915601917,w),(p=!1,r=null,l=null,Promise.resolve()).then(()=>{r=e,u={};let t=[];for(let n of e.procDebugInfo)t[n.idx]=n;for(let n of e.procDebugInfo)for(let e of n.calls)u[e.addr+""]={from:n,to:t[e.procIndex],stack:e.stack}}).then(()=>{let e=r.outfiles[pxtc.BINARY_UF2],t=n.stringToUint8Array(atob(e));return d=pxtc.UF2.toBin(t),h.reflashAsync(r).then(()=>h.reconnectAsync())}).then(()=>h.talkAsync(287358355).catch(e=>{})).then(()=>n.delay(200)).then(()=>h.reconnectAsync()).then(A).then(T)},t.handleMessage=function(t){if(e.log("HWDBGMSG",t),"debugger"!=t.type)return;let n=!1;switch(t.subtype){case"stepinto":n=!0;case"stepover":k(n)}},t.resumeAsync=k,t.waitForHaltAsync=T,t.getHwStateAsync=x}(e.HWDBG||(e.HWDBG={}))}(pxt||(pxt={})),function(e){e.ImageConverter=class{logTime(){if(this.start){let t=Date.now()-this.start;e.debug("Icon creation: "+t+"ms")}}convert(t){this.start||(this.start=Date.now());let n=atob(t.slice(t.indexOf(",")+1)),i=n.charCodeAt(0),s=n.charCodeAt(1),r=n.charCodeAt(2);if(135===i&&(i=224|n.charCodeAt(1),s=n.charCodeAt(2)|n.charCodeAt(3)<<8,r=n.charCodeAt(4)|n.charCodeAt(5)<<8,n=n.slice(4)),225!=i&&228!=i)return null;if(this.palette||this.setPalette(e.appTarget.runtime.palette.map(function(e){const t=parseInt(e.replace(/#/,""),16);return[255&t,t>>8&255,t>>16&255,255]})),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)}setPalette(e){e[0][3]=0,this.palette=new Uint8Array(4*e.length);for(let t=0;t<e.length;++t)this.palette[4*t+0]=e[t][0],this.palette[4*t+1]=e[t][1],this.palette[4*t+2]=e[t][2],this.palette[4*t+3]=e[t][3]}genMonochrome(t,n,i){let s=n+3&-4,r=54+this.palette.length,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))}},e.convertUint8BufferToPngUri=function(t,n){const i=new e.ImageConverter,s=[];for(let e=0;e<16;e++)s.push([t[3*e+2],t[3*e+1],t[3*e+0],255]);i.setPalette(s);const r=String.fromCharCode.apply(null,n),a=`data:image/x-mkcd-f4;base64,${btoa(r)}`;return i.convert(a)}}(pxt||(pxt={})),function(e){!function(t){function n(){const e={"tsconfig.json":t.TS_CONFIG,"test.ts":`// ${lf("tests go here; this will not be compiled when this package is used as an extension.")}\n`,"_config.yml":"makecode:\n target: @TARGET@\n platform: @PLATFORM@\n home_url: @HOMEURL@\ntheme: jekyll-theme-slate\ninclude:\n - assets\n - README.md\n",Makefile:"all: deploy\n\nbuild:\n\tpxt build\n\ndeploy:\n\tpxt deploy\n\ntest:\n\tpxt test\n",Gemfile:"source 'https://rubygems.org'\ngem 'github-pages', group: :jekyll_plugins","README.md":`\n> ${lf("Open this page at {0}","[https://@REPOOWNER@.github.io/@REPONAME@/](https://@REPOOWNER@.github.io/@REPONAME@/)")}\n\n## ${lf("Use as Extension")}\n\n${lf("This repository can be added as an **extension** in MakeCode.")}\n\n* ${lf("open [@HOMEURL@](@HOMEURL@)")}\n* ${lf("click on **New Project**")}\n* ${lf("click on **Extensions** under the gearwheel menu")}\n* ${lf("search for **https://github.com/@REPO@** and import")}\n\n## ${lf("Edit this project")}\n\n${lf("To edit this repository in MakeCode.")}\n\n* ${lf("open [@HOMEURL@](@HOMEURL@)")}\n* ${lf("click on **Import** then click on **Import URL**")}\n* ${lf("paste **https://github.com/@REPO@** and click import")}\n\n#### ${lf("Metadata (used for search, rendering)")}\n\n* for PXT/@TARGET@\n<script src="https://makecode.com/gh-pages-embed.js"><\/script><script>makeCodeRender("{{ site.makecode.home_url }}", "{{ site.github.owner_name }}/{{ site.github.repository_name }}");<\/script>\n`,".gitignore":"# MakeCode\nbuilt\nnode_modules\nyotta_modules\nyotta_targets\npxt_modules\n.pxt\n_site\n*.db\n*.tgz\n.header.json\n.simstate.json\n",".vscode/settings.json":'{\n "editor.formatOnType": true,\n "files.autoSave": "afterDelay",\n "files.watcherExclude": {\n "**/.git/objects/**": true,\n "**/built/**": true,\n "**/node_modules/**": true,\n "**/yotta_modules/**": true,\n "**/yotta_targets": true,\n "**/pxt_modules/**": true,\n "**/.pxt/**": true\n },\n "files.associations": {\n "*.blocks": "html",\n "*.jres": "json"\n },\n "search.exclude": {\n "**/built": true,\n "**/node_modules": true,\n "**/yotta_modules": true,\n "**/yotta_targets": true,\n "**/pxt_modules": true,\n "**/.pxt": true\n },\n "files.exclude": {\n "**/pxt_modules": true,\n "**/.pxt": true\n }\n}',".vscode/extensions.json":'{\n "recommendations": ["ms-edu.pxt-vscode-web"]\n}'},n=i();return n&&Object.keys(n).forEach(t=>e[t]=n[t]),e}function i(){const t=e.appTarget.bundledpkgs[e.template.TEMPLATE_PRJ];if(t){const n=e.Util.clone(t);return delete n[e.CONFIG_NAME],n}}t.TS_CONFIG='{\n "compilerOptions": {\n "target": "ES5",\n "noImplicitAny": true,\n "outDir": "built",\n "rootDir": "."\n },\n "exclude": ["pxt_modules/**/*test.ts"]\n}\n',t.defaultFiles=n,t.targetTemplateFiles=i,t.TEMPLATE_PRJ="template",t.packageFiles=function(t){const i=e.appTarget.blocksprj||e.appTarget.tsprj,s=e.U.clone(i.config);delete s.installedVersion,delete s.additionalFilePath,delete s.additionalFilePaths,s.preferredEditor=s.files.find(e=>/\.blocks$/.test(e))?e.BLOCKS_PROJECT_NAME:e.JAVASCRIPT_PROJECT_NAME,s.name=t,s.public=!0,s.version||(s.version="0.0.0");const r={},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 m;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(")")])}}(m=t.Helpers||(t.Helpers={})),t.H=m;const g={"=":3,"+=":3,"-=":3,"?":4,":":4,"||":5,"&&":6,"|":7,"^":8,"&":9,"==":10,"!=":10,"===":10,"!==":10,"<":11,">":11,"<=":11,">=":11,">>":12,">>>":12,"<<":12,"+":13,"-":13,"*":14,"/":14,"%":14,"**":15,"!":16,"~":16,"P-":16,"P+":16,"++":16,"--":16,".":18};function b(t){let s=[],r={},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(g,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 m(" {\n\t\n}"+n);let i=e.U.clone(l[l.length-1]||{});l.push(i),o+=" "," "!=a[a.length-1]&&m(" ");m("{\n");for(let e of t.children)f(e);o=o.slice(4),b(),m("\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,g=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,g)}else{const e={id:t.id,startLine:d,startPos:h,endLine:p,endPos:g};r[t.id]=e,s.push(e)}}function m(e){u(e.replace(/\n/g,"\n"+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){var t;!function(n){const i=[".","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];n.BLOCKLY_TILESET_TYPE="BLOCKLY_TILESET_TYPE",n.TILE_PREFIX="tile",n.TILE_NAMESPACE="myTiles",n.IMAGES_NAMESPACE="myImages",n.IMAGE_PREFIX="image",n.ANIMATION_NAMESPACE="myAnimations",n.ANIMATION_PREFIX="anim",n.SONG_NAMESPACE="mySongs",n.JSON_NAMESPACE="myFiles",n.SONG_PREFIX="song",n.JSON_PREFIX="file";class s{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 s(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,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}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 p(this,e,t)}coordToIndex(e,t){return e+t*this.width}getCore(e){const t=Math.floor(e/2);return e%2==0?15&this.buf[t]:(240&this.buf[t])>>4}setCore(e,t){const n=Math.floor(e/2);this.buf[n]=e%2==0?240&this.buf[n]|15&t:15&this.buf[n]|(15&t)<<4}dataLength(){return Math.ceil(this.width*this.height/2)}}n.Bitmap=s;class r extends s{static fromData(e){return new r(e.width,e.height,e.x0,e.y0,e.data)}copy(e=0,t=0,n=this.width,i=this.height){const s=new r(n,i);s.x0=e,s.y0=t;for(let r=0;r<n;r++)for(let n=0;n<i;n++)s.set(r,n,this.get(e+r,t+n));return s}resize(e,t){return f(this,e,t)}getCore(e){return this.buf[e]}setCore(e,t){this.buf[e]=t}dataLength(){return this.width*this.height}}n.Tilemap=r;class a{constructor(e,t,n){this.tilemap=e,this.tileset=t,this.layers=n,this.nextId=0}cloneData(e=!1){var t,n,i,r;const o=this.tilemap.copy(),l={tileWidth:this.tileset.tileWidth,tiles:this.tileset.tiles.map(e=>Object.assign(Object.assign({},e),{bitmap:s.fromData(e.bitmap).copy().data()}))},c=s.fromData(this.layers).copy().data(),u=new a(o,l,c);return e&&(u.nextId=this.nextId,u.projectReferences=null===(t=this.projectReferences)||void 0===t?void 0:t.slice(),u.tileOrder=null===(n=this.tileOrder)||void 0===n?void 0:n.slice(),u.editedTiles=null===(i=this.editedTiles)||void 0===i?void 0:i.slice(),u.deletedTiles=null===(r=this.deletedTiles)||void 0===r?void 0:r.slice()),u}equals(e){return this.tilemap.equals(e.tilemap)&&w(this.tileset,e.tileset)&&v(this.layers,e.layers)}}n.TilemapData=a;function o(e){return l(atob(e.slice(e.indexOf(",")+1)))}function l(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 c(e,t){!(e=(e=(e=e.replace(/[ `]|(?:`)|(?:	)|(?:hex)/g,"").trim()).replace(/^["`\(\)]*/,"").replace(/["`\(\)]*$/,"")).replace(/ /g,"\n"))&&t&&(e=t);const n=parseInt(e.substr(0,2),16)|parseInt(e.substr(2,2),16)<<8,i=parseInt(e.substr(4,2),16)|parseInt(e.substr(6,2),16)<<8,s=T(e.substring(8));return r.fromData({width:n,height:i,x0:0,y0:0,data:s})}function u(e){return`${h(e.width,2)}${h(e.height,2)}${x(e.data().data)}`}function d(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=m(e);return t.createNewTile(n.data())}switch(e){case"myTiles.tile0":case"myTiles.transparency16":return t.getTransparency(16);case"myTiles.transparency8":return t.getTransparency(8);case"myTiles.transparency4":return t.getTransparency(4);case"myTiles.transparency32":return t.getTransparency(32);default:return t.resolveTile(e)}}(e,t)):[]}function h(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 p(e,t,n){const i=new s(t,n);return i.apply(e),i}function f(e,t,n){const i=new r(t,n);return i.apply(e),i}function m(e,t="img"){const n=(e=(e=(e=(e=e.replace(/[ `]|(?:`)|(?:	)|(?:img)/g,"").trim()).replaceAll(t,"")).replace(/^["`\(\)]*/,"").replace(/["`\(\)]*$/,"")).replace(/ /g,"\n")).split("\n"),i=[];let r=0;for(let e=0;e<n.length;e++){const t=n[e],s=[];for(let e=0;e<t.length;e++)switch(t[e]){case"0":case".":s.push(0);break;case"1":case"#":s.push(1);break;case"2":case"T":s.push(2);break;case"3":case"t":s.push(3);break;case"4":case"N":s.push(4);break;case"5":case"n":s.push(5);break;case"6":case"G":s.push(6);break;case"7":case"g":s.push(7);break;case"8":s.push(8);break;case"9":s.push(9);break;case"a":case"A":case"R":s.push(10);break;case"b":case"B":case"P":s.push(11);break;case"c":case"C":case"p":s.push(12);break;case"d":case"D":case"O":s.push(13);break;case"e":case"E":case"Y":s.push(14);break;case"f":case"F":case"W":s.push(15);break;default:if(!/\s/.test(t[e]))return}s.length&&(i.push(s),r=Math.max(r,s.length))}const a=i.length,o=new s(r,a);for(let e=0;e<a;e++){const t=i[e];for(let n=0;n<r;n++)n<t.length?o.set(n,e,t[n]):o.set(n,e,0)}return o}function g(e,t="img"){let n="";if("python"===e)n=`${t}("""`;else n=`${t}\``;return n}function b(e){let t="";if("python"===e)t+='""")';else t+="`";return t}function y(e,t,n="img"){if(!e||0===e.height||0===e.width)return"";let s=g(t,n);if(e){const t=e.width*e.height>300?"":" ";for(let n=0;n<e.height;n++){s+="\n";for(let r=0;r<e.width;r++)s+=i[e.get(r,n)]+t}}return s+="\n",s+=b(t),s}function v(t,n){return t===n||!(!t&&n||!n&&t)&&e.sprite.Bitmap.fromData(t).equals(e.sprite.Bitmap.fromData(n))}function w(t,n){return t.tileWidth===n.tileWidth&&e.U.arrayEquals(t.tiles,n.tiles,e.assetEquals)}function A(e){switch(e){case 4:return"TileScale.Four";case 8:return"TileScale.Eight";case 16:return"TileScale.Sixteen";case 32:return"TileScale.ThirtyTwo";default:return Math.floor(Math.log2(e)).toString()}}function k(e){switch(e=e.replace(/\s/g,"")){case"TileScale.Four":return 4;case"TileScale.Eight":return 8;case"TileScale.Sixteen":return 16;case"TileScale.ThirtyTwo":return 32;default:return Math.pow(2,parseInt(e))}}function T(e){let t=new Uint8ClampedArray(e.length>>1);for(let n=0;n<e.length;n+=2)t[n>>1]=parseInt(e.slice(n,n+2),16);return t}function x(e){const t="0123456789abcdef";let n="";for(let i=0;i<e.length;++i)n+=t[e[i]>>4],n+=t[15&e[i]];return n}function E(e,t,n){e[t]=255&n,e[t+1]=n>>8&255}function C(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[I(t),S(t),N(t)]}function I(e){return e>>16&255}function S(e){return e>>8&255}function N(e){return 255&e}n.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}},n.encodeTilemap=function(e,t,n){return e?`tiles.createTilemap(${function(e){return e?`hex\`${u(e)}\``:"hex``"}(e.tilemap)}, ${y(s.fromData(e.layers),t)}, [${e.tileset.tiles.map(e=>function(e,t,n){if(n&&n[e.id])return n[e.id];return e.id}(e,0,n))}], ${A(e.tileset.tileWidth)})`:"null"},n.decodeTilemap=function(t,n,i){if(!(t=e.Util.htmlUnescape(t).trim()).trim()||-1===t.indexOf("("))return null;const s=(t=(t=t.substr(t.indexOf("(")+1)).substr(0,t.lastIndexOf(")"))).substr(0,t.indexOf(",")),r=(t=t.substr(s.length+1)).substr(0,t.indexOf(",")),o=(t=t.substr(r.length+1)).substr(0,t.lastIndexOf("]")+1),l=t=t.substr(o.length+1);return new a(c(s),{tiles:d(o,i),tileWidth:k(l)},m(r).data())},n.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},n.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},n.computeAverageColor=function(e,t){const n=t.map(C),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"},n.getBitmap=function(e,t){const n=e.apis.byQName[t];return n?o(n.attributes.jresURL):null},n.getBitmapFromJResURL=o,n.hexToBitmap=l,n.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})},n.getGalleryItems=function(t,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))}(t.apis,i);return s=s.filter(e=>e.namespace!=n.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}})},n.base64EncodeBitmap=function(t){const n=s.fromData(t),i=pxtc.f4EncodeImg(t.width,t.height,4,(e,t)=>n.get(e,t));return btoa(e.U.uint8ArrayToString(T(i)))},n.tilemapLiteralToTilemap=c,n.hexEncodeTilemap=u,n.formatByte=h,n.resizeBitmap=p,n.resizeTilemap=f,n.imageLiteralToBitmap=m,n.encodeAnimationString=function(t,n){const i=t.map(e=>e.data),s=new Uint8ClampedArray(8+i[0].length*i.length);E(s,0,n),E(s,2,t[0].width),E(s,4,t[0].height),E(s,6,t.length);let r=8;return i.forEach(e=>{s.set(e,r),r+=e.length}),btoa(e.sprite.uint8ArrayToHex(s))},n.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)},n.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)},n.isTilemapEmptyOrUnused=function(e,n,i){const s=t.Bitmap.fromData(e.data.layers);for(let t=0;t<e.data.tilemap.width;t++)for(let n=0;n<e.data.tilemap.height;n++)if(e.data.tilemap.get(t,n)||s.get(t,n))return!1;return!n.isAssetUsed(e,i)},n.imageLiteralFromDimensions=function(e,t,n,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+=i[n]+a}return r+="\n",r+=b(s),r},n.bitmapToImageLiteral=y,n.bitmapEquals=v,n.tilesetEquals=w,n.tileWidthToTileScale=A,n.tileScaleToTileWidth=k,n.hexToUint8Array=T,n.uint8ArrayToHex=x,n.colorStringToRGB=C}(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,this.type="localstorage"}targetKey(e){return this.storageId+"/"+e}removeItem(e){window.localStorage.removeItem(this.targetKey(e))}getItem(e){return window.localStorage[this.targetKey(e)]}setItem(e,t){window.localStorage[this.targetKey(e)]=t}clear(){let e=this.targetKey(""),t=[];for(let n=0;n<window.localStorage.length;++n){let i=window.localStorage.key(n);0==i.indexOf(e)&&t.push(i)}t.forEach(e=>window.localStorage.removeItem(e))}}function s(){if(e.appTarget)return e.appTarget.id;const t=window.pxtConfig;if(t)return t.targetId;const n=window.pxtTargetBundle;return n?n.id:""}let r;function a(){if(r)return;const t=s();let a=!1;if(!e.shell.isSandboxMode())try{const n=e.Util.guidGen();window.localStorage[t]=n;a=window.localStorage[t]===n}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});if(204===i.statusCode)throw new Error(`Missing ${r} not available in ${t}`);return i.json?i.json:i.text?i.text:void 0}{const n=e.storage.getLocal(`${t}:${r}`),i=e.Util.jsonTryParse(n);return i||n}},t.setAsync=async function(t,r,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){function t(e){let t=0;for(let n=0;n<e.length;n++)if(" "===e.charAt(n))t++;else{if("\t"!==e.charAt(n))return t;t+=4}return 0}e.getSectionsFromMarkdownMetadata=function(e){const n=e.split(/\r?\n/);let i=[],s=null,r=null,a=null,o=[],l=0,c=null;for(const e of n)if(e.trim()){if(e.startsWith("```")){if(c){s&&(s.codeBlocks?s.codeBlocks.push(c):s.codeBlocks=[c]),c=null;continue}{const t=/^```([a-zA-Z_\-]*)$/.exec(e);if(t){c={content:"",languageCode:t[1]};continue}}}else c&&(c.content+=e+"\n");if(e.startsWith("#")){const t=/^(#+)\s*(.+)$/.exec(e);if(t){u(),s={headerKind:1===t[1].length?"single":2===t[1].length?"double":"triple",header:t[2],attributes:{}},r=null,a=null,l=0;continue}}if(s){const n=t(e),i=e.trim(),c=/^[*-]\s+(?:([^:]+):)?(.*)$/.exec(i);if(!c)continue;if(Math.abs(n-l)>1&&r){if(n>l){const e={key:r,items:[]};o.length?o[o.length-1].items.push(e):(s.listAttributes||(s.listAttributes={}),s.listAttributes[r]=e),r=null,o.push(e)}else{const e=o.pop();r&&a&&(null==e||e.items.push((r+":"+a).trim()),a=null)}l=n}c&&(c[1]?(r&&a&&(o.length?o[o.length-1].items.push((r+":"+a).trim()):s.attributes[r]=a.trim()),r=c[1].trim().toLowerCase(),a=c[2]):r&&(a+=c[2]))}}else a&&(a+="\n");return u(),i;function u(){s&&(r&&a&&(o.length?o[o.length-1].items.push((r+":"+a).trim()):s.attributes[r]=a.trim()),i.push(s)),o=[]}}}(pxt||(pxt={})),function(e){!function(t){let n;!function(e){e[e.PROD=0]="PROD",e[e.STAGING=1]="STAGING",e[e.LOCAL=2]="LOCAL"}(n||(n={}));let i=n.STAGING;t.ABSOLUTE_LINKS={PROD_BETA:"https://arcade.makecode.com/beta--multiplayer",STAGING_BETA:"https://arcade.staging.pxt.io/beta--multiplayer",LOCAL:"http://localhost:3000"},t.RELATIVE_LINKS={PROD:"/--multiplayer",BETA:"/beta--multiplayer"},t.SHORT_LINKS={PROD:"https://aka.ms/a9",PROD_BETA:"https://aka.ms/a9b",STAGING:"https://aka.ms/a9s",STAGING_BETA:"https://aka.ms/a9sb"},t.RELATIVE_LINK=()=>{if(e.BrowserUtils.isLocalHostDev())switch(i){case n.PROD:return t.ABSOLUTE_LINKS.PROD_BETA;case n.STAGING:return t.ABSOLUTE_LINKS.STAGING_BETA;case n.LOCAL:return t.ABSOLUTE_LINKS.LOCAL}return window.location.pathname.startsWith("/beta")?t.RELATIVE_LINKS.BETA:t.RELATIVE_LINKS.PROD},t.SHORT_LINK=()=>{if(e.BrowserUtils.isLocalHostDev())switch(i){case n.PROD:return t.SHORT_LINKS.PROD_BETA;case n.STAGING:return t.SHORT_LINKS.STAGING_BETA;case n.LOCAL:return t.ABSOLUTE_LINKS.LOCAL}return window.location.host.endsWith(".staging.pxt.io")?window.location.pathname.startsWith("/beta")?t.SHORT_LINKS.STAGING_BETA:t.SHORT_LINKS.STAGING:window.location.pathname.startsWith("/beta")?t.SHORT_LINKS.PROD_BETA:t.SHORT_LINKS.PROD},t.makeHostLink=function(e,n){return`${n?t.SHORT_LINK():t.RELATIVE_LINK()}?host=${encodeURIComponent(e)}`},t.makeJoinLink=function(e,n){return`${n?t.SHORT_LINK():t.RELATIVE_LINK()}?join=${encodeURIComponent(e)}`}}(e.multiplayer||(e.multiplayer={}))}(pxt||(pxt={})),function(e){!function(t){!function(t){function n(e,t,n){const i=new Uint8Array(2);new Uint16Array(i.buffer)[0]=0|n,e[t]=i[0],e[t+1]=i[1]}function i(e,t){const n=new Uint8Array(2);return n[0]=e[t],n[1]=e[t+1],new Uint16Array(n.buffer)[0]}function s(e){const t=new Uint8Array(5+7*e.steps.length);t[0]=e.steps.length,n(t,1,e.startFrequency),n(t,3,e.startVolume);for(let i=0;i<e.steps.length;i++){const s=5+7*i;t[s]=e.steps[i].waveform,n(t,s+1,e.steps[i].frequency),n(t,s+3,e.steps[i].volume),n(t,s+5,e.steps[i].duration)}return t}function r(e,t,i){const s=new Uint8Array(5+e.notes.length);n(s,0,e.startTick),n(s,2,e.endTick),s[4]=e.notes.length;for(let n=0;n<e.notes.length;n++)s[5+n]=a(e.notes[n],t,i);return s}function a(e,t,n){if(n)return e.note;let i=0;return"flat"===e.enharmonicSpelling?i=1:"sharp"===e.enharmonicSpelling&&(i=2),e.note-12*(t-2)|i<<6}function o(e){return e.drums?function(e){const t=e.drums.map(s),i=t.reduce((e,t)=>t.length+e,0),a=e.notes.map(e=>r(e,0,!0)),o=a.reduce((e,t)=>t.length+e,0),l=new Uint8Array(6+i+o);l[0]=e.id,l[1]=1,n(l,2,i);let c=4;for(const e of t)l.set(e,c),c+=e.length;n(l,c,o),c+=2;for(const e of a)l.set(e,c),c+=e.length;return l}(e):function(e){const t=function(e){var t,i,s,r,a,o,l,c,u;const d=new Uint8Array(28);return d[0]=e.waveform,n(d,1,e.ampEnvelope.attack),n(d,3,e.ampEnvelope.decay),n(d,5,e.ampEnvelope.sustain),n(d,7,e.ampEnvelope.release),n(d,9,e.ampEnvelope.amplitude),n(d,11,(null===(t=e.pitchEnvelope)||void 0===t?void 0:t.attack)||0),n(d,13,(null===(i=e.pitchEnvelope)||void 0===i?void 0:i.decay)||0),n(d,15,(null===(s=e.pitchEnvelope)||void 0===s?void 0:s.sustain)||0),n(d,17,(null===(r=e.pitchEnvelope)||void 0===r?void 0:r.release)||0),n(d,19,(null===(a=e.pitchEnvelope)||void 0===a?void 0:a.amplitude)||0),d[21]=(null===(o=e.ampLFO)||void 0===o?void 0:o.frequency)||0,n(d,22,(null===(l=e.ampLFO)||void 0===l?void 0:l.amplitude)||0),d[24]=(null===(c=e.pitchLFO)||void 0===c?void 0:c.frequency)||0,n(d,25,(null===(u=e.pitchLFO)||void 0===u?void 0:u.amplitude)||0),d[27]=e.octave,d}(e.instrument),i=e.notes.map(t=>r(t,e.instrument.octave,!1)),s=i.reduce((e,t)=>t.length+e,0),a=new Uint8Array(6+t.length+s);a[0]=e.id,a[1]=0,n(a,2,t.length);let o=4;a.set(t,o),o+=t.length,n(a,o,s),o+=2;for(const e of i)a.set(e,o),o+=e.length;return a}(e)}function l(e,t){return{waveform:e[t],ampEnvelope:{attack:i(e,t+1),decay:i(e,t+3),sustain:i(e,t+5),release:i(e,t+7),amplitude:i(e,t+9)},pitchEnvelope:{attack:i(e,t+11),decay:i(e,t+13),sustain:i(e,t+15),release:i(e,t+17),amplitude:i(e,t+19)},ampLFO:{frequency:e[t+21],amplitude:i(e,22)},pitchLFO:{frequency:e[t+24],amplitude:i(e,25)},octave:e[t+27]}}function c(e,t){return e[t+1]?function(e,t){const n={id:e[t],instrument:{ampEnvelope:{attack:0,decay:0,sustain:0,release:0,amplitude:0},waveform:0},notes:[],drums:[]},s=i(e,t+2);let r=t+4;for(;r<t+4+s;)n.drums.push(u(e,r)),r+=5+7*n.drums[n.drums.length-1].steps.length;const a=i(e,r);r+=2;for(;r<t+4+s+a;)n.notes.push(d(e,r,0,!0)),r+=5+n.notes[n.notes.length-1].notes.length;return[n,r]}(e,t):function(e,t){const n={id:e[t],instrument:l(e,t+4),notes:[]},s=t+4+i(e,t+2),r=i(e,s);let a=s+2;for(;a<s+2+r;)n.notes.push(d(e,a,n.instrument.octave,!1)),a+=5+n.notes[n.notes.length-1].notes.length;return[n,a]}(e,t)}function u(e,t){const n={startFrequency:i(e,t+1),startVolume:i(e,t+3),steps:[]};for(let s=0;s<e[t];s++){const r=t+5+7*s;n.steps.push({waveform:e[r],frequency:i(e,r+1),volume:i(e,r+3),duration:i(e,r+5)})}return n}function d(e,t,n,s){const r={startTick:i(e,t),endTick:i(e,t+2),notes:[]};for(let i=0;i<e[t+4];i++)r.notes.push(h(e[t+5+i],n,s));return r}function h(e,t,n){const i=e>>6,s={note:n?e:(63&e)+12*(t-2),enharmonicSpelling:"normal"};return 1===i?s.enharmonicSpelling="flat":2===i&&(s.enharmonicSpelling="sharp"),s}function p(e,t){if(typeof e!=typeof t)return!1;if("object"!=typeof e)return e===t;if(Array.isArray(e)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!p(e[n],t[n]))return!1;return!0}const n=Object.keys(e),i=Object.keys(t);if(n.length!==i.length)return!1;for(const s of n){if(-1===i.indexOf(s))return!1;if(!p(e[s],t[s]))return!1}return!0}function f(e){return{ticksPerBeat:8,beatsPerMeasure:4,beatsPerMinute:120,measures:e,tracks:[{id:0,name:lf("Dog"),notes:[],iconURI:"music-editor/dog.png",instrument:{waveform:1,octave:4,ampEnvelope:{attack:10,decay:100,sustain:500,release:100,amplitude:1024},pitchLFO:{frequency:5,amplitude:0}}},{id:1,name:lf("Duck"),notes:[],iconURI:"music-editor/duck.png",instrument:{waveform:15,octave:4,ampEnvelope:{attack:5,decay:530,sustain:705,release:450,amplitude:1024},pitchEnvelope:{attack:5,decay:40,sustain:0,release:100,amplitude:40},ampLFO:{frequency:3,amplitude:20},pitchLFO:{frequency:6,amplitude:2}}},{id:2,name:lf("Cat"),notes:[],iconURI:"music-editor/cat.png",instrument:{waveform:12,octave:5,ampEnvelope:{attack:150,decay:100,sustain:365,release:400,amplitude:1024},pitchEnvelope:{attack:120,decay:300,sustain:0,release:100,amplitude:50},pitchLFO:{frequency:10,amplitude:6}}},{id:3,name:lf("Fish"),notes:[],iconURI:"music-editor/fish.png",instrument:{waveform:1,octave:3,ampEnvelope:{attack:220,decay:105,sustain:1024,release:350,amplitude:1024},ampLFO:{frequency:5,amplitude:100},pitchLFO:{frequency:1,amplitude:4}}},{id:4,name:lf("Car"),notes:[],iconURI:"music-editor/car.png",instrument:{waveform:16,octave:4,ampEnvelope:{attack:5,decay:100,sustain:1024,release:30,amplitude:1024},pitchLFO:{frequency:10,amplitude:4}}},{id:5,name:lf("Computer"),notes:[],iconURI:"music-editor/computer.png",instrument:{waveform:15,octave:2,ampEnvelope:{attack:10,decay:100,sustain:500,release:10,amplitude:1024}}},{id:6,name:lf("Burger"),notes:[],iconURI:"music-editor/burger.png",instrument:{waveform:1,octave:2,ampEnvelope:{attack:10,decay:100,sustain:500,release:100,amplitude:1024}}},{id:7,name:lf("Cherry"),notes:[],iconURI:"music-editor/cherry.png",instrument:{waveform:2,octave:3,ampEnvelope:{attack:10,decay:100,sustain:500,release:100,amplitude:1024}}},{id:8,name:lf("Lemon"),notes:[],iconURI:"music-editor/lemon.png",instrument:{waveform:14,octave:2,ampEnvelope:{attack:5,decay:70,sustain:870,release:50,amplitude:1024},pitchEnvelope:{attack:10,decay:45,sustain:0,release:100,amplitude:20},ampLFO:{frequency:1,amplitude:50},pitchLFO:{frequency:2,amplitude:1}}},{id:9,name:lf("Drums"),notes:[],iconURI:"music-editor/explosion.png",instrument:{waveform:11,octave:4,ampEnvelope:{attack:10,decay:100,sustain:500,release:100,amplitude:1024}},drums:[{startFrequency:100,startVolume:1024,steps:[{waveform:3,frequency:120,duration:10,volume:1024},{waveform:3,frequency:1,duration:100,volume:0}]},{startFrequency:200,startVolume:1024,steps:[{frequency:0,volume:0,duration:100,waveform:1}]},{startFrequency:100,startVolume:1024,steps:[{frequency:0,volume:0,duration:250,waveform:1}]},{startFrequency:175,startVolume:1024,steps:[{waveform:1,frequency:200,duration:10,volume:1024},{waveform:1,frequency:150,duration:20,volume:1024},{waveform:5,frequency:1,duration:20,volume:100},{waveform:5,frequency:1,duration:300,volume:0}]},{startFrequency:220,startVolume:1024,steps:[{waveform:1,frequency:250,duration:10,volume:1024},{waveform:1,frequency:200,duration:20,volume:1024},{waveform:5,frequency:2e3,duration:20,volume:100},{waveform:5,frequency:2e3,duration:200,volume:0}]},{startFrequency:400,startVolume:500,steps:[{frequency:450,volume:500,duration:10,waveform:5},{frequency:400,volume:20,duration:20,waveform:5}]},{startFrequency:400,startVolume:0,steps:[{frequency:450,volume:500,duration:5,waveform:5},{frequency:900,volume:5,duration:50,waveform:5},{frequency:900,volume:0,duration:250,waveform:5}]},{startFrequency:400,startVolume:0,steps:[{frequency:450,volume:500,duration:5,waveform:5},{frequency:900,volume:200,duration:50,waveform:5},{frequency:900,volume:5,duration:100,waveform:5},{frequency:900,volume:0,duration:400,waveform:5}]},{startFrequency:400,startVolume:0,steps:[{frequency:450,volume:500,duration:5,waveform:5},{frequency:900,volume:200,duration:100,waveform:5},{frequency:900,volume:5,duration:200,waveform:5},{frequency:900,volume:0,duration:500,waveform:5}]},{startFrequency:3500,startVolume:1024,steps:[{frequency:4e3,volume:0,duration:10,waveform:4},{frequency:3500,volume:800,duration:1,waveform:4},{frequency:4e3,volume:0,duration:40,waveform:4},{frequency:3500,volume:400,duration:1,waveform:4},{frequency:4e3,volume:0,duration:40,waveform:4}]},{startFrequency:2e3,startVolume:1024,steps:[{frequency:1800,volume:15,duration:100,waveform:4},{frequency:1800,volume:0,duration:200,waveform:4}]},{startFrequency:200,startVolume:200,steps:[{frequency:125,volume:200,duration:25,waveform:14},{frequency:100,volume:15,duration:50,waveform:14},{frequency:120,volume:0,duration:250,waveform:14}]},{startFrequency:300,startVolume:200,steps:[{frequency:225,volume:200,duration:25,waveform:14},{frequency:200,volume:15,duration:50,waveform:14},{frequency:220,volume:0,duration:250,waveform:14}]},{startFrequency:500,startVolume:200,steps:[{frequency:425,volume:200,duration:25,waveform:14},{frequency:400,volume:15,duration:50,waveform:14},{frequency:420,volume:0,duration:250,waveform:14}]},{startFrequency:200,startVolume:1024,steps:[{frequency:75,volume:0,duration:200,waveform:1}]},{startFrequency:300,startVolume:1024,steps:[{frequency:200,volume:0,duration:200,waveform:1}]},{startFrequency:400,startVolume:1024,steps:[{frequency:300,volume:0,duration:200,waveform:1}]},{startFrequency:200,startVolume:1024,steps:[{frequency:200,volume:15,duration:100,waveform:4},{frequency:150,volume:0,duration:200,waveform:4}]},{startFrequency:450,startVolume:1024,steps:[{frequency:350,volume:15,duration:100,waveform:4},{frequency:300,volume:0,duration:100,waveform:4}]},{startFrequency:2500,startVolume:1024,steps:[{frequency:2500,volume:100,duration:150,waveform:4},{frequency:2550,volume:0,duration:500,waveform:4}]},{startFrequency:3e3,startVolume:1024,steps:[{frequency:3e3,volume:100,duration:300,waveform:4},{frequency:3060,volume:0,duration:500,waveform:4}]},{startFrequency:800,startVolume:0,steps:[{frequency:800,volume:1024,duration:10,waveform:4},{frequency:800,volume:0,duration:490,waveform:4}]},{startFrequency:400,startVolume:0,steps:[{frequency:400,volume:1024,duration:10,waveform:4},{frequency:400,volume:0,duration:400,waveform:4}]},{startFrequency:2e3,startVolume:1024,steps:[{frequency:2e3,volume:100,duration:150,waveform:16},{frequency:2e3,volume:0,duration:200,waveform:16}]}]}]}}t.encodeSongToHex=function(t){const i=function(e){const t=e.tracks.filter(e=>e.notes.length>0).map(o),i=t.reduce((e,t)=>t.length+e,0),s=new Uint8Array(7+i);s[0]=0,n(s,1,e.beatsPerMinute),s[3]=e.beatsPerMeasure,s[4]=e.ticksPerBeat,s[5]=e.measures,s[6]=t.length;let r=7;for(const e of t)s.set(e,r),r+=e.length;return s}(t);return e.U.toHex(i)},t.decodeSongFromHex=function(t){return function(e){const t={beatsPerMinute:i(e,1),beatsPerMeasure:e[3],ticksPerBeat:e[4],measures:e[5],tracks:[]};let n=7;for(;n<e.length;){const[i,s]=c(e,n);n=s,t.tracks.push(i)}return t}(e.U.fromHex(t))},t.cloneSong=function(e){return Object.assign(Object.assign({},e),{tracks:e.tracks.map(e=>Object.assign(Object.assign({},e),{instrument:e.instrument&&Object.assign(Object.assign({},e.instrument),{ampEnvelope:Object.assign({},e.instrument.ampEnvelope),pitchEnvelope:e.instrument.pitchEnvelope&&Object.assign({},e.instrument.pitchEnvelope),ampLFO:e.instrument.ampLFO&&Object.assign({},e.instrument.ampLFO),pitchLFO:e.instrument.pitchLFO&&Object.assign({},e.instrument.pitchLFO)}),drums:e.drums&&e.drums.map(e=>Object.assign(Object.assign({},e),{steps:e.steps.map(e=>Object.assign({},e))})),notes:e.notes.map(e=>Object.assign(Object.assign({},e),{notes:e.notes.slice()}))}))})},t.songEquals=function(e,t){return p(e,t)},t.inflateSong=function(e){const t=f(1);e.tracks=t.tracks.map((t,n)=>{const i=e.tracks.find(e=>e.id===n);return i&&(t.notes=i.notes),t})},t.getSongInfo=function(e){return{ticksPerBeat:e.ticksPerBeat,beatsPerMeasure:e.beatsPerMeasure,beatsPerMinute:e.beatsPerMinute,measures:e.measures}},t.getEmptySong=f}(t.music||(t.music={}))}(e.assets||(e.assets={}))}(pxt||(pxt={})),function(e){const t=["name","version","description","license","dependencies","files","testFiles","testDependencies","fileDependencies","public","targetVersions","supportedTargets","preferredEditor","languageRestriction","additionalFilePath","additionalFilePaths"];class n{constructor(e,t,n,i,s){this.id=e,this._verspec=t,this.parent=n,this.depName=s,this.level=-1,this.isLoaded=!1,this.ignoreTests=!1,this.cppOnly=!1,i&&(this.level=i.level+1),this.addedBy=[i]}static stringifyConfig(e){const n=e,i={};for(const e of t)n.hasOwnProperty(e)&&(i[e]=n[e]);for(const e of Object.keys(n))i.hasOwnProperty(e)||(i[e]=n[e]);return JSON.stringify(i,null,4)+"\n"}static parseAndValidConfig(t){const n=e.Util.jsonTryParse(t);return n&&void 0!==n.name&&"string"==typeof n.name&&n.files&&Array.isArray(n.files)&&n.files.every(e=>"string"==typeof e)&&n.dependencies&&Object.keys(n.dependencies).every(e=>"string"==typeof n.dependencies[e])&&n}static async getConfigAsync(t,n,i){if(e.github.isGithubId(i)){const t=e.github.parseRepoId(i),n=await e.packagesConfigAsync();return await e.github.repoAsync(t.fullName,n)?await e.github.pkgConfigAsync(t.fullName,t.tag,n):null}if(i.startsWith("workspace:")){i.slice(10);return null}if(!i.startsWith("pub:")){const s=e.patching.upgradePackageReference(t,n,i),r=e.appTarget.bundledpkgs[s];return JSON.parse(r[e.CONFIG_NAME])}{const t=i.slice(4);try{const n=await e.Cloud.downloadScriptFilesAsync(t);return JSON.parse(n[e.CONFIG_NAME])}catch(t){return e.log(`Unable to fetch files for published script '${i}'`),null}}}static corePackages(){const t=e.appTarget.bundledpkgs;return Object.keys(t).map(n=>JSON.parse(t[n][e.CONFIG_NAME])).filter(e=>!!e)}disablesVariant(e){return this.config&&this.config.disablesVariants&&this.config.disablesVariants.indexOf(e)>=0}invalid(){return/^invalid:/.test(this.version())}version(){return this.resolvedVersion||this._verspec}verProtocol(){let e=this.version().split(":");return e.length>1?e[0]:""}verArgument(){let e=this.verProtocol();return e?this.version().slice(e.length+1):this.version()}targetVersion(){return this.parent&&this.parent!=this?this.parent.targetVersion():this.config.targetVersions?this.config.targetVersions.target:void 0}async commonDownloadAsync(){const t=this.verProtocol();let n;if("pub"==t)n=await e.Cloud.downloadScriptFilesAsync(this.verArgument());else if("github"==t){const t=await e.packagesConfigAsync();n=(await e.github.downloadPackageAsync(this.verArgument(),t)).files}else if("embed"==t)n=e.getEmbeddedScript(this.verArgument());else if("pkg"==t){const t=(this.parent||this).readFile(this.verArgument()),i=e.U.jsonTryParse(t);i||e.log(`unable to find ${this.verArgument()}`),n=i}return n}writeAssetPackFiles(){const t=JSON.parse(JSON.stringify(this.config));t.files=t.files.filter(e=>e.endsWith(".jres")),t.files.push("gallery.ts"),t.dependencies={},t.assetPack=!0,this.config=t,this.saveConfig();let n="";for(const i of t.files){const t=this.readFile(i),s=e.U.jsonTryParse(t);if(s){const[t,r]=e.emitGalleryDeclarations(s,this.getNamespaceName());this.writeFile(i,JSON.stringify(t,null,4)),n+=r}}this.writeFile("gallery.ts",n)}getNamespaceName(){let e=this,t=e.addedBy[0];const n=[];for(;t&&t!==e;)e.depName&&n.push(e.depName),e=t,t=e.addedBy[0];return n.reverse().map(e=>ts.pxtc.escapeIdentifier(e)).join(".")}host(){return this.parent._host}readFile(e){return this.host().readFile(this,e)}writeFile(e,t){this.host().writeFile(this,e,t,!0)}readGitJson(){const t=this.readFile(e.github.GIT_JSON);return e.Util.jsonTryParse(t)}resolveDep(e){return this.parent.deps.hasOwnProperty(e)?this.parent.deps[e]:null}saveConfig(){const t=e.U.clone(this.config);delete t.additionalFilePaths;const n=e.Package.stringifyConfig(t);this.host().writeFile(this,e.CONFIG_NAME,n)}setPreferredEditor(e){this.config.preferredEditor!=e&&(this.config.preferredEditor=e,this.saveConfig())}getPreferredEditor(){let t=this.config.preferredEditor;if(!t){if(!(this.getFiles().indexOf(e.MAIN_BLOCKS)>=0))return e.JAVASCRIPT_PROJECT_NAME;const t=this.readFile(e.MAIN_BLOCKS),n=this.readFile(e.MAIN_TS);return!t&&n?e.JAVASCRIPT_PROJECT_NAME:e.BLOCKS_PROJECT_NAME}return t}parseJRes(t={}){for(const n of this.getFiles())e.U.endsWith(n,".jres")&&i(JSON.parse(this.readFile(n)),t);return t}isAssetPack(){var e;return this.level>0&&!!(null===(e=this.config)||void 0===e?void 0:e.assetPack)}resolveVersionAsync(){var t;let n=this._verspec;if(e.getEmbeddedScript(this.id))this.resolvedVersion=n="embed:"+this.id;else if(n&&"*"!=n){if("github"==this.verProtocol()){const i=e.github.parseRepoId(this._verspec);if(i&&!i.tag&&this.parent){e.debug("dep: unbound github extensions, trying to resolve tag");const s=e.semver.sortLatestTags(e.Util.values((null===(t=this.parent)||void 0===t?void 0:t.deps)||{}).map(t=>e.github.parseRepoId(t.version())).filter(e=>(null==e?void 0:e.slug)===i.slug).map(e=>e.tag)),r=s[0];r&&(i.tag=r,this.resolvedVersion=n=e.github.stringifyRepo(i),e.debug(`dep: github patched ${this._verspec} to ${n}`))}}}else this.configureAsInvalidPackage(lf("version not specified for {0}",this.id)),n=this._verspec;return Promise.resolve(n)}downloadAsync(){return this.resolveVersionAsync().then(t=>{if(this.invalid())e.debug(`skip download of invalid package ${this.id}`);else if(/^embed:/.test(t)||this.installedVersion!=t)return e.debug("downloading "+t),this.host().downloadPackageAsync(this).then(()=>{this.loadConfig(),this.isAssetPack()&&this.writeAssetPackFiles(),e.debug(`installed ${this.id} /${t}`)})})}loadConfig(){if(0!=this.level&&this.invalid())return;const t=this.readFile(e.CONFIG_NAME);t||e.U.userError(`extension ${this.id} is missing ${e.CONFIG_NAME}`),this.parseConfig(t),0!=this.level&&(this.installedVersion=this.version()),this.saveConfig()}validateConfig(){this.config.dependencies||e.U.userError("Missing dependencies in config of: "+this.id),Array.isArray(this.config.files)||e.U.userError("Missing files in config of: "+this.id),"string"==typeof this.config.name&&this.config.name||(this.config.name=lf("Untitled")),this.config.targetVersions&&this.config.targetVersions.target&&this.config.targetVersions.targetId===e.appTarget.id&&e.appTarget.versions&&e.semver.majorCmp(this.config.targetVersions.target,e.appTarget.versions.target)>0&&e.U.userError(lf("{0} requires target version {1} (you are running {2})",this.config.name,this.config.targetVersions.target,e.appTarget.versions.target))}isPackageInUse(t,n=this.readFile(e.MAIN_TS)){let i=null;const s=e.patching.computePatches(this.targetVersion(),"missingPackage");return s&&s.forEach(e=>{Object.keys(e.map).forEach(n=>{e.map[n]===t&&(i=new RegExp(n,"g"))})}),i||(i=new RegExp(t+"\\.","g")),i.test(n)}upgradePackagesAsync(){return this.config||this.loadConfig(),e.packagesConfigAsync().then(async t=>{let n=0,i={};const s=[];return e.U.iterMap(this.config.dependencies,(r,a)=>{s.push((async()=>{if(e.github.isGithubId(a)){const s=await e.github.upgradedPackageReferenceAsync(t,a);s&&s!=a&&(e.log(`upgrading dep ${r}: ${a} -> ${s}`),i[a]=s,this.config.dependencies[r]=s,n++)}})())}),await Promise.all(s),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=>{var n;if(s=t,s){const t=s.yotta?e.U.jsonFlatten(s.yotta.config):null;this.parent.sortedDeps().forEach(n=>{if(s.core&&n.config.core&&s.name!=n.config.name){const t=new e.cpp.PkgConflictError(lf("conflict between core extensions {0} and {1}",s.name,n.id));return t.pkg0=n,void r.push(t)}let 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} (added: {1}, adding: {2})",n.id,n._verspec,i));t.pkg0=n,t.isVersionConflict=!0,r.push(t)}}})}return Object.keys(null!==(n=null==s?void 0:s.dependencies)&&void 0!==n?n:{}).reduce((e,t)=>e.then(()=>this.findConflictsAsync(t,s.dependencies[t])).then(e=>r.push.apply(r,e)),Promise.resolve())}).then(()=>{const t=e=>{const n=[];return e.addedBy.forEach(e=>{e.id!==this.id&&(n.push.apply(t(e)),n.push(e))}),n},n=[];return r.forEach(r=>{n.push.apply(n,t(r.pkg0).map(t=>{const n=new e.cpp.PkgConflictError(r.isVersionConflict?lf("a dependency of {0} has a version mismatch with extension {1} (added: {1}, adding: {2})",t.id,s.name,r.pkg0._verspec,i):lf("conflict on yotta setting {0} between extensions {1} and {2}",r.settingName,s.name,r.pkg0.id));return n.pkg0=t,n}))}),r.push.apply(r,n),r=r.filter((e,t)=>{for(let n=0;n<t;++n)if(e.pkg0.id===r[n].pkg0.id)return!1;return!0}),r})}configureAsInvalidPackage(t){e.log(`invalid package ${this.id}: ${t}`),this._verspec="invalid:"+this.id,this.config={name:this.id,description:t,dependencies:{},files:[]}}parseConfig(t,n){var i;try{const e=JSON.parse(t);this.config=e}catch(t){this.configureAsInvalidPackage(lf("Syntax error in pxt.json")),e.tickEvent("package.invalidConfigEncountered")}const s=JSON.stringify(this.config);(null===(i=this.config)||void 0===i?void 0:i.files)&&(this.config.files=this.config.files.filter(t=>t!==e.HISTORY_FILE&&t!==e.CONFIG_NAME&&"undefined"!==t&&"null"!==t&&!!t));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)!=s&&this.saveConfig(),this.validateConfig()}patchCorePackage(){e.Util.assert(e.appTarget.simulator&&e.appTarget.simulator.dynamicBoardDefinition),e.Util.assert(0==this.level);const t=Object.keys(this.config.dependencies).filter(t=>!!t&&(t==e.BLOCKS_PROJECT_NAME||t==e.JAVASCRIPT_PROJECT_NAME||JSON.parse((e.appTarget.bundledpkgs[t]||{})[e.CONFIG_NAME]||"{}").core));if(0==t.length){const t=e.Package.corePackages();t.length&&this.config.dependencies[t[0].name]}else t.length>1&&(t.pop(),t.forEach(t=>{e.log(`removing core package ${t}`),delete this.config.dependencies[t]}))}resolvedDependencies(){return Object.keys(this.dependencies()).map(e=>this.resolveDep(e))}dependencies(t=!1){if(!this.config)return{};const n=e.Util.clone(this.config.dependencies||{});return 0==this.level&&this.config.testDependencies&&e.Util.iterMap(this.config.testDependencies,(t,i)=>{("*"!=i||e.appTarget.bundledpkgs[t])&&(n[t]=i)}),t&&this.config.cppDependencies&&e.Util.jsonMergeFrom(n,this.config.cppDependencies),n}async loadAsync(t=!1,i){var s;if(this.isLoaded)return;0!=this.level||e.appTarget.multiVariants||e.setAppTargetVariant(null),this.isLoaded=!0;const r=this.readFile(e.CONFIG_NAME);if(null==r?t||e.U.userError("Package not installed: "+this.id+", did you forget to run `pxt install`?"):this.parseConfig(r),t||await this.upgradePackagesAsync(),t&&(await this.downloadAsync(),0!==this.level&&!this.isAssetPack()))for(const e of this.addedBy)if(null===(s=e.config.assetPacks)||void 0===s?void 0:s[this.id]){this.writeAssetPackFiles();break}if(t){const t=await this.upgradePackagesAsync();t&&(Object.keys(t).forEach(t=>e.tickEvent("package.doubleload",{extension:t})),e.log("upgraded, downloading again"),e.debug(t),await this.downloadAsync())}if(e.appTarget.simulator&&e.appTarget.simulator.dynamicBoardDefinition&&(0==this.level&&this.patchCorePackage(),this.config.compileServiceVariant&&e.setAppTargetVariant(this.config.compileServiceVariant),this.config.files.indexOf("board.json")>=0)){const t=e.appTarget.simulator.boardDefinition=JSON.parse(this.readFile("board.json"));t.id=this.config.name,e.appTarget.appTheme.boardName=t.boardName||lf("board"),e.appTarget.appTheme.driveDisplayName=t.driveDisplayName||lf("DRIVE");let n=t=>{let n=/^pkg:\/\/(.*)/.exec(t);if(n){let t=n[1],i=this.readFile(t);return e.U.toDataUri(i,e.U.getMime(t))}return t},i=e.appTarget.simulator.boardDefinition;if("object"==typeof i.visual){let e=i.visual;e.image=n(e.image),e.outlineImage=n(e.outlineImage)}}const 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=r.tag;if(a&&!o)return void e.debug(`unversioned ${n}, using ${a}`);const l=e.semver.strcmp(a,r.tag);if(0==l)return void e.debug(`resolved version are ${a}`);if(l>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);const c=e.github.parseRepoId(l);if(null==c?void 0:c.slug){const t=Object.values(s.parent.deps).map(t=>e.github.parseRepoId(t._verspec)).filter(e=>(null==e?void 0:e.slug)===c.slug).map(e=>e.tag).reduce((t,n)=>e.semver.strcmp(t,n)>0?t:n,"0.0.0");e.debug(`dep: common repo ${c.slug} version found ${t}`),e.semver.strcmp(t,"0.0.0")>0&&(!c.tag||e.semver.strcmp(t,c.tag)>0)&&(e.debug(`dep: upgrade from ${c.tag} to ${t}`),c.tag=t,l=e.github.stringifyRepo(c,!0))}let u=s.resolveDep(o);if(u){if(u.invalid()||u._verspec===l||a(u,l),u.invalid()){u.level=Math.min(u.level,s.level+1),u.addedBy.push(s);continue}r||(u.level=Math.min(u.level,s.level+1),u.addedBy.push(s))}else u=new n(o,l,s.parent,s,o),r&&(u.cppOnly=!0),s.parent.deps[o]=u,s.parent.deps[o.replace(/---.*/,"")]=u,await u.loadAsync(t)}};if(await o(null,this),this.patchAppTargetPalette(),this.config.screenSize&&e.appTarget.runtime&&(e.appTarget.runtime.screenSize=e.U.clone(this.config.screenSize)),0===this.level){const t=this.readFile(e.MAIN_TS);if(t){const n=this.getMissingPackages(this.config,t);let i=!1;for(const t of Object.keys(n)){const s=await this.findConflictsAsync(t,n[t]);if(s.length){const n=s.map(e=>e.pkg0.id).join(", "),i=s.map(e=>e.settingName).filter(e=>!!e).join(", ");e.log(`skipping missing package ${t} because it conflicts with the following packages: ${n} (conflicting settings: ${i})`)}else{e.log(`adding missing package ${t}`),i=!0,this.config.dependencies[t]="*";const s={};s[t]=n[t],await o(s,this)}}i&&(this.saveConfig(),this.validateConfig())}await Promise.all(e.U.values(this.parent.deps).map(e=>o(null,e,!0)))}e.debug(` installed ${this.id}`)}getFiles(){let t;t=0!=this.level||this.ignoreTests?this.config.files.slice(0):this.config.files.concat(this.config.testFiles||[]);const i=this.config.fileDependencies;return this.config.fileDependencies&&(t=t.filter(t=>{const s=i=>{if("!"==(i=i.trim())[0])return!s(i.slice(1));if(/^[\w-]+$/.test(i)){const e=this.parent.resolveDep(i);return!(!e||e.cppOnly)}const r=/^target:(\w+)$/.exec(i);return r?r[1]==e.appTarget.id||r[1]==e.appTarget.platformid:(n.depWarnings[i]||(n.depWarnings[i]=!0,e.log(`invalid dependency expression: ${i} in ${this.id}/${t}`)),!1)},r=e.U.lookup(i,t);return!r||!r.trim()||r.split("||").some(e=>e.split("&&").every(s))})),t}addSnapshot(t,n=[""]){for(let i of this.getFiles())n.some(t=>e.U.endsWith(i,t))&&(t[this.id+"/"+i]=this.readFile(i));t[this.id+"/"+e.CONFIG_NAME]=this.readFile(e.CONFIG_NAME)}packageLocalizationStringsAsync(t){const n=e.appTarget.id,i=[this.config.name+"-jsdoc",this.config.name],s={};e.appTarget.appTheme;return this.config.skipLocalization?Promise.resolve(s):e.Util.liveLocalizationEnabled()&&"this"!=this.id&&e.appTarget.bundledpkgs[this.id]?(e.debug(`loading live translations for ${this.id}`),Promise.all(i.map(i=>e.Util.downloadLiveTranslationsAsync(t,`${n}/${i}-strings.json`).then(n=>{n&&Object.keys(n).length?e.Util.jsonMergeFrom(s,n):(e.tickEvent("translations.livetranslationsfailed",{filename:i}),e.Util.jsonMergeFrom(s,this.bundledStringsForFile(t,i)))}).catch(r=>{e.tickEvent("translations.livetranslationsfailed",{filename:i}),e.log(`error while downloading ${n}/${i}-strings.json`),e.Util.jsonMergeFrom(s,this.bundledStringsForFile(t,i))}))).then(()=>s)):(i.map(e=>this.bundledStringsForFile(t,e)).filter(e=>!!e).forEach(t=>e.Util.jsonMergeFrom(s,t)),Promise.resolve(s))}bundledStringsForFile(t,n){let i={},[s,r,a]=e.Util.normalizeLanguageCode(t);const o=this.config.files;let l=`_locales/${s}/${n}-strings.json`;if(a&&-1===o.indexOf(l)&&(l=`_locales/${a}/${n}-strings.json`),r&&-1===o.indexOf(l)&&(l=`_locales/${r}/${n}-strings.json`),o.indexOf(l)>-1)try{i=JSON.parse(this.readFile(l))}catch(n){e.reportError("extension","Extension localization JSON failed to parse",{fileName:l,lang:t,extension:this.verArgument()});"github"===this.verProtocol()&&e.tickEvent("loc.errors.json",{repo:this.verArgument(),file:l})}return i}patchAppTargetPalette(){this.config.palette&&e.appTarget.runtime&&(e.appTarget.runtime.palette=e.U.clone(this.config.palette),this.config.paletteNames&&(e.appTarget.runtime.paletteNames=this.config.paletteNames))}}n.depWarnings={},e.Package=n;function i(e,t={}){let n=e["*"]||{};for(let i of Object.keys(e)){if("*"==i)continue;let s=e[i];"string"==typeof s&&(s={data:s});let r=s.namespace||n.namespace||"";r&&!r.endsWith(".")&&(r+=".");let 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,tags:s.tags}}return t}e.MainPackage=class extends n{constructor(e){super("this","file:.",null,null,null),this._host=e,this.deps={},this.parent=this,this.addedBy=[this],this.level=0,this.deps[this.id]=this}installAllAsync(e){return this.loadAsync(!0,e)}sortedDeps(t=!1){let n={},i=[];const s=e=>e.config?Object.keys(e.config.cppDependencies||{}).length:0,r=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()){var n;let i={sourceFiles:[],fileSystem:{},target:t,name:this.config?this.config.name:""};const s=(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))},r=e.appTarget.disabledVariants;let a=!1;const o=async n=>{const i={extinfo:null,target:null},r=e.appTargetVariant;let o;n&&e.setAppTargetVariant(n,{temporary:!0});try{i.target=e.appTarget.compile,o=e.cpp.getExtensionInfo(this),a||!o.shimsDTS&&!o.enumsDTS||(a=!0,o.shimsDTS&&s("shims.d.ts",o.shimsDTS),o.enumsDTS&&s("enums.d.ts",o.enumsDTS))}finally{n&&e.setAppTargetVariant(r,{temporary:!0})}o.appVariant=n;const l=t.isNative?await this.host().getHexInfoAsync(o):null;return o=e.U.flatClone(o),t.keepCppFiles||(delete o.compileData,delete o.generatedFiles,delete o.extensionFiles),o.hexinfo=l,i.extinfo=o,i};let l;await this.loadAsync(),i.bannedCategories=this.resolveBannedCategories(),e.debug(`building: ${this.sortedDeps().map(e=>{var t;return null===(t=e.config)||void 0===t?void 0:t.name}).join(", ")}`),e.appTarget.multiVariants?(l=e.appTargetVariant?[e.appTargetVariant]:e.appTarget.alwaysMultiVariant||e.appTarget.compile.switches.multiVariant?e.appTarget.multiVariants:[e.appTarget.multiVariants[0]],!e.appTarget.alwaysMultiVariant&&r&&(l=l.filter(e=>!r.includes(e)))):l=[null];let c=null;await Promise.all(l.map(async t=>{c&&e.debug(`building for ${t}`);const n=await o(t),s=n.extinfo;s.appVariant=t,s.outputPrefix=1!=l.length&&t?t+"-":"",(null==r?void 0:r.indexOf(t))>-1&&(s.disabledDeps=s.disabledDeps||"user-disabled"),c?i.otherMultiVariants.push(n):(n.target.isNative=i.target.isNative,i.target=n.target,c=s,i.otherMultiVariants=[])})),i.extinfo=c,i.target.preferredEditor=this.getPreferredEditor();if(!(e.appTarget.compile.shortPointers||"vm"==e.appTarget.compile.nativeType||this.config.binaryonly||!i.target.isNative)){const t=await this.filesToBePublishedAsync(!0),n=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(n+s);r&&(i.embedMeta=JSON.stringify({compression:"LZMA",headerSize:n.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}),i.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 n=t;e.level>0&&(n="pxt_modules/"+e.id+"/"+t),i.sourceFiles.push(n),i.fileSystem[n]=e.readFile(t)}i.jres=this.getJRes();const u=e.appTarget.runtime&&e.appTarget.runtime.functionsOptions;i.allowedArgumentTypes=u&&u.extraFunctionEditorTypes&&u.extraFunctionEditorTypes.map(e=>e.typeName).concat("number","boolean","string"),i.unfetteredInitializers=null===(n=e.appTarget.compile)||void 0===n?void 0:n.unfetteredInitializers;for(const e of this.sortedDeps())e.patchAppTargetPalette();return this.patchAppTargetPalette(),i}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.files=t.files.filter(t=>t!==e.HISTORY_FILE),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||t===e.HISTORY_FILE)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!!(null==n?void 0:n.isConnected())},t.isConnecting=function(){return!!(null==n?void 0:n.isConnecting())},t.icon=function(){var t;return!!n&&(n.icon||(null===(t=e.appTarget.appTheme.downloadDialogTheme)||void 0===t?void 0:t.deviceIcon)||"usb")},t.unsupportedParts=function(){return(null==n?void 0:n.unsupportedParts)?n.unsupportedParts():[]},t.deviceVariant=function(){return null==n?void 0:n.devVariant},t.disconnectAsync=l,t.configureEvents=function(e,t,i){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){function n(t,n,i){const s=e.semver.tryParse(t||"0.0.0")||e.semver.tryParse("0.0.0");let r=[];return Object.keys(n).filter(t=>e.semver.inRange(t,s)).forEach(e=>r=r.concat(n[e])),i&&(r=r.filter(e=>e.type==i)),r.length?r:void 0}function i(e,t,n){let i=t;return n&&(n.filter(e=>"api"===e.type).forEach(e=>{Object.keys(e.map).forEach(t=>{const n=new RegExp(t,"g");i=i.replace(n,e.map[t])})}),n.filter(e=>"userenum"===e.type).forEach(e=>{Object.keys(e.map).forEach(t=>{const n=new RegExp("enum\\s+"+t+"\\s*{","gm");i=i.replace(n,`enum ${e.map[t]} {`);const s=new RegExp(`(^|[^_a-zA-Z0-9])${t}(\\s*\\.)`,"g");i=i.replace(s,`$1${e.map[t]}$2`)})})),i}t.computePatches=function(t,i){const s=e.appTarget.compile?e.appTarget.compile.patches:void 0;if(s)return n(t,s,i)},t.computePyPatches=function(t,i){const s=e.appTarget.compile?e.appTarget.compile.pyPatches:void 0;if(s)return n(t,s,i)},t.upgradePackageReference=function(t,n,i){if("*"!=i)return n;const s=e.patching.computePatches(t,"package");let r=n;return s&&s.forEach(e=>{Object.keys(e.map).forEach(t=>{r==t&&(r=e.map[t])})}),r},t.patchJavaScript=function(t,n){return i(t,n,e.patching.computePatches(t))},t.patchPython=function(t,n){return i(t,n,e.patching.computePyPatches(t))}}(e.patching||(e.patching={}))}(pxt||(pxt={})),function(e){e.react||(e.react={})}(pxt||(pxt={})),function(e){!function(t){function n(t,n){if(t){if(n){let i=t.major-n.major||t.minor-n.minor||t.patch-n.patch;if(i)return i;if(0==t.pre.length&&n.pre.length>0)return 1;if(t.pre.length>0&&0==n.pre.length)return-1;for(let s=0;s<t.pre.length+1;++s){let r=t.pre[s],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.bump=function(t,n){let s=i(r(t));switch(n){case"major":s.major++,s.minor=0,s.patch=0;break;case"minor":s.minor++,s.patch=0;break;case"patch":s.patch++;break;default:s=e.semver.parse(n)}return s},t.test=function(){e.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]);e.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]));e.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}function n(t,n){const i=pxt.Util.translationsCache();i[e.BLOCK_TRANSLATION_CACHE_KEY]||(i[e.BLOCK_TRANSLATION_CACHE_KEY]={}),i[e.BLOCK_TRANSLATION_CACHE_KEY][t]=n}function i(t){const n=pxt.Util.translationsCache();n[e.BLOCK_TRANSLATION_CACHE_KEY]&&delete n[e.BLOCK_TRANSLATION_CACHE_KEY][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.BLOCK_TRANSLATION_CACHE_KEY="_blocks",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,n=!1){if(!e.usedSymbols||!pxt.appTarget.simulator||!n&&!pxt.appTarget.simulator.parts)return[];const i=(e,t)=>{if(e){const n=e.split(/[ ,]+/g);t.push(...n.filter(e=>!!e&&t.indexOf(e)<0))}};let s=[],r=[];if(Object.keys(e.usedSymbols).forEach(t=>{const n=e.usedSymbols[t];i(null==n?void 0:n.attributes.parts,s),i(null==n?void 0:n.attributes.hiddenParts,r)}),t){const e=pxt.appTarget.simulator.boardDefinition.onboardComponents;e&&("ignorebuiltin"===t?s=s.filter(t=>-1===e.indexOf(t)):"onlybuiltin"===t&&(s=s.filter(t=>e.indexOf(t)>=0)))}return s=s.filter(e=>r.indexOf(e)<0),s.sort(),s=s.reverse(),s},e.buildSimJsInfo=function(t){var n;return{js:t.outfiles[e.BINARY_JS],targetVersion:pxt.appTarget.versions.target,fnArgs:t.usedArguments,parts:e.computeUsedParts(t,"ignorebuiltin"),usedBuiltinParts:e.computeUsedParts(t,"onlybuiltin"),allParts:e.computeUsedParts(t,void 0,!0),breakpoints:null===(n=t.breakpoints)||void 0===n?void 0:n.map(e=>e.id)}},e.blocksCategory=function(t){const n=t?t.attributes.blockNamespace||t.namespace:void 0;return n?e.Util.capitalize(n.split(".")[0]):void 0},e.getBlocksInfo=function(t,n){var i,s;let r=[];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||""}`,m=`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?`%${f} %property`:s?e.U.lf("set %{0} %property to %{1}",f,m):e.U.lf("change %{0} %property by %{1}",f,m),o(p.attributes),pxt.Util.isTranslationMode()&&(p.attributes.translationId=p.attributes.block,p.attributes.block=i?`%${f} %property`:s?`set %${f} %property to %${m}`:`change %${f} %property by %${m}`,o(p.attributes),pxt.crowdin.inContextLoadAsync(p.attributes.translationId).then(e=>{p.attributes.block=e,o(p.attributes)})),r.push(p)}function f(e){n.attributes[e]&&(p.attributes[e]?p.attributes[e]!==n.attributes[e]&&pxt.debug(`Ignoring duplicate ${e} for get/set/change block: ${n.attributes[e]}`):p.attributes[e]=n.attributes[e])}f("blockCombineChangeHelp"),f("blockCombineGetHelp"),f("blockCombineSetHelp"),f("help"),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]&&(pxt.warn(`Enum block ${n.attributes.blockId} trying to overwrite enum ${n.attributes.enumName}`),e=!0),n.attributes.enumMemberName||(pxt.warn(`Enum block ${n.attributes.blockId} should specify enumMemberName`),e=!0),n.attributes.enumPromptHint||(pxt.warn(`Enum block ${n.attributes.blockId} should specify enumPromptHint`),e=!0),n.attributes.enumInitialMembers&&n.attributes.enumInitialMembers.length||(pxt.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]){pxt.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&&!n.attributes.blockIdentity){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 r=null!==(s=null===(i=n.parameters)||void 0===i?void 0:i.filter(e=>!a(e)))&&void 0!==s?s:[];for(let e of r)t+=" %"+e.name;n.attributes.block=t,o(n.attributes)}r.push(n)}}for(let n of r){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&&(r=r.filter(e=>{let t=(e.attributes.blockNamespace||e.namespace).split(".")[0];return-1===f.indexOf(t)}))),{apis:t,blocks:r,blocksById:pxt.Util.toDictionary(r,e=>e.attributes.blockId),enumsByName:d,kindsByName:h}},e.tsSnippetToPySnippet=function(t,n){const i={true:"True",false:"False",null:"None"}[t];if(i)return i;if(n&&6==n.kind||!n&&t.includes(".")){const n=t.lastIndexOf("."),i=t.substr(0,n);let s=t.substr(n+1);return s=e.U.snakify(s).toUpperCase(),i?`${i}.${s}`:s}return t},e.apiLocalizationStrings={},e.localizeApisAsync=async function(s,r){const a=e.Util.userLanguage();if("en"==a)return Promise.resolve(t(s));const l=a.toLowerCase(),c=l+"|jsdoc",u=l+"|block",d=await r.localizationStringsAsync(a);e.apiLocalizationStrings&&e.Util.jsonMergeFrom(d,e.apiLocalizationStrings);const h=e.Util.values(s.byQName).filter(e=>e.attributes._translatedLanguageCode!==a);return await e.Util.promiseMapAll(h,async t=>{var r,h,p;const f=t.attributes.useLoc||t.attributes.blockAliasFor,m=f&&s.byQName[f];t.attributes._untranslatedJsDoc&&(t.attributes.jsDoc=t.attributes._untranslatedJsDoc),t.attributes._untranslatedBlock&&(t.attributes.jsDoc=t.attributes._untranslatedBlock);const g=(e,n)=>{var i,s;return d[t.qName+e]||(null===(i=t.attributes.locs)||void 0===i?void 0:i[n])||m&&(d[m.qName+e]||(null===(s=m.attributes.locs)||void 0===s?void 0:s[n]))},b=g("",c);b&&(t.attributes._untranslatedJsDoc||(t.attributes._untranslatedJsDoc=t.attributes.jsDoc),t.attributes.jsDoc=b),null===(r=t.parameters)||void 0===r||r.forEach(e=>{const t=`|param|${e.name}`,n=g(t,l+t);n&&(e.description=n)});const y=d["{id:category}"+e.Util.capitalize(t.qName)];let v=d[`${t.qName}|block`]||(null===(h=t.attributes.locs)||void 0===h?void 0:h[u]);if(t.attributes.block){const e=pxt.blocks.compileInfo(t);if(e.handlerArgs)for(const t of e.handlerArgs)d[t.localizationKey]?n(t.localizationKey,d[t.localizationKey]):i(t.localizationKey)}if(!v&&m){const e=d[`${m.qName}|block`]||(null===(p=m.attributes.locs)||void 0===p?void 0:p[u]);t.attributes.block===(m.attributes._untranslatedBlock||m.attributes.block)&&e&&(v=e)}if(v&&pxt.Util.isTranslationMode()&&(t.attributes.translationId=v,v=await pxt.crowdin.inContextLoadAsync(v)),y)t.attributes.block?t.attributes.block=v||t.attributes.block:t.attributes.block=y,o(t.attributes);else if(t.attributes.block&&v){const e=pxt.blocks.compileInfo(t),n=t.attributes.block;if(t.attributes.block=pxt.blocks.normalizeBlock(v,e=>{pxt.tickEvent("loc.normalized",{block:t.attributes.block,lang:a,error:e})}),t.attributes._untranslatedBlock||(t.attributes._untranslatedBlock=n),n!=t.attributes.block){o(t.attributes);(function(e,t){if(e.parameters.length!=t.parameters.length)return pxt.debug("Localized block has extra or missing parameters"),!1;for(const n of e.parameters){const e=t.actualNameToParam[n.actualName];if(!e||n.type!=e.type||n.shadowBlockId!=e.shadowBlockId||n.definitionName!=e.definitionName)return pxt.debug(`Parameter ${n.actualName} type, shadow block, or definition name does not match after localization`),!1}return!0})(e,pxt.blocks.compileInfo(t))||(pxt.reportError("loc.errors","block has non matching arguments",{block:t.attributes.blockId,lang:a,originalDefinition:n,translatedBlock:t.attributes.block}),pxt.tickEvent("loc.errors",{block:t.attributes.blockId,lang:a}),t.attributes.block=n,o(t.attributes))}}else o(t.attributes);t.attributes._translatedLanguageCode=a}),t(s)},e.getBlockTranslationsCacheKey=function(t){const n=pxt.Util.translationsCache();if(n[e.BLOCK_TRANSLATION_CACHE_KEY])return n[e.BLOCK_TRANSLATION_CACHE_KEY][t]},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 s=["weight","imageLiteral","gridLiteral","topblockWeight","inlineInputModeLimit"],r=["advanced","handlerStatement","forceStatement","afterOnStart","optionalVariableArgs","blockHidden","constantShim","blockCombine","enumIsBitMask","enumIsHash","decompileIndirectFixedInstances","topblock","callInDebugger","duplicateShadowOnDrag","argsNullable","compileHiddenArguments","expandArgumentsInToolbox"];function a(e){return"Action"===e.type||/^\([^\)]*\)\s*=>/.test(e.type)}function o(e){if(e.block){const n=e.block.split("||");e._def=t(l(n[0])),e._def||pxt.debug("Unable to parse block def for id: "+e.blockId),n[1]&&(e._expandedDef=t(l(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 l(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=[],o=0,l="",u=[];for(let e=0;e<t.length;e++){const n=t[e].kind,i=a[a.length-1];if(15&n)if(m(t[e].content),n&o)if(i&n){a.pop(),o^=n;const e=i&o|n&o;e&&a.push(e)}else p();else o|=n,a.push(n);else 144&n?l+=t[e].content:1120&n&&f();if(64==n){const n={kind:"param",name:t[e].content,shadowBlockId:t[e].type,ref:!1};t[e].name&&(n.varName=t[e].name),s.push(n),r.push(n)}else if(1024==n){const n={kind:"param",name:t[e].content,shadowBlockId:t[e].type,ref:!0};t[e].name&&(n.varName=t[e].name),s.push(n),r.push(n)}else 256==n?(m(),u.push({kind:"image",uri:t[e].content})):512==n?(m(),u.push({kind:"label",text:t[e].content,cssClass:t[e].type})):32==n&&s.push({kind:"break"})}return f(),{parts:s,parameters:r};function d(t,n=!1){let s="";for(n&&i++;i<e.length&&t(e[i]);)s+=e[i],++i;return s&&i--,s}function h(t){const n=d(e=>e!==t,!0);if(e[i+1]===t)return++i,n}function p(){let e="",t=[];for(const n of u)c(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=[],o=0}function f(){for(m(),o&&p();u.length;){const e=u.shift();if(c(e))s.push(e);else{if(!e.content)continue;const t=[];10&e.styles&&t.push("bold"),5&e.styles&&t.push("italics"),s.push({kind:"label",text:e.content,style:t})}}}function m(e){u.push({content:l,styles:o,endingToken:e}),l=""}}function c(e){return!!e.kind}let u;e.parseCommentString=function(t){let n={paramDefl:{},callingConvention:0,_source:t},i=!0;for(;i;)i=!1,t=t.replace(/\/\/%[ \t]*([\w\.-]+)(=(("[^"\n]*")|'([^'\n]*)'|([^\s]*)))?/,(t,s,r,a,o,l,c)=>{let u=o?JSON.parse(o):r?o||l||c:"true";if(u||(u=""),e.U.startsWith(s,"block.loc."))n.locs||(n.locs={}),n.locs[s.slice(10).toLowerCase()+"|block"]=u;else if(e.U.startsWith(s,"jsdoc.loc."))n.locs||(n.locs={}),n.locs[s.slice(10).toLowerCase()+"|jsdoc"]=u;else if(e.U.contains(s,".loc.")){n.locs||(n.locs={});const e=s.slice(0,s.indexOf(".loc.")),t=s.slice(s.indexOf(".loc.")+5);n.locs[t+"|param|"+e]=u}else if(e.U.endsWith(s,".defl"))u.indexOf(" ")>-1?n.paramDefl[s.slice(0,s.length-5)]=`"${u}"`:n.paramDefl[s.slice(0,s.length-5)]=u,n.explicitDefaults||(n.explicitDefaults=[]),n.explicitDefaults.push(s.slice(0,s.length-5));else if(e.U.endsWith(s,".shadow"))n._shadowOverrides||(n._shadowOverrides={}),n._shadowOverrides[s.slice(0,s.length-7)]=u;else if(e.U.endsWith(s,".snippet")){n.paramSnippets||(n.paramSnippets={});const e=s.slice(0,s.length-8);n.paramSnippets[e]||(n.paramSnippets[e]={}),n.paramSnippets[e].ts=u}else if(e.U.endsWith(s,".pySnippet")){n.paramSnippets||(n.paramSnippets={});const e=s.slice(0,s.length-10);n.paramSnippets[e]||(n.paramSnippets[e]={}),n.paramSnippets[e].python=u}else if(e.U.endsWith(s,".fieldEditor"))n.paramFieldEditor||(n.paramFieldEditor={}),n.paramFieldEditor[s.slice(0,s.length-12)]=u;else if(e.U.contains(s,".fieldOptions.")){n.paramFieldEditorOptions||(n.paramFieldEditorOptions={});const e=s.slice(0,s.indexOf(".fieldOptions.")),t=s.slice(s.indexOf(".fieldOptions.")+14,s.length);n.paramFieldEditorOptions[e]||(n.paramFieldEditorOptions[e]={}),n.paramFieldEditorOptions[e][t]=u}else if(e.U.contains(s,".shadowOptions.")){n.paramShadowOptions||(n.paramShadowOptions={});const e=s.slice(0,s.indexOf(".shadowOptions.")),t=s.slice(s.indexOf(".shadowOptions.")+15,s.length);n.paramShadowOptions[e]||(n.paramShadowOptions[e]={}),n.paramShadowOptions[e][t]=u}else e.U.endsWith(s,".min")?(n.paramMin||(n.paramMin={}),n.paramMin[s.slice(0,s.length-4)]=u):e.U.endsWith(s,".max")?(n.paramMax||(n.paramMax={}),n.paramMax[s.slice(0,s.length-4)]=u):n[s]=u;return i=!0,"//% "});for(let e of s)"string"==typeof n[e]&&(n[e]=parseInt(n[e]));for(let e of r)"string"==typeof n[e]&&(n[e]="true"==n[e]||"1"==n[e]);if(n.trackArgs&&(n.trackArgs=n.trackArgs.split(/[ ,]+/).map(e=>parseInt(e)||0)),n.enumInitialMembers&&(n.enumInitialMembers=n.enumInitialMembers.split(/[ ,]+/)),n.blockExternalInputs&&!n.inlineInputMode&&(n.inlineInputMode="external"),n.paramHelp={},n.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,i)=>{if(n.paramHelp[t]=i,!n.paramDefl[t]){let e=/\beg\.?:\s*(.+)/.exec(i);if(e&&e[1]){let i=/(?:"([^"]*)")|(?:'([^']*)')|(?:([^\s,]+))/g.exec(e[1]);if(i){let e=i[1]||i[2]||i[3];e||(e=""),e.indexOf(" ")>-1?n.paramDefl[t]=`"${e}"`:n.paramDefl[t]=e}}}return""}),n.jsDoc+=t,"")),n.jsDoc=n.jsDoc.trim(),n.async&&(n.callingConvention=1),n.promise&&(n.callingConvention=2),n.jres&&(n.whenUsed=!0),n.subcategories)try{n.subcategories=JSON.parse(n.subcategories)}catch(e){n.subcategories=void 0}if(n.groups)try{n.groups=JSON.parse(n.groups)}catch(e){n.groups=void 0}if(n.groupIcons)try{n.groupIcons=JSON.parse(n.groupIcons)}catch(e){n.groupIcons=void 0}if(n.groupHelp)try{n.groupHelp=JSON.parse(n.groupHelp)}catch(e){n.groupHelp=void 0}return o(n),n},e.parameterTypeIsArrowFunction=a,e.updateBlockDef=o,e.parseBlockDefinition=l,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=void 0){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)}}}}(u=e.UF2||(e.UF2={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){!function(e){let t;!function(e){e[e.Bundled=1]="Bundled",e[e.Github=2]="Github",e[e.ShareScript=3]="ShareScript"}(t=e.ExtensionType||(e.ExtensionType={}))}(e.service||(e.service={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){let n,i,s;!function(e){e[e.IDE=0]="IDE",e[e.Sandbox=1]="Sandbox",e[e.Widget=2]="Widget",e[e.Controller=3]="Controller"}(n=t.EditorLayoutType||(t.EditorLayoutType={})),function(e){e[e.None=0]="None",e[e.Basic=1]="Basic",e[e.App=2]="App"}(i=t.ControllerMode||(t.ControllerMode={}));let r=i.None,a=!1,o=!1;function l(){if(void 0===s){if(e.BrowserUtils.hasWindow()){const t=/sandbox=1|#sandbox|#sandboxproject/i.test(window.location.href)||e.BrowserUtils.isIFrame(),l=/nosandbox=1/i.test(window.location.href),c=/controller=(0|1|2)/i.exec(window.location.href);c&&e.BrowserUtils.isIFrame()&&(r=parseInt(c[1]));const u=r!==i.None,d=/readonly=1/i.test(window.location.href),h=/editorlayout=(widget|sandbox|ide)/i.exec(window.location.href),p=/noproject=1/i.test(window.location.href);if(s=n.IDE,l?s=n.Widget:u?s=n.Controller:t&&(s=n.Sandbox),u&&d&&(a=!0),u&&p&&(o=!0),h)switch(h[1].toLowerCase()){case"widget":s=n.Widget;break;case"sandbox":s=n.Sandbox;break;case"ide":s=n.IDE}}else s=n.Sandbox;e.debug(`shell: layout type ${n[s]}, readonly ${d()}`)}}function c(){return l(),s==n.Sandbox}function u(){return/[?&]timeMachine=1/i.test(window.location.href)}function d(){return!e.BrowserUtils.hasWindow()||u()||c()&&!/[?&]edit=1/i.test(window.location.href)||h()&&a}function h(){return l(),s==n.Controller}t.layoutTypeClass=function(){return l(),e.shell.EditorLayoutType[s].toLowerCase()},t.isSandboxMode=c,t.isTimeMachineEmbed=u,t.isReadOnly=d,t.isNoProject=function(){return o},t.isControllerMode=h,t.getControllerMode=function(){return l(),r},t.isPyLangPref=function(){return"py"==e.storage.getLocal("editorlangpref")},t.getEditorLanguagePref=function(){return e.storage.getLocal("editorlangpref")},t.setEditorLanguagePref=function(t){t.match(/prj$/)&&(t=t.replace(/prj$/,"")),e.storage.setLocal("editorlangpref",t)},t.getToolboxAnimation=function(){return e.storage.getLocal("toolboxanimation")},t.setToolboxAnimation=function(){e.storage.setLocal("toolboxanimation","1")},t.hasHomeScreen=function(){return!e.shell.isControllerMode()&&!e.appTarget.appTheme.lockedEditor}}(e.shell||(e.shell={}))}(pxt||(pxt={})),function(e){!function(t){t.USER_VERSION="0.0.1";class n{constructor(){this.db=new e.BrowserUtils.IDBWrapper(n.databaseName,n.version,(e,t)=>{const i=t.result;e.oldVersion<1&&(i.createObjectStore(n.projectTable,{keyPath:n.projectKey}),i.createObjectStore(n.userTable,{keyPath:n.userKey}))})}initAsync(){return this.db.openAsync()}getAllProjectsAsync(){return this.db.getAllAsync(n.projectTable).then(e=>e.map(e=>e.project).filter(e=>!e.deleted))}deleteProjectAsync(e){return this.getProjectAsync(e).then(e=>{e.deleted=!0,this.saveProjectAsync(e)})}getProjectAsync(e){return this.db.getAsync(n.projectTable,e).then(e=>null==e?void 0:e.project)}saveProjectAsync(e){return this.db.setAsync(n.projectTable,{id:e.header.id,project:e})}getUserStateAsync(){return this.db.getAsync(n.userTable,"local-user").then(e=>null==e?void 0:e.user)}saveUserStateAsync(e){return this.db.setAsync(n.userTable,{id:"local-user",user:e})}}n.version=6,n.databaseName="local-skill-map",n.projectTable="projects",n.projectKey="id",n.userTable="users",n.userKey="id",t.IndexedDBWorkspace=n}(e.skillmap||(e.skillmap={}))}(pxt||(pxt={})),function(e){!function(e){e.MAX_FREQUENCY=5e3,e.MAX_VOLUME=255,e.renderSoundPath=function(i,s,r){let{startFrequency:a,endFrequency:o,startVolume:l,endVolume:c,wave:u,interpolation:d}=i;a=Math.max(Math.min(a,e.MAX_FREQUENCY),1),o=Math.max(Math.min(o,e.MAX_FREQUENCY),1),l=Math.max(Math.min(l,e.MAX_VOLUME),0),c=Math.max(Math.min(c,e.MAX_VOLUME),0);const h=new t(a+o+1);let p;switch(d){case"linear":p=e=>a+e*(o-a)/s;break;case"curve":p=e=>a+(o-a)*Math.sin(e/s*(Math.PI/2));break;case"logarithmic":p=e=>a+Math.log10(1+e/s*9)*(o-a)}"noise"===u&&(p=()=>h.randomRange(500,5e3));const f=t=>Math.max(Math.min((c-l)/s*t+l,e.MAX_VOLUME),0),m=s/2,g=t=>t/e.MAX_VOLUME*(r-2)/2,b=t=>(1-t/e.MAX_FREQUENCY)*(m-10)+10,y=["M 2 "+r/2];let v=0;for(;v<s;)y.push(n(g(f(v)),b(p(v))/2,u,!1,h)),v+=b(p(v))/2,y.push(n(g(f(v)),b(p(v))/2,u,!0,h)),v+=b(p(v))/2;return y.join(" ")},e.renderWaveSnapshot=function(i,s,r,a,o,l){const c=new t(i);"noise"===r&&(i=c.randomRange(500,5e3)),i=Math.max(Math.min(i,e.MAX_FREQUENCY),1);const u=s/e.MAX_VOLUME*(o-2)/2,d=a/(i*l/1e3)/2;let h=Math.ceil(a/(2*d));h%2==1&&h++;const p=[`M ${a/2-h*d} ${o/2}`];let f=0;for(let e=0;e<h;e++)p.push(n(u,d,r,!1,c)),f+=d,p.push(n(u,d,r,!0,c)),f+=d;return p.join(" ")};class t{constructor(e){this.seed=e,this.lfsr=e}next(){return(this.lfsr=this.lfsr>>1^46080&-(1&this.lfsr))/65535}randomRange(e,t){return e+(t-e)*this.next()}}function n(e,t,n,i,s){switch(n){case"triangle":return`l ${t/2} ${i?e:-e} l ${t/2} ${i?-e:e}`;case"square":return`v ${i?e:-e} h ${t} v ${i?-e:e}`;case"sawtooth":return i?`l ${t} ${e} v ${-e}`:`v ${-e} l ${t} ${e}`;case"sine":return`q ${t/2} ${1.9*(i?e:-e)} ${t} 0`;case"noise":const n=[],r=[],a=Math.min(4,t/4);let o=i;for(let n=0;n<t;n+=a)r.push(s.randomRange(0,e)*(o?1:-1)),o=!o;r[0]=i?e:-e,r[r.length-1]=0;let l=0,c=0;for(const e of r){let i=Math.min(a,t-c);if(n.push(`v ${e-l} h ${i}`),l=e,c+=i,c>=t)break}return n.join(" ")}}function i(e){switch(e){case"square":return 15;case"sine":return 3;case"triangle":return 1;case"noise":return 18;case"sawtooth":return 2}}function s(e,t,n){const i=new Uint8Array(2);new Uint16Array(i.buffer)[0]=0|n,e[t]=i[0],e[t+1]=i[1]}e.soundToInstructionBuffer=function(t,n,r){const{startFrequency:a,endFrequency:o,startVolume:l,endVolume:c,interpolation:u,duration:d}=t,h=[];if("linear"===t.interpolation&&"none"===t.effect)h.push({frequency:a,volume:l/e.MAX_VOLUME*1024}),h.push({frequency:o,volume:c/e.MAX_VOLUME*1024});else{n=Math.min(n,Math.floor(d/5));const i=t=>(l+t*(c-l)/d)/e.MAX_VOLUME*1024;let s;switch(u){case"linear":s=e=>a+e*(o-a)/d;break;case"curve":s=e=>a+(o-a)*Math.sin(e/d*(Math.PI/2));break;case"logarithmic":s=e=>a+Math.log10(1+e/d*9)*(o-a)}const p=d/n;for(let e=0;e<n;e++){const n={frequency:Math.max(s(e*p),1),volume:i(e*p)};"tremolo"===t.effect?n.volume=e%2==0?Math.max(n.volume-500*r,0):Math.min(n.volume+500*r,1023):"vibrato"===t.effect?n.frequency=e%2==0?Math.max(n.frequency-100*r,1):n.frequency+100*r:"warble"===t.effect&&(n.frequency=e%2==0?Math.max(n.frequency-1e3*r,1):n.frequency+1e3*r),h.push(n)}}const p=new Uint8Array(12*(h.length-1)),f=Math.floor(d/(h.length-1));for(let e=0;e<h.length-1;e++){const n=12*e;p[n]=i(t.wave),s(p,n+2,h[e].frequency),s(p,n+4,f),s(p,n+6,h[e].volume),s(p,n+8,h[e+1].volume),s(p,n+10,h[e+1].frequency)}return p}}(e.assets||(e.assets={}))}(pxt||(pxt={})),function(e){!function(t){t.createStreamAsync=function(t,n){return e.Cloud.privatePostAsync("streams",{target:t,name:n||"data"}).then(e=>e)},t.postPayloadAsync=function(t,n){return e.Util.assert(!!t.privatekey),e.Cloud.privatePostAsync(`${t.id}/data?privatekey=${t.privatekey}`,n)}}(e.streams||(e.streams={}))}(pxt||(pxt={})),function(e){!function(t){let n,i;!function(e){e[e.userSpaceOnUse=0]="userSpaceOnUse",e[e.objectBoundingBox=1]="objectBoundingBox"}(n=t.PatternUnits||(t.PatternUnits={})),function(e){e[e.em=0]="em",e[e.ex=1]="ex",e[e.px=2]="px",e[e.in=3]="in",e[e.cm=4]="cm",e[e.mm=5]="mm",e[e.pt=6]="pt",e[e.pc=7]="pc",e[e.percent=8]="percent"}(i=t.LengthUnit||(t.LengthUnit={}));class s{constructor(e){this.el=T(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=T("title"),this.el.firstChild?this.el.insertBefore(this.titleElement,this.el.firstChild):this.el.appendChild(this.titleElement)),this.titleElement.textContent=e}setVisible(e){return this.setAttribute("visibility",e?"visible":"hidden")}}t.BaseElement=s;class r extends s{draw(e){const t=function(e){switch(e){case"text":return new d;case"circle":return new p;case"rect":return new h;case"line":return new f;case"polygon":return new b;case"polyline":return new g;case"path":return new y;default:return new u(e)}}(e);return this.el.appendChild(t.el),t}element(e,t){return t(this.draw(e)),this}group(){const e=new 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 A;break;case"linearGradient":n=new w;break;case"clipPath":n=new k;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 m extends u{points(e){return this.setAttribute("points",e)}with(e){return this.points(e.map(({x:e,y:t})=>e+" "+t).join(","))}}t.PolyElement=m;class g extends m{constructor(){super("polyline")}}t.Polyline=g;class b extends m{constructor(){super("polygon")}}t.Polygon=b;class y extends u{constructor(){super("path"),this.d=new x}update(){return this.setAttribute("d",this.d.toAttribute())}path(e){return e(this.d),this.update()}setD(e){return this.setAttribute("d",e),this}}t.Path=y;t.Image=class extends u{constructor(){super("image")}src(e){return this.setAttributeNS("http://www.w3.org/1999/xlink","href",e)}width(e,t=i.px){return this.setAttribute("width",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=T("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 A 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=A;class k extends r{constructor(){super("clipPath")}clipPathUnits(e){return e?this.setAttribute("clipPathUnits","objectBoundingBox"):this.setAttribute("clipPathUnits","userSpaceOnUse")}}function T(e){return document.createElementNS("http://www.w3.org/2000/svg",e)}t.ClipPath=k;class x{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=x}(e.svgUtil||(e.svgUtil={}))}(pxt||(pxt={})),function(e){!function(e){!function(e){function t(){return"undefined"!=typeof window&&("ontouchstart"in window||navigator&&navigator.maxTouchPoints>0)}function n(){return"undefined"!=typeof window&&!!window.PointerEvent}e.isTouchEnabled=t,e.hasPointerEvents=n,e.down=function(e,i){n()?e.addEventListener("pointerdown",i):t()?(e.addEventListener("mousedown",i),e.addEventListener("touchstart",i)):e.addEventListener("mousedown",i)},e.up=function(e,i){n()?e.addEventListener("pointerup",i):(t(),e.addEventListener("mouseup",i))},e.enter=function(e,i){n()?e.addEventListener("pointerover",e=>{i(!!(1&e.buttons))}):t()?e.addEventListener("touchstart",e=>{i(!0)}):e.addEventListener("mouseover",e=>{i(!!(1&e.buttons))})},e.leave=function(e,i){n()?e.addEventListener("pointerleave",i):t()?e.addEventListener("touchend",i):e.addEventListener("mouseleave",i)},e.move=function(e,i){n()?e.addEventListener("pointermove",i):t()?e.addEventListener("touchmove",i):e.addEventListener("mousemove",i)},e.click=function(e,t){e.addEventListener("click",t)}}(e.events||(e.events={}))}(e.svgUtil||(e.svgUtil={}))}(pxt||(pxt={})),function(e){!function(e){!function(t){class n extends e.Text{at(e,t){return this.cx=e,this.cy=t,this.rePosition(),this}text(e,t=12){return super.text(e),this.fontSizePixels=t,this.setAttribute("font-size",t+"px"),this.rePosition(),this}rePosition(){null!=this.cx&&null!=this.cy&&null!=this.fontSizePixels&&(this.setAttribute("x",this.cx),this.setAttribute("y",this.cy),this.setAttribute("text-anchor","middle"),this.setAttribute("alignment-baseline","middle"))}}t.CenteredText=n}(e.helpers||(e.helpers={}))}(e.svgUtil||(e.svgUtil={}))}(pxt||(pxt={})),function(e){!function(e){e.initExtensionsAsync=e=>Promise.resolve({}),e.initFieldExtensionsAsync=e=>Promise.resolve({})}(e.editor||(e.editor={}))}(pxt||(pxt={})),function(e){e.IMAGE_MIME_TYPE="image/x-mkcd-f4",e.TILEMAP_MIME_TYPE="application/mkcd-tilemap",e.ANIMATION_MIME_TYPE="application/mkcd-animation",e.SONG_MIME_TYPE="application/mkcd-song",e.JSON_MIME_TYPE="application/json";class t{constructor(e){this.type=e,this.assets=[],this.takenNames={},this.listeners=[]}add(e){if(this.takenNames[e.id])return this.update(e.id,e);{const t=o(e);return this.takenNames[t.id]=!0,this.takenNames[f(t)]=!0,t.meta.displayName&&t.meta.displayName!==t.id&&(this.takenNames[t.meta.displayName]&&(t.meta.displayName=this.generateNewDisplayName(t.meta.displayName)),this.takenNames[t.meta.displayName]=!0),this.assets.push(t),o(t)}}getSnapshot(e){return e?this.assets.filter(t=>e(t)).map(e=>o(e)):this.assets.map(e=>o(e))}update(t,n){let i;if(this.takenNames[t]){const s=this.lookupByID(t);if(h(s,n))i=n;else{if(!m(n)&&m(s))return e.warn("Refusing to overwrite asset with invalid version"),e.tickEvent("assets.invalidAssetOverwrite",{assetType:n.type}),s;this.removeByID(t),i=this.add(n),this.notifyListener(n.internalID)}}else i=this.add(n);return i}removeByID(e){const t=this.lookupByID(e);this.assets=this.assets.filter(t=>t.id!==e),delete this.takenNames[e],t&&delete this.takenNames[f(t)],(null==t?void 0:t.meta.displayName)&&delete this.takenNames[null==t?void 0:t.meta.displayName]}getByID(e){const t=this.lookupByID(e);return t&&o(t)}getByDisplayName(e){if(this.takenNames[e])for(const t of this.assets)if(t.meta.displayName===e||f(t)===e)return o(t)}getByValue(e){for(const t of this.assets)if(h(e,t,!0))return t}isIDTaken(e){return!!this.takenNames[e]}clone(){const e=new t(this.type);return e.assets=this.getSnapshot(),e.takenNames=Object.assign({},this.takenNames),e}serializeToJRes(e={},t){for(const n of this.assets)t&&!t(n)||d(n,e);return e}addListener(e,t){this.listeners.push({internalID:e,callback:t})}removeListener(e){this.listeners=this.listeners.filter(t=>t.callback!==e)}diff(e){let t={before:[],after:[]},n={};for(const i of e.assets){n[i.internalID]=!0;const e=this.lookupByInternalID(i.internalID);e&&h(i,e)||(t.before.push(i),t.after.push(e))}for(const e of this.assets.filter(e=>!n[e.internalID]))t.before.push(null),t.after.push(e);return t}applyDiff(t,n=!1){const i=n?t.after:t.before,s=n?t.before:t.after;e.Util.assert(i.length===s.length);for(let e=0;e<i.length;e++)i[e]?(this.removeByInternalID(i[e].internalID),s[e]&&this.assets.push(s[e]),this.notifyListener(i[e].internalID)):(this.assets.push(s[e]),this.notifyListener(s[e].internalID));this.takenNames={};for(const t of this.assets)e.Util.assert(!this.takenNames[t.id]),this.takenNames[t.id]=!0,this.takenNames[f(t)]=!0,t.meta.displayName&&(t.meta.displayName!==t.id&&e.Util.assert(!this.takenNames[t.meta.displayName]),this.takenNames[t.meta.displayName]=!0)}lookupByID(e){for(const t of this.assets)if(t.id===e)return t;return null}lookupByInternalID(e){for(const t of this.assets)if(t.internalID===e)return t;return null}removeByInternalID(e){this.assets=this.assets.filter(t=>t.internalID!==e)}notifyListener(e){for(const t of this.listeners)t.internalID===e&&t.callback()}generateNewDisplayName(e){e=e.replace(/\d+$/,"");let t=0;for(;this.takenNames[e+t];)++t;return e+t}}class n{constructor(){this.needsRebuild=!0,this.nextID=0,this.nextInternalID=0,this.committedState={revision:n.nextRevision++,assets:{image:new t("image"),tile:new t("tile"),tilemap:new t("tilemap"),animation:new t("animation"),song:new t("song"),json:new t("json")}},this.state={revision:n.nextRevision++,assets:{image:new t("image"),tile:new t("tile"),tilemap:new t("tilemap"),animation:new t("animation"),song:new t("song"),json:new t("json")}},this.gallery={revision:0,assets:{image:new t("image"),tile:new t("tile"),tilemap:new t("tilemap"),animation:new t("animation"),song:new t("song"),json:new t("json")}},this.undoStack=[],this.redoStack=[]}getNewInternalId(){return this.nextInternalID++}createNewImage(t=16,n=16){this.onChange();const i=this.generateNewID("image"),s=new e.sprite.Bitmap(t,n).data(),r={internalID:this.getNewInternalId(),id:i,type:"image",bitmap:s,meta:{},jresData:e.sprite.base64EncodeBitmap(s)};return this.getAssetCollection("image").add(r)}createNewAnimation(t=16,n=16){this.onChange();const i=this.generateNewID("animation"),s=new e.sprite.Bitmap(t,n).data(),r={internalID:this.getNewInternalId(),id:i,type:"animation",frames:[s],interval:500,meta:{}};return this.getAssetCollection("animation").add(r)}createNewAnimationFromData(e,t=500,n){this.onChange();const i=this.generateNewID("animation"),s={internalID:this.getNewInternalId(),id:i,type:"animation",frames:e,interval:t,meta:{displayName:n}};return this.getAssetCollection("animation").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.getAssetCollection("image").getSnapshot()}getProjectTiles(t,n){const i=this.getAssetCollection("tile").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.getAssetCollection("tile").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.getAssetCollection("image").add(i)}createNewSong(t,n){this.onChange();const i={internalID:this.getNewInternalId(),id:this.generateNewID("song"),type:"song",song:e.assets.music.cloneSong(t),meta:{displayName:n}};return this.getAssetCollection("song").add(i)}createNewJsonAsset(e,t,n){this.onChange();const i={internalID:this.getNewInternalId(),id:this.generateNewID("json"),type:"json",data:e,fileName:t,meta:{displayName:n}};return this.getAssetCollection("json").add(i)}updateTile(t){this.onChange();const n=this.resolveProjectTileByInternalID(t.internalID);if(n){if(this.getAssetCollection("tile").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.getAssetCollection("tile").removeByID(e)}getProjectTilesetJRes(t){const n={};return this.getAssetCollection("tile").serializeToJRes(n),this.getAssetCollection("tilemap").serializeToJRes(n,n=>!t||!e.sprite.isTilemapEmptyOrUnused(n,this,t)),n["*"]={mimeType:"image/x-mkcd-f4",dataEncoding:"base64",namespace:e.sprite.TILE_NAMESPACE},n}getProjectAssetsJRes(){const t={};for(const e of Object.keys(this.state.assets))"tilemap"!==e&&"tile"!==e&&this.state.assets[e].serializeToJRes(t);return t["*"]={mimeType:"image/x-mkcd-f4",dataEncoding:"base64",namespace:e.sprite.IMAGES_NAMESPACE},t}getTilemap(e){return this.getAssetCollection("tilemap").getByID(e)}updateTilemap(e,t){const n=this.getAssetCollection("tilemap").getByID(e);if(n){this.onChange();const i=Object.assign(Object.assign({},n),{data:t});return this.getAssetCollection("tilemap").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.getAssetCollection("tile").getSnapshot(t=>t.internalID===e)[0]}resolveTileByBitmap(t){const n=e.sprite.base64EncodeBitmap(t);return this.getAssetCollection("tile").getSnapshot(e=>e.jresData===n)[0]}getTransparency(t){const n=e.sprite.TILE_NAMESPACE+".transparency"+t;let i=this.getAssetCollection("tile").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.getAssetCollection("tile").add(i)}return i}createNewTilemapFromData(e,t){this.onChange();const n=this.generateNewIDInternal("tilemap",t||lf("level"));return this.getAssetCollection("tilemap").add({internalID:this.getNewInternalId(),id:n,type:"tilemap",meta:{displayName:t||n},data:e}),[n,e]}cloneState(){const e={revision:this.state.revision,assets:{}};for(const t of Object.keys(this.state.assets))e.assets[t]=this.state.assets[t].clone();return e}undo(){if(this.state.revision!==this.committedState.revision&&this.pushUndo(),this.undoStack.length){const e=this.undoStack.pop();for(const t of Object.keys(e.assetDiffs))this.getAssetCollection(t).applyDiff(e.assetDiffs[t],!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();for(const t of Object.keys(e.assetDiffs))this.getAssetCollection(t).applyDiff(e.assetDiffs[t]);this.state.revision=e.afterRevision,this.undoStack.push(e),this.committedState=this.cloneState(),this.needsRebuild=!0}}pushUndo(){if(this.undoStack.length&&this.committedState.revision===this.state.revision)return;this.redoStack=[],this.undoStack.push({beforeRevision:this.committedState.revision,afterRevision:this.state.revision,assetDiffs:{}});const e=this.undoStack[this.undoStack.length-1];for(const t of Object.keys(this.state.assets))e.assetDiffs[t]=this.state.assets[t].diff(this.committedState.assets[t]);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=>this.getAssetCollection(e).isIDTaken(t)||this.getAssetCollection(e,!0).isIDTaken(t),i=b(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(f(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;case"song":o=`assets.song\`${s}\``,r&&(o+=`|assets.song\`${r}\``);break;case"json":o=`assets.json\`${s}\``,r&&(o+=`|assets.json\`${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;case"song":c=`assets.song("""${s}""")`,r&&(c+=`|assets.song("""${r}""")`);break;case"json":c=`assets.json("""${s}""")`,r&&(c+=`|assets.json("""${r}""")`);break;default:c=`assets.image("""${s}""")`,r&&(c+=`|assets.image("""${r}""")`)}const u=new RegExp(c,"gm");for(let e of Object.keys(n)){if((null==i?void 0:i.indexOf(e))>=0)continue;const t=n[e];if(e.match(/((?!\.g).{2}|^.{0,1})\.ts$/i)){if(t.content.match(l))return!0}else if(e.endsWith(".py")&&t.content.match(u))return!0}}return!1}lookupAsset(e,t){return this.getAssetCollection(e).getByID(t)||this.getAssetCollection(e,!0).getByID(t)}lookupAssetByName(e,t){return this.getAssetCollection(e).getByDisplayName(t)}lookupAssetByValue(e,t){return this.getAssetCollection(e).getByValue(t)}getAssets(e){return this.getAssetCollection(e).getSnapshot()}getGalleryAssets(e){return this.getAssetCollection(e,!0).getSnapshot()}lookupBlockAsset(e,t){return this.getAssetCollection(e).getSnapshot(e=>{var n,i;return-1!==(null===(i=null===(n=e.meta)||void 0===n?void 0:n.blockIDs)||void 0===i?void 0:i.indexOf(t))})[0]}updateAsset(e){return this.onChange(),"tile"===e.type?this.updateTile(e):this.getAssetCollection(e.type).update(e.id,e)}duplicateAsset(e,t){var n;this.onChange();const i=o(e),s=t||(null===(n=i.meta)||void 0===n?void 0:n.displayName);let r;switch(e.type){case"image":r=this.createNewProjectImage(i.bitmap,s);break;case"tile":r=this.createNewTile(i.bitmap,null,s);break;case"tilemap":const[t,n]=this.createNewTilemapFromData(i.data,s);r=this.getTilemap(t);break;case"animation":r=this.createNewAnimationFromData(i.frames,i.interval,s);break;case"song":r=this.createNewSong(i.song,s);break;case"json":r=this.createNewJsonAsset(i.data,e.fileName,s)}return r}removeAsset(e){this.onChange(),this.getAssetCollection(e.type).removeByID(e.id)}addChangeListener(e,t){this.getAssetCollection(e.type).addListener(e.internalID,t)}removeChangeListener(e,t){this.getAssetCollection(e).removeListener(t)}loadPackage(t){const n=t.sortedDeps();this.extensionTileSets=[];for(const t of n){const n="this"===t.id,i=this.readImages(t.parseJRes(),n);for(const s of i)if(s.meta.package=t.id,"tile"===s.type)this.getAssetCollection("tile",!n).add(s);else if("image"===s.type)this.getAssetCollection("image",!n).add(s);else if("animation"===s.type)this.getAssetCollection("animation",!n).add(s);else if("json"===s.type)this.getAssetCollection("json",!n).add(s);else if(n){const t=e.sprite.IMAGES_NAMESPACE+".";s.id.startsWith(t)&&(s.id=s.id.replace(t,e.sprite.SONG_NAMESPACE+".")),this.getAssetCollection("song").add(s)}else this.getAssetCollection("song",!0).add(s)}for(const e of n){const t="this"===e.id;for(const n of i(e.parseJRes()))t?this.getAssetCollection("tilemap").add({internalID:this.getNewInternalId(),type:"tilemap",id:n.id,meta:{displayName:n.displayName||n.id,package:e.id},data:a(n,e=>this.resolveTile(e))}):this.getAssetCollection("tilemap",!0).add({internalID:this.getNewInternalId(),type:"tilemap",id:n.id,meta:{displayName:n.displayName||n.id,package:e.id},data:a(n,e=>this.getAssetCollection("tile",!0).getByID(e))})}this.committedState=this.cloneState(),this.undoStack=[],this.redoStack=[]}loadTilemapJRes(t,n=!1,s=!1){t=e.inflateJRes(t);const r=this.readImages(t,!s).filter(e=>"tile"===e.type);let o={};if(s)for(const e of r)this.getAssetCollection("tile",!0).add(e);else for(const e of r){if(n){const t=this.resolveTileByBitmap(e.bitmap);if(t){o[e.id]=t.id;continue}}const t=this.createNewTile(e.bitmap,e.id,e.meta.displayName);t.id!==e.id&&(o[e.id]=t.id)}for(const e of i(t))this.getAssetCollection("tilemap",s).add({internalID:this.getNewInternalId(),type:"tilemap",id:e.id,meta:{displayName:e.displayName||e.id},data:a(e,e=>(o[e]&&(e=o[e]),this.resolveTile(e)))})}loadAssetsJRes(t,n=!1){t=e.inflateJRes(t);const i=[];for(const s of Object.keys(t)){const r=t[s];if(r.tilemapTile)this.getAssetCollection("tile",n).add(this.generateImage(r,"tile"));else if(r.mimeType===e.IMAGE_MIME_TYPE)this.getAssetCollection("image",n).add(this.generateImage(r,"image"));else if(r.mimeType===e.ANIMATION_MIME_TYPE){const[e,t]=this.generateAnimation(r);t?i.push(e):this.getAssetCollection("animation",n).add(e)}else r.mimeType===e.SONG_MIME_TYPE?this.getAssetCollection("song",n).add(this.generateSong(r)):r.mimeType===e.JSON_MIME_TYPE&&this.getAssetCollection("json",n).add(this.generateJsonAsset(r))}for(const e of i)this.getAssetCollection("animation",n).add(this.inflateAnimation(e,this.getAssetCollection("image",n).getSnapshot()))}removeInactiveBlockAssets(e){for(const e of Object.keys(this.state.assets))t(this.state.assets[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)}}clone(){var e;const t=new n;return t.committedState=l(this.committedState),t.state=l(this.state),t.gallery=l(this.gallery),t.extensionTileSets=null===(e=this.extensionTileSets)||void 0===e?void 0:e.map(e=>Object.assign(Object.assign({},e),{tileSets:e.tileSets.map(e=>Object.assign(Object.assign({},e),{tiles:e.tiles.map(e=>o(e))}))})),t.needsRebuild=this.needsRebuild,t.nextID=this.nextID,t.nextInternalID=this.nextInternalID,t.undoStack=this.undoStack.map(e=>c(e)),t.redoStack=this.undoStack.map(e=>c(e)),t}saveGallerySnapshot(){return this.gallery}loadGallerySnapshot(e){this.gallery=e}generateImage(t,n){return{internalID:this.getNewInternalId(),type:n,id:t.id,meta:{displayName:t.displayName,tags:t.tags},jresData:t.data,bitmap:e.sprite.getBitmapFromJResURL(`data:${e.IMAGE_MIME_TYPE};base64,${t.data}`).data()}}generateSong(t){return{internalID:this.getNewInternalId(),type:"song",id:t.id,meta:{displayName:t.displayName,tags:t.tags},song:e.assets.music.decodeSongFromHex(t.data)}}generateJsonAsset(e){const t=JSON.parse(e.data);return{internalID:this.getNewInternalId(),type:"json",id:e.id,meta:{displayName:e.displayName,tags:e.tags},data:t.data,fileName:t.fileName}}generateAnimation(t){if("json"===t.dataEncoding){let n;try{n=JSON.parse(t.data)}catch(n){e.warn("could not parse json data of '"+t.id+"'")}return[{internalID:this.getNewInternalId(),type:"animation",meta:{displayName:t.displayName,tags:t.tags},id:t.id,frames:[],frameIds:n.frames,interval:100,flippedHorizontal:n.flippedHorizontal},!0]}return[Object.assign(Object.assign({},y(t)),{internalID:this.getNewInternalId()}),!1]}inflateAnimation(t,n){return t.frames=t.frameIds.map(e=>n.find(t=>t.id===e).bitmap),t.flippedHorizontal&&(t.frames=t.frames.map(t=>{const n=e.sprite.Bitmap.fromData(t),i=new e.sprite.Bitmap(t.width,t.height);for(let e=0;e<i.width;e++)for(let t=0;t<i.height;t++)i.set(e,t,n.get(n.width-e-1,t));return i.data()})),t}generateNewID(t){switch(t){case"animation":return this.generateNewIDInternal("animation",e.sprite.ANIMATION_PREFIX,e.sprite.ANIMATION_NAMESPACE);case"image":return this.generateNewIDInternal("image",e.sprite.IMAGE_PREFIX,e.sprite.IMAGES_NAMESPACE);case"tile":return this.generateNewIDInternal("tile",e.sprite.TILE_PREFIX,e.sprite.TILE_NAMESPACE);case"tilemap":return this.generateNewIDInternal("tilemap",lf("level"));case"song":return this.generateNewIDInternal("song",e.sprite.SONG_PREFIX,e.sprite.SONG_NAMESPACE);case"json":return this.generateNewIDInternal("json",e.sprite.JSON_PREFIX,e.sprite.JSON_NAMESPACE)}}generateNewName(t,n){const i=n||e.getDefaultAssetDisplayName(t);if(!this.isNameTaken(t,i))return i;const s=/^(.*)(\d+)$/.exec(i),r=s?s[1]:i;let a=s?parseInt(s[2],10)+1:1,o=r+a;for(;this.isNameTaken(t,o);)a++,o=r+a;return o}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=n.nextRevision++}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)}else a.mimeType===e.SONG_MIME_TYPE?i.push(this.generateSong(a)):a.mimeType===e.JSON_MIME_TYPE&&i.push(this.generateJsonAsset(a))}for(const e of s)i.push(this.inflateAnimation(e,i));return i}cleanupTemporaryAssets(){const e=this.getAssetCollection("image"),t=e.getSnapshot(e=>{var t;return!e.meta.displayName&&!(null===(t=e.meta.blockIDs)||void 0===t?void 0:t.length)});for(const n of t)e.removeByID(n.id)}getAssetCollection(e,t=!1){return w(t?this.gallery:this.state,e,!0)}}function i(t){const n=[];for(const i of Object.keys(t)){const s=t[i];s.mimeType===e.TILEMAP_MIME_TYPE&&n.push(s)}return n}function s(e,t){const n=" ";return`\n${n}helpers._registerFactory("${e}", function(name: string) {\n${n}${n}switch(helpers.stringTrim(name)) {\n`+t.map(e=>e.keys.filter(e=>!!e).map(e=>`${n}${n}${n}case "${e}":`).join("\n")+`return ${e.expression};`).join("\n")+"\n"+`${n}${n}}\n`+`${n}${n}return null;\n`+`${n}})\n`}function r(t){return e.sprite.Bitmap.fromData(t).copy().data()}function a(t,n){var i;const s=atob(t.data),r=e.U.fromHex(s),a=r[1]|r[2]<<8,o=r[3]|r[4]<<8,l=t.tileset.map(e=>n&&n(e)||{id:e});let c=r[0];c||(c=l.length&&(null===(i=l.find(e=>{var t;return null===(t=e.bitmap)||void 0===t?void 0:t.width}))||void 0===i?void 0:i.bitmap.width)),c=c||16;const u={tileWidth:c,tiles:l},d=r.slice(5,5+a*o),h=new e.sprite.Tilemap(a,o,0,0,new Uint8ClampedArray(d)),p=r.slice(5+d.length),f=new e.sprite.Bitmap(a,o,0,0,new Uint8ClampedArray(p)).data();return new e.sprite.TilemapData(h,u,f)}function o(t,n=!1){switch(t.meta=Object.assign({},t.meta),t.meta.temporaryInfo&&(t.meta.temporaryInfo=Object.assign({},t.meta.temporaryInfo)),t.type){case"tile":case"image":return Object.assign(Object.assign({},t),{bitmap:r(t.bitmap)});case"animation":return Object.assign(Object.assign({},t),{frames:t.frames.map(e=>r(e))});case"tilemap":return Object.assign(Object.assign({},t),{data:t.data.cloneData(n)});case"song":return Object.assign(Object.assign({},t),{song:e.assets.music.cloneSong(t.song)});case"json":return Object.assign(Object.assign({},t),{data:e.U.clone(t.data)})}}function l(e){const t={revision:e.revision,assets:{}};for(const n of Object.keys(e.assets)){const i=e.assets[n];t.assets[n]=i.clone()}return t}function c(e){const t=Object.assign(Object.assign({},e),{assetDiffs:{}});for(const n of Object.keys(e.assetDiffs)){const i=e.assetDiffs[n];t.assetDiffs[n]=u(i)}return t}function u(e){return Object.assign(Object.assign({},e),{before:e.before.map(e=>o(e)),after:e.after.map(e=>o(e))})}function d(t,n){const i=t.id.substr(t.id.lastIndexOf(".")+1),s=t.meta.tags;switch(t.type){case"image":if(n[i]=t.jresData,t.meta.displayName||(null==s?void 0:s.length)){const r={data:t.jresData,mimeType:e.IMAGE_MIME_TYPE};t.meta.displayName&&(r.displayName=t.meta.displayName),(null==s?void 0:s.length)&&(r.tags=s),n[i]=r}break;case"tile":const r={data:t.jresData,mimeType:e.IMAGE_MIME_TYPE,tilemapTile:!0,displayName:t.meta.displayName};(null==s?void 0:s.length)&&(r.tags=s),n[i]=r;break;case"tilemap":const a=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[a.id]=a;break;case"animation":n[i]=function(t){var n;const i={namespace:t.id.substr(0,t.id.lastIndexOf(".")),id:t.id.substr(t.id.lastIndexOf(".")+1),mimeType:e.ANIMATION_MIME_TYPE,data:e.sprite.encodeAnimationString(t.frames,t.interval),displayName:t.meta.displayName};(null===(n=t.meta.tags)||void 0===n?void 0:n.length)&&(i.tags=t.meta.tags);return i}(t);break;case"song":const o={data:e.assets.music.encodeSongToHex(t.song),mimeType:e.SONG_MIME_TYPE,displayName:t.meta.displayName,namespace:e.sprite.SONG_NAMESPACE+"."};(null==s?void 0:s.length)&&(o.tags=s),n[i]=o;break;case"json":const l={data:JSON.stringify({data:t.data,fileName:t.fileName}),mimeType:e.JSON_MIME_TYPE,displayName:t.meta.displayName,namespace:e.sprite.JSON_NAMESPACE+"."};(null==s?void 0:s.length)&&(l.tags=s),n[i]=l}}function h(t,n,i=!1){if(t==n)return!0;if(!t&&n||!n&&t||t.type!==n.type)return!1;if(!(i||t.id===n.id&&e.U.arrayEquals(t.meta.tags,n.meta.tags)&&e.U.arrayEquals(t.meta.blockIDs,n.meta.blockIDs)&&t.meta.displayName===n.meta.displayName))return!1;switch(t.type){case"image":case"tile":return e.sprite.bitmapEquals(t.bitmap,n.bitmap);case"animation":const i=n;return t.interval===i.interval&&e.U.arrayEquals(t.frames,i.frames,e.sprite.bitmapEquals);case"tilemap":return t.data.equals(n.data);case"song":return e.assets.music.songEquals(t.song,n.song);case"json":return t.fileName===n.fileName&&e.U.deepEqual(t.data,n.data)}}function p(e){const t=/^\s*(?:(?:assets\s*\.\s*(image|tile|animation|tilemap|song))|(tilemap))\s*(?:`|\(""")([^`"]*)(?:`|"""\))\s*$/m.exec(e);if(t){return{type:t[1]||t[2],name:t[3].trim()}}}function f(e){return b(e.type,e.id)}function m(t){if(!t)return!1;switch(t.type){case"image":case"tile":return function(t){return!!t.bitmap&&g(e.sprite.Bitmap.fromData(t.bitmap))}(t);case"tilemap":return function(t){var n;if(!(t.data&&t.data.tilemap&&t.data.tileset&&t.data.tileset.tileWidth&&(null===(n=t.data.tileset.tiles)||void 0===n?void 0:n.length)&&t.data.layers))return!1;return g(e.sprite.Bitmap.fromData(t.data.layers))&&g(t.data.tilemap)}(t);case"animation":return function(t){var n;if(!(null===(n=t.frames)||void 0===n?void 0:n.length)||t.interval<=0)return!1;return!t.frames.some(t=>!g(e.sprite.Bitmap.fromData(t)))}(t);case"song":return(n=t).song&&n.song.ticksPerBeat>0&&n.song.beatsPerMeasure>0&&n.song.measures>0&&n.song.beatsPerMinute>0&&!!n.song.tracks;case"json":return!!t.data}var n}function g(e){return e.width>0&&e.height>0&&!Number.isNaN(e.x0)&&!Number.isNaN(e.y0)&&e.data().data.length===e.dataLength()}function b(t,n,i=!1){let s;switch(t){case"image":s=e.sprite.IMAGES_NAMESPACE+".";break;case"tile":s=e.sprite.TILE_NAMESPACE+".";break;case"tilemap":s="";break;case"animation":s=e.sprite.ANIMATION_NAMESPACE+".";break;case"song":s=e.sprite.SONG_NAMESPACE+".";break;case"json":s=e.sprite.JSON_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 y(t){const n=atob(t.data),i=new Uint8ClampedArray(e.U.fromHex(n)),s=v(i,0),r=v(i,2),a=v(i,4),o=v(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,tags:t.tags}}}function v(e,t){return e[t]|e[t+1]<<8}function w(e,n,i=!1){if(!e.assets[n]){if(!i)return;e.assets[n]=new t(n)}return e.assets[n]}n.nextRevision=0,e.TilemapProject=n,e.emitGalleryDeclarations=function(t,n){var i;const s=Object.keys(t),r=" ";let o="";const l={},c={},u={},d=e=>{let n=t[e].namespace||t["*"].namespace;const i=t[e].id||e;return n&&(n.endsWith(".")&&(n=n.slice(0,n.length-1)),!i.startsWith(n+"."))?n+"."+i:i};t["*"]&&(u["*"]=Object.assign(Object.assign({},t["*"]),{namespace:n}));for(const e of s){if("*"===e)continue;const i=t[e],s=d(e);let r=ts.pxtc.escapeIdentifier(i.displayName||s.split(".").pop());if(l[r]){const e=r;let t=2;for(;l[r];)r=e+t,t++}l[r]=!0,c[s]=n+"."+r}for(const l of s){if("*"===l)continue;const s=t[l];let h,p,f=s.mimeType||(null===(i=t["*"])||void 0===i?void 0:i.mimeType);const m=c[d(l)].split(".").pop();let g=s.tags;if(!g&&(g=[],-1!==m.toLowerCase().indexOf("background")&&g.push("background"),-1!==m.toLowerCase().indexOf("dialog")&&g.push("dialog"),s.tilemapTile)){let e;if(g.push("tile"),s.displayName&&-1!==s.displayName.indexOf("--")){e=s.displayName.split("--")[1].trim().split(/[\s\-]+/g).map((e,t)=>0===t?e:e.charAt(0).toUpperCase()+e.slice(1)).join("")}e||/^transparency(?:4|8|16|32)$/.test(m)||(e=n),e&&g.push("category-"+e)}if(f===e.IMAGE_MIME_TYPE)p="image.ofBuffer(hex``)",h=s.tilemapTile?"images._tile":"images._image";else if(f===e.ANIMATION_MIME_TYPE){p=`[${y(s).frames.map(t=>e.sprite.bitmapToImageLiteral(e.sprite.Bitmap.fromData(t),"typescript")).join(",")}]`}else if(f===e.TILEMAP_MIME_TYPE){const t=a(s);p=e.sprite.encodeTilemap(t,"typescript",c)}else f===e.SONG_MIME_TYPE?p=`hex\`${s.data}\``:f===e.JSON_MIME_TYPE&&(p=s.data);o+=`${r}//% fixedInstance jres whenUsed\n`,h&&(o+=`${r}//% blockIdentity=${h}\n`),g.length&&(o+=`${r}//% tags="${g.join(" ")}"\n`),o+=`${r}export const ${m} = ${p};\n`,"string"==typeof s?u[m]=s:(u[m]=Object.assign(Object.assign({},s),{id:c[d(l)],tags:g}),s.namespace&&(u[m].namespace=n,s.namespace.endsWith(".")&&(u[m].namespace+=".")),u[m].tileset&&(u[m].tileset=s.tileset.map(e=>c[e]||e)))}const h=lf("Auto-generated code. Do not edit.");return[u,`// ${h}\nnamespace ${n} {\n${o}\n}\n// ${h}\n`]},e.emitTilemapsFromJRes=function(t){const n=Object.keys(t),i=" ";let r="";const o=[],l=[];for(const s of n){if("*"===s)continue;const n=t[s];if(n.tilemapTile){let e=s;-1!==e.indexOf(".")&&(e=e.split(".").slice(-1)[0]),r+=`${i}//% fixedInstance jres blockIdentity=images._tile\n`,r+=`${i}export const ${e} = image.ofBuffer(hex\`\`);\n`,l.push({keys:[n.displayName,b("tile",s,!0)],expression:s})}if(n.mimeType===e.TILEMAP_MIME_TYPE){const t=a(n);o.push({keys:[n.displayName,b("tilemap",n.id)],expression:e.sprite.encodeTilemap(t,"typescript")})}}o.length&&(r+=s("tilemap",o)),l.length&&(r+=s("tile",l));const c=lf("Auto-generated code. Do not edit.");return`// ${c}\nnamespace ${e.sprite.TILE_NAMESPACE} {\n${r}\n}\n// ${c}\n`},e.emitProjectImages=function(t){const n=Object.keys(t);let i="";const r=[],a=[],o=[],l=[];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=[b("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=y(n);a.push({keys:[n.displayName,b("animation",i,!0)],expression:`[${t.frames.map(t=>e.sprite.bitmapToImageLiteral(e.sprite.Bitmap.fromData(t),"typescript")).join(", ")}]`})}else n.mimeType===e.SONG_MIME_TYPE?o.push({keys:[b("song",i,!0),n.displayName],expression:`hex\`${n.data}\``}):n.mimeType===e.JSON_MIME_TYPE&&l.push({keys:[b("json",i,!0),n.displayName],expression:n.data})}const c=lf("Auto-generated code. Do not edit.");return i+=s("image",r),i+=s("animation",a),i+=s("song",o),i+=s("json",l),`// ${c}\nnamespace ${e.sprite.IMAGES_NAMESPACE} {\n${i}\n}\n// ${c}\n`},e.cloneAsset=o,e.assetEquals=h,e.validateAssetName=function(e){return!!e&&!/[\u0000-\u001f\u0021-\u002c\u002e\u002f\u003a-\u0040\u005b-\u005e\u0060\u007b-\u007f]/.test(e)},e.getTSReferenceForAsset=function(e,t=!1){var n;let i;if(i=(null===(n=e.meta)||void 0===n?void 0:n.displayName)?e.meta.displayName:f(e),!i)return"image"===e.type||"tile"===e.type?e.id:void 0;const s=t?'("""':"`",r=t?'""")':"`";switch(e.type){case"tile":return`assets.tile${s}${i}${r}`;case"image":return`assets.image${s}${i}${r}`;case"animation":return`assets.animation${s}${i}${r}`;case"tilemap":return`tilemap${s}${i}${r}`;case"song":return`assets.song${s}${i}${r}`;case"json":return`assets.json${s}${i}${r}`}},e.parseAssetTSReference=p,e.lookupProjectAssetByTSReference=function(e,t){const n=p(e);if(n){const{type:e,name:i}=n;switch(e){case"tile":return t.lookupAssetByName("tile",i);case"image":return t.lookupAssetByName("image",i);case"tilemap":return t.lookupAssetByName("tilemap",i)||t.lookupAsset("tilemap",i);case"animation":return t.lookupAssetByName("animation",i);case"song":return t.lookupAssetByName("song",i);case"json":return t.lookupAssetByName("json",i)}}},e.getDefaultAssetDisplayName=function(e){switch(e){case"image":return lf("myImage");case"tile":return lf("myTile");case"tilemap":return lf("level");case"animation":return lf("myAnim");case"song":return lf("mySong");case"json":return lf("myFile");default:return lf("asset")}},e.getShortIDForAsset=f,e.validateAsset=m,e.patchTemporaryAsset=function(e,t,n){if(!e||h(e,t)||t.id!==e.id)return t;t=o(t,!0);const i=-1===e.internalID,s=-1===t.internalID&&void 0===t.meta.displayName;return i&&!s&&(t.id=n.generateNewID(t.type),t.internalID=n.getNewInternalId()),t}}(pxt||(pxt={})),function(e){!function(t){const n={};t.blockColors={loops:"#107c10",logic:"#006970",math:"#712672",variables:"#A80000",functions:"#005a9e",text:"#996600",arrays:"#A94400",advanced:"#3c3c3c",addpackage:"#717171",search:"#000",debug:"#e03030",default:"#dddddd",topblocks:"#aa8f00",recipes:"#717171"},t.blockIcons={loops:"",logic:"",math:"",variables:"",functions:"",text:"",arrays:"",advancedcollapsed:"",advancedexpanded:"",more:"",addpackage:"",search:"",debug:"",default:"",topblocks:"",recipes:""};let i="";function s(e){const t=function(e,t,n){let i=0,s=0,r=0;if(0==t)i=n,s=n,r=n;else{let 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`#${r(t[0])}${r(t[1])}${r(t[2])}`}function r(e){const t=e.toString(16);return 1==t.length?"0"+t:t}function a(t){var i,s;return(null===(s=null===(i=e.appTarget)||void 0===i?void 0:i.appTheme)||void 0===s?void 0:s.adjustBlockContrast)?(n[t]||(n[t]=e.getWhiteContrastingBackground(t)),n[t]):t}t.appendToolboxIconCss=function(t,n){if(!(i.indexOf(t)>-1))if(1===n.length){const s=e.Util.unicodeToChar(n);i+=`\n .blocklyTreeIcon.${t}::before {\n content: "${s}";\n }\n `}else i+=`\n .blocklyTreeIcon.${t} {\n background-image: url("${e.Util.pathJoin(e.webConfig.commitCdnUrl,encodeURI(n))}")!important;\n width: 30px;\n height: 100%;\n background-size: 20px !important;\n background-repeat: no-repeat !important;\n background-position: 50% 50% !important;\n }\n `},t.getNamespaceColor=function(t){let n;return t=t.toLowerCase(),e.appTarget.appTheme.blockColors&&e.appTarget.appTheme.blockColors[t]?n=e.appTarget.appTheme.blockColors[t]:e.toolbox.blockColors[t]&&(n=e.toolbox.blockColors[t]),n?a(n):""},t.getNamespaceIcon=function(t){return t=t.toLowerCase(),e.appTarget.appTheme.blockIcons&&e.appTarget.appTheme.blockIcons[t]?e.appTarget.appTheme.blockIcons[t]:e.toolbox.blockIcons[t]?e.toolbox.blockIcons[t]:""},t.advancedTitle=function(){return e.Util.lf("{id:category}Advanced")},t.addPackageTitle=function(){return e.Util.lf("{id:category}Extensions")},t.recipesTitle=function(){return e.Util.lf("{id:category}Tutorials")},t.convertColor=function(e){var t;e=(t=e)?"0x"==t.substring(0,2)?"#"+t.substring(2):t:"#000000";const n=parseInt(e);return isNaN(n)?e:s(n)},t.hueToRgb=s,t.fadeColor=function(e,t,n){(e=e.replace(/[^0-9a-f]/gi,"")).length<6&&(e=e[0]+e[0]+e[1]+e[1]+e[2]+e[2]);let i="#";for(let s=0;s<3;s++){let r=parseInt(e.substr(2*s,2),16);r=Math.round(Math.min(Math.max(0,n?r+r*t:r-r*t),255));let a=r.toString(16);i+=("00"+a).substr(a.length)}return i},t.getAccessibleBackground=a}(e.toolbox||(e.toolbox={}))}(pxt||(pxt={})),function(e){!function(t){const n=/^##[^#](.*)$([\s\S]*?)(?=^##[^#]|$(?![\r\n]))/gim,i=/^###[^#](.*)$([\s\S]*?)(?=^###[^#]|$(?![\r\n]))/gim;function s(){return/``` *(sim|block|blocks|filterblocks|spy|ghost|typescript|ts|js|javascript|template|python|jres|assetjson|customts|simtheme|python-template|ts-template|typescript-template|js-template|javascript-template|hiddennamespaces)\s*\n([\s\S]*?)\n```/gim}function r(t,i,s){let r=i||n,c=[];if(t.replace(r,function(e,t,n){n=n.trim();let{header:i,hint:r}=function(e,t){e=l(e);let n,i=e;if(t){const t=/#+ ~ tutorialhint([\s\S]*)/i;i=e.replace(t,function(e,t){return n=t,""})}else{const t=/(^[\s\S]*?\S)\s*((```|\[?\!\[[\s\S]+?\]\(\S+?\)\]?)[\s\S]*)/im;let s=e.match(t);s&&s.length>2&&(i=s[1].trim(),n=s[2].trim())}return{header:i,hint:n}}(n,s&&s.explicitHints);const u=a("local",n),d=o("local",n);let h={title:t.match(/^\{.*\}$/)?void 0:t.replace(/@(fullscreen|unplugged|showdialog|showhint|tutorialCompleted|resetDiff)/gi,"").trim(),contentMd:n,headerContentMd:i,localBlockConfig:u,localValidationConfig:d};return/@(fullscreen|unplugged|showdialog|showhint)/i.test(t)&&(h.showHint=!0),/@(unplugged|showdialog)/i.test(t)&&(h.showDialog=!0),/@tutorialCompleted/.test(t)&&(h.tutorialCompleted=!0),/@resetDiff/.test(t)&&(h.resetDiff=!0),r&&(h.hintContentMd=r),c.push(h),""}),0!=t.indexOf("# Not found"))return c;e.debug("tutorial not found")}function a(e,t){let n={md:"",blocks:[]};const i=new RegExp(`\`\`\`\\s*blockconfig\\.${e}\\s*\\n([\\s\\S]*?)\\n\`\`\``,"gmi");return t.replace(i,(e,t)=>(n.md+=`${t}\n`,"")),n}function o(t,n){let i;const s=new RegExp(`\`\`\`\\s*validation\\.${t}\\s*\\n([\\s\\S]*?)\\n\`\`\``,"gmi");if(n.replace(s,(e,t)=>(i=t,"")),!i||""==i)return null;return{validatorsMetadata:e.getSectionsFromMarkdownMetadata(i).map(e=>({validatorType:e.header,properties:e.attributes}))}}function l(e){if(!e)return e;return e.replace(/```(filterblocks|package|ghost|config|template|jres|assetjson|simtheme|customts|hiddennamespaces|blockconfig\.local|blockconfig\.global|validation\.local|validation\.global)\s*\n([\s\S]*?)\n```/gim,"").trim()}function c(t){if(!t)return;const n=JSON.parse(t);return{[e.TILEMAP_JRES]:n[e.TILEMAP_JRES],[e.TILEMAP_CODE]:n[e.TILEMAP_CODE],[e.IMAGES_JRES]:n[e.IMAGES_JRES],[e.IMAGES_CODE]:n[e.IMAGES_CODE]}}function u(t){const n=e.Util.jsonTryParse(t);if(!n)return;const i={};return n.theme&&(i.theme=n.theme),n.palette&&(i.palette=n.palette),i}t.parseTutorial=function(t){const{metadata:s,body:d}=function(t){const n=/### @(\S+) ([ \S]+)/gi,i={},s=t.replace(n,function(e,t,n){try{i[t]=JSON.parse(n)}catch(e){i[t]=n}return""}),r=i;void 0!==r.explicitHints&&e.appTarget.appTheme&&e.appTarget.appTheme.tutorialExplicitHints&&(r.explicitHints=!0);return{metadata:r,body:s}}(t),{steps:h,activities:p}=function(e,t){if(t&&t.activities)return function(e,t){let s=[],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}}}(d,s),f=function(e){let t=e.match(/^#[^#](.*)$/im);return t&&t.length>1?t[1].trim():null}(d);if(!h)return;const{code:m,templateCode:g,templateLanguage:b,editor:y,language:v,jres:w,assetJson:A,customTs:k,simThemeJson:T,hiddenNamespaces:x}=function(t){let n;const i=/``` *(sim|block|blocks|filterblocks|spy|ghost|typescript|ts|js|javascript|template|python|jres|assetjson|customts|simtheme|python-template|ts-template|typescript-template|js-template|javascript-template|hiddennamespaces)\s*\n([\s\S]*?)\n```/gim;let s,r,a,o,l,c,u,d,h=[];return t.replace(/((?!.)\s)+/g,"\n").replace(i,function(t,n,i){switch(n){case"block":case"blocks":case"blockconfig.local":case"blockconfig.global":case"filterblocks":if(!p(e.BLOCKS_PROJECT_NAME))return;break;case"spy":case"python":if(!p(e.PYTHON_PROJECT_NAME))return;"python"==n&&(o=n);break;case"typescript":case"ts":case"javascript":case"js":if(!p(e.JAVASCRIPT_PROJECT_NAME))return;break;case"template":r=i;break;case"python-template":if(!p(e.PYTHON_PROJECT_NAME))return;r=i,a="python",o="python";break;case"ts-template":case"typescript-template":case"js-template":case"javascript-template":if(!p(e.JAVASCRIPT_PROJECT_NAME))return;r=i,a="typescript";break;case"jres":s=i;break;case"assetjson":l=i;break;case"simtheme":u=i;break;case"customts":c=i,i="";break;case"hiddennamespaces":d=i.split(/\s/m).map(e=>e.trim()).filter(e=>!!e),i=""}return h.push("python"===o?`\n${i}\n`:`{\n${i}\n}`),""}),n=n||e.BLOCKS_PROJECT_NAME,{code:h,templateCode:r,templateLanguage:a,editor:n,language:o,jres:s,assetJson:l,customTs:c,simThemeJson:u,hiddenNamespaces:d};function p(t){return n&&n!=t?(e.debug("tutorial ambiguous: contains snippets of different types"),!1):(n=t,!0)}}(d);e.BrowserUtils.useOldTutorialLayout()&&"python"===v&&s.flyoutOnly&&(s.flyoutOnly=!1,s.hideToolbox=!0),(!0===s.diffs||!1!==s.diffs&&!0!==s.noDiffs&&(y==e.BLOCKS_PROJECT_NAME&&e.appTarget.appTheme.tutorialBlocksDiff||y!=e.BLOCKS_PROJECT_NAME&&e.appTarget.appTheme.tutorialTextDiff))&&function(e,t){let n;function i(e){const t={typescript:"diff",spy:"diffspy",blocks:"diffblocks",python:"diff"},i=/\s*(\/\/|#)\s*@highlight/gm;return e?e.replace(/```(typescript|spy|python|blocks|ghost|template)((?:.|[\r\n])+)```/,function(e,s,r){const 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)}})}(h,p);const E=c(A),C=u(T),I=a("global",t),S=o("global",t);return h.forEach(e=>{e.contentMd=l(e.contentMd),e.headerContentMd=l(e.headerContentMd),e.hintContentMd=l(e.hintContentMd)}),{editor:y,title:f,steps:h,activities:p,code:m,templateCode:g,templateLanguage:b,metadata:s,language:v,jres:w,assetFiles:E,customTs:k,globalBlockConfig:I,globalValidationConfig:S,simTheme:C,hiddenNamespaces:x}},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,templateLanguage:o.templateLanguage,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,globalBlockConfig:o.globalBlockConfig,globalValidationConfig:o.globalValidationConfig,simTheme:o.simTheme,hiddenNamespaces:o.hiddenNamespaces},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,t.highlightBlocks,t.validateBlocks)}else for(let t of Object.keys(i)){const n=i[t];n.usedBlocks&&n.hash&&e.setWithHashAsync(t,n.snippetBlocks,n.hash,n.highlightBlocks,n.validateBlocks)}}).catch(e=>{}):Promise.resolve()},t.resolveLocalizedMarkdown=function(t,n,i){let s,r=i||t.fileName||"README";r.endsWith(".md")||(r+=".md");const[a,o,l]=e.Util.normalizeLanguageCode(e.Util.userLanguage());return s=a&&o&&l?n[`_locales/${a}/${r}`]||n[`_locales/${l}/${r}`]||n[`_locales/${o}/${r}`]:n[`_locales/${a}/${r}`],s=s||n[r],s},t.parseAssetJson=c,t.parseSimThemeJson=u,t.getTutorialHighlightedBlocks=async function(t){const n=await e.BrowserUtils.tutorialInfoDbAsync(),i=await n.getAsync(t.tutorial,t.tutorialCode);return null==i?void 0:i.highlightBlocks},t.getTutorialValidateBlocks=async function(t){const n=await e.BrowserUtils.tutorialInfoDbAsync(),i=await n.getAsync(t.tutorial,t.tutorialCode);return null==i?void 0:i.validateBlocks},t.getRequiredBlockCounts=function(e){if(!e)return;const t={},n=e["validate-exists"];return n&&n.forEach(e=>{t[e]=(t[e]||0)+1}),t},t.getTutorialStepHash=function(t){const{tutorialStepInfo:n,tutorialStep:i}=t,s=function(e){let t=[];return null==e||e.replace(/((?!.)\s)+/g,"\n").replace(/``` *(block|blocks)\s*\n([\s\S]*?)\n```/gim,function(e,n,i){return t.push(`{\n${i}\n}`),""}),t}(n[i].hintContentMd);return e.BrowserUtils.getTutorialCodeHash(s)},t.shouldFilterProject=function(e){return!!e&&!(!e.hideFromProjects&&!e.hideIteration)}}(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]=255&this.flashOffset,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(){var e,t;this.enabled||(this.enabled=!0,this.log("registering webusb events"),null===(e=navigator.usb)||void 0===e||e.addEventListener("disconnect",this.handleUSBDisconnected,!1),null===(t=navigator.usb)||void 0===t||t.addEventListener("connect",this.handleUSBConnected,!1))}disable(){var e,t;this.enabled&&(this.enabled=!1,this.log("unregistering webusb events"),null===(e=navigator.usb)||void 0===e||e.removeEventListener("disconnect",this.handleUSBDisconnected),null===(t=navigator.usb)||void 0===t||t.removeEventListener("connect",this.handleUSBConnected))}async disposeAsync(){this.disable()}handleUSBDisconnected(e){var t;this.log("device disconnected"),e.device==this.dev&&(this.log("clear device"),this.clearDev(),null===(t=this.onDeviceConnectionChanged)||void 0===t||t.call(this,!1))}handleUSBConnected(e){var t;const n=e.device;this.log(`device connected ${n.serialNumber}`),this.dev||this.connecting||(this.log("attach device"),null===(t=this.onDeviceConnectionChanged)||void 0===t||t.call(this,!0))}clearDev(){var e;this.dev&&(this.dev=null,this.epIn=null,this.epOut=null,null===(e=this.onConnectionChanged)||void 0===e||e.call(this))}error(t){throw new n(e.U.lf("USB error on device {0} ({1})",this.dev.productName,t))}log(t){e.debug("webusb: "+t)}async disconnectAsync(){if(this.ready=!1,this.dev){this.log("close device");try{await this.dev.close()}catch(e){}this.clearDev(),await e.U.delay(500)}}async forgetAsync(){var e;if(!(null===(e=this.dev)||void 0===e?void 0:e.forget))return!1;try{const e=this.dev;return await this.disconnectAsync(),await e.forget(),!0}catch(e){return!1}}async reconnectAsync(){this.log("reconnect"),this.setConnecting(!0);try{await this.disconnectAsync();const e=await o();await this.connectAsync(e)}finally{this.setConnecting(!1)}}setConnecting(e){var t;e!=this.connecting&&(this.connecting=e,null===(t=this.onConnectionChanged)||void 0===t||t.call(this))}isConnecting(){return this.connecting}isConnected(){return!!this.dev&&this.ready}async connectAsync(t){if(this.log(`trying to connect (${t.length} devices)`),0==t.length){const e=new Error("Device not found.");throw e.type="devicenotfound",e}this.setConnecting(!0);try{if(this.lastKnownDeviceSerialNumber){const n=t.find(e=>e.serialNumber===this.lastKnownDeviceSerialNumber);n?(this.log("last known device spotted"),t.splice(t.indexOf(n),1),t.unshift(n)):(this.log("delay for last known device"),await e.U.delay(2e3))}for(let e=0;e<t.length;++e){const n=t[e];this.dev=n,this.log(`connect device: ${n.manufacturerName} ${n.productName}`),this.log(`serial number: ${n.serialNumber} ${this.lastKnownDeviceSerialNumber===n.serialNumber?"(last known device)":""} `);try{return void await this.initAsync()}catch(e){this.dev=void 0,this.log(`connection failed, ${e.message}`)}}const n=new Error(e.U.lf("Device in use or not found."));throw n.type="devicelocked",n}finally{this.setConnecting(!1)}}async sendPacketAsync(t){if(!this.dev)throw new Error("Disconnected");if(e.Util.assert(t.length<=64),this.epOut){"ok"!=(await this.dev.transferOut(this.epOut.endpointNumber,t)).status&&this.error("USB OUT transfer failed")}else{"ok"!=(await this.dev.controlTransferOut({requestType:"class",recipient:"interface",request:9,value:512,index:this.iface.interfaceNumber},t)).status&&this.error("USB CTRL OUT transfer failed")}}async readLoop(){if(!this.readLoopStarted)for(this.readLoopStarted=!0,this.log("start read loop");;)if(this.ready)try{const t=await this.recvPacketAsync();t[0]?this.onData(t):await e.U.delay(500)}catch(t){this.dev&&this.onError(t),await e.U.delay(300)}else await e.U.delay(300)}async recvPacketAsync(e){const t=Date.now();for(;!e||Date.now()<t+e;){if(!this.dev)throw new Error("Disconnected");const e=await(this.epIn?this.dev.transferIn(this.epIn.endpointNumber,64):this.dev.controlTransferIn({requestType:"class",recipient:"interface",request:1,value:256,index:this.iface.interfaceNumber},64));"ok"!=e.status&&this.error("USB IN transfer failed");let t=new Uint8Array(e.data.buffer);if(0!=t.length)return t}this.error("USB IN timed out")}async initAsync(){var n;if(!this.dev)throw new Error("Disconnected");const i=this.dev;this.log("open device"),await i.open(),this.log("select configuration"),await i.selectConfiguration(1);this.log("got "+i.configurations[0].interfaces.length+" interfaces");const s=i.configurations[0].interfaces.filter(e=>{let n=e.alternates[0];for(let e of t.filters)if((null==e.classCode||n.interfaceClass===e.classCode)&&!(null!=e.subclassCode&&n.interfaceSubclass!==e.subclassCode||null!=e.protocolCode&&n.interfaceProtocol!==e.protocolCode)){if(0==n.endpoints.length)return!0;if(2==n.endpoints.length&&n.endpoints.every(e=>64==e.packetSize))return!0}return!1});let a=s[s.length-1];this.log(`${s.length} matching interfaces; picking ${a?"#"+a.interfaceNumber:"n/a"}`),a||this.error("cannot find supported USB interface"),this.altIface=a.alternates[0],this.iface=a,this.altIface.endpoints.length?(this.log("using dedicated endpoints"),this.epIn=this.altIface.endpoints.filter(e=>"in"==e.direction)[0],this.epOut=this.altIface.endpoints.filter(e=>"out"==e.direction)[0],e.Util.assert(64==this.epIn.packetSize),e.Util.assert(64==this.epOut.packetSize)):this.log("using ctrl pipe"),this.log("claim interface"),await i.claimInterface(a.interfaceNumber),this.log("device ready"),this.lastKnownDeviceSerialNumber=this.dev.serialNumber,this.ready=!0,r&&this.readLoop(),null===(n=this.onConnectionChanged)||void 0===n||n.call(this)}}async function o(){var t;e.log("webusb: get devices");try{return await(null===(t=navigator.usb)||void 0===t?void 0:t.getDevices())||[]}catch(t){return e.reportException(t),[]}}async function l(){var t,n;if(void 0!==s)return;if(e.debug("webusb: checking availability"),!(null===(n=null===(t=e.appTarget)||void 0===t?void 0:t.compile)||void 0===n?void 0:n.webUSB))return void(s=!1);const i=await c();if(i)switch(s=!1,e.tickEvent("webusb.off",{reason:i}),i){case"electron":e.debug("webusb: off, electron");break;case"notimpl":e.debug("webusb: off, not implemented by browser");break;case"oldwindows":e.debug("webusb: off, older windows version");break;case"security":e.debug("webusb: off, security exception")}else s=!0}async function c(){if(e.BrowserUtils.isElectron())return"electron";const t=navigator.usb;if(!t)return"notimpl";let n=/Windows NT (\d+\.\d+)/.exec(navigator.userAgent);if(n&&parseFloat(n[1])<6.3)return"oldwindows";try{await t.getDevices()}catch(e){return"security"}}function u(){return void 0===s&&(e.error("checkAvailableAsync not called"),l()),!!s}t.pairAsync=async function(){var e;try{return!!await(null===(e=navigator.usb)||void 0===e?void 0:e.requestDevice({filters:t.filters}))}catch(e){if("NotFoundError"==e.name)return;throw e}},t.tryGetDevicesAsync=o,t.mkWebUSBHIDPacketIOAsync=function(){return e.debug("packetio: mk webusb io"),i||(i=new a),i.enable(),Promise.resolve(i)},t.forgetDeviceAsync=async function(){return e.debug("packetio: forget webusb io"),!!i&&i.forgetAsync()},t.isEnabled=!1,t.setEnabled=function(e){u()||(e=!1),t.isEnabled=e},t.checkAvailableAsync=l,t.getReasonUnavailable=c,t.isAvailable=u}(e.usb||(e.usb={}))}(pxt||(pxt={})),function(e){!function(t){var n=e.Util;let i={};function s(e){let t={},i=0,s=new n.PromiseQueue,r=new Promise((e,n)=>{t.ready=e});s.enqueue("main",()=>r);return{opAsync:function(n,r){return s.enqueue("main",()=>new Promise((s,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(Measurements.WebworkerRecvHandler),i.recvHandler(t.data),e.perf.measureEnd(Measurements.WebworkerRecvHandler)},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=u("opcode name doesn't match","<name>");class s{constructor(t,n,i,s,r){this.opcode=i,this.mask=s,this.is32bit=r,this.canBeShared=!1,e.assert((i&s)==i),this.ei=t,this.code=n.replace(/\s+/g," "),this.friendlyFmt=n.replace(/\$\w+/g,e=>this.ei.encoders[e]?this.ei.encoders[e].pretty:e);let a=l(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=[],l=null,c=null,d=null;for(let i=0;i<this.args.length;++i){let h=this.args[i],p=n[r++];if("$"==h[0]){let i=this.ei.encoders[h],f=null;if(i.isRegister){if(f=this.ei.registerNo(p),null==f)return u("expecting register name",p);this.ei.isPush(this.opcode)?a++:this.ei.isPop(this.opcode)&&a--}else if(i.isImmediate){if(p=p.replace(/^#/,""),f=t.bin.parseOneInt(p),null==f)return u("expecting number",p);this.ei.isAddSP(this.opcode)?a=-f/this.ei.wordSize():this.ei.isSubSP(this.opcode)&&(a=f/this.ei.wordSize())}else if(i.isRegList){if("{"!=p)return u("expecting {",p);for(f=0;"}"!=n[r];){if(p=n[r++],!p)return u("expecting }",n[r-2]);let e=this.ei.registerNo(p);if(null==e)return u("expecting register name",p);if(f&1<<e)return u("duplicate register name",p);f|=1<<e,this.ei.isPush(this.opcode)?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),l="rel"+f;else if(/^0x[0-9a-fA-F]+$/.test(p))f=parseInt(p,16),l="abs"+f;else if(l=p,f=this.ei.getAddressFromLabel(t.bin,this,p,i.isWordAligned),null==f){if(t.bin.finalEmit)return u("unknown label",p);f=8}if(this.ei.is32bit(this)){c=f,d=p;continue}}else e.oops();if(null==f)return u("didn't understand it",p);if(o.push(f),f=i.encode(f),null==f)return u("argument out of range or mis-aligned",p);e.assert(0==(s&f)),s|=f}else if(h!=p)return u("expecting "+h,p)}return n[r]?u("trailing tokens",n[r]):this.ei.is32bit(this)?this.ei.emit32(s,c,t.bin.normalizeExternalLabel(d)):{stack:a,opcode:s,numArgs:o,labelName:t.bin.normalizeExternalLabel(l)}}toString(){return this.friendlyFmt}}t.Instruction=s;class r{constructor(e,t){this.bin=e,this.text=t}getOpExt(){return this.instruction?this.instruction.code:""}getOp(){return this.instruction?this.instruction.name:""}update(e){this.bin.peepOps++,(e=e.replace(/^\s*/,""))||this.bin.peepDel++,e&&(e+=" "),e=" "+e,this.text=e+"; WAS: "+this.text.trim(),this.instruction=null,this.numArgs=null,this.words=l(e)||[],0==this.words.length?this.type="empty":"@"==this.words[0][0]&&(this.type="directive")}}t.Line=r;class a{constructor(e,t){this.id=e,this.description=t,this.sizeAdj=0,this.users=[]}get size(){return this.endLocation-this.startLocation-this.sizeAdj}}class o{constructor(e){this.baseOffset=0,this.checkStack=!0,this.inlineMode=!1,this.normalizeExternalLabel=e=>e,this.currLineNo=0,this.scope="",this.scopeId=0,this.errors=[],this.labels={},this.equs={},this.stackpointers={},this.stack=0,this.commPtr=0,this.peepOps=0,this.peepDel=0,this.peepCounts={},this.stats="",this.throwOnError=!1,this.disablePeepHole=!1,this.stackAtLabel={},this.codeSizeStats=!1,this.labelToObject={},this.idToObject={},this.objSuspendStart=0,this.labelsToObjectDone=!1,this.currLine=new r(this,"<start>"),this.currLine.lineNo=0,this.ei=e,this.ei.file=this}emitShort(t){e.assert(0<=t&&t<=65535),this.buf.push(t)}emitOpCode(e){this.emitShort(e)}location(){return 2*this.buf.length}pc(){return this.location()+this.baseOffset}useLabel(t){if(!this.currObject||"."==t[0]||this.objSuspendStart)return;const n=e.U.lookup(this.labelToObject,t);n&&n!=this.currObject&&n.users.length<5&&n.users.indexOf(this.currObject)<0&&n.users.push(this.currObject)}parseOneInt(t){if(!t)return null;if(/^\d+$/.test(t))return parseInt(t,10);const i=t.indexOf("-");if(i>0)return this.parseOneInt(t.slice(0,i))-this.parseOneInt(t.slice(i+1));let s=1;if(t.indexOf("*")>=0){let e=null;for(;null!=(e=/^([^\*]*)\*(.*)$/.exec(t));){let n=this.parseOneInt(e[1]);if(null==n)return null;s*=n,t=e[2]}}if("-"==t[0]?(s*=-1,t=t.slice(1)):"+"==t[0]&&(t=t.slice(1)),/^\d+$/.test(t))return s*parseInt(t,10);if(e.U.endsWith(t,"|1"))return 1|this.parseOneInt(t.slice(0,t.length-2));if(e.U.endsWith(t,"-1"))return this.parseOneInt(t.slice(0,t.length-2))-1;if(e.U.endsWith(t,"+1"))return this.parseOneInt(t.slice(0,t.length-2))+1;let r=/(.*)>>(\d+)$/.exec(t);if(r){let e=this.parseOneInt(r[1]);return e&=~(-16777216&this.baseOffset),e>>parseInt(r[2])}let 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){this.useLabel(e);let i=null,s=this.scopedName(e);return this.labels.hasOwnProperty(s)?(i=this.labels[s],i=this.ei.postProcessRelAddress(this,i)):this.lookupExternalLabel&&(i=this.lookupExternalLabel(e),null!=i&&(i=this.ei.postProcessAbsAddress(this,i))),null==i&&this.equs.hasOwnProperty(s)&&(i=this.equs[s]),null==i&&t&&(this.finalEmit?this.directiveError(n("unknown label: {0}",e)):i=11111),i}align(t){for(e.assert(2==t||4==t||8==t||16==t);this.location()%t!=0;)this.emitOpCode(0)}pushError(e,t=""){let i={scope:this.scope,message:n(" -> Line {2} ('{1}'), error: {0}\n{3}",e,this.currLine.text,this.currLine.lineNo,t),lineNo:this.currLine.lineNo,line:this.currLine.text,coremsg:e,hints:t};if(this.errors.push(i),this.throwOnError)throw new Error(i.message)}directiveError(e){this.pushError(e)}emitString(e,t=!1){function i(e,t){return 255&(e.charCodeAt(t)||0)}let s,r=/^\s*([\w\.]+\s*:\s*)?.\w+\s+(".*")\s*$/.exec(e);if(r&&null!=(s=c(r[2])))if(this.align(2),t)for(let e=0;e<s.length;e++)this.emitShort(s.charCodeAt(e));else for(let e=0;e<s.length+1;e+=2)this.emitShort(i(s,e+1)<<8|i(s,e));else this.directiveError(n("expecting string"))}parseNumber(e){let t=this.parseOneInt(e.shift());return null==t?null:t}parseNumbers(e){e=e.slice(1);let t=[];for(;;){let i=this.parseNumber(e);if(null==i){this.directiveError(n("cannot parse number at '{0}'",e[0]));break}if(t.push(i),","!=e[0]){if(null==e[0])break;this.directiveError(n("expecting number, got '{0}'",e[0]));break}if(e.shift(),null==e[0])break}return t}emitSpace(e){let t=this.parseNumbers(e);if(1==t.length&&t.push(0),2!=t.length)this.directiveError(n("expecting one or two numbers"));else if(t[0]%2!=0)this.directiveError(n("only even space supported"));else{let e=255&t[1];e|=e<<8;for(let n=0;n<t[0];n+=2)this.emitShort(e)}}emitBytes(e){let t=this.parseNumbers(e);t.length%2!=0&&(this.directiveError(".bytes needs an even number of arguments"),t.push(0));for(let e=0;e<t.length;e+=2){let i=t[e],s=t[e+1];0<=i&&s<=255&&0<=s&&i<=255?this.emitShort(255&i|(255&s)<<8):this.directiveError(n("expecting uint8"))}}emitHex(e){e.slice(1).forEach(e=>{if(","!=e)if(e.length%4!=0)this.directiveError(".hex needs an even number of bytes");else if(/^[a-f0-9]+$/i.test(e))for(let t=0;t<e.length;t+=4){let n=parseInt(e.slice(t,t+4),16);n=(255&n)<<8|n>>8&255,this.emitShort(n)}else this.directiveError(".hex needs a hex number")})}handleDirective(t){let i,s=t.words,r=()=>{2!=s.length&&this.directiveError(n("expecting one argument"))};switch(s[0]){case".object":if(this.codeSizeStats)if("PUSH"==s[1])this.objSuspendStart=this.location();else if("POP"==s[1])this.objSuspendStart&&(this.currObject.sizeAdj+=this.location()-this.objSuspendStart),this.objSuspendStart=0;else{if(this.currObject&&(this.currObject.endLocation=this.location()),this.currObject=e.U.lookup(this.idToObject,s[1]),!this.currObject){const e=t.text.replace(/^[^"]*/,"");let i=s[1];s.length>2&&(i=c(e.trim()),null==i&&this.directiveError(n("expecting string in .object"))),this.currObject=new a(s[1],i),this.idToObject[s[1]]=this.currObject}this.currObject.sizeAdj=0,this.currObject.startLocation=this.location()}else;break;case".ascii":case".asciz":case".string":this.emitString(t.text);break;case".utf16":this.emitString(t.text,!0);break;case".align":if(r(),i=this.parseOneInt(s[1]),null!=i){if(0==i)return;i<=4?this.align(1<<i):this.directiveError(n("expecting 1, 2, 3 or 4 (for 2, 4, 8, or 16 byte alignment)"))}else this.directiveError(n("expecting number"));break;case".balign":if(r(),i=this.parseOneInt(s[1]),null!=i){if(1==i)return;2==i||4==i||8==i||16==i?this.align(i):this.directiveError(n("expecting 2, 4, 8, or 16"))}else this.directiveError(n("expecting number"));break;case".p2align":r(),i=this.parseOneInt(s[1]),null!=i?this.align(1<<i):this.directiveError(n("expecting number"));break;case".byte":this.emitBytes(s);break;case".hex":this.emitHex(s);break;case".hword":case".short":case".2bytes":this.parseNumbers(s).forEach(e=>{-32768<=e&&e<=65535?this.emitShort(65535&e):this.directiveError(n("expecting int16"))});break;case".word":case".4bytes":case".long":this.parseNumbers(s).forEach(e=>{-2147483648<=e&&e<=4294967295?(this.emitShort(65535&e),this.emitShort(e>>16&65535)):this.directiveError(n("expecting int32"))});break;case".skip":case".space":this.emitSpace(s);break;case".set":case".equ":/^\w+$/.test(s[1])||this.directiveError(n("expecting name"));const o=this.parseNumbers(s.slice(","==s[2]||"="==s[2]?2:1));1!=o.length&&this.directiveError(n("expecting one value")),void 0!==this.equs[s[1]]&&this.equs[s[1]]!=o[0]&&this.directiveError(n("redefinition of {0}",s[1])),this.equs[s[1]]=o[0];break;case".startaddr":this.location()&&this.directiveError(n(".startaddr can be only be specified at the beginning of the file")),r(),this.baseOffset=this.parseOneInt(s[1]);break;case"@stackmark":r(),this.stackpointers[s[1]]=this.stack;break;case"@stackempty":this.checkStack&&(null==this.stackpointers[s[1]]?this.directiveError(n("no such saved stack")):this.stackpointers[s[1]]!=this.stack&&this.directiveError(n("stack mismatch")));break;case"@scope":this.scope=s[1]||"",this.currLineNo=this.scope?0:this.realCurrLineNo;break;case".syntax":case"@nostackcheck":this.checkStack=!1;break;case"@dummystack":r(),this.stack+=this.parseOneInt(s[1]);break;case".section":case".global":this.stackpointers={},this.stack=0,this.scope="$S"+this.scopeId++;break;case".comm":{s=s.filter(e=>","!=e),s.shift();let e=this.parseOneInt(s[1]),t=0;if(t=s[2]?this.parseOneInt(s[2]):4,null==this.lookupLabel(s[0])){for(this.commPtr||(this.commPtr=this.lookupExternalLabel("_pxt_comm_base")||0,this.commPtr||this.directiveError(n("PXT_COMM_BASE not defined")));this.commPtr&t-1;)this.commPtr++;this.labels[this.scopedName(s[0])]=this.commPtr-this.baseOffset,this.commPtr+=e}break}case".file":case".text":case".cpu":case".fpu":case".eabi_attribute":case".code":case".thumb_func":case".type":case".fnstart":case".save":case".size":case".fnend":case".pad":case".globl":case".local":case"@":break;default:/^\.cfi_/.test(s[0])||this.directiveError(n("unknown directive"))}}handleOneInstruction(e,t){this.codeSizeStats&&e.ldlitLabel&&this.useLabel(e.ldlitLabel);let i=t.emit(e);return!i.error&&(this.stack+=i.stack,this.checkStack&&this.stack<0&&this.pushError(n("stack underflow")),e.location=this.location(),e.opcode=i.opcode,e.stack=i.stack,this.emitOpCode(i.opcode),null!=i.opcode2&&this.emitOpCode(i.opcode2),null!=i.opcode3&&this.emitOpCode(i.opcode3),e.instruction=t,e.numArgs=i.numArgs,!0)}handleInstruction(e){if(e.instruction&&this.handleOneInstruction(e,e.instruction))return;let t=e=>this.ei.instructions.hasOwnProperty(e)?this.ei.instructions[e]:[];if(!e.instruction){let n=t(e.words[0]);for(let t=0;t<n.length;++t)if(this.handleOneInstruction(e,n[t]))return}let i=e.words[0].toLowerCase().replace(/s$/,"").replace(/[^a-z]/g,""),s="",r=t(i).concat(t(i+"s"));r.length>0&&r.forEach(t=>{let i=t.emit(e);s+=n(" Maybe: {0} ({1} at '{2}')\n",t.toString(),i.error,i.errorAt)}),this.pushError(n("assembly error"),s)}buildLine(e,t){let n=e=>{let n=new r(this,e);return n.scope=this.scope,n.lineNo=this.currLineNo,t.push(n),n},i=n(e),s=l(i.text)||[];i.words=s;let 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 o=a.charAt(0);"."==o||"@"==o?(i.type="directive","@scope"==i.words[0]&&this.handleDirective(i)):0==i.words.length?i.type="empty":i.type="instruction"}prepLines(e){this.currLineNo=0,this.realCurrLineNo=0,this.lines=[],e.split(/\r?\n/).forEach(e=>{this.errors.length>10||(this.currLineNo++,this.realCurrLineNo++,this.buildLine(e,this.lines))})}iterLines(){this.stack=0,this.buf=[],this.scopeId=0,this.lines.forEach(t=>{if(!(this.errors.length>10)&&(this.currLine=t,0!=t.words.length))if("label"==t.type){this.currObject&&!this.labelsToObjectDone&&"."!=t.words[0][0]&&(this.labelToObject[t.words[0]]=this.currObject);let i=this.scopedName(t.words[0]);if(this.prevLabel=i,this.finalEmit){null!=this.equs[i]&&this.directiveError(n(".equ redefined as label"));let t=this.labels[i];null==t&&e.oops(),0==this.errors.length&&t!=this.location()&&e.oops(`invalid location: ${this.location()} != ${t} at ${i}`),e.assert(this.errors.length>0||t==this.location()),this.reallyFinalEmit&&(this.stackAtLabel[i]=this.stack)}else this.labels.hasOwnProperty(i)?this.directiveError(n("label redefinition")):this.inlineMode&&/^_/.test(i)?this.directiveError(n("labels starting with '_' are reserved for the compiler")):this.labels[i]=this.location();t.location=this.location()}else"directive"==t.type?this.handleDirective(t):"instruction"==t.type?this.handleInstruction(t):"empty"==t.type||e.oops()}),this.labelsToObjectDone=!0,this.currObject=null}getSourceMap(){const e={};let t="",n=0,i=0,s=0;function r(){t&&i&&(e[t]||(e[t]=[]),e[t].push(n,i,s-i)),i=0,s=0}return this.lines.forEach((e,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}getCodeSizeStats(){if(!this.codeSizeStats)return"";const t=e.U.values(this.idToObject);t.sort((e,t)=>t.size-e.size);let n=";\n; Code size:\n;\n";for(const e of t)if(n+=`; ${(" "+e.size).slice(-6)} ${e.description} [${e.id}]\n`,e.users.length>=5)n+=`; by many, including ${e.users[0].description}\n`;else for(const t of e.users)n+=`; by ${t.description} [${t.id}]\n`;return n}getSource(e,i=1,s=0){let r=0,a=e=>{let t=this.labels[e]||r,n=t-r;return r=t,n},o=this.buf?this.location():0,l=a("_code_end"),c=a("_helpers_end"),u=a("_vtables_end"),d=a("_literals_end"),h=r,p=o+this.baseOffset&16777215;if(s&&p>s){const e=new Error(n("program too big by {0} bytes!",p-s));throw e.ksErrorCode=9283,e}let f=n("; total bytes: {0} ({1}% of {2}k flash with {3} free)",p,(100*p/(s=s||131072)).toFixed(1),(s/1024).toFixed(1),s-p),m=n("; generated code sizes (bytes): {0} (incl. {1} user, {2} helpers, {3} vtables, {4} lits); src size {5}\n",h,l,c,u,d,o-h)+n("; assembly: {0} lines; density: {1} bytes/stmt; ({2} stmts)\n",this.lines.length,Math.round(100*l/i)/100,i)+f+"\n"+this.stats+this.getCodeSizeStats()+"\n\n",g=!1;return this.lines.forEach((n,i)=>{if("_stored_program"==n.words[0])return m+='_stored_program: .string "..."\n',void(g=!0);if(g)return void(g=!1);let s=n.text;if(e){if("@stackempty"==n.words[0]&&this.lines[i-1].text==n.text)return;if(s=s.replace(/; WAS: .*/,""),!s.trim())return}t.debug&&("label"!=n.type&&"instruction"!=n.type||(s+=` \t; 0x${(n.location+this.baseOffset).toString(16)}`)),m+=s+"\n"}),m}peepHole(){let e=this.lines.filter(e=>"empty"!=e.type);for(let t=0;t<e.length;++t){let n=e[t];if(/^user/.test(n.scope))continue;let i=e[t+1];if(!i)continue;let s=e[t+2];"instruction"==n.type&&this.ei.peephole(n,i,s)}}clearLabels(){this.labels={},this.commPtr=0}peepPass(t){this.disablePeepHole||(this.peepOps=0,this.peepDel=0,this.peepCounts={},this.peepHole(),this.throwOnError=!0,this.finalEmit=!1,this.clearLabels(),this.iterLines(),e.assert(!this.checkStack||0==this.stack),this.finalEmit=!0,this.reallyFinalEmit=t||0==this.peepOps,this.iterLines(),this.stats+=n("; peep hole pass: {0} instructions removed and {1} updated\n",this.peepDel,this.peepOps-this.peepDel))}getLabels(){return this.userLabelsCache||(this.userLabelsCache=e.U.mapMap(this.labels,(e,t)=>t+this.baseOffset)),this.userLabelsCache}emit(t){if(e.assert(null==this.buf),this.prepLines(t),this.errors.length>0)return;if(this.clearLabels(),this.iterLines(),this.checkStack&&0!=this.stack&&this.directiveError(n("stack misaligned at the end of the file")),this.errors.length>0)return;if(this.ei.expandLdlit(this),this.clearLabels(),this.iterLines(),this.finalEmit=!0,this.reallyFinalEmit=this.disablePeepHole,this.iterLines(),this.errors.length>0)return;for(let e=0;e<5&&(pxt.debug(`Peephole OPT, pass ${e}`),this.peepPass(5==e),0!=this.peepOps);++e);pxt.debug("emit done")}}t.File=o;t.VMFile=class extends o{constructor(e){super(e)}};function l(e){let t=[],n="";e:for(let i=0;i<e.length;++i)switch(e[i]){case"[":case"]":case"!":case"{":case"}":case",":n&&(t.push(n),n=""),t.push(e[i]);break;case" ":case"\t":case"\r":case"\n":n&&(t.push(n),n="");break;case";":break e;default:n+=e[i]}return n&&(t.push(n),n=""),t[0]?t:null}function c(e){e=e.replace(/\\\\/g,"\\B").replace(/\\(['\?])/g,(e,t)=>t).replace(/\\[z0]/g,"\0").replace(/\\x([0-9a-f][0-9a-f])/gi,(e,t)=>"\\u00"+t).replace(/\\B/g,"\\\\");try{return JSON.parse(e)}catch(e){return null}}function u(e,t){return{stack:null,opcode:null,error:e,errorAt:t}}function d(e){return e<0||e>65535?("0x"+e.toString(16)).toLowerCase():("0x"+("000"+e.toString(16)).slice(-4)).toLowerCase()}t.AbstractProcessor=class{constructor(){this.file=null,this.addEnc=(e,t,n)=>{let i={name:e,pretty:t,encode:n,isRegister:/^\$r\d/.test(e),isImmediate:/^\$i\d/.test(e),isRegList:/^\$rl\d/.test(e),isLabel:/^\$l[a-z]/.test(e)};return this.encoders[e]=i,i},this.inrange=(e,t,n)=>Math.floor(t)!=t||t<0||t>e?null:n,this.inminmax=(e,t,n,i)=>Math.floor(n)!=n||n<e||n>t?null:i,this.inseq=(e,t)=>{let n=e.indexOf(t);return n<0?null:n},this.inrangeSigned=(e,t,n)=>{if(Math.floor(t)!=t)return null;if(t<-(e+1))return null;if(t>e)return null;return n&(e<<1|1)},this.addInst=(e,t,n,i)=>{let r=new s(this,e,t,n,i);return this.instructions.hasOwnProperty(r.name)||(this.instructions[r.name]=[]),this.instructions[r.name].push(r),r},this.encoders={},this.instructions={}}toFnPtr(e,t,n){return e}wordSize(){return-1}computeStackOffset(e,t){return t}is32bit(e){return!1}emit32(e,t,n){return null}postProcessRelAddress(e,t){return t}postProcessAbsAddress(e,t){return t}peephole(e,t,n){}registerNo(e){return null}getAddressFromLabel(e,t,n,i=!1){return null}isPop(e){return!1}isPush(e){return!1}isAddSP(e){return!1}isSubSP(e){return!1}testAssembler(){e.assert(!1)}expandLdlit(e){}},t.emitErr=u,t.expectError=function(t,n){let i=new o(t);i.emit(n),0==i.errors.length&&e.oops("ASMTEST: expecting error for: "+n)},t.tohex=d,t.expect=function(t,n){let i=[],s=n.replace(/^([0-9a-fA-F]{4,8})\s/gm,(e,t)=>(i.push(parseInt(t.slice(0,4),16)),8==t.length&&i.push(parseInt(t.slice(4,8),16)),"")),r=new o(t);r.throwOnError=!0,r.disablePeepHole=!0,r.emit(s),r.errors.length>0&&(pxt.debug(r.errors[0].message),e.oops("ASMTEST: not expecting errors")),r.buf.length!=i.length&&e.oops("ASMTEST: wrong buf len");for(let t=0;t<i.length;++t)r.buf[t]!=i[t]&&e.oops("ASMTEST: wrong buf content at "+t+" , exp:"+d(i[t])+", got: "+d(r.buf[t]))}}(e.assembler||(e.assembler={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){var n=pxtc.Util;t.apiRoot=e.BrowserUtils.isLocalHost()||n.isNodeJS?"https://www.makecode.com/api/":"/api/",t.accessToken="",t.localToken="";let i,s=!0;function r(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 a(n,i){return e.U.requestAsync({url:"/api/"+n,headers:{Authorization:t.localToken},method:i?"POST":"GET",data:i||void 0,allowHttpErrors:!0})}function o(){return e.webConfig&&!e.webConfig.isStatic&&!e.BrowserUtils.isLocalHost()&&!!e.webConfig.cdnUrl&&("undefined"==typeof window||!/nocdn=1/i.test(window.location.href))}function l(n){if(n=n.replace(/^\//,""),!o())return t.apiRoot+n;const i=new Date,s=i.getUTCFullYear()+("0"+(i.getUTCMonth()+1)).slice(-2)+("0"+i.getUTCDate()).slice(-2);return n.indexOf("?")<0?n+="?":n+="&",n+="cdn="+s,e.webConfig.cdnUrl+"/api/"+n}function c(e){return o()?(e.url=l(e.url),n.requestAsync(e).catch(t=>u(e,t))):d(e)}function u(e,n){return 0==n.statusCode?(s&&(s=!1,t.onOffline()),r(e.url)):Promise.reject(n)}function d(i){var s;return i.url=(null===(s=e.webConfig)||void 0===s?void 0:s.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=>u(i,e))):r(i.url)}function h(){return navigator&&navigator.onLine}t.onOffline=()=>{},t.hasAccessToken=function(){return!!t.accessToken},t.localRequestAsync=a,t.useCdnApi=o,t.cdnApiUrl=l,t.apiRequestWithCdnAsync=c,t.privateRequestAsync=d,t.privateGetTextAsync=function(e,t){return d({url:e,headers:t}).then(e=>e.text)},t.privateGetAsync=function(e,t=!1){return d({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()?a(i).then(e=>e?e.json:void 0):c({url:i}).then(e=>e.json)},t.downloadScriptFilesAsync=function(e){return d({url:e+"/text"+(e.startsWith("S")?`?time=${Date.now()}`:""),forceLiveEndpoint:!0}).then(e=>JSON.parse(e.text))},t.downloadScriptMetaAsync=function(e){return d({url:e+(e.startsWith("S")?`?time=${Date.now()}`:""),forceLiveEndpoint:!0}).then(e=>JSON.parse(e.text).meta)},t.downloadBuiltSimJsInfoAsync=async function(t){const n=e.appTarget.versions&&e.appTarget.versions.target||"",i=e.U.stringifyQueryString(t+"/js",{v:"v"+n})+(t.startsWith("S")?`&time=${Date.now()}`:"");return(await d({url:i,forceLiveEndpoint:!0})).json},t.markdownAsync=async function(t,n,i,s){const r=e.BrowserUtils.isLocalHostDev()?0:36e5,l=24*r*7;n=n||e.Util.userLanguage();const u=await e.BrowserUtils.translationDbAsync(),h=await u.getAsync(n,t),p=async()=>{try{const i=await async function(t,n,i,s){var r;const l=null===(r=e.webConfig)||void 0===r?void 0:r.isStatic,u=e.appTarget.versions&&e.appTarget.versions.target||"?";let h;const p=new URLSearchParams;if(l){h=t;const e=/\/?docs\//.test(h),n=/\.\w+$/.test(h);if(!e){const e="/"===h[0];h=`docs${e?"":"/"}${h}`}n||(h=`${h}.md`)}else h=`md/${e.appTarget.id}/${t.replace(/^\//,"")}`,p.set("targetVersion",u);"en"!=n&&p.set("lang",n);if(h=e.BrowserUtils.appendUrlQueryParams(h,p),e.BrowserUtils.isLocalHost()&&!e.Util.liveLocalizationEnabled())return a(h).then(e=>404==e.statusCode?d({url:h,method:"GET"}).then(e=>({md:e.text,etag:e.headers.etag})):{md:e.text,etag:void 0});const f=i&&!o()?{"If-None-Match":i}:void 0;let m,g;if(!l&&s){h=h.replace(/^md\//,"ghtutorial/docs/"),m=await c({url:h,method:"GET",headers:f});const t=m.json;await e.github.db.cacheReposAsync(t),g=t.markdown}else m=await c({url:h,method:"GET",headers:f}),g=m.text;return{md:g,etag:m.headers.etag}}(t,n,null==h?void 0:h.etag,s);return!h||i.md&&h.md!==i.md?(await u.setAsync(n,t,i.etag,void 0,i.md),i.md):h.md}catch(e){if(i)throw e;return""}};if(h){const t=Date.now()-h.time,n=t>r;if(t>l)e.tickEvent("markdown.update.wait");else if(n&&(e.tickEvent("markdown.update.background"),p()),h.md)return h.md}return p()},t.privateDeleteAsync=function(e){return d({url:e,method:"DELETE"}).then(e=>e.json)},t.privatePostAsync=function(e,t,n=!1){return d({url:e,data:t||{},forceLiveEndpoint:n}).then(e=>e.json)},t.isLoggedIn=function(){return!!t.accessToken},t.isNavigatorOnline=h,t.isOnline=function(){return"undefined"!=typeof navigator&&h()&&(s=!0),s},t.getServiceUrl=function(){return t.apiRoot.replace(/\/api\/$/,"")},t.getUserId=function(){let e=/^0(\w+)\./.exec(t.accessToken);return e?e[1]:null},t.parseScriptId=function(t){var i;const s=e.appTarget;if(!t||!s.appTheme||!(null===(i=s.cloud)||void 0===i?void 0:i.sharing))return;let r=["makecode.com"];s.appTheme.embedUrl&&r.push(s.appTheme.embedUrl),s.appTheme.shareUrl&&r.push(s.appTheme.shareUrl),r=n.unique(r,e=>e).map(e=>n.escapeForRegex(n.stripUrlProtocol(e).replace(/\/$/,"")).toLowerCase());const a=`(?:(?:https://)?(?:${r.join("|")})/)`,o=new RegExp(`^${a}?(?:v[0-9]+/)?(?:(?:api/oembed\\?url=.*%2F([^&#]*)&.*)|(?:/?([a-z0-9\\-_]+)(?:[#?&].*)?))$`,"i").exec(t.trim()),l=(null==o?void 0:o[1])||(null==o?void 0:o[2]);return/^(_.{12}|S?[0-9\-]{23})$/.test(l)?l:void 0},t.initRegionAsync=async function(){var t;if(void 0===i)if(e.BrowserUtils.isLocalHost())i=e.cloud.DEV_REGION;else if(null===(t=e.webConfig)||void 0===t?void 0:t.cdnUrl)try{const t={url:new URL("geo",e.webConfig.cdnUrl).toString()},s=await n.requestAsync(t);200!==s.statusCode&&e.error(`Failed to get region: ${s.statusCode}`),i=s.text.trim()}catch(t){e.error("Unable to determine region",t),i="unknown"}else i="unknown"},t.getRegion=function(){return i||e.error("Accessing region before it is initialized. Call initRegionAsync first."),i}}(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.contentDiv.setAttribute("role","menu"),this.contentDiv.setAttribute("tabindex","0"),this.keyDownHandler=this.keyDownListener.bind(this),this.contentDiv.addEventListener("keydown",this.keyDownHandler),this.focusHandler=this.focusListener.bind(this),this.contentDiv.addEventListener("focus",this.focusHandler),this.blurHandler=this.blurListener.bind(this),this.contentDiv.addEventListener("blur",this.blurHandler),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)}keyDownListener(e){if(!this.selectedColRow)return;const[t,n]=this.selectedColRow,i=pxt.Util.isUserLanguageRtl()?"ArrowRight":"ArrowLeft",s=pxt.Util.isUserLanguageRtl()?"ArrowLeft":"ArrowRight";switch(e.code){case"ArrowUp":this.selectedColRow=[t,Math.max(0,n-1)];break;case"ArrowDown":this.selectedColRow=[t,Math.min(this.selectionButtons.length-1,n+1)];break;case i:this.selectedColRow=[Math.max(0,t-1),n];break;case s:this.selectedColRow=[Math.min(1,t+1),n];break;case"Enter":case"Space":return this.selectedElement.click(),e.stopPropagation(),void e.preventDefault();default:return}this.selectedElement.classList.remove("selected");const[r,a]=this.selectedColRow;this.selectedElement=0===r?this.selectionButtons[a]:this.previewButtons[a],this.selectedElement.classList.add("selected"),this.contentDiv.setAttribute("aria-activedescendant",getCellId(r,a));const o=this.contentDiv.getBoundingClientRect(),l=this.selectedElement.getBoundingClientRect();l.bottom>o.bottom?this.selectedElement.scrollIntoView({block:"end"}):l.top<o.top&&this.selectedElement.scrollIntoView({block:"start"}),e.stopPropagation(),e.preventDefault()}focusListener(e){this.selectedElement||(this.selectedColRow=[0,0],this.selectedElement=this.selectionButtons[0]),this.selectedElement.classList.add("selected");const[t,n]=this.selectedColRow;this.contentDiv.setAttribute("aria-activedescendant",getCellId(t,n))}blurListener(e){var t;this.contentDiv.removeAttribute("aria-activedescendant"),null===(t=this.selectedElement)||void 0===t||t.classList.remove("selected")}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(){var e;this.visible=!1,pxt.BrowserUtils.removeClass(this.contentDiv,"shown"),pxt.BrowserUtils.addClass(this.contentDiv,"hidden-above"),this.value=null,this.stopMelody(),this.contentDiv.removeAttribute("aria-activedescendant"),null===(e=this.selectedElement)||void 0===e||e.classList.remove("selected"),this.selectedElement=void 0,this.selectedColRow=void 0}clearDomReferences(){this.contentDiv.removeEventListener("keydown",this.keyDownHandler),this.contentDiv.removeEventListener("focus",this.focusHandler),this.contentDiv.removeEventListener("blur",this.blurHandler),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"}getLastFocusableElement(){return this.contentDiv}buildDom(){for(;this.contentDiv.firstChild;)this.contentDiv.removeChild(this.contentDiv.firstChild);const t=e.SampleMelodies;this.playIcons=[],this.selectionButtons=[],this.previewButtons=[];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",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:"menuitem",title:e.name,tabIndex:-1,id:getCellId(n,0)},()=>this.handleSelection(e));c.appendChild(a),c.appendChild(o),c.appendChild(l),r.appendChild(c),this.selectionButtons[n]=c;const u=t("div",{className:"melody-editor-button right-button",role:"menuitem",title:lf("Preview {0}",e.name),tabIndex:-1,id:getCellId(n,1)},()=>this.togglePlay(e,n)),d=t("i",{className:"play icon"});this.playIcons[n]=d,u.appendChild(d),r.appendChild(u),this.previewButtons[n]=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.playIcons[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.playIcons[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={}));const getCellId=(e,t)=>`:${e}-${0===t?"selection":"preview"}`;var 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,r=!1;function a(e){Object.keys(e).forEach(t=>{"string"==typeof e[t]?n[t]=e[t]:i[t]=e[t]})}!function(e){e[e.Off=0]="Off",e[e.Short=1]="Short",e[e.Verbose=2]="Verbose"}(s=t.ConsoleTickOptions||(t.ConsoleTickOptions={})),t.consoleTicks=s.Off,t.addDefaultProperties=a,t.enable=function(o){if(!e.aiTrackException||!e.aiTrackEvent||r)return;r=!0,"string"==typeof o&&0!=o.length||(o="en"),a({lang:o}),e.debug("setting up app insights");const l=e.tickEvent;e.tickEvent=function(r,a,o){if(a=e.Util.cleanData(a),t.consoleTicks!=s.Off){const n=t.consoleTicks==s.Short?"":`${(new Date).toLocaleTimeString(void 0,{hour12:!1})} - Tick - `,i=`${r} ${a?JSON.stringify(a):"<no data>"} ${o?JSON.stringify(o):"<no opts>"}`;e.log(n+i)}if(l&&l(r,a,o),(null==o?void 0:o.interactiveConsent)&&e.setInteractiveConsent(!0),a){const t=Object.assign({},n),s=Object.assign({},i);Object.keys(a).forEach(e=>{"string"==typeof a[e]?t[e]=a[e]:"number"==typeof a[e]?s[e]=a[e]:t[e]=JSON.stringify(a[e]||"")}),e.aiTrackEvent(r,t,s)}else e.aiTrackEvent(r)};const c=e.reportException;e.reportException=function(t,n){n=e.Util.cleanData(n),c&&c(t,n);const i={target:e.appTarget.id,version:e.appTarget.versions.target};n&&e.Util.jsonMergeFrom(i,n),e.aiTrackException(t,"exception",i)};const u=e.reportError;e.reportError=function(t,n,i){i=e.Util.cleanData(i),u&&u(t,n,i);try{throw n}catch(s){const r={target:e.appTarget.id,version:e.appTarget.versions.target,category:t,message:n};i&&e.Util.jsonMergeFrom(r,i),e.aiTrackException(s,"error",r)}}},t.trackPerformanceReport=function(){if(e.perf.perfReportLogged)return;const t=e.perf.report();if(t){const{durations:n,milestones:i}=t;e.tickEvent("performance.milestones",i),e.tickEvent("performance.durations",n)}}}(e.analytics||(e.analytics={}))}(pxt||(pxt={})),pxt||(pxt={}),function(e){!function(e){let t,n,i,s=0,r=!1;function 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(isNaN(e)||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",a="interactive-login-until";let o,l=!1;t.DEFAULT_USER_PREFERENCES=()=>({language:e.appTarget.appTheme.defaultLocale,highContrast:!1,accessibleBlocks:!1,colorThemeIds:{},reader:"",skillmap:{mapProgress:{},completedTags:{}},email:!1}),t.client=function(){if(!l)return o};let c=0,u=0;async function d(t,i){return i?await e.storage.shared.setAsync(n,t,i):await e.storage.shared.delAsync(n,t)}async function h(t){try{return await e.storage.shared.getAsync(n,t)}catch(e){return}}async function p(){const e=await h(i);return t.cachedHasAuthToken=!!e,e}async function f(e){return t.cachedHasAuthToken=!!e,await d(i,e)}async function m(){return!!await p()}async function g(){return t.cachedHasAuthToken=!1,await d(i,void 0)}async function b(){let i;try{i=await e.storage.shared.getAsync(n,r)}catch(e){i={}}return t.cachedUserState=i,i}async function y(i){return t.cachedUserState=Object.assign({},i),await e.storage.shared.setAsync(n,r,i)}async function v(){return t.cachedUserState=void 0,await e.storage.shared.delAsync(n,r)}async function w(t){var n;const i={};return(t=t||await p())&&(i.authorization=`mkcd ${t}`),i["x-pxt-target"]=null===(n=e.appTarget)||void 0===n?void 0:n.id,i}t.cachedHasAuthToken=!1,t.getAuthTokenAsync=p,t.hasAuthTokenAsync=m,t.getUserStateAsync=b,t.getAuthHeadersAsync=w;class A{constructor(){this.initialUserPreferences_=void 0,this.initialAuthCheck_=void 0,this.patchQueue=[],o=this}async initAsync(){const e=await b();this.setUserProfileAsync(null==e?void 0:e.profile),this.setUserPreferencesAsync(null==e?void 0:e.preferences)}async loginAsync(t,i,r=void 0){if(!x()||!function(e){return T().filter(t=>t.id===e).length>0}(t))return;r=null!=r?r:k,this.clearAuthStateAsync();const o={key:(Math.PI*Math.random()).toString(36).slice(2),callbackState:r,callbackPathname:window.location.pathname,idp:t,persistent:i},l=(parseInt(await h(a))||0)>Date.now(),c=e.Util.stringifyQueryString("/api/auth/login",{response_type:"token",provider:t,persistent:i,redirect_uri:`${window.location.origin}${window.location.pathname}?authcallback=1&state=${o.key}`,prompt:l?"select_account":"silent"}),u=await this.apiAsync(c);if(u.success)o.authCodeVerifier=u.resp.authCodeVerifier,await e.storage.shared.setAsync(n,s,o),e.tickEvent("auth.login.start",{provider:t}),window.location.href=u.resp.loginUrl;else try{await this.onSignInFailed()}catch(e){}}async logoutAsync(e){if(x()){await A.staticLogoutAsync(e);try{await this.onStateCleared()}catch(e){}try{await this.onSignedOut()}catch(e){}}}static async staticLogoutAsync(t){if(!x())return;e.tickEvent("auth.logout"),await d(a,(Date.now()+6e4).toString()),t=t?t.startsWith("#")?t:`#${t}`:"";const n=`${window.location.origin}${window.location.pathname}${window.location.search}${t}`;let i="";try{const t=e.Util.stringifyQueryString("/api/auth/logout",{redirect_uri:n,authcallback:"1"}),s=await A.staticApiAsync(t);s.success&&(i=s.resp.logoutUrl)}catch(e){}await g(),await v(),e.BrowserUtils.hasWindow()&&(i?window.location.href=i:(window.location.href=n,location.reload()))}async deleteProfileAsync(){var t;if(!await this.loggedInAsync())return;const n=await b(),i=null===(t=null==n?void 0:n.profile)||void 0===t?void 0:t.id,s=await this.apiAsync("/api/user",null,"DELETE");if(s.err)try{await this.onApiError(s.err)}catch(e){}else try{await this.clearAuthStateAsync();try{await this.onProfileDeleted(i)}catch(e){}}finally{e.tickEvent("auth.profile.deleted")}}async initialUserPreferencesAsync(){if(await this.loggedInAsync())return this.initialUserPreferences_||(this.initialUserPreferences_=this.fetchUserPreferencesAsync()),this.initialUserPreferences_}async userProfileAsync(){if(!await this.loggedInAsync())return;const e=await b();return Object.assign({},e.profile)}async userPreferencesAsync(){const e=await b();return Object.assign({},e.preferences)}async authCheckAsync(){var e;if(!x())return;if(!await m())return;const t=await b();return(null===(e=null==t?void 0:t.profile)||void 0===e?void 0:e.id)?this.initialAuthCheck_||(this.initialAuthCheck_=Promise.resolve(t.profile)):this.initialAuthCheck_||(this.initialAuthCheck_=this.fetchUserAsync()),this.initialAuthCheck_}async loggedInAsync(){return!!await this.authCheckAsync()&&await this.hasUserIdAsync()}async updateUserProfileAsync(e){if(!await this.loggedInAsync())return!1;const t=await b(),n=await this.apiAsync("/api/user/profile",{id:t.profile.id,username:e.username,avatarUrl:e.avatarUrl});return n.success&&await this.setUserProfileAsync(n.resp),n.success}async patchUserPreferencesAsync(n,i={}){const s=async()=>({success:!0,res:await this.userPreferencesAsync()});if(!(n=(n=Array.isArray(n)?n:[n]).filter(e=>!!e)).length)return await s();const r=(t,n,i)=>{const s=e.U.deepCopy(t);ts.pxtc.jsonPatch.patchInPlace(s,n);let r=ts.pxtc.jsonPatch.diff(t,s);return r.length&&i&&(r=r.filter(i)),r},a=await this.userPreferencesAsync(),o=r(a,n,i.filter);if(!o.length)return await s();if(ts.pxtc.jsonPatch.patchInPlace(a,o),await this.setUserPreferencesAsync(a),!await this.loggedInAsync())return await s();this.patchQueue.push({ops:n,filter:i.filter}),clearTimeout(c);const l=async()=>{if(u=0,!this.patchQueue.length)return await s();const n=await this.apiAsync("/api/user/preferences");if(!n.success)return e.reportError("identity","failed to fetch preferences for patch",n),{success:!1,res:void 0};const i=e.U.deepCopy(n.resp)||t.DEFAULT_USER_PREFERENCES(),a=this.patchQueue;this.patchQueue=[],a.forEach(e=>{const t=r(i,e.ops,e.filter);ts.pxtc.jsonPatch.patchInPlace(i,t)});const o=pxtc.jsonPatch.diff(n.resp,i),l=await this.apiAsync("/api/user/preferences",o,"PATCH");return l.success?this.setUserPreferencesAsync(l.resp):e.reportError("identity","failed to patch preferences",l),{success:l.success,res:l.resp}};return i.immediate?await l():(u||(u=e.U.now()),1e4<e.U.now()-u?await l():(c=setTimeout(l,1e3),{success:!1,res:void 0}))}async hasUserIdAsync(){var e;if(!x())return!1;if(!await m())return;const t=await b();return!!(null===(e=null==t?void 0:t.profile)||void 0===e?void 0:e.id)}async fetchUserAsync(){var e;if(!x())return;if(!await m())return;const t=await b();if(null===(e=null==t?void 0:t.profile)||void 0===e?void 0:e.id)return t.profile;const n=await this.apiAsync("/api/user/profile");if(n.success){const e=n.resp;return await this.setUserProfileAsync(e),e}}async setUserProfileAsync(e){const t=await this.hasUserIdAsync();await this.transformUserProfileAsync(e);const n=await this.hasUserIdAsync();try{await this.onUserProfileChanged()}catch(e){}if(n&&!t)try{await this.onSignedIn()}catch(e){}else if(!n&&t)try{await this.onSignedOut()}catch(e){}}async setUserPreferencesAsync(e){var n;const i=await b(),s=null!==(n=null==i?void 0:i.preferences)&&void 0!==n?n:t.DEFAULT_USER_PREFERENCES(),r=ts.pxtc.jsonPatch.diff(s,e),a=await this.transformUserPreferencesAsync(Object.assign(Object.assign({},s),e));try{await this.onUserPreferencesChanged(r)}catch(e){}return a}async fetchUserPreferencesAsync(){if(!await this.loggedInAsync())return;await b();const e=await this.apiAsync("/api/user/preferences");if(e.success&&e.resp){return this.setUserPreferencesAsync(e.resp)}}async transformUserProfileAsync(e){let t=await b();return t=Object.assign(Object.assign({},t),{profile:Object.assign({},e)}),await y(t),t.profile}async transformUserPreferencesAsync(e){let t=await b();return t=Object.assign(Object.assign({},t),{preferences:Object.assign({},e)}),await y(t),t.preferences}async clearAuthStateAsync(){await g(),await v();try{await this.onStateCleared()}catch(e){}}async apiAsync(e,t,n,i){return await A.staticApiAsync(e,t,n,i)}static async staticApiAsync(t,n,i,s){const r=await w(s);return t=e.BrowserUtils.isLocalHostDev()?`${e.cloud.DEV_BACKEND}${t}`:t,e.Util.requestAsync({url:t,headers:r,data:n,method:i||(n?"POST":"GET"),withCredentials:!0}).then(e=>({statusCode:e.statusCode,resp:e.json,success:2===Math.floor(e.statusCode/100),err:null})).catch(async e=>(/logout/.test(t)||401!=e.statusCode||await A.staticLogoutAsync(),{statusCode:e.statusCode,err:e,resp:null,success:!1}))}}t.AuthClient=A;const k={hash:"",params:{}};function T(){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 x(){return!l&&!e.BrowserUtils.isPxtElectron()&&T().length>0}function E(e,t){return e.id===t.id&&e.sourceURL===t.sourceURL}t.loginCallbackAsync=async function(t){let i,r=Object.assign({},k);do{if(i=await e.storage.shared.getAsync(n,s),!i)return void e.debug("Auth state not found in storge.");await e.storage.shared.delAsync(n,s);const o=t.state;if(!o||i.key!==o)return void e.debug("Failed to get auth state for key");r=Object.assign(Object.assign({},k),i.callbackState);const l=t.error;if(l){const n=t.error_description;e.tickEvent("auth.login.error",{error:l,provider:i.idp}),e.log(`Auth failed: ${l}:${n}`),r=Object.assign({},k);break}const c=t.token;if(!c){e.debug("Missing authToken in auth callback.");break}if(i.authCodeVerifier){const t=e.Util.stringifyQueryString("/api/otac/check",{persistent:i.persistent});await A.staticApiAsync(t,null,null,i.authCodeVerifier)}await f(c),await d(a,void 0),e.tickEvent("auth.login.success",{provider:i.idp})}while(0);const o=r.hash.startsWith("#")?r.hash:`#${r.hash}`,l=e.Util.stringifyQueryString("",r.params),c=`${i.callbackPathname.startsWith("/")?i.callbackPathname:`/${i.callbackPathname}`}${l}${o}`;window.location.href=c},t.identityProviders=T,t.identityProvider=function(e){return T().filter(t=>t.id===e).shift()},t.hasIdentity=x,t.enableAuth=function(e=!0){l=!e},t.userName=function(e){var t,n,i,s;return null!==(s=null!==(n=null===(t=null==e?void 0:e.idp)||void 0===t?void 0:t.displayName)&&void 0!==n?n:null===(i=null==e?void 0:e.idp)||void 0===i?void 0:i.username)&&void 0!==s?s:"??"},t.identityProviderId=function(e){var t;return null===(t=null==e?void 0:e.idp)||void 0===t?void 0:t.provider},t.firstName=function(t){const n=e.auth.userName(t);return(null==n?void 0:n.split(" ").shift())||n},t.userInitials=function(t){const n=e.auth.userName(t);return ts.pxtc.Util.initials(n)},t.generateUserProfilePicDataUrl=function(t){var n,i;if(null===(i=null===(n=null==t?void 0:t.idp)||void 0===n?void 0:n.picture)||void 0===i?void 0:i.encoded){const n=window.URL||window.webkitURL;try{const i=e.Util.stringToUint8Array(atob(t.idp.picture.encoded)),s=new Blob([i],{type:t.idp.picture.mimeType});t.idp.picture.dataUrl=n.createObjectURL(s)}catch(e){}}},t.badgeEquals=E,t.hasBadge=function(e,t){return e.badges.some(e=>E(e,t))}}(e.auth||(e.auth={}))}(pxt||(pxt={})),function(e){e.tickEvent=function(e){}}(pxt||(pxt={})),function(e){let t;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Log=1]="Log",e[e.Warning=2]="Warning",e[e.Error=3]="Error"}(t=e.LogLevel||(e.LogLevel={}));class n{constructor(){this.setLogLevel(t.Info)}setLogLevel(e){this.logLevel=e}getLogLevel(){return this.logLevel}info(...e){this.shouldLog(t.Info)&&(null===console||void 0===console?void 0:console.info)&&console.info.call(null,...e)}log(...e){this.shouldLog(t.Log)&&(null===console||void 0===console?void 0:console.log)&&console.log.call(null,...e)}debug(...e){this.shouldLog(t.Debug)&&(null===console||void 0===console?void 0:console.debug)&&console.debug.call(null,...e)}error(...e){this.shouldLog(t.Error)&&(null===console||void 0===console?void 0:console.error)&&console.error.call(null,...e)}warn(...e){this.shouldLog(t.Warning)&&(null===console||void 0===console?void 0:console.warn)&&console.warn.call(null,...e)}shouldLog(e){return e>=this.logLevel}}e.ConsoleLogger=n;let i=new n;e.info=function(...e){i.info(...e)},e.log=function(...e){i.log(...e)},e.debug=function(...e){i.debug(...e)},e.error=function(...e){i.error(...e)},e.warn=function(...e){i.warn(...e)},e.setLogger=function(e){const t=null==i?void 0:i.getLogLevel();i=e,void 0!==t&&i.setLogLevel(t)},e.setLogLevel=function(e){i.setLogLevel(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 .!?\-$])/gu,e=>"&#"+e.codePointAt(0)+";"):e},e.htmlUnescape=function(e){return e?e.replace(/(&#\d+;)/g,e=>String.fromCodePoint(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,3})-(\w{2,4}$)/i.exec(e);return t&&t[1]&&t[2]?[`${t[1].toLowerCase()}-${t[2].toUpperCase()}`,t[1].toLowerCase(),`${t[1].toLowerCase()}-${t[2].toLowerCase()}`]:[(e||"en").toLowerCase()]}function l(){return a()==e.TRANSLATION_LOCALE}function c(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=l,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=c,e.fmt=function(e,...t){return c(e,t)};const u={};e.dumpLocStats=function(){const e={};Object.keys(u).sort((e,t)=>u[t]-u[e]).forEach(t=>e[t]=t),pxt.log("prioritized list of strings:"),pxt.log(JSON.stringify(e,null,2))};function d(t,n){if(!t)return t;u[t]=(u[t]||0)+1;let i=e._localize(t);return i=i.replace(/^\{(id|loc):[^\}]+\}/g,""),c(i,n)}e.lf_va=d,e.lf=function(e,...t){return d(e,t)},e.rlf=function(e,...t){return d(e,t)},e.blf=function(e){return l()?e:d(e,[])},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.deepEqual=function e(t,n){if(t===n)return!0;if(t&&n&&"object"==typeof t&&"object"==typeof n){const i=Array.isArray(t),s=Array.isArray(n);if(i&&s){if(t.length!==n.length)return!1;for(let i=0;i<t.length;++i)if(!e(t[i],n[i]))return!1;return!0}if(i!==s)return!1;const r=Object.keys(t);if(r.length!==Object.keys(n).length)return!1;for(const i of r){if(!n.hasOwnProperty(i))return!1;if(!e(t[i],n[i]))return!1}return!0}return t!=t&&n!=n}}(e.Util||(e.Util={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={}));const lf=ts.pxtc.Util.lf;var Measurements,pxt,ts;!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.sanitizeFileName=function(e){return e.replace(/[()\\\/.,?*^:<>!;'#$%^&|"@+=«»°{}\[\]¾½¼³²¦¬¤¢£~¯¸`±\x00-\x1F]/g,"").trim().replace(/\s+/g,"-")},n.repeatMap=function(e,t){e=e||0;let n=[];for(let i=0;i<e;++i)n.push(t(i));return n},n.listsEqual=function(e,t){if(!e||!t||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0},n.oops=function(e="OOPS"){throw new Error(e)},n.reversed=function(e){return(e=e.slice(0)).reverse(),e},n.arrayEquals=function(e,t,n=(e,t)=>e===t){if(e==t)return!0;if(!e&&t||!t&&e||e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!n(e[i],t[i]))return!1;return!0},n.iterMap=function(e,t){Object.keys(e).forEach(n=>t(n,e[n]))},n.mapMap=function(e,t){let n={};return Object.keys(e).forEach(i=>n[i]=t(i,e[i])),n},n.values=function(e){return Object.keys(e||{}).map(t=>e[t])},n.pushRange=i,n.concatArrayLike=function(e){return s(e)},n.concat=s,n.memcpy=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=n&&!i;return clearTimeout(i),i=setTimeout(function(){i=null,n||e.apply(s,r)},t),a&&e.apply(s,r),i}};function d(e){return e&&(e=e.replace(/\\/g,"/")),e}function h(e){const i={url:`${encodeURI(e.url.replace(/[?#].*/,"..."))}`,method:`${e.method||"GET"}`};return pxt.perf.measureStart(Measurements.NetworkRequest),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}).then(e=>{const t=e.headers["content-length"];if(t)i.sizeInBytes=`${t}`;else if(e.text&&pxt.perf.isEnabled()){const t=(new TextEncoder).encode(e.text);i.sizeInBytes=t.length+""}return i.statusCode=`${e.statusCode}`,e}).finally(()=>{pxt.perf.measureEnd(Measurements.NetworkRequest,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=n&&!i;i||(i=setTimeout(function(){i=null,n||e.apply(s,r)},t)),a&&e.apply(s,r)}},n.randomPermute=function(e){for(let t=0;t<e.length;++t){let n=m()%e.length,i=e[t];e[t]=e[n],e[n]=i}},n.randomPick=function(e){return 0==e.length?null:e[m()%e.length]},n.timeSince=function(e){let t=(Date.now()-(e*=1e3))/1e3;return isNaN(t)?"":t<-30?(t=-t,t<60?n.lf("in a few seconds"):t<120?n.lf("in a minute"):t<3600?n.lf("in {0} minute{0:s}",Math.floor(t/60)):t<7200?n.lf("in an hour"):t<86400?n.lf("in {0} hour{0:s}",Math.floor(t/60/60)):t<2592e3?n.lf("in {0} day{0:s}",Math.floor(t/60/60/24)):t<31536e3?n.lf("in {0} month{0:s}",Math.floor(t/60/60/24/30)):n.lf("in {0} year{0:s}",Math.floor(t/60/60/24/365))):t<0?n.lf("now"):t<10?n.lf("a few seconds ago"):t<60?n.lf("{0} second{0:s} ago",Math.floor(t)):t<120?n.lf("a minute ago"):t<3600?n.lf("{0} minute{0:s} ago",Math.floor(t/60)):t<7200?n.lf("an hour ago"):t<86400?n.lf("{0} hour{0:s} ago",Math.floor(t/60/60)):t<2592e3?n.lf("{0} day{0:s} ago",Math.floor(t/60/60/24)):t<31536e3?n.lf("{0} month{0:s} ago",Math.floor(t/60/60/24/30)):n.lf("{0} year{0:s} ago",Math.floor(t/60/60/24/365))},n.unicodeToChar=function(e){return e.replace(/\\u([\d\w]{4})/gi,function(e,t){return String.fromCharCode(parseInt(t,16))})},n.escapeForRegex=function(e){return null==e?void 0:e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},n.stripUrlProtocol=function(e){return null==e?void 0:e.replace(/.*?:\/\//g,"")},n.normalizePath=d,n.pathJoin=function(e,t){if(d(e),d(t),e||t)return e?t?("/"!==e.charAt(e.length-1)&&(e+="/"),"/"==t.charAt(0)&&(t=t.substring(1)),e+t):e:t},n.isNodeJS="undefined"==typeof window,n.requestAsync=h,n.httpGetTextAsync=function(e){return h({url:e}).then(e=>e.text)},n.httpGetJsonAsync=function(e){return h({url:e}).then(e=>e.json)},n.httpPostJsonAsync=function(e,t){return h({url:e,data:t||{}}).then(e=>e.json)},n.stringToUint8Array=function(e){let t=e.length,n=new Uint8Array(t);for(let i=0;i<t;++i)n[i]=255&e.charCodeAt(i);return n},n.uint8ArrayToString=function(e){let t=e.length,n="";for(let i=0;i<t;++i)n+=String.fromCharCode(e[i]);return n},n.fromUTF8=function(e){if(!e)return"";let t="";for(let n=0;n<e.length;++n){let i=255&e.charCodeAt(n);t+=37==i||i>127?"%"+i.toString(16):e.charAt(n)}return decodeURIComponent(t)},n.toUTF8=p,n.toHex=function(e){let t="";for(let n=0;n<e.length;++n)t+=("0"+e[n].toString(16)).slice(-2);return t},n.fromHex=function(e){let t=new Uint8Array(e.length>>1);for(let n=0;n<e.length;n+=2)t[n>>1]=parseInt(e.slice(n,n+2),16);return t};n.PromiseQueue=class{constructor(){this.promises={}}enqueue(e,t){return new Promise((n,i)=>{let s=this.promises[e];s||(s=this.promises[e]=[]),s.push(()=>t().finally(()=>{s.shift(),0==s.length?delete this.promises[e]:s[0]()}).then(n,i)),1==s.length&&s[0]()})}};function f(){return Date.now()}function m(){let e=new Uint8Array(4);return n.getRandomBuf(e),new Uint32Array(e.buffer)[0]}function g(e,t,n){function i(i){pxt.debug(`downloading translations for ${e} ${t}`);let s=pxt.BrowserUtils.isLocalHost()||pxt.webConfig.isStatic?"https://makecode.com/api/":"",r=`${s}translations?lang=${encodeURIComponent(e)}&filename=${encodeURIComponent(t)}&approved=true`;const a={};return n&&!pxt.Cloud.useCdnApi()&&(a["If-None-Match"]=n),(s?h:pxt.Cloud.apiRequestWithCdnAsync)({url:r,headers:a}).then(s=>304==s.statusCode||200==s.statusCode?(n=s.headers.etag||"",pxt.BrowserUtils.translationDbAsync().then(r=>r.setAsync(e,t,n,s.json||i)).then(()=>s.json||i)):s.json,e=>{pxt.log(`failed to load translations from ${r}`)})}return pxt.BrowserUtils.translationDbAsync().then(n=>n.getAsync(e,t)).then(e=>{if(e){n=e.etag;return(Date.now()-e.time)/1e3>300&&i(e.strings),e.strings}return i()})}function b(e){let[t,i]=n.normalizeLanguageCode(e),s=pxt.appTarget.appTheme;if(s&&s.availableLocales){if(s.availableLocales.indexOf(t)>-1)return!0;if(i&&s.availableLocales.indexOf(i)>-1)return!0}return!1}let y;function v(e,i,s,r,a){if(a=a||y.Editor,"en-US"===(s=n.normalizeLanguageCode(s)[0])||"en"===s)return Promise.resolve(void 0);let o,l,c=`${s}/${r}/${a}`;if(n.translationsCache()[c])return Promise.resolve(n.translationsCache()[c]);switch(a){case y.Editor:o=[{staticName:"strings.json",path:"strings.json"},{staticName:"target-strings.json",path:e+"/target-strings.json"}];break;case y.Sim:o=[{staticName:"sim-strings.json",path:e+"/sim-strings.json"}];break;case y.Apis:o=[{staticName:"bundled-strings.json",path:e+"/bundled-strings.json"}];break;case y.SkillMap:o=[{staticName:"skillmap-strings.json",path:"/skillmap-strings.json"}]}function u(e){e&&(l||(l={}),Object.keys(e).filter(t=>!!e[t]).forEach(t=>l[t]=e[t]))}if(r){let r=0;return t.U.promiseMapAllSeries(o,e=>g(s,e.path).then(u,e=>{pxt.log(e.message),++r})).then(()=>(r&&(n.translationsCache()[c]=l),r!==o.length&&l?Promise.resolve(l):(pxt.tickEvent("translations.livetranslationsfailed"),v(e,i,s,!1,a))))}return Promise.all(o.map(e=>n.httpGetJsonAsync(`${i}locales/${s}/${e.staticName}`).catch(e=>{}))).then(e=>{let t={};e.forEach(e=>pxt.Util.jsonMergeFrom(t,e)),Object.keys(t).length&&(l=t,n.translationsCache()[c]=l)},e=>{pxt.error("failed to load localizations")}).then(()=>l)}function w(e){const t={};for(const n of Object.keys(e))t[n]=A(e[n]);return t}function A(e){var t;return{attributes:Object.assign({},e.attributes),parameters:null===(t=e.parameters)||void 0===t?void 0:t.map(k),extendsTypes:e.extendsTypes?[...e.extendsTypes]:void 0,pkgs:e.pkgs?[...e.pkgs]:void 0,combinedProperties:e.combinedProperties?[...e.combinedProperties]:void 0,name:e.name,namespace:e.namespace,fileName:e.fileName,kind:e.kind,retType:e.retType,isInstance:e.isInstance,isContextual:e.isContextual,qName:e.qName,pkg:e.pkg,snippet:e.snippet,snippetName:e.snippetName,snippetWithMarkers:e.snippetWithMarkers,pySnippet:e.pySnippet,pySnippetName:e.pySnippetName,pySnippetWithMarkers:e.pySnippetWithMarkers,blockFields:e.blockFields,isReadOnly:e.isReadOnly,pyName:e.pyName,pyQName:e.pyQName,snippetAddsDefinitions:e.snippetAddsDefinitions}}function k(e){var n,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(T),handlerParameters:null===(i=e.handlerParameters)||void 0===i?void 0:i.map(T),options:e.options?t.U.clone(e.options):void 0,isEnum:e.isEnum}}function T(e){return{name:e.name,type:e.type}}function x(e){if(!e)return e;const t=[{label:"Google API Key",regex:/AIza[A-Za-z0-9_\\\-]{35}/},{label:"Slack Token",regex:/xox[pbar]\-[A-Za-z0-9]/},{label:"GitHub Token",regex:/(gh[psuro]_[a-zA-Z0-9]{36}|github_pat_[a-zA-Z0-9]{22}_[a-zA-Z0-9]{59})/},{label:"Generic Secret",regex:/\b(token|signature|password|passwd|pwd|android:value)[^a-zA-Z0-9]{0,200}/i},{label:"CLI Credentials",regex:/((login|psexec|(certutil|psexec)\.exe).{1,50}(\s-u(ser(name)?)?\s+.{3,100})?\s-(admin|user|vm|root)?p(ass(word)?)?\s+["']?[^$\-\/\s]|(^|[\s\r\n\\])net(\.exe)?.{1,5}(user\s+|share\s+\/user:| user -? secrets ? set) \s + [^ $\s \/])/},{label:"JWT Token",regex:/\beyJ[A-Za-z0-9_\-]+?\.[A-Za-z0-9_\-]+?\.[A-Za-z0-9_\-]+?\b/},{label:"Email",regex:/\b[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,63}\b/i}];for(const n of t)if(n.regex.test(e))return`<REDACTED: ${n.label}>`;return e}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.runWithBackoffAsync=async function(e,t,n,i,s,r,a=1.5){let o=n;const l=Date.now();for(;Date.now()-l<s;){const n=await e();if(t(n))return n;await pxt.Util.timeout(o),o=Math.min(o*a,i)}throw new Error(r)},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";case"wasm":return"application/wasm";default:return"application/octet-stream"}},n.randomUint32=m,n.guidGen=function(){function e(){return(65536|m()).toString(16).slice(-4)}return e()+e()+"-"+e()+"-4"+e().slice(-3)+"-"+e()+"-"+e()+e()+e()},n.downloadLiveTranslationsAsync=g,n.pxtLangCookieId="PXT_LANG",n.langCookieExpirationDays=30,n.allLanguages={af:{englishName:"Afrikaans",localizedName:"Afrikaans"},ar:{englishName:"Arabic",localizedName:"العربية"},az:{englishName:"Azerbaijani",localizedName:"آذربایجان دیلی"},bg:{englishName:"Bulgarian",localizedName:"български"},bi:{englishName:"Bislama",localizedName:"Bislama"},bn:{englishName:"Bengali",localizedName:"বাংলা"},ca:{englishName:"Catalan",localizedName:"Català"},cs:{englishName:"Czech",localizedName:"Čeština"},cy:{englishName:"Welsh",localizedName:"Cymraeg"},da:{englishName:"Danish",localizedName:"Dansk"},de:{englishName:"German",localizedName:"Deutsch"},el:{englishName:"Greek",localizedName:"Ελληνικά"},en:{englishName:"English",localizedName:"English"},"es-ES":{englishName:"Spanish (Spain)",localizedName:"Español (España)"},"es-MX":{englishName:"Spanish (Mexico)",localizedName:"Español (México)"},et:{englishName:"Estonian",localizedName:"Eesti"},eu:{englishName:"Basque",localizedName:"Euskara"},fa:{englishName:"Persian",localizedName:"فارسی"},fi:{englishName:"Finnish",localizedName:"Suomi"},fil:{englishName:"Filipino",localizedName:"Filipino"},fo:{englishName:"Faroese",localizedName:"føroyskt"},fr:{englishName:"French",localizedName:"Français"},"fr-CA":{englishName:"French (Canada)",localizedName:"Français (Canada)"},"ga-IE":{englishName:"Irish",localizedName:"Gaeilge"},gl:{englishName:"Galician",localizedName:"galego"},gn:{englishName:"Guarani",localizedName:"Avañe'ẽ"},"gu-IN":{englishName:"Gujarati",localizedName:"ગુજરાતી"},haw:{englishName:"Hawaiian",localizedName:"ʻŌlelo Hawaiʻi"},hi:{englishName:"Hindi",localizedName:"हिन्दी"},he:{englishName:"Hebrew",localizedName:"עברית"},hr:{englishName:"Croatian",localizedName:"Hrvatski"},hu:{englishName:"Hungarian",localizedName:"Magyar"},"hy-AM":{englishName:"Armenian (Armenia)",localizedName:"Հայերէն (Հայաստան)"},id:{englishName:"Indonesian",localizedName:"Bahasa Indonesia"},is:{englishName:"Icelandic",localizedName:"Íslenska"},it:{englishName:"Italian",localizedName:"Italiano"},ja:{englishName:"Japanese",localizedName:"日本語"},"ja-HIRA":{englishName:"Hiragana",localizedName:"にほんご"},ka:{englishName:"Georgian",localizedName:"ქართული"},kab:{englishName:"Kabyle",localizedName:"شئعم"},kk:{englishName:"Kazakh",localizedName:"қазақ тілі"},km:{englishName:"Khmer",localizedName:"ខ្មែរ"},kmr:{englishName:"Kurmanji (Kurdish)",localizedName:"کورمانجی"},kn:{englishName:"Kannada",localizedName:"ಕನ್ನಡ"},ko:{englishName:"Korean",localizedName:"한국어"},lt:{englishName:"Lithuanian",localizedName:"Lietuvių"},lv:{englishName:"Latvian",localizedName:"Latviešu"},"ml-IN":{englishName:"Malayalam",localizedName:"മലയാളം"},mr:{englishName:"Marathi",localizedName:"मराठी"},ms:{englishName:"Malay",localizedName:"Melayu"},nl:{englishName:"Dutch",localizedName:"Nederlands"},no:{englishName:"Norwegian",localizedName:"Norsk"},nb:{englishName:"Norwegian Bokmal",localizedName:"Norsk bokmål"},"nn-NO":{englishName:"Norwegian Nynorsk",localizedName:"Norsk nynorsk"},"pa-IN":{englishName:"Punjabi",localizedName:"ਪੰਜਾਬੀ"},pl:{englishName:"Polish",localizedName:"Polski"},ps:{englishName:"Pashto",localizedName:"پښتو"},"pt-BR":{englishName:"Portuguese (Brazil)",localizedName:"Português (Brasil)"},"pt-PT":{englishName:"Portuguese (Portugal)",localizedName:"Português (Portugal)"},ro:{englishName:"Romanian",localizedName:"Română"},ru:{englishName:"Russian",localizedName:"Русский"},sat:{englishName:"Santali",localizedName:"ᱥᱚᱸᱴᱚᱞᱤ"},"si-LK":{englishName:"Sinhala",localizedName:"සිංහල"},sk:{englishName:"Slovak",localizedName:"Slovenčina"},sl:{englishName:"Slovenian",localizedName:"Slovenski"},sq:{englishName:"Albanian",localizedName:"shqip"},sr:{englishName:"Serbian (Cyrillic)",localizedName:"Srpski"},su:{englishName:"Sundanese",localizedName:"ᮘᮞ ᮞᮥᮔ᮪ᮓ"},"sv-SE":{englishName:"Swedish",localizedName:"Svenska"},sw:{englishName:"Swahili",localizedName:"Kiswahili"},"sw-TZ":{englishName:"Swahili (Tanzania)",localizedName:"Kiswahili (Tanzania)"},ta:{englishName:"Tamil",localizedName:"தமிழ்"},te:{englishName:"Telugu",localizedName:"తెలుగు"},th:{englishName:"Thai",localizedName:"ภาษาไทย"},tl:{englishName:"Tagalog",localizedName:"ᜏᜒᜃᜅ᜔ ᜆᜄᜎᜓᜄ᜔"},tr:{englishName:"Turkish",localizedName:"Türkçe"},uk:{englishName:"Ukrainian",localizedName:"Українська"},"ur-IN":{englishName:"Urdu (India)",localizedName:"اردو (ہندوستان)"},"ur-PK":{englishName:"Urdu (Pakistan)",localizedName:"اردو (پاکستان)"},vi:{englishName:"Vietnamese",localizedName:"Tiếng việt"},"zh-CN":{englishName:"Chinese (Simplified)",localizedName:"中文(简体)"},"zh-TW":{englishName:"Chinese (Traditional)",localizedName:"中文(繁體)"}},n.isLocaleEnabled=b,n.updateLocalizationAsync=function(t){const{targetId:i,baseUrl:s,force:r}=t;let{code:a}=t;if(a=n.normalizeLanguageCode(a)[0],"en-US"===a&&(a="en"),a===n.userLanguage()||!b(a)&&!r)return pxt.debug(`loc: ${a} (using built-in)`),Promise.resolve();pxt.debug(`loc: ${a}`);const o=pxt.Util.liveLocalizationEnabled();return v(i,s,a,o,e.pxtc.Util.TranslationsKind.Editor).then(t=>{var r;return t&&(n.setUserLanguage(a),null===(r=pxt.analytics)||void 0===r||r.addDefaultProperties({lang:a}),n.setLocalizedStrings(t)),e.pxtc.Util.downloadTranslationsAsync(i,s,a,o,e.pxtc.Util.TranslationsKind.Apis).then(t=>{t&&(e.pxtc.apiLocalizationStrings=t)})})},function(e){e[e.Editor=0]="Editor",e[e.Sim=1]="Sim",e[e.Apis=2]="Apis",e[e.SkillMap=3]="SkillMap"}(y=n.TranslationsKind||(n.TranslationsKind={})),n.downloadTranslationsAsync=v,n.capitalize=function(e){return e?e[0].toLocaleUpperCase()+e.slice(1):e},n.uncapitalize=function(e){return(e||"").split(/(?=[A-Z])/g).join(" ").toLowerCase()},n.camelCaseToLowercaseWithSpaces=function(e){return e.replace(/([A-Z])/gm," $1").toLocaleLowerCase().trim()},n.snakeCaseToLowercaseWithSpaces=function(e){return e.replace(/_/g," ").toLocaleLowerCase().trim()},n.range=function(e){let t=[];for(let n=0;n<e;++n)t.push(n);return t},n.multipartPostAsync=function(e,t={},i=null,s=null){const r="--------------------------0461489f461126c5";let 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&~++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(!(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&~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),highlightBlocks:Object.assign({},t.highlightBlocks),validateBlocks:Object.assign({},t.validateBlocks)}}}return a},n.cloneApis=w,n.cloneSymbolInfo=A,n.toUTF8Array=function(e){return(new TextEncoder).encode(e)},n.fromUTF8Array=function(e){return(new TextDecoder).decode(e)},n.getHomeUrl=function(){var e,t,n;let i=null===(e=pxt.webConfig)||void 0===e?void 0:e.relprefix.substr(0,pxt.webConfig.relprefix.length-3);return pxt.appTarget.appTheme.homeUrl&&i?((null===(t=pxt.appTarget.appTheme.homeUrl)||void 0===t?void 0:t.lastIndexOf("/"))===(null===(n=pxt.appTarget.appTheme.homeUrl)||void 0===n?void 0:n.length)-1&&(i=i.substr(1)),pxt.appTarget.appTheme.homeUrl+i):pxt.appTarget.appTheme.homeUrl},n.isExperienceSupported=function(e){var t,n,i,s;const r=null===(i=null===(n=null===(t=pxt.appTarget)||void 0===t?void 0:t.appTheme)||void 0===n?void 0:n.supportedExperiences)||void 0===i?void 0:i.map(e=>e.toLocaleLowerCase()),a=e.toLocaleLowerCase();return null!==(s=null==r?void 0:r.includes(a))&&void 0!==s&&s},n.ocvEnabled=function(){var e,t,n,i;return(null===(t=null===(e=pxt.webConfig)||void 0===e?void 0:e.ocv)||void 0===t?void 0:t.appId)&&(null===(i=null===(n=pxt.webConfig)||void 0===n?void 0:n.ocv)||void 0===i?void 0:i.iframeEndpoint)},n.bresenhamLine=function(e,t,n,i,s){const r=n-e,a=i-t;if(0===r){const n=a>=0?i:t;for(let r=a>=0?t:i;r<=n;r++)s(e,r);return}const o=r>0?1:-1,l=a>0?1:-1,c=Math.abs(a/r);let u=0,d=t;for(let t=e;o>0?t<=n:t>=n;t+=o)for(s(t,d),u+=c;u>=.5;)(l>0?d<=i:d>=i)&&s(t,d),d+=l,u-=1},n.isFeatureEnabled=function(e){var t,n;const i=null===(n=null===(t=pxt.appTarget.appTheme)||void 0===t?void 0:t.enabledFeatures)||void 0===n?void 0:n[e];if(!i)return!1;let s=!0;const r=pxt.Cloud.getRegion()?pxt.Cloud.getRegion().toUpperCase():void 0;return i.includeRegions&&(s=r&&i.includeRegions.some(e=>e.toUpperCase()==r)),s&&i.excludeRegions&&(s=r&&!i.excludeRegions.some(e=>e.toUpperCase()==r)),s},n.cleanData=function(e){if(!e)return e;let t;if("string"==typeof e)t=x(e);else if("object"==typeof e){t={};for(const[n,i]of Object.entries(e))t[n]="string"==typeof i?x(i):i}else t=e;return t}}(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(Measurements.Sha256Buffer);const n=r(e.Util.toUTF8Array(t));return pxt.perf.measureEnd(Measurements.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(n){var i;(i=n.tests||(n.tests={})).diffTests=function(){const n=[{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 n){pxt.log(i.comment);const n=e.pxtc.jsonPatch.diff(i.obja,i.objb);t.U.deepEqual(n,i.expected)?pxt.log("succeeded"):(pxt.error("FAILED"),pxt.log("got",n),pxt.log("exp",i.expected))}},i.patchTests=function(){const n=[{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 n)pxt.log(i.comment),e.pxtc.jsonPatch.patchInPlace(i.obj,i.patches),t.U.deepEqual(i.obj,i.expected)&&i.validate&&!i.validate(i.obj)?i.expected&&(pxt.error("FAILED"),pxt.log("got",i.obj),pxt.log("exp",i.expected)):pxt.log("succeeded")}}(t.jsonPatch||(t.jsonPatch={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){e.perf||(e.perf={})}(pxt||(pxt={})),pxt.perf.isEnabled||(pxt.perf.isEnabled=()=>!1),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(e,t,n){if(Array.isArray(e))return e.map(e=>o(e,t,n));if(e&&"object"==typeof e){for(const i of Object.keys(e))e[i]=o(e[i],t,n);return e}return"string"==typeof e&&t.test(e)?n(e):e}function l(){let t=e.appTarget.compile;t||(t=e.appTarget.compile={isNative:!1,hasHex:!1,switches:{}}),t.hasHex&&(t.nativeType||(t.nativeType=pxtc.NATIVE_TYPE_THUMB)),t.switches||(t.switches={}),t.nativeType==pxtc.NATIVE_TYPE_VM&&(t.sourceMap=!0),e.U.jsonCopyFrom(t.switches,r),t.jsRefCounting=!1,t.useUF2||t.useELF||null!=t.noSourceInFlash||(t.noSourceInFlash=!0),void 0===t.utf8&&(t.utf8=!0),e.appTarget.appTheme||(e.appTarget.appTheme={}),e.appTarget.appTheme.embedUrl||(e.appTarget.appTheme.embedUrl=e.appTarget.appTheme.homeUrl);let n=e.appTarget.compileService;if(n&&n.yottaTarget&&!n.yottaBinary&&(n.yottaBinary="pxt-microbit-app-combined.hex"),e.appTarget=o(e.appTarget,/^@cdnUrl@/i,t=>e.BrowserUtils.patchCdn(t)),e.appTarget.bundledpkgs&&Object.keys(e.appTarget.bundledpkgs).forEach(t=>{const n=e.appTarget.bundledpkgs[t],i=JSON.parse(n[e.CONFIG_NAME]);i.icon&&(i.icon=e.BrowserUtils.patchCdn(i.icon)),n[e.CONFIG_NAME]=e.Package.stringifyConfig(i)}),"undefined"!=typeof window){const t={"lockededitor=1":{appTheme:{lockedEditor:!0}},"hidemenu=1":{appTheme:{hideMenuBar:!0}}};e.appTarget.queryVariants&&e.Util.jsonCopyFrom(t,e.appTarget.queryVariants);const n=window.location.href;Object.keys(t).forEach(i=>{if(new RegExp(i,"i").exec(n)){let n=t[i];n&&e.U.jsonMergeFrom(e.appTarget,n)}})}}function c(n=!1){e.perf.measureStart(Measurements.ReloadAppTargetVariant);const i=n?"":JSON.stringify(e.appTarget);if(e.appTarget=e.U.cloneTargetBundle(t),e.appTargetVariant){const t=e.appTarget.variants&&e.appTarget.variants[e.appTargetVariant];t?e.U.jsonMergeFrom(e.appTarget,t):e.U.userError(lf("Variant '{0}' not defined in pxtarget.json",e.appTargetVariant))}l(),!n&&e.onAppTargetChanged&&i!=JSON.stringify(e.appTarget)&&e.onAppTargetChanged(),e.perf.measureEnd(Measurements.ReloadAppTargetVariant)}function u(){return{relprefix:"/--",workerjs:"/worker.js",monacoworkerjs:"/monacoworker.js",gifworkerjs:"/gifjs/gif.worker.js",serviceworkerjs:"/serviceworker.js",typeScriptWorkerJs:"/tsworker.js",pxtVersion:"local",pxtRelId:"localRelId",pxtCdnUrl:"/cdn/",commitCdnUrl:"/cdn/",blobCdnUrl:"/blb/",cdnUrl:"/cdn/",targetUrl:"",targetVersion:"local",targetRelId:"",targetId:e.appTarget?e.appTarget.id:"",simUrl:"/sim/simulator.html",simserviceworkerUrl:"/simulatorserviceworker.js",simworkerconfigUrl:"/sim/workerConfig.js",partsUrl:"/sim/siminstructions.html"}}function d(){return s||(s=e.Cloud.downloadTargetConfigAsync().then(e=>e||{},e=>({}))),s}function h(t=null){return t||(t=e.appTarget.compile),t.nativeType==ts.pxtc.NATIVE_TYPE_VM?t.useESP?t.useUF2?ts.pxtc.BINARY_UF2:ts.pxtc.BINARY_ESP:ts.pxtc.BINARY_PXT64:t.useUF2&&!t.switches.rawELF?ts.pxtc.BINARY_UF2:t.useELF?ts.pxtc.BINARY_ELF:ts.pxtc.BINARY_HEX}e.setAppTarget=function(n){e.appTarget=n||{},l(),t=e.U.cloneTargetBundle(e.appTarget)},e.setBundledApiInfo=function(e){for(const t of Object.keys(e)){const n=e[t].apis.byQName;for(const e of Object.keys(n)){const t=n[e],i=e.lastIndexOf("."),s=t.pyQName,r=n[e]={kind:Math.abs(t.kind||7),qName:e,namespace:e.slice(0,i<0?0:i),name:e.slice(i+1),pyQName:s,pyName:s?s.slice(s.lastIndexOf(".")+1):void 0,fileName:"",attributes:t.attributes||{},retType:t.retType||"void",parameters:t.parameters?t.parameters.map(e=>({name:e.name,description:e.description||"",type:e.type||"number",initializer:e.initializer,default:e.default,options:e.options||{},isEnum:!!e.isEnum,handlerParameters:e.handlerParameters})):null,extendsTypes:t.extendsTypes,snippet:t.kind&&t.kind<0?null:void 0,isInstance:!!t.isInstance,isReadOnly:!!t.isReadOnly},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.replaceStringsInJsonBlob=o,e.reloadAppTargetVariant=c,e.setAppTargetVariant=function(t,n={}){e.debug(`app variant: ${t}`),(n.force||e.appTargetVariant!==t&&(e.appTargetVariant||t))&&(e.appTargetVariant=t,c(n.temporary))},e.setHwVariant=function(t,n){t=t.replace(/.*---/,""),/^[\w\-]+$/.test(t)?(e.hwVariant=t,e.hwName=n||t):(e.hwVariant=null,e.hwName=null),e.debug(`hwVariant: ${e.hwVariant} (${e.hwName})`)},e.hasHwVariants=function(){return!!e.appTarget.variants&&Object.keys(e.appTarget.bundledpkgs).some(e=>/^hw---/.test(e))},e.getHwVariants=function(){return e.appTarget.variants?Object.keys(e.appTarget.bundledpkgs).filter(e=>/^hw---/.test(e)).map(t=>JSON.parse(e.appTarget.bundledpkgs[t][e.CONFIG_NAME])).filter(t=>!!e.appTarget.appTheme.experimentalHw||!t.experimentalHw):[]},e.getActiveHwVariant=function(){return e.hwVariant},e.options={},e.reportException=function(t,n){if(e.error(t),n)try{e.error(n)}catch(t){}},e.reportError=function(t,n,i){if(e.error(`${t}: ${n}`),i)try{e.log(JSON.stringify(i,null,2))}catch(e){}},e.localWebConfig=u,e.getOnlineCdnUrl=function(){if(!e.webConfig)return null;let t=/^(https:\/\/[^\/]+)/.exec(e.webConfig.commitCdnUrl);return t?t[1]:null},e.setupWebConfig=function(t){t?e.webConfig=t:e.webConfig||(e.webConfig=u())},e.getEmbeddedScript=function(t){return e.U.lookup(e.appTarget.bundledpkgs||{},t)},e.targetConfigAsync=d,e.packagesConfigAsync=function(){return d().then(e=>e?e.packages:void 0)},e.CONFIG_NAME="pxt.json",e.SIMSTATE_JSON=".simstate.json",e.SERIAL_EDITOR_FILE="serial.txt",e.README_FILE="README.md",e.GITIGNORE_FILE=".gitignore",e.ASSETS_FILE="assets.json",e.CLOUD_ID="pxt/",e.BLOCKS_PROJECT_NAME="blocksprj",e.JAVASCRIPT_PROJECT_NAME="tsprj",e.PYTHON_PROJECT_NAME="pyprj",e.MAIN_BLOCKS="main.blocks",e.MAIN_TS="main.ts",e.MAIN_PY="main.py",e.DEFAULT_GROUP_NAME="other",e.TILEMAP_CODE="tilemap.g.ts",e.TILEMAP_JRES="tilemap.g.jres",e.IMAGES_CODE="images.g.ts",e.IMAGES_JRES="images.g.jres",e.TUTORIAL_CODE_START="_onCodeStart.ts",e.TUTORIAL_CODE_STOP="_onCodeStop.ts",e.TUTORIAL_INFO_FILE="tutorial-info-cache.json",e.TUTORIAL_CUSTOM_TS="tutorial.custom.ts",e.BREAKPOINT_TABLET=991,e.PALETTES_FILE="_palettes.json",e.HISTORY_FILE="_history",e.MAX_DESCRIPTION_LENGTH=5e3,e.outputName=h,e.isOutputText=function(e=null){return h(e)==ts.pxtc.BINARY_HEX}}(pxt||(pxt={})),function(e){!function(t){const n="this";let i;function s(){if(i={device_while:{name:e.Util.lf("a loop that repeats while the condition is true"),tooltip:e.Util.lf("Run the same sequence of actions while the condition is met."),url:"/blocks/loops/while",category:"loops",block:{message0:e.Util.blf("while %1"),appendField:e.Util.blf("{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.blf("for %1 from 0 to %2"),variable:e.Util.blf("{id:var}index"),appendField:e.Util.blf("{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.blf("for %1 from 0 to %2"),variable:e.Util.blf("{id:var}index"),appendField:e.Util.blf("{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.blf("for element %1 of %2"),variable:e.Util.blf("{id:var}value"),appendField:e.Util.blf("{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.blf("for element %1 of %2"),variable:e.Util.blf("{id:var}value"),appendField:e.Util.blf("{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"]},block:{message0:e.Util.blf("%1 of %2 and %3"),optionMin:e.Util.blf("{id:op}min"),optionMax:e.Util.blf("{id:op}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.blf("absolute of %1")}},math_number:{name:e.Util.lf("{id:block}number"),url:"/types/number",category:"math",tooltip:e.appTarget&&e.appTarget.compile?e.Util.lf("a decimal number"):e.Util.lf("an integer number")},math_integer:{name:e.Util.lf("{id:block}number"),url:"/types/number",category:"math",tooltip:e.Util.lf("an integer number")},math_whole_number:{name:e.Util.lf("{id:block}number"),url:"/types/number",category:"math",tooltip:e.Util.lf("a whole number")},math_number_minmax:{name:e.Util.lf("{id:block}number"),url:"/blocks/math",category:"math"},math_arithmetic:{name:e.Util.lf("arithmetic operation"),url:"/blocks/math",tooltip:{ADD:e.Util.lf("Return the sum of the two numbers."),MINUS:e.Util.lf("Return the difference of the two numbers."),MULTIPLY:e.Util.lf("Return the product of the two numbers."),DIVIDE:e.Util.lf("Return the quotient of the two numbers."),POWER:e.Util.lf("Return the first number raised to the power of the second number.")},operators:{OP:["ADD","MINUS","MULTIPLY","DIVIDE","POWER"]},category:"math",block:{MATH_ADDITION_SYMBOL:e.Util.blf("{id:op}+"),MATH_SUBTRACTION_SYMBOL:e.Util.blf("{id:op}-"),MATH_MULTIPLICATION_SYMBOL:e.Util.blf("{id:op}×"),MATH_DIVISION_SYMBOL:e.Util.blf("{id:op}/"),MATH_POWER_SYMBOL:e.Util.blf("{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.blf("remainder of %1 / %2")}},math_js_op:{name:e.Util.lf("math function"),tooltip:{sqrt:e.Util.lf("Returns the square root of the argument"),sin:e.Util.lf("Returns the sine of the argument"),cos:e.Util.lf("Returns the cosine of the argument"),acos:e.Util.lf("Returns the arccosine of the argument"),asine:e.Util.lf("Returns the arcsine of the argument"),tan:e.Util.lf("Returns the tangent of the argument"),atan2:e.Util.lf("Returns the arctangent of the quotient of the two arguments"),idiv:e.Util.lf("Returns the integer portion of the division operation on the two arguments"),imul:e.Util.lf("Returns the integer portion of the multiplication operation on the two arguments")},url:"/blocks/math",operators:{OP:["sqrt","sin","cos","tan","atan2","idiv","imul"]},category:"math",block:{sqrt:e.Util.blf("{id:op}square root"),sin:e.Util.blf("{id:op}sin"),cos:e.Util.blf("{id:op}cos"),asin:e.Util.blf("{id:op}asin"),acos:e.Util.blf("{id:op}acos"),tan:e.Util.blf("{id:op}tan"),atan2:e.Util.blf("{id:op}atan2"),idiv:e.Util.blf("{id:op}integer /"),imul:e.Util.blf("{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.blf("{id:op}round"),ceil:e.Util.blf("{id:op}ceiling"),floor:e.Util.blf("{id:op}floor"),trunc:e.Util.blf("{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.blf("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.blf("repeat %1 times"),CONTROLS_REPEAT_INPUT_DO:e.Util.blf("{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.blf("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.blf("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.blf("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.blf("{id:logic}if"),CONTROLS_IF_MSG_THEN:e.Util.blf("{id:logic}then"),CONTROLS_IF_MSG_ELSE:e.Util.blf("{id:logic}else"),CONTROLS_IF_MSG_ELSEIF:e.Util.blf("{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.blf("empty array"),LISTS_CREATE_WITH_INPUT_WITH:e.Util.blf("array of"),LISTS_CREATE_WITH_CONTAINER_TITLE_ADD:e.Util.blf("array"),LISTS_CREATE_WITH_ITEM_TITLE:e.Util.blf("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.blf("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.blf("%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.blf("%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.blf("{id:op}and"),LOGIC_OPERATION_OR:e.Util.blf("{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.blf("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.blf("{id:boolean}true"),LOGIC_BOOLEAN_FALSE:e.Util.blf("{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.blf("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.blf("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.blf("function"),PROCEDURE_ALREADY_EXISTS:e.Util.blf("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.blf("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.blf("return %1"),message_no_value:e.Util.blf("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.blf("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.blf("call"),FUNCTIONS_GO_TO_DEFINITION_OPTION:e.Util.blf("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.blf("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.blf("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.blf("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.blf("continue")}},e.Util.isTranslationMode())for(const t of Object.keys(i)){const n=i[t];if(n.block){n.translationIds=Object.values(n.block).map(t=>e.U.rlf(t));for(const t of Object.keys(n.block))n.block[t]=e.U.fmt_va(n.block[t].replace(/^\{(id|loc):[^\}]+\}/g,""),[])}}if(e.blocks.showBlockIdInTooltip)for(const e of Object.keys(i)){const t=i[e].tooltip;if("object"==typeof t&&null!==t)for(const n in t)t.hasOwnProperty(n)&&(i[e].tooltip[n]=`${t[n]} (id: ${e})`);else i[e].tooltip=`${i[e].tooltip} (id: ${e})`}}t.showBlockIdInTooltip=!1,t.requirePxtBlockly=()=>{},t.requireBlockly=()=>{},t.registerFieldEditor=()=>{},t.MATH_FUNCTIONS={unary:["sqrt","sin","cos","tan","asin","acos"],binary:["atan2"],infix:["idiv","imul"]},t.ROUNDING_FUNCTIONS=["round","ceil","floor","trunc"],t.builtinFunctionInfo={"Math.abs":{blockId:"math_op3",params:["x"]},"Math.min":{blockId:"math_op2",params:["x","y"]},"Math.max":{blockId:"math_op2",params:["x","y"]}},t.normalizeBlock=function(t,n=e.log){if(!t)return t;let i=t.replace(/(?:^|[^\\])([%$])\s+/g,"$1");return i!=t&&(n(`block has extra spaces: ${t}`),t=i),i=(t=i).replace(/([%$]\w+)\s*=\s*(\w+)/,"$1=$2"),i!=t&&(n(`block has space between %name and = : ${t}`),t=i),i=i.replace(/\s*\|\s*/g,"|"),i},t.compileInfo=function(e){var i;const s={parameters:[],actualNameToParam:{},definitionNameToParam:{},handlerArgs:[]};let r=!(1!=e.kind&&2!=e.kind||e.attributes.defaultInstance||e.isStatic);"boolean"!=typeof e.isInstance||(null===(i=e.attributes)||void 0===i?void 0:i.defaultInstance)||(r=e.isInstance);const a=!!e.attributes._def,o=a?e.attributes._def.parameters.slice(0):void 0,l=a?o.length:e.parameters?e.parameters.length:0,c=t.builtinFunctionInfo[e.qName];a&&e.attributes._expandedDef&&o.push(...e.attributes._expandedDef.parameters);const u={},d=o?o.filter(e=>!e.ref||(u[e.name]=e,!1)):[];if(r&&a&&o.length){const t=u[n]||o[0],i=t.name,r=!t.shadowBlockId||"variables_get"===t.shadowBlockId;let a=e.attributes.paramDefl[i]||e.attributes.paramDefl.this;r&&(a=t.varName||a),s.thisParameter={actualName:n,definitionName:i,shadowBlockId:t.shadowBlockId,type:e.namespace,defaultValue:a,definitionIndex:o.indexOf(t),fieldEditor:h(i,n),fieldOptions:p(i,n),shadowOptions:f(i,n)}}if(e.parameters){let t=r&&!u[n]?1:0;e.parameters.forEach((n,i)=>{let r;if(u[n.name]?r=u[n.name]:t<d.length&&(r=d[t],++t),r||!a){let e;n.options&&n.options.min&&n.options.max&&(e={min:n.options.min.value,max:n.options.max.value});const a=r?r.name:c?c.params[t++]:n.name,u=r&&("variables_get"===r.shadowBlockId||"lists_create_with"==r.shadowBlockId);s.parameters.push({actualName:n.name,type:n.type,defaultValue:u&&r.varName||n.default,definitionName:a,definitionIndex:r?o.indexOf(r):i,shadowBlockId:r&&r.shadowBlockId,isOptional:!!o&&o.indexOf(r)>=l,fieldEditor:h(a,n.name),fieldOptions:p(a,n.name),shadowOptions:f(a,n.name),range:e})}n.handlerParameters&&n.handlerParameters.forEach(t=>{s.handlerArgs.push({name:t.name,type:t.type,inBlockDef:!!o&&o.some(e=>e.ref&&e.name===t.name),localizationKey:`${e.qName}|handlerParam|${t.name}`})})})}return s.parameters.forEach(e=>{s.actualNameToParam[e.actualName]=e,s.definitionNameToParam[e.definitionName]=e}),s;function h(t,n){return e.attributes.paramFieldEditor&&(e.attributes.paramFieldEditor[t]||e.attributes.paramFieldEditor[n])}function p(t,n){return e.attributes.paramFieldEditorOptions&&(e.attributes.paramFieldEditorOptions[t]||e.attributes.paramFieldEditorOptions[n])}function f(t,n){return e.attributes.paramShadowOptions&&(e.attributes.paramShadowOptions[t]||e.attributes.paramShadowOptions[n])}},t.hasHandler=function(e){return e.parameters&&e.parameters.some(e=>{var t,n;return"() => void"==e.type||"Action"==e.type||!!(null===(t=e.properties)||void 0===t?void 0:t.length)||!!(null===(n=e.handlerParameters)||void 0===n?void 0:n.length)})},t.getHelpUrl=function(t){var n,i,s;let r=t.attributes.help;if((null===(n=t.attributes.blockId)||void 0===n?void 0:n.endsWith("_blockCombine_get"))?r=t.attributes.blockCombineGetHelp||r:(null===(i=t.attributes.blockId)||void 0===i?void 0:i.endsWith("_blockCombine_set"))?r=t.attributes.blockCombineSetHelp||r:(null===(s=t.attributes.blockId)||void 0===s?void 0:s.endsWith("_blockCombine_change"))&&(r=t.attributes.blockCombineChangeHelp||r),r){const e=r.replace(/^\//,"");if(/^github:/.test(e))return e;if("none"!==e)return"/reference/"+e}else if(t.pkg&&!e.appTarget.bundledpkgs[t.pkg]){let e=t.qName.toLowerCase().split(".");return e[0]==t.pkg&&e.shift(),`/pkg/${t.pkg}#${encodeURIComponent(e.join("-"))}`}},t.reporterTypeForArgType=function(e){let t="argument_reporter_custom";return"boolean"!==e&&"number"!==e&&"string"!==e||(t=`argument_reporter_${e}`),/^(?:Array<(?:.+)>)|(?:(?:.+)\[\])$/.test(e)&&(t="argument_reporter_array"),t},t.defaultIconForArgType=function(e=""){switch(e){case"number":return"calculator";case"string":return"text width";case"boolean":return"random";case"Array":return"list";default:return"align justify"}},t.parseFields=function(e){return e.split("|").map((e,t)=>{let n=/([^%]*)\s*%([a-zA-Z0-9_]+)/.exec(e);if(!n)return{n:e,ni:t};let i=n[1];return i&&(i=i.trim()),{n:e,ni:t,pre:i,p:n[2]}})},t.blockDefinitions=function(){return i||s(),i},t.getBlockDefinition=function(e){return i||s(),i[e]}}(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 m(){return n()&&/Epiphany/i.test(navigator.userAgent)}function g(){return"undefined"!=typeof window&&("ontouchstart"in window||navigator&&navigator.maxTouchPoints>0)}function b(){return"undefined"!=typeof window&&!!window.pxtElectron}function y(){return"undefined"!=typeof window&&!!window.ipcRenderer}function v(){return b()||y()}function w(t){var n;try{return"undefined"!=typeof window&&/^https?:\/\/(?:localhost|127\.0\.0\.1|192\.168\.\d{1,3}\.\d{1,3}|[a-zA-Z0-9.-]+\.local):\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 A(){return"undefined"!=typeof window&&!!window.PointerEvent}function k(){return i()?"windows":r()?"mac":a()&&o()?"rpi":a()?"linux":"unknown"}function T(){return l()?"edge":m()?"epiphany":f()?"midori":p()?"opera":c()?"ie":u()?"chrome":d()?"safari":h()?"firefox":"unknown"}function x(){if(!n())return null;let e=[];return p()&&(e=/(Opera|OPR)\/([0-9\.]+)/i.exec(navigator.userAgent)),m()?e=/Epiphany\/([0-9\.]+)/i.exec(navigator.userAgent):f()?e=/Midori\/([0-9\.]+)/i.exec(navigator.userAgent):d()?(e=/Version\/([0-9\.]+)/i.exec(navigator.userAgent),e||(e=/(Macintosh|iPod( touch)?|iPhone|iPad); (CPU|Intel).*?OS (X )?(\d+)/i.exec(navigator.userAgent))):e=u()?/(Chrome|Chromium)\/([0-9\.]+)/i.exec(navigator.userAgent):l()?/Edge\/([0-9\.]+)/i.exec(navigator.userAgent):c()?/(MSIE |rv:)([0-9\.]+)/i.exec(navigator.userAgent):/(Firefox|Seamonkey)\/([0-9\.]+)/i.exec(navigator.userAgent),e&&0!=e.length?e[e.length-1]:null}t.isDocumentVisible=function(){return"undefined"!=typeof window&&"visible"===document.visibilityState},t.isIFrame=function(){try{return window&&window.self!==window.top}catch(e){return!0}},t.hasNavigator=n,t.hasWindow=function(){return"undefined"!=typeof window},t.isWindows=i,t.isWindows10=function(){return n()&&/(Win32|Win64|WOW64)/i.test(navigator.platform)&&/Windows NT 10/i.test(navigator.userAgent)},t.isMobile=s,t.isIOS=function(){return n()&&(/iPad|iPhone|iPod/.test(navigator.userAgent)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1)},t.isAndroid=function(){return n()&&/android/i.test(navigator.userAgent)},t.isMac=r,t.isLinux=a,t.isARM=o,t.isEdge=l,t.isChromiumEdge=function(){return n()&&/Edg\//i.test(navigator.userAgent)},t.isIE=c,t.isChrome=u,t.isSafari=d,t.isFirefox=h,t.isOpera=p,t.isMidori=f,t.isEpiphany=m,t.isTouchEnabled=g,t.isPxtElectron=b,t.isIpcRenderer=y,t.isElectron=v,t.isWinRT=()=>"undefined"!=typeof Windows,t.isLocalHost=w,t.isLocalHostDev=function(){return w()&&!v()},t.isSkillmapEditor=function(){try{return/skill(?:s?)map=1/i.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.isInGame=function(){return!!/inGame=1/i.exec(window.location.href)},t.hasFileAccess=function(){const t=e.appTarget.appTheme.disableFileAccessinMaciOs&&(e.BrowserUtils.isMac()||e.BrowserUtils.isIOS()),n=e.appTarget.appTheme.disableFileAccessinAndroid&&e.BrowserUtils.isAndroid();return!t&&!n},t.noSharedLocalStorage=function(){try{return/nosharedlocalstorage/i.test(window.location.href)}catch(e){return!1}},t.useOldTutorialLayout=function(){var t,n;if(null===(n=null===(t=e.appTarget)||void 0===t?void 0:t.appTheme)||void 0===n?void 0:n.legacyTutorial)return!0;try{return/tutorialview=old/.test(window.location.href)}catch(e){return!1}},t.hasPointerEvents=A,t.os=k,t.browser=T,t.browserVersion=x;let E=!1;function C(){return s()&&d()&&!/downloadWindowOpen=0/i.test(window.location.href)}function I(t,n,i){const r=C(),a=x(),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 S(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 N(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=S(t,n),I(d,n,a)}catch(t){o&&o(t),e.debug("saving failed")}return d}function U(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==T()))return!1;const s=x(),r=parseInt(s||"0"),c=u()&&r>=38,g=h()&&r>=31,b=l(),y=d()&&r>=9,v=p()&&u()&&r>=21;let w=c||g||b||y||v;const A=f()||a()&&o()&&m();return w=w&&!A,w=w||/anybrowser=(true|1)/.test(window.location.href),E||(e.log(`Browser: ${T()} ${s} on ${k()}`),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 N(ts.pxtc.encodeBase64(e),t,n)},t.browserDownloadText=function(t,n,i){return N(ts.pxtc.encodeBase64(e.Util.toUTF8(t)),n,i)},t.isBrowserDownloadInSameWindow=C,t.isBrowserDownloadWithinUserContext=function(){const e=x(),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 N(ts.pxtc.encodeBase64(e.Util.uint8ArrayToString(t)),n,i)},t.toDownloadDataUri=S,t.browserDownloadBase64=N,t.loadImageAsync=U,t.loadCanvasAsync=function(e){return U(e).then(e=>{const t=document.createElement("canvas");t.width=e.width,t.height=e.height;return t.getContext("2d").drawImage(e,0,0),t})},t.scaleImageData=function(e,t){const n=document.createElement("canvas"),i=document.createElement("canvas");n.width=e.width,n.height=e.height,i.width=e.width*t,i.height=e.height*t;const s=n.getContext("2d"),r=i.getContext("2d");return s.putImageData(e,0,0),r.imageSmoothingEnabled=!1,r.scale(t,t),r.drawImage(n,0,0),r.getImageData(0,0,e.width*t,e.height*t)},t.imageDataToPNG=function(e,t=1){if(!e)return;const n=document.createElement("canvas"),i=document.createElement("canvas");n.width=e.width,n.height=e.height,i.width=e.width*t,i.height=e.height*t;const s=n.getContext("2d"),r=i.getContext("2d");return s.putImageData(e,0,0),r.imageSmoothingEnabled=!1,r.scale(t,t),r.drawImage(n,0,0),i.toDataURL("image/png")};const O=1e7;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=O,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)};try{const e=new URL(t);"http:"!==e.protocol&&"https:"!==e.protocol||e.host===window.location.host||c.setAttribute("crossOrigin","anonymous")}catch(e){}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 P,L,D,$={};function M(e,t){if(!e)return t;if(!t)return e;return(e.indexOf("/")==e.length-1?e.substring(0,e.length-1):e)+"/"+(0==t.indexOf("/")?t.substring(1):t)}function R(){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=$[n];return i||(i=$[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 $[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(!P){e.debug("blockly: delay load");let t=e.BrowserUtils.loadStyleAsync("blockly.css",ts.pxtc.Util.isUserLanguageRtl());t=t.then(()=>{e.debug("blockly: loaded")}),P=t}return P},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=M,t.joinURLs=function(...e){let t;if(e)for(let n=0;n<e.length;n++)t=M(t,e[n]);return t},t.storageEstimateAsync=R,t.scheduleStorageCleanup=n()&&navigator.storage&&navigator.storage.estimate?ts.pxtc.Util.throttle(function(){R().then(t=>(e.debug(`storage estimate: ${t.usage/t.quota*100|0}%, ${t.usage/1e6|0}/${t.quota/1e6|0}Mb`),t.quota&&t.usage&&t.quota>1e6&&t.usage/t.quota>.9?(e.log("quota usage exceeded, clearing translations"),e.tickEvent("storage.cleanup"),z()):Promise.resolve())).catch(t=>{e.reportException(t)})},1e4,!1):()=>{},t.stressTranslationsAsync=function t(){let n="...";for(let e=0;e<16;++e)n+=n+Math.random();return e.log(`adding entry ${2*n.length} bytes`),e.U.delay(1).then(()=>G()).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){return`${e}|${t}|master`}get(e,t){return this.translations[this.key(e,t)]}getAsync(e,t){return Promise.resolve(this.get(e,t))}set(e,t,n,i,s,r){this.translations[this.key(e,t)]={etag:n,time:i,strings:s,md:r}}setAsync(t,n,i,s,r){return this.set(t,n,i,e.Util.now(),s),Promise.resolve()}clearAsync(){return this.translations={},Promise.resolve()}}class F{constructor(e,t,n,i,s=!1){this.name=e,this.version=t,this.upgradeHandler=n,this.quotaExceededHandler=i,this.skipErrorLog=s}throwIfNotOpened(){if(!this._db)throw new Error("Database not opened; call IDBWrapper.openAsync() first")}errorHandler(t,n,i){this.skipErrorLog?i(t):(e.error(new Error(`${this.name} IDBWrapper error for ${n}: ${t.message}`)),i(t),"QuotaExceededError"==t.name&&(e.log("storage quota exceeded..."),e.tickEvent("storage.quotaexceedederror"),this.quotaExceededHandler&&this.quotaExceededHandler()))}getObjectStore(e,t="readonly"){this.throwIfNotOpened();return this._db.transaction([e],t).objectStore(e)}static deleteDatabaseAsync(e){return new Promise((t,n)=>{const i=(window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB).deleteDatabase(e);i.onsuccess=()=>t(),i.onerror=()=>n(i.error)})}openAsync(){return new Promise((e,t)=>{const n=(window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB).open(this.name,this.version);n.onsuccess=()=>{this._db=n.result,e()},n.onerror=()=>this.errorHandler(n.error,"open",t),n.onupgradeneeded=e=>this.upgradeHandler(e,n)})}getAsync(e,t){return new Promise((n,i)=>{const s=this.getObjectStore(e).get(t);s.onsuccess=()=>n(s.result),s.onerror=()=>this.errorHandler(s.error,"get",i)})}getAllAsync(e){return new Promise((t,n)=>{const i=this.getObjectStore(e).openCursor(),s=[];i.onsuccess=()=>{i.result?(s.push(i.result.value),i.result.continue()):t(s)},i.onerror=()=>this.errorHandler(i.error,"getAll",n)})}setAsync(e,t){return new Promise((n,i)=>{const s=this.getObjectStore(e,"readwrite");let r;r=void 0!==t.id&&null!==t.id?s.put(t):s.add(t),r.onsuccess=()=>n(),r.onerror=()=>this.errorHandler(r.error,"set",i)})}deleteAsync(e,t){return new Promise((n,i)=>{const s=this.getObjectStore(e,"readwrite").delete(t);s.onsuccess=()=>n(),s.onerror=()=>this.errorHandler(s.error,"delete",i)})}deleteAllAsync(e){return new Promise((t,n)=>{const i=this.getObjectStore(e,"readwrite").clear();i.onsuccess=()=>t(),i.onerror=()=>this.errorHandler(i.error,"deleteAll",n)})}getObjectStoreWrapper(e){return new B(this,e)}}t.IDBWrapper=F;class B{constructor(e,t){this.db=e,this.storeName=t}getAsync(e){return this.db.getAsync(this.storeName,e)}getAllAsync(){return this.db.getAllAsync(this.storeName)}setAsync(e){return this.db.setAsync(this.storeName,e)}async deleteAsync(e){await this.db.deleteAsync(this.storeName,e)}async deleteAllAsync(){await this.db.deleteAllAsync(this.storeName)}}t.IDBObjectStoreWrapper=B;class H{constructor(e){this.db=e,this.mem=new j}static dbName(){return`__pxt_translations_${e.appTarget.id||""}`}static createAsync(){function t(){const e=new F(H.dbName(),2,(e,t)=>{t.result.createObjectStore(H.TABLE,{keyPath:H.KEYPATH})},()=>{z().catch(e=>{})});return e.openAsync().then(()=>new H(e))}return t().catch(n=>(e.log("db: failed to open database, try delete entire store..."),F.deleteDatabaseAsync(H.dbName()).then(()=>t())))}getAsync(e,t){e=(e||"en-US").toLowerCase();const n=this.mem.key(e,t),i=this.mem.get(e,t);return i?Promise.resolve(i):this.db.getAsync(H.TABLE,n).then(n=>n?(this.mem.set(e,t,n.etag,n.time,n.strings),Promise.resolve(n)):Promise.resolve(void 0)).catch(e=>Promise.resolve(void 0))}setAsync(n,i,s,r,a){n=(n||"en-US").toLowerCase();const o=this.mem.key(n,i);let l=e.Util.now();this.mem.set(n,i,s,l,r,a),r&&Object.keys(r).filter(e=>!r[e]).forEach(e=>delete r[e]);const c={id:o,etag:s,time:l,strings:r,md:a};return this.db.setAsync(H.TABLE,c).finally(()=>t.scheduleStorageCleanup()).catch(t=>(e.log(`db: set failed (${t.message}), recycling...`),this.clearAsync()))}clearAsync(){return this.db.deleteAllAsync(H.TABLE).then(()=>e.debug("db: all clean")).catch(t=>{e.error("db: failed to delete all")})}}function G(){return e.Util.isNodeJS?Promise.resolve(new j):(L||(L=H.createAsync().catch(()=>new j)),L)}function z(){function t(){const t=H.dbName();return F.deleteDatabaseAsync(t).then(()=>{L=void 0}).catch(n=>{e.log(`db: failed to delete ${t}`),L=void 0})}return L?L.then(e=>e.clearAsync()).catch(e=>t().then()):t()}function q(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"}`}H.TABLE="files",H.KEYPATH="id",t.translationDbAsync=G,t.clearTranslationDbAsync=z,t.getTutorialCodeHash=q;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=>(e.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=q(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,r,a){e.perf.measureStart(Measurements.TutorialInfoDbSetAsync);V(t,a);const o=q(i);return this.setWithHashAsync(t,n,o,s,r)}setWithHashAsync(t,n,i,s,r,a){e.perf.measureStart(Measurements.TutorialInfoDbSetAsync);const o=V(t,a),l={};Object.keys(n).forEach(e=>{Object.keys(n[e]).forEach(t=>{l[t]=n[e][t]})});const c={id:o,time:e.Util.now(),hash:i,snippets:n,blocks:l,highlightBlocks:s,validateBlocks:r};return this.db.setAsync(J.TABLE,c).then(()=>{e.perf.measureEnd(Measurements.TutorialInfoDbSetAsync)})}clearAsync(){return this.db.deleteAllAsync(J.TABLE).then(()=>e.debug("db: all clean")).catch(t=>{e.error("db: failed to delete all")})}}function W(e){return e.split(/\s+/).filter(e=>!!e)}function K(){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 D||(D=J.createAsync()),D},t.clearTutorialInfoDbAsync=function(){function t(){const t=J.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()},t.pointerEvents=A()?{up:"pointerup",down:["pointerdown"],move:"pointermove",enter:"pointerenter",leave:"pointerleave"}:g()?{up:"mouseup",down:["mousedown","touchstart"],move:"touchmove",enter:"touchenter",leave:"touchend"}:{up:"mouseup",down:["mousedown"],move:"mousemove",enter:"mouseenter",leave:"mouseleave"},t.getPageX=function(e){return"pageX"in e?e.pageX:e.changedTouches[0].pageX},t.getPageY=function(e){return"pageY"in e?e.pageY:e.changedTouches[0].pageY},t.getClientX=function(e){return"clientX"in e?e.clientX:e.changedTouches[0].clientX},t.getClientY=function(e){return"clientY"in e?e.clientY:e.changedTouches[0].clientY},t.popupWindow=function(t,n,i,s){try{const r=window.screenLeft?window.screenLeft:window.screenX,a=window.screenTop?window.screenTop:window.screenY,o=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth,l=window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight,c="width="+i+", height="+s+", top="+(l/2-s/2+a)+", left="+(o/2-i/2+r),u=window.open(t,n,e.BrowserUtils.isIpcRenderer()?void 0:c);return u.focus&&u.focus(),u}catch(t){return e.tickEvent("pxt.popupError",{msg:t.message}),null}},t.containsClass=function(e,t){return W(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){W(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){W(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=K,t.setCookieLang=function(t,n=!1){if(e.Util.allLanguages[t]&&t!==K()){e.tickEvent("menu.lang.setcookielang",{lang:t,docs:`${n}`});const i=new Date;i.setTime(i.getTime()+24*e.Util.langCookieExpirationDays*60*60*1e3),document.cookie=`${e.Util.pxtLangCookieId}=${t}; expires=${i.toUTCString()}; path=/`}},t.cacheBustingUrl=function(e){return e?/[?&]rnd=/.test(e)?e:`${e}${e.indexOf("?")>0?"&":"?"}rnd=${Math.random()}`:e},t.appendUrlQueryParams=function(e,t){const n=[];for(const[e,i]of t.entries())n.push(`${encodeURIComponent(e)}=${encodeURIComponent(i)}`);return n.length&&(-1!==e.indexOf("?")?e+="&"+n.join("&"):e+="?"+n.join("&")),e},t.legacyCopyText=function(t){t.focus(),t.setSelectionRange(0,9999);try{const t=document.execCommand("copy");return e.debug("copy: "+t),!!t}catch(e){return!1}},t.setApplicationTheme=function(e){const t=document.body,n=t.classList;for(let e=0;e<n.length;e++)/^theme-/.test(n[e])&&t.classList.remove(n[e]);e&&t.classList.add(`theme-${e}`)},t.isElement=function(e){return e.nodeType===Node.ELEMENT_NODE}}(e.BrowserUtils||(e.BrowserUtils={}))}(pxt||(pxt={})),function(e){!function(e){const t="https://staging.pxt.io";e.DEV_BACKEND=t,e.DEV_REGION="US",e.devBackendType=function(){return"https://makecode.com"===e.DEV_BACKEND?"prod":e.DEV_BACKEND===t?"staging":"http://localhost:8080"===e.DEV_BACKEND?"localhost":"prod"},e.cloudStatus={none:{value:"none"},synced:{value:"synced",icon:"cloud-saved-b",tooltip:lf("Project saved to cloud"),shortStatus:lf("saved"),longStatus:lf("Saved to cloud"),indicator:""},justSynced:{value:"justSynced",icon:"cloud-saved-b",tooltip:lf("Project saved to cloud"),shortStatus:lf("saved!"),longStatus:lf("Saved to cloud!"),indicator:""},offline:{value:"offline",icon:"cloud-error-b",tooltip:lf("Unable to connect to cloud"),shortStatus:lf("offline"),longStatus:lf("Offline"),indicator:lf("offline")},syncing:{value:"syncing",icon:"cloud-saving-b",tooltip:lf("Saving project to cloud..."),shortStatus:lf("saving..."),longStatus:lf("Saving to cloud..."),indicator:lf("syncing...")},conflict:{value:"conflict",icon:"cloud-error-b",tooltip:lf("Project was edited in two places and the changes conflict"),shortStatus:lf("conflict!"),longStatus:lf("Project has a conflict!"),indicator:"!"},localEdits:{value:"localEdits",icon:"cloud-saving-b",tooltip:lf("Project has local changes and will save to cloud soon."),shortStatus:"",longStatus:"",indicator:"*"}}}(e.cloud||(e.cloud={}))}(pxt||(pxt={})),function(e){!function(e){let t;!function(e){e[e.Failed=0]="Failed",e[e.Success=1]="Success",e[e.UserRejected=2]="UserRejected"}(t=e.WebUSBPairResult||(e.WebUSBPairResult={})),e.deployCoreAsync=void 0,e.deployFallbackAsync=void 0,e.hasDeployFn=()=>e.deployCoreAsync||e.deployFallbackAsync,e.deployAsync=(t,n)=>(e.deployCoreAsync||e.deployFallbackAsync)(t,n),e.patchCompileResultAsync=void 0,e.browserDownloadAsync=void 0,e.saveOnlyAsync=void 0,e.renderBrowserDownloadInstructions=void 0,e.renderUsbPairDialog=void 0,e.renderIncompatibleHardwareDialog=void 0,e.showUploadInstructionsAsync=void 0,e.saveProjectAsync=void 0,e.electronDeployAsync=void 0,e.electronFileDeployAsync=void 0,e.webUsbPairDialogAsync=void 0,e.onTutorialCompleted=void 0,e.perfMeasurementThresholdMs=void 0,e.onPerfMilestone=void 0,e.onPerfMeasurement=void 0,e.workspaceLoadedAsync=void 0,e.getDownloadMenuItems=void 0,e.notifyProjectCompiled=void 0,e.notifyProjectSaved=void 0,e.onDownloadButtonClick=void 0,e.getDefaultProjectName=void 0,e.onMarkdownActivityLoad=void 0}(e.commands||(e.commands={}))}(pxt||(pxt={})),function(e){function t(t){const n=e.toolbox.convertColor(t),i=parseInt(n.slice(1,3),16)/255,s=parseInt(n.slice(3,5),16)/255,r=parseInt(n.slice(5,7),16)/255;return.2126*(i<=.03928?i/12.92:Math.pow((i+.055)/1.055,2.4))+.7152*(s<=.03928?s/12.92:Math.pow((s+.055)/1.055,2.4))+.0722*(r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4))}function n(e,n){return(t(e)+.05)/(t(n)+.05)}function i(e){const t=(1-Math.abs(2*e.l-1))*e.s,n=e.h/60,i=t*(1-Math.abs(n%2-1));let r;void 0===e.h?r=[0,0,0]:n<=1?r=[t,i,0]:n<=2?r=[i,t,0]:n<=3?r=[0,t,i]:n<=4?r=[0,i,t]:n<=5?r=[i,0,t]:n<=6&&(r=[t,0,i]);let a=e.l-.5*t;return o=Math.round(255*(r[0]+a)),l=Math.round(255*(r[1]+a)),c=Math.round(255*(r[2]+a)),"#"+s(o)+s(l)+s(c);var o,l,c}function s(e){return("0"+e.toString(16)).slice(-2)}e.getWhiteContrastingBackground=function(t){if(n("#ffffff",t)>=4.5)return t;const s=function(t){const n=e.toolbox.convertColor(t),i=parseInt(n.slice(1,3),16)/255,s=parseInt(n.slice(3,5),16)/255,r=parseInt(n.slice(5,7),16)/255,a=Math.max(Math.max(i,s),r),o=Math.min(Math.min(i,s),r),l=a-o;let c;0===l?c=0:a===i?c=((s-r)/l%6+6)%6:a===s?c=(r-i)/l+2:a===r&&(c=(i-s)/l+4);let u=(o+a)/2,d=0===l?0:l/(1-Math.abs(2*u-1));return{h:60*c,s:d,l:u}}(t);let r=s.l-.05;for(;r>0;){const e=i({h:s.h,s:s.s,l:r});if(n("#ffffff",e)>=4.5)return e;r-=.05}return e.warn(`Couldn't find a contrasting background for color ${t}`),t},e.contrastRatio=n}(pxt||(pxt={})),function(e){e.TutorialInfoDbSetAsync="tutorial info db setAsync",e.ReloadAppTargetVariant="reloadAppTargetVariant",e.Sha256Buffer="sha256buffer",e.WebworkerRecvHandler="webworker recvHandler",e.NetworkRequest="network.request"}(Measurements||(Measurements={})),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 m=JSON.stringify(c),g=o[m];if(g){e.debug("Using cached extinfo");const t=n.flatClone(g);return t.disabledDeps=h,t}e.debug("Generating new extinfo");const b=pxtc.emptyExtInfo();b.disabledDeps=h;let y=e.appTarget.compileService;y||(y={gittag:"none",serviceId:"nocompile"}),y=n.clone(y);let v=t.getTargetOptions();v||(v={isNative:!1,hasHex:!1,switches:{}});const w=!!y.platformioIni,A="codal"==y.buildEngine||"dockercodal"==y.buildEngine,k="dockermake"==y.buildEngine||"dockercross"==y.buildEngine,T="dockerespidf"==y.buildEngine,x=!(w||A||k||T),E=v.nativeType==pxtc.NATIVE_TYPE_VM;w?d="/src/":A||k?d="/pxtapp/":T&&(d="/main/");let C="// Configuration defines\n",I="\nPXT_SHIMS_BEGIN\n",S="",N="",U='#include "pxt.h"\n',O="",_=e=>O+=` ${L}(${P}): ${e}\n`,P=0,L="",D=r("namespace"),$=r("declare namespace"),M=r("declare namespace"),R="",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,`${u} 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 q(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 V=0,J=!1,W="",K="",Y="",X=!1;function Q(){$.setNs(""),$.write(""),$.write(""),(Y||K)&&($.write(K),$.write(Y),Y="",K="")}function Z(e,t){let r;W="",K="",Y="",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":case"ImageLiteral_":return"T";case"bool":return"B";case"double":return"D";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),P=0,J=!1,V=0,M.setNs(""),$.setNs(""),e.split(/\r?\n/).forEach(e=>{++P;let d=q(e);!function(e){let t=q(e);if(J&&t.indexOf("}")>=0&&(J=!1,M.write("}")),!J)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),V=a(s),null==V&&_("cannot determine value of "+t)}else V++,s=V+"";M.write(` ${H(e)} = ${s},${r}`)}else M.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],J=!0,V=-1,M.write(""),M.write(""),(Y||K)&&(M.write(K),M.write(Y),Y="",K=""),M.write(`declare const enum ${H(p)} ${f}`),j[p]=!0,t||(D.setNs(W),D.write(`enum ${h[2]} : int;`))),function(e){return!(!J&&(/^\s*\/\*\*/.test(e)?(X=!0,K=e+"\n",/\*\//.test(e)&&(X=!1),0):X?(K+=e+"\n",/\*\//.test(e)&&(X=!1),0):!/^\s*\/\/%/.test(e)||(Y+=e+"\n",0)))}(e))return;/^typedef.*;\s*$/.test(e)&&(D.setNs(W),D.write(e));let m=/^\s*namespace\s+(\w+)/.exec(e);if(!m){if(m=/^PXT_ABI\((\w+)\)/.exec(e),m&&!E&&(I+=`PXT_FNPTR(::${m[1]}),\n`,N+=`extern "C" void ${m[1]}();\n`,b.functions.push({name:m[1],argsFmt:[],value:0})),m=/^\s*PXT_EXPORT\(([:\&\w]+)\)/.exec(e),m&&(b.vmPointers||(b.vmPointers=[]),b.vmPointers.push(m[1])),m=/^#define\s+PXT_COMM_BASE\s+([0-9a-fx]+)/.exec(e),m&&(b.commBase=parseInt(m[1])),m=/^\s*(\w+)([\*\&]*\s+[\*\&]*)(\w+)\s*\(([^\(\)]*)\)\s*(;\s*$|\{|$)/.exec(e),Y&&m){r=null;let e=pxtc.parseCommentString(Y);W||_("missing namespace declaration");let o=(m[1]+m[2]).replace(/\s+/g,""),d=m[3],h=m[4];Y=Y.trim().replace(/ \w+\.defl=\w+/g,"");let p=[u(o)],f=[],g=h.split(/,/).filter(e=>!!e).map(t=>{let i=function(e,t){t=t.trim();let i=/(.*)=\s*(-?\w+)$/.exec(t),s="",r="";if(i&&(s=i[2],r="?",t=i[1].trim()),i=/^(.*?)(\w+)$/.exec(t),!i)return _("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),Y+=` ${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(K)if($.setNs(H(W)),$.write(""),$.write(K),/ImageLiteral/.test(m[4])&&!/imageLiteral=/.test(Y)&&(Y+=" imageLiteral=1"),Y+=` shim=${y.name}`,$.write(Y),d=H(d),l()){let e=(g[0]||"").replace(/^.*:\s*/,"").trim();e.toLowerCase()!=l().toLowerCase()&&_(i("Invalid first argument; should be of type '{0}', but is '{1}'",l(),e)),g.shift(),0==g.length&&/\bproperty\b/.test(Y)?$.write(`${d}: ${c(o)};`):$.write(`${d}(${g.join(", ")}): ${c(o)};`)}else $.write(`function ${d}(${g.join(", ")}): ${c(o)};`);if(K="",Y="",t||(D.setNs(W),D.write(`${o} ${d}(${h});`)),b.functions.push(y),x)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,S+=`\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&&(S+=" auto prevSP = ctx->sp;\n"),S+=a,r&&(S+=" if (panicCode) { ctx->sp = prevSP; return; }\n");const o=`::${e.name}(${s.join(", ")})`;return"V"==e.argsFmt[0]?(S+=` ${o};\n`,S+=" ctx->r0 = NULL;\n"):"I"==e.argsFmt[0]?S+=` ctx->r0 = fromInt(${o});\n`:"B"==e.argsFmt[0]?S+=` ctx->r0 = fromBool(${o});\n`:S+=` ctx->r0 = (TValue)${o};\n`,r&&(S+=" ctx->sp = prevSP;\n"),i>1&&(S+=` ctx->sp += ${i-1};\n`),S+="}\n",n}(y,f),t=y.argsFmt.length-1;I+=`{ "${y.name}", (OpFun)(void*)${e}, ${t} },\n`}}else I+="PXT_FNPTR(::"+y.name+"),\n";return}if(m=/^\s*extern const (\w+) (\w+);/.exec(e),Y&&m){let e={name:W+"::"+m[2],argsFmt:[],value:null};return b.functions.push(e),E||(I+="PXT_FNPTR(&::"+e.name+"),\n"),void(Y="")}if(m=/^\s*(\w+)\s+(\w+)\s*;/.exec(e),Y&&m){let e=pxtc.parseCommentString(Y);e.indexedInstanceNS&&(r=e,$.setNs(e.indexedInstanceNS),o=0);let t=m[1],n=m[2];if(r)return Y=Y.trim(),Y+=` fixedInstance shim=${r.indexedInstanceShim}(${o++})`,$.write(""),$.write(K),$.write(Y),$.write(`const ${n}: ${c(t)};`),K="",void(Y="")}return Y&&e.trim()?(_("declaration not understood: "+e),Y="",void(K="")):void 0}if(W=m[1],l()){Q();let e=l();$.setNs(W,`declare interface ${e} {`)}else(Y||K)&&(Q(),$.setNs(H(W)),M.setNs(H(W)))})}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(A&&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(x&&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){O="",se(s),s==t?(e=!0,$.clear(),M.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&&(U+=`#include "${x?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)),L=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}}O&&(R+=i("Extension {0}:\n",s.id)+O)}e||($.clear(),M.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))}R&&n.userError(R),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}),!x&&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(k){let e={name:"pxt-app",private:!0,dependencies:b.npmDependencies};b.generatedFiles["/package.json"]=JSON.stringify(e,null,4)+"\n"}else if(T){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(A){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"]}`),b.codal=r}else if(w){const e=y.platformioIni.slice();e.push("lib_deps ="),n.iterMap(b.platformio.dependencies,(t,n)=>{let i=/[@#\/]/.test(n)?n:t+"@"+n;e.push(" "+i)}),b.generatedFiles["/platformio.ini"]=e.join("\n")+"\n"}else{b.yotta.config=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"]=U+D.finish()+N+S+I+"\nPXT_SHIMS_END\n",b.generatedFiles[d+"pxtconfig.h"]=C,e.debug(`pxtconfig.h: ${b.generatedFiles[d+"pxtconfig.h"]}`),x&&(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:x?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=$.finish(),b.enumsDTS=M.finish(),Object.keys(o).length>10&&(o={}),o[m]=b,b},t.unpackSourceFromHexFileAsync=function(t){if(t)return e.Util.fileReadAsBufferAsync(t).then(e=>h(new Uint8Array(e)))},t.unpackSourceFromHexAsync=h}(e.cpp||(e.cpp={}))}(pxt||(pxt={})),function(e){!function(t){const n={};let i,s={};function r(s){return n.hasOwnProperty(s.sha)||(n[s.sha]=function(n){let s="";return t.showLoading(e.U.lf("Compiling (this may take a minute)...")),e.tickEvent("cppcompile.start"),function(t){if(t.skipCloudBuild)return Promise.resolve({hex:["SKIP"]});if(e.webConfig&&e.webConfig.isStatic)return e.Util.requestAsync({url:`${e.webConfig.cdnUrl}hexcache/${t.sha}.hex`}).then(t=>{if(t.text){const e={enums:[],functions:[],hex:t.text.split(/\r?\n/)};return Promise.resolve(e)}return e.log("Hex info not found in bundled hex cache"),Promise.resolve()}).catch(t=>(e.log("Error fetching hex info from bundled hex cache"),Promise.resolve()));if(!e.Cloud.localToken||!window||!e.BrowserUtils.isLocalHost())return Promise.resolve(void 0);return(n="compile/"+t.sha,e.Cloud.localRequestAsync(n,i).then(e=>e.json)).then(e=>e&&!e.notInOfflineCache&&e.hex?(e.hex=e.hex.split(/\r?\n/),e):Promise.resolve(void 0)).catch(e=>Promise.resolve(void 0));var n,i}(n).then(r=>r?(e.tickEvent("cppcompile.cachehit"),r):function(){if(i)return i;{let t=e.getOnlineCdnUrl();if(t)return i=Promise.resolve(t);const n=e.webConfig&&e.webConfig.isStatic;return i=e.Cloud.privateGetAsync("clientconfig",n).then(e=>e.primaryCdnUrl)}}().then(t=>(s=t+"/compile/"+n.sha,e.U.httpGetTextAsync(s+".hex"))).then(e=>e,t=>e.Cloud.privatePostAsync("compile/extension",{data:n.compileData},!0).then(t=>new Promise((n,i)=>{let r=0;const 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(t){e.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(t,n,i){return t.cacheGetAsync(n).then(s=>{let r;try{r=JSON.parse(s||"[]")}catch(i){return e.error("invalid cache entry, clearing entry"),t.cacheStoreAsync(n,"[]")}return r[0]!=i?(r=r.filter(e=>e!=i),r.unshift(i),t.cacheStoreAsync(n,JSON.stringify(r))):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(t){e.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){t.KEY_VARIABLE="CROWDIN_KEY",t.testMode=!1,t.setTestMode=function(){e.crowdin.testMode=!0,e.log("CROWDIN TEST MODE - files will NOT be uploaded")},t.inContextLoadAsync=function(t){const n=document.createElement("input");n.type="text",n.setAttribute("class","hidden"),n.value=t;let i=new Promise((i,s)=>{const r=new MutationObserver(()=>{if(t==n.value)return;const s=e.Util.rlf(n.value);n.remove(),r.disconnect(),i(s)});r.observe(n,{attributes:!0})});return document.body.appendChild(n),i}}(e.crowdin||(e.crowdin={}))}(pxt||(pxt={})),function(e){!function(t){function n(e,t){if(!e)return[];if(t){const t=[];let n=0;for(let i=0;i<e.length;i++){"\n"===e.charAt(i)&&(t.push(e.substring(n,i+1)),n=i+1)}return t.push(e.substring(n)),t}return e.split(/\r?\n/)}let i;function s(e,t,s={}){s.ignoreWhitespace&&(e=e.replace(/[\r\n]+$/,""),t=t.replace(/[\r\n]+$/,""));const r=n(e,!0),a=n(t,!0),o=Math.min(s.maxDiffSize||1024,r.length+a.length);if(0==o)return[];const l=r.length>65520?Uint32Array:Uint16Array,c={};let u=0;const d=p(r),h=p(a);function p(e){const t=new l(e.length);let n=0;for(let i of e)s.ignoreWhitespace&&(i=i.replace(/\s+$/g,"").replace(/^\s+/g,"")),c.hasOwnProperty(i)?t[n]=c[i]:(++u,t[n]=u,c[i]=u),n++;return t}const f=new l(2*o+1);let m=-1;for(let e=0;e<=o;e++)null!=w(e,f)&&(m=e);if(-1==m)return null;const g=[];let b=null;for(let e=0;e<=m;e++){const t=g.length?g[g.length-1].slice(0):new l(2*m+1);if(g.push(t),b=w(e,t),null!=b)break}const y=[];let v=b;for(let e=g.length-1;e>=0;e--){const t=g[e];let n=0,s=0;v==-e||v!=e&&t[o+v-1]<t[o+v+1]?(s=v+1,n=t[o+s]):(s=v-1,n=t[o+s]+1);let l=n-v;for(let e=t[o+v]-n-1;e>=0;--e)y.push([i.Unchanged,a[l+e]]);s==v-1?y.push([i.Deleted,r[n-1]]):l>0&&y.push([i.Added,a[l-1]]),v=s}return y.reverse(),y;function w(e,t){for(let n=-e;n<=e;n+=2){let i=0;i=n==-e||n!=e&&t[o+n-1]<t[o+n+1]?t[o+n+1]:t[o+n-1]+1;let s=i-n;for(;i<d.length&&s<h.length&&d[i]==h[s];)i++,s++;if(t[o+n]=i,i>=d.length&&s>=h.length)return n}return null}}function r(e,t,n={}){const r=s(e,t,n);if(n.context==1/0||n.full)return r.map(a);let o=1,l=1,c=0;const u=[],d=n.context||3;for(;c<r.length;){let e=c;for(;e<r.length&&r[e][0]===i.Unchanged;)e++;if(e==r.length)break;const t=e-d,n=t-c;n>0&&(o+=n,l+=n,c=t);const s=u.length,h=o,p=l;u.push("@@");let f=c,m=0;for(;f<r.length;){if(r[f][0]===i.Unchanged){if(m++,m>2*d+2){f-=d+2;break}}else m=0;f++}for(;c<f;){u.push(a(r[c]));switch(r[c][0]){case i.Deleted:o++;break;case i.Added:l++;break;case i.Unchanged:o++,l++}c++}u[s]=`@@ -${h},${o-h} +${p},${l-p} @@`}return u}function a([e,t]){let n;return n=e===i.Added?"+ ":e===i.Deleted?"- ":" ",n+t.replace(/\r?\n/,"")}function o(e){return n(e).map(e=>e.replace(/;\s*$/,"")).join("\n")}function l(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,function(e){e[e.Added=1]="Added",e[e.Deleted=-1]="Deleted",e[e.Unchanged=0]="Unchanged"}(i||(i={})),t.compute=s,t.computeFormattedDiff=r,t.computePatch=function(e,t){const n=s(e,t,{full:!0,maxDiffSize:2048});if(!n)return[{start1:0,length1:e.length,diffs:[[i.Added,t]]}];const r=function(e){const t=[];let n="",s="",r="",a=i.Unchanged;const o=()=>{t.push({start1:n.length,length1:r.length,diffs:[[i.Added,s]]}),n+=s,s="",r=""};for(let t=0;t<e.length;t++){const[l,c]=e[t];l==i.Unchanged?(a!==i.Unchanged&&o(),n+=c):l===i.Added?s+=c:l===i.Deleted&&(a===i.Added&&o(),r+=c),a=l}return a!==i.Unchanged&&o(),t}(n);return r},t.applyPatch=function(e,t){let n=e;for(const e of t){const t=e.diffs.filter(e=>e[0]!==i.Deleted).map(e=>e[1]).join("");n=n.substring(0,e.start1)+t+n.substring(e.start1+e.length1)}return n},t.diff3=function(t,r,a,o,l){const c=b(t),u=b(a);if(!c||!u)return;const d=n(t),h=n(a);let p=0,f=[],m=0,g=0;for(let t=0;t<c.length-1;)if(c[t]==m&&u[t]==g)f.push(d[m]),m++,g++,t++;else{let n=!0,i=!0,s=t;for(;s<c.length&&(c[s]!=m+s-t&&(n=!1),u[s]!=g+s-t&&(i=!1),null==c[s]||null==u[s]);)s++;if(e.U.assert(s<c.length),n)for(;g<u[s];)f.push(h[g++]);else if(i)for(;m<c[s];)f.push(d[m++]);else if(d.slice(m,c[s]).join("\n")==h.slice(g,u[s]).join("\n"))for(;m<c[s];)f.push(d[m++]);else{for(p++,f.push("<<<<<<< "+o);m<c[s];)f.push(d[m++]);for(f.push("=======");g<u[s];)f.push(h[g++]);f.push(">>>>>>> "+l)}t=s,m=c[s],g=u[s]}return{merged:f.join("\n"),numConflicts:p};function b(t){const n=s(r,t,{context:1/0});if(!n)return;const a=[];let o=0,l=0;for(let t of n)t[0]==i.Added?o++:t[0]==i.Deleted?(a[l]=null,l++):t[0]==i.Unchanged?(a[l]=o,o++,l++):e.U.oops();return a.push(o+1),a}},t.removeTrailingSemiColumns=o,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$/,""),s=n[1].replace(/^\n/,"");return t&&t.removeTrailingSemiColumns&&(i=o(i),s=o(s)),{fileA:i,fileB:s}},t.parseDiffMarker=l,t.render=function(t,n,i={}){const s=r(t,n,i);if(!s)return e.dom.el("div",null,pxtc.Util.lf("Too many differences to render diff."));const a={"@":"diff-marker"," ":"diff-unchanged","+":"diff-added","-":"diff-removed"};let o=0,c=0,u="";const d=e.dom.el("tbody"),h=e.dom.el("table",{class:"diffview "+(i.update?"update":"")},d);let p=null;return s.forEach((t,n)=>{const h=l(t);h?(o=h.oldStart,c=h.newStart):("+"!=t[0]&&o++,"-"!=t[0]&&c++);const f=s[n+1]?s[n+1][0]:"",m=s[n+2]?s[n+2][0]:"",g=t.slice(2);let b=e.dom.el("code",null,g);if(p)b=p,p=null;else if(!("-"!=t[0]||" "!=u&&"@"!=u||"+"!=f||" "!=m&&"@"!=m&&""!=m)){const i=function(t,n){const i=r(t.split("").join("\n"),n.split("").join("\n"),{context:1/0});if(!i)return{a:e.dom.el("div",{class:"inline-diff"},e.dom.el("code",null,t)),b:e.dom.el("div",{class:"inline-diff"},e.dom.el("code",null,n))};const s=[],a=[];for(let t=0;t<i.length;){let n=t;const r=i[t][0];for(;i[n]&&i[n][0]==r;)n++;const o=i.slice(t,n).map(e=>e.slice(2)).join("");" "==r?(s.push(e.dom.el("code",{class:"ch-common"},o)),a.push(e.dom.el("code",{class:"ch-common"},o))):"-"==r?s.push(e.dom.el("code",{class:"ch-removed"},o)):"+"==r?a.push(e.dom.el("code",{class:"ch-added"},o)):e.Util.oops(),t=n}return{a:e.dom.el("div",{class:"inline-diff"},s),b:e.dom.el("div",{class:"inline-diff"},a)}}(t.slice(2),s[n+1].slice(2));b=i.a,p=i.b}if(u=t[0],i.hideMarkerLine&&"@"==u||i.hideRemoved&&"-"==u)return;const y="@"==u,v=`${a[u]}`;d.appendChild(e.dom.el("tr",{class:v},[!i.hideLineNumbers&&e.dom.el("td",{class:"line-a","data-content":o}),!i.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)),!i.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",hideToolbox:"\x3c!-- hideToolbox --\x3e",hideIteration:"\x3c!-- iter --\x3e",codeStart:"\x3c!-- start --\x3e",codeStop:"\x3c!-- stop --\x3e",autoOpen:"\x3c!-- autoOpen --\x3e",autoexpandOff:"\x3c!-- autoexpandOff --\x3e",preferredEditor:"\x3c!-- preferredEditor --\x3e"};function l(e,t,n){return e.split(t).join(n)}function c(e){return e=l(e,"&","&"),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=()=>{const e=null===globalThis||void 0===globalThis?void 0:globalThis.marked;if(e)return e;if("undefined"==typeof require)return;const t=e=>{var t;try{const n=require(e);return(null==n?void 0:n.marked)?n.marked:(null===(t=null==n?void 0:n.default)||void 0===t?void 0:t.marked)?n.default.marked:(null==n?void 0:n.default)?n.default:n}catch(e){return}};return t("marked/lib/marked.umd.js")||t("marked")},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 g(n,i,["ITEMS"])},m=[{name:lf("Docs"),href:"/docs"}];const b=e.TOC||p.TOC||[];let y=[],v=t=>{for(let e of t.subitems||[])if(v(e))return y.push(t),!0;return!(!e.filepath||!t.path||e.filepath!=t.path)&&(y.push(t),!0)};b.forEach(v);let w=(t,n)=>{let i=c.item,s={NAME:t.name};return t.path&&!/^(https?:|\/)/.test(t.path)?h("Invalid link: "+t.path):(/^\//.test(t.path)&&e.versionPath&&(t.path=`/${e.versionPath}${t.path}`),s.LINK=t.path,y.indexOf(t)>=0?(s.ACTIVE="active",s.EXPANDED="true",m.push({name:t.name,href:t.path})):s.EXPANDED="false",t.subitems&&t.subitems.length>0?(i=c["toc-dropdown"]?""!==t.name?c["toc-dropdown"]:c["toc-dropdown-noLink"]:0==n?""!==t.name?c["top-dropdown"]:c["top-dropdown-noHeading"]:1==n?c["inner-dropdown"]:c["nested-dropdown"],s.ITEMS=t.subitems.map(e=>w(e,n+1)).join("\n")):/^-+$/.test(t.name)&&(i=c.divider),g(i,s,["ITEMS"]))};d.menu=(p.docMenu||[]).map(e=>f(e,0)).join("\n"),d.TOC=b.map(e=>w(e,0)).join("\n"),p.appStoreID&&(d.appstoremeta=`<meta name="apple-itunes-app" content="app-id=${n.htmlEscape(p.appStoreID)}"/>`);let A="";m.length>1&&(A=`\n <nav class="ui breadcrumb" aria-label="${lf("Breadcrumb")}">\n ${m.map((e,t)=>`<a class="${t==m.length-1?"active":""} section"\n href="${u(e.href)}" aria-current="${t==m.length-1?"page":""}">${u(e.name)}</a>`).join('<i class="right chevron icon divider"></i>')}\n </nav>`),d.breadcrumb=A,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 k=p.docsLogo&&n.htmlEscape(p.docsLogo),T=(p.organizationWideLogo||p.organizationLogo)&&n.htmlEscape(p.organizationWideLogo||p.organizationLogo),x=p.organizationLogo&&n.htmlEscape(p.organizationLogo);d.targetlogo=k?`<img aria-hidden="true" role="presentation" class="ui ${p.logoWide?"small":"mini"} image" src="${k}" />`:"",d.orglogo=T?`<img aria-hidden="true" role="presentation" class="ui image" src="${T}" />`:"",d.orglogomobile=x?`<img aria-hidden="true" role="presentation" class="ui image" src="${x}" />`:"";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"),S=`\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=S;const N=`\n <a id="togglesidebar" class="launch icon item" tabindex="0" title="Side menu" aria-label="${lf("Side menu")}" role="menuitem" aria-expanded="false">\n <i class="content icon"></i>\n </a>\n `;d.sidebarToggle=N;const U=["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=U[0],d.searchBar2=U[1];let O="";p.accentColor&&(O+=`\n.ui.accent { color: ${p.accentColor}; }\n.ui.inverted.accent { background: ${p.accentColor}; }\n`),d.targetstyle=O,d.tocclass=p.lightToc?"lighttoc":"inverted";for(let e of Object.keys(p)){let t=p[e];void 0===d[e]&&"string"==typeof t&&(d[e]=t)}e.finish=()=>g(e.html,d,["body","menu","accMenu","TOC","prev","next","printBtn","breadcrumb","targetlogo","orglogo","orglogomobile","github","JSON","appstoremeta","sidebarToggle","searchBar1","searchBar2"])}function f(e,t={}){e.image=function(e){var t;const n=e.href||"",i=e.title||"",s=e.text||"";if(n.startsWith("youtube:")){const e=n.split(":").pop();return`<div class="tutorial-video-embed" data-youtube="${encodeURIComponent(e)}" title="${s}"></div>`}{let e=`<img class="ui image" src="${n}" alt="${s}"`;return i&&(e+=` title="${i}"`),e+=' loading="lazy"',e+=(null===(t=this.options)||void 0===t?void 0:t.xhtml)?"/>":">",e}},e.listitem=function(e){const t=this.parser.parse(e.tokens,!!e.loose);return e.task?`<li class="${e.checked?"checked":"unchecked"}">${t}</li>\n`:`<li>${t}</li>\n`},e.heading=function(e){var t;let n=this.parser.parseInline(e.tokens).trim(),i="";const s=/(.*)#([\w\-]+)\s*$/.exec(e.text||"");s&&(i=s[2],n=n.replace(/#([\w\-]+)\s*$/,"").trim()),n=n.replace(/@(fullscreen|unplugged|showdialog|showhint)/gi,"").trim();const r=n.match(/\{([\s\S]+)\}/);if(r&&(n=r[1].trim()),!i){i=(e=>{let t;do{t=e,e=e.replace(/<[^>]+>/g,"")}while(e!==t);return e})(n).toLowerCase().replace(/[^\w]+/g,"-")}const a=(null===(t=this.options)||void 0===t?void 0:t.headerPrefix)||"";return`<h${e.depth} id="${a}${i}">${n}</h${e.depth}>`},e.code=function(e){const t=c(("string"==typeof(null==e?void 0:e.lang)?e.lang.trim():"").toLowerCase()),n="string"==typeof(null==e?void 0:e.text)?e.text:"";return`<pre><code${t?` class="lang-${t}"`:""}>${!1!=!!(null==e?void 0:e.escaped)?n:c(n)}</code></pre>`};const n=null==t?void 0:t.versionPath,i=e.link?e.link.bind(e):void 0;e.link=function(e){const t=e.href||"",s=/^[/#]/.test(t),r=s&&n?`/${n}${t}`:t,a=Object.assign(Object.assign({},e),{href:r}),o=i?i(a):`<a href="${a.href}">${this.parser.parseInline(a.tokens||[])}</a>`,l=[];s||l.push('target="_blank"'),l.push('rel="nofollow noopener"');const c=l.join(" ");return o.replace(/^<a /,`<a ${c} `)}}function m(e,t){return e.replace(/<!--\s*@(ifn?def)\s+(\w+)\s*-->([^]*?)<!--\s*@endif\s*-->/g,(e,n,i,s)=>"ifdef"==n&&t[i]||"ifndef"==n&&!t[i]?`\x3c!-- ${n} ${i} --\x3e${s}\x3c!-- endif --\x3e`:`\x3c!-- ${n} ${i} endif --\x3e`)}function g(e,t,i=[]){return e?e.replace(/@(\w+)@/g,(e,s)=>{let r=n.lookup(t,s)||"";return r+="",i.indexOf(s)<0&&(r=u(r)),r}):""}t.prepTemplate=p,t.setupRenderer=f,t.renderConditionalMacros=m,t.renderMarkdown=function(e){let s=!0;e.pubinfo||(s=!1,e.pubinfo={});let r=e.pubinfo;if(e.theme||(e.theme={}),delete e.pubinfo.private,r.time){let e=parseInt(r.time);r.timems||(r.timems=1e3*e+""),r.humantime||(r.humantime=n.isoTime(e))}r.name&&(r.dirname=r.name.replace(/[^A-Za-z0-9_]/g,"-"),r.title=r.name),s&&(r.JSON=JSON.stringify(r,null,4).replace(/</g,"\\u003c"));let 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=m(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};if(p(o),i||(i=t.requireMarked()),!i)return o.finish?o.finish():o.html;const l=new i.Renderer;f(l,{versionPath:o.versionPath});let c=t.requireDOMSanitizer();i.setOptions({renderer:l,async:!1,gfm:!0,tables:!0,breaks:!1,pedantic:!1});let b=e.markdown;e.repo&&(b+=`\n\`\`\`package\n${e.repo.name.replace(/^pxt-/,"")}=github:${e.repo.fullName}#${e.repo.tag||"master"}\n\`\`\`\n`),b=b.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}),b=b.replace(/@([a-z]+)@/gi,(t,i)=>{let s=r[i];return!s&&e.throwOnError&&n.userError(`unknown macro ${i}`),s||"unknown macro"});let v=i.parse(b);const w=(e,t="")=>"string"==typeof e?e:e&&"function"==typeof e.toString?e.toString():t;let A=v;c&&(A=c(v)),v=w(A,w(v,"")),v=v.replace(/<br\s*\/>/gi,"<br/>"),v=v.replace(/(<img [^>]* src=")\/docs\/static\/([^">]+)"/g,(e,t,n)=>t+"/static/"+n+'"');let k="",T=0;function x(e,t,n){let i=n;return e<=T&&(i=k+i,k="",T=0),i}if(v=v.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]:"";d=u(d),c=u(c);const p=parseInt(i,10);if(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(p,0,g(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(p,0,e[0].replace("@ARGS@",d));k=e[1];let i=t.match(/data-[^>\s]+/gi);return i&&i.indexOf("data-inferred")>=0&&(T=p),n}return e.throwOnError&&n.userError(`Unknown box: ~ ${c}`),h(`Unknown box: ~ ${c}`)}}return x(p,0,t)}),k&&(v+=k),!r.title){let e=/<h1[^<>]*>([^<>]+)<\/h1>/.exec(v);e&&(r.title=u(e[1]))}if(!r.description){let e=/<p>([^]+?)<\/p>/.exec(v);e&&(r.description=u(e[1]))}const E=/<div class="ui embed mdvid"[^<>]+?data-placeholder="([^"]+)"[^>]*\/?>/i.exec(v)||/<img class="ui [^"]*image" src="([^"]+)"[^>]*\/?>/i.exec(v);E&&(r.cardLogo=u(E[1])),r.twitter=u(e.theme.twitter||"@msmakecode");let C={main:""};v=v.replace(/<!-- BEGIN-ASIDE (\S+) -->([^]*?)<!-- END-ASIDE -->/g,(e,t,i)=>{let s=n.lookup(C,t);return C[t]=(s||"")+i,"\x3c!-- aside --\x3e"}),v=v.replace(/\n<\/code>/g,"</code>"),C.main=v;let I=(e,t)=>g(o.boxes[e]||"@BODY@",{BODY:t},["BODY"]);v="";for(let e of Object.keys(C))v+=I(e+"-container",C[e]);r.body=v,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(t){if(!t)return null;const n=e.docs.requireMarked();if(!n)return null;const i={renderer:new n.Renderer,gfm:!0,tables:!1,breaks:!1,pedantic:!1,smartLists:!1,smartypants:!1},s=n.lexer(t,i),r=e=>(e||"").replace(/\.md$/i,""),a=e=>{if(!e)return"";if("string"==typeof e.text)return e.text.trim();if(e.tokens&&e.tokens.length)for(const t of e.tokens){const e=a(t);if(e)return e}return""},o=e=>{const t={name:"",path:"",subitems:[]};let n="";const i=e=>{if(e)for(const s of e)if(s)switch(s.type){case"link":t.name||(t.name=(s.text||"").trim()),t.path||(t.path=r(s.href));break;case"text":case"codespan":case"strong":case"em":case"paragraph":s.tokens&&s.tokens.length?i(s.tokens):n||"string"!=typeof s.text||(n=s.text.trim());break;default:s.tokens&&s.tokens.length&&i(s.tokens)}};return i(null==e?void 0:e.tokens),t.name||(n=n||a(e),n||"string"!=typeof(null==e?void 0:e.text)||(n=e.text.split(/\n/)[0].trim()),t.name=n||""),t.path=r(t.path),t},l=(e,t)=>{if(e&&e.length)for(const n of e){const e=o(n),i=((null==n?void 0:n.tokens)||[]).filter(e=>"list"===(null==e?void 0:e.type));for(const t of i)l((null==t?void 0:t.items)||[],e.subitems);(e.name||e.subitems.length)&&t.push(e)}},c=[];for(const e of s)"list"===(null==e?void 0:e.type)&&Array.isArray(e.items)&&l(e.items,c);const u=e=>e.filter(e=>!!e.name||e.subitems&&e.subitems.length).map(e=>({name:e.name,path:e.path,subitems:e.subitems?u(e.subitems):[]}));let d=u(c);return d.length?d:null},t.visitTOC=function(e,t){e.forEach(function(e){t(e),e.subitems&&e.subitems.forEach(t)})};let A=!1;function k(t,i){if(A||function(){function t(t,n,i){let s=k(t,n).trim();if(s!=(i=i.trim()))throw e.log(`*** Template:\n${t}\n*** Input:\n${n}\n*** Expected:\n${i}\n*** Output:\n${s}`),new Error("augment docs test fail")}A=!0;let n="\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",i="\n# @extends\n# #ex2\nMy example\n## See Also These! #also\nMy links\n",s="\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",r="\n# @extends\n### #ex\nFoo\n#### Example 1\nEx1\n#### Example 2x #ex2\nEx2\n## See Also These! #also\nMy links\n",a="\n# T0\n## Examples #ex\nFoo\n#### Example 1\nEx1\n#### Example 2x #ex2\nEx2\n## See Also These! #also\nMy links\n";t(n,"",n),t(n," ",n),t(n,i,s),t(n,r,a)}(),!i)return t;let s=w(t,null),r=w(i,s),a={},o={};for(let e of r.children)n.assert(0==e.children.length),n.assert(!!e.id),a[e.id]=e.text;let l=e=>{e.id&&void 0!==a[e.id]&&(o[e.id]=!0,e.text=a[e.id],e.children=[]),e.children.forEach(l)};l(s);let c="",u=e=>{c+=e.text,e.children.forEach(u)};u(s);let d="",h=r.text.replace(/^\s*#+\s*@extends.*/gm,"").replace(/^\s*\n/gm,"");h.trim()&&(d+=h.trim()+"\n");for(let e of r.children)o[e.id]||(d+=e.text);return d&&(c+="## Couldn't apply replacement logic to:\n"+d),c}t.augmentDocs=k,t.hydrateYouTubeEmbeds=function(t,n){var i,s;for(const r of t.querySelectorAll(".tutorial-video-embed[data-youtube]")){const t=decodeURIComponent(r.getAttribute("data-youtube")),a=document.createElement("iframe");a.className="yt-embed";const o=`https://www.youtube-nocookie.com/embed/${t}`;let l=null!==(s=null===(i=e.appTarget.appTheme)||void 0===i?void 0:i.defaultLocale)&&void 0!==s?s:"en",c=new URL(o);n&&e.tickEvent("video.loaded",{player:"youtube",url:o}),c.searchParams.append("hl",l),c.searchParams.append("rel","0"),c.searchParams.append("modestbranding","1"),c.searchParams.append("autoplay","0"),c.searchParams.append("showinfo","0"),a.setAttribute("src",c.toString()),a.setAttribute("title",r.getAttribute("title")||""),a.setAttribute("frameborder","0"),a.setAttribute("allowFullScreen","true"),a.setAttribute("allow","autoplay; picture-in-picture"),a.setAttribute("sandbox","allow-same-origin allow-scripts"),r.textContent="",r.appendChild(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){const n=/```simtheme\s+([\s\S]*?)```/i.exec(t);return n?e.tutorial.parseSimThemeJson(n[1]):{}}function o(t){let n=e.Util.jsonTryParse(t);return n&&!Array.isArray(n)&&(n=[n]),(null==n?void 0:n.length)?n:(n=t.split(/^---$/gm).filter(e=>!!e).map(e=>{let t={};return e.replace(/^\s*(?:-|\*)\s+(\w+)\s*:\s*(.*)$/gm,(e,n,i)=>{if("flags"==n)t[n]=i.split(",");else if("otherAction"===n){const e=i.split(",").map(e=>null==e?void 0:e.trim());(t.otherActions||(t.otherActions=[])).push({url:e[0],editor:e[1],cardType:e[2]})}else t[n]=i;return""}),!!Object.keys(t).length&&t}).filter(e=>!!e),(null==n?void 0:n.length)?n:void 0)}function l(t){if(!t)return[];const n=[];let i,s=!1,r="";return t.split(/\r?\n/).forEach(t=>{if(/^## /.test(t))i=t.substr(2).trim();else if(/^(### ~ |```)codecard$/.test(t))s=!0;else if(/^(### ~|```)$/.test(t)){if(s=!1,i&&r){const t=o(r);(null==t?void 0:t.length)?n.push({name:i,cards:t}):e.log("invalid gallery format")}r="",i=void 0}else s&&(r+=t+"\n")}),n.forEach(t=>t.cards.forEach(t=>{if(t.otherActions&&!t.otherActions.length&&("tutorial"==t.cardType||"example"==t.cardType)){const n=["js"];e.appTarget.appTheme.python&&n.unshift("py"),t.otherActions=n.map(e=>({url:t.url,cardType:t.cardType,editor:e}))}})),n}t.parsePackagesFromMarkdown=n,t.parseFeaturesFromMarkdown=i,t.parseJResFromMarkdown=s,t.parseTemplateProjectJSON=r,t.parseSimThemeJSON=a,t.parseExampleMarkdown=function(t,o){if(!o)return;const l=/```(blocks?|typescript|python|spy|sim)\s+((.|\s)+?)\s*```/i.exec(o);if(!l)return;const c=n(o),u=l[1],d=l[2],h=i(o),p=s(o),f=a(o),m={name:t,filesOverride:{[e.MAIN_BLOCKS]:'<xml xmlns="http://www.w3.org/1999/xhtml"></xml>',["python"===l[1]?e.MAIN_PY:e.MAIN_TS]:d},dependencies:c,features:h,snippetType:u,source:d,simTheme:f};return m.filesOverride=Object.assign(Object.assign({},m.filesOverride),r(o)),p&&(m.filesOverride[e.TILEMAP_JRES]=p.jres,m.filesOverride[e.TILEMAP_CODE]=p.ts),m},t.parseCodeCards=o,t.parseCodeCardsHtml=function(t){let n,i=[];return Array.from(t.children).forEach(e=>{"UL"===e.tagName||"OL"===e.tagName?(n||(n={}),Array.from(e.querySelectorAll("li")).forEach(e=>{const t=e.innerText,i=/^\s*(\w+)\s*:\s*(.*)$/.exec(t);if(i){const e=i[1];n[e]=i[2].trim(),"flags"===e&&(n[e]=n[e].split(/,\s*/))}})):"HR"==e.tagName&&(n&&i.push(n),n=void 0)}),n&&i.push(n),0===i.length&&"CODE"===t.tagName&&(i=e.Util.jsonTryParse(t.textContent)),!!(null==i?void 0:i.length)&&i},t.parseGalleryMardown=l,t.loadGalleryAsync=function(t){return e.Cloud.markdownAsync(t).then(e=>l(e))},t.codeCardsToMarkdown=function(e){return`### ~ codecard\n\n${(e||[]).map(e=>Object.keys(e).filter(t=>!!e[t]).map(t=>"otherActions"===t?e[t].map(e=>`* otherAction: ${e.url}, ${e.editor||""}, ${e.cardType||""}`).join("\n"):`* ${t}: ${e[t]}`).join("\n")).join("\n\n---\n\n")}\n\n### ~\n`}}(e.gallery||(e.gallery={}))}(pxt||(pxt={})),function(e){e.GDBServer=class{constructor(t){this.io=t,this.q=new e.U.PromiseQueue,this.dataBuf="",this.numSent=0,this.pktSize=400,this.trace=!1,this.bmpMode=!0,this.targetInfo="",this.onEvent=e=>{},this.io.onData=e=>this.onData(e)}onData(t){for(this.dataBuf+=e.U.uint8ArrayToString(t);this.dataBuf.length>0;){let e=this.dataBuf[0];if("+"==e)this.dataBuf=this.dataBuf.slice(1);else if("$"==e||"%"==e){let t=this.decodeResp(this.dataBuf.slice(1));if(null==t)break;"$"==e?(this.io.sendPacketAsync(this.buildCmd("+")),this.onResponse?this.onResponse(t):this.numSent>0&&this.io.error("unexpected response: "+t)):this.onEvent(t)}else this.io.error("invalid character: "+e)}}buildCmd(t){if("+"==t)return e.U.stringToUint8Array(t);let n="";for(let e=0;e<t.length;++e){let i=t.charAt(e);"}"==i||"#"==i||"$"==i?(n+="}",n+=String.fromCharCode(32^i.charCodeAt(0))):n+=i}let i=0;t=n;for(let e=0;e<t.length;++e)i=i+t.charCodeAt(e)&255;return n="$"+t+"#"+("0"+i.toString(16)).slice(-2),e.U.stringToUint8Array(n)}decodeResp(e){let t="";for(let n=0;n<e.length;++n){let i=e[n];if("}"==i)++n,t+=String.fromCharCode(32^e.charCodeAt(n));else if("*"==i){++n;let i=e.charCodeAt(n)-29,s=t.charAt(t.length-1);for(;i-- >0;)t+=s}else{if("#"==i){return 2==e.slice(n+1,n+3).length?(this.dataBuf=e.slice(n+3),t):null}t+=i}}return null}sendCmdOKAsync(e){return this.sendCmdAsync(e,e=>"OK"==e)}error(e){this.io.error(e),this.io.disconnectAsync()}sendCmdAsync(t,n){this.numSent++;const i=this.buildCmd(t);return this.q.enqueue("one",()=>null===n?this.io.sendPacketAsync(i).then(()=>null):new Promise(s=>{this.onResponse=i=>{this.onResponse=null,this.trace&&e.log(`GDB: '${t}' -> '${i}'`),void 0===n||n(i)||this.error(`Invalid GDB command response: '${t}' -> '${i}'`),s(i)},this.io.sendPacketAsync(i)}))}sendRCmdAsync(t){return this.sendMCmdAsync("qRcmd,"+(n=t,e.U.toHex(e.U.stringToUint8Array(n))));var n}sendMCmdAsync(t){this.numSent++;const n=this.buildCmd(t);let i="";return this.q.enqueue("one",()=>new Promise(s=>{this.onResponse=n=>{var r;"OK"!=n&&"O"==n[0]?i+=(r=n.slice(1),e.U.uint8ArrayToString(e.U.fromHex(r))):("OK"!=n&&(i+=" - "+n),this.onResponse=null,this.trace&&e.log(`Final GDB: '${t}' -> '${i}'`),s(i))},this.io.sendPacketAsync(n)}))}write32Async(t,n){let i=new Uint8Array(4);return e.HF2.write32(i,0,n),this.writeMemAsync(t,i)}writeMemAsync(t,n){const i=this.pktSize/2-10;return e.U.assert(n.length<i),this.sendCmdOKAsync("M"+t.toString(16)+","+n.length.toString(16)+":"+e.U.toHex(n)).then(t=>{e.log(t)})}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)}function i(e){return!!t.forceProxy||!(t.token&&!e)&&n()}t.token=null,t.forceProxy=!1;const s=["microsoft"];t.shouldUseProxyForRepo=function(e){if(!t.token)return i();const n=S(e);if(!n)return i();const r=n.owner.toLowerCase();return!!s.some(e=>e===r)||i()};const r={};function a(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==D?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 o(e){return a({url:e,method:"GET"}).then(e=>e.json)}function l(t){return e.Cloud.apiRequestWithCdnAsync({url:"gh/"+t,forceLiveEndpoint:!0}).then(e=>e.json)}function c(t){e.log(`github proxy error: ${t.message}`),e.debug(t)}t.isOrgAsync=function(e){return a({url:`https://api.github.com/orgs/${e}`,method:"GET",allowHttpErrors:!0}).then(e=>200==e.statusCode)};class u{constructor(){this.latestVersions={},this.configs={},this.packages={}}proxyWithCdnLoadPackageAsync(t,n){const i=`${t}/${n}`;let s=this.packages[i];if(s)return e.debug(`github cache ${t}/${n}/text`),Promise.resolve(s);const r=S(t);return l(O(r.slug,n,r.fileName,"text")).then(e=>this.packages[i]={files:e})}cacheConfig(t,n){const i=e.Package.parseAndValidConfig(n);return this.configs[t]=i,e.U.clone(i)}async loadConfigAsync(t,i){i||(e.debug("dep: default to master branch"),i="master");const s=`${t}/${i}`;let r=this.configs[s];if(r)return e.debug(`github cache ${t}/${i}/config`),e.U.clone(r);if(n())try{const n=await this.proxyWithCdnLoadPackageAsync(t,i);return this.cacheConfig(s,n.files[e.CONFIG_NAME])}catch(e){c(e)}const a=await h(t,i,e.CONFIG_NAME);return this.cacheConfig(s,a)}async latestVersionAsync(t,n){let i=this.latestVersions[t];return i||(e.debug(`dep: resolve latest version of ${t}`),this.latestVersions[t]=i=await e.github.latestVersionAsync(t,n,!0,!1)),i}async loadPackageAsync(t,i){if(i||(e.debug("load pkg: default to master branch"),i="master"),n())try{return await this.proxyWithCdnLoadPackageAsync(t,i).then(t=>e.U.clone(t))}catch(e){c(e)}return await this.githubLoadPackageAsync(t,i)}githubLoadPackageAsync(t,n){return v(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}`),h(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=>h(t,i,e).then(t=>{r.files[e]=t})).then(()=>(this.packages[s]=r,e.U.clone(r)))}))})}async loadTutorialMarkdown(t,n){t=M(t);const i=(await p(t,n)).resp,s=i.markdown;return e.Util.assert("object"==typeof s),await this.cacheReposAsync(i),s.repo}async cacheReposAsync(e){if("object"==typeof e.markdown){const t=e.markdown;this.cacheRepo(t.repo)}for(const t of e.dependencies)this.cacheRepo(t)}cacheRepo(e){let t=e.repo;e.subPath&&(t+="/"+e.subPath);let n=t;n+="/"+e.sha,this.packages[n]={files:e.files},e.latestVersion&&this.cacheLatestVersion(t,e.latestVersion);const i=e.files["pxt.json"];if(i){const t=n+"/"+(e.version||"master");this.cacheConfig(n,i),this.cacheConfig(t,i)}}cacheLatestVersion(e,t){this.latestVersions[e]=t}}function d(t,n,i){return a({url:"https://api.github.com/repos/"+O(t.slug,"contents",t.fileName,i+"?ref="+n),method:"GET"}).then(n=>{const i=n.json;return r[t.slug]=!0,i&&"base64"==i.encoding&&null!=i.content?e.Util.fromUTF8(atob(i.content)):e.U.httpGetTextAsync(i.download_url)})}function h(t,n,i){const s=S(t);return r[s.slug]?d(s,n,i):e.U.requestAsync({url:"https://raw.githubusercontent.com/"+O(s.slug,n,s.fileName,i),allowHttpErrors:!0}).then(e=>200==e.statusCode?e.text:d(s,n,i))}async function p(t,n,i,s){let r=e.Cloud.apiRequestWithCdnAsync;const a=new URLSearchParams;n&&a.set("ref",n),i&&(a.set("noCache","1"),r=e.Cloud.privateRequestAsync);let o=`ghtutorial/${t}`;o=e.BrowserUtils.appendUrlQueryParams(o,a);const l=s?{"If-None-Match":s}:void 0,c=await r({url:o,method:"GET",headers:l});let u;return u=304===c.statusCode?void 0:c.json,{resp:u,etag:c.headers.etag}}function f(e,t,n,i){return a({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 m(e,t){let n=1;for(;e.refs[t+n];)n++;return t+n}async function g(e,t,n){return await f(e+"/git/refs",{ref:"refs/heads/"+t,sha:n}),t}function b(t,n="tags",s,r){const a=S(t),l=i(s);let c=null;const u=l?e.U.httpGetJsonAsync(e.BrowserUtils.cacheBustingUrl(`${e.Cloud.apiRoot}gh/${a.slug}/refs${r?"?nocache=1":""}`)).then(t=>{let i=Object.keys(t.refs).filter(t=>e.U.startsWith(t,"refs/"+n+"/")).map(e=>({ref:e,object:{sha:t.refs[e]}}));return c=t.refs.HEAD,i}):o(`https://api.github.com/repos/${a.slug}/git/refs/${n}/?per_page=100`);let d=e=>e.replace(/^refs\/[^\/]+\//,"");return u.then(t=>{t.sort((t,n)=>e.semver.strcmp(d(t.ref),d(n.ref)));let n={};for(let e of t)n[d(e.ref)]=e.object.sha;return{refs:n,head:c}},e=>404==e.statusCode?{refs:{}}:Promise.reject(e))}function y(e){return"commit"==e.object.type?Promise.resolve(e.object.sha):"tag"==e.object.type?o(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 v(e,t){if(/^[a-f0-9]{40}$/.test(t))return Promise.resolve(t);const n=S(e);return o(`https://api.github.com/repos/${n.slug}/git/refs/tags/${t}`).then(y,e=>o(`https://api.github.com/repos/${n.slug}/git/refs/heads/${t}`).then(y))}async function w(e,n,i){return n||(n=await t.db.latestVersionAsync(e,i)),await t.db.loadConfigAsync(e,n)}async function A(n,i){const s=S(n);if(!s)return void e.log("Unknown GitHub syntax");if(C(s,i))return e.tickEvent("github.download.banned"),void e.log("Github repo is banned");s.tag||(s.tag=await t.db.latestVersionAsync(s.slug,i));const r=await t.db.loadPackageAsync(s.fullName,s.tag),a=P(i,n);if(a){const t=e.Package.parseAndValidConfig(r.files[e.CONFIG_NAME]);t&&(e.log(`auto-disable ${a.join(",")} due to targetconfig entry for ${n}`),t.disablesVariants=a,r.files[e.CONFIG_NAME]=e.Package.stringifyConfig(t))}return r}let k;function T(t){return e.Cloud.cdnApiUrl(`gh/${t.fullName}/icon`)}function x(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=E(i,null==t?void 0:t.config),i}function E(e,t){return e?C(e,t)?k.Banned:function(e,t){var n,i;if(function(e,t){return!(!e||!t)&&!!(e.owner&&t.approvedOrgs&&t.approvedOrgs.some(t=>t.toLowerCase()==e.owner.toLowerCase()))}(e,t))return!0;const s=null===(n=null==e?void 0:e.fullName)||void 0===n?void 0:n.toLowerCase(),r=null===(i=null==e?void 0:e.slug)||void 0===i?void 0:i.toLowerCase();return!(!(null==t?void 0:t.approvedRepoLib)||!s&&!r)&&!(!t.approvedRepoLib[s]&&!t.approvedRepoLib[r])}(e,t)?k.Approved:k.Unknown:k.Unknown}function C(e,t){var n,i;if(function(e,t){return!(!t||e&&e.owner&&(!t.bannedOrgs||!t.bannedOrgs.some(t=>t.toLowerCase()==e.owner.toLowerCase())))}(e,t))return!0;if(!t)return!1;if(!e)return!0;const s=null===(n=e.fullName)||void 0===n?void 0:n.toLowerCase(),r=null===(i=e.slug)||void 0===i?void 0:i.toLowerCase();return!(!t.bannedRepos||!t.bannedRepos.some(e=>e&&(e.toLowerCase()==s||e.toLowerCase()==r)))}async function I(t,i){const s=S(t);if(!s)return;const r=E(s,i);if(r==k.Banned)return;if(n())try{return await function(t,n){return l(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,displayName:e.displayName,description:e.description,defaultBranch:e.defaultBranch||"master",tag:t.tag,status:n}}).catch(t=>{e.reportException(t)})}(s,r)}catch(e){c(e)}return x(await o("https://api.github.com/repos/"+s.slug),{config:i,fullName:s.fullName,fileName:s.fileName,tag:s.tag})}function S(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:O(i,s),fullName:O(i,s,r),tag:a,fileName:r}}function N(e){return!!e&&"github:"==e.slice(0,7)}function U(e,t=!1){return e?"github:"+(t?e.fullName:e.fullName.toLowerCase())+(e.tag?`#${e.tag}`:""):void 0}function O(...e){return e.filter(e=>!!e).join("/")}function _(t,n){var i;if(!t)return null;const s=S(n);if(!s)return null;t.approvedRepoLib;return t.approvedRepoLib&&(null===(i=e.U.lookup(t.approvedRepoLib,s.slug.toLowerCase()))||void 0===i?void 0:i.upgrades)}function P(e,t){const n=_(e,t)||[];if(!n)return null;for(const e of n){const t=/^dv:(.*)/.exec(e);if(t){const e=t[1].split(/,/);return e.some(e=>!/^\w+$/.test(e))?null:e}}return null}function L(t,n,i,s){const r=S(t);return r?I(r.slug,n).then(t=>{if(t)return b(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||v(t.slug,t.defaultBranch)})}):Promise.resolve(null)}t.MemoryGithubDb=u,t.downloadTextAsync=h,t.downloadMarkdownTutorialInfoAsync=p,t.downloadTutorialMarkdownAsync=async function(e,n){return t.db.loadTutorialMarkdown(e,n)},t.db=new u,t.authenticatedUserAsync=function(){return t.token?o("https://api.github.com/user"):Promise.resolve(void 0)},t.getCommitsAsync=function(e,t){return o("https://api.github.com/repos/"+S(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 o("https://api.github.com/repos/"+S(e).slug+"/git/commits/"+t).then(e=>o(e.tree.url+"?recursive=1").then(t=>(e.tree=t,e)))},t.createObjectAsync=function(e,t,n){return f(S(e).slug+"/git/"+t+"s",n).then(e=>e.sha)},t.postCommitComment=function(e,t,n,i,s){return f(`${S(e).slug}/commits/${t}/comments`,{body:n,path:i,position:s}).then(e=>e.id)},t.fastForwardAsync=async function(e,t,n){const i=S(e);return 200==(await a({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 s=S(t);await a({url:`https://api.github.com/repos/${e.github.join(s.slug,"contents",s.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 f(e+"/git/refs",{ref:"refs/tags/"+t,sha:n})},t.createReleaseAsync=async function(e,t,n){await f(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 f(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,s){return a({url:`https://api.github.com/repos/${S(t).slug}/merges`,method:"POST",successCodes:[201,204,409],data:{base:n,head:i,commit_message:s}}).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 o("https://api.github.com/repos/"+e+"/git/refs/heads/"+(t=t||"master")).then(y).catch(e=>{404!=e.statusCode&&Promise.reject(e)})},t.getNewBranchNameAsync=async function(e,t="patch-"){return m(await b(e,"heads"),t)},t.createNewBranchAsync=g,t.forkRepoAsync=async function(t,n,i="pr-"){const s=S(t),r=x(await f(`${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 b(r.slug,"heads")}catch(e){}}if(!o)throw new Error(lf("Timeout waiting for fork"));const l=m(o,i);return await g(r.slug,l,n),r.fullName+"#"+l},t.listRefsAsync=function(e,t="tags",n,i){return b(e,t,n,i).then(e=>Object.keys(e.refs))},t.listRefsExtAsync=b,t.pkgConfigAsync=w,t.downloadPackageAsync=A,t.downloadLatestPackageAsync=async function(t,n,i){const s=await e.packagesConfigAsync(),r=await e.github.latestVersionAsync(t.slug,s,n,i),a=`${t.fullName}#${r}`;return await e.github.downloadPackageAsync(a,s),{version:`github:${a}`,config:await w(t.fullName,r,s)}},t.cacheProjectDependenciesAsync=async function(t){var n;const i=null===(n=Object.keys(t.dependencies))||void 0===n?void 0:n.filter(e=>N(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 A(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"}(k=t.GitRepoStatus||(t.GitRepoStatus={})),t.isDefaultBranch=function(e,t){return t&&t.defaultBranch?e===t.defaultBranch:/^(main|master)$/.test(e)},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: "HEAD:pxt.json") {\n ... on Blob {\n text\n }\n }\n readme: object(expression: "HEAD:README.md") {\n ... on Blob {\n text\n }\n }\n }\n }\n }\n}').then(t=>t.data.viewer.repositories.nodes.filter(e=>e.pxtjson).filter(t=>{t.default_branch=t.defaultBranchRef.name;const n=e.Package.parseAndValidConfig(t.pxtjson&&t.pxtjson.text),i=t.readme&&t.readme.text;return!!n&&(n.supportedTargets?n.supportedTargets.indexOf(e.appTarget.id)>-1:i&&i.indexOf("PXT/"+e.appTarget.id)>-1)}).map(e=>x(e,{fullName:e.full_name})))},t.createRepoAsync=function(e,t,n){return f("https://api.github.com/user/repos",{name:e,description:t,private:!!n,has_issues:!0,has_projects:!1,has_wiki:!1,allow_rebase_merge:!1,allow_merge_commit:!0,delete_branch_on_merge:!1}).then(e=>x(e))},t.enablePagesAsync=async function(t){const n=S(t);let i;try{const e=await o(`https://api.github.com/repos/${n.slug}/pages`);e&&(i=e.html_url)}catch(e){}if(!i)try{i=(await f(`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 o(`https://api.github.com/repos/${t}`);if(n&&!n.homepage)try{await f(`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==k.Approved)return T(e)},t.mkRepoIconUrl=T,t.repoStatus=E,t.isRepoHidden=function(e,t){var n,i;if(!e||!t)return!0;const s=null===(n=e.fullName)||void 0===n?void 0:n.toLowerCase(),r=null===(i=e.slug)||void 0===i?void 0:i.toLowerCase(),a=t.approvedRepoLib[s]||t.approvedRepoLib[r];return!(!a||!a.hidden)},t.repoAsync=I,t.searchAsync=function(t,n){if(!n)return Promise.resolve([]);let i=t.split("|").map(S).filter(e=>!!e);return i.length>0?Promise.all(i.map(e=>I(e.fullName,n))).then(e=>e.filter(e=>e&&e.status!=k.Banned)):e.U.httpGetJsonAsync(`${e.Cloud.apiRoot}ghsearch/${e.appTarget.id}/${e.appTarget.platformid||e.appTarget.id}?q=${encodeURIComponent(t)}`).then(t=>t.items.map(e=>x(e,{config:n,fullName:e.full_name})).filter(e=>e.status==k.Approved||n.allowUnapproved&&e.status==k.Unknown).filter(t=>!e.appTarget.appTheme.githubUrl||`https://github.com/${t.fullName}`!=e.appTarget.appTheme.githubUrl.toLowerCase())).catch(e=>[])},t.parseRepoId=S,t.toGithubDependencyPath=function(e,t){let n="github:"+e;return t&&(n+="#"+t),n},t.isGithubId=N,t.stringifyRepo=U,t.normalizeRepoId=function(e,t){const n=S(e);if(n)return!n.tag&&t&&(n.tag=t),U(n)},t.join=O,t.upgradedPackageReferenceAsync=async function t(n,i){const s=_(n,i);if(!s)return null;for(const r of s){const s=/^move:(.*)$/.exec(r);if(s){const r=S(s[1]);if(r){r.tag||(r.tag=await L(s[1],n));const a=S(i);!r.fileName&&a.fileName&&(r.fileName=a.fileName,r.fullName=O(r.owner,r.project,r.fileName));const o=U(r);e.debug(`upgrading ${i} to ${o}}`);const l=await t(n,o);return l||o}e.log(`cannot parse move target: ${s[1]}`)}const a=/^min:(.*)/.exec(r),o=a&&e.semver.tryParse(a[1]);if(o){const t=S(i),n=e.semver.tryParse(t.tag);return n&&e.semver.cmp(n,o)<0?(t.tag=a[1],e.debug(`upgrading ${i} to ${a[1]}`),U(t)):(n||e.log(`not upgrading ${i} - cannot parse version`),null)}P(n,i)||e.log(`invalid upgrade rule: ${i} -> ${r}`)}return i},t.upgradedPackageId=function(e,t){const n=P(e,t);return n?t+"?dv="+n.join(","):t},t.latestVersionAsync=L,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 D="https://api.github.com/graphql";function $(e){const t=JSON.stringify({query:e});return f(D,t)}function M(e){if(/^github\:/i.test(e)&&(e=e.slice(7)),/^https?\:/i.test(e)){e=new URL(e).pathname.slice(1);const t=/^((?:[^\/]+\/){2})blob\/[^\/]+\/(.*)\.md$/.exec(e);t&&(e=t[1]+t[2])}return e}t.lookupFile=function(e,t,n){if(!t)return null;const i=O(e.fileName,n);return t.tree.tree.find(e=>e.path==i)},t.ghGraphQLQueryAsync=$,t.findPRNumberforBranchAsync=function(e,t){const n=S(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 o(`https://api.github.com/repos/${e}/pages`).catch(e=>({status:null}))},t.normalizeTutorialPath=M}(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]=255&n,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]=255&n,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.initialized=!1,this.cmdSeq=e.U.randomUint32(),this.lock=new e.U.PromiseQueue,this.flashing=!1,this.rawMode=!1,this.maxMsgSize=63,this.bootloaderMode=!1,this.reconnectTries=0,this.autoReconnect=!1,this.icon=(null===(i=e.appTarget.appTheme.downloadDialogTheme)||void 0===i?void 0:i.deviceIcon)||"usb",this.msgs=new e.U.PromiseBuffer,this.eventHandlers={},this.jacdacAvailable=!1,this.onSerial=(e,t)=>{},this.onCustomEvent=(e,t)=>{},this.onConnectionChanged=()=>{};let r=[];n.onDeviceConnectionChanged=e=>this.disconnectAsync().then(()=>e&&this.reconnectAsync()),n.onSerial=(e,t)=>this.onSerial(e,t),n.onData=i=>{let s=i[0]&t.HF2_FLAG_MASK,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.initialized=!1,this.lock=new e.U.PromiseQueue,this.info=null,this.infoRaw=null,this.pageSize=null,this.flashSize=null,this.maxMsgSize=63,this.bootloaderMode=!1,this.msgs.drain()}onEvent(n,i){e.U.assert(!!(n&t.HF2_EV_MASK)),this.eventHandlers[n+""]=i}sendCustomEventAsync(e,n){return e==t.CUSTOM_EV_JACDAC?this.jacdacAvailable?this.talkAsync(t.HF2_CMD_JDS_SEND,n).then(()=>{}):Promise.resolve():Promise.reject(new Error("invalid custom event type"))}isConnected(){return this.io.isConnected()&&this.initialized}isConnecting(){return this.io.isConnecting()||this.io.isConnected()&&!this.initialized}reconnectAsync(){return this.resetState(),l(`reconnect raw=${this.rawMode}`),this.io.reconnectAsync().then(()=>this.initAsync()).catch(t=>{if(this.reconnectTries<5)return this.reconnectTries++,l(`error ${t.message}; reconnecting attempt #${this.reconnectTries}`),e.U.delay(500).then(()=>this.reconnectAsync());throw t})}disconnectAsync(){return l("disconnect"),this.io.disconnectAsync()}error(e){return this.io.error(e)}talkAsync(s,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?(this.initialized=!0,Promise.resolve()):Promise.resolve().then(()=>this.talkAsync(t.HF2_CMD_BININFO)).then(e=>(this.bootloaderMode=e[0]==t.HF2_MODE_BOOTLOADER,this.pageSize=s(e,4),this.flashSize=s(e,8)*this.pageSize,this.maxMsgSize=s(e,12),this.familyID=s(e,16),l(`Connected; msgSize ${this.maxMsgSize}B; flash ${this.flashSize/1024}kB; ${this.bootloaderMode?"bootloader":"application"} mode; family=0x${this.familyID.toString(16)}`),this.talkAsync(t.HF2_CMD_INFO))).then(t=>{this.infoRaw=e.Util.fromUTF8Array(t),e.debug("Info: "+this.infoRaw);let n={};("Header: "+this.infoRaw).replace(/^([\w\-]+):\s*([^\n\r]*)/gm,(e,t,i)=>(n[t.replace(/-/g,"")]=i,"")),this.info=n;let i=/v(\d\S+)(\s+(\S+))?/.exec(this.info.Header);this.info.Parsed=i?{Version:i[1],Features:i[3]||""}:{Version:"?",Features:""},l(`Board-ID: ${this.info.BoardID} v${this.info.Parsed.Version} f${this.info.Parsed.Features}`)}).then(()=>this.talkAsync(t.HF2_CMD_JDS_CONFIG,new Uint8Array([1])).then(()=>{this.jacdacAvailable=!0},e=>{this.jacdacAvailable=!1})).then(()=>{this.reconnectTries=0,this.initialized=!0,this.io.onConnectionChanged()})}}function u(t,n){if(!e.appTarget.compile.flashChecksumAddr)return Promise.resolve(t);let i=pxtc.UF2.readBytes(t,e.appTarget.compile.flashChecksumAddr,48),r=pxtc.parseChecksumBlock(i);return r?function(t){return e.appTarget.compile.flashChecksumAddr?t(e.appTarget.compile.flashChecksumAddr,12).then(n=>{let i=pxtc.parseChecksumBlock(n);return i?t(i.endMarkerPos,1).then(t=>s(t,0)!=i.endMarker?(e.log("end-marker mismatch"),null):i):null}):Promise.resolve(null)}(n).then(e=>{if(!e)return t;let n=e.regions.filter(e=>r.regions.some(t=>e.checksum==t.checksum&&e.length==t.length&&e.start==t.start));if(0==n.length)return t;l("skipping flash at: "+n.map(e=>`${pxtc.assembler.tohex(e.start)} (${e.length/1024}kB)`).join(", "));let i=e=>n.some(t=>t.start<=e&&e<t.start+t.length);return t.filter(e=>!(i(e.targetAddr)&&i(e.targetAddr+e.payloadSize-1)))}):Promise.resolve(t)}t.Wrapper=c,t.mkHF2PacketIOWrapper=function(t){return e.debug("packetio: wrapper hf2"),new c(t)},t.onlyChangedBlocksAsync=u}(e.HF2||(e.HF2={}))}(pxt||(pxt={})),function(e){!function(t){var n=e.Util,i=e.HF2;const s=i.read32;let r,a,o,l,c,u,d,h,p=!1;function f(e){return e<<2|2}function m(e){return 1&e?e>>1:0!=e?2&e?e==t.taggedNull?null:e!=t.taggedFalse&&(e==t.taggedTrue||{tagged:e>>2}):{ptr:e}:void 0}function g(e,t){if(n.assert(!(3&e)),n.assert(e>=0),e<2097152){let i=new Uint8Array(t);return e-=d.start,n.memcpy(i,0,d.buf,e,t),Promise.resolve(i)}let i=h.maxMsgSize-32;if(t>i){let s=[];for(;t>0;){let n=Math.min(i,t);s.push(g(e,n)),t-=n,e+=n}return Promise.all(s).then(n.uint8ArrayConcat)}return h.readWordsAsync(e,Math.ceil(t/4)).then(e=>e.length>t?e.slice(0,t):e)}function b(t){if("object"!=typeof t||!t)return Promise.resolve(t);if("number"==typeof t.ptr){if(3&t.ptr)return Promise.resolve({unalignedPtr:t.ptr});let s=0;return g(t.ptr,56).then(r=>{s=i.read16(r,2);let 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?g(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,x().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(!(3&e.index)),r=m(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]=m(e[s++]);i=2147483646&e[s++];let d=u[i+""];for(let t of a.args)l.locals[t.name]=m(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 A(){p=!1,a=new Promise((e,t)=>{o=e})}function k(e=!1){return Promise.resolve().then(()=>h.talkAsync(665147697,i.encodeU32LE([e?1:3]))).then(A)}function T(){return a||(a=Promise.resolve()),a}function x(){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=t=>e.log(t),t.decodeValue=m,t.heapExpandAsync=b,t.heapExpandMapAsync=y,t.startDebugAsync=function(e,t){return h=t,h.onEvent(915601917,w),(p=!1,r=null,l=null,Promise.resolve()).then(()=>{r=e,u={};let t=[];for(let n of e.procDebugInfo)t[n.idx]=n;for(let n of e.procDebugInfo)for(let e of n.calls)u[e.addr+""]={from:n,to:t[e.procIndex],stack:e.stack}}).then(()=>{let e=r.outfiles[pxtc.BINARY_UF2],t=n.stringToUint8Array(atob(e));return d=pxtc.UF2.toBin(t),h.reflashAsync(r).then(()=>h.reconnectAsync())}).then(()=>h.talkAsync(287358355).catch(e=>{})).then(()=>n.delay(200)).then(()=>h.reconnectAsync()).then(A).then(T)},t.handleMessage=function(t){if(e.log("HWDBGMSG",t),"debugger"!=t.type)return;let n=!1;switch(t.subtype){case"stepinto":n=!0;case"stepover":k(n)}},t.resumeAsync=k,t.waitForHaltAsync=T,t.getHwStateAsync=x}(e.HWDBG||(e.HWDBG={}))}(pxt||(pxt={})),function(e){e.ImageConverter=class{logTime(){if(this.start){let t=Date.now()-this.start;e.debug("Icon creation: "+t+"ms")}}convert(t){this.start||(this.start=Date.now());let n=atob(t.slice(t.indexOf(",")+1)),i=n.charCodeAt(0),s=n.charCodeAt(1),r=n.charCodeAt(2);if(135===i&&(i=224|n.charCodeAt(1),s=n.charCodeAt(2)|n.charCodeAt(3)<<8,r=n.charCodeAt(4)|n.charCodeAt(5)<<8,n=n.slice(4)),225!=i&&228!=i)return null;if(this.palette||this.setPalette(e.appTarget.runtime.palette.map(function(e){const t=parseInt(e.replace(/#/,""),16);return[255&t,t>>8&255,t>>16&255,255]})),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)}setPalette(e){e[0][3]=0,this.palette=new Uint8Array(4*e.length);for(let t=0;t<e.length;++t)this.palette[4*t+0]=e[t][0],this.palette[4*t+1]=e[t][1],this.palette[4*t+2]=e[t][2],this.palette[4*t+3]=e[t][3]}genMonochrome(t,n,i){let s=n+3&-4,r=54+this.palette.length,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))}},e.convertUint8BufferToPngUri=function(t,n){const i=new e.ImageConverter,s=[];for(let e=0;e<16;e++)s.push([t[3*e+2],t[3*e+1],t[3*e+0],255]);i.setPalette(s);const r=String.fromCharCode.apply(null,n),a=`data:image/x-mkcd-f4;base64,${btoa(r)}`;return i.convert(a)}}(pxt||(pxt={})),function(e){!function(t){function n(){const e={"tsconfig.json":t.TS_CONFIG,"test.ts":`// ${lf("tests go here; this will not be compiled when this package is used as an extension.")}\n`,"_config.yml":"makecode:\n target: @TARGET@\n platform: @PLATFORM@\n home_url: @HOMEURL@\ntheme: jekyll-theme-slate\ninclude:\n - assets\n - README.md\n",Makefile:"all: deploy\n\nbuild:\n\tpxt build\n\ndeploy:\n\tpxt deploy\n\ntest:\n\tpxt test\n",Gemfile:"source 'https://rubygems.org'\ngem 'github-pages', group: :jekyll_plugins","README.md":`\n> ${lf("Open this page at {0}","[https://@REPOOWNER@.github.io/@REPONAME@/](https://@REPOOWNER@.github.io/@REPONAME@/)")}\n\n## ${lf("Use as Extension")}\n\n${lf("This repository can be added as an **extension** in MakeCode.")}\n\n* ${lf("open [@HOMEURL@](@HOMEURL@)")}\n* ${lf("click on **New Project**")}\n* ${lf("click on **Extensions** under the gearwheel menu")}\n* ${lf("search for **https://github.com/@REPO@** and import")}\n\n## ${lf("Edit this project")}\n\n${lf("To edit this repository in MakeCode.")}\n\n* ${lf("open [@HOMEURL@](@HOMEURL@)")}\n* ${lf("click on **Import** then click on **Import URL**")}\n* ${lf("paste **https://github.com/@REPO@** and click import")}\n\n#### ${lf("Metadata (used for search, rendering)")}\n\n* for PXT/@TARGET@\n<script src="https://makecode.com/gh-pages-embed.js"><\/script><script>makeCodeRender("{{ site.makecode.home_url }}", "{{ site.github.owner_name }}/{{ site.github.repository_name }}");<\/script>\n`,".gitignore":"# MakeCode\nbuilt\nnode_modules\nyotta_modules\nyotta_targets\npxt_modules\n.pxt\n_site\n*.db\n*.tgz\n.header.json\n.simstate.json\n",".vscode/settings.json":'{\n "editor.formatOnType": true,\n "files.autoSave": "afterDelay",\n "files.watcherExclude": {\n "**/.git/objects/**": true,\n "**/built/**": true,\n "**/node_modules/**": true,\n "**/yotta_modules/**": true,\n "**/yotta_targets": true,\n "**/pxt_modules/**": true,\n "**/.pxt/**": true\n },\n "files.associations": {\n "*.blocks": "html",\n "*.jres": "json"\n },\n "search.exclude": {\n "**/built": true,\n "**/node_modules": true,\n "**/yotta_modules": true,\n "**/yotta_targets": true,\n "**/pxt_modules": true,\n "**/.pxt": true\n },\n "files.exclude": {\n "**/pxt_modules": true,\n "**/.pxt": true\n }\n}',".vscode/extensions.json":'{\n "recommendations": ["ms-edu.pxt-vscode-web"]\n}'},n=i();return n&&Object.keys(n).forEach(t=>e[t]=n[t]),e}function i(){const t=e.appTarget.bundledpkgs[e.template.TEMPLATE_PRJ];if(t){const n=e.Util.clone(t);return delete n[e.CONFIG_NAME],n}}t.TS_CONFIG='{\n "compilerOptions": {\n "target": "ES5",\n "noImplicitAny": true,\n "outDir": "built",\n "rootDir": "."\n },\n "exclude": ["pxt_modules/**/*test.ts"]\n}\n',t.defaultFiles=n,t.targetTemplateFiles=i,t.TEMPLATE_PRJ="template",t.packageFiles=function(t){const i=e.appTarget.blocksprj||e.appTarget.tsprj,s=e.U.clone(i.config);delete s.installedVersion,delete s.additionalFilePath,delete s.additionalFilePaths,s.preferredEditor=s.files.find(e=>/\.blocks$/.test(e))?e.BLOCKS_PROJECT_NAME:e.JAVASCRIPT_PROJECT_NAME,s.name=t,s.public=!0,s.version||(s.version="0.0.0");const r={},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 m;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(")")])}}(m=t.Helpers||(t.Helpers={})),t.H=m;const g={"=":3,"+=":3,"-=":3,"?":4,":":4,"||":5,"&&":6,"|":7,"^":8,"&":9,"==":10,"!=":10,"===":10,"!==":10,"<":11,">":11,"<=":11,">=":11,">>":12,">>>":12,"<<":12,"+":13,"-":13,"*":14,"/":14,"%":14,"**":15,"!":16,"~":16,"P-":16,"P+":16,"++":16,"--":16,".":18};function b(t){let s=[],r={},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(g,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 m(" {\n\t\n}"+n);let i=e.U.clone(l[l.length-1]||{});l.push(i),o+=" "," "!=a[a.length-1]&&m(" ");m("{\n");for(let e of t.children)f(e);o=o.slice(4),b(),m("\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,g=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,g)}else{const e={id:t.id,startLine:d,startPos:h,endLine:p,endPos:g};r[t.id]=e,s.push(e)}}function m(e){u(e.replace(/\n/g,"\n"+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){var t;!function(n){const i=[".","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];n.BLOCKLY_TILESET_TYPE="BLOCKLY_TILESET_TYPE",n.TILE_PREFIX="tile",n.TILE_NAMESPACE="myTiles",n.IMAGES_NAMESPACE="myImages",n.IMAGE_PREFIX="image",n.ANIMATION_NAMESPACE="myAnimations",n.ANIMATION_PREFIX="anim",n.SONG_NAMESPACE="mySongs",n.JSON_NAMESPACE="myFiles",n.SONG_PREFIX="song",n.JSON_PREFIX="file";class s{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 s(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,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}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 p(this,e,t)}coordToIndex(e,t){return e+t*this.width}getCore(e){const t=Math.floor(e/2);return e%2==0?15&this.buf[t]:(240&this.buf[t])>>4}setCore(e,t){const n=Math.floor(e/2);this.buf[n]=e%2==0?240&this.buf[n]|15&t:15&this.buf[n]|(15&t)<<4}dataLength(){return Math.ceil(this.width*this.height/2)}}n.Bitmap=s;class r extends s{static fromData(e){return new r(e.width,e.height,e.x0,e.y0,e.data)}copy(e=0,t=0,n=this.width,i=this.height){const s=new r(n,i);s.x0=e,s.y0=t;for(let r=0;r<n;r++)for(let n=0;n<i;n++)s.set(r,n,this.get(e+r,t+n));return s}resize(e,t){return f(this,e,t)}getCore(e){return this.buf[e]}setCore(e,t){this.buf[e]=t}dataLength(){return this.width*this.height}}n.Tilemap=r;class a{constructor(e,t,n){this.tilemap=e,this.tileset=t,this.layers=n,this.nextId=0}cloneData(e=!1){var t,n,i,r;const o=this.tilemap.copy(),l={tileWidth:this.tileset.tileWidth,tiles:this.tileset.tiles.map(e=>Object.assign(Object.assign({},e),{bitmap:s.fromData(e.bitmap).copy().data()}))},c=s.fromData(this.layers).copy().data(),u=new a(o,l,c);return e&&(u.nextId=this.nextId,u.projectReferences=null===(t=this.projectReferences)||void 0===t?void 0:t.slice(),u.tileOrder=null===(n=this.tileOrder)||void 0===n?void 0:n.slice(),u.editedTiles=null===(i=this.editedTiles)||void 0===i?void 0:i.slice(),u.deletedTiles=null===(r=this.deletedTiles)||void 0===r?void 0:r.slice()),u}equals(e){return this.tilemap.equals(e.tilemap)&&w(this.tileset,e.tileset)&&v(this.layers,e.layers)}}n.TilemapData=a;function o(e){return l(atob(e.slice(e.indexOf(",")+1)))}function l(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 c(e,t){!(e=(e=(e=e.replace(/[ `]|(?:`)|(?:	)|(?:hex)/g,"").trim()).replace(/^["`\(\)]*/,"").replace(/["`\(\)]*$/,"")).replace(/ /g,"\n"))&&t&&(e=t);const n=parseInt(e.substr(0,2),16)|parseInt(e.substr(2,2),16)<<8,i=parseInt(e.substr(4,2),16)|parseInt(e.substr(6,2),16)<<8,s=T(e.substring(8));return r.fromData({width:n,height:i,x0:0,y0:0,data:s})}function u(e){return`${h(e.width,2)}${h(e.height,2)}${x(e.data().data)}`}function d(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=m(e);return t.createNewTile(n.data())}switch(e){case"myTiles.tile0":case"myTiles.transparency16":return t.getTransparency(16);case"myTiles.transparency8":return t.getTransparency(8);case"myTiles.transparency4":return t.getTransparency(4);case"myTiles.transparency32":return t.getTransparency(32);default:return t.resolveTile(e)}}(e,t)):[]}function h(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 p(e,t,n){const i=new s(t,n);return i.apply(e),i}function f(e,t,n){const i=new r(t,n);return i.apply(e),i}function m(e,t="img"){const n=(e=(e=(e=(e=e.replace(/[ `]|(?:`)|(?:	)|(?:img)/g,"").trim()).replaceAll(t,"")).replace(/^["`\(\)]*/,"").replace(/["`\(\)]*$/,"")).replace(/ /g,"\n")).split("\n"),i=[];let r=0;for(let e=0;e<n.length;e++){const t=n[e],s=[];for(let e=0;e<t.length;e++)switch(t[e]){case"0":case".":s.push(0);break;case"1":case"#":s.push(1);break;case"2":case"T":s.push(2);break;case"3":case"t":s.push(3);break;case"4":case"N":s.push(4);break;case"5":case"n":s.push(5);break;case"6":case"G":s.push(6);break;case"7":case"g":s.push(7);break;case"8":s.push(8);break;case"9":s.push(9);break;case"a":case"A":case"R":s.push(10);break;case"b":case"B":case"P":s.push(11);break;case"c":case"C":case"p":s.push(12);break;case"d":case"D":case"O":s.push(13);break;case"e":case"E":case"Y":s.push(14);break;case"f":case"F":case"W":s.push(15);break;default:if(!/\s/.test(t[e]))return}s.length&&(i.push(s),r=Math.max(r,s.length))}const a=i.length,o=new s(r,a);for(let e=0;e<a;e++){const t=i[e];for(let n=0;n<r;n++)n<t.length?o.set(n,e,t[n]):o.set(n,e,0)}return o}function g(e,t="img"){let n="";if("python"===e)n=`${t}("""`;else n=`${t}\``;return n}function b(e){let t="";if("python"===e)t+='""")';else t+="`";return t}function y(e,t,n="img"){if(!e||0===e.height||0===e.width)return"";let s=g(t,n);if(e){const t=e.width*e.height>300?"":" ";for(let n=0;n<e.height;n++){s+="\n";for(let r=0;r<e.width;r++)s+=i[e.get(r,n)]+t}}return s+="\n",s+=b(t),s}function v(t,n){return t===n||!(!t&&n||!n&&t)&&e.sprite.Bitmap.fromData(t).equals(e.sprite.Bitmap.fromData(n))}function w(t,n){return t.tileWidth===n.tileWidth&&e.U.arrayEquals(t.tiles,n.tiles,e.assetEquals)}function A(e){switch(e){case 4:return"TileScale.Four";case 8:return"TileScale.Eight";case 16:return"TileScale.Sixteen";case 32:return"TileScale.ThirtyTwo";default:return Math.floor(Math.log2(e)).toString()}}function k(e){switch(e=e.replace(/\s/g,"")){case"TileScale.Four":return 4;case"TileScale.Eight":return 8;case"TileScale.Sixteen":return 16;case"TileScale.ThirtyTwo":return 32;default:return Math.pow(2,parseInt(e))}}function T(e){let t=new Uint8ClampedArray(e.length>>1);for(let n=0;n<e.length;n+=2)t[n>>1]=parseInt(e.slice(n,n+2),16);return t}function x(e){const t="0123456789abcdef";let n="";for(let i=0;i<e.length;++i)n+=t[e[i]>>4],n+=t[15&e[i]];return n}function E(e,t,n){e[t]=255&n,e[t+1]=n>>8&255}function C(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[I(t),S(t),N(t)]}function I(e){return e>>16&255}function S(e){return e>>8&255}function N(e){return 255&e}n.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}},n.encodeTilemap=function(e,t,n){return e?`tiles.createTilemap(${function(e){return e?`hex\`${u(e)}\``:"hex``"}(e.tilemap)}, ${y(s.fromData(e.layers),t)}, [${e.tileset.tiles.map(e=>function(e,t,n){if(n&&n[e.id])return n[e.id];return e.id}(e,0,n))}], ${A(e.tileset.tileWidth)})`:"null"},n.decodeTilemap=function(t,n,i){if(!(t=e.Util.htmlUnescape(t).trim()).trim()||-1===t.indexOf("("))return null;const s=(t=(t=t.substr(t.indexOf("(")+1)).substr(0,t.lastIndexOf(")"))).substr(0,t.indexOf(",")),r=(t=t.substr(s.length+1)).substr(0,t.indexOf(",")),o=(t=t.substr(r.length+1)).substr(0,t.lastIndexOf("]")+1),l=t=t.substr(o.length+1);return new a(c(s),{tiles:d(o,i),tileWidth:k(l)},m(r).data())},n.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},n.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},n.computeAverageColor=function(e,t){const n=t.map(C),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"},n.getBitmap=function(e,t){const n=e.apis.byQName[t];return n?o(n.attributes.jresURL):null},n.getBitmapFromJResURL=o,n.hexToBitmap=l,n.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})},n.getGalleryItems=function(t,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))}(t.apis,i);return s=s.filter(e=>e.namespace!=n.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}})},n.base64EncodeBitmap=function(t){const n=s.fromData(t),i=pxtc.f4EncodeImg(t.width,t.height,4,(e,t)=>n.get(e,t));return btoa(e.U.uint8ArrayToString(T(i)))},n.tilemapLiteralToTilemap=c,n.hexEncodeTilemap=u,n.formatByte=h,n.resizeBitmap=p,n.resizeTilemap=f,n.imageLiteralToBitmap=m,n.encodeAnimationString=function(t,n){const i=t.map(e=>e.data),s=new Uint8ClampedArray(8+i[0].length*i.length);E(s,0,n),E(s,2,t[0].width),E(s,4,t[0].height),E(s,6,t.length);let r=8;return i.forEach(e=>{s.set(e,r),r+=e.length}),btoa(e.sprite.uint8ArrayToHex(s))},n.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)},n.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)},n.isTilemapEmptyOrUnused=function(e,n,i){const s=t.Bitmap.fromData(e.data.layers);for(let t=0;t<e.data.tilemap.width;t++)for(let n=0;n<e.data.tilemap.height;n++)if(e.data.tilemap.get(t,n)||s.get(t,n))return!1;return!n.isAssetUsed(e,i)},n.imageLiteralFromDimensions=function(e,t,n,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+=i[n]+a}return r+="\n",r+=b(s),r},n.bitmapToImageLiteral=y,n.bitmapEquals=v,n.tilesetEquals=w,n.tileWidthToTileScale=A,n.tileScaleToTileWidth=k,n.hexToUint8Array=T,n.uint8ArrayToHex=x,n.colorStringToRGB=C}(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,this.type="localstorage"}targetKey(e){return this.storageId+"/"+e}removeItem(e){window.localStorage.removeItem(this.targetKey(e))}getItem(e){return window.localStorage[this.targetKey(e)]}setItem(e,t){window.localStorage[this.targetKey(e)]=t}clear(){let e=this.targetKey(""),t=[];for(let n=0;n<window.localStorage.length;++n){let i=window.localStorage.key(n);0==i.indexOf(e)&&t.push(i)}t.forEach(e=>window.localStorage.removeItem(e))}}function s(){if(e.appTarget)return e.appTarget.id;const t=window.pxtConfig;if(t)return t.targetId;const n=window.pxtTargetBundle;return n?n.id:""}let r;function a(){if(r)return;const t=s();let a=!1;if(!e.shell.isSandboxMode())try{const n=e.Util.guidGen();window.localStorage[t]=n;a=window.localStorage[t]===n}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});if(204===i.statusCode)throw new Error(`Missing ${r} not available in ${t}`);return i.json?i.json:i.text?i.text:void 0}{const n=e.storage.getLocal(`${t}:${r}`),i=e.Util.jsonTryParse(n);return i||n}},t.setAsync=async function(t,r,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){function t(e){let t=0;for(let n=0;n<e.length;n++)if(" "===e.charAt(n))t++;else{if("\t"!==e.charAt(n))return t;t+=4}return 0}e.getSectionsFromMarkdownMetadata=function(e){const n=e.split(/\r?\n/);let i=[],s=null,r=null,a=null,o=[],l=0,c=null;for(const e of n)if(e.trim()){if(e.startsWith("```")){if(c){s&&(s.codeBlocks?s.codeBlocks.push(c):s.codeBlocks=[c]),c=null;continue}{const t=/^```([a-zA-Z_\-]*)$/.exec(e);if(t){c={content:"",languageCode:t[1]};continue}}}else c&&(c.content+=e+"\n");if(e.startsWith("#")){const t=/^(#+)\s*(.+)$/.exec(e);if(t){u(),s={headerKind:1===t[1].length?"single":2===t[1].length?"double":"triple",header:t[2],attributes:{}},r=null,a=null,l=0;continue}}if(s){const n=t(e),i=e.trim(),c=/^[*-]\s+(?:([^:]+):)?(.*)$/.exec(i);if(!c)continue;if(Math.abs(n-l)>1&&r){if(n>l){const e={key:r,items:[]};o.length?o[o.length-1].items.push(e):(s.listAttributes||(s.listAttributes={}),s.listAttributes[r]=e),r=null,o.push(e)}else{const e=o.pop();r&&a&&(null==e||e.items.push((r+":"+a).trim()),a=null)}l=n}c&&(c[1]?(r&&a&&(o.length?o[o.length-1].items.push((r+":"+a).trim()):s.attributes[r]=a.trim()),r=c[1].trim().toLowerCase(),a=c[2]):r&&(a+=c[2]))}}else a&&(a+="\n");return u(),i;function u(){s&&(r&&a&&(o.length?o[o.length-1].items.push((r+":"+a).trim()):s.attributes[r]=a.trim()),i.push(s)),o=[]}}}(pxt||(pxt={})),function(e){!function(t){let n;!function(e){e[e.PROD=0]="PROD",e[e.STAGING=1]="STAGING",e[e.LOCAL=2]="LOCAL"}(n||(n={}));let i=n.STAGING;t.ABSOLUTE_LINKS={PROD_BETA:"https://arcade.makecode.com/beta--multiplayer",STAGING_BETA:"https://arcade.staging.pxt.io/beta--multiplayer",LOCAL:"http://localhost:3000"},t.RELATIVE_LINKS={PROD:"/--multiplayer",BETA:"/beta--multiplayer"},t.SHORT_LINKS={PROD:"https://aka.ms/a9",PROD_BETA:"https://aka.ms/a9b",STAGING:"https://aka.ms/a9s",STAGING_BETA:"https://aka.ms/a9sb"},t.RELATIVE_LINK=()=>{if(e.BrowserUtils.isLocalHostDev())switch(i){case n.PROD:return t.ABSOLUTE_LINKS.PROD_BETA;case n.STAGING:return t.ABSOLUTE_LINKS.STAGING_BETA;case n.LOCAL:return t.ABSOLUTE_LINKS.LOCAL}return window.location.pathname.startsWith("/beta")?t.RELATIVE_LINKS.BETA:t.RELATIVE_LINKS.PROD},t.SHORT_LINK=()=>{if(e.BrowserUtils.isLocalHostDev())switch(i){case n.PROD:return t.SHORT_LINKS.PROD_BETA;case n.STAGING:return t.SHORT_LINKS.STAGING_BETA;case n.LOCAL:return t.ABSOLUTE_LINKS.LOCAL}return window.location.host.endsWith(".staging.pxt.io")?window.location.pathname.startsWith("/beta")?t.SHORT_LINKS.STAGING_BETA:t.SHORT_LINKS.STAGING:window.location.pathname.startsWith("/beta")?t.SHORT_LINKS.PROD_BETA:t.SHORT_LINKS.PROD},t.makeHostLink=function(e,n){return`${n?t.SHORT_LINK():t.RELATIVE_LINK()}?host=${encodeURIComponent(e)}`},t.makeJoinLink=function(e,n){return`${n?t.SHORT_LINK():t.RELATIVE_LINK()}?join=${encodeURIComponent(e)}`}}(e.multiplayer||(e.multiplayer={}))}(pxt||(pxt={})),function(e){!function(t){!function(t){function n(e,t,n){const i=new Uint8Array(2);new Uint16Array(i.buffer)[0]=0|n,e[t]=i[0],e[t+1]=i[1]}function i(e,t){const n=new Uint8Array(2);return n[0]=e[t],n[1]=e[t+1],new Uint16Array(n.buffer)[0]}function s(e){const t=new Uint8Array(5+7*e.steps.length);t[0]=e.steps.length,n(t,1,e.startFrequency),n(t,3,e.startVolume);for(let i=0;i<e.steps.length;i++){const s=5+7*i;t[s]=e.steps[i].waveform,n(t,s+1,e.steps[i].frequency),n(t,s+3,e.steps[i].volume),n(t,s+5,e.steps[i].duration)}return t}function r(e,t,i){const s=new Uint8Array(5+e.notes.length);n(s,0,e.startTick),n(s,2,e.endTick),s[4]=e.notes.length;for(let n=0;n<e.notes.length;n++)s[5+n]=a(e.notes[n],t,i);return s}function a(e,t,n){if(n)return e.note;let i=0;return"flat"===e.enharmonicSpelling?i=1:"sharp"===e.enharmonicSpelling&&(i=2),e.note-12*(t-2)|i<<6}function o(e){return e.drums?function(e){const t=e.drums.map(s),i=t.reduce((e,t)=>t.length+e,0),a=e.notes.map(e=>r(e,0,!0)),o=a.reduce((e,t)=>t.length+e,0),l=new Uint8Array(6+i+o);l[0]=e.id,l[1]=1,n(l,2,i);let c=4;for(const e of t)l.set(e,c),c+=e.length;n(l,c,o),c+=2;for(const e of a)l.set(e,c),c+=e.length;return l}(e):function(e){const t=function(e){var t,i,s,r,a,o,l,c,u;const d=new Uint8Array(28);return d[0]=e.waveform,n(d,1,e.ampEnvelope.attack),n(d,3,e.ampEnvelope.decay),n(d,5,e.ampEnvelope.sustain),n(d,7,e.ampEnvelope.release),n(d,9,e.ampEnvelope.amplitude),n(d,11,(null===(t=e.pitchEnvelope)||void 0===t?void 0:t.attack)||0),n(d,13,(null===(i=e.pitchEnvelope)||void 0===i?void 0:i.decay)||0),n(d,15,(null===(s=e.pitchEnvelope)||void 0===s?void 0:s.sustain)||0),n(d,17,(null===(r=e.pitchEnvelope)||void 0===r?void 0:r.release)||0),n(d,19,(null===(a=e.pitchEnvelope)||void 0===a?void 0:a.amplitude)||0),d[21]=(null===(o=e.ampLFO)||void 0===o?void 0:o.frequency)||0,n(d,22,(null===(l=e.ampLFO)||void 0===l?void 0:l.amplitude)||0),d[24]=(null===(c=e.pitchLFO)||void 0===c?void 0:c.frequency)||0,n(d,25,(null===(u=e.pitchLFO)||void 0===u?void 0:u.amplitude)||0),d[27]=e.octave,d}(e.instrument),i=e.notes.map(t=>r(t,e.instrument.octave,!1)),s=i.reduce((e,t)=>t.length+e,0),a=new Uint8Array(6+t.length+s);a[0]=e.id,a[1]=0,n(a,2,t.length);let o=4;a.set(t,o),o+=t.length,n(a,o,s),o+=2;for(const e of i)a.set(e,o),o+=e.length;return a}(e)}function l(e,t){return{waveform:e[t],ampEnvelope:{attack:i(e,t+1),decay:i(e,t+3),sustain:i(e,t+5),release:i(e,t+7),amplitude:i(e,t+9)},pitchEnvelope:{attack:i(e,t+11),decay:i(e,t+13),sustain:i(e,t+15),release:i(e,t+17),amplitude:i(e,t+19)},ampLFO:{frequency:e[t+21],amplitude:i(e,22)},pitchLFO:{frequency:e[t+24],amplitude:i(e,25)},octave:e[t+27]}}function c(e,t){return e[t+1]?function(e,t){const n={id:e[t],instrument:{ampEnvelope:{attack:0,decay:0,sustain:0,release:0,amplitude:0},waveform:0},notes:[],drums:[]},s=i(e,t+2);let r=t+4;for(;r<t+4+s;)n.drums.push(u(e,r)),r+=5+7*n.drums[n.drums.length-1].steps.length;const a=i(e,r);r+=2;for(;r<t+4+s+a;)n.notes.push(d(e,r,0,!0)),r+=5+n.notes[n.notes.length-1].notes.length;return[n,r]}(e,t):function(e,t){const n={id:e[t],instrument:l(e,t+4),notes:[]},s=t+4+i(e,t+2),r=i(e,s);let a=s+2;for(;a<s+2+r;)n.notes.push(d(e,a,n.instrument.octave,!1)),a+=5+n.notes[n.notes.length-1].notes.length;return[n,a]}(e,t)}function u(e,t){const n={startFrequency:i(e,t+1),startVolume:i(e,t+3),steps:[]};for(let s=0;s<e[t];s++){const r=t+5+7*s;n.steps.push({waveform:e[r],frequency:i(e,r+1),volume:i(e,r+3),duration:i(e,r+5)})}return n}function d(e,t,n,s){const r={startTick:i(e,t),endTick:i(e,t+2),notes:[]};for(let i=0;i<e[t+4];i++)r.notes.push(h(e[t+5+i],n,s));return r}function h(e,t,n){const i=e>>6,s={note:n?e:(63&e)+12*(t-2),enharmonicSpelling:"normal"};return 1===i?s.enharmonicSpelling="flat":2===i&&(s.enharmonicSpelling="sharp"),s}function p(e,t){if(typeof e!=typeof t)return!1;if("object"!=typeof e)return e===t;if(Array.isArray(e)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!p(e[n],t[n]))return!1;return!0}const n=Object.keys(e),i=Object.keys(t);if(n.length!==i.length)return!1;for(const s of n){if(-1===i.indexOf(s))return!1;if(!p(e[s],t[s]))return!1}return!0}function f(e){return{ticksPerBeat:8,beatsPerMeasure:4,beatsPerMinute:120,measures:e,tracks:[{id:0,name:lf("Dog"),notes:[],iconURI:"music-editor/dog.png",instrument:{waveform:1,octave:4,ampEnvelope:{attack:10,decay:100,sustain:500,release:100,amplitude:1024},pitchLFO:{frequency:5,amplitude:0}}},{id:1,name:lf("Duck"),notes:[],iconURI:"music-editor/duck.png",instrument:{waveform:15,octave:4,ampEnvelope:{attack:5,decay:530,sustain:705,release:450,amplitude:1024},pitchEnvelope:{attack:5,decay:40,sustain:0,release:100,amplitude:40},ampLFO:{frequency:3,amplitude:20},pitchLFO:{frequency:6,amplitude:2}}},{id:2,name:lf("Cat"),notes:[],iconURI:"music-editor/cat.png",instrument:{waveform:12,octave:5,ampEnvelope:{attack:150,decay:100,sustain:365,release:400,amplitude:1024},pitchEnvelope:{attack:120,decay:300,sustain:0,release:100,amplitude:50},pitchLFO:{frequency:10,amplitude:6}}},{id:3,name:lf("Fish"),notes:[],iconURI:"music-editor/fish.png",instrument:{waveform:1,octave:3,ampEnvelope:{attack:220,decay:105,sustain:1024,release:350,amplitude:1024},ampLFO:{frequency:5,amplitude:100},pitchLFO:{frequency:1,amplitude:4}}},{id:4,name:lf("Car"),notes:[],iconURI:"music-editor/car.png",instrument:{waveform:16,octave:4,ampEnvelope:{attack:5,decay:100,sustain:1024,release:30,amplitude:1024},pitchLFO:{frequency:10,amplitude:4}}},{id:5,name:lf("Computer"),notes:[],iconURI:"music-editor/computer.png",instrument:{waveform:15,octave:2,ampEnvelope:{attack:10,decay:100,sustain:500,release:10,amplitude:1024}}},{id:6,name:lf("Burger"),notes:[],iconURI:"music-editor/burger.png",instrument:{waveform:1,octave:2,ampEnvelope:{attack:10,decay:100,sustain:500,release:100,amplitude:1024}}},{id:7,name:lf("Cherry"),notes:[],iconURI:"music-editor/cherry.png",instrument:{waveform:2,octave:3,ampEnvelope:{attack:10,decay:100,sustain:500,release:100,amplitude:1024}}},{id:8,name:lf("Lemon"),notes:[],iconURI:"music-editor/lemon.png",instrument:{waveform:14,octave:2,ampEnvelope:{attack:5,decay:70,sustain:870,release:50,amplitude:1024},pitchEnvelope:{attack:10,decay:45,sustain:0,release:100,amplitude:20},ampLFO:{frequency:1,amplitude:50},pitchLFO:{frequency:2,amplitude:1}}},{id:9,name:lf("Drums"),notes:[],iconURI:"music-editor/explosion.png",instrument:{waveform:11,octave:4,ampEnvelope:{attack:10,decay:100,sustain:500,release:100,amplitude:1024}},drums:[{startFrequency:100,startVolume:1024,steps:[{waveform:3,frequency:120,duration:10,volume:1024},{waveform:3,frequency:1,duration:100,volume:0}]},{startFrequency:200,startVolume:1024,steps:[{frequency:0,volume:0,duration:100,waveform:1}]},{startFrequency:100,startVolume:1024,steps:[{frequency:0,volume:0,duration:250,waveform:1}]},{startFrequency:175,startVolume:1024,steps:[{waveform:1,frequency:200,duration:10,volume:1024},{waveform:1,frequency:150,duration:20,volume:1024},{waveform:5,frequency:1,duration:20,volume:100},{waveform:5,frequency:1,duration:300,volume:0}]},{startFrequency:220,startVolume:1024,steps:[{waveform:1,frequency:250,duration:10,volume:1024},{waveform:1,frequency:200,duration:20,volume:1024},{waveform:5,frequency:2e3,duration:20,volume:100},{waveform:5,frequency:2e3,duration:200,volume:0}]},{startFrequency:400,startVolume:500,steps:[{frequency:450,volume:500,duration:10,waveform:5},{frequency:400,volume:20,duration:20,waveform:5}]},{startFrequency:400,startVolume:0,steps:[{frequency:450,volume:500,duration:5,waveform:5},{frequency:900,volume:5,duration:50,waveform:5},{frequency:900,volume:0,duration:250,waveform:5}]},{startFrequency:400,startVolume:0,steps:[{frequency:450,volume:500,duration:5,waveform:5},{frequency:900,volume:200,duration:50,waveform:5},{frequency:900,volume:5,duration:100,waveform:5},{frequency:900,volume:0,duration:400,waveform:5}]},{startFrequency:400,startVolume:0,steps:[{frequency:450,volume:500,duration:5,waveform:5},{frequency:900,volume:200,duration:100,waveform:5},{frequency:900,volume:5,duration:200,waveform:5},{frequency:900,volume:0,duration:500,waveform:5}]},{startFrequency:3500,startVolume:1024,steps:[{frequency:4e3,volume:0,duration:10,waveform:4},{frequency:3500,volume:800,duration:1,waveform:4},{frequency:4e3,volume:0,duration:40,waveform:4},{frequency:3500,volume:400,duration:1,waveform:4},{frequency:4e3,volume:0,duration:40,waveform:4}]},{startFrequency:2e3,startVolume:1024,steps:[{frequency:1800,volume:15,duration:100,waveform:4},{frequency:1800,volume:0,duration:200,waveform:4}]},{startFrequency:200,startVolume:200,steps:[{frequency:125,volume:200,duration:25,waveform:14},{frequency:100,volume:15,duration:50,waveform:14},{frequency:120,volume:0,duration:250,waveform:14}]},{startFrequency:300,startVolume:200,steps:[{frequency:225,volume:200,duration:25,waveform:14},{frequency:200,volume:15,duration:50,waveform:14},{frequency:220,volume:0,duration:250,waveform:14}]},{startFrequency:500,startVolume:200,steps:[{frequency:425,volume:200,duration:25,waveform:14},{frequency:400,volume:15,duration:50,waveform:14},{frequency:420,volume:0,duration:250,waveform:14}]},{startFrequency:200,startVolume:1024,steps:[{frequency:75,volume:0,duration:200,waveform:1}]},{startFrequency:300,startVolume:1024,steps:[{frequency:200,volume:0,duration:200,waveform:1}]},{startFrequency:400,startVolume:1024,steps:[{frequency:300,volume:0,duration:200,waveform:1}]},{startFrequency:200,startVolume:1024,steps:[{frequency:200,volume:15,duration:100,waveform:4},{frequency:150,volume:0,duration:200,waveform:4}]},{startFrequency:450,startVolume:1024,steps:[{frequency:350,volume:15,duration:100,waveform:4},{frequency:300,volume:0,duration:100,waveform:4}]},{startFrequency:2500,startVolume:1024,steps:[{frequency:2500,volume:100,duration:150,waveform:4},{frequency:2550,volume:0,duration:500,waveform:4}]},{startFrequency:3e3,startVolume:1024,steps:[{frequency:3e3,volume:100,duration:300,waveform:4},{frequency:3060,volume:0,duration:500,waveform:4}]},{startFrequency:800,startVolume:0,steps:[{frequency:800,volume:1024,duration:10,waveform:4},{frequency:800,volume:0,duration:490,waveform:4}]},{startFrequency:400,startVolume:0,steps:[{frequency:400,volume:1024,duration:10,waveform:4},{frequency:400,volume:0,duration:400,waveform:4}]},{startFrequency:2e3,startVolume:1024,steps:[{frequency:2e3,volume:100,duration:150,waveform:16},{frequency:2e3,volume:0,duration:200,waveform:16}]}]}]}}t.encodeSongToHex=function(t){const i=function(e){const t=e.tracks.filter(e=>e.notes.length>0).map(o),i=t.reduce((e,t)=>t.length+e,0),s=new Uint8Array(7+i);s[0]=0,n(s,1,e.beatsPerMinute),s[3]=e.beatsPerMeasure,s[4]=e.ticksPerBeat,s[5]=e.measures,s[6]=t.length;let r=7;for(const e of t)s.set(e,r),r+=e.length;return s}(t);return e.U.toHex(i)},t.decodeSongFromHex=function(t){return function(e){const t={beatsPerMinute:i(e,1),beatsPerMeasure:e[3],ticksPerBeat:e[4],measures:e[5],tracks:[]};let n=7;for(;n<e.length;){const[i,s]=c(e,n);n=s,t.tracks.push(i)}return t}(e.U.fromHex(t))},t.cloneSong=function(e){return Object.assign(Object.assign({},e),{tracks:e.tracks.map(e=>Object.assign(Object.assign({},e),{instrument:e.instrument&&Object.assign(Object.assign({},e.instrument),{ampEnvelope:Object.assign({},e.instrument.ampEnvelope),pitchEnvelope:e.instrument.pitchEnvelope&&Object.assign({},e.instrument.pitchEnvelope),ampLFO:e.instrument.ampLFO&&Object.assign({},e.instrument.ampLFO),pitchLFO:e.instrument.pitchLFO&&Object.assign({},e.instrument.pitchLFO)}),drums:e.drums&&e.drums.map(e=>Object.assign(Object.assign({},e),{steps:e.steps.map(e=>Object.assign({},e))})),notes:e.notes.map(e=>Object.assign(Object.assign({},e),{notes:e.notes.slice()}))}))})},t.songEquals=function(e,t){return p(e,t)},t.inflateSong=function(e){const t=f(1);e.tracks=t.tracks.map((t,n)=>{const i=e.tracks.find(e=>e.id===n);return i&&(t.notes=i.notes),t})},t.getSongInfo=function(e){return{ticksPerBeat:e.ticksPerBeat,beatsPerMeasure:e.beatsPerMeasure,beatsPerMinute:e.beatsPerMinute,measures:e.measures}},t.getEmptySong=f}(t.music||(t.music={}))}(e.assets||(e.assets={}))}(pxt||(pxt={})),function(e){const t=["name","version","description","license","dependencies","files","testFiles","testDependencies","fileDependencies","public","targetVersions","supportedTargets","preferredEditor","languageRestriction","additionalFilePath","additionalFilePaths"];class n{constructor(e,t,n,i,s){this.id=e,this._verspec=t,this.parent=n,this.depName=s,this.level=-1,this.isLoaded=!1,this.ignoreTests=!1,this.cppOnly=!1,i&&(this.level=i.level+1),this.addedBy=[i]}static stringifyConfig(e){const n=e,i={};for(const e of t)n.hasOwnProperty(e)&&(i[e]=n[e]);for(const e of Object.keys(n))i.hasOwnProperty(e)||(i[e]=n[e]);return JSON.stringify(i,null,4)+"\n"}static parseAndValidConfig(t){const n=e.Util.jsonTryParse(t);return n&&void 0!==n.name&&"string"==typeof n.name&&n.files&&Array.isArray(n.files)&&n.files.every(e=>"string"==typeof e)&&n.dependencies&&Object.keys(n.dependencies).every(e=>"string"==typeof n.dependencies[e])&&n}static async getConfigAsync(t,n,i){if(e.github.isGithubId(i)){const t=e.github.parseRepoId(i),n=await e.packagesConfigAsync();return await e.github.repoAsync(t.fullName,n)?await e.github.pkgConfigAsync(t.fullName,t.tag,n):null}if(i.startsWith("workspace:")){i.slice(10);return null}if(!i.startsWith("pub:")){const s=e.patching.upgradePackageReference(t,n,i),r=e.appTarget.bundledpkgs[s];return JSON.parse(r[e.CONFIG_NAME])}{const t=i.slice(4);try{const n=await e.Cloud.downloadScriptFilesAsync(t);return JSON.parse(n[e.CONFIG_NAME])}catch(t){return e.log(`Unable to fetch files for published script '${i}'`),null}}}static corePackages(){const t=e.appTarget.bundledpkgs;return Object.keys(t).map(n=>JSON.parse(t[n][e.CONFIG_NAME])).filter(e=>!!e)}disablesVariant(e){return this.config&&this.config.disablesVariants&&this.config.disablesVariants.indexOf(e)>=0}invalid(){return/^invalid:/.test(this.version())}version(){return this.resolvedVersion||this._verspec}verProtocol(){let e=this.version().split(":");return e.length>1?e[0]:""}verArgument(){let e=this.verProtocol();return e?this.version().slice(e.length+1):this.version()}targetVersion(){return this.parent&&this.parent!=this?this.parent.targetVersion():this.config.targetVersions?this.config.targetVersions.target:void 0}async commonDownloadAsync(){const t=this.verProtocol();let n;if("pub"==t)n=await e.Cloud.downloadScriptFilesAsync(this.verArgument());else if("github"==t){const t=await e.packagesConfigAsync();n=(await e.github.downloadPackageAsync(this.verArgument(),t)).files}else if("embed"==t)n=e.getEmbeddedScript(this.verArgument());else if("pkg"==t){const t=(this.parent||this).readFile(this.verArgument()),i=e.U.jsonTryParse(t);i||e.log(`unable to find ${this.verArgument()}`),n=i}return n}writeAssetPackFiles(){const t=JSON.parse(JSON.stringify(this.config));t.files=t.files.filter(e=>e.endsWith(".jres")),t.files.push("gallery.ts"),t.dependencies={},t.assetPack=!0,this.config=t,this.saveConfig();let n="";for(const i of t.files){const t=this.readFile(i),s=e.U.jsonTryParse(t);if(s){const[t,r]=e.emitGalleryDeclarations(s,this.getNamespaceName());this.writeFile(i,JSON.stringify(t,null,4)),n+=r}}this.writeFile("gallery.ts",n)}getNamespaceName(){let e=this,t=e.addedBy[0];const n=[];for(;t&&t!==e;)e.depName&&n.push(e.depName),e=t,t=e.addedBy[0];return n.reverse().map(e=>ts.pxtc.escapeIdentifier(e)).join(".")}host(){return this.parent._host}readFile(e){return this.host().readFile(this,e)}writeFile(e,t){this.host().writeFile(this,e,t,!0)}readGitJson(){const t=this.readFile(e.github.GIT_JSON);return e.Util.jsonTryParse(t)}resolveDep(e){return this.parent.deps.hasOwnProperty(e)?this.parent.deps[e]:null}saveConfig(){const t=e.U.clone(this.config);delete t.additionalFilePaths;const n=e.Package.stringifyConfig(t);this.host().writeFile(this,e.CONFIG_NAME,n)}setPreferredEditor(e){this.config.preferredEditor!=e&&(this.config.preferredEditor=e,this.saveConfig())}getPreferredEditor(){let t=this.config.preferredEditor;if(!t){if(!(this.getFiles().indexOf(e.MAIN_BLOCKS)>=0))return e.JAVASCRIPT_PROJECT_NAME;const t=this.readFile(e.MAIN_BLOCKS),n=this.readFile(e.MAIN_TS);return!t&&n?e.JAVASCRIPT_PROJECT_NAME:e.BLOCKS_PROJECT_NAME}return t}parseJRes(t={}){for(const n of this.getFiles())e.U.endsWith(n,".jres")&&i(JSON.parse(this.readFile(n)),t);return t}isAssetPack(){var e;return this.level>0&&!!(null===(e=this.config)||void 0===e?void 0:e.assetPack)}resolveVersionAsync(){var t;let n=this._verspec;if(e.getEmbeddedScript(this.id))this.resolvedVersion=n="embed:"+this.id;else if(n&&"*"!=n){if("github"==this.verProtocol()){const i=e.github.parseRepoId(this._verspec);if(i&&!i.tag&&this.parent){e.debug("dep: unbound github extensions, trying to resolve tag");const s=e.semver.sortLatestTags(e.Util.values((null===(t=this.parent)||void 0===t?void 0:t.deps)||{}).map(t=>e.github.parseRepoId(t.version())).filter(e=>(null==e?void 0:e.slug)===i.slug).map(e=>e.tag)),r=s[0];r&&(i.tag=r,this.resolvedVersion=n=e.github.stringifyRepo(i),e.debug(`dep: github patched ${this._verspec} to ${n}`))}}}else this.configureAsInvalidPackage(lf("version not specified for {0}",this.id)),n=this._verspec;return Promise.resolve(n)}downloadAsync(){return this.resolveVersionAsync().then(t=>{if(this.invalid())e.debug(`skip download of invalid package ${this.id}`);else if(/^embed:/.test(t)||this.installedVersion!=t)return e.debug("downloading "+t),this.host().downloadPackageAsync(this).then(()=>{this.loadConfig(),this.isAssetPack()&&this.writeAssetPackFiles(),e.debug(`installed ${this.id} /${t}`)})})}loadConfig(){if(0!=this.level&&this.invalid())return;const t=this.readFile(e.CONFIG_NAME);t||e.U.userError(`extension ${this.id} is missing ${e.CONFIG_NAME}`),this.parseConfig(t),0!=this.level&&(this.installedVersion=this.version()),this.saveConfig()}validateConfig(){this.config.dependencies||e.U.userError("Missing dependencies in config of: "+this.id),Array.isArray(this.config.files)||e.U.userError("Missing files in config of: "+this.id),"string"==typeof this.config.name&&this.config.name||(this.config.name=lf("Untitled")),this.config.targetVersions&&this.config.targetVersions.target&&this.config.targetVersions.targetId===e.appTarget.id&&e.appTarget.versions&&e.semver.majorCmp(this.config.targetVersions.target,e.appTarget.versions.target)>0&&e.U.userError(lf("{0} requires target version {1} (you are running {2})",this.config.name,this.config.targetVersions.target,e.appTarget.versions.target))}isPackageInUse(t,n=this.readFile(e.MAIN_TS)){let i=null;const s=e.patching.computePatches(this.targetVersion(),"missingPackage");return s&&s.forEach(e=>{Object.keys(e.map).forEach(n=>{e.map[n]===t&&(i=new RegExp(n,"g"))})}),i||(i=new RegExp(t+"\\.","g")),i.test(n)}upgradePackagesAsync(){return this.config||this.loadConfig(),e.packagesConfigAsync().then(async t=>{let n=0,i={};const s=[];return e.U.iterMap(this.config.dependencies,(r,a)=>{s.push((async()=>{if(e.github.isGithubId(a)){const s=await e.github.upgradedPackageReferenceAsync(t,a);s&&s!=a&&(e.log(`upgrading dep ${r}: ${a} -> ${s}`),i[a]=s,this.config.dependencies[r]=s,n++)}})())}),await Promise.all(s),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=>{var n;if(s=t,s){const t=s.yotta?e.U.jsonFlatten(s.yotta.config):null;this.parent.sortedDeps().forEach(n=>{if(s.core&&n.config.core&&s.name!=n.config.name){const t=new e.cpp.PkgConflictError(lf("conflict between core extensions {0} and {1}",s.name,n.id));return t.pkg0=n,void r.push(t)}let 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} (added: {1}, adding: {2})",n.id,n._verspec,i));t.pkg0=n,t.isVersionConflict=!0,r.push(t)}}})}return Object.keys(null!==(n=null==s?void 0:s.dependencies)&&void 0!==n?n:{}).reduce((e,t)=>e.then(()=>this.findConflictsAsync(t,s.dependencies[t])).then(e=>r.push.apply(r,e)),Promise.resolve())}).then(()=>{const t=e=>{const n=[];return e.addedBy.forEach(e=>{e.id!==this.id&&(n.push.apply(t(e)),n.push(e))}),n},n=[];return r.forEach(r=>{n.push.apply(n,t(r.pkg0).map(t=>{const n=new e.cpp.PkgConflictError(r.isVersionConflict?lf("a dependency of {0} has a version mismatch with extension {1} (added: {1}, adding: {2})",t.id,s.name,r.pkg0._verspec,i):lf("conflict on yotta setting {0} between extensions {1} and {2}",r.settingName,s.name,r.pkg0.id));return n.pkg0=t,n}))}),r.push.apply(r,n),r=r.filter((e,t)=>{for(let n=0;n<t;++n)if(e.pkg0.id===r[n].pkg0.id)return!1;return!0}),r})}configureAsInvalidPackage(t){e.log(`invalid package ${this.id}: ${t}`),this._verspec="invalid:"+this.id,this.config={name:this.id,description:t,dependencies:{},files:[]}}parseConfig(t,n){var i;try{const e=JSON.parse(t);this.config=e}catch(t){this.configureAsInvalidPackage(lf("Syntax error in pxt.json")),e.tickEvent("package.invalidConfigEncountered")}const s=JSON.stringify(this.config);(null===(i=this.config)||void 0===i?void 0:i.files)&&(this.config.files=this.config.files.filter(t=>t!==e.HISTORY_FILE&&t!==e.CONFIG_NAME&&"undefined"!==t&&"null"!==t&&!!t));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)!=s&&this.saveConfig(),this.validateConfig()}patchCorePackage(){e.Util.assert(e.appTarget.simulator&&e.appTarget.simulator.dynamicBoardDefinition),e.Util.assert(0==this.level);const t=Object.keys(this.config.dependencies).filter(t=>!!t&&(t==e.BLOCKS_PROJECT_NAME||t==e.JAVASCRIPT_PROJECT_NAME||JSON.parse((e.appTarget.bundledpkgs[t]||{})[e.CONFIG_NAME]||"{}").core));if(0==t.length){const t=e.Package.corePackages();t.length&&this.config.dependencies[t[0].name]}else t.length>1&&(t.pop(),t.forEach(t=>{e.log(`removing core package ${t}`),delete this.config.dependencies[t]}))}resolvedDependencies(){return Object.keys(this.dependencies()).map(e=>this.resolveDep(e))}dependencies(t=!1){if(!this.config)return{};const n=e.Util.clone(this.config.dependencies||{});return 0==this.level&&this.config.testDependencies&&e.Util.iterMap(this.config.testDependencies,(t,i)=>{("*"!=i||e.appTarget.bundledpkgs[t])&&(n[t]=i)}),t&&this.config.cppDependencies&&e.Util.jsonMergeFrom(n,this.config.cppDependencies),n}async loadAsync(t=!1,i){var s;if(this.isLoaded)return;0!=this.level||e.appTarget.multiVariants||e.setAppTargetVariant(null),this.isLoaded=!0;const r=this.readFile(e.CONFIG_NAME);if(null==r?t||e.U.userError("Package not installed: "+this.id+", did you forget to run `pxt install`?"):this.parseConfig(r),t||await this.upgradePackagesAsync(),t&&(await this.downloadAsync(),0!==this.level&&!this.isAssetPack()))for(const e of this.addedBy)if(null===(s=e.config.assetPacks)||void 0===s?void 0:s[this.id]){this.writeAssetPackFiles();break}if(t){const t=await this.upgradePackagesAsync();t&&(Object.keys(t).forEach(t=>e.tickEvent("package.doubleload",{extension:t})),e.log("upgraded, downloading again"),e.debug(t),await this.downloadAsync())}if(e.appTarget.simulator&&e.appTarget.simulator.dynamicBoardDefinition&&(0==this.level&&this.patchCorePackage(),this.config.compileServiceVariant&&e.setAppTargetVariant(this.config.compileServiceVariant),this.config.files.indexOf("board.json")>=0)){const t=e.appTarget.simulator.boardDefinition=JSON.parse(this.readFile("board.json"));t.id=this.config.name,e.appTarget.appTheme.boardName=t.boardName||lf("board"),e.appTarget.appTheme.driveDisplayName=t.driveDisplayName||lf("DRIVE");let n=t=>{let n=/^pkg:\/\/(.*)/.exec(t);if(n){let t=n[1],i=this.readFile(t);return e.U.toDataUri(i,e.U.getMime(t))}return t},i=e.appTarget.simulator.boardDefinition;if("object"==typeof i.visual){let e=i.visual;e.image=n(e.image),e.outlineImage=n(e.outlineImage)}}const 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=r.tag;if(a&&!o)return void e.debug(`unversioned ${n}, using ${a}`);const l=e.semver.strcmp(a,r.tag);if(0==l)return void e.debug(`resolved version are ${a}`);if(l>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);const c=e.github.parseRepoId(l);if(null==c?void 0:c.slug){const t=Object.values(s.parent.deps).map(t=>e.github.parseRepoId(t._verspec)).filter(e=>(null==e?void 0:e.slug)===c.slug).map(e=>e.tag).reduce((t,n)=>e.semver.strcmp(t,n)>0?t:n,"0.0.0");e.debug(`dep: common repo ${c.slug} version found ${t}`),e.semver.strcmp(t,"0.0.0")>0&&(!c.tag||e.semver.strcmp(t,c.tag)>0)&&(e.debug(`dep: upgrade from ${c.tag} to ${t}`),c.tag=t,l=e.github.stringifyRepo(c,!0))}let u=s.resolveDep(o);if(u){if(u.invalid()||u._verspec===l||a(u,l),u.invalid()){u.level=Math.min(u.level,s.level+1),u.addedBy.push(s);continue}r||(u.level=Math.min(u.level,s.level+1),u.addedBy.push(s))}else u=new n(o,l,s.parent,s,o),r&&(u.cppOnly=!0),s.parent.deps[o]=u,s.parent.deps[o.replace(/---.*/,"")]=u,await u.loadAsync(t)}};if(await o(null,this),this.patchAppTargetPalette(),this.config.screenSize&&e.appTarget.runtime&&(e.appTarget.runtime.screenSize=e.U.clone(this.config.screenSize)),0===this.level){const t=this.readFile(e.MAIN_TS);if(t){const n=this.getMissingPackages(this.config,t);let i=!1;for(const t of Object.keys(n)){const s=await this.findConflictsAsync(t,n[t]);if(s.length){const n=s.map(e=>e.pkg0.id).join(", "),i=s.map(e=>e.settingName).filter(e=>!!e).join(", ");e.log(`skipping missing package ${t} because it conflicts with the following packages: ${n} (conflicting settings: ${i})`)}else{e.log(`adding missing package ${t}`),i=!0,this.config.dependencies[t]="*";const s={};s[t]=n[t],await o(s,this)}}i&&(this.saveConfig(),this.validateConfig())}await Promise.all(e.U.values(this.parent.deps).map(e=>o(null,e,!0)))}e.debug(` installed ${this.id}`)}getFiles(){let t;t=0!=this.level||this.ignoreTests?this.config.files.slice(0):this.config.files.concat(this.config.testFiles||[]);const i=this.config.fileDependencies;return this.config.fileDependencies&&(t=t.filter(t=>{const s=i=>{if("!"==(i=i.trim())[0])return!s(i.slice(1));if(/^[\w-]+$/.test(i)){const e=this.parent.resolveDep(i);return!(!e||e.cppOnly)}const r=/^target:(\w+)$/.exec(i);return r?r[1]==e.appTarget.id||r[1]==e.appTarget.platformid:(n.depWarnings[i]||(n.depWarnings[i]=!0,e.log(`invalid dependency expression: ${i} in ${this.id}/${t}`)),!1)},r=e.U.lookup(i,t);return!r||!r.trim()||r.split("||").some(e=>e.split("&&").every(s))})),t}addSnapshot(t,n=[""]){for(let i of this.getFiles())n.some(t=>e.U.endsWith(i,t))&&(t[this.id+"/"+i]=this.readFile(i));t[this.id+"/"+e.CONFIG_NAME]=this.readFile(e.CONFIG_NAME)}packageLocalizationStringsAsync(t){const n=e.appTarget.id,i=[this.config.name+"-jsdoc",this.config.name],s={};e.appTarget.appTheme;return this.config.skipLocalization?Promise.resolve(s):e.Util.liveLocalizationEnabled()&&"this"!=this.id&&e.appTarget.bundledpkgs[this.id]?(e.debug(`loading live translations for ${this.id}`),Promise.all(i.map(i=>e.Util.downloadLiveTranslationsAsync(t,`${n}/${i}-strings.json`).then(n=>{n&&Object.keys(n).length?e.Util.jsonMergeFrom(s,n):(e.tickEvent("translations.livetranslationsfailed",{filename:i}),e.Util.jsonMergeFrom(s,this.bundledStringsForFile(t,i)))}).catch(r=>{e.tickEvent("translations.livetranslationsfailed",{filename:i}),e.log(`error while downloading ${n}/${i}-strings.json`),e.Util.jsonMergeFrom(s,this.bundledStringsForFile(t,i))}))).then(()=>s)):(i.map(e=>this.bundledStringsForFile(t,e)).filter(e=>!!e).forEach(t=>e.Util.jsonMergeFrom(s,t)),Promise.resolve(s))}bundledStringsForFile(t,n){let i={},[s,r,a]=e.Util.normalizeLanguageCode(t);const o=this.config.files;let l=`_locales/${s}/${n}-strings.json`;if(a&&-1===o.indexOf(l)&&(l=`_locales/${a}/${n}-strings.json`),r&&-1===o.indexOf(l)&&(l=`_locales/${r}/${n}-strings.json`),o.indexOf(l)>-1)try{i=JSON.parse(this.readFile(l))}catch(n){e.reportError("extension","Extension localization JSON failed to parse",{fileName:l,lang:t,extension:this.verArgument()});"github"===this.verProtocol()&&e.tickEvent("loc.errors.json",{repo:this.verArgument(),file:l})}return i}patchAppTargetPalette(){this.config.palette&&e.appTarget.runtime&&(e.appTarget.runtime.palette=e.U.clone(this.config.palette),this.config.paletteNames&&(e.appTarget.runtime.paletteNames=this.config.paletteNames))}}n.depWarnings={},e.Package=n;function i(e,t={}){let n=e["*"]||{};for(let i of Object.keys(e)){if("*"==i)continue;let s=e[i];"string"==typeof s&&(s={data:s});let r=s.namespace||n.namespace||"";r&&!r.endsWith(".")&&(r+=".");let 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,tags:s.tags}}return t}e.MainPackage=class extends n{constructor(e){super("this","file:.",null,null,null),this._host=e,this.deps={},this.parent=this,this.addedBy=[this],this.level=0,this.deps[this.id]=this}installAllAsync(e){return this.loadAsync(!0,e)}sortedDeps(t=!1){let n={},i=[];const s=e=>e.config?Object.keys(e.config.cppDependencies||{}).length:0,r=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()){var n;let i={sourceFiles:[],fileSystem:{},target:t,name:this.config?this.config.name:""};const s=(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))},r=e.appTarget.disabledVariants;let a=!1;const o=async n=>{const i={extinfo:null,target:null},r=e.appTargetVariant;let o;n&&e.setAppTargetVariant(n,{temporary:!0});try{i.target=e.appTarget.compile,o=e.cpp.getExtensionInfo(this),a||!o.shimsDTS&&!o.enumsDTS||(a=!0,o.shimsDTS&&s("shims.d.ts",o.shimsDTS),o.enumsDTS&&s("enums.d.ts",o.enumsDTS))}finally{n&&e.setAppTargetVariant(r,{temporary:!0})}o.appVariant=n;const l=t.isNative?await this.host().getHexInfoAsync(o):null;return o=e.U.flatClone(o),t.keepCppFiles||(delete o.compileData,delete o.generatedFiles,delete o.extensionFiles),o.hexinfo=l,i.extinfo=o,i};let l;await this.loadAsync(),i.bannedCategories=this.resolveBannedCategories(),e.debug(`building: ${this.sortedDeps().map(e=>{var t;return null===(t=e.config)||void 0===t?void 0:t.name}).join(", ")}`),e.appTarget.multiVariants?(l=e.appTargetVariant?[e.appTargetVariant]:e.appTarget.alwaysMultiVariant||e.appTarget.compile.switches.multiVariant?e.appTarget.multiVariants:[e.appTarget.multiVariants[0]],!e.appTarget.alwaysMultiVariant&&r&&(l=l.filter(e=>!r.includes(e)))):l=[null];let c=null;await Promise.all(l.map(async t=>{c&&e.debug(`building for ${t}`);const n=await o(t),s=n.extinfo;s.appVariant=t,s.outputPrefix=1!=l.length&&t?t+"-":"",(null==r?void 0:r.indexOf(t))>-1&&(s.disabledDeps=s.disabledDeps||"user-disabled"),c?i.otherMultiVariants.push(n):(n.target.isNative=i.target.isNative,i.target=n.target,c=s,i.otherMultiVariants=[])})),i.extinfo=c,i.target.preferredEditor=this.getPreferredEditor();if(!(e.appTarget.compile.shortPointers||"vm"==e.appTarget.compile.nativeType||this.config.binaryonly||!i.target.isNative)){const t=await this.filesToBePublishedAsync(!0),n=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(n+s);r&&(i.embedMeta=JSON.stringify({compression:"LZMA",headerSize:n.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}),i.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 n=t;e.level>0&&(n="pxt_modules/"+e.id+"/"+t),i.sourceFiles.push(n),i.fileSystem[n]=e.readFile(t)}i.jres=this.getJRes();const u=e.appTarget.runtime&&e.appTarget.runtime.functionsOptions;i.allowedArgumentTypes=u&&u.extraFunctionEditorTypes&&u.extraFunctionEditorTypes.map(e=>e.typeName).concat("number","boolean","string"),i.unfetteredInitializers=null===(n=e.appTarget.compile)||void 0===n?void 0:n.unfetteredInitializers;for(const e of this.sortedDeps())e.patchAppTargetPalette();return this.patchAppTargetPalette(),i}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.files=t.files.filter(t=>t!==e.HISTORY_FILE),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||t===e.HISTORY_FILE)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!!(null==n?void 0:n.isConnected())},t.isConnecting=function(){return!!(null==n?void 0:n.isConnecting())},t.icon=function(){var t;return!!n&&(n.icon||(null===(t=e.appTarget.appTheme.downloadDialogTheme)||void 0===t?void 0:t.deviceIcon)||"usb")},t.unsupportedParts=function(){return(null==n?void 0:n.unsupportedParts)?n.unsupportedParts():[]},t.deviceVariant=function(){return null==n?void 0:n.devVariant},t.disconnectAsync=l,t.configureEvents=function(e,t,i){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){function n(t,n,i){const s=e.semver.tryParse(t||"0.0.0")||e.semver.tryParse("0.0.0");let r=[];return Object.keys(n).filter(t=>e.semver.inRange(t,s)).forEach(e=>r=r.concat(n[e])),i&&(r=r.filter(e=>e.type==i)),r.length?r:void 0}function i(e,t,n){let i=t;return n&&(n.filter(e=>"api"===e.type).forEach(e=>{Object.keys(e.map).forEach(t=>{const n=new RegExp(t,"g");i=i.replace(n,e.map[t])})}),n.filter(e=>"userenum"===e.type).forEach(e=>{Object.keys(e.map).forEach(t=>{const n=new RegExp("enum\\s+"+t+"\\s*{","gm");i=i.replace(n,`enum ${e.map[t]} {`);const s=new RegExp(`(^|[^_a-zA-Z0-9])${t}(\\s*\\.)`,"g");i=i.replace(s,`$1${e.map[t]}$2`)})})),i}t.computePatches=function(t,i){const s=e.appTarget.compile?e.appTarget.compile.patches:void 0;if(s)return n(t,s,i)},t.computePyPatches=function(t,i){const s=e.appTarget.compile?e.appTarget.compile.pyPatches:void 0;if(s)return n(t,s,i)},t.upgradePackageReference=function(t,n,i){if("*"!=i)return n;const s=e.patching.computePatches(t,"package");let r=n;return s&&s.forEach(e=>{Object.keys(e.map).forEach(t=>{r==t&&(r=e.map[t])})}),r},t.patchJavaScript=function(t,n){return i(t,n,e.patching.computePatches(t))},t.patchPython=function(t,n){return i(t,n,e.patching.computePyPatches(t))}}(e.patching||(e.patching={}))}(pxt||(pxt={})),function(e){e.react||(e.react={})}(pxt||(pxt={})),function(e){!function(t){function n(t,n){if(t){if(n){let i=t.major-n.major||t.minor-n.minor||t.patch-n.patch;if(i)return i;if(0==t.pre.length&&n.pre.length>0)return 1;if(t.pre.length>0&&0==n.pre.length)return-1;for(let s=0;s<t.pre.length+1;++s){let r=t.pre[s],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.bump=function(t,n){let s=i(r(t));switch(n){case"major":s.major++,s.minor=0,s.patch=0;break;case"minor":s.minor++,s.patch=0;break;case"patch":s.patch++;break;default:s=e.semver.parse(n)}return s},t.test=function(){e.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]);e.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]));e.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}function n(t,n){const i=pxt.Util.translationsCache();i[e.BLOCK_TRANSLATION_CACHE_KEY]||(i[e.BLOCK_TRANSLATION_CACHE_KEY]={}),i[e.BLOCK_TRANSLATION_CACHE_KEY][t]=n}function i(t){const n=pxt.Util.translationsCache();n[e.BLOCK_TRANSLATION_CACHE_KEY]&&delete n[e.BLOCK_TRANSLATION_CACHE_KEY][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.BLOCK_TRANSLATION_CACHE_KEY="_blocks",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,n=!1){if(!e.usedSymbols||!pxt.appTarget.simulator||!n&&!pxt.appTarget.simulator.parts)return[];const i=(e,t)=>{if(e){const n=e.split(/[ ,]+/g);t.push(...n.filter(e=>!!e&&t.indexOf(e)<0))}};let s=[],r=[];if(Object.keys(e.usedSymbols).forEach(t=>{const n=e.usedSymbols[t];i(null==n?void 0:n.attributes.parts,s),i(null==n?void 0:n.attributes.hiddenParts,r)}),t){const e=pxt.appTarget.simulator.boardDefinition.onboardComponents;e&&("ignorebuiltin"===t?s=s.filter(t=>-1===e.indexOf(t)):"onlybuiltin"===t&&(s=s.filter(t=>e.indexOf(t)>=0)))}return s=s.filter(e=>r.indexOf(e)<0),s.sort(),s=s.reverse(),s},e.buildSimJsInfo=function(t){var n;return{js:t.outfiles[e.BINARY_JS],targetVersion:pxt.appTarget.versions.target,fnArgs:t.usedArguments,parts:e.computeUsedParts(t,"ignorebuiltin"),usedBuiltinParts:e.computeUsedParts(t,"onlybuiltin"),allParts:e.computeUsedParts(t,void 0,!0),breakpoints:null===(n=t.breakpoints)||void 0===n?void 0:n.map(e=>e.id)}},e.blocksCategory=function(t){const n=t?t.attributes.blockNamespace||t.namespace:void 0;return n?e.Util.capitalize(n.split(".")[0]):void 0},e.getBlocksInfo=function(t,n){var i,s;let r=[];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||""}`,m=`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?`%${f} %property`:s?e.U.lf("set %{0} %property to %{1}",f,m):e.U.lf("change %{0} %property by %{1}",f,m),o(p.attributes),pxt.Util.isTranslationMode()&&(p.attributes.translationId=p.attributes.block,p.attributes.block=i?`%${f} %property`:s?`set %${f} %property to %${m}`:`change %${f} %property by %${m}`,o(p.attributes),pxt.crowdin.inContextLoadAsync(p.attributes.translationId).then(e=>{p.attributes.block=e,o(p.attributes)})),r.push(p)}function f(e){n.attributes[e]&&(p.attributes[e]?p.attributes[e]!==n.attributes[e]&&pxt.debug(`Ignoring duplicate ${e} for get/set/change block: ${n.attributes[e]}`):p.attributes[e]=n.attributes[e])}f("blockCombineChangeHelp"),f("blockCombineGetHelp"),f("blockCombineSetHelp"),f("help"),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]&&(pxt.warn(`Enum block ${n.attributes.blockId} trying to overwrite enum ${n.attributes.enumName}`),e=!0),n.attributes.enumMemberName||(pxt.warn(`Enum block ${n.attributes.blockId} should specify enumMemberName`),e=!0),n.attributes.enumPromptHint||(pxt.warn(`Enum block ${n.attributes.blockId} should specify enumPromptHint`),e=!0),n.attributes.enumInitialMembers&&n.attributes.enumInitialMembers.length||(pxt.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]){pxt.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&&!n.attributes.blockIdentity){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 r=null!==(s=null===(i=n.parameters)||void 0===i?void 0:i.filter(e=>!a(e)))&&void 0!==s?s:[];for(let e of r)t+=" %"+e.name;n.attributes.block=t,o(n.attributes)}r.push(n)}}for(let n of r){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&&(r=r.filter(e=>{let t=(e.attributes.blockNamespace||e.namespace).split(".")[0];return-1===f.indexOf(t)}))),{apis:t,blocks:r,blocksById:pxt.Util.toDictionary(r,e=>e.attributes.blockId),enumsByName:d,kindsByName:h}},e.tsSnippetToPySnippet=function(t,n){const i={true:"True",false:"False",null:"None"}[t];if(i)return i;if(n&&6==n.kind||!n&&t.includes(".")){const n=t.lastIndexOf("."),i=t.substr(0,n);let s=t.substr(n+1);return s=e.U.snakify(s).toUpperCase(),i?`${i}.${s}`:s}return t},e.apiLocalizationStrings={},e.localizeApisAsync=async function(s,r){const a=e.Util.userLanguage();if("en"==a)return Promise.resolve(t(s));const l=a.toLowerCase(),c=l+"|jsdoc",u=l+"|block",d=await r.localizationStringsAsync(a);e.apiLocalizationStrings&&e.Util.jsonMergeFrom(d,e.apiLocalizationStrings);const h=e.Util.values(s.byQName).filter(e=>e.attributes._translatedLanguageCode!==a);return await e.Util.promiseMapAll(h,async t=>{var r,h,p;const f=t.attributes.useLoc||t.attributes.blockAliasFor,m=f&&s.byQName[f];t.attributes._untranslatedJsDoc&&(t.attributes.jsDoc=t.attributes._untranslatedJsDoc),t.attributes._untranslatedBlock&&(t.attributes.jsDoc=t.attributes._untranslatedBlock);const g=(e,n)=>{var i,s;return d[t.qName+e]||(null===(i=t.attributes.locs)||void 0===i?void 0:i[n])||m&&(d[m.qName+e]||(null===(s=m.attributes.locs)||void 0===s?void 0:s[n]))},b=g("",c);b&&(t.attributes._untranslatedJsDoc||(t.attributes._untranslatedJsDoc=t.attributes.jsDoc),t.attributes.jsDoc=b),null===(r=t.parameters)||void 0===r||r.forEach(e=>{const t=`|param|${e.name}`,n=g(t,l+t);n&&(e.description=n)});const y=d["{id:category}"+e.Util.capitalize(t.qName)];let v=d[`${t.qName}|block`]||(null===(h=t.attributes.locs)||void 0===h?void 0:h[u]);if(t.attributes.block){const e=pxt.blocks.compileInfo(t);if(e.handlerArgs)for(const t of e.handlerArgs)d[t.localizationKey]?n(t.localizationKey,d[t.localizationKey]):i(t.localizationKey)}if(!v&&m){const e=d[`${m.qName}|block`]||(null===(p=m.attributes.locs)||void 0===p?void 0:p[u]);t.attributes.block===(m.attributes._untranslatedBlock||m.attributes.block)&&e&&(v=e)}if(v&&pxt.Util.isTranslationMode()&&(t.attributes.translationId=v,v=await pxt.crowdin.inContextLoadAsync(v)),y)t.attributes.block?t.attributes.block=v||t.attributes.block:t.attributes.block=y,o(t.attributes);else if(t.attributes.block&&v){const e=pxt.blocks.compileInfo(t),n=t.attributes.block;if(t.attributes.block=pxt.blocks.normalizeBlock(v,e=>{pxt.tickEvent("loc.normalized",{block:t.attributes.block,lang:a,error:e})}),t.attributes._untranslatedBlock||(t.attributes._untranslatedBlock=n),n!=t.attributes.block){o(t.attributes);(function(e,t){if(e.parameters.length!=t.parameters.length)return pxt.debug("Localized block has extra or missing parameters"),!1;for(const n of e.parameters){const e=t.actualNameToParam[n.actualName];if(!e||n.type!=e.type||n.shadowBlockId!=e.shadowBlockId||n.definitionName!=e.definitionName)return pxt.debug(`Parameter ${n.actualName} type, shadow block, or definition name does not match after localization`),!1}return!0})(e,pxt.blocks.compileInfo(t))||(pxt.reportError("loc.errors","block has non matching arguments",{block:t.attributes.blockId,lang:a,originalDefinition:n,translatedBlock:t.attributes.block}),pxt.tickEvent("loc.errors",{block:t.attributes.blockId,lang:a}),t.attributes.block=n,o(t.attributes))}}else o(t.attributes);t.attributes._translatedLanguageCode=a}),t(s)},e.getBlockTranslationsCacheKey=function(t){const n=pxt.Util.translationsCache();if(n[e.BLOCK_TRANSLATION_CACHE_KEY])return n[e.BLOCK_TRANSLATION_CACHE_KEY][t]},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 s=["weight","imageLiteral","gridLiteral","topblockWeight","inlineInputModeLimit"],r=["advanced","handlerStatement","forceStatement","afterOnStart","optionalVariableArgs","blockHidden","constantShim","blockCombine","enumIsBitMask","enumIsHash","decompileIndirectFixedInstances","topblock","callInDebugger","duplicateShadowOnDrag","argsNullable","compileHiddenArguments","expandArgumentsInToolbox"];function a(e){return"Action"===e.type||/^\([^\)]*\)\s*=>/.test(e.type)}function o(e){if(e.block){const n=e.block.split("||");e._def=t(l(n[0])),e._def||pxt.debug("Unable to parse block def for id: "+e.blockId),n[1]&&(e._expandedDef=t(l(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 l(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=[],o=0,l="",u=[];for(let e=0;e<t.length;e++){const n=t[e].kind,i=a[a.length-1];if(15&n)if(m(t[e].content),n&o)if(i&n){a.pop(),o^=n;const e=i&o|n&o;e&&a.push(e)}else p();else o|=n,a.push(n);else 144&n?l+=t[e].content:1120&n&&f();if(64==n){const n={kind:"param",name:t[e].content,shadowBlockId:t[e].type,ref:!1};t[e].name&&(n.varName=t[e].name),s.push(n),r.push(n)}else if(1024==n){const n={kind:"param",name:t[e].content,shadowBlockId:t[e].type,ref:!0};t[e].name&&(n.varName=t[e].name),s.push(n),r.push(n)}else 256==n?(m(),u.push({kind:"image",uri:t[e].content})):512==n?(m(),u.push({kind:"label",text:t[e].content,cssClass:t[e].type})):32==n&&s.push({kind:"break"})}return f(),{parts:s,parameters:r};function d(t,n=!1){let s="";for(n&&i++;i<e.length&&t(e[i]);)s+=e[i],++i;return s&&i--,s}function h(t){const n=d(e=>e!==t,!0);if(e[i+1]===t)return++i,n}function p(){let e="",t=[];for(const n of u)c(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=[],o=0}function f(){for(m(),o&&p();u.length;){const e=u.shift();if(c(e))s.push(e);else{if(!e.content)continue;const t=[];10&e.styles&&t.push("bold"),5&e.styles&&t.push("italics"),s.push({kind:"label",text:e.content,style:t})}}}function m(e){u.push({content:l,styles:o,endingToken:e}),l=""}}function c(e){return!!e.kind}let u;e.parseCommentString=function(t){let n={paramDefl:{},callingConvention:0,_source:t},i=!0;for(;i;)i=!1,t=t.replace(/\/\/%[ \t]*([\w\.-]+)(=(("[^"\n]*")|'([^'\n]*)'|([^\s]*)))?/,(t,s,r,a,o,l,c)=>{let u=o?JSON.parse(o):r?o||l||c:"true";if(u||(u=""),e.U.startsWith(s,"block.loc."))n.locs||(n.locs={}),n.locs[s.slice(10).toLowerCase()+"|block"]=u;else if(e.U.startsWith(s,"jsdoc.loc."))n.locs||(n.locs={}),n.locs[s.slice(10).toLowerCase()+"|jsdoc"]=u;else if(e.U.contains(s,".loc.")){n.locs||(n.locs={});const e=s.slice(0,s.indexOf(".loc.")),t=s.slice(s.indexOf(".loc.")+5);n.locs[t+"|param|"+e]=u}else if(e.U.endsWith(s,".defl"))u.indexOf(" ")>-1?n.paramDefl[s.slice(0,s.length-5)]=`"${u}"`:n.paramDefl[s.slice(0,s.length-5)]=u,n.explicitDefaults||(n.explicitDefaults=[]),n.explicitDefaults.push(s.slice(0,s.length-5));else if(e.U.endsWith(s,".shadow"))n._shadowOverrides||(n._shadowOverrides={}),n._shadowOverrides[s.slice(0,s.length-7)]=u;else if(e.U.endsWith(s,".snippet")){n.paramSnippets||(n.paramSnippets={});const e=s.slice(0,s.length-8);n.paramSnippets[e]||(n.paramSnippets[e]={}),n.paramSnippets[e].ts=u}else if(e.U.endsWith(s,".pySnippet")){n.paramSnippets||(n.paramSnippets={});const e=s.slice(0,s.length-10);n.paramSnippets[e]||(n.paramSnippets[e]={}),n.paramSnippets[e].python=u}else if(e.U.endsWith(s,".fieldEditor"))n.paramFieldEditor||(n.paramFieldEditor={}),n.paramFieldEditor[s.slice(0,s.length-12)]=u;else if(e.U.contains(s,".fieldOptions.")){n.paramFieldEditorOptions||(n.paramFieldEditorOptions={});const e=s.slice(0,s.indexOf(".fieldOptions.")),t=s.slice(s.indexOf(".fieldOptions.")+14,s.length);n.paramFieldEditorOptions[e]||(n.paramFieldEditorOptions[e]={}),n.paramFieldEditorOptions[e][t]=u}else if(e.U.contains(s,".shadowOptions.")){n.paramShadowOptions||(n.paramShadowOptions={});const e=s.slice(0,s.indexOf(".shadowOptions.")),t=s.slice(s.indexOf(".shadowOptions.")+15,s.length);n.paramShadowOptions[e]||(n.paramShadowOptions[e]={}),n.paramShadowOptions[e][t]=u}else e.U.endsWith(s,".min")?(n.paramMin||(n.paramMin={}),n.paramMin[s.slice(0,s.length-4)]=u):e.U.endsWith(s,".max")?(n.paramMax||(n.paramMax={}),n.paramMax[s.slice(0,s.length-4)]=u):n[s]=u;return i=!0,"//% "});for(let e of s)"string"==typeof n[e]&&(n[e]=parseInt(n[e]));for(let e of r)"string"==typeof n[e]&&(n[e]="true"==n[e]||"1"==n[e]);if(n.trackArgs&&(n.trackArgs=n.trackArgs.split(/[ ,]+/).map(e=>parseInt(e)||0)),n.enumInitialMembers&&(n.enumInitialMembers=n.enumInitialMembers.split(/[ ,]+/)),n.blockExternalInputs&&!n.inlineInputMode&&(n.inlineInputMode="external"),n.paramHelp={},n.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,i)=>{if(n.paramHelp[t]=i,!n.paramDefl[t]){let e=/\beg\.?:\s*(.+)/.exec(i);if(e&&e[1]){let i=/(?:"([^"]*)")|(?:'([^']*)')|(?:([^\s,]+))/g.exec(e[1]);if(i){let e=i[1]||i[2]||i[3];e||(e=""),e.indexOf(" ")>-1?n.paramDefl[t]=`"${e}"`:n.paramDefl[t]=e}}}return""}),n.jsDoc+=t,"")),n.jsDoc=n.jsDoc.trim(),n.async&&(n.callingConvention=1),n.promise&&(n.callingConvention=2),n.jres&&(n.whenUsed=!0),n.subcategories)try{n.subcategories=JSON.parse(n.subcategories)}catch(e){n.subcategories=void 0}if(n.groups)try{n.groups=JSON.parse(n.groups)}catch(e){n.groups=void 0}if(n.groupIcons)try{n.groupIcons=JSON.parse(n.groupIcons)}catch(e){n.groupIcons=void 0}if(n.groupHelp)try{n.groupHelp=JSON.parse(n.groupHelp)}catch(e){n.groupHelp=void 0}return o(n),n},e.parameterTypeIsArrowFunction=a,e.updateBlockDef=o,e.parseBlockDefinition=l,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=void 0){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)}}}}(u=e.UF2||(e.UF2={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){!function(e){let t;!function(e){e[e.Bundled=1]="Bundled",e[e.Github=2]="Github",e[e.ShareScript=3]="ShareScript"}(t=e.ExtensionType||(e.ExtensionType={}))}(e.service||(e.service={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){let n,i,s;!function(e){e[e.IDE=0]="IDE",e[e.Sandbox=1]="Sandbox",e[e.Widget=2]="Widget",e[e.Controller=3]="Controller"}(n=t.EditorLayoutType||(t.EditorLayoutType={})),function(e){e[e.None=0]="None",e[e.Basic=1]="Basic",e[e.App=2]="App"}(i=t.ControllerMode||(t.ControllerMode={}));let r=i.None,a=!1,o=!1;function l(){if(void 0===s){if(e.BrowserUtils.hasWindow()){const t=/sandbox=1|#sandbox|#sandboxproject/i.test(window.location.href)||e.BrowserUtils.isIFrame(),l=/nosandbox=1/i.test(window.location.href),c=/controller=(0|1|2)/i.exec(window.location.href);c&&e.BrowserUtils.isIFrame()&&(r=parseInt(c[1]));const u=r!==i.None,d=/readonly=1/i.test(window.location.href),h=/editorlayout=(widget|sandbox|ide)/i.exec(window.location.href),p=/noproject=1/i.test(window.location.href);if(s=n.IDE,l?s=n.Widget:u?s=n.Controller:t&&(s=n.Sandbox),u&&d&&(a=!0),u&&p&&(o=!0),h)switch(h[1].toLowerCase()){case"widget":s=n.Widget;break;case"sandbox":s=n.Sandbox;break;case"ide":s=n.IDE}}else s=n.Sandbox;e.debug(`shell: layout type ${n[s]}, readonly ${d()}`)}}function c(){return l(),s==n.Sandbox}function u(){return/[?&]timeMachine=1/i.test(window.location.href)}function d(){return!e.BrowserUtils.hasWindow()||u()||c()&&!/[?&]edit=1/i.test(window.location.href)||h()&&a}function h(){return l(),s==n.Controller}t.layoutTypeClass=function(){return l(),e.shell.EditorLayoutType[s].toLowerCase()},t.isSandboxMode=c,t.isTimeMachineEmbed=u,t.isReadOnly=d,t.isNoProject=function(){return o},t.isControllerMode=h,t.getControllerMode=function(){return l(),r},t.isPyLangPref=function(){return"py"==e.storage.getLocal("editorlangpref")},t.getEditorLanguagePref=function(){return e.storage.getLocal("editorlangpref")},t.setEditorLanguagePref=function(t){t.match(/prj$/)&&(t=t.replace(/prj$/,"")),e.storage.setLocal("editorlangpref",t)},t.getToolboxAnimation=function(){return e.storage.getLocal("toolboxanimation")},t.setToolboxAnimation=function(){e.storage.setLocal("toolboxanimation","1")},t.hasHomeScreen=function(){return!e.shell.isControllerMode()&&!e.appTarget.appTheme.lockedEditor}}(e.shell||(e.shell={}))}(pxt||(pxt={})),function(e){!function(t){t.USER_VERSION="0.0.1";class n{constructor(){this.db=new e.BrowserUtils.IDBWrapper(n.databaseName,n.version,(e,t)=>{const i=t.result;e.oldVersion<1&&(i.createObjectStore(n.projectTable,{keyPath:n.projectKey}),i.createObjectStore(n.userTable,{keyPath:n.userKey}))})}initAsync(){return this.db.openAsync()}getAllProjectsAsync(){return this.db.getAllAsync(n.projectTable).then(e=>e.map(e=>e.project).filter(e=>!e.deleted))}deleteProjectAsync(e){return this.getProjectAsync(e).then(e=>{e.deleted=!0,this.saveProjectAsync(e)})}getProjectAsync(e){return this.db.getAsync(n.projectTable,e).then(e=>null==e?void 0:e.project)}saveProjectAsync(e){return this.db.setAsync(n.projectTable,{id:e.header.id,project:e})}getUserStateAsync(){return this.db.getAsync(n.userTable,"local-user").then(e=>null==e?void 0:e.user)}saveUserStateAsync(e){return this.db.setAsync(n.userTable,{id:"local-user",user:e})}}n.version=6,n.databaseName="local-skill-map",n.projectTable="projects",n.projectKey="id",n.userTable="users",n.userKey="id",t.IndexedDBWorkspace=n}(e.skillmap||(e.skillmap={}))}(pxt||(pxt={})),function(e){!function(e){e.MAX_FREQUENCY=5e3,e.MAX_VOLUME=255,e.renderSoundPath=function(i,s,r){let{startFrequency:a,endFrequency:o,startVolume:l,endVolume:c,wave:u,interpolation:d}=i;a=Math.max(Math.min(a,e.MAX_FREQUENCY),1),o=Math.max(Math.min(o,e.MAX_FREQUENCY),1),l=Math.max(Math.min(l,e.MAX_VOLUME),0),c=Math.max(Math.min(c,e.MAX_VOLUME),0);const h=new t(a+o+1);let p;switch(d){case"linear":p=e=>a+e*(o-a)/s;break;case"curve":p=e=>a+(o-a)*Math.sin(e/s*(Math.PI/2));break;case"logarithmic":p=e=>a+Math.log10(1+e/s*9)*(o-a)}"noise"===u&&(p=()=>h.randomRange(500,5e3));const f=t=>Math.max(Math.min((c-l)/s*t+l,e.MAX_VOLUME),0),m=s/2,g=t=>t/e.MAX_VOLUME*(r-2)/2,b=t=>(1-t/e.MAX_FREQUENCY)*(m-10)+10,y=["M 2 "+r/2];let v=0;for(;v<s;)y.push(n(g(f(v)),b(p(v))/2,u,!1,h)),v+=b(p(v))/2,y.push(n(g(f(v)),b(p(v))/2,u,!0,h)),v+=b(p(v))/2;return y.join(" ")},e.renderWaveSnapshot=function(i,s,r,a,o,l){const c=new t(i);"noise"===r&&(i=c.randomRange(500,5e3)),i=Math.max(Math.min(i,e.MAX_FREQUENCY),1);const u=s/e.MAX_VOLUME*(o-2)/2,d=a/(i*l/1e3)/2;let h=Math.ceil(a/(2*d));h%2==1&&h++;const p=[`M ${a/2-h*d} ${o/2}`];let f=0;for(let e=0;e<h;e++)p.push(n(u,d,r,!1,c)),f+=d,p.push(n(u,d,r,!0,c)),f+=d;return p.join(" ")};class t{constructor(e){this.seed=e,this.lfsr=e}next(){return(this.lfsr=this.lfsr>>1^46080&-(1&this.lfsr))/65535}randomRange(e,t){return e+(t-e)*this.next()}}function n(e,t,n,i,s){switch(n){case"triangle":return`l ${t/2} ${i?e:-e} l ${t/2} ${i?-e:e}`;case"square":return`v ${i?e:-e} h ${t} v ${i?-e:e}`;case"sawtooth":return i?`l ${t} ${e} v ${-e}`:`v ${-e} l ${t} ${e}`;case"sine":return`q ${t/2} ${1.9*(i?e:-e)} ${t} 0`;case"noise":const n=[],r=[],a=Math.min(4,t/4);let o=i;for(let n=0;n<t;n+=a)r.push(s.randomRange(0,e)*(o?1:-1)),o=!o;r[0]=i?e:-e,r[r.length-1]=0;let l=0,c=0;for(const e of r){let i=Math.min(a,t-c);if(n.push(`v ${e-l} h ${i}`),l=e,c+=i,c>=t)break}return n.join(" ")}}function i(e){switch(e){case"square":return 15;case"sine":return 3;case"triangle":return 1;case"noise":return 18;case"sawtooth":return 2}}function s(e,t,n){const i=new Uint8Array(2);new Uint16Array(i.buffer)[0]=0|n,e[t]=i[0],e[t+1]=i[1]}e.soundToInstructionBuffer=function(t,n,r){const{startFrequency:a,endFrequency:o,startVolume:l,endVolume:c,interpolation:u,duration:d}=t,h=[];if("linear"===t.interpolation&&"none"===t.effect)h.push({frequency:a,volume:l/e.MAX_VOLUME*1024}),h.push({frequency:o,volume:c/e.MAX_VOLUME*1024});else{n=Math.min(n,Math.floor(d/5));const i=t=>(l+t*(c-l)/d)/e.MAX_VOLUME*1024;let s;switch(u){case"linear":s=e=>a+e*(o-a)/d;break;case"curve":s=e=>a+(o-a)*Math.sin(e/d*(Math.PI/2));break;case"logarithmic":s=e=>a+Math.log10(1+e/d*9)*(o-a)}const p=d/n;for(let e=0;e<n;e++){const n={frequency:Math.max(s(e*p),1),volume:i(e*p)};"tremolo"===t.effect?n.volume=e%2==0?Math.max(n.volume-500*r,0):Math.min(n.volume+500*r,1023):"vibrato"===t.effect?n.frequency=e%2==0?Math.max(n.frequency-100*r,1):n.frequency+100*r:"warble"===t.effect&&(n.frequency=e%2==0?Math.max(n.frequency-1e3*r,1):n.frequency+1e3*r),h.push(n)}}const p=new Uint8Array(12*(h.length-1)),f=Math.floor(d/(h.length-1));for(let e=0;e<h.length-1;e++){const n=12*e;p[n]=i(t.wave),s(p,n+2,h[e].frequency),s(p,n+4,f),s(p,n+6,h[e].volume),s(p,n+8,h[e+1].volume),s(p,n+10,h[e+1].frequency)}return p}}(e.assets||(e.assets={}))}(pxt||(pxt={})),function(e){!function(t){t.createStreamAsync=function(t,n){return e.Cloud.privatePostAsync("streams",{target:t,name:n||"data"}).then(e=>e)},t.postPayloadAsync=function(t,n){return e.Util.assert(!!t.privatekey),e.Cloud.privatePostAsync(`${t.id}/data?privatekey=${t.privatekey}`,n)}}(e.streams||(e.streams={}))}(pxt||(pxt={})),function(e){!function(t){let n,i;!function(e){e[e.userSpaceOnUse=0]="userSpaceOnUse",e[e.objectBoundingBox=1]="objectBoundingBox"}(n=t.PatternUnits||(t.PatternUnits={})),function(e){e[e.em=0]="em",e[e.ex=1]="ex",e[e.px=2]="px",e[e.in=3]="in",e[e.cm=4]="cm",e[e.mm=5]="mm",e[e.pt=6]="pt",e[e.pc=7]="pc",e[e.percent=8]="percent"}(i=t.LengthUnit||(t.LengthUnit={}));class s{constructor(e){this.el=T(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=T("title"),this.el.firstChild?this.el.insertBefore(this.titleElement,this.el.firstChild):this.el.appendChild(this.titleElement)),this.titleElement.textContent=e}setVisible(e){return this.setAttribute("visibility",e?"visible":"hidden")}}t.BaseElement=s;class r extends s{draw(e){const t=function(e){switch(e){case"text":return new d;case"circle":return new p;case"rect":return new h;case"line":return new f;case"polygon":return new b;case"polyline":return new g;case"path":return new y;default:return new u(e)}}(e);return this.el.appendChild(t.el),t}element(e,t){return t(this.draw(e)),this}group(){const e=new 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 A;break;case"linearGradient":n=new w;break;case"clipPath":n=new k;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 m extends u{points(e){return this.setAttribute("points",e)}with(e){return this.points(e.map(({x:e,y:t})=>e+" "+t).join(","))}}t.PolyElement=m;class g extends m{constructor(){super("polyline")}}t.Polyline=g;class b extends m{constructor(){super("polygon")}}t.Polygon=b;class y extends u{constructor(){super("path"),this.d=new x}update(){return this.setAttribute("d",this.d.toAttribute())}path(e){return e(this.d),this.update()}setD(e){return this.setAttribute("d",e),this}}t.Path=y;t.Image=class extends u{constructor(){super("image")}src(e){return this.setAttributeNS("http://www.w3.org/1999/xlink","href",e)}width(e,t=i.px){return this.setAttribute("width",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=T("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 A 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=A;class k extends r{constructor(){super("clipPath")}clipPathUnits(e){return e?this.setAttribute("clipPathUnits","objectBoundingBox"):this.setAttribute("clipPathUnits","userSpaceOnUse")}}function T(e){return document.createElementNS("http://www.w3.org/2000/svg",e)}t.ClipPath=k;class x{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=x}(e.svgUtil||(e.svgUtil={}))}(pxt||(pxt={})),function(e){!function(e){!function(e){function t(){return"undefined"!=typeof window&&("ontouchstart"in window||navigator&&navigator.maxTouchPoints>0)}function n(){return"undefined"!=typeof window&&!!window.PointerEvent}e.isTouchEnabled=t,e.hasPointerEvents=n,e.down=function(e,i){n()?e.addEventListener("pointerdown",i):t()?(e.addEventListener("mousedown",i),e.addEventListener("touchstart",i)):e.addEventListener("mousedown",i)},e.up=function(e,i){n()?e.addEventListener("pointerup",i):(t(),e.addEventListener("mouseup",i))},e.enter=function(e,i){n()?e.addEventListener("pointerover",e=>{i(!!(1&e.buttons))}):t()?e.addEventListener("touchstart",e=>{i(!0)}):e.addEventListener("mouseover",e=>{i(!!(1&e.buttons))})},e.leave=function(e,i){n()?e.addEventListener("pointerleave",i):t()?e.addEventListener("touchend",i):e.addEventListener("mouseleave",i)},e.move=function(e,i){n()?e.addEventListener("pointermove",i):t()?e.addEventListener("touchmove",i):e.addEventListener("mousemove",i)},e.click=function(e,t){e.addEventListener("click",t)}}(e.events||(e.events={}))}(e.svgUtil||(e.svgUtil={}))}(pxt||(pxt={})),function(e){!function(e){!function(t){class n extends e.Text{at(e,t){return this.cx=e,this.cy=t,this.rePosition(),this}text(e,t=12){return super.text(e),this.fontSizePixels=t,this.setAttribute("font-size",t+"px"),this.rePosition(),this}rePosition(){null!=this.cx&&null!=this.cy&&null!=this.fontSizePixels&&(this.setAttribute("x",this.cx),this.setAttribute("y",this.cy),this.setAttribute("text-anchor","middle"),this.setAttribute("alignment-baseline","middle"))}}t.CenteredText=n}(e.helpers||(e.helpers={}))}(e.svgUtil||(e.svgUtil={}))}(pxt||(pxt={})),function(e){!function(e){e.initExtensionsAsync=e=>Promise.resolve({}),e.initFieldExtensionsAsync=e=>Promise.resolve({})}(e.editor||(e.editor={}))}(pxt||(pxt={})),function(e){e.IMAGE_MIME_TYPE="image/x-mkcd-f4",e.TILEMAP_MIME_TYPE="application/mkcd-tilemap",e.ANIMATION_MIME_TYPE="application/mkcd-animation",e.SONG_MIME_TYPE="application/mkcd-song",e.JSON_MIME_TYPE="application/json";class t{constructor(e){this.type=e,this.assets=[],this.takenNames={},this.listeners=[]}add(e){if(this.takenNames[e.id])return this.update(e.id,e);{const t=o(e);return this.takenNames[t.id]=!0,this.takenNames[f(t)]=!0,t.meta.displayName&&t.meta.displayName!==t.id&&(this.takenNames[t.meta.displayName]&&(t.meta.displayName=this.generateNewDisplayName(t.meta.displayName)),this.takenNames[t.meta.displayName]=!0),this.assets.push(t),o(t)}}getSnapshot(e){return e?this.assets.filter(t=>e(t)).map(e=>o(e)):this.assets.map(e=>o(e))}update(t,n){let i;if(this.takenNames[t]){const s=this.lookupByID(t);if(h(s,n))i=n;else{if(!m(n)&&m(s))return e.warn("Refusing to overwrite asset with invalid version"),e.tickEvent("assets.invalidAssetOverwrite",{assetType:n.type}),s;this.removeByID(t),i=this.add(n),this.notifyListener(n.internalID)}}else i=this.add(n);return i}removeByID(e){const t=this.lookupByID(e);this.assets=this.assets.filter(t=>t.id!==e),delete this.takenNames[e],t&&delete this.takenNames[f(t)],(null==t?void 0:t.meta.displayName)&&delete this.takenNames[null==t?void 0:t.meta.displayName]}getByID(e){const t=this.lookupByID(e);return t&&o(t)}getByDisplayName(e){if(this.takenNames[e])for(const t of this.assets)if(t.meta.displayName===e||f(t)===e)return o(t)}getByValue(e){for(const t of this.assets)if(h(e,t,!0))return t}isIDTaken(e){return!!this.takenNames[e]}clone(){const e=new t(this.type);return e.assets=this.getSnapshot(),e.takenNames=Object.assign({},this.takenNames),e}serializeToJRes(e={},t){for(const n of this.assets)t&&!t(n)||d(n,e);return e}addListener(e,t){this.listeners.push({internalID:e,callback:t})}removeListener(e){this.listeners=this.listeners.filter(t=>t.callback!==e)}diff(e){let t={before:[],after:[]},n={};for(const i of e.assets){n[i.internalID]=!0;const e=this.lookupByInternalID(i.internalID);e&&h(i,e)||(t.before.push(i),t.after.push(e))}for(const e of this.assets.filter(e=>!n[e.internalID]))t.before.push(null),t.after.push(e);return t}applyDiff(t,n=!1){const i=n?t.after:t.before,s=n?t.before:t.after;e.Util.assert(i.length===s.length);for(let e=0;e<i.length;e++)i[e]?(this.removeByInternalID(i[e].internalID),s[e]&&this.assets.push(s[e]),this.notifyListener(i[e].internalID)):(this.assets.push(s[e]),this.notifyListener(s[e].internalID));this.takenNames={};for(const t of this.assets)e.Util.assert(!this.takenNames[t.id]),this.takenNames[t.id]=!0,this.takenNames[f(t)]=!0,t.meta.displayName&&(t.meta.displayName!==t.id&&e.Util.assert(!this.takenNames[t.meta.displayName]),this.takenNames[t.meta.displayName]=!0)}lookupByID(e){for(const t of this.assets)if(t.id===e)return t;return null}lookupByInternalID(e){for(const t of this.assets)if(t.internalID===e)return t;return null}removeByInternalID(e){this.assets=this.assets.filter(t=>t.internalID!==e)}notifyListener(e){for(const t of this.listeners)t.internalID===e&&t.callback()}generateNewDisplayName(e){e=e.replace(/\d+$/,"");let t=0;for(;this.takenNames[e+t];)++t;return e+t}}class n{constructor(){this.needsRebuild=!0,this.nextID=0,this.nextInternalID=0,this.committedState={revision:n.nextRevision++,assets:{image:new t("image"),tile:new t("tile"),tilemap:new t("tilemap"),animation:new t("animation"),song:new t("song"),json:new t("json")}},this.state={revision:n.nextRevision++,assets:{image:new t("image"),tile:new t("tile"),tilemap:new t("tilemap"),animation:new t("animation"),song:new t("song"),json:new t("json")}},this.gallery={revision:0,assets:{image:new t("image"),tile:new t("tile"),tilemap:new t("tilemap"),animation:new t("animation"),song:new t("song"),json:new t("json")}},this.undoStack=[],this.redoStack=[]}getNewInternalId(){return this.nextInternalID++}createNewImage(t=16,n=16){this.onChange();const i=this.generateNewID("image"),s=new e.sprite.Bitmap(t,n).data(),r={internalID:this.getNewInternalId(),id:i,type:"image",bitmap:s,meta:{},jresData:e.sprite.base64EncodeBitmap(s)};return this.getAssetCollection("image").add(r)}createNewAnimation(t=16,n=16){this.onChange();const i=this.generateNewID("animation"),s=new e.sprite.Bitmap(t,n).data(),r={internalID:this.getNewInternalId(),id:i,type:"animation",frames:[s],interval:500,meta:{}};return this.getAssetCollection("animation").add(r)}createNewAnimationFromData(e,t=500,n){this.onChange();const i=this.generateNewID("animation"),s={internalID:this.getNewInternalId(),id:i,type:"animation",frames:e,interval:t,meta:{displayName:n}};return this.getAssetCollection("animation").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.getAssetCollection("image").getSnapshot()}getProjectTiles(t,n){const i=this.getAssetCollection("tile").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.getAssetCollection("tile").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.getAssetCollection("image").add(i)}createNewSong(t,n){this.onChange();const i={internalID:this.getNewInternalId(),id:this.generateNewID("song"),type:"song",song:e.assets.music.cloneSong(t),meta:{displayName:n}};return this.getAssetCollection("song").add(i)}createNewJsonAsset(e,t,n){this.onChange();const i={internalID:this.getNewInternalId(),id:this.generateNewID("json"),type:"json",data:e,fileName:t,meta:{displayName:n}};return this.getAssetCollection("json").add(i)}updateTile(t){this.onChange();const n=this.resolveProjectTileByInternalID(t.internalID);if(n){if(this.getAssetCollection("tile").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.getAssetCollection("tile").removeByID(e)}getProjectTilesetJRes(t){const n={};return this.getAssetCollection("tile").serializeToJRes(n),this.getAssetCollection("tilemap").serializeToJRes(n,n=>!t||!e.sprite.isTilemapEmptyOrUnused(n,this,t)),n["*"]={mimeType:"image/x-mkcd-f4",dataEncoding:"base64",namespace:e.sprite.TILE_NAMESPACE},n}getProjectAssetsJRes(){const t={};for(const e of Object.keys(this.state.assets))"tilemap"!==e&&"tile"!==e&&this.state.assets[e].serializeToJRes(t);return t["*"]={mimeType:"image/x-mkcd-f4",dataEncoding:"base64",namespace:e.sprite.IMAGES_NAMESPACE},t}getTilemap(e){return this.getAssetCollection("tilemap").getByID(e)}updateTilemap(e,t){const n=this.getAssetCollection("tilemap").getByID(e);if(n){this.onChange();const i=Object.assign(Object.assign({},n),{data:t});return this.getAssetCollection("tilemap").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.getAssetCollection("tile").getSnapshot(t=>t.internalID===e)[0]}resolveTileByBitmap(t){const n=e.sprite.base64EncodeBitmap(t);return this.getAssetCollection("tile").getSnapshot(e=>e.jresData===n)[0]}getTransparency(t){const n=e.sprite.TILE_NAMESPACE+".transparency"+t;let i=this.getAssetCollection("tile").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.getAssetCollection("tile").add(i)}return i}createNewTilemapFromData(e,t){this.onChange();const n=this.generateNewIDInternal("tilemap",t||lf("level"));return this.getAssetCollection("tilemap").add({internalID:this.getNewInternalId(),id:n,type:"tilemap",meta:{displayName:t||n},data:e}),[n,e]}cloneState(){const e={revision:this.state.revision,assets:{}};for(const t of Object.keys(this.state.assets))e.assets[t]=this.state.assets[t].clone();return e}undo(){if(this.state.revision!==this.committedState.revision&&this.pushUndo(),this.undoStack.length){const e=this.undoStack.pop();for(const t of Object.keys(e.assetDiffs))this.getAssetCollection(t).applyDiff(e.assetDiffs[t],!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();for(const t of Object.keys(e.assetDiffs))this.getAssetCollection(t).applyDiff(e.assetDiffs[t]);this.state.revision=e.afterRevision,this.undoStack.push(e),this.committedState=this.cloneState(),this.needsRebuild=!0}}pushUndo(){if(this.undoStack.length&&this.committedState.revision===this.state.revision)return;this.redoStack=[],this.undoStack.push({beforeRevision:this.committedState.revision,afterRevision:this.state.revision,assetDiffs:{}});const e=this.undoStack[this.undoStack.length-1];for(const t of Object.keys(this.state.assets))e.assetDiffs[t]=this.state.assets[t].diff(this.committedState.assets[t]);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=>this.getAssetCollection(e).isIDTaken(t)||this.getAssetCollection(e,!0).isIDTaken(t),i=b(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(f(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;case"song":o=`assets.song\`${s}\``,r&&(o+=`|assets.song\`${r}\``);break;case"json":o=`assets.json\`${s}\``,r&&(o+=`|assets.json\`${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;case"song":c=`assets.song("""${s}""")`,r&&(c+=`|assets.song("""${r}""")`);break;case"json":c=`assets.json("""${s}""")`,r&&(c+=`|assets.json("""${r}""")`);break;default:c=`assets.image("""${s}""")`,r&&(c+=`|assets.image("""${r}""")`)}const u=new RegExp(c,"gm");for(let e of Object.keys(n)){if((null==i?void 0:i.indexOf(e))>=0)continue;const t=n[e];if(e.match(/((?!\.g).{2}|^.{0,1})\.ts$/i)){if(t.content.match(l))return!0}else if(e.endsWith(".py")&&t.content.match(u))return!0}}return!1}lookupAsset(e,t){return this.getAssetCollection(e).getByID(t)||this.getAssetCollection(e,!0).getByID(t)}lookupAssetByName(e,t){return this.getAssetCollection(e).getByDisplayName(t)}lookupAssetByValue(e,t){return this.getAssetCollection(e).getByValue(t)}getAssets(e){return this.getAssetCollection(e).getSnapshot()}getGalleryAssets(e){return this.getAssetCollection(e,!0).getSnapshot()}lookupBlockAsset(e,t){return this.getAssetCollection(e).getSnapshot(e=>{var n,i;return-1!==(null===(i=null===(n=e.meta)||void 0===n?void 0:n.blockIDs)||void 0===i?void 0:i.indexOf(t))})[0]}updateAsset(e){return this.onChange(),"tile"===e.type?this.updateTile(e):this.getAssetCollection(e.type).update(e.id,e)}duplicateAsset(e,t){var n;this.onChange();const i=o(e),s=t||(null===(n=i.meta)||void 0===n?void 0:n.displayName);let r;switch(e.type){case"image":r=this.createNewProjectImage(i.bitmap,s);break;case"tile":r=this.createNewTile(i.bitmap,null,s);break;case"tilemap":const[t,n]=this.createNewTilemapFromData(i.data,s);r=this.getTilemap(t);break;case"animation":r=this.createNewAnimationFromData(i.frames,i.interval,s);break;case"song":r=this.createNewSong(i.song,s);break;case"json":r=this.createNewJsonAsset(i.data,e.fileName,s)}return r}removeAsset(e){this.onChange(),this.getAssetCollection(e.type).removeByID(e.id)}addChangeListener(e,t){this.getAssetCollection(e.type).addListener(e.internalID,t)}removeChangeListener(e,t){this.getAssetCollection(e).removeListener(t)}loadPackage(t){const n=t.sortedDeps();this.extensionTileSets=[];for(const t of n){const n="this"===t.id,i=this.readImages(t.parseJRes(),n);for(const s of i)if(s.meta.package=t.id,"tile"===s.type)this.getAssetCollection("tile",!n).add(s);else if("image"===s.type)this.getAssetCollection("image",!n).add(s);else if("animation"===s.type)this.getAssetCollection("animation",!n).add(s);else if("json"===s.type)this.getAssetCollection("json",!n).add(s);else if(n){const t=e.sprite.IMAGES_NAMESPACE+".";s.id.startsWith(t)&&(s.id=s.id.replace(t,e.sprite.SONG_NAMESPACE+".")),this.getAssetCollection("song").add(s)}else this.getAssetCollection("song",!0).add(s)}for(const e of n){const t="this"===e.id;for(const n of i(e.parseJRes()))t?this.getAssetCollection("tilemap").add({internalID:this.getNewInternalId(),type:"tilemap",id:n.id,meta:{displayName:n.displayName||n.id,package:e.id},data:a(n,e=>this.resolveTile(e))}):this.getAssetCollection("tilemap",!0).add({internalID:this.getNewInternalId(),type:"tilemap",id:n.id,meta:{displayName:n.displayName||n.id,package:e.id},data:a(n,e=>this.getAssetCollection("tile",!0).getByID(e))})}this.committedState=this.cloneState(),this.undoStack=[],this.redoStack=[]}loadTilemapJRes(t,n=!1,s=!1){t=e.inflateJRes(t);const r=this.readImages(t,!s).filter(e=>"tile"===e.type);let o={};if(s)for(const e of r)this.getAssetCollection("tile",!0).add(e);else for(const e of r){if(n){const t=this.resolveTileByBitmap(e.bitmap);if(t){o[e.id]=t.id;continue}}const t=this.createNewTile(e.bitmap,e.id,e.meta.displayName);t.id!==e.id&&(o[e.id]=t.id)}for(const e of i(t))this.getAssetCollection("tilemap",s).add({internalID:this.getNewInternalId(),type:"tilemap",id:e.id,meta:{displayName:e.displayName||e.id},data:a(e,e=>(o[e]&&(e=o[e]),this.resolveTile(e)))})}loadAssetsJRes(t,n=!1){t=e.inflateJRes(t);const i=[];for(const s of Object.keys(t)){const r=t[s];if(r.tilemapTile)this.getAssetCollection("tile",n).add(this.generateImage(r,"tile"));else if(r.mimeType===e.IMAGE_MIME_TYPE)this.getAssetCollection("image",n).add(this.generateImage(r,"image"));else if(r.mimeType===e.ANIMATION_MIME_TYPE){const[e,t]=this.generateAnimation(r);t?i.push(e):this.getAssetCollection("animation",n).add(e)}else r.mimeType===e.SONG_MIME_TYPE?this.getAssetCollection("song",n).add(this.generateSong(r)):r.mimeType===e.JSON_MIME_TYPE&&this.getAssetCollection("json",n).add(this.generateJsonAsset(r))}for(const e of i)this.getAssetCollection("animation",n).add(this.inflateAnimation(e,this.getAssetCollection("image",n).getSnapshot()))}removeInactiveBlockAssets(e){for(const e of Object.keys(this.state.assets))t(this.state.assets[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)}}clone(){var e;const t=new n;return t.committedState=l(this.committedState),t.state=l(this.state),t.gallery=l(this.gallery),t.extensionTileSets=null===(e=this.extensionTileSets)||void 0===e?void 0:e.map(e=>Object.assign(Object.assign({},e),{tileSets:e.tileSets.map(e=>Object.assign(Object.assign({},e),{tiles:e.tiles.map(e=>o(e))}))})),t.needsRebuild=this.needsRebuild,t.nextID=this.nextID,t.nextInternalID=this.nextInternalID,t.undoStack=this.undoStack.map(e=>c(e)),t.redoStack=this.undoStack.map(e=>c(e)),t}saveGallerySnapshot(){return this.gallery}loadGallerySnapshot(e){this.gallery=e}generateImage(t,n){return{internalID:this.getNewInternalId(),type:n,id:t.id,meta:{displayName:t.displayName,tags:t.tags},jresData:t.data,bitmap:e.sprite.getBitmapFromJResURL(`data:${e.IMAGE_MIME_TYPE};base64,${t.data}`).data()}}generateSong(t){return{internalID:this.getNewInternalId(),type:"song",id:t.id,meta:{displayName:t.displayName,tags:t.tags},song:e.assets.music.decodeSongFromHex(t.data)}}generateJsonAsset(e){const t=JSON.parse(e.data);return{internalID:this.getNewInternalId(),type:"json",id:e.id,meta:{displayName:e.displayName,tags:e.tags},data:t.data,fileName:t.fileName}}generateAnimation(t){if("json"===t.dataEncoding){let n;try{n=JSON.parse(t.data)}catch(n){e.warn("could not parse json data of '"+t.id+"'")}return[{internalID:this.getNewInternalId(),type:"animation",meta:{displayName:t.displayName,tags:t.tags},id:t.id,frames:[],frameIds:n.frames,interval:100,flippedHorizontal:n.flippedHorizontal},!0]}return[Object.assign(Object.assign({},y(t)),{internalID:this.getNewInternalId()}),!1]}inflateAnimation(t,n){return t.frames=t.frameIds.map(e=>n.find(t=>t.id===e).bitmap),t.flippedHorizontal&&(t.frames=t.frames.map(t=>{const n=e.sprite.Bitmap.fromData(t),i=new e.sprite.Bitmap(t.width,t.height);for(let e=0;e<i.width;e++)for(let t=0;t<i.height;t++)i.set(e,t,n.get(n.width-e-1,t));return i.data()})),t}generateNewID(t){switch(t){case"animation":return this.generateNewIDInternal("animation",e.sprite.ANIMATION_PREFIX,e.sprite.ANIMATION_NAMESPACE);case"image":return this.generateNewIDInternal("image",e.sprite.IMAGE_PREFIX,e.sprite.IMAGES_NAMESPACE);case"tile":return this.generateNewIDInternal("tile",e.sprite.TILE_PREFIX,e.sprite.TILE_NAMESPACE);case"tilemap":return this.generateNewIDInternal("tilemap",lf("level"));case"song":return this.generateNewIDInternal("song",e.sprite.SONG_PREFIX,e.sprite.SONG_NAMESPACE);case"json":return this.generateNewIDInternal("json",e.sprite.JSON_PREFIX,e.sprite.JSON_NAMESPACE)}}generateNewName(t,n){const i=n||e.getDefaultAssetDisplayName(t);if(!this.isNameTaken(t,i))return i;const s=/^(.*)(\d+)$/.exec(i),r=s?s[1]:i;let a=s?parseInt(s[2],10)+1:1,o=r+a;for(;this.isNameTaken(t,o);)a++,o=r+a;return o}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=n.nextRevision++}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)}else a.mimeType===e.SONG_MIME_TYPE?i.push(this.generateSong(a)):a.mimeType===e.JSON_MIME_TYPE&&i.push(this.generateJsonAsset(a))}for(const e of s)i.push(this.inflateAnimation(e,i));return i}cleanupTemporaryAssets(){const e=this.getAssetCollection("image"),t=e.getSnapshot(e=>{var t;return!e.meta.displayName&&!(null===(t=e.meta.blockIDs)||void 0===t?void 0:t.length)});for(const n of t)e.removeByID(n.id)}getAssetCollection(e,t=!1){return w(t?this.gallery:this.state,e,!0)}}function i(t){const n=[];for(const i of Object.keys(t)){const s=t[i];s.mimeType===e.TILEMAP_MIME_TYPE&&n.push(s)}return n}function s(e,t){const n=" ";return`\n${n}helpers._registerFactory("${e}", function(name: string) {\n${n}${n}switch(helpers.stringTrim(name)) {\n`+t.map(e=>e.keys.filter(e=>!!e).map(e=>`${n}${n}${n}case "${e}":`).join("\n")+`return ${e.expression};`).join("\n")+"\n"+`${n}${n}}\n`+`${n}${n}return null;\n`+`${n}})\n`}function r(t){return e.sprite.Bitmap.fromData(t).copy().data()}function a(t,n){var i;const s=atob(t.data),r=e.U.fromHex(s),a=r[1]|r[2]<<8,o=r[3]|r[4]<<8,l=t.tileset.map(e=>n&&n(e)||{id:e});let c=r[0];c||(c=l.length&&(null===(i=l.find(e=>{var t;return null===(t=e.bitmap)||void 0===t?void 0:t.width}))||void 0===i?void 0:i.bitmap.width)),c=c||16;const u={tileWidth:c,tiles:l},d=r.slice(5,5+a*o),h=new e.sprite.Tilemap(a,o,0,0,new Uint8ClampedArray(d)),p=r.slice(5+d.length),f=new e.sprite.Bitmap(a,o,0,0,new Uint8ClampedArray(p)).data();return new e.sprite.TilemapData(h,u,f)}function o(t,n=!1){switch(t.meta=Object.assign({},t.meta),t.meta.temporaryInfo&&(t.meta.temporaryInfo=Object.assign({},t.meta.temporaryInfo)),t.type){case"tile":case"image":return Object.assign(Object.assign({},t),{bitmap:r(t.bitmap)});case"animation":return Object.assign(Object.assign({},t),{frames:t.frames.map(e=>r(e))});case"tilemap":return Object.assign(Object.assign({},t),{data:t.data.cloneData(n)});case"song":return Object.assign(Object.assign({},t),{song:e.assets.music.cloneSong(t.song)});case"json":return Object.assign(Object.assign({},t),{data:e.U.clone(t.data)})}}function l(e){const t={revision:e.revision,assets:{}};for(const n of Object.keys(e.assets)){const i=e.assets[n];t.assets[n]=i.clone()}return t}function c(e){const t=Object.assign(Object.assign({},e),{assetDiffs:{}});for(const n of Object.keys(e.assetDiffs)){const i=e.assetDiffs[n];t.assetDiffs[n]=u(i)}return t}function u(e){return Object.assign(Object.assign({},e),{before:e.before.map(e=>o(e)),after:e.after.map(e=>o(e))})}function d(t,n){const i=t.id.substr(t.id.lastIndexOf(".")+1),s=t.meta.tags;switch(t.type){case"image":if(n[i]=t.jresData,t.meta.displayName||(null==s?void 0:s.length)){const r={data:t.jresData,mimeType:e.IMAGE_MIME_TYPE};t.meta.displayName&&(r.displayName=t.meta.displayName),(null==s?void 0:s.length)&&(r.tags=s),n[i]=r}break;case"tile":const r={data:t.jresData,mimeType:e.IMAGE_MIME_TYPE,tilemapTile:!0,displayName:t.meta.displayName};(null==s?void 0:s.length)&&(r.tags=s),n[i]=r;break;case"tilemap":const a=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[a.id]=a;break;case"animation":n[i]=function(t){var n;const i={namespace:t.id.substr(0,t.id.lastIndexOf(".")),id:t.id.substr(t.id.lastIndexOf(".")+1),mimeType:e.ANIMATION_MIME_TYPE,data:e.sprite.encodeAnimationString(t.frames,t.interval),displayName:t.meta.displayName};(null===(n=t.meta.tags)||void 0===n?void 0:n.length)&&(i.tags=t.meta.tags);return i}(t);break;case"song":const o={data:e.assets.music.encodeSongToHex(t.song),mimeType:e.SONG_MIME_TYPE,displayName:t.meta.displayName,namespace:e.sprite.SONG_NAMESPACE+"."};(null==s?void 0:s.length)&&(o.tags=s),n[i]=o;break;case"json":const l={data:JSON.stringify({data:t.data,fileName:t.fileName}),mimeType:e.JSON_MIME_TYPE,displayName:t.meta.displayName,namespace:e.sprite.JSON_NAMESPACE+"."};(null==s?void 0:s.length)&&(l.tags=s),n[i]=l}}function h(t,n,i=!1){if(t==n)return!0;if(!t&&n||!n&&t||t.type!==n.type)return!1;if(!(i||t.id===n.id&&e.U.arrayEquals(t.meta.tags,n.meta.tags)&&e.U.arrayEquals(t.meta.blockIDs,n.meta.blockIDs)&&t.meta.displayName===n.meta.displayName))return!1;switch(t.type){case"image":case"tile":return e.sprite.bitmapEquals(t.bitmap,n.bitmap);case"animation":const i=n;return t.interval===i.interval&&e.U.arrayEquals(t.frames,i.frames,e.sprite.bitmapEquals);case"tilemap":return t.data.equals(n.data);case"song":return e.assets.music.songEquals(t.song,n.song);case"json":return t.fileName===n.fileName&&e.U.deepEqual(t.data,n.data)}}function p(e){const t=/^\s*(?:(?:assets\s*\.\s*(image|tile|animation|tilemap|song))|(tilemap))\s*(?:`|\(""")([^`"]*)(?:`|"""\))\s*$/m.exec(e);if(t){return{type:t[1]||t[2],name:t[3].trim()}}}function f(e){return b(e.type,e.id)}function m(t){if(!t)return!1;switch(t.type){case"image":case"tile":return function(t){return!!t.bitmap&&g(e.sprite.Bitmap.fromData(t.bitmap))}(t);case"tilemap":return function(t){var n;if(!(t.data&&t.data.tilemap&&t.data.tileset&&t.data.tileset.tileWidth&&(null===(n=t.data.tileset.tiles)||void 0===n?void 0:n.length)&&t.data.layers))return!1;return g(e.sprite.Bitmap.fromData(t.data.layers))&&g(t.data.tilemap)}(t);case"animation":return function(t){var n;if(!(null===(n=t.frames)||void 0===n?void 0:n.length)||t.interval<=0)return!1;return!t.frames.some(t=>!g(e.sprite.Bitmap.fromData(t)))}(t);case"song":return(n=t).song&&n.song.ticksPerBeat>0&&n.song.beatsPerMeasure>0&&n.song.measures>0&&n.song.beatsPerMinute>0&&!!n.song.tracks;case"json":return!!t.data}var n}function g(e){return e.width>0&&e.height>0&&!Number.isNaN(e.x0)&&!Number.isNaN(e.y0)&&e.data().data.length===e.dataLength()}function b(t,n,i=!1){let s;switch(t){case"image":s=e.sprite.IMAGES_NAMESPACE+".";break;case"tile":s=e.sprite.TILE_NAMESPACE+".";break;case"tilemap":s="";break;case"animation":s=e.sprite.ANIMATION_NAMESPACE+".";break;case"song":s=e.sprite.SONG_NAMESPACE+".";break;case"json":s=e.sprite.JSON_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 y(t){const n=atob(t.data),i=new Uint8ClampedArray(e.U.fromHex(n)),s=v(i,0),r=v(i,2),a=v(i,4),o=v(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,tags:t.tags}}}function v(e,t){return e[t]|e[t+1]<<8}function w(e,n,i=!1){if(!e.assets[n]){if(!i)return;e.assets[n]=new t(n)}return e.assets[n]}n.nextRevision=0,e.TilemapProject=n,e.emitGalleryDeclarations=function(t,n){var i;const s=Object.keys(t),r=" ";let o="";const l={},c={},u={},d=e=>{let n=t[e].namespace||t["*"].namespace;const i=t[e].id||e;return n&&(n.endsWith(".")&&(n=n.slice(0,n.length-1)),!i.startsWith(n+"."))?n+"."+i:i};t["*"]&&(u["*"]=Object.assign(Object.assign({},t["*"]),{namespace:n}));for(const e of s){if("*"===e)continue;const i=t[e],s=d(e);let r=ts.pxtc.escapeIdentifier(i.displayName||s.split(".").pop());if(l[r]){const e=r;let t=2;for(;l[r];)r=e+t,t++}l[r]=!0,c[s]=n+"."+r}for(const l of s){if("*"===l)continue;const s=t[l];let h,p,f=s.mimeType||(null===(i=t["*"])||void 0===i?void 0:i.mimeType);const m=c[d(l)].split(".").pop();let g=s.tags;if(!g&&(g=[],-1!==m.toLowerCase().indexOf("background")&&g.push("background"),-1!==m.toLowerCase().indexOf("dialog")&&g.push("dialog"),s.tilemapTile)){let e;if(g.push("tile"),s.displayName&&-1!==s.displayName.indexOf("--")){e=s.displayName.split("--")[1].trim().split(/[\s\-]+/g).map((e,t)=>0===t?e:e.charAt(0).toUpperCase()+e.slice(1)).join("")}e||/^transparency(?:4|8|16|32)$/.test(m)||(e=n),e&&g.push("category-"+e)}if(f===e.IMAGE_MIME_TYPE)p="image.ofBuffer(hex``)",h=s.tilemapTile?"images._tile":"images._image";else if(f===e.ANIMATION_MIME_TYPE){p=`[${y(s).frames.map(t=>e.sprite.bitmapToImageLiteral(e.sprite.Bitmap.fromData(t),"typescript")).join(",")}]`}else if(f===e.TILEMAP_MIME_TYPE){const t=a(s);p=e.sprite.encodeTilemap(t,"typescript",c)}else f===e.SONG_MIME_TYPE?p=`hex\`${s.data}\``:f===e.JSON_MIME_TYPE&&(p=s.data);o+=`${r}//% fixedInstance jres whenUsed\n`,h&&(o+=`${r}//% blockIdentity=${h}\n`),g.length&&(o+=`${r}//% tags="${g.join(" ")}"\n`),o+=`${r}export const ${m} = ${p};\n`,"string"==typeof s?u[m]=s:(u[m]=Object.assign(Object.assign({},s),{id:c[d(l)],tags:g}),s.namespace&&(u[m].namespace=n,s.namespace.endsWith(".")&&(u[m].namespace+=".")),u[m].tileset&&(u[m].tileset=s.tileset.map(e=>c[e]||e)))}const h=lf("Auto-generated code. Do not edit.");return[u,`// ${h}\nnamespace ${n} {\n${o}\n}\n// ${h}\n`]},e.emitTilemapsFromJRes=function(t){const n=Object.keys(t),i=" ";let r="";const o=[],l=[];for(const s of n){if("*"===s)continue;const n=t[s];if(n.tilemapTile){let e=s;-1!==e.indexOf(".")&&(e=e.split(".").slice(-1)[0]),r+=`${i}//% fixedInstance jres blockIdentity=images._tile\n`,r+=`${i}export const ${e} = image.ofBuffer(hex\`\`);\n`,l.push({keys:[n.displayName,b("tile",s,!0)],expression:s})}if(n.mimeType===e.TILEMAP_MIME_TYPE){const t=a(n);o.push({keys:[n.displayName,b("tilemap",n.id)],expression:e.sprite.encodeTilemap(t,"typescript")})}}o.length&&(r+=s("tilemap",o)),l.length&&(r+=s("tile",l));const c=lf("Auto-generated code. Do not edit.");return`// ${c}\nnamespace ${e.sprite.TILE_NAMESPACE} {\n${r}\n}\n// ${c}\n`},e.emitProjectImages=function(t){const n=Object.keys(t);let i="";const r=[],a=[],o=[],l=[];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=[b("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=y(n);a.push({keys:[n.displayName,b("animation",i,!0)],expression:`[${t.frames.map(t=>e.sprite.bitmapToImageLiteral(e.sprite.Bitmap.fromData(t),"typescript")).join(", ")}]`})}else n.mimeType===e.SONG_MIME_TYPE?o.push({keys:[b("song",i,!0),n.displayName],expression:`hex\`${n.data}\``}):n.mimeType===e.JSON_MIME_TYPE&&l.push({keys:[b("json",i,!0),n.displayName],expression:n.data})}const c=lf("Auto-generated code. Do not edit.");return i+=s("image",r),i+=s("animation",a),i+=s("song",o),i+=s("json",l),`// ${c}\nnamespace ${e.sprite.IMAGES_NAMESPACE} {\n${i}\n}\n// ${c}\n`},e.cloneAsset=o,e.assetEquals=h,e.validateAssetName=function(e){return!!e&&!/[\u0000-\u001f\u0021-\u002c\u002e\u002f\u003a-\u0040\u005b-\u005e\u0060\u007b-\u007f]/.test(e)},e.getTSReferenceForAsset=function(e,t=!1){var n;let i;if(i=(null===(n=e.meta)||void 0===n?void 0:n.displayName)?e.meta.displayName:f(e),!i)return"image"===e.type||"tile"===e.type?e.id:void 0;const s=t?'("""':"`",r=t?'""")':"`";switch(e.type){case"tile":return`assets.tile${s}${i}${r}`;case"image":return`assets.image${s}${i}${r}`;case"animation":return`assets.animation${s}${i}${r}`;case"tilemap":return`tilemap${s}${i}${r}`;case"song":return`assets.song${s}${i}${r}`;case"json":return`assets.json${s}${i}${r}`}},e.parseAssetTSReference=p,e.lookupProjectAssetByTSReference=function(e,t){const n=p(e);if(n){const{type:e,name:i}=n;switch(e){case"tile":return t.lookupAssetByName("tile",i);case"image":return t.lookupAssetByName("image",i);case"tilemap":return t.lookupAssetByName("tilemap",i)||t.lookupAsset("tilemap",i);case"animation":return t.lookupAssetByName("animation",i);case"song":return t.lookupAssetByName("song",i);case"json":return t.lookupAssetByName("json",i)}}},e.getDefaultAssetDisplayName=function(e){switch(e){case"image":return lf("myImage");case"tile":return lf("myTile");case"tilemap":return lf("level");case"animation":return lf("myAnim");case"song":return lf("mySong");case"json":return lf("myFile");default:return lf("asset")}},e.getShortIDForAsset=f,e.validateAsset=m,e.patchTemporaryAsset=function(e,t,n){if(!e||h(e,t)||t.id!==e.id)return t;t=o(t,!0);const i=-1===e.internalID,s=-1===t.internalID&&void 0===t.meta.displayName;return i&&!s&&(t.id=n.generateNewID(t.type),t.internalID=n.getNewInternalId()),t}}(pxt||(pxt={})),function(e){!function(t){const n={};t.blockColors={loops:"#107c10",logic:"#006970",math:"#712672",variables:"#A80000",functions:"#005a9e",text:"#996600",arrays:"#A94400",advanced:"#3c3c3c",addpackage:"#717171",search:"#000",debug:"#e03030",default:"#dddddd",topblocks:"#aa8f00",recipes:"#717171"},t.blockIcons={loops:"",logic:"",math:"",variables:"",functions:"",text:"",arrays:"",advancedcollapsed:"",advancedexpanded:"",more:"",addpackage:"",search:"",debug:"",default:"",topblocks:"",recipes:""};let i="";function s(e){const t=function(e,t,n){let i=0,s=0,r=0;if(0==t)i=n,s=n,r=n;else{let 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`#${r(t[0])}${r(t[1])}${r(t[2])}`}function r(e){const t=e.toString(16);return 1==t.length?"0"+t:t}function a(t){var i,s;return(null===(s=null===(i=e.appTarget)||void 0===i?void 0:i.appTheme)||void 0===s?void 0:s.adjustBlockContrast)?(n[t]||(n[t]=e.getWhiteContrastingBackground(t)),n[t]):t}t.appendToolboxIconCss=function(t,n){if(!(i.indexOf(t)>-1))if(1===n.length){const s=e.Util.unicodeToChar(n);i+=`\n .blocklyTreeIcon.${t}::before {\n content: "${s}";\n }\n `}else i+=`\n .blocklyTreeIcon.${t} {\n background-image: url("${e.Util.pathJoin(e.webConfig.commitCdnUrl,encodeURI(n))}")!important;\n width: 30px;\n height: 100%;\n background-size: 20px !important;\n background-repeat: no-repeat !important;\n background-position: 50% 50% !important;\n }\n `},t.getNamespaceColor=function(t){let n;return t=t.toLowerCase(),e.appTarget.appTheme.blockColors&&e.appTarget.appTheme.blockColors[t]?n=e.appTarget.appTheme.blockColors[t]:e.toolbox.blockColors[t]&&(n=e.toolbox.blockColors[t]),n?a(n):""},t.getNamespaceIcon=function(t){return t=t.toLowerCase(),e.appTarget.appTheme.blockIcons&&e.appTarget.appTheme.blockIcons[t]?e.appTarget.appTheme.blockIcons[t]:e.toolbox.blockIcons[t]?e.toolbox.blockIcons[t]:""},t.advancedTitle=function(){return e.Util.lf("{id:category}Advanced")},t.addPackageTitle=function(){return e.Util.lf("{id:category}Extensions")},t.recipesTitle=function(){return e.Util.lf("{id:category}Tutorials")},t.convertColor=function(e){var t;e=(t=e)?"0x"==t.substring(0,2)?"#"+t.substring(2):t:"#000000";const n=parseInt(e);return isNaN(n)?e:s(n)},t.hueToRgb=s,t.fadeColor=function(e,t,n){(e=e.replace(/[^0-9a-f]/gi,"")).length<6&&(e=e[0]+e[0]+e[1]+e[1]+e[2]+e[2]);let i="#";for(let s=0;s<3;s++){let r=parseInt(e.substr(2*s,2),16);r=Math.round(Math.min(Math.max(0,n?r+r*t:r-r*t),255));let a=r.toString(16);i+=("00"+a).substr(a.length)}return i},t.getAccessibleBackground=a}(e.toolbox||(e.toolbox={}))}(pxt||(pxt={})),function(e){!function(t){const n=/^##[^#](.*)$([\s\S]*?)(?=^##[^#]|$(?![\r\n]))/gim,i=/^###[^#](.*)$([\s\S]*?)(?=^###[^#]|$(?![\r\n]))/gim;function s(){return/``` *(sim|block|blocks|filterblocks|spy|ghost|typescript|ts|js|javascript|template|python|jres|assetjson|customts|simtheme|python-template|ts-template|typescript-template|js-template|javascript-template|hiddennamespaces)\s*\n([\s\S]*?)\n```/gim}function r(t,i,s){let r=i||n,c=[];if(t.replace(r,function(e,t,n){n=n.trim();let{header:i,hint:r}=function(e,t){e=l(e);let n,i=e;if(t){const t=/#+ ~ tutorialhint([\s\S]*)/i;i=e.replace(t,function(e,t){return n=t,""})}else{const t=/(^[\s\S]*?\S)\s*((```|\[?\!\[[\s\S]+?\]\(\S+?\)\]?)[\s\S]*)/im;let s=e.match(t);s&&s.length>2&&(i=s[1].trim(),n=s[2].trim())}return{header:i,hint:n}}(n,s&&s.explicitHints);const u=a("local",n),d=o("local",n);let h={title:t.match(/^\{.*\}$/)?void 0:t.replace(/@(fullscreen|unplugged|showdialog|showhint|tutorialCompleted|resetDiff)/gi,"").trim(),contentMd:n,headerContentMd:i,localBlockConfig:u,localValidationConfig:d};return/@(fullscreen|unplugged|showdialog|showhint)/i.test(t)&&(h.showHint=!0),/@(unplugged|showdialog)/i.test(t)&&(h.showDialog=!0),/@tutorialCompleted/.test(t)&&(h.tutorialCompleted=!0),/@resetDiff/.test(t)&&(h.resetDiff=!0),r&&(h.hintContentMd=r),c.push(h),""}),0!=t.indexOf("# Not found"))return c;e.debug("tutorial not found")}function a(e,t){let n={md:"",blocks:[]};const i=new RegExp(`\`\`\`\\s*blockconfig\\.${e}\\s*\\n([\\s\\S]*?)\\n\`\`\``,"gmi");return t.replace(i,(e,t)=>(n.md+=`${t}\n`,"")),n}function o(t,n){let i;const s=new RegExp(`\`\`\`\\s*validation\\.${t}\\s*\\n([\\s\\S]*?)\\n\`\`\``,"gmi");if(n.replace(s,(e,t)=>(i=t,"")),!i||""==i)return null;return{validatorsMetadata:e.getSectionsFromMarkdownMetadata(i).map(e=>({validatorType:e.header,properties:e.attributes}))}}function l(e){if(!e)return e;return e.replace(/```(filterblocks|package|ghost|config|template|jres|assetjson|simtheme|customts|hiddennamespaces|blockconfig\.local|blockconfig\.global|validation\.local|validation\.global)\s*\n([\s\S]*?)\n```/gim,"").trim()}function c(t){if(!t)return;const n=JSON.parse(t);return{[e.TILEMAP_JRES]:n[e.TILEMAP_JRES],[e.TILEMAP_CODE]:n[e.TILEMAP_CODE],[e.IMAGES_JRES]:n[e.IMAGES_JRES],[e.IMAGES_CODE]:n[e.IMAGES_CODE]}}function u(t){const n=e.Util.jsonTryParse(t);if(!n)return;const i={};return n.theme&&(i.theme=n.theme),n.palette&&(i.palette=n.palette),i}t.parseTutorial=function(t){const{metadata:s,body:d}=function(t){const n=/### @(\S+) ([ \S]+)/gi,i={},s=t.replace(n,function(e,t,n){try{i[t]=JSON.parse(n)}catch(e){i[t]=n}return""}),r=i;void 0!==r.explicitHints&&e.appTarget.appTheme&&e.appTarget.appTheme.tutorialExplicitHints&&(r.explicitHints=!0);return{metadata:r,body:s}}(t),{steps:h,activities:p}=function(e,t){if(t&&t.activities)return function(e,t){let s=[],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}}}(d,s),f=function(e){let t=e.match(/^#[^#](.*)$/im);return t&&t.length>1?t[1].trim():null}(d);if(!h)return;const{code:m,templateCode:g,templateLanguage:b,editor:y,language:v,jres:w,assetJson:A,customTs:k,simThemeJson:T,hiddenNamespaces:x}=function(t){let n;const i=/``` *(sim|block|blocks|filterblocks|spy|ghost|typescript|ts|js|javascript|template|python|jres|assetjson|customts|simtheme|python-template|ts-template|typescript-template|js-template|javascript-template|hiddennamespaces)\s*\n([\s\S]*?)\n```/gim;let s,r,a,o,l,c,u,d,h=[];return t.replace(/((?!.)\s)+/g,"\n").replace(i,function(t,n,i){switch(n){case"block":case"blocks":case"blockconfig.local":case"blockconfig.global":case"filterblocks":if(!p(e.BLOCKS_PROJECT_NAME))return;break;case"spy":case"python":if(!p(e.PYTHON_PROJECT_NAME))return;"python"==n&&(o=n);break;case"typescript":case"ts":case"javascript":case"js":if(!p(e.JAVASCRIPT_PROJECT_NAME))return;break;case"template":r=i;break;case"python-template":if(!p(e.PYTHON_PROJECT_NAME))return;r=i,a="python",o="python";break;case"ts-template":case"typescript-template":case"js-template":case"javascript-template":if(!p(e.JAVASCRIPT_PROJECT_NAME))return;r=i,a="typescript";break;case"jres":s=i;break;case"assetjson":l=i;break;case"simtheme":u=i;break;case"customts":c=i,i="";break;case"hiddennamespaces":d=i.split(/\s/m).map(e=>e.trim()).filter(e=>!!e),i=""}return h.push("python"===o?`\n${i}\n`:`{\n${i}\n}`),""}),n=n||e.BLOCKS_PROJECT_NAME,{code:h,templateCode:r,templateLanguage:a,editor:n,language:o,jres:s,assetJson:l,customTs:c,simThemeJson:u,hiddenNamespaces:d};function p(t){return n&&n!=t?(e.debug("tutorial ambiguous: contains snippets of different types"),!1):(n=t,!0)}}(d);e.BrowserUtils.useOldTutorialLayout()&&"python"===v&&s.flyoutOnly&&(s.flyoutOnly=!1,s.hideToolbox=!0),(!0===s.diffs||!1!==s.diffs&&!0!==s.noDiffs&&(y==e.BLOCKS_PROJECT_NAME&&e.appTarget.appTheme.tutorialBlocksDiff||y!=e.BLOCKS_PROJECT_NAME&&e.appTarget.appTheme.tutorialTextDiff))&&function(e,t){let n;function i(e){const t={typescript:"diff",spy:"diffspy",blocks:"diffblocks",python:"diff"},i=/\s*(\/\/|#)\s*@highlight/gm;return e?e.replace(/```(typescript|spy|python|blocks|ghost|template)((?:.|[\r\n])+)```/,function(e,s,r){const 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)}})}(h,p);const E=c(A),C=u(T),I=a("global",t),S=o("global",t);return h.forEach(e=>{e.contentMd=l(e.contentMd),e.headerContentMd=l(e.headerContentMd),e.hintContentMd=l(e.hintContentMd)}),{editor:y,title:f,steps:h,activities:p,code:m,templateCode:g,templateLanguage:b,metadata:s,language:v,jres:w,assetFiles:E,customTs:k,globalBlockConfig:I,globalValidationConfig:S,simTheme:C,hiddenNamespaces:x}},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,templateLanguage:o.templateLanguage,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,globalBlockConfig:o.globalBlockConfig,globalValidationConfig:o.globalValidationConfig,simTheme:o.simTheme,hiddenNamespaces:o.hiddenNamespaces},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,t.highlightBlocks,t.validateBlocks)}else for(let t of Object.keys(i)){const n=i[t];n.usedBlocks&&n.hash&&e.setWithHashAsync(t,n.snippetBlocks,n.hash,n.highlightBlocks,n.validateBlocks)}}).catch(e=>{}):Promise.resolve()},t.resolveLocalizedMarkdown=function(t,n,i){let s,r=i||t.fileName||"README";r.endsWith(".md")||(r+=".md");const[a,o,l]=e.Util.normalizeLanguageCode(e.Util.userLanguage());return s=a&&o&&l?n[`_locales/${a}/${r}`]||n[`_locales/${l}/${r}`]||n[`_locales/${o}/${r}`]:n[`_locales/${a}/${r}`],s=s||n[r],s},t.parseAssetJson=c,t.parseSimThemeJson=u,t.getTutorialHighlightedBlocks=async function(t){const n=await e.BrowserUtils.tutorialInfoDbAsync(),i=await n.getAsync(t.tutorial,t.tutorialCode);return null==i?void 0:i.highlightBlocks},t.getTutorialValidateBlocks=async function(t){const n=await e.BrowserUtils.tutorialInfoDbAsync(),i=await n.getAsync(t.tutorial,t.tutorialCode);return null==i?void 0:i.validateBlocks},t.getRequiredBlockCounts=function(e){if(!e)return;const t={},n=e["validate-exists"];return n&&n.forEach(e=>{t[e]=(t[e]||0)+1}),t},t.getTutorialStepHash=function(t){const{tutorialStepInfo:n,tutorialStep:i}=t,s=function(e){let t=[];return null==e||e.replace(/((?!.)\s)+/g,"\n").replace(/``` *(block|blocks)\s*\n([\s\S]*?)\n```/gim,function(e,n,i){return t.push(`{\n${i}\n}`),""}),t}(n[i].hintContentMd);return e.BrowserUtils.getTutorialCodeHash(s)},t.shouldFilterProject=function(e){return!!e&&!(!e.hideFromProjects&&!e.hideIteration)}}(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]=255&this.flashOffset,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(){var e,t;this.enabled||(this.enabled=!0,this.log("registering webusb events"),null===(e=navigator.usb)||void 0===e||e.addEventListener("disconnect",this.handleUSBDisconnected,!1),null===(t=navigator.usb)||void 0===t||t.addEventListener("connect",this.handleUSBConnected,!1))}disable(){var e,t;this.enabled&&(this.enabled=!1,this.log("unregistering webusb events"),null===(e=navigator.usb)||void 0===e||e.removeEventListener("disconnect",this.handleUSBDisconnected),null===(t=navigator.usb)||void 0===t||t.removeEventListener("connect",this.handleUSBConnected))}async disposeAsync(){this.disable()}handleUSBDisconnected(e){var t;this.log("device disconnected"),e.device==this.dev&&(this.log("clear device"),this.clearDev(),null===(t=this.onDeviceConnectionChanged)||void 0===t||t.call(this,!1))}handleUSBConnected(e){var t;const n=e.device;this.log(`device connected ${n.serialNumber}`),this.dev||this.connecting||(this.log("attach device"),null===(t=this.onDeviceConnectionChanged)||void 0===t||t.call(this,!0))}clearDev(){var e;this.dev&&(this.dev=null,this.epIn=null,this.epOut=null,null===(e=this.onConnectionChanged)||void 0===e||e.call(this))}error(t){throw new n(e.U.lf("USB error on device {0} ({1})",this.dev.productName,t))}log(t){e.debug("webusb: "+t)}async disconnectAsync(){if(this.ready=!1,this.dev){this.log("close device");try{await this.dev.close()}catch(e){}this.clearDev(),await e.U.delay(500)}}async forgetAsync(){var e;if(!(null===(e=this.dev)||void 0===e?void 0:e.forget))return!1;try{const e=this.dev;return await this.disconnectAsync(),await e.forget(),!0}catch(e){return!1}}async reconnectAsync(){this.log("reconnect"),this.setConnecting(!0);try{await this.disconnectAsync();const e=await o();await this.connectAsync(e)}finally{this.setConnecting(!1)}}setConnecting(e){var t;e!=this.connecting&&(this.connecting=e,null===(t=this.onConnectionChanged)||void 0===t||t.call(this))}isConnecting(){return this.connecting}isConnected(){return!!this.dev&&this.ready}async connectAsync(t){if(this.log(`trying to connect (${t.length} devices)`),0==t.length){const e=new Error("Device not found.");throw e.type="devicenotfound",e}this.setConnecting(!0);try{if(this.lastKnownDeviceSerialNumber){const n=t.find(e=>e.serialNumber===this.lastKnownDeviceSerialNumber);n?(this.log("last known device spotted"),t.splice(t.indexOf(n),1),t.unshift(n)):(this.log("delay for last known device"),await e.U.delay(2e3))}for(let e=0;e<t.length;++e){const n=t[e];this.dev=n,this.log(`connect device: ${n.manufacturerName} ${n.productName}`),this.log(`serial number: ${n.serialNumber} ${this.lastKnownDeviceSerialNumber===n.serialNumber?"(last known device)":""} `);try{return void await this.initAsync()}catch(e){this.dev=void 0,this.log(`connection failed, ${e.message}`)}}const n=new Error(e.U.lf("Device in use or not found."));throw n.type="devicelocked",n}finally{this.setConnecting(!1)}}async sendPacketAsync(t){if(!this.dev)throw new Error("Disconnected");if(e.Util.assert(t.length<=64),this.epOut){"ok"!=(await this.dev.transferOut(this.epOut.endpointNumber,t)).status&&this.error("USB OUT transfer failed")}else{"ok"!=(await this.dev.controlTransferOut({requestType:"class",recipient:"interface",request:9,value:512,index:this.iface.interfaceNumber},t)).status&&this.error("USB CTRL OUT transfer failed")}}async readLoop(){if(!this.readLoopStarted)for(this.readLoopStarted=!0,this.log("start read loop");;)if(this.ready)try{const t=await this.recvPacketAsync();t[0]?this.onData(t):await e.U.delay(500)}catch(t){this.dev&&this.onError(t),await e.U.delay(300)}else await e.U.delay(300)}async recvPacketAsync(e){const t=Date.now();for(;!e||Date.now()<t+e;){if(!this.dev)throw new Error("Disconnected");const e=await(this.epIn?this.dev.transferIn(this.epIn.endpointNumber,64):this.dev.controlTransferIn({requestType:"class",recipient:"interface",request:1,value:256,index:this.iface.interfaceNumber},64));"ok"!=e.status&&this.error("USB IN transfer failed");let t=new Uint8Array(e.data.buffer);if(0!=t.length)return t}this.error("USB IN timed out")}async initAsync(){var n;if(!this.dev)throw new Error("Disconnected");const i=this.dev;this.log("open device"),await i.open(),this.log("select configuration"),await i.selectConfiguration(1);this.log("got "+i.configurations[0].interfaces.length+" interfaces");const s=i.configurations[0].interfaces.filter(e=>{let n=e.alternates[0];for(let e of t.filters)if((null==e.classCode||n.interfaceClass===e.classCode)&&!(null!=e.subclassCode&&n.interfaceSubclass!==e.subclassCode||null!=e.protocolCode&&n.interfaceProtocol!==e.protocolCode)){if(0==n.endpoints.length)return!0;if(2==n.endpoints.length&&n.endpoints.every(e=>64==e.packetSize))return!0}return!1});let a=s[s.length-1];this.log(`${s.length} matching interfaces; picking ${a?"#"+a.interfaceNumber:"n/a"}`),a||this.error("cannot find supported USB interface"),this.altIface=a.alternates[0],this.iface=a,this.altIface.endpoints.length?(this.log("using dedicated endpoints"),this.epIn=this.altIface.endpoints.filter(e=>"in"==e.direction)[0],this.epOut=this.altIface.endpoints.filter(e=>"out"==e.direction)[0],e.Util.assert(64==this.epIn.packetSize),e.Util.assert(64==this.epOut.packetSize)):this.log("using ctrl pipe"),this.log("claim interface"),await i.claimInterface(a.interfaceNumber),this.log("device ready"),this.lastKnownDeviceSerialNumber=this.dev.serialNumber,this.ready=!0,r&&this.readLoop(),null===(n=this.onConnectionChanged)||void 0===n||n.call(this)}}async function o(){var t;e.log("webusb: get devices");try{return await(null===(t=navigator.usb)||void 0===t?void 0:t.getDevices())||[]}catch(t){return e.reportException(t),[]}}async function l(){var t,n;if(void 0!==s)return;if(e.debug("webusb: checking availability"),!(null===(n=null===(t=e.appTarget)||void 0===t?void 0:t.compile)||void 0===n?void 0:n.webUSB))return void(s=!1);const i=await c();if(i)switch(s=!1,e.tickEvent("webusb.off",{reason:i}),i){case"electron":e.debug("webusb: off, electron");break;case"notimpl":e.debug("webusb: off, not implemented by browser");break;case"oldwindows":e.debug("webusb: off, older windows version");break;case"security":e.debug("webusb: off, security exception")}else s=!0}async function c(){if(e.BrowserUtils.isElectron())return"electron";const t=navigator.usb;if(!t)return"notimpl";let n=/Windows NT (\d+\.\d+)/.exec(navigator.userAgent);if(n&&parseFloat(n[1])<6.3)return"oldwindows";try{await t.getDevices()}catch(e){return"security"}}function u(){return void 0===s&&(e.error("checkAvailableAsync not called"),l()),!!s}t.pairAsync=async function(){var e;try{return!!await(null===(e=navigator.usb)||void 0===e?void 0:e.requestDevice({filters:t.filters}))}catch(e){if("NotFoundError"==e.name)return;throw e}},t.tryGetDevicesAsync=o,t.mkWebUSBHIDPacketIOAsync=function(){return e.debug("packetio: mk webusb io"),i||(i=new a),i.enable(),Promise.resolve(i)},t.forgetDeviceAsync=async function(){return e.debug("packetio: forget webusb io"),!!i&&i.forgetAsync()},t.isEnabled=!1,t.setEnabled=function(e){u()||(e=!1),t.isEnabled=e},t.checkAvailableAsync=l,t.getReasonUnavailable=c,t.isAvailable=u}(e.usb||(e.usb={}))}(pxt||(pxt={})),function(e){!function(t){var n=e.Util;let i={};function s(e){let t={},i=0,s=new n.PromiseQueue,r=new Promise((e,n)=>{t.ready=e});s.enqueue("main",()=>r);return{opAsync:function(n,r){return s.enqueue("main",()=>new Promise((s,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(Measurements.WebworkerRecvHandler),i.recvHandler(t.data),e.perf.measureEnd(Measurements.WebworkerRecvHandler)},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=u("opcode name doesn't match","<name>");class s{constructor(t,n,i,s,r){this.opcode=i,this.mask=s,this.is32bit=r,this.canBeShared=!1,e.assert((i&s)==i),this.ei=t,this.code=n.replace(/\s+/g," "),this.friendlyFmt=n.replace(/\$\w+/g,e=>this.ei.encoders[e]?this.ei.encoders[e].pretty:e);let a=l(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=[],l=null,c=null,d=null;for(let i=0;i<this.args.length;++i){let h=this.args[i],p=n[r++];if("$"==h[0]){let i=this.ei.encoders[h],f=null;if(i.isRegister){if(f=this.ei.registerNo(p),null==f)return u("expecting register name",p);this.ei.isPush(this.opcode)?a++:this.ei.isPop(this.opcode)&&a--}else if(i.isImmediate){if(p=p.replace(/^#/,""),f=t.bin.parseOneInt(p),null==f)return u("expecting number",p);this.ei.isAddSP(this.opcode)?a=-f/this.ei.wordSize():this.ei.isSubSP(this.opcode)&&(a=f/this.ei.wordSize())}else if(i.isRegList){if("{"!=p)return u("expecting {",p);for(f=0;"}"!=n[r];){if(p=n[r++],!p)return u("expecting }",n[r-2]);let e=this.ei.registerNo(p);if(null==e)return u("expecting register name",p);if(f&1<<e)return u("duplicate register name",p);f|=1<<e,this.ei.isPush(this.opcode)?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),l="rel"+f;else if(/^0x[0-9a-fA-F]+$/.test(p))f=parseInt(p,16),l="abs"+f;else if(l=p,f=this.ei.getAddressFromLabel(t.bin,this,p,i.isWordAligned),null==f){if(t.bin.finalEmit)return u("unknown label",p);f=8}if(this.ei.is32bit(this)){c=f,d=p;continue}}else e.oops();if(null==f)return u("didn't understand it",p);if(o.push(f),f=i.encode(f),null==f)return u("argument out of range or mis-aligned",p);e.assert(0==(s&f)),s|=f}else if(h!=p)return u("expecting "+h,p)}return n[r]?u("trailing tokens",n[r]):this.ei.is32bit(this)?this.ei.emit32(s,c,t.bin.normalizeExternalLabel(d)):{stack:a,opcode:s,numArgs:o,labelName:t.bin.normalizeExternalLabel(l)}}toString(){return this.friendlyFmt}}t.Instruction=s;class r{constructor(e,t){this.bin=e,this.text=t}getOpExt(){return this.instruction?this.instruction.code:""}getOp(){return this.instruction?this.instruction.name:""}update(e){this.bin.peepOps++,(e=e.replace(/^\s*/,""))||this.bin.peepDel++,e&&(e+=" "),e=" "+e,this.text=e+"; WAS: "+this.text.trim(),this.instruction=null,this.numArgs=null,this.words=l(e)||[],0==this.words.length?this.type="empty":"@"==this.words[0][0]&&(this.type="directive")}}t.Line=r;class a{constructor(e,t){this.id=e,this.description=t,this.sizeAdj=0,this.users=[]}get size(){return this.endLocation-this.startLocation-this.sizeAdj}}class o{constructor(e){this.baseOffset=0,this.checkStack=!0,this.inlineMode=!1,this.normalizeExternalLabel=e=>e,this.currLineNo=0,this.scope="",this.scopeId=0,this.errors=[],this.labels={},this.equs={},this.stackpointers={},this.stack=0,this.commPtr=0,this.peepOps=0,this.peepDel=0,this.peepCounts={},this.stats="",this.throwOnError=!1,this.disablePeepHole=!1,this.stackAtLabel={},this.codeSizeStats=!1,this.labelToObject={},this.idToObject={},this.objSuspendStart=0,this.labelsToObjectDone=!1,this.currLine=new r(this,"<start>"),this.currLine.lineNo=0,this.ei=e,this.ei.file=this}emitShort(t){e.assert(0<=t&&t<=65535),this.buf.push(t)}emitOpCode(e){this.emitShort(e)}location(){return 2*this.buf.length}pc(){return this.location()+this.baseOffset}useLabel(t){if(!this.currObject||"."==t[0]||this.objSuspendStart)return;const n=e.U.lookup(this.labelToObject,t);n&&n!=this.currObject&&n.users.length<5&&n.users.indexOf(this.currObject)<0&&n.users.push(this.currObject)}parseOneInt(t){if(!t)return null;if(/^\d+$/.test(t))return parseInt(t,10);const i=t.indexOf("-");if(i>0)return this.parseOneInt(t.slice(0,i))-this.parseOneInt(t.slice(i+1));let s=1;if(t.indexOf("*")>=0){let e=null;for(;null!=(e=/^([^\*]*)\*(.*)$/.exec(t));){let n=this.parseOneInt(e[1]);if(null==n)return null;s*=n,t=e[2]}}if("-"==t[0]?(s*=-1,t=t.slice(1)):"+"==t[0]&&(t=t.slice(1)),/^\d+$/.test(t))return s*parseInt(t,10);if(e.U.endsWith(t,"|1"))return 1|this.parseOneInt(t.slice(0,t.length-2));if(e.U.endsWith(t,"-1"))return this.parseOneInt(t.slice(0,t.length-2))-1;if(e.U.endsWith(t,"+1"))return this.parseOneInt(t.slice(0,t.length-2))+1;let r=/(.*)>>(\d+)$/.exec(t);if(r){let e=this.parseOneInt(r[1]);return e&=~(-16777216&this.baseOffset),e>>parseInt(r[2])}let 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){this.useLabel(e);let i=null,s=this.scopedName(e);return this.labels.hasOwnProperty(s)?(i=this.labels[s],i=this.ei.postProcessRelAddress(this,i)):this.lookupExternalLabel&&(i=this.lookupExternalLabel(e),null!=i&&(i=this.ei.postProcessAbsAddress(this,i))),null==i&&this.equs.hasOwnProperty(s)&&(i=this.equs[s]),null==i&&t&&(this.finalEmit?this.directiveError(n("unknown label: {0}",e)):i=11111),i}align(t){for(e.assert(2==t||4==t||8==t||16==t);this.location()%t!=0;)this.emitOpCode(0)}pushError(e,t=""){let i={scope:this.scope,message:n(" -> Line {2} ('{1}'), error: {0}\n{3}",e,this.currLine.text,this.currLine.lineNo,t),lineNo:this.currLine.lineNo,line:this.currLine.text,coremsg:e,hints:t};if(this.errors.push(i),this.throwOnError)throw new Error(i.message)}directiveError(e){this.pushError(e)}emitString(e,t=!1){function i(e,t){return 255&(e.charCodeAt(t)||0)}let s,r=/^\s*([\w\.]+\s*:\s*)?.\w+\s+(".*")\s*$/.exec(e);if(r&&null!=(s=c(r[2])))if(this.align(2),t)for(let e=0;e<s.length;e++)this.emitShort(s.charCodeAt(e));else for(let e=0;e<s.length+1;e+=2)this.emitShort(i(s,e+1)<<8|i(s,e));else this.directiveError(n("expecting string"))}parseNumber(e){let t=this.parseOneInt(e.shift());return null==t?null:t}parseNumbers(e){e=e.slice(1);let t=[];for(;;){let i=this.parseNumber(e);if(null==i){this.directiveError(n("cannot parse number at '{0}'",e[0]));break}if(t.push(i),","!=e[0]){if(null==e[0])break;this.directiveError(n("expecting number, got '{0}'",e[0]));break}if(e.shift(),null==e[0])break}return t}emitSpace(e){let t=this.parseNumbers(e);if(1==t.length&&t.push(0),2!=t.length)this.directiveError(n("expecting one or two numbers"));else if(t[0]%2!=0)this.directiveError(n("only even space supported"));else{let e=255&t[1];e|=e<<8;for(let n=0;n<t[0];n+=2)this.emitShort(e)}}emitBytes(e){let t=this.parseNumbers(e);t.length%2!=0&&(this.directiveError(".bytes needs an even number of arguments"),t.push(0));for(let e=0;e<t.length;e+=2){let i=t[e],s=t[e+1];0<=i&&s<=255&&0<=s&&i<=255?this.emitShort(255&i|(255&s)<<8):this.directiveError(n("expecting uint8"))}}emitHex(e){e.slice(1).forEach(e=>{if(","!=e)if(e.length%4!=0)this.directiveError(".hex needs an even number of bytes");else if(/^[a-f0-9]+$/i.test(e))for(let t=0;t<e.length;t+=4){let n=parseInt(e.slice(t,t+4),16);n=(255&n)<<8|n>>8&255,this.emitShort(n)}else this.directiveError(".hex needs a hex number")})}handleDirective(t){let i,s=t.words,r=()=>{2!=s.length&&this.directiveError(n("expecting one argument"))};switch(s[0]){case".object":if(this.codeSizeStats)if("PUSH"==s[1])this.objSuspendStart=this.location();else if("POP"==s[1])this.objSuspendStart&&(this.currObject.sizeAdj+=this.location()-this.objSuspendStart),this.objSuspendStart=0;else{if(this.currObject&&(this.currObject.endLocation=this.location()),this.currObject=e.U.lookup(this.idToObject,s[1]),!this.currObject){const e=t.text.replace(/^[^"]*/,"");let i=s[1];s.length>2&&(i=c(e.trim()),null==i&&this.directiveError(n("expecting string in .object"))),this.currObject=new a(s[1],i),this.idToObject[s[1]]=this.currObject}this.currObject.sizeAdj=0,this.currObject.startLocation=this.location()}else;break;case".ascii":case".asciz":case".string":this.emitString(t.text);break;case".utf16":this.emitString(t.text,!0);break;case".align":if(r(),i=this.parseOneInt(s[1]),null!=i){if(0==i)return;i<=4?this.align(1<<i):this.directiveError(n("expecting 1, 2, 3 or 4 (for 2, 4, 8, or 16 byte alignment)"))}else this.directiveError(n("expecting number"));break;case".balign":if(r(),i=this.parseOneInt(s[1]),null!=i){if(1==i)return;2==i||4==i||8==i||16==i?this.align(i):this.directiveError(n("expecting 2, 4, 8, or 16"))}else this.directiveError(n("expecting number"));break;case".p2align":r(),i=this.parseOneInt(s[1]),null!=i?this.align(1<<i):this.directiveError(n("expecting number"));break;case".byte":this.emitBytes(s);break;case".hex":this.emitHex(s);break;case".hword":case".short":case".2bytes":this.parseNumbers(s).forEach(e=>{-32768<=e&&e<=65535?this.emitShort(65535&e):this.directiveError(n("expecting int16"))});break;case".word":case".4bytes":case".long":this.parseNumbers(s).forEach(e=>{-2147483648<=e&&e<=4294967295?(this.emitShort(65535&e),this.emitShort(e>>16&65535)):this.directiveError(n("expecting int32"))});break;case".skip":case".space":this.emitSpace(s);break;case".set":case".equ":/^\w+$/.test(s[1])||this.directiveError(n("expecting name"));const o=this.parseNumbers(s.slice(","==s[2]||"="==s[2]?2:1));1!=o.length&&this.directiveError(n("expecting one value")),void 0!==this.equs[s[1]]&&this.equs[s[1]]!=o[0]&&this.directiveError(n("redefinition of {0}",s[1])),this.equs[s[1]]=o[0];break;case".startaddr":this.location()&&this.directiveError(n(".startaddr can be only be specified at the beginning of the file")),r(),this.baseOffset=this.parseOneInt(s[1]);break;case"@stackmark":r(),this.stackpointers[s[1]]=this.stack;break;case"@stackempty":this.checkStack&&(null==this.stackpointers[s[1]]?this.directiveError(n("no such saved stack")):this.stackpointers[s[1]]!=this.stack&&this.directiveError(n("stack mismatch")));break;case"@scope":this.scope=s[1]||"",this.currLineNo=this.scope?0:this.realCurrLineNo;break;case".syntax":case"@nostackcheck":this.checkStack=!1;break;case"@dummystack":r(),this.stack+=this.parseOneInt(s[1]);break;case".section":case".global":this.stackpointers={},this.stack=0,this.scope="$S"+this.scopeId++;break;case".comm":{s=s.filter(e=>","!=e),s.shift();let e=this.parseOneInt(s[1]),t=0;if(t=s[2]?this.parseOneInt(s[2]):4,null==this.lookupLabel(s[0])){for(this.commPtr||(this.commPtr=this.lookupExternalLabel("_pxt_comm_base")||0,this.commPtr||this.directiveError(n("PXT_COMM_BASE not defined")));this.commPtr&t-1;)this.commPtr++;this.labels[this.scopedName(s[0])]=this.commPtr-this.baseOffset,this.commPtr+=e}break}case".file":case".text":case".cpu":case".fpu":case".eabi_attribute":case".code":case".thumb_func":case".type":case".fnstart":case".save":case".size":case".fnend":case".pad":case".globl":case".local":case"@":break;default:/^\.cfi_/.test(s[0])||this.directiveError(n("unknown directive"))}}handleOneInstruction(e,t){this.codeSizeStats&&e.ldlitLabel&&this.useLabel(e.ldlitLabel);let i=t.emit(e);return!i.error&&(this.stack+=i.stack,this.checkStack&&this.stack<0&&this.pushError(n("stack underflow")),e.location=this.location(),e.opcode=i.opcode,e.stack=i.stack,this.emitOpCode(i.opcode),null!=i.opcode2&&this.emitOpCode(i.opcode2),null!=i.opcode3&&this.emitOpCode(i.opcode3),e.instruction=t,e.numArgs=i.numArgs,!0)}handleInstruction(e){if(e.instruction&&this.handleOneInstruction(e,e.instruction))return;let t=e=>this.ei.instructions.hasOwnProperty(e)?this.ei.instructions[e]:[];if(!e.instruction){let n=t(e.words[0]);for(let t=0;t<n.length;++t)if(this.handleOneInstruction(e,n[t]))return}let i=e.words[0].toLowerCase().replace(/s$/,"").replace(/[^a-z]/g,""),s="",r=t(i).concat(t(i+"s"));r.length>0&&r.forEach(t=>{let i=t.emit(e);s+=n(" Maybe: {0} ({1} at '{2}')\n",t.toString(),i.error,i.errorAt)}),this.pushError(n("assembly error"),s)}buildLine(e,t){let n=e=>{let n=new r(this,e);return n.scope=this.scope,n.lineNo=this.currLineNo,t.push(n),n},i=n(e),s=l(i.text)||[];i.words=s;let 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 o=a.charAt(0);"."==o||"@"==o?(i.type="directive","@scope"==i.words[0]&&this.handleDirective(i)):0==i.words.length?i.type="empty":i.type="instruction"}prepLines(e){this.currLineNo=0,this.realCurrLineNo=0,this.lines=[],e.split(/\r?\n/).forEach(e=>{this.errors.length>10||(this.currLineNo++,this.realCurrLineNo++,this.buildLine(e,this.lines))})}iterLines(){this.stack=0,this.buf=[],this.scopeId=0,this.lines.forEach(t=>{if(!(this.errors.length>10)&&(this.currLine=t,0!=t.words.length))if("label"==t.type){this.currObject&&!this.labelsToObjectDone&&"."!=t.words[0][0]&&(this.labelToObject[t.words[0]]=this.currObject);let i=this.scopedName(t.words[0]);if(this.prevLabel=i,this.finalEmit){null!=this.equs[i]&&this.directiveError(n(".equ redefined as label"));let t=this.labels[i];null==t&&e.oops(),0==this.errors.length&&t!=this.location()&&e.oops(`invalid location: ${this.location()} != ${t} at ${i}`),e.assert(this.errors.length>0||t==this.location()),this.reallyFinalEmit&&(this.stackAtLabel[i]=this.stack)}else this.labels.hasOwnProperty(i)?this.directiveError(n("label redefinition")):this.inlineMode&&/^_/.test(i)?this.directiveError(n("labels starting with '_' are reserved for the compiler")):this.labels[i]=this.location();t.location=this.location()}else"directive"==t.type?this.handleDirective(t):"instruction"==t.type?this.handleInstruction(t):"empty"==t.type||e.oops()}),this.labelsToObjectDone=!0,this.currObject=null}getSourceMap(){const e={};let t="",n=0,i=0,s=0;function r(){t&&i&&(e[t]||(e[t]=[]),e[t].push(n,i,s-i)),i=0,s=0}return this.lines.forEach((e,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}getCodeSizeStats(){if(!this.codeSizeStats)return"";const t=e.U.values(this.idToObject);t.sort((e,t)=>t.size-e.size);let n=";\n; Code size:\n;\n";for(const e of t)if(n+=`; ${(" "+e.size).slice(-6)} ${e.description} [${e.id}]\n`,e.users.length>=5)n+=`; by many, including ${e.users[0].description}\n`;else for(const t of e.users)n+=`; by ${t.description} [${t.id}]\n`;return n}getSource(e,i=1,s=0){let r=0,a=e=>{let t=this.labels[e]||r,n=t-r;return r=t,n},o=this.buf?this.location():0,l=a("_code_end"),c=a("_helpers_end"),u=a("_vtables_end"),d=a("_literals_end"),h=r,p=o+this.baseOffset&16777215;if(s&&p>s){const e=new Error(n("program too big by {0} bytes!",p-s));throw e.ksErrorCode=9283,e}let f=n("; total bytes: {0} ({1}% of {2}k flash with {3} free)",p,(100*p/(s=s||131072)).toFixed(1),(s/1024).toFixed(1),s-p),m=n("; generated code sizes (bytes): {0} (incl. {1} user, {2} helpers, {3} vtables, {4} lits); src size {5}\n",h,l,c,u,d,o-h)+n("; assembly: {0} lines; density: {1} bytes/stmt; ({2} stmts)\n",this.lines.length,Math.round(100*l/i)/100,i)+f+"\n"+this.stats+this.getCodeSizeStats()+"\n\n",g=!1;return this.lines.forEach((n,i)=>{if("_stored_program"==n.words[0])return m+='_stored_program: .string "..."\n',void(g=!0);if(g)return void(g=!1);let s=n.text;if(e){if("@stackempty"==n.words[0]&&this.lines[i-1].text==n.text)return;if(s=s.replace(/; WAS: .*/,""),!s.trim())return}t.debug&&("label"!=n.type&&"instruction"!=n.type||(s+=` \t; 0x${(n.location+this.baseOffset).toString(16)}`)),m+=s+"\n"}),m}peepHole(){let e=this.lines.filter(e=>"empty"!=e.type);for(let t=0;t<e.length;++t){let n=e[t];if(/^user/.test(n.scope))continue;let i=e[t+1];if(!i)continue;let s=e[t+2];"instruction"==n.type&&this.ei.peephole(n,i,s)}}clearLabels(){this.labels={},this.commPtr=0}peepPass(t){this.disablePeepHole||(this.peepOps=0,this.peepDel=0,this.peepCounts={},this.peepHole(),this.throwOnError=!0,this.finalEmit=!1,this.clearLabels(),this.iterLines(),e.assert(!this.checkStack||0==this.stack),this.finalEmit=!0,this.reallyFinalEmit=t||0==this.peepOps,this.iterLines(),this.stats+=n("; peep hole pass: {0} instructions removed and {1} updated\n",this.peepDel,this.peepOps-this.peepDel))}getLabels(){return this.userLabelsCache||(this.userLabelsCache=e.U.mapMap(this.labels,(e,t)=>t+this.baseOffset)),this.userLabelsCache}emit(t){if(e.assert(null==this.buf),this.prepLines(t),this.errors.length>0)return;if(this.clearLabels(),this.iterLines(),this.checkStack&&0!=this.stack&&this.directiveError(n("stack misaligned at the end of the file")),this.errors.length>0)return;if(this.ei.expandLdlit(this),this.clearLabels(),this.iterLines(),this.finalEmit=!0,this.reallyFinalEmit=this.disablePeepHole,this.iterLines(),this.errors.length>0)return;for(let e=0;e<5&&(pxt.debug(`Peephole OPT, pass ${e}`),this.peepPass(5==e),0!=this.peepOps);++e);pxt.debug("emit done")}}t.File=o;t.VMFile=class extends o{constructor(e){super(e)}};function l(e){let t=[],n="";e:for(let i=0;i<e.length;++i)switch(e[i]){case"[":case"]":case"!":case"{":case"}":case",":n&&(t.push(n),n=""),t.push(e[i]);break;case" ":case"\t":case"\r":case"\n":n&&(t.push(n),n="");break;case";":break e;default:n+=e[i]}return n&&(t.push(n),n=""),t[0]?t:null}function c(e){e=e.replace(/\\\\/g,"\\B").replace(/\\(['\?])/g,(e,t)=>t).replace(/\\[z0]/g,"\0").replace(/\\x([0-9a-f][0-9a-f])/gi,(e,t)=>"\\u00"+t).replace(/\\B/g,"\\\\");try{return JSON.parse(e)}catch(e){return null}}function u(e,t){return{stack:null,opcode:null,error:e,errorAt:t}}function d(e){return e<0||e>65535?("0x"+e.toString(16)).toLowerCase():("0x"+("000"+e.toString(16)).slice(-4)).toLowerCase()}t.AbstractProcessor=class{constructor(){this.file=null,this.addEnc=(e,t,n)=>{let i={name:e,pretty:t,encode:n,isRegister:/^\$r\d/.test(e),isImmediate:/^\$i\d/.test(e),isRegList:/^\$rl\d/.test(e),isLabel:/^\$l[a-z]/.test(e)};return this.encoders[e]=i,i},this.inrange=(e,t,n)=>Math.floor(t)!=t||t<0||t>e?null:n,this.inminmax=(e,t,n,i)=>Math.floor(n)!=n||n<e||n>t?null:i,this.inseq=(e,t)=>{let n=e.indexOf(t);return n<0?null:n},this.inrangeSigned=(e,t,n)=>{if(Math.floor(t)!=t)return null;if(t<-(e+1))return null;if(t>e)return null;return n&(e<<1|1)},this.addInst=(e,t,n,i)=>{let r=new s(this,e,t,n,i);return this.instructions.hasOwnProperty(r.name)||(this.instructions[r.name]=[]),this.instructions[r.name].push(r),r},this.encoders={},this.instructions={}}toFnPtr(e,t,n){return e}wordSize(){return-1}computeStackOffset(e,t){return t}is32bit(e){return!1}emit32(e,t,n){return null}postProcessRelAddress(e,t){return t}postProcessAbsAddress(e,t){return t}peephole(e,t,n){}registerNo(e){return null}getAddressFromLabel(e,t,n,i=!1){return null}isPop(e){return!1}isPush(e){return!1}isAddSP(e){return!1}isSubSP(e){return!1}testAssembler(){e.assert(!1)}expandLdlit(e){}},t.emitErr=u,t.expectError=function(t,n){let i=new o(t);i.emit(n),0==i.errors.length&&e.oops("ASMTEST: expecting error for: "+n)},t.tohex=d,t.expect=function(t,n){let i=[],s=n.replace(/^([0-9a-fA-F]{4,8})\s/gm,(e,t)=>(i.push(parseInt(t.slice(0,4),16)),8==t.length&&i.push(parseInt(t.slice(4,8),16)),"")),r=new o(t);r.throwOnError=!0,r.disablePeepHole=!0,r.emit(s),r.errors.length>0&&(pxt.debug(r.errors[0].message),e.oops("ASMTEST: not expecting errors")),r.buf.length!=i.length&&e.oops("ASMTEST: wrong buf len");for(let t=0;t<i.length;++t)r.buf[t]!=i[t]&&e.oops("ASMTEST: wrong buf content at "+t+" , exp:"+d(i[t])+", got: "+d(r.buf[t]))}}(e.assembler||(e.assembler={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){var n=pxtc.Util;t.apiRoot=e.BrowserUtils.isLocalHost()||n.isNodeJS?"https://www.makecode.com/api/":"/api/",t.accessToken="",t.localToken="";let i,s=!0;function r(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 a(n,i){return e.U.requestAsync({url:"/api/"+n,headers:{Authorization:t.localToken},method:i?"POST":"GET",data:i||void 0,allowHttpErrors:!0})}function o(){return e.webConfig&&!e.webConfig.isStatic&&!e.BrowserUtils.isLocalHost()&&!!e.webConfig.cdnUrl&&("undefined"==typeof window||!/nocdn=1/i.test(window.location.href))}function l(n){if(n=n.replace(/^\//,""),!o())return t.apiRoot+n;const i=new Date,s=i.getUTCFullYear()+("0"+(i.getUTCMonth()+1)).slice(-2)+("0"+i.getUTCDate()).slice(-2);return n.indexOf("?")<0?n+="?":n+="&",n+="cdn="+s,e.webConfig.cdnUrl+"/api/"+n}function c(e){return o()?(e.url=l(e.url),n.requestAsync(e).catch(t=>u(e,t))):d(e)}function u(e,n){return 0==n.statusCode?(s&&(s=!1,t.onOffline()),r(e.url)):Promise.reject(n)}function d(i){var s;return i.url=(null===(s=e.webConfig)||void 0===s?void 0:s.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=>u(i,e))):r(i.url)}function h(){return navigator&&navigator.onLine}t.onOffline=()=>{},t.hasAccessToken=function(){return!!t.accessToken},t.localRequestAsync=a,t.useCdnApi=o,t.cdnApiUrl=l,t.apiRequestWithCdnAsync=c,t.privateRequestAsync=d,t.privateGetTextAsync=function(e,t){return d({url:e,headers:t}).then(e=>e.text)},t.privateGetAsync=function(e,t=!1){return d({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()?a(i).then(e=>e?e.json:void 0):c({url:i}).then(e=>e.json)},t.downloadScriptFilesAsync=function(e){return d({url:e+"/text"+(e.startsWith("S")?`?time=${Date.now()}`:""),forceLiveEndpoint:!0}).then(e=>JSON.parse(e.text))},t.downloadScriptMetaAsync=function(e){return d({url:e+(e.startsWith("S")?`?time=${Date.now()}`:""),forceLiveEndpoint:!0}).then(e=>JSON.parse(e.text).meta)},t.downloadBuiltSimJsInfoAsync=async function(t){const n=e.appTarget.versions&&e.appTarget.versions.target||"",i=e.U.stringifyQueryString(t+"/js",{v:"v"+n})+(t.startsWith("S")?`&time=${Date.now()}`:"");return(await d({url:i,forceLiveEndpoint:!0})).json},t.markdownAsync=async function(t,n,i,s){const r=e.BrowserUtils.isLocalHostDev()?0:36e5,l=24*r*7;n=n||e.Util.userLanguage();const u=await e.BrowserUtils.translationDbAsync(),h=await u.getAsync(n,t),p=async()=>{try{const i=await async function(t,n,i,s){var r;const l=null===(r=e.webConfig)||void 0===r?void 0:r.isStatic,u=e.appTarget.versions&&e.appTarget.versions.target||"?";let h;const p=new URLSearchParams;if(l){h=t;const e=/\/?docs\//.test(h),n=/\.\w+$/.test(h);if(!e){const e="/"===h[0];h=`docs${e?"":"/"}${h}`}n||(h=`${h}.md`)}else h=`md/${e.appTarget.id}/${t.replace(/^\//,"")}`,p.set("targetVersion",u);"en"!=n&&p.set("lang",n);if(h=e.BrowserUtils.appendUrlQueryParams(h,p),e.BrowserUtils.isLocalHost()&&!e.Util.liveLocalizationEnabled())return a(h).then(e=>404==e.statusCode?d({url:h,method:"GET"}).then(e=>({md:e.text,etag:e.headers.etag})):{md:e.text,etag:void 0});const f=i&&!o()?{"If-None-Match":i}:void 0;let m,g;if(!l&&s){h=h.replace(/^md\//,"ghtutorial/docs/"),m=await c({url:h,method:"GET",headers:f});const t=m.json;await e.github.db.cacheReposAsync(t),g=t.markdown}else m=await c({url:h,method:"GET",headers:f}),g=m.text;return{md:g,etag:m.headers.etag}}(t,n,null==h?void 0:h.etag,s);return!h||i.md&&h.md!==i.md?(await u.setAsync(n,t,i.etag,void 0,i.md),i.md):h.md}catch(e){if(i)throw e;return""}};if(h){const t=Date.now()-h.time,n=t>r;if(t>l)e.tickEvent("markdown.update.wait");else if(n&&(e.tickEvent("markdown.update.background"),p()),h.md)return h.md}return p()},t.privateDeleteAsync=function(e){return d({url:e,method:"DELETE"}).then(e=>e.json)},t.privatePostAsync=function(e,t,n=!1){return d({url:e,data:t||{},forceLiveEndpoint:n}).then(e=>e.json)},t.isLoggedIn=function(){return!!t.accessToken},t.isNavigatorOnline=h,t.isOnline=function(){return"undefined"!=typeof navigator&&h()&&(s=!0),s},t.getServiceUrl=function(){return t.apiRoot.replace(/\/api\/$/,"")},t.getUserId=function(){let e=/^0(\w+)\./.exec(t.accessToken);return e?e[1]:null},t.parseScriptId=function(t){var i;const s=e.appTarget;if(!t||!s.appTheme||!(null===(i=s.cloud)||void 0===i?void 0:i.sharing))return;let r=["makecode.com"];s.appTheme.embedUrl&&r.push(s.appTheme.embedUrl),s.appTheme.shareUrl&&r.push(s.appTheme.shareUrl),r=n.unique(r,e=>e).map(e=>n.escapeForRegex(n.stripUrlProtocol(e).replace(/\/$/,"")).toLowerCase());const a=`(?:(?:https://)?(?:${r.join("|")})/)`,o=new RegExp(`^${a}?(?:v[0-9]+/)?(?:(?:api/oembed\\?url=.*%2F([^&#]*)&.*)|(?:/?([a-z0-9\\-_]+)(?:[#?&].*)?))$`,"i").exec(t.trim()),l=(null==o?void 0:o[1])||(null==o?void 0:o[2]);return/^(_.{12}|S?[0-9\-]{23})$/.test(l)?l:void 0},t.initRegionAsync=async function(){var t;if(void 0===i)if(e.BrowserUtils.isLocalHost())i=e.cloud.DEV_REGION;else if(null===(t=e.webConfig)||void 0===t?void 0:t.cdnUrl)try{const t={url:new URL("geo",e.webConfig.cdnUrl).toString()},s=await n.requestAsync(t);200!==s.statusCode&&e.error(`Failed to get region: ${s.statusCode}`),i=s.text.trim()}catch(t){e.error("Unable to determine region",t),i="unknown"}else i="unknown"},t.getRegion=function(){return i||e.error("Accessing region before it is initialized. Call initRegionAsync first."),i}}(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.contentDiv.setAttribute("role","menu"),this.contentDiv.setAttribute("tabindex","0"),this.keyDownHandler=this.keyDownListener.bind(this),this.contentDiv.addEventListener("keydown",this.keyDownHandler),this.focusHandler=this.focusListener.bind(this),this.contentDiv.addEventListener("focus",this.focusHandler),this.blurHandler=this.blurListener.bind(this),this.contentDiv.addEventListener("blur",this.blurHandler),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)}keyDownListener(e){if(!this.selectedColRow)return;const[t,n]=this.selectedColRow,i=pxt.Util.isUserLanguageRtl()?"ArrowRight":"ArrowLeft",s=pxt.Util.isUserLanguageRtl()?"ArrowLeft":"ArrowRight";switch(e.code){case"ArrowUp":this.selectedColRow=[t,Math.max(0,n-1)];break;case"ArrowDown":this.selectedColRow=[t,Math.min(this.selectionButtons.length-1,n+1)];break;case i:this.selectedColRow=[Math.max(0,t-1),n];break;case s:this.selectedColRow=[Math.min(1,t+1),n];break;case"Enter":case"Space":return this.selectedElement.click(),e.stopPropagation(),void e.preventDefault();default:return}this.selectedElement.classList.remove("selected");const[r,a]=this.selectedColRow;this.selectedElement=0===r?this.selectionButtons[a]:this.previewButtons[a],this.selectedElement.classList.add("selected"),this.contentDiv.setAttribute("aria-activedescendant",getCellId(r,a));const o=this.contentDiv.getBoundingClientRect(),l=this.selectedElement.getBoundingClientRect();l.bottom>o.bottom?this.selectedElement.scrollIntoView({block:"end"}):l.top<o.top&&this.selectedElement.scrollIntoView({block:"start"}),e.stopPropagation(),e.preventDefault()}focusListener(e){this.selectedElement||(this.selectedColRow=[0,0],this.selectedElement=this.selectionButtons[0]),this.selectedElement.classList.add("selected");const[t,n]=this.selectedColRow;this.contentDiv.setAttribute("aria-activedescendant",getCellId(t,n))}blurListener(e){var t;this.contentDiv.removeAttribute("aria-activedescendant"),null===(t=this.selectedElement)||void 0===t||t.classList.remove("selected")}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(){var e;this.visible=!1,pxt.BrowserUtils.removeClass(this.contentDiv,"shown"),pxt.BrowserUtils.addClass(this.contentDiv,"hidden-above"),this.value=null,this.stopMelody(),this.contentDiv.removeAttribute("aria-activedescendant"),null===(e=this.selectedElement)||void 0===e||e.classList.remove("selected"),this.selectedElement=void 0,this.selectedColRow=void 0}clearDomReferences(){this.contentDiv.removeEventListener("keydown",this.keyDownHandler),this.contentDiv.removeEventListener("focus",this.focusHandler),this.contentDiv.removeEventListener("blur",this.blurHandler),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"}getLastFocusableElement(){return this.contentDiv}buildDom(){for(;this.contentDiv.firstChild;)this.contentDiv.removeChild(this.contentDiv.firstChild);const t=e.SampleMelodies;this.playIcons=[],this.selectionButtons=[],this.previewButtons=[];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",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:"menuitem",title:e.name,tabIndex:-1,id:getCellId(n,0)},()=>this.handleSelection(e));c.appendChild(a),c.appendChild(o),c.appendChild(l),r.appendChild(c),this.selectionButtons[n]=c;const u=t("div",{className:"melody-editor-button right-button",role:"menuitem",title:lf("Preview {0}",e.name),tabIndex:-1,id:getCellId(n,1)},()=>this.togglePlay(e,n)),d=t("i",{className:"play icon"});this.playIcons[n]=d,u.appendChild(d),r.appendChild(u),this.previewButtons[n]=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.playIcons[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.playIcons[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={}));const getCellId=(e,t)=>`:${e}-${0===t?"selection":"preview"}`;var 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={}));
|