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.
@@ -34,19 +34,24 @@ interface apiResponse {
34
34
  /**
35
35
  * Per-call configuration shared by every core API function.
36
36
  *
37
- * Nothing here is React-specific. By accepting these options per call, the
38
- * core layer works in the browser/Next (relative `/api/...` URLs, the default)
39
- * AND in Node / CLI / Vue / Angular by passing an absolute `baseUrl`, an auth
40
- * `token`, and/or a custom `fetch` implementation.
37
+ * Nothing here is React-specific. In the browser/Next leave `baseUrl` empty to
38
+ * call the app's own `/api/...` routes (which hold the session). From Node, a
39
+ * CLI or tests, pass an absolute `baseUrl` pointing at such an app plus a
40
+ * `token`.
41
41
  */
42
42
  interface RequestOptions {
43
43
  /**
44
44
  * Prefixed in front of every request path. Leave undefined in the browser to
45
- * use relative URLs (e.g. `/api/products`). In Node/CLI pass something like
46
- * `https://api.shopwave.com`.
45
+ * use relative URLs (e.g. `/api/products`). From Node pass the app origin,
46
+ * e.g. `http://localhost:3000`.
47
47
  */
48
48
  baseUrl?: string;
49
- /** OAuth/session token forwarded in the `extras.token` header. */
49
+ /**
50
+ * Shopwave OAuth access token. Sent as `Authorization: OAuth <token>` on every
51
+ * request (GET, POST, PUT and DELETE alike). A value that already starts with
52
+ * a scheme (`OAuth …` / `Bearer …`) is sent as-is. Leave unset in the browser:
53
+ * the app's routes use the session cookie.
54
+ */
50
55
  token?: string;
51
56
  /**
52
57
  * Custom fetch implementation. Defaults to the global `fetch`. Useful for
@@ -58,24 +63,79 @@ interface RequestOptions {
58
63
  }
59
64
  /** The Shopwave API ships request metadata inside a single `extras` header. */
60
65
  type Extras = Record<string, unknown>;
66
+ /** Options with `token` filled in from a legacy per-call `params.token`, unless `options.token` is set. */
67
+ declare function withToken(options: RequestOptions, token: string | undefined): RequestOptions;
68
+ /** `Authorization` header value for a token (`OAuth <token>` unless it already has a scheme). */
69
+ declare function authorizationFor(token: string): string;
70
+ /**
71
+ * Low-level request: resolves `{ status, body }` for 2xx responses and throws
72
+ * {@link ShopwaveApiError} otherwise. `init.headers` are merged over the
73
+ * standard ones (Accept + Authorization).
74
+ */
75
+ declare function apiRequest(path: string, init: RequestInit, options?: RequestOptions): Promise<{
76
+ status: number;
77
+ body: unknown;
78
+ }>;
61
79
  /**
62
80
  * Returns a JSON string of API errors if the response carries any, otherwise
63
- * `null`. Mirrors the original `!responseJson.api.message.errors` checks.
81
+ * `null`. Kept for backwards compatibility; prefer `ShopwaveApiError`.
64
82
  */
65
83
  declare function getApiErrors(api?: apiResponse): string | null;
66
84
  /**
67
- * GET helper. Sends request metadata via the `extras` header exactly like the
68
- * original hooks did, parses JSON, and returns the typed payload.
85
+ * GET helper. Sends request metadata via the `extras` header, parses JSON and
86
+ * returns the payload. Throws {@link ShopwaveApiError} for non-2xx responses.
69
87
  */
70
88
  declare function apiGet<T>(path: string, extras: Extras, options?: RequestOptions): Promise<T>;
71
89
  /**
72
- * JSON body helper for POST/PUT mutations.
90
+ * JSON body helper for POST/PUT mutations. Returns the parsed body (`null` for
91
+ * an empty one). Throws {@link ShopwaveApiError} for non-2xx responses.
73
92
  */
74
93
  declare function apiSend<T>(path: string, method: "POST" | "PUT", payload: unknown, options?: RequestOptions): Promise<T>;
75
94
  /**
76
- * DELETE helper.
95
+ * DELETE helper. Shopwave answers deletes with 205 and an empty body; if a body
96
+ * does come back and carries API errors, they are thrown. Returns the parsed
97
+ * body (`null` when empty).
77
98
  */
78
- declare function apiDelete(path: string, options?: RequestOptions): Promise<void>;
99
+ declare function apiDelete(path: string, options?: RequestOptions): Promise<unknown>;
100
+ //#endregion
101
+ //#region src/core/errors.d.ts
102
+ /** Map of Shopwave API errors as found in `api.message.errors`, keyed by error code. */
103
+ type ShopwaveErrorMap = Record<string, Partial<ErrorMessage>>;
104
+ /**
105
+ * Thrown by every `core` function when a request fails, either at the HTTP
106
+ * level (`status` is the HTTP status) or because the Shopwave response carried
107
+ * `api.message.errors` (then `status` is the HTTP status of that response,
108
+ * usually 200/201, and `errors` holds the API errors).
109
+ *
110
+ * Branch on `status` (e.g. `isUnauthorized` → send the user to log in) rather
111
+ * than parsing `message`.
112
+ */
113
+ declare class ShopwaveApiError extends Error {
114
+ /** HTTP status of the response (0 when the request never got a response). */
115
+ readonly status: number;
116
+ /** Shopwave API errors, when the response carried any. */
117
+ readonly errors: ShopwaveErrorMap | null;
118
+ /** Parsed response body, when there was one. */
119
+ readonly body?: unknown;
120
+ constructor(status: number, message: string, details?: {
121
+ errors?: ShopwaveErrorMap | null;
122
+ body?: unknown;
123
+ cause?: unknown;
124
+ });
125
+ /** 401, or the Shopwave "token expired / invalid" error 908. */
126
+ get isUnauthorized(): boolean;
127
+ get isNotFound(): boolean;
128
+ }
129
+ /** The `api.message.errors` (or `api.message.error`) map of a Shopwave response, or `null` when there are none. */
130
+ declare function getApiErrorMap(body: unknown): ShopwaveErrorMap | null;
131
+ /**
132
+ * Builds a {@link ShopwaveApiError} for a response. Understands the Shopwave
133
+ * envelope (`api.message.errors`) and the `{ error, message }` bodies returned
134
+ * by the `react-shopwave-connect/next` routes.
135
+ */
136
+ declare function toShopwaveApiError(status: number, body: unknown, fallback?: string): ShopwaveApiError;
137
+ /** Throws a {@link ShopwaveApiError} when the response body carries API errors. */
138
+ declare function assertNoApiErrors(body: unknown, status: number): void;
79
139
  //#endregion
80
140
  //#region src/core/category.d.ts
81
141
  interface Category {
@@ -96,7 +156,7 @@ interface FetchCategoriesParams {
96
156
  categoryIds?: Array<number>;
97
157
  /** Whether to include soft-deleted records. Defaults to `false`. */
98
158
  deleted?: boolean;
99
- /** Token override (also accepted via `options.token`). */
159
+ /** @deprecated Pass `options.token` instead. Sent the same way (Authorization header). */
100
160
  token?: string;
101
161
  }
102
162
  /**
@@ -159,6 +219,8 @@ interface FetchEmployeesParams {
159
219
  employeeIds?: Array<number>;
160
220
  /** Whether to include soft-deleted records. Defaults to `false`. */
161
221
  deleted?: boolean;
222
+ /** @deprecated Pass `options.token` instead. Sent the same way (Authorization header). */
223
+ token?: string;
162
224
  }
163
225
  /**
164
226
  * Fetches employees. Returns the flattened `Employee[]`.
@@ -203,7 +265,7 @@ interface FetchProductsParams {
203
265
  storeId?: number;
204
266
  /** Whether to include soft-deleted records. Defaults to `false`. */
205
267
  deleted?: boolean;
206
- /** Token override (also accepted via `options.token`). */
268
+ /** @deprecated Pass `options.token` instead. Sent the same way (Authorization header). */
207
269
  token?: string;
208
270
  }
209
271
  /**
@@ -265,7 +327,7 @@ interface FetchPromotionsParams {
265
327
  active?: boolean;
266
328
  /** Filter for expired promotions. */
267
329
  expired?: boolean;
268
- /** Token override (also accepted via `options.token`). */
330
+ /** @deprecated Pass `options.token` instead. Sent the same way (Authorization header). */
269
331
  token?: string;
270
332
  }
