@viu/emporix-sdk 2.6.0 → 2.8.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/CHANGELOG.md CHANGED
@@ -1,5 +1,39 @@
1
1
  # @viu/emporix-sdk
2
2
 
3
+ ## 2.8.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#98](https://github.com/viuteam/emporix-sdk/pull/98) [`108a724`](https://github.com/viuteam/emporix-sdk/commit/108a724f1d4342532ae8d575faa501d54d8c591f) Thanks [@amnael1](https://github.com/amnael1)! - Support partial cart-item updates. `client.carts.updateItem(cartId, itemId,
8
+ patch, auth, { partial: true })` now sends `?partial=true`, so a quantity-only
9
+ change can be `{ quantity }` instead of a full item replace (which otherwise
10
+ requires re-sending `itemYrn` + the `price` row). The React
11
+ `useCartMutations().updateItem` mutation accepts an optional `partial` flag in
12
+ its variables. Default behavior is unchanged.
13
+
14
+ ## 2.7.0
15
+
16
+ ### Minor Changes
17
+
18
+ - [#96](https://github.com/viuteam/emporix-sdk/pull/96) [`da1113a`](https://github.com/viuteam/emporix-sdk/commit/da1113a07f70dceb9f1cb732b28462ccb3671f4a) Thanks [@amnael1](https://github.com/amnael1)! - Fix and extend the Category service for catalogue + hierarchy browsing. Several
19
+ methods targeted routes that don't exist on the deployed category service
20
+ (verified against a live tenant):
21
+ - **`categories.productsIn(...)`** requested a non-existent
22
+ `/categories/{id}/products` route (always 404). It now resolves products via
23
+ category **assignments** (`/categories/{id}/assignments` → keep `PRODUCT`
24
+ refs → `/products/search`), preserving its `PaginatedItems<Product>` contract;
25
+ categories with no products return an empty page instead of throwing.
26
+ - **`categories.tree()`** pointed at a non-existent `/categories/{...}Tree`
27
+ route. It now reads `/category-trees` and returns the catalogue's **root
28
+ categories** (`Promise<Category[]>`) for top-level navigation. (Return type
29
+ changed from the previous nested-node shape; the `rootId` argument is removed.)
30
+ - **New `categories.subcategories(categoryId)`** (+ React `useSubcategories`):
31
+ a category's direct child categories, resolved from `CATEGORY` assignment refs
32
+ (mirrors `productsIn`). Returns `[]` when there are none.
33
+
34
+ React `useCategoryTree()` now returns `Category[]` (root categories) and takes no
35
+ `rootId`.
36
+
3
37
  ## 2.6.0
4
38
 
5
39
  ### Minor Changes
package/dist/cart.cjs CHANGED
@@ -131,13 +131,19 @@ var CartService = class {
131
131
  body: items
132
132
  });
133
133
  }
134
- /** Updates an item. */
135
- async updateItem(cartId, itemId, patch, auth) {
134
+ /**
135
+ * Updates an item. By default this is a **full replace** — the server expects
136
+ * the complete item (e.g. `itemYrn` + the `price` row). Pass
137
+ * `{ partial: true }` to send a **partial update** (`?partial=true`), e.g. a
138
+ * quantity-only change with just `{ quantity }`.
139
+ */
140
+ async updateItem(cartId, itemId, patch, auth, opts = {}) {
136
141
  return this.ctx.http.request({
137
142
  method: "PUT",
138
143
  path: `${this.base()}/${cartId}/items/${itemId}`,
139
144
  auth: requireCartAuth(auth),
140
- body: patch
145
+ body: patch,
146
+ ...opts.partial ? { query: { partial: "true" } } : {}
141
147
  });
142
148
  }
143
149
  /** Removes an item. */
package/dist/cart.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/errors.ts","../src/services/cart.ts"],"names":[],"mappings":";;;AACA,IAAM,kBAAA,uBAAyB,GAAA,CAAI;AAAA,EACjC,cAAA;AAAA,EAAgB,eAAA;AAAA,EAAiB,OAAA;AAAA,EAAS,eAAA;AAAA,EAAiB,WAAA;AAAA,EAC3D,QAAA;AAAA,EAAU,eAAA;AAAA,EAAiB,eAAA;AAAA,EAAiB;AAC9C,CAAC,CAAA;AAED,SAAS,MAAM,IAAA,EAAwB;AACrC,EAAA,IAAI,MAAM,OAAA,CAAQ,IAAI,GAAG,OAAO,IAAA,CAAK,IAAI,KAAK,CAAA;AAC9C,EAAA,IAAI,IAAA,IAAQ,OAAO,IAAA,KAAS,QAAA,EAAU;AACpC,IAAA,MAAM,MAA+B,EAAC;AACtC,IAAA,KAAA,MAAW,CAAC,CAA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B,IAAA,EAAM,gBAAgB,IAAI,CAAA;AAAA,MAC1B,IAAA,EAAM;AAAA,KACP,CAAA;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,MAAM,KAAA,CACJ,cAAA,EACA,gBAAA,EACA,IAAA,EACe;AACf,IAAA,OAAO,IAAA,CAAK,GAAA,CAAI,IAAA,CAAK,OAAA,CAAc;AAAA,MACjC,MAAA,EAAQ,MAAA;AAAA,MACR,MAAM,CAAA,EAAG,IAAA,CAAK,IAAA,EAAM,IAAI,cAAc,CAAA,MAAA,CAAA;AAAA,MACtC,IAAA,EAAM,oBAAoB,IAAI,CAAA;AAAA,MAC9B,IAAA,EAAM,EAAE,KAAA,EAAO,gBAAA;AAAiB,KACjC,CAAA;AAAA,EACH;AACF","file":"cart.cjs","sourcesContent":["/** Keys whose values are stripped from any serialised error body. */\nconst REDACTED_BODY_KEYS = new Set([\n \"access_token\", \"refresh_token\", \"token\", \"customertoken\", \"saastoken\",\n \"secret\", \"client_secret\", \"authorization\", \"password\",\n]);\n\nfunction scrub(body: unknown): unknown {\n if (Array.isArray(body)) return body.map(scrub);\n if (body && typeof body === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(body as Record<string, unknown>)) {\n out[k] = REDACTED_BODY_KEYS.has(k.toLowerCase()) ? \"***redacted***\" : scrub(v);\n }\n return out;\n }\n return body;\n}\n\n/** Base class for every error thrown by the SDK. */\nexport class EmporixError extends Error {\n readonly status: number | undefined;\n readonly body: unknown;\n constructor(message: string, status?: number, body?: unknown) {\n super(message);\n this.name = new.target.name;\n this.status = status;\n this.body = body;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n /** Safe serialisation — token-like body fields are redacted. */\n toJSON(): Record<string, unknown> {\n return { name: this.name, message: this.message, status: this.status, body: scrub(this.body) };\n }\n}\n\n/** 401 — authentication failed or token expired. */\nexport class EmporixAuthError extends EmporixError {}\n/** 403 — authenticated but not permitted. */\nexport class EmporixForbiddenError extends EmporixError {}\n/** 404 — resource not found. */\nexport class EmporixNotFoundError extends EmporixError {}\n/** 400/422 — request validation failed. */\nexport class EmporixValidationError extends EmporixError {}\n/** 5xx — server-side failure. */\nexport class EmporixServerError extends EmporixError {}\n\n/**\n * 403 with a `missing scope: <name>` hint in the body's `details` array.\n * Subclasses {@link EmporixForbiddenError} so existing 403 catches still work.\n */\nexport class EmporixInsufficientScopeError extends EmporixForbiddenError {\n readonly requiredScope: string | undefined;\n constructor(message: string, status: number, body: unknown, requiredScope?: string) {\n super(message, status, body);\n this.requiredScope = requiredScope;\n }\n}\n\nconst SCOPE_HINT_RE = /missing scope[: ]+([a-z0-9._-]+)/i;\n\nfunction extractRequiredScope(body: unknown): string | undefined {\n if (body && typeof body === \"object\" && \"details\" in body) {\n const details = (body as { details?: unknown }).details;\n if (Array.isArray(details)) {\n for (const d of details) {\n if (typeof d === \"string\") {\n const m = d.match(SCOPE_HINT_RE);\n if (m) return m[1];\n }\n }\n }\n }\n return undefined;\n}\n\n/** Maps an HTTP status to the matching {@link EmporixError} subclass. */\nexport function errorFromResponse(status: number, message: string, body: unknown): EmporixError {\n if (status === 401) return new EmporixAuthError(message, status, body);\n if (status === 403) {\n const scope = extractRequiredScope(body);\n if (scope) return new EmporixInsufficientScopeError(message, status, body, scope);\n return new EmporixForbiddenError(message, status, body);\n }\n if (status === 404) return new EmporixNotFoundError(message, status, body);\n if (status === 400 || status === 422) return new EmporixValidationError(message, status, body);\n if (status >= 500) return new EmporixServerError(message, status, body);\n return new EmporixError(message, status, body);\n}\n","import type { ClientContext } from \"../core/context\";\nimport type { AuthContext } from \"../core/auth\";\nimport { EmporixNotFoundError, EmporixValidationError } from \"../core/errors\";\nimport type {\n Cart as GeneratedCart,\n CreateCart,\n CreatedCart,\n CartItemRequest,\n UpdateCartItem,\n AddressRequest,\n BatchResponse as GeneratedBatchResponse,\n SingleBatchResponse as GeneratedSingleBatchResponse,\n} from \"../generated/cart\";\n\n/** A cart as returned by the Cart service (all generated fields). */\nexport type Cart = GeneratedCart;\n\n/** The cart-create response (`{ cartId, yrn }`, generated). */\nexport type CartCreated = CreatedCart;\n\n/** Generated request bodies (caller sends the exact wire shape). */\nexport type CreateCartInput = CreateCart;\nexport type CartItemInput = CartItemRequest;\nexport type CartItemUpdate = UpdateCartItem;\n\n/** Per-entry result of `addItemsBatch`. `status` is HTTP-style per entry (e.g. 201 = added, 4xx = failed). */\nexport type CartItemBatchEntry = GeneratedSingleBatchResponse;\n/** Response shape of `addItemsBatch` — one entry per input item, matching by `index`. */\nexport type CartItemsBatchResponse = GeneratedBatchResponse;\n\n/** An address payload for cart shipping/billing (generated). */\nexport type CartAddress = AddressRequest;\n\nfunction requireCartAuth(auth: AuthContext | undefined): AuthContext {\n if (auth && (auth.kind === \"customer\" || auth.kind === \"anonymous\")) return auth;\n throw new EmporixValidationError(\n \"CartService requires an explicit { kind: 'customer' } or { kind: 'anonymous' } AuthContext\",\n );\n}\n\nfunction requireCustomerAuth(auth: AuthContext | undefined): AuthContext {\n if (auth && auth.kind === \"customer\") return auth;\n throw new EmporixValidationError(\"cart.merge requires a { kind: 'customer' } AuthContext\");\n}\n\n/** Cart operations. Every method requires an explicit customer/anonymous context. */\nexport class CartService {\n constructor(private readonly ctx: ClientContext) {}\n\n private base(): string {\n return `/cart/${this.ctx.tenant}/carts`;\n }\n\n /** Creates a cart. */\n async create(\n input: CreateCartInput | undefined,\n auth: AuthContext,\n ): Promise<CartCreated> {\n return this.ctx.http.request<CartCreated>({\n method: \"POST\",\n path: this.base(),\n auth: requireCartAuth(auth),\n body: input ?? {},\n });\n }\n\n /** Fetches a cart by id. */\n async get(cartId: string, auth: AuthContext): Promise<Cart> {\n return this.ctx.http.request<Cart>({\n method: \"GET\",\n path: `${this.base()}/${cartId}`,\n auth: requireCartAuth(auth),\n });\n }\n\n /** Returns the current cart for the session, or null if none. */\n /**\n * Get the customer / anonymous cart matching the given criteria. Per Emporix:\n * uniqueness is defined by `siteCode` + `type` + `legalEntityId` +\n * (`customerId` derived from a customer token, or `sessionId` derived from an\n * anonymous token). With `create: true`, Emporix creates a new cart if none\n * matches.\n *\n * Returns `null` on 404 (no cart found and `create` was not set). All other\n * errors are propagated.\n */\n async getCurrent(\n auth: AuthContext,\n opts: { siteCode: string; type?: string; legalEntityId?: string; create?: boolean },\n ): Promise<Cart | null> {\n const query: Record<string, string | number> = { siteCode: opts.siteCode };\n if (opts.type !== undefined) query.type = opts.type;\n if (opts.legalEntityId !== undefined) query.legalEntityId = opts.legalEntityId;\n if (opts.create) query.create = \"true\";\n try {\n return await this.ctx.http.request<Cart>({\n method: \"GET\",\n path: this.base(),\n query,\n auth: requireCartAuth(auth),\n });\n } catch (e) {\n if (e instanceof EmporixNotFoundError) return null;\n throw e;\n }\n }\n\n /** Adds an item. */\n async addItem(\n cartId: string,\n item: CartItemInput,\n auth: AuthContext,\n ): Promise<Cart> {\n return this.ctx.http.request<Cart>({\n method: \"POST\",\n path: `${this.base()}/${cartId}/items`,\n auth: requireCartAuth(auth),\n body: item,\n });\n }\n\n /**\n * Adds multiple items in a single request via `POST /carts/{id}/itemsBatch`.\n * Server-side limit is 200 entries per call — callers handling larger sets\n * must chunk. The response carries a per-entry `status` (HTTP-style: 201\n * for added, 4xx/5xx for failed) and `index` matching the input position;\n * partial failures do **not** throw — inspect `status` per entry.\n */\n async addItemsBatch(\n cartId: string,\n items: CartItemInput[],\n auth: AuthContext,\n ): Promise<CartItemsBatchResponse> {\n return this.ctx.http.request<CartItemsBatchResponse>({\n method: \"POST\",\n path: `${this.base()}/${cartId}/itemsBatch`,\n auth: requireCartAuth(auth),\n body: items,\n });\n }\n\n /** Updates an item. */\n async updateItem(\n cartId: string,\n itemId: string,\n patch: CartItemUpdate,\n auth: AuthContext,\n ): Promise<Cart> {\n return this.ctx.http.request<Cart>({\n method: \"PUT\",\n path: `${this.base()}/${cartId}/items/${itemId}`,\n auth: requireCartAuth(auth),\n body: patch,\n });\n }\n\n /** Removes an item. */\n async removeItem(cartId: string, itemId: string, auth: AuthContext): Promise<Cart> {\n return this.ctx.http.request<Cart>({\n method: \"DELETE\",\n path: `${this.base()}/${cartId}/items/${itemId}`,\n auth: requireCartAuth(auth),\n });\n }\n\n /** Empties the cart. */\n async clear(cartId: string, auth: AuthContext): Promise<Cart> {\n return this.ctx.http.request<Cart>({\n method: \"DELETE\",\n path: `${this.base()}/${cartId}/items`,\n auth: requireCartAuth(auth),\n });\n }\n\n /** Applies a coupon. */\n async applyCoupon(cartId: string, code: string, auth: AuthContext): Promise<Cart> {\n return this.ctx.http.request<Cart>({\n method: \"POST\",\n path: `${this.base()}/${cartId}/coupons`,\n auth: requireCartAuth(auth),\n body: { code },\n });\n }\n\n /** Removes a coupon. */\n async removeCoupon(cartId: string, code: string, auth: AuthContext): Promise<Cart> {\n return this.ctx.http.request<Cart>({\n method: \"DELETE\",\n path: `${this.base()}/${cartId}/coupons/${code}`,\n auth: requireCartAuth(auth),\n });\n }\n\n /** Sets the shipping address. */\n async setShippingAddress(\n cartId: string,\n address: CartAddress,\n auth: AuthContext,\n ): Promise<Cart> {\n return this.ctx.http.request<Cart>({\n method: \"PUT\",\n path: `${this.base()}/${cartId}/shipping-address`,\n auth: requireCartAuth(auth),\n body: address,\n });\n }\n\n /** Sets the billing address. */\n async setBillingAddress(\n cartId: string,\n address: CartAddress,\n auth: AuthContext,\n ): Promise<Cart> {\n return this.ctx.http.request<Cart>({\n method: \"PUT\",\n path: `${this.base()}/${cartId}/billing-address`,\n auth: requireCartAuth(auth),\n body: address,\n });\n }\n\n /**\n * Merges one or more anonymous carts into the specified customer cart.\n * Per Emporix: the target cart in the path **must belong to the logged-in\n * customer**, and each id in `anonymousCartIds` must belong to an anonymous\n * customer. Anonymous carts go `CLOSED` on success.\n *\n * Requires a customer `AuthContext`.\n */\n async merge(\n customerCartId: string,\n anonymousCartIds: string[],\n auth: AuthContext,\n ): Promise<Cart> {\n return this.ctx.http.request<Cart>({\n method: \"POST\",\n path: `${this.base()}/${customerCartId}/merge`,\n auth: requireCustomerAuth(auth),\n body: { carts: anonymousCartIds },\n });\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/core/errors.ts","../src/services/cart.ts"],"names":[],"mappings":";;;AACA,IAAM,kBAAA,uBAAyB,GAAA,CAAI;AAAA,EACjC,cAAA;AAAA,EAAgB,eAAA;AAAA,EAAiB,OAAA;AAAA,EAAS,eAAA;AAAA,EAAiB,WAAA;AAAA,EAC3D,QAAA;AAAA,EAAU,eAAA;AAAA,EAAiB,eAAA;AAAA,EAAiB;AAC9C,CAAC,CAAA;AAED,SAAS,MAAM,IAAA,EAAwB;AACrC,EAAA,IAAI,MAAM,OAAA,CAAQ,IAAI,GAAG,OAAO,IAAA,CAAK,IAAI,KAAK,CAAA;AAC9C,EAAA,IAAI,IAAA,IAAQ,OAAO,IAAA,KAAS,QAAA,EAAU;AACpC,IAAA,MAAM,MAA+B,EAAC;AACtC,IAAA,KAAA,MAAW,CAAC,CAAA,EAAG,CAAC,KAAK,MAAA,CAAO,OAAA,CAAQ,IAA+B,CAAA,EAAG;AACpE,MAAA,GAAA,CAAI,CAAC,CAAA,GAAI,kBAAA,CAAmB,GAAA,CAAI,CAAA,CAAE,aAAa,CAAA,GAAI,gBAAA,GAAmB,KAAA,CAAM,CAAC,CAAA;AAAA,IAC/E;AACA,IAAA,OAAO,GAAA;AAAA,EACT;AACA,EAAA,OAAO,IAAA;AACT;AAGO,IAAM,YAAA,GAAN,cAA2B,KAAA,CAAM;AAAA,EAC7B,MAAA;AAAA,EACA,IAAA;AAAA,EACT,WAAA,CAAY,OAAA,EAAiB,MAAA,EAAiB,IAAA,EAAgB;AAC5D,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,OAAO,GAAA,CAAA,MAAA,CAAW,IAAA;AACvB,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,MAAA,CAAO,cA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gBAAA;AAAiB,KACjC,CAAA;AAAA,EACH;AACF","file":"cart.cjs","sourcesContent":["/** Keys whose values are stripped from any serialised error body. */\nconst REDACTED_BODY_KEYS = new Set([\n \"access_token\", \"refresh_token\", \"token\", \"customertoken\", \"saastoken\",\n \"secret\", \"client_secret\", \"authorization\", \"password\",\n]);\n\nfunction scrub(body: unknown): unknown {\n if (Array.isArray(body)) return body.map(scrub);\n if (body && typeof body === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(body as Record<string, unknown>)) {\n out[k] = REDACTED_BODY_KEYS.has(k.toLowerCase()) ? \"***redacted***\" : scrub(v);\n }\n return out;\n }\n return body;\n}\n\n/** Base class for every error thrown by the SDK. */\nexport class EmporixError extends Error {\n readonly status: number | undefined;\n readonly body: unknown;\n constructor(message: string, status?: number, body?: unknown) {\n super(message);\n this.name = new.target.name;\n this.status = status;\n this.body = body;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n /** Safe serialisation — token-like body fields are redacted. */\n toJSON(): Record<string, unknown> {\n return { name: this.name, message: this.message, status: this.status, body: scrub(this.body) };\n }\n}\n\n/** 401 — authentication failed or token expired. */\nexport class EmporixAuthError extends EmporixError {}\n/** 403 — authenticated but not permitted. */\nexport class EmporixForbiddenError extends EmporixError {}\n/** 404 — resource not found. */\nexport class EmporixNotFoundError extends EmporixError {}\n/** 400/422 — request validation failed. */\nexport class EmporixValidationError extends EmporixError {}\n/** 5xx — server-side failure. */\nexport class EmporixServerError extends EmporixError {}\n\n/**\n * 403 with a `missing scope: <name>` hint in the body's `details` array.\n * Subclasses {@link EmporixForbiddenError} so existing 403 catches still work.\n */\nexport class EmporixInsufficientScopeError extends EmporixForbiddenError {\n readonly requiredScope: string | undefined;\n constructor(message: string, status: number, body: unknown, requiredScope?: string) {\n super(message, status, body);\n this.requiredScope = requiredScope;\n }\n}\n\nconst SCOPE_HINT_RE = /missing scope[: ]+([a-z0-9._-]+)/i;\n\nfunction extractRequiredScope(body: unknown): string | undefined {\n if (body && typeof body === \"object\" && \"details\" in body) {\n const details = (body as { details?: unknown }).details;\n if (Array.isArray(details)) {\n for (const d of details) {\n if (typeof d === \"string\") {\n const m = d.match(SCOPE_HINT_RE);\n if (m) return m[1];\n }\n }\n }\n }\n return undefined;\n}\n\n/** Maps an HTTP status to the matching {@link EmporixError} subclass. */\nexport function errorFromResponse(status: number, message: string, body: unknown): EmporixError {\n if (status === 401) return new EmporixAuthError(message, status, body);\n if (status === 403) {\n const scope = extractRequiredScope(body);\n if (scope) return new EmporixInsufficientScopeError(message, status, body, scope);\n return new EmporixForbiddenError(message, status, body);\n }\n if (status === 404) return new EmporixNotFoundError(message, status, body);\n if (status === 400 || status === 422) return new EmporixValidationError(message, status, body);\n if (status >= 500) return new EmporixServerError(message, status, body);\n return new EmporixError(message, status, body);\n}\n","import type { ClientContext } from \"../core/context\";\nimport type { AuthContext } from \"../core/auth\";\nimport { EmporixNotFoundError, EmporixValidationError } from \"../core/errors\";\nimport type {\n Cart as GeneratedCart,\n CreateCart,\n CreatedCart,\n CartItemRequest,\n UpdateCartItem,\n AddressRequest,\n BatchResponse as GeneratedBatchResponse,\n SingleBatchResponse as GeneratedSingleBatchResponse,\n} from \"../generated/cart\";\n\n/** A cart as returned by the Cart service (all generated fields). */\nexport type Cart = GeneratedCart;\n\n/** The cart-create response (`{ cartId, yrn }`, generated). */\nexport type CartCreated = CreatedCart;\n\n/** Generated request bodies (caller sends the exact wire shape). */\nexport type CreateCartInput = CreateCart;\nexport type CartItemInput = CartItemRequest;\nexport type CartItemUpdate = UpdateCartItem;\n\n/** Per-entry result of `addItemsBatch`. `status` is HTTP-style per entry (e.g. 201 = added, 4xx = failed). */\nexport type CartItemBatchEntry = GeneratedSingleBatchResponse;\n/** Response shape of `addItemsBatch` — one entry per input item, matching by `index`. */\nexport type CartItemsBatchResponse = GeneratedBatchResponse;\n\n/** An address payload for cart shipping/billing (generated). */\nexport type CartAddress = AddressRequest;\n\nfunction requireCartAuth(auth: AuthContext | undefined): AuthContext {\n if (auth && (auth.kind === \"customer\" || auth.kind === \"anonymous\")) return auth;\n throw new EmporixValidationError(\n \"CartService requires an explicit { kind: 'customer' } or { kind: 'anonymous' } AuthContext\",\n );\n}\n\nfunction requireCustomerAuth(auth: AuthContext | undefined): AuthContext {\n if (auth && auth.kind === \"customer\") return auth;\n throw new EmporixValidationError(\"cart.merge requires a { kind: 'customer' } AuthContext\");\n}\n\n/** Cart operations. Every method requires an explicit customer/anonymous context. */\nexport class CartService {\n constructor(private readonly ctx: ClientContext) {}\n\n private base(): string {\n return `/cart/${this.ctx.tenant}/carts`;\n }\n\n /** Creates a cart. */\n async create(\n input: CreateCartInput | undefined,\n auth: AuthContext,\n ): Promise<CartCreated> {\n return this.ctx.http.request<CartCreated>({\n method: \"POST\",\n path: this.base(),\n auth: requireCartAuth(auth),\n body: input ?? {},\n });\n }\n\n /** Fetches a cart by id. */\n async get(cartId: string, auth: AuthContext): Promise<Cart> {\n return this.ctx.http.request<Cart>({\n method: \"GET\",\n path: `${this.base()}/${cartId}`,\n auth: requireCartAuth(auth),\n });\n }\n\n /** Returns the current cart for the session, or null if none. */\n /**\n * Get the customer / anonymous cart matching the given criteria. Per Emporix:\n * uniqueness is defined by `siteCode` + `type` + `legalEntityId` +\n * (`customerId` derived from a customer token, or `sessionId` derived from an\n * anonymous token). With `create: true`, Emporix creates a new cart if none\n * matches.\n *\n * Returns `null` on 404 (no cart found and `create` was not set). All other\n * errors are propagated.\n */\n async getCurrent(\n auth: AuthContext,\n opts: { siteCode: string; type?: string; legalEntityId?: string; create?: boolean },\n ): Promise<Cart | null> {\n const query: Record<string, string | number> = { siteCode: opts.siteCode };\n if (opts.type !== undefined) query.type = opts.type;\n if (opts.legalEntityId !== undefined) query.legalEntityId = opts.legalEntityId;\n if (opts.create) query.create = \"true\";\n try {\n return await this.ctx.http.request<Cart>({\n method: \"GET\",\n path: this.base(),\n query,\n auth: requireCartAuth(auth),\n });\n } catch (e) {\n if (e instanceof EmporixNotFoundError) return null;\n throw e;\n }\n }\n\n /** Adds an item. */\n async addItem(\n cartId: string,\n item: CartItemInput,\n auth: AuthContext,\n ): Promise<Cart> {\n return this.ctx.http.request<Cart>({\n method: \"POST\",\n path: `${this.base()}/${cartId}/items`,\n auth: requireCartAuth(auth),\n body: item,\n });\n }\n\n /**\n * Adds multiple items in a single request via `POST /carts/{id}/itemsBatch`.\n * Server-side limit is 200 entries per call — callers handling larger sets\n * must chunk. The response carries a per-entry `status` (HTTP-style: 201\n * for added, 4xx/5xx for failed) and `index` matching the input position;\n * partial failures do **not** throw — inspect `status` per entry.\n */\n async addItemsBatch(\n cartId: string,\n items: CartItemInput[],\n auth: AuthContext,\n ): Promise<CartItemsBatchResponse> {\n return this.ctx.http.request<CartItemsBatchResponse>({\n method: \"POST\",\n path: `${this.base()}/${cartId}/itemsBatch`,\n auth: requireCartAuth(auth),\n body: items,\n });\n }\n\n /**\n * Updates an item. By default this is a **full replace** — the server expects\n * the complete item (e.g. `itemYrn` + the `price` row). Pass\n * `{ partial: true }` to send a **partial update** (`?partial=true`), e.g. a\n * quantity-only change with just `{ quantity }`.\n */\n async updateItem(\n cartId: string,\n itemId: string,\n patch: CartItemUpdate,\n auth: AuthContext,\n opts: { partial?: boolean } = {},\n ): Promise<Cart> {\n return this.ctx.http.request<Cart>({\n method: \"PUT\",\n path: `${this.base()}/${cartId}/items/${itemId}`,\n auth: requireCartAuth(auth),\n body: patch,\n ...(opts.partial ? { query: { partial: \"true\" } } : {}),\n });\n }\n\n /** Removes an item. */\n async removeItem(cartId: string, itemId: string, auth: AuthContext): Promise<Cart> {\n return this.ctx.http.request<Cart>({\n method: \"DELETE\",\n path: `${this.base()}/${cartId}/items/${itemId}`,\n auth: requireCartAuth(auth),\n });\n }\n\n /** Empties the cart. */\n async clear(cartId: string, auth: AuthContext): Promise<Cart> {\n return this.ctx.http.request<Cart>({\n method: \"DELETE\",\n path: `${this.base()}/${cartId}/items`,\n auth: requireCartAuth(auth),\n });\n }\n\n /** Applies a coupon. */\n async applyCoupon(cartId: string, code: string, auth: AuthContext): Promise<Cart> {\n return this.ctx.http.request<Cart>({\n method: \"POST\",\n path: `${this.base()}/${cartId}/coupons`,\n auth: requireCartAuth(auth),\n body: { code },\n });\n }\n\n /** Removes a coupon. */\n async removeCoupon(cartId: string, code: string, auth: AuthContext): Promise<Cart> {\n return this.ctx.http.request<Cart>({\n method: \"DELETE\",\n path: `${this.base()}/${cartId}/coupons/${code}`,\n auth: requireCartAuth(auth),\n });\n }\n\n /** Sets the shipping address. */\n async setShippingAddress(\n cartId: string,\n address: CartAddress,\n auth: AuthContext,\n ): Promise<Cart> {\n return this.ctx.http.request<Cart>({\n method: \"PUT\",\n path: `${this.base()}/${cartId}/shipping-address`,\n auth: requireCartAuth(auth),\n body: address,\n });\n }\n\n /** Sets the billing address. */\n async setBillingAddress(\n cartId: string,\n address: CartAddress,\n auth: AuthContext,\n ): Promise<Cart> {\n return this.ctx.http.request<Cart>({\n method: \"PUT\",\n path: `${this.base()}/${cartId}/billing-address`,\n auth: requireCartAuth(auth),\n body: address,\n });\n }\n\n /**\n * Merges one or more anonymous carts into the specified customer cart.\n * Per Emporix: the target cart in the path **must belong to the logged-in\n * customer**, and each id in `anonymousCartIds` must belong to an anonymous\n * customer. Anonymous carts go `CLOSED` on success.\n *\n * Requires a customer `AuthContext`.\n */\n async merge(\n customerCartId: string,\n anonymousCartIds: string[],\n auth: AuthContext,\n ): Promise<Cart> {\n return this.ctx.http.request<Cart>({\n method: \"POST\",\n path: `${this.base()}/${customerCartId}/merge`,\n auth: requireCustomerAuth(auth),\n body: { carts: anonymousCartIds },\n });\n }\n}\n"]}
package/dist/cart.d.cts CHANGED
@@ -1779,8 +1779,15 @@ declare class CartService {
1779
1779
  * partial failures do **not** throw — inspect `status` per entry.
1780
1780
  */
1781
1781
  addItemsBatch(cartId: string, items: CartItemInput[], auth: AuthContext): Promise<CartItemsBatchResponse>;
1782
- /** Updates an item. */
1783
- updateItem(cartId: string, itemId: string, patch: CartItemUpdate, auth: AuthContext): Promise<Cart>;
1782
+ /**
1783
+ * Updates an item. By default this is a **full replace** — the server expects
1784
+ * the complete item (e.g. `itemYrn` + the `price` row). Pass
1785
+ * `{ partial: true }` to send a **partial update** (`?partial=true`), e.g. a
1786
+ * quantity-only change with just `{ quantity }`.
1787
+ */
1788
+ updateItem(cartId: string, itemId: string, patch: CartItemUpdate, auth: AuthContext, opts?: {
1789
+ partial?: boolean;
1790
+ }): Promise<Cart>;
1784
1791
  /** Removes an item. */
1785
1792
  removeItem(cartId: string, itemId: string, auth: AuthContext): Promise<Cart>;
1786
1793
  /** Empties the cart. */
package/dist/cart.d.ts CHANGED
@@ -1779,8 +1779,15 @@ declare class CartService {
1779
1779
  * partial failures do **not** throw — inspect `status` per entry.
1780
1780
  */
1781
1781
  addItemsBatch(cartId: string, items: CartItemInput[], auth: AuthContext): Promise<CartItemsBatchResponse>;
1782
- /** Updates an item. */
1783
- updateItem(cartId: string, itemId: string, patch: CartItemUpdate, auth: AuthContext): Promise<Cart>;
1782
+ /**
1783
+ * Updates an item. By default this is a **full replace** — the server expects
1784
+ * the complete item (e.g. `itemYrn` + the `price` row). Pass
1785
+ * `{ partial: true }` to send a **partial update** (`?partial=true`), e.g. a
1786
+ * quantity-only change with just `{ quantity }`.
1787
+ */
1788
+ updateItem(cartId: string, itemId: string, patch: CartItemUpdate, auth: AuthContext, opts?: {
1789
+ partial?: boolean;
1790
+ }): Promise<Cart>;
1784
1791
  /** Removes an item. */
1785
1792
  removeItem(cartId: string, itemId: string, auth: AuthContext): Promise<Cart>;
1786
1793
  /** Empties the cart. */
package/dist/cart.js CHANGED
@@ -1,4 +1,4 @@
1
- export { CartService } from './chunk-IEZHGU7F.js';
1
+ export { CartService } from './chunk-I3YYGSN2.js';
2
2
  import './chunk-KTODT6DV.js';
3
3
  //# sourceMappingURL=cart.js.map
4
4
  //# sourceMappingURL=cart.js.map
package/dist/category.cjs CHANGED
@@ -43,26 +43,67 @@ var CategoryService = class {
43
43
  const pageSize = params.pageSize ?? 50;
44
44
  return iterateAll((pageNumber) => this.list({ pageNumber, pageSize }, auth));
45
45
  }
46
- /** Fetches the category tree, optionally rooted at `rootId`. */
47
- async tree(rootId, auth = ANON) {
46
+ /**
47
+ * The catalogue's **root categories** — the published category trees
48
+ * (`GET /category-trees`). Use these for top-level storefront navigation;
49
+ * drill into a node's children with {@link subcategories}.
50
+ */
51
+ async tree(auth = ANON) {
48
52
  return this.ctx.http.request({
49
53
  method: "GET",
50
- path: `/category/${this.ctx.tenant}/categories/tree`,
51
- query: rootId ? { rootId } : {},
54
+ path: `/category/${this.ctx.tenant}/category-trees`,
55
+ auth
56
+ });
57
+ }
58
+ /**
59
+ * Direct child categories of a category (for hierarchy drill-down). Mirrors
60
+ * {@link productsIn}: reads the category's **assignments** and keeps the
61
+ * `CATEGORY` references, resolving them to full categories. Returns an empty
62
+ * array when the category has no child categories.
63
+ */
64
+ async subcategories(categoryId, params = {}, auth = ANON) {
65
+ const pageNumber = params.pageNumber ?? 1;
66
+ const pageSize = params.pageSize ?? 50;
67
+ const assignments = await this.ctx.http.request({
68
+ method: "GET",
69
+ path: `/category/${this.ctx.tenant}/categories/${categoryId}/assignments`,
70
+ query: { pageNumber, pageSize },
52
71
  auth
53
72
  });
73
+ const categoryIds = assignments.map((a) => a.ref?.type?.toUpperCase() === "CATEGORY" ? a.ref.id : void 0).filter((id) => Boolean(id));
74
+ if (categoryIds.length === 0) return [];
75
+ return this.searchByIds(categoryIds, {}, auth);
54
76
  }
55
- /** One page of products in a category. */
77
+ /**
78
+ * One page of products in a category. The category service exposes products
79
+ * as **assignments** (`/categories/{id}/assignments`) — references, not full
80
+ * products — so this fetches a page of assignments, keeps the `PRODUCT`
81
+ * references, and resolves them to full products via `/products/search`.
82
+ * `hasNextPage` reflects the assignments page (the source of truth for
83
+ * pagination).
84
+ */
56
85
  async productsIn(categoryId, params = {}, auth = ANON) {
57
86
  const pageNumber = params.pageNumber ?? 1;
58
87
  const pageSize = params.pageSize ?? 50;
59
- const items = await this.ctx.http.request({
88
+ const assignments = await this.ctx.http.request({
60
89
  method: "GET",
61
- path: `/category/${this.ctx.tenant}/categories/${categoryId}/products`,
90
+ path: `/category/${this.ctx.tenant}/categories/${categoryId}/assignments`,
62
91
  query: { pageNumber, pageSize },
63
92
  auth
64
93
  });
65
- return { items, pageNumber, pageSize, hasNextPage: items.length === pageSize };
94
+ const hasNextPage = assignments.length === pageSize;
95
+ const productIds = assignments.map((a) => a.ref?.type?.toUpperCase() === "PRODUCT" ? a.ref.id : void 0).filter((id) => Boolean(id));
96
+ if (productIds.length === 0) {
97
+ return { items: [], pageNumber, pageSize, hasNextPage };
98
+ }
99
+ const items = await this.ctx.http.request({
100
+ method: "POST",
101
+ path: `/product/${this.ctx.tenant}/products/search`,
102
+ query: { pageSize: productIds.length },
103
+ auth,
104
+ body: { q: `id:(${productIds.join(",")})` }
105
+ });
106
+ return { items, pageNumber, pageSize, hasNextPage };
66
107
  }
67
108
  /**
68
109
  * Bulk fetch by id. POSTs `/categories/search` with `q="id:(id1,id2,…)"`,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/context.ts","../src/services/category.ts"],"names":[],"mappings":";;;AAkCA,gBAAuB,UAAA,CACrB,SAAA,EACA,KAAA,GAAQ,CAAA,EACU;AAClB,EAAA,IAAI,CAAA,GAAI,KAAA;AACR,EAAA,WAAS;AACP,IAAA,MAAM,IAAA,GAAO,MAAM,SAAA,CAAU,CAAC,CAAA;AAC9B,IAAA,KAAA,MAAW,EAAA,IAAM,IAAA,CAAK,KAAA,EAAO,MAAM,EAAA;AACnC,IAAA,IAAI,CAAC,KAAK,WAAA,EAAa;AACvB,IAAA,CAAA,IAAK,CAAA;AAAA,EACP;AACF;;;ACvCA,IAAM,IAAA,GAAoB,EAAE,IAAA,EAAM,WAAA,EAAY;AASvC,IAAM,kBAAN,MAAsB;AAAA,EAC3B,YAA6B,GAAA,EAAoB;AAApB,IAAA,IAAA,CAAA,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AI,CAAA,EAAG,CAAA,GAAI,GAAA,CAAI,MAAA,EAAQ,KAAK,SAAA,EAAW;AAC9C,MAAA,MAAA,CAAO,KAAK,GAAA,CAAI,KAAA,CAAM,CAAA,EAAG,CAAA,GAAI,SAAS,CAAC,CAAA;AAAA,IACzC;AACA,IAAA,MAAM,KAAA,GAAQ,MAAM,OAAA,CAAQ,GAAA;AAAA,MAC1B,MAAA,CAAO,GAAA;AAAA,QAAI,CAAC,KAAA,KACV,IAAA,CAAK,GAAA,CAAI,KAAK,OAAA,CAAoB;AAAA,UAChC,MAAA,EAAQ,MAAA;AAAA,UACR,IAAA,EAAM,CAAA,UAAA,EAAa,IAAA,CAAK,GAAA,CAAI,MAAM,CAAA,kBAAA,CAAA;AAAA,UAClC,KAAA,EAAO,EAAE,QAAA,EAAU,KAAA,CAAM,MAAA,EAAO;AAAA,UAChC,IAAA;AAAA,UACA,IAAA,EAAM,EAAE,CAAA,EAAG,CAAA,IAAA,EAAO,MAAM,IAAA,CAAK,GAAG,CAAC,CAAA,CAAA,CAAA;AAAI,SACtC;AAAA;AACH,KACF;AACA,IAAA,OAAO,MAAM,IAAA,EAAK;AAAA,EACpB;AACF","file":"category.cjs","sourcesContent":["import type { HttpClient } from \"./http\";\nimport type { TokenProvider, AuthContext } from \"./auth\";\nimport type { Logger } from \"./logger\";\n\n/** Shared dependencies every service facade receives. */\nexport interface ClientContext {\n tenant: string;\n http: HttpClient;\n tokenProvider: TokenProvider;\n logger: Logger;\n}\n\n/**\n * A cursor-paged collection — `pageNumber`/`pageSize` indexing with a\n * `hasNextPage` signal driven by the source page being full. Used by all\n * paginated services and hooks across the SDK.\n */\nexport interface PaginatedItems<T> {\n items: T[];\n pageNumber: number;\n pageSize: number;\n hasNextPage: boolean;\n}\n\n/** Default `AuthContext` applied by a service when the caller passes none. */\nexport type DefaultAuth = AuthContext | undefined;\n\n/**\n * Async-iterates every item across pages of a `PaginatedItems<T>` source.\n * Stops when the source reports `hasNextPage: false`.\n *\n * @param fetchPage - given a 1-based page number, returns the page.\n * @param start - first page to fetch (default `1`).\n */\nexport async function* iterateAll<T>(\n fetchPage: (pageNumber: number) => Promise<PaginatedItems<T>>,\n start = 1,\n): AsyncIterable<T> {\n let p = start;\n for (;;) {\n const page = await fetchPage(p);\n for (const it of page.items) yield it;\n if (!page.hasNextPage) return;\n p += 1;\n }\n}\n\n","import type { ClientContext, PaginatedItems } from \"../core/context\";\nimport { iterateAll } from \"../core/context\";\nimport type { AuthContext } from \"../core/auth\";\nimport type { Product } from \"./product\";\nimport type { Category as GeneratedCategory, CategoryTree } from \"../generated/category\";\n\nconst ANON: AuthContext = { kind: \"anonymous\" };\n\n/** A category as returned by the Category service (all generated fields). */\nexport type Category = GeneratedCategory;\n\n/** The category tree as returned by the Category service. */\nexport type CategoryNode = CategoryTree;\n\n/** Category reads. Default auth: anonymous. */\nexport class CategoryService {\n constructor(private readonly ctx: ClientContext) {}\n\n /** Fetches one category by id. */\n async get(categoryId: string, auth: AuthContext = ANON): Promise<Category> {\n return this.ctx.http.request<Category>({\n method: \"GET\",\n path: `/category/${this.ctx.tenant}/categories/${categoryId}`,\n auth,\n });\n }\n\n /** One page of categories. */\n async list(\n params: { pageNumber?: number; pageSize?: number } = {},\n auth: AuthContext = ANON,\n ): Promise<PaginatedItems<Category>> {\n const pageNumber = params.pageNumber ?? 1;\n const pageSize = params.pageSize ?? 50;\n const items = await this.ctx.http.request<Category[]>({\n method: \"GET\",\n path: `/category/${this.ctx.tenant}/categories`,\n query: { pageNumber, pageSize },\n auth,\n });\n return { items, pageNumber, pageSize, hasNextPage: items.length === pageSize };\n }\n\n /** Async-iterates every category across pages. */\n listAll(params: { pageSize?: number } = {}, auth: AuthContext = ANON): AsyncIterable<Category> {\n const pageSize = params.pageSize ?? 50;\n return iterateAll<Category>((pageNumber) => this.list({ pageNumber, pageSize }, auth));\n }\n\n /** Fetches the category tree, optionally rooted at `rootId`. */\n async tree(rootId?: string, auth: AuthContext = ANON): Promise<CategoryNode> {\n return this.ctx.http.request<CategoryNode>({\n method: \"GET\",\n path: `/category/${this.ctx.tenant}/categories/tree`,\n query: rootId ? { rootId } : {},\n auth,\n });\n }\n\n /** One page of products in a category. */\n async productsIn(\n categoryId: string,\n params: { pageNumber?: number; pageSize?: number } = {},\n auth: AuthContext = ANON,\n ): Promise<PaginatedItems<Product>> {\n const pageNumber = params.pageNumber ?? 1;\n const pageSize = params.pageSize ?? 50;\n const items = await this.ctx.http.request<Product[]>({\n method: \"GET\",\n path: `/category/${this.ctx.tenant}/categories/${categoryId}/products`,\n query: { pageNumber, pageSize },\n auth,\n });\n return { items, pageNumber, pageSize, hasNextPage: items.length === pageSize };\n }\n\n /**\n * Bulk fetch by id. POSTs `/categories/search` with `q=\"id:(id1,id2,…)\"`,\n * chunking when the list is larger than `options.chunkSize` (default\n * 100). An empty list short-circuits with no HTTP call. **Order is not\n * guaranteed** across chunks — re-index by `id` if order matters.\n */\n async searchByIds(\n ids: string[],\n options: { chunkSize?: number } = {},\n auth: AuthContext = ANON,\n ): Promise<Category[]> {\n if (ids.length === 0) return [];\n const chunkSize = options.chunkSize ?? 100;\n const chunks: string[][] = [];\n for (let i = 0; i < ids.length; i += chunkSize) {\n chunks.push(ids.slice(i, i + chunkSize));\n }\n const pages = await Promise.all(\n chunks.map((chunk) =>\n this.ctx.http.request<Category[]>({\n method: \"POST\",\n path: `/category/${this.ctx.tenant}/categories/search`,\n query: { pageSize: chunk.length },\n auth,\n body: { q: `id:(${chunk.join(\",\")})` },\n }),\n ),\n );\n return pages.flat();\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/core/context.ts","../src/services/category.ts"],"names":[],"mappings":";;;AAkCA,gBAAuB,UAAA,CACrB,SAAA,EACA,KAAA,GAAQ,CAAA,EACU;AAClB,EAAA,IAAI,CAAA,GAAI,KAAA;AACR,EAAA,WAAS;AACP,IAAA,MAAM,IAAA,GAAO,MAAM,SAAA,CAAU,CAAC,CAAA;AAC9B,IAAA,KAAA,MAAW,EAA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AM,MAAA,EAAO;AAAA,UAChC,IAAA;AAAA,UACA,IAAA,EAAM,EAAE,CAAA,EAAG,CAAA,IAAA,EAAO,MAAM,IAAA,CAAK,GAAG,CAAC,CAAA,CAAA,CAAA;AAAI,SACtC;AAAA;AACH,KACF;AACA,IAAA,OAAO,MAAM,IAAA,EAAK;AAAA,EACpB;AACF","file":"category.cjs","sourcesContent":["import type { HttpClient } from \"./http\";\nimport type { TokenProvider, AuthContext } from \"./auth\";\nimport type { Logger } from \"./logger\";\n\n/** Shared dependencies every service facade receives. */\nexport interface ClientContext {\n tenant: string;\n http: HttpClient;\n tokenProvider: TokenProvider;\n logger: Logger;\n}\n\n/**\n * A cursor-paged collection — `pageNumber`/`pageSize` indexing with a\n * `hasNextPage` signal driven by the source page being full. Used by all\n * paginated services and hooks across the SDK.\n */\nexport interface PaginatedItems<T> {\n items: T[];\n pageNumber: number;\n pageSize: number;\n hasNextPage: boolean;\n}\n\n/** Default `AuthContext` applied by a service when the caller passes none. */\nexport type DefaultAuth = AuthContext | undefined;\n\n/**\n * Async-iterates every item across pages of a `PaginatedItems<T>` source.\n * Stops when the source reports `hasNextPage: false`.\n *\n * @param fetchPage - given a 1-based page number, returns the page.\n * @param start - first page to fetch (default `1`).\n */\nexport async function* iterateAll<T>(\n fetchPage: (pageNumber: number) => Promise<PaginatedItems<T>>,\n start = 1,\n): AsyncIterable<T> {\n let p = start;\n for (;;) {\n const page = await fetchPage(p);\n for (const it of page.items) yield it;\n if (!page.hasNextPage) return;\n p += 1;\n }\n}\n\n","import type { ClientContext, PaginatedItems } from \"../core/context\";\nimport { iterateAll } from \"../core/context\";\nimport type { AuthContext } from \"../core/auth\";\nimport type { Product } from \"./product\";\nimport type { Category as GeneratedCategory, CategoryTree } from \"../generated/category\";\n\nconst ANON: AuthContext = { kind: \"anonymous\" };\n\n/** A category as returned by the Category service (all generated fields). */\nexport type Category = GeneratedCategory;\n\n/** The category tree as returned by the Category service. */\nexport type CategoryNode = CategoryTree;\n\n/** Category reads. Default auth: anonymous. */\nexport class CategoryService {\n constructor(private readonly ctx: ClientContext) {}\n\n /** Fetches one category by id. */\n async get(categoryId: string, auth: AuthContext = ANON): Promise<Category> {\n return this.ctx.http.request<Category>({\n method: \"GET\",\n path: `/category/${this.ctx.tenant}/categories/${categoryId}`,\n auth,\n });\n }\n\n /** One page of categories. */\n async list(\n params: { pageNumber?: number; pageSize?: number } = {},\n auth: AuthContext = ANON,\n ): Promise<PaginatedItems<Category>> {\n const pageNumber = params.pageNumber ?? 1;\n const pageSize = params.pageSize ?? 50;\n const items = await this.ctx.http.request<Category[]>({\n method: \"GET\",\n path: `/category/${this.ctx.tenant}/categories`,\n query: { pageNumber, pageSize },\n auth,\n });\n return { items, pageNumber, pageSize, hasNextPage: items.length === pageSize };\n }\n\n /** Async-iterates every category across pages. */\n listAll(params: { pageSize?: number } = {}, auth: AuthContext = ANON): AsyncIterable<Category> {\n const pageSize = params.pageSize ?? 50;\n return iterateAll<Category>((pageNumber) => this.list({ pageNumber, pageSize }, auth));\n }\n\n /**\n * The catalogue's **root categories** — the published category trees\n * (`GET /category-trees`). Use these for top-level storefront navigation;\n * drill into a node's children with {@link subcategories}.\n */\n async tree(auth: AuthContext = ANON): Promise<Category[]> {\n return this.ctx.http.request<Category[]>({\n method: \"GET\",\n path: `/category/${this.ctx.tenant}/category-trees`,\n auth,\n });\n }\n\n /**\n * Direct child categories of a category (for hierarchy drill-down). Mirrors\n * {@link productsIn}: reads the category's **assignments** and keeps the\n * `CATEGORY` references, resolving them to full categories. Returns an empty\n * array when the category has no child categories.\n */\n async subcategories(\n categoryId: string,\n params: { pageNumber?: number; pageSize?: number } = {},\n auth: AuthContext = ANON,\n ): Promise<Category[]> {\n const pageNumber = params.pageNumber ?? 1;\n const pageSize = params.pageSize ?? 50;\n const assignments = await this.ctx.http.request<Array<{ ref?: { id?: string; type?: string } }>>({\n method: \"GET\",\n path: `/category/${this.ctx.tenant}/categories/${categoryId}/assignments`,\n query: { pageNumber, pageSize },\n auth,\n });\n const categoryIds = assignments\n .map((a) => (a.ref?.type?.toUpperCase() === \"CATEGORY\" ? a.ref.id : undefined))\n .filter((id): id is string => Boolean(id));\n if (categoryIds.length === 0) return [];\n return this.searchByIds(categoryIds, {}, auth);\n }\n\n /**\n * One page of products in a category. The category service exposes products\n * as **assignments** (`/categories/{id}/assignments`) — references, not full\n * products — so this fetches a page of assignments, keeps the `PRODUCT`\n * references, and resolves them to full products via `/products/search`.\n * `hasNextPage` reflects the assignments page (the source of truth for\n * pagination).\n */\n async productsIn(\n categoryId: string,\n params: { pageNumber?: number; pageSize?: number } = {},\n auth: AuthContext = ANON,\n ): Promise<PaginatedItems<Product>> {\n const pageNumber = params.pageNumber ?? 1;\n const pageSize = params.pageSize ?? 50;\n const assignments = await this.ctx.http.request<Array<{ ref?: { id?: string; type?: string } }>>({\n method: \"GET\",\n path: `/category/${this.ctx.tenant}/categories/${categoryId}/assignments`,\n query: { pageNumber, pageSize },\n auth,\n });\n const hasNextPage = assignments.length === pageSize;\n const productIds = assignments\n .map((a) => (a.ref?.type?.toUpperCase() === \"PRODUCT\" ? a.ref.id : undefined))\n .filter((id): id is string => Boolean(id));\n if (productIds.length === 0) {\n return { items: [], pageNumber, pageSize, hasNextPage };\n }\n const items = await this.ctx.http.request<Product[]>({\n method: \"POST\",\n path: `/product/${this.ctx.tenant}/products/search`,\n query: { pageSize: productIds.length },\n auth,\n body: { q: `id:(${productIds.join(\",\")})` },\n });\n return { items, pageNumber, pageSize, hasNextPage };\n }\n\n /**\n * Bulk fetch by id. POSTs `/categories/search` with `q=\"id:(id1,id2,…)\"`,\n * chunking when the list is larger than `options.chunkSize` (default\n * 100). An empty list short-circuits with no HTTP call. **Order is not\n * guaranteed** across chunks — re-index by `id` if order matters.\n */\n async searchByIds(\n ids: string[],\n options: { chunkSize?: number } = {},\n auth: AuthContext = ANON,\n ): Promise<Category[]> {\n if (ids.length === 0) return [];\n const chunkSize = options.chunkSize ?? 100;\n const chunks: string[][] = [];\n for (let i = 0; i < ids.length; i += chunkSize) {\n chunks.push(ids.slice(i, i + chunkSize));\n }\n const pages = await Promise.all(\n chunks.map((chunk) =>\n this.ctx.http.request<Category[]>({\n method: \"POST\",\n path: `/category/${this.ctx.tenant}/categories/search`,\n query: { pageSize: chunk.length },\n auth,\n body: { q: `id:(${chunk.join(\",\")})` },\n }),\n ),\n );\n return pages.flat();\n }\n}\n"]}
