mini-three-adapter 0.1.5 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/AGENTS.md +1 -1
  2. package/README.md +1 -1
  3. package/dist/build/rollup.d.ts +2 -2
  4. package/dist/build/rollup.js.map +1 -1
  5. package/dist/build/vite.d.ts +2 -2
  6. package/dist/build/vite.js.map +1 -1
  7. package/dist/{chunk-F7CSLEUI.js → chunk-7XOHQFZ6.js} +43 -4
  8. package/dist/chunk-7XOHQFZ6.js.map +1 -0
  9. package/dist/{chunk-LE4FRYNG.js → chunk-DDCQIBWW.js} +4 -4
  10. package/dist/{chunk-LE4FRYNG.js.map → chunk-DDCQIBWW.js.map} +1 -1
  11. package/dist/{chunk-ZB3AYNOS.js → chunk-FQ2GOIOE.js} +4 -4
  12. package/dist/{chunk-ZB3AYNOS.js.map → chunk-FQ2GOIOE.js.map} +1 -1
  13. package/dist/{chunk-VA7SZFLN.js → chunk-HKT54DDM.js} +3 -3
  14. package/dist/{chunk-VA7SZFLN.js.map → chunk-HKT54DDM.js.map} +1 -1
  15. package/dist/{chunk-LCJNTN6F.js → chunk-U3P3XHA3.js} +8 -5
  16. package/dist/chunk-U3P3XHA3.js.map +1 -0
  17. package/dist/{chunk-ZFJLEEF4.js → chunk-V64V4HIZ.js} +111 -58
  18. package/dist/chunk-V64V4HIZ.js.map +1 -0
  19. package/dist/core/index.d.ts +9 -3
  20. package/dist/core/index.js +2 -2
  21. package/dist/index.d.ts +2 -2
  22. package/dist/index.js +6 -6
  23. package/dist/platforms/browser.d.ts +2 -2
  24. package/dist/platforms/browser.js +3 -3
  25. package/dist/platforms/wechat-game.d.ts +2 -2
  26. package/dist/platforms/wechat-game.js +4 -4
  27. package/dist/platforms/wechat-miniprogram.d.ts +2 -2
  28. package/dist/platforms/wechat-miniprogram.js +4 -4
  29. package/dist/{plugin-core-BuqW9C-L.d.ts → plugin-core-CBOr1cyv.d.ts} +15 -4
  30. package/dist/polyfills/index.d.ts +1 -1
  31. package/dist/polyfills/index.js +1 -1
  32. package/dist/{runtime-BrHExTjl.d.ts → runtime-C8_xIlDM.d.ts} +29 -1
  33. package/dist/scope.d.ts +1 -1
  34. package/dist/{types-X_5SJh4y.d.ts → types-DOoJ7noL.d.ts} +13 -1
  35. package/docs/03-module-map.md +7 -7
  36. package/docs/04-api-reference.md +12 -6
  37. package/docs/06-platform-notes.md +15 -1
  38. package/docs/07-integration-guide.md +2 -1
  39. package/docs/09-testing-and-release.md +5 -3
  40. package/docs/11-compat-matrix.md +3 -3
  41. package/docs/adr/0010-native-event-target-boundary.md +82 -0
  42. package/docs/adr/README.md +1 -0
  43. package/package.json +3 -2
  44. package/dist/chunk-F7CSLEUI.js.map +0 -1
  45. package/dist/chunk-LCJNTN6F.js.map +0 -1
  46. package/dist/chunk-ZFJLEEF4.js.map +0 -1
package/AGENTS.md CHANGED
@@ -21,7 +21,7 @@
21
21
 
22
22
  ```bash
23
23
  npm run typecheck # tsc --noEmit, strict + noUncheckedIndexedAccess
24
- npm test # vitest run(单 fork,79 例)
24
+ npm test # vitest run(单 fork,95 例)
25
25
  npm run build # tsup → dist/*.js + *.d.ts
26
26
  npm run check # 以上全部
27
27
  ```
