mini-three-adapter 0.1.7 → 0.1.8
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.
- package/AGENTS.md +85 -85
- package/LICENSE +21 -21
- package/README.md +159 -159
- package/dist/build/rollup.js.map +1 -1
- package/dist/build/vite.js.map +1 -1
- package/dist/{chunk-HKT54DDM.js → chunk-DQH3YRGN.js} +3 -3
- package/dist/chunk-DQH3YRGN.js.map +1 -0
- package/dist/{chunk-35XVAVDB.js → chunk-J34MD3IL.js} +2 -2
- package/dist/chunk-J34MD3IL.js.map +1 -0
- package/dist/{chunk-U3P3XHA3.js → chunk-LAVHSWBU.js} +2 -2
- package/dist/{chunk-U3P3XHA3.js.map → chunk-LAVHSWBU.js.map} +1 -1
- package/dist/{chunk-7XOHQFZ6.js → chunk-RYWYBOYO.js} +4 -4
- package/dist/chunk-RYWYBOYO.js.map +1 -0
- package/dist/{chunk-DDCQIBWW.js → chunk-SXQUZI22.js} +4 -4
- package/dist/chunk-SXQUZI22.js.map +1 -0
- package/dist/{chunk-V64V4HIZ.js → chunk-TPMMZFHW.js} +22 -6
- package/dist/chunk-TPMMZFHW.js.map +1 -0
- package/dist/{chunk-FQ2GOIOE.js → chunk-YPG3QUYK.js} +4 -4
- package/dist/chunk-YPG3QUYK.js.map +1 -0
- package/dist/core/index.js +3 -3
- package/dist/index.js +7 -7
- package/dist/platforms/browser.js +4 -4
- package/dist/platforms/wechat-game.js +5 -5
- package/dist/platforms/wechat-miniprogram.js +5 -5
- package/dist/polyfills/index.js +1 -1
- package/dist/scope.js +1 -1
- package/docs/01-design-principles.md +105 -105
- package/docs/03-module-map.md +99 -99
- package/docs/04-api-reference.md +310 -310
- package/docs/05-build-plugin.md +176 -176
- package/docs/06-platform-notes.md +6 -3
- package/docs/07-integration-guide.md +226 -226
- package/docs/08-extension-guide.md +101 -101
- package/docs/09-testing-and-release.md +212 -212
- package/docs/11-compat-matrix.md +100 -100
- package/docs/README.md +41 -41
- package/docs/adr/0001-scoped-globals.md +41 -41
- package/docs/adr/0002-unified-runtime-lifecycle.md +40 -40
- package/docs/adr/0003-ast-rewrite.md +51 -51
- package/docs/adr/0004-in-place-patching.md +42 -42
- package/docs/adr/0005-webgl2-only.md +44 -44
- package/docs/adr/0006-zero-three-dependency.md +43 -43
- package/docs/adr/0007-capability-probe-fallback.md +61 -61
- package/docs/adr/0008-probe-fallback-boundary.md +56 -56
- package/docs/adr/0009-placeholder-scope-environment-globals.md +69 -69
- package/docs/adr/0010-native-event-target-boundary.md +82 -82
- package/docs/adr/0011-host-callback-slot-bridging.md +45 -0
- package/docs/adr/README.md +33 -32
- package/package.json +126 -126
- package/dist/chunk-35XVAVDB.js.map +0 -1
- package/dist/chunk-7XOHQFZ6.js.map +0 -1
- package/dist/chunk-DDCQIBWW.js.map +0 -1
- package/dist/chunk-FQ2GOIOE.js.map +0 -1
- package/dist/chunk-HKT54DDM.js.map +0 -1
- package/dist/chunk-V64V4HIZ.js.map +0 -1
package/dist/build/rollup.js.map
CHANGED
|
@@ -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 BuildSourceMap,\n type RewriteOptions,\n} from './scope-rewrite';\nimport {\n collectAssetReferences,\n collectAssets,\n type AssetManifest,\n type AssetOptions,\n} from './assets';\n\nexport interface MiniThreePluginOptions extends AssetOptions {\n /** Extra modules to transform. Receives a normalized (slash-separated) id. */\n include?: (id: string) => boolean;\n /** Modules to skip even when they match. */\n exclude?: (id: string) => boolean;\n /** Also transform application code (off by default). */\n includeUserCode?: boolean;\n /** Rewrite options (advanced). */\n rewrite?: RewriteOptions;\n /** How to handle `three/webgpu` imports. Default 'warn'. */\n webgpu?: 'warn' | 'error' | 'rewrite' | 'ignore';\n /** Print a build report summary. Default true. */\n report?: boolean;\n /** Verbose per-module logs. */\n debug?: boolean;\n}\n\nexport interface BuildReport {\n modulesScanned: number;\n modulesRewritten: number;\n rewrites: number;\n globalsSeen: string[];\n assetReferences: string[];\n missingAssets: string[];\n webgpuWarnings: string[];\n parseFailures: string[];\n}\n\nexport interface PluginContext {\n warn(message: string): void;\n error(message: string): never;\n emitFile(file: { type: 'asset'; fileName: string; source: string | Uint8Array }): string;\n}\n\nexport interface MiniThreePlugin {\n name: string;\n enforce: 'pre';\n transform(this: PluginContext, code: string, id: string): { code: string; map: BuildSourceMap | null } | null;\n generateBundle(this: PluginContext, options: { dir?: string; file?: string }): Promise<void>;\n api: {\n report(): BuildReport;\n };\n}\n\nconst DEFAULT_INCLUDE = (id: string): boolean => {\n const normalized = id.replace(/\\\\/g, '/').split('?')[0] ?? id;\n return (\n normalized.includes('/node_modules/three/') ||\n normalized.includes('/node_modules/three-stdlib/') ||\n normalized.includes('/node_modules/@react-three/') ||\n normalized.includes('/node_modules/@tresjs/') ||\n normalized.includes('/node_modules/.vite/deps/three') ||\n normalized.includes('/node_modules/.vite/deps/three-stdlib') ||\n /\\/node_modules\\/three@[^/]+\\//.test(normalized)\n );\n};\n\nexport function miniThreePlugin(options: MiniThreePluginOptions = {}): MiniThreePlugin {\n const include = options.include ?? DEFAULT_INCLUDE;\n const exclude = options.exclude ?? (() => false);\n const webgpuMode = options.webgpu ?? 'warn';\n const report: BuildReport = {\n modulesScanned: 0,\n modulesRewritten: 0,\n rewrites: 0,\n globalsSeen: [],\n assetReferences: [],\n missingAssets: [],\n webgpuWarnings: [],\n parseFailures: [],\n };\n const seenGlobals = new Set<string>();\n const assetRefs = new Set<string>();\n let manifest: AssetManifest | null = null;\n let filesToEmit = new Map<string, string>();\n\n const note = (ctx: PluginContext, message: string): void => {\n if (options.debug) ctx.warn(`[mini-three] ${message}`);\n };\n\n return {\n name: 'mini-three-adapter',\n enforce: 'pre',\n\n transform(this: PluginContext, code: string, id: string) {\n const normalized = id.replace(/\\\\/g, '/');\n const shouldTransform = options.includeUserCode\n ? !normalized.includes('/node_modules/mini-three-adapter/') && !exclude(normalized)\n : include(normalized) && !exclude(normalized);\n if (!shouldTransform) return null;\n\n report.modulesScanned++;\n for (const ref of collectAssetReferences(code)) assetRefs.add(ref);\n\n let currentCode = code;\n if (webgpuMode !== 'ignore' && /from\\s*['\"`]three\\/webgpu['\"`]/.test(code)) {\n const message = `[mini-three] ${normalized} imports 'three/webgpu'; WebGPU is not available in WeChat mini games.`;\n report.webgpuWarnings.push(message);\n if (webgpuMode === 'error') this.error(message);\n if (webgpuMode === 'warn') this.warn(`${message} Use three's WebGLRenderer instead.`);\n if (webgpuMode === 'rewrite') {\n currentCode = currentCode\n .replace(/(['\"`])three\\/webgpu\\1/g, '$1three$1')\n .replace(/\\bWebGPURenderer\\b/g, 'WebGLRenderer');\n note(this, `rewrote three/webgpu -> three in ${normalized}`);\n }\n }\n\n const result = rewriteGlobals(currentCode, normalized, {\n ...options.rewrite,\n ...(options.rewrite?.forceUndef ? {} : { forceUndef: [...DEFAULT_FORCE_UNDEF] }),\n });\n if (result && 'error' in result) {\n report.parseFailures.push(result.error);\n this.warn(`[mini-three] ${result.error}`);\n return null;\n }\n if (!result) return webgpuMode === 'rewrite' ? { code: currentCode, map: null } : null;\n\n report.modulesRewritten++;\n report.rewrites += result.count;\n for (const name of result.seen) seenGlobals.add(name);\n note(this, `${normalized}: ${result.count} global(s) rewritten (${result.seen.join(', ')})`);\n return { code: result.code, map: result.map };\n },\n\n async generateBundle(this: PluginContext, bundleOptions) {\n const refs = Array.from(assetRefs);\n report.assetReferences = refs;\n report.globalsSeen = Array.from(seenGlobals).sort();\n\n if (refs.length > 0) {\n const collected = await collectAssets(refs, {\n cwd: options.cwd,\n roots: options.roots,\n outputDir: options.outputDir,\n brotli: options.brotli,\n manifest: options.manifest,\n });\n manifest = collected.manifest;\n filesToEmit = collected.files;\n report.missingAssets = collected.missing;\n for (const missing of collected.missing) {\n this.warn(`[mini-three] asset not found in known roots: ${missing}`);\n }\n for (const [destination, source] of filesToEmit) {\n try {\n const content = await fs.readFile(source);\n this.emitFile({ type: 'asset', fileName: destination, source: content });\n } catch (error) {\n this.warn(`[mini-three] could not emit ${destination}: ${String(error)}`);\n }\n }\n } else {\n manifest = {\n generatedBy: 'mini-three-adapter',\n outputDir: options.outputDir ?? 'assets/three',\n entries: [],\n gameJsonSuggestion: {},\n decoderPaths: {},\n };\n }\n\n if (options.manifest !== false) {\n this.emitFile({\n type: 'asset',\n fileName: 'mini-three-assets.json',\n source: JSON.stringify({ ...manifest, build: report, output: bundleOptions.dir ?? bundleOptions.file ?? '' }, null, 2),\n });\n }\n if (options.report !== false) {\n this.warn(\n `[mini-three] build report: ${report.modulesScanned} module(s) scanned, ` +\n `${report.modulesRewritten} rewritten, ${report.rewrites} reference(s) -> scope, ` +\n `${filesToEmit.size} asset(s) emitted, ${report.missingAssets.length} missing.`,\n );\n }\n },\n\n api: {\n report: () => ({\n ...report,\n globalsSeen: Array.from(seenGlobals).sort(),\n assetReferences: Array.from(assetRefs),\n webgpuWarnings: [...report.webgpuWarnings],\n parseFailures: [...report.parseFailures],\n }),\n },\n };\n}\n","/**\n * AST-based global-to-scope rewriting.\n *\n * The reference adapter uses a Rollup \"prefix global\" pass that effectively\n * text-replaces identifiers. That breaks on shadowed locals, object keys, and\n * `typeof window` feature detection. Here we parse with @babel/parser and use\n * Babel's scope binding information, so ONLY free (unbound) references to\n * browser globals are rewritten — application code is never touched.\n */\nimport { parse } from '@babel/parser';\nimport _traverse from '@babel/traverse';\nimport MagicString from 'magic-string';\nimport type { NodePath } from '@babel/traverse';\nimport type { Identifier } from '@babel/types';\nimport type { Node } from '@babel/types';\n\n// Babel's CJS/ESM interop differs between bundlers; normalize once.\nconst traverse = (typeof _traverse === 'function'\n ? _traverse\n : (_traverse as unknown as { default: typeof _traverse }).default) as typeof _traverse;\n\nexport const DEFAULT_GLOBAL_NAMES: readonly string[] = [\n 'window', 'self', 'document', 'navigator', 'screen', 'location',\n 'innerWidth', 'innerHeight', 'outerWidth', 'outerHeight',\n 'devicePixelRatio', 'pageXOffset', 'pageYOffset',\n 'performance', 'requestAnimationFrame', 'cancelAnimationFrame',\n 'getComputedStyle', 'matchMedia', 'atob', 'btoa',\n 'Event', 'EventTarget', 'CustomEvent', 'PointerEvent', 'MouseEvent',\n 'TouchEvent', 'MessageEvent', 'ProgressEvent', 'KeyboardEvent', 'DOMException',\n 'HTMLElement', 'HTMLCanvasElement', 'HTMLImageElement', 'HTMLVideoElement',\n 'OffscreenCanvas', 'Image', 'ImageData', 'DOMRect',\n 'WebGLRenderingContext', 'WebGL2RenderingContext', 'AudioContext',\n 'Blob', 'URL', 'URLSearchParams', 'FileReader', 'TextDecoder', 'TextEncoder',\n 'AbortController', 'AbortSignal', 'fetch', 'XMLHttpRequest', 'WebSocket',\n 'createImageBitmap', 'Worker', 'WebAssembly', 'ResizeObserver',\n];\n\n/** Globals that must remain `undefined` in the mini game scope. */\nexport const DEFAULT_FORCE_UNDEF: readonly string[] = ['createImageBitmap'];\n\nexport interface RewriteOptions {\n /** Extra global identifiers to rewrite. */\n extraGlobals?: string[];\n /** Replace the default global list instead of extending it. */\n globals?: string[];\n /** Identifiers that must evaluate to `undefined` (feature-detection off). */\n forceUndef?: string[];\n /** Name of the injected scope accessor. Default `__m3`. */\n accessor?: string;\n /** Module specifier that exports `getActiveScope`. */\n scopeModule?: string;\n}\n\n/**\n * Minimal source-map shape accepted by Rollup / Vite as a transform result.\n * Declared locally so `dist/*.d.ts` stays self-contained (`rollup` is an\n * optional peer). `magic-string`'s `SourceMap` satisfies it structurally.\n */\nexport interface BuildSourceMap {\n version: number;\n file?: string;\n sources: string[];\n sourcesContent?: Array<string | null>;\n names: string[];\n mappings: string;\n}\n\nexport interface RewriteResult {\n code: string;\n map: BuildSourceMap | null;\n /** Number of rewritten references. */\n count: number;\n /** Globals actually seen (useful for the build report). */\n seen: string[];\n}\n\nexport interface RewriteFailure {\n code: string;\n error: string;\n}\n\nexport const SCOPE_IMPORT = (\n accessor: string,\n module: string,\n extraSpecifiers: readonly string[] = [],\n): string => {\n const specifiers = [`getActiveScope as ${accessor}`, ...extraSpecifiers].join(', ');\n return `import { ${specifiers} } from '${module}';\\n`;\n};\n\n/**\n * Reference or range equality. `@babel/parser` emits TWO distinct `Identifier`\n * nodes with identical `[start, end]` for a shorthand property (`{ X }`: one for\n * `key`, one for `value`), so reference equality alone is not enough to tell\n * \"this identifier is an object key\".\n */\nfunction sameNode(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n const x = a as { start?: number | null; end?: number | null } | null | undefined;\n const y = b as { start?: number | null; end?: number | null } | null | undefined;\n return Boolean(x && y && x.start != null && x.start === y.start && x.end === y.end);\n}\n\nfunction isNonComputedKey(path: NodePath): boolean {\n const parent = path.parentPath;\n if (!parent) return false;\n const self: unknown = path.node;\n if (parent.isObjectProperty() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\n if (parent.isObjectMethod() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\n if (parent.isClassProperty() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\n if (parent.isClassMethod() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\n if (parent.isMemberExpression() && !parent.node.computed && sameNode(parent.node.property, self)) return true;\n return false;\n}\n\n/**\n * `{ X }`: the value node shares its range with the key, so it cannot be\n * rewritten in place — it must be expanded to `{ X: <expr> }`.\n */\nfunction isShorthandValue(path: NodePath): boolean {\n const parent = path.parentPath;\n if (!parent?.isObjectProperty()) return false;\n if (!parent.node.shorthand || parent.node.computed) return false;\n if (parent.node.value !== path.node) return false;\n // `const { X } = obj` destructures a binding, never a global reference. Babel\n // already treats it as a binding, this guard keeps the two paths disjoint.\n return !parent.parentPath?.isObjectPattern();\n}\n\n/**\n * Is this identifier the left-most link of a `new X` / `new X.Y.Z` callee chain?\n *\n * `new f().g()` parses as `(new f()).g()`, so rewriting `X` to a *call*\n * (`__m3().X`) without parentheses silently turns `new X()` into\n * `(new __m3()).X()` — the scope object gets constructed and the class is then\n * invoked as a plain function. Wrapping only the chain root is enough:\n * `new (a().b).c` parses as `new ((a().b).c)`.\n */\nfunction isNewCalleeRoot(path: NodePath): boolean {\n let cur: NodePath = path;\n let parent = cur.parentPath;\n while (parent?.isMemberExpression() && parent.node.object === cur.node) {\n cur = parent;\n parent = parent.parentPath;\n }\n return Boolean(parent?.isNewExpression() && parent.node.callee === cur.node);\n}\n\n/** `typeof X` must never throw: `typeof a.b` is legal even when `a` is unbound. */\nfunction isDirectTypeofOperand(path: NodePath): boolean {\n const parent = path.parentPath;\n return Boolean(\n parent?.isUnaryExpression() &&\n parent.node.operator === 'typeof' &&\n parent.node.argument === path.node,\n );\n}\n\n/**\n * Globals that `getActiveScope()` resolves to itself even before a runtime\n * exists, so `typeof window` is already `'object'` and needs no guard.\n */\nconst ALWAYS_OBJECT_GLOBALS: ReadonlySet<string> = new Set(['window', 'self', 'globalThis']);\n\n/** Rewrite free browser-global references in one module. Returns null if nothing changed. */\nexport function rewriteGlobals(\n code: string,\n id: string,\n options: RewriteOptions = {},\n): RewriteResult | RewriteFailure | null {\n const names = new Set<string>([\n ...(options.globals ?? DEFAULT_GLOBAL_NAMES),\n ...(options.extraGlobals ?? []),\n ...(options.forceUndef ?? DEFAULT_FORCE_UNDEF),\n ]);\n const accessor = options.accessor ?? '__m3';\n const scopeModule = options.scopeModule ?? 'mini-three-adapter/scope';\n\n let ast;\n try {\n ast = parse(code, {\n sourceType: 'unambiguous',\n errorRecovery: true,\n plugins: ['importAttributes', 'classProperties', 'topLevelAwait', 'typescript', 'jsx'],\n });\n } catch (error) {\n return { code, error: `[mini-three] parse failed for ${id}: ${String(error)}` };\n }\n\n const ms = new MagicString(code);\n const seen = new Set<string>();\n const hasAccessor = `${accessor}Has`;\n let count = 0;\n let needsHasGuard = false;\n\n traverse(ast, {\n ReferencedIdentifier(path: NodePath<Node>) {\n const node = path.node as Identifier;\n const name = node.name;\n if (!name || !names.has(name)) return;\n if (node.start == null || node.end == null) return;\n // Babel scope knows about imports, function params, local declarations,\n // catch bindings and block-scoped shadowing. This is the critical check\n // that a regex-based replacement cannot perform.\n if (path.scope.hasBinding(name, true)) return;\n\n const ref = `${accessor}().${name}`;\n\n // 1) Shorthand must be handled before the key check: once `isNonComputedKey`\n // compares ranges, `{ X }`'s value looks like a key too and would be\n // silently skipped (leaving an undefined global behind).\n if (isShorthandValue(path)) {\n seen.add(name);\n ms.overwrite(node.start, node.end, `${name}: (${ref})`);\n count++;\n return;\n }\n\n // 2) Object keys / member property names are not references.\n if (isNonComputedKey(path)) return;\n\n seen.add(name);\n if (isDirectTypeofOperand(path) && !ALWAYS_OBJECT_GLOBALS.has(name)) {\n // `typeof X` must never throw. The placeholder scope answers the\n // environment globals (document/navigator/screen/...) with `undefined`\n // already, but everything else — TextDecoder, HTMLCanvasElement,\n // Blob, ... — throws an actionable error on access, and a `typeof`\n // probe must not become that error.\n ms.overwrite(node.start, node.end, `(${hasAccessor}() ? ${ref} : undefined)`);\n needsHasGuard = true;\n count++;\n return;\n }\n ms.overwrite(node.start, node.end, isNewCalleeRoot(path) ? `(${ref})` : ref);\n count++;\n },\n });\n\n if (count === 0) return null;\n ms.prepend(SCOPE_IMPORT(\n accessor,\n scopeModule,\n needsHasGuard ? [`hasActiveScope as ${hasAccessor}`] : [],\n ));\n return {\n code: ms.toString(),\n map: ms.generateMap({ source: id, includeContent: true, hires: true }),\n count,\n seen: Array.from(seen).sort(),\n };\n}\n","/**\n * Worker / WASM asset collection for three.js addons.\n *\n * DRACOLoader, KTX2Loader, 3DMLoader, LottieLoader, ... reference decoder\n * `.js` and `.wasm` files by string path. In a mini game those files are not\n * reachable via HTTP; they must be copied into the code package (ideally a\n * subpackage) and `setDecoderPath` must point at the copied location.\n *\n * The plugin scans transformed modules, resolves each referenced basename in a\n * small set of known directories, copies it, and emits a manifest plus a\n * `game.json` suggestion. No global state, no hidden writes.\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\n\nexport interface AssetOptions {\n /** Extra directories to search (besides three's jsm/libs). */\n roots?: string[];\n /** Output directory relative to the bundle root. Default 'assets/three'. */\n outputDir?: string;\n /** Copy `.wasm.br` alongside `.wasm` when available. Default true. */\n brotli?: boolean;\n /** Emit `mini-three-assets.json`. Default true. */\n manifest?: boolean;\n /** Working directory used to resolve roots. Default process.cwd(). */\n cwd?: string;\n}\n\nexport interface AssetEntry {\n /** Original string found in the module. */\n reference: string;\n /** Resolved absolute source path. */\n source: string;\n /** Relative destination inside the bundle. */\n destination: string;\n kind: 'worker' | 'wasm' | 'data';\n}\n\nexport interface AssetManifest {\n generatedBy: 'mini-three-adapter';\n outputDir: string;\n entries: AssetEntry[];\n /** Paste into game.json (adjust subpackage names to your project). */\n gameJsonSuggestion: Record<string, unknown>;\n /** Decoder paths to feed to loaders at runtime. */\n decoderPaths: Record<string, string>;\n}\n\nconst ASSET_PATTERN = /(['\"`])([^'\"`\\n]*\\.(?:wasm|wasm\\.br|bin|js))\\1/g;\nconst DECODER_KEYWORDS = [\n 'draco', 'basis', 'ktx2', 'rhino3dm', 'zstd', 'meshopt', 'ammo',\n 'worker', 'decoder', 'transcoder', 'lottie', 'sdf',\n];\n\nexport function collectAssetReferences(code: string): string[] {\n const found = new Set<string>();\n let match: RegExpExecArray | null;\n ASSET_PATTERN.lastIndex = 0;\n while ((match = ASSET_PATTERN.exec(code)) !== null) {\n const value = match[2] ?? '';\n const lower = value.toLowerCase();\n if (DECODER_KEYWORDS.some((keyword) => lower.includes(keyword))) found.add(value);\n }\n return Array.from(found);\n}\n\nasync function indexFiles(root: string, maxDepth = 5): Promise<Map<string, string>> {\n const index = new Map<string, string>();\n const walk = async (dir: string, depth: number): Promise<void> => {\n if (depth > maxDepth) return;\n let entries;\n try { entries = await fs.readdir(dir, { withFileTypes: true }); }\n catch { return; }\n for (const entry of entries) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) await walk(full, depth + 1);\n else if (entry.isFile() && !index.has(entry.name)) index.set(entry.name, full);\n }\n };\n await walk(root, 0);\n return index;\n}\n\nfunction classify(name: string): AssetEntry['kind'] {\n if (name.endsWith('.wasm') || name.endsWith('.wasm.br')) return 'wasm';\n if (name.endsWith('.js')) return 'worker';\n return 'data';\n}\n\nexport function defaultRoots(cwd: string): string[] {\n return [\n path.join(cwd, 'node_modules/three/examples/jsm/libs'),\n path.join(cwd, 'node_modules/three/examples/jsm'),\n path.join(cwd, 'node_modules/three-stdlib'),\n path.join(cwd, 'public'),\n path.join(cwd, 'static'),\n ];\n}\n\nexport interface CollectResult {\n manifest: AssetManifest;\n /** Files to write: destination (relative) -> absolute source. */\n files: Map<string, string>;\n missing: string[];\n}\n\n/** Resolve references against known roots without copying anything. */\nexport async function collectAssets(references: string[], options: AssetOptions = {}): Promise<CollectResult> {\n const cwd = options.cwd ?? process.cwd();\n const outputDir = (options.outputDir ?? 'assets/three').replace(/\\\\/g, '/').replace(/\\/$/, '');\n const roots = [...defaultRoots(cwd), ...(options.roots ?? [])];\n const indexes = await Promise.all(roots.map((root) => indexFiles(root)));\n const find = (name: string): string | undefined => {\n for (const index of indexes) {\n const hit = index.get(name);\n if (hit) return hit;\n }\n return undefined;\n };\n\n const entries: AssetEntry[] = [];\n const files = new Map<string, string>();\n const missing: string[] = [];\n\n for (const reference of references) {\n const base = path.posix.basename(reference.split('?')[0] ?? reference);\n const source = find(base);\n if (!source) { missing.push(reference); continue; }\n const entry: AssetEntry = {\n reference,\n source,\n destination: `${outputDir}/${base}`,\n kind: classify(base),\n };\n entries.push(entry);\n files.set(entry.destination, source);\n if (options.brotli !== false && entry.kind === 'wasm') {\n const br = find(`${base}.br`);\n if (br) {\n entries.push({ reference: `${reference}.br`, source: br, destination: `${outputDir}/${base}.br`, kind: 'wasm' });\n files.set(`${outputDir}/${base}.br`, br);\n }\n }\n }\n\n const decoderPaths: Record<string, string> = {};\n for (const entry of entries) {\n const name = path.posix.basename(entry.destination).toLowerCase();\n for (const key of ['draco', 'ktx2', 'basis', 'meshopt', 'rhino3dm', 'zstd', 'ammo']) {\n if (name.includes(key)) decoderPaths[key] = `${outputDir}/`;\n }\n }\n\n const manifest: AssetManifest = {\n generatedBy: 'mini-three-adapter',\n outputDir,\n entries,\n gameJsonSuggestion: {\n workers: { path: `${outputDir}`, isSubpackage: true },\n subpackages: [{ name: 'three-assets', root: `${outputDir}/` }],\n },\n decoderPaths,\n };\n return { manifest, files, missing };\n}\n\n/** Copy resolved files into `outDir`. */\nexport async function copyAssets(files: Map<string, string>, outDir: string): Promise<number> {\n let written = 0;\n for (const [destination, source] of files) {\n const target = path.join(outDir, destination);\n await fs.mkdir(path.dirname(target), { recursive: true });\n await fs.copyFile(source, target);\n written++;\n }\n return written;\n}\n","/** Rollup entry: `import { miniThree } from 'mini-three-adapter/rollup'`. */\nimport { miniThreePlugin, type MiniThreePlugin, type MiniThreePluginOptions } from './plugin-core';\n\nexport function miniThree(options: MiniThreePluginOptions = {}): MiniThreePlugin {\n return miniThreePlugin(options);\n}\n\nexport default miniThree;\nexport { miniThreePlugin } from './plugin-core';\nexport type { MiniThreePluginOptions, BuildReport } from './plugin-core';\nexport { DEFAULT_GLOBAL_NAMES, DEFAULT_FORCE_UNDEF, rewriteGlobals } from './scope-rewrite';\nexport type { RewriteOptions, RewriteResult } from './scope-rewrite';\nexport { collectAssetReferences, collectAssets, copyAssets } from './assets';\nexport type { AssetOptions, AssetManifest, AssetEntry } from './assets';\n"],"mappings":";AASA,SAAS,YAAYA,WAAU;;;ACA/B,SAAS,aAAa;AACtB,OAAO,eAAe;AACtB,OAAO,iBAAiB;AAMxB,IAAM,WAAY,OAAO,c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AAA,MACF,OAAO;AACL,mBAAW;AAAA,UACT,aAAa;AAAA,UACb,WAAW,QAAQ,aAAa;AAAA,UAChC,SAAS,CAAC;AAAA,UACV,oBAAoB,CAAC;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;;;AGjNO,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":["/**\r\n * Rollup/Vite-compatible plugin core (zero hard dependency on either bundler).\r\n *\r\n * Responsibilities:\r\n * 1. Rewrite free browser globals inside third-party modules to scoped access.\r\n * 2. Handle `three/webgpu` (WebGPU is unavailable in WeChat mini games).\r\n * 3. Collect worker/wasm assets referenced by addons and emit them + a manifest.\r\n * 4. Produce a machine-readable build report for CI and AI-assisted iteration.\r\n */\r\nimport { promises as fs } from 'node:fs';\r\nimport {\r\n DEFAULT_FORCE_UNDEF,\r\n rewriteGlobals,\r\n type BuildSourceMap,\r\n type RewriteOptions,\r\n} from './scope-rewrite';\r\nimport {\r\n collectAssetReferences,\r\n collectAssets,\r\n type AssetManifest,\r\n type AssetOptions,\r\n} from './assets';\r\n\r\nexport interface MiniThreePluginOptions extends AssetOptions {\r\n /** Extra modules to transform. Receives a normalized (slash-separated) id. */\r\n include?: (id: string) => boolean;\r\n /** Modules to skip even when they match. */\r\n exclude?: (id: string) => boolean;\r\n /** Also transform application code (off by default). */\r\n includeUserCode?: boolean;\r\n /** Rewrite options (advanced). */\r\n rewrite?: RewriteOptions;\r\n /** How to handle `three/webgpu` imports. Default 'warn'. */\r\n webgpu?: 'warn' | 'error' | 'rewrite' | 'ignore';\r\n /** Print a build report summary. Default true. */\r\n report?: boolean;\r\n /** Verbose per-module logs. */\r\n debug?: boolean;\r\n}\r\n\r\nexport interface BuildReport {\r\n modulesScanned: number;\r\n modulesRewritten: number;\r\n rewrites: number;\r\n globalsSeen: string[];\r\n assetReferences: string[];\r\n missingAssets: string[];\r\n webgpuWarnings: string[];\r\n parseFailures: string[];\r\n}\r\n\r\nexport interface PluginContext {\r\n warn(message: string): void;\r\n error(message: string): never;\r\n emitFile(file: { type: 'asset'; fileName: string; source: string | Uint8Array }): string;\r\n}\r\n\r\nexport interface MiniThreePlugin {\r\n name: string;\r\n enforce: 'pre';\r\n transform(this: PluginContext, code: string, id: string): { code: string; map: BuildSourceMap | null } | null;\r\n generateBundle(this: PluginContext, options: { dir?: string; file?: string }): Promise<void>;\r\n api: {\r\n report(): BuildReport;\r\n };\r\n}\r\n\r\nconst DEFAULT_INCLUDE = (id: string): boolean => {\r\n const normalized = id.replace(/\\\\/g, '/').split('?')[0] ?? id;\r\n return (\r\n normalized.includes('/node_modules/three/') ||\r\n normalized.includes('/node_modules/three-stdlib/') ||\r\n normalized.includes('/node_modules/@react-three/') ||\r\n normalized.includes('/node_modules/@tresjs/') ||\r\n normalized.includes('/node_modules/.vite/deps/three') ||\r\n normalized.includes('/node_modules/.vite/deps/three-stdlib') ||\r\n /\\/node_modules\\/three@[^/]+\\//.test(normalized)\r\n );\r\n};\r\n\r\nexport function miniThreePlugin(options: MiniThreePluginOptions = {}): MiniThreePlugin {\r\n const include = options.include ?? DEFAULT_INCLUDE;\r\n const exclude = options.exclude ?? (() => false);\r\n const webgpuMode = options.webgpu ?? 'warn';\r\n const report: BuildReport = {\r\n modulesScanned: 0,\r\n modulesRewritten: 0,\r\n rewrites: 0,\r\n globalsSeen: [],\r\n assetReferences: [],\r\n missingAssets: [],\r\n webgpuWarnings: [],\r\n parseFailures: [],\r\n };\r\n const seenGlobals = new Set<string>();\r\n const assetRefs = new Set<string>();\r\n let manifest: AssetManifest | null = null;\r\n let filesToEmit = new Map<string, string>();\r\n\r\n const note = (ctx: PluginContext, message: string): void => {\r\n if (options.debug) ctx.warn(`[mini-three] ${message}`);\r\n };\r\n\r\n return {\r\n name: 'mini-three-adapter',\r\n enforce: 'pre',\r\n\r\n transform(this: PluginContext, code: string, id: string) {\r\n const normalized = id.replace(/\\\\/g, '/');\r\n const shouldTransform = options.includeUserCode\r\n ? !normalized.includes('/node_modules/mini-three-adapter/') && !exclude(normalized)\r\n : include(normalized) && !exclude(normalized);\r\n if (!shouldTransform) return null;\r\n\r\n report.modulesScanned++;\r\n for (const ref of collectAssetReferences(code)) assetRefs.add(ref);\r\n\r\n let currentCode = code;\r\n if (webgpuMode !== 'ignore' && /from\\s*['\"`]three\\/webgpu['\"`]/.test(code)) {\r\n const message = `[mini-three] ${normalized} imports 'three/webgpu'; WebGPU is not available in WeChat mini games.`;\r\n report.webgpuWarnings.push(message);\r\n if (webgpuMode === 'error') this.error(message);\r\n if (webgpuMode === 'warn') this.warn(`${message} Use three's WebGLRenderer instead.`);\r\n if (webgpuMode === 'rewrite') {\r\n currentCode = currentCode\r\n .replace(/(['\"`])three\\/webgpu\\1/g, '$1three$1')\r\n .replace(/\\bWebGPURenderer\\b/g, 'WebGLRenderer');\r\n note(this, `rewrote three/webgpu -> three in ${normalized}`);\r\n }\r\n }\r\n\r\n const result = rewriteGlobals(currentCode, normalized, {\r\n ...options.rewrite,\r\n ...(options.rewrite?.forceUndef ? {} : { forceUndef: [...DEFAULT_FORCE_UNDEF] }),\r\n });\r\n if (result && 'error' in result) {\r\n report.parseFailures.push(result.error);\r\n this.warn(`[mini-three] ${result.error}`);\r\n return null;\r\n }\r\n if (!result) return webgpuMode === 'rewrite' ? { code: currentCode, map: null } : null;\r\n\r\n report.modulesRewritten++;\r\n report.rewrites += result.count;\r\n for (const name of result.seen) seenGlobals.add(name);\r\n note(this, `${normalized}: ${result.count} global(s) rewritten (${result.seen.join(', ')})`);\r\n return { code: result.code, map: result.map };\r\n },\r\n\r\n async generateBundle(this: PluginContext, bundleOptions) {\r\n const refs = Array.from(assetRefs);\r\n report.assetReferences = refs;\r\n report.globalsSeen = Array.from(seenGlobals).sort();\r\n\r\n if (refs.length > 0) {\r\n const collected = await collectAssets(refs, {\r\n cwd: options.cwd,\r\n roots: options.roots,\r\n outputDir: options.outputDir,\r\n brotli: options.brotli,\r\n manifest: options.manifest,\r\n });\r\n manifest = collected.manifest;\r\n filesToEmit = collected.files;\r\n report.missingAssets = collected.missing;\r\n for (const missing of collected.missing) {\r\n this.warn(`[mini-three] asset not found in known roots: ${missing}`);\r\n }\r\n for (const [destination, source] of filesToEmit) {\r\n try {\r\n const content = await fs.readFile(source);\r\n this.emitFile({ type: 'asset', fileName: destination, source: content });\r\n } catch (error) {\r\n this.warn(`[mini-three] could not emit ${destination}: ${String(error)}`);\r\n }\r\n }\r\n } else {\r\n manifest = {\r\n generatedBy: 'mini-three-adapter',\r\n outputDir: options.outputDir ?? 'assets/three',\r\n entries: [],\r\n gameJsonSuggestion: {},\r\n decoderPaths: {},\r\n };\r\n }\r\n\r\n if (options.manifest !== false) {\r\n this.emitFile({\r\n type: 'asset',\r\n fileName: 'mini-three-assets.json',\r\n source: JSON.stringify({ ...manifest, build: report, output: bundleOptions.dir ?? bundleOptions.file ?? '' }, null, 2),\r\n });\r\n }\r\n if (options.report !== false) {\r\n this.warn(\r\n `[mini-three] build report: ${report.modulesScanned} module(s) scanned, ` +\r\n `${report.modulesRewritten} rewritten, ${report.rewrites} reference(s) -> scope, ` +\r\n `${filesToEmit.size} asset(s) emitted, ${report.missingAssets.length} missing.`,\r\n );\r\n }\r\n },\r\n\r\n api: {\r\n report: () => ({\r\n ...report,\r\n globalsSeen: Array.from(seenGlobals).sort(),\r\n assetReferences: Array.from(assetRefs),\r\n webgpuWarnings: [...report.webgpuWarnings],\r\n parseFailures: [...report.parseFailures],\r\n }),\r\n },\r\n };\r\n}\r\n","/**\r\n * AST-based global-to-scope rewriting.\r\n *\r\n * The reference adapter uses a Rollup \"prefix global\" pass that effectively\r\n * text-replaces identifiers. That breaks on shadowed locals, object keys, and\r\n * `typeof window` feature detection. Here we parse with @babel/parser and use\r\n * Babel's scope binding information, so ONLY free (unbound) references to\r\n * browser globals are rewritten — application code is never touched.\r\n */\r\nimport { parse } from '@babel/parser';\r\nimport _traverse from '@babel/traverse';\r\nimport MagicString from 'magic-string';\r\nimport type { NodePath } from '@babel/traverse';\r\nimport type { Identifier } from '@babel/types';\r\nimport type { Node } from '@babel/types';\r\n\r\n// Babel's CJS/ESM interop differs between bundlers; normalize once.\r\nconst traverse = (typeof _traverse === 'function'\r\n ? _traverse\r\n : (_traverse as unknown as { default: typeof _traverse }).default) as typeof _traverse;\r\n\r\nexport const DEFAULT_GLOBAL_NAMES: readonly string[] = [\r\n 'window', 'self', 'document', 'navigator', 'screen', 'location',\r\n 'innerWidth', 'innerHeight', 'outerWidth', 'outerHeight',\r\n 'devicePixelRatio', 'pageXOffset', 'pageYOffset',\r\n 'performance', 'requestAnimationFrame', 'cancelAnimationFrame',\r\n 'getComputedStyle', 'matchMedia', 'atob', 'btoa',\r\n 'Event', 'EventTarget', 'CustomEvent', 'PointerEvent', 'MouseEvent',\r\n 'TouchEvent', 'MessageEvent', 'ProgressEvent', 'KeyboardEvent', 'DOMException',\r\n 'HTMLElement', 'HTMLCanvasElement', 'HTMLImageElement', 'HTMLVideoElement',\r\n 'OffscreenCanvas', 'Image', 'ImageData', 'DOMRect',\r\n 'WebGLRenderingContext', 'WebGL2RenderingContext', 'AudioContext',\r\n 'Blob', 'URL', 'URLSearchParams', 'FileReader', 'TextDecoder', 'TextEncoder',\r\n 'AbortController', 'AbortSignal', 'fetch', 'XMLHttpRequest', 'WebSocket',\r\n 'createImageBitmap', 'Worker', 'WebAssembly', 'ResizeObserver',\r\n];\r\n\r\n/** Globals that must remain `undefined` in the mini game scope. */\r\nexport const DEFAULT_FORCE_UNDEF: readonly string[] = ['createImageBitmap'];\r\n\r\nexport interface RewriteOptions {\r\n /** Extra global identifiers to rewrite. */\r\n extraGlobals?: string[];\r\n /** Replace the default global list instead of extending it. */\r\n globals?: string[];\r\n /** Identifiers that must evaluate to `undefined` (feature-detection off). */\r\n forceUndef?: string[];\r\n /** Name of the injected scope accessor. Default `__m3`. */\r\n accessor?: string;\r\n /** Module specifier that exports `getActiveScope`. */\r\n scopeModule?: string;\r\n}\r\n\r\n/**\r\n * Minimal source-map shape accepted by Rollup / Vite as a transform result.\r\n * Declared locally so `dist/*.d.ts` stays self-contained (`rollup` is an\r\n * optional peer). `magic-string`'s `SourceMap` satisfies it structurally.\r\n */\r\nexport interface BuildSourceMap {\r\n version: number;\r\n file?: string;\r\n sources: string[];\r\n sourcesContent?: Array<string | null>;\r\n names: string[];\r\n mappings: string;\r\n}\r\n\r\nexport interface RewriteResult {\r\n code: string;\r\n map: BuildSourceMap | null;\r\n /** Number of rewritten references. */\r\n count: number;\r\n /** Globals actually seen (useful for the build report). */\r\n seen: string[];\r\n}\r\n\r\nexport interface RewriteFailure {\r\n code: string;\r\n error: string;\r\n}\r\n\r\nexport const SCOPE_IMPORT = (\r\n accessor: string,\r\n module: string,\r\n extraSpecifiers: readonly string[] = [],\r\n): string => {\r\n const specifiers = [`getActiveScope as ${accessor}`, ...extraSpecifiers].join(', ');\r\n return `import { ${specifiers} } from '${module}';\\n`;\r\n};\r\n\r\n/**\r\n * Reference or range equality. `@babel/parser` emits TWO distinct `Identifier`\r\n * nodes with identical `[start, end]` for a shorthand property (`{ X }`: one for\r\n * `key`, one for `value`), so reference equality alone is not enough to tell\r\n * \"this identifier is an object key\".\r\n */\r\nfunction sameNode(a: unknown, b: unknown): boolean {\r\n if (a === b) return true;\r\n const x = a as { start?: number | null; end?: number | null } | null | undefined;\r\n const y = b as { start?: number | null; end?: number | null } | null | undefined;\r\n return Boolean(x && y && x.start != null && x.start === y.start && x.end === y.end);\r\n}\r\n\r\nfunction isNonComputedKey(path: NodePath): boolean {\r\n const parent = path.parentPath;\r\n if (!parent) return false;\r\n const self: unknown = path.node;\r\n if (parent.isObjectProperty() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\r\n if (parent.isObjectMethod() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\r\n if (parent.isClassProperty() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\r\n if (parent.isClassMethod() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\r\n if (parent.isMemberExpression() && !parent.node.computed && sameNode(parent.node.property, self)) return true;\r\n return false;\r\n}\r\n\r\n/**\r\n * `{ X }`: the value node shares its range with the key, so it cannot be\r\n * rewritten in place — it must be expanded to `{ X: <expr> }`.\r\n */\r\nfunction isShorthandValue(path: NodePath): boolean {\r\n const parent = path.parentPath;\r\n if (!parent?.isObjectProperty()) return false;\r\n if (!parent.node.shorthand || parent.node.computed) return false;\r\n if (parent.node.value !== path.node) return false;\r\n // `const { X } = obj` destructures a binding, never a global reference. Babel\r\n // already treats it as a binding, this guard keeps the two paths disjoint.\r\n return !parent.parentPath?.isObjectPattern();\r\n}\r\n\r\n/**\r\n * Is this identifier the left-most link of a `new X` / `new X.Y.Z` callee chain?\r\n *\r\n * `new f().g()` parses as `(new f()).g()`, so rewriting `X` to a *call*\r\n * (`__m3().X`) without parentheses silently turns `new X()` into\r\n * `(new __m3()).X()` — the scope object gets constructed and the class is then\r\n * invoked as a plain function. Wrapping only the chain root is enough:\r\n * `new (a().b).c` parses as `new ((a().b).c)`.\r\n */\r\nfunction isNewCalleeRoot(path: NodePath): boolean {\r\n let cur: NodePath = path;\r\n let parent = cur.parentPath;\r\n while (parent?.isMemberExpression() && parent.node.object === cur.node) {\r\n cur = parent;\r\n parent = parent.parentPath;\r\n }\r\n return Boolean(parent?.isNewExpression() && parent.node.callee === cur.node);\r\n}\r\n\r\n/** `typeof X` must never throw: `typeof a.b` is legal even when `a` is unbound. */\r\nfunction isDirectTypeofOperand(path: NodePath): boolean {\r\n const parent = path.parentPath;\r\n return Boolean(\r\n parent?.isUnaryExpression() &&\r\n parent.node.operator === 'typeof' &&\r\n parent.node.argument === path.node,\r\n );\r\n}\r\n\r\n/**\r\n * Globals that `getActiveScope()` resolves to itself even before a runtime\r\n * exists, so `typeof window` is already `'object'` and needs no guard.\r\n */\r\nconst ALWAYS_OBJECT_GLOBALS: ReadonlySet<string> = new Set(['window', 'self', 'globalThis']);\r\n\r\n/** Rewrite free browser-global references in one module. Returns null if nothing changed. */\r\nexport function rewriteGlobals(\r\n code: string,\r\n id: string,\r\n options: RewriteOptions = {},\r\n): RewriteResult | RewriteFailure | null {\r\n const names = new Set<string>([\r\n ...(options.globals ?? DEFAULT_GLOBAL_NAMES),\r\n ...(options.extraGlobals ?? []),\r\n ...(options.forceUndef ?? DEFAULT_FORCE_UNDEF),\r\n ]);\r\n const accessor = options.accessor ?? '__m3';\r\n const scopeModule = options.scopeModule ?? 'mini-three-adapter/scope';\r\n\r\n let ast;\r\n try {\r\n ast = parse(code, {\r\n sourceType: 'unambiguous',\r\n errorRecovery: true,\r\n plugins: ['importAttributes', 'classProperties', 'topLevelAwait', 'typescript', 'jsx'],\r\n });\r\n } catch (error) {\r\n return { code, error: `[mini-three] parse failed for ${id}: ${String(error)}` };\r\n }\r\n\r\n const ms = new MagicString(code);\r\n const seen = new Set<string>();\r\n const hasAccessor = `${accessor}Has`;\r\n let count = 0;\r\n let needsHasGuard = false;\r\n\r\n traverse(ast, {\r\n ReferencedIdentifier(path: NodePath<Node>) {\r\n const node = path.node as Identifier;\r\n const name = node.name;\r\n if (!name || !names.has(name)) return;\r\n if (node.start == null || node.end == null) return;\r\n // Babel scope knows about imports, function params, local declarations,\r\n // catch bindings and block-scoped shadowing. This is the critical check\r\n // that a regex-based replacement cannot perform.\r\n if (path.scope.hasBinding(name, true)) return;\r\n\r\n const ref = `${accessor}().${name}`;\r\n\r\n // 1) Shorthand must be handled before the key check: once `isNonComputedKey`\r\n // compares ranges, `{ X }`'s value looks like a key too and would be\r\n // silently skipped (leaving an undefined global behind).\r\n if (isShorthandValue(path)) {\r\n seen.add(name);\r\n ms.overwrite(node.start, node.end, `${name}: (${ref})`);\r\n count++;\r\n return;\r\n }\r\n\r\n // 2) Object keys / member property names are not references.\r\n if (isNonComputedKey(path)) return;\r\n\r\n seen.add(name);\r\n if (isDirectTypeofOperand(path) && !ALWAYS_OBJECT_GLOBALS.has(name)) {\r\n // `typeof X` must never throw. The placeholder scope answers the\r\n // environment globals (document/navigator/screen/...) with `undefined`\r\n // already, but everything else — TextDecoder, HTMLCanvasElement,\r\n // Blob, ... — throws an actionable error on access, and a `typeof`\r\n // probe must not become that error.\r\n ms.overwrite(node.start, node.end, `(${hasAccessor}() ? ${ref} : undefined)`);\r\n needsHasGuard = true;\r\n count++;\r\n return;\r\n }\r\n ms.overwrite(node.start, node.end, isNewCalleeRoot(path) ? `(${ref})` : ref);\r\n count++;\r\n },\r\n });\r\n\r\n if (count === 0) return null;\r\n ms.prepend(SCOPE_IMPORT(\r\n accessor,\r\n scopeModule,\r\n needsHasGuard ? [`hasActiveScope as ${hasAccessor}`] : [],\r\n ));\r\n return {\r\n code: ms.toString(),\r\n map: ms.generateMap({ source: id, includeContent: true, hires: true }),\r\n count,\r\n seen: Array.from(seen).sort(),\r\n };\r\n}\r\n","/**\r\n * Worker / WASM asset collection for three.js addons.\r\n *\r\n * DRACOLoader, KTX2Loader, 3DMLoader, LottieLoader, ... reference decoder\r\n * `.js` and `.wasm` files by string path. In a mini game those files are not\r\n * reachable via HTTP; they must be copied into the code package (ideally a\r\n * subpackage) and `setDecoderPath` must point at the copied location.\r\n *\r\n * The plugin scans transformed modules, resolves each referenced basename in a\r\n * small set of known directories, copies it, and emits a manifest plus a\r\n * `game.json` suggestion. No global state, no hidden writes.\r\n */\r\nimport { promises as fs } from 'node:fs';\r\nimport path from 'node:path';\r\n\r\nexport interface AssetOptions {\r\n /** Extra directories to search (besides three's jsm/libs). */\r\n roots?: string[];\r\n /** Output directory relative to the bundle root. Default 'assets/three'. */\r\n outputDir?: string;\r\n /** Copy `.wasm.br` alongside `.wasm` when available. Default true. */\r\n brotli?: boolean;\r\n /** Emit `mini-three-assets.json`. Default true. */\r\n manifest?: boolean;\r\n /** Working directory used to resolve roots. Default process.cwd(). */\r\n cwd?: string;\r\n}\r\n\r\nexport interface AssetEntry {\r\n /** Original string found in the module. */\r\n reference: string;\r\n /** Resolved absolute source path. */\r\n source: string;\r\n /** Relative destination inside the bundle. */\r\n destination: string;\r\n kind: 'worker' | 'wasm' | 'data';\r\n}\r\n\r\nexport interface AssetManifest {\r\n generatedBy: 'mini-three-adapter';\r\n outputDir: string;\r\n entries: AssetEntry[];\r\n /** Paste into game.json (adjust subpackage names to your project). */\r\n gameJsonSuggestion: Record<string, unknown>;\r\n /** Decoder paths to feed to loaders at runtime. */\r\n decoderPaths: Record<string, string>;\r\n}\r\n\r\nconst ASSET_PATTERN = /(['\"`])([^'\"`\\n]*\\.(?:wasm|wasm\\.br|bin|js))\\1/g;\r\nconst DECODER_KEYWORDS = [\r\n 'draco', 'basis', 'ktx2', 'rhino3dm', 'zstd', 'meshopt', 'ammo',\r\n 'worker', 'decoder', 'transcoder', 'lottie', 'sdf',\r\n];\r\n\r\nexport function collectAssetReferences(code: string): string[] {\r\n const found = new Set<string>();\r\n let match: RegExpExecArray | null;\r\n ASSET_PATTERN.lastIndex = 0;\r\n while ((match = ASSET_PATTERN.exec(code)) !== null) {\r\n const value = match[2] ?? '';\r\n const lower = value.toLowerCase();\r\n if (DECODER_KEYWORDS.some((keyword) => lower.includes(keyword))) found.add(value);\r\n }\r\n return Array.from(found);\r\n}\r\n\r\nasync function indexFiles(root: string, maxDepth = 5): Promise<Map<string, string>> {\r\n const index = new Map<string, string>();\r\n const walk = async (dir: string, depth: number): Promise<void> => {\r\n if (depth > maxDepth) return;\r\n let entries;\r\n try { entries = await fs.readdir(dir, { withFileTypes: true }); }\r\n catch { return; }\r\n for (const entry of entries) {\r\n const full = path.join(dir, entry.name);\r\n if (entry.isDirectory()) await walk(full, depth + 1);\r\n else if (entry.isFile() && !index.has(entry.name)) index.set(entry.name, full);\r\n }\r\n };\r\n await walk(root, 0);\r\n return index;\r\n}\r\n\r\nfunction classify(name: string): AssetEntry['kind'] {\r\n if (name.endsWith('.wasm') || name.endsWith('.wasm.br')) return 'wasm';\r\n if (name.endsWith('.js')) return 'worker';\r\n return 'data';\r\n}\r\n\r\nexport function defaultRoots(cwd: string): string[] {\r\n return [\r\n path.join(cwd, 'node_modules/three/examples/jsm/libs'),\r\n path.join(cwd, 'node_modules/three/examples/jsm'),\r\n path.join(cwd, 'node_modules/three-stdlib'),\r\n path.join(cwd, 'public'),\r\n path.join(cwd, 'static'),\r\n ];\r\n}\r\n\r\nexport interface CollectResult {\r\n manifest: AssetManifest;\r\n /** Files to write: destination (relative) -> absolute source. */\r\n files: Map<string, string>;\r\n missing: string[];\r\n}\r\n\r\n/** Resolve references against known roots without copying anything. */\r\nexport async function collectAssets(references: string[], options: AssetOptions = {}): Promise<CollectResult> {\r\n const cwd = options.cwd ?? process.cwd();\r\n const outputDir = (options.outputDir ?? 'assets/three').replace(/\\\\/g, '/').replace(/\\/$/, '');\r\n const roots = [...defaultRoots(cwd), ...(options.roots ?? [])];\r\n const indexes = await Promise.all(roots.map((root) => indexFiles(root)));\r\n const find = (name: string): string | undefined => {\r\n for (const index of indexes) {\r\n const hit = index.get(name);\r\n if (hit) return hit;\r\n }\r\n return undefined;\r\n };\r\n\r\n const entries: AssetEntry[] = [];\r\n const files = new Map<string, string>();\r\n const missing: string[] = [];\r\n\r\n for (const reference of references) {\r\n const base = path.posix.basename(reference.split('?')[0] ?? reference);\r\n const source = find(base);\r\n if (!source) { missing.push(reference); continue; }\r\n const entry: AssetEntry = {\r\n reference,\r\n source,\r\n destination: `${outputDir}/${base}`,\r\n kind: classify(base),\r\n };\r\n entries.push(entry);\r\n files.set(entry.destination, source);\r\n if (options.brotli !== false && entry.kind === 'wasm') {\r\n const br = find(`${base}.br`);\r\n if (br) {\r\n entries.push({ reference: `${reference}.br`, source: br, destination: `${outputDir}/${base}.br`, kind: 'wasm' });\r\n files.set(`${outputDir}/${base}.br`, br);\r\n }\r\n }\r\n }\r\n\r\n const decoderPaths: Record<string, string> = {};\r\n for (const entry of entries) {\r\n const name = path.posix.basename(entry.destination).toLowerCase();\r\n for (const key of ['draco', 'ktx2', 'basis', 'meshopt', 'rhino3dm', 'zstd', 'ammo']) {\r\n if (name.includes(key)) decoderPaths[key] = `${outputDir}/`;\r\n }\r\n }\r\n\r\n const manifest: AssetManifest = {\r\n generatedBy: 'mini-three-adapter',\r\n outputDir,\r\n entries,\r\n gameJsonSuggestion: {\r\n workers: { path: `${outputDir}`, isSubpackage: true },\r\n subpackages: [{ name: 'three-assets', root: `${outputDir}/` }],\r\n },\r\n decoderPaths,\r\n };\r\n return { manifest, files, missing };\r\n}\r\n\r\n/** Copy resolved files into `outDir`. */\r\nexport async function copyAssets(files: Map<string, string>, outDir: string): Promise<number> {\r\n let written = 0;\r\n for (const [destination, source] of files) {\r\n const target = path.join(outDir, destination);\r\n await fs.mkdir(path.dirname(target), { recursive: true });\r\n await fs.copyFile(source, target);\r\n written++;\r\n }\r\n return written;\r\n}\r\n","/** Rollup entry: `import { miniThree } from 'mini-three-adapter/rollup'`. */\r\nimport { miniThreePlugin, type MiniThreePlugin, type MiniThreePluginOptions } from './plugin-core';\r\n\r\nexport function miniThree(options: MiniThreePluginOptions = {}): MiniThreePlugin {\r\n return miniThreePlugin(options);\r\n}\r\n\r\nexport default miniThree;\r\nexport { miniThreePlugin } from './plugin-core';\r\nexport type { MiniThreePluginOptions, BuildReport } from './plugin-core';\r\nexport { DEFAULT_GLOBAL_NAMES, DEFAULT_FORCE_UNDEF, rewriteGlobals } from './scope-rewrite';\r\nexport type { RewriteOptions, RewriteResult } from './scope-rewrite';\r\nexport { collectAssetReferences, collectAssets, copyAssets } from './assets';\r\nexport type { AssetOptions, AssetManifest, AssetEntry } from './assets';\r\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;AAA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QACxE;AAAA,MACF;AAAA,IACF;AAAA,IAEA,KAAK;AAAA,MACH,QAAQ,OAAO;AAAA,QACb,GAAG;AAAA,QACH,aAAa,MAAM,KAAK,WAAW,EAAE,KAAK;AAAA,QAC1C,iBAAiB,MAAM,KAAK,SAAS;AAAA,QACrC,gBAAgB,CAAC,GAAG,OAAO,cAAc;AAAA,QACzC,eAAe,CAAC,GAAG,OAAO,aAAa;AAAA,MACzC;AAAA,IACF;AAAA,EACF;AACF;;;AGjNO,SAAS,UAAU,UAAkC,CAAC,GAAoB;AAC/E,SAAO,gBAAgB,OAAO;AAChC;AAEA,IAAO,iBAAQ;","names":["fs","path","fs"]}
|
package/dist/build/vite.js.map
CHANGED
|
@@ -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 BuildSourceMap,\n type RewriteOptions,\n} from './scope-rewrite';\nimport {\n collectAssetReferences,\n collectAssets,\n type AssetManifest,\n type AssetOptions,\n} from './assets';\n\nexport interface MiniThreePluginOptions extends AssetOptions {\n /** Extra modules to transform. Receives a normalized (slash-separated) id. */\n include?: (id: string) => boolean;\n /** Modules to skip even when they match. */\n exclude?: (id: string) => boolean;\n /** Also transform application code (off by default). */\n includeUserCode?: boolean;\n /** Rewrite options (advanced). */\n rewrite?: RewriteOptions;\n /** How to handle `three/webgpu` imports. Default 'warn'. */\n webgpu?: 'warn' | 'error' | 'rewrite' | 'ignore';\n /** Print a build report summary. Default true. */\n report?: boolean;\n /** Verbose per-module logs. */\n debug?: boolean;\n}\n\nexport interface BuildReport {\n modulesScanned: number;\n modulesRewritten: number;\n rewrites: number;\n globalsSeen: string[];\n assetReferences: string[];\n missingAssets: string[];\n webgpuWarnings: string[];\n parseFailures: string[];\n}\n\nexport interface PluginContext {\n warn(message: string): void;\n error(message: string): never;\n emitFile(file: { type: 'asset'; fileName: string; source: string | Uint8Array }): string;\n}\n\nexport interface MiniThreePlugin {\n name: string;\n enforce: 'pre';\n transform(this: PluginContext, code: string, id: string): { code: string; map: BuildSourceMap | null } | null;\n generateBundle(this: PluginContext, options: { dir?: string; file?: string }): Promise<void>;\n api: {\n report(): BuildReport;\n };\n}\n\nconst DEFAULT_INCLUDE = (id: string): boolean => {\n const normalized = id.replace(/\\\\/g, '/').split('?')[0] ?? id;\n return (\n normalized.includes('/node_modules/three/') ||\n normalized.includes('/node_modules/three-stdlib/') ||\n normalized.includes('/node_modules/@react-three/') ||\n normalized.includes('/node_modules/@tresjs/') ||\n normalized.includes('/node_modules/.vite/deps/three') ||\n normalized.includes('/node_modules/.vite/deps/three-stdlib') ||\n /\\/node_modules\\/three@[^/]+\\//.test(normalized)\n );\n};\n\nexport function miniThreePlugin(options: MiniThreePluginOptions = {}): MiniThreePlugin {\n const include = options.include ?? DEFAULT_INCLUDE;\n const exclude = options.exclude ?? (() => false);\n const webgpuMode = options.webgpu ?? 'warn';\n const report: BuildReport = {\n modulesScanned: 0,\n modulesRewritten: 0,\n rewrites: 0,\n globalsSeen: [],\n assetReferences: [],\n missingAssets: [],\n webgpuWarnings: [],\n parseFailures: [],\n };\n const seenGlobals = new Set<string>();\n const assetRefs = new Set<string>();\n let manifest: AssetManifest | null = null;\n let filesToEmit = new Map<string, string>();\n\n const note = (ctx: PluginContext, message: string): void => {\n if (options.debug) ctx.warn(`[mini-three] ${message}`);\n };\n\n return {\n name: 'mini-three-adapter',\n enforce: 'pre',\n\n transform(this: PluginContext, code: string, id: string) {\n const normalized = id.replace(/\\\\/g, '/');\n const shouldTransform = options.includeUserCode\n ? !normalized.includes('/node_modules/mini-three-adapter/') && !exclude(normalized)\n : include(normalized) && !exclude(normalized);\n if (!shouldTransform) return null;\n\n report.modulesScanned++;\n for (const ref of collectAssetReferences(code)) assetRefs.add(ref);\n\n let currentCode = code;\n if (webgpuMode !== 'ignore' && /from\\s*['\"`]three\\/webgpu['\"`]/.test(code)) {\n const message = `[mini-three] ${normalized} imports 'three/webgpu'; WebGPU is not available in WeChat mini games.`;\n report.webgpuWarnings.push(message);\n if (webgpuMode === 'error') this.error(message);\n if (webgpuMode === 'warn') this.warn(`${message} Use three's WebGLRenderer instead.`);\n if (webgpuMode === 'rewrite') {\n currentCode = currentCode\n .replace(/(['\"`])three\\/webgpu\\1/g, '$1three$1')\n .replace(/\\bWebGPURenderer\\b/g, 'WebGLRenderer');\n note(this, `rewrote three/webgpu -> three in ${normalized}`);\n }\n }\n\n const result = rewriteGlobals(currentCode, normalized, {\n ...options.rewrite,\n ...(options.rewrite?.forceUndef ? {} : { forceUndef: [...DEFAULT_FORCE_UNDEF] }),\n });\n if (result && 'error' in result) {\n report.parseFailures.push(result.error);\n this.warn(`[mini-three] ${result.error}`);\n return null;\n }\n if (!result) return webgpuMode === 'rewrite' ? { code: currentCode, map: null } : null;\n\n report.modulesRewritten++;\n report.rewrites += result.count;\n for (const name of result.seen) seenGlobals.add(name);\n note(this, `${normalized}: ${result.count} global(s) rewritten (${result.seen.join(', ')})`);\n return { code: result.code, map: result.map };\n },\n\n async generateBundle(this: PluginContext, bundleOptions) {\n const refs = Array.from(assetRefs);\n report.assetReferences = refs;\n report.globalsSeen = Array.from(seenGlobals).sort();\n\n if (refs.length > 0) {\n const collected = await collectAssets(refs, {\n cwd: options.cwd,\n roots: options.roots,\n outputDir: options.outputDir,\n brotli: options.brotli,\n manifest: options.manifest,\n });\n manifest = collected.manifest;\n filesToEmit = collected.files;\n report.missingAssets = collected.missing;\n for (const missing of collected.missing) {\n this.warn(`[mini-three] asset not found in known roots: ${missing}`);\n }\n for (const [destination, source] of filesToEmit) {\n try {\n const content = await fs.readFile(source);\n this.emitFile({ type: 'asset', fileName: destination, source: content });\n } catch (error) {\n this.warn(`[mini-three] could not emit ${destination}: ${String(error)}`);\n }\n }\n } else {\n manifest = {\n generatedBy: 'mini-three-adapter',\n outputDir: options.outputDir ?? 'assets/three',\n entries: [],\n gameJsonSuggestion: {},\n decoderPaths: {},\n };\n }\n\n if (options.manifest !== false) {\n this.emitFile({\n type: 'asset',\n fileName: 'mini-three-assets.json',\n source: JSON.stringify({ ...manifest, build: report, output: bundleOptions.dir ?? bundleOptions.file ?? '' }, null, 2),\n });\n }\n if (options.report !== false) {\n this.warn(\n `[mini-three] build report: ${report.modulesScanned} module(s) scanned, ` +\n `${report.modulesRewritten} rewritten, ${report.rewrites} reference(s) -> scope, ` +\n `${filesToEmit.size} asset(s) emitted, ${report.missingAssets.length} missing.`,\n );\n }\n },\n\n api: {\n report: () => ({\n ...report,\n globalsSeen: Array.from(seenGlobals).sort(),\n assetReferences: Array.from(assetRefs),\n webgpuWarnings: [...report.webgpuWarnings],\n parseFailures: [...report.parseFailures],\n }),\n },\n };\n}\n","/**\n * AST-based global-to-scope rewriting.\n *\n * The reference adapter uses a Rollup \"prefix global\" pass that effectively\n * text-replaces identifiers. That breaks on shadowed locals, object keys, and\n * `typeof window` feature detection. Here we parse with @babel/parser and use\n * Babel's scope binding information, so ONLY free (unbound) references to\n * browser globals are rewritten — application code is never touched.\n */\nimport { parse } from '@babel/parser';\nimport _traverse from '@babel/traverse';\nimport MagicString from 'magic-string';\nimport type { NodePath } from '@babel/traverse';\nimport type { Identifier } from '@babel/types';\nimport type { Node } from '@babel/types';\n\n// Babel's CJS/ESM interop differs between bundlers; normalize once.\nconst traverse = (typeof _traverse === 'function'\n ? _traverse\n : (_traverse as unknown as { default: typeof _traverse }).default) as typeof _traverse;\n\nexport const DEFAULT_GLOBAL_NAMES: readonly string[] = [\n 'window', 'self', 'document', 'navigator', 'screen', 'location',\n 'innerWidth', 'innerHeight', 'outerWidth', 'outerHeight',\n 'devicePixelRatio', 'pageXOffset', 'pageYOffset',\n 'performance', 'requestAnimationFrame', 'cancelAnimationFrame',\n 'getComputedStyle', 'matchMedia', 'atob', 'btoa',\n 'Event', 'EventTarget', 'CustomEvent', 'PointerEvent', 'MouseEvent',\n 'TouchEvent', 'MessageEvent', 'ProgressEvent', 'KeyboardEvent', 'DOMException',\n 'HTMLElement', 'HTMLCanvasElement', 'HTMLImageElement', 'HTMLVideoElement',\n 'OffscreenCanvas', 'Image', 'ImageData', 'DOMRect',\n 'WebGLRenderingContext', 'WebGL2RenderingContext', 'AudioContext',\n 'Blob', 'URL', 'URLSearchParams', 'FileReader', 'TextDecoder', 'TextEncoder',\n 'AbortController', 'AbortSignal', 'fetch', 'XMLHttpRequest', 'WebSocket',\n 'createImageBitmap', 'Worker', 'WebAssembly', 'ResizeObserver',\n];\n\n/** Globals that must remain `undefined` in the mini game scope. */\nexport const DEFAULT_FORCE_UNDEF: readonly string[] = ['createImageBitmap'];\n\nexport interface RewriteOptions {\n /** Extra global identifiers to rewrite. */\n extraGlobals?: string[];\n /** Replace the default global list instead of extending it. */\n globals?: string[];\n /** Identifiers that must evaluate to `undefined` (feature-detection off). */\n forceUndef?: string[];\n /** Name of the injected scope accessor. Default `__m3`. */\n accessor?: string;\n /** Module specifier that exports `getActiveScope`. */\n scopeModule?: string;\n}\n\n/**\n * Minimal source-map shape accepted by Rollup / Vite as a transform result.\n * Declared locally so `dist/*.d.ts` stays self-contained (`rollup` is an\n * optional peer). `magic-string`'s `SourceMap` satisfies it structurally.\n */\nexport interface BuildSourceMap {\n version: number;\n file?: string;\n sources: string[];\n sourcesContent?: Array<string | null>;\n names: string[];\n mappings: string;\n}\n\nexport interface RewriteResult {\n code: string;\n map: BuildSourceMap | null;\n /** Number of rewritten references. */\n count: number;\n /** Globals actually seen (useful for the build report). */\n seen: string[];\n}\n\nexport interface RewriteFailure {\n code: string;\n error: string;\n}\n\nexport const SCOPE_IMPORT = (\n accessor: string,\n module: string,\n extraSpecifiers: readonly string[] = [],\n): string => {\n const specifiers = [`getActiveScope as ${accessor}`, ...extraSpecifiers].join(', ');\n return `import { ${specifiers} } from '${module}';\\n`;\n};\n\n/**\n * Reference or range equality. `@babel/parser` emits TWO distinct `Identifier`\n * nodes with identical `[start, end]` for a shorthand property (`{ X }`: one for\n * `key`, one for `value`), so reference equality alone is not enough to tell\n * \"this identifier is an object key\".\n */\nfunction sameNode(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n const x = a as { start?: number | null; end?: number | null } | null | undefined;\n const y = b as { start?: number | null; end?: number | null } | null | undefined;\n return Boolean(x && y && x.start != null && x.start === y.start && x.end === y.end);\n}\n\nfunction isNonComputedKey(path: NodePath): boolean {\n const parent = path.parentPath;\n if (!parent) return false;\n const self: unknown = path.node;\n if (parent.isObjectProperty() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\n if (parent.isObjectMethod() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\n if (parent.isClassProperty() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\n if (parent.isClassMethod() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\n if (parent.isMemberExpression() && !parent.node.computed && sameNode(parent.node.property, self)) return true;\n return false;\n}\n\n/**\n * `{ X }`: the value node shares its range with the key, so it cannot be\n * rewritten in place — it must be expanded to `{ X: <expr> }`.\n */\nfunction isShorthandValue(path: NodePath): boolean {\n const parent = path.parentPath;\n if (!parent?.isObjectProperty()) return false;\n if (!parent.node.shorthand || parent.node.computed) return false;\n if (parent.node.value !== path.node) return false;\n // `const { X } = obj` destructures a binding, never a global reference. Babel\n // already treats it as a binding, this guard keeps the two paths disjoint.\n return !parent.parentPath?.isObjectPattern();\n}\n\n/**\n * Is this identifier the left-most link of a `new X` / `new X.Y.Z` callee chain?\n *\n * `new f().g()` parses as `(new f()).g()`, so rewriting `X` to a *call*\n * (`__m3().X`) without parentheses silently turns `new X()` into\n * `(new __m3()).X()` — the scope object gets constructed and the class is then\n * invoked as a plain function. Wrapping only the chain root is enough:\n * `new (a().b).c` parses as `new ((a().b).c)`.\n */\nfunction isNewCalleeRoot(path: NodePath): boolean {\n let cur: NodePath = path;\n let parent = cur.parentPath;\n while (parent?.isMemberExpression() && parent.node.object === cur.node) {\n cur = parent;\n parent = parent.parentPath;\n }\n return Boolean(parent?.isNewExpression() && parent.node.callee === cur.node);\n}\n\n/** `typeof X` must never throw: `typeof a.b` is legal even when `a` is unbound. */\nfunction isDirectTypeofOperand(path: NodePath): boolean {\n const parent = path.parentPath;\n return Boolean(\n parent?.isUnaryExpression() &&\n parent.node.operator === 'typeof' &&\n parent.node.argument === path.node,\n );\n}\n\n/**\n * Globals that `getActiveScope()` resolves to itself even before a runtime\n * exists, so `typeof window` is already `'object'` and needs no guard.\n */\nconst ALWAYS_OBJECT_GLOBALS: ReadonlySet<string> = new Set(['window', 'self', 'globalThis']);\n\n/** Rewrite free browser-global references in one module. Returns null if nothing changed. */\nexport function rewriteGlobals(\n code: string,\n id: string,\n options: RewriteOptions = {},\n): RewriteResult | RewriteFailure | null {\n const names = new Set<string>([\n ...(options.globals ?? DEFAULT_GLOBAL_NAMES),\n ...(options.extraGlobals ?? []),\n ...(options.forceUndef ?? DEFAULT_FORCE_UNDEF),\n ]);\n const accessor = options.accessor ?? '__m3';\n const scopeModule = options.scopeModule ?? 'mini-three-adapter/scope';\n\n let ast;\n try {\n ast = parse(code, {\n sourceType: 'unambiguous',\n errorRecovery: true,\n plugins: ['importAttributes', 'classProperties', 'topLevelAwait', 'typescript', 'jsx'],\n });\n } catch (error) {\n return { code, error: `[mini-three] parse failed for ${id}: ${String(error)}` };\n }\n\n const ms = new MagicString(code);\n const seen = new Set<string>();\n const hasAccessor = `${accessor}Has`;\n let count = 0;\n let needsHasGuard = false;\n\n traverse(ast, {\n ReferencedIdentifier(path: NodePath<Node>) {\n const node = path.node as Identifier;\n const name = node.name;\n if (!name || !names.has(name)) return;\n if (node.start == null || node.end == null) return;\n // Babel scope knows about imports, function params, local declarations,\n // catch bindings and block-scoped shadowing. This is the critical check\n // that a regex-based replacement cannot perform.\n if (path.scope.hasBinding(name, true)) return;\n\n const ref = `${accessor}().${name}`;\n\n // 1) Shorthand must be handled before the key check: once `isNonComputedKey`\n // compares ranges, `{ X }`'s value looks like a key too and would be\n // silently skipped (leaving an undefined global behind).\n if (isShorthandValue(path)) {\n seen.add(name);\n ms.overwrite(node.start, node.end, `${name}: (${ref})`);\n count++;\n return;\n }\n\n // 2) Object keys / member property names are not references.\n if (isNonComputedKey(path)) return;\n\n seen.add(name);\n if (isDirectTypeofOperand(path) && !ALWAYS_OBJECT_GLOBALS.has(name)) {\n // `typeof X` must never throw. The placeholder scope answers the\n // environment globals (document/navigator/screen/...) with `undefined`\n // already, but everything else — TextDecoder, HTMLCanvasElement,\n // Blob, ... — throws an actionable error on access, and a `typeof`\n // probe must not become that error.\n ms.overwrite(node.start, node.end, `(${hasAccessor}() ? ${ref} : undefined)`);\n needsHasGuard = true;\n count++;\n return;\n }\n ms.overwrite(node.start, node.end, isNewCalleeRoot(path) ? `(${ref})` : ref);\n count++;\n },\n });\n\n if (count === 0) return null;\n ms.prepend(SCOPE_IMPORT(\n accessor,\n scopeModule,\n needsHasGuard ? [`hasActiveScope as ${hasAccessor}`] : [],\n ));\n return {\n code: ms.toString(),\n map: ms.generateMap({ source: id, includeContent: true, hires: true }),\n count,\n seen: Array.from(seen).sort(),\n };\n}\n","/**\n * Worker / WASM asset collection for three.js addons.\n *\n * DRACOLoader, KTX2Loader, 3DMLoader, LottieLoader, ... reference decoder\n * `.js` and `.wasm` files by string path. In a mini game those files are not\n * reachable via HTTP; they must be copied into the code package (ideally a\n * subpackage) and `setDecoderPath` must point at the copied location.\n *\n * The plugin scans transformed modules, resolves each referenced basename in a\n * small set of known directories, copies it, and emits a manifest plus a\n * `game.json` suggestion. No global state, no hidden writes.\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\n\nexport interface AssetOptions {\n /** Extra directories to search (besides three's jsm/libs). */\n roots?: string[];\n /** Output directory relative to the bundle root. Default 'assets/three'. */\n outputDir?: string;\n /** Copy `.wasm.br` alongside `.wasm` when available. Default true. */\n brotli?: boolean;\n /** Emit `mini-three-assets.json`. Default true. */\n manifest?: boolean;\n /** Working directory used to resolve roots. Default process.cwd(). */\n cwd?: string;\n}\n\nexport interface AssetEntry {\n /** Original string found in the module. */\n reference: string;\n /** Resolved absolute source path. */\n source: string;\n /** Relative destination inside the bundle. */\n destination: string;\n kind: 'worker' | 'wasm' | 'data';\n}\n\nexport interface AssetManifest {\n generatedBy: 'mini-three-adapter';\n outputDir: string;\n entries: AssetEntry[];\n /** Paste into game.json (adjust subpackage names to your project). */\n gameJsonSuggestion: Record<string, unknown>;\n /** Decoder paths to feed to loaders at runtime. */\n decoderPaths: Record<string, string>;\n}\n\nconst ASSET_PATTERN = /(['\"`])([^'\"`\\n]*\\.(?:wasm|wasm\\.br|bin|js))\\1/g;\nconst DECODER_KEYWORDS = [\n 'draco', 'basis', 'ktx2', 'rhino3dm', 'zstd', 'meshopt', 'ammo',\n 'worker', 'decoder', 'transcoder', 'lottie', 'sdf',\n];\n\nexport function collectAssetReferences(code: string): string[] {\n const found = new Set<string>();\n let match: RegExpExecArray | null;\n ASSET_PATTERN.lastIndex = 0;\n while ((match = ASSET_PATTERN.exec(code)) !== null) {\n const value = match[2] ?? '';\n const lower = value.toLowerCase();\n if (DECODER_KEYWORDS.some((keyword) => lower.includes(keyword))) found.add(value);\n }\n return Array.from(found);\n}\n\nasync function indexFiles(root: string, maxDepth = 5): Promise<Map<string, string>> {\n const index = new Map<string, string>();\n const walk = async (dir: string, depth: number): Promise<void> => {\n if (depth > maxDepth) return;\n let entries;\n try { entries = await fs.readdir(dir, { withFileTypes: true }); }\n catch { return; }\n for (const entry of entries) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) await walk(full, depth + 1);\n else if (entry.isFile() && !index.has(entry.name)) index.set(entry.name, full);\n }\n };\n await walk(root, 0);\n return index;\n}\n\nfunction classify(name: string): AssetEntry['kind'] {\n if (name.endsWith('.wasm') || name.endsWith('.wasm.br')) return 'wasm';\n if (name.endsWith('.js')) return 'worker';\n return 'data';\n}\n\nexport function defaultRoots(cwd: string): string[] {\n return [\n path.join(cwd, 'node_modules/three/examples/jsm/libs'),\n path.join(cwd, 'node_modules/three/examples/jsm'),\n path.join(cwd, 'node_modules/three-stdlib'),\n path.join(cwd, 'public'),\n path.join(cwd, 'static'),\n ];\n}\n\nexport interface CollectResult {\n manifest: AssetManifest;\n /** Files to write: destination (relative) -> absolute source. */\n files: Map<string, string>;\n missing: string[];\n}\n\n/** Resolve references against known roots without copying anything. */\nexport async function collectAssets(references: string[], options: AssetOptions = {}): Promise<CollectResult> {\n const cwd = options.cwd ?? process.cwd();\n const outputDir = (options.outputDir ?? 'assets/three').replace(/\\\\/g, '/').replace(/\\/$/, '');\n const roots = [...defaultRoots(cwd), ...(options.roots ?? [])];\n const indexes = await Promise.all(roots.map((root) => indexFiles(root)));\n const find = (name: string): string | undefined => {\n for (const index of indexes) {\n const hit = index.get(name);\n if (hit) return hit;\n }\n return undefined;\n };\n\n const entries: AssetEntry[] = [];\n const files = new Map<string, string>();\n const missing: string[] = [];\n\n for (const reference of references) {\n const base = path.posix.basename(reference.split('?')[0] ?? reference);\n const source = find(base);\n if (!source) { missing.push(reference); continue; }\n const entry: AssetEntry = {\n reference,\n source,\n destination: `${outputDir}/${base}`,\n kind: classify(base),\n };\n entries.push(entry);\n files.set(entry.destination, source);\n if (options.brotli !== false && entry.kind === 'wasm') {\n const br = find(`${base}.br`);\n if (br) {\n entries.push({ reference: `${reference}.br`, source: br, destination: `${outputDir}/${base}.br`, kind: 'wasm' });\n files.set(`${outputDir}/${base}.br`, br);\n }\n }\n }\n\n const decoderPaths: Record<string, string> = {};\n for (const entry of entries) {\n const name = path.posix.basename(entry.destination).toLowerCase();\n for (const key of ['draco', 'ktx2', 'basis', 'meshopt', 'rhino3dm', 'zstd', 'ammo']) {\n if (name.includes(key)) decoderPaths[key] = `${outputDir}/`;\n }\n }\n\n const manifest: AssetManifest = {\n generatedBy: 'mini-three-adapter',\n outputDir,\n entries,\n gameJsonSuggestion: {\n workers: { path: `${outputDir}`, isSubpackage: true },\n subpackages: [{ name: 'three-assets', root: `${outputDir}/` }],\n },\n decoderPaths,\n };\n return { manifest, files, missing };\n}\n\n/** Copy resolved files into `outDir`. */\nexport async function copyAssets(files: Map<string, string>, outDir: string): Promise<number> {\n let written = 0;\n for (const [destination, source] of files) {\n const target = path.join(outDir, destination);\n await fs.mkdir(path.dirname(target), { recursive: true });\n await fs.copyFile(source, target);\n written++;\n }\n return written;\n}\n","/** Vite entry: `import miniThree from 'mini-three-adapter/vite'`. */\nimport { miniThreePlugin, type MiniThreePlugin, type MiniThreePluginOptions } from './plugin-core';\n\nexport interface ViteMiniThreePlugin extends MiniThreePlugin {\n config(): Record<string, unknown>;\n}\n\n/**\n * Vite plugin. `optimizeDeps.exclude` keeps three's ESM sources intact so the\n * AST rewrite sees the original module graph instead of a pre-bundled blob.\n */\nexport function miniThree(options: MiniThreePluginOptions = {}): ViteMiniThreePlugin {\n const core = miniThreePlugin(options);\n return {\n ...core,\n config() {\n return {\n optimizeDeps: {\n exclude: ['three', 'three-stdlib', 'three/examples/jsm'],\n },\n build: {\n commonjsOptions: { transformMixedEsModules: true },\n rollupOptions: {\n output: {\n manualChunks: undefined,\n },\n },\n },\n };\n },\n };\n}\n\nexport default miniThree;\nexport { miniThreePlugin } from './plugin-core';\nexport type { MiniThreePluginOptions, BuildReport } from './plugin-core';\n"],"mappings":";AASA,SAAS,YAAYA,WAAU;;;ACA/B,SAAS,aAAa;AACtB,OAAO,eAAe;AACtB,OAAO,iBAAiB;AAMxB,IAAM,WAAY,OAAO,cAAc,aACnC,YACC,UAAuD;AAErD,IAAM,uBAA0C;AAAA,EACrD;AAAA,EAAU;AAAA,EAAQ;AA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AM,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;;;AGzMO,SAAS,UAAU,UAAkC,CAAC,GAAwB;AACnF,QAAM,OAAO,gBAAgB,OAAO;AACpC,SAAO;AAAA,IACL,GAAG;AAAA,IACH,SAAS;AACP,aAAO;AAAA,QACL,cAAc;AAAA,UACZ,SAAS,CAAC,SAAS,gBAAgB,oBAAoB;AAAA,QACzD;AAAA,QACA,OAAO;AAAA,UACL,iBAAiB,EAAE,yBAAyB,KAAK;AAAA,UACjD,eAAe;AAAA,YACb,QAAQ;AAAA,cACN,cAAc;AAAA,YAChB;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AAEA,IAAO,eAAQ;","names":["fs","path","fs"]}
|
|
1
|
+
{"version":3,"sources":["../../src/build/plugin-core.ts","../../src/build/scope-rewrite.ts","../../src/build/assets.ts","../../src/build/vite.ts"],"sourcesContent":["/**\r\n * Rollup/Vite-compatible plugin core (zero hard dependency on either bundler).\r\n *\r\n * Responsibilities:\r\n * 1. Rewrite free browser globals inside third-party modules to scoped access.\r\n * 2. Handle `three/webgpu` (WebGPU is unavailable in WeChat mini games).\r\n * 3. Collect worker/wasm assets referenced by addons and emit them + a manifest.\r\n * 4. Produce a machine-readable build report for CI and AI-assisted iteration.\r\n */\r\nimport { promises as fs } from 'node:fs';\r\nimport {\r\n DEFAULT_FORCE_UNDEF,\r\n rewriteGlobals,\r\n type BuildSourceMap,\r\n type RewriteOptions,\r\n} from './scope-rewrite';\r\nimport {\r\n collectAssetReferences,\r\n collectAssets,\r\n type AssetManifest,\r\n type AssetOptions,\r\n} from './assets';\r\n\r\nexport interface MiniThreePluginOptions extends AssetOptions {\r\n /** Extra modules to transform. Receives a normalized (slash-separated) id. */\r\n include?: (id: string) => boolean;\r\n /** Modules to skip even when they match. */\r\n exclude?: (id: string) => boolean;\r\n /** Also transform application code (off by default). */\r\n includeUserCode?: boolean;\r\n /** Rewrite options (advanced). */\r\n rewrite?: RewriteOptions;\r\n /** How to handle `three/webgpu` imports. Default 'warn'. */\r\n webgpu?: 'warn' | 'error' | 'rewrite' | 'ignore';\r\n /** Print a build report summary. Default true. */\r\n report?: boolean;\r\n /** Verbose per-module logs. */\r\n debug?: boolean;\r\n}\r\n\r\nexport interface BuildReport {\r\n modulesScanned: number;\r\n modulesRewritten: number;\r\n rewrites: number;\r\n globalsSeen: string[];\r\n assetReferences: string[];\r\n missingAssets: string[];\r\n webgpuWarnings: string[];\r\n parseFailures: string[];\r\n}\r\n\r\nexport interface PluginContext {\r\n warn(message: string): void;\r\n error(message: string): never;\r\n emitFile(file: { type: 'asset'; fileName: string; source: string | Uint8Array }): string;\r\n}\r\n\r\nexport interface MiniThreePlugin {\r\n name: string;\r\n enforce: 'pre';\r\n transform(this: PluginContext, code: string, id: string): { code: string; map: BuildSourceMap | null } | null;\r\n generateBundle(this: PluginContext, options: { dir?: string; file?: string }): Promise<void>;\r\n api: {\r\n report(): BuildReport;\r\n };\r\n}\r\n\r\nconst DEFAULT_INCLUDE = (id: string): boolean => {\r\n const normalized = id.replace(/\\\\/g, '/').split('?')[0] ?? id;\r\n return (\r\n normalized.includes('/node_modules/three/') ||\r\n normalized.includes('/node_modules/three-stdlib/') ||\r\n normalized.includes('/node_modules/@react-three/') ||\r\n normalized.includes('/node_modules/@tresjs/') ||\r\n normalized.includes('/node_modules/.vite/deps/three') ||\r\n normalized.includes('/node_modules/.vite/deps/three-stdlib') ||\r\n /\\/node_modules\\/three@[^/]+\\//.test(normalized)\r\n );\r\n};\r\n\r\nexport function miniThreePlugin(options: MiniThreePluginOptions = {}): MiniThreePlugin {\r\n const include = options.include ?? DEFAULT_INCLUDE;\r\n const exclude = options.exclude ?? (() => false);\r\n const webgpuMode = options.webgpu ?? 'warn';\r\n const report: BuildReport = {\r\n modulesScanned: 0,\r\n modulesRewritten: 0,\r\n rewrites: 0,\r\n globalsSeen: [],\r\n assetReferences: [],\r\n missingAssets: [],\r\n webgpuWarnings: [],\r\n parseFailures: [],\r\n };\r\n const seenGlobals = new Set<string>();\r\n const assetRefs = new Set<string>();\r\n let manifest: AssetManifest | null = null;\r\n let filesToEmit = new Map<string, string>();\r\n\r\n const note = (ctx: PluginContext, message: string): void => {\r\n if (options.debug) ctx.warn(`[mini-three] ${message}`);\r\n };\r\n\r\n return {\r\n name: 'mini-three-adapter',\r\n enforce: 'pre',\r\n\r\n transform(this: PluginContext, code: string, id: string) {\r\n const normalized = id.replace(/\\\\/g, '/');\r\n const shouldTransform = options.includeUserCode\r\n ? !normalized.includes('/node_modules/mini-three-adapter/') && !exclude(normalized)\r\n : include(normalized) && !exclude(normalized);\r\n if (!shouldTransform) return null;\r\n\r\n report.modulesScanned++;\r\n for (const ref of collectAssetReferences(code)) assetRefs.add(ref);\r\n\r\n let currentCode = code;\r\n if (webgpuMode !== 'ignore' && /from\\s*['\"`]three\\/webgpu['\"`]/.test(code)) {\r\n const message = `[mini-three] ${normalized} imports 'three/webgpu'; WebGPU is not available in WeChat mini games.`;\r\n report.webgpuWarnings.push(message);\r\n if (webgpuMode === 'error') this.error(message);\r\n if (webgpuMode === 'warn') this.warn(`${message} Use three's WebGLRenderer instead.`);\r\n if (webgpuMode === 'rewrite') {\r\n currentCode = currentCode\r\n .replace(/(['\"`])three\\/webgpu\\1/g, '$1three$1')\r\n .replace(/\\bWebGPURenderer\\b/g, 'WebGLRenderer');\r\n note(this, `rewrote three/webgpu -> three in ${normalized}`);\r\n }\r\n }\r\n\r\n const result = rewriteGlobals(currentCode, normalized, {\r\n ...options.rewrite,\r\n ...(options.rewrite?.forceUndef ? {} : { forceUndef: [...DEFAULT_FORCE_UNDEF] }),\r\n });\r\n if (result && 'error' in result) {\r\n report.parseFailures.push(result.error);\r\n this.warn(`[mini-three] ${result.error}`);\r\n return null;\r\n }\r\n if (!result) return webgpuMode === 'rewrite' ? { code: currentCode, map: null } : null;\r\n\r\n report.modulesRewritten++;\r\n report.rewrites += result.count;\r\n for (const name of result.seen) seenGlobals.add(name);\r\n note(this, `${normalized}: ${result.count} global(s) rewritten (${result.seen.join(', ')})`);\r\n return { code: result.code, map: result.map };\r\n },\r\n\r\n async generateBundle(this: PluginContext, bundleOptions) {\r\n const refs = Array.from(assetRefs);\r\n report.assetReferences = refs;\r\n report.globalsSeen = Array.from(seenGlobals).sort();\r\n\r\n if (refs.length > 0) {\r\n const collected = await collectAssets(refs, {\r\n cwd: options.cwd,\r\n roots: options.roots,\r\n outputDir: options.outputDir,\r\n brotli: options.brotli,\r\n manifest: options.manifest,\r\n });\r\n manifest = collected.manifest;\r\n filesToEmit = collected.files;\r\n report.missingAssets = collected.missing;\r\n for (const missing of collected.missing) {\r\n this.warn(`[mini-three] asset not found in known roots: ${missing}`);\r\n }\r\n for (const [destination, source] of filesToEmit) {\r\n try {\r\n const content = await fs.readFile(source);\r\n this.emitFile({ type: 'asset', fileName: destination, source: content });\r\n } catch (error) {\r\n this.warn(`[mini-three] could not emit ${destination}: ${String(error)}`);\r\n }\r\n }\r\n } else {\r\n manifest = {\r\n generatedBy: 'mini-three-adapter',\r\n outputDir: options.outputDir ?? 'assets/three',\r\n entries: [],\r\n gameJsonSuggestion: {},\r\n decoderPaths: {},\r\n };\r\n }\r\n\r\n if (options.manifest !== false) {\r\n this.emitFile({\r\n type: 'asset',\r\n fileName: 'mini-three-assets.json',\r\n source: JSON.stringify({ ...manifest, build: report, output: bundleOptions.dir ?? bundleOptions.file ?? '' }, null, 2),\r\n });\r\n }\r\n if (options.report !== false) {\r\n this.warn(\r\n `[mini-three] build report: ${report.modulesScanned} module(s) scanned, ` +\r\n `${report.modulesRewritten} rewritten, ${report.rewrites} reference(s) -> scope, ` +\r\n `${filesToEmit.size} asset(s) emitted, ${report.missingAssets.length} missing.`,\r\n );\r\n }\r\n },\r\n\r\n api: {\r\n report: () => ({\r\n ...report,\r\n globalsSeen: Array.from(seenGlobals).sort(),\r\n assetReferences: Array.from(assetRefs),\r\n webgpuWarnings: [...report.webgpuWarnings],\r\n parseFailures: [...report.parseFailures],\r\n }),\r\n },\r\n };\r\n}\r\n","/**\r\n * AST-based global-to-scope rewriting.\r\n *\r\n * The reference adapter uses a Rollup \"prefix global\" pass that effectively\r\n * text-replaces identifiers. That breaks on shadowed locals, object keys, and\r\n * `typeof window` feature detection. Here we parse with @babel/parser and use\r\n * Babel's scope binding information, so ONLY free (unbound) references to\r\n * browser globals are rewritten — application code is never touched.\r\n */\r\nimport { parse } from '@babel/parser';\r\nimport _traverse from '@babel/traverse';\r\nimport MagicString from 'magic-string';\r\nimport type { NodePath } from '@babel/traverse';\r\nimport type { Identifier } from '@babel/types';\r\nimport type { Node } from '@babel/types';\r\n\r\n// Babel's CJS/ESM interop differs between bundlers; normalize once.\r\nconst traverse = (typeof _traverse === 'function'\r\n ? _traverse\r\n : (_traverse as unknown as { default: typeof _traverse }).default) as typeof _traverse;\r\n\r\nexport const DEFAULT_GLOBAL_NAMES: readonly string[] = [\r\n 'window', 'self', 'document', 'navigator', 'screen', 'location',\r\n 'innerWidth', 'innerHeight', 'outerWidth', 'outerHeight',\r\n 'devicePixelRatio', 'pageXOffset', 'pageYOffset',\r\n 'performance', 'requestAnimationFrame', 'cancelAnimationFrame',\r\n 'getComputedStyle', 'matchMedia', 'atob', 'btoa',\r\n 'Event', 'EventTarget', 'CustomEvent', 'PointerEvent', 'MouseEvent',\r\n 'TouchEvent', 'MessageEvent', 'ProgressEvent', 'KeyboardEvent', 'DOMException',\r\n 'HTMLElement', 'HTMLCanvasElement', 'HTMLImageElement', 'HTMLVideoElement',\r\n 'OffscreenCanvas', 'Image', 'ImageData', 'DOMRect',\r\n 'WebGLRenderingContext', 'WebGL2RenderingContext', 'AudioContext',\r\n 'Blob', 'URL', 'URLSearchParams', 'FileReader', 'TextDecoder', 'TextEncoder',\r\n 'AbortController', 'AbortSignal', 'fetch', 'XMLHttpRequest', 'WebSocket',\r\n 'createImageBitmap', 'Worker', 'WebAssembly', 'ResizeObserver',\r\n];\r\n\r\n/** Globals that must remain `undefined` in the mini game scope. */\r\nexport const DEFAULT_FORCE_UNDEF: readonly string[] = ['createImageBitmap'];\r\n\r\nexport interface RewriteOptions {\r\n /** Extra global identifiers to rewrite. */\r\n extraGlobals?: string[];\r\n /** Replace the default global list instead of extending it. */\r\n globals?: string[];\r\n /** Identifiers that must evaluate to `undefined` (feature-detection off). */\r\n forceUndef?: string[];\r\n /** Name of the injected scope accessor. Default `__m3`. */\r\n accessor?: string;\r\n /** Module specifier that exports `getActiveScope`. */\r\n scopeModule?: string;\r\n}\r\n\r\n/**\r\n * Minimal source-map shape accepted by Rollup / Vite as a transform result.\r\n * Declared locally so `dist/*.d.ts` stays self-contained (`rollup` is an\r\n * optional peer). `magic-string`'s `SourceMap` satisfies it structurally.\r\n */\r\nexport interface BuildSourceMap {\r\n version: number;\r\n file?: string;\r\n sources: string[];\r\n sourcesContent?: Array<string | null>;\r\n names: string[];\r\n mappings: string;\r\n}\r\n\r\nexport interface RewriteResult {\r\n code: string;\r\n map: BuildSourceMap | null;\r\n /** Number of rewritten references. */\r\n count: number;\r\n /** Globals actually seen (useful for the build report). */\r\n seen: string[];\r\n}\r\n\r\nexport interface RewriteFailure {\r\n code: string;\r\n error: string;\r\n}\r\n\r\nexport const SCOPE_IMPORT = (\r\n accessor: string,\r\n module: string,\r\n extraSpecifiers: readonly string[] = [],\r\n): string => {\r\n const specifiers = [`getActiveScope as ${accessor}`, ...extraSpecifiers].join(', ');\r\n return `import { ${specifiers} } from '${module}';\\n`;\r\n};\r\n\r\n/**\r\n * Reference or range equality. `@babel/parser` emits TWO distinct `Identifier`\r\n * nodes with identical `[start, end]` for a shorthand property (`{ X }`: one for\r\n * `key`, one for `value`), so reference equality alone is not enough to tell\r\n * \"this identifier is an object key\".\r\n */\r\nfunction sameNode(a: unknown, b: unknown): boolean {\r\n if (a === b) return true;\r\n const x = a as { start?: number | null; end?: number | null } | null | undefined;\r\n const y = b as { start?: number | null; end?: number | null } | null | undefined;\r\n return Boolean(x && y && x.start != null && x.start === y.start && x.end === y.end);\r\n}\r\n\r\nfunction isNonComputedKey(path: NodePath): boolean {\r\n const parent = path.parentPath;\r\n if (!parent) return false;\r\n const self: unknown = path.node;\r\n if (parent.isObjectProperty() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\r\n if (parent.isObjectMethod() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\r\n if (parent.isClassProperty() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\r\n if (parent.isClassMethod() && !parent.node.computed && sameNode(parent.node.key, self)) return true;\r\n if (parent.isMemberExpression() && !parent.node.computed && sameNode(parent.node.property, self)) return true;\r\n return false;\r\n}\r\n\r\n/**\r\n * `{ X }`: the value node shares its range with the key, so it cannot be\r\n * rewritten in place — it must be expanded to `{ X: <expr> }`.\r\n */\r\nfunction isShorthandValue(path: NodePath): boolean {\r\n const parent = path.parentPath;\r\n if (!parent?.isObjectProperty()) return false;\r\n if (!parent.node.shorthand || parent.node.computed) return false;\r\n if (parent.node.value !== path.node) return false;\r\n // `const { X } = obj` destructures a binding, never a global reference. Babel\r\n // already treats it as a binding, this guard keeps the two paths disjoint.\r\n return !parent.parentPath?.isObjectPattern();\r\n}\r\n\r\n/**\r\n * Is this identifier the left-most link of a `new X` / `new X.Y.Z` callee chain?\r\n *\r\n * `new f().g()` parses as `(new f()).g()`, so rewriting `X` to a *call*\r\n * (`__m3().X`) without parentheses silently turns `new X()` into\r\n * `(new __m3()).X()` — the scope object gets constructed and the class is then\r\n * invoked as a plain function. Wrapping only the chain root is enough:\r\n * `new (a().b).c` parses as `new ((a().b).c)`.\r\n */\r\nfunction isNewCalleeRoot(path: NodePath): boolean {\r\n let cur: NodePath = path;\r\n let parent = cur.parentPath;\r\n while (parent?.isMemberExpression() && parent.node.object === cur.node) {\r\n cur = parent;\r\n parent = parent.parentPath;\r\n }\r\n return Boolean(parent?.isNewExpression() && parent.node.callee === cur.node);\r\n}\r\n\r\n/** `typeof X` must never throw: `typeof a.b` is legal even when `a` is unbound. */\r\nfunction isDirectTypeofOperand(path: NodePath): boolean {\r\n const parent = path.parentPath;\r\n return Boolean(\r\n parent?.isUnaryExpression() &&\r\n parent.node.operator === 'typeof' &&\r\n parent.node.argument === path.node,\r\n );\r\n}\r\n\r\n/**\r\n * Globals that `getActiveScope()` resolves to itself even before a runtime\r\n * exists, so `typeof window` is already `'object'` and needs no guard.\r\n */\r\nconst ALWAYS_OBJECT_GLOBALS: ReadonlySet<string> = new Set(['window', 'self', 'globalThis']);\r\n\r\n/** Rewrite free browser-global references in one module. Returns null if nothing changed. */\r\nexport function rewriteGlobals(\r\n code: string,\r\n id: string,\r\n options: RewriteOptions = {},\r\n): RewriteResult | RewriteFailure | null {\r\n const names = new Set<string>([\r\n ...(options.globals ?? DEFAULT_GLOBAL_NAMES),\r\n ...(options.extraGlobals ?? []),\r\n ...(options.forceUndef ?? DEFAULT_FORCE_UNDEF),\r\n ]);\r\n const accessor = options.accessor ?? '__m3';\r\n const scopeModule = options.scopeModule ?? 'mini-three-adapter/scope';\r\n\r\n let ast;\r\n try {\r\n ast = parse(code, {\r\n sourceType: 'unambiguous',\r\n errorRecovery: true,\r\n plugins: ['importAttributes', 'classProperties', 'topLevelAwait', 'typescript', 'jsx'],\r\n });\r\n } catch (error) {\r\n return { code, error: `[mini-three] parse failed for ${id}: ${String(error)}` };\r\n }\r\n\r\n const ms = new MagicString(code);\r\n const seen = new Set<string>();\r\n const hasAccessor = `${accessor}Has`;\r\n let count = 0;\r\n let needsHasGuard = false;\r\n\r\n traverse(ast, {\r\n ReferencedIdentifier(path: NodePath<Node>) {\r\n const node = path.node as Identifier;\r\n const name = node.name;\r\n if (!name || !names.has(name)) return;\r\n if (node.start == null || node.end == null) return;\r\n // Babel scope knows about imports, function params, local declarations,\r\n // catch bindings and block-scoped shadowing. This is the critical check\r\n // that a regex-based replacement cannot perform.\r\n if (path.scope.hasBinding(name, true)) return;\r\n\r\n const ref = `${accessor}().${name}`;\r\n\r\n // 1) Shorthand must be handled before the key check: once `isNonComputedKey`\r\n // compares ranges, `{ X }`'s value looks like a key too and would be\r\n // silently skipped (leaving an undefined global behind).\r\n if (isShorthandValue(path)) {\r\n seen.add(name);\r\n ms.overwrite(node.start, node.end, `${name}: (${ref})`);\r\n count++;\r\n return;\r\n }\r\n\r\n // 2) Object keys / member property names are not references.\r\n if (isNonComputedKey(path)) return;\r\n\r\n seen.add(name);\r\n if (isDirectTypeofOperand(path) && !ALWAYS_OBJECT_GLOBALS.has(name)) {\r\n // `typeof X` must never throw. The placeholder scope answers the\r\n // environment globals (document/navigator/screen/...) with `undefined`\r\n // already, but everything else — TextDecoder, HTMLCanvasElement,\r\n // Blob, ... — throws an actionable error on access, and a `typeof`\r\n // probe must not become that error.\r\n ms.overwrite(node.start, node.end, `(${hasAccessor}() ? ${ref} : undefined)`);\r\n needsHasGuard = true;\r\n count++;\r\n return;\r\n }\r\n ms.overwrite(node.start, node.end, isNewCalleeRoot(path) ? `(${ref})` : ref);\r\n count++;\r\n },\r\n });\r\n\r\n if (count === 0) return null;\r\n ms.prepend(SCOPE_IMPORT(\r\n accessor,\r\n scopeModule,\r\n needsHasGuard ? [`hasActiveScope as ${hasAccessor}`] : [],\r\n ));\r\n return {\r\n code: ms.toString(),\r\n map: ms.generateMap({ source: id, includeContent: true, hires: true }),\r\n count,\r\n seen: Array.from(seen).sort(),\r\n };\r\n}\r\n","/**\r\n * Worker / WASM asset collection for three.js addons.\r\n *\r\n * DRACOLoader, KTX2Loader, 3DMLoader, LottieLoader, ... reference decoder\r\n * `.js` and `.wasm` files by string path. In a mini game those files are not\r\n * reachable via HTTP; they must be copied into the code package (ideally a\r\n * subpackage) and `setDecoderPath` must point at the copied location.\r\n *\r\n * The plugin scans transformed modules, resolves each referenced basename in a\r\n * small set of known directories, copies it, and emits a manifest plus a\r\n * `game.json` suggestion. No global state, no hidden writes.\r\n */\r\nimport { promises as fs } from 'node:fs';\r\nimport path from 'node:path';\r\n\r\nexport interface AssetOptions {\r\n /** Extra directories to search (besides three's jsm/libs). */\r\n roots?: string[];\r\n /** Output directory relative to the bundle root. Default 'assets/three'. */\r\n outputDir?: string;\r\n /** Copy `.wasm.br` alongside `.wasm` when available. Default true. */\r\n brotli?: boolean;\r\n /** Emit `mini-three-assets.json`. Default true. */\r\n manifest?: boolean;\r\n /** Working directory used to resolve roots. Default process.cwd(). */\r\n cwd?: string;\r\n}\r\n\r\nexport interface AssetEntry {\r\n /** Original string found in the module. */\r\n reference: string;\r\n /** Resolved absolute source path. */\r\n source: string;\r\n /** Relative destination inside the bundle. */\r\n destination: string;\r\n kind: 'worker' | 'wasm' | 'data';\r\n}\r\n\r\nexport interface AssetManifest {\r\n generatedBy: 'mini-three-adapter';\r\n outputDir: string;\r\n entries: AssetEntry[];\r\n /** Paste into game.json (adjust subpackage names to your project). */\r\n gameJsonSuggestion: Record<string, unknown>;\r\n /** Decoder paths to feed to loaders at runtime. */\r\n decoderPaths: Record<string, string>;\r\n}\r\n\r\nconst ASSET_PATTERN = /(['\"`])([^'\"`\\n]*\\.(?:wasm|wasm\\.br|bin|js))\\1/g;\r\nconst DECODER_KEYWORDS = [\r\n 'draco', 'basis', 'ktx2', 'rhino3dm', 'zstd', 'meshopt', 'ammo',\r\n 'worker', 'decoder', 'transcoder', 'lottie', 'sdf',\r\n];\r\n\r\nexport function collectAssetReferences(code: string): string[] {\r\n const found = new Set<string>();\r\n let match: RegExpExecArray | null;\r\n ASSET_PATTERN.lastIndex = 0;\r\n while ((match = ASSET_PATTERN.exec(code)) !== null) {\r\n const value = match[2] ?? '';\r\n const lower = value.toLowerCase();\r\n if (DECODER_KEYWORDS.some((keyword) => lower.includes(keyword))) found.add(value);\r\n }\r\n return Array.from(found);\r\n}\r\n\r\nasync function indexFiles(root: string, maxDepth = 5): Promise<Map<string, string>> {\r\n const index = new Map<string, string>();\r\n const walk = async (dir: string, depth: number): Promise<void> => {\r\n if (depth > maxDepth) return;\r\n let entries;\r\n try { entries = await fs.readdir(dir, { withFileTypes: true }); }\r\n catch { return; }\r\n for (const entry of entries) {\r\n const full = path.join(dir, entry.name);\r\n if (entry.isDirectory()) await walk(full, depth + 1);\r\n else if (entry.isFile() && !index.has(entry.name)) index.set(entry.name, full);\r\n }\r\n };\r\n await walk(root, 0);\r\n return index;\r\n}\r\n\r\nfunction classify(name: string): AssetEntry['kind'] {\r\n if (name.endsWith('.wasm') || name.endsWith('.wasm.br')) return 'wasm';\r\n if (name.endsWith('.js')) return 'worker';\r\n return 'data';\r\n}\r\n\r\nexport function defaultRoots(cwd: string): string[] {\r\n return [\r\n path.join(cwd, 'node_modules/three/examples/jsm/libs'),\r\n path.join(cwd, 'node_modules/three/examples/jsm'),\r\n path.join(cwd, 'node_modules/three-stdlib'),\r\n path.join(cwd, 'public'),\r\n path.join(cwd, 'static'),\r\n ];\r\n}\r\n\r\nexport interface CollectResult {\r\n manifest: AssetManifest;\r\n /** Files to write: destination (relative) -> absolute source. */\r\n files: Map<string, string>;\r\n missing: string[];\r\n}\r\n\r\n/** Resolve references against known roots without copying anything. */\r\nexport async function collectAssets(references: string[], options: AssetOptions = {}): Promise<CollectResult> {\r\n const cwd = options.cwd ?? process.cwd();\r\n const outputDir = (options.outputDir ?? 'assets/three').replace(/\\\\/g, '/').replace(/\\/$/, '');\r\n const roots = [...defaultRoots(cwd), ...(options.roots ?? [])];\r\n const indexes = await Promise.all(roots.map((root) => indexFiles(root)));\r\n const find = (name: string): string | undefined => {\r\n for (const index of indexes) {\r\n const hit = index.get(name);\r\n if (hit) return hit;\r\n }\r\n return undefined;\r\n };\r\n\r\n const entries: AssetEntry[] = [];\r\n const files = new Map<string, string>();\r\n const missing: string[] = [];\r\n\r\n for (const reference of references) {\r\n const base = path.posix.basename(reference.split('?')[0] ?? reference);\r\n const source = find(base);\r\n if (!source) { missing.push(reference); continue; }\r\n const entry: AssetEntry = {\r\n reference,\r\n source,\r\n destination: `${outputDir}/${base}`,\r\n kind: classify(base),\r\n };\r\n entries.push(entry);\r\n files.set(entry.destination, source);\r\n if (options.brotli !== false && entry.kind === 'wasm') {\r\n const br = find(`${base}.br`);\r\n if (br) {\r\n entries.push({ reference: `${reference}.br`, source: br, destination: `${outputDir}/${base}.br`, kind: 'wasm' });\r\n files.set(`${outputDir}/${base}.br`, br);\r\n }\r\n }\r\n }\r\n\r\n const decoderPaths: Record<string, string> = {};\r\n for (const entry of entries) {\r\n const name = path.posix.basename(entry.destination).toLowerCase();\r\n for (const key of ['draco', 'ktx2', 'basis', 'meshopt', 'rhino3dm', 'zstd', 'ammo']) {\r\n if (name.includes(key)) decoderPaths[key] = `${outputDir}/`;\r\n }\r\n }\r\n\r\n const manifest: AssetManifest = {\r\n generatedBy: 'mini-three-adapter',\r\n outputDir,\r\n entries,\r\n gameJsonSuggestion: {\r\n workers: { path: `${outputDir}`, isSubpackage: true },\r\n subpackages: [{ name: 'three-assets', root: `${outputDir}/` }],\r\n },\r\n decoderPaths,\r\n };\r\n return { manifest, files, missing };\r\n}\r\n\r\n/** Copy resolved files into `outDir`. */\r\nexport async function copyAssets(files: Map<string, string>, outDir: string): Promise<number> {\r\n let written = 0;\r\n for (const [destination, source] of files) {\r\n const target = path.join(outDir, destination);\r\n await fs.mkdir(path.dirname(target), { recursive: true });\r\n await fs.copyFile(source, target);\r\n written++;\r\n }\r\n return written;\r\n}\r\n","/** Vite entry: `import miniThree from 'mini-three-adapter/vite'`. */\r\nimport { miniThreePlugin, type MiniThreePlugin, type MiniThreePluginOptions } from './plugin-core';\r\n\r\nexport interface ViteMiniThreePlugin extends MiniThreePlugin {\r\n config(): Record<string, unknown>;\r\n}\r\n\r\n/**\r\n * Vite plugin. `optimizeDeps.exclude` keeps three's ESM sources intact so the\r\n * AST rewrite sees the original module graph instead of a pre-bundled blob.\r\n */\r\nexport function miniThree(options: MiniThreePluginOptions = {}): ViteMiniThreePlugin {\r\n const core = miniThreePlugin(options);\r\n return {\r\n ...core,\r\n config() {\r\n return {\r\n optimizeDeps: {\r\n exclude: ['three', 'three-stdlib', 'three/examples/jsm'],\r\n },\r\n build: {\r\n commonjsOptions: { transformMixedEsModules: true },\r\n rollupOptions: {\r\n output: {\r\n manualChunks: undefined,\r\n },\r\n },\r\n },\r\n };\r\n },\r\n };\r\n}\r\n\r\nexport default miniThree;\r\nexport { miniThreePlugin } from './plugin-core';\r\nexport type { MiniThreePluginOptions, BuildReport } from './plugin-core';\r\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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AAM,KAAK,SAAS;AAAA,QACrC,gBAAgB,CAAC,GAAG,OAAO,cAAc;AAAA,QACzC,eAAe,CAAC,GAAG,OAAO,aAAa;AAAA,MACzC;AAAA,IACF;AAAA,EACF;AACF;;;AGzMO,SAAS,UAAU,UAAkC,CAAC,GAAwB;AACnF,QAAM,OAAO,gBAAgB,OAAO;AACpC,SAAO;AAAA,IACL,GAAG;AAAA,IACH,SAAS;AACP,aAAO;AAAA,QACL,cAAc;AAAA,UACZ,SAAS,CAAC,SAAS,gBAAgB,oBAAoB;AAAA,QACzD;AAAA,QACA,OAAO;AAAA,UACL,iBAAiB,EAAE,yBAAyB,KAAK;AAAA,UACjD,eAAe;AAAA,YACb,QAAQ;AAAA,cACN,cAAc;AAAA,YAChB;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AAEA,IAAO,eAAQ;","names":["fs","path","fs"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createImageFactory } from './chunk-
|
|
1
|
+
import { createImageFactory } from './chunk-TPMMZFHW.js';
|
|
2
2
|
|
|
3
3
|
// src/platforms/wechat-common.ts
|
|
4
4
|
function createWechatImageFactory(wx, diagnostics) {
|
|
@@ -152,5 +152,5 @@ function resolveWx(injected) {
|
|
|
152
152
|
}
|
|
153
153
|
|
|
154
154
|
export { createNow, createOffscreenCanvasRaw, createRafPair, createWechatImageFactory, probeContext, rectFromSelectorResult, rectFromWindowInfo, resolveWx, watchWxTouch, watchWxVisibility };
|
|
155
|
-
//# sourceMappingURL=chunk-
|
|
156
|
-
//# sourceMappingURL=chunk-
|
|
155
|
+
//# sourceMappingURL=chunk-DQH3YRGN.js.map
|
|
156
|
+
//# sourceMappingURL=chunk-DQH3YRGN.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/platforms/wechat-common.ts","../src/platforms/wx-types.ts"],"names":["_a","_b","raw"],"mappings":";;;AAMO,SAAS,wBAAA,CAAyB,IA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KAAA,KAAP,IAAA,GAAA,EAAA,GAAgB,IAAA,GAAO,KAAA;AAAA,IAC9B,MAAA,EAAA,CAAQ,EAAA,GAAA,MAAA,CAAO,MAAA,KAAP,IAAA,GAAA,EAAA,GAAiB,GAAA,GAAM;AAAA,GACjC;AACF;;;ACvDO,SAAS,UAAU,QAAA,EAA2B;AACnD,EAAA,IAAI,UAAU,OAAO,QAAA;AACrB,EAAA,MAAM,IAAA,GAAO,UAAA;AACb,EAAA,MAAM,KAAK,IAAA,CAAK,EAAA;AAChB,EAAA,IAAI,CAAC,EAAA,EAAI;AACP,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KACF;AAAA,EACF;AACA,EAAA,OAAO,EAAA;AACT","file":"chunk-DQH3YRGN.js","sourcesContent":["/** Shared WeChat plumbing used by both mini game and mini program bindings. */\r\nimport type { ContextType, Disposer, Rect, TouchLikeEvent } from '../types';\r\nimport type { WxCanvas, WxLike, WxTouchEvent } from './wx-types';\r\nimport { createImageFactory, type ImageFactory } from '../core/image';\r\nimport type { Diagnostics } from '../core/diagnostics';\r\n\r\nexport function createWechatImageFactory(wx: WxLike, diagnostics?: Diagnostics): ImageFactory {\r\n return createImageFactory(wx, diagnostics);\r\n}\r\n\r\n/** rAF comes from the global in mini games, from the canvas node in mini programs. */\r\nexport function createRafPair(\r\n wx: WxLike,\r\n canvas?: WxCanvas,\r\n): { request(cb: (time: number) => void): number; cancel(id: number): void } {\r\n const host = globalThis as unknown as {\r\n requestAnimationFrame?: (cb: (time: number) => void) => number;\r\n cancelAnimationFrame?: (id: number) => void;\r\n };\r\n const canvasRaf = canvas?.requestAnimationFrame?.bind(canvas);\r\n const canvasCaf = canvas?.cancelAnimationFrame?.bind(canvas);\r\n const request = canvasRaf ?? host.requestAnimationFrame?.bind(host) ??\r\n ((cb: (time: number) => void) => setTimeout(() => cb(Date.now()), 16) as unknown as number);\r\n const cancel = canvasCaf ?? host.cancelAnimationFrame?.bind(host) ??\r\n ((id: number) => clearTimeout(id as unknown as ReturnType<typeof setTimeout>));\r\n void wx;\r\n return { request, cancel };\r\n}\r\n\r\nexport function createNow(wx: WxLike): () => number {\r\n const perf = wx.getPerformance?.();\r\n if (perf && typeof perf.now === 'function') return () => perf.now();\r\n const host = globalThis as unknown as { performance?: { now(): number } };\r\n const hostPerf = host.performance;\r\n if (hostPerf && typeof hostPerf.now === 'function') return () => hostPerf.now();\r\n const start = Date.now();\r\n return () => Date.now() - start;\r\n}\r\n\r\n/** Subscribe to mini game touch events. Mini programs use WXML bindings instead. */\r\nexport function watchWxTouch(wx: WxLike, handler: (event: TouchLikeEvent) => void): Disposer {\r\n const methods = ['onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel'] as const;\r\n const offs = ['offTouchStart', 'offTouchMove', 'offTouchEnd', 'offTouchCancel'] as const;\r\n const attached: Array<[string, (event: WxTouchEvent) => void]> = [];\r\n methods.forEach((name, index) => {\r\n const attach = wx[name];\r\n if (typeof attach !== 'function') return;\r\n const listener = (event: WxTouchEvent): void => handler(event as TouchLikeEvent);\r\n attach.call(wx, listener);\r\n attached.push([offs[index] as string, listener]);\r\n });\r\n return () => {\r\n for (const [off, listener] of attached) {\r\n const fn = (wx as Record<string, unknown>)[off];\r\n if (typeof fn === 'function') (fn as (l: unknown) => void).call(wx, listener);\r\n }\r\n };\r\n}\r\n\r\nexport function watchWxVisibility(wx: WxLike, handler: (visible: boolean) => void): Disposer {\r\n const onShow = (): void => handler(true);\r\n const onHide = (): void => handler(false);\r\n wx.onShow?.(onShow);\r\n wx.onHide?.(onHide);\r\n return () => {\r\n wx.offShow?.(onShow);\r\n wx.offHide?.(onHide);\r\n };\r\n}\r\n\r\nexport interface ProbeContextOptions {\r\n /**\r\n * Allow falling back to a second `wx.createCanvas()` when the offscreen probe\r\n * answers \"no\". Only callers that already resolved the on-screen canvas may\r\n * opt in, and only when `createOffscreenCanvas` exists at all (see ADR-0007\r\n * and ADR-0008).\r\n */\r\n allowCanvasFallback?: boolean;\r\n /**\r\n * Every object that could be the on-screen canvas on this device: the canvas\r\n * in use, the one the host seeded through `GameGlobal.screencanvas`, and\r\n * `globalThis.canvas` (weapp-adapter style).\r\n *\r\n * WeChat returns the *on-screen* canvas from the first `createCanvas()` call.\r\n * A host that seeded the canvas never consumes that first call, so the\r\n * fallback below can receive the screen canvas back — or a *different*\r\n * pre-seeded canvas when the host also passed `canvas` explicitly. Probing\r\n * any of them creates a context and then destroys it with\r\n * `WEBGL_lose_context`: a black screen with no error. Identity is the only\r\n * reliable judgement, so the whole candidate set is passed in.\r\n */\r\n reservedCanvases?: readonly (WxCanvas | null | undefined)[];\r\n}\r\n\r\n/** Identity check against every known on-screen canvas candidate. */\r\nfunction isReserved(raw: WxCanvas, reserved: readonly (WxCanvas | null | undefined)[]): boolean {\r\n for (const candidate of reserved) {\r\n if (candidate != null && candidate === raw) return true;\r\n }\r\n return false;\r\n}\r\n\r\n/** Try one canvas; returns `false` when the context is simply unavailable. */\r\nfunction probeRawContext(raw: WxCanvas, type: ContextType): boolean {\r\n const ctx = raw.getContext(type);\r\n if (!ctx) return false;\r\n // Release GPU resources as soon as possible on constrained devices.\r\n const lose = (ctx as { getExtension?: (name: string) => { loseContext?: () => void } | null }).getExtension;\r\n lose?.call(ctx, 'WEBGL_lose_context')?.loseContext?.();\r\n return true;\r\n}\r\n\r\n/**\r\n * WebGL2 / WebGL1 capability probe.\r\n *\r\n * The offscreen canvas is preferred because it has no side effects on the\r\n * on-screen canvas. But offscreen support is NOT the same capability as\r\n * on-screen support: a base library can render WebGL2 on the screen canvas while\r\n * `createOffscreenCanvas` is missing or cannot create a WebGL2 context. So when\r\n * the offscreen answer is negative and the caller allows it, we ask the real\r\n * canvas type as well.\r\n *\r\n * Returns `undefined` when the host cannot answer — callers must treat that as\r\n * \"unknown\", never as \"unsupported\".\r\n */\r\nexport function probeContext(\r\n wx: WxLike,\r\n type: ContextType,\r\n options: ProbeContextOptions = {},\r\n): boolean | undefined {\r\n let offscreen: boolean | undefined;\r\n if (typeof wx.createOffscreenCanvas === 'function') {\r\n try {\r\n offscreen = probeRawContext(wx.createOffscreenCanvas({ width: 1, height: 1, type }), type);\r\n } catch {\r\n // Some base libraries expose the API but throw for webgl2; keep probing.\r\n offscreen = undefined;\r\n }\r\n }\r\n if (offscreen === true) return true;\r\n if (!options.allowCanvasFallback) return offscreen;\r\n if (typeof wx.createOffscreenCanvas !== 'function') {\r\n // No offscreen API at all: nothing tells us whether the first\r\n // `createCanvas()` was already consumed, so the fallback turns into a coin\r\n // flip whose losing side is a destroyed screen context. Report \"unknown\"\r\n // and let the caller infer from the base library version instead.\r\n return undefined;\r\n }\r\n if (typeof wx.createCanvas !== 'function') return undefined;\r\n try {\r\n const raw = wx.createCanvas();\r\n // Identity check, not a heuristic: the screen canvas must never be probed,\r\n // because probing creates a context and then loses it.\r\n if (isReserved(raw, options.reservedCanvases ?? [])) return undefined;\r\n return probeRawContext(raw, type);\r\n } catch {\r\n return undefined;\r\n }\r\n}\r\n\r\nexport function createOffscreenCanvasRaw(\r\n wx: WxLike,\r\n width: number,\r\n height: number,\r\n type: ContextType,\r\n diagnostics?: Diagnostics,\r\n): WxCanvas {\r\n if (typeof wx.createOffscreenCanvas === 'function') {\r\n try {\r\n const raw = wx.createOffscreenCanvas({ width, height, type });\r\n raw.width = width;\r\n raw.height = height;\r\n return raw;\r\n } catch (error) {\r\n diagnostics?.warn(`createOffscreenCanvas(${type}) failed, falling back to 2d`, error);\r\n }\r\n }\r\n // Last resort for old base libraries: createCanvas() after the first call is\r\n // guaranteed to be off-screen, but it still counts against the canvas budget.\r\n if (typeof wx.createCanvas !== 'function') {\r\n throw new Error('[mini-three-adapter] no canvas creation API available');\r\n }\r\n const raw = wx.createCanvas();\r\n raw.width = width;\r\n raw.height = height;\r\n return raw;\r\n}\r\n\r\nexport function rectFromWindowInfo(wx: WxLike): Rect {\r\n const info = wx.getWindowInfo?.() ?? wx.getSystemInfoSync?.() ??\r\n { windowWidth: 0, windowHeight: 0, pixelRatio: 1 };\r\n return {\r\n left: 0,\r\n top: 0,\r\n width: info.windowWidth,\r\n height: info.windowHeight,\r\n right: info.windowWidth,\r\n bottom: info.windowHeight,\r\n };\r\n}\r\n\r\nexport function rectFromSelectorResult(result: {\r\n width?: number; height?: number; top?: number; left?: number; right?: number; bottom?: number;\r\n}): Rect {\r\n const width = result.width ?? 0;\r\n const height = result.height ?? 0;\r\n const left = result.left ?? 0;\r\n const top = result.top ?? 0;\r\n return {\r\n width, height, left, top,\r\n right: result.right ?? left + width,\r\n bottom: result.bottom ?? top + height,\r\n };\r\n}\r\n","/**\r\n * Hand-written, minimal structural types for the WeChat runtime.\r\n *\r\n * Why not `minigame-api-typings`? Because consuming the official typings forces\r\n * a global `wx` declaration onto every consumer (including browser builds and\r\n * Node tests) and couples us to a specific version. Structural interfaces let\r\n * the adapter work with a real `wx`, a mock in tests, or a future platform.\r\n */\r\n\r\nexport interface WxCanvas {\r\n width: number;\r\n height: number;\r\n getContext(type: string, attributes?: Record<string, unknown>): unknown;\r\n toDataURL?(type?: string, quality?: number): string;\r\n createImage?(): WxImage;\r\n requestAnimationFrame?(callback: (time: number) => void): number;\r\n cancelAnimationFrame?(id: number): void;\r\n [key: string]: unknown;\r\n}\r\n\r\nexport interface WxImage {\r\n width: number;\r\n height: number;\r\n src: string;\r\n onload?: ((event?: unknown) => void) | null;\r\n onerror?: ((error?: unknown) => void) | null;\r\n complete?: boolean;\r\n [key: string]: unknown;\r\n}\r\n\r\nexport interface WxImageInfo {\r\n width: number;\r\n height: number;\r\n path?: string;\r\n type?: string;\r\n orientation?: string;\r\n}\r\n\r\nexport interface WxGetImageInfoOptions {\r\n src: string;\r\n success?: (info: WxImageInfo) => void;\r\n fail?: (error: { errMsg?: string; [key: string]: unknown }) => void;\r\n}\r\n\r\nexport interface WxRect {\r\n top: number;\r\n left: number;\r\n width: number;\r\n height: number;\r\n right: number;\r\n bottom: number;\r\n}\r\n\r\nexport interface WxWindowInfo {\r\n windowWidth: number;\r\n windowHeight: number;\r\n pixelRatio: number;\r\n screenWidth?: number;\r\n screenHeight?: number;\r\n safeArea?: WxRect;\r\n}\r\n\r\nexport interface WxTouchPoint {\r\n identifier?: number;\r\n clientX?: number;\r\n clientY?: number;\r\n pageX?: number;\r\n pageY?: number;\r\n x?: number;\r\n y?: number;\r\n force?: number;\r\n}\r\n\r\nexport interface WxTouchEvent {\r\n type: string;\r\n touches?: ArrayLike<WxTouchPoint>;\r\n changedTouches?: ArrayLike<WxTouchPoint>;\r\n timeStamp?: number;\r\n}\r\n\r\nexport interface WxRequestResult {\r\n statusCode: number;\r\n data: string | ArrayBuffer | Record<string, unknown>;\r\n header?: Record<string, string>;\r\n errMsg?: string;\r\n}\r\n\r\nexport interface WxRequestOptions {\r\n url: string;\r\n method?: string;\r\n data?: unknown;\r\n header?: Record<string, string>;\r\n responseType?: 'text' | 'arraybuffer';\r\n timeout?: number;\r\n success?: (result: WxRequestResult) => void;\r\n fail?: (error: { errMsg?: string; [key: string]: unknown }) => void;\r\n}\r\n\r\nexport interface WxSelectorQueryResult {\r\n node?: WxCanvas;\r\n width?: number;\r\n height?: number;\r\n top?: number;\r\n left?: number;\r\n right?: number;\r\n bottom?: number;\r\n}\r\n\r\nexport interface WxSelectorQuery {\r\n select(selector: string): WxSelectorQuery;\r\n fields(fields: Record<string, boolean>): WxSelectorQuery;\r\n exec(callback: (results: (WxSelectorQueryResult | null)[]) => void): void;\r\n}\r\n\r\n/** The subset of `wx` the adapter touches. All members are optional so the\r\n * same interface can describe a mini game, a mini program or a test mock. */\r\nexport interface WxLike {\r\n createCanvas?(): WxCanvas;\r\n createOffscreenCanvas?(options?: {\r\n width?: number;\r\n height?: number;\r\n type?: '2d' | 'webgl' | 'webgl2';\r\n }): WxCanvas;\r\n createImage?(): WxImage;\r\n createImageData?(width: number, height: number): unknown;\r\n /** Metadata-only decode: proves an asset is readable without loading it. */\r\n getImageInfo?(options: WxGetImageInfoOptions): void;\r\n getWindowInfo?(): WxWindowInfo;\r\n getSystemInfoSync?(): WxWindowInfo;\r\n onWindowResize?(listener: (res: { windowWidth: number; windowHeight: number }) => void): void;\r\n offWindowResize?(listener: (res: { windowWidth: number; windowHeight: number }) => void): void;\r\n\r\n onTouchStart?(listener: (event: WxTouchEvent) => void): void;\r\n onTouchMove?(listener: (event: WxTouchEvent) => void): void;\r\n onTouchEnd?(listener: (event: WxTouchEvent) => void): void;\r\n onTouchCancel?(listener: (event: WxTouchEvent) => void): void;\r\n offTouchStart?(listener: (event: WxTouchEvent) => void): void;\r\n offTouchMove?(listener: (event: WxTouchEvent) => void): void;\r\n offTouchEnd?(listener: (event: WxTouchEvent) => void): void;\r\n offTouchCancel?(listener: (event: WxTouchEvent) => void): void;\r\n\r\n onShow?(listener: () => void): void;\r\n onHide?(listener: () => void): void;\r\n offShow?(listener: () => void): void;\r\n offHide?(listener: () => void): void;\r\n\r\n request?(options: WxRequestOptions): { abort?(): void };\r\n createSelectorQuery?(): WxSelectorQuery;\r\n getPerformance?(): { now(): number };\r\n setPreferredFramesPerSecond?(fps: number): void;\r\n triggerGC?(): void;\r\n createWorker?(path: string, options?: unknown): unknown;\r\n env?: { USER_DATA_PATH?: string; [key: string]: unknown };\r\n getSystemInfo?(options: { success?: (info: WxWindowInfo & { SDKVersion?: string }) => void }): void;\r\n [key: string]: unknown;\r\n}\r\n\r\n/** Resolve `wx` from an explicit injection or from the host global. */\r\nexport function resolveWx(injected?: WxLike): WxLike {\r\n if (injected) return injected;\r\n const host = globalThis as unknown as Record<string, unknown>;\r\n const wx = host.wx as WxLike | undefined;\r\n if (!wx) {\r\n throw new Error(\r\n '[mini-three-adapter] `wx` is not available. Pass `{ wx }` in options when running outside WeChat (e.g. in Node tests).',\r\n );\r\n }\r\n return wx;\r\n}\r\n"]}
|
|
@@ -142,5 +142,5 @@ function installGlobals(scope, options = {}) {
|
|
|
142
142
|
}
|
|
143
143
|
|
|
144
144
|
export { clearEarlyScopeReads, createScope, getActiveScope, getEarlyScopeReads, hasActiveScope, installGlobals, setActiveScope };
|
|
145
|
-
//# sourceMappingURL=chunk-
|
|
146
|
-
//# sourceMappingURL=chunk-
|
|
145
|
+
//# sourceMappingURL=chunk-J34MD3IL.js.map
|
|
146
|
+
//# sourceMappingURL=chunk-J34MD3IL.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/scope.ts"],"names":[],"mappings":";AA4HA,IAAI,MAAA,GAAgC,IAAA;AAEpC,SAAS,eAAe,IAAA,EAAqB;AAC3C,EAAA,MAAM,IAAI,KAAA;AAAA,IACR,uCAAuC,IAAI,CAAA,yLAAA;AAAA,GAG7C;AACF;AAkBA,IAAM,wBAAA,uBAAoD,GAAA,CAAI;AAAA,EAC5D,UAAA;AAAA,EACA,WAAA;AAAA,EACA,QAAA;AAAA,EACA,UAAA;AAAA,EACA;AACF,CAAC,CAAA;AAED,IAAM,UAAA,uBAAiB,GAAA,EAAY;AAM5B,SAAS,kBAAA,GAAwC;AACtD,EAAA,OAAO,KAAA,CAAM,KAAK,UAAU,CAAA;AAC9B;AAGO,SAAS,oBAAA,GAA6B;AAC3C,EAAA,UAAA,CAAW,KAAA,EAAM;AACnB;AAQA,IAAM,aAA6B,IAAI,KAAA;AAAA,EACrC,EAAE,MAAA,EAAQ,IAAA,EAAM,IAAA,EAAM,IAAA,EAAM,YAAY,IAAA,EAAK;AAAA,EAC7C;AAAA,IACE,GAAA,CAAI,QAAQ,IAAA,EAAM;AAChB,MAAA,IAAI,SAAS,QAAA,IAAY,IAAA,KAAS,MAAA,IAAU,IAAA,KAAS,cAAc,OAAO,UAAA;AAC1E,MAAA,IAAI,IAAA,KAAS,MAAA,CAAO,WAAA,EAAa,OAAO,gBAAA;AACxC,MAAA,IAAI,OAAO,IAAA,KAAS,QAAA,IAAY,wBAAA,CAAyB,GAAA,CAAI,IAAI,CAAA,EAAG;AAClE,QAAA,UAAA,CAAW,IAAI,IAAI,CAAA;AACnB,QAAA,OAAO,MAAA;AAAA,MACT;AAGA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E9D,EAAA,KAAA,MAAW,OAAO,IAAA,EAAM;AACtB,IAAA,MAAM,QAAA,GAAW,MAAA,CAAO,wBAAA,CAAyB,MAAA,EAAQ,GAAG,CAAA;AAC5D,IAAA,IAAI,OAAA,CAAQ,gBAAgB,QAAA,EAAU;AACtC,IAAA,IAAI,EAAE,OAAO,KAAA,CAAA,EAAQ;AACrB,IAAA,KAAA,CAAM,GAAA,CAAI,KAAK,QAAQ,CAAA;AACvB,IAAA,MAAA,CAAO,cAAA,CAAe,QAAQ,GAAA,EAAK;AAAA,MACjC,GAAA,EAAK,MAAO,KAAA,CAAkC,GAAG,CAAA;AAAA,MACjD,YAAA,EAAc,IAAA;AAAA,MACd,UAAA,EAAY;AAAA,KACb,CAAA;AAAA,EACH;AAEA,EAAA,OAAO,MAAM;AACX,IAAA,KAAA,MAAW,CAAC,GAAA,EAAK,UAAU,CAAA,IAAK,KAAA,EAAO;AACrC,MAAA,IAAI,UAAA,EAAY,MAAA,CAAO,cAAA,CAAe,MAAA,EAAQ,KAAK,UAAU,CAAA;AAAA,WACxD,OAAO,OAAO,GAAG,CAAA;AAAA,IACxB;AAAA,EACF,CAAA;AACF","file":"chunk-J34MD3IL.js","sourcesContent":["/**\r\n * Scoped globals: the central design decision of mini-three-adapter.\r\n *\r\n * The original adapter style (and WeChat's official `weapp-adapter`) writes\r\n * `window`, `document`, `Image`, ... onto `globalThis`. That is convenient but\r\n * irreversible: it breaks H5 dual-target builds, makes two three.js versions\r\n * fight over the same canvas, and cannot be un-installed in tests.\r\n *\r\n * Here the shims live in one explicit `MiniThreeScope` object. Third-party\r\n * modules (three, three/addons, three-stdlib, ...) are rewritten at build time\r\n * by `mini-three-adapter/vite` so that their *free* references to browser\r\n * globals resolve through `getActiveScope()`. Application code is untouched.\r\n *\r\n * `installGlobals()` remains available as an explicit, reversible escape hatch\r\n * for libraries that cannot be transformed.\r\n */\r\nimport type {\r\n CanvasStyleLike,\r\n EventTargetLike,\r\n PatchedCanvas,\r\n Rect,\r\n} from './types';\r\n\r\nexport interface DocumentLike extends EventTargetLike {\r\n createElement(tagName: string): PatchedCanvas | unknown;\r\n createElementNS(namespaceURI: string | null, tagName: string): PatchedCanvas | unknown;\r\n body: ElementLike;\r\n documentElement: ElementLike;\r\n defaultView: MiniThreeScope | null;\r\n [key: string]: unknown;\r\n}\r\n\r\nexport interface ElementLike extends EventTargetLike {\r\n style: CanvasStyleLike;\r\n clientWidth: number;\r\n clientHeight: number;\r\n getBoundingClientRect(): Rect;\r\n setAttribute(name: string, value: unknown): void;\r\n removeAttribute(name: string): void;\r\n [key: string]: unknown;\r\n}\r\n\r\nexport interface NavigatorLike {\r\n userAgent: string;\r\n platform: string;\r\n hardwareConcurrency: number;\r\n [key: string]: unknown;\r\n}\r\n\r\n/**\r\n * The set of browser globals three.js (and its addons) may read. Members are\r\n * typed where they matter and `unknown` in the index signature so the build\r\n * plugin can add platform-specific extras without loosening the whole object.\r\n */\r\nexport interface MiniThreeScope extends EventTargetLike {\r\n readonly window: MiniThreeScope;\r\n readonly self: MiniThreeScope;\r\n readonly globalThis: MiniThreeScope;\r\n document: DocumentLike;\r\n navigator: NavigatorLike;\r\n screen: EventTargetLike & {\r\n width: number;\r\n height: number;\r\n availWidth: number;\r\n availHeight: number;\r\n colorDepth: number;\r\n pixelDepth: number;\r\n };\r\n innerWidth: number;\r\n innerHeight: number;\r\n outerWidth: number;\r\n outerHeight: number;\r\n devicePixelRatio: number;\r\n pageXOffset: number;\r\n pageYOffset: number;\r\n performance: { now(): number };\r\n requestAnimationFrame(callback: (time: number) => void): number;\r\n cancelAnimationFrame(id: number): void;\r\n getComputedStyle(element: unknown): CanvasStyleLike;\r\n matchMedia(query: string): { matches: boolean; media: string; addListener(l: unknown): void; removeListener(l: unknown): void };\r\n atob(data: string): string;\r\n btoa(data: string): string;\r\n\r\n Event: unknown;\r\n EventTarget: unknown;\r\n CustomEvent: unknown;\r\n PointerEvent: unknown;\r\n MouseEvent: unknown;\r\n TouchEvent: unknown;\r\n MessageEvent: unknown;\r\n ProgressEvent: unknown;\r\n KeyboardEvent: unknown;\r\n DOMException: unknown;\r\n\r\n HTMLElement: unknown;\r\n HTMLCanvasElement: unknown;\r\n HTMLImageElement: unknown;\r\n HTMLVideoElement: unknown;\r\n OffscreenCanvas: unknown;\r\n Image: unknown;\r\n ImageData: unknown;\r\n DOMRect: unknown;\r\n WebGLRenderingContext: unknown;\r\n WebGL2RenderingContext: unknown;\r\n AudioContext: unknown;\r\n\r\n Blob: unknown;\r\n URL: unknown;\r\n FileReader: unknown;\r\n TextDecoder: unknown;\r\n TextEncoder: unknown;\r\n AbortController: unknown;\r\n AbortSignal: unknown;\r\n fetch: unknown;\r\n XMLHttpRequest: unknown;\r\n WebSocket: unknown;\r\n createImageBitmap: unknown;\r\n Worker: unknown;\r\n WebAssembly: unknown;\r\n ResizeObserver: unknown;\r\n\r\n [key: string]: unknown;\r\n}\r\n\r\nlet active: MiniThreeScope | null = null;\r\n\r\nfunction notInitialized(name: string): never {\r\n throw new Error(\r\n `[mini-three-adapter] Scoped global \"${name}\" was read before a runtime was created. ` +\r\n `Import 'mini-three-adapter/wechat-game' and await createWeChatGameRuntime() before importing three.js, ` +\r\n `or call installGlobals(scope) explicitly.`,\r\n );\r\n}\r\n\r\n/**\r\n * Globals that describe *whether a DOM exists* rather than a concrete API.\r\n *\r\n * Feature detection reads them with `typeof` or truthiness — `typeof document`,\r\n * `typeof window.document`, `if (navigator.userAgent)`. `typeof x.y` is NOT a\r\n * safe operator in JavaScript: it throws as soon as the getter throws, and the\r\n * build plugin can only guard a *direct* `typeof X` operand, not a member\r\n * chain. Throwing here therefore turns \"is this a browser?\" into a crash inside\r\n * the adapter, which is the one place a library cannot afford it.\r\n *\r\n * So before a runtime exists these keys read as `undefined` — exactly what a\r\n * non-DOM host looks like — and the early read is recorded so `createRuntime()`\r\n * can still point at the real cause. Every other key keeps throwing: touching\r\n * `HTMLCanvasElement` or `TextDecoder` is a real use, not a probe, and a silent\r\n * `undefined` would surface three frames later in an unrelated place.\r\n */\r\nconst UNDEFINED_BEFORE_RUNTIME: ReadonlySet<string> = new Set([\r\n 'document',\r\n 'navigator',\r\n 'screen',\r\n 'location',\r\n 'history',\r\n]);\r\n\r\nconst earlyReads = new Set<string>();\r\n\r\n/**\r\n * Names read from the placeholder scope before any runtime existed. Reported\r\n * once by `createRuntime()`: it means some module was evaluated too early.\r\n */\r\nexport function getEarlyScopeReads(): readonly string[] {\r\n return Array.from(earlyReads);\r\n}\r\n\r\n/** Clear the recorded early reads (called by `createRuntime()` after reporting). */\r\nexport function clearEarlyScopeReads(): void {\r\n earlyReads.clear();\r\n}\r\n\r\n/**\r\n * A stable placeholder returned when no runtime exists yet. `typeof scope.window`\r\n * still yields \"object\" (which is what three.js feature-detection expects), the\r\n * environment globals read as `undefined`, and any other access throws an\r\n * actionable error instead of silently returning `undefined` three frames later.\r\n */\r\nconst emptyScope: MiniThreeScope = new Proxy(\r\n { window: null, self: null, globalThis: null } as unknown as MiniThreeScope,\r\n {\r\n get(target, prop) {\r\n if (prop === 'window' || prop === 'self' || prop === 'globalThis') return emptyScope;\r\n if (prop === Symbol.toStringTag) return 'MiniThreeScope';\r\n if (typeof prop === 'string' && UNDEFINED_BEFORE_RUNTIME.has(prop)) {\r\n earlyReads.add(prop);\r\n return undefined;\r\n }\r\n // Protocol hooks (Symbol.iterator, util.inspect.custom, ...) must not\r\n // explode while someone is merely logging the placeholder.\r\n if (typeof prop === 'symbol') return undefined;\r\n return notInitialized(prop);\r\n },\r\n has() {\r\n return false;\r\n },\r\n },\r\n);\r\n\r\n/** Returns the currently installed scope (or the throwing placeholder). */\r\nexport function getActiveScope(): MiniThreeScope {\r\n return active ?? emptyScope;\r\n}\r\n\r\n/** Install / replace the active scope. Returns a disposer. */\r\nexport function setActiveScope(scope: MiniThreeScope | null): () => void {\r\n const previous = active;\r\n active = scope;\r\n return () => {\r\n if (active === scope) active = previous;\r\n };\r\n}\r\n\r\nexport function hasActiveScope(): boolean {\r\n return active !== null;\r\n}\r\n\r\n/**\r\n * Build a scope with a set of overrides. `window`, `self` and `globalThis`\r\n * are wired to the scope itself so that `window.window === window`.\r\n */\r\nexport function createScope(overrides: Partial<MiniThreeScope> = {}): MiniThreeScope {\r\n const scope = {\r\n ...overrides,\r\n } as MiniThreeScope;\r\n Object.defineProperties(scope, {\r\n window: { get: () => scope, enumerable: true, configurable: true },\r\n self: { get: () => scope, enumerable: true, configurable: true },\r\n globalThis: { get: () => scope, enumerable: true, configurable: true },\r\n });\r\n return scope;\r\n}\r\n\r\n/** Keys written by `installGlobals`. Kept explicit so restoration is exact. */\r\nconst GLOBAL_KEYS = [\r\n 'window', 'self', 'document', 'navigator', 'screen',\r\n 'innerWidth', 'innerHeight', 'outerWidth', 'outerHeight', 'devicePixelRatio',\r\n 'pageXOffset', 'pageYOffset', 'performance',\r\n 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'matchMedia',\r\n 'atob', 'btoa',\r\n 'Event', 'EventTarget', 'CustomEvent', 'PointerEvent', 'MouseEvent', 'TouchEvent',\r\n 'MessageEvent', 'ProgressEvent', 'KeyboardEvent', 'DOMException',\r\n 'HTMLElement', 'HTMLCanvasElement', 'HTMLImageElement', 'HTMLVideoElement',\r\n 'OffscreenCanvas', 'Image', 'ImageData', 'DOMRect',\r\n 'WebGLRenderingContext', 'WebGL2RenderingContext', 'AudioContext',\r\n 'Blob', 'URL', 'FileReader', 'TextDecoder', 'TextEncoder',\r\n 'AbortController', 'AbortSignal', 'fetch', 'XMLHttpRequest', 'WebSocket',\r\n 'createImageBitmap', 'Worker', 'WebAssembly', 'ResizeObserver',\r\n] as const;\r\n\r\nexport interface InstallGlobalsOptions {\r\n /** Defaults to `globalThis`. */\r\n target?: Record<string, unknown>;\r\n /** Skip keys that already exist (useful in a browser / H5 build). */\r\n skipExisting?: boolean;\r\n /** Additional keys to copy from the scope. */\r\n extraKeys?: string[];\r\n}\r\n\r\n/**\r\n * Explicit opt-in global pollution for libraries that cannot be transformed.\r\n * Returns a disposer that restores every overwritten descriptor exactly.\r\n *\r\n * This is intentionally NOT called automatically: the default path is scoped.\r\n */\r\nexport function installGlobals(\r\n scope: MiniThreeScope,\r\n options: InstallGlobalsOptions = {},\r\n): () => void {\r\n const target = options.target ?? (globalThis as unknown as Record<string, unknown>);\r\n const keys: string[] = [...GLOBAL_KEYS, ...(options.extraKeys ?? [])];\r\n const saved = new Map<string, PropertyDescriptor | undefined>();\r\n\r\n for (const key of keys) {\r\n const existing = Object.getOwnPropertyDescriptor(target, key);\r\n if (options.skipExisting && existing) continue;\r\n if (!(key in scope)) continue;\r\n saved.set(key, existing);\r\n Object.defineProperty(target, key, {\r\n get: () => (scope as Record<string, unknown>)[key],\r\n configurable: true,\r\n enumerable: true,\r\n });\r\n }\r\n\r\n return () => {\r\n for (const [key, descriptor] of saved) {\r\n if (descriptor) Object.defineProperty(target, key, descriptor);\r\n else delete target[key];\r\n }\r\n };\r\n}\r\n"]}
|
|
@@ -720,5 +720,5 @@ function createXMLHttpRequestFactory(wx) {
|
|
|
720
720
|
}
|
|
721
721
|
|
|
722
722
|
export { MiniAbortController, MiniAbortSignal, MiniBlob, MiniCustomEvent, MiniDOMException, MiniEvent, MiniEventTarget, MiniMessageEvent, MiniMouseEvent, MiniPointerEvent, MiniProgressEvent, MiniTextDecoder, MiniTextEncoder, MiniURL, MiniURLSearchParams, MiniXMLHttpRequest, OBJECT_URL_PREFIX, atob, base64ToBytes, btoa, bytesToBase64, createFetch, createXMLHttpRequestFactory, patchEventTarget, resolveUrl };
|
|
723
|
-
//# sourceMappingURL=chunk-
|
|
724
|
-
//# sourceMappingURL=chunk-
|
|
723
|
+
//# sourceMappingURL=chunk-LAVHSWBU.js.map
|
|
724
|
+
//# sourceMappingURL=chunk-LAVHSWBU.js.map
|