@disconetwork/core 0.0.2 → 0.0.4
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/dist/index.d.ts +26 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +18 -0
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -334,6 +334,19 @@ type CreateTrackingManagerOptions = {
|
|
|
334
334
|
*/
|
|
335
335
|
fetch?: typeof fetch;
|
|
336
336
|
};
|
|
337
|
+
/**
|
|
338
|
+
* Result of `getRecommendationsWithTracker`: the **raw** recommendations
|
|
339
|
+
* response plus a tracker already bound to its session.
|
|
340
|
+
*/
|
|
341
|
+
type RecommendationsWithTracker = {
|
|
342
|
+
/**
|
|
343
|
+
* The verbatim API response (snake_case), exactly as `getRecommendations`
|
|
344
|
+
* returns it. Pass it through `mapRecommendationsResponse` for the friendly
|
|
345
|
+
* denormalized shape.
|
|
346
|
+
*/
|
|
347
|
+
data: RawRecommendationsResponse; /** Event tracker bound to this response's session. */
|
|
348
|
+
tracker: EventTracker;
|
|
349
|
+
};
|
|
337
350
|
/**
|
|
338
351
|
* Thrown by `DiscoClient.getRecommendations` when the server returns a
|
|
339
352
|
* non-2xx status. The HTTP status and an optional parsed body are
|
|
@@ -370,6 +383,18 @@ declare class DiscoClient {
|
|
|
370
383
|
* (network, parse) propagate as-is.
|
|
371
384
|
*/
|
|
372
385
|
getRecommendations: (request: RecommendationsRequest, options?: GetRecommendationsOptions) => Promise<RawRecommendationsResponse>;
|
|
386
|
+
/**
|
|
387
|
+
* Fetch recommendations and create a session-bound tracker in one call.
|
|
388
|
+
*
|
|
389
|
+
* Composition convenience over `getRecommendations` + `createTrackingManager`:
|
|
390
|
+
* it derives the tracker's session from the response so callers don't have to
|
|
391
|
+
* thread `session_id` through themselves (and can't bind a tracker to the
|
|
392
|
+
* wrong session). The returned `data` is the **raw** response — call
|
|
393
|
+
* `mapRecommendationsResponse` on it if you want the friendly shape.
|
|
394
|
+
*
|
|
395
|
+
* Throws `DiscoApiError` on non-2xx responses, same as `getRecommendations`.
|
|
396
|
+
*/
|
|
397
|
+
getRecommendationsWithTracker: (request: RecommendationsRequest, options?: GetRecommendationsOptions & CreateTrackingManagerOptions) => Promise<RecommendationsWithTracker>;
|
|
373
398
|
/**
|
|
374
399
|
* Create an event tracker for a recommendations response from this client.
|
|
375
400
|
*
|
|
@@ -380,5 +405,5 @@ declare class DiscoClient {
|
|
|
380
405
|
createTrackingManager: (recommendations: Pick<RecommendationsResponse, "sessionId">, options?: CreateTrackingManagerOptions) => EventTracker;
|
|
381
406
|
}
|
|
382
407
|
//#endregion
|
|
383
|
-
export { type Advertiser, type ApiKeyConfig, type BrandClickInitiatingTarget, type BrandDisplayInitiatingTarget, type BrandProperties, type BrandVisibilityEventType, type CreateTrackingManagerOptions, DiscoApiError, DiscoClient, type DiscoClientConfig, type DiscoEnv, type ElementClickInitiatingTarget, type EventPayload, type EventTracker, type Footer, type GetRecommendationsOptions, type LayoutId, type Offer, type OfferAsset, type OfferCtaDetails, type OfferDisclosureDetails, type OrderDetails, type PlacementDetails, type ProductDisplayInitiatingTarget, type ProductEventType, type ProductProperties, type PublisherCustomization, type Purchase, type RawAdvertiser, type RawFooter, type RawGroupEntry, type RawGroupProperties, type RawOffer, type RawOfferAsset, type RawOfferCtaDetails, type RawPublisherCustomization, type RawRecommendation, type RawRecommendationsResponse, type Recommendation, type RecommendationGroup, type RecommendationsRequest, type RecommendationsResponse, type RunningExperiment, type ShopGidConfig, type UserDetails, type WidgetEventType, envFromApiKey, mapRecommendationsResponse };
|
|
408
|
+
export { type Advertiser, type ApiKeyConfig, type BrandClickInitiatingTarget, type BrandDisplayInitiatingTarget, type BrandProperties, type BrandVisibilityEventType, type CreateTrackingManagerOptions, DiscoApiError, DiscoClient, type DiscoClientConfig, type DiscoEnv, type ElementClickInitiatingTarget, type EventPayload, type EventTracker, type Footer, type GetRecommendationsOptions, type LayoutId, type Offer, type OfferAsset, type OfferCtaDetails, type OfferDisclosureDetails, type OrderDetails, type PlacementDetails, type ProductDisplayInitiatingTarget, type ProductEventType, type ProductProperties, type PublisherCustomization, type Purchase, type RawAdvertiser, type RawFooter, type RawGroupEntry, type RawGroupProperties, type RawOffer, type RawOfferAsset, type RawOfferCtaDetails, type RawPublisherCustomization, type RawRecommendation, type RawRecommendationsResponse, type Recommendation, type RecommendationGroup, type RecommendationsRequest, type RecommendationsResponse, type RecommendationsWithTracker, type RunningExperiment, type ShopGidConfig, type UserDetails, type WidgetEventType, envFromApiKey, mapRecommendationsResponse };
|
|
384
409
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/env.ts","../src/types.ts","../src/TrackingManager.ts","../src/recommendations.ts","../src/recommendationsMapper.ts","../src/DiscoClient.ts"],"mappings":";;AAMA;;;;AAAoB;KAAR,QAAA;ACiBZ;;;;AAAwC;AAKxC;;;;AAA0C;AAQ1C;;AAbA,iBDkBgB,aAAA,CAAc,MAAA,WAAiB,QAAQ;;;;AAnCvD;;KCHY,0BAAA;;ADGQ;AAmCpB;KC9BY,4BAAA;;;AD8B2C;KClB3C,4BAAA;;;AApBZ;KAyBY,8BAAA;;;AAzB0B;AAQtC;;;KAyBY,eAAA;EACV,OAAA;EACA,YAAA;EACA,WAAA;AAAA;AAAA,KAGU,iBAAA;EACV,SAAS;AAAA;AAAA,KAGC,eAAA;AAAA,KAEA,wBAAA;AAAA,KAEA,gBAAA;AAtB8B;AAQ1C;;;;;AAR0C,KAiC9B,YAAA;EACN,IAAA,EAAM,eAAA;AAAA;EAEN,IAAA,EAAM,wBAAA;EACN,KAAA,EAAO,eAAA;EACP,MAAA,EAAQ,4BAAA;AAAA;EAGR,IAAA;EACA,KAAA,EAAO,eAAA;EACP,MAAA,EAAQ,0BAAA;EACR,OAAA;AAAA;EAGA,IAAA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AA,KAGX,kBAAA;EACV,WAAA;EACA,YAAA;EACA,eAAA;AAAA;AAAA,KAGU,aAAA;EACV,EAAA;EACA,SAAA;EACA,UAAA;AAAA;AAAA,KAGU,SAAA;EACV,mBAAA;IACE,IAAA;IACA,cAAA;IACA,UAAA;EAAA;EAEF,cAAA;IACE,IAAA;IACA,UAAA;EAAA;AAAA;AAAA,KAIQ,yBAAA,GAA4B,MAAM,SAAS,MAAA;;;;;;;;;;iBAavC,0BAAA,CACd,GAAA,EAAK,0BAAA,GACJ,uBAAuB;;;;AJzHN;AAmCpB;;;;AAAuD;;KKzB3C,YAAA;EACV,MAAA;EACA,KAAA,UAAe,KAAK;AAAA;;;AJfgB;AAQtC;;;;AAAwC;AAYxC;;;KISY,aAAA;EACV,OAAA;EACA,GAAA,EAAK,QAAA;EACL,KAAA,UAAe,KAAK;AAAA;AAAA,KAGV,iBAAA,GAAoB,YAAA,GAAe,aAAa;AAAA,KAEhD,yBAAA;EJJA,uEIMV,MAAA,GAAS,WAAW;AAAA;AAAA,KAGV,4BAAA;EJRV;;;;EIaA,KAAA,UAAe,KAAK;AAAA;;;;AJPX;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/env.ts","../src/types.ts","../src/TrackingManager.ts","../src/recommendations.ts","../src/recommendationsMapper.ts","../src/DiscoClient.ts"],"mappings":";;AAMA;;;;AAAoB;KAAR,QAAA;ACiBZ;;;;AAAwC;AAKxC;;;;AAA0C;AAQ1C;;AAbA,iBDkBgB,aAAA,CAAc,MAAA,WAAiB,QAAQ;;;;AAnCvD;;KCHY,0BAAA;;ADGQ;AAmCpB;KC9BY,4BAAA;;;AD8B2C;KClB3C,4BAAA;;;AApBZ;KAyBY,8BAAA;;;AAzB0B;AAQtC;;;KAyBY,eAAA;EACV,OAAA;EACA,YAAA;EACA,WAAA;AAAA;AAAA,KAGU,iBAAA;EACV,SAAS;AAAA;AAAA,KAGC,eAAA;AAAA,KAEA,wBAAA;AAAA,KAEA,gBAA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AA;cAMC,MAAA,EAAQ,iBAAA;EJ3ChB;;;;;;;;;EIuEJ,kBAAA,GACE,OAAA,EAAS,sBAAA,EACT,OAAA,GAAU,yBAAA,KACT,OAAA,CAAQ,0BAAA;EJhEP;;;;;;;;;;;EI8FJ,6BAAA,GACE,OAAA,EAAS,sBAAA,EACT,OAAA,GAAU,yBAAA,GAA4B,4BAAA,KACrC,OAAA,CAAQ,0BAAA;EJzFC;;AAA8B;;;;ACtD5C;EGiKE,qBAAA,GACE,eAAA,EAAiB,IAAA,CAAK,uBAAA,gBACtB,OAAA,GAAU,4BAAA,KACT,YAAA;AAAA"}
|
package/dist/index.js
CHANGED
|
@@ -184,6 +184,24 @@ var DiscoClient = class {
|
|
|
184
184
|
return await response.json();
|
|
185
185
|
};
|
|
186
186
|
/**
|
|
187
|
+
* Fetch recommendations and create a session-bound tracker in one call.
|
|
188
|
+
*
|
|
189
|
+
* Composition convenience over `getRecommendations` + `createTrackingManager`:
|
|
190
|
+
* it derives the tracker's session from the response so callers don't have to
|
|
191
|
+
* thread `session_id` through themselves (and can't bind a tracker to the
|
|
192
|
+
* wrong session). The returned `data` is the **raw** response — call
|
|
193
|
+
* `mapRecommendationsResponse` on it if you want the friendly shape.
|
|
194
|
+
*
|
|
195
|
+
* Throws `DiscoApiError` on non-2xx responses, same as `getRecommendations`.
|
|
196
|
+
*/
|
|
197
|
+
getRecommendationsWithTracker = async (request, options) => {
|
|
198
|
+
const data = await this.getRecommendations(request, { signal: options?.signal });
|
|
199
|
+
return {
|
|
200
|
+
data,
|
|
201
|
+
tracker: this.createTrackingManager({ sessionId: data.session_id }, { fetch: options?.fetch })
|
|
202
|
+
};
|
|
203
|
+
};
|
|
204
|
+
/**
|
|
187
205
|
* Create an event tracker for a recommendations response from this client.
|
|
188
206
|
*
|
|
189
207
|
* The tracker uses the same API-key-derived environment as the
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["#endpoint","#sessionId","#fetch","#dedupe","#isDeduped","#toBody","#env","#url","#headers","#fetch"],"sources":["../src/env.ts","../src/TrackingManager.ts","../src/DiscoClient.ts","../src/recommendationsMapper.ts"],"sourcesContent":["/**\n * Disco backend environments. The SDK does not accept arbitrary URLs —\n * consumers pick an environment and the SDK resolves the correct\n * endpoints internally. This keeps partners from pointing the client or\n * tracker at unintended hosts while still supporting staging.\n */\nexport type DiscoEnv = \"production\" | \"staging\";\n\nexport type EnvEndpoints = {\n /** Base URL for the recommendations API (no trailing slash). */\n apiBaseUrl: string;\n /** Absolute URL events are POSTed to. */\n trackingEndpoint: string;\n};\n\nexport const ENV_ENDPOINTS = {\n production: {\n apiBaseUrl: \"https://consumer.disconetwork.com\",\n trackingEndpoint: \"https://consumer.disconetwork.com/track/partners_event/\",\n },\n staging: {\n apiBaseUrl: \"https://consumer.disconetwork-staging.com\",\n trackingEndpoint:\n \"https://consumer.disconetwork-staging.com/track/partners_event/\",\n },\n} as const satisfies Record<DiscoEnv, EnvEndpoints>;\n\nexport const DEFAULT_ENV: DiscoEnv = \"production\";\n\n/**\n * Derive the environment from a Disco public API key.\n *\n * Public keys are prefixed `disco_pk_<env>_…`, where `<env>` is `live`\n * (→ production) or `sandbox` (→ staging). The key is the single source\n * of truth for which backend the SDK talks to — there is no separate\n * `env` to pass or keep in sync, and a `live` key can't be pointed at\n * staging (or vice versa).\n *\n * Throws on anything that isn't a recognized public key — including a\n * secret (`disco_sk_…`) key, which must never be used in browser code.\n */\nexport function envFromApiKey(apiKey: string): DiscoEnv {\n if (apiKey.startsWith(\"disco_pk_live_\")) return \"production\";\n if (apiKey.startsWith(\"disco_pk_sandbox_\")) return \"staging\";\n throw new Error(\n 'Invalid Disco API key: expected a public key prefixed \"disco_pk_live_\" ' +\n '(production) or \"disco_pk_sandbox_\" (staging).',\n );\n}\n","import { ENV_ENDPOINTS, type DiscoEnv } from \"./env.js\";\nimport type { BrandProperties, EventPayload } from \"./types.js\";\n\nexport type TrackingManagerConfig = {\n /**\n * Session identifier returned by the recommendations API. Stamped onto\n * every emitted event as `session_id`. A tracker is meaningless without\n * a session, so this is required — instantiate the manager only after\n * the recommendations response is in hand.\n */\n sessionId: string;\n\n /**\n * Which Disco environment to send events to. The endpoint URL is resolved\n * internally — it is not configurable.\n *\n * Prefer `DiscoClient#createTrackingManager` so tracking uses the same\n * API-key-derived environment as the recommendations call.\n */\n env: DiscoEnv;\n\n /**\n * Override the global `fetch`. Primarily useful in tests and in runtimes\n * that provide a non-standard fetch implementation. Defaults to\n * `globalThis.fetch`.\n */\n fetch?: typeof fetch;\n};\n\nexport type EventTracker = {\n track: (event: EventPayload) => void;\n};\n\n/**\n * Renderer-agnostic event tracker for Disco recommendation surfaces.\n *\n * Owns:\n * - the dedup set (so repeated display/view events for the same brand\n * don't get re-sent within a session)\n * - the network call to the partner-events endpoint\n * - payload formatting (snake_case keys, BE-friendly datetime)\n *\n * Does not know about React. Wrap it in a Provider (`@disconetwork/react`'s\n * `DiscoProvider`) when consuming from a React tree, or instantiate it\n * directly from any other JS environment.\n *\n * `track` is implemented as an instance-bound arrow function so consumers\n * can safely destructure it without losing `this`.\n */\nexport class TrackingManager {\n readonly #endpoint: string;\n readonly #sessionId: string;\n readonly #fetch: typeof fetch;\n readonly #dedupe = new Set<string>();\n\n constructor(config: TrackingManagerConfig) {\n this.#endpoint = ENV_ENDPOINTS[config.env].trackingEndpoint;\n this.#sessionId = config.sessionId;\n this.#fetch = config.fetch ?? globalThis.fetch.bind(globalThis);\n }\n\n /**\n * Send a tracking event. Fire-and-forget — never throws.\n * Failures are logged via `console.error`.\n *\n * Idempotency: `WIDGET_DISPLAY`, `WIDGET_VIEW`, `BRAND_DISPLAY`, and\n * `BRAND_VIEW` are deduped per-instance by (event type, insertionId).\n */\n track = (event: EventPayload): void => {\n if (this.#isDeduped(event)) return;\n\n this.#fetch(this.#endpoint, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(this.#toBody(event)),\n }).catch((error: unknown) => {\n console.error(\"Event tracking failed:\", error);\n });\n };\n\n #isDeduped(event: EventPayload): boolean {\n if (\n event.type === \"WIDGET_DISPLAY\" ||\n event.type === \"WIDGET_VIEW\" ||\n event.type === \"BRAND_DISPLAY\" ||\n event.type === \"BRAND_VIEW\"\n ) {\n const key =\n event.type + (\"brand\" in event ? event.brand.insertionId : \"widget\");\n if (this.#dedupe.has(key)) return true;\n this.#dedupe.add(key);\n }\n return false;\n }\n\n #toBody(event: EventPayload): Record<string, unknown> {\n const commonEventFields = {\n session_id: this.#sessionId,\n event_name: event.type,\n // BE validation can't parse the \"Z\" timezone suffix, so replace it\n // with \"+00:00\".\n event_datetime: new Date().toISOString().replace(\"Z\", \"+00:00\"),\n };\n\n switch (event.type) {\n case \"BRAND_CLICK\":\n case \"BRAND_DISPLAY\":\n case \"BRAND_VIEW\":\n return {\n ...commonEventFields,\n brand_properties: brandProperties(event.brand),\n initiating_target: event.target,\n };\n case \"ELEMENT_CLICK\":\n return {\n ...commonEventFields,\n brand_properties: event.brand\n ? brandProperties(event.brand)\n : undefined,\n initiating_target: event.target,\n };\n default:\n return commonEventFields;\n }\n }\n}\n\nfunction brandProperties(brand: BrandProperties) {\n return {\n offer_id: brand.offerId,\n advertiser_id: brand.advertiserId,\n insertion_id: brand.insertionId,\n };\n}\n","import { ENV_ENDPOINTS, envFromApiKey, type DiscoEnv } from \"./env.js\";\nimport { TrackingManager, type EventTracker } from \"./TrackingManager.js\";\nimport type {\n RecommendationsRequest,\n RecommendationsResponse,\n} from \"./recommendations.js\";\nimport type { RawRecommendationsResponse } from \"./recommendationsMapper.js\";\n\n/**\n * Authenticate with a scoped public API key. Sent as the `x-api-key`\n * header against the unified `/core/recommendations/` endpoint. The key\n * prefix (`disco_pk_live_` / `disco_pk_sandbox_`) determines the\n * environment, so there is no separate `env` to set.\n *\n * Use this from partner apps and server-side code that hold a key.\n */\nexport type ApiKeyConfig = {\n apiKey: string;\n fetch?: typeof fetch;\n};\n\n/**\n * Authenticate by Shopify shop — for surfaces that must not embed a key,\n * notably the App-Store-deployed checkout extension. The request hits the\n * `/core/recommendations/shop_gid/<id>/` proxy with **no** API key; the\n * backend resolves the publisher from the shop and injects the key\n * server-side.\n *\n * `env` is required here because, unlike `ApiKeyConfig`, there is no key\n * to derive it from. `shopGid` may be a full `gid://shopify/Shop/<id>` or\n * the bare id.\n */\nexport type ShopGidConfig = {\n shopGid: string;\n env: DiscoEnv;\n fetch?: typeof fetch;\n};\n\nexport type DiscoClientConfig = ApiKeyConfig | ShopGidConfig;\n\nexport type GetRecommendationsOptions = {\n /** Forwarded to `fetch` so consumers can cancel in-flight requests. */\n signal?: AbortSignal;\n};\n\nexport type CreateTrackingManagerOptions = {\n /**\n * Override the fetch implementation used by the tracker. Defaults to the\n * same fetch implementation configured on the client.\n */\n fetch?: typeof fetch;\n};\n\n/**\n * Thrown by `DiscoClient.getRecommendations` when the server returns a\n * non-2xx status. The HTTP status and an optional parsed body are\n * preserved for error UIs and retry logic.\n */\nexport class DiscoApiError extends Error {\n readonly status: number;\n readonly statusText: string;\n readonly body: unknown;\n\n constructor(\n message: string,\n info: {\n status: number;\n statusText: string;\n body?: unknown;\n },\n ) {\n super(message);\n this.name = \"DiscoApiError\";\n this.status = info.status;\n this.statusText = info.statusText;\n this.body = info.body;\n }\n}\n\n/**\n * Typed client for the Disco recommendations API.\n *\n * Renderer-agnostic: this class makes plain HTTP calls and has no\n * React dependency. Wrap it in a Provider (`@disconetwork/react`'s\n * `DiscoProvider`) for use from a React tree, or instantiate it\n * directly from server code, scripts, or tests.\n */\nexport class DiscoClient {\n readonly #env: DiscoEnv;\n readonly #url: string;\n readonly #headers: Record<string, string>;\n readonly #fetch: typeof fetch;\n\n constructor(config: DiscoClientConfig) {\n this.#fetch = config.fetch ?? globalThis.fetch.bind(globalThis);\n\n if (\"apiKey\" in config) {\n this.#env = envFromApiKey(config.apiKey);\n this.#url = `${ENV_ENDPOINTS[this.#env].apiBaseUrl}/core/recommendations/`;\n this.#headers = {\n \"x-api-key\": config.apiKey,\n \"Content-Type\": \"application/json\",\n };\n } else {\n this.#env = config.env;\n const shopId = stripShopGid(config.shopGid);\n this.#url = `${ENV_ENDPOINTS[this.#env].apiBaseUrl}/core/recommendations/shop_gid/${encodeURIComponent(shopId)}/`;\n // No x-api-key: the backend resolves auth from the shop_gid.\n this.#headers = { \"Content-Type\": \"application/json\" };\n }\n }\n\n /**\n * POST the recommendations endpoint and return the backend's response\n * **verbatim** — this reflects `ExternalAPIRecommendationView` with no\n * transformation. Pass the result through `mapRecommendationsResponse`\n * if you want the friendly denormalized `RecommendationsResponse`.\n *\n * Throws `DiscoApiError` on non-2xx responses; other failures\n * (network, parse) propagate as-is.\n */\n getRecommendations = async (\n request: RecommendationsRequest,\n options?: GetRecommendationsOptions,\n ): Promise<RawRecommendationsResponse> => {\n const response = await this.#fetch(this.#url, {\n method: \"POST\",\n headers: this.#headers,\n body: JSON.stringify(toRequestBody(request)),\n signal: options?.signal,\n });\n\n if (!response.ok) {\n const body = await safeReadBody(response);\n throw new DiscoApiError(\n `Recommendations request failed: ${response.status} ${response.statusText}`,\n { status: response.status, statusText: response.statusText, body },\n );\n }\n\n return (await response.json()) as RawRecommendationsResponse;\n };\n\n /**\n * Create an event tracker for a recommendations response from this client.\n *\n * The tracker uses the same API-key-derived environment as the\n * recommendations call, so sandbox recommendations cannot accidentally emit\n * production tracking events.\n */\n createTrackingManager = (\n recommendations: Pick<RecommendationsResponse, \"sessionId\">,\n options?: CreateTrackingManagerOptions,\n ): EventTracker =>\n new TrackingManager({\n sessionId: recommendations.sessionId,\n env: this.#env,\n fetch: options?.fetch ?? this.#fetch,\n });\n}\n\nfunction stripShopGid(shopGid: string): string {\n return shopGid.replace(\"gid://shopify/Shop/\", \"\");\n}\n\n// ─── Request transformation ────────────────────────────────────────────────\n\nfunction toRequestBody(req: RecommendationsRequest): Record<string, unknown> {\n return {\n recommendations_data: {\n user_details: req.user && {\n email: req.user.email,\n first_name: req.user.firstName,\n last_name: req.user.lastName,\n phone: req.user.phone,\n },\n placement_details: req.placement && {\n display_mode: req.placement.displayMode,\n view: req.placement.view,\n },\n order_details: req.order && {\n order_id: req.order.id,\n cost_details:\n req.order.amount !== undefined || req.order.currencyCode !== undefined\n ? {\n amount: req.order.amount,\n currency_code: req.order.currencyCode,\n }\n : undefined,\n },\n purchases: req.purchases?.map((p) => ({\n name: p.name,\n type: p.type,\n variant: p.variant,\n quantity: p.quantity,\n product_id: p.productId,\n cost_details:\n p.amount !== undefined || p.currencyCode !== undefined\n ? { amount: p.amount, currency_code: p.currencyCode }\n : undefined,\n })),\n },\n running_experiments: req.experiments?.map((e) => ({\n id: e.id,\n variant: e.variant,\n })),\n attributes: req.attributes,\n ...req.extras,\n };\n}\n\n// ─── Misc ──────────────────────────────────────────────────────────────────\n\nasync function safeReadBody(response: Response): Promise<unknown> {\n try {\n return await response.clone().json();\n } catch {\n try {\n return await response.text();\n } catch {\n return undefined;\n }\n }\n}\n","/**\n * Raw wire types for the recommendations endpoint and the opt-in mapper\n * that denormalizes them into the public `RecommendationsResponse`.\n *\n * `DiscoClient.getRecommendations` returns `RawRecommendationsResponse`\n * verbatim — it reflects exactly what the backend's\n * `ExternalAPIRecommendationView` returns, with no transformation. Callers\n * that want the friendlier denormalized shape pass that raw value through\n * `mapRecommendationsResponse`. Keeping the two separate means the SDK's\n * transport contract is just \"the server's response\", and the (drift-prone)\n * mapping is an explicit, swappable step.\n */\n\nimport type {\n Advertiser,\n Footer,\n Offer,\n OfferAsset,\n OfferCtaDetails,\n Recommendation,\n RecommendationGroup,\n RecommendationsResponse,\n} from \"./recommendations.js\";\n\n// ─── Raw wire shape ──────────────────────────────────────────────────────────\n//\n// The endpoint returns a *normalized* payload: a flat map of recommendations\n// keyed by offer id, separate per-group entry lists that reference those offer\n// ids, and separate per-group properties. Plus assorted top-level fields the\n// proxy adds (widget_type, etc.) that the mapper doesn't need but that other\n// consumers (e.g. the script SDK) read directly off the raw response.\n\nexport type RawRecommendationsResponse = {\n session_id: string;\n layout_id: string;\n /** Map of offer id → recommendation. */\n recommendations?: Record<string, RawRecommendation> | null;\n /** Map of group key → ordered entry list referencing offer ids. */\n recommendation_groups?: Record<string, RawGroupEntry[]> | null;\n /** Map of group key → group display properties. */\n recommendation_group_properties?: Record<string, RawGroupProperties> | null;\n footer: RawFooter;\n publisher_customization?: RawPublisherCustomization | null;\n // Proxy-added top-level fields. Not used by the mapper; surfaced so raw\n // consumers can read them. Open-ended — see ExternalAPIRecommendationView.\n is_using_cmos_recommendations?: boolean;\n widget_type?: string;\n widget_mode?: string;\n widget_version?: string;\n running_experiments?: unknown[];\n};\n\nexport type RawRecommendation = {\n advertiser: RawAdvertiser;\n offer: RawOffer;\n};\n\nexport type RawGroupEntry = {\n insertion_order: number;\n insertion_id: string;\n offer_id: string;\n advertiser_id: string;\n};\n\nexport type RawGroupProperties = {\n heading?: string | null;\n slot_context: string;\n};\n\nexport type RawAdvertiser = {\n id: string;\n name: string;\n logo_url: string;\n description?: string | null;\n};\n\nexport type RawOffer = {\n id: string;\n heading?: string | null;\n subheading?: string | null;\n json_content?: Record<string, unknown> | null;\n target_url: string;\n cta_details: RawOfferCtaDetails;\n assets?: RawOfferAsset[] | null;\n metadata?: Record<string, unknown> | null;\n disclosure_details?: Record<string, unknown> | null;\n};\n\nexport type RawOfferCtaDetails = {\n accept_copy: string;\n decline_copy: string;\n transition_copy?: string | null;\n};\n\nexport type RawOfferAsset = {\n id: string;\n image_url: string;\n target_url?: string | null;\n};\n\nexport type RawFooter = {\n attribution_details: {\n copy: string;\n disco_logo_url: string;\n target_url: string;\n };\n privacy_policy: {\n copy: string;\n target_url: string;\n };\n};\n\nexport type RawPublisherCustomization = Record<string, Record<string, string>>;\n\n// ─── Mapper ───────────────────────────────────────────────────────────────────\n\n/**\n * Denormalize a raw recommendations response into the public\n * `RecommendationsResponse`: join group entries → recommendations by offer id,\n * order groups by the numeric suffix of their key (group_0, group_1, …), and\n * convert snake_case to camelCase.\n *\n * Pure and side-effect-free — call it on the result of\n * `DiscoClient.getRecommendations` when you want the friendly shape.\n */\nexport function mapRecommendationsResponse(\n raw: RawRecommendationsResponse,\n): RecommendationsResponse {\n const recommendations = raw.recommendations ?? {};\n const groupEntries = raw.recommendation_groups ?? {};\n const groupProps = raw.recommendation_group_properties ?? {};\n\n const orderedKeys = Object.keys(groupEntries).sort(\n (a, b) => numericSuffix(a) - numericSuffix(b),\n );\n\n const recommendationGroups: RecommendationGroup[] = [];\n for (const key of orderedKeys) {\n const entries = groupEntries[key];\n const props = groupProps[key];\n // Skip groups missing their entry list or display properties.\n if (!entries || !props) continue;\n\n const recs: Recommendation[] = [];\n for (const entry of entries) {\n const rawRec = recommendations[entry.offer_id];\n if (!rawRec) continue; // entry references an absent recommendation\n recs.push({\n id: rawRec.offer.id,\n insertionId: entry.insertion_id,\n advertiser: mapAdvertiser(rawRec.advertiser),\n offer: mapOffer(rawRec.offer),\n });\n }\n\n recommendationGroups.push({\n heading: props.heading ?? null,\n slotContext: props.slot_context,\n recommendations: recs,\n });\n }\n\n return {\n sessionId: raw.session_id,\n layoutId: raw.layout_id,\n recommendationGroups,\n footer: mapFooter(raw.footer),\n publisherCustomization: raw.publisher_customization ?? null,\n };\n}\n\nfunction numericSuffix(value: string): number {\n const suffix = value.split(\"_\").pop() ?? \"\";\n const parsed = Number.parseInt(suffix, 10);\n return Number.isNaN(parsed) ? Number.POSITIVE_INFINITY : parsed;\n}\n\nfunction mapAdvertiser(raw: RawAdvertiser): Advertiser {\n return {\n id: raw.id,\n name: raw.name,\n logoUrl: raw.logo_url,\n description: raw.description ?? null,\n };\n}\n\nfunction mapOffer(raw: RawOffer): Offer {\n return {\n id: raw.id,\n heading: raw.heading ?? null,\n subheading: raw.subheading ?? null,\n jsonContent: raw.json_content ?? null,\n targetUrl: raw.target_url,\n ctaDetails: mapCtaDetails(raw.cta_details),\n assets: (raw.assets ?? []).map(mapAsset),\n metadata: raw.metadata ?? null,\n disclosureDetails: raw.disclosure_details ?? null,\n };\n}\n\nfunction mapCtaDetails(raw: RawOfferCtaDetails): OfferCtaDetails {\n return {\n acceptCopy: raw.accept_copy,\n declineCopy: raw.decline_copy,\n transitionCopy: raw.transition_copy ?? null,\n };\n}\n\nfunction mapAsset(raw: RawOfferAsset): OfferAsset {\n return {\n id: raw.id,\n imageUrl: raw.image_url,\n targetUrl: raw.target_url ?? null,\n };\n}\n\nfunction mapFooter(raw: RawFooter): Footer {\n return {\n attributionDetails: {\n copy: raw.attribution_details.copy,\n discoLogoUrl: raw.attribution_details.disco_logo_url,\n targetUrl: raw.attribution_details.target_url,\n },\n privacyPolicy: {\n copy: raw.privacy_policy.copy,\n targetUrl: raw.privacy_policy.target_url,\n },\n };\n}\n"],"mappings":";AAeA,MAAa,gBAAgB;CAC3B,YAAY;EACV,YAAY;EACZ,kBAAkB;CACpB;CACA,SAAS;EACP,YAAY;EACZ,kBACE;CACJ;AACF;;;;;;;;;;;;;AAgBA,SAAgB,cAAc,QAA0B;CACtD,IAAI,OAAO,WAAW,gBAAgB,GAAG,OAAO;CAChD,IAAI,OAAO,WAAW,mBAAmB,GAAG,OAAO;CACnD,MAAM,IAAI,MACR,2HAEF;AACF;;;;;;;;;;;;;;;;;;;ACCA,IAAa,kBAAb,MAA6B;CAC3B;CACA;CACA;CACA,0BAAmB,IAAI,IAAY;CAEnC,YAAY,QAA+B;EACzC,KAAKA,YAAY,cAAc,OAAO,KAAK;EAC3C,KAAKC,aAAa,OAAO;EACzB,KAAKC,SAAS,OAAO,SAAS,WAAW,MAAM,KAAK,UAAU;CAChE;;;;;;;;CASA,SAAS,UAA8B;EACrC,IAAI,KAAKE,WAAW,KAAK,GAAG;EAE5B,KAAKF,OAAO,KAAKF,WAAW;GAC1B,QAAQ;GACR,SAAS,EAAE,gBAAgB,mBAAmB;GAC9C,MAAM,KAAK,UAAU,KAAKK,QAAQ,KAAK,CAAC;EAC1C,CAAC,EAAE,OAAO,UAAmB;GAC3B,QAAQ,MAAM,0BA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IAAI,oBAAoB;GAC9B,cAAc,IAAI,oBAAoB;GACtC,WAAW,IAAI,oBAAoB;EACrC;EACA,eAAe;GACb,MAAM,IAAI,eAAe;GACzB,WAAW,IAAI,eAAe;EAChC;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["#endpoint","#sessionId","#fetch","#dedupe","#isDeduped","#toBody","#env","#url","#headers","#fetch"],"sources":["../src/env.ts","../src/TrackingManager.ts","../src/DiscoClient.ts","../src/recommendationsMapper.ts"],"sourcesContent":["/**\n * Disco backend environments. The SDK does not accept arbitrary URLs —\n * consumers pick an environment and the SDK resolves the correct\n * endpoints internally. This keeps partners from pointing the client or\n * tracker at unintended hosts while still supporting staging.\n */\nexport type DiscoEnv = \"production\" | \"staging\";\n\nexport type EnvEndpoints = {\n /** Base URL for the recommendations API (no trailing slash). */\n apiBaseUrl: string;\n /** Absolute URL events are POSTed to. */\n trackingEndpoint: string;\n};\n\nexport const ENV_ENDPOINTS = {\n production: {\n apiBaseUrl: \"https://consumer.disconetwork.com\",\n trackingEndpoint: \"https://consumer.disconetwork.com/track/partners_event/\",\n },\n staging: {\n apiBaseUrl: \"https://consumer.disconetwork-staging.com\",\n trackingEndpoint:\n \"https://consumer.disconetwork-staging.com/track/partners_event/\",\n },\n} as const satisfies Record<DiscoEnv, EnvEndpoints>;\n\nexport const DEFAULT_ENV: DiscoEnv = \"production\";\n\n/**\n * Derive the environment from a Disco public API key.\n *\n * Public keys are prefixed `disco_pk_<env>_…`, where `<env>` is `live`\n * (→ production) or `sandbox` (→ staging). The key is the single source\n * of truth for which backend the SDK talks to — there is no separate\n * `env` to pass or keep in sync, and a `live` key can't be pointed at\n * staging (or vice versa).\n *\n * Throws on anything that isn't a recognized public key — including a\n * secret (`disco_sk_…`) key, which must never be used in browser code.\n */\nexport function envFromApiKey(apiKey: string): DiscoEnv {\n if (apiKey.startsWith(\"disco_pk_live_\")) return \"production\";\n if (apiKey.startsWith(\"disco_pk_sandbox_\")) return \"staging\";\n throw new Error(\n 'Invalid Disco API key: expected a public key prefixed \"disco_pk_live_\" ' +\n '(production) or \"disco_pk_sandbox_\" (staging).',\n );\n}\n","import { ENV_ENDPOINTS, type DiscoEnv } from \"./env.js\";\nimport type { BrandProperties, EventPayload } from \"./types.js\";\n\nexport type TrackingManagerConfig = {\n /**\n * Session identifier returned by the recommendations API. Stamped onto\n * every emitted event as `session_id`. A tracker is meaningless without\n * a session, so this is required — instantiate the manager only after\n * the recommendations response is in hand.\n */\n sessionId: string;\n\n /**\n * Which Disco environment to send events to. The endpoint URL is resolved\n * internally — it is not configurable.\n *\n * Prefer `DiscoClient#createTrackingManager` so tracking uses the same\n * API-key-derived environment as the recommendations call.\n */\n env: DiscoEnv;\n\n /**\n * Override the global `fetch`. Primarily useful in tests and in runtimes\n * that provide a non-standard fetch implementation. Defaults to\n * `globalThis.fetch`.\n */\n fetch?: typeof fetch;\n};\n\nexport type EventTracker = {\n track: (event: EventPayload) => void;\n};\n\n/**\n * Renderer-agnostic event tracker for Disco recommendation surfaces.\n *\n * Owns:\n * - the dedup set (so repeated display/view events for the same brand\n * don't get re-sent within a session)\n * - the network call to the partner-events endpoint\n * - payload formatting (snake_case keys, BE-friendly datetime)\n *\n * Does not know about React. Wrap it in a Provider (`@disconetwork/react`'s\n * `DiscoProvider`) when consuming from a React tree, or instantiate it\n * directly from any other JS environment.\n *\n * `track` is implemented as an instance-bound arrow function so consumers\n * can safely destructure it without losing `this`.\n */\nexport class TrackingManager {\n readonly #endpoint: string;\n readonly #sessionId: string;\n readonly #fetch: typeof fetch;\n readonly #dedupe = new Set<string>();\n\n constructor(config: TrackingManagerConfig) {\n this.#endpoint = ENV_ENDPOINTS[config.env].trackingEndpoint;\n this.#sessionId = config.sessionId;\n this.#fetch = config.fetch ?? globalThis.fetch.bind(globalThis);\n }\n\n /**\n * Send a tracking event. Fire-and-forget — never throws.\n * Failures are logged via `console.error`.\n *\n * Idempotency: `WIDGET_DISPLAY`, `WIDGET_VIEW`, `BRAND_DISPLAY`, and\n * `BRAND_VIEW` are deduped per-instance by (event type, insertionId).\n */\n track = (event: EventPayload): void => {\n if (this.#isDeduped(event)) return;\n\n this.#fetch(this.#endpoint, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(this.#toBody(event)),\n }).catch((error: unknown) => {\n console.error(\"Event tracking failed:\", error);\n });\n };\n\n #isDeduped(event: EventPayload): boolean {\n if (\n event.type === \"WIDGET_DISPLAY\" ||\n event.type === \"WIDGET_VIEW\" ||\n event.type === \"BRAND_DISPLAY\" ||\n event.type === \"BRAND_VIEW\"\n ) {\n const key =\n event.type + (\"brand\" in event ? event.brand.insertionId : \"widget\");\n if (this.#dedupe.has(key)) return true;\n this.#dedupe.add(key);\n }\n return false;\n }\n\n #toBody(event: EventPayload): Record<string, unknown> {\n const commonEventFields = {\n session_id: this.#sessionId,\n event_name: event.type,\n // BE validation can't parse the \"Z\" timezone suffix, so replace it\n // with \"+00:00\".\n event_datetime: new Date().toISOString().replace(\"Z\", \"+00:00\"),\n };\n\n switch (event.type) {\n case \"BRAND_CLICK\":\n case \"BRAND_DISPLAY\":\n case \"BRAND_VIEW\":\n return {\n ...commonEventFields,\n brand_properties: brandProperties(event.brand),\n initiating_target: event.target,\n };\n case \"ELEMENT_CLICK\":\n return {\n ...commonEventFields,\n brand_properties: event.brand\n ? brandProperties(event.brand)\n : undefined,\n initiating_target: event.target,\n };\n default:\n return commonEventFields;\n }\n }\n}\n\nfunction brandProperties(brand: BrandProperties) {\n return {\n offer_id: brand.offerId,\n advertiser_id: brand.advertiserId,\n insertion_id: brand.insertionId,\n };\n}\n","import { ENV_ENDPOINTS, envFromApiKey, type DiscoEnv } from \"./env.js\";\nimport { TrackingManager, type EventTracker } from \"./TrackingManager.js\";\nimport type {\n RecommendationsRequest,\n RecommendationsResponse,\n} from \"./recommendations.js\";\nimport type { RawRecommendationsResponse } from \"./recommendationsMapper.js\";\n\n/**\n * Authenticate with a scoped public API key. Sent as the `x-api-key`\n * header against the unified `/core/recommendations/` endpoint. The key\n * prefix (`disco_pk_live_` / `disco_pk_sandbox_`) determines the\n * environment, so there is no separate `env` to set.\n *\n * Use this from partner apps and server-side code that hold a key.\n */\nexport type ApiKeyConfig = {\n apiKey: string;\n fetch?: typeof fetch;\n};\n\n/**\n * Authenticate by Shopify shop — for surfaces that must not embed a key,\n * notably the App-Store-deployed checkout extension. The request hits the\n * `/core/recommendations/shop_gid/<id>/` proxy with **no** API key; the\n * backend resolves the publisher from the shop and injects the key\n * server-side.\n *\n * `env` is required here because, unlike `ApiKeyConfig`, there is no key\n * to derive it from. `shopGid` may be a full `gid://shopify/Shop/<id>` or\n * the bare id.\n */\nexport type ShopGidConfig = {\n shopGid: string;\n env: DiscoEnv;\n fetch?: typeof fetch;\n};\n\nexport type DiscoClientConfig = ApiKeyConfig | ShopGidConfig;\n\nexport type GetRecommendationsOptions = {\n /** Forwarded to `fetch` so consumers can cancel in-flight requests. */\n signal?: AbortSignal;\n};\n\nexport type CreateTrackingManagerOptions = {\n /**\n * Override the fetch implementation used by the tracker. Defaults to the\n * same fetch implementation configured on the client.\n */\n fetch?: typeof fetch;\n};\n\n/**\n * Result of `getRecommendationsWithTracker`: the **raw** recommendations\n * response plus a tracker already bound to its session.\n */\nexport type RecommendationsWithTracker = {\n /**\n * The verbatim API response (snake_case), exactly as `getRecommendations`\n * returns it. Pass it through `mapRecommendationsResponse` for the friendly\n * denormalized shape.\n */\n data: RawRecommendationsResponse;\n /** Event tracker bound to this response's session. */\n tracker: EventTracker;\n};\n\n/**\n * Thrown by `DiscoClient.getRecommendations` when the server returns a\n * non-2xx status. The HTTP status and an optional parsed body are\n * preserved for error UIs and retry logic.\n */\nexport class DiscoApiError extends Error {\n readonly status: number;\n readonly statusText: string;\n readonly body: unknown;\n\n constructor(\n message: string,\n info: {\n status: number;\n statusText: string;\n body?: unknown;\n },\n ) {\n super(message);\n this.name = \"DiscoApiError\";\n this.status = info.status;\n this.statusText = info.statusText;\n this.body = info.body;\n }\n}\n\n/**\n * Typed client for the Disco recommendations API.\n *\n * Renderer-agnostic: this class makes plain HTTP calls and has no\n * React dependency. Wrap it in a Provider (`@disconetwork/react`'s\n * `DiscoProvider`) for use from a React tree, or instantiate it\n * directly from server code, scripts, or tests.\n */\nexport class DiscoClient {\n readonly #env: DiscoEnv;\n readonly #url: string;\n readonly #headers: Record<string, string>;\n readonly #fetch: typeof fetch;\n\n constructor(config: DiscoClientConfig) {\n this.#fetch = config.fetch ?? globalThis.fetch.bind(globalThis);\n\n if (\"apiKey\" in config) {\n this.#env = envFromApiKey(config.apiKey);\n this.#url = `${ENV_ENDPOINTS[this.#env].apiBaseUrl}/core/recommendations/`;\n this.#headers = {\n \"x-api-key\": config.apiKey,\n \"Content-Type\": \"application/json\",\n };\n } else {\n this.#env = config.env;\n const shopId = stripShopGid(config.shopGid);\n this.#url = `${ENV_ENDPOINTS[this.#env].apiBaseUrl}/core/recommendations/shop_gid/${encodeURIComponent(shopId)}/`;\n // No x-api-key: the backend resolves auth from the shop_gid.\n this.#headers = { \"Content-Type\": \"application/json\" };\n }\n }\n\n /**\n * POST the recommendations endpoint and return the backend's response\n * **verbatim** — this reflects `ExternalAPIRecommendationView` with no\n * transformation. Pass the result through `mapRecommendationsResponse`\n * if you want the friendly denormalized `RecommendationsResponse`.\n *\n * Throws `DiscoApiError` on non-2xx responses; other failures\n * (network, parse) propagate as-is.\n */\n getRecommendations = async (\n request: RecommendationsRequest,\n options?: GetRecommendationsOptions,\n ): Promise<RawRecommendationsResponse> => {\n const response = await this.#fetch(this.#url, {\n method: \"POST\",\n headers: this.#headers,\n body: JSON.stringify(toRequestBody(request)),\n signal: options?.signal,\n });\n\n if (!response.ok) {\n const body = await safeReadBody(response);\n throw new DiscoApiError(\n `Recommendations request failed: ${response.status} ${response.statusText}`,\n { status: response.status, statusText: response.statusText, body },\n );\n }\n\n return (await response.json()) as RawRecommendationsResponse;\n };\n\n /**\n * Fetch recommendations and create a session-bound tracker in one call.\n *\n * Composition convenience over `getRecommendations` + `createTrackingManager`:\n * it derives the tracker's session from the response so callers don't have to\n * thread `session_id` through themselves (and can't bind a tracker to the\n * wrong session). The returned `data` is the **raw** response — call\n * `mapRecommendationsResponse` on it if you want the friendly shape.\n *\n * Throws `DiscoApiError` on non-2xx responses, same as `getRecommendations`.\n */\n getRecommendationsWithTracker = async (\n request: RecommendationsRequest,\n options?: GetRecommendationsOptions & CreateTrackingManagerOptions,\n ): Promise<RecommendationsWithTracker> => {\n const data = await this.getRecommendations(request, {\n signal: options?.signal,\n });\n const tracker = this.createTrackingManager(\n { sessionId: data.session_id },\n { fetch: options?.fetch },\n );\n return { data, tracker };\n };\n\n /**\n * Create an event tracker for a recommendations response from this client.\n *\n * The tracker uses the same API-key-derived environment as the\n * recommendations call, so sandbox recommendations cannot accidentally emit\n * production tracking events.\n */\n createTrackingManager = (\n recommendations: Pick<RecommendationsResponse, \"sessionId\">,\n options?: CreateTrackingManagerOptions,\n ): EventTracker =>\n new TrackingManager({\n sessionId: recommendations.sessionId,\n env: this.#env,\n fetch: options?.fetch ?? this.#fetch,\n });\n}\n\nfunction stripShopGid(shopGid: string): string {\n return shopGid.replace(\"gid://shopify/Shop/\", \"\");\n}\n\n// ─── Request transformation ────────────────────────────────────────────────\n\nfunction toRequestBody(req: RecommendationsRequest): Record<string, unknown> {\n return {\n recommendations_data: {\n user_details: req.user && {\n email: req.user.email,\n first_name: req.user.firstName,\n last_name: req.user.lastName,\n phone: req.user.phone,\n },\n placement_details: req.placement && {\n display_mode: req.placement.displayMode,\n view: req.placement.view,\n },\n order_details: req.order && {\n order_id: req.order.id,\n cost_details:\n req.order.amount !== undefined || req.order.currencyCode !== undefined\n ? {\n amount: req.order.amount,\n currency_code: req.order.currencyCode,\n }\n : undefined,\n },\n purchases: req.purchases?.map((p) => ({\n name: p.name,\n type: p.type,\n variant: p.variant,\n quantity: p.quantity,\n product_id: p.productId,\n cost_details:\n p.amount !== undefined || p.currencyCode !== undefined\n ? { amount: p.amount, currency_code: p.currencyCode }\n : undefined,\n })),\n },\n running_experiments: req.experiments?.map((e) => ({\n id: e.id,\n variant: e.variant,\n })),\n attributes: req.attributes,\n ...req.extras,\n };\n}\n\n// ─── Misc ──────────────────────────────────────────────────────────────────\n\nasync function safeReadBody(response: Response): Promise<unknown> {\n try {\n return await response.clone().json();\n } catch {\n try {\n return await response.text();\n } catch {\n return undefined;\n }\n }\n}\n","/**\n * Raw wire types for the recommendations endpoint and the opt-in mapper\n * that denormalizes them into the public `RecommendationsResponse`.\n *\n * `DiscoClient.getRecommendations` returns `RawRecommendationsResponse`\n * verbatim — it reflects exactly what the backend's\n * `ExternalAPIRecommendationView` returns, with no transformation. Callers\n * that want the friendlier denormalized shape pass that raw value through\n * `mapRecommendationsResponse`. Keeping the two separate means the SDK's\n * transport contract is just \"the server's response\", and the (drift-prone)\n * mapping is an explicit, swappable step.\n */\n\nimport type {\n Advertiser,\n Footer,\n Offer,\n OfferAsset,\n OfferCtaDetails,\n Recommendation,\n RecommendationGroup,\n RecommendationsResponse,\n} from \"./recommendations.js\";\n\n// ─── Raw wire shape ──────────────────────────────────────────────────────────\n//\n// The endpoint returns a *normalized* payload: a flat map of recommendations\n// keyed by offer id, separate per-group entry lists that reference those offer\n// ids, and separate per-group properties. Plus assorted top-level fields the\n// proxy adds (widget_type, etc.) that the mapper doesn't need but that other\n// consumers (e.g. the script SDK) read directly off the raw response.\n\nexport type RawRecommendationsResponse = {\n session_id: string;\n layout_id: string;\n /** Map of offer id → recommendation. */\n recommendations?: Record<string, RawRecommendation> | null;\n /** Map of group key → ordered entry list referencing offer ids. */\n recommendation_groups?: Record<string, RawGroupEntry[]> | null;\n /** Map of group key → group display properties. */\n recommendation_group_properties?: Record<string, RawGroupProperties> | null;\n footer: RawFooter;\n publisher_customization?: RawPublisherCustomization | null;\n // Proxy-added top-level fields. Not used by the mapper; surfaced so raw\n // consumers can read them. Open-ended — see ExternalAPIRecommendationView.\n is_using_cmos_recommendations?: boolean;\n widget_type?: string;\n widget_mode?: string;\n widget_version?: string;\n running_experiments?: unknown[];\n};\n\nexport type RawRecommendation = {\n advertiser: RawAdvertiser;\n offer: RawOffer;\n};\n\nexport type RawGroupEntry = {\n insertion_order: number;\n insertion_id: string;\n offer_id: string;\n advertiser_id: string;\n};\n\nexport type RawGroupProperties = {\n heading?: string | null;\n slot_context: string;\n};\n\nexport type RawAdvertiser = {\n id: string;\n name: string;\n logo_url: string;\n description?: string | null;\n};\n\nexport type RawOffer = {\n id: string;\n heading?: string | null;\n subheading?: string | null;\n json_content?: Record<string, unknown> | null;\n target_url: string;\n cta_details: RawOfferCtaDetails;\n assets?: RawOfferAsset[] | null;\n metadata?: Record<string, unknown> | null;\n disclosure_details?: Record<string, unknown> | null;\n};\n\nexport type RawOfferCtaDetails = {\n accept_copy: string;\n decline_copy: string;\n transition_copy?: string | null;\n};\n\nexport type RawOfferAsset = {\n id: string;\n image_url: string;\n target_url?: string | null;\n};\n\nexport type RawFooter = {\n attribution_details: {\n copy: string;\n disco_logo_url: string;\n target_url: string;\n };\n privacy_policy: {\n copy: string;\n target_url: string;\n };\n};\n\nexport type RawPublisherCustomization = Record<string, Record<string, string>>;\n\n// ─── Mapper ───────────────────────────────────────────────────────────────────\n\n/**\n * Denormalize a raw recommendations response into the public\n * `RecommendationsResponse`: join group entries → recommendations by offer id,\n * order groups by the numeric suffix of their key (group_0, group_1, …), and\n * convert snake_case to camelCase.\n *\n * Pure and side-effect-free — call it on the result of\n * `DiscoClient.getRecommendations` when you want the friendly shape.\n */\nexport function mapRecommendationsResponse(\n raw: RawRecommendationsResponse,\n): RecommendationsResponse {\n const recommendations = raw.recommendations ?? {};\n const groupEntries = raw.recommendation_groups ?? {};\n const groupProps = raw.recommendation_group_properties ?? {};\n\n const orderedKeys = Object.keys(groupEntries).sort(\n (a, b) => numericSuffix(a) - numericSuffix(b),\n );\n\n const recommendationGroups: RecommendationGroup[] = [];\n for (const key of orderedKeys) {\n const entries = groupEntries[key];\n const props = groupProps[key];\n // Skip groups missing their entry list or display properties.\n if (!entries || !props) continue;\n\n const recs: Recommendation[] = [];\n for (const entry of entries) {\n const rawRec = recommendations[entry.offer_id];\n if (!rawRec) continue; // entry references an absent recommendation\n recs.push({\n id: rawRec.offer.id,\n insertionId: entry.insertion_id,\n advertiser: mapAdvertiser(rawRec.advertiser),\n offer: mapOffer(rawRec.offer),\n });\n }\n\n recommendationGroups.push({\n heading: props.heading ?? null,\n slotContext: props.slot_context,\n recommendations: recs,\n });\n }\n\n return {\n sessionId: raw.session_id,\n layoutId: raw.layout_id,\n recommendationGroups,\n footer: mapFooter(raw.footer),\n publisherCustomization: raw.publisher_customization ?? null,\n };\n}\n\nfunction numericSuffix(value: string): number {\n const suffix = value.split(\"_\").pop() ?? \"\";\n const parsed = Number.parseInt(suffix, 10);\n return Number.isNaN(parsed) ? Number.POSITIVE_INFINITY : parsed;\n}\n\nfunction mapAdvertiser(raw: RawAdvertiser): Advertiser {\n return {\n id: raw.id,\n name: raw.name,\n logoUrl: raw.logo_url,\n description: raw.description ?? null,\n };\n}\n\nfunction mapOffer(raw: RawOffer): Offer {\n return {\n id: raw.id,\n heading: raw.heading ?? null,\n subheading: raw.subheading ?? null,\n jsonContent: raw.json_content ?? null,\n targetUrl: raw.target_url,\n ctaDetails: mapCtaDetails(raw.cta_details),\n assets: (raw.assets ?? []).map(mapAsset),\n metadata: raw.metadata ?? null,\n disclosureDetails: raw.disclosure_details ?? null,\n };\n}\n\nfunction mapCtaDetails(raw: RawOfferCtaDetails): OfferCtaDetails {\n return {\n acceptCopy: raw.accept_copy,\n declineCopy: raw.decline_copy,\n transitionCopy: raw.transition_copy ?? null,\n };\n}\n\nfunction mapAsset(raw: RawOfferAsset): OfferAsset {\n return {\n id: raw.id,\n imageUrl: raw.image_url,\n targetUrl: raw.target_url ?? null,\n };\n}\n\nfunction mapFooter(raw: RawFooter): Footer {\n return {\n attributionDetails: {\n copy: raw.attribution_details.copy,\n discoLogoUrl: raw.attribution_details.disco_logo_url,\n targetUrl: raw.attribution_details.target_url,\n },\n privacyPolicy: {\n copy: raw.privacy_policy.copy,\n targetUrl: raw.privacy_policy.target_url,\n },\n };\n}\n"],"mappings":";AAeA,MAAa,gBAAgB;CAC3B,YAAY;EACV,YAAY;EACZ,kBAAkB;CACpB;CACA,SAAS;EACP,YAAY;EACZ,kBACE;CACJ;AACF;;;;;;;;;;;;;AAgBA,SAAgB,cAAc,QAA0B;CACtD,IAAI,OAAO,WAAW,gBAAgB,GAAG,OAAO;CAChD,IAAI,OAAO,WAAW,mBAAmB,GAAG,OAAO;CACnD,MAAM,IAAI,MACR,2HAEF;AACF;;;;;;;;;;;;;;;;;;;ACCA,IAAa,kBAAb,MAA6B;CAC3B;CACA;CACA;CACA,0BAAmB,IAAI,IAAY;CAEnC,YAAY,QAA+B;EACzC,KAAKA,YAAY,cAAc,OAAO,KAAK;EAC3C,KAAKC,aAAa,OAAO;EACzB,KAAKC,SAAS,OAAO,SAAS,WAAW,MAAM,KAAK,UAAU;CAChE;;;;;;;;CASA,SAAS,UAA8B;EACrC,IAAI,KAAKE,WAAW,KAAK,GAAG;EAE5B,KAAKF,OAAO,KAAKF,WAAW;GAC1B,QAAQ;GACR,SAAS,EAAE,gBAAgB,mBAAmB;GAC9C,MAAM,KAAK,UAAU,KAAKK,QAAQ,KAAK,CAAC;EAC1C,CAAC,EAAE,OAAO,UAAmB;GAC3B,QAAQ,MAAM,0BAA0B,KAAK;EAC/C,CAAC;CACH;CAEA,WAAW,OAA8B;EACvC,IACE,MAAM,SAAS,oBACf,MAAM,SAAS,iBACf,MAAM,SAAS,mBACf,MAAM,SAAS,cACf;GACA,MAAM,MACJ,MAAM,QAAQ,WAAW,QAAQ,MAAM,MAAM,cAAc;GAC7D,IAAI,KAAKF,QAAQ,IAAI,GAAG,GAAG,OAAO;GAClC,KAAKA,QAAQ,IAAI,GAAG;EACtB;EACA,OAAO;CACT;CAEA,QAAQ,OAA8C;EACpD,MAAM,oBAAoB;GACxB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