@disconetwork/core 0.0.17 → 0.0.19

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.
Files changed (120) hide show
  1. package/README.md +14 -12
  2. package/dist/TrackingManager.d.ts +64 -0
  3. package/dist/TrackingManager.d.ts.map +1 -0
  4. package/dist/TrackingManager.js +114 -0
  5. package/dist/TrackingManager.js.map +1 -0
  6. package/dist/api/generated/events/client/client.gen.js +176 -0
  7. package/dist/api/generated/events/client/client.gen.js.map +1 -0
  8. package/dist/api/generated/events/client/utils.gen.js +179 -0
  9. package/dist/api/generated/events/client/utils.gen.js.map +1 -0
  10. package/dist/api/generated/events/client.gen.js +8 -0
  11. package/dist/api/generated/events/client.gen.js.map +1 -0
  12. package/dist/api/generated/events/core/auth.gen.js +12 -0
  13. package/dist/api/generated/events/core/auth.gen.js.map +1 -0
  14. package/dist/api/generated/events/core/bodySerializer.gen.js +6 -0
  15. package/dist/api/generated/events/core/bodySerializer.gen.js.map +1 -0
  16. package/dist/api/generated/events/core/pathSerializer.gen.js +82 -0
  17. package/dist/api/generated/events/core/pathSerializer.gen.js.map +1 -0
  18. package/dist/api/generated/events/core/serverSentEvents.gen.js +95 -0
  19. package/dist/api/generated/events/core/serverSentEvents.gen.js.map +1 -0
  20. package/dist/api/generated/events/core/utils.gen.js +78 -0
  21. package/dist/api/generated/events/core/utils.gen.js.map +1 -0
  22. package/dist/api/generated/events/sdk.gen.js +31 -0
  23. package/dist/api/generated/events/sdk.gen.js.map +1 -0
  24. package/dist/api/generated/events/zod.gen.js +197 -0
  25. package/dist/api/generated/events/zod.gen.js.map +1 -0
  26. package/dist/api/generated/recommendations/client/client.gen.js +176 -0
  27. package/dist/api/generated/recommendations/client/client.gen.js.map +1 -0
  28. package/dist/api/generated/recommendations/client/utils.gen.js +179 -0
  29. package/dist/api/generated/recommendations/client/utils.gen.js.map +1 -0
  30. package/dist/api/generated/recommendations/client.gen.js +8 -0
  31. package/dist/api/generated/recommendations/client.gen.js.map +1 -0
  32. package/dist/api/generated/recommendations/core/auth.gen.js +12 -0
  33. package/dist/api/generated/recommendations/core/auth.gen.js.map +1 -0
  34. package/dist/api/generated/recommendations/core/bodySerializer.gen.js +6 -0
  35. package/dist/api/generated/recommendations/core/bodySerializer.gen.js.map +1 -0
  36. package/dist/api/generated/recommendations/core/pathSerializer.gen.js +82 -0
  37. package/dist/api/generated/recommendations/core/pathSerializer.gen.js.map +1 -0
  38. package/dist/api/generated/recommendations/core/serverSentEvents.gen.js +95 -0
  39. package/dist/api/generated/recommendations/core/serverSentEvents.gen.js.map +1 -0
  40. package/dist/api/generated/recommendations/core/utils.gen.js +78 -0
  41. package/dist/api/generated/recommendations/core/utils.gen.js.map +1 -0
  42. package/dist/api/generated/recommendations/sdk.gen.js +35 -0
  43. package/dist/api/generated/recommendations/sdk.gen.js.map +1 -0
  44. package/dist/api/generated/recommendations/types.gen.d.ts +32 -0
  45. package/dist/api/generated/recommendations/types.gen.d.ts.map +1 -0
  46. package/dist/api/generated/recommendations/zod.gen.js +407 -0
  47. package/dist/api/generated/recommendations/zod.gen.js.map +1 -0
  48. package/dist/api/index.js +60 -0
  49. package/dist/api/index.js.map +1 -0
  50. package/dist/apiKey.js +13 -0
  51. package/dist/apiKey.js.map +1 -0
  52. package/dist/config.js +38 -0
  53. package/dist/config.js.map +1 -0
  54. package/dist/env.d.ts +5 -0
  55. package/dist/env.d.ts.map +1 -0
  56. package/dist/errors.d.ts +56 -0
  57. package/dist/errors.d.ts.map +1 -0
  58. package/dist/errors.js +76 -0
  59. package/dist/errors.js.map +1 -0
  60. package/dist/events/dedupe.d.ts +15 -0
  61. package/dist/events/dedupe.d.ts.map +1 -0
  62. package/dist/events/dedupe.js +34 -0
  63. package/dist/events/dedupe.js.map +1 -0
  64. package/dist/events/eventMapping.js +88 -0
  65. package/dist/events/eventMapping.js.map +1 -0
  66. package/dist/external/DiscoClient.d.ts +88 -0
  67. package/dist/external/DiscoClient.d.ts.map +1 -0
  68. package/dist/external/DiscoClient.js +122 -0
  69. package/dist/external/DiscoClient.js.map +1 -0
  70. package/dist/external/recommendations.d.ts +186 -0
  71. package/dist/external/recommendations.d.ts.map +1 -0
  72. package/dist/external/recommendationsTransforms.js +216 -0
  73. package/dist/external/recommendationsTransforms.js.map +1 -0
  74. package/dist/index.d.ts +8 -97
  75. package/dist/index.js +3 -1769
  76. package/dist/internal/InternalDiscoClient.d.ts +129 -0
  77. package/dist/internal/InternalDiscoClient.d.ts.map +1 -0
  78. package/dist/internal/InternalDiscoClient.js +137 -0
  79. package/dist/internal/InternalDiscoClient.js.map +1 -0
  80. package/dist/internal/denormalize.d.ts +18 -0
  81. package/dist/internal/denormalize.d.ts.map +1 -0
  82. package/dist/internal/denormalize.js +49 -0
  83. package/dist/internal/denormalize.js.map +1 -0
  84. package/dist/internal/recommendations.d.ts +90 -0
  85. package/dist/internal/recommendations.d.ts.map +1 -0
  86. package/dist/internal/recommendationsMapper.js +68 -0
  87. package/dist/internal/recommendationsMapper.js.map +1 -0
  88. package/dist/internal/recommendationsRequestMapper.js +121 -0
  89. package/dist/internal/recommendationsRequestMapper.js.map +1 -0
  90. package/dist/internal/screens.d.ts +77 -0
  91. package/dist/internal/screens.d.ts.map +1 -0
  92. package/dist/internal/screens.js +79 -0
  93. package/dist/internal/screens.js.map +1 -0
  94. package/dist/internal.d.ts +11 -400
  95. package/dist/internal.js +5 -564
  96. package/dist/lib/case.js +26 -0
  97. package/dist/lib/case.js.map +1 -0
  98. package/dist/lib/http.js +21 -0
  99. package/dist/lib/http.js.map +1 -0
  100. package/dist/lib/primitives.js +23 -0
  101. package/dist/lib/primitives.js.map +1 -0
  102. package/dist/lib/schemas.js +25 -0
  103. package/dist/lib/schemas.js.map +1 -0
  104. package/dist/package.js +7 -0
  105. package/dist/package.js.map +1 -0
  106. package/dist/sdkIdentity.d.ts +9 -0
  107. package/dist/sdkIdentity.d.ts.map +1 -0
  108. package/dist/sdkIdentity.js +16 -0
  109. package/dist/sdkIdentity.js.map +1 -0
  110. package/dist/types.d.ts +91 -0
  111. package/dist/types.d.ts.map +1 -0
  112. package/package.json +4 -4
  113. package/dist/errors-DpKOKpT8.d.ts +0 -363
  114. package/dist/errors-DpKOKpT8.d.ts.map +0 -1
  115. package/dist/index.d.ts.map +0 -1
  116. package/dist/index.js.map +0 -1
  117. package/dist/internal.d.ts.map +0 -1
  118. package/dist/internal.js.map +0 -1
  119. package/dist/recommendationsTransforms-D_E4xU1d.js +0 -748
  120. package/dist/recommendationsTransforms-D_E4xU1d.js.map +0 -1
