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