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.
@@ -173,5 +173,174 @@ declare class ShopwaveAuthError extends Error {
173
173
  get isInvalidGrant(): boolean;
174
174
  }
175
175
  //#endregion
176
- export { SHOPWAVE_TOKEN_EXPIRED_ERROR_ID, ShopwaveAuthError, type ShopwaveAuthErrorCode, type ShopwaveOAuthClient, type ShopwaveOAuthConfig, type ShopwaveToken, type ShopwaveTokenResponse, assertOAuthConfig, authorizationHeader, createShopwaveOAuth, createState, isExpiredTokenResponse, isTokenExpired, normalizeStoredToken, safeEqual, sanitizeReturnTo, tokenFromResponse };
176
+ //#region src/core/entities.d.ts
177
+ /**
178
+ * How each Shopwave entity is addressed, shared by the client functions below
179
+ * and the server route handlers in `react-shopwave-connect/next`, so the two
180
+ * halves of the contract can't drift apart.
181
+ */
182
+ interface EntityDefinition {
183
+ /** App route segment: `/api/<route>` and `/api/<route>/<id>`. */
184
+ route: string;
185
+ /** Key of the entity map in requests and responses (`{ products: { … } }`). */
186
+ collection: string;
187
+ /** Shopwave API path (`GET/POST/DELETE {apiUrl}/<upstream>`). */
188
+ upstream: string;
189
+ /** Header that filters reads by id (`productIds: 1,2`). */
190
+ idsHeader: string;
191
+ /** Header that names the record to delete (`productId: 1`). */
192
+ idHeader: string;
193
+ /** False for read-only entities (the API has no POST for them). */
194
+ writable: boolean;
195
+ /**
196
+ * How a delete is done upstream:
197
+ * - `"delete"`: `DELETE {apiUrl}/<upstream>` with the `idHeader` (205, empty body)
198
+ * - `"retire"`: the API has no DELETE; the record is retired by POSTing
199
+ * `{ id, [retireField]: <now> }` (employees: `exitDate`, promotions: `endDate`)
200
+ * - `"none"`: can't be deleted
201
+ */
202
+ deleteMode: "delete" | "retire" | "none";
203
+ /** Date field set to "now" when `deleteMode` is `"retire"`. */
204
+ retireField?: string;
205
+ }
206
+ type EntityKind = "product" | "category" | "store" | "promotion" | "employee" | "consumer";
207
+ /** Entities that can be created/updated through the API. */
208
+ type WritableEntityKind = Exclude<EntityKind, "consumer">;
209
+ /** Entities that can be deleted (or retired) through the API. */
210
+ type DeletableEntityKind = Exclude<EntityKind, "consumer">;
211
+ /**
212
+ * Addressing per entity, following the Shopwave API reference
213
+ * (https://developer.merchantstack.com/api-reference.html) and checked against
214
+ * the live API where noted:
215
+ * - category/product/store: GET filtered by `<x>Ids`, POST upsert, DELETE with `<x>Id` → 205.
216
+ * - promotion: no DELETE; "deleting" a promotion ends it by setting `endDate` to now.
217
+ * - employee: POST updates `roleId`, `joinedDate`, `exitDate` (names can't be
218
+ * changed); no DELETE (live API: "Cannot DELETE /employee") → retired via `exitDate`.
219
+ * - consumer: read-only (`GET` with `ids`, comma-separated); live POST → 404.
220
+ */
221
+ declare const SHOPWAVE_ENTITIES: Readonly<Record<EntityKind, EntityDefinition>>;
222
+ //#endregion
223
+ //#region src/server/api.d.ts
224
+ /**
225
+ * The OAuth token a caller sent with the request, without its scheme, or `null`.
226
+ *
227
+ * Reads, in order: `Authorization: OAuth|Bearer <token>` (what the SDK sends
228
+ * from 0.3), the `token` header (SDK ≤ 0.2 writes), and `extras.token`
229
+ * (SDK ≤ 0.2 reads).
230
+ */
231
+ declare function readRequestToken(request: Request): string | null;
232
+ /**
233
+ * `extras` keys that are never forwarded upstream (case-insensitive).
234
+ * `Content-Type` is allowed (SDK clients have always sent `application/json`
235
+ * on reads) but is replaced by the form content type on writes.
236
+ */
237
+ declare const BLOCKED_EXTRAS: ReadonlySet<string>;
238
+ /**
239
+ * Parses the `extras` request header into upstream headers.
240
+ * Returns `null` when the header isn't a JSON object.
241
+ */
242
+ declare function parseExtras(raw: string | null, blocked?: ReadonlySet<string>): Record<string, string> | null;
243
+ declare class RequestBodyError extends Error {}
244
+ /**
245
+ * Normalises a write request body into the Shopwave envelope
246
+ * `{ <collection>: { <ref>: entity, … } }`.
247
+ *
248
+ * Accepts:
249
+ * - the SDK ≥ 0.3 shape `{ <collection>: { "0": {...}, "1": {...} } }` (refs kept),
250
+ * - the older AdminUI shapes `{ <collection>: { new: {...} } }` / `{ updated: {...} }`,
251
+ * - a bare entity object `{ title: … }`.
252
+ *
253
+ * With `forcedId` (item routes) exactly one entity is allowed and its `id` is
254
+ * set from the URL.
255
+ */
256
+ declare function normalizeWriteBody(def: Pick<EntityDefinition, "collection">, body: unknown, forcedId?: string): Record<string, Record<string, Record<string, unknown>>>;
257
+ interface ShopwaveApiConfig {
258
+ /** Shopwave API base URL, e.g. `process.env.SHOPWAVE_API_SERVER_URL`. */
259
+ apiUrl: string;
260
+ /**
261
+ * `Authorization` header value for the logged-in user (`"OAuth <token>"`),
262
+ * or `null` when logged out. Called again with `forceRefresh: true` when the
263
+ * API reports the token expired.
264
+ */
265
+ getAuthorization?: (options?: {
266
+ forceRefresh?: boolean;
267
+ }) => Promise<string | null>;
268
+ /**
269
+ * Accept a token sent by the caller (`Authorization: OAuth <token>`, or the
270
+ * legacy `token` header / `extras.token`) instead of the session. The token
271
+ * is only forwarded to the Shopwave API, which validates it. Defaults to `true`
272
+ * (SDK integration tests, scripts and server-to-server calls rely on it).
273
+ */
274
+ allowRequestToken?: boolean;
275
+ /** `x-accept-version` sent upstream. Defaults to `"2.0"`. */
276
+ apiVersion?: string;
277
+ /** Custom fetch for the upstream call. */
278
+ fetch?: typeof fetch;
279
+ /** Override how an entity is addressed (e.g. a different id header). */
280
+ entities?: Partial<Record<EntityKind, Partial<EntityDefinition>>>;
281
+ /** Extra `extras` keys to drop, on top of {@link BLOCKED_EXTRAS}. */
282
+ blockedExtras?: string[];
283
+ /**
284
+ * Called when the upstream call throws (network error). Defaults to a
285
+ * `console.error` with the method and path only — never headers or tokens.
286
+ */
287
+ onError?: (error: unknown, context: {
288
+ method: string;
289
+ path: string;
290
+ }) => void;
291
+ }
292
+ interface ForwardInit {
293
+ /** HTTP method sent upstream. Defaults to `GET`. */
294
+ method?: string;
295
+ /** Shopwave API path, e.g. `"product"`. */
296
+ path: string;
297
+ /** Extra upstream headers; they win over `extras`. */
298
+ headers?: Record<string, string>;
299
+ /** Sent as the form field `postBody=<JSON>`. */
300
+ postBody?: unknown;
301
+ /** Forward the caller's `extras` header as upstream headers. Defaults to `true`. */
302
+ forwardExtras?: boolean;
303
+ }
304
+ /** Second argument Next.js (and similar) pass to dynamic route handlers. */
305
+ interface RouteContext {
306
+ params?: Promise<Record<string, string | string[] | undefined>> | Record<string, string | string[] | undefined>;
307
+ }
308
+ type RouteHandler = (request: Request, context?: RouteContext) => Promise<Response>;
309
+ interface CollectionHandlers {
310
+ /** List/filter via `extras` (e.g. `productIds`, `deleted`). */
311
+ GET: RouteHandler;
312
+ /** Create or update (Shopwave upserts: an `id` means update). */
313
+ POST: RouteHandler;
314
+ /** Same as POST (kept for older clients). */
315
+ PUT: RouteHandler;
316
+ }
317
+ interface ItemHandlers {
318
+ /** Read one record by the `[id]` route param. */
319
+ GET: RouteHandler;
320
+ /** Update the record at `[id]` (the id in the URL wins). */
321
+ PUT: RouteHandler;
322
+ /** Delete the record at `[id]`. Shopwave answers 205 with an empty body. */
323
+ DELETE: RouteHandler;
324
+ }
325
+ interface ShopwaveApiHandlers {
326
+ /** Calls the Shopwave API for this request (token, extras, refresh-retry) and returns its answer. */
327
+ forward(request: Request, init: ForwardInit): Promise<Response>;
328
+ /** Handlers for `app/api/<route>/route.ts`. */
329
+ collection(kind: EntityKind): CollectionHandlers;
330
+ /** Handlers for `app/api/<route>/[id]/route.ts`. */
331
+ item(kind: EntityKind, options?: {
332
+ param?: string;
333
+ }): ItemHandlers;
334
+ /** GET-only proxy for a Shopwave path (e.g. `"report"`, `"user"`, `"merchant"`). */
335
+ passthrough(path: string): {
336
+ GET: RouteHandler;
337
+ };
338
+ /** The entity table in use (defaults merged with `config.entities`). */
339
+ entity(kind: EntityKind): EntityDefinition;
340
+ }
341
+ /** `YYYY-MM-DD HH:mm:ss` in UTC, the datetime format Shopwave writes use (e.g. promotions). */
342
+ declare function shopwaveDateTime(date?: Date): string;
343
+ declare function createShopwaveApiHandlers(config: ShopwaveApiConfig): ShopwaveApiHandlers;
344
+ //#endregion
345
+ export { BLOCKED_EXTRAS, type CollectionHandlers, type DeletableEntityKind, type EntityDefinition, type EntityKind, type ForwardInit, type ItemHandlers, RequestBodyError, type RouteContext, type RouteHandler, SHOPWAVE_ENTITIES, SHOPWAVE_TOKEN_EXPIRED_ERROR_ID, type ShopwaveApiConfig, type ShopwaveApiHandlers, ShopwaveAuthError, type ShopwaveAuthErrorCode, type ShopwaveOAuthClient, type ShopwaveOAuthConfig, type ShopwaveToken, type ShopwaveTokenResponse, type WritableEntityKind, assertOAuthConfig, authorizationHeader, createShopwaveApiHandlers, createShopwaveOAuth, createState, isExpiredTokenResponse, isTokenExpired, normalizeStoredToken, normalizeWriteBody, parseExtras, readRequestToken, safeEqual, sanitizeReturnTo, shopwaveDateTime, tokenFromResponse };
177
346
  //# sourceMappingURL=index.d.cts.map
