@dropins/storefront-company-switcher 1.0.0-beta4 → 1.0.0-beta6

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/api.js CHANGED
@@ -1,4 +1,4 @@
1
1
  /*! Copyright 2025 Adobe
2
2
  All Rights Reserved. */
3
- var f=Object.defineProperty;var l=(t,e,r)=>e in t?f(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var a=(t,e,r)=>l(t,typeof e!="symbol"?e+"":e,r);import{g as C,u as S}from"./chunks/customerCompanyContext.js";import{C as F,f as O,c as x,r as N,s as P,a as T,b as w}from"./chunks/customerCompanyContext.js";import{Initializer as G}from"@dropins/tools/lib.js";import{events as p}from"@dropins/tools/event-bus.js";import"@dropins/tools/fetch-graphql.js";class K{constructor(){a(this,"companyHeaderSet",!1);a(this,"companyHeaderAppliers",[]);a(this,"companyHeaderRemovers",[]);a(this,"headerKey");this.headerKey=m.getConfig().companyHeader,this.setFetchGraphQlModules(m.getConfig().fetchGraphQlModules)}setHeaderKey(e){this.headerKey=e}setFetchGraphQlModules(e){this.companyHeaderAppliers=[],this.companyHeaderRemovers=[],e.forEach(({setFetchGraphQlHeader:r,removeFetchGraphQlHeader:s})=>{this.companyHeaderAppliers.push(r),this.companyHeaderRemovers.push(s)})}setCompanyHeaders(e){if(e===null){this.removeCompanyHeaders();return}this.companyHeaderAppliers.forEach(r=>{r(this.headerKey,e)}),this.companyHeaderSet=!0}removeCompanyHeaders(){this.companyHeaderRemovers.forEach(e=>{e(this.headerKey)}),this.companyHeaderSet=!1}isCompanyHeaderSet(){return this.companyHeaderSet}}let u=null;const n=()=>(u||(u=new K),u);class I{constructor(){a(this,"groupHeaderSet",!1);a(this,"groupHeaderAppliers",[]);a(this,"groupHeaderRemovers",[]);a(this,"headerKey");this.headerKey=m.getConfig().customerGroupHeader,this.setFetchGraphQlModules(m.getConfig().groupGraphQlModules)}setHeaderKey(e){this.headerKey=e}setFetchGraphQlModules(e){e.forEach(({setFetchGraphQlHeader:r,removeFetchGraphQlHeader:s})=>{this.groupHeaderAppliers.push(r),this.groupHeaderRemovers.push(s)})}setGroupHeaders(e){this.removeGroupHeaders(),e!==null&&(this.groupHeaderAppliers.forEach(r=>{r(this.headerKey,e)}),this.groupHeaderSet=!0)}removeGroupHeaders(){this.groupHeaderRemovers.forEach(e=>{e(this.headerKey)}),this.groupHeaderSet=!1}isGroupHeaderSet(){return this.groupHeaderSet}}let y=null;const g=()=>(y||(y=new I),y),o=new G({init:async t=>{const e={fetchGraphQlModules:[],groupGraphQlModules:[],companyHeader:"X-Adobe-Company",customerGroupHeader:"Magento-Customer-Group",companySessionStorageKey:"DROPIN__COMPANYSWITCHER__COMPANY__CONTEXT",groupSessionStorageKey:"DROPIN__COMPANYSWITCHER__GROUP__CONTEXT"};o.config.setConfig({...e,...t});const r=sessionStorage.getItem(o.config.getConfig().groupSessionStorageKey),s=sessionStorage.getItem(o.config.getConfig().companySessionStorageKey);s&&!n().isCompanyHeaderSet()&&(n().setCompanyHeaders(s),p.emit("companyContext/restored",s)),r&&!g().isGroupHeaderSet()&&g().setGroupHeaders(r),p.on("authenticated",async i=>{if(!i)sessionStorage.removeItem(o.config.getConfig().companySessionStorageKey),sessionStorage.removeItem(o.config.getConfig().groupSessionStorageKey),n().removeCompanyHeaders(),g().removeGroupHeaders();else{if(sessionStorage.getItem(o.config.getConfig().companySessionStorageKey)||n().isCompanyHeaderSet())return;const c=await C();if(c.customerCompanies.length<2)return;const h=c.currentCompany.id,H=c.customerGroupId;n().setCompanyHeaders(h),g().setGroupHeaders(H),sessionStorage.setItem(o.config.getConfig().companySessionStorageKey,h),sessionStorage.setItem(o.config.getConfig().groupSessionStorageKey,H),p.emit("companyContext/restored",h)}},{eager:!0}),p.on("companyContext/changing",async i=>{n().setCompanyHeaders(i),sessionStorage.setItem(o.config.getConfig().companySessionStorageKey,i);const d=await S();d&&(g().setGroupHeaders(d),sessionStorage.setItem(o.config.getConfig().groupSessionStorageKey,d)),p.emit("companyContext/changed",i)},{eager:!0})},listeners:()=>[]}),m=o.config;export{F as CustomerCompanyContext,m as config,O as fetchGraphQl,n as getCompanyHeaderManager,x as getConfig,C as getCustomerCompanyInfo,g as getGroupHeaderManager,o as initialize,N as removeFetchGraphQlHeader,P as setEndpoint,T as setFetchGraphQlHeader,w as setFetchGraphQlHeaders,S as updateCustomerGroup};
3
+ import{C as o,c as p,f as n,e as i,g as m,d as g,h,i as C,r as d,s as u,a as c,b as f,u as G}from"./chunks/customerCompanyContext.js";import"@dropins/tools/lib.js";import"@dropins/tools/event-bus.js";import"@dropins/tools/fetch-graphql.js";export{o as CustomerCompanyContext,p as config,n as fetchGraphQl,i as getCompanyHeaderManager,m as getConfig,g as getCustomerCompanyInfo,h as getGroupHeaderManager,C as initialize,d as removeFetchGraphQlHeader,u as setEndpoint,c as setFetchGraphQlHeader,f as setFetchGraphQlHeaders,G as updateCustomerGroup};
4
4
  //# sourceMappingURL=api.js.map
package/api.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"api.js","sources":["/@dropins/storefront-company-switcher/src/api/setCompanyHeaders/setCompanyHeaders.ts","/@dropins/storefront-company-switcher/src/api/setGroupHeaders/setGroupHeaders.ts","/@dropins/storefront-company-switcher/src/api/initialize/initialize.ts"],"sourcesContent":["/********************************************************************\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: Adobe permits you to use, modify, and distribute this \n * file in accordance with the terms of the Adobe license agreement \n * accompanying it. \n *******************************************************************/\nimport { config } from '../initialize/initialize';\nimport { setFetchGraphQlHeader, removeFetchGraphQlHeader, FetchGraphQL } from '@adobe-commerce/fetch-graphql';\n\nclass CompanyHeaderManager {\n private companyHeaderSet: boolean = false;\n private companyHeaderAppliers: typeof setFetchGraphQlHeader[] = [];\n private companyHeaderRemovers: typeof removeFetchGraphQlHeader[] = [];\n private headerKey: string;\n\n constructor() {\n this.headerKey = config.getConfig().companyHeader;\n this.setFetchGraphQlModules(config.getConfig().fetchGraphQlModules);\n }\n\n public setHeaderKey(headerKey: string): void {\n this.headerKey = headerKey;\n }\n\n public setFetchGraphQlModules(modules: FetchGraphQL[]): void {\n this.companyHeaderAppliers = [];\n this.companyHeaderRemovers = [];\n modules.forEach(({ setFetchGraphQlHeader, removeFetchGraphQlHeader }) => {\n this.companyHeaderAppliers.push(setFetchGraphQlHeader);\n this.companyHeaderRemovers.push(removeFetchGraphQlHeader);\n });\n }\n\n public setCompanyHeaders(companyId: string | null): void {\n if (companyId === null) {\n this.removeCompanyHeaders();\n return;\n }\n this.companyHeaderAppliers.forEach((setFn) => {\n setFn(this.headerKey, companyId);\n });\n this.companyHeaderSet = true;\n }\n\n public removeCompanyHeaders(): void {\n this.companyHeaderRemovers.forEach((removeFn) => {\n removeFn(this.headerKey);\n });\n this.companyHeaderSet = false;\n }\n\n public isCompanyHeaderSet(): boolean {\n return this.companyHeaderSet;\n }\n}\n\nlet _companyHeaderManager: CompanyHeaderManager | null = null;\nexport const getCompanyHeaderManager = () => {\n if (!_companyHeaderManager) {\n _companyHeaderManager = new CompanyHeaderManager();\n }\n return _companyHeaderManager;\n};\n","/********************************************************************\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: Adobe permits you to use, modify, and distribute this \n * file in accordance with the terms of the Adobe license agreement \n * accompanying it. \n *******************************************************************/\nimport { config } from '../initialize/initialize';\nimport { setFetchGraphQlHeader, removeFetchGraphQlHeader, FetchGraphQL } from '@adobe-commerce/fetch-graphql';\n\nclass GroupHeaderManager {\n private groupHeaderSet: boolean = false;\n private groupHeaderAppliers: typeof setFetchGraphQlHeader[] = [];\n private groupHeaderRemovers: typeof removeFetchGraphQlHeader[] = [];\n private headerKey: string;\n\n constructor() {\n this.headerKey = config.getConfig().customerGroupHeader;\n this.setFetchGraphQlModules(config.getConfig().groupGraphQlModules);\n }\n\n public setHeaderKey(headerKey: string): void {\n this.headerKey = headerKey;\n }\n\n public setFetchGraphQlModules(modules: FetchGraphQL[]): void {\n modules.forEach(({ setFetchGraphQlHeader, removeFetchGraphQlHeader }) => {\n this.groupHeaderAppliers.push(setFetchGraphQlHeader);\n this.groupHeaderRemovers.push(removeFetchGraphQlHeader);\n });\n }\n\n public setGroupHeaders(groupId: string | null): void {\n this.removeGroupHeaders();\n if (groupId === null) {\n return;\n }\n this.groupHeaderAppliers.forEach((setFn) => {\n setFn(this.headerKey, groupId);\n });\n this.groupHeaderSet = true;\n }\n\n public removeGroupHeaders(): void {\n this.groupHeaderRemovers.forEach((removeFn) => {\n removeFn(this.headerKey);\n });\n this.groupHeaderSet = false;\n }\n\n public isGroupHeaderSet(): boolean {\n return this.groupHeaderSet;\n }\n}\n\nlet _groupHeaderManager: GroupHeaderManager | null = null;\nexport const getGroupHeaderManager = () => {\n if (!_groupHeaderManager) {\n _groupHeaderManager = new GroupHeaderManager();\n }\n return _groupHeaderManager;\n};\n","/********************************************************************\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: Adobe permits you to use, modify, and distribute this \n * file in accordance with the terms of the Adobe license agreement \n * accompanying it. \n *******************************************************************/\n\nimport { Initializer } from '@adobe-commerce/elsie/lib';\nimport { Lang } from '@adobe-commerce/elsie/i18n';\nimport { FetchGraphQL } from '@adobe-commerce/fetch-graphql';\nimport { getCompanyHeaderManager } from '../setCompanyHeaders/setCompanyHeaders';\nimport { getGroupHeaderManager } from '../setGroupHeaders/setGroupHeaders';\nimport { updateCustomerGroup, getCustomerCompanyInfo } from '../customerCompanyContext/customerCompanyContext';\nimport { events } from '@adobe-commerce/event-bus';\n\ntype ConfigProps = {\n langDefinitions?: Lang;\n companyHeader: string;\n customerGroupHeader: string;\n companySessionStorageKey: string;\n groupSessionStorageKey: string;\n fetchGraphQlModules: FetchGraphQL[];\n groupGraphQlModules: FetchGraphQL[];\n};\n\nexport const initialize = new Initializer<ConfigProps>({\n init: async (config) => {\n const defaultConfig = {\n fetchGraphQlModules: [],\n groupGraphQlModules: [],\n companyHeader: 'X-Adobe-Company',\n customerGroupHeader: 'Magento-Customer-Group',\n companySessionStorageKey: 'DROPIN__COMPANYSWITCHER__COMPANY__CONTEXT',\n groupSessionStorageKey: 'DROPIN__COMPANYSWITCHER__GROUP__CONTEXT'\n };\n initialize.config.setConfig({ ...defaultConfig, ...config });\n \n const groupId = sessionStorage.getItem(initialize.config.getConfig().groupSessionStorageKey);\n const companyId = sessionStorage.getItem(initialize.config.getConfig().companySessionStorageKey);\n if (companyId && !getCompanyHeaderManager().isCompanyHeaderSet()) {\n getCompanyHeaderManager().setCompanyHeaders(companyId);\n events.emit('companyContext/restored', companyId);\n }\n if (groupId && !getGroupHeaderManager().isGroupHeaderSet()) {\n getGroupHeaderManager().setGroupHeaders(groupId);\n }\n\n events.on('authenticated', async (authenticated: boolean) => {\n if (!authenticated) {\n sessionStorage.removeItem(initialize.config.getConfig().companySessionStorageKey);\n sessionStorage.removeItem(initialize.config.getConfig().groupSessionStorageKey);\n getCompanyHeaderManager().removeCompanyHeaders();\n getGroupHeaderManager().removeGroupHeaders();\n } else {\n const storedCompanyId = sessionStorage.getItem(initialize.config.getConfig().companySessionStorageKey);\n if (storedCompanyId || getCompanyHeaderManager().isCompanyHeaderSet()) {\n return;\n }\n const companyInfo = await getCustomerCompanyInfo();\n if (companyInfo.customerCompanies.length < 2) {\n return;\n }\n\n const currentCompanyId = companyInfo.currentCompany.id;\n const groupId = companyInfo.customerGroupId;\n getCompanyHeaderManager().setCompanyHeaders(currentCompanyId);\n getGroupHeaderManager().setGroupHeaders(groupId);\n sessionStorage.setItem(initialize.config.getConfig().companySessionStorageKey, currentCompanyId);\n sessionStorage.setItem(initialize.config.getConfig().groupSessionStorageKey, groupId);\n events.emit('companyContext/restored', currentCompanyId);\n }\n }, { eager: true });\n\n events.on('companyContext/changing', async (companyId: string) => {\n getCompanyHeaderManager().setCompanyHeaders(companyId);\n sessionStorage.setItem(initialize.config.getConfig().companySessionStorageKey, companyId);\n\n const groupId = await updateCustomerGroup();\n if (groupId) {\n getGroupHeaderManager().setGroupHeaders(groupId);\n sessionStorage.setItem(initialize.config.getConfig().groupSessionStorageKey, groupId);\n }\n events.emit('companyContext/changed', companyId);\n }, { eager: true });\n },\n listeners: () => [\n \n ],\n});\n\nexport const config = initialize.config;\n"],"names":["CompanyHeaderManager","__publicField","config","headerKey","modules","setFetchGraphQlHeader","removeFetchGraphQlHeader","companyId","setFn","removeFn","_companyHeaderManager","getCompanyHeaderManager","GroupHeaderManager","groupId","_groupHeaderManager","getGroupHeaderManager","initialize","Initializer","defaultConfig","events","authenticated","companyInfo","getCustomerCompanyInfo","currentCompanyId","updateCustomerGroup"],"mappings":"odAWA,MAAMA,CAAqB,CAMzB,aAAc,CALNC,EAAA,wBAA4B,IAC5BA,EAAA,6BAAwD,CAAA,GACxDA,EAAA,6BAA2D,CAAA,GAC3DA,EAAA,kBAGN,KAAK,UAAYC,EAAO,UAAA,EAAY,cACpC,KAAK,uBAAuBA,EAAO,UAAA,EAAY,mBAAmB,CACpE,CAEO,aAAaC,EAAyB,CAC3C,KAAK,UAAYA,CACnB,CAEO,uBAAuBC,EAA+B,CAC3D,KAAK,sBAAwB,CAAA,EAC7B,KAAK,sBAAwB,CAAA,EAC7BA,EAAQ,QAAQ,CAAC,CAAE,sBAAAC,EAAuB,yBAAAC,KAA+B,CACvE,KAAK,sBAAsB,KAAKD,CAAqB,EACrD,KAAK,sBAAsB,KAAKC,CAAwB,CAC1D,CAAC,CACH,CAEO,kBAAkBC,EAAgC,CACvD,GAAIA,IAAc,KAAM,CACtB,KAAK,qBAAA,EACL,MACF,CACA,KAAK,sBAAsB,QAASC,GAAU,CAC5CA,EAAM,KAAK,UAAWD,CAAS,CACjC,CAAC,EACD,KAAK,iBAAmB,EAC1B,CAEO,sBAA6B,CAClC,KAAK,sBAAsB,QAASE,GAAa,CAC/CA,EAAS,KAAK,SAAS,CACzB,CAAC,EACD,KAAK,iBAAmB,EAC1B,CAEO,oBAA8B,CACnC,OAAO,KAAK,gBACd,CAC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BAA0BZ,CAAS,CACjD,EAAG,CAAE,MAAO,GAAM,CACpB,EACA,UAAW,IAAM,CAAA,CAGnB,CAAC,EAEYL,EAASc,EAAW"}
1
+ {"version":3,"file":"api.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
@@ -1,6 +1,6 @@
1
1
  /*! Copyright 2025 Adobe
2
2
  All Rights Reserved. */
3
- var i=Object.defineProperty;var h=(s,t,e)=>t in s?i(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var o=(s,t,e)=>h(s,typeof t!="symbol"?t+"":t,e);import{FetchGraphQL as p}from"@dropins/tools/fetch-graphql.js";const{setEndpoint:E,setFetchGraphQlHeader:O,removeFetchGraphQlHeader:f,setFetchGraphQlHeaders:l,fetchGraphQl:u,getConfig:m}=new p().getMethods(),d=`
3
+ var G=Object.defineProperty;var S=(s,e,r)=>e in s?G(s,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):s[e]=r;var t=(s,e,r)=>S(s,typeof e!="symbol"?e+"":e,r);import{Initializer as M}from"@dropins/tools/lib.js";import{events as u}from"@dropins/tools/event-bus.js";import{FetchGraphQL as T}from"@dropins/tools/fetch-graphql.js";class E{constructor(){t(this,"companyHeaderSet",!1);t(this,"companyHeaderAppliers",[]);t(this,"companyHeaderRemovers",[]);t(this,"headerKey");this.headerKey=h.getConfig().companyHeader,this.setFetchGraphQlModules(h.getConfig().fetchGraphQlModules)}setHeaderKey(e){this.headerKey=e}setFetchGraphQlModules(e){this.companyHeaderAppliers=[],this.companyHeaderRemovers=[],e.forEach(({setFetchGraphQlHeader:r,removeFetchGraphQlHeader:o})=>{this.companyHeaderAppliers.push(r),this.companyHeaderRemovers.push(o)})}setCompanyHeaders(e){if(e===null){this.removeCompanyHeaders();return}this.companyHeaderAppliers.forEach(r=>{r(this.headerKey,e)}),this.companyHeaderSet=!0}removeCompanyHeaders(){this.companyHeaderRemovers.forEach(e=>{e(this.headerKey)}),this.companyHeaderSet=!1}isCompanyHeaderSet(){return this.companyHeaderSet}}let l=null;const c=()=>(l||(l=new E),l);class I{constructor(){t(this,"groupHeaderSet",!1);t(this,"groupHeaderAppliers",[]);t(this,"groupHeaderRemovers",[]);t(this,"headerKey");this.headerKey=h.getConfig().customerGroupHeader,this.setFetchGraphQlModules(h.getConfig().groupGraphQlModules)}setHeaderKey(e){this.headerKey=e}setFetchGraphQlModules(e){e.forEach(({setFetchGraphQlHeader:r,removeFetchGraphQlHeader:o})=>{this.groupHeaderAppliers.push(r),this.groupHeaderRemovers.push(o)})}setGroupHeaders(e){this.removeGroupHeaders(),e!==null&&(this.groupHeaderAppliers.forEach(r=>{r(this.headerKey,e)}),this.groupHeaderSet=!0)}removeGroupHeaders(){this.groupHeaderRemovers.forEach(e=>{e(this.headerKey)}),this.groupHeaderSet=!1}isGroupHeaderSet(){return this.groupHeaderSet}}let C=null;const d=()=>(C||(C=new I),C),p=new M({init:async s=>{const e={fetchGraphQlModules:[],groupGraphQlModules:[],companyHeader:"X-Adobe-Company",customerGroupHeader:"Magento-Customer-Group",companySessionStorageKey:"DROPIN__COMPANYSWITCHER__COMPANY__CONTEXT",groupSessionStorageKey:"DROPIN__COMPANYSWITCHER__GROUP__CONTEXT"};p.config.setConfig({...e,...s});const r=sessionStorage.getItem(p.config.getConfig().groupSessionStorageKey),o=sessionStorage.getItem(p.config.getConfig().companySessionStorageKey);o&&!c().isCompanyHeaderSet()&&(c().setCompanyHeaders(o),u.emit("companyContext/changed",o)),r&&!d().isGroupHeaderSet()&&d().setGroupHeaders(r),u.on("authenticated",async a=>{const i=p.config.getConfig();if(!a)sessionStorage.removeItem(i.companySessionStorageKey),sessionStorage.removeItem(i.groupSessionStorageKey),c().removeCompanyHeaders(),d().removeGroupHeaders(),u.emit("companyContext/changed",null);else{if(sessionStorage.getItem(i.companySessionStorageKey)||c().isCompanyHeaderSet())return;const g=await R();if(g.customerCompanies.length<2)return;const y=g.currentCompany.id,H=g.customerGroupId;c().setCompanyHeaders(y),d().setGroupHeaders(H),sessionStorage.setItem(i.companySessionStorageKey,y),sessionStorage.setItem(i.groupSessionStorageKey,H),u.emit("companyContext/changed",y)}},{eager:!0})},listeners:()=>[]}),h=p.config,{setEndpoint:U,setFetchGraphQlHeader:w,removeFetchGraphQlHeader:F,setFetchGraphQlHeaders:Y,fetchGraphQl:f,getConfig:O}=new T().getMethods(),_=`
4
4
  query GET_CUSTOMER_COMPANIES {
5
5
  customer {
6
6
  companies {
@@ -18,11 +18,11 @@ var i=Object.defineProperty;var h=(s,t,e)=>t in s?i(s,t,{enumerable:!0,configura
18
18
  uid
19
19
  }
20
20
  }
21
- `,C=`
21
+ `,A=`
22
22
  query GET_CUSTOMER_GROUP {
23
23
  customerGroup {
24
24
  uid
25
25
  }
26
26
  }
27
- `,r=class r{constructor(){o(this,"EMPTY_CUSTOMER_COMPANY_CONTEXT",{currentCompany:{id:"",name:""},customerCompanies:[],customerGroupId:""});o(this,"cache",null);o(this,"transformCompanyToOption",t=>({text:t.name,value:t.id}))}static getInstance(){return r.instance??(r.instance=new r)}async processCustomerGroupId(t){const e=Uint8Array.from(atob(t),a=>a.charCodeAt(0)),n=await crypto.subtle.digest("SHA-1",e);return Array.from(new Uint8Array(n)).map(a=>a.toString(16).padStart(2,"0")).join("")}isUserAuthenticated(){var t;return!!((t=m().fetchGraphQlHeaders)!=null&&t.Authorization)}resetCache(){this.cache=null}async updateCustomerGroup(){if(!this.isUserAuthenticated())return null;try{const t=await u(C);if(t.errors)return null;const e=await this.processCustomerGroupId(t.data.customerGroup.uid);return this.cache&&(this.cache.customerGroupId=e),e}catch(t){return console.error(t),null}}async getCustomerCompanyInfo(){if(this.cache)return this.cache;if(!this.isUserAuthenticated())return this.EMPTY_CUSTOMER_COMPANY_CONTEXT;try{const t=await u(d);if(t.errors)return this.EMPTY_CUSTOMER_COMPANY_CONTEXT;const e=t.data,n=await this.processCustomerGroupId(t.data.customerGroup.uid),a=e.customer.companies.items.map(this.transformCompanyToOption);return this.cache={currentCompany:e.company,customerCompanies:a,customerGroupId:n},this.cache}catch{return this.EMPTY_CUSTOMER_COMPANY_CONTEXT}}};o(r,"instance");let c=r;const M=()=>c.getInstance().getCustomerCompanyInfo(),_=()=>c.getInstance().updateCustomerGroup();export{c as C,O as a,l as b,m as c,u as f,M as g,f as r,E as s,_ as u};
27
+ `,n=class n{constructor(){t(this,"EMPTY_CUSTOMER_COMPANY_CONTEXT",{currentCompany:{id:"",name:""},customerCompanies:[],customerGroupId:""});t(this,"cache",null);t(this,"transformCompanyToOption",e=>({text:e.name,value:e.id}))}static getInstance(){return n.instance??(n.instance=new n)}async processCustomerGroupId(e){const r=Uint8Array.from(atob(e),a=>a.charCodeAt(0)),o=await crypto.subtle.digest("SHA-1",r);return Array.from(new Uint8Array(o)).map(a=>a.toString(16).padStart(2,"0")).join("")}isUserAuthenticated(){var e;return!!((e=O().fetchGraphQlHeaders)!=null&&e.Authorization)}resetCache(){this.cache=null}async updateCustomerGroup(){if(!this.isUserAuthenticated())return null;try{const e=await f(A);if(e.errors)return null;const r=await this.processCustomerGroupId(e.data.customerGroup.uid);return this.cache&&(this.cache.customerGroupId=r),r}catch(e){return console.error(e),null}}async getCustomerCompanyInfo(){if(this.cache)return this.cache;if(!this.isUserAuthenticated())return this.EMPTY_CUSTOMER_COMPANY_CONTEXT;try{const e=await f(_);if(e.errors)return this.EMPTY_CUSTOMER_COMPANY_CONTEXT;const r=e.data,o=await this.processCustomerGroupId(e.data.customerGroup.uid),a=r.customer.companies.items.map(this.transformCompanyToOption);return this.cache={currentCompany:r.company,customerCompanies:a,customerGroupId:o},this.cache}catch(e){return console.error(e),this.EMPTY_CUSTOMER_COMPANY_CONTEXT}}};t(n,"instance");let m=n;const R=()=>m.getInstance().getCustomerCompanyInfo(),X=()=>m.getInstance().updateCustomerGroup();export{m as C,w as a,Y as b,h as c,R as d,c as e,f,O as g,d as h,p as i,F as r,U as s,X as u};
28
28
  //# sourceMappingURL=customerCompanyContext.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"customerCompanyContext.js","sources":["/@dropins/storefront-company-switcher/src/api/fetch-graphql/fetch-graphql.ts","/@dropins/storefront-company-switcher/src/api/customerCompanyContext/graphql/customerCompanyContext.graphql.ts","/@dropins/storefront-company-switcher/src/api/customerCompanyContext/graphql/customerGroupContext.graphql.ts","/@dropins/storefront-company-switcher/src/api/customerCompanyContext/customerCompanyContext.ts"],"sourcesContent":["import { FetchGraphQL } from '@adobe-commerce/fetch-graphql';\n\nexport const {\n setEndpoint,\n setFetchGraphQlHeader,\n removeFetchGraphQlHeader,\n setFetchGraphQlHeaders,\n fetchGraphQl,\n getConfig,\n} = new FetchGraphQL().getMethods();\n","/********************************************************************\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: Adobe permits you to use, modify, and distribute this \n * file in accordance with the terms of the Adobe license agreement \n * accompanying it. \n *******************************************************************/\n\nexport const GET_CUSTOMER_COMPANY_CONTEXT = `\n query GET_CUSTOMER_COMPANIES {\n customer {\n companies {\n items {\n name\n id\n }\n }\n }\n company {\n name\n id\n }\n customerGroup {\n uid\n }\n }\n`;\n","/********************************************************************\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: Adobe permits you to use, modify, and distribute this \n * file in accordance with the terms of the Adobe license agreement \n * accompanying it. \n *******************************************************************/\n\nexport const GET_CUSTOMER_GROUP_CONTEXT = `\n query GET_CUSTOMER_GROUP {\n customerGroup {\n uid\n }\n }\n`;\n","/********************************************************************\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: Adobe permits you to use, modify, and distribute this \n * file in accordance with the terms of the Adobe license agreement \n * accompanying it. \n *******************************************************************/\n\nimport { fetchGraphQl, getConfig } from \"@/company-switcher/api\";\nimport type { Company, CompanyOption, CustomerCompanyInfo, GraphQLResponse } from '@/company-switcher/types/company';\nimport { GET_CUSTOMER_COMPANY_CONTEXT } from './graphql/customerCompanyContext.graphql';\nimport { GET_CUSTOMER_GROUP_CONTEXT } from './graphql/customerGroupContext.graphql';\n\nexport class CustomerCompanyContext {\n private static instance: CustomerCompanyContext;\n\n // Constants\n private readonly EMPTY_CUSTOMER_COMPANY_CONTEXT: CustomerCompanyInfo = {\n currentCompany: { id: '', name: '' },\n customerCompanies: [],\n customerGroupId: '',\n };\n\n private cache: CustomerCompanyInfo | null = null;\n\n /**\n * Get singleton instance\n */\n static getInstance(): CustomerCompanyContext {\n return CustomerCompanyContext.instance ??= new CustomerCompanyContext();\n }\n\n /**\n * Transforms a company object into a company option for UI components\n */\n private transformCompanyToOption = (company: Company): CompanyOption => ({\n text: company.name,\n value: company.id\n });\n\n /**\n * Decodes base64 string and returns SHA1 hash\n */\n private async processCustomerGroupId(base64String: string): Promise<string> {\n const decoded = Uint8Array.from(atob(base64String), c => c.charCodeAt(0));\n const hashBuffer = await crypto.subtle.digest('SHA-1', decoded);\n return Array.from(new Uint8Array(hashBuffer)).map(b => b.toString(16).padStart(2, '0')).join('');\n }\n\n /**\n * Checks if the user is authenticated by verifying the Authorization header\n */\n private isUserAuthenticated(): boolean {\n return Boolean(getConfig().fetchGraphQlHeaders?.Authorization);\n }\n\n resetCache(): void {\n this.cache = null;\n }\n\n /**\n * Fetches and updates only the customer group information in the cache\n * \n * @returns Promise containing the updated customer group ID\n * @throws Will not throw errors - returns null on failure\n */\n async updateCustomerGroup(): Promise<string | null> {\n if (!this.isUserAuthenticated()) {\n return null;\n }\n\n try {\n const response = await fetchGraphQl<{ customerGroup: { uid: string } }>(GET_CUSTOMER_GROUP_CONTEXT);\n if (response.errors) {\n return null;\n }\n const customerGroupId = await this.processCustomerGroupId(response.data.customerGroup.uid);\n if (this.cache) {\n this.cache.customerGroupId = customerGroupId;\n }\n return customerGroupId;\n } catch (e) {\n console.error(e)\n return null;\n }\n }\n\n /**\n * Fetches customer company information including the current company and all available companies\n * \n * @returns Promise containing current company and list of available companies\n * @throws Will not throw errors - returns empty data on failure\n */\n async getCustomerCompanyInfo(): Promise<CustomerCompanyInfo> {\n // Return cached data if available\n if (this.cache) {\n return this.cache;\n }\n \n // Return empty data if user is not authenticated\n if (!this.isUserAuthenticated()) {\n return this.EMPTY_CUSTOMER_COMPANY_CONTEXT;\n }\n\n try {\n // Fetch company data from GraphQL API\n const response = (await fetchGraphQl<GraphQLResponse>(GET_CUSTOMER_COMPANY_CONTEXT));\n if (response.errors) {\n return this.EMPTY_CUSTOMER_COMPANY_CONTEXT;\n }\n\n const data = response.data;\n const customerGroup = await this.processCustomerGroupId(response.data.customerGroup.uid);\n const customerCompanies = data.customer.companies.items.map(this.transformCompanyToOption);\n\n this.cache = {\n currentCompany: data.company,\n customerCompanies,\n customerGroupId: customerGroup\n }\n return this.cache;\n } catch (e) {\n return this.EMPTY_CUSTOMER_COMPANY_CONTEXT;\n }\n }\n}\n\nexport const getCustomerCompanyInfo = (): Promise<CustomerCompanyInfo> => {\n return CustomerCompanyContext.getInstance().getCustomerCompanyInfo();\n};\n\nexport const updateCustomerGroup = (): Promise<string | null> => {\n return CustomerCompanyContext.getInstance().updateCustomerGroup();\n};"],"names":["setEndpoint","setFetchGraphQlHeader","removeFetchGraphQlHeader","setFetchGraphQlHeaders","fetchGraphQl","getConfig","FetchGraphQL","GET_CUSTOMER_COMPANY_CONTEXT","GET_CUSTOMER_GROUP_CONTEXT","_CustomerCompanyContext","__publicField","company","base64String","decoded","c","hashBuffer","b","_a","response","customerGroupId","e","data","customerGroup","customerCompanies","CustomerCompanyContext","getCustomerCompanyInfo","updateCustomerGroup"],"mappings":"mOAEO,KAAM,CACX,YAAAA,EACA,sBAAAC,EACA,yBAAAC,EACA,uBAAAC,EACA,aAAAC,EACA,UAAAC,CACF,EAAI,IAAIC,EAAA,EAAe,WAAA,ECAVC,EAA+B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,ECA/BC,EAA6B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,ECK7BC,EAAN,MAAMA,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AAOH,EAAS,KAChBI,EAAgB,MAAM,KAAK,uBAAuBJ,EAAS,KAAK,cAAc,GAAG,EACjFK,EAAoBF,EAAK,SAAS,UAAU,MAAM,IAAI,KAAK,wBAAwB,EAEzF,YAAK,MAAQ,CACX,eAAgBA,EAAK,QACrB,kBAAAE,EACA,gBAAiBD,CAAA,EAEZ,KAAK,KACd,MAAY,CACV,OAAO,KAAK,8BACd,CACF,CACF,EA/GEZ,EADWD,EACI,YADV,IAAMe,EAANf,EAkHA,MAAMgB,EAAyB,IAC7BD,EAAuB,YAAA,EAAc,uBAAA,EAGjCE,EAAsB,IAC1BF,EAAuB,YAAA,EAAc,oBAAA"}
1
+ {"version":3,"file":"customerCompanyContext.js","sources":["/@dropins/storefront-company-switcher/src/api/setCompanyHeaders/setCompanyHeaders.ts","/@dropins/storefront-company-switcher/src/api/setGroupHeaders/setGroupHeaders.ts","/@dropins/storefront-company-switcher/src/api/initialize/initialize.ts","/@dropins/storefront-company-switcher/src/api/fetch-graphql/fetch-graphql.ts","/@dropins/storefront-company-switcher/src/api/customerCompanyContext/graphql/customerCompanyContext.graphql.ts","/@dropins/storefront-company-switcher/src/api/customerCompanyContext/graphql/customerGroupContext.graphql.ts","/@dropins/storefront-company-switcher/src/api/customerCompanyContext/customerCompanyContext.ts"],"sourcesContent":["/********************************************************************\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: Adobe permits you to use, modify, and distribute this \n * file in accordance with the terms of the Adobe license agreement \n * accompanying it. \n *******************************************************************/\nimport { config } from '../initialize/initialize';\nimport { setFetchGraphQlHeader, removeFetchGraphQlHeader, FetchGraphQL } from '@adobe-commerce/fetch-graphql';\n\nclass CompanyHeaderManager {\n private companyHeaderSet: boolean = false;\n private companyHeaderAppliers: typeof setFetchGraphQlHeader[] = [];\n private companyHeaderRemovers: typeof removeFetchGraphQlHeader[] = [];\n private headerKey: string;\n\n constructor() {\n this.headerKey = config.getConfig().companyHeader;\n this.setFetchGraphQlModules(config.getConfig().fetchGraphQlModules);\n }\n\n public setHeaderKey(headerKey: string): void {\n this.headerKey = headerKey;\n }\n\n public setFetchGraphQlModules(modules: FetchGraphQL[]): void {\n this.companyHeaderAppliers = [];\n this.companyHeaderRemovers = [];\n modules.forEach(({ setFetchGraphQlHeader, removeFetchGraphQlHeader }) => {\n this.companyHeaderAppliers.push(setFetchGraphQlHeader);\n this.companyHeaderRemovers.push(removeFetchGraphQlHeader);\n });\n }\n\n public setCompanyHeaders(companyId: string | null): void {\n if (companyId === null) {\n this.removeCompanyHeaders();\n return;\n }\n this.companyHeaderAppliers.forEach((setFn) => {\n setFn(this.headerKey, companyId);\n });\n this.companyHeaderSet = true;\n }\n\n public removeCompanyHeaders(): void {\n this.companyHeaderRemovers.forEach((removeFn) => {\n removeFn(this.headerKey);\n });\n this.companyHeaderSet = false;\n }\n\n public isCompanyHeaderSet(): boolean {\n return this.companyHeaderSet;\n }\n}\n\nlet _companyHeaderManager: CompanyHeaderManager | null = null;\nexport const getCompanyHeaderManager = () => {\n if (!_companyHeaderManager) {\n _companyHeaderManager = new CompanyHeaderManager();\n }\n return _companyHeaderManager;\n};\n","/********************************************************************\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: Adobe permits you to use, modify, and distribute this \n * file in accordance with the terms of the Adobe license agreement \n * accompanying it. \n *******************************************************************/\nimport { config } from '../initialize/initialize';\nimport { setFetchGraphQlHeader, removeFetchGraphQlHeader, FetchGraphQL } from '@adobe-commerce/fetch-graphql';\n\nclass GroupHeaderManager {\n private groupHeaderSet: boolean = false;\n private groupHeaderAppliers: typeof setFetchGraphQlHeader[] = [];\n private groupHeaderRemovers: typeof removeFetchGraphQlHeader[] = [];\n private headerKey: string;\n\n constructor() {\n this.headerKey = config.getConfig().customerGroupHeader;\n this.setFetchGraphQlModules(config.getConfig().groupGraphQlModules);\n }\n\n public setHeaderKey(headerKey: string): void {\n this.headerKey = headerKey;\n }\n\n public setFetchGraphQlModules(modules: FetchGraphQL[]): void {\n modules.forEach(({ setFetchGraphQlHeader, removeFetchGraphQlHeader }) => {\n this.groupHeaderAppliers.push(setFetchGraphQlHeader);\n this.groupHeaderRemovers.push(removeFetchGraphQlHeader);\n });\n }\n\n public setGroupHeaders(groupId: string | null): void {\n this.removeGroupHeaders();\n if (groupId === null) {\n return;\n }\n this.groupHeaderAppliers.forEach((setFn) => {\n setFn(this.headerKey, groupId);\n });\n this.groupHeaderSet = true;\n }\n\n public removeGroupHeaders(): void {\n this.groupHeaderRemovers.forEach((removeFn) => {\n removeFn(this.headerKey);\n });\n this.groupHeaderSet = false;\n }\n\n public isGroupHeaderSet(): boolean {\n return this.groupHeaderSet;\n }\n}\n\nlet _groupHeaderManager: GroupHeaderManager | null = null;\nexport const getGroupHeaderManager = () => {\n if (!_groupHeaderManager) {\n _groupHeaderManager = new GroupHeaderManager();\n }\n return _groupHeaderManager;\n};\n","/********************************************************************\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: Adobe permits you to use, modify, and distribute this \n * file in accordance with the terms of the Adobe license agreement \n * accompanying it. \n *******************************************************************/\n\nimport { Initializer } from '@adobe-commerce/elsie/lib';\nimport { Lang } from '@adobe-commerce/elsie/i18n';\nimport { FetchGraphQL } from '@adobe-commerce/fetch-graphql';\nimport { getCompanyHeaderManager } from '../setCompanyHeaders/setCompanyHeaders';\nimport { getGroupHeaderManager } from '../setGroupHeaders/setGroupHeaders';\nimport { getCustomerCompanyInfo } from '../customerCompanyContext/customerCompanyContext';\nimport { events } from '@adobe-commerce/event-bus';\n\ntype ConfigProps = {\n langDefinitions?: Lang;\n companyHeader: string;\n customerGroupHeader: string;\n companySessionStorageKey: string;\n groupSessionStorageKey: string;\n fetchGraphQlModules: FetchGraphQL[];\n groupGraphQlModules: FetchGraphQL[];\n};\n\nexport const initialize = new Initializer<ConfigProps>({\n init: async (config) => {\n const defaultConfig = {\n fetchGraphQlModules: [],\n groupGraphQlModules: [],\n companyHeader: 'X-Adobe-Company',\n customerGroupHeader: 'Magento-Customer-Group',\n companySessionStorageKey: 'DROPIN__COMPANYSWITCHER__COMPANY__CONTEXT',\n groupSessionStorageKey: 'DROPIN__COMPANYSWITCHER__GROUP__CONTEXT'\n };\n initialize.config.setConfig({ ...defaultConfig, ...config });\n \n const groupId = sessionStorage.getItem(initialize.config.getConfig().groupSessionStorageKey);\n const companyId = sessionStorage.getItem(initialize.config.getConfig().companySessionStorageKey);\n if (companyId && !getCompanyHeaderManager().isCompanyHeaderSet()) {\n getCompanyHeaderManager().setCompanyHeaders(companyId);\n events.emit('companyContext/changed', companyId);\n }\n if (groupId && !getGroupHeaderManager().isGroupHeaderSet()) {\n getGroupHeaderManager().setGroupHeaders(groupId);\n }\n\n events.on('authenticated', async (authenticated: boolean) => {\n const config = initialize.config.getConfig();\n if (!authenticated) {\n sessionStorage.removeItem(config.companySessionStorageKey);\n sessionStorage.removeItem(config.groupSessionStorageKey);\n getCompanyHeaderManager().removeCompanyHeaders();\n getGroupHeaderManager().removeGroupHeaders();\n events.emit('companyContext/changed', null);\n } else {\n const storedCompanyId = sessionStorage.getItem(config.companySessionStorageKey);\n if (storedCompanyId || getCompanyHeaderManager().isCompanyHeaderSet()) {\n return;\n }\n const companyInfo = await getCustomerCompanyInfo();\n if (companyInfo.customerCompanies.length < 2) {\n return;\n }\n\n const currentCompanyId = companyInfo.currentCompany.id;\n const groupId = companyInfo.customerGroupId;\n getCompanyHeaderManager().setCompanyHeaders(currentCompanyId);\n getGroupHeaderManager().setGroupHeaders(groupId);\n sessionStorage.setItem(config.companySessionStorageKey, currentCompanyId);\n sessionStorage.setItem(config.groupSessionStorageKey, groupId);\n events.emit('companyContext/changed', currentCompanyId);\n }\n }, { eager: true })\n },\n listeners: () => [\n ],\n});\n\nexport const config = initialize.config;\n","import { FetchGraphQL } from '@adobe-commerce/fetch-graphql';\n\nexport const {\n setEndpoint,\n setFetchGraphQlHeader,\n removeFetchGraphQlHeader,\n setFetchGraphQlHeaders,\n fetchGraphQl,\n getConfig,\n} = new FetchGraphQL().getMethods();\n","/********************************************************************\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: Adobe permits you to use, modify, and distribute this \n * file in accordance with the terms of the Adobe license agreement \n * accompanying it. \n *******************************************************************/\n\nexport const GET_CUSTOMER_COMPANY_CONTEXT = `\n query GET_CUSTOMER_COMPANIES {\n customer {\n companies {\n items {\n name\n id\n }\n }\n }\n company {\n name\n id\n }\n customerGroup {\n uid\n }\n }\n`;\n","/********************************************************************\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: Adobe permits you to use, modify, and distribute this \n * file in accordance with the terms of the Adobe license agreement \n * accompanying it. \n *******************************************************************/\n\nexport const GET_CUSTOMER_GROUP_CONTEXT = `\n query GET_CUSTOMER_GROUP {\n customerGroup {\n uid\n }\n }\n`;\n","/********************************************************************\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: Adobe permits you to use, modify, and distribute this \n * file in accordance with the terms of the Adobe license agreement \n * accompanying it. \n *******************************************************************/\n\nimport { fetchGraphQl, getConfig } from \"@/company-switcher/api\";\nimport type { Company, CompanyOption, CustomerCompanyInfo, GraphQLResponse } from '@/company-switcher/types/company';\nimport { GET_CUSTOMER_COMPANY_CONTEXT } from './graphql/customerCompanyContext.graphql';\nimport { GET_CUSTOMER_GROUP_CONTEXT } from './graphql/customerGroupContext.graphql';\n\nexport class CustomerCompanyContext {\n private static instance: CustomerCompanyContext;\n\n // Constants\n private readonly EMPTY_CUSTOMER_COMPANY_CONTEXT: CustomerCompanyInfo = {\n currentCompany: { id: '', name: '' },\n customerCompanies: [],\n customerGroupId: '',\n };\n\n private cache: CustomerCompanyInfo | null = null;\n\n /**\n * Get singleton instance\n */\n static getInstance(): CustomerCompanyContext {\n return CustomerCompanyContext.instance ??= new CustomerCompanyContext();\n }\n\n /**\n * Transforms a company object into a company option for UI components\n */\n private transformCompanyToOption = (company: Company): CompanyOption => ({\n text: company.name,\n value: company.id\n });\n\n /**\n * Decodes base64 string and returns SHA1 hash\n */\n private async processCustomerGroupId(base64String: string): Promise<string> {\n const decoded = Uint8Array.from(atob(base64String), c => c.charCodeAt(0));\n const hashBuffer = await crypto.subtle.digest('SHA-1', decoded);\n return Array.from(new Uint8Array(hashBuffer)).map(b => b.toString(16).padStart(2, '0')).join('');\n }\n\n /**\n * Checks if the user is authenticated by verifying the Authorization header\n */\n private isUserAuthenticated(): boolean {\n return Boolean(getConfig().fetchGraphQlHeaders?.Authorization);\n }\n\n resetCache(): void {\n this.cache = null;\n }\n\n /**\n * Fetches and updates only the customer group information in the cache\n * \n * @returns Promise containing the updated customer group ID\n * @throws Will not throw errors - returns null on failure\n */\n async updateCustomerGroup(): Promise<string | null> {\n if (!this.isUserAuthenticated()) {\n return null;\n }\n\n try {\n const response = await fetchGraphQl<{ customerGroup: { uid: string } }>(GET_CUSTOMER_GROUP_CONTEXT);\n if (response.errors) {\n return null;\n }\n const customerGroupId = await this.processCustomerGroupId(response.data.customerGroup.uid);\n if (this.cache) {\n this.cache.customerGroupId = customerGroupId;\n }\n return customerGroupId;\n } catch (e) {\n console.error(e)\n return null;\n }\n }\n\n /**\n * Fetches customer company information including the current company and all available companies\n * \n * @returns Promise containing current company and list of available companies\n * @throws Will not throw errors - returns empty data on failure\n */\n async getCustomerCompanyInfo(): Promise<CustomerCompanyInfo> {\n // Return cached data if available\n if (this.cache) {\n return this.cache;\n }\n \n // Return empty data if user is not authenticated\n if (!this.isUserAuthenticated()) {\n return this.EMPTY_CUSTOMER_COMPANY_CONTEXT;\n }\n\n try {\n // Fetch company data from GraphQL API\n const response = (await fetchGraphQl<GraphQLResponse>(GET_CUSTOMER_COMPANY_CONTEXT));\n if (response.errors) {\n return this.EMPTY_CUSTOMER_COMPANY_CONTEXT;\n }\n\n const data = response.data;\n const customerGroup = await this.processCustomerGroupId(response.data.customerGroup.uid);\n const customerCompanies = data.customer.companies.items.map(this.transformCompanyToOption);\n\n this.cache = {\n currentCompany: data.company,\n customerCompanies,\n customerGroupId: customerGroup\n }\n return this.cache;\n } catch (e) {\n console.error(e);\n return this.EMPTY_CUSTOMER_COMPANY_CONTEXT;\n }\n }\n}\n\nexport const getCustomerCompanyInfo = (): Promise<CustomerCompanyInfo> => {\n return CustomerCompanyContext.getInstance().getCustomerCompanyInfo();\n};\n\nexport const updateCustomerGroup = (): Promise<string | null> => {\n return CustomerCompanyContext.getInstance().updateCustomerGroup();\n};"],"names":["CompanyHeaderManager","__publicField","config","headerKey","modules","setFetchGraphQlHeader","removeFetchGraphQlHeader","companyId","setFn","removeFn","_companyHeaderManager","getCompanyHeaderManager","GroupHeaderManager","groupId","_groupHeaderManager","getGroupHeaderManager","initialize","Initializer","defaultConfig","events","authenticated","companyInfo","getCustomerCompanyInfo","currentCompanyId","setEndpoint","setFetchGraphQlHeaders","fetchGraphQl","getConfig","FetchGraphQL","GET_CUSTOMER_COMPANY_CONTEXT","GET_CUSTOMER_GROUP_CONTEXT","_CustomerCompanyContext","company","base64String","decoded","c","hashBuffer","b","_a","response","customerGroupId","data","customerGroup","customerCompanies","CustomerCompanyContext","updateCustomerGroup"],"mappings":"4UAWA,MAAMA,CAAqB,CAMzB,aAAc,CALNC,EAAA,wBAA4B,IAC5BA,EAAA,6BAAwD,CAAA,GACxDA,EAAA,6BAA2D,CAAA,GAC3DA,EAAA,kBAGN,KAAK,UAAYC,EAAO,UAAA,EAAY,cACpC,KAAK,uBAAuBA,EAAO,UAAA,EAAY,mBAAmB,CACpE,CAEO,aAAaC,EAAyB,CAC3C,KAAK,UAAYA,CACnB,CAEO,uBAAuBC,EAA+B,CAC3D,KAAK,sBAAwB,CAAA,EAC7B,KAAK,sBAAwB,CAAA,EAC7BA,EAAQ,QAAQ,CAAC,CAAE,sBAAAC,EAAuB,yBAAAC,KAA+B,CACvE,KAAK,sBAAsB,KAAKD,CAAqB,EACrD,KAAK,sBAAsB,KAAKC,CAAwB,CAC1D,CAAC,CACH,CAEO,kBAAkBC,EAAgC,CACvD,GAAIA,IAAc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kB,MAAM,KAAK,uBAAuBD,EAAS,KAAK,cAAc,GAAG,EACzF,OAAI,KAAK,QACP,KAAK,MAAM,gBAAkBC,GAExBA,CACT,OAAS,EAAG,CACV,eAAQ,MAAM,CAAC,EACR,IACT,CACF,CAQA,MAAM,wBAAuD,CAE3D,GAAI,KAAK,MACP,OAAO,KAAK,MAId,GAAI,CAAC,KAAK,sBACR,OAAO,KAAK,+BAGd,GAAI,CAEF,MAAMD,EAAY,MAAMb,EAA8BG,CAA4B,EAClF,GAAIU,EAAS,OACX,OAAO,KAAK,+BAGd,MAAME,EAAOF,EAAS,KAChBG,EAAgB,MAAM,KAAK,uBAAuBH,EAAS,KAAK,cAAc,GAAG,EACjFI,EAAoBF,EAAK,SAAS,UAAU,MAAM,IAAI,KAAK,wBAAwB,EAEzF,YAAK,MAAQ,CACX,eAAgBA,EAAK,QACrB,kBAAAE,EACA,gBAAiBD,CAAA,EAEZ,KAAK,KACd,OAAS,EAAG,CACV,eAAQ,MAAM,CAAC,EACR,KAAK,8BACd,CACF,CACF,EAhHEzC,EADW8B,EACI,YADV,IAAMa,EAANb,EAmHA,MAAMT,EAAyB,IAC7BsB,EAAuB,YAAA,EAAc,uBAAA,EAGjCC,EAAsB,IAC1BD,EAAuB,YAAA,EAAc,oBAAA"}
@@ -1,4 +1,4 @@
1
1
  /*! Copyright 2025 Adobe
2
2
  All Rights Reserved. */
3
- import{jsx as u}from"@dropins/tools/preact-jsx-runtime.js";import{useState as f,useCallback as C,useEffect as x,useMemo as v}from"@dropins/tools/preact-hooks.js";import{Picker as I}from"@dropins/tools/components.js";import{events as i}from"@dropins/tools/event-bus.js";import{C as g}from"../chunks/customerCompanyContext.js";import"@dropins/tools/fetch-graphql.js";const w=()=>{const[r,m]=f([]),[c,a]=f({text:"",value:""}),p=C(async()=>{var t,n;try{const e=await g.getInstance().getCustomerCompanyInfo();m(e.customerCompanies),(t=e.currentCompany)!=null&&t.name&&((n=e.currentCompany)!=null&&n.id)&&a({text:e.currentCompany.name,value:e.currentCompany.id})}catch(o){console.error("Failed to load company data:",o)}},[]),s=C(t=>{const o=t.target.value,e=r.find(h=>h.value===o);e&&a(e),i.emit("companyContext/changing",o)},[r]),y=C(()=>{g.getInstance().resetCache(),m([]),a({text:"",value:""})},[]),l=C(t=>{t?p():y()},[p,y]),d=C(t=>{m(n=>{const o=n.find(e=>e.value===t);return o&&a(o),n})},[]);return x(()=>{const t=i.on("authenticated",l,{eager:!0}),n=i.on("companyContext/restored",d,{eager:!0});return()=>{var o,e;(o=t==null?void 0:t.off)==null||o.call(t),(e=n==null?void 0:n.off)==null||e.call(n)}},[l,d]),{companies:r,currentCompany:c,handleCompanyChange:s}},F=({ariaLabel:r,...m})=>{const{companies:c,currentCompany:a,handleCompanyChange:p}=w(),s=v(()=>c,[c]);return c.length<2?null:u("div",{...m,children:u(I,{options:s,value:a.value,onChange:p,"aria-label":r||"Select company","aria-describedby":"company-switcher-description"})})};export{F as CompanySwitcher,F as default,w as useCompanyData};
3
+ import{jsx as h}from"@dropins/tools/preact-jsx-runtime.js";import{useState as f,useCallback as p,useEffect as x,useMemo as I}from"@dropins/tools/preact-hooks.js";import{Picker as w}from"@dropins/tools/components.js";import{events as l}from"@dropins/tools/event-bus.js";import{C as S,e as H,c as g,u as K,h as k}from"../chunks/customerCompanyContext.js";import"@dropins/tools/lib.js";import"@dropins/tools/fetch-graphql.js";const G=()=>{const[c,r]=f([]),[i,a]=f({text:"",value:""}),C=p(async()=>{var e,n;try{const o=await S.getInstance().getCustomerCompanyInfo();r(o.customerCompanies),(e=o.currentCompany)!=null&&e.name&&((n=o.currentCompany)!=null&&n.id)&&a({text:o.currentCompany.name,value:o.currentCompany.id})}catch(t){console.error("Failed to load company data:",t)}},[]),u=p(async e=>{const t=e.target.value,o=c.find(v=>v.value===t);o&&a(o),H().setCompanyHeaders(t),t?sessionStorage.setItem(g.getConfig().companySessionStorageKey,t):sessionStorage.removeItem(g.getConfig().companySessionStorageKey);const d=await K();k().setGroupHeaders(d),d?sessionStorage.setItem(g.getConfig().groupSessionStorageKey,d):sessionStorage.removeItem(g.getConfig().groupSessionStorageKey),l.emit("companyContext/changed",t)},[c]),s=p(()=>{S.getInstance().resetCache(),r([]),a({text:"",value:""})},[]),y=p(e=>{e?C():s()},[C,s]),m=p(e=>{if(!e){s();return}r(n=>{const t=n.find(o=>o.value===e);return t&&a(t),n})},[s,r,a]);return x(()=>{const e=l.on("authenticated",y,{eager:!0}),n=l.on("companyContext/changed",m,{eager:!0});return()=>{var t,o;(t=e==null?void 0:e.off)==null||t.call(e),(o=n==null?void 0:n.off)==null||o.call(n)}},[y,m]),{companies:c,currentCompany:i,handleCompanyChange:u}},P=({ariaLabel:c,...r})=>{const{companies:i,currentCompany:a,handleCompanyChange:C}=G(),[u,s]=f(!0),y=I(()=>i,[i]);return x(()=>{const m=l.on("checkout/initialized",()=>{s(!1)});return()=>m==null?void 0:m.off()},[]),i.length<2||!u?null:h("div",{...r,children:h(w,{options:y,value:a.value,onChange:C,"aria-label":c||"Select company","aria-describedby":"company-switcher-description"})})};export{P as CompanySwitcher,P as default,G as useCompanyData};
4
4
  //# sourceMappingURL=CompanySwitcher.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"CompanySwitcher.js","sources":["/@dropins/storefront-company-switcher/src/containers/CompanySwitcher/useCompanyData.ts","/@dropins/storefront-company-switcher/src/containers/CompanySwitcher/CompanySwitcher.tsx"],"sourcesContent":["/********************************************************************\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: Adobe permits you to use, modify, and distribute this \n * file in accordance with the terms of the Adobe license agreement \n * accompanying it. \n *******************************************************************/\n\nimport { useState, useCallback, useEffect } from 'preact/hooks';\nimport { events } from '@adobe-commerce/event-bus';\nimport { CustomerCompanyContext } from '@/company-switcher/api/customerCompanyContext';\nimport type { CompanyOption, CustomerCompanyInfo, UseCompanyDataReturn } from '@/company-switcher/types/company';\n\n/**\n * Custom hook that manages company data fetching and state management\n * @returns {UseCompanyDataReturn} Company data and handlers\n */\nexport const useCompanyData = (): UseCompanyDataReturn => {\n const [companies, setCompanies] = useState<CompanyOption[]>([]);\n const [currentCompany, setCurrentCompany] = useState<CompanyOption>({ text: '', value: '' });\n\n\n /**\n * Loads company information from the API and updates state\n */\n const loadCompanyData = useCallback(async (): Promise<void> => {\n try {\n const customerCompanyContext = CustomerCompanyContext.getInstance();\n const companyInfo: CustomerCompanyInfo = await customerCompanyContext.getCustomerCompanyInfo();\n setCompanies(companyInfo.customerCompanies);\n \n if (companyInfo.currentCompany?.name && companyInfo.currentCompany?.id) {\n setCurrentCompany({\n text: companyInfo.currentCompany.name, \n value: companyInfo.currentCompany.id\n });\n }\n } catch (err) {\n console.error('Failed to load company data:', err);\n }\n }, []);\n\n /**\n * Handles company selection change\n */\n const handleCompanyChange = useCallback((event: Event): void => {\n const target = event.target as HTMLSelectElement;\n const companyId = target.value;\n \n // Update local state\n const selectedCompany = companies.find(c => c.value === companyId);\n if (selectedCompany) {\n setCurrentCompany(selectedCompany);\n }\n \n // Emit event for other components to react to company change\n events.emit('companyContext/changing', companyId);\n }, [companies]);\n\n /**\n * Clears company context\n */\n const clearCompanyContext = useCallback((): void => {\n const customerCompanyContext = CustomerCompanyContext.getInstance();\n customerCompanyContext.resetCache();\n setCompanies([]);\n setCurrentCompany({ text: '', value: '' });\n }, []);\n\n /**\n * Handles authentication state changes\n */\n const handleAuthenticationChange = useCallback((authenticated: boolean) => {\n if (authenticated) {\n loadCompanyData();\n } else {\n clearCompanyContext();\n }\n }, [loadCompanyData, clearCompanyContext]);\n\n /**\n * Handles company context restoration\n */\n const handleCompanyContextRestored = useCallback((companyId: string) => {\n // Store the company ID to be restored when companies are loaded\n setCompanies(prevCompanies => {\n const restoredCompany = prevCompanies.find(company => company.value === companyId);\n if (restoredCompany) {\n setCurrentCompany(restoredCompany);\n }\n return prevCompanies;\n });\n }, []);\n\n // Set up event listeners\n useEffect(() => {\n const unsubscribeAuth = events.on('authenticated', handleAuthenticationChange, { eager: true });\n const unsubscribeRestore = events.on('companyContext/restored', handleCompanyContextRestored, { eager: true });\n \n return () => {\n unsubscribeAuth?.off?.();\n unsubscribeRestore?.off?.();\n };\n }, [handleAuthenticationChange, handleCompanyContextRestored]);\n\n return {\n companies,\n currentCompany,\n handleCompanyChange\n };\n};\n","/********************************************************************\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: Adobe permits you to use, modify, and distribute this \n * file in accordance with the terms of the Adobe license agreement \n * accompanying it. \n *******************************************************************/\n \nimport { HTMLAttributes } from 'preact/compat';\nimport { useMemo } from 'preact/hooks';\nimport { Container } from '@adobe-commerce/elsie/lib';\nimport { Picker } from '@adobe-commerce/elsie/components';\nimport { useCompanyData } from './useCompanyData';\n\nexport interface CompanySwitcherProps extends HTMLAttributes<HTMLDivElement> {\n /** Custom aria-label for the picker */\n ariaLabel?: string;\n}\n\n/**\n * CompanySwitcher component allows users to switch between companies they have access to.\n * It only renders when a user has access to multiple companies.\n * This is a presentational component that uses the useCompanyData hook for all business logic.\n */\nexport const CompanySwitcher: Container<CompanySwitcherProps> = ({ \n ariaLabel,\n ...props \n}) => {\n const { companies, currentCompany, handleCompanyChange } = useCompanyData();\n\n // Memoize the companies array to prevent unnecessary re-renders\n const memoizedCompanies = useMemo(() => companies, [companies]);\n\n // Only render if user has access to multiple companies\n if (companies.length < 2) {\n return null;\n }\n\n return (\n <div {...props}>\n <Picker \n options={memoizedCompanies} \n value={currentCompany.value} \n onChange={handleCompanyChange}\n aria-label={ariaLabel || 'Select company'}\n aria-describedby=\"company-switcher-description\"\n />\n </div>\n );\n};\n"],"names":["useCompanyData","companies","setCompanies","useState","currentCompany","setCurrentCompany","loadCompanyData","useCallback","companyInfo","CustomerCompanyContext","_a","_b","err","handleCompanyChange","event","companyId","selectedCompany","c","events","clearCompanyContext","handleAuthenticationChange","authenticated","handleCompanyContextRestored","prevCompanies","restoredCompany","company","useEffect","unsubscribeAuth","unsubscribeRestore","CompanySwitcher","ariaLabel","props","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A,CAAE,EAGL,OAAAG,EAAU,IAAM,CACd,MAAMC,EAAkBT,EAAO,GAAG,gBAAiBE,EAA4B,CAAE,MAAO,GAAM,EACxFQ,EAAqBV,EAAO,GAAG,0BAA2BI,EAA8B,CAAE,MAAO,GAAM,EAE7G,MAAO,IAAM,UACXZ,EAAAiB,GAAA,YAAAA,EAAiB,MAAjB,MAAAjB,EAAA,KAAAiB,IACAhB,EAAAiB,GAAA,YAAAA,EAAoB,MAApB,MAAAjB,EAAA,KAAAiB,EACF,CACF,EAAG,CAACR,EAA4BE,CAA4B,CAAC,EAEtD,CACL,UAAArB,EACA,eAAAG,EACA,oBAAAS,CAAA,CAEJ,ECtFagB,EAAmD,CAAC,CAC/D,UAAAC,EACA,GAAGC,CACL,IAAM,CACJ,KAAM,CAAE,UAAA9B,EAAW,eAAAG,EAAgB,oBAAAS,CAAA,EAAwBb,EAAA,EAGrDgC,EAAoBC,EAAQ,IAAMhC,EAAW,CAACA,CAAS,CAAC,EAG9D,OAAIA,EAAU,OAAS,EACd,KAIPiC,EAAC,MAAA,CAAK,GAAGH,EACP,SAAAG,EAACC,EAAA,CACC,QAASH,EACT,MAAO5B,EAAe,MACtB,SAAUS,EACV,aAAYiB,GAAa,iBACzB,mBAAiB,8BAAA,CAAA,EAErB,CAEJ"}
1
+ {"version":3,"file":"CompanySwitcher.js","sources":["/@dropins/storefront-company-switcher/src/containers/CompanySwitcher/useCompanyData.ts","/@dropins/storefront-company-switcher/src/containers/CompanySwitcher/CompanySwitcher.tsx"],"sourcesContent":["/********************************************************************\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: Adobe permits you to use, modify, and distribute this \n * file in accordance with the terms of the Adobe license agreement \n * accompanying it. \n *******************************************************************/\n\nimport { useState, useCallback, useEffect } from 'preact/hooks';\nimport { events } from '@adobe-commerce/event-bus';\nimport { CustomerCompanyContext, updateCustomerGroup } from '@/company-switcher/api/customerCompanyContext';\nimport type { CompanyOption, CustomerCompanyInfo, UseCompanyDataReturn } from '@/company-switcher/types/company';\nimport { config } from '@/company-switcher/api/initialize';\nimport { getGroupHeaderManager } from '@/company-switcher/api/setGroupHeaders';\nimport { getCompanyHeaderManager } from '@/company-switcher/api/setCompanyHeaders';\n\n/**\n * Custom hook that manages company data fetching and state management\n * @returns {UseCompanyDataReturn} Company data and handlers\n */\nexport const useCompanyData = (): UseCompanyDataReturn => {\n const [companies, setCompanies] = useState<CompanyOption[]>([]);\n const [currentCompany, setCurrentCompany] = useState<CompanyOption>({ text: '', value: '' });\n\n\n /**\n * Loads company information from the API and updates state\n */\n const loadCompanyData = useCallback(async (): Promise<void> => {\n try {\n const customerCompanyContext = CustomerCompanyContext.getInstance();\n const companyInfo: CustomerCompanyInfo = await customerCompanyContext.getCustomerCompanyInfo();\n setCompanies(companyInfo.customerCompanies);\n \n if (companyInfo.currentCompany?.name && companyInfo.currentCompany?.id) {\n setCurrentCompany({\n text: companyInfo.currentCompany.name, \n value: companyInfo.currentCompany.id\n });\n }\n } catch (err) {\n console.error('Failed to load company data:', err);\n }\n }, []);\n\n /**\n * Handles company selection change\n */\n const handleCompanyChange = useCallback(async (event: Event): Promise<void> => {\n const target = event.target as HTMLSelectElement;\n const companyId = target.value;\n \n // Update local state\n const selectedCompany = companies.find(c => c.value === companyId);\n if (selectedCompany) {\n setCurrentCompany(selectedCompany);\n }\n \n getCompanyHeaderManager().setCompanyHeaders(companyId);\n if (companyId) {\n sessionStorage.setItem(config.getConfig().companySessionStorageKey, companyId);\n } else {\n sessionStorage.removeItem(config.getConfig().companySessionStorageKey);\n }\n const groupId = await updateCustomerGroup();\n getGroupHeaderManager().setGroupHeaders(groupId);\n if (groupId) {\n sessionStorage.setItem(config.getConfig().groupSessionStorageKey, groupId);\n } else {\n sessionStorage.removeItem(config.getConfig().groupSessionStorageKey);\n }\n\n events.emit('companyContext/changed', companyId);\n }, [companies]);\n\n /**\n * Clears company context\n */\n const clearCompanyContext = useCallback((): void => {\n const customerCompanyContext = CustomerCompanyContext.getInstance();\n customerCompanyContext.resetCache();\n setCompanies([]);\n setCurrentCompany({ text: '', value: '' });\n }, []);\n\n /**\n * Handles authentication state changes\n */\n const handleAuthenticationChange = useCallback((authenticated: boolean) => {\n if (authenticated) {\n loadCompanyData();\n } else {\n clearCompanyContext();\n }\n }, [loadCompanyData, clearCompanyContext]);\n\n /**\n * Handles company context restoration\n */\n const handleCompanyContextRestored = useCallback((companyId: string | null) => {\n if (!companyId) {\n clearCompanyContext();\n return;\n }\n // Store the company ID to be restored when companies are loaded\n setCompanies(prevCompanies => {\n const restoredCompany = prevCompanies.find(company => company.value === companyId);\n if (restoredCompany) {\n setCurrentCompany(restoredCompany);\n }\n return prevCompanies;\n });\n }, [clearCompanyContext, setCompanies, setCurrentCompany]);\n\n // Set up event listeners\n useEffect(() => {\n const unsubscribeAuth = events.on('authenticated', handleAuthenticationChange, { eager: true });\n const unsubscribeRestore = events.on('companyContext/changed', handleCompanyContextRestored, { eager: true });\n \n return () => {\n unsubscribeAuth?.off?.();\n unsubscribeRestore?.off?.();\n };\n }, [handleAuthenticationChange, handleCompanyContextRestored]);\n\n return {\n companies,\n currentCompany,\n handleCompanyChange\n };\n};\n","/********************************************************************\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: Adobe permits you to use, modify, and distribute this \n * file in accordance with the terms of the Adobe license agreement \n * accompanying it. \n *******************************************************************/\n \nimport { HTMLAttributes } from 'preact/compat';\nimport { useMemo, useState, useEffect } from 'preact/hooks';\nimport { Container } from '@adobe-commerce/elsie/lib';\nimport { Picker } from '@adobe-commerce/elsie/components';\nimport { events } from '@adobe-commerce/event-bus';\nimport { useCompanyData } from './useCompanyData';\n\nexport interface CompanySwitcherProps extends HTMLAttributes<HTMLDivElement> {\n /** Custom aria-label for the picker */\n ariaLabel?: string;\n}\n\n/**\n * CompanySwitcher component allows users to switch between companies they have access to.\n * It only renders when a user has access to multiple companies.\n * This is a presentational component that uses the useCompanyData hook for all business logic.\n */\nexport const CompanySwitcher: Container<CompanySwitcherProps> = ({ \n ariaLabel,\n ...props \n}) => {\n const { companies, currentCompany, handleCompanyChange } = useCompanyData();\n const [isVisible, setIsVisible] = useState(true);\n\n // Memoize the companies array to prevent unnecessary re-renders\n const memoizedCompanies = useMemo(() => companies, [companies]);\n\n // Listen for checkout/initialized event to hide the picker\n useEffect(() => {\n const unsubscribe = events.on('checkout/initialized', () => {\n setIsVisible(false);\n });\n\n return () => unsubscribe?.off();\n }, []);\n\n // Only render if user has access to multiple companies and picker is visible\n if (companies.length < 2 || !isVisible) {\n return null;\n }\n\n return (\n <div {...props}>\n <Picker \n options={memoizedCompanies} \n value={currentCompany.value} \n onChange={handleCompanyChange}\n aria-label={ariaLabel || 'Select company'}\n aria-describedby=\"company-switcher-description\"\n />\n </div>\n );\n};\n"],"names":["useCompanyData","companies","setCompanies","useState","currentCompany","setCurrentCompany","loadCompanyData","useCallback","companyInfo","CustomerCompanyContext","_a","_b","err","handleCompanyChange","event","companyId","selectedCompany","c","getCompanyHeaderManager","config","groupId","updateCustomerGroup","getGroupHeaderManager","events","clearCompanyContext","handleAuthenticationChange","authenticated","handleCompanyContextRestored","prevCompanies","restoredCompany","company","useEffect","unsubscribeAuth","unsubscribeRestore","CompanySwitcher","ariaLabel","props","isVisible","setIsVisible","memoizedCompanies","useMemo","unsubscribe","jsx","Picker"],"mappings":"uaAqBO,MAAMA,EAAiB,IAA4B,CACxD,KAAM,CAACC,EAAWC,CAAY,EAAIC,EAA0B,CAAA,CAAE,EACxD,CAACC,EAAgBC,CAAiB,EAAIF,EAAwB,CAAE,KAAM,GAAI,MAAO,GAAI,EAMrFG,EAAkBC,EAAY,SAA2B,SAC7D,GAAI,CAEF,MAAMC,EAAmC,MADVC,EAAuB,YAAA,EACgB,uBAAA,EACtEP,EAAaM,EAAY,iBAAiB,GAEtCE,EAAAF,EAAY,iBAAZ,MAAAE,EAA4B,QAAQC,EAAAH,EAAY,iBAAZ,MAAAG,EAA4B,KAClEN,EAAkB,CACh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AA0B,EAAU,IAAM,CACd,MAAMC,EAAkBT,EAAO,GAAG,gBAAiBE,EAA4B,CAAE,MAAO,GAAM,EACxFQ,EAAqBV,EAAO,GAAG,yBAA0BI,EAA8B,CAAE,MAAO,GAAM,EAE5G,MAAO,IAAM,UACXjB,EAAAsB,GAAA,YAAAA,EAAiB,MAAjB,MAAAtB,EAAA,KAAAsB,IACArB,EAAAsB,GAAA,YAAAA,EAAoB,MAApB,MAAAtB,EAAA,KAAAsB,EACF,CACF,EAAG,CAACR,EAA4BE,CAA4B,CAAC,EAEtD,CACL,UAAA1B,EACA,eAAAG,EACA,oBAAAS,CAAA,CAEJ,ECzGaqB,EAAmD,CAAC,CAC/D,UAAAC,EACA,GAAGC,CACL,IAAM,CACJ,KAAM,CAAE,UAAAnC,EAAW,eAAAG,EAAgB,oBAAAS,CAAA,EAAwBb,EAAA,EACrD,CAACqC,EAAWC,CAAY,EAAInC,EAAS,EAAI,EAGzCoC,EAAoBC,EAAQ,IAAMvC,EAAW,CAACA,CAAS,CAAC,EAY9D,OATA8B,EAAU,IAAM,CACd,MAAMU,EAAclB,EAAO,GAAG,uBAAwB,IAAM,CAC1De,EAAa,EAAK,CACpB,CAAC,EAED,MAAO,IAAMG,GAAA,YAAAA,EAAa,KAC5B,EAAG,CAAA,CAAE,EAGDxC,EAAU,OAAS,GAAK,CAACoC,EACpB,KAIPK,EAAC,MAAA,CAAK,GAAGN,EACP,SAAAM,EAACC,EAAA,CACC,QAASJ,EACT,MAAOnC,EAAe,MACtB,SAAUS,EACV,aAAYsB,GAAa,iBACzB,mBAAiB,8BAAA,CAAA,EAErB,CAEJ"}
package/package.json CHANGED
@@ -1 +1 @@
1
- {"name": "@dropins/storefront-company-switcher", "version": "1.0.0-beta4", "@dropins/tools": "^1.3.0", "license": "SEE LICENSE IN LICENSE.md"}
1
+ {"name": "@dropins/storefront-company-switcher", "version": "1.0.0-beta6", "@dropins/tools": "^1.3.0", "license": "SEE LICENSE IN LICENSE.md"}
@@ -34,7 +34,7 @@ export interface CustomerCompanyInfo {
34
34
  export interface UseCompanyDataReturn {
35
35
  companies: CompanyOption[];
36
36
  currentCompany: CompanyOption;
37
- handleCompanyChange: (event: Event) => void;
37
+ handleCompanyChange: (event: Event) => Promise<void>;
38
38
  }
39
39
  /**
40
40
  * GraphQL response wrapper