@supersdk/jssdk 1.0.0 → 3.0.3-SNAPSHOT

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/CHANGELOG.md CHANGED
@@ -1,5 +1,64 @@
1
1
  # Changelog
2
2
 
3
+ ## 3.0.1-SNAPSHOT - 2026-11-18
4
+
5
+ - First npm publication since `1.0.0` (dist-tag `next`). Carries everything previously shipped only as a vendored `supersdk.js` in the 2.x line. No runtime change from `3.0.0-SNAPSHOT` other than the reported `sdkVersion`.
6
+
7
+ ## 3.0.0-SNAPSHOT - 2026-11-18 (not published to npm)
8
+
9
+ - Version line unified with the Android and iOS SDKs: all three now share one three-segment version taken from the monorepo's `vars.properties` (`SDK_VERSION`), starting at `3.0.0`. Test builds are published to the `next` dist-tag as `x.y.z-SNAPSHOT`; every release, test or stable, takes the next patch number.
10
+ - No runtime behaviour change from `2.8.0` other than the reported `sdkVersion`.
11
+
12
+ ## 2.8.0 - 2026-11-17
13
+
14
+ - Experiment emergency stop (WS-12-S5). Keys listed in the `emergency_stopped` of an accepted full assign response (not `not_modified`, not one dropped for a lower `rules_version`; applied after `live_vids` pruning, same as Android / iOS) leave the page's freeze table and read as not participating (`reason: 'paused'`, the caller's default payload) for the rest of the page session, with no exposure; their vids leave the exposed set, so later events' `exp_vids` and `getRequestHeaders()` / `appendVidsToUrl()` / `fetch()` no longer carry them (the same outcome as `live_vids` pruning). One diagnostic per key (`experiment` / `EMERGENCY_STOPPED`, `state: 'frozen' | 'unread'`, `discarded`). A key that is assigned again later in the same page (experiment resumed) stays stopped until the next page session.
15
+ - In-app delegated mode: when native answers a mirrored or frozen key as not participating with `reason: 'paused'` (through `getExperiment` or a `refresh()` / `getAllExperiments` reload), the page's entry adopts that value and its vid leaves the mirrored exposed set; other changes to a frozen key still keep the page's frozen value.
16
+ - `rollout` results (unchanged, now covered by tests): participating, never exposed, never in `exp_vids` or the request vids.
17
+
18
+ ## 2.7.0 - 2026-11-17
19
+
20
+ - Server-side experiments (WS-12-S6). Assign results now keep both `client` and `server` experiments; `getAll()` items carry `type`. `get(key)` on a `server` experiment returns not-participating with `reason: 'unknown'`, without freezing or exposing (diagnostic `experiment` / `SERVER_EXPERIMENT_READ`, once per key).
21
+ - New synchronous `SuperSDK.experiment.getRequestHeaders()` → `{ 'X-Super-AB-Vids': '<vids>' }` (`{}` when the exposed set is empty), `appendVidsToUrl(url)` (sets / overwrites `super_ab_vids`, keeps other params, hash and relative form; unchanged when empty) and `fetch(input, init?)` (global `fetch` with the header merged; SDK value wins over a same-name caller header; works with `Headers`, arrays, plain objects and `Request` input). Each call first treats every assigned `server` experiment in the loaded namespaces as read: frozen for the session, `$exp_exposure` reported once (usual dedupe), vid added to the exposed set (the same set as `exp_vids`).
22
+ - Web-path SDK requests to the platform that are already CORS-preflighted JSON POSTs (assign, analytics upload, monitoring, feedback) carry `X-Super-AB-Vids` with the current exposed set only (omitted when empty); they never trigger the server-experiment side effect. The CORS-simple settings GET does not carry it (no extra preflight).
23
+ - In-app delegated mode: `getAllExperiments` items gain `type` / `exposed`; the three methods compute the value synchronously from the mirror (empty before `ready()`, native not called) and call the new shared JSB method `getExperimentRequestVids(callbackId, paramsJson)` → `{ vids }` asynchronously so native freezes and exposes (`source: "h5"`), adopting native's set (`experiment_native` / `NATIVE_RESULT_MISMATCH` on mismatch). The method is optional: containers without it get the mirror-only value (`REQUEST_VIDS_UNSUPPORTED` once). Bridge protocol now has 63 methods.
24
+
25
+ ## 2.6.0 - 2026-11-17
26
+
27
+ - In-app `SuperSDK.experiment` delegates to native (WS-12-S2) when the container declares the five new shared JSB methods `experimentReady`, `getAllExperiments`, `getExperiment`, `exposeExperiment` and `setExperimentAttributes` (all `(callbackId, paramsJson)` requests; bridge protocol now has 62 methods). In that mode native fetches, freezes (shared with native code and other WebViews) and reports `$exp_exposure` with `source: "h5"`; the JSSDK sends no assign request, reports no exposure and attaches no `exp_vids` (native stamps it on events created from H5 `reportEvent`). `ready()` mirrors native results via `experimentReady` + `getAllExperiments`; `get()` stays synchronous, reads the mirror and asks native asynchronously, adopting native's frozen value (diagnostic `experiment_native` / `NATIVE_RESULT_MISMATCH` when they differ); a read before `ready()` returns `no_result` and stays frozen for the page without notifying native; `refresh()` re-reads native's results. Older containers keep the 2.5.0 web path.
28
+
29
+ ## 2.5.0 - 2026-11-17
30
+
31
+ - Add the `SuperSDK.experiment` namespace (A/B experiments, WS-12-S1): `ready({ timeoutMs?, namespaces? })` (resolves when this page's first assign fetch settles or after `timeoutMs`, default 2000), synchronous `get(key, { expose?, default? })` → `{ inExperiment, variant, vid, payload, reason }`, `expose(key)`, `getAll()` (diagnostic: no freeze, no exposure), `refresh()` and `setAttributes(map)` (`attr.*`, debounced refetch). The SDK fetches the device's assignment list from `POST {baseUrl}/v2/experiments/assign` (base URL rotation + suenc decoding; `known_version` only when attributes and namespaces are unchanged since the last success; lower `rules_version` responses dropped; results older than `stale_after_sec` count as `no_result`), stores it in `localStorage` per spid + environment + device id, freezes each key on its first read for the page session, and reports `$exp_exposure` on read (deduped per session and per calendar day; `rollout` never exposed). Analytics consent gates everything: `denied` → no request and `reason: 'no_subject'`; revoking clears the stored results and exposed set. In-app the same web path is used with the device id from the native `getEnv()` (fetched on first experiment API use).
32
+ - Every analytics event now carries the SDK-owned `exp_vids` param (ascending, comma-joined exposed vids, at most 500) captured when the event is created, not when it is uploaded; the set is pruned with the assign response's `live_vids`. Caller-supplied `exp_vids` (event params or common params) is ignored. `protocol/experiment-v1.json` and `protocol/experiment-v1-golden.json` ship in the package.
33
+
34
+ ## 2.4.0 - 2026-10-11
35
+
36
+ - Add the `SuperSDK.push` namespace: `getStatus()` (`{ supported, permission, registered, lastError?, lastOpened? }`; `lastOpened` is consumed by the first `getStatus()` that reads it), `requestPermission()` (interactive, 120s callback timeout), `setTags(tags)` / `setUserId(userId)` (`null` / empty clears; bounds are validated by the native container and surface as `INVALID_ARGUMENT`), and `onMessage(cb)` / `onOpened(cb)` as aliases of `subscribe('push.message' | 'push.opened')` returning an unsubscribe function. In the browser `getStatus()` resolves `{ supported: false }` and the other methods reject `NOT_SUPPORTED` without throwing synchronously; containers that answer `NOT_SUPPORTED` / `NOT_IMPLEMENTED` (unwired host, iOS stub) also yield `{ supported: false }` from `getStatus()` and `UNSUPPORTED` elsewhere. Android requires the optional `supersdk-push-firebase` module.
37
+ - Bridge protocol manifest grows to 57 methods (`pushGetStatus` / `pushRequestPermission` / `pushSetTags` / `pushSetUserId`) and 6 events (`push.message` / `push.opened`, BROADCAST); the native code registry maps `NO_ACTIVITY` to `UNAVAILABLE` (retryable). `protocol/push-v1.json` ships the Day-0 push HTTP contract fixture; `@supersdk/jssdk/protocol` typings gain `PushStatusWire` / `PushMessagePayload` / `PushOpenedPayload`.
38
+
39
+ ## 2.3.0 - 2026-09-16
40
+
41
+ - Add `submitFeedback(params)` (`{ scene, subScene?, title, content, userId?, extra? }` → `{ feedbackId }`). In-app it calls the new shared JSB `submitFeedback(callbackId, paramsJson)` and the native container fills `spid / env / device_id / platform / versions` before posting to `/superapi/v2/feedback`; on the web runtime the SDK posts the snake_case wire body directly with `X-Aid` / `X-Super-API-ENV`, rotates base URLs only on transient failures, reads the envelope through the suenc-aware decoder and surfaces server business rejections as `INVALID_ARGUMENT` with `nativeCode`. Submissions are visible in the console under 业务运营 → 用户反馈.
42
+ - Bridge protocol manifest grows to 53 methods (`submitFeedback`); `@supersdk/jssdk/protocol` typings gain `FeedbackParams` / `FeedbackReceipt`.
43
+
44
+ ## 2.2.0 - 2026-09-02
45
+
46
+ - Add `pay.querySubscriptionOffers(options)` (Google Play eligible subscription offers) on the shared JSB.
47
+
48
+ ## 2.1.0 - 2026-08-15
49
+
50
+ - Add `setAPIEnvironment(environment)` / `getAPIEnvironment()`. In web fallback mode the setter validates `^[a-z0-9]{1,10}$`, flushes pending analytics under the old environment before switching, and subsequent settings fetches and event reports use the new value; settings request caching is already keyed by environment, so entries never leak across environments. In-app the setter rejects with `UNSUPPORTED` (the environment is controlled by the native host via `SuperSDK.setAPIEnvironment`) and the getter passes through the native value.
51
+
52
+ ## 2.0.0 - 2026-08-10
53
+
54
+ - Add the versioned JSB IDL, golden vectors, deterministic generator and `protocol`/`mock` package exports.
55
+ - Add five-state bridge discovery plus typed request, local-dispatch command, stream, subscription, deadline, abort and dispose lifecycles.
56
+ - Add a target-scoped callback hub with owner isolation, foreign-handler delegation, identity-drift cleanup and compare-and-swap restoration.
57
+ - Map native errors through one public registry and restrict diagnostics to bounded metadata.
58
+ - Add opt-in frontend/container monitoring with independent consent, bounded local snapshots/subscribers, generated `supersdk.monitoring.v1` contracts and no implicit network delivery.
59
+ - Correct TypeScript declarations for file results, downloads, directory listing, login and navigation. These declaration corrections are the intentional 2.0 source break; legacy runtime wrappers remain behavior-compatible.
60
+ - Publish stable builds to the `candidate` tag first; promotion to `latest` is a separately approved exact-artifact workflow.
61
+
3
62
  ## 1.0.0 - 2026-08-09
4
63
 
5
64
  - Publish environment-neutral ESM, CommonJS, TypeScript and explicit global entries.
package/JSBridge.md ADDED
@@ -0,0 +1,416 @@
1
+ # JSBridge 技术文档
2
+
3
+ 本文档说明 JSBridge 的底层通信机制,面向需要了解 Native 与 JS 交互原理的开发者。
4
+
5
+ ## 2.0 协议入口
6
+
7
+ 2.0 在历史 wrapper 之外提供 `sdk.bridge`。容器通过同步、无副作用的保留方法 `getBridgeManifest()` 返回 v1 manifest;该方法不属于业务 methods,不能从 `supports/request/command` 调用。IDL 和正反向量分别随包发布在 `protocol/v1.json` 与 `protocol/golden-vectors.json`,运行时数据/校验器从 `@supersdk/jssdk/protocol` 导入。
8
+
9
+ ```js
10
+ const state = await SuperSDK.bridge.ready();
11
+ if (state.status === 'negotiated' && SuperSDK.bridge.supports('getEnv')) {
12
+ const env = await SuperSDK.bridge.request('getEnv', []);
13
+ }
14
+ ```
15
+
16
+ 状态固定为 `absent / legacy / negotiated / incompatible / degraded`。bootstrap 存在但读取、大小、JSON 或签名校验失败时进入 `degraded`,不会静默回退。`request` 默认 deadline 为 5000ms,`openStream` 默认 300000ms;二者支持 AbortSignal。`command` 只表达同步派发已接受,在下一 microtask 完成,不创建 native ack timer。
17
+
18
+ 同一个 target 上的多个 SDK instance 共享 owner 隔离的 callback hub。已认领 callback 只进入所属 owner,事件按订阅投递,返回键按 owner 后进先出;未认领消息才委托安装前的 foreign handler。`dispose()` 清除本 owner 的 pending/listener,最后 owner 仅在全局对象仍为当前 hub 时恢复原 handler。
19
+
20
+ 错误 envelope 的 `code` 缺失、非字符串或空串统一为 `PROTOCOL_MISMATCH`;已登记 code 按公开 registry 映射;任意未知非空 provider code 统一为 `BRIDGE_ERROR` 和 `nativeCode: "UNKNOWN"`。诊断只记录有界 method/event/state/outcome/error class,不记录参数、结果、路径、URL、message 或 stack。
21
+
22
+ ## 架构概述
23
+
24
+ ```
25
+ ┌─────────────────────────────────────────────────────────┐
26
+ │ Web 页面 │
27
+ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
28
+ │ │ SuperSDK │ │ JSBridge │ │ 业务代码 │ │
29
+ │ └──────┬──────┘ └──────┬──────┘ └─────────────┘ │
30
+ │ │ │ │
31
+ │ ▼ ▼ │
32
+ │ ┌─────────────────────────────────────────────────────┤
33
+ │ │ window.appbridge │
34
+ │ │ (Native 注入的 JS 接口) │
35
+ │ └─────────────────────────────────────────────────────┤
36
+ └─────────────────────────────────────────────────────────┘
37
+ │
38
+ │ @JavascriptInterface
39
+ ▼
40
+ ┌─────────────────────────────────────────────────────────┐
41
+ │ Android │
42
+ │ ┌──────────────────────────────────────────────────┐ │
43
+ │ │ SuperWebview.java │ │
44
+ │ │ - WebView 配置与初始化 │ │
45
+ │ │ - URL 拦截处理 │ │
46
+ │ │ - 生命周期管理 │ │
47
+ │ │ - WebView 间通信 (broadcastToAll, sendToWebview) │ │
48
+ │ │ - 异步回调 (asyncCallbackSuccess/Fail) │ │
49
+ │ └──────────────────────────────────────────────────┘ │
50
+ │ │ │
51
+ │ │ 注入 │
52
+ │ ▼ │
53
+ │ ┌──────────────────────────────────────────────────┐ │
54
+ │ │ AppBridge.java │ │
55
+ │ │ - 环境与配置 JSB │ │
56
+ │ │ - 页面导航 JSB │ │
57
+ │ │ - 分享 JSB │ │
58
+ │ │ - WebView 通信 JSB │ │
59
+ │ │ - 文件下载 JSB │ │
60
+ │ │ - 文件操作 JSB │ │
61
+ │ └──────────────────────────────────────────────────┘ │
62
+ └─────────────────────────────────────────────────────────┘
63
+ ```
64
+
65
+ ## 文件结构
66
+
67
+ ```
68
+ app/src/main/java/com/asuper/android/webview/
69
+ ├── SuperWebview.java # WebView 核心类
70
+ ├── AppBridge.java # JSB 门面类,委托给各模块
71
+ └── bridge/ # JSB 功能模块
72
+ ├── BaseBridge.java # 基类,提供通用功能
73
+ ├── EnvBridge.java # 环境与配置
74
+ ├── NavigationBridge.java # 页面导航
75
+ ├── ShareBridge.java # 分享
76
+ ├── WebViewBridge.java # WebView 间通信
77
+ ├── DownloadBridge.java # 文件下载
78
+ └── FileBridge.java # 文件操作
79
+ ```
80
+
81
+ ### SuperWebview.java
82
+
83
+ WebView 核心类,职责:
84
+ - WebView 配置初始化
85
+ - URL 拦截与处理
86
+ - 生命周期事件分发
87
+ - WebView 注册表管理
88
+ - JS 回调调度 (`callSubscribeHandler`)
89
+ - 异步回调辅助方法 (`asyncCallbackSuccess/Fail`)
90
+
91
+ ### AppBridge.java
92
+
93
+ JSB 门面类,职责:
94
+ - 所有 `@JavascriptInterface` 标注的方法入口
95
+ - 将请求委托给对应的功能模块
96
+
97
+ ### bridge/ 模块
98
+
99
+ | 模块 | 职责 |
100
+ |------|------|
101
+ | BaseBridge | 基类,提供 Context、WebView 弱引用、MainHandler |
102
+ | EnvBridge | 环境信息、配置获取 |
103
+ | NavigationBridge | 页面打开、关闭、外部跳转 |
104
+ | ShareBridge | 系统分享 |
105
+ | WebViewBridge | WebView 间消息广播 |
106
+ | DownloadBridge | 文件下载、缓存下载、取消下载 |
107
+ | FileBridge | 文件增删改查操作 |
108
+
109
+ ## 通信机制
110
+
111
+ ### 1. JS 调用 Native
112
+
113
+ 通过 `window.appbridge` 对象直接调用 Native 方法:
114
+
115
+ ```javascript
116
+ // 同步调用
117
+ appbridge.share(content);
118
+
119
+ // 异步调用(需要 callbackId)
120
+ appbridge.getEnvAsync(callbackId);
121
+ ```
122
+
123
+ ### 2. Native 调用 JS
124
+
125
+ Native 通过 `evaluateJavascript` 调用 JS 的 `JSBridge.subscribeHandler`:
126
+
127
+ ```java
128
+ // SuperWebview.java
129
+ public void callSubscribeHandler(String eventType, String eventKey, String jsonData) {
130
+ APool.executeUI(() -> {
131
+ String js = "JSBridge.subscribeHandler(\"" + eventType + "\",\"" + eventKey + "\"," + jsonData + ")";
132
+ evaluateJavascript(js, null);
133
+ });
134
+ }
135
+ ```
136
+
137
+ ## 事件类型
138
+
139
+ | 常量 | 值 | 说明 |
140
+ |------|------|------|
141
+ | EVENT_TYPE_ASYNC_CALLBACK | "ASYNC_CALLBACK" | 异步方法的回调响应 |
142
+ | EVENT_TYPE_BROADCAST | "BROADCAST" | WebView 间的广播消息 |
143
+ | EVENT_TYPE_SYSTEM | "SYSTEM" | 系统级事件(生命周期等) |
144
+
145
+ ## subscribeHandler 协议
146
+
147
+ Native 调用 JS 的统一入口:
148
+
149
+ ```javascript
150
+ JSBridge.subscribeHandler(eventType, eventKey, data)
151
+ ```
152
+
153
+ | 参数 | 类型 | 说明 |
154
+ |------|------|------|
155
+ | eventType | string | 事件类型:ASYNC_CALLBACK / BROADCAST / SYSTEM |
156
+ | eventKey | string | 事件标识:回调ID / 事件名 / 系统事件名 |
157
+ | data | object | JSON 格式的数据 |
158
+
159
+ ### 异步回调响应格式
160
+
161
+ 成功:
162
+ ```json
163
+ {
164
+ "code": "SUCCESS",
165
+ "message": "",
166
+ "data": { ... }
167
+ }
168
+ ```
169
+
170
+ 失败:
171
+ ```json
172
+ {
173
+ "code": "ERROR_CODE",
174
+ "message": "错误信息"
175
+ }
176
+ ```
177
+
178
+ ### 系统事件格式
179
+
180
+ ```json
181
+ {
182
+ "triggerFrom": "window" | "view" | "activity"
183
+ }
184
+ ```
185
+
186
+ ## Native 接口列表 (AppBridge.java)
187
+
188
+ ### 环境与配置
189
+
190
+ | 方法 | 参数 | 说明 |
191
+ |------|------|------|
192
+ | getEnvAsync | callbackId | 获取环境信息 |
193
+ | getSettingsAsync | callbackId | 获取所有配置 |
194
+ | getSettingsByKeyAsync | key, callbackId | 根据 key 获取配置 |
195
+
196
+ ### 页面导航
197
+
198
+ | 方法 | 参数 | 说明 |
199
+ |------|------|------|
200
+ | openPage | url, config | 打开新 WebView 页面 |
201
+ | openExternal | url | 系统方式打开 URL |
202
+ | openWithBrowser | url | 浏览器打开 URL |
203
+ | closePage | - | 关闭当前页面 |
204
+
205
+ ### 分享
206
+
207
+ | 方法 | 参数 | 说明 |
208
+ |------|------|------|
209
+ | share | content | 分享文本内容 |
210
+
211
+ ### WebView 间通信
212
+
213
+ | 方法 | 参数 | 说明 |
214
+ |------|------|------|
215
+ | publishToWebView | targetId, eventKey, jsonContent | 广播消息到其他 WebView |
216
+
217
+ ### 文件下载
218
+
219
+ | 方法 | 参数 | 说明 |
220
+ |------|------|------|
221
+ | downloadFile | callbackId, url, headers, savePath | 下载文件(支持进度回调) |
222
+ | downloadWithCache | callbackId, fileUrl, fileMd5, cacheTts, fileCacheKey | 下载并缓存文件,命中缓存直接返回本地路径 |
223
+ | cancelDownload | callbackId | 取消下载任务 |
224
+
225
+ ### 文件操作
226
+
227
+ | 方法 | 参数 | 说明 |
228
+ |------|------|------|
229
+ | fileExists | path, callbackId | 检查文件/目录是否存在 |
230
+ | getFileMd5 | path, callbackId | 获取文件 MD5 |
231
+ | deleteFile | path, callbackId | 删除文件或目录 |
232
+ | moveFile | srcPath, destPath, callbackId | 移动/重命名文件 |
233
+ | createDir | path, callbackId | 创建目录 |
234
+ | listDir | path, callbackId | 列出目录内容 |
235
+ | readFile | path, callbackId | 读取文本文件 |
236
+ | writeFile | path, content, callbackId | 写入文本文件 |
237
+
238
+ ### ZIP 压缩与解压
239
+
240
+ | 方法 | 参数 | 说明 |
241
+ |------|------|------|
242
+ | unzipFile | zipPath, destPath, callbackId | 解压 ZIP 文件到目标目录 |
243
+ | zipDir | sourcePath, zipPath, callbackId | 将目录压缩为 ZIP 文件 |
244
+
245
+ ### 广告(Android)
246
+
247
+ | 方法 | 参数 | 说明 |
248
+ |------|------|------|
249
+ | showRewardAd | config, callbackId | 加载并展示激励视频,终态返回 `{ dismissed, rewarded }` |
250
+ | showRewardedInterstitialAd | config, callbackId | 加载并展示激励插屏;业务调用前必须展示奖励说明和可跳过 intro |
251
+ | showInterstitialAd | config, callbackId | 加载并展示插屏广告 |
252
+ | showBannerAd | config, callbackId | 展示 Banner,成功返回 `adId` |
253
+ | hideBannerAd | adId, callbackId | 移除并销毁 Banner |
254
+
255
+ `config` 为 JSON 字符串,至少包含 `adUnitId`,可选 `adSource`(默认 `ADMOB`)。Rewarded Interstitial 当前仅 Android 支持;JSSDK 在旧桥或不支持平台立即返回 `NOT_SUPPORTED`。
256
+
257
+ ### A/B 实验(双端 · WS-12-S2 / S6)
258
+
259
+ 六个方法签名相同:`(callbackId, paramsJson)`,异步回调。原生与端内 H5 共用同一份结果、同一张冻结表与同一套曝光去重;H5 经 `getExperiment` / `exposeExperiment` 触发的 `$exp_exposure` 记 `source: "h5"`。
260
+
261
+ | 方法 | paramsJson | 成功回调 data |
262
+ |------|------------|---------------|
263
+ | experimentReady | `{ timeoutMs?, namespaces? }` | `{ ready }`(超时为 `false`) |
264
+ | getAllExperiments | `{}` | `{ experiments: [{ key, inExperiment, variant, vid, payload, reason, frozen, type, exposed }] }`(不冻结、不曝光;`type` 为 `client` / `server`,`exposed` 表示该 vid 在已曝光集合里,S6 起) |
265
+ | getExperiment | `{ key, expose?, default? }` | `{ inExperiment, variant, vid, payload, reason }`(冻结;`expose` 默认 `true`;服务端实验返回未参与 `reason: "unknown"`,不冻结不曝光) |
266
+ | getExperimentRequestVids | `{}` | `{ vids }`:已加载命名空间里命中的服务端实验视为已读取(冻结、曝光 `source: "h5"`、加入集合)后的已曝光集合,升序逗号分隔,空集合为 `""`(S6 起) |
267
+ | exposeExperiment | `{ key }` | `{}` |
268
+ | setExperimentAttributes | `{ attributes }`(键不带 `attr.` 前缀,值为字符串,`null` 删除) | `{}` |
269
+
270
+ JSSDK 只在容器同时声明前五个方法时委托原生(`bridge.supports`);`getExperimentRequestVids` 可选,缺失时 JSSDK 只按 `getAllExperiments` 镜像计算请求头的值;端内 H5 经 `reportEvent` 上报的事件由原生在创建时写入 `exp_vids`,JSSDK 不再附带。
271
+
272
+ ## Native 事件触发
273
+
274
+ ### 系统事件
275
+
276
+ | 事件名 | 触发时机 | 数据 |
277
+ |------|------|------|
278
+ | onEnterForeground | WebView 变为可见 | { triggerFrom } |
279
+ | onEnterBackground | WebView 变为不可见 | { triggerFrom } |
280
+
281
+ ### triggerFrom 来源
282
+
283
+ | 值 | 触发时机 |
284
+ |------|------|
285
+ | window | onWindowVisibilityChanged |
286
+ | view | setVisibility |
287
+ | activity | Activity onResume/onPause |
288
+
289
+ ## WebView 注册表
290
+
291
+ SuperWebview 维护一个全局的 WebView 实例注册表,用于实现 WebView 间通信:
292
+
293
+ ```java
294
+ // SuperWebview.java
295
+ private static final Map<String, WeakReference<SuperWebview>> webviewRegistry = new ConcurrentHashMap<>();
296
+
297
+ // 注册
298
+ @Override
299
+ protected void onAttachedToWindow() {
300
+ super.onAttachedToWindow();
301
+ webviewRegistry.put(webviewId, new WeakReference<>(this));
302
+ }
303
+
304
+ // 注销
305
+ @Override
306
+ protected void onDetachedFromWindow() {
307
+ super.onDetachedFromWindow();
308
+ webviewRegistry.remove(webviewId);
309
+ }
310
+
311
+ // 广播到所有
312
+ static void broadcastToAll(String eventKey, String jsonContent) {
313
+ for (Map.Entry<String, WeakReference<SuperWebview>> entry : webviewRegistry.entrySet()) {
314
+ SuperWebview webview = entry.getValue().get();
315
+ if (webview != null) {
316
+ webview.callSubscribeHandler(EVENT_TYPE_BROADCAST, eventKey, jsonContent);
317
+ }
318
+ }
319
+ }
320
+
321
+ // 发送到指定 WebView
322
+ static void sendToWebview(String targetWebviewId, String eventKey, String jsonContent) {
323
+ WeakReference<SuperWebview> ref = webviewRegistry.get(targetWebviewId);
324
+ if (ref != null) {
325
+ SuperWebview webview = ref.get();
326
+ if (webview != null) {
327
+ webview.callSubscribeHandler(EVENT_TYPE_BROADCAST, eventKey, jsonContent);
328
+ }
329
+ }
330
+ }
331
+ ```
332
+
333
+ ## 流程示例
334
+
335
+ ### 异步调用流程
336
+
337
+ ```
338
+ ┌────────┐ ┌──────────┐ ┌────────────┐
339
+ │ JS │ │AppBridge │ │ JS │
340
+ └───┬────┘ └────┬─────┘ └─────┬──────┘
341
+ │ │ │
342
+ │ appbridge.getEnvAsync(callbackId) │
343
+ │──────────────────►│ │
344
+ │ │ │
345
+ │ │ 执行业务逻辑 │
346
+ │ │ webview.asyncCallbackSuccess()
347
+ │ │ │
348
+ │ │ JSBridge.subscribeHandler(
349
+ │ │ "ASYNC_CALLBACK",
350
+ │ │ callbackId,
351
+ │ │ result)
352
+ │ │─────────────────────►│
353
+ │ │ │
354
+ │ │ │ 查找并执行回调
355
+ │ │ │
356
+ ```
357
+
358
+ ### 广播流程
359
+
360
+ ```
361
+ ┌────────────┐ ┌──────────┐ ┌────────────┐
362
+ │ WebView A │ │AppBridge │ │ WebView B │
363
+ └─────┬──────┘ └────┬─────┘ └─────┬──────┘
364
+ │ │ │
365
+ │ publishToWebView("*", "event", data)│
366
+ │─────────────────►│ │
367
+ │ │ │
368
+ │ │ SuperWebview.broadcastToAll()
369
+ │ │ │
370
+ │ subscribeHandler│ subscribeHandler│
371
+ │◄─────────────────│─────────────────►│
372
+ │ │ │
373
+ ```
374
+
375
+ ### 文件下载流程
376
+
377
+ ```
378
+ ┌────────┐ ┌──────────┐ ┌────────────┐
379
+ │ JS │ │AppBridge │ │ JS │
380
+ └───┬────┘ └────┬─────┘ └─────┬──────┘
381
+ │ │ │
382
+ │ downloadFile(callbackId, url, ...) │
383
+ │──────────────────►│ │
384
+ │ │ │
385
+ │ │ callback: START │
386
+ │ │─────────────────────►
387
+ │ │ │
388
+ │ │ callback: PROGRESS (每300ms)
389
+ │ │─────────────────────►
390
+ │ │ │
391
+ │ │ callback: SUCCESS/FAIL
392
+ │ │─────────────────────►
393
+ │ │ │
394
+ ```
395
+
396
+ ## 容器职责
397
+
398
+ ### WebPageActivity
399
+
400
+ - 设置 `OnClosePageListener` → `this::finish`
401
+ - 在 `onResume` 调用 `dispatchActivityResume()`
402
+ - 在 `onPause` 调用 `dispatchActivityPause()`
403
+
404
+ ### TabWebViewManager
405
+
406
+ - 仅负责 Tab 切换和 WebView 缓存管理
407
+ - 不设置 `OnClosePageListener`(closePage 无效果)
408
+ - 通过 `setVisibility` 触发可见性事件
409
+
410
+ ## 安全考虑
411
+
412
+ 1. **WeakReference**: AppBridge 持有 WebView 的弱引用,防止内存泄漏
413
+ 2. **MainHandler**: 确保 UI 操作在主线程执行
414
+ 3. **文件路径隔离**: 文件操作限制在 SDK 存储目录内
415
+ 4. **参数校验**: Native 方法对参数进行校验
416
+ 5. **包级访问**: `asyncCallbackSuccess/Fail` 等方法使用包级访问控制
package/README.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  SuperSDK is one JavaScript runtime for ordinary browser projects and SuperSDK App containers. Browser projects can read public settings and report consented analytics; Hybrid projects keep the existing JSBridge API.
4
4
 
5
+ Version 2.0 adds a negotiated, typed low-level bridge without changing the observable runtime behavior of the legacy wrappers. Existing 1.x applications can stay pinned to 1.x while migrating TypeScript declarations.
6
+
5
7
  ## Install
6
8
 
7
9
  ```bash
@@ -52,10 +54,70 @@ Bundlers may explicitly import `@supersdk/jssdk/global`. The root ESM/CommonJS e
52
54
 
53
55
  `initFallback(config)` remains a compatibility alias of `init(config)`. Existing `addEventCommonParam(key, value)` remains supported; Web projects may also call `addEventCommonParams(object)`.
54
56
 
57
+ ## Frontend monitoring
58
+
59
+ Monitoring is disabled by default and uses consent independent from analytics. It works in ordinary browser projects without calling `init()` when envelopes are consumed locally:
60
+
61
+ ```js
62
+ const unsubscribe = SuperSDK.monitoring.onEnvelope((envelope) => {
63
+ // supersdk.monitoring.v1 contains bounded metadata only.
64
+ console.log(envelope.signal, envelope.summary.count);
65
+ });
66
+
67
+ SuperSDK.monitoring.setConsent({ errors: 'granted', performance: 'granted' });
68
+ SuperSDK.monitoring.start();
69
+
70
+ const snapshot = SuperSDK.monitoring.getSnapshot();
71
+
72
+ SuperSDK.monitoring.stop();
73
+ unsubscribe();
74
+ ```
75
+
76
+ Without an explicit remote adapter, monitoring never sends network requests. A custom adapter may be supplied with `start({ remoteAdapter })`; delivery is at most once, has a fixed five-second deadline and receives an `AbortSignal`. The built-in `{ kind: 'reportEventV2' }` adapter requires a valid prior `init()` and yields to pending analytics delivery. JSSDK remote delivery is blocked inside App containers because native business-queue state is not visible to JavaScript; local snapshots and subscribers continue to work.
77
+
78
+ The two monitoring categories default to `denied`. Revoking either category immediately removes its collectors and in-memory data without changing analytics consent, analytics identity or the business outbox. Envelopes expose only the generated `supersdk.monitoring.v1` allowlist: no raw error message, stack, URL, DOM/input, headers/body or JSB arguments/results. Protocol constants, types and validation are also exported from `@supersdk/jssdk/protocol`.
79
+
80
+ ## Negotiated bridge
81
+
82
+ ```js
83
+ import { createSuperSDK } from '@supersdk/jssdk';
84
+
85
+ const sdk = createSuperSDK({ target: window });
86
+ const state = await sdk.bridge.ready();
87
+ if (sdk.bridge.supports('getEnv')) {
88
+ const environment = await sdk.bridge.request('getEnv', [], { timeoutMs: 5000 });
89
+ }
90
+
91
+ const stop = sdk.bridge.subscribe('system.onEnterForeground', (event) => {
92
+ console.log(event.id);
93
+ });
94
+ stop();
95
+ sdk.bridge.dispose();
96
+ ```
97
+
98
+ The five container states are `absent`, `legacy`, `negotiated`, `incompatible` and `degraded`. A declared but malformed bootstrap is `degraded`; it never silently falls back to legacy dispatch. `request()` and `openStream()` use native callback envelopes, while `command()` resolves after local synchronous dispatch and never waits for an invented acknowledgement.
99
+
100
+ Protocol data and the validator are exported from `@supersdk/jssdk/protocol`. Deterministic tests can use `createBridgeMock` from `@supersdk/jssdk/mock`. Application code cannot call the reserved `getBridgeManifest` bootstrap through `supports()`, `request()` or `command()`.
101
+
102
+ ### 2.0 TypeScript migration
103
+
104
+ The 1.0 declarations disagreed with the already-published runtime in four places. Version 2.0 makes the declarations match the runtime bytes:
105
+
106
+ | API | 1.0 declaration | Runtime and 2.0 declaration |
107
+ | --- | --- | --- |
108
+ | `fileExists(path)` | `Promise<boolean>` | `Promise<{exists,isFile,isDirectory}>` |
109
+ | `readFile(path)` | `Promise<string>` | `Promise<{content:string}>` |
110
+ | `getFileMd5(path)` | `Promise<string>` | `Promise<{md5:string}>` |
111
+ | `downloadFile(...)` | URL arguments and `Promise` | options object and synchronous cancel function |
112
+
113
+ `listDir()` likewise resolves `{files:[...]}`, `downloadWithCache()` keeps its positional runtime arguments, `requestLogin()` accepts `{provider}`, and `openPage()` accepts an options object. These are intentional source-level type breaks in the 2.0 major; runtime wrapper wire and timing remain compatible with 1.0.
114
+
55
115
  ## Native-only methods
56
116
 
57
117
  Payment, native login, ads, file access, offline packages, native blocks, app navigation and host-defined methods still require a SuperSDK App container. Importing this package does not emulate those capabilities in a browser.
58
118
 
119
+ Low-level bridge failures reject `SuperSDKError` with stable codes including `BRIDGE_ABSENT`, `BRIDGE_INCOMPATIBLE`, `BRIDGE_DEGRADED`, `BRIDGE_ERROR`, `CANCELLED`, `TIMEOUT` and `DISPOSED`. Unknown non-empty provider codes become `BRIDGE_ERROR` with `nativeCode: "UNKNOWN"`; malformed envelopes become `PROTOCOL_MISMATCH`.
120
+
59
121
  ## Privacy and trust
60
122
 
61
123
  Browser analytics data is anonymous/untrusted input and must not be used for authentication, billing or security decisions. Denying or revoking analytics removes SDK-owned persistent identity and pending browser events. Diagnostics never include event parameters, settings bodies, URL query/hash, request headers, spid or device ID values.