@shopkit/data-layer 1.7.0 → 1.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.
@@ -306,6 +306,16 @@ var BaseCommerceClient = class {
306
306
  queryCollections(params, options) {
307
307
  this.throwNotImplemented("queryCollections");
308
308
  }
309
+ /**
310
+ * Read a page of a collection's products, with one card per matching variant
311
+ * @param params - Handle plus page/per_page, sort, filter, fields
312
+ * @param options - Request options (headers, timeout, etc.)
313
+ * @returns Promise resolving to a VariantCardsPageDto
314
+ * @throws NotImplementedError if not implemented in adapter (custom backend only)
315
+ */
316
+ getCollectionVariantCards(params, options) {
317
+ this.throwNotImplemented("getCollectionVariantCards");
318
+ }
309
319
  // ========================================
310
320
  // ORDER OPERATIONS
311
321
  // ========================================
@@ -3805,7 +3815,8 @@ var PRODUCT_ENDPOINTS = {
3805
3815
  getCollectionById: (v = DEFAULT_VERSION, id) => `/api/${v}/collections/${encodeURIComponent(id)}`,
3806
3816
  getCollectionsByHandles: (v = DEFAULT_VERSION) => `/api/${v}/collections/details`,
3807
3817
  getCollectionFilters: (v = DEFAULT_VERSION, collectionHandle) => `/api/${v}/storefront/collections/${encodeURIComponent(collectionHandle)}/filters`,
3808
- queryCollections: (v = DEFAULT_VERSION) => `/api/${v}/collections/query`
3818
+ queryCollections: (v = DEFAULT_VERSION) => `/api/${v}/collections/query`,
3819
+ collectionVariants: (v = DEFAULT_VERSION, handle) => `/api/${v}/collections/${encodeURIComponent(handle)}/variants`
3809
3820
  };
3810
3821
 
3811
3822
  // src/adapters/custom/product/service.ts
@@ -4470,7 +4481,268 @@ var ProductService2 = class extends BaseCustomService {
4470
4481
  });
4471
4482
  }
4472
4483
  }
