@disconetwork/core 0.0.13 → 0.0.14

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.
@@ -1,4 +1,5 @@
1
1
  import { C as OfferMetadata, O as RecommendationsResponse$1, S as OfferDisclosureDetails, _ as Advertiser, a as BrandClickInitiatingTarget, b as OfferAsset, c as BrandVisibilityEventType, d as EventPlacementDetails, f as EventTracker, g as WidgetEventType, h as ProductProperties, i as DiscoValidationError, l as ElementClickInitiatingTarget, m as ProductEventType, n as DiscoError, o as BrandDisplayInitiatingTarget, p as ProductDisplayInitiatingTarget, r as DiscoNetworkError, s as BrandProperties, t as DiscoApiError, u as EventPayload, v as Footer, x as OfferCtaDetails, y as Offer } from "./errors-D9ga0zfp.js";
2
+ import * as z from "zod/v4";
2
3
 
3
4
  //#region src/env.d.ts
4
5
  type DiscoEnv = "production" | "staging";
@@ -271,5 +272,120 @@ declare class TrackingManager {
271
272
  */
272
273
  declare function denormalize(response: RecommendationsResponse$1): RecommendationGroup[];
273
274
  //#endregion
274
- export { type Advertiser, type ApiKeyConfig, type BrandClickInitiatingTarget, type BrandDisplayInitiatingTarget, type BrandProperties, type BrandVisibilityEventType, type CreateTrackingManagerOptions, DiscoApiError, type DiscoClientConfig, type DiscoEnv, DiscoError, DiscoNetworkError, DiscoValidationError, type ElementClickInitiatingTarget, type EventPayload, type EventPlacementDetails, type EventTracker, type Footer, type GetRecommendationsOptions, INTERNAL_BASE_URL, InternalDiscoClient, type LayoutId, type Offer, type OfferAsset, type OfferCtaDetails, type OfferDisclosureDetails, type OfferMetadata, type OrderDetails, type PlacementDetails, type ProductDisplayInitiatingTarget, type ProductEventType, type ProductProperties, type PublisherCustomization, type Purchase, type Recommendation, type RecommendationGroup, type RecommendationsRequest, type RecommendationsResponse, type RecommendationsWithTracker, type RunningExperiment, type ShopGidConfig, TrackingManager, type TrackingManagerConfig, type UserDetails, type WidgetEventType, denormalize };
275
+ //#region src/internal/screens.d.ts
276
+ declare const TextNodeSchema: z.ZodObject<{
277
+ type: z.ZodLiteral<"text">;
278
+ text: z.ZodString;
279
+ }, z.core.$strip>;
280
+ type ASTChildrenSchema = z.ZodArray<z.ZodDiscriminatedUnion<[typeof TextNodeSchema, typeof LinkNodeSchema, typeof ParagraphNodeSchema, typeof ScrollViewNodeSchema]>>;
281
+ declare const LinkNodeSchema: z.ZodObject<{
282
+ type: z.ZodLiteral<"link">;
283
+ attributes: z.ZodUnion<readonly [z.ZodObject<{
284
+ to: z.ZodURL;
285
+ external: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
286
+ }, z.core.$strip>, z.ZodObject<{
287
+ targetScreenId: z.ZodString;
288
+ }, z.core.$strip>]>;
289
+ children: ASTChildrenSchema;
290
+ }, z.core.$strip>;
291
+ declare const ParagraphNodeSchema: z.ZodObject<{
292
+ type: z.ZodLiteral<"paragraph">;
293
+ children: ASTChildrenSchema;
294
+ }, z.core.$strip>;
295
+ declare const ScrollViewNodeSchema: z.ZodObject<{
296
+ type: z.ZodLiteral<"scrollview">;
297
+ attributes: z.ZodOptional<z.ZodObject<{
298
+ maxBlockSize: z.ZodOptional<z.ZodNumber>;
299
+ }, z.core.$strip>>;
300
+ children: ASTChildrenSchema;
301
+ }, z.core.$strip>;
302
+ declare const ASTNodeSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
303
+ type: z.ZodLiteral<"text">;
304
+ text: z.ZodString;
305
+ }, z.core.$strip>, z.ZodObject<{
306
+ type: z.ZodLiteral<"link">;
307
+ attributes: z.ZodUnion<readonly [z.ZodObject<{
308
+ to: z.ZodURL;
309
+ external: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
310
+ }, z.core.$strip>, z.ZodObject<{
311
+ targetScreenId: z.ZodString;
312
+ }, z.core.$strip>]>;
313
+ children: ASTChildrenSchema;
314
+ }, z.core.$strip>, z.ZodObject<{
315
+ type: z.ZodLiteral<"paragraph">;
316
+ children: ASTChildrenSchema;
317
+ }, z.core.$strip>, z.ZodObject<{
318
+ type: z.ZodLiteral<"scrollview">;
319
+ attributes: z.ZodOptional<z.ZodObject<{
320
+ maxBlockSize: z.ZodOptional<z.ZodNumber>;
321
+ }, z.core.$strip>>;
322
+ children: ASTChildrenSchema;
323
+ }, z.core.$strip>], "type">;
324
+ declare const ScreenSchema: z.ZodObject<{
325
+ children: z.ZodArray<z.ZodDiscriminatedUnion<[z.ZodObject<{
326
+ type: z.ZodLiteral<"text">;
327
+ text: z.ZodString;
328
+ }, z.core.$strip>, z.ZodObject<{
329
+ type: z.ZodLiteral<"link">;
330
+ attributes: z.ZodUnion<readonly [z.ZodObject<{
331
+ to: z.ZodURL;
332
+ external: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
333
+ }, z.core.$strip>, z.ZodObject<{
334
+ targetScreenId: z.ZodString;
335
+ }, z.core.$strip>]>;
336
+ children: ASTChildrenSchema;
337
+ }, z.core.$strip>, z.ZodObject<{
338
+ type: z.ZodLiteral<"paragraph">;
339
+ children: ASTChildrenSchema;
340
+ }, z.core.$strip>, z.ZodObject<{
341
+ type: z.ZodLiteral<"scrollview">;
342
+ attributes: z.ZodOptional<z.ZodObject<{
343
+ maxBlockSize: z.ZodOptional<z.ZodNumber>;
344
+ }, z.core.$strip>>;
345
+ children: ASTChildrenSchema;
346
+ }, z.core.$strip>], "type">>;
347
+ id: z.ZodString;
348
+ }, z.core.$strip>;
349
+ declare const ScreenDocumentSchema: z.ZodObject<{
350
+ screens: z.ZodArray<z.ZodObject<{
351
+ children: z.ZodArray<z.ZodDiscriminatedUnion<[z.ZodObject<{
352
+ type: z.ZodLiteral<"text">;
353
+ text: z.ZodString;
354
+ }, z.core.$strip>, z.ZodObject<{
355
+ type: z.ZodLiteral<"link">;
356
+ attributes: z.ZodUnion<readonly [z.ZodObject<{
357
+ to: z.ZodURL;
358
+ external: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
359
+ }, z.core.$strip>, z.ZodObject<{
360
+ targetScreenId: z.ZodString;
361
+ }, z.core.$strip>]>;
362
+ children: ASTChildrenSchema;
363
+ }, z.core.$strip>, z.ZodObject<{
364
+ type: z.ZodLiteral<"paragraph">;
365
+ children: ASTChildrenSchema;
366
+ }, z.core.$strip>, z.ZodObject<{
367
+ type: z.ZodLiteral<"scrollview">;
368
+ attributes: z.ZodOptional<z.ZodObject<{
369
+ maxBlockSize: z.ZodOptional<z.ZodNumber>;
370
+ }, z.core.$strip>>;
371
+ children: ASTChildrenSchema;
372
+ }, z.core.$strip>], "type">>;
373
+ id: z.ZodString;
374
+ }, z.core.$strip>>;
375
+ }, z.core.$strip>;
376
+ type TextNode = z.infer<typeof TextNodeSchema>;
377
+ type LinkNode = z.infer<typeof LinkNodeSchema>;
378
+ type ParagraphNode = z.infer<typeof ParagraphNodeSchema>;
379
+ type ScrollViewNode = z.infer<typeof ScrollViewNodeSchema>;
380
+ type ASTNode = z.infer<typeof ASTNodeSchema>;
381
+ type Screen = z.infer<typeof ScreenSchema>;
382
+ type ScreenDocument = z.infer<typeof ScreenDocumentSchema>;
383
+ /**
384
+ * Parse offer screens content into a list of screens. Returns `null` when the
385
+ * content is missing or matches neither the screen document nor the legacy
386
+ * single-root shape, so callers can render a fallback.
387
+ */
388
+ declare function parseScreens(jsonContent: Record<string, unknown> | undefined | null): Screen[] | null;
389
+ //#endregion
390
+ export { type ASTNode, type Advertiser, type ApiKeyConfig, type BrandClickInitiatingTarget, type BrandDisplayInitiatingTarget, type BrandProperties, type BrandVisibilityEventType, type CreateTrackingManagerOptions, DiscoApiError, type DiscoClientConfig, type DiscoEnv, DiscoError, DiscoNetworkError, DiscoValidationError, type ElementClickInitiatingTarget, type EventPayload, type EventPlacementDetails, type EventTracker, type Footer, type GetRecommendationsOptions, INTERNAL_BASE_URL, InternalDiscoClient, type LayoutId, type LinkNode, type Offer, type OfferAsset, type OfferCtaDetails, type OfferDisclosureDetails, type OfferMetadata, type OrderDetails, type ParagraphNode, type PlacementDetails, type ProductDisplayInitiatingTarget, type ProductEventType, type ProductProperties, type PublisherCustomization, type Purchase, type Recommendation, type RecommendationGroup, type RecommendationsRequest, type RecommendationsResponse, type RecommendationsWithTracker, type RunningExperiment, type Screen, type ScreenDocument, type ScrollViewNode, type ShopGidConfig, type TextNode, TrackingManager, type TrackingManagerConfig, type UserDetails, type WidgetEventType, denormalize, parseScreens };
275
391
  //# sourceMappingURL=internal.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"internal.d.ts","names":[],"sources":["../src/env.ts","../src/internal/recommendations.ts","../src/internal/InternalDiscoClient.ts","../src/TrackingManager.ts","../src/internal/denormalize.ts"],"mappings":";;;KAAY,QAAA;;;KCyCA,sBAAA;EACV,IAAA,GAAO,WAAA;EACP,SAAA,GAAY,gBAAA;EACZ,KAAA,GAAQ,YAAA;EACR,SAAA,GAAY,QAAA;EACZ,WAAA,GAAc,iBAAA;EACd,UAAA,GAAa,MAAA;EALN;;;;;;EAYP,MAAA,GAAS,MAAA;AAAA;AAAA,KAGC,WAAA;EACV,KAAA;EACA,SAAA;EACA,QAAA;EACA,KAAA;AAAA;AAAA,KAGU,gBAAA;EAPA,sEASV,WAAA;EAEA,IAAI;AAAA;AAAA,KAGM,YAAA;EACV,EAAA;EACA,MAAA;EACA,YAAA;AAAA;AAAA,KAGU,QAAA;EACV,IAAA;EACA,IAAA;EACA,OAAA;EACA,QAAA;EACA,SAAA;EACA,MAAA;EACA,YAAA;AAAA;AAAA,KAGU,iBAAA;EACV,EAAA;EACA,OAAO;AAAA;AAAA,KAKG,QAAA;AAAA,KAOA,uBAAA;EACV,SAAA;EACA,QAAA,EAAU,QAAA;EACV,oBAAA,EAAsB,mBAAA;EACtB,MAAA,EAAQ,MAAA;EACR,sBAAA,EAAwB,sBAAA;AAAA;AAAA,KAGd,mBAAA;EACV,OAAA;EACA,WAAA;EACA,eAAA,EAAiB,cAAc;AAAA;AA5BnB;AAGd;;;;AAES;AALK,KAqCF,cAAA;EACV,EAAA;EACA,WAAA;EACA,UAAA,EAAY,UA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;;;;;;;;;;AFuBL;AAGjB;;;;;;cEPa,eAAA;EAAA;cAOC,MAAA,EAAQ,qBAAA;EFIf;AAGP;;;;AAIM;AAGN;EEAE,KAAA,GAAS,KAAA,EAAO,YAAY;AAAA;;;;;;;;;;;;;iBC3Cd,WAAA,CACd,QAAA,EAAU,yBAAA,GACT,mBAAmB"}
