uni-webview-rpc 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +213 -2
- package/browser/uni-webview-rpc.js +979 -0
- package/browser/uni.webview.js +1 -0
- package/lib/auto.cjs +976 -0
- package/lib/context.cjs +181 -0
- package/lib/defaults.cjs +173 -0
- package/lib/h5.cjs +972 -0
- package/lib/host.cjs +937 -0
- package/lib/index.cjs +1170 -0
- package/lib/transports.cjs +436 -0
- package/package.json +81 -4
- package/src/auto.js +17 -0
- package/src/config.js +18 -0
- package/src/context.js +174 -0
- package/src/core.js +312 -0
- package/src/defaults.js +146 -0
- package/src/h5.js +350 -0
- package/src/host.js +99 -0
- package/src/index.js +16 -0
- package/src/protocol.js +210 -0
- package/src/transports/app.js +91 -0
- package/src/transports/h5.js +16 -0
- package/src/transports/index.js +69 -0
- package/src/transports/mp.js +90 -0
- package/src/transports/postmessage.js +106 -0
- package/types/index.d.ts +213 -0
- package/vendor/uni.webview.js +1 -0
|
@@ -0,0 +1,979 @@
|
|
|
1
|
+
/* uni-webview-rpc · 自动生成,请勿直接编辑;改 src/ 后执行 yarn build */
|
|
2
|
+
var WebViewBridgeSDK = (() => {
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
+
var __export = (target, all) => {
|
|
8
|
+
for (var name in all)
|
|
9
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
|
+
};
|
|
11
|
+
var __copyProps = (to, from, except, desc) => {
|
|
12
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
13
|
+
for (let key of __getOwnPropNames(from))
|
|
14
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
15
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
16
|
+
}
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
20
|
+
|
|
21
|
+
// src/auto.js
|
|
22
|
+
var auto_exports = {};
|
|
23
|
+
__export(auto_exports, {
|
|
24
|
+
api: () => api,
|
|
25
|
+
boot: () => boot,
|
|
26
|
+
default: () => auto_default
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
// src/protocol.js
|
|
30
|
+
var PROTOCOL_VERSION = 1;
|
|
31
|
+
var DEFAULT_CHANNEL = "webview.rpc";
|
|
32
|
+
var LEGACY_CHANNEL = "isee.bridge";
|
|
33
|
+
var MAX_FRAME_CHARS = 64 * 1024;
|
|
34
|
+
var DEFAULT_PARAM_PREFIX = "__wvrpc_";
|
|
35
|
+
var LEGACY_PARAM_PREFIX = "__isee_";
|
|
36
|
+
var FRAME_FIELD = "__wvrpc_frame__";
|
|
37
|
+
var LEGACY_FRAME_FIELD = "__isee_frame__";
|
|
38
|
+
var PARAM = {
|
|
39
|
+
ENABLED: `${DEFAULT_PARAM_PREFIX}bridge__`,
|
|
40
|
+
HOST: `${DEFAULT_PARAM_PREFIX}host__`,
|
|
41
|
+
SITE: `${DEFAULT_PARAM_PREFIX}site__`,
|
|
42
|
+
SESSION: `${DEFAULT_PARAM_PREFIX}session__`,
|
|
43
|
+
TIMESTAMP: `${DEFAULT_PARAM_PREFIX}t__`
|
|
44
|
+
};
|
|
45
|
+
var ROLE = {
|
|
46
|
+
HOST: "host",
|
|
47
|
+
H5: "h5"
|
|
48
|
+
};
|
|
49
|
+
var KIND = {
|
|
50
|
+
REQUEST: "req",
|
|
51
|
+
RESPONSE: "res",
|
|
52
|
+
EVENT: "evt",
|
|
53
|
+
READY: "ready",
|
|
54
|
+
PING: "ping",
|
|
55
|
+
PONG: "pong"
|
|
56
|
+
};
|
|
57
|
+
var ERROR_CODE = {
|
|
58
|
+
TIMEOUT: "BRIDGE_TIMEOUT",
|
|
59
|
+
METHOD_NOT_FOUND: "METHOD_NOT_FOUND",
|
|
60
|
+
HANDLER_ERROR: "HANDLER_ERROR",
|
|
61
|
+
TRANSPORT_CLOSED: "TRANSPORT_CLOSED",
|
|
62
|
+
UNAVAILABLE: "BRIDGE_UNAVAILABLE",
|
|
63
|
+
PAYLOAD_TOO_LARGE: "PAYLOAD_TOO_LARGE",
|
|
64
|
+
PROTOCOL: "PROTOCOL_ERROR"
|
|
65
|
+
};
|
|
66
|
+
var KIND_SET = new Set(Object.values(KIND));
|
|
67
|
+
var BridgeError = class _BridgeError extends Error {
|
|
68
|
+
constructor(code, message, data) {
|
|
69
|
+
super(message || code);
|
|
70
|
+
this.name = "BridgeError";
|
|
71
|
+
this.code = code || ERROR_CODE.HANDLER_ERROR;
|
|
72
|
+
this.data = data;
|
|
73
|
+
}
|
|
74
|
+
toJSON() {
|
|
75
|
+
return { code: this.code, message: this.message, data: this.data };
|
|
76
|
+
}
|
|
77
|
+
static from(value) {
|
|
78
|
+
if (!value) return new _BridgeError(ERROR_CODE.HANDLER_ERROR, "unknown bridge error");
|
|
79
|
+
if (value instanceof _BridgeError) return value;
|
|
80
|
+
if (typeof value === "string") return new _BridgeError(ERROR_CODE.HANDLER_ERROR, value);
|
|
81
|
+
return new _BridgeError(value.code || ERROR_CODE.HANDLER_ERROR, value.message || "remote error", value.data);
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
function normalizeError(err, fallbackCode = ERROR_CODE.HANDLER_ERROR) {
|
|
85
|
+
if (err instanceof BridgeError) return err.toJSON();
|
|
86
|
+
if (err && typeof err === "object" && err.code && err.message) {
|
|
87
|
+
return { code: String(err.code), message: String(err.message), data: err.data };
|
|
88
|
+
}
|
|
89
|
+
return {
|
|
90
|
+
code: fallbackCode,
|
|
91
|
+
message: err && err.message ? String(err.message) : String(err != null ? err : "unknown error")
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
var globalSeq = 0;
|
|
95
|
+
function nextFrameId(role = ROLE.HOST) {
|
|
96
|
+
globalSeq += 1;
|
|
97
|
+
return `${role}-${Date.now().toString(36)}-${globalSeq.toString(36)}`;
|
|
98
|
+
}
|
|
99
|
+
function base(kind, extra, channel, from) {
|
|
100
|
+
return {
|
|
101
|
+
v: PROTOCOL_VERSION,
|
|
102
|
+
ch: channel || DEFAULT_CHANNEL,
|
|
103
|
+
k: kind,
|
|
104
|
+
ts: Date.now(),
|
|
105
|
+
from,
|
|
106
|
+
...extra
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
function makeRequest({ id, method, params, channel, from }) {
|
|
110
|
+
if (!method || typeof method !== "string") throw new TypeError("[bridge] method \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");
|
|
111
|
+
return base(KIND.REQUEST, { id: id || nextFrameId(from), m: method, p: params != null ? params : {} }, channel, from);
|
|
112
|
+
}
|
|
113
|
+
function makeResponse(requestFrame, { result, error, channel, from }) {
|
|
114
|
+
const payload = error ? { e: normalizeError(error) } : { r: result != null ? result : null };
|
|
115
|
+
return base(KIND.RESPONSE, { id: requestFrame.id, ...payload }, channel || requestFrame.ch, from);
|
|
116
|
+
}
|
|
117
|
+
function makeEvent({ method, params, channel, from }) {
|
|
118
|
+
return base(KIND.EVENT, { m: method, p: params != null ? params : {} }, channel, from);
|
|
119
|
+
}
|
|
120
|
+
function makeReady({ info, channel, from, id }) {
|
|
121
|
+
return base(KIND.READY, { id: id || nextFrameId(from), m: "bridge/ready", p: info != null ? info : {} }, channel, from);
|
|
122
|
+
}
|
|
123
|
+
function makePing({ channel, from, id }) {
|
|
124
|
+
return base(KIND.PING, { id: id || nextFrameId(from), m: "bridge/ping" }, channel, from);
|
|
125
|
+
}
|
|
126
|
+
function makePong(pingFrame, { channel, from, info }) {
|
|
127
|
+
return base(KIND.PONG, { id: pingFrame.id, m: "bridge/pong", p: info != null ? info : {} }, channel || pingFrame.ch, from);
|
|
128
|
+
}
|
|
129
|
+
function encodeFrame(frame, maxChars = MAX_FRAME_CHARS) {
|
|
130
|
+
const text = JSON.stringify(frame);
|
|
131
|
+
if (text.length > maxChars) {
|
|
132
|
+
throw new BridgeError(ERROR_CODE.PAYLOAD_TOO_LARGE, `\u5E27\u8FC7\u5927: ${text.length} > ${maxChars} \u5B57\u7B26`);
|
|
133
|
+
}
|
|
134
|
+
return text;
|
|
135
|
+
}
|
|
136
|
+
function decodeFrame(raw, { channel = DEFAULT_CHANNEL, version = PROTOCOL_VERSION } = {}) {
|
|
137
|
+
let value = raw;
|
|
138
|
+
if (typeof raw === "string") {
|
|
139
|
+
try {
|
|
140
|
+
value = JSON.parse(raw);
|
|
141
|
+
} catch (e) {
|
|
142
|
+
return null;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
146
|
+
const accepted = Array.isArray(channel) ? channel : [.../* @__PURE__ */ new Set([channel, DEFAULT_CHANNEL, LEGACY_CHANNEL])];
|
|
147
|
+
if (!accepted.includes(value.ch)) return null;
|
|
148
|
+
if (value.v !== version) return null;
|
|
149
|
+
if (!KIND_SET.has(value.k)) return null;
|
|
150
|
+
if (value.k === KIND.RESPONSE && typeof value.id !== "string") return null;
|
|
151
|
+
if ((value.k === KIND.REQUEST || value.k === KIND.EVENT) && typeof value.m !== "string") return null;
|
|
152
|
+
return value;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// src/config.js
|
|
156
|
+
var BRIDGE_CONFIG = {
|
|
157
|
+
channel: DEFAULT_CHANNEL,
|
|
158
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
159
|
+
timeout: 1e4,
|
|
160
|
+
readyTimeout: 6e3,
|
|
161
|
+
maxPayload: 64 * 1024
|
|
162
|
+
};
|
|
163
|
+
function resolveConfig(overrides = {}) {
|
|
164
|
+
return { ...BRIDGE_CONFIG, ...overrides };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// src/core.js
|
|
168
|
+
var noop = () => {
|
|
169
|
+
};
|
|
170
|
+
function createBridgeCore({
|
|
171
|
+
transport,
|
|
172
|
+
role = ROLE.HOST,
|
|
173
|
+
channel = DEFAULT_CHANNEL,
|
|
174
|
+
timeout = 1e4,
|
|
175
|
+
handlers = {},
|
|
176
|
+
onLog = noop,
|
|
177
|
+
onReadyChange = noop
|
|
178
|
+
} = {}) {
|
|
179
|
+
if (!transport || typeof transport.send !== "function" || typeof transport.onFrame !== "function") {
|
|
180
|
+
throw new TypeError("[bridge] transport \u5FC5\u987B\u5B9E\u73B0 send(frame) / onFrame(cb)");
|
|
181
|
+
}
|
|
182
|
+
const pending = /* @__PURE__ */ new Map();
|
|
183
|
+
const handlerMap = /* @__PURE__ */ new Map();
|
|
184
|
+
const eventListeners = /* @__PURE__ */ new Map();
|
|
185
|
+
const seenResponses = /* @__PURE__ */ new Set();
|
|
186
|
+
let closed = false;
|
|
187
|
+
let ready = false;
|
|
188
|
+
for (const [name, fn] of Object.entries(handlers || {})) {
|
|
189
|
+
if (typeof fn === "function") handlerMap.set(name, fn);
|
|
190
|
+
}
|
|
191
|
+
const readyPromise = Promise.resolve(transport.ready).catch(() => {
|
|
192
|
+
});
|
|
193
|
+
function log(dir, frame, note = "") {
|
|
194
|
+
try {
|
|
195
|
+
onLog({ dir, frame, note, at: Date.now(), role });
|
|
196
|
+
} catch (e) {
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
function notifyReady(value) {
|
|
200
|
+
if (ready === value) return;
|
|
201
|
+
ready = value;
|
|
202
|
+
onReadyChange(value);
|
|
203
|
+
}
|
|
204
|
+
readyPromise.then(() => {
|
|
205
|
+
if (!closed) notifyReady(true);
|
|
206
|
+
});
|
|
207
|
+
function safeSend(frame) {
|
|
208
|
+
if (closed) throw new BridgeError(ERROR_CODE.TRANSPORT_CLOSED, "\u6865\u5DF2\u5173\u95ED");
|
|
209
|
+
encodeFrame(frame);
|
|
210
|
+
transport.send(frame);
|
|
211
|
+
log("out", frame);
|
|
212
|
+
}
|
|
213
|
+
function rejectPending(entry, error) {
|
|
214
|
+
clearTimeout(entry.timer);
|
|
215
|
+
pending.delete(entry.frame.id);
|
|
216
|
+
entry.reject(error instanceof Error ? error : BridgeError.from(error));
|
|
217
|
+
}
|
|
218
|
+
function handleResponse(frame) {
|
|
219
|
+
const key = frame.id;
|
|
220
|
+
if (seenResponses.has(key)) return;
|
|
221
|
+
seenResponses.add(key);
|
|
222
|
+
if (seenResponses.size > 500) seenResponses.clear();
|
|
223
|
+
const entry = pending.get(key);
|
|
224
|
+
if (!entry) return;
|
|
225
|
+
clearTimeout(entry.timer);
|
|
226
|
+
pending.delete(key);
|
|
227
|
+
if (frame.e) entry.reject(BridgeError.from(frame.e));
|
|
228
|
+
else entry.resolve(frame.r);
|
|
229
|
+
}
|
|
230
|
+
function handleRequest(frame) {
|
|
231
|
+
const fn = handlerMap.get(frame.m);
|
|
232
|
+
const ctx = { frame, role, from: frame.from, channel };
|
|
233
|
+
if (!fn) {
|
|
234
|
+
try {
|
|
235
|
+
safeSend(makeResponse(frame, {
|
|
236
|
+
error: new BridgeError(ERROR_CODE.METHOD_NOT_FOUND, `\u5BF9\u7AEF\u672A\u6CE8\u518C\u65B9\u6CD5: ${frame.m}`),
|
|
237
|
+
from: role
|
|
238
|
+
}));
|
|
239
|
+
} catch (err) {
|
|
240
|
+
log("out", frame, `\u56DE\u4F20 METHOD_NOT_FOUND \u5931\u8D25: ${err.message}`);
|
|
241
|
+
}
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
Promise.resolve().then(() => {
|
|
245
|
+
var _a;
|
|
246
|
+
return fn((_a = frame.p) != null ? _a : {}, ctx);
|
|
247
|
+
}).then((result) => {
|
|
248
|
+
if (closed) return;
|
|
249
|
+
safeSend(makeResponse(frame, { result, from: role }));
|
|
250
|
+
}).catch((err) => {
|
|
251
|
+
if (closed) return;
|
|
252
|
+
try {
|
|
253
|
+
safeSend(makeResponse(frame, { error: normalizeError(err), from: role }));
|
|
254
|
+
} catch (e) {
|
|
255
|
+
log("out", frame, `\u56DE\u4F20\u9519\u8BEF\u5931\u8D25: ${e.message}`);
|
|
256
|
+
}
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
function handleEvent(frame) {
|
|
260
|
+
var _a;
|
|
261
|
+
const list = eventListeners.get(frame.m);
|
|
262
|
+
if (!list || !list.size) return;
|
|
263
|
+
for (const fn of Array.from(list)) {
|
|
264
|
+
try {
|
|
265
|
+
fn((_a = frame.p) != null ? _a : {}, { frame, from: frame.from });
|
|
266
|
+
} catch (err) {
|
|
267
|
+
log("in", frame, `\u4E8B\u4EF6\u76D1\u542C\u5668\u629B\u9519: ${err.message}`);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
function handleFrame(frame) {
|
|
272
|
+
var _a, _b, _c;
|
|
273
|
+
if (closed || !frame) return;
|
|
274
|
+
log("in", frame);
|
|
275
|
+
if (frame.k === KIND.READY) {
|
|
276
|
+
(_a = transport.onReadyFrame) == null ? void 0 : _a.call(transport, frame);
|
|
277
|
+
notifyReady(true);
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
if (frame.k === KIND.PING) {
|
|
281
|
+
(_b = transport.onPing) == null ? void 0 : _b.call(transport, frame);
|
|
282
|
+
try {
|
|
283
|
+
safeSend(makePong(frame, { from: role, info: { role } }));
|
|
284
|
+
} catch (e) {
|
|
285
|
+
}
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
if (frame.k === KIND.PONG) {
|
|
289
|
+
(_c = transport.onPong) == null ? void 0 : _c.call(transport, frame);
|
|
290
|
+
const entry = pending.get(frame.id);
|
|
291
|
+
if (entry) {
|
|
292
|
+
clearTimeout(entry.timer);
|
|
293
|
+
pending.delete(frame.id);
|
|
294
|
+
entry.resolve(frame.p || {});
|
|
295
|
+
}
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
switch (frame.k) {
|
|
299
|
+
case KIND.RESPONSE:
|
|
300
|
+
handleResponse(frame);
|
|
301
|
+
break;
|
|
302
|
+
case KIND.REQUEST:
|
|
303
|
+
handleRequest(frame);
|
|
304
|
+
break;
|
|
305
|
+
case KIND.EVENT:
|
|
306
|
+
handleEvent(frame);
|
|
307
|
+
break;
|
|
308
|
+
default:
|
|
309
|
+
break;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
transport.onFrame(handleFrame);
|
|
313
|
+
return {
|
|
314
|
+
/** 调用对端注册的方法,返回 Promise */
|
|
315
|
+
call(method, params = {}, callOptions = {}) {
|
|
316
|
+
if (closed) {
|
|
317
|
+
return Promise.reject(new BridgeError(ERROR_CODE.TRANSPORT_CLOSED, "\u6865\u5DF2\u5173\u95ED"));
|
|
318
|
+
}
|
|
319
|
+
if (typeof transport.canCall === "function" && !transport.canCall()) {
|
|
320
|
+
return Promise.reject(new BridgeError(
|
|
321
|
+
ERROR_CODE.UNAVAILABLE,
|
|
322
|
+
transport.unavailableReason || "\u5F53\u524D\u7AEF\u4E0D\u652F\u6301\u5B9E\u65F6 RPC"
|
|
323
|
+
));
|
|
324
|
+
}
|
|
325
|
+
const ms = Number(callOptions.timeout) > 0 ? Number(callOptions.timeout) : timeout;
|
|
326
|
+
const frame = makeRequest({ method, params, channel, from: role });
|
|
327
|
+
return new Promise((resolve, reject) => {
|
|
328
|
+
const timer = setTimeout(() => {
|
|
329
|
+
if (!pending.has(frame.id)) return;
|
|
330
|
+
pending.delete(frame.id);
|
|
331
|
+
reject(new BridgeError(ERROR_CODE.TIMEOUT, `\u8C03\u7528 ${method} \u8D85\u65F6 (${ms}ms)`));
|
|
332
|
+
}, ms);
|
|
333
|
+
const entry = { resolve, reject, timer, frame, startedAt: Date.now() };
|
|
334
|
+
pending.set(frame.id, entry);
|
|
335
|
+
readyPromise.then(() => {
|
|
336
|
+
if (!pending.has(frame.id)) return;
|
|
337
|
+
try {
|
|
338
|
+
safeSend(frame);
|
|
339
|
+
} catch (err) {
|
|
340
|
+
rejectPending(entry, err);
|
|
341
|
+
}
|
|
342
|
+
});
|
|
343
|
+
});
|
|
344
|
+
},
|
|
345
|
+
/** 注册供对端调用的方法(支持 async) */
|
|
346
|
+
register(method, fn) {
|
|
347
|
+
if (typeof fn !== "function") throw new TypeError("[bridge] handler \u5FC5\u987B\u662F\u51FD\u6570");
|
|
348
|
+
handlerMap.set(method, fn);
|
|
349
|
+
return () => handlerMap.delete(method);
|
|
350
|
+
},
|
|
351
|
+
registerMany(map) {
|
|
352
|
+
for (const [name, fn] of Object.entries(map || {})) this.register(name, fn);
|
|
353
|
+
return this;
|
|
354
|
+
},
|
|
355
|
+
unregister(method) {
|
|
356
|
+
handlerMap.delete(method);
|
|
357
|
+
},
|
|
358
|
+
hasMethod(method) {
|
|
359
|
+
return handlerMap.has(method);
|
|
360
|
+
},
|
|
361
|
+
listMethods() {
|
|
362
|
+
return Array.from(handlerMap.keys());
|
|
363
|
+
},
|
|
364
|
+
/** 单向广播,不等待返回值 */
|
|
365
|
+
emit(method, params = {}) {
|
|
366
|
+
safeSend(makeEvent({ method, params, channel, from: role }));
|
|
367
|
+
},
|
|
368
|
+
/** 订阅对端广播的事件 */
|
|
369
|
+
on(method, fn) {
|
|
370
|
+
if (!eventListeners.has(method)) eventListeners.set(method, /* @__PURE__ */ new Set());
|
|
371
|
+
eventListeners.get(method).add(fn);
|
|
372
|
+
return () => {
|
|
373
|
+
var _a;
|
|
374
|
+
return (_a = eventListeners.get(method)) == null ? void 0 : _a.delete(fn);
|
|
375
|
+
};
|
|
376
|
+
},
|
|
377
|
+
off(method, fn) {
|
|
378
|
+
var _a;
|
|
379
|
+
(_a = eventListeners.get(method)) == null ? void 0 : _a.delete(fn);
|
|
380
|
+
},
|
|
381
|
+
/** 主动探测对端是否在线;PONG 由 core 的 handleFrame 按 id 配对 resolve */
|
|
382
|
+
ping(timeoutMs = 3e3) {
|
|
383
|
+
if (closed) return Promise.reject(new BridgeError(ERROR_CODE.TRANSPORT_CLOSED, "\u6865\u5DF2\u5173\u95ED"));
|
|
384
|
+
if (typeof transport.canCall === "function" && !transport.canCall()) {
|
|
385
|
+
return Promise.reject(new BridgeError(
|
|
386
|
+
ERROR_CODE.UNAVAILABLE,
|
|
387
|
+
transport.unavailableReason || "\u5F53\u524D\u7AEF\u4E0D\u652F\u6301\u5B9E\u65F6 RPC"
|
|
388
|
+
));
|
|
389
|
+
}
|
|
390
|
+
const frame = makePing({ channel, from: role });
|
|
391
|
+
return new Promise((resolve, reject) => {
|
|
392
|
+
const timer = setTimeout(() => {
|
|
393
|
+
if (!pending.has(frame.id)) return;
|
|
394
|
+
pending.delete(frame.id);
|
|
395
|
+
reject(new BridgeError(ERROR_CODE.TIMEOUT, `ping \u8D85\u65F6 (${timeoutMs}ms)`));
|
|
396
|
+
}, timeoutMs);
|
|
397
|
+
pending.set(frame.id, { resolve, reject, timer, frame });
|
|
398
|
+
readyPromise.then(() => {
|
|
399
|
+
if (!pending.has(frame.id)) return;
|
|
400
|
+
try {
|
|
401
|
+
safeSend(frame);
|
|
402
|
+
} catch (err) {
|
|
403
|
+
const entry = pending.get(frame.id);
|
|
404
|
+
if (entry) rejectPending(entry, err);
|
|
405
|
+
}
|
|
406
|
+
});
|
|
407
|
+
});
|
|
408
|
+
},
|
|
409
|
+
get isReady() {
|
|
410
|
+
return ready;
|
|
411
|
+
},
|
|
412
|
+
get pendingCount() {
|
|
413
|
+
return pending.size;
|
|
414
|
+
},
|
|
415
|
+
waitReady() {
|
|
416
|
+
return readyPromise;
|
|
417
|
+
},
|
|
418
|
+
/** 页面卸载时调用:清理定时器、拒绝所有悬着的 Promise */
|
|
419
|
+
destroy() {
|
|
420
|
+
var _a;
|
|
421
|
+
if (closed) return;
|
|
422
|
+
closed = true;
|
|
423
|
+
for (const entry of Array.from(pending.values())) {
|
|
424
|
+
clearTimeout(entry.timer);
|
|
425
|
+
entry.reject(new BridgeError(ERROR_CODE.TRANSPORT_CLOSED, "\u6865\u5DF2\u5173\u95ED"));
|
|
426
|
+
}
|
|
427
|
+
pending.clear();
|
|
428
|
+
eventListeners.clear();
|
|
429
|
+
notifyReady(false);
|
|
430
|
+
(_a = transport.destroy) == null ? void 0 : _a.call(transport);
|
|
431
|
+
}
|
|
432
|
+
};
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
// src/context.js
|
|
436
|
+
function makeParams(paramPrefix = DEFAULT_PARAM_PREFIX) {
|
|
437
|
+
return {
|
|
438
|
+
enabled: `${paramPrefix}bridge__`,
|
|
439
|
+
host: `${paramPrefix}host__`,
|
|
440
|
+
site: `${paramPrefix}site__`,
|
|
441
|
+
session: `${paramPrefix}session__`,
|
|
442
|
+
parent: `${paramPrefix}parent__`,
|
|
443
|
+
uniWebview: `${paramPrefix}uniwebview__`,
|
|
444
|
+
init: `${paramPrefix}init__`,
|
|
445
|
+
channel: `${paramPrefix}channel__`,
|
|
446
|
+
timestamp: `${paramPrefix}t__`
|
|
447
|
+
};
|
|
448
|
+
}
|
|
449
|
+
function parseSearch(search = "") {
|
|
450
|
+
const out = {};
|
|
451
|
+
const raw = String(search || "");
|
|
452
|
+
const qIndex = raw.indexOf("?");
|
|
453
|
+
const body = qIndex >= 0 ? raw.slice(qIndex + 1) : raw.replace(/^#.*$/, "");
|
|
454
|
+
if (!body) return out;
|
|
455
|
+
for (const part of body.split("&")) {
|
|
456
|
+
if (!part) continue;
|
|
457
|
+
const eq = part.indexOf("=");
|
|
458
|
+
const key = eq < 0 ? part : part.slice(0, eq);
|
|
459
|
+
const value = eq < 0 ? "" : part.slice(eq + 1);
|
|
460
|
+
try {
|
|
461
|
+
out[decodeURIComponent(key)] = decodeURIComponent(value);
|
|
462
|
+
} catch (e) {
|
|
463
|
+
out[key] = value;
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
return out;
|
|
467
|
+
}
|
|
468
|
+
function makeReader(q, paramPrefix) {
|
|
469
|
+
const p = makeParams(paramPrefix);
|
|
470
|
+
const legacy = paramPrefix === DEFAULT_PARAM_PREFIX ? makeParams(LEGACY_PARAM_PREFIX) : null;
|
|
471
|
+
const read = (name, fallback = "") => {
|
|
472
|
+
if (q[p[name]] !== void 0) return q[p[name]];
|
|
473
|
+
if (legacy && q[legacy[name]] !== void 0) return q[legacy[name]];
|
|
474
|
+
return fallback;
|
|
475
|
+
};
|
|
476
|
+
return { p, read };
|
|
477
|
+
}
|
|
478
|
+
function readH5Context({
|
|
479
|
+
search = typeof location !== "undefined" ? location.search : "",
|
|
480
|
+
paramPrefix = DEFAULT_PARAM_PREFIX
|
|
481
|
+
} = {}) {
|
|
482
|
+
const { p, read } = makeReader(parseSearch(search), paramPrefix);
|
|
483
|
+
const parseOrigins = (raw) => raw ? raw.split(",").map((s) => s.trim()).filter(Boolean) : [];
|
|
484
|
+
return {
|
|
485
|
+
paramPrefix,
|
|
486
|
+
params: p,
|
|
487
|
+
enabled: read("enabled") === "1",
|
|
488
|
+
host: read("host"),
|
|
489
|
+
siteId: read("site"),
|
|
490
|
+
sessionId: read("session"),
|
|
491
|
+
channel: read("channel") || DEFAULT_CHANNEL,
|
|
492
|
+
uniWebviewPath: read("uniWebview") || "./uni.webview.js",
|
|
493
|
+
parentOrigins: parseOrigins(read("parent")),
|
|
494
|
+
initFrames: read("init")
|
|
495
|
+
};
|
|
496
|
+
}
|
|
497
|
+
function detectHost(ctx) {
|
|
498
|
+
if (ctx.host === "app" || ctx.host === "mp" || ctx.host === "h5") return ctx.host;
|
|
499
|
+
if (typeof window === "undefined") return "standalone";
|
|
500
|
+
if (window.__wxjs_environment === "miniprogram" || /miniProgram/i.test(navigator.userAgent)) return "mp";
|
|
501
|
+
if (window.plus || window.uni && typeof window.uni.postMessage === "function") return "app";
|
|
502
|
+
if (window.parent !== window) return "h5";
|
|
503
|
+
return "standalone";
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
// src/transports/postmessage.js
|
|
507
|
+
var noop2 = () => {
|
|
508
|
+
};
|
|
509
|
+
function createPostMessageTransport({
|
|
510
|
+
getTargetWindow,
|
|
511
|
+
getExpectedSource = () => null,
|
|
512
|
+
allowedOrigins = [],
|
|
513
|
+
initialTargetOrigin = "*",
|
|
514
|
+
channel,
|
|
515
|
+
onLog = noop2
|
|
516
|
+
} = {}) {
|
|
517
|
+
const listeners = [];
|
|
518
|
+
let learnedOrigin = "";
|
|
519
|
+
let closed = false;
|
|
520
|
+
const seenRequests = /* @__PURE__ */ new Set();
|
|
521
|
+
let resolveReady;
|
|
522
|
+
const ready = new Promise((resolve) => {
|
|
523
|
+
resolveReady = resolve;
|
|
524
|
+
});
|
|
525
|
+
function targetOrigin() {
|
|
526
|
+
return learnedOrigin || initialTargetOrigin;
|
|
527
|
+
}
|
|
528
|
+
function emit(frame) {
|
|
529
|
+
if (frame.k === KIND.REQUEST) {
|
|
530
|
+
if (seenRequests.has(frame.id)) return;
|
|
531
|
+
seenRequests.add(frame.id);
|
|
532
|
+
if (seenRequests.size > 300) seenRequests.clear();
|
|
533
|
+
}
|
|
534
|
+
for (const fn of listeners.slice()) fn(frame);
|
|
535
|
+
}
|
|
536
|
+
function onMessage(event) {
|
|
537
|
+
if (closed) return;
|
|
538
|
+
const expected = getExpectedSource();
|
|
539
|
+
if (expected && event.source !== expected) return;
|
|
540
|
+
if (allowedOrigins.length && event.origin && !allowedOrigins.includes(event.origin)) return;
|
|
541
|
+
const frame = decodeFrame(event.data, { channel });
|
|
542
|
+
if (!frame) return;
|
|
543
|
+
if (event.origin && event.origin !== "null") {
|
|
544
|
+
if (!learnedOrigin) {
|
|
545
|
+
learnedOrigin = event.origin;
|
|
546
|
+
onLog(`\u5DF2\u9501\u5B9A\u7236\u7A97\u53E3 origin: ${learnedOrigin}`);
|
|
547
|
+
} else if (learnedOrigin !== event.origin) {
|
|
548
|
+
return;
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
resolveReady();
|
|
552
|
+
emit(frame);
|
|
553
|
+
}
|
|
554
|
+
if (typeof window !== "undefined" && window.addEventListener) {
|
|
555
|
+
window.addEventListener("message", onMessage, false);
|
|
556
|
+
}
|
|
557
|
+
return {
|
|
558
|
+
name: "postmessage",
|
|
559
|
+
realtime: true,
|
|
560
|
+
duplex: true,
|
|
561
|
+
ready,
|
|
562
|
+
note: "iframe / \u7236\u7A97\u53E3\uFF0C\u53CC\u5411\u5B9E\u65F6",
|
|
563
|
+
channel,
|
|
564
|
+
onFrame(cb) {
|
|
565
|
+
listeners.push(cb);
|
|
566
|
+
},
|
|
567
|
+
send(frame) {
|
|
568
|
+
if (closed) throw new BridgeError(ERROR_CODE.TRANSPORT_CLOSED, "postMessage \u901A\u9053\u5DF2\u5173\u95ED");
|
|
569
|
+
const win = getTargetWindow == null ? void 0 : getTargetWindow();
|
|
570
|
+
if (!win) throw new BridgeError(ERROR_CODE.UNAVAILABLE, "\u76EE\u6807\u7A97\u53E3\u4E0D\u53EF\u7528");
|
|
571
|
+
win.postMessage(encodeFrame(frame), targetOrigin());
|
|
572
|
+
},
|
|
573
|
+
/** 外部(例如 iframe load 事件)也可直接喂帧 */
|
|
574
|
+
receive(raw) {
|
|
575
|
+
const frame = decodeFrame(raw, { channel });
|
|
576
|
+
if (frame) {
|
|
577
|
+
resolveReady();
|
|
578
|
+
emit(frame);
|
|
579
|
+
}
|
|
580
|
+
},
|
|
581
|
+
markLoaded() {
|
|
582
|
+
setTimeout(resolveReady, 50);
|
|
583
|
+
},
|
|
584
|
+
setReady() {
|
|
585
|
+
resolveReady();
|
|
586
|
+
},
|
|
587
|
+
get learnedOrigin() {
|
|
588
|
+
return learnedOrigin;
|
|
589
|
+
},
|
|
590
|
+
destroy() {
|
|
591
|
+
closed = true;
|
|
592
|
+
listeners.length = 0;
|
|
593
|
+
if (typeof window !== "undefined" && window.removeEventListener) {
|
|
594
|
+
window.removeEventListener("message", onMessage, false);
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
};
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
// src/defaults.js
|
|
601
|
+
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
602
|
+
function createH5Handlers() {
|
|
603
|
+
return {
|
|
604
|
+
"page.getInfo": () => ({
|
|
605
|
+
title: document.title,
|
|
606
|
+
href: location.href,
|
|
607
|
+
hash: location.hash,
|
|
608
|
+
origin: location.origin,
|
|
609
|
+
userAgent: navigator.userAgent,
|
|
610
|
+
readyState: document.readyState,
|
|
611
|
+
viewport: { width: innerWidth, height: innerHeight },
|
|
612
|
+
at: Date.now()
|
|
613
|
+
}),
|
|
614
|
+
"page.getRoute": () => ({ hash: location.hash, search: location.search, pathname: location.pathname }),
|
|
615
|
+
"page.echo": (params) => ({ echoed: params != null ? params : {}, at: Date.now() }),
|
|
616
|
+
"page.delay": async ({ ms = 300 } = {}) => {
|
|
617
|
+
const wait = Math.min(Math.max(Number(ms) || 0, 0), 1e4);
|
|
618
|
+
await sleep(wait);
|
|
619
|
+
return { waited: wait, at: Date.now() };
|
|
620
|
+
},
|
|
621
|
+
"page.fail": ({ message = "H5 \u6545\u610F\u629B\u51FA\u7684\u9519\u8BEF" } = {}) => {
|
|
622
|
+
throw new Error(message);
|
|
623
|
+
},
|
|
624
|
+
"page.setTitle": ({ title } = {}) => {
|
|
625
|
+
if (!title) throw new Error("\u7F3A\u5C11 title");
|
|
626
|
+
document.title = String(title);
|
|
627
|
+
return { title: document.title };
|
|
628
|
+
},
|
|
629
|
+
"page.scrollTo": ({ top = 0 } = {}) => {
|
|
630
|
+
window.scrollTo({ top: Number(top) || 0, behavior: "smooth" });
|
|
631
|
+
return { top };
|
|
632
|
+
},
|
|
633
|
+
/** 宿主 -> H5 的可见效果:页面右上角浮一条提示 */
|
|
634
|
+
"page.notify": ({ message = "", duration = 2600 } = {}) => {
|
|
635
|
+
const id = "webview-rpc-toast";
|
|
636
|
+
let el = document.getElementById(id);
|
|
637
|
+
if (!el) {
|
|
638
|
+
el = document.createElement("div");
|
|
639
|
+
el.id = id;
|
|
640
|
+
el.style.cssText = "position:fixed;z-index:2147483647;top:16px;right:16px;max-width:75vw;padding:10px 14px;border-radius:10px;background:rgba(30,26,24,.92);color:#fff;font:14px/1.5 -apple-system,BlinkMacSystemFont,sans-serif;box-shadow:0 6px 24px rgba(0,0,0,.2);transition:opacity .2s;pointer-events:none";
|
|
641
|
+
document.body.appendChild(el);
|
|
642
|
+
}
|
|
643
|
+
el.textContent = String(message);
|
|
644
|
+
el.style.opacity = "1";
|
|
645
|
+
clearTimeout(el.__timer);
|
|
646
|
+
el.__timer = setTimeout(() => {
|
|
647
|
+
el.style.opacity = "0";
|
|
648
|
+
}, Number(duration) || 2600);
|
|
649
|
+
return { shown: true, message };
|
|
650
|
+
}
|
|
651
|
+
};
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
// src/h5.js
|
|
655
|
+
var VERSION = 1;
|
|
656
|
+
var noop3 = () => {
|
|
657
|
+
};
|
|
658
|
+
var DEFAULT_GLOBAL_NAMES = {
|
|
659
|
+
api: ["WebViewBridge", "IseeBridge"],
|
|
660
|
+
receive: ["__WEBVIEW_BRIDGE_RECEIVE__", "__ISEE_BRIDGE_RECEIVE__"],
|
|
661
|
+
readyEvent: ["WebViewBridgeReady", "IseeBridgeReady"],
|
|
662
|
+
hostEnvEvent: ["WebViewBridgeHostEnv", "IseeBridgeHostEnv"]
|
|
663
|
+
};
|
|
664
|
+
function loadScript(src, timeout = 8e3) {
|
|
665
|
+
return new Promise((resolve, reject) => {
|
|
666
|
+
if (typeof document === "undefined") {
|
|
667
|
+
reject(new Error("\u5F53\u524D\u73AF\u5883\u4E0D\u652F\u6301\u52A8\u6001\u52A0\u8F7D\u811A\u672C"));
|
|
668
|
+
return;
|
|
669
|
+
}
|
|
670
|
+
const existing = document.querySelector(`script[src="${src}"]`);
|
|
671
|
+
if (existing) {
|
|
672
|
+
resolve();
|
|
673
|
+
return;
|
|
674
|
+
}
|
|
675
|
+
const el = document.createElement("script");
|
|
676
|
+
const timer = setTimeout(() => reject(new Error(`\u52A0\u8F7D\u811A\u672C\u8D85\u65F6: ${src}`)), timeout);
|
|
677
|
+
el.src = src;
|
|
678
|
+
el.onload = () => {
|
|
679
|
+
clearTimeout(timer);
|
|
680
|
+
resolve();
|
|
681
|
+
};
|
|
682
|
+
el.onerror = () => {
|
|
683
|
+
clearTimeout(timer);
|
|
684
|
+
reject(new Error(`\u52A0\u8F7D\u811A\u672C\u5931\u8D25: ${src}`));
|
|
685
|
+
};
|
|
686
|
+
document.head.appendChild(el);
|
|
687
|
+
});
|
|
688
|
+
}
|
|
689
|
+
function createAppChannel({ ctx, emit, onStatus }) {
|
|
690
|
+
let senderReady = false;
|
|
691
|
+
let loadFailed = false;
|
|
692
|
+
let resolveReady;
|
|
693
|
+
const ready = new Promise((resolve) => {
|
|
694
|
+
resolveReady = resolve;
|
|
695
|
+
});
|
|
696
|
+
const pending = [];
|
|
697
|
+
function flush() {
|
|
698
|
+
while (pending.length) {
|
|
699
|
+
const frame = pending.shift();
|
|
700
|
+
try {
|
|
701
|
+
sendRaw(frame);
|
|
702
|
+
} catch (err) {
|
|
703
|
+
onStatus(`[app] \u5E27\u6295\u9012\u5931\u8D25\uFF1A${err.message}`);
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
loadScript(ctx.uniWebviewPath).then(() => {
|
|
708
|
+
const fire = () => {
|
|
709
|
+
senderReady = true;
|
|
710
|
+
resolveReady();
|
|
711
|
+
flush();
|
|
712
|
+
};
|
|
713
|
+
if (window.uni && typeof window.uni.postMessage === "function") fire();
|
|
714
|
+
else document.addEventListener("UniAppJSBridgeReady", fire, { once: true });
|
|
715
|
+
}).catch((err) => {
|
|
716
|
+
loadFailed = true;
|
|
717
|
+
onStatus(`[app] \u672A\u80FD\u52A0\u8F7D uni.webview.js: ${err.message}`);
|
|
718
|
+
resolveReady();
|
|
719
|
+
flush();
|
|
720
|
+
});
|
|
721
|
+
function sendRaw(frame) {
|
|
722
|
+
var _a, _b, _c;
|
|
723
|
+
const direct = typeof ((_a = window.uni) == null ? void 0 : _a.postMessage) === "function";
|
|
724
|
+
const fn = direct ? window.uni.postMessage : (_c = (_b = window.uni) == null ? void 0 : _b.webView) == null ? void 0 : _c.postMessage;
|
|
725
|
+
if (typeof fn !== "function") throw new BridgeError(ERROR_CODE.UNAVAILABLE, "uni.postMessage \u4E0D\u53EF\u7528");
|
|
726
|
+
const receiver = direct ? window.uni : window.uni.webView;
|
|
727
|
+
const text = encodeFrame(frame);
|
|
728
|
+
fn.call(receiver, { data: { [FRAME_FIELD]: text, [LEGACY_FRAME_FIELD]: text } });
|
|
729
|
+
}
|
|
730
|
+
return {
|
|
731
|
+
name: "app-webview",
|
|
732
|
+
realtime: true,
|
|
733
|
+
duplex: true,
|
|
734
|
+
ready,
|
|
735
|
+
note: "App \u7AEF H5\uFF1Auni.postMessage \u53D1 / evalJS \u6CE8\u5165\u6536",
|
|
736
|
+
send(frame) {
|
|
737
|
+
if (loadFailed) throw new BridgeError(ERROR_CODE.UNAVAILABLE, "uni.webview.js \u52A0\u8F7D\u5931\u8D25\uFF0C\u65E0\u6CD5\u4E0E\u5BBF\u4E3B\u901A\u8BAF");
|
|
738
|
+
if (!senderReady) pending.push(frame);
|
|
739
|
+
else sendRaw(frame);
|
|
740
|
+
},
|
|
741
|
+
receive(raw) {
|
|
742
|
+
emit(decodeFrame(raw, { channel: ctx.channel }));
|
|
743
|
+
},
|
|
744
|
+
canCall: () => !loadFailed,
|
|
745
|
+
destroy() {
|
|
746
|
+
pending.length = 0;
|
|
747
|
+
}
|
|
748
|
+
};
|
|
749
|
+
}
|
|
750
|
+
function createMpChannel({ ctx, emit }) {
|
|
751
|
+
let readyResolver;
|
|
752
|
+
const ready = new Promise((resolve) => {
|
|
753
|
+
readyResolver = resolve;
|
|
754
|
+
});
|
|
755
|
+
const JSSDK = "https://res.wx.qq.com/open/js/jweixin-1.4.0.js";
|
|
756
|
+
loadScript(JSSDK).then(() => readyResolver()).catch(() => readyResolver());
|
|
757
|
+
return {
|
|
758
|
+
name: "mp-webview",
|
|
759
|
+
realtime: false,
|
|
760
|
+
duplex: false,
|
|
761
|
+
ready,
|
|
762
|
+
note: "\u5C0F\u7A0B\u5E8F\u539F\u751F\u901A\u9053\uFF1ApostMessage \u4EC5\u5728\u540E\u9000/\u9500\u6BC1/\u5206\u4EAB/\u590D\u5236\u94FE\u63A5\u65F6\u9001\u8FBE",
|
|
763
|
+
send(frame) {
|
|
764
|
+
var _a, _b, _c, _d;
|
|
765
|
+
const fn = ((_b = (_a = window.wx) == null ? void 0 : _a.miniProgram) == null ? void 0 : _b.postMessage) || ((_c = window.uni) == null ? void 0 : _c.postMessage);
|
|
766
|
+
if (typeof fn !== "function") return;
|
|
767
|
+
const text = encodeFrame(frame);
|
|
768
|
+
fn.call(((_d = window.wx) == null ? void 0 : _d.miniProgram) || window.uni, {
|
|
769
|
+
data: { [FRAME_FIELD]: text, [LEGACY_FRAME_FIELD]: text }
|
|
770
|
+
});
|
|
771
|
+
},
|
|
772
|
+
canCall: () => false,
|
|
773
|
+
unavailableReason: "\u5FAE\u4FE1\u5C0F\u7A0B\u5E8F web-view \u7684 postMessage \u53EA\u5728\u540E\u9000/\u9500\u6BC1/\u5206\u4EAB\u65F6\u9001\u8FBE\uFF0C\u65E0\u6CD5\u5B9E\u65F6\u53CC\u5411\u901A\u8BAF\uFF0C\u6865\u5DF2\u964D\u7EA7\u3002",
|
|
774
|
+
destroy() {
|
|
775
|
+
}
|
|
776
|
+
};
|
|
777
|
+
}
|
|
778
|
+
function createStandaloneChannel() {
|
|
779
|
+
return {
|
|
780
|
+
name: "standalone",
|
|
781
|
+
realtime: false,
|
|
782
|
+
duplex: false,
|
|
783
|
+
ready: Promise.resolve(),
|
|
784
|
+
note: "\u672A\u68C0\u6D4B\u5230\u5916\u58F3\uFF0C\u6865\u5904\u4E8E\u505C\u7528\u72B6\u6001\uFF08\u7F51\u7AD9\u529F\u80FD\u4E0D\u53D7\u5F71\u54CD\uFF09",
|
|
785
|
+
send() {
|
|
786
|
+
},
|
|
787
|
+
canCall: () => false,
|
|
788
|
+
unavailableReason: "\u5F53\u524D\u9875\u9762\u4E0D\u662F\u7531\u652F\u6301\u672C\u6865\u7684\u5916\u58F3\u6253\u5F00\uFF0C\u6865\u4E0D\u53EF\u7528",
|
|
789
|
+
destroy() {
|
|
790
|
+
}
|
|
791
|
+
};
|
|
792
|
+
}
|
|
793
|
+
function createH5SideTransport({ ctx, hostType, onStatus }) {
|
|
794
|
+
const listeners = [];
|
|
795
|
+
const buffer = [];
|
|
796
|
+
const seen = /* @__PURE__ */ new Set();
|
|
797
|
+
function emit(frame) {
|
|
798
|
+
if (!frame) return;
|
|
799
|
+
const key = `${frame.id || ""}:${frame.k}:${frame.ts || ""}`;
|
|
800
|
+
if (seen.has(key)) return;
|
|
801
|
+
seen.add(key);
|
|
802
|
+
if (seen.size > 400) seen.clear();
|
|
803
|
+
if (!listeners.length) buffer.push(frame);
|
|
804
|
+
else for (const fn of listeners.slice()) fn(frame);
|
|
805
|
+
}
|
|
806
|
+
let native;
|
|
807
|
+
if (hostType === "app") native = createAppChannel({ ctx, emit, onStatus });
|
|
808
|
+
else if (hostType === "mp") native = createMpChannel({ ctx, emit });
|
|
809
|
+
else if (hostType === "h5") {
|
|
810
|
+
native = createPostMessageTransport({
|
|
811
|
+
getTargetWindow: () => window.parent,
|
|
812
|
+
getExpectedSource: () => window.parent,
|
|
813
|
+
allowedOrigins: ctx.parentOrigins,
|
|
814
|
+
initialTargetOrigin: ctx.parentOrigins[0] || "*",
|
|
815
|
+
channel: ctx.channel,
|
|
816
|
+
onLog: onStatus
|
|
817
|
+
});
|
|
818
|
+
} else native = createStandaloneChannel();
|
|
819
|
+
if (typeof native.onFrame === "function") native.onFrame(emit);
|
|
820
|
+
const canCall = () => typeof native.canCall === "function" ? native.canCall() : true;
|
|
821
|
+
return {
|
|
822
|
+
name: native.name,
|
|
823
|
+
realtime: !!native.realtime,
|
|
824
|
+
duplex: !!native.duplex,
|
|
825
|
+
ready: Promise.resolve(native.ready).catch(() => {
|
|
826
|
+
}),
|
|
827
|
+
note: native.note,
|
|
828
|
+
channel: ctx.channel,
|
|
829
|
+
onFrame(cb) {
|
|
830
|
+
listeners.push(cb);
|
|
831
|
+
while (buffer.length) cb(buffer.shift());
|
|
832
|
+
},
|
|
833
|
+
send(frame) {
|
|
834
|
+
native.send(frame);
|
|
835
|
+
},
|
|
836
|
+
canCall,
|
|
837
|
+
unavailableReason: canCall() ? "" : native.unavailableReason || "",
|
|
838
|
+
receive(raw) {
|
|
839
|
+
emit(decodeFrame(raw, { channel: ctx.channel }));
|
|
840
|
+
},
|
|
841
|
+
markLoaded() {
|
|
842
|
+
var _a;
|
|
843
|
+
(_a = native.markLoaded) == null ? void 0 : _a.call(native);
|
|
844
|
+
},
|
|
845
|
+
setReady() {
|
|
846
|
+
var _a;
|
|
847
|
+
(_a = native.setReady) == null ? void 0 : _a.call(native);
|
|
848
|
+
},
|
|
849
|
+
destroy() {
|
|
850
|
+
var _a;
|
|
851
|
+
(_a = native.destroy) == null ? void 0 : _a.call(native);
|
|
852
|
+
listeners.length = 0;
|
|
853
|
+
},
|
|
854
|
+
get nativeChannel() {
|
|
855
|
+
return native;
|
|
856
|
+
}
|
|
857
|
+
};
|
|
858
|
+
}
|
|
859
|
+
function dispatchEvents(names, detail) {
|
|
860
|
+
if (typeof document === "undefined" || typeof CustomEvent === "undefined") return;
|
|
861
|
+
for (const name of names || []) document.dispatchEvent(new CustomEvent(name, { detail }));
|
|
862
|
+
}
|
|
863
|
+
function createH5Bridge({
|
|
864
|
+
paramPrefix,
|
|
865
|
+
search,
|
|
866
|
+
config,
|
|
867
|
+
handlers = {},
|
|
868
|
+
useDefaultHandlers = true,
|
|
869
|
+
autoProbe = true,
|
|
870
|
+
attachGlobals = false,
|
|
871
|
+
globalNames = DEFAULT_GLOBAL_NAMES,
|
|
872
|
+
onStatus = noop3
|
|
873
|
+
} = {}) {
|
|
874
|
+
var _a;
|
|
875
|
+
if (typeof window === "undefined") return null;
|
|
876
|
+
const cfg = resolveConfig(config);
|
|
877
|
+
const ctx = readH5Context({ search, ...paramPrefix ? { paramPrefix } : {} });
|
|
878
|
+
const hostType = detectHost(ctx);
|
|
879
|
+
const status = [];
|
|
880
|
+
const pushStatus = (text) => {
|
|
881
|
+
status.push(String(text));
|
|
882
|
+
if (window.__WEBVIEW_RPC_DEBUG__ || window.__ISEE_BRIDGE_DEBUG__) console.info("[webview-rpc]", text);
|
|
883
|
+
onStatus(text);
|
|
884
|
+
};
|
|
885
|
+
const transport = createH5SideTransport({ ctx, hostType, onStatus: pushStatus });
|
|
886
|
+
const allHandlers = {
|
|
887
|
+
...useDefaultHandlers ? createH5Handlers() : {},
|
|
888
|
+
...handlers
|
|
889
|
+
};
|
|
890
|
+
const bridge = createBridgeCore({
|
|
891
|
+
transport,
|
|
892
|
+
role: ROLE.H5,
|
|
893
|
+
channel: ctx.channel || DEFAULT_CHANNEL,
|
|
894
|
+
timeout: cfg.timeout,
|
|
895
|
+
handlers: allHandlers,
|
|
896
|
+
onLog: noop3
|
|
897
|
+
});
|
|
898
|
+
const capabilities = {
|
|
899
|
+
version: VERSION,
|
|
900
|
+
contextEnabled: ctx.enabled,
|
|
901
|
+
hostType,
|
|
902
|
+
siteId: ctx.siteId,
|
|
903
|
+
sessionId: ctx.sessionId,
|
|
904
|
+
channel: ctx.channel,
|
|
905
|
+
transport: transport.name,
|
|
906
|
+
realtime: transport.realtime,
|
|
907
|
+
duplex: transport.duplex,
|
|
908
|
+
note: transport.note,
|
|
909
|
+
unavailableReason: transport.unavailableReason
|
|
910
|
+
};
|
|
911
|
+
const api2 = {
|
|
912
|
+
version: VERSION,
|
|
913
|
+
capabilities,
|
|
914
|
+
call: (method, params, options) => bridge.call(method, params, options),
|
|
915
|
+
register: (method, fn) => bridge.register(method, fn),
|
|
916
|
+
registerMany: (map) => bridge.registerMany(map),
|
|
917
|
+
unregister: (method) => bridge.unregister(method),
|
|
918
|
+
hasMethod: (method) => bridge.hasMethod(method),
|
|
919
|
+
listMethods: () => bridge.listMethods(),
|
|
920
|
+
emit: (method, params) => bridge.emit(method, params),
|
|
921
|
+
on: (method, fn) => bridge.on(method, fn),
|
|
922
|
+
off: (method, fn) => bridge.off(method, fn),
|
|
923
|
+
ping: (timeout) => bridge.ping(timeout),
|
|
924
|
+
ready: () => bridge.waitReady(),
|
|
925
|
+
get isReady() {
|
|
926
|
+
return bridge.isReady;
|
|
927
|
+
},
|
|
928
|
+
get pendingCount() {
|
|
929
|
+
return bridge.pendingCount;
|
|
930
|
+
},
|
|
931
|
+
status: () => status.slice(),
|
|
932
|
+
/** 供 App 宿主 evalJS 调用,也供调试控制台手动喂帧 */
|
|
933
|
+
receive: (raw) => transport.receive(raw),
|
|
934
|
+
destroy: () => bridge.destroy()
|
|
935
|
+
};
|
|
936
|
+
function attach() {
|
|
937
|
+
for (const name of globalNames.api || []) window[name] = api2;
|
|
938
|
+
for (const name of globalNames.receive || []) window[name] = (raw) => transport.receive(raw);
|
|
939
|
+
return api2;
|
|
940
|
+
}
|
|
941
|
+
api2.attachGlobals = attach;
|
|
942
|
+
if (attachGlobals) attach();
|
|
943
|
+
if (ctx.initFrames) {
|
|
944
|
+
try {
|
|
945
|
+
const frames = JSON.parse(ctx.initFrames);
|
|
946
|
+
for (const raw of Array.isArray(frames) ? frames : [frames]) transport.receive(raw);
|
|
947
|
+
} catch (err) {
|
|
948
|
+
pushStatus(`[init] \u65E0\u6CD5\u89E3\u6790\u521D\u59CB\u5316\u5E27: ${err.message}`);
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
(_a = transport.setReady) == null ? void 0 : _a.call(transport);
|
|
952
|
+
Promise.resolve(transport.ready).then(() => {
|
|
953
|
+
var _a2;
|
|
954
|
+
try {
|
|
955
|
+
transport.send(makeReady({ info: capabilities, channel: ctx.channel, from: ROLE.H5 }));
|
|
956
|
+
} catch (err) {
|
|
957
|
+
pushStatus(`[ready] \u63E1\u624B\u5E27\u53D1\u9001\u5931\u8D25: ${err.message}`);
|
|
958
|
+
}
|
|
959
|
+
(_a2 = transport.markLoaded) == null ? void 0 : _a2.call(transport);
|
|
960
|
+
dispatchEvents(globalNames.readyEvent, api2);
|
|
961
|
+
if (autoProbe && transport.canCall()) {
|
|
962
|
+
api2.call("host.getEnv", {}, { timeout: 5e3 }).then((env) => {
|
|
963
|
+
capabilities.hostEnv = env;
|
|
964
|
+
api2.emit("page/host-env", env);
|
|
965
|
+
dispatchEvents(globalNames.hostEnvEvent, env);
|
|
966
|
+
}).catch((err) => pushStatus(`[probe] H5 -> \u5BBF\u4E3B host.getEnv \u5931\u8D25: ${err.message}`));
|
|
967
|
+
}
|
|
968
|
+
});
|
|
969
|
+
return api2;
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
// src/auto.js
|
|
973
|
+
function boot(options = {}) {
|
|
974
|
+
return createH5Bridge({ ...options, attachGlobals: true });
|
|
975
|
+
}
|
|
976
|
+
var api = boot();
|
|
977
|
+
var auto_default = api;
|
|
978
|
+
return __toCommonJS(auto_exports);
|
|
979
|
+
})();
|