@webview-bridge/react-native 1.6.2 → 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 (38) hide show
  1. package/dist/index.cjs +922 -0
  2. package/dist/{packages/react-native/src/createWebView.d.ts → index.d.cts} +37 -7
  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.js +0 -212
  7. package/dist/packages/react-native/src/error.d.ts +0 -3
  8. package/dist/packages/react-native/src/error.js +0 -10
  9. package/dist/packages/react-native/src/index.d.ts +0 -6
  10. package/dist/packages/react-native/src/index.js +0 -22
  11. package/dist/packages/react-native/src/integrations/bridge.d.ts +0 -20
  12. package/dist/packages/react-native/src/integrations/bridge.js +0 -95
  13. package/dist/packages/react-native/src/integrations/console.d.ts +0 -3
  14. package/dist/packages/react-native/src/integrations/console.js +0 -56
  15. package/dist/packages/react-native/src/integrations/handleRegisterWebMethod.d.ts +0 -4
  16. package/dist/packages/react-native/src/integrations/handleRegisterWebMethod.js +0 -30
  17. package/dist/packages/react-native/src/integrations/postMessageSchema.d.ts +0 -2
  18. package/dist/packages/react-native/src/integrations/postMessageSchema.js +0 -56
  19. package/dist/packages/react-native/src/types/webview.d.ts +0 -3
  20. package/dist/packages/react-native/src/types/webview.js +0 -2
  21. package/dist/packages/react-native/src/useBridge.d.ts +0 -3
  22. package/dist/packages/react-native/src/useBridge.js +0 -9
  23. package/dist/shared/util/src/createEvents.d.ts +0 -25
  24. package/dist/shared/util/src/createEvents.js +0 -40
  25. package/dist/shared/util/src/createRandomId.d.ts +0 -1
  26. package/dist/shared/util/src/createRandomId.js +0 -10
  27. package/dist/shared/util/src/equals.d.ts +0 -1
  28. package/dist/shared/util/src/equals.js +0 -49
  29. package/dist/shared/util/src/index.d.ts +0 -6
  30. package/dist/shared/util/src/index.js +0 -22
  31. package/dist/shared/util/src/noop.d.ts +0 -1
  32. package/dist/shared/util/src/noop.js +0 -5
  33. package/dist/shared/util/src/removeUndefinedKeys.d.ts +0 -1
  34. package/dist/shared/util/src/removeUndefinedKeys.js +0 -12
  35. package/dist/shared/util/src/timeout.d.ts +0 -1
  36. package/dist/shared/util/src/timeout.js +0 -16
  37. package/dist/shared/util/src/types.d.ts +0 -36
  38. package/dist/shared/util/src/types.js +0 -2
