@01.software/sdk 0.30.1 → 0.32.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.
Files changed (56) hide show
  1. package/README.md +160 -48
  2. package/dist/analytics/react.cjs.map +1 -1
  3. package/dist/analytics/react.js.map +1 -1
  4. package/dist/analytics.cjs.map +1 -1
  5. package/dist/analytics.js.map +1 -1
  6. package/dist/client.cjs +91 -62
  7. package/dist/client.cjs.map +1 -1
  8. package/dist/client.d.cts +6 -6
  9. package/dist/client.d.ts +6 -6
  10. package/dist/client.js +91 -62
  11. package/dist/client.js.map +1 -1
  12. package/dist/{collection-client-QPbwimkU.d.cts → collection-client-CORhppPb.d.cts} +3 -3
  13. package/dist/{collection-client-B9d9kr1d.d.ts → collection-client-DPGXnhoF.d.ts} +3 -3
  14. package/dist/{const-VZuk2tWc.d.cts → const-Brk2Ff0q.d.cts} +4 -4
  15. package/dist/{const-B75IFDRi.d.ts → const-DcY2_z9O.d.ts} +4 -4
  16. package/dist/{index-B2WbhEgT.d.cts → index-BGEhoDUs.d.cts} +1 -1
  17. package/dist/{index-B2WbhEgT.d.ts → index-BGEhoDUs.d.ts} +1 -1
  18. package/dist/index.cjs +214 -66
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.cts +9 -9
  21. package/dist/index.d.ts +9 -9
  22. package/dist/index.js +214 -66
  23. package/dist/index.js.map +1 -1
  24. package/dist/{payload-types-DPjO_IbQ.d.cts → payload-types-DVK1QCeU.d.cts} +793 -531
  25. package/dist/{payload-types-DPjO_IbQ.d.ts → payload-types-DVK1QCeU.d.ts} +793 -531
  26. package/dist/query.cjs +63 -13
  27. package/dist/query.cjs.map +1 -1
  28. package/dist/query.d.cts +17 -17
  29. package/dist/query.d.ts +17 -17
  30. package/dist/query.js +63 -13
  31. package/dist/query.js.map +1 -1
  32. package/dist/realtime.cjs.map +1 -1
  33. package/dist/realtime.d.cts +2 -2
  34. package/dist/realtime.d.ts +2 -2
  35. package/dist/realtime.js.map +1 -1
  36. package/dist/server.cjs +176 -18
  37. package/dist/server.cjs.map +1 -1
  38. package/dist/server.d.cts +124 -7
  39. package/dist/server.d.ts +124 -7
  40. package/dist/server.js +176 -18
  41. package/dist/server.js.map +1 -1
  42. package/dist/{types-BwT0eeaz.d.cts → types-ByMrR_Z_.d.cts} +6 -2
  43. package/dist/{types-DuSKPiY5.d.ts → types-CAkWqIr6.d.cts} +82 -9
  44. package/dist/{types-Dlb2mwpX.d.cts → types-CYMSBkJC.d.ts} +82 -9
  45. package/dist/{types-1fBLrYU7.d.ts → types-DUPC7Xn6.d.ts} +6 -2
  46. package/dist/ui/form.d.cts +1 -1
  47. package/dist/ui/form.d.ts +1 -1
  48. package/dist/ui/video.d.cts +1 -1
  49. package/dist/ui/video.d.ts +1 -1
  50. package/dist/webhook.cjs +48 -1
  51. package/dist/webhook.cjs.map +1 -1
  52. package/dist/webhook.d.cts +73 -4
  53. package/dist/webhook.d.ts +73 -4
  54. package/dist/webhook.js +48 -1
  55. package/dist/webhook.js.map +1 -1
  56. package/package.json +3 -3
@@ -1,4 +1,4 @@
1
- import { C as CustomerProfile, a as CustomerProfileList, P as Post, b as Comment, R as Reaction, c as Config } from './payload-types-DPjO_IbQ.cjs';
1
+ import { P as Product, C as CustomerProfile, a as CustomerProfileList, b as ProductCollection, c as Post, d as Comment, R as Reaction, e as Config } from './payload-types-DVK1QCeU.cjs';
2
2
 
3
3
  type PublicCustomerProfile = Omit<CustomerProfile, 'tenant' | 'customer' | 'isPublic' | 'anonymizedAt' | 'metadata'>;
4
4
  type PublicProfileRelation = string | PublicCustomerProfile;
