@15gifts/sdk 0.6.1 → 0.6.3

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
@@ -1264,7 +1264,60 @@ interface paths {
1264
1264
  * } */
1265
1265
  'application/json': {
1266
1266
  additionalProperties?: {
1267
- [key: string]: boolean | number | string;
1267
+ /** @description A 32 character alphanumeric hash that uniquely identifies a session */
1268
+ session_id?: string;
1269
+ /** @description A 32 character alphanumeric hash that uniquely identifies a user */
1270
+ user_id?: string;
1271
+ /** @description A timestamp describing the time the event occurred. This should conform to ISO 8601 standards and be in UTC. Example: \"2024-07-17T10:11:16.591Z\" */
1272
+ event_at?: string;
1273
+ /** @description The page url at the time the event is fired */
1274
+ url?: string;
1275
+ /** @description What web browser the user is using e.g. chrome/firefox/safari etc. */
1276
+ browser?: string;
1277
+ /** @description The customer that the event occurred on */
1278
+ customer_id?: string;
1279
+ /** @description The user agent string e.g. \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36\" */
1280
+ user_agent?: string;
1281
+ /** @description A 32 character alphanumeric hash that uniquely identifies a tracking event */
1282
+ event_id?: string;
1283
+ /** @description The name of the system/service that the event originates from */
1284
+ service?: string;
1285
+ /** @description A JSON object containing the different versions of services directly used by the service that tracks an event. The version of the service that is firing any tracking event should ALWAYS be included, for example if the conversation_api is firing an event, service_versions should include conversation_api_version. It should also ideally include the version numbers of any other services used in the generation of the event that is being tracked. */
1286
+ service_versions?: Record<string, never>;
1287
+ /** @description The environment the event originated from (production/development/testing/staging/local) */
1288
+ environment?: string;
1289
+ /** @description The associated text based on the answer provided by the user at the end of the conversation when they are asked to provide feedback by clicking on one of the emojis */
1290
+ feedback_score_text?: string;
1291
+ /** @description A 32 character alphanumeric hash that uniquely identifies a conversation */
1292
+ conversation_id?: string;
1293
+ /** @description An integer representing the rank of the corresponding feedback score. It should always start at 0, even if the number of options changes. */
1294
+ feedback_score_num?: number;
1295
+ /** @description The turn number in the conversation. This links each user message to a corresponding assistant response. If there is an opening message from the assistant, this would have a message_turn of 0. Then the first message a user sends would have a message_turn of 1. The first actual response the assistant sends would have a message_turn of 1.
1296
+ *
1297
+ * All message_turn values except for 0 (the opening message if it exists) should be expected to come in pairs.
1298
+ *
1299
+ * Here's an example sequence of message_turn values where the user is provided with an opening message at the beginning of a conversation, and then sends 5 separate messages themselves with 5 corresponding assistant responses:
1300
+ *
1301
+ * 0,1,1,2,2,3,3,4,4,5,5 */
1302
+ conversation_turn_num?: number;
1303
+ /** @description An alphanumeric hash that uniquely identifies a turn in a conversation */
1304
+ conversation_turn_id?: string;
1305
+ /** @description Describes the type of message e.g. text, single select, multi select etc */
1306
+ message_type?: string;
1307
+ /** @description The text that was sent by either the user or the assistant. For messages where message_type is not 'text', this should be a string representation of the more complex data type. */
1308
+ message_text?: string;
1309
+ /** @description List of objects that represents the options for single & multiselect questions. */
1310
+ message_select_options?: unknown[];
1311
+ /** @description true or false depending on whether the users message caused the assistant to provide a guardrail response */
1312
+ is_user_message_guardrailed?: boolean;
1313
+ /** @description A list of products sent in a conversation api message, typically initially in a recommendation message, but then could also be in an exit_to_purchase message. */
1314
+ recommendation_products?: unknown[];
1315
+ /** @description Contains the fallback text provided by the conversation api to a frontend that non 'text' (single_select/multi_select etc) messages could revert to if they needed to. Described in the conversation api docs as: \"What should a client render if they do not have a native renderer for this message type?\". */
1316
+ fallback_text?: string;
1317
+ /** @description Specifies if a free text response can be provided to an assistant single/multi-select message */
1318
+ is_allow_free_text_message?: boolean;
1319
+ /** @description The reason an exit to chat response was provided by the conversation api */
1320
+ exit_to_chat_reason?: string;
1268
1321
  };
1269
1322
  /** @description Conversation ID */
1270
1323
  conversationId?: string;
@@ -1277,7 +1330,7 @@ interface paths {
1277
1330
  * @description Event Name
1278
1331
  * @enum {string}
1279
1332
  */
1280
- eventName: 'welcome_screen-shown' | 'tab-shown' | 'feedback_submit-clicked' | 'page-shown' | 'tool-closed' | 'user_message-submitted' | 'assistant_message-submitted' | 'feedback-shown' | 'feedback_skip-clicked' | 'sale-completed' | 'tab-clicked' | 'tool_close-clicked' | 'woo_assistant_message-submitted' | 'woo_user_message-submitted' | 'woo_reaction-submitted';
1333
+ eventName: 'welcome_screen-shown' | 'tab-shown' | 'feedback_submit-clicked' | 'page-shown' | 'tool-closed' | 'user_message-submitted' | 'user_message-submitted message' | 'user_message-submitted single_select' | 'user_message-submitted multi_select' | 'assistant_message-submitted' | 'assistant_message-submitted recommendation' | 'assistant_message-submitted message' | 'assistant_message-submitted single_select' | 'assistant_message-submitted multi_select' | 'assistant_message-submitted exit_to_chat' | 'assistant_message-submitted exit_to_purchase' | 'feedback-shown' | 'feedback_skip-clicked' | 'sale-completed' | 'tab-clicked' | 'tool_close-clicked' | 'exit_to_purchase-completed' | 'exit_to_chat-completed';
1281
1334
  /** @description Pageview ID */
1282
1335
  pageviewId?: string;
1283
1336
  /** @description URL */
@@ -1538,11 +1591,34 @@ declare class Client {
1538
1591
  content: {
1539
1592
  "application/json": {
1540
1593
  additionalProperties?: {
1541
- [key: string]: boolean | number | string;
1594
+ session_id?: string;
1595
+ user_id?: string;
1596
+ event_at?: string;
1597
+ url?: string;
1598
+ browser?: string;
1599
+ customer_id?: string;
1600
+ user_agent?: string;
1601
+ event_id?: string;
1602
+ service?: string;
1603
+ service_versions?: Record<string, never>;
1604
+ environment?: string;
1605
+ feedback_score_text?: string;
1606
+ conversation_id?: string;
1607
+ feedback_score_num?: number;
1608
+ conversation_turn_num?: number;
1609
+ conversation_turn_id?: string;
1610
+ message_type?: string;
1611
+ message_text?: string;
1612
+ message_select_options?: unknown[];
1613
+ is_user_message_guardrailed?: boolean;
1614
+ recommendation_products?: unknown[];
1615
+ fallback_text?: string;
1616
+ is_allow_free_text_message?: boolean;
1617
+ exit_to_chat_reason?: string;
1542
1618
  };
1543
1619
  conversationId?: string;
1544
1620
  deviceType?: "desktop" | "mobile" | "tablet";
1545
- eventName: "welcome_screen-shown" | "tab-shown" | "feedback_submit-clicked" | "page-shown" | "tool-closed" | "user_message-submitted" | "assistant_message-submitted" | "feedback-shown" | "feedback_skip-clicked" | "sale-completed" | "tab-clicked" | "tool_close-clicked" | "woo_assistant_message-submitted" | "woo_user_message-submitted" | "woo_reaction-submitted";
1621
+ eventName: "welcome_screen-shown" | "tab-shown" | "feedback_submit-clicked" | "page-shown" | "tool-closed" | "user_message-submitted" | "user_message-submitted message" | "user_message-submitted single_select" | "user_message-submitted multi_select" | "assistant_message-submitted" | "assistant_message-submitted recommendation" | "assistant_message-submitted message" | "assistant_message-submitted single_select" | "assistant_message-submitted multi_select" | "assistant_message-submitted exit_to_chat" | "assistant_message-submitted exit_to_purchase" | "feedback-shown" | "feedback_skip-clicked" | "sale-completed" | "tab-clicked" | "tool_close-clicked" | "exit_to_purchase-completed" | "exit_to_chat-completed";
1546
1622
  pageviewId?: string;
1547
1623
  url?: string;
1548
1624
  userAgent?: string;
package/dist/index.d.ts CHANGED
@@ -1264,7 +1264,60 @@ interface paths {
1264
1264
  * } */
1265
1265
  'application/json': {
1266
1266
  additionalProperties?: {
1267
- [key: string]: boolean | number | string;
1267
+ /** @description A 32 character alphanumeric hash that uniquely identifies a session */
1268
+ session_id?: string;
1269
+ /** @description A 32 character alphanumeric hash that uniquely identifies a user */
1270
+ user_id?: string;
1271
+ /** @description A timestamp describing the time the event occurred. This should conform to ISO 8601 standards and be in UTC. Example: \"2024-07-17T10:11:16.591Z\" */
1272
+ event_at?: string;
1273
+ /** @description The page url at the time the event is fired */
1274
+ url?: string;
1275
+ /** @description What web browser the user is using e.g. chrome/firefox/safari etc. */
1276
+ browser?: string;
1277
+ /** @description The customer that the event occurred on */
1278
+ customer_id?: string;
1279
+ /** @description The user agent string e.g. \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36\" */
1280
+ user_agent?: string;
1281
+ /** @description A 32 character alphanumeric hash that uniquely identifies a tracking event */
1282
+ event_id?: string;
1283
+ /** @description The name of the system/service that the event originates from */
1284
+ service?: string;
1285
+ /** @description A JSON object containing the different versions of services directly used by the service that tracks an event. The version of the service that is firing any tracking event should ALWAYS be included, for example if the conversation_api is firing an event, service_versions should include conversation_api_version. It should also ideally include the version numbers of any other services used in the generation of the event that is being tracked. */
1286
+ service_versions?: Record<string, never>;
1287
+ /** @description The environment the event originated from (production/development/testing/staging/local) */
1288
+ environment?: string;
1289
+ /** @description The associated text based on the answer provided by the user at the end of the conversation when they are asked to provide feedback by clicking on one of the emojis */
1290
+ feedback_score_text?: string;
1291
+ /** @description A 32 character alphanumeric hash that uniquely identifies a conversation */
1292
+ conversation_id?: string;
1293
+ /** @description An integer representing the rank of the corresponding feedback score. It should always start at 0, even if the number of options changes. */
1294
+ feedback_score_num?: number;
1295
+ /** @description The turn number in the conversation. This links each user message to a corresponding assistant response. If there is an opening message from the assistant, this would have a message_turn of 0. Then the first message a user sends would have a message_turn of 1. The first actual response the assistant sends would have a message_turn of 1.
1296
+ *
1297
+ * All message_turn values except for 0 (the opening message if it exists) should be expected to come in pairs.
1298
+ *
1299
+ * Here's an example sequence of message_turn values where the user is provided with an opening message at the beginning of a conversation, and then sends 5 separate messages themselves with 5 corresponding assistant responses:
1300
+ *
1301
+ * 0,1,1,2,2,3,3,4,4,5,5 */
1302
+ conversation_turn_num?: number;
1303
+ /** @description An alphanumeric hash that uniquely identifies a turn in a conversation */
1304
+ conversation_turn_id?: string;
1305
+ /** @description Describes the type of message e.g. text, single select, multi select etc */
1306
+ message_type?: string;
1307
+ /** @description The text that was sent by either the user or the assistant. For messages where message_type is not 'text', this should be a string representation of the more complex data type. */
1308
+ message_text?: string;
1309
+ /** @description List of objects that represents the options for single & multiselect questions. */
1310
+ message_select_options?: unknown[];
1311
+ /** @description true or false depending on whether the users message caused the assistant to provide a guardrail response */
1312
+ is_user_message_guardrailed?: boolean;
1313
+ /** @description A list of products sent in a conversation api message, typically initially in a recommendation message, but then could also be in an exit_to_purchase message. */
1314
+ recommendation_products?: unknown[];
1315
+ /** @description Contains the fallback text provided by the conversation api to a frontend that non 'text' (single_select/multi_select etc) messages could revert to if they needed to. Described in the conversation api docs as: \"What should a client render if they do not have a native renderer for this message type?\". */
1316
+ fallback_text?: string;
1317
+ /** @description Specifies if a free text response can be provided to an assistant single/multi-select message */
1318
+ is_allow_free_text_message?: boolean;
1319
+ /** @description The reason an exit to chat response was provided by the conversation api */
1320
+ exit_to_chat_reason?: string;
1268
1321
  };
1269
1322
  /** @description Conversation ID */
1270
1323
  conversationId?: string;
@@ -1277,7 +1330,7 @@ interface paths {
1277
1330
  * @description Event Name
1278
1331
  * @enum {string}
1279
1332
  */
1280
- eventName: 'welcome_screen-shown' | 'tab-shown' | 'feedback_submit-clicked' | 'page-shown' | 'tool-closed' | 'user_message-submitted' | 'assistant_message-submitted' | 'feedback-shown' | 'feedback_skip-clicked' | 'sale-completed' | 'tab-clicked' | 'tool_close-clicked' | 'woo_assistant_message-submitted' | 'woo_user_message-submitted' | 'woo_reaction-submitted';
1333
+ eventName: 'welcome_screen-shown' | 'tab-shown' | 'feedback_submit-clicked' | 'page-shown' | 'tool-closed' | 'user_message-submitted' | 'user_message-submitted message' | 'user_message-submitted single_select' | 'user_message-submitted multi_select' | 'assistant_message-submitted' | 'assistant_message-submitted recommendation' | 'assistant_message-submitted message' | 'assistant_message-submitted single_select' | 'assistant_message-submitted multi_select' | 'assistant_message-submitted exit_to_chat' | 'assistant_message-submitted exit_to_purchase' | 'feedback-shown' | 'feedback_skip-clicked' | 'sale-completed' | 'tab-clicked' | 'tool_close-clicked' | 'exit_to_purchase-completed' | 'exit_to_chat-completed';
1281
1334
  /** @description Pageview ID */
1282
1335
  pageviewId?: string;
1283
1336
  /** @description URL */
@@ -1538,11 +1591,34 @@ declare class Client {
1538
1591
  content: {
1539
1592
  "application/json": {
1540
1593
  additionalProperties?: {
1541
- [key: string]: boolean | number | string;
1594
+ session_id?: string;
1595
+ user_id?: string;
1596
+ event_at?: string;
1597
+ url?: string;
1598
+ browser?: string;
1599
+ customer_id?: string;
1600
+ user_agent?: string;
1601
+ event_id?: string;
1602
+ service?: string;
1603
+ service_versions?: Record<string, never>;
1604
+ environment?: string;
1605
+ feedback_score_text?: string;
1606
+ conversation_id?: string;
1607
+ feedback_score_num?: number;
1608
+ conversation_turn_num?: number;
1609
+ conversation_turn_id?: string;
1610
+ message_type?: string;
1611
+ message_text?: string;
1612
+ message_select_options?: unknown[];
1613
+ is_user_message_guardrailed?: boolean;
1614
+ recommendation_products?: unknown[];
1615
+ fallback_text?: string;
1616
+ is_allow_free_text_message?: boolean;
1617
+ exit_to_chat_reason?: string;
1542
1618
  };
1543
1619
  conversationId?: string;
1544
1620
  deviceType?: "desktop" | "mobile" | "tablet";
1545
- eventName: "welcome_screen-shown" | "tab-shown" | "feedback_submit-clicked" | "page-shown" | "tool-closed" | "user_message-submitted" | "assistant_message-submitted" | "feedback-shown" | "feedback_skip-clicked" | "sale-completed" | "tab-clicked" | "tool_close-clicked" | "woo_assistant_message-submitted" | "woo_user_message-submitted" | "woo_reaction-submitted";
1621
+ eventName: "welcome_screen-shown" | "tab-shown" | "feedback_submit-clicked" | "page-shown" | "tool-closed" | "user_message-submitted" | "user_message-submitted message" | "user_message-submitted single_select" | "user_message-submitted multi_select" | "assistant_message-submitted" | "assistant_message-submitted recommendation" | "assistant_message-submitted message" | "assistant_message-submitted single_select" | "assistant_message-submitted multi_select" | "assistant_message-submitted exit_to_chat" | "assistant_message-submitted exit_to_purchase" | "feedback-shown" | "feedback_skip-clicked" | "sale-completed" | "tab-clicked" | "tool_close-clicked" | "exit_to_purchase-completed" | "exit_to_chat-completed";
1546
1622
  pageviewId?: string;
1547
1623
  url?: string;
1548
1624
  userAgent?: string;
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var b=Object.create;var a=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var _=Object.getOwnPropertyNames;var T=Object.getPrototypeOf,D=Object.prototype.hasOwnProperty;var P=(t,e)=>{for(var s in e)a(t,s,{get:e[s],enumerable:!0})},w=(t,e,s,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of _(e))!D.call(t,i)&&i!==s&&a(t,i,{get:()=>e[i],enumerable:!(n=O(e,i))||n.enumerable});return t};var N=(t,e,s)=>(s=t!=null?b(T(t)):{},w(e||!t||!t.__esModule?a(s,"default",{value:t,enumerable:!0}):s,t)),k=t=>w(a({},"__esModule",{value:!0}),t);var W={};P(W,{CONVERSATION_ID:()=>d,Client:()=>E,SESSION_ID:()=>v,TTL:()=>M,USER_ID:()=>y,authMiddleware:()=>p,deleteConversationId:()=>g,getConversationId:()=>I,getSessionId:()=>f,getUserId:()=>h,setConversationId:()=>c,setSessionId:()=>m,setUserId:()=>x});module.exports=k(W);var S=N(require("openapi-fetch"));var d="__15gifts_conversation_id",g=()=>sessionStorage.removeItem(d),I=()=>sessionStorage.getItem(d),c=t=>sessionStorage.setItem(d,t);var v="__15gifts_session_id",f=()=>sessionStorage.getItem(v),m=t=>sessionStorage.setItem(v,t);var A=t=>{let e=localStorage.getItem(t);if(!e)return null;let s=JSON.parse(e);return Date.now()>s.expires?(localStorage.removeItem(t),null):s.value},u=A;var R=(t,e,s)=>{let n={expires:Date.now()+s,value:e};localStorage.setItem(t,JSON.stringify(n))},l=R;var y="__15gifts_user_id",M=1e3*60*60*24*30,h=()=>u(y),x=t=>l(y,t,M);var U=t=>({onRequest:async({request:e})=>(e.headers.set("Authorization",`Bearer ${t}`),e)}),p=U;var C="0.6.1";var E=class{endpoint;identity;constructor({customerId:e,fetch:s,conversationUrl:n,frontendUrl:i}){let o={"X-SDK-VERSION":C};this.endpoint={conversation:(0,S.default)({baseUrl:n,fetch:s,headers:o}),frontend:(0,S.default)({baseUrl:i,fetch:s,headers:o})},this.identity={customerId:e,conversationId:I()??void 0,sessionId:f()??void 0,userId:h()??void 0}}async createIdentity(){let{customerId:e,pageviewId:s,sessionId:n,userId:i}=this.identity,{data:o}=await this.endpoint.frontend.POST("/api/tracking/identity/v2",{body:{customerId:e,sessionId:n,userId:i}});o&&(s||(this.identity.pageviewId=o.pageviewId),n||(this.identity.sessionId=o.sessionId,m(o.sessionId)),i||(this.identity.userId=o.userId,x(o.userId)),Object.values(this.endpoint).forEach(r=>{r.use(p(o.token))}))}endConversation(){g(),this.identity.conversationId=void 0}async startConversation(e){this.endConversation();let s={availableProductIds:[],...e},{data:n}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{type:"START_CONVERSATION",conversationContext:s}}),[i,o]=n,r=i.conversationId;if(!r)throw new Error("Conversation ID not received");return c(r),this.identity.conversationId=r,o}async sendMessage({userMessage:e}){let{data:s}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{conversationId:this.identity.conversationId,userMessage:e,type:"MESSAGE"}});if(!s)return;let n=s.filter(r=>r.type==="DEBUG");n.length&&console.info("Debug messages:",n);let i=s.find(r=>r.type==="CONVERSATION_ID")?.conversationId;return i&&(c(i),this.identity.conversationId=i),s.filter(r=>r.type!=="CONVERSATION_ID"&&r.type!=="DEBUG")}async trackEvent(e,s){let n={additionalProperties:s,conversationId:this.identity.conversationId,deviceType:void 0,eventName:e,pageviewId:this.identity.pageviewId,url:window.location.href,userAgent:window.navigator.userAgent};return this.endpoint.frontend.POST("/api/tracking/user/v2",{body:n})}};0&&(module.exports={CONVERSATION_ID,Client,SESSION_ID,TTL,USER_ID,authMiddleware,deleteConversationId,getConversationId,getSessionId,getUserId,setConversationId,setSessionId,setUserId});
1
+ "use strict";var b=Object.create;var a=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var _=Object.getOwnPropertyNames;var T=Object.getPrototypeOf,D=Object.prototype.hasOwnProperty;var P=(t,e)=>{for(var s in e)a(t,s,{get:e[s],enumerable:!0})},w=(t,e,s,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of _(e))!D.call(t,i)&&i!==s&&a(t,i,{get:()=>e[i],enumerable:!(n=O(e,i))||n.enumerable});return t};var N=(t,e,s)=>(s=t!=null?b(T(t)):{},w(e||!t||!t.__esModule?a(s,"default",{value:t,enumerable:!0}):s,t)),k=t=>w(a({},"__esModule",{value:!0}),t);var W={};P(W,{CONVERSATION_ID:()=>d,Client:()=>E,SESSION_ID:()=>v,TTL:()=>M,USER_ID:()=>y,authMiddleware:()=>p,deleteConversationId:()=>g,getConversationId:()=>I,getSessionId:()=>f,getUserId:()=>h,setConversationId:()=>c,setSessionId:()=>m,setUserId:()=>x});module.exports=k(W);var S=N(require("openapi-fetch"));var d="__15gifts_conversation_id",g=()=>sessionStorage.removeItem(d),I=()=>sessionStorage.getItem(d),c=t=>sessionStorage.setItem(d,t);var v="__15gifts_session_id",f=()=>sessionStorage.getItem(v),m=t=>sessionStorage.setItem(v,t);var A=t=>{let e=localStorage.getItem(t);if(!e)return null;let s=JSON.parse(e);return Date.now()>s.expires?(localStorage.removeItem(t),null):s.value},u=A;var R=(t,e,s)=>{let n={expires:Date.now()+s,value:e};localStorage.setItem(t,JSON.stringify(n))},l=R;var y="__15gifts_user_id",M=1e3*60*60*24*30,h=()=>u(y),x=t=>l(y,t,M);var U=t=>({onRequest:async({request:e})=>(e.headers.set("Authorization",`Bearer ${t}`),e)}),p=U;var C="0.6.3";var E=class{endpoint;identity;constructor({customerId:e,fetch:s,conversationUrl:n,frontendUrl:i}){let o={"X-SDK-VERSION":C};this.endpoint={conversation:(0,S.default)({baseUrl:n,fetch:s,headers:o}),frontend:(0,S.default)({baseUrl:i,fetch:s,headers:o})},this.identity={customerId:e,conversationId:I()??void 0,sessionId:f()??void 0,userId:h()??void 0}}async createIdentity(){let{customerId:e,pageviewId:s,sessionId:n,userId:i}=this.identity,{data:o}=await this.endpoint.frontend.POST("/api/tracking/identity/v2",{body:{customerId:e,sessionId:n,userId:i}});o&&(s||(this.identity.pageviewId=o.pageviewId),n||(this.identity.sessionId=o.sessionId,m(o.sessionId)),i||(this.identity.userId=o.userId,x(o.userId)),Object.values(this.endpoint).forEach(r=>{r.use(p(o.token))}))}endConversation(){g(),this.identity.conversationId=void 0}async startConversation(e){this.endConversation();let s={availableProductIds:[],...e},{data:n}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{type:"START_CONVERSATION",conversationContext:s}}),[i,o]=n,r=i.conversationId;if(!r)throw new Error("Conversation ID not received");return c(r),this.identity.conversationId=r,o}async sendMessage({userMessage:e}){let{data:s}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{conversationId:this.identity.conversationId,userMessage:e,type:"MESSAGE"}});if(!s)return;let n=s.filter(r=>r.type==="DEBUG");n.length&&console.info("Debug messages:",n);let i=s.find(r=>r.type==="CONVERSATION_ID")?.conversationId;return i&&(c(i),this.identity.conversationId=i),s.filter(r=>r.type!=="CONVERSATION_ID"&&r.type!=="DEBUG")}async trackEvent(e,s){let n={additionalProperties:s,conversationId:this.identity.conversationId,deviceType:void 0,eventName:e,pageviewId:this.identity.pageviewId,url:window.location.href,userAgent:window.navigator.userAgent};return this.endpoint.frontend.POST("/api/tracking/user/v2",{body:n})}};0&&(module.exports={CONVERSATION_ID,Client,SESSION_ID,TTL,USER_ID,authMiddleware,deleteConversationId,getConversationId,getSessionId,getUserId,setConversationId,setSessionId,setUserId});
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/middlewares/auth.ts","../package.json"],"sourcesContent":["export * from './client'\nexport * from './identity'\nexport * from './middlewares'\nexport * from './types'\n","import createClient from 'openapi-fetch'\n\nimport {\n deleteConversationId,\n getConversationId,\n getSessionId,\n getUserId,\n setConversationId,\n setSessionId,\n setUserId,\n} from './identity'\nimport { authMiddleware } from './middlewares'\nimport type { paths as conversationPaths } from './schemas/conversation'\nimport type { paths as frontendPaths } from './schemas/frontend'\nimport type {\n BasicMessage,\n Config,\n ConversationIdMessage,\n DebugMessage,\n Endpoint,\n Identity,\n Message,\n TrackingEvent,\n} from './types'\nimport { version } from '../package.json'\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/v2')\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({ customerId, fetch, conversationUrl, frontendUrl }: Config) {\n const headers = {\n 'X-SDK-VERSION': version,\n }\n\n this.endpoint = {\n conversation: createClient<conversationPaths>({ baseUrl: conversationUrl, fetch, headers }),\n frontend: createClient<frontendPaths>({ baseUrl: frontendUrl, fetch, headers }),\n }\n this.identity = {\n customerId,\n conversationId: getConversationId() ?? undefined,\n sessionId: getSessionId() ?? undefined,\n userId: getUserId() ?? undefined,\n }\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 *\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, pageviewId, sessionId, userId } = this.identity\n\n const { data } = await this.endpoint.frontend.POST('/api/tracking/identity/v2', {\n body: {\n customerId,\n sessionId,\n userId,\n },\n })\n\n if (data) {\n if (!pageviewId) {\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 Object.values(this.endpoint).forEach((endpont) => {\n endpont.use(authMiddleware(data.token))\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.productOverrides Overrides for product details.\n *\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(context?: {\n eligibleProducts?: string[]\n productOverrides?: Record<string, { price: number; minSpeed?: number; maxSpeed?: number }>\n }): Promise<BasicMessage | undefined> {\n this.endConversation()\n\n const conversationContext = {\n availableProductIds: [],\n ...context,\n }\n\n const { data } = await this.endpoint.conversation.POST(`/api/conversation/v3`, {\n body: {\n type: 'START_CONVERSATION',\n conversationContext,\n },\n })\n\n const [conversationIdMessage, openingMessage] = data as [ConversationIdMessage, BasicMessage]\n\n const conversationId = conversationIdMessage.conversationId\n if (!conversationId) {\n throw new Error('Conversation ID not received')\n }\n\n setConversationId(conversationId)\n this.identity.conversationId = conversationId\n\n return openingMessage\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({\n userMessage,\n }: {\n userMessage: string\n }): Promise<Exclude<Message, ConversationIdMessage | DebugMessage>[] | undefined> {\n const { data } = await this.endpoint.conversation.POST('/api/conversation/v3', {\n body: {\n conversationId: this.identity.conversationId,\n userMessage,\n type: 'MESSAGE',\n },\n })\n\n if (!data) return undefined\n\n // Log debug messages\n // These will only be in the response when used in internal testing\n const debugMessages = data.filter((message) => message.type === 'DEBUG')\n if (debugMessages.length) {\n console.info('Debug messages:', debugMessages)\n }\n\n // When a request does not contain a conversation ID, the API will return a new conversation ID as the first message\n const conversationId = data.find((message) => message.type === 'CONVERSATION_ID')?.conversationId\n if (conversationId) {\n setConversationId(conversationId)\n this.identity.conversationId = conversationId\n }\n\n const messages = data.filter((message) => message.type !== 'CONVERSATION_ID' && message.type !== 'DEBUG')\n return messages\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('tab-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 deviceType: undefined,\n eventName,\n pageviewId: this.identity.pageviewId,\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 * 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","const 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'\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 = 1000 * 60 * 60 * 24 * 30 // 30 days\n\n/**\n * Retrieves the user ID from `localStorage`.\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 = () => getItemWithExpiry(USER_ID)\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","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 request.headers.set('Authorization', `Bearer ${accessToken}`)\n\n return request\n },\n})\n\nexport default authMiddleware\n","{\n \"name\": \"@15gifts/sdk\",\n \"version\": \"0.6.1\",\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 \"dev\": \"tsup --watch\",\n \"format\": \"prettier . --write\",\n \"generate\": \"npx openapi-typescript\",\n \"lint\": \"eslint .\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"typecheck\": \"tsc\"\n },\n \"dependencies\": {\n \"openapi-fetch\": \"^0.13.3\"\n },\n \"devDependencies\": {\n \"openapi-typescript\": \"^7.4.4\",\n \"tsup\": \"^8.3.5\"\n },\n \"sideEffects\": false,\n \"prettier\": \"prettier-config-custom\"\n}\n"],"mappings":"0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,EAAA,WAAAC,EAAA,eAAAC,EAAA,QAAAC,EAAA,YAAAC,EAAA,mBAAAC,EAAA,yBAAAC,EAAA,sBAAAC,EAAA,iBAAAC,EAAA,cAAAC,EAAA,sBAAAC,EAAA,iBAAAC,EAAA,cAAAC,IAAA,eAAAC,EAAAf,GCAA,IAAAgB,EAAyB,4BCKlB,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,EChBf,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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C9B,WAAY,OACZ,UAAAD,EACA,WAAY,KAAK,SAAS,WAC1B,IAAK,OAAO,SAAS,KACrB,UAAW,OAAO,UAAU,SAC9B,EAEA,OAAO,KAAK,SAAS,SAAS,KAAK,wBAAyB,CAC1D,KAAAE,CACF,CAAC,CACH,CACF","names":["index_exports","__export","CONVERSATION_ID","Client","SESSION_ID","TTL","USER_ID","auth_default","deleteConversationId","getConversationId","getSessionId","getUserId","setConversationId","setSessionId","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","USER_ID","TTL","getUserId","getItemWithExpiry_default","setUserId","userId","setItemWithExpiry_default","authMiddleware","accessToken","request","auth_default","version","Client","customerId","fetch","conversationUrl","frontendUrl","headers","version","createClient","getConversationId","getSessionId","getUserId","pageviewId","sessionId","userId","data","setSessionId","setUserId","endpont","auth_default","deleteConversationId","context","conversationContext","conversationIdMessage","openingMessage","conversationId","setConversationId","userMessage","debugMessages","message","eventName","properties","body"]}
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/middlewares/auth.ts","../package.json"],"sourcesContent":["export * from './client'\nexport * from './identity'\nexport * from './middlewares'\nexport * from './types'\n","import createClient from 'openapi-fetch'\n\nimport {\n deleteConversationId,\n getConversationId,\n getSessionId,\n getUserId,\n setConversationId,\n setSessionId,\n setUserId,\n} from './identity'\nimport { authMiddleware } from './middlewares'\nimport type { paths as conversationPaths } from './schemas/conversation'\nimport type { paths as frontendPaths } from './schemas/frontend'\nimport type {\n BasicMessage,\n Config,\n ConversationIdMessage,\n DebugMessage,\n Endpoint,\n Identity,\n Message,\n TrackingEvent,\n} from './types'\nimport { version } from '../package.json'\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/v2')\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({ customerId, fetch, conversationUrl, frontendUrl }: Config) {\n const headers = {\n 'X-SDK-VERSION': version,\n }\n\n this.endpoint = {\n conversation: createClient<conversationPaths>({ baseUrl: conversationUrl, fetch, headers }),\n frontend: createClient<frontendPaths>({ baseUrl: frontendUrl, fetch, headers }),\n }\n this.identity = {\n customerId,\n conversationId: getConversationId() ?? undefined,\n sessionId: getSessionId() ?? undefined,\n userId: getUserId() ?? undefined,\n }\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 *\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, pageviewId, sessionId, userId } = this.identity\n\n const { data } = await this.endpoint.frontend.POST('/api/tracking/identity/v2', {\n body: {\n customerId,\n sessionId,\n userId,\n },\n })\n\n if (data) {\n if (!pageviewId) {\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 Object.values(this.endpoint).forEach((endpont) => {\n endpont.use(authMiddleware(data.token))\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.productOverrides Overrides for product details.\n *\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(context?: {\n eligibleProducts?: string[]\n productOverrides?: Record<string, { price: number; minSpeed?: number; maxSpeed?: number }>\n }): Promise<BasicMessage | undefined> {\n this.endConversation()\n\n const conversationContext = {\n availableProductIds: [],\n ...context,\n }\n\n const { data } = await this.endpoint.conversation.POST(`/api/conversation/v3`, {\n body: {\n type: 'START_CONVERSATION',\n conversationContext,\n },\n })\n\n const [conversationIdMessage, openingMessage] = data as [ConversationIdMessage, BasicMessage]\n\n const conversationId = conversationIdMessage.conversationId\n if (!conversationId) {\n throw new Error('Conversation ID not received')\n }\n\n setConversationId(conversationId)\n this.identity.conversationId = conversationId\n\n return openingMessage\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({\n userMessage,\n }: {\n userMessage: string\n }): Promise<Exclude<Message, ConversationIdMessage | DebugMessage>[] | undefined> {\n const { data } = await this.endpoint.conversation.POST('/api/conversation/v3', {\n body: {\n conversationId: this.identity.conversationId,\n userMessage,\n type: 'MESSAGE',\n },\n })\n\n if (!data) return undefined\n\n // Log debug messages\n // These will only be in the response when used in internal testing\n const debugMessages = data.filter((message) => message.type === 'DEBUG')\n if (debugMessages.length) {\n console.info('Debug messages:', debugMessages)\n }\n\n // When a request does not contain a conversation ID, the API will return a new conversation ID as the first message\n const conversationId = data.find((message) => message.type === 'CONVERSATION_ID')?.conversationId\n if (conversationId) {\n setConversationId(conversationId)\n this.identity.conversationId = conversationId\n }\n\n const messages = data.filter((message) => message.type !== 'CONVERSATION_ID' && message.type !== 'DEBUG')\n return messages\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('tab-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 deviceType: undefined,\n eventName,\n pageviewId: this.identity.pageviewId,\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 * 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","const 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'\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 = 1000 * 60 * 60 * 24 * 30 // 30 days\n\n/**\n * Retrieves the user ID from `localStorage`.\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 = () => getItemWithExpiry(USER_ID)\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","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 request.headers.set('Authorization', `Bearer ${accessToken}`)\n\n return request\n },\n})\n\nexport default authMiddleware\n","{\n \"name\": \"@15gifts/sdk\",\n \"version\": \"0.6.3\",\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 \"dev\": \"tsup --watch\",\n \"format\": \"prettier . --write\",\n \"generate\": \"npx openapi-typescript\",\n \"lint\": \"eslint .\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"typecheck\": \"tsc\"\n },\n \"dependencies\": {\n \"openapi-fetch\": \"^0.13.3\"\n },\n \"devDependencies\": {\n \"openapi-typescript\": \"^7.4.4\",\n \"tsup\": \"^8.3.5\"\n },\n \"sideEffects\": false,\n \"prettier\": \"prettier-config-custom\"\n}\n"],"mappings":"0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,EAAA,WAAAC,EAAA,eAAAC,EAAA,QAAAC,EAAA,YAAAC,EAAA,mBAAAC,EAAA,yBAAAC,EAAA,sBAAAC,EAAA,iBAAAC,EAAA,cAAAC,EAAA,sBAAAC,EAAA,iBAAAC,EAAA,cAAAC,IAAA,eAAAC,EAAAf,GCAA,IAAAgB,EAAyB,4BCKlB,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,EChBf,IAAMK,EAAoB,CAACC,EAAaC,EAAeC,IAAgB,CACrE,IAAMC,EAAO,CACX,QAAS,KAAK,IAAI,EAAID,EACtB,MAAAD,CACF,EAEA,aAAa,QAAQD,EAAK,KAAK,UAAUG,CAAI,CAAC,CAChD,EAEOC,EAAQL,ECFR,IAAMM,EAAU,oBAQVC,EAAM,IAAO,GAAK,GAAK,GAAK,GAkB5BC,EAAY,IAAMC,EAAkB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,SAAS,SAAS,KAAK,wBAAyB,CAC1D,KAAAE,CACF,CAAC,CACH,CACF","names":["index_exports","__export","CONVERSATION_ID","Client","SESSION_ID","TTL","USER_ID","auth_default","deleteConversationId","getConversationId","getSessionId","getUserId","setConversationId","setSessionId","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","USER_ID","TTL","getUserId","getItemWithExpiry_default","setUserId","userId","setItemWithExpiry_default","authMiddleware","accessToken","request","auth_default","version","Client","customerId","fetch","conversationUrl","frontendUrl","headers","version","createClient","getConversationId","getSessionId","getUserId","pageviewId","sessionId","userId","data","setSessionId","setUserId","endpont","auth_default","deleteConversationId","context","conversationContext","conversationIdMessage","openingMessage","conversationId","setConversationId","userMessage","debugMessages","message","eventName","properties","body"]}
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import S from"openapi-fetch";var a="__15gifts_conversation_id",I=()=>sessionStorage.removeItem(a),v=()=>sessionStorage.getItem(a),d=s=>sessionStorage.setItem(a,s);var f="__15gifts_session_id",m=()=>sessionStorage.getItem(f),u=s=>sessionStorage.setItem(f,s);var w=s=>{let t=localStorage.getItem(s);if(!t)return null;let e=JSON.parse(t);return Date.now()>e.expires?(localStorage.removeItem(s),null):e.value},c=w;var M=(s,t,e)=>{let n={expires:Date.now()+e,value:t};localStorage.setItem(s,JSON.stringify(n))},p=M;var l="__15gifts_user_id",C=1e3*60*60*24*30,y=()=>c(l),h=s=>p(l,s,C);var b=s=>({onRequest:async({request:t})=>(t.headers.set("Authorization",`Bearer ${s}`),t)}),g=b;var x="0.6.1";var E=class{endpoint;identity;constructor({customerId:t,fetch:e,conversationUrl:n,frontendUrl:r}){let i={"X-SDK-VERSION":x};this.endpoint={conversation:S({baseUrl:n,fetch:e,headers:i}),frontend:S({baseUrl:r,fetch:e,headers:i})},this.identity={customerId:t,conversationId:v()??void 0,sessionId:m()??void 0,userId:y()??void 0}}async createIdentity(){let{customerId:t,pageviewId:e,sessionId:n,userId:r}=this.identity,{data:i}=await this.endpoint.frontend.POST("/api/tracking/identity/v2",{body:{customerId:t,sessionId:n,userId:r}});i&&(e||(this.identity.pageviewId=i.pageviewId),n||(this.identity.sessionId=i.sessionId,u(i.sessionId)),r||(this.identity.userId=i.userId,h(i.userId)),Object.values(this.endpoint).forEach(o=>{o.use(g(i.token))}))}endConversation(){I(),this.identity.conversationId=void 0}async startConversation(t){this.endConversation();let e={availableProductIds:[],...t},{data:n}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{type:"START_CONVERSATION",conversationContext:e}}),[r,i]=n,o=r.conversationId;if(!o)throw new Error("Conversation ID not received");return d(o),this.identity.conversationId=o,i}async sendMessage({userMessage:t}){let{data:e}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{conversationId:this.identity.conversationId,userMessage:t,type:"MESSAGE"}});if(!e)return;let n=e.filter(o=>o.type==="DEBUG");n.length&&console.info("Debug messages:",n);let r=e.find(o=>o.type==="CONVERSATION_ID")?.conversationId;return r&&(d(r),this.identity.conversationId=r),e.filter(o=>o.type!=="CONVERSATION_ID"&&o.type!=="DEBUG")}async trackEvent(t,e){let n={additionalProperties:e,conversationId:this.identity.conversationId,deviceType:void 0,eventName:t,pageviewId:this.identity.pageviewId,url:window.location.href,userAgent:window.navigator.userAgent};return this.endpoint.frontend.POST("/api/tracking/user/v2",{body:n})}};export{a as CONVERSATION_ID,E as Client,f as SESSION_ID,C as TTL,l as USER_ID,g as authMiddleware,I as deleteConversationId,v as getConversationId,m as getSessionId,y as getUserId,d as setConversationId,u as setSessionId,h as setUserId};
1
+ import S from"openapi-fetch";var a="__15gifts_conversation_id",I=()=>sessionStorage.removeItem(a),v=()=>sessionStorage.getItem(a),d=s=>sessionStorage.setItem(a,s);var f="__15gifts_session_id",m=()=>sessionStorage.getItem(f),u=s=>sessionStorage.setItem(f,s);var w=s=>{let t=localStorage.getItem(s);if(!t)return null;let e=JSON.parse(t);return Date.now()>e.expires?(localStorage.removeItem(s),null):e.value},c=w;var M=(s,t,e)=>{let n={expires:Date.now()+e,value:t};localStorage.setItem(s,JSON.stringify(n))},p=M;var l="__15gifts_user_id",C=1e3*60*60*24*30,y=()=>c(l),h=s=>p(l,s,C);var b=s=>({onRequest:async({request:t})=>(t.headers.set("Authorization",`Bearer ${s}`),t)}),g=b;var x="0.6.3";var E=class{endpoint;identity;constructor({customerId:t,fetch:e,conversationUrl:n,frontendUrl:r}){let i={"X-SDK-VERSION":x};this.endpoint={conversation:S({baseUrl:n,fetch:e,headers:i}),frontend:S({baseUrl:r,fetch:e,headers:i})},this.identity={customerId:t,conversationId:v()??void 0,sessionId:m()??void 0,userId:y()??void 0}}async createIdentity(){let{customerId:t,pageviewId:e,sessionId:n,userId:r}=this.identity,{data:i}=await this.endpoint.frontend.POST("/api/tracking/identity/v2",{body:{customerId:t,sessionId:n,userId:r}});i&&(e||(this.identity.pageviewId=i.pageviewId),n||(this.identity.sessionId=i.sessionId,u(i.sessionId)),r||(this.identity.userId=i.userId,h(i.userId)),Object.values(this.endpoint).forEach(o=>{o.use(g(i.token))}))}endConversation(){I(),this.identity.conversationId=void 0}async startConversation(t){this.endConversation();let e={availableProductIds:[],...t},{data:n}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{type:"START_CONVERSATION",conversationContext:e}}),[r,i]=n,o=r.conversationId;if(!o)throw new Error("Conversation ID not received");return d(o),this.identity.conversationId=o,i}async sendMessage({userMessage:t}){let{data:e}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{conversationId:this.identity.conversationId,userMessage:t,type:"MESSAGE"}});if(!e)return;let n=e.filter(o=>o.type==="DEBUG");n.length&&console.info("Debug messages:",n);let r=e.find(o=>o.type==="CONVERSATION_ID")?.conversationId;return r&&(d(r),this.identity.conversationId=r),e.filter(o=>o.type!=="CONVERSATION_ID"&&o.type!=="DEBUG")}async trackEvent(t,e){let n={additionalProperties:e,conversationId:this.identity.conversationId,deviceType:void 0,eventName:t,pageviewId:this.identity.pageviewId,url:window.location.href,userAgent:window.navigator.userAgent};return this.endpoint.frontend.POST("/api/tracking/user/v2",{body:n})}};export{a as CONVERSATION_ID,E as Client,f as SESSION_ID,C as TTL,l as USER_ID,g as authMiddleware,I as deleteConversationId,v as getConversationId,m as getSessionId,y as getUserId,d as setConversationId,u as setSessionId,h as setUserId};
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/middlewares/auth.ts","../package.json"],"sourcesContent":["import createClient from 'openapi-fetch'\n\nimport {\n deleteConversationId,\n getConversationId,\n getSessionId,\n getUserId,\n setConversationId,\n setSessionId,\n setUserId,\n} from './identity'\nimport { authMiddleware } from './middlewares'\nimport type { paths as conversationPaths } from './schemas/conversation'\nimport type { paths as frontendPaths } from './schemas/frontend'\nimport type {\n BasicMessage,\n Config,\n ConversationIdMessage,\n DebugMessage,\n Endpoint,\n Identity,\n Message,\n TrackingEvent,\n} from './types'\nimport { version } from '../package.json'\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/v2')\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({ customerId, fetch, conversationUrl, frontendUrl }: Config) {\n const headers = {\n 'X-SDK-VERSION': version,\n }\n\n this.endpoint = {\n conversation: createClient<conversationPaths>({ baseUrl: conversationUrl, fetch, headers }),\n frontend: createClient<frontendPaths>({ baseUrl: frontendUrl, fetch, headers }),\n }\n this.identity = {\n customerId,\n conversationId: getConversationId() ?? undefined,\n sessionId: getSessionId() ?? undefined,\n userId: getUserId() ?? undefined,\n }\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 *\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, pageviewId, sessionId, userId } = this.identity\n\n const { data } = await this.endpoint.frontend.POST('/api/tracking/identity/v2', {\n body: {\n customerId,\n sessionId,\n userId,\n },\n })\n\n if (data) {\n if (!pageviewId) {\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 Object.values(this.endpoint).forEach((endpont) => {\n endpont.use(authMiddleware(data.token))\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.productOverrides Overrides for product details.\n *\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(context?: {\n eligibleProducts?: string[]\n productOverrides?: Record<string, { price: number; minSpeed?: number; maxSpeed?: number }>\n }): Promise<BasicMessage | undefined> {\n this.endConversation()\n\n const conversationContext = {\n availableProductIds: [],\n ...context,\n }\n\n const { data } = await this.endpoint.conversation.POST(`/api/conversation/v3`, {\n body: {\n type: 'START_CONVERSATION',\n conversationContext,\n },\n })\n\n const [conversationIdMessage, openingMessage] = data as [ConversationIdMessage, BasicMessage]\n\n const conversationId = conversationIdMessage.conversationId\n if (!conversationId) {\n throw new Error('Conversation ID not received')\n }\n\n setConversationId(conversationId)\n this.identity.conversationId = conversationId\n\n return openingMessage\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({\n userMessage,\n }: {\n userMessage: string\n }): Promise<Exclude<Message, ConversationIdMessage | DebugMessage>[] | undefined> {\n const { data } = await this.endpoint.conversation.POST('/api/conversation/v3', {\n body: {\n conversationId: this.identity.conversationId,\n userMessage,\n type: 'MESSAGE',\n },\n })\n\n if (!data) return undefined\n\n // Log debug messages\n // These will only be in the response when used in internal testing\n const debugMessages = data.filter((message) => message.type === 'DEBUG')\n if (debugMessages.length) {\n console.info('Debug messages:', debugMessages)\n }\n\n // When a request does not contain a conversation ID, the API will return a new conversation ID as the first message\n const conversationId = data.find((message) => message.type === 'CONVERSATION_ID')?.conversationId\n if (conversationId) {\n setConversationId(conversationId)\n this.identity.conversationId = conversationId\n }\n\n const messages = data.filter((message) => message.type !== 'CONVERSATION_ID' && message.type !== 'DEBUG')\n return messages\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('tab-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 deviceType: undefined,\n eventName,\n pageviewId: this.identity.pageviewId,\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 * 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","const 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'\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 = 1000 * 60 * 60 * 24 * 30 // 30 days\n\n/**\n * Retrieves the user ID from `localStorage`.\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 = () => getItemWithExpiry(USER_ID)\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","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 request.headers.set('Authorization', `Bearer ${accessToken}`)\n\n return request\n },\n})\n\nexport default authMiddleware\n","{\n \"name\": \"@15gifts/sdk\",\n \"version\": \"0.6.1\",\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 \"dev\": \"tsup --watch\",\n \"format\": \"prettier . --write\",\n \"generate\": \"npx openapi-typescript\",\n \"lint\": \"eslint .\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"typecheck\": \"tsc\"\n },\n \"dependencies\": {\n \"openapi-fetch\": \"^0.13.3\"\n },\n \"devDependencies\": {\n \"openapi-typescript\": \"^7.4.4\",\n \"tsup\": \"^8.3.5\"\n },\n \"sideEffects\": false,\n \"prettier\": \"prettier-config-custom\"\n}\n"],"mappings":"AAAA,OAAOA,MAAkB,gBCKlB,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,E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M,OAIX,IAAMa,EAAgBb,EAAK,OAAQc,GAAYA,EAAQ,OAAS,OAAO,EACnED,EAAc,QAChB,QAAQ,KAAK,kBAAmBA,CAAa,EAI/C,IAAMH,EAAiBV,EAAK,KAAMc,GAAYA,EAAQ,OAAS,iBAAiB,GAAG,eACnF,OAAIJ,IACFC,EAAkBD,CAAc,EAChC,KAAK,SAAS,eAAiBA,GAGhBV,EAAK,OAAQc,GAAYA,EAAQ,OAAS,mBAAqBA,EAAQ,OAAS,OAAO,CAE1G,CAcA,MAAM,WAAWC,EAAuCC,EAAoD,CAC1G,IAAMC,EAAsB,CAC1B,qBAAsBD,EACtB,eAAgB,KAAK,SAAS,eAC9B,WAAY,OACZ,UAAAD,EACA,WAAY,KAAK,SAAS,WAC1B,IAAK,OAAO,SAAS,KACrB,UAAW,OAAO,UAAU,SAC9B,EAEA,OAAO,KAAK,SAAS,SAAS,KAAK,wBAAyB,CAC1D,KAAAE,CACF,CAAC,CACH,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","USER_ID","TTL","getUserId","getItemWithExpiry_default","setUserId","userId","setItemWithExpiry_default","authMiddleware","accessToken","request","auth_default","version","Client","customerId","fetch","conversationUrl","frontendUrl","headers","version","createClient","getConversationId","getSessionId","getUserId","pageviewId","sessionId","userId","data","setSessionId","setUserId","endpont","auth_default","deleteConversationId","context","conversationContext","conversationIdMessage","openingMessage","conversationId","setConversationId","userMessage","debugMessages","message","eventName","properties","body"]}
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/middlewares/auth.ts","../package.json"],"sourcesContent":["import createClient from 'openapi-fetch'\n\nimport {\n deleteConversationId,\n getConversationId,\n getSessionId,\n getUserId,\n setConversationId,\n setSessionId,\n setUserId,\n} from './identity'\nimport { authMiddleware } from './middlewares'\nimport type { paths as conversationPaths } from './schemas/conversation'\nimport type { paths as frontendPaths } from './schemas/frontend'\nimport type {\n BasicMessage,\n Config,\n ConversationIdMessage,\n DebugMessage,\n Endpoint,\n Identity,\n Message,\n TrackingEvent,\n} from './types'\nimport { version } from '../package.json'\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/v2')\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({ customerId, fetch, conversationUrl, frontendUrl }: Config) {\n const headers = {\n 'X-SDK-VERSION': version,\n }\n\n this.endpoint = {\n conversation: createClient<conversationPaths>({ baseUrl: conversationUrl, fetch, headers }),\n frontend: createClient<frontendPaths>({ baseUrl: frontendUrl, fetch, headers }),\n }\n this.identity = {\n customerId,\n conversationId: getConversationId() ?? undefined,\n sessionId: getSessionId() ?? undefined,\n userId: getUserId() ?? undefined,\n }\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 *\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, pageviewId, sessionId, userId } = this.identity\n\n const { data } = await this.endpoint.frontend.POST('/api/tracking/identity/v2', {\n body: {\n customerId,\n sessionId,\n userId,\n },\n })\n\n if (data) {\n if (!pageviewId) {\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 Object.values(this.endpoint).forEach((endpont) => {\n endpont.use(authMiddleware(data.token))\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.productOverrides Overrides for product details.\n *\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(context?: {\n eligibleProducts?: string[]\n productOverrides?: Record<string, { price: number; minSpeed?: number; maxSpeed?: number }>\n }): Promise<BasicMessage | undefined> {\n this.endConversation()\n\n const conversationContext = {\n availableProductIds: [],\n ...context,\n }\n\n const { data } = await this.endpoint.conversation.POST(`/api/conversation/v3`, {\n body: {\n type: 'START_CONVERSATION',\n conversationContext,\n },\n })\n\n const [conversationIdMessage, openingMessage] = data as [ConversationIdMessage, BasicMessage]\n\n const conversationId = conversationIdMessage.conversationId\n if (!conversationId) {\n throw new Error('Conversation ID not received')\n }\n\n setConversationId(conversationId)\n this.identity.conversationId = conversationId\n\n return openingMessage\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({\n userMessage,\n }: {\n userMessage: string\n }): Promise<Exclude<Message, ConversationIdMessage | DebugMessage>[] | undefined> {\n const { data } = await this.endpoint.conversation.POST('/api/conversation/v3', {\n body: {\n conversationId: this.identity.conversationId,\n userMessage,\n type: 'MESSAGE',\n },\n })\n\n if (!data) return undefined\n\n // Log debug messages\n // These will only be in the response when used in internal testing\n const debugMessages = data.filter((message) => message.type === 'DEBUG')\n if (debugMessages.length) {\n console.info('Debug messages:', debugMessages)\n }\n\n // When a request does not contain a conversation ID, the API will return a new conversation ID as the first message\n const conversationId = data.find((message) => message.type === 'CONVERSATION_ID')?.conversationId\n if (conversationId) {\n setConversationId(conversationId)\n this.identity.conversationId = conversationId\n }\n\n const messages = data.filter((message) => message.type !== 'CONVERSATION_ID' && message.type !== 'DEBUG')\n return messages\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('tab-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 deviceType: undefined,\n eventName,\n pageviewId: this.identity.pageviewId,\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 * 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","const 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'\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 = 1000 * 60 * 60 * 24 * 30 // 30 days\n\n/**\n * Retrieves the user ID from `localStorage`.\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 = () => getItemWithExpiry(USER_ID)\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","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 request.headers.set('Authorization', `Bearer ${accessToken}`)\n\n return request\n },\n})\n\nexport default authMiddleware\n","{\n \"name\": \"@15gifts/sdk\",\n \"version\": \"0.6.3\",\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 \"dev\": \"tsup --watch\",\n \"format\": \"prettier . --write\",\n \"generate\": \"npx openapi-typescript\",\n \"lint\": \"eslint .\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"typecheck\": \"tsc\"\n },\n \"dependencies\": {\n \"openapi-fetch\": \"^0.13.3\"\n },\n \"devDependencies\": {\n \"openapi-typescript\": \"^7.4.4\",\n \"tsup\": \"^8.3.5\"\n },\n \"sideEffects\": false,\n \"prettier\": \"prettier-config-custom\"\n}\n"],"mappings":"AAAA,OAAOA,MAAkB,gBCKlB,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,EChBf,IAAMK,EAAoB,CAACC,EAAaC,EAAeC,IAAgB,CACrE,IAAMC,EAAO,CACX,QAAS,KAAK,IAAI,EAAID,EACtB,MAAAD,CACF,EAEA,aAAa,QAAQD,EAAK,KAAK,UAAUG,CAAI,CAAC,CAChD,EAEOC,EAAQL,ECFR,IAAMM,EAAU,oBAQVC,EAAM,IAAO,GAAK,GAAK,GAAK,GAkB5BC,EAAY,IAAMC,E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AAS,KAAK,wBAAyB,CAC1D,KAAAE,CACF,CAAC,CACH,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","USER_ID","TTL","getUserId","getItemWithExpiry_default","setUserId","userId","setItemWithExpiry_default","authMiddleware","accessToken","request","auth_default","version","Client","customerId","fetch","conversationUrl","frontendUrl","headers","version","createClient","getConversationId","getSessionId","getUserId","pageviewId","sessionId","userId","data","setSessionId","setUserId","endpont","auth_default","deleteConversationId","context","conversationContext","conversationIdMessage","openingMessage","conversationId","setConversationId","userMessage","debugMessages","message","eventName","properties","body"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@15gifts/sdk",
3
- "version": "0.6.1",
3
+ "version": "0.6.3",
4
4
  "files": [
5
5
  "dist"
6
6
  ],