package/dist/index.cjs ADDED
@@ -0,0 +1,922 @@
1
+ "use strict";
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
+ var __create = Object.create;
345
+ var __defProp = Object.defineProperty;
346
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
347
+ var __getOwnPropNames = Object.getOwnPropertyNames;
348
+ var __getProtoOf = Object.getPrototypeOf;
349
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
350
+ var __export = function(target, all) {
351
+ for(var name in all)__defProp(target, name, {
352
+ get: all[name],
353
+ enumerable: true
354
+ });
355
+ };
356
+ var __copyProps = function(to, from, except, desc) {
357
+ if (from && (typeof from === "undefined" ? "undefined" : _type_of(from)) === "object" || typeof from === "function") {
358
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
359
+ try {
360
+ var _loop = function() {
361
+ var key = _step.value;
362
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
363
+ get: function() {
364
+ return from[key];
365
+ },
366
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
367
+ });
368
+ };
369
+ for(var _iterator = __getOwnPropNames(from)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true)_loop();
370
+ } catch (err) {
371
+ _didIteratorError = true;
372
+ _iteratorError = err;
373
+ } finally{
374
+ try {
375
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
376
+ _iterator.return();
377
+ }
378
+ } finally{
379
+ if (_didIteratorError) {
380
+ throw _iteratorError;
381
+ }
382
+ }
383
+ }
384
+ }
385
+ return to;
386
+ };
387
+ var __toESM = function(mod, isNodeMode, target) {
388
+ return target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(// If the importer is in node compatibility mode or this is not an ESM
389
+ // file that has been converted to a CommonJS file using a Babel-
390
+ // compatible transform (i.e. "__esModule" has not been set), then set
391
+ // "default" to the CommonJS "module.exports" for node compatibility.
392
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
393
+ value: mod,
394
+ enumerable: true
395
+ }) : target, mod);
396
+ };
397
+ var __toCommonJS = function(mod) {
398
+ return __copyProps(__defProp({}, "__esModule", {
399
+ value: true
400
+ }), mod);
401
+ };
402
+ // src/index.ts
403
+ var src_exports = {};
404
+ __export(src_exports, {
405
+ INJECT_BRIDGE_METHODS: function() {
406
+ return INJECT_BRIDGE_METHODS;
407
+ },
408
+ INJECT_BRIDGE_STATE: function() {
409
+ return INJECT_BRIDGE_STATE;
410
+ },
411
+ SAFE_NATIVE_EMITTER_EMIT: function() {
412
+ return SAFE_NATIVE_EMITTER_EMIT;
413
+ },
414
+ SAFE_NATIVE_EMITTER_THROW: function() {
415
+ return SAFE_NATIVE_EMITTER_THROW;
416
+ },
417
+ bridge: function() {
418
+ return bridge;
419
+ },
420
+ createWebView: function() {
421
+ return createWebView;
422
+ },
423
+ handleBridge: function() {
424
+ return handleBridge;
425
+ },
426
+ postMessageSchema: function() {
427
+ return postMessageSchema;
428
+ },
429
+ useBridge: function() {
430
+ return useBridge;
431
+ }
432
+ });
433
+ module.exports = __toCommonJS(src_exports);
434
+ // src/createWebView.tsx
435
+ var import_utils3 = require("@webview-bridge/utils");
436
+ var import_react = __toESM(require("react"), 1);
437
+ var import_react_native_webview = __toESM(require("react-native-webview"), 1);
438
+ // src/integrations/bridge.ts
439
+ var import_utils = require("@webview-bridge/utils");
440
+ var bridge = function(procedures) {
441
+ var getState = function() {
442
+ return state;
443
+ };
444
+ var setState = function(newState) {
445
+ var _newState = _object_spread({}, state, (0, import_utils.removeUndefinedKeys)(newState));
446
+ if ((0, import_utils.equals)(state, _newState)) {
447
+ return;
448
+ }
449
+ var prevState = state;
450
+ state = _newState;
451
+ emitChange(state, prevState);
452
+ };
453
+ var state = typeof procedures === "function" ? procedures({
454
+ get: getState,
455
+ set: setState
456
+ }) : procedures;
457
+ var listeners = /* @__PURE__ */ new Set();
458
+ var emitChange = function(newState, prevState) {
459
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
460
+ try {
461
+ for(var _iterator = listeners[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
462
+ var listener = _step.value;
463
+ listener(newState, prevState);
464
+ }
465
+ } catch (err) {
466
+ _didIteratorError = true;
467
+ _iteratorError = err;
468
+ } finally{
469
+ try {
470
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
471
+ _iterator.return();
472
+ }
473
+ } finally{
474
+ if (_didIteratorError) {
475
+ throw _iteratorError;
476
+ }
477
+ }
478
+ }
479
+ };
480
+ var subscribe = function(listener) {
481
+ listeners.add(listener);
482
+ return function() {
483
+ return listeners.delete(listener);
484
+ };
485
+ };
486
+ return {
487
+ getState: getState,
488
+ setState: setState,
489
+ subscribe: subscribe
490
+ };
491
+ };
492
+ var handleBridge = /*#__PURE__*/ function() {
493
+ var _ref = _async_to_generator(function(param) {
494
+ var bridge2, method, args, webview, eventId, _bridge, _method, handleThrow, response, error;
495
+ return _ts_generator(this, function(_state) {
496
+ switch(_state.label){
497
+ case 0:
498
+ bridge2 = param.bridge, method = param.method, args = param.args, webview = param.webview, eventId = param.eventId;
499
+ _bridge = bridge2.getState();
500
+ _method = _bridge[method];
501
+ handleThrow = function() {
502
+ webview.injectJavaScript(SAFE_NATIVE_EMITTER_THROW("".concat(method, "-").concat(eventId)));
503
+ };
504
+ if (!(method in _bridge)) {
505
+ handleThrow();
506
+ return [
507
+ 2
508
+ ];
509
+ }
510
+ if (typeof _method !== "function") {
511
+ return [
512
+ 2
513
+ ];
514
+ }
515
+ _state.label = 1;
516
+ case 1:
517
+ _state.trys.push([
518
+ 1,
519
+ 3,
520
+ ,
521
+ 4
522
+ ]);
523
+ return [
524
+ 4,
525
+ _method === null || _method === void 0 ? void 0 : _method.apply(void 0, _to_consumable_array(args !== null && args !== void 0 ? args : []))
526
+ ];
527
+ case 2:
528
+ response = _state.sent();
529
+ webview.injectJavaScript(SAFE_NATIVE_EMITTER_EMIT("".concat(method, "-").concat(eventId), response));
530
+ return [
531
+ 3,
532
+ 4
533
+ ];
534
+ case 3:
535
+ error = _state.sent();
536
+ handleThrow();
537
+ console.error(error);
538
+ return [
539
+ 3,
540
+ 4
541
+ ];
542
+ case 4:
543
+ return [
544
+ 2
545
+ ];
546
+ }
547
+ });
548
+ });
549
+ return function handleBridge(_) {
550
+ return _ref.apply(this, arguments);
551
+ };
552
+ }();
553
+ var INJECT_BRIDGE_METHODS = function(bridgeNames) {
554
+ return "\n window.__bridgeMethods__ = ".concat(JSON.stringify(bridgeNames), ";\n");
555
+ };
556
+ var INJECT_BRIDGE_STATE = function(initialState) {
557
+ return "\n window.__bridgeInitialState__ = ".concat(JSON.stringify(initialState), ";\n");
558
+ };
559
+ var SAFE_NATIVE_EMITTER_EMIT = function(eventName, data) {
560
+ var dataString = JSON.stringify(data);
561
+ 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");
562
+ };
563
+ var SAFE_NATIVE_EMITTER_THROW = function(eventName) {
564
+ 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");
565
+ };
566
+ // src/integrations/console.ts
567
+ 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';
568
+ var handleLog = function(type, message) {
569
+ var _JSON_parse = _to_array(JSON.parse(message)), formatMessage = _JSON_parse[0], parsedMessage = _JSON_parse.slice(1);
570
+ var webviewMark = "(WebView) ";
571
+ var webviewMarkedMessage = typeof formatMessage === "string" ? [
572
+ webviewMark + formatMessage
573
+ ].concat(_to_consumable_array(parsedMessage)) : [
574
+ webviewMark,
575
+ formatMessage
576
+ ].concat(_to_consumable_array(parsedMessage));
577
+ switch(type){
578
+ case "log":
579
+ {
580
+ var _console;
581
+ (_console = console).log.apply(_console, _to_consumable_array(webviewMarkedMessage));
582
+ break;
583
+ }
584
+ case "error":
585
+ {
586
+ var _console1;
587
+ (_console1 = console).error.apply(_console1, _to_consumable_array(webviewMarkedMessage));
588
+ break;
589
+ }
590
+ case "warn":
591
+ {
592
+ var _console2;
593
+ (_console2 = console).warn.apply(_console2, _to_consumable_array(webviewMarkedMessage));
594
+ break;
595
+ }
596
+ }
597
+ };
598
+ // src/integrations/handleRegisterWebMethod.ts
599
+ var import_utils2 = require("@webview-bridge/utils");
600
+ // src/error.ts
601
+ var WebMethodError = /*#__PURE__*/ function(Error1) {
602
+ _inherits(WebMethodError, Error1);
603
+ function WebMethodError(methodName) {
604
+ _class_call_check(this, WebMethodError);
605
+ var _this;
606
+ _this = _call_super(this, WebMethodError, [
607
+ "An error occurred in the WebMethod.current.".concat(methodName)
608
+ ]);
609
+ _this.name = "WebMethodError";
610
+ return _this;
611
+ }
612
+ return WebMethodError;
613
+ }(_wrap_native_super(Error));
614
+ // src/integrations/handleRegisterWebMethod.ts
615
+ var handleRegisterWebMethod = function(emitter, webview, bridgeNames, responseTimeout) {
616
+ return bridgeNames.reduce(function(acc, methodName) {
617
+ acc[methodName] = /*#__PURE__*/ _async_to_generator(function() {
618
+ var _len, args, _key, eventId;
619
+ var _arguments = arguments;
620
+ return _ts_generator(this, function(_state) {
621
+ for(_len = _arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
622
+ args[_key] = _arguments[_key];
623
+ }
624
+ eventId = (0, import_utils2.createRandomId)();
625
+ return [
626
+ 2,
627
+ Promise.race([
628
+ (0, import_utils2.createResolver)({
629
+ emitter: emitter,
630
+ methodName: methodName,
631
+ eventId: eventId,
632
+ evaluate: function() {
633
+ webview.injectJavaScript("\n window.webEmitter.emit('".concat(methodName, "', '").concat(eventId, "', ").concat(JSON.stringify(args), ");\n \n true;\n "));
634
+ },
635
+ failHandler: new WebMethodError(methodName)
636
+ }),
637
+ (0, import_utils2.timeout)(responseTimeout)
638
+ ])
639
+ ];
640
+ });
641
+ });
642
+ return acc;
643
+ }, {});
644
+ };
645
+ // src/createWebView.tsx
646
+ var createWebView = function(param) {
647
+ 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;
648
+ var WebMethod = {
649
+ current: {
650
+ isReady: false
651
+ }
652
+ };
653
+ var webviewRefList = [];
654
+ var emitter = (0, import_utils3.createEvents)();
655
+ bridge2.subscribe(function(state) {
656
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
657
+ try {
658
+ for(var _iterator = webviewRefList[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
659
+ var ref = _step.value;
660
+ var _ref_current;
661
+ 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));
662
+ }
663
+ } catch (err) {
664
+ _didIteratorError = true;
665
+ _iteratorError = err;
666
+ } finally{
667
+ try {
668
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
669
+ _iterator.return();
670
+ }
671
+ } finally{
672
+ if (_didIteratorError) {
673
+ throw _iteratorError;
674
+ }
675
+ }
676
+ }
677
+ });
678
+ return {
679
+ /**
680
+ * Sends an event from React Native to the Web.
681
+ * @link https://gronxb.github.io/webview-bridge/using-a-post-message.html
682
+ */ postMessage: function(eventName, args) {
683
+ var _args = args;
684
+ if (postMessageSchema2) {
685
+ _args = postMessageSchema2[eventName].validate(args);
686
+ }
687
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
688
+ try {
689
+ for(var _iterator = webviewRefList[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
690
+ var ref = _step.value;
691
+ var _ref_current;
692
+ 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));
693
+ }
694
+ } catch (err) {
695
+ _didIteratorError = true;
696
+ _iteratorError = err;
697
+ } finally{
698
+ try {
699
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
700
+ _iterator.return();
701
+ }
702
+ } finally{
703
+ if (_didIteratorError) {
704
+ throw _iteratorError;
705
+ }
706
+ }
707
+ }
708
+ },
709
+ WebView: (0, import_react.forwardRef)(function(props, ref) {
710
+ var webviewRef = (0, import_react.useRef)(null);
711
+ (0, import_react.useLayoutEffect)(function() {
712
+ webviewRefList.push(webviewRef);
713
+ return function() {
714
+ webviewRefList.pop();
715
+ };
716
+ }, []);
717
+ var initData = (0, import_react.useMemo)(function() {
718
+ var _bridge2_getState;
719
+ var bridgeMethods = Object.entries((_bridge2_getState = bridge2.getState()) !== null && _bridge2_getState !== void 0 ? _bridge2_getState : {}).filter(function(param) {
720
+ var _param = _sliced_to_array(param, 2), _ = _param[0], bridge3 = _param[1];
721
+ return typeof bridge3 === "function";
722
+ }).map(function(param) {
723
+ var _param = _sliced_to_array(param, 1), name = _param[0];
724
+ return name;
725
+ });
726
+ var _bridge2_getState1;
727
+ var initialState = Object.fromEntries(Object.entries((_bridge2_getState1 = bridge2.getState()) !== null && _bridge2_getState1 !== void 0 ? _bridge2_getState1 : {}).filter(function(param) {
728
+ var _param = _sliced_to_array(param, 2), _ = _param[0], value = _param[1];
729
+ return typeof value !== "function";
730
+ }));
731
+ return {
732
+ bridgeMethods: bridgeMethods,
733
+ initialState: initialState
734
+ };
735
+ }, []);
736
+ (0, import_react.useEffect)(function() {
737
+ var _webviewRef_current;
738
+ (_webviewRef_current = webviewRef.current) === null || _webviewRef_current === void 0 ? void 0 : _webviewRef_current.injectJavaScript(SAFE_NATIVE_EMITTER_EMIT("hydrate", initData));
739
+ }, [
740
+ initData
741
+ ]);
742
+ (0, import_react.useImperativeHandle)(ref, function() {
743
+ return webviewRef.current;
744
+ }, []);
745
+ var handleMessage = /*#__PURE__*/ function() {
746
+ var _ref = _async_to_generator(function(event) {
747
+ 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;
748
+ return _ts_generator(this, function(_state) {
749
+ (_props_onMessage = props.onMessage) === null || _props_onMessage === void 0 ? void 0 : _props_onMessage.call(props, event);
750
+ if (!webviewRef.current) {
751
+ return [
752
+ 2
753
+ ];
754
+ }
755
+ _JSON_parse = JSON.parse(event.nativeEvent.data), type = _JSON_parse.type, body = _JSON_parse.body;
756
+ switch(type){
757
+ case "log":
758
+ {
759
+ method = body.method, args = body.args;
760
+ debug && handleLog(method, args);
761
+ return [
762
+ 2
763
+ ];
764
+ }
765
+ case "bridge":
766
+ {
767
+ method1 = body.method, args1 = body.args, eventId = body.eventId;
768
+ handleBridge({
769
+ bridge: bridge2,
770
+ method: method1,
771
+ args: args1,
772
+ eventId: eventId,
773
+ webview: webviewRef.current
774
+ });
775
+ return [
776
+ 2
777
+ ];
778
+ }
779
+ case "getBridgeState":
780
+ {
781
+ _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
782
+ try {
783
+ for(_iterator = webviewRefList[Symbol.iterator](); !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
784
+ ref2 = _step.value;
785
+ ;
786
+ 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()));
787
+ }
788
+ } catch (err) {
789
+ _didIteratorError = true;
790
+ _iteratorError = err;
791
+ } finally{
792
+ try {
793
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
794
+ _iterator.return();
795
+ }
796
+ } finally{
797
+ if (_didIteratorError) {
798
+ throw _iteratorError;
799
+ }
800
+ }
801
+ }
802
+ return [
803
+ 2
804
+ ];
805
+ }
806
+ case "registerWebMethod":
807
+ {
808
+ bridgeNames = body.bridgeNames;
809
+ Object.assign(WebMethod.current, handleRegisterWebMethod(emitter, webviewRef.current, bridgeNames, responseTimeout));
810
+ WebMethod.current.isReady = true;
811
+ return [
812
+ 2
813
+ ];
814
+ }
815
+ case "webMethodResponse":
816
+ {
817
+ eventId1 = body.eventId, funcName = body.funcName, value = body.value;
818
+ emitter.emit("".concat(funcName, "-").concat(eventId1), value);
819
+ return [
820
+ 2
821
+ ];
822
+ }
823
+ case "webMethodError":
824
+ {
825
+ eventId2 = body.eventId, funcName1 = body.funcName;
826
+ emitter.emit("".concat(funcName1, "-").concat(eventId2), {}, true);
827
+ return [
828
+ 2
829
+ ];
830
+ }
831
+ case "fallback":
832
+ {
833
+ method2 = body.method;
834
+ fallback === null || fallback === void 0 ? void 0 : fallback(method2);
835
+ return [
836
+ 2
837
+ ];
838
+ }
839
+ }
840
+ return [
841
+ 2
842
+ ];
843
+ });
844
+ });
845
+ return function handleMessage(event) {
846
+ return _ref.apply(this, arguments);
847
+ };
848
+ }();
849
+ return /* @__PURE__ */ import_react.default.createElement(import_react_native_webview.default, _object_spread_props(_object_spread({}, props), {
850
+ ref: webviewRef,
851
+ onMessage: handleMessage,
852
+ injectedJavaScriptBeforeContentLoaded: [
853
+ INJECT_BRIDGE_METHODS(initData.bridgeMethods),
854
+ INJECT_BRIDGE_STATE(initData.initialState),
855
+ props.injectedJavaScriptBeforeContentLoaded,
856
+ "true;"
857
+ ].filter(Boolean).join("\n"),
858
+ injectedJavaScript: [
859
+ debug && INJECT_DEBUG,
860
+ props.injectedJavaScript,
861
+ "true;"
862
+ ].filter(Boolean).join("\n")
863
+ }));
864
+ }),
865
+ /**
866
+ * @deprecated Use `postMessage` instead. And complete the type through the `postMessageSchema` option.
867
+ * @see https://gronxb.github.io/webview-bridge/using-a-post-message.html
868
+ * @example
869
+ import { createWebView, postMessageSchema } from "@webview-bridge/react-native";
870
+ import { z } from "zod";
871
+
872
+ const appPostMessageSchema = postMessageSchema({
873
+ eventName1: z.object({
874
+ message: z.string(),
875
+ }),
876
+ eventName2: z.string(),
877
+ });
878
+
879
+
880
+ // Export the event schema to be used in the web application
881
+ export type AppPostMessageSchema = typeof appPostMessageSchema;
882
+
883
+ // When you bridge a webview, a postMessage is extracted.
884
+ export const { postMessage } = createWebView({
885
+ 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.
886
+ // ..
887
+ });
888
+
889
+ // usage
890
+ postMessage("eventName1", {
891
+ message: "test",
892
+ });
893
+ postMessage("eventName2", "test");
894
+ */ linkWebMethod: function linkWebMethod() {
895
+ return WebMethod;
896
+ }
897
+ };
898
+ };
899
+ // src/integrations/postMessageSchema.ts
900
+ var postMessageSchema = function(schema) {
901
+ return schema;
902
+ };
903
+ // src/useBridge.ts
904
+ var import_with_selector = require("use-sync-external-store/with-selector.js");
905
+ function useBridge(store, selector) {
906
+ var $selector = selector !== null && selector !== void 0 ? selector : function(state) {
907
+ return state;
908
+ };
909
+ return (0, import_with_selector.useSyncExternalStoreWithSelector)(store.subscribe, store.getState, store.getState, $selector);
910
+ }
911
+ // Annotate the CommonJS export names for ESM import in node:
912
+ 0 && (module.exports = {
913
+ INJECT_BRIDGE_METHODS: INJECT_BRIDGE_METHODS,
914
+ INJECT_BRIDGE_STATE: INJECT_BRIDGE_STATE,
915
+ SAFE_NATIVE_EMITTER_EMIT: SAFE_NATIVE_EMITTER_EMIT,
916
+ SAFE_NATIVE_EMITTER_THROW: SAFE_NATIVE_EMITTER_THROW,
917
+ bridge: bridge,
918
+ createWebView: createWebView,
919
+ handleBridge: handleBridge,
920
+ postMessageSchema: postMessageSchema,
921
+ useBridge: useBridge
922
+ });