@@ -27,13 +27,17 @@ type PublicComment = Omit<Comment, 'authorProfile'> & {
27
27
  type PublicReaction = Omit<Reaction, 'actorProfile'> & {
28
28
  actorProfile: PublicProfileRelation;
29
29
  };
30
+ type PublicProduct = Omit<Product, 'collectionItems'>;
31
+ type PublicProductCollection = Omit<ProductCollection, 'items'>;
30
32
  type PublicCollectionOverrides = {
31
33
  'customer-profiles': PublicCustomerProfile;
32
34
  'customer-profile-lists': PublicCustomerProfileList;
35
+ products: PublicProduct;
36
+ 'product-collections': PublicProductCollection;
33
37
  posts: PublicPost;
34
38
  comments: PublicComment;
35
39
  reactions: PublicReaction;
36
40
  };
37
41
  type CollectionType<T extends string> = T extends keyof PublicCollectionOverrides ? PublicCollectionOverrides[T] : T extends keyof Config['collections'] ? Config['collections'][T] : never;
38
42
 
39
- export type { CollectionType as C };
43
+ export type { CollectionType as C, PublicProduct as P, PublicProductCollection as a };
@@ -1,6 +1,6 @@
1
- import { P as PublicCollection } from './const-B75IFDRi.js';
2
- import { C as CollectionType } from './types-1fBLrYU7.js';
3
- import { O as Order, h as Cart, i as CartItem, d as Product, l as OrderItem, m as Transaction, n as Fulfillment, o as Return } from './payload-types-DPjO_IbQ.js';
1
+ import { P as PublicCollection } from './const-Brk2Ff0q.cjs';
2
+ import { P as PublicProduct, C as CollectionType } from './types-ByMrR_Z_.cjs';
3
+ import { O as Order, i as Cart, j as CartItem, m as Transaction, n as Fulfillment, o as Return } from './payload-types-DVK1QCeU.cjs';
4
4
 
5
5
  interface CommunityClientOptions {
6
6
  publishableKey?: string;
@@ -488,6 +488,31 @@ type ProductListingGroup<TVariant extends ProductVariantShape = ProductVariantSh
488
488
  variants: TVariant[];
489
489
  listing: ProductListingProjection;
490
490
  };
491
+ type ProductListingCardPriceRange = {
492
+ minPrice: number | null;
493
+ maxPrice: number | null;
494
+ minCompareAtPrice: number | null;
495
+ maxCompareAtPrice: number | null;
496
+ isPriceRange: boolean;
497
+ };
498
+ type ProductListingSwatch = {
499
+ optionId: EntityID;
500
+ optionValueId: EntityID;
501
+ label: string;
502
+ swatchColor: string | null;
503
+ thumbnail: ProductDetailMedia | null;
504
+ href: string;
505
+ availableForSale: boolean;
506
+ };
507
+ type ProductListingCard = {
508
+ id: EntityID;
509
+ href: string;
510
+ title: string;
511
+ primaryImage: ProductDetailMedia | null;
512
+ priceRange: ProductListingCardPriceRange;
513
+ availableForSale: boolean;
514
+ swatches: ProductListingSwatch[];
515
+ };
491
516
  type ProductSelectionByOptionValue = string | number | null | undefined | {
492
517
  valueId?: string | number | null;
493
518
  valueSlug?: string | null;
@@ -614,6 +639,10 @@ type ProductHrefOptions = {
614
639
  };
615
640
  declare function buildProductHref(product: ProductHrefProduct, group?: ProductHrefGroup | null, options?: ProductHrefOptions): string;
616
641
  declare function buildProductListingProjection(product: ProductListingProductShape | null | undefined, variants: ProductVariantShape[]): ProductListingProjection;
642
+ declare function buildProductListingCard(item: ProductListingGroupsItem, options?: {
643
+ basePath?: string;
644
+ trailingSlash?: boolean;
645
+ }): ProductListingCard;
617
646
  /**
618
647
  * Builds product-first listing groups for one primary option.
619
648
  *
@@ -637,8 +666,10 @@ type StockCheckParams = {
637
666
  };
638
667
  type StockCheckResult = {
639
668
  variantId: string;
669
+ status: 'available' | 'not_published' | 'archived' | 'not_found';
640
670
  available: boolean;
641
671
  availableStock: number;
672
+ isUnlimited: boolean;
642
673
  requestedQuantity: number;
643
674
  error?: string;
644
675
  };
@@ -649,20 +680,45 @@ type StockCheckResponse = {
649
680
  type ListingGroupsParams = {
650
681
  productIds: string[];
651
682
  };
652
- type ProductListingGroupSummary = Omit<ProductListingGroup, 'variants'>;
683
+ type ListingGroupingState = 'grouped' | 'no_primary_option' | 'empty';
684
+ type ProductListingGroupVariant = Pick<ProductVariantShape, 'id' | 'optionValues' | 'price' | 'compareAtPrice' | 'stock' | 'isUnlimited' | 'isActive' | 'thumbnail' | 'images' | '_order'>;
685
+ type ProductListingGroupSummary = ProductListingGroup<ProductListingGroupVariant>;
686
+ type ProductListingGroupsProductVariants = NonNullable<PublicProduct['variants']>;
687
+ type ProductListingGroupsProduct = Omit<PublicProduct, 'variants'> & {
688
+ id: string;
689
+ slug: string;
690
+ title: string;
691
+ variants?: (Omit<ProductListingGroupsProductVariants, 'docs'> & {
692
+ docs: ProductListingGroupVariant[];
693
+ }) | null;
694
+ };
653
695
  type ProductListingGroupsItem = {
654
- product: Product;
696
+ product: ProductListingGroupsProduct;
655
697
  primaryOptionId: string | null;
698
+ listingGroupingState: ListingGroupingState;
656
699
  groups: ProductListingGroupSummary[];
657
700
  };
658
701
  type ProductListingGroupsResponse = {
702
+ /**
703
+ * Matching products in the same order as the requested productIds, excluding
704
+ * ids that were not found, not published, or not accessible for the current
705
+ * tenant/key.
706
+ */
659
707
  docs: ProductListingGroupsItem[];
708
+ /** Requested productIds that could not be returned. */
709
+ missing: string[];
660
710
  };
661
711
  type ProductDetailParams = {
662
712
  slug: string;
663
713
  } | {
664
714
  id: string;
665
715
  };
716
+ type ProductDetailPreviewParams = {
717
+ id: string;
718
+ };
719
+ type ProductDetailPreviewOptions = {
720
+ previewToken: string;
721
+ };
666
722
  interface ProductDetailVariantOptionValue {
667
723
  optionId: string | number;
668
724
  optionSlug: string;
@@ -815,7 +871,7 @@ type ProductUpsertParams = {
815
871
  };
816
872
  type ProductUpsertResponse = {
817
873
  ok: true;
818
- product: Product;
874
+ product: PublicProduct;
819
875
  } | {
820
876
  ok: false;
821
877
  failedEntity: 'product' | 'option' | 'option-value' | 'variant';
@@ -834,7 +890,7 @@ declare class ProductApi extends BaseApi {
834
890
  /**
835
891
  * Fetch full product detail by slug or id.
836
892
  * Returns `null` on 404 regardless of reason (`not_found` / `not_published` /
837
- * `tenant_mismatch` / `feature_disabled`). For the reason behind a null,
893
+ * `feature_disabled`). For the reason behind a null,
838
894
  * inspect `client.lastRequestId` against backend logs.
839
895
  */
840
896
  detail(params: ProductDetailParams): Promise<ProductDetail | null>;
@@ -896,12 +952,29 @@ type ReturnItem = {
896
952
  orderItem: string;
897
953
  quantity: number;
898
954
  };
955
+ type OrderCreateEntityID = string | number;
956
+ type CreateOrderItem = {
957
+ product: OrderCreateEntityID;
958
+ variant: OrderCreateEntityID;
959
+ option: OrderCreateEntityID;
960
+ quantity: number;
961
+ /**
962
+ * Compatibility input: the create-order endpoint accepts this, but the server
963
+ * derives authoritative line pricing from the product variant.
964
+ */
965
+ unitPrice?: number;
966
+ /**
967
+ * Compatibility input: the create-order endpoint accepts this, but the server
968
+ * derives authoritative line totals from the product variant.
969
+ */
970
+ totalPrice?: number;
971
+ };
899
972
  type CreateOrderParams = {
900
973
  orderNumber: string;
901
974
  customer?: string;
902
975
  customerSnapshot: CustomerSnapshot;
903
976
  shippingAddress: Order['shippingAddress'];
904
- orderItems: Pick<OrderItem, 'product' | 'variant' | 'quantity' | 'unitPrice' | 'totalPrice'>[];
977
+ orderItems: CreateOrderItem[];
905
978
  totalAmount: number;
906
979
  shippingAmount?: number;
907
980
  pgPaymentId?: string;
@@ -1246,4 +1319,4 @@ type DeepPartial<T> = {
1246
1319
  };
1247
1320
  type ExtractArrayType<T> = T extends (infer U)[] ? U : never;
1248
1321
 
1249
- export { type OrderApiOptions as $, type ApiQueryOptions as A, BaseApi as B, CommerceClient as C, type DebugConfig as D, type ExtractArrayType as E, type CreateFulfillmentParams as F, type CreateOrderParams as G, type CreateReturnParams as H, CustomerAuth as I, type CustomerAuthOptions as J, type CustomerAuthResponse as K, type CustomerLoginData as L, type CustomerProfile as M, type CustomerRefreshResponse as N, type CustomerRegisterData as O, type PayloadFindResponse as P, type CustomerRegisterResponse as Q, type RetryConfig as R, type Sort as S, type CustomerSnapshot as T, DiscountApi as U, type DiscountApiOptions as V, type Where as W, type LegacyProductSelectionParamEvent as X, type ListingGroupsParams as Y, type NormalizedProductSelection as Z, OrderApi as _, CommunityClient as a, buildProductOptionMatrixFromDetail as a$, ProductApi as a0, type ProductApiOptions as a1, type ProductDetail as a2, type ProductDetailBrand as a3, type ProductDetailCategory as a4, type ProductDetailImage as a5, type ProductDetailImageMedia as a6, type ProductDetailListing as a7, type ProductDetailMedia as a8, type ProductDetailOption as a9, type ProductSelectionResolution as aA, type ProductSelectionResolutionContext as aB, type ProductVariantShape as aC, type RemoveDiscountParams as aD, type RemoveItemParams as aE, type RequestOptions as aF, type ReturnItem as aG, type ReturnReason as aH, type ReturnWithRefundParams as aI, type ServerApiOptions as aJ, ShippingApi as aK, type ShippingApiOptions as aL, type StockCheckParams as aM, type StockCheckResponse as aN, type StockCheckResult as aO, type UpdateFulfillmentParams as aP, type UpdateItemParams as aQ, type UpdateOrderParams as aR, type UpdateProfileData as aS, type UpdateReturnParams as aT, type UpdateTransactionParams as aU, type ValidateDiscountParams as aV, type ValidateDiscountResult as aW, buildProductHref as aX, buildProductListingGroupsByOption as aY, buildProductListingProjection as aZ, buildProductOptionMatrix as a_, type ProductDetailOptionValue as aa, type ProductDetailParams as ab, type ProductDetailTag as ac, type ProductDetailVariant as ad, type ProductDetailVariantOptionValue as ae, type ProductDetailVideo as af, type ProductHrefGroup as ag, type ProductHrefOptions as ah, type ProductHrefProduct as ai, type ProductListingGroup as aj, type ProductListingGroupSummary as ak, type ProductListingGroupsItem as al, type ProductListingGroupsResponse as am, type ProductListingProductShape as an, type ProductListingProjection as ao, type ProductOptionMatrix as ap, type ProductOptionMatrixOption as aq, type ProductOptionMatrixValue as ar, type ProductOptionMatrixVariant as as, type ProductOptionShape as at, type ProductOptionValueShape as au, type ProductSelectionAvailableValue as av, type ProductSelectionByOptionValue as aw, ProductSelectionCodecError as ax, type ProductSelectionCodecOptions as ay, type ProductSelectionInput as az, CustomerNamespace as b, createProductSelectionCodec as b0, getAvailableOptionValues as b1, getProductSelectionImages as b2, getSelectedValueByOptionId as b3, normalizeProductSelection as b4, normalizeProductSelectionFromMatrix as b5, normalizeSelectedValueIds as b6, parseProductSelection as b7, resolveProductSelection as b8, resolveProductSelectionFromMatrix as b9, resolveVariantForSelection as ba, stringifyProductSelection as bb, type ProductUpsertParams as bc, type ProductUpsertResponse as bd, type ClientServerConfig as be, type ClientState as c, type ClientConfig as d, type ClientMetadata as e, type DeepPartial as f, type PayloadMutationResponse as g, type RootClient as h, type RootCollectionClient as i, type RootReadOnlyQueryBuilder as j, type AddItemParams as k, type ApplyDiscountParams as l, type BulkImportFulfillmentsParams as m, type BulkImportFulfillmentsResponse as n, type CalculateShippingParams as o, type CalculateShippingResult as p, CartApi as q, type CartApiOptions as r, type CheckoutParams as s, type ClearCartParams as t, type CommerceClientOptions as u, type CommunityClientOptions as v, type CommunityPost as w, type CompatibilityProductSelectionParamEvent as x, type ConfirmPaymentParams as y, type ConfirmPaymentResponse as z };
1322
+ export { type NormalizedProductSelection as $, type ApiQueryOptions as A, BaseApi as B, CommerceClient as C, type DebugConfig as D, type ExtractArrayType as E, type CreateFulfillmentParams as F, type CreateOrderItem as G, type CreateOrderParams as H, type CreateReturnParams as I, CustomerAuth as J, type CustomerAuthOptions as K, type CustomerAuthResponse as L, type CustomerLoginData as M, type CustomerProfile as N, type CustomerRefreshResponse as O, type PayloadFindResponse as P, type CustomerRegisterData as Q, type RetryConfig as R, type Sort as S, type CustomerRegisterResponse as T, type CustomerSnapshot as U, DiscountApi as V, type Where as W, type DiscountApiOptions as X, type LegacyProductSelectionParamEvent as Y, type ListingGroupingState as Z, type ListingGroupsParams as _, CommunityClient as a, type UpdateTransactionParams as a$, OrderApi as a0, type OrderApiOptions as a1, ProductApi as a2, type ProductApiOptions as a3, type ProductDetail as a4, type ProductDetailBrand as a5, type ProductDetailCategory as a6, type ProductDetailImage as a7, type ProductDetailImageMedia as a8, type ProductDetailListing as a9, type ProductOptionShape as aA, type ProductOptionValueShape as aB, type ProductSelectionAvailableValue as aC, type ProductSelectionByOptionValue as aD, ProductSelectionCodecError as aE, type ProductSelectionCodecOptions as aF, type ProductSelectionInput as aG, type ProductSelectionResolution as aH, type ProductSelectionResolutionContext as aI, type ProductVariantShape as aJ, type RemoveDiscountParams as aK, type RemoveItemParams as aL, type RequestOptions as aM, type ReturnItem as aN, type ReturnReason as aO, type ReturnWithRefundParams as aP, type ServerApiOptions as aQ, ShippingApi as aR, type ShippingApiOptions as aS, type StockCheckParams as aT, type StockCheckResponse as aU, type StockCheckResult as aV, type UpdateFulfillmentParams as aW, type UpdateItemParams as aX, type UpdateOrderParams as aY, type UpdateProfileData as aZ, type UpdateReturnParams as a_, type ProductDetailMedia as aa, type ProductDetailOption as ab, type ProductDetailOptionValue as ac, type ProductDetailParams as ad, type ProductDetailTag as ae, type ProductDetailVariant as af, type ProductDetailVariantOptionValue as ag, type ProductDetailVideo as ah, type ProductHrefGroup as ai, type ProductHrefOptions as aj, type ProductHrefProduct as ak, type ProductListingCard as al, type ProductListingCardPriceRange as am, type ProductListingGroup as an, type ProductListingGroupSummary as ao, type ProductListingGroupVariant as ap, type ProductListingGroupsItem as aq, type ProductListingGroupsProduct as ar, type ProductListingGroupsResponse as as, type ProductListingProductShape as at, type ProductListingProjection as au, type ProductListingSwatch as av, type ProductOptionMatrix as aw, type ProductOptionMatrixOption as ax, type ProductOptionMatrixValue as ay, type ProductOptionMatrixVariant as az, CustomerNamespace as b, type ValidateDiscountParams as b0, type ValidateDiscountResult as b1, buildProductHref as b2, buildProductListingCard as b3, buildProductListingGroupsByOption as b4, buildProductListingProjection as b5, buildProductOptionMatrix as b6, buildProductOptionMatrixFromDetail as b7, createProductSelectionCodec as b8, getAvailableOptionValues as b9, getProductSelectionImages as ba, getSelectedValueByOptionId as bb, normalizeProductSelection as bc, normalizeProductSelectionFromMatrix as bd, normalizeSelectedValueIds as be, parseProductSelection as bf, resolveProductSelection as bg, resolveProductSelectionFromMatrix as bh, resolveVariantForSelection as bi, stringifyProductSelection as bj, type ProductDetailPreviewParams as bk, type ProductDetailPreviewOptions as bl, type ProductUpsertParams as bm, type ProductUpsertResponse as bn, type ClientServerConfig as bo, type ClientState as c, type ClientConfig as d, type ClientMetadata as e, type DeepPartial as f, type PayloadMutationResponse as g, type RootClient as h, type RootCollectionClient as i, type RootReadOnlyQueryBuilder as j, type AddItemParams as k, type ApplyDiscountParams as l, type BulkImportFulfillmentsParams as m, type BulkImportFulfillmentsResponse as n, type CalculateShippingParams as o, type CalculateShippingResult as p, CartApi as q, type CartApiOptions as r, type CheckoutParams as s, type ClearCartParams as t, type CommerceClientOptions as u, type CommunityClientOptions as v, type CommunityPost as w, type CompatibilityProductSelectionParamEvent as x, type ConfirmPaymentParams as y, type ConfirmPaymentResponse as z };
@@ -1,6 +1,6 @@
1
- import { P as PublicCollection } from './const-VZuk2tWc.cjs';
2
- import { C as CollectionType } from './types-BwT0eeaz.cjs';
3
- import { O as Order, h as Cart, i as CartItem, d as Product, l as OrderItem, m as Transaction, n as Fulfillment, o as Return } from './payload-types-DPjO_IbQ.cjs';
1
+ import { P as PublicCollection } from './const-DcY2_z9O.js';
2
+ import { P as PublicProduct, C as CollectionType } from './types-DUPC7Xn6.js';
3
+ import { O as Order, i as Cart, j as CartItem, m as Transaction, n as Fulfillment, o as Return } from './payload-types-DVK1QCeU.js';
4
4
 
5
5
  interface CommunityClientOptions {
6
6
  publishableKey?: string;
@@ -488,6 +488,31 @@ type ProductListingGroup<TVariant extends ProductVariantShape = ProductVariantSh
488
488
  variants: TVariant[];
489
489
  listing: ProductListingProjection;
490
490
  };
491
+ type ProductListingCardPriceRange = {
492
+ minPrice: number | null;
493
+ maxPrice: number | null;
494
+ minCompareAtPrice: number | null;
495
+ maxCompareAtPrice: number | null;
496
+ isPriceRange: boolean;
497
+ };
498
+ type ProductListingSwatch = {
499
+ optionId: EntityID;
500
+ optionValueId: EntityID;
501
+ label: string;
502
+ swatchColor: string | null;
503
+ thumbnail: ProductDetailMedia | null;
504
+ href: string;
505
+ availableForSale: boolean;
506
+ };
507
+ type ProductListingCard = {
508
+ id: EntityID;
509
+ href: string;
510
+ title: string;
511
+ primaryImage: ProductDetailMedia | null;
512
+ priceRange: ProductListingCardPriceRange;
513
+ availableForSale: boolean;
514
+ swatches: ProductListingSwatch[];
515
+ };
491
516
  type ProductSelectionByOptionValue = string | number | null | undefined | {
492
517
  valueId?: string | number | null;
493
518
  valueSlug?: string | null;
@@ -614,6 +639,10 @@ type ProductHrefOptions = {
614
639
  };
615
640
  declare function buildProductHref(product: ProductHrefProduct, group?: ProductHrefGroup | null, options?: ProductHrefOptions): string;
616
641
  declare function buildProductListingProjection(product: ProductListingProductShape | null | undefined, variants: ProductVariantShape[]): ProductListingProjection;
642
+ declare function buildProductListingCard(item: ProductListingGroupsItem, options?: {
643
+ basePath?: string;
644
+ trailingSlash?: boolean;
645
+ }): ProductListingCard;
617
646
  /**
618
647
  * Builds product-first listing groups for one primary option.
619
648
  *
@@ -637,8 +666,10 @@ type StockCheckParams = {
637
666
  };
638
667
  type StockCheckResult = {
639
668
  variantId: string;
669
+ status: 'available' | 'not_published' | 'archived' | 'not_found';
640
670
  available: boolean;
641
671
  availableStock: number;
672
+ isUnlimited: boolean;
642
673
  requestedQuantity: number;
643
674
  error?: string;
644
675
  };
@@ -649,20 +680,45 @@ type StockCheckResponse = {
649
680
  type ListingGroupsParams = {
650
681
  productIds: string[];
651
682
  };
652
- type ProductListingGroupSummary = Omit<ProductListingGroup, 'variants'>;
683
+ type ListingGroupingState = 'grouped' | 'no_primary_option' | 'empty';
684
+ type ProductListingGroupVariant = Pick<ProductVariantShape, 'id' | 'optionValues' | 'price' | 'compareAtPrice' | 'stock' | 'isUnlimited' | 'isActive' | 'thumbnail' | 'images' | '_order'>;
685
+ type ProductListingGroupSummary = ProductListingGroup<ProductListingGroupVariant>;
686
+ type ProductListingGroupsProductVariants = NonNullable<PublicProduct['variants']>;
687
+ type ProductListingGroupsProduct = Omit<PublicProduct, 'variants'> & {
688
+ id: string;
689
+ slug: string;
690
+ title: string;
691
+ variants?: (Omit<ProductListingGroupsProductVariants, 'docs'> & {
692
+ docs: ProductListingGroupVariant[];
693
+ }) | null;
694
+ };
653
695
  type ProductListingGroupsItem = {
654
- product: Product;
696
+ product: ProductListingGroupsProduct;
655
697
  primaryOptionId: string | null;
698
+ listingGroupingState: ListingGroupingState;
656
699
  groups: ProductListingGroupSummary[];
657
700
  };
658
701
  type ProductListingGroupsResponse = {
702
+ /**
703
+ * Matching products in the same order as the requested productIds, excluding
704
+ * ids that were not found, not published, or not accessible for the current
705
+ * tenant/key.
706
+ */
659
707
  docs: ProductListingGroupsItem[];
708
+ /** Requested productIds that could not be returned. */
709
+ missing: string[];
660
710
  };
661
711
  type ProductDetailParams = {
662
712
  slug: string;
663
713
  } | {
664
714
  id: string;
665
715
  };
716
+ type ProductDetailPreviewParams = {
717
+ id: string;
718
+ };
719
+ type ProductDetailPreviewOptions = {
720
+ previewToken: string;
721
+ };
666
722
  interface ProductDetailVariantOptionValue {
667
723
  optionId: string | number;
668
724
  optionSlug: string;
@@ -815,7 +871,7 @@ type ProductUpsertParams = {
815
871
  };
816
872
  type ProductUpsertResponse = {
817
873
  ok: true;
818
- product: Product;
874
+ product: PublicProduct;
819
875
  } | {
820
876
  ok: false;
821
877
  failedEntity: 'product' | 'option' | 'option-value' | 'variant';
@@ -834,7 +890,7 @@ declare class ProductApi extends BaseApi {
834
890
  /**
835
891
  * Fetch full product detail by slug or id.
836
892
  * Returns `null` on 404 regardless of reason (`not_found` / `not_published` /
837
- * `tenant_mismatch` / `feature_disabled`). For the reason behind a null,
893
+ * `feature_disabled`). For the reason behind a null,
838
894
  * inspect `client.lastRequestId` against backend logs.
839
895
  */
840
896
  detail(params: ProductDetailParams): Promise<ProductDetail | null>;
@@ -896,12 +952,29 @@ type ReturnItem = {
896
952
  orderItem: string;
897
953
  quantity: number;
898
954
  };
955
+ type OrderCreateEntityID = string | number;
956
+ type CreateOrderItem = {
957
+ product: OrderCreateEntityID;
958
+ variant: OrderCreateEntityID;
959
+ option: OrderCreateEntityID;
960
+ quantity: number;
961
+ /**
962
+ * Compatibility input: the create-order endpoint accepts this, but the server
963
+ * derives authoritative line pricing from the product variant.
964
+ */
965
+ unitPrice?: number;
966
+ /**
967
+ * Compatibility input: the create-order endpoint accepts this, but the server
968
+ * derives authoritative line totals from the product variant.
969
+ */
970
+ totalPrice?: number;
971
+ };
899
972
  type CreateOrderParams = {
900
973
  orderNumber: string;
901
974
  customer?: string;
902
975
  customerSnapshot: CustomerSnapshot;
903
976
  shippingAddress: Order['shippingAddress'];
904
- orderItems: Pick<OrderItem, 'product' | 'variant' | 'quantity' | 'unitPrice' | 'totalPrice'>[];
977
+ orderItems: CreateOrderItem[];
905
978
  totalAmount: number;
906
979
  shippingAmount?: number;
907
980
  pgPaymentId?: string;
@@ -1246,4 +1319,4 @@ type DeepPartial<T> = {
1246
1319
  };
1247
1320
  type ExtractArrayType<T> = T extends (infer U)[] ? U : never;
1248
1321
 
1249
- export { type OrderApiOptions as $, type ApiQueryOptions as A, BaseApi as B, CommerceClient as C, type DebugConfig as D, type ExtractArrayType as E, type CreateFulfillmentParams as F, type CreateOrderParams as G, type CreateReturnParams as H, CustomerAuth as I, type CustomerAuthOptions as J, type CustomerAuthResponse as K, type CustomerLoginData as L, type CustomerProfile as M, type CustomerRefreshResponse as N, type CustomerRegisterData as O, type PayloadFindResponse as P, type CustomerRegisterResponse as Q, type RetryConfig as R, type Sort as S, type CustomerSnapshot as T, DiscountApi as U, type DiscountApiOptions as V, type Where as W, type LegacyProductSelectionParamEvent as X, type ListingGroupsParams as Y, type NormalizedProductSelection as Z, OrderApi as _, CommunityClient as a, buildProductOptionMatrixFromDetail as a$, ProductApi as a0, type ProductApiOptions as a1, type ProductDetail as a2, type ProductDetailBrand as a3, type ProductDetailCategory as a4, type ProductDetailImage as a5, type ProductDetailImageMedia as a6, type ProductDetailListing as a7, type ProductDetailMedia as a8, type ProductDetailOption as a9, type ProductSelectionResolution as aA, type ProductSelectionResolutionContext as aB, type ProductVariantShape as aC, type RemoveDiscountParams as aD, type RemoveItemParams as aE, type RequestOptions as aF, type ReturnItem as aG, type ReturnReason as aH, type ReturnWithRefundParams as aI, type ServerApiOptions as aJ, ShippingApi as aK, type ShippingApiOptions as aL, type StockCheckParams as aM, type StockCheckResponse as aN, type StockCheckResult as aO, type UpdateFulfillmentParams as aP, type UpdateItemParams as aQ, type UpdateOrderParams as aR, type UpdateProfileData as aS, type UpdateReturnParams as aT, type UpdateTransactionParams as aU, type ValidateDiscountParams as aV, type ValidateDiscountResult as aW, buildProductHref as aX, buildProductListingGroupsByOption as aY, buildProductListingProjection as aZ, buildProductOptionMatrix as a_, type ProductDetailOptionValue as aa, type ProductDetailParams as ab, type ProductDetailTag as ac, type ProductDetailVariant as ad, type ProductDetailVariantOptionValue as ae, type ProductDetailVideo as af, type ProductHrefGroup as ag, type ProductHrefOptions as ah, type ProductHrefProduct as ai, type ProductListingGroup as aj, type ProductListingGroupSummary as ak, type ProductListingGroupsItem as al, type ProductListingGroupsResponse as am, type ProductListingProductShape as an, type ProductListingProjection as ao, type ProductOptionMatrix as ap, type ProductOptionMatrixOption as aq, type ProductOptionMatrixValue as ar, type ProductOptionMatrixVariant as as, type ProductOptionShape as at, type ProductOptionValueShape as au, type ProductSelectionAvailableValue as av, type ProductSelectionByOptionValue as aw, ProductSelectionCodecError as ax, type ProductSelectionCodecOptions as ay, type ProductSelectionInput as az, CustomerNamespace as b, createProductSelectionCodec as b0, getAvailableOptionValues as b1, getProductSelectionImages as b2, getSelectedValueByOptionId as b3, normalizeProductSelection as b4, normalizeProductSelectionFromMatrix as b5, normalizeSelectedValueIds as b6, parseProductSelection as b7, resolveProductSelection as b8, resolveProductSelectionFromMatrix as b9, resolveVariantForSelection as ba, stringifyProductSelection as bb, type ProductUpsertParams as bc, type ProductUpsertResponse as bd, type ClientServerConfig as be, type ClientState as c, type ClientConfig as d, type ClientMetadata as e, type DeepPartial as f, type PayloadMutationResponse as g, type RootClient as h, type RootCollectionClient as i, type RootReadOnlyQueryBuilder as j, type AddItemParams as k, type ApplyDiscountParams as l, type BulkImportFulfillmentsParams as m, type BulkImportFulfillmentsResponse as n, type CalculateShippingParams as o, type CalculateShippingResult as p, CartApi as q, type CartApiOptions as r, type CheckoutParams as s, type ClearCartParams as t, type CommerceClientOptions as u, type CommunityClientOptions as v, type CommunityPost as w, type CompatibilityProductSelectionParamEvent as x, type ConfirmPaymentParams as y, type ConfirmPaymentResponse as z };
1322
+ export { type NormalizedProductSelection as $, type ApiQueryOptions as A, BaseApi as B, CommerceClient as C, type DebugConfig as D, type ExtractArrayType as E, type CreateFulfillmentParams as F, type CreateOrderItem as G, type CreateOrderParams as H, type CreateReturnParams as I, CustomerAuth as J, type CustomerAuthOptions as K, type CustomerAuthResponse as L, type CustomerLoginData as M, type CustomerProfile as N, type CustomerRefreshResponse as O, type PayloadFindResponse as P, type CustomerRegisterData as Q, type RetryConfig as R, type Sort as S, type CustomerRegisterResponse as T, type CustomerSnapshot as U, DiscountApi as V, type Where as W, type DiscountApiOptions as X, type LegacyProductSelectionParamEvent as Y, type ListingGroupingState as Z, type ListingGroupsParams as _, CommunityClient as a, type UpdateTransactionParams as a$, OrderApi as a0, type OrderApiOptions as a1, ProductApi as a2, type ProductApiOptions as a3, type ProductDetail as a4, type ProductDetailBrand as a5, type ProductDetailCategory as a6, type ProductDetailImage as a7, type ProductDetailImageMedia as a8, type ProductDetailListing as a9, type ProductOptionShape as aA, type ProductOptionValueShape as aB, type ProductSelectionAvailableValue as aC, type ProductSelectionByOptionValue as aD, ProductSelectionCodecError as aE, type ProductSelectionCodecOptions as aF, type ProductSelectionInput as aG, type ProductSelectionResolution as aH, type ProductSelectionResolutionContext as aI, type ProductVariantShape as aJ, type RemoveDiscountParams as aK, type RemoveItemParams as aL, type RequestOptions as aM, type ReturnItem as aN, type ReturnReason as aO, type ReturnWithRefundParams as aP, type ServerApiOptions as aQ, ShippingApi as aR, type ShippingApiOptions as aS, type StockCheckParams as aT, type StockCheckResponse as aU, type StockCheckResult as aV, type UpdateFulfillmentParams as aW, type UpdateItemParams as aX, type UpdateOrderParams as aY, type UpdateProfileData as aZ, type UpdateReturnParams as a_, type ProductDetailMedia as aa, type ProductDetailOption as ab, type ProductDetailOptionValue as ac, type ProductDetailParams as ad, type ProductDetailTag as ae, type ProductDetailVariant as af, type ProductDetailVariantOptionValue as ag, type ProductDetailVideo as ah, type ProductHrefGroup as ai, type ProductHrefOptions as aj, type ProductHrefProduct as ak, type ProductListingCard as al, type ProductListingCardPriceRange as am, type ProductListingGroup as an, type ProductListingGroupSummary as ao, type ProductListingGroupVariant as ap, type ProductListingGroupsItem as aq, type ProductListingGroupsProduct as ar, type ProductListingGroupsResponse as as, type ProductListingProductShape as at, type ProductListingProjection as au, type ProductListingSwatch as av, type ProductOptionMatrix as aw, type ProductOptionMatrixOption as ax, type ProductOptionMatrixValue as ay, type ProductOptionMatrixVariant as az, CustomerNamespace as b, type ValidateDiscountParams as b0, type ValidateDiscountResult as b1, buildProductHref as b2, buildProductListingCard as b3, buildProductListingGroupsByOption as b4, buildProductListingProjection as b5, buildProductOptionMatrix as b6, buildProductOptionMatrixFromDetail as b7, createProductSelectionCodec as b8, getAvailableOptionValues as b9, getProductSelectionImages as ba, getSelectedValueByOptionId as bb, normalizeProductSelection as bc, normalizeProductSelectionFromMatrix as bd, normalizeSelectedValueIds as be, parseProductSelection as bf, resolveProductSelection as bg, resolveProductSelectionFromMatrix as bh, resolveVariantForSelection as bi, stringifyProductSelection as bj, type ProductDetailPreviewParams as bk, type ProductDetailPreviewOptions as bl, type ProductUpsertParams as bm, type ProductUpsertResponse as bn, type ClientServerConfig as bo, type ClientState as c, type ClientConfig as d, type ClientMetadata as e, type DeepPartial as f, type PayloadMutationResponse as g, type RootClient as h, type RootCollectionClient as i, type RootReadOnlyQueryBuilder as j, type AddItemParams as k, type ApplyDiscountParams as l, type BulkImportFulfillmentsParams as m, type BulkImportFulfillmentsResponse as n, type CalculateShippingParams as o, type CalculateShippingResult as p, CartApi as q, type CartApiOptions as r, type CheckoutParams as s, type ClearCartParams as t, type CommerceClientOptions as u, type CommunityClientOptions as v, type CommunityPost as w, type CompatibilityProductSelectionParamEvent as x, type ConfirmPaymentParams as y, type ConfirmPaymentResponse as z };
@@ -1,4 +1,4 @@
1
- import { C as CustomerProfile, a as CustomerProfileList, P as Post, b as Comment, R as Reaction, c as Config } from './payload-types-DPjO_IbQ.js';
1
+ import { P as Product, C as CustomerProfile, a as CustomerProfileList, b as ProductCollection, c as Post, d as Comment, R as Reaction, e as Config } from './payload-types-DVK1QCeU.js';
2
2
 
3
3
  type PublicCustomerProfile = Omit<CustomerProfile, 'tenant' | 'customer' | 'isPublic' | 'anonymizedAt' | 'metadata'>;
4
4
  type PublicProfileRelation = string | PublicCustomerProfile;
@@ -27,13 +27,17 @@ type PublicComment = Omit<Comment, 'authorProfile'> & {
27
27
  type PublicReaction = Omit<Reaction, 'actorProfile'> & {
28
28
  actorProfile: PublicProfileRelation;
29
29
  };
30
+ type PublicProduct = Omit<Product, 'collectionItems'>;
31
+ type PublicProductCollection = Omit<ProductCollection, 'items'>;
30
32
  type PublicCollectionOverrides = {
31
33
  'customer-profiles': PublicCustomerProfile;
32
34
  'customer-profile-lists': PublicCustomerProfileList;
35
+ products: PublicProduct;
36
+ 'product-collections': PublicProductCollection;
33
37
  posts: PublicPost;
34
38
  comments: PublicComment;
35
39
  reactions: PublicReaction;
36
40
  };
37
41
  type CollectionType<T extends string> = T extends keyof PublicCollectionOverrides ? PublicCollectionOverrides[T] : T extends keyof Config['collections'] ? Config['collections'][T] : never;
38
42
 
39
- export type { CollectionType as C };
43
+ export type { CollectionType as C, PublicProduct as P, PublicProductCollection as a };
@@ -1,5 +1,5 @@
1
1
  import React from 'react';
2
- import { F as Form } from '../payload-types-DPjO_IbQ.cjs';
2
+ import { F as Form } from '../payload-types-DVK1QCeU.cjs';
3
3
  import { RichTextData } from './rich-text.cjs';
4
4
  import '@payloadcms/richtext-lexical';
5
5
  import '@payloadcms/richtext-lexical/lexical';
package/dist/ui/form.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import React from 'react';
2
- import { F as Form } from '../payload-types-DPjO_IbQ.js';
2
+ import { F as Form } from '../payload-types-DVK1QCeU.js';
3
3
  import { RichTextData } from './rich-text.js';
4
4
  import '@payloadcms/richtext-lexical';
5
5
  import '@payloadcms/richtext-lexical/lexical';
@@ -1,7 +1,7 @@
1
1
  import React, { CSSProperties } from 'react';
2
2
  import { MuxPlayerProps, MuxPlayerRefAttributes } from '@mux/mux-player-react';
3
3
  export { MuxPlayerRefAttributes as VideoPlayerRef } from '@mux/mux-player-react';
4
- import { V as Video } from '../payload-types-DPjO_IbQ.cjs';
4
+ import { V as Video } from '../payload-types-DVK1QCeU.cjs';
5
5
  export { V as VideoGifOptions, a as VideoThumbnailOptions, g as getVideoGif, b as getVideoMp4Url, c as getVideoStoryboard, d as getVideoStreamUrl, e as getVideoThumbnail } from '../video-WR_TFO9a.cjs';
6
6
 
7
7
  interface VideoPlayerCSSProperties extends CSSProperties {
@@ -1,7 +1,7 @@
1
1
  import React, { CSSProperties } from 'react';
2
2
  import { MuxPlayerProps, MuxPlayerRefAttributes } from '@mux/mux-player-react';
3
3
  export { MuxPlayerRefAttributes as VideoPlayerRef } from '@mux/mux-player-react';
4
- import { V as Video } from '../payload-types-DPjO_IbQ.js';
4
+ import { V as Video } from '../payload-types-DVK1QCeU.js';
5
5
  export { V as VideoGifOptions, a as VideoThumbnailOptions, g as getVideoGif, b as getVideoMp4Url, c as getVideoStoryboard, d as getVideoStreamUrl, e as getVideoThumbnail } from '../video-WR_TFO9a.js';
6
6
 
7
7
  interface VideoPlayerCSSProperties extends CSSProperties {
package/dist/webhook.cjs CHANGED
@@ -21,20 +21,67 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var webhook_exports = {};
22
22
  __export(webhook_exports, {
23
23
  CUSTOMER_PASSWORD_RESET_OPERATION: () => CUSTOMER_PASSWORD_RESET_OPERATION,
24
+ ORDER_CHANGED_EVENT_TYPE: () => ORDER_CHANGED_EVENT_TYPE,
24
25
  createCustomerAuthWebhookHandler: () => createCustomerAuthWebhookHandler,
25
26
  createTypedWebhookHandler: () => createTypedWebhookHandler,
26
27
  handleWebhook: () => handleWebhook,
27
28
  isCustomerPasswordResetWebhookEvent: () => isCustomerPasswordResetWebhookEvent,
28
- isValidWebhookEvent: () => isValidWebhookEvent
29
+ isOrderChangedWebhookEvent: () => isOrderChangedWebhookEvent,
30
+ isValidWebhookEvent: () => isValidWebhookEvent,
31
+ isWebhookCollection: () => isWebhookCollection,
32
+ isWebhookOperation: () => isWebhookOperation
29
33
  });
30
34
  module.exports = __toCommonJS(webhook_exports);
31
35
 
32
36
  // src/core/webhook/index.ts
37
+ var ORDER_CHANGED_EVENT_TYPE = "collection.orderChanged";
33
38
  function isValidWebhookEvent(data) {
34
39
  if (typeof data !== "object" || data === null) return false;
35
40
  const obj = data;
36
41
  return typeof obj.collection === "string" && typeof obj.operation === "string" && obj.operation.length > 0 && typeof obj.data === "object" && obj.data !== null;
37
42
  }
43
+ function isStringOrNumber(value) {
44
+ return typeof value === "string" || typeof value === "number";
45
+ }
46
+ function isWebhookOrderScope(value) {
47
+ if (!isRecord(value)) return false;
48
+ if (value.kind === "collection") {
49
+ return typeof value.collection === "string";
50
+ }
51
+ if (value.kind === "join") {
52
+ return typeof value.collection === "string" && typeof value.field === "string" && isStringOrNumber(value.id);
53
+ }
54
+ return false;
55
+ }
56
+ function isWebhookOrderMoved(value) {
57
+ if (!isRecord(value)) return false;
58
+ return typeof value.collection === "string" && isStringOrNumber(value.id) && (value.relatedCollection === void 0 || typeof value.relatedCollection === "string") && (value.relatedId === void 0 || isStringOrNumber(value.relatedId));
59
+ }
60
+ function hasOptionalOrderValue(value, key) {
61
+ return value[key] === void 0 || value[key] === null || typeof value[key] === "string";
62
+ }
63
+ function isWebhookOrderChange(value) {
64
+ if (!isRecord(value)) return false;
65
+ return value.type === "order" && value.source === "payload-orderable" && (value.orderableFieldName === void 0 || typeof value.orderableFieldName === "string") && hasOptionalOrderValue(value, "previousOrder") && hasOptionalOrderValue(value, "nextOrder") && isWebhookOrderScope(value.scope) && isWebhookOrderMoved(value.moved);
66
+ }
67
+ function isOrderChangedWebhookEvent(event) {
68
+ if (!isValidWebhookEvent(event) || event.operation !== "update" || event.eventType !== ORDER_CHANGED_EVENT_TYPE || !isWebhookOrderChange(event.change)) {
69
+ return false;
70
+ }
71
+ if (event.collection !== event.change.scope.collection) {
72
+ return false;
73
+ }
74
+ if (event.change.scope.kind === "collection" && event.change.moved.collection !== event.change.scope.collection) {
75
+ return false;
76
+ }
77
+ return true;
78
+ }
79
+ function isWebhookCollection(event, collection) {
80
+ return isValidWebhookEvent(event) && event.collection === collection;
81
+ }
82
+ function isWebhookOperation(event, operation) {
83
+ return isValidWebhookEvent(event) && event.operation === operation;
84
+ }
38
85
  var CUSTOMER_PASSWORD_RESET_OPERATION = "password-reset";
39
86
  function isRecord(value) {
40
87
  return typeof value === "object" && value !== null;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/webhook.ts","../src/core/webhook/index.ts"],"sourcesContent":["export {\n handleWebhook,\n createTypedWebhookHandler,\n createCustomerAuthWebhookHandler,\n isValidWebhookEvent,\n isCustomerPasswordResetWebhookEvent,\n CUSTOMER_PASSWORD_RESET_OPERATION,\n} from './core/webhook'\nexport type {\n CustomerAuthWebhookEvent,\n CustomerAuthWebhookHandlers,\n CustomerPasswordResetWebhookData,\n CustomerPasswordResetWebhookEvent,\n WebhookEvent,\n WebhookHandler,\n WebhookOperation,\n WebhookOptions,\n} from './core/webhook'\n","import type { Collection } from '../client/types'\nimport type { CollectionType } from '../collection/types'\n\nexport type WebhookOperation = string\n\nexport interface WebhookEvent<\n T extends Collection | string = Collection,\n TData = T extends Collection ? CollectionType<T> : Record<string, unknown>,\n> {\n collection: T\n operation: WebhookOperation\n data: TData\n timestamp?: string\n deliveryId?: string\n}\n\nexport type WebhookHandler<\n T extends Collection | string = Collection,\n TData = T extends Collection ? CollectionType<T> : Record<string, unknown>,\n> = (\n event: WebhookEvent<T, TData>,\n) => Promise<void> | void\n\nexport interface WebhookOptions {\n secret?: string\n /** Max accepted skew for signed webhook delivery timestamps. Default: 300s. */\n toleranceSeconds?: number\n}\n\nexport function isValidWebhookEvent(data: unknown): data is WebhookEvent {\n if (typeof data !== 'object' || data === null) return false\n const obj = data as Record<string, unknown>\n return (\n typeof obj.collection === 'string' &&\n typeof obj.operation === 'string' &&\n obj.operation.length > 0 &&\n typeof obj.data === 'object' &&\n obj.data !== null\n )\n}\n\nexport const CUSTOMER_PASSWORD_RESET_OPERATION = 'password-reset' as const\n\nexport interface CustomerPasswordResetWebhookData {\n customerId: string | number\n email: string\n name: string\n resetPasswordToken: string\n resetPasswordExpiresAt: string\n}\n\nexport type CustomerPasswordResetWebhookEvent = WebhookEvent<\n 'customers',\n CustomerPasswordResetWebhookData\n> & {\n operation: typeof CUSTOMER_PASSWORD_RESET_OPERATION\n}\n\nexport type CustomerAuthWebhookEvent = CustomerPasswordResetWebhookEvent\n\ntype MaybePromise<T> = T | Promise<T>\n\nexport interface CustomerAuthWebhookHandlers {\n passwordReset?: (\n data: CustomerPasswordResetWebhookData,\n event: CustomerPasswordResetWebhookEvent,\n ) => MaybePromise<void>\n unhandled?: (event: WebhookEvent<string, unknown>) => MaybePromise<void>\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\n}\n\nfunction hasString(value: Record<string, unknown>, key: string): boolean {\n return typeof value[key] === 'string'\n}\n\nfunction hasStringOrNumber(\n value: Record<string, unknown>,\n key: string,\n): boolean {\n return typeof value[key] === 'string' || typeof value[key] === 'number'\n}\n\nexport function isCustomerPasswordResetWebhookEvent(\n event: WebhookEvent<string, unknown>,\n): event is CustomerPasswordResetWebhookEvent {\n if (\n event.collection !== 'customers' ||\n event.operation !== CUSTOMER_PASSWORD_RESET_OPERATION ||\n !isRecord(event.data)\n ) {\n return false\n }\n\n return (\n hasStringOrNumber(event.data, 'customerId') &&\n hasString(event.data, 'email') &&\n hasString(event.data, 'name') &&\n hasString(event.data, 'resetPasswordToken') &&\n hasString(event.data, 'resetPasswordExpiresAt')\n )\n}\n\nexport function createCustomerAuthWebhookHandler(\n handlers: CustomerAuthWebhookHandlers,\n): WebhookHandler<string, unknown> {\n return async (event) => {\n if (isCustomerPasswordResetWebhookEvent(event) && handlers.passwordReset) {\n await handlers.passwordReset(event.data, event)\n return\n }\n\n await handlers.unhandled?.(event)\n }\n}\n\nasync function verifySignature(\n payload: string,\n secret: string,\n signature: string,\n timestamp: string,\n deliveryId: string,\n): Promise<boolean> {\n const encoder = new TextEncoder()\n const key = await crypto.subtle.importKey(\n 'raw',\n encoder.encode(secret),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['verify'],\n )\n // Validate and convert hex signature to Uint8Array\n if (signature.length % 2 !== 0 || !/^[0-9a-fA-F]*$/.test(signature)) {\n return false\n }\n const sigBytes = new Uint8Array(\n (signature.match(/.{2}/g) ?? []).map((byte) => parseInt(byte, 16)),\n )\n // crypto.subtle.verify performs constant-time comparison internally\n return crypto.subtle.verify(\n 'HMAC',\n key,\n sigBytes,\n encoder.encode(`${timestamp}.${deliveryId}.${payload}`),\n )\n}\n\nfunction timestampIsFresh(timestamp: string, toleranceSeconds: number): boolean {\n if (!/^\\d+$/.test(timestamp)) return false\n const timestampMs = Number(timestamp)\n if (!Number.isFinite(timestampMs)) return false\n const skewMs = Math.abs(Date.now() - timestampMs)\n return skewMs <= toleranceSeconds * 1000\n}\n\nexport async function handleWebhook<\n T extends Collection | string = Collection,\n TData = T extends Collection ? CollectionType<T> : Record<string, unknown>,\n>(\n request: Request,\n handler: WebhookHandler<T, TData>,\n options?: WebhookOptions,\n): Promise<Response> {\n try {\n const rawBody = await request.text()\n\n if (options?.secret) {\n const signature = request.headers.get('x-webhook-signature') || ''\n const timestamp = request.headers.get('x-webhook-timestamp') || ''\n const deliveryId = request.headers.get('x-webhook-delivery-id') || ''\n const toleranceSeconds = options.toleranceSeconds ?? 300\n const valid = Boolean(timestamp && deliveryId) &&\n timestampIsFresh(timestamp, toleranceSeconds) &&\n (await verifySignature(\n rawBody,\n options.secret,\n signature,\n timestamp,\n deliveryId,\n ))\n if (!valid) {\n return new Response(\n JSON.stringify({ error: 'Invalid webhook signature' }),\n { status: 401, headers: { 'Content-Type': 'application/json' } },\n )\n }\n } else {\n console.warn(\n '[@01.software/sdk] Webhook signature verification is disabled. ' +\n 'Set { secret } in handleWebhook() options to enable HMAC-SHA256 verification.',\n )\n }\n\n const body = JSON.parse(rawBody)\n\n if (!isValidWebhookEvent(body)) {\n return new Response(\n JSON.stringify({ error: 'Invalid webhook event format' }),\n { status: 400, headers: { 'Content-Type': 'application/json' } },\n )\n }\n\n await handler(body as WebhookEvent<T, TData>)\n\n return new Response(\n JSON.stringify({ success: true, message: 'Webhook processed' }),\n { status: 200, headers: { 'Content-Type': 'application/json' } },\n )\n } catch (error) {\n console.error('Webhook processing error:', error)\n\n return new Response(JSON.stringify({ error: 'Internal server error' }), {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n })\n }\n}\n\nexport function createTypedWebhookHandler<T extends Collection>(\n collection: T,\n handler: (event: WebhookEvent<T>) => Promise<void> | void,\n): WebhookHandler<T> {\n return async (event: WebhookEvent<T>) => {\n if (event.collection !== collection) {\n throw new Error(\n `Expected collection \"${collection}\", got \"${event.collection}\"`,\n )\n }\n return handler(event)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC6BO,SAAS,oBAAoB,MAAqC;AACvE,MAAI,OAAO,SAAS,YAAY,SAAS,KAAM,QAAO;AACtD,QAAM,MAAM;AACZ,SACE,OAAO,IAAI,eAAe,YAC1B,OAAO,IAAI,cAAc,YACzB,IAAI,UAAU,SAAS,KACvB,OAAO,IAAI,SAAS,YACpB,IAAI,SAAS;AAEjB;AAEO,IAAM,oCAAoC;AA6BjD,SAAS,SAAS,OAAkD;AAClE,SAAO,OAAO,UAAU,YAAY,UAAU;AAChD;AAEA,SAAS,UAAU,OAAgC,KAAsB;AACvE,SAAO,OAAO,MAAM,GAAG,MAAM;AAC/B;AAEA,SAAS,kBACP,OACA,KACS;AACT,SAAO,OAAO,MAAM,GAAG,MAAM,YAAY,OAAO,MAAM,GAAG,MAAM;AACjE;AAEO,SAAS,oCACd,OAC4C;AAC5C,MACE,MAAM,eAAe,eACrB,MAAM,cAAc,qCACpB,CAAC,SAAS,MA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KAAK,UAAU,EAAE,OAAO,wBAAwB,CAAC,GAAG;AAAA,MACtE,QAAQ;AAAA,MACR,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,IAChD,CAAC;AAAA,EACH;AACF;AAEO,SAAS,0BACd,YACA,SACmB;AACnB,SAAO,OAAO,UAA2B;AACvC,QAAI,MAAM,eAAe,YAAY;AACnC,YAAM,IAAI;AAAA,QACR,wBAAwB,UAAU,WAAW,MAAM,UAAU;AAAA,MAC/D;AAAA,IACF;AACA,WAAO,QAAQ,KAAK;AAAA,EACtB;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/webhook.ts","../src/core/webhook/index.ts"],"sourcesContent":["export {\n handleWebhook,\n createTypedWebhookHandler,\n createCustomerAuthWebhookHandler,\n isValidWebhookEvent,\n isCustomerPasswordResetWebhookEvent,\n isOrderChangedWebhookEvent,\n isWebhookCollection,\n isWebhookOperation,\n CUSTOMER_PASSWORD_RESET_OPERATION,\n ORDER_CHANGED_EVENT_TYPE,\n} from './core/webhook'\nexport type {\n CollectionWebhookOperation,\n CustomerAuthWebhookEvent,\n CustomerAuthWebhookHandlers,\n CustomerPasswordResetWebhookData,\n CustomerPasswordResetWebhookEvent,\n OrderChangedWebhookEvent,\n WebhookChange,\n WebhookEvent,\n WebhookHandler,\n WebhookKnownOperation,\n WebhookOperation,\n WebhookOptions,\n WebhookOrderChange,\n WebhookOrderMoved,\n WebhookOrderScope,\n} from './core/webhook'\n","import type { Collection } from '../client/types'\nimport type { CollectionType } from '../collection/types'\n\nexport type WebhookOperation = string\n\n/**\n * Semantic event type for manual Admin Panel ordering changes.\n *\n * Order-change webhooks remain `operation: \"update\"` events for compatibility.\n * Do not filter on or emit `operation: \"reorder\"`; use this event type with\n * `isOrderChangedWebhookEvent()` to distinguish ordering from normal content\n * updates.\n */\nexport const ORDER_CHANGED_EVENT_TYPE = 'collection.orderChanged' as const\n\n/** Collection webhook operations emitted for tenant collection writes. */\nexport type CollectionWebhookOperation = 'create' | 'update'\n\n/** Describes the ordered area affected by an order-change webhook. */\nexport type WebhookOrderScope =\n | { kind: 'collection'; collection: string }\n | { kind: 'join'; collection: string; field: string; id: string | number }\n\n/** Identifies the public moved document for the ordered scope. */\nexport type WebhookOrderMoved = {\n collection: string\n id: string | number\n relatedCollection?: string\n relatedId?: string | number\n}\n\n/** Metadata attached to `collection.orderChanged` webhook events. */\nexport type WebhookOrderChange = {\n type: 'order'\n source: 'payload-orderable'\n /**\n * Diagnostic Payload order field name.\n *\n * This may contain hidden implementation field names. Application routing\n * should use `change.scope` and `change.moved` instead.\n */\n orderableFieldName?: string\n previousOrder?: string | null\n nextOrder?: string | null\n scope: WebhookOrderScope\n moved: WebhookOrderMoved\n}\n\n/** Known semantic webhook change metadata. */\nexport type WebhookChange = WebhookOrderChange\n\nexport interface WebhookEvent<\n T extends Collection | string = Collection,\n TData = T extends Collection ? CollectionType<T> : Record<string, unknown>,\n> {\n collection: T\n operation: WebhookOperation\n data: TData\n eventType?: string\n change?: unknown\n timestamp?: string\n deliveryId?: string\n}\n\nexport type WebhookHandler<\n T extends Collection | string = Collection,\n TData = T extends Collection ? CollectionType<T> : Record<string, unknown>,\n> = (event: WebhookEvent<T, TData>) => Promise<void> | void\n\nexport interface WebhookOptions {\n secret?: string\n /** Max accepted skew for signed webhook delivery timestamps. Default: 300s. */\n toleranceSeconds?: number\n}\n\nexport function isValidWebhookEvent(data: unknown): data is WebhookEvent {\n if (typeof data !== 'object' || data === null) return false\n const obj = data as Record<string, unknown>\n return (\n typeof obj.collection === 'string' &&\n typeof obj.operation === 'string' &&\n obj.operation.length > 0 &&\n typeof obj.data === 'object' &&\n obj.data !== null\n )\n}\n\n/** Webhook event emitted when manual Admin Panel ordering changes. */\nexport type OrderChangedWebhookEvent<\n T extends Collection | string = Collection,\n TData = T extends Collection ? CollectionType<T> : Record<string, unknown>,\n> = WebhookEvent<T, TData> & {\n operation: 'update'\n eventType: typeof ORDER_CHANGED_EVENT_TYPE\n change: WebhookOrderChange\n}\n\nfunction isStringOrNumber(value: unknown): value is string | number {\n return typeof value === 'string' || typeof value === 'number'\n}\n\nfunction isWebhookOrderScope(value: unknown): value is WebhookOrderScope {\n if (!isRecord(value)) return false\n\n if (value.kind === 'collection') {\n return typeof value.collection === 'string'\n }\n\n if (value.kind === 'join') {\n return (\n typeof value.collection === 'string' &&\n typeof value.field === 'string' &&\n isStringOrNumber(value.id)\n )\n }\n\n return false\n}\n\nfunction isWebhookOrderMoved(value: unknown): value is WebhookOrderMoved {\n if (!isRecord(value)) return false\n\n return (\n typeof value.collection === 'string' &&\n isStringOrNumber(value.id) &&\n (value.relatedCollection === undefined ||\n typeof value.relatedCollection === 'string') &&\n (value.relatedId === undefined || isStringOrNumber(value.relatedId))\n )\n}\n\nfunction hasOptionalOrderValue(\n value: Record<string, unknown>,\n key: string,\n): boolean {\n return (\n value[key] === undefined ||\n value[key] === null ||\n typeof value[key] === 'string'\n )\n}\n\nfunction isWebhookOrderChange(value: unknown): value is WebhookOrderChange {\n if (!isRecord(value)) return false\n\n return (\n value.type === 'order' &&\n value.source === 'payload-orderable' &&\n (value.orderableFieldName === undefined ||\n typeof value.orderableFieldName === 'string') &&\n hasOptionalOrderValue(value, 'previousOrder') &&\n hasOptionalOrderValue(value, 'nextOrder') &&\n isWebhookOrderScope(value.scope) &&\n isWebhookOrderMoved(value.moved)\n )\n}\n\n/**\n * Returns true for semantic order-change webhooks emitted as update events.\n *\n * Use this guard with `ORDER_CHANGED_EVENT_TYPE` instead of filtering on\n * `operation: \"reorder\"`. Tenant order-change webhooks intentionally keep\n * `operation: \"update\"` for compatibility with existing webhook handlers.\n */\nexport function isOrderChangedWebhookEvent(\n event: unknown,\n): event is OrderChangedWebhookEvent<string, unknown> {\n if (\n !isValidWebhookEvent(event) ||\n event.operation !== 'update' ||\n event.eventType !== ORDER_CHANGED_EVENT_TYPE ||\n !isWebhookOrderChange(event.change)\n ) {\n return false\n }\n\n if (event.collection !== event.change.scope.collection) {\n return false\n }\n\n if (\n event.change.scope.kind === 'collection' &&\n event.change.moved.collection !== event.change.scope.collection\n ) {\n return false\n }\n\n return true\n}\n\n/** Narrows a webhook event to a specific collection. */\nexport function isWebhookCollection<TCollection extends string>(\n event: unknown,\n collection: TCollection,\n): event is WebhookEvent<TCollection, unknown> {\n return isValidWebhookEvent(event) && event.collection === collection\n}\n\n/** Narrows a webhook event to a specific operation. */\nexport function isWebhookOperation<TOperation extends string>(\n event: unknown,\n operation: TOperation,\n): event is WebhookEvent<string, unknown> & { operation: TOperation } {\n return isValidWebhookEvent(event) && event.operation === operation\n}\n\nexport const CUSTOMER_PASSWORD_RESET_OPERATION = 'password-reset' as const\n\nexport type WebhookKnownOperation =\n | CollectionWebhookOperation\n | typeof CUSTOMER_PASSWORD_RESET_OPERATION\n\nexport interface CustomerPasswordResetWebhookData {\n customerId: string | number\n email: string\n name: string\n resetPasswordToken: string\n resetPasswordExpiresAt: string\n}\n\nexport type CustomerPasswordResetWebhookEvent = WebhookEvent<\n 'customers',\n CustomerPasswordResetWebhookData\n> & {\n operation: typeof CUSTOMER_PASSWORD_RESET_OPERATION\n}\n\nexport type CustomerAuthWebhookEvent = CustomerPasswordResetWebhookEvent\n\ntype MaybePromise<T> = T | Promise<T>\n\nexport interface CustomerAuthWebhookHandlers {\n passwordReset?: (\n data: CustomerPasswordResetWebhookData,\n event: CustomerPasswordResetWebhookEvent,\n ) => MaybePromise<void>\n unhandled?: (event: WebhookEvent<string, unknown>) => MaybePromise<void>\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\n}\n\nfunction hasString(value: Record<string, unknown>, key: string): boolean {\n return typeof value[key] === 'string'\n}\n\nfunction hasStringOrNumber(\n value: Record<string, unknown>,\n key: string,\n): boolean {\n return typeof value[key] === 'string' || typeof value[key] === 'number'\n}\n\nexport function isCustomerPasswordResetWebhookEvent(\n event: WebhookEvent<string, unknown>,\n): event is CustomerPasswordResetWebhookEvent {\n if (\n event.collection !== 'customers' ||\n event.operation !== CUSTOMER_PASSWORD_RESET_OPERATION ||\n !isRecord(event.data)\n ) {\n return false\n }\n\n return (\n hasStringOrNumber(event.data, 'customerId') &&\n hasString(event.data, 'email') &&\n hasString(event.data, 'name') &&\n hasString(event.data, 'resetPasswordToken') &&\n hasString(event.data, 'resetPasswordExpiresAt')\n )\n}\n\nexport function createCustomerAuthWebhookHandler(\n handlers: CustomerAuthWebhookHandlers,\n): WebhookHandler<string, unknown> {\n return async (event) => {\n if (isCustomerPasswordResetWebhookEvent(event) && handlers.passwordReset) {\n await handlers.passwordReset(event.data, event)\n return\n }\n\n await handlers.unhandled?.(event)\n }\n}\n\nasync function verifySignature(\n payload: string,\n secret: string,\n signature: string,\n timestamp: string,\n deliveryId: string,\n): Promise<boolean> {\n const encoder = new TextEncoder()\n const key = await crypto.subtle.importKey(\n 'raw',\n encoder.encode(secret),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['verify'],\n )\n // Validate and convert hex signature to Uint8Array\n if (signature.length % 2 !== 0 || !/^[0-9a-fA-F]*$/.test(signature)) {\n return false\n }\n const sigBytes = new Uint8Array(\n (signature.match(/.{2}/g) ?? []).map((byte) => parseInt(byte, 16)),\n )\n // crypto.subtle.verify performs constant-time comparison internally\n return crypto.subtle.verify(\n 'HMAC',\n key,\n sigBytes,\n encoder.encode(`${timestamp}.${deliveryId}.${payload}`),\n )\n}\n\nfunction timestampIsFresh(\n timestamp: string,\n toleranceSeconds: number,\n): boolean {\n if (!/^\\d+$/.test(timestamp)) return false\n const timestampMs = Number(timestamp)\n if (!Number.isFinite(timestampMs)) return false\n const skewMs = Math.abs(Date.now() - timestampMs)\n return skewMs <= toleranceSeconds * 1000\n}\n\nexport async function handleWebhook<\n T extends Collection | string = Collection,\n TData = T extends Collection ? CollectionType<T> : Record<string, unknown>,\n>(\n request: Request,\n handler: WebhookHandler<T, TData>,\n options?: WebhookOptions,\n): Promise<Response> {\n try {\n const rawBody = await request.text()\n\n if (options?.secret) {\n const signature = request.headers.get('x-webhook-signature') || ''\n const timestamp = request.headers.get('x-webhook-timestamp') || ''\n const deliveryId = request.headers.get('x-webhook-delivery-id') || ''\n const toleranceSeconds = options.toleranceSeconds ?? 300\n const valid =\n Boolean(timestamp && deliveryId) &&\n timestampIsFresh(timestamp, toleranceSeconds) &&\n (await verifySignature(\n rawBody,\n options.secret,\n signature,\n timestamp,\n deliveryId,\n ))\n if (!valid) {\n return new Response(\n JSON.stringify({ error: 'Invalid webhook signature' }),\n { status: 401, headers: { 'Content-Type': 'application/json' } },\n )\n }\n } else {\n console.warn(\n '[@01.software/sdk] Webhook signature verification is disabled. ' +\n 'Set { secret } in handleWebhook() options to enable HMAC-SHA256 verification.',\n )\n }\n\n const body = JSON.parse(rawBody)\n\n if (!isValidWebhookEvent(body)) {\n return new Response(\n JSON.stringify({ error: 'Invalid webhook event format' }),\n { status: 400, headers: { 'Content-Type': 'application/json' } },\n )\n }\n\n await handler(body as WebhookEvent<T, TData>)\n\n return new Response(\n JSON.stringify({ success: true, message: 'Webhook processed' }),\n { status: 200, headers: { 'Content-Type': 'application/json' } },\n )\n } catch (error) {\n console.error('Webhook processing error:', error)\n\n return new Response(JSON.stringify({ error: 'Internal server error' }), {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n })\n }\n}\n\nexport function createTypedWebhookHandler<T extends Collection>(\n collection: T,\n handler: (event: WebhookEvent<T>) => Promise<void> | void,\n): WebhookHandler<T> {\n return async (event: WebhookEvent<T>) => {\n if (event.collection !== collection) {\n throw new Error(\n `Expected collection \"${collection}\", got \"${event.collection}\"`,\n )\n }\n return handler(event)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACaO,IAAM,2BAA2B;AA8DjC,SAAS,oBAAoB,MAAqC;AACvE,MAAI,OAAO,SAAS,YAAY,SAAS,KAAM,QAAO;AACtD,QAAM,MAAM;AAC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