package/README.md CHANGED
@@ -149,7 +149,7 @@ export function startScene(runtime: MiniThreeRuntime) {
149
149
  ```bash
150
150
  npm install
151
151
  npm run typecheck # tsc --noEmit
152
- npm test # vitest run (79 tests)
152
+ npm test # vitest run (82 tests)
153
153
  npm run build # tsup: dist/*.js + dist/*.d.ts
154
154
  npm run check # 以上三项
155
155
  ```
@@ -1,5 +1,5 @@
1
- import { M as MiniThreePluginOptions, a as MiniThreePlugin } from '../plugin-core-BuqW9C-L.js';
2
- export { A as AssetEntry, b as AssetManifest, c as AssetOptions, B as BuildReport, D as DEFAULT_FORCE_UNDEF, d as DEFAULT_GLOBAL_NAMES, R as RewriteOptions, e as RewriteResult, f as collectAssetReferences, g as collectAssets, h as copyAssets, m as miniThreePlugin, r as rewriteGlobals } from '../plugin-core-BuqW9C-L.js';
1
+ import { M as MiniThreePluginOptions, a as MiniThreePlugin } from '../plugin-core-CBOr1cyv.js';
2
+ export { A as AssetEntry, b as AssetManifest, c as AssetOptions, B as BuildReport, D as DEFAULT_FORCE_UNDEF, d as DEFAULT_GLOBAL_NAMES, R as RewriteOptions, e as RewriteResult, f as collectAssetReferences, g as collectAssets, h as copyAssets, m as miniThreePlugin, r as rewriteGlobals } from '../plugin-core-CBOr1cyv.js';
3
3
 
4
4
  /** Rollup entry: `import { miniThree } from 'mini-three-adapter/rollup'`. */
5
5
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/build/plugin-core.ts","../../src/build/scope-rewrite.ts","../../src/build/assets.ts","../../src/build/rollup.ts"],"sourcesContent":["/**\n * Rollup/Vite-compatible plugin core (zero hard dependency on either bundler).\n *\n * Responsibilities:\n * 1. Rewrite free browser globals inside third-party modules to scoped access.\n * 2. Handle `three/webgpu` (WebGPU is unavailable in WeChat mini games).\n * 3. Collect worker/wasm assets referenced by addons and emit them + a manifest.\n * 4. Produce a machine-readable build report for CI and AI-assisted iteration.\n */\nimport { promises as fs } from 'node:fs';\nimport {\n DEFAULT_FORCE_UNDEF,\n rewriteGlobals,\n type RewriteOptions,\n} from './scope-rewrite';\nimport {\n collectAssetReferences,\n collectAssets,\n type AssetManifest,\n type AssetOptions,\n} from './assets';\n\nexport interface MiniThreePluginOptions extends AssetOptions {\n /** Extra modules to transform. Receives a normalized (slash-separated) id. */\n include?: (id: string) => boolean;\n /** Modules to skip even when they match. */\n exclude?: (id: string) => boolean;\n /** Also transform application code (off by default). */\n includeUserCode?: boolean;\n /** Rewrite options (advanced). */\n rewrite?: RewriteOptions;\n /** How to handle `three/webgpu` imports. Default 'warn'. */\n webgpu?: 'warn' | 'error' | 'rewrite' | 'ignore';\n /** Print a build report summary. Default true. */\n report?: boolean;\n /** Verbose per-module logs. */\n debug?: boolean;\n}\n\nexport interface BuildReport {\n modulesScanned: number;\n modulesRewritten: number;\n rewrites: number;\n globalsSeen: string[];\n assetReferences: string[];\n missingAssets: string[];\n webgpuWarnings: string[];\n parseFailures: string[];\n}\n\nexport interface PluginContext {\n warn(message: string): void;\n error(message: string): never;\n emitFile(file: { type: 'asset'; fileName: string; source: string | Uint8Array }): string;\n}\n\nexport interface MiniThreePlugin {\n name: string;\n enforce: 'pre';\n transform(this: PluginContext, code: string, id: string): { code: string; map: unknown } | null;\n generateBundle(this: PluginContext, options: { dir?: string; file?: string }): Promise<void>;\n api: {\n report(): BuildReport;\n };\n}\n\nconst DEFAULT_INCLUDE = (id: string): boolean => {\n const normalized = id.replace(/\\\\/g, '/').split('?')[0] ?? id;\n return (\n normalized.includes('/node_modules/three/') ||\n normalized.includes('/node_modules/three-stdlib/') ||\n normalized.includes('/node_modules/@react-three/') ||\n normalized.includes('/node_modules/@tresjs/') ||\n normalized.includes('/node_modules/.vite/deps/three') ||\n normalized.includes('/node_modules/.vite/deps/three-stdlib') ||\n /\\/node_modules\\/three@[^/]+\\//.test(normalized)\n );\n};\n\nexport function miniThreePlugin(options: MiniThreePluginOptions = {}): MiniThreePlugin {\n const include = options.include ?? DEFAULT_INCLUDE;\n const exclude = options.exclude ?? (() => false);\n const webgpuMode = options.webgpu ?? 'warn';\n const report: BuildReport = {\n modulesScanned: 0,\n modulesRewritten: 0,\n rewrites: 0,\n globalsSeen: [],\n assetReferences: [],\n missingAssets: [],\n webgpuWarnings: [],\n parseFailures: [],\n };\n const seenGlobals = new Set<string>();\n const assetRefs = new Set<string>();\n let manifest: AssetManifest | null = null;\n let filesToEmit = new Map<string, string>();\n\n const note = (ctx: PluginContext, message: string): void => {\n if (options.debug) ctx.warn(`[mini-three] ${message}`);\n };\n\n return {\n name: 'mini-three-adapter',\n enforce: 'pre',\n\n transform(this: PluginContext, code: string, id: string) {\n const normalized = id.replace(/\\\\/g, '/');\n const shouldTransform = options.includeUserCode\n ? !normalized.includes('/node_modules/mini-three-adapter/') && !exclude(normalized)\n : include(normalized) && !exclude(normalized);\n if (!shouldTransform) return null;\n\n report.modulesScanned++;\n for (const ref of collectAssetReferences(code)) assetRefs.add(ref);\n\n let currentCode = code;\n if (webgpuMode !== 'ignore' && /from\\s*['\"`]three\\/webgpu['\"`]/.test(code)) {\n const message = `[mini-three] ${normalized} imports 'three/webgpu'; WebGPU is not available in WeChat mini games.`;\n report.webgpuWarnings.push(message);\n if (webgpuMode === 'error') this.error(message);\n if (webgpuMode === 'warn') this.warn(`${message} Use three's WebGLRenderer instead.`);\n if (webgpuMode === 'rewrite') {\n currentCode = currentCode\n .replace(/(['\"`])three\\/webgpu\\1/g, '$1three$1')\n .replace(/\\bWebGPURenderer\\b/g, 'WebGLRenderer');\n note(this, `rewrote three/webgpu -> three in ${normalized}`);\n }\n }\n\n const result = rewriteGlobals(currentCode, normalized, {\n ...options.rewrite,\n ...(options.rewrite?.forceUndef ? {} : { forceUndef: [...DEFAULT_FORCE_UNDEF] }),\n });\n if (result && 'error' in result) {\n report.parseFailures.push(result.error);\n this.warn(`[mini-three] ${result.error}`);\n return null;\n }\n if (!result) return webgpuMode === 'rewrite' ? { code: currentCode, map: null } : null;\n\n report.modulesRewritten++;\n report.rewrites += result.count;\n for (const name of result.seen) seenGlobals.add(name);\n note(this, `${normalized}: ${result.count} global(s) rewritten (${result.seen.join(', ')})`);\n return { code: result.code, map: result.map };\n },\n\n async generateBundle(this: PluginContext, bundleOptions) {\n const refs = Array.from(assetRefs);\n report.assetReferences = refs;\n report.globalsSeen = Array.from(seenGlobals).sort();\n\n if (refs.length > 0) {\n const collected = await collectAssets(refs, {\n cwd: options.cwd,\n roots: options.roots,\n outputDir: options.outputDir,\n brotli: options.brotli,\n manifest: options.manifest,\n });\n manifest = collected.manifest;\n filesToEmit = collected.files;\n report.missingAssets = collected.missing;\n for (const missing of collected.missing) {\n this.warn(`[mini-three] asset not found in known roots: ${missing}`);\n }\n for (const [destination, source] of filesToEmit) {\n try {\n const content = await fs.readFile(source);\n this.emitFile({ type: 'asset', fileName: destination, source: content });\n } catch (error) {\n this.warn(`[mini-three] could not emit ${destination}: ${String(error)}`);\n }\n }\n } else {\n manifest = {\n generatedBy: 'mini-three-adapter',\n outputDir: options.outputDir ?? 'assets/three',\n entries: [],\n gameJsonSuggestion: {},\n decoderPaths: {},\n };\n }\n\n if (options.manifest !== false) {\n this.emitFile({\n type: 'asset',\n fileName: 'mini-three-assets.json',\n source: JSON.stringify({ ...manifest, build: report, output: bundleOptions.dir ?? bundleOptions.file ?? '' }, null, 2),\n });\n }\n if (options.report !== false) {\n this.warn(\n `[mini-three] build report: ${report.modulesScanned} module(s) scanned, ` +\n `${report.modulesRewritten} rewritten, ${report.rewrites} reference(s) -> scope, ` +\n `${filesToEmit.size} asset(s) emitted, ${report.missingAssets.length} missing.`,\n );\n }\n },\n\n api: {\n report: () => ({\n ...report,\n globalsSeen: Array.from(seenGlobals).sort(),\n assetReferences: Array.from(assetRefs),\n webgpuWarnings: [...report.webgpuWarnings],\n parseFailures: [...report.parseFailures],\n }),\n },\n };\n}\n","/**\n * AST-based global-to-scope rewriting.\n *\n * The reference adapter uses a Rollup \"prefix global\" pass that effectively\n * text-replaces identifiers. That breaks on shadowed locals, object keys, and\n * `typeof window` feature detection. Here we parse with @babel/parser and use\n * Babel's scope binding information, so ONLY free (unbound) references to\n * browser globals are rewritten — application code is never touched.\n */\nimport { parse } from '@babel/parser';\nimport _traverse from '@babel/traverse';\nimport MagicString from 'magic-string';\nimport type { NodePath } from '@babel/traverse';\nimport type { Identifier } from '@babel/types';\nimport type { Node } from '@babel/types';\n\n// Babel's CJS/ESM interop differs between bundlers; normalize once.\nconst traverse = (typeof _traverse === 'function'\n ? _traverse\n : (_traverse as unknown as { default: typeof _traverse }).default) as typeof _traverse;\n\nexport const DEFAULT_GLOBAL_NAMES: readonly string[] = [\n 'window', 'self', 'document', 'navigator', 'screen', 'location',\n 'innerWidth', 'innerHeight', 'outerWidth', 'outerHeight',\n 'devicePixelRatio', 'pageXOffset', 'pageYOffset',\n 'performance', 'requestAnimationFrame', 'cancelAnimationFrame',\n 'getComputedStyle', 'matchMedia', 'atob', 'btoa',\n 'Event', 'EventTarget', 'CustomEvent', 'PointerEvent', 'MouseEvent',\n 'TouchEvent', 'MessageEvent', 'ProgressEvent', 'KeyboardEvent', 'DOMException',\n 'HTMLElement', 'HTMLCanvasElement', 'HTMLImageElement', 'HTMLVideoElement',\n 'OffscreenCanvas', 'Image', 'ImageData', 'DOMRect',\n 'WebGLRenderingContext', 'WebGL2RenderingContext', 'AudioContext',\n 'Blob', 'URL', 'URLSearchParams', 'FileReader', 'TextDecoder', 'TextEncoder',\n 'AbortController', 'AbortSignal', 'fetch', 'XMLHttpRequest', 'WebSocket',\n 'createImageBitmap', 'Worker', 'WebAssembly', 'ResizeObserver',\n];\n\n/** Globals that must remain `undefined` in the mini game scope. */\nexport const DEFAULT_FORCE_UNDEF: readonly string[] = ['createImageBitmap'];\n\nexport interface RewriteOptions {\n /** Extra global identifiers to rewrite. */\n extraGlobals?: string[];\n /** Replace the default global list instead of extending it. */\n globals?: string[];\n /** Identifiers that must evaluate to `undefined` (feature-detection off). */\n forceUndef?: string[];\n /** Name of the injected scope accessor. Default `__m3`. */\n accessor?: string;\n /** Module specifier that exports `getActiveScope`. */\n scopeModule?: string;\n}\n\nexport interface RewriteResult {\n code: string;\n map: { toString(): string } | null;\n /** Number of rewritten references. */\n count: number;\n /** Globals actually seen (useful for the build report). */\n seen: string[];\n}\n\nexport interface RewriteFailure {\n code: string;\n error: string;\n}\n\nexport const SCOPE_IMPORT = (\n accessor: string,\n module: string,\n extraSpecifiers: readonly string[] = [],\n): string => {\n const specifiers = [`getActiveScope as ${accessor}`, ...extraSpecifiers].join(', ');\n return `import { ${specifiers} } from '${module}';\\n`;\n};\n\n/**\n * Reference or range equality. `@babel/parser` emits TWO distinct `Identifier`\n * nodes with identical `[start, end]` for a shorthand property (`{ X }`: one for\n * `key`, one for `value`), so reference equality alone is not enough to tell\n * \"this identifier is an object key\".\n */\nfunction sameNode(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n const x = a as { start?: number | null; end?: number | null } | null | undefined;\n const y = b as { start?: number | null; end?: number | null } | null | undefined;\n return Boolean(x && y && x.start != null && x.start === y.start && x.end === y.end);\n}\n\nfunction isNonComputedKey(path: NodePath): boolean {\n const parent = path.parentPath;\n if (!parent) return false;\n const self: unknown = path.node;\n if (parent.isObjectProperty() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\n if (parent.isObjectMethod() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\n if (parent.isClassProperty() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\n if (parent.isClassMethod() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\n if (parent.isMemberExpression() && !parent.node.computed && sameNode(parent.node.property, self)) return true;\n return false;\n}\n\n/**\n * `{ X }`: the value node shares its range with the key, so it cannot be\n * rewritten in place — it must be expanded to `{ X: <expr> }`.\n */\nfunction isShorthandValue(path: NodePath): boolean {\n const parent = path.parentPath;\n if (!parent?.isObjectProperty()) return false;\n if (!parent.node.shorthand || parent.node.computed) return false;\n if (parent.node.value !== path.node) return false;\n // `const { X } = obj` destructures a binding, never a global reference. Babel\n // already treats it as a binding, this guard keeps the two paths disjoint.\n return !parent.parentPath?.isObjectPattern();\n}\n\n/**\n * Is this identifier the left-most link of a `new X` / `new X.Y.Z` callee chain?\n *\n * `new f().g()` parses as `(new f()).g()`, so rewriting `X` to a *call*\n * (`__m3().X`) without parentheses silently turns `new X()` into\n * `(new __m3()).X()` — the scope object gets constructed and the class is then\n * invoked as a plain function. Wrapping only the chain root is enough:\n * `new (a().b).c` parses as `new ((a().b).c)`.\n */\nfunction isNewCalleeRoot(path: NodePath): boolean {\n let cur: NodePath = path;\n let parent = cur.parentPath;\n while (parent?.isMemberExpression() && parent.node.object === cur.node) {\n cur = parent;\n parent = parent.parentPath;\n }\n return Boolean(parent?.isNewExpression() && parent.node.callee === cur.node);\n}\n\n/** `typeof X` must never throw: `typeof a.b` is legal even when `a` is unbound. */\nfunction isDirectTypeofOperand(path: NodePath): boolean {\n const parent = path.parentPath;\n return Boolean(\n parent?.isUnaryExpression() &&\n parent.node.operator === 'typeof' &&\n parent.node.argument === path.node,\n );\n}\n\n/**\n * Globals that `getActiveScope()` resolves to itself even before a runtime\n * exists, so `typeof window` is already `'object'` and needs no guard.\n */\nconst ALWAYS_OBJECT_GLOBALS: ReadonlySet<string> = new Set(['window', 'self', 'globalThis']);\n\n/** Rewrite free browser-global references in one module. Returns null if nothing changed. */\nexport function rewriteGlobals(\n code: string,\n id: string,\n options: RewriteOptions = {},\n): RewriteResult | RewriteFailure | null {\n const names = new Set<string>([\n ...(options.globals ?? DEFAULT_GLOBAL_NAMES),\n ...(options.extraGlobals ?? []),\n ...(options.forceUndef ?? DEFAULT_FORCE_UNDEF),\n ]);\n const accessor = options.accessor ?? '__m3';\n const scopeModule = options.scopeModule ?? 'mini-three-adapter/scope';\n\n let ast;\n try {\n ast = parse(code, {\n sourceType: 'unambiguous',\n errorRecovery: true,\n plugins: ['importAttributes', 'classProperties', 'topLevelAwait', 'typescript', 'jsx'],\n });\n } catch (error) {\n return { code, error: `[mini-three] parse failed for ${id}: ${String(error)}` };\n }\n\n const ms = new MagicString(code);\n const seen = new Set<string>();\n const hasAccessor = `${accessor}Has`;\n let count = 0;\n let needsHasGuard = false;\n\n traverse(ast, {\n ReferencedIdentifier(path: NodePath<Node>) {\n const node = path.node as Identifier;\n const name = node.name;\n if (!name || !names.has(name)) return;\n if (node.start == null || node.end == null) return;\n // Babel scope knows about imports, function params, local declarations,\n // catch bindings and block-scoped shadowing. This is the critical check\n // that a regex-based replacement cannot perform.\n if (path.scope.hasBinding(name, true)) return;\n\n const ref = `${accessor}().${name}`;\n\n // 1) Shorthand must be handled before the key check: once `isNonComputedKey`\n // compares ranges, `{ X }`'s value looks like a key too and would be\n // silently skipped (leaving an undefined global behind).\n if (isShorthandValue(path)) {\n seen.add(name);\n ms.overwrite(node.start, node.end, `${name}: (${ref})`);\n count++;\n return;\n }\n\n // 2) Object keys / member property names are not references.\n if (isNonComputedKey(path)) return;\n\n seen.add(name);\n if (isDirectTypeofOperand(path) && !ALWAYS_OBJECT_GLOBALS.has(name)) {\n // `typeof X` must never throw. The placeholder scope answers the\n // environment globals (document/navigator/screen/...) with `undefined`\n // already, but everything else — TextDecoder, HTMLCanvasElement,\n // Blob, ... — throws an actionable error on access, and a `typeof`\n // probe must not become that error.\n ms.overwrite(node.start, node.end, `(${hasAccessor}() ? ${ref} : undefined)`);\n needsHasGuard = true;\n count++;\n return;\n }\n ms.overwrite(node.start, node.end, isNewCalleeRoot(path) ? `(${ref})` : ref);\n count++;\n },\n });\n\n if (count === 0) return null;\n ms.prepend(SCOPE_IMPORT(\n accessor,\n scopeModule,\n needsHasGuard ? [`hasActiveScope as ${hasAccessor}`] : [],\n ));\n return {\n code: ms.toString(),\n map: ms.generateMap({ source: id, includeContent: true, hires: true }) as unknown as { toString(): string },\n count,\n seen: Array.from(seen).sort(),\n };\n}\n","/**\n * Worker / WASM asset collection for three.js addons.\n *\n * DRACOLoader, KTX2Loader, 3DMLoader, LottieLoader, ... reference decoder\n * `.js` and `.wasm` files by string path. In a mini game those files are not\n * reachable via HTTP; they must be copied into the code package (ideally a\n * subpackage) and `setDecoderPath` must point at the copied location.\n *\n * The plugin scans transformed modules, resolves each referenced basename in a\n * small set of known directories, copies it, and emits a manifest plus a\n * `game.json` suggestion. No global state, no hidden writes.\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\n\nexport interface AssetOptions {\n /** Extra directories to search (besides three's jsm/libs). */\n roots?: string[];\n /** Output directory relative to the bundle root. Default 'assets/three'. */\n outputDir?: string;\n /** Copy `.wasm.br` alongside `.wasm` when available. Default true. */\n brotli?: boolean;\n /** Emit `mini-three-assets.json`. Default true. */\n manifest?: boolean;\n /** Working directory used to resolve roots. Default process.cwd(). */\n cwd?: string;\n}\n\nexport interface AssetEntry {\n /** Original string found in the module. */\n reference: string;\n /** Resolved absolute source path. */\n source: string;\n /** Relative destination inside the bundle. */\n destination: string;\n kind: 'worker' | 'wasm' | 'data';\n}\n\nexport interface AssetManifest {\n generatedBy: 'mini-three-adapter';\n outputDir: string;\n entries: AssetEntry[];\n /** Paste into game.json (adjust subpackage names to your project). */\n gameJsonSuggestion: Record<string, unknown>;\n /** Decoder paths to feed to loaders at runtime. */\n decoderPaths: Record<string, string>;\n}\n\nconst ASSET_PATTERN = /(['\"`])([^'\"`\\n]*\\.(?:wasm|wasm\\.br|bin|js))\\1/g;\nconst DECODER_KEYWORDS = [\n 'draco', 'basis', 'ktx2', 'rhino3dm', 'zstd', 'meshopt', 'ammo',\n 'worker', 'decoder', 'transcoder', 'lottie', 'sdf',\n];\n\nexport function collectAssetReferences(code: string): string[] {\n const found = new Set<string>();\n let match: RegExpExecArray | null;\n ASSET_PATTERN.lastIndex = 0;\n while ((match = ASSET_PATTERN.exec(code)) !== null) {\n const value = match[2] ?? '';\n const lower = value.toLowerCase();\n if (DECODER_KEYWORDS.some((keyword) => lower.includes(keyword))) found.add(value);\n }\n return Array.from(found);\n}\n\nasync function indexFiles(root: string, maxDepth = 5): Promise<Map<string, string>> {\n const index = new Map<string, string>();\n const walk = async (dir: string, depth: number): Promise<void> => {\n if (depth > maxDepth) return;\n let entries;\n try { entries = await fs.readdir(dir, { withFileTypes: true }); }\n catch { return; }\n for (const entry of entries) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) await walk(full, depth + 1);\n else if (entry.isFile() && !index.has(entry.name)) index.set(entry.name, full);\n }\n };\n await walk(root, 0);\n return index;\n}\n\nfunction classify(name: string): AssetEntry['kind'] {\n if (name.endsWith('.wasm') || name.endsWith('.wasm.br')) return 'wasm';\n if (name.endsWith('.js')) return 'worker';\n return 'data';\n}\n\nexport function defaultRoots(cwd: string): string[] {\n return [\n path.join(cwd, 'node_modules/three/examples/jsm/libs'),\n path.join(cwd, 'node_modules/three/examples/jsm'),\n path.join(cwd, 'node_modules/three-stdlib'),\n path.join(cwd, 'public'),\n path.join(cwd, 'static'),\n ];\n}\n\nexport interface CollectResult {\n manifest: AssetManifest;\n /** Files to write: destination (relative) -> absolute source. */\n files: Map<string, string>;\n missing: string[];\n}\n\n/** Resolve references against known roots without copying anything. */\nexport async function collectAssets(references: string[], options: AssetOptions = {}): Promise<CollectResult> {\n const cwd = options.cwd ?? process.cwd();\n const outputDir = (options.outputDir ?? 'assets/three').replace(/\\\\/g, '/').replace(/\\/$/, '');\n const roots = [...defaultRoots(cwd), ...(options.roots ?? [])];\n const indexes = await Promise.all(roots.map((root) => indexFiles(root)));\n const find = (name: string): string | undefined => {\n for (const index of indexes) {\n const hit = index.get(name);\n if (hit) return hit;\n }\n return undefined;\n };\n\n const entries: AssetEntry[] = [];\n const files = new Map<string, string>();\n const missing: string[] = [];\n\n for (const reference of references) {\n const base = path.posix.basename(reference.split('?')[0] ?? reference);\n const source = find(base);\n if (!source) { missing.push(reference); continue; }\n const entry: AssetEntry = {\n reference,\n source,\n destination: `${outputDir}/${base}`,\n kind: classify(base),\n };\n entries.push(entry);\n files.set(entry.destination, source);\n if (options.brotli !== false && entry.kind === 'wasm') {\n const br = find(`${base}.br`);\n if (br) {\n entries.push({ reference: `${reference}.br`, source: br, destination: `${outputDir}/${base}.br`, kind: 'wasm' });\n files.set(`${outputDir}/${base}.br`, br);\n }\n }\n }\n\n const decoderPaths: Record<string, string> = {};\n for (const entry of entries) {\n const name = path.posix.basename(entry.destination).toLowerCase();\n for (const key of ['draco', 'ktx2', 'basis', 'meshopt', 'rhino3dm', 'zstd', 'ammo']) {\n if (name.includes(key)) decoderPaths[key] = `${outputDir}/`;\n }\n }\n\n const manifest: AssetManifest = {\n generatedBy: 'mini-three-adapter',\n outputDir,\n entries,\n gameJsonSuggestion: {\n workers: { path: `${outputDir}`, isSubpackage: true },\n subpackages: [{ name: 'three-assets', root: `${outputDir}/` }],\n },\n decoderPaths,\n };\n return { manifest, files, missing };\n}\n\n/** Copy resolved files into `outDir`. */\nexport async function copyAssets(files: Map<string, string>, outDir: string): Promise<number> {\n let written = 0;\n for (const [destination, source] of files) {\n const target = path.join(outDir, destination);\n await fs.mkdir(path.dirname(target), { recursive: true });\n await fs.copyFile(source, target);\n written++;\n }\n return written;\n}\n","/** Rollup entry: `import { miniThree } from 'mini-three-adapter/rollup'`. */\nimport { miniThreePlugin, type MiniThreePlugin, type MiniThreePluginOptions } from './plugin-core';\n\nexport function miniThree(options: MiniThreePluginOptions = {}): MiniThreePlugin {\n return miniThreePlugin(options);\n}\n\nexport default miniThree;\nexport { miniThreePlugin } from './plugin-core';\nexport type { MiniThreePluginOptions, BuildReport } from './plugin-core';\nexport { DEFAULT_GLOBAL_NAMES, DEFAULT_FORCE_UNDEF, rewriteGlobals } from './scope-rewrite';\nexport type { RewriteOptions, RewriteResult } from './scope-rewrite';\nexport { collectAssetReferences, collectAssets, copyAssets } from './assets';\nexport type { AssetOptions, AssetManifest, AssetEntry } from './assets';\n"],"mappings":";AASA,SAAS,YAAYA,WAAU;;;ACA/B,SAAS,aAAa;AACtB,OAAO,eAAe;AACtB,OAAO,iBAAiB;AAMxB,IAAM,WAAY,OAAO,cAAc,aACnC,YACC,UAAuD;AAErD,IAAM,uBAA0C;AAAA,EACrD;AAAA,EAAU;AAAA,EAAQ;AAAA,EAAY;AAAA,EAAa;AAAA,EAAU;AAAA,EACrD;AAAA,EAAc;AAAA,EAAe;AAAA,EAAc;AAAA,EAC3C;AAAA,EAAoB;AAAA,EAAe;AAAA,EACnC;AAAA,EAAe;AAAA,EAAyB;AAAA,EACxC;AAAA,EAAoB;AAAA,EAAc;AAAA,EAAQ;AAAA,EAC1C;AAAA,EAAS;AAAA,EAAe;AAAA,EAAe;AAAA,EAAgB;AAAA,EACvD;AAAA,EAAc;AAAA,EAAgB;AAAA,EAAiB;AAAA,EAAiB;AAAA,EAChE;AAAA,EAAe;AAAA,EAAqB;AAAA,EAAoB;AAAA,EACxD;AAAA,EAAmB;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AAgB,eAAe,OAAO,QAAQ,2BACrD,YAAY,IAAI,sBAAsB,OAAO,cAAc,MAAM;AAAA,QACxE;AAAA,MACF;AAAA,IACF;AAAA,IAEA,KAAK;AAAA,MACH,QAAQ,OAAO;AAAA,QACb,GAAG;AAAA,QACH,aAAa,MAAM,KAAK,WAAW,EAAE,KAAK;AAAA,QAC1C,iBAAiB,MAAM,KAAK,SAAS;AAAA,QACrC,gBAAgB,CAAC,GAAG,OAAO,cAAc;AAAA,QACzC,eAAe,CAAC,GAAG,OAAO,aAAa;AAAA,MACzC;AAAA,IACF;AAAA,EACF;AACF;;;AGhNO,SAAS,UAAU,UAAkC,CAAC,GAAoB;AAC/E,SAAO,gBAAgB,OAAO;AAChC;AAEA,IAAO,iBAAQ;","names":["fs","path","fs"]}
1
+ {"version":3,"sources":["../../src/build/plugin-core.ts","../../src/build/scope-rewrite.ts","../../src/build/assets.ts","../../src/build/rollup.ts"],"sourcesContent":["/**\n * Rollup/Vite-compatible plugin core (zero hard dependency on either bundler).\n *\n * Responsibilities:\n * 1. Rewrite free browser globals inside third-party modules to scoped access.\n * 2. Handle `three/webgpu` (WebGPU is unavailable in WeChat mini games).\n * 3. Collect worker/wasm assets referenced by addons and emit them + a manifest.\n * 4. Produce a machine-readable build report for CI and AI-assisted iteration.\n */\nimport { promises as fs } from 'node:fs';\nimport {\n DEFAULT_FORCE_UNDEF,\n rewriteGlobals,\n type BuildSourceMap,\n type RewriteOptions,\n} from './scope-rewrite';\nimport {\n collectAssetReferences,\n collectAssets,\n type AssetManifest,\n type AssetOptions,\n} from './assets';\n\nexport interface MiniThreePluginOptions extends AssetOptions {\n /** Extra modules to transform. Receives a normalized (slash-separated) id. */\n include?: (id: string) => boolean;\n /** Modules to skip even when they match. */\n exclude?: (id: string) => boolean;\n /** Also transform application code (off by default). */\n includeUserCode?: boolean;\n /** Rewrite options (advanced). */\n rewrite?: RewriteOptions;\n /** How to handle `three/webgpu` imports. Default 'warn'. */\n webgpu?: 'warn' | 'error' | 'rewrite' | 'ignore';\n /** Print a build report summary. Default true. */\n report?: boolean;\n /** Verbose per-module logs. */\n debug?: boolean;\n}\n\nexport interface BuildReport {\n modulesScanned: number;\n modulesRewritten: number;\n rewrites: number;\n globalsSeen: string[];\n assetReferences: string[];\n missingAssets: string[];\n webgpuWarnings: string[];\n parseFailures: string[];\n}\n\nexport interface PluginContext {\n warn(message: string): void;\n error(message: string): never;\n emitFile(file: { type: 'asset'; fileName: string; source: string | Uint8Array }): string;\n}\n\nexport interface MiniThreePlugin {\n name: string;\n enforce: 'pre';\n transform(this: PluginContext, code: string, id: string): { code: string; map: BuildSourceMap | null } | null;\n generateBundle(this: PluginContext, options: { dir?: string; file?: string }): Promise<void>;\n api: {\n report(): BuildReport;\n };\n}\n\nconst DEFAULT_INCLUDE = (id: string): boolean => {\n const normalized = id.replace(/\\\\/g, '/').split('?')[0] ?? id;\n return (\n normalized.includes('/node_modules/three/') ||\n normalized.includes('/node_modules/three-stdlib/') ||\n normalized.includes('/node_modules/@react-three/') ||\n normalized.includes('/node_modules/@tresjs/') ||\n normalized.includes('/node_modules/.vite/deps/three') ||\n normalized.includes('/node_modules/.vite/deps/three-stdlib') ||\n /\\/node_modules\\/three@[^/]+\\//.test(normalized)\n );\n};\n\nexport function miniThreePlugin(options: MiniThreePluginOptions = {}): MiniThreePlugin {\n const include = options.include ?? DEFAULT_INCLUDE;\n const exclude = options.exclude ?? (() => false);\n const webgpuMode = options.webgpu ?? 'warn';\n const report: BuildReport = {\n modulesScanned: 0,\n modulesRewritten: 0,\n rewrites: 0,\n globalsSeen: [],\n assetReferences: [],\n missingAssets: [],\n webgpuWarnings: [],\n parseFailures: [],\n };\n const seenGlobals = new Set<string>();\n const assetRefs = new Set<string>();\n let manifest: AssetManifest | null = null;\n let filesToEmit = new Map<string, string>();\n\n const note = (ctx: PluginContext, message: string): void => {\n if (options.debug) ctx.warn(`[mini-three] ${message}`);\n };\n\n return {\n name: 'mini-three-adapter',\n enforce: 'pre',\n\n transform(this: PluginContext, code: string, id: string) {\n const normalized = id.replace(/\\\\/g, '/');\n const shouldTransform = options.includeUserCode\n ? !normalized.includes('/node_modules/mini-three-adapter/') && !exclude(normalized)\n : include(normalized) && !exclude(normalized);\n if (!shouldTransform) return null;\n\n report.modulesScanned++;\n for (const ref of collectAssetReferences(code)) assetRefs.add(ref);\n\n let currentCode = code;\n if (webgpuMode !== 'ignore' && /from\\s*['\"`]three\\/webgpu['\"`]/.test(code)) {\n const message = `[mini-three] ${normalized} imports 'three/webgpu'; WebGPU is not available in WeChat mini games.`;\n report.webgpuWarnings.push(message);\n if (webgpuMode === 'error') this.error(message);\n if (webgpuMode === 'warn') this.warn(`${message} Use three's WebGLRenderer instead.`);\n if (webgpuMode === 'rewrite') {\n currentCode = currentCode\n .replace(/(['\"`])three\\/webgpu\\1/g, '$1three$1')\n .replace(/\\bWebGPURenderer\\b/g, 'WebGLRenderer');\n note(this, `rewrote three/webgpu -> three in ${normalized}`);\n }\n }\n\n const result = rewriteGlobals(currentCode, normalized, {\n ...options.rewrite,\n ...(options.rewrite?.forceUndef ? {} : { forceUndef: [...DEFAULT_FORCE_UNDEF] }),\n });\n if (result && 'error' in result) {\n report.parseFailures.push(result.error);\n this.warn(`[mini-three] ${result.error}`);\n return null;\n }\n if (!result) return webgpuMode === 'rewrite' ? { code: currentCode, map: null } : null;\n\n report.modulesRewritten++;\n report.rewrites += result.count;\n for (const name of result.seen) seenGlobals.add(name);\n note(this, `${normalized}: ${result.count} global(s) rewritten (${result.seen.join(', ')})`);\n return { code: result.code, map: result.map };\n },\n\n async generateBundle(this: PluginContext, bundleOptions) {\n const refs = Array.from(assetRefs);\n report.assetReferences = refs;\n report.globalsSeen = Array.from(seenGlobals).sort();\n\n if (refs.length > 0) {\n const collected = await collectAssets(refs, {\n cwd: options.cwd,\n roots: options.roots,\n outputDir: options.outputDir,\n brotli: options.brotli,\n manifest: options.manifest,\n });\n manifest = collected.manifest;\n filesToEmit = collected.files;\n report.missingAssets = collected.missing;\n for (const missing of collected.missing) {\n this.warn(`[mini-three] asset not found in known roots: ${missing}`);\n }\n for (const [destination, source] of filesToEmit) {\n try {\n const content = await fs.readFile(source);\n this.emitFile({ type: 'asset', fileName: destination, source: content });\n } catch (error) {\n this.warn(`[mini-three] could not emit ${destination}: ${String(error)}`);\n }\n }\n } else {\n manifest = {\n generatedBy: 'mini-three-adapter',\n outputDir: options.outputDir ?? 'assets/three',\n entries: [],\n gameJsonSuggestion: {},\n decoderPaths: {},\n };\n }\n\n if (options.manifest !== false) {\n this.emitFile({\n type: 'asset',\n fileName: 'mini-three-assets.json',\n source: JSON.stringify({ ...manifest, build: report, output: bundleOptions.dir ?? bundleOptions.file ?? '' }, null, 2),\n });\n }\n if (options.report !== false) {\n this.warn(\n `[mini-three] build report: ${report.modulesScanned} module(s) scanned, ` +\n `${report.modulesRewritten} rewritten, ${report.rewrites} reference(s) -> scope, ` +\n `${filesToEmit.size} asset(s) emitted, ${report.missingAssets.length} missing.`,\n );\n }\n },\n\n api: {\n report: () => ({\n ...report,\n globalsSeen: Array.from(seenGlobals).sort(),\n assetReferences: Array.from(assetRefs),\n webgpuWarnings: [...report.webgpuWarnings],\n parseFailures: [...report.parseFailures],\n }),\n },\n };\n}\n","/**\n * AST-based global-to-scope rewriting.\n *\n * The reference adapter uses a Rollup \"prefix global\" pass that effectively\n * text-replaces identifiers. That breaks on shadowed locals, object keys, and\n * `typeof window` feature detection. Here we parse with @babel/parser and use\n * Babel's scope binding information, so ONLY free (unbound) references to\n * browser globals are rewritten — application code is never touched.\n */\nimport { parse } from '@babel/parser';\nimport _traverse from '@babel/traverse';\nimport MagicString from 'magic-string';\nimport type { NodePath } from '@babel/traverse';\nimport type { Identifier } from '@babel/types';\nimport type { Node } from '@babel/types';\n\n// Babel's CJS/ESM interop differs between bundlers; normalize once.\nconst traverse = (typeof _traverse === 'function'\n ? _traverse\n : (_traverse as unknown as { default: typeof _traverse }).default) as typeof _traverse;\n\nexport const DEFAULT_GLOBAL_NAMES: readonly string[] = [\n 'window', 'self', 'document', 'navigator', 'screen', 'location',\n 'innerWidth', 'innerHeight', 'outerWidth', 'outerHeight',\n 'devicePixelRatio', 'pageXOffset', 'pageYOffset',\n 'performance', 'requestAnimationFrame', 'cancelAnimationFrame',\n 'getComputedStyle', 'matchMedia', 'atob', 'btoa',\n 'Event', 'EventTarget', 'CustomEvent', 'PointerEvent', 'MouseEvent',\n 'TouchEvent', 'MessageEvent', 'ProgressEvent', 'KeyboardEvent', 'DOMException',\n 'HTMLElement', 'HTMLCanvasElement', 'HTMLImageElement', 'HTMLVideoElement',\n 'OffscreenCanvas', 'Image', 'ImageData', 'DOMRect',\n 'WebGLRenderingContext', 'WebGL2RenderingContext', 'AudioContext',\n 'Blob', 'URL', 'URLSearchParams', 'FileReader', 'TextDecoder', 'TextEncoder',\n 'AbortController', 'AbortSignal', 'fetch', 'XMLHttpRequest', 'WebSocket',\n 'createImageBitmap', 'Worker', 'WebAssembly', 'ResizeObserver',\n];\n\n/** Globals that must remain `undefined` in the mini game scope. */\nexport const DEFAULT_FORCE_UNDEF: readonly string[] = ['createImageBitmap'];\n\nexport interface RewriteOptions {\n /** Extra global identifiers to rewrite. */\n extraGlobals?: string[];\n /** Replace the default global list instead of extending it. */\n globals?: string[];\n /** Identifiers that must evaluate to `undefined` (feature-detection off). */\n forceUndef?: string[];\n /** Name of the injected scope accessor. Default `__m3`. */\n accessor?: string;\n /** Module specifier that exports `getActiveScope`. */\n scopeModule?: string;\n}\n\n/**\n * Minimal source-map shape accepted by Rollup / Vite as a transform result.\n * Declared locally so `dist/*.d.ts` stays self-contained (`rollup` is an\n * optional peer). `magic-string`'s `SourceMap` satisfies it structurally.\n */\nexport interface BuildSourceMap {\n version: number;\n file?: string;\n sources: string[];\n sourcesContent?: Array<string | null>;\n names: string[];\n mappings: string;\n}\n\nexport interface RewriteResult {\n code: string;\n map: BuildSourceMap | null;\n /** Number of rewritten references. */\n count: number;\n /** Globals actually seen (useful for the build report). */\n seen: string[];\n}\n\nexport interface RewriteFailure {\n code: string;\n error: string;\n}\n\nexport const SCOPE_IMPORT = (\n accessor: string,\n module: string,\n extraSpecifiers: readonly string[] = [],\n): string => {\n const specifiers = [`getActiveScope as ${accessor}`, ...extraSpecifiers].join(', ');\n return `import { ${specifiers} } from '${module}';\\n`;\n};\n\n/**\n * Reference or range equality. `@babel/parser` emits TWO distinct `Identifier`\n * nodes with identical `[start, end]` for a shorthand property (`{ X }`: one for\n * `key`, one for `value`), so reference equality alone is not enough to tell\n * \"this identifier is an object key\".\n */\nfunction sameNode(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n const x = a as { start?: number | null; end?: number | null } | null | undefined;\n const y = b as { start?: number | null; end?: number | null } | null | undefined;\n return Boolean(x && y && x.start != null && x.start === y.start && x.end === y.end);\n}\n\nfunction isNonComputedKey(path: NodePath): boolean {\n const parent = path.parentPath;\n if (!parent) return false;\n const self: unknown = path.node;\n if (parent.isObjectProperty() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\n if (parent.isObjectMethod() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\n if (parent.isClassProperty() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\n if (parent.isClassMethod() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\n if (parent.isMemberExpression() && !parent.node.computed && sameNode(parent.node.property, self)) return true;\n return false;\n}\n\n/**\n * `{ X }`: the value node shares its range with the key, so it cannot be\n * rewritten in place — it must be expanded to `{ X: <expr> }`.\n */\nfunction isShorthandValue(path: NodePath): boolean {\n const parent = path.parentPath;\n if (!parent?.isObjectProperty()) return false;\n if (!parent.node.shorthand || parent.node.computed) return false;\n if (parent.node.value !== path.node) return false;\n // `const { X } = obj` destructures a binding, never a global reference. Babel\n // already treats it as a binding, this guard keeps the two paths disjoint.\n return !parent.parentPath?.isObjectPattern();\n}\n\n/**\n * Is this identifier the left-most link of a `new X` / `new X.Y.Z` callee chain?\n *\n * `new f().g()` parses as `(new f()).g()`, so rewriting `X` to a *call*\n * (`__m3().X`) without parentheses silently turns `new X()` into\n * `(new __m3()).X()` — the scope object gets constructed and the class is then\n * invoked as a plain function. Wrapping only the chain root is enough:\n * `new (a().b).c` parses as `new ((a().b).c)`.\n */\nfunction isNewCalleeRoot(path: NodePath): boolean {\n let cur: NodePath = path;\n let parent = cur.parentPath;\n while (parent?.isMemberExpression() && parent.node.object === cur.node) {\n cur = parent;\n parent = parent.parentPath;\n }\n return Boolean(parent?.isNewExpression() && parent.node.callee === cur.node);\n}\n\n/** `typeof X` must never throw: `typeof a.b` is legal even when `a` is unbound. */\nfunction isDirectTypeofOperand(path: NodePath): boolean {\n const parent = path.parentPath;\n return Boolean(\n parent?.isUnaryExpression() &&\n parent.node.operator === 'typeof' &&\n parent.node.argument === path.node,\n );\n}\n\n/**\n * Globals that `getActiveScope()` resolves to itself even before a runtime\n * exists, so `typeof window` is already `'object'` and needs no guard.\n */\nconst ALWAYS_OBJECT_GLOBALS: ReadonlySet<string> = new Set(['window', 'self', 'globalThis']);\n\n/** Rewrite free browser-global references in one module. Returns null if nothing changed. */\nexport function rewriteGlobals(\n code: string,\n id: string,\n options: RewriteOptions = {},\n): RewriteResult | RewriteFailure | null {\n const names = new Set<string>([\n ...(options.globals ?? DEFAULT_GLOBAL_NAMES),\n ...(options.extraGlobals ?? []),\n ...(options.forceUndef ?? DEFAULT_FORCE_UNDEF),\n ]);\n const accessor = options.accessor ?? '__m3';\n const scopeModule = options.scopeModule ?? 'mini-three-adapter/scope';\n\n let ast;\n try {\n ast = parse(code, {\n sourceType: 'unambiguous',\n errorRecovery: true,\n plugins: ['importAttributes', 'classProperties', 'topLevelAwait', 'typescript', 'jsx'],\n });\n } catch (error) {\n return { code, error: `[mini-three] parse failed for ${id}: ${String(error)}` };\n }\n\n const ms = new MagicString(code);\n const seen = new Set<string>();\n const hasAccessor = `${accessor}Has`;\n let count = 0;\n let needsHasGuard = false;\n\n traverse(ast, {\n ReferencedIdentifier(path: NodePath<Node>) {\n const node = path.node as Identifier;\n const name = node.name;\n if (!name || !names.has(name)) return;\n if (node.start == null || node.end == null) return;\n // Babel scope knows about imports, function params, local declarations,\n // catch bindings and block-scoped shadowing. This is the critical check\n // that a regex-based replacement cannot perform.\n if (path.scope.hasBinding(name, true)) return;\n\n const ref = `${accessor}().${name}`;\n\n // 1) Shorthand must be handled before the key check: once `isNonComputedKey`\n // compares ranges, `{ X }`'s value looks like a key too and would be\n // silently skipped (leaving an undefined global behind).\n if (isShorthandValue(path)) {\n seen.add(name);\n ms.overwrite(node.start, node.end, `${name}: (${ref})`);\n count++;\n return;\n }\n\n // 2) Object keys / member property names are not references.\n if (isNonComputedKey(path)) return;\n\n seen.add(name);\n if (isDirectTypeofOperand(path) && !ALWAYS_OBJECT_GLOBALS.has(name)) {\n // `typeof X` must never throw. The placeholder scope answers the\n // environment globals (document/navigator/screen/...) with `undefined`\n // already, but everything else — TextDecoder, HTMLCanvasElement,\n // Blob, ... — throws an actionable error on access, and a `typeof`\n // probe must not become that error.\n ms.overwrite(node.start, node.end, `(${hasAccessor}() ? ${ref} : undefined)`);\n needsHasGuard = true;\n count++;\n return;\n }\n ms.overwrite(node.start, node.end, isNewCalleeRoot(path) ? `(${ref})` : ref);\n count++;\n },\n });\n\n if (count === 0) return null;\n ms.prepend(SCOPE_IMPORT(\n accessor,\n scopeModule,\n needsHasGuard ? [`hasActiveScope as ${hasAccessor}`] : [],\n ));\n return {\n code: ms.toString(),\n map: ms.generateMap({ source: id, includeContent: true, hires: true }),\n count,\n seen: Array.from(seen).sort(),\n };\n}\n","/**\n * Worker / WASM asset collection for three.js addons.\n *\n * DRACOLoader, KTX2Loader, 3DMLoader, LottieLoader, ... reference decoder\n * `.js` and `.wasm` files by string path. In a mini game those files are not\n * reachable via HTTP; they must be copied into the code package (ideally a\n * subpackage) and `setDecoderPath` must point at the copied location.\n *\n * The plugin scans transformed modules, resolves each referenced basename in a\n * small set of known directories, copies it, and emits a manifest plus a\n * `game.json` suggestion. No global state, no hidden writes.\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\n\nexport interface AssetOptions {\n /** Extra directories to search (besides three's jsm/libs). */\n roots?: string[];\n /** Output directory relative to the bundle root. Default 'assets/three'. */\n outputDir?: string;\n /** Copy `.wasm.br` alongside `.wasm` when available. Default true. */\n brotli?: boolean;\n /** Emit `mini-three-assets.json`. Default true. */\n manifest?: boolean;\n /** Working directory used to resolve roots. Default process.cwd(). */\n cwd?: string;\n}\n\nexport interface AssetEntry {\n /** Original string found in the module. */\n reference: string;\n /** Resolved absolute source path. */\n source: string;\n /** Relative destination inside the bundle. */\n destination: string;\n kind: 'worker' | 'wasm' | 'data';\n}\n\nexport interface AssetManifest {\n generatedBy: 'mini-three-adapter';\n outputDir: string;\n entries: AssetEntry[];\n /** Paste into game.json (adjust subpackage names to your project). */\n gameJsonSuggestion: Record<string, unknown>;\n /** Decoder paths to feed to loaders at runtime. */\n decoderPaths: Record<string, string>;\n}\n\nconst ASSET_PATTERN = /(['\"`])([^'\"`\\n]*\\.(?:wasm|wasm\\.br|bin|js))\\1/g;\nconst DECODER_KEYWORDS = [\n 'draco', 'basis', 'ktx2', 'rhino3dm', 'zstd', 'meshopt', 'ammo',\n 'worker', 'decoder', 'transcoder', 'lottie', 'sdf',\n];\n\nexport function collectAssetReferences(code: string): string[] {\n const found = new Set<string>();\n let match: RegExpExecArray | null;\n ASSET_PATTERN.lastIndex = 0;\n while ((match = ASSET_PATTERN.exec(code)) !== null) {\n const value = match[2] ?? '';\n const lower = value.toLowerCase();\n if (DECODER_KEYWORDS.some((keyword) => lower.includes(keyword))) found.add(value);\n }\n return Array.from(found);\n}\n\nasync function indexFiles(root: string, maxDepth = 5): Promise<Map<string, string>> {\n const index = new Map<string, string>();\n const walk = async (dir: string, depth: number): Promise<void> => {\n if (depth > maxDepth) return;\n let entries;\n try { entries = await fs.readdir(dir, { withFileTypes: true }); }\n catch { return; }\n for (const entry of entries) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) await walk(full, depth + 1);\n else if (entry.isFile() && !index.has(entry.name)) index.set(entry.name, full);\n }\n };\n await walk(root, 0);\n return index;\n}\n\nfunction classify(name: string): AssetEntry['kind'] {\n if (name.endsWith('.wasm') || name.endsWith('.wasm.br')) return 'wasm';\n if (name.endsWith('.js')) return 'worker';\n return 'data';\n}\n\nexport function defaultRoots(cwd: string): string[] {\n return [\n path.join(cwd, 'node_modules/three/examples/jsm/libs'),\n path.join(cwd, 'node_modules/three/examples/jsm'),\n path.join(cwd, 'node_modules/three-stdlib'),\n path.join(cwd, 'public'),\n path.join(cwd, 'static'),\n ];\n}\n\nexport interface CollectResult {\n manifest: AssetManifest;\n /** Files to write: destination (relative) -> absolute source. */\n files: Map<string, string>;\n missing: string[];\n}\n\n/** Resolve references against known roots without copying anything. */\nexport async function collectAssets(references: string[], options: AssetOptions = {}): Promise<CollectResult> {\n const cwd = options.cwd ?? process.cwd();\n const outputDir = (options.outputDir ?? 'assets/three').replace(/\\\\/g, '/').replace(/\\/$/, '');\n const roots = [...defaultRoots(cwd), ...(options.roots ?? [])];\n const indexes = await Promise.all(roots.map((root) => indexFiles(root)));\n const find = (name: string): string | undefined => {\n for (const index of indexes) {\n const hit = index.get(name);\n if (hit) return hit;\n }\n return undefined;\n };\n\n const entries: AssetEntry[] = [];\n const files = new Map<string, string>();\n const missing: string[] = [];\n\n for (const reference of references) {\n const base = path.posix.basename(reference.split('?')[0] ?? reference);\n const source = find(base);\n if (!source) { missing.push(reference); continue; }\n const entry: AssetEntry = {\n reference,\n source,\n destination: `${outputDir}/${base}`,\n kind: classify(base),\n };\n entries.push(entry);\n files.set(entry.destination, source);\n if (options.brotli !== false && entry.kind === 'wasm') {\n const br = find(`${base}.br`);\n if (br) {\n entries.push({ reference: `${reference}.br`, source: br, destination: `${outputDir}/${base}.br`, kind: 'wasm' });\n files.set(`${outputDir}/${base}.br`, br);\n }\n }\n }\n\n const decoderPaths: Record<string, string> = {};\n for (const entry of entries) {\n const name = path.posix.basename(entry.destination).toLowerCase();\n for (const key of ['draco', 'ktx2', 'basis', 'meshopt', 'rhino3dm', 'zstd', 'ammo']) {\n if (name.includes(key)) decoderPaths[key] = `${outputDir}/`;\n }\n }\n\n const manifest: AssetManifest = {\n generatedBy: 'mini-three-adapter',\n outputDir,\n entries,\n gameJsonSuggestion: {\n workers: { path: `${outputDir}`, isSubpackage: true },\n subpackages: [{ name: 'three-assets', root: `${outputDir}/` }],\n },\n decoderPaths,\n };\n return { manifest, files, missing };\n}\n\n/** Copy resolved files into `outDir`. */\nexport async function copyAssets(files: Map<string, string>, outDir: string): Promise<number> {\n let written = 0;\n for (const [destination, source] of files) {\n const target = path.join(outDir, destination);\n await fs.mkdir(path.dirname(target), { recursive: true });\n await fs.copyFile(source, target);\n written++;\n }\n return written;\n}\n","/** Rollup entry: `import { miniThree } from 'mini-three-adapter/rollup'`. */\nimport { miniThreePlugin, type MiniThreePlugin, type MiniThreePluginOptions } from './plugin-core';\n\nexport function miniThree(options: MiniThreePluginOptions = {}): MiniThreePlugin {\n return miniThreePlugin(options);\n}\n\nexport default miniThree;\nexport { miniThreePlugin } from './plugin-core';\nexport type { MiniThreePluginOptions, BuildReport } from './plugin-core';\nexport { DEFAULT_GLOBAL_NAMES, DEFAULT_FORCE_UNDEF, rewriteGlobals } from './scope-rewrite';\nexport type { RewriteOptions, RewriteResult } from './scope-rewrite';\nexport { collectAssetReferences, collectAssets, copyAssets } from './assets';\nexport type { AssetOptions, AssetManifest, AssetEntry } from './assets';\n"],"mappings":";AASA,SAAS,YAAYA,WAAU;;;ACA/B,SAAS,aAAa;AACtB,OAAO,eAAe;AACtB,OAAO,iBAAiB;AAMxB,IAAM,WAAY,OAAO,cAAc,aACnC,YACC,UAAuD;AAErD,IAAM,uBAA0C;AAAA,EACrD;AAAA,EAAU;AAAA,EAAQ;AAAA,EAAY;AAAA,EAAa;AAAA,EAAU;AAAA,EACrD;AAAA,EAAc;AAAA,EAAe;AAAA,EAAc;AAAA,EAC3C;AAAA,E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AQ,aAAa,OAAO;AAC9B,aAAK,SAAS;AAAA,UACZ,MAAM;AAAA,UACN,UAAU;AAAA,UACV,QAAQ,KAAK,UAAU,EAAE,GAAG,UAAU,OAAO,QAAQ,QAAQ,cAAc,OAAO,cAAc,QAAQ,GAAG,GAAG,MAAM,CAAC;AAAA,QACvH,CAAC;AAAA,MACH;AACA,UAAI,QAAQ,WAAW,OAAO;AAC5B,aAAK;AAAA,UACH,8BAA8B,OAAO,cAAc,uBAC9C,OAAO,gBAAgB,eAAe,OAAO,QAAQ,2BACrD,YAAY,IAAI,sBAAsB,OAAO,cAAc,MAAM;AAAA,QACxE;AAAA,MACF;AAAA,IACF;AAAA,IAEA,KAAK;AAAA,MACH,QAAQ,OAAO;AAAA,QACb,GAAG;AAAA,QACH,aAAa,MAAM,KAAK,WAAW,EAAE,KAAK;AAAA,QAC1C,iBAAiB,MAAM,KAAK,SAAS;AAAA,QACrC,gBAAgB,CAAC,GAAG,OAAO,cAAc;AAAA,QACzC,eAAe,CAAC,GAAG,OAAO,aAAa;AAAA,MACzC;AAAA,IACF;AAAA,EACF;AACF;;;AGjNO,SAAS,UAAU,UAAkC,CAAC,GAAoB;AAC/E,SAAO,gBAAgB,OAAO;AAChC;AAEA,IAAO,iBAAQ;","names":["fs","path","fs"]}
@@ -1,5 +1,5 @@
1
- import { a as MiniThreePlugin, M as MiniThreePluginOptions } from '../plugin-core-BuqW9C-L.js';
2
- export { B as BuildReport, m as miniThreePlugin } from '../plugin-core-BuqW9C-L.js';
1
+ import { a as MiniThreePlugin, M as MiniThreePluginOptions } from '../plugin-core-CBOr1cyv.js';
2
+ export { B as BuildReport, m as miniThreePlugin } from '../plugin-core-CBOr1cyv.js';
3
3
 
4
4
  /** Vite entry: `import miniThree from 'mini-three-adapter/vite'`. */
5
5
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/build/plugin-core.ts","../../src/build/scope-rewrite.ts","../../src/build/assets.ts","../../src/build/vite.ts"],"sourcesContent":["/**\n * Rollup/Vite-compatible plugin core (zero hard dependency on either bundler).\n *\n * Responsibilities:\n * 1. Rewrite free browser globals inside third-party modules to scoped access.\n * 2. Handle `three/webgpu` (WebGPU is unavailable in WeChat mini games).\n * 3. Collect worker/wasm assets referenced by addons and emit them + a manifest.\n * 4. Produce a machine-readable build report for CI and AI-assisted iteration.\n */\nimport { promises as fs } from 'node:fs';\nimport {\n DEFAULT_FORCE_UNDEF,\n rewriteGlobals,\n type RewriteOptions,\n} from './scope-rewrite';\nimport {\n collectAssetReferences,\n collectAssets,\n type AssetManifest,\n type AssetOptions,\n} from './assets';\n\nexport interface MiniThreePluginOptions extends AssetOptions {\n /** Extra modules to transform. Receives a normalized (slash-separated) id. */\n include?: (id: string) => boolean;\n /** Modules to skip even when they match. */\n exclude?: (id: string) => boolean;\n /** Also transform application code (off by default). */\n includeUserCode?: boolean;\n /** Rewrite options (advanced). */\n rewrite?: RewriteOptions;\n /** How to handle `three/webgpu` imports. Default 'warn'. */\n webgpu?: 'warn' | 'error' | 'rewrite' | 'ignore';\n /** Print a build report summary. Default true. */\n report?: boolean;\n /** Verbose per-module logs. */\n debug?: boolean;\n}\n\nexport interface BuildReport {\n modulesScanned: number;\n modulesRewritten: number;\n rewrites: number;\n globalsSeen: string[];\n assetReferences: string[];\n missingAssets: string[];\n webgpuWarnings: string[];\n parseFailures: string[];\n}\n\nexport interface PluginContext {\n warn(message: string): void;\n error(message: string): never;\n emitFile(file: { type: 'asset'; fileName: string; source: string | Uint8Array }): string;\n}\n\nexport interface MiniThreePlugin {\n name: string;\n enforce: 'pre';\n transform(this: PluginContext, code: string, id: string): { code: string; map: unknown } | null;\n generateBundle(this: PluginContext, options: { dir?: string; file?: string }): Promise<void>;\n api: {\n report(): BuildReport;\n };\n}\n\nconst DEFAULT_INCLUDE = (id: string): boolean => {\n const normalized = id.replace(/\\\\/g, '/').split('?')[0] ?? id;\n return (\n normalized.includes('/node_modules/three/') ||\n normalized.includes('/node_modules/three-stdlib/') ||\n normalized.includes('/node_modules/@react-three/') ||\n normalized.includes('/node_modules/@tresjs/') ||\n normalized.includes('/node_modules/.vite/deps/three') ||\n normalized.includes('/node_modules/.vite/deps/three-stdlib') ||\n /\\/node_modules\\/three@[^/]+\\//.test(normalized)\n );\n};\n\nexport function miniThreePlugin(options: MiniThreePluginOptions = {}): MiniThreePlugin {\n const include = options.include ?? DEFAULT_INCLUDE;\n const exclude = options.exclude ?? (() => false);\n const webgpuMode = options.webgpu ?? 'warn';\n const report: BuildReport = {\n modulesScanned: 0,\n modulesRewritten: 0,\n rewrites: 0,\n globalsSeen: [],\n assetReferences: [],\n missingAssets: [],\n webgpuWarnings: [],\n parseFailures: [],\n };\n const seenGlobals = new Set<string>();\n const assetRefs = new Set<string>();\n let manifest: AssetManifest | null = null;\n let filesToEmit = new Map<string, string>();\n\n const note = (ctx: PluginContext, message: string): void => {\n if (options.debug) ctx.warn(`[mini-three] ${message}`);\n };\n\n return {\n name: 'mini-three-adapter',\n enforce: 'pre',\n\n transform(this: PluginContext, code: string, id: string) {\n const normalized = id.replace(/\\\\/g, '/');\n const shouldTransform = options.includeUserCode\n ? !normalized.includes('/node_modules/mini-three-adapter/') && !exclude(normalized)\n : include(normalized) && !exclude(normalized);\n if (!shouldTransform) return null;\n\n report.modulesScanned++;\n for (const ref of collectAssetReferences(code)) assetRefs.add(ref);\n\n let currentCode = code;\n if (webgpuMode !== 'ignore' && /from\\s*['\"`]three\\/webgpu['\"`]/.test(code)) {\n const message = `[mini-three] ${normalized} imports 'three/webgpu'; WebGPU is not available in WeChat mini games.`;\n report.webgpuWarnings.push(message);\n if (webgpuMode === 'error') this.error(message);\n if (webgpuMode === 'warn') this.warn(`${message} Use three's WebGLRenderer instead.`);\n if (webgpuMode === 'rewrite') {\n currentCode = currentCode\n .replace(/(['\"`])three\\/webgpu\\1/g, '$1three$1')\n .replace(/\\bWebGPURenderer\\b/g, 'WebGLRenderer');\n note(this, `rewrote three/webgpu -> three in ${normalized}`);\n }\n }\n\n const result = rewriteGlobals(currentCode, normalized, {\n ...options.rewrite,\n ...(options.rewrite?.forceUndef ? {} : { forceUndef: [...DEFAULT_FORCE_UNDEF] }),\n });\n if (result && 'error' in result) {\n report.parseFailures.push(result.error);\n this.warn(`[mini-three] ${result.error}`);\n return null;\n }\n if (!result) return webgpuMode === 'rewrite' ? { code: currentCode, map: null } : null;\n\n report.modulesRewritten++;\n report.rewrites += result.count;\n for (const name of result.seen) seenGlobals.add(name);\n note(this, `${normalized}: ${result.count} global(s) rewritten (${result.seen.join(', ')})`);\n return { code: result.code, map: result.map };\n },\n\n async generateBundle(this: PluginContext, bundleOptions) {\n const refs = Array.from(assetRefs);\n report.assetReferences = refs;\n report.globalsSeen = Array.from(seenGlobals).sort();\n\n if (refs.length > 0) {\n const collected = await collectAssets(refs, {\n cwd: options.cwd,\n roots: options.roots,\n outputDir: options.outputDir,\n brotli: options.brotli,\n manifest: options.manifest,\n });\n manifest = collected.manifest;\n filesToEmit = collected.files;\n report.missingAssets = collected.missing;\n for (const missing of collected.missing) {\n this.warn(`[mini-three] asset not found in known roots: ${missing}`);\n }\n for (const [destination, source] of filesToEmit) {\n try {\n const content = await fs.readFile(source);\n this.emitFile({ type: 'asset', fileName: destination, source: content });\n } catch (error) {\n this.warn(`[mini-three] could not emit ${destination}: ${String(error)}`);\n }\n }\n } else {\n manifest = {\n generatedBy: 'mini-three-adapter',\n outputDir: options.outputDir ?? 'assets/three',\n entries: [],\n gameJsonSuggestion: {},\n decoderPaths: {},\n };\n }\n\n if (options.manifest !== false) {\n this.emitFile({\n type: 'asset',\n fileName: 'mini-three-assets.json',\n source: JSON.stringify({ ...manifest, build: report, output: bundleOptions.dir ?? bundleOptions.file ?? '' }, null, 2),\n });\n }\n if (options.report !== false) {\n this.warn(\n `[mini-three] build report: ${report.modulesScanned} module(s) scanned, ` +\n `${report.modulesRewritten} rewritten, ${report.rewrites} reference(s) -> scope, ` +\n `${filesToEmit.size} asset(s) emitted, ${report.missingAssets.length} missing.`,\n );\n }\n },\n\n api: {\n report: () => ({\n ...report,\n globalsSeen: Array.from(seenGlobals).sort(),\n assetReferences: Array.from(assetRefs),\n webgpuWarnings: [...report.webgpuWarnings],\n parseFailures: [...report.parseFailures],\n }),\n },\n };\n}\n","/**\n * AST-based global-to-scope rewriting.\n *\n * The reference adapter uses a Rollup \"prefix global\" pass that effectively\n * text-replaces identifiers. That breaks on shadowed locals, object keys, and\n * `typeof window` feature detection. Here we parse with @babel/parser and use\n * Babel's scope binding information, so ONLY free (unbound) references to\n * browser globals are rewritten — application code is never touched.\n */\nimport { parse } from '@babel/parser';\nimport _traverse from '@babel/traverse';\nimport MagicString from 'magic-string';\nimport type { NodePath } from '@babel/traverse';\nimport type { Identifier } from '@babel/types';\nimport type { Node } from '@babel/types';\n\n// Babel's CJS/ESM interop differs between bundlers; normalize once.\nconst traverse = (typeof _traverse === 'function'\n ? _traverse\n : (_traverse as unknown as { default: typeof _traverse }).default) as typeof _traverse;\n\nexport const DEFAULT_GLOBAL_NAMES: readonly string[] = [\n 'window', 'self', 'document', 'navigator', 'screen', 'location',\n 'innerWidth', 'innerHeight', 'outerWidth', 'outerHeight',\n 'devicePixelRatio', 'pageXOffset', 'pageYOffset',\n 'performance', 'requestAnimationFrame', 'cancelAnimationFrame',\n 'getComputedStyle', 'matchMedia', 'atob', 'btoa',\n 'Event', 'EventTarget', 'CustomEvent', 'PointerEvent', 'MouseEvent',\n 'TouchEvent', 'MessageEvent', 'ProgressEvent', 'KeyboardEvent', 'DOMException',\n 'HTMLElement', 'HTMLCanvasElement', 'HTMLImageElement', 'HTMLVideoElement',\n 'OffscreenCanvas', 'Image', 'ImageData', 'DOMRect',\n 'WebGLRenderingContext', 'WebGL2RenderingContext', 'AudioContext',\n 'Blob', 'URL', 'URLSearchParams', 'FileReader', 'TextDecoder', 'TextEncoder',\n 'AbortController', 'AbortSignal', 'fetch', 'XMLHttpRequest', 'WebSocket',\n 'createImageBitmap', 'Worker', 'WebAssembly', 'ResizeObserver',\n];\n\n/** Globals that must remain `undefined` in the mini game scope. */\nexport const DEFAULT_FORCE_UNDEF: readonly string[] = ['createImageBitmap'];\n\nexport interface RewriteOptions {\n /** Extra global identifiers to rewrite. */\n extraGlobals?: string[];\n /** Replace the default global list instead of extending it. */\n globals?: string[];\n /** Identifiers that must evaluate to `undefined` (feature-detection off). */\n forceUndef?: string[];\n /** Name of the injected scope accessor. Default `__m3`. */\n accessor?: string;\n /** Module specifier that exports `getActiveScope`. */\n scopeModule?: string;\n}\n\nexport interface RewriteResult {\n code: string;\n map: { toString(): string } | null;\n /** Number of rewritten references. */\n count: number;\n /** Globals actually seen (useful for the build report). */\n seen: string[];\n}\n\nexport interface RewriteFailure {\n code: string;\n error: string;\n}\n\nexport const SCOPE_IMPORT = (\n accessor: string,\n module: string,\n extraSpecifiers: readonly string[] = [],\n): string => {\n const specifiers = [`getActiveScope as ${accessor}`, ...extraSpecifiers].join(', ');\n return `import { ${specifiers} } from '${module}';\\n`;\n};\n\n/**\n * Reference or range equality. `@babel/parser` emits TWO distinct `Identifier`\n * nodes with identical `[start, end]` for a shorthand property (`{ X }`: one for\n * `key`, one for `value`), so reference equality alone is not enough to tell\n * \"this identifier is an object key\".\n */\nfunction sameNode(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n const x = a as { start?: number | null; end?: number | null } | null | undefined;\n const y = b as { start?: number | null; end?: number | null } | null | undefined;\n return Boolean(x && y && x.start != null && x.start === y.start && x.end === y.end);\n}\n\nfunction isNonComputedKey(path: NodePath): boolean {\n const parent = path.parentPath;\n if (!parent) return false;\n const self: unknown = path.node;\n if (parent.isObjectProperty() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\n if (parent.isObjectMethod() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\n if (parent.isClassProperty() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\n if (parent.isClassMethod() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\n if (parent.isMemberExpression() && !parent.node.computed && sameNode(parent.node.property, self)) return true;\n return false;\n}\n\n/**\n * `{ X }`: the value node shares its range with the key, so it cannot be\n * rewritten in place — it must be expanded to `{ X: <expr> }`.\n */\nfunction isShorthandValue(path: NodePath): boolean {\n const parent = path.parentPath;\n if (!parent?.isObjectProperty()) return false;\n if (!parent.node.shorthand || parent.node.computed) return false;\n if (parent.node.value !== path.node) return false;\n // `const { X } = obj` destructures a binding, never a global reference. Babel\n // already treats it as a binding, this guard keeps the two paths disjoint.\n return !parent.parentPath?.isObjectPattern();\n}\n\n/**\n * Is this identifier the left-most link of a `new X` / `new X.Y.Z` callee chain?\n *\n * `new f().g()` parses as `(new f()).g()`, so rewriting `X` to a *call*\n * (`__m3().X`) without parentheses silently turns `new X()` into\n * `(new __m3()).X()` — the scope object gets constructed and the class is then\n * invoked as a plain function. Wrapping only the chain root is enough:\n * `new (a().b).c` parses as `new ((a().b).c)`.\n */\nfunction isNewCalleeRoot(path: NodePath): boolean {\n let cur: NodePath = path;\n let parent = cur.parentPath;\n while (parent?.isMemberExpression() && parent.node.object === cur.node) {\n cur = parent;\n parent = parent.parentPath;\n }\n return Boolean(parent?.isNewExpression() && parent.node.callee === cur.node);\n}\n\n/** `typeof X` must never throw: `typeof a.b` is legal even when `a` is unbound. */\nfunction isDirectTypeofOperand(path: NodePath): boolean {\n const parent = path.parentPath;\n return Boolean(\n parent?.isUnaryExpression() &&\n parent.node.operator === 'typeof' &&\n parent.node.argument === path.node,\n );\n}\n\n/**\n * Globals that `getActiveScope()` resolves to itself even before a runtime\n * exists, so `typeof window` is already `'object'` and needs no guard.\n */\nconst ALWAYS_OBJECT_GLOBALS: ReadonlySet<string> = new Set(['window', 'self', 'globalThis']);\n\n/** Rewrite free browser-global references in one module. Returns null if nothing changed. */\nexport function rewriteGlobals(\n code: string,\n id: string,\n options: RewriteOptions = {},\n): RewriteResult | RewriteFailure | null {\n const names = new Set<string>([\n ...(options.globals ?? DEFAULT_GLOBAL_NAMES),\n ...(options.extraGlobals ?? []),\n ...(options.forceUndef ?? DEFAULT_FORCE_UNDEF),\n ]);\n const accessor = options.accessor ?? '__m3';\n const scopeModule = options.scopeModule ?? 'mini-three-adapter/scope';\n\n let ast;\n try {\n ast = parse(code, {\n sourceType: 'unambiguous',\n errorRecovery: true,\n plugins: ['importAttributes', 'classProperties', 'topLevelAwait', 'typescript', 'jsx'],\n });\n } catch (error) {\n return { code, error: `[mini-three] parse failed for ${id}: ${String(error)}` };\n }\n\n const ms = new MagicString(code);\n const seen = new Set<string>();\n const hasAccessor = `${accessor}Has`;\n let count = 0;\n let needsHasGuard = false;\n\n traverse(ast, {\n ReferencedIdentifier(path: NodePath<Node>) {\n const node = path.node as Identifier;\n const name = node.name;\n if (!name || !names.has(name)) return;\n if (node.start == null || node.end == null) return;\n // Babel scope knows about imports, function params, local declarations,\n // catch bindings and block-scoped shadowing. This is the critical check\n // that a regex-based replacement cannot perform.\n if (path.scope.hasBinding(name, true)) return;\n\n const ref = `${accessor}().${name}`;\n\n // 1) Shorthand must be handled before the key check: once `isNonComputedKey`\n // compares ranges, `{ X }`'s value looks like a key too and would be\n // silently skipped (leaving an undefined global behind).\n if (isShorthandValue(path)) {\n seen.add(name);\n ms.overwrite(node.start, node.end, `${name}: (${ref})`);\n count++;\n return;\n }\n\n // 2) Object keys / member property names are not references.\n if (isNonComputedKey(path)) return;\n\n seen.add(name);\n if (isDirectTypeofOperand(path) && !ALWAYS_OBJECT_GLOBALS.has(name)) {\n // `typeof X` must never throw. The placeholder scope answers the\n // environment globals (document/navigator/screen/...) with `undefined`\n // already, but everything else — TextDecoder, HTMLCanvasElement,\n // Blob, ... — throws an actionable error on access, and a `typeof`\n // probe must not become that error.\n ms.overwrite(node.start, node.end, `(${hasAccessor}() ? ${ref} : undefined)`);\n needsHasGuard = true;\n count++;\n return;\n }\n ms.overwrite(node.start, node.end, isNewCalleeRoot(path) ? `(${ref})` : ref);\n count++;\n },\n });\n\n if (count === 0) return null;\n ms.prepend(SCOPE_IMPORT(\n accessor,\n scopeModule,\n needsHasGuard ? [`hasActiveScope as ${hasAccessor}`] : [],\n ));\n return {\n code: ms.toString(),\n map: ms.generateMap({ source: id, includeContent: true, hires: true }) as unknown as { toString(): string },\n count,\n seen: Array.from(seen).sort(),\n };\n}\n","/**\n * Worker / WASM asset collection for three.js addons.\n *\n * DRACOLoader, KTX2Loader, 3DMLoader, LottieLoader, ... reference decoder\n * `.js` and `.wasm` files by string path. In a mini game those files are not\n * reachable via HTTP; they must be copied into the code package (ideally a\n * subpackage) and `setDecoderPath` must point at the copied location.\n *\n * The plugin scans transformed modules, resolves each referenced basename in a\n * small set of known directories, copies it, and emits a manifest plus a\n * `game.json` suggestion. No global state, no hidden writes.\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\n\nexport interface AssetOptions {\n /** Extra directories to search (besides three's jsm/libs). */\n roots?: string[];\n /** Output directory relative to the bundle root. Default 'assets/three'. */\n outputDir?: string;\n /** Copy `.wasm.br` alongside `.wasm` when available. Default true. */\n brotli?: boolean;\n /** Emit `mini-three-assets.json`. Default true. */\n manifest?: boolean;\n /** Working directory used to resolve roots. Default process.cwd(). */\n cwd?: string;\n}\n\nexport interface AssetEntry {\n /** Original string found in the module. */\n reference: string;\n /** Resolved absolute source path. */\n source: string;\n /** Relative destination inside the bundle. */\n destination: string;\n kind: 'worker' | 'wasm' | 'data';\n}\n\nexport interface AssetManifest {\n generatedBy: 'mini-three-adapter';\n outputDir: string;\n entries: AssetEntry[];\n /** Paste into game.json (adjust subpackage names to your project). */\n gameJsonSuggestion: Record<string, unknown>;\n /** Decoder paths to feed to loaders at runtime. */\n decoderPaths: Record<string, string>;\n}\n\nconst ASSET_PATTERN = /(['\"`])([^'\"`\\n]*\\.(?:wasm|wasm\\.br|bin|js))\\1/g;\nconst DECODER_KEYWORDS = [\n 'draco', 'basis', 'ktx2', 'rhino3dm', 'zstd', 'meshopt', 'ammo',\n 'worker', 'decoder', 'transcoder', 'lottie', 'sdf',\n];\n\nexport function collectAssetReferences(code: string): string[] {\n const found = new Set<string>();\n let match: RegExpExecArray | null;\n ASSET_PATTERN.lastIndex = 0;\n while ((match = ASSET_PATTERN.exec(code)) !== null) {\n const value = match[2] ?? '';\n const lower = value.toLowerCase();\n if (DECODER_KEYWORDS.some((keyword) => lower.includes(keyword))) found.add(value);\n }\n return Array.from(found);\n}\n\nasync function indexFiles(root: string, maxDepth = 5): Promise<Map<string, string>> {\n const index = new Map<string, string>();\n const walk = async (dir: string, depth: number): Promise<void> => {\n if (depth > maxDepth) return;\n let entries;\n try { entries = await fs.readdir(dir, { withFileTypes: true }); }\n catch { return; }\n for (const entry of entries) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) await walk(full, depth + 1);\n else if (entry.isFile() && !index.has(entry.name)) index.set(entry.name, full);\n }\n };\n await walk(root, 0);\n return index;\n}\n\nfunction classify(name: string): AssetEntry['kind'] {\n if (name.endsWith('.wasm') || name.endsWith('.wasm.br')) return 'wasm';\n if (name.endsWith('.js')) return 'worker';\n return 'data';\n}\n\nexport function defaultRoots(cwd: string): string[] {\n return [\n path.join(cwd, 'node_modules/three/examples/jsm/libs'),\n path.join(cwd, 'node_modules/three/examples/jsm'),\n path.join(cwd, 'node_modules/three-stdlib'),\n path.join(cwd, 'public'),\n path.join(cwd, 'static'),\n ];\n}\n\nexport interface CollectResult {\n manifest: AssetManifest;\n /** Files to write: destination (relative) -> absolute source. */\n files: Map<string, string>;\n missing: string[];\n}\n\n/** Resolve references against known roots without copying anything. */\nexport async function collectAssets(references: string[], options: AssetOptions = {}): Promise<CollectResult> {\n const cwd = options.cwd ?? process.cwd();\n const outputDir = (options.outputDir ?? 'assets/three').replace(/\\\\/g, '/').replace(/\\/$/, '');\n const roots = [...defaultRoots(cwd), ...(options.roots ?? [])];\n const indexes = await Promise.all(roots.map((root) => indexFiles(root)));\n const find = (name: string): string | undefined => {\n for (const index of indexes) {\n const hit = index.get(name);\n if (hit) return hit;\n }\n return undefined;\n };\n\n const entries: AssetEntry[] = [];\n const files = new Map<string, string>();\n const missing: string[] = [];\n\n for (const reference of references) {\n const base = path.posix.basename(reference.split('?')[0] ?? reference);\n const source = find(base);\n if (!source) { missing.push(reference); continue; }\n const entry: AssetEntry = {\n reference,\n source,\n destination: `${outputDir}/${base}`,\n kind: classify(base),\n };\n entries.push(entry);\n files.set(entry.destination, source);\n if (options.brotli !== false && entry.kind === 'wasm') {\n const br = find(`${base}.br`);\n if (br) {\n entries.push({ reference: `${reference}.br`, source: br, destination: `${outputDir}/${base}.br`, kind: 'wasm' });\n files.set(`${outputDir}/${base}.br`, br);\n }\n }\n }\n\n const decoderPaths: Record<string, string> = {};\n for (const entry of entries) {\n const name = path.posix.basename(entry.destination).toLowerCase();\n for (const key of ['draco', 'ktx2', 'basis', 'meshopt', 'rhino3dm', 'zstd', 'ammo']) {\n if (name.includes(key)) decoderPaths[key] = `${outputDir}/`;\n }\n }\n\n const manifest: AssetManifest = {\n generatedBy: 'mini-three-adapter',\n outputDir,\n entries,\n gameJsonSuggestion: {\n workers: { path: `${outputDir}`, isSubpackage: true },\n subpackages: [{ name: 'three-assets', root: `${outputDir}/` }],\n },\n decoderPaths,\n };\n return { manifest, files, missing };\n}\n\n/** Copy resolved files into `outDir`. */\nexport async function copyAssets(files: Map<string, string>, outDir: string): Promise<number> {\n let written = 0;\n for (const [destination, source] of files) {\n const target = path.join(outDir, destination);\n await fs.mkdir(path.dirname(target), { recursive: true });\n await fs.copyFile(source, target);\n written++;\n }\n return written;\n}\n","/** Vite entry: `import miniThree from 'mini-three-adapter/vite'`. */\nimport { miniThreePlugin, type MiniThreePlugin, type MiniThreePluginOptions } from './plugin-core';\n\nexport interface ViteMiniThreePlugin extends MiniThreePlugin {\n config(): Record<string, unknown>;\n}\n\n/**\n * Vite plugin. `optimizeDeps.exclude` keeps three's ESM sources intact so the\n * AST rewrite sees the original module graph instead of a pre-bundled blob.\n */\nexport function miniThree(options: MiniThreePluginOptions = {}): ViteMiniThreePlugin {\n const core = miniThreePlugin(options);\n return {\n ...core,\n config() {\n return {\n optimizeDeps: {\n exclude: ['three', 'three-stdlib', 'three/examples/jsm'],\n },\n build: {\n commonjsOptions: { transformMixedEsModules: true },\n rollupOptions: {\n output: {\n manualChunks: undefined,\n },\n },\n },\n };\n },\n };\n}\n\nexport default miniThree;\nexport { miniThreePlugin } from './plugin-core';\nexport type { MiniThreePluginOptions, BuildReport } from './plugin-core';\n"],"mappings":";AASA,SAAS,YAAYA,WAAU;;;ACA/B,SAAS,aAAa;AACtB,OAAO,eAAe;AACtB,OAAO,iBAAiB;AAMxB,IAAM,WAAY,OAAO,cAAc,aACnC,YACC,UAAuD;AAErD,IAAM,uBAA0C;AAAA,EACrD;AAAA,EAAU;AAAA,EAAQ;AAAA,EAAY;AAAA,EAAa;AAAA,EAAU;AAAA,EACrD;AAAA,EAAc;AAAA,EAAe;AAAA,EAAc;AAAA,EAC3C;AAAA,EAAoB;AAAA,EAAe;AAAA,EACnC;AAAA,EAAe;AAAA,EAAyB;AAAA,EACxC;AAAA,EAAoB;AAAA,EAAc;AAAA,EAAQ;AAAA,EAC1C;AAAA,EAAS;AAAA,EAAe;AAAA,EAAe;AAAA,EAAgB;AAAA,EACvD;AAAA,EAAc;AAAA,EAAgB;AAAA,EAAiB;AAAA,EAAiB;AAAA,EAChE;AAAA,EAAe;AAAA,EAAqB;AAAA,EAAoB;AAAA,EACxD;AAAA,EAAmB;AAAA,EAAS;AAAA,EAAa;AAAA,EACzC;AAAA,EAAyB;AAAA,EAA0B;AAAA,EACnD;AAAA,EAAQ;AAAA,EAAO;AAAA,EAAmB;AAAA,EAAc;AAAA,EAAe;AAAA,EAC/D;AAAA,EAAmB;AAAA,EAAe;AAAA,EAAS;AAAA,EAAkB;AAAA,EAC7D;AAAA,EAAqB;AAAA,EAAU;AAAA,EAAe;AAChD;AAGO,IAAM,sBAAyC,CAAC,mBAAmB;AA6BnE,IAAM,eAAe,CAC1B,UACA,QACA,kBAAqC,CAAC,MAC3B;AACX,QAAM,aAAa,CAAC,qBAAqB,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ACb,QAAQ;AAAA,cACN,cAAc;AAAA,YAChB;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AAEA,IAAO,eAAQ;","names":["fs","path","fs"]}
1
+ {"version":3,"sources":["../../src/build/plugin-core.ts","../../src/build/scope-rewrite.ts","../../src/build/assets.ts","../../src/build/vite.ts"],"sourcesContent":["/**\n * Rollup/Vite-compatible plugin core (zero hard dependency on either bundler).\n *\n * Responsibilities:\n * 1. Rewrite free browser globals inside third-party modules to scoped access.\n * 2. Handle `three/webgpu` (WebGPU is unavailable in WeChat mini games).\n * 3. Collect worker/wasm assets referenced by addons and emit them + a manifest.\n * 4. Produce a machine-readable build report for CI and AI-assisted iteration.\n */\nimport { promises as fs } from 'node:fs';\nimport {\n DEFAULT_FORCE_UNDEF,\n rewriteGlobals,\n type BuildSourceMap,\n type RewriteOptions,\n} from './scope-rewrite';\nimport {\n collectAssetReferences,\n collectAssets,\n type AssetManifest,\n type AssetOptions,\n} from './assets';\n\nexport interface MiniThreePluginOptions extends AssetOptions {\n /** Extra modules to transform. Receives a normalized (slash-separated) id. */\n include?: (id: string) => boolean;\n /** Modules to skip even when they match. */\n exclude?: (id: string) => boolean;\n /** Also transform application code (off by default). */\n includeUserCode?: boolean;\n /** Rewrite options (advanced). */\n rewrite?: RewriteOptions;\n /** How to handle `three/webgpu` imports. Default 'warn'. */\n webgpu?: 'warn' | 'error' | 'rewrite' | 'ignore';\n /** Print a build report summary. Default true. */\n report?: boolean;\n /** Verbose per-module logs. */\n debug?: boolean;\n}\n\nexport interface BuildReport {\n modulesScanned: number;\n modulesRewritten: number;\n rewrites: number;\n globalsSeen: string[];\n assetReferences: string[];\n missingAssets: string[];\n webgpuWarnings: string[];\n parseFailures: string[];\n}\n\nexport interface PluginContext {\n warn(message: string): void;\n error(message: string): never;\n emitFile(file: { type: 'asset'; fileName: string; source: string | Uint8Array }): string;\n}\n\nexport interface MiniThreePlugin {\n name: string;\n enforce: 'pre';\n transform(this: PluginContext, code: string, id: string): { code: string; map: BuildSourceMap | null } | null;\n generateBundle(this: PluginContext, options: { dir?: string; file?: string }): Promise<void>;\n api: {\n report(): BuildReport;\n };\n}\n\nconst DEFAULT_INCLUDE = (id: string): boolean => {\n const normalized = id.replace(/\\\\/g, '/').split('?')[0] ?? id;\n return (\n normalized.includes('/node_modules/three/') ||\n normalized.includes('/node_modules/three-stdlib/') ||\n normalized.includes('/node_modules/@react-three/') ||\n normalized.includes('/node_modules/@tresjs/') ||\n normalized.includes('/node_modules/.vite/deps/three') ||\n normalized.includes('/node_modules/.vite/deps/three-stdlib') ||\n /\\/node_modules\\/three@[^/]+\\//.test(normalized)\n );\n};\n\nexport function miniThreePlugin(options: MiniThreePluginOptions = {}): MiniThreePlugin {\n const include = options.include ?? DEFAULT_INCLUDE;\n const exclude = options.exclude ?? (() => false);\n const webgpuMode = options.webgpu ?? 'warn';\n const report: BuildReport = {\n modulesScanned: 0,\n modulesRewritten: 0,\n rewrites: 0,\n globalsSeen: [],\n assetReferences: [],\n missingAssets: [],\n webgpuWarnings: [],\n parseFailures: [],\n };\n const seenGlobals = new Set<string>();\n const assetRefs = new Set<string>();\n let manifest: AssetManifest | null = null;\n let filesToEmit = new Map<string, string>();\n\n const note = (ctx: PluginContext, message: string): void => {\n if (options.debug) ctx.warn(`[mini-three] ${message}`);\n };\n\n return {\n name: 'mini-three-adapter',\n enforce: 'pre',\n\n transform(this: PluginContext, code: string, id: string) {\n const normalized = id.replace(/\\\\/g, '/');\n const shouldTransform = options.includeUserCode\n ? !normalized.includes('/node_modules/mini-three-adapter/') && !exclude(normalized)\n : include(normalized) && !exclude(normalized);\n if (!shouldTransform) return null;\n\n report.modulesScanned++;\n for (const ref of collectAssetReferences(code)) assetRefs.add(ref);\n\n let currentCode = code;\n if (webgpuMode !== 'ignore' && /from\\s*['\"`]three\\/webgpu['\"`]/.test(code)) {\n const message = `[mini-three] ${normalized} imports 'three/webgpu'; WebGPU is not available in WeChat mini games.`;\n report.webgpuWarnings.push(message);\n if (webgpuMode === 'error') this.error(message);\n if (webgpuMode === 'warn') this.warn(`${message} Use three's WebGLRenderer instead.`);\n if (webgpuMode === 'rewrite') {\n currentCode = currentCode\n .replace(/(['\"`])three\\/webgpu\\1/g, '$1three$1')\n .replace(/\\bWebGPURenderer\\b/g, 'WebGLRenderer');\n note(this, `rewrote three/webgpu -> three in ${normalized}`);\n }\n }\n\n const result = rewriteGlobals(currentCode, normalized, {\n ...options.rewrite,\n ...(options.rewrite?.forceUndef ? {} : { forceUndef: [...DEFAULT_FORCE_UNDEF] }),\n });\n if (result && 'error' in result) {\n report.parseFailures.push(result.error);\n this.warn(`[mini-three] ${result.error}`);\n return null;\n }\n if (!result) return webgpuMode === 'rewrite' ? { code: currentCode, map: null } : null;\n\n report.modulesRewritten++;\n report.rewrites += result.count;\n for (const name of result.seen) seenGlobals.add(name);\n note(this, `${normalized}: ${result.count} global(s) rewritten (${result.seen.join(', ')})`);\n return { code: result.code, map: result.map };\n },\n\n async generateBundle(this: PluginContext, bundleOptions) {\n const refs = Array.from(assetRefs);\n report.assetReferences = refs;\n report.globalsSeen = Array.from(seenGlobals).sort();\n\n if (refs.length > 0) {\n const collected = await collectAssets(refs, {\n cwd: options.cwd,\n roots: options.roots,\n outputDir: options.outputDir,\n brotli: options.brotli,\n manifest: options.manifest,\n });\n manifest = collected.manifest;\n filesToEmit = collected.files;\n report.missingAssets = collected.missing;\n for (const missing of collected.missing) {\n this.warn(`[mini-three] asset not found in known roots: ${missing}`);\n }\n for (const [destination, source] of filesToEmit) {\n try {\n const content = await fs.readFile(source);\n this.emitFile({ type: 'asset', fileName: destination, source: content });\n } catch (error) {\n this.warn(`[mini-three] could not emit ${destination}: ${String(error)}`);\n }\n }\n } else {\n manifest = {\n generatedBy: 'mini-three-adapter',\n outputDir: options.outputDir ?? 'assets/three',\n entries: [],\n gameJsonSuggestion: {},\n decoderPaths: {},\n };\n }\n\n if (options.manifest !== false) {\n this.emitFile({\n type: 'asset',\n fileName: 'mini-three-assets.json',\n source: JSON.stringify({ ...manifest, build: report, output: bundleOptions.dir ?? bundleOptions.file ?? '' }, null, 2),\n });\n }\n if (options.report !== false) {\n this.warn(\n `[mini-three] build report: ${report.modulesScanned} module(s) scanned, ` +\n `${report.modulesRewritten} rewritten, ${report.rewrites} reference(s) -> scope, ` +\n `${filesToEmit.size} asset(s) emitted, ${report.missingAssets.length} missing.`,\n );\n }\n },\n\n api: {\n report: () => ({\n ...report,\n globalsSeen: Array.from(seenGlobals).sort(),\n assetReferences: Array.from(assetRefs),\n webgpuWarnings: [...report.webgpuWarnings],\n parseFailures: [...report.parseFailures],\n }),\n },\n };\n}\n","/**\n * AST-based global-to-scope rewriting.\n *\n * The reference adapter uses a Rollup \"prefix global\" pass that effectively\n * text-replaces identifiers. That breaks on shadowed locals, object keys, and\n * `typeof window` feature detection. Here we parse with @babel/parser and use\n * Babel's scope binding information, so ONLY free (unbound) references to\n * browser globals are rewritten — application code is never touched.\n */\nimport { parse } from '@babel/parser';\nimport _traverse from '@babel/traverse';\nimport MagicString from 'magic-string';\nimport type { NodePath } from '@babel/traverse';\nimport type { Identifier } from '@babel/types';\nimport type { Node } from '@babel/types';\n\n// Babel's CJS/ESM interop differs between bundlers; normalize once.\nconst traverse = (typeof _traverse === 'function'\n ? _traverse\n : (_traverse as unknown as { default: typeof _traverse }).default) as typeof _traverse;\n\nexport const DEFAULT_GLOBAL_NAMES: readonly string[] = [\n 'window', 'self', 'document', 'navigator', 'screen', 'location',\n 'innerWidth', 'innerHeight', 'outerWidth', 'outerHeight',\n 'devicePixelRatio', 'pageXOffset', 'pageYOffset',\n 'performance', 'requestAnimationFrame', 'cancelAnimationFrame',\n 'getComputedStyle', 'matchMedia', 'atob', 'btoa',\n 'Event', 'EventTarget', 'CustomEvent', 'PointerEvent', 'MouseEvent',\n 'TouchEvent', 'MessageEvent', 'ProgressEvent', 'KeyboardEvent', 'DOMException',\n 'HTMLElement', 'HTMLCanvasElement', 'HTMLImageElement', 'HTMLVideoElement',\n 'OffscreenCanvas', 'Image', 'ImageData', 'DOMRect',\n 'WebGLRenderingContext', 'WebGL2RenderingContext', 'AudioContext',\n 'Blob', 'URL', 'URLSearchParams', 'FileReader', 'TextDecoder', 'TextEncoder',\n 'AbortController', 'AbortSignal', 'fetch', 'XMLHttpRequest', 'WebSocket',\n 'createImageBitmap', 'Worker', 'WebAssembly', 'ResizeObserver',\n];\n\n/** Globals that must remain `undefined` in the mini game scope. */\nexport const DEFAULT_FORCE_UNDEF: readonly string[] = ['createImageBitmap'];\n\nexport interface RewriteOptions {\n /** Extra global identifiers to rewrite. */\n extraGlobals?: string[];\n /** Replace the default global list instead of extending it. */\n globals?: string[];\n /** Identifiers that must evaluate to `undefined` (feature-detection off). */\n forceUndef?: string[];\n /** Name of the injected scope accessor. Default `__m3`. */\n accessor?: string;\n /** Module specifier that exports `getActiveScope`. */\n scopeModule?: string;\n}\n\n/**\n * Minimal source-map shape accepted by Rollup / Vite as a transform result.\n * Declared locally so `dist/*.d.ts` stays self-contained (`rollup` is an\n * optional peer). `magic-string`'s `SourceMap` satisfies it structurally.\n */\nexport interface BuildSourceMap {\n version: number;\n file?: string;\n sources: string[];\n sourcesContent?: Array<string | null>;\n names: string[];\n mappings: string;\n}\n\nexport interface RewriteResult {\n code: string;\n map: BuildSourceMap | null;\n /** Number of rewritten references. */\n count: number;\n /** Globals actually seen (useful for the build report). */\n seen: string[];\n}\n\nexport interface RewriteFailure {\n code: string;\n error: string;\n}\n\nexport const SCOPE_IMPORT = (\n accessor: string,\n module: string,\n extraSpecifiers: readonly string[] = [],\n): string => {\n const specifiers = [`getActiveScope as ${accessor}`, ...extraSpecifiers].join(', ');\n return `import { ${specifiers} } from '${module}';\\n`;\n};\n\n/**\n * Reference or range equality. `@babel/parser` emits TWO distinct `Identifier`\n * nodes with identical `[start, end]` for a shorthand property (`{ X }`: one for\n * `key`, one for `value`), so reference equality alone is not enough to tell\n * \"this identifier is an object key\".\n */\nfunction sameNode(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n const x = a as { start?: number | null; end?: number | null } | null | undefined;\n const y = b as { start?: number | null; end?: number | null } | null | undefined;\n return Boolean(x && y && x.start != null && x.start === y.start && x.end === y.end);\n}\n\nfunction isNonComputedKey(path: NodePath): boolean {\n const parent = path.parentPath;\n if (!parent) return false;\n const self: unknown = path.node;\n if (parent.isObjectProperty() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\n if (parent.isObjectMethod() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\n if (parent.isClassProperty() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\n if (parent.isClassMethod() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\n if (parent.isMemberExpression() && !parent.node.computed && sameNode(parent.node.property, self)) return true;\n return false;\n}\n\n/**\n * `{ X }`: the value node shares its range with the key, so it cannot be\n * rewritten in place — it must be expanded to `{ X: <expr> }`.\n */\nfunction isShorthandValue(path: NodePath): boolean {\n const parent = path.parentPath;\n if (!parent?.isObjectProperty()) return false;\n if (!parent.node.shorthand || parent.node.computed) return false;\n if (parent.node.value !== path.node) return false;\n // `const { X } = obj` destructures a binding, never a global reference. Babel\n // already treats it as a binding, this guard keeps the two paths disjoint.\n return !parent.parentPath?.isObjectPattern();\n}\n\n/**\n * Is this identifier the left-most link of a `new X` / `new X.Y.Z` callee chain?\n *\n * `new f().g()` parses as `(new f()).g()`, so rewriting `X` to a *call*\n * (`__m3().X`) without parentheses silently turns `new X()` into\n * `(new __m3()).X()` — the scope object gets constructed and the class is then\n * invoked as a plain function. Wrapping only the chain root is enough:\n * `new (a().b).c` parses as `new ((a().b).c)`.\n */\nfunction isNewCalleeRoot(path: NodePath): boolean {\n let cur: NodePath = path;\n let parent = cur.parentPath;\n while (parent?.isMemberExpression() && parent.node.object === cur.node) {\n cur = parent;\n parent = parent.parentPath;\n }\n return Boolean(parent?.isNewExpression() && parent.node.callee === cur.node);\n}\n\n/** `typeof X` must never throw: `typeof a.b` is legal even when `a` is unbound. */\nfunction isDirectTypeofOperand(path: NodePath): boolean {\n const parent = path.parentPath;\n return Boolean(\n parent?.isUnaryExpression() &&\n parent.node.operator === 'typeof' &&\n parent.node.argument === path.node,\n );\n}\n\n/**\n * Globals that `getActiveScope()` resolves to itself even before a runtime\n * exists, so `typeof window` is already `'object'` and needs no guard.\n */\nconst ALWAYS_OBJECT_GLOBALS: ReadonlySet<string> = new Set(['window', 'self', 'globalThis']);\n\n/** Rewrite free browser-global references in one module. Returns null if nothing changed. */\nexport function rewriteGlobals(\n code: string,\n id: string,\n options: RewriteOptions = {},\n): RewriteResult | RewriteFailure | null {\n const names = new Set<string>([\n ...(options.globals ?? DEFAULT_GLOBAL_NAMES),\n ...(options.extraGlobals ?? []),\n ...(options.forceUndef ?? DEFAULT_FORCE_UNDEF),\n ]);\n const accessor = options.accessor ?? '__m3';\n const scopeModule = options.scopeModule ?? 'mini-three-adapter/scope';\n\n let ast;\n try {\n ast = parse(code, {\n sourceType: 'unambiguous',\n errorRecovery: true,\n plugins: ['importAttributes', 'classProperties', 'topLevelAwait', 'typescript', 'jsx'],\n });\n } catch (error) {\n return { code, error: `[mini-three] parse failed for ${id}: ${String(error)}` };\n }\n\n const ms = new MagicString(code);\n const seen = new Set<string>();\n const hasAccessor = `${accessor}Has`;\n let count = 0;\n let needsHasGuard = false;\n\n traverse(ast, {\n ReferencedIdentifier(path: NodePath<Node>) {\n const node = path.node as Identifier;\n const name = node.name;\n if (!name || !names.has(name)) return;\n if (node.start == null || node.end == null) return;\n // Babel scope knows about imports, function params, local declarations,\n // catch bindings and block-scoped shadowing. This is the critical check\n // that a regex-based replacement cannot perform.\n if (path.scope.hasBinding(name, true)) return;\n\n const ref = `${accessor}().${name}`;\n\n // 1) Shorthand must be handled before the key check: once `isNonComputedKey`\n // compares ranges, `{ X }`'s value looks like a key too and would be\n // silently skipped (leaving an undefined global behind).\n if (isShorthandValue(path)) {\n seen.add(name);\n ms.overwrite(node.start, node.end, `${name}: (${ref})`);\n count++;\n return;\n }\n\n // 2) Object keys / member property names are not references.\n if (isNonComputedKey(path)) return;\n\n seen.add(name);\n if (isDirectTypeofOperand(path) && !ALWAYS_OBJECT_GLOBALS.has(name)) {\n // `typeof X` must never throw. The placeholder scope answers the\n // environment globals (document/navigator/screen/...) with `undefined`\n // already, but everything else — TextDecoder, HTMLCanvasElement,\n // Blob, ... — throws an actionable error on access, and a `typeof`\n // probe must not become that error.\n ms.overwrite(node.start, node.end, `(${hasAccessor}() ? ${ref} : undefined)`);\n needsHasGuard = true;\n count++;\n return;\n }\n ms.overwrite(node.start, node.end, isNewCalleeRoot(path) ? `(${ref})` : ref);\n count++;\n },\n });\n\n if (count === 0) return null;\n ms.prepend(SCOPE_IMPORT(\n accessor,\n scopeModule,\n needsHasGuard ? [`hasActiveScope as ${hasAccessor}`] : [],\n ));\n return {\n code: ms.toString(),\n map: ms.generateMap({ source: id, includeContent: true, hires: true }),\n count,\n seen: Array.from(seen).sort(),\n };\n}\n","/**\n * Worker / WASM asset collection for three.js addons.\n *\n * DRACOLoader, KTX2Loader, 3DMLoader, LottieLoader, ... reference decoder\n * `.js` and `.wasm` files by string path. In a mini game those files are not\n * reachable via HTTP; they must be copied into the code package (ideally a\n * subpackage) and `setDecoderPath` must point at the copied location.\n *\n * The plugin scans transformed modules, resolves each referenced basename in a\n * small set of known directories, copies it, and emits a manifest plus a\n * `game.json` suggestion. No global state, no hidden writes.\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\n\nexport interface AssetOptions {\n /** Extra directories to search (besides three's jsm/libs). */\n roots?: string[];\n /** Output directory relative to the bundle root. Default 'assets/three'. */\n outputDir?: string;\n /** Copy `.wasm.br` alongside `.wasm` when available. Default true. */\n brotli?: boolean;\n /** Emit `mini-three-assets.json`. Default true. */\n manifest?: boolean;\n /** Working directory used to resolve roots. Default process.cwd(). */\n cwd?: string;\n}\n\nexport interface AssetEntry {\n /** Original string found in the module. */\n reference: string;\n /** Resolved absolute source path. */\n source: string;\n /** Relative destination inside the bundle. */\n destination: string;\n kind: 'worker' | 'wasm' | 'data';\n}\n\nexport interface AssetManifest {\n generatedBy: 'mini-three-adapter';\n outputDir: string;\n entries: AssetEntry[];\n /** Paste into game.json (adjust subpackage names to your project). */\n gameJsonSuggestion: Record<string, unknown>;\n /** Decoder paths to feed to loaders at runtime. */\n decoderPaths: Record<string, string>;\n}\n\nconst ASSET_PATTERN = /(['\"`])([^'\"`\\n]*\\.(?:wasm|wasm\\.br|bin|js))\\1/g;\nconst DECODER_KEYWORDS = [\n 'draco', 'basis', 'ktx2', 'rhino3dm', 'zstd', 'meshopt', 'ammo',\n 'worker', 'decoder', 'transcoder', 'lottie', 'sdf',\n];\n\nexport function collectAssetReferences(code: string): string[] {\n const found = new Set<string>();\n let match: RegExpExecArray | null;\n ASSET_PATTERN.lastIndex = 0;\n while ((match = ASSET_PATTERN.exec(code)) !== null) {\n const value = match[2] ?? '';\n const lower = value.toLowerCase();\n if (DECODER_KEYWORDS.some((keyword) => lower.includes(keyword))) found.add(value);\n }\n return Array.from(found);\n}\n\nasync function indexFiles(root: string, maxDepth = 5): Promise<Map<string, string>> {\n const index = new Map<string, string>();\n const walk = async (dir: string, depth: number): Promise<void> => {\n if (depth > maxDepth) return;\n let entries;\n try { entries = await fs.readdir(dir, { withFileTypes: true }); }\n catch { return; }\n for (const entry of entries) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) await walk(full, depth + 1);\n else if (entry.isFile() && !index.has(entry.name)) index.set(entry.name, full);\n }\n };\n await walk(root, 0);\n return index;\n}\n\nfunction classify(name: string): AssetEntry['kind'] {\n if (name.endsWith('.wasm') || name.endsWith('.wasm.br')) return 'wasm';\n if (name.endsWith('.js')) return 'worker';\n return 'data';\n}\n\nexport function defaultRoots(cwd: string): string[] {\n return [\n path.join(cwd, 'node_modules/three/examples/jsm/libs'),\n path.join(cwd, 'node_modules/three/examples/jsm'),\n path.join(cwd, 'node_modules/three-stdlib'),\n path.join(cwd, 'public'),\n path.join(cwd, 'static'),\n ];\n}\n\nexport interface CollectResult {\n manifest: AssetManifest;\n /** Files to write: destination (relative) -> absolute source. */\n files: Map<string, string>;\n missing: string[];\n}\n\n/** Resolve references against known roots without copying anything. */\nexport async function collectAssets(references: string[], options: AssetOptions = {}): Promise<CollectResult> {\n const cwd = options.cwd ?? process.cwd();\n const outputDir = (options.outputDir ?? 'assets/three').replace(/\\\\/g, '/').replace(/\\/$/, '');\n const roots = [...defaultRoots(cwd), ...(options.roots ?? [])];\n const indexes = await Promise.all(roots.map((root) => indexFiles(root)));\n const find = (name: string): string | undefined => {\n for (const index of indexes) {\n const hit = index.get(name);\n if (hit) return hit;\n }\n return undefined;\n };\n\n const entries: AssetEntry[] = [];\n const files = new Map<string, string>();\n const missing: string[] = [];\n\n for (const reference of references) {\n const base = path.posix.basename(reference.split('?')[0] ?? reference);\n const source = find(base);\n if (!source) { missing.push(reference); continue; }\n const entry: AssetEntry = {\n reference,\n source,\n destination: `${outputDir}/${base}`,\n kind: classify(base),\n };\n entries.push(entry);\n files.set(entry.destination, source);\n if (options.brotli !== false && entry.kind === 'wasm') {\n const br = find(`${base}.br`);\n if (br) {\n entries.push({ reference: `${reference}.br`, source: br, destination: `${outputDir}/${base}.br`, kind: 'wasm' });\n files.set(`${outputDir}/${base}.br`, br);\n }\n }\n }\n\n const decoderPaths: Record<string, string> = {};\n for (const entry of entries) {\n const name = path.posix.basename(entry.destination).toLowerCase();\n for (const key of ['draco', 'ktx2', 'basis', 'meshopt', 'rhino3dm', 'zstd', 'ammo']) {\n if (name.includes(key)) decoderPaths[key] = `${outputDir}/`;\n }\n }\n\n const manifest: AssetManifest = {\n generatedBy: 'mini-three-adapter',\n outputDir,\n entries,\n gameJsonSuggestion: {\n workers: { path: `${outputDir}`, isSubpackage: true },\n subpackages: [{ name: 'three-assets', root: `${outputDir}/` }],\n },\n decoderPaths,\n };\n return { manifest, files, missing };\n}\n\n/** Copy resolved files into `outDir`. */\nexport async function copyAssets(files: Map<string, string>, outDir: string): Promise<number> {\n let written = 0;\n for (const [destination, source] of files) {\n const target = path.join(outDir, destination);\n await fs.mkdir(path.dirname(target), { recursive: true });\n await fs.copyFile(source, target);\n written++;\n }\n return written;\n}\n","/** Vite entry: `import miniThree from 'mini-three-adapter/vite'`. */\nimport { miniThreePlugin, type MiniThreePlugin, type MiniThreePluginOptions } from './plugin-core';\n\nexport interface ViteMiniThreePlugin extends MiniThreePlugin {\n config(): Record<string, unknown>;\n}\n\n/**\n * Vite plugin. `optimizeDeps.exclude` keeps three's ESM sources intact so the\n * AST rewrite sees the original module graph instead of a pre-bundled blob.\n */\nexport function miniThree(options: MiniThreePluginOptions = {}): ViteMiniThreePlugin {\n const core = miniThreePlugin(options);\n return {\n ...core,\n config() {\n return {\n optimizeDeps: {\n exclude: ['three', 'three-stdlib', 'three/examples/jsm'],\n },\n build: {\n commonjsOptions: { transformMixedEsModules: true },\n rollupOptions: {\n output: {\n manualChunks: undefined,\n },\n },\n },\n };\n },\n };\n}\n\nexport default miniThree;\nexport { miniThreePlugin } from './plugin-core';\nexport type { MiniThreePluginOptions, BuildReport } from './plugin-core';\n"],"mappings":";AASA,SAAS,YAAYA,WAAU;;;ACA/B,SAAS,aAAa;AACtB,OAAO,eAAe;AACtB,OAAO,iBAAiB;AAMxB,IAAM,WAAY,OAAO,cAAc,aACnC,YACC,UAAuD;AAErD,IAAM,uBAA0C;AAAA,EACrD;AAAA,EAAU;AAAA,EAAQ;AAAA,EAAY;AAAA,EAAa;AAAA,EAAU;AAAA,EACrD;AAAA,EAAc;AAAA,EAAe;AAAA,EAAc;AAAA,EAC3C;AAAA,EAAoB;AAAA,EAAe;AAAA,EACnC;AAAA,EAAe;AAAA,EAAyB;AAAA,EACxC;AAAA,EAAoB;AAAA,EAAc;AAAA,EAAQ;AAAA,EAC1C;AAAA,EAAS;AAAA,EAAe;AAAA,EAAe;AAAA,EAAgB;AAAA,EACvD;AAAA,EAAc;AAAA,EAAgB;AAAA,EAAiB;AAAA,EA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AAE,KAAK;AAAA,QAC1C,iBAAiB,MAAM,KAAK,SAAS;AAAA,QACrC,gBAAgB,CAAC,GAAG,OAAO,cAAc;AAAA,QACzC,eAAe,CAAC,GAAG,OAAO,aAAa;AAAA,MACzC;AAAA,IACF;AAAA,EACF;AACF;;;AGzMO,SAAS,UAAU,UAAkC,CAAC,GAAwB;AACnF,QAAM,OAAO,gBAAgB,OAAO;AACpC,SAAO;AAAA,IACL,GAAG;AAAA,IACH,SAAS;AACP,aAAO;AAAA,QACL,cAAc;AAAA,UACZ,SAAS,CAAC,SAAS,gBAAgB,oBAAoB;AAAA,QACzD;AAAA,QACA,OAAO;AAAA,UACL,iBAAiB,EAAE,yBAAyB,KAAK;AAAA,UACjD,eAAe;AAAA,YACb,QAAQ;AAAA,cACN,cAAc;AAAA,YAChB;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AAEA,IAAO,eAAQ;","names":["fs","path","fs"]}
@@ -1,8 +1,40 @@
1
- import { createDiagnostics, detectCapabilities, createImageFactory, createRuntime } from './chunk-ZFJLEEF4.js';
1
+ import { createDiagnostics, detectCapabilities, createImageFactory, createRuntime } from './chunk-V64V4HIZ.js';
2
+ import { patchEventTarget } from './chunk-U3P3XHA3.js';
2
3
 
3
4
  // src/platforms/browser.ts
5
+ function hostEvents() {
6
+ return globalThis;
7
+ }
8
+ function ctorFor(type) {
9
+ var _a;
10
+ const host = hostEvents();
11
+ if (type.startsWith("pointer")) return host.PointerEvent;
12
+ if (type === "wheel") return (_a = host.WheelEvent) != null ? _a : host.MouseEvent;
13
+ if (type.startsWith("mouse") || type === "click") return host.MouseEvent;
14
+ return void 0;
15
+ }
16
+ function createNativeEvent(type, init) {
17
+ const Ctor = ctorFor(type);
18
+ if (Ctor) {
19
+ try {
20
+ return new Ctor(type, init);
21
+ } catch {
22
+ }
23
+ }
24
+ const Base = hostEvents().Event;
25
+ if (!Base) return { type, ...init };
26
+ const base = new Base(type, { bubbles: init.bubbles, cancelable: init.cancelable });
27
+ for (const [key, value] of Object.entries(init)) {
28
+ if (key in base) continue;
29
+ try {
30
+ Object.defineProperty(base, key, { value, configurable: true, enumerable: true, writable: true });
31
+ } catch {
32
+ }
33
+ }
34
+ return base;
35
+ }
4
36
  function createMockCanvas(width = 1, height = 1) {
5
- return {
37
+ const canvas = {
6
38
  width,
7
39
  height,
8
40
  getContext: () => ({
@@ -12,6 +44,8 @@ function createMockCanvas(width = 1, height = 1) {
12
44
  }),
13
45
  toDataURL: () => "data:,"
14
46
  };
47
+ patchEventTarget(canvas);
48
+ return canvas;
15
49
  }
16
50
  function browserWx() {
17
51
  const host = globalThis;
@@ -95,6 +129,7 @@ function createBrowserBinding(options = {}) {
95
129
  return { top: 0, left: 0, width: rawCanvas.width, height: rawCanvas.height, right: rawCanvas.width, bottom: rawCanvas.height };
96
130
  };
97
131
  const watchTouch = (handler) => {
132
+ if (typeof hostEvents().PointerEvent === "function") return () => void 0;
98
133
  const element = rawCanvas;
99
134
  if (typeof element.addEventListener !== "function") return () => void 0;
100
135
  const names = ["touchstart", "touchmove", "touchend", "touchcancel"];
@@ -116,6 +151,10 @@ function createBrowserBinding(options = {}) {
116
151
  wx,
117
152
  rawCanvas,
118
153
  capabilities,
154
+ // A browser canvas already owns its event system: the runtime must not
155
+ // replace it. See ADR-0010.
156
+ nativeEventTarget: true,
157
+ createEvent: createNativeEvent,
119
158
  imageFactory: createImageFactory(wx, diagnostics),
120
159
  getCanvasRect,
121
160
  createOffscreenCanvas: (width, height, _type) => {
@@ -141,5 +180,5 @@ function createBrowserRuntime(options = {}) {
141
180
  }
142
181
 
143
182
  export { createBrowserBinding, createBrowserRuntime };
144
- //# sourceMappingURL=chunk-F7CSLEUI.js.map
145
- //# sourceMappingURL=chunk-F7CSLEUI.js.map
183
+ //# sourceMappingURL=chunk-7XOHQFZ6.js.map
184
+ //# sourceMappingURL=chunk-7XOHQFZ6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/platfor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IACjD,OAAA,EAAS,MAAM,WAAA,CAAY,KAAA,CAAM,0BAA0B;AAAA,GAC7D;AACF;AAIO,SAAS,oBAAA,CAAqB,OAAA,GAAiC,EAAC,EAA8B;AACnG,EAAA,OAAO,aAAA,CAAc,MAAM,oBAAA,CAAqB,OAAO,GAAG,OAAO,CAAA;AACnE","file":"chunk-7XOHQFZ6.js","sourcesContent":["/**\n * Browser platform. Used for H5 dual-target builds (uni-app / weapp-vite H5)\n * and for running the adapter in Node-based unit tests with an injected canvas.\n *\n * The whole point of scoped globals is that the SAME application code can run\n * here without uninstalling a `window` shim first.\n */\nimport type { Capabilities, ContextType, Disposer, NativeEventInit, Rect, TouchLikeEvent } from '../types';\nimport type { PlatformBinding } from '../core/platform';\nimport { createRuntime, type MiniThreeRuntime, type RuntimeOptions } from '../core/runtime';\nimport { detectCapabilities } from '../core/capabilities';\nimport { createDiagnostics, type Diagnostics } from '../core/diagnostics';\nimport { createImageFactory } from '../core/image';\nimport { patchEventTarget } from '../polyfills/event';\nimport type { WxCanvas, WxLike, WxWindowInfo } from './wx-types';\n\ntype NativeEventCtor = new (type: string, init?: Record<string, unknown>) => object;\n\nfunction hostEvents(): {\n PointerEvent?: NativeEventCtor;\n MouseEvent?: NativeEventCtor;\n WheelEvent?: NativeEventCtor;\n Event?: NativeEventCtor;\n} {\n return globalThis as unknown as {\n PointerEvent?: NativeEventCtor;\n MouseEvent?: NativeEventCtor;\n WheelEvent?: NativeEventCtor;\n Event?: NativeEventCtor;\n };\n}\n\n/**\n * Specialised constructors only. Falling back to `Event` here would silently\n * drop `clientX` / `pointerId`, because `new Event(type, init)` ignores them;\n * the generic path below fills those fields explicitly instead.\n */\nfunction ctorFor(type: string): NativeEventCtor | undefined {\n const host = hostEvents();\n if (type.startsWith('pointer')) return host.PointerEvent;\n if (type === 'wheel') return host.WheelEvent ?? host.MouseEvent;\n if (type.startsWith('mouse') || type === 'click') return host.MouseEvent;\n return undefined;\n}\n\n/**\n * Build a real DOM event. Falls back to `Event` plus own properties when the\n * host lacks the specialised constructor (old WebViews, Node tests): a plain\n * `Event` is what `dispatchEvent` accepts, and the extra fields keep readers\n * like OrbitControls working.\n */\nfunction createNativeEvent(type: string, init: NativeEventInit): unknown {\n const Ctor = ctorFor(type);\n if (Ctor) {\n try {\n return new Ctor(type, init as Record<string, unknown>);\n } catch {\n /* constructor rejected a field; use the generic path below */\n }\n }\n const Base = hostEvents().Event;\n if (!Base) return { type, ...init };\n const base = new Base(type, { bubbles: init.bubbles, cancelable: init.cancelable });\n for (const [key, value] of Object.entries(init)) {\n if (key in base) continue;\n try {\n Object.defineProperty(base, key, { value, configurable: true, enumerable: true, writable: true });\n } catch {\n /* non-extensible host event */\n }\n }\n return base;\n}\n\nexport interface BrowserPlatformOptions {\n canvas?: HTMLCanvasElement;\n capabilities?: Partial<Capabilities>;\n diagnostics?: Diagnostics;\n}\n\nfunction createMockCanvas(width = 1, height = 1): WxCanvas {\n const canvas: WxCanvas = {\n width,\n height,\n getContext: () => ({\n canvas: null,\n getExtension: () => null,\n getParameter: () => 0,\n }),\n toDataURL: () => 'data:,',\n };\n // No `document` (Node tests): this stand-in has no native event system, so\n // give it one before the runtime treats it as a native target.\n patchEventTarget(canvas);\n return canvas;\n}\n\nfunction browserWx(): WxLike {\n const host = globalThis as unknown as {\n window?: Window;\n document?: Document;\n innerWidth?: number;\n innerHeight?: number;\n devicePixelRatio?: number;\n };\n const resizeListeners = new Set<(info: { windowWidth: number; windowHeight: number }) => void>();\n const onResize = (): void => {\n for (const listener of resizeListeners) {\n listener({ windowWidth: host.innerWidth ?? 1, windowHeight: host.innerHeight ?? 1 });\n }\n };\n if (host.window && typeof host.window.addEventListener === 'function') {\n host.window.addEventListener('resize', onResize);\n }\n const info = (): WxWindowInfo => ({\n windowWidth: host.innerWidth ?? host.document?.documentElement?.clientWidth ?? 1,\n windowHeight: host.innerHeight ?? host.document?.documentElement?.clientHeight ?? 1,\n pixelRatio: host.devicePixelRatio ?? 1,\n });\n\n return {\n getWindowInfo: info,\n onWindowResize: (listener) => { resizeListeners.add(listener); },\n offWindowResize: (listener) => { resizeListeners.delete(listener); },\n createCanvas: () => (host.document\n ? (host.document.createElement('canvas') as unknown as WxCanvas)\n : createMockCanvas()),\n createOffscreenCanvas: ({ width = 1, height = 1 } = {}) => {\n if (typeof OffscreenCanvas !== 'undefined') {\n return new OffscreenCanvas(width, height) as unknown as WxCanvas;\n }\n const c = host.document\n ? (host.document.createElement('canvas') as unknown as WxCanvas)\n : createMockCanvas(width, height);\n c.width = width;\n c.height = height;\n return c;\n },\n createImage: () => (host.document\n ? (host.document.createElement('img') as unknown as ReturnType<NonNullable<WxLike['createImage']>>)\n : ({} as ReturnType<NonNullable<WxLike['createImage']>>)),\n request: (options) => {\n const nativeFetch = (globalThis as unknown as Record<string, unknown>).fetch as\n | ((url: string, init?: unknown) => Promise<unknown>)\n | undefined;\n if (!nativeFetch) { options.fail?.({ errMsg: 'fetch unavailable' }); return {}; }\n void nativeFetch(String(options.url), { method: options.method, headers: options.header })\n .then(async (response) => {\n const res = response as { status: number; headers: Headers; arrayBuffer(): Promise<ArrayBuffer> };\n const data = options.responseType === 'arraybuffer' ? await res.arrayBuffer() : await (response as Response).text();\n const header: Record<string, string> = {};\n res.headers?.forEach?.((value: string, key: string) => { header[key] = value; });\n options.success?.({ statusCode: res.status, data, header });\n })\n .catch((error: unknown) => options.fail?.({ errMsg: String(error) }));\n return {};\n },\n } as WxLike;\n}\n\nexport function createBrowserBinding(options: BrowserPlatformOptions = {}): PlatformBinding {\n const wx = browserWx();\n const diagnostics = options.diagnostics ?? createDiagnostics('warn');\n const host = globalThis as unknown as {\n document?: Document;\n requestAnimationFrame?: (cb: (time: number) => void) => number;\n cancelAnimationFrame?: (id: number) => void;\n performance?: Performance;\n };\n const rawCanvas = (options.canvas ?? wx.createCanvas?.()) as WxCanvas;\n if (!rawCanvas) throw new Error('[mini-three-adapter] no canvas available in browser platform');\n\n const capabilities = detectCapabilities(wx, 'browser', {\n overrides: { webgl2: true, webgl1: true, worker: true, wasm: true, ...options.capabilities },\n });\n\n const getCanvasRect = (): Rect => {\n const rect = (rawCanvas as unknown as HTMLCanvasElement).getBoundingClientRect?.();\n if (rect && rect.width > 0) {\n return { top: rect.top, left: rect.left, width: rect.width, height: rect.height, right: rect.right, bottom: rect.bottom };\n }\n return { top: 0, left: 0, width: rawCanvas.width, height: rawCanvas.height, right: rawCanvas.width, bottom: rawCanvas.height };\n };\n\n const watchTouch = (handler: (event: TouchLikeEvent) => void): Disposer => {\n // A real canvas owns a trusted pointer stream already. Synthesising a\n // second one from touch* would double-deliver every gesture, so only old\n // hosts without PointerEvent fall back to the bridge.\n if (typeof hostEvents().PointerEvent === 'function') return () => undefined;\n const element = rawCanvas as unknown as HTMLCanvasElement;\n if (typeof element.addEventListener !== 'function') return () => undefined;\n const names = ['touchstart', 'touchmove', 'touchend', 'touchcancel'];\n const forward = (event: Event): void => handler(event as unknown as TouchLikeEvent);\n for (const name of names) element.addEventListener(name, forward, { passive: true });\n return () => {\n for (const name of names) element.removeEventListener(name, forward);\n };\n };\n\n const watchVisibility = (handler: (visible: boolean) => void): Disposer => {\n const doc = host.document;\n if (!doc) return () => undefined;\n const forward = (): void => handler(doc.visibilityState !== 'hidden');\n doc.addEventListener('visibilitychange', forward);\n return () => doc.removeEventListener('visibilitychange', forward);\n };\n\n return {\n kind: 'browser',\n wx,\n rawCanvas,\n capabilities,\n // A browser canvas already owns its event system: the runtime must not\n // replace it. See ADR-0010.\n nativeEventTarget: true,\n createEvent: createNativeEvent,\n imageFactory: createImageFactory(wx, diagnostics),\n getCanvasRect,\n createOffscreenCanvas: (width: number, height: number, _type: ContextType) => {\n const c = wx.createOffscreenCanvas?.({ width, height, type: '2d' }) ?? createMockCanvas(width, height);\n c.width = width;\n c.height = height;\n return c;\n },\n watchTouch,\n watchVisibility,\n requestAnimationFrame: (cb) => host.requestAnimationFrame\n ? host.requestAnimationFrame(cb)\n : (setTimeout(() => cb(Date.now()), 16) as unknown as number),\n cancelAnimationFrame: (id) => host.cancelAnimationFrame\n ? host.cancelAnimationFrame(id)\n : clearTimeout(id as unknown as ReturnType<typeof setTimeout>),\n now: () => host.performance?.now?.() ?? Date.now(),\n dispose: () => diagnostics.debug('browser binding disposed'),\n };\n}\n\nexport type BrowserRuntimeOptions = BrowserPlatformOptions & RuntimeOptions;\n\nexport function createBrowserRuntime(options: BrowserRuntimeOptions = {}): Promise<MiniThreeRuntime> {\n return createRuntime(() => createBrowserBinding(options), options);\n}\n"]}
@@ -1,5 +1,5 @@
1
- import { resolveWx, probeContext, createWechatImageFactory, createRafPair, createNow, rectFromSelectorResult, createOffscreenCanvasRaw, watchWxVisibility } from './chunk-VA7SZFLN.js';
2
- import { createDiagnostics, detectCapabilities, createRuntime } from './chunk-ZFJLEEF4.js';
1
+ import { resolveWx, probeContext, createWechatImageFactory, createRafPair, createNow, rectFromSelectorResult, createOffscreenCanvasRaw, watchWxVisibility } from './chunk-HKT54DDM.js';
2
+ import { createDiagnostics, detectCapabilities, createRuntime } from './chunk-V64V4HIZ.js';
3
3
 
4
4
  // src/platforms/wechat-miniprogram.ts
5
5
  function queryNode(ctx, selector, delay) {
@@ -91,5 +91,5 @@ function createWeChatMiniProgramRuntime(options) {
91
91
  }
92
92
 
93
93
  export { createWeChatMiniProgramBinding, createWeChatMiniProgramRuntime };
94
- //# sourceMappingURL=chunk-LE4FRYNG.js.map
95
- //# sourceMappingURL=chunk-LE4FRYNG.js.map
94
+ //# sourceMappingURL=chunk-DDCQIBWW.js.map
95
+ //# sourceMappingURL=chunk-DDCQIBWW.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/platforms/wechat-miniprogram.ts"],"names":[],"mappings":";;;;AAiCA,SAAS,SAAA,CACP,GAAA,EACA,QAAA,EACA,KAAA,EAC4D;AAC5D,EAAA,OAAO,IAAI,OAAA,CAAQ,CAAC,OAAA,EAAS,MAAA,KAAW;AACtC,IAAA,MAAM,MAAM,MAAY;AACtB,MAAA,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AAA;AAAA,IAC3B,sBAAsB,GAAA,CAAI,MAAA;AAAA,IAC1B,GAAA;AAAA,IACA,OAAA,EAAS,MAAM,WAAA,CAAY,KAAA,CAAM,qCAAqC;AAAA,GACxE;AACF;AAIO,SAAS,+BACd,OAAA,EAC2B;AAC3B,EAAA,OAAO,aAAA,CAAc,MAAM,8BAAA,CAA+B,OAAO,GAAG,OAAO,CAAA;AAC7E","file":"chunk-LE4FRYNG.js","sourcesContent":["/** WeChat Mini Program (小程序, canvas type=\"webgl2\") platform binding. */\nimport type { Capabilities, ContextType, Disposer, Rect, TouchLikeEvent } from '../types';\nimport type { PlatformBinding } from '../core/platform';\nimport { createRuntime, type MiniThreeRuntime, type RuntimeOptions } from '../core/runtime';\nimport { detectCapabilities } from '../core/capabilities';\nimport { createDiagnostics, type Diagnostics } from '../core/diagnostics';\nimport {\n createNow,\n createOffscreenCanvasRaw,\n createRafPair,\n createWechatImageFactory,\n probeContext,\n rectFromSelectorResult,\n watchWxVisibility,\n} from './wechat-common';\nimport { resolveWx, type WxCanvas, type WxLike, type WxSelectorQuery, type WxSelectorQueryResult } from './wx-types';\n\nexport interface SelectorCtx {\n createSelectorQuery(): WxSelectorQuery;\n}\n\nexport interface WeChatMiniProgramOptions {\n wx?: WxLike;\n /** CSS selector of the `<canvas type=\"webgl2\">` node. */\n selector: string;\n /** Inside a custom component, pass `this` so the query is scoped correctly. */\n selectorCtx?: SelectorCtx;\n /** Milliseconds to wait for layout before querying (uni-app needs a tick). */\n queryDelay?: number;\n capabilities?: Partial<Capabilities>;\n diagnostics?: Diagnostics;\n}\n\nfunction queryNode(\n ctx: SelectorCtx | WxLike,\n selector: string,\n delay: number,\n): Promise<{ node: WxCanvas; result: WxSelectorQueryResult }> {\n return new Promise((resolve, reject) => {\n const run = (): void => {\n try {\n const create = ctx.createSelectorQuery;\n if (typeof create !== 'function') {\n reject(new Error('[mini-three-adapter] createSelectorQuery is unavailable; pass a valid selectorCtx'));\n return;\n }\n const query = create.call(ctx);\n query\n .select(selector)\n .fields({ node: true, id: true, rect: true, size: true })\n .exec((results) => {\n const result = results?.[0];\n if (!result?.node) {\n reject(new Error(\n `[mini-three-adapter] selector \"${selector}\" returned no canvas node. ` +\n 'Ensure <canvas type=\"webgl2\" id=\"...\"> exists and the component is rendered.',\n ));\n return;\n }\n resolve({ node: result.node, result });\n });\n } catch (error) {\n reject(error instanceof Error ? error : new Error(String(error)));\n }\n };\n if (delay > 0) setTimeout(run, delay);\n else run();\n });\n}\n\nexport async function createWeChatMiniProgramBinding(\n options: WeChatMiniProgramOptions,\n): Promise<PlatformBinding> {\n const wx = resolveWx(options.wx);\n const diagnostics = options.diagnostics ?? createDiagnostics('warn');\n const ctx = options.selectorCtx ?? wx;\n const { node, result } = await queryNode(ctx, options.selector, options.queryDelay ?? 0);\n const rawCanvas = node;\n const capabilities = detectCapabilities(wx, 'wechat-miniprogram', {\n overrides: options.capabilities,\n diagnostics,\n // No createCanvas() fallback here: the canvas node comes from a selector\n // query and probing it directly would create the real GL context with\n // default attributes before three.js asks for its own.\n probeContext: (type) => probeContext(wx, type),\n });\n const imageFactory = createWechatImageFactory(wx, diagnostics);\n const raf = createRafPair(wx, rawCanvas);\n const now = createNow(wx);\n let lastRect = rectFromSelectorResult(result);\n\n const getCanvasRect = async (): Promise<Rect> => {\n const fresh = await queryNode(ctx, options.selector, 0);\n lastRect = rectFromSelectorResult(fresh.result);\n return lastRect;\n };\n\n const watchVisibility = (handler: (visible: boolean) => void): Disposer => {\n const host = wx as Record<string, unknown>;\n const onShow = (): void => handler(true);\n const onHide = (): void => handler(false);\n if (typeof host.onAppShow === 'function') (host.onAppShow as (l: () => void) => void).call(wx, onShow);\n if (typeof host.onAppHide === 'function') (host.onAppHide as (l: () => void) => void).call(wx, onHide);\n const fallback = watchWxVisibility(wx, handler);\n return () => {\n if (typeof host.offAppShow === 'function') (host.offAppShow as (l: () => void) => void).call(wx, onShow);\n if (typeof host.offAppHide === 'function') (host.offAppHide as (l: () => void) => void).call(wx, onHide);\n fallback();\n };\n };\n\n diagnostics.info('mini program canvas resolved', { selector: options.selector, rect: lastRect });\n\n return {\n kind: 'wechat-miniprogram',\n wx,\n rawCanvas,\n capabilities,\n imageFactory,\n getCanvasRect,\n createOffscreenCanvas: (width: number, height: number, type: ContextType) =>\n createOffscreenCanvasRaw(wx, width, height, type, diagnostics),\n // Mini programs deliver touch events through WXML bindings, not wx.onTouch*.\n // The app must forward them: <canvas @touchstart=\"runtime.handleTouch\" ... />\n watchTouch: (_handler: (event: TouchLikeEvent) => void): Disposer => () => undefined,\n watchVisibility,\n requestAnimationFrame: raf.request,\n cancelAnimationFrame: raf.cancel,\n now,\n dispose: () => diagnostics.debug('wechat-miniprogram binding disposed'),\n };\n}\n\nexport type WeChatMiniProgramRuntimeOptions = WeChatMiniProgramOptions & RuntimeOptions;\n\nexport function createWeChatMiniProgramRuntime(\n options: WeChatMiniProgramRuntimeOptions,\n): Promise<MiniThreeRuntime> {\n return createRuntime(() => createWeChatMiniProgramBinding(options), options);\n}\n"]}
1
+ {"version":3,"sources":["../src/platforms/wechat-miniprogram.ts"],"names":[],"mappings":";;;;AAiCA,SAAS,SAAA,CACP,GAAA,EACA,QAAA,EACA,KAAA,EAC4D;AAC5D,EAAA,OAAO,IAAI,OAAA,CAAQ,CAAC,OAAA,EAAS,MAAA,KAAW;AACtC,IAAA,MAAM,MAAM,MAAY;AACtB,MAAA,IAAI;AACF,QAAA,MAAM,SAAS,GAAA,CAAI,mBAAA;AACnB,QAAA,IAAI,OAAO,WAAW,UAAA,EAAY;AAChC,UAAA,MAAA,CAAO,IAAI,KAAA,CAAM,mFAAmF,CAAC,CAAA;AACrG,UAAA;AAAA,QACF;AACA,QAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,IAAA,CAAK,GAAG,CAAA;AAC7B,QAAA,KAAA,CACG,OAAO,QAAQ,CAAA,CACf,MAAA,CAAO,EAAE,MAAM,IAAA,EAAM,EAAA,EAAI,IAAA,EAAM,IAAA,EA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IAAA,MAAM,QAAA,GAAW,iBAAA,CAAkB,EAAA,EAAI,OAAO,CAAA;AAC9C,IAAA,OAAO,MAAM;AACX,MAAA,IAAI,OAAO,KAAK,UAAA,KAAe,UAAA,EAAa,IAAA,CAAK,UAAA,CAAuC,IAAA,CAAK,EAAA,EAAI,MAAM,CAAA;AACvG,MAAA,IAAI,OAAO,KAAK,UAAA,KAAe,UAAA,EAAa,IAAA,CAAK,UAAA,CAAuC,IAAA,CAAK,EAAA,EAAI,MAAM,CAAA;AACvG,MAAA,QAAA,EAAS;AAAA,IACX,CAAA;AAAA,EACF,CAAA;AAEA,EAAA,WAAA,CAAY,IAAA,CAAK,gCAAgC,EAAE,QAAA,EAAU,QAAQ,QAAA,EAAU,IAAA,EAAM,UAAU,CAAA;AAE/F,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,oBAAA;AAAA,IACN,EAAA;AAAA,IACA,SAAA;AAAA,IACA,YAAA;AAAA,IACA,YAAA;AAAA,IACA,aAAA;AAAA,IACA,qBAAA,EAAuB,CAAC,KAAA,EAAe,MAAA,EAAgB,IAAA,KACrD,yBAAyB,EAAA,EAAI,KAAA,EAAO,MAAA,EAAQ,IAAA,EAAM,WAAW,CAAA;AAAA;AAAA;AAAA,IAG/D,UAAA,EAAY,CAAC,QAAA,KAAwD,MAAM,MAAA;AAAA,IAC3E,eAAA;AAAA,IACA,uBAAuB,GAAA,CAAI,OAAA;AAAA,IAC3B,sBAAsB,GAAA,CAAI,MAAA;AAAA,IAC1B,GAAA;AAAA,IACA,OAAA,EAAS,MAAM,WAAA,CAAY,KAAA,CAAM,qCAAqC;AAAA,GACxE;AACF;AAIO,SAAS,+BACd,OAAA,EAC2B;AAC3B,EAAA,OAAO,aAAA,CAAc,MAAM,8BAAA,CAA+B,OAAO,GAAG,OAAO,CAAA;AAC7E","file":"chunk-DDCQIBWW.js","sourcesContent":["/** WeChat Mini Program (小程序, canvas type=\"webgl2\") platform binding. */\nimport type { Capabilities, ContextType, Disposer, Rect, TouchLikeEvent } from '../types';\nimport type { PlatformBinding } from '../core/platform';\nimport { createRuntime, type MiniThreeRuntime, type RuntimeOptions } from '../core/runtime';\nimport { detectCapabilities } from '../core/capabilities';\nimport { createDiagnostics, type Diagnostics } from '../core/diagnostics';\nimport {\n createNow,\n createOffscreenCanvasRaw,\n createRafPair,\n createWechatImageFactory,\n probeContext,\n rectFromSelectorResult,\n watchWxVisibility,\n} from './wechat-common';\nimport { resolveWx, type WxCanvas, type WxLike, type WxSelectorQuery, type WxSelectorQueryResult } from './wx-types';\n\nexport interface SelectorCtx {\n createSelectorQuery(): WxSelectorQuery;\n}\n\nexport interface WeChatMiniProgramOptions {\n wx?: WxLike;\n /** CSS selector of the `<canvas type=\"webgl2\">` node. */\n selector: string;\n /** Inside a custom component, pass `this` so the query is scoped correctly. */\n selectorCtx?: SelectorCtx;\n /** Milliseconds to wait for layout before querying (uni-app needs a tick). */\n queryDelay?: number;\n capabilities?: Partial<Capabilities>;\n diagnostics?: Diagnostics;\n}\n\nfunction queryNode(\n ctx: SelectorCtx | WxLike,\n selector: string,\n delay: number,\n): Promise<{ node: WxCanvas; result: WxSelectorQueryResult }> {\n return new Promise((resolve, reject) => {\n const run = (): void => {\n try {\n const create = ctx.createSelectorQuery;\n if (typeof create !== 'function') {\n reject(new Error('[mini-three-adapter] createSelectorQuery is unavailable; pass a valid selectorCtx'));\n return;\n }\n const query = create.call(ctx);\n query\n .select(selector)\n .fields({ node: true, id: true, rect: true, size: true })\n .exec((results) => {\n const result = results?.[0];\n if (!result?.node) {\n reject(new Error(\n `[mini-three-adapter] selector \"${selector}\" returned no canvas node. ` +\n 'Ensure <canvas type=\"webgl2\" id=\"...\"> exists and the component is rendered.',\n ));\n return;\n }\n resolve({ node: result.node, result });\n });\n } catch (error) {\n reject(error instanceof Error ? error : new Error(String(error)));\n }\n };\n if (delay > 0) setTimeout(run, delay);\n else run();\n });\n}\n\nexport async function createWeChatMiniProgramBinding(\n options: WeChatMiniProgramOptions,\n): Promise<PlatformBinding> {\n const wx = resolveWx(options.wx);\n const diagnostics = options.diagnostics ?? createDiagnostics('warn');\n const ctx = options.selectorCtx ?? wx;\n const { node, result } = await queryNode(ctx, options.selector, options.queryDelay ?? 0);\n const rawCanvas = node;\n const capabilities = detectCapabilities(wx, 'wechat-miniprogram', {\n overrides: options.capabilities,\n diagnostics,\n // No createCanvas() fallback here: the canvas node comes from a selector\n // query and probing it directly would create the real GL context with\n // default attributes before three.js asks for its own.\n probeContext: (type) => probeContext(wx, type),\n });\n const imageFactory = createWechatImageFactory(wx, diagnostics);\n const raf = createRafPair(wx, rawCanvas);\n const now = createNow(wx);\n let lastRect = rectFromSelectorResult(result);\n\n const getCanvasRect = async (): Promise<Rect> => {\n const fresh = await queryNode(ctx, options.selector, 0);\n lastRect = rectFromSelectorResult(fresh.result);\n return lastRect;\n };\n\n const watchVisibility = (handler: (visible: boolean) => void): Disposer => {\n const host = wx as Record<string, unknown>;\n const onShow = (): void => handler(true);\n const onHide = (): void => handler(false);\n if (typeof host.onAppShow === 'function') (host.onAppShow as (l: () => void) => void).call(wx, onShow);\n if (typeof host.onAppHide === 'function') (host.onAppHide as (l: () => void) => void).call(wx, onHide);\n const fallback = watchWxVisibility(wx, handler);\n return () => {\n if (typeof host.offAppShow === 'function') (host.offAppShow as (l: () => void) => void).call(wx, onShow);\n if (typeof host.offAppHide === 'function') (host.offAppHide as (l: () => void) => void).call(wx, onHide);\n fallback();\n };\n };\n\n diagnostics.info('mini program canvas resolved', { selector: options.selector, rect: lastRect });\n\n return {\n kind: 'wechat-miniprogram',\n wx,\n rawCanvas,\n capabilities,\n imageFactory,\n getCanvasRect,\n createOffscreenCanvas: (width: number, height: number, type: ContextType) =>\n createOffscreenCanvasRaw(wx, width, height, type, diagnostics),\n // Mini programs deliver touch events through WXML bindings, not wx.onTouch*.\n // The app must forward them: <canvas @touchstart=\"runtime.handleTouch\" ... />\n watchTouch: (_handler: (event: TouchLikeEvent) => void): Disposer => () => undefined,\n watchVisibility,\n requestAnimationFrame: raf.request,\n cancelAnimationFrame: raf.cancel,\n now,\n dispose: () => diagnostics.debug('wechat-miniprogram binding disposed'),\n };\n}\n\nexport type WeChatMiniProgramRuntimeOptions = WeChatMiniProgramOptions & RuntimeOptions;\n\nexport function createWeChatMiniProgramRuntime(\n options: WeChatMiniProgramRuntimeOptions,\n): Promise<MiniThreeRuntime> {\n return createRuntime(() => createWeChatMiniProgramBinding(options), options);\n}\n"]}