-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathprovider.tsx
More file actions
336 lines (314 loc) · 10.6 KB
/
provider.tsx
File metadata and controls
336 lines (314 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
/*
* Copyright (c) 2022, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import React, {ReactElement, useEffect, useMemo} from 'react'
import Auth from './auth'
import {ApiClientConfigParams, ApiClients, SDKClientTransformer} from './hooks/types'
import {Logger} from './types'
import {DWSID_COOKIE_NAME, SERVER_AFFINITY_HEADER_KEY} from './constant'
import {
ShopperBaskets,
ShopperContexts,
ShopperConfigurations,
ShopperCustomers,
ShopperExperience,
ShopperGiftCertificates,
ShopperLogin,
ShopperOrders,
ShopperProducts,
ShopperPromotions,
ShopperSearch,
ShopperSEO,
ShopperStores,
FetchOptions
} from 'commerce-sdk-isomorphic'
import {transformSDKClient} from './utils'
export interface CommerceApiProviderProps extends ApiClientConfigParams {
children: React.ReactNode
proxy: string
locale: string
currency: string
redirectURI: string
fetchOptions?: FetchOptions
headers?: Record<string, string>
fetchedToken?: string
enablePWAKitPrivateClient?: boolean
privateClientProxyEndpoint?: string
clientSecret?: string
silenceWarnings?: boolean
logger?: Logger
defaultDnt?: boolean
passwordlessLoginCallbackURI?: string
refreshTokenRegisteredCookieTTL?: number
refreshTokenGuestCookieTTL?: number
apiClients?: ApiClients
disableAuthInit?: boolean
hybridAuthEnabled?: boolean
/** When true, proxy returns tokens in HttpOnly cookies. */
useHttpOnlySessionCookies?: boolean
}
/**
* @internal
*/
export const CommerceApiContext = React.createContext({} as ApiClients)
/**
* @internal
*/
export const ConfigContext = React.createContext(
{} as Omit<CommerceApiProviderProps, 'children' | 'apiClients'>
)
/**
* @internal
*/
export const AuthContext = React.createContext({} as Auth)
/**
* Initialize a set of Commerce API clients and make it available to all of descendant components
*
* @group Components
*
* @example
* ```js
import {CommerceApiProvider} from '@salesforce/commerce-sdk-react'
const App = ({children}) => {
return (
<CommerceApiProvider
clientId="12345678-1234-1234-1234-123412341234"
organizationId="f_ecom_aaaa_001"
proxy="localhost:3000/mobify/proxy/api"
redirectURI="localhost:3000/callback"
siteId="RefArch"
shortCode="12345678"
locale="en-US"
enablePWAKitPrivateClient={true}
currency="USD"
logger={logger}
>
{children}
</CommerceApiProvider>
)
}
export default App
* ```
* Note: The provider can enable SLAS Private Client mode in 2 ways.
* `enablePWAKitPrivateClient` sets commerce-sdk-react to work with the PWA proxy
* `/mobify/slas/private` to set the private client secret. PWA users should use
* this option.
*
* Non-PWA Kit users can enable private client mode by passing in a client secret
* directly to the provider. However, be careful when doing this as you will have
* to make sure the secret is not unexpectedly exposed to the client.
*
*
* `hybridAuthEnabled` is an optional flag that indicates the current Site has Hybrid Auth enabled.
* This drives the behavior of the `clearECOMSession` method. If `hybridAuthEnabled` is true,
* the `clearECOMSession` method will not be called. This makes sure the session-bridged dwsid, received from `/oauth2/token` call
* on shopper login is NOT cleared and can be used to maintain the server affinity.
*
* `hybridAuthEnabled` flag can also be used to drive other Hybrid Auth specific behaviors in the future.
*
* Note: `hybridAuthEnabled` should NOT be set to true for hybrid storefronts using Plugin SLAS as we need the dwsid to be deleted
* to force session-bridging on SFRA as in this case, the `oauth2/token` call does not return a dwsid.
*
* @returns Provider to wrap your app with
*/
const CommerceApiProvider = (props: CommerceApiProviderProps): ReactElement => {
const {
children,
clientId,
headers = {},
organizationId,
proxy,
redirectURI,
fetchOptions,
siteId,
shortCode,
locale,
currency,
fetchedToken,
enablePWAKitPrivateClient,
privateClientProxyEndpoint,
clientSecret,
silenceWarnings,
logger,
defaultDnt,
passwordlessLoginCallbackURI,
refreshTokenRegisteredCookieTTL,
refreshTokenGuestCookieTTL,
apiClients,
disableAuthInit = false,
hybridAuthEnabled = false,
useHttpOnlySessionCookies = false
} = props
// Set the logger based on provided configuration, or default to the console object if no logger is provided
const configLogger = logger || console
// When HttpOnly cookies are enabled, ensure fetch credentials allow cookies to be sent.
const effectiveFetchOptions =
useHttpOnlySessionCookies &&
(!fetchOptions?.credentials || fetchOptions.credentials === 'omit')
? {...fetchOptions, credentials: 'same-origin' as RequestCredentials}
: fetchOptions
const auth = useMemo(() => {
return new Auth({
clientId,
organizationId,
shortCode,
siteId,
proxy,
redirectURI,
headers,
fetchOptions: effectiveFetchOptions,
fetchedToken,
enablePWAKitPrivateClient,
privateClientProxyEndpoint,
clientSecret,
silenceWarnings,
logger: configLogger,
defaultDnt,
passwordlessLoginCallbackURI,
refreshTokenRegisteredCookieTTL,
refreshTokenGuestCookieTTL,
hybridAuthEnabled,
useHttpOnlySessionCookies
})
}, [
clientId,
organizationId,
shortCode,
siteId,
proxy,
redirectURI,
headers,
effectiveFetchOptions,
fetchedToken,
enablePWAKitPrivateClient,
privateClientProxyEndpoint,
clientSecret,
silenceWarnings,
configLogger,
defaultDnt,
passwordlessLoginCallbackURI,
refreshTokenRegisteredCookieTTL,
refreshTokenGuestCookieTTL,
apiClients,
hybridAuthEnabled,
useHttpOnlySessionCookies
])
const dwsid = auth.get(DWSID_COOKIE_NAME)
const serverAffinityHeader: Record<string, string> = {}
if (dwsid) {
serverAffinityHeader[SERVER_AFFINITY_HEADER_KEY] = dwsid
}
const _defaultTransformer: SDKClientTransformer<Record<string, any>> = (_, _$, options) => {
return {
...options,
headers: {
...options.headers,
...serverAffinityHeader
},
throwOnBadResponse: true,
fetchOptions: {
...options.fetchOptions,
...effectiveFetchOptions
}
}
}
const updatedClients: ApiClients = useMemo(() => {
if (apiClients) {
const clients: Record<string, any> = {}
// transformSDKClient is simply a utility function that wraps the SDK Client instance
// in a Proxy that allows us to transform the method arguments and modify headers, parameters, and other options.
// We don't really need to pass in the children prop to the transformer function, so we'll just pass in the rest of the props.
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const {children, ...restProps} = props
Object.entries(apiClients ?? {}).forEach(([key, apiClient]) => {
clients[key] = transformSDKClient(apiClient, {
props: restProps,
transformer: _defaultTransformer
})
})
return clients as ApiClients
}
const config = {
proxy,
headers: {
...headers,
...serverAffinityHeader
},
parameters: {
clientId,
organizationId,
shortCode,
siteId,
locale,
currency
},
throwOnBadResponse: true,
fetchOptions: effectiveFetchOptions
}
return {
shopperBaskets: new ShopperBaskets(config),
shopperContexts: new ShopperContexts(config),
shopperConfigurations: new ShopperConfigurations(config),
shopperCustomers: new ShopperCustomers(config),
shopperExperience: new ShopperExperience(config),
shopperGiftCertificates: new ShopperGiftCertificates(config),
shopperLogin: new ShopperLogin({
...config,
proxy: enablePWAKitPrivateClient ? privateClientProxyEndpoint : config.proxy
}),
shopperOrders: new ShopperOrders(config),
shopperProducts: new ShopperProducts(config),
shopperPromotions: new ShopperPromotions(config),
shopperSearch: new ShopperSearch(config),
shopperSeo: new ShopperSEO(config),
shopperStores: new ShopperStores(config)
}
}, [
clientId,
organizationId,
shortCode,
siteId,
proxy,
effectiveFetchOptions,
locale,
currency,
headers?.['correlation-id'],
apiClients
])
// Initialize the session
useEffect(() => {
if (!disableAuthInit) {
void auth.ready()
}
}, [auth, disableAuthInit])
return (
<ConfigContext.Provider
value={{
clientId,
headers,
organizationId,
proxy,
redirectURI,
fetchOptions,
siteId,
shortCode,
locale,
currency,
silenceWarnings,
logger: configLogger,
defaultDnt,
passwordlessLoginCallbackURI,
refreshTokenRegisteredCookieTTL,
refreshTokenGuestCookieTTL
}}
>
<CommerceApiContext.Provider value={updatedClients}>
<AuthContext.Provider value={auth}>{children}</AuthContext.Provider>
</CommerceApiContext.Provider>
</ConfigContext.Provider>
)
}
export default CommerceApiProvider