A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(editor): say what a Node built-in import actually means
yhh70b2f209c613
diff --git a/desktop/electron/buildScripts.ts b/desktop/electron/buildScripts.tsindex 8705c9acf..a95d6d239 100644--- a/desktop/electron/buildScripts.ts+++ b/desktop/electron/buildScripts.ts@@ -16,6 +16,7 @@ import type { BuildResult } from 'esbuild';import { existsSync } from 'node:fs';import path from 'node:path';import { loadEsbuild } from './esbuildRuntime';+import { explainBundleErrors, type BundleMessage } from './bundleDiagnostics';/** esengine and any subpath import are left for the realm's import map to resolve. */const EXTERNAL = ['esengine', 'esengine/*'];@@ -64,15 +65,15 @@ export async function buildProjectScripts(return {ok: true,outputPath,- errors: result.errors.map((e) => e.text),+ errors: explainBundleErrors(result.errors),warnings: result.warnings.map((w) => w.text),};} catch (err) {- const e = err as { errors?: { text: string }[]; warnings?: { text: string }[]; message?: string };+ const e = err as { errors?: BundleMessage[]; warnings?: { text: string }[]; message?: string };return {ok: false,outputPath: null,- errors: e.errors?.map((x) => x.text) ?? [String(e.message ?? err)],+ errors: e.errors ? explainBundleErrors(e.errors) : [String(e.message ?? err)],warnings: e.warnings?.map((x) => x.text) ?? [],};}diff --git a/desktop/electron/bundleDiagnostics.ts b/desktop/electron/bundleDiagnostics.tsnew file mode 100644index 000000000..b82414ef2--- /dev/null+++ b/desktop/electron/bundleDiagnostics.ts@@ -0,0 +1,82 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Turning a bundler's message into one someone can act on.+ *+ * A project's scripts are bundled with esbuild, and npm packages come+ * along — which works, until one of them reaches for a Node built-in.+ * What comes back then is:+ *+ * Could not resolve "crypto"+ *+ * Every word of that is true and none of it helps. It does not say that+ * the game runs in a browser or a mini-game host where there is no+ * `crypto` to resolve, it does not say which file asked for it (usually+ * not one the developer wrote), and it does not say what to do instead.+ * A developer who has just run `npm install` reads it as "the engine+ * cannot handle npm packages", which is the wrong conclusion.+ *+ * The built-in list comes from Node itself rather than a copy kept here:+ * a hand-maintained list is one that is wrong the first time Node adds a+ * module, and being wrong here means silently NOT explaining the error+ * the developer is actually looking at.+ *+ * Pure — the message in, a better message out — so the four bundling+ * paths (web/desktop, mini-game, playable, and the editor's Play realm)+ * can share it and the tests need no bundler.+ */+import { builtinModules } from 'node:module';++/** esbuild's `Message`, narrowed to what an explanation can use. */+export interface BundleMessage {+ text: string;+ location?: { file?: string } | null;+}++const BUILTINS = new Set(builtinModules);++/** `Could not resolve "x"` — esbuild's wording for a specifier it could not find. */+const UNRESOLVED = /^Could not resolve "([^"]+)"/;++/** Whether a specifier names a Node built-in, in either spelling. */+export function isNodeBuiltin(specifier: string): boolean {+ const bare = specifier.startsWith('node:') ? specifier.slice('node:'.length) : specifier;+ // Subpaths are real (`node:fs/promises`), and the root is what identifies it.+ return BUILTINS.has(bare) || BUILTINS.has(bare.split('/')[0] ?? '');+}++/**+ * esbuild's message, plus what to do about it — when there is something to say.+ *+ * Anything unrecognized passes through untouched. A wrong guess appended to a+ * real compile error costs more than the explanation is worth, so this only+ * speaks about the one case it can identify with certainty.+ */+export function explainBundleError(message: BundleMessage): string {+ const match = UNRESOLVED.exec(message.text);+ const specifier = match?.[1];+ if (!specifier || !isNodeBuiltin(specifier)) return message.text;++ const from = message.location?.file;+ // Where it came from decides the advice. Something under node_modules means a+ // dependency reached for it and the developer's own code is fine — the fix is+ // a different package or entry point, not a different import.+ const viaDependency = !!from && /(^|[\\/])node_modules[\\/]/.test(from);++ const where = from ? ` (imported by ${from})` : '';+ const why = `"${specifier}" is a Node built-in, and a game does not run in Node — `+ + 'the web build runs in a browser, and a mini-game host has neither Node nor the DOM.';+ const how = viaDependency+ ? 'This came from a dependency, so the fix is on the package rather than in your code: '+ + 'many publish a browser-safe entry point (protobufjs/minimal, for one), and some ship a '+ + '"browser" field npm and esbuild will pick automatically. If it has neither, it cannot be '+ + 'bundled into a game.'+ : 'Use a web API instead (crypto.subtle, fetch, localStorage), or the engine\'s own equivalent — '+ + 'Assets for files, Storage for saved data — all of which work on every target.';+ return `${message.text}${where}. ${why} ${how}`;+}++/** Map a batch of esbuild messages, explaining the ones that can be explained. */+export function explainBundleErrors(messages: readonly BundleMessage[]): string[] {+ return messages.map(explainBundleError);+}diff --git a/desktop/electron/exportGame.ts b/desktop/electron/exportGame.tsindex 83658f2a3..13d8d6c06 100644--- a/desktop/electron/exportGame.ts+++ b/desktop/electron/exportGame.ts@@ -36,6 +36,7 @@ import { exportPlayable } from './exportPlayable';import { genericPlayableProfile, type PlayableAdProfile } from './playableAdProfile';import type { OnExportProgress } from './exportProgress';import { ESENGINE_EXTERNAL } from './esengineResolve';+import { explainBundleErrors, type BundleMessage } from './bundleDiagnostics';import { orientationCss, orientationOverlayHtml, orientationLockScript, orientationLockCspHash, type ScreenOrientation } from './orientationHtml';import { emitIosXcodeProject, type IosProjectSources } from '../../build-tools/utils/iosProject.js';import { emitAndroidGradleProject } from '../../build-tools/utils/gradleProject.js';@@ -690,7 +691,7 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>if (!nativeContent) {progress({ phase: 'Bundling game host' });const host = await build({ ...common, entryPoints: [opts.gameHostEntry], outfile: path.join(payloadDir, 'game.js') });- errors.push(...host.errors.map((e) => e.text));+ errors.push(...explainBundleErrors(host.errors));}// 3. Project bundle (defineComponent/defineSystem). ESM + esengine external on// the web (the import map resolves it); on native an IIFE the host evals,@@ -704,11 +705,11 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>entryPoints: [scriptsAbs], outfile: path.join(payloadDir, 'scripts.js'),}): await build({ ...common, entryPoints: [scriptsAbs], outfile: path.join(payloadDir, 'scripts.mjs') });- errors.push(...proj.errors.map((e) => e.text));+ errors.push(...explainBundleErrors(proj.errors));}} catch (err) {- const e = err as { errors?: { text: string }[]; message?: string };- errors.push(...(e.errors?.map((x) => x.text) ?? [String(e.message ?? err)]));+ const e = err as { errors?: BundleMessage[]; message?: string };+ errors.push(...(e.errors ? explainBundleErrors(e.errors) : [String(e.message ?? err)]));return { ok: false, platform, outDir: absOut, included: cook.included.length, warnings, errors };}diff --git a/desktop/electron/exportMiniGame.ts b/desktop/electron/exportMiniGame.tsindex 82ee0d003..b4f03e965 100644--- a/desktop/electron/exportMiniGame.ts+++ b/desktop/electron/exportMiniGame.ts@@ -37,6 +37,7 @@ import { buildAddressableManifest } from './addressableManifest';import type { ExportScene } from './exportGame';import type { OnExportProgress } from './exportProgress';import { esengineAlias } from './esengineResolve';+import { explainBundleErrors, type BundleMessage } from './bundleDiagnostics';import {sceneUsesPhysics, sceneUsesVideo, sceneUsesDragonBones, detectSpineVersion, detectSpineVersionJson,spineModuleId, SIDE_MODULE_FILE,@@ -345,10 +346,10 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {logLevel: 'silent',write: true,});- errors.push(...res.errors.map((e) => e.text));+ errors.push(...explainBundleErrors(res.errors));} catch (err) {- const e = err as { errors?: { text: string }[]; message?: string };- errors.push(...(e.errors?.map((x) => x.text) ?? [String(e.message ?? err)]));+ const e = err as { errors?: BundleMessage[]; message?: string };+ errors.push(...(e.errors ? explainBundleErrors(e.errors) : [String(e.message ?? err)]));}// 4b. The open data context — a SECOND bundle, for a second JS runtime.@@ -387,10 +388,10 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {logLevel: 'silent',write: true,});- errors.push(...res.errors.map((e) => e.text));+ errors.push(...explainBundleErrors(res.errors));} catch (err) {- const e = err as { errors?: { text: string }[]; message?: string };- errors.push(...(e.errors?.map((x) => x.text) ?? [String(e.message ?? err)]));+ const e = err as { errors?: BundleMessage[]; message?: string };+ errors.push(...(e.errors ? explainBundleErrors(e.errors) : [String(e.message ?? err)]));}}diff --git a/desktop/electron/exportPlayable.ts b/desktop/electron/exportPlayable.tsindex 3a8321eb1..7accb774b 100644--- a/desktop/electron/exportPlayable.ts+++ b/desktop/electron/exportPlayable.ts@@ -23,6 +23,7 @@ import path from 'node:path';import { cookAssets } from './cookAssets';import type { OnExportProgress } from './exportProgress';import { esengineAlias } from './esengineResolve';+import { explainBundleErrors, type BundleMessage } from './bundleDiagnostics';import type { ScreenOrientation } from './orientationHtml';import { genericPlayableProfile, playableAdInjection, type PlayableAdProfile } from './playableAdProfile';import { makeZip } from '../../build-tools/utils/zip.js';@@ -274,11 +275,11 @@ export async function exportPlayable(opts: {outfile: 'game-bundle.js',logLevel: 'silent',});- errors.push(...res.errors.map((e) => e.text));+ errors.push(...explainBundleErrors(res.errors));bundle = res.outputFiles?.[0]?.text ?? '';} catch (err) {- const e = err as { errors?: { text: string }[]; message?: string };- errors.push(...(e.errors?.map((x) => x.text) ?? [String(e.message ?? err)]));+ const e = err as { errors?: BundleMessage[]; message?: string };+ errors.push(...(e.errors ? explainBundleErrors(e.errors) : [String(e.message ?? err)]));}// 5. Engine runtime: reuse the shipped WEB build (esengine.js glue + esengine.wasm),diff --git a/desktop/tests/bundle-diagnostics.test.ts b/desktop/tests/bundle-diagnostics.test.tsnew file mode 100644index 000000000..c6f5fddef--- /dev/null+++ b/desktop/tests/bundle-diagnostics.test.ts@@ -0,0 +1,94 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file `Could not resolve "crypto"` is true and useless.+ *+ * npm packages bundle into a game fine — until one reaches for a Node built-in,+ * and then the export fails with a bundler message that names no cause, no+ * culprit file and no fix. A developer who has just run `npm install` reads it+ * as "this engine cannot handle npm", which is the wrong conclusion and an+ * expensive one.+ *+ * The rule this file holds: explain the ONE case that can be identified with+ * certainty, and leave everything else exactly as the bundler said it. A guess+ * appended to a real compile error costs more than the explanation is worth.+ */+import { describe, it, expect } from 'vitest';+import { explainBundleError, explainBundleErrors, isNodeBuiltin } from '../electron/bundleDiagnostics';++describe('recognizing a Node built-in', () => {+ it('knows the built-ins in both spellings', () => {+ expect(isNodeBuiltin('crypto')).toBe(true);+ expect(isNodeBuiltin('node:crypto')).toBe(true);+ expect(isNodeBuiltin('fs/promises')).toBe(true);+ expect(isNodeBuiltin('node:fs/promises')).toBe(true);+ });++ it('does not mistake an npm package for one', () => {+ expect(isNodeBuiltin('protobufjs')).toBe(false);+ expect(isNodeBuiltin('protobufjs/minimal')).toBe(false);+ expect(isNodeBuiltin('./local-module')).toBe(false);+ });+});++describe('explaining', () => {+ it('says why, and points at web APIs when the import is the developer\'s own', () => {+ const said = explainBundleError({+ text: 'Could not resolve "crypto"',+ location: { file: 'src/net/sign.ts' },+ });+ expect(said).toContain('Could not resolve "crypto"'); // the original, kept+ expect(said).toContain('src/net/sign.ts'); // who asked+ expect(said).toContain('does not run in Node'); // why+ expect(said).toContain('crypto.subtle'); // what instead+ });++ it('points at the package when a dependency is the one reaching', () => {+ // The developer's own code is fine here — telling them to "use a web API+ // instead" would be advice about code they did not write.+ const said = explainBundleError({+ text: 'Could not resolve "fs"',+ location: { file: 'node_modules/some-lib/dist/index.js' },+ });+ expect(said).toContain('came from a dependency');+ expect(said).toContain('browser'); // the "browser" field / browser entry+ expect(said).not.toContain('crypto.subtle'); // not the own-code advice+ });++ it('recognizes a windows path under node_modules too', () => {+ const said = explainBundleError({+ text: 'Could not resolve "path"',+ location: { file: 'C:\\proj\\node_modules\\some-lib\\index.js' },+ });+ expect(said).toContain('came from a dependency');+ });++ it('still explains when the bundler named no file', () => {+ const said = explainBundleError({ text: 'Could not resolve "os"' });+ expect(said).toContain('is a Node built-in');+ expect(said).not.toContain('imported by');+ });+});++describe('leaving well enough alone', () => {+ it('passes through an unresolved npm package untouched', () => {+ // A missing dependency is a different problem with a different fix+ // (`npm install`), and this has nothing to add to it.+ const text = 'Could not resolve "protobufjs"';+ expect(explainBundleError({ text })).toBe(text);+ });++ it('passes through an ordinary compile error untouched', () => {+ const text = 'Expected ";" but found "}"';+ expect(explainBundleError({ text, location: { file: 'src/main.ts' } })).toBe(text);+ });++ it('maps a batch, explaining only what it can', () => {+ const out = explainBundleErrors([+ { text: 'Could not resolve "fs"' },+ { text: 'Expected ";" but found "}"' },+ ]);+ expect(out[0]).toContain('Node built-in');+ expect(out[1]).toBe('Expected ";" but found "}"');+ });+});