prezense 0.0.0-stage → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of prezense might be problematic. Click here for more details.

@@ -0,0 +1,80 @@
1
+ import { operation, text, number, invalidInput } from './graphql.js';
2
+
3
+ // Every value goes in as a GraphQL variable (graphql.js), never spliced into
4
+ // the query text.
5
+
6
+ function validItems(items) {
7
+ return Array.isArray(items) && items.length > 0 && !items.some((item) => item == null || typeof item !== 'object');
8
+ }
9
+
10
+ function invalidItems() {
11
+ return invalidInput('items must be a non-empty list of { variantID, quantity }');
12
+ }
13
+
14
+ function appendItemsInput(items) {
15
+ return items.map(i => ({ variantID: text(i.variantID), quantity: number(i.quantity) }));
16
+ }
17
+
18
+ export class PostPurchase {
19
+ constructor(client) {
20
+ this.client = client;
21
+ }
22
+
23
+ async recommendations({ orderID, userID, data, limit }) {
24
+ const args = {
25
+ orderID: ['String!', text(orderID)],
26
+ userID: ['String', text(userID)],
27
+ limit: ['Int', number(limit)],
28
+ };
29
+ return this.client.sendRequest(operation('query', 'getPostPurchaseRecommendations', args, data), 'getPostPurchaseRecommendations');
30
+ }
31
+
32
+ /**
33
+ * What adding `items` to an order charges the shopper. Call it right
34
+ * before creating the Stripe payment for the upsell, then charge
35
+ * `amountMinor` in `currency.toLowerCase()` and pass both to
36
+ * `appendItems` as paymentAmount / paymentCurrency.
37
+ *
38
+ * An order paid in another currency is charged in that same currency at
39
+ * the order's own rate; any other order is charged its base total.
40
+ * `taxAmount` is the tax on the added items, in the store's base currency.
41
+ *
42
+ * Fields: currency, amount, amountMinor, baseCurrency, baseAmount,
43
+ * exchangeRate, converted. All of them when `data` is left out.
44
+ */
45
+ async quoteCharge({ orderID, items, taxAmount, data } = {}) {
46
+ if (!validItems(items)) return invalidItems();
47
+ const args = {
48
+ orderID: ['String!', text(orderID)],
49
+ items: ['[AppendOrderItemInput!]!', appendItemsInput(items)],
50
+ taxAmount: ['Float', Number(taxAmount) || 0],
51
+ };
52
+ const selection = data ?? 'currency amount amountMinor baseCurrency baseAmount exchangeRate converted';
53
+ return this.client.sendRequest(operation('query', 'quotePostPurchaseCharge', args, selection), 'quotePostPurchaseCharge');
54
+ }
55
+
56
+ // paymentAmount / paymentCurrency: what the payment charged, as Stripe
57
+ // reports it on the PaymentIntent (`amount` in minor units, `currency`).
58
+ // Optional. When given, the append is refused unless they match
59
+ // quoteCharge.
60
+ async appendItems({ orderID, items, paymentReference, taxAmount, paymentAmount, paymentCurrency, data }) {
61
+ if (!validItems(items)) return invalidItems();
62
+ const args = {
63
+ orderID: ['String!', text(orderID)],
64
+ items: ['[AppendOrderItemInput!]!', appendItemsInput(items)],
65
+ paymentReference: ['String!', text(paymentReference)],
66
+ taxAmount: ['Float!', Number(taxAmount) || 0],
67
+ paymentAmount: ['Int', paymentAmount == null ? undefined : Math.round(Number(paymentAmount))],
68
+ paymentCurrency: ['String', paymentCurrency ? text(paymentCurrency).toUpperCase() : undefined],
69
+ };
70
+ return this.client.sendRequest(operation('mutation', 'appendItemsToOrder', args, data), 'appendItemsToOrder');
71
+ }
72
+
73
+ async rollbackAppend({ orderID, appendID, data }) {
74
+ const args = {
75
+ orderID: ['String!', text(orderID)],
76
+ appendID: ['String!', text(appendID)],
77
+ };
78
+ return this.client.sendRequest(operation('mutation', 'rollbackAppendedItems', args, data), 'rollbackAppendedItems');
79
+ }
80
+ }
package/prezanse.js ADDED
@@ -0,0 +1,262 @@
1
+ import fetch from 'node-fetch';
2
+ import { Products } from './products.js';
3
+ import { Cart } from './cart.js';
4
+ import { Locations } from './locations.js';
5
+ import { Promotions } from './promotions.js';
6
+ import { Media } from './media.js';
7
+ import { Reviews } from './reviews.js';
8
+ import { Accounts } from './accounts.js';
9
+ import { Orders } from './orders.js';
10
+ import { Analytics } from './analytics.js';
11
+ import { Shipping } from './shipping.js';
12
+ import { Personalization } from './personalization.js';
13
+ import { PostPurchase } from './post_purchase.js';
14
+ import { Trending } from './trending.js';
15
+ import { Search } from './search.js';
16
+ import { Bundles } from './bundles.js';
17
+ import { Currency } from './currency.js';
18
+ import { Loyalty } from './loyalty.js';
19
+ import { Fraud } from './fraud.js';
20
+ import { Alerts } from './alerts.js';
21
+ import { Collections } from './collections.js';
22
+ import { Pages } from './pages.js';
23
+ import { GiftCards } from './gift_cards.js';
24
+ import { sdkError } from './graphql.js';
25
+
26
+ const MODULES = [
27
+ 'products', 'cart', 'locations', 'promotions', 'media', 'reviews', 'accounts',
28
+ 'orders', 'analytics', 'shipping', 'personalization', 'postPurchase', 'trending',
29
+ 'search', 'bundles', 'currency', 'loyalty', 'fraud', 'alerts', 'collections',
30
+ 'pages', 'giftCards',
31
+ ];
32
+
33
+ const warned = new Set();
34
+
35
+ /** Warn once per process that an endpoint variable is missing in production. */
36
+ function warnOnce(variable, fallback) {
37
+ if (warned.has(variable)) return;
38
+ warned.add(variable);
39
+ console.warn(`[prezense] ${variable} is not set, so the SDK is using ${fallback}. Set ${variable} in this environment.`);
40
+ }
41
+
42
+ /**
43
+ * Wrap each async method of a module so it never throws: a call with no
44
+ * arguments is treated as a call with `{}` (so it gets the method's own
45
+ * error, e.g. MISSING_DATA), and anything thrown resolves to
46
+ * { error, response: null }.
47
+ */
48
+ function guard(module) {
49
+ const prototype = Object.getPrototypeOf(module);
50
+ for (const name of Object.getOwnPropertyNames(prototype)) {
51
+ if (name === 'constructor') continue;
52
+ const method = prototype[name];
53
+ if (typeof method !== 'function' || method.constructor.name !== 'AsyncFunction') continue;
54
+ module[name] = async (...args) => {
55
+ if (args[0] == null) args[0] = {};
56
+ try {
57
+ return await method.apply(module, args);
58
+ } catch (error) {
59
+ return { error, response: null };
60
+ }
61
+ };
62
+ }
63
+ }
64
+
65
+ export class Prezense {
66
+ constructor(apiKey, platformKey, options = {}) {
67
+ // `new Prezense({ ...options })` — options alone, keys from env — is
68
+ // the usual storefront form.
69
+ if (apiKey && typeof apiKey === 'object') {
70
+ options = apiKey;
71
+ apiKey = undefined;
72
+ platformKey = undefined;
73
+ }
74
+ // Credentials and endpoints all fall back to env so the SDK works with
75
+ // zero args inside an E2B sandbox (env injected by the harness). Explicit
76
+ // args still win; the localhost defaults keep local dev intact.
77
+ this.apiKey = apiKey || process.env.PREZENSE_API_KEY;
78
+ this.platformKey = platformKey || process.env.PREZENSE_PLATFORM_KEY;
79
+ this.currencyCode = options.currency || null;
80
+ // The shopper this request is for: { ip, userAgent }, read by the
81
+ // storefront from its incoming request. The SDK runs on the server, so
82
+ // without it Prezense would see the storefront server's IP and
83
+ // User-Agent instead of the shopper's — for fraud checks, currency
84
+ // detection and analytics (guides/shopper-context).
85
+ // An x-forwarded-for chain ("shopper, proxy, …") is cut to its first
86
+ // address, the shopper's.
87
+ this.shopper = options.shopper
88
+ ? {
89
+ ip: options.shopper.ip ? String(options.shopper.ip).split(',')[0].trim() : null,
90
+ userAgent: options.shopper.userAgent ? String(options.shopper.userAgent).slice(0, 500) : null,
91
+ }
92
+ : null;
93
+ this.baseUrl = options.baseUrl || process.env.PREZENSE_API_URL || 'http://localhost:4000/';
94
+ this.trackingUrl = options.trackingUrl || process.env.PREZENSE_TRACKING_URL || 'http://localhost:4001';
95
+ // In production a missing endpoint means every call goes to localhost
96
+ // and fails. Say so once per process, naming the variable to set.
97
+ if (process.env.NODE_ENV === 'production') {
98
+ if (!options.baseUrl && !process.env.PREZENSE_API_URL) warnOnce('PREZENSE_API_URL', this.baseUrl);
99
+ if (!options.trackingUrl && !process.env.PREZENSE_TRACKING_URL) warnOnce('PREZENSE_TRACKING_URL', this.trackingUrl);
100
+ }
101
+ // The HTTP client. node-fetch by default; `options.fetch` swaps it
102
+ // (tests pass a stub).
103
+ this.fetch = typeof options.fetch === 'function' ? options.fetch : fetch;
104
+
105
+ // Instantiate each category class
106
+ this.products = new Products(this);
107
+ this.cart = new Cart(this);
108
+ this.locations = new Locations(this);
109
+ this.promotions = new Promotions(this);
110
+ this.media = new Media(this);
111
+ this.reviews = new Reviews(this);
112
+ this.accounts = new Accounts(this);
113
+ this.orders = new Orders(this);
114
+ this.analytics = new Analytics(this);
115
+ this.shipping = new Shipping(this);
116
+ this.personalization = new Personalization(this);
117
+ this.postPurchase = new PostPurchase(this);
118
+ this.trending = new Trending(this);
119
+ this.search = new Search(this);
120
+ this.bundles = new Bundles(this);
121
+ this.currency = new Currency(this);
122
+ this.loyalty = new Loyalty(this);
123
+ this.fraud = new Fraud(this);
124
+ this.alerts = new Alerts(this);
125
+ this.collections = new Collections(this);
126
+ this.pages = new Pages(this);
127
+ this.giftCards = new GiftCards(this);
128
+
129
+ // Every method resolves { error, response } and never throws, even
130
+ // when called with no arguments or with input it can't use.
131
+ for (const name of MODULES) guard(this[name]);
132
+ }
133
+
134
+ /** The shopper's IP and User-Agent, forwarded so Prezense sees the shopper, not this server. */
135
+ #shopperHeaders() {
136
+ const headers = {};
137
+ const ip = this.shopper?.ip;
138
+ const userAgent = this.shopper?.userAgent;
139
+ if (ip) headers['x-shopper-ip'] = ip;
140
+ if (userAgent) headers['x-shopper-user-agent'] = userAgent;
141
+ return headers;
142
+ }
143
+
144
+ // Method to send a request directly to the GraphQL server
145
+ //
146
+ // Resolves { error, response }:
147
+ // - an operation that couldn't be built (operation() in graphql.js,
148
+ // e.g. MISSING_DATA): that error, without calling the API;
149
+ // - GraphQL errors: the first one as { message, code, details }, where
150
+ // details is the error's `extensions` minus `code` (null if none).
151
+ // Any partial data sent alongside errors is not returned;
152
+ // - a reply that isn't JSON: code INVALID_RESPONSE with the HTTP status;
153
+ // - network failures: the underlying error, as before.
154
+ async sendRequest(query, dataField) {
155
+ if (query && query.error) return { error: query.error, response: null };
156
+ try {
157
+
158
+ const headers = {
159
+ 'Content-Type': 'application/json',
160
+ 'x-api-key': this.apiKey,
161
+ 'x-platform-key': this.platformKey,
162
+ };
163
+
164
+ if (this.currencyCode) {
165
+ headers['x-currency'] = this.currencyCode;
166
+ }
167
+ Object.assign(headers, this.#shopperHeaders());
168
+
169
+ const response = await this.fetch(this.baseUrl, {
170
+ method: 'POST',
171
+ headers,
172
+ body: JSON.stringify(query),
173
+ });
174
+
175
+ const body = await response.text();
176
+ let result;
177
+ try {
178
+ result = JSON.parse(body);
179
+ } catch {
180
+ return {
181
+ error: sdkError(
182
+ `The Prezense API sent a reply that isn't JSON (HTTP ${response.status}).`,
183
+ 'INVALID_RESPONSE',
184
+ { status: response.status },
185
+ ),
186
+ response: null,
187
+ };
188
+ }
189
+
190
+ // Check for errors in the response
191
+ if (Array.isArray(result?.errors) && result.errors.length > 0) {
192
+ // Keep the machine-readable code (e.g. FRAUD_RISK_TOO_HIGH) so
193
+ // callers can branch on it instead of matching message text,
194
+ // and the rest of the extensions (e.g. productIDsNotInStore)
195
+ // as `details`.
196
+ const first = result.errors[0] ?? {};
197
+ const { code: extensionCode, ...rest } = first.extensions ?? {};
198
+ const details = Object.keys(rest).length > 0 ? rest : null;
199
+ const error = sdkError(
200
+ first.message ?? 'The Prezense API returned an error.',
201
+ first.code ?? extensionCode ?? null,
202
+ { details },
203
+ );
204
+ return { error, response: null };
205
+ }
206
+
207
+ // If no errors, return the data
208
+ return { error: null, response: result?.data?.[dataField] ?? null };
209
+ } catch (error) {
210
+ return { error, response: null };
211
+ }
212
+ }
213
+
214
+ // Resolves { error, response }. The reply is read as text, then parsed as
215
+ // JSON when it is JSON (otherwise `response` is the text, or null when
216
+ // empty). A non-2xx reply resolves to
217
+ // { error: { message, code, status }, response: null }, with the server's
218
+ // own `error`/`message` and `code` when it sent them, else
219
+ // code TRACKING_ERROR. Network failures resolve to the underlying error.
220
+ async trackEvent(endpoint, body) {
221
+ try {
222
+
223
+ const response = await this.fetch(`${this.trackingUrl}/track/${endpoint}`, {
224
+ method: 'POST',
225
+ headers: {
226
+ 'Content-Type': 'application/json',
227
+ 'apikey': this.apiKey,
228
+ 'platformkey': this.platformKey,
229
+ ...this.#shopperHeaders(),
230
+ },
231
+ body: JSON.stringify(body),
232
+ });
233
+
234
+ const raw = await response.text();
235
+ let result = raw === '' ? null : raw;
236
+ try {
237
+ if (raw !== '') result = JSON.parse(raw);
238
+ } catch {
239
+ // Not JSON: keep the text.
240
+ }
241
+
242
+ if (!response.ok) {
243
+ const server = result && typeof result === 'object' ? result : {};
244
+ const serverMessage = typeof server.error === 'string' ? server.error : server.message;
245
+ const error = sdkError(
246
+ serverMessage || `The tracking request failed (HTTP ${response.status}).`,
247
+ server.code || 'TRACKING_ERROR',
248
+ { status: response.status },
249
+ );
250
+ return { error, response: null };
251
+ }
252
+
253
+ return { error: null, response: result };
254
+
255
+ } catch (error) {
256
+ return { error, response: null };
257
+ }
258
+ }
259
+ }
260
+
261
+
262
+
package/products.js ADDED
@@ -0,0 +1,108 @@
1
+ import { operation, text, number, bool, textList } from './graphql.js';
2
+
3
+ // Every value goes in as a GraphQL variable (graphql.js), never spliced into
4
+ // the query text — search boxes and category links carry shopper text.
5
+
6
+ export class Products {
7
+ constructor(client) {
8
+ this.client = client;
9
+ }
10
+
11
+ async product({ productID, data }) {
12
+ const args = { productID: ['String!', text(productID)] };
13
+ return this.client.sendRequest(operation('query', 'getProductById', args, data), 'getProductById');
14
+ }
15
+
16
+ async allProducts({ data, limit, offset }) {
17
+ const args = { limit: ['Int', number(limit)], offset: ['Int', number(offset)] };
18
+ return this.client.sendRequest(operation('query', 'getAllProducts', args, data), 'getAllProducts');
19
+ }
20
+
21
+ async productsByID({ productIDs, data, limit, offset }) {
22
+ const args = {
23
+ productIDs: ['[String!]!', textList(productIDs)],
24
+ limit: ['Int', number(limit)],
25
+ offset: ['Int', number(offset)],
26
+ };
27
+ return this.client.sendRequest(operation('query', 'getProductsById', args, data), 'getProductsById');
28
+ }
29
+
30
+ async collectionProducts({ collection, data, limit, offset }) {
31
+ const args = {
32
+ collection: ['String!', text(collection)],
33
+ limit: ['Int', number(limit)],
34
+ offset: ['Int', number(offset)],
35
+ };
36
+ return this.client.sendRequest(operation('query', 'getProductsByCollection', args, data), 'getProductsByCollection');
37
+ }
38
+
39
+ async categoryProducts({ category, data, limit, offset }) {
40
+ const args = {
41
+ category: ['String!', text(category)],
42
+ limit: ['Int', number(limit)],
43
+ offset: ['Int', number(offset)],
44
+ };
45
+ return this.client.sendRequest(operation('query', 'getProductsByCategory', args, data), 'getProductsByCategory');
46
+ }
47
+
48
+ async typeProducts({ type, data, limit, offset }) {
49
+ const args = {
50
+ type: ['String!', text(type)],
51
+ limit: ['Int', number(limit)],
52
+ offset: ['Int', number(offset)],
53
+ };
54
+ return this.client.sendRequest(operation('query', 'getProductsByType', args, data), 'getProductsByType');
55
+ }
56
+
57
+ async brandProducts({ brand, data, limit, offset }) {
58
+ const args = {
59
+ brand: ['String!', text(brand)],
60
+ limit: ['Int', number(limit)],
61
+ offset: ['Int', number(offset)],
62
+ };
63
+ return this.client.sendRequest(operation('query', 'getProductsByBrand', args, data), 'getProductsByBrand');
64
+ }
65
+
66
+ async productVariants({ productID, data }) {
67
+ const args = { productID: ['String!', text(productID)] };
68
+ return this.client.sendRequest(operation('query', 'getVariantsById', args, data), 'getVariantsById');
69
+ }
70
+
71
+ async personalizedRecommendations({ userID, data, limit }) {
72
+ const args = { userID: ['String!', text(userID)], limit: ['Int', number(limit)] };
73
+ return this.client.sendRequest(operation('query', 'getPersonalizedRecommendations', args, data), 'getPersonalizedRecommendations');
74
+ }
75
+
76
+ async searchProducts({ query, data, limit, offset }) {
77
+ // The search text is sent as typed — quotes and backslashes included.
78
+ const args = {
79
+ query: ['String!', text(query)],
80
+ limit: ['Int', number(limit)],
81
+ offset: ['Int', number(offset)],
82
+ };
83
+ return this.client.sendRequest(operation('query', 'searchProducts', args, data), 'searchProducts');
84
+ }
85
+
86
+ async trendingProducts({ timeWindow, category, data, limit, minScore, includeProductDetails }) {
87
+ // Arguments left out fall back to the server's defaults.
88
+ const args = {
89
+ timeWindow: ['String!', text(timeWindow)],
90
+ category: ['String', text(category)],
91
+ limit: ['Int', number(limit)],
92
+ minScore: ['Float', number(minScore)],
93
+ includeProductDetails: ['Boolean!', bool(includeProductDetails)],
94
+ };
95
+ return this.client.sendRequest(operation('query', 'getTrendingProducts', args, data), 'getTrendingProducts');
96
+ }
97
+
98
+ async purchaseBundles({ productId, data, limit, minConfidence }) {
99
+ // Values go in as GraphQL variables, never spliced into the query text.
100
+ const args = {
101
+ productId: ['String!', text(productId)],
102
+ limit: ['Int', number(limit)],
103
+ minConfidence: ['Float', number(minConfidence)],
104
+ };
105
+ return this.client.sendRequest(operation('query', 'getProductPurchaseBundles', args, data), 'getProductPurchaseBundles');
106
+ }
107
+
108
+ }
package/promotions.js ADDED
@@ -0,0 +1,42 @@
1
+ import { operation, text, number } from './graphql.js';
2
+
3
+ // Every value goes in as a GraphQL variable (graphql.js), never spliced into
4
+ // the query text.
5
+
6
+ export class Promotions {
7
+ constructor(client) {
8
+ this.client = client;
9
+ }
10
+
11
+ async hasSale({ productID, data, limit, offset }) {
12
+ const args = {
13
+ productID: ['String!', text(productID)],
14
+ limit: ['Int', number(limit)],
15
+ offset: ['Int', number(offset)],
16
+ };
17
+ return this.client.sendRequest(operation('query', 'checkIfProductHasSale', args, data), 'checkIfProductHasSale');
18
+ }
19
+
20
+ async hasDiscount({ productID, data, limit, offset }) {
21
+ const args = {
22
+ productID: ['String!', text(productID)],
23
+ limit: ['Int', number(limit)],
24
+ offset: ['Int', number(offset)],
25
+ };
26
+ return this.client.sendRequest(operation('query', 'checkIfProductHasDiscount', args, data), 'checkIfProductHasDiscount');
27
+ }
28
+
29
+ async hasPromoCode({ productID, data, limit, offset }) {
30
+ const args = {
31
+ productID: ['String!', text(productID)],
32
+ limit: ['Int', number(limit)],
33
+ offset: ['Int', number(offset)],
34
+ };
35
+ return this.client.sendRequest(operation('query', 'checkIfProductHasPromoCode', args, data), 'checkIfProductHasPromoCode');
36
+ }
37
+
38
+ async hasFreeShipping({ productID }) {
39
+ const args = { productID: ['String!', text(productID)] };
40
+ return this.client.sendRequest(operation('query', 'checkIfProductHasFreeShipping', args), 'checkIfProductHasFreeShipping');
41
+ }
42
+ }
package/reviews.js ADDED
@@ -0,0 +1,51 @@
1
+ import { operation, text, number, textList } from './graphql.js';
2
+
3
+ export class Reviews {
4
+ constructor(client) {
5
+ this.client = client;
6
+ }
7
+
8
+ // Every value goes in as a GraphQL variable, never spliced into the query
9
+ // text, so reviews with newlines, quotes or backslashes are sent intact.
10
+ // IDs may be numbers or strings; ratings, limits and offsets may be
11
+ // numbers or numeric strings.
12
+
13
+ // reviewerName (up to 100 characters) and title (up to 150) are optional:
14
+ // left out, they aren't sent and the review has no name or headline.
15
+ async addReview({ productID, rating, review, customerEmail, reviewerName, title }) {
16
+ // addProductReview returns a String, so no field selection.
17
+ const args = {
18
+ productID: ['String!', text(productID)],
19
+ rating: ['Int!', number(rating)],
20
+ review: ['String!', text(review)],
21
+ customerEmail: ['String!', text(customerEmail)],
22
+ reviewerName: ['String', text(reviewerName)],
23
+ title: ['String', text(title)],
24
+ };
25
+ return this.client.sendRequest(operation('mutation', 'addProductReview', args), 'addProductReview');
26
+ }
27
+
28
+ async getAllReviewsOfProduct({ productID, data, limit, offset }) {
29
+ const args = {
30
+ productID: ['String!', text(productID)],
31
+ limit: ['Int', number(limit)],
32
+ offset: ['Int', number(offset)],
33
+ };
34
+ return this.client.sendRequest(operation('query', 'getAllReviewsOfProduct', args, data), 'getAllReviewsOfProduct');
35
+ }
36
+
37
+ async getReviewByID({ reviewID, data }) {
38
+ const args = { reviewID: ['String!', text(reviewID)] };
39
+ return this.client.sendRequest(operation('query', 'getReviewByID', args, data), 'getReviewByID');
40
+ }
41
+
42
+ async getReviewsByID({ reviewIDs, data }) {
43
+ const args = { reviewIDs: ['[String!]!', textList(reviewIDs)] };
44
+ return this.client.sendRequest(operation('query', 'getListOfReviewsByIDs', args, data), 'getListOfReviewsByIDs');
45
+ }
46
+
47
+ async getProductRatingSummary({ productID, data }) {
48
+ const args = { productID: ['String!', text(productID)] };
49
+ return this.client.sendRequest(operation('query', 'getProductRatingSummary', args, data), 'getProductRatingSummary');
50
+ }
51
+ }
package/search.js ADDED
@@ -0,0 +1,18 @@
1
+ import { operation, text, number } from './graphql.js';
2
+
3
+ export class Search {
4
+ constructor(client) {
5
+ this.client = client;
6
+ }
7
+
8
+ async products({ query, data, limit, offset }) {
9
+ // The search text goes in as a GraphQL variable, sent as typed —
10
+ // quotes and backslashes included — never spliced into the query text.
11
+ const args = {
12
+ query: ['String!', text(query)],
13
+ limit: ['Int', number(limit)],
14
+ offset: ['Int', number(offset)],
15
+ };
16
+ return this.client.sendRequest(operation('query', 'searchProducts', args, data), 'searchProducts');
17
+ }
18
+ }
package/shipping.js ADDED
@@ -0,0 +1,42 @@
1
+ import { operation, text, textList } from './graphql.js';
2
+
3
+ // Every value goes in as a GraphQL variable (graphql.js), never spliced into
4
+ // the query text.
5
+
6
+ export class Shipping {
7
+ constructor(client) {
8
+ this.client = client;
9
+ }
10
+
11
+ /**
12
+ * The carriers the merchant has connected, each as
13
+ * { carrierName, displayName, serviceCodes }. Pass a carrierName and
14
+ * serviceCodes from here to `rates`. An empty list means none are
15
+ * connected.
16
+ */
17
+ async carriers({ data }) {
18
+ return this.client.sendRequest(operation('query', 'getShippingCarriers', {}, data), 'getShippingCarriers');
19
+ }
20
+
21
+ async rates({ cartID, carrierName, serviceCodes, data }) {
22
+ const args = {
23
+ cartID: ['String!', text(cartID)],
24
+ carrierName: ['String!', text(carrierName)],
25
+ serviceCodes: ['[String!]!', textList(serviceCodes)],
26
+ };
27
+ return this.client.sendRequest(operation('mutation', 'shippingRates', args, data), 'shippingRates');
28
+ }
29
+
30
+ async validateRates({ cartID, data }) {
31
+ const args = { cartID: ['String!', text(cartID)] };
32
+ return this.client.sendRequest(operation('query', 'validateShippingRates', args, data), 'validateShippingRates');
33
+ }
34
+
35
+ async saveShippingOption({ cartID, serviceCode, data }) {
36
+ const args = {
37
+ cartID: ['String!', text(cartID)],
38
+ serviceCode: ['String!', text(serviceCode)],
39
+ };
40
+ return this.client.sendRequest(operation('mutation', 'saveCustomerShippingOption', args, data), 'saveCustomerShippingOption');
41
+ }
42
+ }
@@ -0,0 +1,44 @@
1
+ // Charging in the shopper's currency: cart.prepareCheckoutPayment and the
2
+ // new orders.create arguments. Offline, like offline.test.js.
3
+ import { test } from 'node:test';
4
+ import assert from 'node:assert/strict';
5
+ import { Prezense } from '../index.js';
6
+
7
+ function client(body = { data: {} }) {
8
+ const calls = [];
9
+ const fetch = async (url, init) => {
10
+ calls.push(JSON.parse(init.body));
11
+ const text = JSON.stringify(body);
12
+ return { ok: true, status: 200, text: async () => text, json: async () => JSON.parse(text) };
13
+ };
14
+ const sdk = new Prezense('key', 'platform', { baseUrl: 'http://api.test/', trackingUrl: 'http://track.test', fetch });
15
+ return { sdk, calls };
16
+ }
17
+
18
+ test('prepareCheckoutPayment asks for every field by default and returns the charge', async () => {
19
+ const charge = { currency: 'CAD', amount: 74.68, amountMinor: 7468, baseCurrency: 'USD', baseAmount: 50.5, exchangeRate: 1.4274, converted: true };
20
+ const { sdk, calls } = client({ data: { prepareCheckoutPayment: charge } });
21
+ const result = await sdk.cart.prepareCheckoutPayment({ cartID: 'c1' });
22
+ assert.deepEqual(result.response, charge);
23
+ assert.match(calls[0].query, /mutation \(\$cartID: String!\)/);
24
+ assert.match(calls[0].query, /prepareCheckoutPayment\(cartID: \$cartID\) \{ currency amount amountMinor baseCurrency baseAmount exchangeRate converted \}/);
25
+ assert.deepEqual(calls[0].variables, { cartID: 'c1' });
26
+ });
27
+
28
+ test('prepareCheckoutPayment without a cart ID makes no request', async () => {
29
+ const { sdk, calls } = client();
30
+ const result = await sdk.cart.prepareCheckoutPayment({});
31
+ assert.equal(result.error.code, 'MISSING_CART_ID');
32
+ assert.equal(calls.length, 0);
33
+ });
34
+
35
+ test('orders.create sends what the payment charged, and leaves it out when not given', async () => {
36
+ const { sdk, calls } = client({ data: { createOrder: { success: true } } });
37
+ await sdk.orders.create({ cartID: 'c1', stripePaymentIntentID: 'pi_1', paymentAmount: 7468, paymentCurrency: 'cad', data: 'success' });
38
+ assert.match(calls[0].query, /\$paymentAmount: Int, \$paymentCurrency: String/);
39
+ assert.deepEqual(calls[0].variables, { cartID: 'c1', stripePaymentIntentID: 'pi_1', paymentAmount: 7468, paymentCurrency: 'CAD' });
40
+
41
+ await sdk.orders.create({ cartID: 'c1', stripePaymentIntentID: 'pi_1', data: 'success' });
42
+ assert.doesNotMatch(calls[1].query, /payment(Amount|Currency)/);
43
+ assert.deepEqual(calls[1].variables, { cartID: 'c1', stripePaymentIntentID: 'pi_1' });
44
+ });