iframe-bridge-kit 1.1.0 → 1.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +38 -76
- package/dist/full/core.js +1 -1
- package/dist/full/core.mjs +1 -1
- package/dist/index.d.mts +7 -16
- package/dist/index.d.ts +7 -16
- package/dist/index.js +156 -42
- package/dist/index.mjs +155 -40
- package/dist/mini/core.js +1 -1
- package/dist/mini/core.mjs +1 -1
- package/dist/vite.js +46 -84
- package/dist/vite.mjs +46 -84
- package/package.json +1 -1
- package/dist/full/parent-core.js +0 -1
- package/dist/full/parent-core.mjs +0 -1
- package/dist/mini/parent-core.js +0 -1
- package/dist/mini/parent-core.mjs +0 -1
package/dist/vite.mjs
CHANGED
|
@@ -2,11 +2,12 @@
|
|
|
2
2
|
import * as ts from "typescript";
|
|
3
3
|
import * as path from "path";
|
|
4
4
|
import * as fs from "fs";
|
|
5
|
+
import { createRequire } from "module";
|
|
5
6
|
|
|
6
7
|
// package.json
|
|
7
8
|
var package_default = {
|
|
8
9
|
name: "iframe-bridge-kit",
|
|
9
|
-
version: "1.1.
|
|
10
|
+
version: "1.1.1",
|
|
10
11
|
description: "A type-safe communication bridge for iframes. Define strongly typed RPC APIs for cross-window messaging with ease.",
|
|
11
12
|
main: "dist/index.js",
|
|
12
13
|
module: "dist/index.mjs",
|
|
@@ -66,6 +67,20 @@ var package_default = {
|
|
|
66
67
|
|
|
67
68
|
// src/vite.ts
|
|
68
69
|
var packageName = package_default.name;
|
|
70
|
+
var requireFromCwd = createRequire(path.join(process.cwd(), "package.json"));
|
|
71
|
+
function getCoreDirs(variant) {
|
|
72
|
+
const dirs = [];
|
|
73
|
+
try {
|
|
74
|
+
const viteEntry = requireFromCwd.resolve(`${packageName}/vite`);
|
|
75
|
+
dirs.push(path.join(path.dirname(viteEntry), variant));
|
|
76
|
+
} catch {
|
|
77
|
+
}
|
|
78
|
+
dirs.push(
|
|
79
|
+
path.resolve(process.cwd(), "node_modules", packageName, "dist", variant),
|
|
80
|
+
path.resolve(process.cwd(), "dist", variant)
|
|
81
|
+
);
|
|
82
|
+
return Array.from(new Set(dirs));
|
|
83
|
+
}
|
|
69
84
|
function extractScriptFromVue(code) {
|
|
70
85
|
const scriptRegex = /<script(?:\s+setup)?(?:\s+lang\s*=\s*["']?(ts|typescript)["']?)?[^>]*>([\s\S]*?)<\/script>/i;
|
|
71
86
|
const match = code.match(scriptRegex);
|
|
@@ -214,7 +229,7 @@ function parseBridgeFromCode(code, filePath) {
|
|
|
214
229
|
collectTypeImports(stmt);
|
|
215
230
|
}
|
|
216
231
|
}
|
|
217
|
-
const
|
|
232
|
+
const defineBridgeNames = /* @__PURE__ */ new Set();
|
|
218
233
|
for (const stmt of sourceFile.statements) {
|
|
219
234
|
if (ts.isImportDeclaration(stmt) && ts.isStringLiteral(stmt.moduleSpecifier) && stmt.moduleSpecifier.text === packageName) {
|
|
220
235
|
const namedBindings = stmt.importClause?.namedBindings;
|
|
@@ -222,21 +237,17 @@ function parseBridgeFromCode(code, filePath) {
|
|
|
222
237
|
for (const element of namedBindings.elements) {
|
|
223
238
|
const originalName = element.propertyName?.text ?? element.name.text;
|
|
224
239
|
if (originalName === "defineBridge") {
|
|
225
|
-
|
|
226
|
-
}
|
|
227
|
-
if (originalName === "defineIframeBridge") {
|
|
228
|
-
bridgeFactories.set(element.name.text, "parent");
|
|
240
|
+
defineBridgeNames.add(element.name.text);
|
|
229
241
|
}
|
|
230
242
|
}
|
|
231
243
|
}
|
|
232
244
|
}
|
|
233
245
|
}
|
|
234
|
-
if (
|
|
246
|
+
if (defineBridgeNames.size === 0) {
|
|
235
247
|
return { results, cleanup };
|
|
236
248
|
}
|
|
237
249
|
const visit = (node) => {
|
|
238
|
-
if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) &&
|
|
239
|
-
const target = bridgeFactories.get(node.expression.text);
|
|
250
|
+
if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && defineBridgeNames.has(node.expression.text)) {
|
|
240
251
|
const [nameArg, methodsArg] = node.arguments;
|
|
241
252
|
if (!nameArg || !ts.isStringLiteral(nameArg)) {
|
|
242
253
|
return;
|
|
@@ -333,12 +344,8 @@ function parseBridgeFromCode(code, filePath) {
|
|
|
333
344
|
}
|
|
334
345
|
}
|
|
335
346
|
const emitMap = [];
|
|
336
|
-
let emitTypeName;
|
|
337
347
|
if (node.typeArguments && node.typeArguments.length > 0) {
|
|
338
348
|
const emitTypeNode = node.typeArguments[0];
|
|
339
|
-
if (ts.isTypeReferenceNode(emitTypeNode) && ts.isIdentifier(emitTypeNode.typeName)) {
|
|
340
|
-
emitTypeName = emitTypeNode.typeName.text;
|
|
341
|
-
}
|
|
342
349
|
const emitType = checker.getTypeFromTypeNode(emitTypeNode);
|
|
343
350
|
emitType.getProperties().forEach((prop) => {
|
|
344
351
|
const name = prop.getName();
|
|
@@ -352,13 +359,11 @@ function parseBridgeFromCode(code, filePath) {
|
|
|
352
359
|
mergeImports(bridgeImports, typeImports);
|
|
353
360
|
results.push({
|
|
354
361
|
name: bridgeName,
|
|
355
|
-
target,
|
|
356
362
|
methods,
|
|
357
363
|
sourceFile: filePath,
|
|
358
364
|
typeDeclarations,
|
|
359
365
|
imports: bridgeImports,
|
|
360
|
-
emitMap
|
|
361
|
-
emitTypeName
|
|
366
|
+
emitMap
|
|
362
367
|
});
|
|
363
368
|
}
|
|
364
369
|
ts.forEachChild(node, visit);
|
|
@@ -530,52 +535,6 @@ function generateDtsContent(info, outDir, preserveModules = []) {
|
|
|
530
535
|
lines.push("");
|
|
531
536
|
}
|
|
532
537
|
}
|
|
533
|
-
const localTypeDeclarations = info.typeDeclarations.filter(({ name }) => name !== info.emitTypeName && name !== "EmitMap");
|
|
534
|
-
if (localTypeDeclarations.length > 0) {
|
|
535
|
-
lines.push("// Local type definitions");
|
|
536
|
-
for (const { content } of localTypeDeclarations) {
|
|
537
|
-
lines.push(content);
|
|
538
|
-
lines.push("");
|
|
539
|
-
}
|
|
540
|
-
}
|
|
541
|
-
if (info.target === "parent") {
|
|
542
|
-
if (processedEmitTypes.length > 0) {
|
|
543
|
-
lines.push("export interface EmitMap {");
|
|
544
|
-
processedEmitTypes.forEach((e) => {
|
|
545
|
-
lines.push(` "${e.name}": ${e.type};`);
|
|
546
|
-
});
|
|
547
|
-
lines.push("}");
|
|
548
|
-
lines.push("");
|
|
549
|
-
}
|
|
550
|
-
lines.push("export interface BridgeConnection {");
|
|
551
|
-
lines.push(" api: {");
|
|
552
|
-
lines.push(
|
|
553
|
-
...processedMethods.map(
|
|
554
|
-
(m) => (m.jsdoc ? ` ${m.jsdoc}
|
|
555
|
-
` : "") + ` ${m.name}: (${m.params}) => ${m.returnType},`
|
|
556
|
-
)
|
|
557
|
-
);
|
|
558
|
-
lines.push(" };");
|
|
559
|
-
if (processedEmitTypes.length > 0) {
|
|
560
|
-
lines.push(" onMessage<K extends keyof EmitMap>(type: K, cb: (data: EmitMap[K]) => void, once?: boolean): () => void;");
|
|
561
|
-
lines.push(" onMessage(type: string, cb: Function, once?: boolean): () => void;");
|
|
562
|
-
lines.push(" offMessage<K extends keyof EmitMap>(type: K, fn?: (data: EmitMap[K]) => void): void;");
|
|
563
|
-
lines.push(" offMessage(type: string, fn?: Function): void;");
|
|
564
|
-
} else {
|
|
565
|
-
lines.push(" onMessage(type: string, cb: Function, once?: boolean): () => void;");
|
|
566
|
-
lines.push(" offMessage(type: string, fn?: Function): void;");
|
|
567
|
-
}
|
|
568
|
-
lines.push(" isInit(): boolean;");
|
|
569
|
-
lines.push(" onInit(cb: Function): void;");
|
|
570
|
-
lines.push(" destroy(): void;");
|
|
571
|
-
lines.push("}");
|
|
572
|
-
lines.push("");
|
|
573
|
-
lines.push("export declare function create(iframe: HTMLIFrameElement, allowedOrigins?: string[]): BridgeConnection;");
|
|
574
|
-
lines.push("declare const bridge: { create: typeof create };");
|
|
575
|
-
lines.push("export default bridge;");
|
|
576
|
-
lines.push("");
|
|
577
|
-
return lines.join("\n");
|
|
578
|
-
}
|
|
579
538
|
if (processedEmitTypes.length > 0) {
|
|
580
539
|
lines.push("export interface EmitMap {");
|
|
581
540
|
processedEmitTypes.forEach((e) => {
|
|
@@ -583,18 +542,10 @@ function generateDtsContent(info, outDir, preserveModules = []) {
|
|
|
583
542
|
});
|
|
584
543
|
lines.push("}");
|
|
585
544
|
lines.push("");
|
|
586
|
-
lines.push("export declare function onMessage<K extends keyof EmitMap>(type: K, cb: (data: EmitMap[K]) => void, once?: boolean): () => void;");
|
|
587
|
-
lines.push("export declare function onMessage(type: string, cb: Function, once?: boolean): () => void;");
|
|
588
|
-
lines.push("export declare function offMessage<K extends keyof EmitMap>(type: K, fn?: (data: EmitMap[K]) => void): void;");
|
|
589
|
-
lines.push("export declare function offMessage(type: string, fn?: Function): void;");
|
|
590
|
-
} else {
|
|
591
|
-
lines.push("export declare function onMessage(type: string, cb: Function, once?: boolean): () => void;");
|
|
592
|
-
lines.push("export declare function offMessage(type: string, fn?: Function): void;");
|
|
593
545
|
}
|
|
594
|
-
lines.push("export declare function
|
|
595
|
-
lines.push("export declare function onInit(cb: Function): void;");
|
|
546
|
+
lines.push("export declare function createBridgeClient(remoteWindow: Window, allowedOrigins?: string[]): BridgeClient;");
|
|
596
547
|
lines.push("");
|
|
597
|
-
lines.push(`export
|
|
548
|
+
lines.push(`export interface BridgeApi {`);
|
|
598
549
|
lines.push(
|
|
599
550
|
...processedMethods.map(
|
|
600
551
|
(m) => (m.jsdoc ? ` ${m.jsdoc}
|
|
@@ -603,6 +554,24 @@ function generateDtsContent(info, outDir, preserveModules = []) {
|
|
|
603
554
|
);
|
|
604
555
|
lines.push("}");
|
|
605
556
|
lines.push("");
|
|
557
|
+
lines.push("export type BridgeClient = BridgeApi & {");
|
|
558
|
+
if (processedEmitTypes.length > 0) {
|
|
559
|
+
lines.push(" onMessage<K extends keyof EmitMap>(type: K, cb: (data: EmitMap[K]) => void, once?: boolean): () => void;");
|
|
560
|
+
lines.push(" onMessage(type: string, cb: Function, once?: boolean): () => void;");
|
|
561
|
+
lines.push(" offMessage<K extends keyof EmitMap>(type: K, fn?: (data: EmitMap[K]) => void): void;");
|
|
562
|
+
lines.push(" offMessage(type: string, fn?: Function): void;");
|
|
563
|
+
} else {
|
|
564
|
+
lines.push(" onMessage(type: string, cb: Function, once?: boolean): () => void;");
|
|
565
|
+
lines.push(" offMessage(type: string, fn?: Function): void;");
|
|
566
|
+
}
|
|
567
|
+
lines.push(" isInit(): boolean;");
|
|
568
|
+
lines.push(" onInit(cb: (api: BridgeClient) => void): void;");
|
|
569
|
+
lines.push(" destroy(): void;");
|
|
570
|
+
lines.push("}");
|
|
571
|
+
lines.push("");
|
|
572
|
+
lines.push("declare const createBridge: () => BridgeClient;");
|
|
573
|
+
lines.push("export default createBridge;");
|
|
574
|
+
lines.push("");
|
|
606
575
|
return lines.join("\n");
|
|
607
576
|
}
|
|
608
577
|
function writeDtsFile(info, options) {
|
|
@@ -628,7 +597,7 @@ function processFile(filePath, code, options) {
|
|
|
628
597
|
const { results: bridges, cleanup } = parseBridgeFromCode(code, filePath);
|
|
629
598
|
for (const bridge of bridges) {
|
|
630
599
|
writeDtsFile(bridge, options);
|
|
631
|
-
writeBridgeRuntime(bridge, options);
|
|
600
|
+
writeBridgeRuntime(bridge.name, options);
|
|
632
601
|
}
|
|
633
602
|
cleanup();
|
|
634
603
|
return bridges;
|
|
@@ -637,19 +606,13 @@ function processFile(filePath, code, options) {
|
|
|
637
606
|
return [];
|
|
638
607
|
}
|
|
639
608
|
}
|
|
640
|
-
function writeBridgeRuntime(
|
|
609
|
+
function writeBridgeRuntime(bridgeName, options) {
|
|
641
610
|
const isFull = options.full !== false;
|
|
642
611
|
const allowedOrigins = options.allowedOrigins || ["*"];
|
|
643
612
|
const outDir = options.outDir || "bridges";
|
|
644
613
|
const variant = isFull ? "full" : "mini";
|
|
645
|
-
const basePaths = [
|
|
646
|
-
// 1. 假设我们在 dist 目录中运行
|
|
647
|
-
path.resolve(__dirname, variant),
|
|
648
|
-
// 2. 假设我们在 src 目录中运行
|
|
649
|
-
path.resolve(__dirname, "../dist", variant)
|
|
650
|
-
];
|
|
651
614
|
let coreDir = "";
|
|
652
|
-
for (const p of
|
|
615
|
+
for (const p of getCoreDirs(variant)) {
|
|
653
616
|
if (fs.existsSync(p)) {
|
|
654
617
|
coreDir = p;
|
|
655
618
|
break;
|
|
@@ -658,15 +621,14 @@ function writeBridgeRuntime(info, options) {
|
|
|
658
621
|
if (!coreDir) {
|
|
659
622
|
return;
|
|
660
623
|
}
|
|
661
|
-
const absoluteOutDir = path.resolve(process.cwd(), outDir,
|
|
624
|
+
const absoluteOutDir = path.resolve(process.cwd(), outDir, bridgeName);
|
|
662
625
|
if (!fs.existsSync(absoluteOutDir)) {
|
|
663
626
|
fs.mkdirSync(absoluteOutDir, { recursive: true });
|
|
664
627
|
}
|
|
665
628
|
const extensions = ["js", "mjs"];
|
|
666
629
|
const replaceContent = JSON.stringify(allowedOrigins).slice(1, -1);
|
|
667
|
-
const runtimeName = info.target === "parent" ? "parent-core" : "core";
|
|
668
630
|
for (const ext of extensions) {
|
|
669
|
-
const srcFile = path.join(coreDir,
|
|
631
|
+
const srcFile = path.join(coreDir, `core.${ext}`);
|
|
670
632
|
if (fs.existsSync(srcFile)) {
|
|
671
633
|
try {
|
|
672
634
|
let content = fs.readFileSync(srcFile, "utf-8");
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "iframe-bridge-kit",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.1",
|
|
4
4
|
"description": "A type-safe communication bridge for iframes. Define strongly typed RPC APIs for cross-window messaging with ease.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.mjs",
|
package/dist/full/parent-core.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";var P=Object.defineProperty;var J=Object.getOwnPropertyDescriptor;var X=Object.getOwnPropertyNames;var q=Object.prototype.hasOwnProperty;var B=(e,t)=>{for(var n in t)P(e,n,{get:t[n],enumerable:!0})},Q=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of X(t))!q.call(e,r)&&r!==n&&P(e,r,{get:()=>t[r],enumerable:!(s=J(t,r))||s.enumerable});return e};var Z=e=>Q(P({},"__esModule",{value:!0}),e);var Le={};B(Le,{create:()=>K,default:()=>Oe});module.exports=Z(Le);var ee=class extends Error{code;constructor(e,t){super(t),this.name="PenpalError",this.code=e}},M=ee,te=e=>({name:e.name,message:e.message,stack:e.stack,penpalCode:e instanceof M?e.code:void 0}),re=({name:e,message:t,stack:n,penpalCode:s})=>{let r=s?new M(s,t):new Error(t);return r.name=e,r.stack=n,r},ne=Symbol("Reply"),se=class{value;transferables;#t=ne;constructor(e,t){this.value=e,this.transferables=t?.transferables}},ae=se,v="penpal",N=e=>typeof e=="object"&&e!==null,F=e=>typeof e=="function",oe=e=>N(e)&&e.namespace===v,S=e=>e.type==="SYN",O=e=>e.type==="ACK1",R=e=>e.type==="ACK2",x=e=>e.type==="CALL",U=e=>e.type==="REPLY",ie=e=>e.type==="DESTROY",W=(e,t=[])=>{let n=[];for(let s of Object.keys(e)){let r=e[s];F(r)?n.push([...t,s]):N(r)&&n.push(...W(r,[...t,s]))}return n},de=(e,t)=>{let n=e.reduce((s,r)=>N(s)?s[r]:void 0,t);return F(n)?n:void 0},g=e=>e.join("."),b=(e,t,n)=>({namespace:v,channel:e,type:"REPLY",callId:t,isError:!0,...n instanceof Error?{value:te(n),isSerializedErrorInstance:!0}:{value:n}}),le=(e,t,n,s)=>{let r=!1,o=async i=>{if(r||!x(i))return;s?.(`Received ${g(i.methodPath)}() call`,i);let{methodPath:h,args:l,id:a}=i,d,p;try{let u=de(h,t);if(!u)throw new M("METHOD_NOT_FOUND",`Method \`${g(h)}\` is not found.`);let f=await u(...l);f instanceof ae&&(p=f.transferables,f=await f.value),d={namespace:v,channel:n,type:"REPLY",callId:a,value:f}}catch(u){d=b(n,a,u)}if(!r)try{s?.(`Sending ${g(h)}() reply`,d),e.sendMessage(d,p)}catch(u){throw u.name==="DataCloneError"&&(d=b(n,a,u),s?.(`Sending ${g(h)}() reply`,d),e.sendMessage(d)),u}};return e.addMessageHandler(o),()=>{r=!0,e.removeMessageHandler(o)}},ce=le,$=crypto.randomUUID?.bind(crypto)??(()=>new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")),he=Symbol("CallOptions"),ue=class{transferables;timeout;#t=he;constructor(e){this.transferables=e?.transferables,this.timeout=e?.timeout}},fe=ue,Me=new Set(["apply","call","bind"]),V=(e,t,n=[])=>new Proxy(n.length?()=>{}:Object.create(null),{get(s,r){if(r!=="then")return n.length&&Me.has(r)?Reflect.get(s,r):V(e,t,[...n,r])},apply(s,r,o){return e(n,o)}}),D=e=>new M("CONNECTION_DESTROYED",`Method call ${g(e)}() failed due to destroyed connection`),pe=(e,t,n)=>{let s=!1,r=new Map,o=l=>{if(!U(l))return;let{callId:a,value:d,isError:p,isSerializedErrorInstance:u}=l,f=r.get(a);f&&(r.delete(a),n?.(`Received ${g(f.methodPath)}() call`,l),p?f.reject(u?re(d):d):f.resolve(d))};return e.addMessageHandler(o),{remoteProxy:V((l,a)=>{if(s)throw D(l);let d=$(),p=a[a.length-1],u=p instanceof fe,{timeout:f,transferables:C}=u?p:{},w=u?a.slice(0,-1):a;return new Promise((m,I)=>{let _=f!==void 0?window.setTimeout(()=>{r.delete(d),I(new M("METHOD_CALL_TIMEOUT",`Method call ${g(l)}() timed out after ${f}ms`))},f):void 0;r.set(d,{methodPath:l,resolve:m,reject:I,timeoutId:_});try{let E={namespace:v,channel:t,type:"CALL",id:d,methodPath:l,args:w};n?.(`Sending ${g(l)}() call`,E),e.sendMessage(E,C)}catch(E){I(new M("TRANSMISSION_FAILED",E.message))}})},n),destroy:()=>{s=!0,e.removeMessageHandler(o);for(let{methodPath:l,reject:a,timeoutId:d}of r.values())clearTimeout(d),a(D(l));r.clear()}}},ve=pe,ge=()=>{let e,t;return{promise:new Promise((s,r)=>{e=s,t=r}),resolve:e,reject:t}},ye=ge,T="deprecated-penpal",Ee=e=>N(e)&&"penpal"in e,Ie=e=>e.split("."),k=e=>e.join("."),we=e=>{try{return JSON.stringify(e)}catch{return String(e)}},Y=e=>new M("TRANSMISSION_FAILED",`Unexpected message to translate: ${we(e)}`),me=e=>{if(e.penpal==="syn")return{namespace:v,channel:void 0,type:"SYN",participantId:T};if(e.penpal==="ack")return{namespace:v,channel:void 0,type:"ACK2"};if(e.penpal==="call")return{namespace:v,channel:void 0,type:"CALL",id:e.id,methodPath:Ie(e.methodName),args:e.args};if(e.penpal==="reply")return e.resolution==="fulfilled"?{namespace:v,channel:void 0,type:"REPLY",callId:e.id,value:e.returnValue}:{namespace:v,channel:void 0,type:"REPLY",callId:e.id,isError:!0,...e.returnValueIsError?{value:e.returnValue,isSerializedErrorInstance:!0}:{value:e.returnValue}};throw Y(e)},Ae=e=>{if(O(e))return{penpal:"synAck",methodNames:e.methodPaths.map(k)};if(x(e))return{penpal:"call",id:e.id,methodName:k(e.methodPath),args:e.args};if(U(e))return e.isError?{penpal:"reply",id:e.callId,resolution:"rejected",...e.isSerializedErrorInstance?{returnValue:e.value,returnValueIsError:!0}:{returnValue:e.value}}:{penpal:"reply",id:e.callId,resolution:"fulfilled",returnValue:e.value};throw Y(e)},Se=({messenger:e,methods:t,timeout:n,channel:s,log:r})=>{let o=$(),i,h=[],l=!1,a=W(t),{promise:d,resolve:p,reject:u}=ye(),f=n!==void 0?setTimeout(()=>{u(new M("CONNECTION_TIMEOUT",`Connection timed out after ${n}ms`))},n):void 0,C=()=>{for(let c of h)c()},w=()=>{if(l)return;h.push(ce(e,t,s,r));let{remoteProxy:c,destroy:y}=ve(e,s,r);h.push(y),clearTimeout(f),l=!0,p({remoteProxy:c,destroy:C})},m=()=>{let c={namespace:v,type:"SYN",channel:s,participantId:o};r?.("Sending handshake SYN",c);try{e.sendMessage(c)}catch(y){u(new M("TRANSMISSION_FAILED",y.message))}},I=c=>{if(r?.("Received handshake SYN",c),c.participantId===i&&i!==T||(i=c.participantId,m(),!(o>i||i===T)))return;let A={namespace:v,channel:s,type:"ACK1",methodPaths:a};r?.("Sending handshake ACK1",A);try{e.sendMessage(A)}catch(G){u(new M("TRANSMISSION_FAILED",G.message));return}},_=c=>{r?.("Received handshake ACK1",c);let y={namespace:v,channel:s,type:"ACK2"};r?.("Sending handshake ACK2",y);try{e.sendMessage(y)}catch(A){u(new M("TRANSMISSION_FAILED",A.message));return}w()},E=c=>{r?.("Received handshake ACK2",c),w()},L=c=>{S(c)&&I(c),O(c)&&_(c),R(c)&&E(c)};return e.addMessageHandler(L),h.push(()=>e.removeMessageHandler(L)),m(),d},Ne=Se,Ce=e=>{let t=!1,n;return(...s)=>(t||(t=!0,n=e(...s)),n)},_e=Ce,H=new WeakSet,Pe=({messenger:e,methods:t={},timeout:n,channel:s,log:r})=>{if(!e)throw new M("INVALID_ARGUMENT","messenger must be defined");if(H.has(e))throw new M("INVALID_ARGUMENT","A messenger can only be used for a single connection");H.add(e);let o=[e.destroy],i=_e(a=>{if(a){let d={namespace:v,channel:s,type:"DESTROY"};try{e.sendMessage(d)}catch{}}for(let d of o)d();r?.("Connection destroyed")}),h=a=>oe(a)&&a.channel===s;return{promise:(async()=>{try{e.initialize({log:r,validateReceivedMessage:h}),e.addMessageHandler(p=>{ie(p)&&i(!1)});let{remoteProxy:a,destroy:d}=await Ne({messenger:e,methods:t,timeout:n,channel:s,log:r});return o.push(d),a}catch(a){throw i(!0),a}})(),destroy:()=>{i(!0)}}},j=Pe,Re=class{#t;#s;#r;#i;#a;#n=new Set;#e;#o=!1;constructor({remoteWindow:e,allowedOrigins:t}){if(!e)throw new M("INVALID_ARGUMENT","remoteWindow must be defined");this.#t=e,this.#s=t?.length?t:[window.origin]}initialize=({log:e,validateReceivedMessage:t})=>{this.#r=e,this.#i=t,window.addEventListener("message",this.#h)};sendMessage=(e,t)=>{if(S(e)){let n=this.#d(e);this.#t.postMessage(e,{targetOrigin:n,transfer:t});return}if(O(e)||this.#o){let n=this.#o?Ae(e):e,s=this.#d(e);this.#t.postMessage(n,{targetOrigin:s,transfer:t});return}if(R(e)){let{port1:n,port2:s}=new MessageChannel;this.#e=n,n.addEventListener("message",this.#l),n.start();let r=[s,...t||[]],o=this.#d(e);this.#t.postMessage(e,{targetOrigin:o,transfer:r});return}if(this.#e){this.#e.postMessage(e,{transfer:t});return}throw new M("TRANSMISSION_FAILED","Cannot send message because the MessagePort is not connected")};addMessageHandler=e=>{this.#n.add(e)};removeMessageHandler=e=>{this.#n.delete(e)};destroy=()=>{window.removeEventListener("message",this.#h),this.#c(),this.#n.clear()};#u=e=>this.#s.some(t=>t instanceof RegExp?t.test(e):t===e||t==="*");#d=e=>{if(S(e))return"*";if(!this.#a)throw new M("TRANSMISSION_FAILED","Cannot send message because the remote origin is not established");return this.#a==="null"&&this.#s.includes("*")?"*":this.#a};#c=()=>{this.#e?.removeEventListener("message",this.#l),this.#e?.close(),this.#e=void 0};#h=({source:e,origin:t,ports:n,data:s})=>{if(e===this.#t){if(Ee(s)){this.#r?.("Please upgrade the child window to the latest version of Penpal."),this.#o=!0;try{s=me(s)}catch(r){this.#r?.(`Failed to translate deprecated message: ${r.message}`);return}}if(this.#i?.(s)){if(!this.#u(t)){this.#r?.(`Received a message from origin \`${t}\` which did not match allowed origins \`[${this.#s.join(", ")}]\``);return}if(S(s)&&(this.#c(),this.#a=t),R(s)&&!this.#o){if(this.#e=n[0],!this.#e){this.#r?.("Ignoring ACK2 because it did not include a MessagePort");return}this.#e.addEventListener("message",this.#l),this.#e.start()}for(let r of this.#n)r(s)}}};#l=({data:e})=>{if(this.#i?.(e))for(let t of this.#n)t(e)}},z=Re;var Te=()=>{let e=new Map,t=(r,o,i)=>{let h=i?(a=>{o(a),n(r,h)}):o,l=e.get(r);return l?l.add(h):e.set(r,new Set([h])),()=>n(r,h)},n=(r,o)=>{if(!o){e.delete(r);return}let i=e.get(r);i&&i.delete(o)};return{onMessage:t,offMessage:n,emitMessage:(r,o)=>{let i=e.get(r);if(i)return i.forEach(h=>h(o)),!0}}},K=(e,t=["__AllowedOrigins__"])=>{if(!e.contentWindow)throw new Error("iframe contentWindow is null");let{onMessage:n,offMessage:s,emitMessage:r}=Te(),o=j({messenger:new z({remoteWindow:e.contentWindow,allowedOrigins:t}),channel:"iframe-bridge-channel",methods:{onMessage(l,a){return r(l,a)}}}),i=!1;return o.promise.then(()=>{i=!0}),{api:new Proxy({},{get(l,a){return async(...d)=>await o.promise.then(p=>p[a](...d))}}),onMessage:n,offMessage:s,isInit:()=>i,onInit(l){if(i){l();return}o.promise.then(()=>{l()})},destroy:o.destroy}},Oe={create:K};0&&(module.exports={create});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var K=class extends Error{code;constructor(e,r){super(r),this.name="PenpalError",this.code=e}},M=K,G=e=>({name:e.name,message:e.message,stack:e.stack,penpalCode:e instanceof M?e.code:void 0}),J=({name:e,message:r,stack:n,penpalCode:s})=>{let t=s?new M(s,r):new Error(r);return t.name=e,t.stack=n,t},X=Symbol("Reply"),q=class{value;transferables;#t=X;constructor(e,r){this.value=e,this.transferables=r?.transferables}},B=q,v="penpal",N=e=>typeof e=="object"&&e!==null,H=e=>typeof e=="function",Q=e=>N(e)&&e.namespace===v,S=e=>e.type==="SYN",T=e=>e.type==="ACK1",P=e=>e.type==="ACK2",F=e=>e.type==="CALL",x=e=>e.type==="REPLY",Z=e=>e.type==="DESTROY",U=(e,r=[])=>{let n=[];for(let s of Object.keys(e)){let t=e[s];H(t)?n.push([...r,s]):N(t)&&n.push(...U(t,[...r,s]))}return n},ee=(e,r)=>{let n=e.reduce((s,t)=>N(s)?s[t]:void 0,r);return H(n)?n:void 0},g=e=>e.join("."),L=(e,r,n)=>({namespace:v,channel:e,type:"REPLY",callId:r,isError:!0,...n instanceof Error?{value:G(n),isSerializedErrorInstance:!0}:{value:n}}),te=(e,r,n,s)=>{let t=!1,o=async i=>{if(t||!F(i))return;s?.(`Received ${g(i.methodPath)}() call`,i);let{methodPath:h,args:l,id:a}=i,d,p;try{let u=ee(h,r);if(!u)throw new M("METHOD_NOT_FOUND",`Method \`${g(h)}\` is not found.`);let f=await u(...l);f instanceof B&&(p=f.transferables,f=await f.value),d={namespace:v,channel:n,type:"REPLY",callId:a,value:f}}catch(u){d=L(n,a,u)}if(!t)try{s?.(`Sending ${g(h)}() reply`,d),e.sendMessage(d,p)}catch(u){throw u.name==="DataCloneError"&&(d=L(n,a,u),s?.(`Sending ${g(h)}() reply`,d),e.sendMessage(d)),u}};return e.addMessageHandler(o),()=>{t=!0,e.removeMessageHandler(o)}},re=te,W=crypto.randomUUID?.bind(crypto)??(()=>new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")),ne=Symbol("CallOptions"),se=class{transferables;timeout;#t=ne;constructor(e){this.transferables=e?.transferables,this.timeout=e?.timeout}},ae=se,oe=new Set(["apply","call","bind"]),$=(e,r,n=[])=>new Proxy(n.length?()=>{}:Object.create(null),{get(s,t){if(t!=="then")return n.length&&oe.has(t)?Reflect.get(s,t):$(e,r,[...n,t])},apply(s,t,o){return e(n,o)}}),b=e=>new M("CONNECTION_DESTROYED",`Method call ${g(e)}() failed due to destroyed connection`),ie=(e,r,n)=>{let s=!1,t=new Map,o=l=>{if(!x(l))return;let{callId:a,value:d,isError:p,isSerializedErrorInstance:u}=l,f=t.get(a);f&&(t.delete(a),n?.(`Received ${g(f.methodPath)}() call`,l),p?f.reject(u?J(d):d):f.resolve(d))};return e.addMessageHandler(o),{remoteProxy:$((l,a)=>{if(s)throw b(l);let d=W(),p=a[a.length-1],u=p instanceof ae,{timeout:f,transferables:C}=u?p:{},w=u?a.slice(0,-1):a;return new Promise((m,I)=>{let _=f!==void 0?window.setTimeout(()=>{t.delete(d),I(new M("METHOD_CALL_TIMEOUT",`Method call ${g(l)}() timed out after ${f}ms`))},f):void 0;t.set(d,{methodPath:l,resolve:m,reject:I,timeoutId:_});try{let E={namespace:v,channel:r,type:"CALL",id:d,methodPath:l,args:w};n?.(`Sending ${g(l)}() call`,E),e.sendMessage(E,C)}catch(E){I(new M("TRANSMISSION_FAILED",E.message))}})},n),destroy:()=>{s=!0,e.removeMessageHandler(o);for(let{methodPath:l,reject:a,timeoutId:d}of t.values())clearTimeout(d),a(b(l));t.clear()}}},de=ie,le=()=>{let e,r;return{promise:new Promise((s,t)=>{e=s,r=t}),resolve:e,reject:r}},ce=le,R="deprecated-penpal",he=e=>N(e)&&"penpal"in e,ue=e=>e.split("."),D=e=>e.join("."),fe=e=>{try{return JSON.stringify(e)}catch{return String(e)}},V=e=>new M("TRANSMISSION_FAILED",`Unexpected message to translate: ${fe(e)}`),Me=e=>{if(e.penpal==="syn")return{namespace:v,channel:void 0,type:"SYN",participantId:R};if(e.penpal==="ack")return{namespace:v,channel:void 0,type:"ACK2"};if(e.penpal==="call")return{namespace:v,channel:void 0,type:"CALL",id:e.id,methodPath:ue(e.methodName),args:e.args};if(e.penpal==="reply")return e.resolution==="fulfilled"?{namespace:v,channel:void 0,type:"REPLY",callId:e.id,value:e.returnValue}:{namespace:v,channel:void 0,type:"REPLY",callId:e.id,isError:!0,...e.returnValueIsError?{value:e.returnValue,isSerializedErrorInstance:!0}:{value:e.returnValue}};throw V(e)},pe=e=>{if(T(e))return{penpal:"synAck",methodNames:e.methodPaths.map(D)};if(F(e))return{penpal:"call",id:e.id,methodName:D(e.methodPath),args:e.args};if(x(e))return e.isError?{penpal:"reply",id:e.callId,resolution:"rejected",...e.isSerializedErrorInstance?{returnValue:e.value,returnValueIsError:!0}:{returnValue:e.value}}:{penpal:"reply",id:e.callId,resolution:"fulfilled",returnValue:e.value};throw V(e)},ve=({messenger:e,methods:r,timeout:n,channel:s,log:t})=>{let o=W(),i,h=[],l=!1,a=U(r),{promise:d,resolve:p,reject:u}=ce(),f=n!==void 0?setTimeout(()=>{u(new M("CONNECTION_TIMEOUT",`Connection timed out after ${n}ms`))},n):void 0,C=()=>{for(let c of h)c()},w=()=>{if(l)return;h.push(re(e,r,s,t));let{remoteProxy:c,destroy:y}=de(e,s,t);h.push(y),clearTimeout(f),l=!0,p({remoteProxy:c,destroy:C})},m=()=>{let c={namespace:v,type:"SYN",channel:s,participantId:o};t?.("Sending handshake SYN",c);try{e.sendMessage(c)}catch(y){u(new M("TRANSMISSION_FAILED",y.message))}},I=c=>{if(t?.("Received handshake SYN",c),c.participantId===i&&i!==R||(i=c.participantId,m(),!(o>i||i===R)))return;let A={namespace:v,channel:s,type:"ACK1",methodPaths:a};t?.("Sending handshake ACK1",A);try{e.sendMessage(A)}catch(z){u(new M("TRANSMISSION_FAILED",z.message));return}},_=c=>{t?.("Received handshake ACK1",c);let y={namespace:v,channel:s,type:"ACK2"};t?.("Sending handshake ACK2",y);try{e.sendMessage(y)}catch(A){u(new M("TRANSMISSION_FAILED",A.message));return}w()},E=c=>{t?.("Received handshake ACK2",c),w()},O=c=>{S(c)&&I(c),T(c)&&_(c),P(c)&&E(c)};return e.addMessageHandler(O),h.push(()=>e.removeMessageHandler(O)),m(),d},ge=ve,ye=e=>{let r=!1,n;return(...s)=>(r||(r=!0,n=e(...s)),n)},Ee=ye,k=new WeakSet,Ie=({messenger:e,methods:r={},timeout:n,channel:s,log:t})=>{if(!e)throw new M("INVALID_ARGUMENT","messenger must be defined");if(k.has(e))throw new M("INVALID_ARGUMENT","A messenger can only be used for a single connection");k.add(e);let o=[e.destroy],i=Ee(a=>{if(a){let d={namespace:v,channel:s,type:"DESTROY"};try{e.sendMessage(d)}catch{}}for(let d of o)d();t?.("Connection destroyed")}),h=a=>Q(a)&&a.channel===s;return{promise:(async()=>{try{e.initialize({log:t,validateReceivedMessage:h}),e.addMessageHandler(p=>{Z(p)&&i(!1)});let{remoteProxy:a,destroy:d}=await ge({messenger:e,methods:r,timeout:n,channel:s,log:t});return o.push(d),a}catch(a){throw i(!0),a}})(),destroy:()=>{i(!0)}}},Y=Ie,we=class{#t;#s;#r;#i;#a;#n=new Set;#e;#o=!1;constructor({remoteWindow:e,allowedOrigins:r}){if(!e)throw new M("INVALID_ARGUMENT","remoteWindow must be defined");this.#t=e,this.#s=r?.length?r:[window.origin]}initialize=({log:e,validateReceivedMessage:r})=>{this.#r=e,this.#i=r,window.addEventListener("message",this.#h)};sendMessage=(e,r)=>{if(S(e)){let n=this.#d(e);this.#t.postMessage(e,{targetOrigin:n,transfer:r});return}if(T(e)||this.#o){let n=this.#o?pe(e):e,s=this.#d(e);this.#t.postMessage(n,{targetOrigin:s,transfer:r});return}if(P(e)){let{port1:n,port2:s}=new MessageChannel;this.#e=n,n.addEventListener("message",this.#l),n.start();let t=[s,...r||[]],o=this.#d(e);this.#t.postMessage(e,{targetOrigin:o,transfer:t});return}if(this.#e){this.#e.postMessage(e,{transfer:r});return}throw new M("TRANSMISSION_FAILED","Cannot send message because the MessagePort is not connected")};addMessageHandler=e=>{this.#n.add(e)};removeMessageHandler=e=>{this.#n.delete(e)};destroy=()=>{window.removeEventListener("message",this.#h),this.#c(),this.#n.clear()};#u=e=>this.#s.some(r=>r instanceof RegExp?r.test(e):r===e||r==="*");#d=e=>{if(S(e))return"*";if(!this.#a)throw new M("TRANSMISSION_FAILED","Cannot send message because the remote origin is not established");return this.#a==="null"&&this.#s.includes("*")?"*":this.#a};#c=()=>{this.#e?.removeEventListener("message",this.#l),this.#e?.close(),this.#e=void 0};#h=({source:e,origin:r,ports:n,data:s})=>{if(e===this.#t){if(he(s)){this.#r?.("Please upgrade the child window to the latest version of Penpal."),this.#o=!0;try{s=Me(s)}catch(t){this.#r?.(`Failed to translate deprecated message: ${t.message}`);return}}if(this.#i?.(s)){if(!this.#u(r)){this.#r?.(`Received a message from origin \`${r}\` which did not match allowed origins \`[${this.#s.join(", ")}]\``);return}if(S(s)&&(this.#c(),this.#a=r),P(s)&&!this.#o){if(this.#e=n[0],!this.#e){this.#r?.("Ignoring ACK2 because it did not include a MessagePort");return}this.#e.addEventListener("message",this.#l),this.#e.start()}for(let t of this.#n)t(s)}}};#l=({data:e})=>{if(this.#i?.(e))for(let r of this.#n)r(e)}},j=we;var me=()=>{let e=new Map,r=(t,o,i)=>{let h=i?(a=>{o(a),n(t,h)}):o,l=e.get(t);return l?l.add(h):e.set(t,new Set([h])),()=>n(t,h)},n=(t,o)=>{if(!o){e.delete(t);return}let i=e.get(t);i&&i.delete(o)};return{onMessage:r,offMessage:n,emitMessage:(t,o)=>{let i=e.get(t);if(i)return i.forEach(h=>h(o)),!0}}},Ae=(e,r=["__AllowedOrigins__"])=>{if(!e.contentWindow)throw new Error("iframe contentWindow is null");let{onMessage:n,offMessage:s,emitMessage:t}=me(),o=Y({messenger:new j({remoteWindow:e.contentWindow,allowedOrigins:r}),channel:"iframe-bridge-channel",methods:{onMessage(l,a){return t(l,a)}}}),i=!1;return o.promise.then(()=>{i=!0}),{api:new Proxy({},{get(l,a){return async(...d)=>await o.promise.then(p=>p[a](...d))}}),onMessage:n,offMessage:s,isInit:()=>i,onInit(l){if(i){l();return}o.promise.then(()=>{l()})},destroy:o.destroy}},Te={create:Ae};export{Ae as create,Te as default};
|
package/dist/mini/parent-core.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";var u=Object.defineProperty;var w=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var h=Object.prototype.hasOwnProperty;var p=(n,t)=>{for(var r in t)u(n,r,{get:t[r],enumerable:!0})},y=(n,t,r,c)=>{if(t&&typeof t=="object"||typeof t=="function")for(let e of M(t))!h.call(n,e)&&e!==r&&u(n,e,{get:()=>t[e],enumerable:!(c=w(t,e))||c.enumerable});return n};var F=n=>y(u({},"__esModule",{value:!0}),n);var x={};p(x,{create:()=>d,default:()=>_});module.exports=F(x);var f=require("penpal"),W=()=>{let n=new Map,t=(e,s,o)=>{let a=o?(g=>{s(g),r(e,a)}):s,i=n.get(e);return i?i.add(a):n.set(e,new Set([a])),()=>r(e,a)},r=(e,s)=>{if(!s){n.delete(e);return}let o=n.get(e);o&&o.delete(s)};return{onMessage:t,offMessage:r,emitMessage:(e,s)=>{let o=n.get(e);if(o)return o.forEach(a=>a(s)),!0}}},d=(n,t=["__AllowedOrigins__"])=>{if(!n.contentWindow)throw new Error("iframe contentWindow is null");let{onMessage:r,offMessage:c,emitMessage:e}=W(),s=(0,f.connect)({messenger:new f.WindowMessenger({remoteWindow:n.contentWindow,allowedOrigins:t}),channel:"iframe-bridge-channel",methods:{onMessage(i,g){return e(i,g)}}}),o=!1;return s.promise.then(()=>{o=!0}),{api:new Proxy({},{get(i,g){return async(...m)=>await s.promise.then(l=>l[g](...m))}}),onMessage:r,offMessage:c,isInit:()=>o,onInit(i){if(o){i();return}s.promise.then(()=>{i()})},destroy:s.destroy}},_={create:d};0&&(module.exports={create});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{WindowMessenger as d,connect as m}from"penpal";var l=()=>{let s=new Map,c=(n,e,t)=>{let r=t?(a=>{e(a),i(n,r)}):e,o=s.get(n);return o?o.add(r):s.set(n,new Set([r])),()=>i(n,r)},i=(n,e)=>{if(!e){s.delete(n);return}let t=s.get(n);t&&t.delete(e)};return{onMessage:c,offMessage:i,emitMessage:(n,e)=>{let t=s.get(n);if(t)return t.forEach(r=>r(e)),!0}}},w=(s,c=["__AllowedOrigins__"])=>{if(!s.contentWindow)throw new Error("iframe contentWindow is null");let{onMessage:i,offMessage:g,emitMessage:n}=l(),e=m({messenger:new d({remoteWindow:s.contentWindow,allowedOrigins:c}),channel:"iframe-bridge-channel",methods:{onMessage(o,a){return n(o,a)}}}),t=!1;return e.promise.then(()=>{t=!0}),{api:new Proxy({},{get(o,a){return async(...f)=>await e.promise.then(u=>u[a](...f))}}),onMessage:i,offMessage:g,isInit:()=>t,onInit(o){if(t){o();return}e.promise.then(()=>{o()})},destroy:e.destroy}},h={create:w};export{w as create,h as default};
|