@kontent-ai/custom-app-sdk 1.0.0 → 2.1.0

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
@@ -18,23 +18,39 @@ It facilitates the communication between the Kontent.ai app and the custom app p
18
18
  ### Installation
19
19
 
20
20
  ```sh
21
- npm install @kontent-ai/custom-app-sdk-js
21
+ npm install @kontent-ai/custom-app-sdk
22
22
  ```
23
23
 
24
24
  > [!IMPORTANT]
25
- > The SDK attaches event listeners to communicate with the Kontent.ai app. Make sure to only include the SDK in the browser environment.
25
+ > The SDK attaches event listeners to communicate with the Kontent.ai app. Make sure to include the SDK only in the browser environment.
26
26
 
27
27
  ## Usage example
28
28
 
29
29
  ```typescript
30
- import { getCustomAppContext, CustomAppContext } from "@kontent-ai/custom-app-sdk-js";
30
+ import { getCustomAppContext, CustomAppContext } from "@kontent-ai/custom-app-sdk";
31
31
 
32
- const response: CustomAppContext = await getCustomAppContext();
32
+ const response = await getCustomAppContext();
33
33
 
34
34
  if (response.isError) {
35
- console.error({ errorCode: response.code, description: response.description});
35
+ console.error({ errorCode: response.code, description: response.description });
36
36
  } else {
37
- console.log({ config: response.config, context: response.context });
37
+ // TypeScript will narrow the type based on currentPage
38
+ switch (response.context.currentPage) {
39
+ case "itemEditor":
40
+ console.log({
41
+ contentItemId: response.context.contentItemId,
42
+ languageId: response.context.languageId,
43
+ validationErrors: response.context.validationErrors
44
+ });
45
+ break;
46
+ case "contentInventory":
47
+ console.log({
48
+ languageId: response.context.languageId,
49
+ itemListingFilter: response.context.itemListingFilter,
50
+ itemListingSelection: response.context.itemListingSelection
51
+ });
52
+ break;
53
+ }
38
54
  }
39
55
  ```
40
56
 
