@disconetwork/core 0.0.4 → 0.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,373 +1,782 @@
1
- //#region src/env.ts
2
- const ENV_ENDPOINTS = {
3
- production: {
4
- apiBaseUrl: "https://consumer.disconetwork.com",
5
- trackingEndpoint: "https://consumer.disconetwork.com/track/partners_event/"
6
- },
7
- staging: {
8
- apiBaseUrl: "https://consumer.disconetwork-staging.com",
9
- trackingEndpoint: "https://consumer.disconetwork-staging.com/track/partners_event/"
1
+ "use client";
2
+ import { a as DiscoApiError, c as DiscoValidationError, d as zRecommendationsBody, f as zRecommendationsResponse2, l as isAbortError, n as transformRequest, o as DiscoError, r as transformResponse, s as DiscoNetworkError, t as TrackingManager, u as envFromApiKey } from "./TrackingManager-_IENEPuL.js";
3
+ import * as z from "zod/v4";
4
+ import { ZodError } from "zod/v4";
5
+ //#region src/api/generated/recommendations/core/bodySerializer.gen.ts
6
+ const jsonBodySerializer = { bodySerializer: (body) => JSON.stringify(body, (_key, value) => typeof value === "bigint" ? value.toString() : value) };
7
+ //#endregion
8
+ //#region src/api/generated/recommendations/core/serverSentEvents.gen.ts
9
+ function createSseClient({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }) {
10
+ let lastEventId;
11
+ const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
12
+ const createStream = async function* () {
13
+ let retryDelay = sseDefaultRetryDelay ?? 3e3;
14
+ let attempt = 0;
15
+ const signal = options.signal ?? new AbortController().signal;
16
+ while (true) {
17
+ if (signal.aborted) break;
18
+ attempt++;
19
+ const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers);
20
+ if (lastEventId !== void 0) headers.set("Last-Event-ID", lastEventId);
21
+ try {
22
+ const requestInit = {
23
+ redirect: "follow",
24
+ ...options,
25
+ body: options.serializedBody,
26
+ headers,
27
+ signal
28
+ };
29
+ let request = new Request(url, requestInit);
30
+ if (onRequest) request = await onRequest(url, requestInit);
31
+ const response = await (options.fetch ?? globalThis.fetch)(request);
32
+ if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`);
33
+ if (!response.body) throw new Error("No body in SSE response");
34
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
35
+ let buffer = "";
36
+ const abortHandler = () => {
37
+ try {
38
+ reader.cancel();
39
+ } catch {}
40
+ };
41
+ signal.addEventListener("abort", abortHandler);
42
+ try {
43
+ while (true) {
44
+ const { done, value } = await reader.read();
45
+ if (done) break;
46
+ buffer += value;
47
+ buffer = buffer.replace(/\r\n?/g, "\n");
48
+ const chunks = buffer.split("\n\n");
49
+ buffer = chunks.pop() ?? "";
50
+ for (const chunk of chunks) {
51
+ const lines = chunk.split("\n");
52
+ const dataLines = [];
53
+ let eventName;
54
+ for (const line of lines) if (line.startsWith("data:")) dataLines.push(line.replace(/^data:\s*/, ""));
55
+ else if (line.startsWith("event:")) eventName = line.replace(/^event:\s*/, "");
56
+ else if (line.startsWith("id:")) lastEventId = line.replace(/^id:\s*/, "");
57
+ else if (line.startsWith("retry:")) {
58
+ const parsed = Number.parseInt(line.replace(/^retry:\s*/, ""), 10);
59
+ if (!Number.isNaN(parsed)) retryDelay = parsed;
60
+ }
61
+ let data;
62
+ let parsedJson = false;
63
+ if (dataLines.length) {
64
+ const rawData = dataLines.join("\n");
65
+ try {
66
+ data = JSON.parse(rawData);
67
+ parsedJson = true;
68
+ } catch {
69
+ data = rawData;
70
+ }
71
+ }
72
+ if (parsedJson) {
73
+ if (responseValidator) await responseValidator(data);
74
+ if (responseTransformer) data = await responseTransformer(data);
75
+ }
76
+ onSseEvent?.({
77
+ data,
78
+ event: eventName,
79
+ id: lastEventId,
80
+ retry: retryDelay
81
+ });
82
+ if (dataLines.length) yield data;
83
+ }
84
+ }
85
+ } finally {
86
+ signal.removeEventListener("abort", abortHandler);
87
+ reader.releaseLock();
88
+ }
89
+ break;
90
+ } catch (error) {
91
+ onSseError?.(error);
92
+ if (sseMaxRetryAttempts !== void 0 && attempt >= sseMaxRetryAttempts) break;
93
+ await sleep(Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 3e4));
94
+ }
95
+ }
96
+ };
97
+ return { stream: createStream() };
98
+ }
99
+ //#endregion
100
+ //#region src/api/generated/recommendations/core/pathSerializer.gen.ts
101
+ const separatorArrayExplode = (style) => {
102
+ switch (style) {
103
+ case "label": return ".";
104
+ case "matrix": return ";";
105
+ case "simple": return ",";
106
+ default: return "&";
10
107
  }
11
108
  };
12
- /**
13
- * Derive the environment from a Disco public API key.
14
- *
15
- * Public keys are prefixed `disco_pk_<env>_…`, where `<env>` is `live`
16
- * (→ production) or `sandbox` (→ staging). The key is the single source
17
- * of truth for which backend the SDK talks to — there is no separate
18
- * `env` to pass or keep in sync, and a `live` key can't be pointed at
19
- * staging (or vice versa).
20
- *
21
- * Throws on anything that isn't a recognized public key — including a
22
- * secret (`disco_sk_…`) key, which must never be used in browser code.
23
- */
24
- function envFromApiKey(apiKey) {
25
- if (apiKey.startsWith("disco_pk_live_")) return "production";
26
- if (apiKey.startsWith("disco_pk_sandbox_")) return "staging";
27
- throw new Error("Invalid Disco API key: expected a public key prefixed \"disco_pk_live_\" (production) or \"disco_pk_sandbox_\" (staging).");
109
+ const separatorArrayNoExplode = (style) => {
110
+ switch (style) {
111
+ case "form": return ",";
112
+ case "pipeDelimited": return "|";
113
+ case "spaceDelimited": return "%20";
114
+ default: return ",";
115
+ }
116
+ };
117
+ const separatorObjectExplode = (style) => {
118
+ switch (style) {
119
+ case "label": return ".";
120
+ case "matrix": return ";";
121
+ case "simple": return ",";
122
+ default: return "&";
123
+ }
124
+ };
125
+ const serializeArrayParam = ({ allowReserved, explode, name, style, value }) => {
126
+ if (!explode) {
127
+ const joinedValues = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
128
+ switch (style) {
129
+ case "label": return `.${joinedValues}`;
130
+ case "matrix": return `;${name}=${joinedValues}`;
131
+ case "simple": return joinedValues;
132
+ default: return `${name}=${joinedValues}`;
133
+ }
134
+ }
135
+ const separator = separatorArrayExplode(style);
136
+ const joinedValues = value.map((v) => {
137
+ if (style === "label" || style === "simple") return allowReserved ? v : encodeURIComponent(v);
138
+ return serializePrimitiveParam({
139
+ allowReserved,
140
+ name,
141
+ value: v
142
+ });
143
+ }).join(separator);
144
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
145
+ };
146
+ const serializePrimitiveParam = ({ allowReserved, name, value }) => {
147
+ if (value === void 0 || value === null) return "";
148
+ if (typeof value === "object") throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");
149
+ return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
150
+ };
151
+ const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly }) => {
152
+ if (value instanceof Date) return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
153
+ if (style !== "deepObject" && !explode) {
154
+ let values = [];
155
+ Object.entries(value).forEach(([key, v]) => {
156
+ values = [
157
+ ...values,
158
+ key,
159
+ allowReserved ? v : encodeURIComponent(v)
160
+ ];
161
+ });
162
+ const joinedValues = values.join(",");
163
+ switch (style) {
164
+ case "form": return `${name}=${joinedValues}`;
165
+ case "label": return `.${joinedValues}`;
166
+ case "matrix": return `;${name}=${joinedValues}`;
167
+ default: return joinedValues;
168
+ }
169
+ }
170
+ const separator = separatorObjectExplode(style);
171
+ const joinedValues = Object.entries(value).map(([key, v]) => serializePrimitiveParam({
172
+ allowReserved,
173
+ name: style === "deepObject" ? `${name}[${key}]` : key,
174
+ value: v
175
+ })).join(separator);
176
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
177
+ };
178
+ //#endregion
179
+ //#region src/api/generated/recommendations/core/utils.gen.ts
180
+ const PATH_PARAM_RE = /\{[^{}]+\}/g;
181
+ const defaultPathSerializer = ({ path, url: _url }) => {
182
+ let url = _url;
183
+ const matches = _url.match(PATH_PARAM_RE);
184
+ if (matches) for (const match of matches) {
185
+ let explode = false;
186
+ let name = match.substring(1, match.length - 1);
187
+ let style = "simple";
188
+ if (name.endsWith("*")) {
189
+ explode = true;
190
+ name = name.substring(0, name.length - 1);
191
+ }
192
+ if (name.startsWith(".")) {
193
+ name = name.substring(1);
194
+ style = "label";
195
+ } else if (name.startsWith(";")) {
196
+ name = name.substring(1);
197
+ style = "matrix";
198
+ }
199
+ const value = path[name];
200
+ if (value === void 0 || value === null) continue;
201
+ if (Array.isArray(value)) {
202
+ url = url.replace(match, serializeArrayParam({
203
+ explode,
204
+ name,
205
+ style,
206
+ value
207
+ }));
208
+ continue;
209
+ }
210
+ if (typeof value === "object") {
211
+ url = url.replace(match, serializeObjectParam({
212
+ explode,
213
+ name,
214
+ style,
215
+ value,
216
+ valueOnly: true
217
+ }));
218
+ continue;
219
+ }
220
+ if (style === "matrix") {
221
+ url = url.replace(match, `;${serializePrimitiveParam({
222
+ name,
223
+ value
224
+ })}`);
225
+ continue;
226
+ }
227
+ const replaceValue = encodeURIComponent(style === "label" ? `.${value}` : value);
228
+ url = url.replace(match, replaceValue);
229
+ }
230
+ return url;
231
+ };
232
+ const getUrl = ({ baseUrl, path, query, querySerializer, url: _url }) => {
233
+ const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
234
+ let url = (baseUrl ?? "") + pathUrl;
235
+ if (path) url = defaultPathSerializer({
236
+ path,
237
+ url
238
+ });
239
+ let search = query ? querySerializer(query) : "";
240
+ if (search.startsWith("?")) search = search.substring(1);
241
+ if (search) url += `?${search}`;
242
+ return url;
243
+ };
244
+ function getValidRequestBody(options) {
245
+ const hasBody = options.body !== void 0;
246
+ if (hasBody && options.bodySerializer) {
247
+ if ("serializedBody" in options) return options.serializedBody !== void 0 && options.serializedBody !== "" ? options.serializedBody : null;
248
+ return options.body !== "" ? options.body : null;
249
+ }
250
+ if (hasBody) return options.body;
28
251
  }
29
252
  //#endregion
30
- //#region src/TrackingManager.ts
253
+ //#region src/api/generated/recommendations/core/auth.gen.ts
254
+ const getAuthToken = async (auth, callback) => {
255
+ const token = typeof callback === "function" ? await callback(auth) : callback;
256
+ if (!token) return;
257
+ if (auth.scheme === "bearer") return `Bearer ${token}`;
258
+ if (auth.scheme === "basic") return `Basic ${btoa(token)}`;
259
+ return token;
260
+ };
261
+ //#endregion
262
+ //#region src/api/generated/recommendations/client/utils.gen.ts
263
+ const createQuerySerializer = ({ parameters = {}, ...args } = {}) => {
264
+ const querySerializer = (queryParams) => {
265
+ const search = [];
266
+ if (queryParams && typeof queryParams === "object") for (const name in queryParams) {
267
+ const value = queryParams[name];
268
+ if (value === void 0 || value === null) continue;
269
+ const options = parameters[name] || args;
270
+ if (Array.isArray(value)) {
271
+ const serializedArray = serializeArrayParam({
272
+ allowReserved: options.allowReserved,
273
+ explode: true,
274
+ name,
275
+ style: "form",
276
+ value,
277
+ ...options.array
278
+ });
279
+ if (serializedArray) search.push(serializedArray);
280
+ } else if (typeof value === "object") {
281
+ const serializedObject = serializeObjectParam({
282
+ allowReserved: options.allowReserved,
283
+ explode: true,
284
+ name,
285
+ style: "deepObject",
286
+ value,
287
+ ...options.object
288
+ });
289
+ if (serializedObject) search.push(serializedObject);
290
+ } else {
291
+ const serializedPrimitive = serializePrimitiveParam({
292
+ allowReserved: options.allowReserved,
293
+ name,
294
+ value
295
+ });
296
+ if (serializedPrimitive) search.push(serializedPrimitive);
297
+ }
298
+ }
299
+ return search.join("&");
300
+ };
301
+ return querySerializer;
302
+ };
31
303
  /**
32
- * Renderer-agnostic event tracker for Disco recommendation surfaces.
33
- *
34
- * Owns:
35
- * - the dedup set (so repeated display/view events for the same brand
36
- * don't get re-sent within a session)
37
- * - the network call to the partner-events endpoint
38
- * - payload formatting (snake_case keys, BE-friendly datetime)
39
- *
40
- * Does not know about React. Wrap it in a Provider (`@disconetwork/react`'s
41
- * `DiscoProvider`) when consuming from a React tree, or instantiate it
42
- * directly from any other JS environment.
43
- *
44
- * `track` is implemented as an instance-bound arrow function so consumers
45
- * can safely destructure it without losing `this`.
304
+ * Infers parseAs value from provided Content-Type header.
46
305
  */
47
- var TrackingManager = class {
48
- #endpoint;
49
- #sessionId;
50
- #fetch;
51
- #dedupe = /* @__PURE__ */ new Set();
52
- constructor(config) {
53
- this.#endpoint = ENV_ENDPOINTS[config.env].trackingEndpoint;
54
- this.#sessionId = config.sessionId;
55
- this.#fetch = config.fetch ?? globalThis.fetch.bind(globalThis);
306
+ const getParseAs = (contentType) => {
307
+ if (!contentType) return "stream";
308
+ const cleanContent = contentType.split(";")[0]?.trim();
309
+ if (!cleanContent) return;
310
+ if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) return "json";
311
+ if (cleanContent === "multipart/form-data") return "formData";
312
+ if ([
313
+ "application/",
314
+ "audio/",
315
+ "image/",
316
+ "video/"
317
+ ].some((type) => cleanContent.startsWith(type))) return "blob";
318
+ if (cleanContent.startsWith("text/")) return "text";
319
+ };
320
+ const checkForExistence = (options, name) => {
321
+ if (!name) return false;
322
+ if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) return true;
323
+ return false;
324
+ };
325
+ async function setAuthParams(options) {
326
+ for (const auth of options.security ?? []) {
327
+ if (checkForExistence(options, auth.name)) continue;
328
+ const token = await getAuthToken(auth, options.auth);
329
+ if (!token) continue;
330
+ const name = auth.name ?? "Authorization";
331
+ switch (auth.in) {
332
+ case "query":
333
+ if (!options.query) options.query = {};
334
+ options.query[name] = token;
335
+ break;
336
+ case "cookie":
337
+ options.headers.append("Cookie", `${name}=${token}`);
338
+ break;
339
+ default:
340
+ options.headers.set(name, token);
341
+ break;
342
+ }
56
343
  }
57
- /**
58
- * Send a tracking event. Fire-and-forget — never throws.
59
- * Failures are logged via `console.error`.
60
- *
61
- * Idempotency: `WIDGET_DISPLAY`, `WIDGET_VIEW`, `BRAND_DISPLAY`, and
62
- * `BRAND_VIEW` are deduped per-instance by (event type, insertionId).
63
- */
64
- track = (event) => {
65
- if (this.#isDeduped(event)) return;
66
- this.#fetch(this.#endpoint, {
67
- method: "POST",
68
- headers: { "Content-Type": "application/json" },
69
- body: JSON.stringify(this.#toBody(event))
70
- }).catch((error) => {
71
- console.error("Event tracking failed:", error);
72
- });
344
+ }
345
+ const buildUrl = (options) => getUrl({
346
+ baseUrl: options.baseUrl,
347
+ path: options.path,
348
+ query: options.query,
349
+ querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer),
350
+ url: options.url
351
+ });
352
+ const mergeConfigs = (a, b) => {
353
+ const config = {
354
+ ...a,
355
+ ...b
73
356
  };
74
- #isDeduped(event) {
75
- if (event.type === "WIDGET_DISPLAY" || event.type === "WIDGET_VIEW" || event.type === "BRAND_DISPLAY" || event.type === "BRAND_VIEW") {
76
- const key = event.type + ("brand" in event ? event.brand.insertionId : "widget");
77
- if (this.#dedupe.has(key)) return true;
78
- this.#dedupe.add(key);
357
+ if (config.baseUrl?.endsWith("/")) config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
358
+ config.headers = mergeHeaders(a.headers, b.headers);
359
+ return config;
360
+ };
361
+ const headersEntries = (headers) => {
362
+ const entries = [];
363
+ headers.forEach((value, key) => {
364
+ entries.push([key, value]);
365
+ });
366
+ return entries;
367
+ };
368
+ const mergeHeaders = (...headers) => {
369
+ const mergedHeaders = new Headers();
370
+ for (const header of headers) {
371
+ if (!header) continue;
372
+ const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
373
+ for (const [key, value] of iterator) if (value === null) mergedHeaders.delete(key);
374
+ else if (Array.isArray(value)) for (const v of value) mergedHeaders.append(key, v);
375
+ else if (value !== void 0) mergedHeaders.set(key, typeof value === "object" ? JSON.stringify(value) : value);
376
+ }
377
+ return mergedHeaders;
378
+ };
379
+ var Interceptors = class {
380
+ fns = [];
381
+ clear() {
382
+ this.fns = [];
383
+ }
384
+ eject(id) {
385
+ const index = this.getInterceptorIndex(id);
386
+ if (this.fns[index]) this.fns[index] = null;
387
+ }
388
+ exists(id) {
389
+ const index = this.getInterceptorIndex(id);
390
+ return Boolean(this.fns[index]);
391
+ }
392
+ getInterceptorIndex(id) {
393
+ if (typeof id === "number") return this.fns[id] ? id : -1;
394
+ return this.fns.indexOf(id);
395
+ }
396
+ update(id, fn) {
397
+ const index = this.getInterceptorIndex(id);
398
+ if (this.fns[index]) {
399
+ this.fns[index] = fn;
400
+ return id;
79
401
  }
80
402
  return false;
81
403
  }
82
- #toBody(event) {
83
- const commonEventFields = {
84
- session_id: this.#sessionId,
85
- event_name: event.type,
86
- event_datetime: (/* @__PURE__ */ new Date()).toISOString().replace("Z", "+00:00")
404
+ use(fn) {
405
+ this.fns.push(fn);
406
+ return this.fns.length - 1;
407
+ }
408
+ };
409
+ const createInterceptors = () => ({
410
+ error: new Interceptors(),
411
+ request: new Interceptors(),
412
+ response: new Interceptors()
413
+ });
414
+ const defaultQuerySerializer = createQuerySerializer({
415
+ allowReserved: false,
416
+ array: {
417
+ explode: true,
418
+ style: "form"
419
+ },
420
+ object: {
421
+ explode: true,
422
+ style: "deepObject"
423
+ }
424
+ });
425
+ const defaultHeaders = { "Content-Type": "application/json" };
426
+ const createConfig = (override = {}) => ({
427
+ ...jsonBodySerializer,
428
+ headers: defaultHeaders,
429
+ parseAs: "auto",
430
+ querySerializer: defaultQuerySerializer,
431
+ ...override
432
+ });
433
+ //#endregion
434
+ //#region src/api/generated/recommendations/client/client.gen.ts
435
+ const createClient = (config = {}) => {
436
+ let _config = mergeConfigs(createConfig(), config);
437
+ const getConfig = () => ({ ..._config });
438
+ const setConfig = (config) => {
439
+ _config = mergeConfigs(_config, config);
440
+ return getConfig();
441
+ };
442
+ const interceptors = createInterceptors();
443
+ const beforeRequest = async (options) => {
444
+ const opts = {
445
+ ..._config,
446
+ ...options,
447
+ fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
448
+ headers: mergeHeaders(_config.headers, options.headers),
449
+ serializedBody: void 0
87
450
  };
88
- switch (event.type) {
89
- case "BRAND_CLICK":
90
- case "BRAND_DISPLAY":
91
- case "BRAND_VIEW": return {
92
- ...commonEventFields,
93
- brand_properties: brandProperties(event.brand),
94
- initiating_target: event.target
451
+ if (opts.security) await setAuthParams(opts);
452
+ if (opts.requestValidator) await opts.requestValidator(opts);
453
+ if (opts.body !== void 0 && opts.bodySerializer) opts.serializedBody = opts.bodySerializer(opts.body);
454
+ if (opts.body === void 0 || opts.serializedBody === "") opts.headers.delete("Content-Type");
455
+ const resolvedOpts = opts;
456
+ return {
457
+ opts: resolvedOpts,
458
+ url: buildUrl(resolvedOpts)
459
+ };
460
+ };
461
+ const request = async (options) => {
462
+ const throwOnError = options.throwOnError ?? _config.throwOnError;
463
+ const responseStyle = options.responseStyle ?? _config.responseStyle;
464
+ let request;
465
+ let response;
466
+ try {
467
+ const { opts, url } = await beforeRequest(options);
468
+ const requestInit = {
469
+ redirect: "follow",
470
+ ...opts,
471
+ body: getValidRequestBody(opts)
472
+ };
473
+ request = new Request(url, requestInit);
474
+ for (const fn of interceptors.request.fns) if (fn) request = await fn(request, opts);
475
+ const _fetch = opts.fetch;
476
+ response = await _fetch(request);
477
+ for (const fn of interceptors.response.fns) if (fn) response = await fn(response, request, opts);
478
+ const result = {
479
+ request,
480
+ response
95
481
  };
96
- case "ELEMENT_CLICK": return {
97
- ...commonEventFields,
98
- brand_properties: event.brand ? brandProperties(event.brand) : void 0,
99
- initiating_target: event.target
482
+ if (response.ok) {
483
+ const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
484
+ if (response.status === 204 || response.headers.get("Content-Length") === "0") {
485
+ let emptyData;
486
+ switch (parseAs) {
487
+ case "arrayBuffer":
488
+ case "blob":
489
+ case "text":
490
+ emptyData = await response[parseAs]();
491
+ break;
492
+ case "formData":
493
+ emptyData = new FormData();
494
+ break;
495
+ case "stream":
496
+ emptyData = response.body;
497
+ break;
498
+ default:
499
+ emptyData = {};
500
+ break;
501
+ }
502
+ return opts.responseStyle === "data" ? emptyData : {
503
+ data: emptyData,
504
+ ...result
505
+ };
506
+ }
507
+ let data;
508
+ switch (parseAs) {
509
+ case "arrayBuffer":
510
+ case "blob":
511
+ case "formData":
512
+ case "text":
513
+ data = await response[parseAs]();
514
+ break;
515
+ case "json": {
516
+ const text = await response.text();
517
+ data = text ? JSON.parse(text) : {};
518
+ break;
519
+ }
520
+ case "stream": return opts.responseStyle === "data" ? response.body : {
521
+ data: response.body,
522
+ ...result
523
+ };
524
+ }
525
+ if (parseAs === "json") {
526
+ if (opts.responseValidator) await opts.responseValidator(data);
527
+ if (opts.responseTransformer) data = await opts.responseTransformer(data);
528
+ }
529
+ return opts.responseStyle === "data" ? data : {
530
+ data,
531
+ ...result
532
+ };
533
+ }
534
+ const textError = await response.text();
535
+ let jsonError;
536
+ try {
537
+ jsonError = JSON.parse(textError);
538
+ } catch {}
539
+ throw jsonError ?? textError;
540
+ } catch (error) {
541
+ let finalError = error;
542
+ for (const fn of interceptors.error.fns) if (fn) finalError = await fn(finalError, response, request, options);
543
+ finalError = finalError || {};
544
+ if (throwOnError) throw finalError;
545
+ return responseStyle === "data" ? void 0 : {
546
+ error: finalError,
547
+ request,
548
+ response
100
549
  };
101
- default: return commonEventFields;
102
550
  }
103
- }
104
- };
105
- function brandProperties(brand) {
551
+ };
552
+ const makeMethodFn = (method) => (options) => request({
553
+ ...options,
554
+ method
555
+ });
556
+ const makeSseFn = (method) => async (options) => {
557
+ const { opts, url } = await beforeRequest(options);
558
+ return createSseClient({
559
+ ...opts,
560
+ body: opts.body,
561
+ method,
562
+ onRequest: async (url, init) => {
563
+ let request = new Request(url, init);
564
+ for (const fn of interceptors.request.fns) if (fn) request = await fn(request, opts);
565
+ return request;
566
+ },
567
+ serializedBody: getValidRequestBody(opts),
568
+ url
569
+ });
570
+ };
571
+ const _buildUrl = (options) => buildUrl({
572
+ ..._config,
573
+ ...options
574
+ });
106
575
  return {
107
- offer_id: brand.offerId,
108
- advertiser_id: brand.advertiserId,
109
- insertion_id: brand.insertionId
576
+ buildUrl: _buildUrl,
577
+ connect: makeMethodFn("CONNECT"),
578
+ delete: makeMethodFn("DELETE"),
579
+ get: makeMethodFn("GET"),
580
+ getConfig,
581
+ head: makeMethodFn("HEAD"),
582
+ interceptors,
583
+ options: makeMethodFn("OPTIONS"),
584
+ patch: makeMethodFn("PATCH"),
585
+ post: makeMethodFn("POST"),
586
+ put: makeMethodFn("PUT"),
587
+ request,
588
+ setConfig,
589
+ sse: {
590
+ connect: makeSseFn("CONNECT"),
591
+ delete: makeSseFn("DELETE"),
592
+ get: makeSseFn("GET"),
593
+ head: makeSseFn("HEAD"),
594
+ options: makeSseFn("OPTIONS"),
595
+ patch: makeSseFn("PATCH"),
596
+ post: makeSseFn("POST"),
597
+ put: makeSseFn("PUT"),
598
+ trace: makeSseFn("TRACE")
599
+ },
600
+ trace: makeMethodFn("TRACE")
110
601
  };
111
- }
602
+ };
603
+ //#endregion
604
+ //#region src/api/generated/recommendations/client.gen.ts
605
+ const client = createClient(createConfig());
112
606
  //#endregion
113
- //#region src/DiscoClient.ts
607
+ //#region src/api/generated/recommendations/sdk.gen.ts
114
608
  /**
115
- * Thrown by `DiscoClient.getRecommendations` when the server returns a
116
- * non-2xx status. The HTTP status and an optional parsed body are
117
- * preserved for error UIs and retry logic.
609
+ * Recommendations
610
+ *
611
+ * Unified recommendations endpoint.
612
+ *
613
+ * Accepts scoped PUBLIC keys (PUBLISHER or PUBLISHER_CHANNEL link level) and
614
+ * legacy partner API keys. The controller operates in channel mode when the
615
+ * auth context wraps a CmosPublisherContext, direct mode otherwise.
118
616
  */
119
- var DiscoApiError = class extends Error {
120
- status;
121
- statusText;
122
- body;
123
- constructor(message, info) {
124
- super(message);
125
- this.name = "DiscoApiError";
126
- this.status = info.status;
127
- this.statusText = info.statusText;
128
- this.body = info.body;
617
+ const recommendations = (options) => (options.client ?? client).post({
618
+ requestValidator: async (data) => await z.object({
619
+ body: zRecommendationsBody,
620
+ path: z.never().optional(),
621
+ query: z.never().optional()
622
+ }).parseAsync(data),
623
+ responseValidator: async (data) => await zRecommendationsResponse2.parseAsync(data),
624
+ security: [{
625
+ name: "x-api-key",
626
+ type: "apiKey"
627
+ }],
628
+ url: "/recommendations",
629
+ ...options,
630
+ headers: {
631
+ "Content-Type": "application/json",
632
+ ...options.headers
129
633
  }
634
+ });
635
+ //#endregion
636
+ //#region src/api/index.ts
637
+ /**
638
+ * Build a dedicated, per-instance recommendations transport client from an
639
+ * already-resolved base URL and auth headers. This is intentionally a pure
640
+ * transport factory: environment derivation and header construction are the
641
+ * caller's responsibility (see `env.ts` / `config.ts`), so there is a single
642
+ * owner of key → env → config resolution rather than one per client.
643
+ *
644
+ * Pass the returned client to the generated `recommendations()` SDK function
645
+ * via its `client` option, e.g.:
646
+ *
647
+ * ```ts
648
+ * const env = envFromApiKey(apiKey);
649
+ * const client = createRecommendationsClient({
650
+ * baseUrl: GATEWAY_BASE_URL[env],
651
+ * headers: authHeaders({ apiKey }),
652
+ * });
653
+ * await recommendations({ client, body, throwOnError: true });
654
+ * ```
655
+ *
656
+ * A per-instance client (rather than the SDK's shared global singleton) keeps
657
+ * each key's base URL and auth isolated, so multiple clients can coexist.
658
+ */
659
+ function createRecommendationsClient(config) {
660
+ return createClient(createConfig({
661
+ baseUrl: config.baseUrl,
662
+ headers: config.headers,
663
+ ...config.fetch ? { fetch: config.fetch } : {}
664
+ }));
665
+ }
666
+ //#endregion
667
+ //#region src/config.ts
668
+ /**
669
+ * Per-environment base URL for the partners API gateway. Both the
670
+ * recommendations and events services sit behind this single origin, routed by
671
+ * path. This is the gateway **root** — callers/SDKs append the operation path
672
+ * (`/recommendations`, `/events`), so it must not be included here.
673
+ *
674
+ * Single source of truth for the external gateway hostnames; consumers
675
+ * ({@link DiscoClient}, the generated recommendations client) derive their URLs
676
+ * from this rather than hard-coding their own.
677
+ */
678
+ const GATEWAY_BASE_URL = {
679
+ production: "https://partners.disconetwork.com",
680
+ staging: "https://partners.disconetwork-staging.com"
130
681
  };
131
682
  /**
132
- * Typed client for the Disco recommendations API.
683
+ * Default value for the required `X-API-Version` header. Overridable per client
684
+ * via `apiVersion`.
685
+ */
686
+ const DEFAULT_API_VERSION = "1.0.0";
687
+ /**
688
+ * Build the auth headers the partners gateway requires from a scoped public API
689
+ * key. The `X-API-Version` defaults to {@link DEFAULT_API_VERSION}.
690
+ */
691
+ function authHeaders(config) {
692
+ return {
693
+ "x-api-key": config.apiKey,
694
+ "X-API-Version": config.apiVersion ?? DEFAULT_API_VERSION
695
+ };
696
+ }
697
+ //#endregion
698
+ //#region src/external/DiscoClient.ts
699
+ /**
700
+ * Typed client for the Disco recommendations API — calls
701
+ * `disco-recommendations-api` **directly** (no proxy) at
702
+ * `partners.disconetwork(-staging).com/recommendations`.
703
+ *
704
+ * This is the recommended, partner-facing client. It maps the friendly
705
+ * camelCase request into the rec-api wire body (sending `x-api-key` +
706
+ * `X-API-Version`) and recases the response into camelCase.
707
+ * Validation is performed by the generated SDK. The wire
708
+ * format is fully encapsulated.
133
709
  *
134
- * Renderer-agnostic: this class makes plain HTTP calls and has no
135
- * React dependency. Wrap it in a Provider (`@disconetwork/react`'s
136
- * `DiscoProvider`) for use from a React tree, or instantiate it
137
- * directly from server code, scripts, or tests.
710
+ * Renderer-agnostic: plain HTTP, no React dependency.
138
711
  */
139
712
  var DiscoClient = class {
140
- #env;
141
- #url;
142
- #headers;
713
+ #recommendationsClient;
714
+ #eventsUrl;
715
+ #apiKey;
143
716
  #fetch;
144
717
  constructor(config) {
718
+ const env = envFromApiKey(config.apiKey);
719
+ this.#apiKey = config.apiKey;
720
+ this.#eventsUrl = `${GATEWAY_BASE_URL[env]}/events`;
145
721
  this.#fetch = config.fetch ?? globalThis.fetch.bind(globalThis);
146
- if ("apiKey" in config) {
147
- this.#env = envFromApiKey(config.apiKey);
148
- this.#url = `${ENV_ENDPOINTS[this.#env].apiBaseUrl}/core/recommendations/`;
149
- this.#headers = {
150
- "x-api-key": config.apiKey,
151
- "Content-Type": "application/json"
152
- };
153
- } else {
154
- this.#env = config.env;
155
- const shopId = stripShopGid(config.shopGid);
156
- this.#url = `${ENV_ENDPOINTS[this.#env].apiBaseUrl}/core/recommendations/shop_gid/${encodeURIComponent(shopId)}/`;
157
- this.#headers = { "Content-Type": "application/json" };
158
- }
722
+ this.#recommendationsClient = createRecommendationsClient({
723
+ baseUrl: GATEWAY_BASE_URL[env],
724
+ headers: authHeaders(config),
725
+ fetch: this.#fetch
726
+ });
159
727
  }
160
728
  /**
161
- * POST the recommendations endpoint and return the backend's response
162
- * **verbatim** — this reflects `ExternalAPIRecommendationView` with no
163
- * transformation. Pass the result through `mapRecommendationsResponse`
164
- * if you want the friendly denormalized `RecommendationsResponse`.
729
+ * Fetch recommendations for the given request.
165
730
  *
166
- * Throws `DiscoApiError` on non-2xx responses; other failures
167
- * (network, parse) propagate as-is.
731
+ * Maps the request to the wire body, POSTs it, then recases the response to
732
+ * camelCase (keeping the API's normalized shape). The generated SDK validates
733
+ * both sides. Throws `DiscoValidationError` on a request/response schema
734
+ * failure, `DiscoApiError` on a non-2xx response, and `DiscoNetworkError` if
735
+ * the request can't reach the server. An aborted request rejects with the
736
+ * native `AbortError`.
168
737
  */
169
738
  getRecommendations = async (request, options) => {
170
- const response = await this.#fetch(this.#url, {
171
- method: "POST",
172
- headers: this.#headers,
173
- body: JSON.stringify(toRequestBody(request)),
739
+ const result = await recommendations({
740
+ client: this.#recommendationsClient,
741
+ body: transformRequest(request),
174
742
  signal: options?.signal
175
743
  });
176
- if (!response.ok) {
177
- const body = await safeReadBody(response);
178
- throw new DiscoApiError(`Recommendations request failed: ${response.status} ${response.statusText}`, {
179
- status: response.status,
180
- statusText: response.statusText,
181
- body
182
- });
744
+ if (result.response && !result.response.ok) throw new DiscoApiError(`Recommendations request failed: ${result.response.status} ${result.response.statusText}`, {
745
+ status: result.response.status,
746
+ statusText: result.response.statusText,
747
+ body: result.error
748
+ });
749
+ if (result.error) {
750
+ if (result.error instanceof ZodError) throw new DiscoValidationError("Failed to validate recommendations payload", result.error, result.data);
751
+ if (isAbortError(result.error)) throw result.error;
752
+ throw new DiscoNetworkError("Recommendations request failed to reach the server", result.error);
183
753
  }
184
- return await response.json();
754
+ return transformResponse(result.data);
185
755
  };
186
756
  /**
187
- * Fetch recommendations and create a session-bound tracker in one call.
188
- *
189
- * Composition convenience over `getRecommendations` + `createTrackingManager`:
190
- * it derives the tracker's session from the response so callers don't have to
191
- * thread `session_id` through themselves (and can't bind a tracker to the
192
- * wrong session). The returned `data` is the **raw** response — call
193
- * `mapRecommendationsResponse` on it if you want the friendly shape.
194
- *
195
- * Throws `DiscoApiError` on non-2xx responses, same as `getRecommendations`.
757
+ * Fetch recommendations and create a session-bound events tracker in one
758
+ * call. The tracker inherits this client's API key and environment.
196
759
  */
197
760
  getRecommendationsWithTracker = async (request, options) => {
198
761
  const data = await this.getRecommendations(request, { signal: options?.signal });
199
762
  return {
200
763
  data,
201
- tracker: this.createTrackingManager({ sessionId: data.session_id }, { fetch: options?.fetch })
764
+ tracker: this.createTrackingManager(data.sessionId, { fetch: options?.fetch })
202
765
  };
203
766
  };
204
767
  /**
205
- * Create an event tracker for a recommendations response from this client.
206
- *
207
- * The tracker uses the same API-key-derived environment as the
208
- * recommendations call, so sandbox recommendations cannot accidentally emit
209
- * production tracking events.
768
+ * Create an events tracker bound to a recommendations session (the
769
+ * `sessionId` from a `getRecommendations` response). Posts to the external
770
+ * `/events` endpoint with this client's `x-api-key`.
210
771
  */
211
- createTrackingManager = (recommendations, options) => new TrackingManager({
212
- sessionId: recommendations.sessionId,
213
- env: this.#env,
772
+ createTrackingManager = (sessionId, options) => new TrackingManager({
773
+ sessionId,
774
+ endpoint: this.#eventsUrl,
775
+ headers: { "x-api-key": this.#apiKey },
214
776
  fetch: options?.fetch ?? this.#fetch
215
777
  });
216
778
  };
217
- function stripShopGid(shopGid) {
218
- return shopGid.replace("gid://shopify/Shop/", "");
219
- }
220
- function toRequestBody(req) {
221
- return {
222
- recommendations_data: {
223
- user_details: req.user && {
224
- email: req.user.email,
225
- first_name: req.user.firstName,
226
- last_name: req.user.lastName,
227
- phone: req.user.phone
228
- },
229
- placement_details: req.placement && {
230
- display_mode: req.placement.displayMode,
231
- view: req.placement.view
232
- },
233
- order_details: req.order && {
234
- order_id: req.order.id,
235
- cost_details: req.order.amount !== void 0 || req.order.currencyCode !== void 0 ? {
236
- amount: req.order.amount,
237
- currency_code: req.order.currencyCode
238
- } : void 0
239
- },
240
- purchases: req.purchases?.map((p) => ({
241
- name: p.name,
242
- type: p.type,
243
- variant: p.variant,
244
- quantity: p.quantity,
245
- product_id: p.productId,
246
- cost_details: p.amount !== void 0 || p.currencyCode !== void 0 ? {
247
- amount: p.amount,
248
- currency_code: p.currencyCode
249
- } : void 0
250
- }))
251
- },
252
- running_experiments: req.experiments?.map((e) => ({
253
- id: e.id,
254
- variant: e.variant
255
- })),
256
- attributes: req.attributes,
257
- ...req.extras
258
- };
259
- }
260
- async function safeReadBody(response) {
261
- try {
262
- return await response.clone().json();
263
- } catch {
264
- try {
265
- return await response.text();
266
- } catch {
267
- return;
268
- }
269
- }
270
- }
271
- //#endregion
272
- //#region src/recommendationsMapper.ts
273
- /**
274
- * Denormalize a raw recommendations response into the public
275
- * `RecommendationsResponse`: join group entries → recommendations by offer id,
276
- * order groups by the numeric suffix of their key (group_0, group_1, …), and
277
- * convert snake_case to camelCase.
278
- *
279
- * Pure and side-effect-free — call it on the result of
280
- * `DiscoClient.getRecommendations` when you want the friendly shape.
281
- */
282
- function mapRecommendationsResponse(raw) {
283
- const recommendations = raw.recommendations ?? {};
284
- const groupEntries = raw.recommendation_groups ?? {};
285
- const groupProps = raw.recommendation_group_properties ?? {};
286
- const orderedKeys = Object.keys(groupEntries).sort((a, b) => numericSuffix(a) - numericSuffix(b));
287
- const recommendationGroups = [];
288
- for (const key of orderedKeys) {
289
- const entries = groupEntries[key];
290
- const props = groupProps[key];
291
- if (!entries || !props) continue;
292
- const recs = [];
293
- for (const entry of entries) {
294
- const rawRec = recommendations[entry.offer_id];
295
- if (!rawRec) continue;
296
- recs.push({
297
- id: rawRec.offer.id,
298
- insertionId: entry.insertion_id,
299
- advertiser: mapAdvertiser(rawRec.advertiser),
300
- offer: mapOffer(rawRec.offer)
301
- });
302
- }
303
- recommendationGroups.push({
304
- heading: props.heading ?? null,
305
- slotContext: props.slot_context,
306
- recommendations: recs
307
- });
308
- }
309
- return {
310
- sessionId: raw.session_id,
311
- layoutId: raw.layout_id,
312
- recommendationGroups,
313
- footer: mapFooter(raw.footer),
314
- publisherCustomization: raw.publisher_customization ?? null
315
- };
316
- }
317
- function numericSuffix(value) {
318
- const suffix = value.split("_").pop() ?? "";
319
- const parsed = Number.parseInt(suffix, 10);
320
- return Number.isNaN(parsed) ? Number.POSITIVE_INFINITY : parsed;
321
- }
322
- function mapAdvertiser(raw) {
323
- return {
324
- id: raw.id,
325
- name: raw.name,
326
- logoUrl: raw.logo_url,
327
- description: raw.description ?? null
328
- };
329
- }
330
- function mapOffer(raw) {
331
- return {
332
- id: raw.id,
333
- heading: raw.heading ?? null,
334
- subheading: raw.subheading ?? null,
335
- jsonContent: raw.json_content ?? null,
336
- targetUrl: raw.target_url,
337
- ctaDetails: mapCtaDetails(raw.cta_details),
338
- assets: (raw.assets ?? []).map(mapAsset),
339
- metadata: raw.metadata ?? null,
340
- disclosureDetails: raw.disclosure_details ?? null
341
- };
342
- }
343
- function mapCtaDetails(raw) {
344
- return {
345
- acceptCopy: raw.accept_copy,
346
- declineCopy: raw.decline_copy,
347
- transitionCopy: raw.transition_copy ?? null
348
- };
349
- }
350
- function mapAsset(raw) {
351
- return {
352
- id: raw.id,
353
- imageUrl: raw.image_url,
354
- targetUrl: raw.target_url ?? null
355
- };
356
- }
357
- function mapFooter(raw) {
358
- return {
359
- attributionDetails: {
360
- copy: raw.attribution_details.copy,
361
- discoLogoUrl: raw.attribution_details.disco_logo_url,
362
- targetUrl: raw.attribution_details.target_url
363
- },
364
- privacyPolicy: {
365
- copy: raw.privacy_policy.copy,
366
- targetUrl: raw.privacy_policy.target_url
367
- }
368
- };
369
- }
370
779
  //#endregion
371
- export { DiscoApiError, DiscoClient, envFromApiKey, mapRecommendationsResponse };
780
+ export { DiscoApiError, DiscoClient, DiscoError, DiscoNetworkError, DiscoValidationError };
372
781
 
373
782
  //# sourceMappingURL=index.js.map