From 275863992d3141ef15d78929885bbd83b95ad858 Mon Sep 17 00:00:00 2001 From: Eric Anderson Date: Tue, 24 Nov 2026 11:04:46 -0800 Subject: [PATCH] Let a target build a DOM-free simulator bundle - pxt buildtarget compiles sim/tsconfig.core.json to built/simcore.js when a target has one, before sim/tsconfig.json. Targets without one build as before. - Added a prepend list to sim/tsconfig.json. The build concatenates the listed files, and their .d.ts, ahead of the compiled output, so sim.js is simcore.js plus the view code. - The npm-installed simulator and the common target build the same way. - Two incidental changes: the simulator builds before the target core so coverage sees it on the first build, and the shim scan no longer duplicates tsc diagnostics. Build, the cli tests and the simulator test tasks pass. --- .../instructions/simulator.instructions.md | 2 + cli/cli.ts | 111 ++++++++++++++---- pxtcompiler/emitter/plaintsc.ts | 12 +- pxtsimcore/README.md | 38 ++++++ 4 files changed, 136 insertions(+), 27 deletions(-) diff --git a/.github/instructions/simulator.instructions.md b/.github/instructions/simulator.instructions.md index 157db6c2d5b1..de74fb1f2928 100644 --- a/.github/instructions/simulator.instructions.md +++ b/.github/instructions/simulator.instructions.md @@ -15,6 +15,8 @@ applyTo: "pxtsim/**/*.ts,pxtsimcore/**,sim/**/*.ts,**/sim/*.ts" - New runtime, board-state and synthesis code belongs to `pxtsimcore`; only view code belongs to `pxtsim` - Globals the core may use are declared in `pxtsimcore/globals.d.ts`; never add the `dom` lib to core - Consumers load `built/pxtsim.js`, which is core followed by the DOM code; keep the `pxsim` namespace +- A target's or library's DOM-free simulator files live in its `core/` folder, and its `tsconfig.core.json` globs that folder +- A lib's or target's full simulator config compiles only its view files against the core bundle's `.d.ts` and prepends the core bundle, so `sim.js` is `simcore.js` followed by the view code; a view file never references a core source file, only the core declarations ## Host Abstractions diff --git a/cli/cli.ts b/cli/cli.ts index 963eddd20a82..50d07bb81f67 100644 --- a/cli/cli.ts +++ b/cli/cli.ts @@ -1648,6 +1648,7 @@ export async function internalBuildTargetAsync(options: BuildTargetOptions = {}) await simshimAsync(); await buildFolderAsync('compiler', true, 'compiler'); fillInCompilerExtension(pxt.appTarget); + await buildSimAsync(); if (options.rebundle) { await buildTargetCoreAsync({ quick: true }); @@ -1656,7 +1657,6 @@ export async function internalBuildTargetAsync(options: BuildTargetOptions = {}) await buildTargetCoreAsync(options); } - await buildSimAsync(); await buildFolderAsync('cmds', true); await buildSemanticUIAsync(); await buildEditorExtensionAsync("editor", "extendEditor"); @@ -1693,53 +1693,83 @@ function buildEditorExtensionAsync(dirname: string, optionName: string) { return Promise.resolve(); } -function buildFolderAsync(p: string, optional?: boolean, outputName?: string): Promise { - if (!fs.existsSync(path.join(p, "tsconfig.json"))) { - if (!optional) U.userError(`${p}/tsconfig.json not found`); +/** + * Compiles the TypeScript project in folder `p` by running tsc on `configName`. When `outputName` + * is given, the config must put its output in `../built/.js`. A sim installed from npm + * (`node_modules/pxt-*-sim`) can build into its own `./built/` folder instead, and the output is + * then copied to `built/`. With `optional`, a missing config just means there is nothing to build. + * + * Files listed in the config's `prepend` are added to the start of the output, in order. If the + * config sets `declaration`, the `.d.ts` files next to them are prepended to the emitted `.d.ts`. + */ +function buildFolderAsync(p: string, optional?: boolean, outputName?: string, configName = "tsconfig.json"): Promise { + const configFile = `${p}/${configName}`; + if (!fs.existsSync(path.join(p, configName))) { + if (!optional) U.userError(`${configFile} not found`); return Promise.resolve() } - const tsConfig = JSON.parse(fs.readFileSync(path.join(p, "tsconfig.json"), "utf8")); + const isMainConfig = configName === "tsconfig.json"; + const tsConfig = JSON.parse(fs.readFileSync(path.join(p, configName), "utf8")); let isNodeModule = false; if (outputName && tsConfig.compilerOptions.outFile !== `../built/${outputName}.js`) { // Special case to support target sim as an NPM package if (/^node_modules[\/\\]+pxt-.*?-sim$/.test(p)) { // Allow the out dir be inside the folder being built, and manually copy the result to ./built afterwards if (tsConfig.compilerOptions.outFile !== `./built/${outputName}.js`) { - U.userError(`${p}/tsconfig.json expected compilerOptions.outFile:"./built/${outputName}.js", got "${tsConfig.compilerOptions.outFile}"`); + U.userError(`${configFile} expected compilerOptions.outFile:"./built/${outputName}.js", got "${tsConfig.compilerOptions.outFile}"`); } isNodeModule = true; } else { - U.userError(`${p}/tsconfig.json expected compilerOptions.outFile:"../built/${outputName}.js", got "${tsConfig.compilerOptions.outFile}"`); + U.userError(`${configFile} expected compilerOptions.outFile:"../built/${outputName}.js", got "${tsConfig.compilerOptions.outFile}"`); } } + if (!isMainConfig && tsConfig.prepend) { + U.userError(`${configFile}: "prepend" is supported only in tsconfig.json`); + } if (!fs.existsSync("node_modules/typescript")) { U.userError("Oops, typescript does not seem to be installed, did you run 'npm install'?"); } - pxt.log(`building ${p}...`) + pxt.log(`building ${isMainConfig ? p : configFile}...`) dirsToWatch.push(p) return nodeutil.spawnAsync({ cmd: "node", - args: [`../${isNodeModule ? "" : "node_modules/"}typescript/bin/tsc`], + args: [`../${isNodeModule ? "" : "node_modules/"}typescript/bin/tsc`, "-p", configName], cwd: p }).then(() => { + const outFile: string = tsConfig.compilerOptions.outFile; + const emitsDeclarations = !!tsConfig.compilerOptions.declaration; + const toDeclaration = (f: string) => f.replace(/\.js$/, ".d.ts"); if (tsConfig.prepend) { - let files: string[] = tsConfig.prepend - files.push(tsConfig.compilerOptions.outFile) - let s = "" - for (let f of files) { - s += fs.readFileSync(path.resolve(p, f), "utf8") + "\n" + const prepends: string[] = tsConfig.prepend; + concatFiles(prepends.concat([outFile]), outFile); + if (emitsDeclarations) { + const declarations = prepends + .filter(f => /\.js$/.test(f)) + .map(toDeclaration) + .filter(f => fs.existsSync(path.resolve(p, f))); + concatFiles(declarations.concat([toDeclaration(outFile)]), toDeclaration(outFile)); } - fs.writeFileSync(path.resolve(p, tsConfig.compilerOptions.outFile), s) } if (isNodeModule) { - const content = fs.readFileSync(path.resolve(p, tsConfig.compilerOptions.outFile), "utf8"); - fs.writeFileSync(path.resolve("built", path.basename(tsConfig.compilerOptions.outFile)), content); + const outputs = emitsDeclarations ? [outFile, toDeclaration(outFile)] : [outFile]; + for (const f of outputs) { + const content = fs.readFileSync(path.resolve(p, f), "utf8"); + fs.writeFileSync(path.resolve("built", path.basename(f)), content); + } } }) + + function concatFiles(sources: string[], dest: string) { + let s = "" + for (const f of sources) { + s += fs.readFileSync(path.resolve(p, f), "utf8") + "\n" + } + fs.writeFileSync(path.resolve(p, dest), s) + } } function copyCommonSim() { @@ -1748,6 +1778,10 @@ function copyCommonSim() { pxt.log(`copying common-sim...`) nodeutil.cp(path.join(p, "common-sim.js"), "built"); nodeutil.cp(path.join(p, "common-sim.d.ts"), "built"); + for (const f of ["common-simcore.js", "common-simcore.d.ts"]) { + if (fs.existsSync(path.join(p, f))) + nodeutil.cp(path.join(p, f), "built"); + } } } @@ -2614,12 +2648,30 @@ function updateColorThemes(cfg: pxt.TargetBundle) { } function rebundleAsync() { - return buildTargetCoreAsync({ quick: true }) - .then(() => buildSimAsync()); + return buildSimAsync() + .then(() => buildTargetCoreAsync({ quick: true })); +} + +/** + * Compiles the target's simulator. The sim folder is `sim/`, or `node_modules/pxt--sim/` + * when `sim/` has no tsconfig.json. The output goes to built/sim.js, plus built/simcore.js when the + * folder has a tsconfig.core.json. The common target builds built/common-sim.js and + * built/common-simcore.js instead. + */ +async function buildSimAsync() { + await buildSimFolderAsync(simDir(), pxt.appTarget.id === "common" ? "common-sim" : "sim"); } -function buildSimAsync() { - return buildFolderAsync(simDir(), true, pxt.appTarget.id === "common" ? "common-sim" : "sim"); +/** + * Compiles a sim folder's tsconfig.json into `../built/.js`. If the folder also has a + * tsconfig.core.json, that is compiled first, into the DOM-free `../built/core.js`. + * A missing config is skipped. An empty `dir` means the working directory, and only its + * tsconfig.json is built. + */ +async function buildSimFolderAsync(dir: string, outputName: string) { + if (dir) + await buildFolderAsync(dir, true, outputName + "core", "tsconfig.core.json"); + await buildFolderAsync(dir, true, outputName); } function compressApiInfo(inf: Map) { @@ -2692,6 +2744,10 @@ async function buildTargetCoreAsync(options: BuildTargetOptions = {}) { pxt.setAppTarget(cfg); pxt.reloadAppTargetVariant(); dirsToWatch = cfg.bundleddirs.slice() + dirsToWatch = dirsToWatch.concat( + cfg.bundleddirs + .map(d => path.join(d, "sim", "core")) + .filter(d => nodeutil.existsDirSync(d))); // library simulator core folders if (pxt.appTarget.id != "core") { if (fs.existsSync("theme")) { dirsToWatch.push("theme"); // simulator @@ -3063,7 +3119,7 @@ async function buildAndWatchTargetAsync(includeSourceMaps: boolean, rebundle: bo function buildCommonSimAsync() { const simPath = path.resolve("node_modules/pxt-common-packages/sim"); if (fs.existsSync(simPath)) { - return buildFolderAsync(simPath) + return buildSimFolderAsync(simPath, "common-sim") } else { return Promise.resolve(); @@ -4268,6 +4324,7 @@ function simulatorCoverage(pkgCompileRes: pxtc.CompileResult, pkgOpts: pxtc.Comp sf.statements.forEach(doStmt) } + const missing: string[] = [] for (let info of pkgOpts.extinfo.functions) { let shim = info.name if (pxtc.isBuiltinSimOp(shim)) @@ -4275,9 +4332,13 @@ function simulatorCoverage(pkgCompileRes: pxtc.CompileResult, pkgOpts: pxtc.Comp let simName = pxtc.shimToJs(shim) let sym = U.lookup(decls, simName) if (!sym) { - pxt.log("missing in sim: " + simName) + missing.push(simName) } } + if (missing.length) { + pxt.log(`${missing.length} target functions have no simulator implementation (run with -d to list them)`) + missing.forEach(simName => pxt.debug("missing in sim: " + simName)) + } /* let apiInfo = pxtc.getApiInfo(pkgCompileRes.ast) @@ -4364,7 +4425,9 @@ function simshimAsync() { pxt.debug("no sim/tsconfig.json; skipping") return Promise.resolve(); } - let prog = pxtc.plainTscCompileDir(path.resolve(simDir())) + // Don't report errors here. The shim scan only reads the //% annotations, and the + // simulator's own build reports any errors. + let prog = pxtc.plainTscCompileDir(path.resolve(simDir()), false) let shims = pxt.simshim(prog, path.parse) let filename = "sims.d.ts" for (const s of Object.keys(shims)) { diff --git a/pxtcompiler/emitter/plaintsc.ts b/pxtcompiler/emitter/plaintsc.ts index b5483c228373..5c78220db799 100644 --- a/pxtcompiler/emitter/plaintsc.ts +++ b/pxtcompiler/emitter/plaintsc.ts @@ -52,13 +52,19 @@ namespace ts.pxtc { return (a as any).file !== undefined; } - export function plainTscCompileDir(dir: string): Program { + /** + * Compiles the TypeScript project in `dir` with the bundled compiler and returns its program. + * Program diagnostics are written to the console unless `reportProgramDiagnostics` is false. + */ + export function plainTscCompileDir(dir: string, reportProgramDiagnostics = true): Program { const commandLine = parseCommandLine([]); let configFileName = findConfigFile(dir, sys.fileExists); const configParseResult = parseConfigFile(); let program = plainTscCompileFiles(configParseResult.fileNames, configParseResult.options) - let diagnostics = getProgramDiagnostics(program) - diagnostics.forEach(reportDiagnostic) + if (reportProgramDiagnostics) { + let diagnostics = getProgramDiagnostics(program) + diagnostics.forEach(reportDiagnostic) + } return program function parseConfigFile(): ParsedCommandLine { diff --git a/pxtsimcore/README.md b/pxtsimcore/README.md index ca83fec66617..9b42076e4142 100644 --- a/pxtsimcore/README.md +++ b/pxtsimcore/README.md @@ -125,3 +125,41 @@ stops sound on `kill`. A view implements `RuntimeBoardView`. The embed calls its the board's, and the program starts when both resolve. A view with breadboard parts passes its `builtinVisuals` and the board state to `visuals.BoardHost`, which pairs each part view with its state by simulation behavior. + +## Target core bundles + +A target ships a DOM-free bundle by adding `sim/tsconfig.core.json`, which compiles `sim/core/` to +`built/simcore.js` without the `dom` lib. `sim/tsconfig.json` then compiles only the view files and +prepends the core bundle. pxt-microbit's pair, trimmed: + +```jsonc +// sim/tsconfig.core.json -> built/simcore.js +{ + "compilerOptions": { "outFile": "../built/simcore.js", "declaration": true, + "lib": ["es2017"], "types": [] }, + "files": [ + "../node_modules/pxt-core/built/pxtsimcore.d.ts", + "../node_modules/pxt-core/built/pxtsimcore-globals.d.ts" + ], + "include": ["core/**/*.ts", "../node_modules/pxt-common-packages/libs/radio/sim/core/*.ts"] +} +// sim/tsconfig.json -> built/sim.js, which is simcore.js followed by the view code +{ + "compilerOptions": { "outFile": "../built/sim.js", "declaration": true, + "lib": ["dom", "es2017"] }, + "files": ["../node_modules/pxt-core/built/pxtsim.d.ts", "../built/simcore.d.ts"], + "include": ["visuals/**/*.ts", "../node_modules/pxt-common-packages/libs/core/sim/neopixel.ts"], + "prepend": ["../built/simcore.js"] +} +``` + +`prepend` is a pxt key, allowed only in `tsconfig.json`. pxt concatenates the listed files ahead of +the output, and their `.d.ts` files ahead of the declarations, so the browser loads `sim.js` as +before. `pxt buildtarget` and `pxt rebundle` build the core config first. A sim installed from npm +at `node_modules/pxt--sim` writes to its own `built/`, and pxt copies the outputs into the +target's `built/`. pxt-common-packages keeps each library's DOM-free files in `libs//sim/core/` +and builds `common-simcore.js` and `common-sim.js`, which `pxt buildtarget` copies the same way. + +To run in a browser, load `pxtsim.js` and `sim.js`. To run without a DOM, load `pxtsimcore.js` and +`simcore.js`. Never load both pairs: `pxtsim.js` already contains core. +