@salla.sa/embedded-sdk 0.2.4 → 0.2.6

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.
@@ -1,4 +1,4 @@
1
- System.register("SallaEmbeddedSDK",[],function(v,Ie){"use strict";return{execute:function(){v({getEmbeddedApp:_,resetEmbeddedApp:Re});const o="embedded::",C={INIT:`${o}iframe.ready`,READY:`${o}ready`,DESTROY:`${o}destroy`},x={PROVIDE:`${o}context.provide`,THEME_CHANGE:`${o}theme.change`},f={LOADING:`${o}ui.loading`,TOAST:`${o}ui.toast`,CONFIRM:`${o}ui.confirm`,CONFIRM_RESPONSE:`${o}ui.confirm.response`},W={},L={REFRESH:`${o}auth.refresh`},m={NAVIGATE:`${o}page.navigate`,REDIRECT:`${o}page.redirect`,SET_TITLE:`${o}page.setTitle`},w={SET_ACTION:`${o}nav.setAction`,CLEAR_ACTION:`${o}nav.clearAction`,ACTION_CLICK:`${o}nav.actionClick`},p={CREATE:`${o}checkout.create`,RESPONSE:`${o}checkout.response`,GET_ADDONS:`${o}checkout.getAddons`,GET_ADDONS_RESPONSE:`${o}checkout.getAddons.response`},S=W.version||"",Y=1e4,B=["localhost","merchants.workers.dev","s.salla.sa",".salla.group",".salla.sa"];let A={showVersion:!0,debug:!1};function Q(t){A={...A,...t}}function k(t){return`%c${t}`}function q(t,e="#fff"){return`background-color: ${t}; color: ${e}; padding: 2px 6px; border-radius: 3px; font-weight: 500; font-size: 11px;`}function b(t,...e){if(t==="debug"&&!A.debug)return;const r=[],i=[];r.push(k("EmbeddedSDK")),i.push(q("#10b981","#fff")),A.showVersion&&(r.push(k(`v${S}`)),i.push(q("#6b7280","#fff")));const n=r.join("").trim();(console[t]||console.log)(n,...i,...e)}const a={log:(...t)=>{b("log",...t)},warn:(...t)=>{b("warn",...t)},error:(...t)=>{b("error",...t)},info:(...t)=>{b("info",...t)},debug:(...t)=>{b("debug",...t)}};function J(t){try{const r=new URL(t).hostname;return B.some(i=>i.startsWith(".")?r.endsWith(i)||r===i.slice(1):r===i||r.startsWith(`${i}:`))}catch{return!1}}function Z(){return typeof window>"u"||window.parent===window?null:window.parent}function u(t,e,r="*",i,n){const s=Z();if(!s){a.warn("Not running in an iframe, cannot post to host");return}const c={event:t,payload:e||{},timestamp:Date.now(),source:"embedded-app",...i&&{requestId:i},metadata:{version:S}};s.postMessage(c,r)}const l=new Map;let R=!1;function z(t){if(process.env.NODE_ENV==="production"&&!J(t.origin))return;const e=t.data;if(!e||typeof e.event!="string"||!e.payload||typeof e.timestamp!="number"||!e.source){a.warn("Invalid message structure received:",e);return}const r=l.get(e.event);r&&r.forEach(n=>{try{n(e)}catch(s){a.error("Error in message handler:",s)}});const i=l.get("*");i&&i.forEach(n=>{try{n(e)}catch(s){a.error("Error in wildcard handler:",s)}})}function ee(){R||typeof window>"u"||(window.addEventListener("message",z),R=!0)}function E(t,e){ee(),l.has(t)||l.set(t,new Set);const r=l.get(t);return r.add(e),()=>{r.delete(e),r.size===0&&l.delete(t)}}function te(t,e=Y){return new Promise((r,i)=>{const n=setTimeout(()=>{s(),i(new Error(`[EmbeddedSDK] Timeout waiting for "${t}" message`))},e),s=E(t,c=>{clearTimeout(n),s(),r(c)})})}function re(){l.clear(),R&&typeof window<"u"&&(window.removeEventListener("message",z),R=!1)}function ie(){return typeof window>"u"?!1:window.parent!==window}function ne(t,e,r){const i={event:t,payload:e,timestamp:Date.now(),source:"merchant-dashboard",...r,metadata:{version:S,synthetic:!0}},n=l.get(t);n==null||n.forEach(s=>{try{s(i)}catch(c){a.error("Error in message handler:",c)}})}const h=new Map,se=3e4;function M(){const t=Date.now(),e=Math.random().toString(36).slice(2,9);return`req_${t}_${e}`}function P(t,e={},r=se){const i=M();return new Promise((n,s)=>{const c=setTimeout(()=>{h.get(i)&&(h.delete(i),s(new Error(`[EmbeddedSDK] Request "${t}" timed out after ${r}ms`)))},r);h.set(i,{resolve:n,reject:s,timeout:c,event:t}),u(t,e,"*",i)})}function U(t,e,r){const i=h.get(t);if(!i){a.warn(`Received response for unknown request: ${t}`);return}clearTimeout(i.timeout),h.delete(t),i.resolve(e)}function ae(t="SDK cleanup"){h.forEach((e,r)=>{clearTimeout(e.timeout),e.reject(new Error(`[EmbeddedSDK] Request ${r} cancelled: ${t}`))}),h.clear()}function I(){const t=new Set;return{subscribe(e){return t.add(e),()=>{t.delete(e)}},notify(...e){t.forEach(r=>{try{r(...e)}catch(i){a.error("Error in subscription callback:",i)}})},clear(){t.clear()},size(){return t.size}}}const oe="https://api.salla.dev";class T extends Error{constructor(e,r,i){super(e),this.status=r,this.response=i,this.name="ApiError"}}async function ue(t,e={}){const{method:r="GET",headers:i={},body:n,timeout:s=3e4}=e,c=`${oe}${t}`,O=new AbortController,X=setTimeout(()=>{O.abort()},s);try{const d=await fetch(c,{method:r,headers:{"Content-Type":"application/json",...i},body:n?JSON.stringify(n):void 0,signal:O.signal});clearTimeout(X);let N;const D=d.headers.get("content-type");if(D!=null&&D.includes("application/json")?N=await d.json():N=await d.text(),!d.ok)throw new T(`API request failed: ${d.statusText}`,d.status,N);return N}catch(d){throw clearTimeout(X),d instanceof T?d:d instanceof Error?d.name==="AbortError"?new T(`Request timeout after ${s}ms`):new T(`Request failed: ${d.message}`):new T("Unknown error occurred")}}function $(t){return{isVerified:!1,isError:!0,error:t,data:null}}async function ce(t){const{token:e,appId:r,refreshOnError:i=!0}=t;if(!e){const n="Token is required. Provide it as a parameter or in URL as ?token=XXX";return a.error("Error in introspect:",n),$(n)}if(!r){const n="App ID is required. Provide it as a parameter or in URL as ?app_id=XXX";return a.error("Error in introspect:",n),$(n)}try{const n=await ue("/exchange-authority/v1/introspect",{method:"POST",headers:{"S-Source":r,"Content-Type":"application/json"},body:{env:"prod",token:e,iss:"merchant-dashboard",subject:"embedded-page"}}),s=n.success;return{isVerified:s,isError:!s,error:s?void 0:"API request failed",data:s?n.data:null}}catch(n){i&&(_().ui.toast.error((n==null?void 0:n.toString())??"Introspect error"),u(L.REFRESH,{})),a.error("Error in introspect:",n);const s=n instanceof Error?n.message:n;return $(s)}}function de(t){return{getToken(){return new URLSearchParams(window.location.search).get("token")},getAppId(){return new URLSearchParams(window.location.search).get("app_id")},refresh(){u(L.REFRESH,{})},async introspect(e={}){const r=e.token??this.getToken()??"",i=e.appId??this.getAppId()??"";return ce({token:r,appId:i,refreshOnError:e.refreshOnError})}}}const V=["success","error","warning","info"];function le(t){const e=[];return t.type===void 0||t.type===null?e.push("Toast type is required"):(typeof t.type!="string"||!V.includes(t.type))&&e.push(`Invalid toast type "${t.type}". Expected: ${V.join(" | ")}`),t.message===void 0||t.message===null?e.push("Toast message is required"):typeof t.message!="string"?e.push("Toast message must be a string"):t.message.trim()===""&&e.push("Toast message cannot be empty"),t.duration!==void 0&&t.duration!==null&&(typeof t.duration!="number"?e.push("Toast duration must be a number"):t.duration<0&&e.push("Toast duration cannot be negative")),{valid:e.length===0,errors:e}}function F(t,e){const r=[];return typeof t!="object"||t===null?(r.push(`${e} must be an object`),r):((typeof t.type!="string"||t.type.trim()==="")&&r.push(`${e} must have a valid type`),(typeof t.slug!="string"||t.slug.trim()==="")&&r.push(`${e} must have a valid slug`),t.quantity!==void 0&&(typeof t.quantity!="number"||t.quantity<1)&&r.push(`${e} must have a quantity >= 1`),r)}function fe(t){const e=[];if(typeof t!="object"||t===null)return e.push("Checkout options must be an object"),{valid:!1,errors:e};const r="item"in t,i="items"in t;if(!r&&!i)return e.push("Checkout requires either 'item' or 'items'"),{valid:!1,errors:e};if(r){const n=F(t.item,"Item");return e.push(...n),{valid:e.length===0,errors:e}}return Array.isArray(t.items)?t.items.length===0?(e.push("At least one item is required"),{valid:!1,errors:e}):(t.items.forEach((n,s)=>{const c=F(n,`Item at index ${s}`);e.push(...c)}),{valid:e.length===0,errors:e}):(e.push("Checkout items must be an array"),{valid:!1,errors:e})}function he(t){const e=[];return t.path===void 0||t.path===null?e.push("Navigation path is required"):typeof t.path!="string"?e.push("Navigation path must be a string"):t.path.trim()===""&&e.push("Navigation path cannot be empty"),t.replace!==void 0&&typeof t.replace!="boolean"&&e.push("Navigation replace option must be a boolean"),{valid:e.length===0,errors:e}}function ge(t){const e=[];if(t.url===void 0||t.url===null)e.push("Redirect URL is required");else if(typeof t.url!="string")e.push("Redirect URL must be a string");else if(t.url.trim()==="")e.push("Redirect URL cannot be empty");else try{new URL(t.url)}catch{e.push(`Invalid redirect URL: "${t.url}"`)}return{valid:e.length===0,errors:e}}function me(t){const e=[];return t.title?typeof t.title!="string"&&e.push("Nav action title must be a string"):e.push("Nav action title is required"),t.value?typeof t.value!="string"&&e.push("Nav action value must be a string"):e.push("Nav action value is required"),t.subTitle!==void 0&&t.subTitle!==null&&typeof t.subTitle!="string"&&e.push("Nav action subTitle must be a string"),t.icon!==void 0&&t.icon!==null&&typeof t.icon!="string"&&e.push("Nav action icon must be a string"),t.disabled!==void 0&&t.disabled!==null&&typeof t.disabled!="boolean"&&e.push("Nav action disabled must be a boolean"),t.extendedActions!==void 0&&t.extendedActions!==null&&(Array.isArray(t.extendedActions)?t.extendedActions.forEach((r,i)=>{if(typeof r!="object"||r===null){e.push(`Extended action at index ${i} must be an object`);return}const n=r;(!n.title||typeof n.title!="string")&&e.push(`Extended action at index ${i} is missing required "title" property`),(!n.value||typeof n.value!="string")&&e.push(`Extended action at index ${i} is missing required "value" property`),n.subTitle!==void 0&&typeof n.subTitle!="string"&&e.push(`Extended action at index ${i} subTitle must be a string`),n.icon!==void 0&&typeof n.icon!="string"&&e.push(`Extended action at index ${i} icon must be a string`),n.disabled!==void 0&&typeof n.disabled!="boolean"&&e.push(`Extended action at index ${i} disabled must be a boolean`)}):e.push("Nav action extendedActions must be an array")),{valid:e.length===0,errors:e}}const j=["danger","warning","info"];function pe(t){const e=[];return t.title===void 0||t.title===null?e.push("Confirm dialog title is required"):typeof t.title!="string"?e.push("Confirm dialog title must be a string"):t.title.trim()===""&&e.push("Confirm dialog title cannot be empty"),t.message===void 0||t.message===null?e.push("Confirm dialog message is required"):typeof t.message!="string"?e.push("Confirm dialog message must be a string"):t.message.trim()===""&&e.push("Confirm dialog message cannot be empty"),t.confirmText!==void 0&&t.confirmText!==null&&typeof t.confirmText!="string"&&e.push("Confirm dialog confirmText must be a string"),t.cancelText!==void 0&&t.cancelText!==null&&typeof t.cancelText!="string"&&e.push("Confirm dialog cancelText must be a string"),t.variant!==void 0&&t.variant!==null&&(typeof t.variant!="string"||!j.includes(t.variant))&&e.push(`Invalid confirm variant "${t.variant}". Expected: ${j.join(" | ")}`),{valid:e.length===0,errors:e}}function g(t,e){a.error(`Validation failed for ${t}:
1
+ System.register("SallaEmbeddedSDK",[],(function(R,Pe){"use strict";return{execute:(function(){R({getEmbeddedApp:z,resetEmbeddedApp:Ue});const u="embedded::",O={INIT:`${u}iframe.ready`,READY:`${u}ready`,DESTROY:`${u}destroy`},P={PROVIDE:`${u}context.provide`,THEME_CHANGE:`${u}theme.change`},g={LOADING:`${u}ui.loading`,BREADCRUMBS:`${u}ui.breadcrumbs`,TOAST:`${u}ui.toast`,CONFIRM:`${u}ui.confirm`,CONFIRM_RESPONSE:`${u}ui.confirm.response`},te={},j={REFRESH:`${u}auth.refresh`},T={NAVIGATE:`${u}page.navigate`,REDIRECT:`${u}page.redirect`,SET_TITLE:`${u}page.setTitle`},h={SET_ACTION:`${u}nav.setAction`,CLEAR_ACTION:`${u}nav.clearAction`,ACTION_CLICK:`${u}nav.actionClick`,ADD_ITEM:`${u}nav.addItem`,ADD_ITEM_RESPONSE:`${u}nav.addItem.response`,UPDATE_ITEM:`${u}nav.updateItem`,REMOVE_ITEM:`${u}nav.removeItem`,ITEM_CLICK:`${u}nav.itemClick`},y={CREATE:`${u}checkout.create`,RESPONSE:`${u}checkout.response`,GET_ADDONS:`${u}checkout.getAddons`,GET_ADDONS_RESPONSE:`${u}checkout.getAddons.response`,RESET_CACHE:`${u}checkout.resetCache`},N=te.version||"",re=1e4,ie=["localhost","merchants.workers.dev","s.salla.sa",".salla.group",".salla.sa"],ne=new Set(["ar","he","fa","ur","ps","sd","yi"]);function se(t){const e=(t??"ar").toLowerCase().split(/[-_]/)[0];return ne.has(e)?"rtl":"ltr"}let $={showVersion:!0,debug:!1};function ae(t){$={...$,...t}}function F(t){return`%c${t}`}function H(t,e="#fff"){return`background-color: ${t}; color: ${e}; padding: 2px 6px; border-radius: 3px; font-weight: 500; font-size: 11px;`}function I(t,...e){if(t==="debug"&&!$.debug)return;const r=[],i=[];r.push(F("EmbeddedSDK")),i.push(H("#10b981","#fff")),$.showVersion&&(r.push(F(`v${N}`)),i.push(H("#6b7280","#fff")));const n=r.join("").trim();(console[t]||console.log)(n,...i,...e)}const o={log:(...t)=>{I("log",...t)},warn:(...t)=>{I("warn",...t)},error:(...t)=>{I("error",...t)},info:(...t)=>{I("info",...t)},debug:(...t)=>{I("debug",...t)}};function oe(t){try{const r=new URL(t).hostname;return ie.some(i=>i.startsWith(".")?r.endsWith(i)||r===i.slice(1):r===i||r.startsWith(`${i}:`))}catch{return!1}}function ue(){return typeof window>"u"||window.parent===window?null:window.parent}function c(t,e,r="*",i,n){const s=ue();if(!s){o.warn("Not running in an iframe, cannot post to host");return}const a={event:t,payload:e||{},timestamp:Date.now(),source:"embedded-app",...i&&{requestId:i},metadata:{version:N}};s.postMessage(a,r)}const v=new Map;let C=!1;function K(t){if(process.env.NODE_ENV==="production"&&!oe(t.origin))return;const e=t.data;if(!e||typeof e.event!="string"||!e.payload||typeof e.timestamp!="number"||!e.source){o.warn("Invalid message structure received:",e);return}const r=v.get(e.event);r&&r.forEach(n=>{try{n(e)}catch(s){o.error("Error in message handler:",s)}});const i=v.get("*");i&&i.forEach(n=>{try{n(e)}catch(s){o.error("Error in wildcard handler:",s)}})}function de(){C||typeof window>"u"||(window.addEventListener("message",K),C=!0)}function b(t,e){de(),v.has(t)||v.set(t,new Set);const r=v.get(t);return r.add(e),()=>{r.delete(e),r.size===0&&v.delete(t)}}function ce(t,e=re){return new Promise((r,i)=>{const n=setTimeout(()=>{s(),i(new Error(`[EmbeddedSDK] Timeout waiting for "${t}" message`))},e),s=b(t,a=>{clearTimeout(n),s(),r(a)})})}function le(){v.clear(),C&&typeof window<"u"&&(window.removeEventListener("message",K),C=!1)}function fe(){return typeof window>"u"?!1:window.parent!==window}function he(t,e,r){const i={event:t,payload:e,timestamp:Date.now(),source:"merchant-dashboard",...r,metadata:{version:N,synthetic:!0}};v.get(t)?.forEach(s=>{try{s(i)}catch(a){o.error("Error in message handler:",a)}})}const E=new Map,me=3e4;function G(){const t=Date.now(),e=Math.random().toString(36).slice(2,9);return`req_${t}_${e}`}function L(t,e={},r=me){const i=G();return new Promise((n,s)=>{const a=setTimeout(()=>{E.get(i)&&(E.delete(i),s(new Error(`[EmbeddedSDK] Request "${t}" timed out after ${r}ms`)))},r);E.set(i,{resolve:n,reject:s,timeout:a,event:t}),c(t,e,"*",i)})}function _(t,e,r){const i=E.get(t);if(!i){o.warn(`Received response for unknown request: ${t}`);return}clearTimeout(i.timeout),E.delete(t),r?i.reject(new Error(r)):i.resolve(e)}function pe(t="SDK cleanup"){E.forEach((e,r)=>{clearTimeout(e.timeout),e.reject(new Error(`[EmbeddedSDK] Request ${r} cancelled: ${t}`))}),E.clear()}function w(){const t=new Set;return{subscribe(e){return t.add(e),()=>{t.delete(e)}},notify(...e){t.forEach(r=>{try{r(...e)}catch(i){o.error("Error in subscription callback:",i)}})},clear(){t.clear()},size(){return t.size}}}const ge="https://api.salla.dev";class A extends Error{constructor(e,r,i){super(e),this.status=r,this.response=i,this.name="ApiError"}}async function ve(t,e={}){const{method:r="GET",headers:i={},body:n,timeout:s=3e4}=e,a=`${ge}${t}`,l=new AbortController,f=setTimeout(()=>{l.abort()},s);try{const d=await fetch(a,{method:r,headers:{"Content-Type":"application/json",...i},body:n?JSON.stringify(n):void 0,signal:l.signal});clearTimeout(f);let m;if(d.headers.get("content-type")?.includes("application/json")?m=await d.json():m=await d.text(),!d.ok)throw new A(`API request failed: ${d.statusText}`,d.status,m);return m}catch(d){throw clearTimeout(f),d instanceof A?d:d instanceof Error?d.name==="AbortError"?new A(`Request timeout after ${s}ms`):new A(`Request failed: ${d.message}`):new A("Unknown error occurred")}}function q(t){return{isVerified:!1,isError:!0,error:t,data:null}}async function be(t){const{token:e,appId:r,refreshOnError:i=!0}=t;if(!e){const n="Token is required. Provide it as a parameter or in URL as ?token=XXX";return o.error("Error in introspect:",n),q(n)}if(!r){const n="App ID is required. Provide it as a parameter or in URL as ?app_id=XXX";return o.error("Error in introspect:",n),q(n)}try{const n=await ve("/exchange-authority/v1/introspect",{method:"POST",headers:{"S-Source":r,"Content-Type":"application/json"},body:{env:"prod",token:e,iss:"merchant-dashboard",subject:"embedded-page"}}),s=n.success;return{isVerified:s,isError:!s,error:s?void 0:"API request failed",data:s?n.data:null}}catch(n){i&&(z().ui.toast.error(n?.toString()??"Introspect error"),c(j.REFRESH,{})),o.error("Error in introspect:",n);const s=n instanceof Error?n.message:n;return q(s)}}function ye(t){return{getToken(){return new URLSearchParams(window.location.search).get("token")},getAppId(){return new URLSearchParams(window.location.search).get("app_id")},refresh(){c(j.REFRESH,{})},async introspect(e={}){const r=e.token??this.getToken()??"",i=e.appId??this.getAppId()??"";return be({token:r,appId:i,refreshOnError:e.refreshOnError})}}}const B=["success","error","warning","info"];function Ee(t){const e=[];return t.type===void 0||t.type===null?e.push("Toast type is required"):(typeof t.type!="string"||!B.includes(t.type))&&e.push(`Invalid toast type "${t.type}". Expected: ${B.join(" | ")}`),t.message===void 0||t.message===null?e.push("Toast message is required"):typeof t.message!="string"?e.push("Toast message must be a string"):t.message.trim()===""&&e.push("Toast message cannot be empty"),t.duration!==void 0&&t.duration!==null&&(typeof t.duration!="number"?e.push("Toast duration must be a number"):t.duration<0&&e.push("Toast duration cannot be negative")),{valid:e.length===0,errors:e}}function X(t,e){const r=[];return typeof t!="object"||t===null?(r.push(`${e} must be an object`),r):((typeof t.type!="string"||t.type.trim()==="")&&r.push(`${e} must have a valid type`),(typeof t.slug!="string"||t.slug.trim()==="")&&r.push(`${e} must have a valid slug`),t.quantity!==void 0&&(typeof t.quantity!="number"||t.quantity<1)&&r.push(`${e} must have a quantity >= 1`),r)}function Te(t){const e=[];if(typeof t!="object"||t===null)return e.push("Checkout options must be an object"),{valid:!1,errors:e};const r="item"in t,i="items"in t;if(!r&&!i)return e.push("Checkout requires either 'item' or 'items'"),{valid:!1,errors:e};if(r){const n=X(t.item,"Item");return e.push(...n),{valid:e.length===0,errors:e}}return Array.isArray(t.items)?t.items.length===0?(e.push("At least one item is required"),{valid:!1,errors:e}):(t.items.forEach((n,s)=>{const a=X(n,`Item at index ${s}`);e.push(...a)}),{valid:e.length===0,errors:e}):(e.push("Checkout items must be an array"),{valid:!1,errors:e})}function Se(t){const e=[];return t.path===void 0||t.path===null?e.push("Navigation path is required"):typeof t.path!="string"?e.push("Navigation path must be a string"):t.path.trim()===""&&e.push("Navigation path cannot be empty"),t.replace!==void 0&&typeof t.replace!="boolean"&&e.push("Navigation replace option must be a boolean"),{valid:e.length===0,errors:e}}function Ie(t){const e=[];if(t.url===void 0||t.url===null)e.push("Redirect URL is required");else if(typeof t.url!="string")e.push("Redirect URL must be a string");else if(t.url.trim()==="")e.push("Redirect URL cannot be empty");else try{new URL(t.url)}catch{e.push(`Invalid redirect URL: "${t.url}"`)}return{valid:e.length===0,errors:e}}function we(t){const e=[];return t.title?typeof t.title!="string"&&e.push("Nav action title must be a string"):e.push("Nav action title is required"),t.value?typeof t.value!="string"&&e.push("Nav action value must be a string"):e.push("Nav action value is required"),t.subTitle!==void 0&&t.subTitle!==null&&typeof t.subTitle!="string"&&e.push("Nav action subTitle must be a string"),t.icon!==void 0&&t.icon!==null&&typeof t.icon!="string"&&e.push("Nav action icon must be a string"),t.disabled!==void 0&&t.disabled!==null&&typeof t.disabled!="boolean"&&e.push("Nav action disabled must be a boolean"),t.extendedActions!==void 0&&t.extendedActions!==null&&(Array.isArray(t.extendedActions)?t.extendedActions.forEach((r,i)=>{if(typeof r!="object"||r===null){e.push(`Extended action at index ${i} must be an object`);return}const n=r;(!n.title||typeof n.title!="string")&&e.push(`Extended action at index ${i} is missing required "title" property`),(!n.value||typeof n.value!="string")&&e.push(`Extended action at index ${i} is missing required "value" property`),n.subTitle!==void 0&&typeof n.subTitle!="string"&&e.push(`Extended action at index ${i} subTitle must be a string`),n.icon!==void 0&&typeof n.icon!="string"&&e.push(`Extended action at index ${i} icon must be a string`),n.disabled!==void 0&&typeof n.disabled!="boolean"&&e.push(`Extended action at index ${i} disabled must be a boolean`)}):e.push("Nav action extendedActions must be an array")),{valid:e.length===0,errors:e}}const D=50;function M(t,e){return t?`${t}.${e}`:e}function Ae(t,e){const r=[];["title","value","url"].forEach(s=>{(typeof t[s]!="string"||!String(t[s]).trim())&&r.push(`Sub-nav addItem "${M(e,s)}" must be non-empty string`)});const i=M(e,"disabled"),n=M(e,"active");return t.disabled!==void 0&&typeof t.disabled!="boolean"&&r.push(`Sub-nav addItem "${i}" must be boolean`),t.active!==void 0&&typeof t.active!="boolean"&&r.push(`Sub-nav addItem "${n}" must be boolean`),r}function k(t,e,r){if(typeof t!="object"||t===null)return[`Sub-nav addItem "${e||"item"}" must be an object`];const i=t,n=Ae(i,e),s=M(e,"children");return i.children===void 0?n:r?Array.isArray(i.children)?i.children.length>D?(n.push(`Sub-nav addItem "${s}" must have at most ${D} items`),n):(i.children.forEach((a,l)=>{const f=e?`${e}.children[${l}]`:`children[${l}]`;n.push(...k(a,f,!1))}),n):(n.push(`Sub-nav addItem "${s}" must be an array`),n):(Array.isArray(i.children)&&i.children.length===0||n.push(`Sub-nav addItem "${s}" is not supported on submenu rows (only one dropdown level)`),n)}function W(t,e,r,i){if(typeof t!="object"||t===null)return i;const n=t;return typeof n.value=="string"&&n.value.trim()&&i.push(n.value.trim()),!r||!Array.isArray(n.children)||n.children.forEach((s,a)=>{const l=e?`${e}.children[${a}]`:`children[${a}]`;W(s,l,!1,i)}),i}function Re(t){const e=W(t,"",!0,[]),r=new Set,i=[];for(const n of e)r.has(n)&&i.push(n),r.add(n);return i.length===0?[]:[`Sub-nav addItem "value" must be globally unique within the item tree (duplicate: ${[...new Set(i)].join(", ")})`]}function Ne(t){if(typeof t!="object"||t===null)return{valid:!1,errors:["Nav addItem expects an object item"]};const e=[...k(t,"",!0),...Re(t)];return{valid:e.length===0,errors:e}}function $e(t){const e=[];if(typeof t!="object"||t===null)return e.push("Nav updateItem expects an object item"),{valid:!1,errors:e};const r=t,i=typeof r.value=="string"&&String(r.value).trim().length>0,n=typeof r.id=="string"&&String(r.id).trim().length>0,s=i?String(r.value).trim():"",a=n?String(r.id).trim():"";if(!i&&!n)return e.push('Sub-nav updateItem requires non-empty string "value"'),{valid:!1,errors:e};if(i&&n&&s!==a)return e.push('Sub-nav updateItem must not specify different "id" and "value"; "value" is the immutable row key and cannot be renamed via patch'),{valid:!1,errors:e};const l=s||a;let f=0;if(r.title!==void 0&&f++,r.url!==void 0&&f++,r.disabled!==void 0&&f++,r.active!==void 0&&f++,r.children!==void 0&&f++,f===0)return e.push("Sub-nav updateItem must include at least one of title, url, disabled, active, children"),{valid:!1,errors:e};if(["title","url"].forEach(d=>{r[d]!==void 0&&(typeof r[d]!="string"||!r[d].trim())&&e.push(`Sub-nav updateItem "${d}" must be non-empty`)}),r.disabled!==void 0&&typeof r.disabled!="boolean"&&e.push('Sub-nav updateItem "disabled" must be boolean'),r.active!==void 0&&typeof r.active!="boolean"&&e.push('Sub-nav updateItem "active" must be boolean'),r.children!==void 0)if(!Array.isArray(r.children))e.push('Sub-nav updateItem "children" must be an array');else if(r.children.length>D)e.push(`Sub-nav updateItem "children" must have at most ${D} items`);else{const d=new Set;r.children.forEach((m,ee)=>{const V=`children[${ee}]`;if(e.push(...k(m,V,!1)),typeof m=="object"&&m!==null){const x=m.value;if(typeof x=="string"&&x.trim()){const U=x.trim();U===l&&e.push(`Sub-nav updateItem "${V}.value" must not equal the parent row identifier`),d.has(U)&&e.push(`Sub-nav updateItem "${V}.value" must be unique within children`),d.add(U)}}})}return{valid:e.length===0,errors:e}}function Ce(t){const e=[];return(typeof t!="string"||!t.trim())&&e.push("Nav removeItem value must be non-empty string"),{valid:e.length===0,errors:e}}const Y=["danger","warning","info"];function _e(t){const e=[];return t.title===void 0||t.title===null?e.push("Confirm dialog title is required"):typeof t.title!="string"?e.push("Confirm dialog title must be a string"):t.title.trim()===""&&e.push("Confirm dialog title cannot be empty"),t.message===void 0||t.message===null?e.push("Confirm dialog message is required"):typeof t.message!="string"?e.push("Confirm dialog message must be a string"):t.message.trim()===""&&e.push("Confirm dialog message cannot be empty"),t.confirmText!==void 0&&t.confirmText!==null&&typeof t.confirmText!="string"&&e.push("Confirm dialog confirmText must be a string"),t.cancelText!==void 0&&t.cancelText!==null&&typeof t.cancelText!="string"&&e.push("Confirm dialog cancelText must be a string"),t.variant!==void 0&&t.variant!==null&&(typeof t.variant!="string"||!Y.includes(t.variant))&&e.push(`Invalid confirm variant "${t.variant}". Expected: ${Y.join(" | ")}`),{valid:e.length===0,errors:e}}function p(t,e){o.error(`Validation failed for ${t}:
2
2
  `+e.map(r=>` • ${r}`).join(`
3
- `))}function Ee(){return{resize:i=>{},autoResize:()=>{},stopAutoResize:()=>{}}}function ye(){const{resize:t,autoResize:e,stopAutoResize:r}=Ee();return{navigate(i,n){const s=he({path:i,...n});if(!s.valid){g(m.NAVIGATE,s.errors);return}u(m.NAVIGATE,{path:i,state:n==null?void 0:n.state,replace:n==null?void 0:n.replace})},redirect(i){const n=ge({url:i});if(!n.valid){g(m.REDIRECT,n.errors);return}u(m.REDIRECT,{url:i})},navTo(i,n){if(i.startsWith("http://")||i.startsWith("https://")){this.redirect(i);return}this.navigate(i,n)},setTitle(i){if(typeof i!="string"||!i.trim()){g(m.SET_TITLE,["Title must be a non-empty string"]);return}u(m.SET_TITLE,{title:i})},resize:t,autoResize:e,stopAutoResize:r}}function be(){const t=I();return E(w.ACTION_CLICK,e=>{t.notify(e.payload.value)}),{setAction(e){var i;const r=me(e);if(!r.valid){g(w.SET_ACTION,r.errors);return}u(w.SET_ACTION,{title:e.title,value:e.value,subTitle:e.subTitle,icon:e.icon,disabled:e.disabled,extendedActions:(i=e.extendedActions)==null?void 0:i.map(n=>({title:n.title,value:n.value,subTitle:n.subTitle,icon:n.icon,disabled:n.disabled}))})},clearAction(){u(w.CLEAR_ACTION,{})},onActionClick(e){return t.subscribe(e)}}}function Te(){return{show(){u(f.LOADING,{action:"show"})},hide(){u(f.LOADING,{action:"hide"})}}}function ve(){const t=e=>{const r=le(e);if(!r.valid){g(f.TOAST,r.errors);return}u(f.TOAST,{type:e.type,message:e.message,duration:e.duration})};return{show:t,success(e,r){t({type:"success",message:e,duration:r})},error(e,r){t({type:"error",message:e,duration:r})},warning(e,r){t({type:"warning",message:e,duration:r})},info(e,r){t({type:"info",message:e,duration:r})}}}function we(){return async t=>{const e=pe(t);return e.valid?P(f.CONFIRM,{title:t.title,message:t.message,confirmText:t.confirmText??"Confirm",cancelText:t.cancelText??"Cancel",variant:t.variant??"info"}):(g(f.CONFIRM,e.errors),Promise.reject(new Error(e.errors.join(", "))))}}function Se(){return{loading:Te(),toast:ve(),confirm:we()}}function Ae(){const t=I(),e=[];return e.push(E(p.RESPONSE,r=>{t.notify({success:r.payload.success,order_id:r.payload.order_id,status:r.payload.status,error:r.payload.error,context:r.payload.context})})),e.push(E(p.GET_ADDONS_RESPONSE,r=>{r.requestId&&U(r.requestId,{success:r.payload.success,addons:r.payload.addons,error:r.payload.error})})),{create(r,i){const n=Array.isArray(r)?r:[r],s=fe({items:n});if(!s.valid)throw g(p.CREATE,s.errors),new Error(s.errors[0]);u(p.CREATE,{items:n.map(c=>({type:c.type,slug:c.slug,quantity:c.quantity??1})),...(i==null?void 0:i.context)!==void 0&&{context:i.context}},"*",M())},onResult(r){return t.subscribe(r)},async getAddons(){try{return await P(p.GET_ADDONS,{},3e4)}catch(r){return{success:!1,error:{code:"REQUEST_FAILED",message:r instanceof Error?r.message:"Unknown error"}}}},destroy(){e.forEach(r=>r()),e.length=0,t.clear()}}}const H={theme:"light",width:0,locale:"ar",currency:"SAR"};class G{constructor(){this.initialized=!1,this.initializing=!1,this.debugMode=!1,this.appReady=!1,this.layout={...H},this.postInitHooks=[],this.themeSubscription=I(),this.initSubscription=I(),this.auth=de(),this.page=ye(),this.nav=be(),this.ui=Se(),this.checkout=Ae(),this.registerPostInitHook(e=>{const r=e.payload.pendingCheckoutResult;r&&(a.debug("Dispatching pending checkout result:",r),queueMicrotask(()=>{ne(p.RESPONSE,{success:r.success,status:r.status,error:r.error,context:r.context})}))}),this.setupListeners()}registerPostInitHook(e){this.postInitHooks.push(e)}setupListeners(){E(x.THEME_CHANGE,e=>{this.layout.theme=e.payload.theme,a.debug("Theme changed:",e.payload.theme),this.themeSubscription.notify(e.payload.theme)}),E(f.CONFIRM_RESPONSE,e=>{a.debug("Received confirm response:",e),e.requestId&&U(e.requestId,{confirmed:e.payload.confirmed})})}getState(){return{ready:this.initialized,initializing:this.initializing,layout:{...this.layout}}}isReady(){return this.initialized}onThemeChange(e){return this.themeSubscription.subscribe(e)}onInit(e){if(this.initialized)try{e(this.getState())}catch(r){a.error("Error in init callback:",r)}return this.initSubscription.subscribe(e)}ready(){if(this.appReady){a.debug("App already signaled as ready");return}if(!this.initialized){a.warn("Cannot signal ready before init() is called");return}this.appReady=!0,u(C.READY,{}),a.debug("Sent ready signal to host")}async init(e={}){if(this.initialized)return a.debug("Already initialized, returning current layout"),{layout:{...this.layout}};if(this.initializing)return a.warn("Initialization already in progress"),new Promise(r=>{const i=this.onInit(n=>{i(),r({layout:{...n.layout}})})});this.initializing=!0,this.debugMode=e.debug??!1,Q({debug:this.debugMode}),ie()||a.warn("Not running in an iframe. Some features may not work."),a.debug("Initializing SDK...");try{u(C.INIT,{height:document.documentElement.scrollHeight}),a.debug("Sent iframe.ready message, waiting for context...");const r=await te(x.PROVIDE);a.debug("Received context from host:",r);const{layout:i}=r.payload;return this.layout={theme:(i==null?void 0:i.theme)??"light",width:(i==null?void 0:i.width)??0,locale:(i==null?void 0:i.locale)??"ar",currency:(i==null?void 0:i.currency)??"SAR"},this.postInitHooks.forEach(n=>{try{n(r)}catch(s){a.error("Error in post-init hook:",s)}}),this.initialized=!0,this.initializing=!1,a.debug("Initialization complete. Layout:",this.layout),this.initSubscription.notify(this.getState()),{layout:{...this.layout}}}catch(r){throw this.initializing=!1,r}}destroy(){a.debug("Destroying SDK instance"),this.initialized&&(u(C.DESTROY,{}),a.debug("Sent destroy event to host")),this.checkout.destroy(),ae("SDK destroyed"),re(),this.themeSubscription.clear(),this.initSubscription.clear(),this.postInitHooks=[],this.initialized=!1,this.initializing=!1,this.appReady=!1,this.layout={...H}}}v("EmbeddedApp",G);let y=null;function _(){return y||(y=new G),y}function Re(){y&&(y.destroy(),y=null)}const K=v("embedded",_()),Ne=v("version",S);typeof window<"u"&&(window.salla=window.salla||window.Salla||{},window.Salla=window.salla,window.salla.embedded||(window.salla.embedded=K),window.Salla.embedded||(window.Salla.embedded=K))}}});
3
+ `))}function De(){return{resize:i=>{},autoResize:()=>{},stopAutoResize:()=>{}}}function Me(){const{resize:t,autoResize:e,stopAutoResize:r}=De();return{navigate(i,n){const s=Se({path:i,...n});if(!s.valid){p(T.NAVIGATE,s.errors);return}c(T.NAVIGATE,{path:i,state:n?.state,replace:n?.replace})},redirect(i){const n=Ie({url:i});if(!n.valid){p(T.REDIRECT,n.errors);return}c(T.REDIRECT,{url:i})},navTo(i,n){if(i.startsWith("http://")||i.startsWith("https://")){this.redirect(i);return}this.navigate(i,n)},setTitle(i){if(typeof i!="string"||!i.trim()){p(T.SET_TITLE,["Title must be a non-empty string"]);return}c(T.SET_TITLE,{title:i})},resize:t,autoResize:e,stopAutoResize:r}}function Oe(){const t=w(),e=w(),r=[];return r.push(b(h.ACTION_CLICK,i=>{t.notify(i.payload.value)})),r.push(b(h.ADD_ITEM_RESPONSE,i=>{if(!i.requestId)return;const n=i.payload;if(typeof n.error=="string"&&n.error.trim()){const a=n.error.trim();o.warn(`embedded::nav.addItem failed: ${a}`),_(i.requestId,{},a);return}const s=n.item;if(s&&typeof s.value=="string"&&s.value.trim()){const a=s.value.trim(),l={value:a,id:a};_(i.requestId,l)}})),r.push(b(h.ITEM_CLICK,i=>{const n=i.payload,s=typeof n.value=="string"&&n.value.trim()?n.value.trim():typeof n.id=="string"&&n.id.trim()?n.id.trim():"";if(!s){e.notify(n);return}e.notify({...n,value:s,id:s})})),{setAction(i){const n=we(i);if(!n.valid){p(h.SET_ACTION,n.errors);return}c(h.SET_ACTION,{title:i.title,value:i.value,subTitle:i.subTitle,icon:i.icon,disabled:i.disabled,extendedActions:i.extendedActions?.map(s=>({title:s.title,value:s.value,subTitle:s.subTitle,icon:s.icon,disabled:s.disabled}))})},clearAction(){c(h.CLEAR_ACTION,{})},onActionClick(i){return t.subscribe(i)},addNavItem(i){const n=Ne(i);return n.valid?L(h.ADD_ITEM,{item:i},2e3):(p(h.ADD_ITEM,n.errors),Promise.reject(new Error(n.errors[0])))},updateNavItem(i){const n=$e(i);if(!n.valid){p(h.UPDATE_ITEM,n.errors);return}const s=i,a=typeof s.value=="string"?s.value.trim():"",l=typeof s.id=="string"?s.id.trim():"",f=a||l,{id:d,...m}=s;c(h.UPDATE_ITEM,{item:{...m,value:f}})},removeNavItem(i){const n=Ce(i);if(!n.valid){p(h.REMOVE_ITEM,n.errors);return}c(h.REMOVE_ITEM,{value:i})},onNavItemClick(i){return e.subscribe(i)},destroy(){r.forEach(i=>i()),r.length=0,t.clear(),e.clear()}}}function Le(){return{show(){c(g.LOADING,{action:"show"})},hide(){c(g.LOADING,{action:"hide"})}}}function qe(){return{hide(){c(g.BREADCRUMBS,{action:"hide"})},show(){c(g.BREADCRUMBS,{action:"show"})}}}function ke(){const t=e=>{const r=Ee(e);if(!r.valid){p(g.TOAST,r.errors);return}c(g.TOAST,{type:e.type,message:e.message,duration:e.duration})};return{show:t,success(e,r){t({type:"success",message:e,duration:r})},error(e,r){t({type:"error",message:e,duration:r})},warning(e,r){t({type:"warning",message:e,duration:r})},info(e,r){t({type:"info",message:e,duration:r})}}}function ze(){return async t=>{const e=_e(t);return e.valid?L(g.CONFIRM,{title:t.title,message:t.message,confirmText:t.confirmText??"Confirm",cancelText:t.cancelText??"Cancel",variant:t.variant??"info"}):(p(g.CONFIRM,e.errors),Promise.reject(new Error(e.errors.join(", "))))}}function Ve(){return{loading:Le(),breadcrumbs:qe(),toast:ke(),confirm:ze()}}function xe(){const t=w(),e=[];return e.push(b(y.RESPONSE,r=>{t.notify({success:r.payload.success,order_id:r.payload.order_id,status:r.payload.status,error:r.payload.error,context:r.payload.context})})),e.push(b(y.GET_ADDONS_RESPONSE,r=>{r.requestId&&_(r.requestId,{success:r.payload.success,addons:r.payload.addons,error:r.payload.error})})),{create(r,i){const n=Array.isArray(r)?r:[r],s=Te({items:n});if(!s.valid)throw p(y.CREATE,s.errors),new Error(s.errors[0]);c(y.CREATE,{items:n.map(a=>({type:a.type,slug:a.slug,quantity:a.quantity??1})),...i?.context!==void 0&&{context:i.context}},"*",G())},onResult(r){return t.subscribe(r)},async getAddons(){try{return await L(y.GET_ADDONS,{},3e4)}catch(r){return{success:!1,error:{code:"REQUEST_FAILED",message:r instanceof Error?r.message:"Unknown error"}}}},resetCache(){c(y.RESET_CACHE,{},"*")},destroy(){e.forEach(r=>r()),e.length=0,t.clear()}}}const Q={theme:"light",dir:"rtl",width:0,locale:"ar",currency:"SAR"};class J{constructor(){this.initialized=!1,this.initializing=!1,this.debugMode=!1,this.appReady=!1,this.layout={...Q},this.postInitHooks=[],this.themeSubscription=w(),this.initSubscription=w(),this.auth=ye(),this.page=Me(),this.nav=Oe(),this.ui=Ve(),this.checkout=xe(),this.registerPostInitHook(e=>{const r=e.payload.pendingCheckoutResult;r&&(o.debug("Dispatching pending checkout result:",r),queueMicrotask(()=>{he(y.RESPONSE,{success:r.success,status:r.status,error:r.error,context:r.context})}))}),this.setupListeners()}registerPostInitHook(e){this.postInitHooks.push(e)}setupListeners(){b(P.THEME_CHANGE,e=>{this.layout.theme=e.payload.theme,o.debug("Theme changed:",e.payload.theme),this.themeSubscription.notify(e.payload.theme)}),b(g.CONFIRM_RESPONSE,e=>{o.debug("Received confirm response:",e),e.requestId&&_(e.requestId,{confirmed:e.payload.confirmed})})}getState(){return{ready:this.initialized,initializing:this.initializing,layout:{...this.layout}}}isReady(){return this.initialized}onThemeChange(e){return this.themeSubscription.subscribe(e)}onInit(e){if(this.initialized)try{e(this.getState())}catch(r){o.error("Error in init callback:",r)}return this.initSubscription.subscribe(e)}ready(){if(this.appReady){o.debug("App already signaled as ready");return}if(!this.initialized){o.warn("Cannot signal ready before init() is called");return}this.appReady=!0,c(O.READY,{}),o.debug("Sent ready signal to host")}async init(e={}){if(this.initialized)return o.debug("Already initialized, returning current layout"),{layout:{...this.layout}};if(this.initializing)return o.warn("Initialization already in progress"),new Promise(r=>{const i=this.onInit(n=>{i(),r({layout:{...n.layout}})})});this.initializing=!0,this.debugMode=e.debug??!1,ae({debug:this.debugMode}),fe()||o.warn("Not running in an iframe. Some features may not work."),o.debug("Initializing SDK...");try{c(O.INIT,{height:document.documentElement.scrollHeight}),o.debug("Sent iframe.ready message, waiting for context...");const r=await ce(P.PROVIDE);o.debug("Received context from host:",r);const{layout:i}=r.payload;return this.layout={theme:i?.theme??"light",dir:i?.dir??se(i?.locale),width:i?.width??0,locale:i?.locale??"ar",currency:i?.currency??"SAR"},this.postInitHooks.forEach(n=>{try{n(r)}catch(s){o.error("Error in post-init hook:",s)}}),this.initialized=!0,this.initializing=!1,o.debug("Initialization complete. Layout:",this.layout),this.initSubscription.notify(this.getState()),{layout:{...this.layout}}}catch(r){throw this.initializing=!1,r}}destroy(){o.debug("Destroying SDK instance"),this.initialized&&(c(O.DESTROY,{}),o.debug("Sent destroy event to host")),this.checkout.destroy(),this.nav.destroy(),pe("SDK destroyed"),le(),this.themeSubscription.clear(),this.initSubscription.clear(),this.postInitHooks=[],this.initialized=!1,this.initializing=!1,this.appReady=!1,this.layout={...Q}}}R("EmbeddedApp",J);let S=null;function z(){return S||(S=new J),S}function Ue(){S&&(S.destroy(),S=null)}const Z=R("embedded",z()),je=R("version",N);typeof window<"u"&&(window.salla=window.salla||window.Salla||{},window.Salla=window.salla,window.salla.embedded||(window.salla.embedded=Z),window.Salla.embedded||(window.Salla.embedded=Z))})}}));
4
4
  //# sourceMappingURL=index.js.map