@15gifts/sdk 0.16.0 → 0.16.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -2
- package/dist/index.d.mts +96 -611
- package/dist/index.d.ts +96 -611
- 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 +6 -5
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var V=Object.create;var c=Object.defineProperty;var N=Object.getOwnPropertyDescriptor;var b=Object.getOwnPropertyNames;var D=Object.getPrototypeOf,W=Object.prototype.hasOwnProperty;var j=(e,t)=>{for(var s in t)c(e,s,{get:t[s],enumerable:!0})},R=(e,t,s,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of b(t))!W.call(e,n)&&n!==s&&c(e,n,{get:()=>t[n],enumerable:!(o=N(t,n))||o.enumerable});return e};var q=(e,t,s)=>(s=e!=null?V(D(e)):{},R(t||!e||!e.__esModule?c(s,"default",{value:e,enumerable:!0}):s,e)),$=e=>R(c({},"__esModule",{value:!0}),e);var H={};j(H,{CONVERSATION_ID:()=>p,Client:()=>O,JWT_TOKEN:()=>m,SDKError:()=>i,SESSION_ID:()=>x,TTL:()=>U,USER_ID:()=>E,authMiddleware:()=>d,deleteConversationId:()=>u,errorMiddleware:()=>l,getConversationId:()=>v,getSessionId:()=>y,getToken:()=>A,getUserId:()=>C,headerMiddleware:()=>h,isTokenExpired:()=>_,setConversationId:()=>I,setSessionId:()=>M,setToken:()=>T,setUserId:()=>g});module.exports=$(H);var P=q(require("openapi-fetch"));var p="__15gifts_conversation_id",u=()=>sessionStorage.removeItem(p),v=()=>sessionStorage.getItem(p),I=e=>sessionStorage.setItem(p,e);var x="__15gifts_session_id",y=()=>sessionStorage.getItem(x),M=e=>sessionStorage.setItem(x,e);var B=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},w=B;var F=(e,t,s)=>{let o={expires:Date.now()+s,value:t};localStorage.setItem(e,JSON.stringify(o))},S=F;var J=1e3*60*60*24,E="__15gifts_user_id",U=J*30,C=()=>{let e=w(E);return e&&g(e),e},g=e=>S(E,e,U);var m="__15gifts_identity_token",_=e=>{try{let[,t]=e.split(".");if(!t)throw new Error("Invalid token payload");let s=JSON.parse(atob(t));return s.exp&&Date.now()/1e3>s.exp}catch(t){return console.error("Invalid token format",t),!0}},A=()=>{let e=localStorage.getItem(m);return!e||_(e)?(localStorage.removeItem(m),null):e},T=e=>localStorage.setItem(m,e);var K=e=>({onRequest:async({request:t})=>{if(t.url.includes("/identity/"))return t;if(!e)throw new Error("Access token is required for authentication.");return t.headers.set("Authorization",`Bearer ${e}`),t}}),d=K;var X={onResponse:async({response:e})=>{if(!e.ok){let t=await e.json();throw new Error(t.message)}return e}},l=X;var z=(e,t)=>({onRequest:async({request:s})=>(e.pageviewId&&s.headers.set("X-PAGEVIEW-ID",e.pageviewId),t&&s.headers.set("X-PAGE-URL",t),s)}),h=z;var f="0.16.
|
|
1
|
+
"use strict";var V=Object.create;var c=Object.defineProperty;var N=Object.getOwnPropertyDescriptor;var b=Object.getOwnPropertyNames;var D=Object.getPrototypeOf,W=Object.prototype.hasOwnProperty;var j=(e,t)=>{for(var s in t)c(e,s,{get:t[s],enumerable:!0})},R=(e,t,s,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of b(t))!W.call(e,n)&&n!==s&&c(e,n,{get:()=>t[n],enumerable:!(o=N(t,n))||o.enumerable});return e};var q=(e,t,s)=>(s=e!=null?V(D(e)):{},R(t||!e||!e.__esModule?c(s,"default",{value:e,enumerable:!0}):s,e)),$=e=>R(c({},"__esModule",{value:!0}),e);var H={};j(H,{CONVERSATION_ID:()=>p,Client:()=>O,JWT_TOKEN:()=>m,SDKError:()=>i,SESSION_ID:()=>x,TTL:()=>U,USER_ID:()=>E,authMiddleware:()=>d,deleteConversationId:()=>u,errorMiddleware:()=>l,getConversationId:()=>v,getSessionId:()=>y,getToken:()=>A,getUserId:()=>C,headerMiddleware:()=>h,isTokenExpired:()=>_,setConversationId:()=>I,setSessionId:()=>M,setToken:()=>T,setUserId:()=>g});module.exports=$(H);var P=q(require("openapi-fetch"));var p="__15gifts_conversation_id",u=()=>sessionStorage.removeItem(p),v=()=>sessionStorage.getItem(p),I=e=>sessionStorage.setItem(p,e);var x="__15gifts_session_id",y=()=>sessionStorage.getItem(x),M=e=>sessionStorage.setItem(x,e);var B=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},w=B;var F=(e,t,s)=>{let o={expires:Date.now()+s,value:t};localStorage.setItem(e,JSON.stringify(o))},S=F;var J=1e3*60*60*24,E="__15gifts_user_id",U=J*30,C=()=>{let e=w(E);return e&&g(e),e},g=e=>S(E,e,U);var m="__15gifts_identity_token",_=e=>{try{let[,t]=e.split(".");if(!t)throw new Error("Invalid token payload");let s=JSON.parse(atob(t));return s.exp&&Date.now()/1e3>s.exp}catch(t){return console.error("Invalid token format",t),!0}},A=()=>{let e=localStorage.getItem(m);return!e||_(e)?(localStorage.removeItem(m),null):e},T=e=>localStorage.setItem(m,e);var K=e=>({onRequest:async({request:t})=>{if(t.url.includes("/identity/"))return t;if(!e)throw new Error("Access token is required for authentication.");return t.headers.set("Authorization",`Bearer ${e}`),t}}),d=K;var X={onResponse:async({response:e})=>{if(!e.ok){let t=await e.json();throw new Error(t.message)}return e}},l=X;var z=(e,t)=>({onRequest:async({request:s})=>(e.pageviewId&&s.headers.set("X-PAGEVIEW-ID",e.pageviewId),t&&s.headers.set("X-PAGE-URL",t),s)}),h=z;var f="0.16.2";var i=class e extends Error{sdkVersion;cause;constructor(t,{cause:s}={}){super(t),this.name="SDKError",this.cause=s,this.sdkVersion=f,Object.setPrototypeOf(this,e.prototype)}};var O=class{endpoint;identity;constructor(t){let{conversationUrl:s,customerId:o,fetch:n,frontendUrl:r,headers:a}=t,k={...a,"X-SDK-VERSION":f};this.endpoint={conversation:(0,P.default)({baseUrl:s,fetch:n,headers:k,credentials:"include"}),frontend:(0,P.default)({baseUrl:r,fetch:n,headers:k})},this.identity={customerId:o,conversationId:v()??void 0,sessionId:y()??void 0,userId:C()??void 0},this.endpoint.conversation.use(l),this.endpoint.conversation.use(h(this.identity,window.location.href))}async createIdentity(){let{customerId:t,sessionId:s,userId:o}=this.identity;try{let{data:n}=await this.endpoint.frontend.POST("/api/tracking/identity/v2",{body:{customerId:t,sessionId:s,userId:o,url:window.location.href,userAgent:window.navigator.userAgent}});if(!n)throw new i("No data received from identity API");this.identity.pageviewId=n.pageviewId,s||(this.identity.sessionId=n.sessionId,M(n.sessionId)),o||(this.identity.userId=n.userId,g(n.userId)),T(n.token),Object.values(this.endpoint).forEach(r=>{r.use(d(n.token))})}catch(n){throw Object.values(this.endpoint).forEach(r=>{r.use(d())}),new i("Failed to create identity",{cause:n})}}endConversation(){u(),this.identity.conversationId=void 0}async startConversation(t){this.endConversation();let s={...t},{data:o}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{type:"START_CONVERSATION",conversationContext:s}});if(!o)throw new i("No data received from Conversation API");let[n,...r]=o,a=n.conversationId;if(!a)throw new i("Conversation ID not received in API response");return I(a),this.identity.conversationId=a,r}async sendMessage(t){let s=this.identity.conversationId;if(!s)throw new i("Conversation ID not set");let{data:o}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{conversationId:s,...t}});if(!o)throw new i("No data received from conversation API");return o.filter(n=>n.type!=="CONVERSATION_ID")}async trackEvent(t,s){let o={additionalProperties:s,conversationId:this.identity.conversationId,eventName:t,pageviewId:this.identity.pageviewId??"unknown",screenWidth:window.screen.width,screenHeight:window.screen.height,screenSize:window.screen.width<=480?"mobile":"large",url:window.location.href,userAgent:window.navigator.userAgent};return this.endpoint.frontend.POST("/api/tracking/user/v2",{body:o})}getIdentity(){return this.identity}getIdentityToken(){return A()}};0&&(module.exports={CONVERSATION_ID,Client,JWT_TOKEN,SDKError,SESSION_ID,TTL,USER_ID,authMiddleware,deleteConversationId,errorMiddleware,getConversationId,getSessionId,getToken,getUserId,headerMiddleware,isTokenExpired,setConversationId,setSessionId,setToken,setUserId});
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/client.ts","../src/identity/conversationId.ts","../src/identity/sessionId.ts","../src/utils/getItemWithExpiry.ts","../src/utils/setItemWithExpiry.ts","../src/identity/userId.ts","../src/identity/token.ts","../src/middlewares/auth.ts","../src/middlewares/error.ts","../src/middlewares/headers.ts","../package.json","../src/utils/SDKError.ts"],"sourcesContent":["export * from './client'\nexport * from './identity'\nexport * from './middlewares'\nexport * from './types'\n","import createClient, { type ClientOptions } from 'openapi-fetch'\n\nimport {\n deleteConversationId,\n getConversationId,\n getSessionId,\n getUserId,\n getToken,\n setConversationId,\n setSessionId,\n setUserId,\n setToken,\n} from './identity'\nimport { authMiddleware, errorMiddleware, headerMiddleware } from './middlewares'\nimport type { components, paths as conversationPaths } from './schemas/conversation'\nimport type { paths as frontendPaths } from './schemas/frontend'\nimport type {\n Config,\n ConversationIdMessage,\n Endpoint,\n Identity,\n Message,\n SendMessagePayload,\n TrackingEvent,\n} from './types'\nimport { version } from '../package.json'\nimport SDKError from './utils/SDKError'\n\n/**\n * The `Client` class provides methods to manage 15gifts API.\n */\nexport class Client {\n /**\n * This can be used to interact with the APIs directly. It is recommended to use the [helper methods](/sdk/sdk-reference/classes/client/#methods) provided by the `Client` class instead.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * const { data } = await client.endpoint.conversation.POST('/api/conversation/v3')\n * ```\n */\n endpoint: Endpoint\n\n /**\n * The identity information.\n */\n identity: Identity\n\n /**\n * Creates a new instance of the `Client` class.\n *\n * @param config - Configuration options for initializing the client.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * ```\n */\n constructor(config: Config) {\n const { conversationUrl, customerId, fetch, frontendUrl, headers: defaultHeaders } = config\n\n const headers: ClientOptions['headers'] = {\n ...defaultHeaders,\n 'X-SDK-VERSION': version,\n }\n\n this.endpoint = {\n conversation: createClient<conversationPaths>({\n baseUrl: conversationUrl,\n fetch,\n headers,\n credentials: 'include',\n }),\n frontend: createClient<frontendPaths>({ baseUrl: frontendUrl, fetch, headers }),\n }\n\n this.identity = {\n customerId,\n conversationId: getConversationId() ?? undefined,\n sessionId: getSessionId() ?? undefined,\n userId: getUserId() ?? undefined,\n }\n\n this.endpoint.conversation.use(errorMiddleware)\n this.endpoint.conversation.use(headerMiddleware(this.identity, window.location.href))\n }\n\n /**\n * Creates a new identity for the user by generating a session ID and user ID if they don't exist, and sets the access token for future API calls.\n * Ends the current conversation if a conversation ID is present before sending a request to update identity.\n * This should not be called more than once per page load.\n *\n * @returns A promise that resolves once the identity is created and the access token is set.\n *\n * @example\n * ```ts\n * await client.createIdentity()\n * console.log('Identity created:', client.identity)\n * ```\n */\n async createIdentity(): Promise<void> {\n const { customerId, sessionId, userId } = this.identity\n\n try {\n const { data } = await this.endpoint.frontend.POST('/api/tracking/identity/v2', {\n body: {\n customerId,\n sessionId,\n userId,\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n },\n })\n\n if (!data) {\n throw new SDKError('No data received from identity API')\n }\n\n this.identity.pageviewId = data.pageviewId\n\n if (!sessionId) {\n this.identity.sessionId = data.sessionId\n setSessionId(data.sessionId)\n }\n if (!userId) {\n this.identity.userId = data.userId\n setUserId(data.userId)\n }\n\n setToken(data.token)\n\n // Add the access token to the Authorization header for all endpoints\n Object.values(this.endpoint).forEach((endpoint) => {\n endpoint.use(authMiddleware(data.token))\n })\n } catch (error) {\n // Enable the auth middleware without a token so that it will throw an error before sending\n // the next request, preventing unnecessary API calls / 401 responses.\n Object.values(this.endpoint).forEach((endpoint) => {\n endpoint.use(authMiddleware())\n })\n throw new SDKError('Failed to create identity', {\n cause: error as Error,\n })\n }\n }\n\n /**\n * Ends the current conversation by deleting the conversation ID.\n *\n * @example\n * ```ts\n * client.endConversation()\n * console.log('Conversation ended')\n * ```\n */\n endConversation(): void {\n deleteConversationId()\n this.identity.conversationId = undefined\n }\n\n /**\n * Clears the existing conversation ID, then generates a new one and returns the opening message.\n *\n * @param context - Optional context to customize the conversation. It can include:\n * @param context.eligibleProducts An array of eligible product IDs.\n * @param context.eligibleBundles An array of eligible bundle IDs.\n * @param context.productOverrides Overrides for product details.\n * @param context.bundleOverrides Overrides for bundle details.\n *\n * @returns A promise that resolves to the opening message.\n *\n * @example\n * ##### Basic usage\n * ```ts\n * const openingMessage = await client.startConversation()\n * console.log('Opening message:', openingMessage)\n * ```\n *\n * ##### With context\n * ```ts\n * const openingMessage = await client.startConversation({ eligibleProducts: ['product-1', 'product-2'], productOverrides: { 'product-1': { price: 40 } })\n * console.log('Opening message:', openingMessage)\n * ```\n */\n async startConversation(context?: components['schemas']['ConversationContext']): Promise<Message[]> {\n this.endConversation()\n\n const conversationContext = {\n ...context,\n }\n\n const { data } = await this.endpoint.conversation.POST(`/api/conversation/v3`, {\n body: {\n type: 'START_CONVERSATION',\n conversationContext,\n },\n })\n\n if (!data) throw new SDKError('No data received from Conversation API')\n\n const [conversationIdMessage, ...rest] = data as [ConversationIdMessage, ...Message[]]\n\n const conversationId = conversationIdMessage.conversationId\n if (!conversationId) {\n throw new SDKError('Conversation ID not received in API response')\n }\n\n setConversationId(conversationId)\n this.identity.conversationId = conversationId\n\n return rest\n }\n\n /**\n * Sends a message in the conversation.\n *\n * @param options - An object containing the user message.\n * @returns A promise that resolves to an array of messages\n *\n * @example\n * ```ts\n * const newMessages = await client.sendMessage({\n * userMessage: 'How can I get support?',\n * })\n *\n * if (newMessages) {\n * console.log('Received messages:', newMessages)\n * } else {\n * console.log('No message received')\n * }\n * ```\n */\n async sendMessage(payload: SendMessagePayload) {\n const conversationId = this.identity.conversationId\n if (!conversationId) {\n throw new SDKError('Conversation ID not set')\n }\n\n const { data } = await this.endpoint.conversation.POST('/api/conversation/v3', {\n body: {\n conversationId,\n ...payload,\n },\n })\n\n if (!data) throw new SDKError('No data received from conversation API')\n\n // Removes any `CONVERSATION_ID` messages from the API response. In reality, these messages will only\n // appear in the response to a `START_CONVERSATION` request.\n return data.filter((message) => message.type !== 'CONVERSATION_ID')\n }\n\n /**\n * Sends an event to the tracking API, with the required properties already set.\n *\n * @param eventName - The name of the event to track.\n * @param properties - Additional properties to include in the event.\n * @returns A promise that resolves once the event is tracked.\n *\n * @example\n * ```ts\n * await client.trackEvent('entry_point-shown')\n * ```\n */\n async trackEvent(eventName: TrackingEvent['eventName'], properties?: TrackingEvent['additionalProperties']) {\n const body: TrackingEvent = {\n additionalProperties: properties,\n conversationId: this.identity.conversationId,\n eventName,\n pageviewId: this.identity.pageviewId ?? 'unknown',\n screenWidth: window.screen.width,\n screenHeight: window.screen.height,\n screenSize: window.screen.width <= 480 ? 'mobile' : 'large',\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n }\n\n return this.endpoint.frontend.POST('/api/tracking/user/v2', {\n body,\n })\n }\n\n /**\n * Gets an existing identity of the user.\n *\n * @returns An Identity object containing `customerId`, `conversationId`, `sessionId`, `userId`.\n *\n * @example\n * ```ts\n * identity = client.getIdentity()\n * console.log('Identity retrieved:', identity)\n * ```\n */\n getIdentity(): Identity {\n return this.identity\n }\n\n /**\n * Gets the JWT from the localStorage.\n *\n * @returns {string | null} the JWT.\n *\n * @example\n * ```ts\n * token = client.getIdentityToken()\n * console.log('Identity token retrieved:', token)\n * ```\n */\n getIdentityToken(): string | null {\n return getToken()\n }\n}\n","/**\n * The key used to store the conversation ID in `sessionStorage`.\n *\n * @ignore\n */\nexport const CONVERSATION_ID = '__15gifts_conversation_id'\n\n/**\n * Deletes the conversation ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { deleteConversationId } from '@15gifts/sdk'\n *\n * deleteConversationId()\n * // The conversation ID will be removed.\n * ```\n */\nexport const deleteConversationId = () => sessionStorage.removeItem(CONVERSATION_ID)\n\n/**\n * Retrieves the conversation ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { getConversationId } from '@15gifts/sdk'\n *\n * const conversationId = getConversationId()\n *\n * if (conversationId) {\n * console.log(`Conversation ID: ${conversationId}`)\n * } else {\n * console.log('No conversation ID found.')\n * }\n * ```\n */\nexport const getConversationId = () => sessionStorage.getItem(CONVERSATION_ID)\n\n/**\n * Stores the given conversation ID in `sessionStorage`.\n *\n * @example\n * ```ts\n * import { setConversationId } from '@15gifts/sdk'\n *\n * setConversationId('ca0ab4ce-f697-41cc-8d0c-081762aace9b')\n * // The conversation ID 'ca0ab4ce-f697-41cc-8d0c-081762aace9b' will be stored.\n * ```\n */\nexport const setConversationId = (conversationId: string) => sessionStorage.setItem(CONVERSATION_ID, conversationId)\n","/**\n * The key used to store the session ID in `sessionStorage`.\n *\n * @ignore\n */\nexport const SESSION_ID = '__15gifts_session_id'\n\n/**\n * Retrieves the session ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { getSessionId } from '@15gifts/sdk'\n *\n * const sessionId = getSessionId()\n *\n * if (sessionId) {\n * console.log(`Session ID: ${sessionId}`)\n * } else {\n * console.log('No session ID found.')\n * }\n * ```\n */\nexport const getSessionId = () => sessionStorage.getItem(SESSION_ID)\n\n/**\n * Stores the given session ID in `sessionStorage`.\n *\n * @example\n * ```ts\n * import { setSessionId } from '@15gifts/sdk'\n *\n * setSessionId('20b2bff6-64a0-4101-bed9-ff545326584a')\n * // The session ID '20b2bff6-64a0-4101-bed9-ff545326584a' will be stored.\n * ```\n */\nexport const setSessionId = (sessionId: string) => sessionStorage.setItem(SESSION_ID, sessionId)\n","const getItemWithExpiry = (key: string) => {\n const itemString = localStorage.getItem(key)\n\n if (!itemString) return null\n\n const item = JSON.parse(itemString) as { expires: number; value: string }\n\n if (Date.now() > item.expires) {\n localStorage.removeItem(key)\n\n return null\n }\n\n return item.value\n}\n\nexport default getItemWithExpiry\n","/**\n * Set an item in localStorage with an expiration time\n * @param key The key under which the value is stored in localStorage\n * @param value The value to be stored\n * @param ttl The time-to-live (TTL) in milliseconds\n */\nconst setItemWithExpiry = (key: string, value: string, ttl: number) => {\n const item = {\n expires: Date.now() + ttl,\n value,\n }\n\n localStorage.setItem(key, JSON.stringify(item))\n}\n\nexport default setItemWithExpiry\n","import { getItemWithExpiry, setItemWithExpiry } from '../utils'\nconst day = 1000 * 60 * 60 * 24\n\n/**\n * The key used to store the user ID in `localStorage`.\n *\n * @ignore\n */\nexport const USER_ID = '__15gifts_user_id'\n\n/**\n * Time-to-live (TTL) for the user ID in milliseconds.\n * Set to 30 days.\n *\n * @ignore\n */\nexport const TTL = day * 30\n\n/**\n * Retrieves the user ID from `localStorage` and updates its expiry time.\n *\n * @example\n * ```ts\n * import { getUserId } from '@15gifts/sdk'\n *\n * const userId = getUserId()\n *\n * if (userId) {\n * console.log(`User ID: ${userId}`)\n * } else {\n * console.log('No user ID found.')\n * }\n * ```\n */\nexport const getUserId = () => {\n const userId = getItemWithExpiry(USER_ID)\n\n // Update the userId with a new expiry time\n // So that it will be valid for another 30 days, rather than 30 days from when it was first set\n if (userId) {\n setUserId(userId)\n }\n\n return userId\n}\n\n/**\n * Stores the given user ID in `localStorage`.\n *\n * @example\n * ```ts\n * import { setUserId } from '@15gifts/sdk'\n *\n * setUserId('5b77656c-ea4c-492f-82bf-7129297c5873')\n * // The user ID '5b77656c-ea4c-492f-82bf-7129297c5873' will be stored with a 30-day expiry.\n * ```\n */\nexport const setUserId = (userId: string) => setItemWithExpiry(USER_ID, userId, TTL)\n","/**\n * The key used to store the JWT in `localStorage`.\n *\n * @ignore\n */\nexport const JWT_TOKEN = '__15gifts_identity_token'\n\n/**\n * Checks if the JWT is expired.\n *\n * @param {string} token - the JWT.\n * @returns {boolean} `true` if expired, `false` otherwise.\n */\nexport const isTokenExpired = (token: string): boolean => {\n try {\n const [, payloadBase64] = token.split('.')\n if (!payloadBase64) {\n throw new Error('Invalid token payload')\n }\n const payload = JSON.parse(atob(payloadBase64))\n\n return payload.exp && Date.now() / 1000 > payload.exp\n } catch (error) {\n console.error('Invalid token format', error)\n return true\n }\n}\n\n/**\n * Retrieves the JWT from `localStorage` and checks if it is expired.\n *\n * @returns {string | null} The JWT if valid, otherwise `null`.\n */\nexport const getToken = (): string | null => {\n const token = localStorage.getItem(JWT_TOKEN)\n\n if (!token || isTokenExpired(token)) {\n localStorage.removeItem(JWT_TOKEN)\n return null\n }\n\n return token\n}\n\n/**\n * Stores the given JWT in `localStorage`.\n *\n * @example\n * ```ts\n * import { setToken } from '@15gifts/sdk'\n *\n * setToken('ey...')\n * ```\n */\nexport const setToken = (token: string) => localStorage.setItem(JWT_TOKEN, token)\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for adding an `Authorization` header to requests.\n *\n * @param accessToken - The token to be included in the `Authorization` header.\n * @returns A middleware object that attaches the access token to the request headers.\n *\n * @example\n * ```ts\n * import { authMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(authMiddleware(accessToken))\n * ```\n */\nconst authMiddleware = (accessToken?: string): Middleware => ({\n onRequest: async ({ request }) => {\n const isIdentityEndpoint = request.url.includes('/identity/')\n if (isIdentityEndpoint) {\n return request\n }\n\n // Throw an error because we know the API will return a 401 if the access token is not set.\n if (!accessToken) {\n throw new Error('Access token is required for authentication.')\n }\n\n request.headers.set('Authorization', `Bearer ${accessToken}`)\n\n return request\n },\n})\n\nexport default authMiddleware\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for handling errors.\n *\n * @returns A middleware object that throws an error if the response is not ok.\n *\n * @example\n * ```ts\n * import { errorMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(errorMiddleware())\n * ```\n */\nconst errorMiddleware: Middleware = {\n // onError does not handle error responses with 4xx or 5xx HTTP status codes, since these are considered \"successful\" responses but with a bad status code.\n // In these cases we need to check the response's status property or ok() method via the onResponse callback.\n onResponse: async ({ response }) => {\n if (!response.ok) {\n const data = await response.json()\n\n throw new Error(data.message)\n }\n\n return response\n },\n}\n\nexport default errorMiddleware\n","import type { Middleware } from 'openapi-fetch'\n\nimport { Identity } from '../types'\n\n/**\n * Middleware for adding request headers that other services use for tracking.\n *\n * @returns A middleware object that throws an error if the response is not ok.\n *\n * @example\n * ```ts\n * import { pageViewId } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(headerMiddleware('123', 'https://example.com'))\n * ```\n */\nconst headerMiddleware = (identity: Identity, url: string): Middleware => ({\n onRequest: async ({ request }) => {\n if (identity.pageviewId) {\n request.headers.set('X-PAGEVIEW-ID', identity.pageviewId)\n }\n if (url) {\n request.headers.set('X-PAGE-URL', url)\n }\n\n return request\n },\n})\n\nexport default headerMiddleware\n","{\n \"name\": \"@15gifts/sdk\",\n \"version\": \"0.16.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\": \"npm run generate && tsup\",\n \"coverage\": \"vitest run --coverage\",\n \"dev\": \"tsup --watch\",\n \"format\": \"prettier . --write\",\n \"generate\": \"npx openapi-typescript\",\n \"lint\": \"eslint .\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"typecheck\": \"tsc\"\n },\n \"dependencies\": {\n \"openapi-fetch\": \"^0.13.4\"\n },\n \"devDependencies\": {\n \"openapi-typescript\": \"^7.6.0\",\n \"tsup\": \"^8.3.6\"\n },\n \"sideEffects\": false,\n \"prettier\": \"prettier-config-custom\"\n}\n","import { version } from '../../package.json'\n\n/**\n * Custom error class for SDK-related errors.\n * Includes the SDK version and an optional cause for better debugging.\n * NOTE: The error.message is intended for developers, not end-users.\n */\nexport default class SDKError extends Error {\n sdkVersion: string\n override cause?: Error\n\n constructor(userMessage: string, { cause }: { cause?: Error } = {}) {\n super(userMessage)\n this.name = 'SDKError'\n this.cause = cause\n this.sdkVersion = version\n\n // Set the prototype explicitly to maintain instanceof checks\n Object.setPrototypeOf(this, SDKError.prototype)\n }\n}\n"],"mappings":"0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,EAAA,WAAAC,EAAA,cAAAC,EAAA,aAAAC,EAAA,eAAAC,EAAA,QAAAC,EAAA,YAAAC,EAAA,mBAAAC,EAAA,yBAAAC,EAAA,oBAAAC,EAAA,sBAAAC,EAAA,iBAAAC,EAAA,aAAAC,EAAA,cAAAC,EAAA,qBAAAC,EAAA,mBAAAC,EAAA,sBAAAC,EAAA,iBAAAC,EAAA,aAAAC,EAAA,cAAAC,IAAA,eAAAC,EAAAtB,GCAA,IAAAuB,EAAiD,4BCK1C,IAAMC,EAAkB,4BAalBC,EAAuB,IAAM,eAAe,WAAWD,CAAe,EAkBtEE,EAAoB,IAAM,eAAe,QAAQF,CAAe,EAahEG,EAAqBC,GAA2B,eAAe,QAAQJ,EAAiBI,CAAc,EC5C5G,IAAMC,EAAa,uBAkBbC,EAAe,IAAM,eAAe,QAAQD,CAAU,EAatDE,EAAgBC,GAAsB,eAAe,QAAQH,EAAYG,CAAS,ECpC/F,IAAMC,EAAqBC,GAAgB,CACzC,IAAMC,EAAa,aAAa,QAAQD,CAAG,EAE3C,GAAI,CAACC,EAAY,OAAO,KAExB,IAAMC,EAAO,KAAK,MAAMD,CAAU,EAElC,OAAI,KAAK,IAAI,EAAIC,EAAK,SACpB,aAAa,WAAWF,CAAG,EAEpB,MAGFE,EAAK,KACd,EAEOC,EAAQJ,ECVf,IAAMK,EAAoB,CAACC,EAAaC,EAAeC,IAAgB,CACrE,IAAMC,EAAO,CACX,QAAS,KAAK,IAAI,EAAID,EACtB,MAAAD,CACF,EAEA,aAAa,QAAQD,EAAK,KAAK,UAAUG,CAAI,CAAC,CAChD,EAEOC,EAAQL,ECdf,IAAMM,EAAM,IAAO,GAAK,GAAK,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iB,KAAK,SAAS,eACrC,GAAI,CAACA,EACH,MAAM,IAAIZ,EAAS,yBAAyB,EAG9C,GAAM,CAAE,KAAAD,CAAK,EAAI,MAAM,KAAK,SAAS,aAAa,KAAK,uBAAwB,CAC7E,KAAM,CACJ,eAAAa,EACA,GAAGE,CACL,CACF,CAAC,EAED,GAAI,CAACf,EAAM,MAAM,IAAIC,EAAS,wCAAwC,EAItE,OAAOD,EAAK,OAAQgB,GAAYA,EAAQ,OAAS,iBAAiB,CACpE,CAcA,MAAM,WAAWC,EAAuCC,EAAoD,CAC1G,IAAMC,EAAsB,CAC1B,qBAAsBD,EACtB,eAAgB,KAAK,SAAS,eAC9B,UAAAD,EACA,WAAY,KAAK,SAAS,YAAc,UACxC,YAAa,OAAO,OAAO,MAC3B,aAAc,OAAO,OAAO,OAC5B,WAAY,OAAO,OAAO,OAAS,IAAM,SAAW,QACpD,IAAK,OAAO,SAAS,KACrB,UAAW,OAAO,UAAU,SAC9B,EAEA,OAAO,KAAK,SAAS,SAAS,KAAK,wBAAyB,CAC1D,KAAAE,CACF,CAAC,CACH,CAaA,aAAwB,CACtB,OAAO,KAAK,QACd,CAaA,kBAAkC,CAChC,OAAOC,EAAS,CAClB,CACF","names":["index_exports","__export","CONVERSATION_ID","Client","JWT_TOKEN","SDKError","SESSION_ID","TTL","USER_ID","auth_default","deleteConversationId","error_default","getConversationId","getSessionId","getToken","getUserId","headers_default","isTokenExpired","setConversationId","setSessionId","setToken","setUserId","__toCommonJS","import_openapi_fetch","CONVERSATION_ID","deleteConversationId","getConversationId","setConversationId","conversationId","SESSION_ID","getSessionId","setSessionId","sessionId","getItemWithExpiry","key","itemString","item","getItemWithExpiry_default","setItemWithExpiry","key","value","ttl","item","setItemWithExpiry_default","day","USER_ID","TTL","getUserId","userId","getItemWithExpiry_default","setUserId","setItemWithExpiry_default","JWT_TOKEN","isTokenExpired","token","payloadBase64","payload","error","getToken","setToken","authMiddleware","accessToken","request","auth_default","errorMiddleware","response","data","error_default","headerMiddleware","identity","url","request","headers_default","version","SDKError","_SDKError","userMessage","cause","version","Client","config","conversationUrl","customerId","fetch","frontendUrl","defaultHeaders","headers","version","createClient","getConversationId","getSessionId","getUserId","error_default","headers_default","sessionId","userId","data","SDKError","setSessionId","setUserId","setToken","endpoint","auth_default","error","deleteConversationId","context","conversationContext","conversationIdMessage","rest","conversationId","setConversationId","payload","message","eventName","properties","body","getToken"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/client.ts","../src/identity/conversationId.ts","../src/identity/sessionId.ts","../src/utils/getItemWithExpiry.ts","../src/utils/setItemWithExpiry.ts","../src/identity/userId.ts","../src/identity/token.ts","../src/middlewares/auth.ts","../src/middlewares/error.ts","../src/middlewares/headers.ts","../package.json","../src/utils/SDKError.ts"],"sourcesContent":["export * from './client'\nexport * from './identity'\nexport * from './middlewares'\nexport * from './types'\n","import createClient, { type ClientOptions } from 'openapi-fetch'\n\nimport {\n deleteConversationId,\n getConversationId,\n getSessionId,\n getUserId,\n getToken,\n setConversationId,\n setSessionId,\n setUserId,\n setToken,\n} from './identity'\nimport { authMiddleware, errorMiddleware, headerMiddleware } from './middlewares'\nimport type { components, paths as conversationPaths } from './schemas/conversation'\nimport type { paths as frontendPaths } from './schemas/frontend'\nimport type {\n Config,\n ConversationIdMessage,\n Endpoint,\n Identity,\n Message,\n SendMessagePayload,\n TrackingEvent,\n} from './types'\nimport { version } from '../package.json'\nimport SDKError from './utils/SDKError'\n\n/**\n * The `Client` class provides methods to manage 15gifts API.\n */\nexport class Client {\n /**\n * This can be used to interact with the APIs directly. It is recommended to use the [helper methods](/sdk/sdk-reference/classes/client/#methods) provided by the `Client` class instead.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * const { data } = await client.endpoint.conversation.POST('/api/conversation/v3')\n * ```\n */\n endpoint: Endpoint\n\n /**\n * The identity information.\n */\n identity: Identity\n\n /**\n * Creates a new instance of the `Client` class.\n *\n * @param config - Configuration options for initializing the client.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * ```\n */\n constructor(config: Config) {\n const { conversationUrl, customerId, fetch, frontendUrl, headers: defaultHeaders } = config\n\n const headers: ClientOptions['headers'] = {\n ...defaultHeaders,\n 'X-SDK-VERSION': version,\n }\n\n this.endpoint = {\n conversation: createClient<conversationPaths>({\n baseUrl: conversationUrl,\n fetch,\n headers,\n credentials: 'include',\n }),\n frontend: createClient<frontendPaths>({ baseUrl: frontendUrl, fetch, headers }),\n }\n\n this.identity = {\n customerId,\n conversationId: getConversationId() ?? undefined,\n sessionId: getSessionId() ?? undefined,\n userId: getUserId() ?? undefined,\n }\n\n this.endpoint.conversation.use(errorMiddleware)\n this.endpoint.conversation.use(headerMiddleware(this.identity, window.location.href))\n }\n\n /**\n * Creates a new identity for the user by generating a session ID and user ID if they don't exist, and sets the access token for future API calls.\n * Ends the current conversation if a conversation ID is present before sending a request to update identity.\n * This should not be called more than once per page load.\n *\n * @returns A promise that resolves once the identity is created and the access token is set.\n *\n * @example\n * ```ts\n * await client.createIdentity()\n * console.log('Identity created:', client.identity)\n * ```\n */\n async createIdentity(): Promise<void> {\n const { customerId, sessionId, userId } = this.identity\n\n try {\n const { data } = await this.endpoint.frontend.POST('/api/tracking/identity/v2', {\n body: {\n customerId,\n sessionId,\n userId,\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n },\n })\n\n if (!data) {\n throw new SDKError('No data received from identity API')\n }\n\n this.identity.pageviewId = data.pageviewId\n\n if (!sessionId) {\n this.identity.sessionId = data.sessionId\n setSessionId(data.sessionId)\n }\n if (!userId) {\n this.identity.userId = data.userId\n setUserId(data.userId)\n }\n\n setToken(data.token)\n\n // Add the access token to the Authorization header for all endpoints\n Object.values(this.endpoint).forEach((endpoint) => {\n endpoint.use(authMiddleware(data.token))\n })\n } catch (error) {\n // Enable the auth middleware without a token so that it will throw an error before sending\n // the next request, preventing unnecessary API calls / 401 responses.\n Object.values(this.endpoint).forEach((endpoint) => {\n endpoint.use(authMiddleware())\n })\n throw new SDKError('Failed to create identity', {\n cause: error as Error,\n })\n }\n }\n\n /**\n * Ends the current conversation by deleting the conversation ID.\n *\n * @example\n * ```ts\n * client.endConversation()\n * console.log('Conversation ended')\n * ```\n */\n endConversation(): void {\n deleteConversationId()\n this.identity.conversationId = undefined\n }\n\n /**\n * Clears the existing conversation ID, then generates a new one and returns the opening message.\n *\n * @param context - Optional context to customize the conversation. It can include:\n * @param context.eligibleProducts An array of eligible product IDs.\n * @param context.eligibleBundles An array of eligible bundle IDs.\n * @param context.productOverrides Overrides for product details.\n * @param context.bundleOverrides Overrides for bundle details.\n *\n * @returns A promise that resolves to the opening message.\n *\n * @example\n * ##### Basic usage\n * ```ts\n * const openingMessage = await client.startConversation()\n * console.log('Opening message:', openingMessage)\n * ```\n *\n * ##### With context\n * ```ts\n * const openingMessage = await client.startConversation({ eligibleProducts: ['product-1', 'product-2'], productOverrides: { 'product-1': { price: 40 } })\n * console.log('Opening message:', openingMessage)\n * ```\n */\n async startConversation(context?: components['schemas']['ConversationContext']): Promise<Message[]> {\n this.endConversation()\n\n const conversationContext = {\n ...context,\n }\n\n const { data } = await this.endpoint.conversation.POST(`/api/conversation/v3`, {\n body: {\n type: 'START_CONVERSATION',\n conversationContext,\n },\n })\n\n if (!data) throw new SDKError('No data received from Conversation API')\n\n const [conversationIdMessage, ...rest] = data as [ConversationIdMessage, ...Message[]]\n\n const conversationId = conversationIdMessage.conversationId\n if (!conversationId) {\n throw new SDKError('Conversation ID not received in API response')\n }\n\n setConversationId(conversationId)\n this.identity.conversationId = conversationId\n\n return rest\n }\n\n /**\n * Sends a message in the conversation.\n *\n * @param options - An object containing the user message.\n * @returns A promise that resolves to an array of messages\n *\n * @example\n * ```ts\n * const newMessages = await client.sendMessage({\n * userMessage: 'How can I get support?',\n * })\n *\n * if (newMessages) {\n * console.log('Received messages:', newMessages)\n * } else {\n * console.log('No message received')\n * }\n * ```\n */\n async sendMessage(payload: SendMessagePayload) {\n const conversationId = this.identity.conversationId\n if (!conversationId) {\n throw new SDKError('Conversation ID not set')\n }\n\n const { data } = await this.endpoint.conversation.POST('/api/conversation/v3', {\n body: {\n conversationId,\n ...payload,\n },\n })\n\n if (!data) throw new SDKError('No data received from conversation API')\n\n // Removes any `CONVERSATION_ID` messages from the API response. In reality, these messages will only\n // appear in the response to a `START_CONVERSATION` request.\n return data.filter((message) => message.type !== 'CONVERSATION_ID')\n }\n\n /**\n * Sends an event to the tracking API, with the required properties already set.\n *\n * @param eventName - The name of the event to track.\n * @param properties - Additional properties to include in the event.\n * @returns A promise that resolves once the event is tracked.\n *\n * @example\n * ```ts\n * await client.trackEvent('entry_point-shown')\n * ```\n */\n async trackEvent(eventName: TrackingEvent['eventName'], properties?: TrackingEvent['additionalProperties']) {\n const body: TrackingEvent = {\n additionalProperties: properties,\n conversationId: this.identity.conversationId,\n eventName,\n pageviewId: this.identity.pageviewId ?? 'unknown',\n screenWidth: window.screen.width,\n screenHeight: window.screen.height,\n screenSize: window.screen.width <= 480 ? 'mobile' : 'large',\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n }\n\n return this.endpoint.frontend.POST('/api/tracking/user/v2', {\n body,\n })\n }\n\n /**\n * Gets an existing identity of the user.\n *\n * @returns An Identity object containing `customerId`, `conversationId`, `sessionId`, `userId`.\n *\n * @example\n * ```ts\n * identity = client.getIdentity()\n * console.log('Identity retrieved:', identity)\n * ```\n */\n getIdentity(): Identity {\n return this.identity\n }\n\n /**\n * Gets the JWT from the localStorage.\n *\n * @returns {string | null} the JWT.\n *\n * @example\n * ```ts\n * token = client.getIdentityToken()\n * console.log('Identity token retrieved:', token)\n * ```\n */\n getIdentityToken(): string | null {\n return getToken()\n }\n}\n","/**\n * The key used to store the conversation ID in `sessionStorage`.\n *\n * @ignore\n */\nexport const CONVERSATION_ID = '__15gifts_conversation_id'\n\n/**\n * Deletes the conversation ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { deleteConversationId } from '@15gifts/sdk'\n *\n * deleteConversationId()\n * // The conversation ID will be removed.\n * ```\n */\nexport const deleteConversationId = () => sessionStorage.removeItem(CONVERSATION_ID)\n\n/**\n * Retrieves the conversation ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { getConversationId } from '@15gifts/sdk'\n *\n * const conversationId = getConversationId()\n *\n * if (conversationId) {\n * console.log(`Conversation ID: ${conversationId}`)\n * } else {\n * console.log('No conversation ID found.')\n * }\n * ```\n */\nexport const getConversationId = () => sessionStorage.getItem(CONVERSATION_ID)\n\n/**\n * Stores the given conversation ID in `sessionStorage`.\n *\n * @example\n * ```ts\n * import { setConversationId } from '@15gifts/sdk'\n *\n * setConversationId('ca0ab4ce-f697-41cc-8d0c-081762aace9b')\n * // The conversation ID 'ca0ab4ce-f697-41cc-8d0c-081762aace9b' will be stored.\n * ```\n */\nexport const setConversationId = (conversationId: string) => sessionStorage.setItem(CONVERSATION_ID, conversationId)\n","/**\n * The key used to store the session ID in `sessionStorage`.\n *\n * @ignore\n */\nexport const SESSION_ID = '__15gifts_session_id'\n\n/**\n * Retrieves the session ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { getSessionId } from '@15gifts/sdk'\n *\n * const sessionId = getSessionId()\n *\n * if (sessionId) {\n * console.log(`Session ID: ${sessionId}`)\n * } else {\n * console.log('No session ID found.')\n * }\n * ```\n */\nexport const getSessionId = () => sessionStorage.getItem(SESSION_ID)\n\n/**\n * Stores the given session ID in `sessionStorage`.\n *\n * @example\n * ```ts\n * import { setSessionId } from '@15gifts/sdk'\n *\n * setSessionId('20b2bff6-64a0-4101-bed9-ff545326584a')\n * // The session ID '20b2bff6-64a0-4101-bed9-ff545326584a' will be stored.\n * ```\n */\nexport const setSessionId = (sessionId: string) => sessionStorage.setItem(SESSION_ID, sessionId)\n","const getItemWithExpiry = (key: string) => {\n const itemString = localStorage.getItem(key)\n\n if (!itemString) return null\n\n const item = JSON.parse(itemString) as { expires: number; value: string }\n\n if (Date.now() > item.expires) {\n localStorage.removeItem(key)\n\n return null\n }\n\n return item.value\n}\n\nexport default getItemWithExpiry\n","/**\n * Set an item in localStorage with an expiration time\n * @param key The key under which the value is stored in localStorage\n * @param value The value to be stored\n * @param ttl The time-to-live (TTL) in milliseconds\n */\nconst setItemWithExpiry = (key: string, value: string, ttl: number) => {\n const item = {\n expires: Date.now() + ttl,\n value,\n }\n\n localStorage.setItem(key, JSON.stringify(item))\n}\n\nexport default setItemWithExpiry\n","import { getItemWithExpiry, setItemWithExpiry } from '../utils'\nconst day = 1000 * 60 * 60 * 24\n\n/**\n * The key used to store the user ID in `localStorage`.\n *\n * @ignore\n */\nexport const USER_ID = '__15gifts_user_id'\n\n/**\n * Time-to-live (TTL) for the user ID in milliseconds.\n * Set to 30 days.\n *\n * @ignore\n */\nexport const TTL = day * 30\n\n/**\n * Retrieves the user ID from `localStorage` and updates its expiry time.\n *\n * @example\n * ```ts\n * import { getUserId } from '@15gifts/sdk'\n *\n * const userId = getUserId()\n *\n * if (userId) {\n * console.log(`User ID: ${userId}`)\n * } else {\n * console.log('No user ID found.')\n * }\n * ```\n */\nexport const getUserId = () => {\n const userId = getItemWithExpiry(USER_ID)\n\n // Update the userId with a new expiry time\n // So that it will be valid for another 30 days, rather than 30 days from when it was first set\n if (userId) {\n setUserId(userId)\n }\n\n return userId\n}\n\n/**\n * Stores the given user ID in `localStorage`.\n *\n * @example\n * ```ts\n * import { setUserId } from '@15gifts/sdk'\n *\n * setUserId('5b77656c-ea4c-492f-82bf-7129297c5873')\n * // The user ID '5b77656c-ea4c-492f-82bf-7129297c5873' will be stored with a 30-day expiry.\n * ```\n */\nexport const setUserId = (userId: string) => setItemWithExpiry(USER_ID, userId, TTL)\n","/**\n * The key used to store the JWT in `localStorage`.\n *\n * @ignore\n */\nexport const JWT_TOKEN = '__15gifts_identity_token'\n\n/**\n * Checks if the JWT is expired.\n *\n * @param {string} token - the JWT.\n * @returns {boolean} `true` if expired, `false` otherwise.\n */\nexport const isTokenExpired = (token: string): boolean => {\n try {\n const [, payloadBase64] = token.split('.')\n if (!payloadBase64) {\n throw new Error('Invalid token payload')\n }\n const payload = JSON.parse(atob(payloadBase64))\n\n return payload.exp && Date.now() / 1000 > payload.exp\n } catch (error) {\n console.error('Invalid token format', error)\n return true\n }\n}\n\n/**\n * Retrieves the JWT from `localStorage` and checks if it is expired.\n *\n * @returns {string | null} The JWT if valid, otherwise `null`.\n */\nexport const getToken = (): string | null => {\n const token = localStorage.getItem(JWT_TOKEN)\n\n if (!token || isTokenExpired(token)) {\n localStorage.removeItem(JWT_TOKEN)\n return null\n }\n\n return token\n}\n\n/**\n * Stores the given JWT in `localStorage`.\n *\n * @example\n * ```ts\n * import { setToken } from '@15gifts/sdk'\n *\n * setToken('ey...')\n * ```\n */\nexport const setToken = (token: string) => localStorage.setItem(JWT_TOKEN, token)\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for adding an `Authorization` header to requests.\n *\n * @param accessToken - The token to be included in the `Authorization` header.\n * @returns A middleware object that attaches the access token to the request headers.\n *\n * @example\n * ```ts\n * import { authMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(authMiddleware(accessToken))\n * ```\n */\nconst authMiddleware = (accessToken?: string): Middleware => ({\n onRequest: async ({ request }) => {\n const isIdentityEndpoint = request.url.includes('/identity/')\n if (isIdentityEndpoint) {\n return request\n }\n\n // Throw an error because we know the API will return a 401 if the access token is not set.\n if (!accessToken) {\n throw new Error('Access token is required for authentication.')\n }\n\n request.headers.set('Authorization', `Bearer ${accessToken}`)\n\n return request\n },\n})\n\nexport default authMiddleware\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for handling errors.\n *\n * @returns A middleware object that throws an error if the response is not ok.\n *\n * @example\n * ```ts\n * import { errorMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(errorMiddleware())\n * ```\n */\nconst errorMiddleware: Middleware = {\n // onError does not handle error responses with 4xx or 5xx HTTP status codes, since these are considered \"successful\" responses but with a bad status code.\n // In these cases we need to check the response's status property or ok() method via the onResponse callback.\n onResponse: async ({ response }) => {\n if (!response.ok) {\n const data = await response.json()\n\n throw new Error(data.message)\n }\n\n return response\n },\n}\n\nexport default errorMiddleware\n","import type { Middleware } from 'openapi-fetch'\n\nimport { Identity } from '../types'\n\n/**\n * Middleware for adding request headers that other services use for tracking.\n *\n * @returns A middleware object that throws an error if the response is not ok.\n *\n * @example\n * ```ts\n * import { pageViewId } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(headerMiddleware('123', 'https://example.com'))\n * ```\n */\nconst headerMiddleware = (identity: Identity, url: string): Middleware => ({\n onRequest: async ({ request }) => {\n if (identity.pageviewId) {\n request.headers.set('X-PAGEVIEW-ID', identity.pageviewId)\n }\n if (url) {\n request.headers.set('X-PAGE-URL', url)\n }\n\n return request\n },\n})\n\nexport default headerMiddleware\n","{\n \"name\": \"@15gifts/sdk\",\n \"version\": \"0.16.2\",\n \"files\": [\n \"dist\"\n ],\n \"main\": \"./dist/index.js\",\n \"module\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"scripts\": {\n \"build\": \"tsup\",\n \"coverage\": \"vitest run --coverage\",\n \"generate-types\": \"npx openapi-typescript\",\n \"dev\": \"tsup --watch\",\n \"format\": \"prettier . --write\",\n \"lint\": \"eslint .\",\n \"test:watch\": \"vitest\",\n \"test\": \"vitest run\",\n \"typecheck\": \"tsc\",\n \"update-schemas\": \"node --experimental-strip-types update-schema.ts && npm run generate-types && npm run format\"\n },\n \"dependencies\": {\n \"openapi-fetch\": \"^0.13.4\"\n },\n \"devDependencies\": {\n \"openapi-typescript\": \"^7.6.0\",\n \"tsup\": \"^8.3.6\"\n },\n \"sideEffects\": false,\n \"prettier\": \"prettier-config-custom\"\n}\n","import { version } from '../../package.json'\n\n/**\n * Custom error class for SDK-related errors.\n * Includes the SDK version and an optional cause for better debugging.\n * NOTE: The error.message is intended for developers, not end-users.\n */\nexport default class SDKError extends Error {\n sdkVersion: string\n override cause?: Error\n\n constructor(userMessage: string, { cause }: { cause?: Error } = {}) {\n super(userMessage)\n this.name = 'SDKError'\n this.cause = cause\n this.sdkVersion = version\n\n // Set the prototype explicitly to maintain instanceof checks\n Object.setPrototypeOf(this, SDKError.prototype)\n }\n}\n"],"mappings":"0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,EAAA,WAAAC,EAAA,cAAAC,EAAA,aAAAC,EAAA,eAAAC,EAAA,QAAAC,EAAA,YAAAC,EAAA,mBAAAC,EAAA,yBAAAC,EAAA,oBAAAC,EAAA,sBAAAC,EAAA,iBAAAC,EAAA,aAAAC,EAAA,cAAAC,EAAA,qBAAAC,EAAA,mBAAAC,EAAA,sBAAAC,EAAA,iBAAAC,EAAA,aAAAC,EAAA,cAAAC,IAAA,eAAAC,EAAAtB,GCAA,IAAAuB,EAAiD,4BCK1C,IAAMC,EAAkB,4BAalBC,EAAuB,IAAM,eAAe,WAAWD,CAAe,EAkBtEE,EAAoB,IAAM,eAAe,QAAQF,CAAe,EAahEG,EAAqBC,GAA2B,eAAe,QAAQJ,EAAiBI,CAAc,EC5C5G,IAAMC,EAAa,uBAkBbC,EAAe,IAAM,eAAe,QAAQD,CAAU,EAatDE,EAAgBC,GAAsB,eAAe,QAAQH,EAAYG,CAAS,ECpC/F,IAAMC,EAAqBC,GAAgB,CACzC,IAAMC,EAAa,aAAa,QAAQD,CAAG,EAE3C,GAAI,CAACC,EAAY,OAAO,KAExB,IAAMC,EAAO,KAAK,MAAMD,CAAU,EAElC,OAAI,KAAK,IAAI,EAAIC,EAAK,SACpB,aAAa,WAAWF,CAAG,EAEpB,MAGFE,EAAK,KACd,EAEOC,EAAQJ,ECVf,IAAMK,EAAoB,CAACC,EAAaC,EAAeC,IAAgB,CACrE,IAAMC,EAAO,CACX,QAAS,KAAK,IAAI,EAAID,EACtB,MAAAD,CACF,EAEA,aAAa,QAAQD,EAAK,KAAK,UAAUG,CAAI,CAAC,CAChD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D,CACT,CAqBA,MAAM,YAAYG,EAA6B,CAC7C,IAAMF,EAAiB,KAAK,SAAS,eACrC,GAAI,CAACA,EACH,MAAM,IAAIZ,EAAS,yBAAyB,EAG9C,GAAM,CAAE,KAAAD,CAAK,EAAI,MAAM,KAAK,SAAS,aAAa,KAAK,uBAAwB,CAC7E,KAAM,CACJ,eAAAa,EACA,GAAGE,CACL,CACF,CAAC,EAED,GAAI,CAACf,EAAM,MAAM,IAAIC,EAAS,wCAAwC,EAItE,OAAOD,EAAK,OAAQgB,GAAYA,EAAQ,OAAS,iBAAiB,CACpE,CAcA,MAAM,WAAWC,EAAuCC,EAAoD,CAC1G,IAAMC,EAAsB,CAC1B,qBAAsBD,EACtB,eAAgB,KAAK,SAAS,eAC9B,UAAAD,EACA,WAAY,KAAK,SAAS,YAAc,UACxC,YAAa,OAAO,OAAO,MAC3B,aAAc,OAAO,OAAO,OAC5B,WAAY,OAAO,OAAO,OAAS,IAAM,SAAW,QACpD,IAAK,OAAO,SAAS,KACrB,UAAW,OAAO,UAAU,SAC9B,EAEA,OAAO,KAAK,SAAS,SAAS,KAAK,wBAAyB,CAC1D,KAAAE,CACF,CAAC,CACH,CAaA,aAAwB,CACtB,OAAO,KAAK,QACd,CAaA,kBAAkC,CAChC,OAAOC,EAAS,CAClB,CACF","names":["index_exports","__export","CONVERSATION_ID","Client","JWT_TOKEN","SDKError","SESSION_ID","TTL","USER_ID","auth_default","deleteConversationId","error_default","getConversationId","getSessionId","getToken","getUserId","headers_default","isTokenExpired","setConversationId","setSessionId","setToken","setUserId","__toCommonJS","import_openapi_fetch","CONVERSATION_ID","deleteConversationId","getConversationId","setConversationId","conversationId","SESSION_ID","getSessionId","setSessionId","sessionId","getItemWithExpiry","key","itemString","item","getItemWithExpiry_default","setItemWithExpiry","key","value","ttl","item","setItemWithExpiry_default","day","USER_ID","TTL","getUserId","userId","getItemWithExpiry_default","setUserId","setItemWithExpiry_default","JWT_TOKEN","isTokenExpired","token","payloadBase64","payload","error","getToken","setToken","authMiddleware","accessToken","request","auth_default","errorMiddleware","response","data","error_default","headerMiddleware","identity","url","request","headers_default","version","SDKError","_SDKError","userMessage","cause","version","Client","config","conversationUrl","customerId","fetch","frontendUrl","defaultHeaders","headers","version","createClient","getConversationId","getSessionId","getUserId","error_default","headers_default","sessionId","userId","data","SDKError","setSessionId","setUserId","setToken","endpoint","auth_default","error","deleteConversationId","context","conversationContext","conversationIdMessage","rest","conversationId","setConversationId","payload","message","eventName","properties","body","getToken"]}
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import P from"openapi-fetch";var p="__15gifts_conversation_id",I=()=>sessionStorage.removeItem(p),x=()=>sessionStorage.getItem(p),y=e=>sessionStorage.setItem(p,e);var M="__15gifts_session_id",w=()=>sessionStorage.getItem(M),S=e=>sessionStorage.setItem(M,e);var k=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},g=k;var R=(e,t,s)=>{let o={expires:Date.now()+s,value:t};localStorage.setItem(e,JSON.stringify(o))},m=R;var U=1e3*60*60*24,E="__15gifts_user_id",_=U*30,C=()=>{let e=g(E);return e&&l(e),e},l=e=>m(E,e,_);var h="__15gifts_identity_token",V=e=>{try{let[,t]=e.split(".");if(!t)throw new Error("Invalid token payload");let s=JSON.parse(atob(t));return s.exp&&Date.now()/1e3>s.exp}catch(t){return console.error("Invalid token format",t),!0}},A=()=>{let e=localStorage.getItem(h);return!e||V(e)?(localStorage.removeItem(h),null):e},T=e=>localStorage.setItem(h,e);var N=e=>({onRequest:async({request:t})=>{if(t.url.includes("/identity/"))return t;if(!e)throw new Error("Access token is required for authentication.");return t.headers.set("Authorization",`Bearer ${e}`),t}}),d=N;var b={onResponse:async({response:e})=>{if(!e.ok){let t=await e.json();throw new Error(t.message)}return e}},f=b;var D=(e,t)=>({onRequest:async({request:s})=>(e.pageviewId&&s.headers.set("X-PAGEVIEW-ID",e.pageviewId),t&&s.headers.set("X-PAGE-URL",t),s)}),u=D;var c="0.16.
|
|
1
|
+
import P from"openapi-fetch";var p="__15gifts_conversation_id",I=()=>sessionStorage.removeItem(p),x=()=>sessionStorage.getItem(p),y=e=>sessionStorage.setItem(p,e);var M="__15gifts_session_id",w=()=>sessionStorage.getItem(M),S=e=>sessionStorage.setItem(M,e);var k=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},g=k;var R=(e,t,s)=>{let o={expires:Date.now()+s,value:t};localStorage.setItem(e,JSON.stringify(o))},m=R;var U=1e3*60*60*24,E="__15gifts_user_id",_=U*30,C=()=>{let e=g(E);return e&&l(e),e},l=e=>m(E,e,_);var h="__15gifts_identity_token",V=e=>{try{let[,t]=e.split(".");if(!t)throw new Error("Invalid token payload");let s=JSON.parse(atob(t));return s.exp&&Date.now()/1e3>s.exp}catch(t){return console.error("Invalid token format",t),!0}},A=()=>{let e=localStorage.getItem(h);return!e||V(e)?(localStorage.removeItem(h),null):e},T=e=>localStorage.setItem(h,e);var N=e=>({onRequest:async({request:t})=>{if(t.url.includes("/identity/"))return t;if(!e)throw new Error("Access token is required for authentication.");return t.headers.set("Authorization",`Bearer ${e}`),t}}),d=N;var b={onResponse:async({response:e})=>{if(!e.ok){let t=await e.json();throw new Error(t.message)}return e}},f=b;var D=(e,t)=>({onRequest:async({request:s})=>(e.pageviewId&&s.headers.set("X-PAGEVIEW-ID",e.pageviewId),t&&s.headers.set("X-PAGE-URL",t),s)}),u=D;var c="0.16.2";var i=class e extends Error{sdkVersion;cause;constructor(t,{cause:s}={}){super(t),this.name="SDKError",this.cause=s,this.sdkVersion=c,Object.setPrototypeOf(this,e.prototype)}};var O=class{endpoint;identity;constructor(t){let{conversationUrl:s,customerId:o,fetch:n,frontendUrl:r,headers:a}=t,v={...a,"X-SDK-VERSION":c};this.endpoint={conversation:P({baseUrl:s,fetch:n,headers:v,credentials:"include"}),frontend:P({baseUrl:r,fetch:n,headers:v})},this.identity={customerId:o,conversationId:x()??void 0,sessionId:w()??void 0,userId:C()??void 0},this.endpoint.conversation.use(f),this.endpoint.conversation.use(u(this.identity,window.location.href))}async createIdentity(){let{customerId:t,sessionId:s,userId:o}=this.identity;try{let{data:n}=await this.endpoint.frontend.POST("/api/tracking/identity/v2",{body:{customerId:t,sessionId:s,userId:o,url:window.location.href,userAgent:window.navigator.userAgent}});if(!n)throw new i("No data received from identity API");this.identity.pageviewId=n.pageviewId,s||(this.identity.sessionId=n.sessionId,S(n.sessionId)),o||(this.identity.userId=n.userId,l(n.userId)),T(n.token),Object.values(this.endpoint).forEach(r=>{r.use(d(n.token))})}catch(n){throw Object.values(this.endpoint).forEach(r=>{r.use(d())}),new i("Failed to create identity",{cause:n})}}endConversation(){I(),this.identity.conversationId=void 0}async startConversation(t){this.endConversation();let s={...t},{data:o}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{type:"START_CONVERSATION",conversationContext:s}});if(!o)throw new i("No data received from Conversation API");let[n,...r]=o,a=n.conversationId;if(!a)throw new i("Conversation ID not received in API response");return y(a),this.identity.conversationId=a,r}async sendMessage(t){let s=this.identity.conversationId;if(!s)throw new i("Conversation ID not set");let{data:o}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{conversationId:s,...t}});if(!o)throw new i("No data received from conversation API");return o.filter(n=>n.type!=="CONVERSATION_ID")}async trackEvent(t,s){let o={additionalProperties:s,conversationId:this.identity.conversationId,eventName:t,pageviewId:this.identity.pageviewId??"unknown",screenWidth:window.screen.width,screenHeight:window.screen.height,screenSize:window.screen.width<=480?"mobile":"large",url:window.location.href,userAgent:window.navigator.userAgent};return this.endpoint.frontend.POST("/api/tracking/user/v2",{body:o})}getIdentity(){return this.identity}getIdentityToken(){return A()}};export{p as CONVERSATION_ID,O as Client,h as JWT_TOKEN,i as SDKError,M as SESSION_ID,_ as TTL,E as USER_ID,d as authMiddleware,I as deleteConversationId,f as errorMiddleware,x as getConversationId,w as getSessionId,A as getToken,C as getUserId,u as headerMiddleware,V as isTokenExpired,y as setConversationId,S as setSessionId,T as setToken,l 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","../src/identity/token.ts","../src/middlewares/auth.ts","../src/middlewares/error.ts","../src/middlewares/headers.ts","../package.json","../src/utils/SDKError.ts"],"sourcesContent":["import createClient, { type ClientOptions } from 'openapi-fetch'\n\nimport {\n deleteConversationId,\n getConversationId,\n getSessionId,\n getUserId,\n getToken,\n setConversationId,\n setSessionId,\n setUserId,\n setToken,\n} from './identity'\nimport { authMiddleware, errorMiddleware, headerMiddleware } from './middlewares'\nimport type { components, paths as conversationPaths } from './schemas/conversation'\nimport type { paths as frontendPaths } from './schemas/frontend'\nimport type {\n Config,\n ConversationIdMessage,\n Endpoint,\n Identity,\n Message,\n SendMessagePayload,\n TrackingEvent,\n} from './types'\nimport { version } from '../package.json'\nimport SDKError from './utils/SDKError'\n\n/**\n * The `Client` class provides methods to manage 15gifts API.\n */\nexport class Client {\n /**\n * This can be used to interact with the APIs directly. It is recommended to use the [helper methods](/sdk/sdk-reference/classes/client/#methods) provided by the `Client` class instead.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * const { data } = await client.endpoint.conversation.POST('/api/conversation/v3')\n * ```\n */\n endpoint: Endpoint\n\n /**\n * The identity information.\n */\n identity: Identity\n\n /**\n * Creates a new instance of the `Client` class.\n *\n * @param config - Configuration options for initializing the client.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * ```\n */\n constructor(config: Config) {\n const { conversationUrl, customerId, fetch, frontendUrl, headers: defaultHeaders } = config\n\n const headers: ClientOptions['headers'] = {\n ...defaultHeaders,\n 'X-SDK-VERSION': version,\n }\n\n this.endpoint = {\n conversation: createClient<conversationPaths>({\n baseUrl: conversationUrl,\n fetch,\n headers,\n credentials: 'include',\n }),\n frontend: createClient<frontendPaths>({ baseUrl: frontendUrl, fetch, headers }),\n }\n\n this.identity = {\n customerId,\n conversationId: getConversationId() ?? undefined,\n sessionId: getSessionId() ?? undefined,\n userId: getUserId() ?? undefined,\n }\n\n this.endpoint.conversation.use(errorMiddleware)\n this.endpoint.conversation.use(headerMiddleware(this.identity, window.location.href))\n }\n\n /**\n * Creates a new identity for the user by generating a session ID and user ID if they don't exist, and sets the access token for future API calls.\n * Ends the current conversation if a conversation ID is present before sending a request to update identity.\n * This should not be called more than once per page load.\n *\n * @returns A promise that resolves once the identity is created and the access token is set.\n *\n * @example\n * ```ts\n * await client.createIdentity()\n * console.log('Identity created:', client.identity)\n * ```\n */\n async createIdentity(): Promise<void> {\n const { customerId, sessionId, userId } = this.identity\n\n try {\n const { data } = await this.endpoint.frontend.POST('/api/tracking/identity/v2', {\n body: {\n customerId,\n sessionId,\n userId,\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n },\n })\n\n if (!data) {\n throw new SDKError('No data received from identity API')\n }\n\n this.identity.pageviewId = data.pageviewId\n\n if (!sessionId) {\n this.identity.sessionId = data.sessionId\n setSessionId(data.sessionId)\n }\n if (!userId) {\n this.identity.userId = data.userId\n setUserId(data.userId)\n }\n\n setToken(data.token)\n\n // Add the access token to the Authorization header for all endpoints\n Object.values(this.endpoint).forEach((endpoint) => {\n endpoint.use(authMiddleware(data.token))\n })\n } catch (error) {\n // Enable the auth middleware without a token so that it will throw an error before sending\n // the next request, preventing unnecessary API calls / 401 responses.\n Object.values(this.endpoint).forEach((endpoint) => {\n endpoint.use(authMiddleware())\n })\n throw new SDKError('Failed to create identity', {\n cause: error as Error,\n })\n }\n }\n\n /**\n * Ends the current conversation by deleting the conversation ID.\n *\n * @example\n * ```ts\n * client.endConversation()\n * console.log('Conversation ended')\n * ```\n */\n endConversation(): void {\n deleteConversationId()\n this.identity.conversationId = undefined\n }\n\n /**\n * Clears the existing conversation ID, then generates a new one and returns the opening message.\n *\n * @param context - Optional context to customize the conversation. It can include:\n * @param context.eligibleProducts An array of eligible product IDs.\n * @param context.eligibleBundles An array of eligible bundle IDs.\n * @param context.productOverrides Overrides for product details.\n * @param context.bundleOverrides Overrides for bundle details.\n *\n * @returns A promise that resolves to the opening message.\n *\n * @example\n * ##### Basic usage\n * ```ts\n * const openingMessage = await client.startConversation()\n * console.log('Opening message:', openingMessage)\n * ```\n *\n * ##### With context\n * ```ts\n * const openingMessage = await client.startConversation({ eligibleProducts: ['product-1', 'product-2'], productOverrides: { 'product-1': { price: 40 } })\n * console.log('Opening message:', openingMessage)\n * ```\n */\n async startConversation(context?: components['schemas']['ConversationContext']): Promise<Message[]> {\n this.endConversation()\n\n const conversationContext = {\n ...context,\n }\n\n const { data } = await this.endpoint.conversation.POST(`/api/conversation/v3`, {\n body: {\n type: 'START_CONVERSATION',\n conversationContext,\n },\n })\n\n if (!data) throw new SDKError('No data received from Conversation API')\n\n const [conversationIdMessage, ...rest] = data as [ConversationIdMessage, ...Message[]]\n\n const conversationId = conversationIdMessage.conversationId\n if (!conversationId) {\n throw new SDKError('Conversation ID not received in API response')\n }\n\n setConversationId(conversationId)\n this.identity.conversationId = conversationId\n\n return rest\n }\n\n /**\n * Sends a message in the conversation.\n *\n * @param options - An object containing the user message.\n * @returns A promise that resolves to an array of messages\n *\n * @example\n * ```ts\n * const newMessages = await client.sendMessage({\n * userMessage: 'How can I get support?',\n * })\n *\n * if (newMessages) {\n * console.log('Received messages:', newMessages)\n * } else {\n * console.log('No message received')\n * }\n * ```\n */\n async sendMessage(payload: SendMessagePayload) {\n const conversationId = this.identity.conversationId\n if (!conversationId) {\n throw new SDKError('Conversation ID not set')\n }\n\n const { data } = await this.endpoint.conversation.POST('/api/conversation/v3', {\n body: {\n conversationId,\n ...payload,\n },\n })\n\n if (!data) throw new SDKError('No data received from conversation API')\n\n // Removes any `CONVERSATION_ID` messages from the API response. In reality, these messages will only\n // appear in the response to a `START_CONVERSATION` request.\n return data.filter((message) => message.type !== 'CONVERSATION_ID')\n }\n\n /**\n * Sends an event to the tracking API, with the required properties already set.\n *\n * @param eventName - The name of the event to track.\n * @param properties - Additional properties to include in the event.\n * @returns A promise that resolves once the event is tracked.\n *\n * @example\n * ```ts\n * await client.trackEvent('entry_point-shown')\n * ```\n */\n async trackEvent(eventName: TrackingEvent['eventName'], properties?: TrackingEvent['additionalProperties']) {\n const body: TrackingEvent = {\n additionalProperties: properties,\n conversationId: this.identity.conversationId,\n eventName,\n pageviewId: this.identity.pageviewId ?? 'unknown',\n screenWidth: window.screen.width,\n screenHeight: window.screen.height,\n screenSize: window.screen.width <= 480 ? 'mobile' : 'large',\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n }\n\n return this.endpoint.frontend.POST('/api/tracking/user/v2', {\n body,\n })\n }\n\n /**\n * Gets an existing identity of the user.\n *\n * @returns An Identity object containing `customerId`, `conversationId`, `sessionId`, `userId`.\n *\n * @example\n * ```ts\n * identity = client.getIdentity()\n * console.log('Identity retrieved:', identity)\n * ```\n */\n getIdentity(): Identity {\n return this.identity\n }\n\n /**\n * Gets the JWT from the localStorage.\n *\n * @returns {string | null} the JWT.\n *\n * @example\n * ```ts\n * token = client.getIdentityToken()\n * console.log('Identity token retrieved:', token)\n * ```\n */\n getIdentityToken(): string | null {\n return getToken()\n }\n}\n","/**\n * The key used to store the conversation ID in `sessionStorage`.\n *\n * @ignore\n */\nexport const CONVERSATION_ID = '__15gifts_conversation_id'\n\n/**\n * Deletes the conversation ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { deleteConversationId } from '@15gifts/sdk'\n *\n * deleteConversationId()\n * // The conversation ID will be removed.\n * ```\n */\nexport const deleteConversationId = () => sessionStorage.removeItem(CONVERSATION_ID)\n\n/**\n * Retrieves the conversation ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { getConversationId } from '@15gifts/sdk'\n *\n * const conversationId = getConversationId()\n *\n * if (conversationId) {\n * console.log(`Conversation ID: ${conversationId}`)\n * } else {\n * console.log('No conversation ID found.')\n * }\n * ```\n */\nexport const getConversationId = () => sessionStorage.getItem(CONVERSATION_ID)\n\n/**\n * Stores the given conversation ID in `sessionStorage`.\n *\n * @example\n * ```ts\n * import { setConversationId } from '@15gifts/sdk'\n *\n * setConversationId('ca0ab4ce-f697-41cc-8d0c-081762aace9b')\n * // The conversation ID 'ca0ab4ce-f697-41cc-8d0c-081762aace9b' will be stored.\n * ```\n */\nexport const setConversationId = (conversationId: string) => sessionStorage.setItem(CONVERSATION_ID, conversationId)\n","/**\n * The key used to store the session ID in `sessionStorage`.\n *\n * @ignore\n */\nexport const SESSION_ID = '__15gifts_session_id'\n\n/**\n * Retrieves the session ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { getSessionId } from '@15gifts/sdk'\n *\n * const sessionId = getSessionId()\n *\n * if (sessionId) {\n * console.log(`Session ID: ${sessionId}`)\n * } else {\n * console.log('No session ID found.')\n * }\n * ```\n */\nexport const getSessionId = () => sessionStorage.getItem(SESSION_ID)\n\n/**\n * Stores the given session ID in `sessionStorage`.\n *\n * @example\n * ```ts\n * import { setSessionId } from '@15gifts/sdk'\n *\n * setSessionId('20b2bff6-64a0-4101-bed9-ff545326584a')\n * // The session ID '20b2bff6-64a0-4101-bed9-ff545326584a' will be stored.\n * ```\n */\nexport const setSessionId = (sessionId: string) => sessionStorage.setItem(SESSION_ID, sessionId)\n","const getItemWithExpiry = (key: string) => {\n const itemString = localStorage.getItem(key)\n\n if (!itemString) return null\n\n const item = JSON.parse(itemString) as { expires: number; value: string }\n\n if (Date.now() > item.expires) {\n localStorage.removeItem(key)\n\n return null\n }\n\n return item.value\n}\n\nexport default getItemWithExpiry\n","/**\n * Set an item in localStorage with an expiration time\n * @param key The key under which the value is stored in localStorage\n * @param value The value to be stored\n * @param ttl The time-to-live (TTL) in milliseconds\n */\nconst setItemWithExpiry = (key: string, value: string, ttl: number) => {\n const item = {\n expires: Date.now() + ttl,\n value,\n }\n\n localStorage.setItem(key, JSON.stringify(item))\n}\n\nexport default setItemWithExpiry\n","import { getItemWithExpiry, setItemWithExpiry } from '../utils'\nconst day = 1000 * 60 * 60 * 24\n\n/**\n * The key used to store the user ID in `localStorage`.\n *\n * @ignore\n */\nexport const USER_ID = '__15gifts_user_id'\n\n/**\n * Time-to-live (TTL) for the user ID in milliseconds.\n * Set to 30 days.\n *\n * @ignore\n */\nexport const TTL = day * 30\n\n/**\n * Retrieves the user ID from `localStorage` and updates its expiry time.\n *\n * @example\n * ```ts\n * import { getUserId } from '@15gifts/sdk'\n *\n * const userId = getUserId()\n *\n * if (userId) {\n * console.log(`User ID: ${userId}`)\n * } else {\n * console.log('No user ID found.')\n * }\n * ```\n */\nexport const getUserId = () => {\n const userId = getItemWithExpiry(USER_ID)\n\n // Update the userId with a new expiry time\n // So that it will be valid for another 30 days, rather than 30 days from when it was first set\n if (userId) {\n setUserId(userId)\n }\n\n return userId\n}\n\n/**\n * Stores the given user ID in `localStorage`.\n *\n * @example\n * ```ts\n * import { setUserId } from '@15gifts/sdk'\n *\n * setUserId('5b77656c-ea4c-492f-82bf-7129297c5873')\n * // The user ID '5b77656c-ea4c-492f-82bf-7129297c5873' will be stored with a 30-day expiry.\n * ```\n */\nexport const setUserId = (userId: string) => setItemWithExpiry(USER_ID, userId, TTL)\n","/**\n * The key used to store the JWT in `localStorage`.\n *\n * @ignore\n */\nexport const JWT_TOKEN = '__15gifts_identity_token'\n\n/**\n * Checks if the JWT is expired.\n *\n * @param {string} token - the JWT.\n * @returns {boolean} `true` if expired, `false` otherwise.\n */\nexport const isTokenExpired = (token: string): boolean => {\n try {\n const [, payloadBase64] = token.split('.')\n if (!payloadBase64) {\n throw new Error('Invalid token payload')\n }\n const payload = JSON.parse(atob(payloadBase64))\n\n return payload.exp && Date.now() / 1000 > payload.exp\n } catch (error) {\n console.error('Invalid token format', error)\n return true\n }\n}\n\n/**\n * Retrieves the JWT from `localStorage` and checks if it is expired.\n *\n * @returns {string | null} The JWT if valid, otherwise `null`.\n */\nexport const getToken = (): string | null => {\n const token = localStorage.getItem(JWT_TOKEN)\n\n if (!token || isTokenExpired(token)) {\n localStorage.removeItem(JWT_TOKEN)\n return null\n }\n\n return token\n}\n\n/**\n * Stores the given JWT in `localStorage`.\n *\n * @example\n * ```ts\n * import { setToken } from '@15gifts/sdk'\n *\n * setToken('ey...')\n * ```\n */\nexport const setToken = (token: string) => localStorage.setItem(JWT_TOKEN, token)\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for adding an `Authorization` header to requests.\n *\n * @param accessToken - The token to be included in the `Authorization` header.\n * @returns A middleware object that attaches the access token to the request headers.\n *\n * @example\n * ```ts\n * import { authMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(authMiddleware(accessToken))\n * ```\n */\nconst authMiddleware = (accessToken?: string): Middleware => ({\n onRequest: async ({ request }) => {\n const isIdentityEndpoint = request.url.includes('/identity/')\n if (isIdentityEndpoint) {\n return request\n }\n\n // Throw an error because we know the API will return a 401 if the access token is not set.\n if (!accessToken) {\n throw new Error('Access token is required for authentication.')\n }\n\n request.headers.set('Authorization', `Bearer ${accessToken}`)\n\n return request\n },\n})\n\nexport default authMiddleware\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for handling errors.\n *\n * @returns A middleware object that throws an error if the response is not ok.\n *\n * @example\n * ```ts\n * import { errorMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(errorMiddleware())\n * ```\n */\nconst errorMiddleware: Middleware = {\n // onError does not handle error responses with 4xx or 5xx HTTP status codes, since these are considered \"successful\" responses but with a bad status code.\n // In these cases we need to check the response's status property or ok() method via the onResponse callback.\n onResponse: async ({ response }) => {\n if (!response.ok) {\n const data = await response.json()\n\n throw new Error(data.message)\n }\n\n return response\n },\n}\n\nexport default errorMiddleware\n","import type { Middleware } from 'openapi-fetch'\n\nimport { Identity } from '../types'\n\n/**\n * Middleware for adding request headers that other services use for tracking.\n *\n * @returns A middleware object that throws an error if the response is not ok.\n *\n * @example\n * ```ts\n * import { pageViewId } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(headerMiddleware('123', 'https://example.com'))\n * ```\n */\nconst headerMiddleware = (identity: Identity, url: string): Middleware => ({\n onRequest: async ({ request }) => {\n if (identity.pageviewId) {\n request.headers.set('X-PAGEVIEW-ID', identity.pageviewId)\n }\n if (url) {\n request.headers.set('X-PAGE-URL', url)\n }\n\n return request\n },\n})\n\nexport default headerMiddleware\n","{\n \"name\": \"@15gifts/sdk\",\n \"version\": \"0.16.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\": \"npm run generate && tsup\",\n \"coverage\": \"vitest run --coverage\",\n \"dev\": \"tsup --watch\",\n \"format\": \"prettier . --write\",\n \"generate\": \"npx openapi-typescript\",\n \"lint\": \"eslint .\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"typecheck\": \"tsc\"\n },\n \"dependencies\": {\n \"openapi-fetch\": \"^0.13.4\"\n },\n \"devDependencies\": {\n \"openapi-typescript\": \"^7.6.0\",\n \"tsup\": \"^8.3.6\"\n },\n \"sideEffects\": false,\n \"prettier\": \"prettier-config-custom\"\n}\n","import { version } from '../../package.json'\n\n/**\n * Custom error class for SDK-related errors.\n * Includes the SDK version and an optional cause for better debugging.\n * NOTE: The error.message is intended for developers, not end-users.\n */\nexport default class SDKError extends Error {\n sdkVersion: string\n override cause?: Error\n\n constructor(userMessage: string, { cause }: { cause?: Error } = {}) {\n super(userMessage)\n this.name = 'SDKError'\n this.cause = cause\n this.sdkVersion = version\n\n // Set the prototype explicitly to maintain instanceof checks\n Object.setPrototypeOf(this, SDKError.prototype)\n }\n}\n"],"mappings":"AAAA,OA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AAO,OAC5B,WAAY,OAAO,OAAO,OAAS,IAAM,SAAW,QACpD,IAAK,OAAO,SAAS,KACrB,UAAW,OAAO,UAAU,SAC9B,EAEA,OAAO,KAAK,SAAS,SAAS,KAAK,wBAAyB,CAC1D,KAAAE,CACF,CAAC,CACH,CAaA,aAAwB,CACtB,OAAO,KAAK,QACd,CAaA,kBAAkC,CAChC,OAAOC,EAAS,CAClB,CACF","names":["createClient","CONVERSATION_ID","deleteConversationId","getConversationId","setConversationId","conversationId","SESSION_ID","getSessionId","setSessionId","sessionId","getItemWithExpiry","key","itemString","item","getItemWithExpiry_default","setItemWithExpiry","key","value","ttl","item","setItemWithExpiry_default","day","USER_ID","TTL","getUserId","userId","getItemWithExpiry_default","setUserId","setItemWithExpiry_default","JWT_TOKEN","isTokenExpired","token","payloadBase64","payload","error","getToken","setToken","authMiddleware","accessToken","request","auth_default","errorMiddleware","response","data","error_default","headerMiddleware","identity","url","request","headers_default","version","SDKError","_SDKError","userMessage","cause","version","Client","config","conversationUrl","customerId","fetch","frontendUrl","defaultHeaders","headers","version","createClient","getConversationId","getSessionId","getUserId","error_default","headers_default","sessionId","userId","data","SDKError","setSessionId","setUserId","setToken","endpoint","auth_default","error","deleteConversationId","context","conversationContext","conversationIdMessage","rest","conversationId","setConversationId","payload","message","eventName","properties","body","getToken"]}
|
|
1
|
+
{"version":3,"sources":["../src/client.ts","../src/identity/conversationId.ts","../src/identity/sessionId.ts","../src/utils/getItemWithExpiry.ts","../src/utils/setItemWithExpiry.ts","../src/identity/userId.ts","../src/identity/token.ts","../src/middlewares/auth.ts","../src/middlewares/error.ts","../src/middlewares/headers.ts","../package.json","../src/utils/SDKError.ts"],"sourcesContent":["import createClient, { type ClientOptions } from 'openapi-fetch'\n\nimport {\n deleteConversationId,\n getConversationId,\n getSessionId,\n getUserId,\n getToken,\n setConversationId,\n setSessionId,\n setUserId,\n setToken,\n} from './identity'\nimport { authMiddleware, errorMiddleware, headerMiddleware } from './middlewares'\nimport type { components, paths as conversationPaths } from './schemas/conversation'\nimport type { paths as frontendPaths } from './schemas/frontend'\nimport type {\n Config,\n ConversationIdMessage,\n Endpoint,\n Identity,\n Message,\n SendMessagePayload,\n TrackingEvent,\n} from './types'\nimport { version } from '../package.json'\nimport SDKError from './utils/SDKError'\n\n/**\n * The `Client` class provides methods to manage 15gifts API.\n */\nexport class Client {\n /**\n * This can be used to interact with the APIs directly. It is recommended to use the [helper methods](/sdk/sdk-reference/classes/client/#methods) provided by the `Client` class instead.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * const { data } = await client.endpoint.conversation.POST('/api/conversation/v3')\n * ```\n */\n endpoint: Endpoint\n\n /**\n * The identity information.\n */\n identity: Identity\n\n /**\n * Creates a new instance of the `Client` class.\n *\n * @param config - Configuration options for initializing the client.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * ```\n */\n constructor(config: Config) {\n const { conversationUrl, customerId, fetch, frontendUrl, headers: defaultHeaders } = config\n\n const headers: ClientOptions['headers'] = {\n ...defaultHeaders,\n 'X-SDK-VERSION': version,\n }\n\n this.endpoint = {\n conversation: createClient<conversationPaths>({\n baseUrl: conversationUrl,\n fetch,\n headers,\n credentials: 'include',\n }),\n frontend: createClient<frontendPaths>({ baseUrl: frontendUrl, fetch, headers }),\n }\n\n this.identity = {\n customerId,\n conversationId: getConversationId() ?? undefined,\n sessionId: getSessionId() ?? undefined,\n userId: getUserId() ?? undefined,\n }\n\n this.endpoint.conversation.use(errorMiddleware)\n this.endpoint.conversation.use(headerMiddleware(this.identity, window.location.href))\n }\n\n /**\n * Creates a new identity for the user by generating a session ID and user ID if they don't exist, and sets the access token for future API calls.\n * Ends the current conversation if a conversation ID is present before sending a request to update identity.\n * This should not be called more than once per page load.\n *\n * @returns A promise that resolves once the identity is created and the access token is set.\n *\n * @example\n * ```ts\n * await client.createIdentity()\n * console.log('Identity created:', client.identity)\n * ```\n */\n async createIdentity(): Promise<void> {\n const { customerId, sessionId, userId } = this.identity\n\n try {\n const { data } = await this.endpoint.frontend.POST('/api/tracking/identity/v2', {\n body: {\n customerId,\n sessionId,\n userId,\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n },\n })\n\n if (!data) {\n throw new SDKError('No data received from identity API')\n }\n\n this.identity.pageviewId = data.pageviewId\n\n if (!sessionId) {\n this.identity.sessionId = data.sessionId\n setSessionId(data.sessionId)\n }\n if (!userId) {\n this.identity.userId = data.userId\n setUserId(data.userId)\n }\n\n setToken(data.token)\n\n // Add the access token to the Authorization header for all endpoints\n Object.values(this.endpoint).forEach((endpoint) => {\n endpoint.use(authMiddleware(data.token))\n })\n } catch (error) {\n // Enable the auth middleware without a token so that it will throw an error before sending\n // the next request, preventing unnecessary API calls / 401 responses.\n Object.values(this.endpoint).forEach((endpoint) => {\n endpoint.use(authMiddleware())\n })\n throw new SDKError('Failed to create identity', {\n cause: error as Error,\n })\n }\n }\n\n /**\n * Ends the current conversation by deleting the conversation ID.\n *\n * @example\n * ```ts\n * client.endConversation()\n * console.log('Conversation ended')\n * ```\n */\n endConversation(): void {\n deleteConversationId()\n this.identity.conversationId = undefined\n }\n\n /**\n * Clears the existing conversation ID, then generates a new one and returns the opening message.\n *\n * @param context - Optional context to customize the conversation. It can include:\n * @param context.eligibleProducts An array of eligible product IDs.\n * @param context.eligibleBundles An array of eligible bundle IDs.\n * @param context.productOverrides Overrides for product details.\n * @param context.bundleOverrides Overrides for bundle details.\n *\n * @returns A promise that resolves to the opening message.\n *\n * @example\n * ##### Basic usage\n * ```ts\n * const openingMessage = await client.startConversation()\n * console.log('Opening message:', openingMessage)\n * ```\n *\n * ##### With context\n * ```ts\n * const openingMessage = await client.startConversation({ eligibleProducts: ['product-1', 'product-2'], productOverrides: { 'product-1': { price: 40 } })\n * console.log('Opening message:', openingMessage)\n * ```\n */\n async startConversation(context?: components['schemas']['ConversationContext']): Promise<Message[]> {\n this.endConversation()\n\n const conversationContext = {\n ...context,\n }\n\n const { data } = await this.endpoint.conversation.POST(`/api/conversation/v3`, {\n body: {\n type: 'START_CONVERSATION',\n conversationContext,\n },\n })\n\n if (!data) throw new SDKError('No data received from Conversation API')\n\n const [conversationIdMessage, ...rest] = data as [ConversationIdMessage, ...Message[]]\n\n const conversationId = conversationIdMessage.conversationId\n if (!conversationId) {\n throw new SDKError('Conversation ID not received in API response')\n }\n\n setConversationId(conversationId)\n this.identity.conversationId = conversationId\n\n return rest\n }\n\n /**\n * Sends a message in the conversation.\n *\n * @param options - An object containing the user message.\n * @returns A promise that resolves to an array of messages\n *\n * @example\n * ```ts\n * const newMessages = await client.sendMessage({\n * userMessage: 'How can I get support?',\n * })\n *\n * if (newMessages) {\n * console.log('Received messages:', newMessages)\n * } else {\n * console.log('No message received')\n * }\n * ```\n */\n async sendMessage(payload: SendMessagePayload) {\n const conversationId = this.identity.conversationId\n if (!conversationId) {\n throw new SDKError('Conversation ID not set')\n }\n\n const { data } = await this.endpoint.conversation.POST('/api/conversation/v3', {\n body: {\n conversationId,\n ...payload,\n },\n })\n\n if (!data) throw new SDKError('No data received from conversation API')\n\n // Removes any `CONVERSATION_ID` messages from the API response. In reality, these messages will only\n // appear in the response to a `START_CONVERSATION` request.\n return data.filter((message) => message.type !== 'CONVERSATION_ID')\n }\n\n /**\n * Sends an event to the tracking API, with the required properties already set.\n *\n * @param eventName - The name of the event to track.\n * @param properties - Additional properties to include in the event.\n * @returns A promise that resolves once the event is tracked.\n *\n * @example\n * ```ts\n * await client.trackEvent('entry_point-shown')\n * ```\n */\n async trackEvent(eventName: TrackingEvent['eventName'], properties?: TrackingEvent['additionalProperties']) {\n const body: TrackingEvent = {\n additionalProperties: properties,\n conversationId: this.identity.conversationId,\n eventName,\n pageviewId: this.identity.pageviewId ?? 'unknown',\n screenWidth: window.screen.width,\n screenHeight: window.screen.height,\n screenSize: window.screen.width <= 480 ? 'mobile' : 'large',\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n }\n\n return this.endpoint.frontend.POST('/api/tracking/user/v2', {\n body,\n })\n }\n\n /**\n * Gets an existing identity of the user.\n *\n * @returns An Identity object containing `customerId`, `conversationId`, `sessionId`, `userId`.\n *\n * @example\n * ```ts\n * identity = client.getIdentity()\n * console.log('Identity retrieved:', identity)\n * ```\n */\n getIdentity(): Identity {\n return this.identity\n }\n\n /**\n * Gets the JWT from the localStorage.\n *\n * @returns {string | null} the JWT.\n *\n * @example\n * ```ts\n * token = client.getIdentityToken()\n * console.log('Identity token retrieved:', token)\n * ```\n */\n getIdentityToken(): string | null {\n return getToken()\n }\n}\n","/**\n * The key used to store the conversation ID in `sessionStorage`.\n *\n * @ignore\n */\nexport const CONVERSATION_ID = '__15gifts_conversation_id'\n\n/**\n * Deletes the conversation ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { deleteConversationId } from '@15gifts/sdk'\n *\n * deleteConversationId()\n * // The conversation ID will be removed.\n * ```\n */\nexport const deleteConversationId = () => sessionStorage.removeItem(CONVERSATION_ID)\n\n/**\n * Retrieves the conversation ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { getConversationId } from '@15gifts/sdk'\n *\n * const conversationId = getConversationId()\n *\n * if (conversationId) {\n * console.log(`Conversation ID: ${conversationId}`)\n * } else {\n * console.log('No conversation ID found.')\n * }\n * ```\n */\nexport const getConversationId = () => sessionStorage.getItem(CONVERSATION_ID)\n\n/**\n * Stores the given conversation ID in `sessionStorage`.\n *\n * @example\n * ```ts\n * import { setConversationId } from '@15gifts/sdk'\n *\n * setConversationId('ca0ab4ce-f697-41cc-8d0c-081762aace9b')\n * // The conversation ID 'ca0ab4ce-f697-41cc-8d0c-081762aace9b' will be stored.\n * ```\n */\nexport const setConversationId = (conversationId: string) => sessionStorage.setItem(CONVERSATION_ID, conversationId)\n","/**\n * The key used to store the session ID in `sessionStorage`.\n *\n * @ignore\n */\nexport const SESSION_ID = '__15gifts_session_id'\n\n/**\n * Retrieves the session ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { getSessionId } from '@15gifts/sdk'\n *\n * const sessionId = getSessionId()\n *\n * if (sessionId) {\n * console.log(`Session ID: ${sessionId}`)\n * } else {\n * console.log('No session ID found.')\n * }\n * ```\n */\nexport const getSessionId = () => sessionStorage.getItem(SESSION_ID)\n\n/**\n * Stores the given session ID in `sessionStorage`.\n *\n * @example\n * ```ts\n * import { setSessionId } from '@15gifts/sdk'\n *\n * setSessionId('20b2bff6-64a0-4101-bed9-ff545326584a')\n * // The session ID '20b2bff6-64a0-4101-bed9-ff545326584a' will be stored.\n * ```\n */\nexport const setSessionId = (sessionId: string) => sessionStorage.setItem(SESSION_ID, sessionId)\n","const getItemWithExpiry = (key: string) => {\n const itemString = localStorage.getItem(key)\n\n if (!itemString) return null\n\n const item = JSON.parse(itemString) as { expires: number; value: string }\n\n if (Date.now() > item.expires) {\n localStorage.removeItem(key)\n\n return null\n }\n\n return item.value\n}\n\nexport default getItemWithExpiry\n","/**\n * Set an item in localStorage with an expiration time\n * @param key The key under which the value is stored in localStorage\n * @param value The value to be stored\n * @param ttl The time-to-live (TTL) in milliseconds\n */\nconst setItemWithExpiry = (key: string, value: string, ttl: number) => {\n const item = {\n expires: Date.now() + ttl,\n value,\n }\n\n localStorage.setItem(key, JSON.stringify(item))\n}\n\nexport default setItemWithExpiry\n","import { getItemWithExpiry, setItemWithExpiry } from '../utils'\nconst day = 1000 * 60 * 60 * 24\n\n/**\n * The key used to store the user ID in `localStorage`.\n *\n * @ignore\n */\nexport const USER_ID = '__15gifts_user_id'\n\n/**\n * Time-to-live (TTL) for the user ID in milliseconds.\n * Set to 30 days.\n *\n * @ignore\n */\nexport const TTL = day * 30\n\n/**\n * Retrieves the user ID from `localStorage` and updates its expiry time.\n *\n * @example\n * ```ts\n * import { getUserId } from '@15gifts/sdk'\n *\n * const userId = getUserId()\n *\n * if (userId) {\n * console.log(`User ID: ${userId}`)\n * } else {\n * console.log('No user ID found.')\n * }\n * ```\n */\nexport const getUserId = () => {\n const userId = getItemWithExpiry(USER_ID)\n\n // Update the userId with a new expiry time\n // So that it will be valid for another 30 days, rather than 30 days from when it was first set\n if (userId) {\n setUserId(userId)\n }\n\n return userId\n}\n\n/**\n * Stores the given user ID in `localStorage`.\n *\n * @example\n * ```ts\n * import { setUserId } from '@15gifts/sdk'\n *\n * setUserId('5b77656c-ea4c-492f-82bf-7129297c5873')\n * // The user ID '5b77656c-ea4c-492f-82bf-7129297c5873' will be stored with a 30-day expiry.\n * ```\n */\nexport const setUserId = (userId: string) => setItemWithExpiry(USER_ID, userId, TTL)\n","/**\n * The key used to store the JWT in `localStorage`.\n *\n * @ignore\n */\nexport const JWT_TOKEN = '__15gifts_identity_token'\n\n/**\n * Checks if the JWT is expired.\n *\n * @param {string} token - the JWT.\n * @returns {boolean} `true` if expired, `false` otherwise.\n */\nexport const isTokenExpired = (token: string): boolean => {\n try {\n const [, payloadBase64] = token.split('.')\n if (!payloadBase64) {\n throw new Error('Invalid token payload')\n }\n const payload = JSON.parse(atob(payloadBase64))\n\n return payload.exp && Date.now() / 1000 > payload.exp\n } catch (error) {\n console.error('Invalid token format', error)\n return true\n }\n}\n\n/**\n * Retrieves the JWT from `localStorage` and checks if it is expired.\n *\n * @returns {string | null} The JWT if valid, otherwise `null`.\n */\nexport const getToken = (): string | null => {\n const token = localStorage.getItem(JWT_TOKEN)\n\n if (!token || isTokenExpired(token)) {\n localStorage.removeItem(JWT_TOKEN)\n return null\n }\n\n return token\n}\n\n/**\n * Stores the given JWT in `localStorage`.\n *\n * @example\n * ```ts\n * import { setToken } from '@15gifts/sdk'\n *\n * setToken('ey...')\n * ```\n */\nexport const setToken = (token: string) => localStorage.setItem(JWT_TOKEN, token)\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for adding an `Authorization` header to requests.\n *\n * @param accessToken - The token to be included in the `Authorization` header.\n * @returns A middleware object that attaches the access token to the request headers.\n *\n * @example\n * ```ts\n * import { authMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(authMiddleware(accessToken))\n * ```\n */\nconst authMiddleware = (accessToken?: string): Middleware => ({\n onRequest: async ({ request }) => {\n const isIdentityEndpoint = request.url.includes('/identity/')\n if (isIdentityEndpoint) {\n return request\n }\n\n // Throw an error because we know the API will return a 401 if the access token is not set.\n if (!accessToken) {\n throw new Error('Access token is required for authentication.')\n }\n\n request.headers.set('Authorization', `Bearer ${accessToken}`)\n\n return request\n },\n})\n\nexport default authMiddleware\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for handling errors.\n *\n * @returns A middleware object that throws an error if the response is not ok.\n *\n * @example\n * ```ts\n * import { errorMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(errorMiddleware())\n * ```\n */\nconst errorMiddleware: Middleware = {\n // onError does not handle error responses with 4xx or 5xx HTTP status codes, since these are considered \"successful\" responses but with a bad status code.\n // In these cases we need to check the response's status property or ok() method via the onResponse callback.\n onResponse: async ({ response }) => {\n if (!response.ok) {\n const data = await response.json()\n\n throw new Error(data.message)\n }\n\n return response\n },\n}\n\nexport default errorMiddleware\n","import type { Middleware } from 'openapi-fetch'\n\nimport { Identity } from '../types'\n\n/**\n * Middleware for adding request headers that other services use for tracking.\n *\n * @returns A middleware object that throws an error if the response is not ok.\n *\n * @example\n * ```ts\n * import { pageViewId } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(headerMiddleware('123', 'https://example.com'))\n * ```\n */\nconst headerMiddleware = (identity: Identity, url: string): Middleware => ({\n onRequest: async ({ request }) => {\n if (identity.pageviewId) {\n request.headers.set('X-PAGEVIEW-ID', identity.pageviewId)\n }\n if (url) {\n request.headers.set('X-PAGE-URL', url)\n }\n\n return request\n },\n})\n\nexport default headerMiddleware\n","{\n \"name\": \"@15gifts/sdk\",\n \"version\": \"0.16.2\",\n \"files\": [\n \"dist\"\n ],\n \"main\": \"./dist/index.js\",\n \"module\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"scripts\": {\n \"build\": \"tsup\",\n \"coverage\": \"vitest run --coverage\",\n \"generate-types\": \"npx openapi-typescript\",\n \"dev\": \"tsup --watch\",\n \"format\": \"prettier . --write\",\n \"lint\": \"eslint .\",\n \"test:watch\": \"vitest\",\n \"test\": \"vitest run\",\n \"typecheck\": \"tsc\",\n \"update-schemas\": \"node --experimental-strip-types update-schema.ts && npm run generate-types && npm run format\"\n },\n \"dependencies\": {\n \"openapi-fetch\": \"^0.13.4\"\n },\n \"devDependencies\": {\n \"openapi-typescript\": \"^7.6.0\",\n \"tsup\": \"^8.3.6\"\n },\n \"sideEffects\": false,\n \"prettier\": \"prettier-config-custom\"\n}\n","import { version } from '../../package.json'\n\n/**\n * Custom error class for SDK-related errors.\n * Includes the SDK version and an optional cause for better debugging.\n * NOTE: The error.message is intended for developers, not end-users.\n */\nexport default class SDKError extends Error {\n sdkVersion: string\n override cause?: Error\n\n constructor(userMessage: string, { cause }: { cause?: Error } = {}) {\n super(userMessage)\n this.name = 'SDKError'\n this.cause = cause\n this.sdkVersion = version\n\n // Set the prototype explicitly to maintain instanceof checks\n Object.setPrototypeOf(this, SDKError.prototype)\n }\n}\n"],"mappings":"AAAA,OAAOA,MAA0C,gBCK1C,IAAMC,EAAkB,4BAalBC,EAAuB,IAAM,eAAe,WAAWD,CAAe,EAkBtEE,EAAoB,IAAM,eAAe,QAAQF,CAAe,EAahEG,EAAqBC,GAA2B,eAAe,QAAQJ,EAAiBI,CAAc,EC5C5G,IAAMC,EAAa,uBAkBbC,EAAe,IAAM,eAAe,QAAQD,CAAU,EAatDE,EAAgBC,GAAsB,eAAe,QAAQH,EAAYG,CAAS,ECpC/F,IAAMC,EAAqBC,GAAgB,CACzC,IAAMC,EAAa,aAAa,QAAQD,CAAG,EAE3C,GAAI,CAACC,EAAY,OAAO,KAExB,IAAMC,EAAO,KAAK,MAAMD,CAAU,EAElC,OAAI,KAAK,IAAI,EAAIC,EAAK,SACpB,aAAa,WAAWF,CAAG,EAEpB,MAGFE,EAAK,KACd,EAEOC,EAAQJ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AAGC,CAAI,EAAIZ,EAEnCa,EAAiBF,EAAsB,eAC7C,GAAI,CAACE,EACH,MAAM,IAAIZ,EAAS,8CAA8C,EAGnE,OAAAa,EAAkBD,CAAc,EAChC,KAAK,SAAS,eAAiBA,EAExBD,CACT,CAqBA,MAAM,YAAYG,EAA6B,CAC7C,IAAMF,EAAiB,KAAK,SAAS,eACrC,GAAI,CAACA,EACH,MAAM,IAAIZ,EAAS,yBAAyB,EAG9C,GAAM,CAAE,KAAAD,CAAK,EAAI,MAAM,KAAK,SAAS,aAAa,KAAK,uBAAwB,CAC7E,KAAM,CACJ,eAAAa,EACA,GAAGE,CACL,CACF,CAAC,EAED,GAAI,CAACf,EAAM,MAAM,IAAIC,EAAS,wCAAwC,EAItE,OAAOD,EAAK,OAAQgB,GAAYA,EAAQ,OAAS,iBAAiB,CACpE,CAcA,MAAM,WAAWC,EAAuCC,EAAoD,CAC1G,IAAMC,EAAsB,CAC1B,qBAAsBD,EACtB,eAAgB,KAAK,SAAS,eAC9B,UAAAD,EACA,WAAY,KAAK,SAAS,YAAc,UACxC,YAAa,OAAO,OAAO,MAC3B,aAAc,OAAO,OAAO,OAC5B,WAAY,OAAO,OAAO,OAAS,IAAM,SAAW,QACpD,IAAK,OAAO,SAAS,KACrB,UAAW,OAAO,UAAU,SAC9B,EAEA,OAAO,KAAK,SAAS,SAAS,KAAK,wBAAyB,CAC1D,KAAAE,CACF,CAAC,CACH,CAaA,aAAwB,CACtB,OAAO,KAAK,QACd,CAaA,kBAAkC,CAChC,OAAOC,EAAS,CAClB,CACF","names":["createClient","CONVERSATION_ID","deleteConversationId","getConversationId","setConversationId","conversationId","SESSION_ID","getSessionId","setSessionId","sessionId","getItemWithExpiry","key","itemString","item","getItemWithExpiry_default","setItemWithExpiry","key","value","ttl","item","setItemWithExpiry_default","day","USER_ID","TTL","getUserId","userId","getItemWithExpiry_default","setUserId","setItemWithExpiry_default","JWT_TOKEN","isTokenExpired","token","payloadBase64","payload","error","getToken","setToken","authMiddleware","accessToken","request","auth_default","errorMiddleware","response","data","error_default","headerMiddleware","identity","url","request","headers_default","version","SDKError","_SDKError","userMessage","cause","version","Client","config","conversationUrl","customerId","fetch","frontendUrl","defaultHeaders","headers","version","createClient","getConversationId","getSessionId","getUserId","error_default","headers_default","sessionId","userId","data","SDKError","setSessionId","setUserId","setToken","endpoint","auth_default","error","deleteConversationId","context","conversationContext","conversationIdMessage","rest","conversationId","setConversationId","payload","message","eventName","properties","body","getToken"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@15gifts/sdk",
|
|
3
|
-
"version": "0.16.
|
|
3
|
+
"version": "0.16.2",
|
|
4
4
|
"files": [
|
|
5
5
|
"dist"
|
|
6
6
|
],
|
|
@@ -8,15 +8,16 @@
|
|
|
8
8
|
"module": "./dist/index.mjs",
|
|
9
9
|
"types": "./dist/index.d.ts",
|
|
10
10
|
"scripts": {
|
|
11
|
-
"build": "
|
|
11
|
+
"build": "tsup",
|
|
12
12
|
"coverage": "vitest run --coverage",
|
|
13
|
+
"generate-types": "npx openapi-typescript",
|
|
13
14
|
"dev": "tsup --watch",
|
|
14
15
|
"format": "prettier . --write",
|
|
15
|
-
"generate": "npx openapi-typescript",
|
|
16
16
|
"lint": "eslint .",
|
|
17
|
-
"test": "vitest run",
|
|
18
17
|
"test:watch": "vitest",
|
|
19
|
-
"
|
|
18
|
+
"test": "vitest run",
|
|
19
|
+
"typecheck": "tsc",
|
|
20
|
+
"update-schemas": "node --experimental-strip-types update-schema.ts && npm run generate-types && npm run format"
|
|
20
21
|
},
|
|
21
22
|
"dependencies": {
|
|
22
23
|
"openapi-fetch": "^0.13.4"
|