@contentful/optimization-api-client 0.1.0-alpha

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 (63) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +282 -0
  3. package/dist/ApiClient.d.ts +74 -0
  4. package/dist/ApiClient.d.ts.map +1 -0
  5. package/dist/ApiClient.js +61 -0
  6. package/dist/ApiClient.js.map +1 -0
  7. package/dist/ApiClientBase.d.ts +113 -0
  8. package/dist/ApiClientBase.d.ts.map +1 -0
  9. package/dist/ApiClientBase.js +94 -0
  10. package/dist/ApiClientBase.js.map +1 -0
  11. package/dist/builders/EventBuilder.d.ts +589 -0
  12. package/dist/builders/EventBuilder.d.ts.map +1 -0
  13. package/dist/builders/EventBuilder.js +349 -0
  14. package/dist/builders/EventBuilder.js.map +1 -0
  15. package/dist/builders/index.d.ts +3 -0
  16. package/dist/builders/index.d.ts.map +1 -0
  17. package/dist/builders/index.js +3 -0
  18. package/dist/builders/index.js.map +1 -0
  19. package/dist/experience/ExperienceApiClient.d.ts +267 -0
  20. package/dist/experience/ExperienceApiClient.d.ts.map +1 -0
  21. package/dist/experience/ExperienceApiClient.js +324 -0
  22. package/dist/experience/ExperienceApiClient.js.map +1 -0
  23. package/dist/experience/index.d.ts +4 -0
  24. package/dist/experience/index.d.ts.map +1 -0
  25. package/dist/experience/index.js +4 -0
  26. package/dist/experience/index.js.map +1 -0
  27. package/dist/fetch/Fetch.d.ts +96 -0
  28. package/dist/fetch/Fetch.d.ts.map +1 -0
  29. package/dist/fetch/Fetch.js +27 -0
  30. package/dist/fetch/Fetch.js.map +1 -0
  31. package/dist/fetch/createProtectedFetchMethod.d.ts +40 -0
  32. package/dist/fetch/createProtectedFetchMethod.d.ts.map +1 -0
  33. package/dist/fetch/createProtectedFetchMethod.js +53 -0
  34. package/dist/fetch/createProtectedFetchMethod.js.map +1 -0
  35. package/dist/fetch/createRetryFetchMethod.d.ts +60 -0
  36. package/dist/fetch/createRetryFetchMethod.d.ts.map +1 -0
  37. package/dist/fetch/createRetryFetchMethod.js +138 -0
  38. package/dist/fetch/createRetryFetchMethod.js.map +1 -0
  39. package/dist/fetch/createTimeoutFetchMethod.d.ts +51 -0
  40. package/dist/fetch/createTimeoutFetchMethod.d.ts.map +1 -0
  41. package/dist/fetch/createTimeoutFetchMethod.js +51 -0
  42. package/dist/fetch/createTimeoutFetchMethod.js.map +1 -0
  43. package/dist/fetch/index.d.ts +7 -0
  44. package/dist/fetch/index.d.ts.map +1 -0
  45. package/dist/fetch/index.js +7 -0
  46. package/dist/fetch/index.js.map +1 -0
  47. package/dist/index.cjs +708 -0
  48. package/dist/index.cjs.map +1 -0
  49. package/dist/index.d.ts +8 -0
  50. package/dist/index.d.ts.map +1 -0
  51. package/dist/index.js +8 -0
  52. package/dist/index.js.map +1 -0
  53. package/dist/index.mjs +583 -0
  54. package/dist/index.mjs.map +1 -0
  55. package/dist/insights/InsightsApiClient.d.ts +130 -0
  56. package/dist/insights/InsightsApiClient.d.ts.map +1 -0
  57. package/dist/insights/InsightsApiClient.js +142 -0
  58. package/dist/insights/InsightsApiClient.js.map +1 -0
  59. package/dist/insights/index.d.ts +4 -0
  60. package/dist/insights/index.d.ts.map +1 -0
  61. package/dist/insights/index.js +4 -0
  62. package/dist/insights/index.js.map +1 -0
  63. package/package.json +27 -0
