@contentful/optimization-api-client 0.1.0-alpha9 → 1.0.1

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="../../contentful-icon.png" width="150">
3
+ <img alt="Contentful Logo" title="Contentful" src="https://raw.githubusercontent.com/contentful/optimization/optimization-api-client-v1.0.1/contentful-icon.png" width="150">
4
4
  </a>
5
5
  </p>
6
6
 
@@ -10,49 +10,36 @@
10
10
 
11
11
  <div align="center">
12
12
 
13
- [Readme](./README.md) · [Reference](https://contentful.github.io/optimization) ·
14
- [Contributing](../../CONTRIBUTING.md)
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/optimization-api-client-v1.0.1/CONTRIBUTING.md)
15
15
 
16
16
  </div>
17
17
 
18
- > [!WARNING]
19
- >
20
- > The Optimization SDK Suite is pre-release (alpha). Breaking changes may be published at any time.
18
+ The Contentful Optimization API Client provides low-level transport for the Experience API and
19
+ Insights API. Application-facing SDKs compose this package with event builders, state management,
20
+ queueing, and runtime-specific defaults.
21
21
 
22
- The Contentful Optimization API Client Library provides methods for interfacing with Contentful's
23
- Experience and Insights APIs, which serve its Personalization and Analytics products.
24
-
25
- > [!NOTE]
26
- >
27
- > In the future, the Experience and Insights APIs may be combined behind an Optimization API
22
+ We recommend starting applications with Web, React Web, Node, or React Native SDKs. Use this package
23
+ directly when building or maintaining SDK layers, tests, tooling, or first-party integrations that
24
+ need raw API access.
28
25
 
29
26
  <details>
30
27
  <summary>Table of Contents</summary>
31
28
  <!-- mtoc-start -->
32
29
 