4484
+ /**
4485
+ * A page of a collection's products, with one card per matching variant
4486
+ * (POST /api/v1/collections/{handle}/variants). A POST because filters are
4487
+ * nested; it is still a read and answers 200.
4488
+ *
4489
+ * With `allVariants: true`, follows `next_cursor` (same body + `after`,
4490
+ * 100 cards per call) and returns the whole page's variants in one result.
4491
+ * The result is complete or it is a failure — never a partial page, which
4492
+ * would be cached as if it were complete. It fails (`UPSTREAM_UNAVAILABLE`)
4493
+ * when a follow-up call fails, when the cursor repeats, or when the page is
4494
+ * not done within ALL_VARIANTS_MAX_CALLS calls or ALL_VARIANTS_DEADLINE_MS.
4495
+ */
4496
+ async getCollectionVariantCards(params, options) {
4497
+ const handle = typeof params?.handle === "string" ? params.handle.trim() : "";
4498
+ if (!handle) {
4499
+ return formatResponse({
4500
+ success: false,
4501
+ message: "Missing required variable: 'handle'",
4502
+ error: {
4503
+ code: "QUERY_REJECTED",
4504
+ message: "handle: is required"
4505
+ }
4506
+ });
4507
+ }
4508
+ if (handle.includes("/") || handle === "." || handle === "..") {
4509
+ return formatResponse({
4510
+ success: false,
4511
+ message: "Collection not found.",
4512
+ error: {
4513
+ code: "NOT_FOUND",
4514
+ message: `No collection with handle ${handle}`
4515
+ }
4516
+ });
4517
+ }
4518
+ const payload = buildCollectionVariantsPayload(params);
4519
+ const requestOptions = {
4520
+ ...options || {},
4521
+ // Same coverage as queryCollections: the broad tag for catalog-wide
4522
+ // purges plus the collection's own, which product.updated /
4523
+ // collection.updated webhooks already purge. No `revalidate`.
4524
+ next: {
4525
+ ...options?.next || {},
4526
+ tags: [
4527
+ CacheTags.collections(),
4528
+ CacheTags.collection(handle),
4529
+ ...options?.next?.tags || []
4530
+ ]
4531
+ }
4532
+ };
4533
+ const endpoint = PRODUCT_ENDPOINTS.collectionVariants(
4534
+ options?.version,
4535
+ handle
4536
+ );
4537
+ const allVariants = params.allVariants === true;
4538
+ const deadline = allVariants ? AbortSignal.timeout(ALL_VARIANTS_DEADLINE_MS) : void 0;
4539
+ const callOptions = () => deadline ? {
4540
+ ...requestOptions,
4541
+ signal: anySignal([
4542
+ deadline,
4543
+ options?.signal ?? AbortSignal.timeout(options?.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS)
4544
+ ])
4545
+ } : requestOptions;
4546
+ let followUp = false;
4547
+ try {
4548
+ let result = await this.request(endpoint, "POST", payload, callOptions());
4549
+ if (!result?.data) return noVariantCardsData(result?.request_id);
4550
+ const page = {
4551
+ ...result.data,
4552
+ variants: Array.isArray(result.data.variants) ? result.data.variants : []
4553
+ };
4554
+ const errors = Array.isArray(result.errors) ? [...result.errors] : [];
4555
+ if (allVariants) {
4556
+ followUp = true;
4557
+ const variants = [];
4558
+ const seenIds = /* @__PURE__ */ new Set();
4559
+ const addCards = (cards) => {
4560
+ for (const card of Array.isArray(cards) ? cards : []) {
4561
+ if (typeof card?.id === "string") {
4562
+ if (seenIds.has(card.id)) continue;
4563
+ seenIds.add(card.id);
4564
+ }
4565
+ variants.push(card);
4566
+ }
4567
+ };
4568
+ addCards(page.variants);
4569
+ const seenCursors = new Set(
4570
+ typeof payload.after === "string" ? [payload.after] : []
4571
+ );
4572
+ let cursor = page.next_cursor;
4573
+ let calls = 1;
4574
+ while (cursor) {
4575
+ if (seenCursors.has(cursor)) {
4576
+ return incompleteVariantCards(
4577
+ "the backend returned a cursor it had already sent",
4578
+ result.request_id,
4579
+ this.logger
4580
+ );
4581
+ }
4582
+ if (calls >= ALL_VARIANTS_MAX_CALLS) {
4583
+ return incompleteVariantCards(
4584
+ `the page has more cards than ${ALL_VARIANTS_MAX_CALLS} calls of ${MAX_VARIANT_CARDS_PER_CALL} hold`,
4585
+ result.request_id,
4586
+ this.logger
4587
+ );
4588
+ }
4589
+ seenCursors.add(cursor);
4590
+ result = await this.request(
4591
+ endpoint,
4592
+ "POST",
4593
+ { ...payload, after: cursor },
4594
+ callOptions()
4595
+ );
4596
+ calls++;
4597
+ if (!result?.data) return noVariantCardsData(result?.request_id);
4598
+ addCards(result.data.variants);
4599
+ if (Array.isArray(result.errors)) errors.push(...result.errors);
4600
+ cursor = result.data.next_cursor;
4601
+ }
4602
+ page.variants = variants;
4603
+ page.next_cursor = null;
4604
+ }
4605
+ const distinctErrors = dedupeErrors(errors);
4606
+ return formatResponse({
4607
+ success: true,
4608
+ message: "Collection variants retrieved successfully.",
4609
+ data: page,
4610
+ meta: {
4611
+ requestId: result.request_id,
4612
+ ...distinctErrors.length > 0 ? { errors: distinctErrors } : {}
4613
+ }
4614
+ });
4615
+ } catch (error) {
4616
+ this.logger.error("Error in getCollectionVariantCards", void 0, {
4617
+ error
4618
+ });
4619
+ const body = error?.body;
4620
+ if (deadline?.aborted) {
4621
+ return incompleteVariantCards(
4622
+ `the page was not complete within ${ALL_VARIANTS_DEADLINE_MS / 1e3}s`,
4623
+ body?.request_id,
4624
+ this.logger
4625
+ );
4626
+ }
4627
+ if (isUpstreamUnavailable(error)) {
4628
+ return formatResponse({
4629
+ success: false,
4630
+ message: "An error occurred while processing the request.",
4631
+ error: {
4632
+ code: "UPSTREAM_UNAVAILABLE",
4633
+ message: typeof error?.status === "number" ? `Request failed: ${error.status}` : "Collection variants request did not complete."
4634
+ },
4635
+ meta: { requestId: body?.request_id }
4636
+ });
4637
+ }
4638
+ const upstreamErrors = Array.isArray(body?.errors) ? body.errors : [];
4639
+ if (error?.status === 404) {
4640
+ if (!followUp && upstreamErrors[0]?.code === "NOT_FOUND") {
4641
+ return formatResponse({
4642
+ success: false,
4643
+ message: "Collection not found.",
4644
+ error: {
4645
+ code: "NOT_FOUND",
4646
+ message: upstreamErrors[0]?.message || `No collection with handle ${handle}`
4647
+ },
4648
+ meta: { requestId: body?.request_id }
4649
+ });
4650
+ }
4651
+ return formatResponse({
4652
+ success: false,
4653
+ message: "An error occurred while processing the request.",
4654
+ error: {
4655
+ code: "UPSTREAM_UNAVAILABLE",
4656
+ message: "Request failed: 404"
4657
+ },
4658
+ meta: { requestId: body?.request_id }
4659
+ });
4660
+ }
4661
+ return formatResponse({
4662
+ success: false,
4663
+ message: "The collection variants request was rejected.",
4664
+ error: {
4665
+ code: "QUERY_REJECTED",
4666
+ message: upstreamErrors[0]?.message || error.message,
4667
+ details: upstreamErrors
4668
+ },
4669
+ meta: { requestId: body?.request_id }
4670
+ });
4671
+ }
4672
+ }
4473
4673
  };
