mini-three-adapter 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/AGENTS.md +85 -85
  2. package/README.md +159 -159
  3. package/dist/build/rollup.js.map +1 -1
  4. package/dist/build/vite.js.map +1 -1
  5. package/dist/{chunk-34RWHAW4.js → chunk-35XVAVDB.js} +23 -5
  6. package/dist/chunk-35XVAVDB.js.map +1 -0
  7. package/dist/{chunk-52IMRKOX.js → chunk-F7CSLEUI.js} +3 -3
  8. package/dist/{chunk-52IMRKOX.js.map → chunk-F7CSLEUI.js.map} +1 -1
  9. package/dist/{chunk-WZ2HKYC5.js → chunk-LE4FRYNG.js} +4 -4
  10. package/dist/{chunk-WZ2HKYC5.js.map → chunk-LE4FRYNG.js.map} +1 -1
  11. package/dist/{chunk-OL7NVZZJ.js → chunk-VA7SZFLN.js} +21 -12
  12. package/dist/chunk-VA7SZFLN.js.map +1 -0
  13. package/dist/{chunk-3QUEDYTT.js → chunk-ZB3AYNOS.js} +19 -11
  14. package/dist/chunk-ZB3AYNOS.js.map +1 -0
  15. package/dist/{chunk-J7VBWZRR.js → chunk-ZFJLEEF4.js} +188 -45
  16. package/dist/chunk-ZFJLEEF4.js.map +1 -0
  17. package/dist/core/index.d.ts +3 -3
  18. package/dist/core/index.js +2 -2
  19. package/dist/index.d.ts +3 -3
  20. package/dist/index.js +6 -6
  21. package/dist/platforms/browser.d.ts +2 -2
  22. package/dist/platforms/browser.js +3 -3
  23. package/dist/platforms/wechat-game.d.ts +2 -2
  24. package/dist/platforms/wechat-game.js +4 -4
  25. package/dist/platforms/wechat-miniprogram.d.ts +2 -2
  26. package/dist/platforms/wechat-miniprogram.js +4 -4
  27. package/dist/polyfills/index.d.ts +1 -1
  28. package/dist/{runtime-DnEkKZjo.d.ts → runtime-BrHExTjl.d.ts} +1 -1
  29. package/dist/scope.d.ts +8 -1
  30. package/dist/scope.js +1 -1
  31. package/dist/{wx-types-NMNyrsWO.d.ts → wx-types-BZTQ2jWG.d.ts} +17 -0
  32. package/docs/02-architecture.md +4 -4
  33. package/docs/03-module-map.md +99 -99
  34. package/docs/04-api-reference.md +304 -294
  35. package/docs/05-build-plugin.md +4 -2
  36. package/docs/06-platform-notes.md +44 -6
  37. package/docs/07-integration-guide.md +2 -2
  38. package/docs/09-testing-and-release.md +210 -209
  39. package/docs/10-ai-playbook.md +2 -1
  40. package/docs/11-compat-matrix.md +100 -96
  41. package/docs/adr/0007-capability-probe-fallback.md +8 -4
  42. package/docs/adr/0008-probe-fallback-boundary.md +56 -0
  43. package/docs/adr/0009-placeholder-scope-environment-globals.md +69 -0
  44. package/docs/adr/README.md +3 -1
  45. package/llms.txt +5 -2
  46. package/package.json +1 -1
  47. package/dist/chunk-34RWHAW4.js.map +0 -1
  48. package/dist/chunk-3QUEDYTT.js.map +0 -1
  49. package/dist/chunk-J7VBWZRR.js.map +0 -1
  50. package/dist/chunk-OL7NVZZJ.js.map +0 -1
