@15gifts/sdk 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +36 -4
- package/dist/index.d.ts +36 -4
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -930,8 +930,11 @@ interface paths {
|
|
|
930
930
|
* "url": "https://www.example.com/telco/"
|
|
931
931
|
* } */
|
|
932
932
|
'application/json': {
|
|
933
|
-
/**
|
|
934
|
-
|
|
933
|
+
/**
|
|
934
|
+
* @description Event Name
|
|
935
|
+
* @enum {string}
|
|
936
|
+
*/
|
|
937
|
+
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';
|
|
935
938
|
/** @description Customer ID */
|
|
936
939
|
customerId: string;
|
|
937
940
|
/** @description User ID */
|
|
@@ -978,9 +981,19 @@ interface paths {
|
|
|
978
981
|
};
|
|
979
982
|
}
|
|
980
983
|
|
|
981
|
-
|
|
984
|
+
/**
|
|
985
|
+
* These are the types as defined in the OpenAPI schema.
|
|
986
|
+
* We don't use them directly, or export them here because of how they appear in the documentation site.
|
|
987
|
+
*/
|
|
988
|
+
type ApiConversationRequest = components['schemas']['ConversationRequest'];
|
|
982
989
|
type ApiMessage = components['schemas']['ConversationResponseMessageChunk'];
|
|
983
990
|
type ApiDebug = components['schemas']['ConversationResponseDebugChunk'];
|
|
991
|
+
type ApiTrackingEvent = paths['/api/tracking/user/v1']['post']['requestBody']['content']['application/json'];
|
|
992
|
+
/**
|
|
993
|
+
* The request to the conversation API.
|
|
994
|
+
*/
|
|
995
|
+
interface ConversationApiRequest extends ApiConversationRequest {
|
|
996
|
+
}
|
|
984
997
|
/**
|
|
985
998
|
* Configuration options for initializing the client.
|
|
986
999
|
*/
|
|
@@ -1068,6 +1081,8 @@ interface DebugResponse {
|
|
|
1068
1081
|
*/
|
|
1069
1082
|
type: ApiDebug['type'];
|
|
1070
1083
|
}
|
|
1084
|
+
interface TrackingEvent extends ApiTrackingEvent {
|
|
1085
|
+
}
|
|
1071
1086
|
|
|
1072
1087
|
/**
|
|
1073
1088
|
* The `Client` class provides methods to manage 15gifts API.
|
|
@@ -1145,6 +1160,23 @@ declare class Client {
|
|
|
1145
1160
|
openingMessage?: ConversationApiRequest['openingMessage'];
|
|
1146
1161
|
userMessage: ConversationApiRequest['userMessage'];
|
|
1147
1162
|
}): Promise<Message | undefined>;
|
|
1163
|
+
/**
|
|
1164
|
+
* Sends an event to the tracking API, with the required properties already set.
|
|
1165
|
+
*
|
|
1166
|
+
* @param eventName - The name of the event to track.
|
|
1167
|
+
* @param properties - Additional properties to include in the event.
|
|
1168
|
+
* @returns A promise that resolves once the event is tracked.
|
|
1169
|
+
*
|
|
1170
|
+
* @example
|
|
1171
|
+
* ```ts
|
|
1172
|
+
* await client.trackEvent('tab-shown')
|
|
1173
|
+
* ```
|
|
1174
|
+
*/
|
|
1175
|
+
trackEvent(eventName: TrackingEvent['eventName'], properties?: TrackingEvent['additionalProperties']): Promise<{
|
|
1176
|
+
data?: undefined;
|
|
1177
|
+
error?: undefined;
|
|
1178
|
+
response: Response;
|
|
1179
|
+
}>;
|
|
1148
1180
|
}
|
|
1149
1181
|
|
|
1150
1182
|
/**
|
|
@@ -1266,4 +1298,4 @@ declare const getUserId: () => string | null;
|
|
|
1266
1298
|
*/
|
|
1267
1299
|
declare const setUserId: (userId: string) => void;
|
|
1268
1300
|
|
|
1269
|
-
export { CONVERSATION_ID, Client, type Config, type ConversationApiRequest, type DebugResponse, type Endpoint, type Identity, type Message, SESSION_ID, TTL, USER_ID, deleteConversationId, getConversationId, getSessionId, getUserId, setConversationId, setSessionId, setUserId };
|
|
1301
|
+
export { CONVERSATION_ID, Client, type Config, type ConversationApiRequest, type DebugResponse, type Endpoint, type Identity, type Message, SESSION_ID, TTL, type TrackingEvent, USER_ID, deleteConversationId, getConversationId, getSessionId, getUserId, setConversationId, setSessionId, setUserId };
|
package/dist/index.d.ts
CHANGED
|
@@ -930,8 +930,11 @@ interface paths {
|
|
|
930
930
|
* "url": "https://www.example.com/telco/"
|
|
931
931
|
* } */
|
|
932
932
|
'application/json': {
|
|
933
|
-
/**
|
|
934
|
-
|
|
933
|
+
/**
|
|
934
|
+
* @description Event Name
|
|
935
|
+
* @enum {string}
|
|
936
|
+
*/
|
|
937
|
+
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';
|
|
935
938
|
/** @description Customer ID */
|
|
936
939
|
customerId: string;
|
|
937
940
|
/** @description User ID */
|
|
@@ -978,9 +981,19 @@ interface paths {
|
|
|
978
981
|
};
|
|
979
982
|
}
|
|
980
983
|
|
|
981
|
-
|
|
984
|
+
/**
|
|
985
|
+
* These are the types as defined in the OpenAPI schema.
|
|
986
|
+
* We don't use them directly, or export them here because of how they appear in the documentation site.
|
|
987
|
+
*/
|
|
988
|
+
type ApiConversationRequest = components['schemas']['ConversationRequest'];
|
|
982
989
|
type ApiMessage = components['schemas']['ConversationResponseMessageChunk'];
|
|
983
990
|
type ApiDebug = components['schemas']['ConversationResponseDebugChunk'];
|
|
991
|
+
type ApiTrackingEvent = paths['/api/tracking/user/v1']['post']['requestBody']['content']['application/json'];
|
|
992
|
+
/**
|
|
993
|
+
* The request to the conversation API.
|
|
994
|
+
*/
|
|
995
|
+
interface ConversationApiRequest extends ApiConversationRequest {
|
|
996
|
+
}
|
|
984
997
|
/**
|
|
985
998
|
* Configuration options for initializing the client.
|
|
986
999
|
*/
|
|
@@ -1068,6 +1081,8 @@ interface DebugResponse {
|
|
|
1068
1081
|
*/
|
|
1069
1082
|
type: ApiDebug['type'];
|
|
1070
1083
|
}
|
|
1084
|
+
interface TrackingEvent extends ApiTrackingEvent {
|
|
1085
|
+
}
|
|
1071
1086
|
|
|
1072
1087
|
/**
|
|
1073
1088
|
* The `Client` class provides methods to manage 15gifts API.
|
|
@@ -1145,6 +1160,23 @@ declare class Client {
|
|
|
1145
1160
|
openingMessage?: ConversationApiRequest['openingMessage'];
|
|
1146
1161
|
userMessage: ConversationApiRequest['userMessage'];
|
|
1147
1162
|
}): Promise<Message | undefined>;
|
|
1163
|
+
/**
|
|
1164
|
+
* Sends an event to the tracking API, with the required properties already set.
|
|
1165
|
+
*
|
|
1166
|
+
* @param eventName - The name of the event to track.
|
|
1167
|
+
* @param properties - Additional properties to include in the event.
|
|
1168
|
+
* @returns A promise that resolves once the event is tracked.
|
|
1169
|
+
*
|
|
1170
|
+
* @example
|
|
1171
|
+
* ```ts
|
|
1172
|
+
* await client.trackEvent('tab-shown')
|
|
1173
|
+
* ```
|
|
1174
|
+
*/
|
|
1175
|
+
trackEvent(eventName: TrackingEvent['eventName'], properties?: TrackingEvent['additionalProperties']): Promise<{
|
|
1176
|
+
data?: undefined;
|
|
1177
|
+
error?: undefined;
|
|
1178
|
+
response: Response;
|
|
1179
|
+
}>;
|
|
1148
1180
|
}
|
|
1149
1181
|
|
|
1150
1182
|
/**
|
|
@@ -1266,4 +1298,4 @@ declare const getUserId: () => string | null;
|
|
|
1266
1298
|
*/
|
|
1267
1299
|
declare const setUserId: (userId: string) => void;
|
|
1268
1300
|
|
|
1269
|
-
export { CONVERSATION_ID, Client, type Config, type ConversationApiRequest, type DebugResponse, type Endpoint, type Identity, type Message, SESSION_ID, TTL, USER_ID, deleteConversationId, getConversationId, getSessionId, getUserId, setConversationId, setSessionId, setUserId };
|
|
1301
|
+
export { CONVERSATION_ID, Client, type Config, type ConversationApiRequest, type DebugResponse, type Endpoint, type Identity, type Message, SESSION_ID, TTL, type TrackingEvent, USER_ID, deleteConversationId, getConversationId, getSessionId, getUserId, setConversationId, setSessionId, setUserId };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
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});
|
|
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 } 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 * 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.2.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,eAA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ACT,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"]}
|
|
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,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,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","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=
|
|
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};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -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 } 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 * 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.2.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,QAAQ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GAAM,CAAE,eAAAC,EAAgB,UAAAC,EAAW,OAAAC,CAAO,EAAI,KAAK,SAInD,GAFIF,GAAgB,KAAK,gBAAgB,EAErC,CAACC,GAAa,CAACC,EAAQ,CACzB,GAAM,CAAE,KAAAC,CAAK,EAAI,MAAM,KAAK,SAAS,SAAS,KAAK,4BAA6B,CAC9E,KAAM,CACJ,gBAAiB,CAACF,EAClB,aAAc,CAACC,EACf,WAAY,KAAK,SAAS,UAC5B,CACF,CAAC,EAEGC,IACE,CAACF,GAAaE,EAAK,YACrB,KAAK,SAAS,UAAYA,EAAK,UAC/BC,EAAaD,EAAK,SAAS,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,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"]}
|
|
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,EAAK,KACd,EAEOC,EAAQJ,EChBf,IAAMK,EAAoB,CAACC,EAAaC,EAAeC,IAAgB,CACrE,IAAMC,EAAO,CACX,QAAS,KAAK,IAAI,EAAID,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AqB,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"]}
|