33
- - [Getting Started](#getting-started)
34
- - [Configuration](#configuration)
35
- - [Top-level Configuration Options](#top-level-configuration-options)
36
- - [Fetch Options](#fetch-options)
37
- - [Analytics Options](#analytics-options)
38
- - [Personalization Options](#personalization-options)
39
- - [Working With the APIs](#working-with-the-apis)
30
+ - [Getting started](#getting-started)
31
+ - [When to use this package](#when-to-use-this-package)
32
+ - [Common configuration](#common-configuration)
33
+ - [API surface](#api-surface)
40
34
  - [Experience API](#experience-api)
41
- - [Get Profile data](#get-profile-data)
42
- - [Create a New Profile](#create-a-new-profile)
43
- - [Update an Existing Profile](#update-an-existing-profile)
44
- - [Upsert a Profile](#upsert-a-profile)
45
- - [Upsert Many Profiles](#upsert-many-profiles)
46
35
  - [Insights API](#insights-api)
47
- - [Send Batch Events](#send-batch-events)
48
- - [Event Builder](#event-builder)
49
- - [Event Builder Configuration](#event-builder-configuration)
50
- - [Event Builder Configured Methods](#event-builder-configured-methods)
36
+ - [Fetch helpers](#fetch-helpers)
37
+ - [Related](#related)
51
38
 
52
39
  <!-- mtoc-end -->
53
40
  </details>
54
41
 
55
- ## Getting Started
42
+ ## Getting started
56
43
 
57
44
  Install using an NPM-compatible package manager, pnpm for example:
58
45
 
@@ -60,254 +47,124 @@ Install using an NPM-compatible package manager, pnpm for example:
60
47
  pnpm install @contentful/optimization-api-client
61
48
  ```
62
49
 
63
- Import the API client; both CJS and ESM module systems are supported, ESM preferred:
50
+ Import and initialize the unified API client; both CJS and ESM module systems are supported, ESM
51
+ preferred:
64
52
 
65
53
  ```ts
66
54
  import { ApiClient } from '@contentful/optimization-api-client'
67
- ```
68
55
 
69
- Configure and initialize the API Client:
70
-
71
- ```ts
72
- const client = new ApiClient({ clientId: 'abc123' })
56
+ const client = new ApiClient({
57
+ clientId: 'your-client-id',
58
+ environment: 'main',
59
+ })
73
60
  ```
74
61
 
75
- ## Configuration
76
-
77
- ### Top-level Configuration Options
78
-
79
- | Option | Required? | Default | Description |
80
- | ----------------- | --------- | ----------------------------- | ------------------------------------------------------------ |
81
- | `analytics` | No | See "Analytics Options" | Configuration specific to the Analytics/Insights API |
82
- | `clientId` | Yes | N/A | The Optimization API key |
83
- | `environment` | No | `'main'` | The environment identifier |
84
- | `fetchOptions` | No | See "Fetch Options" | Configuration for Fetch timeout and retry functionality |
85
- | `personalization` | No | See "Personalization Options" | Configuration specific to the Personalization/Experience API |
86
-
87
- ### Fetch Options
88
-
89
- Fetch options allow for configuration of both a Fetch API-compatible fetch method and the
90
- retry/timeout logic integrated into the Optimization API Client. Specify the `fetchMethod` when the
91
- host application environment does not offer a `fetch` method that is compatible with the standard
92
- Fetch API in its global scope.
93
-
94
- | Option | Required? | Default | Description |
95
- | ------------------ | --------- | ----------- | --------------------------------------------------------------------- |
96
- | `fetchMethod` | No | `undefined` | Signature of a fetch method used by the API clients |
97
- | `intervalTimeout` | No | `0` | Delay (in milliseconds) between retry attempts |
98
- | `onFailedAttempt` | No | `undefined` | Callback invoked whenever a retry attempt fails |
99
- | `onRequestTimeout` | No | `undefined` | Callback invoked when a request exceeds the configured timeout |
100
- | `requestTimeout` | No | `3000` | Maximum time (in milliseconds) to wait for a response before aborting |
101
- | `retries` | No | `1` | Maximum number of retry attempts |
102
-
103
- Configuration method signatures:
104
-
105
- - `fetchMethod`: `(url: string \| URL, init: RequestInit) => Promise<Response>`
106
- - `onFailedAttempt` and `onRequestTimeout`: `(options: FetchMethodCallbackOptions) => void`
107
-
108
- > [!NOTE]
109
- >
110
- > Retry behavior is intentionally fixed to HTTP `503` responses (`Service Unavailable`) for the
111
- > default SDK transport policy. This matches current Experience and Insights API expectations: `503`
112
- > is treated as the transient availability signal, while other response classes are handled by
113
- > caller logic and are intentionally not retried by default. Treat this as deliberate contract
114
- > behavior, not a transport gap; broaden retry status handling only with an explicit API contract
115
- > change.
116
-
117
- ### Analytics Options
118
-
119
- | Option | Required? | Default | Description |
120
- | --------------- | --------- | ------------------------------------------ | ------------------------------------------------------------------------ |
121
- | `baseUrl` | No | `'https://ingest.insights.ninetailed.co/'` | Base URL for the Insights API |
122
- | `beaconHandler` | No | `undefined` | Handler used to enqueue events via the Beacon API or a similar mechanism |
123
-
124
- Configuration method signatures:
125
-
126
- - `beaconHandler`: `(url: string | URL, data: BatchInsightsEventArray) => boolean`
127
-
128
- ### Personalization Options
129
-
130
- | Option | Required? | Default | Description |
131
- | ----------------- | --------- | ------------------------------------- | ------------------------------------------------------------------- |
132
- | `baseUrl` | No | `'https://experience.ninetailed.co/'` | Base URL for the Experience API |
133
- | `enabledFeatures` | No | `['ip-enrichment', 'location']` | Enabled features which the API may use for each request |
134
- | `ip` | No | `undefined` | IP address to override the API behavior for IP analysis |
135
- | `locale` | No | `'en-US'` (in API) | Locale used to translate `location.city` and `location.country` |
136
- | `plainText` | No | `false` | Sends performance-critical endpoints in plain text |
137
- | `preflight` | No | `false` | Instructs the API to aggregate a new profile state but not store it |
138
-
139
- > [!NOTE]
140
- >
141
- > All options except `baseUrl` may also be provided on a per-request basis.
142
-
143
- ## Working With the APIs
62
+ ## When to use this package
63
+
64
+ Use `@contentful/optimization-api-client` when you need direct low-level access to the Experience
65
+ API or Insights API transport surface. Use an application-facing SDK when you need optimization
66
+ state, consent handling, event builders, entry resolution, tracking, or platform defaults.
67
+
68
+ ## Common configuration
69
+
70
+ | Option | Required? | Default | Description |
71
+ | -------------- | --------- | ---------------------------- | ----------------------------------------------------------- |
72
+ | `clientId` | Yes | N/A | Shared API key for Experience API and Insights API requests |
73
+ | `environment` | No | `'main'` | Contentful environment identifier |
74
+ | `experience` | No | See Experience options below | Experience API endpoint and default request options |
75
+ | `insights` | No | See Insights options below | Insights API endpoint options |
76
+ | `fetchOptions` | No | SDK defaults | Fetch timeout and retry behavior |
77
+
78
+ Common Experience API options:
79
+
80
+ | Option | Required? | Default | Description |
81
+ | ----------------- | --------- | ------------------------------------- | ----------------------------------------------- |
82
+ | `baseUrl` | No | `'https://experience.ninetailed.co/'` | Base URL for the Experience API |
83
+ | `enabledFeatures` | No | `['ip-enrichment', 'location']` | Experience API features for mutation requests |
84
+ | `ip` | No | `undefined` | IP address override for Experience API analysis |
85
+ | `locale` | No | API default | Locale query parameter for localized responses |
86
+ | `plainText` | No | Endpoint-specific | Sends single-profile mutation endpoints as text |
87
+ | `preflight` | No | `false` | Aggregates a profile state without storing it |
88
+
89
+ Experience mutation request options except `baseUrl` can also be provided per mutation request.
90
+ `getProfile` is a read request and only uses `locale` from per-call options; mutation-only options
91
+ such as `enabledFeatures`, `ip`, `plainText`, and `preflight` do not apply. Single-profile mutation
92
+ requests default to `plainText: true` and send `text/plain` unless overridden. Batch profile updates
93
+ with `upsertManyProfiles` are the JSON-default exception and use `plainText: false` by default.
94
+ `locale` is sent as the Experience API `locale` query parameter and can localize profile fields such
95
+ as `location.city` and `location.country`. Higher-level SDK merge-tag helpers resolve against the
96
+ profile values returned by the Experience API, so applications that render localized Contentful
97
+ entries commonly pass the same locale used for the CDA entry fetch. Pass a valid locale tag; invalid
98
+ locale syntax can fail 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
+
108
+ Common `fetchOptions` are `fetchMethod`, `requestTimeout`, `retries`, `intervalTimeout`,
109
+ `onFailedAttempt`, and `onRequestTimeout`. Default retries intentionally apply only to HTTP `503`
110
+ responses.
111
+
112
+ For every option, callback payload, request type, and response type, use the generated
113
+ [API Client reference](https://contentful.github.io/optimization/modules/_contentful_optimization-api-client.html).
114
+
115
+ ## API surface
144
116
 
145
117
  ### Experience API
146
118
 
147
- Experience API methods are scoped to the client's `experience` member. All singular experience
148
- methods return a `Promise` that resolves with the following data:
149
-
150
- ```json
151
- {
152
- "profile": {
153
- /* User profile data */
154
- },
155
- "personalizations": [
156
- {
157
- /* Personalization/experience configuration for the associated profile */
158
- }
159
- ],
160
- "changes": [
161
- {
162
- /* Similar to `personalizations` but currently used for Custom Flags */
163
- }
164
- ]
165
- }
166
- ```
167
-
168
- #### Get Profile data
169
-
170
- ```ts
171
- const client = new ApiClient({ clientId: 'abc123' })
172
- const { profile } = await client.experience.getProfile('profile-123', { locale: 'de-DE' })
173
- ```
174
-
175
- #### Create a New Profile
176
-
177
- ```ts
178
- const client = new ApiClient({ clientId: 'abc123' })
179
- const { profile } = await client.experience.createProfile({ events: [...] }, { locale: 'de-DE' })
180
- ```
181
-
182
- #### Update an Existing Profile
119
+ Experience API methods are scoped to `client.experience` and return profile and optimization data:
183
120
 
184
121
  ```ts
185
- const client = new ApiClient({ clientId: 'abc123' })
186
- const { profile } = await client.experience.updateProfile(
122
+ const { profile, selectedOptimizations, changes } = await client.experience.upsertProfile(
187
123
  {
188
- profileId: 'profile-123',
189
- events: [...],
190
- },
191
- { locale: 'de-DE' }
192
- )
193
- ```
194
-
195
- #### Upsert a Profile
196
-
197
- ```ts
198
- const client = new ApiClient({ clientId: 'abc123' })
199
- const { profile } = await client.experience.upsertProfile(
200
- {
201
- profileId,
202
- events: [...],
203
- },
204
- { locale: 'de-DE' }
205
- )
206
- ```
207
-
208
- #### Upsert Many Profiles
209
-
210
- The `upsertManyProfiles` method returns a `Promise` that resolves with an array of user profiles.
211
- The `events` array must contain at least one event. Each event should have an additional
212
- `anonymousId` property set to the associated anonymous ID or profile ID.
213
-
214
- ```ts
215
- const client = new ApiClient({ clientId: 'abc123' })
216
- const profiles = await client.experience.upsertManyProfiles(
217
- {
218
- events: [
219
- {
220
- anonymousId: 'anon-123',
221
- // valid Experience event payload fields
222
- },
223
- ],
124
+ profileId: 'profile-id',
125
+ events: [pageEvent],
224
126
  },
225
127
  { locale: 'de-DE' },
226
128
  )
227
129
  ```
228
130
 
229
- ### Insights API
131
+ Common methods include `getProfile`, `createProfile`, `updateProfile`, `upsertProfile`, and
132
+ `upsertManyProfiles`.
230
133
 
231
- Insights API methods are scoped to the client's `insights` member. The batch send method returns a
232
- `Promise` that resolves to `boolean`.
134
+ ### Insights API
233
135
 
234
- #### Send Batch Events
136
+ Insights API methods are scoped to `client.insights` and send analytics event batches:
235
137
 
236
138
  ```ts
237
- const client = new ApiClient({ clientId: 'abc123' })
238
139
  await client.insights.sendBatchEvents([
239
140
  {
240
- profile: { id: 'abc-123', ... },
241
- events: [
242
- {
243
- type: 'component',
244
- componentId: 'hero-banner',
245
- componentType: 'Entry',
246
- variantIndex: 0,
247
- ...,
248
- },
249
- ],
250
- }
141
+ profile,
142
+ events: [viewEvent],
143
+ },
251
144
  ])
252
145
  ```
253
146
 
254
- ## Event Builder
255
-
256
- The Event Builder is a helper class that assists in constructing valid events for submission to the
257
- Experience and Insights APIs.
258
-
259
- ### Event Builder Configuration
260
-
261
- Event Builder configuration options assist in adding contextual data to each event created by a
262
- builder instance.
263
-
264
- | Option | Required? | Default | Description |
265
- | ------------------- | --------- | ------------------------------- | ---------------------------------------------------------------------------------- |
266
- | `app` | No | `undefined` | The application definition used to attribute events to a specific consumer app |
267
- | `channel` | Yes | N/A | The channel that identifies where events originate from (e.g. `'web'`, `'mobile'`) |
268
- | `library` | Yes | N/A | The client library metadata that is attached to all events |
269
- | `getLocale` | No | `() => 'en-US'` | Function used to resolve the locale for outgoing events |
270
- | `getPageProperties` | No | `() => DEFAULT_PAGE_PROPERTIES` | Function that returns the current page properties |
271
- | `getUserAgent` | No | `() => undefined` | Function used to obtain the current user agent string when applicable |
272
-
273
- The `get*` functions are most useful in stateful environments. Stateless environments should set the
274
- related data directly via Event Builder method arguments.
275
-
276
- The `channel` option may contain one of the following values:
277
-
278
- - `web`
279
- - `mobile`
280
- - `server`
281
-
282
- Configuration method signatures:
147
+ Insights endpoints do not return response data. For last-chance browser lifecycle delivery, pass a
148
+ per-call `beacon` sender that receives the request URL and already serialized body.
283
149
 
284
- - `getLocale`: `() => string | undefined`
285
- - `getPageProperties`:
150
+ ### Fetch helpers
286
151
 
287
- ```ts
288
- () => {
289
- path: string,
290
- query: Record<string, string>,
291
- referrer: string,
292
- search: string,
293
- title?: string,
294
- url: string
295
- }
296
- ```
152
+ This package also exports fetch helper functions used by SDK layers:
297
153
 
298
- - `getUserAgent`: `() => string | undefined`
154
+ | Helper | Purpose |
155
+ | ---------------------------- | ------------------------------------------------------- |
156
+ | `createProtectedFetchMethod` | Adds timeout and retry protection around a fetch method |
157
+ | `createRetryFetchMethod` | Applies retry policy to retryable responses |
158
+ | `createTimeoutFetchMethod` | Aborts requests after the configured timeout |
299
159
 
300
- #### Event Builder Configured Methods
160
+ Use generated reference docs for helper signatures and callback payloads.
301
161
 
302
- - `buildComponentClick`: Builds a component click event payload for a Contentful entry-based
303
- component
304
- - `buildComponentView`: Builds a component view event payload for a Contentful entry-based component
305
- - `buildFlagView`: Builds a component view payload event for a Custom Flag component
306
- - `buildIdentify`: Builds an identify event payload to associate a user ID with traits
307
- - `buildPageView`: Builds a page view event payload
308
- - `buildScreenView`: Builds a screen view event payload
309
- - `buildTrack`: Builds a track event payload for arbitrary user actions
162
+ ## Related
310
163
 
311
- See the
312
- [Event Builder documentation](https://contentful.github.io/optimization/classes/_contentful_optimization-api-client.EventBuilder.html)
313
- for more information regarding arguments and return values.
164
+ - [API Client generated reference](https://contentful.github.io/optimization/modules/_contentful_optimization-api-client.html) -
165
+ exported API reference
166
+ - [API Schemas](https://github.com/contentful/optimization/blob/optimization-api-client-v1.0.1/packages/universal/api-schemas/README.md) - runtime validation schemas and inferred API types
167
+ - [Optimization Core SDK](https://github.com/contentful/optimization/blob/optimization-api-client-v1.0.1/packages/universal/core-sdk/README.md) - platform-agnostic SDK layer that composes this
168
+ client
169
+ - [Choosing the right SDK](https://contentful.github.io/optimization/documents/Documentation.Guides.choosing-the-right-sdk.html) -
170
+ package selection guidance for application integrations