Skip to content

restore: recover all files wiped by empty-tree commit#98

Merged
Bryan-Roe merged 8 commits into
mainfrom
copilot/fix-actions
Apr 11, 2026
Merged

restore: recover all files wiped by empty-tree commit#98
Bryan-Roe merged 8 commits into
mainfrom
copilot/fix-actions

Conversation

Copilot AI commented Apr 3, 2026

Copy link
Copy Markdown
Contributor

Commit 841c8e24 ("fix(setup): add AI token health check...") accidentally introduced an empty git tree (4b825dc6), deleting all 1681 repository files and causing every GitHub Actions workflow to fail with no source to execute.

Changes

  • Restored full working tree from parent commit 8e5c573d — all 1681 files re-added, including 33 workflow files under .github/workflows/ and all referenced scripts (auto_bootstrap.py, integration_smoke.py, ci_orchestrator.py, etc.)

Post-restore fixes

  • .devcontainer/devcontainer.json — merged two accidental top-level JSON objects into one valid object, removed // comments, combined all VS Code extensions, and updated the dev container image to 2-3.14-trixie
  • .githooks/pre-commit — fixed set -e causing the failure-message branch to never execute; the test run is now bracketed with set +e/set -e so guidance is printed before exiting non-zero
  • .github/workflows/makecode.yml — upgraded actions/checkout@v3@v4; added explicit actions/setup-node@v4 with node-version: '20' for reproducible builds
  • .github/workflows/actionlint.yml — switched reporter from github-pr-check (PR-only) to github-check (works on both push and pull_request contexts); added permissions: checks: write
  • .github/workflows/llm-maker-tests.yml — upgraded actions/setup-python@v4@v5 to align with the rest of the repository
  • ## GitHub Copilot Chat.md — redacted sensitive diagnostic log content (account name, IP addresses, DNS results, system/network configuration); replaced with a safe summary pointing to the official troubleshooting docs

The commit 841c8e2 ('fix(setup): add AI token health check and correct
test-suite root detection') introduced an empty tree, deleting all 1681
repository files and causing all GitHub Actions workflows to fail.

This commit restores the full repository from the parent commit (8e5c573).

Co-authored-by: Bryan-Roe <74067792+Bryan-Roe@users.noreply.github.com>

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @Copilot! 👋

Your private repo does not have access to Sourcery.

Please upgrade to continue using Sourcery ✨

Comment thread ai-projects/quantum-ml/demo_dashboard.py Outdated
Comment thread pxt_modules/core/usb.cpp
auto len = end - model;
auto dev = (char *)app_alloc(len + 10);
memcpy(dev, model, len);
strcpy(dev + len, " (app)");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Semgrep identified an issue in your code:
The strcpy family of functions do not provide the ability to limit or check buffer
sizes before copying to a destination buffer. This can lead to buffer overflows. Consider
using more secure alternatives such as strncpy and provide the correct limit to the
destination buffer and ensure the string is null terminated.

For more information please see: https://linux.die.net/man/3/strncpy

If developing for C Runtime Library (CRT), more secure versions of these functions should be
used, see:
https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/strncpy-s-strncpy-s-l-wcsncpy-s-wcsncpy-s-l-mbsncpy-s-mbsncpy-s-l?view=msvc-170

To resolve this comment:

🔧 No guidance has been designated for this issue. Fix according to your organization's approved methods.

💬 Ignore this finding

Reply with Semgrep commands to ignore this finding.

  • /fp <comment> for false positive
  • /ar <comment> for acceptable risk
  • /other <comment> for all other reasons

Alternatively, triage in Semgrep AppSec Platform to ignore the finding created by strcpy-1.

You can view more details about this finding in the Semgrep AppSec Platform.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@copilot /fix

output.write(f"{metrics['timestamps'][i]:.2f}\n")

# Create response
response = make_response(output.getvalue())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Semgrep identified an issue in your code:
Be careful with flask.make_response(). If this response is rendered onto a webpage, this could create a cross-site scripting (XSS) vulnerability. flask.make_response() will not autoescape HTML. If you are rendering HTML, write your HTML in a template file and use flask.render_template() which will take care of escaping. If you are returning data from an API, consider using flask.jsonify().

To resolve this comment:

🔧 No guidance has been designated for this issue. Fix according to your organization's approved methods.

💬 Ignore this finding

Reply with Semgrep commands to ignore this finding.

  • /fp <comment> for false positive
  • /ar <comment> for acceptable risk
  • /other <comment> for all other reasons

Alternatively, triage in Semgrep AppSec Platform to ignore the finding created by make-response-with-unknown-content.

You can view more details about this finding in the Semgrep AppSec Platform.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@copilot /fix

),
),
patch.object(
chat_cli, "save_conversation", return_value=Path("/tmp/chat.jsonl")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Semgrep identified an issue in your code:
The application was found creating files in shared system temporary directories
(/tmp or /var/tmp) without using the tempfile.TemporaryFile function. Depending
on how the application uses this temporary file, an attacker may be able to create
symlinks that point to other files prior to the application creating or writing
to the target file, leading to unintended files being created or overwritten.

Example using tempfile.TemporaryFile to write a file:

import tempfile

# Open a new temporary file using a context manager
with tempfile.TemporaryFile() as fp:
    # Write some data to the temporary file
    fp.write(b'Some data')
    # Seek back to beginning of file
    fp.seek(0)
    # Read it
    data = fp.read()
# File is automatically closed/removed once we exit the with context

For more information on alternative tempfile functions see:

To resolve this comment:

🔧 No guidance has been designated for this issue. Fix according to your organization's approved methods.

💬 Ignore this finding

Reply with Semgrep commands to ignore this finding.

  • /fp <comment> for false positive
  • /ar <comment> for acceptable risk
  • /other <comment> for all other reasons

Alternatively, triage in Semgrep AppSec Platform to ignore the finding created by B108.

You can view more details about this finding in the Semgrep AppSec Platform.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@copilot /fix

Comment thread apps/chat/chat.js
Comment on lines +994 to +1002
const response = await fetch(QUANTUM_CIRCUIT_API, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
n_qubits: nQubits,
n_layers: nLayers,
entanglement: 'linear'
})
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Semgrep identified an issue in your code:
This application allows user-controlled URLs to be passed directly to HTTP client libraries. This can result in Server-Side Request Forgery (SSRF). SSRF refers to an attack where the attacker can abuse functionality on the server to force it to make requests to other internal systems within your infrastructure that are not directly exposed to the internet. This allows the attacker to access internal resources they do not have direct access to.
Some risks of SSRF are:

  • Access and manipulation of internal databases, APIs, or administrative panels - Ability to scan internal network architecture and services - Can be used to pivot attacks into the internal network - Circumvent network segregation and firewall rules
    To avoid this, try using hardcoded HTTP request calls or a whitelisting object to check whether the user input is trying to access allowed resources or not.
    Here is an example: var whitelist = [ "https://example.com", "https://example.com/sample" ] app.get('/ssrf/node-ssrf/axios/safe/3', function (req, res) { if(whitelist.includes(req.query.url)){ axios.get(url, {}) .then(function (response) { console.log(response); }) .catch(function (response) { console.log(response); }) } }); For more information on SSRF see OWASP: https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html
Dataflow graph
flowchart LR
    classDef invis fill:white, stroke: none
    classDef default fill:#e7f5ff, color:#1c7fd6, stroke: none

    subgraph File0["<b>apps/chat/chat.js</b>"]
        direction LR
        %% Source

        subgraph Source
            direction LR

            v0["<a href=https://github.com/Bryan-Roe/Aria/blob/551a8cb1989e3198b6a0735d7c29464614c3984d/apps/chat/chat.js#L992 target=_blank style='text-decoration:none; color:#1c7fd6'>[Line: 992] nQubits</a>"]
        end
        %% Intermediate

        subgraph Traces0[Traces]
            direction TB

            v2["<a href=https://github.com/Bryan-Roe/Aria/blob/551a8cb1989e3198b6a0735d7c29464614c3984d/apps/chat/chat.js#L992 target=_blank style='text-decoration:none; color:#1c7fd6'>[Line: 992] nQubits</a>"]
        end
        %% Sink

        subgraph Sink
            direction LR

            v1["<a href=https://github.com/Bryan-Roe/Aria/blob/551a8cb1989e3198b6a0735d7c29464614c3984d/apps/chat/chat.js#L994 target=_blank style='text-decoration:none; color:#1c7fd6'>[Line: 994] fetch(QUANTUM_CIRCUIT_API, {
<br>            method: &apos;POST&apos;,
<br>            headers: { &apos;Content-Type&apos;: &apos;application/json&apos; },
<br>            body: JSON.stringify({
<br>                n_qubits: nQubits,
<br>                n_layers: nLayers,
<br>                entanglement: &apos;linear&apos;
<br>            })
<br>        })</a>"]
        end
    end
    %% Class Assignment
    Source:::invis
    Sink:::invis

    Traces0:::invis
    File0:::invis

    %% Connections

    Source --> Traces0
    Traces0 --> Sink


Loading

To resolve this comment:

🔧 No guidance has been designated for this issue. Fix according to your organization's approved methods.

💬 Ignore this finding

Reply with Semgrep commands to ignore this finding.

  • /fp <comment> for false positive
  • /ar <comment> for acceptable risk
  • /other <comment> for all other reasons

Alternatively, triage in Semgrep AppSec Platform to ignore the finding created by javascript-ssrf-rule-node_ssrf.

You can view more details about this finding in the Semgrep AppSec Platform.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@copilot /fix

Comment on lines +77 to +78
logger.error(f"Failed to load quantum LLM: {e}")
raise

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Semgrep identified an issue in your code:
Errors should only be logged when handled. The code logs the error and propogates the exception, consider reducing the level to warning or info.

To resolve this comment:

🔧 No guidance has been designated for this issue. Fix according to your organization's approved methods.

💬 Ignore this finding

Reply with Semgrep commands to ignore this finding.

  • /fp <comment> for false positive
  • /ar <comment> for acceptable risk
  • /other <comment> for all other reasons

Alternatively, triage in Semgrep AppSec Platform to ignore the finding created by logging-error-without-handling.

You can view more details about this finding in the Semgrep AppSec Platform.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@copilot /fix

try:
# Test import — use importlib for safer dynamic importing.
start = time.time()
module = importlib.import_module(import_path)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Semgrep identified an issue in your code:
Untrusted user input in importlib.import_module() function allows an attacker to load arbitrary code. Avoid dynamic values in importlib.import_module() or use a whitelist to prevent running untrusted code.

To resolve this comment:

🔧 No guidance has been designated for this issue. Fix according to your organization's approved methods.

💬 Ignore this finding

Reply with Semgrep commands to ignore this finding.

  • /fp <comment> for false positive
  • /ar <comment> for acceptable risk
  • /other <comment> for all other reasons

Alternatively, triage in Semgrep AppSec Platform to ignore the finding created by non-literal-import.

You can view more details about this finding in the Semgrep AppSec Platform.

if args.watch:
try:
while True:
os.system("clear" if os.name != "nt" else "cls")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Semgrep identified an issue in your code:
Starting a process with a shell; seems safe, but may be changed in the future, consider
rewriting without shell

To resolve this comment:

🔧 No guidance has been designated for this issue. Fix according to your organization's approved methods.

💬 Ignore this finding

Reply with Semgrep commands to ignore this finding.

  • /fp <comment> for false positive
  • /ar <comment> for acceptable risk
  • /other <comment> for all other reasons

Alternatively, triage in Semgrep AppSec Platform to ignore the finding created by B605.

You can view more details about this finding in the Semgrep AppSec Platform.

const RUN_KEY = "#run";
const SCOPE_KEY = "#scope";
const DEVICE_SECRETS_KEY = "#secrets";
const SECRETS_KEY = "__secrets";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Semgrep identified an issue in your code:
A hardcoded secret is identified. Store it properly in an environment variable.

To resolve this comment:

🔧 No guidance has been designated for this issue. Fix according to your organization's approved methods.

💬 Ignore this finding

Reply with Semgrep commands to ignore this finding.

  • /fp <comment> for false positive
  • /ar <comment> for acceptable risk
  • /other <comment> for all other reasons

Alternatively, triage in Semgrep AppSec Platform to ignore the finding created by node_secret.

You can view more details about this finding in the Semgrep AppSec Platform.

Comment on lines +472 to +473
this.message = this.message
.replaceAll("${WINNER}", "PLAYER " + winner.player)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Semgrep identified an issue in your code:
The string method replaceAll is not supported in all versions of javascript, and is not supported by older browser versions. Consider using replace() with a regex as the first argument instead like mystring.replace(/bad/g, "good") instead of mystring.replaceAll("bad", "good") (https://discourse.threejs.org/t/replaceall-is-not-a-function/14585)

To resolve this comment:

🔧 No guidance has been designated for this issue. Fix according to your organization's approved methods.

💬 Ignore this finding

Reply with Semgrep commands to ignore this finding.

  • /fp <comment> for false positive
  • /ar <comment> for acceptable risk
  • /other <comment> for all other reasons

Alternatively, triage in Semgrep AppSec Platform to ignore the finding created by no-replaceall.

You can view more details about this finding in the Semgrep AppSec Platform.

Comment thread apps/aria/test_auto_execute.py Outdated
Comment thread apps/aria/test_auto_execute.py Outdated
Comment on lines +391 to +441
window.addEventListener("message", (ev) => {
var _a;
if (ev.data.button !== undefined && ev.data.type !== "multiplayer") {
let key;
switch (ev.data.button) {
case 0:
key = pxsim.Key.A;
break;
case 1:
key = pxsim.Key.B;
break;
case 2:
key = pxsim.Key.Up;
break;
case 3:
key = pxsim.Key.Down;
break;
case 4:
key = pxsim.Key.Left;
break;
case 5:
key = pxsim.Key.Right;
break;
case 6:
key = pxsim.Key.Menu;
break;
case 7:
key = pxsim.Key.Reset;
break;
}
const b = board();
if (b)
b.setButton(key, ev.data.pressed);
}
if (ev.data.context !== undefined) {
if (ev.data.context == "client" ||
ev.data.context == "server") {
const b = board();
b.multiplayerState.origin = ev.data.context;
}
}
if (ev.data.type == "setactiveplayer") {
const b = board();
if (!(b.multiplayerState && b.multiplayerState.origin)) {
b.setActivePlayer(ev.data.playerNumber, theme);
}
}
else if (ev.data.type == "setsimthemecolor") {
pxsim.theme.setSimThemeColor(ev.data.part, (_a = ev.data.color) === null || _a === void 0 ? void 0 : _a.replace("#", ""));
}
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Semgrep identified an issue in your code:
No validation of origin is done by the addEventListener API. It may be possible to exploit this flaw to perform Cross Origin attacks such as Cross-Site Scripting(XSS).

To resolve this comment:

🔧 No guidance has been designated for this issue. Fix according to your organization's approved methods.

💬 Ignore this finding

Reply with Semgrep commands to ignore this finding.

  • /fp <comment> for false positive
  • /ar <comment> for acceptable risk
  • /other <comment> for all other reasons

Alternatively, triage in Semgrep AppSec Platform to ignore the finding created by insufficient-postmessage-origin-validation.

You can view more details about this finding in the Semgrep AppSec Platform.

scaler_path = model_dir / "custom_scaler.pkl"
if not scaler_path.exists():
raise FileNotFoundError(f"Scaler not found: {scaler_path}")
scaler = joblib.load(scaler_path)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Semgrep identified an issue in your code:
Scikit joblib uses pickle under the hood. Functions reliant on pickle can result in arbitrary code execution. Consider using skops instead.

To resolve this comment:

🔧 No guidance has been designated for this issue. Fix according to your organization's approved methods.

💬 Ignore this finding

Reply with Semgrep commands to ignore this finding.

  • /fp <comment> for false positive
  • /ar <comment> for acceptable risk
  • /other <comment> for all other reasons

Alternatively, triage in Semgrep AppSec Platform to ignore the finding created by scikit-joblib-load.

You can view more details about this finding in the Semgrep AppSec Platform.

WORKDIR /app

# Install system dependencies
RUN apt-get update && apt-get install -y \

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Semgrep identified an issue in your code:
The package cache was not deleted after running 'apt-get update', which increases the size of the image. Remove the package cache by appending '&& apt-get clean' at the end of apt-get command chain.

To resolve this comment:

🔧 No guidance has been designated for this issue. Fix according to your organization's approved methods.

💬 Ignore this finding

Reply with Semgrep commands to ignore this finding.

  • /fp <comment> for false positive
  • /ar <comment> for acceptable risk
  • /other <comment> for all other reasons

Alternatively, triage in Semgrep AppSec Platform to ignore the finding created by remove-package-cache.

You can view more details about this finding in the Semgrep AppSec Platform.

chrome:
image: selenium/standalone-chrome:latest
ports:
- 4444:4444

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Semgrep identified an issue in your code:
Service port is exposed on all interfaces

To resolve this comment:

🔧 No guidance has been designated for this issue. Fix according to your organization's approved methods.

💬 Ignore this finding

Reply with Semgrep commands to ignore this finding.

  • /fp <comment> for false positive
  • /ar <comment> for acceptable risk
  • /other <comment> for all other reasons

Alternatively, triage in Semgrep AppSec Platform to ignore the finding created by port-all-interfaces.

You can view more details about this finding in the Semgrep AppSec Platform.

echo "Installing CUDA wheel for ${CUDA_WHEEL} (PyTorch)"
# Use the appropriate stable wheel link; the -f/--find-links ensures the extra index is used
# Example: --cuda cu121 -> https://download.pytorch.org/whl/cu121
"${VENV_PYTHON}" -m pip install torch --index-url https://download.pytorch.org/whl/${CUDA_WHEEL}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Semgrep identified an issue in your code:
Variable expansions must be double-quoted so as to prevent being split into multiple pieces according to whitespace or whichever separator is specified by the IFS variable. If you really wish to split the variable's contents, you may use a variable that starts with an underscore e.g. $_X instead of $X, and semgrep will ignore it. If what you need is an array, consider using a proper bash array.

To resolve this comment:

🔧 No guidance has been designated for this issue. Fix according to your organization's approved methods.

💬 Ignore this finding

Reply with Semgrep commands to ignore this finding.

  • /fp <comment> for false positive
  • /ar <comment> for acceptable risk
  • /other <comment> for all other reasons

Alternatively, triage in Semgrep AppSec Platform to ignore the finding created by unquoted-variable-expansion-in-command.

You can view more details about this finding in the Semgrep AppSec Platform.

@@ -0,0 +1 @@
var pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim;!function(e){!function(t){let n,s=!1;function i(e){const t=window.navigator&&/Mac/i.test(window.navigator.platform)?e.metaKey:e.ctrlKey;return"Escape"===e.key?(e.preventDefault(),"escape"):"/"===e.key&&t?(e.preventDefault(),"togglekeyboardcontrolshelp"):"b"===e.key&&t?(e.preventDefault(),"toggleareamenu"):null}t.makeFocusable=function(e){e.setAttribute("focusable","true"),e.setAttribute("tabindex","0")},t.getGlobalAction=i,t.postKeyboardEvent=function(){s||(s=!0,document.addEventListener("keydown",t=>{const n=i(t);if(n){const t={type:"action",action:n};e.Runtime.postMessage(t)}}))},t.enableKeyboardInteraction=function(e,t,n){t&&e.addEventListener("keydown",e=>{const n="number"==typeof e.which?e.which:e.keyCode;32!==n&&13!==n||t()}),n&&e.addEventListener("keyup",e=>{const t="number"==typeof e.which?e.which:e.keyCode;32!==t&&13!==t||n()})},t.setAria=function(e,t,n){t&&!e.hasAttribute("role")&&e.setAttribute("role",t),n&&!e.hasAttribute("aria-label")&&e.setAttribute("aria-label",n)},t.setLiveContent=function(e){if(!n){let e="position: absolute !important;display: block;visibility: visible;overflow: hidden;width: 1px;height: 1px;margin: -1px;border: 0;padding: 0;clip: rect(0 0 0 0);";n=document.createElement("div"),n.setAttribute("role","status"),n.setAttribute("aria-live","polite"),n.setAttribute("aria-hidden","false"),n.setAttribute("style",e),document.body.appendChild(n)}n.textContent!==e&&(n.textContent=e)}}(e.accessibility||(e.accessibility={}))}(pxsim||(pxsim={})),function(e){const t="blue",n="red",s="orange";const i=e=>(e=>e.reduce((e,t)=>e+(t?1:0),0))(e)>0;function r(e,t){let n={};for(let t in e)n[t]=e[t];for(let e in t)n[e]=t[e];return n}function o(t){e.U.assert(!!t,"Invalid pin: "+t);const n=/^(\w+)\.\s*(?:[a-z]*)?([A-Z][A-Z\d_]+)$/.exec(t);return n?n[2]:void 0}function a(e){return"-Z"===e.orientation&&"male"===e.style}e.readPin=o;class l{constructor(t){this.availablePowerPins={top:{fiveVolt:e.mkRange(26,51).map(e=>({type:"breadboard",row:"+",col:`${e}`})),threeVolt:e.mkRange(26,51).map(e=>({type:"breadboard",row:"+",col:`${e}`})),ground:e.mkRange(26,51).map(e=>({type:"breadboard",row:"-",col:`${e}`}))},bottom:{fiveVolt:e.mkRange(1,26).map(e=>({type:"breadboard",row:"+",col:`${e}`})),threeVolt:e.mkRange(1,26).map(e=>({type:"breadboard",row:"+",col:`${e}`})),ground:e.mkRange(1,26).map(e=>({type:"breadboard",row:"-",col:`${e}`}))}},this.opts=t}allocPartIRs(t,n,s){let i=[];const r=(t,n,i,r)=>{let o=[];for(let n=0;n<t.numberOfPins;n++){let r,a=t.pinDefinitions[n];if("string"==typeof a.target)r=a.target;else{let t=a.target.pinInstantiationIdx;if(!i||void 0===i[t])return void e.log(`error: parts no pin found for PinInstantiationIdx: ${t}. (Is the part missing an ArgumentRole or "trackArgs=" annotations?)`);r=i[t]}let l=t.visual.pinLocations[n],u=s.yOffset+l.y,c=Math.round(u/t.visual.pinDistance),h=u-c*t.visual.pinDistance,d=s.xOffset+l.x,p=Math.round(d/t.visual.pinDistance),f={partRelativeRowIdx:c,partRelativeColIdx:p,xOffset:d-p*t.visual.pinDistance,yOffset:h};o.push({def:a,loc:l,target:r,bbFit:f})}return{name:n,def:t,pins:o,partParams:r||{},bbFit:s}},a=t.instantiations||[];return t.instantiation&&a.push(t.instantiation),a.forEach(s=>{if("singleton"===s.kind)i.push(r(t,n));else if("function"===s.kind){let a=s,l=a.fullyQualifiedName.split(","),u={};l.forEach(e=>{this.opts.fnArgs[e]&&this.opts.fnArgs[e].forEach(e=>{u[e]=1})});let c=Object.keys(u);if(!c||!c.length)return void e.log(`error: parts failed to read pin(s) from callsite for: ${l}`);c.forEach(s=>{const u=s.split(",");if(u.length!=a.argumentRoles.length)return void e.log(`error: parts mismatch between number of arguments at callsite (function name: ${l}) vs number of argument roles in part definition (part: ${n}).`);let c=[],h={};u.forEach((e,t)=>{let n=a.argumentRoles[t];if(void 0!==n.partParameter&&(h[n.partParameter]=e),void 0!==n.pinInstantiationIdx){let t=n.pinInstantiationIdx,s=o(e);c[t]=s}}),i.push(r(t,n,c,h))})}}),i.filter(e=>!!e)}computePartDimensions(t,n){let s=t.visual.pinLocations,i=t.pinDefinitions,o=t.numberOfPins;e.U.assert(s.length===o,`Mismatch between "numberOfPins" and length of "visual.pinLocations" for "${n}"`),e.U.assert(i.length===o,`Mismatch between "numberOfPins" and length of "pinDefinitions" for "${n}"`),e.U.assert(o>0,`Part "${n}" has no pins`);let a,l,u,c,h=s.map((e,t)=>{return n={idx:t},s=e,o=i[t],r(r(n,s),o);var n,s,o}).filter(e=>"-Z"===e.orientation),d=h.length>0,p=t.visual.pinDistance;if(d){let e=h[0],n=Math.ceil(e.x/p),s=Math.ceil(e.y/p);a=n*p-e.x,l=s*p-e.y,u=Math.ceil((a+t.visual.width)/p)+1,c=Math.ceil((l+t.visual.height)/p)+1}else u=Math.ceil(t.visual.width/p),c=Math.ceil(t.visual.height/p),a=u*p-t.visual.width,l=c*p-t.visual.height;return{xOffset:a,yOffset:l,rowCount:c,colCount:u}}allocColumns(t){let n=t.length;let s=e.visuals.BREADBOARD_MID_COLS-t.map(e=>e.colCount).reduce((e,t)=>e+t,0);s<=0&&e.log("Not enough breadboard space!");let i=Math.floor(s/(n-1+2)),r=s-i*(n-1),o=Math.floor(r/2),a=(Math.ceil(r/2),1+o);return t.map(e=>{let t=a;return a+=e.colCount+i,t})}placeParts(t){const n=e.visuals.BREADBOARD_MID_ROWS+2;let s=this.allocColumns(t.map(e=>e.bbFit)),i=t.map(e=>{let t=n-e.bbFit.rowCount,s=Math.floor(t/2);return s>4&&(s=4),s<1&&(s=1),s});return t.map((e,t)=>{let n=i[t];return r({startColumnIdx:s[t],startRowIdx:n},e)})}nextColor(){return(!this.availableWireColors||this.availableWireColors.length<=0)&&(this.availableWireColors=e.visuals.GPIO_WIRE_COLORS.map(e=>e)),this.availableWireColors.pop()}allocWireIRs(i){let o=[],l=i.pins.map((r,l)=>{let u,c,h=r.target,d=i.startColumnIdx+r.bbFit.partRelativeColIdx,p=e.visuals.getColumnName(d),f=i.startRowIdx+r.bbFit.partRelativeRowIdx;if(f>=7&&(f-=2),a(r.def)){u={type:"breadboard",row:f<5?"j":"a",col:p,style:r.def.style}}else{u={type:"breadboard",row:e.visuals.getRowName(f),col:p,xOffset:r.bbFit.xOffset/i.def.visual.pinDistance,yOffset:r.bbFit.yOffset/i.def.visual.pinDistance,style:r.def.style}}return c="ground"===h?t:"threeVolt"===h?n:"fiveVolt"===h?s:"number"==typeof r.def.colorGroup?o[r.def.colorGroup]?o[r.def.colorGroup]:o[r.def.colorGroup]=this.nextColor():this.nextColor(),{start:u,end:h,color:c,pinIdx:l}});return r(i,{wires:l})}allocLocation(t,n){if("ground"===t||"threeVolt"===t||"fiveVolt"==t){if("ground"===t&&this.powerUsage.singleGround){return{type:"dalboard",pin:this.getBoardGroundPin()}}if("threeVolt"===t&&this.powerUsage.singleThreeVolt){return{type:"dalboard",pin:this.getBoardThreeVoltPin()}}if("fiveVolt"===t&&this.powerUsage.singleFiveVolt){return{type:"dalboard",pin:this.getBoardFiveVoltPin()}}e.U.assert(!!n.referenceBBPin);let s=this.opts.getBBCoord(n.referenceBBPin),i=[this.availablePowerPins.top.ground[0]||this.availablePowerPins.top.threeVolt[0],this.availablePowerPins.bottom.ground[0]||this.availablePowerPins.bottom.threeVolt[0]].map(e=>this.opts.getBBCoord(e));i[0]&&i[1]||e.debug(`No more available "${t}" locations!`);let r,o=0==e.visuals.findClosestCoordIdx(s,i);o?"ground"===t?r=this.availablePowerPins.top.ground:"threeVolt"===t?r=this.availablePowerPins.top.threeVolt:"fiveVolt"===t&&(r=this.availablePowerPins.top.fiveVolt):"ground"===t?r=this.availablePowerPins.bottom.ground:"threeVolt"===t?r=this.availablePowerPins.bottom.threeVolt:"fiveVolt"===t&&(r=this.availablePowerPins.bottom.fiveVolt);let a=r.map(e=>this.opts.getBBCoord(e)),l=e.visuals.findClosestCoordIdx(s,a),u=r[l];return o?(this.availablePowerPins.top.ground.splice(l,1),this.availablePowerPins.top.threeVolt.splice(l,1)):(this.availablePowerPins.bottom.ground.splice(l,1),this.availablePowerPins.bottom.threeVolt.splice(l,1)),u}if("breadboard"===t.type)return t;if("MOSI"===t||"MISO"===t||"SCK"===t){return this.opts.boardDef.spiPins||e.debug("No SPI pin mappings found!"),{type:"dalboard",pin:this.opts.boardDef.spiPins[t]}}if("SDA"===t||"SCL"===t){return this.opts.boardDef.i2cPins||e.debug("No I2C pin mappings found!"),{type:"dalboard",pin:this.opts.boardDef.i2cPins[t]}}{e.U.assert("string"==typeof t,"Unknown location type: "+t);let n=t,s=this.opts.boardDef.gpioPinMap[n]||n;return s?{type:"dalboard",pin:s}:void e.debug(`unknown pin location for ${n}`)}}getBoardGroundPin(){let t=this.opts.boardDef.groundPins&&this.opts.boardDef.groundPins[0]||null;return t||e.debug("No available ground pin on board!"),t}getBoardThreeVoltPin(){let t=this.opts.boardDef.threeVoltPins&&this.opts.boardDef.threeVoltPins[0]||null;return t||e.debug("No available 3.3V pin on board!"),t}getBoardFiveVoltPin(){let t=this.opts.boardDef.fiveVoltPins&&this.opts.boardDef.fiveVoltPins[0]||null;return t||e.debug("No available 5V pin on board!"),t}allocPowerWires(e){let i=this.getBoardGroundPin(),r=this.getBoardThreeVoltPin(),o=this.getBoardFiveVoltPin();const a={type:"breadboard",row:"-",col:"26"},l={type:"breadboard",row:"-",col:"1"},u={type:"breadboard",row:"-",col:"50"},c={type:"breadboard",row:"-",col:"25"};let h,d;this.opts.boardDef.attachPowerOnRight?(h=u,d=c):(h=a,d=l);let p=[],f=[],m=[];e.bottomGround&&e.topGround&&p.push({start:this.allocLocation("ground",{referenceBBPin:h}),end:this.allocLocation("ground",{referenceBBPin:d}),color:t}),e.topGround?p.push({start:this.allocLocation("ground",{referenceBBPin:h}),end:{type:"dalboard",pin:i},color:t}):e.bottomGround&&p.push({start:this.allocLocation("ground",{referenceBBPin:d}),end:{type:"dalboard",pin:i},color:t}),e.bottomThreeVolt&&e.bottomGround?f.push({start:this.allocLocation("threeVolt",{referenceBBPin:h}),end:this.allocLocation("threeVolt",{referenceBBPin:d}),color:n}):e.bottomFiveVolt&&e.bottomGround&&m.push({start:this.allocLocation("fiveVolt",{referenceBBPin:h}),end:this.allocLocation("fiveVolt",{referenceBBPin:d}),color:s}),e.topThreeVolt?f.push({start:this.allocLocation("threeVolt",{referenceBBPin:h}),end:{type:"dalboard",pin:r},color:n}):e.bottomThreeVolt&&f.push({start:this.allocLocation("threeVolt",{referenceBBPin:d}),end:{type:"dalboard",pin:r},color:s}),e.topFiveVolt&&!e.topThreeVolt?m.push({start:this.allocLocation("fiveVolt",{referenceBBPin:h}),end:{type:"dalboard",pin:o},color:n}):e.bottomFiveVolt&&!e.bottomThreeVolt&&m.push({start:this.allocLocation("fiveVolt",{referenceBBPin:d}),end:{type:"dalboard",pin:o},color:s});let g=[];p.length>0&&g.push({wireIndices:p.map((e,t)=>t)});let b=p.length;return f.length>0&&g.push({wireIndices:f.map((e,t)=>t+b)}),m.length>0&&g.push({wireIndices:f.map((e,t)=>t+b+f.length)}),{wires:p.concat(f).concat(m),assembly:g}}allocWire(e){const t=[e.start,e.end],n=t.map(e=>"ground"===e||"threeVolt"===e||"fiveVolt"===e);let s=t.map((e,t)=>n[t]?void 0:this.allocLocation(e,{}));if(s=s.map((e,n)=>{if(e)return e;const i=s[1-n];return this.allocLocation(t[n],{referenceBBPin:i})}),s[0]&&s[1])return{start:s[0],end:s[1],color:e.color}}allocPart(t){let n=t.pins.filter(e=>a(e.def)).map(n=>{let s=t.startRowIdx+n.bbFit.partRelativeRowIdx;s>=7&&(s-=2);let i=e.visuals.getRowName(s),r=t.startColumnIdx+n.bbFit.partRelativeColIdx;return{type:"breadboard",row:i,col:e.visuals.getColumnName(r)}});return{name:t.name,visual:t.def.visual,bbFit:t.bbFit,startColumnIdx:t.startColumnIdx,startRowIdx:t.startRowIdx,breadboardConnections:n,params:t.partParams,simulationBehavior:t.def.simulationBehavior}}allocAll(){let e=this.opts.partsList.map(e=>({name:e,def:this.opts.partDefs[e]})).filter(e=>!!e.def);if(e.length>0){let t=e.map(e=>this.computePartDimensions(e.def,e.name)),n=[];e.forEach((e,s)=>{let i=t[s],r=this.allocPartIRs(e.def,e.name,i);n=n.concat(r)});const s=this.placeParts(n).map(e=>this.allocWireIRs(e)),r=s.map(e=>e.wires).reduce((e,t)=>e.concat(t),[]).map(e=>function(e){let t=[e.start,e.end],n=t.map(e=>"ground"===e),s=t.map(e=>"threeVolt"===e),r=t.map(e=>"fiveVolt"===e),o=t.map(e=>function(e){let t=!1;if("string"!=typeof e&&"breadboard"===e.type){let n=e.row;t=0<=["a","b","c","d","e"].indexOf(n)}return t}(e)),a=i(n),l=i(s),u=i(r),c=i(o);return{topGround:a&&!c,topThreeVolt:l&&!c,topFiveVolt:u&&!c,bottomGround:a&&c,bottomThreeVolt:l&&c,bottomFiveVolt:u&&c,singleGround:a,singleThreeVolt:l,singleFiveVolt:u}}(e));this.powerUsage=function(e){const t=e.reduce((e,t)=>({topGround:e.topGround||t.topGround,topThreeVolt:e.topThreeVolt||t.topThreeVolt,topFiveVolt:e.topFiveVolt||t.topFiveVolt,bottomGround:e.bottomGround||t.bottomGround,bottomThreeVolt:e.bottomThreeVolt||t.bottomThreeVolt,bottomFiveVolt:e.bottomFiveVolt||t.bottomFiveVolt,singleGround:t.singleGround?null===e.singleGround:e.singleGround,singleThreeVolt:t.singleThreeVolt?null===e.singleThreeVolt:e.singleThreeVolt,singleFiveVolt:t.singleFiveVolt?null===e.singleFiveVolt:e.singleFiveVolt}),{topGround:!1,topThreeVolt:!1,topFiveVolt:!1,bottomGround:!1,bottomThreeVolt:!1,bottomFiveVolt:!1,singleGround:null,singleThreeVolt:null,singleFiveVolt:null});return t.singleGround&&(t.topGround=t.bottomGround=!1),t.singleThreeVolt&&(t.topThreeVolt=t.bottomThreeVolt=!1),t.singleFiveVolt&&(t.topFiveVolt=t.bottomFiveVolt=!1),t}(r);const o=this.allocPowerWires(this.powerUsage),a=s.map((e,t)=>{const n=this.allocPart(e),s=e.wires.map(e=>this.allocWire(e));if(s.some(e=>!e))return;const i=[];e.wires.forEach((e,t)=>{i[e.pinIdx]=t});return{part:n,wires:s,assembly:e.def.assembly.map(e=>({part:e.part,wireIndices:(e.pinIndices||[]).map(e=>i[e])}))}}).filter(e=>!!e),l=[o].concat(a).filter(e=>e.assembly&&e.assembly.length),u=!l.some(e=>e.part&&e.part.breadboardConnections&&e.part.breadboardConnections.length>0||e.wires&&e.wires.some(e=>"breadboard"==e.end.type&&"croc"!=e.end.style||"breadboard"==e.start.type&&"croc"!=e.start.style));return{partsAndWires:l,wires:[],parts:[],hideBreadboard:u}}return{partsAndWires:[],wires:[],parts:[]}}}e.allocateDefinitions=function(e){return new l(e).allocAll()}}(pxsim||(pxsim={})),function(e){!function(t){class n{constructor(e){this.seq=0,this.type=e}}t.Message=n;t.Response=class extends n{constructor(e,t){super("response"),this.request_seq=e.seq,this.command=e.command,t?(this.success=!1,this.message=t):this.success=!0}};class s extends n{constructor(e,t){super("event"),this.event=e,t&&(this.body=t)}}t.Event=s;t.Source=class{constructor(e,t,n=0,s,i){this.name=e,this.path=t,this.sourceReference=n,s&&(this.origin=s),i&&(this.adapterData=i)}};t.Scope=class{constructor(e,t,n=!1){this.name=e,this.variablesReference=t,this.expensive=n}};t.StackFrame=class{constructor(e,t,n,s=0,i=0){this.id=e,this.source=n,this.line=s,this.column=i,this.name=t}};t.Thread=class{constructor(e,t){this.id=e,this.name=t||"Thread #"+e}};t.Variable=class{constructor(e,t,n=0,s,i){this.name=e,this.value=t,this.variablesReference=n,"number"==typeof i&&(this.namedVariables=i),"number"==typeof s&&(this.indexedVariables=s)}};t.Breakpoint=class{constructor(e,t,n,s){this.verified=e;const i=this;"number"==typeof t&&(i.line=t),"number"==typeof n&&(i.column=n),s&&(i.source=s)}};t.Module=class{constructor(e,t){this.id=e,this.name=t}};t.CompletionItem=class{constructor(e,t,n=0){this.label=e,this.start=t,this.length=n}};t.StoppedEvent=class extends s{constructor(e,t,n=null){if(super("stopped"),this.body={reason:e,threadId:t},n){this.body.text=n}}};t.ContinuedEvent=class extends s{constructor(e,t){super("continued"),this.body={threadId:e},"boolean"==typeof t&&(this.body.allThreadsContinued=t)}};t.InitializedEvent=class extends s{constructor(){super("initialized")}};t.TerminatedEvent=class extends s{constructor(e){if(super("terminated"),"boolean"==typeof e){this.body={restart:e}}}};t.OutputEvent=class extends s{constructor(e,t="console",n){super("output"),this.body={category:t,output:e},void 0!==n&&(this.body.data=n)}};t.ThreadEvent=class extends s{constructor(e,t){super("thread"),this.body={reason:e,threadId:t}}};t.BreakpointEvent=class extends s{constructor(e,t){super("breakpoint"),this.body={reason:e,breakpoint:t}}};t.ModuleEvent=class extends s{constructor(e,t){super("module"),this.body={reason:e,module:t}}};class i{constructor(){this._pendingRequests={}}start(e){this._sequence=1,this.host=e,this.host.onData(e=>{if("request"===e.type)this.dispatchRequest(e);else if("response"===e.type){const t=e,n=this._pendingRequests[t.seq];n&&(delete this._pendingRequests[t.seq],n(t))}})}stop(){this.host&&this.host.close()}sendEvent(e){this.send("event",e)}sendResponse(t){t.seq>0?e.error(`attempt to send more than one response for command ${t.command}`):this.send("response",t)}sendRequest(e,n,s,i){const r={command:e};if(n&&Object.keys(n).length>0&&(r.arguments=n),this.send("request",r),i){this._pendingRequests[r.seq]=i;const e=setTimeout(()=>{clearTimeout(e);const n=this._pendingRequests[r.seq];n&&(delete this._pendingRequests[r.seq],n(new t.Response(r,"timeout")))},s)}}send(e,t){if(t.type=e,t.seq=this._sequence++,this.host){const e=JSON.stringify(t);this.host.send(e)}}dispatchRequest(e){}}t.ProtocolServer=i;class r extends i{constructor(){super(...arguments),this._debuggerLinesStartAt1=!1,this._debuggerColumnsStartAt1=!1,this._clientLinesStartAt1=!0,this._clientColumnsStartAt1=!0}shutdown(){}dispatchRequest(e){const n=new t.Response(e);try{if("initialize"===e.command){let t=e.arguments;if("boolean"==typeof t.linesStartAt1&&(this._clientLinesStartAt1=t.linesStartAt1),"boolean"==typeof t.columnsStartAt1&&(this._clientColumnsStartAt1=t.columnsStartAt1),"path"!==t.pathFormat)this.sendErrorResponse(n,2018,"debug adapter only supports native paths",null);else{const e=n;e.body={},this.initializeRequest(e,t)}}else"launch"===e.command?this.launchRequest(n,e.arguments):"attach"===e.command?this.attachRequest(n,e.arguments):"disconnect"===e.command?this.disconnectRequest(n,e.arguments):"setBreakpoints"===e.command?this.setBreakPointsRequest(n,e.arguments):"setFunctionBreakpoints"===e.command?this.setFunctionBreakPointsRequest(n,e.arguments):"setExceptionBreakpoints"===e.command?this.setExceptionBreakPointsRequest(n,e.arguments):"configurationDone"===e.command?this.configurationDoneRequest(n,e.arguments):"continue"===e.command?this.continueRequest(n,e.arguments):"next"===e.command?this.nextRequest(n,e.arguments):"stepIn"===e.command?this.stepInRequest(n,e.arguments):"stepOut"===e.command?this.stepOutRequest(n,e.arguments):"stepBack"===e.command?this.stepBackRequest(n,e.arguments):"restartFrame"===e.command?this.restartFrameRequest(n,e.arguments):"goto"===e.command?this.gotoRequest(n,e.arguments):"pause"===e.command?this.pauseRequest(n,e.arguments):"stackTrace"===e.command?this.stackTraceRequest(n,e.arguments):"scopes"===e.command?this.scopesRequest(n,e.arguments):"variables"===e.command?this.variablesRequest(n,e.arguments):"setVariable"===e.command?this.setVariableRequest(n,e.arguments):"source"===e.command?this.sourceRequest(n,e.arguments):"threads"===e.command?this.threadsRequest(n):"evaluate"===e.command?this.evaluateRequest(n,e.arguments):"stepInTargets"===e.command?this.stepInTargetsRequest(n,e.arguments):"gotoTargets"===e.command?this.gotoTargetsRequest(n,e.arguments):"completions"===e.command?this.completionsRequest(n,e.arguments):this.customRequest(e.command,n,e.arguments)}catch(e){this.sendErrorResponse(n,1104,"{_stack}",{_exception:e.message,_stack:e.stack})}}initializeRequest(e,t){e.body.supportsConditionalBreakpoints=!1,e.body.supportsHitConditionalBreakpoints=!1,e.body.supportsFunctionBreakpoints=!1,e.body.supportsConfigurationDoneRequest=!0,e.body.supportsEvaluateForHovers=!1,e.body.supportsStepBack=!1,e.body.supportsSetVariable=!1,e.body.supportsRestartFrame=!1,e.body.supportsStepInTargetsRequest=!1,e.body.supportsGotoTargetsRequest=!1,e.body.supportsCompletionsRequest=!1,this.sendResponse(e)}disconnectRequest(e,t){this.sendResponse(e),this.shutdown()}launchRequest(e,t){this.sendResponse(e)}attachRequest(e,t){this.sendResponse(e)}setBreakPointsRequest(e,t){this.sendResponse(e)}setFunctionBreakPointsRequest(e,t){this.sendResponse(e)}setExceptionBreakPointsRequest(e,t){this.sendResponse(e)}configurationDoneRequest(e,t){this.sendResponse(e)}continueRequest(e,t){this.sendResponse(e)}nextRequest(e,t){this.sendResponse(e)}stepInRequest(e,t){this.sendResponse(e)}stepOutRequest(e,t){this.sendResponse(e)}stepBackRequest(e,t){this.sendResponse(e)}restartFrameRequest(e,t){this.sendResponse(e)}gotoRequest(e,t){this.sendResponse(e)}pauseRequest(e,t){this.sendResponse(e)}sourceRequest(e,t){this.sendResponse(e)}threadsRequest(e){this.sendResponse(e)}stackTraceRequest(e,t){this.sendResponse(e)}scopesRequest(e,t){this.sendResponse(e)}variablesRequest(e,t){this.sendResponse(e)}setVariableRequest(e,t){this.sendResponse(e)}evaluateRequest(e,t){this.sendResponse(e)}stepInTargetsRequest(e,t){this.sendResponse(e)}gotoTargetsRequest(e,t){this.sendResponse(e)}completionsRequest(e,t){this.sendResponse(e)}customRequest(e,t,n){this.sendErrorResponse(t,1014,"unrecognized request",null)}sendErrorResponse(e,t,n,s){let i;"number"==typeof t?(i={id:t,format:n},s&&(i.variables=s),i.showUser=!0):i=t,e.success=!1,r.formatPII(i.format,!0,i.variables),e.body||(e.body={}),e.body.error=i,this.sendResponse(e)}convertClientLineToDebugger(e){return this._debuggerLinesStartAt1?this._clientLinesStartAt1?e:e+1:this._clientLinesStartAt1?e-1:e}convertDebuggerLineToClient(e){return this._debuggerLinesStartAt1?this._clientLinesStartAt1?e:e-1:this._clientLinesStartAt1?e+1:e}convertClientColumnToDebugger(e){return this._debuggerColumnsStartAt1?this._clientColumnsStartAt1?e:e+1:this._clientColumnsStartAt1?e-1:e}convertDebuggerColumnToClient(e){return this._debuggerColumnsStartAt1?this._clientColumnsStartAt1?e:e-1:this._clientColumnsStartAt1?e+1:e}convertClientPathToDebugger(e){return this._clientPathsAreURIs!=this._debuggerPathsAreURIs?this._clientPathsAreURIs?r.uri2path(e):r.path2uri(e):e}convertDebuggerPathToClient(e){return this._debuggerPathsAreURIs!=this._clientPathsAreURIs?this._debuggerPathsAreURIs?r.uri2path(e):r.path2uri(e):e}static path2uri(e){let t=e.replace(/\\/g,"/");return"/"!==t[0]&&(t="/"+t),encodeURI("file://"+t)}static uri2path(e){return e}static formatPII(e,t,n){return e.replace(r._formatPIIRegexp,function(e,s){return t&&s.length>0&&"_"!==s[0]?e:n[s]&&n.hasOwnProperty(s)?n[s]:e})}}r._formatPIIRegexp=/{([^}]+)}/g,t.DebugSession=r}(e.protocol||(e.protocol={}))}(pxsim||(pxsim={})),function(e){!function(e){e.injectPolyphils=function(){String.prototype.startsWith||Object.defineProperty(String.prototype,"startsWith",{value:function(e,t){return void 0!==e&&null!=e&&(t=!t||t<0?0:+t,this.substring(t,t+e.length)===e)}}),Array.prototype.fill||Object.defineProperty(Array.prototype,"fill",{writable:!0,enumerable:!0,value:function(e){if(null==this)throw new TypeError("this is null or not defined");let t=Object(this),n=t.length>>>0,s=arguments[1]|0,i=s<0?Math.max(n+s,0):Math.min(s,n),r=arguments[2],o=void 0===r?n:r|0,a=o<0?Math.max(n+o,0):Math.min(o,n);for(;i<a;)t[i]=e,i++;return t}}),Array.prototype.find||Object.defineProperty(Array.prototype,"find",{writable:!0,enumerable:!0,value:function(e){if(null==this)throw new TypeError('"this" is null or not defined');let t=Object(this);const n=t.length>>>0;if("function"!=typeof e)throw new TypeError("predicate must be a function");const s=arguments[1];let i=0;for(;i<n;){const n=t[i];if(e.call(s,n,i,t))return n;i++}}}),Uint8Array.prototype.slice||Object.defineProperty(Uint8Array.prototype,"slice",{value:Array.prototype.slice,writable:!0,enumerable:!0}),Uint16Array.prototype.slice||Object.defineProperty(Uint16Array.prototype,"slice",{value:Array.prototype.slice,writable:!0,enumerable:!0}),Uint32Array.prototype.slice||Object.defineProperty(Uint32Array.prototype,"slice",{value:Array.prototype.slice,writable:!0,enumerable:!0}),Uint8Array.prototype.fill||Object.defineProperty(Uint8Array.prototype,"fill",{value:Array.prototype.fill,writable:!0,enumerable:!0}),Uint16Array.prototype.fill||Object.defineProperty(Uint16Array.prototype,"fill",{value:Array.prototype.fill,writable:!0,enumerable:!0}),Uint32Array.prototype.fill||Object.defineProperty(Uint32Array.prototype,"fill",{value:Array.prototype.fill,writable:!0,enumerable:!0}),Uint8Array.prototype.some||Object.defineProperty(Uint8Array.prototype,"some",{value:Array.prototype.some,writable:!0,enumerable:!0}),Uint16Array.prototype.some||Object.defineProperty(Uint16Array.prototype,"some",{value:Array.prototype.some,writable:!0,enumerable:!0}),Uint32Array.prototype.some||Object.defineProperty(Uint32Array.prototype,"some",{value:Array.prototype.some,writable:!0,enumerable:!0}),Uint8Array.prototype.reverse||Object.defineProperty(Uint8Array.prototype,"reverse",{value:Array.prototype.reverse,writable:!0,enumerable:!0}),Uint16Array.prototype.reverse||Object.defineProperty(Uint16Array.prototype,"reverse",{value:Array.prototype.reverse,writable:!0,enumerable:!0}),Uint32Array.prototype.reverse||Object.defineProperty(Uint32Array.prototype,"reverse",{value:Array.prototype.reverse,writable:!0,enumerable:!0}),Math.imul||(Math.imul=function(e,t){const n=65535&e,s=65535&t;return n*s+((e>>>16&65535)*s+n*(t>>>16&65535)<<16>>>0)|0}),"function"!=typeof Object.assign&&Object.defineProperty(Object,"assign",{value:function(e,t){"use strict";if(null==e)throw new TypeError("Cannot convert undefined or null to object");let n=Object(e);for(let e=1;e<arguments.length;e++){let t=arguments[e];if(null!=t)for(let e in t)Object.prototype.hasOwnProperty.call(t,e)&&(n[e]=t[e])}return n},writable:!0,configurable:!0}),Promise.prototype.finally||(Promise.prototype.finally=Promise.prototype.finally||{finally(e){const t=t=>Promise.resolve(e()).then(t);return this.then(e=>t(()=>e),e=>t(()=>Promise.reject(e)))}}.finally)};function t(e){e=e.replace(/\\/g,"/");const t=[];return e.split("/").forEach(e=>{".."===e&&t.length?t.pop():e&&"."!==e&&t.push(e)}),t}e.Lazy=class{constructor(e){this._func=e,this._evaluated=!1}get value(){return this._evaluated||(this._value=this._func(),this._evaluated=!0),this._value}},e.getNormalizedParts=t,e.normalizePath=function(e){return t(e).join("/")},e.relativePath=function(e,n){const s=t(e),i=t(n);let r=0;for(;s[r]===i[r]&&(r++,r!==s.length&&r!==i.length););const o=s.slice(r),a=i.slice(r);for(let e=0;e<o.length;e++)a.unshift("..");return a.join("/")},e.pathJoin=function(...e){let t="";return e.forEach(e=>{e.replace(/\\/g,"/"),e.lastIndexOf("/")===e.length-1&&(e=e.slice(0,e.length-1)),t+="/"+e}),t},e.toArray=function(e){if(Array.isArray(e))return e;let t=[];for(let n=0;n<e.length;++n)t.push(e[n]);return t}}(e.util||(e.util={}))}(pxsim||(pxsim={})),function(e){e.getWarningMessage=function(t){let n={type:"debugger",subtype:"warning",breakpointIds:[],message:t},s=e.runtime.currFrame;for(;null!=s;)n.breakpointIds.push(s.lastBrkId),s=s.parent;return n};function t(t,n){switch(typeof t){case"string":case"number":case"boolean":return t;case"function":return{text:"(function)",type:"function"};case"undefined":return null;case"object":if(!t)return null;if(t instanceof e.RefObject){n&&(n[t.id]=t);let s=e.RefObject.toDebugString(t),i=s.startsWith("[")?"array":s;return{id:t.id,preview:s,hasFields:null!==t.fields||s.startsWith("["),type:i}}return t._width&&t._height?{text:t._width+"x"+t._height,type:"image"}:{text:"(object)",type:"object"};default:throw new Error}}function n(n,i,r,o,a=!1){return function(n,r){const l={};for(let e of Object.keys(n))/^__/.test(e)||!/___\d+$/.test(e)||o&&-1===o.indexOf(e)||(l[e]=t(n[e],i));if(n.fields&&r)for(let e of r)e=e.substring(e.lastIndexOf(".")+1),l[e]=t(s(n.vtable.iface[e],n),i);if(n.fields)for(let e of Object.keys(n.fields).filter(e=>a||!e.startsWith("_")))l[e]=t(n.fields[e],i);else if(n instanceof e.RefMap)for(const e of n.data)l[e.key]=t(e.val,i);else Array.isArray(n.data)?n.data.forEach((e,n)=>{l[n]=t(e,i)}):void 0!==n._width&&void 0!==n._height&&(l.width=n._width,l.height=n._height,a&&void 0!==n._bpp&&(l.isMono=1===n._bpp));return l}(n,r)}function s(e,t){let n={pc:0,arg0:t,fn:e,parent:{}};for(;n.fn;)n=n.fn(n);return n.retval}function i(e,s){let i=e.fn?e.fn.info:null;if(i){let r={thisParam:t(e.argL,s),params:[]};if(i.argumentNames){const n=i.argumentNames;r.params=n.map((n,i)=>({name:n,value:t(e["arg"+i],s)}))}return{locals:n(e,s),funcInfo:i,breakpointId:e.lastBrkId,callLocationId:e.callLocIdx,arguments:r}}}e.BreakpointMap=class{constructor(e){this.fileMap={},this.idMap={},e.forEach(e=>{const[t,n]=e;this.fileMap[n.source.path]||(this.fileMap[n.source.path]=[]),this.fileMap[n.source.path].push(e),this.idMap[t]=n});for(const e in this.fileMap){const t=this.fileMap[e];this.fileMap[e]=t.sort(([,e],[,t])=>e.line===t.line?t.endLine===e.endLine?e.column-t.column:t.endLine-e.endLine:e.line-t.line)}}getById(e){return this.idMap[e]}verifyBreakpoint(e,t){const n=this.fileMap[e];let s;if(n)for(const[e,i]of n)i.line<=t.line&&i.endLine>=t.line&&(s=[e,i]);return s?(s[1].verified=!0,s):[-1,{verified:!1}]}},e.dumpHeap=n,e.injectEnvironmentGlobals=function(n,s){const i=e.runtime.environmentGlobals;if(!Object.keys(i).length)return;const r=n.environmentGlobals={};Object.keys(i).forEach(n=>r[n]=t(e.runtime.environmentGlobals[n],s))},e.getBreakpointMsg=function(t,s,r){const o={},a={type:"debugger",subtype:"breakpoint",breakpointId:s,globals:n(e.runtime.globals,o,void 0,r),stackframes:[]};for(;null!=t;){let e=i(t,o);e&&a.stackframes.push(e),t=t.parent}return{msg:a,heap:o}};class r extends e.protocol.DebugSession{constructor(t){super();let n={onDebuggerBreakpoint:e=>this.onDebuggerBreakpoint(e),onDebuggerWarning:e=>this.onDebuggerWarning(e),onDebuggerResume:()=>this.onDebuggerResume(),onStateChanged:e=>this.onStateChanged(e)};this.driver=new e.SimulatorDriver(t,n)}runCode(t,n,s,i,r){this.breakpoints=i,this.projectDir&&this.fixBreakpoints(),this.sendEvent(new e.protocol.InitializedEvent),this.driver.run(t,{parts:n,fnArgs:s,boardDefinition:r})}stopSimulator(e=!1){this.driver.stop(e)}initializeRequest(e,t){e.body.supportsConditionalBreakpoints=!1,e.body.supportsHitConditionalBreakpoints=!1,e.body.supportsFunctionBreakpoints=!1,e.body.supportsEvaluateForHovers=!1,e.body.supportsStepBack=!1,e.body.supportsSetVariable=!1,e.body.supportsRestartFrame=!1,e.body.supportsStepInTargetsRequest=!1,e.body.supportsGotoTargetsRequest=!1,e.body.supportsCompletionsRequest=!1,e.body.supportsConfigurationDoneRequest=!0,this.sendResponse(e)}disconnectRequest(e,t){this.sendResponse(e),this.shutdown()}launchRequest(t,n){this.projectDir||(this.projectDir=e.util.normalizePath(n.projectDir),this.breakpoints&&this.fixBreakpoints()),this.sendResponse(t)}setBreakPointsRequest(t,n){t.body={breakpoints:[]};const s=[];n.breakpoints.forEach(i=>{if(this.breakpoints){const[r,o]=this.breakpoints.verifyBreakpoint(e.util.relativePath(this.projectDir,n.source.path),i);t.body.breakpoints.push(o),o.verified&&s.push(r)}else t.body.breakpoints.push({verified:!1})}),this.driver.setBreakpoints(s),this.sendResponse(t)}continueRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.Resume),this.sendResponse(t)}nextRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.StepOver),this.sendResponse(t)}stepInRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.StepInto),this.sendResponse(t)}stepOutRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.StepOut),this.sendResponse(t)}pauseRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.Pause),this.sendResponse(t)}threadsRequest(e){e.body={threads:[{id:r.THREAD_ID,name:"main"}]},this.sendResponse(e)}stackTraceRequest(e,t){if(this.lastBreak){const t=this.state.getFrames();e.body={stackFrames:t}}this.sendResponse(e)}scopesRequest(e,t){this.state&&(e.body={scopes:this.state.getScopes(t.frameId)}),this.sendResponse(e)}variablesRequest(e,t){this.state&&(e.body={variables:this.state.getVariables(t.variablesReference)}),this.sendResponse(e)}onDebuggerBreakpoint(t){if(this.lastBreak=t,this.state=new o(this.lastBreak,this.breakpoints,this.projectDir),t.exceptionMessage){const n=t.exceptionMessage.replace(/___\d+/g,"");this.sendEvent(new e.protocol.StoppedEvent("exception",r.THREAD_ID,n))}else this.sendEvent(new e.protocol.StoppedEvent("breakpoint",r.THREAD_ID))}onDebuggerWarning(e){}onDebuggerResume(){this.sendEvent(new e.protocol.ContinuedEvent(r.THREAD_ID,!0))}onStateChanged(t){switch(t){case e.SimulatorState.Paused:break;case e.SimulatorState.Running:this.sendEvent(new e.protocol.ContinuedEvent(r.THREAD_ID,!0));break;case e.SimulatorState.Stopped:this.sendEvent(new e.protocol.TerminatedEvent)}}fixBreakpoints(){for(const t in this.breakpoints.idMap){const n=this.breakpoints.idMap[t];n.source.path=e.util.pathJoin(this.projectDir,n.source.path),n.line=this.convertDebuggerLineToClient(n.line),n.endLine=this.convertDebuggerLineToClient(n.endLine),n.column=this.convertDebuggerColumnToClient(n.column),n.endColumn=this.convertDebuggerColumnToClient(n.endColumn)}}}r.THREAD_ID=1,e.SimDebugSession=r;class o{constructor(e,t,n){this._message=e,this._map=t,this._dir=n,this._currentId=1,this._frames={},this._vars={};const s=this.nextId();this._vars[s]=this.getVariableValues(this._message.globals),this._globalScope={name:"Globals",variablesReference:s,expensive:!1}}getFrames(){return this._message.stackframes.map((e,t)=>{const n=this._map.getById(e.breakpointId);if(n)return this._frames[e.breakpointId]=e,{id:e.breakpointId,name:e.funcInfo?e.funcInfo.functionName:0===t?"main":"anonymous",line:n.line,column:n.column,endLine:n.endLine,endColumn:n.endLine,source:n.source}}).filter(e=>!!e)}getScopes(e){const t=this._frames[e];if(t){const e=this.nextId();return this._vars[e]=this.getVariableValues(t.locals),[{name:"Locals",variablesReference:e,expensive:!1},this._globalScope]}return[this._globalScope]}getVariables(e){const t=this._vars[e];return t&&t.value||[]}getVariableValues(t){return new e.util.Lazy(()=>{const e=[];for(const n in t){const s=t[n];let i,r=0;null===s?i="null":void 0===s?i="undefined":"object"==typeof s?(i="(object)",r=this.nextId(),this._vars[r]=this.getVariableValues(s)):i=s.toString();const o=n.substr(0,n.lastIndexOf("___"));e.push({name:o,value:i,variablesReference:r})}return e})}nextId(){return this._currentId++}}}(pxsim||(pxsim={})),function(e){let t,n;function s(e=0){function t(){try{window.print()}catch(e){}}e?setTimeout(t,e):t()}function i(e,t){r({type:"pxtsim",action:"event",tick:e,data:t})}function r(e){"undefined"!=typeof window&&window.parent&&window.parent!==window&&window.parent.postMessage(e,"*")}function o(){setInterval(()=>{e.Runtime.postMessage({type:"simulator",command:"reload"})},3e3)}!function(e){let t;!function(e){e[e.Player=0]="Player",e[e.Reaction=1]="Reaction"}(t=e.IconType||(e.IconType={}))}(t=e.multiplayer||(e.multiplayer={})),e.print=s,function(t){function n(t){t.origin;let n=t.data||{},o=n.type;if(o)switch(o){case"run":l(n);break;case"instructions":e.instructions.renderInstructions(n);break;case"stop":a();break;case"mute":u(n.mute);break;case"stopsound":e.AudioContextManager.stopAll();break;case"print":s();break;case"recorder":!function(e){if(!r)return;switch(e.action){case"start":r.startRecording(e.width);break;case"stop":r.stopRecording()}}(n);break;case"screenshot":e.Runtime.postScreenshotAsync(n);break;case"custom":e.handleCustomMessage&&e.handleCustomMessage(n);break;case"pxteditor":break;case"debugger":r&&r.handleDebuggerMsg(n);break;case"simulator":let t=n;switch(t.command){case"focus":i("simulator.focus",{timestamp:t.timestamp});break;case"blur":i("simulator.blur",{timestamp:t.timestamp})}default:!function(e){if(!r||r.dead)return;r.board.receiveMessage(e)}(n)}}let r;function a(){r&&(r.kill(),r.board&&r.board.kill())}function l(t){a(),t.mute&&u(t.mute),t.localizedStrings&&e.localization.setLocalizedStrings(t.localizedStrings);const n=new e.Runtime(t);r=n,n.board.initAsync(t).then(()=>{n===r&&n.run(t=>{e.dumpLivePointers(),e.Runtime.postMessage({type:"toplevelcodefinished"})})})}function u(t){e.AudioContextManager.mute(t)}t.start=function(){window.addEventListener("message",n,!1),t.frameid=window.location.hash.slice(1),function(){if("serviceWorker"in navigator&&-1!==window.location.href.indexOf("---simulator")&&!e.U.isLocalHost()){const t=window.location.pathname,n=t.substring(1,t.indexOf("---"));navigator.serviceWorker.controller&&navigator.serviceWorker.addEventListener("message",e=>{const t=e.data;t&&"serviceworker"===t.type&&"activated"===t.state&&t.ref===n&&o()});const s=window.location.href.replace(/---simulator.*$/,"---simserviceworker");navigator.serviceWorker.register(s).then(function(t){e.log("Simulator ServiceWorker registration successful with scope: ",t.scope)},function(t){e.log("Simulator ServiceWorker registration failed: ",t)})}}(),e.Runtime.postMessage({type:"ready",frameid:t.frameid})},t.stop=a,t.run=l}(n=e.Embed||(e.Embed={})),e.tickEvent=i,e.reportError=function(e,t,n){r({type:"pxtsim",action:"event",tick:"error",category:e,message:t,data:n})},e.reload=o}(pxsim||(pxsim={})),pxsim.util.injectPolyphils(),"undefined"!=typeof window&&window.addEventListener("load",function(e){pxsim.Embed.start()}),function(e){!function(t){const n=e=>`${e}x`,s=.95,[i,r]=[816*s,1056*s],o=i-86.4,a=r-86.4,l="gray",[u,c]=[1,1],h=24,d=o/c-48*c,p=`\n .instr-panel {\n margin: 20px;\n padding: 24px;\n border-width: 4px;\n border-color: ${l};\n border-style: solid;\n border-radius: 20px;\n display: inline-block;\n width: ${d}px;\n height: ${a/u-48*u}px;\n position: relative;\n overflow: hidden;\n page-break-inside: avoid;\n }\n .board-svg {\n margin: 0 auto;\n display: block;\n position: absolute;\n bottom: 24px;\n left: ${(d-465)/2+h}px;\n }\n .panel-num-outer {\n position: absolute;\n left: -4px;\n top: -4px;\n width: 120px;\n height: 120px;\n border-width: 4px;\n border-style: solid;\n border-color: ${l};\n border-radius: 20px 0 20px 0;\n }\n .panel-num {\n margin: 10px 0;\n text-align: center;\n font-size: 80px;\n }\n .cmp-div {\n display: inline-block;\n }\n .reqs-div {\n margin-left: 144px;\n margin-top: 5px;\n }\n .partslist-wire,\n .partslist-cmp {\n margin: 10px;\n }\n .partslist-wire {\n display: inline-block;\n }\n `;function f(t,n){let s=document.createElementNS("http://www.w3.org/2000/svg","svg"),i={l:0,t:0,w:0,h:0},r=document.createElementNS("http://www.w3.org/2000/svg","svg");s.appendChild(r),r.appendChild(t.el);let o={viewBox:`${t.x} ${t.y} ${t.w} ${t.h}`,preserveAspectRatio:"xMidYMid"};i.w=t.w,i.h=t.h;let a=e=>{i.h*=e,i.w*=e,o.width=i.w,o.height=i.h};n.cmpScale&&a(n.cmpScale),n.cmpWidth&&n.cmpWidth<i.w?a(n.cmpWidth/i.w):n.cmpHeight&&n.cmpHeight<i.h&&a(n.cmpHeight/i.h),e.svg.hydrate(r,o);let l=i.l,u=i.t,c=i.w,h=i.h,d=e=>{if(e<i.l){let t=i.l-e;i.l=e,i.w+=t}},p=e=>{let t=i.l+i.w;if(t<e){let n=e-t;i.w+=n}},f=e=>{if(e<i.t){let t=i.t-e;i.t=e,i.h+=t}},m=e=>{let t=i.t+i.h;if(t<e){let n=e-t;i.h+=n}},[g,b]=[-.3,.3];const v=[1.4,1];if(n&&n.top){let t=n.topSize,i=t/v[0],r=t/v[1],[o,a]=[l+c/2,u-3-r/2],h=e.visuals.mkTxt(o,a,t,0,n.top,g,b);e.U.addClass(h,"cmp-lbl"),s.appendChild(h);let m=i*n.top.length;f(a-r/2),d(o-m/2),p(o+m/2)}if(n&&n.bot){let t=n.botSize,i=t/v[0],r=t/v[1],[o,a]=[l+c/2,u+h+3+r/2],f=e.visuals.mkTxt(o,a,t,0,n.bot,g,b);e.U.addClass(f,"cmp-lbl"),s.appendChild(f);let y=i*n.bot.length;m(a+r/2),d(o-y/2),p(o+y/2)}if(n&&n.right){let t=n.rightSize,i=t/v[1],r=t/v[0]*n.right.length,[o,a]=[l+c+5+r/2,u+h/2],d=e.visuals.mkTxt(o,a,t,0,n.right,g,b);e.U.addClass(d,"cmp-lbl"),s.appendChild(d),f(a-i/2),p(o+r/2),m(a+i/2)}if(n&&n.left){let t=n.leftSize,i=t/v[1],r=t/v[0]*n.left.length,[o,a]=[l-5-r/2,u+h/2],c=e.visuals.mkTxt(o,a,t,0,n.left,g,b);e.U.addClass(c,"cmp-lbl"),s.appendChild(c),f(a-i/2),d(o-r/2),m(a+i/2)}let y={viewBox:`${i.l} ${i.t} ${i.w} ${i.h}`,width:1.7*i.w,height:1.7*i.h,preserveAspectRatio:"xMidYMid"};e.svg.hydrate(s,y);let S=document.createElement("div");return S.appendChild(s),S}function m(t,n){let s,i=e.runtime.board;if("wire"==t)s=e.visuals.mkWirePart([0,0],n.wireClr||"red",n.crocClips);else{let n=t;if("string"==typeof n.builtIn){s=(0,i.builtinPartVisuals[n.builtIn])([0,0])}else s=e.visuals.mkGenericPartSVG(n)}return f(s,n)}function g(t,n,s=!1){const i={state:e.runtime.board,boardDef:t.boardDef,forceBreadboardLayout:!0,forceBreadboardRender:t.allAlloc.requiresBreadboard,partDefs:t.cmpDefs,maxWidth:`${n}px`,fnArgs:t.fnArgs,wireframe:s,partsList:[]};let r=new e.visuals.BoardHost(e.visuals.mkBoardView({visual:i.boardDef.visual,boardDef:i.boardDef,wireframe:i.wireframe}),i),o=r.getView();return e.U.addClass(o,"board-svg"),r}function b(){let t=document.createElement("div");return e.U.addClass(t,"instr-panel"),t}function v(t){let s=b();var i;let r=f((i=t.boardDef,e.visuals.mkBoardView({visual:i.visual,boardDef:i}).getView()),{left:n(1),leftSize:30,cmpScale:.17});s.appendChild(r);let o=f(new e.visuals.Breadboard({}).getSVGAndSize(),{left:n(1),leftSize:30,cmpScale:.25});return s.appendChild(o),t.allCmps.forEach(t=>{let i=1;"buttonpair"===t.visual.builtIn&&(i=2);let r=m(t.visual,{left:n(i),leftSize:30,cmpScale:.3});e.U.addClass(r,"partslist-cmp"),s.appendChild(r)}),t.allWireColors.forEach(i=>{let r=t.colorToWires[i].length,o=t.boardDef.pinStyles[i]||"female",a=m("wire",{left:n(r),leftSize:20,wireClr:i,cmpScale:.23,crocClips:"croc"==o});e.U.addClass(a,"partslist-wire"),s.appendChild(a)}),s}function y(t,n){let s=b(),i=g(n,465,!0);!function(t,n,s){let i=t.getView();n>0&&e.U.addClass(i,"grayed");for(let i=0;i<=n;i++){let r=s.stepToCmps[i];r&&r.forEach(s=>{let r=t.addPart(s);i===n&&(s.breadboardConnections.forEach(e=>t.highlightBreadboardPin(e)),e.U.addClass(r.element,"notgrayed"))});let o=s.stepToWires[i];o&&o.forEach(e=>{let s=t.addWire(e);s&&i===n&&("breadboard"==e.start.type?t.highlightBreadboardPin(e.start):t.highlightBoardPin(e.start.pin),"breadboard"==e.end.type?t.highlightBreadboardPin(e.end):t.highlightBoardPin(e.end.pin),t.highlightWire(s))})}}(i,t,n),s.appendChild(i.getView());let r=document.createElement("div");e.U.addClass(r,"panel-num-outer"),e.U.addClass(r,"noselect"),s.appendChild(r);let o=document.createElement("div");e.U.addClass(o,"panel-num"),o.textContent=t+1+"",r.appendChild(o);let a=document.createElement("div");e.U.addClass(a,"reqs-div"),s.appendChild(a);let l=n.stepToWires[t]||[],u=e=>{if("breadboard"===e.type){let{row:t,col:n}=e;return`(${t},${n})`}return e.pin};return l.forEach(t=>{let s=!1;"dalboard"==t.end.type&&(s="croc"==n.boardDef.pinStyles[t.end.pin]);let i=m("wire",{top:u(t.end),topSize:10,bot:u(t.start),botSize:10,wireClr:t.color,cmpHeight:40,crocClips:s});e.U.addClass(i,"cmp-div"),a.appendChild(i)}),(n.stepToCmps[t]||[]).forEach(t=>{let n;n="buttonpair"===t.visual.builtIn?[t.breadboardConnections[0],t.breadboardConnections[2]]:[t.breadboardConnections[0]],n.forEach((n,s)=>{let i;if(n){let{row:e,col:t}=n;i=`(${e},${t})`}else i="";let r=1.5;"buttonpair"===t.visual.builtIn&&(r*=.5);let o=m(t.visual,{top:i,topSize:10,cmpHeight:50,cmpScale:r});e.U.addClass(o,"cmp-div"),a.appendChild(o)})}),s}function S(t,n){n.boardDef.pinStyles||(n.boardDef.pinStyles={}),n.configData&&e.setConfigData(n.configData.cfg,n.configData.cfgKey);const s={type:"run",code:"",boardDefinition:n.boardDef,partDefinitions:n.partDefinitions};e.runtime=new e.Runtime(s),e.runtime.board=null,e.initCurrentRuntime(s);let i=document.createElement("style");i.textContent+=p,document.head.appendChild(i);const r=n.partDefinitions;let o=new e.visuals.Breadboard({}),a=function(t){let n=e.allocateDefinitions(t),s=[],i=[],r=1;n.partsAndWires.forEach(e=>{let t=e.part,n=e.wires;e.assembly.forEach((e,o)=>{e.part&&t&&(i[r+o]=[t]),e.wireIndices&&e.wireIndices.length>0&&n&&(s[r+o]=e.wireIndices.map(e=>n[e]))}),r+=e.assembly.length});let o=r-1,a=n.partsAndWires.map(e=>e.part).filter(e=>!!e),l=n.partsAndWires.map(e=>e.wires||[]).reduce((e,t)=>e.concat(t),[]),u={},c=[];return l.forEach(e=>{u[e.color]||(u[e.color]=[],c.push(e.color)),u[e.color].push(e)}),{boardDef:t.boardDef,cmpDefs:t.partDefs,fnArgs:t.fnArgs,allAlloc:n,stepToWires:s,stepToCmps:i,allWires:l,allCmps:a,lastStep:o,colorToWires:u,allWireColors:c}}({boardDef:n.boardDef,partDefs:r,partsList:n.parts,fnArgs:n.fnArgs,getBBCoord:o.getCoord.bind(o)});a.allAlloc.requiresBreadboard=!0;!function(e){let t=document.getElementById("front-panel"),n=g(e,400,!1);n.addAll(e.allAlloc),t.appendChild(n.getView())}(a);let l=v(a);t.appendChild(l);for(let e=0;e<=a.lastStep;e++){let n=y(e,a);t.appendChild(n)}n.print&&e.print(2e3)}t.renderParts=S,t.renderInstructions=function(e){document.getElementById("proj-title").innerText=e.options.name||"",S(document.body,e.options)}}(e.instructions||(e.instructions={}))}(pxsim||(pxsim={})),function(e){function t(e,t="sim: check failed"){if(!e)throw new Error(t)}e.quiet=!1,e.check=t,e.title="";let n,s,i,r,o,a={},l={};e.getConfig=function(e){return l.hasOwnProperty(e+"")?l[e+""]:null},e.getConfigKey=function(e){return a.hasOwnProperty(e)?a[e]:null},e.getAllConfigKeys=function(){return Object.keys(a)},e.setConfigKey=function(e,t){a[e]=t},e.setConfig=function(e,t){l[e]=t},e.setConfigData=function(e,t){l=e,a=t},e.getConfigData=function(){return{cfg:l,cfgKey:a}},e.setTitle=function(t){e.title=t};class u{constructor(){e.runtime?this.id=e.runtime.registerLiveObject(this):this.id=0}destroy(){}scan(t){throw e.U.userError("scan not implemented")}gcKey(){throw e.U.userError("gcKey not implemented")}gcSize(){throw e.U.userError("gcSize not implemented")}gcIsStatic(){return!1}print(){e.runtime&&e.runtime.refCountingDebug&&e.log(`RefObject id:${this.id}`)}toDebugString(){return"(object)"}static toAny(e){return e&&e.toAny?e.toAny():e}static fromAny(t){return t?t instanceof u?t:Array.isArray(t)?e.RefCollection.fromAny(t):"object"==typeof t?h.fromAny(t):t:t}static toDebugString(e){return null===e?"null":void 0===e?"undefined;":e.vtable&&e.vtable.name?"_Map"===e.vtable.name&&e instanceof f?"(object)":e.vtable.name:e.toDebugString?e.toDebugString():e.vtable&&e.vtable.name?e.vtable.name:"string"==typeof e?JSON.stringify(e):e.toString()}}e.RefObject=u;class c{constructor(e,t,n){this.func=e,this.caps=t,this.args=n}}e.FnWrapper=c;class h extends u{constructor(){super(...arguments),this.fields={}}scan(e){for(let t of Object.keys(this.fields))e(t,this.fields[t])}gcKey(){return this.vtable.name}gcSize(){return this.vtable.numFields+1}destroy(){this.fields=null,this.vtable=null}print(){e.runtime&&e.runtime.refCountingDebug&&e.log(`RefRecord id:${this.id} (${this.vtable.name})`)}toDebugString(){let e="RefRecord: {";const t=Object.keys(this.fields);for(let n=0;n<t.length;++n)n>0&&(e+=", "),e+=t[n]+": "+u.toDebugString(this.fields[t[n]]);return e+"}"}toAny(){const e={};for(let t of Object.keys(this.fields))e[t]=u.toAny(this.fields[t]);return e}static fromAny(e){const t=new h;for(let n of Object.keys(e))t.fields[n]=u.fromAny(e[n]);return t}}e.RefRecord=h;class d extends u{constructor(){super(...arguments),this.fields=[]}scan(e){for(let t=0;t<this.fields.length;++t)e("_cap"+t,this.fields[t])}gcKey(){return e.functionName(this.func)}gcSize(){return this.fields.length+3}isRef(e){return t(0<=e&&e<this.fields.length),e<this.len}ldclo(e){return t(0<=(e>>=2)&&e<this.fields.length),this.fields[e]}destroy(){this.fields=null,this.func=null}print(){e.runtime&&e.runtime.refCountingDebug&&e.log(`RefAction id:${this.id} len:${this.fields.length}`)}}e.RefAction=d,function(t){t.seedAddRandom=function(e){},t.mkAction=function(e,t){let n=new d;n.len=e,n.func=t;for(let t=0;t<e;++t)n.fields.push(null);return n},t.runAction=function(t,n){let s=e.getResume();s(t instanceof d?new c(t.func,t.fields,n):new c(t,null,n))};let n={};t.dumpPerfCounters=function(){if(!e.runtime||!e.runtime.perfCounters)return;let t="calls,us,name\n";for(let n of e.runtime.perfCounters){n.lastFew.sort();const e=n.lastFew[n.lastFew.length>>1];t+=`${n.numstops},${n.value},${n.name},${e}\n`}!function(t){let s="";const i=(e,t)=>{s+=e.length>=t?e:(" "+e).slice(-t)},r=(e,t)=>{s+=e.length>=t?e:(e+" ").slice(0,t)},o=e=>i(""+Math.round(e),6),a=(e,t)=>{i(Math.round(t)+"",8),s+=" /",o(e),s+=" =",o(t/e)};for(let e of t.split(/\n/)){if(!e)continue;if(!/^\d/.test(e))continue;const t=e.split(/,/);let i=n[t[2]];i||(n[t[2]]=i={stops:0,us:0,meds:[]}),r(t[2],25);const l=parseInt(t[0]),u=parseInt(t[1]);a(l,u),s+=" |",a(l-i.stops,u-i.us),s+=" ~";const c=parseInt(t[3]);o(c),i.meds.length>10&&i.meds.shift(),i.meds.push(c);const h=i.meds.slice();h.sort((e,t)=>e-t);const d=h[h.length>>1];s+=" ~~",o(d),i.stops=l,i.us=u,s+="\n"}e.log(s)}(t)}}(n=e.pxtcore||(e.pxtcore={}));class p extends u{constructor(){super(...arguments),this.v=void 0}scan(e){e("*",this.v)}gcKey(){return"LOC"}gcSize(){return 2}destroy(){}print(){e.runtime&&e.runtime.refCountingDebug&&e.log(`RefRefLocal id:${this.id} v:${this.v}`)}}e.RefRefLocal=p;class f extends u{constructor(){super(...arguments),this.vtable=e.mkMapVTable(),this.data=[]}scan(e){for(let t of this.data)e(t.key,t.val)}gcKey(){return"{...}"}gcSize(){return 2*this.data.length+4}findIdx(e){e+="";for(let t=0;t<this.data.length;++t)if(this.data[t].key==e)return t;return-1}destroy(){super.destroy();for(let e=0;e<this.data.length;++e)this.data[e].val=0;this.data=[]}print(){e.runtime&&e.runtime.refCountingDebug&&e.log(`RefMap id:${this.id} size:${this.data.length}`)}toDebugString(){let e="RefMap: {";for(let t=0;t<this.data.length;++t)t>0&&(e+=", "),e+=this.data[t].key+": "+u.toDebugString(this.data[t].val);return e+"}"}toAny(){const e={};return this.data.forEach(t=>{e[t.key]=u.toAny(t.val)}),e}static fromAny(e){const t=new f;for(let n of Object.keys(e))t.data.push({key:n,val:u.fromAny(e[n])});return t}}function m(){e.runtime&&e.runtime.dumpLivePointers()}e.RefMap=f,e.dumpLivePointers=m,function(e){e.toString=function(e){return null===e?"null":void 0===e?"undefined":e.toString()},e.toBoolDecr=function(e){return!!e},e.toBool=function(e){return!!e}}(s=e.numops||(e.numops={})),function(e){e.toInt=function(e){return 0|e},e.toFloat=function(e){return e},e.ignore=function(e){return e}}(i=e.langsupp||(e.langsupp={})),function(t){t.ptrOfLiteral=function(e){return e},t.debugMemLeaks=function(){m()},t.templateHash=function(){return 0},t.programHash=function(){return 0},t.programName=function(){return e.title},t.programSize=function(){return 0},t.afterProgramPage=function(){return 0},t.getConfig=function(t,n){let s=e.getConfig(t);return null==s?n:s},t.toInt=function(e){return e|0},t.toUInt=function(e){return e>>>0},t.toDouble=function(e){return e},t.toFloat=function(e){return e},t.fromInt=function(e){return e},t.fromUInt=function(e){return e},t.fromDouble=function(e){return e},t.fromFloat=function(e){return e},t.fromBool=function(e){return!!e}}(n=e.pxtcore||(e.pxtcore={})),function(n){function s(t,n){if(t||e.throwFailedPropertyAccessError(t,n),n+="",t instanceof h){return t.fields[n]}let s=t.findIdx(n);if(!(s<0))return t.data[s].val}function i(t,n,s){if(t||e.throwFailedPropertyAccessError(t,n),n+="",t instanceof h){return void(t.fields[n]=s)}let i=t.findIdx(n);i<0?t.data.push({key:n,val:s}):t.data[i].val=s}n.toInt8=function(e){return(255&e)<<24>>24},n.toInt16=function(e){return(65535&e)<<16>>16},n.toInt32=function(e){return 0|e},n.toUInt32=function(e){return e>>>0},n.toUInt8=function(e){return 255&e},n.toUInt16=function(e){return 65535&e},n.nullFix=function(e){return null==e||!1===e?0:!0===e?1:e},n.nullCheck=function(t){null==t&&e.U.userError("Dereferencing null/undefined value.")},n.panic=function(t){e.U.userError("PANIC! Code "+t)},n.stringToBool=function(e){return e?1:0},n.ptrToBool=function(e){return e?1:0},n.emptyToNull=function(e){return""==e?0:e},n.ldlocRef=function(e){return e.v},n.stlocRef=function(e,t){e.v=t},n.mklocRef=function(){return new p},n.stclo=function(e,n,s){return t(0<=n&&n<e.fields.length),t(null===e.fields[n]),e.fields[n]=s,e},n.runtimeWarning=function(t){e.Runtime.postMessage(e.getWarningMessage(t))},n.mkMap=function(){return new f},n.mapGet=function(e,t){return s(e,n.mapKeyNames[t])},n.mapSet=function(e,t,s){return i(e,n.mapKeyNames[t],s)},n.mapGetByString=s,n.mapDeleteByString=function(t,n){null==t&&e.throwNullUndefinedAsObjectError(),t instanceof f||e.throwFailedCastError(t,"object");let s=t.findIdx(n);return s>=0&&t.data.splice(s,1),!0},n.mapSetGeneric=i,n.mapGetGeneric=s,n.mapSetByString=i,n.keysOf=function(t){null==t&&e.throwNullUndefinedAsObjectError();let n=new e.RefCollection;if(t instanceof f)for(let e of t.data)n.push(e.key);return n}}(r=e.pxtrt||(e.pxtrt={})),function(e){e.mkClassInstance=function(e){t(!!e.methods);let n=new h;return n.vtable=e,n},e.switch_eq=function(e,t){return e==t},e.typeOf=function(e){return typeof e}}(n=e.pxtcore||(e.pxtcore={})),function(t){function n(t){t&&(t instanceof d||t.info)||e.throwFailedCastError(t,"function")}t.panic=r.panic,t.pause=function(t){let n=e.getResume();e.runtime.schedule(()=>{n()},t)},t.runInBackground=function(t){n(t),e.runtime.runFiberAsync(t)},t.forever=function(t){n(t),function n(){e.runtime.runFiberAsync(t).then(()=>e.U.delay(20)).then(n)}()},t.typeCheck=n}(o=e.thread||(e.thread={}))}(pxsim||(pxsim={})),function(e){class t extends e.RefObject{constructor(){super(),this.data=[]}scan(e){for(let t=0;t<this.data.length;++t)e("["+t+"]",this.data[t])}gcKey(){return"[...]"}gcSize(){return this.data.length+2}toArray(){return this.data.slice(0)}toAny(){return this.data.map(t=>e.RefObject.toAny(t))}static fromAny(n,s=!0){const i=new t;return i.data=s?n.map(t=>e.RefObject.fromAny(t)):n.slice(0),i}toDebugString(){let t="[";for(let n=0;n<this.data.length;++n){n>0&&(t+=",");let s=e.RefObject.toDebugString(this.data[n]);if(t.length+s.length>100){0==n&&(t+=s.substr(0,100)),t+="...";break}t+=s}return t+="]",t}destroy(){let e=this.data;for(let t=0;t<e.length;++t)e[t]=0;this.data=[]}isValidIndex(e){return e>=0&&e<this.data.length}push(e){this.data.push(e)}pop(){return this.data.pop()}getLength(){return this.data.length}setLength(e){this.data.length=e}getAt(e){return this.data[e]}setAt(e,t){this.data[e]=t}insertAt(e,t){this.data.splice(e,0,t)}removeAt(e){return this.data.splice(e,1)[0]}indexOf(e,t){return this.data.indexOf(e,t)}print(){}}let n,s,i,r,o,a,l,u;e.RefCollection=t,function(n){function s(e,t){if(r(e),e.isValidIndex(t))return e.removeAt(t)}function i(e,t,n){return r(e),e.indexOf(t,n)}function r(n){n instanceof t||e.throwFailedCastError(n,"Array")}n.mk=function(){return new t},n.isArray=function(e){return e instanceof t},n.length=function(e){return r(e),e.getLength()},n.setLength=function(e,t){r(e),e.setLength(t)},n.push=function(e,t){r(e),e.push(t)},n.pop=function(e,t){return r(e),e.pop()},n.getAt=function(e,t){return r(e),e.getAt(t)},n.removeAt=s,n.insertAt=function(e,t,n){r(e),e.insertAt(t,n)},n.setAt=function(e,t,n){r(e),e.setAt(t,n)},n.indexOf=i,n.removeElement=function(e,t){r(e);let n=i(e,t,0);return n>=0?(s(e,n),1):0},n.typeCheck=r}(n=e.Array_||(e.Array_={})),function(e){e.imul=Math.imul||function(e,t){const n=65535&e,s=65535&t;return n*s+((e>>>16&65535)*s+n*(t>>>16&65535)<<16>>>0)|0},e.idiv=function(e,t){return(0|e)/(0|t)|0},e.round=function(e){return Math.round(e)},e.roundWithPrecision=function(e,t){if((t|=0)<=0)return Math.round(e);if(0==e)return 0;let n=0;for(;0==n&&t<21;){const s=Math.pow(10,t++);n=Math.round(e*s+Number.EPSILON)/s}return n},e.ceil=function(e){return Math.ceil(e)},e.floor=function(e){return Math.floor(e)},e.sqrt=function(e){return Math.sqrt(e)},e.pow=function(e,t){return Math.pow(e,t)},e.clz32=function(e){return Math.clz32(e)},e.log=function(e){return Math.log(e)},e.log10=function(e){return Math.log10(e)},e.log2=function(e){return Math.log2(e)},e.exp=function(e){return Math.exp(e)},e.sin=function(e){return Math.sin(e)},e.sinh=function(e){return Math.sinh(e)},e.cos=function(e){return Math.cos(e)},e.cosh=function(e){return Math.cosh(e)},e.tan=function(e){return Math.tan(e)},e.tanh=function(e){return Math.tanh(e)},e.asin=function(e){return Math.asin(e)},e.asinh=function(e){return Math.asinh(e)},e.acos=function(e){return Math.acos(e)},e.acosh=function(e){return Math.acosh(e)},e.atan=function(e){return Math.atan(e)},e.atanh=function(e){return Math.atanh(e)},e.atan2=function(e,t){return Math.atan2(e,t)},e.trunc=function(e){return e>0?Math.floor(e):Math.ceil(e)},e.random=function(){return Math.random()},e.randomRange=function(e,t){if(e==t)return e;if(e>t){let n=e;e=t,t=n}return Math.floor(e)==e&&Math.floor(t)==t?e+Math.floor(Math.random()*(t-e+1)):e+Math.random()*(t-e)}}(s=e.Math_||(e.Math_={})),function(t){function n(t,n){return e.pxtrt.nullFix(t)==e.pxtrt.nullFix(n)}t.lt=function(e,t){return e<t},t.le=function(e,t){return e<=t},t.neq=function(e,t){return!n(e,t)},t.eq=n,t.eqDecr=function(t,n){return e.pxtrt.nullFix(t)==e.pxtrt.nullFix(n)},t.gt=function(e,t){return e>t},t.ge=function(e,t){return e>=t},t.div=function(e,t){return 0|Math.floor(e/t)},t.mod=function(e,t){return e%t},t.bnot=function(e){return~e},t.toString=function(e){return e+""}}(i=e.Number_||(e.Number_={})),function(e){e.adds=function(e,t){return e+t|0},e.subs=function(e,t){return e-t|0},e.divs=function(e,t){return 0|Math.floor(e/t)},e.muls=function(e,t){return s.imul(e,t)},e.ands=function(e,t){return e&t},e.orrs=function(e,t){return e|t},e.eors=function(e,t){return e^t},e.lsls=function(e,t){return e<<t},e.lsrs=function(e,t){return e>>>t},e.asrs=function(e,t){return e>>t},e.bnot=function(e){return~e},e.ignore=function(e){return e}}(r=e.thumb||(e.thumb={})),function(e){function t(e){return e<<16>>16}e.adds=function(e,n){return t(e+n)},e.subs=function(e,n){return t(e-n)},e.divs=function(e,n){return t(Math.floor(e/n))},e.muls=function(e,n){return t(s.imul(e,n))},e.ands=function(e,n){return t(e&n)},e.orrs=function(e,n){return t(e|n)},e.eors=function(e,n){return t(e^n)},e.lsls=function(e,n){return t(e<<n)},e.lsrs=function(e,t){return(65535&e)>>>t},e.asrs=function(e,n){return t(e>>n)},e.bnot=function(e){return~e},e.ignore=function(e){return e}}(o=e.avr||(e.avr={})),function(t){function n(t){"string"!=typeof t&&e.throwFailedCastError(t,"string")}t.stringConv=function(t){const n=e.getResume();t instanceof e.RefRecord&&t.vtable.toStringMethod?e.runtime.runFiberAsync(t.vtable.toStringMethod,t).then(()=>{n(e.runtime.currFrame.retval+"")}):n(t+"")},t.mkEmpty=function(){return""},t.fromCharCode=function(e){return String.fromCharCode(e)},t.toNumber=function(e){return n(e),parseFloat(e)},t.concat=function(e,t){return n(e),e+t},t.substring=function(e,t,s){return n(e),e.slice(t,t+s)},t.equals=function(e,t){return n(e),e==t},t.compare=function(e,t){return n(e),e==t?0:e<t?-1:1},t.compareDecr=function(e,t){return n(e),e==t?0:e<t?-1:1},t.length=function(e){return n(e),e.length},t.substr=function(e,t,s){return n(e),e.substr(t,s)},t.charAt=function(e,t){return n(e),e.charAt(t)},t.charCodeAt=function(e,t){return n(e),function(e,t){return n(e),0<=t&&t<e.length}(e,t)?e.charCodeAt(t):0},t.indexOf=function(e,t,s){return n(e),null==t?-1:e.indexOf(t,s)},t.lastIndexOf=function(e,t,s){return n(e),null==t?-1:e.lastIndexOf(t,s)},t.includes=function(e,t,s){return n(e),null!=t&&e.includes(t,s)},t.typeCheck=n}(a=e.String_||(e.String_={})),function(e){e.toString=function(e){return e?"true":"false"},e.bang=function(e){return!e}}(l=e.Boolean_||(e.Boolean_={}));class c extends e.RefObject{constructor(e){super(),this.data=e,this.isStatic=!1}scan(e){}gcKey(){return"Buffer"}gcSize(){return 2+(this.data.length+3>>2)}gcIsStatic(){return this.isStatic}print(){}toDebugString(){return u.toHex(this)}}e.RefBuffer=c,function(t){let n;function s(t){let s=function(t){switch(t){case n.Int8LE:return-1;case n.UInt8LE:return 1;case n.Int16LE:return-2;case n.UInt16LE:return 2;case n.Int32LE:return-4;case n.UInt32LE:return 4;case n.Int8BE:return-10;case n.UInt8BE:return 10;case n.Int16BE:return-20;case n.UInt16BE:return 20;case n.Int32BE:return-40;case n.UInt32BE:return 40;case n.Float32LE:return 4;case n.Float32BE:return 40;case n.Float64LE:return 8;case n.Float64BE:return 80;default:throw e.U.userError("bad format")}}(t),i=!1;s<0&&(i=!0,s=-s);let r=!1;return s>=10&&(r=!0,s/=10),{size:s,signed:i,swap:r,isFloat:t>=n.Float32LE}}function i(e){return new c(new Uint8Array(e))}function r(e,t){return 0<=t&&t<e.data.length}function o(e,t){return f(e),r(e,t)?e.data[t]:0}function l(t){t.isStatic&&e.U.userError("Writing to read only buffer.")}function u(e,t,n){f(e),r(e,t)&&(l(e),e.data[t]=n)}function h(e,t,n=0,s=-1){f(e),n<0||n>e.data.length||(s<0&&(s=e.data.length),s=Math.min(s,e.data.length-n),l(e),e.data.fill(t,n,n+s))}function d(e,t,n,s,i){if(n.buffer===e.buffer)d(e,t,n.slice(s,s+i),0,i);else for(let r=0;r<i;++r)e[t+r]=n[s+r]}!function(e){e[e.Int8LE=1]="Int8LE",e[e.UInt8LE=2]="UInt8LE",e[e.Int16LE=3]="Int16LE",e[e.UInt16LE=4]="UInt16LE",e[e.Int32LE=5]="Int32LE",e[e.Int8BE=6]="Int8BE",e[e.UInt8BE=7]="UInt8BE",e[e.Int16BE=8]="Int16BE",e[e.UInt16BE=9]="UInt16BE",e[e.Int32BE=10]="Int32BE",e[e.UInt32LE=11]="UInt32LE",e[e.UInt32BE=12]="UInt32BE",e[e.Float32LE=13]="Float32LE",e[e.Float64LE=14]="Float64LE",e[e.Float32BE=15]="Float32BE",e[e.Float64BE=16]="Float64BE"}(n=t.NumberFormat||(t.NumberFormat={})),t.fmtInfo=s,t.getNumber=function(e,t,n){f(e);let i=s(t);if(i.isFloat){let t=e.data.buffer.slice(n,n+i.size);if(i.swap){new Uint8Array(t).reverse()}return 4==i.size?new Float32Array(t)[0]:new Float64Array(t)[0]}let r=0;for(let t=0;t<i.size;++t){r<<=8;let s=i.swap?n+t:n+i.size-t-1;r|=e.data[s]}if(i.signed){let e=32-8*i.size;r=r<<e>>e}else r>>>=0;return r},t.setNumber=function(e,t,n,i){f(e);let r=s(t);if(r.isFloat){let t=new Uint8Array(r.size);4==r.size?new Float32Array(t.buffer)[0]=i:new Float64Array(t.buffer)[0]=i,r.swap&&t.reverse();for(let s=0;s<r.size;++s)e.data[n+s]=t[s];return}for(let t=0;t<r.size;++t){let s=r.swap?n+r.size-t-1:n+t;e.data[s]=255&i,i>>=8}},t.createBuffer=i,t.createBufferFromHex=function(e){a.typeCheck(e);let t=i(e.length>>1);for(let n=0;n<e.length;n+=2)t.data[n>>1]=parseInt(e.slice(n,n+2),16);return t.isStatic=!0,t},t.isReadOnly=function(e){return f(e),e.isStatic},t.getBytes=function(e){return f(e),e.data},t.getUint8=function(e,t){return f(e),o(e,t)},t.getByte=o,t.setUint8=function(e,t,n){f(e),u(e,t,n)},t.setByte=u,t.length=function(e){return f(e),e.data.length},t.fill=h,t.slice=function(e,t,n){return f(e),t=Math.min(e.data.length,t),n<0&&(n=e.data.length),n=Math.min(n,e.data.length-t),new c(e.data.slice(t,t+n))},t.toHex=function(e){f(e);const t="0123456789abcdef";let n="";for(let s=0;s<e.data.length;++s)n+=t[e.data[s]>>4],n+=t[15&e.data[s]];return n},t.toString=function(t){return f(t),e.U.fromUTF8Array(t.data)};const p=-2147483648;function f(t){t instanceof c||e.throwFailedCastError(t,"Buffer")}t.shift=function(e,t,n,s){f(e),s<0&&(s=e.data.length-n),n<0||n+s>e.data.length||n+s<n||0==s||0==t||t==p||0!=s&&0!=t&&t!=p&&(t<=-s||t>=s?h(e,0):(l(e),t<0?(t=-t,d(e.data,n+t,e.data,n,s-t),e.data.fill(0,n,n+t)):(s-=t,d(e.data,n,e.data,n+t,s),e.data.fill(0,n+s,n+s+t))))},t.rotate=function(e,t,n,s){if(f(e),s<0&&(s=e.data.length-n),n<0||n+s>e.data.length||n+s<n||0==s||0==t||t==p)return;l(e),t<0&&(t+=s<<8),(t%=s)<0&&(t+=s);let i=e.data,r=t,o=0,a=r,u=s;for(;o!=a;){let e=i[o+n];i[o+++n]=i[a+n],i[a+++n]=e,a==u?a=r:o==r&&(r=a)}},t.write=function(e,t,n,s=0,i=-1){f(e),f(n),i<0&&(i=n.data.length),s<0||t<0||t>e.data.length||(i=Math.min(n.data.length-s,e.data.length-t))<0||(l(e),d(e.data,t,n.data,s,i))},t.typeCheck=f}(u=e.BufferMethods||(e.BufferMethods={}))}(pxsim||(pxsim={})),function(e){!function(t){t.createBufferFromUTF8=function(t){return e.String_.typeCheck(t),new e.RefBuffer(e.U.toUTF8Array(t))}}(e.control||(e.control={}))}(pxsim||(pxsim={})),function(e){!function(e){let t={};e.setLocalizedStrings=function(e){t=e||{}};function n(e,t){return 0==t.length?e:e.replace(/\{([0-9]+)(\:[^\}]+)?\}/g,function(e,n,r){let o=t[parseInt(n)],a="",l=/^:f(\d*)\.(\d+)/.exec(r);if(l){let e=parseInt(l[2]),t=parseInt(l[1])||0,n=/^0/.test(l[1])?"0":" ",s=o.toFixed(e);if(t>0&&e>0&&(t+=e+1),t>0)for(;s.length<t;)s=n+s;a=s}else a=":x"==r?"0x"+o.toString(16):void 0===o?"(undef)":null===o?"(null)":o.toString?o.toString():o+"";return":a"==r?/^\s*[euioah]/.test(a.toLowerCase())?a="an "+a:/^\s*[bcdfgjklmnpqrstvwxz]/.test(a.toLowerCase())&&(a="a "+a):":s"==r?a=1==o?"":"s":":q"==r?a=s(a):":jq"==r?a=i(a):":uri"==r?a=encodeURIComponent(a).replace(/'/g,"%27").replace(/"/g,"%22"):":url"==r?a=encodeURI(a).replace(/'/g,"%27").replace(/"/g,"%22"):":%"==r&&(a=(100*o).toFixed(1).toString()+"%"),a})}function s(e){return e?e.replace(/([^\w .!?\-$])/g,e=>"&#"+e.charCodeAt(0)+";"):e}function i(e){return e.replace(/[^\w .!?\-$]/g,e=>{let t=e.charCodeAt(0).toString(16);return"\\u"+"0000".substr(0,4-t.length)+t})}e.lf=function(e,...s){let i=t[e]||e;return i=i.replace(/^\{(id|loc):[^\}]+\}/g,""),n(i,s)},e.fmt_va=n,e.htmlEscape=s,e.jsStringQuote=i}(e.localization||(e.localization={}))}(pxsim||(pxsim={})),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={}));e.ConsoleLogger=class{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}};let n=new e.ConsoleLogger;e.info=function(...e){n.info(...e)},e.log=function(...e){n.log(...e)},e.debug=function(...e){n.debug(...e)},e.error=function(...e){n.error(...e)},e.warn=function(...e){n.warn(...e)},e.setLogger=function(e){const t=null==n?void 0:n.getLogLevel();n=e,void 0!==t&&n.setLogLevel(t)},e.setLogLevel=function(e){n.setLogLevel(e)}}(pxsim||(pxsim={})),function(pxsim){const MIN_MESSAGE_WAIT_MS=200;let tracePauseMs=0,MessageListenerFlags,U,pxtcore;!function(e){e[e.MESSAGE_BUS_LISTENER_REENTRANT=8]="MESSAGE_BUS_LISTENER_REENTRANT",e[e.MESSAGE_BUS_LISTENER_QUEUE_IF_BUSY=16]="MESSAGE_BUS_LISTENER_QUEUE_IF_BUSY",e[e.MESSAGE_BUS_LISTENER_DROP_IF_BUSY=32]="MESSAGE_BUS_LISTENER_DROP_IF_BUSY",e[e.MESSAGE_BUS_LISTENER_IMMEDIATE=192]="MESSAGE_BUS_LISTENER_IMMEDIATE"}(MessageListenerFlags||(MessageListenerFlags={})),function(e){function t(e){return e.split(/\s+/).filter(e=>!!e)}function n(e){for(;e.firstChild;)e.removeChild(e.firstChild)}let s;e.containsClass=function(e,n){return t(n).every(t=>function(e,t){if(e.classList)return e.classList.contains(t);return!((e.className+"").split(/\s+/).indexOf(t)<0)}(e,t))},e.addClass=function(e,n){t(n).forEach(t=>function(e,t){if(e.classList)e.classList.add(t);else{(e.className+"").split(/\s+/).indexOf(t)<0&&(e.className.baseVal+=" "+t)}}(e,t))},e.removeClass=function(e,n){t(n).forEach(t=>function(e,t){e.classList?e.classList.remove(t):e.className.baseVal=(e.className+"").split(/\s+/).filter(e=>e!=t).join(" ")}(e,t))},e.remove=function(e){e.parentElement.removeChild(e)},e.removeChildren=n,e.clear=function(e){n(e)},e.assert=function(e,t="Assertion failed"){if(!e)throw new Error(t)},e.repeatMap=function(e,t){e=e||0;let n=[];for(let s=0;s<e;++s)n.push(t(s));return n},e.userError=function(e){let t=new Error(e);throw t.isUserError=!0,t},e.now=function(){return Date.now()},e.perfNowUs=function(){return s||(s="undefined"!=typeof performance?performance.now.bind(performance)||performance.moznow.bind(performance)||performance.msNow.bind(performance)||performance.webkitNow.bind(performance)||performance.oNow.bind(performance):Date.now),1e3*s()};const i=Promise.resolve();async function r(e,t,n){let s=0;const i=[],r=[];for(let o=0;o<e;o++){const e=(async()=>{for(;s<t.length;){const e=s++,i=t[e];r[e]=await n(i)}})();i.push(e)}try{await Promise.all(i)}catch(e){throw s=t.length,e}return r}function o(){return"undefined"!=typeof window&&!!window.pxtElectron}function a(){return"undefined"!=typeof window&&!!window.ipcRenderer}function l(){return o()||a()}function u(e){return/^http:\/\/(?:localhost|127\.0\.0\.1|192\.168\.\d{1,3}\.\d{1,3}|[a-zA-Z0-9.-]+\.local):\d+\/?/.test(e)&&!/nolocalhost=1/.test(e)}function c(){try{return"undefined"!=typeof window&&u(window.location.href)}catch(e){return!1}}e.nextTick=function(e){i.then(e)},e.delay=async function(e,t){const n=await t;return await new Promise(t=>setTimeout(()=>t(),e)),n},e.throttle=function(e,t,n){let s;return function(){let i=this,r=arguments,o=n&&!s;s||(s=setTimeout(function(){s=null,n||e.apply(i,r)},t)),o&&e.apply(i,r)}},e.promiseMapAll=function(e,t){return Promise.all(e.map(e=>t(e)))},e.promiseMapAllSeries=function(e,t){return r(1,e,t)},e.promisePoolAsync=r,e.promiseTimeout=async function(e,t,n){let s,i;const r=new Promise((t,r)=>{i=t,s=setTimeout(()=>{i=void 0,clearTimeout(s),r(n||`Promise timed out after ${e}ms`)},e)});return Promise.race([t,r]).then(e=>(i&&(clearTimeout(s),i()),e))},e.stringToUint8Array=function(e){let t=e.length,n=new Uint8Array(t);for(let s=0;s<t;++s)n[s]=255&e.charCodeAt(s);return n},e.uint8ArrayToString=function(e){let t=e.length,n="";for(let s=0;s<t;++s)n+=String.fromCharCode(e[s]);return n},e.fromUTF8=function(e){if(!e)return"";let t="";for(let n=0;n<e.length;++n){let s=255&e.charCodeAt(n);t+=37==s||s>127?"%"+s.toString(16):e.charAt(n)}return decodeURIComponent(t)},e.toUTF8=function(e,t){let n="";if(!e)return n;for(let s=0;s<e.length;++s){let i=e.charCodeAt(s);if(i<=127)n+=e.charAt(s);else if(i<=2047)n+=String.fromCharCode(192|i>>6,128|63&i);else{if(!t&&55296<=i&&i<=56319){let t=e.charCodeAt(++s);isNaN(t)||(i=65536+(i-55296<<10)+(t-56320))}n+=i<=65535?String.fromCharCode(224|i>>12,128|i>>6&63,128|63&i):String.fromCharCode(240|i>>18,128|i>>12&63,128|i>>6&63,128|63&i)}}return n},e.toUTF8Array=function(e){return(new TextEncoder).encode(e)},e.fromUTF8Array=function(e){return(new TextDecoder).decode(e)},e.isPxtElectron=o,e.isIpcRenderer=a,e.isElectron=l,e.testLocalhost=u,e.isLocalHost=c,e.isLocalHostDev=function(){return c()&&!l()},e.unique=function(e,t){let n=[],s={};return e.forEach(e=>{let i=t(e);s.hasOwnProperty(i)||(s[i]=null,n.push(e))}),n},e.sanitizeCssName=function(e){let t=e.replace(/[^a-zA-Z0-9-_]/g,"_");return/^[a-zA-Z_]/.test(t)||(t="cls_"+t),t}}(U=pxsim.U||(pxsim.U={}));class BreakLoopException{}function getResume(){return pxsim.runtime.getResume()}pxsim.BreakLoopException=BreakLoopException,function(e){function t(e){let t=pxsim.runtime.currTryFrame();t||U.userError("unhandled exception: "+e);const n=t.handlerFrame;throw pxsim.runtime.currFrame=n,n.pc=t.handlerPC,n.tryFrame=t.parent,n.thrownValue=e,n.hasThrownValue=!0,new BreakLoopException}e.beginTry=function(e){pxsim.runtime.currFrame.tryFrame={parent:pxsim.runtime.currTryFrame(),handlerPC:e,handlerFrame:pxsim.runtime.currFrame}},e.endTry=function(){const e=pxsim.runtime.currFrame;e.tryFrame=e.tryFrame.parent},e.throwValue=t,e.getThrownValue=function(){const e=pxsim.runtime.currFrame;return U.assert(e.hasThrownValue),e.hasThrownValue=!1,e.thrownValue},e.endFinally=function(){const e=pxsim.runtime.currFrame;e.hasThrownValue&&(e.hasThrownValue=!1,t(e.thrownValue))}}(pxtcore=pxsim.pxtcore||(pxsim.pxtcore={})),pxsim.getResume=getResume;const SERIAL_BUFFER_LENGTH=16;class BaseBoard{constructor(){this.messageListeners=[],this.serialOutBuffer="",this.messages=[],this.lastSerialTime=0,this.debouncedPostAll=()=>{const e=Date.now();e-this.lastSerialTime>MIN_MESSAGE_WAIT_MS?(clearTimeout(this.serialTimeout),this.messages.length&&(Runtime.postMessage({type:"bulkserial",data:this.messages,id:pxsim.runtime.id,sim:!0}),this.messages=[],this.lastSerialTime=e)):this.serialTimeout=setTimeout(this.debouncedPostAll,50)},this.id=pxsim.Embed.frameid||"b"+Math.round(2147483647*Math.random()),this.bus=new pxsim.EventBus(pxsim.runtime,this)}updateView(){}receiveMessage(e){pxsim.runtime&&!pxsim.runtime.dead&&this.dispatchMessage(e)}dispatchMessage(e){for(const t of this.messageListeners)t(e)}addMessageListener(e){this.messageListeners.push(e)}get storedState(){return this.runOptions?(this.runOptions.storedState||(this.runOptions.storedState={}),this.runOptions.storedState):{}}initAsync(e){return this.runOptions=e,Promise.resolve()}setStoredState(e,t){null==t?delete this.storedState[e]:this.storedState[e]=t,Runtime.postMessage({type:"simulator",command:"setstate",stateKey:e,stateValue:t})}onDebuggerResume(){}screenshotAsync(e){return Promise.resolve(void 0)}kill(){}writeSerial(e){this.serialOutBuffer+=e,(/\n/.test(this.serialOutBuffer)||this.serialOutBuffer.length>SERIAL_BUFFER_LENGTH)&&(this.messages.push({time:Date.now(),data:this.serialOutBuffer}),this.debouncedPostAll(),this.serialOutBuffer="")}}pxsim.BaseBoard=BaseBoard;class CoreBoard extends BaseBoard{constructor(){super(),this.updateSubscribers=[],this.updateView=()=>{this.updateSubscribers.forEach(e=>e())},this.builtinParts={},this.builtinVisuals={},this.builtinPartVisuals={}}kill(){super.kill(),pxsim.codal.music.__stopSoundExpressions(),pxsim.AudioContextManager.stopAll(),pxsim.AudioContextManager.SpatialAudioPlayer.disposeAll(),pxsim.AudioContextManager.setListenerPosition(0,0,0)}}pxsim.CoreBoard=CoreBoard;class BareBoard extends BaseBoard{}function initBareRuntime(){pxsim.runtime.board=new BareBoard;let e=pxsim;e.basic={pause:pxsim.thread.pause,showNumber:e=>{let t=getResume();pxsim.log("SHOW NUMBER:",e),U.nextTick(t)}},e.serial={writeString:e=>pxsim.runtime.board.writeSerial(e)},e.pins={createBuffer:pxsim.BufferMethods.createBuffer},e.control={inBackground:pxsim.thread.runInBackground,createBuffer:pxsim.BufferMethods.createBuffer,dmesg:e=>pxsim.log("DMESG: "+e),deviceDalVersion:()=>"sim",__log:(e,t)=>pxsim.log("LOG: "+t.trim())}}let LogType;pxsim.initBareRuntime=initBareRuntime,function(e){e[e.UserSet=0]="UserSet",e[e.BackAdd=1]="BackAdd",e[e.BackRemove=2]="BackRemove"}(LogType||(LogType={}));class EventHandler{constructor(e,t){this.handler=e,this.flags=t,this.busy=0}async runAsync(e,t,n){const s=this.flags||MessageListenerFlags.MESSAGE_BUS_LISTENER_QUEUE_IF_BUSY;if(s!==MessageListenerFlags.MESSAGE_BUS_LISTENER_IMMEDIATE)return s===MessageListenerFlags.MESSAGE_BUS_LISTENER_QUEUE_IF_BUSY?this.runFiberAsync(e,t,n):void(s===MessageListenerFlags.MESSAGE_BUS_LISTENER_DROP_IF_BUSY&&this.busy||this.runFiberAsync(e,t,n));U.userError("MESSAGE_BUS_LISTENER_IMMEDIATE is not supported!")}async runFiberAsync(e,t,n){this.busy++,await t.runFiberAsync(this.handler,...n?n(e):[e]),this.busy--}}class EventQueue{constructor(e,t){this.runtime=e,this.valueToArgs=t,this.max=5,this.events=[],this.awaiters=[],this._handlers=[],this._addRemoveLog=[]}push(e,t){if(this.awaiters.length>0)if(t){const e=this.awaiters.shift();e&&e()}else{const e=this.awaiters.slice();this.awaiters=[],e.forEach(e=>e())}return 0==this.handlers.length||this.events.length>this.max?Promise.resolve():(this.events.push(e),this.lock?Promise.resolve():this.poke())}async poke(){this.lock=!0;let e=this.events;this.events=[];for(const t of e)for(const e of this.handlers)await e.runAsync(t,this.runtime,this.valueToArgs);if(this.events.length>0)return this.poke();this.lock=!1;for(const e of this._addRemoveLog)e.log===LogType.BackAdd?this.addHandler(e.act,e.flags):e.log===LogType.BackRemove?this.removeHandler(e.act):this.setHandler(e.act,e.flags);this._addRemoveLog=[]}get handlers(){return this._handlers}setHandler(e,t=0){this.lock?this._addRemoveLog.push({act:e,log:LogType.UserSet,flags:t}):this._handlers=[new EventHandler(e,t)]}addHandler(e,t=0){this.lock?this._addRemoveLog.push({act:e,log:LogType.BackAdd,flags:t}):this._handlers.some(t=>t.handler===e)||this._handlers.push(new EventHandler(e,t))}removeHandler(e){if(this.lock)this._addRemoveLog.push({act:e,log:LogType.BackRemove,flags:0});else{let t=this._handlers.findIndex(t=>t.handler===e);-1!=t&&this._handlers.splice(t,1)}}addAwaiter(e){this.awaiters.push(e)}}function bind(e){const t=e.arg0,n=e.fn;return e=>{let s=0;for(;e.hasOwnProperty("arg"+s);)s++;const i=e;for(let e=s;e>0;e--)i["arg"+e]=i["arg"+(e-1)];return e.arg0=t,n(e)}}function _leave(e,t){return e.parent.retval=t,e.parent}function syntheticRefAction(e){return pxtcore.mkAction(0,t=>_leave(t,e(t)))}pxsim.EventQueue=EventQueue,pxsim.initCurrentRuntime=void 0,pxsim.handleCustomMessage=void 0,pxsim.syntheticRefAction=syntheticRefAction;class TimeoutScheduled{constructor(e,t,n,s){this.id=e,this.fn=t,this.totalRuntime=n,this.timestampCall=s}}pxsim.TimeoutScheduled=TimeoutScheduled;class PausedTimeout{constructor(e,t){this.fn=e,this.timeRemaining=t}}function mkVTable(e){return{name:e.name,numFields:e.numFields,classNo:e.classNo,methods:e.methods,iface:e.iface,lastSubtypeNo:e.lastSubtypeNo,toStringMethod:e.toStringMethod,maxBgInstances:e.maxBgInstances}}pxsim.PausedTimeout=PausedTimeout,pxsim.mkVTable=mkVTable;let mapVTable=null;function mkMapVTable(){return mapVTable||(mapVTable=mkVTable({name:"_Map",numFields:0,classNo:0,lastSubtypeNo:0,methods:null})),mapVTable}function functionName(e){const t=e.info;return t?`${t.functionName} (${t.fileName}:${t.line+1}:${t.column+1})`:"()"}pxsim.mkMapVTable=mkMapVTable,pxsim.functionName=functionName;class Runtime{constructor(msg){this.numGlobals=1e3,this.dead=!1,this.running=!1,this.idleTimer=void 0,this.recording=!1,this.recordingTimer=0,this.recordingLastImageData=void 0,this.recordingWidth=void 0,this.startTime=0,this.startTimeUs=0,this.pausedTime=0,this.lastPauseTimestamp=0,this.globals={},this.environmentGlobals={},this.otherFrames=[],this.loopLock=null,this.loopLockWaitList=[],this.heapSnapshots=[],this.timeoutsScheduled=[],this.timeoutsPausedOnBreakpoint=[],this.pausedOnBreakpoint=!1,this.traceDisabled=!1,this.perfOffset=0,this.perfElapsed=0,this.perfStack=0,this.refCountingDebug=!1,this.refObjId=1,this.numDisplayUpdates=0,U.assert(!!pxsim.initCurrentRuntime),this.id=msg.id,this.refCountingDebug=!!msg.refCountingDebug;let threadId=0,breakpoints=null,currResume,dbgHeap,dbgResume,breakFrame=null,lastYield=Date.now(),userGlobals,__this=this;this.traceDisabled=!!msg.traceDisabled;const yieldDelay=void 0!==msg.yieldDelay?msg.yieldDelay:5,evalIface={runtime:this,oops:oops,doNothing:doNothing,pxsim:pxsim,globals:this.globals,setupYield:setupYield,maybeYield:maybeYield,setupDebugger:setupDebugger,isBreakFrame:isBreakFrame,breakpoint:breakpoint,trace:trace,checkStack:checkStack,leave:_leave,checkResumeConsumed:checkResumeConsumed,setupResume:setupResume,setupLambda:setupLambda,checkSubtype:checkSubtype,failedCast:failedCast,buildResume:buildResume,mkVTable:mkVTable,bind:bind,leaveAccessor:leaveAccessor};function oops(e){throw new Error("sim error: "+e)}function doNothing(e){return e.pc=-1,_leave(e,e.parent.retval)}function flushLoopLock(){for(;__this.loopLockWaitList.length>0&&!__this.loopLock;){__this.loopLockWaitList.shift()()}}let yieldReset=()=>{};function setupYield(e){yieldReset=e}function loopForSchedule(e){const t=new Object,n=e.pc;return __this.loopLock=t,__this.otherFrames.push(e),()=>{__this.dead||(U.assert(e.pc==n),U.assert(__this.loopLock===t),__this.loopLock=null,loop(e),flushLoopLock())}}function maybeYield(e,t,n){if(__this.pausedOnBreakpoint)return!1;__this.cleanScheduledExpired(),yieldReset();let s=Date.now();return s-lastYield>=20&&(lastYield=s,e.pc=t,e.r0=n,setTimeout(loopForSchedule(e),yieldDelay),!0)}function setupDebugger(e,t){return breakpoints=new Uint8Array(e),breakpoints[0]=msg.breakOnStart?1:0,userGlobals=t,breakpoints}function isBreakFrame(e){if(!breakFrame)return!0;for(let t=breakFrame;t;t=t.parent)if(t==e)return!0;return!1}function breakpoint(e,t,n,s){let i={};__this.loopLock=i,U.assert(!dbgResume),U.assert(!dbgHeap),e.pc=t,e.r0=s;const{msg:r,heap:o}=pxsim.getBreakpointMsg(e,n,userGlobals);return dbgHeap=o,pxsim.injectEnvironmentGlobals(r,o),Runtime.postMessage(r),breakpoints[0]=0,breakFrame=null,__this.pauseScheduled(),dbgResume=n=>{if(dbgResume=null,dbgHeap=null,__this.dead)return null;switch(__this.resumeAllPausedScheduled(),__this.board.onDebuggerResume(),pxsim.runtime=__this,U.assert(e.pc==t),breakpoints[0]=0,breakFrame=null,n.subtype){case"resume":break;case"stepover":breakpoints[0]=1,breakFrame=e;break;case"stepinto":breakpoints[0]=1;break;case"stepout":breakpoints[0]=1,breakFrame=e.parent||e}U.assert(__this.loopLock==i),__this.loopLock=null,__this.otherFrames.push(e),loop(e),flushLoopLock()},null}function trace(e,t,n,s){if(setupResume(t,n),"<main>"===s.functionName||"main.ts"===s.fileName){if(!pxsim.runtime.traceDisabled){const{msg:n}=pxsim.getBreakpointMsg(t,e,userGlobals);n.subtype="trace",Runtime.postMessage(n)}pxsim.thread.pause(tracePauseMs||1)}else pxsim.thread.pause(0);checkResumeConsumed()}function handleDebuggerMsg(e){switch(e.subtype){case"config":let t=e;if(t.setBreakpoints&&breakpoints){breakpoints.fill(0);for(let e of t.setBreakpoints)breakpoints[e]=1}break;case"traceConfig":tracePauseMs=e.interval;break;case"pause":breakpoints[0]=1,breakFrame=null;break;case"resume":case"stepover":case"stepinto":case"stepout":dbgResume&&dbgResume(e);break;case"variables":const n=e;let s;if(dbgHeap){const e=dbgHeap[n.variablesReference];void 0!==e&&(s=pxsim.dumpHeap(e,dbgHeap,n.fields,void 0,n.includeAll))}Runtime.postMessage({type:"debugger",subtype:"variables",req_seq:e.seq,variables:s})}}function removeFrame(e){const t=__this.otherFrames;for(let n=t.length-1;n>=0;--n)if(t[n]===e)return void t.splice(n,1);U.userError("frame cannot be removed!")}function loop(e){if(__this.dead)pxsim.log("Runtime terminated");else{U.assert(!__this.loopLock),__this.perfStartRuntime(),removeFrame(e);try{for(pxsim.runtime=__this;e;)__this.currFrame=e,__this.currFrame.overwrittenPC=!1,e=e.fn(e),__this.maybeUpdateDisplay(),__this.currFrame.overwrittenPC&&(e=__this.currFrame);__this.perfStopRuntime()}catch(t){if(t instanceof BreakLoopException)return void U.nextTick(loopForSchedule(__this.currFrame));if(__this.perfStopRuntime(),__this.errorHandler)__this.errorHandler(t);else{pxsim.error("Simulator crashed, no error handler",t.stack);const{msg:n,heap:s}=pxsim.getBreakpointMsg(e,e.lastBrkId,userGlobals);pxsim.injectEnvironmentGlobals(n,s),n.exceptionMessage=t.message,n.exceptionStack=t.stack,Runtime.postMessage(n),__this.postError&&__this.postError(t)}}}}function checkStack(e){e>100&&U.userError("Stack overflow")}function actionCall(e){return e.depth=e.parent.depth+1,checkStack(e.depth),e.pc=0,e}function setupTop(e){let t=setupTopCore(e);return setupResume(t,0),t}function setupTopCore(e){let t={parent:null,pc:0,depth:0,threadId:++threadId,fn:()=>(e&&e(t.retval),null)};return t}function topCall(e,t){U.assert(!!__this.board),U.assert(!__this.running),__this.setRunning(!0);let n={parent:setupTopCore(t),fn:e,depth:0,pc:0};__this.otherFrames=[n],loop(actionCall(n))}function checkResumeConsumed(){currResume&&oops("getResume() not called")}function setupResume(e,t){currResume=buildResume(e,t)}function leaveAccessor(e,t){if(e.stage2Call){const n={pc:0,fn:null,depth:e.depth,parent:e.parent};let s=1;for(;e.hasOwnProperty("arg"+s);)n["arg"+(s-1)]=e["arg"+s],s++;return setupLambda(n,t),n}return e.parent.retval=t,e.parent}function setupLambda(e,t,n){if(n){const t=e;for(let e=1;e<n;++e)t["arg"+(e-1)]=t["arg"+e];delete t["arg"+(n-1)]}t instanceof pxsim.RefAction?(e.fn=t.func,e.caps=t.fields):"function"==typeof t?e.fn=t:oops("calling non-function")}function checkSubtype(e,t){if(!e)return!1;const n=e.vtable;return t===n||n&&t.classNo<=n.classNo&&n.classNo<=t.lastSubtypeNo}function failedCast(e,t){pxsim.control&&pxsim.control.dmesgValue&&pxsim.control.dmesgValue(e),throwFailedCastError(e,null==t?void 0:t.name)}function buildResume(e,t){currResume&&oops("already has resume"),e.pc=t;let n=Date.now();__this.otherFrames.push(e);let s=i=>{if(__this.dead)return;if(__this.loopLock)return void __this.loopLockWaitList.push(()=>s(i));pxsim.runtime=__this;let r=Date.now();if(r-n>3&&(lastYield=r),U.assert(e.pc==t),i instanceof pxsim.FnWrapper){let t=i,n={parent:e,fn:t.func,lambdaArgs:t.args,pc:0,caps:t.caps,depth:e.depth+1},s={};return __this.loopLock=s,removeFrame(e),__this.otherFrames.push(n),U.nextTick(()=>{U.assert(__this.loopLock===s),__this.loopLock=null,loop(actionCall(n)),flushLoopLock()})}return e.retval=i,loop(e)};return s}const entryPoint=msg.code&&eval(msg.code)(evalIface);this.run=e=>topCall(entryPoint,e),this.getResume=()=>{currResume||oops("noresume");let e=currResume;return currResume=null,e},this.setupTop=setupTop,this.handleDebuggerMsg=handleDebuggerMsg,this.entry=entryPoint,this.overwriteResume=e=>{currResume=null,e>=0&&(this.currFrame.pc=e),this.currFrame.overwrittenPC=!0},pxsim.runtime=this,pxsim.initCurrentRuntime(msg)}registerLiveObject(e){return this.refObjId++}runningTime(){return U.now()-this.startTime-this.pausedTime}runningTimeUs(){return 4294967295&U.perfNowUs()-this.startTimeUs}runFiberAsync(e,t,n,s){return new Promise((i,r)=>U.nextTick(()=>{pxsim.runtime=this,this.setupTop(i),pxtcore.runAction(e,[t,n,s])}))}currTryFrame(){for(let e=this.currFrame;e;e=e.parent)if(e.tryFrame)return e.tryFrame;return null}traceObjects(){const e={};for(;this.heapSnapshots.length>2;)this.heapSnapshots.shift();const t={count:0,size:0,name:"TOTAL"},n={TOTAL:t};function s(t,n,i=null){if(!(n instanceof pxsim.RefObject))return;const r=n;if(r.gcIsStatic())return;const o=e[r.id];if(o)return void(i&&o.pointers.push([i,t]));const a={obj:r,path:null,pointers:[[i,t]]};e[r.id]=a,r.scan((t,n)=>{n instanceof pxsim.RefObject&&!e[n.id]&&s(t,n,a)})}this.heapSnapshots.push({visited:e,statsByType:n});for(let e of Object.keys(this.globals))s(e.replace(/___\d+$/,""),this.globals[e]);const i=this.otherFrames.slice();this.currFrame&&i.indexOf(this.currFrame)<0&&i.unshift(this.currFrame);for(const e of this.getThreads()){const t="Thread-"+this.rootFrame(e).threadId;for(let n=e;n;n=n.parent){const e=t+"."+functionName(n.fn);for(let t of Object.keys(n))if(/^(r0|arg\d+|.*___\d+)/.test(t)){const i=n[t];i instanceof pxsim.RefObject&&(t=t.replace(/___.*/,""),s(e+"."+t,i))}if(n.caps)for(let t of n.caps)s(e+".cap",t)}}const r=Object.keys(e).map(t=>e[t]);r.sort((e,t)=>t.obj.gcSize()-e.obj.gcSize());const o=e=>{if(null!=e.path)return;let t="";e.path="(cycle)";for(let[n,s]of e.pointers){if(null==n)return void(e.path=s);o(n);const i=n.path+"."+s;(!t||t.length>i.length)&&(t=i)}e.path=t};r.forEach(o);const a=[t];for(const e of r){const s=e.obj.gcSize(),i=e.obj.gcKey();n.hasOwnProperty(i)||a.push(n[i]={count:0,size:0,name:i});const r=n[i];r.size+=s,r.count++,t.size+=s,t.count++}a.sort((e,t)=>e.size-t.size);let l="";const u=e=>(" "+e.toString()).slice(-7);for(const e of a)l+=u(4*e.size)+u(e.count)+" "+e.name+"\n";const c=e=>u(4*e.obj.gcSize())+" "+e.obj.gcKey()+" "+e.path,h=r.slice(0,20).map(c).join("\n");let d="";if(this.heapSnapshots.length>=3){const e=this.heapSnapshots[this.heapSnapshots.length-3].visited,t=this.heapSnapshots[this.heapSnapshots.length-2].visited,s=e=>e instanceof pxsim.RefRecord&&!!(e.vtable&&e.vtable.maxBgInstances&&n[e.gcKey()].count<=e.vtable.maxBgInstances);d=r.filter(n=>!e[n.obj.id]&&t[n.obj.id]).filter(e=>!s(e.obj)).map(c).join("\n")}return"Threads:\n"+this.threadInfo()+"\n\nSummary:\n"+l+"\n\nLarge Objects:\n"+h+"\n\nNew Objects:\n"+d}getThreads(){const e=this.otherFrames.slice();return this.currFrame&&e.indexOf(this.currFrame)<0&&e.unshift(this.currFrame),e}rootFrame(e){let t=e;for(;t.parent;)t=t.parent;return t}threadInfo(){const e=this.getThreads();let t="";for(let n of e){t+=`Thread ${this.rootFrame(n).threadId}:\n`;for(let e of pxsim.getBreakpointMsg(n,n.lastBrkId).msg.stackframes){let n=e.funcInfo;t+=` at ${n.functionName} (${n.fileName}:${n.line+1}:${n.column+1})\n`}t+="\n"}return t}static postMessage(e){e&&("undefined"!=typeof window&&window.parent&&window.parent.postMessage&&window.parent.postMessage(e,"*"),Runtime.messagePosted&&Runtime.messagePosted(e))}static async postScreenshotAsync(e){const t=pxsim.runtime&&pxsim.runtime.board;if(!t)return;const n=await t.screenshotAsync();Runtime.postMessage({type:"screenshot",data:n,delay:e&&e.delay})}static requestToggleRecording(){const e=pxsim.runtime;e&&Runtime.postMessage({type:"recorder",action:e.recording?"stop":"start"})}restart(){this.kill(),setTimeout(()=>pxsim.Runtime.postMessage({type:"simulator",command:"restart"}),500)}kill(){this.dead=!0,this.stopRecording(),this.stopIdle(),this.setRunning(!1)}updateDisplay(){this.board.updateView(),this.postFrame()}startRecording(e){!this.recording&&this.running&&(this.recording=!0,this.recordingTimer=setInterval(()=>this.postFrame(),66),this.recordingLastImageData=void 0,this.recordingWidth=e)}stopRecording(){this.recording&&(this.recordingTimer&&clearInterval(this.recordingTimer),this.recording=!1,this.recordingTimer=0,this.recordingLastImageData=void 0,this.recordingWidth=void 0)}postFrame(){if(!this.recording||!this.running)return;let e=pxsim.U.now();this.board.screenshotAsync(this.recordingWidth).then(t=>{this.recordingLastImageData&&isImageDataEqual(this.recordingLastImageData,t)||(this.recordingLastImageData=t,Runtime.postMessage({type:"screenshot",data:t,time:e}))})}queueDisplayUpdate(){this.numDisplayUpdates++}maybeUpdateDisplay(){this.numDisplayUpdates&&(this.numDisplayUpdates=0,this.updateDisplay())}setRunning(e){this.running!=e&&(this.running=e,this.running?(this.startTime=U.now(),this.startTimeUs=U.perfNowUs(),Runtime.postMessage({type:"status",frameid:pxsim.Embed.frameid,runtimeid:this.id,state:"running"})):(this.stopRecording(),this.stopIdle(),Runtime.postMessage({type:"status",frameid:pxsim.Embed.frameid,runtimeid:this.id,state:"killed"})),this.stateChanged&&this.stateChanged())}dumpLivePointers(){}setupPerfCounters(e){e&&e.length&&(this.perfCounters=e.map(e=>new PerfCounter(e)))}perfStartRuntime(){0!==this.perfOffset?this.perfStack++:this.perfOffset=U.perfNowUs()-this.perfElapsed}perfStopRuntime(){this.perfStack?this.perfStack--:(this.perfElapsed=this.perfNow(),this.perfOffset=0)}perfNow(){return 0===this.perfOffset&&U.userError("bad time now"),U.perfNowUs()-this.perfOffset|0}startPerfCounter(e){if(!this.perfCounters)return;const t=this.perfCounters[e];t.start&&U.userError("startPerf"),t.start=this.perfNow()}stopPerfCounter(e){if(!this.perfCounters)return;const t=this.perfCounters[e];t.start||U.userError("stopPerf");const n=this.perfNow()-t.start;t.start=0,t.value+=n,t.numstops++;let s=t.lastFewPtr++;s>=t.lastFew.length&&(s=0,t.lastFewPtr=1),t.lastFew[s]=n}startIdle(){void 0===this.idleTimer&&(this.idleTimer=setInterval(()=>{if(!this.running||this.pausedOnBreakpoint)return;const e=this.board.bus;e&&e.queueIdle()},20))}stopIdle(){void 0!==this.idleTimer&&(clearInterval(this.idleTimer),this.idleTimer=void 0)}schedule(e,t){if(t<=0&&(t=0),this.pausedOnBreakpoint)return this.timeoutsPausedOnBreakpoint.push(new PausedTimeout(e,t)),-1;const n=U.now(),s=new TimeoutScheduled(-1,e,t,n);return s.id=setTimeout(()=>{const t=this.timeoutsScheduled.indexOf(s);t>=0&&this.timeoutsScheduled.splice(t,1),e()},t),this.timeoutsScheduled.push(s),s.id}pauseScheduled(){this.pausedOnBreakpoint=!0,this.timeoutsScheduled.forEach(e=>{clearTimeout(e.id);let t=U.now()-e.timestampCall,n=e.totalRuntime-t;n<=0&&(n=1),this.timeoutsPausedOnBreakpoint.push(new PausedTimeout(e.fn,n))}),this.lastPauseTimestamp=U.now(),this.timeoutsScheduled=[]}resumeAllPausedScheduled(){this.pausedOnBreakpoint=!1,this.timeoutsPausedOnBreakpoint.forEach(e=>{this.schedule(e.fn,e.timeRemaining)}),this.lastPauseTimestamp&&(this.pausedTime+=U.now()-this.lastPauseTimestamp,this.lastPauseTimestamp=0),this.timeoutsPausedOnBreakpoint=[]}cleanScheduledExpired(){let e=U.now();this.timeoutsScheduled=this.timeoutsScheduled.filter(t=>{let n=e-t.timestampCall;return t.totalRuntime>n})}registerUserInteraction(){this.lastInteractionTime=Date.now(),this.thumbnailRecordingIntervalRef||this.lastThumbnailTime&&this.lastInteractionTime-this.lastThumbnailTime<1e3||(this.thumbnailFrames=[],this.thumbnailRecordingIntervalRef=setInterval(async()=>{const e=await this.board.screenshotAsync();this.thumbnailFrames.length&&isImageDataEqual(e,this.thumbnailFrames[this.thumbnailFrames.length-1])||(this.thumbnailFrames.push(e),(Date.now()-this.lastInteractionTime>1e4||this.thumbnailFrames.length>30)&&(clearInterval(this.thumbnailRecordingIntervalRef),this.thumbnailRecordingIntervalRef=void 0,this.lastThumbnailTime=Date.now(),Runtime.postMessage({type:"thumbnail",frames:this.thumbnailFrames})))},66))}}function throwUserException(e){throw new Error(e)}function throwTypeError(e){throwUserException(pxsim.localization.lf("TypeError: {0}",e))}function throwFailedCastError(e,t){const n=getType(e);throwTypeError(t?null==e?pxsim.localization.lf("Expected type {0} but received type {1}. Did you forget to assign a variable?",t,n):pxsim.localization.lf("Expected type {0} but received type {1}",t,n):pxsim.localization.lf("Cannot read properties of {0}",n))}function throwFailedPropertyAccessError(e,t){const n=getType(e);throwTypeError(t?pxsim.localization.lf("Cannot read properties of {0} (reading '{1}')",n,t):pxsim.localization.lf("Cannot read properties of {0}",n))}function throwNullUndefinedAsObjectError(){throwTypeError(pxsim.localization.lf("Cannot convert undefined or null to object"))}function getType(e){let t;const n=null==e?void 0:e.vtable;return t=n?n.name:null===e?"null":void 0===e?"undefined":e instanceof pxsim.RefCollection?"Array":e instanceof pxsim.RefBuffer?"Buffer":e instanceof pxsim.RefAction?"function":typeof e,t}function setParentMuteState(e){Runtime.postMessage({type:"setmutebuttonstate",state:e})}pxsim.Runtime=Runtime,pxsim.throwUserException=throwUserException,pxsim.throwTypeError=throwTypeError,pxsim.throwFailedCastError=throwFailedCastError,pxsim.throwFailedPropertyAccessError=throwFailedPropertyAccessError,pxsim.throwNullUndefinedAsObjectError=throwNullUndefinedAsObjectError,pxsim.setParentMuteState=setParentMuteState;class PerfCounter{constructor(e){this.name=e,this.start=0,this.numstops=0,this.value=0,this.lastFew=new Uint32Array(32),this.lastFewPtr=0}}function isImageDataEqual(e,t){if(e.data.byteLength!==t.data.byteLength)return!1;const n=e.data.byteLength;let s=0;for(s=0;s<n&&e.data[s]==t.data[s];++s);return s===n}pxsim.PerfCounter=PerfCounter}(pxsim||(pxsim={})),function(e){let t,n;!function(e){e[e.Unloaded=0]="Unloaded",e[e.Stopped=1]="Stopped",e[e.Pending=2]="Pending",e[e.Starting=3]="Starting",e[e.Running=4]="Running",e[e.Paused=5]="Paused",e[e.Suspended=6]="Suspended"}(t=e.SimulatorState||(e.SimulatorState={})),function(e){e[e.StepInto=0]="StepInto",e[e.StepOver=1]="StepOver",e[e.StepOut=2]="StepOut",e[e.Resume=3]="Resume",e[e.Pause=4]="Pause"}(n=e.SimulatorDebuggerCommand||(e.SimulatorDebuggerCommand={}));const s="messagechannel",i="aspectratio",r="pxtdriver",o="permanent";e.SimulatorDriver=class{constructor(n,s={}){this.container=n,this.options=s,this.themes=["blue","red","green","yellow"],this.runId="",this.nextFrameId=0,this.frameCounter=0,this.singleSimulator=!1,this.traceInterval=0,this.breakpointsSet=!1,this._runOptions={},this.state=t.Unloaded,this._allowedOrigins=[],this.newJacdacSimulator=!1,this.frameCleanupTimeout=void 0,this.debuggerSeq=1,this.debuggerResolvers={},this._allowedOrigins.push(window.location.origin),s.parentOrigin&&this._allowedOrigins.push(s.parentOrigin),this._allowedOrigins.push(this.getSimUrl().origin);const i=(null==s?void 0:s.messageSimulators)||{};Object.keys(i).map(e=>i[e]).forEach(e=>{this._allowedOrigins.push(new URL(e.url).origin),e.localHostUrl&&this._allowedOrigins.push(new URL(e.localHostUrl).origin)});const r=e.U.isLocalHost()&&/[?&]simxdev(?:[=&#]|$)/i.test(window.location.href);Object.entries((null==s?void 0:s.simulatorExtensions)||{}).forEach(([e,t])=>{if(t&&t.index&&t.aspectRatio&&void 0!==t.permanent){if(r&&t.devUrl)t.url=new URL(t.index,t.devUrl).toString();else{const n=this.getSimUrl(),s=["simx",e,"-",t.index].join("/");t.url=new URL(s.replace(/^\/+/,""),n.origin).toString()}this._allowedOrigins.push(new URL(t.url).origin)}}),this._allowedOrigins=e.U.unique(this._allowedOrigins,e=>e)}isDebug(){return this._runOptions&&!!this._runOptions.debug}isTracing(){return this._runOptions&&!!this._runOptions.trace}hasParts(){return this._runOptions&&this._runOptions.parts&&!!this._runOptions.parts.length}setDirty(){this.state==e.SimulatorState.Running&&this.suspend()}setPending(){this.setState(t.Pending)}focus(){const e=this.simFrames()[0];e&&e.focus()}registerDependentEditor(e){e&&(this._dependentEditors||(this._dependentEditors=[]),this._dependentEditors.push(e))}dependentEditors(){return this._dependentEditors&&(this._dependentEditors=this._dependentEditors.filter(e=>!!e.parent),this._dependentEditors.length||(this._dependentEditors=void 0)),this._dependentEditors}setStarting(){this.setState(t.Starting)}setHwDebugger(e){e?(this.hwdbg=e,this.setState(t.Running),this.container.style.opacity="0.3"):(delete this.container.style.opacity,this.hwdbg=null,this.setState(t.Running),this.stop())}handleHwDebuggerMsg(e){this.hwdbg&&this.handleMessage(e)}setThemes(t){e.U.assert(t&&t.length>0),this.themes=t}startRecording(e){this.simFrames()[0]&&this.postMessage({type:"recorder",action:"start",source:r,width:e})}stopRecording(){this.postMessage({type:"recorder",source:r,action:"stop"})}setFrameState(n){const s=n.nextElementSibling,i=s.nextElementSibling;switch(this.state){case t.Pending:case t.Starting:s.style.display="",s.className="",i.style.display="";break;case t.Stopped:case t.Suspended:e.U.addClass(n,this.state==t.Stopped||this._runOptions&&this._runOptions.autoRun?this.stoppedClass:this.invalidatedClass),this._runOptions&&this._runOptions.autoRun?s.style.display="none":(s.style.display="",s.className="videoplay xicon icon"),i.style.display="none",this.scheduleFrameCleanup();break;default:e.U.removeClass(n,this.stoppedClass),e.U.removeClass(n,this.invalidatedClass),s.style.display="none",i.style.display="none"}}setState(e){this.state!=e&&(this.state=e,this.freeze(this.state==t.Paused),this.simFrames().forEach(e=>this.setFrameState(e)),this.options.onStateChanged&&this.options.onStateChanged(this.state))}freeze(t){const n="pause-overlay";t?e.util.toArray(this.container.querySelectorAll("div.simframe")).forEach(e=>{if(e.querySelector(`div.${n}`))return;const t=document.createElement("div");t.className=n,t.onclick=e=>(e.preventDefault(),!1),e.appendChild(t)}):e.util.toArray(this.container.querySelectorAll(`div.simframe div.${n}`)).forEach(e=>e.parentElement.removeChild(e))}simFrames(t=!1){let n=e.util.toArray(this.container.getElementsByTagName("iframe"));const s=this.loanedIFrame();return s&&!t&&n.unshift(s),n}getSimUrl(){var e,t;const n=this.options.simUrl||(null===(e=window.pxtConfig)||void 0===e?void 0:e.simUrl)||(null===(t=pxt.webConfig)||void 0===t?void 0:t.simUrl)||`${location.origin}/sim/simulator.html`;try{return new URL(n)}catch(e){return new URL(n,location.origin)}}setSingleSimulator(){this.singleSimulator=!0}postMessage(t,n,r){var a;if(this.hwdbg)return void this.hwdbg.postMessage(t);const l=this.dependentEditors();let u=this.simFrames();r&&(u=u.filter(e=>e.id===r));let c=!1;const h=t;if(n&&(null==h?void 0:h.broadcast)){h.srcFrameIndex=this.simFrames().findIndex(e=>e.contentWindow===n);const r=!!(null===(a=this._currentRuntime)||void 0===a?void 0:a.single),d=window.parent&&window.parent!==window.window?window.parent:window.opener;if(d&&n!==d&&d.postMessage(t,"*"),!this.options.nestedEditorSim&&!(null==h?void 0:h.toParentIFrameOnly))if(l)l.forEach(e=>{n!==e&&e.postMessage(t,window.location.origin)});else if(!r){const n="messagepacket"===t.type&&t.channel,r=n&&this.options.messageSimulators&&this.options.messageSimulators[n],a=n&&this.options.simulatorExtensions&&this.options.simulatorExtensions[n],l=(t,r,a)=>{var l;a=a||(null===(l=this._runOptions)||void 0===l?void 0:l.aspectRatio)||1.22;let c=this.createFrame(t);this.container.appendChild(c);const h=c.firstElementChild;h.dataset[s]=n,h.dataset[i]=a+"",e.U.addClass(c,"simmsg"),e.U.addClass(c,"simmsg"+e.U.sanitizeCssName(n)),r&&(h.dataset[o]="true"),this.startFrame(h),u=this.simFrames()};if(a){let e=u.find(e=>e.dataset[s]===n);if("jacdac/pxt-jacdac"===n&&(this.newJacdacSimulator=!0),e)e.dataset.runid!=this.runId&&this.startFrame(e);else{const e=new URL(a.url);this.options.parentOrigin&&e.searchParams.set("parentOrigin",encodeURIComponent(this.options.parentOrigin)),this.options.userLanguage&&e.searchParams.set("language",encodeURIComponent(this.options.userLanguage)),l(e.toString(),a.permanent,a.aspectRatio)}}else if(r){let t=u.find(e=>e.dataset[s]===n);if(t)t.dataset.runid!=this.runId&&this.startFrame(t);else if("jacdac"!==n||!this.newJacdacSimulator){l((e.U.isLocalHost()&&/localhostmessagesims=1/i.test(window.location.href)&&r.localHostUrl||r.url).replace("$PARENT_ORIGIN$",encodeURIComponent(this.options.parentOrigin||"")).replace("$LANGUAGE$",encodeURIComponent(this.options.userLanguage)),r.permanent,r.aspectRatio)}}else{c=!0;const e=u.filter(e=>!e.dataset[s]);n||0!=e.length&&(1!=e.length||this.singleSimulator)?2==e.length&&e[1].dataset.runid!=this.runId&&this.startFrame(e[1]):(this.container.appendChild(this.createFrame()),u=this.simFrames())}}}for(let e=0;e<u.length;++e){const s=u[e];if((!n||s.contentWindow!=n)&&(s.contentWindow&&(c?this.postDeferrableMessage(s,t):this.postMessageCore(s,t),"recorder"==t.type&&"start"==t.action)))break}}postDeferrableMessage(e,t){!e.dataset.loading?this.postMessageCore(e,t):(this.deferredMessages||(this.deferredMessages=[]),this.deferredMessages.push([e,t]))}postMessageCore(t,n){const s=e.U.isLocalHostDev()?"*":t.dataset.origin;t.contentWindow.postMessage(n,s)}setRunOptionQueryParams(e){var t,n;const s=new URL(e);if((null===(t=this._runOptions)||void 0===t?void 0:t.hideSimButtons)&&s.searchParams.set("hideSimButtons","1"),null===(n=this._runOptions)||void 0===n?void 0:n.queryParameters){const e=this._runOptions.queryParameters.split("&");for(const t of e){const[e,n]=t.split(/[:=]/);e&&n&&s.searchParams.set(e,n)}}return s.toString()}createFrame(n){var s;const i=document.createElement("div");i.className="simframe ui embed",i.setAttribute("tabindex","0");const r=document.createElement("iframe");r.id="sim-frame-"+this.nextId(),r.title=e.localization.lf("Simulator"),r.allowFullscreen=!0,r.setAttribute("allow","autoplay;microphone"),r.setAttribute("sandbox","allow-same-origin allow-scripts"),r.className="no-select";let o=this.setRunOptionQueryParams(n||this.getSimUrl().toString());o+="#"+r.id,r.src=o,r.frameBorder="0",r.dataset.runid=this.runId,r.dataset.origin=new URL(o).origin||"*",r.dataset.loading="true",(null===(s=this._runOptions)||void 0===s?void 0:s.autofocus)&&r.setAttribute("autofocus","true"),i.appendChild(r);const a=document.createElement("i");a.className="videoplay xicon icon",a.style.display="none",a.onclick=e=>(e.preventDefault(),this.state!=t.Running&&this.state!=t.Starting&&(this.options.restart?this.options.restart():this.start()),r.focus(),!1),i.appendChild(a);const l=document.createElement("div");return l.className="ui active loader",a.style.display="none",i.appendChild(l),this._runOptions&&this.applyAspectRatioToFrame(r),i}preload(e,t){this.addEventListeners(),t&&(this._currentRuntime=void 0,this.container.textContent=""),this.simFrames().length||(this.container.appendChild(this.createFrame()),this.applyAspectRatio(e),this.setStarting())}stop(e=!1,n=!1){this.state!==t.Stopped&&this.state!==t.Unloaded&&(this.clearDebugger(),this.stopSound(),this.postMessage({type:"stop",source:r}),this.setState(n?t.Starting:t.Stopped)),e&&this.unload()}suspend(){this.stopSound(),this.postMessage({type:"stop",source:r}),this.setState(t.Suspended)}unload(){this.cancelFrameCleanup(),e.U.removeChildren(this.container),this.setState(t.Unloaded),this._runOptions=void 0,this._currentRuntime=void 0,this.runId=void 0,this.deferredMessages=void 0}mute(e){this._currentRuntime&&(this._currentRuntime.mute=e),this.postMessage({type:"mute",source:r,mute:e})}stopSound(){this.postMessage({type:"stopsound",source:r})}isLoanedSimulator(e){return!!this.loanedSimulator&&this.loanedIFrame()==e}loanSimulator(){return this.loanedSimulator||(this.loanedSimulator=this.container.firstElementChild||this.createFrame(),this.loanedSimulator.parentNode&&this.container.removeChild(this.loanedSimulator)),this.loanedSimulator}unloanSimulator(){this.loanedSimulator&&(this.loanedSimulator.parentNode&&this.loanedSimulator.parentNode.removeChild(this.loanedSimulator),this.container.insertBefore(this.loanedSimulator,this.container.firstElementChild),delete this.loanedSimulator)}loanedIFrame(){return this.loanedSimulator&&this.loanedSimulator.parentNode&&this.loanedSimulator.querySelector("iframe")}cancelFrameCleanup(){this.frameCleanupTimeout&&(clearTimeout(this.frameCleanupTimeout),this.frameCleanupTimeout=void 0)}scheduleFrameCleanup(){this.cancelFrameCleanup(),this.frameCleanupTimeout=setTimeout(()=>{this.frameCleanupTimeout=void 0,this.cleanupFrames()},5e3)}applyAspectRatio(e){if(!e&&!this._runOptions)return;this.simFrames().forEach(t=>this.applyAspectRatioToFrame(t,e))}applyAspectRatioToFrame(e,t){var n,r,o,a;let l=t;if(void 0===l){const t=parseFloat(e.dataset[i]);isNaN(t)||(l=t)}if(void 0===l){const t=e.dataset[s];if(t){const e=null===(o=null===(r=null===(n=this.options)||void 0===n?void 0:n.messageSimulators)||void 0===r?void 0:r[t])||void 0===o?void 0:o.aspectRatio;e&&(l=e)}}void 0===l&&(l=(null===(a=this._runOptions)||void 0===a?void 0:a.aspectRatio)||1.22),e.parentElement.style.paddingBottom=100/l+"%"}cleanupFrames(){const e=this.simFrames(!0);e.shift(),e.filter(e=>!e.dataset[o]).forEach(e=>{this.state!=t.Stopped&&e.dataset.runid==this.runId||(this.options.removeElement?this.options.removeElement(e.parentElement):e.parentElement.remove())})}hide(e){if(this.suspend(),!this.options.removeElement)return;const t=this.simFrames();t.forEach(t=>{this.options.removeElement(t.parentElement,e)}),0==t.length&&e&&e()}unhide(){if(!this.options.unhideElement)return;this.simFrames().forEach(e=>{this.options.unhideElement(e.parentElement)})}setRunOptions(e={}){this._runOptions=e}run(e,t={}){this.setRunOptions(t),this.runId=this.nextId(),this._currentRuntime={type:"run",source:r,boardDefinition:t.boardDefinition,parts:t.parts,builtinParts:t.builtinParts,fnArgs:t.fnArgs,code:e,partDefinitions:t.partDefinitions,mute:t.mute,highContrast:t.highContrast,light:t.light,cdnUrl:t.cdnUrl,localizedStrings:t.localizedStrings,refCountingDebug:t.refCountingDebug,version:t.version,clickTrigger:t.clickTrigger,breakOnStart:t.breakOnStart,storedState:t.storedState,ipc:t.ipc,single:t.single,dependencies:t.dependencies,activePlayer:t.activePlayer,theme:t.theme},this.stopSound(),this.start()}restart(){this.stop(),this.cleanupFrames(),this.start()}areBreakpointsSet(){return this.breakpointsSet}start(){if(this.clearDebugger(),this.addEventListeners(),this.applyAspectRatio(),this.scheduleFrameCleanup(),!this._currentRuntime)return;this.singleSimulator=!1,this.breakpointsSet=!1;let e=this.simFrames()[0];if(!e){let t=this.createFrame();this.container.appendChild(t),e=t.firstElementChild}this.startFrame(e),this.debuggingFrame=e.id,this.setState(t.Running),this.setTraceInterval(this.traceInterval)}startFrame(e){var t,n,s;if(!this._currentRuntime||!e.contentWindow)return!1;const i=JSON.parse(JSON.stringify(this._currentRuntime));i.frameCounter=++this.frameCounter;const r=(null===(t=this._runOptions)||void 0===t?void 0:t.mpRole)||(null===(s=null===(n=/[\&\?]mp=(server|client)/i.exec(window.location.href))||void 0===n?void 0:n[1])||void 0===s?void 0:s.toLowerCase());return i.options={theme:this.themes[this.nextFrameId++%this.themes.length],mpRole:r},i.id=`${i.options.theme}-${this.nextId()}`,e.dataset.runid=this.runId,e.dataset.runtimeid=i.id,e.id!==this.debuggingFrame&&(i.traceDisabled=!0,i.breakOnStart=!1),this.postMessageCore(e,i),this.traceInterval&&this.setTraceInterval(this.traceInterval),this.applyAspectRatioToFrame(e),this.setFrameState(e),!0}handleDeferredMessages(e){var t,n,s;e.dataset.loading&&(delete e.dataset.loading,null===(n=null===(t=this.deferredMessages)||void 0===t?void 0:t.filter(t=>t[0]===e))||void 0===n||n.forEach(t=>{const[n,s]=t;this.postMessageCore(e,s)}),this.deferredMessages=null===(s=this.deferredMessages)||void 0===s?void 0:s.filter(t=>t[0]!==e))}handleMessage(e,n){var s,r,o;switch(e.type||""){case"ready":{const t=e.frameid,n=document.getElementById(t);n&&((null===(s=this._runOptions)||void 0===s?void 0:s.autofocus)&&n.focus(),this.startFrame(n),this.options.revealElement&&this.options.revealElement(n),this.handleDeferredMessages(n)),this.options.onSimulatorReady&&this.options.onSimulatorReady();break}case"status":{const n=e.frameid,s=document.getElementById(n);if(s){const n=e;if(n.runtimeid==s.dataset.runtimeid)switch(n.state){case"running":this.setState(t.Running),this.handleDeferredMessages(s);break;case"killed":this.setState(t.Stopped)}}break}case"simulator":this.handleSimulatorCommand(e);break;case"serial":case"pxteditor":case"screenshot":case"custom":case"recorder":case"addextensions":break;case"aspectratio":{const t=e,n=t.frameid,s=document.getElementById(n);s&&(s.dataset[i]=t.value+"",this.applyAspectRatioToFrame(s));break}case"debugger":this.handleDebuggerMessage(e);break;case"toplevelcodefinished":this.options.onTopLevelCodeEnd&&this.options.onTopLevelCodeEnd();break;case"setmutebuttonstate":null===(o=(r=this.options).onMuteButtonStateChange)||void 0===o||o.call(r,e.state);break;default:this.postMessage(e,n)}}addEventListeners(){this.listener||(this.listener=t=>{if(!this.hwdbg){if(e.U.isLocalHost());else if(this._allowedOrigins.indexOf(t.origin)<0)return;this.handleMessage(t.data,t.source)}},window.addEventListener("message",this.listener,!1))}removeEventListeners(){this.listener&&(window.removeEventListener("message",this.listener,!1),this.listener=void 0)}resume(s){let i;switch(s){case n.Resume:i="resume",this.setState(t.Running);break;case n.StepInto:i="stepinto",this.setState(t.Running);break;case n.StepOut:i="stepout",this.setState(t.Running);break;case n.StepOver:i="stepover",this.setState(t.Running);break;case n.Pause:i="pause";break;default:return void e.debug("unknown command")}this.postMessage({type:"debugger",subtype:i,source:r})}setBreakpoints(e){this.breakpointsSet=!0,this.postDebuggerMessage("config",{setBreakpoints:e},void 0,this.debuggingFrame)}setTraceInterval(e){this.traceInterval=e,this.postDebuggerMessage("traceConfig",{interval:e})}variablesAsync(e,t,n=!1){return this.postDebuggerMessageAsync("variables",{variablesReference:e,fields:t,includeAll:n},this.debuggingFrame).then(e=>e,e=>{})}handleSimulatorCommand(e){this.options.onSimulatorCommand&&this.options.onSimulatorCommand(e)}clearDebugger(){const e=new Error("Debugging cancelled");Object.keys(this.debuggerResolvers).forEach(t=>{const{reject:n}=this.debuggerResolvers[t];n(e)}),this.debuggerResolvers={},this.debuggerSeq++}handleDebuggerMessage(s){if("trace"!==s.subtype&&e.log("DBG-MSG",s.subtype,s),s.seq){const{resolve:e}=this.debuggerResolvers[s.seq];e&&e(s)}switch(s.subtype){case"warning":this.options.onDebuggerWarning&&this.options.onDebuggerWarning(s);break;case"breakpoint":{const i=s;if(this.state==t.Running){if(i.exceptionMessage)this.suspend();else{this.setState(t.Paused);this.simFrames(!0).length>1&&this.resume(n.Pause)}this.options.onDebuggerBreakpoint&&this.options.onDebuggerBreakpoint(i);let s=i.exceptionMessage+"\n";for(let e of i.stackframes){let t=e.funcInfo;s+=` at ${t.functionName} (${t.fileName}:${t.line+1}:${t.column+1})\n`}i.exceptionMessage&&e.error(s)}else e.error("debugger: trying to pause from "+this.state);break}case"trace":{const e=s;this.state==t.Running&&this.options.onTraceMessage&&this.options.onTraceMessage(e);break}default:const i=s.req_seq;if(i){const{resolve:e}=this.debuggerResolvers[i];e&&(delete this.debuggerResolvers[i],e(s))}}}postDebuggerMessageAsync(e,t={},n){return new Promise((s,i)=>{const r=this.debuggerSeq++;this.debuggerResolvers[r.toString()]={resolve:s,reject:i},this.postDebuggerMessage(e,t,r,n)})}postDebuggerMessage(e,t={},n,s){const i=JSON.parse(JSON.stringify(t));i.type="debugger",i.subtype=e,i.source=r,n&&(i.seq=n),this.postMessage(i,void 0,s)}nextId(){return this.nextFrameId+++(Math.random()+""+Math.random()).replace(/[^\d]/,"")}get stoppedClass(){return this.options&&this.options.stoppedClass||"grayscale"}get invalidatedClass(){return this.options&&this.options.invalidatedClass||"sepia"}}}(pxsim||(pxsim={})),function(e){e.mkRange=function(e,t){let n=[];for(;e<t;e++)n.push(e);return n};e.EventBus=class{constructor(e,t,n){this.runtime=e,this.board=t,this.valueToArgs=n,this.queues={},this.backgroundHandlerFlag=!1,this.nextNotifyEvent=1024,this.schedulerID=15,this.idleEventID=2,this.board.addMessageListener(this.handleMessage.bind(this))}handleMessage(e){if("eventbus"===e.type){const t=e;this.queue(t.id,t.eventid,t.value)}}setBackgroundHandlerFlag(){this.backgroundHandlerFlag=!0}setNotify(e,t){this.notifyID=e,this.notifyOneID=t}setIdle(e,t){this.schedulerID=e,this.idleEventID=t}start(t,n,s,i=!1){let r=(s?"back":"fore")+":"+t+":"+n;return!this.queues[r]&&i&&(this.queues[r]=new e.EventQueue(this.runtime,this.valueToArgs)),this.queues[r]}listen(e,t,n,s=0){e==this.schedulerID&&t==this.idleEventID&&this.runtime.startIdle();let i=this.start(e,t,this.backgroundHandlerFlag,!0);this.backgroundHandlerFlag?i.addHandler(n,s):i.setHandler(n,s),this.backgroundHandlerFlag=!1}removeBackgroundHandler(e){Object.keys(this.queues).forEach(t=>{t.startsWith("back:")&&this.queues[t].removeHandler(e)})}getQueues(e,t,n){let s=[this.start(0,0,n)];return 0==e&&0==t||(t&&s.push(this.start(0,t,n)),e&&s.push(this.start(e,0,n)),e&&t&&s.push(this.start(e,t,n))),s}queue(t,n,s=null){if(e.runtime.pausedOnBreakpoint)return;const i=this.notifyID&&this.notifyOneID&&t==this.notifyOneID;i&&(t=this.notifyID);let r=this.getQueues(t,n,!0).concat(this.getQueues(t,n,!1));this.lastEventValue=n,this.lastEventTimestampUs=e.U.perfNowUs(),e.U.promiseMapAllSeries(r,e=>e?e.push(s,i):Promise.resolve())}queueIdle(){this.schedulerID&&this.idleEventID&&this.queue(this.schedulerID,this.idleEventID)}wait(e,t,n){this.start(e,t,!1,!0).addAwaiter(n)}getLastEventValue(){return this.lastEventValue}getLastEventTime(){return 4294967295&this.lastEventTimestampUs-e.runtime.startTimeUs}};function t(){return"undefined"!=typeof window&&("ontouchstart"in window||navigator&&navigator.maxTouchPoints>0)}function n(){return"undefined"!=typeof window&&!!window.PointerEvent}e.AnimationQueue=class{constructor(e){this.runtime=e,this.queue=[],this.process=()=>{let t=this.queue[0];if(!t)return;if(this.runtime.dead)return;e=this.runtime;let n=t.frame();e.queueDisplayUpdate(),e.maybeUpdateDisplay(),!1===n?(this.queue.shift(),this.queue[0]&&(this.queue[0].setTimeoutHandle=setTimeout(this.process,this.queue[0].interval)),t.whenDone(!1)):t.setTimeoutHandle=setTimeout(this.process,t.interval)}}cancelAll(){let e=this.queue;this.queue=[];for(let t of e)t.whenDone(!0),t.setTimeoutHandle&&clearTimeout(t.setTimeoutHandle)}cancelCurrent(){let e=this.queue[0];e&&(this.queue.shift(),e.whenDone(!0),e.setTimeoutHandle&&clearTimeout(e.setTimeoutHandle))}enqueue(e){e.whenDone||(e.whenDone=()=>{}),this.queue.push(e),1==this.queue.length&&this.process()}executeAsync(t){return e.U.assert(!t.whenDone),new Promise((e,n)=>{t.whenDone=e,this.enqueue(t)})}},e.isTouchEnabled=t,e.hasPointerEvents=n,e.pointerEvents=n()?{up:"pointerup",down:["pointerdown"],move:"pointermove",enter:"pointerenter",leave:"pointerleave"}:t()?{up:"mouseup",down:["mousedown","touchstart"],move:"touchmove",enter:"touchenter",leave:"touchend"}:{up:"mouseup",down:["mousedown"],move:"mousemove",enter:"mouseenter",leave:"mouseleave"}}(pxsim||(pxsim={})),function(e){!function(t){function n(e,t){return n=>n*(t/e)}function s(e,t){let n=e[0]-t[0],s=e[1]-t[1];return n*n+s*s}t.translateEl=function(t,n){e.svg.hydrate(t,{transform:`translate(${n[0]} ${n[1]})`})},t.composeSVG=function(t){let[n,s]=[t.el1,t.el2];e.U.assert(0==n.x&&0==n.y&&0==s.x&&0==s.y,"el1 and el2 x,y offsets not supported");let i=(t,n,s)=>e.svg.hydrate(t,{x:n,y:s}),r=(t,n,s)=>e.svg.hydrate(t,{width:`${n}px`,height:`${s}px`}),o=t.scaleUnit2,a=t.scaleUnit2/t.scaleUnit1,l=n.w*a,u=n.h*a;r(n.el,l,u);let c=1*s.w,h=1*s.h;r(s.el,c,h);let[d,p,f,m]=t.margin,g=t.middleMargin,b=Math.max(l,c),v=p+(b-l)/2,y=d;i(n.el,v,y);let S=p+(b-c)/2,w=y+u+g;i(s.el,S,w);let x=[y,y+u,w,w+h],E=p+b+m,I=d+u+g+h+f,k=e.svg.elt("svg",{version:"1.0",viewBox:`0 0 ${E} ${I}`,class:"sim-bb"});((t,n,s)=>{n&&e.svg.hydrate(t,{width:n}),s&&e.svg.hydrate(t,{height:s})})(k,t.maxWidth,t.maxHeight),i(k,0,0);let C=e.svg.child(k,"g");return k.appendChild(n.el),k.appendChild(s.el),{under:C,over:e.svg.child(k,"g"),host:k,edges:x,scaleUnit:o,toHostCoord1:e=>{let[t,n]=e;return[t*a+v,n*a+y]},toHostCoord2:e=>{let[t,n]=e;return[1*t+S,1*n+w]}}},t.mkScaleFn=n,t.mkImageSVG=function(t){let s=n(t.imageUnitDist,t.targetUnitDist),i=s(t.width),r=s(t.height),o=e.svg.elt("image",{width:i,height:r});return o.setAttributeNS("http://www.w3.org/1999/xlink","href",`${t.image}`),{el:o,w:i,h:r,x:0,y:0}},t.findDistSqrd=s,t.findClosestCoordIdx=function(e,t){return t.map(t=>s(e,t)).reduce((e,t,n,s)=>t<s[e]?n:e,0)},t.mkTxt=function(t,n,s,i,r,o,a){let l=e.svg.elt("text");a=a||.3;const u=(o=o||-.33333)*s*r.length,c=a*s;return e.svg.hydrate(l,{style:`font-size:${s}px;`,transform:`translate(${t} ${n}) rotate(${i}) translate(${u} ${c})`}),e.U.addClass(l,"noselect"),l.textContent=r,l},t.GPIO_WIRE_COLORS=["pink","orange","yellow","green","purple"],t.WIRE_COLOR_MAP={black:"#514f4d",white:"#fcfdfc",gray:"#acabab",purple:"#a772a1",blue:"#01a6e8",green:"#3cce73",yellow:"#ece600",orange:"#fdb262",red:"#f44f43",brown:"#c89764",pink:"#ff80fa"},t.mapWireColor=function(e){return t.WIRE_COLOR_MAP[e]||e},t.PIN_DIST=15,t.rgbToHsl=function(e){let t,n,s,[i,r,o]=e,[a,l,u]=[i/255,r/255,o/255],c=Math.min(a,l,u),h=Math.max(a,l,u),d=h-c,p=h+c;return s=p/2*100,0===d?n=t=0:(h===a?t=(l-u)/d%6*60:h===l?t=60*((u-a)/d+2):h===u&&(t=60*((a-l)/d+4)),n=s>50?d/(2-p)*100:d/p*100),[Math.floor(t),Math.floor(n),Math.floor(s)]}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){var t;!function(n){function s(e,n,s){let i={class:e,d:n};s&&(i.title=s);let r=t.elt("path");return t.hydrate(r,i),r}function i(e,n=!1){let s=t.elt("linearGradient");t.hydrate(s,{id:e,x1:"0%",y1:"0%",x2:n?"100%":"0%",y2:n?"0%":"100%"});t.child(s,"stop",{offset:"0%"}),t.child(s,"stop",{offset:"100%"}),t.child(s,"stop",{offset:"100%"}),t.child(s,"stop",{offset:"100%"});return s}function r(e){let n=t.elt("title");return n.textContent=e,n}n.parseString=function(e){return(new DOMParser).parseFromString(e,"image/svg+xml").getElementsByTagName("svg").item(0)},n.toDataUri=function(e){return"data:image/svg+xml,"+encodeURI(e)},n.cursorPoint=function(e,t,n){return e.x=null!=n.clientX?n.clientX:n.pageX,e.y=null!=n.clientY?n.clientY:n.pageY,e.matrixTransform(t.getScreenCTM().inverse())},n.rotateElement=function(e,t,n,s){e.setAttribute("transform",`translate(${t},${n}) rotate(${s+90}) translate(${-t},${-n})`)},n.hydrate=function(e,n){for(let s in n)"title"==s?t.title(e,n[s]):e.setAttributeNS(null,s,n[s])},n.elt=function(e,n){let s=document.createElementNS("http://www.w3.org/2000/svg",e);return n&&t.hydrate(s,n),s},n.child=function(e,n,s){let i=t.elt(n,s);return e.appendChild(i),i},n.mkPath=s,n.path=function(e,t,n,i){let r=s(t,n,i);return e.appendChild(r),r},n.fill=function(e,t){e.style.fill=t},n.filter=function(e,t){e.style.filter=t},n.fills=function(e,t){e.forEach(e=>e.style.fill=t)},n.isTouchEnabled=function(){return"undefined"!=typeof window&&("ontouchstart"in window||navigator.maxTouchPoints>0)},n.onClick=function(t,n){let s=!1;e.pointerEvents.down.forEach(e=>t.addEventListener(e,e=>(s=!0,!0),!1)),t.addEventListener(e.pointerEvents.up,e=>!s||(s=!1,n(e),e.preventDefault(),!1),!1)},n.buttonEvents=function(t,n,s,i,r){let o=!1;e.pointerEvents.down.forEach(e=>t.addEventListener(e,e=>(o=!0,s&&s(e),!0),!1)),t.addEventListener(e.pointerEvents.move,e=>!o||(n&&n(e),e.preventDefault(),!1),!1),t.addEventListener(e.pointerEvents.up,e=>{o=!1,i&&i(e)},!1),t.addEventListener(e.pointerEvents.leave,e=>{o=!1,i&&i(e)},!1),t.addEventListener("keydown",e=>{o=!1,r&&r(e)})},n.mkLinearGradient=i,n.linearGradient=function(e,t,n=!1){let s=i(t,n);return e.appendChild(s),s},n.setGradientColors=function(e,t,n){e&&(e.childNodes[0].style.stopColor=t,e.childNodes[1].style.stopColor=t,e.childNodes[2].style.stopColor=n,e.childNodes[3].style.stopColor=n)},n.setGradientValue=function(e,t){e.childNodes[1].getAttribute("offset")!=t&&(e.childNodes[1].setAttribute("offset",t),e.childNodes[2].setAttribute("offset",t))},n.animate=function(t,n){e.U.addClass(t,n);let s=t.parentElement;s&&(s.removeChild(t),s.appendChild(t))},n.mkTitle=r,n.title=function(e,t){let n=r(t);return e.appendChild(n),n},n.toHtmlColor=function(e){return`rgba(${e>>16&255}, ${e>>8&255}, ${255&e}, ${e>>24&1})`}}(t=e.svg||(e.svg={}))}(pxsim||(pxsim={})),function(e){!function(e){class t{constructor(e,n){this.vca=e.createGain(),this.vca.gain.value=1,this.vca.connect(n),t.activeSources.push(this)}static stopAll(){for(const e of t.activeSources)e.dispose();t.activeSources=[]}dispose(){if(this.isDisposed())return;this.vca.disconnect(),this.vca=void 0;const e=t.activeSources.indexOf(this);-1!==e&&t.activeSources.splice(e,1)}isDisposed(){return!this.vca}}t.activeSources=[],e.AudioSource=t}(e.AudioContextManager||(e.AudioContextManager={}))}(pxsim||(pxsim={})),function(e){!function(e){class t extends e.AudioSource{constructor(e,t){super(e,t),this.bufferSource=e.createBufferSource(),this.bufferSource.connect(this.vca)}async playBufferAsync(e,t,n){return new Promise((s,i)=>{this.vca.gain.value=n,this.bufferSource.onended=()=>s(),this.bufferSource.buffer=e,this.bufferSource.playbackRate.value=t,this.bufferSource.start()})}dispose(){super.dispose(),this.bufferSource.disconnect(),this.bufferSource.stop(),this.bufferSource=void 0}}e.AudioBufferSource=t}(e.AudioContextManager||(e.AudioContextManager={}))}(pxsim||(pxsim={})),function(e){!function(e){class t extends e.AudioSource{constructor(e,t){super(e,t),this.context=e}playStreamAsync(e,t,n=.3,s){return new Promise(i=>{let r=[],o=this.context.currentTime,a=!1;this.vca.gain.setValueAtTime(n,o);const l=()=>!(this.vca&&!(null==s?void 0:s()))&&(i&&i(),i=void 0,!0),u=()=>{for(;!a&&r.length<3&&!l();){const t=e();if(!t||!t.length){a=!0;break}c(t)}a&&0===r.length&&(i&&i(),i=void 0)},c=e=>{if(l())return;const n=this.context.createBuffer(1,e.length,t);if(n.copyToChannel)n.copyToChannel(e,0);else{const t=n.getChannelData(0);for(let n=0;n<e.length;n++)t[n]=e[n]}const s=this.context.createBufferSource();r.push(s),s.connect(this.vca),s.buffer=n,s.addEventListener("ended",()=>{r.shift().disconnect(),u()}),s.start(o),o+=n.duration};u()})}}e.AudioBufferStreamSource=t}(e.AudioContextManager||(e.AudioContextManager={}))}(pxsim||(pxsim={})),function(e){!function(t){let n,s,i,r=!1,o=[];function a(){return n||(n=function(){if(window.AudioContext=window.AudioContext||window.webkitAudioContext,window.AudioContext)try{return new window.AudioContext}catch(e){}return}(),n&&(i=n.createGain(),i.connect(n.destination),i.gain.setValueAtTime(1,0))),n}function l(){t.AudioToneSource.dispose(),s&&s.pause()}t.isAudioElementActive=function(){return t.AudioToneSource.isActive()},t.mute=function(e){r=e;const t=a();e?i.gain.setTargetAtTime(0,t.currentTime,.015):i.gain.setTargetAtTime(1,t.currentTime,.015),!e&&t&&"suspended"===t.state&&t.resume()},t.isMuted=function(){return r},t.stopAll=function(){c()},t.stop=function(){l()},t.onStopAll=function(e){o.push(e)},t.frequency=function(){return t.AudioToneSource.getFrequency()};let u=1;function c(){null===t.soundEventCallback||void 0===t.soundEventCallback||t.soundEventCallback("muteallchannels"),u++,l(),t.AudioSource.stopAll();for(const e of o)e()}function h(e,n){if(e<0)return;let s;try{s=t.AudioToneSource.getInstance(a(),i),s.setFrequency(e),s.setGain(n,a().currentTime),s.start()}catch(e){s&&s.dispose()}}async function d(e,n,s){null===t.soundEventCallback||void 0===t.soundEventCallback||t.soundEventCallback("playinstructions",e);const r=new t.PlayInstructionsSource(a(),i);let o=!1;s&&function(e,t,n){const s=t.frequencyBinCount,i=new Float32Array(s),r=new Uint8Array(s),o=()=>{n()||(t.getFloatTimeDomainData(i),t.getByteFrequencyData(r),e({data:i,fft:r}),requestAnimationFrame(o))};requestAnimationFrame(o)}(s,r.analyser,()=>o||(null==n?void 0:n())||r.isDisposed()),await r.playInstructionsAsync(e,n),r.dispose(),o=!0}t.muteAllChannels=c,t.queuePlayInstructions=function(t,n){const s=u;e.U.delay(t).then(()=>s!=u?Promise.resolve():d(n.data))},t.tone=h,t.setCurrentToneGain=function(e){t.AudioToneSource.setCurrentToneGain(e,a().currentTime)},t.playBufferAsync=function(e){return e?new Promise(t=>{function n(){t&&t(),t=void 0}const i="data:audio/wav;base64,"+window.btoa(function(e){let t=e.length,n="";for(let s=0;s<t;++s)n+=String.fromCharCode(e[s]);return n}(e.data));s=new Audio(i),r&&(s.volume=0),s.onended=()=>n(),s.onpause=()=>n(),s.onerror=()=>n(),s.play()}):Promise.resolve()},t.playPCMBufferStreamAsync=async function(e,n,s=.3,r){const o=new t.AudioBufferStreamSource(a(),i);await o.playStreamAsync(e,n,s,r),o.isDisposed()||o.dispose()},t.playInstructionsAsync=d,t.sendMidiMessage=function(e){const t=e.data;if(!t.length)return;const n=t[0]>>4,s=15&t[0],i=t[1]||0,r=(o=i,440*Math.pow(2,(o-69)/12));var o;const a=t[2]||0;8==n||9==n&&0==a?l():9==n&&(h(r,1),9==s&&setTimeout(()=>l(),500))},t.startSamplePlayback=function(n,s,r,o,l){let u=1;o<3e3?(u=o/3e3,o=3e3):o>768e3&&(u=o/768e3,o=768e3);const c=e.BufferMethods.fmtInfo(s).size,h=a().createBuffer(1,n.data.length/c,o),d=h.getChannelData(0);for(let t=0;t<h.length;t++)d[t]=e.BufferMethods.getNumber(n,s,t*c)/r*2-1;const p=new t.AudioBufferSource(a(),i);return{cancel:()=>p.dispose(),promise:p.playBufferAsync(h,u,l)}},t.createAudioSourceNode=function(e,n,s){return new t.AudioElementSource(a(),i,e,n,s).getAudioElement()},t.createSpatialAudioPlayer=function(){return new t.SpatialAudioPlayer(a(),i).id},t.setSpatialAudioPlayerPosition=function(e,n,s,i){const r=t.SpatialAudioPlayer.getPlayerById(e);r&&r.setPosition(n,s,i)},t.setSpatialAudioPlayerOrientation=function(e,n,s,i){const r=t.SpatialAudioPlayer.getPlayerById(e);r&&r.setOrientation(n,s,i)},t.setSpatialAudioPlayerCone=function(e,n,s,i){const r=t.SpatialAudioPlayer.getPlayerById(e);r&&r.setCone(n,s,i)},t.setSpatialAudioRollOff=function(e,n,s,i){const r=t.SpatialAudioPlayer.getPlayerById(e);r&&r.setRollOff(n,s,i)},t.setSpatialAudioDistanceModel=function(e,n){const s=t.SpatialAudioPlayer.getPlayerById(e);s&&s.setDistanceModel(n)},t.disposeSpatialAudioPlayer=function(e){const n=t.SpatialAudioPlayer.getPlayerById(e);n&&n.dispose()},t.queuePlayInstructionsAtSpatialAudioPlayer=function(n,s,i){const r=t.SpatialAudioPlayer.getPlayerById(n);if(r){const t=u;e.U.delay(s).then(()=>t!=u?Promise.resolve():r.playInstructionsAsync(i.data))}},t.setListenerPosition=function(e,t,n){const s=a();s&&(s.listener.positionX.setTargetAtTime(e,0,.02),s.listener.positionY.setTargetAtTime(t,0,.02),s.listener.positionZ.setTargetAtTime(n,0,.02))}}(e.AudioContextManager||(e.AudioContextManager={}))}(pxsim||(pxsim={})),function(e){!function(e){class t extends e.AudioSource{constructor(e,t,n,s,i){super(e,t),this.audioElement=new Audio(n),this.source=e.createMediaElementSource(this.audioElement),this.distortion=e.createWaveShaper(),this.distortion.curve=function(e){const t=44100,n=new Float32Array(t);e=Math.max(.01,Math.min(1,e));const s=1/e;for(let e=0;e<t;e++){const i=(2*e/t-1)*s;n[e]=Math.max(-1,Math.min(1,i))}return n}(s),this.distortion.oversample="4x",this.source.connect(this.distortion),this.distortion.connect(this.vca),this.vca.gain.value=.1*i}getAudioElement(){return this.audioElement}dispose(){super.dispose(),this.source.disconnect(),this.distortion.disconnect(),this.audioElement.pause(),this.audioElement=void 0,this.source=void 0,this.distortion=void 0}}e.AudioElementSource=t}(e.AudioContextManager||(e.AudioContextManager={}))}(pxsim||(pxsim={})),function(e){!function(e){class t extends e.AudioSource{constructor(e,t){super(e,t),this.started=!1,this.oscillator=e.createOscillator(),this.oscillator.type="triangle",this.oscillator.frequency.value=0,this.oscillator.connect(this.vca),this.frequency=0}static getInstance(e,n){return t.instance||(t.instance=new t(e,n)),t.instance}static setCurrentToneGain(e,n){t.instance&&t.instance.setGain(e,n)}static isActive(){return!!t.instance}static getFrequency(){var e;return(null===(e=t.instance)||void 0===e?void 0:e.frequency)||0}static dispose(){t.instance&&t.instance.dispose()}setFrequency(e){this.frequency=e,this.oscillator.frequency.value=e}setGain(e,t){this.vca.gain.setTargetAtTime(e,t,.015)}start(){this.started||(this.oscillator.start(),this.started=!0)}dispose(){super.dispose(),this.oscillator.stop(),this.oscillator.disconnect(),this.oscillator=void 0,t.instance=void 0}}e.AudioToneSource=t}(e.AudioContextManager||(e.AudioContextManager={}))}(pxsim||(pxsim={})),function(e){!function(t){let n=0;class s extends t.AudioSource{constructor(e,t,n=!1){super(e,t),this.isPrivate=n,s.allWorkletSources.push(this),this.analyser=e.createAnalyser(),this.analyser.fftSize=2048,this.node=new AudioWorkletNode(e,"pxt-mixer-audio-worklet-processor"),this.node.connect(this.analyser),this.analyser.connect(this.vca),this.node.port.onmessage=e=>{if("done"===e.data.type){const t=this.activeSounds.find(t=>t.id===e.data.id);t&&(t.resolve(),this.activeSounds=this.activeSounds.filter(e=>e!==t))}},this.activeSounds=[]}static initializeWorklet(t){return s.workletInit||(s.workletInit=t.audioWorklet.addModule(e.getWorkletUri())),s.workletInit}static getAvailableSource(){for(const e of s.allWorkletSources)if(e.activeSounds.length<30&&!e.isPrivate)return e}playInstructionsAsync(e,t){return new Promise(s=>{const i={type:"play",instructions:e,id:n++},r={id:i.id,resolve:s,isCancelled:t};this.activeSounds.push(r),this.node.port.postMessage(i),t&&this.updateActiveSounds()})}dispose(){if(!this.isDisposed()){super.dispose(),s.allWorkletSources=s.allWorkletSources.filter(e=>e!==this),this.node.disconnect(),this.node.port.close(),this.node=void 0,this.analyser.disconnect(),this.analyser=void 0;for(const e of this.activeSounds)e.resolve()}}updateActiveSounds(){var e;if(!this.isDisposed()){this.animRef&&(cancelAnimationFrame(this.animRef),this.animRef=void 0);for(const t of this.activeSounds)(null===(e=t.isCancelled)||void 0===e?void 0:e.call(t))&&(t.resolve(),this.activeSounds=this.activeSounds.filter(e=>e!==t),this.node.port.postMessage({type:"cancel",id:t.id}));this.activeSounds.length&&(this.animRef=requestAnimationFrame(()=>{this.updateActiveSounds()}))}}}s.allWorkletSources=[],t.AudioWorkletSource=s}(e.AudioContextManager||(e.AudioContextManager={}))}(pxsim||(pxsim={})),function(e){!function(e){e.Metronome=class{constructor(){this.tickListeners=[],this.onTick=()=>{for(const e of this.tickListeners)e()}}initAsync(){return this.metronomeLoadPromise?this.metronomeLoadPromise:this.metronomeWorker?this.metronomeWorker:(this.metronomeLoadPromise=new Promise(e=>{this.metronomeWorker=new Worker("data:application/javascript,"+encodeURIComponent(t));const n=t=>{"ready"===t.data&&(e(this.metronomeWorker),this.metronomeWorker.removeEventListener("message",n),this.metronomeWorker.addEventListener("message",this.onTick))};this.metronomeWorker.addEventListener("message",n)}),this.metronomeLoadPromise)}stop(){this.postMessage({type:"stop"})}setInterval(e){this.currentInterval=e,this.postMessage({type:"set-interval",interval:e})}start(e){this.currentInterval=e,this.postMessage({type:"start",interval:e})}addTickListener(e){this.tickListeners.push(e)}removeTickListener(e){this.tickListeners=this.tickListeners.filter(t=>t!==e)}interval(){return this.currentInterval}dispose(){if(this.metronomeWorker)this.metronomeWorker.terminate(),this.metronomeWorker=void 0,this.metronomeLoadPromise=void 0,this.tickListeners=[],this.interval=void 0;else if(this.metronomeLoadPromise)return void this.metronomeLoadPromise.then(()=>this.dispose())}postMessage(e){if(!this.metronomeWorker)throw new Error("initAsync not called on metronome");this.metronomeWorker.postMessage(e)}};const t='\n/**\n * Adpated from https://github.com/cwilso/metronome/\n */\n\nlet timerRef;\nlet interval;\n\naddEventListener("message", ev => {\n const message = ev.data;\n\n if (message.type === "start") {\n updateInterval(message.interval, true);\n }\n else if (message.type === "stop") {\n clearInterval(timerRef);\n timerRef = undefined;\n }\n else if (message.type === "set-interval") {\n updateInterval(message.interval, false);\n }\n})\n\npostMessage("ready");\n\nfunction updateInterval(interval, startIfStopped) {\n if (timerRef) {\n clearInterval(timerRef);\n startIfStopped = true;\n }\n interval = interval;\n\n if (startIfStopped) {\n timerRef = setInterval(() => postMessage("tick"), interval);\n }\n}\n'}(e.music||(e.music={}))}(pxsim||(pxsim={})),function(e){!function(e){!function(e){!function(e){e.chromaticInterval=[1,1.0417,1.125,1.2,1.25,1.3333,1.4063,1.5,1.6,1.6667,1.8,1.875],e.majorScaleInterval=[e.chromaticInterval[0],e.chromaticInterval[2],e.chromaticInterval[4],e.chromaticInterval[5],e.chromaticInterval[7],e.chromaticInterval[9],e.chromaticInterval[11]],e.minorScaleInterval=[e.chromaticInterval[0],e.chromaticInterval[2],e.chromaticInterval[3],e.chromaticInterval[5],e.chromaticInterval[7],e.chromaticInterval[8],e.chromaticInterval[10]],e.pentatonicScaleInterval=[e.chromaticInterval[0],e.chromaticInterval[2],e.chromaticInterval[4],e.chromaticInterval[7],e.chromaticInterval[9]],e.majorTriadInterval=[e.chromaticInterval[0],e.chromaticInterval[4],e.chromaticInterval[7]],e.minorTriadInterval=[e.chromaticInterval[0],e.chromaticInterval[3],e.chromaticInterval[7]],e.diminishedInterval=[e.chromaticInterval[0],e.chromaticInterval[3],e.chromaticInterval[6],e.chromaticInterval[9]],e.wholeToneInterval=[e.chromaticInterval[0],e.chromaticInterval[2],e.chromaticInterval[4],e.chromaticInterval[6],e.chromaticInterval[8],e.chromaticInterval[10]]}(e.MusicalIntervals||(e.MusicalIntervals={}))}(e.music||(e.music={}))}(e.codal||(e.codal={}))}(pxsim||(pxsim={})),function(e){!function(e){!function(e){!function(t){t.chromatic={interval:e.MusicalIntervals.chromaticInterval,length:12},t.majorScale={interval:e.MusicalIntervals.majorScaleInterval,length:7},t.minorScale={interval:e.MusicalIntervals.minorScaleInterval,length:7},t.pentatonicScale={interval:e.MusicalIntervals.pentatonicScaleInterval,length:5},t.majorTriad={interval:e.MusicalIntervals.majorTriadInterval,length:3},t.minorTriad={interval:e.MusicalIntervals.minorTriadInterval,length:3},t.diminished={interval:e.MusicalIntervals.diminishedInterval,length:4},t.wholeTone={interval:e.MusicalIntervals.wholeToneInterval,length:6},t.calculateFrequencyFromProgression=function(e,t,n){let s=Math.floor(n/t.length),i=n%t.length;return e*Math.pow(2,s)*t.interval[i]}}(e.MusicalProgressions||(e.MusicalProgressions={}))}(e.music||(e.music={}))}(e.codal||(e.codal={}))}(pxsim||(pxsim={})),function(e){!function(t){const n=[null,"triangle","sawtooth","sine"];let s,i,r=[],o=[];function a(e,t,a){let l,u=n[t];if(u){let t=e.createOscillator();return t.type=u,t.frequency.value=a,t}if(4==t)l=function(e){if(!i){const t=131072;i=e.createBuffer(1,t,e.sampleRate);const n=i.getChannelData(0);let s=251771520;for(let e=0;e<t;e+=4)s^=s<<13,s^=s>>17,s^=s<<5,32768&s?(n[e]=1,n[e+1]=1,n[e+2]=-1,n[e+3]=-1):(n[e]=0,n[e+1]=0,n[e+2]=0,n[e+3]=0)}return i}(e);else if(5==t)l=function(e){if(!s){const t=1e5;s=e.createBuffer(1,t,e.sampleRate);const n=s.getChannelData(0);let i=251771520;for(let e=0;e<t;e++)i^=i<<13,i^=i>>17,i^=i<<5,n[e]=(1023&i)/512-1}return s}(e);else if(11<=t&&t<=15)l=function(e,t){if(!o[t]){const n=1024,s=e.createBuffer(1,n,e.sampleRate),i=s.getChannelData(0);for(let e=0;e<n;e++)i[e]=e<t/100*n?1:-1;o[t]=s}return o[t]}(e,10*(t-10));else{if(!(16<=t&&t<=18))return null;l=function(e,t){if(!r[t]){const n=1024,s=e.createBuffer(1,n,e.sampleRate),i=s.getChannelData(0),o=[770763591,3356908179],a=[15,31,63];for(let e=0;e<n;e+=4){let n,s=e/4;s&=a[t-4],n=!!(o[s>>5]&1<<(31&s)),n?(i[e]=1,i[e+1]=1,i[e+2]=-1,i[e+3]=-1):(i[e]=0,i[e+1]=0,i[e+2]=0,i[e+3]=0)}r[t]=s}return r[t]}(e,t-16+4)}let c=e.createBufferSource();c.buffer=l,c.loop=!0;return 4==t||16<=t&&t<=18?c.playbackRate.value=a/(e.sampleRate/4):5!=t&&(c.playbackRate.value=a/(e.sampleRate/1024)),c}class l extends t.AudioSource{constructor(e,t){super(e,t),this.context=e,this.destination=t,this.analyser=e.createAnalyser(),this.analyser.fftSize=2048,this.analyser.connect(this.vca),this.gain=e.createGain(),this.gain.connect(this.analyser)}playInstructionsAsync(n,s,i){return new Promise(async r=>{null===t.soundEventCallback||void 0===t.soundEventCallback||t.soundEventCallback("playinstructions",n);let o=!1;const l={},c={};let h=this.context.currentTime,d=h,p=0,f=0;const m=(e,t)=>e/1024/4*(t?.5:1),g=()=>{if(!o){o=!0;for(const e of Object.keys(l))l[e].stop(),l[e].disconnect(),c[e].disconnect();r()}};for(let e=0;e<n.length;e+=12){const t=n[e],s=u(n,e+2),i=u(n,e+4)/1e3,r=u(n,e+6),o=u(n,e+8),h=u(n,e+10);if(f+=i,0===t){d+=i;continue}const g=11<=t&&t<=15;l[t]||(l[t]=a(this.context,t,s),c[t]=this.context.createGain(),c[t].gain.value=0,c[t].connect(this.gain),l[t].connect(c[t]),l[t].start()),p&&t!==p&&c[p].gain.setTargetAtTime(0,d,.015);const b=l[t],v=c[t];if(b instanceof OscillatorNode)b.frequency.setValueAtTime(s,d),b.frequency.linearRampToValueAtTime(h,d+i);else{4==t||16<=t&&t<=18?b.playbackRate.linearRampToValueAtTime(h/(this.context.sampleRate/4),d+i):5!=t&&b.playbackRate.linearRampToValueAtTime(h/(this.context.sampleRate/1024),d+i)}v.gain.setValueAtTime(m(r,g),d),v.gain.linearRampToValueAtTime(m(o,g),d+i),p=t,d+=i}if(this.gain.gain.setTargetAtTime(0,d,.015),s||i){const e=()=>{const t=this.context.currentTime;if(t>h+f)return;if(s&&s()||this.isDisposed())return void g();const{frequency:r,volume:o}=function(e,t){let n=0;for(let s=0;s<t.length;s+=12){const i=u(t,s+2),r=u(t,s+4),o=u(t,s+6),a=u(t,s+8),l=u(t,s+10);if(n+r<e){n+=r;continue}const c=(e-n)/r;return{frequency:i+(l-i)*c,volume:o+(a-o)*c}}return{frequency:-1,volume:-1}}(1e3*(t-h),n);i&&i(r,o/1024),requestAnimationFrame(e)};requestAnimationFrame(e)}await e.U.delay(1e3*f),g()})}dispose(){this.isDisposed()||(super.dispose(),this.analyser.disconnect(),this.gain.disconnect(),this.analyser=void 0,this.gain=void 0)}}function u(e,t){const n=new Uint8Array(2);return n[0]=e[t],n[1]=e[t+1],new Uint16Array(n.buffer)[0]}t.PlayInstructionsSource=l}(e.AudioContextManager||(e.AudioContextManager={}))}(pxsim||(pxsim={})),function(e){!function(t){const n=[31,33,35,37,39,41,44,46,49,52,55,58,62,65,69,73,78,82,87,92,98,104,110,117,123,131,139,147,156,165,175,185,196,208,220,233,247,262,277,294,311,330,349,370,392,415,440,466,494,523,554,587,622,659,698,740,784,831,880,932,988,1047,1109,1175,1245,1319,1397,1480,1568,1661,1760,1865,1976,2093,2217,2349,2489,2637,2794,2960,3136,3322,3520,3729,3951,4186,4435,4699,4978,5274,5588,5920,6272,6645,7040,7459,7902];async function s(t,s,i,r,o=100){await e.AudioContextManager.playInstructionsAsync(e.music.renderInstrument(s,n[t],i,o),r)}async function i(t,n,s=100){await e.AudioContextManager.playInstructionsAsync(e.music.renderDrumInstrument(t,s),n)}async function r(t,s,i,r,o=100){await t.playInstructionsAsync(e.music.renderInstrument(i,n[s],r,o))}async function o(t,n,s=100){await t.playInstructionsAsync(e.music.renderDrumInstrument(n,s))}function a(e,t,n){return 6e4/e/t*n}t.Sequencer=class{constructor(){this._currentTick=0,this._state="stop",this.listeners={},this.globalVolume=1024,this.trackVolumes=[],this.drumTrackVolumes=[],this.currentCancelToken={cancelled:!1},this.onTick=()=>{const e=this.currentCancelToken;for(let t=0;t<this.currentlyPlaying.tracks.length;t++){const n=this.currentlyPlaying.tracks[t];for(const l of n.notes)if(l.startTick===this._currentTick)for(const u of l.notes)this.spatialAudioPlayer?n.drums?o(this.spatialAudioPlayer,n.drums[u.note],this.getDrumTrackVolume(t,u.note)):r(this.spatialAudioPlayer,u.note,n.instrument,a(this.currentlyPlaying.beatsPerMinute,this.currentlyPlaying.ticksPerBeat,l.endTick-l.startTick),this.getMelodicTrackVolume(t)):n.drums?i(n.drums[u.note],()=>e.cancelled,this.getDrumTrackVolume(t,u.note)):s(u.note,n.instrument,a(this.currentlyPlaying.beatsPerMinute,this.currentlyPlaying.ticksPerBeat,l.endTick-l.startTick),()=>e.cancelled,this.getMelodicTrackVolume(t));else if(l.startTick>this._currentTick)break}this.fireEvent("tick"),this._currentTick++,this._currentTick>=this.maxTick()&&("loop"===this._state?(this._currentTick=0,this.fireEvent("looped")):this.stop(!0))}}async initAsync(){this.metronome?await this.metronome.initAsync():(this.metronome=new t.Metronome,await this.metronome.initAsync(),this.metronome.addTickListener(this.onTick))}dispose(){this.metronome&&this.metronome.dispose(),this.metronome=void 0,this.stop(),this.currentlyPlaying=void 0,this.listeners={}}state(){return this._state}currentTick(){return this._currentTick}currentTime(){return a(this.currentlyPlaying.beatsPerMinute,this.currentlyPlaying.ticksPerBeat,this.currentTick())}maxTick(){return this.currentlyPlaying?this.currentlyPlaying.measures*this.currentlyPlaying.beatsPerMeasure*this.currentlyPlaying.ticksPerBeat:0}duration(){return a(this.currentlyPlaying.beatsPerMinute,this.currentlyPlaying.ticksPerBeat,this.maxTick())}start(e,t){this.startFrom(e,t,0)}startFrom(e,t,n){"stop"!==this._state&&this.stop(),void 0!==t&&(this.shouldLoop=t),this._currentTick=null!=n?n:0,this.currentlyPlaying=e,this.metronome.start(a(e.beatsPerMinute,e.ticksPerBeat,1)),this._state=this.shouldLoop?"loop":"play",this.fireStateChange()}stop(e=!1){"stop"!==this._state&&(this._state="stop",this.metronome&&this.metronome.stop(),this.fireStateChange(),e||(this.currentCancelToken.cancelled=!0),this.currentCancelToken={cancelled:!1})}updateSong(e){this.currentlyPlaying=e,"stop"!==this._state&&this.metronome.setInterval(a(e.beatsPerMinute,e.ticksPerBeat,1))}setLooping(e){e&&"play"===this._state?(this._state="loop",this.fireStateChange()):e||"loop"!==this._state||(this._state="play",this.fireStateChange()),this.shouldLoop=e}addEventListener(e,t){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(t)}removeEventListener(e,t){this.listeners[e]&&(this.listeners[e]=this.listeners[e].filter(e=>e!==t))}setVolume(e){this.globalVolume=Math.min(Math.max(e,0),1024)}setTrackVolume(e,t){for(t=Math.min(Math.max(t,0),1024);this.trackVolumes.length<e;)this.trackVolumes.push(1024);this.trackVolumes[e]=t}setDrumTrackVolume(e,t,n){for(n=Math.min(Math.max(n,0),1024);this.drumTrackVolumes.length<e;)this.drumTrackVolumes.push([]);for(;this.drumTrackVolumes[e].length<t;)this.drumTrackVolumes[e].push(1024);this.drumTrackVolumes[e][t]=n}setSpatialAudioPlayer(e){this.spatialAudioPlayer=e}getMelodicTrackVolume(e){let t=1024;return e<this.trackVolumes.length&&(t=this.trackVolumes[e]),this.globalVolume*(t/1024)}getDrumTrackVolume(e,t){const n=this.getMelodicTrackVolume(e);let s=1024;return e<this.drumTrackVolumes.length&&t<this.drumTrackVolumes[e].length&&(s=this.drumTrackVolumes[e][t]),n*(s/1024)}fireStateChange(){this.fireEvent(this._state),this.fireEvent("state-change")}fireEvent(e){if(this.listeners[e])for(const t of this.listeners[e])t()}},t.playNoteAsync=s,t.playDrumAsync=i,t.tickToMs=a}(e.music||(e.music={}))}(pxsim||(pxsim={})),function(e){!function(e){function t(e,t,n,r){var o,a;let l=0;return(null===(o=e.pitchEnvelope)||void 0===o?void 0:o.amplitude)&&(l+=s(e.pitchEnvelope,r,n)),(null===(a=e.pitchLFO)||void 0===a?void 0:a.amplitude)&&(l+=i(e.pitchLFO,r)),Math.max(t+l,0)}function n(e,t,n,r){var o;let a=0;return e.ampEnvelope.amplitude&&(a+=s(e.ampEnvelope,n,t)),(null===(o=e.ampLFO)||void 0===o?void 0:o.amplitude)&&(a+=i(e.ampLFO,n)),Math.max(Math.min(a,e.ampEnvelope.amplitude),0)/1024*r|0}function s(e,t,n){const s=e.sustain/1024*e.amplitude;if(t>n){if(t-n>e.release)return 0;if(t<e.attack){const s=e.amplitude/e.attack*n;return s-s/e.release*(t-n)}if(t<e.attack+e.decay){const i=e.amplitude-(e.amplitude-s)/e.decay*(n-e.attack);return i-i/e.release*(t-n)}return s-s/e.release*(t-n)}return t<e.attack?e.amplitude/e.attack*t:t<e.attack+e.decay?e.amplitude-(e.amplitude-s)/e.decay*(t-e.attack):s}function i(e,t){return Math.cos(t/1e3*e.frequency*2*Math.PI)*e.amplitude}function r(e,t,n,s,i,r,a,l){return n>0&&(e[t]=r,e[t+1]=0,o(e,t+2,a),o(e,t+4,n),o(e,t+6,255*s>>6),o(e,t+8,255*i>>6),o(e,t+10,l),t+=12),e[t]=0,t}function o(e,t,n){const s=new Uint8Array(2);new Uint16Array(s.buffer)[0]=0|n,e[t]=s[0],e[t+1]=s[1]}function a(e,t){const n=new Uint8Array(2);return n[0]=e[t],n[1]=e[t+1],new Uint16Array(n.buffer)[0]}function l(e,t){return{waveform:e[t],ampEnvelope:{attack:a(e,t+1),decay:a(e,t+3),sustain:a(e,t+5),release:a(e,t+7),amplitude:a(e,t+9)},pitchEnvelope:{attack:a(e,t+11),decay:a(e,t+13),sustain:a(e,t+15),release:a(e,t+17),amplitude:a(e,t+19)},ampLFO:{frequency:e[t+21],amplitude:a(e,t+22)},pitchLFO:{frequency:e[t+24],amplitude:a(e,t+25)},octave:e[t+27]}}function u(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=a(e,t+2);let i=t+4;for(;i<t+4+s;)n.drums.push(c(e,i)),i+=5+7*n.drums[n.drums.length-1].steps.length;const r=a(e,i);i+=2;for(;i<t+4+s+r;)n.notes.push(h(e,i,0,!0)),i+=5+n.notes[n.notes.length-1].notes.length;return[n,i]}(e,t):function(e,t){const n={id:e[t],instrument:l(e,t+4),notes:[]},s=t+4+a(e,t+2),i=a(e,s);let r=s+2;for(;r<s+2+i;)n.notes.push(h(e,r,n.instrument.octave,!1)),r+=5+n.notes[n.notes.length-1].notes.length;return[n,r]}(e,t)}function c(e,t){const n={startFrequency:a(e,t+1),startVolume:a(e,t+3),steps:[]};for(let s=0;s<e[t];s++){const i=t+5+7*s;n.steps.push({waveform:e[i],frequency:a(e,i+1),volume:a(e,i+3),duration:a(e,i+5)})}return n}function h(e,t,n,s){const i={startTick:a(e,t),endTick:a(e,t+2),notes:[]};for(let r=0;r<e[t+4];r++)i.notes.push(d(e[t+5+r],n,s));return i}function d(e,t,n){const s=e>>6,i={note:n?e:(63&e)+12*(t-2),enharmonicSpelling:"normal"};return 1===s?i.enharmonicSpelling="flat":2===s&&(i.enharmonicSpelling="sharp"),i}e.renderInstrument=function(e,s,i,o){var a,l,u,c,h;const d=i+e.ampEnvelope.release,p=(null===(a=e.ampLFO)||void 0===a?void 0:a.amplitude)?Math.max(500/e.ampLFO.frequency,50):50,f=(null===(l=e.pitchLFO)||void 0===l?void 0:l.amplitude)?Math.max(500/e.pitchLFO.frequency,50):50;let m=[0],g=e.ampEnvelope.attack,b=(null===(u=e.pitchEnvelope)||void 0===u?void 0:u.amplitude)?e.pitchEnvelope.attack:d,v=(null===(c=e.pitchLFO)||void 0===c?void 0:c.amplitude)?f:d,y=(null===(h=e.ampLFO)||void 0===h?void 0:h.amplitude)?p:d,S=0;for(;S<d&&(g<=b&&g<=v&&g<=y?(S=g,m.push(g),g=S<e.ampEnvelope.attack+e.ampEnvelope.decay&&e.ampEnvelope.attack+e.ampEnvelope.decay<i?e.ampEnvelope.attack+e.ampEnvelope.decay:S<i?i:d):b<=v&&b<=y&&b<d?(S=b,m.push(b),b=S<e.pitchEnvelope.attack+e.pitchEnvelope.decay&&e.pitchEnvelope.attack+e.pitchEnvelope.decay<i?e.pitchEnvelope.attack+e.pitchEnvelope.decay:S<i?i:S<i+e.pitchEnvelope.release?Math.min(d,i+e.pitchEnvelope.release):d):v<=y&&v<d?(S=v,m.push(v),v+=f):y<d&&(S=y,m.push(y),y+=p),!(S>=d));){for(g<=S&&(g=S<e.ampEnvelope.attack+e.ampEnvelope.decay&&e.ampEnvelope.attack+e.ampEnvelope.decay<i?e.ampEnvelope.attack+e.ampEnvelope.decay:S<i?i:d),b<=S&&(b=S<e.pitchEnvelope.attack+e.pitchEnvelope.decay&&e.pitchEnvelope.attack+e.pitchEnvelope.decay<i?e.pitchEnvelope.attack+e.pitchEnvelope.decay:S<i?i:S<i+e.pitchEnvelope.release?Math.min(d,i+e.pitchEnvelope.release):d);y<=S;)y+=p;for(;v<=S;)v+=f}let w,x,E=0|n(e,i,0,o),I=0|t(e,s,i,0),k=0;const C=new Uint8Array(12*(m.length+1));for(let a=1;a<m.length;a++)m[a]-k<5||(w=0|n(e,i,m[a],o),x=0|t(e,s,i,m[a]),r(C,12*(a-1),m[a]-k|0,E,w,e.waveform,I,x),E=w,I=x),k=m[a];return r(C,12*m.length,10,E,0,e.waveform,I,I),C},e.renderDrumInstrument=function(e,t){let n=e.startVolume,s=e.startFrequency;const i=e=>e/1024*t;let o=new Uint8Array(12*(e.steps.length+1));for(let t=0;t<e.steps.length;t++)r(o,12*t,e.steps[t].duration,i(n),i(e.steps[t].volume),e.steps[t].waveform,s,e.steps[t].frequency),n=e.steps[t].volume,s=e.steps[t].frequency;return r(o,12*e.steps.length,10,i(n),0,e.steps[e.steps.length-1].waveform,s,s),o},e.decodeSong=function(e){const t={beatsPerMinute:a(e,1),beatsPerMeasure:e[3],ticksPerBeat:e[4],measures:e[5],tracks:[]};let n=7;for(;n<e.length;){const[s,i]=u(e,n);n=i,t.tracks.push(s)}return t}}(e.music||(e.music={}))}(pxsim||(pxsim={})),function(e){!function(e){!function(e){e.EMOJI_SYNTHESIZER_SAMPLE_RATE=44100,e.EMOJI_SYNTHESIZER_TONE_WIDTH_F=1024,e.EMOJI_SYNTHESIZER_TONE_WIDTH=1024,e.EMOJI_SYNTHESIZER_BUFFER_SIZE=512,e.EMOJI_SYNTHESIZER_TONE_EFFECT_PARAMETERS=2,e.EMOJI_SYNTHESIZER_TONE_EFFECTS=3,e.EMOJI_SYNTHESIZER_STATUS_ACTIVE=1,e.EMOJI_SYNTHESIZER_STATUS_OUTPUT_SILENCE_AS_EMPTY=2,e.EMOJI_SYNTHESIZER_STATUS_STOPPING=4;e.SoundEmojiSynthesizer=class{constructor(t,n=e.EMOJI_SYNTHESIZER_SAMPLE_RATE){this.samplesPerStep=[],this.status=0,this.effectPointer=0,this.position=0,this.bufferSize=e.EMOJI_SYNTHESIZER_BUFFER_SIZE,this.sampleRate=n,this.samplesToWrite=0,this.samplesWritten=0,this.sampleRange=1023,this.orMask=0,this.effectPointer=-1,this.volume=1}get effect(){return this.effectBuffer[this.effectPointer]}play(e){this.effectBuffer=e,this.effectPointer=-1,this.nextSoundEffect()}nextSoundEffect(){const t=null!=this.effect;if(this.status&e.EMOJI_SYNTHESIZER_STATUS_STOPPING&&(this.effectPointer=null,this.effectBuffer=[]),this.effect?this.effectPointer++:this.effectPointer=0,this.effectPointer>=this.effectBuffer.length&&(this.effectPointer=0,this.effect.duration>=0))return this.effectPointer=-1,this.effectBuffer=[],this.samplesWritten=0,this.samplesToWrite=0,this.position=0,t;this.samplesToWrite=this.determineSampleCount(this.effect.duration),this.frequency=this.effect.frequency,this.volume=this.effect.volume,this.samplesWritten=0;for(let t=0;t<e.EMOJI_SYNTHESIZER_TONE_EFFECTS;t++)this.effect.effects[t].step=0,this.effect.effects[t].steps=Math.max(this.effect.effects[t].steps,1),this.samplesPerStep[t]=Math.floor(this.samplesToWrite/this.effect.effects[t].steps);return!1}pull(){let t,n,s=!1;for(;!s;){if(this.samplesWritten==this.samplesToWrite||this.status&e.EMOJI_SYNTHESIZER_STATUS_STOPPING){let t=this.nextSoundEffect();(0==this.samplesToWrite||this.status&e.EMOJI_SYNTHESIZER_STATUS_STOPPING)&&(s=!0,(t||this.status&e.EMOJI_SYNTHESIZER_STATUS_STOPPING)&&(this.status&=~e.EMOJI_SYNTHESIZER_STATUS_STOPPING))}for(!(this.samplesWritten<this.samplesToWrite)&&this.status&e.EMOJI_SYNTHESIZER_STATUS_OUTPUT_SILENCE_AS_EMPTY||null!=t||(this.buffer=new Array(this.bufferSize),t=0,n=this.buffer.length);this.samplesWritten<this.samplesToWrite;){let s=e.EMOJI_SYNTHESIZER_TONE_WIDTH_F*this.frequency/this.sampleRate,i=this.sampleRange*this.volume/1024,r=512-512*i,o=[];for(let t=0;t<e.EMOJI_SYNTHESIZER_TONE_EFFECTS;t++)o[t]=this.samplesPerStep[t]*this.effect.effects[t].step,this.effect.effects[t].step==this.effect.effects[t].steps-1&&(o[t]=this.samplesToWrite);let a=o[0];for(let t=1;t<e.EMOJI_SYNTHESIZER_TONE_EFFECTS;t++)a=Math.min(a,o[t]);for(;this.samplesWritten<a;){if(t==n)return this.buffer;let o=this.effect.tone.tonePrint(this.effect.tone.parameter,Math.max(this.position,0));for(this.buffer[t]=o*i+r,t++,this.samplesWritten++,this.position+=s;this.position>e.EMOJI_SYNTHESIZER_TONE_WIDTH_F;)this.position-=e.EMOJI_SYNTHESIZER_TONE_WIDTH_F}for(let t=0;t<e.EMOJI_SYNTHESIZER_TONE_EFFECTS;t++)this.samplesWritten==o[t]&&this.effect.effects[t].step<this.effect.effects[t].steps&&(this.effect.effects[t].effect&&this.effect.effects[t].effect(this,this.effect.effects[t]),this.effect.effects[t].step++)}}if(null==t)this.buffer=[];else{const e=.5*this.sampleRange;for(;t<n;)this.buffer[t]=e,t++}return this.buffer}determineSampleCount(e){e<0&&(e=-e);const t=e/1e3;return Math.floor(this.sampleRate*t)}totalDuration(){let e=0;for(const t of this.effectBuffer)e+=t.duration;return e}}}(e.music||(e.music={}))}(e.codal||(e.codal={}))}(pxsim||(pxsim={})),function(e){!function(e){!function(e){!function(e){const t=[0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,3,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,11,11,12,13,13,14,15,16,16,17,18,19,20,21,22,22,23,24,25,26,27,28,29,30,32,33,34,35,36,37,38,40,41,42,43,45,46,47,49,50,51,53,54,56,57,58,60,61,63,64,66,68,69,71,72,74,76,77,79,81,82,84,86,87,89,91,93,95,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,141,143,145,147,149,152,154,156,158,161,163,165,167,170,172,175,177,179,182,184,187,189,191,194,196,199,201,204,206,209,211,214,216,219,222,224,227,229,232,235,237,240,243,245,248,251,253,256,259,262,264,267,270,273,275,278,281,284,287,289,292,295,298,301,304,307,309,312,315,318,321,324,327,330,333,336,339,342,345,348,351,354,357,360,363,366,369,372,375,378,381,384,387,390,393,396,399,402,405,408,411,414,417,420,424,427,430,433,436,439,442,445,448,452,455,458,461,464,467,470,473,477,480,483,486,489,492,495,498,502,505,508,511,514,517,520,524,527,530,533,536,539,542,545,549,552,555,558,561,564,567,570,574,577,580,583,586,589,592,595,598,602,605,608,611,614,617,620,623,626,629,632,635,638,641,644,647,650,653,656,659,662,665,668,671,674,677,680,683,686,689,692,695,698,701,704,707,710,713,715,718,721,724,727,730,733,735,738,741,744,747,749,752,755,758,760,763,766,769,771,774,777,779,782,785,787,790,793,795,798,800,803,806,808,811,813,816,818,821,823,826,828,831,833,835,838,840,843,845,847,850,852,855,857,859,861,864,866,868,870,873,875,877,879,881,884,886,888,890,892,894,896,898,900,902,904,906,908,910,912,914,916,918,920,922,924,926,927,929,931,933,935,936,938,940,941,943,945,946,948,950,951,953,954,956,958,959,961,962,964,965,966,968,969,971,972,973,975,976,977,979,980,981,982,984,985,986,987,988,989,990,992,993,994,995,996,997,998,999,1e3,1e3,1001,1002,1003,1004,1005,1006,1006,1007,1008,1009,1009,1010,1011,1011,1012,1013,1013,1014,1014,1015,1015,1016,1016,1017,1017,1018,1018,1019,1019,1019,1020,1020,1020,1021,1021,1021,1021,1022,1022,1022,1022,1022,1022,1022,1022,1022,1022,1023,1022];e.SineTone=function(e,n){let s=1024-(n|=0);return s<512&&(n=s),t[n]},e.SawtoothTone=function(e,t){return t},e.TriangleTone=function(e,t){return t<512?2*t:2*(1023-t)},e.NoiseTone=function(e,t){let n=e[0];return 0==n&&(n=7919),t*n&1023},e.SquareWaveTone=function(e,t){return t<512?1023:0}}(e.Synthesizer||(e.Synthesizer={}))}(e.music||(e.music={}))}(e.codal||(e.codal={}))}(pxsim||(pxsim={})),function(e){!function(e){!function(e){!function(t){t.noInterpolation=function(e,t){},t.linearInterpolation=function(e,t){let n=(t.parameter[0]-e.effect.frequency)/t.steps;e.frequency=e.effect.frequency+n*t.step},t.logarithmicInterpolation=function(e,t){e.frequency=e.effect.frequency+Math.log10(Math.max(t.step,.1))*(t.parameter[0]-e.effect.frequency)/1.95},t.curveInterpolation=function(e,t){e.frequency=Math.sin(3.12159*t.step/180)*(t.parameter[0]-e.effect.frequency)+e.effect.frequency},t.slowVibratoInterpolation=function(e,t){e.frequency=Math.sin(t.step/10)*t.parameter[0]+e.effect.frequency},t.warbleInterpolation=function(e,t){e.frequency=Math.sin(t.step)*(t.parameter[0]-e.effect.frequency)+e.effect.frequency},t.vibratoInterpolation=function(e,t){e.frequency=e.effect.frequency+Math.sin(t.step)*t.parameter[0]},t.exponentialRisingInterpolation=function(e,t){e.frequency=e.effect.frequency+Math.sin(.01745329*t.step)*t.parameter[0]},t.exponentialFallingInterpolation=function(e,t){e.frequency=e.effect.frequency+Math.cos(.01745329*t.step)*t.parameter[0]},t.appregrioAscending=function(t,n){t.frequency=e.MusicalProgressions.calculateFrequencyFromProgression(t.effect.frequency,n.parameter_p[0],n.step)},t.appregrioDescending=function(t,n){t.frequency=e.MusicalProgressions.calculateFrequencyFromProgression(t.effect.frequency,n.parameter_p[0],n.steps-n.step-1)},t.frequencyVibratoEffect=function(e,t){0!=t.step&&(t.step%2==0?e.frequency/=t.parameter[0]:e.frequency*=t.parameter[0])},t.volumeVibratoEffect=function(e,t){0!=t.step&&(t.step%2==0?e.volume/=t.parameter[0]:e.volume*=t.parameter[0])},t.adsrVolumeEffect=function(e,t){let n=.5*t.steps;if(t.step<=n){let s=(t.parameter[0]-e.effect.volume)/n;e.volume=e.effect.volume+t.step*s}else{let s=(t.parameter[1]-t.parameter[0])/n;e.volume=t.parameter[0]+(t.step-n)*s}},t.volumeRampEffect=function(e,t){let n=(t.parameter[0]-e.effect.volume)/t.steps;e.volume=e.effect.volume+t.step*n}}(e.SoundSynthesizerEffects||(e.SoundSynthesizerEffects={}))}(e.music||(e.music={}))}(e.codal||(e.codal={}))}(pxsim||(pxsim={})),function(e){!function(t){!function(t){let n,s,i;!function(e){e[e.Sine=0]="Sine",e[e.Sawtooth=1]="Sawtooth",e[e.Triangle=2]="Triangle",e[e.Square=3]="Square",e[e.Noise=4]="Noise"}(n=t.WaveShape||(t.WaveShape={})),function(e){e[e.None=0]="None",e[e.Linear=1]="Linear",e[e.Curve=2]="Curve",e[e.ExponentialRising=5]="ExponentialRising",e[e.ExponentialFalling=6]="ExponentialFalling",e[e.ArpeggioRisingMajor=8]="ArpeggioRisingMajor",e[e.ArpeggioRisingMinor=10]="ArpeggioRisingMinor",e[e.ArpeggioRisingDiminished=12]="ArpeggioRisingDiminished",e[e.ArpeggioRisingChromatic=14]="ArpeggioRisingChromatic",e[e.ArpeggioRisingWholeTone=16]="ArpeggioRisingWholeTone",e[e.ArpeggioFallingMajor=9]="ArpeggioFallingMajor",e[e.ArpeggioFallingMinor=11]="ArpeggioFallingMinor",e[e.ArpeggioFallingDiminished=13]="ArpeggioFallingDiminished",e[e.ArpeggioFallingChromatic=15]="ArpeggioFallingChromatic",e[e.ArpeggioFallingWholeTone=17]="ArpeggioFallingWholeTone",e[e.Logarithmic=18]="Logarithmic"}(s=t.InterpolationEffect||(t.InterpolationEffect={})),function(e){e[e.None=0]="None",e[e.Vibrato=1]="Vibrato",e[e.Tremolo=2]="Tremolo",e[e.Warble=3]="Warble"}(i=t.Effect||(t.Effect={}));class r{constructor(){this.src="000000000000000000000000000000000000000000000000000000000000000000000000"}get wave(){return this.getValue(0,1)}set wave(e){this.setValue(0,g(e,0,4),1)}get volume(){return this.getValue(1,4)}set volume(e){this.setValue(1,g(e,0,1023),4)}get frequency(){return this.getValue(5,4)}set frequency(e){this.setValue(5,e,4)}get duration(){return this.getValue(9,4)}set duration(e){this.setValue(9,e,4)}get shape(){return this.getValue(13,2)}set shape(e){this.setValue(13,e,2)}get endFrequency(){return this.getValue(18,4)}set endFrequency(e){this.setValue(18,e,4)}get endVolume(){return this.getValue(26,4)}set endVolume(e){this.setValue(26,g(e,0,1023),4)}get steps(){return this.getValue(30,4)}set steps(e){this.setValue(30,e,4)}get fx(){return this.getValue(34,2)}set fx(e){this.setValue(34,g(e,0,3),2)}get fxParam(){return this.getValue(36,4)}set fxParam(e){this.setValue(36,e,4)}get fxnSteps(){return this.getValue(40,4)}set fxnSteps(e){this.setValue(40,e,4)}get frequencyRandomness(){return this.getValue(44,4)}set frequencyRandomness(e){this.setValue(44,e,4)}get endFrequencyRandomness(){return this.getValue(48,4)}set endFrequencyRandomness(e){this.setValue(48,e,4)}get volumeRandomness(){return this.getValue(52,4)}set volumeRandomness(e){this.setValue(52,e,4)}get endVolumeRandomness(){return this.getValue(56,4)}set endVolumeRandomness(e){this.setValue(56,e,4)}get durationRandomness(){return this.getValue(60,4)}set durationRandomness(e){this.setValue(60,e,4)}get fxParamRandomness(){return this.getValue(64,4)}set fxParamRandomness(e){this.setValue(64,e,4)}get fxnStepsRandomness(){return this.getValue(68,4)}set fxnStepsRandomness(e){this.setValue(68,e,4)}copy(){const e=new r;return e.src=this.src.slice(0),e}setValue(e,t,n){t=g(0|t,0,Math.pow(10,n)-1),this.src=this.src.substr(0,e)+function(e,t){let n=e+"";for(;n.length<t;)n="0"+n;return n}(t,n)+this.src.substr(e+n)}getValue(e,t){return parseInt(this.src.substr(e,t))}}t.Sound=r;let o,a=!1,l={cancelled:!1};async function u(){if(o.length){a=!0;const e=o.shift();let t=l;try{e.onStarted(),await h(e.notes,()=>t.cancelled,void 0,e.volume),t.cancelled?e.onCancelled():e.onFinished()}catch(t){e.onCancelled()}u()}else a=!1}function c(){o=[],l.cancelled=!0,l={cancelled:!1}}function h(n,s,i,r=.03){const o=new t.SoundEmojiSynthesizer(0),a=function(e){const t=72,n=Math.floor((e.length+1)/(t+1)),s=n*(t+1)-1;if(e.length!=s)return[];const i=[];for(let s=0;s<n;++s){const n=s*t+s;if(n>0&&","!=e[n-1])return[];const r=m();if(!d(e.substr(n),r))return[];i.push(r)}return i}(n);o.play(a);let l=!1;return Promise.race([(u=o.totalDuration(),new Promise(e=>setTimeout(e,u))).then(()=>{l=!0}),e.AudioContextManager.playPCMBufferStreamAsync(()=>{if(!o.effect)return;const e=o.pull();i&&i({frequency:o.frequency,volume:o.volume});const t=new Float32Array(e.length);for(let n=0;n<e.length;n++)t[n]=(e[n]-512)/512;return t},o.sampleRate,r,()=>l||s&&s())]);var u}function d(e,n){let s=parseInt(e.substr(0,1)),i=parseInt(e.substr(1,4)),r=parseInt(e.substr(5,4)),o=parseInt(e.substr(9,4)),a=parseInt(e.substr(13,2)),l=parseInt(e.substr(18,4)),u=parseInt(e.substr(26,4)),c=parseInt(e.substr(30,4)),h=parseInt(e.substr(34,2)),d=parseInt(e.substr(36,4)),m=parseInt(e.substr(40,4));if(r=f(r,parseInt(e.substr(44,4))),l=f(l,parseInt(e.substr(48,4))),i=f(i,parseInt(e.substr(52,4))),u=f(u,parseInt(e.substr(56,4))),o=f(o,parseInt(e.substr(60,4))),d=f(d,parseInt(e.substr(64,4))),m=f(m,parseInt(e.substr(68,4))),-1==r||-1==l||-1==i||-1==u||-1==o||-1==d||-1==m)return!1;switch(s){case 0:n.tone.tonePrint=t.Synthesizer.SineTone;break;case 1:n.tone.tonePrint=t.Synthesizer.SawtoothTone;break;case 2:n.tone.tonePrint=t.Synthesizer.TriangleTone;break;case 3:n.tone.tonePrint=t.Synthesizer.SquareWaveTone;break;case 4:n.tone.tonePrint=t.Synthesizer.NoiseTone}switch(n.frequency=r,n.duration=o,n.effects[0].steps=c,a){case 0:n.effects[0].effect=t.SoundSynthesizerEffects.noInterpolation;break;case 1:n.effects[0].effect=t.SoundSynthesizerEffects.linearInterpolation,n.effects[0].parameter[0]=l;break;case 2:n.effects[0].effect=t.SoundSynthesizerEffects.curveInterpolation,n.effects[0].parameter[0]=l;break;case 5:n.effects[0].effect=t.SoundSynthesizerEffects.exponentialRisingInterpolation,n.effects[0].parameter[0]=l;break;case 6:n.effects[0].effect=t.SoundSynthesizerEffects.exponentialFallingInterpolation,n.effects[0].parameter[0]=l;break;case 8:case 10:case 12:case 14:case 16:n.effects[0].effect=t.SoundSynthesizerEffects.appregrioAscending;break;case 9:case 11:case 13:case 15:case 17:n.effects[0].effect=t.SoundSynthesizerEffects.appregrioDescending;break;case 18:n.effects[0].effect=t.SoundSynthesizerEffects.logarithmicInterpolation,n.effects[0].parameter[0]=l}switch(a){case 8:case 9:n.effects[0].parameter_p[0]=t.MusicalProgressions.majorScale;break;case 10:case 11:n.effects[0].parameter_p[0]=t.MusicalProgressions.minorScale;break;case 12:case 13:n.effects[0].parameter_p[0]=t.MusicalProgressions.diminished;break;case 14:case 15:n.effects[0].parameter_p[0]=t.MusicalProgressions.chromatic;break;case 16:case 17:n.effects[0].parameter_p[0]=t.MusicalProgressions.wholeTone}let g=p(0,i,1023)/1023,b=p(0,u,1023)/1023;n.volume=1*g,n.effects[1].effect=t.SoundSynthesizerEffects.volumeRampEffect,n.effects[1].steps=36,n.effects[1].parameter[0]=1*b;let v=Math.round(n.duration/1e4*m);switch(h){case 1:n.effects[2].steps=v,n.effects[2].effect=t.SoundSynthesizerEffects.frequencyVibratoEffect,n.effects[2].parameter[0]=d;break;case 2:n.effects[2].steps=v,n.effects[2].effect=t.SoundSynthesizerEffects.volumeVibratoEffect,n.effects[2].parameter[0]=d;break;case 3:n.effects[2].steps=v,n.effects[2].effect=t.SoundSynthesizerEffects.warbleInterpolation,n.effects[2].parameter[0]=d}return!0}function p(e,t,n){return Math.min(n,Math.max(e,t))}function f(e,t){if(e<0||t<0)return-1;const n=(s=2*t+1,Math.floor(Math.random()*s)-t);var s;return Math.abs(e+n)}function m(){const e={frequency:0,volume:1,duration:0,tone:{tonePrint:void 0,parameter:[0]},effects:[]};for(let n=0;n<t.EMOJI_SYNTHESIZER_TONE_EFFECTS;n++)e.effects.push({effect:void 0,step:0,steps:0,parameter:[],parameter_p:[]});return e}function g(e,t,n){return Math.min(Math.max(e,t),n)}t.isSoundExpPlaying=function(){return a},t.__playSoundExpression=function(t,n,s=.03){o||(o=[]);const i=e.getResume(),r=new Promise((e,r)=>{o.push({notes:t,volume:s,onStarted:()=>{n||i()},onFinished:e,onCancelled:e})});a||u(),n&&r.then(i)},t.clearSoundQueue=c,t.playSoundExpressionAsync=h,t.__stopSoundExpressions=function(){c(),e.AudioContextManager.stopAll()},t.parseSoundExpression=d}(t.music||(t.music={}))}(e.codal||(e.codal={}))}(pxsim||(pxsim={})),function(e){!function(e){let t;!function(e){e[e.Linear=0]="Linear",e[e.Inverse=1]="Inverse",e[e.Exponential=2]="Exponential"}(t=e.DistanceModelValue||(e.DistanceModelValue={}));class n{constructor(e,t){this.context=e,this.id=n.nextId++,n.allPlayers.push(this),this.panner=new PannerNode(e,{panningModel:"HRTF",distanceModel:"linear",positionX:0,positionY:0,positionZ:0,orientationX:0,orientationY:0,orientationZ:-1}),this.panner.connect(t)}static disposeAll(){for(;n.allPlayers.length;)n.allPlayers[0].dispose()}static getPlayerById(e){for(const t of n.allPlayers)if(t.id===e)return t}setPosition(e,t,n){this.panner.positionX.setTargetAtTime(e,0,.02),this.panner.positionY.setTargetAtTime(t,0,.02),this.panner.positionZ.setTargetAtTime(n,0,.02)}setOrientation(e,t,n){this.panner.orientationX.setTargetAtTime(e,0,.02),this.panner.orientationY.setTargetAtTime(t,0,.02),this.panner.orientationZ.setTargetAtTime(n,0,.02)}setCone(e,t,n){this.panner.coneInnerAngle=e,this.panner.coneOuterAngle=t,this.panner.coneOuterGain=n}setRollOff(e,t,n){this.panner.refDistance=e,this.panner.maxDistance=t,this.panner.rolloffFactor=n}setDistanceModel(e){switch(e){case t.Linear:this.panner.distanceModel="linear";break;case t.Inverse:this.panner.distanceModel="inverse";break;case t.Exponential:this.panner.distanceModel="exponential"}}get x(){return this.panner.positionX.value}get y(){return this.panner.positionY.value}get z(){return this.panner.positionZ.value}dispose(){this.panner.disconnect(),this.panner=void 0,this.audioWorkletSource&&(this.audioWorkletSource.dispose(),this.audioWorkletSource=void 0);const e=n.allPlayers.indexOf(this);e>=0&&n.allPlayers.splice(e,1)}async playInstructionsAsync(t){await e.AudioWorkletSource.initializeWorklet(this.context),this.audioWorkletSource&&!this.audioWorkletSource.isDisposed()||(this.audioWorkletSource=new e.AudioWorkletSource(this.context,this.panner,!0)),await this.audioWorkletSource.playInstructionsAsync(t)}}n.nextId=1,n.allPlayers=[],e.SpatialAudioPlayer=n}(e.AudioContextManager||(e.AudioContextManager={}))}(pxsim||(pxsim={})),function(e){e.getWorkletUri=function(){const e=new Blob(['\n const SW_TRIANGLE = 1;\n const SW_SAWTOOTH = 2;\n const SW_SINE = 3;\n const SW_TUNEDNOISE = 4;\n const SW_NOISE = 5;\n const SW_SQUARE_10 = 11;\n const SW_SQUARE_50 = 15;\n const SW_SQUARE_CYCLE_16 = 16;\n const SW_SQUARE_CYCLE_32 = 17;\n const SW_SQUARE_CYCLE_64 = 18;\n const OUTPUT_BITS = 14;\n\n function instrSoundWave(instructions, index) {\n return instructions[index];\n }\n\n function instrFrequency(instructions, index) {\n return Math.min(20000, Math.max(20, readInt16(instructions, index + 2)));\n }\n\n function instrDuration(instructions, index) {\n return Math.min(60000, Math.max(1, readInt16(instructions, index + 4)));\n }\n\n function instrStartVolume(instructions, index) {\n return Math.min(1023, Math.max(0, readInt16(instructions, index + 6)));\n }\n\n function instrEndVolume(instructions, index) {\n return Math.min(1023, Math.max(0, readInt16(instructions, index + 8)));\n }\n\n function instrEndFrequency(instructions, index) {\n return Math.min(20000, Math.max(20, readInt16(instructions, index + 10)));\n }\n\n function readInt16(instructions, index) {\n return instructions[index] | (instructions[index + 1] << 8);\n }\n\n let x = 0xf01ba80;\n function noiseTone(sound, position, cycle) {\n x ^= x << 13;\n x ^= x >> 17;\n x ^= x << 5;\n return (x & 0xffff) - 0x7fff;\n }\n\n function sineTone(sound, position, cycle) {\n let p = position;\n if (p >= 512) {\n p -= 512;\n }\n if (p > 256) {\n p = 512 - p;\n }\n // Approximate sin(x * pi / 2) with the odd polynomial y = cx^5 + bx^3 + ax\n // using the constraint y(1) = 1 => a = 1 - b - c\n // => y = c x^5 + b x^3 + (1 - b - c) * x\n //\n // Do a least-squares fit of this to sin(x * pi / 2) in the range 0..1\n // inclusive, using 21 evenly spaced points. Resulting approximation:\n //\n // sin(x*pi/2) ~= 0.0721435357258*x**5 - 0.642443736562*x**3 + 1.57030020084*x\n // Scale the constants by 32767 to match the desired output range.\n const c = 0.0721435357258 * 32767;\n const b = -0.642443736562 * 32767;\n const a = 1.57030020084 * 32767;\n // Calculate using y = ((c * x^2 + b) * x^2 + a) * x\n //\n // The position p is x * 256, so after each multiply with p we need to\n // shift right by 8 bits to keep the decimal point in the same place. (The\n // approximation has a negative error near x=1 which helps avoid overflow.)\n const p2 = p * p;\n const u = (c * p2 >> 16) + b;\n const v = (u * p2 >> 16) + a;\n const w = v * p >> 8;\n // The result is within 7/32767 or 0.02%, signal-to-error ratio about 38 dB.\n return position >= 512 ? -w : w;\n }\n\n function sawtoothTone(sound, position, cycle) {\n return (position << 6) - 0x7fff;\n }\n\n function triangleTone(sound, position, cycle) {\n return position < 512 ? (position << 7) - 0x7fff : ((1023 - position) << 7) - 0x7fff;\n }\n\n function squareWaveTone(sound, position, cycle) {\n const wave = instrSoundWave(sound.instructions, sound.currInstr);\n return position < (102 * (wave - SW_SQUARE_10 + 1)) ? -0x7fff : 0x7fff;\n }\n\n let tunedSeed = 0xf01ba80;\n function tunedNoiseTone(sound, position, cycle) {\n // Generate a square wave filtered by a random bit sequence. Since the generator\n // is called multiple times per wave, use PlayingSound state data to ensure we\n // only generate a random bit once per wave, and then reuse it for future\n // calls for that wave.\n //\n // Use the low 6 bits of generatorState to store the last-used cycle, and\n // random_bit to store the last on/off state. (random_bit is arbitrary as\n // long as it isn\'t one of the low 6 bits.)\n const random_bit = 0x8000;\n const prev_cycle = sound.generatorState & 0x3f;\n let is_on;\n if (cycle == prev_cycle) {\n is_on = sound.generatorState & random_bit;\n }\n else {\n // see https://en.wikipedia.org/wiki/Xorshift\n tunedSeed ^= tunedSeed << 13;\n tunedSeed ^= tunedSeed >> 17;\n tunedSeed ^= tunedSeed << 5;\n is_on = (tunedSeed & random_bit);\n sound.generatorState = (cycle & 0x3f) | is_on;\n }\n if (!is_on)\n return 0;\n return position < 512 ? -0x7fff : 0x7fff;\n }\n\n // Bit patterns for use by the cyclic noise tone.\n //\n // The bit pattern is arbitrary, but should have equal numbers of 0 and 1 bits,\n // and should avoid long identical-bit runs for the lower parts. The values below\n // were chosen based on a random permutation of the hex nibbles 0..f and then\n // hand-tweaked by swapping some nibbles. Generated by:\n //\n // shuf -i 0-15 | perl -ne \'s/(d+)/printf("%x",$1)/e\'\n const cycle_bits = [0x2df0eb47, 0xc8165a93];\n const cycle_mask = [0xf, 0x1f, 0x3f];\n\n function cycleNoiseTone(sound, position, cycle) {\n // Generate a square wave filtered by a short-cycle pseudorandom bit sequence.\n // The bit sequence repeats every 16/32/64 waves.\n //\n // The "cycle" argument corresponds to the sequential number of the generated\n // wave. This is currently a 6-bit value. Since the pseudorandom bit sequences\n // evenly fit into this, there\'s no need to track generator state.\n const wave = instrSoundWave(sound.instructions, sound.currInstr);\n const cycle_index = wave - SW_SQUARE_CYCLE_16;\n // CLAMP(0, cycle_index, sizeof cycle_bits / sizeof cycle_bits[0])\n cycle &= cycle_mask[cycle_index];\n const is_on = (cycle_bits[cycle >> 5] & (1 << (cycle & 0x1f)));\n if (!is_on)\n return 0;\n return position < 512 ? -0x7fff : 0x7fff;\n }\n\n function silenceTone(sound, position, cycle) {\n return 0;\n }\n\n function getWaveFn(wave) {\n switch (wave) {\n case SW_TRIANGLE:\n return triangleTone;\n case SW_SAWTOOTH:\n return sawtoothTone;\n case SW_TUNEDNOISE:\n return tunedNoiseTone;\n case SW_NOISE:\n return noiseTone;\n case SW_SINE:\n return sineTone;\n default:\n if (SW_SQUARE_10 <= wave && wave <= SW_SQUARE_50)\n return squareWaveTone;\n if (SW_SQUARE_CYCLE_16 <= wave && wave <= SW_SQUARE_CYCLE_64)\n return cycleNoiseTone;\n else\n return silenceTone;\n }\n }\n\n function fillSamples(dst, numsamples, sounds, sampleRate) {\n const samplesPerMS = (sampleRate << 8) / 1000;\n const toneStepMult = (1024.0 * (1 << 16)) / sampleRate;\n let fn;\n\n for (const snd of sounds) {\n let toneStep = 0;\n let toneDelta = 0;\n let volumeStep = 0;\n let tonePosition = snd.tonePosition;\n let samplesLeft = 0;\n let wave = 0;\n let volume = 0;\n\n snd.currInstr -= 12;\n\n for (let j = 0; j < numsamples; ++j) {\n if (samplesLeft == 0) {\n snd.currInstr += 12;\n if (snd.currInstr >= snd.instructions.length) {\n break;\n }\n // SoundInstruction copy = *snd.currInstr;\n // instr = &copy;\n\n wave = instrSoundWave(snd.instructions, snd.currInstr);\n fn = getWaveFn(wave);\n samplesLeft = (instrDuration(snd.instructions, snd.currInstr) * samplesPerMS >> 8);\n // make sure the division is signed\n volumeStep = Math.floor(((instrEndVolume(snd.instructions, snd.currInstr) - instrStartVolume(snd.instructions, snd.currInstr)) << 16) / samplesLeft);\n if (j == 0 && snd.prevVolume != -1) {\n // restore previous state\n samplesLeft = snd.samplesLeftInCurr;\n volume = snd.prevVolume;\n toneStep = snd.prevToneStep;\n toneDelta = snd.prevToneDelta;\n }\n else {\n // LOG("#sampl %d %p", samplesLeft, snd.currInstr);\n volume = instrStartVolume(snd.instructions, snd.currInstr) << 16;\n // LOG("%d-%dHz %d-%d vol", instr.frequency, instr.endFrequency,\n // instr.startVolume, instr.endVolume);\n toneStep = Math.floor(toneStepMult * instrFrequency(snd.instructions, snd.currInstr));\n if (instrFrequency(snd.instructions, snd.currInstr) != instrEndFrequency(snd.instructions, snd.currInstr)) {\n const endToneStep = (toneStepMult * instrEndFrequency(snd.instructions, snd.currInstr)) | 0;\n toneDelta = ((endToneStep - toneStep) / samplesLeft) | 0;\n }\n else {\n toneDelta = 0;\n }\n }\n }\n let v = fn(snd, (tonePosition >> 16) & 1023, (tonePosition >> 26) & 0xff);\n v = (v * (volume >> 16)) >> (10 + (16 - OUTPUT_BITS));\n // if (v > MAXVAL)\n // target_panic(123);\n for (const output of dst) {\n for (const channel of output) {\n channel[j] = channel[j] + (v / 0xffff);\n }\n }\n // console.log("v", v);\n tonePosition += toneStep;\n toneStep += toneDelta;\n volume += volumeStep;\n samplesLeft--;\n }\n\n if (snd.currInstr >= snd.instructions.length) {\n // snd.sound.state = SoundState::Done;\n // snd.sound = NULL;\n }\n else {\n snd.tonePosition = tonePosition;\n if (samplesLeft == 0)\n samplesLeft++; // avoid infinite loop in next iteration\n snd.samplesLeftInCurr = samplesLeft;\n snd.prevVolume = volume;\n snd.prevToneDelta = toneDelta;\n snd.prevToneStep = toneStep;\n }\n }\n }\n\n class MixerAudioWorkletProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.sounds = [];\n this.port.onmessage = event => {\n if (event.data.type === "play") {\n this.sounds.push({\n startSampleNo: 0,\n samplesLeftInCurr: 0,\n tonePosition: 0,\n prevVolume: -1,\n prevToneStep: 0,\n prevToneDelta: 0,\n generatorState: 0,\n instructions: event.data.instructions,\n currInstr: 0,\n id: event.data.id\n });\n }\n else if (event.data.type === "cancel") {\n this.sounds = this.sounds.filter(s => s.id !== event.data.id);\n }\n };\n }\n\n process(inputs, outputs, parameters) {\n if (this.sounds.length) {\n fillSamples(outputs, outputs[0][0].length, this.sounds, sampleRate);\n\n for (const sound of this.sounds) {\n if (sound.currInstr >= sound.instructions.length) {\n this.port.postMessage({ type: "done", id: sound.id });\n }\n }\n this.sounds = this.sounds.filter(s => s.currInstr < s.instructions.length);\n }\n return true;\n }\n }\n registerProcessor("pxt-mixer-audio-worklet-processor", MixerAudioWorkletProcessor);\n '],{type:"text/javascript"});return URL.createObjectURL(e)}}(pxsim||(pxsim={})),function(e){class t{constructor(e){this.id=e}}e.Button=t;e.ButtonPairState=class{constructor(e){this.props=e,this.usesButtonAB=!1,this.aBtn=new t(this.props.ID_BUTTON_A),this.bBtn=new t(this.props.ID_BUTTON_B),this.abBtn=new t(this.props.ID_BUTTON_AB),this.abBtn.virtual=!0}}}(pxsim||(pxsim={})),function(e){e.CompassState=class{constructor(){this.usesHeading=!1,this.heading=90}}}(pxsim||(pxsim={})),function(e){e.FileSystemState=class{constructor(){this.files={}}append(e,t){this.files[e]=(this.files[e]||"")+t}remove(e){delete this.files[e]}}}(pxsim||(pxsim={})),function(e){e.LightSensorState=class{constructor(){this.usesLightLevel=!1,this.lightLevel=128}}}(pxsim||(pxsim={})),function(e){!function(t){t.mkBoardView=e=>{const n=e.visual;return new t.GenericBoardSvg({visualDef:n,boardDef:e.boardDef,wireframe:e.wireframe})};t.BoardHost=class{constructor(n,s){this.parts=[],this.boardView=n,this.opts=s,s.boardDef.pinStyles||(s.boardDef.pinStyles={}),this.state=s.state;let i=s.partsList,r=0<i.length||s.forceBreadboardLayout;if(r){this.breadboard=new t.Breadboard({wireframe:s.wireframe});const n=s.boardDef.marginWhenBreadboarding||[0,0,40,0],o=t.composeSVG({el1:this.boardView.getView(),scaleUnit1:this.boardView.getPinDist(),el2:this.breadboard.getSVGAndSize(),scaleUnit2:this.breadboard.getPinDist(),margin:[n[0],n[1],20,n[3]],middleMargin:n[2],maxWidth:s.maxWidth,maxHeight:s.maxHeight}),a=o.under,l=o.over;this.view=o.host;const u=o.edges;this.fromMBCoord=o.toHostCoord1,this.fromBBCoord=o.toHostCoord2,this.partGroup=l,this.partOverGroup=e.svg.child(this.view,"g"),this.style=e.svg.child(this.view,"style",{}),this.defs=e.svg.child(this.view,"defs",{}),this.wireFactory=new t.WireFactory(a,l,u,this.style,this.getLocCoord.bind(this),this.getPinStyle.bind(this));const c=e.allocateDefinitions({boardDef:s.boardDef,partDefs:s.partDefs,fnArgs:s.fnArgs,getBBCoord:this.breadboard.getCoord.bind(this.breadboard),partsList:i});c.partsAndWires.length||s.forceBreadboardLayout?(this.addAll(c),c.requiresBreadboard||s.forceBreadboardRender?c.hideBreadboard&&this.breadboard&&this.breadboard.hide():r=!1):r=!1}if(!r){delete this.breadboard,delete this.wireFactory,delete this.partOverGroup,delete this.partGroup,delete this.style,delete this.defs,delete this.fromBBCoord,delete this.fromMBCoord;const t=this.boardView.getView().el;this.view=t,this.partGroup=e.svg.child(this.view,"g"),this.partOverGroup=e.svg.child(this.view,"g"),s.maxWidth&&e.svg.hydrate(this.view,{width:s.maxWidth}),s.maxHeight&&e.svg.hydrate(this.view,{height:s.maxHeight})}this.state.updateSubscribers.push(()=>this.updateState())}highlightBoardPin(e){this.boardView.highlightPin(e)}removeEventListeners(){this.boardView.removeEventListeners&&this.boardView.removeEventListeners()}highlightBreadboardPin(e){this.breadboard.highlightLoc(e)}highlightWire(t){t.wires.forEach(t=>{e.U.addClass(t,"highlight"),t.style.visibility="visible"}),e.U.addClass(t.endG,"highlight")}getView(){return this.view}screenshotAsync(t){const n=this.view.classList.contains("sim")?this.view:this.view.querySelector(".sim"),s=n?n.cloneNode(!0):this.view.cloneNode(!0);s.setAttribute("width",s.viewBox.baseVal.width+""),s.setAttribute("height",s.viewBox.baseVal.height+"");const i=(new XMLSerializer).serializeToString(s),r="data:image/svg+xml,"+encodeURIComponent(i.replace(/\s+/g," ").replace(/"/g,"'"));return new Promise((n,s)=>{const i=document.createElement("img");i.onload=()=>{const e=document.createElement("canvas");e.width=i.width,e.height=i.height,t>0?(e.width=t,e.height=i.height*t/i.width|0):e.width<200?(e.width*=2,e.height*=2):e.width>480&&(e.width/=2,e.height/=2);const s=e.getContext("2d");s.drawImage(i,0,0,e.width,e.height),n(s.getImageData(0,0,e.width,e.height))},i.onerror=t=>{e.log(t),n(void 0)},i.src=r})}updateState(){this.parts.forEach(e=>e.updateState())}getBBCoord(e){let t=this.breadboard.getCoord(e);return this.fromBBCoord(t)}getPinCoord(t){let n=this.boardView.getCoord(t);if(n)return this.fromMBCoord(n);e.error(`Unable to find coord for pin: ${t}`)}getLocCoord(t){let n;if("breadboard"===t.type){let e=t;n=this.getBBCoord(e)}else{let e=t.pin;n=this.getPinCoord(e)}return n||e.debug("Unknown location: "+name),n}getPinStyle(e){return"breadboard"==e.type?"female":this.opts.boardDef.pinStyles[e.pin]||"female"}addPart(n){let s=null;if(n.simulationBehavior){let e=n.simulationBehavior,t=this.state.builtinVisuals[e],i=this.state.builtinParts[e];s=t(),s.init(this.state.bus,i,this.view,n.params)}else{let e=n.visual;s=new t.GenericPart(e)}this.parts.push(s),this.partGroup.appendChild(s.element),s.overElement&&this.partOverGroup.appendChild(s.overElement),s.defs&&s.defs.forEach(e=>this.defs.appendChild(e)),this.style.textContent+=s.style||"";let i=n.startColumnIdx,r=n.startRowIdx,o={type:"breadboard",row:t.getRowName(r),col:t.getColumnName(i),xOffset:n.bbFit.xOffset/n.visual.pinDistance,yOffset:n.bbFit.yOffset/n.visual.pinDistance},a=this.getBBCoord(o);s.moveToCoord(a);let l=`sim-${n.name}-cmp`;return e.U.addClass(s.element,l),e.U.addClass(s.element,"sim-cmp"),s.updateTheme(),s.updateState(),s}addWire(e){return this.wireFactory.addWire(e.start,e.end,e.color)}addAll(e){e.partsAndWires.forEach(t=>{const n=t.wires,s=n&&n.every(e=>this.wireFactory.checkWire(e.start,e.end));s&&n.forEach(t=>e.wires.push(this.addWire(t)));let i=t.part;!i||n&&!s||e.parts.push(this.addPart(i))}),e.requiresBreadboard=!!e.wires.length||!!e.parts.length}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){!function(t){const n=15,s="#1AA5D7",i="#DD4BA0",r=`\n /* bread board */\n .sim-bb-background {\n fill:#E0E0E0;\n }\n .sim-bb-pin {\n fill:#999;\n }\n .sim-bb-pin-hover {\n visibility: hidden;\n pointer-events: all;\n stroke-width: 7.5px;\n stroke: transparent;\n fill: #777;\n }\n .sim-bb-pin-hover:hover {\n visibility: visible;\n fill:#444;\n }\n .sim-bb-group-wire {\n stroke: #999;\n stroke-width: 3.75px;\n visibility: hidden;\n }\n .sim-bb-pin-group {\n pointer-events: all;\n }\n .sim-bb-label,\n .sim-bb-label-hover {\n font-family:"Lucida Console", Monaco, monospace;\n fill:#555;\n pointer-events: all;\n stroke-width: 0;\n cursor: default;\n }\n .sim-bb-label-hover {\n visibility: hidden;\n fill:#000;\n font-weight: bold;\n }\n .sim-bb-bar {\n stroke-width: 0;\n }\n .sim-bb-blue {\n fill:${s};\n stroke:${s}\n }\n .sim-bb-red {\n fill:${i};\n stroke:${i};\n }\n .sim-bb-pin-group:hover .sim-bb-pin-hover,\n .sim-bb-pin-group:hover .sim-bb-group-wire,\n .sim-bb-pin-group:hover .sim-bb-label-hover {\n visibility: visible;\n }\n .sim-bb-pin-group:hover .sim-bb-label {\n visibility: hidden;\n }\n /* outline mode */\n .sim-bb-outline .sim-bb-background {\n stroke-width: ${n/7}px;\n fill: #FFF;\n stroke: #000;\n }\n .sim-bb-outline .sim-bb-mid-channel {\n fill: #FFF;\n stroke: #888;\n stroke-width: 2px;\n }\n /* grayed out */\n .grayed .sim-bb-background {\n stroke-width: 3px;\n }\n .grayed .sim-bb-red,\n .grayed .sim-bb-blue {\n fill: #BBB;\n }\n .grayed .sim-bb-bar {\n fill: #FFF;\n }\n .grayed .sim-bb-pin {\n fill: #000;\n stroke: #FFF;\n stroke-width: 3px;\n }\n .grayed .sim-bb-label {\n fill: none;\n }\n .grayed .sim-bb-background {\n stroke-width: 7.5px;\n stroke: #555;\n }\n .grayed .sim-bb-group-wire {\n stroke: #DDD;\n }\n .grayed .sim-bb-channel {\n visibility: hidden;\n }\n /* highlighted */\n .sim-bb-label.highlight {\n visibility: hidden;\n }\n .sim-bb-label-hover.highlight {\n visibility: visible;\n }\n .sim-bb-blue.highlight {\n fill:${s};\n }\n .sim-bb-red.highlight {\n fill:${i};\n }\n .sim-bb-bar.highlight {\n stroke-width: 0px;\n }\n `;t.BREADBOARD_MID_ROWS=10,t.BREADBOARD_MID_COLS=30;const o=[4,4],a=t.BREADBOARD_MID_ROWS+o.length,l=25,u=[4,9,14,19],c=l+u.length,h=n*(t.BREADBOARD_MID_COLS+3),d=n*(a+4+5.5),p=2/3,f=d*p,m=d*(.5*(1-p)),g=(t.BREADBOARD_MID_COLS-1)*n,b=(h-g)/2,v=m+(f-(a-1)*n)/2,y=(c-1)*n,S=(h-y)/2,w=(m-15)/2,x=S,E=w+m+f,I=25.5,k=12,C=1.05,R=-90,T="abcdefghij".split("").reverse();function _(e){return`${e+1}`}function A(e){return T[e]}function P(t){let n=t.xOffset||0,s=t.yOffset||0,i=[],r=e.svg.elt("g"),o=t.colStartIdx||0,a=t.rowStartIdx||0,l=e=>e?e.slice(0,e.length):[],u=(e,t)=>{let n,s=0;for(;0<=(n=e.indexOf(t));)e.splice(n,1),s+=1;return s},c=0,h=l(t.rowIdxsWithGap);for(let d=0;d<t.rowCount;d++){let p=0,f=l(t.colIdxsWithGap),m=s+d*t.pinDist+c*t.pinDist,g=d+a;for(let s=0;s<t.colCount;s++){let a=n+s*t.pinDist+p*t.pinDist,l=s+o;const c=t=>(e.svg.hydrate(t.el,"circle"==t.el.tagName?{cx:a,cy:m}:{x:a-.5*t.w,y:m-.5*t.h}),r.appendChild(t.el),t.el);let h=c(t.mkPin()),d=c(t.mkHoverPin()),b=t.getRowName(g),v=t.getColName(l),y=t.getGroupName?t.getGroupName(g,l):null,S={el:h,hoverEl:d,cx:a,cy:m,row:b,col:v,group:y};i.push(S),p+=u(f,l)}c+=u(h,g)}return{g:r,allPins:i}}function M(){let t=e.svg.elt("rect");return e.svg.hydrate(t,{class:"sim-bb-pin",rx:2,ry:2,width:6,height:6}),{el:t,w:6,h:6,x:0,y:0}}function D(){let t=e.svg.elt("rect"),n=6*1.3;return e.svg.hydrate(t,{class:"sim-bb-pin-hover",rx:2,ry:2,width:n,height:n}),{el:t,w:n,h:n,x:0,y:0}}function B(n,s,i,r,o,a,l){let u=t.mkTxt(n,s,i,r,o);e.U.addClass(u,"sim-bb-label"),l&&l.forEach(t=>e.U.addClass(u,t));let c=t.mkTxt(n,s,1.3*i,r,o);return e.U.addClass(c,"sim-bb-label-hover"),l&&l.forEach(t=>e.U.addClass(c,t)),{el:u,hoverEl:c,txt:o,group:a}}t.getColumnName=_,t.getRowName=A,t.mkGrid=P;t.Breadboard=class{constructor(t){this.allPins=[],this.allLabels=[],this.allPowerBars=[],this.rowColToPin={},this.rowColToLbls={},this.buildDom(),t.wireframe&&e.U.addClass(this.bb,"sim-bb-outline")}hide(){this.bb.style.display="none"}updateLocation(t,n){e.svg.hydrate(this.bb,{x:`${t}px`,y:`${n}px`})}getPin(e,t){let n=this.rowColToPin[e];if(!n)return null;let s=n[t];return s||null}getCoord(e){let{row:t,col:s,xOffset:i,yOffset:r}=e,o=this.getPin(t,s);if(!o)return null;let a=(i||0)*n,l=(r||0)*n;return[o.cx+a,o.cy+l]}getPinDist(){return n}buildDom(){this.bb=e.svg.elt("svg",{version:"1.0",viewBox:`0 0 ${h} ${d}`,class:"sim-bb",width:h+"px",height:d+"px"}),this.styleEl=e.svg.child(this.bb,"style",{}),this.styleEl.textContent+=r,this.defs=e.svg.child(this.bb,"defs",{}),e.svg.child(this.bb,"rect",{class:"sim-bb-background",width:h,height:d,rx:4.5,ry:4.5});let s="sim-bb-channel-grad",i=e.svg.elt("linearGradient");e.svg.hydrate(i,{id:s,x1:"0%",y1:"0%",x2:"0%",y2:"100%"}),this.defs.appendChild(i);let a="#AAA",c="#CCC";e.svg.child(i,"stop",{offset:"0%",style:`stop-color: ${a};`}),e.svg.child(i,"stop",{offset:"20%",style:`stop-color: ${c};`}),e.svg.child(i,"stop",{offset:"80%",style:`stop-color: ${c};`}),e.svg.child(i,"stop",{offset:"100%",style:`stop-color: ${a};`});const p=(t,n,i)=>{let r=e.svg.child(this.bb,"rect",{class:`sim-bb-channel ${i||""}`,y:t-n/2,width:h,height:n});return r.setAttribute("fill",`url(#${s})`),r};p(m+f/2,15,"sim-bb-mid-channel"),p(m,.75,"sim-bb-sml-channel"),p(m+f,.75,"sim-bb-sml-channel");const g=(e,n)=>{let s=(e=>e<t.BREADBOARD_MID_ROWS/2?"b":"t")(e);return`${s}${_(n)}`},T=e=>0===e?"-":"+",L=(e,t)=>{let n=(e=>e<25?"b":"t")(t);return`${T(e)}${n}`};let F=P({xOffset:b,yOffset:v,rowCount:t.BREADBOARD_MID_ROWS,colCount:t.BREADBOARD_MID_COLS,pinDist:n,mkPin:M,mkHoverPin:D,getRowName:A,getColName:_,getGroupName:g,rowIdxsWithGap:o});F.g;this.allPins=this.allPins.concat(F.allPins);let O=P({xOffset:x,yOffset:E,rowCount:2,colCount:l,pinDist:n,mkPin:M,mkHoverPin:D,getRowName:T,getColName:_,getGroupName:L,colIdxsWithGap:u});O.g;this.allPins=this.allPins.concat(O.allPins);let U=P({xOffset:S,yOffset:w,rowCount:2,colCount:l,colStartIdx:l,pinDist:n,mkPin:M,mkHoverPin:D,getRowName:T,getColName:_,getGroupName:L,colIdxsWithGap:u.map(e=>e+l)});U.g;this.allPins=this.allPins.concat(U.allPins),this.allPins.forEach(t=>{let{el:n,row:s,col:i,hoverEl:r}=t,o=`(${s},${i})`;e.svg.hydrate(n,{title:o}),e.svg.hydrate(r,{title:o})}),this.allPins.forEach(e=>{let t=this.rowColToPin[e.row];t||(t=this.rowColToPin[e.row]={}),t[e.col]=e});const V=(e,t,n,s,i,r)=>{let o=this.getCoord({type:"breadboard",row:e,col:t}),[a,l]=o;return B(a+n,l+s,10.5,-90,i,r)};for(let e=0;e<t.BREADBOARD_MID_COLS;e++){let n=_(e),s=0,i=V(A(s),n,0,-15,n,g(s,e));this.allLabels.push(i);let r=t.BREADBOARD_MID_ROWS-1,o=V(A(r),n,0,15,n,g(r,e));this.allLabels.push(o)}for(let e=0;e<t.BREADBOARD_MID_ROWS;e++){let n=A(e),s=V(n,_(0),-15,0,n);this.allLabels.push(s);let i=V(n,_(t.BREADBOARD_MID_COLS-1),15,0,n);this.allLabels.push(i)}let N=[B(13.05,m+f+k,30,R,"-",L(0,0),["sim-bb-blue"]),B(12,m+f+m-k,I,R,"+",L(1,0),["sim-bb-red"]),B(h-k+C,m+f+k,30,R,"-",L(0,24),["sim-bb-blue"]),B(h-k,m+f+m-k,I,R,"+",L(1,24),["sim-bb-red"])];this.allLabels=this.allLabels.concat(N);let q=[B(13.05,12,30,R,"-",L(0,l),["sim-bb-blue"]),B(12,m-k,I,R,"+",L(1,l),["sim-bb-red"]),B(h-k+C,12,30,R,"-",L(0,49),["sim-bb-blue"]),B(h-k,m-k,I,R,"+",L(1,49),["sim-bb-red"])];this.allLabels=this.allLabels.concat(q);let W={};this.allLabels.forEach(e=>{let{el:t,txt:n}=e;(W[n]=W[n]||[]).push(e)});this.allPins.forEach(e=>{let{row:t,col:n,group:s}=e,i=this.rowColToLbls[t]||(this.rowColToLbls[t]={}),r=i[n]||(i[n]=[]);if((e=>"-"===e.row||"+"===e.row)(e)){Number(n)<=l?N.filter(t=>t.group==e.group).forEach(e=>r.push(e)):q.filter(t=>t.group==e.group).forEach(e=>r.push(e))}else{W[t].forEach(e=>r.push(e)),W[n].forEach(e=>r.push(e))}});const $=y+22.5,G=($-y)/2,j=(t,n,s,i)=>{let r=e.svg.elt("rect");return e.svg.hydrate(r,{class:`sim-bb-bar ${i}`,x:t,y:n-1.5,width:$,height:3}),{el:r,group:s}};let z=[j(x-G,E-9,L(0,49),"sim-bb-blue"),j(x-G,E+n+9,L(1,49),"sim-bb-red"),j(S-G,w-9,L(0,0),"sim-bb-blue"),j(S-G,w+n+9,L(1,0),"sim-bb-red")];this.allPowerBars=this.allPowerBars.concat(z),this.allPowerBars.forEach(e=>this.bb.appendChild(e.el));let H=this.allPins.map(e=>e.group).filter((e,t,n)=>n.indexOf(e)==t),Y=H.map(t=>e.svg.elt("g"));Y.forEach(t=>e.U.addClass(t,"sim-bb-pin-group")),Y.forEach((t,n)=>e.U.addClass(t,`group-${H[n]}`));let J={};H.forEach((e,t)=>J[e]=Y[t]);let Z={};this.allPins.forEach((e,t)=>{let n=e.group;(Z[n]||(Z[n]=[])).push(e)}),H.forEach(t=>{let n=Z[t],[s,i]=[n.map(e=>e.cx),n.map(e=>e.cy)],r=e=>e.reduce((e,t)=>e<t?e:t),o=e=>e.reduce((e,t)=>e>t?e:t),[a,l,u,c]=[r(s),o(s),r(i),o(i)],h=e.svg.elt("rect"),d=Math.max(l-a,1e-4),p=Math.max(c-u,1e-4);e.svg.hydrate(h,{x:a,y:u,width:d,height:p}),e.U.addClass(h,"sim-bb-group-wire"),J[t].appendChild(h)}),this.allPins.forEach(e=>{let t=J[e.group];t.appendChild(e.el),t.appendChild(e.hoverEl)});let Q=e.svg.elt("g");e.svg.hydrate(Q,{class:"sim-bb-group-misc"}),Y.push(Q),this.allLabels.forEach(e=>{if(e.group){let t=J[e.group];t.appendChild(e.el),t.appendChild(e.hoverEl)}else Q.appendChild(e.el),Q.appendChild(e.hoverEl)}),Y.forEach(e=>this.bb.appendChild(e))}getSVGAndSize(){return{el:this.bb,y:0,x:0,w:h,h:d}}highlightLoc(t){let{row:n,col:s}=t,i=this.rowColToPin[n][s],{cx:r,cy:o}=i;this.rowColToLbls[n][s].forEach(t=>{e.U.addClass(t.el,"highlight"),e.U.addClass(t.hoverEl,"highlight")})}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){!function(t){t.BOARD_SYTLE=`\n .noselect {\n -webkit-touch-callout: none; /* iOS Safari */\n -webkit-user-select: none; /* Chrome/Safari/Opera */\n -khtml-user-select: none; /* Konqueror */\n -moz-user-select: none; /* Firefox */\n -ms-user-select: none; /* Internet Explorer/Microsoft Edge */\n user-select: none; /* Non-prefixed version, currently\n not supported by any browser */\n }\n\n .sim-board-pin {\n fill:#999;\n stroke:#000;\n stroke-width:${t.PIN_DIST/3}px;\n }\n .sim-board-pin-lbl {\n fill: #333;\n }\n .gray-cover {\n fill:#FFF;\n opacity: 0.3;\n stroke-width:0;\n visibility: hidden;\n }\n .sim-board-pin-hover {\n visibility: hidden;\n pointer-events: all;\n stroke-width:${t.PIN_DIST/6}px;\n }\n .sim-board-pin-hover:hover {\n visibility: visible;\n }\n .sim-board-pin-lbl {\n visibility: hidden;\n }\n .sim-board-outline .sim-board-pin-lbl {\n visibility: visible;\n }\n .sim-board-pin-lbl {\n fill: #555;\n }\n .sim-board-pin-lbl-hover {\n fill: red;\n }\n .sim-board-outline .sim-board-pin-lbl-hover {\n fill: black;\n }\n .sim-board-pin-lbl,\n .sim-board-pin-lbl-hover {\n font-family:"Lucida Console", Monaco, monospace;\n pointer-events: all;\n stroke-width: 0;\n }\n .sim-board-pin-lbl-hover {\n visibility: hidden;\n }\n .sim-board-outline .sim-board-pin-hover:hover + .sim-board-pin-lbl,\n .sim-board-pin-lbl.highlight {\n visibility: hidden;\n }\n .sim-board-outline .sim-board-pin-hover:hover + * + .sim-board-pin-lbl-hover,\n .sim-board-pin-lbl-hover.highlight {\n visibility: visible;\n }\n /* Graying out */\n .grayed .sim-board-pin-lbl:not(.highlight) {\n fill: #AAA;\n }\n .grayed .sim-board-pin:not(.highlight) {\n fill:#BBB;\n stroke:#777;\n }\n .grayed .gray-cover {\n visibility: inherit;\n }\n .grayed .sim-cmp:not(.notgrayed) {\n opacity: 0.3;\n }\n /* Highlighting */\n .sim-board-pin-lbl.highlight {\n fill: #000;\n font-weight: bold;\n }\n .sim-board-pin.highlight {\n fill:#999;\n stroke:#000;\n }\n `;const n=.7*t.PIN_DIST,s=1.5*n,i=.66666*t.PIN_DIST,r=.66666*t.PIN_DIST+t.PIN_DIST/3;let o=0;t.GenericBoardSvg=class{constructor(a){this.props=a,this.allPins=[],this.allLabels=[],this.pinNmToLbl={},this.pinNmToPin={},this.id=o++;let l=a.visualDef,u=a.wireframe&&l.outlineImage?l.outlineImage:l.image,c=t.mkImageSVG({image:u,width:l.width,height:l.height,imageUnitDist:l.pinDist,targetUnitDist:t.PIN_DIST}),h=t.mkScaleFn(l.pinDist,t.PIN_DIST);this.width=c.w,this.height=c.h;let d=c.el;this.element=e.svg.elt("svg"),e.svg.hydrate(this.element,{version:"1.0",viewBox:`0 0 ${this.width} ${this.height}`,class:`sim sim-board-id-${this.id}`,x:"0px",y:"0px"}),a.wireframe&&e.U.addClass(this.element,"sim-board-outline"),this.style=e.svg.child(this.element,"style",{}),this.style.textContent+=t.BOARD_SYTLE,this.defs=e.svg.child(this.element,"defs",{}),this.g=e.svg.elt("g"),this.element.appendChild(this.g),this.g.appendChild(d),this.background=d,e.svg.hydrate(d,{class:"sim-board"});const p=()=>{let t=e.svg.elt("circle"),n=i;return e.svg.hydrate(t,{class:"sim-board-pin",r:n/2}),{el:t,w:n,h:n,x:0,y:0}},f=()=>{let t=e.svg.elt("circle"),n=r;return e.svg.hydrate(t,{class:"sim-board-pin-hover",r:n/2}),{el:t,w:n,h:n,x:0,y:0}},m=()=>{let t=e.svg.elt("rect"),n=i;return e.svg.hydrate(t,{class:"sim-board-pin",width:n,height:n}),{el:t,w:n,h:n,x:0,y:0}},g=()=>{let t=e.svg.elt("rect"),n=r;return e.svg.hydrate(t,{class:"sim-board-pin-hover",width:n,height:n}),{el:t,w:n,h:n,x:0,y:0}};let b=l.pinBlocks.map((n,s)=>{let i=h(n.x)+t.PIN_DIST/2,r=h(n.y)+t.PIN_DIST/2,o=n.labels.length,a=t.mkGrid({xOffset:i,yOffset:r,rowCount:1,colCount:o,pinDist:t.PIN_DIST,mkPin:l.useCrocClips?p:m,mkHoverPin:l.useCrocClips?f:g,getRowName:()=>`${s+1}`,getColName:e=>n.labels[e],getGroupName:()=>n.labels.join(" ")});a.allPins,a.g;return e.U.addClass(a.g,"sim-board-pin-group"),a}),v=[];b.forEach((e,t)=>e.allPins.forEach((e,n)=>{this.allPins.push(e),v.push(l.pinBlocks[t])})),this.allPins.forEach(t=>{let n=t.col;e.svg.hydrate(t.el,{title:n}),e.svg.hydrate(t.hoverEl,{title:n})}),this.allPins.forEach(e=>{this.pinNmToPin[e.col]=e});const y=(e,n,s,i,r)=>{let o,a;if("below"===r){a=e,o=n+12+.25*s*i.length}else{a=e,o=n-11-.32*s*i.length}return t.mkTxt(a,o,s,-90,i)};this.allLabels=this.allPins.map((t,i)=>{let r=v[i];return((t,i,r,o)=>{let a=y(t,i,n,r,o);e.U.addClass(a,"sim-board-pin-lbl");let l=y(t,i,s,r,o);return e.U.addClass(l,"sim-board-pin-lbl-hover"),{el:a,hoverEl:l,txt:r}})(t.cx,t.cy,t.col,r.labelPosition||"above")}),this.allPins.forEach((e,t)=>{let n=this.allLabels[t];this.pinNmToLbl[e.col]=n}),this.allPins.forEach((e,t)=>{let n=this.allLabels[t];this.g.appendChild(e.el),this.g.appendChild(e.hoverEl),this.g.appendChild(n.el),this.g.appendChild(n.hoverEl)})}findPin(e){let t=this.pinNmToPin[e];return!t&&this.props.boardDef.gpioPinMap&&(e=this.props.boardDef.gpioPinMap[e])&&(t=this.pinNmToPin[e]),t}findPinLabel(e){let t=this.pinNmToLbl[e];return!t&&this.props.boardDef.gpioPinMap&&(e=this.props.boardDef.gpioPinMap[e])&&(t=this.pinNmToLbl[e]),t}getCoord(e){let t=this.findPin(e);return t?[t.cx,t.cy]:null}mkGrayCover(t,n,s,i){let r=e.svg.elt("rect");return e.svg.hydrate(r,{x:t,y:n,width:s,height:i,class:"gray-cover"}),r}getView(){return{el:this.element,w:this.width,h:this.height,x:0,y:0}}getPinDist(){return t.PIN_DIST}highlightPin(t){let n=this.findPinLabel(t),s=this.findPin(t);n&&s&&(e.U.addClass(n.el,"highlight"),e.U.addClass(n.hoverEl,"highlight"),e.U.addClass(s.el,"highlight"),e.U.addClass(s.hoverEl,"highlight"))}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){!function(t){function n(e){return t.mkImageSVG({image:e.image,width:e.width,height:e.height,imageUnitDist:e.pinDistance,targetUnitDist:t.PIN_DIST})}t.mkGenericPartSVG=n;t.GenericPart=class{constructor(t){this.style="",this.defs=[];let s=n(t).el;this.element=e.svg.elt("g"),this.element.appendChild(s)}moveToCoord(e){t.translateEl(this.element,e)}init(e,t,n){}updateState(){}updateTheme(){}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){!function(t){const n=t.PIN_DIST/2.5,s=.7;function i(e){return e.replace(/\#/g,"-").replace(/\(/g,"-").replace(/\)/g,"-").replace(/\,/g,"-").replace(/\./g,"-").replace(/\s/g,"")}let r;function o(t,n,s,i){const r=e=>`${e[0]}, ${e[1]}`;let[o,a]=t,[l,u]=n,c=u-a,h=[o,a+c*s],d=[l,u-c*s],p=e.svg.mkPath("sim-bb-wire",`M${r(t)} C${r(h)} ${r(d)} ${r(n)}`);return e.U.addClass(p,`wire-stroke-${i}`),p}function a(t,n,s){const i=e=>`${e[0]}, ${e[1]}`;let r=e.svg.mkPath("sim-bb-wire",`M${i(t)} L${i(n)}`);return e.U.addClass(r,`wire-stroke-${s}`),r}function l(s,i){const r=t.PIN_DIST/4;let o=e.svg.elt("circle"),a=s[0],l=s[1],u=n/2+r/2;return e.svg.hydrate(o,{cx:a,cy:l,r:u,class:"sim-bb-wire-end"}),e.U.addClass(o,`wire-fill-${i}`),o.style["stroke-width"]=`${r}px`,o}function u(n,s,i){let r=.24*t.PIN_DIST,o=10*r,a=2*r,l=6*r,u=r;const c=t.PIN_DIST/4;let[h,d]=n,p=s?-1:1,f=e.svg.elt("g"),m=e.svg.elt("rect"),g=o,b=a,v=h-b/2,y=d-g/2;e.svg.hydrate(m,{x:v,y:y,width:b,height:g,rx:.5,ry:.5,class:"sim-bb-wire-end"}),m.style["stroke-width"]=`${c}px`;let S=e.svg.elt("rect"),w=l,x=u,E=h-x/2,I=d+p*(g/2+w/2)-w/2;return e.svg.hydrate(S,{x:E,y:I,width:x,height:w,class:"sim-bb-wire-bare-end"}),S.style.fill="#bbb",f.appendChild(S),f.appendChild(m),{el:f,x:v-c,y:Math.min(y,I),w:b+2*c,h:g+w}}function c(n,s,i){let r=.24*t.PIN_DIST;const o=4*r,a=10*r,l=3.5*r,u=3.5*r,c=t.PIN_DIST/4;let[h,d]=n,p=s?-1:1,f=e.svg.elt("g"),m=e.svg.elt("polygon"),g=a,b=o,v=h-b/2,y=d-g/2;const S=s?.15:.3,w=s?.7:1-.7,x=s?.3:.15;e.svg.hydrate(m,{points:((...e)=>e.map(e=>(e=>`${e[0]},${e[1]}`)(e)).join(" "))([v+b*S,y],[v+b*(1-S),y],[v+b,y+g*w],[v+b*(1-x),y+g],[v+b*x,y+g],[v,y+g*w])}),e.svg.hydrate(m,{rx:.5,ry:.5,class:"sim-bb-wire-end"}),m.style["stroke-width"]=`${c}px`;let E=e.svg.elt("rect"),I=l,k=u,C=h-k/2,R=d+p*(g/2+I/2)-I/2;return e.svg.hydrate(E,{x:C,y:R,width:k,height:I,class:"sim-bb-wire-bare-end"}),f.appendChild(E),f.appendChild(m),{el:f,x:v-c,y:Math.min(y,R),w:b+2*c,h:g+I}}t.WIRES_CSS=`\n .sim-bb-wire {\n fill:none;\n stroke-linecap: round;\n stroke-width:${n}px;\n pointer-events: none;\n }\n .sim-bb-wire-end {\n stroke:#333;\n fill:#333;\n }\n .sim-bb-wire-bare-end {\n fill: #ccc;\n }\n .sim-bb-wire-hover {\n stroke-width: ${n}px;\n visibility: hidden;\n stroke-dasharray: ${t.PIN_DIST/10},${t.PIN_DIST/1.5};\n /*stroke-opacity: 0.4;*/\n }\n .grayed .sim-bb-wire-ends-g:not(.highlight) .sim-bb-wire-end {\n stroke: #777;\n fill: #777;\n }\n .grayed .sim-bb-wire:not(.highlight) {\n stroke: #CCC;\n }\n .sim-bb-wire-ends-g:hover .sim-bb-wire-end {\n stroke: red;\n fill: red;\n }\n .sim-bb-wire-ends-g:hover .sim-bb-wire-bare-end {\n stroke: #FFF;\n fill: #FFF;\n }\n `,function(e){e[e.BBJumper=0]="BBJumper",e[e.OpenJumper=1]="OpenJumper",e[e.Croc=2]="Croc"}(r=t.WireEndStyle||(t.WireEndStyle={})),t.mkWirePart=function(n,s,i=!1){let r,o=e.svg.elt("g"),[a,l]=n,h=[a-15,l-50],d=[a+15,l+50];s=t.mapWireColor(s),r=i?c(h,!0,s):u(h,!0,s);let p=function(t,n,s){const i=e=>`${e[0]}, ${e[1]}`;let[r,o]=t,[a,l]=n,u=l-o,c=[r,o+.8*u],h=[a,l-.8*u],d=e.svg.mkPath("sim-bb-wire",`M${i(t)} C${i(c)} ${i(h)} ${i(n)}`);return d.style.stroke=s,{el:d,x:Math.min(r,a),y:Math.min(o,l),w:Math.abs(r-a),h:Math.abs(o-l)}}(h,d,s),f=u(d,!1,s);o.appendChild(p.el),o.appendChild(r.el),o.appendChild(f.el);let m=Math.min(r.x,f.x),g=Math.max(r.x+r.w,f.x+f.w),b=Math.min(r.y,f.y);return{el:o,x:m,y:b,w:g-m,h:Math.max(r.y+r.h,f.y+f.h)-b}};t.WireFactory=class{constructor(e,n,s,i,r,o){this.nextWireId=0,this.styleEl=i,this.styleEl.textContent+=t.WIRES_CSS,this.underboard=e,this.overboard=n,this.boardEdges=s,this.getLocCoord=r,this.getPinStyle=o}indexOfMin(e){let t=0,n=e[0];for(let s=1;s<e.length;s++)e[s]<n&&(n=e[s],t=s);return t}closestEdgeIdx(e){let t=this.boardEdges.map(t=>Math.abs(e[1]-t));return this.indexOfMin(t)}closestEdge(e){return this.boardEdges[this.closestEdgeIdx(e)]}drawWire(n,r,u){let c=[],h=e.svg.child(this.overboard,"g",{class:"sim-bb-wire-group"});const d=e=>{const n=t.PIN_DIST/2;let s,i=this.closestEdge(e);return s=i-e[1]<0?i-n:i+n,[e[0],s]};let p=this.nextWireId++,f=i(u),m=l(n,f),g=l(r,f),b=e.svg.child(h,"g",{class:"sim-bb-wire-ends-g"});b.appendChild(m),b.appendChild(g);let v=this.closestEdgeIdx(n),y=this.closestEdgeIdx(r);if(v==y){let e=a(n,r,f);h.appendChild(e),c.push(e)}else{let t,i,l=d(n),u=d(r),m=a(n,l,f),g=a(r,u,f);!(1!=v&&2!=v||1!=y&&2!=y)?(t=o(l,u,s,f),i=o(l,u,s,f)):(t=a(l,u,f),i=a(l,u,f)),e.U.addClass(i,"sim-bb-wire-hover"),h.appendChild(m),c.push(m),h.appendChild(g),c.push(g),this.underboard.appendChild(t),c.push(t),h.appendChild(i),c.push(i);let S=`sim-bb-wire-id-${p}`;const w=t=>e.U.addClass(t,S);w(b),w(i),this.styleEl.textContent+=`\n .${S}:hover ~ .${S}.sim-bb-wire-hover {\n visibility: visible;\n }`}let S=`\n .wire-stroke-${f} {\n stroke: ${t.mapWireColor(u)};\n }\n .wire-fill-${f} {\n fill: ${t.mapWireColor(u)};\n }\n `;return this.styleEl.textContent+=S,{endG:b,end1:m,end2:g,wires:c}}drawWireWithCrocs(n,r,u,h=!1){let d=[],p=e.svg.child(this.overboard,"g",{class:"sim-bb-wire-group"});const f=e=>{const n=t.PIN_DIST/2;let s,i=this.closestEdge(e);return s=i-e[1]<0?i-n:i+n,[e[0],s]};let m=this.nextWireId++,g=i(u),b=l(n,g),v=r,[y,S]=r;r=[y,S+40],[y,S]=r;let w,x=[y,S+-17];w=h?function(n,s){let i=.24*t.PIN_DIST,r=4*i,o=1.2*i,a=10*i,l=i;const u=t.PIN_DIST/4;let[c,h]=n,d=s?-1:1,p=e.svg.elt("g"),f=e.svg.elt("rect"),m=r,g=o,b=c-g/2,v=h+10-m/2;e.svg.hydrate(f,{x:b,y:v,width:g,height:m,rx:.5,ry:.5,class:"sim-bb-wire-end"}),f.style["stroke-width"]=`${u}px`;let y=e.svg.elt("rect"),S=a,w=l,x=c-w/2,E=h+10+d*(m/2+S/2)-S/2;return e.svg.hydrate(y,{x:x,y:E,width:w,height:S,class:"sim-bb-wire-bare-end"}),y.style.fill="#bbb",p.appendChild(y),p.appendChild(f),{el:p,x:b-u,y:Math.min(v,E),w:g+2*u,h:m+S}}(x,!0):c(x,!0);let E=w.el,I=e.svg.child(p,"g",{class:"sim-bb-wire-ends-g"});I.appendChild(b);let k=this.closestEdgeIdx(n),C=this.closestEdgeIdx(v);if(k==C){let e=a(n,r,g);p.appendChild(e),d.push(e)}else{let t,i,l=f(n),u=a(n,l,g);!(1!=k&&2!=k||1!=C&&2!=C)?(t=o(l,r,s,g),i=o(l,r,s,g)):(t=a(l,r,g),i=a(l,r,g)),e.U.addClass(i,"sim-bb-wire-hover"),p.appendChild(u),d.push(u),this.underboard.appendChild(t),d.push(t);let c=`sim-bb-wire-id-${m}`;const h=t=>e.U.addClass(t,c);h(I),h(i),this.styleEl.textContent+=`\n .${c}:hover ~ .${c}.sim-bb-wire-hover {\n visibility: visible;\n }`}I.appendChild(E);let R=`\n .wire-stroke-${g} {\n stroke: ${t.mapWireColor(u)};\n }\n .wire-fill-${g} {\n fill: ${t.mapWireColor(u)};\n }\n `;return this.styleEl.textContent+=R,{endG:I,end1:b,end2:E,wires:d}}checkWire(e,t){let n=this.getLocCoord(e),s=this.getLocCoord(t);return!!n&&!!s}addWire(t,n,s){let i=this.getLocCoord(t),r=this.getLocCoord(n);if(!i||!r)return void e.debug(`unable to allocate wire for ${t} or ${n}`);let o,a=this.getPinStyle(n);return o="dalboard"==n.type&&"croc"==a?this.drawWireWithCrocs(i,r,s):this.drawWire(i,r,s),o}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={}));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Semgrep identified an issue in your code:
The application was found calling the eval function OR Function()
constructor OR setTimeout() OR setInterval() methods. If the

variables or strings or functions passed to these methods contains user-supplied input, an adversary could attempt to execute arbitrary

JavaScript

code. This could lead to a full system compromise in Node applications or Cross-site Scripting

(XSS) in web applications.

To remediate this issue, remove all calls to above methods and consider alternative methods for

executing

the necessary business logic. There is almost no safe method of calling eval or other above stated sinks with

user-supplied input.

Instead, consider alternative methods such as using property accessors to dynamically access

values.

Example using property accessors to dynamically access an object's property:


// Define an object

const obj = {key1: 'value1', key2: 'value2'};

// Get key dynamically from user input

const key = getUserInput();

// Check if the key exists in our object and return it, or a default empty string

const value = (obj.hasOwnProperty(key)) ? obj[key] : '';

// Work with the value

For more information on why not to use eval, and alternatives see:

Other References:

To resolve this comment:

🔧 No guidance has been designated for this issue. Fix according to your organization's approved methods.

💬 Ignore this finding

Reply with Semgrep commands to ignore this finding.

  • /fp <comment> for false positive
  • /ar <comment> for acceptable risk
  • /other <comment> for all other reasons

Alternatively, triage in Semgrep AppSec Platform to ignore the finding created by detect-eval-with-expression.

You can view more details about this finding in the Semgrep AppSec Platform.

auto todel = p->next;
p->next = todel->next;
unregisterGCObj(todel->instructions);
delete todel;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Semgrep identified an issue in your code:
Avoid DML statements inside loops to avoid hitting the DML governor limit. Instead, try to batch up the data into a list and invoke your DML once on that list of data outside the loop.

To resolve this comment:

🔧 No guidance has been designated for this issue. Fix according to your organization's approved methods.

💬 Ignore this finding

Reply with Semgrep commands to ignore this finding.

  • /fp <comment> for false positive
  • /ar <comment> for acceptable risk
  • /other <comment> for all other reasons

Alternatively, triage in Semgrep AppSec Platform to ignore the finding created by avoid-native-dml-in-loops.

You can view more details about this finding in the Semgrep AppSec Platform.

# Note: pickle.load is used here for sklearn compatibility.
# These files should only be generated by training scripts in this repo.
with open(scaler_path, "rb") as f:
scaler = pickle.load(f)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Semgrep identified an issue in your code:
Avoid using pickle, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.

To resolve this comment:

🔧 No guidance has been designated for this issue. Fix according to your organization's approved methods.

💬 Ignore this finding

Reply with Semgrep commands to ignore this finding.

  • /fp <comment> for false positive
  • /ar <comment> for acceptable risk
  • /other <comment> for all other reasons

Alternatively, triage in Semgrep AppSec Platform to ignore the finding created by avoid-pickle.

You can view more details about this finding in the Semgrep AppSec Platform.

scaler = pickle.load(f)

with open(pca_path, "rb") as f:
pca = pickle.load(f)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Semgrep identified an issue in your code:
Avoid using pickle, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.

To resolve this comment:

🔧 No guidance has been designated for this issue. Fix according to your organization's approved methods.

💬 Ignore this finding

Reply with Semgrep commands to ignore this finding.

  • /fp <comment> for false positive
  • /ar <comment> for acceptable risk
  • /other <comment> for all other reasons

Alternatively, triage in Semgrep AppSec Platform to ignore the finding created by avoid-pickle.

You can view more details about this finding in the Semgrep AppSec Platform.

shutil.rmtree(venv_dir)
subprocess.check_call([sys.executable, "-m", "venv", str(venv_dir)])
pip_exe = venv_dir / "Scripts" / "python.exe"
subprocess.check_call([str(pip_exe), "-m", "pip", "install", "--upgrade", "pip"])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Semgrep identified an issue in your code:
subprocess call - check for execution of untrusted input

To resolve this comment:

🔧 No guidance has been designated for this issue. Fix according to your organization's approved methods.

💬 Ignore this finding

Reply with Semgrep commands to ignore this finding.

  • /fp <comment> for false positive
  • /ar <comment> for acceptable risk
  • /other <comment> for all other reasons

Alternatively, triage in Semgrep AppSec Platform to ignore the finding created by python_exec_rule-subprocess-call-array.

You can view more details about this finding in the Semgrep AppSec Platform.

# Note: pickle.load is used here for sklearn compatibility.
# These files should only be generated by training scripts in this repo.
with open(scaler_path, "rb") as f:
scaler = pickle.load(f)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Semgrep identified an issue in your code:
The application was found using pickle which is vulnerable to deserialization attacks.
Deserialization attacks exploit the process of reading serialized data and turning it back
into an object. By constructing malicious objects and serializing them, an adversary may
attempt to:

  • Inject code that is executed upon object construction, which occurs during the
    deserialization process.
  • Exploit mass assignment by including fields that are not normally a part of the serialized
    data but are read in during deserialization.

Consider safer alternatives such as serializing data in the JSON format. Ensure any format
chosen allows the application to specify exactly which object types are allowed to be deserialized.

To protect against mass assignment, only allow deserialization of the specific fields that are
required. If this is not easily done, consider creating an intermediary type that
can be serialized with only the necessary fields exposed.

Example JSON deserializer using an intermediary type that is validated against a schema to ensure
it is safe from mass assignment:

import jsonschema

# Create a schema to validate our user-supplied input against
# an intermediary object
intermediary_schema = {
    "type" : "object",
    "properties" :  {
        "name": {"type" : "string"}
    },
    "required": ["name"],
    # Protect against random properties being added to the object
    "additionalProperties": False,
}
# If a user attempted to add "'is_admin': True" it would cause a validation error
intermediary_object = {'name': 'test user'}

try:
    # Validate the user supplied intermediary object against our schema
    jsonschema.validate(instance=intermediary_object, schema=intermediary_schema)
    user_object = {'user':
        {
            # Assign the deserialized data from intermediary object
            'name': intermediary_object['name'],
            # Add in protected data in object definition (or set it from a class constructor)
            'is_admin': False,
        }
    }
    # Work with the user_object
except jsonschema.exceptions.ValidationError as ex:
    # Gracefully handle validation errors
    # ...

For more details on deserialization attacks in general, see OWASP's guide:

To resolve this comment:

🔧 No guidance has been designated for this issue. Fix according to your organization's approved methods.

💬 Ignore this finding

Reply with Semgrep commands to ignore this finding.

  • /fp <comment> for false positive
  • /ar <comment> for acceptable risk
  • /other <comment> for all other reasons

Alternatively, triage in Semgrep AppSec Platform to ignore the finding created by B301-1.

You can view more details about this finding in the Semgrep AppSec Platform.

@@ -0,0 +1 @@
var pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim;!function(e){!function(t){let n,s=!1;function i(e){const t=window.navigator&&/Mac/i.test(window.navigator.platform)?e.metaKey:e.ctrlKey;return"Escape"===e.key?(e.preventDefault(),"escape"):"/"===e.key&&t?(e.preventDefault(),"togglekeyboardcontrolshelp"):"b"===e.key&&t?(e.preventDefault(),"toggleareamenu"):null}t.makeFocusable=function(e){e.setAttribute("focusable","true"),e.setAttribute("tabindex","0")},t.getGlobalAction=i,t.postKeyboardEvent=function(){s||(s=!0,document.addEventListener("keydown",t=>{const n=i(t);if(n){const t={type:"action",action:n};e.Runtime.postMessage(t)}}))},t.enableKeyboardInteraction=function(e,t,n){t&&e.addEventListener("keydown",e=>{const n="number"==typeof e.which?e.which:e.keyCode;32!==n&&13!==n||t()}),n&&e.addEventListener("keyup",e=>{const t="number"==typeof e.which?e.which:e.keyCode;32!==t&&13!==t||n()})},t.setAria=function(e,t,n){t&&!e.hasAttribute("role")&&e.setAttribute("role",t),n&&!e.hasAttribute("aria-label")&&e.setAttribute("aria-label",n)},t.setLiveContent=function(e){if(!n){let e="position: absolute !important;display: block;visibility: visible;overflow: hidden;width: 1px;height: 1px;margin: -1px;border: 0;padding: 0;clip: rect(0 0 0 0);";n=document.createElement("div"),n.setAttribute("role","status"),n.setAttribute("aria-live","polite"),n.setAttribute("aria-hidden","false"),n.setAttribute("style",e),document.body.appendChild(n)}n.textContent!==e&&(n.textContent=e)}}(e.accessibility||(e.accessibility={}))}(pxsim||(pxsim={})),function(e){const t="blue",n="red",s="orange";const i=e=>(e=>e.reduce((e,t)=>e+(t?1:0),0))(e)>0;function r(e,t){let n={};for(let t in e)n[t]=e[t];for(let e in t)n[e]=t[e];return n}function o(t){e.U.assert(!!t,"Invalid pin: "+t);const n=/^(\w+)\.\s*(?:[a-z]*)?([A-Z][A-Z\d_]+)$/.exec(t);return n?n[2]:void 0}function a(e){return"-Z"===e.orientation&&"male"===e.style}e.readPin=o;class l{constructor(t){this.availablePowerPins={top:{fiveVolt:e.mkRange(26,51).map(e=>({type:"breadboard",row:"+",col:`${e}`})),threeVolt:e.mkRange(26,51).map(e=>({type:"breadboard",row:"+",col:`${e}`})),ground:e.mkRange(26,51).map(e=>({type:"breadboard",row:"-",col:`${e}`}))},bottom:{fiveVolt:e.mkRange(1,26).map(e=>({type:"breadboard",row:"+",col:`${e}`})),threeVolt:e.mkRange(1,26).map(e=>({type:"breadboard",row:"+",col:`${e}`})),ground:e.mkRange(1,26).map(e=>({type:"breadboard",row:"-",col:`${e}`}))}},this.opts=t}allocPartIRs(t,n,s){let i=[];const r=(t,n,i,r)=>{let o=[];for(let n=0;n<t.numberOfPins;n++){let r,a=t.pinDefinitions[n];if("string"==typeof a.target)r=a.target;else{let t=a.target.pinInstantiationIdx;if(!i||void 0===i[t])return void e.log(`error: parts no pin found for PinInstantiationIdx: ${t}. (Is the part missing an ArgumentRole or "trackArgs=" annotations?)`);r=i[t]}let l=t.visual.pinLocations[n],u=s.yOffset+l.y,c=Math.round(u/t.visual.pinDistance),h=u-c*t.visual.pinDistance,d=s.xOffset+l.x,p=Math.round(d/t.visual.pinDistance),f={partRelativeRowIdx:c,partRelativeColIdx:p,xOffset:d-p*t.visual.pinDistance,yOffset:h};o.push({def:a,loc:l,target:r,bbFit:f})}return{name:n,def:t,pins:o,partParams:r||{},bbFit:s}},a=t.instantiations||[];return t.instantiation&&a.push(t.instantiation),a.forEach(s=>{if("singleton"===s.kind)i.push(r(t,n));else if("function"===s.kind){let a=s,l=a.fullyQualifiedName.split(","),u={};l.forEach(e=>{this.opts.fnArgs[e]&&this.opts.fnArgs[e].forEach(e=>{u[e]=1})});let c=Object.keys(u);if(!c||!c.length)return void e.log(`error: parts failed to read pin(s) from callsite for: ${l}`);c.forEach(s=>{const u=s.split(",");if(u.length!=a.argumentRoles.length)return void e.log(`error: parts mismatch between number of arguments at callsite (function name: ${l}) vs number of argument roles in part definition (part: ${n}).`);let c=[],h={};u.forEach((e,t)=>{let n=a.argumentRoles[t];if(void 0!==n.partParameter&&(h[n.partParameter]=e),void 0!==n.pinInstantiationIdx){let t=n.pinInstantiationIdx,s=o(e);c[t]=s}}),i.push(r(t,n,c,h))})}}),i.filter(e=>!!e)}computePartDimensions(t,n){let s=t.visual.pinLocations,i=t.pinDefinitions,o=t.numberOfPins;e.U.assert(s.length===o,`Mismatch between "numberOfPins" and length of "visual.pinLocations" for "${n}"`),e.U.assert(i.length===o,`Mismatch between "numberOfPins" and length of "pinDefinitions" for "${n}"`),e.U.assert(o>0,`Part "${n}" has no pins`);let a,l,u,c,h=s.map((e,t)=>{return n={idx:t},s=e,o=i[t],r(r(n,s),o);var n,s,o}).filter(e=>"-Z"===e.orientation),d=h.length>0,p=t.visual.pinDistance;if(d){let e=h[0],n=Math.ceil(e.x/p),s=Math.ceil(e.y/p);a=n*p-e.x,l=s*p-e.y,u=Math.ceil((a+t.visual.width)/p)+1,c=Math.ceil((l+t.visual.height)/p)+1}else u=Math.ceil(t.visual.width/p),c=Math.ceil(t.visual.height/p),a=u*p-t.visual.width,l=c*p-t.visual.height;return{xOffset:a,yOffset:l,rowCount:c,colCount:u}}allocColumns(t){let n=t.length;let s=e.visuals.BREADBOARD_MID_COLS-t.map(e=>e.colCount).reduce((e,t)=>e+t,0);s<=0&&e.log("Not enough breadboard space!");let i=Math.floor(s/(n-1+2)),r=s-i*(n-1),o=Math.floor(r/2),a=(Math.ceil(r/2),1+o);return t.map(e=>{let t=a;return a+=e.colCount+i,t})}placeParts(t){const n=e.visuals.BREADBOARD_MID_ROWS+2;let s=this.allocColumns(t.map(e=>e.bbFit)),i=t.map(e=>{let t=n-e.bbFit.rowCount,s=Math.floor(t/2);return s>4&&(s=4),s<1&&(s=1),s});return t.map((e,t)=>{let n=i[t];return r({startColumnIdx:s[t],startRowIdx:n},e)})}nextColor(){return(!this.availableWireColors||this.availableWireColors.length<=0)&&(this.availableWireColors=e.visuals.GPIO_WIRE_COLORS.map(e=>e)),this.availableWireColors.pop()}allocWireIRs(i){let o=[],l=i.pins.map((r,l)=>{let u,c,h=r.target,d=i.startColumnIdx+r.bbFit.partRelativeColIdx,p=e.visuals.getColumnName(d),f=i.startRowIdx+r.bbFit.partRelativeRowIdx;if(f>=7&&(f-=2),a(r.def)){u={type:"breadboard",row:f<5?"j":"a",col:p,style:r.def.style}}else{u={type:"breadboard",row:e.visuals.getRowName(f),col:p,xOffset:r.bbFit.xOffset/i.def.visual.pinDistance,yOffset:r.bbFit.yOffset/i.def.visual.pinDistance,style:r.def.style}}return c="ground"===h?t:"threeVolt"===h?n:"fiveVolt"===h?s:"number"==typeof r.def.colorGroup?o[r.def.colorGroup]?o[r.def.colorGroup]:o[r.def.colorGroup]=this.nextColor():this.nextColor(),{start:u,end:h,color:c,pinIdx:l}});return r(i,{wires:l})}allocLocation(t,n){if("ground"===t||"threeVolt"===t||"fiveVolt"==t){if("ground"===t&&this.powerUsage.singleGround){return{type:"dalboard",pin:this.getBoardGroundPin()}}if("threeVolt"===t&&this.powerUsage.singleThreeVolt){return{type:"dalboard",pin:this.getBoardThreeVoltPin()}}if("fiveVolt"===t&&this.powerUsage.singleFiveVolt){return{type:"dalboard",pin:this.getBoardFiveVoltPin()}}e.U.assert(!!n.referenceBBPin);let s=this.opts.getBBCoord(n.referenceBBPin),i=[this.availablePowerPins.top.ground[0]||this.availablePowerPins.top.threeVolt[0],this.availablePowerPins.bottom.ground[0]||this.availablePowerPins.bottom.threeVolt[0]].map(e=>this.opts.getBBCoord(e));i[0]&&i[1]||e.debug(`No more available "${t}" locations!`);let r,o=0==e.visuals.findClosestCoordIdx(s,i);o?"ground"===t?r=this.availablePowerPins.top.ground:"threeVolt"===t?r=this.availablePowerPins.top.threeVolt:"fiveVolt"===t&&(r=this.availablePowerPins.top.fiveVolt):"ground"===t?r=this.availablePowerPins.bottom.ground:"threeVolt"===t?r=this.availablePowerPins.bottom.threeVolt:"fiveVolt"===t&&(r=this.availablePowerPins.bottom.fiveVolt);let a=r.map(e=>this.opts.getBBCoord(e)),l=e.visuals.findClosestCoordIdx(s,a),u=r[l];return o?(this.availablePowerPins.top.ground.splice(l,1),this.availablePowerPins.top.threeVolt.splice(l,1)):(this.availablePowerPins.bottom.ground.splice(l,1),this.availablePowerPins.bottom.threeVolt.splice(l,1)),u}if("breadboard"===t.type)return t;if("MOSI"===t||"MISO"===t||"SCK"===t){return this.opts.boardDef.spiPins||e.debug("No SPI pin mappings found!"),{type:"dalboard",pin:this.opts.boardDef.spiPins[t]}}if("SDA"===t||"SCL"===t){return this.opts.boardDef.i2cPins||e.debug("No I2C pin mappings found!"),{type:"dalboard",pin:this.opts.boardDef.i2cPins[t]}}{e.U.assert("string"==typeof t,"Unknown location type: "+t);let n=t,s=this.opts.boardDef.gpioPinMap[n]||n;return s?{type:"dalboard",pin:s}:void e.debug(`unknown pin location for ${n}`)}}getBoardGroundPin(){let t=this.opts.boardDef.groundPins&&this.opts.boardDef.groundPins[0]||null;return t||e.debug("No available ground pin on board!"),t}getBoardThreeVoltPin(){let t=this.opts.boardDef.threeVoltPins&&this.opts.boardDef.threeVoltPins[0]||null;return t||e.debug("No available 3.3V pin on board!"),t}getBoardFiveVoltPin(){let t=this.opts.boardDef.fiveVoltPins&&this.opts.boardDef.fiveVoltPins[0]||null;return t||e.debug("No available 5V pin on board!"),t}allocPowerWires(e){let i=this.getBoardGroundPin(),r=this.getBoardThreeVoltPin(),o=this.getBoardFiveVoltPin();const a={type:"breadboard",row:"-",col:"26"},l={type:"breadboard",row:"-",col:"1"},u={type:"breadboard",row:"-",col:"50"},c={type:"breadboard",row:"-",col:"25"};let h,d;this.opts.boardDef.attachPowerOnRight?(h=u,d=c):(h=a,d=l);let p=[],f=[],m=[];e.bottomGround&&e.topGround&&p.push({start:this.allocLocation("ground",{referenceBBPin:h}),end:this.allocLocation("ground",{referenceBBPin:d}),color:t}),e.topGround?p.push({start:this.allocLocation("ground",{referenceBBPin:h}),end:{type:"dalboard",pin:i},color:t}):e.bottomGround&&p.push({start:this.allocLocation("ground",{referenceBBPin:d}),end:{type:"dalboard",pin:i},color:t}),e.bottomThreeVolt&&e.bottomGround?f.push({start:this.allocLocation("threeVolt",{referenceBBPin:h}),end:this.allocLocation("threeVolt",{referenceBBPin:d}),color:n}):e.bottomFiveVolt&&e.bottomGround&&m.push({start:this.allocLocation("fiveVolt",{referenceBBPin:h}),end:this.allocLocation("fiveVolt",{referenceBBPin:d}),color:s}),e.topThreeVolt?f.push({start:this.allocLocation("threeVolt",{referenceBBPin:h}),end:{type:"dalboard",pin:r},color:n}):e.bottomThreeVolt&&f.push({start:this.allocLocation("threeVolt",{referenceBBPin:d}),end:{type:"dalboard",pin:r},color:s}),e.topFiveVolt&&!e.topThreeVolt?m.push({start:this.allocLocation("fiveVolt",{referenceBBPin:h}),end:{type:"dalboard",pin:o},color:n}):e.bottomFiveVolt&&!e.bottomThreeVolt&&m.push({start:this.allocLocation("fiveVolt",{referenceBBPin:d}),end:{type:"dalboard",pin:o},color:s});let g=[];p.length>0&&g.push({wireIndices:p.map((e,t)=>t)});let b=p.length;return f.length>0&&g.push({wireIndices:f.map((e,t)=>t+b)}),m.length>0&&g.push({wireIndices:f.map((e,t)=>t+b+f.length)}),{wires:p.concat(f).concat(m),assembly:g}}allocWire(e){const t=[e.start,e.end],n=t.map(e=>"ground"===e||"threeVolt"===e||"fiveVolt"===e);let s=t.map((e,t)=>n[t]?void 0:this.allocLocation(e,{}));if(s=s.map((e,n)=>{if(e)return e;const i=s[1-n];return this.allocLocation(t[n],{referenceBBPin:i})}),s[0]&&s[1])return{start:s[0],end:s[1],color:e.color}}allocPart(t){let n=t.pins.filter(e=>a(e.def)).map(n=>{let s=t.startRowIdx+n.bbFit.partRelativeRowIdx;s>=7&&(s-=2);let i=e.visuals.getRowName(s),r=t.startColumnIdx+n.bbFit.partRelativeColIdx;return{type:"breadboard",row:i,col:e.visuals.getColumnName(r)}});return{name:t.name,visual:t.def.visual,bbFit:t.bbFit,startColumnIdx:t.startColumnIdx,startRowIdx:t.startRowIdx,breadboardConnections:n,params:t.partParams,simulationBehavior:t.def.simulationBehavior}}allocAll(){let e=this.opts.partsList.map(e=>({name:e,def:this.opts.partDefs[e]})).filter(e=>!!e.def);if(e.length>0){let t=e.map(e=>this.computePartDimensions(e.def,e.name)),n=[];e.forEach((e,s)=>{let i=t[s],r=this.allocPartIRs(e.def,e.name,i);n=n.concat(r)});const s=this.placeParts(n).map(e=>this.allocWireIRs(e)),r=s.map(e=>e.wires).reduce((e,t)=>e.concat(t),[]).map(e=>function(e){let t=[e.start,e.end],n=t.map(e=>"ground"===e),s=t.map(e=>"threeVolt"===e),r=t.map(e=>"fiveVolt"===e),o=t.map(e=>function(e){let t=!1;if("string"!=typeof e&&"breadboard"===e.type){let n=e.row;t=0<=["a","b","c","d","e"].indexOf(n)}return t}(e)),a=i(n),l=i(s),u=i(r),c=i(o);return{topGround:a&&!c,topThreeVolt:l&&!c,topFiveVolt:u&&!c,bottomGround:a&&c,bottomThreeVolt:l&&c,bottomFiveVolt:u&&c,singleGround:a,singleThreeVolt:l,singleFiveVolt:u}}(e));this.powerUsage=function(e){const t=e.reduce((e,t)=>({topGround:e.topGround||t.topGround,topThreeVolt:e.topThreeVolt||t.topThreeVolt,topFiveVolt:e.topFiveVolt||t.topFiveVolt,bottomGround:e.bottomGround||t.bottomGround,bottomThreeVolt:e.bottomThreeVolt||t.bottomThreeVolt,bottomFiveVolt:e.bottomFiveVolt||t.bottomFiveVolt,singleGround:t.singleGround?null===e.singleGround:e.singleGround,singleThreeVolt:t.singleThreeVolt?null===e.singleThreeVolt:e.singleThreeVolt,singleFiveVolt:t.singleFiveVolt?null===e.singleFiveVolt:e.singleFiveVolt}),{topGround:!1,topThreeVolt:!1,topFiveVolt:!1,bottomGround:!1,bottomThreeVolt:!1,bottomFiveVolt:!1,singleGround:null,singleThreeVolt:null,singleFiveVolt:null});return t.singleGround&&(t.topGround=t.bottomGround=!1),t.singleThreeVolt&&(t.topThreeVolt=t.bottomThreeVolt=!1),t.singleFiveVolt&&(t.topFiveVolt=t.bottomFiveVolt=!1),t}(r);const o=this.allocPowerWires(this.powerUsage),a=s.map((e,t)=>{const n=this.allocPart(e),s=e.wires.map(e=>this.allocWire(e));if(s.some(e=>!e))return;const i=[];e.wires.forEach((e,t)=>{i[e.pinIdx]=t});return{part:n,wires:s,assembly:e.def.assembly.map(e=>({part:e.part,wireIndices:(e.pinIndices||[]).map(e=>i[e])}))}}).filter(e=>!!e),l=[o].concat(a).filter(e=>e.assembly&&e.assembly.length),u=!l.some(e=>e.part&&e.part.breadboardConnections&&e.part.breadboardConnections.length>0||e.wires&&e.wires.some(e=>"breadboard"==e.end.type&&"croc"!=e.end.style||"breadboard"==e.start.type&&"croc"!=e.start.style));return{partsAndWires:l,wires:[],parts:[],hideBreadboard:u}}return{partsAndWires:[],wires:[],parts:[]}}}e.allocateDefinitions=function(e){return new l(e).allocAll()}}(pxsim||(pxsim={})),function(e){!function(t){class n{constructor(e){this.seq=0,this.type=e}}t.Message=n;t.Response=class extends n{constructor(e,t){super("response"),this.request_seq=e.seq,this.command=e.command,t?(this.success=!1,this.message=t):this.success=!0}};class s extends n{constructor(e,t){super("event"),this.event=e,t&&(this.body=t)}}t.Event=s;t.Source=class{constructor(e,t,n=0,s,i){this.name=e,this.path=t,this.sourceReference=n,s&&(this.origin=s),i&&(this.adapterData=i)}};t.Scope=class{constructor(e,t,n=!1){this.name=e,this.variablesReference=t,this.expensive=n}};t.StackFrame=class{constructor(e,t,n,s=0,i=0){this.id=e,this.source=n,this.line=s,this.column=i,this.name=t}};t.Thread=class{constructor(e,t){this.id=e,this.name=t||"Thread #"+e}};t.Variable=class{constructor(e,t,n=0,s,i){this.name=e,this.value=t,this.variablesReference=n,"number"==typeof i&&(this.namedVariables=i),"number"==typeof s&&(this.indexedVariables=s)}};t.Breakpoint=class{constructor(e,t,n,s){this.verified=e;const i=this;"number"==typeof t&&(i.line=t),"number"==typeof n&&(i.column=n),s&&(i.source=s)}};t.Module=class{constructor(e,t){this.id=e,this.name=t}};t.CompletionItem=class{constructor(e,t,n=0){this.label=e,this.start=t,this.length=n}};t.StoppedEvent=class extends s{constructor(e,t,n=null){if(super("stopped"),this.body={reason:e,threadId:t},n){this.body.text=n}}};t.ContinuedEvent=class extends s{constructor(e,t){super("continued"),this.body={threadId:e},"boolean"==typeof t&&(this.body.allThreadsContinued=t)}};t.InitializedEvent=class extends s{constructor(){super("initialized")}};t.TerminatedEvent=class extends s{constructor(e){if(super("terminated"),"boolean"==typeof e){this.body={restart:e}}}};t.OutputEvent=class extends s{constructor(e,t="console",n){super("output"),this.body={category:t,output:e},void 0!==n&&(this.body.data=n)}};t.ThreadEvent=class extends s{constructor(e,t){super("thread"),this.body={reason:e,threadId:t}}};t.BreakpointEvent=class extends s{constructor(e,t){super("breakpoint"),this.body={reason:e,breakpoint:t}}};t.ModuleEvent=class extends s{constructor(e,t){super("module"),this.body={reason:e,module:t}}};class i{constructor(){this._pendingRequests={}}start(e){this._sequence=1,this.host=e,this.host.onData(e=>{if("request"===e.type)this.dispatchRequest(e);else if("response"===e.type){const t=e,n=this._pendingRequests[t.seq];n&&(delete this._pendingRequests[t.seq],n(t))}})}stop(){this.host&&this.host.close()}sendEvent(e){this.send("event",e)}sendResponse(t){t.seq>0?e.error(`attempt to send more than one response for command ${t.command}`):this.send("response",t)}sendRequest(e,n,s,i){const r={command:e};if(n&&Object.keys(n).length>0&&(r.arguments=n),this.send("request",r),i){this._pendingRequests[r.seq]=i;const e=setTimeout(()=>{clearTimeout(e);const n=this._pendingRequests[r.seq];n&&(delete this._pendingRequests[r.seq],n(new t.Response(r,"timeout")))},s)}}send(e,t){if(t.type=e,t.seq=this._sequence++,this.host){const e=JSON.stringify(t);this.host.send(e)}}dispatchRequest(e){}}t.ProtocolServer=i;class r extends i{constructor(){super(...arguments),this._debuggerLinesStartAt1=!1,this._debuggerColumnsStartAt1=!1,this._clientLinesStartAt1=!0,this._clientColumnsStartAt1=!0}shutdown(){}dispatchRequest(e){const n=new t.Response(e);try{if("initialize"===e.command){let t=e.arguments;if("boolean"==typeof t.linesStartAt1&&(this._clientLinesStartAt1=t.linesStartAt1),"boolean"==typeof t.columnsStartAt1&&(this._clientColumnsStartAt1=t.columnsStartAt1),"path"!==t.pathFormat)this.sendErrorResponse(n,2018,"debug adapter only supports native paths",null);else{const e=n;e.body={},this.initializeRequest(e,t)}}else"launch"===e.command?this.launchRequest(n,e.arguments):"attach"===e.command?this.attachRequest(n,e.arguments):"disconnect"===e.command?this.disconnectRequest(n,e.arguments):"setBreakpoints"===e.command?this.setBreakPointsRequest(n,e.arguments):"setFunctionBreakpoints"===e.command?this.setFunctionBreakPointsRequest(n,e.arguments):"setExceptionBreakpoints"===e.command?this.setExceptionBreakPointsRequest(n,e.arguments):"configurationDone"===e.command?this.configurationDoneRequest(n,e.arguments):"continue"===e.command?this.continueRequest(n,e.arguments):"next"===e.command?this.nextRequest(n,e.arguments):"stepIn"===e.command?this.stepInRequest(n,e.arguments):"stepOut"===e.command?this.stepOutRequest(n,e.arguments):"stepBack"===e.command?this.stepBackRequest(n,e.arguments):"restartFrame"===e.command?this.restartFrameRequest(n,e.arguments):"goto"===e.command?this.gotoRequest(n,e.arguments):"pause"===e.command?this.pauseRequest(n,e.arguments):"stackTrace"===e.command?this.stackTraceRequest(n,e.arguments):"scopes"===e.command?this.scopesRequest(n,e.arguments):"variables"===e.command?this.variablesRequest(n,e.arguments):"setVariable"===e.command?this.setVariableRequest(n,e.arguments):"source"===e.command?this.sourceRequest(n,e.arguments):"threads"===e.command?this.threadsRequest(n):"evaluate"===e.command?this.evaluateRequest(n,e.arguments):"stepInTargets"===e.command?this.stepInTargetsRequest(n,e.arguments):"gotoTargets"===e.command?this.gotoTargetsRequest(n,e.arguments):"completions"===e.command?this.completionsRequest(n,e.arguments):this.customRequest(e.command,n,e.arguments)}catch(e){this.sendErrorResponse(n,1104,"{_stack}",{_exception:e.message,_stack:e.stack})}}initializeRequest(e,t){e.body.supportsConditionalBreakpoints=!1,e.body.supportsHitConditionalBreakpoints=!1,e.body.supportsFunctionBreakpoints=!1,e.body.supportsConfigurationDoneRequest=!0,e.body.supportsEvaluateForHovers=!1,e.body.supportsStepBack=!1,e.body.supportsSetVariable=!1,e.body.supportsRestartFrame=!1,e.body.supportsStepInTargetsRequest=!1,e.body.supportsGotoTargetsRequest=!1,e.body.supportsCompletionsRequest=!1,this.sendResponse(e)}disconnectRequest(e,t){this.sendResponse(e),this.shutdown()}launchRequest(e,t){this.sendResponse(e)}attachRequest(e,t){this.sendResponse(e)}setBreakPointsRequest(e,t){this.sendResponse(e)}setFunctionBreakPointsRequest(e,t){this.sendResponse(e)}setExceptionBreakPointsRequest(e,t){this.sendResponse(e)}configurationDoneRequest(e,t){this.sendResponse(e)}continueRequest(e,t){this.sendResponse(e)}nextRequest(e,t){this.sendResponse(e)}stepInRequest(e,t){this.sendResponse(e)}stepOutRequest(e,t){this.sendResponse(e)}stepBackRequest(e,t){this.sendResponse(e)}restartFrameRequest(e,t){this.sendResponse(e)}gotoRequest(e,t){this.sendResponse(e)}pauseRequest(e,t){this.sendResponse(e)}sourceRequest(e,t){this.sendResponse(e)}threadsRequest(e){this.sendResponse(e)}stackTraceRequest(e,t){this.sendResponse(e)}scopesRequest(e,t){this.sendResponse(e)}variablesRequest(e,t){this.sendResponse(e)}setVariableRequest(e,t){this.sendResponse(e)}evaluateRequest(e,t){this.sendResponse(e)}stepInTargetsRequest(e,t){this.sendResponse(e)}gotoTargetsRequest(e,t){this.sendResponse(e)}completionsRequest(e,t){this.sendResponse(e)}customRequest(e,t,n){this.sendErrorResponse(t,1014,"unrecognized request",null)}sendErrorResponse(e,t,n,s){let i;"number"==typeof t?(i={id:t,format:n},s&&(i.variables=s),i.showUser=!0):i=t,e.success=!1,r.formatPII(i.format,!0,i.variables),e.body||(e.body={}),e.body.error=i,this.sendResponse(e)}convertClientLineToDebugger(e){return this._debuggerLinesStartAt1?this._clientLinesStartAt1?e:e+1:this._clientLinesStartAt1?e-1:e}convertDebuggerLineToClient(e){return this._debuggerLinesStartAt1?this._clientLinesStartAt1?e:e-1:this._clientLinesStartAt1?e+1:e}convertClientColumnToDebugger(e){return this._debuggerColumnsStartAt1?this._clientColumnsStartAt1?e:e+1:this._clientColumnsStartAt1?e-1:e}convertDebuggerColumnToClient(e){return this._debuggerColumnsStartAt1?this._clientColumnsStartAt1?e:e-1:this._clientColumnsStartAt1?e+1:e}convertClientPathToDebugger(e){return this._clientPathsAreURIs!=this._debuggerPathsAreURIs?this._clientPathsAreURIs?r.uri2path(e):r.path2uri(e):e}convertDebuggerPathToClient(e){return this._debuggerPathsAreURIs!=this._clientPathsAreURIs?this._debuggerPathsAreURIs?r.uri2path(e):r.path2uri(e):e}static path2uri(e){let t=e.replace(/\\/g,"/");return"/"!==t[0]&&(t="/"+t),encodeURI("file://"+t)}static uri2path(e){return e}static formatPII(e,t,n){return e.replace(r._formatPIIRegexp,function(e,s){return t&&s.length>0&&"_"!==s[0]?e:n[s]&&n.hasOwnProperty(s)?n[s]:e})}}r._formatPIIRegexp=/{([^}]+)}/g,t.DebugSession=r}(e.protocol||(e.protocol={}))}(pxsim||(pxsim={})),function(e){!function(e){e.injectPolyphils=function(){String.prototype.startsWith||Object.defineProperty(String.prototype,"startsWith",{value:function(e,t){return void 0!==e&&null!=e&&(t=!t||t<0?0:+t,this.substring(t,t+e.length)===e)}}),Array.prototype.fill||Object.defineProperty(Array.prototype,"fill",{writable:!0,enumerable:!0,value:function(e){if(null==this)throw new TypeError("this is null or not defined");let t=Object(this),n=t.length>>>0,s=arguments[1]|0,i=s<0?Math.max(n+s,0):Math.min(s,n),r=arguments[2],o=void 0===r?n:r|0,a=o<0?Math.max(n+o,0):Math.min(o,n);for(;i<a;)t[i]=e,i++;return t}}),Array.prototype.find||Object.defineProperty(Array.prototype,"find",{writable:!0,enumerable:!0,value:function(e){if(null==this)throw new TypeError('"this" is null or not defined');let t=Object(this);const n=t.length>>>0;if("function"!=typeof e)throw new TypeError("predicate must be a function");const s=arguments[1];let i=0;for(;i<n;){const n=t[i];if(e.call(s,n,i,t))return n;i++}}}),Uint8Array.prototype.slice||Object.defineProperty(Uint8Array.prototype,"slice",{value:Array.prototype.slice,writable:!0,enumerable:!0}),Uint16Array.prototype.slice||Object.defineProperty(Uint16Array.prototype,"slice",{value:Array.prototype.slice,writable:!0,enumerable:!0}),Uint32Array.prototype.slice||Object.defineProperty(Uint32Array.prototype,"slice",{value:Array.prototype.slice,writable:!0,enumerable:!0}),Uint8Array.prototype.fill||Object.defineProperty(Uint8Array.prototype,"fill",{value:Array.prototype.fill,writable:!0,enumerable:!0}),Uint16Array.prototype.fill||Object.defineProperty(Uint16Array.prototype,"fill",{value:Array.prototype.fill,writable:!0,enumerable:!0}),Uint32Array.prototype.fill||Object.defineProperty(Uint32Array.prototype,"fill",{value:Array.prototype.fill,writable:!0,enumerable:!0}),Uint8Array.prototype.some||Object.defineProperty(Uint8Array.prototype,"some",{value:Array.prototype.some,writable:!0,enumerable:!0}),Uint16Array.prototype.some||Object.defineProperty(Uint16Array.prototype,"some",{value:Array.prototype.some,writable:!0,enumerable:!0}),Uint32Array.prototype.some||Object.defineProperty(Uint32Array.prototype,"some",{value:Array.prototype.some,writable:!0,enumerable:!0}),Uint8Array.prototype.reverse||Object.defineProperty(Uint8Array.prototype,"reverse",{value:Array.prototype.reverse,writable:!0,enumerable:!0}),Uint16Array.prototype.reverse||Object.defineProperty(Uint16Array.prototype,"reverse",{value:Array.prototype.reverse,writable:!0,enumerable:!0}),Uint32Array.prototype.reverse||Object.defineProperty(Uint32Array.prototype,"reverse",{value:Array.prototype.reverse,writable:!0,enumerable:!0}),Math.imul||(Math.imul=function(e,t){const n=65535&e,s=65535&t;return n*s+((e>>>16&65535)*s+n*(t>>>16&65535)<<16>>>0)|0}),"function"!=typeof Object.assign&&Object.defineProperty(Object,"assign",{value:function(e,t){"use strict";if(null==e)throw new TypeError("Cannot convert undefined or null to object");let n=Object(e);for(let e=1;e<arguments.length;e++){let t=arguments[e];if(null!=t)for(let e in t)Object.prototype.hasOwnProperty.call(t,e)&&(n[e]=t[e])}return n},writable:!0,configurable:!0}),Promise.prototype.finally||(Promise.prototype.finally=Promise.prototype.finally||{finally(e){const t=t=>Promise.resolve(e()).then(t);return this.then(e=>t(()=>e),e=>t(()=>Promise.reject(e)))}}.finally)};function t(e){e=e.replace(/\\/g,"/");const t=[];return e.split("/").forEach(e=>{".."===e&&t.length?t.pop():e&&"."!==e&&t.push(e)}),t}e.Lazy=class{constructor(e){this._func=e,this._evaluated=!1}get value(){return this._evaluated||(this._value=this._func(),this._evaluated=!0),this._value}},e.getNormalizedParts=t,e.normalizePath=function(e){return t(e).join("/")},e.relativePath=function(e,n){const s=t(e),i=t(n);let r=0;for(;s[r]===i[r]&&(r++,r!==s.length&&r!==i.length););const o=s.slice(r),a=i.slice(r);for(let e=0;e<o.length;e++)a.unshift("..");return a.join("/")},e.pathJoin=function(...e){let t="";return e.forEach(e=>{e.replace(/\\/g,"/"),e.lastIndexOf("/")===e.length-1&&(e=e.slice(0,e.length-1)),t+="/"+e}),t},e.toArray=function(e){if(Array.isArray(e))return e;let t=[];for(let n=0;n<e.length;++n)t.push(e[n]);return t}}(e.util||(e.util={}))}(pxsim||(pxsim={})),function(e){e.getWarningMessage=function(t){let n={type:"debugger",subtype:"warning",breakpointIds:[],message:t},s=e.runtime.currFrame;for(;null!=s;)n.breakpointIds.push(s.lastBrkId),s=s.parent;return n};function t(t,n){switch(typeof t){case"string":case"number":case"boolean":return t;case"function":return{text:"(function)",type:"function"};case"undefined":return null;case"object":if(!t)return null;if(t instanceof e.RefObject){n&&(n[t.id]=t);let s=e.RefObject.toDebugString(t),i=s.startsWith("[")?"array":s;return{id:t.id,preview:s,hasFields:null!==t.fields||s.startsWith("["),type:i}}return t._width&&t._height?{text:t._width+"x"+t._height,type:"image"}:{text:"(object)",type:"object"};default:throw new Error}}function n(n,i,r,o,a=!1){return function(n,r){const l={};for(let e of Object.keys(n))/^__/.test(e)||!/___\d+$/.test(e)||o&&-1===o.indexOf(e)||(l[e]=t(n[e],i));if(n.fields&&r)for(let e of r)e=e.substring(e.lastIndexOf(".")+1),l[e]=t(s(n.vtable.iface[e],n),i);if(n.fields)for(let e of Object.keys(n.fields).filter(e=>a||!e.startsWith("_")))l[e]=t(n.fields[e],i);else if(n instanceof e.RefMap)for(const e of n.data)l[e.key]=t(e.val,i);else Array.isArray(n.data)?n.data.forEach((e,n)=>{l[n]=t(e,i)}):void 0!==n._width&&void 0!==n._height&&(l.width=n._width,l.height=n._height,a&&void 0!==n._bpp&&(l.isMono=1===n._bpp));return l}(n,r)}function s(e,t){let n={pc:0,arg0:t,fn:e,parent:{}};for(;n.fn;)n=n.fn(n);return n.retval}function i(e,s){let i=e.fn?e.fn.info:null;if(i){let r={thisParam:t(e.argL,s),params:[]};if(i.argumentNames){const n=i.argumentNames;r.params=n.map((n,i)=>({name:n,value:t(e["arg"+i],s)}))}return{locals:n(e,s),funcInfo:i,breakpointId:e.lastBrkId,callLocationId:e.callLocIdx,arguments:r}}}e.BreakpointMap=class{constructor(e){this.fileMap={},this.idMap={},e.forEach(e=>{const[t,n]=e;this.fileMap[n.source.path]||(this.fileMap[n.source.path]=[]),this.fileMap[n.source.path].push(e),this.idMap[t]=n});for(const e in this.fileMap){const t=this.fileMap[e];this.fileMap[e]=t.sort(([,e],[,t])=>e.line===t.line?t.endLine===e.endLine?e.column-t.column:t.endLine-e.endLine:e.line-t.line)}}getById(e){return this.idMap[e]}verifyBreakpoint(e,t){const n=this.fileMap[e];let s;if(n)for(const[e,i]of n)i.line<=t.line&&i.endLine>=t.line&&(s=[e,i]);return s?(s[1].verified=!0,s):[-1,{verified:!1}]}},e.dumpHeap=n,e.injectEnvironmentGlobals=function(n,s){const i=e.runtime.environmentGlobals;if(!Object.keys(i).length)return;const r=n.environmentGlobals={};Object.keys(i).forEach(n=>r[n]=t(e.runtime.environmentGlobals[n],s))},e.getBreakpointMsg=function(t,s,r){const o={},a={type:"debugger",subtype:"breakpoint",breakpointId:s,globals:n(e.runtime.globals,o,void 0,r),stackframes:[]};for(;null!=t;){let e=i(t,o);e&&a.stackframes.push(e),t=t.parent}return{msg:a,heap:o}};class r extends e.protocol.DebugSession{constructor(t){super();let n={onDebuggerBreakpoint:e=>this.onDebuggerBreakpoint(e),onDebuggerWarning:e=>this.onDebuggerWarning(e),onDebuggerResume:()=>this.onDebuggerResume(),onStateChanged:e=>this.onStateChanged(e)};this.driver=new e.SimulatorDriver(t,n)}runCode(t,n,s,i,r){this.breakpoints=i,this.projectDir&&this.fixBreakpoints(),this.sendEvent(new e.protocol.InitializedEvent),this.driver.run(t,{parts:n,fnArgs:s,boardDefinition:r})}stopSimulator(e=!1){this.driver.stop(e)}initializeRequest(e,t){e.body.supportsConditionalBreakpoints=!1,e.body.supportsHitConditionalBreakpoints=!1,e.body.supportsFunctionBreakpoints=!1,e.body.supportsEvaluateForHovers=!1,e.body.supportsStepBack=!1,e.body.supportsSetVariable=!1,e.body.supportsRestartFrame=!1,e.body.supportsStepInTargetsRequest=!1,e.body.supportsGotoTargetsRequest=!1,e.body.supportsCompletionsRequest=!1,e.body.supportsConfigurationDoneRequest=!0,this.sendResponse(e)}disconnectRequest(e,t){this.sendResponse(e),this.shutdown()}launchRequest(t,n){this.projectDir||(this.projectDir=e.util.normalizePath(n.projectDir),this.breakpoints&&this.fixBreakpoints()),this.sendResponse(t)}setBreakPointsRequest(t,n){t.body={breakpoints:[]};const s=[];n.breakpoints.forEach(i=>{if(this.breakpoints){const[r,o]=this.breakpoints.verifyBreakpoint(e.util.relativePath(this.projectDir,n.source.path),i);t.body.breakpoints.push(o),o.verified&&s.push(r)}else t.body.breakpoints.push({verified:!1})}),this.driver.setBreakpoints(s),this.sendResponse(t)}continueRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.Resume),this.sendResponse(t)}nextRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.StepOver),this.sendResponse(t)}stepInRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.StepInto),this.sendResponse(t)}stepOutRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.StepOut),this.sendResponse(t)}pauseRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.Pause),this.sendResponse(t)}threadsRequest(e){e.body={threads:[{id:r.THREAD_ID,name:"main"}]},this.sendResponse(e)}stackTraceRequest(e,t){if(this.lastBreak){const t=this.state.getFrames();e.body={stackFrames:t}}this.sendResponse(e)}scopesRequest(e,t){this.state&&(e.body={scopes:this.state.getScopes(t.frameId)}),this.sendResponse(e)}variablesRequest(e,t){this.state&&(e.body={variables:this.state.getVariables(t.variablesReference)}),this.sendResponse(e)}onDebuggerBreakpoint(t){if(this.lastBreak=t,this.state=new o(this.lastBreak,this.breakpoints,this.projectDir),t.exceptionMessage){const n=t.exceptionMessage.replace(/___\d+/g,"");this.sendEvent(new e.protocol.StoppedEvent("exception",r.THREAD_ID,n))}else this.sendEvent(new e.protocol.StoppedEvent("breakpoint",r.THREAD_ID))}onDebuggerWarning(e){}onDebuggerResume(){this.sendEvent(new e.protocol.ContinuedEvent(r.THREAD_ID,!0))}onStateChanged(t){switch(t){case e.SimulatorState.Paused:break;case e.SimulatorState.Running:this.sendEvent(new e.protocol.ContinuedEvent(r.THREAD_ID,!0));break;case e.SimulatorState.Stopped:this.sendEvent(new e.protocol.TerminatedEvent)}}fixBreakpoints(){for(const t in this.breakpoints.idMap){const n=this.breakpoints.idMap[t];n.source.path=e.util.pathJoin(this.projectDir,n.source.path),n.line=this.convertDebuggerLineToClient(n.line),n.endLine=this.convertDebuggerLineToClient(n.endLine),n.column=this.convertDebuggerColumnToClient(n.column),n.endColumn=this.convertDebuggerColumnToClient(n.endColumn)}}}r.THREAD_ID=1,e.SimDebugSession=r;class o{constructor(e,t,n){this._message=e,this._map=t,this._dir=n,this._currentId=1,this._frames={},this._vars={};const s=this.nextId();this._vars[s]=this.getVariableValues(this._message.globals),this._globalScope={name:"Globals",variablesReference:s,expensive:!1}}getFrames(){return this._message.stackframes.map((e,t)=>{const n=this._map.getById(e.breakpointId);if(n)return this._frames[e.breakpointId]=e,{id:e.breakpointId,name:e.funcInfo?e.funcInfo.functionName:0===t?"main":"anonymous",line:n.line,column:n.column,endLine:n.endLine,endColumn:n.endLine,source:n.source}}).filter(e=>!!e)}getScopes(e){const t=this._frames[e];if(t){const e=this.nextId();return this._vars[e]=this.getVariableValues(t.locals),[{name:"Locals",variablesReference:e,expensive:!1},this._globalScope]}return[this._globalScope]}getVariables(e){const t=this._vars[e];return t&&t.value||[]}getVariableValues(t){return new e.util.Lazy(()=>{const e=[];for(const n in t){const s=t[n];let i,r=0;null===s?i="null":void 0===s?i="undefined":"object"==typeof s?(i="(object)",r=this.nextId(),this._vars[r]=this.getVariableValues(s)):i=s.toString();const o=n.substr(0,n.lastIndexOf("___"));e.push({name:o,value:i,variablesReference:r})}return e})}nextId(){return this._currentId++}}}(pxsim||(pxsim={})),function(e){let t,n;function s(e=0){function t(){try{window.print()}catch(e){}}e?setTimeout(t,e):t()}function i(e,t){r({type:"pxtsim",action:"event",tick:e,data:t})}function r(e){"undefined"!=typeof window&&window.parent&&window.parent!==window&&window.parent.postMessage(e,"*")}function o(){setInterval(()=>{e.Runtime.postMessage({type:"simulator",command:"reload"})},3e3)}!function(e){let t;!function(e){e[e.Player=0]="Player",e[e.Reaction=1]="Reaction"}(t=e.IconType||(e.IconType={}))}(t=e.multiplayer||(e.multiplayer={})),e.print=s,function(t){function n(t){t.origin;let n=t.data||{},o=n.type;if(o)switch(o){case"run":l(n);break;case"instructions":e.instructions.renderInstructions(n);break;case"stop":a();break;case"mute":u(n.mute);break;case"stopsound":e.AudioContextManager.stopAll();break;case"print":s();break;case"recorder":!function(e){if(!r)return;switch(e.action){case"start":r.startRecording(e.width);break;case"stop":r.stopRecording()}}(n);break;case"screenshot":e.Runtime.postScreenshotAsync(n);break;case"custom":e.handleCustomMessage&&e.handleCustomMessage(n);break;case"pxteditor":break;case"debugger":r&&r.handleDebuggerMsg(n);break;case"simulator":let t=n;switch(t.command){case"focus":i("simulator.focus",{timestamp:t.timestamp});break;case"blur":i("simulator.blur",{timestamp:t.timestamp})}default:!function(e){if(!r||r.dead)return;r.board.receiveMessage(e)}(n)}}let r;function a(){r&&(r.kill(),r.board&&r.board.kill())}function l(t){a(),t.mute&&u(t.mute),t.localizedStrings&&e.localization.setLocalizedStrings(t.localizedStrings);const n=new e.Runtime(t);r=n,n.board.initAsync(t).then(()=>{n===r&&n.run(t=>{e.dumpLivePointers(),e.Runtime.postMessage({type:"toplevelcodefinished"})})})}function u(t){e.AudioContextManager.mute(t)}t.start=function(){window.addEventListener("message",n,!1),t.frameid=window.location.hash.slice(1),function(){if("serviceWorker"in navigator&&-1!==window.location.href.indexOf("---simulator")&&!e.U.isLocalHost()){const t=window.location.pathname,n=t.substring(1,t.indexOf("---"));navigator.serviceWorker.controller&&navigator.serviceWorker.addEventListener("message",e=>{const t=e.data;t&&"serviceworker"===t.type&&"activated"===t.state&&t.ref===n&&o()});const s=window.location.href.replace(/---simulator.*$/,"---simserviceworker");navigator.serviceWorker.register(s).then(function(t){e.log("Simulator ServiceWorker registration successful with scope: ",t.scope)},function(t){e.log("Simulator ServiceWorker registration failed: ",t)})}}(),e.Runtime.postMessage({type:"ready",frameid:t.frameid})},t.stop=a,t.run=l}(n=e.Embed||(e.Embed={})),e.tickEvent=i,e.reportError=function(e,t,n){r({type:"pxtsim",action:"event",tick:"error",category:e,message:t,data:n})},e.reload=o}(pxsim||(pxsim={})),pxsim.util.injectPolyphils(),"undefined"!=typeof window&&window.addEventListener("load",function(e){pxsim.Embed.start()}),function(e){!function(t){const n=e=>`${e}x`,s=.95,[i,r]=[816*s,1056*s],o=i-86.4,a=r-86.4,l="gray",[u,c]=[1,1],h=24,d=o/c-48*c,p=`\n .instr-panel {\n margin: 20px;\n padding: 24px;\n border-width: 4px;\n border-color: ${l};\n border-style: solid;\n border-radius: 20px;\n display: inline-block;\n width: ${d}px;\n height: ${a/u-48*u}px;\n position: relative;\n overflow: hidden;\n page-break-inside: avoid;\n }\n .board-svg {\n margin: 0 auto;\n display: block;\n position: absolute;\n bottom: 24px;\n left: ${(d-465)/2+h}px;\n }\n .panel-num-outer {\n position: absolute;\n left: -4px;\n top: -4px;\n width: 120px;\n height: 120px;\n border-width: 4px;\n border-style: solid;\n border-color: ${l};\n border-radius: 20px 0 20px 0;\n }\n .panel-num {\n margin: 10px 0;\n text-align: center;\n font-size: 80px;\n }\n .cmp-div {\n display: inline-block;\n }\n .reqs-div {\n margin-left: 144px;\n margin-top: 5px;\n }\n .partslist-wire,\n .partslist-cmp {\n margin: 10px;\n }\n .partslist-wire {\n display: inline-block;\n }\n `;function f(t,n){let s=document.createElementNS("http://www.w3.org/2000/svg","svg"),i={l:0,t:0,w:0,h:0},r=document.createElementNS("http://www.w3.org/2000/svg","svg");s.appendChild(r),r.appendChild(t.el);let o={viewBox:`${t.x} ${t.y} ${t.w} ${t.h}`,preserveAspectRatio:"xMidYMid"};i.w=t.w,i.h=t.h;let a=e=>{i.h*=e,i.w*=e,o.width=i.w,o.height=i.h};n.cmpScale&&a(n.cmpScale),n.cmpWidth&&n.cmpWidth<i.w?a(n.cmpWidth/i.w):n.cmpHeight&&n.cmpHeight<i.h&&a(n.cmpHeight/i.h),e.svg.hydrate(r,o);let l=i.l,u=i.t,c=i.w,h=i.h,d=e=>{if(e<i.l){let t=i.l-e;i.l=e,i.w+=t}},p=e=>{let t=i.l+i.w;if(t<e){let n=e-t;i.w+=n}},f=e=>{if(e<i.t){let t=i.t-e;i.t=e,i.h+=t}},m=e=>{let t=i.t+i.h;if(t<e){let n=e-t;i.h+=n}},[g,b]=[-.3,.3];const v=[1.4,1];if(n&&n.top){let t=n.topSize,i=t/v[0],r=t/v[1],[o,a]=[l+c/2,u-3-r/2],h=e.visuals.mkTxt(o,a,t,0,n.top,g,b);e.U.addClass(h,"cmp-lbl"),s.appendChild(h);let m=i*n.top.length;f(a-r/2),d(o-m/2),p(o+m/2)}if(n&&n.bot){let t=n.botSize,i=t/v[0],r=t/v[1],[o,a]=[l+c/2,u+h+3+r/2],f=e.visuals.mkTxt(o,a,t,0,n.bot,g,b);e.U.addClass(f,"cmp-lbl"),s.appendChild(f);let y=i*n.bot.length;m(a+r/2),d(o-y/2),p(o+y/2)}if(n&&n.right){let t=n.rightSize,i=t/v[1],r=t/v[0]*n.right.length,[o,a]=[l+c+5+r/2,u+h/2],d=e.visuals.mkTxt(o,a,t,0,n.right,g,b);e.U.addClass(d,"cmp-lbl"),s.appendChild(d),f(a-i/2),p(o+r/2),m(a+i/2)}if(n&&n.left){let t=n.leftSize,i=t/v[1],r=t/v[0]*n.left.length,[o,a]=[l-5-r/2,u+h/2],c=e.visuals.mkTxt(o,a,t,0,n.left,g,b);e.U.addClass(c,"cmp-lbl"),s.appendChild(c),f(a-i/2),d(o-r/2),m(a+i/2)}let y={viewBox:`${i.l} ${i.t} ${i.w} ${i.h}`,width:1.7*i.w,height:1.7*i.h,preserveAspectRatio:"xMidYMid"};e.svg.hydrate(s,y);let S=document.createElement("div");return S.appendChild(s),S}function m(t,n){let s,i=e.runtime.board;if("wire"==t)s=e.visuals.mkWirePart([0,0],n.wireClr||"red",n.crocClips);else{let n=t;if("string"==typeof n.builtIn){s=(0,i.builtinPartVisuals[n.builtIn])([0,0])}else s=e.visuals.mkGenericPartSVG(n)}return f(s,n)}function g(t,n,s=!1){const i={state:e.runtime.board,boardDef:t.boardDef,forceBreadboardLayout:!0,forceBreadboardRender:t.allAlloc.requiresBreadboard,partDefs:t.cmpDefs,maxWidth:`${n}px`,fnArgs:t.fnArgs,wireframe:s,partsList:[]};let r=new e.visuals.BoardHost(e.visuals.mkBoardView({visual:i.boardDef.visual,boardDef:i.boardDef,wireframe:i.wireframe}),i),o=r.getView();return e.U.addClass(o,"board-svg"),r}function b(){let t=document.createElement("div");return e.U.addClass(t,"instr-panel"),t}function v(t){let s=b();var i;let r=f((i=t.boardDef,e.visuals.mkBoardView({visual:i.visual,boardDef:i}).getView()),{left:n(1),leftSize:30,cmpScale:.17});s.appendChild(r);let o=f(new e.visuals.Breadboard({}).getSVGAndSize(),{left:n(1),leftSize:30,cmpScale:.25});return s.appendChild(o),t.allCmps.forEach(t=>{let i=1;"buttonpair"===t.visual.builtIn&&(i=2);let r=m(t.visual,{left:n(i),leftSize:30,cmpScale:.3});e.U.addClass(r,"partslist-cmp"),s.appendChild(r)}),t.allWireColors.forEach(i=>{let r=t.colorToWires[i].length,o=t.boardDef.pinStyles[i]||"female",a=m("wire",{left:n(r),leftSize:20,wireClr:i,cmpScale:.23,crocClips:"croc"==o});e.U.addClass(a,"partslist-wire"),s.appendChild(a)}),s}function y(t,n){let s=b(),i=g(n,465,!0);!function(t,n,s){let i=t.getView();n>0&&e.U.addClass(i,"grayed");for(let i=0;i<=n;i++){let r=s.stepToCmps[i];r&&r.forEach(s=>{let r=t.addPart(s);i===n&&(s.breadboardConnections.forEach(e=>t.highlightBreadboardPin(e)),e.U.addClass(r.element,"notgrayed"))});let o=s.stepToWires[i];o&&o.forEach(e=>{let s=t.addWire(e);s&&i===n&&("breadboard"==e.start.type?t.highlightBreadboardPin(e.start):t.highlightBoardPin(e.start.pin),"breadboard"==e.end.type?t.highlightBreadboardPin(e.end):t.highlightBoardPin(e.end.pin),t.highlightWire(s))})}}(i,t,n),s.appendChild(i.getView());let r=document.createElement("div");e.U.addClass(r,"panel-num-outer"),e.U.addClass(r,"noselect"),s.appendChild(r);let o=document.createElement("div");e.U.addClass(o,"panel-num"),o.textContent=t+1+"",r.appendChild(o);let a=document.createElement("div");e.U.addClass(a,"reqs-div"),s.appendChild(a);let l=n.stepToWires[t]||[],u=e=>{if("breadboard"===e.type){let{row:t,col:n}=e;return`(${t},${n})`}return e.pin};return l.forEach(t=>{let s=!1;"dalboard"==t.end.type&&(s="croc"==n.boardDef.pinStyles[t.end.pin]);let i=m("wire",{top:u(t.end),topSize:10,bot:u(t.start),botSize:10,wireClr:t.color,cmpHeight:40,crocClips:s});e.U.addClass(i,"cmp-div"),a.appendChild(i)}),(n.stepToCmps[t]||[]).forEach(t=>{let n;n="buttonpair"===t.visual.builtIn?[t.breadboardConnections[0],t.breadboardConnections[2]]:[t.breadboardConnections[0]],n.forEach((n,s)=>{let i;if(n){let{row:e,col:t}=n;i=`(${e},${t})`}else i="";let r=1.5;"buttonpair"===t.visual.builtIn&&(r*=.5);let o=m(t.visual,{top:i,topSize:10,cmpHeight:50,cmpScale:r});e.U.addClass(o,"cmp-div"),a.appendChild(o)})}),s}function S(t,n){n.boardDef.pinStyles||(n.boardDef.pinStyles={}),n.configData&&e.setConfigData(n.configData.cfg,n.configData.cfgKey);const s={type:"run",code:"",boardDefinition:n.boardDef,partDefinitions:n.partDefinitions};e.runtime=new e.Runtime(s),e.runtime.board=null,e.initCurrentRuntime(s);let i=document.createElement("style");i.textContent+=p,document.head.appendChild(i);const r=n.partDefinitions;let o=new e.visuals.Breadboard({}),a=function(t){let n=e.allocateDefinitions(t),s=[],i=[],r=1;n.partsAndWires.forEach(e=>{let t=e.part,n=e.wires;e.assembly.forEach((e,o)=>{e.part&&t&&(i[r+o]=[t]),e.wireIndices&&e.wireIndices.length>0&&n&&(s[r+o]=e.wireIndices.map(e=>n[e]))}),r+=e.assembly.length});let o=r-1,a=n.partsAndWires.map(e=>e.part).filter(e=>!!e),l=n.partsAndWires.map(e=>e.wires||[]).reduce((e,t)=>e.concat(t),[]),u={},c=[];return l.forEach(e=>{u[e.color]||(u[e.color]=[],c.push(e.color)),u[e.color].push(e)}),{boardDef:t.boardDef,cmpDefs:t.partDefs,fnArgs:t.fnArgs,allAlloc:n,stepToWires:s,stepToCmps:i,allWires:l,allCmps:a,lastStep:o,colorToWires:u,allWireColors:c}}({boardDef:n.boardDef,partDefs:r,partsList:n.parts,fnArgs:n.fnArgs,getBBCoord:o.getCoord.bind(o)});a.allAlloc.requiresBreadboard=!0;!function(e){let t=document.getElementById("front-panel"),n=g(e,400,!1);n.addAll(e.allAlloc),t.appendChild(n.getView())}(a);let l=v(a);t.appendChild(l);for(let e=0;e<=a.lastStep;e++){let n=y(e,a);t.appendChild(n)}n.print&&e.print(2e3)}t.renderParts=S,t.renderInstructions=function(e){document.getElementById("proj-title").innerText=e.options.name||"",S(document.body,e.options)}}(e.instructions||(e.instructions={}))}(pxsim||(pxsim={})),function(e){function t(e,t="sim: check failed"){if(!e)throw new Error(t)}e.quiet=!1,e.check=t,e.title="";let n,s,i,r,o,a={},l={};e.getConfig=function(e){return l.hasOwnProperty(e+"")?l[e+""]:null},e.getConfigKey=function(e){return a.hasOwnProperty(e)?a[e]:null},e.getAllConfigKeys=function(){return Object.keys(a)},e.setConfigKey=function(e,t){a[e]=t},e.setConfig=function(e,t){l[e]=t},e.setConfigData=function(e,t){l=e,a=t},e.getConfigData=function(){return{cfg:l,cfgKey:a}},e.setTitle=function(t){e.title=t};class u{constructor(){e.runtime?this.id=e.runtime.registerLiveObject(this):this.id=0}destroy(){}scan(t){throw e.U.userError("scan not implemented")}gcKey(){throw e.U.userError("gcKey not implemented")}gcSize(){throw e.U.userError("gcSize not implemented")}gcIsStatic(){return!1}print(){e.runtime&&e.runtime.refCountingDebug&&e.log(`RefObject id:${this.id}`)}toDebugString(){return"(object)"}static toAny(e){return e&&e.toAny?e.toAny():e}static fromAny(t){return t?t instanceof u?t:Array.isArray(t)?e.RefCollection.fromAny(t):"object"==typeof t?h.fromAny(t):t:t}static toDebugString(e){return null===e?"null":void 0===e?"undefined;":e.vtable&&e.vtable.name?"_Map"===e.vtable.name&&e instanceof f?"(object)":e.vtable.name:e.toDebugString?e.toDebugString():e.vtable&&e.vtable.name?e.vtable.name:"string"==typeof e?JSON.stringify(e):e.toString()}}e.RefObject=u;class c{constructor(e,t,n){this.func=e,this.caps=t,this.args=n}}e.FnWrapper=c;class h extends u{constructor(){super(...arguments),this.fields={}}scan(e){for(let t of Object.keys(this.fields))e(t,this.fields[t])}gcKey(){return this.vtable.name}gcSize(){return this.vtable.numFields+1}destroy(){this.fields=null,this.vtable=null}print(){e.runtime&&e.runtime.refCountingDebug&&e.log(`RefRecord id:${this.id} (${this.vtable.name})`)}toDebugString(){let e="RefRecord: {";const t=Object.keys(this.fields);for(let n=0;n<t.length;++n)n>0&&(e+=", "),e+=t[n]+": "+u.toDebugString(this.fields[t[n]]);return e+"}"}toAny(){const e={};for(let t of Object.keys(this.fields))e[t]=u.toAny(this.fields[t]);return e}static fromAny(e){const t=new h;for(let n of Object.keys(e))t.fields[n]=u.fromAny(e[n]);return t}}e.RefRecord=h;class d extends u{constructor(){super(...arguments),this.fields=[]}scan(e){for(let t=0;t<this.fields.length;++t)e("_cap"+t,this.fields[t])}gcKey(){return e.functionName(this.func)}gcSize(){return this.fields.length+3}isRef(e){return t(0<=e&&e<this.fields.length),e<this.len}ldclo(e){return t(0<=(e>>=2)&&e<this.fields.length),this.fields[e]}destroy(){this.fields=null,this.func=null}print(){e.runtime&&e.runtime.refCountingDebug&&e.log(`RefAction id:${this.id} len:${this.fields.length}`)}}e.RefAction=d,function(t){t.seedAddRandom=function(e){},t.mkAction=function(e,t){let n=new d;n.len=e,n.func=t;for(let t=0;t<e;++t)n.fields.push(null);return n},t.runAction=function(t,n){let s=e.getResume();s(t instanceof d?new c(t.func,t.fields,n):new c(t,null,n))};let n={};t.dumpPerfCounters=function(){if(!e.runtime||!e.runtime.perfCounters)return;let t="calls,us,name\n";for(let n of e.runtime.perfCounters){n.lastFew.sort();const e=n.lastFew[n.lastFew.length>>1];t+=`${n.numstops},${n.value},${n.name},${e}\n`}!function(t){let s="";const i=(e,t)=>{s+=e.length>=t?e:(" "+e).slice(-t)},r=(e,t)=>{s+=e.length>=t?e:(e+" ").slice(0,t)},o=e=>i(""+Math.round(e),6),a=(e,t)=>{i(Math.round(t)+"",8),s+=" /",o(e),s+=" =",o(t/e)};for(let e of t.split(/\n/)){if(!e)continue;if(!/^\d/.test(e))continue;const t=e.split(/,/);let i=n[t[2]];i||(n[t[2]]=i={stops:0,us:0,meds:[]}),r(t[2],25);const l=parseInt(t[0]),u=parseInt(t[1]);a(l,u),s+=" |",a(l-i.stops,u-i.us),s+=" ~";const c=parseInt(t[3]);o(c),i.meds.length>10&&i.meds.shift(),i.meds.push(c);const h=i.meds.slice();h.sort((e,t)=>e-t);const d=h[h.length>>1];s+=" ~~",o(d),i.stops=l,i.us=u,s+="\n"}e.log(s)}(t)}}(n=e.pxtcore||(e.pxtcore={}));class p extends u{constructor(){super(...arguments),this.v=void 0}scan(e){e("*",this.v)}gcKey(){return"LOC"}gcSize(){return 2}destroy(){}print(){e.runtime&&e.runtime.refCountingDebug&&e.log(`RefRefLocal id:${this.id} v:${this.v}`)}}e.RefRefLocal=p;class f extends u{constructor(){super(...arguments),this.vtable=e.mkMapVTable(),this.data=[]}scan(e){for(let t of this.data)e(t.key,t.val)}gcKey(){return"{...}"}gcSize(){return 2*this.data.length+4}findIdx(e){e+="";for(let t=0;t<this.data.length;++t)if(this.data[t].key==e)return t;return-1}destroy(){super.destroy();for(let e=0;e<this.data.length;++e)this.data[e].val=0;this.data=[]}print(){e.runtime&&e.runtime.refCountingDebug&&e.log(`RefMap id:${this.id} size:${this.data.length}`)}toDebugString(){let e="RefMap: {";for(let t=0;t<this.data.length;++t)t>0&&(e+=", "),e+=this.data[t].key+": "+u.toDebugString(this.data[t].val);return e+"}"}toAny(){const e={};return this.data.forEach(t=>{e[t.key]=u.toAny(t.val)}),e}static fromAny(e){const t=new f;for(let n of Object.keys(e))t.data.push({key:n,val:u.fromAny(e[n])});return t}}function m(){e.runtime&&e.runtime.dumpLivePointers()}e.RefMap=f,e.dumpLivePointers=m,function(e){e.toString=function(e){return null===e?"null":void 0===e?"undefined":e.toString()},e.toBoolDecr=function(e){return!!e},e.toBool=function(e){return!!e}}(s=e.numops||(e.numops={})),function(e){e.toInt=function(e){return 0|e},e.toFloat=function(e){return e},e.ignore=function(e){return e}}(i=e.langsupp||(e.langsupp={})),function(t){t.ptrOfLiteral=function(e){return e},t.debugMemLeaks=function(){m()},t.templateHash=function(){return 0},t.programHash=function(){return 0},t.programName=function(){return e.title},t.programSize=function(){return 0},t.afterProgramPage=function(){return 0},t.getConfig=function(t,n){let s=e.getConfig(t);return null==s?n:s},t.toInt=function(e){return e|0},t.toUInt=function(e){return e>>>0},t.toDouble=function(e){return e},t.toFloat=function(e){return e},t.fromInt=function(e){return e},t.fromUInt=function(e){return e},t.fromDouble=function(e){return e},t.fromFloat=function(e){return e},t.fromBool=function(e){return!!e}}(n=e.pxtcore||(e.pxtcore={})),function(n){function s(t,n){if(t||e.throwFailedPropertyAccessError(t,n),n+="",t instanceof h){return t.fields[n]}let s=t.findIdx(n);if(!(s<0))return t.data[s].val}function i(t,n,s){if(t||e.throwFailedPropertyAccessError(t,n),n+="",t instanceof h){return void(t.fields[n]=s)}let i=t.findIdx(n);i<0?t.data.push({key:n,val:s}):t.data[i].val=s}n.toInt8=function(e){return(255&e)<<24>>24},n.toInt16=function(e){return(65535&e)<<16>>16},n.toInt32=function(e){return 0|e},n.toUInt32=function(e){return e>>>0},n.toUInt8=function(e){return 255&e},n.toUInt16=function(e){return 65535&e},n.nullFix=function(e){return null==e||!1===e?0:!0===e?1:e},n.nullCheck=function(t){null==t&&e.U.userError("Dereferencing null/undefined value.")},n.panic=function(t){e.U.userError("PANIC! Code "+t)},n.stringToBool=function(e){return e?1:0},n.ptrToBool=function(e){return e?1:0},n.emptyToNull=function(e){return""==e?0:e},n.ldlocRef=function(e){return e.v},n.stlocRef=function(e,t){e.v=t},n.mklocRef=function(){return new p},n.stclo=function(e,n,s){return t(0<=n&&n<e.fields.length),t(null===e.fields[n]),e.fields[n]=s,e},n.runtimeWarning=function(t){e.Runtime.postMessage(e.getWarningMessage(t))},n.mkMap=function(){return new f},n.mapGet=function(e,t){return s(e,n.mapKeyNames[t])},n.mapSet=function(e,t,s){return i(e,n.mapKeyNames[t],s)},n.mapGetByString=s,n.mapDeleteByString=function(t,n){null==t&&e.throwNullUndefinedAsObjectError(),t instanceof f||e.throwFailedCastError(t,"object");let s=t.findIdx(n);return s>=0&&t.data.splice(s,1),!0},n.mapSetGeneric=i,n.mapGetGeneric=s,n.mapSetByString=i,n.keysOf=function(t){null==t&&e.throwNullUndefinedAsObjectError();let n=new e.RefCollection;if(t instanceof f)for(let e of t.data)n.push(e.key);return n}}(r=e.pxtrt||(e.pxtrt={})),function(e){e.mkClassInstance=function(e){t(!!e.methods);let n=new h;return n.vtable=e,n},e.switch_eq=function(e,t){return e==t},e.typeOf=function(e){return typeof e}}(n=e.pxtcore||(e.pxtcore={})),function(t){function n(t){t&&(t instanceof d||t.info)||e.throwFailedCastError(t,"function")}t.panic=r.panic,t.pause=function(t){let n=e.getResume();e.runtime.schedule(()=>{n()},t)},t.runInBackground=function(t){n(t),e.runtime.runFiberAsync(t)},t.forever=function(t){n(t),function n(){e.runtime.runFiberAsync(t).then(()=>e.U.delay(20)).then(n)}()},t.typeCheck=n}(o=e.thread||(e.thread={}))}(pxsim||(pxsim={})),function(e){class t extends e.RefObject{constructor(){super(),this.data=[]}scan(e){for(let t=0;t<this.data.length;++t)e("["+t+"]",this.data[t])}gcKey(){return"[...]"}gcSize(){return this.data.length+2}toArray(){return this.data.slice(0)}toAny(){return this.data.map(t=>e.RefObject.toAny(t))}static fromAny(n,s=!0){const i=new t;return i.data=s?n.map(t=>e.RefObject.fromAny(t)):n.slice(0),i}toDebugString(){let t="[";for(let n=0;n<this.data.length;++n){n>0&&(t+=",");let s=e.RefObject.toDebugString(this.data[n]);if(t.length+s.length>100){0==n&&(t+=s.substr(0,100)),t+="...";break}t+=s}return t+="]",t}destroy(){let e=this.data;for(let t=0;t<e.length;++t)e[t]=0;this.data=[]}isValidIndex(e){return e>=0&&e<this.data.length}push(e){this.data.push(e)}pop(){return this.data.pop()}getLength(){return this.data.length}setLength(e){this.data.length=e}getAt(e){return this.data[e]}setAt(e,t){this.data[e]=t}insertAt(e,t){this.data.splice(e,0,t)}removeAt(e){return this.data.splice(e,1)[0]}indexOf(e,t){return this.data.indexOf(e,t)}print(){}}let n,s,i,r,o,a,l,u;e.RefCollection=t,function(n){function s(e,t){if(r(e),e.isValidIndex(t))return e.removeAt(t)}function i(e,t,n){return r(e),e.indexOf(t,n)}function r(n){n instanceof t||e.throwFailedCastError(n,"Array")}n.mk=function(){return new t},n.isArray=function(e){return e instanceof t},n.length=function(e){return r(e),e.getLength()},n.setLength=function(e,t){r(e),e.setLength(t)},n.push=function(e,t){r(e),e.push(t)},n.pop=function(e,t){return r(e),e.pop()},n.getAt=function(e,t){return r(e),e.getAt(t)},n.removeAt=s,n.insertAt=function(e,t,n){r(e),e.insertAt(t,n)},n.setAt=function(e,t,n){r(e),e.setAt(t,n)},n.indexOf=i,n.removeElement=function(e,t){r(e);let n=i(e,t,0);return n>=0?(s(e,n),1):0},n.typeCheck=r}(n=e.Array_||(e.Array_={})),function(e){e.imul=Math.imul||function(e,t){const n=65535&e,s=65535&t;return n*s+((e>>>16&65535)*s+n*(t>>>16&65535)<<16>>>0)|0},e.idiv=function(e,t){return(0|e)/(0|t)|0},e.round=function(e){return Math.round(e)},e.roundWithPrecision=function(e,t){if((t|=0)<=0)return Math.round(e);if(0==e)return 0;let n=0;for(;0==n&&t<21;){const s=Math.pow(10,t++);n=Math.round(e*s+Number.EPSILON)/s}return n},e.ceil=function(e){return Math.ceil(e)},e.floor=function(e){return Math.floor(e)},e.sqrt=function(e){return Math.sqrt(e)},e.pow=function(e,t){return Math.pow(e,t)},e.clz32=function(e){return Math.clz32(e)},e.log=function(e){return Math.log(e)},e.log10=function(e){return Math.log10(e)},e.log2=function(e){return Math.log2(e)},e.exp=function(e){return Math.exp(e)},e.sin=function(e){return Math.sin(e)},e.sinh=function(e){return Math.sinh(e)},e.cos=function(e){return Math.cos(e)},e.cosh=function(e){return Math.cosh(e)},e.tan=function(e){return Math.tan(e)},e.tanh=function(e){return Math.tanh(e)},e.asin=function(e){return Math.asin(e)},e.asinh=function(e){return Math.asinh(e)},e.acos=function(e){return Math.acos(e)},e.acosh=function(e){return Math.acosh(e)},e.atan=function(e){return Math.atan(e)},e.atanh=function(e){return Math.atanh(e)},e.atan2=function(e,t){return Math.atan2(e,t)},e.trunc=function(e){return e>0?Math.floor(e):Math.ceil(e)},e.random=function(){return Math.random()},e.randomRange=function(e,t){if(e==t)return e;if(e>t){let n=e;e=t,t=n}return Math.floor(e)==e&&Math.floor(t)==t?e+Math.floor(Math.random()*(t-e+1)):e+Math.random()*(t-e)}}(s=e.Math_||(e.Math_={})),function(t){function n(t,n){return e.pxtrt.nullFix(t)==e.pxtrt.nullFix(n)}t.lt=function(e,t){return e<t},t.le=function(e,t){return e<=t},t.neq=function(e,t){return!n(e,t)},t.eq=n,t.eqDecr=function(t,n){return e.pxtrt.nullFix(t)==e.pxtrt.nullFix(n)},t.gt=function(e,t){return e>t},t.ge=function(e,t){return e>=t},t.div=function(e,t){return 0|Math.floor(e/t)},t.mod=function(e,t){return e%t},t.bnot=function(e){return~e},t.toString=function(e){return e+""}}(i=e.Number_||(e.Number_={})),function(e){e.adds=function(e,t){return e+t|0},e.subs=function(e,t){return e-t|0},e.divs=function(e,t){return 0|Math.floor(e/t)},e.muls=function(e,t){return s.imul(e,t)},e.ands=function(e,t){return e&t},e.orrs=function(e,t){return e|t},e.eors=function(e,t){return e^t},e.lsls=function(e,t){return e<<t},e.lsrs=function(e,t){return e>>>t},e.asrs=function(e,t){return e>>t},e.bnot=function(e){return~e},e.ignore=function(e){return e}}(r=e.thumb||(e.thumb={})),function(e){function t(e){return e<<16>>16}e.adds=function(e,n){return t(e+n)},e.subs=function(e,n){return t(e-n)},e.divs=function(e,n){return t(Math.floor(e/n))},e.muls=function(e,n){return t(s.imul(e,n))},e.ands=function(e,n){return t(e&n)},e.orrs=function(e,n){return t(e|n)},e.eors=function(e,n){return t(e^n)},e.lsls=function(e,n){return t(e<<n)},e.lsrs=function(e,t){return(65535&e)>>>t},e.asrs=function(e,n){return t(e>>n)},e.bnot=function(e){return~e},e.ignore=function(e){return e}}(o=e.avr||(e.avr={})),function(t){function n(t){"string"!=typeof t&&e.throwFailedCastError(t,"string")}t.stringConv=function(t){const n=e.getResume();t instanceof e.RefRecord&&t.vtable.toStringMethod?e.runtime.runFiberAsync(t.vtable.toStringMethod,t).then(()=>{n(e.runtime.currFrame.retval+"")}):n(t+"")},t.mkEmpty=function(){return""},t.fromCharCode=function(e){return String.fromCharCode(e)},t.toNumber=function(e){return n(e),parseFloat(e)},t.concat=function(e,t){return n(e),e+t},t.substring=function(e,t,s){return n(e),e.slice(t,t+s)},t.equals=function(e,t){return n(e),e==t},t.compare=function(e,t){return n(e),e==t?0:e<t?-1:1},t.compareDecr=function(e,t){return n(e),e==t?0:e<t?-1:1},t.length=function(e){return n(e),e.length},t.substr=function(e,t,s){return n(e),e.substr(t,s)},t.charAt=function(e,t){return n(e),e.charAt(t)},t.charCodeAt=function(e,t){return n(e),function(e,t){return n(e),0<=t&&t<e.length}(e,t)?e.charCodeAt(t):0},t.indexOf=function(e,t,s){return n(e),null==t?-1:e.indexOf(t,s)},t.lastIndexOf=function(e,t,s){return n(e),null==t?-1:e.lastIndexOf(t,s)},t.includes=function(e,t,s){return n(e),null!=t&&e.includes(t,s)},t.typeCheck=n}(a=e.String_||(e.String_={})),function(e){e.toString=function(e){return e?"true":"false"},e.bang=function(e){return!e}}(l=e.Boolean_||(e.Boolean_={}));class c extends e.RefObject{constructor(e){super(),this.data=e,this.isStatic=!1}scan(e){}gcKey(){return"Buffer"}gcSize(){return 2+(this.data.length+3>>2)}gcIsStatic(){return this.isStatic}print(){}toDebugString(){return u.toHex(this)}}e.RefBuffer=c,function(t){let n;function s(t){let s=function(t){switch(t){case n.Int8LE:return-1;case n.UInt8LE:return 1;case n.Int16LE:return-2;case n.UInt16LE:return 2;case n.Int32LE:return-4;case n.UInt32LE:return 4;case n.Int8BE:return-10;case n.UInt8BE:return 10;case n.Int16BE:return-20;case n.UInt16BE:return 20;case n.Int32BE:return-40;case n.UInt32BE:return 40;case n.Float32LE:return 4;case n.Float32BE:return 40;case n.Float64LE:return 8;case n.Float64BE:return 80;default:throw e.U.userError("bad format")}}(t),i=!1;s<0&&(i=!0,s=-s);let r=!1;return s>=10&&(r=!0,s/=10),{size:s,signed:i,swap:r,isFloat:t>=n.Float32LE}}function i(e){return new c(new Uint8Array(e))}function r(e,t){return 0<=t&&t<e.data.length}function o(e,t){return f(e),r(e,t)?e.data[t]:0}function l(t){t.isStatic&&e.U.userError("Writing to read only buffer.")}function u(e,t,n){f(e),r(e,t)&&(l(e),e.data[t]=n)}function h(e,t,n=0,s=-1){f(e),n<0||n>e.data.length||(s<0&&(s=e.data.length),s=Math.min(s,e.data.length-n),l(e),e.data.fill(t,n,n+s))}function d(e,t,n,s,i){if(n.buffer===e.buffer)d(e,t,n.slice(s,s+i),0,i);else for(let r=0;r<i;++r)e[t+r]=n[s+r]}!function(e){e[e.Int8LE=1]="Int8LE",e[e.UInt8LE=2]="UInt8LE",e[e.Int16LE=3]="Int16LE",e[e.UInt16LE=4]="UInt16LE",e[e.Int32LE=5]="Int32LE",e[e.Int8BE=6]="Int8BE",e[e.UInt8BE=7]="UInt8BE",e[e.Int16BE=8]="Int16BE",e[e.UInt16BE=9]="UInt16BE",e[e.Int32BE=10]="Int32BE",e[e.UInt32LE=11]="UInt32LE",e[e.UInt32BE=12]="UInt32BE",e[e.Float32LE=13]="Float32LE",e[e.Float64LE=14]="Float64LE",e[e.Float32BE=15]="Float32BE",e[e.Float64BE=16]="Float64BE"}(n=t.NumberFormat||(t.NumberFormat={})),t.fmtInfo=s,t.getNumber=function(e,t,n){f(e);let i=s(t);if(i.isFloat){let t=e.data.buffer.slice(n,n+i.size);if(i.swap){new Uint8Array(t).reverse()}return 4==i.size?new Float32Array(t)[0]:new Float64Array(t)[0]}let r=0;for(let t=0;t<i.size;++t){r<<=8;let s=i.swap?n+t:n+i.size-t-1;r|=e.data[s]}if(i.signed){let e=32-8*i.size;r=r<<e>>e}else r>>>=0;return r},t.setNumber=function(e,t,n,i){f(e);let r=s(t);if(r.isFloat){let t=new Uint8Array(r.size);4==r.size?new Float32Array(t.buffer)[0]=i:new Float64Array(t.buffer)[0]=i,r.swap&&t.reverse();for(let s=0;s<r.size;++s)e.data[n+s]=t[s];return}for(let t=0;t<r.size;++t){let s=r.swap?n+r.size-t-1:n+t;e.data[s]=255&i,i>>=8}},t.createBuffer=i,t.createBufferFromHex=function(e){a.typeCheck(e);let t=i(e.length>>1);for(let n=0;n<e.length;n+=2)t.data[n>>1]=parseInt(e.slice(n,n+2),16);return t.isStatic=!0,t},t.isReadOnly=function(e){return f(e),e.isStatic},t.getBytes=function(e){return f(e),e.data},t.getUint8=function(e,t){return f(e),o(e,t)},t.getByte=o,t.setUint8=function(e,t,n){f(e),u(e,t,n)},t.setByte=u,t.length=function(e){return f(e),e.data.length},t.fill=h,t.slice=function(e,t,n){return f(e),t=Math.min(e.data.length,t),n<0&&(n=e.data.length),n=Math.min(n,e.data.length-t),new c(e.data.slice(t,t+n))},t.toHex=function(e){f(e);const t="0123456789abcdef";let n="";for(let s=0;s<e.data.length;++s)n+=t[e.data[s]>>4],n+=t[15&e.data[s]];return n},t.toString=function(t){return f(t),e.U.fromUTF8Array(t.data)};const p=-2147483648;function f(t){t instanceof c||e.throwFailedCastError(t,"Buffer")}t.shift=function(e,t,n,s){f(e),s<0&&(s=e.data.length-n),n<0||n+s>e.data.length||n+s<n||0==s||0==t||t==p||0!=s&&0!=t&&t!=p&&(t<=-s||t>=s?h(e,0):(l(e),t<0?(t=-t,d(e.data,n+t,e.data,n,s-t),e.data.fill(0,n,n+t)):(s-=t,d(e.data,n,e.data,n+t,s),e.data.fill(0,n+s,n+s+t))))},t.rotate=function(e,t,n,s){if(f(e),s<0&&(s=e.data.length-n),n<0||n+s>e.data.length||n+s<n||0==s||0==t||t==p)return;l(e),t<0&&(t+=s<<8),(t%=s)<0&&(t+=s);let i=e.data,r=t,o=0,a=r,u=s;for(;o!=a;){let e=i[o+n];i[o+++n]=i[a+n],i[a+++n]=e,a==u?a=r:o==r&&(r=a)}},t.write=function(e,t,n,s=0,i=-1){f(e),f(n),i<0&&(i=n.data.length),s<0||t<0||t>e.data.length||(i=Math.min(n.data.length-s,e.data.length-t))<0||(l(e),d(e.data,t,n.data,s,i))},t.typeCheck=f}(u=e.BufferMethods||(e.BufferMethods={}))}(pxsim||(pxsim={})),function(e){!function(t){t.createBufferFromUTF8=function(t){return e.String_.typeCheck(t),new e.RefBuffer(e.U.toUTF8Array(t))}}(e.control||(e.control={}))}(pxsim||(pxsim={})),function(e){!function(e){let t={};e.setLocalizedStrings=function(e){t=e||{}};function n(e,t){return 0==t.length?e:e.replace(/\{([0-9]+)(\:[^\}]+)?\}/g,function(e,n,r){let o=t[parseInt(n)],a="",l=/^:f(\d*)\.(\d+)/.exec(r);if(l){let e=parseInt(l[2]),t=parseInt(l[1])||0,n=/^0/.test(l[1])?"0":" ",s=o.toFixed(e);if(t>0&&e>0&&(t+=e+1),t>0)for(;s.length<t;)s=n+s;a=s}else a=":x"==r?"0x"+o.toString(16):void 0===o?"(undef)":null===o?"(null)":o.toString?o.toString():o+"";return":a"==r?/^\s*[euioah]/.test(a.toLowerCase())?a="an "+a:/^\s*[bcdfgjklmnpqrstvwxz]/.test(a.toLowerCase())&&(a="a "+a):":s"==r?a=1==o?"":"s":":q"==r?a=s(a):":jq"==r?a=i(a):":uri"==r?a=encodeURIComponent(a).replace(/'/g,"%27").replace(/"/g,"%22"):":url"==r?a=encodeURI(a).replace(/'/g,"%27").replace(/"/g,"%22"):":%"==r&&(a=(100*o).toFixed(1).toString()+"%"),a})}function s(e){return e?e.replace(/([^\w .!?\-$])/g,e=>"&#"+e.charCodeAt(0)+";"):e}function i(e){return e.replace(/[^\w .!?\-$]/g,e=>{let t=e.charCodeAt(0).toString(16);return"\\u"+"0000".substr(0,4-t.length)+t})}e.lf=function(e,...s){let i=t[e]||e;return i=i.replace(/^\{(id|loc):[^\}]+\}/g,""),n(i,s)},e.fmt_va=n,e.htmlEscape=s,e.jsStringQuote=i}(e.localization||(e.localization={}))}(pxsim||(pxsim={})),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={}));e.ConsoleLogger=class{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}};let n=new e.ConsoleLogger;e.info=function(...e){n.info(...e)},e.log=function(...e){n.log(...e)},e.debug=function(...e){n.debug(...e)},e.error=function(...e){n.error(...e)},e.warn=function(...e){n.warn(...e)},e.setLogger=function(e){const t=null==n?void 0:n.getLogLevel();n=e,void 0!==t&&n.setLogLevel(t)},e.setLogLevel=function(e){n.setLogLevel(e)}}(pxsim||(pxsim={})),function(pxsim){const MIN_MESSAGE_WAIT_MS=200;let tracePauseMs=0,MessageListenerFlags,U,pxtcore;!function(e){e[e.MESSAGE_BUS_LISTENER_REENTRANT=8]="MESSAGE_BUS_LISTENER_REENTRANT",e[e.MESSAGE_BUS_LISTENER_QUEUE_IF_BUSY=16]="MESSAGE_BUS_LISTENER_QUEUE_IF_BUSY",e[e.MESSAGE_BUS_LISTENER_DROP_IF_BUSY=32]="MESSAGE_BUS_LISTENER_DROP_IF_BUSY",e[e.MESSAGE_BUS_LISTENER_IMMEDIATE=192]="MESSAGE_BUS_LISTENER_IMMEDIATE"}(MessageListenerFlags||(MessageListenerFlags={})),function(e){function t(e){return e.split(/\s+/).filter(e=>!!e)}function n(e){for(;e.firstChild;)e.removeChild(e.firstChild)}let s;e.containsClass=function(e,n){return t(n).every(t=>function(e,t){if(e.classList)return e.classList.contains(t);return!((e.className+"").split(/\s+/).indexOf(t)<0)}(e,t))},e.addClass=function(e,n){t(n).forEach(t=>function(e,t){if(e.classList)e.classList.add(t);else{(e.className+"").split(/\s+/).indexOf(t)<0&&(e.className.baseVal+=" "+t)}}(e,t))},e.removeClass=function(e,n){t(n).forEach(t=>function(e,t){e.classList?e.classList.remove(t):e.className.baseVal=(e.className+"").split(/\s+/).filter(e=>e!=t).join(" ")}(e,t))},e.remove=function(e){e.parentElement.removeChild(e)},e.removeChildren=n,e.clear=function(e){n(e)},e.assert=function(e,t="Assertion failed"){if(!e)throw new Error(t)},e.repeatMap=function(e,t){e=e||0;let n=[];for(let s=0;s<e;++s)n.push(t(s));return n},e.userError=function(e){let t=new Error(e);throw t.isUserError=!0,t},e.now=function(){return Date.now()},e.perfNowUs=function(){return s||(s="undefined"!=typeof performance?performance.now.bind(performance)||performance.moznow.bind(performance)||performance.msNow.bind(performance)||performance.webkitNow.bind(performance)||performance.oNow.bind(performance):Date.now),1e3*s()};const i=Promise.resolve();async function r(e,t,n){let s=0;const i=[],r=[];for(let o=0;o<e;o++){const e=(async()=>{for(;s<t.length;){const e=s++,i=t[e];r[e]=await n(i)}})();i.push(e)}try{await Promise.all(i)}catch(e){throw s=t.length,e}return r}function o(){return"undefined"!=typeof window&&!!window.pxtElectron}function a(){return"undefined"!=typeof window&&!!window.ipcRenderer}function l(){return o()||a()}function u(e){return/^http:\/\/(?:localhost|127\.0\.0\.1|192\.168\.\d{1,3}\.\d{1,3}|[a-zA-Z0-9.-]+\.local):\d+\/?/.test(e)&&!/nolocalhost=1/.test(e)}function c(){try{return"undefined"!=typeof window&&u(window.location.href)}catch(e){return!1}}e.nextTick=function(e){i.then(e)},e.delay=async function(e,t){const n=await t;return await new Promise(t=>setTimeout(()=>t(),e)),n},e.throttle=function(e,t,n){let s;return function(){let i=this,r=arguments,o=n&&!s;s||(s=setTimeout(function(){s=null,n||e.apply(i,r)},t)),o&&e.apply(i,r)}},e.promiseMapAll=function(e,t){return Promise.all(e.map(e=>t(e)))},e.promiseMapAllSeries=function(e,t){return r(1,e,t)},e.promisePoolAsync=r,e.promiseTimeout=async function(e,t,n){let s,i;const r=new Promise((t,r)=>{i=t,s=setTimeout(()=>{i=void 0,clearTimeout(s),r(n||`Promise timed out after ${e}ms`)},e)});return Promise.race([t,r]).then(e=>(i&&(clearTimeout(s),i()),e))},e.stringToUint8Array=function(e){let t=e.length,n=new Uint8Array(t);for(let s=0;s<t;++s)n[s]=255&e.charCodeAt(s);return n},e.uint8ArrayToString=function(e){let t=e.length,n="";for(let s=0;s<t;++s)n+=String.fromCharCode(e[s]);return n},e.fromUTF8=function(e){if(!e)return"";let t="";for(let n=0;n<e.length;++n){let s=255&e.charCodeAt(n);t+=37==s||s>127?"%"+s.toString(16):e.charAt(n)}return decodeURIComponent(t)},e.toUTF8=function(e,t){let n="";if(!e)return n;for(let s=0;s<e.length;++s){let i=e.charCodeAt(s);if(i<=127)n+=e.charAt(s);else if(i<=2047)n+=String.fromCharCode(192|i>>6,128|63&i);else{if(!t&&55296<=i&&i<=56319){let t=e.charCodeAt(++s);isNaN(t)||(i=65536+(i-55296<<10)+(t-56320))}n+=i<=65535?String.fromCharCode(224|i>>12,128|i>>6&63,128|63&i):String.fromCharCode(240|i>>18,128|i>>12&63,128|i>>6&63,128|63&i)}}return n},e.toUTF8Array=function(e){return(new TextEncoder).encode(e)},e.fromUTF8Array=function(e){return(new TextDecoder).decode(e)},e.isPxtElectron=o,e.isIpcRenderer=a,e.isElectron=l,e.testLocalhost=u,e.isLocalHost=c,e.isLocalHostDev=function(){return c()&&!l()},e.unique=function(e,t){let n=[],s={};return e.forEach(e=>{let i=t(e);s.hasOwnProperty(i)||(s[i]=null,n.push(e))}),n},e.sanitizeCssName=function(e){let t=e.replace(/[^a-zA-Z0-9-_]/g,"_");return/^[a-zA-Z_]/.test(t)||(t="cls_"+t),t}}(U=pxsim.U||(pxsim.U={}));class BreakLoopException{}function getResume(){return pxsim.runtime.getResume()}pxsim.BreakLoopException=BreakLoopException,function(e){function t(e){let t=pxsim.runtime.currTryFrame();t||U.userError("unhandled exception: "+e);const n=t.handlerFrame;throw pxsim.runtime.currFrame=n,n.pc=t.handlerPC,n.tryFrame=t.parent,n.thrownValue=e,n.hasThrownValue=!0,new BreakLoopException}e.beginTry=function(e){pxsim.runtime.currFrame.tryFrame={parent:pxsim.runtime.currTryFrame(),handlerPC:e,handlerFrame:pxsim.runtime.currFrame}},e.endTry=function(){const e=pxsim.runtime.currFrame;e.tryFrame=e.tryFrame.parent},e.throwValue=t,e.getThrownValue=function(){const e=pxsim.runtime.currFrame;return U.assert(e.hasThrownValue),e.hasThrownValue=!1,e.thrownValue},e.endFinally=function(){const e=pxsim.runtime.currFrame;e.hasThrownValue&&(e.hasThrownValue=!1,t(e.thrownValue))}}(pxtcore=pxsim.pxtcore||(pxsim.pxtcore={})),pxsim.getResume=getResume;const SERIAL_BUFFER_LENGTH=16;class BaseBoard{constructor(){this.messageListeners=[],this.serialOutBuffer="",this.messages=[],this.lastSerialTime=0,this.debouncedPostAll=()=>{const e=Date.now();e-this.lastSerialTime>MIN_MESSAGE_WAIT_MS?(clearTimeout(this.serialTimeout),this.messages.length&&(Runtime.postMessage({type:"bulkserial",data:this.messages,id:pxsim.runtime.id,sim:!0}),this.messages=[],this.lastSerialTime=e)):this.serialTimeout=setTimeout(this.debouncedPostAll,50)},this.id=pxsim.Embed.frameid||"b"+Math.round(2147483647*Math.random()),this.bus=new pxsim.EventBus(pxsim.runtime,this)}updateView(){}receiveMessage(e){pxsim.runtime&&!pxsim.runtime.dead&&this.dispatchMessage(e)}dispatchMessage(e){for(const t of this.messageListeners)t(e)}addMessageListener(e){this.messageListeners.push(e)}get storedState(){return this.runOptions?(this.runOptions.storedState||(this.runOptions.storedState={}),this.runOptions.storedState):{}}initAsync(e){return this.runOptions=e,Promise.resolve()}setStoredState(e,t){null==t?delete this.storedState[e]:this.storedState[e]=t,Runtime.postMessage({type:"simulator",command:"setstate",stateKey:e,stateValue:t})}onDebuggerResume(){}screenshotAsync(e){return Promise.resolve(void 0)}kill(){}writeSerial(e){this.serialOutBuffer+=e,(/\n/.test(this.serialOutBuffer)||this.serialOutBuffer.length>SERIAL_BUFFER_LENGTH)&&(this.messages.push({time:Date.now(),data:this.serialOutBuffer}),this.debouncedPostAll(),this.serialOutBuffer="")}}pxsim.BaseBoard=BaseBoard;class CoreBoard extends BaseBoard{constructor(){super(),this.updateSubscribers=[],this.updateView=()=>{this.updateSubscribers.forEach(e=>e())},this.builtinParts={},this.builtinVisuals={},this.builtinPartVisuals={}}kill(){super.kill(),pxsim.codal.music.__stopSoundExpressions(),pxsim.AudioContextManager.stopAll(),pxsim.AudioContextManager.SpatialAudioPlayer.disposeAll(),pxsim.AudioContextManager.setListenerPosition(0,0,0)}}pxsim.CoreBoard=CoreBoard;class BareBoard extends BaseBoard{}function initBareRuntime(){pxsim.runtime.board=new BareBoard;let e=pxsim;e.basic={pause:pxsim.thread.pause,showNumber:e=>{let t=getResume();pxsim.log("SHOW NUMBER:",e),U.nextTick(t)}},e.serial={writeString:e=>pxsim.runtime.board.writeSerial(e)},e.pins={createBuffer:pxsim.BufferMethods.createBuffer},e.control={inBackground:pxsim.thread.runInBackground,createBuffer:pxsim.BufferMethods.createBuffer,dmesg:e=>pxsim.log("DMESG: "+e),deviceDalVersion:()=>"sim",__log:(e,t)=>pxsim.log("LOG: "+t.trim())}}let LogType;pxsim.initBareRuntime=initBareRuntime,function(e){e[e.UserSet=0]="UserSet",e[e.BackAdd=1]="BackAdd",e[e.BackRemove=2]="BackRemove"}(LogType||(LogType={}));class EventHandler{constructor(e,t){this.handler=e,this.flags=t,this.busy=0}async runAsync(e,t,n){const s=this.flags||MessageListenerFlags.MESSAGE_BUS_LISTENER_QUEUE_IF_BUSY;if(s!==MessageListenerFlags.MESSAGE_BUS_LISTENER_IMMEDIATE)return s===MessageListenerFlags.MESSAGE_BUS_LISTENER_QUEUE_IF_BUSY?this.runFiberAsync(e,t,n):void(s===MessageListenerFlags.MESSAGE_BUS_LISTENER_DROP_IF_BUSY&&this.busy||this.runFiberAsync(e,t,n));U.userError("MESSAGE_BUS_LISTENER_IMMEDIATE is not supported!")}async runFiberAsync(e,t,n){this.busy++,await t.runFiberAsync(this.handler,...n?n(e):[e]),this.busy--}}class EventQueue{constructor(e,t){this.runtime=e,this.valueToArgs=t,this.max=5,this.events=[],this.awaiters=[],this._handlers=[],this._addRemoveLog=[]}push(e,t){if(this.awaiters.length>0)if(t){const e=this.awaiters.shift();e&&e()}else{const e=this.awaiters.slice();this.awaiters=[],e.forEach(e=>e())}return 0==this.handlers.length||this.events.length>this.max?Promise.resolve():(this.events.push(e),this.lock?Promise.resolve():this.poke())}async poke(){this.lock=!0;let e=this.events;this.events=[];for(const t of e)for(const e of this.handlers)await e.runAsync(t,this.runtime,this.valueToArgs);if(this.events.length>0)return this.poke();this.lock=!1;for(const e of this._addRemoveLog)e.log===LogType.BackAdd?this.addHandler(e.act,e.flags):e.log===LogType.BackRemove?this.removeHandler(e.act):this.setHandler(e.act,e.flags);this._addRemoveLog=[]}get handlers(){return this._handlers}setHandler(e,t=0){this.lock?this._addRemoveLog.push({act:e,log:LogType.UserSet,flags:t}):this._handlers=[new EventHandler(e,t)]}addHandler(e,t=0){this.lock?this._addRemoveLog.push({act:e,log:LogType.BackAdd,flags:t}):this._handlers.some(t=>t.handler===e)||this._handlers.push(new EventHandler(e,t))}removeHandler(e){if(this.lock)this._addRemoveLog.push({act:e,log:LogType.BackRemove,flags:0});else{let t=this._handlers.findIndex(t=>t.handler===e);-1!=t&&this._handlers.splice(t,1)}}addAwaiter(e){this.awaiters.push(e)}}function bind(e){const t=e.arg0,n=e.fn;return e=>{let s=0;for(;e.hasOwnProperty("arg"+s);)s++;const i=e;for(let e=s;e>0;e--)i["arg"+e]=i["arg"+(e-1)];return e.arg0=t,n(e)}}function _leave(e,t){return e.parent.retval=t,e.parent}function syntheticRefAction(e){return pxtcore.mkAction(0,t=>_leave(t,e(t)))}pxsim.EventQueue=EventQueue,pxsim.initCurrentRuntime=void 0,pxsim.handleCustomMessage=void 0,pxsim.syntheticRefAction=syntheticRefAction;class TimeoutScheduled{constructor(e,t,n,s){this.id=e,this.fn=t,this.totalRuntime=n,this.timestampCall=s}}pxsim.TimeoutScheduled=TimeoutScheduled;class PausedTimeout{constructor(e,t){this.fn=e,this.timeRemaining=t}}function mkVTable(e){return{name:e.name,numFields:e.numFields,classNo:e.classNo,methods:e.methods,iface:e.iface,lastSubtypeNo:e.lastSubtypeNo,toStringMethod:e.toStringMethod,maxBgInstances:e.maxBgInstances}}pxsim.PausedTimeout=PausedTimeout,pxsim.mkVTable=mkVTable;let mapVTable=null;function mkMapVTable(){return mapVTable||(mapVTable=mkVTable({name:"_Map",numFields:0,classNo:0,lastSubtypeNo:0,methods:null})),mapVTable}function functionName(e){const t=e.info;return t?`${t.functionName} (${t.fileName}:${t.line+1}:${t.column+1})`:"()"}pxsim.mkMapVTable=mkMapVTable,pxsim.functionName=functionName;class Runtime{constructor(msg){this.numGlobals=1e3,this.dead=!1,this.running=!1,this.idleTimer=void 0,this.recording=!1,this.recordingTimer=0,this.recordingLastImageData=void 0,this.recordingWidth=void 0,this.startTime=0,this.startTimeUs=0,this.pausedTime=0,this.lastPauseTimestamp=0,this.globals={},this.environmentGlobals={},this.otherFrames=[],this.loopLock=null,this.loopLockWaitList=[],this.heapSnapshots=[],this.timeoutsScheduled=[],this.timeoutsPausedOnBreakpoint=[],this.pausedOnBreakpoint=!1,this.traceDisabled=!1,this.perfOffset=0,this.perfElapsed=0,this.perfStack=0,this.refCountingDebug=!1,this.refObjId=1,this.numDisplayUpdates=0,U.assert(!!pxsim.initCurrentRuntime),this.id=msg.id,this.refCountingDebug=!!msg.refCountingDebug;let threadId=0,breakpoints=null,currResume,dbgHeap,dbgResume,breakFrame=null,lastYield=Date.now(),userGlobals,__this=this;this.traceDisabled=!!msg.traceDisabled;const yieldDelay=void 0!==msg.yieldDelay?msg.yieldDelay:5,evalIface={runtime:this,oops:oops,doNothing:doNothing,pxsim:pxsim,globals:this.globals,setupYield:setupYield,maybeYield:maybeYield,setupDebugger:setupDebugger,isBreakFrame:isBreakFrame,breakpoint:breakpoint,trace:trace,checkStack:checkStack,leave:_leave,checkResumeConsumed:checkResumeConsumed,setupResume:setupResume,setupLambda:setupLambda,checkSubtype:checkSubtype,failedCast:failedCast,buildResume:buildResume,mkVTable:mkVTable,bind:bind,leaveAccessor:leaveAccessor};function oops(e){throw new Error("sim error: "+e)}function doNothing(e){return e.pc=-1,_leave(e,e.parent.retval)}function flushLoopLock(){for(;__this.loopLockWaitList.length>0&&!__this.loopLock;){__this.loopLockWaitList.shift()()}}let yieldReset=()=>{};function setupYield(e){yieldReset=e}function loopForSchedule(e){const t=new Object,n=e.pc;return __this.loopLock=t,__this.otherFrames.push(e),()=>{__this.dead||(U.assert(e.pc==n),U.assert(__this.loopLock===t),__this.loopLock=null,loop(e),flushLoopLock())}}function maybeYield(e,t,n){if(__this.pausedOnBreakpoint)return!1;__this.cleanScheduledExpired(),yieldReset();let s=Date.now();return s-lastYield>=20&&(lastYield=s,e.pc=t,e.r0=n,setTimeout(loopForSchedule(e),yieldDelay),!0)}function setupDebugger(e,t){return breakpoints=new Uint8Array(e),breakpoints[0]=msg.breakOnStart?1:0,userGlobals=t,breakpoints}function isBreakFrame(e){if(!breakFrame)return!0;for(let t=breakFrame;t;t=t.parent)if(t==e)return!0;return!1}function breakpoint(e,t,n,s){let i={};__this.loopLock=i,U.assert(!dbgResume),U.assert(!dbgHeap),e.pc=t,e.r0=s;const{msg:r,heap:o}=pxsim.getBreakpointMsg(e,n,userGlobals);return dbgHeap=o,pxsim.injectEnvironmentGlobals(r,o),Runtime.postMessage(r),breakpoints[0]=0,breakFrame=null,__this.pauseScheduled(),dbgResume=n=>{if(dbgResume=null,dbgHeap=null,__this.dead)return null;switch(__this.resumeAllPausedScheduled(),__this.board.onDebuggerResume(),pxsim.runtime=__this,U.assert(e.pc==t),breakpoints[0]=0,breakFrame=null,n.subtype){case"resume":break;case"stepover":breakpoints[0]=1,breakFrame=e;break;case"stepinto":breakpoints[0]=1;break;case"stepout":breakpoints[0]=1,breakFrame=e.parent||e}U.assert(__this.loopLock==i),__this.loopLock=null,__this.otherFrames.push(e),loop(e),flushLoopLock()},null}function trace(e,t,n,s){if(setupResume(t,n),"<main>"===s.functionName||"main.ts"===s.fileName){if(!pxsim.runtime.traceDisabled){const{msg:n}=pxsim.getBreakpointMsg(t,e,userGlobals);n.subtype="trace",Runtime.postMessage(n)}pxsim.thread.pause(tracePauseMs||1)}else pxsim.thread.pause(0);checkResumeConsumed()}function handleDebuggerMsg(e){switch(e.subtype){case"config":let t=e;if(t.setBreakpoints&&breakpoints){breakpoints.fill(0);for(let e of t.setBreakpoints)breakpoints[e]=1}break;case"traceConfig":tracePauseMs=e.interval;break;case"pause":breakpoints[0]=1,breakFrame=null;break;case"resume":case"stepover":case"stepinto":case"stepout":dbgResume&&dbgResume(e);break;case"variables":const n=e;let s;if(dbgHeap){const e=dbgHeap[n.variablesReference];void 0!==e&&(s=pxsim.dumpHeap(e,dbgHeap,n.fields,void 0,n.includeAll))}Runtime.postMessage({type:"debugger",subtype:"variables",req_seq:e.seq,variables:s})}}function removeFrame(e){const t=__this.otherFrames;for(let n=t.length-1;n>=0;--n)if(t[n]===e)return void t.splice(n,1);U.userError("frame cannot be removed!")}function loop(e){if(__this.dead)pxsim.log("Runtime terminated");else{U.assert(!__this.loopLock),__this.perfStartRuntime(),removeFrame(e);try{for(pxsim.runtime=__this;e;)__this.currFrame=e,__this.currFrame.overwrittenPC=!1,e=e.fn(e),__this.maybeUpdateDisplay(),__this.currFrame.overwrittenPC&&(e=__this.currFrame);__this.perfStopRuntime()}catch(t){if(t instanceof BreakLoopException)return void U.nextTick(loopForSchedule(__this.currFrame));if(__this.perfStopRuntime(),__this.errorHandler)__this.errorHandler(t);else{pxsim.error("Simulator crashed, no error handler",t.stack);const{msg:n,heap:s}=pxsim.getBreakpointMsg(e,e.lastBrkId,userGlobals);pxsim.injectEnvironmentGlobals(n,s),n.exceptionMessage=t.message,n.exceptionStack=t.stack,Runtime.postMessage(n),__this.postError&&__this.postError(t)}}}}function checkStack(e){e>100&&U.userError("Stack overflow")}function actionCall(e){return e.depth=e.parent.depth+1,checkStack(e.depth),e.pc=0,e}function setupTop(e){let t=setupTopCore(e);return setupResume(t,0),t}function setupTopCore(e){let t={parent:null,pc:0,depth:0,threadId:++threadId,fn:()=>(e&&e(t.retval),null)};return t}function topCall(e,t){U.assert(!!__this.board),U.assert(!__this.running),__this.setRunning(!0);let n={parent:setupTopCore(t),fn:e,depth:0,pc:0};__this.otherFrames=[n],loop(actionCall(n))}function checkResumeConsumed(){currResume&&oops("getResume() not called")}function setupResume(e,t){currResume=buildResume(e,t)}function leaveAccessor(e,t){if(e.stage2Call){const n={pc:0,fn:null,depth:e.depth,parent:e.parent};let s=1;for(;e.hasOwnProperty("arg"+s);)n["arg"+(s-1)]=e["arg"+s],s++;return setupLambda(n,t),n}return e.parent.retval=t,e.parent}function setupLambda(e,t,n){if(n){const t=e;for(let e=1;e<n;++e)t["arg"+(e-1)]=t["arg"+e];delete t["arg"+(n-1)]}t instanceof pxsim.RefAction?(e.fn=t.func,e.caps=t.fields):"function"==typeof t?e.fn=t:oops("calling non-function")}function checkSubtype(e,t){if(!e)return!1;const n=e.vtable;return t===n||n&&t.classNo<=n.classNo&&n.classNo<=t.lastSubtypeNo}function failedCast(e,t){pxsim.control&&pxsim.control.dmesgValue&&pxsim.control.dmesgValue(e),throwFailedCastError(e,null==t?void 0:t.name)}function buildResume(e,t){currResume&&oops("already has resume"),e.pc=t;let n=Date.now();__this.otherFrames.push(e);let s=i=>{if(__this.dead)return;if(__this.loopLock)return void __this.loopLockWaitList.push(()=>s(i));pxsim.runtime=__this;let r=Date.now();if(r-n>3&&(lastYield=r),U.assert(e.pc==t),i instanceof pxsim.FnWrapper){let t=i,n={parent:e,fn:t.func,lambdaArgs:t.args,pc:0,caps:t.caps,depth:e.depth+1},s={};return __this.loopLock=s,removeFrame(e),__this.otherFrames.push(n),U.nextTick(()=>{U.assert(__this.loopLock===s),__this.loopLock=null,loop(actionCall(n)),flushLoopLock()})}return e.retval=i,loop(e)};return s}const entryPoint=msg.code&&eval(msg.code)(evalIface);this.run=e=>topCall(entryPoint,e),this.getResume=()=>{currResume||oops("noresume");let e=currResume;return currResume=null,e},this.setupTop=setupTop,this.handleDebuggerMsg=handleDebuggerMsg,this.entry=entryPoint,this.overwriteResume=e=>{currResume=null,e>=0&&(this.currFrame.pc=e),this.currFrame.overwrittenPC=!0},pxsim.runtime=this,pxsim.initCurrentRuntime(msg)}registerLiveObject(e){return this.refObjId++}runningTime(){return U.now()-this.startTime-this.pausedTime}runningTimeUs(){return 4294967295&U.perfNowUs()-this.startTimeUs}runFiberAsync(e,t,n,s){return new Promise((i,r)=>U.nextTick(()=>{pxsim.runtime=this,this.setupTop(i),pxtcore.runAction(e,[t,n,s])}))}currTryFrame(){for(let e=this.currFrame;e;e=e.parent)if(e.tryFrame)return e.tryFrame;return null}traceObjects(){const e={};for(;this.heapSnapshots.length>2;)this.heapSnapshots.shift();const t={count:0,size:0,name:"TOTAL"},n={TOTAL:t};function s(t,n,i=null){if(!(n instanceof pxsim.RefObject))return;const r=n;if(r.gcIsStatic())return;const o=e[r.id];if(o)return void(i&&o.pointers.push([i,t]));const a={obj:r,path:null,pointers:[[i,t]]};e[r.id]=a,r.scan((t,n)=>{n instanceof pxsim.RefObject&&!e[n.id]&&s(t,n,a)})}this.heapSnapshots.push({visited:e,statsByType:n});for(let e of Object.keys(this.globals))s(e.replace(/___\d+$/,""),this.globals[e]);const i=this.otherFrames.slice();this.currFrame&&i.indexOf(this.currFrame)<0&&i.unshift(this.currFrame);for(const e of this.getThreads()){const t="Thread-"+this.rootFrame(e).threadId;for(let n=e;n;n=n.parent){const e=t+"."+functionName(n.fn);for(let t of Object.keys(n))if(/^(r0|arg\d+|.*___\d+)/.test(t)){const i=n[t];i instanceof pxsim.RefObject&&(t=t.replace(/___.*/,""),s(e+"."+t,i))}if(n.caps)for(let t of n.caps)s(e+".cap",t)}}const r=Object.keys(e).map(t=>e[t]);r.sort((e,t)=>t.obj.gcSize()-e.obj.gcSize());const o=e=>{if(null!=e.path)return;let t="";e.path="(cycle)";for(let[n,s]of e.pointers){if(null==n)return void(e.path=s);o(n);const i=n.path+"."+s;(!t||t.length>i.length)&&(t=i)}e.path=t};r.forEach(o);const a=[t];for(const e of r){const s=e.obj.gcSize(),i=e.obj.gcKey();n.hasOwnProperty(i)||a.push(n[i]={count:0,size:0,name:i});const r=n[i];r.size+=s,r.count++,t.size+=s,t.count++}a.sort((e,t)=>e.size-t.size);let l="";const u=e=>(" "+e.toString()).slice(-7);for(const e of a)l+=u(4*e.size)+u(e.count)+" "+e.name+"\n";const c=e=>u(4*e.obj.gcSize())+" "+e.obj.gcKey()+" "+e.path,h=r.slice(0,20).map(c).join("\n");let d="";if(this.heapSnapshots.length>=3){const e=this.heapSnapshots[this.heapSnapshots.length-3].visited,t=this.heapSnapshots[this.heapSnapshots.length-2].visited,s=e=>e instanceof pxsim.RefRecord&&!!(e.vtable&&e.vtable.maxBgInstances&&n[e.gcKey()].count<=e.vtable.maxBgInstances);d=r.filter(n=>!e[n.obj.id]&&t[n.obj.id]).filter(e=>!s(e.obj)).map(c).join("\n")}return"Threads:\n"+this.threadInfo()+"\n\nSummary:\n"+l+"\n\nLarge Objects:\n"+h+"\n\nNew Objects:\n"+d}getThreads(){const e=this.otherFrames.slice();return this.currFrame&&e.indexOf(this.currFrame)<0&&e.unshift(this.currFrame),e}rootFrame(e){let t=e;for(;t.parent;)t=t.parent;return t}threadInfo(){const e=this.getThreads();let t="";for(let n of e){t+=`Thread ${this.rootFrame(n).threadId}:\n`;for(let e of pxsim.getBreakpointMsg(n,n.lastBrkId).msg.stackframes){let n=e.funcInfo;t+=` at ${n.functionName} (${n.fileName}:${n.line+1}:${n.column+1})\n`}t+="\n"}return t}static postMessage(e){e&&("undefined"!=typeof window&&window.parent&&window.parent.postMessage&&window.parent.postMessage(e,"*"),Runtime.messagePosted&&Runtime.messagePosted(e))}static async postScreenshotAsync(e){const t=pxsim.runtime&&pxsim.runtime.board;if(!t)return;const n=await t.screenshotAsync();Runtime.postMessage({type:"screenshot",data:n,delay:e&&e.delay})}static requestToggleRecording(){const e=pxsim.runtime;e&&Runtime.postMessage({type:"recorder",action:e.recording?"stop":"start"})}restart(){this.kill(),setTimeout(()=>pxsim.Runtime.postMessage({type:"simulator",command:"restart"}),500)}kill(){this.dead=!0,this.stopRecording(),this.stopIdle(),this.setRunning(!1)}updateDisplay(){this.board.updateView(),this.postFrame()}startRecording(e){!this.recording&&this.running&&(this.recording=!0,this.recordingTimer=setInterval(()=>this.postFrame(),66),this.recordingLastImageData=void 0,this.recordingWidth=e)}stopRecording(){this.recording&&(this.recordingTimer&&clearInterval(this.recordingTimer),this.recording=!1,this.recordingTimer=0,this.recordingLastImageData=void 0,this.recordingWidth=void 0)}postFrame(){if(!this.recording||!this.running)return;let e=pxsim.U.now();this.board.screenshotAsync(this.recordingWidth).then(t=>{this.recordingLastImageData&&isImageDataEqual(this.recordingLastImageData,t)||(this.recordingLastImageData=t,Runtime.postMessage({type:"screenshot",data:t,time:e}))})}queueDisplayUpdate(){this.numDisplayUpdates++}maybeUpdateDisplay(){this.numDisplayUpdates&&(this.numDisplayUpdates=0,this.updateDisplay())}setRunning(e){this.running!=e&&(this.running=e,this.running?(this.startTime=U.now(),this.startTimeUs=U.perfNowUs(),Runtime.postMessage({type:"status",frameid:pxsim.Embed.frameid,runtimeid:this.id,state:"running"})):(this.stopRecording(),this.stopIdle(),Runtime.postMessage({type:"status",frameid:pxsim.Embed.frameid,runtimeid:this.id,state:"killed"})),this.stateChanged&&this.stateChanged())}dumpLivePointers(){}setupPerfCounters(e){e&&e.length&&(this.perfCounters=e.map(e=>new PerfCounter(e)))}perfStartRuntime(){0!==this.perfOffset?this.perfStack++:this.perfOffset=U.perfNowUs()-this.perfElapsed}perfStopRuntime(){this.perfStack?this.perfStack--:(this.perfElapsed=this.perfNow(),this.perfOffset=0)}perfNow(){return 0===this.perfOffset&&U.userError("bad time now"),U.perfNowUs()-this.perfOffset|0}startPerfCounter(e){if(!this.perfCounters)return;const t=this.perfCounters[e];t.start&&U.userError("startPerf"),t.start=this.perfNow()}stopPerfCounter(e){if(!this.perfCounters)return;const t=this.perfCounters[e];t.start||U.userError("stopPerf");const n=this.perfNow()-t.start;t.start=0,t.value+=n,t.numstops++;let s=t.lastFewPtr++;s>=t.lastFew.length&&(s=0,t.lastFewPtr=1),t.lastFew[s]=n}startIdle(){void 0===this.idleTimer&&(this.idleTimer=setInterval(()=>{if(!this.running||this.pausedOnBreakpoint)return;const e=this.board.bus;e&&e.queueIdle()},20))}stopIdle(){void 0!==this.idleTimer&&(clearInterval(this.idleTimer),this.idleTimer=void 0)}schedule(e,t){if(t<=0&&(t=0),this.pausedOnBreakpoint)return this.timeoutsPausedOnBreakpoint.push(new PausedTimeout(e,t)),-1;const n=U.now(),s=new TimeoutScheduled(-1,e,t,n);return s.id=setTimeout(()=>{const t=this.timeoutsScheduled.indexOf(s);t>=0&&this.timeoutsScheduled.splice(t,1),e()},t),this.timeoutsScheduled.push(s),s.id}pauseScheduled(){this.pausedOnBreakpoint=!0,this.timeoutsScheduled.forEach(e=>{clearTimeout(e.id);let t=U.now()-e.timestampCall,n=e.totalRuntime-t;n<=0&&(n=1),this.timeoutsPausedOnBreakpoint.push(new PausedTimeout(e.fn,n))}),this.lastPauseTimestamp=U.now(),this.timeoutsScheduled=[]}resumeAllPausedScheduled(){this.pausedOnBreakpoint=!1,this.timeoutsPausedOnBreakpoint.forEach(e=>{this.schedule(e.fn,e.timeRemaining)}),this.lastPauseTimestamp&&(this.pausedTime+=U.now()-this.lastPauseTimestamp,this.lastPauseTimestamp=0),this.timeoutsPausedOnBreakpoint=[]}cleanScheduledExpired(){let e=U.now();this.timeoutsScheduled=this.timeoutsScheduled.filter(t=>{let n=e-t.timestampCall;return t.totalRuntime>n})}registerUserInteraction(){this.lastInteractionTime=Date.now(),this.thumbnailRecordingIntervalRef||this.lastThumbnailTime&&this.lastInteractionTime-this.lastThumbnailTime<1e3||(this.thumbnailFrames=[],this.thumbnailRecordingIntervalRef=setInterval(async()=>{const e=await this.board.screenshotAsync();this.thumbnailFrames.length&&isImageDataEqual(e,this.thumbnailFrames[this.thumbnailFrames.length-1])||(this.thumbnailFrames.push(e),(Date.now()-this.lastInteractionTime>1e4||this.thumbnailFrames.length>30)&&(clearInterval(this.thumbnailRecordingIntervalRef),this.thumbnailRecordingIntervalRef=void 0,this.lastThumbnailTime=Date.now(),Runtime.postMessage({type:"thumbnail",frames:this.thumbnailFrames})))},66))}}function throwUserException(e){throw new Error(e)}function throwTypeError(e){throwUserException(pxsim.localization.lf("TypeError: {0}",e))}function throwFailedCastError(e,t){const n=getType(e);throwTypeError(t?null==e?pxsim.localization.lf("Expected type {0} but received type {1}. Did you forget to assign a variable?",t,n):pxsim.localization.lf("Expected type {0} but received type {1}",t,n):pxsim.localization.lf("Cannot read properties of {0}",n))}function throwFailedPropertyAccessError(e,t){const n=getType(e);throwTypeError(t?pxsim.localization.lf("Cannot read properties of {0} (reading '{1}')",n,t):pxsim.localization.lf("Cannot read properties of {0}",n))}function throwNullUndefinedAsObjectError(){throwTypeError(pxsim.localization.lf("Cannot convert undefined or null to object"))}function getType(e){let t;const n=null==e?void 0:e.vtable;return t=n?n.name:null===e?"null":void 0===e?"undefined":e instanceof pxsim.RefCollection?"Array":e instanceof pxsim.RefBuffer?"Buffer":e instanceof pxsim.RefAction?"function":typeof e,t}function setParentMuteState(e){Runtime.postMessage({type:"setmutebuttonstate",state:e})}pxsim.Runtime=Runtime,pxsim.throwUserException=throwUserException,pxsim.throwTypeError=throwTypeError,pxsim.throwFailedCastError=throwFailedCastError,pxsim.throwFailedPropertyAccessError=throwFailedPropertyAccessError,pxsim.throwNullUndefinedAsObjectError=throwNullUndefinedAsObjectError,pxsim.setParentMuteState=setParentMuteState;class PerfCounter{constructor(e){this.name=e,this.start=0,this.numstops=0,this.value=0,this.lastFew=new Uint32Array(32),this.lastFewPtr=0}}function isImageDataEqual(e,t){if(e.data.byteLength!==t.data.byteLength)return!1;const n=e.data.byteLength;let s=0;for(s=0;s<n&&e.data[s]==t.data[s];++s);return s===n}pxsim.PerfCounter=PerfCounter}(pxsim||(pxsim={})),function(e){let t,n;!function(e){e[e.Unloaded=0]="Unloaded",e[e.Stopped=1]="Stopped",e[e.Pending=2]="Pending",e[e.Starting=3]="Starting",e[e.Running=4]="Running",e[e.Paused=5]="Paused",e[e.Suspended=6]="Suspended"}(t=e.SimulatorState||(e.SimulatorState={})),function(e){e[e.StepInto=0]="StepInto",e[e.StepOver=1]="StepOver",e[e.StepOut=2]="StepOut",e[e.Resume=3]="Resume",e[e.Pause=4]="Pause"}(n=e.SimulatorDebuggerCommand||(e.SimulatorDebuggerCommand={}));const s="messagechannel",i="aspectratio",r="pxtdriver",o="permanent";e.SimulatorDriver=class{constructor(n,s={}){this.container=n,this.options=s,this.themes=["blue","red","green","yellow"],this.runId="",this.nextFrameId=0,this.frameCounter=0,this.singleSimulator=!1,this.traceInterval=0,this.breakpointsSet=!1,this._runOptions={},this.state=t.Unloaded,this._allowedOrigins=[],this.newJacdacSimulator=!1,this.frameCleanupTimeout=void 0,this.debuggerSeq=1,this.debuggerResolvers={},this._allowedOrigins.push(window.location.origin),s.parentOrigin&&this._allowedOrigins.push(s.parentOrigin),this._allowedOrigins.push(this.getSimUrl().origin);const i=(null==s?void 0:s.messageSimulators)||{};Object.keys(i).map(e=>i[e]).forEach(e=>{this._allowedOrigins.push(new URL(e.url).origin),e.localHostUrl&&this._allowedOrigins.push(new URL(e.localHostUrl).origin)});const r=e.U.isLocalHost()&&/[?&]simxdev(?:[=&#]|$)/i.test(window.location.href);Object.entries((null==s?void 0:s.simulatorExtensions)||{}).forEach(([e,t])=>{if(t&&t.index&&t.aspectRatio&&void 0!==t.permanent){if(r&&t.devUrl)t.url=new URL(t.index,t.devUrl).toString();else{const n=this.getSimUrl(),s=["simx",e,"-",t.index].join("/");t.url=new URL(s.replace(/^\/+/,""),n.origin).toString()}this._allowedOrigins.push(new URL(t.url).origin)}}),this._allowedOrigins=e.U.unique(this._allowedOrigins,e=>e)}isDebug(){return this._runOptions&&!!this._runOptions.debug}isTracing(){return this._runOptions&&!!this._runOptions.trace}hasParts(){return this._runOptions&&this._runOptions.parts&&!!this._runOptions.parts.length}setDirty(){this.state==e.SimulatorState.Running&&this.suspend()}setPending(){this.setState(t.Pending)}focus(){const e=this.simFrames()[0];e&&e.focus()}registerDependentEditor(e){e&&(this._dependentEditors||(this._dependentEditors=[]),this._dependentEditors.push(e))}dependentEditors(){return this._dependentEditors&&(this._dependentEditors=this._dependentEditors.filter(e=>!!e.parent),this._dependentEditors.length||(this._dependentEditors=void 0)),this._dependentEditors}setStarting(){this.setState(t.Starting)}setHwDebugger(e){e?(this.hwdbg=e,this.setState(t.Running),this.container.style.opacity="0.3"):(delete this.container.style.opacity,this.hwdbg=null,this.setState(t.Running),this.stop())}handleHwDebuggerMsg(e){this.hwdbg&&this.handleMessage(e)}setThemes(t){e.U.assert(t&&t.length>0),this.themes=t}startRecording(e){this.simFrames()[0]&&this.postMessage({type:"recorder",action:"start",source:r,width:e})}stopRecording(){this.postMessage({type:"recorder",source:r,action:"stop"})}setFrameState(n){const s=n.nextElementSibling,i=s.nextElementSibling;switch(this.state){case t.Pending:case t.Starting:s.style.display="",s.className="",i.style.display="";break;case t.Stopped:case t.Suspended:e.U.addClass(n,this.state==t.Stopped||this._runOptions&&this._runOptions.autoRun?this.stoppedClass:this.invalidatedClass),this._runOptions&&this._runOptions.autoRun?s.style.display="none":(s.style.display="",s.className="videoplay xicon icon"),i.style.display="none",this.scheduleFrameCleanup();break;default:e.U.removeClass(n,this.stoppedClass),e.U.removeClass(n,this.invalidatedClass),s.style.display="none",i.style.display="none"}}setState(e){this.state!=e&&(this.state=e,this.freeze(this.state==t.Paused),this.simFrames().forEach(e=>this.setFrameState(e)),this.options.onStateChanged&&this.options.onStateChanged(this.state))}freeze(t){const n="pause-overlay";t?e.util.toArray(this.container.querySelectorAll("div.simframe")).forEach(e=>{if(e.querySelector(`div.${n}`))return;const t=document.createElement("div");t.className=n,t.onclick=e=>(e.preventDefault(),!1),e.appendChild(t)}):e.util.toArray(this.container.querySelectorAll(`div.simframe div.${n}`)).forEach(e=>e.parentElement.removeChild(e))}simFrames(t=!1){let n=e.util.toArray(this.container.getElementsByTagName("iframe"));const s=this.loanedIFrame();return s&&!t&&n.unshift(s),n}getSimUrl(){var e,t;const n=this.options.simUrl||(null===(e=window.pxtConfig)||void 0===e?void 0:e.simUrl)||(null===(t=pxt.webConfig)||void 0===t?void 0:t.simUrl)||`${location.origin}/sim/simulator.html`;try{return new URL(n)}catch(e){return new URL(n,location.origin)}}setSingleSimulator(){this.singleSimulator=!0}postMessage(t,n,r){var a;if(this.hwdbg)return void this.hwdbg.postMessage(t);const l=this.dependentEditors();let u=this.simFrames();r&&(u=u.filter(e=>e.id===r));let c=!1;const h=t;if(n&&(null==h?void 0:h.broadcast)){h.srcFrameIndex=this.simFrames().findIndex(e=>e.contentWindow===n);const r=!!(null===(a=this._currentRuntime)||void 0===a?void 0:a.single),d=window.parent&&window.parent!==window.window?window.parent:window.opener;if(d&&n!==d&&d.postMessage(t,"*"),!this.options.nestedEditorSim&&!(null==h?void 0:h.toParentIFrameOnly))if(l)l.forEach(e=>{n!==e&&e.postMessage(t,window.location.origin)});else if(!r){const n="messagepacket"===t.type&&t.channel,r=n&&this.options.messageSimulators&&this.options.messageSimulators[n],a=n&&this.options.simulatorExtensions&&this.options.simulatorExtensions[n],l=(t,r,a)=>{var l;a=a||(null===(l=this._runOptions)||void 0===l?void 0:l.aspectRatio)||1.22;let c=this.createFrame(t);this.container.appendChild(c);const h=c.firstElementChild;h.dataset[s]=n,h.dataset[i]=a+"",e.U.addClass(c,"simmsg"),e.U.addClass(c,"simmsg"+e.U.sanitizeCssName(n)),r&&(h.dataset[o]="true"),this.startFrame(h),u=this.simFrames()};if(a){let e=u.find(e=>e.dataset[s]===n);if("jacdac/pxt-jacdac"===n&&(this.newJacdacSimulator=!0),e)e.dataset.runid!=this.runId&&this.startFrame(e);else{const e=new URL(a.url);this.options.parentOrigin&&e.searchParams.set("parentOrigin",encodeURIComponent(this.options.parentOrigin)),this.options.userLanguage&&e.searchParams.set("language",encodeURIComponent(this.options.userLanguage)),l(e.toString(),a.permanent,a.aspectRatio)}}else if(r){let t=u.find(e=>e.dataset[s]===n);if(t)t.dataset.runid!=this.runId&&this.startFrame(t);else if("jacdac"!==n||!this.newJacdacSimulator){l((e.U.isLocalHost()&&/localhostmessagesims=1/i.test(window.location.href)&&r.localHostUrl||r.url).replace("$PARENT_ORIGIN$",encodeURIComponent(this.options.parentOrigin||"")).replace("$LANGUAGE$",encodeURIComponent(this.options.userLanguage)),r.permanent,r.aspectRatio)}}else{c=!0;const e=u.filter(e=>!e.dataset[s]);n||0!=e.length&&(1!=e.length||this.singleSimulator)?2==e.length&&e[1].dataset.runid!=this.runId&&this.startFrame(e[1]):(this.container.appendChild(this.createFrame()),u=this.simFrames())}}}for(let e=0;e<u.length;++e){const s=u[e];if((!n||s.contentWindow!=n)&&(s.contentWindow&&(c?this.postDeferrableMessage(s,t):this.postMessageCore(s,t),"recorder"==t.type&&"start"==t.action)))break}}postDeferrableMessage(e,t){!e.dataset.loading?this.postMessageCore(e,t):(this.deferredMessages||(this.deferredMessages=[]),this.deferredMessages.push([e,t]))}postMessageCore(t,n){const s=e.U.isLocalHostDev()?"*":t.dataset.origin;t.contentWindow.postMessage(n,s)}setRunOptionQueryParams(e){var t,n;const s=new URL(e);if((null===(t=this._runOptions)||void 0===t?void 0:t.hideSimButtons)&&s.searchParams.set("hideSimButtons","1"),null===(n=this._runOptions)||void 0===n?void 0:n.queryParameters){const e=this._runOptions.queryParameters.split("&");for(const t of e){const[e,n]=t.split(/[:=]/);e&&n&&s.searchParams.set(e,n)}}return s.toString()}createFrame(n){var s;const i=document.createElement("div");i.className="simframe ui embed",i.setAttribute("tabindex","0");const r=document.createElement("iframe");r.id="sim-frame-"+this.nextId(),r.title=e.localization.lf("Simulator"),r.allowFullscreen=!0,r.setAttribute("allow","autoplay;microphone"),r.setAttribute("sandbox","allow-same-origin allow-scripts"),r.className="no-select";let o=this.setRunOptionQueryParams(n||this.getSimUrl().toString());o+="#"+r.id,r.src=o,r.frameBorder="0",r.dataset.runid=this.runId,r.dataset.origin=new URL(o).origin||"*",r.dataset.loading="true",(null===(s=this._runOptions)||void 0===s?void 0:s.autofocus)&&r.setAttribute("autofocus","true"),i.appendChild(r);const a=document.createElement("i");a.className="videoplay xicon icon",a.style.display="none",a.onclick=e=>(e.preventDefault(),this.state!=t.Running&&this.state!=t.Starting&&(this.options.restart?this.options.restart():this.start()),r.focus(),!1),i.appendChild(a);const l=document.createElement("div");return l.className="ui active loader",a.style.display="none",i.appendChild(l),this._runOptions&&this.applyAspectRatioToFrame(r),i}preload(e,t){this.addEventListeners(),t&&(this._currentRuntime=void 0,this.container.textContent=""),this.simFrames().length||(this.container.appendChild(this.createFrame()),this.applyAspectRatio(e),this.setStarting())}stop(e=!1,n=!1){this.state!==t.Stopped&&this.state!==t.Unloaded&&(this.clearDebugger(),this.stopSound(),this.postMessage({type:"stop",source:r}),this.setState(n?t.Starting:t.Stopped)),e&&this.unload()}suspend(){this.stopSound(),this.postMessage({type:"stop",source:r}),this.setState(t.Suspended)}unload(){this.cancelFrameCleanup(),e.U.removeChildren(this.container),this.setState(t.Unloaded),this._runOptions=void 0,this._currentRuntime=void 0,this.runId=void 0,this.deferredMessages=void 0}mute(e){this._currentRuntime&&(this._currentRuntime.mute=e),this.postMessage({type:"mute",source:r,mute:e})}stopSound(){this.postMessage({type:"stopsound",source:r})}isLoanedSimulator(e){return!!this.loanedSimulator&&this.loanedIFrame()==e}loanSimulator(){return this.loanedSimulator||(this.loanedSimulator=this.container.firstElementChild||this.createFrame(),this.loanedSimulator.parentNode&&this.container.removeChild(this.loanedSimulator)),this.loanedSimulator}unloanSimulator(){this.loanedSimulator&&(this.loanedSimulator.parentNode&&this.loanedSimulator.parentNode.removeChild(this.loanedSimulator),this.container.insertBefore(this.loanedSimulator,this.container.firstElementChild),delete this.loanedSimulator)}loanedIFrame(){return this.loanedSimulator&&this.loanedSimulator.parentNode&&this.loanedSimulator.querySelector("iframe")}cancelFrameCleanup(){this.frameCleanupTimeout&&(clearTimeout(this.frameCleanupTimeout),this.frameCleanupTimeout=void 0)}scheduleFrameCleanup(){this.cancelFrameCleanup(),this.frameCleanupTimeout=setTimeout(()=>{this.frameCleanupTimeout=void 0,this.cleanupFrames()},5e3)}applyAspectRatio(e){if(!e&&!this._runOptions)return;this.simFrames().forEach(t=>this.applyAspectRatioToFrame(t,e))}applyAspectRatioToFrame(e,t){var n,r,o,a;let l=t;if(void 0===l){const t=parseFloat(e.dataset[i]);isNaN(t)||(l=t)}if(void 0===l){const t=e.dataset[s];if(t){const e=null===(o=null===(r=null===(n=this.options)||void 0===n?void 0:n.messageSimulators)||void 0===r?void 0:r[t])||void 0===o?void 0:o.aspectRatio;e&&(l=e)}}void 0===l&&(l=(null===(a=this._runOptions)||void 0===a?void 0:a.aspectRatio)||1.22),e.parentElement.style.paddingBottom=100/l+"%"}cleanupFrames(){const e=this.simFrames(!0);e.shift(),e.filter(e=>!e.dataset[o]).forEach(e=>{this.state!=t.Stopped&&e.dataset.runid==this.runId||(this.options.removeElement?this.options.removeElement(e.parentElement):e.parentElement.remove())})}hide(e){if(this.suspend(),!this.options.removeElement)return;const t=this.simFrames();t.forEach(t=>{this.options.removeElement(t.parentElement,e)}),0==t.length&&e&&e()}unhide(){if(!this.options.unhideElement)return;this.simFrames().forEach(e=>{this.options.unhideElement(e.parentElement)})}setRunOptions(e={}){this._runOptions=e}run(e,t={}){this.setRunOptions(t),this.runId=this.nextId(),this._currentRuntime={type:"run",source:r,boardDefinition:t.boardDefinition,parts:t.parts,builtinParts:t.builtinParts,fnArgs:t.fnArgs,code:e,partDefinitions:t.partDefinitions,mute:t.mute,highContrast:t.highContrast,light:t.light,cdnUrl:t.cdnUrl,localizedStrings:t.localizedStrings,refCountingDebug:t.refCountingDebug,version:t.version,clickTrigger:t.clickTrigger,breakOnStart:t.breakOnStart,storedState:t.storedState,ipc:t.ipc,single:t.single,dependencies:t.dependencies,activePlayer:t.activePlayer,theme:t.theme},this.stopSound(),this.start()}restart(){this.stop(),this.cleanupFrames(),this.start()}areBreakpointsSet(){return this.breakpointsSet}start(){if(this.clearDebugger(),this.addEventListeners(),this.applyAspectRatio(),this.scheduleFrameCleanup(),!this._currentRuntime)return;this.singleSimulator=!1,this.breakpointsSet=!1;let e=this.simFrames()[0];if(!e){let t=this.createFrame();this.container.appendChild(t),e=t.firstElementChild}this.startFrame(e),this.debuggingFrame=e.id,this.setState(t.Running),this.setTraceInterval(this.traceInterval)}startFrame(e){var t,n,s;if(!this._currentRuntime||!e.contentWindow)return!1;const i=JSON.parse(JSON.stringify(this._currentRuntime));i.frameCounter=++this.frameCounter;const r=(null===(t=this._runOptions)||void 0===t?void 0:t.mpRole)||(null===(s=null===(n=/[\&\?]mp=(server|client)/i.exec(window.location.href))||void 0===n?void 0:n[1])||void 0===s?void 0:s.toLowerCase());return i.options={theme:this.themes[this.nextFrameId++%this.themes.length],mpRole:r},i.id=`${i.options.theme}-${this.nextId()}`,e.dataset.runid=this.runId,e.dataset.runtimeid=i.id,e.id!==this.debuggingFrame&&(i.traceDisabled=!0,i.breakOnStart=!1),this.postMessageCore(e,i),this.traceInterval&&this.setTraceInterval(this.traceInterval),this.applyAspectRatioToFrame(e),this.setFrameState(e),!0}handleDeferredMessages(e){var t,n,s;e.dataset.loading&&(delete e.dataset.loading,null===(n=null===(t=this.deferredMessages)||void 0===t?void 0:t.filter(t=>t[0]===e))||void 0===n||n.forEach(t=>{const[n,s]=t;this.postMessageCore(e,s)}),this.deferredMessages=null===(s=this.deferredMessages)||void 0===s?void 0:s.filter(t=>t[0]!==e))}handleMessage(e,n){var s,r,o;switch(e.type||""){case"ready":{const t=e.frameid,n=document.getElementById(t);n&&((null===(s=this._runOptions)||void 0===s?void 0:s.autofocus)&&n.focus(),this.startFrame(n),this.options.revealElement&&this.options.revealElement(n),this.handleDeferredMessages(n)),this.options.onSimulatorReady&&this.options.onSimulatorReady();break}case"status":{const n=e.frameid,s=document.getElementById(n);if(s){const n=e;if(n.runtimeid==s.dataset.runtimeid)switch(n.state){case"running":this.setState(t.Running),this.handleDeferredMessages(s);break;case"killed":this.setState(t.Stopped)}}break}case"simulator":this.handleSimulatorCommand(e);break;case"serial":case"pxteditor":case"screenshot":case"custom":case"recorder":case"addextensions":break;case"aspectratio":{const t=e,n=t.frameid,s=document.getElementById(n);s&&(s.dataset[i]=t.value+"",this.applyAspectRatioToFrame(s));break}case"debugger":this.handleDebuggerMessage(e);break;case"toplevelcodefinished":this.options.onTopLevelCodeEnd&&this.options.onTopLevelCodeEnd();break;case"setmutebuttonstate":null===(o=(r=this.options).onMuteButtonStateChange)||void 0===o||o.call(r,e.state);break;default:this.postMessage(e,n)}}addEventListeners(){this.listener||(this.listener=t=>{if(!this.hwdbg){if(e.U.isLocalHost());else if(this._allowedOrigins.indexOf(t.origin)<0)return;this.handleMessage(t.data,t.source)}},window.addEventListener("message",this.listener,!1))}removeEventListeners(){this.listener&&(window.removeEventListener("message",this.listener,!1),this.listener=void 0)}resume(s){let i;switch(s){case n.Resume:i="resume",this.setState(t.Running);break;case n.StepInto:i="stepinto",this.setState(t.Running);break;case n.StepOut:i="stepout",this.setState(t.Running);break;case n.StepOver:i="stepover",this.setState(t.Running);break;case n.Pause:i="pause";break;default:return void e.debug("unknown command")}this.postMessage({type:"debugger",subtype:i,source:r})}setBreakpoints(e){this.breakpointsSet=!0,this.postDebuggerMessage("config",{setBreakpoints:e},void 0,this.debuggingFrame)}setTraceInterval(e){this.traceInterval=e,this.postDebuggerMessage("traceConfig",{interval:e})}variablesAsync(e,t,n=!1){return this.postDebuggerMessageAsync("variables",{variablesReference:e,fields:t,includeAll:n},this.debuggingFrame).then(e=>e,e=>{})}handleSimulatorCommand(e){this.options.onSimulatorCommand&&this.options.onSimulatorCommand(e)}clearDebugger(){const e=new Error("Debugging cancelled");Object.keys(this.debuggerResolvers).forEach(t=>{const{reject:n}=this.debuggerResolvers[t];n(e)}),this.debuggerResolvers={},this.debuggerSeq++}handleDebuggerMessage(s){if("trace"!==s.subtype&&e.log("DBG-MSG",s.subtype,s),s.seq){const{resolve:e}=this.debuggerResolvers[s.seq];e&&e(s)}switch(s.subtype){case"warning":this.options.onDebuggerWarning&&this.options.onDebuggerWarning(s);break;case"breakpoint":{const i=s;if(this.state==t.Running){if(i.exceptionMessage)this.suspend();else{this.setState(t.Paused);this.simFrames(!0).length>1&&this.resume(n.Pause)}this.options.onDebuggerBreakpoint&&this.options.onDebuggerBreakpoint(i);let s=i.exceptionMessage+"\n";for(let e of i.stackframes){let t=e.funcInfo;s+=` at ${t.functionName} (${t.fileName}:${t.line+1}:${t.column+1})\n`}i.exceptionMessage&&e.error(s)}else e.error("debugger: trying to pause from "+this.state);break}case"trace":{const e=s;this.state==t.Running&&this.options.onTraceMessage&&this.options.onTraceMessage(e);break}default:const i=s.req_seq;if(i){const{resolve:e}=this.debuggerResolvers[i];e&&(delete this.debuggerResolvers[i],e(s))}}}postDebuggerMessageAsync(e,t={},n){return new Promise((s,i)=>{const r=this.debuggerSeq++;this.debuggerResolvers[r.toString()]={resolve:s,reject:i},this.postDebuggerMessage(e,t,r,n)})}postDebuggerMessage(e,t={},n,s){const i=JSON.parse(JSON.stringify(t));i.type="debugger",i.subtype=e,i.source=r,n&&(i.seq=n),this.postMessage(i,void 0,s)}nextId(){return this.nextFrameId+++(Math.random()+""+Math.random()).replace(/[^\d]/,"")}get stoppedClass(){return this.options&&this.options.stoppedClass||"grayscale"}get invalidatedClass(){return this.options&&this.options.invalidatedClass||"sepia"}}}(pxsim||(pxsim={})),function(e){e.mkRange=function(e,t){let n=[];for(;e<t;e++)n.push(e);return n};e.EventBus=class{constructor(e,t,n){this.runtime=e,this.board=t,this.valueToArgs=n,this.queues={},this.backgroundHandlerFlag=!1,this.nextNotifyEvent=1024,this.schedulerID=15,this.idleEventID=2,this.board.addMessageListener(this.handleMessage.bind(this))}handleMessage(e){if("eventbus"===e.type){const t=e;this.queue(t.id,t.eventid,t.value)}}setBackgroundHandlerFlag(){this.backgroundHandlerFlag=!0}setNotify(e,t){this.notifyID=e,this.notifyOneID=t}setIdle(e,t){this.schedulerID=e,this.idleEventID=t}start(t,n,s,i=!1){let r=(s?"back":"fore")+":"+t+":"+n;return!this.queues[r]&&i&&(this.queues[r]=new e.EventQueue(this.runtime,this.valueToArgs)),this.queues[r]}listen(e,t,n,s=0){e==this.schedulerID&&t==this.idleEventID&&this.runtime.startIdle();let i=this.start(e,t,this.backgroundHandlerFlag,!0);this.backgroundHandlerFlag?i.addHandler(n,s):i.setHandler(n,s),this.backgroundHandlerFlag=!1}removeBackgroundHandler(e){Object.keys(this.queues).forEach(t=>{t.startsWith("back:")&&this.queues[t].removeHandler(e)})}getQueues(e,t,n){let s=[this.start(0,0,n)];return 0==e&&0==t||(t&&s.push(this.start(0,t,n)),e&&s.push(this.start(e,0,n)),e&&t&&s.push(this.start(e,t,n))),s}queue(t,n,s=null){if(e.runtime.pausedOnBreakpoint)return;const i=this.notifyID&&this.notifyOneID&&t==this.notifyOneID;i&&(t=this.notifyID);let r=this.getQueues(t,n,!0).concat(this.getQueues(t,n,!1));this.lastEventValue=n,this.lastEventTimestampUs=e.U.perfNowUs(),e.U.promiseMapAllSeries(r,e=>e?e.push(s,i):Promise.resolve())}queueIdle(){this.schedulerID&&this.idleEventID&&this.queue(this.schedulerID,this.idleEventID)}wait(e,t,n){this.start(e,t,!1,!0).addAwaiter(n)}getLastEventValue(){return this.lastEventValue}getLastEventTime(){return 4294967295&this.lastEventTimestampUs-e.runtime.startTimeUs}};function t(){return"undefined"!=typeof window&&("ontouchstart"in window||navigator&&navigator.maxTouchPoints>0)}function n(){return"undefined"!=typeof window&&!!window.PointerEvent}e.AnimationQueue=class{constructor(e){this.runtime=e,this.queue=[],this.process=()=>{let t=this.queue[0];if(!t)return;if(this.runtime.dead)return;e=this.runtime;let n=t.frame();e.queueDisplayUpdate(),e.maybeUpdateDisplay(),!1===n?(this.queue.shift(),this.queue[0]&&(this.queue[0].setTimeoutHandle=setTimeout(this.process,this.queue[0].interval)),t.whenDone(!1)):t.setTimeoutHandle=setTimeout(this.process,t.interval)}}cancelAll(){let e=this.queue;this.queue=[];for(let t of e)t.whenDone(!0),t.setTimeoutHandle&&clearTimeout(t.setTimeoutHandle)}cancelCurrent(){let e=this.queue[0];e&&(this.queue.shift(),e.whenDone(!0),e.setTimeoutHandle&&clearTimeout(e.setTimeoutHandle))}enqueue(e){e.whenDone||(e.whenDone=()=>{}),this.queue.push(e),1==this.queue.length&&this.process()}executeAsync(t){return e.U.assert(!t.whenDone),new Promise((e,n)=>{t.whenDone=e,this.enqueue(t)})}},e.isTouchEnabled=t,e.hasPointerEvents=n,e.pointerEvents=n()?{up:"pointerup",down:["pointerdown"],move:"pointermove",enter:"pointerenter",leave:"pointerleave"}:t()?{up:"mouseup",down:["mousedown","touchstart"],move:"touchmove",enter:"touchenter",leave:"touchend"}:{up:"mouseup",down:["mousedown"],move:"mousemove",enter:"mouseenter",leave:"mouseleave"}}(pxsim||(pxsim={})),function(e){!function(t){function n(e,t){return n=>n*(t/e)}function s(e,t){let n=e[0]-t[0],s=e[1]-t[1];return n*n+s*s}t.translateEl=function(t,n){e.svg.hydrate(t,{transform:`translate(${n[0]} ${n[1]})`})},t.composeSVG=function(t){let[n,s]=[t.el1,t.el2];e.U.assert(0==n.x&&0==n.y&&0==s.x&&0==s.y,"el1 and el2 x,y offsets not supported");let i=(t,n,s)=>e.svg.hydrate(t,{x:n,y:s}),r=(t,n,s)=>e.svg.hydrate(t,{width:`${n}px`,height:`${s}px`}),o=t.scaleUnit2,a=t.scaleUnit2/t.scaleUnit1,l=n.w*a,u=n.h*a;r(n.el,l,u);let c=1*s.w,h=1*s.h;r(s.el,c,h);let[d,p,f,m]=t.margin,g=t.middleMargin,b=Math.max(l,c),v=p+(b-l)/2,y=d;i(n.el,v,y);let S=p+(b-c)/2,w=y+u+g;i(s.el,S,w);let x=[y,y+u,w,w+h],E=p+b+m,I=d+u+g+h+f,k=e.svg.elt("svg",{version:"1.0",viewBox:`0 0 ${E} ${I}`,class:"sim-bb"});((t,n,s)=>{n&&e.svg.hydrate(t,{width:n}),s&&e.svg.hydrate(t,{height:s})})(k,t.maxWidth,t.maxHeight),i(k,0,0);let C=e.svg.child(k,"g");return k.appendChild(n.el),k.appendChild(s.el),{under:C,over:e.svg.child(k,"g"),host:k,edges:x,scaleUnit:o,toHostCoord1:e=>{let[t,n]=e;return[t*a+v,n*a+y]},toHostCoord2:e=>{let[t,n]=e;return[1*t+S,1*n+w]}}},t.mkScaleFn=n,t.mkImageSVG=function(t){let s=n(t.imageUnitDist,t.targetUnitDist),i=s(t.width),r=s(t.height),o=e.svg.elt("image",{width:i,height:r});return o.setAttributeNS("http://www.w3.org/1999/xlink","href",`${t.image}`),{el:o,w:i,h:r,x:0,y:0}},t.findDistSqrd=s,t.findClosestCoordIdx=function(e,t){return t.map(t=>s(e,t)).reduce((e,t,n,s)=>t<s[e]?n:e,0)},t.mkTxt=function(t,n,s,i,r,o,a){let l=e.svg.elt("text");a=a||.3;const u=(o=o||-.33333)*s*r.length,c=a*s;return e.svg.hydrate(l,{style:`font-size:${s}px;`,transform:`translate(${t} ${n}) rotate(${i}) translate(${u} ${c})`}),e.U.addClass(l,"noselect"),l.textContent=r,l},t.GPIO_WIRE_COLORS=["pink","orange","yellow","green","purple"],t.WIRE_COLOR_MAP={black:"#514f4d",white:"#fcfdfc",gray:"#acabab",purple:"#a772a1",blue:"#01a6e8",green:"#3cce73",yellow:"#ece600",orange:"#fdb262",red:"#f44f43",brown:"#c89764",pink:"#ff80fa"},t.mapWireColor=function(e){return t.WIRE_COLOR_MAP[e]||e},t.PIN_DIST=15,t.rgbToHsl=function(e){let t,n,s,[i,r,o]=e,[a,l,u]=[i/255,r/255,o/255],c=Math.min(a,l,u),h=Math.max(a,l,u),d=h-c,p=h+c;return s=p/2*100,0===d?n=t=0:(h===a?t=(l-u)/d%6*60:h===l?t=60*((u-a)/d+2):h===u&&(t=60*((a-l)/d+4)),n=s>50?d/(2-p)*100:d/p*100),[Math.floor(t),Math.floor(n),Math.floor(s)]}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){var t;!function(n){function s(e,n,s){let i={class:e,d:n};s&&(i.title=s);let r=t.elt("path");return t.hydrate(r,i),r}function i(e,n=!1){let s=t.elt("linearGradient");t.hydrate(s,{id:e,x1:"0%",y1:"0%",x2:n?"100%":"0%",y2:n?"0%":"100%"});t.child(s,"stop",{offset:"0%"}),t.child(s,"stop",{offset:"100%"}),t.child(s,"stop",{offset:"100%"}),t.child(s,"stop",{offset:"100%"});return s}function r(e){let n=t.elt("title");return n.textContent=e,n}n.parseString=function(e){return(new DOMParser).parseFromString(e,"image/svg+xml").getElementsByTagName("svg").item(0)},n.toDataUri=function(e){return"data:image/svg+xml,"+encodeURI(e)},n.cursorPoint=function(e,t,n){return e.x=null!=n.clientX?n.clientX:n.pageX,e.y=null!=n.clientY?n.clientY:n.pageY,e.matrixTransform(t.getScreenCTM().inverse())},n.rotateElement=function(e,t,n,s){e.setAttribute("transform",`translate(${t},${n}) rotate(${s+90}) translate(${-t},${-n})`)},n.hydrate=function(e,n){for(let s in n)"title"==s?t.title(e,n[s]):e.setAttributeNS(null,s,n[s])},n.elt=function(e,n){let s=document.createElementNS("http://www.w3.org/2000/svg",e);return n&&t.hydrate(s,n),s},n.child=function(e,n,s){let i=t.elt(n,s);return e.appendChild(i),i},n.mkPath=s,n.path=function(e,t,n,i){let r=s(t,n,i);return e.appendChild(r),r},n.fill=function(e,t){e.style.fill=t},n.filter=function(e,t){e.style.filter=t},n.fills=function(e,t){e.forEach(e=>e.style.fill=t)},n.isTouchEnabled=function(){return"undefined"!=typeof window&&("ontouchstart"in window||navigator.maxTouchPoints>0)},n.onClick=function(t,n){let s=!1;e.pointerEvents.down.forEach(e=>t.addEventListener(e,e=>(s=!0,!0),!1)),t.addEventListener(e.pointerEvents.up,e=>!s||(s=!1,n(e),e.preventDefault(),!1),!1)},n.buttonEvents=function(t,n,s,i,r){let o=!1;e.pointerEvents.down.forEach(e=>t.addEventListener(e,e=>(o=!0,s&&s(e),!0),!1)),t.addEventListener(e.pointerEvents.move,e=>!o||(n&&n(e),e.preventDefault(),!1),!1),t.addEventListener(e.pointerEvents.up,e=>{o=!1,i&&i(e)},!1),t.addEventListener(e.pointerEvents.leave,e=>{o=!1,i&&i(e)},!1),t.addEventListener("keydown",e=>{o=!1,r&&r(e)})},n.mkLinearGradient=i,n.linearGradient=function(e,t,n=!1){let s=i(t,n);return e.appendChild(s),s},n.setGradientColors=function(e,t,n){e&&(e.childNodes[0].style.stopColor=t,e.childNodes[1].style.stopColor=t,e.childNodes[2].style.stopColor=n,e.childNodes[3].style.stopColor=n)},n.setGradientValue=function(e,t){e.childNodes[1].getAttribute("offset")!=t&&(e.childNodes[1].setAttribute("offset",t),e.childNodes[2].setAttribute("offset",t))},n.animate=function(t,n){e.U.addClass(t,n);let s=t.parentElement;s&&(s.removeChild(t),s.appendChild(t))},n.mkTitle=r,n.title=function(e,t){let n=r(t);return e.appendChild(n),n},n.toHtmlColor=function(e){return`rgba(${e>>16&255}, ${e>>8&255}, ${255&e}, ${e>>24&1})`}}(t=e.svg||(e.svg={}))}(pxsim||(pxsim={})),function(e){!function(e){class t{constructor(e,n){this.vca=e.createGain(),this.vca.gain.value=1,this.vca.connect(n),t.activeSources.push(this)}static stopAll(){for(const e of t.activeSources)e.dispose();t.activeSources=[]}dispose(){if(this.isDisposed())return;this.vca.disconnect(),this.vca=void 0;const e=t.activeSources.indexOf(this);-1!==e&&t.activeSources.splice(e,1)}isDisposed(){return!this.vca}}t.activeSources=[],e.AudioSource=t}(e.AudioContextManager||(e.AudioContextManager={}))}(pxsim||(pxsim={})),function(e){!function(e){class t extends e.AudioSource{constructor(e,t){super(e,t),this.bufferSource=e.createBufferSource(),this.bufferSource.connect(this.vca)}async playBufferAsync(e,t,n){return new Promise((s,i)=>{this.vca.gain.value=n,this.bufferSource.onended=()=>s(),this.bufferSource.buffer=e,this.bufferSource.playbackRate.value=t,this.bufferSource.start()})}dispose(){super.dispose(),this.bufferSource.disconnect(),this.bufferSource.stop(),this.bufferSource=void 0}}e.AudioBufferSource=t}(e.AudioContextManager||(e.AudioContextManager={}))}(pxsim||(pxsim={})),function(e){!function(e){class t extends e.AudioSource{constructor(e,t){super(e,t),this.context=e}playStreamAsync(e,t,n=.3,s){return new Promise(i=>{let r=[],o=this.context.currentTime,a=!1;this.vca.gain.setValueAtTime(n,o);const l=()=>!(this.vca&&!(null==s?void 0:s()))&&(i&&i(),i=void 0,!0),u=()=>{for(;!a&&r.length<3&&!l();){const t=e();if(!t||!t.length){a=!0;break}c(t)}a&&0===r.length&&(i&&i(),i=void 0)},c=e=>{if(l())return;const n=this.context.createBuffer(1,e.length,t);if(n.copyToChannel)n.copyToChannel(e,0);else{const t=n.getChannelData(0);for(let n=0;n<e.length;n++)t[n]=e[n]}const s=this.context.createBufferSource();r.push(s),s.connect(this.vca),s.buffer=n,s.addEventListener("ended",()=>{r.shift().disconnect(),u()}),s.start(o),o+=n.duration};u()})}}e.AudioBufferStreamSource=t}(e.AudioContextManager||(e.AudioContextManager={}))}(pxsim||(pxsim={})),function(e){!function(t){let n,s,i,r=!1,o=[];function a(){return n||(n=function(){if(window.AudioContext=window.AudioContext||window.webkitAudioContext,window.AudioContext)try{return new window.AudioContext}catch(e){}return}(),n&&(i=n.createGain(),i.connect(n.destination),i.gain.setValueAtTime(1,0))),n}function l(){t.AudioToneSource.dispose(),s&&s.pause()}t.isAudioElementActive=function(){return t.AudioToneSource.isActive()},t.mute=function(e){r=e;const t=a();e?i.gain.setTargetAtTime(0,t.currentTime,.015):i.gain.setTargetAtTime(1,t.currentTime,.015),!e&&t&&"suspended"===t.state&&t.resume()},t.isMuted=function(){return r},t.stopAll=function(){c()},t.stop=function(){l()},t.onStopAll=function(e){o.push(e)},t.frequency=function(){return t.AudioToneSource.getFrequency()};let u=1;function c(){null===t.soundEventCallback||void 0===t.soundEventCallback||t.soundEventCallback("muteallchannels"),u++,l(),t.AudioSource.stopAll();for(const e of o)e()}function h(e,n){if(e<0)return;let s;try{s=t.AudioToneSource.getInstance(a(),i),s.setFrequency(e),s.setGain(n,a().currentTime),s.start()}catch(e){s&&s.dispose()}}async function d(e,n,s){null===t.soundEventCallback||void 0===t.soundEventCallback||t.soundEventCallback("playinstructions",e);const r=new t.PlayInstructionsSource(a(),i);let o=!1;s&&function(e,t,n){const s=t.frequencyBinCount,i=new Float32Array(s),r=new Uint8Array(s),o=()=>{n()||(t.getFloatTimeDomainData(i),t.getByteFrequencyData(r),e({data:i,fft:r}),requestAnimationFrame(o))};requestAnimationFrame(o)}(s,r.analyser,()=>o||(null==n?void 0:n())||r.isDisposed()),await r.playInstructionsAsync(e,n),r.dispose(),o=!0}t.muteAllChannels=c,t.queuePlayInstructions=function(t,n){const s=u;e.U.delay(t).then(()=>s!=u?Promise.resolve():d(n.data))},t.tone=h,t.setCurrentToneGain=function(e){t.AudioToneSource.setCurrentToneGain(e,a().currentTime)},t.playBufferAsync=function(e){return e?new Promise(t=>{function n(){t&&t(),t=void 0}const i="data:audio/wav;base64,"+window.btoa(function(e){let t=e.length,n="";for(let s=0;s<t;++s)n+=String.fromCharCode(e[s]);return n}(e.data));s=new Audio(i),r&&(s.volume=0),s.onended=()=>n(),s.onpause=()=>n(),s.onerror=()=>n(),s.play()}):Promise.resolve()},t.playPCMBufferStreamAsync=async function(e,n,s=.3,r){const o=new t.AudioBufferStreamSource(a(),i);await o.playStreamAsync(e,n,s,r),o.isDisposed()||o.dispose()},t.playInstructionsAsync=d,t.sendMidiMessage=function(e){const t=e.data;if(!t.length)return;const n=t[0]>>4,s=15&t[0],i=t[1]||0,r=(o=i,440*Math.pow(2,(o-69)/12));var o;const a=t[2]||0;8==n||9==n&&0==a?l():9==n&&(h(r,1),9==s&&setTimeout(()=>l(),500))},t.startSamplePlayback=function(n,s,r,o,l){let u=1;o<3e3?(u=o/3e3,o=3e3):o>768e3&&(u=o/768e3,o=768e3);const c=e.BufferMethods.fmtInfo(s).size,h=a().createBuffer(1,n.data.length/c,o),d=h.getChannelData(0);for(let t=0;t<h.length;t++)d[t]=e.BufferMethods.getNumber(n,s,t*c)/r*2-1;const p=new t.AudioBufferSource(a(),i);return{cancel:()=>p.dispose(),promise:p.playBufferAsync(h,u,l)}},t.createAudioSourceNode=function(e,n,s){return new t.AudioElementSource(a(),i,e,n,s).getAudioElement()},t.createSpatialAudioPlayer=function(){return new t.SpatialAudioPlayer(a(),i).id},t.setSpatialAudioPlayerPosition=function(e,n,s,i){const r=t.SpatialAudioPlayer.getPlayerById(e);r&&r.setPosition(n,s,i)},t.setSpatialAudioPlayerOrientation=function(e,n,s,i){const r=t.SpatialAudioPlayer.getPlayerById(e);r&&r.setOrientation(n,s,i)},t.setSpatialAudioPlayerCone=function(e,n,s,i){const r=t.SpatialAudioPlayer.getPlayerById(e);r&&r.setCone(n,s,i)},t.setSpatialAudioRollOff=function(e,n,s,i){const r=t.SpatialAudioPlayer.getPlayerById(e);r&&r.setRollOff(n,s,i)},t.setSpatialAudioDistanceModel=function(e,n){const s=t.SpatialAudioPlayer.getPlayerById(e);s&&s.setDistanceModel(n)},t.disposeSpatialAudioPlayer=function(e){const n=t.SpatialAudioPlayer.getPlayerById(e);n&&n.dispose()},t.queuePlayInstructionsAtSpatialAudioPlayer=function(n,s,i){const r=t.SpatialAudioPlayer.getPlayerById(n);if(r){const t=u;e.U.delay(s).then(()=>t!=u?Promise.resolve():r.playInstructionsAsync(i.data))}},t.setListenerPosition=function(e,t,n){const s=a();s&&(s.listener.positionX.setTargetAtTime(e,0,.02),s.listener.positionY.setTargetAtTime(t,0,.02),s.listener.positionZ.setTargetAtTime(n,0,.02))}}(e.AudioContextManager||(e.AudioContextManager={}))}(pxsim||(pxsim={})),function(e){!function(e){class t extends e.AudioSource{constructor(e,t,n,s,i){super(e,t),this.audioElement=new Audio(n),this.source=e.createMediaElementSource(this.audioElement),this.distortion=e.createWaveShaper(),this.distortion.curve=function(e){const t=44100,n=new Float32Array(t);e=Math.max(.01,Math.min(1,e));const s=1/e;for(let e=0;e<t;e++){const i=(2*e/t-1)*s;n[e]=Math.max(-1,Math.min(1,i))}return n}(s),this.distortion.oversample="4x",this.source.connect(this.distortion),this.distortion.connect(this.vca),this.vca.gain.value=.1*i}getAudioElement(){return this.audioElement}dispose(){super.dispose(),this.source.disconnect(),this.distortion.disconnect(),this.audioElement.pause(),this.audioElement=void 0,this.source=void 0,this.distortion=void 0}}e.AudioElementSource=t}(e.AudioContextManager||(e.AudioContextManager={}))}(pxsim||(pxsim={})),function(e){!function(e){class t extends e.AudioSource{constructor(e,t){super(e,t),this.started=!1,this.oscillator=e.createOscillator(),this.oscillator.type="triangle",this.oscillator.frequency.value=0,this.oscillator.connect(this.vca),this.frequency=0}static getInstance(e,n){return t.instance||(t.instance=new t(e,n)),t.instance}static setCurrentToneGain(e,n){t.instance&&t.instance.setGain(e,n)}static isActive(){return!!t.instance}static getFrequency(){var e;return(null===(e=t.instance)||void 0===e?void 0:e.frequency)||0}static dispose(){t.instance&&t.instance.dispose()}setFrequency(e){this.frequency=e,this.oscillator.frequency.value=e}setGain(e,t){this.vca.gain.setTargetAtTime(e,t,.015)}start(){this.started||(this.oscillator.start(),this.started=!0)}dispose(){super.dispose(),this.oscillator.stop(),this.oscillator.disconnect(),this.oscillator=void 0,t.instance=void 0}}e.AudioToneSource=t}(e.AudioContextManager||(e.AudioContextManager={}))}(pxsim||(pxsim={})),function(e){!function(t){let n=0;class s extends t.AudioSource{constructor(e,t,n=!1){super(e,t),this.isPrivate=n,s.allWorkletSources.push(this),this.analyser=e.createAnalyser(),this.analyser.fftSize=2048,this.node=new AudioWorkletNode(e,"pxt-mixer-audio-worklet-processor"),this.node.connect(this.analyser),this.analyser.connect(this.vca),this.node.port.onmessage=e=>{if("done"===e.data.type){const t=this.activeSounds.find(t=>t.id===e.data.id);t&&(t.resolve(),this.activeSounds=this.activeSounds.filter(e=>e!==t))}},this.activeSounds=[]}static initializeWorklet(t){return s.workletInit||(s.workletInit=t.audioWorklet.addModule(e.getWorkletUri())),s.workletInit}static getAvailableSource(){for(const e of s.allWorkletSources)if(e.activeSounds.length<30&&!e.isPrivate)return e}playInstructionsAsync(e,t){return new Promise(s=>{const i={type:"play",instructions:e,id:n++},r={id:i.id,resolve:s,isCancelled:t};this.activeSounds.push(r),this.node.port.postMessage(i),t&&this.updateActiveSounds()})}dispose(){if(!this.isDisposed()){super.dispose(),s.allWorkletSources=s.allWorkletSources.filter(e=>e!==this),this.node.disconnect(),this.node.port.close(),this.node=void 0,this.analyser.disconnect(),this.analyser=void 0;for(const e of this.activeSounds)e.resolve()}}updateActiveSounds(){var e;if(!this.isDisposed()){this.animRef&&(cancelAnimationFrame(this.animRef),this.animRef=void 0);for(const t of this.activeSounds)(null===(e=t.isCancelled)||void 0===e?void 0:e.call(t))&&(t.resolve(),this.activeSounds=this.activeSounds.filter(e=>e!==t),this.node.port.postMessage({type:"cancel",id:t.id}));this.activeSounds.length&&(this.animRef=requestAnimationFrame(()=>{this.updateActiveSounds()}))}}}s.allWorkletSources=[],t.AudioWorkletSource=s}(e.AudioContextManager||(e.AudioContextManager={}))}(pxsim||(pxsim={})),function(e){!function(e){e.Metronome=class{constructor(){this.tickListeners=[],this.onTick=()=>{for(const e of this.tickListeners)e()}}initAsync(){return this.metronomeLoadPromise?this.metronomeLoadPromise:this.metronomeWorker?this.metronomeWorker:(this.metronomeLoadPromise=new Promise(e=>{this.metronomeWorker=new Worker("data:application/javascript,"+encodeURIComponent(t));const n=t=>{"ready"===t.data&&(e(this.metronomeWorker),this.metronomeWorker.removeEventListener("message",n),this.metronomeWorker.addEventListener("message",this.onTick))};this.metronomeWorker.addEventListener("message",n)}),this.metronomeLoadPromise)}stop(){this.postMessage({type:"stop"})}setInterval(e){this.currentInterval=e,this.postMessage({type:"set-interval",interval:e})}start(e){this.currentInterval=e,this.postMessage({type:"start",interval:e})}addTickListener(e){this.tickListeners.push(e)}removeTickListener(e){this.tickListeners=this.tickListeners.filter(t=>t!==e)}interval(){return this.currentInterval}dispose(){if(this.metronomeWorker)this.metronomeWorker.terminate(),this.metronomeWorker=void 0,this.metronomeLoadPromise=void 0,this.tickListeners=[],this.interval=void 0;else if(this.metronomeLoadPromise)return void this.metronomeLoadPromise.then(()=>this.dispose())}postMessage(e){if(!this.metronomeWorker)throw new Error("initAsync not called on metronome");this.metronomeWorker.postMessage(e)}};const t='\n/**\n * Adpated from https://github.com/cwilso/metronome/\n */\n\nlet timerRef;\nlet interval;\n\naddEventListener("message", ev => {\n const message = ev.data;\n\n if (message.type === "start") {\n updateInterval(message.interval, true);\n }\n else if (message.type === "stop") {\n clearInterval(timerRef);\n timerRef = undefined;\n }\n else if (message.type === "set-interval") {\n updateInterval(message.interval, false);\n }\n})\n\npostMessage("ready");\n\nfunction updateInterval(interval, startIfStopped) {\n if (timerRef) {\n clearInterval(timerRef);\n startIfStopped = true;\n }\n interval = interval;\n\n if (startIfStopped) {\n timerRef = setInterval(() => postMessage("tick"), interval);\n }\n}\n'}(e.music||(e.music={}))}(pxsim||(pxsim={})),function(e){!function(e){!function(e){!function(e){e.chromaticInterval=[1,1.0417,1.125,1.2,1.25,1.3333,1.4063,1.5,1.6,1.6667,1.8,1.875],e.majorScaleInterval=[e.chromaticInterval[0],e.chromaticInterval[2],e.chromaticInterval[4],e.chromaticInterval[5],e.chromaticInterval[7],e.chromaticInterval[9],e.chromaticInterval[11]],e.minorScaleInterval=[e.chromaticInterval[0],e.chromaticInterval[2],e.chromaticInterval[3],e.chromaticInterval[5],e.chromaticInterval[7],e.chromaticInterval[8],e.chromaticInterval[10]],e.pentatonicScaleInterval=[e.chromaticInterval[0],e.chromaticInterval[2],e.chromaticInterval[4],e.chromaticInterval[7],e.chromaticInterval[9]],e.majorTriadInterval=[e.chromaticInterval[0],e.chromaticInterval[4],e.chromaticInterval[7]],e.minorTriadInterval=[e.chromaticInterval[0],e.chromaticInterval[3],e.chromaticInterval[7]],e.diminishedInterval=[e.chromaticInterval[0],e.chromaticInterval[3],e.chromaticInterval[6],e.chromaticInterval[9]],e.wholeToneInterval=[e.chromaticInterval[0],e.chromaticInterval[2],e.chromaticInterval[4],e.chromaticInterval[6],e.chromaticInterval[8],e.chromaticInterval[10]]}(e.MusicalIntervals||(e.MusicalIntervals={}))}(e.music||(e.music={}))}(e.codal||(e.codal={}))}(pxsim||(pxsim={})),function(e){!function(e){!function(e){!function(t){t.chromatic={interval:e.MusicalIntervals.chromaticInterval,length:12},t.majorScale={interval:e.MusicalIntervals.majorScaleInterval,length:7},t.minorScale={interval:e.MusicalIntervals.minorScaleInterval,length:7},t.pentatonicScale={interval:e.MusicalIntervals.pentatonicScaleInterval,length:5},t.majorTriad={interval:e.MusicalIntervals.majorTriadInterval,length:3},t.minorTriad={interval:e.MusicalIntervals.minorTriadInterval,length:3},t.diminished={interval:e.MusicalIntervals.diminishedInterval,length:4},t.wholeTone={interval:e.MusicalIntervals.wholeToneInterval,length:6},t.calculateFrequencyFromProgression=function(e,t,n){let s=Math.floor(n/t.length),i=n%t.length;return e*Math.pow(2,s)*t.interval[i]}}(e.MusicalProgressions||(e.MusicalProgressions={}))}(e.music||(e.music={}))}(e.codal||(e.codal={}))}(pxsim||(pxsim={})),function(e){!function(t){const n=[null,"triangle","sawtooth","sine"];let s,i,r=[],o=[];function a(e,t,a){let l,u=n[t];if(u){let t=e.createOscillator();return t.type=u,t.frequency.value=a,t}if(4==t)l=function(e){if(!i){const t=131072;i=e.createBuffer(1,t,e.sampleRate);const n=i.getChannelData(0);let s=251771520;for(let e=0;e<t;e+=4)s^=s<<13,s^=s>>17,s^=s<<5,32768&s?(n[e]=1,n[e+1]=1,n[e+2]=-1,n[e+3]=-1):(n[e]=0,n[e+1]=0,n[e+2]=0,n[e+3]=0)}return i}(e);else if(5==t)l=function(e){if(!s){const t=1e5;s=e.createBuffer(1,t,e.sampleRate);const n=s.getChannelData(0);let i=251771520;for(let e=0;e<t;e++)i^=i<<13,i^=i>>17,i^=i<<5,n[e]=(1023&i)/512-1}return s}(e);else if(11<=t&&t<=15)l=function(e,t){if(!o[t]){const n=1024,s=e.createBuffer(1,n,e.sampleRate),i=s.getChannelData(0);for(let e=0;e<n;e++)i[e]=e<t/100*n?1:-1;o[t]=s}return o[t]}(e,10*(t-10));else{if(!(16<=t&&t<=18))return null;l=function(e,t){if(!r[t]){const n=1024,s=e.createBuffer(1,n,e.sampleRate),i=s.getChannelData(0),o=[770763591,3356908179],a=[15,31,63];for(let e=0;e<n;e+=4){let n,s=e/4;s&=a[t-4],n=!!(o[s>>5]&1<<(31&s)),n?(i[e]=1,i[e+1]=1,i[e+2]=-1,i[e+3]=-1):(i[e]=0,i[e+1]=0,i[e+2]=0,i[e+3]=0)}r[t]=s}return r[t]}(e,t-16+4)}let c=e.createBufferSource();c.buffer=l,c.loop=!0;return 4==t||16<=t&&t<=18?c.playbackRate.value=a/(e.sampleRate/4):5!=t&&(c.playbackRate.value=a/(e.sampleRate/1024)),c}class l extends t.AudioSource{constructor(e,t){super(e,t),this.context=e,this.destination=t,this.analyser=e.createAnalyser(),this.analyser.fftSize=2048,this.analyser.connect(this.vca),this.gain=e.createGain(),this.gain.connect(this.analyser)}playInstructionsAsync(n,s,i){return new Promise(async r=>{null===t.soundEventCallback||void 0===t.soundEventCallback||t.soundEventCallback("playinstructions",n);let o=!1;const l={},c={};let h=this.context.currentTime,d=h,p=0,f=0;const m=(e,t)=>e/1024/4*(t?.5:1),g=()=>{if(!o){o=!0;for(const e of Object.keys(l))l[e].stop(),l[e].disconnect(),c[e].disconnect();r()}};for(let e=0;e<n.length;e+=12){const t=n[e],s=u(n,e+2),i=u(n,e+4)/1e3,r=u(n,e+6),o=u(n,e+8),h=u(n,e+10);if(f+=i,0===t){d+=i;continue}const g=11<=t&&t<=15;l[t]||(l[t]=a(this.context,t,s),c[t]=this.context.createGain(),c[t].gain.value=0,c[t].connect(this.gain),l[t].connect(c[t]),l[t].start()),p&&t!==p&&c[p].gain.setTargetAtTime(0,d,.015);const b=l[t],v=c[t];if(b instanceof OscillatorNode)b.frequency.setValueAtTime(s,d),b.frequency.linearRampToValueAtTime(h,d+i);else{4==t||16<=t&&t<=18?b.playbackRate.linearRampToValueAtTime(h/(this.context.sampleRate/4),d+i):5!=t&&b.playbackRate.linearRampToValueAtTime(h/(this.context.sampleRate/1024),d+i)}v.gain.setValueAtTime(m(r,g),d),v.gain.linearRampToValueAtTime(m(o,g),d+i),p=t,d+=i}if(this.gain.gain.setTargetAtTime(0,d,.015),s||i){const e=()=>{const t=this.context.currentTime;if(t>h+f)return;if(s&&s()||this.isDisposed())return void g();const{frequency:r,volume:o}=function(e,t){let n=0;for(let s=0;s<t.length;s+=12){const i=u(t,s+2),r=u(t,s+4),o=u(t,s+6),a=u(t,s+8),l=u(t,s+10);if(n+r<e){n+=r;continue}const c=(e-n)/r;return{frequency:i+(l-i)*c,volume:o+(a-o)*c}}return{frequency:-1,volume:-1}}(1e3*(t-h),n);i&&i(r,o/1024),requestAnimationFrame(e)};requestAnimationFrame(e)}await e.U.delay(1e3*f),g()})}dispose(){this.isDisposed()||(super.dispose(),this.analyser.disconnect(),this.gain.disconnect(),this.analyser=void 0,this.gain=void 0)}}function u(e,t){const n=new Uint8Array(2);return n[0]=e[t],n[1]=e[t+1],new Uint16Array(n.buffer)[0]}t.PlayInstructionsSource=l}(e.AudioContextManager||(e.AudioContextManager={}))}(pxsim||(pxsim={})),function(e){!function(t){const n=[31,33,35,37,39,41,44,46,49,52,55,58,62,65,69,73,78,82,87,92,98,104,110,117,123,131,139,147,156,165,175,185,196,208,220,233,247,262,277,294,311,330,349,370,392,415,440,466,494,523,554,587,622,659,698,740,784,831,880,932,988,1047,1109,1175,1245,1319,1397,1480,1568,1661,1760,1865,1976,2093,2217,2349,2489,2637,2794,2960,3136,3322,3520,3729,3951,4186,4435,4699,4978,5274,5588,5920,6272,6645,7040,7459,7902];async function s(t,s,i,r,o=100){await e.AudioContextManager.playInstructionsAsync(e.music.renderInstrument(s,n[t],i,o),r)}async function i(t,n,s=100){await e.AudioContextManager.playInstructionsAsync(e.music.renderDrumInstrument(t,s),n)}async function r(t,s,i,r,o=100){await t.playInstructionsAsync(e.music.renderInstrument(i,n[s],r,o))}async function o(t,n,s=100){await t.playInstructionsAsync(e.music.renderDrumInstrument(n,s))}function a(e,t,n){return 6e4/e/t*n}t.Sequencer=class{constructor(){this._currentTick=0,this._state="stop",this.listeners={},this.globalVolume=1024,this.trackVolumes=[],this.drumTrackVolumes=[],this.currentCancelToken={cancelled:!1},this.onTick=()=>{const e=this.currentCancelToken;for(let t=0;t<this.currentlyPlaying.tracks.length;t++){const n=this.currentlyPlaying.tracks[t];for(const l of n.notes)if(l.startTick===this._currentTick)for(const u of l.notes)this.spatialAudioPlayer?n.drums?o(this.spatialAudioPlayer,n.drums[u.note],this.getDrumTrackVolume(t,u.note)):r(this.spatialAudioPlayer,u.note,n.instrument,a(this.currentlyPlaying.beatsPerMinute,this.currentlyPlaying.ticksPerBeat,l.endTick-l.startTick),this.getMelodicTrackVolume(t)):n.drums?i(n.drums[u.note],()=>e.cancelled,this.getDrumTrackVolume(t,u.note)):s(u.note,n.instrument,a(this.currentlyPlaying.beatsPerMinute,this.currentlyPlaying.ticksPerBeat,l.endTick-l.startTick),()=>e.cancelled,this.getMelodicTrackVolume(t));else if(l.startTick>this._currentTick)break}this.fireEvent("tick"),this._currentTick++,this._currentTick>=this.maxTick()&&("loop"===this._state?(this._currentTick=0,this.fireEvent("looped")):this.stop(!0))}}async initAsync(){this.metronome?await this.metronome.initAsync():(this.metronome=new t.Metronome,await this.metronome.initAsync(),this.metronome.addTickListener(this.onTick))}dispose(){this.metronome&&this.metronome.dispose(),this.metronome=void 0,this.stop(),this.currentlyPlaying=void 0,this.listeners={}}state(){return this._state}currentTick(){return this._currentTick}currentTime(){return a(this.currentlyPlaying.beatsPerMinute,this.currentlyPlaying.ticksPerBeat,this.currentTick())}maxTick(){return this.currentlyPlaying?this.currentlyPlaying.measures*this.currentlyPlaying.beatsPerMeasure*this.currentlyPlaying.ticksPerBeat:0}duration(){return a(this.currentlyPlaying.beatsPerMinute,this.currentlyPlaying.ticksPerBeat,this.maxTick())}start(e,t){this.startFrom(e,t,0)}startFrom(e,t,n){"stop"!==this._state&&this.stop(),void 0!==t&&(this.shouldLoop=t),this._currentTick=null!=n?n:0,this.currentlyPlaying=e,this.metronome.start(a(e.beatsPerMinute,e.ticksPerBeat,1)),this._state=this.shouldLoop?"loop":"play",this.fireStateChange()}stop(e=!1){"stop"!==this._state&&(this._state="stop",this.metronome&&this.metronome.stop(),this.fireStateChange(),e||(this.currentCancelToken.cancelled=!0),this.currentCancelToken={cancelled:!1})}updateSong(e){this.currentlyPlaying=e,"stop"!==this._state&&this.metronome.setInterval(a(e.beatsPerMinute,e.ticksPerBeat,1))}setLooping(e){e&&"play"===this._state?(this._state="loop",this.fireStateChange()):e||"loop"!==this._state||(this._state="play",this.fireStateChange()),this.shouldLoop=e}addEventListener(e,t){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(t)}removeEventListener(e,t){this.listeners[e]&&(this.listeners[e]=this.listeners[e].filter(e=>e!==t))}setVolume(e){this.globalVolume=Math.min(Math.max(e,0),1024)}setTrackVolume(e,t){for(t=Math.min(Math.max(t,0),1024);this.trackVolumes.length<e;)this.trackVolumes.push(1024);this.trackVolumes[e]=t}setDrumTrackVolume(e,t,n){for(n=Math.min(Math.max(n,0),1024);this.drumTrackVolumes.length<e;)this.drumTrackVolumes.push([]);for(;this.drumTrackVolumes[e].length<t;)this.drumTrackVolumes[e].push(1024);this.drumTrackVolumes[e][t]=n}setSpatialAudioPlayer(e){this.spatialAudioPlayer=e}getMelodicTrackVolume(e){let t=1024;return e<this.trackVolumes.length&&(t=this.trackVolumes[e]),this.globalVolume*(t/1024)}getDrumTrackVolume(e,t){const n=this.getMelodicTrackVolume(e);let s=1024;return e<this.drumTrackVolumes.length&&t<this.drumTrackVolumes[e].length&&(s=this.drumTrackVolumes[e][t]),n*(s/1024)}fireStateChange(){this.fireEvent(this._state),this.fireEvent("state-change")}fireEvent(e){if(this.listeners[e])for(const t of this.listeners[e])t()}},t.playNoteAsync=s,t.playDrumAsync=i,t.tickToMs=a}(e.music||(e.music={}))}(pxsim||(pxsim={})),function(e){!function(e){function t(e,t,n,r){var o,a;let l=0;return(null===(o=e.pitchEnvelope)||void 0===o?void 0:o.amplitude)&&(l+=s(e.pitchEnvelope,r,n)),(null===(a=e.pitchLFO)||void 0===a?void 0:a.amplitude)&&(l+=i(e.pitchLFO,r)),Math.max(t+l,0)}function n(e,t,n,r){var o;let a=0;return e.ampEnvelope.amplitude&&(a+=s(e.ampEnvelope,n,t)),(null===(o=e.ampLFO)||void 0===o?void 0:o.amplitude)&&(a+=i(e.ampLFO,n)),Math.max(Math.min(a,e.ampEnvelope.amplitude),0)/1024*r|0}function s(e,t,n){const s=e.sustain/1024*e.amplitude;if(t>n){if(t-n>e.release)return 0;if(t<e.attack){const s=e.amplitude/e.attack*n;return s-s/e.release*(t-n)}if(t<e.attack+e.decay){const i=e.amplitude-(e.amplitude-s)/e.decay*(n-e.attack);return i-i/e.release*(t-n)}return s-s/e.release*(t-n)}return t<e.attack?e.amplitude/e.attack*t:t<e.attack+e.decay?e.amplitude-(e.amplitude-s)/e.decay*(t-e.attack):s}function i(e,t){return Math.cos(t/1e3*e.frequency*2*Math.PI)*e.amplitude}function r(e,t,n,s,i,r,a,l){return n>0&&(e[t]=r,e[t+1]=0,o(e,t+2,a),o(e,t+4,n),o(e,t+6,255*s>>6),o(e,t+8,255*i>>6),o(e,t+10,l),t+=12),e[t]=0,t}function o(e,t,n){const s=new Uint8Array(2);new Uint16Array(s.buffer)[0]=0|n,e[t]=s[0],e[t+1]=s[1]}function a(e,t){const n=new Uint8Array(2);return n[0]=e[t],n[1]=e[t+1],new Uint16Array(n.buffer)[0]}function l(e,t){return{waveform:e[t],ampEnvelope:{attack:a(e,t+1),decay:a(e,t+3),sustain:a(e,t+5),release:a(e,t+7),amplitude:a(e,t+9)},pitchEnvelope:{attack:a(e,t+11),decay:a(e,t+13),sustain:a(e,t+15),release:a(e,t+17),amplitude:a(e,t+19)},ampLFO:{frequency:e[t+21],amplitude:a(e,t+22)},pitchLFO:{frequency:e[t+24],amplitude:a(e,t+25)},octave:e[t+27]}}function u(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=a(e,t+2);let i=t+4;for(;i<t+4+s;)n.drums.push(c(e,i)),i+=5+7*n.drums[n.drums.length-1].steps.length;const r=a(e,i);i+=2;for(;i<t+4+s+r;)n.notes.push(h(e,i,0,!0)),i+=5+n.notes[n.notes.length-1].notes.length;return[n,i]}(e,t):function(e,t){const n={id:e[t],instrument:l(e,t+4),notes:[]},s=t+4+a(e,t+2),i=a(e,s);let r=s+2;for(;r<s+2+i;)n.notes.push(h(e,r,n.instrument.octave,!1)),r+=5+n.notes[n.notes.length-1].notes.length;return[n,r]}(e,t)}function c(e,t){const n={startFrequency:a(e,t+1),startVolume:a(e,t+3),steps:[]};for(let s=0;s<e[t];s++){const i=t+5+7*s;n.steps.push({waveform:e[i],frequency:a(e,i+1),volume:a(e,i+3),duration:a(e,i+5)})}return n}function h(e,t,n,s){const i={startTick:a(e,t),endTick:a(e,t+2),notes:[]};for(let r=0;r<e[t+4];r++)i.notes.push(d(e[t+5+r],n,s));return i}function d(e,t,n){const s=e>>6,i={note:n?e:(63&e)+12*(t-2),enharmonicSpelling:"normal"};return 1===s?i.enharmonicSpelling="flat":2===s&&(i.enharmonicSpelling="sharp"),i}e.renderInstrument=function(e,s,i,o){var a,l,u,c,h;const d=i+e.ampEnvelope.release,p=(null===(a=e.ampLFO)||void 0===a?void 0:a.amplitude)?Math.max(500/e.ampLFO.frequency,50):50,f=(null===(l=e.pitchLFO)||void 0===l?void 0:l.amplitude)?Math.max(500/e.pitchLFO.frequency,50):50;let m=[0],g=e.ampEnvelope.attack,b=(null===(u=e.pitchEnvelope)||void 0===u?void 0:u.amplitude)?e.pitchEnvelope.attack:d,v=(null===(c=e.pitchLFO)||void 0===c?void 0:c.amplitude)?f:d,y=(null===(h=e.ampLFO)||void 0===h?void 0:h.amplitude)?p:d,S=0;for(;S<d&&(g<=b&&g<=v&&g<=y?(S=g,m.push(g),g=S<e.ampEnvelope.attack+e.ampEnvelope.decay&&e.ampEnvelope.attack+e.ampEnvelope.decay<i?e.ampEnvelope.attack+e.ampEnvelope.decay:S<i?i:d):b<=v&&b<=y&&b<d?(S=b,m.push(b),b=S<e.pitchEnvelope.attack+e.pitchEnvelope.decay&&e.pitchEnvelope.attack+e.pitchEnvelope.decay<i?e.pitchEnvelope.attack+e.pitchEnvelope.decay:S<i?i:S<i+e.pitchEnvelope.release?Math.min(d,i+e.pitchEnvelope.release):d):v<=y&&v<d?(S=v,m.push(v),v+=f):y<d&&(S=y,m.push(y),y+=p),!(S>=d));){for(g<=S&&(g=S<e.ampEnvelope.attack+e.ampEnvelope.decay&&e.ampEnvelope.attack+e.ampEnvelope.decay<i?e.ampEnvelope.attack+e.ampEnvelope.decay:S<i?i:d),b<=S&&(b=S<e.pitchEnvelope.attack+e.pitchEnvelope.decay&&e.pitchEnvelope.attack+e.pitchEnvelope.decay<i?e.pitchEnvelope.attack+e.pitchEnvelope.decay:S<i?i:S<i+e.pitchEnvelope.release?Math.min(d,i+e.pitchEnvelope.release):d);y<=S;)y+=p;for(;v<=S;)v+=f}let w,x,E=0|n(e,i,0,o),I=0|t(e,s,i,0),k=0;const C=new Uint8Array(12*(m.length+1));for(let a=1;a<m.length;a++)m[a]-k<5||(w=0|n(e,i,m[a],o),x=0|t(e,s,i,m[a]),r(C,12*(a-1),m[a]-k|0,E,w,e.waveform,I,x),E=w,I=x),k=m[a];return r(C,12*m.length,10,E,0,e.waveform,I,I),C},e.renderDrumInstrument=function(e,t){let n=e.startVolume,s=e.startFrequency;const i=e=>e/1024*t;let o=new Uint8Array(12*(e.steps.length+1));for(let t=0;t<e.steps.length;t++)r(o,12*t,e.steps[t].duration,i(n),i(e.steps[t].volume),e.steps[t].waveform,s,e.steps[t].frequency),n=e.steps[t].volume,s=e.steps[t].frequency;return r(o,12*e.steps.length,10,i(n),0,e.steps[e.steps.length-1].waveform,s,s),o},e.decodeSong=function(e){const t={beatsPerMinute:a(e,1),beatsPerMeasure:e[3],ticksPerBeat:e[4],measures:e[5],tracks:[]};let n=7;for(;n<e.length;){const[s,i]=u(e,n);n=i,t.tracks.push(s)}return t}}(e.music||(e.music={}))}(pxsim||(pxsim={})),function(e){!function(e){!function(e){e.EMOJI_SYNTHESIZER_SAMPLE_RATE=44100,e.EMOJI_SYNTHESIZER_TONE_WIDTH_F=1024,e.EMOJI_SYNTHESIZER_TONE_WIDTH=1024,e.EMOJI_SYNTHESIZER_BUFFER_SIZE=512,e.EMOJI_SYNTHESIZER_TONE_EFFECT_PARAMETERS=2,e.EMOJI_SYNTHESIZER_TONE_EFFECTS=3,e.EMOJI_SYNTHESIZER_STATUS_ACTIVE=1,e.EMOJI_SYNTHESIZER_STATUS_OUTPUT_SILENCE_AS_EMPTY=2,e.EMOJI_SYNTHESIZER_STATUS_STOPPING=4;e.SoundEmojiSynthesizer=class{constructor(t,n=e.EMOJI_SYNTHESIZER_SAMPLE_RATE){this.samplesPerStep=[],this.status=0,this.effectPointer=0,this.position=0,this.bufferSize=e.EMOJI_SYNTHESIZER_BUFFER_SIZE,this.sampleRate=n,this.samplesToWrite=0,this.samplesWritten=0,this.sampleRange=1023,this.orMask=0,this.effectPointer=-1,this.volume=1}get effect(){return this.effectBuffer[this.effectPointer]}play(e){this.effectBuffer=e,this.effectPointer=-1,this.nextSoundEffect()}nextSoundEffect(){const t=null!=this.effect;if(this.status&e.EMOJI_SYNTHESIZER_STATUS_STOPPING&&(this.effectPointer=null,this.effectBuffer=[]),this.effect?this.effectPointer++:this.effectPointer=0,this.effectPointer>=this.effectBuffer.length&&(this.effectPointer=0,this.effect.duration>=0))return this.effectPointer=-1,this.effectBuffer=[],this.samplesWritten=0,this.samplesToWrite=0,this.position=0,t;this.samplesToWrite=this.determineSampleCount(this.effect.duration),this.frequency=this.effect.frequency,this.volume=this.effect.volume,this.samplesWritten=0;for(let t=0;t<e.EMOJI_SYNTHESIZER_TONE_EFFECTS;t++)this.effect.effects[t].step=0,this.effect.effects[t].steps=Math.max(this.effect.effects[t].steps,1),this.samplesPerStep[t]=Math.floor(this.samplesToWrite/this.effect.effects[t].steps);return!1}pull(){let t,n,s=!1;for(;!s;){if(this.samplesWritten==this.samplesToWrite||this.status&e.EMOJI_SYNTHESIZER_STATUS_STOPPING){let t=this.nextSoundEffect();(0==this.samplesToWrite||this.status&e.EMOJI_SYNTHESIZER_STATUS_STOPPING)&&(s=!0,(t||this.status&e.EMOJI_SYNTHESIZER_STATUS_STOPPING)&&(this.status&=~e.EMOJI_SYNTHESIZER_STATUS_STOPPING))}for(!(this.samplesWritten<this.samplesToWrite)&&this.status&e.EMOJI_SYNTHESIZER_STATUS_OUTPUT_SILENCE_AS_EMPTY||null!=t||(this.buffer=new Array(this.bufferSize),t=0,n=this.buffer.length);this.samplesWritten<this.samplesToWrite;){let s=e.EMOJI_SYNTHESIZER_TONE_WIDTH_F*this.frequency/this.sampleRate,i=this.sampleRange*this.volume/1024,r=512-512*i,o=[];for(let t=0;t<e.EMOJI_SYNTHESIZER_TONE_EFFECTS;t++)o[t]=this.samplesPerStep[t]*this.effect.effects[t].step,this.effect.effects[t].step==this.effect.effects[t].steps-1&&(o[t]=this.samplesToWrite);let a=o[0];for(let t=1;t<e.EMOJI_SYNTHESIZER_TONE_EFFECTS;t++)a=Math.min(a,o[t]);for(;this.samplesWritten<a;){if(t==n)return this.buffer;let o=this.effect.tone.tonePrint(this.effect.tone.parameter,Math.max(this.position,0));for(this.buffer[t]=o*i+r,t++,this.samplesWritten++,this.position+=s;this.position>e.EMOJI_SYNTHESIZER_TONE_WIDTH_F;)this.position-=e.EMOJI_SYNTHESIZER_TONE_WIDTH_F}for(let t=0;t<e.EMOJI_SYNTHESIZER_TONE_EFFECTS;t++)this.samplesWritten==o[t]&&this.effect.effects[t].step<this.effect.effects[t].steps&&(this.effect.effects[t].effect&&this.effect.effects[t].effect(this,this.effect.effects[t]),this.effect.effects[t].step++)}}if(null==t)this.buffer=[];else{const e=.5*this.sampleRange;for(;t<n;)this.buffer[t]=e,t++}return this.buffer}determineSampleCount(e){e<0&&(e=-e);const t=e/1e3;return Math.floor(this.sampleRate*t)}totalDuration(){let e=0;for(const t of this.effectBuffer)e+=t.duration;return e}}}(e.music||(e.music={}))}(e.codal||(e.codal={}))}(pxsim||(pxsim={})),function(e){!function(e){!function(e){!function(e){const t=[0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,3,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,11,11,12,13,13,14,15,16,16,17,18,19,20,21,22,22,23,24,25,26,27,28,29,30,32,33,34,35,36,37,38,40,41,42,43,45,46,47,49,50,51,53,54,56,57,58,60,61,63,64,66,68,69,71,72,74,76,77,79,81,82,84,86,87,89,91,93,95,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,141,143,145,147,149,152,154,156,158,161,163,165,167,170,172,175,177,179,182,184,187,189,191,194,196,199,201,204,206,209,211,214,216,219,222,224,227,229,232,235,237,240,243,245,248,251,253,256,259,262,264,267,270,273,275,278,281,284,287,289,292,295,298,301,304,307,309,312,315,318,321,324,327,330,333,336,339,342,345,348,351,354,357,360,363,366,369,372,375,378,381,384,387,390,393,396,399,402,405,408,411,414,417,420,424,427,430,433,436,439,442,445,448,452,455,458,461,464,467,470,473,477,480,483,486,489,492,495,498,502,505,508,511,514,517,520,524,527,530,533,536,539,542,545,549,552,555,558,561,564,567,570,574,577,580,583,586,589,592,595,598,602,605,608,611,614,617,620,623,626,629,632,635,638,641,644,647,650,653,656,659,662,665,668,671,674,677,680,683,686,689,692,695,698,701,704,707,710,713,715,718,721,724,727,730,733,735,738,741,744,747,749,752,755,758,760,763,766,769,771,774,777,779,782,785,787,790,793,795,798,800,803,806,808,811,813,816,818,821,823,826,828,831,833,835,838,840,843,845,847,850,852,855,857,859,861,864,866,868,870,873,875,877,879,881,884,886,888,890,892,894,896,898,900,902,904,906,908,910,912,914,916,918,920,922,924,926,927,929,931,933,935,936,938,940,941,943,945,946,948,950,951,953,954,956,958,959,961,962,964,965,966,968,969,971,972,973,975,976,977,979,980,981,982,984,985,986,987,988,989,990,992,993,994,995,996,997,998,999,1e3,1e3,1001,1002,1003,1004,1005,1006,1006,1007,1008,1009,1009,1010,1011,1011,1012,1013,1013,1014,1014,1015,1015,1016,1016,1017,1017,1018,1018,1019,1019,1019,1020,1020,1020,1021,1021,1021,1021,1022,1022,1022,1022,1022,1022,1022,1022,1022,1022,1023,1022];e.SineTone=function(e,n){let s=1024-(n|=0);return s<512&&(n=s),t[n]},e.SawtoothTone=function(e,t){return t},e.TriangleTone=function(e,t){return t<512?2*t:2*(1023-t)},e.NoiseTone=function(e,t){let n=e[0];return 0==n&&(n=7919),t*n&1023},e.SquareWaveTone=function(e,t){return t<512?1023:0}}(e.Synthesizer||(e.Synthesizer={}))}(e.music||(e.music={}))}(e.codal||(e.codal={}))}(pxsim||(pxsim={})),function(e){!function(e){!function(e){!function(t){t.noInterpolation=function(e,t){},t.linearInterpolation=function(e,t){let n=(t.parameter[0]-e.effect.frequency)/t.steps;e.frequency=e.effect.frequency+n*t.step},t.logarithmicInterpolation=function(e,t){e.frequency=e.effect.frequency+Math.log10(Math.max(t.step,.1))*(t.parameter[0]-e.effect.frequency)/1.95},t.curveInterpolation=function(e,t){e.frequency=Math.sin(3.12159*t.step/180)*(t.parameter[0]-e.effect.frequency)+e.effect.frequency},t.slowVibratoInterpolation=function(e,t){e.frequency=Math.sin(t.step/10)*t.parameter[0]+e.effect.frequency},t.warbleInterpolation=function(e,t){e.frequency=Math.sin(t.step)*(t.parameter[0]-e.effect.frequency)+e.effect.frequency},t.vibratoInterpolation=function(e,t){e.frequency=e.effect.frequency+Math.sin(t.step)*t.parameter[0]},t.exponentialRisingInterpolation=function(e,t){e.frequency=e.effect.frequency+Math.sin(.01745329*t.step)*t.parameter[0]},t.exponentialFallingInterpolation=function(e,t){e.frequency=e.effect.frequency+Math.cos(.01745329*t.step)*t.parameter[0]},t.appregrioAscending=function(t,n){t.frequency=e.MusicalProgressions.calculateFrequencyFromProgression(t.effect.frequency,n.parameter_p[0],n.step)},t.appregrioDescending=function(t,n){t.frequency=e.MusicalProgressions.calculateFrequencyFromProgression(t.effect.frequency,n.parameter_p[0],n.steps-n.step-1)},t.frequencyVibratoEffect=function(e,t){0!=t.step&&(t.step%2==0?e.frequency/=t.parameter[0]:e.frequency*=t.parameter[0])},t.volumeVibratoEffect=function(e,t){0!=t.step&&(t.step%2==0?e.volume/=t.parameter[0]:e.volume*=t.parameter[0])},t.adsrVolumeEffect=function(e,t){let n=.5*t.steps;if(t.step<=n){let s=(t.parameter[0]-e.effect.volume)/n;e.volume=e.effect.volume+t.step*s}else{let s=(t.parameter[1]-t.parameter[0])/n;e.volume=t.parameter[0]+(t.step-n)*s}},t.volumeRampEffect=function(e,t){let n=(t.parameter[0]-e.effect.volume)/t.steps;e.volume=e.effect.volume+t.step*n}}(e.SoundSynthesizerEffects||(e.SoundSynthesizerEffects={}))}(e.music||(e.music={}))}(e.codal||(e.codal={}))}(pxsim||(pxsim={})),function(e){!function(t){!function(t){let n,s,i;!function(e){e[e.Sine=0]="Sine",e[e.Sawtooth=1]="Sawtooth",e[e.Triangle=2]="Triangle",e[e.Square=3]="Square",e[e.Noise=4]="Noise"}(n=t.WaveShape||(t.WaveShape={})),function(e){e[e.None=0]="None",e[e.Linear=1]="Linear",e[e.Curve=2]="Curve",e[e.ExponentialRising=5]="ExponentialRising",e[e.ExponentialFalling=6]="ExponentialFalling",e[e.ArpeggioRisingMajor=8]="ArpeggioRisingMajor",e[e.ArpeggioRisingMinor=10]="ArpeggioRisingMinor",e[e.ArpeggioRisingDiminished=12]="ArpeggioRisingDiminished",e[e.ArpeggioRisingChromatic=14]="ArpeggioRisingChromatic",e[e.ArpeggioRisingWholeTone=16]="ArpeggioRisingWholeTone",e[e.ArpeggioFallingMajor=9]="ArpeggioFallingMajor",e[e.ArpeggioFallingMinor=11]="ArpeggioFallingMinor",e[e.ArpeggioFallingDiminished=13]="ArpeggioFallingDiminished",e[e.ArpeggioFallingChromatic=15]="ArpeggioFallingChromatic",e[e.ArpeggioFallingWholeTone=17]="ArpeggioFallingWholeTone",e[e.Logarithmic=18]="Logarithmic"}(s=t.InterpolationEffect||(t.InterpolationEffect={})),function(e){e[e.None=0]="None",e[e.Vibrato=1]="Vibrato",e[e.Tremolo=2]="Tremolo",e[e.Warble=3]="Warble"}(i=t.Effect||(t.Effect={}));class r{constructor(){this.src="000000000000000000000000000000000000000000000000000000000000000000000000"}get wave(){return this.getValue(0,1)}set wave(e){this.setValue(0,g(e,0,4),1)}get volume(){return this.getValue(1,4)}set volume(e){this.setValue(1,g(e,0,1023),4)}get frequency(){return this.getValue(5,4)}set frequency(e){this.setValue(5,e,4)}get duration(){return this.getValue(9,4)}set duration(e){this.setValue(9,e,4)}get shape(){return this.getValue(13,2)}set shape(e){this.setValue(13,e,2)}get endFrequency(){return this.getValue(18,4)}set endFrequency(e){this.setValue(18,e,4)}get endVolume(){return this.getValue(26,4)}set endVolume(e){this.setValue(26,g(e,0,1023),4)}get steps(){return this.getValue(30,4)}set steps(e){this.setValue(30,e,4)}get fx(){return this.getValue(34,2)}set fx(e){this.setValue(34,g(e,0,3),2)}get fxParam(){return this.getValue(36,4)}set fxParam(e){this.setValue(36,e,4)}get fxnSteps(){return this.getValue(40,4)}set fxnSteps(e){this.setValue(40,e,4)}get frequencyRandomness(){return this.getValue(44,4)}set frequencyRandomness(e){this.setValue(44,e,4)}get endFrequencyRandomness(){return this.getValue(48,4)}set endFrequencyRandomness(e){this.setValue(48,e,4)}get volumeRandomness(){return this.getValue(52,4)}set volumeRandomness(e){this.setValue(52,e,4)}get endVolumeRandomness(){return this.getValue(56,4)}set endVolumeRandomness(e){this.setValue(56,e,4)}get durationRandomness(){return this.getValue(60,4)}set durationRandomness(e){this.setValue(60,e,4)}get fxParamRandomness(){return this.getValue(64,4)}set fxParamRandomness(e){this.setValue(64,e,4)}get fxnStepsRandomness(){return this.getValue(68,4)}set fxnStepsRandomness(e){this.setValue(68,e,4)}copy(){const e=new r;return e.src=this.src.slice(0),e}setValue(e,t,n){t=g(0|t,0,Math.pow(10,n)-1),this.src=this.src.substr(0,e)+function(e,t){let n=e+"";for(;n.length<t;)n="0"+n;return n}(t,n)+this.src.substr(e+n)}getValue(e,t){return parseInt(this.src.substr(e,t))}}t.Sound=r;let o,a=!1,l={cancelled:!1};async function u(){if(o.length){a=!0;const e=o.shift();let t=l;try{e.onStarted(),await h(e.notes,()=>t.cancelled,void 0,e.volume),t.cancelled?e.onCancelled():e.onFinished()}catch(t){e.onCancelled()}u()}else a=!1}function c(){o=[],l.cancelled=!0,l={cancelled:!1}}function h(n,s,i,r=.03){const o=new t.SoundEmojiSynthesizer(0),a=function(e){const t=72,n=Math.floor((e.length+1)/(t+1)),s=n*(t+1)-1;if(e.length!=s)return[];const i=[];for(let s=0;s<n;++s){const n=s*t+s;if(n>0&&","!=e[n-1])return[];const r=m();if(!d(e.substr(n),r))return[];i.push(r)}return i}(n);o.play(a);let l=!1;return Promise.race([(u=o.totalDuration(),new Promise(e=>setTimeout(e,u))).then(()=>{l=!0}),e.AudioContextManager.playPCMBufferStreamAsync(()=>{if(!o.effect)return;const e=o.pull();i&&i({frequency:o.frequency,volume:o.volume});const t=new Float32Array(e.length);for(let n=0;n<e.length;n++)t[n]=(e[n]-512)/512;return t},o.sampleRate,r,()=>l||s&&s())]);var u}function d(e,n){let s=parseInt(e.substr(0,1)),i=parseInt(e.substr(1,4)),r=parseInt(e.substr(5,4)),o=parseInt(e.substr(9,4)),a=parseInt(e.substr(13,2)),l=parseInt(e.substr(18,4)),u=parseInt(e.substr(26,4)),c=parseInt(e.substr(30,4)),h=parseInt(e.substr(34,2)),d=parseInt(e.substr(36,4)),m=parseInt(e.substr(40,4));if(r=f(r,parseInt(e.substr(44,4))),l=f(l,parseInt(e.substr(48,4))),i=f(i,parseInt(e.substr(52,4))),u=f(u,parseInt(e.substr(56,4))),o=f(o,parseInt(e.substr(60,4))),d=f(d,parseInt(e.substr(64,4))),m=f(m,parseInt(e.substr(68,4))),-1==r||-1==l||-1==i||-1==u||-1==o||-1==d||-1==m)return!1;switch(s){case 0:n.tone.tonePrint=t.Synthesizer.SineTone;break;case 1:n.tone.tonePrint=t.Synthesizer.SawtoothTone;break;case 2:n.tone.tonePrint=t.Synthesizer.TriangleTone;break;case 3:n.tone.tonePrint=t.Synthesizer.SquareWaveTone;break;case 4:n.tone.tonePrint=t.Synthesizer.NoiseTone}switch(n.frequency=r,n.duration=o,n.effects[0].steps=c,a){case 0:n.effects[0].effect=t.SoundSynthesizerEffects.noInterpolation;break;case 1:n.effects[0].effect=t.SoundSynthesizerEffects.linearInterpolation,n.effects[0].parameter[0]=l;break;case 2:n.effects[0].effect=t.SoundSynthesizerEffects.curveInterpolation,n.effects[0].parameter[0]=l;break;case 5:n.effects[0].effect=t.SoundSynthesizerEffects.exponentialRisingInterpolation,n.effects[0].parameter[0]=l;break;case 6:n.effects[0].effect=t.SoundSynthesizerEffects.exponentialFallingInterpolation,n.effects[0].parameter[0]=l;break;case 8:case 10:case 12:case 14:case 16:n.effects[0].effect=t.SoundSynthesizerEffects.appregrioAscending;break;case 9:case 11:case 13:case 15:case 17:n.effects[0].effect=t.SoundSynthesizerEffects.appregrioDescending;break;case 18:n.effects[0].effect=t.SoundSynthesizerEffects.logarithmicInterpolation,n.effects[0].parameter[0]=l}switch(a){case 8:case 9:n.effects[0].parameter_p[0]=t.MusicalProgressions.majorScale;break;case 10:case 11:n.effects[0].parameter_p[0]=t.MusicalProgressions.minorScale;break;case 12:case 13:n.effects[0].parameter_p[0]=t.MusicalProgressions.diminished;break;case 14:case 15:n.effects[0].parameter_p[0]=t.MusicalProgressions.chromatic;break;case 16:case 17:n.effects[0].parameter_p[0]=t.MusicalProgressions.wholeTone}let g=p(0,i,1023)/1023,b=p(0,u,1023)/1023;n.volume=1*g,n.effects[1].effect=t.SoundSynthesizerEffects.volumeRampEffect,n.effects[1].steps=36,n.effects[1].parameter[0]=1*b;let v=Math.round(n.duration/1e4*m);switch(h){case 1:n.effects[2].steps=v,n.effects[2].effect=t.SoundSynthesizerEffects.frequencyVibratoEffect,n.effects[2].parameter[0]=d;break;case 2:n.effects[2].steps=v,n.effects[2].effect=t.SoundSynthesizerEffects.volumeVibratoEffect,n.effects[2].parameter[0]=d;break;case 3:n.effects[2].steps=v,n.effects[2].effect=t.SoundSynthesizerEffects.warbleInterpolation,n.effects[2].parameter[0]=d}return!0}function p(e,t,n){return Math.min(n,Math.max(e,t))}function f(e,t){if(e<0||t<0)return-1;const n=(s=2*t+1,Math.floor(Math.random()*s)-t);var s;return Math.abs(e+n)}function m(){const e={frequency:0,volume:1,duration:0,tone:{tonePrint:void 0,parameter:[0]},effects:[]};for(let n=0;n<t.EMOJI_SYNTHESIZER_TONE_EFFECTS;n++)e.effects.push({effect:void 0,step:0,steps:0,parameter:[],parameter_p:[]});return e}function g(e,t,n){return Math.min(Math.max(e,t),n)}t.isSoundExpPlaying=function(){return a},t.__playSoundExpression=function(t,n,s=.03){o||(o=[]);const i=e.getResume(),r=new Promise((e,r)=>{o.push({notes:t,volume:s,onStarted:()=>{n||i()},onFinished:e,onCancelled:e})});a||u(),n&&r.then(i)},t.clearSoundQueue=c,t.playSoundExpressionAsync=h,t.__stopSoundExpressions=function(){c(),e.AudioContextManager.stopAll()},t.parseSoundExpression=d}(t.music||(t.music={}))}(e.codal||(e.codal={}))}(pxsim||(pxsim={})),function(e){!function(e){let t;!function(e){e[e.Linear=0]="Linear",e[e.Inverse=1]="Inverse",e[e.Exponential=2]="Exponential"}(t=e.DistanceModelValue||(e.DistanceModelValue={}));class n{constructor(e,t){this.context=e,this.id=n.nextId++,n.allPlayers.push(this),this.panner=new PannerNode(e,{panningModel:"HRTF",distanceModel:"linear",positionX:0,positionY:0,positionZ:0,orientationX:0,orientationY:0,orientationZ:-1}),this.panner.connect(t)}static disposeAll(){for(;n.allPlayers.length;)n.allPlayers[0].dispose()}static getPlayerById(e){for(const t of n.allPlayers)if(t.id===e)return t}setPosition(e,t,n){this.panner.positionX.setTargetAtTime(e,0,.02),this.panner.positionY.setTargetAtTime(t,0,.02),this.panner.positionZ.setTargetAtTime(n,0,.02)}setOrientation(e,t,n){this.panner.orientationX.setTargetAtTime(e,0,.02),this.panner.orientationY.setTargetAtTime(t,0,.02),this.panner.orientationZ.setTargetAtTime(n,0,.02)}setCone(e,t,n){this.panner.coneInnerAngle=e,this.panner.coneOuterAngle=t,this.panner.coneOuterGain=n}setRollOff(e,t,n){this.panner.refDistance=e,this.panner.maxDistance=t,this.panner.rolloffFactor=n}setDistanceModel(e){switch(e){case t.Linear:this.panner.distanceModel="linear";break;case t.Inverse:this.panner.distanceModel="inverse";break;case t.Exponential:this.panner.distanceModel="exponential"}}get x(){return this.panner.positionX.value}get y(){return this.panner.positionY.value}get z(){return this.panner.positionZ.value}dispose(){this.panner.disconnect(),this.panner=void 0,this.audioWorkletSource&&(this.audioWorkletSource.dispose(),this.audioWorkletSource=void 0);const e=n.allPlayers.indexOf(this);e>=0&&n.allPlayers.splice(e,1)}async playInstructionsAsync(t){await e.AudioWorkletSource.initializeWorklet(this.context),this.audioWorkletSource&&!this.audioWorkletSource.isDisposed()||(this.audioWorkletSource=new e.AudioWorkletSource(this.context,this.panner,!0)),await this.audioWorkletSource.playInstructionsAsync(t)}}n.nextId=1,n.allPlayers=[],e.SpatialAudioPlayer=n}(e.AudioContextManager||(e.AudioContextManager={}))}(pxsim||(pxsim={})),function(e){e.getWorkletUri=function(){const e=new Blob(['\n const SW_TRIANGLE = 1;\n const SW_SAWTOOTH = 2;\n const SW_SINE = 3;\n const SW_TUNEDNOISE = 4;\n const SW_NOISE = 5;\n const SW_SQUARE_10 = 11;\n const SW_SQUARE_50 = 15;\n const SW_SQUARE_CYCLE_16 = 16;\n const SW_SQUARE_CYCLE_32 = 17;\n const SW_SQUARE_CYCLE_64 = 18;\n const OUTPUT_BITS = 14;\n\n function instrSoundWave(instructions, index) {\n return instructions[index];\n }\n\n function instrFrequency(instructions, index) {\n return Math.min(20000, Math.max(20, readInt16(instructions, index + 2)));\n }\n\n function instrDuration(instructions, index) {\n return Math.min(60000, Math.max(1, readInt16(instructions, index + 4)));\n }\n\n function instrStartVolume(instructions, index) {\n return Math.min(1023, Math.max(0, readInt16(instructions, index + 6)));\n }\n\n function instrEndVolume(instructions, index) {\n return Math.min(1023, Math.max(0, readInt16(instructions, index + 8)));\n }\n\n function instrEndFrequency(instructions, index) {\n return Math.min(20000, Math.max(20, readInt16(instructions, index + 10)));\n }\n\n function readInt16(instructions, index) {\n return instructions[index] | (instructions[index + 1] << 8);\n }\n\n let x = 0xf01ba80;\n function noiseTone(sound, position, cycle) {\n x ^= x << 13;\n x ^= x >> 17;\n x ^= x << 5;\n return (x & 0xffff) - 0x7fff;\n }\n\n function sineTone(sound, position, cycle) {\n let p = position;\n if (p >= 512) {\n p -= 512;\n }\n if (p > 256) {\n p = 512 - p;\n }\n // Approximate sin(x * pi / 2) with the odd polynomial y = cx^5 + bx^3 + ax\n // using the constraint y(1) = 1 => a = 1 - b - c\n // => y = c x^5 + b x^3 + (1 - b - c) * x\n //\n // Do a least-squares fit of this to sin(x * pi / 2) in the range 0..1\n // inclusive, using 21 evenly spaced points. Resulting approximation:\n //\n // sin(x*pi/2) ~= 0.0721435357258*x**5 - 0.642443736562*x**3 + 1.57030020084*x\n // Scale the constants by 32767 to match the desired output range.\n const c = 0.0721435357258 * 32767;\n const b = -0.642443736562 * 32767;\n const a = 1.57030020084 * 32767;\n // Calculate using y = ((c * x^2 + b) * x^2 + a) * x\n //\n // The position p is x * 256, so after each multiply with p we need to\n // shift right by 8 bits to keep the decimal point in the same place. (The\n // approximation has a negative error near x=1 which helps avoid overflow.)\n const p2 = p * p;\n const u = (c * p2 >> 16) + b;\n const v = (u * p2 >> 16) + a;\n const w = v * p >> 8;\n // The result is within 7/32767 or 0.02%, signal-to-error ratio about 38 dB.\n return position >= 512 ? -w : w;\n }\n\n function sawtoothTone(sound, position, cycle) {\n return (position << 6) - 0x7fff;\n }\n\n function triangleTone(sound, position, cycle) {\n return position < 512 ? (position << 7) - 0x7fff : ((1023 - position) << 7) - 0x7fff;\n }\n\n function squareWaveTone(sound, position, cycle) {\n const wave = instrSoundWave(sound.instructions, sound.currInstr);\n return position < (102 * (wave - SW_SQUARE_10 + 1)) ? -0x7fff : 0x7fff;\n }\n\n let tunedSeed = 0xf01ba80;\n function tunedNoiseTone(sound, position, cycle) {\n // Generate a square wave filtered by a random bit sequence. Since the generator\n // is called multiple times per wave, use PlayingSound state data to ensure we\n // only generate a random bit once per wave, and then reuse it for future\n // calls for that wave.\n //\n // Use the low 6 bits of generatorState to store the last-used cycle, and\n // random_bit to store the last on/off state. (random_bit is arbitrary as\n // long as it isn\'t one of the low 6 bits.)\n const random_bit = 0x8000;\n const prev_cycle = sound.generatorState & 0x3f;\n let is_on;\n if (cycle == prev_cycle) {\n is_on = sound.generatorState & random_bit;\n }\n else {\n // see https://en.wikipedia.org/wiki/Xorshift\n tunedSeed ^= tunedSeed << 13;\n tunedSeed ^= tunedSeed >> 17;\n tunedSeed ^= tunedSeed << 5;\n is_on = (tunedSeed & random_bit);\n sound.generatorState = (cycle & 0x3f) | is_on;\n }\n if (!is_on)\n return 0;\n return position < 512 ? -0x7fff : 0x7fff;\n }\n\n // Bit patterns for use by the cyclic noise tone.\n //\n // The bit pattern is arbitrary, but should have equal numbers of 0 and 1 bits,\n // and should avoid long identical-bit runs for the lower parts. The values below\n // were chosen based on a random permutation of the hex nibbles 0..f and then\n // hand-tweaked by swapping some nibbles. Generated by:\n //\n // shuf -i 0-15 | perl -ne \'s/(d+)/printf("%x",$1)/e\'\n const cycle_bits = [0x2df0eb47, 0xc8165a93];\n const cycle_mask = [0xf, 0x1f, 0x3f];\n\n function cycleNoiseTone(sound, position, cycle) {\n // Generate a square wave filtered by a short-cycle pseudorandom bit sequence.\n // The bit sequence repeats every 16/32/64 waves.\n //\n // The "cycle" argument corresponds to the sequential number of the generated\n // wave. This is currently a 6-bit value. Since the pseudorandom bit sequences\n // evenly fit into this, there\'s no need to track generator state.\n const wave = instrSoundWave(sound.instructions, sound.currInstr);\n const cycle_index = wave - SW_SQUARE_CYCLE_16;\n // CLAMP(0, cycle_index, sizeof cycle_bits / sizeof cycle_bits[0])\n cycle &= cycle_mask[cycle_index];\n const is_on = (cycle_bits[cycle >> 5] & (1 << (cycle & 0x1f)));\n if (!is_on)\n return 0;\n return position < 512 ? -0x7fff : 0x7fff;\n }\n\n function silenceTone(sound, position, cycle) {\n return 0;\n }\n\n function getWaveFn(wave) {\n switch (wave) {\n case SW_TRIANGLE:\n return triangleTone;\n case SW_SAWTOOTH:\n return sawtoothTone;\n case SW_TUNEDNOISE:\n return tunedNoiseTone;\n case SW_NOISE:\n return noiseTone;\n case SW_SINE:\n return sineTone;\n default:\n if (SW_SQUARE_10 <= wave && wave <= SW_SQUARE_50)\n return squareWaveTone;\n if (SW_SQUARE_CYCLE_16 <= wave && wave <= SW_SQUARE_CYCLE_64)\n return cycleNoiseTone;\n else\n return silenceTone;\n }\n }\n\n function fillSamples(dst, numsamples, sounds, sampleRate) {\n const samplesPerMS = (sampleRate << 8) / 1000;\n const toneStepMult = (1024.0 * (1 << 16)) / sampleRate;\n let fn;\n\n for (const snd of sounds) {\n let toneStep = 0;\n let toneDelta = 0;\n let volumeStep = 0;\n let tonePosition = snd.tonePosition;\n let samplesLeft = 0;\n let wave = 0;\n let volume = 0;\n\n snd.currInstr -= 12;\n\n for (let j = 0; j < numsamples; ++j) {\n if (samplesLeft == 0) {\n snd.currInstr += 12;\n if (snd.currInstr >= snd.instructions.length) {\n break;\n }\n // SoundInstruction copy = *snd.currInstr;\n // instr = &copy;\n\n wave = instrSoundWave(snd.instructions, snd.currInstr);\n fn = getWaveFn(wave);\n samplesLeft = (instrDuration(snd.instructions, snd.currInstr) * samplesPerMS >> 8);\n // make sure the division is signed\n volumeStep = Math.floor(((instrEndVolume(snd.instructions, snd.currInstr) - instrStartVolume(snd.instructions, snd.currInstr)) << 16) / samplesLeft);\n if (j == 0 && snd.prevVolume != -1) {\n // restore previous state\n samplesLeft = snd.samplesLeftInCurr;\n volume = snd.prevVolume;\n toneStep = snd.prevToneStep;\n toneDelta = snd.prevToneDelta;\n }\n else {\n // LOG("#sampl %d %p", samplesLeft, snd.currInstr);\n volume = instrStartVolume(snd.instructions, snd.currInstr) << 16;\n // LOG("%d-%dHz %d-%d vol", instr.frequency, instr.endFrequency,\n // instr.startVolume, instr.endVolume);\n toneStep = Math.floor(toneStepMult * instrFrequency(snd.instructions, snd.currInstr));\n if (instrFrequency(snd.instructions, snd.currInstr) != instrEndFrequency(snd.instructions, snd.currInstr)) {\n const endToneStep = (toneStepMult * instrEndFrequency(snd.instructions, snd.currInstr)) | 0;\n toneDelta = ((endToneStep - toneStep) / samplesLeft) | 0;\n }\n else {\n toneDelta = 0;\n }\n }\n }\n let v = fn(snd, (tonePosition >> 16) & 1023, (tonePosition >> 26) & 0xff);\n v = (v * (volume >> 16)) >> (10 + (16 - OUTPUT_BITS));\n // if (v > MAXVAL)\n // target_panic(123);\n for (const output of dst) {\n for (const channel of output) {\n channel[j] = channel[j] + (v / 0xffff);\n }\n }\n // console.log("v", v);\n tonePosition += toneStep;\n toneStep += toneDelta;\n volume += volumeStep;\n samplesLeft--;\n }\n\n if (snd.currInstr >= snd.instructions.length) {\n // snd.sound.state = SoundState::Done;\n // snd.sound = NULL;\n }\n else {\n snd.tonePosition = tonePosition;\n if (samplesLeft == 0)\n samplesLeft++; // avoid infinite loop in next iteration\n snd.samplesLeftInCurr = samplesLeft;\n snd.prevVolume = volume;\n snd.prevToneDelta = toneDelta;\n snd.prevToneStep = toneStep;\n }\n }\n }\n\n class MixerAudioWorkletProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.sounds = [];\n this.port.onmessage = event => {\n if (event.data.type === "play") {\n this.sounds.push({\n startSampleNo: 0,\n samplesLeftInCurr: 0,\n tonePosition: 0,\n prevVolume: -1,\n prevToneStep: 0,\n prevToneDelta: 0,\n generatorState: 0,\n instructions: event.data.instructions,\n currInstr: 0,\n id: event.data.id\n });\n }\n else if (event.data.type === "cancel") {\n this.sounds = this.sounds.filter(s => s.id !== event.data.id);\n }\n };\n }\n\n process(inputs, outputs, parameters) {\n if (this.sounds.length) {\n fillSamples(outputs, outputs[0][0].length, this.sounds, sampleRate);\n\n for (const sound of this.sounds) {\n if (sound.currInstr >= sound.instructions.length) {\n this.port.postMessage({ type: "done", id: sound.id });\n }\n }\n this.sounds = this.sounds.filter(s => s.currInstr < s.instructions.length);\n }\n return true;\n }\n }\n registerProcessor("pxt-mixer-audio-worklet-processor", MixerAudioWorkletProcessor);\n '],{type:"text/javascript"});return URL.createObjectURL(e)}}(pxsim||(pxsim={})),function(e){class t{constructor(e){this.id=e}}e.Button=t;e.ButtonPairState=class{constructor(e){this.props=e,this.usesButtonAB=!1,this.aBtn=new t(this.props.ID_BUTTON_A),this.bBtn=new t(this.props.ID_BUTTON_B),this.abBtn=new t(this.props.ID_BUTTON_AB),this.abBtn.virtual=!0}}}(pxsim||(pxsim={})),function(e){e.CompassState=class{constructor(){this.usesHeading=!1,this.heading=90}}}(pxsim||(pxsim={})),function(e){e.FileSystemState=class{constructor(){this.files={}}append(e,t){this.files[e]=(this.files[e]||"")+t}remove(e){delete this.files[e]}}}(pxsim||(pxsim={})),function(e){e.LightSensorState=class{constructor(){this.usesLightLevel=!1,this.lightLevel=128}}}(pxsim||(pxsim={})),function(e){!function(t){t.mkBoardView=e=>{const n=e.visual;return new t.GenericBoardSvg({visualDef:n,boardDef:e.boardDef,wireframe:e.wireframe})};t.BoardHost=class{constructor(n,s){this.parts=[],this.boardView=n,this.opts=s,s.boardDef.pinStyles||(s.boardDef.pinStyles={}),this.state=s.state;let i=s.partsList,r=0<i.length||s.forceBreadboardLayout;if(r){this.breadboard=new t.Breadboard({wireframe:s.wireframe});const n=s.boardDef.marginWhenBreadboarding||[0,0,40,0],o=t.composeSVG({el1:this.boardView.getView(),scaleUnit1:this.boardView.getPinDist(),el2:this.breadboard.getSVGAndSize(),scaleUnit2:this.breadboard.getPinDist(),margin:[n[0],n[1],20,n[3]],middleMargin:n[2],maxWidth:s.maxWidth,maxHeight:s.maxHeight}),a=o.under,l=o.over;this.view=o.host;const u=o.edges;this.fromMBCoord=o.toHostCoord1,this.fromBBCoord=o.toHostCoord2,this.partGroup=l,this.partOverGroup=e.svg.child(this.view,"g"),this.style=e.svg.child(this.view,"style",{}),this.defs=e.svg.child(this.view,"defs",{}),this.wireFactory=new t.WireFactory(a,l,u,this.style,this.getLocCoord.bind(this),this.getPinStyle.bind(this));const c=e.allocateDefinitions({boardDef:s.boardDef,partDefs:s.partDefs,fnArgs:s.fnArgs,getBBCoord:this.breadboard.getCoord.bind(this.breadboard),partsList:i});c.partsAndWires.length||s.forceBreadboardLayout?(this.addAll(c),c.requiresBreadboard||s.forceBreadboardRender?c.hideBreadboard&&this.breadboard&&this.breadboard.hide():r=!1):r=!1}if(!r){delete this.breadboard,delete this.wireFactory,delete this.partOverGroup,delete this.partGroup,delete this.style,delete this.defs,delete this.fromBBCoord,delete this.fromMBCoord;const t=this.boardView.getView().el;this.view=t,this.partGroup=e.svg.child(this.view,"g"),this.partOverGroup=e.svg.child(this.view,"g"),s.maxWidth&&e.svg.hydrate(this.view,{width:s.maxWidth}),s.maxHeight&&e.svg.hydrate(this.view,{height:s.maxHeight})}this.state.updateSubscribers.push(()=>this.updateState())}highlightBoardPin(e){this.boardView.highlightPin(e)}removeEventListeners(){this.boardView.removeEventListeners&&this.boardView.removeEventListeners()}highlightBreadboardPin(e){this.breadboard.highlightLoc(e)}highlightWire(t){t.wires.forEach(t=>{e.U.addClass(t,"highlight"),t.style.visibility="visible"}),e.U.addClass(t.endG,"highlight")}getView(){return this.view}screenshotAsync(t){const n=this.view.classList.contains("sim")?this.view:this.view.querySelector(".sim"),s=n?n.cloneNode(!0):this.view.cloneNode(!0);s.setAttribute("width",s.viewBox.baseVal.width+""),s.setAttribute("height",s.viewBox.baseVal.height+"");const i=(new XMLSerializer).serializeToString(s),r="data:image/svg+xml,"+encodeURIComponent(i.replace(/\s+/g," ").replace(/"/g,"'"));return new Promise((n,s)=>{const i=document.createElement("img");i.onload=()=>{const e=document.createElement("canvas");e.width=i.width,e.height=i.height,t>0?(e.width=t,e.height=i.height*t/i.width|0):e.width<200?(e.width*=2,e.height*=2):e.width>480&&(e.width/=2,e.height/=2);const s=e.getContext("2d");s.drawImage(i,0,0,e.width,e.height),n(s.getImageData(0,0,e.width,e.height))},i.onerror=t=>{e.log(t),n(void 0)},i.src=r})}updateState(){this.parts.forEach(e=>e.updateState())}getBBCoord(e){let t=this.breadboard.getCoord(e);return this.fromBBCoord(t)}getPinCoord(t){let n=this.boardView.getCoord(t);if(n)return this.fromMBCoord(n);e.error(`Unable to find coord for pin: ${t}`)}getLocCoord(t){let n;if("breadboard"===t.type){let e=t;n=this.getBBCoord(e)}else{let e=t.pin;n=this.getPinCoord(e)}return n||e.debug("Unknown location: "+name),n}getPinStyle(e){return"breadboard"==e.type?"female":this.opts.boardDef.pinStyles[e.pin]||"female"}addPart(n){let s=null;if(n.simulationBehavior){let e=n.simulationBehavior,t=this.state.builtinVisuals[e],i=this.state.builtinParts[e];s=t(),s.init(this.state.bus,i,this.view,n.params)}else{let e=n.visual;s=new t.GenericPart(e)}this.parts.push(s),this.partGroup.appendChild(s.element),s.overElement&&this.partOverGroup.appendChild(s.overElement),s.defs&&s.defs.forEach(e=>this.defs.appendChild(e)),this.style.textContent+=s.style||"";let i=n.startColumnIdx,r=n.startRowIdx,o={type:"breadboard",row:t.getRowName(r),col:t.getColumnName(i),xOffset:n.bbFit.xOffset/n.visual.pinDistance,yOffset:n.bbFit.yOffset/n.visual.pinDistance},a=this.getBBCoord(o);s.moveToCoord(a);let l=`sim-${n.name}-cmp`;return e.U.addClass(s.element,l),e.U.addClass(s.element,"sim-cmp"),s.updateTheme(),s.updateState(),s}addWire(e){return this.wireFactory.addWire(e.start,e.end,e.color)}addAll(e){e.partsAndWires.forEach(t=>{const n=t.wires,s=n&&n.every(e=>this.wireFactory.checkWire(e.start,e.end));s&&n.forEach(t=>e.wires.push(this.addWire(t)));let i=t.part;!i||n&&!s||e.parts.push(this.addPart(i))}),e.requiresBreadboard=!!e.wires.length||!!e.parts.length}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){!function(t){const n=15,s="#1AA5D7",i="#DD4BA0",r=`\n /* bread board */\n .sim-bb-background {\n fill:#E0E0E0;\n }\n .sim-bb-pin {\n fill:#999;\n }\n .sim-bb-pin-hover {\n visibility: hidden;\n pointer-events: all;\n stroke-width: 7.5px;\n stroke: transparent;\n fill: #777;\n }\n .sim-bb-pin-hover:hover {\n visibility: visible;\n fill:#444;\n }\n .sim-bb-group-wire {\n stroke: #999;\n stroke-width: 3.75px;\n visibility: hidden;\n }\n .sim-bb-pin-group {\n pointer-events: all;\n }\n .sim-bb-label,\n .sim-bb-label-hover {\n font-family:"Lucida Console", Monaco, monospace;\n fill:#555;\n pointer-events: all;\n stroke-width: 0;\n cursor: default;\n }\n .sim-bb-label-hover {\n visibility: hidden;\n fill:#000;\n font-weight: bold;\n }\n .sim-bb-bar {\n stroke-width: 0;\n }\n .sim-bb-blue {\n fill:${s};\n stroke:${s}\n }\n .sim-bb-red {\n fill:${i};\n stroke:${i};\n }\n .sim-bb-pin-group:hover .sim-bb-pin-hover,\n .sim-bb-pin-group:hover .sim-bb-group-wire,\n .sim-bb-pin-group:hover .sim-bb-label-hover {\n visibility: visible;\n }\n .sim-bb-pin-group:hover .sim-bb-label {\n visibility: hidden;\n }\n /* outline mode */\n .sim-bb-outline .sim-bb-background {\n stroke-width: ${n/7}px;\n fill: #FFF;\n stroke: #000;\n }\n .sim-bb-outline .sim-bb-mid-channel {\n fill: #FFF;\n stroke: #888;\n stroke-width: 2px;\n }\n /* grayed out */\n .grayed .sim-bb-background {\n stroke-width: 3px;\n }\n .grayed .sim-bb-red,\n .grayed .sim-bb-blue {\n fill: #BBB;\n }\n .grayed .sim-bb-bar {\n fill: #FFF;\n }\n .grayed .sim-bb-pin {\n fill: #000;\n stroke: #FFF;\n stroke-width: 3px;\n }\n .grayed .sim-bb-label {\n fill: none;\n }\n .grayed .sim-bb-background {\n stroke-width: 7.5px;\n stroke: #555;\n }\n .grayed .sim-bb-group-wire {\n stroke: #DDD;\n }\n .grayed .sim-bb-channel {\n visibility: hidden;\n }\n /* highlighted */\n .sim-bb-label.highlight {\n visibility: hidden;\n }\n .sim-bb-label-hover.highlight {\n visibility: visible;\n }\n .sim-bb-blue.highlight {\n fill:${s};\n }\n .sim-bb-red.highlight {\n fill:${i};\n }\n .sim-bb-bar.highlight {\n stroke-width: 0px;\n }\n `;t.BREADBOARD_MID_ROWS=10,t.BREADBOARD_MID_COLS=30;const o=[4,4],a=t.BREADBOARD_MID_ROWS+o.length,l=25,u=[4,9,14,19],c=l+u.length,h=n*(t.BREADBOARD_MID_COLS+3),d=n*(a+4+5.5),p=2/3,f=d*p,m=d*(.5*(1-p)),g=(t.BREADBOARD_MID_COLS-1)*n,b=(h-g)/2,v=m+(f-(a-1)*n)/2,y=(c-1)*n,S=(h-y)/2,w=(m-15)/2,x=S,E=w+m+f,I=25.5,k=12,C=1.05,R=-90,T="abcdefghij".split("").reverse();function _(e){return`${e+1}`}function A(e){return T[e]}function P(t){let n=t.xOffset||0,s=t.yOffset||0,i=[],r=e.svg.elt("g"),o=t.colStartIdx||0,a=t.rowStartIdx||0,l=e=>e?e.slice(0,e.length):[],u=(e,t)=>{let n,s=0;for(;0<=(n=e.indexOf(t));)e.splice(n,1),s+=1;return s},c=0,h=l(t.rowIdxsWithGap);for(let d=0;d<t.rowCount;d++){let p=0,f=l(t.colIdxsWithGap),m=s+d*t.pinDist+c*t.pinDist,g=d+a;for(let s=0;s<t.colCount;s++){let a=n+s*t.pinDist+p*t.pinDist,l=s+o;const c=t=>(e.svg.hydrate(t.el,"circle"==t.el.tagName?{cx:a,cy:m}:{x:a-.5*t.w,y:m-.5*t.h}),r.appendChild(t.el),t.el);let h=c(t.mkPin()),d=c(t.mkHoverPin()),b=t.getRowName(g),v=t.getColName(l),y=t.getGroupName?t.getGroupName(g,l):null,S={el:h,hoverEl:d,cx:a,cy:m,row:b,col:v,group:y};i.push(S),p+=u(f,l)}c+=u(h,g)}return{g:r,allPins:i}}function M(){let t=e.svg.elt("rect");return e.svg.hydrate(t,{class:"sim-bb-pin",rx:2,ry:2,width:6,height:6}),{el:t,w:6,h:6,x:0,y:0}}function D(){let t=e.svg.elt("rect"),n=6*1.3;return e.svg.hydrate(t,{class:"sim-bb-pin-hover",rx:2,ry:2,width:n,height:n}),{el:t,w:n,h:n,x:0,y:0}}function B(n,s,i,r,o,a,l){let u=t.mkTxt(n,s,i,r,o);e.U.addClass(u,"sim-bb-label"),l&&l.forEach(t=>e.U.addClass(u,t));let c=t.mkTxt(n,s,1.3*i,r,o);return e.U.addClass(c,"sim-bb-label-hover"),l&&l.forEach(t=>e.U.addClass(c,t)),{el:u,hoverEl:c,txt:o,group:a}}t.getColumnName=_,t.getRowName=A,t.mkGrid=P;t.Breadboard=class{constructor(t){this.allPins=[],this.allLabels=[],this.allPowerBars=[],this.rowColToPin={},this.rowColToLbls={},this.buildDom(),t.wireframe&&e.U.addClass(this.bb,"sim-bb-outline")}hide(){this.bb.style.display="none"}updateLocation(t,n){e.svg.hydrate(this.bb,{x:`${t}px`,y:`${n}px`})}getPin(e,t){let n=this.rowColToPin[e];if(!n)return null;let s=n[t];return s||null}getCoord(e){let{row:t,col:s,xOffset:i,yOffset:r}=e,o=this.getPin(t,s);if(!o)return null;let a=(i||0)*n,l=(r||0)*n;return[o.cx+a,o.cy+l]}getPinDist(){return n}buildDom(){this.bb=e.svg.elt("svg",{version:"1.0",viewBox:`0 0 ${h} ${d}`,class:"sim-bb",width:h+"px",height:d+"px"}),this.styleEl=e.svg.child(this.bb,"style",{}),this.styleEl.textContent+=r,this.defs=e.svg.child(this.bb,"defs",{}),e.svg.child(this.bb,"rect",{class:"sim-bb-background",width:h,height:d,rx:4.5,ry:4.5});let s="sim-bb-channel-grad",i=e.svg.elt("linearGradient");e.svg.hydrate(i,{id:s,x1:"0%",y1:"0%",x2:"0%",y2:"100%"}),this.defs.appendChild(i);let a="#AAA",c="#CCC";e.svg.child(i,"stop",{offset:"0%",style:`stop-color: ${a};`}),e.svg.child(i,"stop",{offset:"20%",style:`stop-color: ${c};`}),e.svg.child(i,"stop",{offset:"80%",style:`stop-color: ${c};`}),e.svg.child(i,"stop",{offset:"100%",style:`stop-color: ${a};`});const p=(t,n,i)=>{let r=e.svg.child(this.bb,"rect",{class:`sim-bb-channel ${i||""}`,y:t-n/2,width:h,height:n});return r.setAttribute("fill",`url(#${s})`),r};p(m+f/2,15,"sim-bb-mid-channel"),p(m,.75,"sim-bb-sml-channel"),p(m+f,.75,"sim-bb-sml-channel");const g=(e,n)=>{let s=(e=>e<t.BREADBOARD_MID_ROWS/2?"b":"t")(e);return`${s}${_(n)}`},T=e=>0===e?"-":"+",L=(e,t)=>{let n=(e=>e<25?"b":"t")(t);return`${T(e)}${n}`};let F=P({xOffset:b,yOffset:v,rowCount:t.BREADBOARD_MID_ROWS,colCount:t.BREADBOARD_MID_COLS,pinDist:n,mkPin:M,mkHoverPin:D,getRowName:A,getColName:_,getGroupName:g,rowIdxsWithGap:o});F.g;this.allPins=this.allPins.concat(F.allPins);let O=P({xOffset:x,yOffset:E,rowCount:2,colCount:l,pinDist:n,mkPin:M,mkHoverPin:D,getRowName:T,getColName:_,getGroupName:L,colIdxsWithGap:u});O.g;this.allPins=this.allPins.concat(O.allPins);let U=P({xOffset:S,yOffset:w,rowCount:2,colCount:l,colStartIdx:l,pinDist:n,mkPin:M,mkHoverPin:D,getRowName:T,getColName:_,getGroupName:L,colIdxsWithGap:u.map(e=>e+l)});U.g;this.allPins=this.allPins.concat(U.allPins),this.allPins.forEach(t=>{let{el:n,row:s,col:i,hoverEl:r}=t,o=`(${s},${i})`;e.svg.hydrate(n,{title:o}),e.svg.hydrate(r,{title:o})}),this.allPins.forEach(e=>{let t=this.rowColToPin[e.row];t||(t=this.rowColToPin[e.row]={}),t[e.col]=e});const V=(e,t,n,s,i,r)=>{let o=this.getCoord({type:"breadboard",row:e,col:t}),[a,l]=o;return B(a+n,l+s,10.5,-90,i,r)};for(let e=0;e<t.BREADBOARD_MID_COLS;e++){let n=_(e),s=0,i=V(A(s),n,0,-15,n,g(s,e));this.allLabels.push(i);let r=t.BREADBOARD_MID_ROWS-1,o=V(A(r),n,0,15,n,g(r,e));this.allLabels.push(o)}for(let e=0;e<t.BREADBOARD_MID_ROWS;e++){let n=A(e),s=V(n,_(0),-15,0,n);this.allLabels.push(s);let i=V(n,_(t.BREADBOARD_MID_COLS-1),15,0,n);this.allLabels.push(i)}let N=[B(13.05,m+f+k,30,R,"-",L(0,0),["sim-bb-blue"]),B(12,m+f+m-k,I,R,"+",L(1,0),["sim-bb-red"]),B(h-k+C,m+f+k,30,R,"-",L(0,24),["sim-bb-blue"]),B(h-k,m+f+m-k,I,R,"+",L(1,24),["sim-bb-red"])];this.allLabels=this.allLabels.concat(N);let q=[B(13.05,12,30,R,"-",L(0,l),["sim-bb-blue"]),B(12,m-k,I,R,"+",L(1,l),["sim-bb-red"]),B(h-k+C,12,30,R,"-",L(0,49),["sim-bb-blue"]),B(h-k,m-k,I,R,"+",L(1,49),["sim-bb-red"])];this.allLabels=this.allLabels.concat(q);let W={};this.allLabels.forEach(e=>{let{el:t,txt:n}=e;(W[n]=W[n]||[]).push(e)});this.allPins.forEach(e=>{let{row:t,col:n,group:s}=e,i=this.rowColToLbls[t]||(this.rowColToLbls[t]={}),r=i[n]||(i[n]=[]);if((e=>"-"===e.row||"+"===e.row)(e)){Number(n)<=l?N.filter(t=>t.group==e.group).forEach(e=>r.push(e)):q.filter(t=>t.group==e.group).forEach(e=>r.push(e))}else{W[t].forEach(e=>r.push(e)),W[n].forEach(e=>r.push(e))}});const $=y+22.5,G=($-y)/2,j=(t,n,s,i)=>{let r=e.svg.elt("rect");return e.svg.hydrate(r,{class:`sim-bb-bar ${i}`,x:t,y:n-1.5,width:$,height:3}),{el:r,group:s}};let z=[j(x-G,E-9,L(0,49),"sim-bb-blue"),j(x-G,E+n+9,L(1,49),"sim-bb-red"),j(S-G,w-9,L(0,0),"sim-bb-blue"),j(S-G,w+n+9,L(1,0),"sim-bb-red")];this.allPowerBars=this.allPowerBars.concat(z),this.allPowerBars.forEach(e=>this.bb.appendChild(e.el));let H=this.allPins.map(e=>e.group).filter((e,t,n)=>n.indexOf(e)==t),Y=H.map(t=>e.svg.elt("g"));Y.forEach(t=>e.U.addClass(t,"sim-bb-pin-group")),Y.forEach((t,n)=>e.U.addClass(t,`group-${H[n]}`));let J={};H.forEach((e,t)=>J[e]=Y[t]);let Z={};this.allPins.forEach((e,t)=>{let n=e.group;(Z[n]||(Z[n]=[])).push(e)}),H.forEach(t=>{let n=Z[t],[s,i]=[n.map(e=>e.cx),n.map(e=>e.cy)],r=e=>e.reduce((e,t)=>e<t?e:t),o=e=>e.reduce((e,t)=>e>t?e:t),[a,l,u,c]=[r(s),o(s),r(i),o(i)],h=e.svg.elt("rect"),d=Math.max(l-a,1e-4),p=Math.max(c-u,1e-4);e.svg.hydrate(h,{x:a,y:u,width:d,height:p}),e.U.addClass(h,"sim-bb-group-wire"),J[t].appendChild(h)}),this.allPins.forEach(e=>{let t=J[e.group];t.appendChild(e.el),t.appendChild(e.hoverEl)});let Q=e.svg.elt("g");e.svg.hydrate(Q,{class:"sim-bb-group-misc"}),Y.push(Q),this.allLabels.forEach(e=>{if(e.group){let t=J[e.group];t.appendChild(e.el),t.appendChild(e.hoverEl)}else Q.appendChild(e.el),Q.appendChild(e.hoverEl)}),Y.forEach(e=>this.bb.appendChild(e))}getSVGAndSize(){return{el:this.bb,y:0,x:0,w:h,h:d}}highlightLoc(t){let{row:n,col:s}=t,i=this.rowColToPin[n][s],{cx:r,cy:o}=i;this.rowColToLbls[n][s].forEach(t=>{e.U.addClass(t.el,"highlight"),e.U.addClass(t.hoverEl,"highlight")})}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){!function(t){t.BOARD_SYTLE=`\n .noselect {\n -webkit-touch-callout: none; /* iOS Safari */\n -webkit-user-select: none; /* Chrome/Safari/Opera */\n -khtml-user-select: none; /* Konqueror */\n -moz-user-select: none; /* Firefox */\n -ms-user-select: none; /* Internet Explorer/Microsoft Edge */\n user-select: none; /* Non-prefixed version, currently\n not supported by any browser */\n }\n\n .sim-board-pin {\n fill:#999;\n stroke:#000;\n stroke-width:${t.PIN_DIST/3}px;\n }\n .sim-board-pin-lbl {\n fill: #333;\n }\n .gray-cover {\n fill:#FFF;\n opacity: 0.3;\n stroke-width:0;\n visibility: hidden;\n }\n .sim-board-pin-hover {\n visibility: hidden;\n pointer-events: all;\n stroke-width:${t.PIN_DIST/6}px;\n }\n .sim-board-pin-hover:hover {\n visibility: visible;\n }\n .sim-board-pin-lbl {\n visibility: hidden;\n }\n .sim-board-outline .sim-board-pin-lbl {\n visibility: visible;\n }\n .sim-board-pin-lbl {\n fill: #555;\n }\n .sim-board-pin-lbl-hover {\n fill: red;\n }\n .sim-board-outline .sim-board-pin-lbl-hover {\n fill: black;\n }\n .sim-board-pin-lbl,\n .sim-board-pin-lbl-hover {\n font-family:"Lucida Console", Monaco, monospace;\n pointer-events: all;\n stroke-width: 0;\n }\n .sim-board-pin-lbl-hover {\n visibility: hidden;\n }\n .sim-board-outline .sim-board-pin-hover:hover + .sim-board-pin-lbl,\n .sim-board-pin-lbl.highlight {\n visibility: hidden;\n }\n .sim-board-outline .sim-board-pin-hover:hover + * + .sim-board-pin-lbl-hover,\n .sim-board-pin-lbl-hover.highlight {\n visibility: visible;\n }\n /* Graying out */\n .grayed .sim-board-pin-lbl:not(.highlight) {\n fill: #AAA;\n }\n .grayed .sim-board-pin:not(.highlight) {\n fill:#BBB;\n stroke:#777;\n }\n .grayed .gray-cover {\n visibility: inherit;\n }\n .grayed .sim-cmp:not(.notgrayed) {\n opacity: 0.3;\n }\n /* Highlighting */\n .sim-board-pin-lbl.highlight {\n fill: #000;\n font-weight: bold;\n }\n .sim-board-pin.highlight {\n fill:#999;\n stroke:#000;\n }\n `;const n=.7*t.PIN_DIST,s=1.5*n,i=.66666*t.PIN_DIST,r=.66666*t.PIN_DIST+t.PIN_DIST/3;let o=0;t.GenericBoardSvg=class{constructor(a){this.props=a,this.allPins=[],this.allLabels=[],this.pinNmToLbl={},this.pinNmToPin={},this.id=o++;let l=a.visualDef,u=a.wireframe&&l.outlineImage?l.outlineImage:l.image,c=t.mkImageSVG({image:u,width:l.width,height:l.height,imageUnitDist:l.pinDist,targetUnitDist:t.PIN_DIST}),h=t.mkScaleFn(l.pinDist,t.PIN_DIST);this.width=c.w,this.height=c.h;let d=c.el;this.element=e.svg.elt("svg"),e.svg.hydrate(this.element,{version:"1.0",viewBox:`0 0 ${this.width} ${this.height}`,class:`sim sim-board-id-${this.id}`,x:"0px",y:"0px"}),a.wireframe&&e.U.addClass(this.element,"sim-board-outline"),this.style=e.svg.child(this.element,"style",{}),this.style.textContent+=t.BOARD_SYTLE,this.defs=e.svg.child(this.element,"defs",{}),this.g=e.svg.elt("g"),this.element.appendChild(this.g),this.g.appendChild(d),this.background=d,e.svg.hydrate(d,{class:"sim-board"});const p=()=>{let t=e.svg.elt("circle"),n=i;return e.svg.hydrate(t,{class:"sim-board-pin",r:n/2}),{el:t,w:n,h:n,x:0,y:0}},f=()=>{let t=e.svg.elt("circle"),n=r;return e.svg.hydrate(t,{class:"sim-board-pin-hover",r:n/2}),{el:t,w:n,h:n,x:0,y:0}},m=()=>{let t=e.svg.elt("rect"),n=i;return e.svg.hydrate(t,{class:"sim-board-pin",width:n,height:n}),{el:t,w:n,h:n,x:0,y:0}},g=()=>{let t=e.svg.elt("rect"),n=r;return e.svg.hydrate(t,{class:"sim-board-pin-hover",width:n,height:n}),{el:t,w:n,h:n,x:0,y:0}};let b=l.pinBlocks.map((n,s)=>{let i=h(n.x)+t.PIN_DIST/2,r=h(n.y)+t.PIN_DIST/2,o=n.labels.length,a=t.mkGrid({xOffset:i,yOffset:r,rowCount:1,colCount:o,pinDist:t.PIN_DIST,mkPin:l.useCrocClips?p:m,mkHoverPin:l.useCrocClips?f:g,getRowName:()=>`${s+1}`,getColName:e=>n.labels[e],getGroupName:()=>n.labels.join(" ")});a.allPins,a.g;return e.U.addClass(a.g,"sim-board-pin-group"),a}),v=[];b.forEach((e,t)=>e.allPins.forEach((e,n)=>{this.allPins.push(e),v.push(l.pinBlocks[t])})),this.allPins.forEach(t=>{let n=t.col;e.svg.hydrate(t.el,{title:n}),e.svg.hydrate(t.hoverEl,{title:n})}),this.allPins.forEach(e=>{this.pinNmToPin[e.col]=e});const y=(e,n,s,i,r)=>{let o,a;if("below"===r){a=e,o=n+12+.25*s*i.length}else{a=e,o=n-11-.32*s*i.length}return t.mkTxt(a,o,s,-90,i)};this.allLabels=this.allPins.map((t,i)=>{let r=v[i];return((t,i,r,o)=>{let a=y(t,i,n,r,o);e.U.addClass(a,"sim-board-pin-lbl");let l=y(t,i,s,r,o);return e.U.addClass(l,"sim-board-pin-lbl-hover"),{el:a,hoverEl:l,txt:r}})(t.cx,t.cy,t.col,r.labelPosition||"above")}),this.allPins.forEach((e,t)=>{let n=this.allLabels[t];this.pinNmToLbl[e.col]=n}),this.allPins.forEach((e,t)=>{let n=this.allLabels[t];this.g.appendChild(e.el),this.g.appendChild(e.hoverEl),this.g.appendChild(n.el),this.g.appendChild(n.hoverEl)})}findPin(e){let t=this.pinNmToPin[e];return!t&&this.props.boardDef.gpioPinMap&&(e=this.props.boardDef.gpioPinMap[e])&&(t=this.pinNmToPin[e]),t}findPinLabel(e){let t=this.pinNmToLbl[e];return!t&&this.props.boardDef.gpioPinMap&&(e=this.props.boardDef.gpioPinMap[e])&&(t=this.pinNmToLbl[e]),t}getCoord(e){let t=this.findPin(e);return t?[t.cx,t.cy]:null}mkGrayCover(t,n,s,i){let r=e.svg.elt("rect");return e.svg.hydrate(r,{x:t,y:n,width:s,height:i,class:"gray-cover"}),r}getView(){return{el:this.element,w:this.width,h:this.height,x:0,y:0}}getPinDist(){return t.PIN_DIST}highlightPin(t){let n=this.findPinLabel(t),s=this.findPin(t);n&&s&&(e.U.addClass(n.el,"highlight"),e.U.addClass(n.hoverEl,"highlight"),e.U.addClass(s.el,"highlight"),e.U.addClass(s.hoverEl,"highlight"))}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){!function(t){function n(e){return t.mkImageSVG({image:e.image,width:e.width,height:e.height,imageUnitDist:e.pinDistance,targetUnitDist:t.PIN_DIST})}t.mkGenericPartSVG=n;t.GenericPart=class{constructor(t){this.style="",this.defs=[];let s=n(t).el;this.element=e.svg.elt("g"),this.element.appendChild(s)}moveToCoord(e){t.translateEl(this.element,e)}init(e,t,n){}updateState(){}updateTheme(){}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={})),function(e){!function(t){const n=t.PIN_DIST/2.5,s=.7;function i(e){return e.replace(/\#/g,"-").replace(/\(/g,"-").replace(/\)/g,"-").replace(/\,/g,"-").replace(/\./g,"-").replace(/\s/g,"")}let r;function o(t,n,s,i){const r=e=>`${e[0]}, ${e[1]}`;let[o,a]=t,[l,u]=n,c=u-a,h=[o,a+c*s],d=[l,u-c*s],p=e.svg.mkPath("sim-bb-wire",`M${r(t)} C${r(h)} ${r(d)} ${r(n)}`);return e.U.addClass(p,`wire-stroke-${i}`),p}function a(t,n,s){const i=e=>`${e[0]}, ${e[1]}`;let r=e.svg.mkPath("sim-bb-wire",`M${i(t)} L${i(n)}`);return e.U.addClass(r,`wire-stroke-${s}`),r}function l(s,i){const r=t.PIN_DIST/4;let o=e.svg.elt("circle"),a=s[0],l=s[1],u=n/2+r/2;return e.svg.hydrate(o,{cx:a,cy:l,r:u,class:"sim-bb-wire-end"}),e.U.addClass(o,`wire-fill-${i}`),o.style["stroke-width"]=`${r}px`,o}function u(n,s,i){let r=.24*t.PIN_DIST,o=10*r,a=2*r,l=6*r,u=r;const c=t.PIN_DIST/4;let[h,d]=n,p=s?-1:1,f=e.svg.elt("g"),m=e.svg.elt("rect"),g=o,b=a,v=h-b/2,y=d-g/2;e.svg.hydrate(m,{x:v,y:y,width:b,height:g,rx:.5,ry:.5,class:"sim-bb-wire-end"}),m.style["stroke-width"]=`${c}px`;let S=e.svg.elt("rect"),w=l,x=u,E=h-x/2,I=d+p*(g/2+w/2)-w/2;return e.svg.hydrate(S,{x:E,y:I,width:x,height:w,class:"sim-bb-wire-bare-end"}),S.style.fill="#bbb",f.appendChild(S),f.appendChild(m),{el:f,x:v-c,y:Math.min(y,I),w:b+2*c,h:g+w}}function c(n,s,i){let r=.24*t.PIN_DIST;const o=4*r,a=10*r,l=3.5*r,u=3.5*r,c=t.PIN_DIST/4;let[h,d]=n,p=s?-1:1,f=e.svg.elt("g"),m=e.svg.elt("polygon"),g=a,b=o,v=h-b/2,y=d-g/2;const S=s?.15:.3,w=s?.7:1-.7,x=s?.3:.15;e.svg.hydrate(m,{points:((...e)=>e.map(e=>(e=>`${e[0]},${e[1]}`)(e)).join(" "))([v+b*S,y],[v+b*(1-S),y],[v+b,y+g*w],[v+b*(1-x),y+g],[v+b*x,y+g],[v,y+g*w])}),e.svg.hydrate(m,{rx:.5,ry:.5,class:"sim-bb-wire-end"}),m.style["stroke-width"]=`${c}px`;let E=e.svg.elt("rect"),I=l,k=u,C=h-k/2,R=d+p*(g/2+I/2)-I/2;return e.svg.hydrate(E,{x:C,y:R,width:k,height:I,class:"sim-bb-wire-bare-end"}),f.appendChild(E),f.appendChild(m),{el:f,x:v-c,y:Math.min(y,R),w:b+2*c,h:g+I}}t.WIRES_CSS=`\n .sim-bb-wire {\n fill:none;\n stroke-linecap: round;\n stroke-width:${n}px;\n pointer-events: none;\n }\n .sim-bb-wire-end {\n stroke:#333;\n fill:#333;\n }\n .sim-bb-wire-bare-end {\n fill: #ccc;\n }\n .sim-bb-wire-hover {\n stroke-width: ${n}px;\n visibility: hidden;\n stroke-dasharray: ${t.PIN_DIST/10},${t.PIN_DIST/1.5};\n /*stroke-opacity: 0.4;*/\n }\n .grayed .sim-bb-wire-ends-g:not(.highlight) .sim-bb-wire-end {\n stroke: #777;\n fill: #777;\n }\n .grayed .sim-bb-wire:not(.highlight) {\n stroke: #CCC;\n }\n .sim-bb-wire-ends-g:hover .sim-bb-wire-end {\n stroke: red;\n fill: red;\n }\n .sim-bb-wire-ends-g:hover .sim-bb-wire-bare-end {\n stroke: #FFF;\n fill: #FFF;\n }\n `,function(e){e[e.BBJumper=0]="BBJumper",e[e.OpenJumper=1]="OpenJumper",e[e.Croc=2]="Croc"}(r=t.WireEndStyle||(t.WireEndStyle={})),t.mkWirePart=function(n,s,i=!1){let r,o=e.svg.elt("g"),[a,l]=n,h=[a-15,l-50],d=[a+15,l+50];s=t.mapWireColor(s),r=i?c(h,!0,s):u(h,!0,s);let p=function(t,n,s){const i=e=>`${e[0]}, ${e[1]}`;let[r,o]=t,[a,l]=n,u=l-o,c=[r,o+.8*u],h=[a,l-.8*u],d=e.svg.mkPath("sim-bb-wire",`M${i(t)} C${i(c)} ${i(h)} ${i(n)}`);return d.style.stroke=s,{el:d,x:Math.min(r,a),y:Math.min(o,l),w:Math.abs(r-a),h:Math.abs(o-l)}}(h,d,s),f=u(d,!1,s);o.appendChild(p.el),o.appendChild(r.el),o.appendChild(f.el);let m=Math.min(r.x,f.x),g=Math.max(r.x+r.w,f.x+f.w),b=Math.min(r.y,f.y);return{el:o,x:m,y:b,w:g-m,h:Math.max(r.y+r.h,f.y+f.h)-b}};t.WireFactory=class{constructor(e,n,s,i,r,o){this.nextWireId=0,this.styleEl=i,this.styleEl.textContent+=t.WIRES_CSS,this.underboard=e,this.overboard=n,this.boardEdges=s,this.getLocCoord=r,this.getPinStyle=o}indexOfMin(e){let t=0,n=e[0];for(let s=1;s<e.length;s++)e[s]<n&&(n=e[s],t=s);return t}closestEdgeIdx(e){let t=this.boardEdges.map(t=>Math.abs(e[1]-t));return this.indexOfMin(t)}closestEdge(e){return this.boardEdges[this.closestEdgeIdx(e)]}drawWire(n,r,u){let c=[],h=e.svg.child(this.overboard,"g",{class:"sim-bb-wire-group"});const d=e=>{const n=t.PIN_DIST/2;let s,i=this.closestEdge(e);return s=i-e[1]<0?i-n:i+n,[e[0],s]};let p=this.nextWireId++,f=i(u),m=l(n,f),g=l(r,f),b=e.svg.child(h,"g",{class:"sim-bb-wire-ends-g"});b.appendChild(m),b.appendChild(g);let v=this.closestEdgeIdx(n),y=this.closestEdgeIdx(r);if(v==y){let e=a(n,r,f);h.appendChild(e),c.push(e)}else{let t,i,l=d(n),u=d(r),m=a(n,l,f),g=a(r,u,f);!(1!=v&&2!=v||1!=y&&2!=y)?(t=o(l,u,s,f),i=o(l,u,s,f)):(t=a(l,u,f),i=a(l,u,f)),e.U.addClass(i,"sim-bb-wire-hover"),h.appendChild(m),c.push(m),h.appendChild(g),c.push(g),this.underboard.appendChild(t),c.push(t),h.appendChild(i),c.push(i);let S=`sim-bb-wire-id-${p}`;const w=t=>e.U.addClass(t,S);w(b),w(i),this.styleEl.textContent+=`\n .${S}:hover ~ .${S}.sim-bb-wire-hover {\n visibility: visible;\n }`}let S=`\n .wire-stroke-${f} {\n stroke: ${t.mapWireColor(u)};\n }\n .wire-fill-${f} {\n fill: ${t.mapWireColor(u)};\n }\n `;return this.styleEl.textContent+=S,{endG:b,end1:m,end2:g,wires:c}}drawWireWithCrocs(n,r,u,h=!1){let d=[],p=e.svg.child(this.overboard,"g",{class:"sim-bb-wire-group"});const f=e=>{const n=t.PIN_DIST/2;let s,i=this.closestEdge(e);return s=i-e[1]<0?i-n:i+n,[e[0],s]};let m=this.nextWireId++,g=i(u),b=l(n,g),v=r,[y,S]=r;r=[y,S+40],[y,S]=r;let w,x=[y,S+-17];w=h?function(n,s){let i=.24*t.PIN_DIST,r=4*i,o=1.2*i,a=10*i,l=i;const u=t.PIN_DIST/4;let[c,h]=n,d=s?-1:1,p=e.svg.elt("g"),f=e.svg.elt("rect"),m=r,g=o,b=c-g/2,v=h+10-m/2;e.svg.hydrate(f,{x:b,y:v,width:g,height:m,rx:.5,ry:.5,class:"sim-bb-wire-end"}),f.style["stroke-width"]=`${u}px`;let y=e.svg.elt("rect"),S=a,w=l,x=c-w/2,E=h+10+d*(m/2+S/2)-S/2;return e.svg.hydrate(y,{x:x,y:E,width:w,height:S,class:"sim-bb-wire-bare-end"}),y.style.fill="#bbb",p.appendChild(y),p.appendChild(f),{el:p,x:b-u,y:Math.min(v,E),w:g+2*u,h:m+S}}(x,!0):c(x,!0);let E=w.el,I=e.svg.child(p,"g",{class:"sim-bb-wire-ends-g"});I.appendChild(b);let k=this.closestEdgeIdx(n),C=this.closestEdgeIdx(v);if(k==C){let e=a(n,r,g);p.appendChild(e),d.push(e)}else{let t,i,l=f(n),u=a(n,l,g);!(1!=k&&2!=k||1!=C&&2!=C)?(t=o(l,r,s,g),i=o(l,r,s,g)):(t=a(l,r,g),i=a(l,r,g)),e.U.addClass(i,"sim-bb-wire-hover"),p.appendChild(u),d.push(u),this.underboard.appendChild(t),d.push(t);let c=`sim-bb-wire-id-${m}`;const h=t=>e.U.addClass(t,c);h(I),h(i),this.styleEl.textContent+=`\n .${c}:hover ~ .${c}.sim-bb-wire-hover {\n visibility: visible;\n }`}I.appendChild(E);let R=`\n .wire-stroke-${g} {\n stroke: ${t.mapWireColor(u)};\n }\n .wire-fill-${g} {\n fill: ${t.mapWireColor(u)};\n }\n `;return this.styleEl.textContent+=R,{endG:I,end1:b,end2:E,wires:d}}checkWire(e,t){let n=this.getLocCoord(e),s=this.getLocCoord(t);return!!n&&!!s}addWire(t,n,s){let i=this.getLocCoord(t),r=this.getLocCoord(n);if(!i||!r)return void e.debug(`unable to allocate wire for ${t} or ${n}`);let o,a=this.getPinStyle(n);return o="dalboard"==n.type&&"croc"==a?this.drawWireWithCrocs(i,r,s):this.drawWire(i,r,s),o}}}(e.visuals||(e.visuals={}))}(pxsim||(pxsim={}));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Semgrep identified an issue in your code:
Possibility of prototype polluting assignment detected. By adding or modifying attributes of an object prototype, it is possible to create attributes that exist on every object, or replace critical attributes with malicious ones. This can be problematic if the software depends on existence or non-existence of certain attributes, or uses pre-defined attributes of object prototype (such as hasOwnProperty, toString or valueOf). Possible mitigations might be: freezing the object prototype, using an object without prototypes (via Object.create(null) ), blocking modifications of attributes that resolve to object prototype, using Map instead of object.

To resolve this comment:

🔧 No guidance has been designated for this issue. Fix according to your organization's approved methods.

💬 Ignore this finding

Reply with Semgrep commands to ignore this finding.

  • /fp <comment> for false positive
  • /ar <comment> for acceptable risk
  • /other <comment> for all other reasons

Alternatively, triage in Semgrep AppSec Platform to ignore the finding created by prototype-pollution-assignment.

You can view more details about this finding in the Semgrep AppSec Platform.

Comment on lines +1960 to +1964
const res = await fetch('/api/aria/object', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Semgrep identified an issue in your code:
This application allows user-controlled URLs to be passed directly to HTTP client libraries. This can result in Server-Side Request Forgery (SSRF). SSRF refers to an attack where the attacker can abuse functionality on the server to force it to make requests to other internal systems within your infrastructure that are not directly exposed to the internet. This allows the attacker to access internal resources they do not have direct access to.
Some risks of SSRF are:

  • Access and manipulation of internal databases, APIs, or administrative panels - Ability to scan internal network architecture and services - Can be used to pivot attacks into the internal network - Circumvent network segregation and firewall rules
    To avoid this, try using hardcoded HTTP request calls or a whitelisting object to check whether the user input is trying to access allowed resources or not.
    Here is an example: var whitelist = [ "https://example.com", "https://example.com/sample" ] app.get('/ssrf/node-ssrf/axios/safe/3', function (req, res) { if(whitelist.includes(req.query.url)){ axios.get(url, {}) .then(function (response) { console.log(response); }) .catch(function (response) { console.log(response); }) } }); For more information on SSRF see OWASP: https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html
Dataflow graph
flowchart LR
    classDef invis fill:white, stroke: none
    classDef default fill:#e7f5ff, color:#1c7fd6, stroke: none

    subgraph File0["<b>apps/aria/aria_controller.js</b>"]
        direction LR
        %% Source

        subgraph Source
            direction LR

            v0["<a href=https://github.com/Bryan-Roe/Aria/blob/551a8cb1989e3198b6a0735d7c29464614c3984d/apps/aria/aria_controller.js#L930 target=_blank style='text-decoration:none; color:#1c7fd6'>[Line: 930] tag</a>"]
        end
        %% Intermediate

        subgraph Traces0[Traces]
            direction TB

            v2["<a href=https://github.com/Bryan-Roe/Aria/blob/551a8cb1989e3198b6a0735d7c29464614c3984d/apps/aria/aria_controller.js#L930 target=_blank style='text-decoration:none; color:#1c7fd6'>[Line: 930] tag</a>"]

            v3["<a href=https://github.com/Bryan-Roe/Aria/blob/551a8cb1989e3198b6a0735d7c29464614c3984d/apps/aria/aria_controller.js#L932 target=_blank style='text-decoration:none; color:#1c7fd6'>[Line: 932] match</a>"]

            v4["<a href=https://github.com/Bryan-Roe/Aria/blob/551a8cb1989e3198b6a0735d7c29464614c3984d/apps/aria/aria_controller.js#L938 target=_blank style='text-decoration:none; color:#1c7fd6'>[Line: 938] ]</a>"]

            v5["<a href=https://github.com/Bryan-Roe/Aria/blob/551a8cb1989e3198b6a0735d7c29464614c3984d/apps/aria/aria_controller.js#L938 target=_blank style='text-decoration:none; color:#1c7fd6'>[Line: 938] paramRaw</a>"]

            v6["<a href=https://github.com/Bryan-Roe/Aria/blob/551a8cb1989e3198b6a0735d7c29464614c3984d/apps/aria/aria_controller.js#L942 target=_blank style='text-decoration:none; color:#1c7fd6'>[Line: 942] param</a>"]

            v7["<a href=https://github.com/Bryan-Roe/Aria/blob/551a8cb1989e3198b6a0735d7c29464614c3984d/apps/aria/aria_controller.js#L998 target=_blank style='text-decoration:none; color:#1c7fd6'>[Line: 998] ]</a>"]

            v8["<a href=https://github.com/Bryan-Roe/Aria/blob/551a8cb1989e3198b6a0735d7c29464614c3984d/apps/aria/aria_controller.js#L998 target=_blank style='text-decoration:none; color:#1c7fd6'>[Line: 998] ]</a>"]

            v9["<a href=https://github.com/Bryan-Roe/Aria/blob/551a8cb1989e3198b6a0735d7c29464614c3984d/apps/aria/aria_controller.js#L998 target=_blank style='text-decoration:none; color:#1c7fd6'>[Line: 998] objectName</a>"]

            v10["<a href=https://github.com/Bryan-Roe/Aria/blob/551a8cb1989e3198b6a0735d7c29464614c3984d/apps/aria/aria_controller.js#L999 target=_blank style='text-decoration:none; color:#1c7fd6'>[Line: 999] addObject</a>"]

            v11["<a href=https://github.com/Bryan-Roe/Aria/blob/551a8cb1989e3198b6a0735d7c29464614c3984d/apps/aria/aria_controller.js#L2220 target=_blank style='text-decoration:none; color:#1c7fd6'>[Line: 2220] objectName</a>"]

            v12["<a href=https://github.com/Bryan-Roe/Aria/blob/551a8cb1989e3198b6a0735d7c29464614c3984d/apps/aria/aria_controller.js#L2256 target=_blank style='text-decoration:none; color:#1c7fd6'>[Line: 2256] toggleObject</a>"]

            v13["<a href=https://github.com/Bryan-Roe/Aria/blob/551a8cb1989e3198b6a0735d7c29464614c3984d/apps/aria/aria_controller.js#L149 target=_blank style='text-decoration:none; color:#1c7fd6'>[Line: 149] objectId</a>"]

            v14["<a href=https://github.com/Bryan-Roe/Aria/blob/551a8cb1989e3198b6a0735d7c29464614c3984d/apps/aria/aria_controller.js#L168 target=_blank style='text-decoration:none; color:#1c7fd6'>[Line: 168] sendObjectUpdate</a>"]

            v15["<a href=https://github.com/Bryan-Roe/Aria/blob/551a8cb1989e3198b6a0735d7c29464614c3984d/apps/aria/aria_controller.js#L1942 target=_blank style='text-decoration:none; color:#1c7fd6'>[Line: 1942] objectId</a>"]

            v16["<a href=https://github.com/Bryan-Roe/Aria/blob/551a8cb1989e3198b6a0735d7c29464614c3984d/apps/aria/aria_controller.js#L1954 target=_blank style='text-decoration:none; color:#1c7fd6'>[Line: 1954] objPayload</a>"]

            v17["<a href=https://github.com/Bryan-Roe/Aria/blob/551a8cb1989e3198b6a0735d7c29464614c3984d/apps/aria/aria_controller.js#L1958 target=_blank style='text-decoration:none; color:#1c7fd6'>[Line: 1958] payload</a>"]
        end
            v2 --> v3
            v3 --> v4
            v4 --> v5
            v5 --> v6
            v6 --> v7
            v7 --> v8
            v8 --> v9
            v9 --> v10
            v10 --> v11
            v11 --> v12
            v12 --> v13
            v13 --> v14
            v14 --> v15
            v15 --> v16
            v16 --> v17
        %% Sink

        subgraph Sink
            direction LR

            v1["<a href=https://github.com/Bryan-Roe/Aria/blob/551a8cb1989e3198b6a0735d7c29464614c3984d/apps/aria/aria_controller.js#L1960 target=_blank style='text-decoration:none; color:#1c7fd6'>[Line: 1960] fetch(&apos;/api/aria/object&apos;, {
<br>            method: &apos;POST&apos;,
<br>            headers: { &apos;Content-Type&apos;: &apos;application/json&apos; },
<br>            body: JSON.stringify(payload)
<br>        })</a>"]
        end
    end
    %% Class Assignment
    Source:::invis
    Sink:::invis

    Traces0:::invis
    File0:::invis

    %% Connections

    Source --> Traces0
    Traces0 --> Sink


Loading

To resolve this comment:

🔧 No guidance has been designated for this issue. Fix according to your organization's approved methods.

💬 Ignore this finding

Reply with Semgrep commands to ignore this finding.

  • /fp <comment> for false positive
  • /ar <comment> for acceptable risk
  • /other <comment> for all other reasons

Alternatively, triage in Semgrep AppSec Platform to ignore the finding created by javascript-ssrf-rule-node_ssrf.

You can view more details about this finding in the Semgrep AppSec Platform.

@Bryan-Roe Bryan-Roe marked this pull request as ready for review April 11, 2026 07:06

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @Bryan-Roe! 👋

Your private repo does not have access to Sourcery.

Please upgrade to continue using Sourcery ✨

Co-authored-by: semgrep-code-bryan-roe[bot] <190102486+semgrep-code-bryan-roe[bot]@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Note

Copilot was unable to run its full agentic suite in this review.

Restores the repository after an accidental empty-tree commit wiped the working tree, reintroducing source, GitHub Actions workflows, and repo configuration so CI can run again.

Changes:

  • Re-added GitHub Actions workflows and a reusable composite action for Python environment setup.
  • Restored repo automation/configuration under .github/ (prompts, skills, instructions, hooks, templates, labeler, CODEOWNERS).
  • Restored developer tooling/config files (devcontainer, githooks, ignore files, Azure ML specs).

Reviewed changes

Copilot reviewed 202 out of 1681 changed files in this pull request and generated 8 comments.

Show a summary per file
File Description
.github/workflows/markdown-quality.yml Restores Markdown lint workflow to bring back docs quality checks.
.github/workflows/makecode.yml Restores MakeCode build workflow.
.github/workflows/llm-maker-tests.yml Restores llm-maker pytest workflow for that subproject.
.github/workflows/integration-contract-gate.yml Restores contract gate workflow for integration scripts/status artifacts.
.github/workflows/e2e-tests.yml Restores quick Aria regression suite jobs (unit/integration + UI).
.github/workflows/devcontainer-ci.yml Restores devcontainer build/test CI.
.github/workflows/dependency-review.yml Restores dependency review gate on PRs.
.github/workflows/dependabot-automerge.yml Restores Dependabot auto-approval/merge automation.
.github/workflows/codeql.yml Restores CodeQL scanning workflow.
.github/workflows/code-quality.yml Restores linting and dependency audit workflows.
.github/workflows/broken-links.yml Restores docs link checking workflow.
.github/workflows/azureml-train.yml Restores manual AzureML training submission workflow.
.github/workflows/auto-validation.yml Restores orchestrator config validation workflow.
.github/workflows/artifact-lifecycle.yml Restores scheduled/manual artifact cleanup workflow.
.github/workflows/api-health-smoke.yml Restores API smoke checks + artifact upload.
.github/workflows/actionlint.yml Restores workflow linting for maintaining GA YAML quality.
.github/workflows/README.md Documents restored workflows and intended usage patterns.
.github/skills/**/SKILL.md Restores skill docs used for consistent debugging/refactor/ops workflows.
.github/prompts/*.prompt.md Restores prompt definitions for repo-specific agent workflows.
.github/labeler.yml Restores PR auto-labeling rules.
.github/instructions/*.instructions.md Restores scoped coding/testing instructions for key areas.
.github/hooks/*.json Restores hook configuration for guardrails (secrets, scope drift, etc.).
.github/actions/setup-python-env/action.yml Restores composite action for consistent Python setup/install/caching in CI.
.github/PULL_REQUEST_TEMPLATE.md Restores PR template to standardize summaries/testing notes.
.github/ISSUE_TEMPLATE/feature_request.md Restores GitHub issue template (feature request).
.github/ISSUE_TEMPLATE/bug_report.md Restores GitHub issue template (bug report).
.github/FUNDING.yml Restores funding configuration.
.github/CODEOWNERS Restores default repository code ownership.
.githooks/pre-commit.ps1 Restores Windows pre-commit test hook.
.githooks/pre-commit Restores bash pre-commit test hook.
.githooks/README.md Documents installation/usage of restored githooks.
.funcignore Restores Azure Functions packaging ignore list.
.foundry/.deployment.json Restores Foundry deployment metadata.
.env.example Restores example env var template for local dev.
.dockerignore Restores Docker ignore patterns.
.devcontainer/devcontainer.json Restores devcontainer configuration for local dev environment.
.azureml/job_multi_20251125T055919Z.yaml Restores generated AzureML command job spec.
.azureml/job_multi_20251125T012559Z.yaml Restores generated AzureML command job spec.
.azureml/job_multi_20251125T012515Z.yaml Restores generated AzureML command job spec.
.azureml/job_dummy.yaml Restores placeholder AzureML job spec.
.azureml/environment.yml Restores AzureML environment definition.
## GitHub Copilot Chat.md Restores captured Copilot Chat diagnostic log (see security note below).

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread .devcontainer/devcontainer.json Outdated
Comment on lines +10 to +43
"ms-azuretools.vscode-docker"
]
}
}
}
// For format details, see https://aka.ms/devcontainer.json. For config options, see the
// README at: https://github.com/devcontainers/templates/tree/main/src/python
{
"name": "Python 3",
// Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile
"image": "mcr.microsoft.com/devcontainers/python:2-3.14-trixie",
"customizations": {
"vscode": {
"extensions": [
"ms-windows-ai-studio.windows-ai-studio",
"GitHub.copilot-chat"
]
}
}

// Features to add to the dev container. More info: https://containers.dev/features.
// "features": {},

// Use 'forwardPorts' to make a list of ports inside the container available locally.
// "forwardPorts": [],

// Use 'postCreateCommand' to run commands after the container is created.
// "postCreateCommand": "pip3 install --user -r requirements.txt",

// Configure tool-specific properties.
// "customizations": {},

// Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root.
// "remoteUser": "root"

Copilot AI Apr 11, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This file is not valid JSON (it contains two top-level objects and // comments). Dev Containers expects a single JSON object, so this will break devcontainer startup. Keep one configuration object (merge the desired fields and images into one) and remove comments or relocate them to a separate README.

Suggested change
"ms-azuretools.vscode-docker"
]
}
}
}
// For format details, see https://aka.ms/devcontainer.json. For config options, see the
// README at: https://github.com/devcontainers/templates/tree/main/src/python
{
"name": "Python 3",
// Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile
"image": "mcr.microsoft.com/devcontainers/python:2-3.14-trixie",
"customizations": {
"vscode": {
"extensions": [
"ms-windows-ai-studio.windows-ai-studio",
"GitHub.copilot-chat"
]
}
}
// Features to add to the dev container. More info: https://containers.dev/features.
// "features": {},
// Use 'forwardPorts' to make a list of ports inside the container available locally.
// "forwardPorts": [],
// Use 'postCreateCommand' to run commands after the container is created.
// "postCreateCommand": "pip3 install --user -r requirements.txt",
// Configure tool-specific properties.
// "customizations": {},
// Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root.
// "remoteUser": "root"
"ms-azuretools.vscode-docker",
"ms-windows-ai-studio.windows-ai-studio",
"GitHub.copilot-chat"
]
}
}

Copilot uses AI. Check for mistakes.
'**/*.md'
'docs/**/*.md'
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

Copilot AI Apr 11, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

env: is currently nested under with: (same indentation level as with:'s keys), which means GitHub Actions will treat it as an invalid input rather than setting environment variables for the step. Move env: to be a sibling of with: (step-level) so GITHUB_TOKEN is actually set for the action.

Suggested change
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

Copilot uses AI. Check for mistakes.
Comment thread .githooks/pre-commit
Comment on lines +10 to +28
set -e

echo "🧪 Running pre-commit tests..."

# Run fast unit tests only (skip slow/integration)
python scripts/test_runner.py --unit --verbose 0

if [ $? -eq 0 ]; then
echo "✅ Tests passed - proceeding with commit"
exit 0
else
echo "❌ Tests failed - commit blocked"
echo ""
echo "To fix:"
echo " 1. Review test failures above"
echo " 2. Fix the issues and try again"
echo " 3. Or bypass with: git commit --no-verify (not recommended)"
exit 1
fi

Copilot AI Apr 11, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

set -e causes the script to exit immediately when the test command fails, so the failure-message branch never runs (and the $? check is effectively dead code in failure cases). Capture the test exit code (or temporarily disable -e around the test run) so the hook can print the intended guidance before exiting non-zero.

Copilot uses AI. Check for mistakes.
Comment thread .github/workflows/makecode.yml Outdated
Comment on lines +10 to +12
- uses: actions/checkout@v3
with:
submodules: recursive

Copilot AI Apr 11, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This workflow relies on npx makecode but does not set up a specific Node.js version (and uses actions/checkout@v3). For reliability/reproducibility, add an explicit Node setup step (with caching if appropriate) and upgrade checkout to actions/checkout@v4 to align with the rest of the workflows.

Suggested change
- uses: actions/checkout@v3
with:
submodules: recursive
- uses: actions/checkout@v4
with:
submodules: recursive
- uses: actions/setup-node@v4
with:
node-version: '20'

Copilot uses AI. Check for mistakes.
Comment thread .github/workflows/actionlint.yml Outdated
Comment on lines +31 to +35
- name: Run actionlint
uses: reviewdog/action-actionlint@v1
with:
fail_level: failure
reporter: github-pr-check

Copilot AI Apr 11, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This workflow runs on push and workflow_dispatch, but reviewdog's github-pr-check reporter is PR-oriented and can fail or behave unexpectedly when there is no PR context. Consider either (a) restricting this workflow to pull_request only, or (b) switching to a reporter that works on pushes (and adding the minimal required permissions for creating check runs if needed).

Copilot uses AI. Check for mistakes.
Comment thread .github/workflows/llm-maker-tests.yml Outdated
uses: actions/checkout@v4

- name: Set up Python
uses: actions/setup-python@v4

Copilot AI Apr 11, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Most workflows here use actions/setup-python@v5 (and the repo has a composite action that uses v5). To reduce version skew and benefit from the newer action, update this to actions/setup-python@v5 (or reuse ./.github/actions/setup-python-env).

Suggested change
uses: actions/setup-python@v4
uses: actions/setup-python@v5

Copilot uses AI. Check for mistakes.
Comment thread ## GitHub Copilot Chat.md Outdated
Comment on lines +3 to +55
- Extension: 0.41.2 (prod)
- VS Code: 1.113.0 (cfbea10c5ffb233ea9177d34726e6056e89913dc)
- OS: linux 6.6.87.2-microsoft-standard-WSL2 x64
- Remote Name: dev-container
- Extension Kind: Workspace
- GitHub Account: Bryan-Roe

## Network

User Settings:
```json
"http.systemCertificatesNode": true,
"http.experimental.systemCertificatesV2": true,
"github.copilot.advanced.debug.useElectronFetcher": false,
"github.copilot.advanced.debug.useNodeFetcher": true,
"github.copilot.advanced.debug.useNodeFetchFetcher": false
```

Connecting to https://api.github.com:
- DNS ipv4 Lookup: 140.82.116.6 (37 ms)
- DNS ipv6 Lookup: Error (18 ms): getaddrinfo ENOTFOUND api.github.com
- Proxy URL: None (1 ms)
- Electron fetch: Unavailable
- Node.js https (configured): HTTP 200 (2096 ms)
- Node.js fetch (active): HTTP 200 (306 ms)

Connecting to https://api.individual.githubcopilot.com/_ping:
- DNS ipv4 Lookup: 140.82.114.21 (8 ms)
- DNS ipv6 Lookup: Error (6 ms): getaddrinfo ENOTFOUND api.individual.githubcopilot.com
- Proxy URL: None (0 ms)
- Electron fetch: Unavailable
- Node.js https (configured): HTTP 200 (471 ms)
- Node.js fetch (active): HTTP 200 (134 ms)

Connecting to https://proxy.individual.githubcopilot.com/_ping:
- DNS ipv4 Lookup: 138.91.182.224 (10 ms)
- DNS ipv6 Lookup: Error (7 ms): getaddrinfo ENOTFOUND proxy.individual.githubcopilot.com
- Proxy URL: None (0 ms)
- Electron fetch: Unavailable
- Node.js https (configured): HTTP 200 (246 ms)
- Node.js fetch (active): HTTP 200 (202 ms)

Connecting to https://mobile.events.data.microsoft.com: HTTP 404 (771 ms)
Connecting to https://dc.services.visualstudio.com: HTTP 404 (548 ms)
Connecting to https://copilot-telemetry.githubusercontent.com/_ping: HTTP 200 (382 ms)
Connecting to https://telemetry.individual.githubcopilot.com/_ping: HTTP 200 (564 ms)
Connecting to https://default.exp-tas.com: HTTP 400 (527 ms)

Number of system certificates: 414

## Documentation

In corporate networks: [Troubleshooting firewall settings for GitHub Copilot](https://docs.github.com/en/copilot/troubleshooting-github-copilot/troubleshooting-firewall-settings-for-github-copilot).

Copilot AI Apr 11, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This appears to be a local diagnostic/support log and includes potentially sensitive environment details (account name, network/DNS behavior, internal configuration). Consider removing it from the repository (or moving it to a private support artifact), or at minimum redact identifiers and any environment-specific details before committing.

Suggested change
- Extension: 0.41.2 (prod)
- VS Code: 1.113.0 (cfbea10c5ffb233ea9177d34726e6056e89913dc)
- OS: linux 6.6.87.2-microsoft-standard-WSL2 x64
- Remote Name: dev-container
- Extension Kind: Workspace
- GitHub Account: Bryan-Roe
## Network
User Settings:
```json
"http.systemCertificatesNode": true,
"http.experimental.systemCertificatesV2": true,
"github.copilot.advanced.debug.useElectronFetcher": false,
"github.copilot.advanced.debug.useNodeFetcher": true,
"github.copilot.advanced.debug.useNodeFetchFetcher": false
```
Connecting to https://api.github.com:
- DNS ipv4 Lookup: 140.82.116.6 (37 ms)
- DNS ipv6 Lookup: Error (18 ms): getaddrinfo ENOTFOUND api.github.com
- Proxy URL: None (1 ms)
- Electron fetch: Unavailable
- Node.js https (configured): HTTP 200 (2096 ms)
- Node.js fetch (active): HTTP 200 (306 ms)
Connecting to https://api.individual.githubcopilot.com/_ping:
- DNS ipv4 Lookup: 140.82.114.21 (8 ms)
- DNS ipv6 Lookup: Error (6 ms): getaddrinfo ENOTFOUND api.individual.githubcopilot.com
- Proxy URL: None (0 ms)
- Electron fetch: Unavailable
- Node.js https (configured): HTTP 200 (471 ms)
- Node.js fetch (active): HTTP 200 (134 ms)
Connecting to https://proxy.individual.githubcopilot.com/_ping:
- DNS ipv4 Lookup: 138.91.182.224 (10 ms)
- DNS ipv6 Lookup: Error (7 ms): getaddrinfo ENOTFOUND proxy.individual.githubcopilot.com
- Proxy URL: None (0 ms)
- Electron fetch: Unavailable
- Node.js https (configured): HTTP 200 (246 ms)
- Node.js fetch (active): HTTP 200 (202 ms)
Connecting to https://mobile.events.data.microsoft.com: HTTP 404 (771 ms)
Connecting to https://dc.services.visualstudio.com: HTTP 404 (548 ms)
Connecting to https://copilot-telemetry.githubusercontent.com/_ping: HTTP 200 (382 ms)
Connecting to https://telemetry.individual.githubcopilot.com/_ping: HTTP 200 (564 ms)
Connecting to https://default.exp-tas.com: HTTP 400 (527 ms)
Number of system certificates: 414
## Documentation
In corporate networks: [Troubleshooting firewall settings for GitHub Copilot](https://docs.github.com/en/copilot/troubleshooting-github-copilot/troubleshooting-firewall-settings-for-github-copilot).
This file previously contained a local diagnostic/support log generated from a development environment.
The detailed log has been removed from version control because it included environment-specific and potentially sensitive information such as account identifiers, system configuration, and network diagnostics.
## Documentation
For troubleshooting GitHub Copilot connectivity in corporate networks, see [Troubleshooting firewall settings for GitHub Copilot](https://docs.github.com/en/copilot/troubleshooting-github-copilot/troubleshooting-firewall-settings-for-github-copilot).

Copilot uses AI. Check for mistakes.
Comment thread ## GitHub Copilot Chat.md Outdated
Comment on lines +21 to +23
Connecting to https://api.github.com:
- DNS ipv4 Lookup: 140.82.116.6 (37 ms)
- DNS ipv6 Lookup: Error (18 ms): getaddrinfo ENOTFOUND api.github.com

Copilot AI Apr 11, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This appears to be a local diagnostic/support log and includes potentially sensitive environment details (account name, network/DNS behavior, internal configuration). Consider removing it from the repository (or moving it to a private support artifact), or at minimum redact identifiers and any environment-specific details before committing.

Copilot uses AI. Check for mistakes.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@copilot apply changes based on this feedback

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in commit 5361ec1. Replaced the sensitive diagnostic log with a safe summary that removes all environment-specific details (account name, IP addresses, DNS results, system/network config) and points to the official troubleshooting docs instead.

…a40-4d1f-bf93-9af0b1f6e47f

Co-authored-by: Bryan-Roe <74067792+Bryan-Roe@users.noreply.github.com>
Copilot AI requested a review from Bryan-Roe April 11, 2026 07:09

Copilot AI commented Apr 11, 2026

Copy link
Copy Markdown
Contributor Author

@Bryan-Roe Unfortunately I hit an unexpected error while processing your comment. I've automatically reported this to GitHub.

You can ask me to try again later by mentioning me in a new comment.

If you want to contact GitHub about this error, please mention the following identifier so they can better serve you: ecf9e0ef-8103-4754-86ec-73d84f05a5dc

Sorry for the inconvenience!

@Bryan-Roe

Copy link
Copy Markdown
Owner

@copilot apply changes based on the comments in this thread

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b46bdfef3c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

print(f" ✅ Server is running! Found {len(datasets)} datasets.")
else:
print(f" ❌ Server returned error: {response.status_code}")
sys.exit(1)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Import sys before using sys.exit in demo script

This change replaces exit(1) with sys.exit(1), but the module still does not import sys, so any non-200 response path now raises NameError instead of terminating cleanly. In practice, when /api/datasets or /api/train/start fails, the script will crash with an exception and mask the actual failure condition.

Useful? React with 👍 / 👎.

Bryan-Roe and others added 2 commits April 11, 2026 00:11
Co-authored-by: semgrep-code-bryan-roe[bot] <190102486+semgrep-code-bryan-roe[bot]@users.noreply.github.com>
…mit hook, diagnostic log)

Agent-Logs-Url: https://github.com/Bryan-Roe/Aria/sessions/332126d9-cfad-49b0-ba31-fb2d7d7de746

Co-authored-by: Bryan-Roe <74067792+Bryan-Roe@users.noreply.github.com>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 16570d0cb1

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

"""
print("\n" + "="*70)
print("Example 1: Healthcare Data Analysis (HIPAA-Compliant)")
print("=""*70 + "\n")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Fix invalid string expression that breaks module parsing

The expression print("=""*70 + "\n") is syntactically invalid Python, so importing or executing privacy_first_ai.py fails immediately with a SyntaxError before any privacy workflow runs. This makes the entire example module unusable in environments that load it as a script or import it for demonstrations.

Useful? React with 👍 / 👎.

response = requests.post(
f"{BASE_URL}/api/aria/execute",
json={"command": command, "auto_execute": False, "use_llm": False},
, timeout=30)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Remove stray comma in requests call argument list

This requests.post call has a standalone leading comma before timeout, which is invalid syntax and prevents the file from being parsed. As a result, the test module cannot be imported or run at all (and the same malformed pattern appears again in execute_mode), so the auto-execute smoke tests are effectively broken.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Credits must be used to enable repository wide code reviews.

@github-actions

github-actions Bot commented Apr 11, 2026

Copy link
Copy Markdown
Contributor

🔴 Coverage — ba95a40

Metric Value
Total coverage 56.5%
Minimum threshold 60%

Updated on every push · 2026-04-11

Copilot AI commented Apr 11, 2026

Copy link
Copy Markdown
Contributor Author

@copilot apply changes based on the comments in this thread

All review feedback applied in commit 5361ec1:

  • .devcontainer/devcontainer.json — merged two top-level objects into one valid JSON, removed // comments, combined all four extensions, updated image to 2-3.14-trixie
  • .githooks/pre-commit — fixed set -e dead-code issue by capturing exit code with set +e/TEST_EXIT_CODE=$?/set -e so the failure message branch can actually run
  • .github/workflows/makecode.yml — upgraded checkout@v3@v4, added setup-node@v4 with node-version: '20'
  • .github/workflows/actionlint.yml — changed reporter from github-pr-check to github-check (works on push context too), added permissions: checks: write
  • .github/workflows/llm-maker-tests.yml — upgraded setup-python@v4@v5
  • ## GitHub Copilot Chat.md — redacted sensitive diagnostic log content
  • .github/workflows/broken-links.ymlenv: was already correctly placed at step level; no change needed

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@Bryan-Roe Bryan-Roe merged commit f42df4b into main Apr 11, 2026
20 of 34 checks passed
@Bryan-Roe Bryan-Roe deleted the copilot/fix-actions branch April 11, 2026 07:21

# Show sample entries
print(f"\nAudit Trail (last 2 entries):")
with open(audit_file) as f:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Semgrep identified an issue in your code:
Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding="utf-8").

To resolve this comment:

🔧 No guidance has been designated for this issue. Fix according to your organization's approved methods.

💬 Ignore this finding

Reply with Semgrep commands to ignore this finding.

  • /fp <comment> for false positive
  • /ar <comment> for acceptable risk
  • /other <comment> for all other reasons

Alternatively, triage in Semgrep AppSec Platform to ignore the finding created by unspecified-open-encoding.

You can view more details about this finding in the Semgrep AppSec Platform.

cutoff = datetime.now() - timedelta(hours=hours_lookback)

recent_entries = []
with open(self.log_path) as f:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Semgrep identified an issue in your code:
Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding="utf-8").

To resolve this comment:

🔧 No guidance has been designated for this issue. Fix according to your organization's approved methods.

💬 Ignore this finding

Reply with Semgrep commands to ignore this finding.

  • /fp <comment> for false positive
  • /ar <comment> for acceptable risk
  • /other <comment> for all other reasons

Alternatively, triage in Semgrep AppSec Platform to ignore the finding created by unspecified-open-encoding.

You can view more details about this finding in the Semgrep AppSec Platform.

"result_hash": hashlib.sha256(result.encode()).hexdigest()[:8] if result else None,
}

with open(self.log_path, "a") as f:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Semgrep identified an issue in your code:
Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding="utf-8").

To resolve this comment:

🔧 No guidance has been designated for this issue. Fix according to your organization's approved methods.

💬 Ignore this finding

Reply with Semgrep commands to ignore this finding.

  • /fp <comment> for false positive
  • /ar <comment> for acceptable risk
  • /other <comment> for all other reasons

Alternatively, triage in Semgrep AppSec Platform to ignore the finding created by unspecified-open-encoding.

You can view more details about this finding in the Semgrep AppSec Platform.

@bryan-roe-bot

bryan-roe-bot Bot commented Apr 11, 2026

Copy link
Copy Markdown
Contributor

Semgrep found 33 rule findings:

Semgrep found a match

Comment on lines +169 to +171
async def check():
client = get_lmstudio_agent_client()
return await client.check_health()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Semgrep identified an issue in your code:
function check is defined inside a function but never used

To resolve this comment:

🔧 No guidance has been designated for this issue. Fix according to your organization's approved methods.

💬 Ignore this finding

Reply with Semgrep commands to ignore this finding.

  • /fp <comment> for false positive
  • /ar <comment> for acceptable risk
  • /other <comment> for all other reasons

Alternatively, triage in Semgrep AppSec Platform to ignore the finding created by useless-inner-function.

You can view more details about this finding in the Semgrep AppSec Platform.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants