@webview-bridge/react-native 1.6.1 → 1.7.0-rc.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.
Files changed (39) hide show
  1. package/dist/index.cjs +922 -0
  2. package/dist/index.d.cts +155 -0
  3. package/dist/index.d.ts +155 -0
  4. package/dist/index.js +821 -0
  5. package/package.json +19 -25
  6. package/dist/packages/react-native/src/createWebView.d.ts +0 -50
  7. package/dist/packages/react-native/src/createWebView.js +0 -180
  8. package/dist/packages/react-native/src/error.d.ts +0 -3
  9. package/dist/packages/react-native/src/error.js +0 -10
  10. package/dist/packages/react-native/src/index.d.ts +0 -6
  11. package/dist/packages/react-native/src/index.js +0 -22
  12. package/dist/packages/react-native/src/integrations/bridge.d.ts +0 -20
  13. package/dist/packages/react-native/src/integrations/bridge.js +0 -95
  14. package/dist/packages/react-native/src/integrations/console.d.ts +0 -3
  15. package/dist/packages/react-native/src/integrations/console.js +0 -56
  16. package/dist/packages/react-native/src/integrations/handleRegisterWebMethod.d.ts +0 -4
  17. package/dist/packages/react-native/src/integrations/handleRegisterWebMethod.js +0 -30
  18. package/dist/packages/react-native/src/integrations/postMessageSchema.d.ts +0 -2
  19. package/dist/packages/react-native/src/integrations/postMessageSchema.js +0 -56
  20. package/dist/packages/react-native/src/types/webview.d.ts +0 -3
  21. package/dist/packages/react-native/src/types/webview.js +0 -2
  22. package/dist/packages/react-native/src/useBridge.d.ts +0 -3
  23. package/dist/packages/react-native/src/useBridge.js +0 -9
  24. package/dist/shared/util/src/createEvents.d.ts +0 -25
  25. package/dist/shared/util/src/createEvents.js +0 -40
  26. package/dist/shared/util/src/createRandomId.d.ts +0 -1
  27. package/dist/shared/util/src/createRandomId.js +0 -10
  28. package/dist/shared/util/src/equals.d.ts +0 -1
  29. package/dist/shared/util/src/equals.js +0 -49
  30. package/dist/shared/util/src/index.d.ts +0 -6
  31. package/dist/shared/util/src/index.js +0 -22
  32. package/dist/shared/util/src/noop.d.ts +0 -1
  33. package/dist/shared/util/src/noop.js +0 -5
  34. package/dist/shared/util/src/removeUndefinedKeys.d.ts +0 -1
  35. package/dist/shared/util/src/removeUndefinedKeys.js +0 -12
  36. package/dist/shared/util/src/timeout.d.ts +0 -1
  37. package/dist/shared/util/src/timeout.js +0 -16
  38. package/dist/shared/util/src/types.d.ts +0 -36
  39. package/dist/shared/util/src/types.js +0 -2
