@shop-on/theme-server 0.10.0 → 0.11.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 (168) hide show
  1. package/dist/account-state.js +1 -2
  2. package/dist/account.d.ts +1 -3
  3. package/dist/account.js +1 -3
  4. package/dist/activity.d.ts +1 -3
  5. package/dist/activity.js +1 -2
  6. package/dist/analytics-proxy.d.ts +8 -14
  7. package/dist/analytics-proxy.js +111 -28
  8. package/dist/analytics-script-proxy.d.ts +1 -5
  9. package/dist/analytics-script-proxy.js +4 -14
  10. package/dist/api-contract/src/addresses.js +32 -0
  11. package/dist/api-contract/src/areas.js +49 -0
  12. package/dist/api-contract/src/custom-data.d.ts +31 -0
  13. package/dist/api-contract/src/custom-data.js +303 -0
  14. package/dist/api-contract/src/ids.js +110 -0
  15. package/dist/api-contract/src/image.js +65 -0
  16. package/dist/api-contract/src/limits.js +44 -0
  17. package/dist/api-contract/src/media.js +13 -0
  18. package/dist/api-contract/src/pickup.js +11 -0
  19. package/dist/api-contract/src/recommendations.js +4 -0
  20. package/dist/api-contract/src/shops.js +27 -0
  21. package/dist/api-contract/src/storefront/analytics.d.ts +100 -0
  22. package/dist/api-contract/src/storefront/analytics.js +138 -0
  23. package/dist/api-contract/src/storefront/areas.d.ts +2 -0
  24. package/dist/api-contract/src/storefront/cart.d.ts +132 -0
  25. package/dist/api-contract/src/storefront/cart.js +248 -0
  26. package/dist/api-contract/src/storefront/catalog.d.ts +3 -0
  27. package/dist/api-contract/src/storefront/checkout-analytics.d.ts +2 -0
  28. package/dist/api-contract/src/storefront/checkout.d.ts +2 -0
  29. package/dist/api-contract/src/storefront/checkout.js +624 -0
  30. package/dist/api-contract/src/storefront/client.d.ts +3 -0
  31. package/dist/api-contract/src/storefront/client.js +6 -0
  32. package/dist/api-contract/src/storefront/content.d.ts +3 -0
  33. package/dist/api-contract/src/storefront/custom-data.d.ts +2 -0
  34. package/dist/api-contract/src/storefront/custom-data.js +27 -0
  35. package/dist/api-contract/src/storefront/customer.d.ts +2 -0
  36. package/dist/api-contract/src/storefront/customer.js +261 -0
  37. package/dist/api-contract/src/storefront/downloads.d.ts +2 -0
  38. package/dist/api-contract/src/storefront/draft-order-invoice.d.ts +2 -0
  39. package/dist/api-contract/src/storefront/forms.d.ts +2 -0
  40. package/dist/api-contract/src/storefront/forms.js +82 -0
  41. package/dist/api-contract/src/storefront/index.d.ts +20956 -0
  42. package/dist/api-contract/src/storefront/orders.d.ts +2 -0
  43. package/dist/api-contract/src/storefront/policies.d.ts +2 -0
  44. package/dist/api-contract/src/storefront/procedure.d.ts +2 -0
  45. package/dist/api-contract/src/storefront/procedure.js +29 -0
  46. package/dist/api-contract/src/storefront/reviews.d.ts +20 -0
  47. package/dist/api-contract/src/storefront/search.d.ts +3 -0
  48. package/dist/api-contract/src/storefront/seo.d.ts +2 -0
  49. package/dist/api-contract/src/storefront/seo.js +132 -0
  50. package/dist/api-contract/src/storefront/shop.d.ts +2 -0
  51. package/dist/api-contract/src/storefront/shop.js +101 -0
  52. package/dist/api-contract/src/taxonomy.js +5 -0
  53. package/dist/api-contract/src/text.js +15 -0
  54. package/dist/api-contract/src/theme-documents.js +13 -0
  55. package/dist/api-contract/src/theme-translations.d.ts +14 -0
  56. package/dist/api-contract/src/theme-translations.js +30 -0
  57. package/dist/api-contract/src/video.js +19 -0
  58. package/dist/availability.d.ts +6 -3
  59. package/dist/availability.js +11 -5
  60. package/dist/blog.d.ts +53 -59
  61. package/dist/blog.js +197 -497
  62. package/dist/cache.d.ts +5 -6
  63. package/dist/cache.js +1 -2
  64. package/dist/canonical-host.d.ts +4 -6
  65. package/dist/canonical-host.js +5 -6
  66. package/dist/card.js +159 -0
  67. package/dist/cart-customer.d.ts +1 -3
  68. package/dist/cart-customer.js +64 -105
  69. package/dist/cart-mutations.d.ts +43 -77
  70. package/dist/cart-mutations.js +106 -232
  71. package/dist/cart-recommendations.d.ts +1 -3
  72. package/dist/cart-recommendations.js +1 -2
  73. package/dist/cart-session.d.ts +1 -3
  74. package/dist/cart-session.js +1 -2
  75. package/dist/cart.d.ts +63 -224
  76. package/dist/cart.js +70 -197
  77. package/dist/checkout.d.ts +13 -17
  78. package/dist/checkout.js +75 -101
  79. package/dist/coalesce.js +57 -0
  80. package/dist/collection.d.ts +89 -298
  81. package/dist/collection.js +210 -656
  82. package/dist/contact.d.ts +20 -10
  83. package/dist/contact.js +36 -30
  84. package/dist/content-version.d.ts +37 -21
  85. package/dist/content-version.js +64 -42
  86. package/dist/contract-kit/src/client.d.ts +12 -0
  87. package/dist/contract-kit/src/client.js +156 -0
  88. package/dist/contract-kit/src/errors.d.ts +1 -0
  89. package/dist/contract-kit/src/errors.js +81 -0
  90. package/dist/contract-kit/src/ids.d.ts +1 -0
  91. package/dist/contract-kit/src/ids.js +118 -0
  92. package/dist/contract-kit/src/index.d.ts +7 -0
  93. package/dist/contract-kit/src/money.d.ts +1 -0
  94. package/dist/contract-kit/src/money.js +10 -0
  95. package/dist/contract-kit/src/pagination.d.ts +1 -0
  96. package/dist/contract-kit/src/procedure.d.ts +69 -0
  97. package/dist/contract-kit/src/procedure.js +16 -0
  98. package/dist/contract-kit/src/realtime.d.ts +1 -0
  99. package/dist/cookie-secret.js +1 -2
  100. package/dist/csrf.js +1 -2
  101. package/dist/customer-handoff.d.ts +1 -3
  102. package/dist/customer-handoff.js +10 -25
  103. package/dist/customer-session.d.ts +1 -3
  104. package/dist/customer-session.js +1 -2
  105. package/dist/customer.d.ts +2 -3
  106. package/dist/customer.js +27 -44
  107. package/dist/files.d.ts +49 -10
  108. package/dist/files.js +106 -89
  109. package/dist/fonts.d.ts +3 -5
  110. package/dist/fonts.js +16 -35
  111. package/dist/html.d.ts +1 -3
  112. package/dist/html.js +1 -2
  113. package/dist/liquid.d.ts +4 -10
  114. package/dist/liquid.js +25 -32
  115. package/dist/listing.js +79 -0
  116. package/dist/marketing-cookies.d.ts +1 -3
  117. package/dist/marketing-cookies.js +1 -2
  118. package/dist/menu.d.ts +46 -155
  119. package/dist/menu.js +51 -61
  120. package/dist/metafields.d.ts +9 -5
  121. package/dist/metafields.js +10 -38
  122. package/dist/metaobject.d.ts +10 -5
  123. package/dist/metaobject.js +43 -66
  124. package/dist/money.d.ts +7 -0
  125. package/dist/money.js +18 -0
  126. package/dist/newsletter.d.ts +19 -10
  127. package/dist/newsletter.js +31 -25
  128. package/dist/page.d.ts +13 -17
  129. package/dist/page.js +49 -105
  130. package/dist/password-session.d.ts +1 -3
  131. package/dist/password-session.js +1 -2
  132. package/dist/password.d.ts +25 -18
  133. package/dist/password.js +41 -59
  134. package/dist/policy.d.ts +7 -7
  135. package/dist/policy.js +19 -55
  136. package/dist/product.d.ts +42 -67
  137. package/dist/product.js +144 -644
  138. package/dist/read-ahead.d.ts +18 -0
  139. package/dist/read-ahead.js +32 -0
  140. package/dist/recommendations.d.ts +6 -12
  141. package/dist/recommendations.js +36 -60
  142. package/dist/review.d.ts +134 -94
  143. package/dist/review.js +257 -469
  144. package/dist/search.d.ts +59 -64
  145. package/dist/search.js +170 -469
  146. package/dist/seo-context.d.ts +1 -3
  147. package/dist/seo-context.js +4 -5
  148. package/dist/seo-documents.d.ts +50 -0
  149. package/dist/seo-documents.js +149 -0
  150. package/dist/shop-seo.d.ts +3 -5
  151. package/dist/shop-seo.js +7 -26
  152. package/dist/shop.d.ts +38 -42
  153. package/dist/shop.js +37 -51
  154. package/dist/store-availability.d.ts +12 -14
  155. package/dist/store-availability.js +18 -56
  156. package/dist/storefront.js +199 -0
  157. package/dist/structured-data.d.ts +3 -28
  158. package/dist/structured-data.js +19 -49
  159. package/dist/trace.js +1 -2
  160. package/dist/translations.d.ts +26 -31
  161. package/dist/translations.js +55 -28
  162. package/package.json +16 -14
  163. package/dist/graphql-env.d.ts +0 -22778
  164. package/dist/graphql.d.ts +0 -64
  165. package/dist/graphql.js +0 -344
  166. package/dist/schema.storefront.graphql +0 -10483
  167. package/dist/seo-proxy.d.ts +0 -11
  168. package/dist/seo-proxy.js +0 -26