@@ -292,9 +292,30 @@ declare class CategoryService {
292
292
  listAll(params?: {
293
293
  pageSize?: number;
294
294
  }, auth?: AuthContext): AsyncIterable<Category>;
295
- /** Fetches the category tree, optionally rooted at `rootId`. */
296
- tree(rootId?: string, auth?: AuthContext): Promise<CategoryNode>;
297
- /** One page of products in a category. */
295
+ /**
296
+ * The catalogue's **root categories** — the published category trees
297
+ * (`GET /category-trees`). Use these for top-level storefront navigation;
298
+ * drill into a node's children with {@link subcategories}.
299
+ */
300
+ tree(auth?: AuthContext): Promise<Category[]>;
301
+ /**
302
+ * Direct child categories of a category (for hierarchy drill-down). Mirrors
303
+ * {@link productsIn}: reads the category's **assignments** and keeps the
304
+ * `CATEGORY` references, resolving them to full categories. Returns an empty
305
+ * array when the category has no child categories.
306
+ */
307
+ subcategories(categoryId: string, params?: {
308
+ pageNumber?: number;
309
+ pageSize?: number;
310
+ }, auth?: AuthContext): Promise<Category[]>;
311
+ /**
312
+ * One page of products in a category. The category service exposes products
313
+ * as **assignments** (`/categories/{id}/assignments`) — references, not full
314
+ * products — so this fetches a page of assignments, keeps the `PRODUCT`
315
+ * references, and resolves them to full products via `/products/search`.
316
+ * `hasNextPage` reflects the assignments page (the source of truth for
317
+ * pagination).
318
+ */
298
319
  productsIn(categoryId: string, params?: {
299
320
  pageNumber?: number;
300
321
  pageSize?: number;
@@ -292,9 +292,30 @@ declare class CategoryService {
292
292
  listAll(params?: {
293
293
  pageSize?: number;
294
294
  }, auth?: AuthContext): AsyncIterable<Category>;
295
- /** Fetches the category tree, optionally rooted at `rootId`. */
296
- tree(rootId?: string, auth?: AuthContext): Promise<CategoryNode>;
297
- /** One page of products in a category. */
295
+ /**
296
+ * The catalogue's **root categories** — the published category trees
297
+ * (`GET /category-trees`). Use these for top-level storefront navigation;
298
+ * drill into a node's children with {@link subcategories}.
299
+ */
300
+ tree(auth?: AuthContext): Promise<Category[]>;
301
+ /**
302
+ * Direct child categories of a category (for hierarchy drill-down). Mirrors
303
+ * {@link productsIn}: reads the category's **assignments** and keeps the
304
+ * `CATEGORY` references, resolving them to full categories. Returns an empty
305
+ * array when the category has no child categories.
306
+ */
307
+ subcategories(categoryId: string, params?: {
308
+ pageNumber?: number;
309
+ pageSize?: number;
310
+ }, auth?: AuthContext): Promise<Category[]>;
311
+ /**
312
+ * One page of products in a category. The category service exposes products
313
+ * as **assignments** (`/categories/{id}/assignments`) — references, not full
314
+ * products — so this fetches a page of assignments, keeps the `PRODUCT`
315
+ * references, and resolves them to full products via `/products/search`.
316
+ * `hasNextPage` reflects the assignments page (the source of truth for
317
+ * pagination).
318
+ */
298
319
  productsIn(categoryId: string, params?: {
299
320
  pageNumber?: number;
300
321
  pageSize?: number;
package/dist/category.js CHANGED
@@ -1,4 +1,4 @@
1
- export { CategoryService } from './chunk-4BJUCCKJ.js';
1
+ export { CategoryService } from './chunk-AUVJ5V47.js';
2
2
  import './chunk-GWJ2U2CP.js';
3
3
  //# sourceMappingURL=category.js.map
4
4
  //# sourceMappingURL=category.js.map
@@ -32,26 +32,67 @@ var CategoryService = class {
32
32
  const pageSize = params.pageSize ?? 50;
33
33
  return iterateAll((pageNumber) => this.list({ pageNumber, pageSize }, auth));
34
34
  }
35
- /** Fetches the category tree, optionally rooted at `rootId`. */
36
- async tree(rootId, auth = ANON) {
35
+ /**
36
+ * The catalogue's **root categories** — the published category trees
37
+ * (`GET /category-trees`). Use these for top-level storefront navigation;
38
+ * drill into a node's children with {@link subcategories}.
39
+ */
40
+ async tree(auth = ANON) {
37
41
  return this.ctx.http.request({
38
42
  method: "GET",
39
- path: `/category/${this.ctx.tenant}/categories/tree`,
40
- query: rootId ? { rootId } : {},
43
+ path: `/category/${this.ctx.tenant}/category-trees`,
44
+ auth
45
+ });
46
+ }
47
+ /**
48
+ * Direct child categories of a category (for hierarchy drill-down). Mirrors
49
+ * {@link productsIn}: reads the category's **assignments** and keeps the
50
+ * `CATEGORY` references, resolving them to full categories. Returns an empty
51
+ * array when the category has no child categories.
52
+ */
53
+ async subcategories(categoryId, params = {}, auth = ANON) {
54
+ const pageNumber = params.pageNumber ?? 1;
55
+ const pageSize = params.pageSize ?? 50;
56
+ const assignments = await this.ctx.http.request({
57
+ method: "GET",
58
+ path: `/category/${this.ctx.tenant}/categories/${categoryId}/assignments`,
59
+ query: { pageNumber, pageSize },
41
60
  auth
42
61
  });
62
+ const categoryIds = assignments.map((a) => a.ref?.type?.toUpperCase() === "CATEGORY" ? a.ref.id : void 0).filter((id) => Boolean(id));
63
+ if (categoryIds.length === 0) return [];
64
+ return this.searchByIds(categoryIds, {}, auth);
43
65
  }
44
- /** One page of products in a category. */
66
+ /**
67
+ * One page of products in a category. The category service exposes products
68
+ * as **assignments** (`/categories/{id}/assignments`) — references, not full
69
+ * products — so this fetches a page of assignments, keeps the `PRODUCT`
70
+ * references, and resolves them to full products via `/products/search`.
71
+ * `hasNextPage` reflects the assignments page (the source of truth for
72
+ * pagination).
73
+ */
45
74
  async productsIn(categoryId, params = {}, auth = ANON) {
46
75
  const pageNumber = params.pageNumber ?? 1;
47
76
  const pageSize = params.pageSize ?? 50;
48
- const items = await this.ctx.http.request({
77
+ const assignments = await this.ctx.http.request({
49
78
  method: "GET",
50
- path: `/category/${this.ctx.tenant}/categories/${categoryId}/products`,
79
+ path: `/category/${this.ctx.tenant}/categories/${categoryId}/assignments`,
51
80
  query: { pageNumber, pageSize },
52
81
  auth
53
82
  });
54
- return { items, pageNumber, pageSize, hasNextPage: items.length === pageSize };
83
+ const hasNextPage = assignments.length === pageSize;
84
+ const productIds = assignments.map((a) => a.ref?.type?.toUpperCase() === "PRODUCT" ? a.ref.id : void 0).filter((id) => Boolean(id));
85
+ if (productIds.length === 0) {
86
+ return { items: [], pageNumber, pageSize, hasNextPage };
87
+ }
88
+ const items = await this.ctx.http.request({
89
+ method: "POST",
90
+ path: `/product/${this.ctx.tenant}/products/search`,
91
+ query: { pageSize: productIds.length },
92
+ auth,
93
+ body: { q: `id:(${productIds.join(",")})` }
94
+ });
95
+ return { items, pageNumber, pageSize, hasNextPage };
55
96
  }
56
97
  /**
57
98
  * Bulk fetch by id. POSTs `/categories/search` with `q="id:(id1,id2,…)"`,
@@ -82,5 +123,5 @@ var CategoryService = class {
82
123
  };
83
124
 
84
125
  export { CategoryService };
85
- //# sourceMappingURL=chunk-4BJUCCKJ.js.map
86
- //# sourceMappingURL=chunk-4BJUCCKJ.js.map
126
+ //# sourceMappingURL=chunk-AUVJ5V47.js.map
127
+ //# sourceMappingURL=chunk-AUVJ5V47.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/services/category.ts"],"names":[],"mappings":";;;AAMA,IAAM,IAAA,GAAoB,EAAE,IAAA,EAAM,WAAA,EAAY;AASvC,IAAM,kBAAN,MAAsB;AAAA,EAC3B,YAA6B,GAAA,EAAoB;AAApB,IAAA,IAAA,CAAA,GAAA,GAAA,GAAA;AAAA,EAAqB;AAAA,EAArB,GAAA;AAAA;AAAA,EAG7B,MAAM,GAAA,CAAI,UAAA,EAAoB,IAAA,GAAoB,IAAA,EAAyB;AACzE,IAAA,OAAO,IAAA,CAAK,GAAA,CAAI,IAAA,CAAK,OAAA,CAAkB;AAAA,MACrC,MAAA,EAAQ,KAAA;AAAA,MACR,MAAM,CAAA,UAAA,EAAa,IAAA,CAAK,GAAA,CAAI,MAAM,eAAe,UAAU,CAAA,CAAA;AAAA,MAC3D;AAAA,KACD,CAAA;AAAA,EACH;AAAA;AAAA,EAGA,MAAM,IAAA,CACJ,MAAA,GAAqD,EAAC,EACtD,OAAoB,IAAA,EACe;AACnC,IAAA,MAAM,UAAA,GA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CAAA,GAAI,GAAA,CAAI,MAAA,EAAQ,KAAK,SAAA,EAAW;AAC9C,MAAA,MAAA,CAAO,KAAK,GAAA,CAAI,KAAA,CAAM,CAAA,EAAG,CAAA,GAAI,SAAS,CAAC,CAAA;AAAA,IACzC;AACA,IAAA,MAAM,KAAA,GAAQ,MAAM,OAAA,CAAQ,GAAA;AAAA,MAC1B,MAAA,CAAO,GAAA;AAAA,QAAI,CAAC,KAAA,KACV,IAAA,CAAK,GAAA,CAAI,KAAK,OAAA,CAAoB;AAAA,UAChC,MAAA,EAAQ,MAAA;AAAA,UACR,IAAA,EAAM,CAAA,UAAA,EAAa,IAAA,CAAK,GAAA,CAAI,MAAM,CAAA,kBAAA,CAAA;AAAA,UAClC,KAAA,EAAO,EAAE,QAAA,EAAU,KAAA,CAAM,MAAA,EAAO;AAAA,UAChC,IAAA;AAAA,UACA,IAAA,EAAM,EAAE,CAAA,EAAG,CAAA,IAAA,EAAO,MAAM,IAAA,CAAK,GAAG,CAAC,CAAA,CAAA,CAAA;AAAI,SACtC;AAAA;AACH,KACF;AACA,IAAA,OAAO,MAAM,IAAA,EAAK;AAAA,EACpB;AACF","file":"chunk-AUVJ5V47.js","sourcesContent":["import type { ClientContext, PaginatedItems } from \"../core/context\";\nimport { iterateAll } from \"../core/context\";\nimport type { AuthContext } from \"../core/auth\";\nimport type { Product } from \"./product\";\nimport type { Category as GeneratedCategory, CategoryTree } from \"../generated/category\";\n\nconst ANON: AuthContext = { kind: \"anonymous\" };\n\n/** A category as returned by the Category service (all generated fields). */\nexport type Category = GeneratedCategory;\n\n/** The category tree as returned by the Category service. */\nexport type CategoryNode = CategoryTree;\n\n/** Category reads. Default auth: anonymous. */\nexport class CategoryService {\n constructor(private readonly ctx: ClientContext) {}\n\n /** Fetches one category by id. */\n async get(categoryId: string, auth: AuthContext = ANON): Promise<Category> {\n return this.ctx.http.request<Category>({\n method: \"GET\",\n path: `/category/${this.ctx.tenant}/categories/${categoryId}`,\n auth,\n });\n }\n\n /** One page of categories. */\n async list(\n params: { pageNumber?: number; pageSize?: number } = {},\n auth: AuthContext = ANON,\n ): Promise<PaginatedItems<Category>> {\n const pageNumber = params.pageNumber ?? 1;\n const pageSize = params.pageSize ?? 50;\n const items = await this.ctx.http.request<Category[]>({\n method: \"GET\",\n path: `/category/${this.ctx.tenant}/categories`,\n query: { pageNumber, pageSize },\n auth,\n });\n return { items, pageNumber, pageSize, hasNextPage: items.length === pageSize };\n }\n\n /** Async-iterates every category across pages. */\n listAll(params: { pageSize?: number } = {}, auth: AuthContext = ANON): AsyncIterable<Category> {\n const pageSize = params.pageSize ?? 50;\n return iterateAll<Category>((pageNumber) => this.list({ pageNumber, pageSize }, auth));\n }\n\n /**\n * The catalogue's **root categories** — the published category trees\n * (`GET /category-trees`). Use these for top-level storefront navigation;\n * drill into a node's children with {@link subcategories}.\n */\n async tree(auth: AuthContext = ANON): Promise<Category[]> {\n return this.ctx.http.request<Category[]>({\n method: \"GET\",\n path: `/category/${this.ctx.tenant}/category-trees`,\n auth,\n });\n }\n\n /**\n * Direct child categories of a category (for hierarchy drill-down). Mirrors\n * {@link productsIn}: reads the category's **assignments** and keeps the\n * `CATEGORY` references, resolving them to full categories. Returns an empty\n * array when the category has no child categories.\n */\n async subcategories(\n categoryId: string,\n params: { pageNumber?: number; pageSize?: number } = {},\n auth: AuthContext = ANON,\n ): Promise<Category[]> {\n const pageNumber = params.pageNumber ?? 1;\n const pageSize = params.pageSize ?? 50;\n const assignments = await this.ctx.http.request<Array<{ ref?: { id?: string; type?: string } }>>({\n method: \"GET\",\n path: `/category/${this.ctx.tenant}/categories/${categoryId}/assignments`,\n query: { pageNumber, pageSize },\n auth,\n });\n const categoryIds = assignments\n .map((a) => (a.ref?.type?.toUpperCase() === \"CATEGORY\" ? a.ref.id : undefined))\n .filter((id): id is string => Boolean(id));\n if (categoryIds.length === 0) return [];\n return this.searchByIds(categoryIds, {}, auth);\n }\n\n /**\n * One page of products in a category. The category service exposes products\n * as **assignments** (`/categories/{id}/assignments`) — references, not full\n * products — so this fetches a page of assignments, keeps the `PRODUCT`\n * references, and resolves them to full products via `/products/search`.\n * `hasNextPage` reflects the assignments page (the source of truth for\n * pagination).\n */\n async productsIn(\n categoryId: string,\n params: { pageNumber?: number; pageSize?: number } = {},\n auth: AuthContext = ANON,\n ): Promise<PaginatedItems<Product>> {\n const pageNumber = params.pageNumber ?? 1;\n const pageSize = params.pageSize ?? 50;\n const assignments = await this.ctx.http.request<Array<{ ref?: { id?: string; type?: string } }>>({\n method: \"GET\",\n path: `/category/${this.ctx.tenant}/categories/${categoryId}/assignments`,\n query: { pageNumber, pageSize },\n auth,\n });\n const hasNextPage = assignments.length === pageSize;\n const productIds = assignments\n .map((a) => (a.ref?.type?.toUpperCase() === \"PRODUCT\" ? a.ref.id : undefined))\n .filter((id): id is string => Boolean(id));\n if (productIds.length === 0) {\n return { items: [], pageNumber, pageSize, hasNextPage };\n }\n const items = await this.ctx.http.request<Product[]>({\n method: \"POST\",\n path: `/product/${this.ctx.tenant}/products/search`,\n query: { pageSize: productIds.length },\n auth,\n body: { q: `id:(${productIds.join(\",\")})` },\n });\n return { items, pageNumber, pageSize, hasNextPage };\n }\n\n /**\n * Bulk fetch by id. POSTs `/categories/search` with `q=\"id:(id1,id2,…)\"`,\n * chunking when the list is larger than `options.chunkSize` (default\n * 100). An empty list short-circuits with no HTTP call. **Order is not\n * guaranteed** across chunks — re-index by `id` if order matters.\n */\n async searchByIds(\n ids: string[],\n options: { chunkSize?: number } = {},\n auth: AuthContext = ANON,\n ): Promise<Category[]> {\n if (ids.length === 0) return [];\n const chunkSize = options.chunkSize ?? 100;\n const chunks: string[][] = [];\n for (let i = 0; i < ids.length; i += chunkSize) {\n chunks.push(ids.slice(i, i + chunkSize));\n }\n const pages = await Promise.all(\n chunks.map((chunk) =>\n this.ctx.http.request<Category[]>({\n method: \"POST\",\n path: `/category/${this.ctx.tenant}/categories/search`,\n query: { pageSize: chunk.length },\n auth,\n body: { q: `id:(${chunk.join(\",\")})` },\n }),\n ),\n );\n return pages.flat();\n }\n}\n"]}
@@ -88,13 +88,19 @@ var CartService = class {
88
88
  body: items
89
89
  });
90
90
  }
91
- /** Updates an item. */
92
- async updateItem(cartId, itemId, patch, auth) {
91
+ /**
92
+ * Updates an item. By default this is a **full replace** — the server expects
93
+ * the complete item (e.g. `itemYrn` + the `price` row). Pass
94
+ * `{ partial: true }` to send a **partial update** (`?partial=true`), e.g. a
95
+ * quantity-only change with just `{ quantity }`.
96
+ */
97
+ async updateItem(cartId, itemId, patch, auth, opts = {}) {
93
98
  return this.ctx.http.request({
94
99
  method: "PUT",
95
100
  path: `${this.base()}/${cartId}/items/${itemId}`,
96
101
  auth: requireCartAuth(auth),
97
- body: patch
102
+ body: patch,
103
+ ...opts.partial ? { query: { partial: "true" } } : {}
98
104
  });
99
105
  }
100
106
  /** Removes an item. */
@@ -167,5 +173,5 @@ var CartService = class {
167
173
  };
168
174
 
169
175
  export { CartService };
170
- //# sourceMappingURL=chunk-IEZHGU7F.js.map
171
- //# sourceMappingURL=chunk-IEZHGU7F.js.map
176
+ //# sourceMappingURL=chunk-I3YYGSN2.js.map
177
+ //# sourceMappingURL=chunk-I3YYGSN2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/services/cart.ts"],"names":[],"mappings":";;;AAiCA,SAAS,gBAAgB,IAAA,EAA4C;AACnE,EAAA,IAAI,SAAS,IAAA,CAAK,IAAA,KAAS,cAAc,IAAA,CAAK,IAAA,KAAS,cAAc,OAAO,IAAA;AAC5E,EAAA,MAAM,IAAI,sBAAA;AAAA,IACR;AAAA,GACF;AACF;AAEA,SAAS,oBAAoB,IAAA,EAA4C;AACvE,EAAA,IAAI,IAAA,IAAQ,IAAA,CAAK,IAAA,KAAS,UAAA,EAAY,OAAO,IAAA;AAC7C,EAAA,MAAM,IAAI,uBAAuB,wDAAwD,CAAA;AAC3F;AAGO,IAAM,cAAN,MAAkB;AAAA,EACvB,YAA6B,GAAA,EAAoB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A;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,MAAM,KAAA,CACJ,cAAA,EACA,gBAAA,EACA,IAAA,EACe;AACf,IAAA,OAAO,IAAA,CAAK,GAAA,CAAI,IAAA,CAAK,OAAA,CAAc;AAAA,MACjC,MAAA,EAAQ,MAAA;AAAA,MACR,MAAM,CAAA,EAAG,IAAA,CAAK,IAAA,EAAM,IAAI,cAAc,CAAA,MAAA,CAAA;AAAA,MACtC,IAAA,EAAM,oBAAoB,IAAI,CAAA;AAAA,MAC9B,IAAA,EAAM,EAAE,KAAA,EAAO,gBAAA;AAAiB,KACjC,CAAA;AAAA,EACH;AACF","file":"chunk-I3YYGSN2.js","sourcesContent":["import type { ClientContext } from \"../core/context\";\nimport type { AuthContext } from \"../core/auth\";\nimport { EmporixNotFoundError, EmporixValidationError } from \"../core/errors\";\nimport type {\n Cart as GeneratedCart,\n CreateCart,\n CreatedCart,\n CartItemRequest,\n UpdateCartItem,\n AddressRequest,\n BatchResponse as GeneratedBatchResponse,\n SingleBatchResponse as GeneratedSingleBatchResponse,\n} from \"../generated/cart\";\n\n/** A cart as returned by the Cart service (all generated fields). */\nexport type Cart = GeneratedCart;\n\n/** The cart-create response (`{ cartId, yrn }`, generated). */\nexport type CartCreated = CreatedCart;\n\n/** Generated request bodies (caller sends the exact wire shape). */\nexport type CreateCartInput = CreateCart;\nexport type CartItemInput = CartItemRequest;\nexport type CartItemUpdate = UpdateCartItem;\n\n/** Per-entry result of `addItemsBatch`. `status` is HTTP-style per entry (e.g. 201 = added, 4xx = failed). */\nexport type CartItemBatchEntry = GeneratedSingleBatchResponse;\n/** Response shape of `addItemsBatch` — one entry per input item, matching by `index`. */\nexport type CartItemsBatchResponse = GeneratedBatchResponse;\n\n/** An address payload for cart shipping/billing (generated). */\nexport type CartAddress = AddressRequest;\n\nfunction requireCartAuth(auth: AuthContext | undefined): AuthContext {\n if (auth && (auth.kind === \"customer\" || auth.kind === \"anonymous\")) return auth;\n throw new EmporixValidationError(\n \"CartService requires an explicit { kind: 'customer' } or { kind: 'anonymous' } AuthContext\",\n );\n}\n\nfunction requireCustomerAuth(auth: AuthContext | undefined): AuthContext {\n if (auth && auth.kind === \"customer\") return auth;\n throw new EmporixValidationError(\"cart.merge requires a { kind: 'customer' } AuthContext\");\n}\n\n/** Cart operations. Every method requires an explicit customer/anonymous context. */\nexport class CartService {\n constructor(private readonly ctx: ClientContext) {}\n\n private base(): string {\n return `/cart/${this.ctx.tenant}/carts`;\n }\n\n /** Creates a cart. */\n async create(\n input: CreateCartInput | undefined,\n auth: AuthContext,\n ): Promise<CartCreated> {\n return this.ctx.http.request<CartCreated>({\n method: \"POST\",\n path: this.base(),\n auth: requireCartAuth(auth),\n body: input ?? {},\n });\n }\n\n /** Fetches a cart by id. */\n async get(cartId: string, auth: AuthContext): Promise<Cart> {\n return this.ctx.http.request<Cart>({\n method: \"GET\",\n path: `${this.base()}/${cartId}`,\n auth: requireCartAuth(auth),\n });\n }\n\n /** Returns the current cart for the session, or null if none. */\n /**\n * Get the customer / anonymous cart matching the given criteria. Per Emporix:\n * uniqueness is defined by `siteCode` + `type` + `legalEntityId` +\n * (`customerId` derived from a customer token, or `sessionId` derived from an\n * anonymous token). With `create: true`, Emporix creates a new cart if none\n * matches.\n *\n * Returns `null` on 404 (no cart found and `create` was not set). All other\n * errors are propagated.\n */\n async getCurrent(\n auth: AuthContext,\n opts: { siteCode: string; type?: string; legalEntityId?: string; create?: boolean },\n ): Promise<Cart | null> {\n const query: Record<string, string | number> = { siteCode: opts.siteCode };\n if (opts.type !== undefined) query.type = opts.type;\n if (opts.legalEntityId !== undefined) query.legalEntityId = opts.legalEntityId;\n if (opts.create) query.create = \"true\";\n try {\n return await this.ctx.http.request<Cart>({\n method: \"GET\",\n path: this.base(),\n query,\n auth: requireCartAuth(auth),\n });\n } catch (e) {\n if (e instanceof EmporixNotFoundError) return null;\n throw e;\n }\n }\n\n /** Adds an item. */\n async addItem(\n cartId: string,\n item: CartItemInput,\n auth: AuthContext,\n ): Promise<Cart> {\n return this.ctx.http.request<Cart>({\n method: \"POST\",\n path: `${this.base()}/${cartId}/items`,\n auth: requireCartAuth(auth),\n body: item,\n });\n }\n\n /**\n * Adds multiple items in a single request via `POST /carts/{id}/itemsBatch`.\n * Server-side limit is 200 entries per call — callers handling larger sets\n * must chunk. The response carries a per-entry `status` (HTTP-style: 201\n * for added, 4xx/5xx for failed) and `index` matching the input position;\n * partial failures do **not** throw — inspect `status` per entry.\n */\n async addItemsBatch(\n cartId: string,\n items: CartItemInput[],\n auth: AuthContext,\n ): Promise<CartItemsBatchResponse> {\n return this.ctx.http.request<CartItemsBatchResponse>({\n method: \"POST\",\n path: `${this.base()}/${cartId}/itemsBatch`,\n auth: requireCartAuth(auth),\n body: items,\n });\n }\n\n /**\n * Updates an item. By default this is a **full replace** — the server expects\n * the complete item (e.g. `itemYrn` + the `price` row). Pass\n * `{ partial: true }` to send a **partial update** (`?partial=true`), e.g. a\n * quantity-only change with just `{ quantity }`.\n */\n async updateItem(\n cartId: string,\n itemId: string,\n patch: CartItemUpdate,\n auth: AuthContext,\n opts: { partial?: boolean } = {},\n ): Promise<Cart> {\n return this.ctx.http.request<Cart>({\n method: \"PUT\",\n path: `${this.base()}/${cartId}/items/${itemId}`,\n auth: requireCartAuth(auth),\n body: patch,\n ...(opts.partial ? { query: { partial: \"true\" } } : {}),\n });\n }\n\n /** Removes an item. */\n async removeItem(cartId: string, itemId: string, auth: AuthContext): Promise<Cart> {\n return this.ctx.http.request<Cart>({\n method: \"DELETE\",\n path: `${this.base()}/${cartId}/items/${itemId}`,\n auth: requireCartAuth(auth),\n });\n }\n\n /** Empties the cart. */\n async clear(cartId: string, auth: AuthContext): Promise<Cart> {\n return this.ctx.http.request<Cart>({\n method: \"DELETE\",\n path: `${this.base()}/${cartId}/items`,\n auth: requireCartAuth(auth),\n });\n }\n\n /** Applies a coupon. */\n async applyCoupon(cartId: string, code: string, auth: AuthContext): Promise<Cart> {\n return this.ctx.http.request<Cart>({\n method: \"POST\",\n path: `${this.base()}/${cartId}/coupons`,\n auth: requireCartAuth(auth),\n body: { code },\n });\n }\n\n /** Removes a coupon. */\n async removeCoupon(cartId: string, code: string, auth: AuthContext): Promise<Cart> {\n return this.ctx.http.request<Cart>({\n method: \"DELETE\",\n path: `${this.base()}/${cartId}/coupons/${code}`,\n auth: requireCartAuth(auth),\n });\n }\n\n /** Sets the shipping address. */\n async setShippingAddress(\n cartId: string,\n address: CartAddress,\n auth: AuthContext,\n ): Promise<Cart> {\n return this.ctx.http.request<Cart>({\n method: \"PUT\",\n path: `${this.base()}/${cartId}/shipping-address`,\n auth: requireCartAuth(auth),\n body: address,\n });\n }\n\n /** Sets the billing address. */\n async setBillingAddress(\n cartId: string,\n address: CartAddress,\n auth: AuthContext,\n ): Promise<Cart> {\n return this.ctx.http.request<Cart>({\n method: \"PUT\",\n path: `${this.base()}/${cartId}/billing-address`,\n auth: requireCartAuth(auth),\n body: address,\n });\n }\n\n /**\n * Merges one or more anonymous carts into the specified customer cart.\n * Per Emporix: the target cart in the path **must belong to the logged-in\n * customer**, and each id in `anonymousCartIds` must belong to an anonymous\n * customer. Anonymous carts go `CLOSED` on success.\n *\n * Requires a customer `AuthContext`.\n */\n async merge(\n customerCartId: string,\n anonymousCartIds: string[],\n auth: AuthContext,\n ): Promise<Cart> {\n return this.ctx.http.request<Cart>({\n method: \"POST\",\n path: `${this.base()}/${customerCartId}/merge`,\n auth: requireCustomerAuth(auth),\n body: { carts: anonymousCartIds },\n });\n }\n}\n"]}