1
+ {"version":3,"file":"internal.d.ts","names":[],"sources":["../src/env.ts","../src/internal/recommendations.ts","../src/internal/InternalDiscoClient.ts","../src/TrackingManager.ts","../src/internal/denormalize.ts","../src/internal/screens.ts"],"mappings":";;;;KAAY,QAAA;;;KCyCA,sBAAA;EACV,IAAA,GAAO,WAAA;EACP,SAAA,GAAY,gBAAA;EACZ,KAAA,GAAQ,YAAA;EACR,SAAA,GAAY,QAAA;EACZ,WAAA,GAAc,iBAAA;EACd,UAAA,GAAa,MAAA;EALb;;;;;;EAYA,MAAA,GAAS,MAAA;AAAA;AAAA,KAGC,WAAA;EACV,KAAA;EACA,SAAA;EACA,QAAA;EACA,KAAA;AAAA;AAAA,KAGU,gBAAA;EAVK,sEAYf,WAAA,WATqB;EAWrB,IAAI;AAAA;AAAA,KAGM,YAAA;EACV,EAAA;EACA,MAAA;EACA,YAAA;AAAA;AAAA,KAGU,QAAA;EACV,IAAA;EACA,IAAA;EACA,OAAA;EACA,QAAA;EACA,SAAA;EACA,MAAA;EACA,YAAA;AAAA;AAAA,KAGU,iBAAA;EACV,EAAA;EACA,OAAO;AAAA;AAAA,KAKG,QAAA;AAAA,KAOA,uBAAA;EACV,SAAA;EACA,QAAA,EAAU,QAAA;EACV,oBAAA,EAAsB,mBAAA;EACtB,MAAA,EAAQ,MAAA;EACR,sBAAA,EAAwB,sBAAA;AAAA;AAAA,KAGd,mBAAA;EACV,OAAA;EACA,WAAA;EACA,eAAA,EAAiB,cAAc;AAAA;;AA5BnB;AAGd;;;;KAkCY,cAAA;EACV,EAAA;EACA,WAAA;EACA,UAAA,EAAY,UAAA;EACZ,KAAA,EAAO,K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A;AAAA,KACxB,cAAA,GAAiB,CAAA,CAAE,KAAK,QAAQ,oBAAA;;;;;;iBAO5B,YAAA,CACd,WAAA,EAAa,MAAA,uCACZ,MAAM"}
package/dist/internal.js CHANGED
@@ -476,6 +476,79 @@ function stripShopGid(shopGid) {
476
476
  return shopGid.replace("gid://shopify/Shop/", "");
477
477
  }
478
478
  //#endregion
479
- export { DiscoApiError, DiscoError, DiscoNetworkError, DiscoValidationError, INTERNAL_BASE_URL, InternalDiscoClient, TrackingManager, denormalize };
479
+ //#region src/internal/screens.ts
480
+ const TextNodeSchema = z.object({
481
+ type: z.literal("text"),
482
+ text: z.string()
483
+ });
484
+ const ExternalLinkAttributesSchema = z.object({
485
+ to: z.url(),
486
+ external: z.boolean().optional().default(true)
487
+ });
488
+ const InternalLinkAttributesSchema = z.object({ targetScreenId: z.string() });
489
+ const LinkAttributesSchema = z.union([ExternalLinkAttributesSchema, InternalLinkAttributesSchema]);
490
+ const LinkNodeSchema = z.object({
491
+ type: z.literal("link"),
492
+ attributes: LinkAttributesSchema,
493
+ get children() {
494
+ return z.array(ASTNodeSchema).min(1);
495
+ }
496
+ });
497
+ const ParagraphNodeSchema = z.object({
498
+ type: z.literal("paragraph"),
499
+ get children() {
500
+ return z.array(ASTNodeSchema).min(1);
501
+ }
502
+ });
503
+ const ScrollViewNodeSchema = z.object({
504
+ type: z.literal("scrollview"),
505
+ attributes: z.object({ maxBlockSize: z.number().optional() }).optional(),
506
+ get children() {
507
+ return z.array(ASTNodeSchema).min(1);
508
+ }
509
+ });
510
+ const ASTNodeSchema = z.discriminatedUnion("type", [
511
+ TextNodeSchema,
512
+ LinkNodeSchema,
513
+ ParagraphNodeSchema,
514
+ ScrollViewNodeSchema
515
+ ]);
516
+ const ASTSchema = z.object({ get children() {
517
+ return z.array(ASTNodeSchema).min(1);
518
+ } });
519
+ const ScreenSchema = ASTSchema.extend({ id: z.string() });
520
+ function collectTargetScreenIds(nodes) {
521
+ const ids = [];
522
+ for (const node of nodes) {
523
+ if (node.type === "link" && "targetScreenId" in node.attributes) ids.push(node.attributes.targetScreenId);
524
+ if ("children" in node) ids.push(...collectTargetScreenIds(node.children));
525
+ }
526
+ return ids;
527
+ }
528
+ const ScreenDocumentSchema = z.object({ screens: z.array(ScreenSchema).min(1) }).refine((doc) => {
529
+ const ids = doc.screens.map((s) => s.id);
530
+ return new Set(ids).size === ids.length;
531
+ }, { message: "Duplicate screen IDs" }).refine((doc) => {
532
+ const screenIds = new Set(doc.screens.map((s) => s.id));
533
+ return doc.screens.flatMap((s) => collectTargetScreenIds(s.children)).every((id) => screenIds.has(id));
534
+ }, { message: "targetScreenId references a non-existent screen" });
535
+ /**
536
+ * Parse offer screens content into a list of screens. Returns `null` when the
537
+ * content is missing or matches neither the screen document nor the legacy
538
+ * single-root shape, so callers can render a fallback.
539
+ */
540
+ function parseScreens(jsonContent) {
541
+ if (!jsonContent) return null;
542
+ const screenResult = ScreenDocumentSchema.safeParse(jsonContent);
543
+ if (screenResult.success) return screenResult.data.screens;
544
+ const legacyResult = ASTSchema.safeParse(jsonContent);
545
+ if (legacyResult.success) return [{
546
+ id: "default",
547
+ children: legacyResult.data.children
548
+ }];
549
+ return null;
550
+ }
551
+ //#endregion
552
+ export { DiscoApiError, DiscoError, DiscoNetworkError, DiscoValidationError, INTERNAL_BASE_URL, InternalDiscoClient, TrackingManager, denormalize, parseScreens };
480
553
 