package/dist/cache.d.ts CHANGED
@@ -1,4 +1,3 @@
1
- //#region src/cache.d.ts
2
1
  export declare const DEFAULT_TTL_MS = 60000;
3
2
  export declare function __memoSizeForTesting(memo: object): number;
4
3
  export declare function memoTTL<Args extends unknown[], T>(fn: (...args: Args) => Promise<T>, opts?: {
@@ -11,13 +10,13 @@ export declare function memoTTL<Args extends unknown[], T>(fn: (...args: Args) =
11
10
  shouldCache?: (value: T, ...args: Args) => boolean;
12
11
  /** Resolves a cache-busting version that is prepended to the key. When it
13
12
  * changes (a storefront content write bumped it), prior entries are
14
- * bypassed under their old key and age out via the TTL. Must not throw —
15
- * resolve a stable fallback on failure so a Redis blip can't reject the
16
- * loader. Omitting it preserves the original synchronous behaviour. */
13
+ * bypassed under their old key and age out via the TTL. Must not throw on
14
+ * a blip — resolve a stable fallback so an api outage can't reject the
15
+ * loader; what it throws (a refused storefront key) rejects the call.
16
+ * Omitting it preserves the original synchronous behaviour. */
17
17
  version?: () => Promise<string>;
18
18
  /** How long a miss holds its key before a waiting request takes over. */
19
19
  leaseMs?: number;
20
20
  /** Most entries kept; past it the oldest is dropped. */
21
21
  maxEntries?: number;
22
- }): (...args: Args) => Promise<T>;
23
- //#endregion
22
+ }): (...args: Args) => Promise<T>;
package/dist/cache.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createLease } from "./lease.js";
2
- //#region src/cache.ts
2
+ // src/cache.ts
3
3
  const DEFAULT_TTL_MS = 6e4;
