mobile-web-bridge 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,831 @@
1
+ /*!
2
+ MIT License
3
+
4
+ Copyright (c) 2026 gaoxiao228
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
23
+
24
+ # DSBridge third-party notice
25
+
26
+ DSBridge JavaScript 3.1.4: https://www.npmjs.com/package/dsbridge/v/3.1.4
27
+ DSBridge Android 3.0.0: https://github.com/wendux/DSBridge-Android/tree/d3e5ebc6ca8170f97e420f2f482680c8e149b471
28
+ DSBridge iOS 3.0.6: https://github.com/wendux/DSBridge-IOS/tree/f0e3c724dd362800528f8b6c788bdad7006cc187
29
+
30
+ Author: wendux (杜文 / Du Wen), as identified by upstream package metadata and source.
31
+ The upstream npm metadata, Android readme.md and iOS podspec declare MIT.
32
+ The pinned native trees do not provide a separate LICENSE file; the MIT terms
33
+ are reproduced below without inventing an absent upstream copyright notice.
34
+ Original iOS source notices are retained verbatim:
35
+
36
+ Copyright © 2016年 杜文. All rights reserved.
37
+ Copyright © 2018年 杜文. All rights reserved.
38
+
39
+ MIT License
40
+
41
+ Permission is hereby granted, free of charge, to any person obtaining a copy
42
+ of this software and associated documentation files (the "Software"), to deal
43
+ in the Software without restriction, including without limitation the rights
44
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
45
+ copies of the Software, and to permit persons to whom the Software is
46
+ furnished to do so, subject to the following conditions:
47
+
48
+ The above copyright notice and this permission notice shall be included in all
49
+ copies or substantial portions of the Software.
50
+
51
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
52
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
53
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
54
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
55
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
56
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
57
+ SOFTWARE.
58
+
59
+ */
60
+ "use strict";
61
+ (() => {
62
+ var __create = Object.create;
63
+ var __defProp = Object.defineProperty;
64
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
65
+ var __getOwnPropNames = Object.getOwnPropertyNames;
66
+ var __getProtoOf = Object.getPrototypeOf;
67
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
68
+ var __commonJS = (cb, mod) => function __require() {
69
+ try {
70
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
71
+ } catch (e) {
72
+ throw mod = 0, e;
73
+ }
74
+ };
75
+ var __copyProps = (to, from, except, desc) => {
76
+ if (from && typeof from === "object" || typeof from === "function") {
77
+ for (let key of __getOwnPropNames(from))
78
+ if (!__hasOwnProp.call(to, key) && key !== except)
79
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
80
+ }
81
+ return to;
82
+ };
83
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
84
+ // If the importer is in node compatibility mode or this is not an ESM
85
+ // file that has been converted to a CommonJS file using a Babel-
86
+ // compatible transform (i.e. "__esModule" has not been set), then set
87
+ // "default" to the CommonJS "module.exports" for node compatibility.
88
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
89
+ mod
90
+ ));
91
+
92
+ // node_modules/dsbridge/index.js
93
+ var require_dsbridge = __commonJS({
94
+ "node_modules/dsbridge/index.js"(exports, module) {
95
+ var bridge = {
96
+ default: exports,
97
+ // for typescript
98
+ call: function(method, args, cb) {
99
+ var ret = "";
100
+ if (typeof args == "function") {
101
+ cb = args;
102
+ args = {};
103
+ }
104
+ var arg = { data: args === void 0 ? null : args };
105
+ if (typeof cb == "function") {
106
+ var cbName = "dscb" + window.dscb++;
107
+ window[cbName] = cb;
108
+ arg["_dscbstub"] = cbName;
109
+ }
110
+ arg = JSON.stringify(arg);
111
+ if (window._dsbridge) {
112
+ ret = _dsbridge.call(method, arg);
113
+ } else if (window._dswk || navigator.userAgent.indexOf("_dsbridge") != -1) {
114
+ ret = prompt("_dsbridge=" + method, arg);
115
+ }
116
+ return JSON.parse(ret || "{}").data;
117
+ },
118
+ register: function(name, fun, asyn) {
119
+ var q = asyn ? window._dsaf : window._dsf;
120
+ if (!window._dsInit) {
121
+ window._dsInit = true;
122
+ setTimeout(function() {
123
+ bridge.call("_dsb.dsinit");
124
+ }, 0);
125
+ }
126
+ if (typeof fun == "object") {
127
+ q._obs[name] = fun;
128
+ } else {
129
+ q[name] = fun;
130
+ }
131
+ },
132
+ registerAsyn: function(name, fun) {
133
+ this.register(name, fun, true);
134
+ },
135
+ hasNativeMethod: function(name, type) {
136
+ return this.call("_dsb.hasNativeMethod", { name, type: type || "all" });
137
+ },
138
+ disableJavascriptDialogBlock: function(disable) {
139
+ this.call("_dsb.disableJavascriptDialogBlock", {
140
+ disable: disable !== false
141
+ });
142
+ }
143
+ };
144
+ !(function() {
145
+ if (window._dsf) return;
146
+ var ob = {
147
+ _dsf: {
148
+ _obs: {}
149
+ },
150
+ _dsaf: {
151
+ _obs: {}
152
+ },
153
+ dscb: 0,
154
+ dsBridge: bridge,
155
+ close: function() {
156
+ bridge.call("_dsb.closePage");
157
+ },
158
+ _handleMessageFromNative: function(info) {
159
+ var arg = JSON.parse(info.data);
160
+ var ret = {
161
+ id: info.callbackId,
162
+ complete: true
163
+ };
164
+ var f = this._dsf[info.method];
165
+ var af = this._dsaf[info.method];
166
+ var callSyn = function(f2, ob3) {
167
+ ret.data = f2.apply(ob3, arg);
168
+ bridge.call("_dsb.returnValue", ret);
169
+ };
170
+ var callAsyn = function(f2, ob3) {
171
+ arg.push(function(data, complete) {
172
+ ret.data = data;
173
+ ret.complete = complete !== false;
174
+ bridge.call("_dsb.returnValue", ret);
175
+ });
176
+ f2.apply(ob3, arg);
177
+ };
178
+ if (f) {
179
+ callSyn(f, this._dsf);
180
+ } else if (af) {
181
+ callAsyn(af, this._dsaf);
182
+ } else {
183
+ var name = info.method.split(".");
184
+ if (name.length < 2) return;
185
+ var method = name.pop();
186
+ var namespace = name.join(".");
187
+ var obs = this._dsf._obs;
188
+ var ob2 = obs[namespace] || {};
189
+ var m = ob2[method];
190
+ if (m && typeof m == "function") {
191
+ callSyn(m, ob2);
192
+ return;
193
+ }
194
+ obs = this._dsaf._obs;
195
+ ob2 = obs[namespace] || {};
196
+ m = ob2[method];
197
+ if (m && typeof m == "function") {
198
+ callAsyn(m, ob2);
199
+ return;
200
+ }
201
+ }
202
+ }
203
+ };
204
+ for (var attr in ob) {
205
+ window[attr] = ob[attr];
206
+ }
207
+ bridge.register("_hasJavascriptMethod", function(method, tag) {
208
+ var name = method.split(".");
209
+ if (name.length < 2) {
210
+ return !!(_dsf[name] || _dsaf[name]);
211
+ } else {
212
+ var method = name.pop();
213
+ var namespace = name.join(".");
214
+ var ob2 = _dsf._obs[namespace] || _dsaf._obs[namespace];
215
+ return ob2 && !!ob2[method];
216
+ }
217
+ });
218
+ })();
219
+ module.exports = bridge;
220
+ }
221
+ });
222
+
223
+ // src/index.ts
224
+ var import_dsbridge = __toESM(require_dsbridge(), 1);
225
+
226
+ // src/types.ts
227
+ var version = "0.1.1";
228
+
229
+ // src/eventHub.ts
230
+ var hubs = /* @__PURE__ */ new WeakMap();
231
+ var EventHub = class {
232
+ constructor(bridge) {
233
+ this.bridge = bridge;
234
+ this.listeners = /* @__PURE__ */ new Map();
235
+ bridge.register?.("mwb.backBtnPressed", () => this.back?.handler() ?? false);
236
+ }
237
+ on(name, handler) {
238
+ let listeners = this.listeners.get(name);
239
+ if (!listeners) {
240
+ listeners = /* @__PURE__ */ new Set();
241
+ this.listeners.set(name, listeners);
242
+ this.bridge.register?.(name, (...args) => {
243
+ for (const callback of [...this.listeners.get(name) ?? []]) {
244
+ try {
245
+ callback(...args);
246
+ } catch (error) {
247
+ console.error("MWB event listener failed", error);
248
+ }
249
+ }
250
+ });
251
+ }
252
+ listeners.add(handler);
253
+ return () => {
254
+ listeners.delete(handler);
255
+ };
256
+ }
257
+ setBack(owner, handler) {
258
+ if (handler) this.back = { owner, handler };
259
+ else if (this.back?.owner === owner) this.back = void 0;
260
+ }
261
+ };
262
+ function getEventHub(bridge) {
263
+ let hub = hubs.get(bridge);
264
+ if (!hub) {
265
+ hub = new EventHub(bridge);
266
+ hubs.set(bridge, hub);
267
+ }
268
+ return hub;
269
+ }
270
+
271
+ // src/events.ts
272
+ function createEvents() {
273
+ const custom = /* @__PURE__ */ new Map();
274
+ const listeners = /* @__PURE__ */ new Map();
275
+ let backHandler;
276
+ let eventBridge;
277
+ const owner = {};
278
+ const relayStops = /* @__PURE__ */ new Map();
279
+ function bridge() {
280
+ if (typeof window === "undefined") return void 0;
281
+ return window.dsBridge;
282
+ }
283
+ function ensureEventsRegistered() {
284
+ const current = bridge();
285
+ if (!current?.register || eventBridge === current) return;
286
+ relayStops.forEach((stop) => stop());
287
+ relayStops.clear();
288
+ if (eventBridge) getEventHub(eventBridge).setBack(owner);
289
+ const hub = getEventHub(current);
290
+ relayStops.set("dispatchEvent", hub.on("mwb.dispatchEvent", (message) => {
291
+ if (!message || typeof message !== "object") return;
292
+ const event = message;
293
+ if (!event.name) return;
294
+ for (const handler of [...listeners.get(event.name) ?? []]) {
295
+ try {
296
+ handler(event.data);
297
+ } catch (error) {
298
+ console.error("MWB event listener failed", error);
299
+ }
300
+ }
301
+ }));
302
+ eventBridge = current;
303
+ if (backHandler) hub.setBack(owner, backHandler);
304
+ for (const name of custom.keys()) attachCustom(name);
305
+ }
306
+ function attachCustom(name) {
307
+ if (!eventBridge || relayStops.has(`custom:${name}`)) return;
308
+ relayStops.set(`custom:${name}`, getEventHub(eventBridge).on(`mwb.${name}`, (data) => {
309
+ for (const callback of [...custom.get(name) ?? []]) {
310
+ try {
311
+ callback(data);
312
+ } catch (error) {
313
+ console.error("MWB handler failed", error);
314
+ }
315
+ }
316
+ }));
317
+ }
318
+ function on(name, handler) {
319
+ ensureEventsRegistered();
320
+ if (!listeners.has(name)) listeners.set(name, /* @__PURE__ */ new Set());
321
+ listeners.get(name)?.add(handler);
322
+ }
323
+ function off(name, handler) {
324
+ listeners.get(name)?.delete(handler);
325
+ }
326
+ ensureEventsRegistered();
327
+ return {
328
+ registerHandler(handlerName, handler) {
329
+ ensureEventsRegistered();
330
+ if (!custom.has(handlerName)) {
331
+ custom.set(handlerName, /* @__PURE__ */ new Set());
332
+ }
333
+ custom.get(handlerName)?.add(handler);
334
+ attachCustom(handlerName);
335
+ },
336
+ unRegisterHandlers(handlerName) {
337
+ custom.delete(handlerName);
338
+ },
339
+ unRegisterHandler(handlerName, handler) {
340
+ const handlers = custom.get(handlerName);
341
+ handlers?.delete(handler);
342
+ if (handlers?.size === 0) custom.delete(handlerName);
343
+ },
344
+ checkHandlerExist(handlerName) {
345
+ return Boolean(custom.get(handlerName)?.size);
346
+ },
347
+ onNetworkStatusChange(handler) {
348
+ on("networkStatusChange", handler);
349
+ },
350
+ offNetworkStatusChange(handler) {
351
+ off("networkStatusChange", handler);
352
+ },
353
+ onAppShow(handler) {
354
+ on("appShow", handler);
355
+ },
356
+ offAppShow(handler) {
357
+ off("appShow", handler);
358
+ },
359
+ onAppHide(handler) {
360
+ on("appHide", handler);
361
+ },
362
+ offAppHide(handler) {
363
+ off("appHide", handler);
364
+ },
365
+ onRemoteNotificationReceive(handler) {
366
+ on("remoteNotificationReceive", handler);
367
+ },
368
+ offRemoteNotificationReceive(handler) {
369
+ off("remoteNotificationReceive", handler);
370
+ },
371
+ onPageShow(handler) {
372
+ on("pageShow", handler);
373
+ },
374
+ offPageShow(handler) {
375
+ off("pageShow", handler);
376
+ },
377
+ onPageHide(handler) {
378
+ on("pageHide", handler);
379
+ },
380
+ offPageHide(handler) {
381
+ off("pageHide", handler);
382
+ },
383
+ onBackBtnPressed(handler) {
384
+ ensureEventsRegistered();
385
+ backHandler = handler;
386
+ if (eventBridge) getEventHub(eventBridge).setBack(owner, handler);
387
+ },
388
+ offBackBtnPressed() {
389
+ backHandler = void 0;
390
+ if (eventBridge) getEventHub(eventBridge).setBack(owner);
391
+ }
392
+ };
393
+ }
394
+
395
+ // src/assembleMWB.ts
396
+ function assembleMWB(plugins) {
397
+ const events = createEvents();
398
+ const protectedNames = /* @__PURE__ */ new Set(["basic", "version", "hasPlugin", "pluginSession", "pluginInfo", "invokePlugin", "pluginEvent", "constructor", "prototype", "__proto__", ...Object.keys(events)]);
399
+ const methods = /* @__PURE__ */ Object.create(null);
400
+ const selected = /* @__PURE__ */ new Set();
401
+ for (const plugin of plugins) {
402
+ if (selected.has(plugin)) continue;
403
+ selected.add(plugin);
404
+ for (const [name, method] of Object.entries(plugin.methods)) {
405
+ if (protectedNames.has(name)) throw new Error(`Reserved MWB basic method: ${name}`);
406
+ if (Object.prototype.hasOwnProperty.call(methods, name)) throw new Error(`Duplicate MWB basic method: ${name}`);
407
+ methods[name] = method;
408
+ }
409
+ }
410
+ const nativeSetTheme = methods.setNavigationBarTheme;
411
+ if (nativeSetTheme) {
412
+ let currentActionClick;
413
+ methods.setNavigationBarTheme = async (param) => {
414
+ const { onActionClick, ...nativeParam } = param;
415
+ const result = await nativeSetTheme(nativeParam);
416
+ if (currentActionClick) events.unRegisterHandler("navigationActionClick", currentActionClick);
417
+ currentActionClick = void 0;
418
+ if (nativeParam.actionTxt?.trim() && onActionClick) {
419
+ events.registerHandler("navigationActionClick", onActionClick);
420
+ currentActionClick = onActionClick;
421
+ }
422
+ return result;
423
+ };
424
+ }
425
+ const basic = Object.freeze({ ...methods, ...events });
426
+ return { version, ...basic, basic };
427
+ }
428
+
429
+ // src/apiManifest.ts
430
+ var apiMethods = [
431
+ "notifyPageReady",
432
+ "setEnableDebug",
433
+ "openAppAuthorizeSetting",
434
+ "toast",
435
+ "getAppInfoSync",
436
+ "setBadgeCount",
437
+ "navigateTo",
438
+ "navigateBack",
439
+ "navigateBackToRoot",
440
+ "openExternalBrowser",
441
+ "setNavigationBarTheme",
442
+ "getDeviceInfoSync",
443
+ "getClipboardDataSync",
444
+ "setClipboardData",
445
+ "makePhoneCall",
446
+ "getNetworkTypeSync",
447
+ "getNotificationSwitchStatus",
448
+ "cleanWebviewCache",
449
+ "compressImage",
450
+ "scanCode",
451
+ "saveImageToPhotosAlbum",
452
+ "chooseImage",
453
+ "setStorageSync",
454
+ "getStorageSync",
455
+ "removeStorageSync",
456
+ "clearStorageSync",
457
+ "openFile",
458
+ "exitApp",
459
+ "checkRequestCameraPermissions",
460
+ "convertImagePathToBase64",
461
+ "openNativePage",
462
+ "registerHandler",
463
+ "unRegisterHandlers",
464
+ "unRegisterHandler",
465
+ "checkHandlerExist",
466
+ "onNetworkStatusChange",
467
+ "offNetworkStatusChange",
468
+ "onAppShow",
469
+ "offAppShow",
470
+ "onAppHide",
471
+ "offAppHide",
472
+ "onRemoteNotificationReceive",
473
+ "offRemoteNotificationReceive",
474
+ "onPageShow",
475
+ "offPageShow",
476
+ "onPageHide",
477
+ "offPageHide",
478
+ "onBackBtnPressed",
479
+ "offBackBtnPressed"
480
+ ];
481
+
482
+ // src/bridge.ts
483
+ var MWBBridgeError = class extends Error {
484
+ constructor(errCode, errorMsg) {
485
+ super(errorMsg);
486
+ this.errCode = errCode;
487
+ this.errorMsg = errorMsg;
488
+ this.name = "MWBBridgeError";
489
+ }
490
+ };
491
+ function getBridge() {
492
+ if (typeof window === "undefined") {
493
+ throw new MWBBridgeError(-1e3, "MWB bridge is not ready");
494
+ }
495
+ const bridgeWindow = window;
496
+ const nativeReady = Boolean(bridgeWindow._dsbridge || bridgeWindow._dswk || typeof navigator !== "undefined" && navigator.userAgent.includes("_dsbridge"));
497
+ if (!nativeReady || !bridgeWindow.dsBridge) {
498
+ throw new MWBBridgeError(-1e3, "MWB bridge is not ready");
499
+ }
500
+ return bridgeWindow.dsBridge;
501
+ }
502
+ function parseNative(value) {
503
+ if (typeof value !== "string") return value;
504
+ try {
505
+ return JSON.parse(value);
506
+ } catch {
507
+ return value;
508
+ }
509
+ }
510
+ function callSync(method, args) {
511
+ const bridge = getBridge();
512
+ if (bridge.hasNativeMethod && !bridge.hasNativeMethod(`mwb.${method}`, "syn")) {
513
+ throw new MWBBridgeError(-1003, `MWB native method is unavailable: ${method}`);
514
+ }
515
+ try {
516
+ const value = parseNative(bridge.call(`mwb.${method}`, args));
517
+ if (value && typeof value === "object" && "errCode" in value && typeof value.errCode === "number" && value.errCode !== 0) {
518
+ throw new MWBBridgeError(
519
+ value.errCode,
520
+ "errorMsg" in value && typeof value.errorMsg === "string" ? value.errorMsg : `MWB call failed: ${method}`
521
+ );
522
+ }
523
+ return value;
524
+ } catch (error) {
525
+ if (error instanceof MWBBridgeError) throw error;
526
+ throw new MWBBridgeError(-1002, error instanceof Error ? error.message : String(error));
527
+ }
528
+ }
529
+ function callAsync(method, args) {
530
+ return new Promise((resolve, reject) => {
531
+ let bridge;
532
+ try {
533
+ bridge = getBridge();
534
+ if (bridge.hasNativeMethod && !bridge.hasNativeMethod(`mwb.${method}`, "asyn")) {
535
+ throw new MWBBridgeError(-1003, `MWB native method is unavailable: ${method}`);
536
+ }
537
+ bridge.call(`mwb.${method}`, args, (value) => {
538
+ const parsed = parseNative(value);
539
+ if (!parsed || typeof parsed !== "object" || typeof parsed.errCode !== "number") {
540
+ reject(new MWBBridgeError(-1001, `Invalid MWB native response: ${method}`));
541
+ return;
542
+ }
543
+ const result = parsed;
544
+ if (result.errCode === 0) resolve(result);
545
+ else reject(new MWBBridgeError(result.errCode, result.errorMsg ?? `MWB call failed: ${method}`));
546
+ });
547
+ } catch (error) {
548
+ reject(error instanceof MWBBridgeError ? error : new MWBBridgeError(-1002, error instanceof Error ? error.message : String(error)));
549
+ }
550
+ });
551
+ }
552
+
553
+ // src/nativePlugins.ts
554
+ var descriptorBrand = /* @__PURE__ */ Symbol("MWBNativePlugin");
555
+ var reserved = /* @__PURE__ */ new Set([...apiMethods, "basic", "version", "hasPlugin", "pluginSession", "pluginInfo", "invokePlugin", "pluginEvent", "dispatchEvent", "backBtnPressed", "on", "then", "catch", "finally", "toJSON", "inspect", "constructor", "prototype", "__proto__"]);
556
+ var methodReserved = /* @__PURE__ */ new Set(["on", "then", "catch", "finally", "toJSON", "inspect", "constructor", "prototype", "__proto__"]);
557
+ function validName(name) {
558
+ return typeof name === "string" && /^[a-z][a-zA-Z0-9_]*$/.test(name);
559
+ }
560
+ function assertJSON(value, ancestors = /* @__PURE__ */ new Set()) {
561
+ if (value === null || typeof value === "string" || typeof value === "boolean") return;
562
+ if (typeof value === "number" && Number.isFinite(value)) return;
563
+ if (typeof value !== "object" || value === null || ancestors.has(value)) throw new MWBBridgeError(-1102, "Plugin data must be finite, acyclic JSON");
564
+ const prototype = Object.getPrototypeOf(value);
565
+ if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null) throw new MWBBridgeError(-1102, "Plugin data must contain plain JSON objects");
566
+ if (Object.getOwnPropertySymbols(value).length) throw new MWBBridgeError(-1102, "Symbol properties are not JSON data");
567
+ if (Object.values(Object.getOwnPropertyDescriptors(value)).some((property) => property.get || property.set)) {
568
+ throw new MWBBridgeError(-1102, "Plugin data must not contain accessors");
569
+ }
570
+ ancestors.add(value);
571
+ const values = Array.isArray(value) ? Array.from(value) : Object.values(value);
572
+ for (const child of values) assertJSON(child, ancestors);
573
+ ancestors.delete(value);
574
+ }
575
+ function envelope(value) {
576
+ if (typeof value === "string") {
577
+ try {
578
+ value = JSON.parse(value);
579
+ } catch {
580
+ throw new MWBBridgeError(-1102, "Invalid plugin response JSON");
581
+ }
582
+ }
583
+ if (!value || typeof value !== "object" || !("errCode" in value) || !Number.isInteger(value.errCode)) throw new MWBBridgeError(-1102, "Invalid plugin response");
584
+ const response = value;
585
+ if (response.errCode !== 0) throw new MWBBridgeError(response.errCode, response.errorMsg ?? "MWB plugin call failed");
586
+ if ("result" in response) assertJSON(response.result);
587
+ return response;
588
+ }
589
+ function session(bridge) {
590
+ if (bridge.hasNativeMethod && !bridge.hasNativeMethod("mwb.pluginSession", "syn")) throw new MWBBridgeError(-1106, "This app does not support MWB native plugins");
591
+ let value;
592
+ try {
593
+ value = bridge.call("mwb.pluginSession");
594
+ } catch (error) {
595
+ throw new MWBBridgeError(-1106, error instanceof Error ? error.message : "Plugin session unavailable");
596
+ }
597
+ if (value === void 0 || value === null || value === "") throw new MWBBridgeError(-1106, "This app does not support MWB native plugins");
598
+ const info = envelope(value).result;
599
+ if (info?.protocol !== 1 || typeof info.documentId !== "string" || !info.documentId) throw new MWBBridgeError(-1106, "Incompatible MWB plugin protocol");
600
+ return info;
601
+ }
602
+ var nextCall = 0;
603
+ function invoke(gateway, payload, timeoutMs) {
604
+ return new Promise((resolve, reject) => {
605
+ let timer;
606
+ let finished = false;
607
+ const complete = (value, error) => {
608
+ if (finished) return;
609
+ finished = true;
610
+ if (timer !== void 0) clearTimeout(timer);
611
+ try {
612
+ if (error) throw error;
613
+ resolve(envelope(value));
614
+ } catch (failure) {
615
+ reject(failure instanceof MWBBridgeError ? failure : new MWBBridgeError(-1105, failure instanceof Error ? failure.message : String(failure)));
616
+ }
617
+ };
618
+ try {
619
+ const bridge = getBridge();
620
+ const identity = session(bridge);
621
+ if (bridge.hasNativeMethod && !bridge.hasNativeMethod(gateway, "asyn")) throw new MWBBridgeError(-1106, "Plugin gateway unavailable in this app");
622
+ timer = setTimeout(() => complete(void 0, new MWBBridgeError(-1103, "MWB plugin call timed out")), timeoutMs);
623
+ bridge.call(gateway, { ...identity, ...payload }, (value) => complete(value));
624
+ } catch (error) {
625
+ complete(void 0, error);
626
+ }
627
+ });
628
+ }
629
+ async function hasNativePlugin(name) {
630
+ if (!validName(name)) throw new MWBBridgeError(-1102, "Invalid plugin name");
631
+ const value = await invoke("mwb.pluginInfo", { plugin: name }, 3e4);
632
+ if (typeof value.result?.available !== "boolean") throw new MWBBridgeError(-1102, "Invalid plugin availability response");
633
+ return value.result.available;
634
+ }
635
+ function notifyPageReady() {
636
+ return invoke("mwb.invokePlugin", {
637
+ plugin: "basic",
638
+ method: "notifyPageReady",
639
+ params: null,
640
+ callId: `mwb-${Date.now()}-${++nextCall}`,
641
+ timeoutMs: 3e4
642
+ }, 3e4);
643
+ }
644
+ function createNamespace(descriptor) {
645
+ const functions = /* @__PURE__ */ new Map();
646
+ const on = (name, handler) => {
647
+ if (!validName(name) || methodReserved.has(name) || typeof handler !== "function") throw new MWBBridgeError(-1102, "Invalid plugin event subscription");
648
+ const bridge = getBridge();
649
+ const identity = session(bridge);
650
+ return getEventHub(bridge).on("mwb.pluginEvent", (value) => {
651
+ if (!value || typeof value !== "object") return;
652
+ const event = value;
653
+ if (event.plugin === descriptor.name && event.name === name && event.documentId === identity.documentId) {
654
+ assertJSON(event.data);
655
+ handler(event.data);
656
+ }
657
+ });
658
+ };
659
+ return new Proxy(/* @__PURE__ */ Object.create(null), {
660
+ get(_target, property) {
661
+ if (property === "on") return on;
662
+ if (!validName(property) || methodReserved.has(property)) return void 0;
663
+ if (!functions.has(property)) functions.set(property, (...args) => {
664
+ try {
665
+ if (args.length > 1) throw new MWBBridgeError(-1102, "Plugin methods accept one JSON parameter");
666
+ const params = args[0] === void 0 ? null : args[0];
667
+ assertJSON(params);
668
+ return invoke("mwb.invokePlugin", {
669
+ plugin: descriptor.name,
670
+ method: property,
671
+ params,
672
+ callId: `mwb-${Date.now()}-${++nextCall}`,
673
+ timeoutMs: descriptor.timeoutMs
674
+ }, descriptor.timeoutMs);
675
+ } catch (error) {
676
+ return Promise.reject(error instanceof MWBBridgeError ? error : new MWBBridgeError(-1102, "Plugin parameters are not valid JSON"));
677
+ }
678
+ });
679
+ return functions.get(property);
680
+ }
681
+ });
682
+ }
683
+ function attachNativePlugins(target, plugins) {
684
+ for (const descriptor of plugins) {
685
+ if (descriptor[descriptorBrand] !== true || !validName(descriptor.name) || reserved.has(descriptor.name)) throw new Error("Invalid MWB native plugin descriptor");
686
+ if (Object.prototype.hasOwnProperty.call(target, descriptor.name)) throw new Error(`Duplicate MWB plugin: ${descriptor.name}`);
687
+ Object.defineProperty(target, descriptor.name, { value: createNamespace(descriptor), enumerable: true });
688
+ }
689
+ }
690
+
691
+ // src/plugins/container.ts
692
+ var containerPlugin = {
693
+ name: "container",
694
+ methods: {
695
+ notifyPageReady,
696
+ setEnableDebug(enabled) {
697
+ callSync("setEnableDebug", { enabled });
698
+ },
699
+ toast(param) {
700
+ return callAsync("toast", param);
701
+ },
702
+ navigateTo(param) {
703
+ return callAsync("navigateTo", param);
704
+ },
705
+ navigateBack(callbackInfo) {
706
+ return callAsync("navigateBack", callbackInfo);
707
+ },
708
+ navigateBackToRoot() {
709
+ return callAsync("navigateBackToRoot");
710
+ },
711
+ openExternalBrowser(param) {
712
+ return callAsync("openExternalBrowser", param);
713
+ },
714
+ setNavigationBarTheme(param) {
715
+ return callAsync("setNavigationBarTheme", param);
716
+ },
717
+ cleanWebviewCache() {
718
+ return callAsync("cleanWebviewCache");
719
+ },
720
+ exitApp() {
721
+ return callAsync("exitApp");
722
+ },
723
+ openNativePage(param) {
724
+ return callAsync("openNativePage", param);
725
+ }
726
+ }
727
+ };
728
+
729
+ // src/plugins/device.ts
730
+ var devicePlugin = {
731
+ name: "device",
732
+ methods: {
733
+ openAppAuthorizeSetting() {
734
+ return callAsync("openAppAuthorizeSetting");
735
+ },
736
+ getAppInfoSync() {
737
+ return callSync("getAppInfoSync");
738
+ },
739
+ setBadgeCount(param) {
740
+ return callAsync("setBadgeCount", param);
741
+ },
742
+ getDeviceInfoSync() {
743
+ return callSync("getDeviceInfoSync");
744
+ },
745
+ getClipboardDataSync() {
746
+ return callSync("getClipboardDataSync");
747
+ },
748
+ setClipboardData(param) {
749
+ return callAsync("setClipboardData", param);
750
+ },
751
+ makePhoneCall(param) {
752
+ return callAsync("makePhoneCall", param);
753
+ },
754
+ getNetworkTypeSync() {
755
+ return callSync("getNetworkTypeSync");
756
+ },
757
+ getNotificationSwitchStatus() {
758
+ return callAsync("getNotificationSwitchStatus");
759
+ }
760
+ }
761
+ };
762
+
763
+ // src/plugins/media.ts
764
+ var mediaPlugin = {
765
+ name: "media",
766
+ methods: {
767
+ compressImage(param) {
768
+ return callAsync("compressImage", param);
769
+ },
770
+ scanCode(param) {
771
+ return callAsync("scanCode", param);
772
+ },
773
+ saveImageToPhotosAlbum(param) {
774
+ return callAsync("saveImageToPhotosAlbum", param);
775
+ },
776
+ chooseImage(param) {
777
+ return callAsync("chooseImage", param);
778
+ },
779
+ openFile(param) {
780
+ return callAsync("openFile", param);
781
+ },
782
+ checkRequestCameraPermissions(param) {
783
+ return callAsync("checkRequestCameraPermissions", param);
784
+ },
785
+ convertImagePathToBase64(param) {
786
+ return callAsync("convertImagePathToBase64", param);
787
+ }
788
+ }
789
+ };
790
+
791
+ // src/plugins/storage.ts
792
+ var storagePlugin = {
793
+ name: "storage",
794
+ methods: {
795
+ setStorageSync(key, data, groupName, validSecond) {
796
+ callSync("setStorageSync", { key, data, groupName, validSecond });
797
+ },
798
+ getStorageSync(key, groupName) {
799
+ const response = callSync("getStorageSync", { key, groupName });
800
+ return response?.data;
801
+ },
802
+ removeStorageSync(key, groupName) {
803
+ callSync("removeStorageSync", { key, groupName });
804
+ },
805
+ clearStorageSync(groupName) {
806
+ callSync("clearStorageSync", { groupName });
807
+ }
808
+ }
809
+ };
810
+
811
+ // src/createMWB.ts
812
+ var defaultPlugins = [containerPlugin, devicePlugin, mediaPlugin, storagePlugin];
813
+ function createMWB(input = defaultPlugins) {
814
+ const sdk = assembleMWB(Array.isArray(input) ? input : defaultPlugins);
815
+ Object.assign(sdk, { hasPlugin: hasNativePlugin });
816
+ if (!Array.isArray(input)) attachNativePlugins(sdk, input.plugins);
817
+ return sdk;
818
+ }
819
+
820
+ // src/plugins/basic.ts
821
+ var basicPlugin = {
822
+ name: "basic",
823
+ methods: { ...containerPlugin.methods, ...devicePlugin.methods, ...mediaPlugin.methods, ...storagePlugin.methods }
824
+ };
825
+
826
+ // src/index.ts
827
+ var mwb = createMWB();
828
+
829
+ // src/browser.ts
830
+ window.mwb = mwb;
831
+ })();