@@ -1,294 +1,304 @@
1
- # 04 · API 参考
2
-
3
- > 版本:0.1.0。所有签名以 `src/**` 与 `npm run build` 生成的 `dist/*.d.ts` 为准。
4
- > 子路径导入可最大化 tree-shaking;`mini-three-adapter` 是汇总入口。
5
-
6
- ## 4.1 子路径
7
-
8
- | 子路径 | 内容 |
9
- | --- | --- |
10
- | `mini-three-adapter` | 全部公开 API |
11
- | `mini-three-adapter/core` | 平台无关运行时 |
12
- | `mini-three-adapter/scope` | `getActiveScope()` 等(**构建插件注入的 import 目标**) |
13
- | `mini-three-adapter/wechat-game` | 小游戏入口 |
14
- | `mini-three-adapter/wechat-miniprogram` | 小程序入口 |
15
- | `mini-three-adapter/browser` | 浏览器 / H5 / Node 测试 |
16
- | `mini-three-adapter/polyfills` | 独立 polyfill |
17
- | `mini-three-adapter/vite` | Vite 插件 |
18
- | `mini-three-adapter/rollup` | Rollup 插件 + 高级 API |
19
- | `mini-three-adapter/plugin` | `vite` 的别名 |
20
- | `mini-three-adapter/package.json` | 读取包元信息(`version`、`exports`) |
21
-
22
- ---
23
-
24
- ## 4.2 生命周期
25
-
26
- ### `createRuntime(platform, options?) => Promise<MiniThreeRuntime>`
27
-
28
- 平台无关的总装配入口。通常不直接调用,而用下面的平台快捷函数。
29
-
30
- ```ts
31
- function createRuntime(
32
- platform: PlatformBinding | PlatformFactory,
33
- options?: RuntimeOptions,
34
- ): Promise<MiniThreeRuntime>;
35
- ```
36
-
37
- ### `createWeChatGameRuntime(options?) => Promise<MiniThreeRuntime>`
38
-
39
- ```ts
40
- interface WeChatGameOptions {
41
- wx?: WxLike; // 注入 wx(测试/非微信宿主)
42
- canvas?: WxCanvas; // 复用已有上屏画布
43
- capabilities?: Partial<Capabilities>;
44
- diagnostics?: Diagnostics;
45
- preferredFps?: number; // wx.setPreferredFramesPerSecond
46
- }
47
- type WeChatGameRuntimeOptions = WeChatGameOptions & RuntimeOptions;
48
- ```
49
-
50
- 另有 `createWeChatGameBinding(options) => PlatformBinding`(同步)、`getScreenCanvas(wx, supplied?)`、`resetScreenCanvasCache()`(测试用)。
51
-
52
- ### `createWeChatMiniProgramRuntime(options) => Promise<MiniThreeRuntime>`
53
-
54
- ```ts
55
- interface WeChatMiniProgramOptions {
56
- wx?: WxLike;
57
- selector: string; // 例如 '#gl'
58
- selectorCtx?: SelectorCtx; // 自定义组件内传 this
59
- queryDelay?: number; // 等待布局的毫秒数
60
- capabilities?: Partial<Capabilities>;
61
- diagnostics?: Diagnostics;
62
- }
63
- ```
64
-
65
- 另有 `createWeChatMiniProgramBinding(options) => Promise<PlatformBinding>`。
66
-
67
- ### `createBrowserRuntime(options?) => Promise<MiniThreeRuntime>`
68
-
69
- ```ts
70
- interface BrowserPlatformOptions {
71
- canvas?: HTMLCanvasElement;
72
- capabilities?: Partial<Capabilities>;
73
- diagnostics?: Diagnostics;
74
- }
75
- ```
76
-
77
- ---
78
-
79
- ### `RuntimeOptions`
80
-
81
- | 选项 | 类型 | 默认 | 说明 |
82
- | --- | --- | --- | --- |
83
- | `pixelRatioCap` | `number` | `2` | 限制 DPR,`0` 表示不封顶 |
84
- | `propagatePointerEvents` | `boolean` | `true` | 是否同时派发到 `document` / `window` |
85
- | `emitMouseEvents` | `boolean` | `true` | 是否额外发 `mouse*` / `click` |
86
- | `defaultContextType` | `'webgl2' \| 'webgl' \| '2d'` | `'webgl2'` | `document.createElement('canvas')` 的默认上下文 |
87
- | `cacheContexts` | `boolean` | `true` | 缓存 `getContext()` 结果,保证上下文身份稳定 |
88
- | `normalizeWebGL` | `boolean` | `true` | 修正 `getExtension` 返回值、`drawingBufferWidth/Height` |
89
- | `fpsCap` | `number` | `0` | 逻辑帧率上限 |
90
- | `slowFrameThreshold` | `number` | `0` | 慢帧告警阈值(ms) |
91
- | `logLevel` | `'silent' \| 'error' \| 'warn' \| 'info' \| 'debug'` | `'warn'` | 日志级别 |
92
- | `reporter` | `Reporter` | console | 自定义日志出口 |
93
- | `capabilities` | `Partial<Capabilities>` | — | 覆盖探测结果 |
94
- | `installGlobals` | `boolean` | `false` | 启动时立即注入全局(可逆) |
95
- | `diagnostics` | `Diagnostics` | — | 平台层注入(平台 options) |
96
-
97
- ### `MiniThreeRuntime`
98
-
99
- | 成员 | 类型 | 说明 |
100
- | --- | --- | --- |
101
- | `canvas` | `HTMLCanvasElement` | 已就地补丁的上屏/节点画布 |
102
- | `scope` | `MiniThreeScope` | 三方代码可见的作用域对象 |
103
- | `document` | `DocumentLike` | `createElement` / `createElementNS` / `body` / `defaultView` |
104
- | `capabilities` | `Capabilities` | 探测结果 |
105
- | `diagnostics` | `Diagnostics` | 日志与报告 |
106
- | `frames` | `FrameScheduler` | rAF / delta / fps |
107
- | `bridge` | `PointerBridge` | 事件桥 |
108
- | `windowInfo` | `WindowInfo` | 实时尺寸与 DPR(getter) |
109
- | `rendererHints` | `RendererHints` | 可直接展开给 `new THREE.WebGLRenderer()` |
110
- | `disposed` | `boolean` | 是否已释放 |
111
- | `handleTouch(event, opts?)` | `(TouchLikeEvent, {propagate?, computeRect?}) => void` | 手动转发触摸(小程序必需) |
112
- | `resize()` | `() => Promise<void>` | 重新测量并广播 resize |
113
- | `installGlobals(opts?)` | `() => Disposer` | 显式全局注入并返回还原函数 |
114
- | `createCanvas(w?, h?, type?)` | `() => HTMLCanvasElement` | 额外的离屏画布 |
115
- | `on(event, listener)` | `() => Disposer` | 见下表 |
116
- | `report()` | `() => string` | 能力报告文本 |
117
- | `dispose()` | `() => void` | 释放全部副作用 |
118
-
119
- `RuntimeEvents`:
120
-
121
- | 事件 | 回调 |
122
- | --- | --- |
123
- | `resize` | `(info: WindowInfo) => void` |
124
- | `visibilitychange` | `(visible: boolean) => void` |
125
- | `contextlost` | `() => void` |
126
- | `dispose` | `() => void` |
127
- | `error` | `(error: Error) => void` |
128
-
129
- `RendererHints`:`{ canvas, antialias: false, alpha: false, powerPreference: 'high-performance', preserveDrawingBuffer: false, outputColorSpace: 'srgb' }`。
130
-
131
- ---
132
-
133
- ## 4.3 作用域
134
-
135
- ```ts
136
- function createScope(overrides?: Partial<MiniThreeScope>): MiniThreeScope;
137
- function getActiveScope(): MiniThreeScope; // 未初始化时返回「可 typeof、取值即抛错」的占位
138
- function setActiveScope(scope: MiniThreeScope | null): () => void;
139
- function hasActiveScope(): boolean;
140
- function installGlobals(scope, options?): () => void;
141
- ```
142
-
143
- `MiniThreeScope` 同时扮演 `window` / `self` / `globalThis`(三者指向自身),并包含:
144
-
145
- - 领域对象:`document`、`navigator`、`screen`、`performance`、`getComputedStyle`、`matchMedia`;
146
- - 尺寸:`innerWidth`、`innerHeight`、`outerWidth`、`outerHeight`、`devicePixelRatio`、`pageXOffset`、`pageYOffset`(均为 live getter);
147
- - 事件:`Event`、`EventTarget`、`CustomEvent`、`PointerEvent`、`MouseEvent`、`TouchEvent`、`MessageEvent`、`ProgressEvent`、`KeyboardEvent`、`DOMException`;
148
- - DOM:`HTMLElement`、`HTMLCanvasElement`、`HTMLImageElement`、`OffscreenCanvas`、`Image`、`ImageData`、`DOMRect`、`WebGLRenderingContext`、`WebGL2RenderingContext`、`AudioContext`;
149
- - 网络/编码:`Blob`、`URL`、`TextEncoder`、`TextDecoder`、`fetch`、`XMLHttpRequest`、`AbortController`、`AbortSignal`、`atob`、`btoa`;
150
- - 帧:`requestAnimationFrame`、`cancelAnimationFrame`;
151
- - 明确不可用:`createImageBitmap`、`FileReader`、`WebSocket` 为 `undefined`(让 three 走降级分支)。
152
-
153
- `installGlobals(scope, { target?, skipExisting?, extraKeys? })` 把上述键定义为 `globalThis` 上的 getter;返回的 disposer 会精确还原原有 descriptor。
154
-
155
- ---
156
-
157
- ## 4.4 core 子路径
158
-
159
- | API | 签名 / 说明 |
160
- | --- | --- |
161
- | `patchElement(instance, options)` | 就地补 DOM 属性,返回 `{ element, updateRect, disposers }` |
162
- | `createMockClass(name)` | 生成带 `Symbol.hasInstance` + `WeakSet` 的构造器 shim |
163
- | `markAs(ctor, obj)` / `isMarked(ctor, obj)` | 注册 / 查询 instanceof 关系 |
164
- | `*Shim` | `HTMLCanvasElementShim`、`HTMLImageElementShim`、`HTMLElementShim`、`OffscreenCanvasShim`、`ImageDataShim`、`WebGLRenderingContextShim`、`WebGL2RenderingContextShim`、`DOMRectShim` |
165
- | `patchCanvas(raw, options)` | 返回 `{ canvas, contexts, updateRect, element, disposers }` |
166
- | `createOffscreenCanvas(wx, w?, h?, options?)` | 直接创建并补丁离屏画布 |
167
- | `createImageFactory(wx, diagnostics?)` | `{ Image, HTMLImageElement, ImageData, createImage, createImageData, createImageBitmap: undefined }`。工厂会把底层 `wx` 图片的**原生** `onload`/`onerror` 桥接成合成事件:`img.onload = fn` 与 `addEventListener('load', fn)` 都能收到通知,`decode()` 也据此 settle |
168
- | `createDocument(options)` / `createScreen(w, h)` / `ShimDOMRect` | 伪 DOM 容器 |
169
- | `PointerBridge` | `dispatch(event, opts?)`、`dispatchMouse(event)`、`setRect`、`refreshRect`、`setPointerCapture`、`releasePointerCapture`、`activePointerCount`、`dispose` |
170
- | `createFrameScheduler(raf, caf, options)` | `request` / `cancel` / `loop(cb)` / `setFpsCap` / `fps` / `dispose` |
171
- | `createWindowInfoStore(wx, options)` | `info` / `refresh()` / `onChange()` / `setPixelRatioCap()` / `dispose()` |
172
- | `detectCapabilities(wx, platform, options)` / `versionAtLeast(a, b)` | 能力探测。`options.probeContext(type)` 返回 `true` / `false` / `undefined`,**`undefined` 表示「探测不到」而不是「不支持」**,此时 `webgl2` 按基础库版本推断并在 `webgl2Source` 里标记为 `'inferred'` |
173
- | `createDiagnostics(level, reporter)` / `capabilityReport(caps)` | 日志与报告 |
174
- | `currentScope()` | 返回当前作用域或 `null` |
175
-
176
- ### `PlatformBinding`(新增平台时实现)
177
-
178
- ```ts
179
- interface PlatformBinding {
180
- readonly kind: 'wechat-game' | 'wechat-miniprogram' | 'browser' | 'unknown';
181
- readonly wx?: WxLike;
182
- readonly rawCanvas: WxCanvas;
183
- readonly capabilities: Capabilities;
184
- readonly imageFactory: ImageFactory;
185
- getCanvasRect(): Rect | Promise<Rect>;
186
- createOffscreenCanvas(w: number, h: number, type: ContextType): WxCanvas;
187
- watchTouch(handler: (e: TouchLikeEvent) => void): Disposer;
188
- watchVisibility(handler: (visible: boolean) => void): Disposer;
189
- requestAnimationFrame(cb: (time: number) => void): number;
190
- cancelAnimationFrame(id: number): void;
191
- now(): number;
192
- dispose(): void;
193
- }
194
- ```
195
-
196
- ---
197
-
198
- ## 4.5 polyfills 子路径
199
-
200
- | API | 说明 |
201
- | --- | --- |
202
- | `MiniEvent` / `MiniCustomEvent` / `MiniPointerEvent` / `MiniMouseEvent` / `MiniMessageEvent` / `MiniProgressEvent` / `MiniDOMException` | 事件对象 |
203
- | `MiniEventTarget` / `patchEventTarget(obj)` | 事件目标;`patchEventTarget` 不改变对象身份。监听器被调用时 `this`、`event.target`、`event.currentTarget` 都是**宿主元素**而不是内部载体——three 的 `ImageLoader` 用 `this` 取 `<img>` 当纹理源,拿错对象就等于没有像素 |
204
- | `MiniBlob` | `bytes()`、`arrayBuffer()`、`text()`、`slice()`、`dataURL()`、`size`、`type` |
205
- | `MiniURL` | `createObjectURL` / `revokeObjectURL` / `resolveObjectURL` / `clearObjectURLs`;构造器支持相对路径解析 |
206
- | `MiniURLSearchParams` | `get` / `set` / `toString` |
207
- | `bytesToBase64` / `base64ToBytes` / `resolveUrl` | 编码与 URL 工具 |
208
- | `atob` / `btoa` / `MiniTextEncoder` / `MiniTextDecoder` | 编码 |
209
- | `createFetch(wx)` / `MiniXMLHttpRequest` / `createXMLHttpRequestFactory(wx)` / `MiniAbortController` / `MiniAbortSignal` | 网络 |
210
-
211
- > 注意:对象 URL 采用 `mini-three-blob:` 前缀并解析为 `data:` URI,而不是浏览器 `blob:` ——因为微信 image loader 只认 `data:` / 本地路径。
212
-
213
- ---
214
-
215
- ## 4.6 构建插件
216
-
217
- ### Vite
218
-
219
- ```ts
220
- import miniThree from 'mini-three-adapter/vite';
221
- plugins: [miniThree(options)];
222
- ```
223
-
224
- 插件额外提供 `config()`,设置 `optimizeDeps.exclude: ['three', 'three-stdlib', 'three/examples/jsm']`,确保 AST 重写见到原始 ESM 模块图。
225
-
226
- ### Rollup
227
-
228
- ```ts
229
- import { miniThree } from 'mini-three-adapter/rollup';
230
- plugins: [miniThree(options)];
231
- ```
232
-
233
- ### `MiniThreePluginOptions`
234
-
235
- | 选项 | 类型 | 默认 | 说明 |
236
- | --- | --- | --- | --- |
237
- | `include` | `(id: string) => boolean` | 匹配 `three` / `three-stdlib` / `@react-three` / `@tresjs` / `.vite/deps/three*` | 需要重写的模块 |
238
- | `exclude` | `(id: string) => boolean` | `() => false` | 排除 |
239
- | `includeUserCode` | `boolean` | `false` | 是否也改写应用代码 |
240
- | `rewrite` | `RewriteOptions` | — | 高级重写配置 |
241
- | `webgpu` | `'warn' \| 'error' \| 'rewrite' \| 'ignore'` | `'warn'` | 遇到 `three/webgpu` 的策略 |
242
- | `roots` | `string[]` | three jsm/libs、`three-stdlib`、`public`、`static` | 资源搜索目录 |
243
- | `outputDir` | `string` | `'assets/three'` | 资源输出目录 |
244
- | `brotli` | `boolean` | `true` | 同时拷贝 `.wasm.br` |
245
- | `manifest` | `boolean` | `true` | 输出 `mini-three-assets.json` |
246
- | `cwd` | `string` | `process.cwd()` | 解析 roots 的根目录 |
247
- | `report` | `boolean` | `true` | 打印构建摘要 |
248
- | `debug` | `boolean` | `false` | 逐模块日志 |
249
-
250
- ### `RewriteOptions`
251
-
252
- | 选项 | 默认 | 说明 |
253
- | --- | --- | --- |
254
- | `globals` | `DEFAULT_GLOBAL_NAMES` | 替换默认清单(而非追加) |
255
- | `extraGlobals` | `[]` | 追加清单 |
256
- | `forceUndef` | `['createImageBitmap']` | 强制走 `__m3().x`(作用域中恒为 `undefined`) |
257
- | `accessor` | `'__m3'` | 注入的 `getActiveScope` 别名 |
258
- | `scopeModule` | `'mini-three-adapter/scope'` | 注入的 import 路径 |
259
-
260
- ### 高级导出(`mini-three-adapter/rollup`)
261
-
262
- `rewriteGlobals(code, id, options)`、`DEFAULT_GLOBAL_NAMES`、`DEFAULT_FORCE_UNDEF`、`collectAssetReferences`、`collectAssets`、`copyAssets`、`miniThreePlugin`。
263
-
264
- `plugin.api.report()` → `BuildReport`:`modulesScanned`、`modulesRewritten`、`rewrites`、`globalsSeen`、`assetReferences`、`missingAssets`、`webgpuWarnings`、`parseFailures`。
265
-
266
- ---
267
-
268
- ## 4.7 类型速查
269
-
270
- ```ts
271
- interface Capabilities {
272
- platform: 'wechat-game' | 'wechat-miniprogram' | 'browser' | 'unknown';
273
- webgl2: boolean;
274
- /** 'probe' 实测 / 'inferred' 版本推断 / 'override' 调用方覆盖 */
275
- webgl2Source?: 'probe' | 'inferred' | 'override';
276
- webgl1: boolean; offscreenCanvas: boolean;
277
- worker: boolean; wasm: boolean; brotliWasm: boolean; nativeImage: boolean;
278
- triggerGC: boolean; getWindowInfo: boolean; windowResizeEvent: boolean;
279
- baseLibraryVersion: string;
280
- }
281
-
282
- interface WindowInfo {
283
- width: number; height: number; pixelRatio: number; rawPixelRatio: number;
284
- safeArea?: Rect;
285
- }
286
-
287
- interface Rect { top: number; left: number; width: number; height: number; right: number; bottom: number; }
288
-
289
- interface TouchLikeEvent {
290
- type: string; touches?: ArrayLike<TouchPoint>;
291
- changedTouches?: ArrayLike<TouchPoint>; timeStamp?: number;
292
- [key: string]: unknown;
293
- }
294
- ```
1
+ # 04 · API 参考
2
+
3
+ > 版本:0.1.5。所有签名以 `src/**` 与 `npm run build` 生成的 `dist/*.d.ts` 为准。
4
+ > 子路径导入可最大化 tree-shaking;`mini-three-adapter` 是汇总入口。
5
+
6
+ ## 4.1 子路径
7
+
8
+ | 子路径 | 内容 |
9
+ | --- | --- |
10
+ | `mini-three-adapter` | 全部公开 API |
11
+ | `mini-three-adapter/core` | 平台无关运行时 |
12
+ | `mini-three-adapter/scope` | `getActiveScope()` 等(**构建插件注入的 import 目标**) |
13
+ | `mini-three-adapter/wechat-game` | 小游戏入口 |
14
+ | `mini-three-adapter/wechat-miniprogram` | 小程序入口 |
15
+ | `mini-three-adapter/browser` | 浏览器 / H5 / Node 测试 |
16
+ | `mini-three-adapter/polyfills` | 独立 polyfill |
17
+ | `mini-three-adapter/vite` | Vite 插件 |
18
+ | `mini-three-adapter/rollup` | Rollup 插件 + 高级 API |
19
+ | `mini-three-adapter/plugin` | `vite` 的别名 |
20
+ | `mini-three-adapter/package.json` | 读取包元信息(`version`、`exports`) |
21
+
22
+ ---
23
+
24
+ ## 4.2 生命周期
25
+
26
+ ### `createRuntime(platform, options?) => Promise<MiniThreeRuntime>`
27
+
28
+ 平台无关的总装配入口。通常不直接调用,而用下面的平台快捷函数。
29
+
30
+ ```ts
31
+ function createRuntime(
32
+ platform: PlatformBinding | PlatformFactory,
33
+ options?: RuntimeOptions,
34
+ ): Promise<MiniThreeRuntime>;
35
+ ```
36
+
37
+ ### `createWeChatGameRuntime(options?) => Promise<MiniThreeRuntime>`
38
+
39
+ ```ts
40
+ interface WeChatGameOptions {
41
+ wx?: WxLike; // 注入 wx(测试/非微信宿主)
42
+ canvas?: WxCanvas; // 复用已有上屏画布
43
+ capabilities?: Partial<Capabilities>;
44
+ diagnostics?: Diagnostics;
45
+ preferredFps?: number; // wx.setPreferredFramesPerSecond
46
+ }
47
+ type WeChatGameRuntimeOptions = WeChatGameOptions & RuntimeOptions;
48
+ ```
49
+
50
+ 另有 `createWeChatGameBinding(options) => PlatformBinding`(同步)、`getScreenCanvas(wx, supplied?)`、`resetScreenCanvasCache()`(测试用)。
51
+
52
+ ### `createWeChatMiniProgramRuntime(options) => Promise<MiniThreeRuntime>`
53
+
54
+ ```ts
55
+ interface WeChatMiniProgramOptions {
56
+ wx?: WxLike;
57
+ selector: string; // 例如 '#gl'
58
+ selectorCtx?: SelectorCtx; // 自定义组件内传 this
59
+ queryDelay?: number; // 等待布局的毫秒数
60
+ capabilities?: Partial<Capabilities>;
61
+ diagnostics?: Diagnostics;
62
+ }
63
+ ```
64
+
65
+ 另有 `createWeChatMiniProgramBinding(options) => Promise<PlatformBinding>`。
66
+
67
+ ### `createBrowserRuntime(options?) => Promise<MiniThreeRuntime>`
68
+
69
+ ```ts
70
+ interface BrowserPlatformOptions {
71
+ canvas?: HTMLCanvasElement;
72
+ capabilities?: Partial<Capabilities>;
73
+ diagnostics?: Diagnostics;
74
+ }
75
+ ```
76
+
77
+ ---
78
+
79
+ ### `RuntimeOptions`
80
+
81
+ | 选项 | 类型 | 默认 | 说明 |
82
+ | --- | --- | --- | --- |
83
+ | `pixelRatioCap` | `number` | `2` | 限制 DPR,`0` 表示不封顶 |
84
+ | `propagatePointerEvents` | `boolean` | `true` | 是否同时派发到 `document` / `window` |
85
+ | `emitMouseEvents` | `boolean` | `true` | 是否额外发 `mouse*` / `click` |
86
+ | `defaultContextType` | `'webgl2' \| 'webgl' \| '2d'` | `'webgl2'` | `document.createElement('canvas')` 的默认上下文 |
87
+ | `cacheContexts` | `boolean` | `true` | 缓存 `getContext()` 结果,保证上下文身份稳定 |
88
+ | `normalizeWebGL` | `boolean` | `true` | 修正 `getExtension` 返回值、`drawingBufferWidth/Height` |
89
+ | `fpsCap` | `number` | `0` | 逻辑帧率上限 |
90
+ | `slowFrameThreshold` | `number` | `0` | 慢帧告警阈值(ms) |
91
+ | `logLevel` | `'silent' \| 'error' \| 'warn' \| 'info' \| 'debug'` | `'warn'` | 日志级别 |
92
+ | `reporter` | `Reporter` | console | 自定义日志出口 |
93
+ | `capabilities` | `Partial<Capabilities>` | — | 覆盖探测结果 |
94
+ | `installGlobals` | `boolean` | `false` | 启动时立即注入全局(可逆) |
95
+ | `diagnostics` | `Diagnostics` | — | 平台层注入(平台 options) |
96
+
97
+ ### `MiniThreeRuntime`
98
+
99
+ | 成员 | 类型 | 说明 |
100
+ | --- | --- | --- |
101
+ | `canvas` | `HTMLCanvasElement` | 已就地补丁的上屏/节点画布 |
102
+ | `scope` | `MiniThreeScope` | 三方代码可见的作用域对象 |
103
+ | `document` | `DocumentLike` | `createElement` / `createElementNS` / `body` / `defaultView` |
104
+ | `capabilities` | `Capabilities` | 探测结果 |
105
+ | `diagnostics` | `Diagnostics` | 日志与报告 |
106
+ | `frames` | `FrameScheduler` | rAF / delta / fps |
107
+ | `bridge` | `PointerBridge` | 事件桥 |
108
+ | `windowInfo` | `WindowInfo` | 实时尺寸与 DPR(getter) |
109
+ | `rendererHints` | `RendererHints` | 可直接展开给 `new THREE.WebGLRenderer()` |
110
+ | `disposed` | `boolean` | 是否已释放 |
111
+ | `handleTouch(event, opts?)` | `(TouchLikeEvent, {propagate?, computeRect?}) => void` | 手动转发触摸(小程序必需) |
112
+ | `resize()` | `() => Promise<void>` | 重新测量并广播 resize |
113
+ | `installGlobals(opts?)` | `() => Disposer` | 显式全局注入并返回还原函数 |
114
+ | `createCanvas(w?, h?, type?)` | `() => HTMLCanvasElement` | 额外的离屏画布 |
115
+ | `on(event, listener)` | `() => Disposer` | 见下表 |
116
+ | `report()` | `() => string` | 能力报告文本 |
117
+ | `dispose()` | `() => void` | 释放全部副作用 |
118
+
119
+ `RuntimeEvents`:
120
+
121
+ | 事件 | 回调 |
122
+ | --- | --- |
123
+ | `resize` | `(info: WindowInfo) => void` |
124
+ | `visibilitychange` | `(visible: boolean) => void` |
125
+ | `contextlost` | `() => void` |
126
+ | `dispose` | `() => void` |
127
+ | `error` | `(error: Error) => void` |
128
+
129
+ `RendererHints`:`{ canvas, antialias: false, alpha: false, powerPreference: 'high-performance', preserveDrawingBuffer: false, outputColorSpace: 'srgb' }`。
130
+
131
+ ---
132
+
133
+ ## 4.3 作用域
134
+
135
+ ```ts
136
+ function createScope(overrides?: Partial<MiniThreeScope>): MiniThreeScope;
137
+ function getActiveScope(): MiniThreeScope; // 未初始化时返回占位对象,见下
138
+ function setActiveScope(scope: MiniThreeScope | null): () => void;
139
+ function hasActiveScope(): boolean;
140
+ function installGlobals(scope, options?): () => void;
141
+ function getEarlyScopeReads(): readonly string[]; // 未初始化时被读过的全局名
142
+ function clearEarlyScopeReads(): void;
143
+ ```
144
+
145
+ 未初始化时的占位对象有两条不同策略:
146
+
147
+ - `window` / `self` / `globalThis` 指向自身,`typeof window === 'object'`,与 three 的特性检测假设一致;
148
+ - `document` / `navigator` / `screen` / `location` / `history` 读作 `undefined`,等价于「这个宿主没有 DOM」。`typeof` 对这些键永不抛错,包括构建插件无法守卫的 `typeof window.document` 形态;
149
+ - 其余键(`HTMLCanvasElement`、`TextDecoder`、`Blob` …)读取即抛错,因为那不是探测而是真实使用,静默 `undefined` 只会在几帧之后以无关的形式爆掉。
150
+
151
+ 这些「读作 `undefined`」的早读会被记录,`createRuntime()` 启动后 `warnOnce` 汇总一次(提示 `three` 求值过早),随后清空。
152
+
153
+ `MiniThreeScope` 同时扮演 `window` / `self` / `globalThis`(三者指向自身),并包含:
154
+
155
+ - 领域对象:`document`、`navigator`、`screen`、`performance`、`getComputedStyle`、`matchMedia`;
156
+ - 尺寸:`innerWidth`、`innerHeight`、`outerWidth`、`outerHeight`、`devicePixelRatio`、`pageXOffset`、`pageYOffset`(均为 live getter);
157
+ - 事件:`Event`、`EventTarget`、`CustomEvent`、`PointerEvent`、`MouseEvent`、`TouchEvent`、`MessageEvent`、`ProgressEvent`、`KeyboardEvent`、`DOMException`;
158
+ - DOM:`HTMLElement`、`HTMLCanvasElement`、`HTMLImageElement`、`OffscreenCanvas`、`Image`、`ImageData`、`DOMRect`、`WebGLRenderingContext`、`WebGL2RenderingContext`、`AudioContext`;
159
+ - 网络/编码:`Blob`、`URL`、`TextEncoder`、`TextDecoder`、`fetch`、`XMLHttpRequest`、`AbortController`、`AbortSignal`、`atob`、`btoa`;
160
+ - 帧:`requestAnimationFrame`、`cancelAnimationFrame`;
161
+ - 明确不可用:`createImageBitmap`、`FileReader`、`WebSocket` 为 `undefined`(让 three 走降级分支)。
162
+
163
+ `installGlobals(scope, { target?, skipExisting?, extraKeys? })` 把上述键定义为 `globalThis` 上的 getter;返回的 disposer 会精确还原原有 descriptor。
164
+
165
+ ---
166
+
167
+ ## 4.4 core 子路径
168
+
169
+ | API | 签名 / 说明 |
170
+ | --- | --- |
171
+ | `patchElement(instance, options)` | 就地补 DOM 属性,返回 `{ element, updateRect, disposers }` |
172
+ | `createMockClass(name)` | 生成带 `Symbol.hasInstance` + `WeakSet` 的构造器 shim |
173
+ | `markAs(ctor, obj)` / `isMarked(ctor, obj)` | 注册 / 查询 instanceof 关系 |
174
+ | `*Shim` | `HTMLCanvasElementShim`、`HTMLImageElementShim`、`HTMLElementShim`、`OffscreenCanvasShim`、`ImageDataShim`、`WebGLRenderingContextShim`、`WebGL2RenderingContextShim`、`DOMRectShim` |
175
+ | `patchCanvas(raw, options)` | 返回 `{ canvas, contexts, updateRect, element, disposers }` |
176
+ | `createOffscreenCanvas(wx, w?, h?, options?)` | 直接创建并补丁离屏画布 |
177
+ | `createImageFactory(wx, diagnostics?)` | `{ Image, HTMLImageElement, ImageData, createImage, createImageData, createImageBitmap: undefined }`。工厂按「原生 `addEventListener` → `onload`/`onerror` 赋值 → `wx.getImageInfo` → 2s watchdog」四级兜底把宿主事件桥接成合成事件:`img.onload = fn` 与 `addEventListener('load', fn)` 都能收到通知,`complete` 在成功/失败后都为 `true`,`decode()` 据此 resolve/reject。宿主既无事件入口也无 `getImageInfo` 时不再静默挂起,而是在 2s 内派发带 `reason` 的 `error` |
178
+ | `createDocument(options)` / `createScreen(w, h)` / `ShimDOMRect` | 伪 DOM 容器 |
179
+ | `PointerBridge` | `dispatch(event, opts?)`、`dispatchMouse(event)`、`setRect`、`refreshRect`、`setPointerCapture`、`releasePointerCapture`、`activePointerCount`、`dispose` |
180
+ | `createFrameScheduler(raf, caf, options)` | `request` / `cancel` / `loop(cb)` / `setFpsCap` / `fps` / `dispose` |
181
+ | `createWindowInfoStore(wx, options)` | `info` / `refresh()` / `onChange()` / `setPixelRatioCap()` / `dispose()` |
182
+ | `detectCapabilities(wx, platform, options)` / `versionAtLeast(a, b)` | 能力探测。`options.probeContext(type)` 返回 `true` / `false` / `undefined`,**`undefined` 表示「探测不到」而不是「不支持」**,此时 `webgl2` 按基础库版本推断并在 `webgl2Source` 里标记为 `'inferred'` |
183
+ | `createDiagnostics(level, reporter)` / `capabilityReport(caps)` | 日志与报告 |
184
+ | `currentScope()` | 返回当前作用域或 `null` |
185
+
186
+ ### `PlatformBinding`(新增平台时实现)
187
+
188
+ ```ts
189
+ interface PlatformBinding {
190
+ readonly kind: 'wechat-game' | 'wechat-miniprogram' | 'browser' | 'unknown';
191
+ readonly wx?: WxLike;
192
+ readonly rawCanvas: WxCanvas;
193
+ readonly capabilities: Capabilities;
194
+ readonly imageFactory: ImageFactory;
195
+ getCanvasRect(): Rect | Promise<Rect>;
196
+ createOffscreenCanvas(w: number, h: number, type: ContextType): WxCanvas;
197
+ watchTouch(handler: (e: TouchLikeEvent) => void): Disposer;
198
+ watchVisibility(handler: (visible: boolean) => void): Disposer;
199
+ requestAnimationFrame(cb: (time: number) => void): number;
200
+ cancelAnimationFrame(id: number): void;
201
+ now(): number;
202
+ dispose(): void;
203
+ }
204
+ ```
205
+
206
+ ---
207
+
208
+ ## 4.5 polyfills 子路径
209
+
210
+ | API | 说明 |
211
+ | --- | --- |
212
+ | `MiniEvent` / `MiniCustomEvent` / `MiniPointerEvent` / `MiniMouseEvent` / `MiniMessageEvent` / `MiniProgressEvent` / `MiniDOMException` | 事件对象 |
213
+ | `MiniEventTarget` / `patchEventTarget(obj)` | 事件目标;`patchEventTarget` 不改变对象身份。监听器被调用时 `this`、`event.target`、`event.currentTarget` 都是**宿主元素**而不是内部载体——three 的 `ImageLoader` 用 `this` 取 `<img>` 当纹理源,拿错对象就等于没有像素 |
214
+ | `MiniBlob` | `bytes()`、`arrayBuffer()`、`text()`、`slice()`、`dataURL()`、`size`、`type` |
215
+ | `MiniURL` | `createObjectURL` / `revokeObjectURL` / `resolveObjectURL` / `clearObjectURLs`;构造器支持相对路径解析 |
216
+ | `MiniURLSearchParams` | `get` / `set` / `toString` |
217
+ | `bytesToBase64` / `base64ToBytes` / `resolveUrl` | 编码与 URL 工具 |
218
+ | `atob` / `btoa` / `MiniTextEncoder` / `MiniTextDecoder` | 编码 |
219
+ | `createFetch(wx)` / `MiniXMLHttpRequest` / `createXMLHttpRequestFactory(wx)` / `MiniAbortController` / `MiniAbortSignal` | 网络 |
220
+
221
+ > 注意:对象 URL 采用 `mini-three-blob:` 前缀并解析为 `data:` URI,而不是浏览器 `blob:` ——因为微信 image loader 只认 `data:` / 本地路径。
222
+
223
+ ---
224
+
225
+ ## 4.6 构建插件
226
+
227
+ ### Vite
228
+
229
+ ```ts
230
+ import miniThree from 'mini-three-adapter/vite';
231
+ plugins: [miniThree(options)];
232
+ ```
233
+
234
+ 插件额外提供 `config()`,设置 `optimizeDeps.exclude: ['three', 'three-stdlib', 'three/examples/jsm']`,确保 AST 重写见到原始 ESM 模块图。
235
+
236
+ ### Rollup
237
+
238
+ ```ts
239
+ import { miniThree } from 'mini-three-adapter/rollup';
240
+ plugins: [miniThree(options)];
241
+ ```
242
+
243
+ ### `MiniThreePluginOptions`
244
+
245
+ | 选项 | 类型 | 默认 | 说明 |
246
+ | --- | --- | --- | --- |
247
+ | `include` | `(id: string) => boolean` | 匹配 `three` / `three-stdlib` / `@react-three` / `@tresjs` / `.vite/deps/three*` | 需要重写的模块 |
248
+ | `exclude` | `(id: string) => boolean` | `() => false` | 排除 |
249
+ | `includeUserCode` | `boolean` | `false` | 是否也改写应用代码 |
250
+ | `rewrite` | `RewriteOptions` | — | 高级重写配置 |
251
+ | `webgpu` | `'warn' \| 'error' \| 'rewrite' \| 'ignore'` | `'warn'` | 遇到 `three/webgpu` 的策略 |
252
+ | `roots` | `string[]` | three jsm/libs、`three-stdlib`、`public`、`static` | 资源搜索目录 |
253
+ | `outputDir` | `string` | `'assets/three'` | 资源输出目录 |
254
+ | `brotli` | `boolean` | `true` | 同时拷贝 `.wasm.br` |
255
+ | `manifest` | `boolean` | `true` | 输出 `mini-three-assets.json` |
256
+ | `cwd` | `string` | `process.cwd()` | 解析 roots 的根目录 |
257
+ | `report` | `boolean` | `true` | 打印构建摘要 |
258
+ | `debug` | `boolean` | `false` | 逐模块日志 |
259
+
260
+ ### `RewriteOptions`
261
+
262
+ | 选项 | 默认 | 说明 |
263
+ | --- | --- | --- |
264
+ | `globals` | `DEFAULT_GLOBAL_NAMES` | 替换默认清单(而非追加) |
265
+ | `extraGlobals` | `[]` | 追加清单 |
266
+ | `forceUndef` | `['createImageBitmap']` | 强制走 `__m3().x`(作用域中恒为 `undefined`) |
267
+ | `accessor` | `'__m3'` | 注入的 `getActiveScope` 别名 |
268
+ | `scopeModule` | `'mini-three-adapter/scope'` | 注入的 import 路径 |
269
+
270
+ ### 高级导出(`mini-three-adapter/rollup`)
271
+
272
+ `rewriteGlobals(code, id, options)`、`DEFAULT_GLOBAL_NAMES`、`DEFAULT_FORCE_UNDEF`、`collectAssetReferences`、`collectAssets`、`copyAssets`、`miniThreePlugin`。
273
+
274
+ `plugin.api.report()` → `BuildReport`:`modulesScanned`、`modulesRewritten`、`rewrites`、`globalsSeen`、`assetReferences`、`missingAssets`、`webgpuWarnings`、`parseFailures`。
275
+
276
+ ---
277
+
278
+ ## 4.7 类型速查
279
+
280
+ ```ts
281
+ interface Capabilities {
282
+ platform: 'wechat-game' | 'wechat-miniprogram' | 'browser' | 'unknown';
283
+ webgl2: boolean;
284
+ /** 'probe' 实测 / 'inferred' 版本推断 / 'override' 调用方覆盖 */
285
+ webgl2Source?: 'probe' | 'inferred' | 'override';
286
+ webgl1: boolean; offscreenCanvas: boolean;
287
+ worker: boolean; wasm: boolean; brotliWasm: boolean; nativeImage: boolean;
288
+ triggerGC: boolean; getWindowInfo: boolean; windowResizeEvent: boolean;
289
+ baseLibraryVersion: string;
290
+ }
291
+
292
+ interface WindowInfo {
293
+ width: number; height: number; pixelRatio: number; rawPixelRatio: number;
294
+ safeArea?: Rect;
295
+ }
296
+
297
+ interface Rect { top: number; left: number; width: number; height: number; right: number; bottom: number; }
298
+
299
+ interface TouchLikeEvent {
300
+ type: string; touches?: ArrayLike<TouchPoint>;
301
+ changedTouches?: ArrayLike<TouchPoint>; timeStamp?: number;
302
+ [key: string]: unknown;
303
+ }
304
+ ```
@@ -57,7 +57,9 @@ flowchart TD
57
57
 