4
4
  const DEFAULT_MAX_ENTRIES = 500;
5
5
  const memoSizes = /* @__PURE__ */ new WeakMap();
@@ -56,5 +56,4 @@ function memoTTL(fn, opts = {}) {
56
56
  memoSizes.set(memoized, () => cache.size);
57
57
  return memoized;
58
58
  }
59
- //#endregion
60
59
  export { DEFAULT_TTL_MS, __memoSizeForTesting, memoTTL };
@@ -1,10 +1,9 @@
1
- //#region src/canonical-host.d.ts
2
1
  export interface CanonicalHostInput {
3
2
  /** Public-facing origin of the request (scheme + host + any port), as
4
3
  * resolved from the `x-forwarded-*` headers — never the shard-internal URL. */
5
4
  requestOrigin: string;
6
- /** `shop.primaryDomain.fqdn`, or null/undefined when the shop has none. */
7
- primaryFqdn: string | null | undefined;
5
+ /** `shop.primaryDomain.hostname`, or null/undefined when the shop has none. */
6
+ primaryHostname: string | null | undefined;
8
7
  }
9
8
  /**
10
9
  * The origin this page should call its own: the primary domain when the shop
@@ -15,12 +14,11 @@ export interface CanonicalHostInput {
15
14
  * Returns `requestOrigin` unchanged for anything it cannot improve on — a shop
16
15
  * with no primary domain, a preview host, or an unparseable origin.
17
16
  */
18
- export declare function canonicalOrigin({ requestOrigin, primaryFqdn }: CanonicalHostInput): string;
17
+ export declare function canonicalOrigin({ requestOrigin, primaryHostname }: CanonicalHostInput): string;
19
18
  /**
20
19
  * Absolute URL to redirect this request to, or null when it is already on the
21
20
  * canonical host (or on a host that must not be redirected). `pathWithSearch`
22
21
  * is taken verbatim — the caller owns locale rewriting, exactly as the
23
22
  * post-auth and password redirects in the themes' roots do.
24
23
  */
25
- export declare function canonicalRedirectTarget(input: CanonicalHostInput, pathWithSearch: string): string | null;
26
- //#endregion
24
+ export declare function canonicalRedirectTarget(input: CanonicalHostInput, pathWithSearch: string): string | null;
@@ -1,4 +1,4 @@
1
- //#region src/canonical-host.ts
1
+ // src/canonical-host.ts
2
2
  const PREVIEW_HOST_SEPARATOR = "--";