481
554
  //# sourceMappingURL=internal.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"internal.js","names":["#endpoint","#headers","#sessionId","#fetch","#dedupe","#isDeduped","#toBody","#env","#url","#headers","#fetch"],"sources":["../src/lib/http.ts","../src/TrackingManager.ts","../src/internal/denormalize.ts","../src/internal/recommendationsMapper.ts","../src/lib/schemas.ts","../src/internal/recommendationsRequestMapper.ts","../src/internal/InternalDiscoClient.ts"],"sourcesContent":["/**\n * Best-effort read of a non-2xx response body: try JSON, fall back to text,\n * then give up with `undefined`. Used by both clients to populate\n * `DiscoApiError.body` without ever throwing from the error path.\n */\nexport async 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","import 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 * Absolute URL events are POSTed to. The external client points this at the\n * events service (`/events`); the internal client at the proxy\n * (`/track/partners_event/`). Prefer a client's `createTrackingManager` over\n * constructing this directly, so the endpoint and auth stay consistent with\n * the recommendations call.\n */\n endpoint: string;\n\n /**\n * Extra request headers — e.g. `{ \"x-api-key\": key }` for the external\n * events service. `Content-Type: application/json` is always sent.\n */\n headers?: Record<string, string>;\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\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 #headers: Record<string, string>;\n readonly #sessionId: string;\n readonly #fetch: typeof fetch;\n readonly #dedupe = new Set<string>();\n\n constructor(config: TrackingManagerConfig) {\n this.#endpoint = config.endpoint;\n this.#headers = config.headers ?? {};\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\", ...this.#headers },\n body: JSON.stringify(this.#toBody(event)),\n keepalive: true,\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 // RFC-3339 with an explicit offset. \"+00:00\" is accepted by both the\n // events service and the legacy proxy validator (the latter can't parse\n // the bare \"Z\" suffix).\n event_datetime: new Date().toISOString().replace(\"Z\", \"+00:00\"),\n placement_details: event.placement\n ? {\n display_mode: event.placement.displayMode,\n view: event.placement.view,\n layout_id: event.placement.layoutId,\n }\n : undefined,\n };\n\n switch (event.type) {\n case \"BRAND_CLICK\":\n return {\n ...commonEventFields,\n brand_properties: brandProperties(event.brand),\n initiating_target: event.target,\n asset_id: event.assetId,\n };\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 \"PRODUCT_DISPLAY\":\n case \"PRODUCT_VIEW\":\n case \"PRODUCT_CLICK\":\n return {\n ...commonEventFields,\n brand_properties: brandProperties(event.brand),\n product_properties: { product_id: event.product.productId },\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","/**\n * Join the external normalized recommendations response into ordered,\n * render-ready `RecommendationGroup[]`.\n *\n * The external `DiscoClient` returns the API's normalized maps (offer-id keyed\n * recommendations + group entries that reference them); this performs the join\n * into denormalized groups. It is the shared join used both by the internal\n * proxy mapper (`mapRecommendationsResponse`) and by `@disconetwork/react-native`\n * — hence its home on the first-party `@disconetwork/core/internal` surface\n * rather than the partner-facing package root.\n */\n\n// Input is the *external* normalized response (what `transformResponse` /\n// `DiscoClient.getRecommendations` produce). The result types are the internal\n// denormalized ones — reused so this isn't a third parallel set of group types.\nimport type { RecommendationsResponse } from \"../external/recommendations.js\";\nimport type { Recommendation, RecommendationGroup } from \"./recommendations.js\";\n\n/**\n * Join the normalized response maps into ordered `RecommendationGroup[]`.\n *\n * Groups are ordered by the numeric suffix of their key (`group_0` before\n * `group_10`); within each group, entries are ordered by `insertionOrder`.\n * Groups missing their entry list or display properties are skipped, as are\n * entries whose `offerId` is absent from the recommendations map. Each result\n * recommendation's `id` is the offer's id and its `insertionId` comes from the\n * group entry.\n */\nexport function denormalize(\n response: RecommendationsResponse,\n): RecommendationGroup[] {\n const recommendations = response.recommendations;\n const groupEntries = response.recommendationGroups;\n const groupProps = response.recommendationGroupProperties ?? {};\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 // for (const entry of [...entries].sort(\n // (a, b) => a.insertionOrder - b.insertionOrder,\n // )) {\n const rec = recommendations[entry.offerId];\n if (!rec) continue; // entry references an absent recommendation\n recs.push({\n id: rec.offer.id,\n insertionId: entry.insertionId,\n advertiser: rec.advertiser,\n offer: rec.offer,\n });\n }\n\n recommendationGroups.push({\n heading: props.heading ?? null,\n slotContext: props.slotContext,\n recommendations: recs,\n });\n }\n\n return recommendationGroups;\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","/**\n * Maps the proxy `/recommendations` response into the public, denormalized\n * `RecommendationsResponse` (`mapRecommendationsResponse`).\n *\n * The proxy response is the external `/recommendations` response **verbatim plus\n * a few extra top-level fields** (`layout_id`, `publisher_customization`, the\n * `widget_*` markers, …). So this reuses the external machinery — the generated\n * zod validator (`zRecommendationsResponse2`) and the external `transformResponse`\n * mapper — and only layers on the denormalization (the join into\n * `RecommendationGroup[]`) and the proxy extras.\n *\n * Validation is zod-backed: the external-wire part is validated by the generated\n * `zRecommendationsResponse2` and the proxy extras by a small local schema, so a\n * malformed server response surfaces as a `DiscoValidationError` rather than an\n * opaque `undefined`-access crash deep in the join.\n */\n\nimport { ZodError } from \"zod/v4\";\nimport { zRecommendationsResponse2 } from \"../api/generated/recommendations/zod.gen.js\";\nimport type { RecommendationsResponse as RecommendationsWireResponse } from \"../api/generated/recommendations/types.gen.js\";\nimport { transformResponse } from \"../external/recommendationsTransforms.js\";\nimport { denormalize } from \"./denormalize.js\";\nimport { DiscoValidationError } from \"../errors.js\";\nimport * as z from \"zod/v4\";\nimport type {\n RecommendationsResponse,\n PublisherCustomization,\n} from \"./recommendations.js\";\n\n// ─── Validation of the proxy extras ──────────────────────────────────────────\n//\n// The external-wire part is validated by the generated `zRecommendationsResponse2`\n// (which STRIPS unknown keys — so the proxy extras won't survive it). The few\n// extra top-level fields the proxy adds are validated separately by this small\n// schema, run against the same raw payload. zod/v4 — to match the generated\n// validator and so its `ZodError` is caught by the `zod/v4` import above.\nconst zProxyExtras = z.object({\n layout_id: z.string().optional(),\n publisher_customization: z\n .record(\n z.string(),\n z.record(z.string(), z.union([z.string(), z.boolean()])),\n )\n .nullish(),\n});\n\n// ─── Mapper ───────────────────────────────────────────────────────────────────\n\n/**\n * Validate the proxy recommendations response and denormalize it into the\n * public `RecommendationsResponse`.\n *\n * The proxy payload is the external wire response plus extras, so this reuses\n * the external machinery: validate the wire part with the generated\n * `zRecommendationsResponse2` and the extras with `zProxyExtras`, recase via\n * the external `transformResponse`, then denormalize the resulting maps into\n * `RecommendationGroup[]` (the internal value-add) and assemble the response\n * with the proxy extras layered on.\n *\n * Throws `DiscoValidationError` if the server payload doesn't match the\n * expected shape.\n *\n * @internal Built into `InternalDiscoClient.getRecommendations`; not part of\n * the public API. The wire shape is encapsulated by the client on purpose.\n */\nexport function mapRecommendationsResponse(\n raw: unknown,\n): RecommendationsResponse {\n let wire: RecommendationsWireResponse;\n let extras: z.infer<typeof zProxyExtras>;\n try {\n // The generated validator pins the external-wire shape; cast its (inferred)\n // output to the wire type `transformResponse` consumes — both describe the\n // same spec shape.\n wire = zRecommendationsResponse2.parse(raw) as RecommendationsWireResponse;\n extras = zProxyExtras.parse(raw);\n } catch (error) {\n if (error instanceof ZodError) {\n throw new DiscoValidationError(\n \"Failed to validate recommendations response\",\n error,\n raw,\n );\n }\n throw error;\n }\n\n // Reuse the external mapper for the leaf types + casing (free), then join the\n // normalized maps into the denormalized groups via the shared `denormalize`\n // helper (the same join the external surface exposes to consumers).\n const normalized = transformResponse(wire);\n const recommendationGroups = denormalize(normalized);\n\n return {\n sessionId: normalized.sessionId,\n layoutId: extras.layout_id ?? \"SHOPIFY_NATIVE_ESSENTIAL\",\n recommendationGroups,\n footer: normalized.footer,\n publisherCustomization:\n (extras.publisher_customization as PublisherCustomization | null) ?? null,\n };\n}\n","/**\n * Thin wrappers around Zod parsing that convert a thrown `ZodError` into a\n * `DiscoValidationError`, so validation failures surface as a Disco error type\n * rather than leaking Zod's internals to consumers. Modeled on the equivalent\n * helpers in Speakeasy-generated SDKs.\n */\n\nimport * as z from \"zod/v4\";\nimport { DiscoValidationError } from \"../errors.js\";\n\n/**\n * Run `fn` (typically a `schema.parse`) and, if it throws a `ZodError`, rethrow\n * it as a `DiscoValidationError`. Any non-Zod error propagates untouched.\n */\nexport function parse<Inp, Out>(\n rawValue: Inp,\n fn: (value: Inp) => Out,\n errorMessage: string,\n): Out {\n try {\n return fn(rawValue);\n } catch (err) {\n if (err instanceof z.ZodError) {\n throw new DiscoValidationError(errorMessage, err, rawValue);\n }\n throw err;\n }\n}\n","/**\n * Wire types for the recommendations *request* and `transformRequest`, which\n * builds the snake_case wire body from the public `RecommendationsRequest`.\n *\n * `InternalDiscoClient.getRecommendations` calls `transformRequest` to map the\n * camelCase request into the wire body before POSTing it.\n *\n * The mapping is Zod-backed: `RecommendationsRequest$outboundSchema` validates\n * the public request before the `.transform()` reshapes it into the wire body,\n * so a malformed request surfaces as a `DiscoValidationError` *before* it hits\n * the network. This mirrors how Speakeasy-generated SDKs use an\n * `$outboundSchema` per model.\n */\n\nimport * as z from \"zod/v4\";\nimport { parse } from \"../lib/schemas.js\";\nimport { remap } from \"../lib/primitives.js\";\nimport type {\n OrderDetails,\n PlacementDetails,\n Purchase,\n RecommendationsRequest,\n RunningExperiment,\n UserDetails,\n} from \"./recommendations.js\";\n\n// ─── Raw wire shape ──────────────────────────────────────────────────────────\n//\n// The endpoint nests most request fields under `recommendations_data`, with\n// monetary fields tucked into a `cost_details` sub-object, while experiments\n// and attributes sit at the top level. The public `RecommendationsRequest` is\n// a flatter façade over this; the outbound schema bridges the two.\n\ntype RawCostDetails = {\n amount?: number | string;\n currency_code?: string;\n};\n\ntype RawUserDetails = {\n email?: string;\n first_name?: string;\n last_name?: string;\n phone?: string;\n};\n\ntype RawPlacementDetails = {\n display_mode?: string;\n view?: string;\n};\n\ntype RawOrderDetails = {\n order_id?: string;\n cost_details?: RawCostDetails;\n};\n\ntype RawPurchase = {\n name?: string;\n type?: string;\n variant?: string;\n quantity?: number;\n product_id?: string;\n cost_details?: RawCostDetails;\n};\n\ntype RawRunningExperiment = {\n id: string;\n variant: string;\n};\n\ntype RawRecommendationsData = {\n user_details?: RawUserDetails;\n placement_details?: RawPlacementDetails;\n order_details?: RawOrderDetails;\n purchases?: RawPurchase[];\n};\n\ntype RawRecommendationsRequest = {\n recommendations_data?: RawRecommendationsData;\n running_experiments?: RawRunningExperiment[];\n attributes?: Record<string, unknown>;\n /**\n * Platform-specific top-level fields passed through untransformed\n * (e.g. `shopify_checkout_token`). The public type funnels these through\n * `extras`; on the raw body they're just additional keys.\n */\n [key: string]: unknown;\n};\n\n// ─── Outbound schemas ──────────────────────────────────────────────────────────\n//\n// Each schema validates a slice of the public (camelCase) request and\n// `.transform()`s it into the snake_case wire shape. Simple field renames go\n// through `remap`; the monetary fields fold into a `cost_details` sub-object\n// that's omitted entirely when no amount/currency is present. The\n// `z.ZodType<RawX, PublicX>` annotation pins input and output types\n// to the hand-written shapes so they can't drift.\n\nconst UserDetails$outboundSchema: z.ZodType<RawUserDetails, UserDetails> = z\n .object({\n email: z.string().optional(),\n firstName: z.string().optional(),\n lastName: z.string().optional(),\n phone: z.string().optional(),\n })\n .transform((v) =>\n remap(v, { firstName: \"first_name\", lastName: \"last_name\" }),\n );\n\nconst PlacementDetails$outboundSchema: z.ZodType<\n RawPlacementDetails,\n PlacementDetails\n> = z\n .object({\n displayMode: z.string().optional(),\n view: z.string().optional(),\n })\n .transform((v) => remap(v, { displayMode: \"display_mode\" }));\n\nconst OrderDetails$outboundSchema: z.ZodType<RawOrderDetails, OrderDetails> = z\n .object({\n id: z.string().optional(),\n amount: z.union([z.number(), z.string()]).optional(),\n currencyCode: z.string().optional(),\n })\n .transform((v) => ({\n order_id: v.id,\n cost_details:\n v.amount !== undefined || v.currencyCode !== undefined\n ? { amount: v.amount, currency_code: v.currencyCode }\n : undefined,\n }));\n\nconst Purchase$outboundSchema: z.ZodType<RawPurchase, Purchase> = z\n .object({\n name: z.string().optional(),\n type: z.string().optional(),\n variant: z.string().optional(),\n quantity: z.number().optional(),\n productId: z.string().optional(),\n amount: z.number().optional(),\n currencyCode: z.string().optional(),\n })\n .transform((v) => ({\n name: v.name,\n type: v.type,\n variant: v.variant,\n quantity: v.quantity,\n product_id: v.productId,\n cost_details:\n v.amount !== undefined || v.currencyCode !== undefined\n ? { amount: v.amount, currency_code: v.currencyCode }\n : undefined,\n }));\n\nconst RunningExperiment$outboundSchema: z.ZodType<\n RawRunningExperiment,\n RunningExperiment\n> = z.object({\n id: z.string(),\n variant: z.string(),\n});\n\n/**\n * Validates the public request and reshapes it into the raw wire body: nest\n * fields under `recommendations_data`, fold monetary fields into `cost_details`,\n * convert camelCase to snake_case, and spread `extras` at the top level\n * untransformed.\n */\nconst RecommendationsRequest$outboundSchema: z.ZodType<\n RawRecommendationsRequest,\n RecommendationsRequest\n> = z\n .object({\n user: UserDetails$outboundSchema.optional(),\n placement: PlacementDetails$outboundSchema.optional(),\n order: OrderDetails$outboundSchema.optional(),\n purchases: z.array(Purchase$outboundSchema).optional(),\n experiments: z.array(RunningExperiment$outboundSchema).optional(),\n attributes: z.record(z.string(), z.unknown()).optional(),\n extras: z.record(z.string(), z.unknown()).optional(),\n })\n .transform((v) => ({\n recommendations_data: {\n user_details: v.user,\n placement_details: v.placement,\n order_details: v.order,\n purchases: v.purchases,\n },\n running_experiments: v.experiments,\n attributes: v.attributes,\n ...v.extras,\n }));\n\n// ─── Mapper ───────────────────────────────────────────────────────────────────\n\n/**\n * Build the raw request body from the public `RecommendationsRequest`: nest\n * fields under `recommendations_data`, fold monetary fields into `cost_details`\n * (omitted entirely when no amount/currency is present), and convert camelCase\n * to snake_case. `extras` is spread at the top level untransformed.\n *\n * Validates the input first and throws `DiscoValidationError` if the request\n * doesn't match the expected shape.\n *\n * @internal Built into `DiscoClient.getRecommendations`; not part of the public\n * API. The wire shape is encapsulated by the client on purpose.\n */\nexport function transformRequest(\n req: RecommendationsRequest,\n): RawRecommendationsRequest {\n return parse(\n req,\n (value) => RecommendationsRequest$outboundSchema.parse(value),\n \"Failed to validate recommendations request\",\n );\n}\n","import { validatePublicApiKey } from \"../apiKey.js\";\nimport type { DiscoEnv } from \"../env.js\";\nimport { DiscoApiError, DiscoNetworkError, isAbortError } from \"../errors.js\";\nimport { safeReadBody } from \"../lib/http.js\";\nimport { TrackingManager } from \"../TrackingManager.js\";\nimport type { EventTracker } from \"../types.js\";\nimport type {\n RecommendationsRequest,\n RecommendationsResponse,\n} from \"./recommendations.js\";\nimport { mapRecommendationsResponse } from \"./recommendationsMapper.js\";\nimport { transformRequest } from \"./recommendationsRequestMapper.js\";\n\n/**\n * Per-environment base URL for the internal/proxy backend — the legacy server\n * that orchestrates and forwards to the downstream services. Both the\n * recommendations and tracking endpoints sit under this origin, routed by path\n * (the client appends `/core/recommendations/…` and `/track/partners_event/`).\n */\nexport const INTERNAL_BASE_URL = {\n production: \"https://consumer.disconetwork.com\",\n staging: \"https://consumer.disconetwork-staging.com\",\n} as const satisfies Record<DiscoEnv, string>;\n\n/**\n * Authenticate with a scoped public API key. Sent as the `x-api-key`\n * header against the unified `/core/recommendations/` endpoint. Both\n * `disco_pk_live_…` and `disco_pk_sandbox_…` keys use production; there is\n * 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 to select the backend for shop-based authentication.\n * `shopGid` may be a full `gid://shopify/Shop/<id>` or 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 mapped recommendations\n * response plus a tracker already bound to its session.\n */\nexport type RecommendationsWithTracker = {\n /**\n * The mapped, denormalized recommendations response — the same friendly\n * camelCase shape `getRecommendations` returns.\n */\n data: RecommendationsResponse;\n /** Event tracker bound to this response's session. */\n tracker: EventTracker;\n};\n\n/**\n * Internal client for the legacy **proxy** recommendations endpoint\n * (`/core/recommendations/` on the backend), which orchestrates placement,\n * experiments, layout, and `publisher_customization` server-side and supports\n * `shopGid` auth for first-party surfaces (e.g. the Shopify checkout\n * extension).\n *\n * First-party / legacy only — exported from `@disconetwork/core/internal`.\n * External partners use the `DiscoClient` from the package root, which talks\n * directly to `disco-recommendations-api`.\n *\n * Renderer-agnostic: this class makes plain HTTP calls and has no React\n * dependency.\n */\nexport class InternalDiscoClient {\n readonly #env: DiscoEnv;\n readonly #url: string;\n readonly #headers: Record<string, string>;\n readonly #fetch: typeof fetch;\n\n get env(): DiscoEnv {\n return this.#env;\n }\n\n constructor(config: DiscoClientConfig) {\n this.#fetch = config.fetch ?? globalThis.fetch.bind(globalThis);\n\n if (\"apiKey\" in config) {\n validatePublicApiKey(config.apiKey);\n this.#env = \"production\";\n this.#url = `${INTERNAL_BASE_URL[this.#env]}/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 = `${INTERNAL_BASE_URL[this.#env]}/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 * Fetch recommendations for the given request.\n *\n * Validates and transforms the friendly camelCase `request` into the wire\n * body, POSTs it, then validates and denormalizes the response into the\n * friendly `RecommendationsResponse`. The snake_case wire format is fully\n * encapsulated — callers never see it.\n *\n * Throws `DiscoValidationError` if the request or response fails schema\n * validation, `DiscoApiError` on non-2xx responses, and `DiscoNetworkError`\n * if the request can't reach the server (an abort rejects with the native\n * `AbortError`). Parse failures propagate as-is.\n */\n getRecommendations = async (\n request: RecommendationsRequest,\n options?: GetRecommendationsOptions,\n ): Promise<RecommendationsResponse> => {\n // `transformRequest` validates the request and builds the wire body; its\n // `DiscoValidationError` must propagate, so it runs *before* the fetch try\n // (otherwise the catch below would mis-wrap it as a `DiscoNetworkError`).\n const body = JSON.stringify(transformRequest(request));\n let response: Response;\n try {\n response = await this.#fetch(this.#url, {\n method: \"POST\",\n headers: this.#headers,\n body,\n signal: options?.signal,\n });\n } catch (error) {\n // A cancellation propagates as-is; any other transport failure is wrapped.\n if (isAbortError(error)) throw error;\n throw new DiscoNetworkError(\n \"Recommendations request failed to reach the server\",\n error,\n );\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 mapRecommendationsResponse(await response.json());\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 the session id through themselves (and can't bind a tracker to the\n * wrong session). The returned `data` is the mapped `RecommendationsResponse`.\n *\n * Throws `DiscoValidationError` / `DiscoApiError` the same as\n * `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(data.sessionId, {\n fetch: options?.fetch,\n });\n return { data, tracker };\n };\n\n /**\n * Create an event tracker bound to a recommendations session (the `sessionId`\n * from a `getRecommendations` response).\n *\n * The tracker uses the same environment as the recommendations call.\n * Both live and sandbox public keys use production.\n */\n createTrackingManager = (\n sessionId: string,\n options?: CreateTrackingManagerOptions,\n ): EventTracker =>\n new TrackingManager({\n sessionId,\n endpoint: `${INTERNAL_BASE_URL[this.#env]}/track/partners_event/`,\n fetch: options?.fetch ?? this.#fetch,\n });\n}\n\nfunction stripShopGid(shopGid: string): string {\n return shopGid.replace(\"gid://shopify/Shop/\", \"\");\n}\n"],"mappings":";;;;;;;;;;AAKA,eAAsB,aAAa,UAAsC;CACvE,IAAI;EACF,OAAO,MAAM,SAAS,MAAM,EAAE,KAAK;CACrC,QAAQ;EACN,IAAI;GACF,OAAO,MAAM,SAAS,KAAK;EAC7B,QAAQ;GACN;EACF;CACF;AACF;;;;;;;;;;;;;;;;;;;ACmCA,IAAa,kBAAb,MAA6B;CAC3B;CACA;CACA;CACA;CACA,0BAAmB,IAAI,IAAY;CAEnC,YAAY,QAA+B;EACzC,KAAKA,YAAY,OAAO;EACxB,KAAKC,WAAW,OAAO,WAAW,CAAC;EACnC,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,KAAKH,WAAW;GAC1B,QAAQ;GACR,SAAS;IAAE,gBAAgB;IAAoB,GAAG,KAAKC;GAAS;GAChE,MAAM,KAAK,UAAU,KAAKK,QAAQ,KAAK,CAAC;GACxC,WAAW;EACb,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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;;;;;;;;;;;CAaA,gCAAgC,OAC9B,SACA,YACwC;EACxC,MAAM,OAAO,MAAM,KAAK,mBAAmB,SAAS,EAClD,QAAQ,SAAS,OACnB,CAAC;EAID,OAAO;GAAE;GAAM,SAHC,KAAK,sBAAsB,KAAK,WAAW,EACzD,OAAO,SAAS,MAClB,CACqB;EAAE;CACzB;;;;;;;;CASA,yBACE,WACA,YAEA,IAAI,gBAAgB;EAClB;EACA,UAAU,GAAG,kBAAkB,KAAKF,MAAM;EAC1C,OAAO,SAAS,SAAS,KAAKG;CAChC,CAAC;AACL;AAEA,SAAS,aAAa,SAAyB;CAC7C,OAAO,QAAQ,QAAQ,uBAAuB,EAAE;AAClD"}
