@contentful/optimization-api-client 0.1.0-alpha15 → 0.1.0-alpha17
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/README.md +27 -21
- package/THIRD_PARTY_NOTICES.txt +213 -31
- package/dist/index.cjs +50 -29
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +25 -31
- package/dist/index.d.mts +25 -31
- package/dist/index.d.ts +25 -31
- package/dist/index.mjs +50 -29
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -4
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","sources":["../src/lib/logger/LogSink.ts","../src/lib/logger/logging.ts","../src/lib/logger/Logger.ts","../src/lib/logger/ConsoleLogSink.ts","webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../src/fetch/createRetryFetchMethod.ts","../src/fetch/createTimeoutFetchMethod.ts","../src/fetch/createProtectedFetchMethod.ts","../src/fetch/Fetch.ts","../src/fetch/index.ts","../src/ApiClientBase.ts","../src/experience/ExperienceApiClient.ts","../src/insights/InsightsApiClient.ts","../src/ApiClient.ts"],"sourcesContent":["import type { LogEvent } from './logging'\n\n/**\n * Abstract base class for log sinks that receive and process log events.\n *\n * @example\n * ```typescript\n * class MyCustomSink extends LogSink {\n * name = 'MyCustomSink'\n *\n * ingest(event: LogEvent): void {\n * // process the event\n * }\n * }\n * ```\n *\n * @public\n */\nabstract class LogSink {\n /** Display name used to identify this sink for addition and removal. */\n abstract name: string\n\n /**\n * Processes an incoming log event.\n *\n * @param event - The log event to process.\n * @returns Nothing.\n */\n abstract ingest(event: LogEvent): void\n}\n\nexport default LogSink\n","/**\n * Supported log levels ordered from highest to lowest severity.\n *\n * @public\n */\nexport type LogLevels = 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'log'\n\n/**\n * A log event emitted by the logger package.\n *\n * @public\n */\nexport interface LogEvent {\n /** Logger scope name. */\n name: string\n /** Event severity level. */\n level: LogLevels\n /** Event payload, where the first entry is the formatted message. */\n messages: unknown[]\n /** Optional additional context attached by sinks or middleware. */\n [other: string]: unknown\n}\n\n/**\n * Numeric severity map used for log-level threshold comparisons.\n *\n * @public\n */\nexport const logLevelSeverity: Readonly<Record<LogLevels, number>> = {\n fatal: 60,\n error: 50,\n warn: 40,\n info: 30,\n debug: 20,\n log: 10,\n}\n","import type LogSink from './LogSink'\nimport type { LogEvent, LogLevels } from './logging'\n\n/**\n * Central logger that routes log events through registered {@link LogSink} instances.\n *\n * @example\n * ```typescript\n * import { logger } from '@contentful/optimization-api-client/logger'\n *\n * logger.info('MyModule', 'Application started')\n * ```\n *\n * @public\n */\nexport class Logger {\n /** The logger's identifier, used as the event scope name. */\n readonly name = '@contentful/optimization'\n\n private readonly PREFIX_PARTS = ['Ctfl', 'O10n']\n private readonly DELIMITER = ':'\n private sinks: LogSink[] = []\n\n private assembleLocationPrefix(logLocation: string): string {\n return `[${[...this.PREFIX_PARTS, logLocation].join(this.DELIMITER)}]`\n }\n\n /**\n * Registers a log sink. If a sink with the same name already exists, it is replaced.\n *\n * @param sink - The {@link LogSink} instance to register.\n * @returns Nothing.\n *\n * @example\n * ```typescript\n * import { logger, ConsoleLogSink } from '@contentful/optimization-api-client/logger'\n *\n * logger.addSink(new ConsoleLogSink('debug'))\n * ```\n */\n public addSink(sink: LogSink): void {\n this.sinks = [...this.sinks.filter((existingSink) => existingSink.name !== sink.name), sink]\n }\n\n /**\n * Removes a registered sink by name.\n *\n * @param name - The name of the sink to remove.\n * @returns Nothing.\n *\n * @example\n * ```typescript\n * logger.removeSink('ConsoleLogSink')\n * ```\n */\n public removeSink(name: string): void {\n this.sinks = this.sinks.filter((sink) => sink.name !== name)\n }\n\n /**\n * Removes all registered sinks.\n *\n * @returns Nothing.\n *\n * @example\n * ```typescript\n * logger.removeSinks()\n * ```\n */\n public removeSinks(): void {\n this.sinks = []\n }\n\n /**\n * Logs a message at the debug level.\n *\n * @param logLocation - The module or component identifier.\n * @param message - The log message.\n * @param args - Additional arguments forwarded in the log event.\n * @returns Nothing.\n *\n * @example\n * ```typescript\n * logger.debug('MyModule', 'Debugging value', someVariable)\n * ```\n */\n public debug(logLocation: string, message: string, ...args: unknown[]): void {\n this.emit('debug', logLocation, message, ...args)\n }\n\n /**\n * Logs a message at the info level.\n *\n * @param logLocation - The module or component identifier.\n * @param message - The log message.\n * @param args - Additional arguments forwarded in the log event.\n * @returns Nothing.\n *\n * @example\n * ```typescript\n * logger.info('MyModule', 'Operation completed')\n * ```\n */\n public info(logLocation: string, message: string, ...args: unknown[]): void {\n this.emit('info', logLocation, message, ...args)\n }\n\n /**\n * Logs a message at the log level.\n *\n * @param logLocation - The module or component identifier.\n * @param message - The log message.\n * @param args - Additional arguments forwarded in the log event.\n * @returns Nothing.\n *\n * @example\n * ```typescript\n * logger.log('MyModule', 'General log entry')\n * ```\n */\n public log(logLocation: string, message: string, ...args: unknown[]): void {\n this.emit('log', logLocation, message, ...args)\n }\n\n /**\n * Logs a message at the warn level.\n *\n * @param logLocation - The module or component identifier.\n * @param message - The log message.\n * @param args - Additional arguments forwarded in the log event.\n * @returns Nothing.\n *\n * @example\n * ```typescript\n * logger.warn('MyModule', 'Deprecated method called')\n * ```\n */\n public warn(logLocation: string, message: string, ...args: unknown[]): void {\n this.emit('warn', logLocation, message, ...args)\n }\n\n /**\n * Logs a message at the error level.\n *\n * @param logLocation - The module or component identifier.\n * @param message - The log message or Error object.\n * @param args - Additional arguments forwarded in the log event.\n * @returns Nothing.\n *\n * @example\n * ```typescript\n * logger.error('MyModule', new Error('Something failed'))\n * ```\n */\n public error(logLocation: string, message: string | Error, ...args: unknown[]): void {\n this.emit('error', logLocation, message, ...args)\n }\n\n /**\n * Logs a message at the fatal level.\n *\n * @param logLocation - The module or component identifier.\n * @param message - The log message or Error object.\n * @param args - Additional arguments forwarded in the log event.\n * @returns Nothing.\n *\n * @example\n * ```typescript\n * logger.fatal('MyModule', new Error('Unrecoverable failure'))\n * ```\n */\n public fatal(logLocation: string, message: string | Error, ...args: unknown[]): void {\n this.emit('fatal', logLocation, message, ...args)\n }\n\n private emit(\n level: LogLevels,\n logLocation: string,\n message: string | Error,\n ...args: unknown[]\n ): void {\n this.onLogEvent({\n name: this.name,\n level,\n messages: [`${this.assembleLocationPrefix(logLocation)} ${String(message)}`, ...args],\n })\n }\n\n private onLogEvent(event: LogEvent): void {\n this.sinks.forEach((sink) => {\n sink.ingest(event)\n })\n }\n}\n\n/**\n * Shared singleton {@link Logger} instance used across the SDK.\n *\n * @public\n */\nexport const logger = new Logger()\n\n/**\n * A location-scoped logger interface whose methods omit the `logLocation` parameter.\n *\n * @public\n */\nexport interface ScopedLogger {\n /** Logs at debug level. */\n debug: (message: string, ...args: unknown[]) => void\n /** Logs at info level. */\n info: (message: string, ...args: unknown[]) => void\n /** Logs at log level. */\n log: (message: string, ...args: unknown[]) => void\n /** Logs at warn level. */\n warn: (message: string, ...args: unknown[]) => void\n /** Logs at error level. */\n error: (message: string | Error, ...args: unknown[]) => void\n /** Logs at fatal level. */\n fatal: (message: string | Error, ...args: unknown[]) => void\n}\n\n/**\n * Creates a {@link ScopedLogger} that automatically prepends the given location to every log call.\n *\n * @param location - The module or component identifier to prepend.\n * @returns A {@link ScopedLogger} bound to the specified location.\n *\n * @example\n * ```typescript\n * import { createScopedLogger } from '@contentful/optimization-api-client/logger'\n *\n * const log = createScopedLogger('MyModule')\n * log.info('Initialization complete')\n * ```\n *\n * @public\n */\nexport function createScopedLogger(location: string): ScopedLogger {\n return {\n debug: (message: string, ...args: unknown[]) => {\n logger.debug(location, message, ...args)\n },\n info: (message: string, ...args: unknown[]) => {\n logger.info(location, message, ...args)\n },\n log: (message: string, ...args: unknown[]) => {\n logger.log(location, message, ...args)\n },\n warn: (message: string, ...args: unknown[]) => {\n logger.warn(location, message, ...args)\n },\n error: (message: string | Error, ...args: unknown[]) => {\n logger.error(location, message, ...args)\n },\n fatal: (message: string | Error, ...args: unknown[]) => {\n logger.fatal(location, message, ...args)\n },\n }\n}\n","/* eslint-disable no-console -- using console */\nimport { logLevelSeverity, type LogEvent, type LogLevels } from './logging'\nimport LogSink from './LogSink'\n\nconst consoleMap = {\n debug: (...args: unknown[]) => {\n console.debug(...args)\n },\n info: (...args: unknown[]) => {\n console.info(...args)\n },\n log: (...args: unknown[]) => {\n console.log(...args)\n },\n warn: (...args: unknown[]) => {\n console.warn(...args)\n },\n error: (...args: unknown[]) => {\n console.error(...args)\n },\n fatal: (...args: unknown[]) => {\n console.error(...args)\n },\n}\n\n/**\n * A {@link LogSink} that writes log events to the browser or Node.js console,\n * filtering by a configurable verbosity threshold.\n *\n * @example\n * ```typescript\n * import { logger, ConsoleLogSink } from '@contentful/optimization-api-client/logger'\n *\n * logger.addSink(new ConsoleLogSink('debug'))\n * ```\n *\n * @public\n */\nexport class ConsoleLogSink extends LogSink {\n /** Identifies this sink when registered with the {@link Logger}. */\n public name = 'ConsoleLogSink'\n\n /**\n * Minimum log level required for events to be output.\n *\n * @defaultValue 'error'\n */\n readonly verbosity: LogLevels\n\n /**\n * Creates a new ConsoleLogSink.\n *\n * @param verbosity - Minimum log level to output.\n */\n constructor(verbosity?: LogLevels) {\n super()\n\n this.verbosity = verbosity ?? 'error'\n }\n\n /**\n * Writes a log event to the console if its level meets the verbosity threshold.\n *\n * @param event - The log event to process.\n * @returns Nothing.\n */\n ingest(event: LogEvent): void {\n if (logLevelSeverity[event.level] < logLevelSeverity[this.verbosity]) return\n\n consoleMap[event.level](...event.messages)\n }\n}\n","__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import { createScopedLogger } from '../logger'\nimport type { BaseFetchMethodOptions, FetchMethod, FetchMethodCallbackOptions } from './Fetch'\n\nconst logger = createScopedLogger('ApiClient:Retry')\n\n/**\n * Default interval (in milliseconds) between retry attempts.\n *\n * @internal\n */\nconst DEFAULT_INTERVAL_TIMEOUT = 0\n\n/**\n * Default number of retry attempts.\n *\n * @internal\n */\nconst DEFAULT_RETRY_COUNT = 1\n\n/**\n * HTTP status code that triggers a retry.\n *\n * @remarks\n * This value is fixed to `503 Service Unavailable`.\n *\n * @internal\n */\nconst RETRY_RESPONSE_STATUS = 503\n\n/**\n * Default HTTP status code used for {@link HttpError}.\n *\n * @internal\n */\nconst HTTP_ERROR_RESPONSE_STATUS = 500\n\n/**\n * Error type representing HTTP failures with an associated status code.\n *\n * @internal\n */\nclass HttpError extends Error {\n /**\n * The HTTP status code associated with the error.\n */\n public status: number\n\n /**\n * Creates a new {@link HttpError}.\n *\n * @param message - Description of the error.\n * @param status - HTTP status code associated with the error.\n */\n constructor(message: string, status: number = HTTP_ERROR_RESPONSE_STATUS) {\n super(message)\n Object.setPrototypeOf(this, HttpError.prototype)\n this.status = status\n }\n}\n\n/**\n * Configuration options for {@link createRetryFetchMethod}.\n *\n * @public\n */\nexport interface RetryFetchMethodOptions extends BaseFetchMethodOptions {\n /**\n * Delay (in milliseconds) between retry attempts.\n *\n * @defaultValue `0`\n */\n intervalTimeout?: number\n\n /**\n * Callback invoked whenever a retry attempt fails.\n *\n * @param options - Information about the failed attempt.\n *\n * @remarks\n * This callback is invoked with additional metadata such as the attempt\n * number and the number of retries left.\n */\n onFailedAttempt?: (options: FetchMethodCallbackOptions) => void\n\n /**\n * Maximum number of retry attempts.\n *\n * @defaultValue `1`\n */\n retries?: number\n}\n\n/**\n * Internal configuration passed to the retry callback.\n *\n * @internal\n */\ninterface RetryFetchCallbackOptions extends RetryFetchMethodOptions {\n /**\n * Abort controller used to cancel the underlying fetch requests.\n */\n controller: AbortController\n\n /**\n * Initialization options passed to the `fetch` implementation.\n */\n init: RequestInit\n\n /**\n * Request URL.\n */\n url: string | URL\n}\n\n/**\n * Creates a callback function used by the retry loop to perform a protected fetch attempt.\n *\n * @param options - Internal options controlling request execution and retry classification.\n * @returns A function that performs one fetch attempt and either:\n * - returns a successful {@link Response},\n * - throws {@link HttpError} for retriable `503` responses, or\n * - aborts and returns `undefined` for non-retriable failures.\n *\n * @internal\n */\nfunction createRetryFetchCallback({\n apiName = 'Optimization',\n controller,\n fetchMethod = fetch,\n init,\n url,\n}: RetryFetchCallbackOptions) {\n return async () => {\n try {\n const response = await fetchMethod(url, init)\n\n if (response.status === RETRY_RESPONSE_STATUS) {\n throw new HttpError(\n `${apiName} API request to \"${url.toString()}\" failed with status: \"[${response.status}] ${response.statusText}\".`,\n RETRY_RESPONSE_STATUS,\n )\n }\n\n if (!response.ok) {\n const httpError = new Error(\n `Request to \"${url.toString()}\" failed with status: [${response.status}] ${response.statusText} - traceparent: ${response.headers.get('traceparent')}`,\n )\n logger.error('Request failed with non-OK status:', httpError)\n\n controller.abort()\n\n return\n }\n\n logger.debug(`Response from \"${url.toString()}\":`, response)\n\n return response\n } catch (error) {\n if (error instanceof HttpError && error.status === RETRY_RESPONSE_STATUS) {\n throw error\n }\n\n logger.error(`Request to \"${url.toString()}\" failed:`, error)\n\n controller.abort()\n }\n }\n}\n\n/**\n * Waits for the configured retry delay between attempts.\n *\n * @param intervalTimeout - Delay in milliseconds before the next retry attempt.\n * @returns A promise that resolves immediately when delay is non-positive,\n * otherwise after the timeout elapses.\n *\n * @internal\n */\nasync function delayRetry(intervalTimeout: number): Promise<void> {\n if (intervalTimeout <= 0) {\n return\n }\n\n const { promise, resolve } = Promise.withResolvers<undefined>()\n setTimeout(() => {\n resolve(undefined)\n }, intervalTimeout)\n await promise\n}\n\n/**\n * Creates a {@link FetchMethod} that retries failed requests according to the\n * provided configuration.\n *\n * @param options - Configuration options that control retry behavior.\n * @returns A {@link FetchMethod} that automatically retries qualifying failures.\n *\n * @throws Error\n * Thrown when the request cannot be retried and no successful response is obtained.\n *\n * @remarks\n * This wrapper uses a lightweight internal retry loop and an {@link AbortController}\n * to cancel pending requests when a non-retriable error occurs.\n *\n * @example\n * ```ts\n * const fetchWithRetry = createRetryFetchMethod({\n * apiName: 'Optimization',\n * retries: 3,\n * intervalTimeout: 200,\n * onFailedAttempt: ({ attemptNumber, retriesLeft }) => {\n * console.warn(`Attempt ${attemptNumber} failed. Retries left: ${retriesLeft}`)\n * },\n * })\n *\n * const response = await fetchWithRetry('https://example.com', { method: 'GET' })\n * ```\n *\n * @public\n */\nexport function createRetryFetchMethod({\n apiName = 'Optimization',\n fetchMethod = fetch,\n intervalTimeout = DEFAULT_INTERVAL_TIMEOUT,\n onFailedAttempt,\n retries = DEFAULT_RETRY_COUNT,\n}: RetryFetchMethodOptions = {}): FetchMethod {\n return async (url: string | URL, init: RequestInit) => {\n const controller = new AbortController()\n const maxAttempts = retries + 1\n const attemptFetch = createRetryFetchCallback({\n apiName,\n controller,\n fetchMethod,\n init,\n url,\n })\n\n for (let attemptNumber = 1; attemptNumber <= maxAttempts; attemptNumber++) {\n try {\n const response = await attemptFetch()\n\n if (response) {\n return response\n }\n\n break\n } catch (error) {\n if (!(error instanceof HttpError) || error.status !== RETRY_RESPONSE_STATUS) {\n throw error\n }\n\n const retriesLeft = maxAttempts - attemptNumber\n\n onFailedAttempt?.({\n apiName,\n error,\n attemptNumber,\n retriesLeft,\n } satisfies FetchMethodCallbackOptions)\n\n if (retriesLeft === 0) {\n throw error\n }\n\n await delayRetry(intervalTimeout)\n }\n }\n\n throw new Error(`${apiName} API request to \"${url.toString()}\" may not be retried.`)\n }\n}\n","import { createScopedLogger } from '../logger'\nimport type { BaseFetchMethodOptions, FetchMethod, FetchMethodCallbackOptions } from './Fetch'\n\nconst logger = createScopedLogger('ApiClient:Timeout')\n\n/**\n * Default timeout (in milliseconds) for outgoing requests.\n *\n * @internal\n */\nconst DEFAULT_REQUEST_TIMEOUT = 3000\n\n/**\n * Configuration options for {@link createTimeoutFetchMethod}.\n *\n * @public\n */\nexport interface TimeoutFetchMethodOptions extends BaseFetchMethodOptions {\n /**\n * Callback invoked when a request exceeds the configured timeout.\n *\n * @param options - Information about the timed-out request.\n *\n * @remarks\n * If this callback is not provided, a default error is logged.\n *\n * @see {@link FetchMethodCallbackOptions}\n */\n onRequestTimeout?: (options: FetchMethodCallbackOptions) => void\n\n /**\n * Maximum time (in milliseconds) to wait for a response before aborting the request.\n *\n * @defaultValue `3000`\n */\n requestTimeout?: number\n}\n\n/**\n * Creates a {@link FetchMethod} that aborts requests after a configurable timeout.\n *\n * @param options - Configuration options controlling timeout behavior.\n * @returns A {@link FetchMethod} that enforces a timeout for each request.\n *\n * @remarks\n * When a timeout occurs, the request is aborted using an {@link AbortController}.\n * If `onRequestTimeout` is not provided, an error is logged by the package logger.\n *\n * @example\n * ```ts\n * const fetchWithTimeout = createTimeoutFetchMethod({\n * apiName: 'Optimization',\n * requestTimeout: 5000,\n * onRequestTimeout: ({ apiName }) => {\n * console.warn(`${apiName} request timed out`)\n * },\n * })\n *\n * const response = await fetchWithTimeout('https://example.com', { method: 'GET' })\n * ```\n *\n * @see {@link TimeoutFetchMethodOptions}\n *\n * @public\n */\nexport function createTimeoutFetchMethod({\n apiName = 'Optimization',\n fetchMethod = fetch,\n onRequestTimeout,\n requestTimeout = DEFAULT_REQUEST_TIMEOUT,\n}: TimeoutFetchMethodOptions = {}): FetchMethod {\n return async (url: string | URL, init: RequestInit) => {\n const controller = new AbortController()\n\n const id = setTimeout(() => {\n if (typeof onRequestTimeout === 'function') {\n onRequestTimeout({ apiName })\n } else {\n logger.error(`Request to \"${url.toString()}\" timed out`, new Error('Request timeout'))\n }\n\n controller.abort()\n }, requestTimeout)\n\n const requestInit: RequestInit = { ...init }\n Object.assign(requestInit, { signal: controller.signal })\n\n const response = await fetchMethod(url, requestInit)\n\n clearTimeout(id)\n\n return response\n }\n}\n","import { createScopedLogger } from '../logger'\nimport { createRetryFetchMethod, type RetryFetchMethodOptions } from './createRetryFetchMethod'\nimport {\n createTimeoutFetchMethod,\n type TimeoutFetchMethodOptions,\n} from './createTimeoutFetchMethod'\nimport type { FetchMethod } from './Fetch'\n\nconst logger = createScopedLogger('ApiClient:Fetch')\n\n/**\n * Options for {@link createProtectedFetchMethod}, combining timeout and retry behavior.\n *\n * @see {@link RetryFetchMethodOptions}\n * @see {@link TimeoutFetchMethodOptions}\n *\n * @public\n */\nexport interface ProtectedFetchMethodOptions\n extends RetryFetchMethodOptions, TimeoutFetchMethodOptions {}\n\n/**\n * Creates a {@link FetchMethod} that combines timeout and retry protection.\n *\n * @param options - Configuration options for both timeout and retry behavior.\n * @returns A {@link FetchMethod} that applies timeout and retry logic to requests.\n *\n * @throws Error\n * Rethrows the original error after logging, including abort errors.\n *\n * @remarks\n * The resulting method first wraps the base fetch with a timeout (via\n * {@link createTimeoutFetchMethod}), then applies retry behavior (via\n * {@link createRetryFetchMethod}).\n *\n * If an error is thrown during configuration or request execution, it is logged.\n *\n * @example\n * ```ts\n * const fetchProtected = createProtectedFetchMethod({\n * apiName: 'Optimization',\n * requestTimeout: 4000,\n * retries: 2,\n * })\n *\n * const response = await fetchProtected('https://example.com/experiences', {\n * method: 'GET',\n * })\n * ```\n *\n * @public\n */\nexport function createProtectedFetchMethod(options: ProtectedFetchMethodOptions): FetchMethod {\n try {\n const timeoutFetchMethod = createTimeoutFetchMethod(options)\n const retryFetchMethod = createRetryFetchMethod({ ...options, fetchMethod: timeoutFetchMethod })\n\n return retryFetchMethod\n } catch (error) {\n if (error instanceof Error) {\n if (error.name === 'AbortError') {\n logger.warn('Request aborted due to network issues. This request may not be retried.')\n } else {\n logger.error('Request failed:', error)\n }\n }\n throw error\n }\n}\n","import { createProtectedFetchMethod } from './createProtectedFetchMethod'\n\n/**\n * Signature of a fetch method used by the API clients.\n *\n * @param url - The request URL.\n * @param init - Initialization options passed to `fetch`.\n * @returns A promise that resolves with the {@link Response}.\n *\n * @remarks\n * This abstraction allows the underlying implementation to be replaced,\n * for example in tests or different runtime environments.\n *\n * @example\n * ```ts\n * const method: FetchMethod = async (url, init) => {\n * return fetch(url, init)\n * }\n * ```\n *\n * @public\n */\nexport type FetchMethod = (url: string | URL, init: RequestInit) => Promise<Response>\n\n/**\n * Base options shared across fetch method factories.\n *\n * @public\n */\nexport interface BaseFetchMethodOptions {\n /**\n * Human-readable name of the API being called.\n *\n * @remarks\n * Used primarily for logging and error messages.\n */\n apiName?: string\n\n /**\n * Custom fetch implementation to use instead of the global `fetch`.\n *\n * @remarks\n * This is useful for providing polyfills, mocks, or instrumented fetch\n * implementations.\n */\n fetchMethod?: FetchMethod\n}\n\n/**\n * Options passed to callback functions invoked by fetch wrappers.\n *\n * @remarks\n * Not all fields are guaranteed to be present in all callback scenarios.\n *\n * @public\n */\nexport interface FetchMethodCallbackOptions {\n /**\n * Name of the API associated with the request.\n */\n apiName?: string\n\n /**\n * Error that caused the callback to be invoked, if available.\n */\n error?: Error\n\n /**\n * The current attempt number (for retry callbacks).\n */\n attemptNumber?: number\n\n /**\n * Number of retry attempts remaining (for retry callbacks).\n */\n retriesLeft?: number\n}\n\n/**\n * Namespace-like object providing factory methods for protected fetch functions.\n *\n * @public\n */\nconst Fetch = {\n /**\n * Creates a fully protected fetch method with timeout and retry behavior.\n *\n * @example\n * ```ts\n * const fetchMethod = Fetch.create({\n * apiName: 'Optimization',\n * requestTimeout: 3000,\n * retries: 2,\n * })\n *\n * const response = await fetchMethod('https://example.com', { method: 'GET' })\n * ```\n *\n * @see {@link createProtectedFetchMethod}\n */\n create: createProtectedFetchMethod,\n}\n\nexport default Fetch\n","import Fetch from './Fetch'\n\nexport * from './createProtectedFetchMethod'\nexport * from './createRetryFetchMethod'\nexport * from './createTimeoutFetchMethod'\nexport * from './Fetch'\n\nexport default Fetch\n","import Fetch, { type FetchMethod, type ProtectedFetchMethodOptions } from './fetch'\nimport { createScopedLogger } from './logger'\n\nconst logger = createScopedLogger('ApiClient')\n\n/**\n * Default Contentful environment used when none is explicitly provided.\n *\n * @internal\n */\nconst DEFAULT_ENVIRONMENT = 'main'\n\n/**\n * Configuration options for API clients extending `ApiClientBase`.\n *\n * @public\n */\nexport interface ApiConfig {\n /**\n * Base URL for the API.\n *\n * @remarks\n * When omitted, the concrete client is expected to construct full URLs\n * internally.\n */\n baseUrl?: string\n\n /**\n * Contentful environment identifier.\n *\n * @defaultValue `'main'`\n */\n environment?: string\n\n /**\n * Options used to configure the underlying protected fetch method.\n *\n * @remarks\n * `apiName` is derived from the client name and must not be provided here.\n */\n fetchOptions?: Omit<ProtectedFetchMethodOptions, 'apiName'>\n\n /**\n * Client identifier used for authentication or tracking.\n */\n clientId: string\n}\n\n/**\n * Properties that can be shared between global and per-client API configuration.\n *\n * @public\n */\nexport type GlobalApiConfigProperties = 'environment' | 'fetchOptions' | 'clientId'\n\n/**\n * Base class for API clients that provides shared configuration and error logging.\n *\n * @remarks\n * This abstract class is intended for internal use within the package and\n * must not be treated as part of the public API surface.\n *\n * Concrete API clients must extend this class to inherit consistent logging\n * behavior and fetch configuration.\n *\n * @example\n * ```ts\n * interface MyClientConfig extends ApiConfig {\n * // additional config\n * }\n *\n * class MyClient extends ApiClientBase {\n * constructor(config: MyClientConfig) {\n * super('MyClient', config)\n * }\n *\n * async getSomething() {\n * const response = await this.fetch('https://example.com', { method: 'GET' })\n * return response.json()\n * }\n * }\n * ```\n *\n * @internal\n */\nabstract class ApiClientBase {\n /**\n * Name of the API client, used in log messages and as the `apiName` for fetch.\n */\n protected readonly name: string\n\n /**\n * Client identifier used for authentication or tracking.\n */\n protected readonly clientId: string\n\n /**\n * Contentful environment associated with this client.\n */\n protected readonly environment: string\n\n /**\n * Protected fetch method used by the client to perform HTTP requests.\n */\n protected readonly fetch: FetchMethod\n\n /**\n * Creates a new API client base instance.\n *\n * @param name - Human-readable name of the client (used for logging and `apiName`).\n * @param config - Configuration options for the client.\n */\n constructor(name: string, { fetchOptions, clientId, environment }: ApiConfig) {\n this.clientId = clientId\n this.environment = environment ?? DEFAULT_ENVIRONMENT\n this.name = name\n\n this.fetch = Fetch.create({ ...(fetchOptions ?? {}), apiName: name })\n }\n\n /**\n * Logs errors that occur during API requests with standardized messages.\n *\n * @param error - The error thrown by the underlying operation.\n * @param options - Additional metadata about the request.\n * @param options.requestName - Human-readable name of the request operation.\n *\n * @remarks\n * Abort errors are logged at `warn` level and other errors at `error` level.\n * The log message includes the client name for better debugging context.\n */\n protected logRequestError(error: unknown, { requestName }: { requestName: string }): void {\n if (error instanceof Error) {\n if (error.name === 'AbortError') {\n logger.warn(\n `[${this.name}] \"${requestName}\" request aborted due to network issues. This request may not be retried.`,\n )\n } else {\n logger.error(`[${this.name}] \"${requestName}\" request failed:`, error)\n }\n }\n }\n}\n\nexport default ApiClientBase\n","import {\n BatchExperienceRequestData,\n BatchExperienceResponse,\n ExperienceEventArray,\n ExperienceRequestData,\n ExperienceResponse,\n parseWithFriendlyError,\n type BatchExperienceEventArray,\n type BatchExperienceResponseData,\n type ExperienceRequestOptions as ExperienceRequestBodyOptions,\n type OptimizationData,\n} from '@contentful/optimization-api-schemas'\nimport ApiClientBase, { type ApiConfig } from '../ApiClientBase'\nimport { createScopedLogger } from '../logger'\n\nconst logger = createScopedLogger('ApiClient:Experience')\n\n/**\n * Default base URL for the Experience API.\n *\n * @public\n */\nexport const EXPERIENCE_BASE_URL = 'https://experience.ninetailed.co/'\n\n/**\n * Feature flags supported by the Experience API.\n *\n * @internal\n */\nexport type Feature = 'ip-enrichment' | 'location'\n\n/**\n * Options that control how requests to the Experience API are handled.\n *\n * @public\n */\nexport interface ExperienceApiClientRequestOptions {\n /**\n * Enabled features (for example, `\"ip-enrichment\"`) for the API to use for this request.\n *\n * @remarks\n * When omitted, the API can apply a default set of features.\n */\n enabledFeatures?: Feature[]\n\n /**\n * IP address to override the API behavior for IP analysis.\n *\n * @remarks\n * Commonly used in ESR or SSR environments, as the API otherwise uses\n * the server IP.\n */\n ip?: string\n\n /**\n * Experience API `locale` query parameter used to translate profile location fields such as\n * `location.city` and `location.country`.\n *\n * @remarks\n * When omitted, the API can use a server-side default.\n */\n locale?: string\n\n /**\n * When `true`, sends performance-critical endpoints in plain text.\n *\n * @remarks\n * The Ninetailed API accepts certain endpoints in plain text to avoid CORS\n * preflight requests, which can improve performance in browser environments.\n */\n plainText?: boolean\n\n /**\n * When `true`, instructs the API to aggregate a new profile state but not store it.\n *\n * @remarks\n * This is commonly used in ESR or SSR environments where you want to\n * preview the result without persisting changes.\n */\n preflight?: boolean\n}\n\n/**\n * Internal options for profile mutation requests.\n *\n * @internal\n */\ninterface ProfileMutationRequestOptions {\n url: string\n body: unknown\n options: ExperienceApiClientRequestOptions\n}\n\n/**\n * Parameters used when creating a profile.\n *\n * @public\n */\nexport interface CreateProfileParams {\n /**\n * Events used to aggregate the profile state.\n */\n events: ExperienceEventArray\n}\n\n/**\n * Parameters used when updating an existing profile.\n *\n * @public\n */\nexport interface UpdateProfileParams extends CreateProfileParams {\n /**\n * ID of the profile to update.\n */\n profileId: string\n}\n\n/**\n * Parameters used when creating or updating a profile.\n *\n * @public\n */\nexport interface UpsertProfileParams extends CreateProfileParams {\n /**\n * Optional ID of the profile; when omitted, a new profile is created.\n */\n profileId?: string\n}\n\n/**\n * Parameters used when performing a batch profile update.\n *\n * @public\n */\nexport interface BatchUpdateProfileParams {\n /**\n * Batch of events to process.\n */\n events: BatchExperienceEventArray\n}\n\n/**\n * Configuration for {@link ExperienceApiClient}.\n *\n * @public\n */\nexport interface ExperienceApiClientConfig extends ApiConfig, ExperienceApiClientRequestOptions {}\n\n/**\n * Client for interacting with the Experience API.\n *\n * @remarks\n * This client is responsible for reading and mutating Ninetailed profiles\n * using the Experience API.\n *\n * @example\n * ```ts\n * const client = new ExperienceApiClient({\n * clientId: 'org-id',\n * environment: 'main',\n * })\n *\n * const profile = await client.getProfile('profile-id')\n * ```\n *\n * Extends `ApiClientBase`.\n *\n * @public\n */\nexport default class ExperienceApiClient extends ApiClientBase {\n /**\n * Base URL used for Experience API requests.\n */\n protected readonly baseUrl: string\n\n private readonly enabledFeatures?: ExperienceApiClientRequestOptions['enabledFeatures']\n private readonly ip?: ExperienceApiClientRequestOptions['ip']\n private locale?: ExperienceApiClientRequestOptions['locale']\n private readonly plainText?: ExperienceApiClientRequestOptions['plainText']\n private readonly preflight?: ExperienceApiClientRequestOptions['preflight']\n\n /**\n * Creates a new {@link ExperienceApiClient} instance.\n *\n * @param config - Configuration for the Experience API client.\n */\n constructor(config: ExperienceApiClientConfig) {\n super('Experience', config)\n\n const { baseUrl, enabledFeatures, ip, locale, plainText, preflight } = config\n\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing -- Set default for anything falsey\n this.baseUrl = baseUrl || EXPERIENCE_BASE_URL\n this.enabledFeatures = enabledFeatures\n this.ip = ip\n this.locale = locale\n this.plainText = plainText\n this.preflight = preflight\n }\n\n /**\n * Update the default Experience API locale used when request options omit `locale`.\n *\n * @param locale - Next default Experience API locale.\n *\n * @public\n */\n public setLocale(locale: ExperienceApiClientRequestOptions['locale']): void {\n this.locale = locale\n }\n\n /**\n * Retrieves a profile by ID.\n *\n * @param id - The profile ID to retrieve.\n * @param options - Optional request options. `preflight` and `plainText` are not allowed here.\n * @returns The current optimization data for the profile.\n *\n * @throws Error\n * Thrown if `id` is missing or the underlying request fails.\n *\n * @example\n * ```ts\n * const profile = await client.getProfile('profile-id', {\n * locale: 'en-US',\n * })\n * ```\n */\n public async getProfile(\n id: string,\n options: Omit<ExperienceApiClientRequestOptions, 'preflight' | 'plainText'> = {},\n ): Promise<OptimizationData> {\n if (!id) throw new Error('Valid profile ID required.')\n\n const requestName = 'Get Profile'\n\n logger.info(`Sending \"${requestName}\" request`)\n\n try {\n const response = await this.fetch(\n this.constructUrl(\n `v2/organizations/${this.clientId}/environments/${this.environment}/profiles/${id}`,\n options,\n ),\n {\n method: 'GET',\n },\n )\n\n const {\n data: { changes, experiences, profile },\n } = parseWithFriendlyError(ExperienceResponse, await response.json())\n\n const data = { changes, selectedOptimizations: experiences, profile }\n\n logger.debug(`\"${requestName}\" request successfully completed`)\n\n return data\n } catch (error) {\n this.logRequestError(error, { requestName })\n\n throw error\n }\n }\n\n /**\n * Sends a POST request to mutate a profile or profiles.\n *\n * @param request - Mutation request options including URL, body, and request options.\n * @returns The raw {@link Response} from the underlying fetch.\n *\n * @internal\n */\n private async makeProfileMutationRequest({\n url,\n body,\n options,\n }: ProfileMutationRequestOptions): Promise<Response> {\n return await this.fetch(this.constructUrl(url, options), {\n method: 'POST',\n headers: this.constructHeaders(options),\n body: JSON.stringify(body),\n keepalive: true,\n })\n }\n\n /**\n * Creates a profile and returns the resulting optimization data.\n *\n * @param params - Parameters containing the events to aggregate into the profile.\n * @param options - Optional request options.\n * @returns The optimization data for the newly created profile.\n *\n * @remarks\n * The returned profile ID can be used for subsequent update requests.\n *\n * @example\n * ```ts\n * const data = await client.createProfile({\n * events: [{ type: 'identify', userId: 'user-123' }],\n * })\n * ```\n */\n public async createProfile(\n { events }: CreateProfileParams,\n options: ExperienceApiClientRequestOptions = {},\n ): Promise<OptimizationData> {\n const requestName = 'Create Profile'\n\n logger.info(`Sending \"${requestName}\" request`)\n\n const body = this.constructExperienceRequestBody(events, options)\n\n logger.debug(`\"${requestName}\" request body:`, body)\n\n try {\n const response = await this.makeProfileMutationRequest({\n url: `v2/organizations/${this.clientId}/environments/${this.environment}/profiles`,\n body,\n options,\n })\n\n const {\n data: { changes, experiences, profile },\n } = parseWithFriendlyError(ExperienceResponse, await response.json())\n\n const data = { changes, selectedOptimizations: experiences, profile }\n\n logger.debug(`\"${requestName}\" request successfully completed`)\n\n return data\n } catch (error) {\n this.logRequestError(error, { requestName })\n\n throw error\n }\n }\n\n /**\n * Updates an existing profile with the given profile ID.\n *\n * @param params - Parameters including the profile ID and events.\n * @param options - Optional request options.\n * @returns The updated optimization data for the profile.\n *\n * @throws Error\n * Thrown if `profileId` is missing or the underlying request fails.\n *\n * @example\n * ```ts\n * const data = await client.updateProfile({\n * profileId: 'profile-id',\n * events: [{ type: 'track', event: 'viewed_video' }],\n * })\n * ```\n */\n public async updateProfile(\n { profileId, events }: UpdateProfileParams,\n options: ExperienceApiClientRequestOptions = {},\n ): Promise<OptimizationData> {\n if (!profileId) throw new Error('Valid profile ID required.')\n\n const requestName = 'Update Profile'\n\n logger.info(`Sending \"${requestName}\" request`)\n\n const body = this.constructExperienceRequestBody(events, options)\n\n logger.debug(`\"${requestName}\" request body:`, body)\n\n try {\n const response = await this.makeProfileMutationRequest({\n url: `v2/organizations/${this.clientId}/environments/${this.environment}/profiles/${profileId}`,\n body,\n options,\n })\n\n const {\n data: { changes, experiences, profile },\n } = parseWithFriendlyError(ExperienceResponse, await response.json())\n\n const data = { changes, selectedOptimizations: experiences, profile }\n\n logger.debug(`\"${requestName}\" request successfully completed`)\n\n return data\n } catch (error) {\n this.logRequestError(error, { requestName })\n\n throw error\n }\n }\n\n /**\n * Creates or updates a profile depending on whether a `profileId` is provided.\n *\n * @param params - Parameters including optional profile ID and events.\n * @param options - Optional request options.\n * @returns The resulting optimization data.\n *\n * @example\n * ```ts\n * // Create\n * await client.upsertProfile({ events })\n *\n * // Update\n * await client.upsertProfile({ profileId: 'profile-id', events })\n * ```\n */\n public async upsertProfile(\n { profileId, events }: UpsertProfileParams,\n options?: ExperienceApiClientRequestOptions,\n ): Promise<OptimizationData> {\n if (!profileId) {\n return await this.createProfile({ events }, options)\n } else {\n return await this.updateProfile({ profileId, events }, options)\n }\n }\n\n /**\n * Sends multiple events to the Ninetailed Experience API to upsert many profiles.\n *\n * @param params - Parameters containing the batch of events.\n * @param options - Optional request options.\n * @returns The list of profiles affected by the batch operation.\n *\n * @remarks\n * Batch requests must contain at least one event. Every event must contain\n * an anonymous ID. Profiles will be created or updated according to the\n * anonymous ID.\n *\n * This method is intended to be used from server environments.\n *\n * @example\n * ```ts\n * const profiles = await client.upsertManyProfiles({\n * events: [\n * { anonymousId: 'anon-1', type: 'identify', ... },\n * { anonymousId: 'anon-2', type: 'identify', ... },\n * ],\n * })\n * ```\n */\n public async upsertManyProfiles(\n { events }: BatchUpdateProfileParams,\n options: ExperienceApiClientRequestOptions = {},\n ): Promise<BatchExperienceResponseData['profiles']> {\n const requestName = 'Upsert Many Profiles'\n\n logger.info(`Sending \"${requestName}\" request`)\n\n const body = parseWithFriendlyError(BatchExperienceRequestData, {\n events,\n options: this.constructBodyOptions(options),\n })\n\n logger.debug(`\"${requestName}\" request body:`, body)\n\n try {\n const response = await this.makeProfileMutationRequest({\n url: `v2/organizations/${this.clientId}/environments/${this.environment}/events`,\n body,\n options: { plainText: false, ...options },\n })\n\n const {\n data: { profiles },\n } = parseWithFriendlyError(BatchExperienceResponse, await response.json())\n\n logger.debug(`\"${requestName}\" request successfully completed`)\n\n return profiles\n } catch (error) {\n this.logRequestError(error, { requestName })\n\n throw error\n }\n }\n\n /**\n * Constructs a request URL with query parameters derived from request options.\n *\n * @param path - Path relative to the Experience API base URL.\n * @param options - Request options that can influence query parameters.\n * @returns The fully constructed URL as a string.\n *\n * @internal\n */\n private constructUrl(path: string, options: ExperienceApiClientRequestOptions): string {\n const url = new URL(path, this.baseUrl)\n const locale = options.locale ?? this.locale\n const preflight = options.preflight ?? this.preflight\n\n if (locale) {\n url.searchParams.set('locale', locale)\n }\n\n if (preflight) {\n url.searchParams.set('type', 'preflight')\n }\n\n return url.toString()\n }\n\n /**\n * Constructs request headers based on request options and default configuration.\n *\n * @param options - Request options that can influence headers.\n * @returns A record of HTTP headers to send with the request.\n *\n * @internal\n */\n private constructHeaders({\n ip = this.ip,\n plainText = this.plainText,\n }: ExperienceApiClientRequestOptions): Record<string, string> {\n const headers = new Map<string, string>()\n\n if (ip) {\n headers.set('X-Force-IP', ip)\n }\n\n if (plainText ?? this.plainText ?? true) {\n headers.set('Content-Type', 'text/plain')\n } else {\n headers.set('Content-Type', 'application/json')\n }\n\n return Object.fromEntries(headers)\n }\n\n /**\n * Constructs the `options` section of the request body for profile mutations.\n *\n * @param options - Request options that can specify enabled features.\n * @returns Experience API body options including feature flags.\n *\n * @internal\n */\n private readonly constructBodyOptions = ({\n enabledFeatures = this.enabledFeatures,\n }: ExperienceApiClientRequestOptions): ExperienceRequestBodyOptions => {\n const bodyOptions: ExperienceRequestBodyOptions = {}\n\n if (enabledFeatures && Array.isArray(enabledFeatures) && enabledFeatures.length > 0) {\n bodyOptions.features = enabledFeatures\n } else {\n bodyOptions.features = ['ip-enrichment', 'location']\n }\n\n return bodyOptions\n }\n\n /**\n * Construct and validate the singular Experience mutation request payload.\n *\n * @param events - Events for the Experience API to evaluate.\n * @param options - Request options that can contribute body options.\n * @returns Validated singular Experience request body.\n *\n * @internal\n */\n private constructExperienceRequestBody(\n events: ExperienceEventArray,\n options: ExperienceApiClientRequestOptions,\n ): ExperienceRequestData {\n return ExperienceRequestData.parse({\n events: parseWithFriendlyError(ExperienceEventArray, events),\n options: this.constructBodyOptions(options),\n })\n }\n}\n","import {\n BatchInsightsEventArray,\n parseWithFriendlyError,\n} from '@contentful/optimization-api-schemas'\nimport ApiClientBase, { type ApiConfig } from '../ApiClientBase'\nimport { createScopedLogger } from '../logger'\n\nconst logger = createScopedLogger('ApiClient:Insights')\n\n/**\n * Default base URL for the Insights ingest API.\n *\n * @public\n */\nexport const INSIGHTS_BASE_URL = 'https://ingest.insights.ninetailed.co/'\n\n/**\n * Options that control how Insights events are sent.\n *\n * @public\n */\nexport interface InsightsApiClientRequestOptions {\n /**\n * Handler used to enqueue events via the Beacon API or a similar mechanism.\n *\n * @param url - Target URL for the batched events.\n * @param data - Array of batched insights events to be sent.\n * @returns `true` if the events were successfully queued, `false` otherwise.\n *\n * @remarks\n * When provided, this handler is preferred over direct `fetch` calls. If it\n * returns `false`, the client falls back to emitting events immediately via\n * `fetch`.\n */\n beaconHandler?: (url: string | URL, data: BatchInsightsEventArray) => boolean\n}\n\n/**\n * Configuration for {@link InsightsApiClient}.\n *\n * @public\n */\nexport interface InsightsApiClientConfig extends ApiConfig, InsightsApiClientRequestOptions {}\n\n/**\n * Client for sending analytics and insights events to the Ninetailed Insights API.\n *\n * @remarks\n * This client is optimized for sending batched events, optionally using a\n * custom beacon-like handler when available.\n *\n * @example\n * ```ts\n * const insightsClient = new InsightsApiClient({\n * clientId: 'org-id',\n * environment: 'main',\n * })\n *\n * await insightsClient.sendBatchEvents([\n * {\n * profile: { id: 'profile-123', ... },\n * events: [\n * {\n * type: 'track',\n * event: 'button_clicked',\n * properties: { id: 'primary-cta' },\n * },\n * ],\n * }\n * ])\n * ```\n *\n * Extends `ApiClientBase`.\n *\n * @public\n */\nexport default class InsightsApiClient extends ApiClientBase {\n /**\n * Base URL used for Insights API requests.\n */\n protected readonly baseUrl: string\n\n /**\n * Optional handler used to enqueue events via the Beacon API or a similar mechanism.\n */\n private readonly beaconHandler: InsightsApiClientRequestOptions['beaconHandler']\n\n /**\n * Creates a new {@link InsightsApiClient} instance.\n *\n * @param config - Configuration for the Insights API client.\n *\n * @example\n * ```ts\n * const client = new InsightsApiClient({\n * clientId: 'org-id',\n * environment: 'main',\n * beaconHandler: (url, data) => {\n * return navigator.sendBeacon(url.toString(), JSON.stringify(data))\n * },\n * })\n * ```\n */\n constructor(config: InsightsApiClientConfig) {\n super('Insights', config)\n\n const { baseUrl, beaconHandler } = config\n\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing -- Set default for anything falsey\n this.baseUrl = baseUrl || INSIGHTS_BASE_URL\n this.beaconHandler = beaconHandler\n }\n\n /**\n * Sends batches of insights events to the Ninetailed Insights API.\n *\n * @param batches - Array of event batches to send.\n * @param options - Optional request options, including a per-call `beaconHandler`.\n * @returns `true` when the event batch is successfully queued by the beacon\n * handler or a direct request is successfully sent, `false` otherwise.\n *\n * @remarks\n * If a `beaconHandler` is provided (either in the method call or in the\n * client configuration) it will be invoked first. When the handler returns\n * `true`, the events are considered successfully queued and no network\n * request is made by this method.\n *\n * If the handler is missing or returns `false`, the events are emitted\n * immediately via `fetch`.\n *\n * @example\n * ```ts\n * const success = await insightsClient.sendBatchEvents(batches)\n * ```\n *\n * @example\n * ```ts\n * // Override beaconHandler for a single call\n * const success = await insightsClient.sendBatchEvents(batches, {\n * beaconHandler: (url, data) => {\n * return navigator.sendBeacon(url.toString(), JSON.stringify(data))\n * },\n * })\n * ```\n */\n public async sendBatchEvents(\n batches: BatchInsightsEventArray,\n options: InsightsApiClientRequestOptions = {},\n ): Promise<boolean> {\n const { beaconHandler = this.beaconHandler } = options\n\n const url = new URL(\n `v1/organizations/${this.clientId}/environments/${this.environment}/events`,\n this.baseUrl,\n )\n\n const body = parseWithFriendlyError(BatchInsightsEventArray, batches)\n\n if (typeof beaconHandler === 'function') {\n logger.debug('Queueing events via beaconHandler')\n\n const beaconSuccessfullyQueued = beaconHandler(url, body)\n\n if (beaconSuccessfullyQueued) {\n return true\n } else {\n logger.warn(\n 'beaconHandler failed to queue events; events will be emitted immediately via fetch',\n )\n }\n }\n\n const requestName = 'Event Batches'\n\n logger.info(`Sending \"${requestName}\" request`)\n\n logger.debug(`\"${requestName}\" request body:`, body)\n\n try {\n await this.fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(body),\n keepalive: true,\n })\n\n logger.debug(`\"${requestName}\" request successfully completed`)\n\n return true\n } catch (error) {\n this.logRequestError(error, { requestName })\n\n return false\n }\n }\n}\n","import type { ApiConfig, GlobalApiConfigProperties } from './ApiClientBase'\nimport { ExperienceApiClient, type ExperienceApiClientConfig } from './experience'\nimport { InsightsApiClient, type InsightsApiClientConfig } from './insights'\n\n/**\n * Configuration for the high-level {@link ApiClient}.\n *\n * @public\n */\nexport interface ApiClientConfig extends Pick<ApiConfig, GlobalApiConfigProperties> {\n /**\n * Configuration for the Experience API client.\n *\n * @remarks\n * Shared fields (`clientId`, `environment`, `fetchOptions`) are inherited\n * from top-level config; this object is for Experience-specific options.\n */\n experience?: Omit<ExperienceApiClientConfig, GlobalApiConfigProperties>\n\n /**\n * Configuration for the Insights API client.\n *\n * @remarks\n * Shared fields (`clientId`, `environment`, `fetchOptions`) are inherited\n * from top-level config; this object is for Insights-specific options.\n */\n insights?: Omit<InsightsApiClientConfig, GlobalApiConfigProperties>\n}\n\n/**\n * Aggregated API client providing access to Experience and Insights APIs.\n *\n * @remarks\n * This client encapsulates shared configuration and exposes dedicated\n * sub-clients for experience and insights use cases.\n *\n * @example\n * ```ts\n * const client = new ApiClient({\n * clientId: 'org-id',\n * environment: 'main',\n * experience: {\n * // experience-specific overrides\n * },\n * insights: {\n * // insights-specific overrides\n * },\n * })\n *\n * const profile = await client.experience.getProfile('profile-id')\n * await client.insights.sendBatchEvents(batches)\n * ```\n *\n * @see {@link ExperienceApiClient}\n * @see {@link InsightsApiClient}\n *\n * @public\n */\nexport default class ApiClient {\n /**\n * Shared configuration applied to both Experience and Insights clients.\n *\n * @see {@link ApiConfig}\n */\n readonly config: ApiConfig\n\n /**\n * Client for experience-related operations.\n *\n * @see {@link ExperienceApiClient}\n */\n readonly experience: ExperienceApiClient\n\n /**\n * Client for insights-related operations.\n *\n * @see {@link InsightsApiClient}\n */\n readonly insights: InsightsApiClient\n\n /**\n * Creates a new aggregated {@link ApiClient} instance.\n *\n * @param config - Global API client configuration with optional per-client overrides.\n */\n constructor(config: ApiClientConfig) {\n const { experience, insights, clientId, environment, fetchOptions } = config\n const apiConfig: ApiConfig = {\n clientId,\n environment,\n fetchOptions,\n }\n\n this.config = apiConfig\n\n this.experience = new ExperienceApiClient({\n ...apiConfig,\n ...experience,\n })\n\n this.insights = new InsightsApiClient({\n ...apiConfig,\n ...insights,\n })\n }\n}\n"],"names":["LogSink","logLevelSeverity","Logger","logLocation","sink","existingSink","name","message","args","level","String","event","logger","createScopedLogger","location","__webpack_require__","definition","key","Object","obj","prop","Symbol","DEFAULT_INTERVAL_TIMEOUT","DEFAULT_RETRY_COUNT","RETRY_RESPONSE_STATUS","HTTP_ERROR_RESPONSE_STATUS","HttpError","Error","status","createRetryFetchCallback","apiName","controller","fetchMethod","fetch","init","url","response","httpError","error","delayRetry","intervalTimeout","promise","resolve","Promise","setTimeout","undefined","createRetryFetchMethod","onFailedAttempt","retries","AbortController","maxAttempts","attemptFetch","attemptNumber","retriesLeft","DEFAULT_REQUEST_TIMEOUT","createTimeoutFetchMethod","onRequestTimeout","requestTimeout","id","requestInit","clearTimeout","createProtectedFetchMethod","options","timeoutFetchMethod","retryFetchMethod","Fetch","DEFAULT_ENVIRONMENT","ApiClientBase","fetchOptions","clientId","environment","requestName","EXPERIENCE_BASE_URL","ExperienceApiClient","config","baseUrl","enabledFeatures","ip","locale","plainText","preflight","changes","experiences","profile","parseWithFriendlyError","ExperienceResponse","data","body","JSON","events","profileId","BatchExperienceRequestData","profiles","BatchExperienceResponse","path","URL","headers","Map","bodyOptions","Array","ExperienceRequestData","ExperienceEventArray","INSIGHTS_BASE_URL","InsightsApiClient","beaconHandler","batches","BatchInsightsEventArray","beaconSuccessfullyQueued","ApiClient","experience","insights","apiConfig"],"mappings":";;;;;;QAkBA,MAAeA;QAWf;QAEA,gCAAeA;;;;;;QCHR,MAAMC,mBAAwD;YACnE,OAAO;YACP,OAAO;YACP,MAAM;YACN,MAAM;YACN,OAAO;YACP,KAAK;QACP;;;;;;QCpBO,MAAMC;YAEF,OAAO,2BAA0B;YAEzB,eAAe;gBAAC;gBAAQ;aAAO;YAC/B,YAAY,IAAG;YACxB,QAAmB,EAAE;YAErB,uBAAuBC,WAAmB,EAAU;gBAC1D,OAAO,CAAC,CAAC,EAAE;uBAAI,IAAI,CAAC,YAAY;oBAAEA;iBAAY,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC,CAAC;YACxE;YAeO,QAAQC,IAAa,EAAQ;gBAClC,IAAI,CAAC,KAAK,GAAG;uBAAI,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAACC,eAAiBA,aAAa,IAAI,KAAK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BACZ,GAAGD,QAAQ;YACb;QACF;IACF"}
|
|
1
|
+
{"version":3,"file":"index.cjs","sources":["../src/lib/logger/LogSink.ts","../src/lib/logger/logging.ts","../src/lib/logger/Logger.ts","../src/lib/logger/ConsoleLogSink.ts","webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../src/fetch/fetchInputToString.ts","../src/fetch/resolveFetchMethod.ts","../src/fetch/createRetryFetchMethod.ts","../src/fetch/createTimeoutFetchMethod.ts","../src/fetch/createProtectedFetchMethod.ts","../src/fetch/Fetch.ts","../src/fetch/index.ts","../src/ApiClientBase.ts","../src/experience/ExperienceApiClient.ts","../src/insights/InsightsApiClient.ts","../src/ApiClient.ts"],"sourcesContent":["import type { LogEvent } from './logging'\n\n/**\n * Abstract base class for log sinks that receive and process log events.\n *\n * @example\n * ```typescript\n * class MyCustomSink extends LogSink {\n * name = 'MyCustomSink'\n *\n * ingest(event: LogEvent): void {\n * // process the event\n * }\n * }\n * ```\n *\n * @public\n */\nabstract class LogSink {\n /** Display name used to identify this sink for addition and removal. */\n abstract name: string\n\n /**\n * Processes an incoming log event.\n *\n * @param event - The log event to process.\n * @returns Nothing.\n */\n abstract ingest(event: LogEvent): void\n}\n\nexport default LogSink\n","/**\n * Supported log levels ordered from highest to lowest severity.\n *\n * @public\n */\nexport type LogLevels = 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'log'\n\n/**\n * A log event emitted by the logger package.\n *\n * @public\n */\nexport interface LogEvent {\n /** Logger scope name. */\n name: string\n /** Event severity level. */\n level: LogLevels\n /** Event payload, where the first entry is the formatted message. */\n messages: unknown[]\n /** Optional additional context attached by sinks or middleware. */\n [other: string]: unknown\n}\n\n/**\n * Numeric severity map used for log-level threshold comparisons.\n *\n * @public\n */\nexport const logLevelSeverity: Readonly<Record<LogLevels, number>> = {\n fatal: 60,\n error: 50,\n warn: 40,\n info: 30,\n debug: 20,\n log: 10,\n}\n","import type LogSink from './LogSink'\nimport type { LogEvent, LogLevels } from './logging'\n\n/**\n * Central logger that routes log events through registered {@link LogSink} instances.\n *\n * @example\n * ```typescript\n * import { logger } from '@contentful/optimization-api-client/logger'\n *\n * logger.info('MyModule', 'Application started')\n * ```\n *\n * @public\n */\nexport class Logger {\n /** The logger's identifier, used as the event scope name. */\n readonly name = '@contentful/optimization'\n\n private readonly PREFIX_PARTS = ['Ctfl', 'O10n']\n private readonly DELIMITER = ':'\n private sinks: LogSink[] = []\n\n private assembleLocationPrefix(logLocation: string): string {\n return `[${[...this.PREFIX_PARTS, logLocation].join(this.DELIMITER)}]`\n }\n\n /**\n * Registers a log sink. If a sink with the same name already exists, it is replaced.\n *\n * @param sink - The {@link LogSink} instance to register.\n * @returns Nothing.\n *\n * @example\n * ```typescript\n * import { logger, ConsoleLogSink } from '@contentful/optimization-api-client/logger'\n *\n * logger.addSink(new ConsoleLogSink('debug'))\n * ```\n */\n public addSink(sink: LogSink): void {\n this.sinks = [...this.sinks.filter((existingSink) => existingSink.name !== sink.name), sink]\n }\n\n /**\n * Removes a registered sink by name.\n *\n * @param name - The name of the sink to remove.\n * @returns Nothing.\n *\n * @example\n * ```typescript\n * logger.removeSink('ConsoleLogSink')\n * ```\n */\n public removeSink(name: string): void {\n this.sinks = this.sinks.filter((sink) => sink.name !== name)\n }\n\n /**\n * Removes all registered sinks.\n *\n * @returns Nothing.\n *\n * @example\n * ```typescript\n * logger.removeSinks()\n * ```\n */\n public removeSinks(): void {\n this.sinks = []\n }\n\n /**\n * Logs a message at the debug level.\n *\n * @param logLocation - The module or component identifier.\n * @param message - The log message.\n * @param args - Additional arguments forwarded in the log event.\n * @returns Nothing.\n *\n * @example\n * ```typescript\n * logger.debug('MyModule', 'Debugging value', someVariable)\n * ```\n */\n public debug(logLocation: string, message: string, ...args: unknown[]): void {\n this.emit('debug', logLocation, message, ...args)\n }\n\n /**\n * Logs a message at the info level.\n *\n * @param logLocation - The module or component identifier.\n * @param message - The log message.\n * @param args - Additional arguments forwarded in the log event.\n * @returns Nothing.\n *\n * @example\n * ```typescript\n * logger.info('MyModule', 'Operation completed')\n * ```\n */\n public info(logLocation: string, message: string, ...args: unknown[]): void {\n this.emit('info', logLocation, message, ...args)\n }\n\n /**\n * Logs a message at the log level.\n *\n * @param logLocation - The module or component identifier.\n * @param message - The log message.\n * @param args - Additional arguments forwarded in the log event.\n * @returns Nothing.\n *\n * @example\n * ```typescript\n * logger.log('MyModule', 'General log entry')\n * ```\n */\n public log(logLocation: string, message: string, ...args: unknown[]): void {\n this.emit('log', logLocation, message, ...args)\n }\n\n /**\n * Logs a message at the warn level.\n *\n * @param logLocation - The module or component identifier.\n * @param message - The log message.\n * @param args - Additional arguments forwarded in the log event.\n * @returns Nothing.\n *\n * @example\n * ```typescript\n * logger.warn('MyModule', 'Deprecated method called')\n * ```\n */\n public warn(logLocation: string, message: string, ...args: unknown[]): void {\n this.emit('warn', logLocation, message, ...args)\n }\n\n /**\n * Logs a message at the error level.\n *\n * @param logLocation - The module or component identifier.\n * @param message - The log message or Error object.\n * @param args - Additional arguments forwarded in the log event.\n * @returns Nothing.\n *\n * @example\n * ```typescript\n * logger.error('MyModule', new Error('Something failed'))\n * ```\n */\n public error(logLocation: string, message: string | Error, ...args: unknown[]): void {\n this.emit('error', logLocation, message, ...args)\n }\n\n /**\n * Logs a message at the fatal level.\n *\n * @param logLocation - The module or component identifier.\n * @param message - The log message or Error object.\n * @param args - Additional arguments forwarded in the log event.\n * @returns Nothing.\n *\n * @example\n * ```typescript\n * logger.fatal('MyModule', new Error('Unrecoverable failure'))\n * ```\n */\n public fatal(logLocation: string, message: string | Error, ...args: unknown[]): void {\n this.emit('fatal', logLocation, message, ...args)\n }\n\n private emit(\n level: LogLevels,\n logLocation: string,\n message: string | Error,\n ...args: unknown[]\n ): void {\n this.onLogEvent({\n name: this.name,\n level,\n messages: [`${this.assembleLocationPrefix(logLocation)} ${String(message)}`, ...args],\n })\n }\n\n private onLogEvent(event: LogEvent): void {\n this.sinks.forEach((sink) => {\n sink.ingest(event)\n })\n }\n}\n\n/**\n * Shared singleton {@link Logger} instance used across the SDK.\n *\n * @public\n */\nexport const logger = new Logger()\n\n/**\n * A location-scoped logger interface whose methods omit the `logLocation` parameter.\n *\n * @public\n */\nexport interface ScopedLogger {\n /** Logs at debug level. */\n debug: (message: string, ...args: unknown[]) => void\n /** Logs at info level. */\n info: (message: string, ...args: unknown[]) => void\n /** Logs at log level. */\n log: (message: string, ...args: unknown[]) => void\n /** Logs at warn level. */\n warn: (message: string, ...args: unknown[]) => void\n /** Logs at error level. */\n error: (message: string | Error, ...args: unknown[]) => void\n /** Logs at fatal level. */\n fatal: (message: string | Error, ...args: unknown[]) => void\n}\n\n/**\n * Creates a {@link ScopedLogger} that automatically prepends the given location to every log call.\n *\n * @param location - The module or component identifier to prepend.\n * @returns A {@link ScopedLogger} bound to the specified location.\n *\n * @example\n * ```typescript\n * import { createScopedLogger } from '@contentful/optimization-api-client/logger'\n *\n * const log = createScopedLogger('MyModule')\n * log.info('Initialization complete')\n * ```\n *\n * @public\n */\nexport function createScopedLogger(location: string): ScopedLogger {\n return {\n debug: (message: string, ...args: unknown[]) => {\n logger.debug(location, message, ...args)\n },\n info: (message: string, ...args: unknown[]) => {\n logger.info(location, message, ...args)\n },\n log: (message: string, ...args: unknown[]) => {\n logger.log(location, message, ...args)\n },\n warn: (message: string, ...args: unknown[]) => {\n logger.warn(location, message, ...args)\n },\n error: (message: string | Error, ...args: unknown[]) => {\n logger.error(location, message, ...args)\n },\n fatal: (message: string | Error, ...args: unknown[]) => {\n logger.fatal(location, message, ...args)\n },\n }\n}\n","/* eslint-disable no-console -- using console */\nimport { logLevelSeverity, type LogEvent, type LogLevels } from './logging'\nimport LogSink from './LogSink'\n\nconst consoleMap = {\n debug: (...args: unknown[]) => {\n console.debug(...args)\n },\n info: (...args: unknown[]) => {\n console.info(...args)\n },\n log: (...args: unknown[]) => {\n console.log(...args)\n },\n warn: (...args: unknown[]) => {\n console.warn(...args)\n },\n error: (...args: unknown[]) => {\n console.error(...args)\n },\n fatal: (...args: unknown[]) => {\n console.error(...args)\n },\n}\n\n/**\n * A {@link LogSink} that writes log events to the browser or Node.js console,\n * filtering by a configurable verbosity threshold.\n *\n * @example\n * ```typescript\n * import { logger, ConsoleLogSink } from '@contentful/optimization-api-client/logger'\n *\n * logger.addSink(new ConsoleLogSink('debug'))\n * ```\n *\n * @public\n */\nexport class ConsoleLogSink extends LogSink {\n /** Identifies this sink when registered with the {@link Logger}. */\n public name = 'ConsoleLogSink'\n\n /**\n * Minimum log level required for events to be output.\n *\n * @defaultValue 'error'\n */\n readonly verbosity: LogLevels\n\n /**\n * Creates a new ConsoleLogSink.\n *\n * @param verbosity - Minimum log level to output.\n */\n constructor(verbosity?: LogLevels) {\n super()\n\n this.verbosity = verbosity ?? 'error'\n }\n\n /**\n * Writes a log event to the console if its level meets the verbosity threshold.\n *\n * @param event - The log event to process.\n * @returns Nothing.\n */\n ingest(event: LogEvent): void {\n if (logLevelSeverity[event.level] < logLevelSeverity[this.verbosity]) return\n\n consoleMap[event.level](...event.messages)\n }\n}\n","__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import type { FetchMethod } from './Fetch'\n\nexport const fetchInputToString = (input: Parameters<FetchMethod>[0]): string => {\n if (typeof input === 'string') return input\n\n return input.url\n}\n","import type { FetchMethod } from './Fetch'\n\nconst MISSING_FETCH_METHOD_MESSAGE = 'No fetch implementation available. Provide a fetchMethod.'\n\nexport function resolveFetchMethod(fetchMethod?: FetchMethod): FetchMethod {\n if (fetchMethod) return fetchMethod\n\n if (typeof globalThis.fetch === 'function') {\n return globalThis.fetch.bind(globalThis)\n }\n\n throw new Error(MISSING_FETCH_METHOD_MESSAGE)\n}\n","import { createScopedLogger } from '../logger'\nimport type { BaseFetchMethodOptions, FetchMethod, FetchMethodCallbackOptions } from './Fetch'\nimport { fetchInputToString } from './fetchInputToString'\nimport { resolveFetchMethod } from './resolveFetchMethod'\n\nconst logger = createScopedLogger('ApiClient:Retry')\n\n/**\n * Default interval (in milliseconds) between retry attempts.\n *\n * @internal\n */\nconst DEFAULT_INTERVAL_TIMEOUT = 0\n\n/**\n * Default number of retry attempts.\n *\n * @internal\n */\nconst DEFAULT_RETRY_COUNT = 1\n\n/**\n * HTTP status code that triggers a retry.\n *\n * @remarks\n * This value is fixed to `503 Service Unavailable`.\n *\n * @internal\n */\nconst RETRY_RESPONSE_STATUS = 503\n\n/**\n * Default HTTP status code used for {@link HttpError}.\n *\n * @internal\n */\nconst HTTP_ERROR_RESPONSE_STATUS = 500\n\n/**\n * Error type representing HTTP failures with an associated status code.\n *\n * @internal\n */\nclass HttpError extends Error {\n /**\n * The HTTP status code associated with the error.\n */\n public status: number\n\n /**\n * Creates a new {@link HttpError}.\n *\n * @param message - Description of the error.\n * @param status - HTTP status code associated with the error.\n */\n constructor(message: string, status: number = HTTP_ERROR_RESPONSE_STATUS) {\n super(message)\n Object.setPrototypeOf(this, HttpError.prototype)\n this.status = status\n }\n}\n\n/**\n * Configuration options for {@link createRetryFetchMethod}.\n *\n * @public\n */\nexport interface RetryFetchMethodOptions extends BaseFetchMethodOptions {\n /**\n * Delay (in milliseconds) between retry attempts.\n *\n * @defaultValue `0`\n */\n intervalTimeout?: number\n\n /**\n * Callback invoked whenever a retry attempt fails.\n *\n * @param options - Information about the failed attempt.\n *\n * @remarks\n * This callback is invoked with additional metadata such as the attempt\n * number and the number of retries left.\n */\n onFailedAttempt?: (options: FetchMethodCallbackOptions) => void\n\n /**\n * Maximum number of retry attempts.\n *\n * @defaultValue `1`\n */\n retries?: number\n}\n\n/**\n * Internal configuration passed to the retry callback.\n *\n * @internal\n */\ninterface RetryFetchCallbackOptions extends RetryFetchMethodOptions {\n fetchMethod: FetchMethod\n\n /**\n * Abort controller used to cancel the underlying fetch requests.\n */\n controller: AbortController\n\n /**\n * Initialization options passed to the `fetch` implementation.\n */\n init: Parameters<FetchMethod>[1]\n\n /**\n * Request URL.\n */\n url: Parameters<FetchMethod>[0]\n}\n\n/**\n * Creates a callback function used by the retry loop to perform a protected fetch attempt.\n *\n * @param options - Internal options controlling request execution and retry classification.\n * @returns A function that performs one fetch attempt and either:\n * - returns a successful {@link Response},\n * - throws {@link HttpError} for retriable `503` responses, or\n * - aborts and returns `undefined` for non-retriable failures.\n *\n * @internal\n */\nfunction createRetryFetchCallback({\n apiName = 'Optimization',\n controller,\n fetchMethod,\n init,\n url,\n}: RetryFetchCallbackOptions) {\n return async () => {\n const urlLabel = fetchInputToString(url)\n\n try {\n const response = await fetchMethod(url, init)\n\n if (response.status === RETRY_RESPONSE_STATUS) {\n throw new HttpError(\n `${apiName} API request to \"${urlLabel}\" failed with status: \"[${response.status}] ${response.statusText}\".`,\n RETRY_RESPONSE_STATUS,\n )\n }\n\n if (!response.ok) {\n const httpError = new Error(\n `Request to \"${urlLabel}\" failed with status: [${response.status}] ${response.statusText} - traceparent: ${response.headers.get('traceparent')}`,\n )\n logger.error('Request failed with non-OK status:', httpError)\n\n controller.abort()\n\n return\n }\n\n logger.debug(`Response from \"${urlLabel}\":`, response)\n\n return response\n } catch (error) {\n if (error instanceof HttpError && error.status === RETRY_RESPONSE_STATUS) {\n throw error\n }\n\n logger.error(`Request to \"${urlLabel}\" failed:`, error)\n\n controller.abort()\n }\n }\n}\n\n/**\n * Waits for the configured retry delay between attempts.\n *\n * @param intervalTimeout - Delay in milliseconds before the next retry attempt.\n * @returns A promise that resolves immediately when delay is non-positive,\n * otherwise after the timeout elapses.\n *\n * @internal\n */\nasync function delayRetry(intervalTimeout: number): Promise<void> {\n if (intervalTimeout <= 0) {\n return\n }\n\n const { promise, resolve } = Promise.withResolvers<undefined>()\n setTimeout(() => {\n resolve(undefined)\n }, intervalTimeout)\n await promise\n}\n\n/**\n * Creates a {@link FetchMethod} that retries failed requests according to the\n * provided configuration.\n *\n * @param options - Configuration options that control retry behavior.\n * @returns A {@link FetchMethod} that automatically retries qualifying failures.\n *\n * @throws Error\n * Thrown when the request cannot be retried and no successful response is obtained.\n *\n * @remarks\n * This wrapper uses a lightweight internal retry loop and an {@link AbortController}\n * to cancel pending requests when a non-retriable error occurs.\n *\n * @example\n * ```ts\n * const fetchWithRetry = createRetryFetchMethod({\n * apiName: 'Optimization',\n * retries: 3,\n * intervalTimeout: 200,\n * onFailedAttempt: ({ attemptNumber, retriesLeft }) => {\n * console.warn(`Attempt ${attemptNumber} failed. Retries left: ${retriesLeft}`)\n * },\n * })\n *\n * const response = await fetchWithRetry('https://example.com', { method: 'GET' })\n * ```\n *\n * @public\n */\nexport function createRetryFetchMethod({\n apiName = 'Optimization',\n fetchMethod,\n intervalTimeout = DEFAULT_INTERVAL_TIMEOUT,\n onFailedAttempt,\n retries = DEFAULT_RETRY_COUNT,\n}: RetryFetchMethodOptions = {}): FetchMethod {\n const resolvedFetchMethod = resolveFetchMethod(fetchMethod)\n\n return async (url, init) => {\n const controller = new AbortController()\n const maxAttempts = retries + 1\n const attemptFetch = createRetryFetchCallback({\n apiName,\n controller,\n fetchMethod: resolvedFetchMethod,\n init,\n url,\n })\n\n for (let attemptNumber = 1; attemptNumber <= maxAttempts; attemptNumber++) {\n try {\n const response = await attemptFetch()\n\n if (response) {\n return response\n }\n\n break\n } catch (error) {\n if (!(error instanceof HttpError) || error.status !== RETRY_RESPONSE_STATUS) {\n throw error\n }\n\n const retriesLeft = maxAttempts - attemptNumber\n\n onFailedAttempt?.({\n apiName,\n error,\n attemptNumber,\n retriesLeft,\n } satisfies FetchMethodCallbackOptions)\n\n if (retriesLeft === 0) {\n throw error\n }\n\n await delayRetry(intervalTimeout)\n }\n }\n\n throw new Error(`${apiName} API request to \"${fetchInputToString(url)}\" may not be retried.`)\n }\n}\n","import { createScopedLogger } from '../logger'\nimport type { BaseFetchMethodOptions, FetchMethod, FetchMethodCallbackOptions } from './Fetch'\nimport { fetchInputToString } from './fetchInputToString'\nimport { resolveFetchMethod } from './resolveFetchMethod'\n\nconst logger = createScopedLogger('ApiClient:Timeout')\n\n/**\n * Default timeout (in milliseconds) for outgoing requests.\n *\n * @internal\n */\nconst DEFAULT_REQUEST_TIMEOUT = 3000\n\n/** @internal */\nfunction isFetchAbortSignal(signal: unknown): signal is NonNullable<RequestInit['signal']> {\n return typeof signal === 'object' && signal !== null\n}\n\n/**\n * Configuration options for {@link createTimeoutFetchMethod}.\n *\n * @public\n */\nexport interface TimeoutFetchMethodOptions extends BaseFetchMethodOptions {\n /**\n * Callback invoked when a request exceeds the configured timeout.\n *\n * @param options - Information about the timed-out request.\n *\n * @remarks\n * If this callback is not provided, a default error is logged.\n *\n * @see {@link FetchMethodCallbackOptions}\n */\n onRequestTimeout?: (options: FetchMethodCallbackOptions) => void\n\n /**\n * Maximum time (in milliseconds) to wait for a response before aborting the request.\n *\n * @defaultValue `3000`\n */\n requestTimeout?: number\n}\n\n/**\n * Creates a {@link FetchMethod} that aborts requests after a configurable timeout.\n *\n * @param options - Configuration options controlling timeout behavior.\n * @returns A {@link FetchMethod} that enforces a timeout for each request.\n *\n * @remarks\n * When a timeout occurs, the request is aborted using an {@link AbortController}.\n * If `onRequestTimeout` is not provided, an error is logged by the package logger.\n *\n * @example\n * ```ts\n * const fetchWithTimeout = createTimeoutFetchMethod({\n * apiName: 'Optimization',\n * requestTimeout: 5000,\n * onRequestTimeout: ({ apiName }) => {\n * console.warn(`${apiName} request timed out`)\n * },\n * })\n *\n * const response = await fetchWithTimeout('https://example.com', { method: 'GET' })\n * ```\n *\n * @see {@link TimeoutFetchMethodOptions}\n *\n * @public\n */\nexport function createTimeoutFetchMethod({\n apiName = 'Optimization',\n fetchMethod,\n onRequestTimeout,\n requestTimeout = DEFAULT_REQUEST_TIMEOUT,\n}: TimeoutFetchMethodOptions = {}): FetchMethod {\n const resolvedFetchMethod = resolveFetchMethod(fetchMethod)\n\n return async (url, init) => {\n const controller = new AbortController()\n\n const id = setTimeout(() => {\n if (typeof onRequestTimeout === 'function') {\n onRequestTimeout({ apiName })\n } else {\n logger.error(\n `Request to \"${fetchInputToString(url)}\" timed out`,\n new Error('Request timeout'),\n )\n }\n\n controller.abort()\n }, requestTimeout)\n\n const { signal } = controller\n\n if (!isFetchAbortSignal(signal)) {\n throw new Error('AbortController signal is not compatible with fetch.')\n }\n\n const requestInit = { ...init, signal }\n\n const response = await resolvedFetchMethod(url, requestInit)\n\n clearTimeout(id)\n\n return response\n }\n}\n","import { createScopedLogger } from '../logger'\nimport { createRetryFetchMethod, type RetryFetchMethodOptions } from './createRetryFetchMethod'\nimport {\n createTimeoutFetchMethod,\n type TimeoutFetchMethodOptions,\n} from './createTimeoutFetchMethod'\nimport type { FetchMethod } from './Fetch'\n\nconst logger = createScopedLogger('ApiClient:Fetch')\n\n/**\n * Options for {@link createProtectedFetchMethod}, combining timeout and retry behavior.\n *\n * @see {@link RetryFetchMethodOptions}\n * @see {@link TimeoutFetchMethodOptions}\n *\n * @public\n */\nexport interface ProtectedFetchMethodOptions\n extends RetryFetchMethodOptions, TimeoutFetchMethodOptions {}\n\n/**\n * Creates a {@link FetchMethod} that combines timeout and retry protection.\n *\n * @param options - Configuration options for both timeout and retry behavior.\n * @returns A {@link FetchMethod} that applies timeout and retry logic to requests.\n *\n * @throws Error\n * Rethrows the original error after logging, including abort errors.\n *\n * @remarks\n * The resulting method first wraps the base fetch with a timeout (via\n * {@link createTimeoutFetchMethod}), then applies retry behavior (via\n * {@link createRetryFetchMethod}).\n *\n * If an error is thrown during configuration or request execution, it is logged.\n *\n * @example\n * ```ts\n * const fetchProtected = createProtectedFetchMethod({\n * apiName: 'Optimization',\n * requestTimeout: 4000,\n * retries: 2,\n * })\n *\n * const response = await fetchProtected('https://example.com/experiences', {\n * method: 'GET',\n * })\n * ```\n *\n * @public\n */\nexport function createProtectedFetchMethod(options: ProtectedFetchMethodOptions): FetchMethod {\n try {\n const timeoutFetchMethod = createTimeoutFetchMethod(options)\n const retryFetchMethod = createRetryFetchMethod({ ...options, fetchMethod: timeoutFetchMethod })\n\n return retryFetchMethod\n } catch (error) {\n if (error instanceof Error) {\n if (error.name === 'AbortError') {\n logger.warn('Request aborted due to network issues. This request may not be retried.')\n } else {\n logger.error('Request failed:', error)\n }\n }\n throw error\n }\n}\n","import { createProtectedFetchMethod } from './createProtectedFetchMethod'\n\n/**\n * Signature of a fetch method used by the API clients.\n *\n * @param url - The request URL.\n * @param init - Initialization options passed to `fetch`.\n * @returns A promise that resolves with the {@link Response}.\n *\n * @remarks\n * This abstraction allows the underlying implementation to be replaced,\n * for example in tests or different runtime environments.\n *\n * @example\n * ```ts\n * const method: FetchMethod = async (input, init) => {\n * return fetch(input, init)\n * }\n * ```\n *\n * @public\n */\nexport type FetchInput = string | Request\nexport type FetchMethod = (input: FetchInput, init?: RequestInit) => Promise<Response>\n\n/**\n * Base options shared across fetch method factories.\n *\n * @public\n */\nexport interface BaseFetchMethodOptions {\n /**\n * Human-readable name of the API being called.\n *\n * @remarks\n * Used primarily for logging and error messages.\n */\n apiName?: string\n\n /**\n * Custom fetch implementation to use instead of the global `fetch`.\n *\n * @remarks\n * This is useful for providing polyfills, mocks, or instrumented fetch\n * implementations. It is required in runtimes that do not provide\n * `globalThis.fetch`.\n */\n fetchMethod?: FetchMethod\n}\n\n/**\n * Options passed to callback functions invoked by fetch wrappers.\n *\n * @remarks\n * Not all fields are guaranteed to be present in all callback scenarios.\n *\n * @public\n */\nexport interface FetchMethodCallbackOptions {\n /**\n * Name of the API associated with the request.\n */\n apiName?: string\n\n /**\n * Error that caused the callback to be invoked, if available.\n */\n error?: Error\n\n /**\n * The current attempt number (for retry callbacks).\n */\n attemptNumber?: number\n\n /**\n * Number of retry attempts remaining (for retry callbacks).\n */\n retriesLeft?: number\n}\n\n/**\n * Namespace-like object providing factory methods for protected fetch functions.\n *\n * @public\n */\nconst Fetch = {\n /**\n * Creates a fully protected fetch method with timeout and retry behavior.\n *\n * @example\n * ```ts\n * const fetchMethod = Fetch.create({\n * apiName: 'Optimization',\n * requestTimeout: 3000,\n * retries: 2,\n * })\n *\n * const response = await fetchMethod('https://example.com', { method: 'GET' })\n * ```\n *\n * @see {@link createProtectedFetchMethod}\n */\n create: createProtectedFetchMethod,\n}\n\nexport default Fetch\n","import Fetch from './Fetch'\n\nexport * from './createProtectedFetchMethod'\nexport * from './createRetryFetchMethod'\nexport * from './createTimeoutFetchMethod'\nexport * from './Fetch'\n\nexport default Fetch\n","import Fetch, { type FetchMethod, type ProtectedFetchMethodOptions } from './fetch'\nimport { createScopedLogger } from './logger'\n\nconst logger = createScopedLogger('ApiClient')\n\n/**\n * Default Contentful environment used when none is explicitly provided.\n *\n * @internal\n */\nconst DEFAULT_ENVIRONMENT = 'main'\n\n/**\n * Configuration options for API clients extending `ApiClientBase`.\n *\n * @public\n */\nexport interface ApiConfig {\n /**\n * Base URL for the API.\n *\n * @remarks\n * When omitted, the concrete client is expected to construct full URLs\n * internally.\n */\n baseUrl?: string\n\n /**\n * Contentful environment identifier.\n *\n * @defaultValue `'main'`\n */\n environment?: string\n\n /**\n * Options used to configure the underlying protected fetch method.\n *\n * @remarks\n * `apiName` is derived from the client name and must not be provided here.\n */\n fetchOptions?: Omit<ProtectedFetchMethodOptions, 'apiName'>\n\n /**\n * Client identifier used for authentication or tracking.\n */\n clientId: string\n}\n\n/**\n * Properties that can be shared between global and per-client API configuration.\n *\n * @public\n */\nexport type GlobalApiConfigProperties = 'environment' | 'fetchOptions' | 'clientId'\n\n/**\n * Base class for API clients that provides shared configuration and error logging.\n *\n * @remarks\n * This abstract class is intended for internal use within the package and\n * must not be treated as part of the public API surface.\n *\n * Concrete API clients must extend this class to inherit consistent logging\n * behavior and fetch configuration.\n *\n * @example\n * ```ts\n * interface MyClientConfig extends ApiConfig {\n * // additional config\n * }\n *\n * class MyClient extends ApiClientBase {\n * constructor(config: MyClientConfig) {\n * super('MyClient', config)\n * }\n *\n * async getSomething() {\n * const response = await this.fetch('https://example.com', { method: 'GET' })\n * return response.json()\n * }\n * }\n * ```\n *\n * @internal\n */\nabstract class ApiClientBase {\n /**\n * Name of the API client, used in log messages and as the `apiName` for fetch.\n */\n protected readonly name: string\n\n /**\n * Client identifier used for authentication or tracking.\n */\n protected readonly clientId: string\n\n /**\n * Contentful environment associated with this client.\n */\n protected readonly environment: string\n\n /**\n * Protected fetch method used by the client to perform HTTP requests.\n */\n protected readonly fetch: FetchMethod\n\n /**\n * Creates a new API client base instance.\n *\n * @param name - Human-readable name of the client (used for logging and `apiName`).\n * @param config - Configuration options for the client.\n */\n constructor(name: string, { fetchOptions, clientId, environment }: ApiConfig) {\n this.clientId = clientId\n this.environment = environment ?? DEFAULT_ENVIRONMENT\n this.name = name\n\n this.fetch = Fetch.create({ ...(fetchOptions ?? {}), apiName: name })\n }\n\n /**\n * Logs errors that occur during API requests with standardized messages.\n *\n * @param error - The error thrown by the underlying operation.\n * @param options - Additional metadata about the request.\n * @param options.requestName - Human-readable name of the request operation.\n *\n * @remarks\n * Abort errors are logged at `warn` level and other errors at `error` level.\n * The log message includes the client name for better debugging context.\n */\n protected logRequestError(error: unknown, { requestName }: { requestName: string }): void {\n if (error instanceof Error) {\n if (error.name === 'AbortError') {\n logger.warn(\n `[${this.name}] \"${requestName}\" request aborted due to network issues. This request may not be retried.`,\n )\n } else {\n logger.error(`[${this.name}] \"${requestName}\" request failed:`, error)\n }\n }\n }\n}\n\nexport default ApiClientBase\n","import {\n BatchExperienceRequestData,\n BatchExperienceResponse,\n ExperienceEventArray,\n ExperienceRequestData,\n ExperienceResponse,\n parseWithFriendlyError,\n type BatchExperienceEventArray,\n type BatchExperienceResponseData,\n type ExperienceRequestOptions as ExperienceRequestBodyOptions,\n type OptimizationData,\n} from '@contentful/optimization-api-schemas'\nimport ApiClientBase, { type ApiConfig } from '../ApiClientBase'\nimport { createScopedLogger } from '../logger'\n\nconst logger = createScopedLogger('ApiClient:Experience')\n\n/**\n * Default base URL for the Experience API.\n *\n * @public\n */\nexport const EXPERIENCE_BASE_URL = 'https://experience.ninetailed.co/'\n\n/**\n * Feature flags supported by the Experience API.\n *\n * @internal\n */\nexport type Feature = 'ip-enrichment' | 'location'\n\n/**\n * Options that control how requests to the Experience API are handled.\n *\n * @public\n */\nexport interface ExperienceApiClientRequestOptions {\n /**\n * Enabled features (for example, `\"ip-enrichment\"`) for the API to use for this request.\n *\n * @remarks\n * When omitted, the API can apply a default set of features.\n */\n enabledFeatures?: Feature[]\n\n /**\n * IP address to override the API behavior for IP analysis.\n *\n * @remarks\n * Commonly used in ESR or SSR environments, as the API otherwise uses\n * the server IP.\n */\n ip?: string\n\n /**\n * Experience API `locale` query parameter used to translate profile location fields such as\n * `location.city` and `location.country`.\n *\n * @remarks\n * When omitted, the API can use a server-side default.\n */\n locale?: string\n\n /**\n * When `true`, sends performance-critical endpoints in plain text.\n *\n * @remarks\n * The Ninetailed API accepts certain endpoints in plain text to avoid CORS\n * preflight requests, which can improve performance in browser environments.\n */\n plainText?: boolean\n\n /**\n * When `true`, instructs the API to aggregate a new profile state but not store it.\n *\n * @remarks\n * This is commonly used in ESR or SSR environments where you want to\n * preview the result without persisting changes.\n */\n preflight?: boolean\n}\n\n/**\n * Internal options for profile mutation requests.\n *\n * @internal\n */\ninterface ProfileMutationRequestOptions {\n url: string\n body: unknown\n options: ExperienceApiClientRequestOptions\n}\n\n/**\n * Parameters used when creating a profile.\n *\n * @public\n */\nexport interface CreateProfileParams {\n /**\n * Events used to aggregate the profile state.\n */\n events: ExperienceEventArray\n}\n\n/**\n * Parameters used when updating an existing profile.\n *\n * @public\n */\nexport interface UpdateProfileParams extends CreateProfileParams {\n /**\n * ID of the profile to update.\n */\n profileId: string\n}\n\n/**\n * Parameters used when creating or updating a profile.\n *\n * @public\n */\nexport interface UpsertProfileParams extends CreateProfileParams {\n /**\n * Optional ID of the profile; when omitted, a new profile is created.\n */\n profileId?: string\n}\n\n/**\n * Parameters used when performing a batch profile update.\n *\n * @public\n */\nexport interface BatchUpdateProfileParams {\n /**\n * Batch of events to process.\n */\n events: BatchExperienceEventArray\n}\n\n/**\n * Configuration for {@link ExperienceApiClient}.\n *\n * @public\n */\nexport interface ExperienceApiClientConfig extends ApiConfig, ExperienceApiClientRequestOptions {}\n\n/**\n * Client for interacting with the Experience API.\n *\n * @remarks\n * This client is responsible for reading and mutating Ninetailed profiles\n * using the Experience API.\n *\n * @example\n * ```ts\n * const client = new ExperienceApiClient({\n * clientId: 'org-id',\n * environment: 'main',\n * })\n *\n * const profile = await client.getProfile('profile-id')\n * ```\n *\n * Extends `ApiClientBase`.\n *\n * @public\n */\nexport default class ExperienceApiClient extends ApiClientBase {\n /**\n * Base URL used for Experience API requests.\n */\n protected readonly baseUrl: string\n\n private readonly enabledFeatures?: ExperienceApiClientRequestOptions['enabledFeatures']\n private readonly ip?: ExperienceApiClientRequestOptions['ip']\n private locale?: ExperienceApiClientRequestOptions['locale']\n private readonly plainText?: ExperienceApiClientRequestOptions['plainText']\n private readonly preflight?: ExperienceApiClientRequestOptions['preflight']\n\n /**\n * Creates a new {@link ExperienceApiClient} instance.\n *\n * @param config - Configuration for the Experience API client.\n */\n constructor(config: ExperienceApiClientConfig) {\n super('Experience', config)\n\n const { baseUrl, enabledFeatures, ip, locale, plainText, preflight } = config\n\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing -- Set default for anything falsey\n this.baseUrl = baseUrl || EXPERIENCE_BASE_URL\n this.enabledFeatures = enabledFeatures\n this.ip = ip\n this.locale = locale\n this.plainText = plainText\n this.preflight = preflight\n }\n\n /**\n * Update the default Experience API locale used when request options omit `locale`.\n *\n * @param locale - Next default Experience API locale.\n *\n * @public\n */\n public setLocale(locale: ExperienceApiClientRequestOptions['locale']): void {\n this.locale = locale\n }\n\n /**\n * Retrieves a profile by ID.\n *\n * @param id - The profile ID to retrieve.\n * @param options - Optional request options. `preflight` and `plainText` are not allowed here.\n * @returns The current optimization data for the profile.\n *\n * @throws Error\n * Thrown if `id` is missing or the underlying request fails.\n *\n * @example\n * ```ts\n * const profile = await client.getProfile('profile-id', {\n * locale: 'en-US',\n * })\n * ```\n */\n public async getProfile(\n id: string,\n options: Omit<ExperienceApiClientRequestOptions, 'preflight' | 'plainText'> = {},\n ): Promise<OptimizationData> {\n if (!id) throw new Error('Valid profile ID required.')\n\n const requestName = 'Get Profile'\n\n logger.info(`Sending \"${requestName}\" request`)\n\n try {\n const response = await this.fetch(\n this.constructUrl(\n `v2/organizations/${this.clientId}/environments/${this.environment}/profiles/${id}`,\n options,\n ),\n {\n method: 'GET',\n },\n )\n\n const {\n data: { changes, experiences, profile },\n } = parseWithFriendlyError(ExperienceResponse, await response.json())\n\n const data = { changes, selectedOptimizations: experiences, profile }\n\n logger.debug(`\"${requestName}\" request successfully completed`)\n\n return data\n } catch (error) {\n this.logRequestError(error, { requestName })\n\n throw error\n }\n }\n\n /**\n * Sends a POST request to mutate a profile or profiles.\n *\n * @param request - Mutation request options including URL, body, and request options.\n * @returns The raw {@link Response} from the underlying fetch.\n *\n * @internal\n */\n private async makeProfileMutationRequest({\n url,\n body,\n options,\n }: ProfileMutationRequestOptions): Promise<Response> {\n return await this.fetch(this.constructUrl(url, options), {\n method: 'POST',\n headers: this.constructHeaders(options),\n body: JSON.stringify(body),\n keepalive: true,\n })\n }\n\n /**\n * Creates a profile and returns the resulting optimization data.\n *\n * @param params - Parameters containing the events to aggregate into the profile.\n * @param options - Optional request options.\n * @returns The optimization data for the newly created profile.\n *\n * @remarks\n * The returned profile ID can be used for subsequent update requests.\n *\n * @example\n * ```ts\n * const data = await client.createProfile({\n * events: [{ type: 'identify', userId: 'user-123' }],\n * })\n * ```\n */\n public async createProfile(\n { events }: CreateProfileParams,\n options: ExperienceApiClientRequestOptions = {},\n ): Promise<OptimizationData> {\n const requestName = 'Create Profile'\n\n logger.info(`Sending \"${requestName}\" request`)\n\n const body = this.constructExperienceRequestBody(events, options)\n\n logger.debug(`\"${requestName}\" request body:`, body)\n\n try {\n const response = await this.makeProfileMutationRequest({\n url: `v2/organizations/${this.clientId}/environments/${this.environment}/profiles`,\n body,\n options,\n })\n\n const {\n data: { changes, experiences, profile },\n } = parseWithFriendlyError(ExperienceResponse, await response.json())\n\n const data = { changes, selectedOptimizations: experiences, profile }\n\n logger.debug(`\"${requestName}\" request successfully completed`)\n\n return data\n } catch (error) {\n this.logRequestError(error, { requestName })\n\n throw error\n }\n }\n\n /**\n * Updates an existing profile with the given profile ID.\n *\n * @param params - Parameters including the profile ID and events.\n * @param options - Optional request options.\n * @returns The updated optimization data for the profile.\n *\n * @throws Error\n * Thrown if `profileId` is missing or the underlying request fails.\n *\n * @example\n * ```ts\n * const data = await client.updateProfile({\n * profileId: 'profile-id',\n * events: [{ type: 'track', event: 'viewed_video' }],\n * })\n * ```\n */\n public async updateProfile(\n { profileId, events }: UpdateProfileParams,\n options: ExperienceApiClientRequestOptions = {},\n ): Promise<OptimizationData> {\n if (!profileId) throw new Error('Valid profile ID required.')\n\n const requestName = 'Update Profile'\n\n logger.info(`Sending \"${requestName}\" request`)\n\n const body = this.constructExperienceRequestBody(events, options)\n\n logger.debug(`\"${requestName}\" request body:`, body)\n\n try {\n const response = await this.makeProfileMutationRequest({\n url: `v2/organizations/${this.clientId}/environments/${this.environment}/profiles/${profileId}`,\n body,\n options,\n })\n\n const {\n data: { changes, experiences, profile },\n } = parseWithFriendlyError(ExperienceResponse, await response.json())\n\n const data = { changes, selectedOptimizations: experiences, profile }\n\n logger.debug(`\"${requestName}\" request successfully completed`)\n\n return data\n } catch (error) {\n this.logRequestError(error, { requestName })\n\n throw error\n }\n }\n\n /**\n * Creates or updates a profile depending on whether a `profileId` is provided.\n *\n * @param params - Parameters including optional profile ID and events.\n * @param options - Optional request options.\n * @returns The resulting optimization data.\n *\n * @example\n * ```ts\n * // Create\n * await client.upsertProfile({ events })\n *\n * // Update\n * await client.upsertProfile({ profileId: 'profile-id', events })\n * ```\n */\n public async upsertProfile(\n { profileId, events }: UpsertProfileParams,\n options?: ExperienceApiClientRequestOptions,\n ): Promise<OptimizationData> {\n if (!profileId) {\n return await this.createProfile({ events }, options)\n } else {\n return await this.updateProfile({ profileId, events }, options)\n }\n }\n\n /**\n * Sends multiple events to the Ninetailed Experience API to upsert many profiles.\n *\n * @param params - Parameters containing the batch of events.\n * @param options - Optional request options.\n * @returns The list of profiles affected by the batch operation.\n *\n * @remarks\n * Batch requests must contain at least one event. Every event must contain\n * an anonymous ID. Profiles will be created or updated according to the\n * anonymous ID.\n *\n * This method is intended to be used from server environments.\n *\n * @example\n * ```ts\n * const profiles = await client.upsertManyProfiles({\n * events: [\n * { anonymousId: 'anon-1', type: 'identify', ... },\n * { anonymousId: 'anon-2', type: 'identify', ... },\n * ],\n * })\n * ```\n */\n public async upsertManyProfiles(\n { events }: BatchUpdateProfileParams,\n options: ExperienceApiClientRequestOptions = {},\n ): Promise<BatchExperienceResponseData['profiles']> {\n const requestName = 'Upsert Many Profiles'\n\n logger.info(`Sending \"${requestName}\" request`)\n\n const body = parseWithFriendlyError(BatchExperienceRequestData, {\n events,\n options: this.constructBodyOptions(options),\n })\n\n logger.debug(`\"${requestName}\" request body:`, body)\n\n try {\n const response = await this.makeProfileMutationRequest({\n url: `v2/organizations/${this.clientId}/environments/${this.environment}/events`,\n body,\n options: { plainText: false, ...options },\n })\n\n const {\n data: { profiles },\n } = parseWithFriendlyError(BatchExperienceResponse, await response.json())\n\n logger.debug(`\"${requestName}\" request successfully completed`)\n\n return profiles\n } catch (error) {\n this.logRequestError(error, { requestName })\n\n throw error\n }\n }\n\n /**\n * Constructs a request URL with query parameters derived from request options.\n *\n * @param path - Path relative to the Experience API base URL.\n * @param options - Request options that can influence query parameters.\n * @returns The fully constructed URL as a string.\n *\n * @internal\n */\n private constructUrl(path: string, options: ExperienceApiClientRequestOptions): string {\n const url = new URL(path, this.baseUrl)\n const locale = options.locale ?? this.locale\n const preflight = options.preflight ?? this.preflight\n\n if (locale) {\n url.searchParams.set('locale', locale)\n }\n\n if (preflight) {\n url.searchParams.set('type', 'preflight')\n }\n\n return url.toString()\n }\n\n /**\n * Constructs request headers based on request options and default configuration.\n *\n * @param options - Request options that can influence headers.\n * @returns A record of HTTP headers to send with the request.\n *\n * @internal\n */\n private constructHeaders({\n ip = this.ip,\n plainText = this.plainText,\n }: ExperienceApiClientRequestOptions): Record<string, string> {\n const headers = new Map<string, string>()\n\n if (ip) {\n headers.set('X-Force-IP', ip)\n }\n\n if (plainText ?? this.plainText ?? true) {\n headers.set('Content-Type', 'text/plain')\n } else {\n headers.set('Content-Type', 'application/json')\n }\n\n return Object.fromEntries(headers)\n }\n\n /**\n * Constructs the `options` section of the request body for profile mutations.\n *\n * @param options - Request options that can specify enabled features.\n * @returns Experience API body options including feature flags.\n *\n * @internal\n */\n private readonly constructBodyOptions = ({\n enabledFeatures = this.enabledFeatures,\n }: ExperienceApiClientRequestOptions): ExperienceRequestBodyOptions => {\n const bodyOptions: ExperienceRequestBodyOptions = {}\n\n if (enabledFeatures && Array.isArray(enabledFeatures) && enabledFeatures.length > 0) {\n bodyOptions.features = enabledFeatures\n } else {\n bodyOptions.features = ['ip-enrichment', 'location']\n }\n\n return bodyOptions\n }\n\n /**\n * Construct and validate the singular Experience mutation request payload.\n *\n * @param events - Events for the Experience API to evaluate.\n * @param options - Request options that can contribute body options.\n * @returns Validated singular Experience request body.\n *\n * @internal\n */\n private constructExperienceRequestBody(\n events: ExperienceEventArray,\n options: ExperienceApiClientRequestOptions,\n ): ExperienceRequestData {\n return ExperienceRequestData.parse({\n events: parseWithFriendlyError(ExperienceEventArray, events),\n options: this.constructBodyOptions(options),\n })\n }\n}\n","import {\n BatchInsightsEventArray,\n parseWithFriendlyError,\n} from '@contentful/optimization-api-schemas'\nimport ApiClientBase, { type ApiConfig } from '../ApiClientBase'\nimport { createScopedLogger } from '../logger'\n\nconst logger = createScopedLogger('ApiClient:Insights')\nconst BEACON_FALLBACK_MESSAGE = 'beacon failed; falling back to fetch'\n\n/**\n * Default base URL for the Insights ingest API.\n *\n * @public\n */\nexport const INSIGHTS_BASE_URL = 'https://ingest.insights.ninetailed.co/'\n\n/**\n * Options that control how Insights events are sent.\n *\n * @public\n */\nexport interface InsightsApiClientRequestOptions {\n /**\n * Sender used to enqueue serialized events via the Beacon API or a similar mechanism.\n *\n * @param url - Target URL for the batched events.\n * @param body - Serialized batched insights events to be sent.\n * @returns `true` if the events were successfully queued, `false` otherwise.\n *\n * @remarks\n * This option is intended for last-chance lifecycle delivery. If it returns\n * `false` or throws, the client falls back to emitting events immediately via\n * `fetch` with `keepalive`.\n */\n beacon?: (url: string, body: string) => boolean\n}\n\n/**\n * Configuration for {@link InsightsApiClient}.\n *\n * @public\n */\nexport interface InsightsApiClientConfig extends ApiConfig {}\n\n/**\n * Client for sending analytics and insights events to the Ninetailed Insights API.\n *\n * @remarks\n * This client is optimized for sending batched events, optionally using a\n * custom beacon-like sender for last-chance lifecycle delivery.\n *\n * @example\n * ```ts\n * const insightsClient = new InsightsApiClient({\n * clientId: 'org-id',\n * environment: 'main',\n * })\n *\n * await insightsClient.sendBatchEvents([\n * {\n * profile: { id: 'profile-123', ... },\n * events: [\n * {\n * type: 'track',\n * event: 'button_clicked',\n * properties: { id: 'primary-cta' },\n * },\n * ],\n * }\n * ])\n * ```\n *\n * Extends `ApiClientBase`.\n *\n * @public\n */\nexport default class InsightsApiClient extends ApiClientBase {\n /**\n * Base URL used for Insights API requests.\n */\n protected readonly baseUrl: string\n\n /**\n * Creates a new {@link InsightsApiClient} instance.\n *\n * @param config - Configuration for the Insights API client.\n *\n * @example\n * ```ts\n * const client = new InsightsApiClient({\n * clientId: 'org-id',\n * environment: 'main',\n * })\n * ```\n */\n constructor(config: InsightsApiClientConfig) {\n super('Insights', config)\n\n const { baseUrl } = config\n\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing -- Set default for anything falsey\n this.baseUrl = baseUrl || INSIGHTS_BASE_URL\n }\n\n /**\n * Sends batches of insights events to the Ninetailed Insights API.\n *\n * @param batches - Array of event batches to send.\n * @param options - Optional request options, including a per-call `beacon` sender.\n * @returns `true` when the event batch is successfully queued by the beacon\n * sender or a direct request is successfully sent, `false` otherwise.\n *\n * @remarks\n * If a `beacon` sender is provided, it will be invoked first with the\n * serialized request body. When the sender returns `true`, the events are\n * considered successfully queued and no network request is made by this\n * method.\n *\n * If the sender is missing, returns `false`, or throws, the events are\n * emitted immediately via `fetch`.\n *\n * @example\n * ```ts\n * const success = await insightsClient.sendBatchEvents(batches)\n * ```\n *\n * @example\n * ```ts\n * // Use Beacon for a last-chance lifecycle flush\n * const success = await insightsClient.sendBatchEvents(batches, {\n * beacon: (url, body) => navigator.sendBeacon(url, body),\n * })\n * ```\n */\n public async sendBatchEvents(\n batches: BatchInsightsEventArray,\n options: InsightsApiClientRequestOptions = {},\n ): Promise<boolean> {\n const { beacon } = options\n\n const url = new URL(\n `v1/organizations/${this.clientId}/environments/${this.environment}/events`,\n this.baseUrl,\n )\n const urlString = url.toString()\n\n const body = parseWithFriendlyError(BatchInsightsEventArray, batches)\n const serializedBody = JSON.stringify(body)\n\n if (beacon) {\n logger.debug('Queueing events via beacon')\n\n try {\n const beaconSuccessfullyQueued = beacon(urlString, serializedBody)\n\n if (beaconSuccessfullyQueued) {\n return true\n }\n\n logger.warn(BEACON_FALLBACK_MESSAGE)\n } catch (error) {\n logger.warn(BEACON_FALLBACK_MESSAGE, error)\n }\n }\n\n const requestName = 'Event Batches'\n\n logger.info(`Sending \"${requestName}\" request`)\n\n logger.debug(`\"${requestName}\" request body:`, body)\n\n try {\n await this.fetch(urlString, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: serializedBody,\n keepalive: !!beacon,\n })\n\n logger.debug(`\"${requestName}\" request successfully completed`)\n\n return true\n } catch (error) {\n this.logRequestError(error, { requestName })\n\n return false\n }\n }\n}\n","import type { ApiConfig, GlobalApiConfigProperties } from './ApiClientBase'\nimport { ExperienceApiClient, type ExperienceApiClientConfig } from './experience'\nimport { InsightsApiClient, type InsightsApiClientConfig } from './insights'\n\n/**\n * Configuration for the high-level {@link ApiClient}.\n *\n * @public\n */\nexport interface ApiClientConfig extends Pick<ApiConfig, GlobalApiConfigProperties> {\n /**\n * Configuration for the Experience API client.\n *\n * @remarks\n * Shared fields (`clientId`, `environment`, `fetchOptions`) are inherited\n * from top-level config; this object is for Experience-specific options.\n */\n experience?: Omit<ExperienceApiClientConfig, GlobalApiConfigProperties>\n\n /**\n * Configuration for the Insights API client.\n *\n * @remarks\n * Shared fields (`clientId`, `environment`, `fetchOptions`) are inherited\n * from top-level config; this object is for Insights-specific options.\n */\n insights?: Omit<InsightsApiClientConfig, GlobalApiConfigProperties>\n}\n\n/**\n * Aggregated API client providing access to Experience and Insights APIs.\n *\n * @remarks\n * This client encapsulates shared configuration and exposes dedicated\n * sub-clients for experience and insights use cases.\n *\n * @example\n * ```ts\n * const client = new ApiClient({\n * clientId: 'org-id',\n * environment: 'main',\n * experience: {\n * // experience-specific overrides\n * },\n * insights: {\n * // insights-specific overrides\n * },\n * })\n *\n * const profile = await client.experience.getProfile('profile-id')\n * await client.insights.sendBatchEvents(batches)\n * ```\n *\n * @see {@link ExperienceApiClient}\n * @see {@link InsightsApiClient}\n *\n * @public\n */\nexport default class ApiClient {\n /**\n * Shared configuration applied to both Experience and Insights clients.\n *\n * @see {@link ApiConfig}\n */\n readonly config: ApiConfig\n\n /**\n * Client for experience-related operations.\n *\n * @see {@link ExperienceApiClient}\n */\n readonly experience: ExperienceApiClient\n\n /**\n * Client for insights-related operations.\n *\n * @see {@link InsightsApiClient}\n */\n readonly insights: InsightsApiClient\n\n /**\n * Creates a new aggregated {@link ApiClient} instance.\n *\n * @param config - Global API client configuration with optional per-client overrides.\n */\n constructor(config: ApiClientConfig) {\n const { experience, insights, clientId, environment, fetchOptions } = config\n const apiConfig: ApiConfig = {\n clientId,\n environment,\n fetchOptions,\n }\n\n this.config = apiConfig\n\n this.experience = new ExperienceApiClient({\n ...apiConfig,\n ...experience,\n })\n\n this.insights = new InsightsApiClient({\n ...apiConfig,\n ...insights,\n })\n }\n}\n"],"names":["LogSink","logLevelSeverity","Logger","logLocation","sink","existingSink","name","message","args","level","String","event","logger","createScopedLogger","location","__webpack_require__","definition","key","Object","obj","prop","Symbol","fetchInputToString","input","MISSING_FETCH_METHOD_MESSAGE","resolveFetchMethod","fetchMethod","globalThis","Error","DEFAULT_INTERVAL_TIMEOUT","DEFAULT_RETRY_COUNT","RETRY_RESPONSE_STATUS","HTTP_ERROR_RESPONSE_STATUS","HttpError","status","createRetryFetchCallback","apiName","controller","init","url","urlLabel","response","httpError","error","delayRetry","intervalTimeout","promise","resolve","Promise","setTimeout","undefined","createRetryFetchMethod","onFailedAttempt","retries","resolvedFetchMethod","AbortController","maxAttempts","attemptFetch","attemptNumber","retriesLeft","DEFAULT_REQUEST_TIMEOUT","isFetchAbortSignal","signal","createTimeoutFetchMethod","onRequestTimeout","requestTimeout","id","requestInit","clearTimeout","createProtectedFetchMethod","options","timeoutFetchMethod","retryFetchMethod","Fetch","DEFAULT_ENVIRONMENT","ApiClientBase","fetchOptions","clientId","environment","requestName","EXPERIENCE_BASE_URL","ExperienceApiClient","config","baseUrl","enabledFeatures","ip","locale","plainText","preflight","changes","experiences","profile","parseWithFriendlyError","ExperienceResponse","data","body","JSON","events","profileId","BatchExperienceRequestData","profiles","BatchExperienceResponse","path","URL","headers","Map","bodyOptions","Array","ExperienceRequestData","ExperienceEventArray","BEACON_FALLBACK_MESSAGE","INSIGHTS_BASE_URL","InsightsApiClient","batches","beacon","urlString","BatchInsightsEventArray","serializedBody","beaconSuccessfullyQueued","ApiClient","experience","insights","apiConfig"],"mappings":";;;;;;QAkBA,MAAeA;QAWf;QAEA,gCAAeA;;;;;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AGT1G,yBAAO,IAAI,CAACkG;gBACd,EAAE,OAAOnE,OAAO;oBACd/B,yBAAO,IAAI,CAACkG,yBAAyBnE;gBACvC;YACF;YAEA,MAAMoC,cAAc;YAEpBnE,yBAAO,IAAI,CAAC,CAAC,SAAS,EAAEmE,YAAY,SAAS,CAAC;YAE9CnE,yBAAO,KAAK,CAAC,CAAC,CAAC,EAAEmE,YAAY,eAAe,CAAC,EAAEgB;YAE/C,IAAI;gBACF,MAAM,IAAI,CAAC,KAAK,CAACoB,WAAW;oBAC1B,QAAQ;oBACR,SAAS;wBACP,gBAAgB;oBAClB;oBACA,MAAME;oBACN,WAAW,CAAC,CAACH;gBACf;gBAEAtG,yBAAO,KAAK,CAAC,CAAC,CAAC,EAAEmE,YAAY,gCAAgC,CAAC;gBAE9D,OAAO;YACT,EAAE,OAAOpC,OAAO;gBACd,IAAI,CAAC,eAAe,CAACA,OAAO;oBAAEoC;gBAAY;gBAE1C,OAAO;YACT;QACF;IACF;ICrIe,MAAMwC;QAMV,OAAiB;QAOjB,WAA+B;QAO/B,SAA2B;QAOpC,YAAYrC,MAAuB,CAAE;YACnC,MAAM,EAAEsC,UAAU,EAAEC,QAAQ,EAAE5C,QAAQ,EAAEC,WAAW,EAAEF,YAAY,EAAE,GAAGM;YACtE,MAAMwC,YAAuB;gBAC3B7C;gBACAC;gBACAF;YACF;YAEA,IAAI,CAAC,MAAM,GAAG8C;YAEd,IAAI,CAAC,UAAU,GAAG,IAAIzC,oBAAoB;gBACxC,GAAGyC,SAAS;gBACZ,GAAGF,UAAU;YACf;YAEA,IAAI,CAAC,QAAQ,GAAG,IAAIR,kBAAkB;gBACpC,GAAGU,SAAS;gBACZ,GAAGD,QAAQ;YACb;QACF;IACF"}
|
package/dist/index.d.cts
CHANGED
|
@@ -213,7 +213,8 @@ export declare interface BaseFetchMethodOptions {
|
|
|
213
213
|
*
|
|
214
214
|
* @remarks
|
|
215
215
|
* This is useful for providing polyfills, mocks, or instrumented fetch
|
|
216
|
-
* implementations.
|
|
216
|
+
* implementations. It is required in runtimes that do not provide
|
|
217
|
+
* `globalThis.fetch`.
|
|
217
218
|
*/
|
|
218
219
|
fetchMethod?: FetchMethod;
|
|
219
220
|
}
|
|
@@ -609,14 +610,16 @@ export declare type Feature = 'ip-enrichment' | 'location';
|
|
|
609
610
|
*
|
|
610
611
|
* @example
|
|
611
612
|
* ```ts
|
|
612
|
-
* const method: FetchMethod = async (
|
|
613
|
-
* return fetch(
|
|
613
|
+
* const method: FetchMethod = async (input, init) => {
|
|
614
|
+
* return fetch(input, init)
|
|
614
615
|
* }
|
|
615
616
|
* ```
|
|
616
617
|
*
|
|
617
618
|
* @public
|
|
618
619
|
*/
|
|
619
|
-
export declare type
|
|
620
|
+
export declare type FetchInput = string | Request;
|
|
621
|
+
|
|
622
|
+
export declare type FetchMethod = (input: FetchInput, init?: RequestInit) => Promise<Response>;
|
|
620
623
|
|
|
621
624
|
/**
|
|
622
625
|
* Options passed to callback functions invoked by fetch wrappers.
|
|
@@ -664,7 +667,7 @@ export declare const INSIGHTS_BASE_URL = "https://ingest.insights.ninetailed.co/
|
|
|
664
667
|
*
|
|
665
668
|
* @remarks
|
|
666
669
|
* This client is optimized for sending batched events, optionally using a
|
|
667
|
-
* custom beacon-like
|
|
670
|
+
* custom beacon-like sender for last-chance lifecycle delivery.
|
|
668
671
|
*
|
|
669
672
|
* @example
|
|
670
673
|
* ```ts
|
|
@@ -696,10 +699,6 @@ export declare class InsightsApiClient extends ApiClientBase {
|
|
|
696
699
|
* Base URL used for Insights API requests.
|
|
697
700
|
*/
|
|
698
701
|
protected readonly baseUrl: string;
|
|
699
|
-
/**
|
|
700
|
-
* Optional handler used to enqueue events via the Beacon API or a similar mechanism.
|
|
701
|
-
*/
|
|
702
|
-
private readonly beaconHandler;
|
|
703
702
|
/**
|
|
704
703
|
* Creates a new {@link InsightsApiClient} instance.
|
|
705
704
|
*
|
|
@@ -710,9 +709,6 @@ export declare class InsightsApiClient extends ApiClientBase {
|
|
|
710
709
|
* const client = new InsightsApiClient({
|
|
711
710
|
* clientId: 'org-id',
|
|
712
711
|
* environment: 'main',
|
|
713
|
-
* beaconHandler: (url, data) => {
|
|
714
|
-
* return navigator.sendBeacon(url.toString(), JSON.stringify(data))
|
|
715
|
-
* },
|
|
716
712
|
* })
|
|
717
713
|
* ```
|
|
718
714
|
*/
|
|
@@ -721,18 +717,18 @@ export declare class InsightsApiClient extends ApiClientBase {
|
|
|
721
717
|
* Sends batches of insights events to the Ninetailed Insights API.
|
|
722
718
|
*
|
|
723
719
|
* @param batches - Array of event batches to send.
|
|
724
|
-
* @param options - Optional request options, including a per-call `
|
|
720
|
+
* @param options - Optional request options, including a per-call `beacon` sender.
|
|
725
721
|
* @returns `true` when the event batch is successfully queued by the beacon
|
|
726
|
-
*
|
|
722
|
+
* sender or a direct request is successfully sent, `false` otherwise.
|
|
727
723
|
*
|
|
728
724
|
* @remarks
|
|
729
|
-
* If a `
|
|
730
|
-
*
|
|
731
|
-
*
|
|
732
|
-
*
|
|
725
|
+
* If a `beacon` sender is provided, it will be invoked first with the
|
|
726
|
+
* serialized request body. When the sender returns `true`, the events are
|
|
727
|
+
* considered successfully queued and no network request is made by this
|
|
728
|
+
* method.
|
|
733
729
|
*
|
|
734
|
-
* If the
|
|
735
|
-
* immediately via `fetch`.
|
|
730
|
+
* If the sender is missing, returns `false`, or throws, the events are
|
|
731
|
+
* emitted immediately via `fetch`.
|
|
736
732
|
*
|
|
737
733
|
* @example
|
|
738
734
|
* ```ts
|
|
@@ -741,11 +737,9 @@ export declare class InsightsApiClient extends ApiClientBase {
|
|
|
741
737
|
*
|
|
742
738
|
* @example
|
|
743
739
|
* ```ts
|
|
744
|
-
* //
|
|
740
|
+
* // Use Beacon for a last-chance lifecycle flush
|
|
745
741
|
* const success = await insightsClient.sendBatchEvents(batches, {
|
|
746
|
-
*
|
|
747
|
-
* return navigator.sendBeacon(url.toString(), JSON.stringify(data))
|
|
748
|
-
* },
|
|
742
|
+
* beacon: (url, body) => navigator.sendBeacon(url, body),
|
|
749
743
|
* })
|
|
750
744
|
* ```
|
|
751
745
|
*/
|
|
@@ -757,7 +751,7 @@ export declare class InsightsApiClient extends ApiClientBase {
|
|
|
757
751
|
*
|
|
758
752
|
* @public
|
|
759
753
|
*/
|
|
760
|
-
export declare interface InsightsApiClientConfig extends ApiConfig
|
|
754
|
+
export declare interface InsightsApiClientConfig extends ApiConfig {
|
|
761
755
|
}
|
|
762
756
|
|
|
763
757
|
/**
|
|
@@ -767,18 +761,18 @@ export declare interface InsightsApiClientConfig extends ApiConfig, InsightsApiC
|
|
|
767
761
|
*/
|
|
768
762
|
export declare interface InsightsApiClientRequestOptions {
|
|
769
763
|
/**
|
|
770
|
-
*
|
|
764
|
+
* Sender used to enqueue serialized events via the Beacon API or a similar mechanism.
|
|
771
765
|
*
|
|
772
766
|
* @param url - Target URL for the batched events.
|
|
773
|
-
* @param
|
|
767
|
+
* @param body - Serialized batched insights events to be sent.
|
|
774
768
|
* @returns `true` if the events were successfully queued, `false` otherwise.
|
|
775
769
|
*
|
|
776
770
|
* @remarks
|
|
777
|
-
*
|
|
778
|
-
*
|
|
779
|
-
* `fetch`.
|
|
771
|
+
* This option is intended for last-chance lifecycle delivery. If it returns
|
|
772
|
+
* `false` or throws, the client falls back to emitting events immediately via
|
|
773
|
+
* `fetch` with `keepalive`.
|
|
780
774
|
*/
|
|
781
|
-
|
|
775
|
+
beacon?: (url: string, body: string) => boolean;
|
|
782
776
|
}
|
|
783
777
|
|
|
784
778
|
/**
|
package/dist/index.d.mts
CHANGED
|
@@ -213,7 +213,8 @@ export declare interface BaseFetchMethodOptions {
|
|
|
213
213
|
*
|
|
214
214
|
* @remarks
|
|
215
215
|
* This is useful for providing polyfills, mocks, or instrumented fetch
|
|
216
|
-
* implementations.
|
|
216
|
+
* implementations. It is required in runtimes that do not provide
|
|
217
|
+
* `globalThis.fetch`.
|
|
217
218
|
*/
|
|
218
219
|
fetchMethod?: FetchMethod;
|
|
219
220
|
}
|
|
@@ -609,14 +610,16 @@ export declare type Feature = 'ip-enrichment' | 'location';
|
|
|
609
610
|
*
|
|
610
611
|
* @example
|
|
611
612
|
* ```ts
|
|
612
|
-
* const method: FetchMethod = async (
|
|
613
|
-
* return fetch(
|
|
613
|
+
* const method: FetchMethod = async (input, init) => {
|
|
614
|
+
* return fetch(input, init)
|
|
614
615
|
* }
|
|
615
616
|
* ```
|
|
616
617
|
*
|
|
617
618
|
* @public
|
|
618
619
|
*/
|
|
619
|
-
export declare type
|
|
620
|
+
export declare type FetchInput = string | Request;
|
|
621
|
+
|
|
622
|
+
export declare type FetchMethod = (input: FetchInput, init?: RequestInit) => Promise<Response>;
|
|
620
623
|
|
|
621
624
|
/**
|
|
622
625
|
* Options passed to callback functions invoked by fetch wrappers.
|
|
@@ -664,7 +667,7 @@ export declare const INSIGHTS_BASE_URL = "https://ingest.insights.ninetailed.co/
|
|
|
664
667
|
*
|
|
665
668
|
* @remarks
|
|
666
669
|
* This client is optimized for sending batched events, optionally using a
|
|
667
|
-
* custom beacon-like
|
|
670
|
+
* custom beacon-like sender for last-chance lifecycle delivery.
|
|
668
671
|
*
|
|
669
672
|
* @example
|
|
670
673
|
* ```ts
|
|
@@ -696,10 +699,6 @@ export declare class InsightsApiClient extends ApiClientBase {
|
|
|
696
699
|
* Base URL used for Insights API requests.
|
|
697
700
|
*/
|
|
698
701
|
protected readonly baseUrl: string;
|
|
699
|
-
/**
|
|
700
|
-
* Optional handler used to enqueue events via the Beacon API or a similar mechanism.
|
|
701
|
-
*/
|
|
702
|
-
private readonly beaconHandler;
|
|
703
702
|
/**
|
|
704
703
|
* Creates a new {@link InsightsApiClient} instance.
|
|
705
704
|
*
|
|
@@ -710,9 +709,6 @@ export declare class InsightsApiClient extends ApiClientBase {
|
|
|
710
709
|
* const client = new InsightsApiClient({
|
|
711
710
|
* clientId: 'org-id',
|
|
712
711
|
* environment: 'main',
|
|
713
|
-
* beaconHandler: (url, data) => {
|
|
714
|
-
* return navigator.sendBeacon(url.toString(), JSON.stringify(data))
|
|
715
|
-
* },
|
|
716
712
|
* })
|
|
717
713
|
* ```
|
|
718
714
|
*/
|
|
@@ -721,18 +717,18 @@ export declare class InsightsApiClient extends ApiClientBase {
|
|
|
721
717
|
* Sends batches of insights events to the Ninetailed Insights API.
|
|
722
718
|
*
|
|
723
719
|
* @param batches - Array of event batches to send.
|
|
724
|
-
* @param options - Optional request options, including a per-call `
|
|
720
|
+
* @param options - Optional request options, including a per-call `beacon` sender.
|
|
725
721
|
* @returns `true` when the event batch is successfully queued by the beacon
|
|
726
|
-
*
|
|
722
|
+
* sender or a direct request is successfully sent, `false` otherwise.
|
|
727
723
|
*
|
|
728
724
|
* @remarks
|
|
729
|
-
* If a `
|
|
730
|
-
*
|
|
731
|
-
*
|
|
732
|
-
*
|
|
725
|
+
* If a `beacon` sender is provided, it will be invoked first with the
|
|
726
|
+
* serialized request body. When the sender returns `true`, the events are
|
|
727
|
+
* considered successfully queued and no network request is made by this
|
|
728
|
+
* method.
|
|
733
729
|
*
|
|
734
|
-
* If the
|
|
735
|
-
* immediately via `fetch`.
|
|
730
|
+
* If the sender is missing, returns `false`, or throws, the events are
|
|
731
|
+
* emitted immediately via `fetch`.
|
|
736
732
|
*
|
|
737
733
|
* @example
|
|
738
734
|
* ```ts
|
|
@@ -741,11 +737,9 @@ export declare class InsightsApiClient extends ApiClientBase {
|
|
|
741
737
|
*
|
|
742
738
|
* @example
|
|
743
739
|
* ```ts
|
|
744
|
-
* //
|
|
740
|
+
* // Use Beacon for a last-chance lifecycle flush
|
|
745
741
|
* const success = await insightsClient.sendBatchEvents(batches, {
|
|
746
|
-
*
|
|
747
|
-
* return navigator.sendBeacon(url.toString(), JSON.stringify(data))
|
|
748
|
-
* },
|
|
742
|
+
* beacon: (url, body) => navigator.sendBeacon(url, body),
|
|
749
743
|
* })
|
|
750
744
|
* ```
|
|
751
745
|
*/
|
|
@@ -757,7 +751,7 @@ export declare class InsightsApiClient extends ApiClientBase {
|
|
|
757
751
|
*
|
|
758
752
|
* @public
|
|
759
753
|
*/
|
|
760
|
-
export declare interface InsightsApiClientConfig extends ApiConfig
|
|
754
|
+
export declare interface InsightsApiClientConfig extends ApiConfig {
|
|
761
755
|
}
|
|
762
756
|
|
|
763
757
|
/**
|
|
@@ -767,18 +761,18 @@ export declare interface InsightsApiClientConfig extends ApiConfig, InsightsApiC
|
|
|
767
761
|
*/
|
|
768
762
|
export declare interface InsightsApiClientRequestOptions {
|
|
769
763
|
/**
|
|
770
|
-
*
|
|
764
|
+
* Sender used to enqueue serialized events via the Beacon API or a similar mechanism.
|
|
771
765
|
*
|
|
772
766
|
* @param url - Target URL for the batched events.
|
|
773
|
-
* @param
|
|
767
|
+
* @param body - Serialized batched insights events to be sent.
|
|
774
768
|
* @returns `true` if the events were successfully queued, `false` otherwise.
|
|
775
769
|
*
|
|
776
770
|
* @remarks
|
|
777
|
-
*
|
|
778
|
-
*
|
|
779
|
-
* `fetch`.
|
|
771
|
+
* This option is intended for last-chance lifecycle delivery. If it returns
|
|
772
|
+
* `false` or throws, the client falls back to emitting events immediately via
|
|
773
|
+
* `fetch` with `keepalive`.
|
|
780
774
|
*/
|
|
781
|
-
|
|
775
|
+
beacon?: (url: string, body: string) => boolean;
|
|
782
776
|
}
|
|
783
777
|
|
|
784
778
|
/**
|