import { assert, assertString } from './util/mod.ts'; /** Used to determine server settings to use. */ type Touchpoint = 'desktop' | 'mobile'; type UserContext = 'PERSONALIZED' | 'UNPERSONALIZED' | 'ANONYMOUS' | 'SYNTHETIC'; type MaybePromise = T | Promise; type MaybeLazy = T | (() => T); /** * Session information for a specific visitor * * Can be either {@linkcode SessionMetadata} synchronously or as a promise, * or a callback function called to retrieve that same information. * * @example * ```ts * declare function loadSession(): SessionMetadata; * declare function loadSessionAsync(): Promise; * declare function consented(): boolean; * * // Any of these is a valid `Session`: * const a: Session = { // direct object * customerKey: '', * sessionKey: '' * }; * const b: Session = loadSessionAsync(); // promise * const c: Session = loadSession; // sync callback * const d: Session = loadSessionAsync; // async callback * * // Direct user-context via string literal * const e: Session = () => consented() ? 'ANONYMOUS' : loadSession(); * const f: Session = 'SYNTHETIC'; * ``` */ type Session = MaybeLazy>; /** * For user contexts that do not require `sessionKey` or `customerKey` * * This allows using a terser form compared to {@linkcode SessionMetadata} for these contexts, * e.g. `'ANONYMOUS'` instead of `{ userContext: 'ANONYMOUS' }`. * * @example * ```ts * const api = elevate({ * ... * session: 'ANONYMOUS' * }); * ``` */ type KeylessContext = Extract; /** Keys identifying the current visitor and their session. */ interface SessionKeys { /** * A key that uniquely identifies the current visitor. Using UUIDs as keys are recommended. * @see https://docs.elevate.voyado.cloud/elevate/4/integration/site-integration/query-integration/query-parameters/#common-parameters */ customerKey: string; /** * A unique key, identifying the session. Using UUIDs as keys are recommended. * @see https://docs.elevate.voyado.cloud/elevate/4/integration/site-integration/query-integration/query-parameters/#common-parameters */ sessionKey: string; } /** Discriminant carrying the user context a request is made in. */ interface WithUserContext { /** * The type of user context the current request will be made in. * @see https://docs.elevate.voyado.cloud/elevate/4/integration/site-integration/query-integration/query-parameters/#user-context */ userContext: T; } /** Default context — both keys are required and `userContext` may be omitted or set explicitly. */ type PersonalizedSession = SessionKeys & Partial>; /** Only `sessionKey` is used; `userContext` must be set explicitly. */ type UnpersonalizedSession = Pick & WithUserContext<'UNPERSONALIZED'>; /** No keys are allowed; `userContext` must be set explicitly. */ type AnonymousSession = WithUserContext<'ANONYMOUS'>; /** Keys are optional and ignored by the server; `userContext` must be set explicitly. */ type SyntheticSession = Partial & WithUserContext<'SYNTHETIC'>; /** Metadata regarding a visitor, used during requests to the Elevate Storefront API. */ type SessionMetadata = PersonalizedSession | UnpersonalizedSession | AnonymousSession | SyntheticSession; /** * Configuration required during initialization for the Elevate Storefront API. * * @example * ```ts * const config: Config = { ... }; * const api = elevate(config); * ``` */ interface Config { /** * The ID for the Elevate cluster for all subsequent API requests. * Production/Test/Development clusters each have their own unique ID. * The value for `clusterId` can be found in credentials tab in * the Voyado Elevate app, * * The value should be: * - An identifier in a format similar to `'w00000000'` * - A URL with the origin to the Elevate cluster, e.g. * `'https://w00000000.api.esales.apptus.cloud/'` * * @example * ```ts * const api = elevate({ clusterId: 'w00000000' }); * ``` */ clusterId: string; /** Required for loading correct products and behavior data. */ market: string; /** Required for loading localized product and facet data. */ locale: string; /** Used to determine various server settings. */ touchpoint: Touchpoint; /** Configures how session metadata (customerKey & sessionKey) is retrieved before requests to the API */ session: Session; } /** * Subset of Config for interacting with the Notifications API. * @see Config */ type NotificationConfig = Pick; /** * Created from a validated `Config`. Used internally. * @internal */ interface BaseOptions extends Omit { clusterUrl: string; } /** * Created from a validated `Config`. Used internally. * @internal */ interface FullOptions extends Omit { clusterUrl: string; } function validateBaseConfig(config: unknown): asserts config is NotificationConfig { assert(typeof config === 'object' && config !== null, 'API config must be an "object"'); const c: Partial = config; assertString(c.clusterId, 'Property "clusterId" must be a non-empty string'); assertString(c.market, 'Property "market" must be a non-empty string'); const s = c.session; assert( typeof s === 'string' || typeof s === 'function' || (typeof s === 'object' && s !== null), 'Property "session" must be a string, object, promise, or method.' ); } /** * Validates that user supplied config is in a correct format. `unknown` is used as parameter * value to indicate that we do not yet trust the user input. * * @param config raw configuration for creating the API library to be validated */ export function validateConfig(config: unknown): asserts config is Config { validateBaseConfig(config); const c: Partial = config; const touchpoints: Touchpoint[] = ['desktop', 'mobile']; assertString(c.locale, 'Property "locale" must be a string and valid locale, e.g. "en-US".'); assert(touchpoints.includes(c.touchpoint!), `Property "touchpoint" must be one of: ${touchpoints.join(', ')}`); } function resolveClusterUrl(config: T) { const { clusterId, ...rest } = config; const clusterUrl = (() => { /** Ensures consistent casing and trailing slash of URL's */ const normalizeUrl = (url: string) => new URL(url).href; try { // Will throw for invalid URL, and normalize trailing slash return normalizeUrl(clusterId); } catch { /* empty */ } return normalizeUrl(`https://${clusterId}.api.esales.apptus.cloud/`); })(); return { ...rest, clusterUrl }; } /** Prepares user-supplied configuration for internal use. */ export function resolveConfig(config: Config): FullOptions { // TODO(@csvn): Allow this code to be removed in a production build? validateConfig(config); return resolveClusterUrl(config); } /** Prepares user-supplied configuration for internal use. */ export function resolveNotificationConfig(config: NotificationConfig): BaseOptions { // TODO(@csvn): Allow this code to be removed in a production build? validateBaseConfig(config); return resolveClusterUrl(config); } export type { Config, NotificationConfig, BaseOptions, FullOptions, Session, SessionMetadata, PersonalizedSession, Touchpoint, UserContext };