mini-three-adapter 0.1.1 → 0.1.3

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 (51) hide show
  1. package/AGENTS.md +85 -85
  2. package/README.md +159 -159
  3. package/dist/build/rollup.js +60 -9
  4. package/dist/build/rollup.js.map +1 -1
  5. package/dist/build/vite.js +60 -9
  6. package/dist/build/vite.js.map +1 -1
  7. package/dist/{chunk-Z7AMDRN3.js → chunk-3QUEDYTT.js} +12 -5
  8. package/dist/chunk-3QUEDYTT.js.map +1 -0
  9. package/dist/{chunk-WLRQDTSZ.js → chunk-52IMRKOX.js} +3 -3
  10. package/dist/{chunk-WLRQDTSZ.js.map → chunk-52IMRKOX.js.map} +1 -1
  11. package/dist/{chunk-3UGQWFH3.js → chunk-J7VBWZRR.js} +87 -27
  12. package/dist/chunk-J7VBWZRR.js.map +1 -0
  13. package/dist/{chunk-4UEBRAK6.js → chunk-LCJNTN6F.js} +19 -9
  14. package/dist/chunk-LCJNTN6F.js.map +1 -0
  15. package/dist/{chunk-MTBMOFAL.js → chunk-OL7NVZZJ.js} +29 -14
  16. package/dist/chunk-OL7NVZZJ.js.map +1 -0
  17. package/dist/{chunk-LB3WL24R.js → chunk-WZ2HKYC5.js} +8 -4
  18. package/dist/chunk-WZ2HKYC5.js.map +1 -0
  19. package/dist/core/index.d.ts +15 -5
  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/polyfills/index.d.ts +8 -1
  30. package/dist/polyfills/index.js +1 -1
  31. package/dist/{runtime-7uUOoFhC.d.ts → runtime-DnEkKZjo.d.ts} +1 -1
  32. package/dist/scope.d.ts +1 -1
  33. package/dist/{types-BzK0LQMa.d.ts → types-X_5SJh4y.d.ts} +7 -0
  34. package/docs/02-architecture.md +126 -126
  35. package/docs/03-module-map.md +99 -99
  36. package/docs/04-api-reference.md +294 -291
  37. package/docs/05-build-plugin.md +33 -5
  38. package/docs/06-platform-notes.md +116 -108
  39. package/docs/07-integration-guide.md +14 -0
  40. package/docs/09-testing-and-release.md +209 -206
  41. package/docs/10-ai-playbook.md +141 -140
  42. package/docs/11-compat-matrix.md +96 -94
  43. package/docs/adr/0007-capability-probe-fallback.md +57 -0
  44. package/docs/adr/README.md +1 -0
  45. package/llms.txt +69 -65
  46. package/package.json +1 -1
  47. package/dist/chunk-3UGQWFH3.js.map +0 -1
  48. package/dist/chunk-4UEBRAK6.js.map +0 -1
  49. package/dist/chunk-LB3WL24R.js.map +0 -1
  50. package/dist/chunk-MTBMOFAL.js.map +0 -1
  51. package/dist/chunk-Z7AMDRN3.js.map +0 -1