271
333
  /**
@@ -297,8 +359,12 @@ interface StoreResponse {
297
359
  api: apiResponse;
298
360
  }
299
361
  interface FetchStoresParams {
362
+ /** Optional id filter. */
363
+ storeIds?: Array<number>;
300
364
  /** Whether to include soft-deleted records. Defaults to `false`. */
301
365
  deleted?: boolean;
366
+ /** @deprecated Pass `options.token` instead. Sent the same way (Authorization header). */
367
+ token?: string;
302
368
  }
303
369
  /**
304
370
  * Fetches stores. Returns the flattened `Store[]`.
@@ -376,10 +442,12 @@ declare function logout(options?: RequestOptions): Promise<void>;
376
442
  //#endregion
377
443
  //#region src/core/entity.d.ts
378
444
  /**
379
- * Generic CRUD-style mutations extracted from `useHandleDelete` /
380
- * `useHandleSubmit`. The original hooks also surfaced notistack snackbars; that
381
- * UI concern is deliberately left to the hooks/host layer so core stays
382
- * dependency-free.
445
+ * Low-level, untyped mutations: the caller supplies the route and payload.
446
+ *
447
+ * Prefer the typed functions in `./entities` (`saveProduct`, `deleteCategory`,
448
+ * …): they know each route, build the request envelope, check the response and
449
+ * return the saved entity with its id. Keep these for routes that have no typed
450
+ * function yet (e.g. `/api/merchant`).
383
451
  */
