@15gifts/sdk 0.19.0 → 0.20.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/dist/index.d.mts CHANGED
@@ -6,6 +6,23 @@ import { Client as Client$1, ClientOptions, Middleware } from 'openapi-fetch';
6
6
  * Do not make direct changes to the file.
7
7
  */
8
8
  interface paths$1 {
9
+ '/api/conversation/{conversation_id}/v1': {
10
+ parameters: {
11
+ query?: never;
12
+ header?: never;
13
+ path?: never;
14
+ cookie?: never;
15
+ };
16
+ /** Get Conversation */
17
+ get: operations['get_conversation_api_conversation__conversation_id__v1_get'];
18
+ put?: never;
19
+ post?: never;
20
+ delete?: never;
21
+ options?: never;
22
+ head?: never;
23
+ patch?: never;
24
+ trace?: never;
25
+ };
9
26
  '/api/conversation/v3': {
10
27
  parameters: {
11
28
  query?: never;
@@ -516,6 +533,23 @@ interface components {
516
533
  * @enum {string}
517
534
  */
518
535
  ExitToHumanReason: 'WANT_TO_TALK_TO_HUMAN' | 'OUT_OF_SCOPE_QUESTIONS' | 'NOT_BEHAVING_CORRECTLY';
536
+ /**
537
+ * GetConversationResponse
538
+ * @description Response model for the get conversation endpoint
539
+ */
540
+ GetConversationResponse: components['schemas']['GetConversationTurn'][];
541
+ /** GetConversationTurn */
542
+ GetConversationTurn: {
543
+ /** Usermessage */
544
+ userMessage: components['schemas']['UserTextMessage'] | components['schemas']['UserSingleSelectMessage'] | components['schemas']['UserMultiSelectMessage'] | components['schemas']['UserStartConversationMessage'];
545
+ /** Assistantmessages */
546
+ assistantMessages: (components['schemas']['AssistantTextMessage'] | components['schemas']['AssistantSingleSelectMessage'] | components['schemas']['AssistantMultiSelectMessage'] | components['schemas']['AssistantExitToChatMessage'] | components['schemas']['AssistantExitToPhoneMessage'] | components['schemas']['AssistantRecommendationMessage'] | components['schemas']['AssistantRecommendationMessageV2'] | components['schemas']['AssistantConversationIdMessage'] | components['schemas']['AssistantExitToPurchaseMessage'] | components['schemas']['AssistantExitToPurchaseMessageV2'])[];
547
+ };
548
+ /** HTTPValidationError */
549
+ HTTPValidationError: {
550
+ /** Detail */
551
+ detail?: components['schemas']['ValidationError'][];
552
+ };
519
553
  /** HeaderDetails */
520
554
  HeaderDetails: {
521
555
  /**
@@ -867,6 +901,15 @@ interface components {
867
901
  */
868
902
  userMessage: string;
869
903
  };
904
+ /** ValidationError */
905
+ ValidationError: {
906
+ /** Location */
907
+ loc: (string | number)[];
908
+ /** Message */
909
+ msg: string;
910
+ /** Error Type */
911
+ type: string;
912
+ };
870
913
  };
871
914
  responses: never;
872
915
  parameters: never;
@@ -875,6 +918,55 @@ interface components {
875
918
  pathItems: never;
876
919
  }
877
920
  interface operations {
921
+ get_conversation_api_conversation__conversation_id__v1_get: {
922
+ parameters: {
923
+ query?: never;
924
+ header?: never;
925
+ path: {
926
+ conversation_id: string;
927
+ };
928
+ cookie?: {
929
+ conversation_session_id?: string | null;
930
+ };
931
+ };
932
+ requestBody?: never;
933
+ responses: {
934
+ /** @description A successful response from the conversation service */
935
+ 200: {
936
+ headers: {
937
+ [name: string]: unknown;
938
+ };
939
+ content: {
940
+ 'application/json': components['schemas']['GetConversationResponse'];
941
+ };
942
+ };
943
+ /** @description The user does not have permission to access the requested conversation */
944
+ 403: {
945
+ headers: {
946
+ [name: string]: unknown;
947
+ };
948
+ content: {
949
+ /**
950
+ * @example {
951
+ * "code": "ERROR_UNHANDLED",
952
+ * "message": "An error occurred",
953
+ * "detail": "Access forbidden"
954
+ * }
955
+ */
956
+ 'application/json': unknown;
957
+ };
958
+ };
959
+ /** @description Validation Error */
960
+ 422: {
961
+ headers: {
962
+ [name: string]: unknown;
963
+ };
964
+ content: {
965
+ 'application/json': components['schemas']['HTTPValidationError'];
966
+ };
967
+ };
968
+ };
969
+ };
878
970
  generate_conversation_response_api_conversation_v3_post: {
879
971
  parameters: {
880
972
  query?: never;
@@ -1449,6 +1541,10 @@ interface Identity {
1449
1541
  * The pageview ID.
1450
1542
  */
1451
1543
  pageviewId?: string;
1544
+ /**
1545
+ * The identity token.
1546
+ */
1547
+ token?: string;
1452
1548
  /**
1453
1549
  * The session ID associated with the user.
1454
1550
  */
@@ -1463,6 +1559,29 @@ interface Identity {
1463
1559
  * Note that the API response may contain additional types that the SDK does not return.
1464
1560
  */
1465
1561
  type Message = ExitToChatMessage | ExitToPhoneMessage | ExitToPurchaseMessage | ExitToPurchaseV2Message | MultiSelectMessage | RecommendationMessage | RecommendationV2Message | SingleSelectMessage | TextMessage;
1562
+ /**
1563
+ * A conversation turn as returned by the raw API response.
1564
+ */
1565
+ type ConversationResponse = components['schemas']['GetConversationResponse'];
1566
+ type ConversationTurn = ConversationResponse[number];
1567
+ /**
1568
+ * A restored conversation turn returned by `client.getConversation()`.
1569
+ * It has been transformed from the raw API response to be more suitable for rendering in the UI.
1570
+ */
1571
+ interface RestoredTurn {
1572
+ /**
1573
+ * A stable client-side identifier for the restored turn.
1574
+ */
1575
+ id: string;
1576
+ /**
1577
+ * The user message text to render for this turn.
1578
+ */
1579
+ userMessage: Omit<UserTextMessage, 'conversationId'> | Omit<UserSingleSelectMessage, 'conversationId'> | Omit<UserMultiSelectMessage, 'conversationId'>;
1580
+ /**
1581
+ * The assistant messages to render for this turn.
1582
+ */
1583
+ assistantReply: Message[];
1584
+ }
1466
1585
  interface ConversationIdMessage extends ApiConversationIdMessage {
1467
1586
  }
1468
1587
  interface ExitToChatMessage extends ApiExitToChatMessage {
@@ -1601,7 +1720,30 @@ declare class Client {
1601
1720
  type: "EXIT_TO_PURCHASE";
1602
1721
  fallbackMessage: string;
1603
1722
  recommendationIdForExit?: string | null;
1604
- products: components["schemas"]["Product"][];
1723
+ products: components["schemas"] /**
1724
+ * Clears the existing conversation ID, then generates a new one and returns the opening message.
1725
+ *
1726
+ * @param context - Optional context to customize the conversation. It can include:
1727
+ * @param context.eligibleProducts An array of eligible product IDs.
1728
+ * @param context.eligibleBundles An array of eligible bundle IDs.
1729
+ * @param context.productOverrides Overrides for product details.
1730
+ * @param context.bundleOverrides Overrides for bundle details.
1731
+ *
1732
+ * @returns A promise that resolves to the opening message.
1733
+ *
1734
+ * @example
1735
+ * ##### Basic usage
1736
+ * ```ts
1737
+ * const openingMessage = await client.startConversation()
1738
+ * console.log('Opening message:', openingMessage)
1739
+ * ```
1740
+ *
1741
+ * ##### With context
1742
+ * ```ts
1743
+ * const openingMessage = await client.startConversation({ eligibleProducts: ['product-1', 'product-2'], productOverrides: { 'product-1': { price: 40 } })
1744
+ * console.log('Opening message:', openingMessage)
1745
+ * ```
1746
+ */["Product"][];
1605
1747
  bundles: components["schemas"]["Bundle"][];
1606
1748
  offers: components["schemas"]["Offer"][];
1607
1749
  } | {
@@ -1649,15 +1791,7 @@ declare class Client {
1649
1791
  trackEvent(eventName: TrackingEvent['eventName'], properties?: TrackingEvent['additionalProperties']): Promise<openapi_fetch.FetchResponse<{
1650
1792
  parameters: {
1651
1793
  query?: never;
1652
- header? /**
1653
- * Ends the current conversation by deleting the conversation ID.
1654
- *
1655
- * @example
1656
- * ```ts
1657
- * client.endConversation()
1658
- * console.log('Conversation ended')
1659
- * ```
1660
- */: never;
1794
+ header?: never;
1661
1795
  path?: never;
1662
1796
  cookie?: never;
1663
1797
  };
@@ -1747,6 +1881,8 @@ declare class Client {
1747
1881
  getIdentity(): Identity;
1748
1882
  /**
1749
1883
  * Gets the JWT from the localStorage.
1884
+ * Use this method to retrieve the token for use in other parts of your system,
1885
+ * such as calling the Humara sales tracking API
1750
1886
  *
1751
1887
  * @returns {string | null} the JWT.
1752
1888
  *
@@ -1757,166 +1893,15 @@ declare class Client {
1757
1893
  * ```
1758
1894
  */
1759
1895
  getIdentityToken(): string | null;
1896
+ /**
1897
+ * Gets the conversation history for a given conversation ID.
1898
+ *
1899
+ * @param conversationId - The ID of the conversation to retrieve.
1900
+ * @returns A promise that resolves to the conversation history as an array of turns. Each turn contains a user message and its corresponding response.
1901
+ */
1902
+ getConversation(conversationId: string): Promise<RestoredTurn[]>;
1760
1903
  }
1761
1904
 
1762
- /**
1763
- * The key used to store the conversation ID in `sessionStorage`.
1764
- *
1765
- * @ignore
1766
- */
1767
- declare const CONVERSATION_ID = "__15gifts_conversation_id";
1768
- /**
1769
- * Deletes the conversation ID from `sessionStorage`.
1770
- *
1771
- * @example
1772
- * ```ts
1773
- * import { deleteConversationId } from '@15gifts/sdk'
1774
- *
1775
- * deleteConversationId()
1776
- * // The conversation ID will be removed.
1777
- * ```
1778
- */
1779
- declare const deleteConversationId: () => void;
1780
- /**
1781
- * Retrieves the conversation ID from `sessionStorage`.
1782
- *
1783
- * @example
1784
- * ```ts
1785
- * import { getConversationId } from '@15gifts/sdk'
1786
- *
1787
- * const conversationId = getConversationId()
1788
- *
1789
- * if (conversationId) {
1790
- * console.log(`Conversation ID: ${conversationId}`)
1791
- * } else {
1792
- * console.log('No conversation ID found.')
1793
- * }
1794
- * ```
1795
- */
1796
- declare const getConversationId: () => string | null;
1797
- /**
1798
- * Stores the given conversation ID in `sessionStorage`.
1799
- *
1800
- * @example
1801
- * ```ts
1802
- * import { setConversationId } from '@15gifts/sdk'
1803
- *
1804
- * setConversationId('ca0ab4ce-f697-41cc-8d0c-081762aace9b')
1805
- * // The conversation ID 'ca0ab4ce-f697-41cc-8d0c-081762aace9b' will be stored.
1806
- * ```
1807
- */
1808
- declare const setConversationId: (conversationId: string) => void;
1809
-
1810
- /**
1811
- * The key used to store the session ID in `sessionStorage`.
1812
- *
1813
- * @ignore
1814
- */
1815
- declare const SESSION_ID = "__15gifts_session_id";
1816
- /**
1817
- * Retrieves the session ID from `sessionStorage`.
1818
- *
1819
- * @example
1820
- * ```ts
1821
- * import { getSessionId } from '@15gifts/sdk'
1822
- *
1823
- * const sessionId = getSessionId()
1824
- *
1825
- * if (sessionId) {
1826
- * console.log(`Session ID: ${sessionId}`)
1827
- * } else {
1828
- * console.log('No session ID found.')
1829
- * }
1830
- * ```
1831
- */
1832
- declare const getSessionId: () => string | null;
1833
- /**
1834
- * Stores the given session ID in `sessionStorage`.
1835
- *
1836
- * @example
1837
- * ```ts
1838
- * import { setSessionId } from '@15gifts/sdk'
1839
- *
1840
- * setSessionId('20b2bff6-64a0-4101-bed9-ff545326584a')
1841
- * // The session ID '20b2bff6-64a0-4101-bed9-ff545326584a' will be stored.
1842
- * ```
1843
- */
1844
- declare const setSessionId: (sessionId: string) => void;
1845
-
1846
- /**
1847
- * The key used to store the user ID in `localStorage`.
1848
- *
1849
- * @ignore
1850
- */
1851
- declare const USER_ID = "__15gifts_user_id";
1852
- /**
1853
- * Time-to-live (TTL) for the user ID in milliseconds.
1854
- * Set to 30 days.
1855
- *
1856
- * @ignore
1857
- */
1858
- declare const TTL: number;
1859
- /**
1860
- * Retrieves the user ID from `localStorage` and updates its expiry time.
1861
- *
1862
- * @example
1863
- * ```ts
1864
- * import { getUserId } from '@15gifts/sdk'
1865
- *
1866
- * const userId = getUserId()
1867
- *
1868
- * if (userId) {
1869
- * console.log(`User ID: ${userId}`)
1870
- * } else {
1871
- * console.log('No user ID found.')
1872
- * }
1873
- * ```
1874
- */
1875
- declare const getUserId: () => string | null;
1876
- /**
1877
- * Stores the given user ID in `localStorage`.
1878
- *
1879
- * @example
1880
- * ```ts
1881
- * import { setUserId } from '@15gifts/sdk'
1882
- *
1883
- * setUserId('5b77656c-ea4c-492f-82bf-7129297c5873')
1884
- * // The user ID '5b77656c-ea4c-492f-82bf-7129297c5873' will be stored with a 30-day expiry.
1885
- * ```
1886
- */
1887
- declare const setUserId: (userId: string) => void;
1888
-
1889
- /**
1890
- * The key used to store the JWT in `localStorage`.
1891
- *
1892
- * @ignore
1893
- */
1894
- declare const JWT_TOKEN = "__15gifts_identity_token";
1895
- /**
1896
- * Checks if the JWT is expired.
1897
- *
1898
- * @param {string} token - the JWT.
1899
- * @returns {boolean} `true` if expired, `false` otherwise.
1900
- */
1901
- declare const isTokenExpired: (token: string) => boolean;
1902
- /**
1903
- * Retrieves the JWT from `localStorage` and checks if it is expired.
1904
- *
1905
- * @returns {string | null} The JWT if valid, otherwise `null`.
1906
- */
1907
- declare const getToken: () => string | null;
1908
- /**
1909
- * Stores the given JWT in `localStorage`.
1910
- *
1911
- * @example
1912
- * ```ts
1913
- * import { setToken } from '@15gifts/sdk'
1914
- *
1915
- * setToken('ey...')
1916
- * ```
1917
- */
1918
- declare const setToken: (token: string) => void;
1919
-
1920
1905
  /**
1921
1906
  * Middleware for adding an `Authorization` header to requests.
1922
1907
  *
@@ -1960,4 +1945,4 @@ declare const errorMiddleware: Middleware;
1960
1945
  */
1961
1946
  declare const headerMiddleware: (identity: Identity, url: string) => Middleware;
1962
1947
 
1963
- export { CONVERSATION_ID, Client, type Config, type ConversationIdMessage, type Endpoint, type ExitToChatMessage, type ExitToPhoneMessage, type ExitToPurchaseMessage, type ExitToPurchaseV2Message, type Identity, JWT_TOKEN, type Message, type MultiSelectMessage, type RecommendationMessage, type RecommendationV2Message, SDKError, SESSION_ID, type SendMessagePayload, type SingleSelectMessage, TTL, type TextMessage, type TrackingEvent, USER_ID, type UserStartConversationMessage, authMiddleware, deleteConversationId, errorMiddleware, getConversationId, getSessionId, getToken, getUserId, headerMiddleware, isTokenExpired, setConversationId, setSessionId, setToken, setUserId };
1948
+ export { Client, type Config, type ConversationIdMessage, type ConversationTurn, type Endpoint, type ExitToChatMessage, type ExitToPhoneMessage, type ExitToPurchaseMessage, type ExitToPurchaseV2Message, type Identity, type Message, type MultiSelectMessage, type RecommendationMessage, type RecommendationV2Message, type RestoredTurn, SDKError, type SendMessagePayload, type SingleSelectMessage, type TextMessage, type TrackingEvent, type UserSingleSelectMessage, type UserStartConversationMessage, authMiddleware, errorMiddleware, headerMiddleware };
package/dist/index.d.ts CHANGED
@@ -6,6 +6,23 @@ import { Client as Client$1, ClientOptions, Middleware } from 'openapi-fetch';
6
6
  * Do not make direct changes to the file.
7
7
  */
8
8
  interface paths$1 {
9
+ '/api/conversation/{conversation_id}/v1': {
10
+ parameters: {
11
+ query?: never;
12
+ header?: never;
13
+ path?: never;
14
+ cookie?: never;
15
+ };
16
+ /** Get Conversation */
17
+ get: operations['get_conversation_api_conversation__conversation_id__v1_get'];
18
+ put?: never;
19
+ post?: never;
20
+ delete?: never;
21
+ options?: never;
22
+ head?: never;
23
+ patch?: never;
24
+ trace?: never;
25
+ };
9
26
  '/api/conversation/v3': {
10
27
  parameters: {
11
28
  query?: never;
@@ -516,6 +533,23 @@ interface components {
516
533
  * @enum {string}
517
534
  */
518
535
  ExitToHumanReason: 'WANT_TO_TALK_TO_HUMAN' | 'OUT_OF_SCOPE_QUESTIONS' | 'NOT_BEHAVING_CORRECTLY';
536
+ /**
537
+ * GetConversationResponse
538
+ * @description Response model for the get conversation endpoint
539
+ */
540
+ GetConversationResponse: components['schemas']['GetConversationTurn'][];
541
+ /** GetConversationTurn */
542
+ GetConversationTurn: {
543
+ /** Usermessage */
544
+ userMessage: components['schemas']['UserTextMessage'] | components['schemas']['UserSingleSelectMessage'] | components['schemas']['UserMultiSelectMessage'] | components['schemas']['UserStartConversationMessage'];
545
+ /** Assistantmessages */
546
+ assistantMessages: (components['schemas']['AssistantTextMessage'] | components['schemas']['AssistantSingleSelectMessage'] | components['schemas']['AssistantMultiSelectMessage'] | components['schemas']['AssistantExitToChatMessage'] | components['schemas']['AssistantExitToPhoneMessage'] | components['schemas']['AssistantRecommendationMessage'] | components['schemas']['AssistantRecommendationMessageV2'] | components['schemas']['AssistantConversationIdMessage'] | components['schemas']['AssistantExitToPurchaseMessage'] | components['schemas']['AssistantExitToPurchaseMessageV2'])[];
547
+ };
548
+ /** HTTPValidationError */
549
+ HTTPValidationError: {
550
+ /** Detail */
551
+ detail?: components['schemas']['ValidationError'][];
552
+ };
519
553
  /** HeaderDetails */
520
554
  HeaderDetails: {
521
555
  /**
@@ -867,6 +901,15 @@ interface components {
867
901
  */
868
902
  userMessage: string;
869
903
  };
904
+ /** ValidationError */
905
+ ValidationError: {
906
+ /** Location */
907
+ loc: (string | number)[];
908
+ /** Message */
909
+ msg: string;
910
+ /** Error Type */
911
+ type: string;
912
+ };
870
913
  };
871
914
  responses: never;
872
915
  parameters: never;
@@ -875,6 +918,55 @@ interface components {
875
918
  pathItems: never;
876
919
  }
877
920
  interface operations {
921
+ get_conversation_api_conversation__conversation_id__v1_get: {
922
+ parameters: {
923
+ query?: never;
924
+ header?: never;
925
+ path: {
926
+ conversation_id: string;
927
+ };
928
+ cookie?: {
929
+ conversation_session_id?: string | null;
930
+ };
931
+ };
932
+ requestBody?: never;
933
+ responses: {
934
+ /** @description A successful response from the conversation service */
935
+ 200: {
936
+ headers: {
937
+ [name: string]: unknown;
938
+ };
939
+ content: {
940
+ 'application/json': components['schemas']['GetConversationResponse'];
941
+ };
942
+ };
943
+ /** @description The user does not have permission to access the requested conversation */
944
+ 403: {
945
+ headers: {
946
+ [name: string]: unknown;
947
+ };
948
+ content: {
949
+ /**
950
+ * @example {
951
+ * "code": "ERROR_UNHANDLED",
952
+ * "message": "An error occurred",
953
+ * "detail": "Access forbidden"
954
+ * }
955
+ */
956
+ 'application/json': unknown;
957
+ };
958
+ };
959
+ /** @description Validation Error */
960
+ 422: {
961
+ headers: {
962
+ [name: string]: unknown;
963
+ };
964
+ content: {
965
+ 'application/json': components['schemas']['HTTPValidationError'];
966
+ };
967
+ };
968
+ };
969
+ };
878
970
  generate_conversation_response_api_conversation_v3_post: {
879
971
  parameters: {
880
972
  query?: never;
@@ -1449,6 +1541,10 @@ interface Identity {
1449
1541
  * The pageview ID.
1450
1542
  */
1451
1543
  pageviewId?: string;
1544
+ /**
1545
+ * The identity token.
1546
+ */
1547
+ token?: string;
1452
1548
  /**
1453
1549
  * The session ID associated with the user.
1454
1550
  */
@@ -1463,6 +1559,29 @@ interface Identity {
1463
1559
  * Note that the API response may contain additional types that the SDK does not return.
1464
1560
  */
1465
1561
  type Message = ExitToChatMessage | ExitToPhoneMessage | ExitToPurchaseMessage | ExitToPurchaseV2Message | MultiSelectMessage | RecommendationMessage | RecommendationV2Message | SingleSelectMessage | TextMessage;
1562
+ /**
1563
+ * A conversation turn as returned by the raw API response.
1564
+ */
1565
+ type ConversationResponse = components['schemas']['GetConversationResponse'];
1566
+ type ConversationTurn = ConversationResponse[number];
1567
+ /**
1568
+ * A restored conversation turn returned by `client.getConversation()`.
1569
+ * It has been transformed from the raw API response to be more suitable for rendering in the UI.
1570
+ */
1571
+ interface RestoredTurn {
1572
+ /**
1573
+ * A stable client-side identifier for the restored turn.
1574
+ */
1575
+ id: string;
1576
+ /**
1577
+ * The user message text to render for this turn.
1578
+ */
1579
+ userMessage: Omit<UserTextMessage, 'conversationId'> | Omit<UserSingleSelectMessage, 'conversationId'> | Omit<UserMultiSelectMessage, 'conversationId'>;
1580
+ /**
1581
+ * The assistant messages to render for this turn.
1582
+ */
1583
+ assistantReply: Message[];
1584
+ }
1466
1585
  interface ConversationIdMessage extends ApiConversationIdMessage {
1467
1586
  }
1468
1587
  interface ExitToChatMessage extends ApiExitToChatMessage {
@@ -1601,7 +1720,30 @@ declare class Client {
1601
1720
  type: "EXIT_TO_PURCHASE";
1602
1721
  fallbackMessage: string;
1603
1722
  recommendationIdForExit?: string | null;
1604
- products: components["schemas"]["Product"][];
1723
+ products: components["schemas"] /**
1724
+ * Clears the existing conversation ID, then generates a new one and returns the opening message.
1725
+ *
1726
+ * @param context - Optional context to customize the conversation. It can include:
1727
+ * @param context.eligibleProducts An array of eligible product IDs.
1728
+ * @param context.eligibleBundles An array of eligible bundle IDs.
1729
+ * @param context.productOverrides Overrides for product details.
1730
+ * @param context.bundleOverrides Overrides for bundle details.
1731
+ *
1732
+ * @returns A promise that resolves to the opening message.
1733
+ *
1734
+ * @example
1735
+ * ##### Basic usage
1736
+ * ```ts
1737
+ * const openingMessage = await client.startConversation()
1738
+ * console.log('Opening message:', openingMessage)
1739
+ * ```
1740
+ *
1741
+ * ##### With context
1742
+ * ```ts
1743
+ * const openingMessage = await client.startConversation({ eligibleProducts: ['product-1', 'product-2'], productOverrides: { 'product-1': { price: 40 } })
1744
+ * console.log('Opening message:', openingMessage)
1745
+ * ```
1746
+ */["Product"][];
1605
1747
  bundles: components["schemas"]["Bundle"][];
1606
1748
  offers: components["schemas"]["Offer"][];
1607
1749
  } | {
@@ -1649,15 +1791,7 @@ declare class Client {
1649
1791
  trackEvent(eventName: TrackingEvent['eventName'], properties?: TrackingEvent['additionalProperties']): Promise<openapi_fetch.FetchResponse<{
1650
1792
  parameters: {
1651
1793
  query?: never;
1652
- header? /**
1653
- * Ends the current conversation by deleting the conversation ID.
1654
- *
1655
- * @example
1656
- * ```ts
1657
- * client.endConversation()
1658
- * console.log('Conversation ended')
1659
- * ```
1660
- */: never;
1794
+ header?: never;
1661
1795
  path?: never;
1662
1796
  cookie?: never;
1663
1797
  };
@@ -1747,6 +1881,8 @@ declare class Client {
1747
1881
  getIdentity(): Identity;
1748
1882
  /**
1749
1883
  * Gets the JWT from the localStorage.
1884
+ * Use this method to retrieve the token for use in other parts of your system,
1885
+ * such as calling the Humara sales tracking API
1750
1886
  *
1751
1887
  * @returns {string | null} the JWT.
1752
1888
  *
@@ -1757,166 +1893,15 @@ declare class Client {
1757
1893
  * ```
1758
1894
  */
1759
1895
  getIdentityToken(): string | null;
1896
+ /**
1897
+ * Gets the conversation history for a given conversation ID.
1898
+ *
1899
+ * @param conversationId - The ID of the conversation to retrieve.
1900
+ * @returns A promise that resolves to the conversation history as an array of turns. Each turn contains a user message and its corresponding response.
1901
+ */
1902
+ getConversation(conversationId: string): Promise<RestoredTurn[]>;
1760
1903
  }
1761
1904
 
1762
- /**
1763
- * The key used to store the conversation ID in `sessionStorage`.
1764
- *
1765
- * @ignore
1766
- */
1767
- declare const CONVERSATION_ID = "__15gifts_conversation_id";
1768
- /**
1769
- * Deletes the conversation ID from `sessionStorage`.
1770
- *
1771
- * @example
1772
- * ```ts
1773
- * import { deleteConversationId } from '@15gifts/sdk'
1774
- *
1775
- * deleteConversationId()
1776
- * // The conversation ID will be removed.
1777
- * ```
1778
- */
1779
- declare const deleteConversationId: () => void;
1780
- /**
1781
- * Retrieves the conversation ID from `sessionStorage`.
1782
- *
1783
- * @example
1784
- * ```ts
1785
- * import { getConversationId } from '@15gifts/sdk'
1786
- *
1787
- * const conversationId = getConversationId()
1788
- *
1789
- * if (conversationId) {
1790
- * console.log(`Conversation ID: ${conversationId}`)
1791
- * } else {
1792
- * console.log('No conversation ID found.')
1793
- * }
1794
- * ```
1795
- */
1796
- declare const getConversationId: () => string | null;
1797
- /**
1798
- * Stores the given conversation ID in `sessionStorage`.
1799
- *
1800
- * @example
1801
- * ```ts
1802
- * import { setConversationId } from '@15gifts/sdk'
1803
- *
1804
- * setConversationId('ca0ab4ce-f697-41cc-8d0c-081762aace9b')
1805
- * // The conversation ID 'ca0ab4ce-f697-41cc-8d0c-081762aace9b' will be stored.
1806
- * ```
1807
- */
1808
- declare const setConversationId: (conversationId: string) => void;
1809
-
1810
- /**
1811
- * The key used to store the session ID in `sessionStorage`.
1812
- *
1813
- * @ignore
1814
- */
1815
- declare const SESSION_ID = "__15gifts_session_id";
1816
- /**
1817
- * Retrieves the session ID from `sessionStorage`.
1818
- *
1819
- * @example
1820
- * ```ts
1821
- * import { getSessionId } from '@15gifts/sdk'
1822
- *
1823
- * const sessionId = getSessionId()
1824
- *
1825
- * if (sessionId) {
1826
- * console.log(`Session ID: ${sessionId}`)
1827
- * } else {
1828
- * console.log('No session ID found.')
1829
- * }
1830
- * ```
1831
- */
1832
- declare const getSessionId: () => string | null;
1833
- /**
1834
- * Stores the given session ID in `sessionStorage`.
1835
- *
1836
- * @example
1837
- * ```ts
1838
- * import { setSessionId } from '@15gifts/sdk'
1839
- *
1840
- * setSessionId('20b2bff6-64a0-4101-bed9-ff545326584a')
1841
- * // The session ID '20b2bff6-64a0-4101-bed9-ff545326584a' will be stored.
1842
- * ```
1843
- */
1844
- declare const setSessionId: (sessionId: string) => void;
1845
-
1846
- /**
1847
- * The key used to store the user ID in `localStorage`.
1848
- *
1849
- * @ignore
1850
- */
1851
- declare const USER_ID = "__15gifts_user_id";
1852
- /**
1853
- * Time-to-live (TTL) for the user ID in milliseconds.
1854
- * Set to 30 days.
1855
- *
1856
- * @ignore
1857
- */
1858
- declare const TTL: number;
1859
- /**
1860
- * Retrieves the user ID from `localStorage` and updates its expiry time.
1861
- *
1862
- * @example
1863
- * ```ts
1864
- * import { getUserId } from '@15gifts/sdk'
1865
- *
1866
- * const userId = getUserId()
1867
- *
1868
- * if (userId) {
1869
- * console.log(`User ID: ${userId}`)
1870
- * } else {
1871
- * console.log('No user ID found.')
1872
- * }
1873
- * ```
1874
- */
1875
- declare const getUserId: () => string | null;
1876
- /**
1877
- * Stores the given user ID in `localStorage`.
1878
- *
1879
- * @example
1880
- * ```ts
1881
- * import { setUserId } from '@15gifts/sdk'
1882
- *
1883
- * setUserId('5b77656c-ea4c-492f-82bf-7129297c5873')
1884
- * // The user ID '5b77656c-ea4c-492f-82bf-7129297c5873' will be stored with a 30-day expiry.
1885
- * ```
1886
- */
1887
- declare const setUserId: (userId: string) => void;
1888
-
1889
- /**
1890
- * The key used to store the JWT in `localStorage`.
1891
- *
1892
- * @ignore
1893
- */
1894
- declare const JWT_TOKEN = "__15gifts_identity_token";
1895
- /**
1896
- * Checks if the JWT is expired.
1897
- *
1898
- * @param {string} token - the JWT.
1899
- * @returns {boolean} `true` if expired, `false` otherwise.
1900
- */
1901
- declare const isTokenExpired: (token: string) => boolean;
1902
- /**
1903
- * Retrieves the JWT from `localStorage` and checks if it is expired.
1904
- *
1905
- * @returns {string | null} The JWT if valid, otherwise `null`.
1906
- */
1907
- declare const getToken: () => string | null;
1908
- /**
1909
- * Stores the given JWT in `localStorage`.
1910
- *
1911
- * @example
1912
- * ```ts
1913
- * import { setToken } from '@15gifts/sdk'
1914
- *
1915
- * setToken('ey...')
1916
- * ```
1917
- */
1918
- declare const setToken: (token: string) => void;
1919
-
1920
1905
  /**
1921
1906
  * Middleware for adding an `Authorization` header to requests.
1922
1907
  *
@@ -1960,4 +1945,4 @@ declare const errorMiddleware: Middleware;
1960
1945
  */
1961
1946
  declare const headerMiddleware: (identity: Identity, url: string) => Middleware;
1962
1947
 
1963
- export { CONVERSATION_ID, Client, type Config, type ConversationIdMessage, type Endpoint, type ExitToChatMessage, type ExitToPhoneMessage, type ExitToPurchaseMessage, type ExitToPurchaseV2Message, type Identity, JWT_TOKEN, type Message, type MultiSelectMessage, type RecommendationMessage, type RecommendationV2Message, SDKError, SESSION_ID, type SendMessagePayload, type SingleSelectMessage, TTL, type TextMessage, type TrackingEvent, USER_ID, type UserStartConversationMessage, authMiddleware, deleteConversationId, errorMiddleware, getConversationId, getSessionId, getToken, getUserId, headerMiddleware, isTokenExpired, setConversationId, setSessionId, setToken, setUserId };
1948
+ export { Client, type Config, type ConversationIdMessage, type ConversationTurn, type Endpoint, type ExitToChatMessage, type ExitToPhoneMessage, type ExitToPurchaseMessage, type ExitToPurchaseV2Message, type Identity, type Message, type MultiSelectMessage, type RecommendationMessage, type RecommendationV2Message, type RestoredTurn, SDKError, type SendMessagePayload, type SingleSelectMessage, type TextMessage, type TrackingEvent, type UserSingleSelectMessage, type UserStartConversationMessage, authMiddleware, errorMiddleware, headerMiddleware };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var N=Object.create;var d=Object.defineProperty;var V=Object.getOwnPropertyDescriptor;var D=Object.getOwnPropertyNames;var b=Object.getPrototypeOf,q=Object.prototype.hasOwnProperty;var j=(e,t)=>{for(var s in t)d(e,s,{get:t[s],enumerable:!0})},_=(e,t,s,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of D(t))!q.call(e,n)&&n!==s&&d(e,n,{get:()=>t[n],enumerable:!(o=V(t,n))||o.enumerable});return e};var L=(e,t,s)=>(s=e!=null?N(b(e)):{},_(t||!e||!e.__esModule?d(s,"default",{value:e,enumerable:!0}):s,e)),W=e=>_(d({},"__esModule",{value:!0}),e);var K={};j(K,{CONVERSATION_ID:()=>c,Client:()=>O,JWT_TOKEN:()=>l,SDKError:()=>i,SESSION_ID:()=>y,TTL:()=>k,USER_ID:()=>A,authMiddleware:()=>p,deleteConversationId:()=>h,errorMiddleware:()=>u,getConversationId:()=>I,getSessionId:()=>E,getToken:()=>T,getUserId:()=>C,headerMiddleware:()=>f,isTokenExpired:()=>U,setConversationId:()=>x,setSessionId:()=>M,setToken:()=>R,setUserId:()=>g});module.exports=W(K);var P=L(require("openapi-fetch"));var c="__15gifts_conversation_id",h=()=>sessionStorage.removeItem(c),I=()=>sessionStorage.getItem(c),x=e=>sessionStorage.setItem(c,e);var y="__15gifts_session_id",E=()=>sessionStorage.getItem(y),M=e=>sessionStorage.setItem(y,e);var X=e=>{let t=localStorage.getItem(e);if(!t)return null;let s=JSON.parse(t);return Date.now()>s.expires?(localStorage.removeItem(e),null):s.value},S=X;var G=(e,t,s)=>{let o={expires:Date.now()+s,value:t};localStorage.setItem(e,JSON.stringify(o))},w=G;var H=1e3*60*60*24,A="__15gifts_user_id",k=H*30,C=()=>{let e=S(A);return e&&g(e),e},g=e=>w(A,e,k);var l="__15gifts_identity_token",U=e=>{try{let[,t]=e.split(".");if(!t)throw new Error("Invalid token payload");let s=JSON.parse(atob(t));return s.exp&&Date.now()/1e3>s.exp}catch(t){return console.error("Invalid token format",t),!0}},T=()=>{let e=localStorage.getItem(l);return!e||U(e)?(localStorage.removeItem(l),null):e},R=e=>localStorage.setItem(l,e);var B=e=>({onRequest:async({request:t})=>{if(t.url.includes("/identity/"))return t;if(!e)throw new Error("Access token is required for authentication.");return t.headers.set("Authorization",`Bearer ${e}`),t}}),p=B;var $={onResponse:async({response:e})=>{if(!e.ok){let t=await e.json();throw new Error(t.message)}return e}},u=$;var F=(e,t)=>({onRequest:async({request:s})=>(e.pageviewId&&s.headers.set("X-PAGEVIEW-ID",e.pageviewId),t&&s.headers.set("X-PAGE-URL",t),s)}),f=F;var m="0.19.0";var i=class e extends Error{sdkVersion;cause;constructor(t,{cause:s}={}){super(t),this.name="SDKError",this.cause=s,this.sdkVersion=m,Object.setPrototypeOf(this,e.prototype)}};var O=class{endpoint;identity;constructor(t){let{conversationUrl:s,customerId:o,fetch:n,frontendUrl:r,headers:v}=t,a={...v,"X-SDK-VERSION":m};this.endpoint={conversation:(0,P.default)({baseUrl:s,fetch:n,headers:a,credentials:"include"}),frontend:(0,P.default)({baseUrl:r,fetch:n,headers:a})},this.identity={customerId:o,conversationId:I()??void 0,sessionId:E()??void 0,userId:C()??void 0},this.endpoint.conversation.use(u),this.endpoint.conversation.use(f(this.identity,window.location.href))}async createIdentity(){let{customerId:t,sessionId:s,userId:o}=this.identity;try{let{data:n}=await this.endpoint.frontend.POST("/api/tracking/identity/v2",{body:{customerId:t,sessionId:s,userId:o,url:window.location.href,userAgent:window.navigator.userAgent}});if(!n)throw new i("No data received from identity API");this.identity.pageviewId=n.pageviewId,s||(this.identity.sessionId=n.sessionId,M(n.sessionId)),o||(this.identity.userId=n.userId,g(n.userId)),R(n.token),Object.values(this.endpoint).forEach(r=>{r.use(p(n.token))})}catch(n){throw Object.values(this.endpoint).forEach(r=>{r.use(p())}),new i("Failed to create identity",{cause:n})}}endConversation(){h(),this.identity.conversationId=void 0}async startConversation(t,s){this.endConversation();let o={...t},{data:n}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{type:"START_CONVERSATION",conversationContext:o,openingUserMessage:s}});if(!n)throw new i("No data received from Conversation API");let[r,...v]=n,a=r.conversationId;if(!a)throw new i("Conversation ID not received in API response");return x(a),this.identity.conversationId=a,v}async sendMessage(t){let s=this.identity.conversationId;if(!s)throw new i("Conversation ID not set");let{data:o}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{conversationId:s,...t}});if(!o)throw new i("No data received from conversation API");return o.filter(n=>n.type!=="CONVERSATION_ID")}async trackEvent(t,s){let o={additionalProperties:s,conversationId:this.identity.conversationId,eventName:t,pageviewId:this.identity.pageviewId??"unknown",screenWidth:window.screen.width,screenHeight:window.screen.height,screenSize:window.screen.width<=480?"mobile":"large",url:window.location.href,userAgent:window.navigator.userAgent};return this.endpoint.frontend.POST("/api/tracking/user/v2",{body:o})}getIdentity(){return this.identity}getIdentityToken(){return T()}};0&&(module.exports={CONVERSATION_ID,Client,JWT_TOKEN,SDKError,SESSION_ID,TTL,USER_ID,authMiddleware,deleteConversationId,errorMiddleware,getConversationId,getSessionId,getToken,getUserId,headerMiddleware,isTokenExpired,setConversationId,setSessionId,setToken,setUserId});
1
+ "use strict";var R=Object.create;var p=Object.defineProperty;var P=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var _=Object.getPrototypeOf,U=Object.prototype.hasOwnProperty;var k=(e,t)=>{for(var s in t)p(e,s,{get:t[s],enumerable:!0})},x=(e,t,s,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of O(t))!U.call(e,n)&&n!==s&&p(e,n,{get:()=>t[n],enumerable:!(o=P(t,n))||o.enumerable});return e};var N=(e,t,s)=>(s=e!=null?R(_(e)):{},x(t||!e||!e.__esModule?p(s,"default",{value:e,enumerable:!0}):s,e)),b=e=>x(p({},"__esModule",{value:!0}),e);var se={};k(se,{Client:()=>E,SDKError:()=>r,authMiddleware:()=>d,errorMiddleware:()=>g,headerMiddleware:()=>u});module.exports=b(se);var M=N(require("openapi-fetch"));var V=e=>{let t=localStorage.getItem(e);if(!t)return null;let s=JSON.parse(t);return Date.now()>s.expires?(localStorage.removeItem(e),null):s.value},y=V;var D=(e,t,s)=>{let o={expires:Date.now()+s,value:t};localStorage.setItem(e,JSON.stringify(o))},m=D;var L=1e3*60*60*24,G=L*30,I="__15gifts_conversation_id",S="__15gifts_session_id",f="__15gifts_identity_token",T="__15gifts_user_id",j=()=>sessionStorage.removeItem(I),q=()=>sessionStorage.getItem(I),K=e=>sessionStorage.setItem(I,e),W=()=>sessionStorage.getItem(S),H=e=>sessionStorage.setItem(S,e),X=e=>{try{let[,t]=e.split(".");if(!t)throw new Error("Invalid token payload");let s=JSON.parse(atob(t));return s.exp&&Date.now()/1e3>s.exp}catch(t){return console.error("Invalid token format",t),!0}},B=()=>{let e=localStorage.getItem(f);return!e||X(e)?(localStorage.removeItem(f),null):e},$=e=>localStorage.setItem(f,e),F=()=>{let e=y(T);return e&&C(e),e},C=e=>m(T,e,G),c=(e,t,s)=>({enumerable:!0,configurable:!0,get:()=>e()??void 0,set:o=>{if(o){t(o);return}s?.()}}),w=e=>{let t={customerId:e},s={conversationId:c(q,K,j),sessionId:c(W,H),token:c(B,$),userId:c(F,C)};return Object.defineProperties(t,s),t};var J=e=>({onRequest:async({request:t})=>{if(t.url.includes("/identity/"))return t;if(!e)throw new Error("Access token is required for authentication.");return t.headers.set("Authorization",`Bearer ${e}`),t}}),d=J;var z={onResponse:async({response:e})=>{if(!e.ok){let t=await e.json();throw new Error(t.message)}return e}},g=z;var Q=(e,t)=>({onRequest:async({request:s})=>(e.pageviewId&&s.headers.set("X-PAGEVIEW-ID",e.pageviewId),t&&s.headers.set("X-PAGE-URL",t),s)}),u=Q;var h=e=>{let{conversationId:t,...s}=e;return s},Y=(e,t)=>t?.assistantMessages.find(n=>n.type==="SINGLE_SELECT")?.options.find(n=>n.value===e.option)?.label||"",Z=(e,t)=>{let{userMessage:s}=e;switch(s.type){case"SINGLE_SELECT":return{...h(s),userMessage:Y(s,t)};case"START_CONVERSATION":return{type:"MESSAGE",userMessage:s.openingUserMessage?.option||""};case"MESSAGE":return h(s);case"MULTI_SELECT":return h(s)}},ee=(e,t)=>{let s=!!t;return e.assistantMessages.filter(o=>o.type!=="CONVERSATION_ID"&&!(s&&o.type==="SINGLE_SELECT"))},A=e=>e.map((t,s)=>{let o=s>0?e[s-1]:void 0,n=s<e.length-1?e[s+1]:void 0;return{id:`restored-turn-${s}`,userMessage:Z(t,o),assistantReply:ee(t,n)}});var l="0.20.0";var r=class e extends Error{sdkVersion;cause;constructor(t,{cause:s}={}){super(t),this.name="SDKError",this.cause=s,this.sdkVersion=l,Object.setPrototypeOf(this,e.prototype)}};var E=class{endpoint;identity;constructor(t){let{conversationUrl:s,customerId:o,fetch:n,frontendUrl:i,headers:v}=t,a={...v,"X-SDK-VERSION":l};this.endpoint={conversation:(0,M.default)({baseUrl:s,fetch:n,headers:a,credentials:"include"}),frontend:(0,M.default)({baseUrl:i,fetch:n,headers:a})},this.identity=w(o),this.endpoint.conversation.use(g),this.endpoint.conversation.use(u(this.identity,window.location.href))}async createIdentity(){let{customerId:t,sessionId:s,userId:o}=this.identity;try{let{data:n}=await this.endpoint.frontend.POST("/api/tracking/identity/v2",{body:{customerId:t,sessionId:s,userId:o,url:window.location.href,userAgent:window.navigator.userAgent}});if(!n)throw new r("No data received from identity API");this.identity.pageviewId=n.pageviewId,s||(this.identity.sessionId=n.sessionId),o||(this.identity.userId=n.userId),this.identity.token=n.token,Object.values(this.endpoint).forEach(i=>{i.use(d(n.token))})}catch(n){throw Object.values(this.endpoint).forEach(i=>{i.use(d())}),new r("Failed to create identity",{cause:n})}}endConversation(){this.identity.conversationId=void 0}async startConversation(t,s){this.endConversation();let o={...t},{data:n}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{type:"START_CONVERSATION",conversationContext:o,openingUserMessage:s}});if(!n)throw new r("No data received from Conversation API");let[i,...v]=n,a=i.conversationId;if(!a)throw new r("Conversation ID not received in API response");return this.identity.conversationId=a,v}async sendMessage(t){let s=this.identity.conversationId;if(!s)throw new r("Conversation ID not set");let{data:o}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{conversationId:s,...t}});if(!o)throw new r("No data received from conversation API");return o.filter(n=>n.type!=="CONVERSATION_ID")}async trackEvent(t,s){let o={additionalProperties:s,conversationId:this.identity.conversationId,eventName:t,pageviewId:this.identity.pageviewId??"unknown",screenWidth:window.screen.width,screenHeight:window.screen.height,screenSize:window.screen.width<=480?"mobile":"large",url:window.location.href,userAgent:window.navigator.userAgent};return this.endpoint.frontend.POST("/api/tracking/user/v2",{body:o})}getIdentity(){return this.identity}getIdentityToken(){return this.identity.token??null}async getConversation(t){if(!t)throw new r("Conversation ID not set");try{let{data:s}=await this.endpoint.conversation.GET("/api/conversation/{conversation_id}/v1",{params:{path:{conversation_id:t}}});if(this.identity.conversationId=t,!s)throw new r("No data received from conversation history API");return A(s)}catch(s){throw new r("Failed to get conversation history",{cause:s})}}};0&&(module.exports={Client,SDKError,authMiddleware,errorMiddleware,headerMiddleware});
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/client.ts","../src/identity/conversationId.ts","../src/identity/sessionId.ts","../src/utils/getItemWithExpiry.ts","../src/utils/setItemWithExpiry.ts","../src/identity/userId.ts","../src/identity/token.ts","../src/middlewares/auth.ts","../src/middlewares/error.ts","../src/middlewares/headers.ts","../package.json","../src/utils/SDKError.ts"],"sourcesContent":["export * from './client'\nexport * from './identity'\nexport * from './middlewares'\nexport * from './types'\n","import createClient, { type ClientOptions } from 'openapi-fetch'\n\nimport {\n deleteConversationId,\n getConversationId,\n getSessionId,\n getUserId,\n getToken,\n setConversationId,\n setSessionId,\n setUserId,\n setToken,\n} from './identity'\nimport { authMiddleware, errorMiddleware, headerMiddleware } from './middlewares'\nimport type { components, paths as conversationPaths } from './schemas/conversation'\nimport type { paths as frontendPaths } from './schemas/frontend'\nimport type {\n Config,\n ConversationIdMessage,\n Endpoint,\n Identity,\n Message,\n SendMessagePayload,\n TrackingEvent,\n UserStartConversationMessage,\n} from './types'\nimport { version } from '../package.json'\nimport SDKError from './utils/SDKError'\n\n/**\n * The `Client` class provides methods to manage 15gifts API.\n */\nexport class Client {\n /**\n * This can be used to interact with the APIs directly. It is recommended to use the [helper methods](/sdk/sdk-reference/classes/client/#methods) provided by the `Client` class instead.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * const { data } = await client.endpoint.conversation.POST('/api/conversation/v3')\n * ```\n */\n endpoint: Endpoint\n\n /**\n * The identity information.\n */\n identity: Identity\n\n /**\n * Creates a new instance of the `Client` class.\n *\n * @param config - Configuration options for initializing the client.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * ```\n */\n constructor(config: Config) {\n const { conversationUrl, customerId, fetch, frontendUrl, headers: defaultHeaders } = config\n\n const headers: ClientOptions['headers'] = {\n ...defaultHeaders,\n 'X-SDK-VERSION': version,\n }\n\n this.endpoint = {\n conversation: createClient<conversationPaths>({\n baseUrl: conversationUrl,\n fetch,\n headers,\n credentials: 'include',\n }),\n frontend: createClient<frontendPaths>({ baseUrl: frontendUrl, fetch, headers }),\n }\n\n this.identity = {\n customerId,\n conversationId: getConversationId() ?? undefined,\n sessionId: getSessionId() ?? undefined,\n userId: getUserId() ?? undefined,\n }\n\n this.endpoint.conversation.use(errorMiddleware)\n this.endpoint.conversation.use(headerMiddleware(this.identity, window.location.href))\n }\n\n /**\n * Creates a new identity for the user by generating a session ID and user ID if they don't exist, and sets the access token for future API calls.\n * Ends the current conversation if a conversation ID is present before sending a request to update identity.\n * This should not be called more than once per page load.\n *\n * @returns A promise that resolves once the identity is created and the access token is set.\n *\n * @example\n * ```ts\n * await client.createIdentity()\n * console.log('Identity created:', client.identity)\n * ```\n */\n async createIdentity(): Promise<void> {\n const { customerId, sessionId, userId } = this.identity\n\n try {\n const { data } = await this.endpoint.frontend.POST('/api/tracking/identity/v2', {\n body: {\n customerId,\n sessionId,\n userId,\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n },\n })\n\n if (!data) {\n throw new SDKError('No data received from identity API')\n }\n\n this.identity.pageviewId = data.pageviewId\n\n if (!sessionId) {\n this.identity.sessionId = data.sessionId\n setSessionId(data.sessionId)\n }\n if (!userId) {\n this.identity.userId = data.userId\n setUserId(data.userId)\n }\n\n setToken(data.token)\n\n // Add the access token to the Authorization header for all endpoints\n Object.values(this.endpoint).forEach((endpoint) => {\n endpoint.use(authMiddleware(data.token))\n })\n } catch (error) {\n // Enable the auth middleware without a token so that it will throw an error before sending\n // the next request, preventing unnecessary API calls / 401 responses.\n Object.values(this.endpoint).forEach((endpoint) => {\n endpoint.use(authMiddleware())\n })\n throw new SDKError('Failed to create identity', {\n cause: error as Error,\n })\n }\n }\n\n /**\n * Ends the current conversation by deleting the conversation ID.\n *\n * @example\n * ```ts\n * client.endConversation()\n * console.log('Conversation ended')\n * ```\n */\n endConversation(): void {\n deleteConversationId()\n this.identity.conversationId = undefined\n }\n\n /**\n * Clears the existing conversation ID, then generates a new one and returns the opening message.\n *\n * @param context - Optional context to customize the conversation. It can include:\n * @param context.eligibleProducts An array of eligible product IDs.\n * @param context.eligibleBundles An array of eligible bundle IDs.\n * @param context.productOverrides Overrides for product details.\n * @param context.bundleOverrides Overrides for bundle details.\n *\n * @returns A promise that resolves to the opening message.\n *\n * @example\n * ##### Basic usage\n * ```ts\n * const openingMessage = await client.startConversation()\n * console.log('Opening message:', openingMessage)\n * ```\n *\n * ##### With context\n * ```ts\n * const openingMessage = await client.startConversation({ eligibleProducts: ['product-1', 'product-2'], productOverrides: { 'product-1': { price: 40 } })\n * console.log('Opening message:', openingMessage)\n * ```\n */\n async startConversation(\n context?: components['schemas']['ConversationContext'],\n userMessage?: UserStartConversationMessage['openingUserMessage'],\n ): Promise<Message[]> {\n this.endConversation()\n\n const conversationContext = {\n ...context,\n }\n\n const { data } = await this.endpoint.conversation.POST(`/api/conversation/v3`, {\n body: {\n type: 'START_CONVERSATION',\n conversationContext,\n openingUserMessage: userMessage,\n },\n })\n\n if (!data) throw new SDKError('No data received from Conversation API')\n\n const [conversationIdMessage, ...rest] = data as [ConversationIdMessage, ...Message[]]\n\n const conversationId = conversationIdMessage.conversationId\n if (!conversationId) {\n throw new SDKError('Conversation ID not received in API response')\n }\n\n setConversationId(conversationId)\n this.identity.conversationId = conversationId\n\n return rest\n }\n\n /**\n * Sends a message in the conversation.\n *\n * @param options - An object containing the user message.\n * @returns A promise that resolves to an array of messages\n *\n * @example\n * ```ts\n * const newMessages = await client.sendMessage({\n * userMessage: 'How can I get support?',\n * })\n *\n * if (newMessages) {\n * console.log('Received messages:', newMessages)\n * } else {\n * console.log('No message received')\n * }\n * ```\n */\n async sendMessage(payload: SendMessagePayload) {\n const conversationId = this.identity.conversationId\n if (!conversationId) {\n throw new SDKError('Conversation ID not set')\n }\n\n const { data } = await this.endpoint.conversation.POST('/api/conversation/v3', {\n body: {\n conversationId,\n ...payload,\n },\n })\n\n if (!data) throw new SDKError('No data received from conversation API')\n\n // Removes any `CONVERSATION_ID` messages from the API response. In reality, these messages will only\n // appear in the response to a `START_CONVERSATION` request.\n return data.filter((message) => message.type !== 'CONVERSATION_ID')\n }\n\n /**\n * Sends an event to the tracking API, with the required properties already set.\n *\n * @param eventName - The name of the event to track.\n * @param properties - Additional properties to include in the event.\n * @returns A promise that resolves once the event is tracked.\n *\n * @example\n * ```ts\n * await client.trackEvent('entry_point-shown')\n * ```\n */\n async trackEvent(eventName: TrackingEvent['eventName'], properties?: TrackingEvent['additionalProperties']) {\n const body: TrackingEvent = {\n additionalProperties: properties,\n conversationId: this.identity.conversationId,\n eventName,\n pageviewId: this.identity.pageviewId ?? 'unknown',\n screenWidth: window.screen.width,\n screenHeight: window.screen.height,\n screenSize: window.screen.width <= 480 ? 'mobile' : 'large',\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n }\n\n return this.endpoint.frontend.POST('/api/tracking/user/v2', {\n body,\n })\n }\n\n /**\n * Gets an existing identity of the user.\n *\n * @returns An Identity object containing `customerId`, `conversationId`, `sessionId`, `userId`.\n *\n * @example\n * ```ts\n * identity = client.getIdentity()\n * console.log('Identity retrieved:', identity)\n * ```\n */\n getIdentity(): Identity {\n return this.identity\n }\n\n /**\n * Gets the JWT from the localStorage.\n *\n * @returns {string | null} the JWT.\n *\n * @example\n * ```ts\n * token = client.getIdentityToken()\n * console.log('Identity token retrieved:', token)\n * ```\n */\n getIdentityToken(): string | null {\n return getToken()\n }\n}\n","/**\n * The key used to store the conversation ID in `sessionStorage`.\n *\n * @ignore\n */\nexport const CONVERSATION_ID = '__15gifts_conversation_id'\n\n/**\n * Deletes the conversation ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { deleteConversationId } from '@15gifts/sdk'\n *\n * deleteConversationId()\n * // The conversation ID will be removed.\n * ```\n */\nexport const deleteConversationId = () => sessionStorage.removeItem(CONVERSATION_ID)\n\n/**\n * Retrieves the conversation ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { getConversationId } from '@15gifts/sdk'\n *\n * const conversationId = getConversationId()\n *\n * if (conversationId) {\n * console.log(`Conversation ID: ${conversationId}`)\n * } else {\n * console.log('No conversation ID found.')\n * }\n * ```\n */\nexport const getConversationId = () => sessionStorage.getItem(CONVERSATION_ID)\n\n/**\n * Stores the given conversation ID in `sessionStorage`.\n *\n * @example\n * ```ts\n * import { setConversationId } from '@15gifts/sdk'\n *\n * setConversationId('ca0ab4ce-f697-41cc-8d0c-081762aace9b')\n * // The conversation ID 'ca0ab4ce-f697-41cc-8d0c-081762aace9b' will be stored.\n * ```\n */\nexport const setConversationId = (conversationId: string) => sessionStorage.setItem(CONVERSATION_ID, conversationId)\n","/**\n * The key used to store the session ID in `sessionStorage`.\n *\n * @ignore\n */\nexport const SESSION_ID = '__15gifts_session_id'\n\n/**\n * Retrieves the session ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { getSessionId } from '@15gifts/sdk'\n *\n * const sessionId = getSessionId()\n *\n * if (sessionId) {\n * console.log(`Session ID: ${sessionId}`)\n * } else {\n * console.log('No session ID found.')\n * }\n * ```\n */\nexport const getSessionId = () => sessionStorage.getItem(SESSION_ID)\n\n/**\n * Stores the given session ID in `sessionStorage`.\n *\n * @example\n * ```ts\n * import { setSessionId } from '@15gifts/sdk'\n *\n * setSessionId('20b2bff6-64a0-4101-bed9-ff545326584a')\n * // The session ID '20b2bff6-64a0-4101-bed9-ff545326584a' will be stored.\n * ```\n */\nexport const setSessionId = (sessionId: string) => sessionStorage.setItem(SESSION_ID, sessionId)\n","const getItemWithExpiry = (key: string) => {\n const itemString = localStorage.getItem(key)\n\n if (!itemString) return null\n\n const item = JSON.parse(itemString) as { expires: number; value: string }\n\n if (Date.now() > item.expires) {\n localStorage.removeItem(key)\n\n return null\n }\n\n return item.value\n}\n\nexport default getItemWithExpiry\n","/**\n * Set an item in localStorage with an expiration time\n * @param key The key under which the value is stored in localStorage\n * @param value The value to be stored\n * @param ttl The time-to-live (TTL) in milliseconds\n */\nconst setItemWithExpiry = (key: string, value: string, ttl: number) => {\n const item = {\n expires: Date.now() + ttl,\n value,\n }\n\n localStorage.setItem(key, JSON.stringify(item))\n}\n\nexport default setItemWithExpiry\n","import { getItemWithExpiry, setItemWithExpiry } from '../utils'\nconst day = 1000 * 60 * 60 * 24\n\n/**\n * The key used to store the user ID in `localStorage`.\n *\n * @ignore\n */\nexport const USER_ID = '__15gifts_user_id'\n\n/**\n * Time-to-live (TTL) for the user ID in milliseconds.\n * Set to 30 days.\n *\n * @ignore\n */\nexport const TTL = day * 30\n\n/**\n * Retrieves the user ID from `localStorage` and updates its expiry time.\n *\n * @example\n * ```ts\n * import { getUserId } from '@15gifts/sdk'\n *\n * const userId = getUserId()\n *\n * if (userId) {\n * console.log(`User ID: ${userId}`)\n * } else {\n * console.log('No user ID found.')\n * }\n * ```\n */\nexport const getUserId = () => {\n const userId = getItemWithExpiry(USER_ID)\n\n // Update the userId with a new expiry time\n // So that it will be valid for another 30 days, rather than 30 days from when it was first set\n if (userId) {\n setUserId(userId)\n }\n\n return userId\n}\n\n/**\n * Stores the given user ID in `localStorage`.\n *\n * @example\n * ```ts\n * import { setUserId } from '@15gifts/sdk'\n *\n * setUserId('5b77656c-ea4c-492f-82bf-7129297c5873')\n * // The user ID '5b77656c-ea4c-492f-82bf-7129297c5873' will be stored with a 30-day expiry.\n * ```\n */\nexport const setUserId = (userId: string) => setItemWithExpiry(USER_ID, userId, TTL)\n","/**\n * The key used to store the JWT in `localStorage`.\n *\n * @ignore\n */\nexport const JWT_TOKEN = '__15gifts_identity_token'\n\n/**\n * Checks if the JWT is expired.\n *\n * @param {string} token - the JWT.\n * @returns {boolean} `true` if expired, `false` otherwise.\n */\nexport const isTokenExpired = (token: string): boolean => {\n try {\n const [, payloadBase64] = token.split('.')\n if (!payloadBase64) {\n throw new Error('Invalid token payload')\n }\n const payload = JSON.parse(atob(payloadBase64))\n\n return payload.exp && Date.now() / 1000 > payload.exp\n } catch (error) {\n console.error('Invalid token format', error)\n return true\n }\n}\n\n/**\n * Retrieves the JWT from `localStorage` and checks if it is expired.\n *\n * @returns {string | null} The JWT if valid, otherwise `null`.\n */\nexport const getToken = (): string | null => {\n const token = localStorage.getItem(JWT_TOKEN)\n\n if (!token || isTokenExpired(token)) {\n localStorage.removeItem(JWT_TOKEN)\n return null\n }\n\n return token\n}\n\n/**\n * Stores the given JWT in `localStorage`.\n *\n * @example\n * ```ts\n * import { setToken } from '@15gifts/sdk'\n *\n * setToken('ey...')\n * ```\n */\nexport const setToken = (token: string) => localStorage.setItem(JWT_TOKEN, token)\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for adding an `Authorization` header to requests.\n *\n * @param accessToken - The token to be included in the `Authorization` header.\n * @returns A middleware object that attaches the access token to the request headers.\n *\n * @example\n * ```ts\n * import { authMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(authMiddleware(accessToken))\n * ```\n */\nconst authMiddleware = (accessToken?: string): Middleware => ({\n onRequest: async ({ request }) => {\n const isIdentityEndpoint = request.url.includes('/identity/')\n if (isIdentityEndpoint) {\n return request\n }\n\n // Throw an error because we know the API will return a 401 if the access token is not set.\n if (!accessToken) {\n throw new Error('Access token is required for authentication.')\n }\n\n request.headers.set('Authorization', `Bearer ${accessToken}`)\n\n return request\n },\n})\n\nexport default authMiddleware\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for handling errors.\n *\n * @returns A middleware object that throws an error if the response is not ok.\n *\n * @example\n * ```ts\n * import { errorMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(errorMiddleware())\n * ```\n */\nconst errorMiddleware: Middleware = {\n // onError does not handle error responses with 4xx or 5xx HTTP status codes, since these are considered \"successful\" responses but with a bad status code.\n // In these cases we need to check the response's status property or ok() method via the onResponse callback.\n onResponse: async ({ response }) => {\n if (!response.ok) {\n const data = await response.json()\n\n throw new Error(data.message)\n }\n\n return response\n },\n}\n\nexport default errorMiddleware\n","import type { Middleware } from 'openapi-fetch'\n\nimport { Identity } from '../types'\n\n/**\n * Middleware for adding request headers that other services use for tracking.\n *\n * @returns A middleware object that throws an error if the response is not ok.\n *\n * @example\n * ```ts\n * import { pageViewId } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(headerMiddleware('123', 'https://example.com'))\n * ```\n */\nconst headerMiddleware = (identity: Identity, url: string): Middleware => ({\n onRequest: async ({ request }) => {\n if (identity.pageviewId) {\n request.headers.set('X-PAGEVIEW-ID', identity.pageviewId)\n }\n if (url) {\n request.headers.set('X-PAGE-URL', url)\n }\n\n return request\n },\n})\n\nexport default headerMiddleware\n","{\n \"name\": \"@15gifts/sdk\",\n \"version\": \"0.19.0\",\n \"files\": [\n \"dist\"\n ],\n \"main\": \"./dist/index.js\",\n \"module\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"scripts\": {\n \"build\": \"tsup\",\n \"coverage\": \"vitest run --coverage\",\n \"generate-types\": \"npx openapi-typescript\",\n \"dev\": \"tsup --watch\",\n \"format\": \"prettier . --write\",\n \"lint\": \"eslint .\",\n \"test:watch\": \"vitest\",\n \"test\": \"vitest run\",\n \"typecheck\": \"tsc\",\n \"update-schemas\": \"node --experimental-strip-types update-schema.ts && npm run generate-types && npm run format\"\n },\n \"dependencies\": {\n \"openapi-fetch\": \"^0.13.4\"\n },\n \"devDependencies\": {\n \"openapi-typescript\": \"^7.6.0\",\n \"tsup\": \"^8.3.6\"\n },\n \"sideEffects\": false,\n \"prettier\": \"prettier-config-custom\"\n}\n","import { version } from '../../package.json'\n\n/**\n * Custom error class for SDK-related errors.\n * Includes the SDK version and an optional cause for better debugging.\n * NOTE: The error.message is intended for developers, not end-users.\n */\nexport default class SDKError extends Error {\n sdkVersion: string\n override cause?: Error\n\n constructor(userMessage: string, { cause }: { cause?: Error } = {}) {\n super(userMessage)\n this.name = 'SDKError'\n this.cause = cause\n this.sdkVersion = version\n\n // Set the prototype explicitly to maintain instanceof checks\n Object.setPrototypeOf(this, SDKError.prototype)\n }\n}\n"],"mappings":"0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,EAAA,WAAAC,EAAA,cAAAC,EAAA,aAAAC,EAAA,eAAAC,EAAA,QAAAC,EAAA,YAAAC,EAAA,mBAAAC,EAAA,yBAAAC,EAAA,oBAAAC,EAAA,sBAAAC,EAAA,iBAAAC,EAAA,aAAAC,EAAA,cAAAC,EAAA,qBAAAC,EAAA,mBAAAC,EAAA,sBAAAC,EAAA,iBAAAC,EAAA,aAAAC,EAAA,cAAAC,IAAA,eAAAC,EAAAtB,GCAA,IAAAuB,EAAiD,4BCK1C,IAAMC,EAAkB,4BAalBC,EAAuB,IAAM,eAAe,WAAWD,CAAe,EAkBtEE,EAAoB,IAAM,eAAe,QAAQF,CAAe,EAahEG,EAAqBC,GAA2B,eAAe,QAAQJ,EAAiBI,CAAc,EC5C5G,IAAMC,EAAa,uBAkBbC,EAAe,IAAM,eAAe,QAAQD,CAAU,EAatDE,EAAgBC,GAAsB,eAAe,QAAQH,EAAYG,CAAS,ECpC/F,IAAMC,EAAqBC,GAAgB,CACzC,IAAMC,EAAa,aAAa,QAAQD,CAAG,EAE3C,GAAI,CAACC,EAAY,OAAO,KAExB,IAAMC,EAAO,KAAK,MAAMD,CAAU,EAElC,OAAI,KAAK,IAAI,EAAIC,EAAK,SACpB,aAAa,WAAWF,CAAG,EAEpB,MAGFE,EAAK,KACd,EAEOC,EAAQJ,ECVf,IAAMK,EAAoB,CAACC,EAAaC,EAAeC,IAAgB,CACrE,IAAMC,EAAO,CACX,QAAS,KAAK,IAAI,EAAID,EACtB,MAAAD,CACF,EAEA,aAAa,QAAQD,EAAK,KAAK,UAAUG,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,EAChC,KAAK,SAAS,eAAiBA,EAExBD,CACT,CAqBA,MAAM,YAAYG,EAA6B,CAC7C,IAAMF,EAAiB,KAAK,SAAS,eACrC,GAAI,CAACA,EACH,MAAM,IAAIb,EAAS,yBAAyB,EAG9C,GAAM,CAAE,KAAAD,CAAK,EAAI,MAAM,KAAK,SAAS,aAAa,KAAK,uBAAwB,CAC7E,KAAM,CACJ,eAAAc,EACA,GAAGE,CACL,CACF,CAAC,EAED,GAAI,CAAChB,EAAM,MAAM,IAAIC,EAAS,wCAAwC,EAItE,OAAOD,EAAK,OAAQiB,GAAYA,EAAQ,OAAS,iBAAiB,CACpE,CAcA,MAAM,WAAWC,EAAuCC,EAAoD,CAC1G,IAAMC,EAAsB,CAC1B,qBAAsBD,EACtB,eAAgB,KAAK,SAAS,eAC9B,UAAAD,EACA,WAAY,KAAK,SAAS,YAAc,UACxC,YAAa,OAAO,OAAO,MAC3B,aAAc,OAAO,OAAO,OAC5B,WAAY,OAAO,OAAO,OAAS,IAAM,SAAW,QACpD,IAAK,OAAO,SAAS,KACrB,UAAW,OAAO,UAAU,SAC9B,EAEA,OAAO,KAAK,SAAS,SAAS,KAAK,wBAAyB,CAC1D,KAAAE,CACF,CAAC,CACH,CAaA,aAAwB,CACtB,OAAO,KAAK,QACd,CAaA,kBAAkC,CAChC,OAAOC,EAAS,CAClB,CACF","names":["index_exports","__export","CONVERSATION_ID","Client","JWT_TOKEN","SDKError","SESSION_ID","TTL","USER_ID","auth_default","deleteConversationId","error_default","getConversationId","getSessionId","getToken","getUserId","headers_default","isTokenExpired","setConversationId","setSessionId","setToken","setUserId","__toCommonJS","import_openapi_fetch","CONVERSATION_ID","deleteConversationId","getConversationId","setConversationId","conversationId","SESSION_ID","getSessionId","setSessionId","sessionId","getItemWithExpiry","key","itemString","item","getItemWithExpiry_default","setItemWithExpiry","key","value","ttl","item","setItemWithExpiry_default","day","USER_ID","TTL","getUserId","userId","getItemWithExpiry_default","setUserId","setItemWithExpiry_default","JWT_TOKEN","isTokenExpired","token","payloadBase64","payload","error","getToken","setToken","authMiddleware","accessToken","request","auth_default","errorMiddleware","response","data","error_default","headerMiddleware","identity","url","request","headers_default","version","SDKError","_SDKError","userMessage","cause","version","Client","config","conversationUrl","customerId","fetch","frontendUrl","defaultHeaders","headers","version","createClient","getConversationId","getSessionId","getUserId","error_default","headers_default","sessionId","userId","data","SDKError","setSessionId","setUserId","setToken","endpoint","auth_default","error","deleteConversationId","context","userMessage","conversationContext","conversationIdMessage","rest","conversationId","setConversationId","payload","message","eventName","properties","body","getToken"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/client.ts","../src/utils/getItemWithExpiry.ts","../src/utils/setItemWithExpiry.ts","../src/identity/createIdentityStore.ts","../src/middlewares/auth.ts","../src/middlewares/error.ts","../src/middlewares/headers.ts","../src/restoreConversation/restoreConversation.ts","../package.json","../src/utils/SDKError.ts"],"sourcesContent":["export * from './client'\nexport * from './middlewares'\nexport * from './types'\n","import createClient, { type ClientOptions } from 'openapi-fetch'\n\nimport { createIdentityStore } from './identity/createIdentityStore'\nimport { authMiddleware, errorMiddleware, headerMiddleware } from './middlewares'\nimport { restoreConversation } from './restoreConversation/restoreConversation'\nimport type { components, paths as conversationPaths } from './schemas/conversation'\nimport type { paths as frontendPaths } from './schemas/frontend'\nimport type {\n Config,\n ConversationIdMessage,\n Endpoint,\n Identity,\n Message,\n RestoredTurn,\n SendMessagePayload,\n TrackingEvent,\n UserStartConversationMessage,\n} from './types'\nimport { version } from '../package.json'\nimport SDKError from './utils/SDKError'\n\n/**\n * The `Client` class provides methods to manage 15gifts API.\n */\nexport class Client {\n /**\n * This can be used to interact with the APIs directly. It is recommended to use the [helper methods](/sdk/sdk-reference/classes/client/#methods) provided by the `Client` class instead.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * const { data } = await client.endpoint.conversation.POST('/api/conversation/v3')\n * ```\n */\n endpoint: Endpoint\n\n /**\n * The identity information.\n */\n identity: Identity\n\n /**\n * Creates a new instance of the `Client` class.\n *\n * @param config - Configuration options for initializing the client.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * ```\n */\n constructor(config: Config) {\n const { conversationUrl, customerId, fetch, frontendUrl, headers: defaultHeaders } = config\n\n const headers: ClientOptions['headers'] = {\n ...defaultHeaders,\n 'X-SDK-VERSION': version,\n }\n\n this.endpoint = {\n conversation: createClient<conversationPaths>({\n baseUrl: conversationUrl,\n fetch,\n headers,\n credentials: 'include',\n }),\n frontend: createClient<frontendPaths>({ baseUrl: frontendUrl, fetch, headers }),\n }\n\n this.identity = createIdentityStore(customerId)\n\n this.endpoint.conversation.use(errorMiddleware)\n this.endpoint.conversation.use(headerMiddleware(this.identity, window.location.href))\n }\n\n /**\n * Creates a new identity for the user by generating a session ID and user ID if they don't exist, and sets the access token for future API calls.\n * Ends the current conversation if a conversation ID is present before sending a request to update identity.\n * This should not be called more than once per page load.\n *\n * @returns A promise that resolves once the identity is created and the access token is set.\n *\n * @example\n * ```ts\n * await client.createIdentity()\n * console.log('Identity created:', client.identity)\n * ```\n */\n async createIdentity(): Promise<void> {\n const { customerId, sessionId, userId } = this.identity\n\n try {\n const { data } = await this.endpoint.frontend.POST('/api/tracking/identity/v2', {\n body: {\n customerId,\n sessionId,\n userId,\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n },\n })\n\n if (!data) {\n throw new SDKError('No data received from identity API')\n }\n\n this.identity.pageviewId = data.pageviewId\n\n if (!sessionId) {\n this.identity.sessionId = data.sessionId\n }\n if (!userId) {\n this.identity.userId = data.userId\n }\n\n this.identity.token = data.token\n\n // Add the access token to the Authorization header for all endpoints\n Object.values(this.endpoint).forEach((endpoint) => {\n endpoint.use(authMiddleware(data.token))\n })\n } catch (error) {\n // Enable the auth middleware without a token so that it will throw an error before sending\n // the next request, preventing unnecessary API calls / 401 responses.\n Object.values(this.endpoint).forEach((endpoint) => {\n endpoint.use(authMiddleware())\n })\n throw new SDKError('Failed to create identity', {\n cause: error as Error,\n })\n }\n }\n\n /**\n * Ends the current conversation by deleting the conversation ID.\n *\n * @example\n * ```ts\n * client.endConversation()\n * console.log('Conversation ended')\n * ```\n */\n endConversation(): void {\n this.identity.conversationId = undefined\n }\n\n /**\n * Clears the existing conversation ID, then generates a new one and returns the opening message.\n *\n * @param context - Optional context to customize the conversation. It can include:\n * @param context.eligibleProducts An array of eligible product IDs.\n * @param context.eligibleBundles An array of eligible bundle IDs.\n * @param context.productOverrides Overrides for product details.\n * @param context.bundleOverrides Overrides for bundle details.\n *\n * @returns A promise that resolves to the opening message.\n *\n * @example\n * ##### Basic usage\n * ```ts\n * const openingMessage = await client.startConversation()\n * console.log('Opening message:', openingMessage)\n * ```\n *\n * ##### With context\n * ```ts\n * const openingMessage = await client.startConversation({ eligibleProducts: ['product-1', 'product-2'], productOverrides: { 'product-1': { price: 40 } })\n * console.log('Opening message:', openingMessage)\n * ```\n */\n async startConversation(\n context?: components['schemas']['ConversationContext'],\n userMessage?: UserStartConversationMessage['openingUserMessage'],\n ): Promise<Message[]> {\n this.endConversation()\n\n const conversationContext = {\n ...context,\n }\n\n const { data } = await this.endpoint.conversation.POST(`/api/conversation/v3`, {\n body: {\n type: 'START_CONVERSATION',\n conversationContext,\n openingUserMessage: userMessage,\n },\n })\n\n if (!data) throw new SDKError('No data received from Conversation API')\n\n const [conversationIdMessage, ...rest] = data as [ConversationIdMessage, ...Message[]]\n\n const conversationId = conversationIdMessage.conversationId\n if (!conversationId) {\n throw new SDKError('Conversation ID not received in API response')\n }\n\n this.identity.conversationId = conversationId\n\n return rest\n }\n\n /**\n * Sends a message in the conversation.\n *\n * @param options - An object containing the user message.\n * @returns A promise that resolves to an array of messages\n *\n * @example\n * ```ts\n * const newMessages = await client.sendMessage({\n * userMessage: 'How can I get support?',\n * })\n *\n * if (newMessages) {\n * console.log('Received messages:', newMessages)\n * } else {\n * console.log('No message received')\n * }\n * ```\n */\n async sendMessage(payload: SendMessagePayload) {\n const conversationId = this.identity.conversationId\n if (!conversationId) {\n throw new SDKError('Conversation ID not set')\n }\n\n const { data } = await this.endpoint.conversation.POST('/api/conversation/v3', {\n body: {\n conversationId,\n ...payload,\n },\n })\n\n if (!data) throw new SDKError('No data received from conversation API')\n\n // Removes any `CONVERSATION_ID` messages from the API response. In reality, these messages will only\n // appear in the response to a `START_CONVERSATION` request.\n return data.filter((message) => message.type !== 'CONVERSATION_ID')\n }\n\n /**\n * Sends an event to the tracking API, with the required properties already set.\n *\n * @param eventName - The name of the event to track.\n * @param properties - Additional properties to include in the event.\n * @returns A promise that resolves once the event is tracked.\n *\n * @example\n * ```ts\n * await client.trackEvent('entry_point-shown')\n * ```\n */\n async trackEvent(eventName: TrackingEvent['eventName'], properties?: TrackingEvent['additionalProperties']) {\n const body: TrackingEvent = {\n additionalProperties: properties,\n conversationId: this.identity.conversationId,\n eventName,\n pageviewId: this.identity.pageviewId ?? 'unknown',\n screenWidth: window.screen.width,\n screenHeight: window.screen.height,\n screenSize: window.screen.width <= 480 ? 'mobile' : 'large',\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n }\n\n return this.endpoint.frontend.POST('/api/tracking/user/v2', {\n body,\n })\n }\n\n /**\n * Gets an existing identity of the user.\n *\n * @returns An Identity object containing `customerId`, `conversationId`, `sessionId`, `userId`.\n *\n * @example\n * ```ts\n * identity = client.getIdentity()\n * console.log('Identity retrieved:', identity)\n * ```\n */\n getIdentity(): Identity {\n return this.identity\n }\n\n /**\n * Gets the JWT from the localStorage.\n * Use this method to retrieve the token for use in other parts of your system,\n * such as calling the Humara sales tracking API\n *\n * @returns {string | null} the JWT.\n *\n * @example\n * ```ts\n * token = client.getIdentityToken()\n * console.log('Identity token retrieved:', token)\n * ```\n */\n getIdentityToken(): string | null {\n return this.identity.token ?? null\n }\n\n /**\n * Gets the conversation history for a given conversation ID.\n *\n * @param conversationId - The ID of the conversation to retrieve.\n * @returns A promise that resolves to the conversation history as an array of turns. Each turn contains a user message and its corresponding response.\n */\n async getConversation(conversationId: string): Promise<RestoredTurn[]> {\n if (!conversationId) {\n throw new SDKError('Conversation ID not set')\n }\n\n try {\n const { data } = await this.endpoint.conversation.GET('/api/conversation/{conversation_id}/v1', {\n params: {\n path: {\n conversation_id: conversationId,\n },\n },\n })\n\n // Sets the current conversation ID to the one just retrieved, so that subsequent calls to `sendMessage` and `trackEvent` will use this conversation ID.\n this.identity.conversationId = conversationId\n\n if (!data) throw new SDKError('No data received from conversation history API')\n\n return restoreConversation(data)\n } catch (error) {\n throw new SDKError('Failed to get conversation history', {\n cause: error as Error,\n })\n }\n }\n}\n","const getItemWithExpiry = (key: string) => {\n const itemString = localStorage.getItem(key)\n\n if (!itemString) return null\n\n const item = JSON.parse(itemString) as { expires: number; value: string }\n\n if (Date.now() > item.expires) {\n localStorage.removeItem(key)\n\n return null\n }\n\n return item.value\n}\n\nexport default getItemWithExpiry\n","/**\n * Set an item in localStorage with an expiration time\n * @param key The key under which the value is stored in localStorage\n * @param value The value to be stored\n * @param ttl The time-to-live (TTL) in milliseconds\n */\nconst setItemWithExpiry = (key: string, value: string, ttl: number) => {\n const item = {\n expires: Date.now() + ttl,\n value,\n }\n\n localStorage.setItem(key, JSON.stringify(item))\n}\n\nexport default setItemWithExpiry\n","import type { Config, Identity } from '../types'\nimport { getItemWithExpiry, setItemWithExpiry } from '../utils'\n\ntype IdentityKey = 'conversationId' | 'sessionId' | 'token' | 'userId'\n\nconst day = 1000 * 60 * 60 * 24\nconst userIdTtl = day * 30\n\nconst conversationIdKey = '__15gifts_conversation_id'\nconst sessionIdKey = '__15gifts_session_id'\nconst tokenKey = '__15gifts_identity_token'\nconst userIdKey = '__15gifts_user_id'\n\nconst deleteConversationId = () => sessionStorage.removeItem(conversationIdKey)\nconst getConversationId = () => sessionStorage.getItem(conversationIdKey)\nconst setConversationId = (conversationId: string) => sessionStorage.setItem(conversationIdKey, conversationId)\n\nconst getSessionId = () => sessionStorage.getItem(sessionIdKey)\nconst setSessionId = (sessionId: string) => sessionStorage.setItem(sessionIdKey, sessionId)\n\nconst isTokenExpired = (token: string): boolean => {\n try {\n const [, payloadBase64] = token.split('.')\n if (!payloadBase64) {\n throw new Error('Invalid token payload')\n }\n const payload = JSON.parse(atob(payloadBase64))\n\n return payload.exp && Date.now() / 1000 > payload.exp\n } catch (error) {\n console.error('Invalid token format', error)\n return true\n }\n}\n\nconst getToken = (): string | null => {\n const token = localStorage.getItem(tokenKey)\n\n if (!token || isTokenExpired(token)) {\n localStorage.removeItem(tokenKey)\n return null\n }\n\n return token\n}\n\nconst setToken = (token: string) => localStorage.setItem(tokenKey, token)\n\nconst getUserId = () => {\n const userId = getItemWithExpiry(userIdKey)\n\n if (userId) {\n setUserId(userId)\n }\n\n return userId\n}\n\nconst setUserId = (userId: string) => setItemWithExpiry(userIdKey, userId, userIdTtl)\n\nconst createIdentityProperty = (\n getValue: () => string | null,\n setValue: (value: string) => void,\n clearValue?: () => void,\n): PropertyDescriptor => ({\n enumerable: true,\n configurable: true,\n get: () => getValue() ?? undefined,\n set: (value: string | undefined) => {\n if (value) {\n setValue(value)\n return\n }\n\n clearValue?.()\n },\n})\n\n/**\n * Creates an identity object backed by browser storage.\n *\n * The returned object exposes the public `Identity` shape while keeping\n * `conversationId`, `sessionId`, and `userId` synchronized with their\n * corresponding storage helpers.\n */\nexport const createIdentityStore = (customerId: Config['customerId']): Identity => {\n const identity: Identity = {\n customerId,\n }\n\n const properties: Record<IdentityKey, PropertyDescriptor> = {\n conversationId: createIdentityProperty(getConversationId, setConversationId, deleteConversationId),\n sessionId: createIdentityProperty(getSessionId, setSessionId),\n token: createIdentityProperty(getToken, setToken),\n userId: createIdentityProperty(getUserId, setUserId),\n }\n\n Object.defineProperties(identity, properties)\n\n return identity\n}\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for adding an `Authorization` header to requests.\n *\n * @param accessToken - The token to be included in the `Authorization` header.\n * @returns A middleware object that attaches the access token to the request headers.\n *\n * @example\n * ```ts\n * import { authMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(authMiddleware(accessToken))\n * ```\n */\nconst authMiddleware = (accessToken?: string): Middleware => ({\n onRequest: async ({ request }) => {\n const isIdentityEndpoint = request.url.includes('/identity/')\n if (isIdentityEndpoint) {\n return request\n }\n\n // Throw an error because we know the API will return a 401 if the access token is not set.\n if (!accessToken) {\n throw new Error('Access token is required for authentication.')\n }\n\n request.headers.set('Authorization', `Bearer ${accessToken}`)\n\n return request\n },\n})\n\nexport default authMiddleware\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for handling errors.\n *\n * @returns A middleware object that throws an error if the response is not ok.\n *\n * @example\n * ```ts\n * import { errorMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(errorMiddleware())\n * ```\n */\nconst errorMiddleware: Middleware = {\n // onError does not handle error responses with 4xx or 5xx HTTP status codes, since these are considered \"successful\" responses but with a bad status code.\n // In these cases we need to check the response's status property or ok() method via the onResponse callback.\n onResponse: async ({ response }) => {\n if (!response.ok) {\n const data = await response.json()\n\n throw new Error(data.message)\n }\n\n return response\n },\n}\n\nexport default errorMiddleware\n","import type { Middleware } from 'openapi-fetch'\n\nimport { Identity } from '../types'\n\n/**\n * Middleware for adding request headers that other services use for tracking.\n *\n * @returns A middleware object that throws an error if the response is not ok.\n *\n * @example\n * ```ts\n * import { pageViewId } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(headerMiddleware('123', 'https://example.com'))\n * ```\n */\nconst headerMiddleware = (identity: Identity, url: string): Middleware => ({\n onRequest: async ({ request }) => {\n if (identity.pageviewId) {\n request.headers.set('X-PAGEVIEW-ID', identity.pageviewId)\n }\n if (url) {\n request.headers.set('X-PAGE-URL', url)\n }\n\n return request\n },\n})\n\nexport default headerMiddleware\n","/**\n * The GET `/api/conversation/{conversation_id}` endpoint returns data as a historical record, but\n * it makes little sense when rendered.\n * We transform it so that the user doesn't see all single_select messages again, only the option\n * they selected.\n **/\n\nimport type { ConversationTurn, Message, SingleSelectMessage, UserSingleSelectMessage, RestoredTurn } from '../types'\n\n/**\n * Removes the conversationId from the user message, as this is not needed for rendering and would just add noise.\n */\nconst stripConversationId = <T extends { conversationId?: string }>(userMessage: T): Omit<T, 'conversationId'> => {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { conversationId, ...rest } = userMessage\n\n return rest\n}\n\n// We have the string that was sent to the API, this finds the label for the option that it relates to.\nconst getSelectedOptionLabel = (userMessage: UserSingleSelectMessage, previousTurn?: ConversationTurn) => {\n const previousSingleSelect = previousTurn?.assistantMessages.find(\n (message): message is SingleSelectMessage => message.type === 'SINGLE_SELECT',\n )\n const selectedOption = previousSingleSelect?.options.find((option) => option.value === userMessage.option)\n\n return selectedOption?.label || ''\n}\n\n// Turns the user message back in to how the user would have seen it\nconst getRestoredUserMessage = (\n turn: ConversationTurn,\n previousTurn?: ConversationTurn,\n): RestoredTurn['userMessage'] => {\n const { userMessage } = turn\n\n switch (userMessage.type) {\n case 'SINGLE_SELECT':\n return {\n ...stripConversationId(userMessage),\n userMessage: getSelectedOptionLabel(userMessage, previousTurn),\n }\n\n case 'START_CONVERSATION':\n // There isn't anything we want to render from the START_CONVERSATION message except for the openingUserMessage,\n // which is what the user would have submitted to start the conversation.\n return {\n type: 'MESSAGE',\n userMessage: userMessage.openingUserMessage?.option || '',\n }\n\n case 'MESSAGE':\n return stripConversationId(userMessage)\n\n case 'MULTI_SELECT':\n return stripConversationId(userMessage)\n }\n}\n\n// Turns the assistant message back in to how the user would have seen it\nconst getRestoredAssistantReply = (turn: ConversationTurn, nextTurn?: ConversationTurn) => {\n const shouldHideSingleSelect = Boolean(nextTurn)\n\n return turn.assistantMessages.filter(\n (message): message is Message =>\n message.type !== 'CONVERSATION_ID' && !(shouldHideSingleSelect && message.type === 'SINGLE_SELECT'),\n )\n}\n\nexport const restoreConversation = (turns: ConversationTurn[]): RestoredTurn[] => {\n return turns.map((turn, index) => {\n const previousTurn = index > 0 ? turns[index - 1] : undefined\n const nextTurn = index < turns.length - 1 ? turns[index + 1] : undefined\n\n return {\n id: `restored-turn-${index}`,\n userMessage: getRestoredUserMessage(turn, previousTurn),\n assistantReply: getRestoredAssistantReply(turn, nextTurn),\n }\n })\n}\n","{\n \"name\": \"@15gifts/sdk\",\n \"version\": \"0.20.0\",\n \"files\": [\n \"dist\"\n ],\n \"main\": \"./dist/index.js\",\n \"module\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"scripts\": {\n \"build\": \"tsup\",\n \"coverage\": \"vitest run --coverage\",\n \"generate-types\": \"npx openapi-typescript\",\n \"dev\": \"tsup --watch\",\n \"format\": \"prettier . --write\",\n \"lint\": \"eslint .\",\n \"test:watch\": \"vitest\",\n \"test\": \"vitest run\",\n \"typecheck\": \"tsc\",\n \"update-schemas\": \"node --experimental-strip-types update-schema.ts && npm run generate-types && npm run format\"\n },\n \"dependencies\": {\n \"openapi-fetch\": \"^0.13.4\"\n },\n \"devDependencies\": {\n \"openapi-typescript\": \"^7.6.0\",\n \"tsup\": \"^8.3.6\"\n },\n \"sideEffects\": false,\n \"prettier\": \"prettier-config-custom\"\n}\n","import { version } from '../../package.json'\n\n/**\n * Custom error class for SDK-related errors.\n * Includes the SDK version and an optional cause for better debugging.\n * NOTE: The error.message is intended for developers, not end-users.\n */\nexport default class SDKError extends Error {\n sdkVersion: string\n override cause?: Error\n\n constructor(userMessage: string, { cause }: { cause?: Error } = {}) {\n super(userMessage)\n this.name = 'SDKError'\n this.cause = cause\n this.sdkVersion = version\n\n // Set the prototype explicitly to maintain instanceof checks\n Object.setPrototypeOf(this, SDKError.prototype)\n }\n}\n"],"mappings":"0jBAAA,IAAAA,GAAA,GAAAC,EAAAD,GAAA,YAAAE,EAAA,aAAAC,EAAA,mBAAAC,EAAA,oBAAAC,EAAA,qBAAAC,IAAA,eAAAC,EAAAP,ICAA,IAAAQ,EAAiD,4BCAjD,IAAMC,EAAqBC,GAAgB,CACzC,IAAMC,EAAa,aAA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AAgB,KAAK,SAAS,eAC9B,UAAAD,EACA,WAAY,KAAK,SAAS,YAAc,UACxC,YAAa,OAAO,OAAO,MAC3B,aAAc,OAAO,OAAO,OAC5B,WAAY,OAAO,OAAO,OAAS,IAAM,SAAW,QACpD,IAAK,OAAO,SAAS,KACrB,UAAW,OAAO,UAAU,SAC9B,EAEA,OAAO,KAAK,SAAS,SAAS,KAAK,wBAAyB,CAC1D,KAAAE,CACF,CAAC,CACH,CAaA,aAAwB,CACtB,OAAO,KAAK,QACd,CAeA,kBAAkC,CAChC,OAAO,KAAK,SAAS,OAAS,IAChC,CAQA,MAAM,gBAAgBL,EAAiD,CACrE,GAAI,CAACA,EACH,MAAM,IAAIT,EAAS,yBAAyB,EAG9C,GAAI,CACF,GAAM,CAAE,KAAAD,CAAK,EAAI,MAAM,KAAK,SAAS,aAAa,IAAI,yCAA0C,CAC9F,OAAQ,CACN,KAAM,CACJ,gBAAiBU,CACnB,CACF,CACF,CAAC,EAKD,GAFA,KAAK,SAAS,eAAiBA,EAE3B,CAACV,EAAM,MAAM,IAAIC,EAAS,gDAAgD,EAE9E,OAAOe,EAAoBhB,CAAI,CACjC,OAASI,EAAO,CACd,MAAM,IAAIH,EAAS,qCAAsC,CACvD,MAAOG,CACT,CAAC,CACH,CACF,CACF","names":["index_exports","__export","Client","SDKError","auth_default","error_default","headers_default","__toCommonJS","import_openapi_fetch","getItemWithExpiry","key","itemString","item","getItemWithExpiry_default","setItemWithExpiry","key","value","ttl","item","setItemWithExpiry_default","day","userIdTtl","conversationIdKey","sessionIdKey","tokenKey","userIdKey","deleteConversationId","getConversationId","setConversationId","conversationId","getSessionId","setSessionId","sessionId","isTokenExpired","token","payloadBase64","payload","error","getToken","setToken","getUserId","userId","getItemWithExpiry_default","setUserId","setItemWithExpiry_default","createIdentityProperty","getValue","setValue","clearValue","value","createIdentityStore","customerId","identity","properties","authMiddleware","accessToken","request","auth_default","errorMiddleware","response","data","error_default","headerMiddleware","identity","url","request","headers_default","stripConversationId","userMessage","conversationId","rest","getSelectedOptionLabel","previousTurn","message","option","getRestoredUserMessage","turn","getRestoredAssistantReply","nextTurn","shouldHideSingleSelect","restoreConversation","turns","index","version","SDKError","_SDKError","userMessage","cause","version","Client","config","conversationUrl","customerId","fetch","frontendUrl","defaultHeaders","headers","version","createClient","createIdentityStore","error_default","headers_default","sessionId","userId","data","SDKError","endpoint","auth_default","error","context","userMessage","conversationContext","conversationIdMessage","rest","conversationId","payload","message","eventName","properties","body","restoreConversation"]}
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import R from"openapi-fetch";var g="__15gifts_conversation_id",I=()=>sessionStorage.removeItem(g),x=()=>sessionStorage.getItem(g),y=e=>sessionStorage.setItem(g,e);var E="__15gifts_session_id",M=()=>sessionStorage.getItem(E),S=e=>sessionStorage.setItem(E,e);var O=e=>{let t=localStorage.getItem(e);if(!t)return null;let s=JSON.parse(t);return Date.now()>s.expires?(localStorage.removeItem(e),null):s.value},l=O;var _=(e,t,s)=>{let o={expires:Date.now()+s,value:t};localStorage.setItem(e,JSON.stringify(o))},u=_;var k=1e3*60*60*24,w="__15gifts_user_id",U=k*30,A=()=>{let e=l(w);return e&&f(e),e},f=e=>u(w,e,U);var m="__15gifts_identity_token",N=e=>{try{let[,t]=e.split(".");if(!t)throw new Error("Invalid token payload");let s=JSON.parse(atob(t));return s.exp&&Date.now()/1e3>s.exp}catch(t){return console.error("Invalid token format",t),!0}},C=()=>{let e=localStorage.getItem(m);return!e||N(e)?(localStorage.removeItem(m),null):e},T=e=>localStorage.setItem(m,e);var V=e=>({onRequest:async({request:t})=>{if(t.url.includes("/identity/"))return t;if(!e)throw new Error("Access token is required for authentication.");return t.headers.set("Authorization",`Bearer ${e}`),t}}),p=V;var D={onResponse:async({response:e})=>{if(!e.ok){let t=await e.json();throw new Error(t.message)}return e}},v=D;var b=(e,t)=>({onRequest:async({request:s})=>(e.pageviewId&&s.headers.set("X-PAGEVIEW-ID",e.pageviewId),t&&s.headers.set("X-PAGE-URL",t),s)}),h=b;var d="0.19.0";var i=class e extends Error{sdkVersion;cause;constructor(t,{cause:s}={}){super(t),this.name="SDKError",this.cause=s,this.sdkVersion=d,Object.setPrototypeOf(this,e.prototype)}};var P=class{endpoint;identity;constructor(t){let{conversationUrl:s,customerId:o,fetch:n,frontendUrl:r,headers:c}=t,a={...c,"X-SDK-VERSION":d};this.endpoint={conversation:R({baseUrl:s,fetch:n,headers:a,credentials:"include"}),frontend:R({baseUrl:r,fetch:n,headers:a})},this.identity={customerId:o,conversationId:x()??void 0,sessionId:M()??void 0,userId:A()??void 0},this.endpoint.conversation.use(v),this.endpoint.conversation.use(h(this.identity,window.location.href))}async createIdentity(){let{customerId:t,sessionId:s,userId:o}=this.identity;try{let{data:n}=await this.endpoint.frontend.POST("/api/tracking/identity/v2",{body:{customerId:t,sessionId:s,userId:o,url:window.location.href,userAgent:window.navigator.userAgent}});if(!n)throw new i("No data received from identity API");this.identity.pageviewId=n.pageviewId,s||(this.identity.sessionId=n.sessionId,S(n.sessionId)),o||(this.identity.userId=n.userId,f(n.userId)),T(n.token),Object.values(this.endpoint).forEach(r=>{r.use(p(n.token))})}catch(n){throw Object.values(this.endpoint).forEach(r=>{r.use(p())}),new i("Failed to create identity",{cause:n})}}endConversation(){I(),this.identity.conversationId=void 0}async startConversation(t,s){this.endConversation();let o={...t},{data:n}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{type:"START_CONVERSATION",conversationContext:o,openingUserMessage:s}});if(!n)throw new i("No data received from Conversation API");let[r,...c]=n,a=r.conversationId;if(!a)throw new i("Conversation ID not received in API response");return y(a),this.identity.conversationId=a,c}async sendMessage(t){let s=this.identity.conversationId;if(!s)throw new i("Conversation ID not set");let{data:o}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{conversationId:s,...t}});if(!o)throw new i("No data received from conversation API");return o.filter(n=>n.type!=="CONVERSATION_ID")}async trackEvent(t,s){let o={additionalProperties:s,conversationId:this.identity.conversationId,eventName:t,pageviewId:this.identity.pageviewId??"unknown",screenWidth:window.screen.width,screenHeight:window.screen.height,screenSize:window.screen.width<=480?"mobile":"large",url:window.location.href,userAgent:window.navigator.userAgent};return this.endpoint.frontend.POST("/api/tracking/user/v2",{body:o})}getIdentity(){return this.identity}getIdentityToken(){return C()}};export{g as CONVERSATION_ID,P as Client,m as JWT_TOKEN,i as SDKError,E as SESSION_ID,U as TTL,w as USER_ID,p as authMiddleware,I as deleteConversationId,v as errorMiddleware,x as getConversationId,M as getSessionId,C as getToken,A as getUserId,h as headerMiddleware,N as isTokenExpired,y as setConversationId,S as setSessionId,T as setToken,f as setUserId};
1
+ import T from"openapi-fetch";var w=t=>{let s=localStorage.getItem(t);if(!s)return null;let e=JSON.parse(s);return Date.now()>e.expires?(localStorage.removeItem(t),null):e.value},u=w;var A=(t,s,e)=>{let n={expires:Date.now()+e,value:s};localStorage.setItem(t,JSON.stringify(n))},l=A;var R=1e3*60*60*24,P=R*30,y="__15gifts_conversation_id",h="__15gifts_session_id",v="__15gifts_identity_token",M="__15gifts_user_id",O=()=>sessionStorage.removeItem(y),_=()=>sessionStorage.getItem(y),U=t=>sessionStorage.setItem(y,t),k=()=>sessionStorage.getItem(h),N=t=>sessionStorage.setItem(h,t),b=t=>{try{let[,s]=t.split(".");if(!s)throw new Error("Invalid token payload");let e=JSON.parse(atob(s));return e.exp&&Date.now()/1e3>e.exp}catch(s){return console.error("Invalid token format",s),!0}},V=()=>{let t=localStorage.getItem(v);return!t||b(t)?(localStorage.removeItem(v),null):t},D=t=>localStorage.setItem(v,t),L=()=>{let t=u(M);return t&&E(t),t},E=t=>l(M,t,P),d=(t,s,e)=>({enumerable:!0,configurable:!0,get:()=>t()??void 0,set:n=>{if(n){s(n);return}e?.()}}),x=t=>{let s={customerId:t},e={conversationId:d(_,U,O),sessionId:d(k,N),token:d(V,D),userId:d(L,E)};return Object.defineProperties(s,e),s};var G=t=>({onRequest:async({request:s})=>{if(s.url.includes("/identity/"))return s;if(!t)throw new Error("Access token is required for authentication.");return s.headers.set("Authorization",`Bearer ${t}`),s}}),p=G;var j={onResponse:async({response:t})=>{if(!t.ok){let s=await t.json();throw new Error(s.message)}return t}},m=j;var q=(t,s)=>({onRequest:async({request:e})=>(t.pageviewId&&e.headers.set("X-PAGEVIEW-ID",t.pageviewId),s&&e.headers.set("X-PAGE-URL",s),e)}),f=q;var I=t=>{let{conversationId:s,...e}=t;return e},K=(t,s)=>s?.assistantMessages.find(o=>o.type==="SINGLE_SELECT")?.options.find(o=>o.value===t.option)?.label||"",W=(t,s)=>{let{userMessage:e}=t;switch(e.type){case"SINGLE_SELECT":return{...I(e),userMessage:K(e,s)};case"START_CONVERSATION":return{type:"MESSAGE",userMessage:e.openingUserMessage?.option||""};case"MESSAGE":return I(e);case"MULTI_SELECT":return I(e)}},H=(t,s)=>{let e=!!s;return t.assistantMessages.filter(n=>n.type!=="CONVERSATION_ID"&&!(e&&n.type==="SINGLE_SELECT"))},S=t=>t.map((s,e)=>{let n=e>0?t[e-1]:void 0,o=e<t.length-1?t[e+1]:void 0;return{id:`restored-turn-${e}`,userMessage:W(s,n),assistantReply:H(s,o)}});var c="0.20.0";var r=class t extends Error{sdkVersion;cause;constructor(s,{cause:e}={}){super(s),this.name="SDKError",this.cause=e,this.sdkVersion=c,Object.setPrototypeOf(this,t.prototype)}};var C=class{endpoint;identity;constructor(s){let{conversationUrl:e,customerId:n,fetch:o,frontendUrl:i,headers:g}=s,a={...g,"X-SDK-VERSION":c};this.endpoint={conversation:T({baseUrl:e,fetch:o,headers:a,credentials:"include"}),frontend:T({baseUrl:i,fetch:o,headers:a})},this.identity=x(n),this.endpoint.conversation.use(m),this.endpoint.conversation.use(f(this.identity,window.location.href))}async createIdentity(){let{customerId:s,sessionId:e,userId:n}=this.identity;try{let{data:o}=await this.endpoint.frontend.POST("/api/tracking/identity/v2",{body:{customerId:s,sessionId:e,userId:n,url:window.location.href,userAgent:window.navigator.userAgent}});if(!o)throw new r("No data received from identity API");this.identity.pageviewId=o.pageviewId,e||(this.identity.sessionId=o.sessionId),n||(this.identity.userId=o.userId),this.identity.token=o.token,Object.values(this.endpoint).forEach(i=>{i.use(p(o.token))})}catch(o){throw Object.values(this.endpoint).forEach(i=>{i.use(p())}),new r("Failed to create identity",{cause:o})}}endConversation(){this.identity.conversationId=void 0}async startConversation(s,e){this.endConversation();let n={...s},{data:o}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{type:"START_CONVERSATION",conversationContext:n,openingUserMessage:e}});if(!o)throw new r("No data received from Conversation API");let[i,...g]=o,a=i.conversationId;if(!a)throw new r("Conversation ID not received in API response");return this.identity.conversationId=a,g}async sendMessage(s){let e=this.identity.conversationId;if(!e)throw new r("Conversation ID not set");let{data:n}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{conversationId:e,...s}});if(!n)throw new r("No data received from conversation API");return n.filter(o=>o.type!=="CONVERSATION_ID")}async trackEvent(s,e){let n={additionalProperties:e,conversationId:this.identity.conversationId,eventName:s,pageviewId:this.identity.pageviewId??"unknown",screenWidth:window.screen.width,screenHeight:window.screen.height,screenSize:window.screen.width<=480?"mobile":"large",url:window.location.href,userAgent:window.navigator.userAgent};return this.endpoint.frontend.POST("/api/tracking/user/v2",{body:n})}getIdentity(){return this.identity}getIdentityToken(){return this.identity.token??null}async getConversation(s){if(!s)throw new r("Conversation ID not set");try{let{data:e}=await this.endpoint.conversation.GET("/api/conversation/{conversation_id}/v1",{params:{path:{conversation_id:s}}});if(this.identity.conversationId=s,!e)throw new r("No data received from conversation history API");return S(e)}catch(e){throw new r("Failed to get conversation history",{cause:e})}}};export{C as Client,r as SDKError,p as authMiddleware,m as errorMiddleware,f as headerMiddleware};
2
2
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client.ts","../src/identity/conversationId.ts","../src/identity/sessionId.ts","../src/utils/getItemWithExpiry.ts","../src/utils/setItemWithExpiry.ts","../src/identity/userId.ts","../src/identity/token.ts","../src/middlewares/auth.ts","../src/middlewares/error.ts","../src/middlewares/headers.ts","../package.json","../src/utils/SDKError.ts"],"sourcesContent":["import createClient, { type ClientOptions } from 'openapi-fetch'\n\nimport {\n deleteConversationId,\n getConversationId,\n getSessionId,\n getUserId,\n getToken,\n setConversationId,\n setSessionId,\n setUserId,\n setToken,\n} from './identity'\nimport { authMiddleware, errorMiddleware, headerMiddleware } from './middlewares'\nimport type { components, paths as conversationPaths } from './schemas/conversation'\nimport type { paths as frontendPaths } from './schemas/frontend'\nimport type {\n Config,\n ConversationIdMessage,\n Endpoint,\n Identity,\n Message,\n SendMessagePayload,\n TrackingEvent,\n UserStartConversationMessage,\n} from './types'\nimport { version } from '../package.json'\nimport SDKError from './utils/SDKError'\n\n/**\n * The `Client` class provides methods to manage 15gifts API.\n */\nexport class Client {\n /**\n * This can be used to interact with the APIs directly. It is recommended to use the [helper methods](/sdk/sdk-reference/classes/client/#methods) provided by the `Client` class instead.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * const { data } = await client.endpoint.conversation.POST('/api/conversation/v3')\n * ```\n */\n endpoint: Endpoint\n\n /**\n * The identity information.\n */\n identity: Identity\n\n /**\n * Creates a new instance of the `Client` class.\n *\n * @param config - Configuration options for initializing the client.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * ```\n */\n constructor(config: Config) {\n const { conversationUrl, customerId, fetch, frontendUrl, headers: defaultHeaders } = config\n\n const headers: ClientOptions['headers'] = {\n ...defaultHeaders,\n 'X-SDK-VERSION': version,\n }\n\n this.endpoint = {\n conversation: createClient<conversationPaths>({\n baseUrl: conversationUrl,\n fetch,\n headers,\n credentials: 'include',\n }),\n frontend: createClient<frontendPaths>({ baseUrl: frontendUrl, fetch, headers }),\n }\n\n this.identity = {\n customerId,\n conversationId: getConversationId() ?? undefined,\n sessionId: getSessionId() ?? undefined,\n userId: getUserId() ?? undefined,\n }\n\n this.endpoint.conversation.use(errorMiddleware)\n this.endpoint.conversation.use(headerMiddleware(this.identity, window.location.href))\n }\n\n /**\n * Creates a new identity for the user by generating a session ID and user ID if they don't exist, and sets the access token for future API calls.\n * Ends the current conversation if a conversation ID is present before sending a request to update identity.\n * This should not be called more than once per page load.\n *\n * @returns A promise that resolves once the identity is created and the access token is set.\n *\n * @example\n * ```ts\n * await client.createIdentity()\n * console.log('Identity created:', client.identity)\n * ```\n */\n async createIdentity(): Promise<void> {\n const { customerId, sessionId, userId } = this.identity\n\n try {\n const { data } = await this.endpoint.frontend.POST('/api/tracking/identity/v2', {\n body: {\n customerId,\n sessionId,\n userId,\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n },\n })\n\n if (!data) {\n throw new SDKError('No data received from identity API')\n }\n\n this.identity.pageviewId = data.pageviewId\n\n if (!sessionId) {\n this.identity.sessionId = data.sessionId\n setSessionId(data.sessionId)\n }\n if (!userId) {\n this.identity.userId = data.userId\n setUserId(data.userId)\n }\n\n setToken(data.token)\n\n // Add the access token to the Authorization header for all endpoints\n Object.values(this.endpoint).forEach((endpoint) => {\n endpoint.use(authMiddleware(data.token))\n })\n } catch (error) {\n // Enable the auth middleware without a token so that it will throw an error before sending\n // the next request, preventing unnecessary API calls / 401 responses.\n Object.values(this.endpoint).forEach((endpoint) => {\n endpoint.use(authMiddleware())\n })\n throw new SDKError('Failed to create identity', {\n cause: error as Error,\n })\n }\n }\n\n /**\n * Ends the current conversation by deleting the conversation ID.\n *\n * @example\n * ```ts\n * client.endConversation()\n * console.log('Conversation ended')\n * ```\n */\n endConversation(): void {\n deleteConversationId()\n this.identity.conversationId = undefined\n }\n\n /**\n * Clears the existing conversation ID, then generates a new one and returns the opening message.\n *\n * @param context - Optional context to customize the conversation. It can include:\n * @param context.eligibleProducts An array of eligible product IDs.\n * @param context.eligibleBundles An array of eligible bundle IDs.\n * @param context.productOverrides Overrides for product details.\n * @param context.bundleOverrides Overrides for bundle details.\n *\n * @returns A promise that resolves to the opening message.\n *\n * @example\n * ##### Basic usage\n * ```ts\n * const openingMessage = await client.startConversation()\n * console.log('Opening message:', openingMessage)\n * ```\n *\n * ##### With context\n * ```ts\n * const openingMessage = await client.startConversation({ eligibleProducts: ['product-1', 'product-2'], productOverrides: { 'product-1': { price: 40 } })\n * console.log('Opening message:', openingMessage)\n * ```\n */\n async startConversation(\n context?: components['schemas']['ConversationContext'],\n userMessage?: UserStartConversationMessage['openingUserMessage'],\n ): Promise<Message[]> {\n this.endConversation()\n\n const conversationContext = {\n ...context,\n }\n\n const { data } = await this.endpoint.conversation.POST(`/api/conversation/v3`, {\n body: {\n type: 'START_CONVERSATION',\n conversationContext,\n openingUserMessage: userMessage,\n },\n })\n\n if (!data) throw new SDKError('No data received from Conversation API')\n\n const [conversationIdMessage, ...rest] = data as [ConversationIdMessage, ...Message[]]\n\n const conversationId = conversationIdMessage.conversationId\n if (!conversationId) {\n throw new SDKError('Conversation ID not received in API response')\n }\n\n setConversationId(conversationId)\n this.identity.conversationId = conversationId\n\n return rest\n }\n\n /**\n * Sends a message in the conversation.\n *\n * @param options - An object containing the user message.\n * @returns A promise that resolves to an array of messages\n *\n * @example\n * ```ts\n * const newMessages = await client.sendMessage({\n * userMessage: 'How can I get support?',\n * })\n *\n * if (newMessages) {\n * console.log('Received messages:', newMessages)\n * } else {\n * console.log('No message received')\n * }\n * ```\n */\n async sendMessage(payload: SendMessagePayload) {\n const conversationId = this.identity.conversationId\n if (!conversationId) {\n throw new SDKError('Conversation ID not set')\n }\n\n const { data } = await this.endpoint.conversation.POST('/api/conversation/v3', {\n body: {\n conversationId,\n ...payload,\n },\n })\n\n if (!data) throw new SDKError('No data received from conversation API')\n\n // Removes any `CONVERSATION_ID` messages from the API response. In reality, these messages will only\n // appear in the response to a `START_CONVERSATION` request.\n return data.filter((message) => message.type !== 'CONVERSATION_ID')\n }\n\n /**\n * Sends an event to the tracking API, with the required properties already set.\n *\n * @param eventName - The name of the event to track.\n * @param properties - Additional properties to include in the event.\n * @returns A promise that resolves once the event is tracked.\n *\n * @example\n * ```ts\n * await client.trackEvent('entry_point-shown')\n * ```\n */\n async trackEvent(eventName: TrackingEvent['eventName'], properties?: TrackingEvent['additionalProperties']) {\n const body: TrackingEvent = {\n additionalProperties: properties,\n conversationId: this.identity.conversationId,\n eventName,\n pageviewId: this.identity.pageviewId ?? 'unknown',\n screenWidth: window.screen.width,\n screenHeight: window.screen.height,\n screenSize: window.screen.width <= 480 ? 'mobile' : 'large',\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n }\n\n return this.endpoint.frontend.POST('/api/tracking/user/v2', {\n body,\n })\n }\n\n /**\n * Gets an existing identity of the user.\n *\n * @returns An Identity object containing `customerId`, `conversationId`, `sessionId`, `userId`.\n *\n * @example\n * ```ts\n * identity = client.getIdentity()\n * console.log('Identity retrieved:', identity)\n * ```\n */\n getIdentity(): Identity {\n return this.identity\n }\n\n /**\n * Gets the JWT from the localStorage.\n *\n * @returns {string | null} the JWT.\n *\n * @example\n * ```ts\n * token = client.getIdentityToken()\n * console.log('Identity token retrieved:', token)\n * ```\n */\n getIdentityToken(): string | null {\n return getToken()\n }\n}\n","/**\n * The key used to store the conversation ID in `sessionStorage`.\n *\n * @ignore\n */\nexport const CONVERSATION_ID = '__15gifts_conversation_id'\n\n/**\n * Deletes the conversation ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { deleteConversationId } from '@15gifts/sdk'\n *\n * deleteConversationId()\n * // The conversation ID will be removed.\n * ```\n */\nexport const deleteConversationId = () => sessionStorage.removeItem(CONVERSATION_ID)\n\n/**\n * Retrieves the conversation ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { getConversationId } from '@15gifts/sdk'\n *\n * const conversationId = getConversationId()\n *\n * if (conversationId) {\n * console.log(`Conversation ID: ${conversationId}`)\n * } else {\n * console.log('No conversation ID found.')\n * }\n * ```\n */\nexport const getConversationId = () => sessionStorage.getItem(CONVERSATION_ID)\n\n/**\n * Stores the given conversation ID in `sessionStorage`.\n *\n * @example\n * ```ts\n * import { setConversationId } from '@15gifts/sdk'\n *\n * setConversationId('ca0ab4ce-f697-41cc-8d0c-081762aace9b')\n * // The conversation ID 'ca0ab4ce-f697-41cc-8d0c-081762aace9b' will be stored.\n * ```\n */\nexport const setConversationId = (conversationId: string) => sessionStorage.setItem(CONVERSATION_ID, conversationId)\n","/**\n * The key used to store the session ID in `sessionStorage`.\n *\n * @ignore\n */\nexport const SESSION_ID = '__15gifts_session_id'\n\n/**\n * Retrieves the session ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { getSessionId } from '@15gifts/sdk'\n *\n * const sessionId = getSessionId()\n *\n * if (sessionId) {\n * console.log(`Session ID: ${sessionId}`)\n * } else {\n * console.log('No session ID found.')\n * }\n * ```\n */\nexport const getSessionId = () => sessionStorage.getItem(SESSION_ID)\n\n/**\n * Stores the given session ID in `sessionStorage`.\n *\n * @example\n * ```ts\n * import { setSessionId } from '@15gifts/sdk'\n *\n * setSessionId('20b2bff6-64a0-4101-bed9-ff545326584a')\n * // The session ID '20b2bff6-64a0-4101-bed9-ff545326584a' will be stored.\n * ```\n */\nexport const setSessionId = (sessionId: string) => sessionStorage.setItem(SESSION_ID, sessionId)\n","const getItemWithExpiry = (key: string) => {\n const itemString = localStorage.getItem(key)\n\n if (!itemString) return null\n\n const item = JSON.parse(itemString) as { expires: number; value: string }\n\n if (Date.now() > item.expires) {\n localStorage.removeItem(key)\n\n return null\n }\n\n return item.value\n}\n\nexport default getItemWithExpiry\n","/**\n * Set an item in localStorage with an expiration time\n * @param key The key under which the value is stored in localStorage\n * @param value The value to be stored\n * @param ttl The time-to-live (TTL) in milliseconds\n */\nconst setItemWithExpiry = (key: string, value: string, ttl: number) => {\n const item = {\n expires: Date.now() + ttl,\n value,\n }\n\n localStorage.setItem(key, JSON.stringify(item))\n}\n\nexport default setItemWithExpiry\n","import { getItemWithExpiry, setItemWithExpiry } from '../utils'\nconst day = 1000 * 60 * 60 * 24\n\n/**\n * The key used to store the user ID in `localStorage`.\n *\n * @ignore\n */\nexport const USER_ID = '__15gifts_user_id'\n\n/**\n * Time-to-live (TTL) for the user ID in milliseconds.\n * Set to 30 days.\n *\n * @ignore\n */\nexport const TTL = day * 30\n\n/**\n * Retrieves the user ID from `localStorage` and updates its expiry time.\n *\n * @example\n * ```ts\n * import { getUserId } from '@15gifts/sdk'\n *\n * const userId = getUserId()\n *\n * if (userId) {\n * console.log(`User ID: ${userId}`)\n * } else {\n * console.log('No user ID found.')\n * }\n * ```\n */\nexport const getUserId = () => {\n const userId = getItemWithExpiry(USER_ID)\n\n // Update the userId with a new expiry time\n // So that it will be valid for another 30 days, rather than 30 days from when it was first set\n if (userId) {\n setUserId(userId)\n }\n\n return userId\n}\n\n/**\n * Stores the given user ID in `localStorage`.\n *\n * @example\n * ```ts\n * import { setUserId } from '@15gifts/sdk'\n *\n * setUserId('5b77656c-ea4c-492f-82bf-7129297c5873')\n * // The user ID '5b77656c-ea4c-492f-82bf-7129297c5873' will be stored with a 30-day expiry.\n * ```\n */\nexport const setUserId = (userId: string) => setItemWithExpiry(USER_ID, userId, TTL)\n","/**\n * The key used to store the JWT in `localStorage`.\n *\n * @ignore\n */\nexport const JWT_TOKEN = '__15gifts_identity_token'\n\n/**\n * Checks if the JWT is expired.\n *\n * @param {string} token - the JWT.\n * @returns {boolean} `true` if expired, `false` otherwise.\n */\nexport const isTokenExpired = (token: string): boolean => {\n try {\n const [, payloadBase64] = token.split('.')\n if (!payloadBase64) {\n throw new Error('Invalid token payload')\n }\n const payload = JSON.parse(atob(payloadBase64))\n\n return payload.exp && Date.now() / 1000 > payload.exp\n } catch (error) {\n console.error('Invalid token format', error)\n return true\n }\n}\n\n/**\n * Retrieves the JWT from `localStorage` and checks if it is expired.\n *\n * @returns {string | null} The JWT if valid, otherwise `null`.\n */\nexport const getToken = (): string | null => {\n const token = localStorage.getItem(JWT_TOKEN)\n\n if (!token || isTokenExpired(token)) {\n localStorage.removeItem(JWT_TOKEN)\n return null\n }\n\n return token\n}\n\n/**\n * Stores the given JWT in `localStorage`.\n *\n * @example\n * ```ts\n * import { setToken } from '@15gifts/sdk'\n *\n * setToken('ey...')\n * ```\n */\nexport const setToken = (token: string) => localStorage.setItem(JWT_TOKEN, token)\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for adding an `Authorization` header to requests.\n *\n * @param accessToken - The token to be included in the `Authorization` header.\n * @returns A middleware object that attaches the access token to the request headers.\n *\n * @example\n * ```ts\n * import { authMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(authMiddleware(accessToken))\n * ```\n */\nconst authMiddleware = (accessToken?: string): Middleware => ({\n onRequest: async ({ request }) => {\n const isIdentityEndpoint = request.url.includes('/identity/')\n if (isIdentityEndpoint) {\n return request\n }\n\n // Throw an error because we know the API will return a 401 if the access token is not set.\n if (!accessToken) {\n throw new Error('Access token is required for authentication.')\n }\n\n request.headers.set('Authorization', `Bearer ${accessToken}`)\n\n return request\n },\n})\n\nexport default authMiddleware\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for handling errors.\n *\n * @returns A middleware object that throws an error if the response is not ok.\n *\n * @example\n * ```ts\n * import { errorMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(errorMiddleware())\n * ```\n */\nconst errorMiddleware: Middleware = {\n // onError does not handle error responses with 4xx or 5xx HTTP status codes, since these are considered \"successful\" responses but with a bad status code.\n // In these cases we need to check the response's status property or ok() method via the onResponse callback.\n onResponse: async ({ response }) => {\n if (!response.ok) {\n const data = await response.json()\n\n throw new Error(data.message)\n }\n\n return response\n },\n}\n\nexport default errorMiddleware\n","import type { Middleware } from 'openapi-fetch'\n\nimport { Identity } from '../types'\n\n/**\n * Middleware for adding request headers that other services use for tracking.\n *\n * @returns A middleware object that throws an error if the response is not ok.\n *\n * @example\n * ```ts\n * import { pageViewId } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(headerMiddleware('123', 'https://example.com'))\n * ```\n */\nconst headerMiddleware = (identity: Identity, url: string): Middleware => ({\n onRequest: async ({ request }) => {\n if (identity.pageviewId) {\n request.headers.set('X-PAGEVIEW-ID', identity.pageviewId)\n }\n if (url) {\n request.headers.set('X-PAGE-URL', url)\n }\n\n return request\n },\n})\n\nexport default headerMiddleware\n","{\n \"name\": \"@15gifts/sdk\",\n \"version\": \"0.19.0\",\n \"files\": [\n \"dist\"\n ],\n \"main\": \"./dist/index.js\",\n \"module\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"scripts\": {\n \"build\": \"tsup\",\n \"coverage\": \"vitest run --coverage\",\n \"generate-types\": \"npx openapi-typescript\",\n \"dev\": \"tsup --watch\",\n \"format\": \"prettier . --write\",\n \"lint\": \"eslint .\",\n \"test:watch\": \"vitest\",\n \"test\": \"vitest run\",\n \"typecheck\": \"tsc\",\n \"update-schemas\": \"node --experimental-strip-types update-schema.ts && npm run generate-types && npm run format\"\n },\n \"dependencies\": {\n \"openapi-fetch\": \"^0.13.4\"\n },\n \"devDependencies\": {\n \"openapi-typescript\": \"^7.6.0\",\n \"tsup\": \"^8.3.6\"\n },\n \"sideEffects\": false,\n \"prettier\": \"prettier-config-custom\"\n}\n","import { version } from '../../package.json'\n\n/**\n * Custom error class for SDK-related errors.\n * Includes the SDK version and an optional cause for better debugging.\n * NOTE: The error.message is intended for developers, not end-users.\n */\nexport default class SDKError extends Error {\n sdkVersion: string\n override cause?: Error\n\n constructor(userMessage: string, { cause }: { cause?: Error } = {}) {\n super(userMessage)\n this.name = 'SDKError'\n this.cause = cause\n this.sdkVersion = version\n\n // Set the prototype explicitly to maintain instanceof checks\n Object.setPrototypeOf(this, SDKError.prototype)\n }\n}\n"],"mappings":"AAAA,OAAOA,MAA0C,gBCK1C,IAAMC,EAAkB,4BAalBC,EAAuB,IAAM,eAAe,WAAWD,CAAe,EAkBtEE,EAAoB,IAAM,eAAe,QAAQF,CAAe,EAahEG,EAAqBC,GAA2B,eAAe,QAAQJ,EAAiBI,CAAc,EC5C5G,IAAMC,EAAa,uBAkBbC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aAAwB,CACtB,OAAO,KAAK,QACd,CAaA,kBAAkC,CAChC,OAAOC,EAAS,CAClB,CACF","names":["createClient","CONVERSATION_ID","deleteConversationId","getConversationId","setConversationId","conversationId","SESSION_ID","getSessionId","setSessionId","sessionId","getItemWithExpiry","key","itemString","item","getItemWithExpiry_default","setItemWithExpiry","key","value","ttl","item","setItemWithExpiry_default","day","USER_ID","TTL","getUserId","userId","getItemWithExpiry_default","setUserId","setItemWithExpiry_default","JWT_TOKEN","isTokenExpired","token","payloadBase64","payload","error","getToken","setToken","authMiddleware","accessToken","request","auth_default","errorMiddleware","response","data","error_default","headerMiddleware","identity","url","request","headers_default","version","SDKError","_SDKError","userMessage","cause","version","Client","config","conversationUrl","customerId","fetch","frontendUrl","defaultHeaders","headers","version","createClient","getConversationId","getSessionId","getUserId","error_default","headers_default","sessionId","userId","data","SDKError","setSessionId","setUserId","setToken","endpoint","auth_default","error","deleteConversationId","context","userMessage","conversationContext","conversationIdMessage","rest","conversationId","setConversationId","payload","message","eventName","properties","body","getToken"]}
1
+ {"version":3,"sources":["../src/client.ts","../src/utils/getItemWithExpiry.ts","../src/utils/setItemWithExpiry.ts","../src/identity/createIdentityStore.ts","../src/middlewares/auth.ts","../src/middlewares/error.ts","../src/middlewares/headers.ts","../src/restoreConversation/restoreConversation.ts","../package.json","../src/utils/SDKError.ts"],"sourcesContent":["import createClient, { type ClientOptions } from 'openapi-fetch'\n\nimport { createIdentityStore } from './identity/createIdentityStore'\nimport { authMiddleware, errorMiddleware, headerMiddleware } from './middlewares'\nimport { restoreConversation } from './restoreConversation/restoreConversation'\nimport type { components, paths as conversationPaths } from './schemas/conversation'\nimport type { paths as frontendPaths } from './schemas/frontend'\nimport type {\n Config,\n ConversationIdMessage,\n Endpoint,\n Identity,\n Message,\n RestoredTurn,\n SendMessagePayload,\n TrackingEvent,\n UserStartConversationMessage,\n} from './types'\nimport { version } from '../package.json'\nimport SDKError from './utils/SDKError'\n\n/**\n * The `Client` class provides methods to manage 15gifts API.\n */\nexport class Client {\n /**\n * This can be used to interact with the APIs directly. It is recommended to use the [helper methods](/sdk/sdk-reference/classes/client/#methods) provided by the `Client` class instead.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * const { data } = await client.endpoint.conversation.POST('/api/conversation/v3')\n * ```\n */\n endpoint: Endpoint\n\n /**\n * The identity information.\n */\n identity: Identity\n\n /**\n * Creates a new instance of the `Client` class.\n *\n * @param config - Configuration options for initializing the client.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * ```\n */\n constructor(config: Config) {\n const { conversationUrl, customerId, fetch, frontendUrl, headers: defaultHeaders } = config\n\n const headers: ClientOptions['headers'] = {\n ...defaultHeaders,\n 'X-SDK-VERSION': version,\n }\n\n this.endpoint = {\n conversation: createClient<conversationPaths>({\n baseUrl: conversationUrl,\n fetch,\n headers,\n credentials: 'include',\n }),\n frontend: createClient<frontendPaths>({ baseUrl: frontendUrl, fetch, headers }),\n }\n\n this.identity = createIdentityStore(customerId)\n\n this.endpoint.conversation.use(errorMiddleware)\n this.endpoint.conversation.use(headerMiddleware(this.identity, window.location.href))\n }\n\n /**\n * Creates a new identity for the user by generating a session ID and user ID if they don't exist, and sets the access token for future API calls.\n * Ends the current conversation if a conversation ID is present before sending a request to update identity.\n * This should not be called more than once per page load.\n *\n * @returns A promise that resolves once the identity is created and the access token is set.\n *\n * @example\n * ```ts\n * await client.createIdentity()\n * console.log('Identity created:', client.identity)\n * ```\n */\n async createIdentity(): Promise<void> {\n const { customerId, sessionId, userId } = this.identity\n\n try {\n const { data } = await this.endpoint.frontend.POST('/api/tracking/identity/v2', {\n body: {\n customerId,\n sessionId,\n userId,\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n },\n })\n\n if (!data) {\n throw new SDKError('No data received from identity API')\n }\n\n this.identity.pageviewId = data.pageviewId\n\n if (!sessionId) {\n this.identity.sessionId = data.sessionId\n }\n if (!userId) {\n this.identity.userId = data.userId\n }\n\n this.identity.token = data.token\n\n // Add the access token to the Authorization header for all endpoints\n Object.values(this.endpoint).forEach((endpoint) => {\n endpoint.use(authMiddleware(data.token))\n })\n } catch (error) {\n // Enable the auth middleware without a token so that it will throw an error before sending\n // the next request, preventing unnecessary API calls / 401 responses.\n Object.values(this.endpoint).forEach((endpoint) => {\n endpoint.use(authMiddleware())\n })\n throw new SDKError('Failed to create identity', {\n cause: error as Error,\n })\n }\n }\n\n /**\n * Ends the current conversation by deleting the conversation ID.\n *\n * @example\n * ```ts\n * client.endConversation()\n * console.log('Conversation ended')\n * ```\n */\n endConversation(): void {\n this.identity.conversationId = undefined\n }\n\n /**\n * Clears the existing conversation ID, then generates a new one and returns the opening message.\n *\n * @param context - Optional context to customize the conversation. It can include:\n * @param context.eligibleProducts An array of eligible product IDs.\n * @param context.eligibleBundles An array of eligible bundle IDs.\n * @param context.productOverrides Overrides for product details.\n * @param context.bundleOverrides Overrides for bundle details.\n *\n * @returns A promise that resolves to the opening message.\n *\n * @example\n * ##### Basic usage\n * ```ts\n * const openingMessage = await client.startConversation()\n * console.log('Opening message:', openingMessage)\n * ```\n *\n * ##### With context\n * ```ts\n * const openingMessage = await client.startConversation({ eligibleProducts: ['product-1', 'product-2'], productOverrides: { 'product-1': { price: 40 } })\n * console.log('Opening message:', openingMessage)\n * ```\n */\n async startConversation(\n context?: components['schemas']['ConversationContext'],\n userMessage?: UserStartConversationMessage['openingUserMessage'],\n ): Promise<Message[]> {\n this.endConversation()\n\n const conversationContext = {\n ...context,\n }\n\n const { data } = await this.endpoint.conversation.POST(`/api/conversation/v3`, {\n body: {\n type: 'START_CONVERSATION',\n conversationContext,\n openingUserMessage: userMessage,\n },\n })\n\n if (!data) throw new SDKError('No data received from Conversation API')\n\n const [conversationIdMessage, ...rest] = data as [ConversationIdMessage, ...Message[]]\n\n const conversationId = conversationIdMessage.conversationId\n if (!conversationId) {\n throw new SDKError('Conversation ID not received in API response')\n }\n\n this.identity.conversationId = conversationId\n\n return rest\n }\n\n /**\n * Sends a message in the conversation.\n *\n * @param options - An object containing the user message.\n * @returns A promise that resolves to an array of messages\n *\n * @example\n * ```ts\n * const newMessages = await client.sendMessage({\n * userMessage: 'How can I get support?',\n * })\n *\n * if (newMessages) {\n * console.log('Received messages:', newMessages)\n * } else {\n * console.log('No message received')\n * }\n * ```\n */\n async sendMessage(payload: SendMessagePayload) {\n const conversationId = this.identity.conversationId\n if (!conversationId) {\n throw new SDKError('Conversation ID not set')\n }\n\n const { data } = await this.endpoint.conversation.POST('/api/conversation/v3', {\n body: {\n conversationId,\n ...payload,\n },\n })\n\n if (!data) throw new SDKError('No data received from conversation API')\n\n // Removes any `CONVERSATION_ID` messages from the API response. In reality, these messages will only\n // appear in the response to a `START_CONVERSATION` request.\n return data.filter((message) => message.type !== 'CONVERSATION_ID')\n }\n\n /**\n * Sends an event to the tracking API, with the required properties already set.\n *\n * @param eventName - The name of the event to track.\n * @param properties - Additional properties to include in the event.\n * @returns A promise that resolves once the event is tracked.\n *\n * @example\n * ```ts\n * await client.trackEvent('entry_point-shown')\n * ```\n */\n async trackEvent(eventName: TrackingEvent['eventName'], properties?: TrackingEvent['additionalProperties']) {\n const body: TrackingEvent = {\n additionalProperties: properties,\n conversationId: this.identity.conversationId,\n eventName,\n pageviewId: this.identity.pageviewId ?? 'unknown',\n screenWidth: window.screen.width,\n screenHeight: window.screen.height,\n screenSize: window.screen.width <= 480 ? 'mobile' : 'large',\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n }\n\n return this.endpoint.frontend.POST('/api/tracking/user/v2', {\n body,\n })\n }\n\n /**\n * Gets an existing identity of the user.\n *\n * @returns An Identity object containing `customerId`, `conversationId`, `sessionId`, `userId`.\n *\n * @example\n * ```ts\n * identity = client.getIdentity()\n * console.log('Identity retrieved:', identity)\n * ```\n */\n getIdentity(): Identity {\n return this.identity\n }\n\n /**\n * Gets the JWT from the localStorage.\n * Use this method to retrieve the token for use in other parts of your system,\n * such as calling the Humara sales tracking API\n *\n * @returns {string | null} the JWT.\n *\n * @example\n * ```ts\n * token = client.getIdentityToken()\n * console.log('Identity token retrieved:', token)\n * ```\n */\n getIdentityToken(): string | null {\n return this.identity.token ?? null\n }\n\n /**\n * Gets the conversation history for a given conversation ID.\n *\n * @param conversationId - The ID of the conversation to retrieve.\n * @returns A promise that resolves to the conversation history as an array of turns. Each turn contains a user message and its corresponding response.\n */\n async getConversation(conversationId: string): Promise<RestoredTurn[]> {\n if (!conversationId) {\n throw new SDKError('Conversation ID not set')\n }\n\n try {\n const { data } = await this.endpoint.conversation.GET('/api/conversation/{conversation_id}/v1', {\n params: {\n path: {\n conversation_id: conversationId,\n },\n },\n })\n\n // Sets the current conversation ID to the one just retrieved, so that subsequent calls to `sendMessage` and `trackEvent` will use this conversation ID.\n this.identity.conversationId = conversationId\n\n if (!data) throw new SDKError('No data received from conversation history API')\n\n return restoreConversation(data)\n } catch (error) {\n throw new SDKError('Failed to get conversation history', {\n cause: error as Error,\n })\n }\n }\n}\n","const getItemWithExpiry = (key: string) => {\n const itemString = localStorage.getItem(key)\n\n if (!itemString) return null\n\n const item = JSON.parse(itemString) as { expires: number; value: string }\n\n if (Date.now() > item.expires) {\n localStorage.removeItem(key)\n\n return null\n }\n\n return item.value\n}\n\nexport default getItemWithExpiry\n","/**\n * Set an item in localStorage with an expiration time\n * @param key The key under which the value is stored in localStorage\n * @param value The value to be stored\n * @param ttl The time-to-live (TTL) in milliseconds\n */\nconst setItemWithExpiry = (key: string, value: string, ttl: number) => {\n const item = {\n expires: Date.now() + ttl,\n value,\n }\n\n localStorage.setItem(key, JSON.stringify(item))\n}\n\nexport default setItemWithExpiry\n","import type { Config, Identity } from '../types'\nimport { getItemWithExpiry, setItemWithExpiry } from '../utils'\n\ntype IdentityKey = 'conversationId' | 'sessionId' | 'token' | 'userId'\n\nconst day = 1000 * 60 * 60 * 24\nconst userIdTtl = day * 30\n\nconst conversationIdKey = '__15gifts_conversation_id'\nconst sessionIdKey = '__15gifts_session_id'\nconst tokenKey = '__15gifts_identity_token'\nconst userIdKey = '__15gifts_user_id'\n\nconst deleteConversationId = () => sessionStorage.removeItem(conversationIdKey)\nconst getConversationId = () => sessionStorage.getItem(conversationIdKey)\nconst setConversationId = (conversationId: string) => sessionStorage.setItem(conversationIdKey, conversationId)\n\nconst getSessionId = () => sessionStorage.getItem(sessionIdKey)\nconst setSessionId = (sessionId: string) => sessionStorage.setItem(sessionIdKey, sessionId)\n\nconst isTokenExpired = (token: string): boolean => {\n try {\n const [, payloadBase64] = token.split('.')\n if (!payloadBase64) {\n throw new Error('Invalid token payload')\n }\n const payload = JSON.parse(atob(payloadBase64))\n\n return payload.exp && Date.now() / 1000 > payload.exp\n } catch (error) {\n console.error('Invalid token format', error)\n return true\n }\n}\n\nconst getToken = (): string | null => {\n const token = localStorage.getItem(tokenKey)\n\n if (!token || isTokenExpired(token)) {\n localStorage.removeItem(tokenKey)\n return null\n }\n\n return token\n}\n\nconst setToken = (token: string) => localStorage.setItem(tokenKey, token)\n\nconst getUserId = () => {\n const userId = getItemWithExpiry(userIdKey)\n\n if (userId) {\n setUserId(userId)\n }\n\n return userId\n}\n\nconst setUserId = (userId: string) => setItemWithExpiry(userIdKey, userId, userIdTtl)\n\nconst createIdentityProperty = (\n getValue: () => string | null,\n setValue: (value: string) => void,\n clearValue?: () => void,\n): PropertyDescriptor => ({\n enumerable: true,\n configurable: true,\n get: () => getValue() ?? undefined,\n set: (value: string | undefined) => {\n if (value) {\n setValue(value)\n return\n }\n\n clearValue?.()\n },\n})\n\n/**\n * Creates an identity object backed by browser storage.\n *\n * The returned object exposes the public `Identity` shape while keeping\n * `conversationId`, `sessionId`, and `userId` synchronized with their\n * corresponding storage helpers.\n */\nexport const createIdentityStore = (customerId: Config['customerId']): Identity => {\n const identity: Identity = {\n customerId,\n }\n\n const properties: Record<IdentityKey, PropertyDescriptor> = {\n conversationId: createIdentityProperty(getConversationId, setConversationId, deleteConversationId),\n sessionId: createIdentityProperty(getSessionId, setSessionId),\n token: createIdentityProperty(getToken, setToken),\n userId: createIdentityProperty(getUserId, setUserId),\n }\n\n Object.defineProperties(identity, properties)\n\n return identity\n}\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for adding an `Authorization` header to requests.\n *\n * @param accessToken - The token to be included in the `Authorization` header.\n * @returns A middleware object that attaches the access token to the request headers.\n *\n * @example\n * ```ts\n * import { authMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(authMiddleware(accessToken))\n * ```\n */\nconst authMiddleware = (accessToken?: string): Middleware => ({\n onRequest: async ({ request }) => {\n const isIdentityEndpoint = request.url.includes('/identity/')\n if (isIdentityEndpoint) {\n return request\n }\n\n // Throw an error because we know the API will return a 401 if the access token is not set.\n if (!accessToken) {\n throw new Error('Access token is required for authentication.')\n }\n\n request.headers.set('Authorization', `Bearer ${accessToken}`)\n\n return request\n },\n})\n\nexport default authMiddleware\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for handling errors.\n *\n * @returns A middleware object that throws an error if the response is not ok.\n *\n * @example\n * ```ts\n * import { errorMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(errorMiddleware())\n * ```\n */\nconst errorMiddleware: Middleware = {\n // onError does not handle error responses with 4xx or 5xx HTTP status codes, since these are considered \"successful\" responses but with a bad status code.\n // In these cases we need to check the response's status property or ok() method via the onResponse callback.\n onResponse: async ({ response }) => {\n if (!response.ok) {\n const data = await response.json()\n\n throw new Error(data.message)\n }\n\n return response\n },\n}\n\nexport default errorMiddleware\n","import type { Middleware } from 'openapi-fetch'\n\nimport { Identity } from '../types'\n\n/**\n * Middleware for adding request headers that other services use for tracking.\n *\n * @returns A middleware object that throws an error if the response is not ok.\n *\n * @example\n * ```ts\n * import { pageViewId } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(headerMiddleware('123', 'https://example.com'))\n * ```\n */\nconst headerMiddleware = (identity: Identity, url: string): Middleware => ({\n onRequest: async ({ request }) => {\n if (identity.pageviewId) {\n request.headers.set('X-PAGEVIEW-ID', identity.pageviewId)\n }\n if (url) {\n request.headers.set('X-PAGE-URL', url)\n }\n\n return request\n },\n})\n\nexport default headerMiddleware\n","/**\n * The GET `/api/conversation/{conversation_id}` endpoint returns data as a historical record, but\n * it makes little sense when rendered.\n * We transform it so that the user doesn't see all single_select messages again, only the option\n * they selected.\n **/\n\nimport type { ConversationTurn, Message, SingleSelectMessage, UserSingleSelectMessage, RestoredTurn } from '../types'\n\n/**\n * Removes the conversationId from the user message, as this is not needed for rendering and would just add noise.\n */\nconst stripConversationId = <T extends { conversationId?: string }>(userMessage: T): Omit<T, 'conversationId'> => {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { conversationId, ...rest } = userMessage\n\n return rest\n}\n\n// We have the string that was sent to the API, this finds the label for the option that it relates to.\nconst getSelectedOptionLabel = (userMessage: UserSingleSelectMessage, previousTurn?: ConversationTurn) => {\n const previousSingleSelect = previousTurn?.assistantMessages.find(\n (message): message is SingleSelectMessage => message.type === 'SINGLE_SELECT',\n )\n const selectedOption = previousSingleSelect?.options.find((option) => option.value === userMessage.option)\n\n return selectedOption?.label || ''\n}\n\n// Turns the user message back in to how the user would have seen it\nconst getRestoredUserMessage = (\n turn: ConversationTurn,\n previousTurn?: ConversationTurn,\n): RestoredTurn['userMessage'] => {\n const { userMessage } = turn\n\n switch (userMessage.type) {\n case 'SINGLE_SELECT':\n return {\n ...stripConversationId(userMessage),\n userMessage: getSelectedOptionLabel(userMessage, previousTurn),\n }\n\n case 'START_CONVERSATION':\n // There isn't anything we want to render from the START_CONVERSATION message except for the openingUserMessage,\n // which is what the user would have submitted to start the conversation.\n return {\n type: 'MESSAGE',\n userMessage: userMessage.openingUserMessage?.option || '',\n }\n\n case 'MESSAGE':\n return stripConversationId(userMessage)\n\n case 'MULTI_SELECT':\n return stripConversationId(userMessage)\n }\n}\n\n// Turns the assistant message back in to how the user would have seen it\nconst getRestoredAssistantReply = (turn: ConversationTurn, nextTurn?: ConversationTurn) => {\n const shouldHideSingleSelect = Boolean(nextTurn)\n\n return turn.assistantMessages.filter(\n (message): message is Message =>\n message.type !== 'CONVERSATION_ID' && !(shouldHideSingleSelect && message.type === 'SINGLE_SELECT'),\n )\n}\n\nexport const restoreConversation = (turns: ConversationTurn[]): RestoredTurn[] => {\n return turns.map((turn, index) => {\n const previousTurn = index > 0 ? turns[index - 1] : undefined\n const nextTurn = index < turns.length - 1 ? turns[index + 1] : undefined\n\n return {\n id: `restored-turn-${index}`,\n userMessage: getRestoredUserMessage(turn, previousTurn),\n assistantReply: getRestoredAssistantReply(turn, nextTurn),\n }\n })\n}\n","{\n \"name\": \"@15gifts/sdk\",\n \"version\": \"0.20.0\",\n \"files\": [\n \"dist\"\n ],\n \"main\": \"./dist/index.js\",\n \"module\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"scripts\": {\n \"build\": \"tsup\",\n \"coverage\": \"vitest run --coverage\",\n \"generate-types\": \"npx openapi-typescript\",\n \"dev\": \"tsup --watch\",\n \"format\": \"prettier . --write\",\n \"lint\": \"eslint .\",\n \"test:watch\": \"vitest\",\n \"test\": \"vitest run\",\n \"typecheck\": \"tsc\",\n \"update-schemas\": \"node --experimental-strip-types update-schema.ts && npm run generate-types && npm run format\"\n },\n \"dependencies\": {\n \"openapi-fetch\": \"^0.13.4\"\n },\n \"devDependencies\": {\n \"openapi-typescript\": \"^7.6.0\",\n \"tsup\": \"^8.3.6\"\n },\n \"sideEffects\": false,\n \"prettier\": \"prettier-config-custom\"\n}\n","import { version } from '../../package.json'\n\n/**\n * Custom error class for SDK-related errors.\n * Includes the SDK version and an optional cause for better debugging.\n * NOTE: The error.message is intended for developers, not end-users.\n */\nexport default class SDKError extends Error {\n sdkVersion: string\n override cause?: Error\n\n constructor(userMessage: string, { cause }: { cause?: Error } = {}) {\n super(userMessage)\n this.name = 'SDKError'\n this.cause = cause\n this.sdkVersion = version\n\n // Set the prototype explicitly to maintain instanceof checks\n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EAAQ,OAAS,iBAAiB,CACpE,CAcA,MAAM,WAAWC,EAAuCC,EAAoD,CAC1G,IAAMC,EAAsB,CAC1B,qBAAsBD,EACtB,eAAgB,KAAK,SAAS,eAC9B,UAAAD,EACA,WAAY,KAAK,SAAS,YAAc,UACxC,YAAa,OAAO,OAAO,MAC3B,aAAc,OAAO,OAAO,OAC5B,WAAY,OAAO,OAAO,OAAS,IAAM,SAAW,QACpD,IAAK,OAAO,SAAS,KACrB,UAAW,OAAO,UAAU,SAC9B,EAEA,OAAO,KAAK,SAAS,SAAS,KAAK,wBAAyB,CAC1D,KAAAE,CACF,CAAC,CACH,CAaA,aAAwB,CACtB,OAAO,KAAK,QACd,CAeA,kBAAkC,CAChC,OAAO,KAAK,SAAS,OAAS,IAChC,CAQA,MAAM,gBAAgBL,EAAiD,CACrE,GAAI,CAACA,EACH,MAAM,IAAIT,EAAS,yBAAyB,EAG9C,GAAI,CACF,GAAM,CAAE,KAAAD,CAAK,EAAI,MAAM,KAAK,SAAS,aAAa,IAAI,yCAA0C,CAC9F,OAAQ,CACN,KAAM,CACJ,gBAAiBU,CACnB,CACF,CACF,CAAC,EAKD,GAFA,KAAK,SAAS,eAAiBA,EAE3B,CAACV,EAAM,MAAM,IAAIC,EAAS,gDAAgD,EAE9E,OAAOe,EAAoBhB,CAAI,CACjC,OAASI,EAAO,CACd,MAAM,IAAIH,EAAS,qCAAsC,CACvD,MAAOG,CACT,CAAC,CACH,CACF,CACF","names":["createClient","getItemWithExpiry","key","itemString","item","getItemWithExpiry_default","setItemWithExpiry","key","value","ttl","item","setItemWithExpiry_default","day","userIdTtl","conversationIdKey","sessionIdKey","tokenKey","userIdKey","deleteConversationId","getConversationId","setConversationId","conversationId","getSessionId","setSessionId","sessionId","isTokenExpired","token","payloadBase64","payload","error","getToken","setToken","getUserId","userId","getItemWithExpiry_default","setUserId","setItemWithExpiry_default","createIdentityProperty","getValue","setValue","clearValue","value","createIdentityStore","customerId","identity","properties","authMiddleware","accessToken","request","auth_default","errorMiddleware","response","data","error_default","headerMiddleware","identity","url","request","headers_default","stripConversationId","userMessage","conversationId","rest","getSelectedOptionLabel","previousTurn","message","option","getRestoredUserMessage","turn","getRestoredAssistantReply","nextTurn","shouldHideSingleSelect","restoreConversation","turns","index","version","SDKError","_SDKError","userMessage","cause","version","Client","config","conversationUrl","customerId","fetch","frontendUrl","defaultHeaders","headers","version","createClient","createIdentityStore","error_default","headers_default","sessionId","userId","data","SDKError","endpoint","auth_default","error","context","userMessage","conversationContext","conversationIdMessage","rest","conversationId","payload","message","eventName","properties","body","restoreConversation"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@15gifts/sdk",
3
- "version": "0.19.0",
3
+ "version": "0.20.0",
4
4
  "files": [
5
5
  "dist"
6
6
  ],