package/dist/index.js ADDED
@@ -0,0 +1,821 @@
1
+ // src/createWebView.tsx
2
+ function _array_like_to_array(arr, len) {
3
+ if (len == null || len > arr.length) len = arr.length;
4
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
5
+ return arr2;
6
+ }
7
+ function _array_with_holes(arr) {
8
+ if (Array.isArray(arr)) return arr;
9
+ }
10
+ function _array_without_holes(arr) {
11
+ if (Array.isArray(arr)) return _array_like_to_array(arr);
12
+ }
13
+ function _assert_this_initialized(self) {
14
+ if (self === void 0) {
15
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
16
+ }
17
+ return self;
18
+ }
19
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
20
+ try {
21
+ var info = gen[key](arg);
22
+ var value = info.value;
23
+ } catch (error) {
24
+ reject(error);
25
+ return;
26
+ }
27
+ if (info.done) {
28
+ resolve(value);
29
+ } else {
30
+ Promise.resolve(value).then(_next, _throw);
31
+ }
32
+ }
33
+ function _async_to_generator(fn) {
34
+ return function() {
35
+ var self = this, args = arguments;
36
+ return new Promise(function(resolve, reject) {
37
+ var gen = fn.apply(self, args);
38
+ function _next(value) {
39
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
40
+ }
41
+ function _throw(err) {
42
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
43
+ }
44
+ _next(undefined);
45
+ });
46
+ };
47
+ }
48
+ function _call_super(_this, derived, args) {
49
+ derived = _get_prototype_of(derived);
50
+ return _possible_constructor_return(_this, _is_native_reflect_construct() ? Reflect.construct(derived, args || [], _get_prototype_of(_this).constructor) : derived.apply(_this, args));
51
+ }
52
+ function _class_call_check(instance, Constructor) {
53
+ if (!(instance instanceof Constructor)) {
54
+ throw new TypeError("Cannot call a class as a function");
55
+ }
56
+ }
57
+ function _construct(Parent, args, Class) {
58
+ if (_is_native_reflect_construct()) {
59
+ _construct = Reflect.construct;
60
+ } else {
61
+ _construct = function construct(Parent, args, Class) {
62
+ var a = [
63
+ null
64
+ ];
65
+ a.push.apply(a, args);
66
+ var Constructor = Function.bind.apply(Parent, a);
67
+ var instance = new Constructor();
68
+ if (Class) _set_prototype_of(instance, Class.prototype);
69
+ return instance;
70
+ };
71
+ }
72
+ return _construct.apply(null, arguments);
73
+ }
74
+ function _define_property(obj, key, value) {
75
+ if (key in obj) {
76
+ Object.defineProperty(obj, key, {
77
+ value: value,
78
+ enumerable: true,
79
+ configurable: true,
80
+ writable: true
81
+ });
82
+ } else {
83
+ obj[key] = value;
84
+ }
85
+ return obj;
86
+ }
87
+ function _get_prototype_of(o) {
88
+ _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
89
+ return o.__proto__ || Object.getPrototypeOf(o);
90
+ };
91
+ return _get_prototype_of(o);
92
+ }
93
+ function _inherits(subClass, superClass) {
94
+ if (typeof superClass !== "function" && superClass !== null) {
95
+ throw new TypeError("Super expression must either be null or a function");
96
+ }
97
+ subClass.prototype = Object.create(superClass && superClass.prototype, {
98
+ constructor: {
99
+ value: subClass,
100
+ writable: true,
101
+ configurable: true
102
+ }
103
+ });
104
+ if (superClass) _set_prototype_of(subClass, superClass);
105
+ }
106
+ function _is_native_function(fn) {
107
+ return Function.toString.call(fn).indexOf("[native code]") !== -1;
108
+ }
109
+ function _iterable_to_array(iter) {
110
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
111
+ }
112
+ function _iterable_to_array_limit(arr, i) {
113
+ var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
114
+ if (_i == null) return;
115
+ var _arr = [];
116
+ var _n = true;
117
+ var _d = false;
118
+ var _s, _e;
119
+ try {
120
+ for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
121
+ _arr.push(_s.value);
122
+ if (i && _arr.length === i) break;
123
+ }
124
+ } catch (err) {
125
+ _d = true;
126
+ _e = err;
127
+ } finally{
128
+ try {
129
+ if (!_n && _i["return"] != null) _i["return"]();
130
+ } finally{
131
+ if (_d) throw _e;
132
+ }
133
+ }
134
+ return _arr;
135
+ }
136
+ function _non_iterable_rest() {
137
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
138
+ }
139
+ function _non_iterable_spread() {
140
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
141
+ }
142
+ function _object_spread(target) {
143
+ for(var i = 1; i < arguments.length; i++){
144
+ var source = arguments[i] != null ? arguments[i] : {};
145
+ var ownKeys = Object.keys(source);
146
+ if (typeof Object.getOwnPropertySymbols === "function") {
147
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
148
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
149
+ }));
150
+ }
151
+ ownKeys.forEach(function(key) {
152
+ _define_property(target, key, source[key]);
153
+ });
154
+ }
155
+ return target;
156
+ }
157
+ function ownKeys(object, enumerableOnly) {
158
+ var keys = Object.keys(object);
159
+ if (Object.getOwnPropertySymbols) {
160
+ var symbols = Object.getOwnPropertySymbols(object);
161
+ if (enumerableOnly) {
162
+ symbols = symbols.filter(function(sym) {
163
+ return Object.getOwnPropertyDescriptor(object, sym).enumerable;
164
+ });
165
+ }
166
+ keys.push.apply(keys, symbols);
167
+ }
168
+ return keys;
169
+ }
170
+ function _object_spread_props(target, source) {
171
+ source = source != null ? source : {};
172
+ if (Object.getOwnPropertyDescriptors) {
173
+ Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
174
+ } else {
175
+ ownKeys(Object(source)).forEach(function(key) {
176
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
177
+ });
178
+ }
179
+ return target;
180
+ }
181
+ function _possible_constructor_return(self, call) {
182
+ if (call && (_type_of(call) === "object" || typeof call === "function")) {
183
+ return call;
184
+ }
185
+ return _assert_this_initialized(self);
186
+ }
187
+ function _set_prototype_of(o, p) {
188
+ _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
189
+ o.__proto__ = p;
190
+ return o;
191
+ };
192
+ return _set_prototype_of(o, p);
193
+ }
194
+ function _sliced_to_array(arr, i) {
195
+ return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
196
+ }
197
+ function _to_array(arr) {
198
+ return _array_with_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_rest();
199
+ }
200
+ function _to_consumable_array(arr) {
201
+ return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
202
+ }
203
+ function _type_of(obj) {
204
+ "@swc/helpers - typeof";
205
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
206
+ }
207
+ function _unsupported_iterable_to_array(o, minLen) {
208
+ if (!o) return;
209
+ if (typeof o === "string") return _array_like_to_array(o, minLen);
210
+ var n = Object.prototype.toString.call(o).slice(8, -1);
211
+ if (n === "Object" && o.constructor) n = o.constructor.name;
212
+ if (n === "Map" || n === "Set") return Array.from(n);
213
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
214
+ }
215
+ function _wrap_native_super(Class) {
216
+ var _cache = typeof Map === "function" ? new Map() : undefined;
217
+ _wrap_native_super = function wrapNativeSuper(Class) {
218
+ if (Class === null || !_is_native_function(Class)) return Class;
219
+ if (typeof Class !== "function") {
220
+ throw new TypeError("Super expression must either be null or a function");
221
+ }
222
+ if (typeof _cache !== "undefined") {
223
+ if (_cache.has(Class)) return _cache.get(Class);
224
+ _cache.set(Class, Wrapper);
225
+ }
226
+ function Wrapper() {
227
+ return _construct(Class, arguments, _get_prototype_of(this).constructor);
228
+ }
229
+ Wrapper.prototype = Object.create(Class.prototype, {
230
+ constructor: {
231
+ value: Wrapper,
232
+ enumerable: false,
233
+ writable: true,
234
+ configurable: true
235
+ }
236
+ });
237
+ return _set_prototype_of(Wrapper, Class);
238
+ };
239
+ return _wrap_native_super(Class);
240
+ }
241
+ function _is_native_reflect_construct() {
242
+ try {
243
+ var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
244
+ } catch (_) {}
245
+ return (_is_native_reflect_construct = function() {
246
+ return !!result;
247
+ })();
248
+ }
249
+ function _ts_generator(thisArg, body) {
250
+ var f, y, t, g, _ = {
251
+ label: 0,
252
+ sent: function() {
253
+ if (t[0] & 1) throw t[1];
254
+ return t[1];
255
+ },
256
+ trys: [],
257
+ ops: []
258
+ };
259
+ return g = {
260
+ next: verb(0),
261
+ "throw": verb(1),
262
+ "return": verb(2)
263
+ }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
264
+ return this;
265
+ }), g;
266
+ function verb(n) {
267
+ return function(v) {
268
+ return step([
269
+ n,
270
+ v
271
+ ]);
272
+ };
273
+ }
274
+ function step(op) {
275
+ if (f) throw new TypeError("Generator is already executing.");
276
+ while(_)try {
277
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
278
+ if (y = 0, t) op = [
279
+ op[0] & 2,
280
+ t.value
281
+ ];
282
+ switch(op[0]){
283
+ case 0:
284
+ case 1:
285
+ t = op;
286
+ break;
287
+ case 4:
288
+ _.label++;
289
+ return {
290
+ value: op[1],
291
+ done: false
292
+ };
293
+ case 5:
294
+ _.label++;
295
+ y = op[1];
296
+ op = [
297
+ 0
298
+ ];
299
+ continue;
300
+ case 7:
301
+ op = _.ops.pop();
302
+ _.trys.pop();
303
+ continue;
304
+ default:
305
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
306
+ _ = 0;
307
+ continue;
308
+ }
309
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
310
+ _.label = op[1];
311
+ break;
312
+ }
313
+ if (op[0] === 6 && _.label < t[1]) {
314
+ _.label = t[1];
315
+ t = op;
316
+ break;
317
+ }
318
+ if (t && _.label < t[2]) {
319
+ _.label = t[2];
320
+ _.ops.push(op);
321
+ break;
322
+ }
323
+ if (t[2]) _.ops.pop();
324
+ _.trys.pop();
325
+ continue;
326
+ }
327
+ op = body.call(thisArg, _);
328
+ } catch (e) {
329
+ op = [
330
+ 6,
331
+ e
332
+ ];
333
+ y = 0;
334
+ } finally{
335
+ f = t = 0;
336
+ }
337
+ if (op[0] & 5) throw op[1];
338
+ return {
339
+ value: op[0] ? op[1] : void 0,
340
+ done: true
341
+ };
342
+ }
343
+ }
344
+ import { createEvents } from "@webview-bridge/utils";
345
+ import React, { forwardRef, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef } from "react";
346
+ import WebView from "react-native-webview";
347
+ // src/integrations/bridge.ts
348
+ import { equals, removeUndefinedKeys } from "@webview-bridge/utils";
349
+ var bridge = function(procedures) {
350
+ var getState = function() {
351
+ return state;
352
+ };
353
+ var setState = function(newState) {
354
+ var _newState = _object_spread({}, state, removeUndefinedKeys(newState));
355
+ if (equals(state, _newState)) {
356
+ return;
357
+ }
358
+ var prevState = state;
359
+ state = _newState;
360
+ emitChange(state, prevState);
361
+ };
362
+ var state = typeof procedures === "function" ? procedures({
363
+ get: getState,
364
+ set: setState
365
+ }) : procedures;
366
+ var listeners = /* @__PURE__ */ new Set();
367
+ var emitChange = function(newState, prevState) {
368
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
369
+ try {
370
+ for(var _iterator = listeners[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
371
+ var listener = _step.value;
372
+ listener(newState, prevState);
373
+ }
374
+ } catch (err) {
375
+ _didIteratorError = true;
376
+ _iteratorError = err;
377
+ } finally{
378
+ try {
379
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
380
+ _iterator.return();
381
+ }
382
+ } finally{
383
+ if (_didIteratorError) {
384
+ throw _iteratorError;
385
+ }
386
+ }
387
+ }
388
+ };
389
+ var subscribe = function(listener) {
390
+ listeners.add(listener);
391
+ return function() {
392
+ return listeners.delete(listener);
393
+ };
394
+ };
395
+ return {
396
+ getState: getState,
397
+ setState: setState,
398
+ subscribe: subscribe
399
+ };
400
+ };
401
+ var handleBridge = /*#__PURE__*/ function() {
402
+ var _ref = _async_to_generator(function(param) {
403
+ var bridge2, method, args, webview, eventId, _bridge, _method, handleThrow, response, error;
404
+ return _ts_generator(this, function(_state) {
405
+ switch(_state.label){
406
+ case 0:
407
+ bridge2 = param.bridge, method = param.method, args = param.args, webview = param.webview, eventId = param.eventId;
408
+ _bridge = bridge2.getState();
409
+ _method = _bridge[method];
410
+ handleThrow = function() {
411
+ webview.injectJavaScript(SAFE_NATIVE_EMITTER_THROW("".concat(method, "-").concat(eventId)));
412
+ };
413
+ if (!(method in _bridge)) {
414
+ handleThrow();
415
+ return [
416
+ 2
417
+ ];
418
+ }
419
+ if (typeof _method !== "function") {
420
+ return [
421
+ 2
422
+ ];
423
+ }
424
+ _state.label = 1;
425
+ case 1:
426
+ _state.trys.push([
427
+ 1,
428
+ 3,
429
+ ,
430
+ 4
431
+ ]);
432
+ return [
433
+ 4,
434
+ _method === null || _method === void 0 ? void 0 : _method.apply(void 0, _to_consumable_array(args !== null && args !== void 0 ? args : []))
435
+ ];
436
+ case 2:
437
+ response = _state.sent();
438
+ webview.injectJavaScript(SAFE_NATIVE_EMITTER_EMIT("".concat(method, "-").concat(eventId), response));
439
+ return [
440
+ 3,
441
+ 4
442
+ ];
443
+ case 3:
444
+ error = _state.sent();
445
+ handleThrow();
446
+ console.error(error);
447
+ return [
448
+ 3,
449
+ 4
450
+ ];
451
+ case 4:
452
+ return [
453
+ 2
454
+ ];
455
+ }
456
+ });
457
+ });
458
+ return function handleBridge(_) {
459
+ return _ref.apply(this, arguments);
460
+ };
461
+ }();
462
+ var INJECT_BRIDGE_METHODS = function(bridgeNames) {
463
+ return "\n window.__bridgeMethods__ = ".concat(JSON.stringify(bridgeNames), ";\n");
464
+ };
465
+ var INJECT_BRIDGE_STATE = function(initialState) {
466
+ return "\n window.__bridgeInitialState__ = ".concat(JSON.stringify(initialState), ";\n");
467
+ };
468
+ var SAFE_NATIVE_EMITTER_EMIT = function(eventName, data) {
469
+ var dataString = JSON.stringify(data);
470
+ return "\nif (window.nativeEmitter) {\n window.nativeEmitter.emit('".concat(eventName, "', ").concat(dataString, ");\n} else {\n window.nativeBatchedEvents = window.nativeBatchedEvents || [];\n window.nativeBatchedEvents.push(['").concat(eventName, "', ").concat(dataString, "]);\n}\ntrue;\n");
471
+ };
472
+ var SAFE_NATIVE_EMITTER_THROW = function(eventName) {
473
+ return "\nif (window.nativeEmitter) {\n window.nativeEmitter.emit('".concat(eventName, "', {}, true);\n} else {\n window.nativeBatchedEvents = window.nativeBatchedEvents || [];\n window.nativeBatchedEvents.push(['").concat(eventName, "', {}, true]);\n}\ntrue;\n");
474
+ };
475
+ // src/integrations/console.ts
476
+ var INJECT_DEBUG = '\n{\n const originalConsoleLog = console.log;\n const originalConsoleError = console.error;\n const originalConsoleWarn = console.warn;\n\n console.log = function() {\n var message = JSON.stringify(Array.from(arguments));\n window.ReactNativeWebView?.postMessage(\n JSON.stringify({ type: "log", body: { method: "log", args: message } }),\n );\n originalConsoleLog.apply(console, arguments);\n };\n\n console.error = function() {\n var message = JSON.stringify(Array.from(arguments));\n window.ReactNativeWebView?.postMessage(\n JSON.stringify({ type: "log", body: { method: "error", args: message } }),\n );\n originalConsoleError.apply(console, arguments);\n };\n\n console.warn = function() {\n var message = JSON.stringify(Array.from(arguments));\n window.ReactNativeWebView?.postMessage(\n JSON.stringify({ type: "log", body: { method: "warn", args: message } }),\n );\n originalConsoleWarn.apply(console, arguments);\n };\n};\n';
477
+ var handleLog = function(type, message) {
478
+ var _JSON_parse = _to_array(JSON.parse(message)), formatMessage = _JSON_parse[0], parsedMessage = _JSON_parse.slice(1);
479
+ var webviewMark = "(WebView) ";
480
+ var webviewMarkedMessage = typeof formatMessage === "string" ? [
481
+ webviewMark + formatMessage
482
+ ].concat(_to_consumable_array(parsedMessage)) : [
483
+ webviewMark,
484
+ formatMessage
485
+ ].concat(_to_consumable_array(parsedMessage));
486
+ switch(type){
487
+ case "log":
488
+ {
489
+ var _console;
490
+ (_console = console).log.apply(_console, _to_consumable_array(webviewMarkedMessage));
491
+ break;
492
+ }
493
+ case "error":
494
+ {
495
+ var _console1;
496
+ (_console1 = console).error.apply(_console1, _to_consumable_array(webviewMarkedMessage));
497
+ break;
498
+ }
499
+ case "warn":
500
+ {
501
+ var _console2;
502
+ (_console2 = console).warn.apply(_console2, _to_consumable_array(webviewMarkedMessage));
503
+ break;
504
+ }
505
+ }
506
+ };
507
+ // src/integrations/handleRegisterWebMethod.ts
508
+ import { createRandomId, createResolver, timeout } from "@webview-bridge/utils";
509
+ // src/error.ts
510
+ var WebMethodError = /*#__PURE__*/ function(Error1) {
511
+ "use strict";
512
+ _inherits(WebMethodError, Error1);
513
+ function WebMethodError(methodName) {
514
+ _class_call_check(this, WebMethodError);
515
+ var _this;
516
+ _this = _call_super(this, WebMethodError, [
517
+ "An error occurred in the WebMethod.current.".concat(methodName)
518
+ ]);
519
+ _this.name = "WebMethodError";
520
+ return _this;
521
+ }
522
+ return WebMethodError;
523
+ }(_wrap_native_super(Error));
524
+ // src/integrations/handleRegisterWebMethod.ts
525
+ var handleRegisterWebMethod = function(emitter, webview, bridgeNames, responseTimeout) {
526
+ return bridgeNames.reduce(function(acc, methodName) {
527
+ acc[methodName] = /*#__PURE__*/ _async_to_generator(function() {
528
+ var _len, args, _key, eventId;
529
+ var _arguments = arguments;
530
+ return _ts_generator(this, function(_state) {
531
+ for(_len = _arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
532
+ args[_key] = _arguments[_key];
533
+ }
534
+ eventId = createRandomId();
535
+ return [
536
+ 2,
537
+ Promise.race([
538
+ createResolver({
539
+ emitter: emitter,
540
+ methodName: methodName,
541
+ eventId: eventId,
542
+ evaluate: function() {
543
+ webview.injectJavaScript("\n window.webEmitter.emit('".concat(methodName, "', '").concat(eventId, "', ").concat(JSON.stringify(args), ");\n \n true;\n "));
544
+ },
545
+ failHandler: new WebMethodError(methodName)
546
+ }),
547
+ timeout(responseTimeout)
548
+ ])
549
+ ];
550
+ });
551
+ });
552
+ return acc;
553
+ }, {});
554
+ };
555
+ // src/createWebView.tsx
556
+ var createWebView = function(param) {
557
+ var bridge2 = param.bridge, debug = param.debug, _param_responseTimeout = param.responseTimeout, responseTimeout = _param_responseTimeout === void 0 ? 2e3 : _param_responseTimeout, postMessageSchema2 = param.postMessageSchema, fallback = param.fallback;
558
+ var WebMethod = {
559
+ current: {
560
+ isReady: false
561
+ }
562
+ };
563
+ var webviewRefList = [];
564
+ var emitter = createEvents();
565
+ bridge2.subscribe(function(state) {
566
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
567
+ try {
568
+ for(var _iterator = webviewRefList[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
569
+ var ref = _step.value;
570
+ var _ref_current;
571
+ ref === null || ref === void 0 ? void 0 : (_ref_current = ref.current) === null || _ref_current === void 0 ? void 0 : _ref_current.injectJavaScript(SAFE_NATIVE_EMITTER_EMIT("bridgeStateChange", state));
572
+ }
573
+ } catch (err) {
574
+ _didIteratorError = true;
575
+ _iteratorError = err;
576
+ } finally{
577
+ try {
578
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
579
+ _iterator.return();
580
+ }
581
+ } finally{
582
+ if (_didIteratorError) {
583
+ throw _iteratorError;
584
+ }
585
+ }
586
+ }
587
+ });
588
+ return {
589
+ /**
590
+ * Sends an event from React Native to the Web.
591
+ * @link https://gronxb.github.io/webview-bridge/using-a-post-message.html
592
+ */ postMessage: function(eventName, args) {
593
+ var _args = args;
594
+ if (postMessageSchema2) {
595
+ _args = postMessageSchema2[eventName].validate(args);
596
+ }
597
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
598
+ try {
599
+ for(var _iterator = webviewRefList[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
600
+ var ref = _step.value;
601
+ var _ref_current;
602
+ ref === null || ref === void 0 ? void 0 : (_ref_current = ref.current) === null || _ref_current === void 0 ? void 0 : _ref_current.injectJavaScript(SAFE_NATIVE_EMITTER_EMIT("postMessage/".concat(String(eventName)), _args));
603
+ }
604
+ } catch (err) {
605
+ _didIteratorError = true;
606
+ _iteratorError = err;
607
+ } finally{
608
+ try {
609
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
610
+ _iterator.return();
611
+ }
612
+ } finally{
613
+ if (_didIteratorError) {
614
+ throw _iteratorError;
615
+ }
616
+ }
617
+ }
618
+ },
619
+ WebView: forwardRef(function(props, ref) {
620
+ var webviewRef = useRef(null);
621
+ useLayoutEffect(function() {
622
+ webviewRefList.push(webviewRef);
623
+ return function() {
624
+ webviewRefList.pop();
625
+ };
626
+ }, []);
627
+ var initData = useMemo(function() {
628
+ var _bridge2_getState;
629
+ var bridgeMethods = Object.entries((_bridge2_getState = bridge2.getState()) !== null && _bridge2_getState !== void 0 ? _bridge2_getState : {}).filter(function(param) {
630
+ var _param = _sliced_to_array(param, 2), _ = _param[0], bridge3 = _param[1];
631
+ return typeof bridge3 === "function";
632
+ }).map(function(param) {
633
+ var _param = _sliced_to_array(param, 1), name = _param[0];
634
+ return name;
635
+ });
636
+ var _bridge2_getState1;
637
+ var initialState = Object.fromEntries(Object.entries((_bridge2_getState1 = bridge2.getState()) !== null && _bridge2_getState1 !== void 0 ? _bridge2_getState1 : {}).filter(function(param) {
638
+ var _param = _sliced_to_array(param, 2), _ = _param[0], value = _param[1];
639
+ return typeof value !== "function";
640
+ }));
641
+ return {
642
+ bridgeMethods: bridgeMethods,
643
+ initialState: initialState
644
+ };
645
+ }, []);
646
+ useEffect(function() {
647
+ var _webviewRef_current;
648
+ (_webviewRef_current = webviewRef.current) === null || _webviewRef_current === void 0 ? void 0 : _webviewRef_current.injectJavaScript(SAFE_NATIVE_EMITTER_EMIT("hydrate", initData));
649
+ }, [
650
+ initData
651
+ ]);
652
+ useImperativeHandle(ref, function() {
653
+ return webviewRef.current;
654
+ }, []);
655
+ var handleMessage = /*#__PURE__*/ function() {
656
+ var _ref = _async_to_generator(function(event) {
657
+ var _props_onMessage, _JSON_parse, type, body, method, args, method1, args1, eventId, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, ref2, _ref2_current, bridgeNames, eventId1, funcName, value, eventId2, funcName1, method2;
658
+ return _ts_generator(this, function(_state) {
659
+ (_props_onMessage = props.onMessage) === null || _props_onMessage === void 0 ? void 0 : _props_onMessage.call(props, event);
660
+ if (!webviewRef.current) {
661
+ return [
662
+ 2
663
+ ];
664
+ }
665
+ _JSON_parse = JSON.parse(event.nativeEvent.data), type = _JSON_parse.type, body = _JSON_parse.body;
666
+ switch(type){
667
+ case "log":
668
+ {
669
+ method = body.method, args = body.args;
670
+ debug && handleLog(method, args);
671
+ return [
672
+ 2
673
+ ];
674
+ }
675
+ case "bridge":
676
+ {
677
+ method1 = body.method, args1 = body.args, eventId = body.eventId;
678
+ handleBridge({
679
+ bridge: bridge2,
680
+ method: method1,
681
+ args: args1,
682
+ eventId: eventId,
683
+ webview: webviewRef.current
684
+ });
685
+ return [
686
+ 2
687
+ ];
688
+ }
689
+ case "getBridgeState":
690
+ {
691
+ _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
692
+ try {
693
+ for(_iterator = webviewRefList[Symbol.iterator](); !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
694
+ ref2 = _step.value;
695
+ ;
696
+ ref2 === null || ref2 === void 0 ? void 0 : (_ref2_current = ref2.current) === null || _ref2_current === void 0 ? void 0 : _ref2_current.injectJavaScript(SAFE_NATIVE_EMITTER_EMIT("bridgeStateChange", bridge2.getState()));
697
+ }
698
+ } catch (err) {
699
+ _didIteratorError = true;
700
+ _iteratorError = err;
701
+ } finally{
702
+ try {
703
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
704
+ _iterator.return();
705
+ }
706
+ } finally{
707
+ if (_didIteratorError) {
708
+ throw _iteratorError;
709
+ }
710
+ }
711
+ }
712
+ return [
713
+ 2
714
+ ];
715
+ }
716
+ case "registerWebMethod":
717
+ {
718
+ bridgeNames = body.bridgeNames;
719
+ Object.assign(WebMethod.current, handleRegisterWebMethod(emitter, webviewRef.current, bridgeNames, responseTimeout));
720
+ WebMethod.current.isReady = true;
721
+ return [
722
+ 2
723
+ ];
724
+ }
725
+ case "webMethodResponse":
726
+ {
727
+ eventId1 = body.eventId, funcName = body.funcName, value = body.value;
728
+ emitter.emit("".concat(funcName, "-").concat(eventId1), value);
729
+ return [
730
+ 2
731
+ ];
732
+ }
733
+ case "webMethodError":
734
+ {
735
+ eventId2 = body.eventId, funcName1 = body.funcName;
736
+ emitter.emit("".concat(funcName1, "-").concat(eventId2), {}, true);
737
+ return [
738
+ 2
739
+ ];
740
+ }
741
+ case "fallback":
742
+ {
743
+ method2 = body.method;
744
+ fallback === null || fallback === void 0 ? void 0 : fallback(method2);
745
+ return [
746
+ 2
747
+ ];
748
+ }
749
+ }
750
+ return [
751
+ 2
752
+ ];
753
+ });
754
+ });
755
+ return function handleMessage(event) {
756
+ return _ref.apply(this, arguments);
757
+ };
758
+ }();
759
+ return /* @__PURE__ */ React.createElement(WebView, _object_spread_props(_object_spread({}, props), {
760
+ ref: webviewRef,
761
+ onMessage: handleMessage,
762
+ injectedJavaScriptBeforeContentLoaded: [
763
+ INJECT_BRIDGE_METHODS(initData.bridgeMethods),
764
+ INJECT_BRIDGE_STATE(initData.initialState),
765
+ props.injectedJavaScriptBeforeContentLoaded,
766
+ "true;"
767
+ ].filter(Boolean).join("\n"),
768
+ injectedJavaScript: [
769
+ debug && INJECT_DEBUG,
770
+ props.injectedJavaScript,
771
+ "true;"
772
+ ].filter(Boolean).join("\n")
773
+ }));
774
+ }),
775
+ /**
776
+ * @deprecated Use `postMessage` instead. And complete the type through the `postMessageSchema` option.
777
+ * @see https://gronxb.github.io/webview-bridge/using-a-post-message.html
778
+ * @example
779
+ import { createWebView, postMessageSchema } from "@webview-bridge/react-native";
780
+ import { z } from "zod";
781
+
782
+ const appPostMessageSchema = postMessageSchema({
783
+ eventName1: z.object({
784
+ message: z.string(),
785
+ }),
786
+ eventName2: z.string(),
787
+ });
788
+
789
+
790
+ // Export the event schema to be used in the web application
791
+ export type AppPostMessageSchema = typeof appPostMessageSchema;
792
+
793
+ // When you bridge a webview, a postMessage is extracted.
794
+ export const { postMessage } = createWebView({
795
+ postMessageSchema: appPostMessageSchema, // Pass in the your schema. This is optional, so if the type doesn't matter to you, you don't need to include it.
796
+ // ..
797
+ });
798
+
799
+ // usage
800
+ postMessage("eventName1", {
801
+ message: "test",
802
+ });
803
+ postMessage("eventName2", "test");
804
+ */ linkWebMethod: function linkWebMethod() {
805
+ return WebMethod;
806
+ }
807
+ };
808
+ };
809
+ // src/integrations/postMessageSchema.ts
810
+ var postMessageSchema = function(schema) {
811
+ return schema;
812
+ };
813
+ // src/useBridge.ts
814
+ import { useSyncExternalStoreWithSelector } from "use-sync-external-store/with-selector.js";
815
+ function useBridge(store, selector) {
816
+ var $selector = selector !== null && selector !== void 0 ? selector : function(state) {
817
+ return state;
818
+ };
819
+ return useSyncExternalStoreWithSelector(store.subscribe, store.getState, store.getState, $selector);
820
+ }
821
+ export { INJECT_BRIDGE_METHODS, INJECT_BRIDGE_STATE, SAFE_NATIVE_EMITTER_EMIT, SAFE_NATIVE_EMITTER_THROW, bridge, createWebView, handleBridge, postMessageSchema, useBridge };