3
3
  /**
4
4
  * The origin this page should call its own: the primary domain when the shop
@@ -9,17 +9,17 @@ const PREVIEW_HOST_SEPARATOR = "--";
9
9
  * Returns `requestOrigin` unchanged for anything it cannot improve on — a shop
10
10
  * with no primary domain, a preview host, or an unparseable origin.
11
11
  */
12
- function canonicalOrigin({ requestOrigin, primaryFqdn }) {
13
- if (!primaryFqdn) return requestOrigin;
12
+ function canonicalOrigin({ requestOrigin, primaryHostname }) {
13
+ if (!primaryHostname) return requestOrigin;
14
14
  let url;
15
15
  try {
16
16
  url = new URL(requestOrigin);
17
17
  } catch {
18
18
  return requestOrigin;
19
19
  }
20
- if (url.hostname === primaryFqdn) return requestOrigin;
20
+ if (url.hostname === primaryHostname) return requestOrigin;
21
21
  if (isPreviewHost(url.hostname)) return requestOrigin;
22
- return `${url.protocol}//${primaryFqdn}${url.port ? `:${url.port}` : ""}`;
22
+ return `${url.protocol}//${primaryHostname}${url.port ? `:${url.port}` : ""}`;
23
23
  }
24
24
  /**
25
25
  * Absolute URL to redirect this request to, or null when it is already on the
@@ -35,5 +35,4 @@ function canonicalRedirectTarget(input, pathWithSearch) {
35
35
  function isPreviewHost(hostname) {
36
36
  return (hostname.split(".")[0] ?? "").includes(PREVIEW_HOST_SEPARATOR);
37
37
  }
38
- //#endregion
39
38
  export { canonicalOrigin, canonicalRedirectTarget };
package/dist/card.js ADDED
@@ -0,0 +1,159 @@
1
+ import { liteId } from "./api-contract/src/ids.js";
2
+ import { imageUrl } from "./api-contract/src/image.js";
3
+ import { metafieldRef } from "./api-contract/src/storefront/custom-data.js";
4
+ import { coalescedReads } from "./coalesce.js";
5
+ import { imageFileInfo, mediaFileInfo } from "./files.js";
6
+ import { customDataMap, metafieldKeysKey } from "./metafields.js";
7
+ import { toMoney } from "./money.js";
8
+ import { storefront } from "./storefront.js";
9
+ /** Media a card carries: its lead, and enough for a hover gallery. */
10
+ const CARD_MEDIA = 5;
11
+ /** A product by handle, or by id (a `prod_…` TypeID, as a product
12
+ * reference's value holds it). Any other id is read as a handle, so a legacy
13
+ * `gid://` matches nothing. */
14
+ function productRef(ref) {
15
+ const id = liteId("prod").safeParse(ref);
16
+ return id.success ? { productId: id.data } : { handle: ref };
17
+ }
18
+ /** A swatch image drawn at most 128px square, as legacy's swatch reads were. */
19
+ const SWATCH_SIZE = 128;
20
+ /** A swatch's image (an option value's, a facet value's) at swatch size. */
21
+ function swatchImageUrl(image) {
22
+ return imageUrl(image, {
23
+ width: SWATCH_SIZE,
24
+ height: SWATCH_SIZE,
25
+ fit: "scale-down"
26
+ });
27
+ }
28
+ function toSwatch(swatch) {
29
+ if (!swatch) return null;
30
+ return {
31
+ color: swatch.color,
32
+ image: swatch.image ? swatchImageUrl(swatch.image) : null
33
+ };
34
+ }
35
+ /** The options a page's picker and a card's swatch row read. */
36
+ function toOption(option, index) {
37
+ return {
38
+ id: option.id,
39
+ name: option.name,
40
+ position: index + 1,
41
+ values: option.values.map((value, at) => ({
42
+ id: value.id,
43
+ name: value.name,
44
+ position: at + 1,
45
+ hasVariants: value.variant !== null,
46
+ swatch: toSwatch(value.swatch)
47
+ }))
48
+ };
49
+ }
50
+ function compareAt(price) {
51
+ return price === null ? null : toMoney(price);
52
+ }
53
+ /** The variant a card's swatch switches to: its price, compare-at, SKU,
54
+ * stock, and its image as an id into the card's `variantMedia`. */
55
+ function toSwatchVariant(variant) {
56
+ return {
57
+ id: variant.id,
58
+ availableForSale: variant.available,
59
+ sku: variant.sku,
60
+ priceV2: toMoney(variant.price),
61
+ compareAtV2: compareAt(variant.compareAtPrice),
62
+ featuredMedia: variant.image ? { id: variant.image.id } : null
63
+ };
64
+ }
65
+ /** A card's options, each value carrying the variant its swatch selects. */
66
+ function cardOption(option, index) {
67
+ const base = toOption(option, index);
68
+ return {
69
+ ...base,
70
+ values: base.values.map((value, at) => {
71
+ const variant = option.values[at].variant;
72
+ return {
73
+ ...value,
74
+ firstSelectableVariant: variant && toSwatchVariant(variant)
75
+ };
76
+ })
77
+ };
78
+ }
79
+ /** The images a card's swatches switch to, once each: the card's `media` is
80
+ * capped too short to carry them. */
81
+ function swatchMedia(options) {
82
+ const images = /* @__PURE__ */ new Map();
83
+ for (const option of options) for (const value of option.values) {
84
+ const image = value.variant?.image;
85
+ if (image && !images.has(image.id)) images.set(image.id, image);
86
+ }
87
+ return [...images.values()].map((image) => imageFileInfo(image, 480));
88
+ }
89
+ function toMedia(media, baseWidth) {
90
+ return media.map((m) => mediaFileInfo(m, baseWidth)).filter((m) => m !== null);
91
+ }
92
+ /** What every card and the page share. */
93
+ function cardFields(p, baseWidth) {
94
+ return {
95
+ id: p.id,
96
+ handle: p.handle,
97
+ title: p.title,
98
+ vendor: p.vendor,
99
+ product_type: p.productType,
100
+ tags: p.badgeTags,
101
+ available: p.available,
102
+ price: toMoney(p.defaultVariant.price),
103
+ compare_at: compareAt(p.defaultVariant.compareAtPrice),
104
+ defaultVariantId: p.defaultVariant.id,
105
+ defaultVariantTitle: p.defaultVariant.title,
106
+ sku: p.defaultVariant.sku,
107
+ variantsCount: p.variantsCount,
108
+ media: toMedia(p.media, baseWidth),
109
+ rating: p.rating && {
110
+ value: p.rating.value,
111
+ count: p.rating.count
112
+ }
113
+ };
114
+ }
115
+ /** A card as every card surface and listing grid reads it. */
116
+ function toCard(c) {
117
+ return {
118
+ ...cardFields(c, 480),
119
+ ...c.options ? {
120
+ options: c.options.map(cardOption),
121
+ variantMedia: swatchMedia(c.options)
122
+ } : {},
123
+ ...c.metafields ? { metafields: customDataMap(c.metafields) } : {},
124
+ ...c.descriptionText !== null ? { descriptionPlain: c.descriptionText } : {}
125
+ };
126
+ }
127
+ /** What a card read asks for: a section names its card's shape, so a grid
128
+ * that renders no swatch never pays for options. */
129
+ function cardShape(shape) {
130
+ return {
131
+ media: shape.media ?? CARD_MEDIA,
132
+ options: shape.options ?? false,
133
+ metafieldKeys: (shape.metafieldKeys ?? []).filter((k) => metafieldRef.safeParse(k).success),
134
+ description: shape.description ?? false
135
+ };
136
+ }
137
+ /** A shape as a cache key's part. */
138
+ function shapeKey(shape) {
139
+ return `${shape.media}|${shape.options}|${shape.description}|${metafieldKeysKey(shape.metafieldKeys)}`;
140
+ }
141
+ const coalescedCard = coalescedReads({
142
+ max: 50,
143
+ matches: (card, ref) => {
144
+ const named = productRef(ref);
145
+ return "productId" in named ? card.id === named.productId : card.handle === named.handle;
146
+ }
147
+ });
148
+ /** One product's card, in a `products.cards` call shared with the other card
149
+ * reads of this request's tick in the same language and shape. Null when a
150
+ * buyer may not see it. */
151
+ function readCard(ref, shape, locale) {
152
+ return coalescedCard(`${locale ?? ""}|${shapeKey(shape)}`, ref, async (refs) => {
153
+ return (await storefront(locale).products.cards({
154
+ refs: refs.map(productRef),
155
+ card: shape
156
+ })).items;
157
+ });
158
+ }
159
+ export { cardFields, cardShape, compareAt, productRef, readCard, shapeKey, swatchImageUrl, toCard, toOption };
@@ -1,6 +1,5 @@
1
1
  import { CartData } from "./cart.js";
2
2
  import { CartFailure } from "./cart-mutations.js";
3
- //#region src/cart-customer.d.ts
4
3
  export type CartCustomerCookieSession = {
5
4
  data: {
6
5
  token?: string;
@@ -22,5 +21,4 @@ export declare function mintOrClaimCart(args: {
22
21
  }): Promise<{
23
22
  ok: true;
24
23
  token: string;
25
- } | CartFailure>;
26
- //#endregion
24
+ } | CartFailure>;
@@ -1,126 +1,85 @@
1
- import { graphql, request } from "./graphql.js";
2
- import { CartByTokenQuery, CartFields, decodeCart, readCartFields } from "./cart.js";
3
- import { mintCart, unwrapCartPayload } from "./cart-mutations.js";
4
- //#region src/cart-customer.ts
5
- const CartAttachToCustomerMutation = graphql(`
6
- mutation CartAttachToCustomer($cartToken: String!) {
7
- cartAttachToCustomer(input: { cartToken: $cartToken }) {
8
- cart {
9
- ...CartFields
10
- }
11
- userErrors {
12
- code
13
- field
14
- message
15
- }
16
- }
17
- }
18
- `, [CartFields]);
19
- const CartClaimMutation = graphql(`
20
- mutation CartClaim {
21
- cartClaim(input: {}) {
22
- cart {
23
- ...CartFields
24
- }
25
- cartToken
26
- userErrors {
27
- code
28
- field
29
- message
30
- }
31
- }
32
- }
33
- `, [CartFields]);
34
- function requestOptions(customerToken, locale) {
35
- return locale ? {
36
- customerSessionToken: customerToken,
37
- acceptLanguage: locale
38
- } : { customerSessionToken: customerToken };
1
+ import { isCartGone, toCart } from "./cart.js";
2
+ import { mintCart } from "./cart-mutations.js";
3
+ import { StorefrontConfigError, buyerStorefront, errorCode } from "./storefront.js";
4
+ // src/cart-customer.ts
5
+ /** What `cart.attach` answers about the carts themselves: the guest cart is
6
+ * gone, another customer's, or cannot take the buyer's lines. Anything else
7
+ * (the api down, a stale buyer session) says nothing about them. */
8
+ const ATTACH_REFUSALS = /* @__PURE__ */ new Set([
9
+ "NOT_FOUND",
10
+ "PRECONDITION_FAILED",
11
+ "INSUFFICIENT_INVENTORY",
12
+ "LIMIT_EXCEEDED"
13
+ ]);
14
+ function unexpected(op, error) {
15
+ if (error instanceof StorefrontConfigError) throw error;
16
+ console.warn(`[cart] ${op} failed: ${errorCode(error) ?? String(error)}`);
39
17
  }
40
18
  async function resolveCartForCustomer(args) {
41
19
  const { session, customerToken, locale } = args;
20
+ const api = buyerStorefront(customerToken, locale);
42
21
  const cookieToken = session.data.token;
43
- const opts = requestOptions(customerToken, locale);
44
- let raw = null;
45
- let readFailed = false;
46
- if (cookieToken) try {
47
- raw = (await request(CartByTokenQuery, { cartToken: cookieToken }, opts)).cart ?? null;
48
- } catch (err) {
49
- readFailed = true;
50
- console.warn("[cart] resolveCartForCustomer read failed:", err);
51
- }
52
- if (!raw) {
53
- if (readFailed) return null;
54
- return await claimAndStore(session, customerToken, locale);
22
+ if (!cookieToken) return claimed(await claim(session, api));
23
+ let read;
24
+ try {
25
+ read = await api.cart.get({ token: cookieToken });
26
+ } catch (error) {
27
+ if (isCartGone(error)) return claimed(await claim(session, api));
28
+ unexpected("cart read", error);
29
+ return null;
55
30
  }
56
- const read = readCartFields(raw);
57
- if (read.attachedToCurrentCustomer) return read.cart;
58
- if (!read.hasCustomer) {
59
- try {
60
- const attachResult = await request(CartAttachToCustomerMutation, { cartToken: cookieToken }, opts);
61
- const unwrapped = unwrapCartPayload(attachResult.cartAttachToCustomer);
62
- if (unwrapped.ok) return decodeCart(unwrapped.cart);
63
- } catch (err) {
64
- console.warn("[cart] resolveCartForCustomer attach failed:", err);
65
- return read.cart;
66
- }
67
- return await claimAndStore(session, customerToken, locale);
31
+ if (read.owner === "you") return toCart(read);
32
+ if (read.owner === "other") return claimed(await claim(session, api));
33
+ try {
34
+ return toCart(await api.cart.attach({ token: cookieToken }));
35
+ } catch (error) {
36
+ if (ATTACH_REFUSALS.has(errorCode(error) ?? "")) return claimed(await claim(session, api));
37
+ unexpected("attach", error);
38
+ return toCart(read);
68
39
  }
69
- return await claimAndStore(session, customerToken, locale);
70
40
  }
71
41
  async function mintOrClaimCart(args) {
72
42
  const { session, customerToken } = args;
73
43
  if (customerToken) {
74
- const claimed = await claim(session, customerToken);
75
- if (claimed) return {
44
+ const claimedCart = await claim(session, buyerStorefront(customerToken));
45
+ if (claimedCart) return {
76
46
  ok: true,
77
- token: claimed.token
47
+ token: claimedCart.token
78
48
  };
79
49
  }
80
50
  const minted = await mintCart(customerToken);
81
- if (minted.ok) {
82
- await session.update({
83
- token: minted.token,
84
- expiresAtMs: Date.parse(minted.expiresAt)
85
- });
86
- return {
87
- ok: true,
88
- token: minted.token
89
- };
90
- }
91
- if (minted.code === "CART_EXISTS" && customerToken) {
92
- const reclaimed = await claim(session, customerToken);
93
- if (reclaimed) return {
94
- ok: true,
95
- token: reclaimed.token
96
- };
97
- }
98
- return minted;
51
+ if (!minted.ok) return minted;
52
+ await session.update({
53
+ token: minted.token,
54
+ expiresAtMs: Date.parse(minted.expiresAt)
55
+ });
56
+ return {
57
+ ok: true,
58
+ token: minted.token
59
+ };
99
60
  }
100
- async function claim(session, customerToken, locale) {
61
+ async function claim(session, api) {
62
+ let answer;
101
63
  try {
102
- const payload = (await request(CartClaimMutation, {}, requestOptions(customerToken, locale))).cartClaim;
103
- const unwrapped = unwrapCartPayload(payload);
104
- if (!unwrapped.ok || !payload?.cartToken) {
105
- if (session.data.token) await session.clear();
106
- return null;
107
- }
108
- const read = readCartFields(unwrapped.cart);
109
- await session.update({
110
- token: payload.cartToken,
111
- expiresAtMs: Date.parse(read.expiresAt)
112
- });
113
- return {
114
- token: payload.cartToken,
115
- cart: read.cart
116
- };
117
- } catch (err) {
118
- console.warn("[cart] cartClaim failed:", err);
64
+ answer = await api.cart.claim({});
65
+ } catch (error) {
66
+ unexpected("claim", error);
67
+ return null;
68
+ }
69
+ if (!answer.token || !answer.cart) {
70
+ if (session.data.token) await session.clear();
119
71
  return null;
120
72
  }
73
+ await session.update({
74
+ token: answer.token,
75
+ expiresAtMs: Date.parse(answer.cart.expiresAt)
76
+ });
77
+ return {
78
+ token: answer.token,
79
+ cart: toCart(answer.cart)
80
+ };
121
81
  }
122
- async function claimAndStore(session, customerToken, locale) {
123
- return (await claim(session, customerToken, locale))?.cart ?? null;
82
+ function claimed(result) {
83
+ return result?.cart ?? null;
124
84
  }
125
- //#endregion
126
85
  export { mintOrClaimCart, resolveCartForCustomer };
@@ -1,115 +1,81 @@
1
- import { CartData, CartFields } from "./cart.js";
2
- import { FragmentOf, VariablesOf } from "gql.tada";
3
- //#region src/cart-mutations.d.ts
4
- export type CartUserError = {
5
- code: string;
6
- field: string | null;
7
- message: string;
8
- };
1
+ import { CartData } from "./cart.js";
2
+ /**
3
+ * Why a write was refused. `code` is the api's, or one of the adapter's:
4
+ * - `NOT_FOUND`: `resource` names what the call named and is not there.
5
+ * `"cart"`: the cookie's cart is gone (expired, placed, merged), and the op
6
+ * cleared the cookie, so the next add opens a new one. `"variant"`: the
7
+ * variant is not on the store. `"cart_line"`: a stale line id.
8
+ * - `INSUFFICIENT_INVENTORY`: the variant cannot sell what the cart would ask of it.
9
+ * - `LIMIT_EXCEEDED`: the cart is at its line cap.
10
+ * - `CART_PAYING`: the buyer is paying for this cart at checkout; it cannot change.
11
+ * - `VALIDATION_FAILED`, `RATE_LIMITED`: the api's.
12
+ * - `REQUEST_FAILED`: anything else (a timeout, the api down); logged.
13
+ * A theme's own guards answer their own codes (`INVALID_QUANTITY`).
14
+ */
9
15
  export type CartFailure = {
10
16
  ok: false;
11
17
  code: string;
12
- field: string | null;
18
+ resource: string | null;
13
19
  message: string;
14
20
  };
15
21
  export type CartActionResult = {
16
22
  ok: true;
17
23
  cart: CartData;
18
24
  } | CartFailure;
19
- /** Only `.clear()` is ever called by these ops; typed structurally so the
20
- * module doesn't couple to `useCartSession`'s full return type. Themes pass
21
- * the `useCartSession()` result straight through. */
25
+ /** Only `.clear()` is ever called; typed structurally so a theme passes its
26
+ * `useCartSession()` result straight through. */
22
27
  export type CartCookieSession = {
23
28
  clear: () => Promise<unknown>;
24
29
  };
25
- declare const CartLinesAddMutation: import("gql.tada").TadaDocumentNode<{
26
- cartLinesAdd: {
27
- cart: {
28
- [$tada.fragmentRefs]: {
29
- CartFields: "ShopCart";
30
- };
31
- } | null;
32
- userErrors: {
33
- code: string;
34
- field: string | null;
35
- message: string;
36
- }[];
37
- } | null;
38
- }, {
39
- cartToken: string;
40
- lines: {
41
- customAttributes?: {
42
- name: string;
43
- value: string;
44
- visible?: boolean | null | undefined;
45
- }[] | null | undefined;
46
- quantity: number;
47
- variantId: string;
48
- }[];
49
- }, void>;
50
- type CartMutationPayload = {
51
- cart?: FragmentOf<typeof CartFields> | null;
52
- userErrors: ReadonlyArray<CartUserError>;
53
- };
54
- export declare function unwrapCartPayload(payload: CartMutationPayload | null | undefined): {
55
- ok: true;
56
- cart: FragmentOf<typeof CartFields>;
57
- } | {
58
- ok: false;
59
- error: CartUserError;
60
- };
61
- /** Mint a fresh cart via `cartCreate`. When `customerToken` is present the
62
- * cart is born attached to that customer. Returns the plaintext token + the
63
- * server-authoritative `expiresAt` so the caller can write its cookie; never
64
- * touches the cookie itself. */
65
- export declare function mintCart(customerToken?: string): Promise<{
30
+ /** Open a new, empty cart, the signed-in buyer's when `buyerSession` is
31
+ * given. Answers its token and when it expires (30 days, never extended) for
32
+ * the caller's cookie; never touches the cookie itself. */
33
+ export declare function mintCart(buyerSession?: string): Promise<{
66
34
  ok: true;
67
35
  token: string;
68
36
  expiresAt: string;
69
- } | {
70
- ok: false;
71
- code: string;
72
- field: string | null;
73
- message: string;
74
- }>;
37
+ } | CartFailure>;
38
+ /** A line to add: a variant, how many, and the buyer's line properties
39
+ * (`visible: false` is kept for the merchant and never shown back). Lines of
40
+ * the same variant and properties merge on the api. */
41
+ export type CartLineInput = {
42
+ variantId: string;
43
+ quantity: number;
44
+ customAttributes?: {
45
+ name: string;
46
+ value: string;
47
+ visible?: boolean;
48
+ }[];
49
+ };
50
+ /** Add lines, all or nothing. */
75
51
  export declare function addLines(args: {
76
52
  session: CartCookieSession;
77
53
  token: string;
78
- customerToken?: string;
79
- lines: VariablesOf<typeof CartLinesAddMutation>["lines"];
54
+ lines: CartLineInput[];
80
55
  }): Promise<CartActionResult>;
81
56
  export declare function removeLines(args: {
82
57
  session: CartCookieSession;
83
58
  token: string;
84
- customerToken?: string;
85
59
  lineIds: string[];
86
60
  }): Promise<CartActionResult>;
87
61
  /**
88
- * Set a single line's quantity. Owns the invariant that quantity ≤ 0 is a
89
- * REMOVE (the DB CHECK constraint rejects 0) so no caller has to re-remember
90
- * it — a qty stepper can drive this straight down to 0 without hitting a raw
91
- * constraint error. This is the op cart UIs should call for a quantity change;
92
- * `updateLines` (batch) stays internal.
62
+ * Set one line's quantity. A quantity of 0 or less removes the line (the api
63
+ * takes a quantity of at least 1), so a stepper can go straight down to 0.
64
+ * The op cart UIs call for a quantity change.
93
65
  */
94
66
  export declare function setLineQuantity(args: {
95
67
  session: CartCookieSession;
96
68
  token: string;
97
- customerToken?: string;
98
69
  lineId: string;
99
70
  quantity: number;
100
71
  }): Promise<CartActionResult>;
101
72
  /**
102
- * Set or clear the buyer's cart note. A blank note CLEARS it: the API treats
103
- * null and whitespace alike, and sending null keeps "no note" one state rather
104
- * than two. The server trims the text and caps it at 1000 characters
105
- * (`VALIDATION_ERROR`, `field: "note"`); a theme's field mirrors the cap as
106
- * `maxLength`.
73
+ * Set or clear the buyer's cart note. The api trims it, and a blank one clears
74
+ * it; it refuses one past `CART_NOTE_MAX_LENGTH` (`VALIDATION_FAILED`), which a
75
+ * theme's field mirrors as `maxLength`.
107
76
  */
108
77
  export declare function setNote(args: {
109
78
  session: CartCookieSession;
110
79
  token: string;
111
- customerToken?: string;
112
80
  note: string;
113
- }): Promise<CartActionResult>;
114
- //#endregion
115
- export {};
81
+ }): Promise<CartActionResult>;