diff --git a/packages/headless/src/app/commerce-engine/commerce-engine.ts b/packages/headless/src/app/commerce-engine/commerce-engine.ts index 4ca88bcb77c..7f2f585a52f 100644 --- a/packages/headless/src/app/commerce-engine/commerce-engine.ts +++ b/packages/headless/src/app/commerce-engine/commerce-engine.ts @@ -27,7 +27,7 @@ import { ExternalEngineOptions, } from '../engine'; import {buildLogger} from '../logger'; -import {stateKey} from '../state-key'; +import {redactEngine, stateKey} from '../state-key'; import {buildThunkExtraArguments} from '../thunk-extra-arguments'; import { CommerceEngineConfiguration, @@ -127,7 +127,7 @@ export function buildCommerceEngine( engine.dispatch(setItems(options.configuration.cart.items)); } - return { + return redactEngine({ ...engine, get [stateKey]() { @@ -147,7 +147,7 @@ export function buildCommerceEngine( const action = executeSearch(); internalEngine.dispatch(action); }, - }; + }); } function validateConfiguration( diff --git a/packages/headless/src/app/state-key.ts b/packages/headless/src/app/state-key.ts index 68a248441ac..77816a44bae 100644 --- a/packages/headless/src/app/state-key.ts +++ b/packages/headless/src/app/state-key.ts @@ -1 +1,25 @@ -export const stateKey = Symbol('state'); +import type {CoreEngineNext} from './engine'; + +const stateKeyDescription = 'state'; +export const stateKey = Symbol(stateKeyDescription); + +export const redactEngine = ( + engine: TEngine +): TEngine => + new Proxy(engine, { + ownKeys(target) { + return Reflect.ownKeys(target).filter((key) => key !== stateKey); + }, + get(target, prop, receiver) { + if ( + typeof prop === 'symbol' && + prop.description === stateKeyDescription && + prop !== stateKey + ) { + engine.logger.warn( + "You might be loading Headless twice. Please check your setup.\nIf you are trying to access the inner state... Don't" + ); + } + return Reflect.get(target, prop, receiver); + }, + });