diff --git a/packages/commerce-sdk-react/src/auth/index.ts b/packages/commerce-sdk-react/src/auth/index.ts index fdc8bcaa4f..aadb2330a9 100644 --- a/packages/commerce-sdk-react/src/auth/index.ts +++ b/packages/commerce-sdk-react/src/auth/index.ts @@ -17,6 +17,8 @@ import {BaseStorage, LocalStorage, CookieStorage, MemoryStorage, StorageType} fr import {CustomerType} from '../hooks/useCustomerType' import {getParentOrigin, isOriginTrusted, onClient} from '../utils' import { + MOBIFY_PATH, + SLAS_PRIVATE_PROXY_PATH, SLAS_SECRET_WARNING_MSG, SLAS_SECRET_PLACEHOLDER, SLAS_SECRET_OVERRIDE_MSG @@ -178,9 +180,9 @@ class Auth { private logger: Logger constructor(config: AuthConfig) { - // Special endpoint for injecting SLAS private client secret - const baseUrl = config.proxy.split(`/mobify/proxy/api`)[0] - const privateClientEndpoint = `${baseUrl}/mobify/slas/private` + // Special endpoint for injecting SLAS private client secret. + const baseUrl = config.proxy.split(MOBIFY_PATH)[0] + const privateClientEndpoint = `${baseUrl}${SLAS_PRIVATE_PROXY_PATH}` this.client = new ShopperLogin({ proxy: config.enablePWAKitPrivateClient ? privateClientEndpoint : config.proxy, diff --git a/packages/commerce-sdk-react/src/components/StorefrontPreview/utils.ts b/packages/commerce-sdk-react/src/components/StorefrontPreview/utils.ts index dab7fecd30..c3ec082e86 100644 --- a/packages/commerce-sdk-react/src/components/StorefrontPreview/utils.ts +++ b/packages/commerce-sdk-react/src/components/StorefrontPreview/utils.ts @@ -7,6 +7,7 @@ import {ApiClients} from '../../hooks/types' import {DEVELOPMENT_ORIGIN, getParentOrigin, isOriginTrusted} from '../../utils' +import {LOCAL_BUNDLE_PATH} from '../../constant' /** Detects whether the storefront is running in an iframe as part of Storefront Preview. * @private @@ -16,13 +17,15 @@ export const detectStorefrontPreview = () => { return isOriginTrusted(parentOrigin) } -/** Returns the URL to load the Storefront Preview client script from the parent origin. +/** + * Returns the URL to load the Storefront Preview client script from the parent origin. + * The client script is served from Runtime Admin and is not a part of the PWA Retail React App bundle. * @private */ export const getClientScript = () => { const parentOrigin = getParentOrigin() ?? 'https://runtime.commercecloud.com' return parentOrigin === DEVELOPMENT_ORIGIN - ? `${parentOrigin}/mobify/bundle/development/static/storefront-preview.js` + ? `${parentOrigin}${LOCAL_BUNDLE_PATH}/static/storefront-preview.js` : `${parentOrigin}/cc/b2c/preview/preview.client.js` } diff --git a/packages/commerce-sdk-react/src/constant.ts b/packages/commerce-sdk-react/src/constant.ts index 63870cd352..991dd5e200 100644 --- a/packages/commerce-sdk-react/src/constant.ts +++ b/packages/commerce-sdk-react/src/constant.ts @@ -14,6 +14,12 @@ export const IFRAME_HOST_ALLOW_LIST = Object.freeze([ 'https://runtime-admin-preview.mobify-storefront.com' ]) +// We hardcode these here since we don't want commerce-sdk-react to have a dependency on pwa-kit-runtime +export const MOBIFY_PATH = '/mobify' +export const PROXY_PATH = `${MOBIFY_PATH}/proxy` +export const LOCAL_BUNDLE_PATH = `${MOBIFY_PATH}/bundle/development` +export const SLAS_PRIVATE_PROXY_PATH = `${MOBIFY_PATH}/slas/private` + export const SLAS_SECRET_WARNING_MSG = 'You are potentially exposing SLAS secret on browser. Make sure to keep it safe and secure!' diff --git a/packages/commerce-sdk-react/src/test-utils.tsx b/packages/commerce-sdk-react/src/test-utils.tsx index be878c270b..9b2a596c7b 100644 --- a/packages/commerce-sdk-react/src/test-utils.tsx +++ b/packages/commerce-sdk-react/src/test-utils.tsx @@ -15,6 +15,7 @@ import { } from '@tanstack/react-query' import nock from 'nock' import CommerceApiProvider, {CommerceApiProviderProps} from './provider' +import {PROXY_PATH} from './constant' // Note: this host does NOT exist // it is intentional b/c we can catch those unintercepted requests @@ -22,7 +23,7 @@ import CommerceApiProvider, {CommerceApiProviderProps} from './provider' export const DEFAULT_TEST_HOST = 'http://localhost:8888' export const DEFAULT_TEST_CONFIG = { - proxy: `${DEFAULT_TEST_HOST}/mobify/proxy/api`, + proxy: `${DEFAULT_TEST_HOST}${PROXY_PATH}/api`, redirectURI: `${DEFAULT_TEST_HOST}/callback`, clientId: '12345678-1234-1234-1234-123412341234', organizationId: 'f_ecom_zzrmy_orgf_001', @@ -31,7 +32,7 @@ export const DEFAULT_TEST_CONFIG = { locale: 'en-US', currency: 'USD', fetchedToken: 'test-token', - OCAPISessionsURL: `${DEFAULT_TEST_HOST}/mobify/proxy/ocapi/s/RefArch/dw/shop/v22_8/sessions` + OCAPISessionsURL: `${DEFAULT_TEST_HOST}${PROXY_PATH}/ocapi/s/RefArch/dw/shop/v22_8/sessions` } export const createQueryClient = () => { diff --git a/packages/pwa-kit-create-app/assets/bootstrap/js/overrides/app/components/_app-config/index.jsx.hbs b/packages/pwa-kit-create-app/assets/bootstrap/js/overrides/app/components/_app-config/index.jsx.hbs index b9f4b04d2e..f0f7e5068d 100644 --- a/packages/pwa-kit-create-app/assets/bootstrap/js/overrides/app/components/_app-config/index.jsx.hbs +++ b/packages/pwa-kit-create-app/assets/bootstrap/js/overrides/app/components/_app-config/index.jsx.hbs @@ -18,6 +18,7 @@ import { resolveLocaleFromUrl } from '@salesforce/retail-react-app/app/utils/site-utils' import {getConfig} from '@salesforce/pwa-kit-runtime/utils/ssr-config' +import {proxyBasePath} from '@salesforce/pwa-kit-runtime/utils/ssr-namespace-paths' import {createUrlTemplate} from '@salesforce/retail-react-app/app/utils/url' import {CommerceApiProvider} from '@salesforce/commerce-sdk-react' @@ -55,7 +56,7 @@ const AppConfig = ({children, locals = {}}) => { redirectURI={`${appOrigin}/callback`} proxy={`${appOrigin}${commerceApiConfig.proxyPath}`} headers={headers} - OCAPISessionsURL={`${appOrigin}/mobify/proxy/ocapi/s/${locals.site?.id}/dw/shop/v22_8/sessions`} + OCAPISessionsURL={`${appOrigin}${proxyBasePath}/ocapi/s/${locals.site?.id}/dw/shop/v22_8/sessions`} {{#if answers.project.commerce.isSlasPrivate}} // Set 'enablePWAKitPrivateClient' to true use SLAS private client login flows. // Make sure to also enable useSLASPrivateClient in ssr.js when enabling this setting. diff --git a/packages/pwa-kit-create-app/assets/templates/@salesforce/retail-react-app/app/components/_app-config/index.jsx.hbs b/packages/pwa-kit-create-app/assets/templates/@salesforce/retail-react-app/app/components/_app-config/index.jsx.hbs index b9f4b04d2e..f0f7e5068d 100644 --- a/packages/pwa-kit-create-app/assets/templates/@salesforce/retail-react-app/app/components/_app-config/index.jsx.hbs +++ b/packages/pwa-kit-create-app/assets/templates/@salesforce/retail-react-app/app/components/_app-config/index.jsx.hbs @@ -18,6 +18,7 @@ import { resolveLocaleFromUrl } from '@salesforce/retail-react-app/app/utils/site-utils' import {getConfig} from '@salesforce/pwa-kit-runtime/utils/ssr-config' +import {proxyBasePath} from '@salesforce/pwa-kit-runtime/utils/ssr-namespace-paths' import {createUrlTemplate} from '@salesforce/retail-react-app/app/utils/url' import {CommerceApiProvider} from '@salesforce/commerce-sdk-react' @@ -55,7 +56,7 @@ const AppConfig = ({children, locals = {}}) => { redirectURI={`${appOrigin}/callback`} proxy={`${appOrigin}${commerceApiConfig.proxyPath}`} headers={headers} - OCAPISessionsURL={`${appOrigin}/mobify/proxy/ocapi/s/${locals.site?.id}/dw/shop/v22_8/sessions`} + OCAPISessionsURL={`${appOrigin}${proxyBasePath}/ocapi/s/${locals.site?.id}/dw/shop/v22_8/sessions`} {{#if answers.project.commerce.isSlasPrivate}} // Set 'enablePWAKitPrivateClient' to true use SLAS private client login flows. // Make sure to also enable useSLASPrivateClient in ssr.js when enabling this setting. diff --git a/packages/pwa-kit-dev/src/configs/jest/jest.config.js b/packages/pwa-kit-dev/src/configs/jest/jest.config.js index c3adee91e9..8ed2189ccc 100644 --- a/packages/pwa-kit-dev/src/configs/jest/jest.config.js +++ b/packages/pwa-kit-dev/src/configs/jest/jest.config.js @@ -26,6 +26,9 @@ module.exports = { DEBUG: true, NODE_ENV: 'test', Progressive: { + // BuildOrigin can be any non-empty string. It does not have to be /mobify/xyz + // This is used by tests that call getAssetUrl in pwa-kit-react-sdk to simulate + // asset urls. buildOrigin: '/mobify/bundle/development/' } }, diff --git a/packages/pwa-kit-dev/src/configs/webpack/config.js b/packages/pwa-kit-dev/src/configs/webpack/config.js index 54634949cf..a42bbc9c8a 100644 --- a/packages/pwa-kit-dev/src/configs/webpack/config.js +++ b/packages/pwa-kit-dev/src/configs/webpack/config.js @@ -121,6 +121,18 @@ const getAppEntryPoint = () => { return resolve('./', EXT_OVERRIDES_DIR_NO_SLASH, 'app', 'main') } +const getPublicPathEntryPoint = () => { + return resolve( + projectDir, + 'node_modules', + '@salesforce', + 'pwa-kit-dev', + 'ssr', + 'server', + 'public-path' + ) +} + const findDepInStack = (pkg) => { // Look for the SDK node_modules in two places because in CI, // pwa-kit-dev is published under a 'dist' directory, which @@ -394,7 +406,11 @@ const enableReactRefresh = (config) => { }, entry: { ...config.entry, - main: ['webpack-hot-middleware/client?path=/__mrt/hmr', getAppEntryPoint()] + main: [ + 'webpack-hot-middleware/client?path=/__mrt/hmr', + getPublicPathEntryPoint(), + getAppEntryPoint() + ] }, plugins: [ ...config.plugins, @@ -403,12 +419,7 @@ const enableReactRefresh = (config) => { new ReactRefreshWebpackPlugin({ overlay: false }) - ], - output: { - ...config.output, - // Setting this so that *.hot-update.json requests are resolving - publicPath: '/mobify/bundle/development/' - } + ] } } diff --git a/packages/pwa-kit-dev/src/ssr/server/build-dev-server.js b/packages/pwa-kit-dev/src/ssr/server/build-dev-server.js index 5d23f8f072..68f92e8c3a 100644 --- a/packages/pwa-kit-dev/src/ssr/server/build-dev-server.js +++ b/packages/pwa-kit-dev/src/ssr/server/build-dev-server.js @@ -19,6 +19,7 @@ import open from 'open' import requireFromString from 'require-from-string' import {RemoteServerFactory} from '@salesforce/pwa-kit-runtime/ssr/server/build-remote-server' import {proxyConfigs} from '@salesforce/pwa-kit-runtime/utils/ssr-shared' +import {bundleBasePath} from '@salesforce/pwa-kit-runtime/utils/ssr-namespace-paths' import { SERVER, CLIENT, @@ -166,7 +167,7 @@ export const DevServerMixin = { app.__hotServerMiddleware = webpackHotServerMiddleware(app.__compiler) } - app.use('/mobify/bundle/development', app.__devMiddleware) + app.use(`${bundleBasePath}/development`, app.__devMiddleware) app.__hmrMiddleware = (_, res) => res.status(501).send('Hot Module Reloading is disabled.') const clientCompiler = app.__compiler.compilers.find((compiler) => compiler.name === CLIENT) @@ -209,7 +210,7 @@ export const DevServerMixin = { // Proxy bundle asset requests to the local // build directory. app.use( - '/mobify/bundle/development', + `${bundleBasePath}/development`, express.static(path.resolve(process.cwd(), 'src'), { dotFiles: 'deny', setHeaders: setLocalAssetHeaders, diff --git a/packages/pwa-kit-dev/src/ssr/server/public-path.js b/packages/pwa-kit-dev/src/ssr/server/public-path.js new file mode 100644 index 0000000000..bb765dfd55 --- /dev/null +++ b/packages/pwa-kit-dev/src/ssr/server/public-path.js @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2024, 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 + */ + +/** + * This file is used to dynamically set the webpack public path used by HMR via the global webpack variable + * __webpack_public_path__ + * See https://webpack.js.org/guides/public-path/ + * + * Previously, we hard coded the public path in our webpack config to '/mobify/bundle/development/' + * but we need something more dynamic to support namespaced /mobify paths. + */ + +import {bundleBasePath} from '@salesforce/pwa-kit-runtime/utils/ssr-namespace-paths' + +/* global __webpack_public_path__: writable */ +__webpack_public_path__ = `${bundleBasePath}/development/` diff --git a/packages/pwa-kit-react-sdk/src/ssr/universal/utils.js b/packages/pwa-kit-react-sdk/src/ssr/universal/utils.js index 439094a35f..2c57e03e78 100644 --- a/packages/pwa-kit-react-sdk/src/ssr/universal/utils.js +++ b/packages/pwa-kit-react-sdk/src/ssr/universal/utils.js @@ -8,6 +8,7 @@ * @module progressive-web-sdk/ssr/universal/utils */ import {proxyConfigs} from '@salesforce/pwa-kit-runtime/utils/ssr-shared' +import {bundleBasePath} from '@salesforce/pwa-kit-runtime/utils/ssr-namespace-paths' const onClient = typeof window !== 'undefined' @@ -22,7 +23,7 @@ export const getAssetUrl = (path) => { /* istanbul ignore next */ const publicPath = onClient ? `${window.Progressive.buildOrigin}` - : `/mobify/bundle/${process.env.BUNDLE_ID || 'development'}/` + : `${bundleBasePath}/${process.env.BUNDLE_ID || 'development'}/` return path ? `${publicPath}${path}` : publicPath } diff --git a/packages/pwa-kit-runtime/src/ssr/server/build-remote-server.js b/packages/pwa-kit-runtime/src/ssr/server/build-remote-server.js index fd958da76d..7290d4c2d4 100644 --- a/packages/pwa-kit-runtime/src/ssr/server/build-remote-server.js +++ b/packages/pwa-kit-runtime/src/ssr/server/build-remote-server.js @@ -11,8 +11,7 @@ import { X_MOBIFY_QUERYSTRING, SET_COOKIE, CACHE_CONTROL, - NO_CACHE, - SLAS_CUSTOM_PROXY_PATH + NO_CACHE } from './constants' import { catchAndLog, @@ -40,6 +39,12 @@ import {RESOLVED_PROMISE} from './express' import http from 'http' import https from 'https' import {proxyConfigs, updatePackageMobify} from '../../utils/ssr-shared' +import { + proxyBasePath, + bundleBasePath, + healthCheckPath, + slasPrivateProxyPath +} from '../../utils/ssr-namespace-paths' import {applyProxyRequestHeaders} from '../../utils/ssr-server/configure-proxy' import awsServerlessExpress from 'aws-serverless-express' import expressLogging from 'morgan' @@ -205,6 +210,13 @@ export const RemoteServerFactory = { return true }, + /** + * @private + */ + _isBundleOrProxyPath(url) { + return url.startsWith(proxyBasePath) || url.startsWith(bundleBasePath) + }, + /** * @private */ @@ -457,7 +469,7 @@ export const RemoteServerFactory = { const processIncomingRequest = (req, res) => { const options = req.app.options // If the request is for a proxy or bundle path, do nothing - if (req.originalUrl.startsWith('/mobify/')) { + if (this._isBundleOrProxyPath(req.originalUrl)) { return } @@ -580,7 +592,7 @@ export const RemoteServerFactory = { // different types of the 'req' object, and will // always contain the original full path. /* istanbul ignore else */ - if (!req.originalUrl.startsWith('/mobify/')) { + if (!this._isBundleOrProxyPath(req.originalUrl)) { req.app.sendMetric( 'RequestTime', Date.now() - locals.requestStart, @@ -626,7 +638,7 @@ export const RemoteServerFactory = { */ // eslint-disable-next-line @typescript-eslint/no-unused-vars _setupProxying(app, options) { - app.all('/mobify/proxy/*', (_, res) => { + app.all(`${proxyBasePath}/*`, (_, res) => { return res.status(501).json({ message: 'Environment proxies are not set: https://developer.salesforce.com/docs/commerce/pwa-kit-managed-runtime/guide/proxying-requests.html' @@ -638,7 +650,7 @@ export const RemoteServerFactory = { * @private */ _handleMissingSlasPrivateEnvVar(app) { - app.use(SLAS_CUSTOM_PROXY_PATH, (_, res) => { + app.use(slasPrivateProxyPath, (_, res) => { return res.status(501).json({ message: 'Environment variable PWA_KIT_SLAS_CLIENT_SECRET not set: Please set this environment variable to proceed.' @@ -653,28 +665,29 @@ export const RemoteServerFactory = { if (!options.useSLASPrivateClient) { return } - localDevLog(`Proxying ${SLAS_CUSTOM_PROXY_PATH} to ${options.slasTarget}`) + + localDevLog(`Proxying ${slasPrivateProxyPath} to ${options.slasTarget}`) const clientId = options.mobify?.app?.commerceAPI?.parameters?.clientId const clientSecret = process.env.PWA_KIT_SLAS_CLIENT_SECRET if (!clientSecret) { - this._handleMissingSlasPrivateEnvVar(app) + this._handleMissingSlasPrivateEnvVar(app, slasPrivateProxyPath) return } const encodedSlasCredentials = Buffer.from(`${clientId}:${clientSecret}`).toString('base64') app.use( - SLAS_CUSTOM_PROXY_PATH, + slasPrivateProxyPath, createProxyMiddleware({ target: options.slasTarget, changeOrigin: true, - pathRewrite: {[SLAS_CUSTOM_PROXY_PATH]: ''}, + pathRewrite: {[slasPrivateProxyPath]: ''}, onProxyReq: (proxyRequest, incomingRequest) => { applyProxyRequestHeaders({ proxyRequest, incomingRequest, - proxyPath: SLAS_CUSTOM_PROXY_PATH, + proxyPath: slasPrivateProxyPath, targetHost: options.slasHostName, targetProtocol: 'https' }) @@ -725,7 +738,7 @@ export const RemoteServerFactory = { * @private */ _setupHealthcheck(app) { - app.get('/mobify/ping', (_, res) => + app.get(`${healthCheckPath}`, (_, res) => res.set('cache-control', NO_CACHE).sendStatus(200).end() ) }, diff --git a/packages/pwa-kit-runtime/src/ssr/server/constants.js b/packages/pwa-kit-runtime/src/ssr/server/constants.js index 62920cd838..c9333656e4 100644 --- a/packages/pwa-kit-runtime/src/ssr/server/constants.js +++ b/packages/pwa-kit-runtime/src/ssr/server/constants.js @@ -7,7 +7,10 @@ export const APPLICATION_OCTET_STREAM = 'application/octet-stream' export const BUILD = 'build' export const STATIC_ASSETS = 'static_assets' + +/** * @deprecated Use ssr-namespace-paths proxyBasePath instead */ export const PROXY_PATH_PREFIX = '/mobify/proxy' + // All these values MUST be lower case export const CONTENT_TYPE = 'content-type' export const CONTENT_ENCODING = 'content-encoding' @@ -19,4 +22,6 @@ export const CACHE_CONTROL = 'cache-control' export const NO_CACHE = 'max-age=0, nocache, nostore, must-revalidate' export const CONTENT_SECURITY_POLICY = 'content-security-policy' export const STRICT_TRANSPORT_SECURITY = 'strict-transport-security' + +/** * @deprecated Use ssr-namespace-paths.slasPrivateProxyPath instead */ export const SLAS_CUSTOM_PROXY_PATH = '/mobify/slas/private' diff --git a/packages/pwa-kit-runtime/src/utils/ssr-namespace-paths.js b/packages/pwa-kit-runtime/src/utils/ssr-namespace-paths.js new file mode 100644 index 0000000000..9942b9f845 --- /dev/null +++ b/packages/pwa-kit-runtime/src/utils/ssr-namespace-paths.js @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2024, 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 + */ + +/** + * This file defines the /mobify paths used to set up our Express endpoints. + * + * If a namespace for the /mobify paths is defined, the methods in here will return the + * namespaced path. ie. /namespace/mobify/... + */ + +const MOBIFY_PATH = '/mobify' +const PROXY_PATH_BASE = `${MOBIFY_PATH}/proxy` +const BUNDLE_PATH_BASE = `${MOBIFY_PATH}/bundle` +const CACHING_PATH_BASE = `${MOBIFY_PATH}/caching` +const HEALTHCHECK_PATH = `${MOBIFY_PATH}/ping` +const SLAS_PRIVATE_CLIENT_PROXY_PATH = `${MOBIFY_PATH}/slas/private` + +/** + * @private + */ +const _getNamespace = () => { + // TODO - namespaces for /mobify path will be implemented at a later date. + // Returns an empty string for now. + // Below is an example of what this implementation might look like. + /* + let {namespace = ""} = getConfig() + namespace = typeof namespace === 'function' ? namespace() : namespace + return namespace + */ + return '' +} + +export const ssrNamespace = _getNamespace() + +export const proxyBasePath = `${ssrNamespace}${PROXY_PATH_BASE}` +export const bundleBasePath = `${ssrNamespace}${BUNDLE_PATH_BASE}` +export const cachingBasePath = `${ssrNamespace}${CACHING_PATH_BASE}` +export const healthCheckPath = `${ssrNamespace}${HEALTHCHECK_PATH}` +export const slasPrivateProxyPath = `${ssrNamespace}${SLAS_PRIVATE_CLIENT_PROXY_PATH}` diff --git a/packages/pwa-kit-runtime/src/utils/ssr-server.test.js b/packages/pwa-kit-runtime/src/utils/ssr-server.test.js index 4e0df7adc4..767b127dbc 100644 --- a/packages/pwa-kit-runtime/src/utils/ssr-server.test.js +++ b/packages/pwa-kit-runtime/src/utils/ssr-server.test.js @@ -43,10 +43,11 @@ import { CONTENT_ENCODING, CONTENT_TYPE, X_ORIGINAL_CONTENT_TYPE, - APPLICATION_OCTET_STREAM, - PROXY_PATH_PREFIX + APPLICATION_OCTET_STREAM } from '../ssr/server/constants' +import {proxyBasePath} from './ssr-namespace-paths' + const baseMobify = { ssrEnabled: true, ssrOnly: ['main.js.map', 'ssr.js', 'ssr.js.map', 'vendor.js.map'], @@ -117,11 +118,11 @@ describe('utils/ssr-server tests', () => { updatePackageMobify(baseMobify) - expect(getFullRequestURL(`${PROXY_PATH_PREFIX}/base/somepath`)).toBe( + expect(getFullRequestURL(`${proxyBasePath}/base/somepath`)).toBe( 'https://www.merlinspotions.com/somepath' ) - expect(getFullRequestURL(`${PROXY_PATH_PREFIX}/base2/somepath`)).toBe( + expect(getFullRequestURL(`${proxyBasePath}/base2/somepath`)).toBe( 'https://api.merlinspotions.com/somepath' ) }) diff --git a/packages/pwa-kit-runtime/src/utils/ssr-server/utils.js b/packages/pwa-kit-runtime/src/utils/ssr-server/utils.js index cf9ea1354f..8f6cad02f0 100644 --- a/packages/pwa-kit-runtime/src/utils/ssr-server/utils.js +++ b/packages/pwa-kit-runtime/src/utils/ssr-server/utils.js @@ -11,8 +11,8 @@ // ../ssr-server.js because it would create circular dependencies. import crypto from 'crypto' -import {PROXY_PATH_PREFIX} from '../../ssr/server/constants' import {proxyConfigs} from '../ssr-shared' +import {proxyBasePath, bundleBasePath} from '../ssr-namespace-paths' import logger from '../logger-instance' // TODO: Clean this up or provide a way to toggle @@ -22,7 +22,7 @@ export const isRemote = () => Object.prototype.hasOwnProperty.call(process.env, 'AWS_LAMBDA_FUNCTION_NAME') export const getBundleBaseUrl = () => { - return `/mobify/bundle/${isRemote() ? process.env.BUNDLE_ID : 'development'}/` + return `${bundleBasePath}/${isRemote() ? process.env.BUNDLE_ID : 'development'}/` } let QUIET = false @@ -88,16 +88,13 @@ export const getHashForString = (text) => { export const getFullRequestURL = (url) => { // If it starts with a protocol (e.g. http(s)://, file://), then it's already a full URL if (/^[a-zA-Z]+:\/\//.test(url)) return url - const proxy = proxyConfigs.find(({path}) => url.startsWith(`${PROXY_PATH_PREFIX}/${path}/`)) + const proxy = proxyConfigs.find(({path}) => url.startsWith(`${proxyBasePath}/${path}/`)) if (proxy) { - return url.replace( - `${PROXY_PATH_PREFIX}/${proxy.path}`, - `${proxy.protocol}://${proxy.host}` - ) + return url.replace(`${proxyBasePath}/${proxy.path}`, `${proxy.protocol}://${proxy.host}`) } throw new Error( - `Unable to fetch ${url}, relative paths must begin with ${PROXY_PATH_PREFIX} followed by a configured proxy path.` + `Unable to fetch ${url}, relative paths must begin with ${proxyBasePath} followed by a configured proxy path.` ) } diff --git a/packages/pwa-kit-runtime/src/utils/ssr-shared.js b/packages/pwa-kit-runtime/src/utils/ssr-shared.js index 4368a3aea7..2e43a2b58f 100644 --- a/packages/pwa-kit-runtime/src/utils/ssr-shared.js +++ b/packages/pwa-kit-runtime/src/utils/ssr-shared.js @@ -4,6 +4,9 @@ * 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 {proxyBasePath, cachingBasePath} from './ssr-namespace-paths' + /** * @module progressive-web-sdk/utils/ssr-shared * @private @@ -166,8 +169,8 @@ export const updatePackageMobify = (newValue) => { } // Generate paths - config.proxyPath = `/mobify/proxy/${config.path}` - config.cachingPath = `/mobify/caching/${config.path}` + config.proxyPath = `${proxyBasePath}/${config.path}` + config.cachingPath = `${cachingBasePath}/${config.path}` proxyConfigs.push(config) } diff --git a/packages/template-retail-react-app/app/components/_app-config/index.jsx b/packages/template-retail-react-app/app/components/_app-config/index.jsx index 44362fe1c3..184b6abc73 100644 --- a/packages/template-retail-react-app/app/components/_app-config/index.jsx +++ b/packages/template-retail-react-app/app/components/_app-config/index.jsx @@ -27,6 +27,7 @@ import { resolveLocaleFromUrl } from '@salesforce/retail-react-app/app/utils/site-utils' import {getConfig} from '@salesforce/pwa-kit-runtime/utils/ssr-config' +import {proxyBasePath} from '@salesforce/pwa-kit-runtime/utils/ssr-namespace-paths' import {createUrlTemplate} from '@salesforce/retail-react-app/app/utils/url' import createLogger from '@salesforce/pwa-kit-runtime/utils/logger-factory' @@ -68,7 +69,7 @@ const AppConfig = ({children, locals = {}}) => { // Uncomment 'enablePWAKitPrivateClient' to use SLAS private client login flows. // Make sure to also enable useSLASPrivateClient in ssr.js when enabling this setting. // enablePWAKitPrivateClient={true} - OCAPISessionsURL={`${appOrigin}/mobify/proxy/ocapi/s/${locals.site?.id}/dw/shop/v22_8/sessions`} + OCAPISessionsURL={`${appOrigin}${proxyBasePath}/ocapi/s/${locals.site?.id}/dw/shop/v22_8/sessions`} logger={createLogger({packageName: 'commerce-sdk-react'})} > diff --git a/packages/template-retail-react-app/app/hooks/use-active-data.js b/packages/template-retail-react-app/app/hooks/use-active-data.js index 76832d6dda..bebe77c87b 100644 --- a/packages/template-retail-react-app/app/hooks/use-active-data.js +++ b/packages/template-retail-react-app/app/hooks/use-active-data.js @@ -6,6 +6,7 @@ */ /*global dw*/ import {ACTIVE_DATA_ENABLED} from '@salesforce/retail-react-app/app/constants' +import {proxyBasePath} from '@salesforce/pwa-kit-runtime/utils/ssr-namespace-paths' import logger from '@salesforce/retail-react-app/app/utils/logger-instance' const useActiveData = () => { @@ -78,7 +79,7 @@ const useActiveData = () => { if (!canTrack()) return try { var activeDataUrl = - '/mobify/proxy/ocapi/on/demandware.store/Sites-' + + `${proxyBasePath}/ocapi/on/demandware.store/Sites-` + siteId + '-Site/' + localeId + diff --git a/packages/test-commerce-sdk-react/app/components/_app-config/index.tsx b/packages/test-commerce-sdk-react/app/components/_app-config/index.tsx index d6b3ba3f1d..28c953845b 100644 --- a/packages/test-commerce-sdk-react/app/components/_app-config/index.tsx +++ b/packages/test-commerce-sdk-react/app/components/_app-config/index.tsx @@ -8,6 +8,7 @@ import React, {useState, ReactElement} from 'react' import {CommerceApiProvider} from '@salesforce/commerce-sdk-react' import {withReactQuery} from '@salesforce/pwa-kit-react-sdk/ssr/universal/components/with-react-query' import {useCorrelationId} from '@salesforce/pwa-kit-react-sdk/ssr/universal/hooks' +import {proxyBasePath} from '@salesforce/pwa-kit-runtime/utils/ssr-namespace-paths' interface AppConfigProps { children: React.ReactNode @@ -31,7 +32,7 @@ const AppConfig = (props: AppConfigProps): ReactElement => { clientId="4afbc51f-6423-41c8-8b29-d7f2825b5bee" organizationId="f_ecom_zzrf_006" redirectURI="http://localhost:3000/callback" - proxy="http://localhost:3000/mobify/proxy/api" + proxy={`http://localhost:3000/${String(proxyBasePath)}/api`} locale={locale} currency="USD" headers={headers} diff --git a/packages/test-commerce-sdk-react/pwa-kit.d.ts b/packages/test-commerce-sdk-react/pwa-kit.d.ts index d3790bca99..d1ae1099af 100644 --- a/packages/test-commerce-sdk-react/pwa-kit.d.ts +++ b/packages/test-commerce-sdk-react/pwa-kit.d.ts @@ -10,3 +10,4 @@ declare module '@salesforce/pwa-kit-react-sdk/ssr/browser/main' declare module '@salesforce/pwa-kit-react-sdk/ssr/universal/components/with-react-query' declare module '@salesforce/pwa-kit-react-sdk/ssr/universal/hooks' +declare module '@salesforce/pwa-kit-runtime/utils/ssr-namespace-paths'