├── .eslintrc.js
├── .github
└── workflows
│ └── test.yml
├── .gitignore
├── .npmrc
├── CHANGELOG.md
├── LICENSE
├── README-en.md
├── README.md
├── index.d.ts
├── package-lock.json
├── package.json
├── test
├── .eslintrc.js
├── api-doc.test.ts
├── api-promisify.test.ts
├── game.test.ts
└── index.d.ts
├── tsconfig.json
├── types
├── index.d.ts
└── wx
│ ├── index.d.ts
│ ├── lib.wx.api.d.ts
│ ├── lib.wx.cloud.d.ts
│ └── lib.wx.wasm.d.ts
└── typings.json
/.eslintrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | root: true,
3 | parser: '@typescript-eslint/parser',
4 | parserOptions: {
5 | project: './tsconfig.json'
6 | },
7 | plugins: [
8 | '@typescript-eslint',
9 | ],
10 | rules: {
11 | indent: ['error', 4],
12 | 'no-trailing-spaces': ['error'],
13 | semi: ['off'],
14 | '@typescript-eslint/semi': ['error', 'never'],
15 | '@typescript-eslint/no-extra-semi': ['error'],
16 | quotes: ['off'],
17 | '@typescript-eslint/quotes': ['error', 'single'],
18 | '@typescript-eslint/ban-ts-comment': ['off'],
19 | '@typescript-eslint/adjacent-overload-signatures': ['error'],
20 | '@typescript-eslint/ban-types': ['error', {
21 | extendDefaults: true,
22 | types: {
23 | /**
24 | * we are using `{}` as noop
25 | * e.g. `type A
= B & (P extends Q ? C : {})`
26 | * will get `B & C` when `P extends Q` and `B` otherwise
27 | */
28 | '{}': false,
29 | /**
30 | * we actually need a type accepting any function-like value
31 | * e.g. `type Methods = Record`
32 | */
33 | 'Function': false,
34 | }
35 | }],
36 | '@typescript-eslint/member-delimiter-style': ['error', {
37 | multiline: {
38 | delimiter: 'none',
39 | requireLast: false,
40 | },
41 | singleline: {
42 | delimiter: 'comma',
43 | requireLast: false
44 | }
45 | }],
46 | '@typescript-eslint/naming-convention': ['error', {
47 | selector: 'enum',
48 | format: ['PascalCase', 'UPPER_CASE'],
49 | leadingUnderscore: 'forbid',
50 | trailingUnderscore: 'forbid',
51 | }, {
52 | selector: 'typeLike',
53 | format: ['PascalCase'],
54 | leadingUnderscore: 'forbid',
55 | trailingUnderscore: 'forbid',
56 | }],
57 | '@typescript-eslint/array-type': ['error', {
58 | default: 'array-simple',
59 | readonly: 'array-simple'
60 | }],
61 | '@typescript-eslint/no-unnecessary-qualifier': ['error'],
62 | },
63 | }
--------------------------------------------------------------------------------
/.github/workflows/test.yml:
--------------------------------------------------------------------------------
1 | # From: https://github.com/wechat-miniprogram/api-typings/blob/9c691dd47158d9a029a68105c2378a3668874cf4/.github/workflows/test.yml
2 | # Author: Mr.Hope
3 | name: Test
4 |
5 | on:
6 | - push
7 | - pull_request
8 |
9 | jobs:
10 | test:
11 | runs-on: ubuntu-latest
12 | steps:
13 | - name: Checkout
14 | uses: actions/checkout@v4
15 | with:
16 | persist-credentials: false
17 |
18 | - name: restore node modules
19 | uses: actions/cache@v4
20 | id: node-modules-cache
21 | with:
22 | path: node_modules
23 | key: ${{ runner.os }}-node-modules-${{ hashFiles('package-lock.json') }}
24 |
25 | - name: Install Deps
26 | if: steps.node-modules-cache.outputs.cache-hit != 'true'
27 | run: npm ci
28 |
29 | - name: Run test
30 | run: npm run test
31 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # npm
2 | node_modules
3 |
4 | # OS X
5 | .DS_Store*
6 | Icon?
7 | ._*
8 |
--------------------------------------------------------------------------------
/.npmrc:
--------------------------------------------------------------------------------
1 | registry=https://registry.npmjs.org
2 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | ## 2025-04-14 v3.8.11
2 | - 更新 API 定义到 3.8.0
3 |
4 | ## 2025-03-17 v3.8.10
5 | - 更新 API 定义到 3.7.10
6 |
7 | ## 2025-02-08 v3.8.9
8 | - 解决依赖安全问题
9 |
10 | ## 2025-02-08 v3.8.8
11 | - 修复 `setTimeout` 和 `setInterval` 的参数 ([wechat-miniprogram/api-typings#323](https://github.com/wechat-miniprogram/api-typings/issues/323))
12 | - 更新 API 定义到 3.7.7
13 |
14 | ## 2024-09-24 v3.8.7
15 | - 更新 API 定义到 3.6.1
16 |
17 | ## 2024-09-24 v3.8.6
18 | - 更新 API 定义到 3.5.7
19 | - 补齐 `wx.getPhoneNumber` 定义
20 |
21 | ## 2024-08-08 v3.8.5
22 | - 更新 API 定义到 3.5.2
23 |
24 | ## 2023-10-17 v3.8.4
25 | - 更新 API 定义到 3.2.3
26 |
27 | ## 2023-10-17 v3.8.3
28 | - 更新 API 定义到 3.1.2
29 |
30 | ## 2023-08-24 v3.8.2
31 | - 更新 API 定义到 3.0.1
32 |
33 | ## 2023-08-04 v3.8.1
34 | - 修正场景值文档链接
35 |
36 | ## 2023-08-04 v3.8.0
37 | - 更新 API 定义到 3.0.0
38 | - 补齐 `WXWebAssembly` 定义
39 |
40 | ## 2023-06-26 v3.7.4
41 | - 更新 API 定义到 2.32.0
42 |
43 | ## 2023-04-10 v3.7.3
44 | - 更新 API 定义到 2.30.4
45 | - 移除 `getFriendCloudStorage` 等开放数据域接口的 Promisify 定义及对应测试用例,因为它们的实现实际上并不支持 Promisify,此前为文档和定义有误
46 |
47 | ## 2023-02-02 v3.7.2
48 | - 补充几个接口缺失的 `errMsg` 字段
49 |
50 | ## 2023-01-12 v3.7.1
51 | - 更新 API 定义到 2.29.1
52 |
53 | ## 2022-09-09 v3.6.0
54 | - 更新 API 定义到 2.26.0
55 | - 更改了部分监听方法及其参数的命名
56 |
57 | ## 2022-06-24 v3.5.0
58 | - 更新 API 定义到 2.24.6
59 |
60 | ## 2022-01-20 v3.4.2
61 | - 更新 API 定义到 2.21.3
62 |
63 | ## 2021-08-02 v3.4.1
64 | - 更新 API 定义到 2.19.0
65 | - 重新整理了注释,包括:
66 | - 将支持和废弃情况挪到前面,使其更不容易因为接口说明太长而被忽略
67 | - 移除文首、文末和多余(连续超过两个)的空行
68 | - 修复几个链接
69 |
70 | ## 2021-07-07 v3.4.0
71 | - 更新 API 定义到 2.18.0
72 | - 自动化测试迁移到 GitHub Actions
73 | - 更新来自文档代码示例的测试用例
74 | - 更新 npm 依赖以解决安全问题
75 | - 修复 [api-typings/#202](https://github.com/wechat-miniprogram/api-typings/issues/202)
76 |
77 | ## 2021-04-21 v3.3.1
78 | - 更新 API 定义到 2.16.1
79 |
80 | ## 2021-03-03 v3.3.0
81 | - 同步 API 定义到基础库 2.15.0
82 | - 支持泛型([api-typings#177](https://github.com/wechat-miniprogram/api-typings/issues/177))
83 | - 支持索引签名,以支持 `wx.requestSubscribeMessage`([api-typings#175](https://github.com/wechat-miniprogram/api-typings/issues/175))
84 |
85 | ## 2021-01-12 v3.2.0
86 | - 同步 API 定义到基础库 2.14.1
87 |
88 | ## 2020-06-15 v2.11.0
89 | - 同步 API 定义到基础库 2.11.0
90 | - 该版本继续合并了一部分完全相同的 interface / callback,是一个 **破坏性改动**,原本字面上引用了这些 interface / callback 的代码可能会报错。
91 |
92 | ## 2020-05-21 v2.10.4
93 | - 同步 API 定义到基础库 2.10.4
94 | - 在之前的版本中,分属于不同接口的两个 interface / callback 即使完全相同,也会拥有不同的名字。在这次更新中,他们将合并为同一个(如 `GetLastRoomInfoSuccessCallbackDataResultRoomInfoRoomMemberInfo` 和 `GetRoomInfoSuccessCallbackDataResultRoomInfoRoomMemberInfo` 都变成了 `RoomMemberInfo`)。这是一个 **破坏性改动**,原本字面上引用了这些 interface / callback 的代码可能会报错。
95 | - 更新了小程序·云开发的 API 定义
96 |
97 | ## 2020-03-26 v2.10.3
98 | - 同步 API 定义到基础库 2.10.3
99 |
100 | ## 2020-03-18 v2.10.2-1
101 | - 支持 API Promise 化调用
102 |
103 | ## 2020-02-26 v2.10.2
104 | - 同步 API 定义到基础库 2.10.2
105 | - 将命名空间从 `wx` 更改为更正式的 `WechatMinigame`,这是一个 **破坏性改动**,原本字面上引用了 `wx` 命名空间的代码可能失效
106 | - 添加自动化测试
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README-en.md:
--------------------------------------------------------------------------------
1 | # Wechat MiniGame API Typings
2 |
3 | > [中文版本](./README.md)
4 |
5 | [](https://www.npmjs.com/package/minigame-api-typings)
6 | [](https://github.com/wechat-miniprogram/minigame-api-typings)
7 | [](https://github.com/wechat-miniprogram/minigame-api-typings/actions/workflows/test.yml)
8 |
9 | Type definitions for APIs of Wechat Mini Game in TypeScript
10 |
11 | ## Install
12 |
13 | Install by NPM:
14 |
15 | ```bash
16 | npm install minigame-api-typings
17 | ```
18 | Manually import it after installed:
19 | - `import 'minigame-api-typings';`
20 |
21 | Or specify types in typescript config:
22 | - Specify `types: ["minigame-api-typings"]` in `tsconfig.json`
23 |
24 | Or reference by [Triple-Slash Directives](https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html):
25 | - `/// `
26 |
27 | ## Changelog
28 |
29 | See [CHANGELOG.md](https://github.com/wechat-miniprogram/minigame-api-typings/blob/master/CHANGELOG.md) (Chinese only)
30 |
31 |
32 | ## Contribution
33 |
34 | Definitions of Wechat APIs (`lib.wx.api.d.ts`) are auto-generated together with our [documentations](https://developers.weixin.qq.com/minigame/en/dev/api/), therefore PRs including that file will __not__ be merged. If you found some APIs defined wrongly, create an issue instead.
35 |
36 |
37 | ### Automated tests
38 |
39 | We use [`tsd`](https://github.com/SamVerschueren/tsd) to check if this definition is working properly. All test cases are under folder `test`.
40 |
41 | To perform an automated test, clone this repo, `npm install --save-dev` and `npm test`.
42 |
43 | If you have test case that fails the test, an issue or PR will be great. Strong test case that passes are also welcomed.
44 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # 微信小游戏定义文件
2 |
3 | > [English version](./README-en.md)
4 |
5 | [](https://www.npmjs.com/package/minigame-api-typings)
6 | [](https://github.com/wechat-miniprogram/minigame-api-typings)
7 | [](https://github.com/wechat-miniprogram/minigame-api-typings/actions/workflows/test.yml)
8 |
9 | 微信小游戏 API 的 TypeScript 类型定义文件
10 |
11 | ## 安装
12 |
13 | ```bash
14 | npm install minigame-api-typings
15 | ```
16 | 安装后手动导入:
17 | - `import 'minigame-api-typings';`
18 |
19 | 或者在 ts 配置中指定:
20 | - 在 `tsconfig.json` 中指定 `types: ["minigame-api-typings"]`
21 |
22 | 或者通过 [三斜杠指令](https://www.tslang.cn/docs/handbook/triple-slash-directives.html) 引用:
23 | - `/// `
24 |
25 | ## 更新日志
26 |
27 | 参考 [CHANGELOG.md](https://github.com/wechat-miniprogram/minigame-api-typings/blob/master/CHANGELOG.md)
28 |
29 | ## 贡献
30 |
31 | API 的定义文件(`lib.wx.api.d.ts`)是随 [文档](https://developers.weixin.qq.com/minigame/dev/api/) 一起自动生成的,如果发现了 API 接口的定义错误,请提一个 issue 给我们,关于 API 的 PR 将 __不会__ 被接受。
32 |
33 | ### 测试
34 |
35 | 本定义文件使用 [`tsd`](https://github.com/SamVerschueren/tsd) 进行测试,所有的测试样例放在 `test` 目录下。
36 |
37 | 想执行测试的话,克隆本项目并完成 `npm install --save-dev` 后执行 `npm test` 即可。
38 |
39 | 如果您发现了不能通过自动化测试的测试样例,可以提交 PR 或者提一个 issue。当然,能通过自动化测试的强有力的测试样例也是欢迎的。
40 |
--------------------------------------------------------------------------------
/index.d.ts:
--------------------------------------------------------------------------------
1 | ///
2 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "minigame-api-typings",
3 | "version": "3.8.11",
4 | "description": "Type definitions for APIs of Wechat MiniGame in TypeScript",
5 | "main": "./index.d.ts",
6 | "types": "./index.d.ts",
7 | "scripts": {
8 | "test": "npm run tsd && npm run eslint",
9 | "tsd": "tsd",
10 | "eslint": "eslint --config .eslintrc.js types/**/*.ts"
11 | },
12 | "repository": {
13 | "type": "git",
14 | "url": "git+https://github.com/wechat-miniprogram/minigame-api-typings.git"
15 | },
16 | "author": "Wechat Miniprogram ",
17 | "license": "MIT",
18 | "bugs": {
19 | "url": "https://github.com/wechat-miniprogram/minigame-api-typings/issues"
20 | },
21 | "homepage": "https://github.com/wechat-miniprogram/minigame-api-typings#readme",
22 | "tsd": {
23 | "directory": "test"
24 | },
25 | "devDependencies": {
26 | "@typescript-eslint/eslint-plugin": "^5.46.0",
27 | "@typescript-eslint/parser": "^5.46.0",
28 | "eslint": "^8.29.0",
29 | "tsd": "^0.25.0",
30 | "typescript": "^4.9.4"
31 | },
32 | "files": [
33 | "LICENSE",
34 | "CHANGELOG.md",
35 | "VERSIONS.md",
36 | "README.md",
37 | "README-en.md",
38 | "index.d.ts",
39 | "typings.json",
40 | "types/"
41 | ]
42 | }
43 |
--------------------------------------------------------------------------------
/test/.eslintrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | rules: {
3 | indent: ['error', 2],
4 | },
5 | }
--------------------------------------------------------------------------------
/test/api-doc.test.ts:
--------------------------------------------------------------------------------
1 | import { expectType } from 'tsd'
2 |
3 | // Test case from `DownloadTask`
4 | {
5 | const downloadTask = wx.downloadFile({
6 | url: 'http://example.com/audio/123', // 仅为示例,并非真实的资源
7 | success() {},
8 | })
9 |
10 | downloadTask.onProgressUpdate(res => {
11 | console.log('下载进度', res.progress)
12 | console.log('已经下载的数据长度', res.totalBytesWritten)
13 | console.log('预期需要下载的数据总长度', res.totalBytesExpectedToWrite)
14 | })
15 |
16 | downloadTask.abort() // 取消下载任务
17 | }
18 |
19 | // Test case from `InnerAudioContext`
20 | {
21 | const innerAudioContext = wx.createInnerAudioContext()
22 | innerAudioContext.autoplay = true
23 | innerAudioContext.src =
24 | 'http://ws.stream.qqmusic.qq.com/M500001VfvsJ21xFqb.mp3?guid=ffffffff82def4af4b12b3cd9337d5e7&uin=346897220&vkey=6292F51E1E384E061FF02C31F716658E5C81F5594D561F2E88B854E81CAAB7806D5E4F103E55D33C16F3FAC506D1AB172DE8600B37E43FAD&fromtag=46'
25 | innerAudioContext.onPlay(() => {
26 | console.log('开始播放')
27 | })
28 | innerAudioContext.onError(res => {
29 | // console.log(res.errMsg)
30 | console.log(res.errCode)
31 | })
32 | }
33 |
34 | // Test case from `RecorderManager`
35 | {
36 | const recorderManager = wx.getRecorderManager()
37 |
38 | recorderManager.onStart(() => {
39 | console.log('recorder start')
40 | })
41 | recorderManager.onPause(() => {
42 | console.log('recorder pause')
43 | })
44 | recorderManager.onStop(res => {
45 | console.log('recorder stop', res)
46 | const { tempFilePath } = res
47 | expectType(tempFilePath)
48 | })
49 | recorderManager.onFrameRecorded(res => {
50 | const { frameBuffer } = res
51 | console.log('frameBuffer.byteLength', frameBuffer.byteLength)
52 | })
53 |
54 | recorderManager.start({
55 | duration: 10000,
56 | sampleRate: 44100,
57 | numberOfChannels: 1,
58 | encodeBitRate: 192000,
59 | format: 'aac',
60 | frameSize: 50,
61 | })
62 | }
63 |
64 | // Test case from `RequestTask`
65 | {
66 | const requestTask = wx.request({
67 | url: 'test.php', // 仅为示例,并非真实的接口地址
68 | data: {
69 | x: '',
70 | y: '',
71 | },
72 | header: {
73 | 'content-type': 'application/json',
74 | },
75 | success(res) {
76 | console.log(res.data)
77 | },
78 | })
79 | requestTask.abort() // 取消请求任务
80 | }
81 |
82 | // Test case from `UpdateManager`
83 | {
84 | const updateManager = wx.getUpdateManager()
85 |
86 | updateManager.onCheckForUpdate(function(res) {
87 | // 请求完新版本信息的回调
88 | console.log(res.hasUpdate)
89 | })
90 |
91 | updateManager.onUpdateReady(function() {
92 | wx.showModal({
93 | title: '更新提示',
94 | content: '新版本已经准备好,是否重启应用?',
95 | success(res) {
96 | if (res.confirm) {
97 | // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
98 | updateManager.applyUpdate()
99 | }
100 | },
101 | })
102 | })
103 |
104 | updateManager.onUpdateFailed(function() {
105 | // 新版本下载失败
106 | })
107 | }
108 |
109 | // Test case from `UploadTask`
110 | {
111 | const uploadTask = wx.uploadFile({
112 | url: 'http://example.weixin.qq.com/upload', // 仅为示例,非真实的接口地址
113 | filePath: '',
114 | name: 'file',
115 | formData: {
116 | user: 'test',
117 | },
118 | success(res) {
119 | const data = res.data
120 | expectType(data)
121 | },
122 | })
123 |
124 | uploadTask.onProgressUpdate(res => {
125 | console.log('上传进度', res.progress)
126 | console.log('已经上传的数据长度', res.totalBytesSent)
127 | console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
128 | })
129 |
130 | uploadTask.abort() // 取消上传任务
131 | }
132 |
133 | // Test case from `Worker.postMessage`
134 | {
135 | const worker = wx.createWorker('workers/request/index.js') // 文件名指定 worker 的入口文件路径,绝对路径
136 | worker.postMessage({
137 | msg: 'hello from worker',
138 | })
139 | }
140 |
141 | // Test case from `wx.createWorker`
142 | {
143 | // 创建普通worker
144 | wx.createWorker('workers/index.js')
145 | }
146 |
147 | // Test case from `wx.createWorker`
148 | {
149 | // 创建实验worker
150 | const worker = wx.createWorker('workers/index.js', {
151 | useExperimentalWorker: true,
152 | })
153 |
154 | // 监听worker被系统回收事件
155 | worker.onProcessKilled(() => {
156 | // 重新创建一个worker
157 | wx.createWorker('workers/index.js', {
158 | useExperimentalWorker: true,
159 | })
160 | })
161 | }
162 |
163 | // Test case from `Worker`
164 | {
165 | const worker = wx.createWorker('workers/request/index.js') // 文件名指定 worker 的入口文件路径,绝对路径
166 |
167 | worker.onMessage(function(res) {
168 | console.log(res)
169 | })
170 |
171 | // 监听worker被系统回收事件
172 | worker.onProcessKilled(function () {
173 | console.log('worker has been killed')
174 | // 重新创建一个worker
175 | // wx.createWorker()
176 | })
177 |
178 | worker.postMessage({
179 | msg: 'hello worker',
180 | })
181 |
182 | worker.terminate()
183 | }
184 |
185 | // Test case from `wx.addCard`
186 | {
187 | wx.addCard({
188 | cardList: [
189 | {
190 | cardId: '',
191 | cardExt: '{"code": "", "openid": "", "timestamp": "", "signature":""}',
192 | },
193 | {
194 | cardId: '',
195 | cardExt: '{"code": "", "openid": "", "timestamp": "", "signature":""}',
196 | },
197 | ],
198 | success(res) {
199 | console.log(res.cardList) // 卡券添加结果
200 | },
201 | })
202 | }
203 |
204 | // Test case from `wx.authorize`
205 | {
206 | wx.getSetting({
207 | success(res) {
208 | if (!res.authSetting['scope.werun']) {
209 | wx.authorize({
210 | scope: 'scope.werun',
211 | success() {},
212 | })
213 | }
214 | },
215 | })
216 | }
217 |
218 | // Test case from `wx.checkSession`
219 | {
220 | wx.checkSession({
221 | success() {
222 | // session_key 未过期,并且在本生命周期一直有效
223 | },
224 | fail() {
225 | // session_key 已经失效,需要重新执行登录流程
226 | wx.login() // 重新登录
227 | },
228 | })
229 | }
230 |
231 | // Test case from `wx.clearStorageSync`
232 | {
233 | wx.clearStorage()
234 | }
235 |
236 | // Test case from `wx.clearStorage`
237 | {
238 | wx.clearStorage()
239 | }
240 |
241 | // Test case from `wx.closeSocket`
242 | {
243 | wx.connectSocket({
244 | url: 'test.php',
245 | })
246 |
247 | // 注意这里有时序问题,
248 | // 如果 wx.connectSocket 还没回调 wx.onSocketOpen,而先调用 wx.closeSocket,那么就做不到关闭 WebSocket 的目的。
249 | // 必须在 WebSocket 打开期间调用 wx.closeSocket 才能关闭。
250 | wx.onSocketOpen(function() {
251 | wx.closeSocket()
252 | })
253 |
254 | wx.onSocketClose(function() {
255 | console.log('WebSocket 已关闭!')
256 | })
257 | }
258 |
259 | // Test case from `wx.connectSocket`
260 | {
261 | wx.connectSocket({
262 | url: 'wss://example.qq.com',
263 | header: {
264 | 'content-type': 'application/json',
265 | },
266 | protocols: ['protocol1'],
267 | })
268 | }
269 |
270 | // Test case from `wx.downloadFile`
271 | {
272 | wx.downloadFile({
273 | url: 'https://example.com/audio/123', // 仅为示例,并非真实的资源
274 | success(res) {
275 | // 只要服务器有响应数据,就会把响应内容写入文件并进入 success 回调,业务需要自行判断是否下载到了想要的内容
276 | if (res.statusCode === 200) {
277 | }
278 | },
279 | })
280 | }
281 |
282 | // Test case from `wx.getClipboardData`
283 | {
284 | wx.getClipboardData({
285 | success(res) {
286 | console.log(res.data)
287 | },
288 | })
289 | }
290 |
291 | // Test case from `wx.getLogManager`
292 | {
293 | const logger = wx.getLogManager({ level: 1 })
294 | logger.log({ str: 'hello world' }, 'basic log', 100, [1, 2, 3])
295 | logger.info({ str: 'hello world' }, 'info log', 100, [1, 2, 3])
296 | logger.debug({ str: 'hello world' }, 'debug log', 100, [1, 2, 3])
297 | logger.warn({ str: 'hello world' }, 'warn log', 100, [1, 2, 3])
298 | }
299 |
300 | // Test case from `wx.getNetworkType`
301 | {
302 | wx.getNetworkType({
303 | success(res) {
304 | expectType<'wifi' | '2g' | '3g' | '4g' | '5g' | 'unknown' | 'none'>(
305 | res.networkType,
306 | )
307 | },
308 | })
309 | }
310 |
311 | // Test case from `wx.getSetting`
312 | {
313 | wx.getSetting({
314 | success(res) {
315 | console.log(res.authSetting)
316 | res.authSetting = {
317 | 'scope.userInfo': true,
318 | 'scope.userLocation': true,
319 | }
320 | },
321 | })
322 | }
323 |
324 | // Test case from `wx.getStorageInfoSync`
325 | {
326 | wx.getStorageInfo({
327 | success(res) {
328 | console.log(res.keys)
329 | console.log(res.currentSize)
330 | console.log(res.limitSize)
331 | },
332 | })
333 | }
334 |
335 | // Test case from `wx.getStorageInfo`
336 | {
337 | wx.getStorageInfo({
338 | success(res) {
339 | console.log(res.keys)
340 | console.log(res.currentSize)
341 | console.log(res.limitSize)
342 | },
343 | })
344 | }
345 |
346 | // Test case from `wx.getStorageSync`
347 | {
348 | wx.getStorage({
349 | key: 'key',
350 | success(res) {
351 | console.log(res.data)
352 | },
353 | })
354 | }
355 |
356 | // Test case from `wx.getStorage`
357 | {
358 | wx.getStorage({
359 | key: 'key',
360 | success(res) {
361 | console.log(res.data)
362 | },
363 | })
364 | }
365 |
366 | // Test case from `wx.getSystemInfoSync`
367 | {
368 | wx.getSystemInfo({
369 | success(res) {
370 | console.log(res.model)
371 | console.log(res.pixelRatio)
372 | console.log(res.windowWidth)
373 | console.log(res.windowHeight)
374 | console.log(res.language)
375 | console.log(res.version)
376 | console.log(res.platform)
377 | },
378 | })
379 | }
380 |
381 | type TPlatform = 'ios' | 'android' | 'windows' | 'mac' | 'devtools' | 'ohos'
382 |
383 | // Test case from `wx.getSystemInfo`
384 | {
385 | wx.getSystemInfo({
386 | success(res) {
387 | expectType(res.model)
388 | expectType(res.pixelRatio)
389 | expectType(res.windowWidth)
390 | expectType(res.windowHeight)
391 | expectType(res.language)
392 | expectType(res.version)
393 | expectType(res.platform)
394 | },
395 | })
396 | }
397 |
398 | // Test case from `wx.getSystemInfoAsync`
399 | {
400 | wx.getSystemInfoAsync({
401 | success (res) {
402 | expectType(res.model)
403 | expectType(res.pixelRatio)
404 | expectType(res.windowWidth)
405 | expectType(res.windowHeight)
406 | expectType(res.language)
407 | expectType(res.version)
408 | expectType(res.platform)
409 | }
410 | })
411 | }
412 |
413 | // Test case from `wx.getUserInfo`
414 | {
415 | // 必须是在用户已经授权的情况下调用
416 | wx.getUserInfo({
417 | success(res) {
418 | const userInfo = res.userInfo
419 | expectType(userInfo.nickName)
420 | expectType(userInfo.avatarUrl)
421 | expectType<0 | 1 | 2>(userInfo.gender)
422 | expectType(userInfo.province)
423 | expectType(userInfo.city)
424 | expectType(userInfo.country)
425 | },
426 | })
427 | }
428 |
429 | // Test case from `wx.getWeRunData`
430 | {
431 | wx.getWeRunData({
432 | success(res) {
433 | // 拿 encryptedData 到开发者后台解密开放数据
434 | expectType(res.encryptedData)
435 | // 或拿 cloudID 通过云调用直接获取开放数据
436 | expectType(res.cloudID)
437 | },
438 | })
439 | }
440 |
441 | // Test case from `wx.hideShareMenu`
442 | {
443 | wx.hideShareMenu()
444 | }
445 |
446 | // Test case from `wx.hideShareMenu`
447 | {
448 | wx.hideShareMenu({
449 | menus: ['shareAppMessage', 'shareTimeline'],
450 | })
451 | }
452 |
453 | // Test case from `wx.login`
454 | {
455 | wx.login({
456 | success(res) {
457 | if (res.code) {
458 | // 发起网络请求
459 | wx.request({
460 | url: 'https://example.com/onLogin',
461 | data: {
462 | code: res.code,
463 | },
464 | })
465 | } else {
466 | console.log('登录失败!' + res.errMsg)
467 | }
468 | },
469 | })
470 | }
471 |
472 | // Test case from `wx.navigateToMiniProgram`
473 | {
474 | wx.navigateToMiniProgram({
475 | appId: '',
476 | path: 'page/index/index?id=123',
477 | extraData: {
478 | foo: 'bar',
479 | },
480 | envVersion: 'develop',
481 | success() {
482 | // 打开成功
483 | },
484 | })
485 | }
486 |
487 | // Test case from `wx.onAccelerometerChange`
488 | {
489 | wx.onAccelerometerChange(function(res) {
490 | expectType(res.x)
491 | expectType(res.y)
492 | expectType(res.z)
493 | })
494 | }
495 |
496 | // Test case from `wx.onNetworkStatusChange`
497 | {
498 | wx.onNetworkStatusChange(function(res) {
499 | expectType(res.isConnected)
500 | expectType<
501 | 'wifi' | '2g' | '3g' | '4g' | '5g' | 'unknown' | 'none'
502 | >(res.networkType)
503 | })
504 | }
505 |
506 | // Test case from `wx.onUserCaptureScreen`
507 | {
508 | wx.onUserCaptureScreen(function() {
509 | console.log('用户截屏了')
510 | })
511 | }
512 |
513 | // Test case from `wx.openCard`
514 | {
515 | wx.openCard({
516 | cardList: [
517 | {
518 | cardId: '',
519 | code: '',
520 | },
521 | {
522 | cardId: '',
523 | code: '',
524 | },
525 | ],
526 | success() {},
527 | })
528 | }
529 |
530 | // Test case from `wx.openSetting`
531 | {
532 | wx.openSetting({
533 | success(res) {
534 | console.log(res.authSetting)
535 | // res.authSetting = {
536 | // "scope.userInfo": true,
537 | // "scope.userLocation": true
538 | // }
539 | },
540 | })
541 | }
542 |
543 | // Test case from `wx.previewImage`
544 | {
545 | wx.previewImage({
546 | current: '', // 当前显示图片的http链接
547 | urls: [], // 需要预览的图片http链接列表
548 | })
549 | }
550 |
551 | // Test case from `wx.removeStorageSync`
552 | {
553 | wx.removeStorage({
554 | key: 'key',
555 | success(res) {
556 | console.log(res)
557 | },
558 | })
559 | }
560 |
561 | // Test case from `wx.removeStorage`
562 | {
563 | wx.removeStorage({
564 | key: 'key',
565 | success(res) {
566 | console.log(res)
567 | },
568 | })
569 | }
570 |
571 | // Test case from `wx.request`
572 | {
573 | wx.request({
574 | url: 'example.php', //仅为示例,并非真实的接口地址
575 | data: {
576 | x: '',
577 | y: '',
578 | },
579 | header: {
580 | 'content-type': 'application/json', // 默认值
581 | },
582 | success(res) {
583 | console.log(res.data)
584 | },
585 | })
586 | }
587 |
588 | // Test case from `wx.saveImageToPhotosAlbum`
589 | {
590 | wx.saveImageToPhotosAlbum({
591 | filePath: '',
592 | success() {},
593 | })
594 | }
595 |
596 | // Test case from `wx.sendSocketMessage`
597 | {
598 | let socketOpen = false
599 | let socketMsgQueue: string[] = []
600 | wx.connectSocket({
601 | url: 'test.php',
602 | })
603 |
604 | wx.onSocketOpen(function() {
605 | socketOpen = true
606 | socketMsgQueue.forEach(socketMsg => {
607 | sendSocketMessage(socketMsg)
608 | })
609 | socketMsgQueue = []
610 | })
611 |
612 | const sendSocketMessage = (msg: string) => {
613 | if (socketOpen) {
614 | wx.sendSocketMessage({
615 | data: msg,
616 | })
617 | } else {
618 | socketMsgQueue.push(msg)
619 | }
620 | }
621 | }
622 |
623 | // Test case from `wx.setClipboardData`
624 | {
625 | wx.setClipboardData({
626 | data: 'data',
627 | success() {
628 | wx.getClipboardData({
629 | success(res) {
630 | console.log(res.data) // data
631 | },
632 | })
633 | },
634 | })
635 | }
636 |
637 | // Test case from `wx.setKeepScreenOn`
638 | {
639 | wx.setKeepScreenOn({
640 | keepScreenOn: true,
641 | })
642 | }
643 |
644 | // Test case from `wx.setStorageSync`
645 | {
646 | wx.setStorage({
647 | key: 'key',
648 | data: 'value',
649 | })
650 | }
651 |
652 | // Test case from `wx.setStorage`
653 | {
654 | wx.setStorage({
655 | key: 'key',
656 | data: 'value',
657 | })
658 | }
659 |
660 | // Test case from `wx.showActionSheet`
661 | {
662 | wx.showActionSheet({
663 | itemList: ['A', 'B', 'C'],
664 | success(res) {
665 | console.log(res.tapIndex)
666 | },
667 | fail(res) {
668 | console.log(res.errMsg)
669 | },
670 | })
671 | }
672 |
673 | // Test case from `wx.showLoading`
674 | {
675 | wx.showLoading({
676 | title: '加载中',
677 | })
678 |
679 | setTimeout(function() {
680 | wx.hideLoading()
681 | }, 2000)
682 | }
683 |
684 | // Test case from `wx.showModal`
685 | {
686 | wx.showModal({
687 | title: '提示',
688 | content: '这是一个模态弹窗',
689 | success(res) {
690 | if (res.confirm) {
691 | console.log('用户点击确定')
692 | } else if (res.cancel) {
693 | console.log('用户点击取消')
694 | }
695 | },
696 | })
697 | }
698 |
699 | // Test case from `wx.showShareMenu`
700 | {
701 | wx.showShareMenu({
702 | withShareTicket: true,
703 | })
704 | }
705 |
706 | // Test case from `wx.showShareMenu`
707 | {
708 | wx.showShareMenu({
709 | withShareTicket: true,
710 | menus: ['shareAppMessage', 'shareTimeline'],
711 | })
712 | }
713 |
714 | // Test case from `wx.showToast`
715 | {
716 | wx.showToast({
717 | title: '成功',
718 | icon: 'success',
719 | duration: 2000,
720 | })
721 | }
722 |
723 | // Test case from `wx.startAccelerometer`
724 | {
725 | wx.startAccelerometer({
726 | interval: 'game',
727 | })
728 | }
729 |
730 | // Test case from `wx.startCompass`
731 | {
732 | wx.startCompass()
733 | }
734 |
735 | // Test case from `wx.stopAccelerometer`
736 | {
737 | wx.stopAccelerometer()
738 | }
739 |
740 | // Test case from `wx.stopCompass`
741 | {
742 | wx.stopCompass()
743 | }
744 |
745 | // Test case from `wx.updateShareMenu`
746 | {
747 | wx.updateShareMenu({
748 | withShareTicket: true,
749 | success() {},
750 | })
751 | }
752 |
753 | // Test case from `wx.uploadFile`
754 | {
755 | wx.chooseImage({
756 | success(res) {
757 | const tempFilePaths = res.tempFilePaths
758 | wx.uploadFile({
759 | url: 'https://example.weixin.qq.com/upload', // 仅为示例,非真实的接口地址
760 | filePath: tempFilePaths[0],
761 | name: 'file',
762 | formData: {
763 | user: 'test',
764 | },
765 | success(res) {
766 | expectType(res.data)
767 | },
768 | })
769 | },
770 | })
771 | }
772 |
773 | // Test case from `Worker.postMessage`
774 | {
775 | const worker = wx.createWorker('workers/request/index.js')
776 |
777 | worker.postMessage({
778 | msg: 'hello from main',
779 | })
780 | }
781 |
782 | // Test case from `wx.clearStorageSync`
783 | {
784 | try {
785 | wx.clearStorageSync()
786 | } catch (e) {
787 | // Do something when catch error
788 | }
789 | }
790 |
791 | // Test case from `wx.clearStorage`
792 | {
793 | try {
794 | wx.clearStorageSync()
795 | } catch (e) {
796 | // Do something when catch error
797 | }
798 | }
799 |
800 | // Test case from `wx.getStorageInfoSync`
801 | {
802 | try {
803 | const res = wx.getStorageInfoSync()
804 | console.log(res.keys)
805 | console.log(res.currentSize)
806 | console.log(res.limitSize)
807 | } catch (e) {
808 | // Do something when catch error
809 | }
810 | }
811 |
812 | // Test case from `wx.getStorageInfo`
813 | {
814 | try {
815 | const res = wx.getStorageInfoSync()
816 | console.log(res.keys)
817 | console.log(res.currentSize)
818 | console.log(res.limitSize)
819 | } catch (e) {
820 | // Do something when catch error
821 | }
822 | }
823 |
824 | // Test case from `wx.getStorageSync`
825 | {
826 | try {
827 | const value = wx.getStorageSync('key')
828 | if (value) {
829 | // Do something with return value
830 | }
831 | } catch (e) {
832 | // Do something when catch error
833 | }
834 | }
835 |
836 | // Test case from `wx.getStorage`
837 | {
838 | try {
839 | const value = wx.getStorageSync('key')
840 | if (value) {
841 | // Do something with return value
842 | }
843 | } catch (e) {
844 | // Do something when catch error
845 | }
846 | }
847 |
848 | // Test case from `wx.getSystemInfoSync`
849 | {
850 | try {
851 | const res = wx.getSystemInfoSync()
852 | expectType(res.model)
853 | expectType(res.pixelRatio)
854 | expectType(res.windowWidth)
855 | expectType(res.windowHeight)
856 | expectType(res.language)
857 | expectType(res.version)
858 | expectType(res.platform)
859 | } catch (e) {
860 | // Do something when catch error
861 | }
862 | }
863 |
864 | // Test case from `wx.getSystemInfo`
865 | {
866 | try {
867 | const res = wx.getSystemInfoSync()
868 | expectType(res.model)
869 | expectType(res.pixelRatio)
870 | expectType(res.windowWidth)
871 | expectType(res.windowHeight)
872 | expectType(res.language)
873 | expectType(res.version)
874 | expectType(res.platform)
875 | } catch (e) {
876 | // Do something when catch error
877 | }
878 | }
879 |
880 | // Test case from `wx.removeStorageSync`
881 | {
882 | try {
883 | wx.removeStorageSync('key')
884 | } catch (e) {
885 | // Do something when catch error
886 | }
887 | }
888 |
889 | // Test case from `wx.removeStorage`
890 | {
891 | try {
892 | wx.removeStorageSync('key')
893 | } catch (e) {
894 | // Do something when catch error
895 | }
896 | }
897 |
898 | // Test case from `wx.setStorageSync`
899 | {
900 | try {
901 | wx.setStorageSync('key', 'value')
902 | } catch (e) {}
903 | }
904 |
905 | // Test case from `wx.setStorage`
906 | {
907 | try {
908 | wx.setStorageSync('key', 'value')
909 | } catch (e) {}
910 | }
911 |
912 | // Test case from `wx.setEnableDebug`
913 | {
914 | // 打开调试
915 | wx.setEnableDebug({
916 | enableDebug: true,
917 | })
918 |
919 | // 关闭调试
920 | wx.setEnableDebug({
921 | enableDebug: false,
922 | })
923 | }
924 |
925 | // Test case from `WebGLRenderingContext.wxBindCanvasTexture`
926 | {
927 | const canvas = wx.createCanvas()
928 | const gl = canvas.getContext('webgl')
929 | gl.wxBindCanvasTexture(gl.TEXTURE_2D, canvas)
930 | }
931 |
932 | // Test case from `WebGLRenderingContext.wxBindCanvasTexture`
933 | {
934 | const canvas = wx.createCanvas()
935 | const gl = canvas.getContext('webgl')
936 | const texture = gl.createTexture()
937 | gl.bindTexture(gl.TEXTURE_2D, texture)
938 |
939 | gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, canvas)
940 | }
941 |
942 | // Test case from `GameRecorder.on`
943 | {
944 | const recorder = wx.getGameRecorder()
945 | recorder.on('stop', res => {
946 | expectType(res.duration)
947 | })
948 | }
949 |
950 | // Test case from `wx.getExtConfig`
951 | {
952 | if (wx.getExtConfig) {
953 | wx.getExtConfig({
954 | success(res) {
955 | console.log(res.extConfig)
956 | },
957 | })
958 | }
959 | }
960 |
961 | // Test case from `wx.getExtConfigSync`
962 | {
963 | const extConfig = wx.getExtConfigSync ? wx.getExtConfigSync() : {}
964 | console.log(extConfig)
965 | }
966 |
967 | // Test case from `wx.chooseImage`
968 | {
969 | wx.chooseImage({
970 | count: 1,
971 | sizeType: ['original', 'compressed'],
972 | sourceType: ['album', 'camera'],
973 | success(res) {
974 | // tempFilePath可以作为img标签的src属性显示图片
975 | expectType(res.tempFilePaths)
976 | },
977 | })
978 | }
979 |
980 | // Test case from `wx.getUserInfo`
981 | {
982 | wx.getSetting({
983 | success(res) {
984 | if (res.authSetting['scope.userInfo']) {
985 | // 已经授权,可以直接调用 getUserInfo 获取头像昵称
986 | wx.getUserInfo({
987 | success(res) {
988 | console.log(res.userInfo)
989 | },
990 | })
991 | }
992 | },
993 | })
994 | }
995 |
996 | // Test case from `GameRecorder`
997 | {
998 | // 可以监听 error 事件
999 | const recorder = wx.getGameRecorder()
1000 | recorder.on('error', res => {
1001 | expectType(res.error.code)
1002 | })
1003 |
1004 | // 也可以在接口的 Promise 中获取
1005 | recorder.stop().catch(res => {
1006 | expectType(res.error.code)
1007 | })
1008 | }
1009 |
1010 | // Test case from `GameRecorder.on`
1011 | {
1012 | const recorder = wx.getGameRecorder()
1013 | recorder.on('timeUpdate', res => {
1014 | console.log(res.currentTime)
1015 | })
1016 | }
1017 |
1018 | // Test case from `GameRecorder.on`
1019 | {
1020 | const recorder = wx.getGameRecorder()
1021 | recorder.on('error', res => {
1022 | console.log('错误码', res.error.code)
1023 | console.log('错误信息', res.error.message)
1024 | })
1025 | }
1026 |
1027 | // Test case from `wx.reportMonitor`
1028 | {
1029 | wx.reportMonitor('1', 1)
1030 | }
1031 |
1032 | // Test case from `wx.startBeaconDiscovery`
1033 | {
1034 | wx.startBeaconDiscovery({
1035 | uuids: [],
1036 | success() {},
1037 | })
1038 | }
1039 |
1040 | // Test case from `wx.closeBLEConnection`
1041 | {
1042 | wx.closeBLEConnection({
1043 | deviceId: '',
1044 | success(res) {
1045 | console.log(res)
1046 | },
1047 | })
1048 | }
1049 |
1050 | // Test case from `wx.closeBluetoothAdapter`
1051 | {
1052 | wx.closeBluetoothAdapter({
1053 | success(res) {
1054 | console.log(res)
1055 | },
1056 | })
1057 | }
1058 |
1059 | // Test case from `wx.createBLEConnection`
1060 | {
1061 | wx.createBLEConnection({
1062 | // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
1063 | deviceId: '',
1064 | success(res) {
1065 | console.log(res)
1066 | },
1067 | })
1068 | }
1069 |
1070 | // Test case from `wx.getBLEDeviceCharacteristics`
1071 | {
1072 | wx.getBLEDeviceCharacteristics({
1073 | // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
1074 | deviceId: '',
1075 | // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
1076 | serviceId: '',
1077 | success(res) {
1078 | console.log('device getBLEDeviceCharacteristics:', res.characteristics)
1079 | },
1080 | })
1081 | }
1082 |
1083 | // Test case from `wx.getBLEDeviceServices`
1084 | {
1085 | wx.getBLEDeviceServices({
1086 | // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
1087 | deviceId: '',
1088 | success(res) {
1089 | console.log('device services:', res.services)
1090 | },
1091 | })
1092 | }
1093 |
1094 | // Test case from `wx.getBluetoothAdapterState`
1095 | {
1096 | wx.getBluetoothAdapterState({
1097 | success(res) {
1098 | console.log(res)
1099 | },
1100 | })
1101 | }
1102 |
1103 | // Test case from `wx.getBluetoothDevices`
1104 | {
1105 | wx.getBluetoothDevices({
1106 | success(res) {
1107 | console.log(res)
1108 | if (res.devices[0]) {
1109 | expectType(res.devices[0].advertisData)
1110 | }
1111 | },
1112 | })
1113 | }
1114 |
1115 | // Test case from `wx.getConnectedBluetoothDevices`
1116 | {
1117 | wx.getConnectedBluetoothDevices({
1118 | services: [],
1119 | success(res) {
1120 | expectType(res.devices)
1121 | },
1122 | })
1123 | }
1124 |
1125 | // Test case from `wx.notifyBLECharacteristicValueChange`
1126 | {
1127 | wx.notifyBLECharacteristicValueChange({
1128 | state: true, // 启用 notify 功能
1129 | // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
1130 | deviceId: '',
1131 | // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
1132 | serviceId: '',
1133 | // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
1134 | characteristicId: '',
1135 | success(res) {
1136 | console.log('notifyBLECharacteristicValueChange success', res.errMsg)
1137 | },
1138 | })
1139 | }
1140 |
1141 | // Test case from `wx.onBLECharacteristicValueChange`
1142 | {
1143 | wx.onBLECharacteristicValueChange(function(res) {
1144 | console.log(
1145 | `characteristic ${res.characteristicId} has changed, now is ${res.value}`,
1146 | )
1147 | expectType(res.value)
1148 | })
1149 | }
1150 |
1151 | // Test case from `wx.onBLEConnectionStateChange`
1152 | {
1153 | wx.onBLEConnectionStateChange(function(res) {
1154 | // 该方法回调中可以用于处理连接意外断开等异常情况
1155 | console.log(
1156 | `device ${res.deviceId} state has changed, connected: ${res.connected}`,
1157 | )
1158 | })
1159 | }
1160 |
1161 | // Test case from `wx.onBluetoothAdapterStateChange`
1162 | {
1163 | wx.onBluetoothAdapterStateChange(function(res) {
1164 | console.log('adapterState changed, now is', res)
1165 | })
1166 | }
1167 |
1168 | // Test case from `wx.onBluetoothDeviceFound`
1169 | {
1170 | wx.onBluetoothDeviceFound(function(res) {
1171 | const devices = res.devices
1172 | console.log('new device list has founded')
1173 | expectType(devices[0].advertisData)
1174 | })
1175 | }
1176 |
1177 | // Test case from `wx.openBluetoothAdapter`
1178 | {
1179 | wx.openBluetoothAdapter({
1180 | success(res) {
1181 | console.log(res)
1182 | },
1183 | })
1184 | }
1185 |
1186 | // Test case from `wx.readBLECharacteristicValue`
1187 | {
1188 | // 必须在这里的回调才能获取
1189 | wx.onBLECharacteristicValueChange(function(characteristic) {
1190 | console.log('characteristic value comed:', characteristic)
1191 | })
1192 |
1193 | wx.readBLECharacteristicValue({
1194 | // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
1195 | deviceId: '',
1196 | // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
1197 | serviceId: '',
1198 | // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
1199 | characteristicId: '',
1200 | success(res) {
1201 | console.log('readBLECharacteristicValue:', res.errCode)
1202 | },
1203 | })
1204 | }
1205 |
1206 | // Test case from `wx.startBluetoothDevicesDiscovery`
1207 | {
1208 | // 以微信硬件平台的蓝牙智能灯为例,主服务的 UUID 是 FEE7。传入这个参数,只搜索主服务 UUID 为 FEE7 的设备
1209 | wx.startBluetoothDevicesDiscovery({
1210 | services: ['FEE7'],
1211 | success(res) {
1212 | console.log(res)
1213 | },
1214 | })
1215 | }
1216 |
1217 | // Test case from `wx.stopBluetoothDevicesDiscovery`
1218 | {
1219 | wx.stopBluetoothDevicesDiscovery({
1220 | success(res) {
1221 | console.log(res)
1222 | },
1223 | })
1224 | }
1225 |
1226 | // Test case from `wx.writeBLECharacteristicValue`
1227 | {
1228 | // 向蓝牙设备发送一个0x00的16进制数据
1229 | const buffer = new ArrayBuffer(1)
1230 | const dataView = new DataView(buffer)
1231 | dataView.setUint8(0, 0)
1232 |
1233 | wx.writeBLECharacteristicValue({
1234 | // 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
1235 | deviceId: '',
1236 | // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
1237 | serviceId: '',
1238 | // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
1239 | characteristicId: '',
1240 | // 这里的value是ArrayBuffer类型
1241 | value: buffer,
1242 | success(res) {
1243 | console.log('writeBLECharacteristicValue success', res.errMsg)
1244 | },
1245 | })
1246 | }
1247 |
1248 | // Test case from `wx.requestSubscribeMessage`
1249 | {
1250 | wx.requestSubscribeMessage({
1251 | tmplIds: [''],
1252 | success(res) {
1253 | expectType(res.TEMPLATE_ID)
1254 | },
1255 | })
1256 | }
1257 |
1258 | // Test case from `wx.requestSubscribeSystemMessage`
1259 | {
1260 | wx.requestSubscribeSystemMessage({
1261 | msgTypeList: ['SYS_MSG_TYPE_INTERACTIVE', 'SYS_MSG_TYPE_RANK'],
1262 | success(res) {
1263 | expectType(res.errMsg)
1264 | },
1265 | })
1266 | }
1267 |
1268 | // Test case from `wx.getSetting`
1269 | {
1270 | wx.getSetting({
1271 | success(res) {
1272 | expectType(res.authSetting['scope.userInfo'])
1273 | expectType(res.subscriptionsSetting.mainSwitch)
1274 | expectType | undefined>(res.subscriptionsSetting.itemSettings)
1275 | },
1276 | })
1277 | }
1278 |
1279 | // Test case from `SubscriptionsSetting`
1280 | {
1281 | wx.getSetting({
1282 | withSubscriptions: true,
1283 | success(res) {
1284 | expectType(res.authSetting['scope.userInfo'])
1285 | expectType(res.authSetting['scope.userLocation'])
1286 | expectType(res.subscriptionsSetting.mainSwitch)
1287 | if (res.subscriptionsSetting.itemSettings !== undefined) {
1288 | expectType(res.subscriptionsSetting.itemSettings.SYS_MSG_TYPE_INTERACTIVE)
1289 | }
1290 | },
1291 | })
1292 | }
1293 |
1294 | // Test case from `wx.reportPerformance`
1295 | {
1296 | wx.reportPerformance(1101, 680)
1297 | }
1298 |
1299 | // Test case from `wx.getAccountInfoSync`
1300 | {
1301 | const accountInfo = wx.getAccountInfoSync()
1302 | // 小程序 appId
1303 | expectType(accountInfo.miniProgram.appId)
1304 | // 插件 appId
1305 | expectType(accountInfo.plugin.appId)
1306 | // 插件版本号, 'a.b.c' 这样的形式
1307 | expectType(accountInfo.plugin.version)
1308 | }
1309 |
1310 | // Test case from `wx.reportPerformance`
1311 | {
1312 | wx.reportPerformance(1101, 680)
1313 | wx.reportPerformance(1101, 680, 'custom')
1314 | }
1315 |
1316 | // Test case from `wx.hideShareMenu`
1317 | {
1318 | wx.hideShareMenu({
1319 | menus: ['shareAppMessage', 'shareTimeline'],
1320 | })
1321 | }
1322 |
1323 | // Test case from `wx.showShareMenu`
1324 | {
1325 | wx.showShareMenu({
1326 | withShareTicket: true,
1327 | menus: ['shareAppMessage', 'shareTimeline'],
1328 | })
1329 | }
1330 |
1331 | // Test case from `wx.getRealtimeLogManager`
1332 | {
1333 | const logger = wx.getRealtimeLogManager()
1334 | logger.info({ str: 'hello world' }, 'info log', 100, [1, 2, 3])
1335 | logger.error({ str: 'hello world' }, 'error log', 100, [1, 2, 3])
1336 | logger.warn({ str: 'hello world' }, 'warn log', 100, [1, 2, 3])
1337 | }
1338 |
1339 | // Test case from `wx.getGroupEnterInfo`
1340 | {
1341 | wx.getGroupEnterInfo({
1342 | success(res) {
1343 | expectType(res.errMsg)
1344 | expectType(res.encryptedData)
1345 | expectType(res.iv)
1346 | }
1347 | })
1348 | }
1349 |
1350 | // Test case from `wx.authPrivateMessage`
1351 | {
1352 | wx.authPrivateMessage({
1353 | shareTicket: 'xxxxxx',
1354 | success(res) {
1355 | expectType(res.valid)
1356 | expectType(res.iv)
1357 | expectType(res.encryptedData)
1358 | },
1359 | fail(res) {
1360 | expectType(res.errMsg)
1361 | },
1362 | })
1363 | }
1364 |
1365 | // Test case from `wx.createMediaAudioPlayer`
1366 | {
1367 | // 创建视频解码器,具体参数见 createVideoDecoder 文档
1368 | const videoDecoder = wx.createVideoDecoder()
1369 | // 创建媒体音频播放器
1370 | const mediaAudioPlayer = wx.createMediaAudioPlayer()
1371 | // 启动视频解码器
1372 | videoDecoder.start({
1373 | source: ''
1374 | })
1375 | // 启动播放器
1376 | mediaAudioPlayer.start().then(() => {
1377 | // 添加播放器音频来源
1378 | mediaAudioPlayer.addAudioSource(videoDecoder).then(res => {
1379 | videoDecoder.getFrameData() // 建议在 requestAnimationFrame 里获取每一帧视频数据
1380 | console.log(res)
1381 | })
1382 |
1383 | // 移除播放器音频来源
1384 | mediaAudioPlayer.removeAudioSource(videoDecoder).then()
1385 | // 停止播放器
1386 | mediaAudioPlayer.stop().then()
1387 | // 销毁播放器
1388 | mediaAudioPlayer.destroy().then()
1389 | // 设置播放器音量
1390 | mediaAudioPlayer.volume = 0.5
1391 | })
1392 | }
1393 |
1394 | // Test case from `FileSystemManager.close`
1395 | {
1396 | const fs = wx.getFileSystemManager()
1397 | // 打开文件
1398 | fs.open({
1399 | filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
1400 | flag: 'a+',
1401 | success(res) {
1402 | // 关闭文件
1403 | fs.close({
1404 | fd: res.fd,
1405 | })
1406 | },
1407 | })
1408 | }
1409 |
1410 | // Test case from `FileSystemManager.closeSync`
1411 | {
1412 | const fs = wx.getFileSystemManager()
1413 | const fd = fs.openSync({
1414 | filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
1415 | flag: 'a+',
1416 | })
1417 |
1418 | // 关闭文件
1419 | fs.closeSync({ fd: fd })
1420 | }
1421 |
1422 | // Test case from `FileSystemManager.fstat`
1423 | {
1424 | const fs = wx.getFileSystemManager()
1425 | // 打开文件
1426 | fs.open({
1427 | filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
1428 | flag: 'a+',
1429 | success(res) {
1430 | // 获取文件的状态信息
1431 | fs.fstat({
1432 | fd: res.fd,
1433 | success(res) {
1434 | expectType(res.stats)
1435 | },
1436 | })
1437 | },
1438 | })
1439 | }
1440 |
1441 | // Test case from `FileSystemManager.fstatSync`
1442 | {
1443 | const fs = wx.getFileSystemManager()
1444 | const fd = fs.openSync({
1445 | filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
1446 | flag: 'a+',
1447 | })
1448 | const stats = fs.fstatSync({ fd: fd })
1449 | expectType(stats)
1450 | }
1451 |
1452 | // Test case from `FileSystemManager.ftruncate`
1453 | {
1454 | const fs = wx.getFileSystemManager()
1455 | // 打开文件
1456 | fs.open({
1457 | filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
1458 | flag: 'a+',
1459 | success(res) {
1460 | // 对文件内容进行截断操作
1461 | fs.ftruncate({
1462 | fd: res.fd,
1463 | length: 10, // 从第10个字节开始截断文件
1464 | success(res) {
1465 | console.log(res)
1466 | },
1467 | })
1468 | },
1469 | })
1470 | }
1471 |
1472 | // Test case from `FileSystemManager.ftruncateSync`
1473 | {
1474 | const fs = wx.getFileSystemManager()
1475 | const fd = fs.openSync({
1476 | filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
1477 | flag: 'a+',
1478 | })
1479 | fs.ftruncateSync({
1480 | fd: fd,
1481 | length: 10, // 从第10个字节开始截断文件
1482 | })
1483 | }
1484 |
1485 | // Test case from `FileSystemManager.open`
1486 | {
1487 | const fs = wx.getFileSystemManager()
1488 | fs.open({
1489 | filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
1490 | flag: 'a+',
1491 | success(res) {
1492 | expectType(res.fd)
1493 | },
1494 | })
1495 | }
1496 |
1497 | // Test case from `FileSystemManager.openSync`
1498 | {
1499 | const fs = wx.getFileSystemManager()
1500 | const fd = fs.openSync({
1501 | filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
1502 | flag: 'a+',
1503 | })
1504 | expectType(fd)
1505 | }
1506 |
1507 | // Test case from `FileSystemManager.read`
1508 | {
1509 | const fs = wx.getFileSystemManager()
1510 | const ab = new ArrayBuffer(1024)
1511 | // 打开文件
1512 | fs.open({
1513 | filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
1514 | flag: 'a+',
1515 | success(res) {
1516 | // 读取文件到 ArrayBuffer 中
1517 | fs.read({
1518 | fd: res.fd,
1519 | arrayBuffer: ab,
1520 | length: 10,
1521 | success(res) {
1522 | console.log(res)
1523 | },
1524 | })
1525 | },
1526 | })
1527 | }
1528 |
1529 | // Test case from `FileSystemManager.readSync`
1530 | {
1531 | const fs = wx.getFileSystemManager()
1532 | const ab = new ArrayBuffer(1024)
1533 | const fd = fs.openSync({
1534 | filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
1535 | flag: 'a+',
1536 | })
1537 | const res = fs.readSync({
1538 | fd: fd,
1539 | arrayBuffer: ab,
1540 | length: 10,
1541 | })
1542 | console.log(res)
1543 | }
1544 |
1545 | // Test case from `FileSystemManager.truncate`
1546 | {
1547 | const fs = wx.getFileSystemManager()
1548 | fs.truncate({
1549 | filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
1550 | length: 10, // 从第10个字节开始截断
1551 | success(res) {
1552 | console.log(res)
1553 | },
1554 | })
1555 | }
1556 |
1557 | // Test case from `FileSystemManager.truncateSync`
1558 | {
1559 | const fs = wx.getFileSystemManager()
1560 | fs.truncateSync({
1561 | filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
1562 | length: 10, // 从第10个字节开始截断
1563 | })
1564 | }
1565 |
1566 | // Test case from `FileSystemManager.write`
1567 | {
1568 | const fs = wx.getFileSystemManager()
1569 | // 打开文件
1570 | fs.open({
1571 | filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
1572 | flag: 'a+',
1573 | success(res) {
1574 | // 写入文件
1575 | fs.write({
1576 | fd: res.fd,
1577 | data: 'some text',
1578 | success(res) {
1579 | expectType(res.bytesWritten)
1580 | },
1581 | })
1582 | },
1583 | })
1584 | }
1585 |
1586 | // Test case from `FileSystemManager.writeSync`
1587 | {
1588 | const fs = wx.getFileSystemManager()
1589 | const fd = fs.openSync({
1590 | filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
1591 | flag: 'a+',
1592 | })
1593 | const res = fs.writeSync({
1594 | fd: fd,
1595 | data: 'some text',
1596 | })
1597 | expectType(res.bytesWritten)
1598 | }
1599 |
1600 | // Test case from `Worker.getCameraFrameData`
1601 | {
1602 | const worker = wx.createWorker('workers/index.js')
1603 |
1604 | const camera = wx.createCamera({
1605 | success() {
1606 | camera.listenFrameChange(worker)
1607 | },
1608 | })
1609 | }
1610 |
1611 | // Test case from `Worker.getCameraFrameData`
1612 | {
1613 | const worker = wx.createWorker('workers/index.js')
1614 |
1615 | const data = worker.getCameraFrameData()
1616 | console.log(data)
1617 | }
1618 |
1619 | // Test case from `FileSystemManager.access`
1620 | {
1621 | const fs = wx.getFileSystemManager()
1622 | // 判断文件/目录是否存在
1623 | fs.access({
1624 | path: `${wx.env.USER_DATA_PATH}/hello.txt`,
1625 | success(res) {
1626 | // 文件存在
1627 | console.log(res)
1628 | },
1629 | fail(res) {
1630 | // 文件不存在或其他错误
1631 | console.error(res)
1632 | }
1633 | })
1634 |
1635 | // 同步接口
1636 | try {
1637 | fs.accessSync(`${wx.env.USER_DATA_PATH}/hello.txt`)
1638 | } catch(e) {
1639 | console.error(e)
1640 | }
1641 | }
1642 |
1643 | // Test case from `FileSystemManager.accessSync`
1644 | {
1645 | const fs = wx.getFileSystemManager()
1646 | // 判断文件/目录是否存在
1647 | fs.access({
1648 | path: `${wx.env.USER_DATA_PATH}/hello.txt`,
1649 | success(res) {
1650 | // 文件存在
1651 | console.log(res)
1652 | },
1653 | fail(res) {
1654 | // 文件不存在或其他错误
1655 | console.error(res)
1656 | }
1657 | })
1658 |
1659 | // 同步接口
1660 | try {
1661 | fs.accessSync(`${wx.env.USER_DATA_PATH}/hello.txt`)
1662 | } catch(e) {
1663 | console.error(e)
1664 | }
1665 | }
1666 |
1667 | // Test case from `FileSystemManager.appendFile`
1668 | {
1669 | const fs = wx.getFileSystemManager()
1670 |
1671 | fs.appendFile({
1672 | filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
1673 | data: 'some text',
1674 | encoding: 'utf8',
1675 | success(res) {
1676 | console.log(res)
1677 | },
1678 | fail(res) {
1679 | console.error(res)
1680 | }
1681 | })
1682 |
1683 | // 同步接口
1684 | try {
1685 | fs.appendFileSync(`${wx.env.USER_DATA_PATH}/hello.txt`, 'some text', 'utf8')
1686 | } catch(e) {
1687 | console.error(e)
1688 | }
1689 | }
1690 |
1691 | // Test case from `FileSystemManager.appendFileSync`
1692 | {
1693 | const fs = wx.getFileSystemManager()
1694 |
1695 | fs.appendFile({
1696 | filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
1697 | data: 'some text',
1698 | encoding: 'utf8',
1699 | success(res) {
1700 | console.log(res)
1701 | },
1702 | fail(res) {
1703 | console.error(res)
1704 | }
1705 | })
1706 |
1707 | // 同步接口
1708 | try {
1709 | fs.appendFileSync(`${wx.env.USER_DATA_PATH}/hello.txt`, 'some text', 'utf8')
1710 | } catch(e) {
1711 | console.error(e)
1712 | }
1713 | }
1714 |
1715 | // Test case from `FileSystemManager.copyFile`
1716 | {
1717 | const fs = wx.getFileSystemManager()
1718 | fs.copyFile({
1719 | srcPath: `${wx.env.USER_DATA_PATH}/hello.txt`,
1720 | destPath: `${wx.env.USER_DATA_PATH}/hello_copy.txt`,
1721 | success(res) {
1722 | console.log(res)
1723 | },
1724 | fail(res) {
1725 | console.error(res)
1726 | }
1727 | })
1728 |
1729 | // 同步接口
1730 | try {
1731 | fs.copyFileSync(
1732 | `${wx.env.USER_DATA_PATH}/hello.txt`,
1733 | `${wx.env.USER_DATA_PATH}/hello_copy.txt`
1734 | )
1735 | } catch(e) {
1736 | console.error(e)
1737 | }
1738 | }
1739 |
1740 | // Test case from `FileSystemManager.copyFileSync`
1741 | {
1742 | const fs = wx.getFileSystemManager()
1743 | fs.copyFile({
1744 | srcPath: `${wx.env.USER_DATA_PATH}/hello.txt`,
1745 | destPath: `${wx.env.USER_DATA_PATH}/hello_copy.txt`,
1746 | success(res) {
1747 | console.log(res)
1748 | },
1749 | fail(res) {
1750 | console.error(res)
1751 | }
1752 | })
1753 |
1754 | // 同步接口
1755 | try {
1756 | fs.copyFileSync(
1757 | `${wx.env.USER_DATA_PATH}/hello.txt`,
1758 | `${wx.env.USER_DATA_PATH}/hello_copy.txt`
1759 | )
1760 | } catch(e) {
1761 | console.error(e)
1762 | }
1763 | }
1764 |
1765 | // Test case from `FileSystemManager.mkdir`
1766 | {
1767 | const fs = wx.getFileSystemManager()
1768 | fs.mkdir({
1769 | dirPath: `${wx.env.USER_DATA_PATH}/example`,
1770 | recursive: false,
1771 | success(res) {
1772 | console.log(res)
1773 | },
1774 | fail(res) {
1775 | console.error(res)
1776 | }
1777 | })
1778 |
1779 | // 同步接口
1780 | try {
1781 | fs.mkdirSync(`${wx.env.USER_DATA_PATH}/example`, false)
1782 | } catch(e) {
1783 | console.error(e)
1784 | }
1785 | }
1786 |
1787 | // Test case from `FileSystemManager.mkdirSync`
1788 | {
1789 | const fs = wx.getFileSystemManager()
1790 | fs.mkdir({
1791 | dirPath: `${wx.env.USER_DATA_PATH}/example`,
1792 | recursive: false,
1793 | success(res) {
1794 | console.log(res)
1795 | },
1796 | fail(res) {
1797 | console.error(res)
1798 | }
1799 | })
1800 |
1801 | // 同步接口
1802 | try {
1803 | fs.mkdirSync(`${wx.env.USER_DATA_PATH}/example`, false)
1804 | } catch(e) {
1805 | console.error(e)
1806 | }
1807 | }
1808 |
1809 | // Test case from `FileSystemManager.readFile`
1810 | {
1811 | const fs = wx.getFileSystemManager()
1812 | fs.readFile({
1813 | filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
1814 | encoding: 'utf8',
1815 | position: 0,
1816 | success(res) {
1817 | console.log(res.data)
1818 | },
1819 | fail(res) {
1820 | console.error(res)
1821 | }
1822 | })
1823 |
1824 | // 同步接口
1825 | try {
1826 | const res = fs.readFileSync(`${wx.env.USER_DATA_PATH}/hello.txt`, 'utf8', 0)
1827 | console.log(res)
1828 | } catch(e) {
1829 | console.error(e)
1830 | }
1831 | }
1832 |
1833 | // Test case from `FileSystemManager.readFileSync`
1834 | {
1835 | const fs = wx.getFileSystemManager()
1836 | fs.readFile({
1837 | filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
1838 | encoding: 'utf8',
1839 | position: 0,
1840 | success(res) {
1841 | console.log(res.data)
1842 | },
1843 | fail(res) {
1844 | console.error(res)
1845 | }
1846 | })
1847 |
1848 | // 同步接口
1849 | try {
1850 | const res = fs.readFileSync(`${wx.env.USER_DATA_PATH}/hello.txt`, 'utf8', 0)
1851 | console.log(res)
1852 | } catch(e) {
1853 | console.error(e)
1854 | }
1855 | }
1856 |
1857 | // Test case from `FileSystemManager.readZipEntry`
1858 | {
1859 | const fs = wx.getFileSystemManager()
1860 | // 读取zip内某个或多个文件
1861 | fs.readZipEntry({
1862 | filePath: 'wxfile://from/to.zip',
1863 | entries: [{
1864 | path: 'some_folder/my_file.txt', // zip内文件路径
1865 | encoding: 'utf-8', // 指定读取文件的字符编码,如果不传 encoding,则以 ArrayBuffer 格式读取文件的二进制内容
1866 | position: 0, // 从文件指定位置开始读,如果不指定,则从文件头开始读。读取的范围应该是左闭右开区间 [position, position+length)。有效范围:[0, fileLength - 1]。单位:byte
1867 | length: 10000, // 指定文件的长度,如果不指定,则读到文件末尾。有效范围:[1, fileLength]。单位:byte
1868 | }, {
1869 | path: 'other_folder/orther_file.txt', // zip内文件路径
1870 | }],
1871 | success(res) {
1872 | console.log(res.entries)
1873 | // res.entries === {
1874 | // 'some_folder/my_file.txt': {
1875 | // errMsg: 'readZipEntry:ok',
1876 | // data: 'xxxxxx'
1877 | // },
1878 | // 'other_folder/orther_file.txt': {
1879 | // data: (ArrayBuffer)
1880 | // }
1881 | // }
1882 | },
1883 | fail(res) {
1884 | console.log(res.errMsg)
1885 | },
1886 | })
1887 |
1888 | // 读取zip内所有文件。允许指定统一的encoding。position、length则不再允许指定,分别默认为0和文件长度
1889 | fs.readZipEntry({
1890 | filePath: 'wxfile://from/to.zip',
1891 | entries: 'all',
1892 | encoding: 'utf-8', // 统一指定读取文件的字符编码,如果不传 encoding,则以 ArrayBuffer 格式读取文件的二进制内容
1893 | success(res) {
1894 | console.log(res.entries)
1895 | // res.entries === {
1896 | // 'some_folder/my_file.txt': {
1897 | // errMsg: 'readZipEntry:ok',
1898 | // data: 'xxxxxx'
1899 | // },
1900 | // 'other_folder/orther_file.txt': {
1901 | // errMsg: 'readZipEntry:ok',
1902 | // data: 'xxxxxx'
1903 | // }
1904 | // }
1905 | },
1906 | fail(res) {
1907 | console.log(res.errMsg)
1908 | },
1909 | })
1910 | }
1911 |
1912 | // Test case from `FileSystemManager.readdir`
1913 | {
1914 | const fs = wx.getFileSystemManager()
1915 | fs.readdir({
1916 | dirPath: `${wx.env.USER_DATA_PATH}/example`,
1917 | success(res) {
1918 | console.log(res.files)
1919 | },
1920 | fail(res) {
1921 | console.error(res)
1922 | }
1923 | })
1924 |
1925 | // 同步接口
1926 | try {
1927 | const res = fs.readdirSync(`${wx.env.USER_DATA_PATH}/example`)
1928 | console.log(res)
1929 | } catch(e) {
1930 | console.error(e)
1931 | }
1932 | }
1933 |
1934 | // Test case from `FileSystemManager.readdirSync`
1935 | {
1936 | const fs = wx.getFileSystemManager()
1937 | fs.readdir({
1938 | dirPath: `${wx.env.USER_DATA_PATH}/example`,
1939 | success(res) {
1940 | console.log(res.files)
1941 | },
1942 | fail(res) {
1943 | console.error(res)
1944 | }
1945 | })
1946 |
1947 | // 同步接口
1948 | try {
1949 | const res = fs.readdirSync(`${wx.env.USER_DATA_PATH}/example`)
1950 | console.log(res)
1951 | } catch(e) {
1952 | console.error(e)
1953 | }
1954 | }
1955 |
1956 | // Test case from `FileSystemManager.rename`
1957 | {
1958 | const fs = wx.getFileSystemManager()
1959 | fs.rename({
1960 | oldPath: `${wx.env.USER_DATA_PATH}/hello.txt`,
1961 | newPath: `${wx.env.USER_DATA_PATH}/hello_new.txt`,
1962 | success(res) {
1963 | console.log(res)
1964 | },
1965 | fail(res) {
1966 | console.error(res)
1967 | }
1968 | })
1969 |
1970 | // 同步接口
1971 | try {
1972 | const res = fs.renameSync(
1973 | `${wx.env.USER_DATA_PATH}/hello.txt`,
1974 | `${wx.env.USER_DATA_PATH}/hello_new.txt`
1975 | )
1976 | console.log(res)
1977 | } catch(e) {
1978 | console.error(e)
1979 | }
1980 | }
1981 |
1982 | // Test case from `FileSystemManager.renameSync`
1983 | {
1984 | const fs = wx.getFileSystemManager()
1985 | fs.rename({
1986 | oldPath: `${wx.env.USER_DATA_PATH}/hello.txt`,
1987 | newPath: `${wx.env.USER_DATA_PATH}/hello_new.txt`,
1988 | success(res) {
1989 | console.log(res)
1990 | },
1991 | fail(res) {
1992 | console.error(res)
1993 | }
1994 | })
1995 |
1996 | // 同步接口
1997 | try {
1998 | const res = fs.renameSync(
1999 | `${wx.env.USER_DATA_PATH}/hello.txt`,
2000 | `${wx.env.USER_DATA_PATH}/hello_new.txt`
2001 | )
2002 | console.log(res)
2003 | } catch(e) {
2004 | console.error(e)
2005 | }
2006 | }
2007 |
2008 | // Test case from `FileSystemManager.rmdir`
2009 | {
2010 | const fs = wx.getFileSystemManager()
2011 | fs.rmdir({
2012 | dirPath: `${wx.env.USER_DATA_PATH}/example`,
2013 | recursive: false,
2014 | success(res) {
2015 | console.log(res)
2016 | },
2017 | fail(res) {
2018 | console.error(res)
2019 | }
2020 | })
2021 |
2022 | // 同步接口
2023 | try {
2024 | const res = fs.rmdirSync(`${wx.env.USER_DATA_PATH}/example`, false)
2025 | console.log(res)
2026 | } catch(e) {
2027 | console.error(e)
2028 | }
2029 | }
2030 |
2031 | // Test case from `FileSystemManager.rmdirSync`
2032 | {
2033 | const fs = wx.getFileSystemManager()
2034 | fs.rmdir({
2035 | dirPath: `${wx.env.USER_DATA_PATH}/example`,
2036 | recursive: false,
2037 | success(res) {
2038 | console.log(res)
2039 | },
2040 | fail(res) {
2041 | console.error(res)
2042 | }
2043 | })
2044 |
2045 | // 同步接口
2046 | try {
2047 | const res = fs.rmdirSync(`${wx.env.USER_DATA_PATH}/example`, false)
2048 | console.log(res)
2049 | } catch(e) {
2050 | console.error(e)
2051 | }
2052 | }
2053 |
2054 | // Test case from `wx.saveFileToDisk`
2055 | {
2056 | wx.saveFileToDisk({
2057 | filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
2058 | success(res) {
2059 | console.log(res)
2060 | },
2061 | fail(res) {
2062 | console.error(res)
2063 | }
2064 | })
2065 | }
2066 |
2067 | // Test case from `FileSystemManager.unlink`
2068 | {
2069 | const fs = wx.getFileSystemManager()
2070 | fs.unlink({
2071 | filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
2072 | success(res) {
2073 | console.log(res)
2074 | },
2075 | fail(res) {
2076 | console.error(res)
2077 | }
2078 | })
2079 |
2080 | // 同步接口
2081 | try {
2082 | const res = fs.unlinkSync(`${wx.env.USER_DATA_PATH}/hello.txt`)
2083 | console.log(res)
2084 | } catch(e) {
2085 | console.error(e)
2086 | }
2087 | }
2088 |
2089 | // Test case from `FileSystemManager.unlinkSync`
2090 | {
2091 | const fs = wx.getFileSystemManager()
2092 | fs.unlink({
2093 | filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
2094 | success(res) {
2095 | console.log(res)
2096 | },
2097 | fail(res) {
2098 | console.error(res)
2099 | }
2100 | })
2101 |
2102 | // 同步接口
2103 | try {
2104 | const res = fs.unlinkSync(`${wx.env.USER_DATA_PATH}/hello.txt`)
2105 | console.log(res)
2106 | } catch(e) {
2107 | console.error(e)
2108 | }
2109 | }
2110 |
2111 | // Test case from `FileSystemManager.unzip`
2112 | {
2113 | const fs = wx.getFileSystemManager()
2114 | fs.unzip({
2115 | zipFilePath: `${wx.env.USER_DATA_PATH}/example.zip`,
2116 | targetPath: '${wx.env.USER_DATA_PATH}/example',
2117 | success(res) {
2118 | console.log(res)
2119 | },
2120 | fail(res) {
2121 | console.error(res)
2122 | }
2123 | })
2124 | }
2125 |
2126 | // Test case from `FileSystemManager.writeFile`
2127 | {
2128 | const fs = wx.getFileSystemManager()
2129 | fs.writeFile({
2130 | filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
2131 | data: 'some text or arrayBuffer',
2132 | encoding: 'utf8',
2133 | success(res) {
2134 | console.log(res)
2135 | },
2136 | fail(res) {
2137 | console.error(res)
2138 | }
2139 | })
2140 |
2141 | // 同步接口
2142 | try {
2143 | const res = fs.writeFileSync(
2144 | `${wx.env.USER_DATA_PATH}/hello.txt`,
2145 | 'some text or arrayBuffer',
2146 | 'utf8'
2147 | )
2148 | console.log(res)
2149 | } catch(e) {
2150 | console.error(e)
2151 | }
2152 | }
2153 |
2154 | // Test case from `FileSystemManager.writeFileSync`
2155 | {
2156 | const fs = wx.getFileSystemManager()
2157 | fs.writeFile({
2158 | filePath: `${wx.env.USER_DATA_PATH}/hello.txt`,
2159 | data: 'some text or arrayBuffer',
2160 | encoding: 'utf8',
2161 | success(res) {
2162 | console.log(res)
2163 | },
2164 | fail(res) {
2165 | console.error(res)
2166 | }
2167 | })
2168 |
2169 | // 同步接口
2170 | try {
2171 | const res = fs.writeFileSync(
2172 | `${wx.env.USER_DATA_PATH}/hello.txt`,
2173 | 'some text or arrayBuffer',
2174 | 'utf8'
2175 | )
2176 | console.log(res)
2177 | } catch(e) {
2178 | console.error(e)
2179 | }
2180 | }
2181 |
2182 | // Test case from `UserCryptoManager.getLatestUserKey`
2183 | {
2184 | const userCryptoManager = wx.getUserCryptoManager()
2185 | userCryptoManager.getLatestUserKey({
2186 | success: res => {
2187 | const {encryptKey, iv, version, expireTime} = res
2188 | console.log(encryptKey, iv, version, expireTime)
2189 | }
2190 | })
2191 | }
2192 |
2193 | // Test case from `Worker.getCameraFrameData`
2194 | {
2195 | // game.js
2196 | const worker = wx.createWorker('workers/index.js', {
2197 | useExperimentalWorker: true
2198 | })
2199 |
2200 | const camera = wx.createCamera({
2201 | success() {
2202 | camera.listenFrameChange(worker)
2203 | }
2204 | })
2205 | }
2206 |
2207 | // Test case from `FileSystemManager.readCompressedFile`
2208 | {
2209 | const fs = wx.getFileSystemManager()
2210 |
2211 | // 异步接口
2212 | fs.readCompressedFile({
2213 | filePath: '${wx.env.USER_DATA_PATH}/hello.br',
2214 | compressionAlgorithm: 'br',
2215 | success(res) {
2216 | expectType(res.data)
2217 | },
2218 | fail(res) {
2219 | console.log('readCompressedFile fail', res)
2220 | },
2221 | })
2222 |
2223 | // 同步接口
2224 | const data = fs.readCompressedFileSync({
2225 | filePath: '${wx.env.USER_DATA_PATH}/hello.br',
2226 | compressionAlgorithm: 'br',
2227 | })
2228 | expectType(data)
2229 | }
2230 |
2231 | // Test case from `FileSystemManager.readCompressedFileSync`
2232 | {
2233 | const fs = wx.getFileSystemManager()
2234 |
2235 | // 异步接口
2236 | fs.readCompressedFile({
2237 | filePath: '${wx.env.USER_DATA_PATH}/hello.br',
2238 | compressionAlgorithm: 'br',
2239 | success(res) {
2240 | expectType(res.data)
2241 | },
2242 | fail(res) {
2243 | console.log('readCompressedFile fail', res)
2244 | },
2245 | })
2246 |
2247 | // 同步接口
2248 | try {
2249 | const data = fs.readCompressedFileSync({
2250 | filePath: '${wx.env.USER_DATA_PATH}/hello.br',
2251 | compressionAlgorithm: 'br',
2252 | })
2253 | expectType(data)
2254 | } catch (err) {
2255 | console.log(err)
2256 | }
2257 | }
2258 |
2259 | // Test case from `wx.getStorage`
2260 | {
2261 | // 开启加密存储
2262 | wx.setStorage({
2263 | key: 'key',
2264 | data: 'value',
2265 | encrypt: true, // 若开启加密存储,setStorage 和 getStorage 需要同时声明 encrypt 的值为 true
2266 | success() {
2267 | wx.getStorage({
2268 | key: 'key',
2269 | encrypt: true, // 若开启加密存储,setStorage 和 getStorage 需要同时声明 encrypt 的值为 true
2270 | success(res) {
2271 | console.log(res.data)
2272 | },
2273 | })
2274 | },
2275 | })
2276 | }
2277 |
2278 | // Test case from `wx.getStorageSync`
2279 | {
2280 | // 开启加密存储
2281 | wx.setStorage({
2282 | key: 'key',
2283 | data: 'value',
2284 | encrypt: true, // 若开启加密存储,setStorage 和 getStorage 需要同时声明 encrypt 的值为 true
2285 | success() {
2286 | wx.getStorage({
2287 | key: 'key',
2288 | encrypt: true, // 若开启加密存储,setStorage 和 getStorage 需要同时声明 encrypt 的值为 true
2289 | success(res) {
2290 | console.log(res.data)
2291 | },
2292 | })
2293 | },
2294 | })
2295 | }
2296 |
2297 | // Test case from `wx.setStorage`
2298 | {
2299 | // 开启加密存储
2300 | wx.setStorage({
2301 | key: 'key',
2302 | data: 'value',
2303 | encrypt: true, // 若开启加密存储,setStorage 和 getStorage 需要同时声明 encrypt 的值为 true
2304 | success() {
2305 | wx.getStorage({
2306 | key: 'key',
2307 | encrypt: true, // 若开启加密存储,setStorage 和 getStorage 需要同时声明 encrypt 的值为 true
2308 | success(res) {
2309 | console.log(res.data)
2310 | },
2311 | })
2312 | },
2313 | })
2314 | }
2315 |
2316 | // Test case from `wx.setStorageSync`
2317 | {
2318 | // 开启加密存储
2319 | wx.setStorage({
2320 | key: 'key',
2321 | data: 'value',
2322 | encrypt: true, // 若开启加密存储,setStorage 和 getStorage 需要同时声明 encrypt 的值为 true
2323 | success() {
2324 | wx.getStorage({
2325 | key: 'key',
2326 | encrypt: true, // 若开启加密存储,setStorage 和 getStorage 需要同时声明 encrypt 的值为 true
2327 | success(res) {
2328 | console.log(res.data)
2329 | },
2330 | })
2331 | },
2332 | })
2333 | }
2334 |
2335 | // Test case from `wx.getLocalIPAddress`
2336 | {
2337 | wx.getLocalIPAddress({
2338 | success(res) {
2339 | const localip = res.localip
2340 | expectType(localip)
2341 | },
2342 | })
2343 | }
2344 |
2345 | // Test case from `wx.onNetworkWeakChange`
2346 | {
2347 | wx.onNetworkWeakChange(function (res) {
2348 | console.log(res.weakNet)
2349 | console.log(res.networkType)
2350 | })
2351 | // 取消监听
2352 | wx.offNetworkWeakChange()
2353 | }
2354 |
2355 | // Test case from `VideoDecoder`
2356 | (async function () {
2357 | const decoder = wx.createVideoDecoder()
2358 | // 启动 videoDecoder
2359 | await new Promise(resolve => {
2360 | decoder.on('start', resolve)
2361 | decoder.start({
2362 | source: 'http://...',
2363 | abortAudio: true, // 不需要音频
2364 | })
2365 | })
2366 | })
2367 |
2368 | // Test case from `wx.getMenuButtonBoundingClientRect`
2369 | {
2370 | const res = wx.getMenuButtonBoundingClientRect()
2371 |
2372 | console.log(res.width)
2373 | console.log(res.height)
2374 | console.log(res.top)
2375 | console.log(res.right)
2376 | console.log(res.bottom)
2377 | console.log(res.left)
2378 | }
2379 |
2380 | // Test case from `wx.onKeyboardHeightChange`
2381 | {
2382 | wx.onKeyboardHeightChange(res => {
2383 | console.log(res.height)
2384 | })
2385 | }
2386 |
2387 | // Test case from `wx.createWorker`
2388 | {
2389 | const createNewWorker = function () {
2390 | const worker = wx.createWorker('workers/index.js', {
2391 | useExperimentalWorker: true,
2392 | })
2393 | // 监听worker被系统回收事件
2394 | worker.onProcessKilled(() => {
2395 | // 重新创建一个worker
2396 | createNewWorker()
2397 | })
2398 | }
2399 | // 创建实验worker
2400 | createNewWorker()
2401 | }
2402 |
2403 | // Test case from `wx.createBLEConnection`
2404 | {
2405 | wx.createBLEConnection({
2406 | deviceId: '',
2407 | success(res) {
2408 | console.log(res)
2409 | },
2410 | })
2411 | }
2412 |
2413 | // Test case from `wx.getBLEMTU`
2414 | {
2415 | wx.getBLEMTU({
2416 | deviceId: '',
2417 | writeType: 'write',
2418 | success(res) {
2419 | console.log(res)
2420 | },
2421 | })
2422 | }
2423 |
2424 | // Test case from `wx.onBLEMTUChange`
2425 | {
2426 | wx.onBLEMTUChange(function (res) {
2427 | console.log('bluetooth mtu is', res.mtu)
2428 | })
2429 | }
2430 |
2431 | // Test case from `wx.requestMidasFriendPayment`
2432 | {
2433 | wx.requestMidasFriendPayment({
2434 | mode: 'game',
2435 | buyQuantity: 1,
2436 | currencyType: 'CNY',
2437 | env: 0,
2438 | nonceStr: '',
2439 | offerId: '',
2440 | outTradeNo: '',
2441 | platform: 'android',
2442 | signature: '',
2443 | timeStamp: 0,
2444 | zoneId: '',
2445 | success(res) {
2446 | expectType(res.encryptedData)
2447 | expectType(res.errMsg)
2448 | expectType(res.iv)
2449 | },
2450 | fail() {
2451 | }
2452 | })
2453 | }
2454 |
2455 | // Test case from `WebAudioContext`
2456 | {
2457 | // 监听状态
2458 | const audioCtx = wx.createWebAudioContext()
2459 | audioCtx.onstatechange = () => {
2460 | expectType(audioCtx.state)
2461 | }
2462 | setTimeout(audioCtx.suspend, 1000)
2463 | setTimeout(audioCtx.resume, 2000)
2464 | }
2465 |
2466 | // Test case from `WebAudioContext.close`
2467 | {
2468 | const audioCtx = wx.createWebAudioContext()
2469 | audioCtx.close().then(() => {
2470 | console.log(audioCtx.state) // bad case:不应该在close后再访问state
2471 | })
2472 | }
2473 |
2474 | // Test case from `WebAudioContext.createPeriodicWave`
2475 | {
2476 | const audioCtx = wx.createWebAudioContext()
2477 |
2478 | const real = new Float32Array(2)
2479 | const imag = new Float32Array(2)
2480 | real[0] = 0
2481 | imag[0] = 0
2482 | real[1] = 1
2483 | imag[1] = 0
2484 |
2485 | audioCtx.createPeriodicWave(real, imag, {
2486 | disableNormalization: true,
2487 | })
2488 | }
2489 |
2490 | // Test case from `wx.chooseMedia`
2491 | {
2492 | wx.chooseMedia({
2493 | count: 9,
2494 | mediaType: ['image','video'],
2495 | sourceType: ['album', 'camera'],
2496 | maxDuration: 30,
2497 | camera: 'back',
2498 | success(res) {
2499 | expectType(res.tempFiles[0].tempFilePath)
2500 | expectType(res.tempFiles[0].size)
2501 | }
2502 | })
2503 | }
2504 |
2505 | // Test case from `wx.chooseMessageFile`
2506 | {
2507 | wx.chooseMessageFile({
2508 | count: 10,
2509 | type: 'image',
2510 | success (res) {
2511 | // tempFilePath可以作为img标签的src属性显示图片
2512 | const tempFilePaths = res.tempFiles
2513 | expectType(tempFilePaths)
2514 | }
2515 | })
2516 | }
--------------------------------------------------------------------------------
/test/api-promisify.test.ts:
--------------------------------------------------------------------------------
1 | import { expectType } from 'tsd'
2 |
3 | // call with callback
4 | wx.requestMidasPayment({
5 | currencyType: 'CNY',
6 | mode: 'game',
7 | offerId: '',
8 | outTradeNo: '',
9 | success(res) {
10 | expectType(res)
11 | },
12 | })
13 | wx.stopAccelerometer({
14 | fail(res) {
15 | expectType(res)
16 | },
17 | })
18 |
19 | wx.stopCompass({
20 | complete(res) {
21 | expectType(res)
22 | },
23 | })
24 |
25 | // call with Promise.prototype.then
26 | wx.requestMidasPayment({
27 | currencyType: 'CNY',
28 | mode: 'game',
29 | offerId: '',
30 | outTradeNo: '',
31 | }).then(res => {
32 | expectType(res)
33 | })
34 | wx.stopAccelerometer().then(res => {
35 | expectType(res)
36 | })
37 | wx.stopCompass().then(res => {
38 | expectType(res)
39 | })
40 |
41 | // call with await
42 | async () => {
43 | expectType(
44 | await wx.requestMidasPayment({
45 | currencyType: 'CNY',
46 | mode: 'game',
47 | offerId: '',
48 | outTradeNo: '',
49 | }),
50 | )
51 | expectType(
52 | await wx.stopAccelerometer(),
53 | )
54 | expectType(await wx.stopCompass())
55 | }
56 |
--------------------------------------------------------------------------------
/test/game.test.ts:
--------------------------------------------------------------------------------
1 | import { expectType } from 'tsd'
2 |
3 | const canvas = wx.createCanvas()
4 | const context = canvas.getContext('2d') // 创建一个 2d context
5 | context.fillStyle = '#1aad19' // 矩形颜色
6 | context.fillRect(0, 0, 100, 100) // 矩形左上角顶点为(0, 0),右下角顶点为(100, 100)
7 | context.fillRect(canvas.width / 2 - 50, 0, 100, 100)
8 | function drawRect(x: number, y: number) {
9 | context.clearRect(x, y - 1, 100, 100)
10 | context.fillRect(x, y, 100, 100)
11 | }
12 | drawRect(canvas.width / 2 - 50, 0)
13 | const rectX = canvas.width / 2 - 50
14 | let rectY = 0
15 | setInterval(function() {
16 | drawRect(rectX, rectY++)
17 | }, 16)
18 | const image = wx.createImage()
19 | const imgX = canvas.width / 2 - 50
20 | const imgY = 500
21 | image.onload = function() {
22 | context.drawImage(image, imgX, imgY)
23 | }
24 | image.src = 'img/plane.png'
25 |
26 | // 存储当前飞机左上角坐标
27 | let touchX = imgX
28 | let touchY = imgY
29 | wx.onTouchMove(function(res) {
30 | context.clearRect(touchX, touchY, 100, 100) // 清除画布上原有的飞机
31 | touchX = res.changedTouches[0].clientX // 重新判断当前触摸点x坐标
32 | touchY = res.changedTouches[0].clientY // 重新判断当前触摸点x坐标
33 | context.drawImage(image, touchX, touchY)
34 | if (
35 | touchX >= rectX - 100 &&
36 | touchX <= rectX + 100 &&
37 | touchY >= rectY - 100 &&
38 | touchY <= rectY + 100
39 | ) {
40 | // 飞机与矩形发生碰撞
41 | wx.showModal({
42 | title: '提示',
43 | content: '发生碰撞,游戏结束!',
44 | })
45 | }
46 | })
47 |
48 | // common.js
49 | function sayHello(name: string) {
50 | console.log(`Hello ${name} !`)
51 | }
52 | function sayGoodbye(name: string) {
53 | console.log(`Goodbye ${name} !`)
54 | }
55 |
56 | module.exports.sayHello = sayHello
57 | exports.sayGoodbye = sayGoodbye
58 |
59 | GameGlobal.globalData = 1
60 |
61 | console.log(GameGlobal.globalData) // 输出 "1"
62 |
63 | const updateManager = wx.getUpdateManager()
64 |
65 | updateManager.onCheckForUpdate(function(res) {
66 | // 请求完新版本信息的回调
67 | console.log(res.hasUpdate)
68 | })
69 |
70 | updateManager.onUpdateReady(function() {
71 | wx.showModal({
72 | title: '更新提示',
73 | content: '新版本已经准备好,是否重启应用?',
74 | success(res) {
75 | if (res.confirm) {
76 | // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
77 | updateManager.applyUpdate()
78 | }
79 | },
80 | })
81 | })
82 |
83 | updateManager.onUpdateFailed(function() {
84 | // 新版本下载失败
85 | })
86 |
87 | const fs = wx.getFileSystemManager()
88 | wx.chooseImage({
89 | success(res) {
90 | expectType(res.tempFilePaths) // tempFilePaths 的每一项是一个本地临时文件路径
91 | },
92 | })
93 | fs.saveFile({
94 | tempFilePath: '', // 传入一个本地临时文件路径
95 | success(res) {
96 | console.log(res.savedFilePath) // res.savedFilePath 为一个本地缓存文件路径
97 | },
98 | })
99 | // 在本地用户文件目录下创建一个文件 hello.txt,写入内容 "hello, world"
100 | fs.writeFileSync(`${wx.env.USER_DATA_PATH}/hello.txt`, 'hello, world', 'utf8')
101 |
102 | const url = 'https://developers.weixin.qq.com'
103 | const audio = wx.createInnerAudioContext()
104 | audio.src = url // src 可以设置 http(s) 的路径,本地文件路径或者代码包文件路径
105 | audio.play()
106 | audio.obeyMuteSwitch = false
107 |
108 | const bgm = wx.createInnerAudioContext()
109 | bgm.autoplay = true
110 | bgm.loop = true
111 | bgm.src = url
112 |
113 | wx.onShow(function() {
114 | bgm.play()
115 | })
116 |
117 | wx.onAudioInterruptionEnd(function() {
118 | bgm.play()
119 | })
120 |
121 | wx.onAudioInterruptionBegin(function() {
122 | // 暂停游戏
123 | })
124 |
125 | const src =
126 | 'http://wxsnsdy.tc.qq.com/105/20210/snsdyvideodownload?filekey=30280201010421301f0201690402534804102ca905ce620b1241b726bc41dcff44e00204012882540400&bizid=1023&hy=SH&fileparam=302c020101042530230204136ffd93020457e3c4ff02024ef202031e8d7f02030f42400204045a320a0201000400'
127 |
128 | const video = wx.createVideo({
129 | x: 10,
130 | y: 76,
131 | width: 300,
132 | height: 200,
133 | poster: '',
134 | // 显示默认的视频控件
135 | controls: true,
136 | // 传入
137 | src,
138 | })
139 |
140 | video.play()
141 | video.pause()
142 | video.seek(10)
143 |
144 | video.onTimeUpdate(res => {
145 | expectType(res.position) // 当前进度
146 | expectType(res.duration) // 视频总时长
147 | })
148 |
149 | video.onEnded(() => {
150 | console.log('视频播放完了')
151 | })
152 |
153 | {
154 | const callback = (res: WechatMinigame.OnTimeUpdateListenerResult) => {
155 | expectType(res.position) // 当前进度
156 | expectType(res.duration) // 视频总时长
157 |
158 | // 当播放到第 3 秒时,调用 off* 接口取消对该事件的监听,callback 函数将不再执行
159 | if (res.position >= 3) {
160 | // video.offTimeUpdate(callback)
161 | }
162 | }
163 |
164 | video.onTimeUpdate(callback)
165 | }
166 |
167 | video.onTimeUpdate(res => {
168 | expectType(res.position) // 当前进度
169 | expectType(res.duration) // 视频总时长
170 | })
171 |
172 | video.play()
173 |
174 | video.destroy()
175 |
176 | const loadTask = wx.loadSubpackage({
177 | name: 'stage1', // name 可以填 name 或者 root
178 | success() {
179 | // 分包加载成功后通过 success 回调
180 | },
181 | fail() {
182 | // 分包加载失败通过 fail 回调
183 | },
184 | complete() {},
185 | })
186 |
187 | loadTask.onProgressUpdate(res => {
188 | expectType(res.progress) // 下载进度
189 | expectType(res.totalBytesWritten) // 已经下载的数据长度
190 | expectType(res.totalBytesExpectedToWrite) // 预期需要下载的数据总长度
191 | })
192 |
193 | const worker = wx.createWorker('workers/request/index.js') // 文件名指定 worker 的入口文件路径,绝对路径
194 |
195 | worker.postMessage({
196 | msg: 'hello worker',
197 | })
198 |
199 | const bannerAd = wx.createBannerAd({
200 | adUnitId: 'xxxx',
201 | style: {
202 | left: 10,
203 | top: 76,
204 | width: 320,
205 | height: 0,
206 | },
207 | adIntervals: 30, // 自动刷新频率不能小于30秒
208 | })
209 | bannerAd.show()
210 | bannerAd.hide()
211 | bannerAd.onError(err => {
212 | console.log(err)
213 | })
214 | bannerAd.show().catch(err => console.log(err))
215 | bannerAd.onLoad(() => {
216 | console.log('banner 广告加载成功')
217 | })
218 | bannerAd.show().then(() => console.log('banner 广告显示'))
219 | bannerAd.style.width = 400
220 | const { screenWidth } = wx.getSystemInfoSync()
221 | expectType(screenWidth)
222 | bannerAd.onResize(res => {
223 | console.log(res.width, res.height)
224 | console.log(bannerAd.style.realWidth, bannerAd.style.realHeight)
225 | })
226 | bannerAd.onResize(res => {
227 | bannerAd.style.width = res.width + Math.random() * 10
228 | })
229 | bannerAd.destroy()
230 |
231 | const video1 = wx.createRewardedVideoAd({ adUnitId: 'xxxx' })
232 | const video2 = wx.createRewardedVideoAd({ adUnitId: 'xxxx' })
233 | console.log(video1 === video2)
234 |
235 | const rewardedVideoAd = wx.createRewardedVideoAd({ adUnitId: 'xxxx' })
236 | rewardedVideoAd.onLoad(() => {
237 | console.log('激励视频 广告加载成功')
238 | })
239 |
240 | rewardedVideoAd.show().then(() => console.log('激励视频 广告显示'))
241 |
242 | rewardedVideoAd.onError(err => {
243 | console.log(err)
244 | })
245 | rewardedVideoAd.show().catch(err => console.log(err))
246 |
247 | rewardedVideoAd.show().catch(() => {
248 | rewardedVideoAd.load().then(() => rewardedVideoAd.show())
249 | })
250 |
251 | const interstitialAd = wx.createInterstitialAd({ adUnitId: 'xxxx' })
252 |
253 | interstitialAd.show().catch(err => {
254 | console.error(err)
255 | })
256 | interstitialAd.onLoad(() => {
257 | console.log('插屏 广告加载成功')
258 | })
259 | interstitialAd.onError(err => {
260 | console.log(err)
261 | })
262 | interstitialAd.onClose(() => {
263 | console.log('插屏 广告关闭')
264 | })
265 |
266 | wx.onShareAppMessage(function() {
267 | // 用户点击了“转发”按钮
268 | return {
269 | title: '转发标题',
270 | }
271 | })
272 |
273 | wx.shareAppMessage({
274 | title: '转发标题',
275 | })
276 |
277 | wx.onShareAppMessage(function() {
278 | return {
279 | title: '转发标题',
280 | imageUrl: canvas.toTempFilePathSync({
281 | destWidth: 500,
282 | destHeight: 400,
283 | }),
284 | }
285 | })
286 |
287 | const id = ''
288 | wx.shareAppMessage({
289 | imageUrlId: id, // 通过 MP 系统审核的图片编号
290 | imageUrl: url, // 通过 MP 系统审核的图片地址
291 | })
292 |
293 | wx.onShareAppMessage(function() {
294 | return {
295 | imageUrlId: id,
296 | imageUrl: url,
297 | }
298 | })
299 |
300 | // 设置 withShareTicket: true
301 | wx.updateShareMenu({
302 | withShareTicket: true,
303 | })
304 |
305 | wx.updateShareMenu({
306 | withShareTicket: true,
307 | isUpdatableMessage: true,
308 | activityId: '', // 活动 ID
309 | templateInfo: {
310 | templateId: '',
311 | parameterList: [
312 | {
313 | name: 'member_count',
314 | value: '1',
315 | },
316 | {
317 | name: 'room_limit',
318 | value: '3',
319 | },
320 | ],
321 | },
322 | })
323 |
324 | const openDataContext = wx.getOpenDataContext()
325 | openDataContext.postMessage({
326 | text: 'hello',
327 | year: new Date().getFullYear(),
328 | })
329 |
--------------------------------------------------------------------------------
/test/index.d.ts:
--------------------------------------------------------------------------------
1 | ///
2 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "allowJs": false,
4 | "alwaysStrict": true,
5 | "experimentalDecorators": true,
6 | "inlineSourceMap": true,
7 | "inlineSources": true,
8 | "lib": ["es6"],
9 | "module": "CommonJS",
10 | "noFallthroughCasesInSwitch": true,
11 | "noImplicitAny": true,
12 | "noImplicitReturns": true,
13 | "noImplicitThis": true,
14 | "noUnusedLocals": true,
15 | "noUnusedParameters": true,
16 | "pretty": true,
17 | "removeComments": true,
18 | "strict": true,
19 | "strictNullChecks": true,
20 | "strictPropertyInitialization": true,
21 | "target": "ES5",
22 | "typeRoots": [ "./node_modules/**/*.d.ts" ]
23 | },
24 | "include": [
25 | "./test/*.ts"
26 | ],
27 | "exclude": [
28 | "node_modules"
29 | ]
30 | }
31 |
--------------------------------------------------------------------------------
/types/index.d.ts:
--------------------------------------------------------------------------------
1 | ///
2 |
--------------------------------------------------------------------------------
/types/wx/index.d.ts:
--------------------------------------------------------------------------------
1 | /*! *****************************************************************************
2 | Copyright (c) 2025 Tencent, Inc. All rights reserved.
3 |
4 | Permission is hereby granted, free of charge, to any person obtaining a copy of
5 | this software and associated documentation files (the "Software"), to deal in
6 | the Software without restriction, including without limitation the rights to
7 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
8 | of the Software, and to permit persons to whom the Software is furnished to do
9 | so, subject to the following conditions:
10 |
11 | The above copyright notice and this permission notice shall be included in all
12 | copies or substantial portions of the Software.
13 |
14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 | SOFTWARE.
21 | ***************************************************************************** */
22 |
23 | ///
24 | ///
25 | ///
26 |
27 | declare namespace WechatMinigame {
28 | type IAnyObject = Record
29 | type Optional = F extends (arg: infer P) => infer R ? (arg?: P) => R : F
30 | type OptionalInterface = { [K in keyof T]: Optional }
31 | interface AsyncMethodOptionLike {
32 | success?: (...args: any[]) => void
33 | }
34 | type PromisifySuccessResult<
35 | P,
36 | T extends AsyncMethodOptionLike
37 | > = P extends {
38 | success: any
39 | }
40 | ? void
41 | : P extends { fail: any }
42 | ? void
43 | : P extends { complete: any }
44 | ? void
45 | : Promise>[0]>
46 |
47 | // TODO: Extract real definition from `lib.dom.d.ts` to replace this
48 | type IIRFilterNode = any
49 | type WaveShaperNode = any
50 | type ConstantSourceNode = any
51 | type OscillatorNode = any
52 | type GainNode = any
53 | type BiquadFilterNode = any
54 | type PeriodicWaveNode = any
55 | type AudioNode = any
56 | type ChannelSplitterNode = any
57 | type ChannelMergerNode = any
58 | type DelayNode = any
59 | type DynamicsCompressorNode = any
60 | type ScriptProcessorNode = any
61 | type PannerNode = any
62 | type AnalyserNode = any
63 | type WebGLTexture = any
64 | }
65 |
66 | declare const console: WechatMinigame.Console
67 | declare const wx: WechatMinigame.Wx
68 | /** 引入模块。返回模块通过 `module.exports` 或 `exports` 暴露的接口。 */
69 | declare function require(
70 | /** 需要引入模块文件相对于当前文件的相对路径,或 npm 模块名,或 npm 模块路径。不支持绝对路径 */
71 | module: string
72 | ): any
73 | /** 引入插件。返回插件通过 `main` 暴露的接口。 */
74 | declare function requirePlugin(
75 | /** 需要引入的插件的 alias */
76 | module: string
77 | ): any
78 | /** 当前模块对象 */
79 | declare let module: {
80 | /** 模块向外暴露的对象,使用 `require` 引用该模块时可以获取 */
81 | exports: any
82 | }
83 | /** `module.exports` 的引用 */
84 | declare let exports: any
85 | declare let GameGlobal: WechatMinigame.IAnyObject
86 |
87 | /** [clearInterval(number intervalID)](https://developers.weixin.qq.com/miniprogram/dev/api/base/timer/clearInterval.html)
88 | *
89 | * 取消由 setInterval 设置的定时器。 */
90 | declare function clearInterval(
91 | /** 要取消的定时器的 ID */
92 | intervalID: number
93 | ): void
94 | /** [clearTimeout(number timeoutID)](https://developers.weixin.qq.com/miniprogram/dev/api/base/timer/clearTimeout.html)
95 | *
96 | * 取消由 setTimeout 设置的定时器。 */
97 | declare function clearTimeout(
98 | /** 要取消的定时器的 ID */
99 | timeoutID: number
100 | ): void
101 | /** [number setInterval(function callback, number delay, any rest)](https://developers.weixin.qq.com/miniprogram/dev/api/base/timer/setInterval.html)
102 | *
103 | * 设定一个定时器。按照指定的周期(以毫秒计)来执行注册的回调函数 */
104 | declare function setInterval(
105 | /** 回调函数 */
106 | callback: (...args: any[]) => any,
107 | /** 执行回调函数之间的时间间隔,单位 ms。 */
108 | delay?: number,
109 | /** param1, param2, ..., paramN 等附加参数,它们会作为参数传递给回调函数。 */
110 | ...rest: any[]
111 | ): number
112 | /** [number setTimeout(function callback, number delay, any rest)](https://developers.weixin.qq.com/miniprogram/dev/api/base/timer/setTimeout.html)
113 | *
114 | * 设定一个定时器。在定时到期以后执行注册的回调函数 */
115 | declare function setTimeout(
116 | /** 回调函数 */
117 | callback: (...args: any[]) => any,
118 | /** 延迟的时间,函数的调用会在该延迟之后发生,单位 ms。 */
119 | delay?: number,
120 | /** param1, param2, ..., paramN 等附加参数,它们会作为参数传递给回调函数。 */
121 | ...rest: any[]
122 | ): number
123 |
--------------------------------------------------------------------------------
/types/wx/lib.wx.cloud.d.ts:
--------------------------------------------------------------------------------
1 | /*! *****************************************************************************
2 | Copyright (c) 2025 Tencent, Inc. All rights reserved.
3 |
4 | Permission is hereby granted, free of charge, to any person obtaining a copy of
5 | this software and associated documentation files (the "Software"), to deal in
6 | the Software without restriction, including without limitation the rights to
7 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
8 | of the Software, and to permit persons to whom the Software is furnished to do
9 | so, subject to the following conditions:
10 |
11 | The above copyright notice and this permission notice shall be included in all
12 | copies or substantial portions of the Software.
13 |
14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 | SOFTWARE.
21 | ***************************************************************************** */
22 |
23 | /**
24 | * Common interfaces and types
25 | */
26 |
27 | interface IAPIError {
28 | errMsg: string
29 | }
30 |
31 | interface IAPIParam {
32 | config?: ICloudConfig
33 | success?: (res: T) => void
34 | fail?: (err: IAPIError) => void
35 | complete?: (val: T | IAPIError) => void
36 | }
37 |
38 | interface IAPISuccessParam {
39 | errMsg: string
40 | }
41 |
42 | type IAPICompleteParam = IAPISuccessParam | IAPIError
43 |
44 | type IAPIFunction> = (param?: P) => Promise
45 |
46 | interface IInitCloudConfig {
47 | env?:
48 | | string
49 | | {
50 | database?: string
51 | functions?: string
52 | storage?: string
53 | }
54 | traceUser?: boolean
55 | }
56 |
57 | interface ICloudConfig {
58 | env?: string
59 | traceUser?: boolean
60 | }
61 |
62 | interface IICloudAPI {
63 | init: (config?: IInitCloudConfig) => void
64 | [api: string]: AnyFunction | IAPIFunction
65 | }
66 |
67 | interface ICloudService {
68 | name: string
69 |
70 | getAPIs: () => { [name: string]: IAPIFunction }
71 | }
72 |
73 | interface ICloudServices {
74 | [serviceName: string]: ICloudService
75 | }
76 |
77 | interface ICloudMetaData {
78 | session_id: string
79 | }
80 |
81 | declare class InternalSymbol {}
82 |
83 | interface AnyObject {
84 | [x: string]: any
85 | }
86 |
87 | type AnyArray = any[]
88 |
89 | type AnyFunction = (...args: any[]) => any
90 |
91 | /**
92 | * extend wx with cloud
93 | */
94 | interface WxCloud {
95 | init: (config?: ICloudConfig) => void
96 |
97 | callFunction(param: OQ): void
98 | callFunction(
99 | param: RQ
100 | ): Promise
101 |
102 | uploadFile(param: OQ): WechatMinigame.UploadTask
103 | uploadFile(
104 | param: RQ
105 | ): Promise
106 |
107 | downloadFile(
108 | param: OQ
109 | ): WechatMinigame.DownloadTask
110 | downloadFile(
111 | param: RQ
112 | ): Promise
113 |
114 | getTempFileURL(param: OQ): void
115 | getTempFileURL(
116 | param: RQ
117 | ): Promise
118 |
119 | deleteFile(param: OQ): void
120 | deleteFile(
121 | param: RQ
122 | ): Promise
123 |
124 | database: (config?: ICloudConfig) => DB.Database
125 |
126 | CloudID: ICloud.ICloudIDConstructor
127 | CDN: ICloud.ICDNConstructor
128 |
129 | callContainer(param: OQ): void
130 | callContainer(
131 | param: RQ
132 | ): Promise
133 |
134 | connectContainer(param: OQ): void
135 | connectContainer(
136 | param: RQ
137 | ): Promise
138 | }
139 |
140 | declare namespace ICloud {
141 | interface ICloudAPIParam extends IAPIParam {
142 | config?: ICloudConfig
143 | }
144 |
145 | // === API: callFunction ===
146 | type CallFunctionData = AnyObject
147 |
148 | interface CallFunctionResult extends IAPISuccessParam {
149 | result: AnyObject | string | undefined
150 | }
151 |
152 | interface CallFunctionParam extends ICloudAPIParam {
153 | name: string
154 | data?: CallFunctionData
155 | slow?: boolean
156 | }
157 | // === end ===
158 |
159 | // === API: container ===
160 | type CallContainerData = AnyObject
161 |
162 | interface CallContainerResult extends IAPISuccessParam {
163 | data: any
164 | statusCode: number
165 | header: Record
166 | callID: string
167 | }
168 |
169 | interface CallContainerParam extends ICloudAPIParam {
170 | path: string
171 | service?: string
172 | method?: string
173 | header?: Record
174 | data?: any // string, object, ArrayBuffer
175 | dataType?: string
176 | responseType?: string
177 | timeout?: number
178 | verbose?: boolean
179 | followRedirect?: boolean
180 | }
181 |
182 | interface ConnectContainerResult extends IAPISuccessParam {
183 | socketTask: WechatMinigame.SocketTask
184 | }
185 |
186 | interface ConnectSocketOptions extends IAPIParam {
187 | header?: Record
188 | protocols?: string[]
189 | tcpNoDelay?: boolean
190 | perMessageDeflate?: boolean
191 | timeout?: number
192 | }
193 |
194 | type ConnectContainerParam = Omit<
195 | ConnectSocketOptions,
196 | 'success' | 'fail' | 'complete'
197 | > &
198 | ICloudAPIParam & {
199 | service: string
200 | path?: string
201 | }
202 | // === end ===
203 |
204 | // === API: uploadFile ===
205 | interface UploadFileResult extends IAPISuccessParam {
206 | fileID: string
207 | statusCode: number
208 | }
209 |
210 | interface UploadFileParam extends ICloudAPIParam {
211 | cloudPath: string
212 | filePath: string
213 | header?: AnyObject
214 | }
215 | // === end ===
216 |
217 | // === API: downloadFile ===
218 | interface DownloadFileResult extends IAPISuccessParam {
219 | tempFilePath: string
220 | statusCode: number
221 | }
222 |
223 | interface DownloadFileParam extends ICloudAPIParam {
224 | fileID: string
225 | cloudPath?: string
226 | }
227 | // === end ===
228 |
229 | // === API: getTempFileURL ===
230 | interface GetTempFileURLResult extends IAPISuccessParam {
231 | fileList: GetTempFileURLResultItem[]
232 | }
233 |
234 | interface GetTempFileURLResultItem {
235 | fileID: string
236 | tempFileURL: string
237 | maxAge: number
238 | status: number
239 | errMsg: string
240 | }
241 |
242 | interface GetTempFileURLParam extends ICloudAPIParam {
243 | fileList: string[]
244 | }
245 | // === end ===
246 |
247 | // === API: deleteFile ===
248 | interface DeleteFileResult extends IAPISuccessParam {
249 | fileList: DeleteFileResultItem[]
250 | }
251 |
252 | interface DeleteFileResultItem {
253 | fileID: string
254 | status: number
255 | errMsg: string
256 | }
257 |
258 | interface DeleteFileParam extends ICloudAPIParam {
259 | fileList: string[]
260 | }
261 | // === end ===
262 |
263 | // === API: CloudID ===
264 | abstract class CloudID {
265 | constructor(cloudID: string)
266 | }
267 |
268 | interface ICloudIDConstructor {
269 | new (cloudId: string): CloudID
270 | (cloudId: string): CloudID
271 | }
272 | // === end ===
273 |
274 | // === API: CDN ===
275 | abstract class CDN {
276 | target: string | ArrayBuffer | ICDNFilePathSpec
277 | constructor(target: string | ArrayBuffer | ICDNFilePathSpec)
278 | }
279 |
280 | interface ICDNFilePathSpec {
281 | type: 'filePath'
282 | filePath: string
283 | }
284 |
285 | interface ICDNConstructor {
286 | new (options: string | ArrayBuffer | ICDNFilePathSpec): CDN
287 | (options: string | ArrayBuffer | ICDNFilePathSpec): CDN
288 | }
289 | // === end ===
290 | }
291 |
292 | // === Database ===
293 | declare namespace DB {
294 | /**
295 | * The class of all exposed cloud database instances
296 | */
297 | class Database {
298 | readonly config: ICloudConfig
299 | readonly command: DatabaseCommand
300 | readonly Geo: IGeo
301 | readonly serverDate: () => ServerDate
302 | readonly RegExp: IRegExpConstructor
303 |
304 | private constructor()
305 |
306 | collection(collectionName: string): CollectionReference
307 | }
308 |
309 | class CollectionReference extends Query {
310 | readonly collectionName: string
311 |
312 | private constructor(name: string, database: Database)
313 |
314 | doc(docId: string | number): DocumentReference
315 |
316 | add(options: OQ): void
317 | add(options: RQ): Promise
318 | }
319 |
320 | class DocumentReference {
321 | private constructor(docId: string | number, database: Database)
322 |
323 | field(object: Record): this
324 |
325 | get(options: OQ): void
326 | get(options?: RQ): Promise
327 |
328 | set(options: OQ): void
329 | set(options?: RQ): Promise
330 |
331 | update(options: OQ): void
332 | update(
333 | options?: RQ
334 | ): Promise
335 |
336 | remove(options: OQ): void
337 | remove(
338 | options?: RQ
339 | ): Promise
340 |
341 | watch(options: IWatchOptions): RealtimeListener
342 | }
343 |
344 | class RealtimeListener {
345 | // "And Now His Watch Is Ended"
346 | close: () => Promise
347 | }
348 |
349 | class Query {
350 | where(condition: IQueryCondition): Query
351 |
352 | orderBy(fieldPath: string, order: string): Query
353 |
354 | limit(max: number): Query
355 |
356 | skip(offset: number): Query
357 |
358 | field(object: Record): Query
359 |
360 | get(options: OQ): void
361 | get(options?: RQ): Promise
362 |
363 | count(options: OQ): void
364 | count(options?: RQ): Promise
365 |
366 | watch(options: IWatchOptions): RealtimeListener
367 | }
368 |
369 | interface DatabaseCommand {
370 | eq(val: any): DatabaseQueryCommand
371 | neq(val: any): DatabaseQueryCommand
372 | gt(val: any): DatabaseQueryCommand
373 | gte(val: any): DatabaseQueryCommand
374 | lt(val: any): DatabaseQueryCommand
375 | lte(val: any): DatabaseQueryCommand
376 | in(val: any[]): DatabaseQueryCommand
377 | nin(val: any[]): DatabaseQueryCommand
378 |
379 | geoNear(options: IGeoNearCommandOptions): DatabaseQueryCommand
380 | geoWithin(options: IGeoWithinCommandOptions): DatabaseQueryCommand
381 | geoIntersects(
382 | options: IGeoIntersectsCommandOptions
383 | ): DatabaseQueryCommand
384 |
385 | and(
386 | ...expressions: Array
387 | ): DatabaseLogicCommand
388 | or(
389 | ...expressions: Array
390 | ): DatabaseLogicCommand
391 | nor(
392 | ...expressions: Array
393 | ): DatabaseLogicCommand
394 | not(expression: DatabaseLogicCommand): DatabaseLogicCommand
395 |
396 | exists(val: boolean): DatabaseQueryCommand
397 |
398 | mod(divisor: number, remainder: number): DatabaseQueryCommand
399 |
400 | all(val: any[]): DatabaseQueryCommand
401 | elemMatch(val: any): DatabaseQueryCommand
402 | size(val: number): DatabaseQueryCommand
403 |
404 | set(val: any): DatabaseUpdateCommand
405 | remove(): DatabaseUpdateCommand
406 | inc(val: number): DatabaseUpdateCommand
407 | mul(val: number): DatabaseUpdateCommand
408 | min(val: number): DatabaseUpdateCommand
409 | max(val: number): DatabaseUpdateCommand
410 | rename(val: string): DatabaseUpdateCommand
411 | bit(val: number): DatabaseUpdateCommand
412 |
413 | push(...values: any[]): DatabaseUpdateCommand
414 | pop(): DatabaseUpdateCommand
415 | shift(): DatabaseUpdateCommand
416 | unshift(...values: any[]): DatabaseUpdateCommand
417 | addToSet(val: any): DatabaseUpdateCommand
418 | pull(val: any): DatabaseUpdateCommand
419 | pullAll(val: any): DatabaseUpdateCommand
420 |
421 | project: {
422 | slice(val: number | [number, number]): DatabaseProjectionCommand
423 | }
424 |
425 | aggregate: {
426 | __safe_props__?: Set
427 |
428 | abs(val: any): DatabaseAggregateCommand
429 | add(val: any): DatabaseAggregateCommand
430 | addToSet(val: any): DatabaseAggregateCommand
431 | allElementsTrue(val: any): DatabaseAggregateCommand
432 | and(val: any): DatabaseAggregateCommand
433 | anyElementTrue(val: any): DatabaseAggregateCommand
434 | arrayElemAt(val: any): DatabaseAggregateCommand
435 | arrayToObject(val: any): DatabaseAggregateCommand
436 | avg(val: any): DatabaseAggregateCommand
437 | ceil(val: any): DatabaseAggregateCommand
438 | cmp(val: any): DatabaseAggregateCommand
439 | concat(val: any): DatabaseAggregateCommand
440 | concatArrays(val: any): DatabaseAggregateCommand
441 | cond(val: any): DatabaseAggregateCommand
442 | convert(val: any): DatabaseAggregateCommand
443 | dateFromParts(val: any): DatabaseAggregateCommand
444 | dateToParts(val: any): DatabaseAggregateCommand
445 | dateFromString(val: any): DatabaseAggregateCommand
446 | dateToString(val: any): DatabaseAggregateCommand
447 | dayOfMonth(val: any): DatabaseAggregateCommand
448 | dayOfWeek(val: any): DatabaseAggregateCommand
449 | dayOfYear(val: any): DatabaseAggregateCommand
450 | divide(val: any): DatabaseAggregateCommand
451 | eq(val: any): DatabaseAggregateCommand
452 | exp(val: any): DatabaseAggregateCommand
453 | filter(val: any): DatabaseAggregateCommand
454 | first(val: any): DatabaseAggregateCommand
455 | floor(val: any): DatabaseAggregateCommand
456 | gt(val: any): DatabaseAggregateCommand
457 | gte(val: any): DatabaseAggregateCommand
458 | hour(val: any): DatabaseAggregateCommand
459 | ifNull(val: any): DatabaseAggregateCommand
460 | in(val: any): DatabaseAggregateCommand
461 | indexOfArray(val: any): DatabaseAggregateCommand
462 | indexOfBytes(val: any): DatabaseAggregateCommand
463 | indexOfCP(val: any): DatabaseAggregateCommand
464 | isArray(val: any): DatabaseAggregateCommand
465 | isoDayOfWeek(val: any): DatabaseAggregateCommand
466 | isoWeek(val: any): DatabaseAggregateCommand
467 | isoWeekYear(val: any): DatabaseAggregateCommand
468 | last(val: any): DatabaseAggregateCommand
469 | let(val: any): DatabaseAggregateCommand
470 | literal(val: any): DatabaseAggregateCommand
471 | ln(val: any): DatabaseAggregateCommand
472 | log(val: any): DatabaseAggregateCommand
473 | log10(val: any): DatabaseAggregateCommand
474 | lt(val: any): DatabaseAggregateCommand
475 | lte(val: any): DatabaseAggregateCommand
476 | ltrim(val: any): DatabaseAggregateCommand
477 | map(val: any): DatabaseAggregateCommand
478 | max(val: any): DatabaseAggregateCommand
479 | mergeObjects(val: any): DatabaseAggregateCommand
480 | meta(val: any): DatabaseAggregateCommand
481 | min(val: any): DatabaseAggregateCommand
482 | millisecond(val: any): DatabaseAggregateCommand
483 | minute(val: any): DatabaseAggregateCommand
484 | mod(val: any): DatabaseAggregateCommand
485 | month(val: any): DatabaseAggregateCommand
486 | multiply(val: any): DatabaseAggregateCommand
487 | neq(val: any): DatabaseAggregateCommand
488 | not(val: any): DatabaseAggregateCommand
489 | objectToArray(val: any): DatabaseAggregateCommand
490 | or(val: any): DatabaseAggregateCommand
491 | pow(val: any): DatabaseAggregateCommand
492 | push(val: any): DatabaseAggregateCommand
493 | range(val: any): DatabaseAggregateCommand
494 | reduce(val: any): DatabaseAggregateCommand
495 | reverseArray(val: any): DatabaseAggregateCommand
496 | rtrim(val: any): DatabaseAggregateCommand
497 | second(val: any): DatabaseAggregateCommand
498 | setDifference(val: any): DatabaseAggregateCommand
499 | setEquals(val: any): DatabaseAggregateCommand
500 | setIntersection(val: any): DatabaseAggregateCommand
501 | setIsSubset(val: any): DatabaseAggregateCommand
502 | setUnion(val: any): DatabaseAggregateCommand
503 | size(val: any): DatabaseAggregateCommand
504 | slice(val: any): DatabaseAggregateCommand
505 | split(val: any): DatabaseAggregateCommand
506 | sqrt(val: any): DatabaseAggregateCommand
507 | stdDevPop(val: any): DatabaseAggregateCommand
508 | stdDevSamp(val: any): DatabaseAggregateCommand
509 | strcasecmp(val: any): DatabaseAggregateCommand
510 | strLenBytes(val: any): DatabaseAggregateCommand
511 | strLenCP(val: any): DatabaseAggregateCommand
512 | substr(val: any): DatabaseAggregateCommand
513 | substrBytes(val: any): DatabaseAggregateCommand
514 | substrCP(val: any): DatabaseAggregateCommand
515 | subtract(val: any): DatabaseAggregateCommand
516 | sum(val: any): DatabaseAggregateCommand
517 | switch(val: any): DatabaseAggregateCommand
518 | toBool(val: any): DatabaseAggregateCommand
519 | toDate(val: any): DatabaseAggregateCommand
520 | toDecimal(val: any): DatabaseAggregateCommand
521 | toDouble(val: any): DatabaseAggregateCommand
522 | toInt(val: any): DatabaseAggregateCommand
523 | toLong(val: any): DatabaseAggregateCommand
524 | toObjectId(val: any): DatabaseAggregateCommand
525 | toString(val: any): DatabaseAggregateCommand
526 | toLower(val: any): DatabaseAggregateCommand
527 | toUpper(val: any): DatabaseAggregateCommand
528 | trim(val: any): DatabaseAggregateCommand
529 | trunc(val: any): DatabaseAggregateCommand
530 | type(val: any): DatabaseAggregateCommand
531 | week(val: any): DatabaseAggregateCommand
532 | year(val: any): DatabaseAggregateCommand
533 | zip(val: any): DatabaseAggregateCommand
534 | }
535 | }
536 |
537 | class DatabaseAggregateCommand {}
538 |
539 | enum LOGIC_COMMANDS_LITERAL {
540 | AND = 'and',
541 | OR = 'or',
542 | NOT = 'not',
543 | NOR = 'nor'
544 | }
545 |
546 | class DatabaseLogicCommand {
547 | and(...expressions: DatabaseLogicCommand[]): DatabaseLogicCommand
548 | or(...expressions: DatabaseLogicCommand[]): DatabaseLogicCommand
549 | nor(...expressions: DatabaseLogicCommand[]): DatabaseLogicCommand
550 | not(expression: DatabaseLogicCommand): DatabaseLogicCommand
551 | }
552 |
553 | enum QUERY_COMMANDS_LITERAL {
554 | // comparison
555 | EQ = 'eq',
556 | NEQ = 'neq',
557 | GT = 'gt',
558 | GTE = 'gte',
559 | LT = 'lt',
560 | LTE = 'lte',
561 | IN = 'in',
562 | NIN = 'nin',
563 | // geo
564 | GEO_NEAR = 'geoNear',
565 | GEO_WITHIN = 'geoWithin',
566 | GEO_INTERSECTS = 'geoIntersects',
567 | // element
568 | EXISTS = 'exists',
569 | // evaluation
570 | MOD = 'mod',
571 | // array
572 | ALL = 'all',
573 | ELEM_MATCH = 'elemMatch',
574 | SIZE = 'size'
575 | }
576 |
577 | class DatabaseQueryCommand extends DatabaseLogicCommand {
578 | eq(val: any): DatabaseLogicCommand
579 | neq(val: any): DatabaseLogicCommand
580 | gt(val: any): DatabaseLogicCommand
581 | gte(val: any): DatabaseLogicCommand
582 | lt(val: any): DatabaseLogicCommand
583 | lte(val: any): DatabaseLogicCommand
584 | in(val: any[]): DatabaseLogicCommand
585 | nin(val: any[]): DatabaseLogicCommand
586 |
587 | exists(val: boolean): DatabaseLogicCommand
588 |
589 | mod(divisor: number, remainder: number): DatabaseLogicCommand
590 |
591 | all(val: any[]): DatabaseLogicCommand
592 | elemMatch(val: any): DatabaseLogicCommand
593 | size(val: number): DatabaseLogicCommand
594 |
595 | geoNear(options: IGeoNearCommandOptions): DatabaseLogicCommand
596 | geoWithin(options: IGeoWithinCommandOptions): DatabaseLogicCommand
597 | geoIntersects(
598 | options: IGeoIntersectsCommandOptions
599 | ): DatabaseLogicCommand
600 | }
601 |
602 | enum PROJECTION_COMMANDS_LITERAL {
603 | SLICE = 'slice'
604 | }
605 |
606 | class DatabaseProjectionCommand {}
607 |
608 | enum UPDATE_COMMANDS_LITERAL {
609 | // field
610 | SET = 'set',
611 | REMOVE = 'remove',
612 | INC = 'inc',
613 | MUL = 'mul',
614 | MIN = 'min',
615 | MAX = 'max',
616 | RENAME = 'rename',
617 | // bitwise
618 | BIT = 'bit',
619 | // array
620 | PUSH = 'push',
621 | POP = 'pop',
622 | SHIFT = 'shift',
623 | UNSHIFT = 'unshift',
624 | ADD_TO_SET = 'addToSet',
625 | PULL = 'pull',
626 | PULL_ALL = 'pullAll'
627 | }
628 |
629 | class DatabaseUpdateCommand {}
630 |
631 | class Batch {}
632 |
633 | /**
634 | * A contract that all API provider must adhere to
635 | */
636 | class APIBaseContract<
637 | PromiseReturn,
638 | CallbackReturn,
639 | Param extends IAPIParam,
640 | Context = any
641 | > {
642 | getContext(param: Param): Context
643 |
644 | /**
645 | * In case of callback-style invocation, this function will be called
646 | */
647 | getCallbackReturn(param: Param, context: Context): CallbackReturn
648 |
649 | getFinalParam(param: Param, context: Context): T
650 |
651 | run(param: T): Promise
652 | }
653 |
654 | interface IGeoPointConstructor {
655 | new (longitude: number, latitide: number): GeoPoint
656 | new (geojson: IGeoJSONPoint): GeoPoint
657 | (longitude: number, latitide: number): GeoPoint
658 | (geojson: IGeoJSONPoint): GeoPoint
659 | }
660 |
661 | interface IGeoMultiPointConstructor {
662 | new (points: GeoPoint[] | IGeoJSONMultiPoint): GeoMultiPoint
663 | (points: GeoPoint[] | IGeoJSONMultiPoint): GeoMultiPoint
664 | }
665 |
666 | interface IGeoLineStringConstructor {
667 | new (points: GeoPoint[] | IGeoJSONLineString): GeoLineString
668 | (points: GeoPoint[] | IGeoJSONLineString): GeoLineString
669 | }
670 |
671 | interface IGeoMultiLineStringConstructor {
672 | new (
673 | lineStrings: GeoLineString[] | IGeoJSONMultiLineString
674 | ): GeoMultiLineString
675 | (
676 | lineStrings: GeoLineString[] | IGeoJSONMultiLineString
677 | ): GeoMultiLineString
678 | }
679 |
680 | interface IGeoPolygonConstructor {
681 | new (lineStrings: GeoLineString[] | IGeoJSONPolygon): GeoPolygon
682 | (lineStrings: GeoLineString[] | IGeoJSONPolygon): GeoPolygon
683 | }
684 |
685 | interface IGeoMultiPolygonConstructor {
686 | new (polygons: GeoPolygon[] | IGeoJSONMultiPolygon): GeoMultiPolygon
687 | (polygons: GeoPolygon[] | IGeoJSONMultiPolygon): GeoMultiPolygon
688 | }
689 |
690 | interface IGeo {
691 | Point: IGeoPointConstructor
692 | MultiPoint: IGeoMultiPointConstructor
693 | LineString: IGeoLineStringConstructor
694 | MultiLineString: IGeoMultiLineStringConstructor
695 | Polygon: IGeoPolygonConstructor
696 | MultiPolygon: IGeoMultiPolygonConstructor
697 | }
698 |
699 | interface IGeoJSONPoint {
700 | type: 'Point'
701 | coordinates: [number, number]
702 | }
703 |
704 | interface IGeoJSONMultiPoint {
705 | type: 'MultiPoint'
706 | coordinates: Array<[number, number]>
707 | }
708 |
709 | interface IGeoJSONLineString {
710 | type: 'LineString'
711 | coordinates: Array<[number, number]>
712 | }
713 |
714 | interface IGeoJSONMultiLineString {
715 | type: 'MultiLineString'
716 | coordinates: Array>
717 | }
718 |
719 | interface IGeoJSONPolygon {
720 | type: 'Polygon'
721 | coordinates: Array>
722 | }
723 |
724 | interface IGeoJSONMultiPolygon {
725 | type: 'MultiPolygon'
726 | coordinates: Array>>
727 | }
728 |
729 | type IGeoJSONObject =
730 | | IGeoJSONPoint
731 | | IGeoJSONMultiPoint
732 | | IGeoJSONLineString
733 | | IGeoJSONMultiLineString
734 | | IGeoJSONPolygon
735 | | IGeoJSONMultiPolygon
736 |
737 | abstract class GeoPoint {
738 | longitude: number
739 | latitude: number
740 |
741 | constructor(longitude: number, latitude: number)
742 |
743 | toJSON(): Record
744 | toString(): string
745 | }
746 |
747 | abstract class GeoMultiPoint {
748 | points: GeoPoint[]
749 |
750 | constructor(points: GeoPoint[])
751 |
752 | toJSON(): IGeoJSONMultiPoint
753 | toString(): string
754 | }
755 |
756 | abstract class GeoLineString {
757 | points: GeoPoint[]
758 |
759 | constructor(points: GeoPoint[])
760 |
761 | toJSON(): IGeoJSONLineString
762 | toString(): string
763 | }
764 |
765 | abstract class GeoMultiLineString {
766 | lines: GeoLineString[]
767 |
768 | constructor(lines: GeoLineString[])
769 |
770 | toJSON(): IGeoJSONMultiLineString
771 | toString(): string
772 | }
773 |
774 | abstract class GeoPolygon {
775 | lines: GeoLineString[]
776 |
777 | constructor(lines: GeoLineString[])
778 |
779 | toJSON(): IGeoJSONPolygon
780 | toString(): string
781 | }
782 |
783 | abstract class GeoMultiPolygon {
784 | polygons: GeoPolygon[]
785 |
786 | constructor(polygons: GeoPolygon[])
787 |
788 | toJSON(): IGeoJSONMultiPolygon
789 | toString(): string
790 | }
791 |
792 | type GeoInstance =
793 | | GeoPoint
794 | | GeoMultiPoint
795 | | GeoLineString
796 | | GeoMultiLineString
797 | | GeoPolygon
798 | | GeoMultiPolygon
799 |
800 | interface IGeoNearCommandOptions {
801 | geometry: GeoPoint
802 | maxDistance?: number
803 | minDistance?: number
804 | }
805 |
806 | interface IGeoWithinCommandOptions {
807 | geometry: GeoPolygon | GeoMultiPolygon
808 | }
809 |
810 | interface IGeoIntersectsCommandOptions {
811 | geometry:
812 | | GeoPoint
813 | | GeoMultiPoint
814 | | GeoLineString
815 | | GeoMultiLineString
816 | | GeoPolygon
817 | | GeoMultiPolygon
818 | }
819 |
820 | interface IServerDateOptions {
821 | offset: number
822 | }
823 |
824 | abstract class ServerDate {
825 | readonly options: IServerDateOptions
826 | constructor(options?: IServerDateOptions)
827 | }
828 |
829 | interface IRegExpOptions {
830 | regexp: string
831 | options?: string
832 | }
833 |
834 | interface IRegExpConstructor {
835 | new (options: IRegExpOptions): RegExp
836 | (options: IRegExpOptions): RegExp
837 | }
838 |
839 | abstract class RegExp {
840 | readonly regexp: string
841 | readonly options: string
842 | constructor(options: IRegExpOptions)
843 | }
844 |
845 | type DocumentId = string | number
846 |
847 | interface IDocumentData {
848 | _id?: DocumentId
849 | [key: string]: any
850 | }
851 |
852 | type IDBAPIParam = IAPIParam
853 |
854 | interface IAddDocumentOptions extends IDBAPIParam {
855 | data: IDocumentData
856 | }
857 |
858 | type IGetDocumentOptions = IDBAPIParam
859 |
860 | type ICountDocumentOptions = IDBAPIParam
861 |
862 | interface IUpdateDocumentOptions extends IDBAPIParam {
863 | data: IUpdateCondition
864 | }
865 |
866 | interface IUpdateSingleDocumentOptions extends IDBAPIParam {
867 | data: IUpdateCondition
868 | }
869 |
870 | interface ISetDocumentOptions extends IDBAPIParam {
871 | data: IUpdateCondition
872 | }
873 |
874 | interface ISetSingleDocumentOptions extends IDBAPIParam {
875 | data: IUpdateCondition
876 | }
877 |
878 | interface IRemoveDocumentOptions extends IDBAPIParam {
879 | query: IQueryCondition
880 | }
881 |
882 | type IRemoveSingleDocumentOptions = IDBAPIParam
883 |
884 | interface IWatchOptions {
885 | // server realtime data init & change event
886 | onChange: (snapshot: ISnapshot) => void
887 | // error while connecting / listening
888 | onError: (error: any) => void
889 | }
890 |
891 | interface ISnapshot {
892 | id: number
893 | docChanges: ISingleDBEvent[]
894 | docs: Record
895 | type?: SnapshotType
896 | }
897 |
898 | type SnapshotType = 'init'
899 |
900 | interface ISingleDBEvent {
901 | id: number
902 | dataType: DataType
903 | queueType: QueueType
904 | docId: string
905 | doc: Record
906 | updatedFields?: Record
907 | removedFields?: string[]
908 | }
909 |
910 | type DataType = 'init' | 'update' | 'replace' | 'add' | 'remove' | 'limit'
911 |
912 | type QueueType = 'init' | 'enqueue' | 'dequeue' | 'update'
913 |
914 | interface IQueryCondition {
915 | [key: string]: any
916 | }
917 |
918 | type IStringQueryCondition = string
919 |
920 | interface IQueryResult extends IAPISuccessParam {
921 | data: IDocumentData[]
922 | }
923 |
924 | interface IQuerySingleResult extends IAPISuccessParam {
925 | data: IDocumentData
926 | }
927 |
928 | interface IUpdateCondition {
929 | [key: string]: any
930 | }
931 |
932 | type IStringUpdateCondition = string
933 |
934 | interface IAddResult extends IAPISuccessParam {
935 | _id: DocumentId
936 | }
937 |
938 | interface IUpdateResult extends IAPISuccessParam {
939 | stats: {
940 | updated: number
941 | // created: number,
942 | }
943 | }
944 |
945 | interface ISetResult extends IAPISuccessParam {
946 | _id: DocumentId
947 | stats: {
948 | updated: number
949 | created: number
950 | }
951 | }
952 |
953 | interface IRemoveResult extends IAPISuccessParam {
954 | stats: {
955 | removed: number
956 | }
957 | }
958 |
959 | interface ICountResult extends IAPISuccessParam {
960 | total: number
961 | }
962 | }
963 |
964 | type Optional = { [K in keyof T]+?: T[K] }
965 |
966 | type OQ<
967 | T extends Optional<
968 | Record<'complete' | 'success' | 'fail', (...args: any[]) => any>
969 | >
970 | > =
971 | | (RQ & Required>)
972 | | (RQ & Required>)
973 | | (RQ & Required>)
974 | | (RQ & Required>)
975 | | (RQ & Required>)
976 | | (RQ & Required>)
977 | | (RQ & Required>)
978 |
979 | type RQ<
980 | T extends Optional<
981 | Record<'complete' | 'success' | 'fail', (...args: any[]) => any>
982 | >
983 | > = Pick>
984 |
--------------------------------------------------------------------------------
/types/wx/lib.wx.wasm.d.ts:
--------------------------------------------------------------------------------
1 | /*! *****************************************************************************
2 | Copyright (c) 2025 Tencent, Inc. All rights reserved.
3 |
4 | Permission is hereby granted, free of charge, to any person obtaining a copy of
5 | this software and associated documentation files (the "Software"), to deal in
6 | the Software without restriction, including without limitation the rights to
7 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
8 | of the Software, and to permit persons to whom the Software is furnished to do
9 | so, subject to the following conditions:
10 |
11 | The above copyright notice and this permission notice shall be included in all
12 | copies or substantial portions of the Software.
13 |
14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 | SOFTWARE.
21 | ***************************************************************************** */
22 |
23 | /** [WXWebAssembly](https://developers.weixin.qq.com/minigame/dev/guide/performance/perf-webassembly.html)
24 | *
25 | * WXWebAssembly */
26 | declare namespace WXWebAssembly {
27 | type BufferSource = ArrayBufferView | ArrayBuffer
28 |
29 | type CompileError = Error
30 |
31 | const CompileError: {
32 | prototype: CompileError
33 | new (message?: string): CompileError
34 | (message?: string): CompileError
35 | }
36 |
37 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance) */
38 | interface Instance {
39 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance/exports) */
40 | readonly exports: Exports
41 | }
42 |
43 | const Instance: {
44 | prototype: Instance
45 | new (module: Module, importObject?: Imports): Instance
46 | }
47 |
48 | type LinkError = Error
49 |
50 | const LinkError: {
51 | prototype: LinkError
52 | new (message?: string): LinkError
53 | (message?: string): LinkError
54 | }
55 |
56 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory) */
57 | interface Memory {
58 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory/buffer) */
59 | readonly buffer: ArrayBuffer
60 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory/grow) */
61 | grow(delta: number): number
62 | }
63 |
64 | const Memory: {
65 | prototype: Memory
66 | new (descriptor: MemoryDescriptor): Memory
67 | }
68 |
69 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module) */
70 | interface Module {}
71 |
72 | const Module: {
73 | prototype: Module
74 | new (bytes: BufferSource): Module
75 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module/customSections) */
76 | customSections(moduleObject: Module, sectionName: string): ArrayBuffer[]
77 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module/exports) */
78 | exports(moduleObject: Module): ModuleExportDescriptor[]
79 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module/imports) */
80 | imports(moduleObject: Module): ModuleImportDescriptor[]
81 | }
82 |
83 | interface RuntimeError extends Error {}
84 |
85 | const RuntimeError: {
86 | prototype: RuntimeError
87 | new (message?: string): RuntimeError
88 | (message?: string): RuntimeError
89 | }
90 |
91 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Table) */
92 | interface Table {
93 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Table/length) */
94 | readonly length: number
95 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Table/get) */
96 | get(index: number): any
97 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Table/grow) */
98 | grow(delta: number, value?: any): number
99 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Table/set) */
100 | set(index: number, value?: any): void
101 | }
102 |
103 | const Table: {
104 | prototype: Table
105 | new (descriptor: TableDescriptor, value?: any): Table
106 | }
107 |
108 | interface MemoryDescriptor {
109 | initial: number
110 | maximum?: number
111 | shared?: boolean
112 | }
113 |
114 | interface ModuleExportDescriptor {
115 | kind: ImportExportKind
116 | name: string
117 | }
118 |
119 | interface ModuleImportDescriptor {
120 | kind: ImportExportKind
121 | module: string
122 | name: string
123 | }
124 |
125 | interface TableDescriptor {
126 | element: TableKind
127 | initial: number
128 | maximum?: number
129 | }
130 |
131 | type ImportExportKind = 'function' | 'global' | 'memory' | 'table'
132 | type TableKind = 'anyfunc' | 'externref'
133 | type ValueType =
134 | | 'anyfunc'
135 | | 'externref'
136 | | 'f32'
137 | | 'f64'
138 | | 'i32'
139 | | 'i64'
140 | | 'v128'
141 | // eslint-disable-next-line @typescript-eslint/ban-types
142 | type ExportValue = Function | Memory | Table
143 | type Exports = Record
144 | type ImportValue = ExportValue | number
145 | type Imports = Record
146 | type ModuleImports = Record
147 | /** [WXWebAssembly](https://developers.weixin.qq.com/miniprogram/dev/framework/performance/wasm.html) */
148 | function instantiate(
149 | path: string,
150 | importObject?: Imports
151 | ): Promise
152 | }
153 |
--------------------------------------------------------------------------------
/typings.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "minigame-api-typings",
3 | "main": "index.d.ts"
4 | }
--------------------------------------------------------------------------------