@shop-on/theme-server 0.9.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/review.js CHANGED
@@ -1,531 +1,319 @@
1
+ import { liteId } from "./api-contract/src/ids.js";
2
+ import { REVIEW_PHOTO_TYPES } from "./api-contract/src/limits.js";
1
3
  import { memoTTL } from "./cache.js";
2
- import { graphql, request, requestUpload } from "./graphql.js";
4
+ import { coalescedReads } from "./coalesce.js";
3
5
  import { getContentVersion } from "./content-version.js";
4
- import { toFileInfo } from "./files.js";
6
+ import { imageFileInfo } from "./files.js";
7
+ import { pageInput } from "./listing.js";
5
8
  import { readCustomerSession } from "./customer-session.js";
6
- //#region src/review.ts
9
+ import { buyerStorefront, errorCode, invalidField, orFallback, orNotFound, storefront } from "./storefront.js";
10
+ // src/review.ts
11
+ const PRODUCT_THUMB_WIDTH = 160;
7
12
  const REVIEW_MEDIA_WIDTH = 640;
8
13
  const REVIEW_THUMB_WIDTH = 160;
9
- function widthSrcset(url, url2x, width) {
10
- if (!url || !url2x || url === url2x) return null;
11
- return `${url} ${width}w, ${url2x} ${width * 2}w`;
14
+ function toMedia(photo) {
15
+ const display = imageFileInfo(photo, REVIEW_MEDIA_WIDTH);
16
+ const thumb = imageFileInfo(photo, REVIEW_THUMB_WIDTH);
17
+ return {
18
+ id: photo.id,
19
+ url: display.url,
20
+ srcset: display.srcset,
21
+ thumbUrl: thumb.url,
22
+ thumbSrcset: thumb.srcset,
23
+ width: photo.width,
24
+ height: photo.height,
25
+ thumbhash: photo.thumbhash
26
+ };
12
27
  }
13
- const ReviewCoreFields = graphql(`
14
- fragment ReviewCoreFields on ShopProductReview @_unmask {
15
- id
16
- rating
17
- title
18
- body
19
- authorName
20
- verified
21
- createdAt
22
- upvoteCount
23
- downvoteCount
24
- media {
25
- id
26
- url(transform: { maxWidth: 640 })
27
- url2x: url(transform: { maxWidth: 640, scale: 2 })
28
- thumbUrl: url(transform: { maxWidth: 160 })
29
- thumbUrl2x: url(transform: { maxWidth: 160, scale: 2 })
30
- width
31
- height
32
- thumbhash
33
- }
34
- merchantReply {
35
- body
36
- repliedAt
37
- }
38
- attributes {
39
- definitionId
40
- name
41
- fieldType
42
- value
43
- valueLabel
44
- }
45
- }
46
- `);
47
- const ReviewFields = graphql(`
48
- fragment ReviewFields on ShopProductReview @_unmask {
49
- ...ReviewCoreFields
50
- product {
51
- handle
52
- title
53
- status
54
- featuredMedia {
55
- __typename
56
- id
57
- alt
58
- thumbhash
59
- ... on ShopMediaImage {
60
- url(transform: { maxWidth: 160 })
61
- url2x: url(transform: { maxWidth: 160, scale: 2 })
62
- width
63
- height
64
- focalPoint {
65
- x
66
- y
67
- }
68
- }
69
- }
70
- }
71
- }
72
- `, [ReviewCoreFields]);
73
- const FetchReviewQuery = graphql(`
74
- query FetchReview($id: ID!) {
75
- review(id: $id) {
76
- ...ReviewFields
77
- }
78
- }
79
- `, [ReviewFields]);
80
- const FetchReviewsQuery = graphql(`
81
- query FetchReviews($ids: [ID!], $first: Int!) {
82
- reviews(ids: $ids, first: $first) {
83
- nodes {
84
- ...ReviewFields
85
- }
86
- }
87
- }
88
- `, [ReviewFields]);
89
- function toReviewData(node) {
28
+ function toReview(r, myVote = null) {
90
29
  return {
91
- id: node.id,
92
- rating: node.rating,
93
- title: node.title ?? null,
94
- body: node.body,
95
- authorName: node.authorName,
96
- verified: node.verified,
97
- createdAt: node.createdAt,
98
- upvoteCount: node.upvoteCount,
99
- downvoteCount: node.downvoteCount,
100
- media: node.media.map((m) => ({
101
- id: m.id,
102
- url: m.url ?? null,
103
- srcset: widthSrcset(m.url, m.url2x, REVIEW_MEDIA_WIDTH),
104
- thumbUrl: m.thumbUrl ?? null,
105
- thumbSrcset: widthSrcset(m.thumbUrl, m.thumbUrl2x, REVIEW_THUMB_WIDTH),
106
- width: m.width ?? null,
107
- height: m.height ?? null,
108
- thumbhash: m.thumbhash ?? null
109
- })),
110
- merchantReply: node.merchantReply ? {
111
- body: node.merchantReply.body,
112
- repliedAt: node.merchantReply.repliedAt
113
- } : null,
114
- attributes: node.attributes.map((a) => ({
115
- definitionId: a.definitionId,
30
+ id: r.id,
31
+ rating: r.rating,
32
+ title: r.title,
33
+ body: r.body,
34
+ authorName: r.authorName,
35
+ verifiedBuyer: r.verifiedBuyer,
36
+ createdAt: r.createdAt,
37
+ answers: r.answers.map((a) => ({
38
+ attributeId: a.attributeId,
39
+ handle: a.handle,
116
40
  name: a.name,
117
- fieldType: a.fieldType,
41
+ type: a.type,
118
42
  value: a.value,
119
- valueLabel: a.valueLabel ?? null
43
+ label: a.label
120
44
  })),
121
- myVote: node.myVote ?? null,
122
- product: node.product ? {
123
- handle: node.product.handle,
124
- title: node.product.title,
125
- active: node.product.status === "ACTIVE",
126
- image: asImage(toFileInfo(node.product.featuredMedia, { baseWidth: 160 }))
127
- } : null
45
+ reply: r.reply && {
46
+ body: r.reply.body,
47
+ repliedAt: r.reply.repliedAt
48
+ },
49
+ media: r.media.map(toMedia),
50
+ upvoteCount: r.upvoteCount,
51
+ downvoteCount: r.downvoteCount,
52
+ myVote
128
53
  };
129
54
  }
130
- function asImage(file) {
131
- return file?.kind === "image" ? file : null;
55
+ function toCard(card) {
56
+ const { product } = card;
57
+ return {
58
+ ...toReview(card),
59
+ product: {
60
+ id: product.id,
61
+ handle: product.handle,
62
+ title: product.title,
63
+ url: product.url,
64
+ image: product.image && imageFileInfo(product.image, PRODUCT_THUMB_WIDTH)
65
+ }
66
+ };
132
67
  }
68
+ /** Picked-review reads of this request's tick in one language share a
69
+ * `reviews.cards` call. */
70
+ const coalescedCard = coalescedReads({
71
+ max: 50,
72
+ matches: (card, ref) => card.id === ref
73
+ });
133
74
  const fetchReviewCached = memoTTL(async (id, locale) => {
134
- const data = await request(FetchReviewQuery, { id }, locale ? { acceptLanguage: locale } : void 0);
135
- return data.review ? toReviewData(data.review) : null;
75
+ const card = await coalescedCard(locale ?? "", id, async (refs) => {
76
+ return (await storefront(locale).reviews.cards({ refs: refs.map((ref) => ({ reviewId: liteId("review").parse(ref) })) })).items;
77
+ });
78
+ return card && toCard(card);
136
79
  }, {
137
80
  key: (id, locale) => `review|${id}|${locale ?? ""}`,
138
81
  shouldCache: (v) => v !== null,
139
82
  version: getContentVersion
140
83
  });
84
+ /** A picked review (`review` setting). Its questions' names and labels are
85
+ * the merchant's, translated, so the read is in the buyer's language. Null for
86
+ * a review a buyer may not see, an id that is no review's (no call is made),
87
+ * and on a failed read. */
141
88
  async function fetchReview(id, locale) {
142
- try {
143
- return await fetchReviewCached(id, locale);
144
- } catch (err) {
145
- console.warn("[fetchReview] failed:", err);
146
- return null;
147
- }
89
+ if (!liteId("review").safeParse(id).success) return null;
90
+ return orFallback(fetchReviewCached(id, locale), null, "fetchReview");
148
91
  }
149
- const REVIEWS_PAGE_MAX = 50;
150
- const rawId = (id) => id.slice(id.lastIndexOf("/") + 1);
151
- const fetchReviewsCached = memoTTL(async (idsKey, locale) => {
152
- const ids = idsKey.split(",");
153
- const data = await request(FetchReviewsQuery, {
154
- ids,
155
- first: ids.length
156
- }, locale ? { acceptLanguage: locale } : void 0);
157
- const byId = new Map(data.reviews.nodes.map((n) => [rawId(String(n.id)), toReviewData(n)]));
158
- return ids.map((id) => byId.get(rawId(id))).filter((r) => r !== void 0);
159
- }, {
160
- key: (idsKey, locale) => `reviews|${idsKey}|${locale ?? ""}`,
161
- shouldCache: (v, idsKey) => v.length === idsKey.split(",").length,
162
- version: getContentVersion
163
- });
92
+ /** A `review_list` setting's picks, in the merchant's order: one a buyer may
93
+ * not see is dropped rather than left as a hole, so a section renders the list
94
+ * without guarding each entry. A review picked twice renders twice. */
164
95
  async function fetchReviews(ids, locale) {
165
- if (ids.length === 0) return [];
166
- let unique = [...new Set(ids)];
167
- if (unique.length > REVIEWS_PAGE_MAX) {
168
- console.warn(`[fetchReviews] ${unique.length} ids requested, serving the first ${REVIEWS_PAGE_MAX}`);
169
- unique = unique.slice(0, REVIEWS_PAGE_MAX);
170
- }
171
- try {
172
- const rows = await fetchReviewsCached(unique.join(","), locale);
173
- if (unique.length === ids.length) return rows;
174
- const byId = new Map(rows.map((r) => [rawId(r.id), r]));
175
- return ids.map((id) => byId.get(rawId(id))).filter((r) => r !== void 0);
176
- } catch (err) {
177
- console.warn("[fetchReviews] failed:", err);
178
- return [];
179
- }
96
+ return (await Promise.all(ids.map((id) => fetchReview(id, locale)))).filter((card) => card !== null);
180
97
  }
181
- const EMPTY_PAGE = {
182
- reviews: [],
183
- hasNextPage: false,
184
- endCursor: null
185
- };
186
- const FetchProductReviewsQuery = graphql(`
187
- query FetchProductReviews(
188
- $handle: String
189
- $first: Int!
190
- $after: String
191
- $sort: ShopProductReviewSortEnum
192
- $ratingEq: Int
193
- $verifiedEq: Boolean
194
- ) {
195
- product(handle: $handle) {
196
- reviews(
197
- first: $first
198
- after: $after
199
- sort: $sort
200
- filter: { ratingEq: $ratingEq, verifiedEq: $verifiedEq }
201
- ) {
202
- nodes {
203
- ...ReviewCoreFields
204
- # Viewer-dependent — resolved against the threaded X-Customer-Session,
205
- # null for an anonymous request. Kept OUT of ReviewCoreFields so the
206
- # shop-wide picker fetches never select it.
207
- myVote
208
- }
209
- pageInfo {
210
- hasNextPage
211
- endCursor
212
- }
213
- }
214
- }
215
- }
216
- `, [ReviewCoreFields]);
217
- async function fetchProductReviewsPage(handle, first, after, sort, ratingEq, verified, locale, token) {
218
- const conn = (await request(FetchProductReviewsQuery, {
219
- handle,
220
- first,
221
- after: after || null,
222
- sort,
223
- ratingEq: ratingEq || null,
224
- verifiedEq: verified ? true : null
225
- }, token || locale ? {
226
- ...token ? { customerSessionToken: token } : {},
227
- ...locale ? { acceptLanguage: locale } : {}
228
- } : void 0)).product?.reviews;
229
- if (!conn) return EMPTY_PAGE;
98
+ /** Page `page` of a product's published reviews, `perPage` a page (at most
99
+ * the api's page size). `rating` narrows the list to that many stars,
100
+ * `verified` to verified buyers' reviews. A signed-in buyer's read carries
101
+ * their own vote on each review (`myVote`). An
102
+ * empty page for a product a buyer may not see and on a failed read: a
103
+ * failed review list must not take the product page down. Read fresh on every
104
+ * call: the page, sort and rating permutations would crowd the TTL cache, and a
105
+ * review just published must show on the next read. */
106
+ async function fetchProductReviews(data) {
107
+ const page = Math.max(1, data.page ?? 1);
108
+ const perPage = Math.min(Math.max(1, data.perPage ?? 5), 50);
109
+ const { offset, limit } = pageInput(page, perPage);
110
+ const session = await readCustomerSession();
111
+ const api = session?.token ? buyerStorefront(session.token, data.locale) : storefront(data.locale);
112
+ const answer = await orFallback(orNotFound(api.products.reviews({
113
+ handle: data.handle,
114
+ sort: data.sort,
115
+ rating: data.rating ?? void 0,
116
+ verified: data.verified ? true : void 0,
117
+ offset,
118
+ limit
119
+ })), null, "fetchProductReviews");
120
+ if (!answer) return {
121
+ reviews: [],
122
+ total: 0,
123
+ page,
124
+ hasNextPage: false
125
+ };
230
126
  return {
231
- reviews: conn.nodes.map(toReviewData),
232
- hasNextPage: conn.pageInfo.hasNextPage,
233
- endCursor: conn.pageInfo.endCursor ?? null
127
+ reviews: answer.items.map((r) => toReview(r, r.myVote)),
128
+ total: answer.total,
129
+ page,
130
+ hasNextPage: offset + answer.items.length < answer.total
234
131
  };
235
132
  }
236
- const fetchProductReviewsCached = memoTTL((handle, first, after, sort, ratingEq, verified, locale) => fetchProductReviewsPage(handle, first, after, sort, ratingEq, verified, locale, ""), {
237
- key: (handle, first, after, sort, ratingEq, verified, locale) => `product-reviews|${handle}|${first}|${after}|${sort}|${ratingEq}|${verified}|${locale}`,
238
- version: getContentVersion
239
- });
240
- /** One page of a product's PUBLISHED reviews. Status filtering is the ability's
241
- * job (see the module header), so the theme never filters. Returns an empty
242
- * page rather than throwing — a failed review fetch must not take the PDP down.
243
- *
244
- * `ratingEq` narrows to a single star bucket (the summary chart's rows are the
245
- * natural trigger); omit it for all reviews. */
246
- async function fetchProductReviews({ handle, first = 5, after, sort = "RELEVANCE", ratingEq, verifiedEq, locale }) {
247
- const session = await readCustomerSession();
248
- const args = [
249
- handle,
250
- Math.min(Math.max(1, first), REVIEWS_PAGE_MAX),
251
- after ?? "",
252
- sort,
253
- ratingEq ?? 0,
254
- verifiedEq ? 1 : 0,
255
- locale ?? ""
256
- ];
257
- try {
258
- return session?.token ? await fetchProductReviewsPage(...args, session.token) : await fetchProductReviewsCached(...args);
259
- } catch (err) {
260
- console.warn("[fetchProductReviews] failed:", err);
261
- return EMPTY_PAGE;
262
- }
263
- }
264
- const FetchReviewAttributeConfigQuery = graphql(`
265
- query FetchReviewAttributeConfig($handle: String) {
266
- product(handle: $handle) {
267
- reviewAttributeDefinitions {
268
- id
269
- handle
270
- name
271
- fieldType
272
- required
273
- choices {
274
- key
275
- label
276
- }
277
- scaleLabels {
278
- min
279
- mid
280
- max
281
- }
282
- }
283
- reviewAttributeAggregates {
284
- definitionId
285
- name
286
- fieldType
287
- count
288
- average
289
- scaleLabels {
290
- min
291
- mid
292
- max
293
- }
294
- distribution {
295
- value
296
- valueLabel
297
- count
298
- }
299
- }
300
- }
301
- }
302
- `);
303
- const fetchReviewAttributeConfigCached = memoTTL(async (handle, locale) => {
304
- const data = await request(FetchReviewAttributeConfigQuery, { handle }, locale ? { acceptLanguage: locale } : void 0);
305
- const defs = data.product?.reviewAttributeDefinitions ?? [];
306
- const aggs = data.product?.reviewAttributeAggregates ?? [];
133
+ function toQuestion(q) {
307
134
  return {
308
- definitions: defs.map((d) => ({
309
- id: d.id,
310
- handle: d.handle,
311
- name: d.name,
312
- fieldType: d.fieldType,
313
- required: d.required,
314
- choices: d.choices ? d.choices.map((c) => ({
315
- key: c.key,
316
- label: c.label
317
- })) : null,
318
- scaleLabels: d.scaleLabels ? {
319
- min: d.scaleLabels.min,
320
- mid: d.scaleLabels.mid ?? null,
321
- max: d.scaleLabels.max
322
- } : null
135
+ id: q.id,
136
+ handle: q.handle,
137
+ name: q.name,
138
+ type: q.type,
139
+ required: q.required,
140
+ choices: q.choices.map((c) => ({
141
+ key: c.key,
142
+ label: c.label
323
143
  })),
324
- aggregates: aggs.map((a) => ({
325
- definitionId: a.definitionId,
326
- name: a.name,
327
- fieldType: a.fieldType,
328
- count: a.count,
329
- average: a.average ?? null,
330
- scaleLabels: a.scaleLabels ? {
331
- min: a.scaleLabels.min,
332
- mid: a.scaleLabels.mid ?? null,
333
- max: a.scaleLabels.max
334
- } : null,
335
- distribution: a.distribution.map((b) => ({
336
- value: b.value,
337
- valueLabel: b.valueLabel ?? null,
338
- count: b.count
339
- }))
144
+ scaleLabels: q.scaleLabels && {
145
+ min: q.scaleLabels.min,
146
+ mid: q.scaleLabels.mid,
147
+ max: q.scaleLabels.max
148
+ },
149
+ count: q.count,
150
+ average: q.average,
151
+ distribution: q.distribution.map((b) => ({
152
+ value: b.value,
153
+ label: b.label,
154
+ count: b.count
340
155
  }))
341
156
  };
157
+ }
158
+ const fetchReviewQuestionsCached = memoTTL(async (handle, locale) => {
159
+ const answer = await orNotFound(storefront(locale).products.reviewAttributes({ handle }));
160
+ return answer && answer.items.map(toQuestion);
342
161
  }, {
343
- key: (handle, locale) => `review-attr-config|${handle}|${locale ?? ""}`,
162
+ key: (handle, locale) => `review-questions|${handle}|${locale ?? ""}`,
163
+ shouldCache: (v) => v !== null,
344
164
  version: getContentVersion
345
165
  });
346
- const EMPTY_ATTRIBUTE_CONFIG = {
347
- definitions: [],
348
- aggregates: []
349
- };
350
- /** The product's custom review-attribute definitions (for the submit form) and
351
- * aggregates (for the summary bars), in one memoized round trip. Shop config +
352
- * review-derived counters, content-version keyed like the other picker fetches.
353
- * Never throws — a failure yields empty config rather than taking the PDP down. */
354
- async function fetchProductReviewAttributeConfig(handle, locale) {
355
- try {
356
- return await fetchReviewAttributeConfigCached(handle, locale);
357
- } catch (err) {
358
- console.warn("[fetchProductReviewAttributeConfig] failed:", err);
359
- return EMPTY_ATTRIBUTE_CONFIG;
360
- }
361
- }
362
- const VoteFields = graphql(`
363
- fragment ReviewVoteFields on ShopProductReview @_unmask {
364
- id
365
- upvoteCount
366
- downvoteCount
367
- myVote
368
- }
369
- `);
370
- const ReviewVoteSetMutation = graphql(`
371
- mutation ReviewVoteSet($reviewId: ID!, $direction: ShopProductReviewVoteDirectionEnum!) {
372
- reviewVoteSet(input: { reviewId: $reviewId, direction: $direction }) {
373
- review {
374
- ...ReviewVoteFields
375
- }
376
- userErrors {
377
- code
378
- message
379
- }
380
- }
381
- }
382
- `, [VoteFields]);
383
- const ReviewVoteDeleteMutation = graphql(`
384
- mutation ReviewVoteDelete($reviewId: ID!) {
385
- reviewVoteDelete(input: { reviewId: $reviewId }) {
386
- review {
387
- ...ReviewVoteFields
388
- }
389
- userErrors {
390
- code
391
- message
392
- }
393
- }
394
- }
395
- `, [VoteFields]);
396
- function toVoteResult(review, userErrors) {
397
- if (userErrors.length > 0 || !review) return {
398
- ok: false,
399
- reason: "FAILED"
400
- };
401
- return {
402
- ok: true,
403
- upvoteCount: review.upvoteCount,
404
- downvoteCount: review.downvoteCount,
405
- myVote: review.myVote ?? null
406
- };
166
+ /** The review questions that apply to a product, in the merchant's order, in
167
+ * the buyer's language. Empty for a product a buyer may not see and on a
168
+ * failed read. */
169
+ async function fetchReviewQuestions(handle, locale) {
170
+ return await orFallback(fetchReviewQuestionsCached(handle, locale), null, "fetchReviewQuestions") ?? [];
407
171
  }
408
- async function runVoteMutation(reviewId, direction) {
172
+ async function runVote(reviewId, direction) {
409
173
  const session = await readCustomerSession();
410
174
  if (!session?.token) return {
411
175
  ok: false,
412
176
  reason: "AUTH_REQUIRED"
413
177
  };
414
- const options = { customerSessionToken: session.token };
415
178
  try {
416
- const payload = direction ? (await request(ReviewVoteSetMutation, {
417
- reviewId,
179
+ const vote = await buyerStorefront(session.token).reviews.vote({
180
+ reviewId: liteId("review").parse(reviewId),
418
181
  direction
419
- }, options)).reviewVoteSet : (await request(ReviewVoteDeleteMutation, { reviewId }, options)).reviewVoteDelete;
420
- return toVoteResult(payload?.review, payload?.userErrors ?? []);
421
- } catch (err) {
422
- console.warn("[reviewVote] failed:", err);
182
+ });
183
+ return {
184
+ ok: true,
185
+ upvoteCount: vote.upvoteCount,
186
+ downvoteCount: vote.downvoteCount,
187
+ myVote: vote.myVote
188
+ };
189
+ } catch (error) {
190
+ if (errorCode(error) === "UNAUTHENTICATED") return {
191
+ ok: false,
192
+ reason: "AUTH_REQUIRED"
193
+ };
194
+ console.warn("[reviewVote] failed:", errorCode(error) ?? error);
423
195
  return {
424
196
  ok: false,
425
197
  reason: "FAILED"
426
198
  };
427
199
  }
428
200
  }
429
- /** Cast (or switch) the current buyer's helpful-vote on a review. Requires a
430
- * customer session — anonymous callers get AUTH_REQUIRED so the theme can route
431
- * them to sign in. Never throws: a transport failure resolves to FAILED. */
201
+ /** Cast or switch the signed-in buyer's helpful vote on a review. Never throws. */
432
202
  async function setReviewVote(reviewId, direction) {
433
- return await runVoteMutation(reviewId, direction);
203
+ return runVote(reviewId, direction);
434
204
  }
435
- /** Clear the current buyer's helpful-vote on a review (un-vote). Same auth +
436
- * failure contract as {@link setReviewVote}. */
205
+ /** Clear the signed-in buyer's helpful vote on a review. Never throws. */
437
206
  async function deleteReviewVote(reviewId) {
438
- return await runVoteMutation(reviewId, null);
207
+ return runVote(reviewId, null);
208
+ }
209
+ function refusal(error) {
210
+ const code = errorCode(error);
211
+ const data = error.data ?? {};
212
+ switch (code) {
213
+ case "RATE_LIMITED": return [{
214
+ code,
215
+ field: null,
216
+ retryAfterSeconds: data.retryAfterSeconds ?? 0
217
+ }];
218
+ case "TURNSTILE_FAILED":
219
+ case "NOT_FOUND": return [{
220
+ code,
221
+ field: null
222
+ }];
223
+ case "CONFLICT": return [{
224
+ code,
225
+ field: "authorEmail"
226
+ }];
227
+ case "VALIDATION_FAILED": return (data.issues ?? []).map((_, at) => ({
228
+ code,
229
+ field: invalidField(error, at)
230
+ }));
231
+ case "ANSWERS_REFUSED": return (data.refused ?? []).flatMap((refused) => "attributeId" in refused ? [{
232
+ code,
233
+ field: null,
234
+ attributeId: refused.attributeId,
235
+ reason: refused.reason
236
+ }] : []);
237
+ case "PHOTOS_REFUSED": return (data.refused ?? []).flatMap((refused) => "photoId" in refused ? [{
238
+ code,
239
+ field: "media",
240
+ reason: refused.reason
241
+ }] : []);
242
+ default:
243
+ console.warn("[submitReview] failed:", code ?? error);
244
+ return [{
245
+ code: "FAILED",
246
+ field: null
247
+ }];
248
+ }
249
+ }
250
+ /** Why a photo would be refused before any upload: the api takes a JPEG, PNG
251
+ * or WebP of at most `REVIEW_PHOTO_BYTES_MAX`. */
252
+ function photoProblem(photo) {
253
+ if (!REVIEW_PHOTO_TYPES.includes(photo.type)) return "invalid_type";
254
+ if (photo.size > 5242880) return "too_large";
255
+ return null;
256
+ }
257
+ /** Upload the review's photos: reserve them (`reviews.photos.create`), then
258
+ * PUT each one's bytes to its presigned URL. Answers their ids in order. */
259
+ async function uploadPhotos(api, media) {
260
+ const { photos } = await api.reviews.photos.create({ photos: media.map((photo) => ({
261
+ filename: photo instanceof File && photo.name ? photo.name : void 0,
262
+ contentType: photo.type,
263
+ byteSize: photo.size
264
+ })) });
265
+ await Promise.all(photos.map(async ({ upload }, at) => {
266
+ const response = await fetch(upload.url, {
267
+ method: upload.method,
268
+ headers: upload.headers,
269
+ body: media[at]
270
+ });
271
+ if (!response.ok) throw new Error(`review photo upload answered ${response.status}`);
272
+ }));
273
+ return photos.map(({ id }) => id);
439
274
  }
440
- const ReviewSubmitMutation = graphql(`
441
- mutation ReviewSubmit(
442
- $productId: ID!
443
- $authorName: String!
444
- $authorEmail: String!
445
- $rating: Int!
446
- $title: String
447
- $body: String!
448
- $media: [Upload!]
449
- $attributes: [ReviewAttributeInput!]
450
- ) {
451
- reviewSubmit(
452
- input: {
453
- productId: $productId
454
- authorName: $authorName
455
- authorEmail: $authorEmail
456
- rating: $rating
457
- title: $title
458
- body: $body
459
- media: $media
460
- attributes: $attributes
461
- }
462
- ) {
463
- review {
464
- ...ReviewCoreFields
465
- # Storefront-visible derived boolean, meaningful on a freshly
466
- # submitted payload — true when the review isn't publicly visible yet.
467
- pending
468
- }
469
- userErrors {
470
- code
471
- field
472
- message
473
- }
474
- }
475
- }
476
- `, [ReviewCoreFields]);
477
- /** Submit a new review on a product. Reads the `customer_session` cookie itself
478
- * (threaded as `X-Customer-Session` so the API can force the buyer's identity +
479
- * compute verified-buyer status). Photos ride a multipart transport
480
- * ({@link requestUpload}); a text-only submit goes out as an ordinary JSON
481
- * mutation. Never throws — a transport failure resolves to a single `FAILED`
482
- * userError so the form can show a generic retry message.
483
- *
484
- * On success, `published` distinguishes the two moderation outcomes: `true` ⇒
485
- * publicly visible now (the caller can render `review` in the list); `false` ⇒
486
- * queued for merchant approval (show a confirmation, don't list it). */
275
+ /** Submit a buyer's review (`reviews.submit`), with up to three photos
276
+ * (`media`) uploaded first. The token goes only when the form has one: a shop
277
+ * without a widget asks for none. Never throws: a refusal the form does not
278
+ * word, and a transport failure, resolve to a single `FAILED` error so it can
279
+ * show a generic retry message. */
487
280
  async function submitReview(input, media = []) {
488
- const session = await readCustomerSession();
489
- const options = session?.token ? { customerSessionToken: session.token } : void 0;
490
- const title = input.title?.trim();
491
- const variables = {
492
- productId: input.productId,
493
- authorName: input.authorName,
494
- authorEmail: input.authorEmail,
495
- rating: input.rating,
496
- title: title || null,
497
- body: input.body,
498
- media: media.length ? media.map(() => null) : null,
499
- attributes: input.attributes?.length ? input.attributes : null
281
+ const { productId, answers, turnstileToken, ...review } = input;
282
+ const refusedPhotos = media.flatMap((photo) => {
283
+ const reason = photoProblem(photo);
284
+ return reason ? [{
285
+ code: "PHOTOS_REFUSED",
286
+ field: "media",
287
+ reason
288
+ }] : [];
289
+ });
290
+ if (refusedPhotos.length > 0) return {
291
+ ok: false,
292
+ errors: refusedPhotos
500
293
  };
294
+ const session = await readCustomerSession();
295
+ const api = session?.token ? buyerStorefront(session.token) : storefront();
501
296
  try {
502
- const payload = (media.length ? await requestUpload(ReviewSubmitMutation, variables, media, "variables.media", options) : await request(ReviewSubmitMutation, variables, options)).reviewSubmit;
503
- const errors = payload?.userErrors ?? [];
504
- if (errors.length > 0 || !payload) return {
505
- ok: false,
506
- userErrors: errors.map((e) => ({
507
- code: e.code,
508
- field: e.field ?? null,
509
- message: e.message
510
- }))
511
- };
512
- const node = payload.review;
297
+ const photoIds = media.length > 0 ? await uploadPhotos(api, media) : [];
298
+ const { status } = await api.reviews.submit({
299
+ ...review,
300
+ productId: liteId("prod").parse(productId),
301
+ answers: answers?.map(({ attributeId, value }) => ({
302
+ attributeId: liteId("review_attribute").parse(attributeId),
303
+ value
304
+ })),
305
+ ...photoIds.length > 0 ? { photoIds } : {},
306
+ ...turnstileToken ? { turnstileToken } : {}
307
+ });
513
308
  return {
514
309
  ok: true,
515
- published: node ? !node.pending : false,
516
- review: node ? toReviewData(node) : null
310
+ published: status === "published"
517
311
  };
518
- } catch (err) {
519
- console.warn("[submitReview] failed:", err);
312
+ } catch (error) {
520
313
  return {
521
314
  ok: false,
522
- userErrors: [{
523
- code: "FAILED",
524
- field: null,
525
- message: ""
526
- }]
315
+ errors: refusal(error)
527
316
  };
528
317
  }
529
318
  }
530
- //#endregion
531
- export { deleteReviewVote, fetchProductReviewAttributeConfig, fetchProductReviews, fetchReview, fetchReviews, setReviewVote, submitReview };
319
+ export { deleteReviewVote, fetchProductReviews, fetchReview, fetchReviewQuestions, fetchReviews, setReviewVote, submitReview };