prezense 1.3.0 → 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.
- package/accounts.js +12 -25
- package/alerts.js +3 -3
- package/bundles.js +11 -6
- package/cart.js +33 -3
- package/cli.js +335 -8
- package/currency.js +3 -0
- package/fraud.js +13 -25
- package/graphql.js +41 -2
- package/loyalty.js +11 -17
- package/orders.js +28 -21
- package/package.json +4 -1
- package/post_purchase.js +46 -3
- package/prezanse.js +117 -11
- package/products.js +6 -5
- package/reviews.js +29 -31
- package/shipping.js +10 -0
- package/test/checkout-payment.test.js +44 -0
- package/test/offline.test.js +261 -0
- package/test/post-purchase-charge.test.js +56 -0
package/accounts.js
CHANGED
|
@@ -14,35 +14,22 @@ export class Accounts {
|
|
|
14
14
|
}
|
|
15
15
|
|
|
16
16
|
async addUserInformation({ email, fingerprint, userInformation, data }) {
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
}
|
|
23
|
-
`;
|
|
24
|
-
const variables = {
|
|
25
|
-
email,
|
|
26
|
-
fingerprint,
|
|
27
|
-
userInformation, // Pass as JS object with snake_case keys
|
|
17
|
+
// userInformation is sent as given (a UserInformationInput object).
|
|
18
|
+
const args = {
|
|
19
|
+
email: ['String!', text(email)],
|
|
20
|
+
fingerprint: ['String!', text(fingerprint)],
|
|
21
|
+
userInformation: ['UserInformationInput!', userInformation ?? null],
|
|
28
22
|
};
|
|
29
|
-
return this.client.sendRequest(
|
|
30
|
-
|
|
23
|
+
return this.client.sendRequest(operation('mutation', 'addUserInformation', args, data), 'addUserInformation');
|
|
24
|
+
}
|
|
31
25
|
|
|
32
26
|
async updateUserInformation({ email, fingerprint, userInformation, data }) {
|
|
33
|
-
const
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
`;
|
|
40
|
-
const variables = {
|
|
41
|
-
email,
|
|
42
|
-
fingerprint,
|
|
43
|
-
userInformation // This should be a JS object with the correct schema fields
|
|
27
|
+
const args = {
|
|
28
|
+
email: ['String!', text(email)],
|
|
29
|
+
fingerprint: ['String!', text(fingerprint)],
|
|
30
|
+
userInformation: ['UserInformationInput!', userInformation ?? null],
|
|
44
31
|
};
|
|
45
|
-
return this.client.sendRequest(
|
|
32
|
+
return this.client.sendRequest(operation('mutation', 'updateUserInformation', args, data), 'updateUserInformation');
|
|
46
33
|
}
|
|
47
34
|
|
|
48
35
|
async addProductToWishlist({ email, productID, data }) {
|
package/alerts.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { sdkError } from './graphql.js';
|
|
2
|
+
|
|
1
3
|
/**
|
|
2
4
|
* Product alerts — a shopper asks to be emailed when a product is back in
|
|
3
5
|
* stock, or when its price drops. Server-side only, like every SDK call.
|
|
@@ -24,9 +26,7 @@ export class Alerts {
|
|
|
24
26
|
const { error, response } = await this.client.trackEvent(endpoint, body);
|
|
25
27
|
if (error) return { error, response: null };
|
|
26
28
|
if (response?.error) {
|
|
27
|
-
|
|
28
|
-
failure.code = response.code ?? null;
|
|
29
|
-
return { error: failure, response: null };
|
|
29
|
+
return { error: sdkError(String(response.error), response.code ?? null), response: null };
|
|
30
30
|
}
|
|
31
31
|
return { error: null, response };
|
|
32
32
|
}
|
package/bundles.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { operation, text, number } from './graphql.js';
|
|
2
|
+
|
|
1
3
|
export class Bundles {
|
|
2
4
|
constructor(client) {
|
|
3
5
|
this.client = client;
|
|
@@ -5,10 +7,13 @@ export class Bundles {
|
|
|
5
7
|
|
|
6
8
|
async purchaseBundles({ productId, data, limit, minConfidence }) {
|
|
7
9
|
// Values go in as GraphQL variables, never spliced into the query text.
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
10
|
+
// productId may be a number or a string; limit and minConfidence may
|
|
11
|
+
// be numbers or numeric strings. Left out, the server defaults apply.
|
|
12
|
+
const args = {
|
|
13
|
+
productId: ['String!', text(productId)],
|
|
14
|
+
limit: ['Int', number(limit)],
|
|
15
|
+
minConfidence: ['Float', number(minConfidence)],
|
|
16
|
+
};
|
|
17
|
+
return this.client.sendRequest(operation('query', 'getProductPurchaseBundles', args, data), 'getProductPurchaseBundles');
|
|
13
18
|
}
|
|
14
|
-
}
|
|
19
|
+
}
|
package/cart.js
CHANGED
|
@@ -12,11 +12,11 @@
|
|
|
12
12
|
* docs guide guides/cart-persistence.
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
|
-
import { operation, text, number, textInput } from './graphql.js';
|
|
15
|
+
import { operation, text, number, textInput, sdkError, invalidInput } from './graphql.js';
|
|
16
16
|
|
|
17
17
|
function missingCartID() {
|
|
18
18
|
return {
|
|
19
|
-
error:
|
|
19
|
+
error: sdkError('cartID is required — pass the shopper\'s cart ID (see guides/cart-persistence).', 'MISSING_CART_ID'),
|
|
20
20
|
response: null,
|
|
21
21
|
};
|
|
22
22
|
}
|
|
@@ -198,13 +198,43 @@ export class Cart {
|
|
|
198
198
|
async setTaxAmount({ cartID, taxAmount, data }) {
|
|
199
199
|
if (!cartID) return missingCartID();
|
|
200
200
|
|
|
201
|
+
// A number or a numeric string ("4.5"). Anything else is refused rather
|
|
202
|
+
// than quietly sent as 0.
|
|
203
|
+
const isBlank = taxAmount == null || (typeof taxAmount === 'string' && taxAmount.trim() === '');
|
|
204
|
+
const amount = isBlank || typeof taxAmount === 'boolean' ? NaN : Number(taxAmount);
|
|
205
|
+
if (!Number.isFinite(amount)) {
|
|
206
|
+
return invalidInput('taxAmount must be a number, e.g. 4.5');
|
|
207
|
+
}
|
|
208
|
+
|
|
201
209
|
const args = {
|
|
202
210
|
cartID: ['String!', text(cartID)],
|
|
203
|
-
taxAmount: ['Float!',
|
|
211
|
+
taxAmount: ['Float!', amount],
|
|
204
212
|
};
|
|
205
213
|
return this.client.sendRequest(operation('mutation', 'setCartTaxAmount', args, data), 'setCartTaxAmount');
|
|
206
214
|
}
|
|
207
215
|
|
|
216
|
+
/**
|
|
217
|
+
* The exact amount and currency to charge for the cart — what the shopper
|
|
218
|
+
* sees (displayTotal in the client's currency, rounded by the store's
|
|
219
|
+
* price-rounding rule), or the base total when nothing is converted.
|
|
220
|
+
* Call it right before creating the Stripe payment, then charge
|
|
221
|
+
* `amountMinor` in `currency.toLowerCase()` and pass both to
|
|
222
|
+
* `orders.create` as paymentAmount / paymentCurrency.
|
|
223
|
+
*
|
|
224
|
+
* Fields: currency, amount, amountMinor, baseCurrency, baseAmount,
|
|
225
|
+
* exchangeRate, converted. All of them when `data` is left out.
|
|
226
|
+
*/
|
|
227
|
+
async prepareCheckoutPayment({ cartID, data } = {}) {
|
|
228
|
+
if (!cartID) return missingCartID();
|
|
229
|
+
|
|
230
|
+
const args = { cartID: ['String!', text(cartID)] };
|
|
231
|
+
const selection = data ?? 'currency amount amountMinor baseCurrency baseAmount exchangeRate converted';
|
|
232
|
+
return this.client.sendRequest(
|
|
233
|
+
operation('mutation', 'prepareCheckoutPayment', args, selection),
|
|
234
|
+
'prepareCheckoutPayment',
|
|
235
|
+
);
|
|
236
|
+
}
|
|
237
|
+
|
|
208
238
|
async removePromoCode({ cartID, data }) {
|
|
209
239
|
if (!cartID) return missingCartID();
|
|
210
240
|
|
package/cli.js
CHANGED
|
@@ -9,9 +9,21 @@
|
|
|
9
9
|
// never node_modules, build output, .git or .env files — and Prezense installs,
|
|
10
10
|
// builds and publishes it, then switches the store's live address over. A
|
|
11
11
|
// failed publish leaves the live site as it was.
|
|
12
|
+
//
|
|
13
|
+
// `prezense upload` — put images, videos and audio from your computer into the
|
|
14
|
+
// store's media library, optionally on a product:
|
|
15
|
+
//
|
|
16
|
+
// npx prezense upload ./photos --product "Diamond necklace"
|
|
17
|
+
//
|
|
18
|
+
// It asks the store's MCP server (the same tools an AI agent uses:
|
|
19
|
+
// start_media_upload, finish_media_upload, get_media_upload_status) for a
|
|
20
|
+
// one-time upload link per file, sends each file straight to it with a
|
|
21
|
+
// progress bar, then waits while videos and audio are processed.
|
|
12
22
|
|
|
13
23
|
import { spawn } from 'node:child_process';
|
|
14
|
-
import { existsSync, readFileSync } from 'node:fs';
|
|
24
|
+
import { createReadStream, existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
|
|
25
|
+
import http from 'node:http';
|
|
26
|
+
import https from 'node:https';
|
|
15
27
|
import path from 'node:path';
|
|
16
28
|
|
|
17
29
|
const DEFAULT_DEPLOY_URL = 'https://deploy.prezense.app';
|
|
@@ -27,13 +39,23 @@ const EXCLUDES = [
|
|
|
27
39
|
'./.env', './.env.*',
|
|
28
40
|
];
|
|
29
41
|
|
|
30
|
-
const HELP = `Usage:
|
|
42
|
+
const HELP = `Usage:
|
|
43
|
+
prezense deploy [folder]
|
|
44
|
+
prezense upload <files or folders…> [--product <id or name>] [--as thumbnail|gallery]
|
|
31
45
|
|
|
32
|
-
Publishes the storefront in [folder] (default: the current folder) to
|
|
33
|
-
Prezense store whose keys it uses.
|
|
34
|
-
PREZENSE_PLATFORM_KEY from the environment, .env.local or .env.
|
|
46
|
+
deploy Publishes the storefront in [folder] (default: the current folder) to
|
|
47
|
+
the Prezense store whose keys it uses.
|
|
35
48
|
|
|
36
|
-
|
|
49
|
+
upload Adds images (png, jpg, gif, webp), videos (mp4, mov) and audio
|
|
50
|
+
(mp3, wav) to the store's media library. A folder adds every such file
|
|
51
|
+
directly inside it. --product links them to a product (its id, or its
|
|
52
|
+
name); --as thumbnail makes an image the product's main picture
|
|
53
|
+
(default: gallery). Shows each file's upload and processing progress
|
|
54
|
+
and prints its media link when done.
|
|
55
|
+
|
|
56
|
+
Both read PREZENSE_API_KEY and PREZENSE_PLATFORM_KEY from the environment,
|
|
57
|
+
.env.local or .env. Copy those keys from the Prezense app: Settings → Your own
|
|
58
|
+
agents.`;
|
|
37
59
|
|
|
38
60
|
function readEnvFile(file) {
|
|
39
61
|
const values = {};
|
|
@@ -144,12 +166,317 @@ async function deploy(folder) {
|
|
|
144
166
|
}
|
|
145
167
|
}
|
|
146
168
|
|
|
147
|
-
|
|
169
|
+
// ── prezense upload ─────────────────────────────────────────────────────────
|
|
170
|
+
|
|
171
|
+
const DEFAULT_STORE_MCP_URL = 'https://mcp.prezense.app/mcp';
|
|
172
|
+
const MEDIA_EXTENSIONS = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'mp4', 'mov', 'mp3', 'wav']);
|
|
173
|
+
const PARALLEL_UPLOADS = 3;
|
|
174
|
+
const STATUS_POLL_MS = 3000;
|
|
175
|
+
const PROCESSING_TIMEOUT_MS = 30 * 60 * 1000;
|
|
176
|
+
|
|
177
|
+
function parseUploadArgs(args) {
|
|
178
|
+
const paths = [];
|
|
179
|
+
let product = null;
|
|
180
|
+
let as = null;
|
|
181
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
182
|
+
const arg = args[i];
|
|
183
|
+
const [flag, inline] = arg.startsWith('--') ? arg.split(/=(.*)/s) : [arg];
|
|
184
|
+
if (flag === '--product' || flag === '--as') {
|
|
185
|
+
const value = inline ?? args[++i];
|
|
186
|
+
if (!value) throw new Error(`${flag} needs a value`);
|
|
187
|
+
if (flag === '--product') product = value;
|
|
188
|
+
else as = value;
|
|
189
|
+
} else if (arg.startsWith('--')) {
|
|
190
|
+
throw new Error(`unknown option ${arg}`);
|
|
191
|
+
} else {
|
|
192
|
+
paths.push(arg);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
if (as && as !== 'thumbnail' && as !== 'gallery') throw new Error('--as must be thumbnail or gallery');
|
|
196
|
+
if (as && !product) throw new Error('--as needs --product as well');
|
|
197
|
+
if (!paths.length) throw new Error('name at least one file or folder to upload');
|
|
198
|
+
return { paths, product, as };
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const extOf = (file) => path.extname(file).slice(1).toLowerCase();
|
|
202
|
+
|
|
203
|
+
/* Files to send: each file named, and the media files directly inside each folder. */
|
|
204
|
+
function collectFiles(paths) {
|
|
205
|
+
const files = [];
|
|
206
|
+
for (const raw of paths) {
|
|
207
|
+
const full = path.resolve(raw);
|
|
208
|
+
if (!existsSync(full)) throw new Error(`${raw} doesn't exist`);
|
|
209
|
+
if (statSync(full).isDirectory()) {
|
|
210
|
+
const found = readdirSync(full)
|
|
211
|
+
.filter((name) => !name.startsWith('.') && MEDIA_EXTENSIONS.has(extOf(name)))
|
|
212
|
+
.map((name) => path.join(full, name))
|
|
213
|
+
.filter((file) => statSync(file).isFile())
|
|
214
|
+
.sort();
|
|
215
|
+
if (!found.length) console.log(`No images, videos or audio in ${raw}.`);
|
|
216
|
+
files.push(...found);
|
|
217
|
+
} else if (MEDIA_EXTENSIONS.has(extOf(full))) {
|
|
218
|
+
files.push(full);
|
|
219
|
+
} else {
|
|
220
|
+
throw new Error(`${raw} isn't a file type the media library takes (${[...MEDIA_EXTENSIONS].join(', ')})`);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
return [...new Set(files)];
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/* One MCP tool call over HTTP (JSON-RPC tools/call; the server is stateless).
|
|
227
|
+
The answer may come back as plain JSON or as one server-sent event. */
|
|
228
|
+
let rpcId = 0;
|
|
229
|
+
async function callTool(endpoint, headers, name, args) {
|
|
230
|
+
rpcId += 1;
|
|
231
|
+
const id = rpcId; // calls run in parallel, so each keeps its own id
|
|
232
|
+
let res;
|
|
233
|
+
try {
|
|
234
|
+
res = await fetch(endpoint, {
|
|
235
|
+
method: 'POST',
|
|
236
|
+
headers: { ...headers, 'content-type': 'application/json', accept: 'application/json, text/event-stream' },
|
|
237
|
+
body: JSON.stringify({ jsonrpc: '2.0', id, method: 'tools/call', params: { name, arguments: args } }),
|
|
238
|
+
});
|
|
239
|
+
} catch (err) {
|
|
240
|
+
throw new Error(`couldn't reach Prezense at ${endpoint} (${err.cause?.code || err.message})`);
|
|
241
|
+
}
|
|
242
|
+
const text = await res.text();
|
|
243
|
+
let message = null;
|
|
244
|
+
if ((res.headers.get('content-type') || '').includes('text/event-stream')) {
|
|
245
|
+
for (const line of text.split(/\r?\n/)) {
|
|
246
|
+
if (!line.startsWith('data:')) continue;
|
|
247
|
+
try {
|
|
248
|
+
const parsed = JSON.parse(line.slice(5));
|
|
249
|
+
if (parsed.id === id) message = parsed;
|
|
250
|
+
} catch { /* not JSON */ }
|
|
251
|
+
}
|
|
252
|
+
} else {
|
|
253
|
+
try { message = JSON.parse(text); } catch { /* below */ }
|
|
254
|
+
}
|
|
255
|
+
if (!message) throw new Error(`Prezense answered ${res.status} to ${name}`);
|
|
256
|
+
if (message.error) throw new Error(message.error.message || `${name} failed`);
|
|
257
|
+
const content = message.result?.content?.[0]?.text;
|
|
258
|
+
let body;
|
|
259
|
+
try { body = JSON.parse(content); } catch { body = { success: false, error: content || `${name} gave no answer` }; }
|
|
260
|
+
if (message.result?.isError && body.success !== false) body = { success: false, error: content };
|
|
261
|
+
return body;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/* PUTs a file to its upload link, reporting bytes sent. */
|
|
265
|
+
function putFile(url, file, size, contentType, onProgress) {
|
|
266
|
+
return new Promise((resolve, reject) => {
|
|
267
|
+
const target = new URL(url);
|
|
268
|
+
const request = (target.protocol === 'http:' ? http : https).request(target, {
|
|
269
|
+
method: 'PUT',
|
|
270
|
+
headers: { 'Content-Type': contentType, 'Content-Length': size },
|
|
271
|
+
}, (res) => {
|
|
272
|
+
let body = '';
|
|
273
|
+
res.on('data', (c) => { body += c; });
|
|
274
|
+
res.on('end', () => {
|
|
275
|
+
if (res.statusCode >= 200 && res.statusCode < 300) resolve();
|
|
276
|
+
else reject(new Error(`the upload was refused (HTTP ${res.statusCode}${/<Code>([^<]+)/.exec(body)?.[1] ? `, ${/<Code>([^<]+)/.exec(body)[1]}` : ''})`));
|
|
277
|
+
});
|
|
278
|
+
});
|
|
279
|
+
request.on('error', (err) => reject(new Error(`the upload failed (${err.code || err.message})`)));
|
|
280
|
+
let sent = 0;
|
|
281
|
+
const stream = createReadStream(file);
|
|
282
|
+
stream.on('data', (chunk) => {
|
|
283
|
+
sent += chunk.length;
|
|
284
|
+
onProgress(sent);
|
|
285
|
+
});
|
|
286
|
+
stream.on('error', (err) => request.destroy(err));
|
|
287
|
+
stream.pipe(request);
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/* The per-file lines. On a terminal they are redrawn in place; otherwise each
|
|
292
|
+
change of stage is printed once. */
|
|
293
|
+
function progressBoard(names) {
|
|
294
|
+
const tty = process.stdout.isTTY;
|
|
295
|
+
const width = Math.min(40, Math.max(...names.map((n) => n.length)));
|
|
296
|
+
const rows = names.map(() => ({ text: 'waiting', bar: null, last: '' }));
|
|
297
|
+
let drawn = 0;
|
|
298
|
+
const bar = (pct) => {
|
|
299
|
+
const filled = Math.round((pct / 100) * 20);
|
|
300
|
+
return `[${'█'.repeat(filled)}${'░'.repeat(20 - filled)}] ${String(Math.round(pct)).padStart(3)}%`;
|
|
301
|
+
};
|
|
302
|
+
const line = (i) => {
|
|
303
|
+
const name = names[i].length > width ? `${names[i].slice(0, width - 1)}…` : names[i].padEnd(width);
|
|
304
|
+
const { text, bar: pct } = rows[i];
|
|
305
|
+
return ` ${name} ${pct === null ? '' : `${bar(pct)} `}${text}`;
|
|
306
|
+
};
|
|
307
|
+
const draw = () => {
|
|
308
|
+
if (!tty) return;
|
|
309
|
+
if (drawn) process.stdout.write(`\x1b[${drawn}A`);
|
|
310
|
+
for (let i = 0; i < rows.length; i += 1) process.stdout.write(`\x1b[2K${line(i)}\n`);
|
|
311
|
+
drawn = rows.length;
|
|
312
|
+
};
|
|
313
|
+
let timer = null;
|
|
314
|
+
return {
|
|
315
|
+
set(i, text, pct = null) {
|
|
316
|
+
rows[i].text = text;
|
|
317
|
+
rows[i].bar = pct;
|
|
318
|
+
if (tty) {
|
|
319
|
+
if (!timer) timer = setTimeout(() => { timer = null; draw(); }, 100);
|
|
320
|
+
} else if (rows[i].last !== text) {
|
|
321
|
+
rows[i].last = text;
|
|
322
|
+
console.log(line(i));
|
|
323
|
+
}
|
|
324
|
+
},
|
|
325
|
+
flush() {
|
|
326
|
+
if (timer) { clearTimeout(timer); timer = null; }
|
|
327
|
+
draw();
|
|
328
|
+
},
|
|
329
|
+
};
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
async function mapLimit(items, limit, fn) {
|
|
333
|
+
let next = 0;
|
|
334
|
+
const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
|
|
335
|
+
while (next < items.length) {
|
|
336
|
+
const i = next++;
|
|
337
|
+
await fn(items[i], i);
|
|
338
|
+
}
|
|
339
|
+
});
|
|
340
|
+
await Promise.all(workers);
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
const CONTENT_TYPES = {
|
|
344
|
+
png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp',
|
|
345
|
+
mp4: 'video/mp4', mov: 'video/quicktime', mp3: 'audio/mpeg', wav: 'audio/wav',
|
|
346
|
+
};
|
|
347
|
+
|
|
348
|
+
async function upload(args) {
|
|
349
|
+
const { paths, product, as } = parseUploadArgs(args);
|
|
350
|
+
const files = collectFiles(paths);
|
|
351
|
+
if (!files.length) throw new Error('nothing to upload');
|
|
352
|
+
|
|
353
|
+
const dir = process.cwd();
|
|
354
|
+
const apiKey = setting('PREZENSE_API_KEY', dir);
|
|
355
|
+
const platformKey = setting('PREZENSE_PLATFORM_KEY', dir);
|
|
356
|
+
if (!apiKey || !platformKey) {
|
|
357
|
+
throw new Error('PREZENSE_API_KEY and PREZENSE_PLATFORM_KEY are not set. Copy them into .env.local from Settings → Your own agents in the Prezense app.');
|
|
358
|
+
}
|
|
359
|
+
const endpoint = setting('PREZENSE_STORE_MCP_URL', dir) || DEFAULT_STORE_MCP_URL;
|
|
360
|
+
const headers = { 'x-api-key': apiKey, 'x-platform-key': platformKey };
|
|
361
|
+
|
|
362
|
+
console.log(`Uploading ${files.length} file${files.length === 1 ? '' : 's'} to store "${platformKey}"${product ? `, for product ${product}${as ? ` (${as})` : ''}` : ''}:`);
|
|
363
|
+
const names = files.map((f) => path.basename(f));
|
|
364
|
+
const board = progressBoard(names);
|
|
365
|
+
const results = files.map(() => ({ uploadId: null, done: false, url: null, error: null }));
|
|
366
|
+
|
|
367
|
+
await mapLimit(files, PARALLEL_UPLOADS, async (file, i) => {
|
|
368
|
+
const result = results[i];
|
|
369
|
+
try {
|
|
370
|
+
const size = statSync(file).size;
|
|
371
|
+
board.set(i, 'starting');
|
|
372
|
+
const started = await callTool(endpoint, headers, 'start_media_upload', {
|
|
373
|
+
file_name: file,
|
|
374
|
+
size_bytes: size,
|
|
375
|
+
content_type: CONTENT_TYPES[extOf(file)],
|
|
376
|
+
...(product ? { product } : {}),
|
|
377
|
+
...(as ? { as } : {}),
|
|
378
|
+
});
|
|
379
|
+
if (!started.success) throw new Error(started.error);
|
|
380
|
+
const { upload_id: uploadId, upload } = started.data;
|
|
381
|
+
result.uploadId = uploadId;
|
|
382
|
+
// The link is signed with this exact Content-Type; sending any
|
|
383
|
+
// other is refused by S3.
|
|
384
|
+
const contentType = upload.headers?.['Content-Type'] ?? CONTENT_TYPES[extOf(file)];
|
|
385
|
+
await putFile(upload.url, file, size, contentType, (sent) => {
|
|
386
|
+
board.set(i, 'uploading', (sent / size) * 100);
|
|
387
|
+
});
|
|
388
|
+
board.set(i, 'uploaded', 100);
|
|
389
|
+
const finished = await callTool(endpoint, headers, 'finish_media_upload', { upload_id: uploadId });
|
|
390
|
+
if (!finished.success) throw new Error(finished.error);
|
|
391
|
+
applyStatus(board, i, result, finished.data);
|
|
392
|
+
} catch (err) {
|
|
393
|
+
result.done = true;
|
|
394
|
+
result.error = err.message;
|
|
395
|
+
board.set(i, `failed: ${err.message}`);
|
|
396
|
+
}
|
|
397
|
+
});
|
|
398
|
+
|
|
399
|
+
// Videos and audio are processed after they arrive; wait for them.
|
|
400
|
+
const started = Date.now();
|
|
401
|
+
for (;;) {
|
|
402
|
+
const pending = results.map((r, i) => [r, i]).filter(([r]) => !r.done && r.uploadId);
|
|
403
|
+
if (!pending.length) break;
|
|
404
|
+
if (Date.now() - started > PROCESSING_TIMEOUT_MS) {
|
|
405
|
+
for (const [r, i] of pending) {
|
|
406
|
+
r.done = true;
|
|
407
|
+
board.set(i, 'still processing — check the Media page in the Prezense app');
|
|
408
|
+
}
|
|
409
|
+
break;
|
|
410
|
+
}
|
|
411
|
+
await sleep(STATUS_POLL_MS);
|
|
412
|
+
try {
|
|
413
|
+
const status = await callTool(endpoint, headers, 'get_media_upload_status', {
|
|
414
|
+
upload_ids: pending.map(([r]) => r.uploadId),
|
|
415
|
+
});
|
|
416
|
+
if (!status.success) throw new Error(status.error);
|
|
417
|
+
for (const u of status.data.uploads) {
|
|
418
|
+
const hit = pending.find(([r]) => r.uploadId === u.upload_id);
|
|
419
|
+
if (hit) applyStatus(board, hit[1], hit[0], u);
|
|
420
|
+
}
|
|
421
|
+
} catch (err) {
|
|
422
|
+
// A blip while polling isn't a failed upload; try again next round.
|
|
423
|
+
if (process.env.DEBUG) console.error(err.message);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
board.flush();
|
|
427
|
+
|
|
428
|
+
const failed = results.filter((r) => r.error).length;
|
|
429
|
+
console.log('');
|
|
430
|
+
results.forEach((r, i) => {
|
|
431
|
+
if (r.url) console.log(` ${names[i]} → ${r.url}`);
|
|
432
|
+
});
|
|
433
|
+
console.log(failed
|
|
434
|
+
? `\n${files.length - failed} of ${files.length} done; ${failed} failed.`
|
|
435
|
+
: `\nDone: ${files.length} file${files.length === 1 ? '' : 's'} in the media library.`);
|
|
436
|
+
if (failed) process.exitCode = 1;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
function applyStatus(board, i, result, data) {
|
|
440
|
+
switch (data.stage) {
|
|
441
|
+
case 'completed':
|
|
442
|
+
result.done = true;
|
|
443
|
+
result.url = data.url;
|
|
444
|
+
board.set(i, 'done', 100);
|
|
445
|
+
break;
|
|
446
|
+
case 'failed':
|
|
447
|
+
result.done = true;
|
|
448
|
+
result.error = data.message || data.reason;
|
|
449
|
+
board.set(i, `failed: ${data.message || data.reason}`);
|
|
450
|
+
break;
|
|
451
|
+
case 'processing':
|
|
452
|
+
board.set(i, 'processing', Number(data.percent) || 0);
|
|
453
|
+
break;
|
|
454
|
+
case 'file_received':
|
|
455
|
+
board.set(i, 'uploaded, waiting to process', 100);
|
|
456
|
+
break;
|
|
457
|
+
case 'waiting_for_file':
|
|
458
|
+
board.set(i, 'waiting for the file to arrive');
|
|
459
|
+
break;
|
|
460
|
+
default:
|
|
461
|
+
result.done = true;
|
|
462
|
+
result.error = data.error || 'unknown upload';
|
|
463
|
+
board.set(i, `failed: ${result.error}`);
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
const [command, ...rest] = process.argv.slice(2);
|
|
148
468
|
if (command === 'deploy') {
|
|
149
|
-
deploy(
|
|
469
|
+
deploy(rest[0]).catch((err) => {
|
|
150
470
|
console.error(`\nprezense deploy: ${err.message}`);
|
|
151
471
|
process.exit(1);
|
|
152
472
|
});
|
|
473
|
+
} else if (command === 'upload' && !rest.some((a) => a === '--help' || a === '-h')) {
|
|
474
|
+
upload(rest).catch((err) => {
|
|
475
|
+
console.error(`\nprezense upload: ${err.message}`);
|
|
476
|
+
process.exit(1);
|
|
477
|
+
});
|
|
478
|
+
} else if (command === 'upload') {
|
|
479
|
+
console.log(HELP);
|
|
153
480
|
} else {
|
|
154
481
|
console.log(HELP);
|
|
155
482
|
process.exit(command && command !== 'help' && command !== '--help' && command !== '-h' ? 1 : 0);
|
package/currency.js
CHANGED
|
@@ -54,6 +54,7 @@ export class Currency {
|
|
|
54
54
|
const selection = `
|
|
55
55
|
originalAmount
|
|
56
56
|
convertedAmount
|
|
57
|
+
roundedAmount
|
|
57
58
|
fromCurrency
|
|
58
59
|
toCurrency
|
|
59
60
|
rate
|
|
@@ -80,6 +81,8 @@ export class Currency {
|
|
|
80
81
|
baseCurrency
|
|
81
82
|
multiCurrencyEnabled
|
|
82
83
|
conversionMode
|
|
84
|
+
priceRounding
|
|
85
|
+
roundingDirection
|
|
83
86
|
supportedCurrencies {
|
|
84
87
|
currencyCode
|
|
85
88
|
manualRate
|
package/fraud.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { operation, text } from './graphql.js';
|
|
2
|
+
|
|
1
3
|
export class Fraud {
|
|
2
4
|
constructor(client) {
|
|
3
5
|
this.client = client;
|
|
@@ -10,12 +12,8 @@ export class Fraud {
|
|
|
10
12
|
* Assess the fraud risk of a cart before authorizing payment.
|
|
11
13
|
*/
|
|
12
14
|
async assessCartFraudRisk({ cartID, data }) {
|
|
13
|
-
const
|
|
14
|
-
|
|
15
|
-
${data.trim()}
|
|
16
|
-
}
|
|
17
|
-
}`;
|
|
18
|
-
return this.client.sendRequest({ query, variables: { cartID } }, 'assessCartFraudRisk');
|
|
15
|
+
const args = { cartID: ['String!', text(cartID)] };
|
|
16
|
+
return this.client.sendRequest(operation('query', 'assessCartFraudRisk', args, data), 'assessCartFraudRisk');
|
|
19
17
|
}
|
|
20
18
|
|
|
21
19
|
/**
|
|
@@ -23,24 +21,16 @@ export class Fraud {
|
|
|
23
21
|
* the cart's customer email; the response carries only a masked hint.
|
|
24
22
|
*/
|
|
25
23
|
async issueFraudChallenge({ cartID, data }) {
|
|
26
|
-
const
|
|
27
|
-
|
|
28
|
-
${data.trim()}
|
|
29
|
-
}
|
|
30
|
-
}`;
|
|
31
|
-
return this.client.sendRequest({ query, variables: { cartID } }, 'issueFraudChallenge');
|
|
24
|
+
const args = { cartID: ['String!', text(cartID)] };
|
|
25
|
+
return this.client.sendRequest(operation('mutation', 'issueFraudChallenge', args, data), 'issueFraudChallenge');
|
|
32
26
|
}
|
|
33
27
|
|
|
34
28
|
/**
|
|
35
29
|
* Verify a previously issued fraud challenge code.
|
|
36
30
|
*/
|
|
37
31
|
async verifyFraudChallenge({ cartID, code, data }) {
|
|
38
|
-
const
|
|
39
|
-
|
|
40
|
-
${data.trim()}
|
|
41
|
-
}
|
|
42
|
-
}`;
|
|
43
|
-
return this.client.sendRequest({ query, variables: { cartID, code } }, 'verifyFraudChallenge');
|
|
32
|
+
const args = { cartID: ['String!', text(cartID)], code: ['String!', text(code)] };
|
|
33
|
+
return this.client.sendRequest(operation('mutation', 'verifyFraudChallenge', args, data), 'verifyFraudChallenge');
|
|
44
34
|
}
|
|
45
35
|
|
|
46
36
|
/**
|
|
@@ -48,12 +38,10 @@ export class Fraud {
|
|
|
48
38
|
* entries to the shared fraud blocklist.
|
|
49
39
|
*/
|
|
50
40
|
async reportChargeback({ order_id, stripe_charge_id, data }) {
|
|
51
|
-
const
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
const variables = { orderId: order_id, stripeChargeId: stripe_charge_id };
|
|
57
|
-
return this.client.sendRequest({ query, variables }, 'reportChargeback');
|
|
41
|
+
const args = {
|
|
42
|
+
orderId: ['String!', text(order_id)],
|
|
43
|
+
stripeChargeId: ['String', text(stripe_charge_id)],
|
|
44
|
+
};
|
|
45
|
+
return this.client.sendRequest(operation('mutation', 'reportChargeback', args, data), 'reportChargeback');
|
|
58
46
|
}
|
|
59
47
|
}
|
package/graphql.js
CHANGED
|
@@ -12,6 +12,34 @@
|
|
|
12
12
|
* text sent, and existing storefront code keeps working.
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
|
+
/**
|
|
16
|
+
* An SDK error: a real Error (so stack traces and `instanceof Error` still
|
|
17
|
+
* work) carrying `code` and any extra fields (`details`, `status`). The
|
|
18
|
+
* message is made enumerable so logging or JSON-encoding the error shows it.
|
|
19
|
+
*/
|
|
20
|
+
export function sdkError(message, code, extra = {}) {
|
|
21
|
+
const error = new Error(message);
|
|
22
|
+
Object.defineProperty(error, 'message', { value: message, enumerable: true, writable: true, configurable: true });
|
|
23
|
+
error.code = code ?? null;
|
|
24
|
+
Object.assign(error, extra);
|
|
25
|
+
return error;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** What a method that needs a field selection resolves to without one. */
|
|
29
|
+
export function missingData() {
|
|
30
|
+
return { error: sdkError('data is required: the fields to return', 'MISSING_DATA'), response: null };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** What a method resolves to when an argument can't be used. */
|
|
34
|
+
export function invalidInput(message) {
|
|
35
|
+
return { error: sdkError(message, 'INVALID_INPUT'), response: null };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** True when `data` is a usable field selection: a non-empty string. */
|
|
39
|
+
export function hasSelection(selection) {
|
|
40
|
+
return typeof selection === 'string' && selection.trim() !== '';
|
|
41
|
+
}
|
|
42
|
+
|
|
15
43
|
/** Text for a String argument. null and undefined pass through. */
|
|
16
44
|
export function text(value) {
|
|
17
45
|
return value == null ? value : String(value);
|
|
@@ -54,15 +82,26 @@ export function textInput(fields) {
|
|
|
54
82
|
* queries did, so the server's own default for it applies. `selection` is the
|
|
55
83
|
* caller's field selection (the `data` string), for fields that return an
|
|
56
84
|
* object.
|
|
85
|
+
*
|
|
86
|
+
* Passing a fourth argument at all means the field returns an object and
|
|
87
|
+
* needs a selection: if it's missing or empty, the result carries the
|
|
88
|
+
* MISSING_DATA error instead of a query, and `sendRequest` resolves to that
|
|
89
|
+
* error without calling the API. Fields that return a plain value (a String,
|
|
90
|
+
* a Boolean) are called with three arguments.
|
|
57
91
|
*/
|
|
58
|
-
export function operation(kind, field, args,
|
|
92
|
+
export function operation(kind, field, args, ...rest) {
|
|
93
|
+
const needsSelection = rest.length > 0;
|
|
94
|
+
const selection = rest[0];
|
|
95
|
+
if (needsSelection && !hasSelection(selection)) {
|
|
96
|
+
return { error: missingData().error };
|
|
97
|
+
}
|
|
59
98
|
const given = Object.entries(args).filter(([, [, value]]) => value !== undefined);
|
|
60
99
|
const declarations = given.map(([name, [type]]) => `$${name}: ${type}`).join(', ');
|
|
61
100
|
const argumentList = given.map(([name]) => `${name}: $${name}`).join(', ');
|
|
62
101
|
const variables = Object.fromEntries(given.map(([name, [, value]]) => [name, value]));
|
|
63
102
|
|
|
64
103
|
const query = `${kind}${given.length ? ` (${declarations})` : ''} {
|
|
65
|
-
${field}${given.length ? `(${argumentList})` : ''}${
|
|
104
|
+
${field}${given.length ? `(${argumentList})` : ''}${needsSelection ? ` { ${selection.trim()} }` : ''}
|
|
66
105
|
}`;
|
|
67
106
|
return { query, variables };
|
|
68
107
|
}
|