58
58
  > 为什么只有 `new` 需要括号:`typeof`、`in`、`delete`、`?.`、`instanceof` 右侧等位置,`__m3().X` 的优先级都足够高;唯一优先级倒挂的是 `new`。
59
59
 
60
- > 为什么 `typeof` 要单独守卫:`typeof` 是本应永不抛错的运算符,而 `emptyScope` 对未初始化的 `document` 等键会抛出可读错误。不加守卫时,库顶层的 `const isBrowser = typeof document !== 'undefined'` 会在 runtime 创建之前直接崩掉,而报错指向适配层,极易误判为「初始化顺序写错」。守卫只加在 `window/self/globalThis` 之外的名字上,因为这三个在 `emptyScope` 里恒指向自身。
60
+ > 为什么 `typeof` 要单独守卫:`typeof` 是本应永不抛错的运算符,而 `emptyScope` 只对 `document` / `navigator` / `screen` / `location` / `history` 返回 `undefined`,其余键(`TextDecoder`、`HTMLCanvasElement`、`Blob` …)仍然抛可读错误。不加守卫时,库顶层的 `typeof TextDecoder !== 'undefined'` 会在 runtime 创建之前直接崩掉,而报错指向适配层,极易误判为「初始化顺序写错」。守卫只加在 `window/self/globalThis` 之外的名字上,因为这三个在 `emptyScope` 里恒指向自身。
61
+
62
+ > 守卫的边界:它只覆盖 `typeof X` 这种**直接操作数**。`typeof window.document` 的操作数是成员表达式,插件唯一能改的是 `window`,因此那条路径靠 `emptyScope` 把 `document` 读作 `undefined` 来兜住(见 [ADR-0009](./adr/0009-placeholder-scope-environment-globals.md))。
61
63
 
