@commmerce/app-bridge 1.0.0-rc.4 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md CHANGED
@@ -1,17 +1,152 @@
1
- # Commmerce UI Licence — DRAFT, NOT YET IN FORCE
2
-
3
- > Draft for legal review. Do not publish packages until this is approved.
4
-
5
- Copyright (c) 2026 Outdo Inc. (Commmerce). All rights reserved.
6
-
7
- 1. **Grant.** You may install, use and include unmodified copies of the Commmerce UI packages
8
- (`@commmerce/tokens`, `@commmerce/ui`, `@commmerce/ui-react`, `@commmerce/app-bridge`) in
9
- software whose purpose is to run on, integrate with or extend a Commmerce platform, including
10
- apps listed in, or privately installed through, the Commmerce app marketplace.
11
- 2. **Restrictions.** You may not use the packages, or the Commmerce name, logo or visual identity
12
- they carry, to build a product that is not for use with a Commmerce platform, or one that
13
- presents itself as made or endorsed by Commmerce. You may not redistribute the packages on their
14
- own or as a competing design system.
15
- 3. **No warranty.** The packages are provided "as is", without warranty of any kind. Commmerce is
16
- not liable for any claim or damages arising from their use.
17
- 4. **Termination.** This licence ends automatically if you breach it.
1
+ # Commmerce UI Licence
2
+
3
+ Version 1.0 | Copyright © 2026 Outdo Inc. (Commmerce)
4
+
5
+ All rights not expressly granted under this licence are reserved.
6
+
7
+ ## 1. Definitions
8
+
9
+ "**Commmerce**" means Outdo Inc. and its affiliates.
10
+
11
+ "**Packages**" means the Commmerce UI software and assets distributed by Commmerce under this licence,
12
+ including the npm packages `@commmerce/tokens`, `@commmerce/icons`, `@commmerce/ui`, `@commmerce/ui-react`
13
+ and `@commmerce/app-bridge`, the Flutter package `commmerce_ui`, and the corresponding files hosted at
14
+ commmerce.com/blog/commmerceui/.
15
+
16
+ "**Commmerce Platform**" means the products, services, infrastructure and applications operated or provided
17
+ by Commmerce.
18
+
19
+ "**Commmerce Software**" means software developed to run on, integrate with, extend or provide functionality
20
+ for a Commmerce Platform, including applications listed in or privately installed through the Commmerce app
21
+ marketplace, and internal business applications used in connection with a Commmerce Platform.
22
+
23
+ "**You**" means the individual or legal entity exercising rights under this licence, including its
24
+ authorised employees, contractors, consultants and agencies acting on its behalf solely for the
25
+ development, maintenance or operation of Commmerce Software.
26
+
27
+ ## 2. Licence Grant
28
+
29
+ Subject to your compliance with this licence, Commmerce grants you a worldwide, non-exclusive,
30
+ royalty-free, limited, non-transferable licence to:
31
+
32
+ (a) install, access and use the Packages;
33
+
34
+ (b) incorporate the Packages into Commmerce Software;
35
+
36
+ (c) modify and adapt the Packages solely to the extent reasonably necessary to develop, maintain, customise
37
+ and operate Commmerce Software;
38
+
39
+ (d) distribute the Packages as integrated components of Commmerce Software, in source, bundled, minified,
40
+ compiled or other executable forms; and
41
+
42
+ (e) permit merchants and end users to use Commmerce Software incorporating the Packages.
43
+
44
+ Normal software development and build processes, including bundling, minification, compilation,
45
+ tree-shaking and configuration through documented options, are permitted.
46
+
47
+ No ownership of the Packages or underlying intellectual property is transferred to you.
48
+
49
+ ## 3. Starter Applications and Code Samples
50
+
51
+ Starter applications, templates and code samples published by Commmerce may be copied, modified, adapted
52
+ and used as the basis for developing your own Commmerce Software.
53
+
54
+ You may incorporate such modifications into your applications and distribute those applications.
55
+
56
+ The Packages and any separately identified third-party components remain subject to their respective
57
+ licences. This section does not grant rights to Commmerce trademarks, logos or other separately protected
58
+ assets.
59
+
60
+ ## 4. Restrictions
61
+
62
+ You must not:
63
+
64
+ (a) use the Packages to develop, operate or distribute software that is not Commmerce Software;
65
+
66
+ (b) redistribute, sublicense, sell, publish or otherwise make the Packages, or modified versions of the
67
+ Packages, available independently or as part of a standalone design system, component library, UI
68
+ toolkit, framework or developer platform intended for use outside the Commmerce ecosystem;
69
+
70
+ (c) extract, repurpose or reuse the Packages or their components to create or distribute a competing
71
+ design system, component library or equivalent developer toolkit;
72
+
73
+ (d) use the Commmerce name, logo or other trademarks in a manner that suggests ownership, official
74
+ affiliation, sponsorship or endorsement, except where expressly authorised under Commmerce's brand or
75
+ developer guidelines; or
76
+
77
+ (e) remove, obscure or alter copyright notices, licence notices or attribution requirements included with
78
+ the Packages.
79
+
80
+ Nothing in this section prevents you from developing and distributing your own applications, business
81
+ logic, integrations, themes or other original software for the Commmerce Platform.
82
+
83
+ ## 5. Third-Party Components
84
+
85
+ Certain components, libraries, typefaces or other materials included with or used by the Packages may be
86
+ subject to third-party licences.
87
+
88
+ Those third-party licences govern the applicable components and prevail to the extent of any
89
+ inconsistency with this licence.
90
+
91
+ Applicable third-party notices and licence texts are provided in the relevant Packages or accompanying
92
+ documentation.
93
+
94
+ ## 6. Later Versions
95
+
96
+ Commmerce may publish new versions of the Packages under this licence or under different licence terms.
97
+
98
+ Each published version is governed by the licence accompanying that version. No change to a later version
99
+ retroactively changes the licence applicable to an earlier version already distributed.
100
+
101
+ ## 7. Intellectual Property and Trademarks
102
+
103
+ The Packages, including their original code, design tokens, component implementations, documentation and
104
+ associated intellectual property, remain the property of Commmerce or their respective rights holders.
105
+
106
+ This licence does not grant any ownership interest or general trademark licence.
107
+
108
+ You may make factual references to compatibility or integration with Commmerce, provided those references
109
+ are accurate and do not imply official endorsement, sponsorship or ownership.
110
+
111
+ ## 8. Disclaimer of Warranties
112
+
113
+ To the maximum extent permitted by applicable law, the Packages are provided "AS IS" and "AS AVAILABLE",
114
+ without warranties, representations or conditions of any kind, whether express, implied or statutory,
115
+ including warranties of merchantability, fitness for a particular purpose, title and non-infringement.
116
+
117
+ Commmerce does not warrant that the Packages will be uninterrupted, error-free, secure or compatible with
118
+ every third-party environment.
119
+
120
+ ## 9. Limitation of Liability
121
+
122
+ To the maximum extent permitted by applicable law, Commmerce and its affiliates, directors, officers,
123
+ employees and licensors shall not be liable for any indirect, incidental, special, exemplary or
124
+ consequential damages, or for loss of profits, revenue, business opportunities, goodwill, business
125
+ interruption or data arising out of or relating to the Packages or this licence.
126
+
127
+ Nothing in this licence excludes or limits liability to the extent that such exclusion or limitation is
128
+ prohibited by applicable law.
129
+
130
+ ## 10. Termination
131
+
132
+ This licence terminates automatically if you materially breach its terms and, where the breach is capable
133
+ of remedy, fail to remedy it within thirty (30) days after receiving written notice.
134
+
135
+ Commmerce may terminate the licence immediately where a breach is incapable of remedy or involves
136
+ unauthorised redistribution, infringement of intellectual property, or a material security risk.
137
+
138
+ Upon termination, you must cease using and distributing the Packages and remove them from systems under
139
+ your control, except to the extent retention is required by applicable law.
140
+
141
+ Where reasonably practicable and where termination does not arise from a security or intellectual property
142
+ violation, Commmerce may permit a limited transition period for existing merchant applications.
143
+
144
+ Termination does not affect rights or obligations accrued before termination.
145
+
146
+ Sections 4, 5, 7, 8, 9 and this section survive termination.
147
+
148
+ ## 11. Contact
149
+
150
+ Questions concerning this licence may be sent to: support@commmerce.com
151
+
152
+ End of Licence
package/README.md CHANGED
@@ -3,7 +3,6 @@
3
3
  Connects an app embedded in the Commmerce admin (in an iframe) to the admin around it: admin-level toasts and
