@contentful/optimization-api-client 0.1.0-alpha13 → 0.1.0-alpha14

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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  <p align="center">
2
2
  <a href="https://www.contentful.com/developers/docs/personalization/">
3
- <img alt="Contentful Logo" title="Contentful" src="https://raw.githubusercontent.com/contentful/optimization/v0.1.0-alpha13/contentful-icon.png" width="150">
3
+ <img alt="Contentful Logo" title="Contentful" src="https://raw.githubusercontent.com/contentful/optimization/v0.1.0-alpha14/contentful-icon.png" width="150">
4
4
  </a>
5
5
  </p>
6
6
 
@@ -11,47 +11,39 @@
11
11
  <div align="center">
12
12
 
13
13
  [Guides](https://contentful.github.io/optimization/documents/Documentation.Guides.html) ·
14
- [Reference](https://contentful.github.io/optimization) · [Contributing](https://github.com/contentful/optimization/blob/v0.1.0-alpha13/CONTRIBUTING.md)
14
+ [Reference](https://contentful.github.io/optimization) · [Contributing](https://github.com/contentful/optimization/blob/v0.1.0-alpha14/CONTRIBUTING.md)
15
15
 
16
16
  </div>
17
17
 
18
18
  > [!WARNING]
19
19
  >
20
- > The Optimization SDK Suite is pre-release (alpha). Breaking changes may be published at any time.
20
+ > The Optimization SDK Suite is pre-release (alpha). Breaking changes can be published at any time.
21
21
 
22
- The Contentful Optimization API Client Library provides methods for interfacing with Contentful's
23
- Experience API and Insights API, which serve its Personalization and Analytics products.
22
+ The Contentful Optimization API Client provides low-level transport for the Experience API and
23
+ Insights API. Application-facing SDKs compose this package with event builders, state management,
24
+ queueing, and runtime-specific defaults.
24
25
 
25
- > [!NOTE]
26
- >
27
- > The Experience API and Insights API are separate today, and this client provides a unified SDK
28
- > surface for both APIs.
26
+ We recommend starting applications with Web, React Web, Node, or React Native SDKs. Use this package
27
+ directly when building or maintaining SDK layers, tests, tooling, or first-party integrations that
28
+ need raw API access.
29
29
 
30
30
  <details>
31
31
  <summary>Table of Contents</summary>
32
32
  <!-- mtoc-start -->
33
33
 
34
- - [Getting Started](#getting-started)
35
- - [Configuration](#configuration)
36
- - [Top-level Configuration Options](#top-level-configuration-options)
37
- - [Fetch Options](#fetch-options)
38
- - [Insights API Options](#insights-api-options)
39
- - [Experience API Options](#experience-api-options)
40
- - [Working With the APIs](#working-with-the-apis)
34
+ - [Getting started](#getting-started)
35
+ - [When to use this package](#when-to-use-this-package)
36
+ - [Common configuration](#common-configuration)
37
+ - [API surface](#api-surface)
41
38
  - [Experience API](#experience-api)
42
- - [Get Profile data](#get-profile-data)
43
- - [Create a New Profile](#create-a-new-profile)
44
- - [Update an Existing Profile](#update-an-existing-profile)
45
- - [Upsert a Profile](#upsert-a-profile)
46
- - [Upsert Many Profiles](#upsert-many-profiles)
47
39
  - [Insights API](#insights-api)
48
- - [Send Batch Events](#send-batch-events)
49
- - [Event Construction](#event-construction)
40
+ - [Fetch helpers](#fetch-helpers)
41
+ - [Related](#related)
50
42
 
51
43
  <!-- mtoc-end -->
52
44
  </details>
53
45
 
54
- ## Getting Started
46
+ ## Getting started
55
47
 
56
48
  Install using an NPM-compatible package manager, pnpm for example:
57
49
 
@@ -59,199 +51,118 @@ Install using an NPM-compatible package manager, pnpm for example:
59
51
  pnpm install @contentful/optimization-api-client
60
52
  ```
61
53
 
62
- Import the API client; both CJS and ESM module systems are supported, ESM preferred:
54
+ Import and initialize the unified API client; both CJS and ESM module systems are supported, ESM
55
+ preferred:
63
56
 
64
57
  ```ts
65
58
  import { ApiClient } from '@contentful/optimization-api-client'
66
- ```
67
59
 
68
- Configure and initialize the API Client:
69
-
70
- ```ts
71
- const client = new ApiClient({ clientId: 'abc123' })
60
+ const client = new ApiClient({
61
+ clientId: 'your-client-id',
62
+ environment: 'main',
63
+ })
72
64
  ```
73
65
 
74
- ## Configuration
66
+ ## When to use this package
75
67
 
76
- ### Top-level Configuration Options
68
+ Use `@contentful/optimization-api-client` when you need direct low-level access to the Experience
69
+ API or Insights API transport surface. Use an application-facing SDK when you need optimization
70
+ state, consent handling, event builders, entry resolution, tracking, or platform defaults.
71
+
72
+ ## Common configuration
77
73
 
78
74
  | Option | Required? | Default | Description |
79
75
  | -------------- | --------- | ---------------------------- | ----------------------------------------------------------- |
80
- | `experience` | No | See "Experience API Options" | Configuration specific to the Experience API |
81
76
  | `clientId` | Yes | N/A | Shared API key for Experience API and Insights API requests |
82
- | `environment` | No | `'main'` | The environment identifier |
83
- | `fetchOptions` | No | See "Fetch Options" | Configuration for Fetch timeout and retry functionality |
84
- | `insights` | No | See "Insights API Options" | Configuration specific to the Insights API |
85
-
86
- ### Fetch Options
87
-
88
- Fetch options allow for configuration of both a Fetch API-compatible fetch method and the
89
- retry/timeout logic integrated into this API client. Specify the `fetchMethod` when the host
90
- application environment does not offer a `fetch` method that is compatible with the standard Fetch
91
- API in its global scope.
92
-
93
- | Option | Required? | Default | Description |
94
- | ------------------ | --------- | ----------- | --------------------------------------------------------------------- |
95
- | `fetchMethod` | No | `undefined` | Signature of a fetch method used by the API clients |
96
- | `intervalTimeout` | No | `0` | Delay (in milliseconds) between retry attempts |
97
- | `onFailedAttempt` | No | `undefined` | Callback invoked whenever a retry attempt fails |
98
- | `onRequestTimeout` | No | `undefined` | Callback invoked when a request exceeds the configured timeout |
99
- | `requestTimeout` | No | `3000` | Maximum time (in milliseconds) to wait for a response before aborting |
100
- | `retries` | No | `1` | Maximum number of retry attempts |
101
-
102
- Configuration method signatures:
103
-
104
- - `fetchMethod`: `(url: string \| URL, init: RequestInit) => Promise<Response>`
105
- - `onFailedAttempt` and `onRequestTimeout`: `(options: FetchMethodCallbackOptions) => void`
106
-
107
- > [!NOTE]
108
- >
109
- > Retry behavior is intentionally fixed to HTTP `503` responses (`Service Unavailable`) for the
110
- > default SDK transport policy. This matches current Experience API and Insights API expectations:
111
- > `503` is treated as the transient availability signal, while other response classes are handled by
112
- > caller logic and are intentionally not retried by default. Treat this as deliberate contract
113
- > behavior, not a transport gap; broaden retry status handling only with an explicit API contract
114
- > change.
115
-
116
- ### Insights API Options
117
-
118
- | Option | Required? | Default | Description |
119
- | --------------- | --------- | ------------------------------------------ | ------------------------------------------------------------------------ |
120
- | `baseUrl` | No | `'https://ingest.insights.ninetailed.co/'` | Base URL for the Insights API |
121
- | `beaconHandler` | No | `undefined` | Handler used to enqueue events via the Beacon API or a similar mechanism |
122
-
123
- Configuration method signatures:
124
-
125
- - `beaconHandler`: `(url: string | URL, data: BatchInsightsEventArray) => boolean`
126
-
127
- ### Experience API Options
128
-
129
- | Option | Required? | Default | Description |
130
- | ----------------- | --------- | ------------------------------------- | ------------------------------------------------------------------- |
131
- | `baseUrl` | No | `'https://experience.ninetailed.co/'` | Base URL for the Experience API |
132
- | `enabledFeatures` | No | `['ip-enrichment', 'location']` | Enabled features which the API may use for each request |
133
- | `ip` | No | `undefined` | IP address to override the API behavior for IP analysis |
134
- | `locale` | No | `'en-US'` (in API) | Locale used to translate `location.city` and `location.country` |
135
- | `plainText` | No | `false` | Sends performance-critical endpoints in plain text |
136
- | `preflight` | No | `false` | Instructs the API to aggregate a new profile state but not store it |
137
-
138
- > [!NOTE]
139
- >
140
- > All options except `baseUrl` may also be provided on a per-request basis.
141
-
142
- ## Working With the APIs
77
+ | `environment` | No | `'main'` | Contentful environment identifier |
78
+ | `experience` | No | See Experience options below | Experience API endpoint and default request options |
79
+ | `insights` | No | See Insights options below | Insights API endpoint options |
80
+ | `fetchOptions` | No | SDK defaults | Fetch timeout and retry behavior |
81
+
82
+ Common Experience API options:
83
+
84
+ | Option | Required? | Default | Description |
85
+ | ----------------- | --------- | ------------------------------------- | ----------------------------------------------- |
86
+ | `baseUrl` | No | `'https://experience.ninetailed.co/'` | Base URL for the Experience API |
87
+ | `enabledFeatures` | No | `['ip-enrichment', 'location']` | Experience API features for each request |
88
+ | `ip` | No | `undefined` | IP address override for Experience API analysis |
89
+ | `locale` | No | API default | Locale query parameter for localized responses |
90
+ | `plainText` | No | `false` | Sends performance-critical endpoints as text |
91
+ | `preflight` | No | `false` | Aggregates a profile state without storing it |
92
+
93
+ All Experience options except `baseUrl` can also be provided per request. `locale` is sent as the
94
+ Experience API `locale` query parameter and can localize profile fields such as `location.city` and
95
+ `location.country`. Higher-level SDK merge-tag helpers resolve against the profile values returned
96
+ by the Experience API, so applications that render localized Contentful entries commonly pass the
97
+ same locale used for the CDA entry fetch. Pass a valid locale tag; invalid locale syntax can fail
98
+ Experience API request validation. See
99
+ [Locale handling in the Optimization SDK Suite](https://contentful.github.io/optimization/documents/Documentation.Concepts.Locale_handling_in_the_Optimization_SDK_Suite.html)
100
+ for how this request locale relates to Contentful and SDK-resolved locales.
101
+
102
+ Common Insights API options:
103
+
104
+ | Option | Required? | Default | Description |
105
+ | --------------- | --------- | ------------------------------------------ | ----------------------------------------------------- |
106
+ | `baseUrl` | No | `'https://ingest.insights.ninetailed.co/'` | Base URL for the Insights API |
107
+ | `beaconHandler` | No | `undefined` | Custom handler for enqueueing event batches if needed |
108
+
109
+ Common `fetchOptions` are `fetchMethod`, `requestTimeout`, `retries`, `intervalTimeout`,
110
+ `onFailedAttempt`, and `onRequestTimeout`. Default retries intentionally apply only to HTTP `503`
111
+ responses.
112
+
113
+ For every option, callback payload, request type, and response type, use the generated
114
+ [API Client reference](https://contentful.github.io/optimization/modules/_contentful_optimization-api-client.html).
115
+
116
+ ## API surface
143
117
 
144
118
  ### Experience API
145
119
 
146
- Experience API methods are scoped to the client's `experience` member. All singular Experience API
147
- methods return a `Promise` that resolves with the following data:
148
-
149
- ```json
150
- {
151
- "profile": {
152
- /* User profile data */
153
- },
154
- "selectedOptimizations": [
155
- {
156
- /* Optimization/Experience API configuration for the associated profile */
157
- }
158
- ],
159
- "changes": [
160
- {
161
- /* Custom Flag changes associated with the evaluated profile */
162
- }
163
- ]
164
- }
165
- ```
166
-
167
- #### Get Profile data
120
+ Experience API methods are scoped to `client.experience` and return profile and optimization data:
168
121
 
169
122
  ```ts
170
- const client = new ApiClient({ clientId: 'abc123' })
171
- const { profile } = await client.experience.getProfile('profile-123', { locale: 'de-DE' })
172
- ```
173
-
174
- #### Create a New Profile
175
-
176
- ```ts
177
- const client = new ApiClient({ clientId: 'abc123' })
178
- const { profile } = await client.experience.createProfile({ events: [...] }, { locale: 'de-DE' })
179
- ```
180
-
181
- #### Update an Existing Profile
182
-
183
- ```ts
184
- const client = new ApiClient({ clientId: 'abc123' })
185
- const { profile } = await client.experience.updateProfile(
123
+ const { profile, selectedOptimizations, changes } = await client.experience.upsertProfile(
186
124
  {
187
- profileId: 'profile-123',
188
- events: [...],
125
+ profileId: 'profile-id',
126
+ events: [pageEvent],
189
127
  },
190
- { locale: 'de-DE' }
128
+ { locale: 'de-DE' },
191
129
  )
192
130
  ```
193
131
 
194
- #### Upsert a Profile
132
+ Common methods include `getProfile`, `createProfile`, `updateProfile`, `upsertProfile`, and
133
+ `upsertManyProfiles`.
195
134
 
196
- ```ts
197
- const client = new ApiClient({ clientId: 'abc123' })
198
- const { profile } = await client.experience.upsertProfile(
199
- {
200
- profileId,
201
- events: [...],
202
- },
203
- { locale: 'de-DE' }
204
- )
205
- ```
206
-
207
- #### Upsert Many Profiles
135
+ ### Insights API
208
136
 
209
- The `upsertManyProfiles` method returns a `Promise` that resolves with an array of user profiles.
210
- The `events` array must contain at least one event. Each event should have an additional
211
- `anonymousId` property set to the associated anonymous ID or profile ID.
137
+ Insights API methods are scoped to `client.insights` and send analytics event batches:
212
138
 
213
139
  ```ts
214
- const client = new ApiClient({ clientId: 'abc123' })
215
- const profiles = await client.experience.upsertManyProfiles(
216
- {
217
- events: [
218
- {
219
- anonymousId: 'anon-123',
220
- // valid Experience API event payload fields
221
- },
222
- ],
223
- },
224
- { locale: 'de-DE' },
225
- )
140
+ await client.insights.sendBatchEvents({
141
+ profile,
142
+ events: [viewEvent],
143
+ })
226
144
  ```
227
145
 
228
- ### Insights API
146
+ Insights endpoints do not return response data.
229
147
 
230
- Insights API methods are scoped to the client's `insights` member. The batch send method returns a
231
- `Promise` that resolves to `boolean`.
148
+ ### Fetch helpers
232
149
 
233
- #### Send Batch Events
150
+ This package also exports fetch helper functions used by SDK layers:
234
151
 
235
- ```ts
236
- const client = new ApiClient({ clientId: 'abc123' })
237
- await client.insights.sendBatchEvents([
238
- {
239
- profile: { id: 'abc-123', ... },
240
- events: [
241
- {
242
- type: 'component',
243
- componentId: 'hero-banner',
244
- componentType: 'Entry',
245
- variantIndex: 0,
246
- ...,
247
- },
248
- ],
249
- }
250
- ])
251
- ```
152
+ | Helper | Purpose |
153
+ | ---------------------------- | ------------------------------------------------------- |
154
+ | `createProtectedFetchMethod` | Adds timeout and retry protection around a fetch method |
155
+ | `createRetryFetchMethod` | Applies retry policy to retryable responses |
156
+ | `createTimeoutFetchMethod` | Aborts requests after the configured timeout |
157
+
158
+ Use generated reference docs for helper signatures and callback payloads.
252
159
 
253
- ## Event Construction
160
+ ## Related
254
161
 
255
- Event-construction helpers (`EventBuilder`) are part of
256
- [`@contentful/optimization-core`](https://github.com/contentful/optimization/blob/v0.1.0-alpha13/packages/universal/core-sdk/README.md) and environment SDKs that build on top of
257
- it. This package focuses on API transport and request/response validation.
162
+ - [API Client generated reference](https://contentful.github.io/optimization/modules/_contentful_optimization-api-client.html) -
163
+ exported API reference
164
+ - [API Schemas](https://github.com/contentful/optimization/blob/v0.1.0-alpha14/packages/universal/api-schemas/README.md) - runtime validation schemas and inferred API types
165
+ - [Optimization Core SDK](https://github.com/contentful/optimization/blob/v0.1.0-alpha14/packages/universal/core-sdk/README.md) - platform-agnostic SDK layer that composes this
166
+ client
167
+ - [Choosing the right SDK](https://contentful.github.io/optimization/documents/Documentation.Guides.choosing-the-right-sdk.html) -
168
+ package selection guidance for application integrations
package/dist/index.cjs CHANGED
@@ -242,10 +242,13 @@ var __webpack_exports__ = {};
242
242
  else createTimeoutFetchMethod_logger.error(`Request to "${url.toString()}" timed out`, new Error('Request timeout'));
243
243
  controller.abort();
244
244
  }, requestTimeout);
245
- const response = await fetchMethod(url, {
246
- ...init,
245
+ const requestInit = {
246
+ ...init
247
+ };
248
+ Object.assign(requestInit, {
247
249
  signal: controller.signal
248
250
  });
251
+ const response = await fetchMethod(url, requestInit);
249
252
  clearTimeout(id);
250
253
  return response;
251
254
  };
@@ -311,6 +314,9 @@ var __webpack_exports__ = {};
311
314
  this.plainText = plainText;
312
315
  this.preflight = preflight;
313
316
  }
317
+ setLocale(locale) {
318
+ this.locale = locale;
319
+ }
314
320
  async getProfile(id, options = {}) {
315
321
  if (!id) throw new Error('Valid profile ID required.');
316
322
  const requestName = 'Get Profile';