62
64
  `globalThis` **故意不在**默认清单里:three 会用它挂调试钩子(`__THREE_DEVTOOLS__` 等),改写会破坏这些逻辑。
63
65
 
@@ -168,7 +170,7 @@ console.log(plugin.api.report());
168
170
  | --- | --- | --- |
169
171
  | `Class constructor xxx cannot be invoked without 'new'`(栈顶常是 `GLTFLoader.js:444`) | 改写产物把 `new TextDecoder()` 变成了 `(new __m3()).TextDecoder()` | 升级到含本修复的版本;宿主侧临时补丁见下 |
170
172
  | `SyntaxError: Unexpected token '.'`,指向 `{ __m3().xxx }` | 对象简写属性被原地替换 | 同上 |
171
- | `Scoped global "document" was read before a runtime was created` | 真的在 runtime 之前读了 `document`(不是 `typeof`) | 按 [`docs/07`](./07-integration-guide.md#74-入口改造最关键的一步) 调整入口顺序 |
173
+ | `Scoped global "document" was read before a runtime was created` | 真的在 runtime 之前读了 `document`(不是 `typeof`);`document` 本身已不再抛错,这个文案现在只会出现在 `TextDecoder` / `HTMLCanvasElement` 这类真实 API 上 | 按 [`docs/07`](./07-integration-guide.md#74-入口改造最关键的一步) 调整入口顺序 |
172
174
  | `new __m3().X` 残留 | 适配层版本过旧 | 检查 `dist` 里的重写器版本,清理缓存后重建 |
173
175
 
174
176
  临时规避(仅用于旧版本):在适配层插件**之后**(`enforce: 'post'`)跑一段产物级正则,把 `new __m3().X()` 改成 `new (__m3().X)()`。它依赖访问器名与「空参数」两个特征,适配层改了默认 `accessor` 就会静默失效,因此修复到位后应当删除。