ota-native-bridge 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/docs/USAGE.md ADDED
@@ -0,0 +1,1486 @@
1
+ # ota-native-bridge 使用文档
2
+
3
+ 在 **Android / iOS / HarmonyOS 壳 App** 的 WebView 里运行的 H5 / Vue / React 项目,用本 SDK 调用原生能力(版本信息、OTA 更新、打开浏览器、剪贴板 / 扫码 / 生物识别等设备 API)。
4
+
5
+ > 包维护见 [README.md](../README.md)。
6
+
7
+ ---
8
+
9
+ ## 快速上手(1 分钟)
10
+
11
+ ```bash
12
+ npm install ota-native-bridge
13
+ ```
14
+
15
+ ```typescript
16
+ import { Native, App, Ota, Browser } from 'ota-native-bridge';
17
+
18
+ // 1. 判断是否在 App 里(不在则走普通网页逻辑)
19
+ if (!Native.isNativePlatform()) {
20
+ console.log('当前是普通浏览器');
21
+ } else {
22
+ // 2. 直接调用(禁止 await;用 .then / callback)
23
+ App.getInfo().then((info) => {
24
+ console.log('版本', info.versionName);
25
+ });
26
+
27
+ // 3. 检查更新:传用户 ID 即可
28
+ Ota.check('用户ID');
29
+
30
+ // 4. 用系统浏览器打开链接(直接传 URL 字符串)
31
+ Browser.open('https://example.com/help');
32
+ }
33
+ ```
34
+
35
+ **记住这四点:**
36
+
37
+ 1. **`Native.isNativePlatform()`** — 是否在壳 App 里
38
+ 2. **直接调用** — 不用先 `ready()`,SDK 会自动等待壳就绪
39
+ 3. **禁止 `async` / `await`** — 原生与 Crypto API 一律用 `.then()` 或 callback
40
+ 4. **外链用 `Browser.open(url)`** — 不要用 `<a target="_blank">`(会在 WebView 内打开)
41
+
42
+ ### 常用 API 一览
43
+
44
+ | 做什么 | 写法 |
45
+ |--------|------|
46
+ | 是否在 App 里 | `Native.isNativePlatform()` |
47
+ | 读应用/版本信息 | `App.getInfo()` |
48
+ | 读打包渠道码 | `App.getChannelCodes()` |
49
+ | 检查 OTA 更新 | `Ota.check('用户ID')` |
50
+ | 打开网页 | `Browser.open('https://...')` |
51
+ | 读安全区 | `Viewport.getSafeAreaInsets()` |
52
+ | 读设备信息 | `Device.getInfo()` |
53
+ | 读分辨率 / 方向 / 锁屏 | `Device.getScreenInfo()` / `getOrientation()` / `getLockStatus()` |
54
+ | 发通知 | `Notification.show({ title, body })` |
55
+ | 剪贴板 / 分享 | `Clipboard.set('hi')` / `Share.open({ text, url })` |
56
+ | 扫码 / 拍照 | `Scan.scan()` / `Picker.takePhoto()` |
57
+ | 生物识别 | `Biometric.authenticate()` |
58
+ | 支付 / 评分 | `Payment.pay({ url })` / `Store.requestReview()` |
59
+ | 推送 token | `Push.getToken()` |
60
+
61
+ 各插件也可通过 `Native.App`、`Native.Ota` 访问,与直接 `import { App }` 相同。
62
+
63
+ ---
64
+
65
+ ## 1. 前置条件
66
+
67
+ | 条件 | 说明 |
68
+ |------|------|
69
+ | 运行环境 | 页面必须在壳 App 的 WebView 中打开,浏览器单独访问无效 |
70
+ | 原生通道 | 壳已注入 `AndroidBridge` / `IOSBridge` / `HarmonyBridge` 之一 |
71
+ | 配置文件 | OTA:`OtaConstants` 源码写死;UI/更新模式:`www/app_config.json` |
72
+ | Node | 本地开发构建 SDK 需 Node ≥ 18 |
73
+
74
+ **壳工程对应:**
75
+
76
+ | 平台 | 工程目录 |
77
+ |------|----------|
78
+ | Android | `OpenAndroidPackage` |
79
+ | iOS | `OpenIOSPackage` |
80
+ | HarmonyOS | `OpenHarmonyPackage` |
81
+
82
+ ---
83
+
84
+ ## 2. 安装与构建
85
+
86
+ ### 2.1 在业务前端项目中安装
87
+
88
+ ```bash
89
+ npm install ota-native-bridge
90
+ # 或
91
+ pnpm add ota-native-bridge
92
+ ```
93
+
94
+ ### 2.2 在 monorepo 内引用本地包
95
+
96
+ ```json
97
+ {
98
+ "dependencies": {
99
+ "ota-native-bridge": "file:../NativeClientSdk"
100
+ }
101
+ }
102
+ ```
103
+
104
+ 安装后若类型未更新,在 `NativeClientSdk` 目录执行一次 `npm run build`。
105
+
106
+ ### 2.3 本地开发 SDK 本身
107
+
108
+ ```bash
109
+ cd NativeClientSdk
110
+ npm install
111
+ npm run build
112
+ npm run verify:types
113
+ ```
114
+
115
+ ---
116
+
117
+ ## 3. 接入方式
118
+
119
+ ### 3.1 npm 项目(推荐)
120
+
121
+ Vue / React / Vite 等项目:`npm install ota-native-bridge`,构建时 SDK 会打进 bundle,**不用**在壳 `www/` 里再放 bridge 脚本。
122
+
123
+ ```typescript
124
+ import { Native, App, Ota, Browser } from 'ota-native-bridge';
125
+
126
+ if (Native.isNativePlatform()) {
127
+ App.getInfo().then(console.log);
128
+ Ota.check('用户ID');
129
+ Browser.open('https://example.com');
130
+ }
131
+ ```
132
+
133
+ **禁止使用 `async` / `await`**,请用 `.then()` 或 callback:
134
+
135
+ ```typescript
136
+ Ota.check('用户ID', (result, err) => {
137
+ if (err) return;
138
+ if (result.hasUpdate) console.log('有新版本');
139
+ });
140
+ ```
141
+
142
+ ### 3.2 纯 HTML(`<script>` 直引)
143
+
144
+ 无打包器时,引入 `ota-native-bridge.js` 后使用全局 `Native`:
145
+
146
+ ```html
147
+ <script src="/ota-native-bridge.js"></script>
148
+ <script>
149
+ if (Native.isNativePlatform()) {
150
+ Native.App.getInfo().then(function (info) {
151
+ console.log(info.versionName);
152
+ });
153
+ Native.Ota.check('用户ID');
154
+ Native.Browser.open('https://example.com');
155
+ }
156
+ </script>
157
+ ```
158
+
159
+ ### 3.3 TypeScript 类型
160
+
161
+ ```typescript
162
+ import type {
163
+ AppInfo,
164
+ AppChannelCodes,
165
+ AppUpdateTriggerResult,
166
+ InstallResourcePackageOptions,
167
+ } from 'ota-native-bridge';
168
+ ```
169
+
170
+ `<script>` 直引时在 `tsconfig.json` 中增加:
171
+
172
+ ```json
173
+ {
174
+ "compilerOptions": {
175
+ "types": ["ota-native-bridge/ota-native-bridge"]
176
+ }
177
+ }
178
+ ```
179
+
180
+ ### 3.4 Vue 3 示例
181
+
182
+ ```vue
183
+ <script setup lang="ts">
184
+ import { ref, onMounted } from 'vue';
185
+ import { App, Browser, Native, type AppInfo } from 'ota-native-bridge';
186
+
187
+ const isApp = Native.isNativePlatform();
188
+ const appInfo = ref<AppInfo | null>(null);
189
+
190
+ onMounted(() => {
191
+ if (!isApp) return;
192
+ App.getInfo().then((info) => {
193
+ appInfo.value = info;
194
+ });
195
+ });
196
+
197
+ function openHelp() {
198
+ const url = 'https://example.com/help';
199
+ if (!isApp) {
200
+ window.open(url, '_blank');
201
+ return;
202
+ }
203
+ Browser.open(url);
204
+ }
205
+ </script>
206
+
207
+ <template>
208
+ <div>
209
+ <p v-if="appInfo">版本:{{ appInfo.versionName }}</p>
210
+ <button type="button" @click="openHelp">帮助中心</button>
211
+ </div>
212
+ </template>
213
+ ```
214
+
215
+ 检查更新按钮:
216
+
217
+ ```vue
218
+ <script setup lang="ts">
219
+ import { Native, Ota } from 'ota-native-bridge';
220
+
221
+ function onCheckUpdate() {
222
+ if (!Native.isNativePlatform()) return;
223
+ Ota.check('用户ID', (result, err) => {
224
+ if (err) console.error(err);
225
+ else console.log('有更新?', result.hasUpdate);
226
+ });
227
+ }
228
+ </script>
229
+
230
+ <template>
231
+ <button type="button" @click="onCheckUpdate">检查更新</button>
232
+ </template>
233
+ ```
234
+
235
+ #### 封装 composable(可选)
236
+
237
+ ```typescript
238
+ // src/composables/useNativeApp.ts
239
+ import { ref } from 'vue';
240
+ import {
241
+ App,
242
+ Browser,
243
+ Native,
244
+ Ota,
245
+ type AppInfo,
246
+ } from 'ota-native-bridge';
247
+
248
+ export function useNativeApp() {
249
+ const isApp = Native.isNativePlatform();
250
+ const appInfo = ref<AppInfo | null>(null);
251
+
252
+ function loadAppInfo() {
253
+ if (!isApp) return;
254
+ App.getInfo().then((info) => {
255
+ appInfo.value = info;
256
+ });
257
+ }
258
+
259
+ function openUrl(url: string) {
260
+ if (!isApp) {
261
+ window.open(url, '_blank');
262
+ return;
263
+ }
264
+ Browser.open(url);
265
+ }
266
+
267
+ function checkUpdate(uid?: string) {
268
+ return Ota.check(uid);
269
+ }
270
+
271
+ return { isApp, appInfo, loadAppInfo, openUrl, checkUpdate };
272
+ }
273
+ ```
274
+
275
+ #### 注意事项
276
+
277
+ | 要点 | 说明 |
278
+ |------|------|
279
+ | 不用 `ready()` | 直接调插件方法即可 |
280
+ | 判断环境 | `Native.isNativePlatform()` |
281
+ | 打开外链 | `Browser.open(url)` |
282
+ | 自定义 OTA | `App.getInfo()` 里 `useCustomUpdate === true` 时,勿调 `Ota.check()`,改调 REST API |
283
+
284
+ 若项目使用 **Pinia**,可在 `stores` 的 `onMounted` 等价逻辑(如路由守卫、App.vue)中调用 composable 的 `init()`,将 `appInfo` 写入 store 供全局使用。
285
+
286
+ #### WebView 与浏览器样式一致(Vue 3)
287
+
288
+ 壳内 **System WebView** 与桌面 Chrome 并非同一渲染环境,样式差异常见。按下列约定可最大程度对齐:
289
+
290
+ **1. `index.html` viewport(必配)**
291
+
292
+ ```html
293
+ <meta name="viewport"
294
+ content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover" />
295
+ ```
296
+
297
+ **2. 安全区:头部沉浸式 + 底部原生收缩**
298
+
299
+ > **头部(`enableTop`)——沉浸式**:WebView 顶满、状态栏透明;壳注入真实 `--status-bar-height`,未适配时给**整段 navbar**加 `padding-top`。**精准判定头部为视频播放时禁止本页沉浸式**,改原生顶 margin + 色条。已适配不重复垫。顶栏也可自行 `padding-top: var(--status-bar-height)`。
300
+ >
301
+ > **底部(`enableBottom`)**:原生 margin / 色条收缩 WebView,对应 CSS inset 归零。
302
+
303
+ 默认 `enableTop / enableBottom` 均为 `true`。
304
+
305
+ 顶栏示例:
306
+
307
+ ```css
308
+ .header {
309
+ padding-top: var(--status-bar-height);
310
+ background: #6b2d8b;
311
+ }
312
+ ```
313
+
314
+ **3. 安全区背景色(前端可配)**
315
+
316
+ `app_config.json` → `safeArea`:
317
+
318
+ ```json
319
+ "safeArea": {
320
+ "enableTop": true,
321
+ "enableBottom": true,
322
+ "topBackgroundColor": "#2196F3",
323
+ "bottomBackgroundColor": "#FFFFFF"
324
+ }
325
+ ```
326
+
327
+ - `topBackgroundColor`:头部安全区 / 状态栏色条颜色;留空回退主题 `backgroundColor`(建议与顶栏同色)。
328
+ - `bottomBackgroundColor`:底部安全区色条颜色;留空回退主题 `backgroundColor`。
329
+ - 状态栏图标明暗仍由 `theme.statusBarStyle`(`light` / `dark`)控制。
330
+
331
+ 也可在运行时动态设置(见 §7.2 `Config.setNativeFeatures`):
332
+
333
+ ```typescript
334
+ Config.setNativeFeatures({
335
+ safeAreaTopBackgroundColor: '#2196F3',
336
+ safeAreaBottomBackgroundColor: '#FFFFFF',
337
+ });
338
+ ```
339
+
340
+ **4. 全屏宽高**
341
+
342
+ ```css
343
+ .page {
344
+ /* 壳注入 --vh/--dvh/--vw/--dvw(安全区内尺寸);亦可写 100dvh/100dvw(旧引擎由壳 polyfill) */
345
+ width: 100vw;
346
+ width: 100dvw;
347
+ width: calc(var(--dvw, var(--vw, 1vw)) * 100);
348
+ min-height: 100vh;
349
+ min-height: 100dvh;
350
+ min-height: calc(var(--dvh, var(--vh, 1vh)) * 100);
351
+ }
352
+ ```
353
+
354
+ **5. 关闭壳内安全区(纯前端自管时)**
355
+
356
+ 关闭对应方向后,该方向不再自动适配(头部不再 `nativeApplyTop`,底部不再 margin 收缩),由前端自行用 `env(safe-area-inset-*)` / CSS 变量适配:
357
+
358
+ ```json
359
+ "safeArea": { "enableTop": false, "enableBottom": false }
360
+ ```
361
+
362
+ **6. 读取安全区(脚本)**
363
+
364
+ ```typescript
365
+ Viewport.getSafeAreaInsets().then((insets) => console.log(insets));
366
+ // 或 window.__SAFE_AREA__(壳注入;enableTop 时 top/statusBarHeight 为真实值)
367
+ ```
368
+
369
+ **7. 调试**
370
+
371
+ Android:`chrome://inspect` 连接 WebView,对比变量与 Chrome DevTools 手机模拟器。
372
+
373
+ #### WebView CSS 变量(推荐)
374
+
375
+ 壳在 **文档最早阶段**(`WebViewCompat.addDocumentStartJavaScript`)注入 CSS 变量,前端可直接用于安全区与视口适配:
376
+
377
+ > 注意:`enableTop=true` 时顶部 inset / `--status-bar-height` 为**真实值**(沉浸式);`enableBottom=true` 时底部 inset 为 `0`(已由原生收缩)。
378
+
379
+ | CSS 变量 | 含义(App 全屏 WebView) |
380
+ |----------|-------------------------|
381
+ | `--status-bar-height` | 状态栏高度(`enableTop` 时为真实值) |
382
+ | `--window-top` / `--window-bottom` | 原生导航/TabBar 占位(本壳为 0,TabBar 由 H5 自绘) |
383
+ | `--safe-area-inset-top/bottom/left/right` | 安全区 inset(底部在 `enableBottom` 时为 0) |
384
+ | `--safe-area-top` / `--safe-area-bottom` | 安全区顶/底(与 inset 同值) |
385
+ | `--vh` / `--dvh` / `--svh` / `--lvh` | 视口高度的 1%;`100vh/100dvh` 在旧引擎由壳改写为 `calc(var(--unit)*100)` |
386
+ | `--vw` / `--dvw` / `--svw` / `--lvw` | 视口宽度的 1%;`100vw/100dvw` 同上 |
387
+
388
+ ```css
389
+ /* 顶部状态栏占位 */
390
+ .status-bar {
391
+ height: var(--status-bar-height);
392
+ width: 100%;
393
+ }
394
+
395
+ .page {
396
+ width: 100vw;
397
+ width: 100dvw;
398
+ width: calc(var(--dvw, var(--vw, 1vw)) * 100);
399
+ min-height: 100vh;
400
+ min-height: 100dvh;
401
+ min-height: calc(var(--dvh, var(--vh, 1vh)) * 100);
402
+ padding-bottom: var(--safe-area-inset-bottom);
403
+ }
404
+ ```
405
+
406
+ 脚本获取(`getWindowInfo()`):
407
+
408
+ ```typescript
409
+ Viewport.getWindowInfo().then((win) => {
410
+ console.log(win.statusBarHeight, win.safeAreaInsets);
411
+ });
412
+ ```
413
+
414
+ ---
415
+
416
+ ## 4. 基本调用流程
417
+
418
+ ```typescript
419
+ import { Native, App, Ota } from 'ota-native-bridge';
420
+
421
+ if (Native.isNativePlatform()) {
422
+ App.getInfo().then((info) => console.log(info.versionName));
423
+ Ota.check('用户ID');
424
+ }
425
+ ```
426
+
427
+ | 步骤 | 写法 | 说明 |
428
+ |------|------|------|
429
+ | 1 | `Native.isNativePlatform()` | 是否在壳 App 里 |
430
+ | 2 | `App.getInfo()` | 读版本、OTA 配置 |
431
+ | 3 | `Ota.check('用户ID')` | 触发检查更新 |
432
+ | 4 | `Browser.open(url)` | 系统浏览器打开链接 |
433
+
434
+ **SDK 版本:**
435
+
436
+ ```typescript
437
+ import { SDK_VERSION, Native } from 'ota-native-bridge';
438
+ // Native.sdkVersion 或 SDK_VERSION
439
+ ```
440
+
441
+ 发版时请与三端壳内 `OtaConstants.SDK_VERSION` 及 `package.json` 的 `version` 保持一致。
442
+
443
+ ---
444
+
445
+ ## 5. OTA 更新(核心)
446
+
447
+ OTA 行为分两层:`platform.otaEnabled`(`platformId` + `apiKey` + `paramPublicKey` 已齐,Client API 可用)与 **`app_config.json` → `update.useCustomUpdate`**(谁负责更新 UI)。前端通过 `App.getInfo()` 读取;原生更新 = `otaEnabled && !useCustomUpdate`。
448
+
449
+ ### 5.1 原生更新模式(默认)
450
+
451
+ `useCustomUpdate: false`(或未配置)时:
452
+
453
+ - 壳负责连接 OTA、检测更新、弹窗、下载、安装(视平台与推送类型而定)。
454
+ - 前端调用 **`Ota.check('用户ID')`** 或 **`Ota.checkUpdate(...)`** 仅**触发**原生流程,**不会**返回 `downloadUrl`。
455
+
456
+ ```typescript
457
+ import { Ota } from 'ota-native-bridge';
458
+
459
+ // 最简单:一行检查更新
460
+ Ota.check('user-123');
461
+
462
+ // 需要更多选项时
463
+ Ota.checkUpdate({ uid: 'user-123', notifyWhenNoUpdate: false }).then((result) => {
464
+ console.log(result.hasUpdate, result.handledByNative);
465
+ });
466
+ ```
467
+
468
+ **`Ota.check` / `Ota.checkUpdate` 返回示例:**
469
+
470
+ ```json
471
+ {
472
+ "success": true,
473
+ "hasUpdate": true,
474
+ "handledByNative": true,
475
+ "message": "update dialog shown"
476
+ }
477
+ ```
478
+
479
+ 无更新时:
480
+
481
+ ```json
482
+ {
483
+ "success": true,
484
+ "hasUpdate": false,
485
+ "handledByNative": true,
486
+ "message": "already latest"
487
+ }
488
+ ```
489
+
490
+ **注意:** 此模式下请勿依赖 JS 自行下载安装包完成整包更新;资源包/安装包安装请使用下文 `installResourcePackage` / `installAppPackage`(通常由原生弹窗流程调用,自定义流程也可主动调用)。
491
+
492
+ ### 5.2 自定义更新模式
493
+
494
+ `app_config.json` 设置 `useCustomUpdate: true`;**API 地址与密钥**在壳工程 `OtaConstants` 源码中写死(见 §6.1)。
495
+
496
+ 此模式下:
497
+
498
+ | 行为 | 说明 |
499
+ |------|------|
500
+ | 自定义 OTA | `App.getInfo()` 里 `useCustomUpdate === true` 时,勿调 `Ota.check()`,改调 REST API |
501
+ | `Ota.check()` / `Ota.checkUpdate()` | **会失败**,请勿调用 |
502
+ | Android WebSocket | 壳**不再**连接 OTA WebSocket |
503
+ | 原生检测/弹窗 | **不执行**,由前端完全接管 |
504
+
505
+ 前端需自行:
506
+
507
+ 1. 使用 `App.getInfo()` 获取 `platform.apiBaseUrl`、`platform.apiKey`、`platform.paramPublicKey`。
508
+ 2. 调用客户端 REST(须 POST + JSON;**业务 JSON 必须先用平台公钥加密**,见 §5.4):
509
+ - `POST {apiBaseUrl}/api/client/v1/update/check`
510
+ - `POST {apiBaseUrl}/api/client/v1/update/download-url`
511
+ - 按需:`update/check-report`、`update/record` 等
512
+ 3. 连接推送:`ws(s)://{host}/api/client/v1/ws/push`,首条消息发送**加密信封**(明文含 `action: subscribe`):
513
+
514
+ **自定义模式示例(检测 + 安装资源包):**
515
+
516
+ ```typescript
517
+ import { App, Ota, Crypto } from 'ota-native-bridge';
518
+
519
+ App.getInfo().then((info) => {
520
+ if (!info.useCustomUpdate) {
521
+ Ota.check();
522
+ return;
523
+ }
524
+
525
+ const base = info.platform?.apiBaseUrl?.replace(/\/$/, '');
526
+ const pem = info.platform!.paramPublicKey!;
527
+ const plain = {
528
+ platformCode: info.platform!.platformId,
529
+ apiKey: info.platform!.apiKey,
530
+ versionName: info.versionName,
531
+ versionCode: info.versionCode,
532
+ resourceVersion: info.resourceVersion,
533
+ };
534
+
535
+ // 所有 Client API 请求体必须用平台公钥加密(明文直传会被服务端拒绝)
536
+ return Crypto.postEncrypted(`${base}/api/client/v1/update/check`, plain, pem).then((checkRes: any) => {
537
+ if (!checkRes.data?.hasUpdate) return;
538
+
539
+ return Crypto.postEncrypted(
540
+ `${base}/api/client/v1/update/download-url`,
541
+ {
542
+ ...plain,
543
+ pushId: checkRes.data.pushId,
544
+ updateType: checkRes.data.updateType,
545
+ },
546
+ pem,
547
+ ).then((urlRes: any) => {
548
+ const downloadUrl = urlRes.data?.downloadUrl;
549
+ if (!downloadUrl) return;
550
+
551
+ return Ota.installResourcePackage({
552
+ url: downloadUrl,
553
+ restart: true,
554
+ pushId: checkRes.data.pushId,
555
+ version: checkRes.data.version,
556
+ });
557
+ });
558
+ });
559
+ });
560
+ ```
561
+
562
+ **`update/check` 返回示例:**
563
+
564
+ ```json
565
+ {
566
+ "code": 200,
567
+ "message": "success",
568
+ "data": {
569
+ "hasUpdate": true,
570
+ "version": "1.2.0",
571
+ "updateType": 1,
572
+ "forceUpdate": 0,
573
+ "updateDesc": "修复若干问题",
574
+ "pushId": 10086
575
+ }
576
+ }
577
+ ```
578
+
579
+ **`update/download-url` 返回示例:**
580
+
581
+ ```json
582
+ {
583
+ "code": 200,
584
+ "message": "success",
585
+ "data": {
586
+ "pushId": 10086,
587
+ "downloadUrl": "https://cdn.example.com/www-1.2.0.zip"
588
+ }
589
+ }
590
+ ```
591
+
592
+ **`Ota.installResourcePackage` 返回示例:**
593
+
594
+ ```json
595
+ {
596
+ "success": true,
597
+ "needsRestart": true,
598
+ "restarted": true,
599
+ "message": "ok"
600
+ }
601
+ ```
602
+
603
+ WebSocket 订阅同样须发送加密信封(解密后明文含 `action: subscribe` + `platformCode` + `apiKey`):
604
+
605
+ ```typescript
606
+ Crypto.encryptRequestBody(
607
+ {
608
+ action: 'subscribe',
609
+ platformCode: info.platform!.platformId,
610
+ apiKey: info.platform!.apiKey,
611
+ osPlatform: 'Android',
612
+ },
613
+ info.platform!.paramPublicKey!,
614
+ ).then((envelope) => {
615
+ ws.send(JSON.stringify(envelope));
616
+ });
617
+ ```
618
+
619
+ **订阅成功后服务端推送示例:**
620
+
621
+ ```json
622
+ {
623
+ "type": "push_notify",
624
+ "event": "upsert",
625
+ "data": {
626
+ "hasUpdate": true,
627
+ "version": "1.2.0",
628
+ "updateType": 1,
629
+ "forceUpdate": 0,
630
+ "pushId": 10086
631
+ }
632
+ }
633
+ ```
634
+
635
+ ### 5.3 安装类插件 API(两种模式均可)
636
+
637
+ | 插件方法 | 说明 |
638
+ |------|------|
639
+ | `Ota.installResourcePackage(options)` | 下载 ZIP,解压到应用内 `www/`;`restart` 默认 `true`;传 `version` + `pushId` 可自动上报 `update/record` |
640
+ | `Ota.installAppPackage(options)` | 下载 APK(或平台安装包)并调起系统安装界面 |
641
+ | `Ota.applyResourceUpdate(url)` | 安装资源包,**不**自动重启 |
642
+ | `Ota.checkResourceUpdate(url?)` | 按 URL 检测资源包更新 |
643
+ | `Ota.checkApkUpdate(url?)` | 按 URL 检测 APK 更新 |
644
+
645
+ ```typescript
646
+ import { Ota } from 'ota-native-bridge';
647
+
648
+ Ota.installResourcePackage({
649
+ url: 'https://cdn.example.com/www-1.0.1.zip',
650
+ restart: true,
651
+ pushId: 1001,
652
+ version: '1.0.1',
653
+ uid: 'user-123',
654
+ });
655
+ // 返回示例:{ "success": true, "needsRestart": true, "restarted": true, "message": "ok" }
656
+
657
+ Ota.installAppPackage({
658
+ url: 'https://cdn.example.com/app-1.0.2.apk',
659
+ pushId: 1002,
660
+ version: '1.0.2',
661
+ });
662
+ // 返回示例:{ "success": true, "message": "install intent started" }
663
+
664
+ Ota.checkResourceUpdate().then(console.log);
665
+ // 返回示例:{ "hasUpdate": true, "version": "1.0.1", "url": "https://...", "force": false }
666
+
667
+ Ota.checkApkUpdate().then(console.log);
668
+ // 返回示例:{ "hasUpdate": true, "versionCode": 12, "versionName": "1.0.2", "url": "https://...", "force": false }
669
+ ```
670
+
671
+ ### 5.4 Client API 请求参数加密(必选)
672
+
673
+ 凡 H5 / 自定义逻辑向 `/api/client/v1/**` 发起的 JSON POST(含 WebSocket 首条 subscribe),**必须**使用创建平台时生成的**参数公钥**加密。明文直传会被服务端拒绝(HTTP 400)。
674
+
675
+ 公钥来源:
676
+
677
+ - 壳内:`App.getInfo().platform.paramPublicKey`(来自 `app_config.json` → `platform.paramPublicKey`)
678
+ - 独立 Stat SDK:初始化时传入 `paramPublicKey`
679
+
680
+ 算法:RSA-OAEP(SHA-256) 包装 AES-256-GCM,信封:
681
+
682
+ ```json
683
+ {
684
+ "v": 1,
685
+ "platformCode": "my-platform",
686
+ "ek": "<Base64>",
687
+ "iv": "<Base64>",
688
+ "ct": "<Base64 ciphertext||tag>"
689
+ }
690
+ ```
691
+
692
+ SDK 封装:
693
+
694
+ ```typescript
695
+ import { Crypto } from 'ota-native-bridge';
696
+
697
+ // 仅加密(禁止 await)
698
+ Crypto.encryptRequestBody(
699
+ { platformCode: 'my-platform', apiKey: 'xxxxxxxxxxxxxxxxxxxx', /* ... */ },
700
+ paramPublicKeyPem,
701
+ ).then((envelope) => {
702
+ // 返回示例:{ "v": 1, "platformCode": "my-platform", "ek": "...", "iv": "...", "ct": "..." }
703
+ console.log(envelope);
704
+ });
705
+
706
+ // 加密并 POST,解析服务端 JSON
707
+ Crypto.postEncrypted(
708
+ 'https://otaapi.appupgrade.vip/api/client/v1/update/check',
709
+ { platformCode: 'my-platform', apiKey: 'xxxxxxxxxxxxxxxxxxxx', versionName: '1.0.0' },
710
+ paramPublicKeyPem,
711
+ ).then((res) => {
712
+ // 返回示例:{ "code": 200, "message": "success", "data": { "hasUpdate": false } }
713
+ console.log(res);
714
+ });
715
+ ```
716
+
717
+ 纯 HTML 全局:`Native.Crypto.encryptRequestBody` / `Native.Crypto.postEncrypted`。
718
+
719
+ ---
720
+
721
+ ## 6. 配置文件分工
722
+
723
+ ### 6.1 `OtaConstants`(OTA 请求地址,代码写死)
724
+
725
+ **不由** `www/app_config.json` 提供,也不允许 init 参数或打包配置覆盖,避免前端资源包热更新或部署环境把流量打到错误主机。三端壳与各 Stat SDK 均写死为 `https://otaapi.appupgrade.vip`。
726
+
727
+ | 平台 | 文件 |
728
+ |------|------|
729
+ | Android | `OpenAndroidPackage/.../ota/OtaConstants.kt` |
730
+ | iOS | `OpenIOSPackage/OpenIOS/OTA/OtaConstants.swift` |
731
+ | HarmonyOS | `OpenHarmonyPackage/entry/src/main/ets/ota/OtaConstants.ets` |
732
+
733
+ Android 示例(`OtaConstants.kt`):
734
+
735
+ ```kotlin
736
+ const val API_BASE_URL = "https://otaapi.appupgrade.vip"
737
+ const val PLATFORM_ID = "android"
738
+ const val API_KEY = "01234567890123456789"
739
+ const val AUTO_CHECK_UPDATE_ON_LAUNCH = true
740
+ ```
741
+
742
+ iOS 对应字段:`apiBaseUrl`、`platformId`、`apiKey`、`autoCheckUpdateOnLaunch`。HarmonyOS 对应:`API_BASE_URL`、`PLATFORM_ID`、`API_KEY`、`AUTO_CHECK_UPDATE_ON_LAUNCH`。
743
+
744
+ | 常量 | 说明 |
745
+ |------|------|
746
+ | API 根地址 | REST / WebSocket 均基于此;**写死,不允许配置** |
747
+ | 平台 ID | 对应 REST 的 `platformCode` |
748
+ | Api 秘钥 | 20 位,与后台「平台管理」一致 |
749
+ | 启动自动检测 | 原生模式下进入主界面是否自动 `Ota.checkUpdate()` |
750
+
751
+ 管理后台打包会把模板 `OtaConstants` 的 API 根地址再次写成同一源站,**不会**用 worker 的 `app.client-api.public-base-url` 覆盖。平台密钥仍写入 `app_config.json`。
752
+
753
+ ### 6.2 `app_config.json`(前端与 UI,可随 www 更新)
754
+
755
+ 路径:`www/app_config.json`(资源热更新后可为 `filesDir/www/app_config.json`)。
756
+
757
+ **OTA 请求地址勿写在此文件。** 仅保留 UI / 行为类配置,例如:
758
+
759
+ ```json
760
+ {
761
+ "packageName": "com.example.app",
762
+ "appName": "示例 App",
763
+ "url": "/",
764
+ "platform": {
765
+ "platformId": "my-platform",
766
+ "apiKey": "xxxxxxxxxxxxxxxxxxxx",
767
+ "paramPublicKey": "-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----"
768
+ },
769
+ "safeArea": {
770
+ "enableTop": true,
771
+ "enableBottom": true,
772
+ "topBackgroundColor": "",
773
+ "bottomBackgroundColor": ""
774
+ },
775
+ "theme": {
776
+ "backgroundColor": "#FFFFFF",
777
+ "statusBarStyle": "light"
778
+ },
779
+ "update": {
780
+ "useCustomUpdate": false
781
+ }
782
+ }
783
+ ```
784
+
785
+ | 字段 | 说明 |
786
+ |------|------|
787
+ | `url` | WebView 入口 |
788
+ | `platform.paramPublicKey` | 创建平台时生成的参数加密公钥(Client API / Stat 加密必填) |
789
+ | `update.useCustomUpdate` | 是否由前端完全接管更新流程 |
790
+ | `safeArea.enableTop` / `enableBottom` | 头部沉浸式适配 / 底部原生收缩(默认 `true`) |
791
+ | `safeArea.topBackgroundColor` / `bottomBackgroundColor` | 头部/底部安全区色条颜色,留空回退 `theme.backgroundColor` |
792
+ | `theme` / `guide` 等 | 界面与功能开关(**开屏广告不在此配置**,由管理后台 OTA 下发,见 [OTA_PROTOCOL.md](../../docs/OTA_PROTOCOL.md)) |
793
+
794
+ ### 6.3 `App.getInfo()` 中的 `platform`
795
+
796
+ `platform` 由壳合并下发:
797
+
798
+ | 字段 | 来源 | 说明 |
799
+ |------|------|------|
800
+ | `platformId` / `apiKey` | `app_config.json → platform`,缺省回退 `OtaConstants` | 鉴权 |
801
+ | `apiBaseUrl` | `OtaConstants` 写死 | Client API 根地址,不允许配置 |
802
+ | `paramPublicKey` | `app_config.json → platform.paramPublicKey`(兼容 `clientParamPublicKey`) | **Client API 请求加密公钥** |
803
+ | `otaEnabled` | Client API 凭证已齐(不等于原生更新已接管) | 布尔 |
804
+
805
+ 自定义更新或 H5 直调 Client API 时,务必使用 `paramPublicKey` 经 `Crypto.encryptRequestBody` / `postEncrypted` 加密。
806
+
807
+ ---
808
+
809
+ ## 7. API 参考
810
+
811
+ 以下按 **插件** 分组;均可通过 `Native.Plugins.*` 或直接 `import { App, Ota, Crypto, ... }` 调用。每个用法附**返回示例**。
812
+
813
+ > **约定:文档与业务代码均禁止 `await` / `async`。** API 返回 Promise,请用 `.then()` / `.catch()` 或 callback 参数。
814
+
815
+ ### 7.1 连接与信息
816
+
817
+ #### `Native.whenReady(timeoutMs?)`
818
+
819
+ ```typescript
820
+ Native.whenReady(8000).then(() => {
821
+ // 成功:无返回值(Promise<void>)
822
+ }).catch((err) => {
823
+ // 失败:Error("Bridge timeout")
824
+ console.error(err);
825
+ });
826
+ ```
827
+
828
+ #### `App.ping()`
829
+
830
+ ```typescript
831
+ App.ping().then(console.log);
832
+ ```
833
+
834
+ 返回示例:
835
+
836
+ ```json
837
+ { "pong": true, "ts": 1720000000000 }
838
+ ```
839
+
840
+ #### `App.getInfo()`
841
+
842
+ ```typescript
843
+ App.getInfo().then(console.log);
844
+ ```
845
+
846
+ 返回示例:
847
+
848
+ ```json
849
+ {
850
+ "appName": "示例 App",
851
+ "packageName": "com.example.app",
852
+ "configPackageName": "com.example.app",
853
+ "versionName": "1.0.0",
854
+ "versionCode": 1,
855
+ "url": "/",
856
+ "wwwVersion": "1.0.0",
857
+ "resourceVersion": "1.0.0",
858
+ "useCustomUpdate": false,
859
+ "frontendChannelCode": "ADC-T3Z8JC",
860
+ "channelCode": "CH-STAT",
861
+ "adCode": "AD-001",
862
+ "resourceCheckUrl": "",
863
+ "apkCheckUrl": "",
864
+ "safeArea": { "enableTop": true, "enableBottom": true, "topBackgroundColor": "", "bottomBackgroundColor": "" },
865
+ "guideEnabled": false,
866
+ "adSplashEnabled": false,
867
+ "highPerformanceMode": false,
868
+ "platform": {
869
+ "platformId": "my-platform",
870
+ "apiKey": "xxxxxxxxxxxxxxxxxxxx",
871
+ "apiBaseUrl": "https://otaapi.appupgrade.vip",
872
+ "paramPublicKey": "-----BEGIN PUBLIC KEY-----\\n...\\n-----END PUBLIC KEY-----",
873
+ "otaEnabled": true
874
+ }
875
+ }
876
+ ```
877
+
878
+ 未填写的码返回空字符串 `""`。`Ota.setChannel` 只影响后续 OTA 上报的前端渠道,**不会**改这里的绑定值。
879
+
880
+ #### `App.getChannelCodes()`
881
+
882
+ 读取打包写入的前端渠道码、统计渠道码、广告码(与 `App.getInfo()` 中同名字段一致)。
883
+
884
+ ```typescript
885
+ App.getChannelCodes().then((codes) => {
886
+ console.log(codes.frontendChannelCode, codes.channelCode, codes.adCode);
887
+ });
888
+ ```
889
+
890
+ 返回示例:
891
+
892
+ ```json
893
+ {
894
+ "frontendChannelCode": "ADC-T3Z8JC",
895
+ "channelCode": "CH-STAT",
896
+ "adCode": "AD-001"
897
+ }
898
+ ```
899
+
900
+ 对应 `app_config.json` → `stat.frontendChannel` / `stat.channel` / `stat.adCode`。
901
+
902
+ #### `Device.getInfo()`
903
+
904
+ ```typescript
905
+ Device.getInfo().then(console.log);
906
+ ```
907
+
908
+ 返回示例:
909
+
910
+ ```json
911
+ {
912
+ "brand": "Xiaomi",
913
+ "manufacturer": "Xiaomi",
914
+ "model": "2201123G",
915
+ "device": "mondrian",
916
+ "androidId": "a1b2c3d4e5f6g7h8",
917
+ "screenWidth": 1080,
918
+ "screenHeight": 2400,
919
+ "density": 2.75,
920
+ "networkType": "WIFI",
921
+ "carrierName": "",
922
+ "orientation": "portrait",
923
+ "rotation": 0,
924
+ "screenLocked": false
925
+ }
926
+ ```
927
+
928
+ > iOS 可能不含 `androidId`;Harmony 字段名与系统能力对齐。`androidId` 仅在合规开关允许时返回。
929
+
930
+ #### `Device.getScreenInfo()`
931
+
932
+ 物理分辨率(px / dp)。CSS 视口请用 `Viewport.getWindowInfo()`。
933
+
934
+ ```typescript
935
+ Device.getScreenInfo().then(console.log);
936
+ ```
937
+
938
+ ```json
939
+ {
940
+ "widthPx": 1080,
941
+ "heightPx": 2400,
942
+ "widthDp": 392,
943
+ "heightDp": 872,
944
+ "density": 2.75,
945
+ "densityDpi": 440,
946
+ "xdpi": 440,
947
+ "ydpi": 440
948
+ }
949
+ ```
950
+
951
+ #### `Device.getOrientation()`
952
+
953
+ ```typescript
954
+ Device.getOrientation().then(console.log);
955
+ ```
956
+
957
+ ```json
958
+ {
959
+ "orientation": "portrait",
960
+ "rotation": 0,
961
+ "portrait": true,
962
+ "landscape": false
963
+ }
964
+ ```
965
+
966
+ `orientation` 为 `portrait` / `landscape` / `unknown`;`rotation` 为 `0` / `90` / `180` / `270`。
967
+
968
+ #### `Device.getLockStatus()`
969
+
970
+ ```typescript
971
+ Device.getLockStatus().then(console.log);
972
+ ```
973
+
974
+ ```json
975
+ {
976
+ "locked": false,
977
+ "keyguardLocked": false,
978
+ "deviceLocked": false,
979
+ "secure": true,
980
+ "supported": true
981
+ }
982
+ ```
983
+
984
+ > Android 使用 `KeyguardManager`。iOS 在保护数据不可用时视为锁屏。Harmony 若系统未暴露锁屏查询则 `supported: false`(前台可调 Bridge 时通常已解锁)。
985
+
986
+ #### `Device.getSystemInfo()`
987
+
988
+ ```typescript
989
+ Device.getSystemInfo().then(console.log);
990
+ ```
991
+
992
+ 返回示例:
993
+
994
+ ```json
995
+ {
996
+ "os": "Android",
997
+ "sdkInt": 34,
998
+ "release": "14",
999
+ "incremental": "UKQ1.230917.001",
1000
+ "locale": "zh-CN",
1001
+ "timezone": "Asia/Shanghai",
1002
+ "abi": "arm64-v8a"
1003
+ }
1004
+ ```
1005
+
1006
+ #### `Config.getNativeConfig()` / `Config.setNativeFeatures(options)`
1007
+
1008
+ ```typescript
1009
+ Config.getNativeConfig().then(console.log);
1010
+ Config.setNativeFeatures({
1011
+ safeAreaTopBackgroundColor: '#2196F3',
1012
+ primaryColor: '#1677ff',
1013
+ }).then(console.log);
1014
+ ```
1015
+
1016
+ 返回示例(二者结构相同):
1017
+
1018
+ ```json
1019
+ {
1020
+ "safeArea": { "enableTop": true, "enableBottom": true, "topBackgroundColor": "#2196F3", "bottomBackgroundColor": "#FFFFFF" },
1021
+ "guide": { "enabled": false },
1022
+ "adSplash": { "enabled": false },
1023
+ "highPerformanceMode": false,
1024
+ "theme": {
1025
+ "primaryColor": "#1677ff",
1026
+ "backgroundColor": "#FFFFFF",
1027
+ "statusBarStyle": "light",
1028
+ "navigationBarStyle": "light"
1029
+ },
1030
+ "location": { "enabled": false, "highAccuracy": true },
1031
+ "videoPlayer": { "enabled": false },
1032
+ "platform": {
1033
+ "platformId": "my-platform",
1034
+ "apiKey": "xxxxxxxxxxxxxxxxxxxx",
1035
+ "apiBaseUrl": "https://otaapi.appupgrade.vip",
1036
+ "paramPublicKey": "-----BEGIN PUBLIC KEY-----\\n...\\n-----END PUBLIC KEY-----",
1037
+ "otaEnabled": true
1038
+ }
1039
+ }
1040
+ ```
1041
+
1042
+ ### 7.2 主题与安全区
1043
+
1044
+ #### `Theme.get()` / `Theme.set(options)`
1045
+
1046
+ ```typescript
1047
+ Theme.get().then(console.log);
1048
+ Theme.set({ primaryColor: '#1677ff', statusBarStyle: 'dark' }).then(console.log);
1049
+ ```
1050
+
1051
+ 返回示例:
1052
+
1053
+ ```json
1054
+ {
1055
+ "primaryColor": "#1677ff",
1056
+ "backgroundColor": "#FFFFFF",
1057
+ "statusBarStyle": "dark",
1058
+ "navigationBarStyle": "light"
1059
+ }
1060
+ ```
1061
+
1062
+ #### `Viewport.getSafeAreaInsets()` / `Viewport.refreshSafeArea()`
1063
+
1064
+ ```typescript
1065
+ Viewport.getSafeAreaInsets().then(console.log);
1066
+ Viewport.refreshSafeArea().then(console.log);
1067
+ ```
1068
+
1069
+ 返回示例:
1070
+
1071
+ ```json
1072
+ {
1073
+ "top": 0,
1074
+ "bottom": 0,
1075
+ "left": 0,
1076
+ "right": 0,
1077
+ "topPx": 0,
1078
+ "bottomPx": 0,
1079
+ "enableTop": true,
1080
+ "enableBottom": true,
1081
+ "topBackgroundColor": "#2196F3",
1082
+ "bottomBackgroundColor": "#FFFFFF"
1083
+ }
1084
+ ```
1085
+
1086
+ #### `Viewport.getWindowInfo()`
1087
+
1088
+ ```typescript
1089
+ Viewport.getWindowInfo().then(console.log);
1090
+ ```
1091
+
1092
+ 返回示例:
1093
+
1094
+ ```json
1095
+ {
1096
+ "pixelRatio": 3,
1097
+ "screenWidth": 390,
1098
+ "screenHeight": 844,
1099
+ "windowWidth": 390,
1100
+ "windowHeight": 780,
1101
+ "windowTop": 0,
1102
+ "windowBottom": 0,
1103
+ "statusBarHeight": 0,
1104
+ "safeArea": { "left": 0, "right": 390, "top": 0, "bottom": 780, "width": 390, "height": 780 },
1105
+ "safeAreaInsets": { "top": 0, "bottom": 0, "left": 0, "right": 0 }
1106
+ }
1107
+ ```
1108
+
1109
+ ### 7.3 桌面图标
1110
+
1111
+ ```typescript
1112
+ Icon.list().then(console.log);
1113
+ // 返回示例:
1114
+ // {
1115
+ // "icons": [
1116
+ // { "id": "default", "label": "默认" },
1117
+ // { "id": "alt1", "label": "图标1" },
1118
+ // { "id": "custom", "label": "自定义", "custom": true }
1119
+ // ],
1120
+ // "current": {
1121
+ // "iconId": "default",
1122
+ // "label": "默认",
1123
+ // "replacesExistingIcon": true,
1124
+ // "launcherEntryCount": 1,
1125
+ // "customIconPath": "",
1126
+ // "customIconExists": false,
1127
+ // "supportsCustomFromUrl": true
1128
+ // }
1129
+ // }
1130
+
1131
+ Icon.get().then(console.log);
1132
+ // 返回示例:同 current 对象
1133
+
1134
+ Icon.set({ iconId: 'alt1' }).then(console.log);
1135
+ // 返回示例:{ "success": true, "iconId": "alt1", "message": "ok", "requiresLauncherRefresh": false }
1136
+
1137
+ Icon.setFromUrl({ url: 'https://cdn.example.com/icon.png' }).then(console.log);
1138
+ // 返回示例:{ "success": true, "iconId": "custom", "message": "ok" }
1139
+
1140
+ Icon.setFromBase64({ base64: 'iVBORw0KGgo...' }).then(console.log);
1141
+ // 返回示例:{ "success": true, "iconId": "custom", "message": "ok" }
1142
+ ```
1143
+
1144
+ ### 7.4 通知与角标
1145
+
1146
+ ```typescript
1147
+ Notification.show({ title: '更新提醒', body: '有新版本可用', badge: 1 }).then(console.log);
1148
+ // 返回示例:{ "success": true, "id": 1, "message": "shown" }
1149
+
1150
+ Notification.setBadgeCount(3).then(console.log);
1151
+ // 返回示例:{ "success": true, "count": 3 }
1152
+ ```
1153
+
1154
+ ### 7.5 打开外部应用与系统浏览器
1155
+
1156
+ ```typescript
1157
+ Browser.open('https://example.com/help').then(console.log);
1158
+ // 返回示例:{ "success": true, "message": "ok", "target": "https://example.com/help" }
1159
+
1160
+ App.launch({
1161
+ packageName: 'com.tencent.mm',
1162
+ fallbackUrl: 'https://weixin.qq.com/',
1163
+ }).then(console.log);
1164
+ // 返回示例:{ "success": true, "message": "launched", "target": "com.tencent.mm" }
1165
+
1166
+ App.isInstalled('com.tencent.mm').then(console.log);
1167
+ // 返回示例:{ "packageName": "com.tencent.mm", "installed": true }
1168
+
1169
+ App.checkInstalled(['com.tencent.mm', 'com.eg.android.AlipayGphone']).then(console.log);
1170
+ // 返回示例:{
1171
+ // "apps": [
1172
+ // { "packageName": "com.tencent.mm", "installed": true },
1173
+ // { "packageName": "com.eg.android.AlipayGphone", "installed": false }
1174
+ // ]
1175
+ // }
1176
+ ```
1177
+
1178
+ ### 7.6 定位
1179
+
1180
+ ```typescript
1181
+ Location.getStatus().then(console.log);
1182
+ // 返回示例:{ "enabled": true, "highAccuracy": true, "permissionGranted": false }
1183
+
1184
+ Location.requestPermission().then(console.log);
1185
+ // 返回示例:{ "success": true, "granted": true, "message": "granted" }
1186
+
1187
+ Location.getCurrent({ highAccuracy: true, timeoutMs: 15000 }).then(console.log);
1188
+ // 返回示例:{
1189
+ // "success": true,
1190
+ // "latitude": 31.2304,
1191
+ // "longitude": 121.4737,
1192
+ // "accuracy": 12.5,
1193
+ // "altitude": 4.2,
1194
+ // "speed": 0,
1195
+ // "bearing": 0,
1196
+ // "timestamp": 1720000000000,
1197
+ // "provider": "gps"
1198
+ // }
1199
+
1200
+ Location.startWatch({ watchId: 'w1', intervalMs: 3000 }).then(console.log);
1201
+ // 返回示例:{ "success": true, "watchId": "w1", "intervalMs": 3000 }
1202
+
1203
+ Location.stopWatch('w1').then(console.log);
1204
+ // 返回示例:{ "success": true, "watchId": "w1" }
1205
+ ```
1206
+
1207
+ 持续定位回调:
1208
+
1209
+ ```typescript
1210
+ window.__nativeBridgeLocationUpdate = (payload) => {
1211
+ console.log(payload);
1212
+ };
1213
+ // payload 示例:
1214
+ // {
1215
+ // "watchId": "w1",
1216
+ // "location": { "latitude": 31.23, "longitude": 121.47, "accuracy": 10, "timestamp": 1720000001000 }
1217
+ // }
1218
+ ```
1219
+
1220
+ 需在 `app_config.json` 中启用 `location.enabled: true`。
1221
+
1222
+ ### 7.7 视频
1223
+
1224
+ ```typescript
1225
+ Media.getVideoPlayerStatus().then(console.log);
1226
+ // 返回示例:{ "enabled": true, "supportedFormats": ["mp4", "m3u8"] }
1227
+
1228
+ Media.playVideo({ url: 'https://cdn.example.com/demo.mp4', title: '演示', autoplay: true }).then(console.log);
1229
+ // 返回示例:{ "success": true, "message": "playing" }
1230
+ ```
1231
+
1232
+ Android 8–9 系统 WebView 无法稳定页内播 HLS 时,应调用 `Media.playVideo` 走壳 ExoPlayer。iOS 走全屏 AVPlayer。Android / iOS 均不强制 `videoPlayer.enabled: true`。
1233
+
1234
+ ### 7.8 HTTP(原生请求)
1235
+
1236
+ ```typescript
1237
+ import { Http } from 'ota-native-bridge';
1238
+
1239
+ Http.request({
1240
+ url: 'https://api.example.com/v1/feed',
1241
+ method: 'GET',
1242
+ headers: { Authorization: 'Bearer xxx' },
1243
+ timeout: 30000,
1244
+ }).then(console.log);
1245
+ // 返回示例:{ status: 200, statusText: "OK", headers: { ... }, data: "{...}", url: "https://..." }
1246
+ ```
1247
+
1248
+ 用于 Android 8–9:页面源是 `https://appassets.androidplatform.net` 时,WebView XHR 跨域常直接 Network Error。GET/HEAD 不要带 JSON `Content-Type`。Android / iOS / Harmony 壳均已实现。
1249
+
1250
+ ### 7.9 OTA(汇总)
1251
+
1252
+ | 插件 / 方法 | 说明 | 返回示例要点 |
1253
+ |------|------|------|
1254
+ | `Ota.check(uid?)` | 检查更新(推荐) | `{ success, hasUpdate, handledByNative, message }` |
1255
+ | `Ota.checkUpdate(options?)` | 可传 `{ uid, notifyWhenNoUpdate }` | 同上 |
1256
+ | `Ota.setUid(uid)` | 仅设置上报用户 ID(主动设置后不再被请求头 Hook 覆盖) | `{ success: true, uid: "user-123" }` |
1257
+ | `Ota.setChannel(channel)` | 仅设置上报渠道码(主动设置后不再被请求头 Hook 覆盖) | `{ success: true, channel: "yyb" }` |
1258
+ | `Ota.installResourcePackage(options)` | 安装资源包 | `{ success, needsRestart, restarted, message }` |
1259
+ | `Ota.installAppPackage(options)` | 安装 APK 等 | `{ success, message, needsInstallPermission? }` |
1260
+ | `Ota.downloadAndInstallApk(url)` | 等同 `installAppPackage({ url })` | 同上 |
1261
+ | `Ota.checkResourceUpdate` / `Ota.checkApkUpdate` | 按 URL 检测 | `{ hasUpdate, version?/versionName?, url? }` |
1262
+ | `Ota.applyResourceUpdate` | 安装资源包不重启 | `{ success: true, needsRestart: true, restarted: false }` |
1263
+
1264
+ 详见 §5.1 / §5.3。
1265
+
1266
+ ### 7.10 Crypto(Client API 加密)
1267
+
1268
+ | 方法 | 说明 |
1269
+ |------|------|
1270
+ | `Crypto.encryptRequestBody(plain, paramPublicKey, platformCode?)` | 返回加密信封 `{ v, platformCode, ek, iv, ct }` |
1271
+ | `Crypto.postEncrypted(url, plain, paramPublicKey, init?)` | 加密后 POST,返回服务端 `{ code, message, data }` |
1272
+
1273
+ 用法与返回示例见 §5.4。
1274
+
1275
+ ### 7.11 设备能力(剪贴板 / 分享 / 相机 / 扫码 / 生物识别等)
1276
+
1277
+ H5 **禁止 `async`/`await`**,用 `.then()` 或 callback。系统权限弹窗由壳处理。包版本 **1.2.0+**。
1278
+
1279
+ ```typescript
1280
+ import {
1281
+ Biometric,
1282
+ Bluetooth,
1283
+ Brightness,
1284
+ Calendar,
1285
+ Capture,
1286
+ Clipboard,
1287
+ Contacts,
1288
+ Flashlight,
1289
+ Haptics,
1290
+ Nfc,
1291
+ Payment,
1292
+ Picker,
1293
+ Push,
1294
+ Recorder,
1295
+ Scan,
1296
+ Sensor,
1297
+ Share,
1298
+ Store,
1299
+ Volume,
1300
+ } from 'ota-native-bridge';
1301
+ ```
1302
+
1303
+ #### 插件 → Bridge 方法
1304
+
1305
+ | 插件 | SDK | 原生 method |
1306
+ |------|-----|-------------|
1307
+ | 剪贴板 | `Clipboard.get` / `set` | `clipboardGet` / `clipboardSet` |
1308
+ | 分享 | `Share.open({ title, text, url })` | `share` |
1309
+ | 选文件 | `Picker.chooseImage` / `chooseVideo` / `chooseFile` | `pickImage` / `pickVideo` / `pickFile` |
1310
+ | 拍照 | `Picker.takePhoto` | `takePhoto` |
1311
+ | 保存相册 | `Picker.saveImage({ dataUrl \| base64 })` | `saveImage` |
1312
+ | 扫码 | `Scan.scan` | `scanCode` |
1313
+ | 生物识别 | `Biometric.status` / `authenticate` | `biometricStatus` / `biometricAuth` |
1314
+ | 通讯录 | `Contacts.pick` | `pickContact` |
1315
+ | 日历 | `Calendar.addEvent({ title, notes, location, startMs, endMs })` | `addCalendarEvent` |
1316
+ | 蓝牙 / NFC | `Bluetooth.getState` / `Nfc.getState` | `bluetoothState` / `nfcState` |
1317
+ | 传感器 | `Sensor.getMotion` / `getPedometer` | `sensorMotion` / `pedometer` |
1318
+ | 振动 | `Haptics.vibrate(ms?)` | `vibrate` |
1319
+ | 手电筒 | `Flashlight.get` / `set(on)` | `flashlightGet` / `flashlightSet` |
1320
+ | 亮度 | `Brightness.get` / `set(0~1)` | `brightnessGet` / `brightnessSet` |
1321
+ | 音量 | `Volume.get` / `set(0~1)` | `volumeGet` / `volumeSet` |
1322
+ | 录音 | `Recorder.start` / `stop` | `recorderStart` / `recorderStop` |
1323
+ | 截屏 / 录屏 | `Capture.screenshot` / `startScreenRecord` / `stopScreenRecord` | `screenshot` / `screenRecordStart` / `screenRecordStop` |
1324
+ | 支付 | `Payment.pay({ url, payUrl, channel })` | `paymentPay` |
1325
+ | 评分 | `Store.requestReview` | `storeReview` |
1326
+ | 推送 | `Push.getToken` | `pushToken` |
1327
+
1328
+ #### 调用与返回示例
1329
+
1330
+ ```javascript
1331
+ Clipboard.get().then(console.log);
1332
+ // { "success": true, "text": "..." }
1333
+ Clipboard.set('hello').then(console.log);
1334
+ // { "success": true }
1335
+
1336
+ Share.open({ title: '标题', text: '正文', url: 'https://example.com' }).then(console.log);
1337
+ // { "success": true, "message": "Share sheet opened" }
1338
+
1339
+ Picker.chooseImage().then(console.log);
1340
+ // { "success": true, "type": "image", "uri": "...", "mimeType": "image/jpeg", "size": 12345, "dataUrl": "data:image/jpeg;base64,..." }
1341
+ Picker.takePhoto().then(console.log);
1342
+ Picker.saveImage({ dataUrl: 'data:image/jpeg;base64,...' }).then(console.log);
1343
+ // { "success": true, "message": "Saved to album" }
1344
+
1345
+ Scan.scan().then(function (r) { console.log(r.text, r.format); });
1346
+ // { "success": true, "text": "https://...", "format": "QR_CODE" }
1347
+
1348
+ Biometric.status().then(console.log);
1349
+ // { "available": true, "enrolled": true, "biometryType": "face"|"touch"|"unknown"|"none", "message": "ok" }
1350
+ Biometric.authenticate({ title: '确认本人' }).then(console.log);
1351
+ // { "success": true, "message": "Authenticated" }
1352
+
1353
+ Contacts.pick().then(console.log);
1354
+ // { "success": true, "name": "张三", "phones": ["13800000000"], "emails": [] }
1355
+ Calendar.addEvent({ title: '会议', startMs: Date.now(), endMs: Date.now() + 3600000 }).then(console.log);
1356
+ // { "success": true, "message": "Calendar editor opened" }
1357
+
1358
+ Bluetooth.getState().then(console.log);
1359
+ Nfc.getState().then(console.log);
1360
+ // { "available": false, "enabled": false, "state": "unsupported"|"on"|"off" }
1361
+
1362
+ Sensor.getMotion().then(console.log);
1363
+ // { "success": true, "accelerometer": { "x": 0, "y": 0, "z": 9.8 }, "gyroscope": { "x": 0, "y": 0, "z": 0 } }
1364
+ Sensor.getPedometer().then(console.log);
1365
+ // { "success": true, "supported": true, "steps": 1234 }
1366
+
1367
+ Haptics.vibrate(200).then(console.log);
1368
+ Flashlight.set(true).then(console.log);
1369
+ // { "success": true, "on": true, "supported": true }
1370
+ Brightness.set(0.7).then(console.log);
1371
+ // { "success": true, "value": 0.7 }
1372
+ Volume.set(0.5).then(console.log);
1373
+ // { "success": true, "value": 0.5 }
1374
+
1375
+ Recorder.start().then(function () { return Recorder.stop(); }).then(console.log);
1376
+ // { "success": true, "path": "/.../audio.m4a" }
1377
+ Capture.screenshot().then(console.log);
1378
+ // { "success": true, "dataUrl": "data:image/jpeg;base64,..." }
1379
+ Capture.startScreenRecord().then(console.log);
1380
+ Capture.stopScreenRecord().then(console.log);
1381
+ // { "success": true, "path": "/.../screen.mp4" }
1382
+
1383
+ Payment.pay({ url: 'https://pay.example.com/cashier' }).then(console.log);
1384
+ // { "success": true, "channel": "url", "target": "https://pay.example.com/cashier" }
1385
+ Store.requestReview().then(console.log);
1386
+ // { "success": true, "shown": true }
1387
+ Push.getToken().then(console.log);
1388
+ // iOS:{ "success": true, "provider": "apns", "token": "...", "connected": true }
1389
+ // Android / Harmony:{ "success": true, "provider": "ota-websocket", "token": "", "connected": true }
1390
+ ```
1391
+
1392
+ #### 三端差异
1393
+
1394
+ | 能力 | Android | iOS | HarmonyOS |
1395
+ |------|---------|-----|-----------|
1396
+ | 剪贴板 / 分享 | 已实现 | 已实现 | 已实现 |
1397
+ | 选图 / 拍照 / 选文件 | 系统选择器 + FileProvider | PHPicker / 相机 / 文档 | PhotoViewPicker / DocumentViewPicker |
1398
+ | 保存相册 | MediaStore | 写入相册(需相册权限) | 系统相册入口,部分机型需业务自行落盘 |
1399
+ | 扫码 | ZXing 全屏扫码 | AVFoundation | Scan Kit |
1400
+ | 生物识别 | BiometricPrompt | LocalAuthentication(面容/指纹) | 因系统版本差异可能返回未接线提示 |
1401
+ | 通讯录 / 日历 | 系统选择器 / 插入日历 Intent | CNContactPicker / EKEventEdit | 日历/联系人选择器因 API 版本可能降级 |
1402
+ | 蓝牙 / NFC | 适配器开关状态;**不做扫描** | 状态有限;NFC 需 Extra entitlement,默认 `unsupported` | NFC 对三方应用通常 `unsupported` |
1403
+ | 手电筒 / 振动 / 亮度 | 已实现 | 已实现;**不能改系统音量** | 振动/音量已接;手电筒依赖 Camera Kit,可能 `supported: false` |
1404
+ | 录音 / 截屏 | MediaRecorder / PixelCopy | AVAudioRecorder / 窗口截图 | 录音、截屏可能提示走系统能力 |
1405
+ | 录屏 | MediaProjection(需用户授权 + 前台服务) | ReplayKit | 提示使用系统录屏 |
1406
+ | 支付 | **不内置**微信/支付宝 SDK,打开 `url`/`payUrl` | 同左 | 同左 |
1407
+ | 应用内评分 | Play In-App Review | `SKStoreReviewController` | 引导应用市场 |
1408
+ | 推送 token | 无 FCM;`provider: ota-websocket` | APNs(App ID 须打开 Push) | `ota-websocket` |
1409
+ | 换图标 | `Icon.set` / `setFromUrl`(自定义槽约 Android 11+) | Alternate Icons:`default`/`alt1`/`alt2`;`setFromUrl` **不能**改桌面图标 | 运行时不能改桌面图标 |
1410
+ | 角标 | ShortcutBadger(看桌面) | `applicationIconBadgeNumber` | `notificationManager.setBadgeNumber` |
1411
+ | 锁屏 | Keyguard 真实状态 | `isProtectedDataAvailable`(前台近似) | `screenLock`;不支持时 `supported: false` |
1412
+
1413
+ **支付 / 推送说明:** 壳不捆绑微信、支付宝、FCM 等第三方支付/推送 SDK。收银请传 H5/收银台 HTTPS 地址;OTA 通知走壳内 WebSocket。
1414
+
1415
+ #### 壳已声明的权限
1416
+
1417
+ 首次调用时由系统弹窗;拒绝后原生返回 `success: false` 或带 `message`。
1418
+
1419
+ | 平台 | 权限 |
1420
+ |------|------|
1421
+ | Android | `CAMERA`、`RECORD_AUDIO`、`VIBRATE`、`FLASHLIGHT`、`NFC`、`USE_BIOMETRIC`、`READ_CONTACTS`、`BLUETOOTH` / `BLUETOOTH_CONNECT`、`FOREGROUND_SERVICE_MEDIA_PROJECTION`、`ACTIVITY_RECOGNITION` |
1422
+ | iOS | `NSCameraUsageDescription`、`NSMicrophoneUsageDescription`、`NSPhotoLibraryUsageDescription`、`NSPhotoLibraryAddUsageDescription`、`NSContactsUsageDescription`、`NSCalendarsUsageDescription`、`NSFaceIDUsageDescription`、`NSMotionUsageDescription`;定位仍为 `NSLocationWhenInUseUsageDescription` |
1423
+ | HarmonyOS | `CAMERA`、`MICROPHONE`、`READ_IMAGEVIDEO`、`VIBRATE` |
1424
+
1425
+ ---
1426
+
1427
+ ## 8. 错误处理
1428
+
1429
+ | 场景 | 典型错误 |
1430
+ |------|----------|
1431
+ | 非 WebView 环境 | `Native bridge not available (AndroidBridge / IOSBridge / HarmonyBridge)` |
1432
+ | `whenReady` 超时 | `Bridge timeout` |
1433
+ | 自定义模式下调用 `Ota.checkUpdate` | 原生返回的业务错误信息(Promise reject) |
1434
+ | 方法不存在或参数错误 | reject 字符串或 JSON 错误体 |
1435
+
1436
+ 建议在业务层统一封装:
1437
+
1438
+ ```typescript
1439
+ import { Native, App } from 'ota-native-bridge';
1440
+
1441
+ function inApp<T>(fn: () => Promise<T>): Promise<T | null> {
1442
+ if (!Native.isNativePlatform()) return Promise.resolve(null);
1443
+ return fn().catch(() => null);
1444
+ }
1445
+
1446
+ inApp(() => App.getInfo()).then((info) => {
1447
+ if (info) console.log(info.versionName);
1448
+ });
1449
+ ```
1450
+
1451
+ ---
1452
+
1453
+ ## 9. 与壳同步 Bridge 脚本(可选)
1454
+
1455
+ **Vue 3 / npm 打包项目可跳过本节。**
1456
+
1457
+ 三端壳(Android / iOS / Harmony)在 Vue 3 + npm 打包场景下,**均无需**在 `www/` 放置 `ota-native-bridge.js` 或 `open-android-bridge-bootstrap.js`。
1458
+
1459
+ 若使用无打包器的纯 HTML,请自行将 `ota-native-bridge.js` 放入静态目录或 `public/`(`npm run sync:bridge` 已不再向壳目录复制文件)。
1460
+
1461
+ ---
1462
+
1463
+ ## 10. 常见问题
1464
+
1465
+ **Q:自定义更新 POST 明文被 400?**
1466
+ A:Client API 要求加密信封。使用 `Crypto.postEncrypted` 或 `Crypto.encryptRequestBody`,公钥取自 `App.getInfo().platform.paramPublicKey`。
1467
+
1468
+ **Q:本地浏览器调试 Bridge 报错?**
1469
+ A:属预期行为,请使用壳 App 或各端模拟器 WebView 调试。
1470
+
1471
+ **Q:`hasUpdate` 为 true 但没有 `downloadUrl`?**
1472
+ A:原生模式下由壳处理下载,不会把 URL 交给 JS;自定义模式请自行调 `update/download-url`(加密)。
1473
+
1474
+ **Q:接口被 OTA 后台关闭返回 403?**
1475
+ A:管理后台「公共接口」可单独关闭端点;与 Bridge 无关,检查服务端 `client_api_endpoint` 配置。
1476
+
1477
+ **Q:TypeScript 提示找不到类型?**
1478
+ A:执行 `npm run build` 生成 `dist/*.d.ts`,或确认依赖版本已包含类型文件。
1479
+
1480
+ ---
1481
+
1482
+ ## 11. 相关文档
1483
+
1484
+ - [README.md](../README.md) — 包结构、构建、npm 发布
1485
+ - 仓库 `AppUpgradeOTASystem` 根目录 `README.md` — OTA 系统整体说明
1486
+ - 管理后台「公共接口」— REST / WebSocket 鉴权与端点列表