@@ -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 = (accessor: string, module: string): string =>\n `import { getActiveScope as ${accessor} } from '${module}';\\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 && (parent.node.key as unknown) === self) return true;\n if (parent.isObjectMethod() && !parent.node.computed && (parent.node.key as unknown) === self) return true;\n if (parent.isClassProperty() && !parent.node.computed && (parent.node.key as unknown) === self) return true;\n if (parent.isClassMethod() && !parent.node.computed && (parent.node.key as unknown) === self) return true;\n if (parent.isMemberExpression() && !parent.node.computed && (parent.node.property as unknown) === self) return true;\n return false;\n}\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 let count = 0;\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 if (isNonComputedKey(path)) 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 // `typeof window` stays correct: `typeof __m3().window` === 'object'.\n seen.add(name);\n ms.overwrite(node.start, node.end, `${accessor}().${name}`);\n count++;\n },\n });\n\n if (count === 0) return null;\n ms.prepend(SCOPE_IMPORT(accessor, scopeModule));\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;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,CAAC,UAAkB,WAC7C,8BAA8B,QAAQ,YAAY,MAAM;AAAA;AAE1D,SAAS,iBAAiBC,OAAyB;AACjD,QAAM,SAASA,MAAK;AACpB,MAAI,CAAC,OAAQ,QAAO;AACpB,QAAM,OAAgBA,MAAK;AAC3B,MAAI,OAAO,iBAAiB,KAAK,C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B;AAAA,MACF;AAEA,UAAI,QAAQ,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;;;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 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, but an uninitialized scope throws for\n // everything except window/self/globalThis. Guard it so feature\n // detection at module top level sees 'undefined' instead of exploding.\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,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AAAA,UACrB,cAAc,CAAC;AAAA,QACjB;AAAA,MACF;AAEA,UAAI,QAAQ,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;;;AGhNO,SAAS,UAAU,UAAkC,CAAC,GAAoB;AAC/E,SAAO,gBAAgB,OAAO;AAChC;AAEA,IAAO,iBAAQ;","names":["fs","path","fs"]}
@@ -65,19 +65,51 @@ var DEFAULT_GLOBAL_NAMES = [
65
65
  "ResizeObserver"
66
66
  ];
67
67
  var DEFAULT_FORCE_UNDEF = ["createImageBitmap"];
68
- var SCOPE_IMPORT = (accessor, module) => `import { getActiveScope as ${accessor} } from '${module}';
68
+ var SCOPE_IMPORT = (accessor, module, extraSpecifiers = []) => {
69
+ const specifiers = [`getActiveScope as ${accessor}`, ...extraSpecifiers].join(", ");
70
+ return `import { ${specifiers} } from '${module}';
69
71
  `;
72
+ };
73
+ function sameNode(a, b) {
74
+ if (a === b) return true;
75
+ const x = a;
76
+ const y = b;
77
+ return Boolean(x && y && x.start != null && x.start === y.start && x.end === y.end);
78
+ }
70
79
  function isNonComputedKey(path2) {
71
80
  const parent = path2.parentPath;
72
81
  if (!parent) return false;
73
82
  const self = path2.node;
74
- if (parent.isObjectProperty() && !parent.node.computed && parent.node.key === self) return true;
75
- if (parent.isObjectMethod() && !parent.node.computed && parent.node.key === self) return true;
76
- if (parent.isClassProperty() && !parent.node.computed && parent.node.key === self) return true;
77
- if (parent.isClassMethod() && !parent.node.computed && parent.node.key === self) return true;
78
- if (parent.isMemberExpression() && !parent.node.computed && parent.node.property === self) return true;
83
+ if (parent.isObjectProperty() && !parent.node.computed && sameNode(parent.node.key, self)) return true;
84
+ if (parent.isObjectMethod() && !parent.node.computed && sameNode(parent.node.key, self)) return true;
85
+ if (parent.isClassProperty() && !parent.node.computed && sameNode(parent.node.key, self)) return true;
86
+ if (parent.isClassMethod() && !parent.node.computed && sameNode(parent.node.key, self)) return true;
87
+ if (parent.isMemberExpression() && !parent.node.computed && sameNode(parent.node.property, self)) return true;
79
88
  return false;
80
89
  }