@@ -0,0 +1,349 @@
1
+ import { Campaign, GeoLocation, Page, PageEventContext, Properties, Screen, ScreenEventContext, Traits, } from '@contentful/optimization-api-schemas';
2
+ import { merge } from 'es-toolkit';
3
+ import * as z from 'zod/mini';
4
+ const UniversalEventBuilderArgs = z.object({
5
+ campaign: z.optional(Campaign),
6
+ locale: z.optional(z.string()),
7
+ location: z.optional(GeoLocation),
8
+ page: z.optional(Page),
9
+ screen: z.optional(Screen),
10
+ userAgent: z.optional(z.string()),
11
+ });
12
+ const ComponentViewBuilderArgs = z.extend(UniversalEventBuilderArgs, {
13
+ componentId: z.string(),
14
+ experienceId: z.optional(z.string()),
15
+ variantIndex: z.optional(z.number()),
16
+ sticky: z.optional(z.boolean()),
17
+ });
18
+ const IdentifyBuilderArgs = z.extend(UniversalEventBuilderArgs, {
19
+ traits: z.optional(Traits),
20
+ userId: z.string(),
21
+ });
22
+ const PageViewBuilderArgs = z.extend(UniversalEventBuilderArgs, {
23
+ properties: z.optional(z.partial(Page)),
24
+ });
25
+ const ScreenViewBuilderArgs = z.extend(UniversalEventBuilderArgs, {
26
+ name: z.string(),
27
+ properties: Properties,
28
+ });
29
+ const TrackBuilderArgs = z.extend(UniversalEventBuilderArgs, {
30
+ event: z.string(),
31
+ properties: z.optional(z.prefault(Properties, {})),
32
+ });
33
+ /**
34
+ * Default page properties used when no explicit page information is available.
35
+ *
36
+ * @public
37
+ *
38
+ * @defaultValue
39
+ * ```ts
40
+ * {
41
+ * path: '',
42
+ * query: {},
43
+ * referrer: '',
44
+ * search: '',
45
+ * title: '',
46
+ * url: '',
47
+ * }
48
+ * ```
49
+ *
50
+ * @remarks
51
+ * Values are required by the API; values may not be `undefined`. Empty values are valid.
52
+ */
53
+ export const DEFAULT_PAGE_PROPERTIES = {
54
+ path: '',
55
+ query: {},
56
+ referrer: '',
57
+ search: '',
58
+ title: '',
59
+ url: '',
60
+ };
61
+ /**
62
+ * Internal helper class for building analytics and personalization events.
63
+ *
64
+ * @remarks
65
+ * This class coordinates configuration and argument validation to produce
66
+ * strongly-typed event payloads compatible with
67
+ * `@contentful/optimization-api-schemas`.
68
+ *
69
+ * @public
70
+ */
71
+ class EventBuilder {
72
+ /**
73
+ * Application metadata attached to each event.
74
+ *
75
+ * @internal
76
+ */
77
+ app;
78
+ /**
79
+ * Channel value attached to each event.
80
+ *
81
+ * @internal
82
+ */
83
+ channel;
84
+ /**
85
+ * Library metadata attached to each event.
86
+ *
87
+ * @internal
88
+ */
89
+ library;
90
+ /**
91
+ * Function that provides the locale when available.
92
+ *
93
+ * @internal
94
+ */
95
+ getLocale;
96
+ /**
97
+ * Function that provides baseline page properties.
98
+ *
99
+ * @internal
100
+ */
101
+ getPageProperties;
102
+ /**
103
+ * Function that provides the user agent string when available.
104
+ *
105
+ * @internal
106
+ */
107
+ getUserAgent;
108
+ /**
109
+ * Creates a new {@link EventBuilder} instance.
110
+ *
111
+ * @param config - Configuration used to customize event payloads.
112
+ *
113
+ * @internal
114
+ * @remarks
115
+ * Callers are expected to reuse a single instance when possible to avoid
116
+ * repeatedly reconfiguring the builder.
117
+ *
118
+ * @example
119
+ * ```ts
120
+ * const builder = new EventBuilder({
121
+ * channel: 'web',
122
+ * library: { name: '@contentful/optimization-sdk', version: '1.0.0' },
123
+ * })
124
+ * ```
125
+ */
126
+ constructor(config) {
127
+ const { app, channel, library, getLocale, getPageProperties, getUserAgent } = config;
128
+ this.app = app;
129
+ this.channel = channel;
130
+ this.library = library;
131
+ this.getLocale = getLocale ?? (() => 'en-US');
132
+ this.getPageProperties = getPageProperties ?? (() => DEFAULT_PAGE_PROPERTIES);
133
+ this.getUserAgent = getUserAgent ?? (() => undefined);
134
+ }
135
+ /**
136
+ * Builds the universal event properties shared across all event types.
137
+ *
138
+ * @param args - Arguments overriding the default context values.
139
+ * @returns A fully populated {@link UniversalEventProperties} object.
140
+ *
141
+ * @protected
142
+ *
143
+ * @remarks
144
+ * This method is used internally by the specific event-builder methods
145
+ * (e.g. {@link EventBuilder.buildPageView}).
146
+ */
147
+ buildUniversalEventProperties({ campaign = {}, locale, location, page, screen, userAgent, }) {
148
+ const timestamp = new Date().toISOString();
149
+ return {
150
+ channel: this.channel,
151
+ context: {
152
+ app: this.app,
153
+ campaign,
154
+ gdpr: { isConsentGiven: true },
155
+ library: this.library,
156
+ locale: locale ?? this.getLocale() ?? 'en-US',
157
+ location,
158
+ page: page ?? this.getPageProperties(),
159
+ screen,
160
+ userAgent: userAgent ?? this.getUserAgent(),
161
+ },
162
+ messageId: crypto.randomUUID(),
163
+ originalTimestamp: timestamp,
164
+ sentAt: timestamp,
165
+ timestamp,
166
+ };
167
+ }
168
+ /**
169
+ * Builds a component view event payload for a Contentful entry-based component.
170
+ *
171
+ * @param args - {@link ComponentViewBuilderArgs} arguments describing the component view.
172
+ * @returns A {@link ComponentViewEvent} describing the view.
173
+ *
174
+ * @public
175
+ *
176
+ * @example
177
+ * ```ts
178
+ * const event = builder.buildComponentView({
179
+ * componentId: 'entry-123',
180
+ * experienceId: 'personalization-123',
181
+ * variantIndex: 1,
182
+ * })
183
+ * ```
184
+ */
185
+ buildComponentView(args) {
186
+ const { componentId, experienceId, variantIndex, ...universal } = ComponentViewBuilderArgs.parse(args);
187
+ return {
188
+ ...this.buildUniversalEventProperties(universal),
189
+ type: 'component',
190
+ componentType: 'Entry',
191
+ componentId,
192
+ experienceId,
193
+ variantIndex: variantIndex ?? 0,
194
+ };
195
+ }
196
+ /**
197
+ * Builds a component view event payload for a Custom Flag component.
198
+ *
199
+ * @param args - {@link ComponentViewBuilderArgs} arguments describing the Custom Flag view.
200
+ * @returns A {@link ComponentViewEvent} describing the view.
201
+ *
202
+ * @public
203
+ *
204
+ * @remarks
205
+ * This is a specialized variant of {@link EventBuilder.buildComponentView}
206
+ * that sets `componentType` to `'Variable'`.
207
+ *
208
+ * @example
209
+ * ```ts
210
+ * const event = builder.buildFlagView({
211
+ * componentId: 'feature-flag-key',
212
+ * experienceId: 'personalization-123',
213
+ * })
214
+ * ```
215
+ */
216
+ buildFlagView(args) {
217
+ return {
218
+ ...this.buildComponentView(args),
219
+ componentType: 'Variable',
220
+ };
221
+ }
222
+ /**
223
+ * Builds an identify event payload to associate a user ID with traits.
224
+ *
225
+ * @param args - {@link IdentifyBuilderArgs} arguments describing the identified user.
226
+ * @returns An {@link IdentifyEvent} payload.
227
+ *
228
+ * @public
229
+ *
230
+ * @remarks
231
+ * - Traits are merged by the API; only specified properties may be overwritten.
232
+ * - The User ID is consumer-specified and should not contain the value of any
233
+ * ID generated by the Experience API.
234
+ *
235
+ * @example
236
+ * ```ts
237
+ * const event = builder.buildIdentify({
238
+ * userId: 'user-123',
239
+ * traits: { plan: 'pro' },
240
+ * })
241
+ * ```
242
+ */
243
+ buildIdentify(args) {
244
+ const { traits = {}, userId, ...universal } = IdentifyBuilderArgs.parse(args);
245
+ return {
246
+ ...this.buildUniversalEventProperties(universal),
247
+ type: 'identify',
248
+ traits,
249
+ userId,
250
+ };
251
+ }
252
+ /**
253
+ * Builds a page view event payload.
254
+ *
255
+ * @param args - Optional {@link PageViewBuilderArgs} overrides for the page view event.
256
+ * @returns A {@link PageViewEvent} payload.
257
+ *
258
+ * @public
259
+ *
260
+ * @remarks
261
+ * Page properties are created by merging:
262
+ * 1. The base page properties from {@link EventBuilderConfig.getPageProperties}, and
263
+ * 2. The partial `properties` argument passed in.
264
+ *
265
+ * The title always falls back to {@link DEFAULT_PAGE_PROPERTIES}.title when undefined.
266
+ *
267
+ * @example
268
+ * ```ts
269
+ * const event = builder.buildPageView({
270
+ * properties: {
271
+ * title: 'Homepage',
272
+ * },
273
+ * })
274
+ * ```
275
+ */
276
+ buildPageView(args = {}) {
277
+ const { properties = {}, ...universal } = PageViewBuilderArgs.parse(args);
278
+ const pageProperties = this.getPageProperties();
279
+ const merged = merge({
280
+ ...pageProperties,
281
+ title: pageProperties.title ?? DEFAULT_PAGE_PROPERTIES.title,
282
+ }, properties);
283
+ const { context: { screen: _, ...universalContext }, ...universalProperties } = this.buildUniversalEventProperties(universal);
284
+ const context = PageEventContext.parse(universalContext);
285
+ return {
286
+ ...universalProperties,
287
+ context,
288
+ type: 'page',
289
+ properties: merged,
290
+ };
291
+ }
292
+ /**
293
+ * Builds a screen view event payload.
294
+ *
295
+ * @param args - {@link ScreenViewBuilderArgs} arguments for the screen view event.
296
+ * @returns A {@link ScreenViewEvent} payload.
297
+ *
298
+ * @public
299
+ *
300
+ * @example
301
+ * ```ts
302
+ * const event = builder.buildScreenView({
303
+ * name: 'home',
304
+ * properties: {
305
+ * title: 'Home Screen',
306
+ * },
307
+ * })
308
+ * ```
309
+ */
310
+ buildScreenView(args) {
311
+ const { name, properties, ...universal } = ScreenViewBuilderArgs.parse(args);
312
+ const { context: { page: _, ...universalContext }, ...universalProperties } = this.buildUniversalEventProperties(universal);
313
+ const context = ScreenEventContext.parse(universalContext);
314
+ return {
315
+ ...universalProperties,
316
+ context,
317
+ type: 'screen',
318
+ name,
319
+ properties,
320
+ };
321
+ }
322
+ /**
323
+ * Builds a track event payload for arbitrary user actions.
324
+ *
325
+ * @param args - {@link TrackBuilderArgs} arguments describing the tracked event.
326
+ * @returns A {@link TrackEvent} payload.
327
+ *
328
+ * @public
329
+ *
330
+ * @example
331
+ * ```ts
332
+ * const event = builder.buildTrack({
333
+ * event: 'button_clicked',
334
+ * properties: { id: 'primary-cta', location: 'hero' },
335
+ * })
336
+ * ```
337
+ */
338
+ buildTrack(args) {
339
+ const { event, properties = {}, ...universal } = TrackBuilderArgs.parse(args);
340
+ return {
341
+ ...this.buildUniversalEventProperties(universal),
342
+ type: 'track',
343
+ event,
344
+ properties,
345
+ };
346
+ }
347
+ }
348
+ export default EventBuilder;
349
+ //# sourceMappingURL=EventBuilder.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"EventBuilder.js","sourceRoot":"","sources":["../../src/builders/EventBuilder.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,QAAQ,EAGR,WAAW,EAGX,IAAI,EACJ,gBAAgB,EAEhB,UAAU,EACV,MAAM,EACN,kBAAkB,EAGlB,MAAM,GAEP,MAAM,sCAAsC,CAAA;AAC7C,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAA;AAClC,OAAO,KAAK,CAAC,MAAM,UAAU,CAAA;AAqF7B,MAAM,yBAAyB,GAAG,CAAC,CAAC,MAAM,CAAC;IACzC,QAAQ,EAAE,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC;IAC9B,MAAM,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC;IAC9B,QAAQ,EAAE,CAAC,CAAC,QAAQ,CAAC,WAAW,C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AC,SAAS,CAAC,CAAA;QAEjD,MAAM,OAAO,GAAG,kBAAkB,CAAC,KAAK,CAAC,gBAAgB,CAAC,CAAA;QAE1D,OAAO;YACL,GAAG,mBAAmB;YACtB,OAAO;YACP,IAAI,EAAE,QAAQ;YACd,IAAI;YACJ,UAAU;SACX,CAAA;IACH,CAAC;IAED;;;;;;;;;;;;;;;OAeG;IACH,UAAU,CAAC,IAAsB;QAC/B,MAAM,EAAE,KAAK,EAAE,UAAU,GAAG,EAAE,EAAE,GAAG,SAAS,EAAE,GAAG,gBAAgB,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;QAE7E,OAAO;YACL,GAAG,IAAI,CAAC,6BAA6B,CAAC,SAAS,CAAC;YAChD,IAAI,EAAE,OAAO;YACb,KAAK;YACL,UAAU;SACX,CAAA;IACH,CAAC;CACF;AAED,eAAe,YAAY,CAAA"}
@@ -0,0 +1,3 @@
1
+ export * from './EventBuilder';
2
+ export { default as EventBuilder } from './EventBuilder';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/builders/index.ts"],"names":[],"mappings":"AAAA,cAAc,gBAAgB,CAAA;AAE9B,OAAO,EAAE,OAAO,IAAI,YAAY,EAAE,MAAM,gBAAgB,CAAA"}
@@ -0,0 +1,3 @@
1
+ export * from './EventBuilder';
2
+ export { default as EventBuilder } from './EventBuilder';
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/builders/index.ts"],"names":[],"mappings":"AAAA,cAAc,gBAAgB,CAAA;AAE9B,OAAO,EAAE,OAAO,IAAI,YAAY,EAAE,MAAM,gBAAgB,CAAA"}
@@ -0,0 +1,267 @@
1
+ import { ExperienceEventArray, type BatchExperienceData, type BatchExperienceEventArray, type OptimizationData } from '@contentful/optimization-api-schemas';
2
+ import ApiClientBase, { type ApiConfig } from '../ApiClientBase';
3
+ /**
4
+ * Default base URL for the Experience API.
5
+ *
6
+ * @public
7
+ */
8
+ export declare const EXPERIENCE_BASE_URL = "https://experience.ninetailed.co/";
9
+ /**
10
+ * Feature flags supported by the Experience API.
11
+ */
12
+ type Feature = 'ip-enrichment' | 'location';
13
+ /**
14
+ * Options that control how requests to the Experience API are handled.
15
+ */
16
+ interface RequestOptions {
17
+ /**
18
+ * Enabled features (for example, `"ip-enrichment"`) which the API should use for this request.
19
+ *
20
+ * @remarks
21
+ * When omitted, a default set of features may be applied.
22
+ */
23
+ enabledFeatures?: Feature[];
24
+ /**
25
+ * IP address to override the API behavior for IP analysis.
26
+ *
27
+ * @remarks
28
+ * Commonly used in ESR or SSR environments, as the API would otherwise use
29
+ * the server IP.
30
+ */
31
+ ip?: string;
32
+ /**
33
+ * Locale used to translate `location.city` and `location.country`.
34
+ *
35
+ * @remarks
36
+ * When omitted, a server-side default may be used.
37
+ */
38
+ locale?: string;
39
+ /**
40
+ * When `true`, sends performance-critical endpoints in plain text.
41
+ *
42
+ * @remarks
43
+ * The Ninetailed API accepts certain endpoints in plain text to avoid CORS
44
+ * preflight requests, which can improve performance in browser environments.
45
+ */
46
+ plainText?: boolean;
47
+ /**
48
+ * When `true`, instructs the API to aggregate a new profile state but not store it.
49
+ *
50
+ * @remarks
51
+ * This is commonly used in ESR or SSR environments where you want to
52
+ * preview the result without persisting changes.
53
+ */
54
+ preflight?: boolean;
55
+ }
56
+ /**
57
+ * Parameters used when creating a profile.
58
+ */
59
+ interface CreateProfileParams {
60
+ /**
61
+ * Events used to aggregate the profile state.
62
+ */
63
+ events: ExperienceEventArray;
64
+ }
65
+ /**
66
+ * Parameters used when updating an existing profile.
67
+ */
68
+ interface UpdateProfileParams extends CreateProfileParams {
69
+ /**
70
+ * ID of the profile to update.
71
+ */
72
+ profileId: string;
73
+ }
74
+ /**
75
+ * Parameters used when creating or updating a profile.
76
+ */
77
+ interface UpsertProfileParams extends CreateProfileParams {
78
+ /**
79
+ * Optional ID of the profile; when omitted, a new profile is created.
80
+ */
81
+ profileId?: string;
82
+ }
83
+ /**
84
+ * Parameters used when performing a batch profile update.
85
+ */
86
+ interface BatchUpdateProfileParams {
87
+ /**
88
+ * Batch of events to process.
89
+ */
90
+ events: BatchExperienceEventArray;
91
+ }
92
+ /**
93
+ * Configuration for {@link ExperienceApiClient}.
94
+ */
95
+ export interface ExperienceApiClientConfig extends ApiConfig, RequestOptions {
96
+ }
97
+ /**
98
+ * Client for interacting with the Experience API.
99
+ *
100
+ * @public
101
+ *
102
+ * @remarks
103
+ * This client is responsible for reading and mutating Ninetailed profiles
104
+ * using the Experience API.
105
+ *
106
+ * @example
107
+ * ```ts
108
+ * const client = new ExperienceApiClient({
109
+ * clientId: 'org-id',
110
+ * environment: 'main',
111
+ * })
112
+ *
113
+ * const profile = await client.getProfile('profile-id')
114
+ * ```
115
+ */
116
+ export default class ExperienceApiClient extends ApiClientBase {
117
+ /**
118
+ * Base URL used for Experience API requests.
119
+ */
120
+ protected readonly baseUrl: string;
121
+ private readonly enabledFeatures?;
122
+ private readonly ip?;
123
+ private readonly locale?;
124
+ private readonly plainText?;
125
+ private readonly preflight?;
126
+ /**
127
+ * Creates a new {@link ExperienceApiClient} instance.
128
+ *
129
+ * @param config - Configuration for the Experience API client.
130
+ */
131
+ constructor(config: ExperienceApiClientConfig);
132
+ /**
133
+ * Retrieves a profile by ID.
134
+ *
135
+ * @param id - The profile ID to retrieve.
136
+ * @param options - Optional request options. `preflight` and `plainText` are not allowed here.
137
+ * @returns The current optimization data for the profile.
138
+ *
139
+ * @throws {@link Error}
140
+ * Thrown if `id` is missing or the underlying request fails.
141
+ *
142
+ * @example
143
+ * ```ts
144
+ * const profile = await client.getProfile('profile-id', {
145
+ * locale: 'en-US',
146
+ * })
147
+ * ```
148
+ */
149
+ getProfile(id: string, options?: Omit<RequestOptions, 'preflight' | 'plainText'>): Promise<OptimizationData>;
150
+ /**
151
+ * Sends a POST request to mutate a profile or profiles.
152
+ *
153
+ * @param request - Mutation request options including URL, body, and request options.
154
+ * @returns The raw {@link Response} from the underlying fetch.
155
+ *
156
+ * @internal
157
+ */
158
+ private makeProfileMutationRequest;
159
+ /**
160
+ * Creates a profile and returns the resulting optimization data.
161
+ *
162
+ * @param params - Parameters containing the events to aggregate into the profile.
163
+ * @param options - Optional request options.
164
+ * @returns The optimization data for the newly created profile.
165
+ *
166
+ * @remarks
167
+ * The returned profile ID can be used for subsequent update requests.
168
+ *
169
+ * @example
170
+ * ```ts
171
+ * const data = await client.createProfile({
172
+ * events: [{ type: 'identify', userId: 'user-123' }],
173
+ * })
174
+ * ```
175
+ */
176
+ createProfile({ events }: CreateProfileParams, options?: RequestOptions): Promise<OptimizationData>;
177
+ /**
178
+ * Updates an existing profile with the given profile ID.
179
+ *
180
+ * @param params - Parameters including the profile ID and events.
181
+ * @param options - Optional request options.
182
+ * @returns The updated optimization data for the profile.
183
+ *
184
+ * @throws {@link Error}
185
+ * Thrown if `profileId` is missing or the underlying request fails.
186
+ *
187
+ * @example
188
+ * ```ts
189
+ * const data = await client.updateProfile({
190
+ * profileId: 'profile-id',
191
+ * events: [{ type: 'track', event: 'viewed_video' }],
192
+ * })
193
+ * ```
194
+ */
195
+ updateProfile({ profileId, events }: UpdateProfileParams, options?: RequestOptions): Promise<OptimizationData>;
196
+ /**
197
+ * Creates or updates a profile depending on whether a `profileId` is provided.
198
+ *
199
+ * @param params - Parameters including optional profile ID and events.
200
+ * @param options - Optional request options.
201
+ * @returns The resulting optimization data.
202
+ *
203
+ * @example
204
+ * ```ts
205
+ * // Create
206
+ * await client.upsertProfile({ events })
207
+ *
208
+ * // Update
209
+ * await client.upsertProfile({ profileId: 'profile-id', events })
210
+ * ```
211
+ */
212
+ upsertProfile({ profileId, events }: UpsertProfileParams, options?: RequestOptions): Promise<OptimizationData>;
213
+ /**
214
+ * Sends multiple events to the Ninetailed Experience API to upsert many profiles.
215
+ *
216
+ * @param params - Parameters containing the batch of events.
217
+ * @param options - Optional request options.
218
+ * @returns The list of profiles affected by the batch operation.
219
+ *
220
+ * @remarks
221
+ * Every event must contain an anonymous ID. Profiles will be created or
222
+ * updated according to the anonymous ID.
223
+ *
224
+ * This method is intended to be used from server environments.
225
+ *
226
+ * @example
227
+ * ```ts
228
+ * const profiles = await client.upsertManyProfiles({
229
+ * events: [
230
+ * [{ type: 'identify', userId: 'user-1' }],
231
+ * [{ type: 'identify', userId: 'user-2' }],
232
+ * ],
233
+ * })
234
+ * ```
235
+ */
236
+ upsertManyProfiles({ events }: BatchUpdateProfileParams, options?: RequestOptions): Promise<BatchExperienceData['profiles']>;
237
+ /**
238
+ * Constructs a request URL with query parameters derived from request options.
239
+ *
240
+ * @param path - Path relative to the Experience API base URL.
241
+ * @param options - Request options that may influence query parameters.
242
+ * @returns The fully constructed URL as a string.
243
+ *
244
+ * @internal
245
+ */
246
+ private constructUrl;
247
+ /**
248
+ * Constructs request headers based on request options and default configuration.
249
+ *
250
+ * @param options - Request options that may influence headers.
251
+ * @returns A record of HTTP headers to send with the request.
252
+ *
253
+ * @internal
254
+ */
255
+ private constructHeaders;
256
+ /**
257
+ * Constructs the `options` section of the request body for profile mutations.
258
+ *
259
+ * @param options - Request options that may specify enabled features.
260
+ * @returns Experience API body options including feature flags.
261
+ *
262
+ * @internal
263
+ */
264
+ private readonly constructBodyOptions;
265
+ }
266
+ export {};
267
+ //# sourceMappingURL=ExperienceApiClient.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ExperienceApiClient.d.ts","sourceRoot":"","sources":["../../src/experience/ExperienceApiClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,oBAAoB,EAEpB,KAAK,mBAAmB,EACxB,KAAK,yBAAyB,EAG9B,KAAK,gBAAgB,EACtB,MAAM,sCAAsC,CAAA;AAE7C,OAAO,aAAa,EAAE,EAAE,KAAK,SAAS,EAAE,MAAM,kBAAkB,CAAA;AAIhE;;;;GAIG;AACH,eAAO,MAAM,mBAAmB,sCAAsC,CAAA;AAEtE;;GAEG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