iframe-link 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,994 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __commonJS = (cb, mod) => function __require() {
9
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
+ };
11
+ var __export = (target, all) => {
12
+ for (var name in all)
13
+ __defProp(target, name, { get: all[name], enumerable: true });
14
+ };
15
+ var __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from === "object" || typeof from === "function") {
17
+ for (let key of __getOwnPropNames(from))
18
+ if (!__hasOwnProp.call(to, key) && key !== except)
19
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
+ // If the importer is in node compatibility mode or this is not an ESM
25
+ // file that has been converted to a CommonJS file using a Babel-
26
+ // compatible transform (i.e. "__esModule" has not been set), then set
27
+ // "default" to the CommonJS "module.exports" for node compatibility.
28
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
+ mod
30
+ ));
31
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
+ var __async = (__this, __arguments, generator) => {
33
+ return new Promise((resolve, reject) => {
34
+ var fulfilled = (value) => {
35
+ try {
36
+ step(generator.next(value));
37
+ } catch (e) {
38
+ reject(e);
39
+ }
40
+ };
41
+ var rejected = (value) => {
42
+ try {
43
+ step(generator.throw(value));
44
+ } catch (e) {
45
+ reject(e);
46
+ }
47
+ };
48
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
49
+ step((generator = generator.apply(__this, __arguments)).next());
50
+ });
51
+ };
52
+
53
+ // node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js
54
+ var require_ms = __commonJS({
55
+ "node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js"(exports, module2) {
56
+ "use strict";
57
+ var s = 1e3;
58
+ var m = s * 60;
59
+ var h = m * 60;
60
+ var d = h * 24;
61
+ var w = d * 7;
62
+ var y = d * 365.25;
63
+ module2.exports = function(val, options) {
64
+ options = options || {};
65
+ var type = typeof val;
66
+ if (type === "string" && val.length > 0) {
67
+ return parse(val);
68
+ } else if (type === "number" && isFinite(val)) {
69
+ return options.long ? fmtLong(val) : fmtShort(val);
70
+ }
71
+ throw new Error(
72
+ "val is not a non-empty string or a valid number. val=" + JSON.stringify(val)
73
+ );
74
+ };
75
+ function parse(str) {
76
+ str = String(str);
77
+ if (str.length > 100) {
78
+ return;
79
+ }
80
+ var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
81
+ str
82
+ );
83
+ if (!match) {
84
+ return;
85
+ }
86
+ var n = parseFloat(match[1]);
87
+ var type = (match[2] || "ms").toLowerCase();
88
+ switch (type) {
89
+ case "years":
90
+ case "year":
91
+ case "yrs":
92
+ case "yr":
93
+ case "y":
94
+ return n * y;
95
+ case "weeks":
96
+ case "week":
97
+ case "w":
98
+ return n * w;
99
+ case "days":
100
+ case "day":
101
+ case "d":
102
+ return n * d;
103
+ case "hours":
104
+ case "hour":
105
+ case "hrs":
106
+ case "hr":
107
+ case "h":
108
+ return n * h;
109
+ case "minutes":
110
+ case "minute":
111
+ case "mins":
112
+ case "min":
113
+ case "m":
114
+ return n * m;
115
+ case "seconds":
116
+ case "second":
117
+ case "secs":
118
+ case "sec":
119
+ case "s":
120
+ return n * s;
121
+ case "milliseconds":
122
+ case "millisecond":
123
+ case "msecs":
124
+ case "msec":
125
+ case "ms":
126
+ return n;
127
+ default:
128
+ return void 0;
129
+ }
130
+ }
131
+ function fmtShort(ms) {
132
+ var msAbs = Math.abs(ms);
133
+ if (msAbs >= d) {
134
+ return Math.round(ms / d) + "d";
135
+ }
136
+ if (msAbs >= h) {
137
+ return Math.round(ms / h) + "h";
138
+ }
139
+ if (msAbs >= m) {
140
+ return Math.round(ms / m) + "m";
141
+ }
142
+ if (msAbs >= s) {
143
+ return Math.round(ms / s) + "s";
144
+ }
145
+ return ms + "ms";
146
+ }
147
+ function fmtLong(ms) {
148
+ var msAbs = Math.abs(ms);
149
+ if (msAbs >= d) {
150
+ return plural(ms, msAbs, d, "day");
151
+ }
152
+ if (msAbs >= h) {
153
+ return plural(ms, msAbs, h, "hour");
154
+ }
155
+ if (msAbs >= m) {
156
+ return plural(ms, msAbs, m, "minute");
157
+ }
158
+ if (msAbs >= s) {
159
+ return plural(ms, msAbs, s, "second");
160
+ }
161
+ return ms + " ms";
162
+ }
163
+ function plural(ms, msAbs, n, name) {
164
+ var isPlural = msAbs >= n * 1.5;
165
+ return Math.round(ms / n) + " " + name + (isPlural ? "s" : "");
166
+ }
167
+ }
168
+ });
169
+
170
+ // node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/common.js
171
+ var require_common = __commonJS({
172
+ "node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/common.js"(exports, module2) {
173
+ "use strict";
174
+ function setup(env) {
175
+ createDebug2.debug = createDebug2;
176
+ createDebug2.default = createDebug2;
177
+ createDebug2.coerce = coerce;
178
+ createDebug2.disable = disable;
179
+ createDebug2.enable = enable;
180
+ createDebug2.enabled = enabled;
181
+ createDebug2.humanize = require_ms();
182
+ createDebug2.destroy = destroy;
183
+ Object.keys(env).forEach((key) => {
184
+ createDebug2[key] = env[key];
185
+ });
186
+ createDebug2.names = [];
187
+ createDebug2.skips = [];
188
+ createDebug2.formatters = {};
189
+ function selectColor(namespace) {
190
+ let hash = 0;
191
+ for (let i = 0; i < namespace.length; i++) {
192
+ hash = (hash << 5) - hash + namespace.charCodeAt(i);
193
+ hash |= 0;
194
+ }
195
+ return createDebug2.colors[Math.abs(hash) % createDebug2.colors.length];
196
+ }
197
+ createDebug2.selectColor = selectColor;
198
+ function createDebug2(namespace) {
199
+ let prevTime;
200
+ let enableOverride = null;
201
+ let namespacesCache;
202
+ let enabledCache;
203
+ function debug(...args) {
204
+ if (!debug.enabled) {
205
+ return;
206
+ }
207
+ const self = debug;
208
+ const curr = Number(/* @__PURE__ */ new Date());
209
+ const ms = curr - (prevTime || curr);
210
+ self.diff = ms;
211
+ self.prev = prevTime;
212
+ self.curr = curr;
213
+ prevTime = curr;
214
+ args[0] = createDebug2.coerce(args[0]);
215
+ if (typeof args[0] !== "string") {
216
+ args.unshift("%O");
217
+ }
218
+ let index = 0;
219
+ args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
220
+ if (match === "%%") {
221
+ return "%";
222
+ }
223
+ index++;
224
+ const formatter = createDebug2.formatters[format];
225
+ if (typeof formatter === "function") {
226
+ const val = args[index];
227
+ match = formatter.call(self, val);
228
+ args.splice(index, 1);
229
+ index--;
230
+ }
231
+ return match;
232
+ });
233
+ createDebug2.formatArgs.call(self, args);
234
+ const logFn = self.log || createDebug2.log;
235
+ logFn.apply(self, args);
236
+ }
237
+ debug.namespace = namespace;
238
+ debug.useColors = createDebug2.useColors();
239
+ debug.color = createDebug2.selectColor(namespace);
240
+ debug.extend = extend;
241
+ debug.destroy = createDebug2.destroy;
242
+ Object.defineProperty(debug, "enabled", {
243
+ enumerable: true,
244
+ configurable: false,
245
+ get: () => {
246
+ if (enableOverride !== null) {
247
+ return enableOverride;
248
+ }
249
+ if (namespacesCache !== createDebug2.namespaces) {
250
+ namespacesCache = createDebug2.namespaces;
251
+ enabledCache = createDebug2.enabled(namespace);
252
+ }
253
+ return enabledCache;
254
+ },
255
+ set: (v) => {
256
+ enableOverride = v;
257
+ }
258
+ });
259
+ if (typeof createDebug2.init === "function") {
260
+ createDebug2.init(debug);
261
+ }
262
+ return debug;
263
+ }
264
+ function extend(namespace, delimiter) {
265
+ const newDebug = createDebug2(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace);
266
+ newDebug.log = this.log;
267
+ return newDebug;
268
+ }
269
+ function enable(namespaces) {
270
+ createDebug2.save(namespaces);
271
+ createDebug2.namespaces = namespaces;
272
+ createDebug2.names = [];
273
+ createDebug2.skips = [];
274
+ const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean);
275
+ for (const ns of split) {
276
+ if (ns[0] === "-") {
277
+ createDebug2.skips.push(ns.slice(1));
278
+ } else {
279
+ createDebug2.names.push(ns);
280
+ }
281
+ }
282
+ }
283
+ function matchesTemplate(search, template) {
284
+ let searchIndex = 0;
285
+ let templateIndex = 0;
286
+ let starIndex = -1;
287
+ let matchIndex = 0;
288
+ while (searchIndex < search.length) {
289
+ if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) {
290
+ if (template[templateIndex] === "*") {
291
+ starIndex = templateIndex;
292
+ matchIndex = searchIndex;
293
+ templateIndex++;
294
+ } else {
295
+ searchIndex++;
296
+ templateIndex++;
297
+ }
298
+ } else if (starIndex !== -1) {
299
+ templateIndex = starIndex + 1;
300
+ matchIndex++;
301
+ searchIndex = matchIndex;
302
+ } else {
303
+ return false;
304
+ }
305
+ }
306
+ while (templateIndex < template.length && template[templateIndex] === "*") {
307
+ templateIndex++;
308
+ }
309
+ return templateIndex === template.length;
310
+ }
311
+ function disable() {
312
+ const namespaces = [
313
+ ...createDebug2.names,
314
+ ...createDebug2.skips.map((namespace) => "-" + namespace)
315
+ ].join(",");
316
+ createDebug2.enable("");
317
+ return namespaces;
318
+ }
319
+ function enabled(name) {
320
+ for (const skip of createDebug2.skips) {
321
+ if (matchesTemplate(name, skip)) {
322
+ return false;
323
+ }
324
+ }
325
+ for (const ns of createDebug2.names) {
326
+ if (matchesTemplate(name, ns)) {
327
+ return true;
328
+ }
329
+ }
330
+ return false;
331
+ }
332
+ function coerce(val) {
333
+ if (val instanceof Error) {
334
+ return val.stack || val.message;
335
+ }
336
+ return val;
337
+ }
338
+ function destroy() {
339
+ console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
340
+ }
341
+ createDebug2.enable(createDebug2.load());
342
+ return createDebug2;
343
+ }
344
+ module2.exports = setup;
345
+ }
346
+ });
347
+
348
+ // node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/browser.js
349
+ var require_browser = __commonJS({
350
+ "node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/browser.js"(exports, module2) {
351
+ "use strict";
352
+ exports.formatArgs = formatArgs;
353
+ exports.save = save;
354
+ exports.load = load;
355
+ exports.useColors = useColors;
356
+ exports.storage = localstorage();
357
+ exports.destroy = /* @__PURE__ */ (() => {
358
+ let warned = false;
359
+ return () => {
360
+ if (!warned) {
361
+ warned = true;
362
+ console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
363
+ }
364
+ };
365
+ })();
366
+ exports.colors = [
367
+ "#0000CC",
368
+ "#0000FF",
369
+ "#0033CC",
370
+ "#0033FF",
371
+ "#0066CC",
372
+ "#0066FF",
373
+ "#0099CC",
374
+ "#0099FF",
375
+ "#00CC00",
376
+ "#00CC33",
377
+ "#00CC66",
378
+ "#00CC99",
379
+ "#00CCCC",
380
+ "#00CCFF",
381
+ "#3300CC",
382
+ "#3300FF",
383
+ "#3333CC",
384
+ "#3333FF",
385
+ "#3366CC",
386
+ "#3366FF",
387
+ "#3399CC",
388
+ "#3399FF",
389
+ "#33CC00",
390
+ "#33CC33",
391
+ "#33CC66",
392
+ "#33CC99",
393
+ "#33CCCC",
394
+ "#33CCFF",
395
+ "#6600CC",
396
+ "#6600FF",
397
+ "#6633CC",
398
+ "#6633FF",
399
+ "#66CC00",
400
+ "#66CC33",
401
+ "#9900CC",
402
+ "#9900FF",
403
+ "#9933CC",
404
+ "#9933FF",
405
+ "#99CC00",
406
+ "#99CC33",
407
+ "#CC0000",
408
+ "#CC0033",
409
+ "#CC0066",
410
+ "#CC0099",
411
+ "#CC00CC",
412
+ "#CC00FF",
413
+ "#CC3300",
414
+ "#CC3333",
415
+ "#CC3366",
416
+ "#CC3399",
417
+ "#CC33CC",
418
+ "#CC33FF",
419
+ "#CC6600",
420
+ "#CC6633",
421
+ "#CC9900",
422
+ "#CC9933",
423
+ "#CCCC00",
424
+ "#CCCC33",
425
+ "#FF0000",
426
+ "#FF0033",
427
+ "#FF0066",
428
+ "#FF0099",
429
+ "#FF00CC",
430
+ "#FF00FF",
431
+ "#FF3300",
432
+ "#FF3333",
433
+ "#FF3366",
434
+ "#FF3399",
435
+ "#FF33CC",
436
+ "#FF33FF",
437
+ "#FF6600",
438
+ "#FF6633",
439
+ "#FF9900",
440
+ "#FF9933",
441
+ "#FFCC00",
442
+ "#FFCC33"
443
+ ];
444
+ function useColors() {
445
+ if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) {
446
+ return true;
447
+ }
448
+ if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
449
+ return false;
450
+ }
451
+ let m;
452
+ return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
453
+ typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
454
+ // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
455
+ typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
456
+ typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
457
+ }
458
+ function formatArgs(args) {
459
+ args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module2.exports.humanize(this.diff);
460
+ if (!this.useColors) {
461
+ return;
462
+ }
463
+ const c = "color: " + this.color;
464
+ args.splice(1, 0, c, "color: inherit");
465
+ let index = 0;
466
+ let lastC = 0;
467
+ args[0].replace(/%[a-zA-Z%]/g, (match) => {
468
+ if (match === "%%") {
469
+ return;
470
+ }
471
+ index++;
472
+ if (match === "%c") {
473
+ lastC = index;
474
+ }
475
+ });
476
+ args.splice(lastC, 0, c);
477
+ }
478
+ exports.log = console.debug || console.log || (() => {
479
+ });
480
+ function save(namespaces) {
481
+ try {
482
+ if (namespaces) {
483
+ exports.storage.setItem("debug", namespaces);
484
+ } else {
485
+ exports.storage.removeItem("debug");
486
+ }
487
+ } catch (error) {
488
+ }
489
+ }
490
+ function load() {
491
+ let r;
492
+ try {
493
+ r = exports.storage.getItem("debug") || exports.storage.getItem("DEBUG");
494
+ } catch (error) {
495
+ }
496
+ if (!r && typeof process !== "undefined" && "env" in process) {
497
+ r = process.env.DEBUG;
498
+ }
499
+ return r;
500
+ }
501
+ function localstorage() {
502
+ try {
503
+ return localStorage;
504
+ } catch (error) {
505
+ }
506
+ }
507
+ module2.exports = require_common()(exports);
508
+ var { formatters } = module2.exports;
509
+ formatters.j = function(v) {
510
+ try {
511
+ return JSON.stringify(v);
512
+ } catch (error) {
513
+ return "[UnexpectedJSONParseError]: " + error.message;
514
+ }
515
+ };
516
+ }
517
+ });
518
+
519
+ // src/index.ts
520
+ var index_exports = {};
521
+ __export(index_exports, {
522
+ DEFAULT_ALLOWED_ORIGIN: () => DEFAULT_ALLOWED_ORIGIN,
523
+ SDK_MESSAGE_TYPES: () => SDK_MESSAGE_TYPES,
524
+ connectToIframe: () => connectToIframe,
525
+ connectToParent: () => connectToParent
526
+ });
527
+ module.exports = __toCommonJS(index_exports);
528
+
529
+ // src/types.ts
530
+ var SDK_MESSAGE_TYPES = ["READY", "ACK", "CALL", "RESULT", "EVENT"];
531
+ var DEFAULT_ALLOWED_ORIGIN = /^https:\/\/oa\.example\.com$/;
532
+
533
+ // src/utils.ts
534
+ var import_debug = __toESM(require_browser(), 1);
535
+ var NAMESPACE = "iframe-link";
536
+ var log = {
537
+ bridge: (0, import_debug.default)(`${NAMESPACE}:bridge`),
538
+ channel: (0, import_debug.default)(`${NAMESPACE}:channel`),
539
+ rpc: (0, import_debug.default)(`${NAMESPACE}:rpc`),
540
+ event: (0, import_debug.default)(`${NAMESPACE}:event`),
541
+ utils: (0, import_debug.default)(`${NAMESPACE}:utils`)
542
+ };
543
+ function enableDebug() {
544
+ import_debug.default.enable(`${NAMESPACE}:*`);
545
+ }
546
+ function isTrustedOrigin(origin, allowed) {
547
+ const result = allowed.some((pattern) => {
548
+ if (pattern === "*") return true;
549
+ if (pattern instanceof RegExp) {
550
+ const matcher = pattern.global || pattern.sticky ? new RegExp(pattern.source, pattern.flags) : pattern;
551
+ return matcher.test(origin);
552
+ }
553
+ return pattern === origin;
554
+ });
555
+ log.utils("isTrustedOrigin: %s -> %s %O", origin, result ? "\u2713" : "\u2717", allowed.map((p) => p.toString()));
556
+ return result;
557
+ }
558
+ function uuid() {
559
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
560
+ return crypto.randomUUID();
561
+ }
562
+ return Date.now().toString(36) + "-" + Math.random().toString(36).slice(2);
563
+ }
564
+ var RPC = class {
565
+ constructor(messenger, methods) {
566
+ this.messenger = messenger;
567
+ this.methods = methods;
568
+ this.destroyed = false;
569
+ this.pending = /* @__PURE__ */ new Map();
570
+ log.rpc("\u521B\u5EFA RPC \u7BA1\u7406\u5668, methods: %O", Object.keys(methods));
571
+ }
572
+ call(name, params) {
573
+ if (this.destroyed) return Promise.reject(new Error("Destroyed"));
574
+ return new Promise((resolve, reject) => {
575
+ const id = uuid();
576
+ log.rpc("\u53D1\u8D77\u8C03\u7528: %s, id=%s, params=%O", name, id, params);
577
+ this.pending.set(id, { resolve, reject });
578
+ try {
579
+ this.messenger.send({ type: "CALL", id, method: name, params });
580
+ } catch (error) {
581
+ this.pending.delete(id);
582
+ reject(error);
583
+ }
584
+ });
585
+ }
586
+ execute(id, name, params) {
587
+ return __async(this, null, function* () {
588
+ log.rpc("\u6267\u884C\u65B9\u6CD5: %s, id=%s, params=%O", name, id, params);
589
+ if (!Object.prototype.hasOwnProperty.call(this.methods, name)) {
590
+ log.rpc("\u65B9\u6CD5\u4E0D\u5B58\u5728: %s", name);
591
+ this.messenger.send({ type: "RESULT", id, error: `Method not found: ${name}` });
592
+ return;
593
+ }
594
+ try {
595
+ const result = yield this.methods[name](params);
596
+ log.rpc("\u2713 \u65B9\u6CD5\u6267\u884C\u6210\u529F: %s, result=%O", name, result);
597
+ this.messenger.send({ type: "RESULT", id, result });
598
+ } catch (error) {
599
+ const message = error instanceof Error ? error.message : String(error);
600
+ log.rpc("\u2717 \u65B9\u6CD5\u6267\u884C\u5931\u8D25: %s, error=%s", name, message);
601
+ this.messenger.send({ type: "RESULT", id, error: message });
602
+ }
603
+ });
604
+ }
605
+ resolve(id, result, error) {
606
+ const p = this.pending.get(id);
607
+ if (!p) {
608
+ log.rpc("\u672A\u627E\u5230\u5F85\u5904\u7406\u7684\u8C03\u7528: %s", id);
609
+ return;
610
+ }
611
+ this.pending.delete(id);
612
+ if (error !== void 0) {
613
+ log.rpc("\u8C03\u7528\u8FD4\u56DE\u9519\u8BEF: id=%s, error=%s", id, error);
614
+ p.reject(new Error(error));
615
+ } else {
616
+ log.rpc("\u8C03\u7528\u8FD4\u56DE\u6210\u529F: id=%s, result=%O", id, result);
617
+ p.resolve(result);
618
+ }
619
+ }
620
+ cleanup() {
621
+ this.destroyed = true;
622
+ log.rpc("\u6E05\u7406 RPC, pending=%d", this.pending.size);
623
+ this.pending.forEach(({ reject }) => reject(new Error("Destroyed")));
624
+ this.pending.clear();
625
+ }
626
+ };
627
+ function createRPC(messenger, methods) {
628
+ return new RPC(messenger, methods);
629
+ }
630
+ function createEvent(messenger) {
631
+ const handlers = /* @__PURE__ */ new Map();
632
+ return {
633
+ on: (type, fn) => {
634
+ if (!handlers.has(type)) handlers.set(type, /* @__PURE__ */ new Set());
635
+ handlers.get(type).add(fn);
636
+ log.event("\u8BA2\u9605\u4E8B\u4EF6: %s, handlers=%d", type, handlers.get(type).size);
637
+ },
638
+ off: (type, fn) => {
639
+ var _a;
640
+ (_a = handlers.get(type)) == null ? void 0 : _a.delete(fn);
641
+ log.event("\u53D6\u6D88\u8BA2\u9605: %s", type);
642
+ },
643
+ emit: (type, data) => {
644
+ log.event("\u53D1\u9001\u4E8B\u4EF6: %s, data=%O", type, data);
645
+ messenger.send({ type: "EVENT", eventType: type, data });
646
+ },
647
+ dispatch: (type, data) => {
648
+ const set = handlers.get(type);
649
+ const count = set ? set.size : 0;
650
+ log.event("\u5206\u53D1\u4E8B\u4EF6: %s, handlers=%d, data=%O", type, count, data);
651
+ if (set) set.forEach((fn) => fn(data));
652
+ },
653
+ cleanup: () => {
654
+ log.event("\u6E05\u7406\u4E8B\u4EF6\u7CFB\u7EDF");
655
+ handlers.clear();
656
+ }
657
+ };
658
+ }
659
+
660
+ // src/channelBridge.ts
661
+ function isValidMessage(data) {
662
+ const valid = data && typeof data === "object" && (data.type || data.action);
663
+ if (!valid && data) {
664
+ log.bridge("\u65E0\u6548\u6D88\u606F\u683C\u5F0F: %O", data);
665
+ }
666
+ return valid;
667
+ }
668
+ function cleanMessage(message) {
669
+ return JSON.parse(JSON.stringify(message));
670
+ }
671
+ function createMessenger(options) {
672
+ return options.isChild ? createChildMessenger(options.allowedOrigins) : createParentMessenger(options.iframe, options.origin);
673
+ }
674
+ function createParentMessenger(iframe, childOrigin) {
675
+ let onMessage;
676
+ let destroyed = false;
677
+ log.bridge("[Parent] \u521B\u5EFA\u901A\u4FE1\u5668, origin=%s, iframe=%s", childOrigin, (iframe == null ? void 0 : iframe.id) || (iframe == null ? void 0 : iframe.src));
678
+ const handleMessageEvent = (event) => {
679
+ log.bridge(
680
+ "[Parent] \u6536\u5230\u6D88\u606F: origin=%s, expected=%s, sourceMatch=%s, data=%O",
681
+ event.origin,
682
+ childOrigin,
683
+ event.source === iframe.contentWindow,
684
+ event.data
685
+ );
686
+ if (destroyed || !onMessage) {
687
+ log.bridge("[Parent] \u8DF3\u8FC7: destroyed=%s, hasHandler=%s", destroyed, !!onMessage);
688
+ return;
689
+ }
690
+ if (event.origin !== childOrigin) {
691
+ log.bridge("[Parent] origin \u4E0D\u5339\u914D: %s !== %s", event.origin, childOrigin);
692
+ return;
693
+ }
694
+ if (event.source !== iframe.contentWindow) {
695
+ log.bridge("[Parent] source \u4E0D\u662F\u76EE\u6807 iframe");
696
+ return;
697
+ }
698
+ if (!isValidMessage(event.data)) {
699
+ return;
700
+ }
701
+ log.bridge("[Parent] \u2713 \u6D88\u606F\u9A8C\u8BC1\u901A\u8FC7: %O", event.data);
702
+ onMessage(event.data);
703
+ };
704
+ const send = (message) => {
705
+ log.bridge("[Parent] \u53D1\u9001: %O -> %s", message, childOrigin);
706
+ if (destroyed) return;
707
+ if (!iframe.contentWindow) throw new Error("Iframe not available");
708
+ try {
709
+ iframe.contentWindow.postMessage(cleanMessage(message), childOrigin);
710
+ log.bridge("[Parent] \u2713 \u5DF2\u53D1\u9001: %s", message.type);
711
+ } catch (e) {
712
+ log.bridge("[Parent] \u2717 \u53D1\u9001\u5F02\u5E38: %O", e);
713
+ throw e;
714
+ }
715
+ };
716
+ return {
717
+ isChild: false,
718
+ init: (handler) => {
719
+ log.bridge("[Parent] \u5F00\u59CB\u76D1\u542C message \u4E8B\u4EF6");
720
+ onMessage = handler;
721
+ window.addEventListener("message", handleMessageEvent);
722
+ },
723
+ send,
724
+ destroy: () => {
725
+ log.bridge("[Parent] \u9500\u6BC1\u901A\u4FE1\u5668");
726
+ if (destroyed) return;
727
+ window.removeEventListener("message", handleMessageEvent);
728
+ onMessage = void 0;
729
+ destroyed = true;
730
+ }
731
+ };
732
+ }
733
+ function createChildMessenger(allowedOrigins) {
734
+ let onMessage;
735
+ let destroyed = false;
736
+ let parentOrigin;
737
+ log.bridge(
738
+ "[Child] \u521B\u5EFA\u901A\u4FE1\u5668, allowed=%O, inIframe=%s, origin=%s",
739
+ allowedOrigins.map((o) => o.toString()),
740
+ window !== window.parent,
741
+ window.location.origin
742
+ );
743
+ const handleMessageEvent = (event) => {
744
+ log.bridge(
745
+ "[Child] \u6536\u5230\u6D88\u606F: origin=%s, parentOrigin=%s, data=%O",
746
+ event.origin,
747
+ parentOrigin,
748
+ event.data
749
+ );
750
+ if (destroyed || !onMessage) {
751
+ log.bridge("[Child] \u8DF3\u8FC7: destroyed=%s, hasHandler=%s", destroyed, !!onMessage);
752
+ return;
753
+ }
754
+ if (event.source !== window.parent) {
755
+ log.bridge("[Child] source \u4E0D\u662F\u7236\u7A97\u53E3");
756
+ return;
757
+ }
758
+ const trusted = isTrustedOrigin(event.origin, allowedOrigins);
759
+ if (!trusted) {
760
+ log.bridge("[Child] origin \u4E0D\u53EF\u4FE1: %s", event.origin);
761
+ return;
762
+ }
763
+ if (!isValidMessage(event.data)) {
764
+ return;
765
+ }
766
+ if (!parentOrigin) {
767
+ parentOrigin = event.origin;
768
+ log.bridge("[Child] \u8BB0\u5F55\u7236\u7A97\u53E3 origin: %s", parentOrigin);
769
+ }
770
+ log.bridge("[Child] \u2713 \u6D88\u606F\u9A8C\u8BC1\u901A\u8FC7: %O", event.data);
771
+ onMessage(event.data);
772
+ };
773
+ const send = (message) => {
774
+ if (message.type !== "READY" && !parentOrigin) return;
775
+ const targetOrigin = message.type === "READY" ? "*" : parentOrigin;
776
+ log.bridge("[Child] \u53D1\u9001: %O -> %s", message, targetOrigin);
777
+ if (destroyed || !window.parent) {
778
+ log.bridge("[Child] \u53D1\u9001\u5931\u8D25: destroyed=%s, hasParent=%s", destroyed, window.parent !== window);
779
+ return;
780
+ }
781
+ try {
782
+ window.parent.postMessage(cleanMessage(message), targetOrigin);
783
+ log.bridge("[Child] \u2713 \u5DF2\u53D1\u9001: %s", message.type);
784
+ } catch (e) {
785
+ log.bridge("[Child] \u2717 \u53D1\u9001\u5F02\u5E38: %O", e);
786
+ throw e;
787
+ }
788
+ };
789
+ return {
790
+ isChild: true,
791
+ init: (handler) => {
792
+ log.bridge("[Child] \u5F00\u59CB\u76D1\u542C message \u4E8B\u4EF6");
793
+ onMessage = handler;
794
+ window.addEventListener("message", handleMessageEvent);
795
+ },
796
+ send,
797
+ destroy: () => {
798
+ log.bridge("[Child] \u9500\u6BC1\u901A\u4FE1\u5668");
799
+ if (destroyed) return;
800
+ window.removeEventListener("message", handleMessageEvent);
801
+ onMessage = void 0;
802
+ destroyed = true;
803
+ }
804
+ };
805
+ }
806
+
807
+ // src/channelConnect.ts
808
+ function isSDKMessage(message) {
809
+ return message && typeof message === "object" && "type" in message && SDK_MESSAGE_TYPES.includes(message.type);
810
+ }
811
+ function isNativeMessage(message) {
812
+ return message && typeof message === "object" && "action" in message && !isSDKMessage(message) && !("success" in message);
813
+ }
814
+ function createChannel(options) {
815
+ const { messenger, methods = {}, debug = false } = options;
816
+ const role = messenger.isChild ? "Child" : "Parent";
817
+ if (debug) {
818
+ enableDebug();
819
+ }
820
+ log.channel("[%s] \u521B\u5EFA\u901A\u4FE1\u901A\u9053, methods=%O", role, Object.keys(methods));
821
+ const rpc = createRPC(messenger, methods);
822
+ const event = createEvent(messenger);
823
+ let resolveHandshake;
824
+ const handshakePromise = new Promise((resolve) => {
825
+ resolveHandshake = resolve;
826
+ });
827
+ messenger.init(handleMessage);
828
+ log.channel("[%s] \u6D88\u606F\u76D1\u542C\u5DF2\u521D\u59CB\u5316", role);
829
+ const RETRY_INTERVAL = 1e3;
830
+ const MAX_RETRIES = 5;
831
+ let retryCount = 0;
832
+ let retryTimer = null;
833
+ if (messenger.isChild) {
834
+ const sendReady = () => {
835
+ retryCount++;
836
+ log.channel("[%s] \u53D1\u9001 READY (%d/%d)", role, retryCount, MAX_RETRIES);
837
+ messenger.send({ type: "READY" });
838
+ if (retryCount >= MAX_RETRIES) {
839
+ if (retryTimer) {
840
+ clearInterval(retryTimer);
841
+ retryTimer = null;
842
+ }
843
+ log.channel("[%s] \u2717 \u63E1\u624B\u8D85\u65F6\uFF0C\u5DF2\u91CD\u8BD5 %d \u6B21", role, MAX_RETRIES);
844
+ }
845
+ };
846
+ sendReady();
847
+ retryTimer = setInterval(sendReady, RETRY_INTERVAL);
848
+ } else {
849
+ log.channel("[%s] \u7B49\u5F85\u5B50\u5E94\u7528 READY", role);
850
+ }
851
+ function createNativeResponse(action, requestId, result, error) {
852
+ return {
853
+ type: "__NATIVE_RESPONSE__",
854
+ action,
855
+ requestId,
856
+ success: error === void 0,
857
+ result,
858
+ error
859
+ };
860
+ }
861
+ function handleMessage(message) {
862
+ log.channel("[%s] handleMessage: %O", role, message);
863
+ if (isSDKMessage(message)) {
864
+ handleSDKMessage(message);
865
+ } else if (isNativeMessage(message)) {
866
+ handleNativeMessage(message).catch((error) => {
867
+ log.channel("[%s] Native \u54CD\u5E94\u53D1\u9001\u5931\u8D25: %O", role, error);
868
+ });
869
+ } else {
870
+ log.channel("[%s] \u672A\u77E5\u6D88\u606F\u7C7B\u578B\uFF0C\u5FFD\u7565", role);
871
+ }
872
+ }
873
+ function handleSDKMessage(message) {
874
+ log.channel("[%s] SDK \u6D88\u606F: %s %O", role, message.type, message);
875
+ switch (message.type) {
876
+ case "READY":
877
+ if (!messenger.isChild) {
878
+ log.channel("[%s] \u6536\u5230 READY\uFF0C\u56DE\u590D ACK", role);
879
+ messenger.send({ type: "ACK" });
880
+ finishHandshake();
881
+ }
882
+ break;
883
+ case "ACK":
884
+ if (messenger.isChild) {
885
+ log.channel("[%s] \u6536\u5230 ACK\uFF0C\u63E1\u624B\u5B8C\u6210", role);
886
+ finishHandshake();
887
+ }
888
+ break;
889
+ case "CALL":
890
+ log.channel("[%s] RPC \u8C03\u7528: %s", role, message.method);
891
+ rpc.execute(message.id, message.method, message.params).catch((error) => {
892
+ log.channel("[%s] RPC \u54CD\u5E94\u53D1\u9001\u5931\u8D25: %O", role, error);
893
+ });
894
+ break;
895
+ case "RESULT":
896
+ log.channel("[%s] RPC \u7ED3\u679C: id=%s", role, message.id);
897
+ rpc.resolve(message.id, message.result, message.error);
898
+ break;
899
+ case "EVENT":
900
+ log.channel("[%s] \u4E8B\u4EF6: %s", role, message.eventType);
901
+ event.dispatch(message.eventType, message.data);
902
+ break;
903
+ }
904
+ }
905
+ function handleNativeMessage(message) {
906
+ return __async(this, null, function* () {
907
+ const { action, data, requestId } = message;
908
+ log.channel("[%s] Native \u6D88\u606F: %s", role, action);
909
+ if (!Object.prototype.hasOwnProperty.call(methods, action)) {
910
+ messenger.send(
911
+ createNativeResponse(
912
+ action,
913
+ requestId,
914
+ void 0,
915
+ `Method not found: ${action}`
916
+ )
917
+ );
918
+ return;
919
+ }
920
+ try {
921
+ const result = yield methods[action](data);
922
+ messenger.send(createNativeResponse(action, requestId, result));
923
+ } catch (e) {
924
+ const error = e instanceof Error ? e.message : String(e);
925
+ messenger.send(
926
+ createNativeResponse(action, requestId, void 0, error)
927
+ );
928
+ }
929
+ });
930
+ }
931
+ function finishHandshake() {
932
+ if (!resolveHandshake) {
933
+ log.channel("[%s] finishHandshake: \u5DF2\u5B8C\u6210\uFF0C\u5FFD\u7565", role);
934
+ return;
935
+ }
936
+ if (retryTimer) {
937
+ clearInterval(retryTimer);
938
+ retryTimer = null;
939
+ }
940
+ log.channel("[%s] \u2713 \u63E1\u624B\u5B8C\u6210 (\u7B2C %d \u6B21\u5C1D\u8BD5)", role, retryCount);
941
+ const remote = new Proxy(
942
+ {},
943
+ {
944
+ get: (_, name) => {
945
+ if (name === "then" || name === "catch" || name === "finally") {
946
+ return void 0;
947
+ }
948
+ return typeof name === "string" ? (params) => rpc.call(name, params) : void 0;
949
+ }
950
+ }
951
+ );
952
+ resolveHandshake(remote);
953
+ resolveHandshake = void 0;
954
+ }
955
+ return {
956
+ promise: handshakePromise,
957
+ on: event.on,
958
+ off: event.off,
959
+ emit: event.emit,
960
+ destroy: () => {
961
+ log.channel("[%s] \u9500\u6BC1\u901A\u9053", role);
962
+ if (retryTimer) {
963
+ clearInterval(retryTimer);
964
+ retryTimer = null;
965
+ }
966
+ rpc.cleanup();
967
+ event.cleanup();
968
+ messenger.destroy();
969
+ }
970
+ };
971
+ }
972
+ function connectToIframe(options) {
973
+ const { iframe, origin, methods, debug } = options;
974
+ log.channel("connectToIframe: iframe=%s, origin=%s, debug=%s", iframe, origin, debug);
975
+ const el = typeof iframe === "string" ? document.querySelector(iframe) : iframe;
976
+ if (!el) {
977
+ log.channel("\u2717 Iframe \u672A\u627E\u5230: %s", iframe);
978
+ throw new Error("Iframe not found");
979
+ }
980
+ if (!origin) {
981
+ log.channel("\u2717 Origin \u7F3A\u5931");
982
+ throw new Error("Origin is required");
983
+ }
984
+ log.channel("\u521B\u5EFA\u7236\u5E94\u7528\u901A\u9053: origin=%s, src=%s", origin, el.src);
985
+ const messenger = createMessenger({ isChild: false, iframe: el, origin });
986
+ return createChannel({ messenger, methods, debug });
987
+ }
988
+ function connectToParent(options = {}) {
989
+ const { allowedOrigins = [DEFAULT_ALLOWED_ORIGIN], methods, debug } = options;
990
+ log.channel("connectToParent: allowed=%O, debug=%s", allowedOrigins.map((o) => o.toString()), debug);
991
+ const messenger = createMessenger({ isChild: true, allowedOrigins });
992
+ return createChannel({ messenger, methods, debug });
993
+ }
994
+ //# sourceMappingURL=index.cjs.map