react-shopwave-connect 0.2.0 → 0.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/README.md +215 -24
- package/dist/core/index.cjs +903 -88
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/index.d.cts +604 -23
- package/dist/core/index.d.ts +604 -23
- package/dist/core/index.js +845 -89
- package/dist/core/index.js.map +1 -1
- package/dist/hooks/index.cjs +735 -109
- package/dist/hooks/index.cjs.map +1 -1
- package/dist/hooks/index.d.cts +263 -12
- package/dist/hooks/index.d.ts +263 -12
- package/dist/hooks/index.js +732 -111
- package/dist/hooks/index.js.map +1 -1
- package/dist/index.cjs +1087 -107
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +670 -24
- package/dist/index.d.ts +670 -24
- package/dist/index.js +1025 -109
- package/dist/index.js.map +1 -1
- package/dist/next/index.cjs +560 -2
- package/dist/next/index.cjs.map +1 -1
- package/dist/next/index.d.cts +249 -1
- package/dist/next/index.d.ts +249 -1
- package/dist/next/index.js +556 -3
- package/dist/next/index.js.map +1 -1
- package/dist/server/index.cjs +531 -1
- package/dist/server/index.cjs.map +1 -1
- package/dist/server/index.d.cts +258 -1
- package/dist/server/index.d.ts +258 -1
- package/dist/server/index.js +521 -2
- package/dist/server/index.js.map +1 -1
- package/package.json +1 -1
package/dist/next/index.js
CHANGED
|
@@ -90,7 +90,8 @@ function authorizationHeader(token) {
|
|
|
90
90
|
*/
|
|
91
91
|
function isExpiredTokenResponse(status, body) {
|
|
92
92
|
if (status === 401) return true;
|
|
93
|
-
const
|
|
93
|
+
const message = body?.api?.message;
|
|
94
|
+
const errors = message?.errors ?? message?.error;
|
|
94
95
|
if (!errors || typeof errors !== "object") return false;
|
|
95
96
|
return Object.entries(errors).some(([key, value]) => key === String(SHOPWAVE_TOKEN_EXPIRED_ERROR_ID) || Number(value?.id) === SHOPWAVE_TOKEN_EXPIRED_ERROR_ID);
|
|
96
97
|
}
|
|
@@ -247,6 +248,524 @@ function safeEqual(a, b) {
|
|
|
247
248
|
return diff === 0;
|
|
248
249
|
}
|
|
249
250
|
|
|
251
|
+
//#endregion
|
|
252
|
+
//#region src/core/entities.ts
|
|
253
|
+
/**
|
|
254
|
+
* Addressing per entity, following the Shopwave API reference
|
|
255
|
+
* (https://developer.merchantstack.com/api-reference.html) and checked against
|
|
256
|
+
* the live API where noted:
|
|
257
|
+
* - category/product/store: GET filtered by `<x>Ids`, POST upsert, DELETE with `<x>Id` → 205.
|
|
258
|
+
* - promotion: no DELETE; "deleting" a promotion ends it by setting `endDate` to now.
|
|
259
|
+
* - employee: POST updates `roleId`, `joinedDate`, `exitDate` (names can't be
|
|
260
|
+
* changed); no DELETE (live API: "Cannot DELETE /employee") → retired via `exitDate`.
|
|
261
|
+
* - consumer: read-only (`GET` with `ids`, comma-separated); live POST → 404.
|
|
262
|
+
*/
|
|
263
|
+
const SHOPWAVE_ENTITIES = Object.freeze({
|
|
264
|
+
product: {
|
|
265
|
+
route: "products",
|
|
266
|
+
collection: "products",
|
|
267
|
+
upstream: "product",
|
|
268
|
+
idsHeader: "productIds",
|
|
269
|
+
idHeader: "productId",
|
|
270
|
+
writable: true,
|
|
271
|
+
deleteMode: "delete"
|
|
272
|
+
},
|
|
273
|
+
category: {
|
|
274
|
+
route: "categories",
|
|
275
|
+
collection: "categories",
|
|
276
|
+
upstream: "category",
|
|
277
|
+
idsHeader: "categoryIds",
|
|
278
|
+
idHeader: "categoryId",
|
|
279
|
+
writable: true,
|
|
280
|
+
deleteMode: "delete"
|
|
281
|
+
},
|
|
282
|
+
store: {
|
|
283
|
+
route: "stores",
|
|
284
|
+
collection: "stores",
|
|
285
|
+
upstream: "store",
|
|
286
|
+
idsHeader: "storeIds",
|
|
287
|
+
idHeader: "storeId",
|
|
288
|
+
writable: true,
|
|
289
|
+
deleteMode: "delete"
|
|
290
|
+
},
|
|
291
|
+
promotion: {
|
|
292
|
+
route: "promotions",
|
|
293
|
+
collection: "promotions",
|
|
294
|
+
upstream: "promotion",
|
|
295
|
+
idsHeader: "promotionIds",
|
|
296
|
+
idHeader: "promotionId",
|
|
297
|
+
writable: true,
|
|
298
|
+
deleteMode: "retire",
|
|
299
|
+
retireField: "endDate"
|
|
300
|
+
},
|
|
301
|
+
employee: {
|
|
302
|
+
route: "employees",
|
|
303
|
+
collection: "employees",
|
|
304
|
+
upstream: "employee",
|
|
305
|
+
idsHeader: "employeeIds",
|
|
306
|
+
idHeader: "employeeId",
|
|
307
|
+
writable: true,
|
|
308
|
+
deleteMode: "retire",
|
|
309
|
+
retireField: "exitDate"
|
|
310
|
+
},
|
|
311
|
+
consumer: {
|
|
312
|
+
route: "consumer",
|
|
313
|
+
collection: "consumers",
|
|
314
|
+
upstream: "consumer",
|
|
315
|
+
idsHeader: "ids",
|
|
316
|
+
idHeader: "consumerId",
|
|
317
|
+
writable: false,
|
|
318
|
+
deleteMode: "none"
|
|
319
|
+
}
|
|
320
|
+
});
|
|
321
|
+
|
|
322
|
+
//#endregion
|
|
323
|
+
//#region src/core/resources.ts
|
|
324
|
+
/**
|
|
325
|
+
* - merchant: `GET /merchant`; `POST /merchant` with `{ merchant: { id, … } }`
|
|
326
|
+
* updates it (without an `id` the API would create a second merchant, so the
|
|
327
|
+
* route requires one).
|
|
328
|
+
* - user: `GET /user` (read-only here; the API's `POST /user` invites users and
|
|
329
|
+
* needs the admin scope).
|
|
330
|
+
*/
|
|
331
|
+
const SHOPWAVE_RESOURCES = Object.freeze({
|
|
332
|
+
merchant: {
|
|
333
|
+
route: "merchant",
|
|
334
|
+
key: "merchant",
|
|
335
|
+
upstream: "merchant",
|
|
336
|
+
writable: true
|
|
337
|
+
},
|
|
338
|
+
user: {
|
|
339
|
+
route: "user",
|
|
340
|
+
key: "user",
|
|
341
|
+
upstream: "user",
|
|
342
|
+
writable: false
|
|
343
|
+
}
|
|
344
|
+
});
|
|
345
|
+
/** `UploadKind` → the API's `contentType` value. */
|
|
346
|
+
const UPLOAD_KINDS = Object.freeze({
|
|
347
|
+
merchant: "merchant",
|
|
348
|
+
merchantFeature: "merchantFeature",
|
|
349
|
+
product: "product",
|
|
350
|
+
user: "user",
|
|
351
|
+
applicationLogo: "applicaionLogo",
|
|
352
|
+
applicationImages: "applicaionImages"
|
|
353
|
+
});
|
|
354
|
+
/** How uploads are addressed (app route and Shopwave uploader). */
|
|
355
|
+
const SHOPWAVE_UPLOAD = Object.freeze({
|
|
356
|
+
route: "upload",
|
|
357
|
+
upstream: "uploader",
|
|
358
|
+
kindHeader: "contentType",
|
|
359
|
+
fileField: "file",
|
|
360
|
+
kindField: "kind"
|
|
361
|
+
});
|
|
362
|
+
function isUploadKind(value) {
|
|
363
|
+
return typeof value === "string" && Object.prototype.hasOwnProperty.call(UPLOAD_KINDS, value);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
//#endregion
|
|
367
|
+
//#region src/server/api.ts
|
|
368
|
+
/**
|
|
369
|
+
* The OAuth token a caller sent with the request, without its scheme, or `null`.
|
|
370
|
+
*
|
|
371
|
+
* Reads, in order: `Authorization: OAuth|Bearer <token>` (what the SDK sends
|
|
372
|
+
* from 0.3), the `token` header (SDK ≤ 0.2 writes), and `extras.token`
|
|
373
|
+
* (SDK ≤ 0.2 reads).
|
|
374
|
+
*/
|
|
375
|
+
function readRequestToken(request) {
|
|
376
|
+
const authz = request.headers.get("authorization");
|
|
377
|
+
if (authz) {
|
|
378
|
+
const match = /^(?:oauth|bearer)\s+(\S+)\s*$/i.exec(authz);
|
|
379
|
+
if (match) return match[1];
|
|
380
|
+
}
|
|
381
|
+
const legacyHeader = request.headers.get("token");
|
|
382
|
+
if (legacyHeader && legacyHeader.trim()) return legacyHeader.trim();
|
|
383
|
+
const extras = request.headers.get("extras");
|
|
384
|
+
if (extras) try {
|
|
385
|
+
const token = JSON.parse(extras)?.token;
|
|
386
|
+
if (typeof token === "string" && token.trim()) return token.trim();
|
|
387
|
+
} catch {}
|
|
388
|
+
return null;
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* `extras` keys that are never forwarded upstream (case-insensitive).
|
|
392
|
+
* `Content-Type` is allowed (SDK clients have always sent `application/json`
|
|
393
|
+
* on reads) but is replaced by the form content type on writes.
|
|
394
|
+
*/
|
|
395
|
+
const BLOCKED_EXTRAS = new Set([
|
|
396
|
+
"authorization",
|
|
397
|
+
"token",
|
|
398
|
+
"cookie",
|
|
399
|
+
"host",
|
|
400
|
+
"x-accept-version",
|
|
401
|
+
"content-length",
|
|
402
|
+
"connection",
|
|
403
|
+
"transfer-encoding",
|
|
404
|
+
"te",
|
|
405
|
+
"upgrade",
|
|
406
|
+
"expect",
|
|
407
|
+
"keep-alive",
|
|
408
|
+
"proxy-authorization",
|
|
409
|
+
"forwarded"
|
|
410
|
+
]);
|
|
411
|
+
const HEADER_NAME = /^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/;
|
|
412
|
+
function headerValue(value) {
|
|
413
|
+
if (value == null) return null;
|
|
414
|
+
let text;
|
|
415
|
+
if (Array.isArray(value)) text = value.map((v) => v != null && typeof v === "object" ? JSON.stringify(v) : String(v)).join(",");
|
|
416
|
+
else if (typeof value === "object") text = JSON.stringify(value);
|
|
417
|
+
else text = String(value);
|
|
418
|
+
return /[\r\n\0]/.test(text) ? null : text;
|
|
419
|
+
}
|
|
420
|
+
/**
|
|
421
|
+
* Parses the `extras` request header into upstream headers.
|
|
422
|
+
* Returns `null` when the header isn't a JSON object.
|
|
423
|
+
*/
|
|
424
|
+
function parseExtras(raw, blocked = BLOCKED_EXTRAS) {
|
|
425
|
+
if (!raw) return {};
|
|
426
|
+
let parsed;
|
|
427
|
+
try {
|
|
428
|
+
parsed = JSON.parse(raw);
|
|
429
|
+
} catch {
|
|
430
|
+
return null;
|
|
431
|
+
}
|
|
432
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
|
433
|
+
const headers = {};
|
|
434
|
+
for (const [key, value] of Object.entries(parsed)) {
|
|
435
|
+
const lower = key.toLowerCase();
|
|
436
|
+
if (!HEADER_NAME.test(key) || blocked.has(lower) || lower.startsWith("x-forwarded-") || lower.startsWith("proxy-")) continue;
|
|
437
|
+
const text = headerValue(value);
|
|
438
|
+
if (text !== null) headers[key] = text;
|
|
439
|
+
}
|
|
440
|
+
return headers;
|
|
441
|
+
}
|
|
442
|
+
var RequestBodyError = class extends Error {};
|
|
443
|
+
function isPlainObject(value) {
|
|
444
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
445
|
+
}
|
|
446
|
+
/**
|
|
447
|
+
* Normalises a write request body into the Shopwave envelope
|
|
448
|
+
* `{ <collection>: { <ref>: entity, … } }`.
|
|
449
|
+
*
|
|
450
|
+
* Accepts:
|
|
451
|
+
* - the SDK ≥ 0.3 shape `{ <collection>: { "0": {...}, "1": {...} } }` (refs kept),
|
|
452
|
+
* - the older AdminUI shapes `{ <collection>: { new: {...} } }` / `{ updated: {...} }`,
|
|
453
|
+
* - a bare entity object `{ title: … }`.
|
|
454
|
+
*
|
|
455
|
+
* With `forcedId` (item routes) exactly one entity is allowed and its `id` is
|
|
456
|
+
* set from the URL.
|
|
457
|
+
*/
|
|
458
|
+
function normalizeWriteBody(def, body, forcedId) {
|
|
459
|
+
if (!isPlainObject(body)) throw new RequestBodyError("Request body must be a JSON object");
|
|
460
|
+
let refs;
|
|
461
|
+
const wrapped = body[def.collection];
|
|
462
|
+
if (wrapped !== void 0) {
|
|
463
|
+
if (!isPlainObject(wrapped)) throw new RequestBodyError(`"${def.collection}" must be an object keyed by ref`);
|
|
464
|
+
const keys = Object.keys(wrapped);
|
|
465
|
+
const entries = keys.length === 1 && (keys[0] === "new" || keys[0] === "updated") ? [["0", wrapped[keys[0]]]] : Object.entries(wrapped);
|
|
466
|
+
refs = {};
|
|
467
|
+
for (const [ref, entity] of entries) {
|
|
468
|
+
if (!isPlainObject(entity)) throw new RequestBodyError(`"${def.collection}.${ref}" must be an object`);
|
|
469
|
+
refs[ref] = { ...entity };
|
|
470
|
+
}
|
|
471
|
+
} else refs = { "0": { ...body } };
|
|
472
|
+
const count = Object.keys(refs).length;
|
|
473
|
+
if (count === 0) throw new RequestBodyError(`No ${def.collection} to save`);
|
|
474
|
+
if (forcedId !== void 0) {
|
|
475
|
+
if (count !== 1) throw new RequestBodyError("Only one entity can be saved at an id route");
|
|
476
|
+
const only = refs[Object.keys(refs)[0]];
|
|
477
|
+
only.id = /^\d+$/.test(forcedId) ? Number(forcedId) : forcedId;
|
|
478
|
+
}
|
|
479
|
+
return { [def.collection]: refs };
|
|
480
|
+
}
|
|
481
|
+
const NO_STORE = { "Cache-Control": "no-store" };
|
|
482
|
+
function jsonError(status, error, message) {
|
|
483
|
+
return new Response(JSON.stringify({
|
|
484
|
+
error,
|
|
485
|
+
message
|
|
486
|
+
}), {
|
|
487
|
+
status,
|
|
488
|
+
headers: {
|
|
489
|
+
"Content-Type": "application/json",
|
|
490
|
+
...NO_STORE
|
|
491
|
+
}
|
|
492
|
+
});
|
|
493
|
+
}
|
|
494
|
+
/** `YYYY-MM-DD HH:mm:ss` in UTC, the datetime format Shopwave writes use (e.g. promotions). */
|
|
495
|
+
function shopwaveDateTime(date = /* @__PURE__ */ new Date()) {
|
|
496
|
+
return date.toISOString().slice(0, 19).replace("T", " ");
|
|
497
|
+
}
|
|
498
|
+
const NULL_BODY_STATUS = new Set([
|
|
499
|
+
101,
|
|
500
|
+
103,
|
|
501
|
+
204,
|
|
502
|
+
205,
|
|
503
|
+
304
|
|
504
|
+
]);
|
|
505
|
+
const ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
|
|
506
|
+
async function readUpstream(response) {
|
|
507
|
+
const text = await response.text();
|
|
508
|
+
if (!text) return {
|
|
509
|
+
text,
|
|
510
|
+
json: null
|
|
511
|
+
};
|
|
512
|
+
try {
|
|
513
|
+
return {
|
|
514
|
+
text,
|
|
515
|
+
json: JSON.parse(text)
|
|
516
|
+
};
|
|
517
|
+
} catch {
|
|
518
|
+
return {
|
|
519
|
+
text,
|
|
520
|
+
json: null
|
|
521
|
+
};
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
async function routeParam(context, name) {
|
|
525
|
+
const value = (await context?.params)?.[name];
|
|
526
|
+
const id = Array.isArray(value) ? value[0] : value;
|
|
527
|
+
return typeof id === "string" && ID_PATTERN.test(id) ? id : null;
|
|
528
|
+
}
|
|
529
|
+
function createShopwaveApiHandlers(config) {
|
|
530
|
+
const allowRequestToken = config.allowRequestToken ?? true;
|
|
531
|
+
const apiVersion = config.apiVersion ?? "2.0";
|
|
532
|
+
const blocked = new Set([...BLOCKED_EXTRAS, ...(config.blockedExtras ?? []).map((k) => k.toLowerCase())]);
|
|
533
|
+
const onError = config.onError ?? ((error, ctx) => console.error(`[react-shopwave-connect] Shopwave API ${ctx.method} /${ctx.path} failed:`, error?.message ?? error));
|
|
534
|
+
function apiBase() {
|
|
535
|
+
const url = config.apiUrl;
|
|
536
|
+
if (!url) throw new Error("Shopwave API: apiUrl is not set (e.g. SHOPWAVE_API_SERVER_URL).");
|
|
537
|
+
return url.replace(/\/+$/, "");
|
|
538
|
+
}
|
|
539
|
+
function entity(kind) {
|
|
540
|
+
const base = SHOPWAVE_ENTITIES[kind];
|
|
541
|
+
if (!base) throw new Error(`Unknown Shopwave entity "${kind}"`);
|
|
542
|
+
return {
|
|
543
|
+
...base,
|
|
544
|
+
...config.entities?.[kind] ?? {}
|
|
545
|
+
};
|
|
546
|
+
}
|
|
547
|
+
async function forward(request, init) {
|
|
548
|
+
const method = (init.method ?? "GET").toUpperCase();
|
|
549
|
+
const path = init.path.replace(/^\/+/, "");
|
|
550
|
+
const extras = init.forwardExtras === false ? {} : parseExtras(request.headers.get("extras"), blocked);
|
|
551
|
+
if (!extras) return jsonError(400, "invalid_extras", "The extras header must be a JSON object");
|
|
552
|
+
const requestToken = allowRequestToken ? readRequestToken(request) : null;
|
|
553
|
+
let authorization;
|
|
554
|
+
try {
|
|
555
|
+
authorization = requestToken ? `OAuth ${requestToken}` : await config.getAuthorization?.() ?? null;
|
|
556
|
+
} catch (error) {
|
|
557
|
+
onError(error, {
|
|
558
|
+
method,
|
|
559
|
+
path: "oauth/token"
|
|
560
|
+
});
|
|
561
|
+
return jsonError(502, "auth_unavailable", "Could not refresh the Shopwave session");
|
|
562
|
+
}
|
|
563
|
+
if (!authorization) return jsonError(401, "unauthorized", "Not logged in");
|
|
564
|
+
const body = init.postBody !== void 0 ? new URLSearchParams({ postBody: JSON.stringify(init.postBody) }) : init.formData;
|
|
565
|
+
const call = (authz) => {
|
|
566
|
+
const headers = new Headers(extras);
|
|
567
|
+
for (const [k, v] of Object.entries(init.headers ?? {})) headers.set(k, v);
|
|
568
|
+
headers.set("Authorization", authz);
|
|
569
|
+
headers.set("x-accept-version", apiVersion);
|
|
570
|
+
if (body instanceof URLSearchParams) headers.set("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
|
|
571
|
+
else if (body) headers.delete("Content-Type");
|
|
572
|
+
return (config.fetch ?? fetch)(`${apiBase()}/${path}`, {
|
|
573
|
+
method,
|
|
574
|
+
headers,
|
|
575
|
+
body,
|
|
576
|
+
cache: "no-store"
|
|
577
|
+
});
|
|
578
|
+
};
|
|
579
|
+
try {
|
|
580
|
+
let response = await call(authorization);
|
|
581
|
+
let upstream = await readUpstream(response);
|
|
582
|
+
if (!requestToken && config.getAuthorization && isExpiredTokenResponse(response.status, upstream.json)) {
|
|
583
|
+
const fresh = await config.getAuthorization({ forceRefresh: true });
|
|
584
|
+
if (!fresh) return jsonError(401, "unauthorized", "The Shopwave session has expired");
|
|
585
|
+
response = await call(fresh);
|
|
586
|
+
upstream = await readUpstream(response);
|
|
587
|
+
}
|
|
588
|
+
if (NULL_BODY_STATUS.has(response.status) || !upstream.text) return new Response(null, {
|
|
589
|
+
status: response.status,
|
|
590
|
+
headers: NO_STORE
|
|
591
|
+
});
|
|
592
|
+
return new Response(upstream.text, {
|
|
593
|
+
status: response.status,
|
|
594
|
+
headers: {
|
|
595
|
+
"Content-Type": upstream.json !== null ? "application/json" : response.headers.get("content-type") ?? "text/plain",
|
|
596
|
+
...NO_STORE
|
|
597
|
+
}
|
|
598
|
+
});
|
|
599
|
+
} catch (error) {
|
|
600
|
+
onError(error, {
|
|
601
|
+
method,
|
|
602
|
+
path
|
|
603
|
+
});
|
|
604
|
+
return jsonError(502, "upstream_unavailable", "The Shopwave API could not be reached");
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
async function readJsonBody(request) {
|
|
608
|
+
const text = await request.text();
|
|
609
|
+
if (!text) throw new RequestBodyError("Request body is empty");
|
|
610
|
+
try {
|
|
611
|
+
return JSON.parse(text);
|
|
612
|
+
} catch {
|
|
613
|
+
throw new RequestBodyError("Request body is not valid JSON");
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
function notSupported(def, what) {
|
|
617
|
+
return jsonError(405, "method_not_allowed", `The Shopwave API doesn't support ${what} for ${def.collection}`);
|
|
618
|
+
}
|
|
619
|
+
async function write(request, def, forcedId) {
|
|
620
|
+
if (!def.writable) return notSupported(def, "writes");
|
|
621
|
+
let postBody;
|
|
622
|
+
try {
|
|
623
|
+
postBody = normalizeWriteBody(def, await readJsonBody(request), forcedId);
|
|
624
|
+
} catch (error) {
|
|
625
|
+
if (error instanceof RequestBodyError) return jsonError(400, "invalid_body", error.message);
|
|
626
|
+
throw error;
|
|
627
|
+
}
|
|
628
|
+
return forward(request, {
|
|
629
|
+
method: "POST",
|
|
630
|
+
path: def.upstream,
|
|
631
|
+
postBody
|
|
632
|
+
});
|
|
633
|
+
}
|
|
634
|
+
function resourceDef(kind) {
|
|
635
|
+
const def = SHOPWAVE_RESOURCES[kind];
|
|
636
|
+
if (!def) throw new Error(`Unknown Shopwave resource "${kind}"`);
|
|
637
|
+
return def;
|
|
638
|
+
}
|
|
639
|
+
async function writeResource(request, def) {
|
|
640
|
+
if (!def.writable) return jsonError(405, "method_not_allowed", `The Shopwave API doesn't support writes for ${def.key}`);
|
|
641
|
+
let record;
|
|
642
|
+
try {
|
|
643
|
+
const body = await readJsonBody(request);
|
|
644
|
+
if (!isPlainObject(body)) throw new RequestBodyError("Request body must be a JSON object");
|
|
645
|
+
const inner = body[def.key];
|
|
646
|
+
if (inner !== void 0 && !isPlainObject(inner)) throw new RequestBodyError(`"${def.key}" must be an object`);
|
|
647
|
+
record = { ...inner ?? body };
|
|
648
|
+
const id = record.id;
|
|
649
|
+
if (id == null || id === "" || !ID_PATTERN.test(String(id))) throw new RequestBodyError(`Missing or invalid ${def.key} id`);
|
|
650
|
+
record.id = /^\d+$/.test(String(id)) ? Number(id) : id;
|
|
651
|
+
} catch (error) {
|
|
652
|
+
if (error instanceof RequestBodyError) return jsonError(400, "invalid_body", error.message);
|
|
653
|
+
throw error;
|
|
654
|
+
}
|
|
655
|
+
return forward(request, {
|
|
656
|
+
method: "POST",
|
|
657
|
+
path: def.upstream,
|
|
658
|
+
postBody: { [def.key]: record }
|
|
659
|
+
});
|
|
660
|
+
}
|
|
661
|
+
function acceptsType(type, accept) {
|
|
662
|
+
const t = type.toLowerCase().split(";")[0].trim();
|
|
663
|
+
return accept.some((a) => {
|
|
664
|
+
const rule = a.toLowerCase();
|
|
665
|
+
return rule.endsWith("/") ? t.startsWith(rule) : t === rule;
|
|
666
|
+
});
|
|
667
|
+
}
|
|
668
|
+
async function uploadFile(request, options) {
|
|
669
|
+
const maxBytes = options.maxBytes ?? 10 * 1024 * 1024;
|
|
670
|
+
const accept = options.accept ?? ["image/"];
|
|
671
|
+
if (Number(request.headers.get("content-length") ?? 0) > maxBytes + 64 * 1024) return jsonError(413, "too_large", `The file is larger than ${maxBytes} bytes`);
|
|
672
|
+
let form;
|
|
673
|
+
try {
|
|
674
|
+
form = await request.formData();
|
|
675
|
+
} catch {
|
|
676
|
+
return jsonError(400, "invalid_body", "Expected a multipart/form-data body");
|
|
677
|
+
}
|
|
678
|
+
const file = form.get(SHOPWAVE_UPLOAD.fileField);
|
|
679
|
+
if (!file || typeof file === "string" || file.size === 0) return jsonError(400, "invalid_body", `Missing "${SHOPWAVE_UPLOAD.fileField}"`);
|
|
680
|
+
const kind = form.get(SHOPWAVE_UPLOAD.kindField);
|
|
681
|
+
if (!isUploadKind(kind)) return jsonError(400, "invalid_body", `"${SHOPWAVE_UPLOAD.kindField}" must be one of ${Object.keys(UPLOAD_KINDS).join(", ")}`);
|
|
682
|
+
if (file.size > maxBytes) return jsonError(413, "too_large", `The file is larger than ${maxBytes} bytes`);
|
|
683
|
+
if (!acceptsType(file.type || "", accept)) return jsonError(415, "unsupported_type", `Files of type "${file.type || "unknown"}" aren't accepted`);
|
|
684
|
+
const upstreamForm = new FormData();
|
|
685
|
+
upstreamForm.append(SHOPWAVE_UPLOAD.fileField, file, file.name || "upload");
|
|
686
|
+
return forward(request, {
|
|
687
|
+
method: "PUT",
|
|
688
|
+
path: SHOPWAVE_UPLOAD.upstream,
|
|
689
|
+
headers: { [SHOPWAVE_UPLOAD.kindHeader]: UPLOAD_KINDS[kind] },
|
|
690
|
+
formData: upstreamForm,
|
|
691
|
+
forwardExtras: false
|
|
692
|
+
});
|
|
693
|
+
}
|
|
694
|
+
function badId() {
|
|
695
|
+
return jsonError(400, "invalid_id", "Missing or invalid id");
|
|
696
|
+
}
|
|
697
|
+
return {
|
|
698
|
+
forward,
|
|
699
|
+
entity,
|
|
700
|
+
collection(kind) {
|
|
701
|
+
const def = entity(kind);
|
|
702
|
+
const save = (request) => write(request, def);
|
|
703
|
+
return {
|
|
704
|
+
GET: (request) => forward(request, { path: def.upstream }),
|
|
705
|
+
POST: save,
|
|
706
|
+
PUT: save
|
|
707
|
+
};
|
|
708
|
+
},
|
|
709
|
+
item(kind, options = {}) {
|
|
710
|
+
const def = entity(kind);
|
|
711
|
+
const param = options.param ?? "id";
|
|
712
|
+
return {
|
|
713
|
+
async GET(request, context) {
|
|
714
|
+
const id = await routeParam(context, param);
|
|
715
|
+
if (!id) return badId();
|
|
716
|
+
return forward(request, {
|
|
717
|
+
path: def.upstream,
|
|
718
|
+
headers: { [def.idsHeader]: id }
|
|
719
|
+
});
|
|
720
|
+
},
|
|
721
|
+
async PUT(request, context) {
|
|
722
|
+
const id = await routeParam(context, param);
|
|
723
|
+
if (!id) return badId();
|
|
724
|
+
return write(request, def, id);
|
|
725
|
+
},
|
|
726
|
+
async DELETE(request, context) {
|
|
727
|
+
const id = await routeParam(context, param);
|
|
728
|
+
if (!id) return badId();
|
|
729
|
+
if (def.deleteMode === "none") return notSupported(def, "deletes");
|
|
730
|
+
if (def.deleteMode === "retire") {
|
|
731
|
+
const field = def.retireField ?? "exitDate";
|
|
732
|
+
return forward(request, {
|
|
733
|
+
method: "POST",
|
|
734
|
+
path: def.upstream,
|
|
735
|
+
postBody: { [def.collection]: { 0: {
|
|
736
|
+
id: /^\d+$/.test(id) ? Number(id) : id,
|
|
737
|
+
[field]: shopwaveDateTime()
|
|
738
|
+
} } },
|
|
739
|
+
forwardExtras: false
|
|
740
|
+
});
|
|
741
|
+
}
|
|
742
|
+
return forward(request, {
|
|
743
|
+
method: "DELETE",
|
|
744
|
+
path: def.upstream,
|
|
745
|
+
headers: { [def.idHeader]: id },
|
|
746
|
+
forwardExtras: false
|
|
747
|
+
});
|
|
748
|
+
}
|
|
749
|
+
};
|
|
750
|
+
},
|
|
751
|
+
passthrough(path) {
|
|
752
|
+
return { GET: (request) => forward(request, { path }) };
|
|
753
|
+
},
|
|
754
|
+
resource(kind) {
|
|
755
|
+
const def = resourceDef(kind);
|
|
756
|
+
const save = (request) => writeResource(request, def);
|
|
757
|
+
return {
|
|
758
|
+
GET: (request) => forward(request, { path: def.upstream }),
|
|
759
|
+
PUT: save,
|
|
760
|
+
POST: save
|
|
761
|
+
};
|
|
762
|
+
},
|
|
763
|
+
upload(options = {}) {
|
|
764
|
+
return { POST: (request) => uploadFile(request, options) };
|
|
765
|
+
}
|
|
766
|
+
};
|
|
767
|
+
}
|
|
768
|
+
|
|
250
769
|
//#endregion
|
|
251
770
|
//#region src/next/index.ts
|
|
252
771
|
function normalizePath(p) {
|
|
@@ -525,8 +1044,10 @@ function createShopwaveAuth(config) {
|
|
|
525
1044
|
sessionPath,
|
|
526
1045
|
...options.publicPaths ?? []
|
|
527
1046
|
])) return;
|
|
1047
|
+
const isApi = pathMatches(pathname, options.apiPaths ?? ["/api"]);
|
|
1048
|
+
if (isApi && options.allowRequestToken && readRequestToken(request)) return void 0;
|
|
528
1049
|
if (await isAuthenticated(request)) return void 0;
|
|
529
|
-
if (
|
|
1050
|
+
if (isApi) return NextResponse.json({ error: "unauthorized" }, {
|
|
530
1051
|
status: 401,
|
|
531
1052
|
headers: noStore
|
|
532
1053
|
});
|
|
@@ -550,7 +1071,39 @@ function createShopwaveAuth(config) {
|
|
|
550
1071
|
}
|
|
551
1072
|
};
|
|
552
1073
|
}
|
|
1074
|
+
/**
|
|
1075
|
+
* Ready-made Next.js route handlers for the SDK's `/api/*` contract, using the
|
|
1076
|
+
* session from `createShopwaveAuth`. Create once (e.g. `lib/shopwave.ts`):
|
|
1077
|
+
*
|
|
1078
|
+
* ```ts
|
|
1079
|
+
* export const shopwave = createShopwaveApi({ auth, apiUrl: process.env.SHOPWAVE_API_SERVER_URL! });
|
|
1080
|
+
* ```
|
|
1081
|
+
*
|
|
1082
|
+
* then each route file is one line:
|
|
1083
|
+
*
|
|
1084
|
+
* ```ts
|
|
1085
|
+
* // app/api/products/route.ts
|
|
1086
|
+
* export const { GET, POST, PUT } = shopwave.collection("product");
|
|
1087
|
+
* // app/api/products/[id]/route.ts
|
|
1088
|
+
* export const { GET, PUT, DELETE } = shopwave.item("product");
|
|
1089
|
+
* // app/api/report/route.ts
|
|
1090
|
+
* export const { GET } = shopwave.passthrough("report");
|
|
1091
|
+
* // app/api/merchant/route.ts, app/api/user/route.ts
|
|
1092
|
+
* export const { GET, PUT } = shopwave.resource("merchant");
|
|
1093
|
+
* export const { GET } = shopwave.resource("user");
|
|
1094
|
+
* // app/api/upload/route.ts
|
|
1095
|
+
* export const { POST } = shopwave.upload();
|
|
1096
|
+
* ```
|
|
1097
|
+
*/
|
|
1098
|
+
function createShopwaveApi(config) {
|
|
1099
|
+
if (typeof window !== "undefined") throw new Error("react-shopwave-connect/next is server-only. Import it from route handlers or server code.");
|
|
1100
|
+
const { auth,...rest } = config;
|
|
1101
|
+
return createShopwaveApiHandlers({
|
|
1102
|
+
...rest,
|
|
1103
|
+
getAuthorization: (options) => auth.getAuthorizationHeader(options)
|
|
1104
|
+
});
|
|
1105
|
+
}
|
|
553
1106
|
|
|
554
1107
|
//#endregion
|
|
555
|
-
export { ShopwaveAuthError, authorizationHeader, createShopwaveAuth, isExpiredTokenResponse };
|
|
1108
|
+
export { SHOPWAVE_ENTITIES, SHOPWAVE_RESOURCES, ShopwaveAuthError, UPLOAD_KINDS, authorizationHeader, createShopwaveApi, createShopwaveAuth, isExpiredTokenResponse, readRequestToken };
|
|
556
1109
|
//# sourceMappingURL=index.js.map
|