@@ -42,38 +58,233 @@ if (response.isError) {
42
58
 
43
59
  ### getCustomAppContext
44
60
 
45
- Use the `getCustomAppContext` function to retrieve context of the custom app. The function takes no arguments and returns a promise with a value of an object of type `CustomAppContext`.
61
+ Retrieves the context of the custom app. The function takes no arguments and automatically detects the current page type, returning the appropriate context with all relevant properties for that page.
46
62
 
47
- #### CustomAppContext
63
+ #### Return Type
64
+
65
+ Returns a promise that resolves to a discriminated union type with two possible states:
66
+
67
+ ##### Success Response (`isError: false`)
48
68
 
49
69
  | Property | Type | Description |
50
70
  |---------------|------------------------|------------------------------------------------------------------------------|
51
- | `isError` | boolean | Determines if there was an error while getting the context of the custom app |
52
- | `code` | ErrorCode enum \| null | The code of the error message |
53
- | `description` | string \| null | The description of the error message |
54
- | `context` | object \| null | Contains data provided by the Kontent.ai application |
55
- | `config` | object \| null | Contains JSON object specified in the custom app configuration |
71
+ | `isError` | `false` | Indicates the request was successful |
72
+ | `context` | `CustomAppContext` | A discriminated union of page-specific context objects |
73
+
74
+ ##### Error Response (`isError: true`)
75
+
76
+ | Property | Type | Description |
77
+ |---------------|------------------------|------------------------------------------------------------------------------|
78
+ | `isError` | `true` | Indicates an error occurred |
79
+ | `code` | ErrorCode enum | The code of the error message |
80
+ | `description` | string | The description of the error message |
81
+
82
+ #### CustomAppContext
83
+
84
+ `CustomAppContext` is a discriminated union type based on the `currentPage` property. Each page type includes only the relevant properties for that specific page:
85
+
86
+ ##### Shared Properties
56
87
 
57
- #### Config
58
- The `config` object is a JSON object that can be defined within the Custom App configuration under Environment settings in the Kontent.ai app.
88
+ All context types include the following shared properties:
59
89
 
60
- #### Context
61
- The `context` object contains data provided by the Kontent.ai application that you can leverage in your custom app.
90
+ | Property | Type | Description |
91
+ |-------------------------|---------------------------------------|----------------------------------------------------------------------|
92
+ | `environmentId` | UUID | The environment's ID |
93
+ | `userId` | string | The current user's ID |
94
+ | `userEmail` | string | The current user's email |
95
+ | `userRoles` | Array\<UserRole\> | An array containing all the roles of the current user in the environment |
96
+ | `path` | string | The current path within the Kontent.ai application |
97
+ | `pageTitle` | string | The title of the current page |
98
+ | `appConfig` | unknown \| undefined | JSON object specified in the custom app configuration |
62
99
 
63
- | Property | Type | Description |
64
- |-----------------|-------------------|--------------------------------------------------------------------------|
65
- | `environmentId` | UUID | The environment's ID |
66
- | `userId` | string | The current user's ID |
67
- | `userEmail` | string | The current user's email |
68
- | `userRoles` | Array of UserRole | An array containing all the roles of the current user in the environment |
100
+ ##### Item Editor Page Context
69
101
 
70
- #### UserRole
102
+ When `currentPage` is `"itemEditor"`, the context includes the shared properties above plus:
103
+
104
+ | Property | Type | Description |
105
+ |-------------------------|---------------------------------------|----------------------------------------------------------------------|
106
+ | `currentPage` | `"itemEditor"` | Identifies this as an item editor page |
107
+ | `contentItemId` | UUID | The ID of the content item being edited |
108
+ | `languageId` | UUID | The ID of the current language |
109
+ | `validationErrors` | Record<string, Array<string>> | A record of validation errors for content item fields |
110
+
111
+ ##### Content Inventory Page Context
112
+
113
+ When `currentPage` is `"contentInventory"`, the context includes the shared properties above plus:
114
+
115
+ | Property | Type | Description |
116
+ |-------------------------|---------------------------------------|----------------------------------------------------------------------|
117
+ | `currentPage` | `"contentInventory"` | Identifies this as a content inventory (item listing) page |
118
+ | `languageId` | UUID | The ID of the current language |
119
+ | `itemListingFilter` | SerializedListingFilter | The current filter settings applied to the content item listing |
120
+ | `itemListingSelection` | ItemListingSelection | The current selection state of items in the listing |
121
+
122
+ ##### Other Page Context
123
+
124
+ When `currentPage` is `"other"`, the context includes the shared properties above plus:
125
+
126
+ | Property | Type | Description |
127
+ |-------------------------|---------------------------------------|----------------------------------------------------------------------|
128
+ | `currentPage` | `"other"` | Identifies this as any other page type |
129
+
130
+ #### UserRole
71
131
 
72
132
  | Property | Type | Description |
73
133
  |------------|--------|----------------------------------------------------------------------|
74
134
  | `id` | UUID | The role's ID |
75
135
  | `codename` | string | The role's codename - applicable only for the _Project manager_ role |
76
136
 
137
+ #### SerializedListingFilter
138
+
139
+ The filter settings applied to the content item listing.
140
+
141
+ | Property | Type | Description |
142
+ |-----------------------------|-----------------------------------------------------|--------------------------------------------------------------|
143
+ | `selectedCollections` | Array\<string\> | IDs of collections selected in the filter |
144
+ | `selectedContentItemStatus` | Array\<VariantCompletionStatus\> | Selected content item workflow status states |
145
+ | `selectedContentTypes` | Array\<string\> | IDs of content types selected in the filter |
146
+ | `selectedContributors` | Array\<string\> | IDs of contributors selected in the filter |
147
+ | `selectedPublishingStates` | Array\<PublishingState\> | Selected publishing states |
148
+ | `selectedSpaces` | Array\<string\> | IDs of spaces selected in the filter |
149
+ | `selectedTaxonomies` | Record\<string, Array\<string\>\> | Selected taxonomy terms grouped by taxonomy ID |
150
+ | `selectedWorkflows` | Record\<string, Array\<string\>\> | Selected workflow steps grouped by workflow ID |
151
+ | `searchPhrase` | string | The search phrase entered by the user |
152
+ | `searchScope` | Array\<string\> | The scope of the search (e.g., content item names, elements) |
153
+
154
+ ##### VariantCompletionStatus
155
+
156
+ An enum representing the possible workflow completion status states for content item variants.
157
+
158
+ | Value | Description |
159
+ |------------------|------------------------------------------------|
160
+ | `"unfinished"` | Content item variant is unfinished |
161
+ | `"ready"` | Content item variant is ready |
162
+ | `"notTranslated"`| Content item variant is not translated |
163
+ | `"allDone"` | Content item variant is all done |
164
+
165
+ ##### PublishingState
166
+
167
+ An enum representing the possible publishing states for content items.
168
+
169
+ | Value | Description |
170
+ |----------------|---------------------------------------------------|
171
+ | `"published"` | Content item is published |
172
+ | `"unpublished"`| Content item is unpublished |
173
+ | `"none"` | Content item has no publishing state |
174
+
175
+ #### ItemListingSelection
176
+
177
+ The current selection state of items in the content inventory listing.
178
+
179
+ | Property | Type | Description |
180
+ |-----------------------|----------------|----------------------------------------------------------------------------------|
181
+ | `selectAll` | boolean | Whether the "select all" option is active |
182
+ | `selectedItemIds` | Array\<UUID\> | IDs of content items that are selected (when `selectAll` is false, these are the selected items; when `selectAll` is true, these are exceptions to the selection) |
183
+ | `unselectedItemIds` | Array\<UUID\> | IDs of content items that are explicitly unselected (used when `selectAll` is true to exclude specific items) |
184
+
185
+ ### observeCustomAppContext
186
+
187
+ Subscribes to context changes and receives notifications when the context is updated. The function takes a callback that will be invoked whenever the context changes.
188
+
189
+ #### Parameters
190
+
191
+ | Parameter | Type | Description |
192
+ |------------|-----------------------------|-------------------------------------------------------|
193
+ | `callback` | `(context: CustomAppContext) => void` | Function to be called when the context changes |
194
+
195
+ #### Return Type
196
+
197
+ Returns a promise that resolves to a discriminated union type with two possible states:
198
+
199
+ ##### Success Response (`isError: false`)
200
+
201
+ | Property | Type | Description |
202
+ |---------------|------------------------|------------------------------------------------------------------------------|
203
+ | `isError` | `false` | Indicates the request was successful |
204
+ | `context` | `CustomAppContext` | The initial context value |
205
+ | `unsubscribe` | `() => Promise<void>` | Function to call to stop receiving context updates |
206
+
207
+ ##### Error Response (`isError: true`)
208
+
209
+ | Property | Type | Description |
210
+ |---------------|------------------------|------------------------------------------------------------------------------|
211
+ | `isError` | `true` | Indicates an error occurred |
212
+ | `code` | ErrorCode enum | The code of the error message |
213
+ | `description` | string | The description of the error message |
214
+
215
+ #### Usage Example
216
+
217
+ ```typescript
218
+ import { observeCustomAppContext } from "@kontent-ai/custom-app-sdk";
219
+
220
+ const response = await observeCustomAppContext((context) => {
221
+ console.log("Context updated:", context);
222
+ });
223
+
224
+ if (response.isError) {
225
+ console.error({ errorCode: response.code, description: response.description });
226
+ } else {
227
+ console.log("Initial context:", response.context);
228
+
229
+ // Later, when you want to stop observing
230
+ await response.unsubscribe();
231
+ }
232
+ ```
233
+
234
+ ### setPopupSize
235
+
236
+ Sets the size of the popup window when the custom app is displayed in a popup.
237
+
238
+ #### Parameters
239
+
240
+ | Parameter | Type | Description |
241
+ |-----------|----------------------|--------------------------------------------------|
242
+ | `width` | `PopupSizeDimension` | The desired width of the popup |
243
+ | `height` | `PopupSizeDimension` | The desired height of the popup |
244
+
245
+ #### PopupSizeDimension
246
+
247
+ A discriminated union type for specifying dimensions in either pixels or percentages:
248
+
249
+ ```typescript
250
+ type PopupSizeDimension =
251
+ | { unit: "px"; value: number }
252
+ | { unit: "%"; value: number };
253
+ ```
254
+
255
+ #### Return Type
256
+
257
+ Returns a promise that resolves to a discriminated union type with two possible states:
258
+
259
+ ##### Success Response (`isError: false`)
260
+
261
+ | Property | Type | Description |
262
+ |---------------|------------------------|------------------------------------------------------------------------------|
263
+ | `isError` | `false` | Indicates the request was successful |
264
+
265
+ ##### Error Response (`isError: true`)
266
+
267
+ | Property | Type | Description |
268
+ |---------------|------------------------|------------------------------------------------------------------------------|
269
+ | `isError` | `true` | Indicates an error occurred |
270
+ | `code` | ErrorCode enum | The code of the error message |
271
+ | `description` | string | The description of the error message |
272
+
273
+ #### Usage Example
274
+
275
+ ```typescript
276
+ import { setPopupSize } from "@kontent-ai/custom-app-sdk";
277
+
278
+ const response = await setPopupSize(
279
+ { unit: "px", value: 800 },
280
+ { unit: "%", value: 90 }
281
+ );
282
+
283
+ if (response.isError) {
284
+ console.error({ errorCode: response.code, description: response.description });
285
+ }
286
+ ```
287
+
77
288
  ## Contributing
78
289
 
79
290
  For Contributing please see <a href="./CONTRIBUTING.md">`CONTRIBUTING.md`</a> for more information.
@@ -0,0 +1,19 @@
1
+ import type { CustomAppContextProperties } from "./iframeSchema";
2
+ declare const itemEditorContextProperties: readonly ["path", "pageTitle", "environmentId", "userId", "userEmail", "userRoles", "appConfig", "contentItemId", "languageId", "validationErrors", "currentPage"];
3
+ type RawItemEditorContext = Pick<CustomAppContextProperties, (typeof itemEditorContextProperties)[number]>;
4
+ export type ItemEditorContext = Required<WithSpecificPage<CustomAppContextProperties, "itemEditor">>;
5
+ export declare const isItemEditorContext: (context: RawItemEditorContext) => context is ItemEditorContext;
6
+ declare const itemListingContextProperties: readonly ["path", "pageTitle", "environmentId", "userId", "userEmail", "userRoles", "appConfig", "languageId", "itemListingFilter", "itemListingSelection", "currentPage"];
7
+ type RawItemListingContext = Pick<CustomAppContextProperties, (typeof itemListingContextProperties)[number]>;
8
+ export type ItemListingContext = Required<WithSpecificPage<CustomAppContextProperties, "contentInventory">>;
9
+ export declare const isItemListingContext: (context: RawItemListingContext) => context is ItemListingContext;
10
+ declare const otherContextProperties: readonly ["path", "pageTitle", "environmentId", "userId", "userEmail", "userRoles", "appConfig", "currentPage"];
11
+ type RawOtherContext = Pick<CustomAppContextProperties, (typeof otherContextProperties)[number]>;
12
+ export type OtherContext = Required<WithSpecificPage<CustomAppContextProperties, "other">>;
13
+ export declare const isOtherContext: (context: RawOtherContext) => context is OtherContext;
14
+ export type Context = ItemEditorContext | ItemListingContext | OtherContext;
15
+ type WithSpecificPage<T extends CustomAppContextProperties, Page extends Context["currentPage"]> = T & {
16
+ readonly currentPage: Page;
17
+ };
18
+ export declare const getContextPropertiesForPage: (currentPage: Context["currentPage"] | undefined) => ReadonlyArray<keyof CustomAppContextProperties>;
19
+ export {};
@@ -0,0 +1,61 @@
1
+ const sharedContextProperties = [
2
+ "path",
3
+ "pageTitle",
4
+ "environmentId",
5
+ "userId",
6
+ "userEmail",
7
+ "userRoles",
8
+ "appConfig",
9
+ ];
10
+ const itemEditorContextProperties = [
11
+ ...sharedContextProperties,
12
+ "contentItemId",
13
+ "languageId",
14
+ "validationErrors",
15
+ "currentPage",
16
+ ];
17
+ const optionalProperties = [
18
+ "appConfig",
19
+ ];
20
+ export const isItemEditorContext = (context) => {
21
+ return (context.currentPage === "itemEditor" &&
22
+ itemEditorContextProperties
23
+ .filter((property) => !optionalProperties.includes(property))
24
+ .every((property) => property in context && context[property] !== undefined));
25
+ };
26
+ const itemListingContextProperties = [
27
+ ...sharedContextProperties,
28
+ "languageId",
29
+ "itemListingFilter",
30
+ "itemListingSelection",
31
+ "currentPage",
32
+ ];
33
+ export const isItemListingContext = (context) => {
34
+ return (context.currentPage === "contentInventory" &&
35
+ itemListingContextProperties
36
+ .filter((property) => !optionalProperties.includes(property))
37
+ .every((property) => property in context && context[property] !== undefined));
38
+ };
39
+ const otherContextProperties = [
40
+ ...sharedContextProperties,
41
+ "currentPage",
42
+ ];
43
+ export const isOtherContext = (context) => {
44
+ return (context.currentPage === "other" &&
45
+ otherContextProperties
46
+ .filter((property) => !optionalProperties.includes(property))
47
+ .every((property) => property in context && context[property] !== undefined));
48
+ };
49
+ export const getContextPropertiesForPage = (currentPage) => {
50
+ switch (currentPage) {
51
+ case "itemEditor":
52
+ return itemEditorContextProperties;
53
+ case "contentInventory":
54
+ return itemListingContextProperties;
55
+ case "other":
56
+ return otherContextProperties;
57
+ case undefined:
58
+ return [];
59
+ }
60
+ };
61
+ //# sourceMappingURL=contexts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contexts.js","sourceRoot":"","sources":["../src/contexts.ts"],"names":[],"mappings":"AAEA,MAAM,uBAAuB,GAAG;IAC9B,MAAM;IACN,WAAW;IACX,eAAe;IACf,QAAQ;IACR,WAAW;IACX,WAAW;IACX,WAAW;CACuD,CAAC;AAErE,MAAM,2BAA2B,GAAG;IAClC,GAAG,uBAAuB;IAC1B,eAAe;IACf,YAAY;IACZ,kBAAkB;IAClB,aAAa;CACqD,CAAC;AAErE,MAAM,kBAAkB,GAAoD;IAC1E,WAAW;CACuD,CAAC;AAWrE,MAAM,CAAC,MAAM,mBAAmB,GAAG,CACjC,OAA6B,EACC,EAAE;IAChC,OAAO,CACL,OAAO,CAAC,WAAW,KAAK,YAAY;QACpC,2BAA2B;aACxB,MAAM,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,kBAAkB,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;aAC5D,KAAK,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,IAAI,OAAO,IAAI,OAAO,CAAC,QAAQ,CAAC,KAAK,SAAS,CAAC,CAC/E,CAAC;AACJ,CAAC,CAAC;AAEF,MAAM,4BAA4B,GAAG;IACnC,GAAG,uBAAuB;IAC1B,YAAY;IACZ,mBAAmB;IACnB,sBAAsB;IACtB,aAAa;CACqD,CAAC;AAWrE,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAClC,OAA8B,EACC,EAAE;IACjC,OAAO,CACL,OAAO,CAAC,WAAW,KAAK,kBAAkB;QAC1C,4BAA4B;aACzB,MAAM,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,kBAAkB,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;aAC5D,KAAK,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,IAAI,OAAO,IAAI,OAAO,CAAC,QAAQ,CAAC,KAAK,SAAS,CAAC,CAC/E,CAAC;AACJ,CAAC,CAAC;AAEF,MAAM,sBAAsB,GAAG;IAC7B,GAAG,uBAAuB;IAC1B,aAAa;CACqD,CAAC;AAMrE,MAAM,CAAC,MAAM,cAAc,GAAG,CAAC,OAAwB,EAA2B,EAAE;IAClF,OAAO,CACL,OAAO,CAAC,WAAW,KAAK,OAAO;QAC/B,sBAAsB;aACnB,MAAM,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,kBAAkB,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;aAC5D,KAAK,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,IAAI,OAAO,IAAI,OAAO,CAAC,QAAQ,CAAC,KAAK,SAAS,CAAC,CAC/E,CAAC;AACJ,CAAC,CAAC;AASF,MAAM,CAAC,MAAM,2BAA2B,GAAG,CACzC,WAA+C,EACE,EAAE;IACnD,QAAQ,WAAW,EAAE,CAAC;QACpB,KAAK,YAAY;YACf,OAAO,2BAA2B,CAAC;QACrC,KAAK,kBAAkB;YACrB,OAAO,4BAA4B,CAAC;QACtC,KAAK,OAAO;YACV,OAAO,sBAAsB,CAAC;QAChC,KAAK,SAAS;YACZ,OAAO,EAAE,CAAC;IACd,CAAC;AACH,CAAC,CAAC"}
@@ -1,21 +1,33 @@
1
+ import { type Context } from "./contexts";
2
+ import { PublishingState, type SerializedListingFilter, type Uuid, VariantCompletionStatus } from "./iframeSchema";
3
+ export { PublishingState, VariantCompletionStatus };
4
+ export type { SerializedListingFilter, Uuid };
1
5
  export declare enum ErrorCode {
2
- UnknownMessage = "unknown-message"
6
+ UnknownMessage = "unknown-message",
7
+ NotSupported = "not-supported",
8
+ OutdatedContext = "outdated-context"
3
9
  }
4
- export type CustomAppContext = {
5
- readonly isError: false;
6
- readonly context: {
7
- readonly environmentId: string;
8
- readonly userId: string;
9
- readonly userEmail: string;
10
- readonly userRoles: ReadonlyArray<{
11
- readonly id: string;
12
- readonly codename: string | null;
13
- }>;
14
- };
15
- readonly config?: unknown;
10
+ export declare const getCustomAppContext: () => Promise<Result<{
11
+ readonly context: Context;
12
+ }>>;
13
+ export type PopupSizeDimension = {
14
+ readonly unit: "px";
15
+ readonly value: number;
16
16
  } | {
17
- readonly isError: true;
18
- readonly code: ErrorCode;
19
- readonly description: string;
17
+ readonly unit: "%";
18
+ readonly value: number;
19
+ };
20
+ export declare const setPopupSize: (width: PopupSizeDimension, height: PopupSizeDimension) => Promise<Result<{
21
+ readonly isError: false;
22
+ }>>;
23
+ export declare const observeCustomAppContext: (callback: (context: Context) => void) => Promise<Result<{
24
+ readonly context: Context;
25
+ readonly unsubscribe: () => Promise<void>;
26
+ }>>;
27
+ type Result<T> = ({
28
+ isError: false;
29
+ } & T) | {
30
+ isError: true;
31
+ code: ErrorCode;
32
+ description: string;
20
33
  };
21
- export declare const getCustomAppContext: () => Promise<CustomAppContext>;
@@ -1,27 +1,147 @@
1
- import { sendMessage } from "./iframeMessenger";
2
- import { ErrorMessage } from "./iframeSchema";
1
+ import { getContextPropertiesForPage, isItemEditorContext, isItemListingContext, isOtherContext, } from "./contexts";
2
+ import { addNotificationCallback, removeNotificationCallback, sendMessage, } from "./iframeMessenger";
3
+ import { ErrorMessage, PublishingState, VariantCompletionStatus, } from "./iframeSchema";
3
4
  import { matchesSchema } from "./matchesSchema";
5
+ export { PublishingState, VariantCompletionStatus };
4
6
  export var ErrorCode;
5
7
  (function (ErrorCode) {
6
8
  ErrorCode["UnknownMessage"] = "unknown-message";
9
+ ErrorCode["NotSupported"] = "not-supported";
10
+ ErrorCode["OutdatedContext"] = "outdated-context";
7
11
  })(ErrorCode || (ErrorCode = {}));
8
- export const getCustomAppContext = () => new Promise((resolve, reject) => {
9
- try {
10
- sendMessage({
11
- type: "get-context-request",
12
+ export const getCustomAppContext = async () => {
13
+ const currentPageResponse = await sendMessage({
14
+ type: "get-context-request",
15
+ version: "2.0.0",
16
+ payload: {
17
+ properties: ["currentPage"],
18
+ },
19
+ });
20
+ if (matchesSchema(ErrorMessage, currentPageResponse)) {
21
+ return {
22
+ isError: true,
23
+ code: currentPageResponse.code,
24
+ description: currentPageResponse.description,
25
+ };
26
+ }
27
+ const currentPage = currentPageResponse.payload.properties.currentPage;
28
+ const propertiesToFetch = getContextPropertiesForPage(currentPage);
29
+ const response = await sendMessage({
30
+ type: "get-context-request",
31
+ version: "2.0.0",
32
+ payload: {
33
+ properties: propertiesToFetch,
34
+ },
35
+ });
36
+ if (matchesSchema(ErrorMessage, response)) {
37
+ return { isError: true, code: response.code, description: response.description };
38
+ }
39
+ return getContextFromProperties(response.payload.properties);
40
+ };
41
+ export const setPopupSize = async (width, height) => {
42
+ const response = await sendMessage({
43
+ type: "set-popup-size-request",
44
+ version: "1.0.0",
45
+ payload: {
46
+ width,
47
+ height,
48
+ },
49
+ });
50
+ if (matchesSchema(ErrorMessage, response)) {
51
+ return { isError: true, code: response.code, description: response.description };
52
+ }
53
+ return { isError: false };
54
+ };
55
+ const outdatedContextError = {
56
+ isError: true,
57
+ code: ErrorCode.OutdatedContext,
58
+ description: "The context we received is outdated, please try to get the context again.",
59
+ };
60
+ export const observeCustomAppContext = async (callback) => {
61
+ const currentPageResponse = await sendMessage({
62
+ type: "get-context-request",
63
+ version: "2.0.0",
64
+ payload: {
65
+ properties: ["currentPage"],
66
+ },
67
+ });
68
+ if (matchesSchema(ErrorMessage, currentPageResponse)) {
69
+ return {
70
+ isError: true,
71
+ code: currentPageResponse.code,
72
+ description: currentPageResponse.description,
73
+ };
74
+ }
75
+ const currentPage = currentPageResponse.payload.properties.currentPage;
76
+ const propertiesToObserve = getContextPropertiesForPage(currentPage);
77
+ const observeResponse = await sendMessage({
78
+ type: "observe-context-request",
79
+ version: "1.0.0",
80
+ payload: {
81
+ properties: propertiesToObserve,
82
+ },
83
+ });
84
+ if (matchesSchema(ErrorMessage, observeResponse)) {
85
+ return { isError: true, code: observeResponse.code, description: observeResponse.description };
86
+ }
87
+ const initialContextResponse = await sendMessage({
88
+ type: "get-context-request",
89
+ version: "2.0.0",
90
+ payload: {
91
+ properties: propertiesToObserve,
92
+ },
93
+ });
94
+ if (matchesSchema(ErrorMessage, initialContextResponse)) {
95
+ return {
96
+ isError: true,
97
+ code: initialContextResponse.code,
98
+ description: initialContextResponse.description,
99
+ };
100
+ }
101
+ const initialContext = getContextFromProperties(initialContextResponse.payload.properties);
102
+ if (initialContext.isError) {
103
+ return initialContext;
104
+ }
105
+ const notificationHandler = (notification) => {
106
+ const contextResult = getContextFromProperties(notification.payload.properties);
107
+ if (!contextResult.isError) {
108
+ callback(contextResult.context);
109
+ }
110
+ };
111
+ addNotificationCallback(observeResponse.payload.subscriptionId, notificationHandler);
112
+ const unsubscribe = async () => {
113
+ removeNotificationCallback(observeResponse.payload.subscriptionId);
114
+ await sendMessage({
115
+ type: "unsubscribe-context-request",
12
116
  version: "1.0.0",
13
- payload: null,
14
- }, (response) => {
15
- if (matchesSchema(ErrorMessage, response)) {
16
- resolve({ isError: true, code: response.code, description: response.description });
17
- }
18
- else {
19
- resolve({ ...response.payload, isError: false });
20
- }
117
+ payload: {
118
+ subscriptionId: observeResponse.payload.subscriptionId,
119
+ },
21
120
  });
121
+ };
122
+ return {
123
+ isError: false,
124
+ context: initialContext.context,
125
+ unsubscribe,
126
+ };
127
+ };
128
+ const getContextFromProperties = (properties) => {
129
+ const currentPage = properties.currentPage;
130
+ switch (currentPage) {
131
+ case "itemEditor":
132
+ return isItemEditorContext(properties)
133
+ ? { isError: false, context: properties }
134
+ : outdatedContextError;
135
+ case "contentInventory":
136
+ return isItemListingContext(properties)
137
+ ? { isError: false, context: properties }
138
+ : outdatedContextError;
139
+ case "other":
140
+ return isOtherContext(properties)
141
+ ? { isError: false, context: properties }
142
+ : outdatedContextError;
143
+ default:
144
+ return outdatedContextError;
22
145
  }
23
- catch (error) {
24
- reject(error);
25
- }
26
- });
146
+ };
27
147
  //# sourceMappingURL=customAppSdk.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"customAppSdk.js","sourceRoot":"","sources":["../src/customAppSdk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAEhD,MAAM,CAAN,IAAY,SAEX;AAFD,WAAY,SAAS;IACnB,+CAAkC,CAAA;AACpC,CAAC,EAFW,SAAS,KAAT,SAAS,QAEpB;AAsBD,MAAM,CAAC,MAAM,mBAAmB,GAAG,GAA8B,EAAE,CACjE,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;IAC9B,IAAI,CAAC;QACH,WAAW,CACT;YACE,IAAI,EAAE,qBAAqB;YAC3B,OAAO,EAAE,OAAO;YAChB,OAAO,EAAE,IAAI;SACd,EACD,CAAC,QAAQ,EAAE,EAAE;YACX,IAAI,aAAa,CAAC,YAAY,EAAE,QAAQ,CAAC,EAAE,CAAC;gBAC1C,OAAO,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,QAAQ,CAAC,IAAI,EAAE,WAAW,EAAE,QAAQ,CAAC,WAAW,EAAE,CAAC,CAAC;YACrF,CAAC;iBAAM,CAAC;gBACN,OAAO,CAAC,EAAE,GAAG,QAAQ,CAAC,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC;YACnD,CAAC;QACH,CAAC,CACF,CAAC;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,CAAC,KAAK,CAAC,CAAC;IAChB,CAAC;AACH,CAAC,CAAC,CAAC"}
1
+ {"version":3,"file":"customAppSdk.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EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,UAAU,EAAE;gBACzC,CAAC,CAAC,oBAAoB,CAAC;QAC3B;YACE,OAAO,oBAAoB,CAAC;IAChC,CAAC;AACH,CAAC,CAAC"}
@@ -1,2 +1,5 @@
1
- import type { Schema } from "./iframeSchema";
2
- export declare const sendMessage: <TMessageType extends keyof Schema["client"]>(message: Omit<Schema["client"][TMessageType]["request"], "requestId">, callback: (data: Schema["client"][TMessageType]["response"]) => void) => void;
1
+ import type { z } from "zod";
2
+ import type { ClientContextChangedV1Notification, Schema } from "./iframeSchema";
3
+ export declare const sendMessage: <TMessageType extends keyof Schema["client"]>(message: Omit<Schema["client"][TMessageType]["request"], "requestId">) => Promise<Schema["client"][TMessageType]["response"]>;
4
+ export declare const addNotificationCallback: (subscriptionId: string, callback: (notification: z.infer<typeof ClientContextChangedV1Notification>) => void) => void;
5
+ export declare const removeNotificationCallback: (subscriptionId: string) => void;