@15gifts/sdk 0.30.0 → 0.30.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/dist/index.d.mts +173 -15
- package/dist/index.d.ts +173 -15
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -70,15 +70,14 @@ interface components {
|
|
|
70
70
|
* Address
|
|
71
71
|
* @description What the address sheet collects.
|
|
72
72
|
*
|
|
73
|
-
*
|
|
74
|
-
*
|
|
75
|
-
* through. Verified against Spectrum for every unit at our one multi-dwelling test address:
|
|
76
|
-
* a combined line resolves to the same location as sending the unit in its own field, with
|
|
77
|
-
* or without a comma before it.
|
|
73
|
+
* The unit of a multi-dwelling address goes in `addressLine2`, as humara-integrations'
|
|
74
|
+
* `Address` does.
|
|
78
75
|
*/
|
|
79
76
|
Address: {
|
|
80
77
|
/** Addressline1 */
|
|
81
78
|
addressLine1: string;
|
|
79
|
+
/** Addressline2 */
|
|
80
|
+
addressLine2?: string | null;
|
|
82
81
|
/** Postcode */
|
|
83
82
|
postcode: string;
|
|
84
83
|
};
|
|
@@ -532,7 +531,9 @@ interface components {
|
|
|
532
531
|
*/
|
|
533
532
|
productOverrides?: {
|
|
534
533
|
[key: string]: {
|
|
535
|
-
[key: string]: string | number |
|
|
534
|
+
[key: string]: string | number | {
|
|
535
|
+
[key: string]: unknown;
|
|
536
|
+
} | unknown[];
|
|
536
537
|
};
|
|
537
538
|
} | null;
|
|
538
539
|
/**
|
|
@@ -556,7 +557,9 @@ interface components {
|
|
|
556
557
|
*/
|
|
557
558
|
bundleOverrides?: {
|
|
558
559
|
[key: string]: {
|
|
559
|
-
[key: string]: string | number |
|
|
560
|
+
[key: string]: string | number | {
|
|
561
|
+
[key: string]: unknown;
|
|
562
|
+
} | unknown[];
|
|
560
563
|
};
|
|
561
564
|
} | null;
|
|
562
565
|
/**
|
|
@@ -573,7 +576,9 @@ interface components {
|
|
|
573
576
|
*/
|
|
574
577
|
offerOverrides?: {
|
|
575
578
|
[key: string]: {
|
|
576
|
-
[key: string]: string | number |
|
|
579
|
+
[key: string]: string | number | {
|
|
580
|
+
[key: string]: unknown;
|
|
581
|
+
} | unknown[];
|
|
577
582
|
};
|
|
578
583
|
} | null;
|
|
579
584
|
/**
|
|
@@ -648,10 +653,11 @@ interface components {
|
|
|
648
653
|
* @description The normalised result of an address check.
|
|
649
654
|
*
|
|
650
655
|
* These string values are a contract with the frontend, which branches on them. Partners
|
|
651
|
-
* describe serviceability in their own vocabulary; every provider maps onto these
|
|
656
|
+
* describe serviceability in their own vocabulary; every provider maps onto these.
|
|
657
|
+
* humara-integrations' `LocalisationOutcome` must list the same values.
|
|
652
658
|
* @enum {string}
|
|
653
659
|
*/
|
|
654
|
-
LocalisationOutcome: 'resolved' | 'needs_unit' | 'no_match' | 'not_serviceable' | 'not_eligible' | 'needs_human';
|
|
660
|
+
LocalisationOutcome: 'resolved' | 'needs_unit' | 'no_match' | 'not_serviceable' | 'not_eligible' | 'existing_service' | 'managed_property' | 'needs_human';
|
|
655
661
|
/**
|
|
656
662
|
* LocalisationResult
|
|
657
663
|
* @description A provider's answer, normalised.
|
|
@@ -666,6 +672,8 @@ interface components {
|
|
|
666
672
|
* `eligibleProducts`, `eligibleBundles` and `eligibleOffers`.
|
|
667
673
|
*
|
|
668
674
|
* `exitToPhoneNumber` is the number to show when the user has to call to get any further.
|
|
675
|
+
*
|
|
676
|
+
* `exitToUrl` is a page on the customer's site that carries on with the outcome.
|
|
669
677
|
*/
|
|
670
678
|
LocalisationResult: {
|
|
671
679
|
outcome: components['schemas']['LocalisationOutcome'];
|
|
@@ -679,6 +687,8 @@ interface components {
|
|
|
679
687
|
eligibleOffers?: string[] | null;
|
|
680
688
|
/** Exittophonenumber */
|
|
681
689
|
exitToPhoneNumber?: string | null;
|
|
690
|
+
/** Exittourl */
|
|
691
|
+
exitToUrl?: string | null;
|
|
682
692
|
};
|
|
683
693
|
/**
|
|
684
694
|
* Offer
|
|
@@ -2000,6 +2010,128 @@ interface paths {
|
|
|
2000
2010
|
}[];
|
|
2001
2011
|
/** @description A unique user id native to our customers web analytics platforms (adobe, google analytics etc). Helps us & our customers align our data with what customers see in their platforms. */
|
|
2002
2012
|
webAnalyticsPlatformUserId?: string;
|
|
2013
|
+
} | {
|
|
2014
|
+
/**
|
|
2015
|
+
* @description The customer that the event occurred on
|
|
2016
|
+
* @enum {string}
|
|
2017
|
+
*/
|
|
2018
|
+
customerId: 'talkmobile-gb-telco-consumer-en';
|
|
2019
|
+
/**
|
|
2020
|
+
* @description The timestamp describing the time the event occurred. This should conform to ISO 8601 standards and be in UTC
|
|
2021
|
+
* @example 2025-04-01T09:44:16.591Z
|
|
2022
|
+
*/
|
|
2023
|
+
eventAt?: string;
|
|
2024
|
+
/**
|
|
2025
|
+
* @description A JWT used to identify the user in the system, can be obtained from the identity endpoint
|
|
2026
|
+
* @example eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjdXN0b21lcklkIjoiY3VzdG9tZXJJZCIsInNlc3Npb25JZCI6Inh4eHh4eHh4LXh4eHgteHh4eC14eHh4LXh4eHh4eHh4eHh4eCIsInVzZXJJZCI6Inh4eHh4eHh4LXh4eHgteHh4eC14eHh4LXh4eHh4eHh4eHh4eCIsImlhdCI6MTc0MzY3Mzc1OCwiZXhwIjoxNzQ2MjY1NzU4fQ.iD3cXMjnTVxw0TsfEAyi4vEtomGY8RJ9ZMHNa4mngvc
|
|
2027
|
+
*/
|
|
2028
|
+
identityToken?: string | null;
|
|
2029
|
+
/** @description The ID for the sale, a unique value we can correlate with customer records. */
|
|
2030
|
+
saleId: string;
|
|
2031
|
+
/**
|
|
2032
|
+
* @description The type of user, for example, existing or prospect.
|
|
2033
|
+
* @enum {string}
|
|
2034
|
+
*/
|
|
2035
|
+
userType: 'existing' | 'prospect';
|
|
2036
|
+
/**
|
|
2037
|
+
* @description The browser the user is using, e.g. Chrome, Firefox, Safari, etc.
|
|
2038
|
+
* @example Chrome
|
|
2039
|
+
* @example Firefox
|
|
2040
|
+
* @example Safari
|
|
2041
|
+
*/
|
|
2042
|
+
browser?: string;
|
|
2043
|
+
/** @description The user agent string e.g. "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" */
|
|
2044
|
+
userAgent?: string;
|
|
2045
|
+
/** @description The device screen width in pixels - window.screen.width in JS. This is a user level property that should never change. */
|
|
2046
|
+
screenWidth?: number;
|
|
2047
|
+
/** @description The device screen height in pixels - window.screen.height in JS. This is a user level property that should never change. */
|
|
2048
|
+
screenHeight?: number;
|
|
2049
|
+
/**
|
|
2050
|
+
* @description The size of the device's screen, based off the actual user experience it will generate, assuming the browser window takes up the whole screen.
|
|
2051
|
+
*
|
|
2052
|
+
* Based off https://15gifts.atlassian.net/wiki/spaces/AI/pages/3981443139/Breakpoints+for+mobile+desktop
|
|
2053
|
+
*
|
|
2054
|
+
* screen_width <= 480px = 'mobile'
|
|
2055
|
+
* screen_width > 480px = 'large'
|
|
2056
|
+
* @enum {string}
|
|
2057
|
+
*/
|
|
2058
|
+
screenSize?: 'mobile' | 'large';
|
|
2059
|
+
/**
|
|
2060
|
+
* @description "A code that represents what currency the product price is listed in e.g. USD, GBP. This should match the ISO 4217 standard - see https://www.iban.com/currency-codes.
|
|
2061
|
+
* @example USD
|
|
2062
|
+
* @example GBP
|
|
2063
|
+
* @example EUR
|
|
2064
|
+
*/
|
|
2065
|
+
currencyCode?: string;
|
|
2066
|
+
/** @description The host/domain of the URL at the time the event is fired */
|
|
2067
|
+
siteHost?: string;
|
|
2068
|
+
/** @description The path of the URL (including an initial `/`) at the time the event is fired */
|
|
2069
|
+
sitePath?: string;
|
|
2070
|
+
/** @description The query string of the URL (including an initial `?`) at the time the event is fired */
|
|
2071
|
+
siteQueryString?: string;
|
|
2072
|
+
/**
|
|
2073
|
+
* @description The language of the part of the site the sales data is coming from in ISO 639-1 format e.g. 'en-us', 'es-us' etc.
|
|
2074
|
+
* @example en-us
|
|
2075
|
+
* @example es-us
|
|
2076
|
+
*/
|
|
2077
|
+
language?: string;
|
|
2078
|
+
/** @description The recurring payment due per payment period */
|
|
2079
|
+
priceRecurring?: number;
|
|
2080
|
+
/**
|
|
2081
|
+
* @description An ISO-8601 duration that represents the period of time that the priceRecurring payment recurs over
|
|
2082
|
+
* @example P1Y
|
|
2083
|
+
* @example P1M
|
|
2084
|
+
* @example P4W
|
|
2085
|
+
* @example P1D
|
|
2086
|
+
* @example P30D
|
|
2087
|
+
*/
|
|
2088
|
+
priceRecurringPeriod?: string;
|
|
2089
|
+
/** @description The upfront price the user has to pay for the product. */
|
|
2090
|
+
priceUpfront?: number;
|
|
2091
|
+
/** @description The full basket value of the sale, inclusive of any offers. */
|
|
2092
|
+
totalValueOfSale?: number;
|
|
2093
|
+
/** @description The taxes the user has to pay relating to the priceUpfront of the product(s) */
|
|
2094
|
+
totalUpfrontTax?: number;
|
|
2095
|
+
/** @description The taxes the user has to pay relating to the priceRecurring of the product(s), due per payment period */
|
|
2096
|
+
totalRecurringTax?: number;
|
|
2097
|
+
totalTaxOnSale?: number;
|
|
2098
|
+
/** @description A list containing separate line items for each product sold. */
|
|
2099
|
+
productsSold: {
|
|
2100
|
+
/** @description The ID or SKU of a product that is provided by the customer */
|
|
2101
|
+
siteProductId?: string;
|
|
2102
|
+
/** @description The name of the product */
|
|
2103
|
+
siteProductName: string;
|
|
2104
|
+
/** @description The category of products the product belongs to. */
|
|
2105
|
+
siteProductType: string;
|
|
2106
|
+
/**
|
|
2107
|
+
* @description An ISO-8601 duration that represents the contract length
|
|
2108
|
+
* @example P1Y
|
|
2109
|
+
* @example P1M
|
|
2110
|
+
* @example P4W
|
|
2111
|
+
* @example P1D
|
|
2112
|
+
* @example P30D
|
|
2113
|
+
*/
|
|
2114
|
+
productContractLength: string;
|
|
2115
|
+
/** @description An integer representing how many of this particular product the user is purchasing */
|
|
2116
|
+
quantity: number;
|
|
2117
|
+
/** @description The upfront price the user has to pay for the product. */
|
|
2118
|
+
productPriceUpfront: number;
|
|
2119
|
+
/** @description The recurring payment per payment period for the product */
|
|
2120
|
+
productPricePerPeriod: number;
|
|
2121
|
+
/**
|
|
2122
|
+
* @description An ISO-8601 duration that represents the period of time that the productPricePerPeriod payment recurs over
|
|
2123
|
+
* @example P1Y
|
|
2124
|
+
* @example P1M
|
|
2125
|
+
* @example P4W
|
|
2126
|
+
* @example P1D
|
|
2127
|
+
* @example P30D
|
|
2128
|
+
*/
|
|
2129
|
+
productRecurringPaymentPeriod: string;
|
|
2130
|
+
/** @description The ID or SKU of a bundle that the product (and other products being purchased at the same time) are part of */
|
|
2131
|
+
bundleId?: string;
|
|
2132
|
+
}[];
|
|
2133
|
+
/** @description A unique user id native to our customers web analytics platforms (adobe, google analytics etc). Helps us & our customers align our data with what customers see in their platforms. */
|
|
2134
|
+
webAnalyticsPlatformUserId?: string;
|
|
2003
2135
|
};
|
|
2004
2136
|
};
|
|
2005
2137
|
};
|
|
@@ -2183,6 +2315,13 @@ interface paths {
|
|
|
2183
2315
|
};
|
|
2184
2316
|
};
|
|
2185
2317
|
};
|
|
2318
|
+
/** @description Default Response */
|
|
2319
|
+
404: {
|
|
2320
|
+
headers: {
|
|
2321
|
+
[name: string]: unknown;
|
|
2322
|
+
};
|
|
2323
|
+
content?: never;
|
|
2324
|
+
};
|
|
2186
2325
|
};
|
|
2187
2326
|
};
|
|
2188
2327
|
delete?: never;
|
|
@@ -2370,10 +2509,27 @@ interface paths {
|
|
|
2370
2509
|
* 0U, 0A, 1U, 1A, 2U, 2A...
|
|
2371
2510
|
*/
|
|
2372
2511
|
conversation_turn_num?: number;
|
|
2373
|
-
/** @description The time-on-page threshold the user has just passed, in seconds. Sent as the threshold that fired, not as a live elapsed time, so each value appears at most once per page view. */
|
|
2374
|
-
time_on_page_seconds?: string;
|
|
2375
2512
|
/** @description The reason an exit to chat response was provided by the conversation api */
|
|
2376
2513
|
exit_to_chat_reason?: string;
|
|
2514
|
+
/** @description The time-on-page threshold the user has just passed, in seconds. Sent as the threshold that fired, not as a live elapsed time, so each value appears at most once per page view. */
|
|
2515
|
+
time_on_page_seconds?: string;
|
|
2516
|
+
/**
|
|
2517
|
+
* @description A unique ID for one showing of the address checker, and for the localisation it produces. A new ID is created each time the address checker is shown, including when a user closes it and it is shown again. Retries within the same showing keep the same ID. Once the address check succeeds, the same ID is sent on every conversation that uses that localisation, so a conversation can be linked back to the address check that localised it. It is a random ID and is never derived from the address.
|
|
2518
|
+
*
|
|
2519
|
+
* Should match UUID V4 (RFC 9562), e.g. f81d4fae-7dec-41d0-a765-00a0c91e6bf6
|
|
2520
|
+
*/
|
|
2521
|
+
localisation_id?: string;
|
|
2522
|
+
/**
|
|
2523
|
+
* @description The result of checking the address the user entered against the customer's availability service. The accepted values are based on the image below:
|
|
2524
|
+
*
|
|
2525
|
+
*
|
|
2526
|
+
*
|
|
2527
|
+
* Note that there are 2 extra allowed outcomes not in the screenshot:
|
|
2528
|
+
*
|
|
2529
|
+
* not_eligible - legitimate outcome that comes from the integration, screenshot is just out of date
|
|
2530
|
+
* integration_failed - not an outcome provided by the integration, instead just tells us the integration timed out or errored
|
|
2531
|
+
*/
|
|
2532
|
+
address_checker_outcome?: string;
|
|
2377
2533
|
};
|
|
2378
2534
|
/**
|
|
2379
2535
|
* @description A 36 character hash, 5 segments, separated by dashes that uniquely identifies a conversation
|
|
@@ -2384,7 +2540,7 @@ interface paths {
|
|
|
2384
2540
|
* @description Event Name
|
|
2385
2541
|
* @enum {string}
|
|
2386
2542
|
*/
|
|
2387
|
-
eventName: 'entry_point-shown' | 'feedback_submit-clicked' | 'page-shown' | 'tool_ui-closed' | 'feedback-shown' | 'feedback_skip-clicked' | 'entry_point-clicked' | 'tool_close-clicked' | 'exit_to_chat-completed' | 'exit_to_purchase-completed' | 'experiment_variation-assigned' | 'entry_point-closed' | 'entry_point-suppressed' | 'user-created' | 'exit_to_human-completed' | 'rec_card_feedback-clicked' | 'message_select_option-clicked' | 'rec_card_cta-clicked' | 'exit_to_purchase-shown' | 'exit_to_purchase_card_cta-clicked' | 'customisations_screen-shown' | 'time_on_page-elapsed' | '
|
|
2543
|
+
eventName: 'entry_point-shown' | 'feedback_submit-clicked' | 'page-shown' | 'tool_ui-closed' | 'feedback-shown' | 'feedback_skip-clicked' | 'entry_point-clicked' | 'tool_close-clicked' | 'exit_to_chat-completed' | 'exit_to_purchase-completed' | 'experiment_variation-assigned' | 'entry_point-closed' | 'entry_point-suppressed' | 'user-created' | 'exit_to_human-completed' | 'rec_card_feedback-clicked' | 'message_select_option-clicked' | 'rec_card_cta-clicked' | 'exit_to_purchase-shown' | 'exit_to_purchase_card_cta-clicked' | 'customisations_screen-shown' | 'exit_to_customer_channel-completed' | 'time_on_page-elapsed' | 'address_checker-shown' | 'address_checker_submit-clicked' | 'address_checker_cancel-clicked' | 'address_checker-completed';
|
|
2388
2544
|
/**
|
|
2389
2545
|
* @description A 36 character hash, 5 segments, separated by dashes that uniquely identifies a page view (page-shown event)
|
|
2390
2546
|
* @example 1a1a1a1a-1a1a-1a1a-1a1a-1a1a1a1a1a1a
|
|
@@ -2785,11 +2941,13 @@ declare class Client {
|
|
|
2785
2941
|
message_select_options?: unknown[];
|
|
2786
2942
|
button_text?: string;
|
|
2787
2943
|
conversation_turn_num?: number;
|
|
2788
|
-
time_on_page_seconds?: string;
|
|
2789
2944
|
exit_to_chat_reason?: string;
|
|
2945
|
+
time_on_page_seconds?: string;
|
|
2946
|
+
localisation_id?: string;
|
|
2947
|
+
address_checker_outcome?: string;
|
|
2790
2948
|
};
|
|
2791
2949
|
conversationId?: string;
|
|
2792
|
-
eventName: "entry_point-shown" | "feedback_submit-clicked" | "page-shown" | "tool_ui-closed" | "feedback-shown" | "feedback_skip-clicked" | "entry_point-clicked" | "tool_close-clicked" | "exit_to_chat-completed" | "exit_to_purchase-completed" | "experiment_variation-assigned" | "entry_point-closed" | "entry_point-suppressed" | "user-created" | "exit_to_human-completed" | "rec_card_feedback-clicked" | "message_select_option-clicked" | "rec_card_cta-clicked" | "exit_to_purchase-shown" | "exit_to_purchase_card_cta-clicked" | "customisations_screen-shown" | "time_on_page-elapsed" | "
|
|
2950
|
+
eventName: "entry_point-shown" | "feedback_submit-clicked" | "page-shown" | "tool_ui-closed" | "feedback-shown" | "feedback_skip-clicked" | "entry_point-clicked" | "tool_close-clicked" | "exit_to_chat-completed" | "exit_to_purchase-completed" | "experiment_variation-assigned" | "entry_point-closed" | "entry_point-suppressed" | "user-created" | "exit_to_human-completed" | "rec_card_feedback-clicked" | "message_select_option-clicked" | "rec_card_cta-clicked" | "exit_to_purchase-shown" | "exit_to_purchase_card_cta-clicked" | "customisations_screen-shown" | "exit_to_customer_channel-completed" | "time_on_page-elapsed" | "address_checker-shown" | "address_checker_submit-clicked" | "address_checker_cancel-clicked" | "address_checker-completed";
|
|
2793
2951
|
pageviewId: string;
|
|
2794
2952
|
screenHeight?: number;
|
|
2795
2953
|
screenSize?: "mobile" | "large";
|
package/dist/index.d.ts
CHANGED
|
@@ -70,15 +70,14 @@ interface components {
|
|
|
70
70
|
* Address
|
|
71
71
|
* @description What the address sheet collects.
|
|
72
72
|
*
|
|
73
|
-
*
|
|
74
|
-
*
|
|
75
|
-
* through. Verified against Spectrum for every unit at our one multi-dwelling test address:
|
|
76
|
-
* a combined line resolves to the same location as sending the unit in its own field, with
|
|
77
|
-
* or without a comma before it.
|
|
73
|
+
* The unit of a multi-dwelling address goes in `addressLine2`, as humara-integrations'
|
|
74
|
+
* `Address` does.
|
|
78
75
|
*/
|
|
79
76
|
Address: {
|
|
80
77
|
/** Addressline1 */
|
|
81
78
|
addressLine1: string;
|
|
79
|
+
/** Addressline2 */
|
|
80
|
+
addressLine2?: string | null;
|
|
82
81
|
/** Postcode */
|
|
83
82
|
postcode: string;
|
|
84
83
|
};
|
|
@@ -532,7 +531,9 @@ interface components {
|
|
|
532
531
|
*/
|
|
533
532
|
productOverrides?: {
|
|
534
533
|
[key: string]: {
|
|
535
|
-
[key: string]: string | number |
|
|
534
|
+
[key: string]: string | number | {
|
|
535
|
+
[key: string]: unknown;
|
|
536
|
+
} | unknown[];
|
|
536
537
|
};
|
|
537
538
|
} | null;
|
|
538
539
|
/**
|
|
@@ -556,7 +557,9 @@ interface components {
|
|
|
556
557
|
*/
|
|
557
558
|
bundleOverrides?: {
|
|
558
559
|
[key: string]: {
|
|
559
|
-
[key: string]: string | number |
|
|
560
|
+
[key: string]: string | number | {
|
|
561
|
+
[key: string]: unknown;
|
|
562
|
+
} | unknown[];
|
|
560
563
|
};
|
|
561
564
|
} | null;
|
|
562
565
|
/**
|
|
@@ -573,7 +576,9 @@ interface components {
|
|
|
573
576
|
*/
|
|
574
577
|
offerOverrides?: {
|
|
575
578
|
[key: string]: {
|
|
576
|
-
[key: string]: string | number |
|
|
579
|
+
[key: string]: string | number | {
|
|
580
|
+
[key: string]: unknown;
|
|
581
|
+
} | unknown[];
|
|
577
582
|
};
|
|
578
583
|
} | null;
|
|
579
584
|
/**
|
|
@@ -648,10 +653,11 @@ interface components {
|
|
|
648
653
|
* @description The normalised result of an address check.
|
|
649
654
|
*
|
|
650
655
|
* These string values are a contract with the frontend, which branches on them. Partners
|
|
651
|
-
* describe serviceability in their own vocabulary; every provider maps onto these
|
|
656
|
+
* describe serviceability in their own vocabulary; every provider maps onto these.
|
|
657
|
+
* humara-integrations' `LocalisationOutcome` must list the same values.
|
|
652
658
|
* @enum {string}
|
|
653
659
|
*/
|
|
654
|
-
LocalisationOutcome: 'resolved' | 'needs_unit' | 'no_match' | 'not_serviceable' | 'not_eligible' | 'needs_human';
|
|
660
|
+
LocalisationOutcome: 'resolved' | 'needs_unit' | 'no_match' | 'not_serviceable' | 'not_eligible' | 'existing_service' | 'managed_property' | 'needs_human';
|
|
655
661
|
/**
|
|
656
662
|
* LocalisationResult
|
|
657
663
|
* @description A provider's answer, normalised.
|
|
@@ -666,6 +672,8 @@ interface components {
|
|
|
666
672
|
* `eligibleProducts`, `eligibleBundles` and `eligibleOffers`.
|
|
667
673
|
*
|
|
668
674
|
* `exitToPhoneNumber` is the number to show when the user has to call to get any further.
|
|
675
|
+
*
|
|
676
|
+
* `exitToUrl` is a page on the customer's site that carries on with the outcome.
|
|
669
677
|
*/
|
|
670
678
|
LocalisationResult: {
|
|
671
679
|
outcome: components['schemas']['LocalisationOutcome'];
|
|
@@ -679,6 +687,8 @@ interface components {
|
|
|
679
687
|
eligibleOffers?: string[] | null;
|
|
680
688
|
/** Exittophonenumber */
|
|
681
689
|
exitToPhoneNumber?: string | null;
|
|
690
|
+
/** Exittourl */
|
|
691
|
+
exitToUrl?: string | null;
|
|
682
692
|
};
|
|
683
693
|
/**
|
|
684
694
|
* Offer
|
|
@@ -2000,6 +2010,128 @@ interface paths {
|
|
|
2000
2010
|
}[];
|
|
2001
2011
|
/** @description A unique user id native to our customers web analytics platforms (adobe, google analytics etc). Helps us & our customers align our data with what customers see in their platforms. */
|
|
2002
2012
|
webAnalyticsPlatformUserId?: string;
|
|
2013
|
+
} | {
|
|
2014
|
+
/**
|
|
2015
|
+
* @description The customer that the event occurred on
|
|
2016
|
+
* @enum {string}
|
|
2017
|
+
*/
|
|
2018
|
+
customerId: 'talkmobile-gb-telco-consumer-en';
|
|
2019
|
+
/**
|
|
2020
|
+
* @description The timestamp describing the time the event occurred. This should conform to ISO 8601 standards and be in UTC
|
|
2021
|
+
* @example 2025-04-01T09:44:16.591Z
|
|
2022
|
+
*/
|
|
2023
|
+
eventAt?: string;
|
|
2024
|
+
/**
|
|
2025
|
+
* @description A JWT used to identify the user in the system, can be obtained from the identity endpoint
|
|
2026
|
+
* @example eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjdXN0b21lcklkIjoiY3VzdG9tZXJJZCIsInNlc3Npb25JZCI6Inh4eHh4eHh4LXh4eHgteHh4eC14eHh4LXh4eHh4eHh4eHh4eCIsInVzZXJJZCI6Inh4eHh4eHh4LXh4eHgteHh4eC14eHh4LXh4eHh4eHh4eHh4eCIsImlhdCI6MTc0MzY3Mzc1OCwiZXhwIjoxNzQ2MjY1NzU4fQ.iD3cXMjnTVxw0TsfEAyi4vEtomGY8RJ9ZMHNa4mngvc
|
|
2027
|
+
*/
|
|
2028
|
+
identityToken?: string | null;
|
|
2029
|
+
/** @description The ID for the sale, a unique value we can correlate with customer records. */
|
|
2030
|
+
saleId: string;
|
|
2031
|
+
/**
|
|
2032
|
+
* @description The type of user, for example, existing or prospect.
|
|
2033
|
+
* @enum {string}
|
|
2034
|
+
*/
|
|
2035
|
+
userType: 'existing' | 'prospect';
|
|
2036
|
+
/**
|
|
2037
|
+
* @description The browser the user is using, e.g. Chrome, Firefox, Safari, etc.
|
|
2038
|
+
* @example Chrome
|
|
2039
|
+
* @example Firefox
|
|
2040
|
+
* @example Safari
|
|
2041
|
+
*/
|
|
2042
|
+
browser?: string;
|
|
2043
|
+
/** @description The user agent string e.g. "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" */
|
|
2044
|
+
userAgent?: string;
|
|
2045
|
+
/** @description The device screen width in pixels - window.screen.width in JS. This is a user level property that should never change. */
|
|
2046
|
+
screenWidth?: number;
|
|
2047
|
+
/** @description The device screen height in pixels - window.screen.height in JS. This is a user level property that should never change. */
|
|
2048
|
+
screenHeight?: number;
|
|
2049
|
+
/**
|
|
2050
|
+
* @description The size of the device's screen, based off the actual user experience it will generate, assuming the browser window takes up the whole screen.
|
|
2051
|
+
*
|
|
2052
|
+
* Based off https://15gifts.atlassian.net/wiki/spaces/AI/pages/3981443139/Breakpoints+for+mobile+desktop
|
|
2053
|
+
*
|
|
2054
|
+
* screen_width <= 480px = 'mobile'
|
|
2055
|
+
* screen_width > 480px = 'large'
|
|
2056
|
+
* @enum {string}
|
|
2057
|
+
*/
|
|
2058
|
+
screenSize?: 'mobile' | 'large';
|
|
2059
|
+
/**
|
|
2060
|
+
* @description "A code that represents what currency the product price is listed in e.g. USD, GBP. This should match the ISO 4217 standard - see https://www.iban.com/currency-codes.
|
|
2061
|
+
* @example USD
|
|
2062
|
+
* @example GBP
|
|
2063
|
+
* @example EUR
|
|
2064
|
+
*/
|
|
2065
|
+
currencyCode?: string;
|
|
2066
|
+
/** @description The host/domain of the URL at the time the event is fired */
|
|
2067
|
+
siteHost?: string;
|
|
2068
|
+
/** @description The path of the URL (including an initial `/`) at the time the event is fired */
|
|
2069
|
+
sitePath?: string;
|
|
2070
|
+
/** @description The query string of the URL (including an initial `?`) at the time the event is fired */
|
|
2071
|
+
siteQueryString?: string;
|
|
2072
|
+
/**
|
|
2073
|
+
* @description The language of the part of the site the sales data is coming from in ISO 639-1 format e.g. 'en-us', 'es-us' etc.
|
|
2074
|
+
* @example en-us
|
|
2075
|
+
* @example es-us
|
|
2076
|
+
*/
|
|
2077
|
+
language?: string;
|
|
2078
|
+
/** @description The recurring payment due per payment period */
|
|
2079
|
+
priceRecurring?: number;
|
|
2080
|
+
/**
|
|
2081
|
+
* @description An ISO-8601 duration that represents the period of time that the priceRecurring payment recurs over
|
|
2082
|
+
* @example P1Y
|
|
2083
|
+
* @example P1M
|
|
2084
|
+
* @example P4W
|
|
2085
|
+
* @example P1D
|
|
2086
|
+
* @example P30D
|
|
2087
|
+
*/
|
|
2088
|
+
priceRecurringPeriod?: string;
|
|
2089
|
+
/** @description The upfront price the user has to pay for the product. */
|
|
2090
|
+
priceUpfront?: number;
|
|
2091
|
+
/** @description The full basket value of the sale, inclusive of any offers. */
|
|
2092
|
+
totalValueOfSale?: number;
|
|
2093
|
+
/** @description The taxes the user has to pay relating to the priceUpfront of the product(s) */
|
|
2094
|
+
totalUpfrontTax?: number;
|
|
2095
|
+
/** @description The taxes the user has to pay relating to the priceRecurring of the product(s), due per payment period */
|
|
2096
|
+
totalRecurringTax?: number;
|
|
2097
|
+
totalTaxOnSale?: number;
|
|
2098
|
+
/** @description A list containing separate line items for each product sold. */
|
|
2099
|
+
productsSold: {
|
|
2100
|
+
/** @description The ID or SKU of a product that is provided by the customer */
|
|
2101
|
+
siteProductId?: string;
|
|
2102
|
+
/** @description The name of the product */
|
|
2103
|
+
siteProductName: string;
|
|
2104
|
+
/** @description The category of products the product belongs to. */
|
|
2105
|
+
siteProductType: string;
|
|
2106
|
+
/**
|
|
2107
|
+
* @description An ISO-8601 duration that represents the contract length
|
|
2108
|
+
* @example P1Y
|
|
2109
|
+
* @example P1M
|
|
2110
|
+
* @example P4W
|
|
2111
|
+
* @example P1D
|
|
2112
|
+
* @example P30D
|
|
2113
|
+
*/
|
|
2114
|
+
productContractLength: string;
|
|
2115
|
+
/** @description An integer representing how many of this particular product the user is purchasing */
|
|
2116
|
+
quantity: number;
|
|
2117
|
+
/** @description The upfront price the user has to pay for the product. */
|
|
2118
|
+
productPriceUpfront: number;
|
|
2119
|
+
/** @description The recurring payment per payment period for the product */
|
|
2120
|
+
productPricePerPeriod: number;
|
|
2121
|
+
/**
|
|
2122
|
+
* @description An ISO-8601 duration that represents the period of time that the productPricePerPeriod payment recurs over
|
|
2123
|
+
* @example P1Y
|
|
2124
|
+
* @example P1M
|
|
2125
|
+
* @example P4W
|
|
2126
|
+
* @example P1D
|
|
2127
|
+
* @example P30D
|
|
2128
|
+
*/
|
|
2129
|
+
productRecurringPaymentPeriod: string;
|
|
2130
|
+
/** @description The ID or SKU of a bundle that the product (and other products being purchased at the same time) are part of */
|
|
2131
|
+
bundleId?: string;
|
|
2132
|
+
}[];
|
|
2133
|
+
/** @description A unique user id native to our customers web analytics platforms (adobe, google analytics etc). Helps us & our customers align our data with what customers see in their platforms. */
|
|
2134
|
+
webAnalyticsPlatformUserId?: string;
|
|
2003
2135
|
};
|
|
2004
2136
|
};
|
|
2005
2137
|
};
|
|
@@ -2183,6 +2315,13 @@ interface paths {
|
|
|
2183
2315
|
};
|
|
2184
2316
|
};
|
|
2185
2317
|
};
|
|
2318
|
+
/** @description Default Response */
|
|
2319
|
+
404: {
|
|
2320
|
+
headers: {
|
|
2321
|
+
[name: string]: unknown;
|
|
2322
|
+
};
|
|
2323
|
+
content?: never;
|
|
2324
|
+
};
|
|
2186
2325
|
};
|
|
2187
2326
|
};
|
|
2188
2327
|
delete?: never;
|
|
@@ -2370,10 +2509,27 @@ interface paths {
|
|
|
2370
2509
|
* 0U, 0A, 1U, 1A, 2U, 2A...
|
|
2371
2510
|
*/
|
|
2372
2511
|
conversation_turn_num?: number;
|
|
2373
|
-
/** @description The time-on-page threshold the user has just passed, in seconds. Sent as the threshold that fired, not as a live elapsed time, so each value appears at most once per page view. */
|
|
2374
|
-
time_on_page_seconds?: string;
|
|
2375
2512
|
/** @description The reason an exit to chat response was provided by the conversation api */
|
|
2376
2513
|
exit_to_chat_reason?: string;
|
|
2514
|
+
/** @description The time-on-page threshold the user has just passed, in seconds. Sent as the threshold that fired, not as a live elapsed time, so each value appears at most once per page view. */
|
|
2515
|
+
time_on_page_seconds?: string;
|
|
2516
|
+
/**
|
|
2517
|
+
* @description A unique ID for one showing of the address checker, and for the localisation it produces. A new ID is created each time the address checker is shown, including when a user closes it and it is shown again. Retries within the same showing keep the same ID. Once the address check succeeds, the same ID is sent on every conversation that uses that localisation, so a conversation can be linked back to the address check that localised it. It is a random ID and is never derived from the address.
|
|
2518
|
+
*
|
|
2519
|
+
* Should match UUID V4 (RFC 9562), e.g. f81d4fae-7dec-41d0-a765-00a0c91e6bf6
|
|
2520
|
+
*/
|
|
2521
|
+
localisation_id?: string;
|
|
2522
|
+
/**
|
|
2523
|
+
* @description The result of checking the address the user entered against the customer's availability service. The accepted values are based on the image below:
|
|
2524
|
+
*
|
|
2525
|
+
*
|
|
2526
|
+
*
|
|
2527
|
+
* Note that there are 2 extra allowed outcomes not in the screenshot:
|
|
2528
|
+
*
|
|
2529
|
+
* not_eligible - legitimate outcome that comes from the integration, screenshot is just out of date
|
|
2530
|
+
* integration_failed - not an outcome provided by the integration, instead just tells us the integration timed out or errored
|
|
2531
|
+
*/
|
|
2532
|
+
address_checker_outcome?: string;
|
|
2377
2533
|
};
|
|
2378
2534
|
/**
|
|
2379
2535
|
* @description A 36 character hash, 5 segments, separated by dashes that uniquely identifies a conversation
|
|
@@ -2384,7 +2540,7 @@ interface paths {
|
|
|
2384
2540
|
* @description Event Name
|
|
2385
2541
|
* @enum {string}
|
|
2386
2542
|
*/
|
|
2387
|
-
eventName: 'entry_point-shown' | 'feedback_submit-clicked' | 'page-shown' | 'tool_ui-closed' | 'feedback-shown' | 'feedback_skip-clicked' | 'entry_point-clicked' | 'tool_close-clicked' | 'exit_to_chat-completed' | 'exit_to_purchase-completed' | 'experiment_variation-assigned' | 'entry_point-closed' | 'entry_point-suppressed' | 'user-created' | 'exit_to_human-completed' | 'rec_card_feedback-clicked' | 'message_select_option-clicked' | 'rec_card_cta-clicked' | 'exit_to_purchase-shown' | 'exit_to_purchase_card_cta-clicked' | 'customisations_screen-shown' | 'time_on_page-elapsed' | '
|
|
2543
|
+
eventName: 'entry_point-shown' | 'feedback_submit-clicked' | 'page-shown' | 'tool_ui-closed' | 'feedback-shown' | 'feedback_skip-clicked' | 'entry_point-clicked' | 'tool_close-clicked' | 'exit_to_chat-completed' | 'exit_to_purchase-completed' | 'experiment_variation-assigned' | 'entry_point-closed' | 'entry_point-suppressed' | 'user-created' | 'exit_to_human-completed' | 'rec_card_feedback-clicked' | 'message_select_option-clicked' | 'rec_card_cta-clicked' | 'exit_to_purchase-shown' | 'exit_to_purchase_card_cta-clicked' | 'customisations_screen-shown' | 'exit_to_customer_channel-completed' | 'time_on_page-elapsed' | 'address_checker-shown' | 'address_checker_submit-clicked' | 'address_checker_cancel-clicked' | 'address_checker-completed';
|
|
2388
2544
|
/**
|
|
2389
2545
|
* @description A 36 character hash, 5 segments, separated by dashes that uniquely identifies a page view (page-shown event)
|
|
2390
2546
|
* @example 1a1a1a1a-1a1a-1a1a-1a1a-1a1a1a1a1a1a
|
|
@@ -2785,11 +2941,13 @@ declare class Client {
|
|
|
2785
2941
|
message_select_options?: unknown[];
|
|
2786
2942
|
button_text?: string;
|
|
2787
2943
|
conversation_turn_num?: number;
|
|
2788
|
-
time_on_page_seconds?: string;
|
|
2789
2944
|
exit_to_chat_reason?: string;
|
|
2945
|
+
time_on_page_seconds?: string;
|
|
2946
|
+
localisation_id?: string;
|
|
2947
|
+
address_checker_outcome?: string;
|
|
2790
2948
|
};
|
|
2791
2949
|
conversationId?: string;
|
|
2792
|
-
eventName: "entry_point-shown" | "feedback_submit-clicked" | "page-shown" | "tool_ui-closed" | "feedback-shown" | "feedback_skip-clicked" | "entry_point-clicked" | "tool_close-clicked" | "exit_to_chat-completed" | "exit_to_purchase-completed" | "experiment_variation-assigned" | "entry_point-closed" | "entry_point-suppressed" | "user-created" | "exit_to_human-completed" | "rec_card_feedback-clicked" | "message_select_option-clicked" | "rec_card_cta-clicked" | "exit_to_purchase-shown" | "exit_to_purchase_card_cta-clicked" | "customisations_screen-shown" | "time_on_page-elapsed" | "
|
|
2950
|
+
eventName: "entry_point-shown" | "feedback_submit-clicked" | "page-shown" | "tool_ui-closed" | "feedback-shown" | "feedback_skip-clicked" | "entry_point-clicked" | "tool_close-clicked" | "exit_to_chat-completed" | "exit_to_purchase-completed" | "experiment_variation-assigned" | "entry_point-closed" | "entry_point-suppressed" | "user-created" | "exit_to_human-completed" | "rec_card_feedback-clicked" | "message_select_option-clicked" | "rec_card_cta-clicked" | "exit_to_purchase-shown" | "exit_to_purchase_card_cta-clicked" | "customisations_screen-shown" | "exit_to_customer_channel-completed" | "time_on_page-elapsed" | "address_checker-shown" | "address_checker_submit-clicked" | "address_checker_cancel-clicked" | "address_checker-completed";
|
|
2793
2951
|
pageviewId: string;
|
|
2794
2952
|
screenHeight?: number;
|
|
2795
2953
|
screenSize?: "mobile" | "large";
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var R=Object.create;var d=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var P=Object.getOwnPropertyNames;var _=Object.getPrototypeOf,k=Object.prototype.hasOwnProperty;var U=(e,t)=>{for(var s in t)d(e,s,{get:t[s],enumerable:!0})},T=(e,t,s,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of P(t))!k.call(e,n)&&n!==s&&d(e,n,{get:()=>t[n],enumerable:!(o=O(t,n))||o.enumerable});return e};var N=(e,t,s)=>(s=e!=null?R(_(e)):{},T(t||!e||!e.__esModule?d(s,"default",{value:e,enumerable:!0}):s,e)),L=e=>T(d({},"__esModule",{value:!0}),e);var oe={};U(oe,{Client:()=>E,SDKError:()=>r,authMiddleware:()=>p,errorMiddleware:()=>g,headerMiddleware:()=>u});module.exports=L(oe);var M=N(require("openapi-fetch"));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},y=b;var V=(e,t,s)=>{let o={expires:Date.now()+s,value:t};localStorage.setItem(e,JSON.stringify(o))},m=V;var D=1e3*60*60*24,G=D*30,f="__15gifts_conversation_id",S="__15gifts_session_id",I="__15gifts_identity_token",x="__15gifts_user_id",j=()=>sessionStorage.removeItem(f),q=()=>sessionStorage.getItem(f),X=e=>sessionStorage.setItem(f,e),H=()=>sessionStorage.getItem(S),K=e=>sessionStorage.setItem(S,e),W=e=>{try{let[,t]=e.split(".");if(!t)throw new Error("Invalid token payload");let s=JSON.parse(atob(t));return s.exp&&Date.now()/1e3>s.exp}catch(t){return console.error("Invalid token format",t),!0}},B=()=>{let e=localStorage.getItem(I);return!e||W(e)?(localStorage.removeItem(I),null):e},$=e=>localStorage.setItem(I,e),F=()=>{let e=y(x);return e&&C(e),e},C=e=>m(x,e,G),c=(e,t,s)=>({enumerable:!0,configurable:!0,get:()=>e()??void 0,set:o=>{if(o){t(o);return}s?.()}}),A=e=>{let t={customerId:e},s={conversationId:c(q,X,j),sessionId:c(H,K),token:c(B,$),userId:c(F,C)};return Object.defineProperties(t,s),t};var J=e=>({onRequest:async({request:t})=>{if(t.url.includes("/identity/"))return t;if(!e)throw new Error("Access token is required for authentication.");return t.headers.set("Authorization",`Bearer ${e}`),t}}),p=J;var z={onResponse:async({response:e})=>{if(!e.ok){let t=await e.json();throw new Error(t.message)}return e}},g=z;var Q=e=>({onRequest:async({request:t})=>(e.pageviewId&&t.headers.set("X-PAGEVIEW-ID",e.pageviewId),t.headers.set("X-PAGE-URL",window.location.href),t)}),u=Q;var Y={MESSAGE:"keep",TITLE:"keep",SINGLE_SELECT:"hideOnceAnswered",MULTI_SELECT:"hideOnceAnswered",EXIT_TO_CHAT:"keep",EXIT_TO_PHONE:"keep",EXIT_TO_PURCHASE:"keep",EXIT_TO_PURCHASE_V2:"keep",RECOMMENDATION:"keep",RECOMMENDATION_V2:"keep",CONVERSATION_ID:"drop"},h=e=>{let{conversationId:t,...s}=e;return s},Z=(e,t)=>t?.assistantMessages.find(n=>n.type==="SINGLE_SELECT")?.options.find(n=>n.value===e.option)?.label||"",ee=(e,t)=>t?.assistantMessages.find(n=>n.type==="MULTI_SELECT")?.options.filter(n=>e.options.includes(n.value))?.map(n=>n.label).join(", ")||"",te=(e,t)=>{let{userMessage:s}=e;switch(s.type){case"SINGLE_SELECT":return{...h(s),userMessage:Z(s,t)};case"START_CONVERSATION":return{type:"MESSAGE",userMessage:s.openingUserMessage?.option||""};case"MESSAGE":return h(s);case"MULTI_SELECT":return{...h(s),userMessage:ee(s,t)}}},se=(e,t)=>{let s=!!t;return e.assistantMessages.filter(o=>{let n=Y[o.type];return n!=="drop"&&!(n==="hideOnceAnswered"&&s)})},w=e=>e.map((t,s)=>{let o=s>0?e[s-1]:void 0,n=s<e.length-1?e[s+1]:void 0;return{id:`restored-turn-${s}`,userMessage:te(t,o),assistantReply:se(t,n)}});var l="0.30.
|
|
1
|
+
"use strict";var R=Object.create;var d=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var P=Object.getOwnPropertyNames;var _=Object.getPrototypeOf,k=Object.prototype.hasOwnProperty;var U=(e,t)=>{for(var s in t)d(e,s,{get:t[s],enumerable:!0})},T=(e,t,s,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of P(t))!k.call(e,n)&&n!==s&&d(e,n,{get:()=>t[n],enumerable:!(o=O(t,n))||o.enumerable});return e};var N=(e,t,s)=>(s=e!=null?R(_(e)):{},T(t||!e||!e.__esModule?d(s,"default",{value:e,enumerable:!0}):s,e)),L=e=>T(d({},"__esModule",{value:!0}),e);var oe={};U(oe,{Client:()=>E,SDKError:()=>r,authMiddleware:()=>p,errorMiddleware:()=>g,headerMiddleware:()=>u});module.exports=L(oe);var M=N(require("openapi-fetch"));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},y=b;var V=(e,t,s)=>{let o={expires:Date.now()+s,value:t};localStorage.setItem(e,JSON.stringify(o))},m=V;var D=1e3*60*60*24,G=D*30,f="__15gifts_conversation_id",S="__15gifts_session_id",I="__15gifts_identity_token",x="__15gifts_user_id",j=()=>sessionStorage.removeItem(f),q=()=>sessionStorage.getItem(f),X=e=>sessionStorage.setItem(f,e),H=()=>sessionStorage.getItem(S),K=e=>sessionStorage.setItem(S,e),W=e=>{try{let[,t]=e.split(".");if(!t)throw new Error("Invalid token payload");let s=JSON.parse(atob(t));return s.exp&&Date.now()/1e3>s.exp}catch(t){return console.error("Invalid token format",t),!0}},B=()=>{let e=localStorage.getItem(I);return!e||W(e)?(localStorage.removeItem(I),null):e},$=e=>localStorage.setItem(I,e),F=()=>{let e=y(x);return e&&C(e),e},C=e=>m(x,e,G),c=(e,t,s)=>({enumerable:!0,configurable:!0,get:()=>e()??void 0,set:o=>{if(o){t(o);return}s?.()}}),A=e=>{let t={customerId:e},s={conversationId:c(q,X,j),sessionId:c(H,K),token:c(B,$),userId:c(F,C)};return Object.defineProperties(t,s),t};var J=e=>({onRequest:async({request:t})=>{if(t.url.includes("/identity/"))return t;if(!e)throw new Error("Access token is required for authentication.");return t.headers.set("Authorization",`Bearer ${e}`),t}}),p=J;var z={onResponse:async({response:e})=>{if(!e.ok){let t=await e.json();throw new Error(t.message)}return e}},g=z;var Q=e=>({onRequest:async({request:t})=>(e.pageviewId&&t.headers.set("X-PAGEVIEW-ID",e.pageviewId),t.headers.set("X-PAGE-URL",window.location.href),t)}),u=Q;var Y={MESSAGE:"keep",TITLE:"keep",SINGLE_SELECT:"hideOnceAnswered",MULTI_SELECT:"hideOnceAnswered",EXIT_TO_CHAT:"keep",EXIT_TO_PHONE:"keep",EXIT_TO_PURCHASE:"keep",EXIT_TO_PURCHASE_V2:"keep",RECOMMENDATION:"keep",RECOMMENDATION_V2:"keep",CONVERSATION_ID:"drop"},h=e=>{let{conversationId:t,...s}=e;return s},Z=(e,t)=>t?.assistantMessages.find(n=>n.type==="SINGLE_SELECT")?.options.find(n=>n.value===e.option)?.label||"",ee=(e,t)=>t?.assistantMessages.find(n=>n.type==="MULTI_SELECT")?.options.filter(n=>e.options.includes(n.value))?.map(n=>n.label).join(", ")||"",te=(e,t)=>{let{userMessage:s}=e;switch(s.type){case"SINGLE_SELECT":return{...h(s),userMessage:Z(s,t)};case"START_CONVERSATION":return{type:"MESSAGE",userMessage:s.openingUserMessage?.option||""};case"MESSAGE":return h(s);case"MULTI_SELECT":return{...h(s),userMessage:ee(s,t)}}},se=(e,t)=>{let s=!!t;return e.assistantMessages.filter(o=>{let n=Y[o.type];return n!=="drop"&&!(n==="hideOnceAnswered"&&s)})},w=e=>e.map((t,s)=>{let o=s>0?e[s-1]:void 0,n=s<e.length-1?e[s+1]:void 0;return{id:`restored-turn-${s}`,userMessage:te(t,o),assistantReply:se(t,n)}});var l="0.30.2";var r=class e extends Error{sdkVersion;cause;constructor(t,{cause:s}={}){super(t),this.name="SDKError",this.cause=s,this.sdkVersion=l,Object.setPrototypeOf(this,e.prototype)}};var E=class{endpoint;identity;constructor(t){let{conversationUrl:s,customerId:o,fetch:n,frontendUrl:i,headers:v}=t,a={...v,"X-SDK-VERSION":l};this.endpoint={conversation:(0,M.default)({baseUrl:s,fetch:n,headers:a,credentials:"include"}),frontend:(0,M.default)({baseUrl:i,fetch:n,headers:a})},this.identity=A(o),this.endpoint.conversation.use(g),this.endpoint.conversation.use(u(this.identity))}async createIdentity(){let{customerId:t,sessionId:s,userId:o}=this.identity;try{let{data:n}=await this.endpoint.frontend.POST("/api/tracking/identity/v2",{body:{customerId:t,sessionId:s,userId:o,url:window.location.href,userAgent:window.navigator.userAgent}});if(!n)throw new r("No data received from identity API");this.identity.pageviewId=n.pageviewId,s||(this.identity.sessionId=n.sessionId),o||(this.identity.userId=n.userId),this.identity.token=n.token,Object.values(this.endpoint).forEach(i=>{i.use(p(n.token))})}catch(n){throw Object.values(this.endpoint).forEach(i=>{i.use(p())}),new r("Failed to create identity",{cause:n})}}endConversation(){this.identity.conversationId=void 0}async startConversation(t,s){this.endConversation();let o={...t},{data:n}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{type:"START_CONVERSATION",conversationContext:o,openingUserMessage:s}});if(!n)throw new r("No data received from Conversation API");let[i,...v]=n,a=i.conversationId;if(!a)throw new r("Conversation ID not received in API response");return this.identity.conversationId=a,v}async sendMessage(t){let s=this.identity.conversationId;if(!s)throw new r("Conversation ID not set");let{data:o}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{conversationId:s,...t}});if(!o)throw new r("No data received from conversation API");return o.filter(n=>n.type!=="CONVERSATION_ID")}async trackEvent(t,s){let o={additionalProperties:s,conversationId:this.identity.conversationId,eventName:t,pageviewId:this.identity.pageviewId??"unknown",screenWidth:window.screen.width,screenHeight:window.screen.height,screenSize:window.screen.width<=480?"mobile":"large",url:window.location.href,userAgent:window.navigator.userAgent};return this.endpoint.frontend.POST("/api/tracking/user/v2",{body:o})}getIdentity(){return this.identity}getIdentityToken(){return this.identity.token??null}async getConversation(t){if(!t)throw new r("Conversation ID not set");try{let{data:s}=await this.endpoint.conversation.GET("/api/conversation/{conversation_id}/v1",{params:{path:{conversation_id:t}}});if(this.identity.conversationId=t,!s)throw new r("No data received from conversation history API");return w(s)}catch(s){throw new r("Failed to get conversation history",{cause:s})}}};0&&(module.exports={Client,SDKError,authMiddleware,errorMiddleware,headerMiddleware});
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/client.ts","../src/utils/getItemWithExpiry.ts","../src/utils/setItemWithExpiry.ts","../src/identity/createIdentityStore.ts","../src/middlewares/auth.ts","../src/middlewares/error.ts","../src/middlewares/headers.ts","../src/restoreConversation/restoreConversation.ts","../package.json","../src/utils/SDKError.ts"],"sourcesContent":["export * from './client'\nexport * from './middlewares'\nexport * from './types'\n","import createClient, { type ClientOptions } from 'openapi-fetch'\n\nimport { createIdentityStore } from './identity/createIdentityStore'\nimport { authMiddleware, errorMiddleware, headerMiddleware } from './middlewares'\nimport { restoreConversation } from './restoreConversation/restoreConversation'\nimport type { components, paths as conversationPaths } from './schemas/conversation'\nimport type { paths as frontendPaths } from './schemas/frontend'\nimport type {\n Config,\n ConversationIdMessage,\n Endpoint,\n Identity,\n Message,\n RestoredTurn,\n SendMessagePayload,\n TrackingEvent,\n UserStartConversationMessage,\n} from './types'\nimport { version } from '../package.json'\nimport SDKError from './utils/SDKError'\n\n/**\n * The `Client` class provides methods to manage 15gifts API.\n */\nexport class Client {\n /**\n * This can be used to interact with the APIs directly. It is recommended to use the [helper methods](/sdk/sdk-reference/classes/client/#methods) provided by the `Client` class instead.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * const { data } = await client.endpoint.conversation.POST('/api/conversation/v3')\n * ```\n */\n endpoint: Endpoint\n\n /**\n * The identity information.\n */\n identity: Identity\n\n /**\n * Creates a new instance of the `Client` class.\n *\n * @param config - Configuration options for initializing the client.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * ```\n */\n constructor(config: Config) {\n const { conversationUrl, customerId, fetch, frontendUrl, headers: defaultHeaders } = config\n\n const headers: ClientOptions['headers'] = {\n ...defaultHeaders,\n 'X-SDK-VERSION': version,\n }\n\n this.endpoint = {\n conversation: createClient<conversationPaths>({\n baseUrl: conversationUrl,\n fetch,\n headers,\n credentials: 'include',\n }),\n frontend: createClient<frontendPaths>({ baseUrl: frontendUrl, fetch, headers }),\n }\n\n this.identity = createIdentityStore(customerId)\n\n this.endpoint.conversation.use(errorMiddleware)\n this.endpoint.conversation.use(headerMiddleware(this.identity))\n }\n\n /**\n * Creates a new identity for the user by generating a session ID and user ID if they don't exist, and sets the access token for future API calls.\n * Ends the current conversation if a conversation ID is present before sending a request to update identity.\n * This should not be called more than once per page load.\n *\n * @returns A promise that resolves once the identity is created and the access token is set.\n *\n * @example\n * ```ts\n * await client.createIdentity()\n * console.log('Identity created:', client.identity)\n * ```\n */\n async createIdentity(): Promise<void> {\n const { customerId, sessionId, userId } = this.identity\n\n try {\n const { data } = await this.endpoint.frontend.POST('/api/tracking/identity/v2', {\n body: {\n customerId,\n sessionId,\n userId,\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n },\n })\n\n if (!data) {\n throw new SDKError('No data received from identity API')\n }\n\n this.identity.pageviewId = data.pageviewId\n\n if (!sessionId) {\n this.identity.sessionId = data.sessionId\n }\n if (!userId) {\n this.identity.userId = data.userId\n }\n\n this.identity.token = data.token\n\n // Add the access token to the Authorization header for all endpoints\n Object.values(this.endpoint).forEach((endpoint) => {\n endpoint.use(authMiddleware(data.token))\n })\n } catch (error) {\n // Enable the auth middleware without a token so that it will throw an error before sending\n // the next request, preventing unnecessary API calls / 401 responses.\n Object.values(this.endpoint).forEach((endpoint) => {\n endpoint.use(authMiddleware())\n })\n throw new SDKError('Failed to create identity', {\n cause: error as Error,\n })\n }\n }\n\n /**\n * Ends the current conversation by deleting the conversation ID.\n *\n * @example\n * ```ts\n * client.endConversation()\n * console.log('Conversation ended')\n * ```\n */\n endConversation(): void {\n this.identity.conversationId = undefined\n }\n\n /**\n * Clears the existing conversation ID, then generates a new one and returns the opening message.\n *\n * @param context - Optional context to customize the conversation. It can include:\n * @param context.eligibleProducts An array of eligible product IDs.\n * @param context.eligibleBundles An array of eligible bundle IDs.\n * @param context.productOverrides Overrides for product details.\n * @param context.bundleOverrides Overrides for bundle details.\n *\n * @returns A promise that resolves to the opening message.\n *\n * @example\n * ##### Basic usage\n * ```ts\n * const openingMessage = await client.startConversation()\n * console.log('Opening message:', openingMessage)\n * ```\n *\n * ##### With context\n * ```ts\n * const openingMessage = await client.startConversation({ eligibleProducts: ['product-1', 'product-2'], productOverrides: { 'product-1': { price: 40 } } })\n * console.log('Opening message:', openingMessage)\n * ```\n */\n async startConversation(\n context?: components['schemas']['ConversationContext'],\n userMessage?: UserStartConversationMessage['openingUserMessage'],\n ): Promise<Message[]> {\n this.endConversation()\n\n const conversationContext = {\n ...context,\n }\n\n const { data } = await this.endpoint.conversation.POST(`/api/conversation/v3`, {\n body: {\n type: 'START_CONVERSATION',\n conversationContext,\n openingUserMessage: userMessage,\n },\n })\n\n if (!data) throw new SDKError('No data received from Conversation API')\n\n const [conversationIdMessage, ...rest] = data as [ConversationIdMessage, ...Message[]]\n\n const conversationId = conversationIdMessage.conversationId\n if (!conversationId) {\n throw new SDKError('Conversation ID not received in API response')\n }\n\n this.identity.conversationId = conversationId\n\n return rest\n }\n\n /**\n * Sends a message in the conversation.\n *\n * @param options - An object containing the user message.\n * @returns A promise that resolves to an array of messages\n *\n * @example\n * ```ts\n * const newMessages = await client.sendMessage({\n * userMessage: 'How can I get support?',\n * })\n *\n * if (newMessages) {\n * console.log('Received messages:', newMessages)\n * } else {\n * console.log('No message received')\n * }\n * ```\n */\n async sendMessage(payload: SendMessagePayload): Promise<Message[]> {\n const conversationId = this.identity.conversationId\n if (!conversationId) {\n throw new SDKError('Conversation ID not set')\n }\n\n const { data } = await this.endpoint.conversation.POST('/api/conversation/v3', {\n body: {\n conversationId,\n ...payload,\n },\n })\n\n if (!data) throw new SDKError('No data received from conversation API')\n\n // Removes any `CONVERSATION_ID` messages from the API response. In reality, these messages will only\n // appear in the response to a `START_CONVERSATION` request.\n return data.filter((message) => message.type !== 'CONVERSATION_ID')\n }\n\n /**\n * Sends an event to the tracking API, with the required properties already set.\n *\n * @param eventName - The name of the event to track.\n * @param properties - Additional properties to include in the event.\n * @returns A promise that resolves once the event is tracked.\n *\n * @example\n * ```ts\n * await client.trackEvent('entry_point-shown')\n * ```\n */\n async trackEvent(eventName: TrackingEvent['eventName'], properties?: TrackingEvent['additionalProperties']) {\n const body: TrackingEvent = {\n additionalProperties: properties,\n conversationId: this.identity.conversationId,\n eventName,\n pageviewId: this.identity.pageviewId ?? 'unknown',\n screenWidth: window.screen.width,\n screenHeight: window.screen.height,\n screenSize: window.screen.width <= 480 ? 'mobile' : 'large',\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n }\n\n return this.endpoint.frontend.POST('/api/tracking/user/v2', {\n body,\n })\n }\n\n /**\n * Gets an existing identity of the user.\n *\n * @returns An Identity object containing `customerId`, `conversationId`, `sessionId`, `userId`.\n *\n * @example\n * ```ts\n * identity = client.getIdentity()\n * console.log('Identity retrieved:', identity)\n * ```\n */\n getIdentity(): Identity {\n return this.identity\n }\n\n /**\n * Gets the JWT from the localStorage.\n * Use this method to retrieve the token for use in other parts of your system,\n * such as calling the Humara sales tracking API\n *\n * @returns {string | null} the JWT.\n *\n * @example\n * ```ts\n * token = client.getIdentityToken()\n * console.log('Identity token retrieved:', token)\n * ```\n */\n getIdentityToken(): string | null {\n return this.identity.token ?? null\n }\n\n /**\n * Gets the conversation history for a given conversation ID.\n *\n * @param conversationId - The ID of the conversation to retrieve.\n * @returns A promise that resolves to the conversation history as an array of turns. Each turn contains a user message and its corresponding response.\n */\n async getConversation(conversationId: string): Promise<RestoredTurn[]> {\n if (!conversationId) {\n throw new SDKError('Conversation ID not set')\n }\n\n try {\n const { data } = await this.endpoint.conversation.GET('/api/conversation/{conversation_id}/v1', {\n params: {\n path: {\n conversation_id: conversationId,\n },\n },\n })\n\n // Sets the current conversation ID to the one just retrieved, so that subsequent calls to `sendMessage` and `trackEvent` will use this conversation ID.\n this.identity.conversationId = conversationId\n\n if (!data) throw new SDKError('No data received from conversation history API')\n\n return restoreConversation(data)\n } catch (error) {\n throw new SDKError('Failed to get conversation history', {\n cause: error as Error,\n })\n }\n }\n}\n","const getItemWithExpiry = (key: string) => {\n const itemString = localStorage.getItem(key)\n\n if (!itemString) return null\n\n const item = JSON.parse(itemString) as { expires: number; value: string }\n\n if (Date.now() > item.expires) {\n localStorage.removeItem(key)\n\n return null\n }\n\n return item.value\n}\n\nexport default getItemWithExpiry\n","/**\n * Set an item in localStorage with an expiration time\n * @param key The key under which the value is stored in localStorage\n * @param value The value to be stored\n * @param ttl The time-to-live (TTL) in milliseconds\n */\nconst setItemWithExpiry = (key: string, value: string, ttl: number) => {\n const item = {\n expires: Date.now() + ttl,\n value,\n }\n\n localStorage.setItem(key, JSON.stringify(item))\n}\n\nexport default setItemWithExpiry\n","import type { Config, Identity } from '../types'\nimport { getItemWithExpiry, setItemWithExpiry } from '../utils'\n\ntype IdentityKey = 'conversationId' | 'sessionId' | 'token' | 'userId'\n\nconst day = 1000 * 60 * 60 * 24\nconst userIdTtl = day * 30\n\nconst conversationIdKey = '__15gifts_conversation_id'\nconst sessionIdKey = '__15gifts_session_id'\nconst tokenKey = '__15gifts_identity_token'\nconst userIdKey = '__15gifts_user_id'\n\nconst deleteConversationId = () => sessionStorage.removeItem(conversationIdKey)\nconst getConversationId = () => sessionStorage.getItem(conversationIdKey)\nconst setConversationId = (conversationId: string) => sessionStorage.setItem(conversationIdKey, conversationId)\n\nconst getSessionId = () => sessionStorage.getItem(sessionIdKey)\nconst setSessionId = (sessionId: string) => sessionStorage.setItem(sessionIdKey, sessionId)\n\nconst isTokenExpired = (token: string): boolean => {\n try {\n const [, payloadBase64] = token.split('.')\n if (!payloadBase64) {\n throw new Error('Invalid token payload')\n }\n const payload = JSON.parse(atob(payloadBase64))\n\n return payload.exp && Date.now() / 1000 > payload.exp\n } catch (error) {\n console.error('Invalid token format', error)\n return true\n }\n}\n\nconst getToken = (): string | null => {\n const token = localStorage.getItem(tokenKey)\n\n if (!token || isTokenExpired(token)) {\n localStorage.removeItem(tokenKey)\n return null\n }\n\n return token\n}\n\nconst setToken = (token: string) => localStorage.setItem(tokenKey, token)\n\nconst getUserId = () => {\n const userId = getItemWithExpiry(userIdKey)\n\n if (userId) {\n setUserId(userId)\n }\n\n return userId\n}\n\nconst setUserId = (userId: string) => setItemWithExpiry(userIdKey, userId, userIdTtl)\n\nconst createIdentityProperty = (\n getValue: () => string | null,\n setValue: (value: string) => void,\n clearValue?: () => void,\n): PropertyDescriptor => ({\n enumerable: true,\n configurable: true,\n get: () => getValue() ?? undefined,\n set: (value: string | undefined) => {\n if (value) {\n setValue(value)\n return\n }\n\n clearValue?.()\n },\n})\n\n/**\n * Creates an identity object backed by browser storage.\n *\n * The returned object exposes the public `Identity` shape while keeping\n * `conversationId`, `sessionId`, and `userId` synchronized with their\n * corresponding storage helpers.\n */\nexport const createIdentityStore = (customerId: Config['customerId']): Identity => {\n const identity: Identity = {\n customerId,\n }\n\n const properties: Record<IdentityKey, PropertyDescriptor> = {\n conversationId: createIdentityProperty(getConversationId, setConversationId, deleteConversationId),\n sessionId: createIdentityProperty(getSessionId, setSessionId),\n token: createIdentityProperty(getToken, setToken),\n userId: createIdentityProperty(getUserId, setUserId),\n }\n\n Object.defineProperties(identity, properties)\n\n return identity\n}\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for adding an `Authorization` header to requests.\n *\n * @param accessToken - The token to be included in the `Authorization` header.\n * @returns A middleware object that attaches the access token to the request headers.\n *\n * @example\n * ```ts\n * import { authMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(authMiddleware(accessToken))\n * ```\n */\nconst authMiddleware = (accessToken?: string): Middleware => ({\n onRequest: async ({ request }) => {\n const isIdentityEndpoint = request.url.includes('/identity/')\n if (isIdentityEndpoint) {\n return request\n }\n\n // Throw an error because we know the API will return a 401 if the access token is not set.\n if (!accessToken) {\n throw new Error('Access token is required for authentication.')\n }\n\n request.headers.set('Authorization', `Bearer ${accessToken}`)\n\n return request\n },\n})\n\nexport default authMiddleware\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for handling errors.\n *\n * @returns A middleware object that throws an error if the response is not ok.\n *\n * @example\n * ```ts\n * import { errorMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(errorMiddleware())\n * ```\n */\nconst errorMiddleware: Middleware = {\n // onError does not handle error responses with 4xx or 5xx HTTP status codes, since these are considered \"successful\" responses but with a bad status code.\n // In these cases we need to check the response's status property or ok() method via the onResponse callback.\n onResponse: async ({ response }) => {\n if (!response.ok) {\n const data = await response.json()\n\n throw new Error(data.message)\n }\n\n return response\n },\n}\n\nexport default errorMiddleware\n","import type { Middleware } from 'openapi-fetch'\n\nimport { Identity } from '../types'\n\n/**\n * Middleware for adding request headers that other services use for tracking.\n *\n * @param identity - The identity whose `pageviewId` is sent as `X-PAGEVIEW-ID`.\n * `X-PAGE-URL` is read from `window.location.href` on every request, so it follows SPA route changes.\n *\n * @returns A middleware object that adds the tracking headers to each request.\n *\n * @example\n * ```ts\n * this.endpoint.conversation.use(headerMiddleware(this.identity))\n * ```\n */\nconst headerMiddleware = (identity: Identity): Middleware => ({\n onRequest: async ({ request }) => {\n if (identity.pageviewId) {\n request.headers.set('X-PAGEVIEW-ID', identity.pageviewId)\n }\n request.headers.set('X-PAGE-URL', window.location.href)\n\n return request\n },\n})\n\nexport default headerMiddleware\n","/**\n * The GET `/api/conversation/{conversation_id}` endpoint returns data as a historical record, but\n * it makes little sense when rendered.\n * We transform it so that the user doesn't see answered single_select and multi_select messages again, only the\n * option(s) they selected.\n **/\n\nimport type {\n ConversationTurn,\n Message,\n MultiSelectMessage,\n SingleSelectMessage,\n UserSingleSelectMessage,\n RestoredTurn,\n} from '../types'\n\ntype UserMultiSelectMessage = Extract<ConversationTurn['userMessage'], { type: 'MULTI_SELECT' }>\n\ntype RestoreRule = 'keep' | 'hideOnceAnswered' | 'drop'\n\n/** How each assistant message type is restored. A new API message type fails the build until it has a rule here. */\nexport const RESTORE_RULES = {\n MESSAGE: 'keep',\n TITLE: 'keep',\n SINGLE_SELECT: 'hideOnceAnswered',\n MULTI_SELECT: 'hideOnceAnswered',\n EXIT_TO_CHAT: 'keep',\n EXIT_TO_PHONE: 'keep',\n EXIT_TO_PURCHASE: 'keep',\n EXIT_TO_PURCHASE_V2: 'keep',\n RECOMMENDATION: 'keep',\n RECOMMENDATION_V2: 'keep',\n CONVERSATION_ID: 'drop',\n} as const satisfies Record<ConversationTurn['assistantMessages'][number]['type'], RestoreRule>\n\n/**\n * Removes the conversationId from the user message, as this is not needed for rendering and would just add noise.\n */\nconst stripConversationId = <T extends { conversationId?: string }>(userMessage: T): Omit<T, 'conversationId'> => {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { conversationId, ...rest } = userMessage\n\n return rest\n}\n\n// We have the string that was sent to the API, this finds the label for the option that it relates to.\nconst getSelectedOptionLabel = (userMessage: UserSingleSelectMessage, previousTurn?: ConversationTurn) => {\n const previousSingleSelect = previousTurn?.assistantMessages.find(\n (message): message is SingleSelectMessage => message.type === 'SINGLE_SELECT',\n )\n const selectedOption = previousSingleSelect?.options.find((option) => option.value === userMessage.option)\n\n return selectedOption?.label || ''\n}\n\nconst getSelectedOptionLabels = (userMessage: UserMultiSelectMessage, previousTurn?: ConversationTurn) => {\n const previousMultiSelect = previousTurn?.assistantMessages.find(\n (message): message is MultiSelectMessage => message.type === 'MULTI_SELECT',\n )\n const selectedOptions = previousMultiSelect?.options.filter((option) => userMessage.options.includes(option.value))\n\n return selectedOptions?.map((option) => option.label).join(', ') || ''\n}\n\n// Turns the user message back in to how the user would have seen it\nconst getRestoredUserMessage = (\n turn: ConversationTurn,\n previousTurn?: ConversationTurn,\n): RestoredTurn['userMessage'] => {\n const { userMessage } = turn\n\n switch (userMessage.type) {\n case 'SINGLE_SELECT':\n return {\n ...stripConversationId(userMessage),\n userMessage: getSelectedOptionLabel(userMessage, previousTurn),\n }\n\n case 'START_CONVERSATION':\n // There isn't anything we want to render from the START_CONVERSATION message except for the openingUserMessage,\n // which is what the user would have submitted to start the conversation.\n return {\n type: 'MESSAGE',\n userMessage: userMessage.openingUserMessage?.option || '',\n }\n\n case 'MESSAGE':\n return stripConversationId(userMessage)\n\n case 'MULTI_SELECT':\n return {\n ...stripConversationId(userMessage),\n userMessage: getSelectedOptionLabels(userMessage, previousTurn),\n }\n }\n}\n\n// Turns the assistant message back in to how the user would have seen it\nconst getRestoredAssistantReply = (turn: ConversationTurn, nextTurn?: ConversationTurn) => {\n const isAnswered = Boolean(nextTurn)\n\n return turn.assistantMessages.filter((message): message is Message => {\n // undefined for types newer than this SDK; those are kept.\n const rule: RestoreRule | undefined = RESTORE_RULES[message.type]\n\n return rule !== 'drop' && !(rule === 'hideOnceAnswered' && isAnswered)\n })\n}\n\nexport const restoreConversation = (turns: ConversationTurn[]): RestoredTurn[] => {\n return turns.map((turn, index) => {\n const previousTurn = index > 0 ? turns[index - 1] : undefined\n const nextTurn = index < turns.length - 1 ? turns[index + 1] : undefined\n\n return {\n id: `restored-turn-${index}`,\n userMessage: getRestoredUserMessage(turn, previousTurn),\n assistantReply: getRestoredAssistantReply(turn, nextTurn),\n }\n })\n}\n","{\n \"name\": \"@15gifts/sdk\",\n \"version\": \"0.30.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\": \"tsc && tsup && npm run typecheck:dist\",\n \"coverage\": \"vitest run --coverage\",\n \"generate-types\": \"npx openapi-typescript\",\n \"dev\": \"tsup --watch\",\n \"format\": \"prettier . --write\",\n \"lint\": \"eslint .\",\n \"pact:publish:conversation\": \"tsx scripts/pact/publish-conversation.ts\",\n \"test\": \"vitest run\",\n \"test:consumer:conversation\": \"tsx scripts/pact/consumer-conversation.ts\",\n \"test:watch\": \"vitest\",\n \"typecheck:dist\": \"tsc --noEmit --skipLibCheck true dist/index.d.ts\",\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 \"@pact-foundation/pact\": \"^16.5.0\",\n \"@types/node\": \"^24.0.0\",\n \"openapi-typescript\": \"^7.13.0\",\n \"tsup\": \"^8.5.1\",\n \"tsx\": \"^4.23.13\"\n },\n \"sideEffects\": false,\n \"prettier\": \"prettier-config-custom\"\n}\n","import { version } from '../../package.json'\n\n/**\n * Custom error class for SDK-related errors.\n * Includes the SDK version and an optional cause for better debugging.\n * NOTE: The error.message is intended for developers, not end-users.\n */\nexport default class SDKError extends Error {\n sdkVersion: string\n override cause?: Error\n\n constructor(userMessage: string, { cause }: { cause?: Error } = {}) {\n super(userMessage)\n this.name = 'SDKError'\n this.cause = cause\n this.sdkVersion = version\n\n // Set the prototype explicitly to maintain instanceof checks\n Object.setPrototypeOf(this, SDKError.prototype)\n }\n}\n"],"mappings":"0jBAAA,IAAAA,GAAA,GAAAC,EAAAD,GAAA,YAAAE,EAAA,aAAAC,EAAA,mBAAAC,EAAA,oBAAAC,EAAA,qBAAAC,IAAA,eAAAC,EAAAP,ICAA,IAAAQ,EAAiD,4BCAjD,IAAMC,EAAqBC,GAAgB,CACzC,IAAMC,EAAa,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,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J,eAAAU,EACA,GAAGC,CACL,CACF,CAAC,EAED,GAAI,CAACX,EAAM,MAAM,IAAIC,EAAS,wCAAwC,EAItE,OAAOD,EAAK,OAAQY,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,CAeA,kBAAkC,CAChC,OAAO,KAAK,SAAS,OAAS,IAChC,CAQA,MAAM,gBAAgBL,EAAiD,CACrE,GAAI,CAACA,EACH,MAAM,IAAIT,EAAS,yBAAyB,EAG9C,GAAI,CACF,GAAM,CAAE,KAAAD,CAAK,EAAI,MAAM,KAAK,SAAS,aAAa,IAAI,yCAA0C,CAC9F,OAAQ,CACN,KAAM,CACJ,gBAAiBU,CACnB,CACF,CACF,CAAC,EAKD,GAFA,KAAK,SAAS,eAAiBA,EAE3B,CAACV,EAAM,MAAM,IAAIC,EAAS,gDAAgD,EAE9E,OAAOe,EAAoBhB,CAAI,CACjC,OAASI,EAAO,CACd,MAAM,IAAIH,EAAS,qCAAsC,CACvD,MAAOG,CACT,CAAC,CACH,CACF,CACF","names":["index_exports","__export","Client","SDKError","auth_default","error_default","headers_default","__toCommonJS","import_openapi_fetch","getItemWithExpiry","key","itemString","item","getItemWithExpiry_default","setItemWithExpiry","key","value","ttl","item","setItemWithExpiry_default","day","userIdTtl","conversationIdKey","sessionIdKey","tokenKey","userIdKey","deleteConversationId","getConversationId","setConversationId","conversationId","getSessionId","setSessionId","sessionId","isTokenExpired","token","payloadBase64","payload","error","getToken","setToken","getUserId","userId","getItemWithExpiry_default","setUserId","setItemWithExpiry_default","createIdentityProperty","getValue","setValue","clearValue","value","createIdentityStore","customerId","identity","properties","authMiddleware","accessToken","request","auth_default","errorMiddleware","response","data","error_default","headerMiddleware","identity","request","headers_default","RESTORE_RULES","stripConversationId","userMessage","conversationId","rest","getSelectedOptionLabel","previousTurn","message","option","getSelectedOptionLabels","getRestoredUserMessage","turn","getRestoredAssistantReply","nextTurn","isAnswered","rule","restoreConversation","turns","index","version","SDKError","_SDKError","userMessage","cause","version","Client","config","conversationUrl","customerId","fetch","frontendUrl","defaultHeaders","headers","version","createClient","createIdentityStore","error_default","headers_default","sessionId","userId","data","SDKError","endpoint","auth_default","error","context","userMessage","conversationContext","conversationIdMessage","rest","conversationId","payload","message","eventName","properties","body","restoreConversation"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/client.ts","../src/utils/getItemWithExpiry.ts","../src/utils/setItemWithExpiry.ts","../src/identity/createIdentityStore.ts","../src/middlewares/auth.ts","../src/middlewares/error.ts","../src/middlewares/headers.ts","../src/restoreConversation/restoreConversation.ts","../package.json","../src/utils/SDKError.ts"],"sourcesContent":["export * from './client'\nexport * from './middlewares'\nexport * from './types'\n","import createClient, { type ClientOptions } from 'openapi-fetch'\n\nimport { createIdentityStore } from './identity/createIdentityStore'\nimport { authMiddleware, errorMiddleware, headerMiddleware } from './middlewares'\nimport { restoreConversation } from './restoreConversation/restoreConversation'\nimport type { components, paths as conversationPaths } from './schemas/conversation'\nimport type { paths as frontendPaths } from './schemas/frontend'\nimport type {\n Config,\n ConversationIdMessage,\n Endpoint,\n Identity,\n Message,\n RestoredTurn,\n SendMessagePayload,\n TrackingEvent,\n UserStartConversationMessage,\n} from './types'\nimport { version } from '../package.json'\nimport SDKError from './utils/SDKError'\n\n/**\n * The `Client` class provides methods to manage 15gifts API.\n */\nexport class Client {\n /**\n * This can be used to interact with the APIs directly. It is recommended to use the [helper methods](/sdk/sdk-reference/classes/client/#methods) provided by the `Client` class instead.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * const { data } = await client.endpoint.conversation.POST('/api/conversation/v3')\n * ```\n */\n endpoint: Endpoint\n\n /**\n * The identity information.\n */\n identity: Identity\n\n /**\n * Creates a new instance of the `Client` class.\n *\n * @param config - Configuration options for initializing the client.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * ```\n */\n constructor(config: Config) {\n const { conversationUrl, customerId, fetch, frontendUrl, headers: defaultHeaders } = config\n\n const headers: ClientOptions['headers'] = {\n ...defaultHeaders,\n 'X-SDK-VERSION': version,\n }\n\n this.endpoint = {\n conversation: createClient<conversationPaths>({\n baseUrl: conversationUrl,\n fetch,\n headers,\n credentials: 'include',\n }),\n frontend: createClient<frontendPaths>({ baseUrl: frontendUrl, fetch, headers }),\n }\n\n this.identity = createIdentityStore(customerId)\n\n this.endpoint.conversation.use(errorMiddleware)\n this.endpoint.conversation.use(headerMiddleware(this.identity))\n }\n\n /**\n * Creates a new identity for the user by generating a session ID and user ID if they don't exist, and sets the access token for future API calls.\n * Ends the current conversation if a conversation ID is present before sending a request to update identity.\n * This should not be called more than once per page load.\n *\n * @returns A promise that resolves once the identity is created and the access token is set.\n *\n * @example\n * ```ts\n * await client.createIdentity()\n * console.log('Identity created:', client.identity)\n * ```\n */\n async createIdentity(): Promise<void> {\n const { customerId, sessionId, userId } = this.identity\n\n try {\n const { data } = await this.endpoint.frontend.POST('/api/tracking/identity/v2', {\n body: {\n customerId,\n sessionId,\n userId,\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n },\n })\n\n if (!data) {\n throw new SDKError('No data received from identity API')\n }\n\n this.identity.pageviewId = data.pageviewId\n\n if (!sessionId) {\n this.identity.sessionId = data.sessionId\n }\n if (!userId) {\n this.identity.userId = data.userId\n }\n\n this.identity.token = data.token\n\n // Add the access token to the Authorization header for all endpoints\n Object.values(this.endpoint).forEach((endpoint) => {\n endpoint.use(authMiddleware(data.token))\n })\n } catch (error) {\n // Enable the auth middleware without a token so that it will throw an error before sending\n // the next request, preventing unnecessary API calls / 401 responses.\n Object.values(this.endpoint).forEach((endpoint) => {\n endpoint.use(authMiddleware())\n })\n throw new SDKError('Failed to create identity', {\n cause: error as Error,\n })\n }\n }\n\n /**\n * Ends the current conversation by deleting the conversation ID.\n *\n * @example\n * ```ts\n * client.endConversation()\n * console.log('Conversation ended')\n * ```\n */\n endConversation(): void {\n this.identity.conversationId = undefined\n }\n\n /**\n * Clears the existing conversation ID, then generates a new one and returns the opening message.\n *\n * @param context - Optional context to customize the conversation. It can include:\n * @param context.eligibleProducts An array of eligible product IDs.\n * @param context.eligibleBundles An array of eligible bundle IDs.\n * @param context.productOverrides Overrides for product details.\n * @param context.bundleOverrides Overrides for bundle details.\n *\n * @returns A promise that resolves to the opening message.\n *\n * @example\n * ##### Basic usage\n * ```ts\n * const openingMessage = await client.startConversation()\n * console.log('Opening message:', openingMessage)\n * ```\n *\n * ##### With context\n * ```ts\n * const openingMessage = await client.startConversation({ eligibleProducts: ['product-1', 'product-2'], productOverrides: { 'product-1': { price: 40 } } })\n * console.log('Opening message:', openingMessage)\n * ```\n */\n async startConversation(\n context?: components['schemas']['ConversationContext'],\n userMessage?: UserStartConversationMessage['openingUserMessage'],\n ): Promise<Message[]> {\n this.endConversation()\n\n const conversationContext = {\n ...context,\n }\n\n const { data } = await this.endpoint.conversation.POST(`/api/conversation/v3`, {\n body: {\n type: 'START_CONVERSATION',\n conversationContext,\n openingUserMessage: userMessage,\n },\n })\n\n if (!data) throw new SDKError('No data received from Conversation API')\n\n const [conversationIdMessage, ...rest] = data as [ConversationIdMessage, ...Message[]]\n\n const conversationId = conversationIdMessage.conversationId\n if (!conversationId) {\n throw new SDKError('Conversation ID not received in API response')\n }\n\n this.identity.conversationId = conversationId\n\n return rest\n }\n\n /**\n * Sends a message in the conversation.\n *\n * @param options - An object containing the user message.\n * @returns A promise that resolves to an array of messages\n *\n * @example\n * ```ts\n * const newMessages = await client.sendMessage({\n * userMessage: 'How can I get support?',\n * })\n *\n * if (newMessages) {\n * console.log('Received messages:', newMessages)\n * } else {\n * console.log('No message received')\n * }\n * ```\n */\n async sendMessage(payload: SendMessagePayload): Promise<Message[]> {\n const conversationId = this.identity.conversationId\n if (!conversationId) {\n throw new SDKError('Conversation ID not set')\n }\n\n const { data } = await this.endpoint.conversation.POST('/api/conversation/v3', {\n body: {\n conversationId,\n ...payload,\n },\n })\n\n if (!data) throw new SDKError('No data received from conversation API')\n\n // Removes any `CONVERSATION_ID` messages from the API response. In reality, these messages will only\n // appear in the response to a `START_CONVERSATION` request.\n return data.filter((message) => message.type !== 'CONVERSATION_ID')\n }\n\n /**\n * Sends an event to the tracking API, with the required properties already set.\n *\n * @param eventName - The name of the event to track.\n * @param properties - Additional properties to include in the event.\n * @returns A promise that resolves once the event is tracked.\n *\n * @example\n * ```ts\n * await client.trackEvent('entry_point-shown')\n * ```\n */\n async trackEvent(eventName: TrackingEvent['eventName'], properties?: TrackingEvent['additionalProperties']) {\n const body: TrackingEvent = {\n additionalProperties: properties,\n conversationId: this.identity.conversationId,\n eventName,\n pageviewId: this.identity.pageviewId ?? 'unknown',\n screenWidth: window.screen.width,\n screenHeight: window.screen.height,\n screenSize: window.screen.width <= 480 ? 'mobile' : 'large',\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n }\n\n return this.endpoint.frontend.POST('/api/tracking/user/v2', {\n body,\n })\n }\n\n /**\n * Gets an existing identity of the user.\n *\n * @returns An Identity object containing `customerId`, `conversationId`, `sessionId`, `userId`.\n *\n * @example\n * ```ts\n * identity = client.getIdentity()\n * console.log('Identity retrieved:', identity)\n * ```\n */\n getIdentity(): Identity {\n return this.identity\n }\n\n /**\n * Gets the JWT from the localStorage.\n * Use this method to retrieve the token for use in other parts of your system,\n * such as calling the Humara sales tracking API\n *\n * @returns {string | null} the JWT.\n *\n * @example\n * ```ts\n * token = client.getIdentityToken()\n * console.log('Identity token retrieved:', token)\n * ```\n */\n getIdentityToken(): string | null {\n return this.identity.token ?? null\n }\n\n /**\n * Gets the conversation history for a given conversation ID.\n *\n * @param conversationId - The ID of the conversation to retrieve.\n * @returns A promise that resolves to the conversation history as an array of turns. Each turn contains a user message and its corresponding response.\n */\n async getConversation(conversationId: string): Promise<RestoredTurn[]> {\n if (!conversationId) {\n throw new SDKError('Conversation ID not set')\n }\n\n try {\n const { data } = await this.endpoint.conversation.GET('/api/conversation/{conversation_id}/v1', {\n params: {\n path: {\n conversation_id: conversationId,\n },\n },\n })\n\n // Sets the current conversation ID to the one just retrieved, so that subsequent calls to `sendMessage` and `trackEvent` will use this conversation ID.\n this.identity.conversationId = conversationId\n\n if (!data) throw new SDKError('No data received from conversation history API')\n\n return restoreConversation(data)\n } catch (error) {\n throw new SDKError('Failed to get conversation history', {\n cause: error as Error,\n })\n }\n }\n}\n","const getItemWithExpiry = (key: string) => {\n const itemString = localStorage.getItem(key)\n\n if (!itemString) return null\n\n const item = JSON.parse(itemString) as { expires: number; value: string }\n\n if (Date.now() > item.expires) {\n localStorage.removeItem(key)\n\n return null\n }\n\n return item.value\n}\n\nexport default getItemWithExpiry\n","/**\n * Set an item in localStorage with an expiration time\n * @param key The key under which the value is stored in localStorage\n * @param value The value to be stored\n * @param ttl The time-to-live (TTL) in milliseconds\n */\nconst setItemWithExpiry = (key: string, value: string, ttl: number) => {\n const item = {\n expires: Date.now() + ttl,\n value,\n }\n\n localStorage.setItem(key, JSON.stringify(item))\n}\n\nexport default setItemWithExpiry\n","import type { Config, Identity } from '../types'\nimport { getItemWithExpiry, setItemWithExpiry } from '../utils'\n\ntype IdentityKey = 'conversationId' | 'sessionId' | 'token' | 'userId'\n\nconst day = 1000 * 60 * 60 * 24\nconst userIdTtl = day * 30\n\nconst conversationIdKey = '__15gifts_conversation_id'\nconst sessionIdKey = '__15gifts_session_id'\nconst tokenKey = '__15gifts_identity_token'\nconst userIdKey = '__15gifts_user_id'\n\nconst deleteConversationId = () => sessionStorage.removeItem(conversationIdKey)\nconst getConversationId = () => sessionStorage.getItem(conversationIdKey)\nconst setConversationId = (conversationId: string) => sessionStorage.setItem(conversationIdKey, conversationId)\n\nconst getSessionId = () => sessionStorage.getItem(sessionIdKey)\nconst setSessionId = (sessionId: string) => sessionStorage.setItem(sessionIdKey, sessionId)\n\nconst isTokenExpired = (token: string): boolean => {\n try {\n const [, payloadBase64] = token.split('.')\n if (!payloadBase64) {\n throw new Error('Invalid token payload')\n }\n const payload = JSON.parse(atob(payloadBase64))\n\n return payload.exp && Date.now() / 1000 > payload.exp\n } catch (error) {\n console.error('Invalid token format', error)\n return true\n }\n}\n\nconst getToken = (): string | null => {\n const token = localStorage.getItem(tokenKey)\n\n if (!token || isTokenExpired(token)) {\n localStorage.removeItem(tokenKey)\n return null\n }\n\n return token\n}\n\nconst setToken = (token: string) => localStorage.setItem(tokenKey, token)\n\nconst getUserId = () => {\n const userId = getItemWithExpiry(userIdKey)\n\n if (userId) {\n setUserId(userId)\n }\n\n return userId\n}\n\nconst setUserId = (userId: string) => setItemWithExpiry(userIdKey, userId, userIdTtl)\n\nconst createIdentityProperty = (\n getValue: () => string | null,\n setValue: (value: string) => void,\n clearValue?: () => void,\n): PropertyDescriptor => ({\n enumerable: true,\n configurable: true,\n get: () => getValue() ?? undefined,\n set: (value: string | undefined) => {\n if (value) {\n setValue(value)\n return\n }\n\n clearValue?.()\n },\n})\n\n/**\n * Creates an identity object backed by browser storage.\n *\n * The returned object exposes the public `Identity` shape while keeping\n * `conversationId`, `sessionId`, and `userId` synchronized with their\n * corresponding storage helpers.\n */\nexport const createIdentityStore = (customerId: Config['customerId']): Identity => {\n const identity: Identity = {\n customerId,\n }\n\n const properties: Record<IdentityKey, PropertyDescriptor> = {\n conversationId: createIdentityProperty(getConversationId, setConversationId, deleteConversationId),\n sessionId: createIdentityProperty(getSessionId, setSessionId),\n token: createIdentityProperty(getToken, setToken),\n userId: createIdentityProperty(getUserId, setUserId),\n }\n\n Object.defineProperties(identity, properties)\n\n return identity\n}\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for adding an `Authorization` header to requests.\n *\n * @param accessToken - The token to be included in the `Authorization` header.\n * @returns A middleware object that attaches the access token to the request headers.\n *\n * @example\n * ```ts\n * import { authMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(authMiddleware(accessToken))\n * ```\n */\nconst authMiddleware = (accessToken?: string): Middleware => ({\n onRequest: async ({ request }) => {\n const isIdentityEndpoint = request.url.includes('/identity/')\n if (isIdentityEndpoint) {\n return request\n }\n\n // Throw an error because we know the API will return a 401 if the access token is not set.\n if (!accessToken) {\n throw new Error('Access token is required for authentication.')\n }\n\n request.headers.set('Authorization', `Bearer ${accessToken}`)\n\n return request\n },\n})\n\nexport default authMiddleware\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for handling errors.\n *\n * @returns A middleware object that throws an error if the response is not ok.\n *\n * @example\n * ```ts\n * import { errorMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(errorMiddleware())\n * ```\n */\nconst errorMiddleware: Middleware = {\n // onError does not handle error responses with 4xx or 5xx HTTP status codes, since these are considered \"successful\" responses but with a bad status code.\n // In these cases we need to check the response's status property or ok() method via the onResponse callback.\n onResponse: async ({ response }) => {\n if (!response.ok) {\n const data = await response.json()\n\n throw new Error(data.message)\n }\n\n return response\n },\n}\n\nexport default errorMiddleware\n","import type { Middleware } from 'openapi-fetch'\n\nimport { Identity } from '../types'\n\n/**\n * Middleware for adding request headers that other services use for tracking.\n *\n * @param identity - The identity whose `pageviewId` is sent as `X-PAGEVIEW-ID`.\n * `X-PAGE-URL` is read from `window.location.href` on every request, so it follows SPA route changes.\n *\n * @returns A middleware object that adds the tracking headers to each request.\n *\n * @example\n * ```ts\n * this.endpoint.conversation.use(headerMiddleware(this.identity))\n * ```\n */\nconst headerMiddleware = (identity: Identity): Middleware => ({\n onRequest: async ({ request }) => {\n if (identity.pageviewId) {\n request.headers.set('X-PAGEVIEW-ID', identity.pageviewId)\n }\n request.headers.set('X-PAGE-URL', window.location.href)\n\n return request\n },\n})\n\nexport default headerMiddleware\n","/**\n * The GET `/api/conversation/{conversation_id}` endpoint returns data as a historical record, but\n * it makes little sense when rendered.\n * We transform it so that the user doesn't see answered single_select and multi_select messages again, only the\n * option(s) they selected.\n **/\n\nimport type {\n ConversationTurn,\n Message,\n MultiSelectMessage,\n SingleSelectMessage,\n UserSingleSelectMessage,\n RestoredTurn,\n} from '../types'\n\ntype UserMultiSelectMessage = Extract<ConversationTurn['userMessage'], { type: 'MULTI_SELECT' }>\n\ntype RestoreRule = 'keep' | 'hideOnceAnswered' | 'drop'\n\n/** How each assistant message type is restored. A new API message type fails the build until it has a rule here. */\nexport const RESTORE_RULES = {\n MESSAGE: 'keep',\n TITLE: 'keep',\n SINGLE_SELECT: 'hideOnceAnswered',\n MULTI_SELECT: 'hideOnceAnswered',\n EXIT_TO_CHAT: 'keep',\n EXIT_TO_PHONE: 'keep',\n EXIT_TO_PURCHASE: 'keep',\n EXIT_TO_PURCHASE_V2: 'keep',\n RECOMMENDATION: 'keep',\n RECOMMENDATION_V2: 'keep',\n CONVERSATION_ID: 'drop',\n} as const satisfies Record<ConversationTurn['assistantMessages'][number]['type'], RestoreRule>\n\n/**\n * Removes the conversationId from the user message, as this is not needed for rendering and would just add noise.\n */\nconst stripConversationId = <T extends { conversationId?: string }>(userMessage: T): Omit<T, 'conversationId'> => {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { conversationId, ...rest } = userMessage\n\n return rest\n}\n\n// We have the string that was sent to the API, this finds the label for the option that it relates to.\nconst getSelectedOptionLabel = (userMessage: UserSingleSelectMessage, previousTurn?: ConversationTurn) => {\n const previousSingleSelect = previousTurn?.assistantMessages.find(\n (message): message is SingleSelectMessage => message.type === 'SINGLE_SELECT',\n )\n const selectedOption = previousSingleSelect?.options.find((option) => option.value === userMessage.option)\n\n return selectedOption?.label || ''\n}\n\nconst getSelectedOptionLabels = (userMessage: UserMultiSelectMessage, previousTurn?: ConversationTurn) => {\n const previousMultiSelect = previousTurn?.assistantMessages.find(\n (message): message is MultiSelectMessage => message.type === 'MULTI_SELECT',\n )\n const selectedOptions = previousMultiSelect?.options.filter((option) => userMessage.options.includes(option.value))\n\n return selectedOptions?.map((option) => option.label).join(', ') || ''\n}\n\n// Turns the user message back in to how the user would have seen it\nconst getRestoredUserMessage = (\n turn: ConversationTurn,\n previousTurn?: ConversationTurn,\n): RestoredTurn['userMessage'] => {\n const { userMessage } = turn\n\n switch (userMessage.type) {\n case 'SINGLE_SELECT':\n return {\n ...stripConversationId(userMessage),\n userMessage: getSelectedOptionLabel(userMessage, previousTurn),\n }\n\n case 'START_CONVERSATION':\n // There isn't anything we want to render from the START_CONVERSATION message except for the openingUserMessage,\n // which is what the user would have submitted to start the conversation.\n return {\n type: 'MESSAGE',\n userMessage: userMessage.openingUserMessage?.option || '',\n }\n\n case 'MESSAGE':\n return stripConversationId(userMessage)\n\n case 'MULTI_SELECT':\n return {\n ...stripConversationId(userMessage),\n userMessage: getSelectedOptionLabels(userMessage, previousTurn),\n }\n }\n}\n\n// Turns the assistant message back in to how the user would have seen it\nconst getRestoredAssistantReply = (turn: ConversationTurn, nextTurn?: ConversationTurn) => {\n const isAnswered = Boolean(nextTurn)\n\n return turn.assistantMessages.filter((message): message is Message => {\n // undefined for types newer than this SDK; those are kept.\n const rule: RestoreRule | undefined = RESTORE_RULES[message.type]\n\n return rule !== 'drop' && !(rule === 'hideOnceAnswered' && isAnswered)\n })\n}\n\nexport const restoreConversation = (turns: ConversationTurn[]): RestoredTurn[] => {\n return turns.map((turn, index) => {\n const previousTurn = index > 0 ? turns[index - 1] : undefined\n const nextTurn = index < turns.length - 1 ? turns[index + 1] : undefined\n\n return {\n id: `restored-turn-${index}`,\n userMessage: getRestoredUserMessage(turn, previousTurn),\n assistantReply: getRestoredAssistantReply(turn, nextTurn),\n }\n })\n}\n","{\n \"name\": \"@15gifts/sdk\",\n \"version\": \"0.30.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\": \"tsc && tsup && npm run typecheck:dist\",\n \"coverage\": \"vitest run --coverage\",\n \"generate-types\": \"npx openapi-typescript\",\n \"dev\": \"tsup --watch\",\n \"format\": \"prettier . --write\",\n \"lint\": \"eslint .\",\n \"pact:publish:conversation\": \"tsx scripts/pact/publish-conversation.ts\",\n \"test\": \"vitest run\",\n \"test:consumer:conversation\": \"tsx scripts/pact/consumer-conversation.ts\",\n \"test:watch\": \"vitest\",\n \"typecheck:dist\": \"tsc --noEmit --skipLibCheck true dist/index.d.ts\",\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 \"@pact-foundation/pact\": \"^16.5.0\",\n \"@types/node\": \"^24.0.0\",\n \"openapi-typescript\": \"^7.13.0\",\n \"tsup\": \"^8.5.1\",\n \"tsx\": \"^4.23.13\"\n },\n \"sideEffects\": false,\n \"prettier\": \"prettier-config-custom\"\n}\n","import { version } from '../../package.json'\n\n/**\n * Custom error class for SDK-related errors.\n * Includes the SDK version and an optional cause for better debugging.\n * NOTE: The error.message is intended for developers, not end-users.\n */\nexport default class SDKError extends Error {\n sdkVersion: string\n override cause?: Error\n\n constructor(userMessage: string, { cause }: { cause?: Error } = {}) {\n super(userMessage)\n this.name = 'SDKError'\n this.cause = cause\n this.sdkVersion = version\n\n // Set the prototype explicitly to maintain instanceof checks\n Object.setPrototypeOf(this, SDKError.prototype)\n }\n}\n"],"mappings":"0jBAAA,IAAAA,GAAA,GAAAC,EAAAD,GAAA,YAAAE,EAAA,aAAAC,EAAA,mBAAAC,EAAA,oBAA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D,EAE9E,OAAOe,EAAoBhB,CAAI,CACjC,OAASI,EAAO,CACd,MAAM,IAAIH,EAAS,qCAAsC,CACvD,MAAOG,CACT,CAAC,CACH,CACF,CACF","names":["index_exports","__export","Client","SDKError","auth_default","error_default","headers_default","__toCommonJS","import_openapi_fetch","getItemWithExpiry","key","itemString","item","getItemWithExpiry_default","setItemWithExpiry","key","value","ttl","item","setItemWithExpiry_default","day","userIdTtl","conversationIdKey","sessionIdKey","tokenKey","userIdKey","deleteConversationId","getConversationId","setConversationId","conversationId","getSessionId","setSessionId","sessionId","isTokenExpired","token","payloadBase64","payload","error","getToken","setToken","getUserId","userId","getItemWithExpiry_default","setUserId","setItemWithExpiry_default","createIdentityProperty","getValue","setValue","clearValue","value","createIdentityStore","customerId","identity","properties","authMiddleware","accessToken","request","auth_default","errorMiddleware","response","data","error_default","headerMiddleware","identity","request","headers_default","RESTORE_RULES","stripConversationId","userMessage","conversationId","rest","getSelectedOptionLabel","previousTurn","message","option","getSelectedOptionLabels","getRestoredUserMessage","turn","getRestoredAssistantReply","nextTurn","isAnswered","rule","restoreConversation","turns","index","version","SDKError","_SDKError","userMessage","cause","version","Client","config","conversationUrl","customerId","fetch","frontendUrl","defaultHeaders","headers","version","createClient","createIdentityStore","error_default","headers_default","sessionId","userId","data","SDKError","endpoint","auth_default","error","context","userMessage","conversationContext","conversationIdMessage","rest","conversationId","payload","message","eventName","properties","body","restoreConversation"]}
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import x from"openapi-fetch";var A=e=>{let t=localStorage.getItem(e);if(!t)return null;let s=JSON.parse(t);return Date.now()>s.expires?(localStorage.removeItem(e),null):s.value},u=A;var w=(e,t,s)=>{let o={expires:Date.now()+s,value:t};localStorage.setItem(e,JSON.stringify(o))},l=w;var R=1e3*60*60*24,O=R*30,y="__15gifts_conversation_id",h="__15gifts_session_id",v="__15gifts_identity_token",M="__15gifts_user_id",P=()=>sessionStorage.removeItem(y),_=()=>sessionStorage.getItem(y),k=e=>sessionStorage.setItem(y,e),U=()=>sessionStorage.getItem(h),N=e=>sessionStorage.setItem(h,e),L=e=>{try{let[,t]=e.split(".");if(!t)throw new Error("Invalid token payload");let s=JSON.parse(atob(t));return s.exp&&Date.now()/1e3>s.exp}catch(t){return console.error("Invalid token format",t),!0}},b=()=>{let e=localStorage.getItem(v);return!e||L(e)?(localStorage.removeItem(v),null):e},V=e=>localStorage.setItem(v,e),D=()=>{let e=u(M);return e&&E(e),e},E=e=>l(M,e,O),p=(e,t,s)=>({enumerable:!0,configurable:!0,get:()=>e()??void 0,set:o=>{if(o){t(o);return}s?.()}}),T=e=>{let t={customerId:e},s={conversationId:p(_,k,P),sessionId:p(U,N),token:p(b,V),userId:p(D,E)};return Object.defineProperties(t,s),t};var G=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=G;var j={onResponse:async({response:e})=>{if(!e.ok){let t=await e.json();throw new Error(t.message)}return e}},m=j;var q=e=>({onRequest:async({request:t})=>(e.pageviewId&&t.headers.set("X-PAGEVIEW-ID",e.pageviewId),t.headers.set("X-PAGE-URL",window.location.href),t)}),I=q;var X={MESSAGE:"keep",TITLE:"keep",SINGLE_SELECT:"hideOnceAnswered",MULTI_SELECT:"hideOnceAnswered",EXIT_TO_CHAT:"keep",EXIT_TO_PHONE:"keep",EXIT_TO_PURCHASE:"keep",EXIT_TO_PURCHASE_V2:"keep",RECOMMENDATION:"keep",RECOMMENDATION_V2:"keep",CONVERSATION_ID:"drop"},f=e=>{let{conversationId:t,...s}=e;return s},H=(e,t)=>t?.assistantMessages.find(n=>n.type==="SINGLE_SELECT")?.options.find(n=>n.value===e.option)?.label||"",K=(e,t)=>t?.assistantMessages.find(n=>n.type==="MULTI_SELECT")?.options.filter(n=>e.options.includes(n.value))?.map(n=>n.label).join(", ")||"",W=(e,t)=>{let{userMessage:s}=e;switch(s.type){case"SINGLE_SELECT":return{...f(s),userMessage:H(s,t)};case"START_CONVERSATION":return{type:"MESSAGE",userMessage:s.openingUserMessage?.option||""};case"MESSAGE":return f(s);case"MULTI_SELECT":return{...f(s),userMessage:K(s,t)}}},B=(e,t)=>{let s=!!t;return e.assistantMessages.filter(o=>{let n=X[o.type];return n!=="drop"&&!(n==="hideOnceAnswered"&&s)})},S=e=>e.map((t,s)=>{let o=s>0?e[s-1]:void 0,n=s<e.length-1?e[s+1]:void 0;return{id:`restored-turn-${s}`,userMessage:W(t,o),assistantReply:B(t,n)}});var c="0.30.
|
|
1
|
+
import x from"openapi-fetch";var A=e=>{let t=localStorage.getItem(e);if(!t)return null;let s=JSON.parse(t);return Date.now()>s.expires?(localStorage.removeItem(e),null):s.value},u=A;var w=(e,t,s)=>{let o={expires:Date.now()+s,value:t};localStorage.setItem(e,JSON.stringify(o))},l=w;var R=1e3*60*60*24,O=R*30,y="__15gifts_conversation_id",h="__15gifts_session_id",v="__15gifts_identity_token",M="__15gifts_user_id",P=()=>sessionStorage.removeItem(y),_=()=>sessionStorage.getItem(y),k=e=>sessionStorage.setItem(y,e),U=()=>sessionStorage.getItem(h),N=e=>sessionStorage.setItem(h,e),L=e=>{try{let[,t]=e.split(".");if(!t)throw new Error("Invalid token payload");let s=JSON.parse(atob(t));return s.exp&&Date.now()/1e3>s.exp}catch(t){return console.error("Invalid token format",t),!0}},b=()=>{let e=localStorage.getItem(v);return!e||L(e)?(localStorage.removeItem(v),null):e},V=e=>localStorage.setItem(v,e),D=()=>{let e=u(M);return e&&E(e),e},E=e=>l(M,e,O),p=(e,t,s)=>({enumerable:!0,configurable:!0,get:()=>e()??void 0,set:o=>{if(o){t(o);return}s?.()}}),T=e=>{let t={customerId:e},s={conversationId:p(_,k,P),sessionId:p(U,N),token:p(b,V),userId:p(D,E)};return Object.defineProperties(t,s),t};var G=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=G;var j={onResponse:async({response:e})=>{if(!e.ok){let t=await e.json();throw new Error(t.message)}return e}},m=j;var q=e=>({onRequest:async({request:t})=>(e.pageviewId&&t.headers.set("X-PAGEVIEW-ID",e.pageviewId),t.headers.set("X-PAGE-URL",window.location.href),t)}),I=q;var X={MESSAGE:"keep",TITLE:"keep",SINGLE_SELECT:"hideOnceAnswered",MULTI_SELECT:"hideOnceAnswered",EXIT_TO_CHAT:"keep",EXIT_TO_PHONE:"keep",EXIT_TO_PURCHASE:"keep",EXIT_TO_PURCHASE_V2:"keep",RECOMMENDATION:"keep",RECOMMENDATION_V2:"keep",CONVERSATION_ID:"drop"},f=e=>{let{conversationId:t,...s}=e;return s},H=(e,t)=>t?.assistantMessages.find(n=>n.type==="SINGLE_SELECT")?.options.find(n=>n.value===e.option)?.label||"",K=(e,t)=>t?.assistantMessages.find(n=>n.type==="MULTI_SELECT")?.options.filter(n=>e.options.includes(n.value))?.map(n=>n.label).join(", ")||"",W=(e,t)=>{let{userMessage:s}=e;switch(s.type){case"SINGLE_SELECT":return{...f(s),userMessage:H(s,t)};case"START_CONVERSATION":return{type:"MESSAGE",userMessage:s.openingUserMessage?.option||""};case"MESSAGE":return f(s);case"MULTI_SELECT":return{...f(s),userMessage:K(s,t)}}},B=(e,t)=>{let s=!!t;return e.assistantMessages.filter(o=>{let n=X[o.type];return n!=="drop"&&!(n==="hideOnceAnswered"&&s)})},S=e=>e.map((t,s)=>{let o=s>0?e[s-1]:void 0,n=s<e.length-1?e[s+1]:void 0;return{id:`restored-turn-${s}`,userMessage:W(t,o),assistantReply:B(t,n)}});var c="0.30.2";var r=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 C=class{endpoint;identity;constructor(t){let{conversationUrl:s,customerId:o,fetch:n,frontendUrl:i,headers:g}=t,a={...g,"X-SDK-VERSION":c};this.endpoint={conversation:x({baseUrl:s,fetch:n,headers:a,credentials:"include"}),frontend:x({baseUrl:i,fetch:n,headers:a})},this.identity=T(o),this.endpoint.conversation.use(m),this.endpoint.conversation.use(I(this.identity))}async createIdentity(){let{customerId:t,sessionId:s,userId:o}=this.identity;try{let{data:n}=await this.endpoint.frontend.POST("/api/tracking/identity/v2",{body:{customerId:t,sessionId:s,userId:o,url:window.location.href,userAgent:window.navigator.userAgent}});if(!n)throw new r("No data received from identity API");this.identity.pageviewId=n.pageviewId,s||(this.identity.sessionId=n.sessionId),o||(this.identity.userId=n.userId),this.identity.token=n.token,Object.values(this.endpoint).forEach(i=>{i.use(d(n.token))})}catch(n){throw Object.values(this.endpoint).forEach(i=>{i.use(d())}),new r("Failed to create identity",{cause:n})}}endConversation(){this.identity.conversationId=void 0}async startConversation(t,s){this.endConversation();let o={...t},{data:n}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{type:"START_CONVERSATION",conversationContext:o,openingUserMessage:s}});if(!n)throw new r("No data received from Conversation API");let[i,...g]=n,a=i.conversationId;if(!a)throw new r("Conversation ID not received in API response");return this.identity.conversationId=a,g}async sendMessage(t){let s=this.identity.conversationId;if(!s)throw new r("Conversation ID not set");let{data:o}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{conversationId:s,...t}});if(!o)throw new r("No data received from conversation API");return o.filter(n=>n.type!=="CONVERSATION_ID")}async trackEvent(t,s){let o={additionalProperties:s,conversationId:this.identity.conversationId,eventName:t,pageviewId:this.identity.pageviewId??"unknown",screenWidth:window.screen.width,screenHeight:window.screen.height,screenSize:window.screen.width<=480?"mobile":"large",url:window.location.href,userAgent:window.navigator.userAgent};return this.endpoint.frontend.POST("/api/tracking/user/v2",{body:o})}getIdentity(){return this.identity}getIdentityToken(){return this.identity.token??null}async getConversation(t){if(!t)throw new r("Conversation ID not set");try{let{data:s}=await this.endpoint.conversation.GET("/api/conversation/{conversation_id}/v1",{params:{path:{conversation_id:t}}});if(this.identity.conversationId=t,!s)throw new r("No data received from conversation history API");return S(s)}catch(s){throw new r("Failed to get conversation history",{cause:s})}}};export{C as Client,r as SDKError,d as authMiddleware,m as errorMiddleware,I as headerMiddleware};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client.ts","../src/utils/getItemWithExpiry.ts","../src/utils/setItemWithExpiry.ts","../src/identity/createIdentityStore.ts","../src/middlewares/auth.ts","../src/middlewares/error.ts","../src/middlewares/headers.ts","../src/restoreConversation/restoreConversation.ts","../package.json","../src/utils/SDKError.ts"],"sourcesContent":["import createClient, { type ClientOptions } from 'openapi-fetch'\n\nimport { createIdentityStore } from './identity/createIdentityStore'\nimport { authMiddleware, errorMiddleware, headerMiddleware } from './middlewares'\nimport { restoreConversation } from './restoreConversation/restoreConversation'\nimport type { components, paths as conversationPaths } from './schemas/conversation'\nimport type { paths as frontendPaths } from './schemas/frontend'\nimport type {\n Config,\n ConversationIdMessage,\n Endpoint,\n Identity,\n Message,\n RestoredTurn,\n SendMessagePayload,\n TrackingEvent,\n UserStartConversationMessage,\n} from './types'\nimport { version } from '../package.json'\nimport SDKError from './utils/SDKError'\n\n/**\n * The `Client` class provides methods to manage 15gifts API.\n */\nexport class Client {\n /**\n * This can be used to interact with the APIs directly. It is recommended to use the [helper methods](/sdk/sdk-reference/classes/client/#methods) provided by the `Client` class instead.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * const { data } = await client.endpoint.conversation.POST('/api/conversation/v3')\n * ```\n */\n endpoint: Endpoint\n\n /**\n * The identity information.\n */\n identity: Identity\n\n /**\n * Creates a new instance of the `Client` class.\n *\n * @param config - Configuration options for initializing the client.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * ```\n */\n constructor(config: Config) {\n const { conversationUrl, customerId, fetch, frontendUrl, headers: defaultHeaders } = config\n\n const headers: ClientOptions['headers'] = {\n ...defaultHeaders,\n 'X-SDK-VERSION': version,\n }\n\n this.endpoint = {\n conversation: createClient<conversationPaths>({\n baseUrl: conversationUrl,\n fetch,\n headers,\n credentials: 'include',\n }),\n frontend: createClient<frontendPaths>({ baseUrl: frontendUrl, fetch, headers }),\n }\n\n this.identity = createIdentityStore(customerId)\n\n this.endpoint.conversation.use(errorMiddleware)\n this.endpoint.conversation.use(headerMiddleware(this.identity))\n }\n\n /**\n * Creates a new identity for the user by generating a session ID and user ID if they don't exist, and sets the access token for future API calls.\n * Ends the current conversation if a conversation ID is present before sending a request to update identity.\n * This should not be called more than once per page load.\n *\n * @returns A promise that resolves once the identity is created and the access token is set.\n *\n * @example\n * ```ts\n * await client.createIdentity()\n * console.log('Identity created:', client.identity)\n * ```\n */\n async createIdentity(): Promise<void> {\n const { customerId, sessionId, userId } = this.identity\n\n try {\n const { data } = await this.endpoint.frontend.POST('/api/tracking/identity/v2', {\n body: {\n customerId,\n sessionId,\n userId,\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n },\n })\n\n if (!data) {\n throw new SDKError('No data received from identity API')\n }\n\n this.identity.pageviewId = data.pageviewId\n\n if (!sessionId) {\n this.identity.sessionId = data.sessionId\n }\n if (!userId) {\n this.identity.userId = data.userId\n }\n\n this.identity.token = data.token\n\n // Add the access token to the Authorization header for all endpoints\n Object.values(this.endpoint).forEach((endpoint) => {\n endpoint.use(authMiddleware(data.token))\n })\n } catch (error) {\n // Enable the auth middleware without a token so that it will throw an error before sending\n // the next request, preventing unnecessary API calls / 401 responses.\n Object.values(this.endpoint).forEach((endpoint) => {\n endpoint.use(authMiddleware())\n })\n throw new SDKError('Failed to create identity', {\n cause: error as Error,\n })\n }\n }\n\n /**\n * Ends the current conversation by deleting the conversation ID.\n *\n * @example\n * ```ts\n * client.endConversation()\n * console.log('Conversation ended')\n * ```\n */\n endConversation(): void {\n this.identity.conversationId = undefined\n }\n\n /**\n * Clears the existing conversation ID, then generates a new one and returns the opening message.\n *\n * @param context - Optional context to customize the conversation. It can include:\n * @param context.eligibleProducts An array of eligible product IDs.\n * @param context.eligibleBundles An array of eligible bundle IDs.\n * @param context.productOverrides Overrides for product details.\n * @param context.bundleOverrides Overrides for bundle details.\n *\n * @returns A promise that resolves to the opening message.\n *\n * @example\n * ##### Basic usage\n * ```ts\n * const openingMessage = await client.startConversation()\n * console.log('Opening message:', openingMessage)\n * ```\n *\n * ##### With context\n * ```ts\n * const openingMessage = await client.startConversation({ eligibleProducts: ['product-1', 'product-2'], productOverrides: { 'product-1': { price: 40 } } })\n * console.log('Opening message:', openingMessage)\n * ```\n */\n async startConversation(\n context?: components['schemas']['ConversationContext'],\n userMessage?: UserStartConversationMessage['openingUserMessage'],\n ): Promise<Message[]> {\n this.endConversation()\n\n const conversationContext = {\n ...context,\n }\n\n const { data } = await this.endpoint.conversation.POST(`/api/conversation/v3`, {\n body: {\n type: 'START_CONVERSATION',\n conversationContext,\n openingUserMessage: userMessage,\n },\n })\n\n if (!data) throw new SDKError('No data received from Conversation API')\n\n const [conversationIdMessage, ...rest] = data as [ConversationIdMessage, ...Message[]]\n\n const conversationId = conversationIdMessage.conversationId\n if (!conversationId) {\n throw new SDKError('Conversation ID not received in API response')\n }\n\n this.identity.conversationId = conversationId\n\n return rest\n }\n\n /**\n * Sends a message in the conversation.\n *\n * @param options - An object containing the user message.\n * @returns A promise that resolves to an array of messages\n *\n * @example\n * ```ts\n * const newMessages = await client.sendMessage({\n * userMessage: 'How can I get support?',\n * })\n *\n * if (newMessages) {\n * console.log('Received messages:', newMessages)\n * } else {\n * console.log('No message received')\n * }\n * ```\n */\n async sendMessage(payload: SendMessagePayload): Promise<Message[]> {\n const conversationId = this.identity.conversationId\n if (!conversationId) {\n throw new SDKError('Conversation ID not set')\n }\n\n const { data } = await this.endpoint.conversation.POST('/api/conversation/v3', {\n body: {\n conversationId,\n ...payload,\n },\n })\n\n if (!data) throw new SDKError('No data received from conversation API')\n\n // Removes any `CONVERSATION_ID` messages from the API response. In reality, these messages will only\n // appear in the response to a `START_CONVERSATION` request.\n return data.filter((message) => message.type !== 'CONVERSATION_ID')\n }\n\n /**\n * Sends an event to the tracking API, with the required properties already set.\n *\n * @param eventName - The name of the event to track.\n * @param properties - Additional properties to include in the event.\n * @returns A promise that resolves once the event is tracked.\n *\n * @example\n * ```ts\n * await client.trackEvent('entry_point-shown')\n * ```\n */\n async trackEvent(eventName: TrackingEvent['eventName'], properties?: TrackingEvent['additionalProperties']) {\n const body: TrackingEvent = {\n additionalProperties: properties,\n conversationId: this.identity.conversationId,\n eventName,\n pageviewId: this.identity.pageviewId ?? 'unknown',\n screenWidth: window.screen.width,\n screenHeight: window.screen.height,\n screenSize: window.screen.width <= 480 ? 'mobile' : 'large',\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n }\n\n return this.endpoint.frontend.POST('/api/tracking/user/v2', {\n body,\n })\n }\n\n /**\n * Gets an existing identity of the user.\n *\n * @returns An Identity object containing `customerId`, `conversationId`, `sessionId`, `userId`.\n *\n * @example\n * ```ts\n * identity = client.getIdentity()\n * console.log('Identity retrieved:', identity)\n * ```\n */\n getIdentity(): Identity {\n return this.identity\n }\n\n /**\n * Gets the JWT from the localStorage.\n * Use this method to retrieve the token for use in other parts of your system,\n * such as calling the Humara sales tracking API\n *\n * @returns {string | null} the JWT.\n *\n * @example\n * ```ts\n * token = client.getIdentityToken()\n * console.log('Identity token retrieved:', token)\n * ```\n */\n getIdentityToken(): string | null {\n return this.identity.token ?? null\n }\n\n /**\n * Gets the conversation history for a given conversation ID.\n *\n * @param conversationId - The ID of the conversation to retrieve.\n * @returns A promise that resolves to the conversation history as an array of turns. Each turn contains a user message and its corresponding response.\n */\n async getConversation(conversationId: string): Promise<RestoredTurn[]> {\n if (!conversationId) {\n throw new SDKError('Conversation ID not set')\n }\n\n try {\n const { data } = await this.endpoint.conversation.GET('/api/conversation/{conversation_id}/v1', {\n params: {\n path: {\n conversation_id: conversationId,\n },\n },\n })\n\n // Sets the current conversation ID to the one just retrieved, so that subsequent calls to `sendMessage` and `trackEvent` will use this conversation ID.\n this.identity.conversationId = conversationId\n\n if (!data) throw new SDKError('No data received from conversation history API')\n\n return restoreConversation(data)\n } catch (error) {\n throw new SDKError('Failed to get conversation history', {\n cause: error as Error,\n })\n }\n }\n}\n","const getItemWithExpiry = (key: string) => {\n const itemString = localStorage.getItem(key)\n\n if (!itemString) return null\n\n const item = JSON.parse(itemString) as { expires: number; value: string }\n\n if (Date.now() > item.expires) {\n localStorage.removeItem(key)\n\n return null\n }\n\n return item.value\n}\n\nexport default getItemWithExpiry\n","/**\n * Set an item in localStorage with an expiration time\n * @param key The key under which the value is stored in localStorage\n * @param value The value to be stored\n * @param ttl The time-to-live (TTL) in milliseconds\n */\nconst setItemWithExpiry = (key: string, value: string, ttl: number) => {\n const item = {\n expires: Date.now() + ttl,\n value,\n }\n\n localStorage.setItem(key, JSON.stringify(item))\n}\n\nexport default setItemWithExpiry\n","import type { Config, Identity } from '../types'\nimport { getItemWithExpiry, setItemWithExpiry } from '../utils'\n\ntype IdentityKey = 'conversationId' | 'sessionId' | 'token' | 'userId'\n\nconst day = 1000 * 60 * 60 * 24\nconst userIdTtl = day * 30\n\nconst conversationIdKey = '__15gifts_conversation_id'\nconst sessionIdKey = '__15gifts_session_id'\nconst tokenKey = '__15gifts_identity_token'\nconst userIdKey = '__15gifts_user_id'\n\nconst deleteConversationId = () => sessionStorage.removeItem(conversationIdKey)\nconst getConversationId = () => sessionStorage.getItem(conversationIdKey)\nconst setConversationId = (conversationId: string) => sessionStorage.setItem(conversationIdKey, conversationId)\n\nconst getSessionId = () => sessionStorage.getItem(sessionIdKey)\nconst setSessionId = (sessionId: string) => sessionStorage.setItem(sessionIdKey, sessionId)\n\nconst isTokenExpired = (token: string): boolean => {\n try {\n const [, payloadBase64] = token.split('.')\n if (!payloadBase64) {\n throw new Error('Invalid token payload')\n }\n const payload = JSON.parse(atob(payloadBase64))\n\n return payload.exp && Date.now() / 1000 > payload.exp\n } catch (error) {\n console.error('Invalid token format', error)\n return true\n }\n}\n\nconst getToken = (): string | null => {\n const token = localStorage.getItem(tokenKey)\n\n if (!token || isTokenExpired(token)) {\n localStorage.removeItem(tokenKey)\n return null\n }\n\n return token\n}\n\nconst setToken = (token: string) => localStorage.setItem(tokenKey, token)\n\nconst getUserId = () => {\n const userId = getItemWithExpiry(userIdKey)\n\n if (userId) {\n setUserId(userId)\n }\n\n return userId\n}\n\nconst setUserId = (userId: string) => setItemWithExpiry(userIdKey, userId, userIdTtl)\n\nconst createIdentityProperty = (\n getValue: () => string | null,\n setValue: (value: string) => void,\n clearValue?: () => void,\n): PropertyDescriptor => ({\n enumerable: true,\n configurable: true,\n get: () => getValue() ?? undefined,\n set: (value: string | undefined) => {\n if (value) {\n setValue(value)\n return\n }\n\n clearValue?.()\n },\n})\n\n/**\n * Creates an identity object backed by browser storage.\n *\n * The returned object exposes the public `Identity` shape while keeping\n * `conversationId`, `sessionId`, and `userId` synchronized with their\n * corresponding storage helpers.\n */\nexport const createIdentityStore = (customerId: Config['customerId']): Identity => {\n const identity: Identity = {\n customerId,\n }\n\n const properties: Record<IdentityKey, PropertyDescriptor> = {\n conversationId: createIdentityProperty(getConversationId, setConversationId, deleteConversationId),\n sessionId: createIdentityProperty(getSessionId, setSessionId),\n token: createIdentityProperty(getToken, setToken),\n userId: createIdentityProperty(getUserId, setUserId),\n }\n\n Object.defineProperties(identity, properties)\n\n return identity\n}\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for adding an `Authorization` header to requests.\n *\n * @param accessToken - The token to be included in the `Authorization` header.\n * @returns A middleware object that attaches the access token to the request headers.\n *\n * @example\n * ```ts\n * import { authMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(authMiddleware(accessToken))\n * ```\n */\nconst authMiddleware = (accessToken?: string): Middleware => ({\n onRequest: async ({ request }) => {\n const isIdentityEndpoint = request.url.includes('/identity/')\n if (isIdentityEndpoint) {\n return request\n }\n\n // Throw an error because we know the API will return a 401 if the access token is not set.\n if (!accessToken) {\n throw new Error('Access token is required for authentication.')\n }\n\n request.headers.set('Authorization', `Bearer ${accessToken}`)\n\n return request\n },\n})\n\nexport default authMiddleware\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for handling errors.\n *\n * @returns A middleware object that throws an error if the response is not ok.\n *\n * @example\n * ```ts\n * import { errorMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(errorMiddleware())\n * ```\n */\nconst errorMiddleware: Middleware = {\n // onError does not handle error responses with 4xx or 5xx HTTP status codes, since these are considered \"successful\" responses but with a bad status code.\n // In these cases we need to check the response's status property or ok() method via the onResponse callback.\n onResponse: async ({ response }) => {\n if (!response.ok) {\n const data = await response.json()\n\n throw new Error(data.message)\n }\n\n return response\n },\n}\n\nexport default errorMiddleware\n","import type { Middleware } from 'openapi-fetch'\n\nimport { Identity } from '../types'\n\n/**\n * Middleware for adding request headers that other services use for tracking.\n *\n * @param identity - The identity whose `pageviewId` is sent as `X-PAGEVIEW-ID`.\n * `X-PAGE-URL` is read from `window.location.href` on every request, so it follows SPA route changes.\n *\n * @returns A middleware object that adds the tracking headers to each request.\n *\n * @example\n * ```ts\n * this.endpoint.conversation.use(headerMiddleware(this.identity))\n * ```\n */\nconst headerMiddleware = (identity: Identity): Middleware => ({\n onRequest: async ({ request }) => {\n if (identity.pageviewId) {\n request.headers.set('X-PAGEVIEW-ID', identity.pageviewId)\n }\n request.headers.set('X-PAGE-URL', window.location.href)\n\n return request\n },\n})\n\nexport default headerMiddleware\n","/**\n * The GET `/api/conversation/{conversation_id}` endpoint returns data as a historical record, but\n * it makes little sense when rendered.\n * We transform it so that the user doesn't see answered single_select and multi_select messages again, only the\n * option(s) they selected.\n **/\n\nimport type {\n ConversationTurn,\n Message,\n MultiSelectMessage,\n SingleSelectMessage,\n UserSingleSelectMessage,\n RestoredTurn,\n} from '../types'\n\ntype UserMultiSelectMessage = Extract<ConversationTurn['userMessage'], { type: 'MULTI_SELECT' }>\n\ntype RestoreRule = 'keep' | 'hideOnceAnswered' | 'drop'\n\n/** How each assistant message type is restored. A new API message type fails the build until it has a rule here. */\nexport const RESTORE_RULES = {\n MESSAGE: 'keep',\n TITLE: 'keep',\n SINGLE_SELECT: 'hideOnceAnswered',\n MULTI_SELECT: 'hideOnceAnswered',\n EXIT_TO_CHAT: 'keep',\n EXIT_TO_PHONE: 'keep',\n EXIT_TO_PURCHASE: 'keep',\n EXIT_TO_PURCHASE_V2: 'keep',\n RECOMMENDATION: 'keep',\n RECOMMENDATION_V2: 'keep',\n CONVERSATION_ID: 'drop',\n} as const satisfies Record<ConversationTurn['assistantMessages'][number]['type'], RestoreRule>\n\n/**\n * Removes the conversationId from the user message, as this is not needed for rendering and would just add noise.\n */\nconst stripConversationId = <T extends { conversationId?: string }>(userMessage: T): Omit<T, 'conversationId'> => {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { conversationId, ...rest } = userMessage\n\n return rest\n}\n\n// We have the string that was sent to the API, this finds the label for the option that it relates to.\nconst getSelectedOptionLabel = (userMessage: UserSingleSelectMessage, previousTurn?: ConversationTurn) => {\n const previousSingleSelect = previousTurn?.assistantMessages.find(\n (message): message is SingleSelectMessage => message.type === 'SINGLE_SELECT',\n )\n const selectedOption = previousSingleSelect?.options.find((option) => option.value === userMessage.option)\n\n return selectedOption?.label || ''\n}\n\nconst getSelectedOptionLabels = (userMessage: UserMultiSelectMessage, previousTurn?: ConversationTurn) => {\n const previousMultiSelect = previousTurn?.assistantMessages.find(\n (message): message is MultiSelectMessage => message.type === 'MULTI_SELECT',\n )\n const selectedOptions = previousMultiSelect?.options.filter((option) => userMessage.options.includes(option.value))\n\n return selectedOptions?.map((option) => option.label).join(', ') || ''\n}\n\n// Turns the user message back in to how the user would have seen it\nconst getRestoredUserMessage = (\n turn: ConversationTurn,\n previousTurn?: ConversationTurn,\n): RestoredTurn['userMessage'] => {\n const { userMessage } = turn\n\n switch (userMessage.type) {\n case 'SINGLE_SELECT':\n return {\n ...stripConversationId(userMessage),\n userMessage: getSelectedOptionLabel(userMessage, previousTurn),\n }\n\n case 'START_CONVERSATION':\n // There isn't anything we want to render from the START_CONVERSATION message except for the openingUserMessage,\n // which is what the user would have submitted to start the conversation.\n return {\n type: 'MESSAGE',\n userMessage: userMessage.openingUserMessage?.option || '',\n }\n\n case 'MESSAGE':\n return stripConversationId(userMessage)\n\n case 'MULTI_SELECT':\n return {\n ...stripConversationId(userMessage),\n userMessage: getSelectedOptionLabels(userMessage, previousTurn),\n }\n }\n}\n\n// Turns the assistant message back in to how the user would have seen it\nconst getRestoredAssistantReply = (turn: ConversationTurn, nextTurn?: ConversationTurn) => {\n const isAnswered = Boolean(nextTurn)\n\n return turn.assistantMessages.filter((message): message is Message => {\n // undefined for types newer than this SDK; those are kept.\n const rule: RestoreRule | undefined = RESTORE_RULES[message.type]\n\n return rule !== 'drop' && !(rule === 'hideOnceAnswered' && isAnswered)\n })\n}\n\nexport const restoreConversation = (turns: ConversationTurn[]): RestoredTurn[] => {\n return turns.map((turn, index) => {\n const previousTurn = index > 0 ? turns[index - 1] : undefined\n const nextTurn = index < turns.length - 1 ? turns[index + 1] : undefined\n\n return {\n id: `restored-turn-${index}`,\n userMessage: getRestoredUserMessage(turn, previousTurn),\n assistantReply: getRestoredAssistantReply(turn, nextTurn),\n }\n })\n}\n","{\n \"name\": \"@15gifts/sdk\",\n \"version\": \"0.30.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\": \"tsc && tsup && npm run typecheck:dist\",\n \"coverage\": \"vitest run --coverage\",\n \"generate-types\": \"npx openapi-typescript\",\n \"dev\": \"tsup --watch\",\n \"format\": \"prettier . --write\",\n \"lint\": \"eslint .\",\n \"pact:publish:conversation\": \"tsx scripts/pact/publish-conversation.ts\",\n \"test\": \"vitest run\",\n \"test:consumer:conversation\": \"tsx scripts/pact/consumer-conversation.ts\",\n \"test:watch\": \"vitest\",\n \"typecheck:dist\": \"tsc --noEmit --skipLibCheck true dist/index.d.ts\",\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 \"@pact-foundation/pact\": \"^16.5.0\",\n \"@types/node\": \"^24.0.0\",\n \"openapi-typescript\": \"^7.13.0\",\n \"tsup\": \"^8.5.1\",\n \"tsx\": \"^4.23.13\"\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,gBCAjD,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,ECVf,IAAMM,EAAM,IAAO,GAAK,GAAK,GACvBC,EAAYD,EAA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gB,KAAK,SAAS,eAC9B,UAAAD,EACA,WAAY,KAAK,SAAS,YAAc,UACxC,YAAa,OAAO,OAAO,MAC3B,aAAc,OAAO,OAAO,OAC5B,WAAY,OAAO,OAAO,OAAS,IAAM,SAAW,QACpD,IAAK,OAAO,SAAS,KACrB,UAAW,OAAO,UAAU,SAC9B,EAEA,OAAO,KAAK,SAAS,SAAS,KAAK,wBAAyB,CAC1D,KAAAE,CACF,CAAC,CACH,CAaA,aAAwB,CACtB,OAAO,KAAK,QACd,CAeA,kBAAkC,CAChC,OAAO,KAAK,SAAS,OAAS,IAChC,CAQA,MAAM,gBAAgBL,EAAiD,CACrE,GAAI,CAACA,EACH,MAAM,IAAIT,EAAS,yBAAyB,EAG9C,GAAI,CACF,GAAM,CAAE,KAAAD,CAAK,EAAI,MAAM,KAAK,SAAS,aAAa,IAAI,yCAA0C,CAC9F,OAAQ,CACN,KAAM,CACJ,gBAAiBU,CACnB,CACF,CACF,CAAC,EAKD,GAFA,KAAK,SAAS,eAAiBA,EAE3B,CAACV,EAAM,MAAM,IAAIC,EAAS,gDAAgD,EAE9E,OAAOe,EAAoBhB,CAAI,CACjC,OAASI,EAAO,CACd,MAAM,IAAIH,EAAS,qCAAsC,CACvD,MAAOG,CACT,CAAC,CACH,CACF,CACF","names":["createClient","getItemWithExpiry","key","itemString","item","getItemWithExpiry_default","setItemWithExpiry","key","value","ttl","item","setItemWithExpiry_default","day","userIdTtl","conversationIdKey","sessionIdKey","tokenKey","userIdKey","deleteConversationId","getConversationId","setConversationId","conversationId","getSessionId","setSessionId","sessionId","isTokenExpired","token","payloadBase64","payload","error","getToken","setToken","getUserId","userId","getItemWithExpiry_default","setUserId","setItemWithExpiry_default","createIdentityProperty","getValue","setValue","clearValue","value","createIdentityStore","customerId","identity","properties","authMiddleware","accessToken","request","auth_default","errorMiddleware","response","data","error_default","headerMiddleware","identity","request","headers_default","RESTORE_RULES","stripConversationId","userMessage","conversationId","rest","getSelectedOptionLabel","previousTurn","message","option","getSelectedOptionLabels","getRestoredUserMessage","turn","getRestoredAssistantReply","nextTurn","isAnswered","rule","restoreConversation","turns","index","version","SDKError","_SDKError","userMessage","cause","version","Client","config","conversationUrl","customerId","fetch","frontendUrl","defaultHeaders","headers","version","createClient","createIdentityStore","error_default","headers_default","sessionId","userId","data","SDKError","endpoint","auth_default","error","context","userMessage","conversationContext","conversationIdMessage","rest","conversationId","payload","message","eventName","properties","body","restoreConversation"]}
|
|
1
|
+
{"version":3,"sources":["../src/client.ts","../src/utils/getItemWithExpiry.ts","../src/utils/setItemWithExpiry.ts","../src/identity/createIdentityStore.ts","../src/middlewares/auth.ts","../src/middlewares/error.ts","../src/middlewares/headers.ts","../src/restoreConversation/restoreConversation.ts","../package.json","../src/utils/SDKError.ts"],"sourcesContent":["import createClient, { type ClientOptions } from 'openapi-fetch'\n\nimport { createIdentityStore } from './identity/createIdentityStore'\nimport { authMiddleware, errorMiddleware, headerMiddleware } from './middlewares'\nimport { restoreConversation } from './restoreConversation/restoreConversation'\nimport type { components, paths as conversationPaths } from './schemas/conversation'\nimport type { paths as frontendPaths } from './schemas/frontend'\nimport type {\n Config,\n ConversationIdMessage,\n Endpoint,\n Identity,\n Message,\n RestoredTurn,\n SendMessagePayload,\n TrackingEvent,\n UserStartConversationMessage,\n} from './types'\nimport { version } from '../package.json'\nimport SDKError from './utils/SDKError'\n\n/**\n * The `Client` class provides methods to manage 15gifts API.\n */\nexport class Client {\n /**\n * This can be used to interact with the APIs directly. It is recommended to use the [helper methods](/sdk/sdk-reference/classes/client/#methods) provided by the `Client` class instead.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * const { data } = await client.endpoint.conversation.POST('/api/conversation/v3')\n * ```\n */\n endpoint: Endpoint\n\n /**\n * The identity information.\n */\n identity: Identity\n\n /**\n * Creates a new instance of the `Client` class.\n *\n * @param config - Configuration options for initializing the client.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * ```\n */\n constructor(config: Config) {\n const { conversationUrl, customerId, fetch, frontendUrl, headers: defaultHeaders } = config\n\n const headers: ClientOptions['headers'] = {\n ...defaultHeaders,\n 'X-SDK-VERSION': version,\n }\n\n this.endpoint = {\n conversation: createClient<conversationPaths>({\n baseUrl: conversationUrl,\n fetch,\n headers,\n credentials: 'include',\n }),\n frontend: createClient<frontendPaths>({ baseUrl: frontendUrl, fetch, headers }),\n }\n\n this.identity = createIdentityStore(customerId)\n\n this.endpoint.conversation.use(errorMiddleware)\n this.endpoint.conversation.use(headerMiddleware(this.identity))\n }\n\n /**\n * Creates a new identity for the user by generating a session ID and user ID if they don't exist, and sets the access token for future API calls.\n * Ends the current conversation if a conversation ID is present before sending a request to update identity.\n * This should not be called more than once per page load.\n *\n * @returns A promise that resolves once the identity is created and the access token is set.\n *\n * @example\n * ```ts\n * await client.createIdentity()\n * console.log('Identity created:', client.identity)\n * ```\n */\n async createIdentity(): Promise<void> {\n const { customerId, sessionId, userId } = this.identity\n\n try {\n const { data } = await this.endpoint.frontend.POST('/api/tracking/identity/v2', {\n body: {\n customerId,\n sessionId,\n userId,\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n },\n })\n\n if (!data) {\n throw new SDKError('No data received from identity API')\n }\n\n this.identity.pageviewId = data.pageviewId\n\n if (!sessionId) {\n this.identity.sessionId = data.sessionId\n }\n if (!userId) {\n this.identity.userId = data.userId\n }\n\n this.identity.token = data.token\n\n // Add the access token to the Authorization header for all endpoints\n Object.values(this.endpoint).forEach((endpoint) => {\n endpoint.use(authMiddleware(data.token))\n })\n } catch (error) {\n // Enable the auth middleware without a token so that it will throw an error before sending\n // the next request, preventing unnecessary API calls / 401 responses.\n Object.values(this.endpoint).forEach((endpoint) => {\n endpoint.use(authMiddleware())\n })\n throw new SDKError('Failed to create identity', {\n cause: error as Error,\n })\n }\n }\n\n /**\n * Ends the current conversation by deleting the conversation ID.\n *\n * @example\n * ```ts\n * client.endConversation()\n * console.log('Conversation ended')\n * ```\n */\n endConversation(): void {\n this.identity.conversationId = undefined\n }\n\n /**\n * Clears the existing conversation ID, then generates a new one and returns the opening message.\n *\n * @param context - Optional context to customize the conversation. It can include:\n * @param context.eligibleProducts An array of eligible product IDs.\n * @param context.eligibleBundles An array of eligible bundle IDs.\n * @param context.productOverrides Overrides for product details.\n * @param context.bundleOverrides Overrides for bundle details.\n *\n * @returns A promise that resolves to the opening message.\n *\n * @example\n * ##### Basic usage\n * ```ts\n * const openingMessage = await client.startConversation()\n * console.log('Opening message:', openingMessage)\n * ```\n *\n * ##### With context\n * ```ts\n * const openingMessage = await client.startConversation({ eligibleProducts: ['product-1', 'product-2'], productOverrides: { 'product-1': { price: 40 } } })\n * console.log('Opening message:', openingMessage)\n * ```\n */\n async startConversation(\n context?: components['schemas']['ConversationContext'],\n userMessage?: UserStartConversationMessage['openingUserMessage'],\n ): Promise<Message[]> {\n this.endConversation()\n\n const conversationContext = {\n ...context,\n }\n\n const { data } = await this.endpoint.conversation.POST(`/api/conversation/v3`, {\n body: {\n type: 'START_CONVERSATION',\n conversationContext,\n openingUserMessage: userMessage,\n },\n })\n\n if (!data) throw new SDKError('No data received from Conversation API')\n\n const [conversationIdMessage, ...rest] = data as [ConversationIdMessage, ...Message[]]\n\n const conversationId = conversationIdMessage.conversationId\n if (!conversationId) {\n throw new SDKError('Conversation ID not received in API response')\n }\n\n this.identity.conversationId = conversationId\n\n return rest\n }\n\n /**\n * Sends a message in the conversation.\n *\n * @param options - An object containing the user message.\n * @returns A promise that resolves to an array of messages\n *\n * @example\n * ```ts\n * const newMessages = await client.sendMessage({\n * userMessage: 'How can I get support?',\n * })\n *\n * if (newMessages) {\n * console.log('Received messages:', newMessages)\n * } else {\n * console.log('No message received')\n * }\n * ```\n */\n async sendMessage(payload: SendMessagePayload): Promise<Message[]> {\n const conversationId = this.identity.conversationId\n if (!conversationId) {\n throw new SDKError('Conversation ID not set')\n }\n\n const { data } = await this.endpoint.conversation.POST('/api/conversation/v3', {\n body: {\n conversationId,\n ...payload,\n },\n })\n\n if (!data) throw new SDKError('No data received from conversation API')\n\n // Removes any `CONVERSATION_ID` messages from the API response. In reality, these messages will only\n // appear in the response to a `START_CONVERSATION` request.\n return data.filter((message) => message.type !== 'CONVERSATION_ID')\n }\n\n /**\n * Sends an event to the tracking API, with the required properties already set.\n *\n * @param eventName - The name of the event to track.\n * @param properties - Additional properties to include in the event.\n * @returns A promise that resolves once the event is tracked.\n *\n * @example\n * ```ts\n * await client.trackEvent('entry_point-shown')\n * ```\n */\n async trackEvent(eventName: TrackingEvent['eventName'], properties?: TrackingEvent['additionalProperties']) {\n const body: TrackingEvent = {\n additionalProperties: properties,\n conversationId: this.identity.conversationId,\n eventName,\n pageviewId: this.identity.pageviewId ?? 'unknown',\n screenWidth: window.screen.width,\n screenHeight: window.screen.height,\n screenSize: window.screen.width <= 480 ? 'mobile' : 'large',\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n }\n\n return this.endpoint.frontend.POST('/api/tracking/user/v2', {\n body,\n })\n }\n\n /**\n * Gets an existing identity of the user.\n *\n * @returns An Identity object containing `customerId`, `conversationId`, `sessionId`, `userId`.\n *\n * @example\n * ```ts\n * identity = client.getIdentity()\n * console.log('Identity retrieved:', identity)\n * ```\n */\n getIdentity(): Identity {\n return this.identity\n }\n\n /**\n * Gets the JWT from the localStorage.\n * Use this method to retrieve the token for use in other parts of your system,\n * such as calling the Humara sales tracking API\n *\n * @returns {string | null} the JWT.\n *\n * @example\n * ```ts\n * token = client.getIdentityToken()\n * console.log('Identity token retrieved:', token)\n * ```\n */\n getIdentityToken(): string | null {\n return this.identity.token ?? null\n }\n\n /**\n * Gets the conversation history for a given conversation ID.\n *\n * @param conversationId - The ID of the conversation to retrieve.\n * @returns A promise that resolves to the conversation history as an array of turns. Each turn contains a user message and its corresponding response.\n */\n async getConversation(conversationId: string): Promise<RestoredTurn[]> {\n if (!conversationId) {\n throw new SDKError('Conversation ID not set')\n }\n\n try {\n const { data } = await this.endpoint.conversation.GET('/api/conversation/{conversation_id}/v1', {\n params: {\n path: {\n conversation_id: conversationId,\n },\n },\n })\n\n // Sets the current conversation ID to the one just retrieved, so that subsequent calls to `sendMessage` and `trackEvent` will use this conversation ID.\n this.identity.conversationId = conversationId\n\n if (!data) throw new SDKError('No data received from conversation history API')\n\n return restoreConversation(data)\n } catch (error) {\n throw new SDKError('Failed to get conversation history', {\n cause: error as Error,\n })\n }\n }\n}\n","const getItemWithExpiry = (key: string) => {\n const itemString = localStorage.getItem(key)\n\n if (!itemString) return null\n\n const item = JSON.parse(itemString) as { expires: number; value: string }\n\n if (Date.now() > item.expires) {\n localStorage.removeItem(key)\n\n return null\n }\n\n return item.value\n}\n\nexport default getItemWithExpiry\n","/**\n * Set an item in localStorage with an expiration time\n * @param key The key under which the value is stored in localStorage\n * @param value The value to be stored\n * @param ttl The time-to-live (TTL) in milliseconds\n */\nconst setItemWithExpiry = (key: string, value: string, ttl: number) => {\n const item = {\n expires: Date.now() + ttl,\n value,\n }\n\n localStorage.setItem(key, JSON.stringify(item))\n}\n\nexport default setItemWithExpiry\n","import type { Config, Identity } from '../types'\nimport { getItemWithExpiry, setItemWithExpiry } from '../utils'\n\ntype IdentityKey = 'conversationId' | 'sessionId' | 'token' | 'userId'\n\nconst day = 1000 * 60 * 60 * 24\nconst userIdTtl = day * 30\n\nconst conversationIdKey = '__15gifts_conversation_id'\nconst sessionIdKey = '__15gifts_session_id'\nconst tokenKey = '__15gifts_identity_token'\nconst userIdKey = '__15gifts_user_id'\n\nconst deleteConversationId = () => sessionStorage.removeItem(conversationIdKey)\nconst getConversationId = () => sessionStorage.getItem(conversationIdKey)\nconst setConversationId = (conversationId: string) => sessionStorage.setItem(conversationIdKey, conversationId)\n\nconst getSessionId = () => sessionStorage.getItem(sessionIdKey)\nconst setSessionId = (sessionId: string) => sessionStorage.setItem(sessionIdKey, sessionId)\n\nconst isTokenExpired = (token: string): boolean => {\n try {\n const [, payloadBase64] = token.split('.')\n if (!payloadBase64) {\n throw new Error('Invalid token payload')\n }\n const payload = JSON.parse(atob(payloadBase64))\n\n return payload.exp && Date.now() / 1000 > payload.exp\n } catch (error) {\n console.error('Invalid token format', error)\n return true\n }\n}\n\nconst getToken = (): string | null => {\n const token = localStorage.getItem(tokenKey)\n\n if (!token || isTokenExpired(token)) {\n localStorage.removeItem(tokenKey)\n return null\n }\n\n return token\n}\n\nconst setToken = (token: string) => localStorage.setItem(tokenKey, token)\n\nconst getUserId = () => {\n const userId = getItemWithExpiry(userIdKey)\n\n if (userId) {\n setUserId(userId)\n }\n\n return userId\n}\n\nconst setUserId = (userId: string) => setItemWithExpiry(userIdKey, userId, userIdTtl)\n\nconst createIdentityProperty = (\n getValue: () => string | null,\n setValue: (value: string) => void,\n clearValue?: () => void,\n): PropertyDescriptor => ({\n enumerable: true,\n configurable: true,\n get: () => getValue() ?? undefined,\n set: (value: string | undefined) => {\n if (value) {\n setValue(value)\n return\n }\n\n clearValue?.()\n },\n})\n\n/**\n * Creates an identity object backed by browser storage.\n *\n * The returned object exposes the public `Identity` shape while keeping\n * `conversationId`, `sessionId`, and `userId` synchronized with their\n * corresponding storage helpers.\n */\nexport const createIdentityStore = (customerId: Config['customerId']): Identity => {\n const identity: Identity = {\n customerId,\n }\n\n const properties: Record<IdentityKey, PropertyDescriptor> = {\n conversationId: createIdentityProperty(getConversationId, setConversationId, deleteConversationId),\n sessionId: createIdentityProperty(getSessionId, setSessionId),\n token: createIdentityProperty(getToken, setToken),\n userId: createIdentityProperty(getUserId, setUserId),\n }\n\n Object.defineProperties(identity, properties)\n\n return identity\n}\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for adding an `Authorization` header to requests.\n *\n * @param accessToken - The token to be included in the `Authorization` header.\n * @returns A middleware object that attaches the access token to the request headers.\n *\n * @example\n * ```ts\n * import { authMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(authMiddleware(accessToken))\n * ```\n */\nconst authMiddleware = (accessToken?: string): Middleware => ({\n onRequest: async ({ request }) => {\n const isIdentityEndpoint = request.url.includes('/identity/')\n if (isIdentityEndpoint) {\n return request\n }\n\n // Throw an error because we know the API will return a 401 if the access token is not set.\n if (!accessToken) {\n throw new Error('Access token is required for authentication.')\n }\n\n request.headers.set('Authorization', `Bearer ${accessToken}`)\n\n return request\n },\n})\n\nexport default authMiddleware\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for handling errors.\n *\n * @returns A middleware object that throws an error if the response is not ok.\n *\n * @example\n * ```ts\n * import { errorMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(errorMiddleware())\n * ```\n */\nconst errorMiddleware: Middleware = {\n // onError does not handle error responses with 4xx or 5xx HTTP status codes, since these are considered \"successful\" responses but with a bad status code.\n // In these cases we need to check the response's status property or ok() method via the onResponse callback.\n onResponse: async ({ response }) => {\n if (!response.ok) {\n const data = await response.json()\n\n throw new Error(data.message)\n }\n\n return response\n },\n}\n\nexport default errorMiddleware\n","import type { Middleware } from 'openapi-fetch'\n\nimport { Identity } from '../types'\n\n/**\n * Middleware for adding request headers that other services use for tracking.\n *\n * @param identity - The identity whose `pageviewId` is sent as `X-PAGEVIEW-ID`.\n * `X-PAGE-URL` is read from `window.location.href` on every request, so it follows SPA route changes.\n *\n * @returns A middleware object that adds the tracking headers to each request.\n *\n * @example\n * ```ts\n * this.endpoint.conversation.use(headerMiddleware(this.identity))\n * ```\n */\nconst headerMiddleware = (identity: Identity): Middleware => ({\n onRequest: async ({ request }) => {\n if (identity.pageviewId) {\n request.headers.set('X-PAGEVIEW-ID', identity.pageviewId)\n }\n request.headers.set('X-PAGE-URL', window.location.href)\n\n return request\n },\n})\n\nexport default headerMiddleware\n","/**\n * The GET `/api/conversation/{conversation_id}` endpoint returns data as a historical record, but\n * it makes little sense when rendered.\n * We transform it so that the user doesn't see answered single_select and multi_select messages again, only the\n * option(s) they selected.\n **/\n\nimport type {\n ConversationTurn,\n Message,\n MultiSelectMessage,\n SingleSelectMessage,\n UserSingleSelectMessage,\n RestoredTurn,\n} from '../types'\n\ntype UserMultiSelectMessage = Extract<ConversationTurn['userMessage'], { type: 'MULTI_SELECT' }>\n\ntype RestoreRule = 'keep' | 'hideOnceAnswered' | 'drop'\n\n/** How each assistant message type is restored. A new API message type fails the build until it has a rule here. */\nexport const RESTORE_RULES = {\n MESSAGE: 'keep',\n TITLE: 'keep',\n SINGLE_SELECT: 'hideOnceAnswered',\n MULTI_SELECT: 'hideOnceAnswered',\n EXIT_TO_CHAT: 'keep',\n EXIT_TO_PHONE: 'keep',\n EXIT_TO_PURCHASE: 'keep',\n EXIT_TO_PURCHASE_V2: 'keep',\n RECOMMENDATION: 'keep',\n RECOMMENDATION_V2: 'keep',\n CONVERSATION_ID: 'drop',\n} as const satisfies Record<ConversationTurn['assistantMessages'][number]['type'], RestoreRule>\n\n/**\n * Removes the conversationId from the user message, as this is not needed for rendering and would just add noise.\n */\nconst stripConversationId = <T extends { conversationId?: string }>(userMessage: T): Omit<T, 'conversationId'> => {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { conversationId, ...rest } = userMessage\n\n return rest\n}\n\n// We have the string that was sent to the API, this finds the label for the option that it relates to.\nconst getSelectedOptionLabel = (userMessage: UserSingleSelectMessage, previousTurn?: ConversationTurn) => {\n const previousSingleSelect = previousTurn?.assistantMessages.find(\n (message): message is SingleSelectMessage => message.type === 'SINGLE_SELECT',\n )\n const selectedOption = previousSingleSelect?.options.find((option) => option.value === userMessage.option)\n\n return selectedOption?.label || ''\n}\n\nconst getSelectedOptionLabels = (userMessage: UserMultiSelectMessage, previousTurn?: ConversationTurn) => {\n const previousMultiSelect = previousTurn?.assistantMessages.find(\n (message): message is MultiSelectMessage => message.type === 'MULTI_SELECT',\n )\n const selectedOptions = previousMultiSelect?.options.filter((option) => userMessage.options.includes(option.value))\n\n return selectedOptions?.map((option) => option.label).join(', ') || ''\n}\n\n// Turns the user message back in to how the user would have seen it\nconst getRestoredUserMessage = (\n turn: ConversationTurn,\n previousTurn?: ConversationTurn,\n): RestoredTurn['userMessage'] => {\n const { userMessage } = turn\n\n switch (userMessage.type) {\n case 'SINGLE_SELECT':\n return {\n ...stripConversationId(userMessage),\n userMessage: getSelectedOptionLabel(userMessage, previousTurn),\n }\n\n case 'START_CONVERSATION':\n // There isn't anything we want to render from the START_CONVERSATION message except for the openingUserMessage,\n // which is what the user would have submitted to start the conversation.\n return {\n type: 'MESSAGE',\n userMessage: userMessage.openingUserMessage?.option || '',\n }\n\n case 'MESSAGE':\n return stripConversationId(userMessage)\n\n case 'MULTI_SELECT':\n return {\n ...stripConversationId(userMessage),\n userMessage: getSelectedOptionLabels(userMessage, previousTurn),\n }\n }\n}\n\n// Turns the assistant message back in to how the user would have seen it\nconst getRestoredAssistantReply = (turn: ConversationTurn, nextTurn?: ConversationTurn) => {\n const isAnswered = Boolean(nextTurn)\n\n return turn.assistantMessages.filter((message): message is Message => {\n // undefined for types newer than this SDK; those are kept.\n const rule: RestoreRule | undefined = RESTORE_RULES[message.type]\n\n return rule !== 'drop' && !(rule === 'hideOnceAnswered' && isAnswered)\n })\n}\n\nexport const restoreConversation = (turns: ConversationTurn[]): RestoredTurn[] => {\n return turns.map((turn, index) => {\n const previousTurn = index > 0 ? turns[index - 1] : undefined\n const nextTurn = index < turns.length - 1 ? turns[index + 1] : undefined\n\n return {\n id: `restored-turn-${index}`,\n userMessage: getRestoredUserMessage(turn, previousTurn),\n assistantReply: getRestoredAssistantReply(turn, nextTurn),\n }\n })\n}\n","{\n \"name\": \"@15gifts/sdk\",\n \"version\": \"0.30.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\": \"tsc && tsup && npm run typecheck:dist\",\n \"coverage\": \"vitest run --coverage\",\n \"generate-types\": \"npx openapi-typescript\",\n \"dev\": \"tsup --watch\",\n \"format\": \"prettier . --write\",\n \"lint\": \"eslint .\",\n \"pact:publish:conversation\": \"tsx scripts/pact/publish-conversation.ts\",\n \"test\": \"vitest run\",\n \"test:consumer:conversation\": \"tsx scripts/pact/consumer-conversation.ts\",\n \"test:watch\": \"vitest\",\n \"typecheck:dist\": \"tsc --noEmit --skipLibCheck true dist/index.d.ts\",\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 \"@pact-foundation/pact\": \"^16.5.0\",\n \"@types/node\": \"^24.0.0\",\n \"openapi-typescript\": \"^7.13.0\",\n \"tsup\": \"^8.5.1\",\n \"tsx\": \"^4.23.13\"\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,gBCAjD,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,CAA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,CAcA,MAAM,WAAWC,EAAuCC,EAAoD,CAC1G,IAAMC,EAAsB,CAC1B,qBAAsBD,EACtB,eAAgB,KAAK,SAAS,eAC9B,UAAAD,EACA,WAAY,KAAK,SAAS,YAAc,UACxC,YAAa,OAAO,OAAO,MAC3B,aAAc,OAAO,OAAO,OAC5B,WAAY,OAAO,OAAO,OAAS,IAAM,SAAW,QACpD,IAAK,OAAO,SAAS,KACrB,UAAW,OAAO,UAAU,SAC9B,EAEA,OAAO,KAAK,SAAS,SAAS,KAAK,wBAAyB,CAC1D,KAAAE,CACF,CAAC,CACH,CAaA,aAAwB,CACtB,OAAO,KAAK,QACd,CAeA,kBAAkC,CAChC,OAAO,KAAK,SAAS,OAAS,IAChC,CAQA,MAAM,gBAAgBL,EAAiD,CACrE,GAAI,CAACA,EACH,MAAM,IAAIT,EAAS,yBAAyB,EAG9C,GAAI,CACF,GAAM,CAAE,KAAAD,CAAK,EAAI,MAAM,KAAK,SAAS,aAAa,IAAI,yCAA0C,CAC9F,OAAQ,CACN,KAAM,CACJ,gBAAiBU,CACnB,CACF,CACF,CAAC,EAKD,GAFA,KAAK,SAAS,eAAiBA,EAE3B,CAACV,EAAM,MAAM,IAAIC,EAAS,gDAAgD,EAE9E,OAAOe,EAAoBhB,CAAI,CACjC,OAASI,EAAO,CACd,MAAM,IAAIH,EAAS,qCAAsC,CACvD,MAAOG,CACT,CAAC,CACH,CACF,CACF","names":["createClient","getItemWithExpiry","key","itemString","item","getItemWithExpiry_default","setItemWithExpiry","key","value","ttl","item","setItemWithExpiry_default","day","userIdTtl","conversationIdKey","sessionIdKey","tokenKey","userIdKey","deleteConversationId","getConversationId","setConversationId","conversationId","getSessionId","setSessionId","sessionId","isTokenExpired","token","payloadBase64","payload","error","getToken","setToken","getUserId","userId","getItemWithExpiry_default","setUserId","setItemWithExpiry_default","createIdentityProperty","getValue","setValue","clearValue","value","createIdentityStore","customerId","identity","properties","authMiddleware","accessToken","request","auth_default","errorMiddleware","response","data","error_default","headerMiddleware","identity","request","headers_default","RESTORE_RULES","stripConversationId","userMessage","conversationId","rest","getSelectedOptionLabel","previousTurn","message","option","getSelectedOptionLabels","getRestoredUserMessage","turn","getRestoredAssistantReply","nextTurn","isAnswered","rule","restoreConversation","turns","index","version","SDKError","_SDKError","userMessage","cause","version","Client","config","conversationUrl","customerId","fetch","frontendUrl","defaultHeaders","headers","version","createClient","createIdentityStore","error_default","headers_default","sessionId","userId","data","SDKError","endpoint","auth_default","error","context","userMessage","conversationContext","conversationIdMessage","rest","conversationId","payload","message","eventName","properties","body","restoreConversation"]}
|