4
4
  modals, the save bar, a loading bar, the resource picker, the admin's address, and session tokens for your backend.
5
5
 
6
- **Preview.** Protocol version 1. APIs can change between releases; read the release notes before upgrading.
7
6
  Docs: https://commmerce.com/blog/commmerceui/#apps--app-bridge
8
7
 
9
8
  ## In your app (inside the iframe)
@@ -1 +1 @@
1
- var H="commmerce-app-bridge",R=1,w=class extends Error{constructor(t,r){super(r),this.name="AppBridgeError",this.code=t}};function A(e){if(!e||typeof e!="object")return!1;let t=e;return t.protocol===H&&typeof t.version=="number"&&(t.kind==="request"||t.kind==="response"||t.kind==="event")}function C(e,t){if(!e||e==="*"||e==="null")throw new TypeError(`App Bridge: ${t} must be an exact origin such as https://app.example.com, not "${e}"`);if(String(e).includes("*"))throw new TypeError(`App Bridge: ${t} must be an exact origin such as https://app.example.com, not the pattern "${e}"`);let r=new URL(e).origin;if(r==="null")throw new TypeError(`App Bridge: ${t} "${e}" has no origin`);return r}var K=/^(?!-)[a-z0-9-]{1,63}(?<!-)$/,Z={"https:":"443","http:":"80"};function x(e){return typeof e=="string"&&e.includes("*")}function O(e,t="origin pattern"){let r=i=>new TypeError(`App Bridge: ${t} "${e}" is not a valid origin pattern: ${i}. Use an exact origin such as https://admin.example.com, or a pattern such as https://*.commmerce.com`),n=/^(https?):\/\/\*\.([^:/?#]*)(?::(\d{1,5}))?$/i.exec(String(e));if(!n)throw r("it must be https://*.domain or http://*.domain, with an optional :port and nothing else");let a=`${n[1].toLowerCase()}:`,s=n[2].toLowerCase(),l=s.split(".");if(s.length>253||!l.every(i=>K.test(i)))throw r('the part after "*." must be a domain name (letters, digits, hyphens and dots)');if(l.length<2&&s!=="localhost")throw r('the domain after "*." needs at least one dot, e.g. *.commmerce.com');if(/^(\d+|0x[0-9a-f]*)$/.test(l[l.length-1]))throw r("IP addresses cannot have a wildcard");let m="";if(n[3]!==void 0){let i=Number(n[3]);if(i<1||i>65535)throw r("the port must be 1 to 65535");m=String(i)===Z[a]?"":String(i)}return{scheme:a,domain:s,port:m,source:String(e)}}function z(e,t){let r=typeof e=="string"?O(e):e;if(typeof t!="string"||!t)return!1;let n;try{n=new URL(t)}catch{return!1}if(n.origin==="null"||n.origin!==t.toLowerCase()||n.protocol!==r.scheme||n.port!==r.port)return!1;let a=`.${r.domain}`;if(!n.hostname.endsWith(a))return!1;let s=n.hostname.slice(0,-a.length);return s.length>0&&s.split(".").every(l=>K.test(l))}function F(e,t){return x(e)?z(O(e,"allowed origin"),t):typeof t=="string"&&t===e}var L=new TextEncoder,W=new TextDecoder;function j(e){let t="";return e.forEach(r=>{t+=String.fromCharCode(r)}),btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function N(e){if(!/^[A-Za-z0-9_-]*$/.test(e))throw new v("malformed","Token is not base64url");let t=atob(e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-e.length%4)%4));return Uint8Array.from(t,r=>r.charCodeAt(0))}var _=(e,t)=>crypto.subtle.importKey("raw",L.encode(e),{name:"HMAC",hash:"SHA-256"},!1,[t]),v=class extends Error{constructor(t,r){super(r),this.name="SessionTokenError",this.code=t}};async function G(e,t){if(!t)throw new TypeError("signSessionToken: secret is required");let r=Math.floor(Date.now()/1e3),n={iat:r,nbf:r,exp:r+60,jti:crypto.randomUUID(),...e},a=j(L.encode(JSON.stringify({alg:"HS256",typ:"JWT"}))),s=j(L.encode(JSON.stringify(n))),l=await crypto.subtle.sign("HMAC",await _(t,"sign"),L.encode(`${a}.${s}`));return`${a}.${s}.${j(new Uint8Array(l))}`}function B(e){let t=String(e).split(".");if(t.length!==3)throw new v("malformed","Token must have three parts");try{return JSON.parse(W.decode(N(t[1])))}catch(r){throw r instanceof v?r:new v("malformed","Token claims are not JSON")}}async function Q(e,t,r){if(!t)throw new TypeError("verifySessionToken: secret is required");if(!r?.audience)throw new TypeError("verifySessionToken: options.audience (your API key) is required");r.issuer&&x(r.issuer)&&O(r.issuer,"verifySessionToken: options.issuer");let n=String(e).split(".");if(n.length!==3)throw new v("malformed","Token must have three parts");let a;try{a=JSON.parse(W.decode(N(n[0])))}catch{throw new v("malformed","Token header is not JSON")}if(a.alg!=="HS256")throw new v("algorithm",`Algorithm ${a.alg} is not allowed`);if(!await crypto.subtle.verify("HMAC",await _(t,"verify"),N(n[2]),L.encode(`${n[0]}.${n[1]}`)))throw new v("signature","Signature does not match");let l=B(e),m=r.now??Math.floor(Date.now()/1e3),i=r.clockTolerance??5;if(typeof l.exp!="number"||m-i>=l.exp)throw new v("expired","Token has expired");if(typeof l.nbf=="number"&&m+i<l.nbf)throw new v("not-yet-valid","Token is not valid yet");if(l.aud!==r.audience)throw new v("audience","Token is for another app");if(r.issuer&&!F(r.issuer,l.iss))throw new v("issuer","Token was issued by someone else");return l}function X(){let e=document.body;if(!e)return 0;let t=getComputedStyle(e),r=e.getBoundingClientRect().top+parseFloat(t.paddingTop)+parseFloat(t.borderTopWidth);for(let n of e.children){let a=getComputedStyle(n);a.position==="fixed"||a.display==="none"||n.localName==="script"||(r=Math.max(r,n.getBoundingClientRect().bottom+parseFloat(a.marginBottom)))}return Math.ceil(r+scrollY+parseFloat(t.paddingBottom)+parseFloat(t.borderBottomWidth)+parseFloat(t.marginBottom))}var D="commmerce-app-bridge:host-origin";function ee(e=te()){let{ancestorOrigins:t,referrer:r,self:n,remembered:a}=e;if(t)return t.length&&t[0]!=="null"?t[0]:void 0;let s;try{s=r?new URL(r).origin:void 0}catch{s=void 0}if(!(!s||s==="null"))return s===n?a||void 0:s}function te(){let e=null;try{e=sessionStorage.getItem(D)}catch{}return{ancestorOrigins:location.ancestorOrigins,referrer:document.referrer,self:location.origin,remembered:e}}function re(e,t){if(!x(e.hostOrigin))return C(e.hostOrigin,"hostOrigin");let r=O(e.hostOrigin,"hostOrigin"),n=e.exactHostOrigin;if(!n){if(t!==window.parent)throw new Error("App Bridge: with a pattern hostOrigin and a custom target, pass exactHostOrigin");n=ee()}if(!n)throw new Error(`App Bridge: hostOrigin is the pattern ${r.source}, but the admin's origin can't be found (no location.ancestorOrigins and no document.referrer, or the admin hides them). Is the page inside the admin?`);if(!z(r,n))throw new Error(`App Bridge: the admin's origin ${n} does not match hostOrigin ${r.source}. Messages to it are refused.`);let a=new URL(n).origin;if(!e.exactHostOrigin)try{sessionStorage.setItem(D,a)}catch{}return a}var ne=["modal.open","resourcePicker.open"],oe=0;function se(e){x(e.hostOrigin)?O(e.hostOrigin,"hostOrigin"):C(e.hostOrigin,"hostOrigin");let t=e.target??window.parent;if(!t||t===window)throw new Error("App Bridge: the app is not inside the admin (no parent window)");let r=re(e,t),n=e.timeout??1e4,a=new Map,s=new Map,l=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,m=!1,i=null,y=new Set,f,d=o=>{if(!A(o.data))return e.onReject?.("not an App Bridge message",o);if(o.source!==t)return e.onReject?.("not from the admin window",o);if(o.origin!==r)return e.onReject?.(`origin ${o.origin} is not ${r}`,o);let p=o.data;if(p.kind==="response"){let u=a.get(p.id);if(!u)return;a.delete(p.id),clearTimeout(u.timer);let b=p;b.ok?u.resolve(b.result):u.reject(new w(b.error?.code??"failed",b.error?.message??"The admin refused the request"))}else p.kind==="event"&&s.get(p.type)?.forEach(u=>u(p.payload))};window.addEventListener("message",d);function c(o,p){if(m)return Promise.reject(new w("failed","App Bridge was destroyed"));let u=`${l}-${++oe}`;return new Promise((b,k)=>{let E={resolve:b,reject:k};ne.includes(o)||(E.timer=setTimeout(()=>{a.delete(u),k(new w("timeout",`The admin did not answer "${o}" within ${n} ms`))},n)),a.set(u,E),t.postMessage({protocol:H,version:1,kind:"request",id:u,type:o,payload:p},r)})}let g=c("ready",e.apiKey?{apiKey:e.apiKey}:{});g.catch(()=>{});let h=(o,p)=>g.then(()=>c(o,p));return{hostOrigin:r,ready:g,toast:{show:(o,p={})=>h("toast.show",{message:o,...p})},modal:{open:o=>h("modal.open",o)},navigate:(o,p={})=>h("navigate",{path:o,...p}),saveBar:{show:(o={})=>h("saveBar.show",o),hide:()=>h("saveBar.hide",{})},resourcePicker:o=>h("resourcePicker.open",o),loading:{start:()=>h("loading.start",{}),stop:()=>h("loading.stop",{})},async getSessionToken(){if(i&&i.exp*1e3-Date.now()>1e4)return i.value;let o=await h("sessionToken.get",{}),p=Number(B(o).exp);return i=Number.isFinite(p)?{value:o,exp:p}:null,o},autoResize(){if(f)return f;let o=-1,p=0,u=()=>{p=0;let S=X();S===o||m||(o=S,h("frame.resize",{height:S}).catch(()=>{}))},b=()=>{p||(p=requestAnimationFrame(u))},k=new ResizeObserver(b),E=()=>{k.disconnect(),k.observe(document.body);for(let S of document.body.children)k.observe(S);b()},U=new MutationObserver(E);U.observe(document.body,{childList:!0}),E();let M=()=>{k.disconnect(),U.disconnect(),cancelAnimationFrame(p),y.delete(M),f===M&&(f=void 0)};return y.add(M),f=M,M},on(o,p){let u=s.get(o)??new Set;return s.set(o,u),u.add(p),()=>u.delete(p)},destroy(){m=!0,[...y].forEach(o=>o()),window.removeEventListener("message",d);for(let[,o]of a)clearTimeout(o.timer),o.reject(new w("failed","App Bridge was destroyed"));a.clear(),s.clear()}}}var P=(e,t)=>typeof e=="string"&&e.trim().length>0&&e.length<=t,$=(e,t)=>e===void 0||P(e,t),q=e=>e===void 0||typeof e=="boolean";function J(e){if(typeof e!="string"||e.length===0||e.length>2e3||!e.startsWith("/")||e.startsWith("//")||e.includes("\\")||/[\u0000-\u001f\u007f]/.test(e))return!1;try{return new URL(e,"https://app-bridge.invalid").origin==="https://app-bridge.invalid"}catch{return!1}}function V(e,t){switch(e){case"ready":return $(t.apiKey,200)?null:"apiKey must be a string";case"toast.show":return P(t.message,200)?t.tone!==void 0&&!["default","success","critical"].includes(t.tone)?"tone must be default, success or critical":t.duration!==void 0&&!(typeof t.duration=="number"&&t.duration>=2e3&&t.duration<=1e4)?"duration must be 2000\u201310000 ms":null:"message must be 1\u2013200 characters";case"modal.open":{if(!P(t.title,100)||!P(t.message,1e3))return"title (1\u2013100) and message (1\u20131000 characters) are required";let r=t.primaryAction,n=t.secondaryAction;return r!==void 0&&!(r&&P(r.label,40)&&q(r.destructive))?"primaryAction needs a label (1\u201340 characters)":n!==void 0&&!(n&&P(n.label,40))?"secondaryAction needs a label (1\u201340 characters)":null}case"navigate":return J(t.path)?q(t.replace)?null:"replace must be a boolean":"path must be a path inside the app, starting with a single / (no \\, no control characters)";case"frame.resize":return typeof t.height=="number"&&Number.isFinite(t.height)&&t.height>=0&&t.height<=1e5?null:"height must be a number of pixels, 0\u2013100000";case"saveBar.show":return $(t.message,100)&&$(t.saveLabel,40)&&$(t.discardLabel,40)&&q(t.loading)?null:"message (\u2264100), saveLabel and discardLabel (\u226440) must be strings; loading a boolean";case"resourcePicker.open":return["product","customer","collection"].includes(t.type)?q(t.multiple)?null:"multiple must be a boolean":"type must be product, customer or collection";default:return null}}function I(e){let t=C(e.appOrigin,"appOrigin"),{iframe:r,handlers:n}=e,a=!1,s=!1,l=d=>{s||r.contentWindow?.postMessage({protocol:H,version:1,...d},t)},m=(d,c,g)=>l({kind:"response",id:d,ok:!1,error:{code:c,message:g}}),i=(d,c)=>{let g=h=>{if(!h)throw new w("not-supported",`This admin does not support "${d}"`)};switch(d){case"ready":if(e.apiKey&&c.apiKey!==e.apiKey)throw new w("failed","API key does not match this app");return a=!0,{version:1,theme:e.info?.theme??"light",locale:e.info?.locale??"en-IN"};case"toast.show":return g(n.toast),n.toast(c);case"modal.open":return g(n.modal),n.modal(c);case"navigate":return g(n.navigate),n.navigate(c);case"saveBar.show":return g(n.saveBar),n.saveBar(c);case"saveBar.hide":return g(n.saveBar),n.saveBar(null);case"resourcePicker.open":return g(n.resourcePicker),n.resourcePicker(c);case"loading.start":return g(n.loading),n.loading(!0);case"loading.stop":return g(n.loading),n.loading(!1);case"sessionToken.get":return g(n.sessionToken),n.sessionToken();case"frame.resize":if(n.resize)return n.resize(c);r.style.blockSize=`${Math.ceil(c.height)}px`;return}},y=["ready","toast.show","modal.open","navigate","saveBar.show","saveBar.hide","resourcePicker.open","loading.start","loading.stop","sessionToken.get","frame.resize"],f=async d=>{if(!A(d.data))return e.onReject?.("not an App Bridge message",d);if(!r.contentWindow||d.source!==r.contentWindow)return e.onReject?.("not from the app frame",d);if(d.origin!==t)return e.onReject?.(`origin ${d.origin} is not ${t}`,d);let c=d.data;if(c.kind!=="request"||typeof c.id!="string")return e.onReject?.("not a request",d);let{id:g,type:h}=c;if(c.version!==1)return m(g,"unsupported-version",`This admin speaks App Bridge version ${1}`);if(!y.includes(h))return m(g,"unknown-type",`Unknown request "${String(h)}"`);if(h!=="ready"&&!a)return m(g,"not-ready",'Send "ready" first');let o=c.payload&&typeof c.payload=="object"?c.payload:{},p=V(h,o);if(p)return m(g,"invalid-payload",p);try{let u=await i(h,o);l({kind:"response",id:g,ok:!0,...u===void 0?{}:{result:u}})}catch(u){u instanceof w?m(g,u.code,u.message):m(g,"failed",u instanceof Error?u.message:"The admin could not complete the request")}};return window.addEventListener("message",f),{send(d,c){a&&l({kind:"event",type:d,payload:c})},get connected(){return a},destroy(){s=!0,a=!1,window.removeEventListener("message",f)}}}var ie={product:"products",customer:"customers",collection:"collections"};function T(e,t={},r){let n=document.createElement(e);for(let[a,s]of Object.entries(t))s!==!1&&n.setAttribute(a,s===!0?"":s);return r!==void 0&&(n.textContent=r),n}function Y(e,t,r,n){return new Promise(a=>{let s=T("cm-modal",{heading:t});s.append(r);let l="close";for(let m of n){let i=T("cm-button",{slot:"footer",variant:m.primary?"primary":"secondary"},m.label);i.addEventListener("click",()=>{l=m.value,s.close()}),s.append(i)}s.addEventListener("cm-closed",()=>{s.remove(),a(l)}),e.append(s),s.show()})}function ae(e){let t=e.root??document.body,r,n=T("cm-toast-region",{"data-app-bridge":"toasts",max:"1"}),a=T("cm-progress-bar",{label:"Loading","label-hidden":!0,size:"small",hidden:!0,"data-app-bridge":"loading"});a.style.cssText="position:fixed;inset-block-start:0;inset-inline:0;z-index:1000";let s=T("cm-save-bar",{"data-app-bridge":"save-bar"});s.addEventListener("cm-save",i=>{i.preventDefault(),r.send("saveBar.save",{})}),s.addEventListener("cm-discard",i=>{i.preventDefault(),r.send("saveBar.discard",{})}),t.append(n,a,s);let l={toast({message:i,tone:y="default",duration:f=5e3}){let d=T("cm-toast",{"data-tone":y});d.message=i,d.tone=y==="critical"?"critical":"default",d.duration=f,n.add(d)},async modal({title:i,message:y,primaryAction:f,secondaryAction:d}){let c=[];return d&&c.push({label:d.label,value:"secondary"}),f&&c.push({label:f.label,value:"primary",primary:!0}),await Y(t,i,T("p",{},y),c)},navigate({path:i,replace:y}){if(e.navigate)return e.navigate(i,!!y);let f=`${location.pathname}${location.search}#${i}`;y?history.replaceState(history.state,"",f):history.pushState(history.state,"",f)},saveBar(i){if(!i){s.open=!1;return}s.message=i.message??"Unsaved changes",i.saveLabel&&(s.saveLabel=i.saveLabel),i.discardLabel&&(s.discardLabel=i.discardLabel),s.loading=!!i.loading,s.open=!0},loading(i){a.hidden=!i}};if(e.resources){let i=e.resources;l.resourcePicker=async({type:y,multiple:f})=>{let d=await i(y),c=T(f?"div":"cm-radio-group",f?{}:{label:`Choose ${y}`});c.style.cssText="display:grid;gap:var(--cm-space-10,10px)";for(let o of d)c.append(T(f?"cm-checkbox":"cm-radio",{label:o.title,value:o.id}));if(await Y(t,`Select ${ie[y]}`,c,[{label:"Cancel",value:"secondary"},{label:"Select",value:"primary",primary:!0}])!=="primary")return null;let h=[...c.querySelectorAll("cm-checkbox, cm-radio")].filter(o=>o.checked).map(o=>o.value);return d.filter(o=>h.includes(o.id))}}e.sessionToken&&(l.sessionToken=e.sessionToken),r=I({...e,handlers:l});let m=r.destroy;return Object.assign(Object.create(null),{send:r.send,get connected(){return r.connected},destroy(){m(),n.remove(),a.remove(),s.remove()}})}export{w as AppBridgeError,H as PROTOCOL,R as PROTOCOL_VERSION,v as SessionTokenError,se as createApp,I as createHost,ae as createReferenceHost,B as decodeClaims,J as isAppPath,A as isMessage,x as isOriginPattern,F as matchesOrigin,z as matchesOriginPattern,C as normalizeOrigin,O as parseOriginPattern,G as signSessionToken,V as validatePayload,Q as verifySessionToken};
1
+ var H="commmerce-app-bridge",O=1,b=class extends Error{constructor(t,r){super(r),this.name="AppBridgeError",this.code=t}};function B(e){if(!e||typeof e!="object")return!1;let t=e;return t.protocol===H&&typeof t.version=="number"&&(t.kind==="request"||t.kind==="response"||t.kind==="event")}function C(e,t){if(!e||e==="*"||e==="null")throw new TypeError(`App Bridge: ${t} must be an exact origin such as https://app.example.com, not "${e}"`);if(String(e).includes("*"))throw new TypeError(`App Bridge: ${t} must be an exact origin such as https://app.example.com, not the pattern "${e}"`);let r=new URL(e).origin;if(r==="null")throw new TypeError(`App Bridge: ${t} "${e}" has no origin`);return r}var W=/^(?!-)[a-z0-9-]{1,63}(?<!-)$/,Z={"https:":"443","http:":"80"};function x(e){return typeof e=="string"&&e.includes("*")}function R(e,t="origin pattern"){let r=u=>new TypeError(`App Bridge: ${t} "${e}" is not a valid origin pattern: ${u}. Use an exact origin such as https://admin.example.com, or a pattern such as https://*.commmerce.com`),n=/^(https?):\/\/\*\.([^:/?#]*)(?::(\d{1,5}))?$/i.exec(String(e));if(!n)throw r("it must be https://*.domain or http://*.domain, with an optional :port and nothing else");let a=`${n[1].toLowerCase()}:`,i=n[2].toLowerCase(),d=i.split(".");if(i.length>253||!d.every(u=>W.test(u)))throw r('the part after "*." must be a domain name (letters, digits, hyphens and dots)');if(d.length<2&&i!=="localhost")throw r('the domain after "*." needs at least one dot, e.g. *.commmerce.com');if(/^(\d+|0x[0-9a-f]*)$/.test(d[d.length-1]))throw r("IP addresses cannot have a wildcard");let m="";if(n[3]!==void 0){let u=Number(n[3]);if(u<1||u>65535)throw r("the port must be 1 to 65535");m=String(u)===Z[a]?"":String(u)}return{scheme:a,domain:i,port:m,source:String(e)}}function N(e,t){let r=typeof e=="string"?R(e):e;if(typeof t!="string"||!t)return!1;let n;try{n=new URL(t)}catch{return!1}if(n.origin==="null"||n.origin!==t.toLowerCase()||n.protocol!==r.scheme||n.port!==r.port)return!1;let a=`.${r.domain}`;if(!n.hostname.endsWith(a))return!1;let i=n.hostname.slice(0,-a.length);return i.length>0&&i.split(".").every(d=>W.test(d))}function F(e,t){return x(e)?N(R(e,"allowed origin"),t):typeof t=="string"&&t===e}var L=new TextEncoder,_=new TextDecoder;function j(e){let t="";return e.forEach(r=>{t+=String.fromCharCode(r)}),btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function I(e){if(!/^[A-Za-z0-9_-]*$/.test(e))throw new y("malformed","Token is not base64url");let t=atob(e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-e.length%4)%4));return Uint8Array.from(t,r=>r.charCodeAt(0))}var D=(e,t)=>crypto.subtle.importKey("raw",L.encode(e),{name:"HMAC",hash:"SHA-256"},!1,[t]),y=class extends Error{constructor(t,r){super(r),this.name="SessionTokenError",this.code=t}};async function G(e,t){if(!t)throw new TypeError("signSessionToken: secret is required");let r=Math.floor(Date.now()/1e3),n={iat:r,nbf:r,exp:r+60,jti:crypto.randomUUID(),...e},a=j(L.encode(JSON.stringify({alg:"HS256",typ:"JWT"}))),i=j(L.encode(JSON.stringify(n))),d=await crypto.subtle.sign("HMAC",await D(t,"sign"),L.encode(`${a}.${i}`));return`${a}.${i}.${j(new Uint8Array(d))}`}function $(e){let t=String(e).split(".");if(t.length!==3)throw new y("malformed","Token must have three parts");try{return JSON.parse(_.decode(I(t[1])))}catch(r){throw r instanceof y?r:new y("malformed","Token claims are not JSON")}}async function Q(e,t,r){if(!t)throw new TypeError("verifySessionToken: secret is required");if(!r?.audience)throw new TypeError("verifySessionToken: options.audience (your API key) is required");r.issuer&&x(r.issuer)&&R(r.issuer,"verifySessionToken: options.issuer");let n=String(e).split(".");if(n.length!==3)throw new y("malformed","Token must have three parts");let a;try{a=JSON.parse(_.decode(I(n[0])))}catch{throw new y("malformed","Token header is not JSON")}if(a.alg!=="HS256")throw new y("algorithm",`Algorithm ${a.alg} is not allowed`);if(!await crypto.subtle.verify("HMAC",await D(t,"verify"),I(n[2]),L.encode(`${n[0]}.${n[1]}`)))throw new y("signature","Signature does not match");let d=$(e),m=r.now??Math.floor(Date.now()/1e3),u=r.clockTolerance??5;if(typeof d.exp!="number"||m-u>=d.exp)throw new y("expired","Token has expired");if(typeof d.nbf=="number"&&m+u<d.nbf)throw new y("not-yet-valid","Token is not valid yet");if(d.aud!==r.audience)throw new y("audience","Token is for another app");if(r.issuer&&!F(r.issuer,d.iss))throw new y("issuer","Token was issued by someone else");return d}function X(){let e=document.body;if(!e)return 0;let t=getComputedStyle(e),r=e.getBoundingClientRect().top+parseFloat(t.paddingTop)+parseFloat(t.borderTopWidth);for(let n of e.children){let a=getComputedStyle(n);a.position==="fixed"||a.display==="none"||n.localName==="script"||(r=Math.max(r,n.getBoundingClientRect().bottom+parseFloat(a.marginBottom)))}return Math.ceil(r+scrollY+parseFloat(t.paddingBottom)+parseFloat(t.borderBottomWidth)+parseFloat(t.marginBottom))}var J="commmerce-app-bridge:host-origin";function ee(e=te()){let{ancestorOrigins:t,referrer:r,self:n,remembered:a,sameOriginParent:i}=e;if(t)return t.length&&t[0]!=="null"?t[0]:void 0;if(i)return n;let d;try{d=r?new URL(r).origin:void 0}catch{d=void 0}if(!(!d||d==="null"))return d===n?a||void 0:d}function te(){let e=null;try{e=sessionStorage.getItem(J)}catch{}let t=!1;try{t=window.parent!==window&&window.parent.location.origin===location.origin}catch{}return{ancestorOrigins:location.ancestorOrigins,referrer:document.referrer,self:location.origin,remembered:e,sameOriginParent:t}}function re(e,t){if(!x(e.hostOrigin))return C(e.hostOrigin,"hostOrigin");let r=R(e.hostOrigin,"hostOrigin"),n=e.exactHostOrigin;if(!n){if(t!==window.parent)throw new Error("App Bridge: with a pattern hostOrigin and a custom target, pass exactHostOrigin");n=ee()}if(!n)throw new Error(`App Bridge: hostOrigin is the pattern ${r.source}, but the admin's origin can't be found (no location.ancestorOrigins and no document.referrer, or the admin hides them). Is the page inside the admin?`);if(!N(r,n))throw new Error(`App Bridge: the admin's origin ${n} does not match hostOrigin ${r.source}. Messages to it are refused.`);let a=new URL(n).origin;if(!e.exactHostOrigin)try{sessionStorage.setItem(J,a)}catch{}return a}var ne=["modal.open","resourcePicker.open"],oe=0;function se(e){x(e.hostOrigin)?R(e.hostOrigin,"hostOrigin"):C(e.hostOrigin,"hostOrigin");let t=e.target??window.parent;if(!t||t===window)throw new Error("App Bridge: the app is not inside the admin (no parent window)");let r=re(e,t),n=e.timeout??1e4,a=new Map,i=new Map,d=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,m=!1,u=null,T=new Set,v,f=s=>{if(!B(s.data))return e.onReject?.("not an App Bridge message",s);if(s.source!==t)return e.onReject?.("not from the admin window",s);if(s.origin!==r)return e.onReject?.(`origin ${s.origin} is not ${r}`,s);let l=s.data;if(l.kind==="response"){let g=a.get(l.id);if(!g)return;a.delete(l.id),clearTimeout(g.timer);let w=l;w.ok?g.resolve(w.result):g.reject(new b(w.error?.code??"failed",w.error?.message??"The admin refused the request"))}else l.kind==="event"&&i.get(l.type)?.forEach(g=>g(l.payload))};window.addEventListener("message",f);function o(s,l){if(m)return Promise.reject(new b("failed","App Bridge was destroyed"));let g=`${d}-${++oe}`;return new Promise((w,h)=>{let E={resolve:w,reject:h};ne.includes(s)||(E.timer=setTimeout(()=>{a.delete(g),h(new b("timeout",`The admin did not answer "${s}" within ${n} ms`))},n)),a.set(g,E),t.postMessage({protocol:H,version:1,kind:"request",id:g,type:s,payload:l},r)})}let c=o("ready",e.apiKey?{apiKey:e.apiKey}:{});c.catch(()=>{});let p=(s,l)=>c.then(()=>o(s,l));return{hostOrigin:r,ready:c,toast:{show:(s,l={})=>p("toast.show",{message:s,...l})},modal:{open:s=>p("modal.open",s)},navigate:(s,l={})=>p("navigate",{path:s,...l}),saveBar:{show:(s={})=>p("saveBar.show",s),hide:()=>p("saveBar.hide",{})},resourcePicker:s=>p("resourcePicker.open",s),loading:{start:()=>p("loading.start",{}),stop:()=>p("loading.stop",{})},async getSessionToken(){if(u&&u.exp*1e3-Date.now()>1e4)return u.value;let s=await p("sessionToken.get",{}),l=Number($(s).exp);return u=Number.isFinite(l)?{value:s,exp:l}:null,s},autoResize(){if(v)return v;let s=-1,l=0,g=()=>{l=0;let S=X();S===s||m||(s=S,p("frame.resize",{height:S}).catch(()=>{}))},w=()=>{l||(l=requestAnimationFrame(g))},h=new ResizeObserver(w),E=()=>{h.disconnect(),h.observe(document.body);for(let S of document.body.children)h.observe(S);w()},K=new MutationObserver(E);K.observe(document.body,{childList:!0}),E();let M=()=>{h.disconnect(),K.disconnect(),cancelAnimationFrame(l),T.delete(M),v===M&&(v=void 0)};return T.add(M),v=M,M},on(s,l){let g=i.get(s)??new Set;return i.set(s,g),g.add(l),()=>g.delete(l)},destroy(){m=!0,[...T].forEach(s=>s()),window.removeEventListener("message",f);for(let[,s]of a)clearTimeout(s.timer),s.reject(new b("failed","App Bridge was destroyed"));a.clear(),i.clear()}}}var P=(e,t)=>typeof e=="string"&&e.trim().length>0&&e.length<=t,q=(e,t)=>e===void 0||P(e,t),z=e=>e===void 0||typeof e=="boolean";function A(e){if(typeof e!="string"||e.length===0||e.length>2e3||!e.startsWith("/")||e.startsWith("//")||e.includes("\\")||/[\u0000-\u001f\u007f]/.test(e))return!1;try{return new URL(e,"https://app-bridge.invalid").origin==="https://app-bridge.invalid"}catch{return!1}}function V(e,t){switch(e){case"ready":return q(t.apiKey,200)?null:"apiKey must be a string";case"toast.show":return P(t.message,200)?t.tone!==void 0&&!["default","success","critical"].includes(t.tone)?"tone must be default, success or critical":t.duration!==void 0&&!(typeof t.duration=="number"&&t.duration>=2e3&&t.duration<=1e4)?"duration must be 2000\u201310000 ms":null:"message must be 1\u2013200 characters";case"modal.open":{if(!P(t.title,100)||!P(t.message,1e3))return"title (1\u2013100) and message (1\u20131000 characters) are required";let r=t.primaryAction,n=t.secondaryAction;return r!==void 0&&!(r&&P(r.label,40)&&z(r.destructive))?"primaryAction needs a label (1\u201340 characters)":n!==void 0&&!(n&&P(n.label,40))?"secondaryAction needs a label (1\u201340 characters)":null}case"navigate":return A(t.path)?z(t.replace)?null:"replace must be a boolean":"path must be a path inside the app, starting with a single / (no \\, no control characters)";case"frame.resize":return typeof t.height=="number"&&Number.isFinite(t.height)&&t.height>=0&&t.height<=1e5?null:"height must be a number of pixels, 0\u2013100000";case"saveBar.show":return q(t.message,100)&&q(t.saveLabel,40)&&q(t.discardLabel,40)&&z(t.loading)?null:"message (\u2264100), saveLabel and discardLabel (\u226440) must be strings; loading a boolean";case"resourcePicker.open":return["product","customer","collection"].includes(t.type)?z(t.multiple)?null:"multiple must be a boolean":"type must be product, customer or collection";default:return null}}function U(e){let t=C(e.appOrigin,"appOrigin"),{iframe:r,handlers:n}=e,a=!1,i=!1,d=f=>{i||r.contentWindow?.postMessage({protocol:H,version:1,...f},t)},m=(f,o,c)=>d({kind:"response",id:f,ok:!1,error:{code:o,message:c}}),u=(f,o)=>{let c=p=>{if(!p)throw new b("not-supported",`This admin does not support "${f}"`)};switch(f){case"ready":if(e.apiKey&&o.apiKey!==e.apiKey)throw new b("failed","API key does not match this app");a=!0;{let p={version:1,theme:e.info?.theme??"light",locale:e.info?.locale??"en-IN"},s=e.currentPath?e.currentPath():e.info?.path;return s!==void 0&&(p.path=A(s)?s:"/"),p}case"toast.show":return c(n.toast),n.toast(o);case"modal.open":return c(n.modal),n.modal(o);case"navigate":return c(n.navigate),n.navigate(o);case"saveBar.show":return c(n.saveBar),n.saveBar(o);case"saveBar.hide":return c(n.saveBar),n.saveBar(null);case"resourcePicker.open":return c(n.resourcePicker),n.resourcePicker(o);case"loading.start":return c(n.loading),n.loading(!0);case"loading.stop":return c(n.loading),n.loading(!1);case"sessionToken.get":return c(n.sessionToken),n.sessionToken();case"frame.resize":if(n.resize)return n.resize(o);r.style.blockSize=`${Math.ceil(o.height)}px`;return}},T=["ready","toast.show","modal.open","navigate","saveBar.show","saveBar.hide","resourcePicker.open","loading.start","loading.stop","sessionToken.get","frame.resize"],v=async f=>{if(!B(f.data))return e.onReject?.("not an App Bridge message",f);if(!r.contentWindow||f.source!==r.contentWindow)return e.onReject?.("not from the app frame",f);if(f.origin!==t)return e.onReject?.(`origin ${f.origin} is not ${t}`,f);let o=f.data;if(o.kind!=="request"||typeof o.id!="string")return e.onReject?.("not a request",f);let{id:c,type:p}=o;if(o.version!==1)return m(c,"unsupported-version",`This admin speaks App Bridge version ${1}`);if(!T.includes(p))return m(c,"unknown-type",`Unknown request "${String(p)}"`);if(p!=="ready"&&!a)return m(c,"not-ready",'Send "ready" first');let s=o.payload&&typeof o.payload=="object"?o.payload:{},l=V(p,s);if(l)return m(c,"invalid-payload",l);try{let g=await u(p,s);d({kind:"response",id:c,ok:!0,...g===void 0?{}:{result:g}})}catch(g){g instanceof b?m(c,g.code,g.message):m(c,"failed",g instanceof Error?g.message:"The admin could not complete the request")}};return window.addEventListener("message",v),{send(f,o){a&&d({kind:"event",type:f,payload:o})},get connected(){return a},destroy(){i=!0,a=!1,window.removeEventListener("message",v)}}}var ie={product:"products",customer:"customers",collection:"collections"};function k(e,t={},r){let n=document.createElement(e);for(let[a,i]of Object.entries(t))i!==!1&&n.setAttribute(a,i===!0?"":i);return r!==void 0&&(n.textContent=r),n}function Y(e,t,r,n){return new Promise(a=>{let i=k("cm-modal",{heading:t});i.append(r);let d="close";for(let m of n){let u=k("cm-button",{slot:"footer",variant:m.primary?"primary":"secondary"},m.label);u.addEventListener("click",()=>{d=m.value,i.close()}),i.append(u)}i.addEventListener("cm-closed",()=>{i.remove(),a(d)}),e.append(i),i.show()})}function ae(e){let t=e.root??document.body,r,n=k("cm-toast-region",{"data-app-bridge":"toasts",max:"1"}),a=k("cm-progress-bar",{label:"Loading","label-hidden":!0,size:"small",hidden:!0,"data-app-bridge":"loading"});a.style.cssText="position:fixed;inset-block-start:0;inset-inline:0;z-index:1000";let i=k("cm-save-bar",{"data-app-bridge":"save-bar"});i.addEventListener("cm-save",o=>{o.preventDefault(),r.send("saveBar.save",{})}),i.addEventListener("cm-discard",o=>{o.preventDefault(),r.send("saveBar.discard",{})}),t.append(n,a,i);let d={toast({message:o,tone:c="default",duration:p=5e3}){let s=k("cm-toast",{"data-tone":c});s.message=o,s.tone=c==="critical"?"critical":"default",s.duration=p,n.add(s)},async modal({title:o,message:c,primaryAction:p,secondaryAction:s}){let l=[];return s&&l.push({label:s.label,value:"secondary"}),p&&l.push({label:p.label,value:"primary",primary:!0}),await Y(t,o,k("p",{},c),l)},navigate({path:o,replace:c}){if(e.navigate)return e.navigate(o,!!c);let p=`${location.pathname}${location.search}#${o}`;c?history.replaceState(history.state,"",p):history.pushState(history.state,"",p)},saveBar(o){if(!o){i.open=!1;return}i.message=o.message??"Unsaved changes",o.saveLabel&&(i.saveLabel=o.saveLabel),o.discardLabel&&(i.discardLabel=o.discardLabel),i.loading=!!o.loading,i.open=!0},loading(o){a.hidden=!o}};if(e.resources){let o=e.resources;d.resourcePicker=async({type:c,multiple:p})=>{let s=await o(c),l=k(p?"div":"cm-radio-group",p?{}:{label:`Choose ${c}`});l.style.cssText="display:grid;gap:var(--cm-space-10,10px)";for(let h of s)l.append(k(p?"cm-checkbox":"cm-radio",{label:h.title,value:h.id}));if(await Y(t,`Select ${ie[c]}`,l,[{label:"Cancel",value:"secondary"},{label:"Select",value:"primary",primary:!0}])!=="primary")return null;let w=[...l.querySelectorAll("cm-checkbox, cm-radio")].filter(h=>h.checked).map(h=>h.value);return s.filter(h=>w.includes(h.id))}}e.sessionToken&&(d.sessionToken=e.sessionToken);let m=()=>{let o=location.hash.slice(1);try{o=decodeURI(o)}catch{}return o.startsWith("/")?o:"/"},u="",T=()=>{let o=m();o!==u&&(u=o,r.connected&&r.send("path.change",{path:A(o)?o:"/"}))},v=!e.navigate;if(v){let o=d.navigate;d.navigate=c=>(u=c.path,o(c)),u=m(),addEventListener("popstate",T),addEventListener("hashchange",T)}r=U({...e,...v&&!e.currentPath?{currentPath:m}:{},handlers:d});let f=r.destroy;return Object.assign(Object.create(null),{send:r.send,get connected(){return r.connected},destroy(){f(),removeEventListener("popstate",T),removeEventListener("hashchange",T),n.remove(),a.remove(),i.remove()}})}export{b as AppBridgeError,H as PROTOCOL,O as PROTOCOL_VERSION,y as SessionTokenError,se as createApp,U as createHost,ae as createReferenceHost,$ as decodeClaims,A as isAppPath,B as isMessage,x as isOriginPattern,F as matchesOrigin,N as matchesOriginPattern,C as normalizeOrigin,R as parseOriginPattern,G as signSessionToken,V as validatePayload,Q as verifySessionToken};
package/dist/client.d.ts CHANGED
@@ -70,13 +70,15 @@ export interface App {
70
70
  * against the pattern, and the browser's own `postMessage` origin check stops anything being sent to another
71
71
  * window. Uses `location.ancestorOrigins[0]` when the browser has it (it is the parent's origin, or `"null"` when
72
72
  * the admin hides it). Otherwise the origin of `document.referrer`: the page that loaded this one into the frame.
73
- * After a link inside the app, the referrer is the app's own page, so the origin remembered for this tab is used.
73
+ * After a link inside the app, the referrer is the app's own page, so the origin remembered for this tab is used,
74
+ * unless the parent is on this page's own origin (`sameOriginParent`: then the parent's origin is known for sure).
74
75
  */
75
76
  export declare function detectHostOrigin(source?: {
76
77
  ancestorOrigins?: ArrayLike<string> | null;
77
78
  referrer?: string;
78
79
  self?: string;
79
80
  remembered?: string | null;
81
+ sameOriginParent?: boolean;
80
82
  }): string | undefined;
81
83
  /** Connects an app running in an iframe to the Commmerce admin around it. */
82
84
  export declare function createApp(config: AppConfig): App;
package/dist/client.js CHANGED
@@ -25,12 +25,15 @@ const REMEMBER = 'commmerce-app-bridge:host-origin';
25
25
  * against the pattern, and the browser's own `postMessage` origin check stops anything being sent to another
26
26
  * window. Uses `location.ancestorOrigins[0]` when the browser has it (it is the parent's origin, or `"null"` when
27
27
  * the admin hides it). Otherwise the origin of `document.referrer`: the page that loaded this one into the frame.
28
- * After a link inside the app, the referrer is the app's own page, so the origin remembered for this tab is used.
28
+ * After a link inside the app, the referrer is the app's own page, so the origin remembered for this tab is used,
29
+ * unless the parent is on this page's own origin (`sameOriginParent`: then the parent's origin is known for sure).
29
30
  */
30
31
  export function detectHostOrigin(source = currentPage()) {
31
- const { ancestorOrigins, referrer, self, remembered } = source;
32
+ const { ancestorOrigins, referrer, self, remembered, sameOriginParent } = source;
32
33
  if (ancestorOrigins)
33
34
  return ancestorOrigins.length && ancestorOrigins[0] !== 'null' ? ancestorOrigins[0] : undefined;
35
+ if (sameOriginParent)
36
+ return self;
34
37
  let from;
35
38
  try {
36
39
  from = referrer ? new URL(referrer).origin : undefined;
@@ -50,7 +53,13 @@ function currentPage() {
50
53
  remembered = sessionStorage.getItem(REMEMBER);
51
54
  }
52
55
  catch { /* storage blocked */ }
53
- return { ancestorOrigins: location.ancestorOrigins, referrer: document.referrer, self: location.origin, remembered };
56
+ // A parent on another origin can't be read (SecurityError); one on this origin can.
57
+ let sameOriginParent = false;
58
+ try {
59
+ sameOriginParent = window.parent !== window && window.parent.location.origin === location.origin;
60
+ }
61
+ catch { /* cross-origin */ }
62
+ return { ancestorOrigins: location.ancestorOrigins, referrer: document.referrer, self: location.origin, remembered, sameOriginParent };
54
63
  }
55
64
  /** The concrete admin origin to talk to, checked against `hostOrigin` (exact or pattern). */
56
65
  function resolveHostOrigin(config, target) {
package/dist/host.d.ts CHANGED
@@ -28,6 +28,12 @@ export interface HostConfig {
28
28
  handlers: Partial<HostHandlers>;
29
29
  /** Sent to the app when it connects. */
30
30
  info?: Partial<Omit<HostInfo, 'version'>>;
31
+ /**
32
+ * The path inside the app that the admin's address points to right now (e.g. `/orders/12`), sent as `path` when
33
+ * the app connects, so a reload opens the same screen. Called on every `ready`, so it stays current. Wins over
34
+ * `info.path`. Paths that fail `isAppPath` are sent as `/`.
35
+ */
36
+ currentPath?: () => string | undefined;
31
37
  /** If set, the app's `ready` request must carry this API key. */
32
38
  apiKey?: string;
33
39
  /** Called with the reason whenever a message is ignored. For logging. */
package/dist/host.js CHANGED
@@ -77,7 +77,13 @@ export function createHost(config) {
77
77
  if (config.apiKey && p.apiKey !== config.apiKey)
78
78
  throw new AppBridgeError('failed', 'API key does not match this app');
79
79
  connected = true;
80
- return { version: PROTOCOL_VERSION, theme: config.info?.theme ?? 'light', locale: config.info?.locale ?? 'en-IN' };
80
+ {
81
+ const info = { version: PROTOCOL_VERSION, theme: config.info?.theme ?? 'light', locale: config.info?.locale ?? 'en-IN' };
82
+ const path = config.currentPath ? config.currentPath() : config.info?.path;
83
+ if (path !== undefined)
84
+ info.path = isAppPath(path) ? path : '/';
85
+ return info;
86
+ }
81
87
  case 'toast.show':
82
88
  need(handlers.toast);
83
89
  return handlers.toast(p);
@@ -62,6 +62,12 @@ export interface HostInfo {
62
62
  theme: 'light' | 'dark';
63
63
  /** BCP 47 locale of the staff member, e.g. `en-IN`. */
64
64
  locale: string;
65
+ /**
66
+ * The path inside your app that the admin's address points to, e.g. `/orders/12`, so a reload or a shared link
67
+ * opens the same screen: show it first. `/` when the address has none. Added in 1.0.0-rc.5 (still protocol v1):
68
+ * older admins leave it out, so treat a missing `path` as `/`.
69
+ */
70
+ path?: string;
65
71
  }
66
72
  /** Every request an app can make, with its payload and result. */
67
73
  export interface RequestMap {
@@ -130,6 +136,13 @@ export interface EventMap {
130
136
  'theme.change': {
131
137
  theme: 'light' | 'dark';
132
138
  };
139
+ /**
140
+ * The admin's address moved to another screen of your app without your app asking (the merchant pressed Back or
141
+ * Forward, or followed an admin link). Show `path`; don't call `navigate` for it. Added in 1.0.0-rc.5.
142
+ */
143
+ 'path.change': {
144
+ path: string;
145
+ };
133
146
  }
134
147
  export type EventType = keyof EventMap;
135
148
  export interface RequestMessage<T extends RequestType = RequestType> {
@@ -9,7 +9,11 @@ import type { PickedResource, ResourcePickerOptions } from './protocol.js';
9
9
  export interface ReferenceHostConfig extends Omit<HostConfig, 'handlers'> {
10
10
  /** Where toasts, modals, the save bar and the loading bar are added. Default `document.body`. */
11
11
  root?: HTMLElement;
12
- /** Update the admin's address. Default: `history.pushState` / `replaceState` with `#<path>`. */
12
+ /**
13
+ * Update the admin's address. Default: `history.pushState` / `replaceState` with `#<path>`, read back on reload
14
+ * (`path` in `ready`) and on Back and Forward (the `path.change` event). With your own `navigate`, also pass
15
+ * `currentPath` and send `path.change` yourself.
16
+ */
13
17
  navigate?: (path: string, replace: boolean) => void;
14
18
  /** The candidates the resource picker lists. Without it, the picker answers `not-supported`. */
15
19
  resources?: (type: ResourcePickerOptions['type']) => Promise<PickedResource[]> | PickedResource[];
@@ -1,4 +1,4 @@
1
- import { createHost } from './host.js';
1
+ import { createHost, isAppPath } from './host.js';
2
2
  const TYPE_NAMES = { product: 'products', customer: 'customers', collection: 'collections' };
3
3
  function el(tag, attrs = {}, text) {
4
4
  const e = document.createElement(tag);
@@ -98,11 +98,35 @@ export function createReferenceHost(config) {
98
98
  }
99
99
  if (config.sessionToken)
100
100
  handlers.sessionToken = config.sessionToken;
101
- host = createHost({ ...config, handlers });
101
+ // Without a custom navigate, the app's path lives in the admin's #hash: hand it back on connect, and tell the
102
+ // app when Back or Forward moves it (pushState from navigate() fires neither event, so the app's own moves
103
+ // are never echoed back).
104
+ const hashPath = () => { let h = location.hash.slice(1); try {
105
+ h = decodeURI(h);
106
+ }
107
+ catch { /* keep it encoded */ } return h.startsWith('/') ? h : '/'; };
108
+ let lastPath = '';
109
+ const onHistory = () => {
110
+ const path = hashPath();
111
+ if (path === lastPath)
112
+ return;
113
+ lastPath = path;
114
+ if (host.connected)
115
+ host.send('path.change', { path: isAppPath(path) ? path : '/' });
116
+ };
117
+ const ownNavigate = !config.navigate;
118
+ if (ownNavigate) {
119
+ const nav = handlers.navigate;
120
+ handlers.navigate = (p) => { lastPath = p.path; return nav(p); };
121
+ lastPath = hashPath();
122
+ addEventListener('popstate', onHistory);
123
+ addEventListener('hashchange', onHistory);
124
+ }
125
+ host = createHost({ ...config, ...(ownNavigate && !config.currentPath ? { currentPath: hashPath } : {}), handlers });
102
126
  const destroy = host.destroy;
103
127
  return Object.assign(Object.create(null), {
104
128
  send: host.send,
105
129
  get connected() { return host.connected; },
106
- destroy() { destroy(); toasts.remove(); bar.remove(); saveBar.remove(); },
130
+ destroy() { destroy(); removeEventListener('popstate', onHistory); removeEventListener('hashchange', onHistory); toasts.remove(); bar.remove(); saveBar.remove(); },
107
131
  });
108
132
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@commmerce/app-bridge",
3
- "version": "1.0.0-rc.4",
3
+ "version": "1.0.0",
4
4
  "description": "Connects an app embedded in the Commmerce admin to the admin: toasts, modals, navigation, save bar, resource picker, loading bar and session tokens.",
5
5
  "keywords": [
6
6
  "commmerce",
@@ -43,7 +43,7 @@
43
43
  "test": "vitest run"
44
44
  },
45
45
  "devDependencies": {
46
- "@commmerce/ui": "1.0.0-rc.4",
46
+ "@commmerce/ui": "1.0.0",
47
47
  "@vitest/browser": "^2.1.8",
48
48
  "playwright": "^1.49.0"
49
49
  }