package/dist/internal.js CHANGED
@@ -1,566 +1,7 @@
1
1
  "use client";
2
- import { a as DiscoError, c as isAbortError, f as zRecommendationsResponse2, i as DiscoApiError, l as validatePublicApiKey, n as transformResponse, o as DiscoNetworkError, r as remap, s as DiscoValidationError, u as getSdkHeaders } from "./recommendationsTransforms-D_E4xU1d.js";
3
- import * as z from "zod/v4";
4
- import { ZodError } from "zod/v4";
5
- //#region src/lib/http.ts
6
- /**
7
- * Best-effort read of a non-2xx response body: try JSON, fall back to text,
8
- * then give up with `undefined`. Used by both clients to populate
9
- * `DiscoApiError.body` without ever throwing from the error path.
10
- */
11
- async function safeReadBody(response) {
12
- try {
13
- return await response.clone().json();
14
- } catch {
15
- try {
16
- return await response.text();
17
- } catch {
18
- return;
19
- }
20
- }
21
- }
22
- //#endregion
23
- //#region src/TrackingManager.ts
24
- /**
25
- * Renderer-agnostic event tracker for Disco recommendation surfaces.
26
- *
27
- * Owns:
28
- * - the dedup set (so repeated display/view events for the same brand
29
- * don't get re-sent within a session)
30
- * - the network call to the partner-events endpoint
31
- * - payload formatting (snake_case keys, BE-friendly datetime)
32
- *
33
- * Does not know about React. Wrap it in a Provider (`@disconetwork/react`'s
34
- * `DiscoProvider`) when consuming from a React tree, or instantiate it
35
- * directly from any other JS environment.
36
- *
37
- * `track` is implemented as an instance-bound arrow function so consumers
38
- * can safely destructure it without losing `this`.
39
- */
40
- var TrackingManager = class {
41
- #endpoint;
42
- #headers;
43
- #sessionId;
44
- #fetch;
45
- #dedupe = /* @__PURE__ */ new Set();
46
- constructor(config) {
47
- this.#endpoint = config.endpoint;
48
- this.#headers = {
49
- ...config.headers,
50
- ...getSdkHeaders(config.sdk)
51
- };
52
- this.#sessionId = config.sessionId;
53
- this.#fetch = config.fetch ?? globalThis.fetch.bind(globalThis);
54
- }
55
- /**
56
- * Send a tracking event. Fire-and-forget — never throws.
57
- * Failures are logged via `console.error`.
58
- *
59
- * Idempotency: `WIDGET_DISPLAY`, `WIDGET_VIEW`, `BRAND_DISPLAY`, and
60
- * `BRAND_VIEW` are deduped per-instance by (event type, insertionId).
61
- */
62
- track = (event) => {
63
- if (this.#isDeduped(event)) return;
64
- this.#fetch(this.#endpoint, {
65
- method: "POST",
66
- headers: {
67
- "Content-Type": "application/json",
68
- ...this.#headers
69
- },
70
- body: JSON.stringify(this.#toBody(event)),
71
- keepalive: true
72
- }).catch((error) => {
73
- console.error("Event tracking failed:", error);
74
- });
75
- };
76
- #isDeduped(event) {
77
- if (event.type === "WIDGET_DISPLAY" || event.type === "WIDGET_VIEW" || event.type === "BRAND_DISPLAY" || event.type === "BRAND_VIEW") {
78
- const key = event.type + ("brand" in event ? event.brand.insertionId : "widget");
79
- if (this.#dedupe.has(key)) return true;
80
- this.#dedupe.add(key);
81
- }
82
- return false;
83
- }
84
- #toBody(event) {
85
- const commonEventFields = {
86
- session_id: this.#sessionId,
87
- event_name: event.type,
88
- event_datetime: (/* @__PURE__ */ new Date()).toISOString().replace("Z", "+00:00"),
89
- placement_details: event.placement ? {
90
- display_mode: event.placement.displayMode,
91
- view: event.placement.view,
92
- layout_id: event.placement.layoutId
93
- } : void 0
94
- };
95
- switch (event.type) {
96
- case "BRAND_CLICK": return {
97
- ...commonEventFields,
98
- brand_properties: brandProperties(event.brand),
99
- initiating_target: event.target,
100
- asset_id: event.assetId
101
- };
102
- case "BRAND_DISPLAY":
103
- case "BRAND_VIEW": return {
104
- ...commonEventFields,
105
- brand_properties: brandProperties(event.brand),
106
- initiating_target: event.target
107
- };
108
- case "PRODUCT_DISPLAY":
109
- case "PRODUCT_VIEW":
110
- case "PRODUCT_CLICK": return {
111
- ...commonEventFields,
112
- brand_properties: brandProperties(event.brand),
113
- product_properties: { product_id: event.product.productId },
114
- initiating_target: event.target
115
- };
116
- case "ELEMENT_CLICK": return {
117
- ...commonEventFields,
118
- brand_properties: event.brand ? brandProperties(event.brand) : void 0,
119
- initiating_target: event.target
120
- };
121
- default: return commonEventFields;
122
- }
123
- }
124
- };
125
- function brandProperties(brand) {
126
- return {
127
- offer_id: brand.offerId,
128
- advertiser_id: brand.advertiserId,
129
- insertion_id: brand.insertionId
130
- };
131
- }
132
- //#endregion
133
- //#region src/internal/denormalize.ts
134
- /**
135
- * Join the normalized response maps into ordered `RecommendationGroup[]`.
136
- *
137
- * Groups are ordered by the numeric suffix of their key (`group_0` before
138
- * `group_10`); within each group, entries are ordered by `insertionOrder`.
139
- * Groups missing their entry list or display properties are skipped, as are
140
- * entries whose `offerId` is absent from the recommendations map. Each result
141
- * recommendation's `id` is the offer's id and its `insertionId` comes from the
142
- * group entry.
143
- */
144
- function denormalize(response) {
145
- const recommendations = response.recommendations;
146
- const groupEntries = response.recommendationGroups;
147
- const groupProps = response.recommendationGroupProperties ?? {};
148
- const orderedKeys = Object.keys(groupEntries).sort((a, b) => numericSuffix(a) - numericSuffix(b));
149
- const recommendationGroups = [];
150
- for (const key of orderedKeys) {
151
- const entries = groupEntries[key];
152
- const props = groupProps[key];
153
- if (!entries || !props) continue;
154
- const recs = [];
155
- for (const entry of entries) {
156
- const rec = recommendations[entry.offerId];
157
- if (!rec) continue;
158
- recs.push({
159
- id: rec.offer.id,
160
- insertionId: entry.insertionId,
161
- advertiser: rec.advertiser,
162
- offer: rec.offer
163
- });
164
- }
165
- recommendationGroups.push({
166
- heading: props.heading ?? null,
167
- slotContext: props.slotContext,
168
- recommendations: recs
169
- });
170
- }
171
- return recommendationGroups;
172
- }
173
- function numericSuffix(value) {
174
- const suffix = value.split("_").pop() ?? "";
175
- const parsed = Number.parseInt(suffix, 10);
176
- return Number.isNaN(parsed) ? Number.POSITIVE_INFINITY : parsed;
177
- }
178
- //#endregion
179
- //#region src/internal/recommendationsMapper.ts
180
- /**
181
- * Maps the proxy `/recommendations` response into the public, denormalized
182
- * `RecommendationsResponse` (`mapRecommendationsResponse`).
183
- *
184
- * The proxy response is the external `/recommendations` response **verbatim plus
185
- * a few extra top-level fields** (`layout_id`, `publisher_customization`, the
186
- * `widget_*` markers, …). So this reuses the external machinery — the generated
187
- * zod validator (`zRecommendationsResponse2`) and the external `transformResponse`
188
- * mapper — and only layers on the denormalization (the join into
189
- * `RecommendationGroup[]`) and the proxy extras.
190
- *
191
- * Validation is zod-backed: the external-wire part is validated by the generated
192
- * `zRecommendationsResponse2` and the proxy extras by a small local schema, so a
193
- * malformed server response surfaces as a `DiscoValidationError` rather than an
194
- * opaque `undefined`-access crash deep in the join.
195
- */
196
- const zProxyExtras = z.object({
197
- layout_id: z.string().optional(),
198
- publisher_customization: z.record(z.string(), z.record(z.string(), z.union([z.string(), z.boolean()]))).nullish()
199
- });
200
- /**
201
- * Validate the proxy recommendations response and denormalize it into the
202
- * public `RecommendationsResponse`.
203
- *
204
- * The proxy payload is the external wire response plus extras, so this reuses
205
- * the external machinery: validate the wire part with the generated
206
- * `zRecommendationsResponse2` and the extras with `zProxyExtras`, recase via
207
- * the external `transformResponse`, then denormalize the resulting maps into
208
- * `RecommendationGroup[]` (the internal value-add) and assemble the response
209
- * with the proxy extras layered on.
210
- *
211
- * Throws `DiscoValidationError` if the server payload doesn't match the
212
- * expected shape.
213
- *
214
- * @internal Built into `InternalDiscoClient.getRecommendations`; not part of
215
- * the public API. The wire shape is encapsulated by the client on purpose.
216
- */
217
- function mapRecommendationsResponse(raw) {
218
- let wire;
219
- let extras;
220
- try {
221
- wire = zRecommendationsResponse2.parse(raw);
222
- extras = zProxyExtras.parse(raw);
223
- } catch (error) {
224
- if (error instanceof ZodError) throw new DiscoValidationError("Failed to validate recommendations response", error, raw);
225
- throw error;
226
- }
227
- const normalized = transformResponse(wire);
228
- const recommendationGroups = denormalize(normalized);
229
- return {
230
- sessionId: normalized.sessionId,
231
- layoutId: extras.layout_id ?? "SHOPIFY_NATIVE_ESSENTIAL",
232
- recommendationGroups,
233
- footer: normalized.footer,
234
- publisherCustomization: extras.publisher_customization ?? null
235
- };
236
- }
237
- //#endregion
238
- //#region src/lib/schemas.ts
239
- /**
240
- * Thin wrappers around Zod parsing that convert a thrown `ZodError` into a
241
- * `DiscoValidationError`, so validation failures surface as a Disco error type
242
- * rather than leaking Zod's internals to consumers. Modeled on the equivalent
243
- * helpers in Speakeasy-generated SDKs.
244
- */
245
- /**
246
- * Run `fn` (typically a `schema.parse`) and, if it throws a `ZodError`, rethrow
247
- * it as a `DiscoValidationError`. Any non-Zod error propagates untouched.
248
- */
249
- function parse(rawValue, fn, errorMessage) {
250
- try {
251
- return fn(rawValue);
252
- } catch (err) {
253
- if (err instanceof z.ZodError) throw new DiscoValidationError(errorMessage, err, rawValue);
254
- throw err;
255
- }
256
- }
257
- //#endregion
258
- //#region src/internal/recommendationsRequestMapper.ts
259
- /**
260
- * Wire types for the recommendations *request* and `transformRequest`, which
261
- * builds the snake_case wire body from the public `RecommendationsRequest`.
262
- *
263
- * `InternalDiscoClient.getRecommendations` calls `transformRequest` to map the
264
- * camelCase request into the wire body before POSTing it.
265
- *
266
- * The mapping is Zod-backed: `RecommendationsRequest$outboundSchema` validates
267
- * the public request before the `.transform()` reshapes it into the wire body,
268
- * so a malformed request surfaces as a `DiscoValidationError` *before* it hits
269
- * the network. This mirrors how Speakeasy-generated SDKs use an
270
- * `$outboundSchema` per model.
271
- */
272
- const UserDetails$outboundSchema = z.object({
273
- email: z.string().optional(),
274
- firstName: z.string().optional(),
275
- lastName: z.string().optional(),
276
- phone: z.string().optional()
277
- }).transform((v) => remap(v, {
278
- firstName: "first_name",
279
- lastName: "last_name"
280
- }));
281
- const PlacementDetails$outboundSchema = z.object({
282
- widgetId: z.string().optional(),
283
- displayMode: z.string().optional(),
284
- view: z.string().optional()
285
- }).transform((v) => remap(v, {
286
- displayMode: "display_mode",
287
- widgetId: "widget_id"
288
- }));
289
- const OrderDetails$outboundSchema = z.object({
290
- id: z.string().optional(),
291
- amount: z.union([z.number(), z.string()]).optional(),
292
- currencyCode: z.string().optional()
293
- }).transform((v) => ({
294
- order_id: v.id,
295
- cost_details: v.amount !== void 0 || v.currencyCode !== void 0 ? {
296
- amount: v.amount,
297
- currency_code: v.currencyCode
298
- } : void 0
299
- }));
300
- const Purchase$outboundSchema = z.object({
301
- name: z.string().optional(),
302
- type: z.string().optional(),
303
- variant: z.string().optional(),
304
- quantity: z.number().optional(),
305
- productId: z.string().optional(),
306
- amount: z.number().optional(),
307
- currencyCode: z.string().optional()
308
- }).transform((v) => ({
309
- name: v.name,
310
- type: v.type,
311
- variant: v.variant,
312
- quantity: v.quantity,
313
- product_id: v.productId,
314
- cost_details: v.amount !== void 0 || v.currencyCode !== void 0 ? {
315
- amount: v.amount,
316
- currency_code: v.currencyCode
317
- } : void 0
318
- }));
319
- const RunningExperiment$outboundSchema = z.object({
320
- id: z.string(),
321
- variant: z.string()
322
- });
323
- /**
324
- * Validates the public request and reshapes it into the raw wire body: nest
325
- * fields under `recommendations_data`, fold monetary fields into `cost_details`,
326
- * convert camelCase to snake_case, and spread `extras` at the top level
327
- * untransformed.
328
- */
329
- const RecommendationsRequest$outboundSchema = z.object({
330
- user: UserDetails$outboundSchema.optional(),
331
- placement: PlacementDetails$outboundSchema.optional(),
332
- order: OrderDetails$outboundSchema.optional(),
333
- purchases: z.array(Purchase$outboundSchema).optional(),
334
- experiments: z.array(RunningExperiment$outboundSchema).optional(),
335
- attributes: z.record(z.string(), z.unknown()).optional(),
336
- extras: z.record(z.string(), z.unknown()).optional()
337
- }).transform((v) => ({
338
- recommendations_data: {
339
- user_details: v.user,
340
- placement_details: v.placement,
341
- order_details: v.order,
342
- purchases: v.purchases
343
- },
344
- running_experiments: v.experiments,
345
- attributes: v.attributes,
346
- ...v.extras
347
- }));
348
- /**
349
- * Build the raw request body from the public `RecommendationsRequest`: nest
350
- * fields under `recommendations_data`, fold monetary fields into `cost_details`
351
- * (omitted entirely when no amount/currency is present), and convert camelCase
352
- * to snake_case. `extras` is spread at the top level untransformed.
353
- *
354
- * Validates the input first and throws `DiscoValidationError` if the request
355
- * doesn't match the expected shape.
356
- *
357
- * @internal Built into `DiscoClient.getRecommendations`; not part of the public
358
- * API. The wire shape is encapsulated by the client on purpose.
359
- */
360
- function transformRequest(req) {
361
- return parse(req, (value) => RecommendationsRequest$outboundSchema.parse(value), "Failed to validate recommendations request");
362
- }
363
- //#endregion
364
- //#region src/internal/InternalDiscoClient.ts
365
- /**
366
- * Per-environment base URL for the internal/proxy backend — the legacy server
367
- * that orchestrates and forwards to the downstream services. Both the
368
- * recommendations and tracking endpoints sit under this origin, routed by path
369
- * (the client appends `/core/recommendations/…` and `/track/partners_event/`).
370
- */
371
- const INTERNAL_BASE_URL = {
372
- production: "https://consumer.disconetwork.com",
373
- staging: "https://consumer.disconetwork-staging.com"
374
- };
375
- /**
376
- * Internal client for the legacy **proxy** recommendations endpoint
377
- * (`/core/recommendations/` on the backend), which orchestrates placement,
378
- * experiments, layout, and `publisher_customization` server-side and supports
379
- * `shopGid` auth for first-party surfaces (e.g. the Shopify checkout
380
- * extension).
381
- *
382
- * First-party / legacy only — exported from `@disconetwork/core/internal`.
383
- * External partners use the `DiscoClient` from the package root, which talks
384
- * directly to `disco-recommendations-api`.
385
- *
386
- * Renderer-agnostic: this class makes plain HTTP calls and has no React
387
- * dependency.
388
- */
389
- var InternalDiscoClient = class {
390
- #env;
391
- #url;
392
- #headers;
393
- #sdk;
394
- #fetch;
395
- get env() {
396
- return this.#env;
397
- }
398
- constructor(config) {
399
- this.#fetch = config.fetch ?? globalThis.fetch.bind(globalThis);
400
- this.#sdk = config.sdk ? { ...config.sdk } : void 0;
401
- if ("apiKey" in config) {
402
- validatePublicApiKey(config.apiKey);
403
- this.#env = "production";
404
- const path = config.surface === "shopify" ? "shopify/" : "";
405
- this.#url = `${INTERNAL_BASE_URL[this.#env]}/core/recommendations/${path}`;
406
- this.#headers = {
407
- "x-api-key": config.apiKey,
408
- "Content-Type": "application/json"
409
- };
410
- } else {
411
- this.#env = config.env;
412
- const shopId = stripShopGid(config.shopGid);
413
- this.#url = `${INTERNAL_BASE_URL[this.#env]}/core/recommendations/shop_gid/${encodeURIComponent(shopId)}/`;
414
- this.#headers = { "Content-Type": "application/json" };
415
- }
416
- Object.assign(this.#headers, getSdkHeaders(this.#sdk));
417
- }
418
- /**
419
- * Fetch recommendations for the given request.
420
- *
421
- * Validates and transforms the friendly camelCase `request` into the wire
422
- * body, POSTs it, then validates and denormalizes the response into the
423
- * friendly `RecommendationsResponse`. The snake_case wire format is fully
424
- * encapsulated — callers never see it.
425
- *
426
- * Throws `DiscoValidationError` if the request or response fails schema
427
- * validation, `DiscoApiError` on non-2xx responses, and `DiscoNetworkError`
428
- * if the request can't reach the server (an abort rejects with the native
429
- * `AbortError`). Parse failures propagate as-is.
430
- */
431
- getRecommendations = async (request, options) => {
432
- const body = JSON.stringify(transformRequest(request));
433
- let response;
434
- try {
435
- response = await this.#fetch(this.#url, {
436
- method: "POST",
437
- headers: this.#headers,
438
- body,
439
- signal: options?.signal
440
- });
441
- } catch (error) {
442
- if (isAbortError(error)) throw error;
443
- throw new DiscoNetworkError("Recommendations request failed to reach the server", error);
444
- }
445
- if (!response.ok) {
446
- const body = await safeReadBody(response);
447
- throw new DiscoApiError(`Recommendations request failed: ${response.status} ${response.statusText}`, {
448
- status: response.status,
449
- statusText: response.statusText,
450
- body
451
- });
452
- }
453
- return mapRecommendationsResponse(await response.json());
454
- };
455
- /**
456
- * Fetch recommendations and create a session-bound tracker in one call.
457
- *
458
- * Composition convenience over `getRecommendations` + `createTrackingManager`:
459
- * it derives the tracker's session from the response so callers don't have to
460
- * thread the session id through themselves (and can't bind a tracker to the
461
- * wrong session). The returned `data` is the mapped `RecommendationsResponse`.
462
- *
463
- * Throws `DiscoValidationError` / `DiscoApiError` the same as
464
- * `getRecommendations`.
465
- */
466
- getRecommendationsWithTracker = async (request, options) => {
467
- const data = await this.getRecommendations(request, { signal: options?.signal });
468
- return {
469
- data,
470
- tracker: this.createTrackingManager(data.sessionId, { fetch: options?.fetch })
471
- };
472
- };
473
- /**
474
- * Create an event tracker bound to a recommendations session (the `sessionId`
475
- * from a `getRecommendations` response).
476
- *
477
- * The tracker uses the same environment as the recommendations call.
478
- * Both live and sandbox public keys use production.
479
- */
480
- createTrackingManager = (sessionId, options) => new TrackingManager({
481
- sessionId,
482
- endpoint: `${INTERNAL_BASE_URL[this.#env]}/track/partners_event/`,
483
- fetch: options?.fetch ?? this.#fetch,
484
- sdk: this.#sdk
485
- });
486
- };
487
- function stripShopGid(shopGid) {
488
- return shopGid.replace("gid://shopify/Shop/", "");
489
- }
490
- //#endregion
491
- //#region src/internal/screens.ts
492
- const TextNodeSchema = z.object({
493
- type: z.literal("text"),
494
- text: z.string()
495
- });
496
- const ExternalLinkAttributesSchema = z.object({
497
- to: z.url(),
498
- external: z.boolean().optional().default(true)
499
- });
500
- const InternalLinkAttributesSchema = z.object({ targetScreenId: z.string() });
501
- const LinkAttributesSchema = z.union([ExternalLinkAttributesSchema, InternalLinkAttributesSchema]);
502
- const LinkNodeSchema = z.object({
503
- type: z.literal("link"),
504
- attributes: LinkAttributesSchema,
505
- get children() {
506
- return z.array(ASTNodeSchema).min(1);
507
- }
508
- });
509
- const ParagraphNodeSchema = z.object({
510
- type: z.literal("paragraph"),
511
- get children() {
512
- return z.array(ASTNodeSchema).min(1);
513
- }
514
- });
515
- const ScrollViewNodeSchema = z.object({
516
- type: z.literal("scrollview"),
517
- attributes: z.object({ maxBlockSize: z.number().optional() }).optional(),
518
- get children() {
519
- return z.array(ASTNodeSchema).min(1);
520
- }
521
- });
522
- const ASTNodeSchema = z.discriminatedUnion("type", [
523
- TextNodeSchema,
524
- LinkNodeSchema,
525
- ParagraphNodeSchema,
526
- ScrollViewNodeSchema
527
- ]);
528
- const ASTSchema = z.object({ get children() {
529
- return z.array(ASTNodeSchema).min(1);
530
- } });
531
- const ScreenSchema = ASTSchema.extend({ id: z.string() });
532
- function collectTargetScreenIds(nodes) {
533
- const ids = [];
534
- for (const node of nodes) {
535
- if (node.type === "link" && "targetScreenId" in node.attributes) ids.push(node.attributes.targetScreenId);
536
- if ("children" in node) ids.push(...collectTargetScreenIds(node.children));
537
- }
538
- return ids;
539
- }
540
- const ScreenDocumentSchema = z.object({ screens: z.array(ScreenSchema).min(1) }).refine((doc) => {
541
- const ids = doc.screens.map((s) => s.id);
542
- return new Set(ids).size === ids.length;
543
- }, { message: "Duplicate screen IDs" }).refine((doc) => {
544
- const screenIds = new Set(doc.screens.map((s) => s.id));
545
- return doc.screens.flatMap((s) => collectTargetScreenIds(s.children)).every((id) => screenIds.has(id));
546
- }, { message: "targetScreenId references a non-existent screen" });
547
- /**
548
- * Parse offer screens content into a list of screens. Returns `null` when the
549
- * content is missing or matches neither the screen document nor the legacy
550
- * single-root shape, so callers can render a fallback.
551
- */
552
- function parseScreens(jsonContent) {
553
- if (!jsonContent) return null;
554
- const screenResult = ScreenDocumentSchema.safeParse(jsonContent);
555
- if (screenResult.success) return screenResult.data.screens;
556
- const legacyResult = ASTSchema.safeParse(jsonContent);
557
- if (legacyResult.success) return [{
558
- id: "default",
559
- children: legacyResult.data.children
560
- }];
561
- return null;
562
- }
563
- //#endregion
2
+ import { DiscoApiError, DiscoError, DiscoNetworkError, DiscoValidationError } from "./errors.js";
3
+ import { TrackingManager } from "./TrackingManager.js";
4
+ import { denormalize } from "./internal/denormalize.js";
5
+ import { INTERNAL_BASE_URL, InternalDiscoClient } from "./internal/InternalDiscoClient.js";
6
+ import { parseScreens } from "./internal/screens.js";
564
7
  export { DiscoApiError, DiscoError, DiscoNetworkError, DiscoValidationError, INTERNAL_BASE_URL, InternalDiscoClient, TrackingManager, denormalize, parseScreens };
