@15gifts/sdk 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -469,7 +469,7 @@ interface operations {
469
469
  [name: string]: unknown;
470
470
  };
471
471
  content: {
472
- 'application/json': components['schemas']['ConversationResponseMessageChunk'] | components['schemas']['ConversationResponseDebugChunk'];
472
+ 'application/json': (components['schemas']['ConversationResponseMessageChunk'] | components['schemas']['ConversationResponseDebugChunk'])[];
473
473
  };
474
474
  };
475
475
  /** @description Validation Error */
@@ -952,7 +952,9 @@ interface paths {
952
952
  deviceType?: 'desktop' | 'mobile' | 'tablet';
953
953
  /** @description User Agent */
954
954
  userAgent?: string;
955
- additionalProperties?: Record<string, never>;
955
+ additionalProperties?: {
956
+ [key: string]: string | number | boolean;
957
+ };
956
958
  };
957
959
  };
958
960
  };
@@ -1053,7 +1055,7 @@ interface Identity {
1053
1055
  /**
1054
1056
  * Message within a conversation.
1055
1057
  */
1056
- interface Message {
1058
+ interface Message extends ApiMessage {
1057
1059
  /**
1058
1060
  * The conversation ID to which the message belongs.
1059
1061
  */
@@ -1139,12 +1141,12 @@ declare class Client {
1139
1141
  * Sends a message in the conversation, optionally with an opening message.
1140
1142
  *
1141
1143
  * @param options - An object containing the opening message and the user message.
1142
- * @returns A promise that resolves to a message or a debug record.
1144
+ * @returns A promise that resolves to an array of messages or debug records.
1143
1145
  * If the message is a debug record, it will throw an error.
1144
1146
  *
1145
1147
  * @example
1146
1148
  * ```ts
1147
- * const newMessage = await client.sendMessage({
1149
+ * const newMessages = await client.sendMessage({
1148
1150
  * openingMessage: 'Hello! How can I help you?',
1149
1151
  * userMessage: 'How can I get support?',
1150
1152
  * })
@@ -1159,7 +1161,7 @@ declare class Client {
1159
1161
  sendMessage({ openingMessage, userMessage, }: {
1160
1162
  openingMessage?: ConversationApiRequest['openingMessage'];
1161
1163
  userMessage: ConversationApiRequest['userMessage'];
1162
- }): Promise<Message | undefined>;
1164
+ }): Promise<Message[] | undefined>;
1163
1165
  /**
1164
1166
  * Sends an event to the tracking API, with the required properties already set.
1165
1167
  *
package/dist/index.d.ts CHANGED
@@ -469,7 +469,7 @@ interface operations {
469
469
  [name: string]: unknown;
470
470
  };
471
471
  content: {
472
- 'application/json': components['schemas']['ConversationResponseMessageChunk'] | components['schemas']['ConversationResponseDebugChunk'];
472
+ 'application/json': (components['schemas']['ConversationResponseMessageChunk'] | components['schemas']['ConversationResponseDebugChunk'])[];
473
473
  };
474
474
  };
475
475
  /** @description Validation Error */
@@ -952,7 +952,9 @@ interface paths {
952
952
  deviceType?: 'desktop' | 'mobile' | 'tablet';
953
953
  /** @description User Agent */
954
954
  userAgent?: string;
955
- additionalProperties?: Record<string, never>;
955
+ additionalProperties?: {
956
+ [key: string]: string | number | boolean;
957
+ };
956
958
  };
957
959
  };
958
960
  };
@@ -1053,7 +1055,7 @@ interface Identity {
1053
1055
  /**
1054
1056
  * Message within a conversation.
1055
1057
  */
1056
- interface Message {
1058
+ interface Message extends ApiMessage {
1057
1059
  /**
1058
1060
  * The conversation ID to which the message belongs.
1059
1061
  */
@@ -1139,12 +1141,12 @@ declare class Client {
1139
1141
  * Sends a message in the conversation, optionally with an opening message.
1140
1142
  *
1141
1143
  * @param options - An object containing the opening message and the user message.
1142
- * @returns A promise that resolves to a message or a debug record.
1144
+ * @returns A promise that resolves to an array of messages or debug records.
1143
1145
  * If the message is a debug record, it will throw an error.
1144
1146
  *
1145
1147
  * @example
1146
1148
  * ```ts
1147
- * const newMessage = await client.sendMessage({
1149
+ * const newMessages = await client.sendMessage({
1148
1150
  * openingMessage: 'Hello! How can I help you?',
1149
1151
  * userMessage: 'How can I get support?',
1150
1152
  * })
@@ -1159,7 +1161,7 @@ declare class Client {
1159
1161
  sendMessage({ openingMessage, userMessage, }: {
1160
1162
  openingMessage?: ConversationApiRequest['openingMessage'];
1161
1163
  userMessage: ConversationApiRequest['userMessage'];
1162
- }): Promise<Message | undefined>;
1164
+ }): Promise<Message[] | undefined>;
1163
1165
  /**
1164
1166
  * Sends an event to the tracking API, with the required properties already set.
1165
1167
  *
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var _=Object.create;var o=Object.defineProperty;var P=Object.getOwnPropertyDescriptor;var w=Object.getOwnPropertyNames;var T=Object.getPrototypeOf,b=Object.prototype.hasOwnProperty;var D=(e,t)=>{for(var s in t)o(e,s,{get:t[s],enumerable:!0})},S=(e,t,s,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of w(t))!b.call(e,i)&&i!==s&&o(e,i,{get:()=>t[i],enumerable:!(n=P(t,i))||n.enumerable});return e};var O=(e,t,s)=>(s=e!=null?_(T(e)):{},S(t||!e||!e.__esModule?o(s,"default",{value:e,enumerable:!0}):s,e)),R=e=>S(o({},"__esModule",{value:!0}),e);var A={};D(A,{CONVERSATION_ID:()=>r,Client:()=>x,SESSION_ID:()=>c,TTL:()=>E,USER_ID:()=>f,deleteConversationId:()=>d,getConversationId:()=>a,getSessionId:()=>I,getUserId:()=>v,setConversationId:()=>p,setSessionId:()=>u,setUserId:()=>y});module.exports=R(A);var h=O(require("openapi-fetch"));var r="__15gifts_conversation_id",d=()=>sessionStorage.removeItem(r),a=()=>sessionStorage.getItem(r),p=e=>sessionStorage.setItem(r,e);var c="__15gifts_session_id",I=()=>sessionStorage.getItem(c),u=e=>sessionStorage.setItem(c,e);var U=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},m=U;var k=(e,t,s)=>{let n={expires:Date.now()+s,value:t};localStorage.setItem(e,JSON.stringify(n))},g=k;var f="__15gifts_user_id",E=1e3*60*60*24*30,v=()=>m(f),y=e=>g(f,e,E);var C="0.3.0";var x=class{endpoint;identity;constructor({customerId:t,fetch:s,conversationUrl:n,frontendUrl:i}){let l={"X-SDK-VERSION":C};this.endpoint={conversation:(0,h.default)({baseUrl:n,fetch:s,headers:l}),frontend:(0,h.default)({baseUrl:i,fetch:s,headers:l})},this.identity={customerId:t,conversationId:a(),sessionId:I()??"",userId:v()}}async createIdentity(){let{conversationId:t,sessionId:s,userId:n}=this.identity;if(t&&this.endConversation(),!s||!n){let{data:i}=await this.endpoint.frontend.POST("/api/tracking/identity/v1",{body:{createSessionId:!s,createUserId:!n,customerId:this.identity.customerId}});i&&(!s&&i.sessionId&&(this.identity.sessionId=i.sessionId,u(i.sessionId)),!n&&i.userId&&(this.identity.userId=i.userId,y(i.userId)))}}endConversation(){d()}async sendMessage({openingMessage:t,userMessage:s}){t&&this.identity.conversationId&&this.endConversation();let{data:n}=await this.endpoint.conversation.POST("/api/conversation/v2",{body:{conversationId:this.identity.conversationId,customerId:this.identity.customerId,openingMessage:t,sessionId:this.identity.sessionId,userId:this.identity.userId,userMessage:s}});if(n){if(p(n.conversationId),n.type==="DEBUG")throw n;return n}}async trackEvent(t,s){let n={additionalProperties:s,conversationId:this.identity.conversationId||void 0,customerId:this.identity.customerId,deviceType:void 0,eventName:t,sessionId:this.identity.sessionId,url:window.location.href,userAgent:window.navigator.userAgent,userId:this.identity.userId||void 0};return this.endpoint.frontend.POST("/api/tracking/user/v1",{body:n})}};0&&(module.exports={CONVERSATION_ID,Client,SESSION_ID,TTL,USER_ID,deleteConversationId,getConversationId,getSessionId,getUserId,setConversationId,setSessionId,setUserId});
1
+ "use strict";var _=Object.create;var o=Object.defineProperty;var P=Object.getOwnPropertyDescriptor;var w=Object.getOwnPropertyNames;var T=Object.getPrototypeOf,O=Object.prototype.hasOwnProperty;var U=(e,t)=>{for(var s in t)o(e,s,{get:t[s],enumerable:!0})},S=(e,t,s,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of w(t))!O.call(e,i)&&i!==s&&o(e,i,{get:()=>t[i],enumerable:!(n=P(t,i))||n.enumerable});return e};var b=(e,t,s)=>(s=e!=null?_(T(e)):{},S(t||!e||!e.__esModule?o(s,"default",{value:e,enumerable:!0}):s,e)),k=e=>S(o({},"__esModule",{value:!0}),e);var R={};U(R,{CONVERSATION_ID:()=>r,Client:()=>x,SESSION_ID:()=>c,TTL:()=>E,USER_ID:()=>f,deleteConversationId:()=>d,getConversationId:()=>a,getSessionId:()=>I,getUserId:()=>v,setConversationId:()=>p,setSessionId:()=>m,setUserId:()=>y});module.exports=k(R);var h=b(require("openapi-fetch"));var r="__15gifts_conversation_id",d=()=>sessionStorage.removeItem(r),a=()=>sessionStorage.getItem(r),p=e=>sessionStorage.setItem(r,e);var c="__15gifts_session_id",I=()=>sessionStorage.getItem(c),m=e=>sessionStorage.setItem(c,e);var D=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},u=D;var M=(e,t,s)=>{let n={expires:Date.now()+s,value:t};localStorage.setItem(e,JSON.stringify(n))},g=M;var f="__15gifts_user_id",E=1e3*60*60*24*30,v=()=>u(f),y=e=>g(f,e,E);var C="0.3.1";var x=class{endpoint;identity;constructor({customerId:t,fetch:s,conversationUrl:n,frontendUrl:i}){let l={"X-SDK-VERSION":C};this.endpoint={conversation:(0,h.default)({baseUrl:n,fetch:s,headers:l}),frontend:(0,h.default)({baseUrl:i,fetch:s,headers:l})},this.identity={customerId:t,conversationId:a(),sessionId:I()??"",userId:v()}}async createIdentity(){let{conversationId:t,sessionId:s,userId:n}=this.identity;if(t&&this.endConversation(),!s||!n){let{data:i}=await this.endpoint.frontend.POST("/api/tracking/identity/v1",{body:{createSessionId:!s,createUserId:!n,customerId:this.identity.customerId}});i&&(!s&&i.sessionId&&(this.identity.sessionId=i.sessionId,m(i.sessionId)),!n&&i.userId&&(this.identity.userId=i.userId,y(i.userId)))}}endConversation(){d()}async sendMessage({openingMessage:t,userMessage:s}){t&&this.identity.conversationId&&this.endConversation();let{data:n}=await this.endpoint.conversation.POST("/api/conversation/v2",{body:{conversationId:this.identity.conversationId,customerId:this.identity.customerId,openingMessage:t,sessionId:this.identity.sessionId,userId:this.identity.userId,userMessage:s}});if(!n)return;let[i]=n;if(i?.conversationId&&p(i.conversationId),i?.type==="DEBUG")throw i;return n}async trackEvent(t,s){let n={additionalProperties:s,conversationId:this.identity.conversationId||void 0,customerId:this.identity.customerId,deviceType:void 0,eventName:t,sessionId:this.identity.sessionId,url:window.location.href,userAgent:window.navigator.userAgent,userId:this.identity.userId||void 0};return this.endpoint.frontend.POST("/api/tracking/user/v1",{body:n})}};0&&(module.exports={CONVERSATION_ID,Client,SESSION_ID,TTL,USER_ID,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","../package.json"],"sourcesContent":["export * from './client'\nexport * from './identity'\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 type { paths as conversationPaths } from './schemas/conversation'\nimport type { paths as frontendPaths } from './schemas/frontend'\nimport type { Config, ConversationApiRequest, DebugResponse, Endpoint, Identity, Message, TrackingEvent } 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-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(),\n sessionId: getSessionId() ?? '',\n userId: getUserId(),\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.\n *\n * @returns A promise that resolves once the identity is created.\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 { conversationId, sessionId, userId } = this.identity\n\n if (conversationId) this.endConversation()\n\n if (!sessionId || !userId) {\n const { data } = await this.endpoint.frontend.POST('/api/tracking/identity/v1', {\n body: {\n createSessionId: !sessionId,\n createUserId: !userId,\n customerId: this.identity.customerId,\n },\n })\n\n if (data) {\n if (!sessionId && data.sessionId) {\n this.identity.sessionId = data.sessionId\n setSessionId(data.sessionId)\n }\n if (!userId && data.userId) {\n this.identity.userId = data.userId\n setUserId(data.userId)\n }\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 }\n\n /**\n * Sends a message in the conversation, optionally with an opening message.\n *\n * @param options - An object containing the opening message and the user message.\n * @returns A promise that resolves to a message or a debug record.\n * If the message is a debug record, it will throw an error.\n *\n * @example\n * ```ts\n * const newMessage = await client.sendMessage({\n * openingMessage: 'Hello! How can I help you?',\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 openingMessage,\n userMessage,\n }: {\n openingMessage?: ConversationApiRequest['openingMessage']\n userMessage: ConversationApiRequest['userMessage']\n }): Promise<Message | undefined> {\n if (openingMessage && this.identity.conversationId) {\n this.endConversation()\n }\n\n const { data } = await this.endpoint.conversation.POST('/api/conversation/v2', {\n body: {\n conversationId: this.identity.conversationId,\n customerId: this.identity.customerId,\n openingMessage,\n sessionId: this.identity.sessionId,\n userId: this.identity.userId,\n userMessage,\n },\n })\n\n if (!data) return undefined\n\n setConversationId(data.conversationId)\n if (data.type === 'DEBUG') {\n throw data as DebugResponse\n }\n\n return data\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(\n eventName: TrackingEvent['eventName'],\n properties?: TrackingEvent['additionalProperties'],\n ): Promise<{ data?: undefined; error?: undefined; response: Response }> {\n const body: TrackingEvent = {\n additionalProperties: properties,\n conversationId: this.identity.conversationId || undefined,\n customerId: this.identity.customerId,\n deviceType: undefined,\n eventName,\n sessionId: this.identity.sessionId,\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n userId: this.identity.userId || undefined,\n }\n\n return this.endpoint.frontend.POST('/api/tracking/user/v1', {\n body,\n })\n }\n}\n","/**\n * The key used to store the conversation ID in `sessionStorage`.\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 */\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 */\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 */\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","{\n \"name\": \"@15gifts/sdk\",\n \"version\": \"0.3.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 \"dev\": \"tsup --watch\",\n \"format\": \"prettier . --write\",\n \"generate\": \"npx openapi-typescript\",\n \"lint\": \"eslint .\",\n \"test\": \"vitest run\",\n \"typecheck\": \"tsc\"\n },\n \"dependencies\": {\n \"openapi-fetch\": \"^0.12.0\"\n },\n \"devDependencies\": {\n \"openapi-typescript\": \"^7.4.0\",\n \"tsup\": \"^8.2.4\"\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,yBAAAC,EAAA,sBAAAC,EAAA,iBAAAC,EAAA,cAAAC,EAAA,sBAAAC,EAAA,iBAAAC,EAAA,cAAAC,IAAA,eAAAC,EAAAd,G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AAD,EACA,UAAW,KAAK,SAAS,UACzB,IAAK,OAAO,SAAS,KACrB,UAAW,OAAO,UAAU,UAC5B,OAAQ,KAAK,SAAS,QAAU,MAClC,EAEA,OAAO,KAAK,SAAS,SAAS,KAAK,wBAAyB,CAC1D,KAAAE,CACF,CAAC,CACH,CACF","names":["src_exports","__export","CONVERSATION_ID","Client","SESSION_ID","TTL","USER_ID","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","version","Client","customerId","fetch","conversationUrl","frontendUrl","headers","version","createClient","getConversationId","getSessionId","getUserId","conversationId","sessionId","userId","data","setSessionId","setUserId","deleteConversationId","openingMessage","userMessage","setConversationId","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","../package.json"],"sourcesContent":["export * from './client'\nexport * from './identity'\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 type { paths as conversationPaths } from './schemas/conversation'\nimport type { paths as frontendPaths } from './schemas/frontend'\nimport type { Config, ConversationApiRequest, Endpoint, Identity, Message, TrackingEvent } 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-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(),\n sessionId: getSessionId() ?? '',\n userId: getUserId(),\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.\n *\n * @returns A promise that resolves once the identity is created.\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 { conversationId, sessionId, userId } = this.identity\n\n if (conversationId) this.endConversation()\n\n if (!sessionId || !userId) {\n const { data } = await this.endpoint.frontend.POST('/api/tracking/identity/v1', {\n body: {\n createSessionId: !sessionId,\n createUserId: !userId,\n customerId: this.identity.customerId,\n },\n })\n\n if (data) {\n if (!sessionId && data.sessionId) {\n this.identity.sessionId = data.sessionId\n setSessionId(data.sessionId)\n }\n if (!userId && data.userId) {\n this.identity.userId = data.userId\n setUserId(data.userId)\n }\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 }\n\n /**\n * Sends a message in the conversation, optionally with an opening message.\n *\n * @param options - An object containing the opening message and the user message.\n * @returns A promise that resolves to an array of messages or debug records.\n * If the message is a debug record, it will throw an error.\n *\n * @example\n * ```ts\n * const newMessages = await client.sendMessage({\n * openingMessage: 'Hello! How can I help you?',\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 openingMessage,\n userMessage,\n }: {\n openingMessage?: ConversationApiRequest['openingMessage']\n userMessage: ConversationApiRequest['userMessage']\n }): Promise<Message[] | undefined> {\n if (openingMessage && this.identity.conversationId) {\n this.endConversation()\n }\n\n const { data } = await this.endpoint.conversation.POST('/api/conversation/v2', {\n body: {\n conversationId: this.identity.conversationId,\n customerId: this.identity.customerId,\n openingMessage,\n sessionId: this.identity.sessionId,\n userId: this.identity.userId,\n userMessage,\n },\n })\n\n if (!data) return undefined\n\n const [firstMessage] = data\n\n if (firstMessage?.conversationId) {\n setConversationId(firstMessage.conversationId)\n }\n\n if (firstMessage?.type === 'DEBUG') {\n throw firstMessage\n }\n\n // Based on the above check, we assume that the data is an array of messages and not debug records\n return data as Message[]\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(\n eventName: TrackingEvent['eventName'],\n properties?: TrackingEvent['additionalProperties'],\n ): Promise<{ data?: undefined; error?: undefined; response: Response }> {\n const body: TrackingEvent = {\n additionalProperties: properties,\n conversationId: this.identity.conversationId || undefined,\n customerId: this.identity.customerId,\n deviceType: undefined,\n eventName,\n sessionId: this.identity.sessionId,\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n userId: this.identity.userId || undefined,\n }\n\n return this.endpoint.frontend.POST('/api/tracking/user/v1', {\n body,\n })\n }\n}\n","/**\n * The key used to store the conversation ID in `sessionStorage`.\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 */\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 */\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 */\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","{\n \"name\": \"@15gifts/sdk\",\n \"version\": \"0.3.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 \"typecheck\": \"tsc\"\n },\n \"dependencies\": {\n \"openapi-fetch\": \"^0.12.0\"\n },\n \"devDependencies\": {\n \"openapi-typescript\": \"^7.4.0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,KAAK,SAAS,UACzB,OAAQ,KAAK,SAAS,OACtB,YAAAC,CACF,CACF,CAAC,EAED,GAAI,CAACL,EAAM,OAEX,GAAM,CAACM,CAAY,EAAIN,EAMvB,GAJIM,GAAc,gBAChBC,EAAkBD,EAAa,cAAc,EAG3CA,GAAc,OAAS,QACzB,MAAMA,EAIR,OAAON,CACT,CAcA,MAAM,WACJQ,EACAC,EACsE,CACtE,IAAMC,EAAsB,CAC1B,qBAAsBD,EACtB,eAAgB,KAAK,SAAS,gBAAkB,OAChD,WAAY,KAAK,SAAS,WAC1B,WAAY,OACZ,UAAAD,EACA,UAAW,KAAK,SAAS,UACzB,IAAK,OAAO,SAAS,KACrB,UAAW,OAAO,UAAU,UAC5B,OAAQ,KAAK,SAAS,QAAU,MAClC,EAEA,OAAO,KAAK,SAAS,SAAS,KAAK,wBAAyB,CAC1D,KAAAE,CACF,CAAC,CACH,CACF","names":["src_exports","__export","CONVERSATION_ID","Client","SESSION_ID","TTL","USER_ID","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","version","Client","customerId","fetch","conversationUrl","frontendUrl","headers","version","createClient","getConversationId","getSessionId","getUserId","conversationId","sessionId","userId","data","setSessionId","setUserId","deleteConversationId","openingMessage","userMessage","firstMessage","setConversationId","eventName","properties","body"]}
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import x from"openapi-fetch";var o="__15gifts_conversation_id",p=()=>sessionStorage.removeItem(o),c=()=>sessionStorage.getItem(o),I=n=>sessionStorage.setItem(o,n);var u="__15gifts_session_id",m=()=>sessionStorage.getItem(u),g=n=>sessionStorage.setItem(u,n);var S=n=>{let s=localStorage.getItem(n);if(!s)return null;let e=JSON.parse(s);return Date.now()>e.expires?(localStorage.removeItem(n),null):e.value},r=S;var E=(n,s,e)=>{let t={expires:Date.now()+e,value:s};localStorage.setItem(n,JSON.stringify(t))},d=E;var f="__15gifts_user_id",C=1e3*60*60*24*30,v=()=>r(f),y=n=>d(f,n,C);var h="0.3.0";var l=class{endpoint;identity;constructor({customerId:s,fetch:e,conversationUrl:t,frontendUrl:i}){let a={"X-SDK-VERSION":h};this.endpoint={conversation:x({baseUrl:t,fetch:e,headers:a}),frontend:x({baseUrl:i,fetch:e,headers:a})},this.identity={customerId:s,conversationId:c(),sessionId:m()??"",userId:v()}}async createIdentity(){let{conversationId:s,sessionId:e,userId:t}=this.identity;if(s&&this.endConversation(),!e||!t){let{data:i}=await this.endpoint.frontend.POST("/api/tracking/identity/v1",{body:{createSessionId:!e,createUserId:!t,customerId:this.identity.customerId}});i&&(!e&&i.sessionId&&(this.identity.sessionId=i.sessionId,g(i.sessionId)),!t&&i.userId&&(this.identity.userId=i.userId,y(i.userId)))}}endConversation(){p()}async sendMessage({openingMessage:s,userMessage:e}){s&&this.identity.conversationId&&this.endConversation();let{data:t}=await this.endpoint.conversation.POST("/api/conversation/v2",{body:{conversationId:this.identity.conversationId,customerId:this.identity.customerId,openingMessage:s,sessionId:this.identity.sessionId,userId:this.identity.userId,userMessage:e}});if(t){if(I(t.conversationId),t.type==="DEBUG")throw t;return t}}async trackEvent(s,e){let t={additionalProperties:e,conversationId:this.identity.conversationId||void 0,customerId:this.identity.customerId,deviceType:void 0,eventName:s,sessionId:this.identity.sessionId,url:window.location.href,userAgent:window.navigator.userAgent,userId:this.identity.userId||void 0};return this.endpoint.frontend.POST("/api/tracking/user/v1",{body:t})}};export{o as CONVERSATION_ID,l as Client,u as SESSION_ID,C as TTL,f as USER_ID,p as deleteConversationId,c as getConversationId,m as getSessionId,v as getUserId,I as setConversationId,g as setSessionId,y as setUserId};
1
+ import x from"openapi-fetch";var o="__15gifts_conversation_id",p=()=>sessionStorage.removeItem(o),c=()=>sessionStorage.getItem(o),I=n=>sessionStorage.setItem(o,n);var m="__15gifts_session_id",u=()=>sessionStorage.getItem(m),g=n=>sessionStorage.setItem(m,n);var S=n=>{let s=localStorage.getItem(n);if(!s)return null;let e=JSON.parse(s);return Date.now()>e.expires?(localStorage.removeItem(n),null):e.value},r=S;var E=(n,s,e)=>{let i={expires:Date.now()+e,value:s};localStorage.setItem(n,JSON.stringify(i))},d=E;var f="__15gifts_user_id",C=1e3*60*60*24*30,v=()=>r(f),y=n=>d(f,n,C);var h="0.3.1";var l=class{endpoint;identity;constructor({customerId:s,fetch:e,conversationUrl:i,frontendUrl:t}){let a={"X-SDK-VERSION":h};this.endpoint={conversation:x({baseUrl:i,fetch:e,headers:a}),frontend:x({baseUrl:t,fetch:e,headers:a})},this.identity={customerId:s,conversationId:c(),sessionId:u()??"",userId:v()}}async createIdentity(){let{conversationId:s,sessionId:e,userId:i}=this.identity;if(s&&this.endConversation(),!e||!i){let{data:t}=await this.endpoint.frontend.POST("/api/tracking/identity/v1",{body:{createSessionId:!e,createUserId:!i,customerId:this.identity.customerId}});t&&(!e&&t.sessionId&&(this.identity.sessionId=t.sessionId,g(t.sessionId)),!i&&t.userId&&(this.identity.userId=t.userId,y(t.userId)))}}endConversation(){p()}async sendMessage({openingMessage:s,userMessage:e}){s&&this.identity.conversationId&&this.endConversation();let{data:i}=await this.endpoint.conversation.POST("/api/conversation/v2",{body:{conversationId:this.identity.conversationId,customerId:this.identity.customerId,openingMessage:s,sessionId:this.identity.sessionId,userId:this.identity.userId,userMessage:e}});if(!i)return;let[t]=i;if(t?.conversationId&&I(t.conversationId),t?.type==="DEBUG")throw t;return i}async trackEvent(s,e){let i={additionalProperties:e,conversationId:this.identity.conversationId||void 0,customerId:this.identity.customerId,deviceType:void 0,eventName:s,sessionId:this.identity.sessionId,url:window.location.href,userAgent:window.navigator.userAgent,userId:this.identity.userId||void 0};return this.endpoint.frontend.POST("/api/tracking/user/v1",{body:i})}};export{o as CONVERSATION_ID,l as Client,m as SESSION_ID,C as TTL,f as USER_ID,p as deleteConversationId,c as getConversationId,u as getSessionId,v as getUserId,I as setConversationId,g as setSessionId,y 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","../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 type { paths as conversationPaths } from './schemas/conversation'\nimport type { paths as frontendPaths } from './schemas/frontend'\nimport type { Config, ConversationApiRequest, DebugResponse, Endpoint, Identity, Message, TrackingEvent } 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-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(),\n sessionId: getSessionId() ?? '',\n userId: getUserId(),\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.\n *\n * @returns A promise that resolves once the identity is created.\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 { conversationId, sessionId, userId } = this.identity\n\n if (conversationId) this.endConversation()\n\n if (!sessionId || !userId) {\n const { data } = await this.endpoint.frontend.POST('/api/tracking/identity/v1', {\n body: {\n createSessionId: !sessionId,\n createUserId: !userId,\n customerId: this.identity.customerId,\n },\n })\n\n if (data) {\n if (!sessionId && data.sessionId) {\n this.identity.sessionId = data.sessionId\n setSessionId(data.sessionId)\n }\n if (!userId && data.userId) {\n this.identity.userId = data.userId\n setUserId(data.userId)\n }\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 }\n\n /**\n * Sends a message in the conversation, optionally with an opening message.\n *\n * @param options - An object containing the opening message and the user message.\n * @returns A promise that resolves to a message or a debug record.\n * If the message is a debug record, it will throw an error.\n *\n * @example\n * ```ts\n * const newMessage = await client.sendMessage({\n * openingMessage: 'Hello! How can I help you?',\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 openingMessage,\n userMessage,\n }: {\n openingMessage?: ConversationApiRequest['openingMessage']\n userMessage: ConversationApiRequest['userMessage']\n }): Promise<Message | undefined> {\n if (openingMessage && this.identity.conversationId) {\n this.endConversation()\n }\n\n const { data } = await this.endpoint.conversation.POST('/api/conversation/v2', {\n body: {\n conversationId: this.identity.conversationId,\n customerId: this.identity.customerId,\n openingMessage,\n sessionId: this.identity.sessionId,\n userId: this.identity.userId,\n userMessage,\n },\n })\n\n if (!data) return undefined\n\n setConversationId(data.conversationId)\n if (data.type === 'DEBUG') {\n throw data as DebugResponse\n }\n\n return data\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(\n eventName: TrackingEvent['eventName'],\n properties?: TrackingEvent['additionalProperties'],\n ): Promise<{ data?: undefined; error?: undefined; response: Response }> {\n const body: TrackingEvent = {\n additionalProperties: properties,\n conversationId: this.identity.conversationId || undefined,\n customerId: this.identity.customerId,\n deviceType: undefined,\n eventName,\n sessionId: this.identity.sessionId,\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n userId: this.identity.userId || undefined,\n }\n\n return this.endpoint.frontend.POST('/api/tracking/user/v1', {\n body,\n })\n }\n}\n","/**\n * The key used to store the conversation ID in `sessionStorage`.\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 */\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 */\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 */\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","{\n \"name\": \"@15gifts/sdk\",\n \"version\": \"0.3.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 \"dev\": \"tsup --watch\",\n \"format\": \"prettier . --write\",\n \"generate\": \"npx openapi-typescript\",\n \"lint\": \"eslint .\",\n \"test\": \"vitest run\",\n \"typecheck\": \"tsc\"\n },\n \"dependencies\": {\n \"openapi-fetch\": \"^0.12.0\"\n },\n \"devDependencies\": {\n \"openapi-typescript\": \"^7.4.0\",\n \"tsup\": \"^8.2.4\"\n },\n \"sideEffects\": false,\n \"prettier\": \"prettier-config-custom\"\n}\n"],"mappings":"AAAA,OAAOA,MAAkB,gBCGlB,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,EClC/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,EA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GAEzB,CAACD,GAAUC,EAAK,SAClB,KAAK,SAAS,OAASA,EAAK,OAC5BE,EAAUF,EAAK,MAAM,GAG3B,CACF,CAWA,iBAAwB,CACtBG,EAAqB,CACvB,CAuBA,MAAM,YAAY,CAChB,eAAAC,EACA,YAAAC,CACF,EAGiC,CAC3BD,GAAkB,KAAK,SAAS,gBAClC,KAAK,gBAAgB,EAGvB,GAAM,CAAE,KAAAJ,CAAK,EAAI,MAAM,KAAK,SAAS,aAAa,KAAK,uBAAwB,CAC7E,KAAM,CACJ,eAAgB,KAAK,SAAS,eAC9B,WAAY,KAAK,SAAS,WAC1B,eAAAI,EACA,UAAW,KAAK,SAAS,UACzB,OAAQ,KAAK,SAAS,OACtB,YAAAC,CACF,CACF,CAAC,EAED,GAAKL,EAGL,IADAM,EAAkBN,EAAK,cAAc,EACjCA,EAAK,OAAS,QAChB,MAAMA,EAGR,OAAOA,EACT,CAcA,MAAM,WACJO,EACAC,EACsE,CACtE,IAAMC,EAAsB,CAC1B,qBAAsBD,EACtB,eAAgB,KAAK,SAAS,gBAAkB,OAChD,WAAY,KAAK,SAAS,WAC1B,WAAY,OACZ,UAAAD,EACA,UAAW,KAAK,SAAS,UACzB,IAAK,OAAO,SAAS,KACrB,UAAW,OAAO,UAAU,UAC5B,OAAQ,KAAK,SAAS,QAAU,MAClC,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","version","Client","customerId","fetch","conversationUrl","frontendUrl","headers","version","createClient","getConversationId","getSessionId","getUserId","conversationId","sessionId","userId","data","setSessionId","setUserId","deleteConversationId","openingMessage","userMessage","setConversationId","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","../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 type { paths as conversationPaths } from './schemas/conversation'\nimport type { paths as frontendPaths } from './schemas/frontend'\nimport type { Config, ConversationApiRequest, Endpoint, Identity, Message, TrackingEvent } 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-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(),\n sessionId: getSessionId() ?? '',\n userId: getUserId(),\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.\n *\n * @returns A promise that resolves once the identity is created.\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 { conversationId, sessionId, userId } = this.identity\n\n if (conversationId) this.endConversation()\n\n if (!sessionId || !userId) {\n const { data } = await this.endpoint.frontend.POST('/api/tracking/identity/v1', {\n body: {\n createSessionId: !sessionId,\n createUserId: !userId,\n customerId: this.identity.customerId,\n },\n })\n\n if (data) {\n if (!sessionId && data.sessionId) {\n this.identity.sessionId = data.sessionId\n setSessionId(data.sessionId)\n }\n if (!userId && data.userId) {\n this.identity.userId = data.userId\n setUserId(data.userId)\n }\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 }\n\n /**\n * Sends a message in the conversation, optionally with an opening message.\n *\n * @param options - An object containing the opening message and the user message.\n * @returns A promise that resolves to an array of messages or debug records.\n * If the message is a debug record, it will throw an error.\n *\n * @example\n * ```ts\n * const newMessages = await client.sendMessage({\n * openingMessage: 'Hello! How can I help you?',\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 openingMessage,\n userMessage,\n }: {\n openingMessage?: ConversationApiRequest['openingMessage']\n userMessage: ConversationApiRequest['userMessage']\n }): Promise<Message[] | undefined> {\n if (openingMessage && this.identity.conversationId) {\n this.endConversation()\n }\n\n const { data } = await this.endpoint.conversation.POST('/api/conversation/v2', {\n body: {\n conversationId: this.identity.conversationId,\n customerId: this.identity.customerId,\n openingMessage,\n sessionId: this.identity.sessionId,\n userId: this.identity.userId,\n userMessage,\n },\n })\n\n if (!data) return undefined\n\n const [firstMessage] = data\n\n if (firstMessage?.conversationId) {\n setConversationId(firstMessage.conversationId)\n }\n\n if (firstMessage?.type === 'DEBUG') {\n throw firstMessage\n }\n\n // Based on the above check, we assume that the data is an array of messages and not debug records\n return data as Message[]\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(\n eventName: TrackingEvent['eventName'],\n properties?: TrackingEvent['additionalProperties'],\n ): Promise<{ data?: undefined; error?: undefined; response: Response }> {\n const body: TrackingEvent = {\n additionalProperties: properties,\n conversationId: this.identity.conversationId || undefined,\n customerId: this.identity.customerId,\n deviceType: undefined,\n eventName,\n sessionId: this.identity.sessionId,\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n userId: this.identity.userId || undefined,\n }\n\n return this.endpoint.frontend.POST('/api/tracking/user/v1', {\n body,\n })\n }\n}\n","/**\n * The key used to store the conversation ID in `sessionStorage`.\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 */\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 */\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 */\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","{\n \"name\": \"@15gifts/sdk\",\n \"version\": \"0.3.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 \"typecheck\": \"tsc\"\n },\n \"dependencies\": {\n \"openapi-fetch\": \"^0.12.0\"\n },\n \"devDependencies\": {\n \"openapi-typescript\": \"^7.4.0\",\n \"tsup\": \"^8.2.4\"\n },\n \"sideEffects\": false,\n \"prettier\": \"prettier-config-custom\"\n}\n"],"mappings":"AAAA,OAAOA,MAAkB,gBCGlB,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,EClC/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,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AG3B,CACF,CAWA,iBAAwB,CACtBG,EAAqB,CACvB,CAuBA,MAAM,YAAY,CAChB,eAAAC,EACA,YAAAC,CACF,EAGmC,CAC7BD,GAAkB,KAAK,SAAS,gBAClC,KAAK,gBAAgB,EAGvB,GAAM,CAAE,KAAAJ,CAAK,EAAI,MAAM,KAAK,SAAS,aAAa,KAAK,uBAAwB,CAC7E,KAAM,CACJ,eAAgB,KAAK,SAAS,eAC9B,WAAY,KAAK,SAAS,WAC1B,eAAAI,EACA,UAAW,KAAK,SAAS,UACzB,OAAQ,KAAK,SAAS,OACtB,YAAAC,CACF,CACF,CAAC,EAED,GAAI,CAACL,EAAM,OAEX,GAAM,CAACM,CAAY,EAAIN,EAMvB,GAJIM,GAAc,gBAChBC,EAAkBD,EAAa,cAAc,EAG3CA,GAAc,OAAS,QACzB,MAAMA,EAIR,OAAON,CACT,CAcA,MAAM,WACJQ,EACAC,EACsE,CACtE,IAAMC,EAAsB,CAC1B,qBAAsBD,EACtB,eAAgB,KAAK,SAAS,gBAAkB,OAChD,WAAY,KAAK,SAAS,WAC1B,WAAY,OACZ,UAAAD,EACA,UAAW,KAAK,SAAS,UACzB,IAAK,OAAO,SAAS,KACrB,UAAW,OAAO,UAAU,UAC5B,OAAQ,KAAK,SAAS,QAAU,MAClC,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","version","Client","customerId","fetch","conversationUrl","frontendUrl","headers","version","createClient","getConversationId","getSessionId","getUserId","conversationId","sessionId","userId","data","setSessionId","setUserId","deleteConversationId","openingMessage","userMessage","firstMessage","setConversationId","eventName","properties","body"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@15gifts/sdk",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "files": [
5
5
  "dist"
6
6
  ],