90
+ function isShorthandValue(path2) {
91
+ const parent = path2.parentPath;
92
+ if (!parent?.isObjectProperty()) return false;
93
+ if (!parent.node.shorthand || parent.node.computed) return false;
94
+ if (parent.node.value !== path2.node) return false;
95
+ return !parent.parentPath?.isObjectPattern();
96
+ }
97
+ function isNewCalleeRoot(path2) {
98
+ let cur = path2;
99
+ let parent = cur.parentPath;
100
+ while (parent?.isMemberExpression() && parent.node.object === cur.node) {
101
+ cur = parent;
102
+ parent = parent.parentPath;
103
+ }
104
+ return Boolean(parent?.isNewExpression() && parent.node.callee === cur.node);
105
+ }
106
+ function isDirectTypeofOperand(path2) {
107
+ const parent = path2.parentPath;
108
+ return Boolean(
109
+ parent?.isUnaryExpression() && parent.node.operator === "typeof" && parent.node.argument === path2.node
110
+ );
111
+ }
112
+ var ALWAYS_OBJECT_GLOBALS = /* @__PURE__ */ new Set(["window", "self", "globalThis"]);
81
113
  function rewriteGlobals(code, id, options = {}) {
82
114
  const names = /* @__PURE__ */ new Set([
83
115
  ...options.globals ?? DEFAULT_GLOBAL_NAMES,
@@ -98,22 +130,41 @@ function rewriteGlobals(code, id, options = {}) {
98
130
  }
99
131
  const ms = new MagicString(code);
100
132
  const seen = /* @__PURE__ */ new Set();
133
+ const hasAccessor = `${accessor}Has`;
101
134
  let count = 0;
135
+ let needsHasGuard = false;
102
136
  traverse(ast, {
103
137
  ReferencedIdentifier(path2) {
104
138
  const node = path2.node;
105
139
  const name = node.name;
106
140
  if (!name || !names.has(name)) return;
107
141
  if (node.start == null || node.end == null) return;
108
- if (isNonComputedKey(path2)) return;
109
142
  if (path2.scope.hasBinding(name, true)) return;
143
+ const ref = `${accessor}().${name}`;
144
+ if (isShorthandValue(path2)) {
145
+ seen.add(name);
146
+ ms.overwrite(node.start, node.end, `${name}: (${ref})`);
147
+ count++;
148
+ return;
149
+ }
150
+ if (isNonComputedKey(path2)) return;
110
151
  seen.add(name);
111
- ms.overwrite(node.start, node.end, `${accessor}().${name}`);
152
+ if (isDirectTypeofOperand(path2) && !ALWAYS_OBJECT_GLOBALS.has(name)) {
153
+ ms.overwrite(node.start, node.end, `(${hasAccessor}() ? ${ref} : undefined)`);
154
+ needsHasGuard = true;
155
+ count++;
156
+ return;
157
+ }
158
+ ms.overwrite(node.start, node.end, isNewCalleeRoot(path2) ? `(${ref})` : ref);
112
159
  count++;
113
160
  }
114
161
  });
115
162
  if (count === 0) return null;
116
- ms.prepend(SCOPE_IMPORT(accessor, scopeModule));
163
+ ms.prepend(SCOPE_IMPORT(
164
+ accessor,
165
+ scopeModule,
166
+ needsHasGuard ? [`hasActiveScope as ${hasAccessor}`] : []
167
+ ));
117
168
  return {
118
169
  code: ms.toString(),
119
170
  map: ms.generateMap({ source: id, includeContent: true, hires: true }),
@@ -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 = (accessor: string, module: string): string =>\n `import { getActiveScope as ${accessor} } from '${module}';\\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 && (parent.node.key as unknown) === self) return true;\n if (parent.isObjectMethod() && !parent.node.computed && (parent.node.key as unknown) === self) return true;\n if (parent.isClassProperty() && !parent.node.computed && (parent.node.key as unknown) === self) return true;\n if (parent.isClassMethod() && !parent.node.computed && (parent.node.key as unknown) === self) return true;\n if (parent.isMemberExpression() && !parent.node.computed && (parent.node.property as unknown) === self) return true;\n return false;\n}\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 let count = 0;\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 if (isNonComputedKey(path)) 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 // `typeof window` stays correct: `typeof __m3().window` === 'object'.\n seen.add(name);\n ms.overwrite(node.start, node.end, `${accessor}().${name}`);\n count++;\n },\n });\n\n if (count === 0) return null;\n ms.prepend(SCOPE_IMPORT(accessor, scopeModule));\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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,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
+ {"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, but an uninitialized scope throws for\n // everything except window/self/globalThis. Guard it so feature\n // detection at module top level sees 'undefined' instead of exploding.\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,E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AA,IACF;AAAA,EACF;AACF;;;AGxMO,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,5 +1,5 @@
1
- import { resolveWx, probeContext, createWechatImageFactory, createRafPair, createNow, watchWxVisibility, watchWxTouch, createOffscreenCanvasRaw, rectFromWindowInfo } from './chunk-MTBMOFAL.js';
2
- import { createDiagnostics, detectCapabilities, createRuntime } from './chunk-3UGQWFH3.js';
1
+ import { resolveWx, probeContext, createWechatImageFactory, createRafPair, createNow, watchWxVisibility, watchWxTouch, createOffscreenCanvasRaw, rectFromWindowInfo } from './chunk-OL7NVZZJ.js';
2
+ import { createDiagnostics, detectCapabilities, createRuntime } from './chunk-J7VBWZRR.js';
3
3
 
4
4
  // src/platforms/wechat-game.ts
5
5
  var cachedScreenCanvas = null;
@@ -30,7 +30,14 @@ function createWeChatGameBinding(options = {}) {
30
30
  const rawCanvas = getScreenCanvas(wx, options.canvas);
31
31
  const capabilities = detectCapabilities(wx, "wechat-game", {
32
32
  overrides: options.capabilities,
33
- probeContext: (type) => probeContext(wx, type)
33
+ diagnostics,
34
+ // The on-screen canvas is already resolved above, so a second
35
+ // createCanvas() is guaranteed to be off-screen and safe to probe — except
36
+ // when the host seeded `GameGlobal.screencanvas`: then the first call was
37
+ // never consumed and can still hand the screen canvas back. Passing it in
38
+ // lets `probeContext` refuse that object by identity instead of creating
39
+ // and immediately losing its context.
40
+ probeContext: (type) => probeContext(wx, type, { allowCanvasFallback: true, screenCanvas: rawCanvas })
34
41
  });
35
42
  const imageFactory = createWechatImageFactory(wx, diagnostics);
36
43
  const raf = createRafPair(wx, rawCanvas);
@@ -62,5 +69,5 @@ function createWeChatGameRuntime(options = {}) {
62
69
  }
63
70
 
64
71
  export { createWeChatGameBinding, createWeChatGameRuntime, getScreenCanvas, resetScreenCanvasCache };
65
- //# sourceMappingURL=chunk-Z7AMDRN3.js.map
66
- //# sourceMappingURL=chunk-Z7AMDRN3.js.map
72
+ //# sourceMappingURL=chunk-3QUEDYTT.js.map
73
+ //# sourceMappingURL=chunk-3QUEDYTT.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/platforms/wechat-game.ts"],"names":[],"mappings":";;;;AAiCA,IAAI,kBAAA,GAAsC,IAAA;AAGnC,SAAS,eAAA,CAAgB,IAAY,QAAA,EAA+B;AApC3E,EAAA,IAAA,EAAA;AAqCE,EAAA,IAAI,UAAU,OAAO,QAAA;AACrB,EAAA,IAAI,oBAAoB,OAAO,kBAAA;AAC/B,EAAA,MAAM,IAAA,GAAO,UAAA;AACb,EAAA,MAAM,aAAa,IAAA,CAAK,UAAA;AACxB,EAAA,MAAM,QAAA,GAAA,CAAY,EAAA,GAAA,UAAA,IAAA,IAAA,GAAA,MAAA,GAAA,UAAA,CAAY,YAAA,KAAZ,IAAA,GAAA,EAAA,GAA4B,IAAA,CAAK,MAAA;AACnD,EAAA,IAAI,QAAA,IAAY,OAAO,QAAA,CAAS,UAAA,KAAe,UAAA,EAAY;AACzD,IAAA,kBAAA,GAAqB,QAAA;AACrB,IAAA,OAAO,QAAA;AAAA,EACT;AACA,EAAA,IAAI,OAAO,EAAA,CAAG,YAAA,KAAiB,UAAA,EAAY;AACzC,IAAA,MAAM,IAAI,MAAM,yFAAyF,CAAA;AAAA,EAC3G;AACA,EAAA,kBAAA,GAAqB,GAAG,YAAA,EAAa;AACrC,EAAA,OAAO,kBAAA;A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A,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,IAC/D,UAAA,EAAY,CAAC,OAAA,KAAuD,YAAA,CAAa,IAAI,OAAO,CAAA;AAAA,IAC5F,eAAA,EAAiB,CAAC,OAAA,KAAY,iBAAA,CAAkB,IAAI,OAAO,CAAA;AAAA,IAC3D,uBAAuB,GAAA,CAAI,OAAA;AAAA,IAC3B,sBAAsB,GAAA,CAAI,MAAA;AAAA,IAC1B,GAAA;AAAA,IACA,SAAS,MAAM;AAEb,MAAA,WAAA,CAAY,MAAM,8BAA8B,CAAA;AAAA,IAClD;AAAA,GACF;AACF;AAKO,SAAS,uBAAA,CACd,OAAA,GAAoC,EAAC,EACV;AAC3B,EAAA,OAAO,aAAA,CAAc,MAAM,uBAAA,CAAwB,OAAO,GAAG,OAAO,CAAA;AACtE","file":"chunk-3QUEDYTT.js","sourcesContent":["/** WeChat Mini Game (小游戏) 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 rectFromWindowInfo,\n watchWxTouch,\n watchWxVisibility,\n} from './wechat-common';\nimport { resolveWx, type WxCanvas, type WxLike } from './wx-types';\n\nexport interface WeChatGameOptions {\n /** Inject a `wx` mock (tests / non-WeChat hosts). */\n wx?: WxLike;\n /**\n * Reuse an existing on-screen canvas. If omitted, the adapter checks\n * `GameGlobal.screencanvas`, `globalThis.canvas` (weapp-adapter) and finally\n * calls `wx.createCanvas()` exactly once.\n */\n canvas?: WxCanvas;\n capabilities?: Partial<Capabilities>;\n diagnostics?: Diagnostics;\n /** Call wx.setPreferredFramesPerSecond(fps) when supported. */\n preferredFps?: number;\n}\n\nlet cachedScreenCanvas: WxCanvas | null = null;\n\n/** Resolve (and memoize) the single on-screen canvas. */\nexport function getScreenCanvas(wx: WxLike, supplied?: WxCanvas): WxCanvas {\n if (supplied) return supplied;\n if (cachedScreenCanvas) return cachedScreenCanvas;\n const host = globalThis as unknown as Record<string, unknown>;\n const gameGlobal = host.GameGlobal as Record<string, unknown> | undefined;\n const existing = (gameGlobal?.screencanvas ?? host.canvas) as WxCanvas | undefined;\n if (existing && typeof existing.getContext === 'function') {\n cachedScreenCanvas = existing;\n return existing;\n }\n if (typeof wx.createCanvas !== 'function') {\n throw new Error('[mini-three-adapter] wx.createCanvas is missing: this is not a WeChat Mini Game runtime');\n }\n cachedScreenCanvas = wx.createCanvas();\n return cachedScreenCanvas;\n}\n\n/** Only for tests: forget the memoized screen canvas. */\nexport function resetScreenCanvasCache(): void {\n cachedScreenCanvas = null;\n}\n\nexport function createWeChatGameBinding(options: WeChatGameOptions = {}): PlatformBinding {\n const wx = resolveWx(options.wx);\n const diagnostics = options.diagnostics ?? createDiagnostics('warn');\n const rawCanvas = getScreenCanvas(wx, options.canvas);\n const capabilities = detectCapabilities(wx, 'wechat-game', {\n overrides: options.capabilities,\n diagnostics,\n // The on-screen canvas is already resolved above, so a second\n // createCanvas() is guaranteed to be off-screen and safe to probe — except\n // when the host seeded `GameGlobal.screencanvas`: then the first call was\n // never consumed and can still hand the screen canvas back. Passing it in\n // lets `probeContext` refuse that object by identity instead of creating\n // and immediately losing its context.\n probeContext: (type) =>\n probeContext(wx, type, { allowCanvasFallback: true, screenCanvas: rawCanvas }),\n });\n const imageFactory = createWechatImageFactory(wx, diagnostics);\n const raf = createRafPair(wx, rawCanvas);\n const now = createNow(wx);\n\n if (options.preferredFps && typeof wx.setPreferredFramesPerSecond === 'function') {\n wx.setPreferredFramesPerSecond(options.preferredFps);\n }\n\n const getCanvasRect = (): Rect => rectFromWindowInfo(wx);\n\n return {\n kind: 'wechat-game',\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 watchTouch: (handler: (event: TouchLikeEvent) => void): Disposer => watchWxTouch(wx, handler),\n watchVisibility: (handler) => watchWxVisibility(wx, handler),\n requestAnimationFrame: raf.request,\n cancelAnimationFrame: raf.cancel,\n now,\n dispose: () => {\n // The on-screen canvas belongs to the game; never destroy it here.\n diagnostics.debug('wechat-game binding disposed');\n },\n };\n}\n\nexport type WeChatGameRuntimeOptions = WeChatGameOptions & RuntimeOptions;\n\n/** One-line bootstrap for mini games. */\nexport function createWeChatGameRuntime(\n options: WeChatGameRuntimeOptions = {},\n): Promise<MiniThreeRuntime> {\n return createRuntime(() => createWeChatGameBinding(options), options);\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { createDiagnostics, detectCapabilities, createImageFactory, createRuntime } from './chunk-3UGQWFH3.js';
1
+ import { createDiagnostics, detectCapabilities, createImageFactory, createRuntime } from './chunk-J7VBWZRR.js';
2
2
 
3
3
  // src/platforms/browser.ts
4
4
  function createMockCanvas(width = 1, height = 1) {
@@ -141,5 +141,5 @@ function createBrowserRuntime(options = {}) {
141
141
  }
142
142
 
143
143
  export { createBrowserBinding, createBrowserRuntime };
144
- //# sourceMappingURL=chunk-WLRQDTSZ.js.map
145
- //# sourceMappingURL=chunk-WLRQDTSZ.js.map
144
+ //# sourceMappingURL=chunk-52IMRKOX.js.map
145
+ //# sourceMappingURL=chunk-52IMRKOX.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/platforms/browser.ts"],"names":["_a","_b","_c"],"mappings":";;;AAqBA,SAAS,gBAAA,CAAiB,KAAA,GAAQ,CAAA,EAAG,MAAA,GAAS,CAAA,EAAa;AACzD,EAAA,OAAO;AA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ACT,CAAA;AAAA,IACA,UAAA;AAAA,IACA,eAAA;AAAA,IACA,uBAAuB,CAAC,EAAA,KAAO,IAAA,CAAK,qBAAA,GAChC,KAAK,qBAAA,CAAsB,EAAE,CAAA,GAC5B,UAAA,CAAW,MAAM,EAAA,CAAG,IAAA,CAAK,GAAA,EAAK,GAAG,EAAE,CAAA;AAAA,IACxC,oBAAA,EAAsB,CAAC,EAAA,KAAO,IAAA,CAAK,oBAAA,GAC/B,KAAK,oBAAA,CAAqB,EAAE,CAAA,GAC5B,YAAA,CAAa,EAA8C,CAAA;AAAA,IAC/D,KAAK,MAAG;AAjKZ,MAAA,IAAAD,KAAAC,GAAAA,EAAAC,GAAAA;AAiKe,MAAA,OAAA,CAAAA,GAAAA,GAAAA,CAAAD,GAAAA,GAAAA,CAAAD,GAAAA,GAAA,IAAA,CAAK,gBAAL,IAAA,GAAA,MAAA,GAAAA,GAAAA,CAAkB,GAAA,KAAlB,IAAA,GAAA,MAAA,GAAAC,IAAA,IAAA,CAAAD,GAAAA,CAAAA,KAAA,IAAA,GAAAE,GAAAA,GAA6B,KAAK,GAAA,EAAI;AAAA,IAAA,CAAA;AAAA,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-WLRQDTSZ.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, 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 type { WxCanvas, WxLike, WxWindowInfo } from './wx-types';\n\nexport interface BrowserPlatformOptions {\n canvas?: HTMLCanvasElement;\n capabilities?: Partial<Capabilities>;\n diagnostics?: Diagnostics;\n}\n\nfunction createMockCanvas(width = 1, height = 1): WxCanvas {\n return {\n width,\n height,\n getContext: () => ({\n canvas: null,\n getExtension: () => null,\n getParameter: () => 0,\n }),\n toDataURL: () => 'data:,',\n };\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 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 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
+ {"version":3,"sources":["../src/platforms/browser.ts"],"names":["_a","_b","_c"],"mappings":";;;AAqBA,SAAS,gBAAA,CAAiB,KAAA,GAAQ,CAAA,EAAG,MAAA,GAAS,CAAA,EAAa;AACzD,EAAA,OAAO;AAAA,IACL,KAAA;AAAA,IACA,MAAA;AAAA,IACA,YAAY,OAAO;AAAA,MACjB,MAAA,EAAQ,IAAA;AAAA,MACR,cAAc,MAAM,IAAA;AAAA,MACpB,cAAc,MAAM;AAAA,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,UAAA,CAAW,MAAM,EAAA,CAAG,IAAA,CAAK,GAAA,EAAK,GAAG,EAAE,CAAA;AAAA,IACxC,oBAAA,EAAsB,CAAC,EAAA,KAAO,IAAA,CAAK,oBAAA,GAC/B,KAAK,oBAAA,CAAqB,EAAE,CAAA,GAC5B,YAAA,CAAa,EAA8C,CAAA;AAAA,IAC/D,KAAK,MAAG;AAjKZ,MAAA,IAAAD,KAAAC,GAAAA,EAAAC,GAAAA;AAiKe,MAAA,OAAA,CAAAA,GAAAA,GAAAA,CAAAD,GAAAA,GAAAA,CAAAD,GAAAA,GAAA,IAAA,CAAK,gBAAL,IAAA,GAAA,MAAA,GAAAA,GAAAA,CAAkB,GAAA,KAAlB,IAAA,GAAA,MAAA,GAAAC,IAAA,IAAA,CAAAD,GAAAA,CAAAA,KAAA,IAAA,GAAAE,GAAAA,GAA6B,KAAK,GAAA,EAAI;AAAA,IAAA,CAAA;AAAA,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-52IMRKOX.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, 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 type { WxCanvas, WxLike, WxWindowInfo } from './wx-types';\n\nexport interface BrowserPlatformOptions {\n canvas?: HTMLCanvasElement;\n capabilities?: Partial<Capabilities>;\n diagnostics?: Diagnostics;\n}\n\nfunction createMockCanvas(width = 1, height = 1): WxCanvas {\n return {\n width,\n height,\n getContext: () => ({\n canvas: null,\n getExtension: () => null,\n getParameter: () => 0,\n }),\n toDataURL: () => 'data:,',\n };\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 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 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"]}