565
-
566
- //# sourceMappingURL=internal.js.map
@@ -0,0 +1,26 @@
1
+ //#region src/lib/case.ts
2
+ /**
3
+ * Recursively convert an object's keys from camelCase to snake_case, descending
4
+ * into nested objects and arrays. Values are left untouched.
5
+ *
6
+ * Reserved for the request's `customMetadata` — an untyped map whose keys are
7
+ * known field names we want recased, not arbitrary data. Everything else on the
8
+ * request path is remapped field-by-field (see `recommendationsTransforms.ts`), so
9
+ * data-keyed values like a purchase `variant` map are never blindly recased.
10
+ */
11
+ function toSnakeKeys(value) {
12
+ if (Array.isArray(value)) return value.map(toSnakeKeys);
13
+ if (value !== null && typeof value === "object") {
14
+ const out = {};
15
+ for (const [key, v] of Object.entries(value)) out[snakeCase(key)] = toSnakeKeys(v);
16
+ return out;
17
+ }
18
+ return value;
19
+ }
20
+ function snakeCase(key) {
21
+ return key.replace(/([A-Za-z])([0-9])/g, "$1_$2").replace(/[A-Z]/g, (match) => `_${match.toLowerCase()}`);
22
+ }
23
+ //#endregion
24
+ export { toSnakeKeys };
25
+
26
+ //# sourceMappingURL=case.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"case.js","names":[],"sources":["../../src/lib/case.ts"],"sourcesContent":["/**\n * Recursively convert an object's keys from camelCase to snake_case, descending\n * into nested objects and arrays. Values are left untouched.\n *\n * Reserved for the request's `customMetadata` — an untyped map whose keys are\n * known field names we want recased, not arbitrary data. Everything else on the\n * request path is remapped field-by-field (see `recommendationsTransforms.ts`), so\n * data-keyed values like a purchase `variant` map are never blindly recased.\n */\nexport function toSnakeKeys(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(toSnakeKeys);\n }\n if (value !== null && typeof value === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [key, v] of Object.entries(value)) {\n out[snakeCase(key)] = toSnakeKeys(v);\n }\n return out;\n }\n return value;\n}\n\nfunction snakeCase(key: string): string {\n return (\n key\n // Split a letter→digit boundary so `addressLine1` → `address_line_1`.\n .replace(/([A-Za-z])([0-9])/g, \"$1_$2\")\n .replace(/[A-Z]/g, (match) => `_${match.toLowerCase()}`)\n );\n}\n"],"mappings":";;;;;;;;;;AASA,SAAgB,YAAY,OAAyB;CACnD,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,MAAM,IAAI,WAAW;CAE9B,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU;EAC/C,MAAM,MAA+B,CAAC;EACtC,KAAK,MAAM,CAAC,KAAK,MAAM,OAAO,QAAQ,KAAK,GACzC,IAAI,UAAU,GAAG,KAAK,YAAY,CAAC;EAErC,OAAO;CACT;CACA,OAAO;AACT;AAEA,SAAS,UAAU,KAAqB;CACtC,OACE,IAEG,QAAQ,sBAAsB,OAAO,EACrC,QAAQ,WAAW,UAAU,IAAI,MAAM,YAAY,GAAG;AAE7D"}
@@ -0,0 +1,21 @@
1
+ //#region src/lib/http.ts
2
+ /**
3
+ * Best-effort read of a non-2xx response body: try JSON, fall back to text,
4
+ * then give up with `undefined`. Used by both clients to populate
5
+ * `DiscoApiError.body` without ever throwing from the error path.
6
+ */
7
+ async function safeReadBody(response) {
8
+ try {
9
+ return await response.clone().json();
10
+ } catch {
11
+ try {
12
+ return await response.text();
13
+ } catch {
14
+ return;
15
+ }
16
+ }
17
+ }
18
+ //#endregion
19
+ export { safeReadBody };
20
+
21
+ //# sourceMappingURL=http.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http.js","names":[],"sources":["../../src/lib/http.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"],"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"}
@@ -0,0 +1,23 @@
1
+ //#region src/lib/primitives.ts
2
+ /**
3
+ * Return a new object with `inp`'s keys renamed according to `mappings`.
4
+ * A key mapped to a string is renamed; a key mapped to `null` is dropped; a key
5
+ * absent from the mapping is kept as-is.
6
+ */
7
+ function remap(inp, mappings) {
8
+ let out = {};
9
+ if (!Object.keys(mappings).length) {
10
+ out = inp;
11
+ return out;
12
+ }
13
+ for (const [k, v] of Object.entries(inp)) {
14
+ const j = mappings[k];
15
+ if (j === null) continue;
16
+ out[j ?? k] = v;
17
+ }
18
+ return out;
19
+ }
20
+ //#endregion
21
+ export { remap };
22
+
23
+ //# sourceMappingURL=primitives.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"primitives.js","names":[],"sources":["../../src/lib/primitives.ts"],"sourcesContent":["/**\n * Key-remapping helper used inside Zod `.transform()` steps to rename fields\n * between the public camelCase shape and the snake_case wire shape — the same\n * utility Speakeasy emits in its generated SDKs.\n */\n\nexport type Remap<Inp, Mapping extends { [k in keyof Inp]?: string | null }> = {\n [k in keyof Inp as Mapping[k] extends string\n ? Mapping[k]\n : Mapping[k] extends null\n ? never\n : k]: Inp[k];\n};\n\n/**\n * Return a new object with `inp`'s keys renamed according to `mappings`.\n * A key mapped to a string is renamed; a key mapped to `null` is dropped; a key\n * absent from the mapping is kept as-is.\n */\nexport function remap<\n Inp extends Record<string, unknown>,\n const Mapping extends { [k in keyof Inp]?: string | null },\n>(inp: Inp, mappings: Mapping): Remap<Inp, Mapping> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let out: any = {};\n\n if (!Object.keys(mappings).length) {\n out = inp;\n return out;\n }\n\n for (const [k, v] of Object.entries(inp)) {\n const j = (mappings as Record<string, string | null | undefined>)[k];\n if (j === null) {\n continue;\n }\n out[j ?? k] = v;\n }\n\n return out;\n}\n"],"mappings":";;;;;;AAmBA,SAAgB,MAGd,KAAU,UAAwC;CAElD,IAAI,MAAW,CAAC;CAEhB,IAAI,CAAC,OAAO,KAAK,QAAQ,EAAE,QAAQ;EACjC,MAAM;EACN,OAAO;CACT;CAEA,KAAK,MAAM,CAAC,GAAG,MAAM,OAAO,QAAQ,GAAG,GAAG;EACxC,MAAM,IAAK,SAAuD;EAClE,IAAI,MAAM,MACR;EAEF,IAAI,KAAK,KAAK;CAChB;CAEA,OAAO;AACT"}
@@ -0,0 +1,25 @@
1
+ import { DiscoValidationError } from "../errors.js";
2
+ import { $ZodError } from "zod/v4/core";
3
+ //#region src/lib/schemas.ts
4
+ /**
5
+ * Thin wrappers around Zod parsing that convert a thrown `$ZodError` into a
6
+ * `DiscoValidationError`, so validation failures surface as a Disco error type
7
+ * rather than leaking Zod's internals to consumers. Modeled on the equivalent
8
+ * helpers in Speakeasy-generated SDKs.
9
+ */
10
+ /**
11
+ * Run `fn` (typically a `schema.parse`) and, if it throws a `$ZodError`, rethrow
12
+ * it as a `DiscoValidationError`. Any non-Zod error propagates untouched.
13
+ */
14
+ function parse(rawValue, fn, errorMessage) {
15
+ try {
16
+ return fn(rawValue);
17
+ } catch (err) {
18
+ if (err instanceof $ZodError) throw new DiscoValidationError(errorMessage, err, rawValue);
19
+ throw err;
20
+ }
21
+ }
22
+ //#endregion
23
+ export { parse };
24
+
25
+ //# sourceMappingURL=schemas.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schemas.js","names":[],"sources":["../../src/lib/schemas.ts"],"sourcesContent":["/**\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 { $ZodError } from \"zod/v4/core\";\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 $ZodError) {\n throw new DiscoValidationError(errorMessage, err, rawValue);\n }\n throw err;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAcA,SAAgB,MACd,UACA,IACA,cACK;CACL,IAAI;EACF,OAAO,GAAG,QAAQ;CACpB,SAAS,KAAK;EACZ,IAAI,eAAe,WACjB,MAAM,IAAI,qBAAqB,cAAc,KAAK,QAAQ;EAE5D,MAAM;CACR;AACF"}