384
452
  /**
385
453
  * Deletes `/api/{resourcePath}/{entityId}`.
@@ -398,8 +466,9 @@ interface SubmitEntityResponse<R = any> {
398
466
  [key: string]: unknown;
399
467
  }
400
468
  /**
401
- * Sends a create/update mutation and returns the parsed `result` field
402
- * (matching the original `result.result` access).
469
+ * Sends a create/update mutation. Returns the response's `result` field when it
470
+ * has one (older app routes wrapped their answer that way), otherwise the whole
471
+ * parsed response body. Throws `ShopwaveApiError` on HTTP or API errors.
403
472
  */
404
473
  declare function submitEntity<R = any>({
405
474
  endpoint,
@@ -407,6 +476,128 @@ declare function submitEntity<R = any>({
407
476
  payload
408
477
  }: SubmitEntityArgs, options?: RequestOptions): Promise<R | undefined>;
409
478
  //#endregion
479
+ //#region src/core/entities.d.ts
480
+ /**
481
+ * How each Shopwave entity is addressed, shared by the client functions below
482
+ * and the server route handlers in `react-shopwave-connect/next`, so the two
483
+ * halves of the contract can't drift apart.
484
+ */
485
+ interface EntityDefinition {
486
+ /** App route segment: `/api/<route>` and `/api/<route>/<id>`. */
487
+ route: string;
488
+ /** Key of the entity map in requests and responses (`{ products: { … } }`). */
489
+ collection: string;
490
+ /** Shopwave API path (`GET/POST/DELETE {apiUrl}/<upstream>`). */
491
+ upstream: string;
492
+ /** Header that filters reads by id (`productIds: 1,2`). */
493
+ idsHeader: string;
494
+ /** Header that names the record to delete (`productId: 1`). */
495
+ idHeader: string;
496
+ /** False for read-only entities (the API has no POST for them). */
497
+ writable: boolean;
498
+ /**
499
+ * How a delete is done upstream:
500
+ * - `"delete"`: `DELETE {apiUrl}/<upstream>` with the `idHeader` (205, empty body)
501
+ * - `"retire"`: the API has no DELETE; the record is retired by POSTing
502
+ * `{ id, [retireField]: <now> }` (employees: `exitDate`, promotions: `endDate`)
503
+ * - `"none"`: can't be deleted
504
+ */
505
+ deleteMode: "delete" | "retire" | "none";
506
+ /** Date field set to "now" when `deleteMode` is `"retire"`. */
507
+ retireField?: string;
508
+ }
509
+ type EntityKind = "product" | "category" | "store" | "promotion" | "employee" | "consumer";
510
+ /** Entities that can be created/updated through the API. */
511
+ type WritableEntityKind = Exclude<EntityKind, "consumer">;
512
+ /** Entities that can be deleted (or retired) through the API. */
513
+ type DeletableEntityKind = Exclude<EntityKind, "consumer">;
514
+ /**
515
+ * Addressing per entity, following the Shopwave API reference
516
+ * (https://developer.merchantstack.com/api-reference.html) and checked against
517
+ * the live API where noted:
518
+ * - category/product/store: GET filtered by `<x>Ids`, POST upsert, DELETE with `<x>Id` → 205.
519
+ * - promotion: no DELETE; "deleting" a promotion ends it by setting `endDate` to now.
520
+ * - employee: POST updates `roleId`, `joinedDate`, `exitDate` (names can't be
521
+ * changed); no DELETE (live API: "Cannot DELETE /employee") → retired via `exitDate`.
522
+ * - consumer: read-only (`GET` with `ids`, comma-separated); live POST → 404.
523
+ */
524
+ declare const SHOPWAVE_ENTITIES: Readonly<Record<EntityKind, EntityDefinition>>;
525
+ interface EntityTypes {
526
+ product: Product;
527
+ category: Category;
528
+ store: Store;
529
+ promotion: Promotion;
530
+ employee: Employee;
531
+ consumer: Consumer;
532
+ }
533
+ /**
534
+ * What a save accepts: any subset of the entity's fields (plus extra API
535
+ * fields the type doesn't list). Include `id` to update; leave it out to create.
536
+ */
537
+ type EntityInput<T> = Partial<T> & {
538
+ [field: string]: unknown;
539
+ };
540
+ /** A saved entity: always has its `id`. */
541
+ type Saved<T> = T & {
542
+ id: number;
543
+ };
544
+ type EntityId = number | string;
545
+ /**
546
+ * Creates or updates several entities of one kind in a single request and
547
+ * returns them as saved (with their ids), in the order given.
548
+ *
549
+ * The request is `{ <collection>: { "0": item0, "1": item1, … } }`. Shopwave
550
+ * answers 201 and echoes every entity under the ref it was sent with, so each
551
+ * result is matched back by ref. Throws {@link ShopwaveApiError} when the
552
+ * response carries `api.message.errors` or any ref is missing from it.
553
+ *
554
+ * The API's partial-success semantics for multi-entity saves haven't been
555
+ * confirmed yet; single saves (`saveProduct` etc.) are the tested path.
556
+ */
557
+ declare function saveEntities<K extends WritableEntityKind>(kind: K, items: ReadonlyArray<EntityInput<EntityTypes[K]>>, options?: RequestOptions): Promise<Array<Saved<EntityTypes[K]>>>;
558
+ /** Creates (no `id`) or updates (with `id`) one entity and returns it with its id. */
559
+ declare function saveEntity<K extends WritableEntityKind>(kind: K, item: EntityInput<EntityTypes[K]>, options?: RequestOptions): Promise<Saved<EntityTypes[K]>>;
560
+ /**
561
+ * Deletes one entity (a soft delete: it stays readable with `deleted: true`).
562
+ * Employees and promotions can't be deleted in Shopwave; for them the route
563
+ * sets `exitDate` / `endDate` to now instead (see `SHOPWAVE_ENTITIES`).
564
+ *
565
+ * Shopwave answers 205 with an empty body — also for ids that don't exist — so
566
+ * a resolved promise means "the API accepted the request", not "a record was
567
+ * deleted".
568
+ */
569
+ declare function deleteEntityById(kind: DeletableEntityKind, id: EntityId, options?: RequestOptions): Promise<void>;
570
+ interface FetchByIdParams {
571
+ /** Also return the record when it has been deleted. Defaults to `false`. */
572
+ deleted?: boolean;
573
+ }
574
+ /** Reads one entity by id, or `null` when there's no such (non-deleted) record. */
575
+ declare function fetchEntityById<K extends EntityKind>(kind: K, id: EntityId, params?: FetchByIdParams, options?: RequestOptions): Promise<EntityTypes[K] | null>;
576
+ declare const saveProduct: (product: EntityInput<Product>, options?: RequestOptions) => Promise<Saved<Product>>;
577
+ declare const deleteProduct: (id: EntityId, options?: RequestOptions) => Promise<void>;
578
+ declare const fetchProduct: (id: EntityId, params?: FetchByIdParams, options?: RequestOptions) => Promise<Product | null>;
579
+ declare const saveCategory: (category: EntityInput<Category>, options?: RequestOptions) => Promise<Saved<Category>>;
580
+ declare const deleteCategory: (id: EntityId, options?: RequestOptions) => Promise<void>;
581
+ declare const fetchCategory: (id: EntityId, params?: FetchByIdParams, options?: RequestOptions) => Promise<Category | null>;
582
+ declare const saveStore: (store: EntityInput<Store>, options?: RequestOptions) => Promise<Saved<Store>>;
583
+ declare const deleteStore: (id: EntityId, options?: RequestOptions) => Promise<void>;
584
+ declare const fetchStore: (id: EntityId, params?: FetchByIdParams, options?: RequestOptions) => Promise<Store | null>;
585
+ declare const savePromotion: (promotion: EntityInput<Promotion>, options?: RequestOptions) => Promise<Saved<Promotion>>;
586
+ /** Ends a promotion: Shopwave has no promotion DELETE, so this sets `endDate` to now. */
587
+ declare const deletePromotion: (id: EntityId, options?: RequestOptions) => Promise<void>;
588
+ declare const fetchPromotion: (id: EntityId, params?: FetchByIdParams, options?: RequestOptions) => Promise<Promotion | null>;
589
+ /**
590
+ * Creates an employee, or updates one (with `id`). On update Shopwave only
591
+ * applies `roleId`, `joinedDate` and `exitDate` (and store roles); names and
592
+ * email can't be changed, and the echo only carries the updated fields — re-read
593
+ * with `fetchEmployee` if you need the stored record.
594
+ */
595
+ declare const saveEmployee: (employee: EntityInput<Employee>, options?: RequestOptions) => Promise<Saved<Employee>>;
596
+ /** Retires an employee: Shopwave has no employee DELETE, so this sets `exitDate` to now. */
597
+ declare const deleteEmployee: (id: EntityId, options?: RequestOptions) => Promise<void>;
598
+ declare const fetchEmployee: (id: EntityId, params?: FetchByIdParams, options?: RequestOptions) => Promise<Employee | null>;
599
+ declare const fetchConsumer: (id: EntityId, params?: FetchByIdParams, options?: RequestOptions) => Promise<Consumer | null>;
600
+ //#endregion
410
601
  //#region src/core/basket.d.ts
411
602
  interface BasketItem {
412
603
  productId: number;
@@ -505,5 +696,5 @@ declare function buildConsumerMap(consumers: Consumer[] | null | undefined): {
505
696
  [id: number]: Consumer;
506
697
  };
507
698
  //#endregion
508
- export { Basket, BasketFilters, BasketItem, BasketPagination, BasketReportRow, BasketSummary, Category, CategoryResponse, CombineBasketRowsParams, Consumer, ConsumerResponse, DEFAULT_BASKET_FILTERS, DEFAULT_PAGINATION, Employee, EmployeeResponse, ErrorMessage, Extras, FetchCategoriesParams, FetchEmployeesParams, FetchProductsParams, FetchPromotionsParams, FetchStoresParams, MessageInfo, ParsedBasket, Product, ProductInstance, ProductResponse, Promotion, PromotionResponse, PromotionRuleSet, ReportData, ReportKey, ReportQuery, ReportQueryMap, ReportResponse, RequestOptions, SessionStatus, Store, StoreResponse, SubmitEntityArgs, SubmitEntityResponse, SuccessMessage, apiDelete, apiGet, apiResponse, apiSend, buildBasketReportQuery, buildConsumerMap, collectConsumerIds, collectProductIds, combineBasketRows, computeBasketSummary, deleteEntity, fetchCategories, fetchConsumers, fetchEmployees, fetchProducts, fetchProductsMap, fetchPromotions, fetchReport, fetchSession, fetchStores, formatDateForQuery, getApiErrors, loginPath, logout, logoutPath, parseBasketReportData, rolesById, submitEntity };
699
+ export { Basket, BasketFilters, BasketItem, BasketPagination, BasketReportRow, BasketSummary, Category, CategoryResponse, CombineBasketRowsParams, Consumer, ConsumerResponse, DEFAULT_BASKET_FILTERS, DEFAULT_PAGINATION, DeletableEntityKind, Employee, EmployeeResponse, EntityDefinition, EntityId, EntityInput, EntityKind, EntityTypes, ErrorMessage, Extras, FetchByIdParams, FetchCategoriesParams, FetchEmployeesParams, FetchProductsParams, FetchPromotionsParams, FetchStoresParams, MessageInfo, ParsedBasket, Product, ProductInstance, ProductResponse, Promotion, PromotionResponse, PromotionRuleSet, ReportData, ReportKey, ReportQuery, ReportQueryMap, ReportResponse, RequestOptions, SHOPWAVE_ENTITIES, Saved, SessionStatus, ShopwaveApiError, ShopwaveErrorMap, Store, StoreResponse, SubmitEntityArgs, SubmitEntityResponse, SuccessMessage, WritableEntityKind, apiDelete, apiGet, apiRequest, apiResponse, apiSend, assertNoApiErrors, authorizationFor, buildBasketReportQuery, buildConsumerMap, collectConsumerIds, collectProductIds, combineBasketRows, computeBasketSummary, deleteCategory, deleteEmployee, deleteEntity, deleteEntityById, deleteProduct, deletePromotion, deleteStore, fetchCategories, fetchCategory, fetchConsumer, fetchConsumers, fetchEmployee, fetchEmployees, fetchEntityById, fetchProduct, fetchProducts, fetchProductsMap, fetchPromotion, fetchPromotions, fetchReport, fetchSession, fetchStore, fetchStores, formatDateForQuery, getApiErrorMap, getApiErrors, loginPath, logout, logoutPath, parseBasketReportData, rolesById, saveCategory, saveEmployee, saveEntities, saveEntity, saveProduct, savePromotion, saveStore, submitEntity, toShopwaveApiError, withToken };
509
700
  //# sourceMappingURL=index.d.ts.map