@alihaiderrana/email-builder-sdk 0.1.6 → 0.1.7

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 CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var D=Object.defineProperty;var ie=Object.getOwnPropertyDescriptor;var ae=Object.getOwnPropertyNames;var se=Object.prototype.hasOwnProperty;var oe=(r,n)=>{for(var i in n)D(r,i,{get:n[i],enumerable:!0})},le=(r,n,i,l)=>{if(n&&typeof n=="object"||typeof n=="function")for(let d of ae(n))!se.call(r,d)&&d!==i&&D(r,d,{get:()=>n[d],enumerable:!(l=ie(n,d))||l.enumerable});return r};var ue=r=>le(D({},"__esModule",{value:!0}),r);var Ee={};oe(Ee,{EMAIL_BUILDER_PROTOCOL_VERSION:()=>G,EmailBuilder:()=>Me,createMessageMeta:()=>k,isMessageLike:()=>h});module.exports=ue(Ee);var e=require("react");var G="1.0.0",ce=["INIT","READY","CHANGE","SAVE","UPLOAD","UPLOAD_SUCCESS","AUTH_ERROR"];function h(r){if(typeof r!="object"||r===null)return!1;let n=r;if(typeof n.type!="string"||!ce.includes(n.type))return!1;if("meta"in n&&n.meta!==void 0){let i=n.meta;if(i.id&&typeof i.id!="string"||i.correlationId&&typeof i.correlationId!="string"||i.version&&typeof i.version!="string"||i.sentAt&&typeof i.sentAt!="number")return!1}return!0}function k(r){return{id:typeof crypto!="undefined"&&"randomUUID"in crypto?crypto.randomUUID():Math.random().toString(36).slice(2),correlationId:r,version:G,sentAt:Date.now()}}function z(r,n){if(n){let l=new URL(n);if(l.origin==="null")throw new Error("allowedOrigin must resolve to a valid origin");return l.origin}let i;try{i=new URL(r)}catch{throw new Error("EmailBuilder `src` must be an absolute URL (e.g. https://example.com)")}if(!i.origin||i.origin==="null")throw new Error("EmailBuilder requires an absolute src URL with a valid origin");return i.origin}function H(r,n){let i=k(n);return{...r,meta:i}}function C(r){return JSON.stringify(r!=null?r:null)}var E=require("react/jsx-runtime"),de="allow-scripts allow-same-origin allow-forms",fe="<h1>Hello World</h1><p>Start building your email template.</p>",pe={position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",fontSize:"0.875rem",fontWeight:500,background:"linear-gradient(135deg, rgba(9,9,9,0.65), rgba(33,33,33,0.85))",color:"#fff",zIndex:2},ge={border:"none",width:"100%",height:"100%"};function ye(r,n){if(!n||!n.trim())return r;try{let i=new URL(r,typeof window!="undefined"?window.location.href:"https://example.com");return i.searchParams.set("embedToken",n),i.toString()}catch{let i=r.includes("?")?"&":"?";return`${r}${i}embedToken=${encodeURIComponent(n)}`}}function me({src:r,initialHtml:n,embedToken:i,templateId:l,config:d,className:K,style:q,iframeTitle:$="Email Builder",sandbox:j=de,onChange:w,onSave:S,onUpload:x,onReady:T,onStatusChange:R,onAuthError:U,allowedOrigin:_},J){let Q=(0,e.useMemo)(()=>ye(r,i),[r,i]),A=(0,e.useRef)(null),o=(0,e.useRef)(null),f=(0,e.useRef)(!1),y=(0,e.useRef)("loading"),[X,N]=(0,e.useState)("loading"),[Z,ee]=(0,e.useState)(0),P=(0,e.useRef)([]),m=(0,e.useRef)(null),u=(0,e.useRef)(null),b=typeof n=="string"?n:l?"":fe,W={html:b,config:d,...l?{templateId:l}:{}},F=(0,e.useRef)(C(W)),I=(0,e.useRef)({type:"INIT",payload:W}),re=(0,e.useMemo)(()=>z(r,_),[r,_]),B=(0,e.useCallback)(()=>"*",[]),c=(0,e.useCallback)(t=>{y.current!==t&&(y.current=t,N(t),R==null||R(t))},[R]),g=(0,e.useCallback)((t,a)=>{var p,M;let s=(M=(p=A.current)==null?void 0:p.contentWindow)!=null?M:o.current;if(s&&(o.current=s),!o.current||!f.current){P.current.push({message:t,correlationId:a});return}o.current.postMessage(H(t,a),B())},[B]),V=(0,e.useCallback)(()=>{if(!f.current||!o.current)return;let t=[...P.current];P.current=[],t.forEach(({message:a,correlationId:s})=>{var p;(p=o.current)==null||p.postMessage(H(a,s),B())})},[B]),L=(0,e.useCallback)(()=>{f.current||(u.current&&(window.clearTimeout(u.current),u.current=null),f.current=!0,c("ready"),T==null||T(),g(I.current),V())},[V,T,g,c]),Y=(0,e.useCallback)(async t=>{var a;if(t.type==="UPLOAD"){if(!x){console.warn("[EmailBuilderSDK] Upload requested but no onUpload handler is configured.");return}try{c("loading");let s=await x(t.payload.file);g({type:"UPLOAD_SUCCESS",payload:{url:s}},(a=t.meta)==null?void 0:a.id)}catch(s){c("error"),console.error("[EmailBuilderSDK] Upload handler failed",s)}finally{y.current!=="error"&&c("ready")}}},[x,g,c]),O=(0,e.useCallback)(t=>{var p,M,v;let a=(M=(p=A.current)==null?void 0:p.contentWindow)!=null?M:o.current;if(!a||t.source!==a||!h(t.data))return;if(!m.current)m.current=t.origin;else if(t.origin!==m.current)return;let s=t.data;switch(t.source&&t.source!==o.current&&(o.current=t.source),s.type){case"READY":L();break;case"CHANGE":w==null||w(s.payload.html);break;case"SAVE":S==null||S(s.payload.html);break;case"UPLOAD":Y(s);break;case"AUTH_ERROR":{let ne=((v=s.payload)==null?void 0:v.message)||"Email builder authentication failed";y.current!=="error"&&(y.current="error",N("error"),U==null||U(ne));break}default:break}},[L,Y,w,S,U,c]);(0,e.useEffect)(()=>{if(typeof window!="undefined")return window.addEventListener("message",O),()=>{window.removeEventListener("message",O)}},[O]),(0,e.useEffect)(()=>{let t={html:b,config:d,...l?{templateId:l}:{}},a=C(t);I.current={type:"INIT",payload:t},a!==F.current&&f.current&&g(I.current),F.current=a},[d,b,g,l]);let te=(0,e.useCallback)(()=>{var t,a;if(o.current=(a=(t=A.current)==null?void 0:t.contentWindow)!=null?a:null,f.current=!1,m.current=null,c("loading"),o.current)try{o.current.postMessage(H(I.current),"*")}catch{}u.current&&window.clearTimeout(u.current),u.current=window.setTimeout(()=>{f.current||L()},4e3)},[re,L,c]);return(0,e.useImperativeHandle)(J,()=>({reload(){P.current=[],f.current=!1,o.current=null,m.current=null,u.current&&(window.clearTimeout(u.current),u.current=null),c("loading"),ee(t=>t+1)}}),[c]),(0,e.useEffect)(()=>()=>{u.current&&(window.clearTimeout(u.current),u.current=null)},[]),(0,E.jsxs)("div",{className:K,style:{position:"relative",width:"100%",height:"100%",...q},children:[(0,E.jsx)("iframe",{ref:A,src:Q,title:$,sandbox:j,style:ge,loading:"lazy",allowFullScreen:!0,onLoad:te},Z),X!=="ready"&&(0,E.jsx)("div",{style:pe,children:"Connecting to builder\u2026"})]})}var Me=(0,e.forwardRef)(me);0&&(module.exports={EMAIL_BUILDER_PROTOCOL_VERSION,EmailBuilder,createMessageMeta,isMessageLike});
1
+ "use strict";var D=Object.defineProperty;var ae=Object.getOwnPropertyDescriptor;var ie=Object.getOwnPropertyNames;var se=Object.prototype.hasOwnProperty;var oe=(r,n)=>{for(var a in n)D(r,a,{get:n[a],enumerable:!0})},le=(r,n,a,u)=>{if(n&&typeof n=="object"||typeof n=="function")for(let p of ie(n))!se.call(r,p)&&p!==a&&D(r,p,{get:()=>n[p],enumerable:!(u=ae(n,p))||u.enumerable});return r};var ue=r=>le(D({},"__esModule",{value:!0}),r);var Me={};oe(Me,{EMAIL_BUILDER_PROTOCOL_VERSION:()=>z,EmailBuilder:()=>we,createMessageMeta:()=>k,isMessageLike:()=>x});module.exports=ue(Me);var e=require("react");var z="1.0.0",ce=["INIT","READY","CHANGE","SAVE","UPLOAD","UPLOAD_SUCCESS","AUTH_ERROR"];function x(r){if(typeof r!="object"||r===null)return!1;let n=r;if(typeof n.type!="string"||!ce.includes(n.type))return!1;if("meta"in n&&n.meta!==void 0){let a=n.meta;if(a.id&&typeof a.id!="string"||a.correlationId&&typeof a.correlationId!="string"||a.version&&typeof a.version!="string"||a.sentAt&&typeof a.sentAt!="number")return!1}return!0}function k(r){return{id:typeof crypto!="undefined"&&"randomUUID"in crypto?crypto.randomUUID():Math.random().toString(36).slice(2),correlationId:r,version:z,sentAt:Date.now()}}function K(r,n){if(n){let u=new URL(n);if(u.origin==="null")throw new Error("allowedOrigin must resolve to a valid origin");return u.origin}let a;try{a=new URL(r)}catch{throw new Error("EmailBuilder `src` must be an absolute URL (e.g. https://example.com)")}if(!a.origin||a.origin==="null")throw new Error("EmailBuilder requires an absolute src URL with a valid origin");return a.origin}function T(r,n){let a=k(n);return{...r,meta:a}}function C(r){return JSON.stringify(r!=null?r:null)}var I=require("react/jsx-runtime"),de="allow-scripts allow-same-origin allow-forms",fe="<h1>Hello World</h1><p>Start building your email template.</p>",pe={position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",fontSize:"0.875rem",fontWeight:500,background:"linear-gradient(135deg, rgba(9,9,9,0.65), rgba(33,33,33,0.85))",color:"#fff",zIndex:2},ge={border:"none",width:"100%",height:"100%"};function me(r,n){if(!n||!n.trim())return r;try{let a=new URL(r,typeof window!="undefined"?window.location.href:"https://example.com");return a.searchParams.set("embedToken",n),a.toString()}catch{let a=r.includes("?")?"&":"?";return`${r}${a}embedToken=${encodeURIComponent(n)}`}}function ye({src:r,initialHtml:n,embedToken:a,templateId:u,config:p,className:q,style:$,iframeTitle:j="Email Builder",sandbox:J=de,onChange:R,onSave:U,onUpload:H,onReady:P,onStatusChange:A,onAuthError:m,allowedOrigin:_},Q){let X=(0,e.useMemo)(()=>me(r,a),[r,a]),B=(0,e.useRef)(null),l=(0,e.useRef)(null),g=(0,e.useRef)(!1),M=(0,e.useRef)("loading"),[Z,N]=(0,e.useState)("loading"),[ee,re]=(0,e.useState)(0),L=(0,e.useRef)([]),E=(0,e.useRef)(null),c=(0,e.useRef)(null),i=(0,e.useRef)(null),b=typeof n=="string"?n:u?"":fe,v={html:b,config:p,...u?{templateId:u}:{}},W=(0,e.useRef)(C(v)),S=(0,e.useRef)({type:"INIT",payload:v}),Ee=(0,e.useMemo)(()=>K(r,_),[r,_]),h=(0,e.useCallback)(()=>"*",[]),d=(0,e.useCallback)(t=>{M.current!==t&&(M.current=t,N(t),A==null||A(t))},[A]),w=(0,e.useCallback)((t,o)=>{var f,y;let s=(y=(f=B.current)==null?void 0:f.contentWindow)!=null?y:l.current;if(s&&(l.current=s),!l.current||!g.current){L.current.push({message:t,correlationId:o});return}l.current.postMessage(T(t,o),h())},[h]),F=(0,e.useCallback)(()=>{if(!g.current||!l.current)return;let t=[...L.current];L.current=[],t.forEach(({message:o,correlationId:s})=>{var f;(f=l.current)==null||f.postMessage(T(o,s),h())})},[h]),V=(0,e.useCallback)(()=>{g.current||(c.current&&(window.clearTimeout(c.current),c.current=null),i.current&&(window.clearInterval(i.current),i.current=null),g.current=!0,d("ready"),P==null||P(),w(S.current),F())},[F,P,w,d]),Y=(0,e.useCallback)(async t=>{var o;if(t.type==="UPLOAD"){if(!H){console.warn("[EmailBuilderSDK] Upload requested but no onUpload handler is configured.");return}try{d("loading");let s=await H(t.payload.file);w({type:"UPLOAD_SUCCESS",payload:{url:s}},(o=t.meta)==null?void 0:o.id)}catch(s){d("error"),console.error("[EmailBuilderSDK] Upload handler failed",s)}finally{M.current!=="error"&&d("ready")}}},[H,w,d]),O=(0,e.useCallback)(t=>{var f,y,G;let o=(y=(f=B.current)==null?void 0:f.contentWindow)!=null?y:l.current;if(!o||t.source!==o||!x(t.data))return;if(!E.current)E.current=t.origin;else if(t.origin!==E.current)return;let s=t.data;switch(t.source&&t.source!==l.current&&(l.current=t.source),s.type){case"READY":V();break;case"CHANGE":R==null||R(s.payload.html);break;case"SAVE":U==null||U(s.payload.html);break;case"UPLOAD":Y(s);break;case"AUTH_ERROR":{let ne=((G=s.payload)==null?void 0:G.message)||"Email builder authentication failed";M.current!=="error"&&(M.current="error",N("error"),m==null||m(ne));break}default:break}},[V,Y,R,U,m,d]);(0,e.useEffect)(()=>{if(typeof window!="undefined")return window.addEventListener("message",O),()=>{window.removeEventListener("message",O)}},[O]),(0,e.useEffect)(()=>{let t={html:b,config:p,...u?{templateId:u}:{}},o=C(t);S.current={type:"INIT",payload:t},o!==W.current&&g.current&&w(S.current),W.current=o},[p,b,w,u]);let te=(0,e.useCallback)(()=>{var s,f;if(l.current=(f=(s=B.current)==null?void 0:s.contentWindow)!=null?f:null,g.current=!1,E.current=null,d("loading"),l.current)try{l.current.postMessage(T(S.current),"*")}catch{}c.current&&window.clearTimeout(c.current),i.current&&window.clearInterval(i.current);let t=0,o=12;i.current=window.setInterval(()=>{var y;if(g.current){i.current&&(window.clearInterval(i.current),i.current=null);return}t+=1;try{(y=l.current)==null||y.postMessage(T(S.current),"*")}catch{}t>=o&&i.current&&(window.clearInterval(i.current),i.current=null)},1e3),c.current=window.setTimeout(()=>{g.current||(i.current&&(window.clearInterval(i.current),i.current=null),d("error"),m==null||m("Builder handshake failed or authentication was rejected."))},12e3)},[m,d]);return(0,e.useImperativeHandle)(Q,()=>({reload(){L.current=[],g.current=!1,l.current=null,E.current=null,c.current&&(window.clearTimeout(c.current),c.current=null),i.current&&(window.clearInterval(i.current),i.current=null),d("loading"),re(t=>t+1)}}),[d]),(0,e.useEffect)(()=>()=>{c.current&&(window.clearTimeout(c.current),c.current=null),i.current&&(window.clearInterval(i.current),i.current=null)},[]),(0,I.jsxs)("div",{className:q,style:{position:"relative",width:"100%",height:"100%",...$},children:[(0,I.jsx)("iframe",{ref:B,src:X,title:j,sandbox:J,style:ge,loading:"lazy",allowFullScreen:!0,onLoad:te},ee),Z!=="ready"&&(0,I.jsx)("div",{style:pe,children:"Connecting to builder\u2026"})]})}var we=(0,e.forwardRef)(ye);0&&(module.exports={EMAIL_BUILDER_PROTOCOL_VERSION,EmailBuilder,createMessageMeta,isMessageLike});
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/EmailBuilder.tsx","../src/protocol.ts","../src/utils.ts"],"sourcesContent":["export * from './EmailBuilder';\nexport * from './types';\nexport * from './protocol';\n","import React, {\n CSSProperties,\n ForwardedRef,\n forwardRef,\n useCallback,\n useEffect,\n useImperativeHandle,\n useMemo,\n useRef,\n useState,\n} from 'react';\nimport type { BuilderToHostMessage, HostToBuilderMessage, InitPayload } from './protocol';\nimport { isMessageLike } from './protocol';\nimport { buildEnvelope, deriveAllowedOrigin, stableSignature } from './utils';\nimport type { EmailBuilderHandle, EmailBuilderProps, EmailBuilderStatus } from './types';\n\nconst DEFAULT_SANDBOX = 'allow-scripts allow-same-origin allow-forms';\nconst DEFAULT_INITIAL_HTML = '<h1>Hello World</h1><p>Start building your email template.</p>';\n\ntype PendingMessage = {\n message: HostToBuilderMessage;\n correlationId?: string;\n};\n\nconst overlayStyle: CSSProperties = {\n position: 'absolute',\n inset: 0,\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n fontSize: '0.875rem',\n fontWeight: 500,\n background: 'linear-gradient(135deg, rgba(9,9,9,0.65), rgba(33,33,33,0.85))',\n color: '#fff',\n zIndex: 2,\n};\n\nconst iframeStyle: CSSProperties = {\n border: 'none',\n width: '100%',\n height: '100%',\n};\n\nfunction appendEmbedTokenToSrc(src: string, embedToken: string | undefined): string {\n if (!embedToken || !embedToken.trim()) {\n return src;\n }\n try {\n const u = new URL(src, typeof window !== 'undefined' ? window.location.href : 'https://example.com');\n u.searchParams.set('embedToken', embedToken);\n return u.toString();\n } catch {\n const sep = src.includes('?') ? '&' : '?';\n return `${src}${sep}embedToken=${encodeURIComponent(embedToken)}`;\n }\n}\n\nfunction EmailBuilderInner(\n {\n src,\n initialHtml,\n embedToken,\n templateId,\n config,\n className,\n style,\n iframeTitle = 'Email Builder',\n sandbox = DEFAULT_SANDBOX,\n onChange,\n onSave,\n onUpload,\n onReady,\n onStatusChange,\n onAuthError,\n allowedOrigin,\n }: EmailBuilderProps,\n ref: ForwardedRef<EmailBuilderHandle>\n) {\n const iframeSrc = useMemo(() => appendEmbedTokenToSrc(src, embedToken), [src, embedToken]);\n\n const iframeRef = useRef<HTMLIFrameElement>(null);\n const builderWindowRef = useRef<Window | null>(null);\n const readyRef = useRef(false);\n const statusRef = useRef<EmailBuilderStatus>('loading');\n const [status, setStatus] = useState<EmailBuilderStatus>('loading');\n const [reloadKey, setReloadKey] = useState(0);\n const queueRef = useRef<PendingMessage[]>([]);\n const runtimeOriginRef = useRef<string | null>(null);\n const handshakeTimerRef = useRef<number | null>(null);\n\n const effectiveInitialHtml =\n typeof initialHtml === 'string'\n ? initialHtml\n : templateId\n ? ''\n : DEFAULT_INITIAL_HTML;\n\n const initPayload: InitPayload = {\n html: effectiveInitialHtml,\n config,\n ...(templateId ? { templateId } : {}),\n };\n\n const initSignatureRef = useRef(stableSignature(initPayload));\n const latestInitRef = useRef<HostToBuilderMessage>({\n type: 'INIT',\n payload: initPayload,\n });\n\n const expectedOrigin = useMemo(() => deriveAllowedOrigin(src, allowedOrigin), [src, allowedOrigin]);\n\n const resolveTargetOrigin = useCallback(() => '*', []);\n\n const setStatusSafely = useCallback(\n (next: EmailBuilderStatus) => {\n if (statusRef.current === next) {\n return;\n }\n statusRef.current = next;\n setStatus(next);\n onStatusChange?.(next);\n },\n [onStatusChange]\n );\n\n const postMessage = useCallback(\n (message: HostToBuilderMessage, correlationId?: string) => {\n const target = iframeRef.current?.contentWindow ?? builderWindowRef.current;\n if (target) {\n builderWindowRef.current = target;\n }\n\n if (!builderWindowRef.current || !readyRef.current) {\n queueRef.current.push({ message, correlationId });\n return;\n }\n\n builderWindowRef.current.postMessage(buildEnvelope(message, correlationId), resolveTargetOrigin());\n },\n [resolveTargetOrigin]\n );\n\n const flushQueue = useCallback(() => {\n if (!readyRef.current || !builderWindowRef.current) {\n return;\n }\n const pending = [...queueRef.current];\n queueRef.current = [];\n pending.forEach(({ message, correlationId }) => {\n builderWindowRef.current?.postMessage(\n buildEnvelope(message, correlationId),\n resolveTargetOrigin()\n );\n });\n }, [resolveTargetOrigin]);\n\n const handleReadyMessage = useCallback(() => {\n if (readyRef.current) {\n return;\n }\n if (handshakeTimerRef.current) {\n window.clearTimeout(handshakeTimerRef.current);\n handshakeTimerRef.current = null;\n }\n readyRef.current = true;\n setStatusSafely('ready');\n onReady?.();\n postMessage(latestInitRef.current);\n flushQueue();\n }, [flushQueue, onReady, postMessage, setStatusSafely]);\n\n const handleUpload = useCallback(\n async (eventMessage: BuilderToHostMessage) => {\n if (eventMessage.type !== 'UPLOAD') {\n return;\n }\n if (!onUpload) {\n console.warn('[EmailBuilderSDK] Upload requested but no onUpload handler is configured.');\n return;\n }\n try {\n setStatusSafely('loading');\n const url = await onUpload(eventMessage.payload.file);\n postMessage({ type: 'UPLOAD_SUCCESS', payload: { url } }, eventMessage.meta?.id);\n } catch (error) {\n setStatusSafely('error');\n console.error('[EmailBuilderSDK] Upload handler failed', error);\n } finally {\n if (statusRef.current !== 'error') {\n setStatusSafely('ready');\n }\n }\n },\n [onUpload, postMessage, setStatusSafely]\n );\n\n const handleMessage = useCallback(\n (event: MessageEvent) => {\n const iframeWindow = iframeRef.current?.contentWindow ?? builderWindowRef.current;\n if (!iframeWindow || event.source !== iframeWindow) {\n return;\n }\n if (!isMessageLike(event.data)) {\n return;\n }\n if (!runtimeOriginRef.current) {\n runtimeOriginRef.current = event.origin;\n } else if (event.origin !== runtimeOriginRef.current) {\n return;\n }\n const message = event.data as BuilderToHostMessage;\n\n if (event.source && event.source !== builderWindowRef.current) {\n builderWindowRef.current = event.source as Window;\n }\n\n switch (message.type) {\n case 'READY':\n handleReadyMessage();\n break;\n case 'CHANGE':\n onChange?.(message.payload.html);\n break;\n case 'SAVE':\n onSave?.(message.payload.html);\n break;\n case 'UPLOAD':\n void handleUpload(message);\n break;\n case 'AUTH_ERROR': {\n const msg = message.payload?.message || 'Email builder authentication failed';\n if (statusRef.current !== 'error') {\n statusRef.current = 'error';\n setStatus('error');\n onAuthError?.(msg);\n }\n break;\n }\n default:\n break;\n }\n },\n [handleReadyMessage, handleUpload, onChange, onSave, onAuthError, setStatusSafely]\n );\n\n useEffect(() => {\n if (typeof window === 'undefined') {\n return;\n }\n window.addEventListener('message', handleMessage);\n return () => {\n window.removeEventListener('message', handleMessage);\n };\n }, [handleMessage]);\n\n useEffect(() => {\n const nextPayload: InitPayload = {\n html: effectiveInitialHtml,\n config,\n ...(templateId ? { templateId } : {}),\n };\n const signature = stableSignature(nextPayload);\n latestInitRef.current = { type: 'INIT', payload: nextPayload };\n if (signature !== initSignatureRef.current && readyRef.current) {\n postMessage(latestInitRef.current);\n }\n initSignatureRef.current = signature;\n }, [config, effectiveInitialHtml, postMessage, templateId]);\n\n const handleIframeLoad = useCallback(() => {\n builderWindowRef.current = iframeRef.current?.contentWindow ?? null;\n readyRef.current = false;\n runtimeOriginRef.current = null;\n setStatusSafely('loading');\n\n if (builderWindowRef.current) {\n try {\n builderWindowRef.current.postMessage(buildEnvelope(latestInitRef.current), '*');\n } catch {\n // Ignore and wait for normal READY/message flow.\n }\n }\n\n if (handshakeTimerRef.current) {\n window.clearTimeout(handshakeTimerRef.current);\n }\n handshakeTimerRef.current = window.setTimeout(() => {\n if (!readyRef.current) {\n handleReadyMessage();\n }\n }, 4000);\n }, [expectedOrigin, handleReadyMessage, setStatusSafely]);\n\n useImperativeHandle(\n ref,\n () => ({\n reload() {\n queueRef.current = [];\n readyRef.current = false;\n builderWindowRef.current = null;\n runtimeOriginRef.current = null;\n if (handshakeTimerRef.current) {\n window.clearTimeout(handshakeTimerRef.current);\n handshakeTimerRef.current = null;\n }\n setStatusSafely('loading');\n setReloadKey((key) => key + 1);\n },\n }),\n [setStatusSafely]\n );\n\n useEffect(() => {\n return () => {\n if (handshakeTimerRef.current) {\n window.clearTimeout(handshakeTimerRef.current);\n handshakeTimerRef.current = null;\n }\n };\n }, []);\n\n return (\n <div className={className} style={{ position: 'relative', width: '100%', height: '100%', ...style }}>\n <iframe\n key={reloadKey}\n ref={iframeRef}\n src={iframeSrc}\n title={iframeTitle}\n sandbox={sandbox}\n style={iframeStyle}\n loading=\"lazy\"\n allowFullScreen\n onLoad={handleIframeLoad}\n />\n {status !== 'ready' && <div style={overlayStyle}>Connecting to builder…</div>}\n </div>\n );\n}\n\nexport const EmailBuilder = forwardRef(EmailBuilderInner);\n","export const EMAIL_BUILDER_PROTOCOL_VERSION = '1.0.0';\n\nexport type MessageType =\n | 'INIT'\n | 'READY'\n | 'CHANGE'\n | 'SAVE'\n | 'UPLOAD'\n | 'UPLOAD_SUCCESS'\n | 'AUTH_ERROR';\n\nexport interface MessageMeta {\n id: string;\n correlationId?: string;\n version: string;\n sentAt: number;\n}\n\nexport type BuilderConfig = Record<string, unknown> | undefined;\n\nexport interface InitPayload {\n /** Inline HTML to import (optional if templateId is set and builder fetches server-side). */\n html?: string;\n /** When set, embedded builder fetches HTML from API using embed token + this id. */\n templateId?: string;\n config?: BuilderConfig;\n}\n\nexport interface ChangePayload {\n html: string;\n}\n\nexport interface SavePayload {\n html: string;\n}\n\nexport interface UploadPayload {\n file: File;\n}\n\nexport interface UploadSuccessPayload {\n url: string;\n}\n\nexport interface AuthErrorPayload {\n message: string;\n}\n\nexport type Message =\n | { type: 'INIT'; payload: InitPayload; meta?: MessageMeta }\n | { type: 'READY'; meta?: MessageMeta }\n | { type: 'CHANGE'; payload: ChangePayload; meta?: MessageMeta }\n | { type: 'SAVE'; payload: SavePayload; meta?: MessageMeta }\n | { type: 'UPLOAD'; payload: UploadPayload; meta?: MessageMeta }\n | { type: 'UPLOAD_SUCCESS'; payload: UploadSuccessPayload; meta?: MessageMeta }\n | { type: 'AUTH_ERROR'; payload: AuthErrorPayload; meta?: MessageMeta };\n\nexport type BuilderToHostMessage = Extract<\n Message,\n { type: 'READY' | 'CHANGE' | 'SAVE' | 'UPLOAD' | 'AUTH_ERROR' }\n>;\n\nexport type HostToBuilderMessage = Extract<\n Message,\n { type: 'INIT' | 'UPLOAD_SUCCESS' }\n>;\n\nconst VALID_TYPES: MessageType[] = [\n 'INIT',\n 'READY',\n 'CHANGE',\n 'SAVE',\n 'UPLOAD',\n 'UPLOAD_SUCCESS',\n 'AUTH_ERROR',\n];\n\nexport function isMessageLike(value: unknown): value is Message {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n\n const candidate = value as { type?: unknown; payload?: unknown; meta?: unknown };\n if (typeof candidate.type !== 'string' || !VALID_TYPES.includes(candidate.type as MessageType)) {\n return false;\n }\n\n if ('meta' in candidate && candidate.meta !== undefined) {\n const meta = candidate.meta as Partial<MessageMeta>;\n if (\n (meta.id && typeof meta.id !== 'string') ||\n (meta.correlationId && typeof meta.correlationId !== 'string') ||\n (meta.version && typeof meta.version !== 'string') ||\n (meta.sentAt && typeof meta.sentAt !== 'number')\n ) {\n return false;\n }\n }\n\n return true;\n}\n\nexport function createMessageMeta(correlationId?: string): MessageMeta {\n const id = typeof crypto !== 'undefined' && 'randomUUID' in crypto\n ? crypto.randomUUID()\n : Math.random().toString(36).slice(2);\n return {\n id,\n correlationId,\n version: EMAIL_BUILDER_PROTOCOL_VERSION,\n sentAt: Date.now(),\n };\n}\n","import type { BuilderToHostMessage, HostToBuilderMessage, MessageMeta } from './protocol';\nimport { createMessageMeta, isMessageLike } from './protocol';\n\nexport function deriveAllowedOrigin(src: string, override?: string): string {\n if (override) {\n const parsed = new URL(override);\n if (parsed.origin === 'null') {\n throw new Error('allowedOrigin must resolve to a valid origin');\n }\n return parsed.origin;\n }\n\n let parsed: URL;\n try {\n parsed = new URL(src);\n } catch {\n throw new Error('EmailBuilder `src` must be an absolute URL (e.g. https://example.com)');\n }\n if (!parsed.origin || parsed.origin === 'null') {\n throw new Error('EmailBuilder requires an absolute src URL with a valid origin');\n }\n return parsed.origin;\n}\n\nexport function buildEnvelope<T extends HostToBuilderMessage>(message: T, correlationId?: string): T {\n const meta: MessageMeta = createMessageMeta(correlationId);\n return { ...message, meta } as T;\n}\n\nexport function sanitizeIncomingMessage(\n event: MessageEvent,\n allowedOrigin: string,\n iframeWindow: Window | null\n): BuilderToHostMessage | null {\n if (event.origin !== allowedOrigin) {\n return null;\n }\n\n if (!iframeWindow || event.source !== iframeWindow) {\n return null;\n }\n\n if (!isMessageLike(event.data)) {\n return null;\n }\n\n return event.data as BuilderToHostMessage;\n}\n\nexport function stableSignature(value: unknown): string {\n return JSON.stringify(value ?? null);\n}\n"],"mappings":"mbAAA,IAAAA,GAA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5B,GAAc,uCAAsB,GACzE,CAEJ,CAEO,IAAMqE,MAAe,cAAW9D,EAAiB","names":["index_exports","__export","EMAIL_BUILDER_PROTOCOL_VERSION","EmailBuilder","createMessageMeta","isMessageLike","__toCommonJS","import_react","EMAIL_BUILDER_PROTOCOL_VERSION","VALID_TYPES","isMessageLike","value","candidate","meta","createMessageMeta","correlationId","deriveAllowedOrigin","src","override","parsed","buildEnvelope","message","correlationId","meta","createMessageMeta","stableSignature","value","import_jsx_runtime","DEFAULT_SANDBOX","DEFAULT_INITIAL_HTML","overlayStyle","iframeStyle","appendEmbedTokenToSrc","src","embedToken","u","sep","EmailBuilderInner","initialHtml","templateId","config","className","style","iframeTitle","sandbox","onChange","onSave","onUpload","onReady","onStatusChange","onAuthError","allowedOrigin","ref","iframeSrc","iframeRef","builderWindowRef","readyRef","statusRef","status","setStatus","reloadKey","setReloadKey","queueRef","runtimeOriginRef","handshakeTimerRef","effectiveInitialHtml","initPayload","initSignatureRef","stableSignature","latestInitRef","expectedOrigin","deriveAllowedOrigin","resolveTargetOrigin","setStatusSafely","next","postMessage","message","correlationId","_a","_b","target","buildEnvelope","flushQueue","pending","handleReadyMessage","handleUpload","eventMessage","url","error","handleMessage","event","_c","iframeWindow","isMessageLike","msg","nextPayload","signature","handleIframeLoad","key","EmailBuilder"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/EmailBuilder.tsx","../src/protocol.ts","../src/utils.ts"],"sourcesContent":["export * from './EmailBuilder';\nexport * from './types';\nexport * from './protocol';\n","import React, {\n CSSProperties,\n ForwardedRef,\n forwardRef,\n useCallback,\n useEffect,\n useImperativeHandle,\n useMemo,\n useRef,\n useState,\n} from 'react';\nimport type { BuilderToHostMessage, HostToBuilderMessage, InitPayload } from './protocol';\nimport { isMessageLike } from './protocol';\nimport { buildEnvelope, deriveAllowedOrigin, stableSignature } from './utils';\nimport type { EmailBuilderHandle, EmailBuilderProps, EmailBuilderStatus } from './types';\n\nconst DEFAULT_SANDBOX = 'allow-scripts allow-same-origin allow-forms';\nconst DEFAULT_INITIAL_HTML = '<h1>Hello World</h1><p>Start building your email template.</p>';\n\ntype PendingMessage = {\n message: HostToBuilderMessage;\n correlationId?: string;\n};\n\nconst overlayStyle: CSSProperties = {\n position: 'absolute',\n inset: 0,\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n fontSize: '0.875rem',\n fontWeight: 500,\n background: 'linear-gradient(135deg, rgba(9,9,9,0.65), rgba(33,33,33,0.85))',\n color: '#fff',\n zIndex: 2,\n};\n\nconst iframeStyle: CSSProperties = {\n border: 'none',\n width: '100%',\n height: '100%',\n};\n\nfunction appendEmbedTokenToSrc(src: string, embedToken: string | undefined): string {\n if (!embedToken || !embedToken.trim()) {\n return src;\n }\n try {\n const u = new URL(src, typeof window !== 'undefined' ? window.location.href : 'https://example.com');\n u.searchParams.set('embedToken', embedToken);\n return u.toString();\n } catch {\n const sep = src.includes('?') ? '&' : '?';\n return `${src}${sep}embedToken=${encodeURIComponent(embedToken)}`;\n }\n}\n\nfunction EmailBuilderInner(\n {\n src,\n initialHtml,\n embedToken,\n templateId,\n config,\n className,\n style,\n iframeTitle = 'Email Builder',\n sandbox = DEFAULT_SANDBOX,\n onChange,\n onSave,\n onUpload,\n onReady,\n onStatusChange,\n onAuthError,\n allowedOrigin,\n }: EmailBuilderProps,\n ref: ForwardedRef<EmailBuilderHandle>\n) {\n const iframeSrc = useMemo(() => appendEmbedTokenToSrc(src, embedToken), [src, embedToken]);\n\n const iframeRef = useRef<HTMLIFrameElement>(null);\n const builderWindowRef = useRef<Window | null>(null);\n const readyRef = useRef(false);\n const statusRef = useRef<EmailBuilderStatus>('loading');\n const [status, setStatus] = useState<EmailBuilderStatus>('loading');\n const [reloadKey, setReloadKey] = useState(0);\n const queueRef = useRef<PendingMessage[]>([]);\n const runtimeOriginRef = useRef<string | null>(null);\n const handshakeTimerRef = useRef<number | null>(null);\n const handshakeRetryIntervalRef = useRef<number | null>(null);\n\n const effectiveInitialHtml =\n typeof initialHtml === 'string'\n ? initialHtml\n : templateId\n ? ''\n : DEFAULT_INITIAL_HTML;\n\n const initPayload: InitPayload = {\n html: effectiveInitialHtml,\n config,\n ...(templateId ? { templateId } : {}),\n };\n\n const initSignatureRef = useRef(stableSignature(initPayload));\n const latestInitRef = useRef<HostToBuilderMessage>({\n type: 'INIT',\n payload: initPayload,\n });\n\n const expectedOrigin = useMemo(() => deriveAllowedOrigin(src, allowedOrigin), [src, allowedOrigin]);\n\n const resolveTargetOrigin = useCallback(() => '*', []);\n\n const setStatusSafely = useCallback(\n (next: EmailBuilderStatus) => {\n if (statusRef.current === next) {\n return;\n }\n statusRef.current = next;\n setStatus(next);\n onStatusChange?.(next);\n },\n [onStatusChange]\n );\n\n const postMessage = useCallback(\n (message: HostToBuilderMessage, correlationId?: string) => {\n const target = iframeRef.current?.contentWindow ?? builderWindowRef.current;\n if (target) {\n builderWindowRef.current = target;\n }\n\n if (!builderWindowRef.current || !readyRef.current) {\n queueRef.current.push({ message, correlationId });\n return;\n }\n\n builderWindowRef.current.postMessage(buildEnvelope(message, correlationId), resolveTargetOrigin());\n },\n [resolveTargetOrigin]\n );\n\n const flushQueue = useCallback(() => {\n if (!readyRef.current || !builderWindowRef.current) {\n return;\n }\n const pending = [...queueRef.current];\n queueRef.current = [];\n pending.forEach(({ message, correlationId }) => {\n builderWindowRef.current?.postMessage(\n buildEnvelope(message, correlationId),\n resolveTargetOrigin()\n );\n });\n }, [resolveTargetOrigin]);\n\n const handleReadyMessage = useCallback(() => {\n if (readyRef.current) {\n return;\n }\n if (handshakeTimerRef.current) {\n window.clearTimeout(handshakeTimerRef.current);\n handshakeTimerRef.current = null;\n }\n if (handshakeRetryIntervalRef.current) {\n window.clearInterval(handshakeRetryIntervalRef.current);\n handshakeRetryIntervalRef.current = null;\n }\n readyRef.current = true;\n setStatusSafely('ready');\n onReady?.();\n postMessage(latestInitRef.current);\n flushQueue();\n }, [flushQueue, onReady, postMessage, setStatusSafely]);\n\n const handleUpload = useCallback(\n async (eventMessage: BuilderToHostMessage) => {\n if (eventMessage.type !== 'UPLOAD') {\n return;\n }\n if (!onUpload) {\n console.warn('[EmailBuilderSDK] Upload requested but no onUpload handler is configured.');\n return;\n }\n try {\n setStatusSafely('loading');\n const url = await onUpload(eventMessage.payload.file);\n postMessage({ type: 'UPLOAD_SUCCESS', payload: { url } }, eventMessage.meta?.id);\n } catch (error) {\n setStatusSafely('error');\n console.error('[EmailBuilderSDK] Upload handler failed', error);\n } finally {\n if (statusRef.current !== 'error') {\n setStatusSafely('ready');\n }\n }\n },\n [onUpload, postMessage, setStatusSafely]\n );\n\n const handleMessage = useCallback(\n (event: MessageEvent) => {\n const iframeWindow = iframeRef.current?.contentWindow ?? builderWindowRef.current;\n if (!iframeWindow || event.source !== iframeWindow) {\n return;\n }\n if (!isMessageLike(event.data)) {\n return;\n }\n if (!runtimeOriginRef.current) {\n runtimeOriginRef.current = event.origin;\n } else if (event.origin !== runtimeOriginRef.current) {\n return;\n }\n const message = event.data as BuilderToHostMessage;\n\n if (event.source && event.source !== builderWindowRef.current) {\n builderWindowRef.current = event.source as Window;\n }\n\n switch (message.type) {\n case 'READY':\n handleReadyMessage();\n break;\n case 'CHANGE':\n onChange?.(message.payload.html);\n break;\n case 'SAVE':\n onSave?.(message.payload.html);\n break;\n case 'UPLOAD':\n void handleUpload(message);\n break;\n case 'AUTH_ERROR': {\n const msg = message.payload?.message || 'Email builder authentication failed';\n if (statusRef.current !== 'error') {\n statusRef.current = 'error';\n setStatus('error');\n onAuthError?.(msg);\n }\n break;\n }\n default:\n break;\n }\n },\n [handleReadyMessage, handleUpload, onChange, onSave, onAuthError, setStatusSafely]\n );\n\n useEffect(() => {\n if (typeof window === 'undefined') {\n return;\n }\n window.addEventListener('message', handleMessage);\n return () => {\n window.removeEventListener('message', handleMessage);\n };\n }, [handleMessage]);\n\n useEffect(() => {\n const nextPayload: InitPayload = {\n html: effectiveInitialHtml,\n config,\n ...(templateId ? { templateId } : {}),\n };\n const signature = stableSignature(nextPayload);\n latestInitRef.current = { type: 'INIT', payload: nextPayload };\n if (signature !== initSignatureRef.current && readyRef.current) {\n postMessage(latestInitRef.current);\n }\n initSignatureRef.current = signature;\n }, [config, effectiveInitialHtml, postMessage, templateId]);\n\n const handleIframeLoad = useCallback(() => {\n builderWindowRef.current = iframeRef.current?.contentWindow ?? null;\n readyRef.current = false;\n runtimeOriginRef.current = null;\n setStatusSafely('loading');\n\n if (builderWindowRef.current) {\n try {\n builderWindowRef.current.postMessage(buildEnvelope(latestInitRef.current), '*');\n } catch {\n // Ignore and wait for normal READY/message flow.\n }\n }\n\n if (handshakeTimerRef.current) {\n window.clearTimeout(handshakeTimerRef.current);\n }\n if (handshakeRetryIntervalRef.current) {\n window.clearInterval(handshakeRetryIntervalRef.current);\n }\n\n let attempts = 0;\n const maxAttempts = 12;\n handshakeRetryIntervalRef.current = window.setInterval(() => {\n if (readyRef.current) {\n if (handshakeRetryIntervalRef.current) {\n window.clearInterval(handshakeRetryIntervalRef.current);\n handshakeRetryIntervalRef.current = null;\n }\n return;\n }\n attempts += 1;\n try {\n builderWindowRef.current?.postMessage(buildEnvelope(latestInitRef.current), '*');\n } catch {\n // Keep retrying until timeout.\n }\n if (attempts >= maxAttempts) {\n if (handshakeRetryIntervalRef.current) {\n window.clearInterval(handshakeRetryIntervalRef.current);\n handshakeRetryIntervalRef.current = null;\n }\n }\n }, 1000);\n\n handshakeTimerRef.current = window.setTimeout(() => {\n if (readyRef.current) {\n return;\n }\n if (handshakeRetryIntervalRef.current) {\n window.clearInterval(handshakeRetryIntervalRef.current);\n handshakeRetryIntervalRef.current = null;\n }\n setStatusSafely('error');\n onAuthError?.('Builder handshake failed or authentication was rejected.');\n }, 12000);\n }, [onAuthError, setStatusSafely]);\n\n useImperativeHandle(\n ref,\n () => ({\n reload() {\n queueRef.current = [];\n readyRef.current = false;\n builderWindowRef.current = null;\n runtimeOriginRef.current = null;\n if (handshakeTimerRef.current) {\n window.clearTimeout(handshakeTimerRef.current);\n handshakeTimerRef.current = null;\n }\n if (handshakeRetryIntervalRef.current) {\n window.clearInterval(handshakeRetryIntervalRef.current);\n handshakeRetryIntervalRef.current = null;\n }\n setStatusSafely('loading');\n setReloadKey((key) => key + 1);\n },\n }),\n [setStatusSafely]\n );\n\n useEffect(() => {\n return () => {\n if (handshakeTimerRef.current) {\n window.clearTimeout(handshakeTimerRef.current);\n handshakeTimerRef.current = null;\n }\n if (handshakeRetryIntervalRef.current) {\n window.clearInterval(handshakeRetryIntervalRef.current);\n handshakeRetryIntervalRef.current = null;\n }\n };\n }, []);\n\n return (\n <div className={className} style={{ position: 'relative', width: '100%', height: '100%', ...style }}>\n <iframe\n key={reloadKey}\n ref={iframeRef}\n src={iframeSrc}\n title={iframeTitle}\n sandbox={sandbox}\n style={iframeStyle}\n loading=\"lazy\"\n allowFullScreen\n onLoad={handleIframeLoad}\n />\n {status !== 'ready' && <div style={overlayStyle}>Connecting to builder…</div>}\n </div>\n );\n}\n\nexport const EmailBuilder = forwardRef(EmailBuilderInner);\n","export const EMAIL_BUILDER_PROTOCOL_VERSION = '1.0.0';\n\nexport type MessageType =\n | 'INIT'\n | 'READY'\n | 'CHANGE'\n | 'SAVE'\n | 'UPLOAD'\n | 'UPLOAD_SUCCESS'\n | 'AUTH_ERROR';\n\nexport interface MessageMeta {\n id: string;\n correlationId?: string;\n version: string;\n sentAt: number;\n}\n\nexport type BuilderConfig = Record<string, unknown> | undefined;\n\nexport interface InitPayload {\n /** Inline HTML to import (optional if templateId is set and builder fetches server-side). */\n html?: string;\n /** When set, embedded builder fetches HTML from API using embed token + this id. */\n templateId?: string;\n config?: BuilderConfig;\n}\n\nexport interface ChangePayload {\n html: string;\n}\n\nexport interface SavePayload {\n html: string;\n}\n\nexport interface UploadPayload {\n file: File;\n}\n\nexport interface UploadSuccessPayload {\n url: string;\n}\n\nexport interface AuthErrorPayload {\n message: string;\n}\n\nexport type Message =\n | { type: 'INIT'; payload: InitPayload; meta?: MessageMeta }\n | { type: 'READY'; meta?: MessageMeta }\n | { type: 'CHANGE'; payload: ChangePayload; meta?: MessageMeta }\n | { type: 'SAVE'; payload: SavePayload; meta?: MessageMeta }\n | { type: 'UPLOAD'; payload: UploadPayload; meta?: MessageMeta }\n | { type: 'UPLOAD_SUCCESS'; payload: UploadSuccessPayload; meta?: MessageMeta }\n | { type: 'AUTH_ERROR'; payload: AuthErrorPayload; meta?: MessageMeta };\n\nexport type BuilderToHostMessage = Extract<\n Message,\n { type: 'READY' | 'CHANGE' | 'SAVE' | 'UPLOAD' | 'AUTH_ERROR' }\n>;\n\nexport type HostToBuilderMessage = Extract<\n Message,\n { type: 'INIT' | 'UPLOAD_SUCCESS' }\n>;\n\nconst VALID_TYPES: MessageType[] = [\n 'INIT',\n 'READY',\n 'CHANGE',\n 'SAVE',\n 'UPLOAD',\n 'UPLOAD_SUCCESS',\n 'AUTH_ERROR',\n];\n\nexport function isMessageLike(value: unknown): value is Message {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n\n const candidate = value as { type?: unknown; payload?: unknown; meta?: unknown };\n if (typeof candidate.type !== 'string' || !VALID_TYPES.includes(candidate.type as MessageType)) {\n return false;\n }\n\n if ('meta' in candidate && candidate.meta !== undefined) {\n const meta = candidate.meta as Partial<MessageMeta>;\n if (\n (meta.id && typeof meta.id !== 'string') ||\n (meta.correlationId && typeof meta.correlationId !== 'string') ||\n (meta.version && typeof meta.version !== 'string') ||\n (meta.sentAt && typeof meta.sentAt !== 'number')\n ) {\n return false;\n }\n }\n\n return true;\n}\n\nexport function createMessageMeta(correlationId?: string): MessageMeta {\n const id = typeof crypto !== 'undefined' && 'randomUUID' in crypto\n ? crypto.randomUUID()\n : Math.random().toString(36).slice(2);\n return {\n id,\n correlationId,\n version: EMAIL_BUILDER_PROTOCOL_VERSION,\n sentAt: Date.now(),\n };\n}\n","import type { BuilderToHostMessage, HostToBuilderMessage, MessageMeta } from './protocol';\nimport { createMessageMeta, isMessageLike } from './protocol';\n\nexport function deriveAllowedOrigin(src: string, override?: string): string {\n if (override) {\n const parsed = new URL(override);\n if (parsed.origin === 'null') {\n throw new Error('allowedOrigin must resolve to a valid origin');\n }\n return parsed.origin;\n }\n\n let parsed: URL;\n try {\n parsed = new URL(src);\n } catch {\n throw new Error('EmailBuilder `src` must be an absolute URL (e.g. https://example.com)');\n }\n if (!parsed.origin || parsed.origin === 'null') {\n throw new Error('EmailBuilder requires an absolute src URL with a valid origin');\n }\n return parsed.origin;\n}\n\nexport function buildEnvelope<T extends HostToBuilderMessage>(message: T, correlationId?: string): T {\n const meta: MessageMeta = createMessageMeta(correlationId);\n return { ...message, meta } as T;\n}\n\nexport function sanitizeIncomingMessage(\n event: MessageEvent,\n allowedOrigin: string,\n iframeWindow: Window | null\n): BuilderToHostMessage | null {\n if (event.origin !== allowedOrigin) {\n return null;\n }\n\n if (!iframeWindow || event.source !== iframeWindow) {\n return null;\n }\n\n if (!isMessageLike(event.data)) {\n return null;\n }\n\n return event.data as BuilderToHostMessage;\n}\n\nexport function stableSignature(value: unknown): string {\n return JSON.stringify(value ?? null);\n}\n"],"mappings":"mbAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,oCAAAE,EAAA,iBAAAC,GAAA,sBAAAC,EAAA,kBAAAC,IAAA,eAAAC,GAAAN,ICAA,IAAAO,EAUO,iBCVA,IAAMC,EAAiC,QAmExCC,GAA6B,CACjC,OACA,QACA,SACA,OACA,SACA,iBACA,YACF,EAEO,SAASC,EAAcC,EAAkC,CAC9D,GAAI,OAAOA,GAAU,UAAYA,IAAU,KACzC,MAAO,GAGT,IAAMC,EAAYD,EAClB,GAAI,OAAOC,EAAU,MAAS,UAAY,CAACH,GAAY,SAASG,EAAU,IAAmB,EAC3F,MAAO,GAGT,GAAI,SAAUA,GAAaA,EAAU,OAAS,OAAW,CACvD,IAAMC,EAAOD,EAAU,KACvB,GACGC,EAAK,IAAM,OAAOA,EAAK,IAAO,UAC9BA,EAAK,eAAiB,OAAOA,EAAK,eAAkB,U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AU,KAExC,EACC,CAAC,CAAC,KAGH,QAAC,OAAI,UAAWxB,EAAW,MAAO,CAAE,SAAU,WAAY,MAAO,OAAQ,OAAQ,OAAQ,GAAGC,CAAM,EAChG,oBAAC,UAEC,IAAKY,EACL,IAAKD,EACL,MAAOV,EACP,QAASC,EACT,MAAOb,GACP,QAAQ,OACR,gBAAe,GACf,OAAQmE,IARHtC,EASP,EACCF,IAAW,YAAW,OAAC,OAAI,MAAO5B,GAAc,uCAAsB,GACzE,CAEJ,CAEO,IAAMwE,MAAe,cAAWjE,EAAiB","names":["index_exports","__export","EMAIL_BUILDER_PROTOCOL_VERSION","EmailBuilder","createMessageMeta","isMessageLike","__toCommonJS","import_react","EMAIL_BUILDER_PROTOCOL_VERSION","VALID_TYPES","isMessageLike","value","candidate","meta","createMessageMeta","correlationId","deriveAllowedOrigin","src","override","parsed","buildEnvelope","message","correlationId","meta","createMessageMeta","stableSignature","value","import_jsx_runtime","DEFAULT_SANDBOX","DEFAULT_INITIAL_HTML","overlayStyle","iframeStyle","appendEmbedTokenToSrc","src","embedToken","u","sep","EmailBuilderInner","initialHtml","templateId","config","className","style","iframeTitle","sandbox","onChange","onSave","onUpload","onReady","onStatusChange","onAuthError","allowedOrigin","ref","iframeSrc","iframeRef","builderWindowRef","readyRef","statusRef","status","setStatus","reloadKey","setReloadKey","queueRef","runtimeOriginRef","handshakeTimerRef","handshakeRetryIntervalRef","effectiveInitialHtml","initPayload","initSignatureRef","stableSignature","latestInitRef","expectedOrigin","deriveAllowedOrigin","resolveTargetOrigin","setStatusSafely","next","postMessage","message","correlationId","_a","_b","target","buildEnvelope","flushQueue","pending","handleReadyMessage","handleUpload","eventMessage","url","error","handleMessage","event","_c","iframeWindow","isMessageLike","msg","nextPayload","signature","handleIframeLoad","attempts","maxAttempts","key","EmailBuilder"]}
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{forwardRef as le,useCallback as p,useEffect as k,useImperativeHandle as ue,useMemo as z,useRef as c,useState as K}from"react";var se="1.0.0",oe=["INIT","READY","CHANGE","SAVE","UPLOAD","UPLOAD_SUCCESS","AUTH_ERROR"];function O(r){if(typeof r!="object"||r===null)return!1;let n=r;if(typeof n.type!="string"||!oe.includes(n.type))return!1;if("meta"in n&&n.meta!==void 0){let t=n.meta;if(t.id&&typeof t.id!="string"||t.correlationId&&typeof t.correlationId!="string"||t.version&&typeof t.version!="string"||t.sentAt&&typeof t.sentAt!="number")return!1}return!0}function v(r){return{id:typeof crypto!="undefined"&&"randomUUID"in crypto?crypto.randomUUID():Math.random().toString(36).slice(2),correlationId:r,version:se,sentAt:Date.now()}}function G(r,n){if(n){let u=new URL(n);if(u.origin==="null")throw new Error("allowedOrigin must resolve to a valid origin");return u.origin}let t;try{t=new URL(r)}catch{throw new Error("EmailBuilder `src` must be an absolute URL (e.g. https://example.com)")}if(!t.origin||t.origin==="null")throw new Error("EmailBuilder requires an absolute src URL with a valid origin");return t.origin}function L(r,n){let t=v(n);return{...r,meta:t}}function D(r){return JSON.stringify(r!=null?r:null)}import{jsx as q,jsxs as me}from"react/jsx-runtime";var ce="allow-scripts allow-same-origin allow-forms",de="<h1>Hello World</h1><p>Start building your email template.</p>",fe={position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",fontSize:"0.875rem",fontWeight:500,background:"linear-gradient(135deg, rgba(9,9,9,0.65), rgba(33,33,33,0.85))",color:"#fff",zIndex:2},pe={border:"none",width:"100%",height:"100%"};function ge(r,n){if(!n||!n.trim())return r;try{let t=new URL(r,typeof window!="undefined"?window.location.href:"https://example.com");return t.searchParams.set("embedToken",n),t.toString()}catch{let t=r.includes("?")?"&":"?";return`${r}${t}embedToken=${encodeURIComponent(n)}`}}function ye({src:r,initialHtml:n,embedToken:t,templateId:u,config:h,className:$,style:j,iframeTitle:J="Email Builder",sandbox:Q=ce,onChange:E,onSave:w,onUpload:H,onReady:S,onStatusChange:T,onAuthError:R,allowedOrigin:C},X){let Z=z(()=>ge(r,t),[r,t]),U=c(null),s=c(null),d=c(!1),y=c("loading"),[ee,_]=K("loading"),[re,te]=K(0),A=c([]),m=c(null),o=c(null),x=typeof n=="string"?n:u?"":de,N={html:x,config:h,...u?{templateId:u}:{}},W=c(D(N)),P=c({type:"INIT",payload:N}),ne=z(()=>G(r,C),[r,C]),I=p(()=>"*",[]),l=p(e=>{y.current!==e&&(y.current=e,_(e),T==null||T(e))},[T]),g=p((e,i)=>{var f,M;let a=(M=(f=U.current)==null?void 0:f.contentWindow)!=null?M:s.current;if(a&&(s.current=a),!s.current||!d.current){A.current.push({message:e,correlationId:i});return}s.current.postMessage(L(e,i),I())},[I]),F=p(()=>{if(!d.current||!s.current)return;let e=[...A.current];A.current=[],e.forEach(({message:i,correlationId:a})=>{var f;(f=s.current)==null||f.postMessage(L(i,a),I())})},[I]),B=p(()=>{d.current||(o.current&&(window.clearTimeout(o.current),o.current=null),d.current=!0,l("ready"),S==null||S(),g(P.current),F())},[F,S,g,l]),V=p(async e=>{var i;if(e.type==="UPLOAD"){if(!H){console.warn("[EmailBuilderSDK] Upload requested but no onUpload handler is configured.");return}try{l("loading");let a=await H(e.payload.file);g({type:"UPLOAD_SUCCESS",payload:{url:a}},(i=e.meta)==null?void 0:i.id)}catch(a){l("error"),console.error("[EmailBuilderSDK] Upload handler failed",a)}finally{y.current!=="error"&&l("ready")}}},[H,g,l]),b=p(e=>{var f,M,Y;let i=(M=(f=U.current)==null?void 0:f.contentWindow)!=null?M:s.current;if(!i||e.source!==i||!O(e.data))return;if(!m.current)m.current=e.origin;else if(e.origin!==m.current)return;let a=e.data;switch(e.source&&e.source!==s.current&&(s.current=e.source),a.type){case"READY":B();break;case"CHANGE":E==null||E(a.payload.html);break;case"SAVE":w==null||w(a.payload.html);break;case"UPLOAD":V(a);break;case"AUTH_ERROR":{let ae=((Y=a.payload)==null?void 0:Y.message)||"Email builder authentication failed";y.current!=="error"&&(y.current="error",_("error"),R==null||R(ae));break}default:break}},[B,V,E,w,R,l]);k(()=>{if(typeof window!="undefined")return window.addEventListener("message",b),()=>{window.removeEventListener("message",b)}},[b]),k(()=>{let e={html:x,config:h,...u?{templateId:u}:{}},i=D(e);P.current={type:"INIT",payload:e},i!==W.current&&d.current&&g(P.current),W.current=i},[h,x,g,u]);let ie=p(()=>{var e,i;if(s.current=(i=(e=U.current)==null?void 0:e.contentWindow)!=null?i:null,d.current=!1,m.current=null,l("loading"),s.current)try{s.current.postMessage(L(P.current),"*")}catch{}o.current&&window.clearTimeout(o.current),o.current=window.setTimeout(()=>{d.current||B()},4e3)},[ne,B,l]);return ue(X,()=>({reload(){A.current=[],d.current=!1,s.current=null,m.current=null,o.current&&(window.clearTimeout(o.current),o.current=null),l("loading"),te(e=>e+1)}}),[l]),k(()=>()=>{o.current&&(window.clearTimeout(o.current),o.current=null)},[]),me("div",{className:$,style:{position:"relative",width:"100%",height:"100%",...j},children:[q("iframe",{ref:U,src:Z,title:J,sandbox:Q,style:pe,loading:"lazy",allowFullScreen:!0,onLoad:ie},re),ee!=="ready"&&q("div",{style:fe,children:"Connecting to builder\u2026"})]})}var Ie=le(ye);export{se as EMAIL_BUILDER_PROTOCOL_VERSION,Ie as EmailBuilder,v as createMessageMeta,O as isMessageLike};
1
+ import{forwardRef as le,useCallback as y,useEffect as k,useImperativeHandle as ue,useMemo as K,useRef as d,useState as q}from"react";var se="1.0.0",oe=["INIT","READY","CHANGE","SAVE","UPLOAD","UPLOAD_SUCCESS","AUTH_ERROR"];function O(r){if(typeof r!="object"||r===null)return!1;let a=r;if(typeof a.type!="string"||!oe.includes(a.type))return!1;if("meta"in a&&a.meta!==void 0){let t=a.meta;if(t.id&&typeof t.id!="string"||t.correlationId&&typeof t.correlationId!="string"||t.version&&typeof t.version!="string"||t.sentAt&&typeof t.sentAt!="number")return!1}return!0}function G(r){return{id:typeof crypto!="undefined"&&"randomUUID"in crypto?crypto.randomUUID():Math.random().toString(36).slice(2),correlationId:r,version:se,sentAt:Date.now()}}function z(r,a){if(a){let f=new URL(a);if(f.origin==="null")throw new Error("allowedOrigin must resolve to a valid origin");return f.origin}let t;try{t=new URL(r)}catch{throw new Error("EmailBuilder `src` must be an absolute URL (e.g. https://example.com)")}if(!t.origin||t.origin==="null")throw new Error("EmailBuilder requires an absolute src URL with a valid origin");return t.origin}function T(r,a){let t=G(a);return{...r,meta:t}}function D(r){return JSON.stringify(r!=null?r:null)}import{jsx as $,jsxs as ye}from"react/jsx-runtime";var ce="allow-scripts allow-same-origin allow-forms",de="<h1>Hello World</h1><p>Start building your email template.</p>",fe={position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",fontSize:"0.875rem",fontWeight:500,background:"linear-gradient(135deg, rgba(9,9,9,0.65), rgba(33,33,33,0.85))",color:"#fff",zIndex:2},pe={border:"none",width:"100%",height:"100%"};function ge(r,a){if(!a||!a.trim())return r;try{let t=new URL(r,typeof window!="undefined"?window.location.href:"https://example.com");return t.searchParams.set("embedToken",a),t.toString()}catch{let t=r.includes("?")?"&":"?";return`${r}${t}embedToken=${encodeURIComponent(a)}`}}function me({src:r,initialHtml:a,embedToken:t,templateId:f,config:h,className:j,style:J,iframeTitle:Q="Email Builder",sandbox:X=ce,onChange:I,onSave:R,onUpload:x,onReady:U,onStatusChange:P,onAuthError:g,allowedOrigin:C},Z){let ee=K(()=>ge(r,t),[r,t]),A=d(null),o=d(null),p=d(!1),M=d("loading"),[re,_]=q("loading"),[te,ne]=q(0),B=d([]),E=d(null),l=d(null),n=d(null),H=typeof a=="string"?a:f?"":de,N={html:H,config:h,...f?{templateId:f}:{}},v=d(D(N)),S=d({type:"INIT",payload:N}),we=K(()=>z(r,C),[r,C]),L=y(()=>"*",[]),u=y(e=>{M.current!==e&&(M.current=e,_(e),P==null||P(e))},[P]),w=y((e,s)=>{var c,m;let i=(m=(c=A.current)==null?void 0:c.contentWindow)!=null?m:o.current;if(i&&(o.current=i),!o.current||!p.current){B.current.push({message:e,correlationId:s});return}o.current.postMessage(T(e,s),L())},[L]),W=y(()=>{if(!p.current||!o.current)return;let e=[...B.current];B.current=[],e.forEach(({message:s,correlationId:i})=>{var c;(c=o.current)==null||c.postMessage(T(s,i),L())})},[L]),F=y(()=>{p.current||(l.current&&(window.clearTimeout(l.current),l.current=null),n.current&&(window.clearInterval(n.current),n.current=null),p.current=!0,u("ready"),U==null||U(),w(S.current),W())},[W,U,w,u]),V=y(async e=>{var s;if(e.type==="UPLOAD"){if(!x){console.warn("[EmailBuilderSDK] Upload requested but no onUpload handler is configured.");return}try{u("loading");let i=await x(e.payload.file);w({type:"UPLOAD_SUCCESS",payload:{url:i}},(s=e.meta)==null?void 0:s.id)}catch(i){u("error"),console.error("[EmailBuilderSDK] Upload handler failed",i)}finally{M.current!=="error"&&u("ready")}}},[x,w,u]),b=y(e=>{var c,m,Y;let s=(m=(c=A.current)==null?void 0:c.contentWindow)!=null?m:o.current;if(!s||e.source!==s||!O(e.data))return;if(!E.current)E.current=e.origin;else if(e.origin!==E.current)return;let i=e.data;switch(e.source&&e.source!==o.current&&(o.current=e.source),i.type){case"READY":F();break;case"CHANGE":I==null||I(i.payload.html);break;case"SAVE":R==null||R(i.payload.html);break;case"UPLOAD":V(i);break;case"AUTH_ERROR":{let ie=((Y=i.payload)==null?void 0:Y.message)||"Email builder authentication failed";M.current!=="error"&&(M.current="error",_("error"),g==null||g(ie));break}default:break}},[F,V,I,R,g,u]);k(()=>{if(typeof window!="undefined")return window.addEventListener("message",b),()=>{window.removeEventListener("message",b)}},[b]),k(()=>{let e={html:H,config:h,...f?{templateId:f}:{}},s=D(e);S.current={type:"INIT",payload:e},s!==v.current&&p.current&&w(S.current),v.current=s},[h,H,w,f]);let ae=y(()=>{var i,c;if(o.current=(c=(i=A.current)==null?void 0:i.contentWindow)!=null?c:null,p.current=!1,E.current=null,u("loading"),o.current)try{o.current.postMessage(T(S.current),"*")}catch{}l.current&&window.clearTimeout(l.current),n.current&&window.clearInterval(n.current);let e=0,s=12;n.current=window.setInterval(()=>{var m;if(p.current){n.current&&(window.clearInterval(n.current),n.current=null);return}e+=1;try{(m=o.current)==null||m.postMessage(T(S.current),"*")}catch{}e>=s&&n.current&&(window.clearInterval(n.current),n.current=null)},1e3),l.current=window.setTimeout(()=>{p.current||(n.current&&(window.clearInterval(n.current),n.current=null),u("error"),g==null||g("Builder handshake failed or authentication was rejected."))},12e3)},[g,u]);return ue(Z,()=>({reload(){B.current=[],p.current=!1,o.current=null,E.current=null,l.current&&(window.clearTimeout(l.current),l.current=null),n.current&&(window.clearInterval(n.current),n.current=null),u("loading"),ne(e=>e+1)}}),[u]),k(()=>()=>{l.current&&(window.clearTimeout(l.current),l.current=null),n.current&&(window.clearInterval(n.current),n.current=null)},[]),ye("div",{className:j,style:{position:"relative",width:"100%",height:"100%",...J},children:[$("iframe",{ref:A,src:ee,title:Q,sandbox:X,style:pe,loading:"lazy",allowFullScreen:!0,onLoad:ae},te),re!=="ready"&&$("div",{style:fe,children:"Connecting to builder\u2026"})]})}var Be=le(me);export{se as EMAIL_BUILDER_PROTOCOL_VERSION,Be as EmailBuilder,G as createMessageMeta,O as isMessageLike};
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/EmailBuilder.tsx","../src/protocol.ts","../src/utils.ts"],"sourcesContent":["import React, {\n CSSProperties,\n ForwardedRef,\n forwardRef,\n useCallback,\n useEffect,\n useImperativeHandle,\n useMemo,\n useRef,\n useState,\n} from 'react';\nimport type { BuilderToHostMessage, HostToBuilderMessage, InitPayload } from './protocol';\nimport { isMessageLike } from './protocol';\nimport { buildEnvelope, deriveAllowedOrigin, stableSignature } from './utils';\nimport type { EmailBuilderHandle, EmailBuilderProps, EmailBuilderStatus } from './types';\n\nconst DEFAULT_SANDBOX = 'allow-scripts allow-same-origin allow-forms';\nconst DEFAULT_INITIAL_HTML = '<h1>Hello World</h1><p>Start building your email template.</p>';\n\ntype PendingMessage = {\n message: HostToBuilderMessage;\n correlationId?: string;\n};\n\nconst overlayStyle: CSSProperties = {\n position: 'absolute',\n inset: 0,\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n fontSize: '0.875rem',\n fontWeight: 500,\n background: 'linear-gradient(135deg, rgba(9,9,9,0.65), rgba(33,33,33,0.85))',\n color: '#fff',\n zIndex: 2,\n};\n\nconst iframeStyle: CSSProperties = {\n border: 'none',\n width: '100%',\n height: '100%',\n};\n\nfunction appendEmbedTokenToSrc(src: string, embedToken: string | undefined): string {\n if (!embedToken || !embedToken.trim()) {\n return src;\n }\n try {\n const u = new URL(src, typeof window !== 'undefined' ? window.location.href : 'https://example.com');\n u.searchParams.set('embedToken', embedToken);\n return u.toString();\n } catch {\n const sep = src.includes('?') ? '&' : '?';\n return `${src}${sep}embedToken=${encodeURIComponent(embedToken)}`;\n }\n}\n\nfunction EmailBuilderInner(\n {\n src,\n initialHtml,\n embedToken,\n templateId,\n config,\n className,\n style,\n iframeTitle = 'Email Builder',\n sandbox = DEFAULT_SANDBOX,\n onChange,\n onSave,\n onUpload,\n onReady,\n onStatusChange,\n onAuthError,\n allowedOrigin,\n }: EmailBuilderProps,\n ref: ForwardedRef<EmailBuilderHandle>\n) {\n const iframeSrc = useMemo(() => appendEmbedTokenToSrc(src, embedToken), [src, embedToken]);\n\n const iframeRef = useRef<HTMLIFrameElement>(null);\n const builderWindowRef = useRef<Window | null>(null);\n const readyRef = useRef(false);\n const statusRef = useRef<EmailBuilderStatus>('loading');\n const [status, setStatus] = useState<EmailBuilderStatus>('loading');\n const [reloadKey, setReloadKey] = useState(0);\n const queueRef = useRef<PendingMessage[]>([]);\n const runtimeOriginRef = useRef<string | null>(null);\n const handshakeTimerRef = useRef<number | null>(null);\n\n const effectiveInitialHtml =\n typeof initialHtml === 'string'\n ? initialHtml\n : templateId\n ? ''\n : DEFAULT_INITIAL_HTML;\n\n const initPayload: InitPayload = {\n html: effectiveInitialHtml,\n config,\n ...(templateId ? { templateId } : {}),\n };\n\n const initSignatureRef = useRef(stableSignature(initPayload));\n const latestInitRef = useRef<HostToBuilderMessage>({\n type: 'INIT',\n payload: initPayload,\n });\n\n const expectedOrigin = useMemo(() => deriveAllowedOrigin(src, allowedOrigin), [src, allowedOrigin]);\n\n const resolveTargetOrigin = useCallback(() => '*', []);\n\n const setStatusSafely = useCallback(\n (next: EmailBuilderStatus) => {\n if (statusRef.current === next) {\n return;\n }\n statusRef.current = next;\n setStatus(next);\n onStatusChange?.(next);\n },\n [onStatusChange]\n );\n\n const postMessage = useCallback(\n (message: HostToBuilderMessage, correlationId?: string) => {\n const target = iframeRef.current?.contentWindow ?? builderWindowRef.current;\n if (target) {\n builderWindowRef.current = target;\n }\n\n if (!builderWindowRef.current || !readyRef.current) {\n queueRef.current.push({ message, correlationId });\n return;\n }\n\n builderWindowRef.current.postMessage(buildEnvelope(message, correlationId), resolveTargetOrigin());\n },\n [resolveTargetOrigin]\n );\n\n const flushQueue = useCallback(() => {\n if (!readyRef.current || !builderWindowRef.current) {\n return;\n }\n const pending = [...queueRef.current];\n queueRef.current = [];\n pending.forEach(({ message, correlationId }) => {\n builderWindowRef.current?.postMessage(\n buildEnvelope(message, correlationId),\n resolveTargetOrigin()\n );\n });\n }, [resolveTargetOrigin]);\n\n const handleReadyMessage = useCallback(() => {\n if (readyRef.current) {\n return;\n }\n if (handshakeTimerRef.current) {\n window.clearTimeout(handshakeTimerRef.current);\n handshakeTimerRef.current = null;\n }\n readyRef.current = true;\n setStatusSafely('ready');\n onReady?.();\n postMessage(latestInitRef.current);\n flushQueue();\n }, [flushQueue, onReady, postMessage, setStatusSafely]);\n\n const handleUpload = useCallback(\n async (eventMessage: BuilderToHostMessage) => {\n if (eventMessage.type !== 'UPLOAD') {\n return;\n }\n if (!onUpload) {\n console.warn('[EmailBuilderSDK] Upload requested but no onUpload handler is configured.');\n return;\n }\n try {\n setStatusSafely('loading');\n const url = await onUpload(eventMessage.payload.file);\n postMessage({ type: 'UPLOAD_SUCCESS', payload: { url } }, eventMessage.meta?.id);\n } catch (error) {\n setStatusSafely('error');\n console.error('[EmailBuilderSDK] Upload handler failed', error);\n } finally {\n if (statusRef.current !== 'error') {\n setStatusSafely('ready');\n }\n }\n },\n [onUpload, postMessage, setStatusSafely]\n );\n\n const handleMessage = useCallback(\n (event: MessageEvent) => {\n const iframeWindow = iframeRef.current?.contentWindow ?? builderWindowRef.current;\n if (!iframeWindow || event.source !== iframeWindow) {\n return;\n }\n if (!isMessageLike(event.data)) {\n return;\n }\n if (!runtimeOriginRef.current) {\n runtimeOriginRef.current = event.origin;\n } else if (event.origin !== runtimeOriginRef.current) {\n return;\n }\n const message = event.data as BuilderToHostMessage;\n\n if (event.source && event.source !== builderWindowRef.current) {\n builderWindowRef.current = event.source as Window;\n }\n\n switch (message.type) {\n case 'READY':\n handleReadyMessage();\n break;\n case 'CHANGE':\n onChange?.(message.payload.html);\n break;\n case 'SAVE':\n onSave?.(message.payload.html);\n break;\n case 'UPLOAD':\n void handleUpload(message);\n break;\n case 'AUTH_ERROR': {\n const msg = message.payload?.message || 'Email builder authentication failed';\n if (statusRef.current !== 'error') {\n statusRef.current = 'error';\n setStatus('error');\n onAuthError?.(msg);\n }\n break;\n }\n default:\n break;\n }\n },\n [handleReadyMessage, handleUpload, onChange, onSave, onAuthError, setStatusSafely]\n );\n\n useEffect(() => {\n if (typeof window === 'undefined') {\n return;\n }\n window.addEventListener('message', handleMessage);\n return () => {\n window.removeEventListener('message', handleMessage);\n };\n }, [handleMessage]);\n\n useEffect(() => {\n const nextPayload: InitPayload = {\n html: effectiveInitialHtml,\n config,\n ...(templateId ? { templateId } : {}),\n };\n const signature = stableSignature(nextPayload);\n latestInitRef.current = { type: 'INIT', payload: nextPayload };\n if (signature !== initSignatureRef.current && readyRef.current) {\n postMessage(latestInitRef.current);\n }\n initSignatureRef.current = signature;\n }, [config, effectiveInitialHtml, postMessage, templateId]);\n\n const handleIframeLoad = useCallback(() => {\n builderWindowRef.current = iframeRef.current?.contentWindow ?? null;\n readyRef.current = false;\n runtimeOriginRef.current = null;\n setStatusSafely('loading');\n\n if (builderWindowRef.current) {\n try {\n builderWindowRef.current.postMessage(buildEnvelope(latestInitRef.current), '*');\n } catch {\n // Ignore and wait for normal READY/message flow.\n }\n }\n\n if (handshakeTimerRef.current) {\n window.clearTimeout(handshakeTimerRef.current);\n }\n handshakeTimerRef.current = window.setTimeout(() => {\n if (!readyRef.current) {\n handleReadyMessage();\n }\n }, 4000);\n }, [expectedOrigin, handleReadyMessage, setStatusSafely]);\n\n useImperativeHandle(\n ref,\n () => ({\n reload() {\n queueRef.current = [];\n readyRef.current = false;\n builderWindowRef.current = null;\n runtimeOriginRef.current = null;\n if (handshakeTimerRef.current) {\n window.clearTimeout(handshakeTimerRef.current);\n handshakeTimerRef.current = null;\n }\n setStatusSafely('loading');\n setReloadKey((key) => key + 1);\n },\n }),\n [setStatusSafely]\n );\n\n useEffect(() => {\n return () => {\n if (handshakeTimerRef.current) {\n window.clearTimeout(handshakeTimerRef.current);\n handshakeTimerRef.current = null;\n }\n };\n }, []);\n\n return (\n <div className={className} style={{ position: 'relative', width: '100%', height: '100%', ...style }}>\n <iframe\n key={reloadKey}\n ref={iframeRef}\n src={iframeSrc}\n title={iframeTitle}\n sandbox={sandbox}\n style={iframeStyle}\n loading=\"lazy\"\n allowFullScreen\n onLoad={handleIframeLoad}\n />\n {status !== 'ready' && <div style={overlayStyle}>Connecting to builder…</div>}\n </div>\n );\n}\n\nexport const EmailBuilder = forwardRef(EmailBuilderInner);\n","export const EMAIL_BUILDER_PROTOCOL_VERSION = '1.0.0';\n\nexport type MessageType =\n | 'INIT'\n | 'READY'\n | 'CHANGE'\n | 'SAVE'\n | 'UPLOAD'\n | 'UPLOAD_SUCCESS'\n | 'AUTH_ERROR';\n\nexport interface MessageMeta {\n id: string;\n correlationId?: string;\n version: string;\n sentAt: number;\n}\n\nexport type BuilderConfig = Record<string, unknown> | undefined;\n\nexport interface InitPayload {\n /** Inline HTML to import (optional if templateId is set and builder fetches server-side). */\n html?: string;\n /** When set, embedded builder fetches HTML from API using embed token + this id. */\n templateId?: string;\n config?: BuilderConfig;\n}\n\nexport interface ChangePayload {\n html: string;\n}\n\nexport interface SavePayload {\n html: string;\n}\n\nexport interface UploadPayload {\n file: File;\n}\n\nexport interface UploadSuccessPayload {\n url: string;\n}\n\nexport interface AuthErrorPayload {\n message: string;\n}\n\nexport type Message =\n | { type: 'INIT'; payload: InitPayload; meta?: MessageMeta }\n | { type: 'READY'; meta?: MessageMeta }\n | { type: 'CHANGE'; payload: ChangePayload; meta?: MessageMeta }\n | { type: 'SAVE'; payload: SavePayload; meta?: MessageMeta }\n | { type: 'UPLOAD'; payload: UploadPayload; meta?: MessageMeta }\n | { type: 'UPLOAD_SUCCESS'; payload: UploadSuccessPayload; meta?: MessageMeta }\n | { type: 'AUTH_ERROR'; payload: AuthErrorPayload; meta?: MessageMeta };\n\nexport type BuilderToHostMessage = Extract<\n Message,\n { type: 'READY' | 'CHANGE' | 'SAVE' | 'UPLOAD' | 'AUTH_ERROR' }\n>;\n\nexport type HostToBuilderMessage = Extract<\n Message,\n { type: 'INIT' | 'UPLOAD_SUCCESS' }\n>;\n\nconst VALID_TYPES: MessageType[] = [\n 'INIT',\n 'READY',\n 'CHANGE',\n 'SAVE',\n 'UPLOAD',\n 'UPLOAD_SUCCESS',\n 'AUTH_ERROR',\n];\n\nexport function isMessageLike(value: unknown): value is Message {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n\n const candidate = value as { type?: unknown; payload?: unknown; meta?: unknown };\n if (typeof candidate.type !== 'string' || !VALID_TYPES.includes(candidate.type as MessageType)) {\n return false;\n }\n\n if ('meta' in candidate && candidate.meta !== undefined) {\n const meta = candidate.meta as Partial<MessageMeta>;\n if (\n (meta.id && typeof meta.id !== 'string') ||\n (meta.correlationId && typeof meta.correlationId !== 'string') ||\n (meta.version && typeof meta.version !== 'string') ||\n (meta.sentAt && typeof meta.sentAt !== 'number')\n ) {\n return false;\n }\n }\n\n return true;\n}\n\nexport function createMessageMeta(correlationId?: string): MessageMeta {\n const id = typeof crypto !== 'undefined' && 'randomUUID' in crypto\n ? crypto.randomUUID()\n : Math.random().toString(36).slice(2);\n return {\n id,\n correlationId,\n version: EMAIL_BUILDER_PROTOCOL_VERSION,\n sentAt: Date.now(),\n };\n}\n","import type { BuilderToHostMessage, HostToBuilderMessage, MessageMeta } from './protocol';\nimport { createMessageMeta, isMessageLike } from './protocol';\n\nexport function deriveAllowedOrigin(src: string, override?: string): string {\n if (override) {\n const parsed = new URL(override);\n if (parsed.origin === 'null') {\n throw new Error('allowedOrigin must resolve to a valid origin');\n }\n return parsed.origin;\n }\n\n let parsed: URL;\n try {\n parsed = new URL(src);\n } catch {\n throw new Error('EmailBuilder `src` must be an absolute URL (e.g. https://example.com)');\n }\n if (!parsed.origin || parsed.origin === 'null') {\n throw new Error('EmailBuilder requires an absolute src URL with a valid origin');\n }\n return parsed.origin;\n}\n\nexport function buildEnvelope<T extends HostToBuilderMessage>(message: T, correlationId?: string): T {\n const meta: MessageMeta = createMessageMeta(correlationId);\n return { ...message, meta } as T;\n}\n\nexport function sanitizeIncomingMessage(\n event: MessageEvent,\n allowedOrigin: string,\n iframeWindow: Window | null\n): BuilderToHostMessage | null {\n if (event.origin !== allowedOrigin) {\n return null;\n }\n\n if (!iframeWindow || event.source !== iframeWindow) {\n return null;\n }\n\n if (!isMessageLike(event.data)) {\n return null;\n }\n\n return event.data as BuilderToHostMessage;\n}\n\nexport function stableSignature(value: unknown): string {\n return JSON.stringify(value ?? null);\n}\n"],"mappings":"AAAA,OAGE,cAAAA,GACA,eAAAC,EACA,aAAAC,EACA,uBAAAC,GACA,WAAAC,EACA,UAAAC,EACA,YAAAC,MACK,QCVA,IAAMC,GAAiC,QAmExCC,GAA6B,CACjC,OACA,QACA,SACA,OACA,SACA,iBACA,YACF,EAEO,SAASC,EAAcC,EAAkC,CAC9D,GAAI,OAAOA,GAAU,UAAYA,IAAU,KACzC,MAAO,GAGT,IAAMC,EAAYD,EAClB,GAAI,OAAOC,EAAU,MAAS,UAAY,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AiB,QAAU,KAC3BW,EAAgB,SAAS,EAErBpB,EAAiB,QACnB,GAAI,CACFA,EAAiB,QAAQ,YAAY4B,EAAcb,EAAc,OAAO,EAAG,GAAG,CAChF,MAAQ,CAER,CAGEL,EAAkB,SACpB,OAAO,aAAaA,EAAkB,OAAO,EAE/CA,EAAkB,QAAU,OAAO,WAAW,IAAM,CAC7CT,EAAS,SACZ8B,EAAmB,CAEvB,EAAG,GAAI,CACT,EAAG,CAACf,GAAgBe,EAAoBX,CAAe,CAAC,EAExD,OAAA0B,GACEnD,EACA,KAAO,CACL,QAAS,CACPa,EAAS,QAAU,CAAC,EACpBP,EAAS,QAAU,GACnBD,EAAiB,QAAU,KAC3BS,EAAiB,QAAU,KACvBC,EAAkB,UACpB,OAAO,aAAaA,EAAkB,OAAO,EAC7CA,EAAkB,QAAU,MAE9BU,EAAgB,SAAS,EACzBb,GAAcwC,GAAQA,EAAM,CAAC,CAC/B,CACF,GACA,CAAC3B,CAAe,CAClB,EAEAsB,EAAU,IACD,IAAM,CACPhC,EAAkB,UACpB,OAAO,aAAaA,EAAkB,OAAO,EAC7CA,EAAkB,QAAU,KAEhC,EACC,CAAC,CAAC,EAGHxC,GAAC,OAAI,UAAWc,EAAW,MAAO,CAAE,SAAU,WAAY,MAAO,OAAQ,OAAQ,OAAQ,GAAGC,CAAM,EAChG,UAAAhB,EAAC,UAEC,IAAK6B,EACL,IAAKF,EACL,MAAOV,EACP,QAASC,EACT,MAAOb,GACP,QAAQ,OACR,gBAAe,GACf,OAAQuE,IARHvC,EASP,EACCH,KAAW,SAAWlC,EAAC,OAAI,MAAOI,GAAc,uCAAsB,GACzE,CAEJ,CAEO,IAAM2E,GAAeC,GAAWrE,EAAiB","names":["forwardRef","useCallback","useEffect","useImperativeHandle","useMemo","useRef","useState","EMAIL_BUILDER_PROTOCOL_VERSION","VALID_TYPES","isMessageLike","value","candidate","meta","createMessageMeta","correlationId","deriveAllowedOrigin","src","override","parsed","buildEnvelope","message","correlationId","meta","createMessageMeta","stableSignature","value","jsx","jsxs","DEFAULT_SANDBOX","DEFAULT_INITIAL_HTML","overlayStyle","iframeStyle","appendEmbedTokenToSrc","src","embedToken","u","sep","EmailBuilderInner","initialHtml","templateId","config","className","style","iframeTitle","sandbox","onChange","onSave","onUpload","onReady","onStatusChange","onAuthError","allowedOrigin","ref","iframeSrc","useMemo","iframeRef","useRef","builderWindowRef","readyRef","statusRef","status","setStatus","useState","reloadKey","setReloadKey","queueRef","runtimeOriginRef","handshakeTimerRef","effectiveInitialHtml","initPayload","initSignatureRef","stableSignature","latestInitRef","expectedOrigin","deriveAllowedOrigin","resolveTargetOrigin","useCallback","setStatusSafely","next","postMessage","message","correlationId","_a","_b","target","buildEnvelope","flushQueue","pending","handleReadyMessage","handleUpload","eventMessage","url","error","handleMessage","event","_c","iframeWindow","isMessageLike","msg","useEffect","nextPayload","signature","handleIframeLoad","useImperativeHandle","key","EmailBuilder","forwardRef"]}
1
+ {"version":3,"sources":["../src/EmailBuilder.tsx","../src/protocol.ts","../src/utils.ts"],"sourcesContent":["import React, {\n CSSProperties,\n ForwardedRef,\n forwardRef,\n useCallback,\n useEffect,\n useImperativeHandle,\n useMemo,\n useRef,\n useState,\n} from 'react';\nimport type { BuilderToHostMessage, HostToBuilderMessage, InitPayload } from './protocol';\nimport { isMessageLike } from './protocol';\nimport { buildEnvelope, deriveAllowedOrigin, stableSignature } from './utils';\nimport type { EmailBuilderHandle, EmailBuilderProps, EmailBuilderStatus } from './types';\n\nconst DEFAULT_SANDBOX = 'allow-scripts allow-same-origin allow-forms';\nconst DEFAULT_INITIAL_HTML = '<h1>Hello World</h1><p>Start building your email template.</p>';\n\ntype PendingMessage = {\n message: HostToBuilderMessage;\n correlationId?: string;\n};\n\nconst overlayStyle: CSSProperties = {\n position: 'absolute',\n inset: 0,\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n fontSize: '0.875rem',\n fontWeight: 500,\n background: 'linear-gradient(135deg, rgba(9,9,9,0.65), rgba(33,33,33,0.85))',\n color: '#fff',\n zIndex: 2,\n};\n\nconst iframeStyle: CSSProperties = {\n border: 'none',\n width: '100%',\n height: '100%',\n};\n\nfunction appendEmbedTokenToSrc(src: string, embedToken: string | undefined): string {\n if (!embedToken || !embedToken.trim()) {\n return src;\n }\n try {\n const u = new URL(src, typeof window !== 'undefined' ? window.location.href : 'https://example.com');\n u.searchParams.set('embedToken', embedToken);\n return u.toString();\n } catch {\n const sep = src.includes('?') ? '&' : '?';\n return `${src}${sep}embedToken=${encodeURIComponent(embedToken)}`;\n }\n}\n\nfunction EmailBuilderInner(\n {\n src,\n initialHtml,\n embedToken,\n templateId,\n config,\n className,\n style,\n iframeTitle = 'Email Builder',\n sandbox = DEFAULT_SANDBOX,\n onChange,\n onSave,\n onUpload,\n onReady,\n onStatusChange,\n onAuthError,\n allowedOrigin,\n }: EmailBuilderProps,\n ref: ForwardedRef<EmailBuilderHandle>\n) {\n const iframeSrc = useMemo(() => appendEmbedTokenToSrc(src, embedToken), [src, embedToken]);\n\n const iframeRef = useRef<HTMLIFrameElement>(null);\n const builderWindowRef = useRef<Window | null>(null);\n const readyRef = useRef(false);\n const statusRef = useRef<EmailBuilderStatus>('loading');\n const [status, setStatus] = useState<EmailBuilderStatus>('loading');\n const [reloadKey, setReloadKey] = useState(0);\n const queueRef = useRef<PendingMessage[]>([]);\n const runtimeOriginRef = useRef<string | null>(null);\n const handshakeTimerRef = useRef<number | null>(null);\n const handshakeRetryIntervalRef = useRef<number | null>(null);\n\n const effectiveInitialHtml =\n typeof initialHtml === 'string'\n ? initialHtml\n : templateId\n ? ''\n : DEFAULT_INITIAL_HTML;\n\n const initPayload: InitPayload = {\n html: effectiveInitialHtml,\n config,\n ...(templateId ? { templateId } : {}),\n };\n\n const initSignatureRef = useRef(stableSignature(initPayload));\n const latestInitRef = useRef<HostToBuilderMessage>({\n type: 'INIT',\n payload: initPayload,\n });\n\n const expectedOrigin = useMemo(() => deriveAllowedOrigin(src, allowedOrigin), [src, allowedOrigin]);\n\n const resolveTargetOrigin = useCallback(() => '*', []);\n\n const setStatusSafely = useCallback(\n (next: EmailBuilderStatus) => {\n if (statusRef.current === next) {\n return;\n }\n statusRef.current = next;\n setStatus(next);\n onStatusChange?.(next);\n },\n [onStatusChange]\n );\n\n const postMessage = useCallback(\n (message: HostToBuilderMessage, correlationId?: string) => {\n const target = iframeRef.current?.contentWindow ?? builderWindowRef.current;\n if (target) {\n builderWindowRef.current = target;\n }\n\n if (!builderWindowRef.current || !readyRef.current) {\n queueRef.current.push({ message, correlationId });\n return;\n }\n\n builderWindowRef.current.postMessage(buildEnvelope(message, correlationId), resolveTargetOrigin());\n },\n [resolveTargetOrigin]\n );\n\n const flushQueue = useCallback(() => {\n if (!readyRef.current || !builderWindowRef.current) {\n return;\n }\n const pending = [...queueRef.current];\n queueRef.current = [];\n pending.forEach(({ message, correlationId }) => {\n builderWindowRef.current?.postMessage(\n buildEnvelope(message, correlationId),\n resolveTargetOrigin()\n );\n });\n }, [resolveTargetOrigin]);\n\n const handleReadyMessage = useCallback(() => {\n if (readyRef.current) {\n return;\n }\n if (handshakeTimerRef.current) {\n window.clearTimeout(handshakeTimerRef.current);\n handshakeTimerRef.current = null;\n }\n if (handshakeRetryIntervalRef.current) {\n window.clearInterval(handshakeRetryIntervalRef.current);\n handshakeRetryIntervalRef.current = null;\n }\n readyRef.current = true;\n setStatusSafely('ready');\n onReady?.();\n postMessage(latestInitRef.current);\n flushQueue();\n }, [flushQueue, onReady, postMessage, setStatusSafely]);\n\n const handleUpload = useCallback(\n async (eventMessage: BuilderToHostMessage) => {\n if (eventMessage.type !== 'UPLOAD') {\n return;\n }\n if (!onUpload) {\n console.warn('[EmailBuilderSDK] Upload requested but no onUpload handler is configured.');\n return;\n }\n try {\n setStatusSafely('loading');\n const url = await onUpload(eventMessage.payload.file);\n postMessage({ type: 'UPLOAD_SUCCESS', payload: { url } }, eventMessage.meta?.id);\n } catch (error) {\n setStatusSafely('error');\n console.error('[EmailBuilderSDK] Upload handler failed', error);\n } finally {\n if (statusRef.current !== 'error') {\n setStatusSafely('ready');\n }\n }\n },\n [onUpload, postMessage, setStatusSafely]\n );\n\n const handleMessage = useCallback(\n (event: MessageEvent) => {\n const iframeWindow = iframeRef.current?.contentWindow ?? builderWindowRef.current;\n if (!iframeWindow || event.source !== iframeWindow) {\n return;\n }\n if (!isMessageLike(event.data)) {\n return;\n }\n if (!runtimeOriginRef.current) {\n runtimeOriginRef.current = event.origin;\n } else if (event.origin !== runtimeOriginRef.current) {\n return;\n }\n const message = event.data as BuilderToHostMessage;\n\n if (event.source && event.source !== builderWindowRef.current) {\n builderWindowRef.current = event.source as Window;\n }\n\n switch (message.type) {\n case 'READY':\n handleReadyMessage();\n break;\n case 'CHANGE':\n onChange?.(message.payload.html);\n break;\n case 'SAVE':\n onSave?.(message.payload.html);\n break;\n case 'UPLOAD':\n void handleUpload(message);\n break;\n case 'AUTH_ERROR': {\n const msg = message.payload?.message || 'Email builder authentication failed';\n if (statusRef.current !== 'error') {\n statusRef.current = 'error';\n setStatus('error');\n onAuthError?.(msg);\n }\n break;\n }\n default:\n break;\n }\n },\n [handleReadyMessage, handleUpload, onChange, onSave, onAuthError, setStatusSafely]\n );\n\n useEffect(() => {\n if (typeof window === 'undefined') {\n return;\n }\n window.addEventListener('message', handleMessage);\n return () => {\n window.removeEventListener('message', handleMessage);\n };\n }, [handleMessage]);\n\n useEffect(() => {\n const nextPayload: InitPayload = {\n html: effectiveInitialHtml,\n config,\n ...(templateId ? { templateId } : {}),\n };\n const signature = stableSignature(nextPayload);\n latestInitRef.current = { type: 'INIT', payload: nextPayload };\n if (signature !== initSignatureRef.current && readyRef.current) {\n postMessage(latestInitRef.current);\n }\n initSignatureRef.current = signature;\n }, [config, effectiveInitialHtml, postMessage, templateId]);\n\n const handleIframeLoad = useCallback(() => {\n builderWindowRef.current = iframeRef.current?.contentWindow ?? null;\n readyRef.current = false;\n runtimeOriginRef.current = null;\n setStatusSafely('loading');\n\n if (builderWindowRef.current) {\n try {\n builderWindowRef.current.postMessage(buildEnvelope(latestInitRef.current), '*');\n } catch {\n // Ignore and wait for normal READY/message flow.\n }\n }\n\n if (handshakeTimerRef.current) {\n window.clearTimeout(handshakeTimerRef.current);\n }\n if (handshakeRetryIntervalRef.current) {\n window.clearInterval(handshakeRetryIntervalRef.current);\n }\n\n let attempts = 0;\n const maxAttempts = 12;\n handshakeRetryIntervalRef.current = window.setInterval(() => {\n if (readyRef.current) {\n if (handshakeRetryIntervalRef.current) {\n window.clearInterval(handshakeRetryIntervalRef.current);\n handshakeRetryIntervalRef.current = null;\n }\n return;\n }\n attempts += 1;\n try {\n builderWindowRef.current?.postMessage(buildEnvelope(latestInitRef.current), '*');\n } catch {\n // Keep retrying until timeout.\n }\n if (attempts >= maxAttempts) {\n if (handshakeRetryIntervalRef.current) {\n window.clearInterval(handshakeRetryIntervalRef.current);\n handshakeRetryIntervalRef.current = null;\n }\n }\n }, 1000);\n\n handshakeTimerRef.current = window.setTimeout(() => {\n if (readyRef.current) {\n return;\n }\n if (handshakeRetryIntervalRef.current) {\n window.clearInterval(handshakeRetryIntervalRef.current);\n handshakeRetryIntervalRef.current = null;\n }\n setStatusSafely('error');\n onAuthError?.('Builder handshake failed or authentication was rejected.');\n }, 12000);\n }, [onAuthError, setStatusSafely]);\n\n useImperativeHandle(\n ref,\n () => ({\n reload() {\n queueRef.current = [];\n readyRef.current = false;\n builderWindowRef.current = null;\n runtimeOriginRef.current = null;\n if (handshakeTimerRef.current) {\n window.clearTimeout(handshakeTimerRef.current);\n handshakeTimerRef.current = null;\n }\n if (handshakeRetryIntervalRef.current) {\n window.clearInterval(handshakeRetryIntervalRef.current);\n handshakeRetryIntervalRef.current = null;\n }\n setStatusSafely('loading');\n setReloadKey((key) => key + 1);\n },\n }),\n [setStatusSafely]\n );\n\n useEffect(() => {\n return () => {\n if (handshakeTimerRef.current) {\n window.clearTimeout(handshakeTimerRef.current);\n handshakeTimerRef.current = null;\n }\n if (handshakeRetryIntervalRef.current) {\n window.clearInterval(handshakeRetryIntervalRef.current);\n handshakeRetryIntervalRef.current = null;\n }\n };\n }, []);\n\n return (\n <div className={className} style={{ position: 'relative', width: '100%', height: '100%', ...style }}>\n <iframe\n key={reloadKey}\n ref={iframeRef}\n src={iframeSrc}\n title={iframeTitle}\n sandbox={sandbox}\n style={iframeStyle}\n loading=\"lazy\"\n allowFullScreen\n onLoad={handleIframeLoad}\n />\n {status !== 'ready' && <div style={overlayStyle}>Connecting to builder…</div>}\n </div>\n );\n}\n\nexport const EmailBuilder = forwardRef(EmailBuilderInner);\n","export const EMAIL_BUILDER_PROTOCOL_VERSION = '1.0.0';\n\nexport type MessageType =\n | 'INIT'\n | 'READY'\n | 'CHANGE'\n | 'SAVE'\n | 'UPLOAD'\n | 'UPLOAD_SUCCESS'\n | 'AUTH_ERROR';\n\nexport interface MessageMeta {\n id: string;\n correlationId?: string;\n version: string;\n sentAt: number;\n}\n\nexport type BuilderConfig = Record<string, unknown> | undefined;\n\nexport interface InitPayload {\n /** Inline HTML to import (optional if templateId is set and builder fetches server-side). */\n html?: string;\n /** When set, embedded builder fetches HTML from API using embed token + this id. */\n templateId?: string;\n config?: BuilderConfig;\n}\n\nexport interface ChangePayload {\n html: string;\n}\n\nexport interface SavePayload {\n html: string;\n}\n\nexport interface UploadPayload {\n file: File;\n}\n\nexport interface UploadSuccessPayload {\n url: string;\n}\n\nexport interface AuthErrorPayload {\n message: string;\n}\n\nexport type Message =\n | { type: 'INIT'; payload: InitPayload; meta?: MessageMeta }\n | { type: 'READY'; meta?: MessageMeta }\n | { type: 'CHANGE'; payload: ChangePayload; meta?: MessageMeta }\n | { type: 'SAVE'; payload: SavePayload; meta?: MessageMeta }\n | { type: 'UPLOAD'; payload: UploadPayload; meta?: MessageMeta }\n | { type: 'UPLOAD_SUCCESS'; payload: UploadSuccessPayload; meta?: MessageMeta }\n | { type: 'AUTH_ERROR'; payload: AuthErrorPayload; meta?: MessageMeta };\n\nexport type BuilderToHostMessage = Extract<\n Message,\n { type: 'READY' | 'CHANGE' | 'SAVE' | 'UPLOAD' | 'AUTH_ERROR' }\n>;\n\nexport type HostToBuilderMessage = Extract<\n Message,\n { type: 'INIT' | 'UPLOAD_SUCCESS' }\n>;\n\nconst VALID_TYPES: MessageType[] = [\n 'INIT',\n 'READY',\n 'CHANGE',\n 'SAVE',\n 'UPLOAD',\n 'UPLOAD_SUCCESS',\n 'AUTH_ERROR',\n];\n\nexport function isMessageLike(value: unknown): value is Message {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n\n const candidate = value as { type?: unknown; payload?: unknown; meta?: unknown };\n if (typeof candidate.type !== 'string' || !VALID_TYPES.includes(candidate.type as MessageType)) {\n return false;\n }\n\n if ('meta' in candidate && candidate.meta !== undefined) {\n const meta = candidate.meta as Partial<MessageMeta>;\n if (\n (meta.id && typeof meta.id !== 'string') ||\n (meta.correlationId && typeof meta.correlationId !== 'string') ||\n (meta.version && typeof meta.version !== 'string') ||\n (meta.sentAt && typeof meta.sentAt !== 'number')\n ) {\n return false;\n }\n }\n\n return true;\n}\n\nexport function createMessageMeta(correlationId?: string): MessageMeta {\n const id = typeof crypto !== 'undefined' && 'randomUUID' in crypto\n ? crypto.randomUUID()\n : Math.random().toString(36).slice(2);\n return {\n id,\n correlationId,\n version: EMAIL_BUILDER_PROTOCOL_VERSION,\n sentAt: Date.now(),\n };\n}\n","import type { BuilderToHostMessage, HostToBuilderMessage, MessageMeta } from './protocol';\nimport { createMessageMeta, isMessageLike } from './protocol';\n\nexport function deriveAllowedOrigin(src: string, override?: string): string {\n if (override) {\n const parsed = new URL(override);\n if (parsed.origin === 'null') {\n throw new Error('allowedOrigin must resolve to a valid origin');\n }\n return parsed.origin;\n }\n\n let parsed: URL;\n try {\n parsed = new URL(src);\n } catch {\n throw new Error('EmailBuilder `src` must be an absolute URL (e.g. https://example.com)');\n }\n if (!parsed.origin || parsed.origin === 'null') {\n throw new Error('EmailBuilder requires an absolute src URL with a valid origin');\n }\n return parsed.origin;\n}\n\nexport function buildEnvelope<T extends HostToBuilderMessage>(message: T, correlationId?: string): T {\n const meta: MessageMeta = createMessageMeta(correlationId);\n return { ...message, meta } as T;\n}\n\nexport function sanitizeIncomingMessage(\n event: MessageEvent,\n allowedOrigin: string,\n iframeWindow: Window | null\n): BuilderToHostMessage | null {\n if (event.origin !== allowedOrigin) {\n return null;\n }\n\n if (!iframeWindow || event.source !== iframeWindow) {\n return null;\n }\n\n if (!isMessageLike(event.data)) {\n return null;\n }\n\n return event.data as BuilderToHostMessage;\n}\n\nexport function stableSignature(value: unknown): string {\n return JSON.stringify(value ?? null);\n}\n"],"mappings":"AAAA,OAGE,cAAAA,GACA,eAAAC,EACA,aAAAC,EACA,uBAAAC,GACA,WAAAC,EACA,UAAAC,EACA,YAAAC,MACK,QCVA,IAAMC,GAAiC,QAmExCC,GAA6B,CACjC,OACA,QACA,SACA,OACA,SACA,iBACA,YACF,EAEO,SAASC,EAAcC,EAAkC,CAC9D,GAAI,OAAOA,GAAU,UAAYA,IAAU,KACzC,MAAO,GAGT,IAAMC,EAAYD,EAClB,GAAI,OAAOC,EAAU,MAAS,UAAY,CAACH,GAAY,SAASG,EAAU,IAAmB,EAC3F,MAAO,GAGT,GAAI,SAAUA,GAAaA,EAAU,OAAS,OAAW,CACvD,IAAMC,EAAOD,EAAU,KACvB,GACGC,EAAK,IAAM,OAAOA,EAAK,IAAO,UAC9BA,EAAK,eAAiB,OAAOA,EAAK,eAAkB,UACpDA,EAAK,SAAW,OAAOA,EAAK,SAAY,UACxCA,EAAK,QAAU,OAAOA,EAAK,QAAW,SAEvC,MAAO,EAEX,CAEA,MAAO,EACT,CAEO,SAASC,EAAkBC,EAAqC,CAIrE,MAAO,CACL,GAJS,OAAO,QAAW,aAAe,eAAgB,OACxD,OAAO,WAAW,EAClB,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,CAAC,EAGpC,cAAAA,EACA,QAASP,GACT,OAAQ,KAAK,IAAI,CACnB,C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ARHxC,EASP,EACCH,KAAW,SAAWlC,EAAC,OAAI,MAAOI,GAAc,uCAAsB,GACzE,CAEJ,CAEO,IAAM8E,GAAeC,GAAWxE,EAAiB","names":["forwardRef","useCallback","useEffect","useImperativeHandle","useMemo","useRef","useState","EMAIL_BUILDER_PROTOCOL_VERSION","VALID_TYPES","isMessageLike","value","candidate","meta","createMessageMeta","correlationId","deriveAllowedOrigin","src","override","parsed","buildEnvelope","message","correlationId","meta","createMessageMeta","stableSignature","value","jsx","jsxs","DEFAULT_SANDBOX","DEFAULT_INITIAL_HTML","overlayStyle","iframeStyle","appendEmbedTokenToSrc","src","embedToken","u","sep","EmailBuilderInner","initialHtml","templateId","config","className","style","iframeTitle","sandbox","onChange","onSave","onUpload","onReady","onStatusChange","onAuthError","allowedOrigin","ref","iframeSrc","useMemo","iframeRef","useRef","builderWindowRef","readyRef","statusRef","status","setStatus","useState","reloadKey","setReloadKey","queueRef","runtimeOriginRef","handshakeTimerRef","handshakeRetryIntervalRef","effectiveInitialHtml","initPayload","initSignatureRef","stableSignature","latestInitRef","expectedOrigin","deriveAllowedOrigin","resolveTargetOrigin","useCallback","setStatusSafely","next","postMessage","message","correlationId","_a","_b","target","buildEnvelope","flushQueue","pending","handleReadyMessage","handleUpload","eventMessage","url","error","handleMessage","event","_c","iframeWindow","isMessageLike","msg","useEffect","nextPayload","signature","handleIframeLoad","attempts","maxAttempts","useImperativeHandle","key","EmailBuilder","forwardRef"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alihaiderrana/email-builder-sdk",
3
- "version": "0.1.6",
3
+ "version": "0.1.7",
4
4
  "description": "React iframe SDK for embedding the Circles email template builder",
5
5
  "license": "MIT",
6
6
  "type": "module",