@@ -173,5 +173,174 @@ declare class ShopwaveAuthError extends Error {
173
173
  get isInvalidGrant(): boolean;
174
174
  }
175
175
  //#endregion
176
- export { SHOPWAVE_TOKEN_EXPIRED_ERROR_ID, ShopwaveAuthError, type ShopwaveAuthErrorCode, type ShopwaveOAuthClient, type ShopwaveOAuthConfig, type ShopwaveToken, type ShopwaveTokenResponse, assertOAuthConfig, authorizationHeader, createShopwaveOAuth, createState, isExpiredTokenResponse, isTokenExpired, normalizeStoredToken, safeEqual, sanitizeReturnTo, tokenFromResponse };
176
+ //#region src/core/entities.d.ts
177
+ /**
178
+ * How each Shopwave entity is addressed, shared by the client functions below
179
+ * and the server route handlers in `react-shopwave-connect/next`, so the two
180
+ * halves of the contract can't drift apart.
181
+ */
182
+ interface EntityDefinition {
183
+ /** App route segment: `/api/<route>` and `/api/<route>/<id>`. */
184
+ route: string;
185
+ /** Key of the entity map in requests and responses (`{ products: { … } }`). */
186
+ collection: string;
187
+ /** Shopwave API path (`GET/POST/DELETE {apiUrl}/<upstream>`). */
188
+ upstream: string;
189
+ /** Header that filters reads by id (`productIds: 1,2`). */
190
+ idsHeader: string;
191
+ /** Header that names the record to delete (`productId: 1`). */
192
+ idHeader: string;
193
+ /** False for read-only entities (the API has no POST for them). */
194
+ writable: boolean;
195
+ /**
196
+ * How a delete is done upstream:
197
+ * - `"delete"`: `DELETE {apiUrl}/<upstream>` with the `idHeader` (205, empty body)
198
+ * - `"retire"`: the API has no DELETE; the record is retired by POSTing
199
+ * `{ id, [retireField]: <now> }` (employees: `exitDate`, promotions: `endDate`)
200
+ * - `"none"`: can't be deleted
201
+ */
202
+ deleteMode: "delete" | "retire" | "none";
203
+ /** Date field set to "now" when `deleteMode` is `"retire"`. */
204
+ retireField?: string;
205
+ }
206
+ type EntityKind = "product" | "category" | "store" | "promotion" | "employee" | "consumer";
207
+ /** Entities that can be created/updated through the API. */
208
+ type WritableEntityKind = Exclude<EntityKind, "consumer">;
209
+ /** Entities that can be deleted (or retired) through the API. */
210
+ type DeletableEntityKind = Exclude<EntityKind, "consumer">;
211
+ /**
212
+ * Addressing per entity, following the Shopwave API reference
213
+ * (https://developer.merchantstack.com/api-reference.html) and checked against
214
+ * the live API where noted:
215
+ * - category/product/store: GET filtered by `<x>Ids`, POST upsert, DELETE with `<x>Id` → 205.
216
+ * - promotion: no DELETE; "deleting" a promotion ends it by setting `endDate` to now.
217
+ * - employee: POST updates `roleId`, `joinedDate`, `exitDate` (names can't be
218
+ * changed); no DELETE (live API: "Cannot DELETE /employee") → retired via `exitDate`.
219
+ * - consumer: read-only (`GET` with `ids`, comma-separated); live POST → 404.
220
+ */
221
+ declare const SHOPWAVE_ENTITIES: Readonly<Record<EntityKind, EntityDefinition>>;
222
+ //#endregion
223
+ //#region src/server/api.d.ts
224
+ /**
225
+ * The OAuth token a caller sent with the request, without its scheme, or `null`.
226
+ *
227
+ * Reads, in order: `Authorization: OAuth|Bearer <token>` (what the SDK sends
228
+ * from 0.3), the `token` header (SDK ≤ 0.2 writes), and `extras.token`
229
+ * (SDK ≤ 0.2 reads).
230
+ */
231
+ declare function readRequestToken(request: Request): string | null;
232
+ /**
233
+ * `extras` keys that are never forwarded upstream (case-insensitive).
234
+ * `Content-Type` is allowed (SDK clients have always sent `application/json`
235
+ * on reads) but is replaced by the form content type on writes.
236
+ */
237
+ declare const BLOCKED_EXTRAS: ReadonlySet<string>;
238
+ /**
239
+ * Parses the `extras` request header into upstream headers.
240
+ * Returns `null` when the header isn't a JSON object.
241
+ */
242
+ declare function parseExtras(raw: string | null, blocked?: ReadonlySet<string>): Record<string, string> | null;
243
+ declare class RequestBodyError extends Error {}
244
+ /**
245
+ * Normalises a write request body into the Shopwave envelope
246
+ * `{ <collection>: { <ref>: entity, … } }`.
247
+ *
248
+ * Accepts:
249
+ * - the SDK ≥ 0.3 shape `{ <collection>: { "0": {...}, "1": {...} } }` (refs kept),
250
+ * - the older AdminUI shapes `{ <collection>: { new: {...} } }` / `{ updated: {...} }`,
251
+ * - a bare entity object `{ title: … }`.
252
+ *
253
+ * With `forcedId` (item routes) exactly one entity is allowed and its `id` is
254
+ * set from the URL.
255
+ */
256
+ declare function normalizeWriteBody(def: Pick<EntityDefinition, "collection">, body: unknown, forcedId?: string): Record<string, Record<string, Record<string, unknown>>>;
257
+ interface ShopwaveApiConfig {
258
+ /** Shopwave API base URL, e.g. `process.env.SHOPWAVE_API_SERVER_URL`. */
259
+ apiUrl: string;
260
+ /**
261
+ * `Authorization` header value for the logged-in user (`"OAuth <token>"`),
262
+ * or `null` when logged out. Called again with `forceRefresh: true` when the
263
+ * API reports the token expired.
264
+ */
265
+ getAuthorization?: (options?: {
266
+ forceRefresh?: boolean;
267
+ }) => Promise<string | null>;
268
+ /**
269
+ * Accept a token sent by the caller (`Authorization: OAuth <token>`, or the
270
+ * legacy `token` header / `extras.token`) instead of the session. The token
271
+ * is only forwarded to the Shopwave API, which validates it. Defaults to `true`
272
+ * (SDK integration tests, scripts and server-to-server calls rely on it).
273
+ */
274
+ allowRequestToken?: boolean;
275
+ /** `x-accept-version` sent upstream. Defaults to `"2.0"`. */
276
+ apiVersion?: string;
277
+ /** Custom fetch for the upstream call. */
278
+ fetch?: typeof fetch;
279
+ /** Override how an entity is addressed (e.g. a different id header). */
280
+ entities?: Partial<Record<EntityKind, Partial<EntityDefinition>>>;
281
+ /** Extra `extras` keys to drop, on top of {@link BLOCKED_EXTRAS}. */
282
+ blockedExtras?: string[];
283
+ /**
284
+ * Called when the upstream call throws (network error). Defaults to a
285
+ * `console.error` with the method and path only — never headers or tokens.
286
+ */
287
+ onError?: (error: unknown, context: {
288
+ method: string;
289
+ path: string;
290
+ }) => void;
291
+ }
292
+ interface ForwardInit {
293
+ /** HTTP method sent upstream. Defaults to `GET`. */
294
+ method?: string;
295
+ /** Shopwave API path, e.g. `"product"`. */
296
+ path: string;
297
+ /** Extra upstream headers; they win over `extras`. */
298
+ headers?: Record<string, string>;
299
+ /** Sent as the form field `postBody=<JSON>`. */
300
+ postBody?: unknown;
301
+ /** Forward the caller's `extras` header as upstream headers. Defaults to `true`. */
302
+ forwardExtras?: boolean;
303
+ }
304
+ /** Second argument Next.js (and similar) pass to dynamic route handlers. */
305
+ interface RouteContext {
306
+ params?: Promise<Record<string, string | string[] | undefined>> | Record<string, string | string[] | undefined>;
307
+ }
308
+ type RouteHandler = (request: Request, context?: RouteContext) => Promise<Response>;
309
+ interface CollectionHandlers {
310
+ /** List/filter via `extras` (e.g. `productIds`, `deleted`). */
311
+ GET: RouteHandler;
312
+ /** Create or update (Shopwave upserts: an `id` means update). */
313
+ POST: RouteHandler;
314
+ /** Same as POST (kept for older clients). */
315
+ PUT: RouteHandler;
316
+ }
317
+ interface ItemHandlers {
318
+ /** Read one record by the `[id]` route param. */
319
+ GET: RouteHandler;
320
+ /** Update the record at `[id]` (the id in the URL wins). */
321
+ PUT: RouteHandler;
322
+ /** Delete the record at `[id]`. Shopwave answers 205 with an empty body. */
323
+ DELETE: RouteHandler;
324
+ }
325
+ interface ShopwaveApiHandlers {
326
+ /** Calls the Shopwave API for this request (token, extras, refresh-retry) and returns its answer. */
327
+ forward(request: Request, init: ForwardInit): Promise<Response>;
328
+ /** Handlers for `app/api/<route>/route.ts`. */
329
+ collection(kind: EntityKind): CollectionHandlers;
330
+ /** Handlers for `app/api/<route>/[id]/route.ts`. */
331
+ item(kind: EntityKind, options?: {
332
+ param?: string;
333
+ }): ItemHandlers;
334
+ /** GET-only proxy for a Shopwave path (e.g. `"report"`, `"user"`, `"merchant"`). */
335
+ passthrough(path: string): {
336
+ GET: RouteHandler;
337
+ };
338
+ /** The entity table in use (defaults merged with `config.entities`). */
339
+ entity(kind: EntityKind): EntityDefinition;
340
+ }
341
+ /** `YYYY-MM-DD HH:mm:ss` in UTC, the datetime format Shopwave writes use (e.g. promotions). */
342
+ declare function shopwaveDateTime(date?: Date): string;
343
+ declare function createShopwaveApiHandlers(config: ShopwaveApiConfig): ShopwaveApiHandlers;
344
+ //#endregion
345
+ export { BLOCKED_EXTRAS, type CollectionHandlers, type DeletableEntityKind, type EntityDefinition, type EntityKind, type ForwardInit, type ItemHandlers, RequestBodyError, type RouteContext, type RouteHandler, SHOPWAVE_ENTITIES, SHOPWAVE_TOKEN_EXPIRED_ERROR_ID, type ShopwaveApiConfig, type ShopwaveApiHandlers, ShopwaveAuthError, type ShopwaveAuthErrorCode, type ShopwaveOAuthClient, type ShopwaveOAuthConfig, type ShopwaveToken, type ShopwaveTokenResponse, type WritableEntityKind, assertOAuthConfig, authorizationHeader, createShopwaveApiHandlers, createShopwaveOAuth, createState, isExpiredTokenResponse, isTokenExpired, normalizeStoredToken, normalizeWriteBody, parseExtras, readRequestToken, safeEqual, sanitizeReturnTo, shopwaveDateTime, tokenFromResponse };
177
346
  //# sourceMappingURL=index.d.ts.map