1
+ {"version":3,"file":"internal.js","names":["#endpoint","#headers","#sessionId","#fetch","#dedupe","#isDeduped","#toBody","#env","#url","#headers","#fetch"],"sources":["../src/lib/http.ts","../src/TrackingManager.ts","../src/internal/denormalize.ts","../src/internal/recommendationsMapper.ts","../src/lib/schemas.ts","../src/internal/recommendationsRequestMapper.ts","../src/internal/InternalDiscoClient.ts","../src/internal/screens.ts"],"sourcesContent":["/**\n * Best-effort read of a non-2xx response body: try JSON, fall back to text,\n * then give up with `undefined`. Used by both clients to populate\n * `DiscoApiError.body` without ever throwing from the error path.\n */\nexport async 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","import 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 * Absolute URL events are POSTed to. The external client points this at the\n * events service (`/events`); the internal client at the proxy\n * (`/track/partners_event/`). Prefer a client's `createTrackingManager` over\n * constructing this directly, so the endpoint and auth stay consistent with\n * the recommendations call.\n */\n endpoint: string;\n\n /**\n * Extra request headers — e.g. `{ \"x-api-key\": key }` for the external\n * events service. `Content-Type: application/json` is always sent.\n */\n headers?: Record<string, string>;\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\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 #headers: Record<string, string>;\n readonly #sessionId: string;\n readonly #fetch: typeof fetch;\n readonly #dedupe = new Set<string>();\n\n constructor(config: TrackingManagerConfig) {\n this.#endpoint = config.endpoint;\n this.#headers = config.headers ?? {};\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\", ...this.#headers },\n body: JSON.stringify(this.#toBody(event)),\n keepalive: true,\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 // RFC-3339 with an explicit offset. \"+00:00\" is accepted by both the\n // events service and the legacy proxy validator (the latter can't parse\n // the bare \"Z\" suffix).\n event_datetime: new Date().toISOString().replace(\"Z\", \"+00:00\"),\n placement_details: event.placement\n ? {\n display_mode: event.placement.displayMode,\n view: event.placement.view,\n layout_id: event.placement.layoutId,\n }\n : undefined,\n };\n\n switch (event.type) {\n case \"BRAND_CLICK\":\n return {\n ...commonEventFields,\n brand_properties: brandProperties(event.brand),\n initiating_target: event.target,\n asset_id: event.assetId,\n };\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 \"PRODUCT_DISPLAY\":\n case \"PRODUCT_VIEW\":\n case \"PRODUCT_CLICK\":\n return {\n ...commonEventFields,\n brand_properties: brandProperties(event.brand),\n product_properties: { product_id: event.product.productId },\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","/**\n * Join the external normalized recommendations response into ordered,\n * render-ready `RecommendationGroup[]`.\n *\n * The external `DiscoClient` returns the API's normalized maps (offer-id keyed\n * recommendations + group entries that reference them); this performs the join\n * into denormalized groups. It is the shared join used both by the internal\n * proxy mapper (`mapRecommendationsResponse`) and by `@disconetwork/react-native`\n * — hence its home on the first-party `@disconetwork/core/internal` surface\n * rather than the partner-facing package root.\n */\n\n// Input is the *external* normalized response (what `transformResponse` /\n// `DiscoClient.getRecommendations` produce). The result types are the internal\n// denormalized ones — reused so this isn't a third parallel set of group types.\nimport type { RecommendationsResponse } from \"../external/recommendations.js\";\nimport type { Recommendation, RecommendationGroup } from \"./recommendations.js\";\n\n/**\n * Join the normalized response maps into ordered `RecommendationGroup[]`.\n *\n * Groups are ordered by the numeric suffix of their key (`group_0` before\n * `group_10`); within each group, entries are ordered by `insertionOrder`.\n * Groups missing their entry list or display properties are skipped, as are\n * entries whose `offerId` is absent from the recommendations map. Each result\n * recommendation's `id` is the offer's id and its `insertionId` comes from the\n * group entry.\n */\nexport function denormalize(\n response: RecommendationsResponse,\n): RecommendationGroup[] {\n const recommendations = response.recommendations;\n const groupEntries = response.recommendationGroups;\n const groupProps = response.recommendationGroupProperties ?? {};\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 // for (const entry of [...entries].sort(\n // (a, b) => a.insertionOrder - b.insertionOrder,\n // )) {\n const rec = recommendations[entry.offerId];\n if (!rec) continue; // entry references an absent recommendation\n recs.push({\n id: rec.offer.id,\n insertionId: entry.insertionId,\n advertiser: rec.advertiser,\n offer: rec.offer,\n });\n }\n\n recommendationGroups.push({\n heading: props.heading ?? null,\n slotContext: props.slotContext,\n recommendations: recs,\n });\n }\n\n return recommendationGroups;\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","/**\n * Maps the proxy `/recommendations` response into the public, denormalized\n * `RecommendationsResponse` (`mapRecommendationsResponse`).\n *\n * The proxy response is the external `/recommendations` response **verbatim plus\n * a few extra top-level fields** (`layout_id`, `publisher_customization`, the\n * `widget_*` markers, …). So this reuses the external machinery — the generated\n * zod validator (`zRecommendationsResponse2`) and the external `transformResponse`\n * mapper — and only layers on the denormalization (the join into\n * `RecommendationGroup[]`) and the proxy extras.\n *\n * Validation is zod-backed: the external-wire part is validated by the generated\n * `zRecommendationsResponse2` and the proxy extras by a small local schema, so a\n * malformed server response surfaces as a `DiscoValidationError` rather than an\n * opaque `undefined`-access crash deep in the join.\n */\n\nimport { ZodError } from \"zod/v4\";\nimport { zRecommendationsResponse2 } from \"../api/generated/recommendations/zod.gen.js\";\nimport type { RecommendationsResponse as RecommendationsWireResponse } from \"../api/generated/recommendations/types.gen.js\";\nimport { transformResponse } from \"../external/recommendationsTransforms.js\";\nimport { denormalize } from \"./denormalize.js\";\nimport { DiscoValidationError } from \"../errors.js\";\nimport * as z from \"zod/v4\";\nimport type {\n RecommendationsResponse,\n PublisherCustomization,\n} from \"./recommendations.js\";\n\n// ─── Validation of the proxy extras ──────────────────────────────────────────\n//\n// The external-wire part is validated by the generated `zRecommendationsResponse2`\n// (which STRIPS unknown keys — so the proxy extras won't survive it). The few\n// extra top-level fields the proxy adds are validated separately by this small\n// schema, run against the same raw payload. zod/v4 — to match the generated\n// validator and so its `ZodError` is caught by the `zod/v4` import above.\nconst zProxyExtras = z.object({\n layout_id: z.string().optional(),\n publisher_customization: z\n .record(\n z.string(),\n z.record(z.string(), z.union([z.string(), z.boolean()])),\n )\n .nullish(),\n});\n\n// ─── Mapper ───────────────────────────────────────────────────────────────────\n\n/**\n * Validate the proxy recommendations response and denormalize it into the\n * public `RecommendationsResponse`.\n *\n * The proxy payload is the external wire response plus extras, so this reuses\n * the external machinery: validate the wire part with the generated\n * `zRecommendationsResponse2` and the extras with `zProxyExtras`, recase via\n * the external `transformResponse`, then denormalize the resulting maps into\n * `RecommendationGroup[]` (the internal value-add) and assemble the response\n * with the proxy extras layered on.\n *\n * Throws `DiscoValidationError` if the server payload doesn't match the\n * expected shape.\n *\n * @internal Built into `InternalDiscoClient.getRecommendations`; not part of\n * the public API. The wire shape is encapsulated by the client on purpose.\n */\nexport function mapRecommendationsResponse(\n raw: unknown,\n): RecommendationsResponse {\n let wire: RecommendationsWireResponse;\n let extras: z.infer<typeof zProxyExtras>;\n try {\n // The generated validator pins the external-wire shape; cast its (inferred)\n // output to the wire type `transformResponse` consumes — both describe the\n // same spec shape.\n wire = zRecommendationsResponse2.parse(raw) as RecommendationsWireResponse;\n extras = zProxyExtras.parse(raw);\n } catch (error) {\n if (error instanceof ZodError) {\n throw new DiscoValidationError(\n \"Failed to validate recommendations response\",\n error,\n raw,\n );\n }\n throw error;\n }\n\n // Reuse the external mapper for the leaf types + casing (free), then join the\n // normalized maps into the denormalized groups via the shared `denormalize`\n // helper (the same join the external surface exposes to consumers).\n const normalized = transformResponse(wire);\n const recommendationGroups = denormalize(normalized);\n\n return {\n sessionId: normalized.sessionId,\n layoutId: extras.layout_id ?? \"SHOPIFY_NATIVE_ESSENTIAL\",\n recommendationGroups,\n footer: normalized.footer,\n publisherCustomization:\n (extras.publisher_customization as PublisherCustomization | null) ?? null,\n };\n}\n","/**\n * Thin wrappers around Zod parsing that convert a thrown `ZodError` into a\n * `DiscoValidationError`, so validation failures surface as a Disco error type\n * rather than leaking Zod's internals to consumers. Modeled on the equivalent\n * helpers in Speakeasy-generated SDKs.\n */\n\nimport * as z from \"zod/v4\";\nimport { DiscoValidationError } from \"../errors.js\";\n\n/**\n * Run `fn` (typically a `schema.parse`) and, if it throws a `ZodError`, rethrow\n * it as a `DiscoValidationError`. Any non-Zod error propagates untouched.\n */\nexport function parse<Inp, Out>(\n rawValue: Inp,\n fn: (value: Inp) => Out,\n errorMessage: string,\n): Out {\n try {\n return fn(rawValue);\n } catch (err) {\n if (err instanceof z.ZodError) {\n throw new DiscoValidationError(errorMessage, err, rawValue);\n }\n throw err;\n }\n}\n","/**\n * Wire types for the recommendations *request* and `transformRequest`, which\n * builds the snake_case wire body from the public `RecommendationsRequest`.\n *\n * `InternalDiscoClient.getRecommendations` calls `transformRequest` to map the\n * camelCase request into the wire body before POSTing it.\n *\n * The mapping is Zod-backed: `RecommendationsRequest$outboundSchema` validates\n * the public request before the `.transform()` reshapes it into the wire body,\n * so a malformed request surfaces as a `DiscoValidationError` *before* it hits\n * the network. This mirrors how Speakeasy-generated SDKs use an\n * `$outboundSchema` per model.\n */\n\nimport * as z from \"zod/v4\";\nimport { parse } from \"../lib/schemas.js\";\nimport { remap } from \"../lib/primitives.js\";\nimport type {\n OrderDetails,\n PlacementDetails,\n Purchase,\n RecommendationsRequest,\n RunningExperiment,\n UserDetails,\n} from \"./recommendations.js\";\n\n// ─── Raw wire shape ──────────────────────────────────────────────────────────\n//\n// The endpoint nests most request fields under `recommendations_data`, with\n// monetary fields tucked into a `cost_details` sub-object, while experiments\n// and attributes sit at the top level. The public `RecommendationsRequest` is\n// a flatter façade over this; the outbound schema bridges the two.\n\ntype RawCostDetails = {\n amount?: number | string;\n currency_code?: string;\n};\n\ntype RawUserDetails = {\n email?: string;\n first_name?: string;\n last_name?: string;\n phone?: string;\n};\n\ntype RawPlacementDetails = {\n display_mode?: string;\n view?: string;\n};\n\ntype RawOrderDetails = {\n order_id?: string;\n cost_details?: RawCostDetails;\n};\n\ntype RawPurchase = {\n name?: string;\n type?: string;\n variant?: string;\n quantity?: number;\n product_id?: string;\n cost_details?: RawCostDetails;\n};\n\ntype RawRunningExperiment = {\n id: string;\n variant: string;\n};\n\ntype RawRecommendationsData = {\n user_details?: RawUserDetails;\n placement_details?: RawPlacementDetails;\n order_details?: RawOrderDetails;\n purchases?: RawPurchase[];\n};\n\ntype RawRecommendationsRequest = {\n recommendations_data?: RawRecommendationsData;\n running_experiments?: RawRunningExperiment[];\n attributes?: Record<string, unknown>;\n /**\n * Platform-specific top-level fields passed through untransformed\n * (e.g. `shopify_checkout_token`). The public type funnels these through\n * `extras`; on the raw body they're just additional keys.\n */\n [key: string]: unknown;\n};\n\n// ─── Outbound schemas ──────────────────────────────────────────────────────────\n//\n// Each schema validates a slice of the public (camelCase) request and\n// `.transform()`s it into the snake_case wire shape. Simple field renames go\n// through `remap`; the monetary fields fold into a `cost_details` sub-object\n// that's omitted entirely when no amount/currency is present. The\n// `z.ZodType<RawX, PublicX>` annotation pins input and output types\n// to the hand-written shapes so they can't drift.\n\nconst UserDetails$outboundSchema: z.ZodType<RawUserDetails, UserDetails> = z\n .object({\n email: z.string().optional(),\n firstName: z.string().optional(),\n lastName: z.string().optional(),\n phone: z.string().optional(),\n })\n .transform((v) =>\n remap(v, { firstName: \"first_name\", lastName: \"last_name\" }),\n );\n\nconst PlacementDetails$outboundSchema: z.ZodType<\n RawPlacementDetails,\n PlacementDetails\n> = z\n .object({\n displayMode: z.string().optional(),\n view: z.string().optional(),\n })\n .transform((v) => remap(v, { displayMode: \"display_mode\" }));\n\nconst OrderDetails$outboundSchema: z.ZodType<RawOrderDetails, OrderDetails> = z\n .object({\n id: z.string().optional(),\n amount: z.union([z.number(), z.string()]).optional(),\n currencyCode: z.string().optional(),\n })\n .transform((v) => ({\n order_id: v.id,\n cost_details:\n v.amount !== undefined || v.currencyCode !== undefined\n ? { amount: v.amount, currency_code: v.currencyCode }\n : undefined,\n }));\n\nconst Purchase$outboundSchema: z.ZodType<RawPurchase, Purchase> = z\n .object({\n name: z.string().optional(),\n type: z.string().optional(),\n variant: z.string().optional(),\n quantity: z.number().optional(),\n productId: z.string().optional(),\n amount: z.number().optional(),\n currencyCode: z.string().optional(),\n })\n .transform((v) => ({\n name: v.name,\n type: v.type,\n variant: v.variant,\n quantity: v.quantity,\n product_id: v.productId,\n cost_details:\n v.amount !== undefined || v.currencyCode !== undefined\n ? { amount: v.amount, currency_code: v.currencyCode }\n : undefined,\n }));\n\nconst RunningExperiment$outboundSchema: z.ZodType<\n RawRunningExperiment,\n RunningExperiment\n> = z.object({\n id: z.string(),\n variant: z.string(),\n});\n\n/**\n * Validates the public request and reshapes it into the raw wire body: nest\n * fields under `recommendations_data`, fold monetary fields into `cost_details`,\n * convert camelCase to snake_case, and spread `extras` at the top level\n * untransformed.\n */\nconst RecommendationsRequest$outboundSchema: z.ZodType<\n RawRecommendationsRequest,\n RecommendationsRequest\n> = z\n .object({\n user: UserDetails$outboundSchema.optional(),\n placement: PlacementDetails$outboundSchema.optional(),\n order: OrderDetails$outboundSchema.optional(),\n purchases: z.array(Purchase$outboundSchema).optional(),\n experiments: z.array(RunningExperiment$outboundSchema).optional(),\n attributes: z.record(z.string(), z.unknown()).optional(),\n extras: z.record(z.string(), z.unknown()).optional(),\n })\n .transform((v) => ({\n recommendations_data: {\n user_details: v.user,\n placement_details: v.placement,\n order_details: v.order,\n purchases: v.purchases,\n },\n running_experiments: v.experiments,\n attributes: v.attributes,\n ...v.extras,\n }));\n\n// ─── Mapper ───────────────────────────────────────────────────────────────────\n\n/**\n * Build the raw request body from the public `RecommendationsRequest`: nest\n * fields under `recommendations_data`, fold monetary fields into `cost_details`\n * (omitted entirely when no amount/currency is present), and convert camelCase\n * to snake_case. `extras` is spread at the top level untransformed.\n *\n * Validates the input first and throws `DiscoValidationError` if the request\n * doesn't match the expected shape.\n *\n * @internal Built into `DiscoClient.getRecommendations`; not part of the public\n * API. The wire shape is encapsulated by the client on purpose.\n */\nexport function transformRequest(\n req: RecommendationsRequest,\n): RawRecommendationsRequest {\n return parse(\n req,\n (value) => RecommendationsRequest$outboundSchema.parse(value),\n \"Failed to validate recommendations request\",\n );\n}\n","import { validatePublicApiKey } from \"../apiKey.js\";\nimport type { DiscoEnv } from \"../env.js\";\nimport { DiscoApiError, DiscoNetworkError, isAbortError } from \"../errors.js\";\nimport { safeReadBody } from \"../lib/http.js\";\nimport { TrackingManager } from \"../TrackingManager.js\";\nimport type { EventTracker } from \"../types.js\";\nimport type {\n RecommendationsRequest,\n RecommendationsResponse,\n} from \"./recommendations.js\";\nimport { mapRecommendationsResponse } from \"./recommendationsMapper.js\";\nimport { transformRequest } from \"./recommendationsRequestMapper.js\";\n\n/**\n * Per-environment base URL for the internal/proxy backend — the legacy server\n * that orchestrates and forwards to the downstream services. Both the\n * recommendations and tracking endpoints sit under this origin, routed by path\n * (the client appends `/core/recommendations/…` and `/track/partners_event/`).\n */\nexport const INTERNAL_BASE_URL = {\n production: \"https://consumer.disconetwork.com\",\n staging: \"https://consumer.disconetwork-staging.com\",\n} as const satisfies Record<DiscoEnv, string>;\n\n/**\n * Authenticate with a scoped public API key. Sent as the `x-api-key`\n * header against the unified `/core/recommendations/` endpoint. Both\n * `disco_pk_live_…` and `disco_pk_sandbox_…` keys use production; there is\n * 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 to select the backend for shop-based authentication.\n * `shopGid` may be a full `gid://shopify/Shop/<id>` or 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 mapped recommendations\n * response plus a tracker already bound to its session.\n */\nexport type RecommendationsWithTracker = {\n /**\n * The mapped, denormalized recommendations response — the same friendly\n * camelCase shape `getRecommendations` returns.\n */\n data: RecommendationsResponse;\n /** Event tracker bound to this response's session. */\n tracker: EventTracker;\n};\n\n/**\n * Internal client for the legacy **proxy** recommendations endpoint\n * (`/core/recommendations/` on the backend), which orchestrates placement,\n * experiments, layout, and `publisher_customization` server-side and supports\n * `shopGid` auth for first-party surfaces (e.g. the Shopify checkout\n * extension).\n *\n * First-party / legacy only — exported from `@disconetwork/core/internal`.\n * External partners use the `DiscoClient` from the package root, which talks\n * directly to `disco-recommendations-api`.\n *\n * Renderer-agnostic: this class makes plain HTTP calls and has no React\n * dependency.\n */\nexport class InternalDiscoClient {\n readonly #env: DiscoEnv;\n readonly #url: string;\n readonly #headers: Record<string, string>;\n readonly #fetch: typeof fetch;\n\n get env(): DiscoEnv {\n return this.#env;\n }\n\n constructor(config: DiscoClientConfig) {\n this.#fetch = config.fetch ?? globalThis.fetch.bind(globalThis);\n\n if (\"apiKey\" in config) {\n validatePublicApiKey(config.apiKey);\n this.#env = \"production\";\n this.#url = `${INTERNAL_BASE_URL[this.#env]}/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 = `${INTERNAL_BASE_URL[this.#env]}/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 * Fetch recommendations for the given request.\n *\n * Validates and transforms the friendly camelCase `request` into the wire\n * body, POSTs it, then validates and denormalizes the response into the\n * friendly `RecommendationsResponse`. The snake_case wire format is fully\n * encapsulated — callers never see it.\n *\n * Throws `DiscoValidationError` if the request or response fails schema\n * validation, `DiscoApiError` on non-2xx responses, and `DiscoNetworkError`\n * if the request can't reach the server (an abort rejects with the native\n * `AbortError`). Parse failures propagate as-is.\n */\n getRecommendations = async (\n request: RecommendationsRequest,\n options?: GetRecommendationsOptions,\n ): Promise<RecommendationsResponse> => {\n // `transformRequest` validates the request and builds the wire body; its\n // `DiscoValidationError` must propagate, so it runs *before* the fetch try\n // (otherwise the catch below would mis-wrap it as a `DiscoNetworkError`).\n const body = JSON.stringify(transformRequest(request));\n let response: Response;\n try {\n response = await this.#fetch(this.#url, {\n method: \"POST\",\n headers: this.#headers,\n body,\n signal: options?.signal,\n });\n } catch (error) {\n // A cancellation propagates as-is; any other transport failure is wrapped.\n if (isAbortError(error)) throw error;\n throw new DiscoNetworkError(\n \"Recommendations request failed to reach the server\",\n error,\n );\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 mapRecommendationsResponse(await response.json());\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 the session id through themselves (and can't bind a tracker to the\n * wrong session). The returned `data` is the mapped `RecommendationsResponse`.\n *\n * Throws `DiscoValidationError` / `DiscoApiError` the same as\n * `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(data.sessionId, {\n fetch: options?.fetch,\n });\n return { data, tracker };\n };\n\n /**\n * Create an event tracker bound to a recommendations session (the `sessionId`\n * from a `getRecommendations` response).\n *\n * The tracker uses the same environment as the recommendations call.\n * Both live and sandbox public keys use production.\n */\n createTrackingManager = (\n sessionId: string,\n options?: CreateTrackingManagerOptions,\n ): EventTracker =>\n new TrackingManager({\n sessionId,\n endpoint: `${INTERNAL_BASE_URL[this.#env]}/track/partners_event/`,\n fetch: options?.fetch ?? this.#fetch,\n });\n}\n\nfunction stripShopGid(shopGid: string): string {\n return shopGid.replace(\"gid://shopify/Shop/\", \"\");\n}\n","// Offer screens content — the JSON document an offer's rich content\n// (`incentive_json`) is authored in. A document is a list of screens, each a\n// tree of AST nodes; links can point to another screen by id. The legacy\n// single-root shape (`{ children }`) is still accepted and becomes one\n// `\"default\"` screen.\n//\n// Framework-agnostic: renderers live in `@disconetwork/react/internal`.\n\nimport * as z from \"zod/v4\";\n\nexport const TextNodeSchema = z.object({\n type: z.literal(\"text\"),\n text: z.string(),\n});\n\nconst ExternalLinkAttributesSchema = z.object({\n to: z.url(),\n external: z.boolean().optional().default(true),\n});\n\nconst InternalLinkAttributesSchema = z.object({\n targetScreenId: z.string(),\n});\n\nconst LinkAttributesSchema = z.union([\n ExternalLinkAttributesSchema,\n InternalLinkAttributesSchema,\n]);\n\ntype ASTChildrenSchema = z.ZodArray<\n z.ZodDiscriminatedUnion<\n [\n typeof TextNodeSchema,\n typeof LinkNodeSchema,\n typeof ParagraphNodeSchema,\n typeof ScrollViewNodeSchema,\n ]\n >\n>;\n\nexport const LinkNodeSchema = z.object({\n type: z.literal(\"link\"),\n attributes: LinkAttributesSchema,\n get children(): ASTChildrenSchema {\n return z.array(ASTNodeSchema).min(1);\n },\n});\n\nexport const ParagraphNodeSchema = z.object({\n type: z.literal(\"paragraph\"),\n get children(): ASTChildrenSchema {\n return z.array(ASTNodeSchema).min(1);\n },\n});\n\nexport const ScrollViewNodeSchema = z.object({\n type: z.literal(\"scrollview\"),\n attributes: z\n .object({\n maxBlockSize: z.number().optional(),\n })\n .optional(),\n get children(): ASTChildrenSchema {\n return z.array(ASTNodeSchema).min(1);\n },\n});\n\nexport const ASTNodeSchema = z.discriminatedUnion(\"type\", [\n TextNodeSchema,\n LinkNodeSchema,\n ParagraphNodeSchema,\n ScrollViewNodeSchema,\n]);\n\n// Root AST schema (legacy single-screen shape).\nexport const ASTSchema = z.object({\n get children() {\n return z.array(ASTNodeSchema).min(1);\n },\n});\n\nexport const ScreenSchema = ASTSchema.extend({\n id: z.string(),\n});\n\nfunction collectTargetScreenIds(\n nodes: z.infer<typeof ASTNodeSchema>[],\n): string[] {\n const ids: string[] = [];\n for (const node of nodes) {\n if (node.type === \"link\" && \"targetScreenId\" in node.attributes) {\n ids.push(node.attributes.targetScreenId);\n }\n if (\"children\" in node) {\n ids.push(...collectTargetScreenIds(node.children));\n }\n }\n return ids;\n}\n\nexport const ScreenDocumentSchema = z\n .object({\n screens: z.array(ScreenSchema).min(1),\n })\n .refine(\n (doc) => {\n const ids = doc.screens.map((s) => s.id);\n return new Set(ids).size === ids.length;\n },\n { message: \"Duplicate screen IDs\" },\n )\n .refine(\n (doc) => {\n const screenIds = new Set(doc.screens.map((s) => s.id));\n const targets = doc.screens.flatMap((s) =>\n collectTargetScreenIds(s.children),\n );\n return targets.every((id) => screenIds.has(id));\n },\n { message: \"targetScreenId references a non-existent screen\" },\n );\n\nexport type TextNode = z.infer<typeof TextNodeSchema>;\nexport type LinkNode = z.infer<typeof LinkNodeSchema>;\nexport type ParagraphNode = z.infer<typeof ParagraphNodeSchema>;\nexport type ScrollViewNode = z.infer<typeof ScrollViewNodeSchema>;\nexport type ASTNode = z.infer<typeof ASTNodeSchema>;\nexport type AST = z.infer<typeof ASTSchema>;\nexport type Screen = z.infer<typeof ScreenSchema>;\nexport type ScreenDocument = z.infer<typeof ScreenDocumentSchema>;\n\n/**\n * Parse offer screens content into a list of screens. Returns `null` when the\n * content is missing or matches neither the screen document nor the legacy\n * single-root shape, so callers can render a fallback.\n */\nexport function parseScreens(\n jsonContent: Record<string, unknown> | undefined | null,\n): Screen[] | null {\n if (!jsonContent) return null;\n\n const screenResult = ScreenDocumentSchema.safeParse(jsonContent);\n if (screenResult.success) {\n return screenResult.data.screens;\n }\n\n const legacyResult = ASTSchema.safeParse(jsonContent);\n if (legacyResult.success) {\n return [{ id: \"default\", children: legacyResult.data.children }];\n }\n\n return null;\n}\n"],"mappings":";;;;;;;;;;AAKA,eAAsB,aAAa,UAAsC;CACvE,IAAI;EACF,OAAO,MAAM,SAAS,MAAM,EAAE,KAAK;CACrC,QAAQ;EACN,IAAI;GACF,OAAO,MAAM,SAAS,KAAK;EAC7B,QAAQ;GACN;EACF;CACF;AACF;;;;;;;;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CAAC;CAErD;CACA,OAAO;AACT;AAEA,MAAa,uBAAuB,EACjC,OAAO,EACN,SAAS,EAAE,MAAM,YAAY,EAAE,IAAI,CAAC,EACtC,CAAC,EACA,QACE,QAAQ;CACP,MAAM,MAAM,IAAI,QAAQ,KAAK,MAAM,EAAE,EAAE;CACvC,OAAO,IAAI,IAAI,GAAG,EAAE,SAAS,IAAI;AACnC,GACA,EAAE,SAAS,uBAAuB,CACpC,EACC,QACE,QAAQ;CACP,MAAM,YAAY,IAAI,IAAI,IAAI,QAAQ,KAAK,MAAM,EAAE,EAAE,CAAC;CAItD,OAHgB,IAAI,QAAQ,SAAS,MACnC,uBAAuB,EAAE,QAAQ,CAEtB,EAAE,OAAO,OAAO,UAAU,IAAI,EAAE,CAAC;AAChD,GACA,EAAE,SAAS,kDAAkD,CAC/D;;;;;;AAgBF,SAAgB,aACd,aACiB;CACjB,IAAI,CAAC,aAAa,OAAO;CAEzB,MAAM,eAAe,qBAAqB,UAAU,WAAW;CAC/D,IAAI,aAAa,SACf,OAAO,aAAa,KAAK;CAG3B,MAAM,eAAe,UAAU,UAAU,WAAW;CACpD,IAAI,aAAa,SACf,OAAO,CAAC;EAAE,IAAI;EAAW,UAAU,aAAa,KAAK;CAAS,CAAC;CAGjE,OAAO;AACT"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@disconetwork/core",
3
- "version": "0.0.13",
3
+ "version": "0.0.14",
4
4
  "description": "Core package for disco-js.",
5
5
  "license": "MIT",
6
6
  "repository": {