react-shopwave-connect 0.2.0 → 0.3.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 +145 -22
- package/dist/core/index.cjs +392 -88
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/index.d.cts +214 -23
- package/dist/core/index.d.ts +214 -23
- package/dist/core/index.js +365 -89
- package/dist/core/index.js.map +1 -1
- package/dist/hooks/index.cjs +281 -111
- package/dist/hooks/index.cjs.map +1 -1
- package/dist/hooks/index.d.cts +34 -11
- package/dist/hooks/index.d.ts +34 -11
- package/dist/hooks/index.js +282 -112
- package/dist/hooks/index.js.map +1 -1
- package/dist/index.cjs +492 -107
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +227 -24
- package/dist/index.d.ts +227 -24
- package/dist/index.js +466 -109
- package/dist/index.js.map +1 -1
- package/dist/next/index.cjs +436 -2
- package/dist/next/index.cjs.map +1 -1
- package/dist/next/index.d.cts +169 -1
- package/dist/next/index.d.ts +169 -1
- package/dist/next/index.js +434 -3
- package/dist/next/index.js.map +1 -1
- package/dist/server/index.cjs +411 -1
- package/dist/server/index.cjs.map +1 -1
- package/dist/server/index.d.cts +170 -1
- package/dist/server/index.d.ts +170 -1
- package/dist/server/index.js +404 -2
- package/dist/server/index.js.map +1 -1
- package/package.json +1 -1
package/dist/next/index.cjs
CHANGED
|
@@ -116,7 +116,8 @@ function authorizationHeader(token) {
|
|
|
116
116
|
*/
|
|
117
117
|
function isExpiredTokenResponse(status, body) {
|
|
118
118
|
if (status === 401) return true;
|
|
119
|
-
const
|
|
119
|
+
const message = body?.api?.message;
|
|
120
|
+
const errors = message?.errors ?? message?.error;
|
|
120
121
|
if (!errors || typeof errors !== "object") return false;
|
|
121
122
|
return Object.entries(errors).some(([key, value]) => key === String(SHOPWAVE_TOKEN_EXPIRED_ERROR_ID) || Number(value?.id) === SHOPWAVE_TOKEN_EXPIRED_ERROR_ID);
|
|
122
123
|
}
|
|
@@ -273,6 +274,407 @@ function safeEqual(a, b) {
|
|
|
273
274
|
return diff === 0;
|
|
274
275
|
}
|
|
275
276
|
|
|
277
|
+
//#endregion
|
|
278
|
+
//#region src/core/entities.ts
|
|
279
|
+
/**
|
|
280
|
+
* Addressing per entity, following the Shopwave API reference
|
|
281
|
+
* (https://developer.merchantstack.com/api-reference.html) and checked against
|
|
282
|
+
* the live API where noted:
|
|
283
|
+
* - category/product/store: GET filtered by `<x>Ids`, POST upsert, DELETE with `<x>Id` → 205.
|
|
284
|
+
* - promotion: no DELETE; "deleting" a promotion ends it by setting `endDate` to now.
|
|
285
|
+
* - employee: POST updates `roleId`, `joinedDate`, `exitDate` (names can't be
|
|
286
|
+
* changed); no DELETE (live API: "Cannot DELETE /employee") → retired via `exitDate`.
|
|
287
|
+
* - consumer: read-only (`GET` with `ids`, comma-separated); live POST → 404.
|
|
288
|
+
*/
|
|
289
|
+
const SHOPWAVE_ENTITIES = Object.freeze({
|
|
290
|
+
product: {
|
|
291
|
+
route: "products",
|
|
292
|
+
collection: "products",
|
|
293
|
+
upstream: "product",
|
|
294
|
+
idsHeader: "productIds",
|
|
295
|
+
idHeader: "productId",
|
|
296
|
+
writable: true,
|
|
297
|
+
deleteMode: "delete"
|
|
298
|
+
},
|
|
299
|
+
category: {
|
|
300
|
+
route: "categories",
|
|
301
|
+
collection: "categories",
|
|
302
|
+
upstream: "category",
|
|
303
|
+
idsHeader: "categoryIds",
|
|
304
|
+
idHeader: "categoryId",
|
|
305
|
+
writable: true,
|
|
306
|
+
deleteMode: "delete"
|
|
307
|
+
},
|
|
308
|
+
store: {
|
|
309
|
+
route: "stores",
|
|
310
|
+
collection: "stores",
|
|
311
|
+
upstream: "store",
|
|
312
|
+
idsHeader: "storeIds",
|
|
313
|
+
idHeader: "storeId",
|
|
314
|
+
writable: true,
|
|
315
|
+
deleteMode: "delete"
|
|
316
|
+
},
|
|
317
|
+
promotion: {
|
|
318
|
+
route: "promotions",
|
|
319
|
+
collection: "promotions",
|
|
320
|
+
upstream: "promotion",
|
|
321
|
+
idsHeader: "promotionIds",
|
|
322
|
+
idHeader: "promotionId",
|
|
323
|
+
writable: true,
|
|
324
|
+
deleteMode: "retire",
|
|
325
|
+
retireField: "endDate"
|
|
326
|
+
},
|
|
327
|
+
employee: {
|
|
328
|
+
route: "employees",
|
|
329
|
+
collection: "employees",
|
|
330
|
+
upstream: "employee",
|
|
331
|
+
idsHeader: "employeeIds",
|
|
332
|
+
idHeader: "employeeId",
|
|
333
|
+
writable: true,
|
|
334
|
+
deleteMode: "retire",
|
|
335
|
+
retireField: "exitDate"
|
|
336
|
+
},
|
|
337
|
+
consumer: {
|
|
338
|
+
route: "consumer",
|
|
339
|
+
collection: "consumers",
|
|
340
|
+
upstream: "consumer",
|
|
341
|
+
idsHeader: "ids",
|
|
342
|
+
idHeader: "consumerId",
|
|
343
|
+
writable: false,
|
|
344
|
+
deleteMode: "none"
|
|
345
|
+
}
|
|
346
|
+
});
|
|
347
|
+
|
|
348
|
+
//#endregion
|
|
349
|
+
//#region src/server/api.ts
|
|
350
|
+
/**
|
|
351
|
+
* The OAuth token a caller sent with the request, without its scheme, or `null`.
|
|
352
|
+
*
|
|
353
|
+
* Reads, in order: `Authorization: OAuth|Bearer <token>` (what the SDK sends
|
|
354
|
+
* from 0.3), the `token` header (SDK ≤ 0.2 writes), and `extras.token`
|
|
355
|
+
* (SDK ≤ 0.2 reads).
|
|
356
|
+
*/
|
|
357
|
+
function readRequestToken(request) {
|
|
358
|
+
const authz = request.headers.get("authorization");
|
|
359
|
+
if (authz) {
|
|
360
|
+
const match = /^(?:oauth|bearer)\s+(\S+)\s*$/i.exec(authz);
|
|
361
|
+
if (match) return match[1];
|
|
362
|
+
}
|
|
363
|
+
const legacyHeader = request.headers.get("token");
|
|
364
|
+
if (legacyHeader && legacyHeader.trim()) return legacyHeader.trim();
|
|
365
|
+
const extras = request.headers.get("extras");
|
|
366
|
+
if (extras) try {
|
|
367
|
+
const token = JSON.parse(extras)?.token;
|
|
368
|
+
if (typeof token === "string" && token.trim()) return token.trim();
|
|
369
|
+
} catch {}
|
|
370
|
+
return null;
|
|
371
|
+
}
|
|
372
|
+
/**
|
|
373
|
+
* `extras` keys that are never forwarded upstream (case-insensitive).
|
|
374
|
+
* `Content-Type` is allowed (SDK clients have always sent `application/json`
|
|
375
|
+
* on reads) but is replaced by the form content type on writes.
|
|
376
|
+
*/
|
|
377
|
+
const BLOCKED_EXTRAS = new Set([
|
|
378
|
+
"authorization",
|
|
379
|
+
"token",
|
|
380
|
+
"cookie",
|
|
381
|
+
"host",
|
|
382
|
+
"x-accept-version",
|
|
383
|
+
"content-length",
|
|
384
|
+
"connection",
|
|
385
|
+
"transfer-encoding",
|
|
386
|
+
"te",
|
|
387
|
+
"upgrade",
|
|
388
|
+
"expect",
|
|
389
|
+
"keep-alive",
|
|
390
|
+
"proxy-authorization",
|
|
391
|
+
"forwarded"
|
|
392
|
+
]);
|
|
393
|
+
const HEADER_NAME = /^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/;
|
|
394
|
+
function headerValue(value) {
|
|
395
|
+
if (value == null) return null;
|
|
396
|
+
let text;
|
|
397
|
+
if (Array.isArray(value)) text = value.map((v) => v != null && typeof v === "object" ? JSON.stringify(v) : String(v)).join(",");
|
|
398
|
+
else if (typeof value === "object") text = JSON.stringify(value);
|
|
399
|
+
else text = String(value);
|
|
400
|
+
return /[\r\n\0]/.test(text) ? null : text;
|
|
401
|
+
}
|
|
402
|
+
/**
|
|
403
|
+
* Parses the `extras` request header into upstream headers.
|
|
404
|
+
* Returns `null` when the header isn't a JSON object.
|
|
405
|
+
*/
|
|
406
|
+
function parseExtras(raw, blocked = BLOCKED_EXTRAS) {
|
|
407
|
+
if (!raw) return {};
|
|
408
|
+
let parsed;
|
|
409
|
+
try {
|
|
410
|
+
parsed = JSON.parse(raw);
|
|
411
|
+
} catch {
|
|
412
|
+
return null;
|
|
413
|
+
}
|
|
414
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
|
415
|
+
const headers = {};
|
|
416
|
+
for (const [key, value] of Object.entries(parsed)) {
|
|
417
|
+
const lower = key.toLowerCase();
|
|
418
|
+
if (!HEADER_NAME.test(key) || blocked.has(lower) || lower.startsWith("x-forwarded-") || lower.startsWith("proxy-")) continue;
|
|
419
|
+
const text = headerValue(value);
|
|
420
|
+
if (text !== null) headers[key] = text;
|
|
421
|
+
}
|
|
422
|
+
return headers;
|
|
423
|
+
}
|
|
424
|
+
var RequestBodyError = class extends Error {};
|
|
425
|
+
function isPlainObject(value) {
|
|
426
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
427
|
+
}
|
|
428
|
+
/**
|
|
429
|
+
* Normalises a write request body into the Shopwave envelope
|
|
430
|
+
* `{ <collection>: { <ref>: entity, … } }`.
|
|
431
|
+
*
|
|
432
|
+
* Accepts:
|
|
433
|
+
* - the SDK ≥ 0.3 shape `{ <collection>: { "0": {...}, "1": {...} } }` (refs kept),
|
|
434
|
+
* - the older AdminUI shapes `{ <collection>: { new: {...} } }` / `{ updated: {...} }`,
|
|
435
|
+
* - a bare entity object `{ title: … }`.
|
|
436
|
+
*
|
|
437
|
+
* With `forcedId` (item routes) exactly one entity is allowed and its `id` is
|
|
438
|
+
* set from the URL.
|
|
439
|
+
*/
|
|
440
|
+
function normalizeWriteBody(def, body, forcedId) {
|
|
441
|
+
if (!isPlainObject(body)) throw new RequestBodyError("Request body must be a JSON object");
|
|
442
|
+
let refs;
|
|
443
|
+
const wrapped = body[def.collection];
|
|
444
|
+
if (wrapped !== void 0) {
|
|
445
|
+
if (!isPlainObject(wrapped)) throw new RequestBodyError(`"${def.collection}" must be an object keyed by ref`);
|
|
446
|
+
const keys = Object.keys(wrapped);
|
|
447
|
+
const entries = keys.length === 1 && (keys[0] === "new" || keys[0] === "updated") ? [["0", wrapped[keys[0]]]] : Object.entries(wrapped);
|
|
448
|
+
refs = {};
|
|
449
|
+
for (const [ref, entity] of entries) {
|
|
450
|
+
if (!isPlainObject(entity)) throw new RequestBodyError(`"${def.collection}.${ref}" must be an object`);
|
|
451
|
+
refs[ref] = { ...entity };
|
|
452
|
+
}
|
|
453
|
+
} else refs = { "0": { ...body } };
|
|
454
|
+
const count = Object.keys(refs).length;
|
|
455
|
+
if (count === 0) throw new RequestBodyError(`No ${def.collection} to save`);
|
|
456
|
+
if (forcedId !== void 0) {
|
|
457
|
+
if (count !== 1) throw new RequestBodyError("Only one entity can be saved at an id route");
|
|
458
|
+
const only = refs[Object.keys(refs)[0]];
|
|
459
|
+
only.id = /^\d+$/.test(forcedId) ? Number(forcedId) : forcedId;
|
|
460
|
+
}
|
|
461
|
+
return { [def.collection]: refs };
|
|
462
|
+
}
|
|
463
|
+
const NO_STORE = { "Cache-Control": "no-store" };
|
|
464
|
+
function jsonError(status, error, message) {
|
|
465
|
+
return new Response(JSON.stringify({
|
|
466
|
+
error,
|
|
467
|
+
message
|
|
468
|
+
}), {
|
|
469
|
+
status,
|
|
470
|
+
headers: {
|
|
471
|
+
"Content-Type": "application/json",
|
|
472
|
+
...NO_STORE
|
|
473
|
+
}
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
/** `YYYY-MM-DD HH:mm:ss` in UTC, the datetime format Shopwave writes use (e.g. promotions). */
|
|
477
|
+
function shopwaveDateTime(date = /* @__PURE__ */ new Date()) {
|
|
478
|
+
return date.toISOString().slice(0, 19).replace("T", " ");
|
|
479
|
+
}
|
|
480
|
+
const NULL_BODY_STATUS = new Set([
|
|
481
|
+
101,
|
|
482
|
+
103,
|
|
483
|
+
204,
|
|
484
|
+
205,
|
|
485
|
+
304
|
|
486
|
+
]);
|
|
487
|
+
const ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
|
|
488
|
+
async function readUpstream(response) {
|
|
489
|
+
const text = await response.text();
|
|
490
|
+
if (!text) return {
|
|
491
|
+
text,
|
|
492
|
+
json: null
|
|
493
|
+
};
|
|
494
|
+
try {
|
|
495
|
+
return {
|
|
496
|
+
text,
|
|
497
|
+
json: JSON.parse(text)
|
|
498
|
+
};
|
|
499
|
+
} catch {
|
|
500
|
+
return {
|
|
501
|
+
text,
|
|
502
|
+
json: null
|
|
503
|
+
};
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
async function routeParam(context, name) {
|
|
507
|
+
const value = (await context?.params)?.[name];
|
|
508
|
+
const id = Array.isArray(value) ? value[0] : value;
|
|
509
|
+
return typeof id === "string" && ID_PATTERN.test(id) ? id : null;
|
|
510
|
+
}
|
|
511
|
+
function createShopwaveApiHandlers(config) {
|
|
512
|
+
const allowRequestToken = config.allowRequestToken ?? true;
|
|
513
|
+
const apiVersion = config.apiVersion ?? "2.0";
|
|
514
|
+
const blocked = new Set([...BLOCKED_EXTRAS, ...(config.blockedExtras ?? []).map((k) => k.toLowerCase())]);
|
|
515
|
+
const onError = config.onError ?? ((error, ctx) => console.error(`[react-shopwave-connect] Shopwave API ${ctx.method} /${ctx.path} failed:`, error?.message ?? error));
|
|
516
|
+
function apiBase() {
|
|
517
|
+
const url = config.apiUrl;
|
|
518
|
+
if (!url) throw new Error("Shopwave API: apiUrl is not set (e.g. SHOPWAVE_API_SERVER_URL).");
|
|
519
|
+
return url.replace(/\/+$/, "");
|
|
520
|
+
}
|
|
521
|
+
function entity(kind) {
|
|
522
|
+
const base = SHOPWAVE_ENTITIES[kind];
|
|
523
|
+
if (!base) throw new Error(`Unknown Shopwave entity "${kind}"`);
|
|
524
|
+
return {
|
|
525
|
+
...base,
|
|
526
|
+
...config.entities?.[kind] ?? {}
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
async function forward(request, init) {
|
|
530
|
+
const method = (init.method ?? "GET").toUpperCase();
|
|
531
|
+
const path = init.path.replace(/^\/+/, "");
|
|
532
|
+
const extras = init.forwardExtras === false ? {} : parseExtras(request.headers.get("extras"), blocked);
|
|
533
|
+
if (!extras) return jsonError(400, "invalid_extras", "The extras header must be a JSON object");
|
|
534
|
+
const requestToken = allowRequestToken ? readRequestToken(request) : null;
|
|
535
|
+
let authorization;
|
|
536
|
+
try {
|
|
537
|
+
authorization = requestToken ? `OAuth ${requestToken}` : await config.getAuthorization?.() ?? null;
|
|
538
|
+
} catch (error) {
|
|
539
|
+
onError(error, {
|
|
540
|
+
method,
|
|
541
|
+
path: "oauth/token"
|
|
542
|
+
});
|
|
543
|
+
return jsonError(502, "auth_unavailable", "Could not refresh the Shopwave session");
|
|
544
|
+
}
|
|
545
|
+
if (!authorization) return jsonError(401, "unauthorized", "Not logged in");
|
|
546
|
+
const body = init.postBody === void 0 ? void 0 : new URLSearchParams({ postBody: JSON.stringify(init.postBody) });
|
|
547
|
+
const call = (authz) => {
|
|
548
|
+
const headers = new Headers(extras);
|
|
549
|
+
for (const [k, v] of Object.entries(init.headers ?? {})) headers.set(k, v);
|
|
550
|
+
headers.set("Authorization", authz);
|
|
551
|
+
headers.set("x-accept-version", apiVersion);
|
|
552
|
+
if (body) headers.set("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
|
|
553
|
+
return (config.fetch ?? fetch)(`${apiBase()}/${path}`, {
|
|
554
|
+
method,
|
|
555
|
+
headers,
|
|
556
|
+
body,
|
|
557
|
+
cache: "no-store"
|
|
558
|
+
});
|
|
559
|
+
};
|
|
560
|
+
try {
|
|
561
|
+
let response = await call(authorization);
|
|
562
|
+
let upstream = await readUpstream(response);
|
|
563
|
+
if (!requestToken && config.getAuthorization && isExpiredTokenResponse(response.status, upstream.json)) {
|
|
564
|
+
const fresh = await config.getAuthorization({ forceRefresh: true });
|
|
565
|
+
if (!fresh) return jsonError(401, "unauthorized", "The Shopwave session has expired");
|
|
566
|
+
response = await call(fresh);
|
|
567
|
+
upstream = await readUpstream(response);
|
|
568
|
+
}
|
|
569
|
+
if (NULL_BODY_STATUS.has(response.status) || !upstream.text) return new Response(null, {
|
|
570
|
+
status: response.status,
|
|
571
|
+
headers: NO_STORE
|
|
572
|
+
});
|
|
573
|
+
return new Response(upstream.text, {
|
|
574
|
+
status: response.status,
|
|
575
|
+
headers: {
|
|
576
|
+
"Content-Type": upstream.json !== null ? "application/json" : response.headers.get("content-type") ?? "text/plain",
|
|
577
|
+
...NO_STORE
|
|
578
|
+
}
|
|
579
|
+
});
|
|
580
|
+
} catch (error) {
|
|
581
|
+
onError(error, {
|
|
582
|
+
method,
|
|
583
|
+
path
|
|
584
|
+
});
|
|
585
|
+
return jsonError(502, "upstream_unavailable", "The Shopwave API could not be reached");
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
async function readJsonBody(request) {
|
|
589
|
+
const text = await request.text();
|
|
590
|
+
if (!text) throw new RequestBodyError("Request body is empty");
|
|
591
|
+
try {
|
|
592
|
+
return JSON.parse(text);
|
|
593
|
+
} catch {
|
|
594
|
+
throw new RequestBodyError("Request body is not valid JSON");
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
function notSupported(def, what) {
|
|
598
|
+
return jsonError(405, "method_not_allowed", `The Shopwave API doesn't support ${what} for ${def.collection}`);
|
|
599
|
+
}
|
|
600
|
+
async function write(request, def, forcedId) {
|
|
601
|
+
if (!def.writable) return notSupported(def, "writes");
|
|
602
|
+
let postBody;
|
|
603
|
+
try {
|
|
604
|
+
postBody = normalizeWriteBody(def, await readJsonBody(request), forcedId);
|
|
605
|
+
} catch (error) {
|
|
606
|
+
if (error instanceof RequestBodyError) return jsonError(400, "invalid_body", error.message);
|
|
607
|
+
throw error;
|
|
608
|
+
}
|
|
609
|
+
return forward(request, {
|
|
610
|
+
method: "POST",
|
|
611
|
+
path: def.upstream,
|
|
612
|
+
postBody
|
|
613
|
+
});
|
|
614
|
+
}
|
|
615
|
+
function badId() {
|
|
616
|
+
return jsonError(400, "invalid_id", "Missing or invalid id");
|
|
617
|
+
}
|
|
618
|
+
return {
|
|
619
|
+
forward,
|
|
620
|
+
entity,
|
|
621
|
+
collection(kind) {
|
|
622
|
+
const def = entity(kind);
|
|
623
|
+
const save = (request) => write(request, def);
|
|
624
|
+
return {
|
|
625
|
+
GET: (request) => forward(request, { path: def.upstream }),
|
|
626
|
+
POST: save,
|
|
627
|
+
PUT: save
|
|
628
|
+
};
|
|
629
|
+
},
|
|
630
|
+
item(kind, options = {}) {
|
|
631
|
+
const def = entity(kind);
|
|
632
|
+
const param = options.param ?? "id";
|
|
633
|
+
return {
|
|
634
|
+
async GET(request, context) {
|
|
635
|
+
const id = await routeParam(context, param);
|
|
636
|
+
if (!id) return badId();
|
|
637
|
+
return forward(request, {
|
|
638
|
+
path: def.upstream,
|
|
639
|
+
headers: { [def.idsHeader]: id }
|
|
640
|
+
});
|
|
641
|
+
},
|
|
642
|
+
async PUT(request, context) {
|
|
643
|
+
const id = await routeParam(context, param);
|
|
644
|
+
if (!id) return badId();
|
|
645
|
+
return write(request, def, id);
|
|
646
|
+
},
|
|
647
|
+
async DELETE(request, context) {
|
|
648
|
+
const id = await routeParam(context, param);
|
|
649
|
+
if (!id) return badId();
|
|
650
|
+
if (def.deleteMode === "none") return notSupported(def, "deletes");
|
|
651
|
+
if (def.deleteMode === "retire") {
|
|
652
|
+
const field = def.retireField ?? "exitDate";
|
|
653
|
+
return forward(request, {
|
|
654
|
+
method: "POST",
|
|
655
|
+
path: def.upstream,
|
|
656
|
+
postBody: { [def.collection]: { 0: {
|
|
657
|
+
id: /^\d+$/.test(id) ? Number(id) : id,
|
|
658
|
+
[field]: shopwaveDateTime()
|
|
659
|
+
} } },
|
|
660
|
+
forwardExtras: false
|
|
661
|
+
});
|
|
662
|
+
}
|
|
663
|
+
return forward(request, {
|
|
664
|
+
method: "DELETE",
|
|
665
|
+
path: def.upstream,
|
|
666
|
+
headers: { [def.idHeader]: id },
|
|
667
|
+
forwardExtras: false
|
|
668
|
+
});
|
|
669
|
+
}
|
|
670
|
+
};
|
|
671
|
+
},
|
|
672
|
+
passthrough(path) {
|
|
673
|
+
return { GET: (request) => forward(request, { path }) };
|
|
674
|
+
}
|
|
675
|
+
};
|
|
676
|
+
}
|
|
677
|
+
|
|
276
678
|
//#endregion
|
|
277
679
|
//#region src/next/index.ts
|
|
278
680
|
function normalizePath(p) {
|
|
@@ -551,8 +953,10 @@ function createShopwaveAuth(config) {
|
|
|
551
953
|
sessionPath,
|
|
552
954
|
...options.publicPaths ?? []
|
|
553
955
|
])) return;
|
|
956
|
+
const isApi = pathMatches(pathname, options.apiPaths ?? ["/api"]);
|
|
957
|
+
if (isApi && options.allowRequestToken && readRequestToken(request)) return void 0;
|
|
554
958
|
if (await isAuthenticated(request)) return void 0;
|
|
555
|
-
if (
|
|
959
|
+
if (isApi) return next_server.NextResponse.json({ error: "unauthorized" }, {
|
|
556
960
|
status: 401,
|
|
557
961
|
headers: noStore
|
|
558
962
|
});
|
|
@@ -576,10 +980,40 @@ function createShopwaveAuth(config) {
|
|
|
576
980
|
}
|
|
577
981
|
};
|
|
578
982
|
}
|
|
983
|
+
/**
|
|
984
|
+
* Ready-made Next.js route handlers for the SDK's `/api/*` contract, using the
|
|
985
|
+
* session from `createShopwaveAuth`. Create once (e.g. `lib/shopwave.ts`):
|
|
986
|
+
*
|
|
987
|
+
* ```ts
|
|
988
|
+
* export const shopwave = createShopwaveApi({ auth, apiUrl: process.env.SHOPWAVE_API_SERVER_URL! });
|
|
989
|
+
* ```
|
|
990
|
+
*
|
|
991
|
+
* then each route file is one line:
|
|
992
|
+
*
|
|
993
|
+
* ```ts
|
|
994
|
+
* // app/api/products/route.ts
|
|
995
|
+
* export const { GET, POST, PUT } = shopwave.collection("product");
|
|
996
|
+
* // app/api/products/[id]/route.ts
|
|
997
|
+
* export const { GET, PUT, DELETE } = shopwave.item("product");
|
|
998
|
+
* // app/api/report/route.ts
|
|
999
|
+
* export const { GET } = shopwave.passthrough("report");
|
|
1000
|
+
* ```
|
|
1001
|
+
*/
|
|
1002
|
+
function createShopwaveApi(config) {
|
|
1003
|
+
if (typeof window !== "undefined") throw new Error("react-shopwave-connect/next is server-only. Import it from route handlers or server code.");
|
|
1004
|
+
const { auth,...rest } = config;
|
|
1005
|
+
return createShopwaveApiHandlers({
|
|
1006
|
+
...rest,
|
|
1007
|
+
getAuthorization: (options) => auth.getAuthorizationHeader(options)
|
|
1008
|
+
});
|
|
1009
|
+
}
|
|
579
1010
|
|
|
580
1011
|
//#endregion
|
|
1012
|
+
exports.SHOPWAVE_ENTITIES = SHOPWAVE_ENTITIES;
|
|
581
1013
|
exports.ShopwaveAuthError = ShopwaveAuthError;
|
|
582
1014
|
exports.authorizationHeader = authorizationHeader;
|
|
1015
|
+
exports.createShopwaveApi = createShopwaveApi;
|
|
583
1016
|
exports.createShopwaveAuth = createShopwaveAuth;
|
|
584
1017
|
exports.isExpiredTokenResponse = isExpiredTokenResponse;
|
|
1018
|
+
exports.readRequestToken = readRequestToken;
|
|
585
1019
|
//# sourceMappingURL=index.cjs.map
|