@opensea/vessel
Advanced tools
Comparing version 0.0.4 to 0.0.5
var O = Object.defineProperty; | ||
var C = (s, e, t) => e in s ? O(s, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : s[e] = t; | ||
var r = (s, e, t) => (C(s, typeof e != "symbol" ? e + "" : e, t), t); | ||
const d = /* @__PURE__ */ new Map(); | ||
const c = /* @__PURE__ */ new Map(); | ||
function k(s, e, t) { | ||
const n = d.get(s); | ||
const n = c.get(s); | ||
n && (n.timeout && clearTimeout(n.timeout), n.reject( | ||
new Error("[Vessel] Same action fired again. Keeping only latest.") | ||
), d.delete(s)), d.set(s, e), typeof t == "number" && t > 0 && (e.timeout = setTimeout(() => { | ||
), c.delete(s)), c.set(s, e), typeof t == "number" && t > 0 && (e.timeout = setTimeout(() => { | ||
u(s), e.reject(new Error("[Vessel] Action timed out.")); | ||
@@ -14,13 +14,13 @@ }, t)); | ||
function u(s) { | ||
const e = d.get(s); | ||
e && (e.timeout && clearTimeout(e.timeout), d.delete(s)); | ||
const e = c.get(s); | ||
e && (e.timeout && clearTimeout(e.timeout), c.delete(s)); | ||
} | ||
function M(s) { | ||
return c.get(s); | ||
} | ||
function b(s) { | ||
return d.get(s); | ||
} | ||
function M(s) { | ||
return `${s ? `[VESSEL-${s.toUpperCase()}]:` : "[VESSEL]:"}`.trimStart(); | ||
} | ||
function f(s = "log", e) { | ||
const t = M(e == null ? void 0 : e.scope); | ||
const t = b(e == null ? void 0 : e.scope); | ||
return (...n) => { | ||
@@ -37,5 +37,5 @@ e != null && e.debug && console[s](t, ...n); | ||
} | ||
class c extends Error { | ||
class d extends Error { | ||
constructor(e, t) { | ||
super(`${M(t)} ${e}`), this.name = "VesselError"; | ||
super(`${b(t)} ${e}`), this.name = "VesselError"; | ||
} | ||
@@ -56,3 +56,3 @@ } | ||
var i = /* @__PURE__ */ ((s) => (s.Handshake = "handshake", s.HandshakeReply = "handshake-reply", s.Message = "message", s.MessageReply = "message-reply", s.Close = "close", s))(i || {}); | ||
class l { | ||
class h { | ||
constructor(e, t) { | ||
@@ -80,3 +80,3 @@ r(this, "type"); | ||
if (s && typeof s == "object" && "from" in s && s.from === e && "type" in s && Object.values(i).includes(s.type) && "id" in s && "operation" in s) | ||
return new l(s.type, { | ||
return new h(s.type, { | ||
id: s.id, | ||
@@ -88,3 +88,3 @@ from: s.from, | ||
}); | ||
throw new c("Invalid message."); | ||
throw new d("Invalid message."); | ||
} | ||
@@ -94,3 +94,3 @@ function R(s, e, t) { | ||
return S(s.data, t ?? g); | ||
throw new c("Invalid message event origin."); | ||
throw new d("Invalid message event origin."); | ||
} | ||
@@ -116,8 +116,8 @@ class w { | ||
this.subscriptions[e].forEach((o) => { | ||
o(t, (a, h) => { | ||
o(t, (a, l) => { | ||
n( | ||
new l(i.MessageReply, { | ||
new h(i.MessageReply, { | ||
operation: t.operation, | ||
payload: a, | ||
metadata: h | ||
metadata: l | ||
}) | ||
@@ -148,3 +148,3 @@ ); | ||
this.log.info(`Received handshake from ${this.parentOrigin}`); | ||
const t = new l(i.HandshakeReply, { | ||
const t = new h(i.HandshakeReply, { | ||
operation: e.operation | ||
@@ -162,3 +162,3 @@ }); | ||
try { | ||
const n = b(e.operation); | ||
const n = M(e.operation); | ||
if (n) { | ||
@@ -179,5 +179,5 @@ this.log.info(`Resolving action ${e.operation}`); | ||
if (!this.parent) | ||
throw new c("Parent frame not found."); | ||
throw new d("Parent frame not found."); | ||
if (this.closed) | ||
throw new c("Cannot send message, frame is closed."); | ||
throw new d("Cannot send message, frame is closed."); | ||
this.parent.postMessage(e.toObject(), this.parentOrigin); | ||
@@ -195,9 +195,9 @@ } | ||
return new Promise((o, a) => { | ||
const h = new l(i.Message, { | ||
const l = new h(i.Message, { | ||
payload: e, | ||
metadata: t | ||
}); | ||
k(h.operation, { resolve: o, reject: a }, n); | ||
k(l.operation, { resolve: o, reject: a }, n); | ||
try { | ||
this.sendMessage(h); | ||
this.sendMessage(l); | ||
} catch (p) { | ||
@@ -214,9 +214,7 @@ this.log.error("Error sending message to parent", p), a(p); | ||
emit(e, t) { | ||
if (this.closed) | ||
throw new c("Cannot emit message, frame is closed."); | ||
const n = new l(i.Message, { | ||
const n = new h(i.Message, { | ||
payload: e, | ||
metadata: t | ||
}); | ||
this.parent.postMessage(n.toObject(), this.parentOrigin); | ||
this.sendMessage(n); | ||
} | ||
@@ -238,3 +236,3 @@ on(e, t) { | ||
this.closed = !0, window.removeEventListener("message", this.onMessage); | ||
const e = new l(i.Close); | ||
const e = new h(i.Close); | ||
this.parent.postMessage(e.toObject(), this.parentOrigin); | ||
@@ -271,3 +269,3 @@ } | ||
e += 1; | ||
const n = new l(i.Handshake); | ||
const n = new h(i.Handshake); | ||
this.handshakeOperation = n.operation, this.sendMessage(n); | ||
@@ -291,8 +289,8 @@ } | ||
this.subscriptions[e].forEach((o) => { | ||
o(t, (a, h) => { | ||
o(t, (a, l) => { | ||
n( | ||
new l(i.MessageReply, { | ||
new h(i.MessageReply, { | ||
operation: t.operation, | ||
payload: a, | ||
metadata: h | ||
metadata: l | ||
}) | ||
@@ -335,3 +333,3 @@ ); | ||
try { | ||
const n = b(e.operation); | ||
const n = M(e.operation); | ||
if (n) { | ||
@@ -352,5 +350,5 @@ this.log.info(`Resolving action ${e.operation}`); | ||
if (!this.child) | ||
throw new c("Child frame not found."); | ||
throw new d("Child frame not found."); | ||
if (e.type !== i.Handshake && !this.connected) | ||
throw new c("Not connected to child frame."); | ||
throw new d("Not connected to child frame."); | ||
this.child.postMessage(e.toObject(), this.childOrigin); | ||
@@ -368,9 +366,9 @@ } | ||
return new Promise((o, a) => { | ||
const h = new l(i.Message, { | ||
const l = new h(i.Message, { | ||
payload: e, | ||
metadata: t | ||
}); | ||
k(h.operation, { resolve: o, reject: a }, n); | ||
k(l.operation, { resolve: o, reject: a }, n); | ||
try { | ||
this.sendMessage(h); | ||
this.sendMessage(l); | ||
} catch (p) { | ||
@@ -381,2 +379,14 @@ this.log.error("Error sending message to child", p), a(p); | ||
} | ||
/** | ||
* Emit a message to the parent frame and don't wait for a reply. | ||
* @param payload The payload to send to the parent frame | ||
* @param metadata The metadata to send to the parent frame | ||
*/ | ||
emit(e, t) { | ||
const n = new h(i.Message, { | ||
payload: e, | ||
metadata: t | ||
}); | ||
this.sendMessage(n); | ||
} | ||
connect() { | ||
@@ -383,0 +393,0 @@ this.log.info(`Connecting to child iframe ${this.childUrl}`), this.frame.addEventListener("load", this.startHandshake.bind(this)), this.frame.src = this.childUrl; |
@@ -1,1 +0,1 @@ | ||
(function(h,a){typeof exports=="object"&&typeof module<"u"?a(exports):typeof define=="function"&&define.amd?define(["exports"],a):(h=typeof globalThis<"u"?globalThis:h||self,a(h.Vessel={}))})(this,function(h){"use strict";var H=Object.defineProperty;var F=(h,a,p)=>a in h?H(h,a,{enumerable:!0,configurable:!0,writable:!0,value:p}):h[a]=p;var r=(h,a,p)=>(F(h,typeof a!="symbol"?a+"":a,p),p);const a=new Map;function p(s,e,t){const n=a.get(s);n&&(n.timeout&&clearTimeout(n.timeout),n.reject(new Error("[Vessel] Same action fired again. Keeping only latest.")),a.delete(s)),a.set(s,e),typeof t=="number"&&t>0&&(e.timeout=setTimeout(()=>{g(s),e.reject(new Error("[Vessel] Action timed out."))},t))}function g(s){const e=a.get(s);e&&(e.timeout&&clearTimeout(e.timeout),a.delete(s))}function M(s){return a.get(s)}function m(s){return`${s?`[VESSEL-${s.toUpperCase()}]:`:"[VESSEL]:"}`.trimStart()}function w(s="log",e){const t=m(e==null?void 0:e.scope);return(...n)=>{e!=null&&e.debug&&console[s](t,...n)}}function E(s){return{info:w("info",s),warn:w("warn",s),error:w("error",s)}}class f extends Error{constructor(e,t){super(`${m(t)} ${e}`),this.name="VesselError"}}let R=(s=21)=>crypto.getRandomValues(new Uint8Array(s)).reduce((e,t)=>(t&=63,t<36?e+=t.toString(36):t<62?e+=(t-26).toString(36).toUpperCase():t>62?e+="-":e+="_",e),"");const y="application/x-opensea-vessel-v1+json";function C(){return`op-${R()}`}function I(){return`msg-${R()}`}function S(s){const e=new URL(s);return`${e.protocol}//${e.host}`}var i=(s=>(s.Handshake="handshake",s.HandshakeReply="handshake-reply",s.Message="message",s.MessageReply="message-reply",s.Close="close",s))(i||{});class c{constructor(e,t){r(this,"type");r(this,"id");r(this,"from");r(this,"operation");r(this,"payload");r(this,"metadata");this.type=e,this.id=(t==null?void 0:t.id)??I(),this.from=(t==null?void 0:t.from)??y,this.operation=(t==null?void 0:t.operation)??C(),this.payload=t==null?void 0:t.payload,this.metadata=t==null?void 0:t.metadata}toObject(){return{type:this.type,id:this.id,from:this.from,operation:this.operation,payload:this.payload,metadata:this.metadata}}}function $(s,e=y){if(s&&typeof s=="object"&&"from"in s&&s.from===e&&"type"in s&&Object.values(i).includes(s.type)&&"id"in s&&"operation"in s)return new c(s.type,{id:s.id,from:s.from,operation:s.operation,payload:s.payload,metadata:s.metadata});throw new f("Invalid message.")}function O(s,e,t){if(e==="*"||s.origin===e)return $(s.data,t??y);throw new f("Invalid message event origin.")}class v{constructor(e){r(this,"log");r(this,"parent",window.parent);r(this,"subscriptions");r(this,"closed",!1);r(this,"parentOrigin");this.parentOrigin=e.parentOrigin,this.subscriptions={[i.Message]:[],[i.Close]:[]},this.log=E({debug:e.debug,scope:"CHILD"}),this.onMessage=this.onMessage.bind(this),window.addEventListener("message",this.onMessage,!1)}callSubscriptions(e,t){const n=this.sendMessage.bind(this);if(e===i.Close){this.close(),this.subscriptions[e].forEach(o=>o(t));return}this.subscriptions[e].forEach(o=>{o(t,(l,d)=>{n(new c(i.MessageReply,{operation:t.operation,payload:l,metadata:d}))})})}onMessage(e){try{const t=O(e,this.parentOrigin);switch(t.type){case i.Handshake:this.sendHandshakeReply(t);return;case i.Message:this.callSubscriptions(i.Message,t);return;case i.MessageReply:this.resolveReply(t);return}}catch(t){this.log.error("Error parsing message from parent",t)}}sendHandshakeReply(e){this.log.info(`Received handshake from ${this.parentOrigin}`);const t=new c(i.HandshakeReply,{operation:e.operation});try{this.parent.postMessage(t.toObject(),this.parentOrigin)}catch(n){this.log.error("Error sending handshake reply",n)}}resolveReply(e){var t;this.log.info(`Received reply for action ${e.operation}`);try{const n=M(e.operation);if(n){this.log.info(`Resolving action ${e.operation}`);const{resolve:o,reject:l}=n;if(g(e.operation),(t=e.payload)!=null&&t.error){l(e.payload.error);return}o(e.payload)}}catch(n){this.log.error("Error resolving reply",n)}}sendMessage(e){if(!this.parent)throw new f("Parent frame not found.");if(this.closed)throw new f("Cannot send message, frame is closed.");this.parent.postMessage(e.toObject(),this.parentOrigin)}async send(e,t,n=5e3){return new Promise((o,l)=>{const d=new c(i.Message,{payload:e,metadata:t});p(d.operation,{resolve:o,reject:l},n);try{this.sendMessage(d)}catch(u){this.log.error("Error sending message to parent",u),l(u)}})}emit(e,t){if(this.closed)throw new f("Cannot emit message, frame is closed.");const n=new c(i.Message,{payload:e,metadata:t});this.parent.postMessage(n.toObject(),this.parentOrigin)}on(e,t){return this.subscriptions[e].push(t),()=>{this.off.call(this,e,t)}}once(e,t){const n=this.on(e,(...o)=>{n(),t(...o)})}off(e,t){this.subscriptions[e]=this.subscriptions[e].filter(n=>n!==t)}close(){this.closed=!0,window.removeEventListener("message",this.onMessage);const e=new c(i.Close);this.parent.postMessage(e.toObject(),this.parentOrigin)}}class b{constructor(e){r(this,"parentFrame");r(this,"child");r(this,"frame");r(this,"handshakeOperation");r(this,"handshakeInterval");r(this,"subscriptions");r(this,"log");r(this,"childOrigin");r(this,"childUrl");r(this,"connected");this.frame=e.frame,this.parentFrame=window,this.child=null,this.childUrl=e.url,this.childOrigin=S(e.url),this.connected=!1,this.handshakeOperation=null,this.handshakeInterval=null,this.subscriptions={[i.Message]:[],[i.Close]:[]},this.log=E({debug:e.debug,scope:"PARENT"}),this.parentFrame.addEventListener("message",this.onMessage.bind(this),!1)}startHandshake(){if(this.log.info(`Sending handshake to ${this.childUrl}`),this.child=this.frame.contentWindow,!this.child)throw new Error("Child frame not found");let e=0;const t=()=>{if(this.log.info("Attempting handshake..."),this.child){e+=1;const n=new c(i.Handshake);this.handshakeOperation=n.operation,this.sendMessage(n)}};t(),this.handshakeInterval=window.setInterval(()=>{if(e>=5){this.log.warn("Handshake failed after 5 attempts. Giving up."),this.handshakeInterval&&window.clearInterval(this.handshakeInterval);return}t()},500)}callSubscriptions(e,t){const n=this.sendMessage.bind(this);if(e===i.Close){this.close(),this.subscriptions[e].forEach(o=>o(t));return}this.subscriptions[e].forEach(o=>{o(t,(l,d)=>{n(new c(i.MessageReply,{operation:t.operation,payload:l,metadata:d}))})})}handleHandshakeReply(e){if(this.log.info(`Received handshake reply from ${this.childUrl}`),e.operation!==this.handshakeOperation)throw new Error("Handshake reply operation does not match");this.handshakeInterval&&window.clearInterval(this.handshakeInterval),this.connected=!0}onMessage(e){try{const t=O(e,this.childOrigin);switch(t.type){case i.HandshakeReply:this.handleHandshakeReply(t);break;case i.Message:this.callSubscriptions(i.Message,t);break;case i.MessageReply:this.resolveReply(t);break;case i.Close:this.callSubscriptions(i.Close,t);break;default:this.log.warn(`Unknown message type: ${t.type}`)}}catch(t){this.log.error("Error handling message",t)}}resolveReply(e){var t;this.log.info(`Received reply for action ${e.operation}`);try{const n=M(e.operation);if(n){this.log.info(`Resolving action ${e.operation}`);const{resolve:o,reject:l}=n;if(g(e.operation),(t=e.payload)!=null&&t.error){l(e.payload.error);return}o(e.payload)}}catch(n){this.log.error("Error resolving reply",n)}}sendMessage(e){if(!this.child)throw new f("Child frame not found.");if(e.type!==i.Handshake&&!this.connected)throw new f("Not connected to child frame.");this.child.postMessage(e.toObject(),this.childOrigin)}async send(e,t,n=5e3){return new Promise((o,l)=>{const d=new c(i.Message,{payload:e,metadata:t});p(d.operation,{resolve:o,reject:l},n);try{this.sendMessage(d)}catch(u){this.log.error("Error sending message to child",u),l(u)}})}connect(){this.log.info(`Connecting to child iframe ${this.childUrl}`),this.frame.addEventListener("load",this.startHandshake.bind(this)),this.frame.src=this.childUrl}on(e,t){return this.subscriptions[e].push(t),()=>{this.off.call(this,e,t)}}once(e,t){const n=this.on(e,(...o)=>{n(),t(...o)})}off(e,t){this.subscriptions[e]=this.subscriptions[e].filter(n=>n!==t)}close(){var e;this.log.info("Closing frames"),this.subscriptions[i.Message]=[],this.subscriptions[i.Close]=[],this.handshakeOperation=null,this.handshakeInterval&&window.clearInterval(this.handshakeInterval),this.connected=!1,(e=this.frame.parentElement)==null||e.removeChild(this.frame)}}class k{static createParentFrame(e){return new b(e)}static createChildFrame(e){return new v(e)}}r(k,"ParentFrame",b),r(k,"ChildFrame",v),h.ChildFrame=v,h.MessageType=i,h.ParentFrame=b,h.Vessel=k,Object.defineProperty(h,Symbol.toStringTag,{value:"Module"})}); | ||
(function(h,a){typeof exports=="object"&&typeof module<"u"?a(exports):typeof define=="function"&&define.amd?define(["exports"],a):(h=typeof globalThis<"u"?globalThis:h||self,a(h.Vessel={}))})(this,function(h){"use strict";var H=Object.defineProperty;var F=(h,a,p)=>a in h?H(h,a,{enumerable:!0,configurable:!0,writable:!0,value:p}):h[a]=p;var r=(h,a,p)=>(F(h,typeof a!="symbol"?a+"":a,p),p);const a=new Map;function p(s,e,t){const n=a.get(s);n&&(n.timeout&&clearTimeout(n.timeout),n.reject(new Error("[Vessel] Same action fired again. Keeping only latest.")),a.delete(s)),a.set(s,e),typeof t=="number"&&t>0&&(e.timeout=setTimeout(()=>{g(s),e.reject(new Error("[Vessel] Action timed out."))},t))}function g(s){const e=a.get(s);e&&(e.timeout&&clearTimeout(e.timeout),a.delete(s))}function b(s){return a.get(s)}function m(s){return`${s?`[VESSEL-${s.toUpperCase()}]:`:"[VESSEL]:"}`.trimStart()}function w(s="log",e){const t=m(e==null?void 0:e.scope);return(...n)=>{e!=null&&e.debug&&console[s](t,...n)}}function E(s){return{info:w("info",s),warn:w("warn",s),error:w("error",s)}}class f extends Error{constructor(e,t){super(`${m(t)} ${e}`),this.name="VesselError"}}let R=(s=21)=>crypto.getRandomValues(new Uint8Array(s)).reduce((e,t)=>(t&=63,t<36?e+=t.toString(36):t<62?e+=(t-26).toString(36).toUpperCase():t>62?e+="-":e+="_",e),"");const y="application/x-opensea-vessel-v1+json";function C(){return`op-${R()}`}function I(){return`msg-${R()}`}function S(s){const e=new URL(s);return`${e.protocol}//${e.host}`}var i=(s=>(s.Handshake="handshake",s.HandshakeReply="handshake-reply",s.Message="message",s.MessageReply="message-reply",s.Close="close",s))(i||{});class c{constructor(e,t){r(this,"type");r(this,"id");r(this,"from");r(this,"operation");r(this,"payload");r(this,"metadata");this.type=e,this.id=(t==null?void 0:t.id)??I(),this.from=(t==null?void 0:t.from)??y,this.operation=(t==null?void 0:t.operation)??C(),this.payload=t==null?void 0:t.payload,this.metadata=t==null?void 0:t.metadata}toObject(){return{type:this.type,id:this.id,from:this.from,operation:this.operation,payload:this.payload,metadata:this.metadata}}}function $(s,e=y){if(s&&typeof s=="object"&&"from"in s&&s.from===e&&"type"in s&&Object.values(i).includes(s.type)&&"id"in s&&"operation"in s)return new c(s.type,{id:s.id,from:s.from,operation:s.operation,payload:s.payload,metadata:s.metadata});throw new f("Invalid message.")}function O(s,e,t){if(e==="*"||s.origin===e)return $(s.data,t??y);throw new f("Invalid message event origin.")}class v{constructor(e){r(this,"log");r(this,"parent",window.parent);r(this,"subscriptions");r(this,"closed",!1);r(this,"parentOrigin");this.parentOrigin=e.parentOrigin,this.subscriptions={[i.Message]:[],[i.Close]:[]},this.log=E({debug:e.debug,scope:"CHILD"}),this.onMessage=this.onMessage.bind(this),window.addEventListener("message",this.onMessage,!1)}callSubscriptions(e,t){const n=this.sendMessage.bind(this);if(e===i.Close){this.close(),this.subscriptions[e].forEach(o=>o(t));return}this.subscriptions[e].forEach(o=>{o(t,(l,d)=>{n(new c(i.MessageReply,{operation:t.operation,payload:l,metadata:d}))})})}onMessage(e){try{const t=O(e,this.parentOrigin);switch(t.type){case i.Handshake:this.sendHandshakeReply(t);return;case i.Message:this.callSubscriptions(i.Message,t);return;case i.MessageReply:this.resolveReply(t);return}}catch(t){this.log.error("Error parsing message from parent",t)}}sendHandshakeReply(e){this.log.info(`Received handshake from ${this.parentOrigin}`);const t=new c(i.HandshakeReply,{operation:e.operation});try{this.parent.postMessage(t.toObject(),this.parentOrigin)}catch(n){this.log.error("Error sending handshake reply",n)}}resolveReply(e){var t;this.log.info(`Received reply for action ${e.operation}`);try{const n=b(e.operation);if(n){this.log.info(`Resolving action ${e.operation}`);const{resolve:o,reject:l}=n;if(g(e.operation),(t=e.payload)!=null&&t.error){l(e.payload.error);return}o(e.payload)}}catch(n){this.log.error("Error resolving reply",n)}}sendMessage(e){if(!this.parent)throw new f("Parent frame not found.");if(this.closed)throw new f("Cannot send message, frame is closed.");this.parent.postMessage(e.toObject(),this.parentOrigin)}async send(e,t,n=5e3){return new Promise((o,l)=>{const d=new c(i.Message,{payload:e,metadata:t});p(d.operation,{resolve:o,reject:l},n);try{this.sendMessage(d)}catch(u){this.log.error("Error sending message to parent",u),l(u)}})}emit(e,t){const n=new c(i.Message,{payload:e,metadata:t});this.sendMessage(n)}on(e,t){return this.subscriptions[e].push(t),()=>{this.off.call(this,e,t)}}once(e,t){const n=this.on(e,(...o)=>{n(),t(...o)})}off(e,t){this.subscriptions[e]=this.subscriptions[e].filter(n=>n!==t)}close(){this.closed=!0,window.removeEventListener("message",this.onMessage);const e=new c(i.Close);this.parent.postMessage(e.toObject(),this.parentOrigin)}}class M{constructor(e){r(this,"parentFrame");r(this,"child");r(this,"frame");r(this,"handshakeOperation");r(this,"handshakeInterval");r(this,"subscriptions");r(this,"log");r(this,"childOrigin");r(this,"childUrl");r(this,"connected");this.frame=e.frame,this.parentFrame=window,this.child=null,this.childUrl=e.url,this.childOrigin=S(e.url),this.connected=!1,this.handshakeOperation=null,this.handshakeInterval=null,this.subscriptions={[i.Message]:[],[i.Close]:[]},this.log=E({debug:e.debug,scope:"PARENT"}),this.parentFrame.addEventListener("message",this.onMessage.bind(this),!1)}startHandshake(){if(this.log.info(`Sending handshake to ${this.childUrl}`),this.child=this.frame.contentWindow,!this.child)throw new Error("Child frame not found");let e=0;const t=()=>{if(this.log.info("Attempting handshake..."),this.child){e+=1;const n=new c(i.Handshake);this.handshakeOperation=n.operation,this.sendMessage(n)}};t(),this.handshakeInterval=window.setInterval(()=>{if(e>=5){this.log.warn("Handshake failed after 5 attempts. Giving up."),this.handshakeInterval&&window.clearInterval(this.handshakeInterval);return}t()},500)}callSubscriptions(e,t){const n=this.sendMessage.bind(this);if(e===i.Close){this.close(),this.subscriptions[e].forEach(o=>o(t));return}this.subscriptions[e].forEach(o=>{o(t,(l,d)=>{n(new c(i.MessageReply,{operation:t.operation,payload:l,metadata:d}))})})}handleHandshakeReply(e){if(this.log.info(`Received handshake reply from ${this.childUrl}`),e.operation!==this.handshakeOperation)throw new Error("Handshake reply operation does not match");this.handshakeInterval&&window.clearInterval(this.handshakeInterval),this.connected=!0}onMessage(e){try{const t=O(e,this.childOrigin);switch(t.type){case i.HandshakeReply:this.handleHandshakeReply(t);break;case i.Message:this.callSubscriptions(i.Message,t);break;case i.MessageReply:this.resolveReply(t);break;case i.Close:this.callSubscriptions(i.Close,t);break;default:this.log.warn(`Unknown message type: ${t.type}`)}}catch(t){this.log.error("Error handling message",t)}}resolveReply(e){var t;this.log.info(`Received reply for action ${e.operation}`);try{const n=b(e.operation);if(n){this.log.info(`Resolving action ${e.operation}`);const{resolve:o,reject:l}=n;if(g(e.operation),(t=e.payload)!=null&&t.error){l(e.payload.error);return}o(e.payload)}}catch(n){this.log.error("Error resolving reply",n)}}sendMessage(e){if(!this.child)throw new f("Child frame not found.");if(e.type!==i.Handshake&&!this.connected)throw new f("Not connected to child frame.");this.child.postMessage(e.toObject(),this.childOrigin)}async send(e,t,n=5e3){return new Promise((o,l)=>{const d=new c(i.Message,{payload:e,metadata:t});p(d.operation,{resolve:o,reject:l},n);try{this.sendMessage(d)}catch(u){this.log.error("Error sending message to child",u),l(u)}})}emit(e,t){const n=new c(i.Message,{payload:e,metadata:t});this.sendMessage(n)}connect(){this.log.info(`Connecting to child iframe ${this.childUrl}`),this.frame.addEventListener("load",this.startHandshake.bind(this)),this.frame.src=this.childUrl}on(e,t){return this.subscriptions[e].push(t),()=>{this.off.call(this,e,t)}}once(e,t){const n=this.on(e,(...o)=>{n(),t(...o)})}off(e,t){this.subscriptions[e]=this.subscriptions[e].filter(n=>n!==t)}close(){var e;this.log.info("Closing frames"),this.subscriptions[i.Message]=[],this.subscriptions[i.Close]=[],this.handshakeOperation=null,this.handshakeInterval&&window.clearInterval(this.handshakeInterval),this.connected=!1,(e=this.frame.parentElement)==null||e.removeChild(this.frame)}}class k{static createParentFrame(e){return new M(e)}static createChildFrame(e){return new v(e)}}r(k,"ParentFrame",M),r(k,"ChildFrame",v),h.ChildFrame=v,h.MessageType=i,h.ParentFrame=M,h.Vessel=k,Object.defineProperty(h,Symbol.toStringTag,{value:"Module"})}); |
@@ -36,2 +36,8 @@ import { Message, MessageMetadataType, MessagePayloadType, MessageType } from "./utils/messaging"; | ||
send<P extends MessagePayloadType, R extends MessagePayloadType, M extends MessageMetadataType>(payload: P, metadata?: M, timeout?: number): Promise<R>; | ||
/** | ||
* Emit a message to the parent frame and don't wait for a reply. | ||
* @param payload The payload to send to the parent frame | ||
* @param metadata The metadata to send to the parent frame | ||
*/ | ||
emit<P extends MessagePayloadType, M extends MessageMetadataType>(payload: P, metadata?: M): void; | ||
connect(): void; | ||
@@ -38,0 +44,0 @@ on(type: MessageType.Message, fn: ActionSubscriptionFn): () => void; |
{ | ||
"name": "@opensea/vessel", | ||
"version": "0.0.4", | ||
"version": "0.0.5", | ||
"description": "🚢 Vessel: a promise-based postMessage library that sails your data smoothly across the Opensea.", | ||
@@ -5,0 +5,0 @@ "files": [ |
@@ -355,3 +355,3 @@ import { | ||
expect(() => cf.emit({ data: "test" })).toThrowErrorMatchingInlineSnapshot( | ||
'"[VESSEL]: Cannot emit message, frame is closed."', | ||
'"[VESSEL]: Cannot send message, frame is closed."', | ||
) | ||
@@ -358,0 +358,0 @@ }) |
@@ -188,6 +188,2 @@ import { ActionSubscriptionFn, CloseSubscriptionFn } from "./parent" | ||
) { | ||
if (this.closed) { | ||
throw new VesselError("Cannot emit message, frame is closed.") | ||
} | ||
const message = new Message<P, M>(MessageType.Message, { | ||
@@ -198,3 +194,3 @@ payload, | ||
this.parent.postMessage(message.toObject(), this.parentOrigin) | ||
this.sendMessage(message) | ||
} | ||
@@ -201,0 +197,0 @@ |
@@ -246,2 +246,19 @@ import { | ||
/** | ||
* Emit a message to the parent frame and don't wait for a reply. | ||
* @param payload The payload to send to the parent frame | ||
* @param metadata The metadata to send to the parent frame | ||
*/ | ||
emit<P extends MessagePayloadType, M extends MessageMetadataType>( | ||
payload: P, | ||
metadata?: M, | ||
) { | ||
const message = new Message<P, M>(MessageType.Message, { | ||
payload, | ||
metadata, | ||
}) | ||
this.sendMessage(message) | ||
} | ||
connect() { | ||
@@ -248,0 +265,0 @@ this.log.info(`Connecting to child iframe ${this.childUrl}`) |
75002
1989