4674
+ function incompleteVariantCards(reason, requestId, logger2) {
4675
+ logger2.warn(`getCollectionVariantCards allVariants incomplete: ${reason}`);
4676
+ return formatResponse({
4677
+ success: false,
4678
+ message: "Collection variants page is incomplete.",
4679
+ error: {
4680
+ code: "UPSTREAM_UNAVAILABLE",
4681
+ message: `allVariants: ${reason}; not returning a partial page.`
4682
+ },
4683
+ meta: { requestId }
4684
+ });
4685
+ }
4686
+ function dedupeErrors(errors) {
4687
+ const seen = /* @__PURE__ */ new Set();
4688
+ return errors.filter((e) => {
4689
+ const err = e;
4690
+ const key = JSON.stringify([err?.code, err?.message]);
4691
+ if (seen.has(key)) return false;
4692
+ seen.add(key);
4693
+ return true;
4694
+ });
4695
+ }
4696
+ function anySignal(signals) {
4697
+ const controller = new AbortController();
4698
+ for (const signal of signals) {
4699
+ if (signal.aborted) {
4700
+ controller.abort(signal.reason);
4701
+ break;
4702
+ }
4703
+ signal.addEventListener("abort", () => controller.abort(signal.reason), {
4704
+ once: true
4705
+ });
4706
+ }
4707
+ return controller.signal;
4708
+ }
4709
+ function noVariantCardsData(requestId) {
4710
+ return formatResponse({
4711
+ success: false,
4712
+ message: "Collection variants request returned no data.",
4713
+ error: {
4714
+ code: "UPSTREAM_UNAVAILABLE",
4715
+ message: "No data in collection variants response."
4716
+ },
4717
+ meta: { requestId }
4718
+ });
4719
+ }
4720
+ var COLLECTION_VARIANTS_KEYS = [
4721
+ "filter",
4722
+ "fields",
4723
+ "product",
4724
+ "sort",
4725
+ "page",
4726
+ "per_page",
4727
+ "limit",
4728
+ "after",
4729
+ "ratings",
4730
+ "metafields"
4731
+ ];
4732
+ var MAX_VARIANT_CARDS_PER_CALL = 100;
4733
+ var ALL_VARIANTS_MAX_CALLS = 20;
4734
+ var ALL_VARIANTS_DEADLINE_MS = 15e3;
4735
+ function buildCollectionVariantsPayload(params) {
4736
+ const source = params || {};
4737
+ const payload = {};
4738
+ for (const key of COLLECTION_VARIANTS_KEYS) {
4739
+ if (source[key] !== void 0) payload[key] = source[key];
4740
+ }
4741
+ if (source.allVariants === true) {
4742
+ payload.limit = MAX_VARIANT_CARDS_PER_CALL;
4743
+ }
4744
+ return payload;
4745
+ }
4474
4746
  var COLLECTIONS_QUERY_KEYS = [
4475
4747
  "filter",
4476
4748
  "fields",
@@ -5112,6 +5384,12 @@ var CustomBackendClient = class extends BaseCommerceClient {
5112
5384
  filterRestOptions(options)
5113
5385
  );
5114
5386
  }
5387
+ async getCollectionVariantCards(params, options) {
5388
+ return this.productService.getCollectionVariantCards(
5389
+ params,
5390
+ filterRestOptions(options)
5391
+ );
5392
+ }
5115
5393
  // ========================================
5116
5394
  // CART OPERATIONS
5117
5395
  // ========================================