@eldrajs/theme-cli 0.0.0-stage → 0.1.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 (483) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/LICENSE +21 -0
  3. package/README.md +27 -2
  4. package/dist/cli.d.ts +1 -0
  5. package/dist/cli.js +203 -0
  6. package/dist/index.d.ts +174 -0
  7. package/dist/index.js +3 -0
  8. package/dist/validate-C6jB8_Oc.js +510 -0
  9. package/package.json +56 -3
  10. package/template/.eldra/block-types.d.ts +429 -0
  11. package/template/.eldra/manifest.json +9377 -0
  12. package/template/.eldra/previews.json +36 -0
  13. package/template/.github/workflows/eldra-deploy.yml +24 -0
  14. package/template/.gitlab-ci.yml +16 -0
  15. package/template/.storybook/eldra.ts +123 -0
  16. package/template/.storybook/i18n.ts +23 -0
  17. package/template/.storybook/main.ts +59 -0
  18. package/template/.storybook/nuxt-link-stub.ts +23 -0
  19. package/template/.storybook/preview.ts +52 -0
  20. package/template/.storybook/shims-vue.d.ts +10 -0
  21. package/template/.storybook/virtual-eldra.d.ts +27 -0
  22. package/template/README.md +288 -0
  23. package/template/app/app.vue +126 -0
  24. package/template/app/assets/main.css +404 -0
  25. package/template/app/components/EldraIcon.vue +66 -0
  26. package/template/app/components/EldraRouterLink.vue +62 -0
  27. package/template/app/components/ui/UiImage.stories.ts +30 -0
  28. package/template/app/components/ui/UiImage.vue +224 -0
  29. package/template/app/components/ui/__tests__/UiImage.spec.ts +292 -0
  30. package/template/app/composables/iconComponent.ts +84 -0
  31. package/template/app/composables/iconFetcher.ts +14 -0
  32. package/template/app/composables/useBlockData.ts +30 -0
  33. package/template/app/composables/useEditing.ts +31 -0
  34. package/template/app/composables/useEldraIcon.ts +46 -0
  35. package/template/app/composables/useRevalidating.ts +69 -0
  36. package/template/app/composables/useRichTextScrollRegions.ts +80 -0
  37. package/template/app/composables/useStorefront.ts +18 -0
  38. package/template/app/composables/useStorefrontFeedback.ts +49 -0
  39. package/template/app/composables/useUiId.ts +18 -0
  40. package/template/app/composables/useWishlist.ts +42 -0
  41. package/template/app/i18n.d.ts +28 -0
  42. package/template/app/icons.ts +185 -0
  43. package/template/app/pages/[...slug].vue +134 -0
  44. package/template/app/plugins/eldra-i18n.ts +98 -0
  45. package/template/app/plugins/eldra-storefront.ts +288 -0
  46. package/template/app/plugins/eldra-ui-messages.ts +112 -0
  47. package/template/app/storefront/cart.ts +245 -0
  48. package/template/app/storefront/categories.ts +283 -0
  49. package/template/app/storefront/collectionSelector.ts +60 -0
  50. package/template/app/storefront/commerce.ts +58 -0
  51. package/template/app/storefront/demo.ts +1313 -0
  52. package/template/app/storefront/facets.ts +476 -0
  53. package/template/app/storefront/feedback.ts +122 -0
  54. package/template/app/storefront/gateway.ts +2256 -0
  55. package/template/app/storefront/history.ts +233 -0
  56. package/template/app/storefront/money.ts +247 -0
  57. package/template/app/storefront/options.ts +71 -0
  58. package/template/app/storefront/prerender.ts +77 -0
  59. package/template/app/storefront/refresh.ts +222 -0
  60. package/template/app/storefront/toProductCard.ts +154 -0
  61. package/template/app/storefront/types.ts +815 -0
  62. package/template/app/storefront/volatile.ts +211 -0
  63. package/template/app/templates.ts +544 -0
  64. package/template/app/utils/classes.ts +40 -0
  65. package/template/app/utils/links.ts +70 -0
  66. package/template/app/utils/pageStructure.ts +77 -0
  67. package/template/app/utils/pageTitle.ts +37 -0
  68. package/template/app/virtual-eldra.d.ts +12 -0
  69. package/template/bitbucket-pipelines.yml +19 -0
  70. package/template/blocks/announcement-bar/Block.vue +203 -0
  71. package/template/blocks/announcement-bar/__tests__/Block.spec.ts +227 -0
  72. package/template/blocks/announcement-bar/block.json +45 -0
  73. package/template/blocks/announcement-bar/mock.json +7 -0
  74. package/template/blocks/announcement-bar/preview.png +0 -0
  75. package/template/blocks/article/Block.vue +317 -0
  76. package/template/blocks/article/__tests__/Block.spec.ts +229 -0
  77. package/template/blocks/article/block.json +148 -0
  78. package/template/blocks/article/mock.json +512 -0
  79. package/template/blocks/article/preview.json +16 -0
  80. package/template/blocks/article/preview.png +0 -0
  81. package/template/blocks/article-list/Block.vue +343 -0
  82. package/template/blocks/article-list/__tests__/Block.spec.ts +279 -0
  83. package/template/blocks/article-list/block.json +181 -0
  84. package/template/blocks/article-list/mock.json +68 -0
  85. package/template/blocks/article-list/preview.json +84 -0
  86. package/template/blocks/article-list/preview.png +0 -0
  87. package/template/blocks/breadcrumbs/Block.vue +278 -0
  88. package/template/blocks/breadcrumbs/__tests__/Block.spec.ts +461 -0
  89. package/template/blocks/breadcrumbs/block.json +89 -0
  90. package/template/blocks/breadcrumbs/mock.json +11 -0
  91. package/template/blocks/breadcrumbs/preview.json +3 -0
  92. package/template/blocks/breadcrumbs/preview.png +0 -0
  93. package/template/blocks/cart/Block.vue +372 -0
  94. package/template/blocks/cart/__tests__/Block.spec.ts +561 -0
  95. package/template/blocks/cart/__tests__/ShippingBar.spec.ts +78 -0
  96. package/template/blocks/cart/__tests__/Summary.spec.ts +245 -0
  97. package/template/blocks/cart/block.json +74 -0
  98. package/template/blocks/cart/mock.json +11 -0
  99. package/template/blocks/cart/parts/CartLines.vue +257 -0
  100. package/template/blocks/cart/parts/ShippingBar.vue +105 -0
  101. package/template/blocks/cart/parts/Summary.vue +291 -0
  102. package/template/blocks/cart/preview.png +0 -0
  103. package/template/blocks/collection-grid/Block.vue +1832 -0
  104. package/template/blocks/collection-grid/__tests__/Block.spec.ts +3037 -0
  105. package/template/blocks/collection-grid/__tests__/groups.spec.ts +731 -0
  106. package/template/blocks/collection-grid/block.json +187 -0
  107. package/template/blocks/collection-grid/mock.json +23 -0
  108. package/template/blocks/collection-grid/parts/groups.ts +861 -0
  109. package/template/blocks/collection-grid/preview.json +7 -0
  110. package/template/blocks/collection-grid/preview.png +0 -0
  111. package/template/blocks/collection-header/Block.vue +533 -0
  112. package/template/blocks/collection-header/__tests__/Block.spec.ts +381 -0
  113. package/template/blocks/collection-header/block.json +140 -0
  114. package/template/blocks/collection-header/mock.json +28 -0
  115. package/template/blocks/collection-header/preview.json +14 -0
  116. package/template/blocks/collection-header/preview.png +0 -0
  117. package/template/blocks/contact/Block.vue +621 -0
  118. package/template/blocks/contact/__tests__/Block.spec.ts +347 -0
  119. package/template/blocks/contact/block.json +174 -0
  120. package/template/blocks/contact/mock.json +28 -0
  121. package/template/blocks/contact/preview.json +9 -0
  122. package/template/blocks/contact/preview.png +0 -0
  123. package/template/blocks/cta/Block.vue +383 -0
  124. package/template/blocks/cta/__tests__/Block.spec.ts +309 -0
  125. package/template/blocks/cta/block.json +86 -0
  126. package/template/blocks/cta/mock.json +10 -0
  127. package/template/blocks/cta/preview.json +9 -0
  128. package/template/blocks/cta/preview.png +0 -0
  129. package/template/blocks/faq/Block.vue +254 -0
  130. package/template/blocks/faq/__tests__/Block.spec.ts +312 -0
  131. package/template/blocks/faq/block.json +113 -0
  132. package/template/blocks/faq/mock.json +115 -0
  133. package/template/blocks/faq/preview.png +0 -0
  134. package/template/blocks/feature-grid/Block.vue +241 -0
  135. package/template/blocks/feature-grid/__tests__/Block.spec.ts +311 -0
  136. package/template/blocks/feature-grid/block.json +106 -0
  137. package/template/blocks/feature-grid/mock.json +29 -0
  138. package/template/blocks/feature-grid/preview.json +45 -0
  139. package/template/blocks/feature-grid/preview.png +0 -0
  140. package/template/blocks/footer/Block.vue +652 -0
  141. package/template/blocks/footer/__tests__/Block.spec.ts +700 -0
  142. package/template/blocks/footer/block.json +240 -0
  143. package/template/blocks/footer/mock.json +161 -0
  144. package/template/blocks/footer/preview.png +0 -0
  145. package/template/blocks/gallery/Block.vue +416 -0
  146. package/template/blocks/gallery/__tests__/Block.spec.ts +289 -0
  147. package/template/blocks/gallery/block.json +87 -0
  148. package/template/blocks/gallery/mock.json +16 -0
  149. package/template/blocks/gallery/preview.json +64 -0
  150. package/template/blocks/gallery/preview.png +0 -0
  151. package/template/blocks/hero/Block.vue +378 -0
  152. package/template/blocks/hero/__tests__/Block.spec.ts +324 -0
  153. package/template/blocks/hero/block.json +146 -0
  154. package/template/blocks/hero/mock.json +11 -0
  155. package/template/blocks/hero/preview.json +55 -0
  156. package/template/blocks/hero/preview.png +0 -0
  157. package/template/blocks/image/Block.vue +232 -0
  158. package/template/blocks/image/__tests__/Block.spec.ts +224 -0
  159. package/template/blocks/image/block.json +67 -0
  160. package/template/blocks/image/mock.json +7 -0
  161. package/template/blocks/image/preview.json +9 -0
  162. package/template/blocks/image/preview.png +0 -0
  163. package/template/blocks/logo-cloud/Block.vue +206 -0
  164. package/template/blocks/logo-cloud/__tests__/Block.spec.ts +210 -0
  165. package/template/blocks/logo-cloud/block.json +79 -0
  166. package/template/blocks/logo-cloud/mock.json +15 -0
  167. package/template/blocks/logo-cloud/preview.json +92 -0
  168. package/template/blocks/logo-cloud/preview.png +0 -0
  169. package/template/blocks/navigation/Block.vue +1348 -0
  170. package/template/blocks/navigation/__tests__/Block.spec.ts +2030 -0
  171. package/template/blocks/navigation/block.json +167 -0
  172. package/template/blocks/navigation/mock.json +191 -0
  173. package/template/blocks/navigation/preview.png +0 -0
  174. package/template/blocks/navigation/useMegaMenuKeys.ts +276 -0
  175. package/template/blocks/newsletter/Block.vue +399 -0
  176. package/template/blocks/newsletter/__tests__/Block.spec.ts +365 -0
  177. package/template/blocks/newsletter/block.json +105 -0
  178. package/template/blocks/newsletter/mock.json +31 -0
  179. package/template/blocks/newsletter/preview.png +0 -0
  180. package/template/blocks/order-status/Block.vue +754 -0
  181. package/template/blocks/order-status/__tests__/Block.spec.ts +515 -0
  182. package/template/blocks/order-status/block.json +138 -0
  183. package/template/blocks/order-status/mock.json +19 -0
  184. package/template/blocks/order-status/preview.png +0 -0
  185. package/template/blocks/pricing-table/Block.vue +297 -0
  186. package/template/blocks/pricing-table/__tests__/Block.spec.ts +357 -0
  187. package/template/blocks/pricing-table/block.json +155 -0
  188. package/template/blocks/pricing-table/mock.json +47 -0
  189. package/template/blocks/pricing-table/preview.png +0 -0
  190. package/template/blocks/product-carousel/Block.vue +459 -0
  191. package/template/blocks/product-carousel/__tests__/Block.spec.ts +957 -0
  192. package/template/blocks/product-carousel/block.json +71 -0
  193. package/template/blocks/product-carousel/mock.json +9 -0
  194. package/template/blocks/product-carousel/preview.json +7 -0
  195. package/template/blocks/product-carousel/preview.png +0 -0
  196. package/template/blocks/product-detail/Block.vue +886 -0
  197. package/template/blocks/product-detail/__tests__/Block.spec.ts +1495 -0
  198. package/template/blocks/product-detail/__tests__/stock.spec.ts +119 -0
  199. package/template/blocks/product-detail/block.json +155 -0
  200. package/template/blocks/product-detail/mock.json +113 -0
  201. package/template/blocks/product-detail/parts/Gallery.vue +181 -0
  202. package/template/blocks/product-detail/parts/StickyBuyBar.vue +99 -0
  203. package/template/blocks/product-detail/preview.png +0 -0
  204. package/template/blocks/product-detail/stock.ts +150 -0
  205. package/template/blocks/quote/Block.vue +206 -0
  206. package/template/blocks/quote/__tests__/Block.spec.ts +265 -0
  207. package/template/blocks/quote/block.json +76 -0
  208. package/template/blocks/quote/mock.json +9 -0
  209. package/template/blocks/quote/preview.json +16 -0
  210. package/template/blocks/quote/preview.png +0 -0
  211. package/template/blocks/rich-text/Block.vue +143 -0
  212. package/template/blocks/rich-text/__tests__/Block.spec.ts +191 -0
  213. package/template/blocks/rich-text/block.json +57 -0
  214. package/template/blocks/rich-text/mock.json +87 -0
  215. package/template/blocks/rich-text/preview.png +0 -0
  216. package/template/blocks/search/Block.vue +589 -0
  217. package/template/blocks/search/PopularChips.vue +40 -0
  218. package/template/blocks/search/TypeSection.vue +148 -0
  219. package/template/blocks/search/__tests__/Block.spec.ts +718 -0
  220. package/template/blocks/search/__tests__/results.spec.ts +166 -0
  221. package/template/blocks/search/block.json +102 -0
  222. package/template/blocks/search/mock.json +18 -0
  223. package/template/blocks/search/preview.png +0 -0
  224. package/template/blocks/search/results.ts +85 -0
  225. package/template/blocks/split-content/Block.vue +195 -0
  226. package/template/blocks/split-content/__tests__/Block.spec.ts +225 -0
  227. package/template/blocks/split-content/block.json +70 -0
  228. package/template/blocks/split-content/mock.json +45 -0
  229. package/template/blocks/split-content/preview.json +58 -0
  230. package/template/blocks/split-content/preview.png +0 -0
  231. package/template/blocks/stats/Block.vue +159 -0
  232. package/template/blocks/stats/__tests__/Block.spec.ts +194 -0
  233. package/template/blocks/stats/block.json +73 -0
  234. package/template/blocks/stats/mock.json +12 -0
  235. package/template/blocks/stats/preview.png +0 -0
  236. package/template/blocks/tabs/Block.vue +278 -0
  237. package/template/blocks/tabs/__tests__/Block.spec.ts +303 -0
  238. package/template/blocks/tabs/block.json +97 -0
  239. package/template/blocks/tabs/mock.json +129 -0
  240. package/template/blocks/tabs/preview.json +153 -0
  241. package/template/blocks/tabs/preview.png +0 -0
  242. package/template/blocks/team/Block.vue +288 -0
  243. package/template/blocks/team/__tests__/Block.spec.ts +221 -0
  244. package/template/blocks/team/block.json +125 -0
  245. package/template/blocks/team/mock.json +39 -0
  246. package/template/blocks/team/preview.json +62 -0
  247. package/template/blocks/team/preview.png +0 -0
  248. package/template/blocks/testimonials/Block.vue +408 -0
  249. package/template/blocks/testimonials/__tests__/Block.spec.ts +319 -0
  250. package/template/blocks/testimonials/block.json +121 -0
  251. package/template/blocks/testimonials/mock.json +46 -0
  252. package/template/blocks/testimonials/preview.json +68 -0
  253. package/template/blocks/testimonials/preview.png +0 -0
  254. package/template/blocks/timeline/Block.vue +274 -0
  255. package/template/blocks/timeline/__tests__/Block.spec.ts +310 -0
  256. package/template/blocks/timeline/block.json +98 -0
  257. package/template/blocks/timeline/mock.json +27 -0
  258. package/template/blocks/timeline/preview.png +0 -0
  259. package/template/blocks/trust-strip/Block.vue +330 -0
  260. package/template/blocks/trust-strip/__tests__/Block.spec.ts +290 -0
  261. package/template/blocks/trust-strip/block.json +117 -0
  262. package/template/blocks/trust-strip/mock.json +37 -0
  263. package/template/blocks/trust-strip/preview.png +0 -0
  264. package/template/blocks/video-embed/Block.vue +354 -0
  265. package/template/blocks/video-embed/__tests__/Block.spec.ts +219 -0
  266. package/template/blocks/video-embed/__tests__/embed.spec.ts +76 -0
  267. package/template/blocks/video-embed/block.json +94 -0
  268. package/template/blocks/video-embed/embed.ts +84 -0
  269. package/template/blocks/video-embed/mock.json +13 -0
  270. package/template/blocks/video-embed/preview.json +9 -0
  271. package/template/blocks/video-embed/preview.png +0 -0
  272. package/template/blocks/wishlist/Block.vue +367 -0
  273. package/template/blocks/wishlist/__tests__/Block.spec.ts +508 -0
  274. package/template/blocks/wishlist/block.json +42 -0
  275. package/template/blocks/wishlist/mock.json +9 -0
  276. package/template/blocks/wishlist/preview.png +0 -0
  277. package/template/i18n/en-US.json +602 -0
  278. package/template/i18n/is-IS.json +602 -0
  279. package/template/nuxt.config.ts +148 -0
  280. package/template/package.json +55 -0
  281. package/template/pages/article.page.json +731 -0
  282. package/template/pages/cart.page.json +85 -0
  283. package/template/pages/category.page.json +133 -0
  284. package/template/pages/collection.page.json +194 -0
  285. package/template/pages/home.page.json +353 -0
  286. package/template/pages/product.page.json +323 -0
  287. package/template/pages/products.page.json +144 -0
  288. package/template/pages/search.page.json +83 -0
  289. package/template/pages/wishlist.page.json +88 -0
  290. package/template/public/demo/article-cover.svg +1 -0
  291. package/template/public/demo/article-figure.svg +1 -0
  292. package/template/public/demo/avatar-1.svg +3 -0
  293. package/template/public/demo/avatar-2.svg +3 -0
  294. package/template/public/demo/avatar-3.svg +3 -0
  295. package/template/public/demo/avatar-4.svg +3 -0
  296. package/template/public/demo/avatar-5.svg +3 -0
  297. package/template/public/demo/avatar-6.svg +3 -0
  298. package/template/public/demo/avatar-7.svg +3 -0
  299. package/template/public/demo/avatar-8.svg +3 -0
  300. package/template/public/demo/collection-1.svg +1 -0
  301. package/template/public/demo/collection-2.svg +1 -0
  302. package/template/public/demo/cta-split.svg +1 -0
  303. package/template/public/demo/feature-1.svg +1 -0
  304. package/template/public/demo/feature-2.svg +1 -0
  305. package/template/public/demo/feature-3.svg +1 -0
  306. package/template/public/demo/feature-4.svg +1 -0
  307. package/template/public/demo/gallery-1.svg +1 -0
  308. package/template/public/demo/gallery-2.svg +1 -0
  309. package/template/public/demo/gallery-3.svg +1 -0
  310. package/template/public/demo/gallery-4.svg +1 -0
  311. package/template/public/demo/gallery-5.svg +1 -0
  312. package/template/public/demo/gallery-6.svg +1 -0
  313. package/template/public/demo/gallery-7.svg +1 -0
  314. package/template/public/demo/gallery-8.svg +1 -0
  315. package/template/public/demo/hero-slide-1.svg +1 -0
  316. package/template/public/demo/hero-slide-2.svg +1 -0
  317. package/template/public/demo/hero-slide-3.svg +1 -0
  318. package/template/public/demo/hero-slide-4.svg +1 -0
  319. package/template/public/demo/hero-wide.svg +1 -0
  320. package/template/public/demo/hero.svg +1 -0
  321. package/template/public/demo/logo-1.svg +4 -0
  322. package/template/public/demo/logo-2.svg +4 -0
  323. package/template/public/demo/logo-3.svg +4 -0
  324. package/template/public/demo/logo-4.svg +4 -0
  325. package/template/public/demo/logo-5.svg +4 -0
  326. package/template/public/demo/logo-6.svg +4 -0
  327. package/template/public/demo/logo-7.svg +4 -0
  328. package/template/public/demo/logo-8.svg +4 -0
  329. package/template/public/demo/logo.svg +3 -0
  330. package/template/public/demo/map.svg +1 -0
  331. package/template/public/demo/poster.svg +1 -0
  332. package/template/public/demo/product-1.svg +4 -0
  333. package/template/public/demo/product-10.svg +4 -0
  334. package/template/public/demo/product-11.svg +4 -0
  335. package/template/public/demo/product-12.svg +4 -0
  336. package/template/public/demo/product-2.svg +4 -0
  337. package/template/public/demo/product-3.svg +4 -0
  338. package/template/public/demo/product-4.svg +4 -0
  339. package/template/public/demo/product-5.svg +4 -0
  340. package/template/public/demo/product-6.svg +4 -0
  341. package/template/public/demo/product-7.svg +4 -0
  342. package/template/public/demo/product-8.svg +4 -0
  343. package/template/public/demo/product-9.svg +4 -0
  344. package/template/public/demo/product-square-1.svg +4 -0
  345. package/template/public/demo/product-square-2.svg +4 -0
  346. package/template/public/demo/product-square-3.svg +4 -0
  347. package/template/public/demo/product-square-4.svg +4 -0
  348. package/template/public/demo/product-square-5.svg +4 -0
  349. package/template/public/demo/product-square-6.svg +4 -0
  350. package/template/public/demo/quote-portrait.svg +4 -0
  351. package/template/public/demo/split-1.svg +1 -0
  352. package/template/public/demo/split-2.svg +1 -0
  353. package/template/public/demo/split-3.svg +1 -0
  354. package/template/public/demo/split-4.svg +1 -0
  355. package/template/public/demo/team-1.svg +4 -0
  356. package/template/public/demo/team-2.svg +4 -0
  357. package/template/public/demo/team-3.svg +4 -0
  358. package/template/public/demo/team-4.svg +4 -0
  359. package/template/scripts/demo-images.mjs +393 -0
  360. package/template/scripts/generate-stories.mjs +156 -0
  361. package/template/scripts/previewHash.mjs +125 -0
  362. package/template/scripts/previews.mjs +149 -0
  363. package/template/stories/generated/announcement-bar.stories.ts +44 -0
  364. package/template/stories/generated/article-list.stories.ts +87 -0
  365. package/template/stories/generated/article.stories.ts +27 -0
  366. package/template/stories/generated/breadcrumbs.stories.ts +39 -0
  367. package/template/stories/generated/cart.stories.ts +38 -0
  368. package/template/stories/generated/collection-grid.stories.ts +117 -0
  369. package/template/stories/generated/collection-header.stories.ts +51 -0
  370. package/template/stories/generated/contact.stories.ts +45 -0
  371. package/template/stories/generated/cta.stories.ts +51 -0
  372. package/template/stories/generated/faq.stories.ts +56 -0
  373. package/template/stories/generated/feature-grid.stories.ts +69 -0
  374. package/template/stories/generated/footer.stories.ts +50 -0
  375. package/template/stories/generated/gallery.stories.ts +81 -0
  376. package/template/stories/generated/hero.stories.ts +75 -0
  377. package/template/stories/generated/image.stories.ts +99 -0
  378. package/template/stories/generated/logo-cloud.stories.ts +57 -0
  379. package/template/stories/generated/navigation.stories.ts +62 -0
  380. package/template/stories/generated/newsletter.stories.ts +68 -0
  381. package/template/stories/generated/order-status.stories.ts +32 -0
  382. package/template/stories/generated/pricing-table.stories.ts +44 -0
  383. package/template/stories/generated/product-carousel.stories.ts +75 -0
  384. package/template/stories/generated/product-detail.stories.ts +62 -0
  385. package/template/stories/generated/quote.stories.ts +69 -0
  386. package/template/stories/generated/rich-text.stories.ts +50 -0
  387. package/template/stories/generated/search.stories.ts +56 -0
  388. package/template/stories/generated/split-content.stories.ts +39 -0
  389. package/template/stories/generated/stats.stories.ts +68 -0
  390. package/template/stories/generated/tabs.stories.ts +45 -0
  391. package/template/stories/generated/team.stories.ts +45 -0
  392. package/template/stories/generated/testimonials.stories.ts +69 -0
  393. package/template/stories/generated/timeline.stories.ts +80 -0
  394. package/template/stories/generated/trust-strip.stories.ts +62 -0
  395. package/template/stories/generated/video-embed.stories.ts +63 -0
  396. package/template/stories/generated/wishlist.stories.ts +26 -0
  397. package/template/stories/pages/article.stories.ts +51 -0
  398. package/template/stories/pages/cart.stories.ts +56 -0
  399. package/template/stories/pages/category.stories.ts +56 -0
  400. package/template/stories/pages/collection.stories.ts +51 -0
  401. package/template/stories/pages/home.stories.ts +51 -0
  402. package/template/stories/pages/product.stories.ts +47 -0
  403. package/template/stories/pages/products.stories.ts +58 -0
  404. package/template/stories/pages/search.stories.ts +54 -0
  405. package/template/stories/pages/wishlist.stories.ts +53 -0
  406. package/template/stories/support/pageBlocks.ts +115 -0
  407. package/template/test/blocksEmptyData.spec.ts +52 -0
  408. package/template/test/carouselKeyboard.spec.ts +272 -0
  409. package/template/test/carouselRing.browser.spec.ts +193 -0
  410. package/template/test/carouselSlideWidth.browser.spec.ts +102 -0
  411. package/template/test/cartDrawer.spec.ts +295 -0
  412. package/template/test/cartToast.spec.ts +86 -0
  413. package/template/test/countPill.browser.spec.ts +196 -0
  414. package/template/test/demoImages.spec.ts +140 -0
  415. package/template/test/deps.spec.ts +102 -0
  416. package/template/test/eldraIcon.spec.ts +58 -0
  417. package/template/test/framing.spec.ts +76 -0
  418. package/template/test/i18n.spec.ts +200 -0
  419. package/template/test/iconComponent.spec.ts +91 -0
  420. package/template/test/inlineEditable.spec.ts +334 -0
  421. package/template/test/localePrefix.spec.ts +342 -0
  422. package/template/test/mainCss.spec.ts +107 -0
  423. package/template/test/mockGatewayContract.spec.ts +122 -0
  424. package/template/test/mocks/blocks.ts +20 -0
  425. package/template/test/mocks/breakpoints.ts +7 -0
  426. package/template/test/mocks/manifest.ts +11 -0
  427. package/template/test/moneyFormatting.spec.ts +89 -0
  428. package/template/test/pageTitle.spec.ts +49 -0
  429. package/template/test/pages/article.spec.ts +231 -0
  430. package/template/test/pages/category.spec.ts +185 -0
  431. package/template/test/pages/collection.spec.ts +396 -0
  432. package/template/test/pages/home.spec.ts +295 -0
  433. package/template/test/pages/hydration.spec.ts +557 -0
  434. package/template/test/pages/product.spec.ts +396 -0
  435. package/template/test/pages/seededPages.spec.ts +190 -0
  436. package/template/test/pages/ssr.spec.ts +393 -0
  437. package/template/test/prerenderCommerce.spec.ts +134 -0
  438. package/template/test/prerenderFailure.spec.ts +130 -0
  439. package/template/test/prerenderRefresh.browser.spec.ts +1431 -0
  440. package/template/test/previewsFresh.spec.ts +56 -0
  441. package/template/test/richText.spec.ts +161 -0
  442. package/template/test/richTextTypography.spec.ts +182 -0
  443. package/template/test/setup.ts +21 -0
  444. package/template/test/slugPage.spec.ts +244 -0
  445. package/template/test/slugPageTemplate.spec.ts +194 -0
  446. package/template/test/starter.spec.ts +1416 -0
  447. package/template/test/storefront/cart.spec.ts +404 -0
  448. package/template/test/storefront/categories.spec.ts +235 -0
  449. package/template/test/storefront/collectionSelector.spec.ts +74 -0
  450. package/template/test/storefront/demo.spec.ts +555 -0
  451. package/template/test/storefront/facets.spec.ts +425 -0
  452. package/template/test/storefront/feedback.spec.ts +97 -0
  453. package/template/test/storefront/gateway.spec.ts +2673 -0
  454. package/template/test/storefront/gatewayCart.spec.ts +289 -0
  455. package/template/test/storefront/gatewayPrerender.spec.ts +1037 -0
  456. package/template/test/storefront/history.spec.ts +341 -0
  457. package/template/test/storefront/money.spec.ts +171 -0
  458. package/template/test/storefront/toProductCard.spec.ts +138 -0
  459. package/template/test/storefront/volatile.spec.ts +284 -0
  460. package/template/test/support/axe.ts +14 -0
  461. package/template/test/support/dialog.ts +51 -0
  462. package/template/test/support/hydrate.ts +118 -0
  463. package/template/test/support/i18nText.ts +11 -0
  464. package/template/test/support/mockGateway.ts +1017 -0
  465. package/template/test/support/mountBlock.ts +194 -0
  466. package/template/test/support/mountPage.spec.ts +72 -0
  467. package/template/test/support/mountPage.ts +254 -0
  468. package/template/test/support/mountProbe.client.ts +69 -0
  469. package/template/test/support/renderSsr.ts +97 -0
  470. package/template/test/support/staticServer.ts +96 -0
  471. package/template/test/themeIcons.spec.ts +140 -0
  472. package/template/test/toastAnnouncement.spec.ts +133 -0
  473. package/template/test/tokens.spec.ts +102 -0
  474. package/template/test/uiMessagesPlugin.spec.ts +104 -0
  475. package/template/test/useBlockData.spec.ts +46 -0
  476. package/template/test/useEditing.spec.ts +54 -0
  477. package/template/test/useEldraIcon.spec.ts +126 -0
  478. package/template/test/useUiId.spec.ts +40 -0
  479. package/template/tokens.json +149 -0
  480. package/template/tsconfig.json +3 -0
  481. package/template/tsconfig.storybook.json +17 -0
  482. package/template/vitest-axe.d.ts +13 -0
  483. package/template/vitest.config.ts +44 -0
@@ -0,0 +1,2256 @@
1
+ import { onWatcherCleanup, ref, watch, type Ref } from 'vue';
2
+ import { createCartSession, EldraHttpError, type EldraClient } from '@eldrajs/sdk';
3
+ import { safeHref } from '../utils/links';
4
+ import { createCartStore, type CartOps, type CartSnapshot } from './cart';
5
+ import { createHistoryStore, createWishlistStore } from './history';
6
+ import { fromMinorUnits, roundMoney, toMinorUnits } from './money';
7
+ import { chunkIds, collectVolatileTargets } from './volatile';
8
+ import { canonicalAvailabilityValues, OPTION_SOURCE_PREFIX } from './facets';
9
+ import { optionDisplayType, storefrontOptionKind } from './options';
10
+ import {
11
+ buildCategoryIndex,
12
+ categoryTrailFor,
13
+ isInSubtree,
14
+ placeCategory,
15
+ type CategoryIndex,
16
+ } from './categories';
17
+ import type { VolatileRefreshEntry } from './refresh';
18
+ import type {
19
+ CatalogFacets,
20
+ StorefrontAck,
21
+ StorefrontCartLine,
22
+ StorefrontCartTotals,
23
+ StorefrontCatalog,
24
+ StorefrontCollectionInfo,
25
+ StorefrontCollectionProducts,
26
+ StorefrontCollectionSelector,
27
+ StorefrontCommerce,
28
+ StorefrontForms,
29
+ StorefrontMedia,
30
+ StorefrontOrder,
31
+ StorefrontOrders,
32
+ StorefrontProduct,
33
+ StorefrontProductListItem,
34
+ StorefrontResult,
35
+ StorefrontRoute,
36
+ StorefrontSearch,
37
+ StorefrontSearchProduct,
38
+ StorefrontSearchResponse,
39
+ StorefrontSource,
40
+ VolatileKey,
41
+ VolatileSnapshot,
42
+ } from './types';
43
+
44
+ /**
45
+ * The live implementation: `client.catalog`/`client.search`/`client.cart`/`client.orders`/
46
+ * `client.inventory` map into the view types in `types.ts`. `@eldrajs/sdk`'s own response types
47
+ * are contract-derived (`EldraContractResponse<...>`) and resolve to `unknown` in this project
48
+ * (no generated `contract.ts` — headless-kit `CLAUDE.md`'s "the SDK ships no response types"
49
+ * invariant), so every `Raw*` interface below is this file's own minimal, hand-written shape of
50
+ * the gateway's actual JSON (matching `packages/sdk/src/__tests__/fixtures/contract.ts`, a
51
+ * generated *test* fixture never imported here) — the same thing a real customer theme has to do
52
+ * before its own `eldra()` Vite plugin has generated a contract against their tenant.
53
+ *
54
+ * `forms.subscribe`/`forms.sendMessage`/`catalog.notifyBackInStock` have no gateway endpoint
55
+ * today: this posts to `options.formsEndpoint` when the plugin configured one, and resolves
56
+ * `{ ok: false, reason: 'unsupported' }` otherwise.
57
+ */
58
+
59
+ // ---------------------------------------------------------------------------------------------
60
+ // Raw gateway shapes this file expects (see the file-level comment above)
61
+ // ---------------------------------------------------------------------------------------------
62
+
63
+ interface RawThumbnail {
64
+ assetId: string;
65
+ url: string;
66
+ altText?: string;
67
+ }
68
+
69
+ interface RawProductListItem {
70
+ id: string;
71
+ slug: string;
72
+ title: string;
73
+ status: string;
74
+ minPrice: number;
75
+ maxPrice: number;
76
+ compareAtPrice?: number;
77
+ thumbnail?: RawThumbnail;
78
+ totalVariants: number;
79
+ /**
80
+ * **Declared, and read when it is there.** The catalogue's product *list* answers no options
81
+ * today — a row carries `totalVariants` and nothing about what the variants differ by — so the
82
+ * colour dots on a card come from the demo source's own fixture and from nothing on the live
83
+ * site. A list read that does carry them (a gateway that grows the field, a customer's own
84
+ * source shaped like this one) feeds `mapProductListItem`'s `colours` without another change
85
+ * here; see its own comment for why the dots are gated on the option's `kind`.
86
+ */
87
+ options?: RawProductOption[] | null;
88
+ }
89
+
90
+ /**
91
+ * One row of the whole-store category list — how a category slug becomes a catalog id, and, through
92
+ * `parentId`, the whole tree a product's breadcrumb trail and the grid's nested category facet are
93
+ * walked from (`app/storefront/categories.ts`). `parentId` is absent on a root and on a gateway
94
+ * answering a contract that had no tree, which `buildCategoryIndex` reads the same way: a root.
95
+ */
96
+ interface RawCategory {
97
+ id: string;
98
+ slug: string;
99
+ title: string;
100
+ parentId?: string | null;
101
+ }
102
+
103
+ /**
104
+ * The `facets` object `facets=true` adds to a product list (`catalogweb_WebProductFacets`), as
105
+ * loosely as this file reads every other response: every field optional, because a gateway that
106
+ * answers an older contract answers none of them and the panel has to degrade rather than throw.
107
+ *
108
+ * `price` is in **minor** units here — the same units as the `minPrice`/`maxPrice` parameters it is
109
+ * counted over, and deliberately unlike a row's own major-unit `minPrice`. `mapFacets` converts.
110
+ *
111
+ * `availability` is **absent, not zeroed**, when the platform could not read stock, which is a
112
+ * different answer from "nothing is in stock": the panel hides that group rather than offering two
113
+ * zeroes (`CatalogFacets.availability`).
114
+ */
115
+ interface RawFacetTerm {
116
+ id?: string;
117
+ slug?: string;
118
+ title?: string;
119
+ count?: number;
120
+ /**
121
+ * The platform's own placement of a `categories` term in the tree (public contract 3.8.0):
122
+ * **absent for a root**, otherwise the nearest *reported* ancestor — an id always present in the
123
+ * same list, never a dangling one. Absent on every term of a pre-3.8.0 response too, which is why
124
+ * the tree is otherwise completed from the category list; a response that places a term is also one
125
+ * whose counts are rolled up, and both halves are then the platform's (see `mapFacets` and
126
+ * `CatalogFacets.categoryCounts`).
127
+ */
128
+ parentId?: string | null;
129
+ }
130
+
131
+ interface RawFacetOptionValue {
132
+ value?: string;
133
+ label?: string;
134
+ /** The same nullable colour `RawProductOptionValue.swatch` carries — one field of the platform's,
135
+ * described the same way on both reads so the two mappings cannot disagree about what `null`
136
+ * means. */
137
+ swatch?: string | null;
138
+ count?: number;
139
+ }
140
+
141
+ interface RawFacetOption {
142
+ key?: string;
143
+ name?: string;
144
+ /** `none` | `color` | `custom`, read through `storefrontOptionKind` — absent on a gateway older
145
+ * than the contract that added it, which reads as `none`. */
146
+ kind?: string;
147
+ /** The merchant's name for a `custom` option; `null`/absent on every other kind. */
148
+ metadata?: string | null;
149
+ values?: RawFacetOptionValue[] | null;
150
+ }
151
+
152
+ interface RawProductFacets {
153
+ price?: { min?: number; max?: number; histogram?: number[] | null } | null;
154
+ categories?: RawFacetTerm[] | null;
155
+ collections?: RawFacetTerm[] | null;
156
+ availability?: { in_stock?: number; out_of_stock?: number } | null;
157
+ options?: RawFacetOption[] | null;
158
+ toggles?: Array<{ key?: string; label?: string; count?: number }> | null;
159
+ }
160
+
161
+ interface RawMediaItem {
162
+ assetId: string;
163
+ url: string;
164
+ altText?: string;
165
+ sortOrder: number;
166
+ }
167
+
168
+ interface RawProductOptionValue {
169
+ id: string;
170
+ key: string;
171
+ name: string;
172
+ /** A hex colour (`#RRGGBB` / `#RRGGBBAA`) the merchant picked for this value. The platform allows
173
+ * one only under a `color`-kind option and omits the key otherwise. */
174
+ swatch?: string | null;
175
+ }
176
+
177
+ interface RawProductOption {
178
+ id: string;
179
+ key: string;
180
+ name: string;
181
+ /** The merchant's "Display as" choice — `none` | `color` | `custom`. Absent on a gateway older
182
+ * than the contract that added it; `storefrontOptionKind` reads that as `none`. */
183
+ kind?: string;
184
+ /** The merchant's name for a `custom` option; `null`/absent on every other kind. */
185
+ metadata?: string | null;
186
+ values?: RawProductOptionValue[] | null;
187
+ }
188
+
189
+ interface RawProductVariant {
190
+ id: string;
191
+ sku: string;
192
+ price: number;
193
+ compareAtPrice?: number;
194
+ status: string;
195
+ media?: RawMediaItem[] | null;
196
+ optionValues?: Array<{
197
+ id: string;
198
+ name: string;
199
+ optionId: string;
200
+ optionValueId: string;
201
+ }> | null;
202
+ }
203
+
204
+ interface RawProductDetails {
205
+ id: string;
206
+ slug: string;
207
+ title: string;
208
+ status: string;
209
+ /** Optional on purpose: the gateway's product detail response carries it for
210
+ * a product that has a category and omits it otherwise. `related` uses it to
211
+ * find products of the same kind — see `relatedProducts`. */
212
+ categoryId?: string;
213
+ /**
214
+ * **The category the breadcrumb trail is walked up from** — the one of `categoryIds` the merchant
215
+ * marked primary. Preferred over `categoryId` above where both are present (they are the same id
216
+ * on every response seen so far; this one is the field the public contract names), and a product
217
+ * with no category carries neither.
218
+ */
219
+ primaryCategoryId?: string;
220
+ /**
221
+ * Every category this product is in. Read by nothing here yet — the trail is one path, not a set,
222
+ * and a product in Cups and in Gifts has one crumb — but declared so the next reader of this file
223
+ * knows the response carries it rather than inferring the catalogue only ever assigns one.
224
+ */
225
+ categoryIds?: string[] | null;
226
+ description?: Record<string, unknown>;
227
+ mediaLinks?: RawMediaItem[] | null;
228
+ options?: RawProductOption[] | null;
229
+ variants?: RawProductVariant[] | null;
230
+ }
231
+
232
+ /** One row of `POST /inventory/v1/stock/availability`'s answer. */
233
+ interface RawStockAvailability {
234
+ variantId: string;
235
+ available: boolean;
236
+ allowBackorder: boolean;
237
+ availableQuantity: number;
238
+ }
239
+
240
+ interface RawCollectionItem {
241
+ id: string;
242
+ slug: string;
243
+ title: string;
244
+ description?: string;
245
+ image?: RawThumbnail;
246
+ productCount: number;
247
+ }
248
+
249
+ interface RawPageMeta {
250
+ page: number;
251
+ pageSize: number;
252
+ total: number;
253
+ totalPages: number;
254
+ rows: number;
255
+ hasNext: boolean;
256
+ hasPrev: boolean;
257
+ }
258
+
259
+ interface RawProductList {
260
+ data: RawProductListItem[] | null;
261
+ meta: RawPageMeta;
262
+ /** Present only when the read asked for it (`facets=true`). */
263
+ facets?: RawProductFacets | null;
264
+ }
265
+
266
+ interface RawSearchResult {
267
+ /** The **search index row's** own id. Unique per row, and not a catalog id: nothing in the
268
+ * catalogue answers to it. */
269
+ id: string;
270
+ /**
271
+ * The id of the **document the row is about** — for a `PRODUCT` row, the catalog product id.
272
+ * Required by the gateway's own schema (`dto_Result`), optional here only so a response that
273
+ * somehow omits it degrades to an unpriced row rather than asking the catalogue about nothing.
274
+ */
275
+ sourceId?: string;
276
+ kind: 'PRODUCT' | 'CMS_ENTRY' | 'CMS_SCHEMA' | 'CATEGORY';
277
+ title: string;
278
+ targetUrl?: string;
279
+ snippet?: string;
280
+ summary?: string;
281
+ breadcrumb?: string;
282
+ metadata?: Record<string, unknown>;
283
+ }
284
+
285
+ interface RawSearchResponse {
286
+ results: RawSearchResult[] | null;
287
+ total: number;
288
+ }
289
+
290
+ interface RawCartItem {
291
+ id: string;
292
+ productId: string;
293
+ /** The product's public slug, snapshotted by the cart; absent on lines added before it was. */
294
+ productSlug?: string;
295
+ variantId: string;
296
+ title: string;
297
+ price: number;
298
+ quantity: number;
299
+ thumbnail?: { assetId: string; url: string };
300
+ optionSnapshots?: Array<{ optionName?: string; optionValueName?: string }> | null;
301
+ }
302
+
303
+ interface RawCartTotals {
304
+ subtotal: number;
305
+ discount: number;
306
+ taxAmount: number;
307
+ total: number;
308
+ }
309
+
310
+ interface RawCart {
311
+ id: string;
312
+ currency: string;
313
+ items?: RawCartItem[] | null;
314
+ totals: RawCartTotals;
315
+ discountCode?: string;
316
+ }
317
+
318
+ interface RawOrderLine {
319
+ id: string;
320
+ productId: string;
321
+ /** The product's public slug as the order snapshotted it; older orders carry none. */
322
+ slug?: string;
323
+ productName: string;
324
+ variantId?: string;
325
+ variantName?: string;
326
+ sku: string;
327
+ quantity: number;
328
+ unitPrice: number;
329
+ totalPrice: number;
330
+ imageUrl?: string;
331
+ }
332
+
333
+ interface RawOrder {
334
+ id: string;
335
+ orderNumber: number;
336
+ status: string;
337
+ createdAt: string;
338
+ orderLines?: RawOrderLine[] | null;
339
+ subtotalAmount: number;
340
+ shippingAmount: number;
341
+ taxAmount: number;
342
+ totalAmount: number;
343
+ discountAmount: number;
344
+ discountCode?: string;
345
+ shipping?: {
346
+ customer: { name: string; address: string; town: string; zipcode: number };
347
+ providerType: string;
348
+ };
349
+ }
350
+
351
+ // ---------------------------------------------------------------------------------------------
352
+ // Mapping — raw gateway JSON → this theme's view types (money is major units on both sides, so
353
+ // every amount below is a pass-through; see `app/storefront/money.ts`)
354
+ // ---------------------------------------------------------------------------------------------
355
+
356
+ function toMedia(
357
+ item: RawThumbnail | RawMediaItem | undefined,
358
+ fallbackAlt: string
359
+ ): StorefrontMedia | null {
360
+ if (!item) return null;
361
+ return { src: item.url, alt: item.altText ?? fallbackAlt };
362
+ }
363
+
364
+ /**
365
+ * **The colour dots a card draws, from the product's `color`-kind option.**
366
+ *
367
+ * `undefined` — not `[]` — when the read carries no options at all, because the two are different
368
+ * answers and `app/storefront/facets.ts` reads them apart: absent means "this source cannot say
369
+ * what colours this product comes in", while an empty list would mean "none", which would exclude
370
+ * the product from every colour filter. The catalogue's list read answers no options today, so that
371
+ * is the live site's answer; see `RawProductListItem.options`.
372
+ *
373
+ * The **first** `color`-kind option only. `colours` is one row of dots under one image: a product
374
+ * with two colour options has no single list of colours to draw, and concatenating them would
375
+ * invent one.
376
+ *
377
+ * A value with no swatch is left out rather than drawn as a blank circle. An option whose kind is
378
+ * `none` contributes nothing, whatever it is called — the same "never guess from the key" rule the
379
+ * product page's picker follows.
380
+ */
381
+ function listItemColours(raw: RawProductListItem): StorefrontProductListItem['colours'] {
382
+ const options = raw.options;
383
+ if (options === undefined || options === null) return undefined;
384
+ const colour = options.find((option) => storefrontOptionKind(option.kind) === 'color');
385
+ if (colour === undefined) return [];
386
+ return (colour.values ?? [])
387
+ .filter((value) => typeof value.swatch === 'string' && value.swatch !== '')
388
+ .map((value) => ({ name: value.name, swatch: value.swatch! }));
389
+ }
390
+
391
+ function mapProductListItem(raw: RawProductListItem): StorefrontProductListItem {
392
+ const colours = listItemColours(raw);
393
+ return {
394
+ handle: raw.slug,
395
+ title: raw.title,
396
+ url: `/products/${raw.slug}`,
397
+ featuredImage: toMedia(raw.thumbnail, raw.title),
398
+ price: {
399
+ amount: raw.minPrice,
400
+ compareAt: raw.compareAtPrice ?? null,
401
+ from: raw.minPrice !== raw.maxPrice,
402
+ },
403
+ ...(colours === undefined ? {} : { colours }),
404
+ // A card stays on the product's published status, not on inventory: the availability read is
405
+ // per *variant*, and a list row carries no variant at all (see `StorefrontProductListItem`), so
406
+ // answering a grid from inventory would mean one product detail read per card. The product page
407
+ // is where the honest number belongs, and it is the only page whose button spends it.
408
+ stock: raw.status === 'ACTIVE' ? 'in' : 'out',
409
+ available: raw.status === 'ACTIVE',
410
+ productId: raw.id,
411
+ };
412
+ }
413
+
414
+ /**
415
+ * What the inventory service says about each of a product's variants, by variant id.
416
+ *
417
+ * `null` — and a variant missing from a non-null map — both mean "nothing known", which is not the
418
+ * same as "nothing left": the mapping below then falls back to the variant's own `status`, exactly
419
+ * what it used before this read existed. That is the fail-soft rule the whole feature rests on: a
420
+ * store that has not set inventory up, an inventory service that is down, and a product whose
421
+ * variants it has never heard of all keep a working product page instead of a catalogue that reads
422
+ * sold out.
423
+ */
424
+ type StockByVariant = ReadonlyMap<string, RawStockAvailability>;
425
+
426
+ /**
427
+ * The product page's inventory read. The catalogue's own product response carries a variant's
428
+ * `status` — whether it is published — and nothing at all about units, so a published variant with
429
+ * no stock read "In stock, ready to ship" beside an Add to cart the cart service then refused. One
430
+ * bulk call answers for every variant of the product at once.
431
+ *
432
+ * No `locationId` is sent: an item without one resolves the organisation's default location, which
433
+ * is the only location a storefront knows about.
434
+ *
435
+ * It never throws and never reports. A shopper cannot act on "we could not reach inventory", and
436
+ * the page has a usable answer without it (see `StockByVariant`), so a failure is silent by design.
437
+ */
438
+ async function readStock(
439
+ client: EldraClient,
440
+ raw: RawProductDetails,
441
+ signal?: AbortSignal
442
+ ): Promise<StockByVariant | null> {
443
+ const items = (raw.variants ?? [])
444
+ .map((variant) => variant.id)
445
+ .filter((variantId) => variantId !== '')
446
+ .map((variantId) => ({ variantId }));
447
+ if (items.length === 0) return null;
448
+ try {
449
+ const answer = (await client.inventory.availability(
450
+ items,
451
+ signal ? { signal } : {}
452
+ )) as unknown as {
453
+ items?: RawStockAvailability[] | null;
454
+ };
455
+ const byVariant = new Map<string, RawStockAvailability>();
456
+ for (const item of answer.items ?? []) byVariant.set(item.variantId, item);
457
+ return byVariant.size === 0 ? null : byVariant;
458
+ } catch {
459
+ return null;
460
+ }
461
+ }
462
+
463
+ /** Can this variant be bought right now: published, and either in stock or open to back-order. */
464
+ function variantBuyable(variant: RawProductVariant, stock: StockByVariant | null): boolean {
465
+ if (variant.status !== 'ACTIVE') return false;
466
+ const known = stock?.get(variant.id);
467
+ return known === undefined || known.available || known.allowBackorder;
468
+ }
469
+
470
+ /** The product-level stock signal `deriveStockLine` reads, for the variant the page shows. */
471
+ function variantStock(
472
+ variant: RawProductVariant | undefined,
473
+ stock: StockByVariant | null
474
+ ): StorefrontProduct['stock'] {
475
+ if (variant === undefined || variant.status !== 'ACTIVE') return 'out';
476
+ const known = stock?.get(variant.id);
477
+ if (known === undefined) return 'in';
478
+ if (known.available) return 'in';
479
+ return known.allowBackorder ? 'preorder' : 'out';
480
+ }
481
+
482
+ function mapProductDetails(
483
+ raw: RawProductDetails,
484
+ stock: StockByVariant | null,
485
+ /**
486
+ * The store's category tree, for the breadcrumb trail. `null` from a read that could not reach the
487
+ * category list, which leaves the trail empty rather than failing the product page: see the
488
+ * `catalog.product` fetcher.
489
+ */
490
+ categories: CategoryIndex | null
491
+ ): StorefrontProduct {
492
+ const variants = raw.variants ?? [];
493
+ // Spec Do/Don't, "Don't pre-select a sold-out variant": the variant the page opens on is the
494
+ // first one a shopper could actually buy, and only when none can does it fall back to the first
495
+ // published one — which is the variant whose sold-out line the shopper then reads.
496
+ const firstAvailable =
497
+ variants.find((variant) => variantBuyable(variant, stock)) ??
498
+ variants.find((variant) => variant.status === 'ACTIVE') ??
499
+ variants[0];
500
+ /** The variant whose unit count is unambiguously *the* count: there is only one thing to buy. */
501
+ const countableVariant =
502
+ variants.length === 1 || (raw.options ?? []).length === 0 ? firstAvailable : undefined;
503
+ const prices = variants.map((variant) => variant.price);
504
+ const minPrice = prices.length > 0 ? Math.min(...prices) : 0;
505
+ const images = (raw.mediaLinks ?? [])
506
+ .slice()
507
+ .sort((a, b) => a.sortOrder - b.sortOrder)
508
+ .map((media) => toMedia(media, raw.title))
509
+ .filter((media): media is StorefrontMedia => media !== null);
510
+
511
+ return {
512
+ handle: raw.slug,
513
+ title: raw.title,
514
+ url: `/products/${raw.slug}`,
515
+ featuredImage: images[0] ?? null,
516
+ images,
517
+ price: {
518
+ amount: firstAvailable?.price ?? minPrice,
519
+ compareAt: firstAvailable?.compareAtPrice ?? null,
520
+ },
521
+ // **The merchant's "Display as" choice is what decides the control**, never the option's name.
522
+ // Every option used to map to `pills`, and the only way a theme could have drawn the colour
523
+ // circles a store's photography needs was to match on the word "Colour" — which is a merchant's
524
+ // label, translated per locale and theirs to change. Now the platform carries `kind` on the
525
+ // option and the swatch hex on each value, and `optionDisplayType` is the single place a kind
526
+ // and its colours become a control (`app/storefront/options.ts`).
527
+ options: (raw.options ?? []).map((option) => {
528
+ const kind = storefrontOptionKind(option.kind);
529
+ const values = (option.values ?? []).map((value) => ({
530
+ value: value.key,
531
+ label: value.name,
532
+ // Passed through whatever the option's kind says — the platform allows a swatch only under
533
+ // `color`, and a picker drawing pills never reads one. Gating the colour on the kind as well
534
+ // would mean a gateway that populates the swatch before it populates the kind silently loses
535
+ // the store's colours.
536
+ ...(value.swatch ? { swatch: value.swatch } : {}),
537
+ available: variants.some(
538
+ (variant) =>
539
+ variantBuyable(variant, stock) &&
540
+ (variant.optionValues ?? []).some((ov) => ov.optionValueId === value.id)
541
+ ),
542
+ }));
543
+ return {
544
+ name: option.key,
545
+ label: option.name,
546
+ kind,
547
+ // Only a `custom` option has a name of its own, and only a non-empty one is a name. A
548
+ // `metadata` the platform sent under another kind is dropped rather than carried: a theme
549
+ // branching on it would be branching on a field the merchant cannot see or set there.
550
+ ...(kind === 'custom' && option.metadata ? { metadata: option.metadata } : {}),
551
+ // The mapped values, not the raw ones: `kind` is permission to draw swatches and these are
552
+ // whether there is anything to draw. A `color` option whose colours a merchant never picked —
553
+ // or cleared again, which Studio's own control allows — is pills, because a swatch picker
554
+ // with no colours hides every value's name in `sr-only` text and the shopper is left picking
555
+ // between identical empty circles.
556
+ type: optionDisplayType(kind, values),
557
+ values,
558
+ };
559
+ }),
560
+ // Root ancestor down to the product's own category, each level a link into the catalogue
561
+ // filtered by it (`app/storefront/categories.ts`). `[]` for a product with no category, a
562
+ // category the list does not hold, and a category read that failed — three honest absences, one
563
+ // of which used to be the only answer this mapping had: it read `result.breadcrumb`, a field of
564
+ // the *search* response that no product read has ever carried, so every product page shipped
565
+ // with no category crumb at all.
566
+ categoryTrail:
567
+ categories === null
568
+ ? []
569
+ : categoryTrailFor(categories, raw.primaryCategoryId ?? raw.categoryId),
570
+ description: (() => {
571
+ const text = raw.description?.text;
572
+ return typeof text === 'string' ? text : '';
573
+ })(),
574
+ // Real units — but only when they cannot be mis-attributed. `StorefrontProduct.inventory` is
575
+ // *the selected variant's* count (see its own declaration), and the one variant this mapping can
576
+ // speak for is `firstAvailable`: the variant an add sends, which is not necessarily the one the
577
+ // shopper has picked in the buy box. So a product with options and more than one variant reports
578
+ // no count at all rather than labelling M's two units "only 2 left in L" — the same `null` a
579
+ // store that tracks no units sends, which simply leaves the low-stock line off (spec States, Low
580
+ // stock). Reporting per-variant counts means carrying every variant's availability on the product
581
+ // and resolving the shopper's selection against it, which is also what the buy box would need to
582
+ // add the variant it is showing rather than the first buyable one.
583
+ inventory: countableVariant
584
+ ? (stock?.get(countableVariant.id)?.availableQuantity ?? null)
585
+ : null,
586
+ stock: variantStock(firstAvailable, stock),
587
+ available: raw.status === 'ACTIVE',
588
+ productId: raw.id,
589
+ // The variant an add would send, paired with `productId` above: the cart service looks the two
590
+ // up together and refuses a variant that does not belong to the product it was given. A product
591
+ // with no variants at all has nothing buyable, so there is no id to fall back to.
592
+ variantId: firstAvailable?.id ?? '',
593
+ };
594
+ }
595
+
596
+ function mapCollectionItem(raw: RawCollectionItem): StorefrontCollectionInfo {
597
+ return {
598
+ handle: raw.slug,
599
+ title: raw.title,
600
+ description: raw.description ?? null,
601
+ image: toMedia(raw.image, raw.title),
602
+ productCount: raw.productCount,
603
+ };
604
+ }
605
+
606
+ function mapCartLine(raw: RawCartItem): StorefrontCartLine {
607
+ const variantLabel = (raw.optionSnapshots ?? [])
608
+ .map((snapshot) => snapshot.optionValueName)
609
+ .filter((value): value is string => Boolean(value))
610
+ .join(' / ');
611
+ return {
612
+ id: raw.id,
613
+ productId: raw.productId,
614
+ variantId: raw.variantId,
615
+ title: raw.title,
616
+ // The storefront's product route is `/products/<slug>`; the id is only a fallback for a line
617
+ // snapshotted before the cart carried the slug, where nothing better exists.
618
+ url: `/products/${raw.productSlug || raw.productId}`,
619
+ variantLabel,
620
+ quantity: raw.quantity,
621
+ unitPrice: raw.price,
622
+ // The one amount this mapping computes rather than copies, so it is the one that needs
623
+ // rounding back to two decimals (major-unit arithmetic is floating point).
624
+ lineTotal: roundMoney(raw.price * raw.quantity),
625
+ image: raw.thumbnail ? { src: raw.thumbnail.url, alt: raw.title } : null,
626
+ max: null,
627
+ };
628
+ }
629
+
630
+ function mapCartTotals(raw: RawCartTotals, discountCode: string | undefined): StorefrontCartTotals {
631
+ return {
632
+ subtotal: raw.subtotal,
633
+ discount:
634
+ discountCode && raw.discount > 0 ? { code: discountCode, amount: raw.discount } : null,
635
+ shipping: null,
636
+ tax: raw.taxAmount,
637
+ total: raw.total,
638
+ };
639
+ }
640
+
641
+ function mapCart(raw: RawCart): CartSnapshot {
642
+ return {
643
+ lines: (raw.items ?? []).map(mapCartLine),
644
+ totals: mapCartTotals(raw.totals, raw.discountCode),
645
+ };
646
+ }
647
+
648
+ const ORDER_STATUS_MAP: Record<string, StorefrontOrder['status']> = {
649
+ PENDING: 'processing',
650
+ CONFIRMED: 'processing',
651
+ PROCESSING: 'processing',
652
+ SHIPPED: 'shipped',
653
+ DELIVERED: 'delivered',
654
+ DELAYED: 'delayed',
655
+ CANCELLED: 'cancelled',
656
+ CANCELED: 'cancelled',
657
+ };
658
+
659
+ function mapOrder(raw: RawOrder): StorefrontOrder {
660
+ const status = ORDER_STATUS_MAP[raw.status.toUpperCase()] ?? 'processing';
661
+ const lines: StorefrontCartLine[] = (raw.orderLines ?? []).map((line) => ({
662
+ id: line.id,
663
+ productId: line.productId,
664
+ variantId: line.variantId ?? '',
665
+ title: line.productName,
666
+ url: `/products/${line.slug || line.productId}`,
667
+ variantLabel: line.variantName ?? '',
668
+ quantity: line.quantity,
669
+ unitPrice: line.unitPrice,
670
+ lineTotal: line.totalPrice,
671
+ image: line.imageUrl ? { src: line.imageUrl, alt: line.productName } : null,
672
+ max: null,
673
+ }));
674
+ return {
675
+ number: `NW-${raw.orderNumber}`,
676
+ placedAt: raw.createdAt,
677
+ itemCount: lines.reduce((sum, line) => sum + line.quantity, 0),
678
+ status,
679
+ steps: [
680
+ { key: 'ordered', label: 'Ordered', date: raw.createdAt, state: 'done' },
681
+ {
682
+ key: 'packed',
683
+ label: 'Packed',
684
+ date: null,
685
+ state: status === 'processing' ? 'current' : 'done',
686
+ },
687
+ {
688
+ key: 'shipped',
689
+ label: 'Shipped',
690
+ date: null,
691
+ state:
692
+ status === 'shipped'
693
+ ? 'current'
694
+ : status === 'delivered' || status === 'delayed'
695
+ ? 'done'
696
+ : 'upcoming',
697
+ },
698
+ {
699
+ key: 'delivered',
700
+ label: 'Delivered',
701
+ date: null,
702
+ state: status === 'delivered' ? 'done' : status === 'delayed' ? 'warning' : 'upcoming',
703
+ },
704
+ ],
705
+ lines,
706
+ totals: {
707
+ subtotal: raw.subtotalAmount,
708
+ discount:
709
+ raw.discountCode && raw.discountAmount > 0
710
+ ? { code: raw.discountCode, amount: raw.discountAmount }
711
+ : null,
712
+ shipping: raw.shippingAmount,
713
+ tax: raw.taxAmount,
714
+ total: raw.totalAmount,
715
+ },
716
+ shippingAddress: raw.shipping
717
+ ? [raw.shipping.customer.name, raw.shipping.customer.address, raw.shipping.customer.town]
718
+ : [],
719
+ payment: { brand: '', last4: '' },
720
+ };
721
+ }
722
+
723
+ /**
724
+ * The authoring surface's own path prefix. A result pointing inside it is an editing URL, not a
725
+ * storefront one: the site serves no file for it, so a shopper who follows the row leaves the shop
726
+ * for a 404.
727
+ */
728
+ const AUTHORING_PATH = '/cms';
729
+
730
+ /**
731
+ * A result's destination, or `null` when the theme cannot route it.
732
+ *
733
+ * Two rules, and both are the theme's own rather than the backend's. `safeHref` is the scheme
734
+ * allowlist every other href in the theme passes through — `javascript:`, `data:`, a
735
+ * protocol-relative `//host` and a missing value all answer `null`. On top of it, a path under
736
+ * `/cms` is dropped: the search index is built over the platform's own documents, and a document
737
+ * that has no public route can only be named by its authoring URL. The backend only returns
738
+ * routable results now; this stays because a result the theme cannot route is worse than a result
739
+ * the shopper never saw, and the theme is the side that knows what it can route.
740
+ */
741
+ function routableResultHref(targetUrl: unknown): string | null {
742
+ const href = safeHref(targetUrl);
743
+ if (href === null) return null;
744
+ if (href === AUTHORING_PATH || href.startsWith(`${AUTHORING_PATH}/`)) return null;
745
+ return href;
746
+ }
747
+
748
+ /**
749
+ * Every URL in this response is gateway-supplied, so each one goes through `routableResultHref`
750
+ * here and a result whose `targetUrl` does not survive it is **dropped**, not carried with a
751
+ * placeholder.
752
+ *
753
+ * This used to be `result.targetUrl ?? '#'`, which turned a result with no destination into a card
754
+ * or row linking to nowhere (a link to the current page), and — worse — let any URL the gateway
755
+ * returned reach the DOM unchecked while every CMS-authored href in the theme was gated. This is the
756
+ * one place the search response crosses that trust boundary, so it is the one place that decides:
757
+ * a result without a usable link is not a result the shopper can act on.
758
+ */
759
+ function mapSearchResponse(raw: RawSearchResponse, query: string): StorefrontSearchResponse {
760
+ const results = raw.results ?? [];
761
+ const linkedResults = results.flatMap((result) => {
762
+ const href = routableResultHref(result.targetUrl);
763
+ return href === null ? [] : [{ result, href }];
764
+ });
765
+ const products: StorefrontSearchProduct[] = linkedResults
766
+ .filter(({ result }) => result.kind === 'PRODUCT')
767
+ .map(({ result, href }) => ({
768
+ // The index row's id, used as nothing but the row's key: a search result carries no slug, and
769
+ // the destination the shopper follows is `targetUrl`, not a handle this theme builds.
770
+ handle: result.id,
771
+ title: result.title,
772
+ url: href,
773
+ // Neither an image nor a price is in a search result. `enrichedSearchResponse` reads both
774
+ // from the catalogue before the response reaches a block, and a product it could not reach
775
+ // keeps `price: null` all the way out — never a zero, which every consumer would format as the
776
+ // store's own "$0.00" (`StorefrontSearchProduct`).
777
+ featuredImage: null,
778
+ price: null,
779
+ stock: 'in',
780
+ available: true,
781
+ // **`sourceId`, not `id`.** `id` names the index row; `sourceId` names the catalog product,
782
+ // and it is the only one of the two the catalogue has ever heard of. Asking
783
+ // `products/list?filter=id:in:<row id>` answers zero rows every time, which is why every
784
+ // search suggestion and every search result card shipped without a price or a thumbnail.
785
+ productId: result.sourceId ?? '',
786
+ }));
787
+ const articles = linkedResults
788
+ .filter(({ result }) => result.kind === 'CMS_ENTRY')
789
+ .map(({ result, href }) => ({
790
+ title: result.title,
791
+ href,
792
+ category: result.breadcrumb ?? '',
793
+ readingTime: '',
794
+ image: null,
795
+ }));
796
+ const pages = linkedResults
797
+ .filter(({ result }) => result.kind === 'CMS_SCHEMA')
798
+ .map(({ result, href }) => ({
799
+ title: result.title,
800
+ href,
801
+ path: href,
802
+ snippet: result.snippet ?? result.summary ?? '',
803
+ }));
804
+ return { query, total: raw.total, products, articles, pages, suggestion: null };
805
+ }
806
+
807
+ // ---------------------------------------------------------------------------------------------
808
+ // StorefrontResult helper — one AbortController per watcher, aborted on re-run/teardown; error
809
+ // text comes from `EldraHttpError.message` when the gateway itself rejected the request.
810
+ // ---------------------------------------------------------------------------------------------
811
+
812
+ function errorMessage(caught: unknown): string {
813
+ if (caught instanceof EldraHttpError) return caught.message;
814
+ if (caught instanceof Error) return caught.message;
815
+ return 'Something went wrong.';
816
+ }
817
+
818
+ /**
819
+ * The two abilities the app layer lends this file, because both of them are its framework's and
820
+ * this file has none: a keyed fetch the framework awaits while it renders the page, and the page's
821
+ * one volatile refresh after hydration. `app/plugins/eldra-storefront.ts` implements them over
822
+ * Nuxt's `useAsyncData` and `app:mounted`; a spec implements them in a dozen lines; Storybook and
823
+ * the demo storefront pass none at all and every result behaves exactly as it did before any of
824
+ * this existed.
825
+ */
826
+ export interface StorefrontRuntime {
827
+ /**
828
+ * Runs a result's *first* load under `key`, so the value is awaited during SSR/prerender, rides
829
+ * to the browser in the page payload, and is read back out of it during hydration without the
830
+ * gateway being called a second time. `null` means "nothing prerendered behind this one" — a
831
+ * result created after hydration — and the result then loads the ordinary way.
832
+ */
833
+ prerender?<T>(key: string, load: () => Promise<T | null>): StorefrontPrerenderHandle<T> | null;
834
+ /** Takes the result into the page's one batched volatile refresh (`refresh.ts`). */
835
+ register?(entry: VolatileRefreshEntry): void;
836
+ }
837
+
838
+ export interface StorefrontPrerenderHandle<T> {
839
+ /**
840
+ * The framework's **settled answer**, known *synchronously* — the hydration payload's own copy.
841
+ * Hydration must paint the prerendered DOM in its first render, and a value that arrives a
842
+ * microtask later arrives after Vue has already matched the server's HTML against an empty page.
843
+ *
844
+ * It is a box rather than the value itself because `null` is an answer: a payload that carries
845
+ * `null` for this key is a read that ran on the server and found nothing — a discontinued
846
+ * product, a collection reference that no longer resolves — and the server painted its
847
+ * "no longer available" line with nothing pending. `{ data: null }` says that; a bare `null`
848
+ * could not be told apart from "no answer yet", which made the browser's first paint the
849
+ * *loading* line over the server's not-found line.
850
+ *
851
+ * `null` therefore means exactly one thing: the load behind the key is still running (every
852
+ * SSR/prerender render, and a hydrating client whose payload has no value for this key).
853
+ */
854
+ answered: { data: T | null } | null;
855
+ /** Settles when the keyed load has finished; already settled for an answered handle. */
856
+ settled: Promise<{ data: T | null; error: string | null }>;
857
+ }
858
+
859
+ /** How a result refreshes its volatile values after hydration — see `refresh.ts`. */
860
+ type VolatileRefresh = 'batch' | ((current: unknown) => Promise<VolatileSnapshot[]>);
861
+
862
+ interface GatewayResultOptions {
863
+ /** The method half of the async-data key: `catalog.product`, `search.run`, … */
864
+ method: string;
865
+ runtime: StorefrontRuntime | undefined;
866
+ /**
867
+ * The active content locale, which is **part of the key**: `/products/x` and `/is-IS/products/x`
868
+ * are one read of one product in two languages, and they must not share a cache entry. Nuxt's
869
+ * payload plugin writes the destination's keys into `nuxtApp.static.data` on every navigation
870
+ * and `useAsyncData` reuses an existing entry for a key it has already seen, so without the
871
+ * locale a shopper switching language would be served the data of the language they left — and,
872
+ * for the tick both pages are mounted, the two would fight over one entry.
873
+ */
874
+ locale?: () => string | undefined;
875
+ /** Arguments that are not reactive sources but still name a different read (`related`'s limit). */
876
+ keyArgs?: readonly unknown[];
877
+ /** Omitted for a result that is not about products (a collection's own info, an order). */
878
+ volatile?: VolatileRefresh;
879
+ }
880
+
881
+ const NOTHING_REVALIDATING: ReadonlySet<VolatileKey> = new Set<VolatileKey>();
882
+
883
+ /**
884
+ * `storefront:<method>:<stable JSON of args>` — the key the framework caches a result's first load
885
+ * under, and therefore the key its value travels to the browser in. Object keys are sorted so a
886
+ * grid's `{page, pageSize, sort}` does not mint a second key (and a second prerendered copy of the
887
+ * same read) because two call sites happened to spell it in a different order.
888
+ */
889
+ function resultKey(method: string, args: readonly unknown[]): string {
890
+ return `storefront:${method}:${stableJson(args)}`;
891
+ }
892
+
893
+ function stableJson(value: unknown): string {
894
+ return JSON.stringify(value, (_key, raw: unknown) => {
895
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return raw;
896
+ const record = raw as Record<string, unknown>;
897
+ const sorted: Record<string, unknown> = {};
898
+ for (const key of Object.keys(record).sort()) sorted[key] = record[key];
899
+ return sorted;
900
+ });
901
+ }
902
+
903
+ function createGatewayResult<T>(
904
+ sources: Ref<unknown>[],
905
+ resolve: (signal: AbortSignal) => Promise<T | null>,
906
+ options: GatewayResultOptions
907
+ ): StorefrontResult<T> {
908
+ const data = ref<T | null>(null) as Ref<T | null>;
909
+ const pending = ref(true);
910
+ const loading = ref(false);
911
+ const error = ref<string | null>(null);
912
+ // Written by the page's refresh (`refresh.ts`) through the entry registered below, and cleared
913
+ // by every load: a reload supersedes a refresh of the values it is replacing.
914
+ const revalidating = ref<ReadonlySet<VolatileKey>>(NOTHING_REVALIDATING);
915
+ /**
916
+ * Bumped by every load, and the one thing that decides which answer is allowed to write.
917
+ * A watcher-scoped `AbortController` cannot do it alone: `refresh()` is a public method a block
918
+ * calls from an event handler, outside any watcher, so nothing ever aborts its controller — a
919
+ * slow manual refresh and a fast reload for changed sources would both write, last one wins,
920
+ * and "last" is whichever request the network happened to answer second. The refresh
921
+ * (`VolatileRefreshEntry.token`) drops its stale answers on the same counter.
922
+ */
923
+ let generation = 0;
924
+ let prerenderable = true;
925
+ /**
926
+ * The first load ran under the framework's prerender, so what this result shows comes from the
927
+ * build and the volatile refresh below is what makes it current again. False for a result
928
+ * created *after* hydration — a client navigation's, a search as the shopper types — which has
929
+ * just read the live values itself and must not cost a batched request for values it already
930
+ * has. Assigned before the first `await` in `load()`, so it is settled by the time the
931
+ * registration below reads it.
932
+ */
933
+ let ranUnderPrerender = false;
934
+
935
+ /** Only the newest load may write; an older one has already been superseded. */
936
+ const isCurrent = (mine: number): boolean => generation === mine;
937
+
938
+ async function load(): Promise<void> {
939
+ generation += 1;
940
+ const mine = generation;
941
+ loading.value = true;
942
+ revalidating.value = NOTHING_REVALIDATING;
943
+ // `pending` is the skeleton state and nothing else: a read in flight with nothing to show yet.
944
+ // A page that already shows a prerendered product must not flash a skeleton over it
945
+ // (`types.ts`'s prerender contract), and neither must a manual `refresh()` — and once a read
946
+ // has answered, `pending` is false even when the answer was "nothing", or a product that does
947
+ // not exist would leave the block loading for the life of the page.
948
+ pending.value = data.value === null;
949
+ error.value = null;
950
+
951
+ const first = prerenderable;
952
+ prerenderable = false;
953
+ const handle =
954
+ first && options.runtime?.prerender !== undefined
955
+ ? options.runtime.prerender<T>(
956
+ resultKey(options.method, [
957
+ ...sources.map((source) => source.value),
958
+ ...(options.keyArgs ?? []),
959
+ ...(options.locale?.() === undefined ? [] : [options.locale()]),
960
+ ]),
961
+ // The framework owns this read — it is keyed, deduplicated and awaited by the render
962
+ // itself — so it is deliberately given a controller nothing aborts. A watcher-scoped
963
+ // one cannot work here: Vue runs an `immediate` watcher once during SSR and then stops
964
+ // it on the spot (`doWatch`, `watchHandle()` under `isInSSRComponentSetup`), which
965
+ // fires every `onWatcherCleanup` before the load has answered. That abort is exactly
966
+ // how a prerendered page used to end up with the skeleton in its HTML. A newer load
967
+ // supersedes this one through `generation` below instead.
968
+ () => resolve(new AbortController().signal)
969
+ )
970
+ : null;
971
+
972
+ if (handle !== null) {
973
+ ranUnderPrerender = true;
974
+ // Hydration: the payload's answer, in this same synchronous turn, so the block's first render
975
+ // is the server's render — including an answer of `null`, which leaves this result settled
976
+ // and empty exactly as the server left it (nothing pending, nothing in flight) rather than
977
+ // loading over a page that already says the product is gone.
978
+ if (handle.answered !== null) {
979
+ data.value = handle.answered.data;
980
+ pending.value = false;
981
+ loading.value = false;
982
+ }
983
+ const outcome = await handle.settled;
984
+ if (!isCurrent(mine)) return;
985
+ if (outcome.error === null) data.value = outcome.data;
986
+ else if (data.value === null) error.value = outcome.error;
987
+ pending.value = false;
988
+ loading.value = false;
989
+ return;
990
+ }
991
+
992
+ const controller = new AbortController();
993
+ onWatcherCleanup(() => controller.abort(), true);
994
+ try {
995
+ const result = await resolve(controller.signal);
996
+ if (controller.signal.aborted || !isCurrent(mine)) return;
997
+ data.value = result;
998
+ } catch (caught) {
999
+ if (controller.signal.aborted || !isCurrent(mine)) return;
1000
+ error.value = errorMessage(caught);
1001
+ } finally {
1002
+ if (!controller.signal.aborted && isCurrent(mine)) {
1003
+ pending.value = false;
1004
+ loading.value = false;
1005
+ }
1006
+ }
1007
+ }
1008
+
1009
+ watch(sources, load, { immediate: true, deep: true });
1010
+
1011
+ const volatile = options.volatile;
1012
+ // Only a result whose first load went through the prerender takes part in the volatile refresh.
1013
+ // That is not an optimisation: the refresher batches by *burst* rather than once per page (see
1014
+ // `refresh.ts`), so without this a result created long after hydration would open a batch of its
1015
+ // own to re-read values it has just read live.
1016
+ if (volatile !== undefined && ranUnderPrerender && options.runtime?.register !== undefined) {
1017
+ const entry: VolatileRefreshEntry = {
1018
+ read: () => data.value,
1019
+ write: (next) => {
1020
+ data.value = next as T | null;
1021
+ },
1022
+ setRevalidating: (keys) => {
1023
+ revalidating.value = keys;
1024
+ },
1025
+ token: () => generation,
1026
+ };
1027
+ if (volatile !== 'batch') entry.own = volatile;
1028
+ options.runtime.register(entry);
1029
+ }
1030
+
1031
+ return { data, pending, loading, error, revalidating, refresh: load };
1032
+ }
1033
+
1034
+ // ---------------------------------------------------------------------------------------------
1035
+ // Cart — createCartSession() for the remembered cart id, client.cart.* for persistence
1036
+ // ---------------------------------------------------------------------------------------------
1037
+
1038
+ /**
1039
+ * Where the cart is handed off is the platform's answer, not the theme's: `client.checkout.url`
1040
+ * reads it from the platform's own public config (once per client, cached there) and builds
1041
+ * `{checkoutUrl}/checkout/{orgId}/{cartId}`. So it is asynchronous, and it can refuse — a platform
1042
+ * that published no checkout URL, a read that did not come back — and neither may touch the cart:
1043
+ * the URL lands in `checkoutUrl` when it resolves, which is when Check out appears, and a refusal
1044
+ * leaves the ref `null`, the cart's own "nowhere to hand this off to" state that
1045
+ * `blocks/cart/parts/Summary.vue` and the drawer's foot already key off. An add that succeeded is
1046
+ * never reported as failed because the checkout URL did not resolve, and neither is a cart
1047
+ * restored from a remembered id.
1048
+ *
1049
+ * None of it runs on the server or under a prerender, and nothing needs guarding for that: the
1050
+ * cart id is browser state (`createCartSession` reads `localStorage`, which the server has none
1051
+ * of), so there is no cart to resolve a URL for until the page is in a browser.
1052
+ */
1053
+ function createGatewayCartOps(client: EldraClient): CartOps {
1054
+ const session = createCartSession();
1055
+ let cartId = session.read();
1056
+ const checkoutUrl = ref<string | null>(null);
1057
+ // The cart id this has asked about, resolved or still in flight. Every add calls `remember()`, and
1058
+ // the hand-off does not change while the cart id does not, so one ask per cart is enough — and two
1059
+ // adds landing before the first answer must not fire two. A refusal clears it, so the next add
1060
+ // asks again (the SDK does not cache a failed config read either).
1061
+ let askedFor: string | null = null;
1062
+
1063
+ function resolveCheckoutUrl(id: string): void {
1064
+ if (id === askedFor) return;
1065
+ askedFor = id;
1066
+ try {
1067
+ void client.checkout
1068
+ .url({ cartId: id })
1069
+ .then((url) => {
1070
+ // Not the cart we are on any more (a different id, or none): leave it alone.
1071
+ if (id === cartId) checkoutUrl.value = url;
1072
+ })
1073
+ .catch(() => {
1074
+ if (askedFor === id) askedFor = null;
1075
+ if (id === cartId) checkoutUrl.value = null;
1076
+ });
1077
+ } catch {
1078
+ // A `checkout.url` that throws *synchronously* — not the SDK's, which is `async`, but a
1079
+ // hand-written stand-in or a customer's own client — must not escape into the add that
1080
+ // triggered this.
1081
+ askedFor = null;
1082
+ }
1083
+ }
1084
+
1085
+ if (cartId) resolveCheckoutUrl(cartId);
1086
+
1087
+ function remember(id: string): void {
1088
+ // A different cart than the one the current URL points at; it is not this cart's hand-off.
1089
+ if (id !== cartId) checkoutUrl.value = null;
1090
+ cartId = id;
1091
+ session.remember(id);
1092
+ resolveCheckoutUrl(id);
1093
+ }
1094
+
1095
+ return {
1096
+ async init() {
1097
+ if (!cartId)
1098
+ return {
1099
+ lines: [],
1100
+ totals: { subtotal: 0, discount: null, shipping: null, tax: null, total: 0 },
1101
+ };
1102
+ try {
1103
+ const raw = (await client.cart.get(cartId)) as unknown as RawCart;
1104
+ return mapCart(raw);
1105
+ } catch {
1106
+ // A remembered cart id the gateway no longer recognises (expired, cleared server-side).
1107
+ session.forget();
1108
+ cartId = null;
1109
+ askedFor = null;
1110
+ checkoutUrl.value = null;
1111
+ return {
1112
+ lines: [],
1113
+ totals: { subtotal: 0, discount: null, shipping: null, tax: null, total: 0 },
1114
+ };
1115
+ }
1116
+ },
1117
+ // `productId` and `variantId` are two different ids and the gateway needs both: its cart
1118
+ // service reads the pair together (one lookup of "this variant, of this product") and answers
1119
+ // 500 for a pair that does not exist. Sending the variant id as both — which is what this did
1120
+ // while a list row's `variantId` was really a product id — made every add fail that way.
1121
+ async add({ productId, variantId, quantity }) {
1122
+ const raw = (await client.cart.addItem({
1123
+ cartId: cartId ?? undefined,
1124
+ productId,
1125
+ variantId,
1126
+ quantity,
1127
+ })) as unknown as RawCart;
1128
+ remember(raw.id);
1129
+ return mapCart(raw);
1130
+ },
1131
+ async setQuantity(lineId, quantity) {
1132
+ if (!cartId) throw new Error('No cart to update yet.');
1133
+ const raw = (await client.cart.updateItem(cartId, lineId, {
1134
+ quantity,
1135
+ })) as unknown as RawCart;
1136
+ return mapCart(raw);
1137
+ },
1138
+ async remove(lineId) {
1139
+ if (!cartId) throw new Error('No cart to update yet.');
1140
+ const raw = (await client.cart.removeItem(cartId, lineId)) as unknown as RawCart;
1141
+ return mapCart(raw);
1142
+ },
1143
+ async applyDiscount(code) {
1144
+ if (!cartId) return { ack: { ok: false, reason: 'invalid' } };
1145
+ try {
1146
+ const result = await client.cart.applyDiscount(cartId, code);
1147
+ const applied = (result as unknown as { applied: boolean }).applied;
1148
+ const raw = (result as unknown as { cart: RawCart }).cart;
1149
+ if (!applied) return { ack: { ok: false, reason: 'invalid' } };
1150
+ return { ack: { ok: true }, snapshot: mapCart(raw) };
1151
+ } catch {
1152
+ return { ack: { ok: false, reason: 'failed' } };
1153
+ }
1154
+ },
1155
+ async removeDiscount() {
1156
+ if (!cartId)
1157
+ return {
1158
+ lines: [],
1159
+ totals: { subtotal: 0, discount: null, shipping: null, tax: null, total: 0 },
1160
+ };
1161
+ const raw = (await client.cart.removeDiscount(cartId)) as unknown as RawCart;
1162
+ return mapCart(raw);
1163
+ },
1164
+ checkoutUrl,
1165
+ };
1166
+ }
1167
+
1168
+ // ---------------------------------------------------------------------------------------------
1169
+ // Forms / back-in-stock — no gateway endpoint today; post to the plugin-configured endpoint.
1170
+ // ---------------------------------------------------------------------------------------------
1171
+
1172
+ async function postToEndpoint(
1173
+ endpoint: string | undefined,
1174
+ body: Record<string, unknown>
1175
+ ): Promise<StorefrontAck> {
1176
+ if (!endpoint) return { ok: false, reason: 'unsupported' };
1177
+ try {
1178
+ const response = await fetch(endpoint, {
1179
+ method: 'POST',
1180
+ headers: { 'Content-Type': 'application/json' },
1181
+ body: JSON.stringify(body),
1182
+ });
1183
+ return response.ok ? { ok: true } : { ok: false, reason: 'failed' };
1184
+ } catch {
1185
+ return { ok: false, reason: 'failed' };
1186
+ }
1187
+ }
1188
+
1189
+ // ---------------------------------------------------------------------------------------------
1190
+ // Gateway filter and sort tokens
1191
+ // ---------------------------------------------------------------------------------------------
1192
+
1193
+ /**
1194
+ * The gateway's list endpoints take repeatable `[groupIndex:]field:op:value`
1195
+ * filter tokens: that shape, and the fact that `filter` is repeatable while
1196
+ * `sort`/`fields` are comma-separated, is what
1197
+ * `packages/sdk/src/__tests__/fixtures/web-gateway.json` documents for the
1198
+ * `filter` parameter of `GET /catalog/v1/products/list` and
1199
+ * `/catalog/v1/collections`. Tokens sharing a `groupIndex` are OR'd; every
1200
+ * other token is AND'd. A token the gateway does not accept is a 400, not an
1201
+ * empty list.
1202
+ *
1203
+ * The fixture does **not** document which fields or operators are accepted.
1204
+ * The set below (`id`, `slug`, `status`, `createdAt` on a storefront product
1205
+ * list, and the `in` operator) is what the gateway accepted when this was
1206
+ * written, verified against the deployed service rather than the contract — so
1207
+ * every token this file builds is written here, once, where a 400 can be traced
1208
+ * to it, rather than at the call sites that used to hand-roll them.
1209
+ */
1210
+ const STATUS_ACTIVE = 'status:eq:ACTIVE';
1211
+
1212
+ /**
1213
+ * `field:in:a,b,c` — the one token that asks for several values of the same
1214
+ * field. The alternative (one `eq` per value) would need the OR-group prefix,
1215
+ * since bare tokens are AND'd and `slug:eq:a` AND `slug:eq:b` matches nothing.
1216
+ *
1217
+ * A value containing a comma or a colon cannot survive the token grammar, so it
1218
+ * is dropped rather than sent as something the gateway would read as a
1219
+ * different filter. Product and collection handles are slugs; nothing legal is
1220
+ * lost.
1221
+ */
1222
+ function inFilter(field: string, values: readonly string[]): string[] {
1223
+ const usable = values.filter(
1224
+ (value) => value !== '' && !value.includes(',') && !value.includes(':')
1225
+ );
1226
+ return usable.length === 0 ? [] : [`${field}:in:${usable.join(',')}`];
1227
+ }
1228
+
1229
+ /**
1230
+ * The block's own sort ids mapped to the gateway's sort fields, which are the
1231
+ * only ones `GET /catalog/v1/collections/{slug}/products` accepts (an unknown
1232
+ * one is a 400, exactly like an unknown filter field). `featured` and
1233
+ * `best-selling` map to nothing: `featured` *is* the collection's own sort
1234
+ * mode, which is what the endpoint already orders by, and the storefront
1235
+ * contract exposes no sales figures to sort by.
1236
+ */
1237
+ const GATEWAY_SORT: Readonly<Record<string, string>> = {
1238
+ newest: '-createdAt',
1239
+ 'price-asc': 'minPrice',
1240
+ 'price-desc': '-minPrice',
1241
+ };
1242
+
1243
+ /**
1244
+ * **The one sort id this gateway can never honour, on either list it reads** (`StorefrontCollectionProducts.unsortable`).
1245
+ * `best-selling` is absent from `GATEWAY_SORT` above for the same reason it is declared here: the
1246
+ * platform gateway's product list carries no sales figures to order by, on the collection-scoped
1247
+ * read and the catalogue-wide one alike — unlike `collection`
1248
+ * (`COLLECTION_SCOPE_UNFILTERABLE` below), which only one of the two scopes cannot honour. `featured`
1249
+ * maps to nothing in `GATEWAY_SORT` too, but it is not unsortable: it *is* the collection's own
1250
+ * default order, which the endpoint already answers in.
1251
+ */
1252
+ const GATEWAY_UNSORTABLE: readonly string[] = ['best-selling'];
1253
+
1254
+ // ---------------------------------------------------------------------------------------------
1255
+ // The shopper's facets as the catalog list's own query parameters
1256
+ // ---------------------------------------------------------------------------------------------
1257
+
1258
+ /**
1259
+ * **The shopper's filters, as `GET /catalog/v1/collections/{slug}/products` takes them** (contract
1260
+ * 3.7.0; the same parameters are on `GET /catalog/v1/products/list`, plus a `collectionId` the
1261
+ * collection-scoped read has no use for). One request, filtered and counted by the platform, for
1262
+ * the whole collection rather than the page this read happened to fetch.
1263
+ *
1264
+ * Three conversions are the whole of it, and each is a bug if it is skipped:
1265
+ *
1266
+ * - **`price` is major units in the URL and minor units in the parameters.** The block's
1267
+ * `"<min>-<max>"` is whole units of the store currency, which is what a shopper typed and what
1268
+ * the chips read back; `minPrice`/`maxPrice` are minor, like the `facets.price` span they are
1269
+ * counted over. So they go through `toMinorUnits` with the store's own fraction digits — ISK has
1270
+ * none, USD two — rather than a hard-coded ×100.
1271
+ * - **`category` is a slug in the URL and a uuid in the request.** The block's values are the facet
1272
+ * terms' slugs (a filtered view has to stay linkable and readable), while `categoryId` takes
1273
+ * catalog ids, so the slugs are resolved through the store's own category list — see
1274
+ * `readCategories`.
1275
+ * - **`availability` is one value, not a set.** Both boxes ticked is every product, which is no
1276
+ * filter at all, so nothing is sent; one box is sent as the platform's own
1277
+ * `in_stock`/`out_of_stock` spelling, which `canonicalAvailabilityValues` also folds the retired
1278
+ * hyphenated one into.
1279
+ *
1280
+ * `option` is the one parameter whose grammar is its own: `option=<key>:<value>`, repeated, OR'd
1281
+ * within a key and AND'd across keys — which is exactly the panel's own semantics, so the
1282
+ * `option:<key>` filter source maps straight onto it.
1283
+ *
1284
+ * A clause this mapping cannot express is left out rather than guessed at (an unknown category
1285
+ * slug, a price bound that is not a number, a `collection` clause on a read that has no
1286
+ * `collectionId` parameter — see `collectionProducts`), which is the storefront's standing
1287
+ * "unknown, not unmatched" rule: a filter nothing can honour must not empty a shopper's grid.
1288
+ */
1289
+ interface CatalogFilterQuery {
1290
+ minPrice?: number;
1291
+ maxPrice?: number;
1292
+ categoryId?: string[];
1293
+ collectionId?: string[];
1294
+ availability?: string;
1295
+ option?: string[];
1296
+ }
1297
+
1298
+ /**
1299
+ * **What a collection's own product list cannot filter by** (`StorefrontCollectionProducts`).
1300
+ *
1301
+ * `collection`, and only that: there is no `collectionId` parameter on
1302
+ * `GET /catalog/v1/collections/{slug}/products`. The scope already *is* one collection, and the
1303
+ * parameter the product list has is an OR over a list of ids — so a second id would widen the scope
1304
+ * rather than intersect it, and there is no token for the intersection either. The `collections`
1305
+ * facet is still answered on that route and still honest: it says which other collections these
1306
+ * products are also in, which is worth reading and is not a filter.
1307
+ *
1308
+ * It is declared rather than silently dropped because the panel has to know: a group whose filter
1309
+ * changes the chips, the URL and nothing else is the defect this whole path exists to remove. A read
1310
+ * scoped to the **whole catalogue** (`GET /catalog/v1/products/list`, which does take `collectionId`)
1311
+ * would declare nothing here; this theme has no faceted grid over it yet.
1312
+ */
1313
+ const COLLECTION_SCOPE_UNFILTERABLE: readonly string[] = ['collection'];
1314
+
1315
+ /**
1316
+ * **A category page's `categoryId` parameter**: the ids the read should be scoped to, or `null` when
1317
+ * the path names no category this store has (which the caller answers as "no such page" rather than
1318
+ * as the unscoped catalogue).
1319
+ *
1320
+ * The platform's `categoryId` matches a whole **subtree**, so the page's own id is the scope and a
1321
+ * shopper ticking a child narrows within it. The parameter is an OR over a list, though, so the
1322
+ * shopper's clause cannot simply be sent beside the scope: it is **intersected** with the subtree,
1323
+ * and a value outside it is dropped rather than allowed to widen the page past its own category. An
1324
+ * intersection that comes out empty falls back to the scope's own id — the page unfiltered, which is
1325
+ * the honest answer when nothing the shopper asked for is in it.
1326
+ */
1327
+ function scopeCategoryIds(
1328
+ index: CategoryIndex,
1329
+ categoryPath: string,
1330
+ filterQuery: CatalogFilterQuery
1331
+ ): string[] | null {
1332
+ const scopeId = index.idByPath.get(categoryPath);
1333
+ if (scopeId === undefined) return null;
1334
+ const inside = (filterQuery.categoryId ?? []).filter((id) => isInSubtree(index, id, scopeId));
1335
+ return inside.length > 0 ? inside : [scopeId];
1336
+ }
1337
+
1338
+ /** `"<min>-<max>"` in whole major units → one bound in minor units, or nothing to send. */
1339
+ function priceParam(raw: string | undefined, currency: string | undefined): number | undefined {
1340
+ if (raw === undefined || raw === '') return undefined;
1341
+ const amount = Number(raw);
1342
+ if (!Number.isFinite(amount) || amount < 0) return undefined;
1343
+ return toMinorUnits(amount, currency);
1344
+ }
1345
+
1346
+ /**
1347
+ * The store's whole category tree — ids, slugs, titles and `parentId` — indexed both ways
1348
+ * (`app/storefront/categories.ts`).
1349
+ *
1350
+ * `GET /catalog/v1/categories` answers the whole list — a storefront's categories are a handful of
1351
+ * rows, and the read takes no filter — so one request answers for every slug a shopper can tick and
1352
+ * every ancestor a trail can name, now or later. Read once per storefront (see
1353
+ * `createGatewayStorefront`), which means a shopper arriving on a shared `?category=ceramics` link
1354
+ * pays for it once and nobody else pays at all.
1355
+ *
1356
+ * Three readers, and they want different halves of it: the `category` filter resolves slugs to the
1357
+ * `categoryId` the list takes (`idBySlug`), `catalog.product` walks a product's `primaryCategoryId`
1358
+ * up to its root for the breadcrumb trail, and the collection grid's category facet borrows the tree
1359
+ * to place and name the parent rows the platform's own counts never mention.
1360
+ *
1361
+ * **It carries no abort signal**, deliberately, because its answer belongs to every read rather than
1362
+ * to the one that happened to ask first: a shopper ticking a second category while the first read is
1363
+ * still resolving aborts that read, and a lookup tied to its signal would reject in the hands of the
1364
+ * read that replaced it — an error over a page whose filter was perfectly answerable. It is one
1365
+ * small request that finishes on its own.
1366
+ *
1367
+ * A failure is swallowed by its two *decorative* readers and by neither of the other two. A trail
1368
+ * nobody can read is a product page without a category crumb, and a facet tree nobody can read is a
1369
+ * flat category group — both are pages. A **filter** that quietly dropped the category the chips, the
1370
+ * URL and the active-filter row all say is applied is a lie, so that one fails the collection read,
1371
+ * which the block already draws as an error over the last good page.
1372
+ */
1373
+ async function readCategories(client: EldraClient): Promise<CategoryIndex> {
1374
+ const rows = (await client.catalog.listCategories({})) as unknown as RawCategory[] | null;
1375
+ return buildCategoryIndex(rows);
1376
+ }
1377
+
1378
+ /**
1379
+ * The catalog ids of some collection slugs, asked for by slug in one `slug:in:a,b` token.
1380
+ *
1381
+ * Unlike the categories, this is **not** read whole: a store's collections are a merchandising list
1382
+ * that grows without bound, while its categories are a handful of rows, and only the slugs a shopper
1383
+ * actually ticked are needed. A slug nothing matches is simply absent from the answer, which the
1384
+ * caller then leaves out of the request — the standing "unknown, not unmatched" rule.
1385
+ */
1386
+ async function readCollectionIds(
1387
+ client: EldraClient,
1388
+ slugs: readonly string[]
1389
+ ): Promise<ReadonlyMap<string, string>> {
1390
+ const filter = inFilter('slug', [...slugs]);
1391
+ const out = new Map<string, string>();
1392
+ if (filter.length === 0) return out;
1393
+ const raw = (await client.catalog.listCollections({
1394
+ pageSize: slugs.length,
1395
+ filter,
1396
+ })) as unknown as { data?: RawCollectionItem[] | null };
1397
+ for (const row of raw.data ?? []) {
1398
+ if (typeof row.slug === 'string' && row.slug !== '' && typeof row.id === 'string') {
1399
+ out.set(row.slug, row.id);
1400
+ }
1401
+ }
1402
+ return out;
1403
+ }
1404
+
1405
+ /**
1406
+ * `filters` as the catalog list takes it. `categoriesOnce` is only awaited when there is a
1407
+ * category clause to resolve, so an unfiltered read — and every filtered read that touches no
1408
+ * category — makes exactly the one request it always made.
1409
+ */
1410
+ async function catalogFilterQuery(
1411
+ filters: Record<string, string[]> | undefined,
1412
+ currency: string | undefined,
1413
+ categoriesOnce: () => Promise<CategoryIndex>,
1414
+ /**
1415
+ * Collection slugs → catalog ids, for a scope whose read **takes** a `collectionId`: the
1416
+ * catalogue-wide product list does, a collection's own product list does not (see
1417
+ * `COLLECTION_SCOPE_UNFILTERABLE`). Omitted, a `collection` clause is left out of the request
1418
+ * exactly as it always was.
1419
+ */
1420
+ collectionIdsFor?: (slugs: readonly string[]) => Promise<ReadonlyMap<string, string>>
1421
+ ): Promise<CatalogFilterQuery> {
1422
+ const query: CatalogFilterQuery = {};
1423
+ if (filters === undefined) return query;
1424
+ const option: string[] = [];
1425
+ for (const [source, selected] of Object.entries(filters)) {
1426
+ if (selected.length === 0) continue;
1427
+ if (source === 'price') {
1428
+ const [min = '', max = ''] = (selected[0] ?? '').split('-');
1429
+ const minPrice = priceParam(min, currency);
1430
+ const maxPrice = priceParam(max, currency);
1431
+ if (minPrice !== undefined) query.minPrice = minPrice;
1432
+ if (maxPrice !== undefined) query.maxPrice = maxPrice;
1433
+ continue;
1434
+ }
1435
+ if (source === 'availability') {
1436
+ const known = canonicalAvailabilityValues(selected);
1437
+ // Both values is every product: no parameter, so the request is identical to an unfiltered
1438
+ // one — and the platform never spends the cross-service stock read on a filter that excludes
1439
+ // nothing.
1440
+ if (known.length === 1) query.availability = known[0];
1441
+ continue;
1442
+ }
1443
+ if (source === 'category') {
1444
+ const { idBySlug } = await categoriesOnce();
1445
+ const matched = selected
1446
+ .map((slug) => idBySlug.get(slug))
1447
+ .filter((id): id is string => id !== undefined);
1448
+ if (matched.length > 0) query.categoryId = matched;
1449
+ continue;
1450
+ }
1451
+ if (source.startsWith(OPTION_SOURCE_PREFIX)) {
1452
+ const key = source.slice(OPTION_SOURCE_PREFIX.length);
1453
+ if (key === '') continue;
1454
+ for (const value of selected) {
1455
+ if (value !== '') option.push(`${key}:${value}`);
1456
+ }
1457
+ continue;
1458
+ }
1459
+ if (source === 'collection') {
1460
+ // Only where the scope's own read takes the parameter. A collection cannot narrow a
1461
+ // collection's own products (see `collectionProducts`), and that scope passes no resolver, so
1462
+ // the clause is dropped there rather than sent as something that would widen the scope.
1463
+ if (collectionIdsFor === undefined) continue;
1464
+ const ids = await collectionIdsFor(selected);
1465
+ const matched = selected
1466
+ .map((slug) => ids.get(slug))
1467
+ .filter((id): id is string => id !== undefined);
1468
+ if (matched.length > 0) query.collectionId = matched;
1469
+ continue;
1470
+ }
1471
+ // A source some other theme invented lands here.
1472
+ }
1473
+ if (option.length > 0) query.option = option;
1474
+ return query;
1475
+ }
1476
+
1477
+ /**
1478
+ * The response's `facets` object as the view type the filter panel reads (`CatalogFacets`), or
1479
+ * `undefined` for a gateway that answered none — which the panel draws as the groups it can fill
1480
+ * without values, never as a scope with nothing in it.
1481
+ *
1482
+ * Only two things happen here. `price` is converted from the platform's minor units to the major
1483
+ * units every money field in `types.ts` carries (`fromMinorUnits`), and the two objects the platform
1484
+ * may **omit** are carried over only when it sent them, because in both cases an absence is a
1485
+ * different answer from a zero:
1486
+ *
1487
+ * - no `availability` means stock could not be read at all, not that nothing is in stock, and the
1488
+ * panel hides that group rather than offering a filter whose counts are unknown;
1489
+ * - no `price` means the scope minus the price filter held nothing to span, not that everything in it
1490
+ * is free. A 0–0 span is a dead track labelled in the store's currency, and writing one would also
1491
+ * suppress the panel's own fallback — the widest span it has seen for this collection — which is
1492
+ * written for exactly this case.
1493
+ */
1494
+ function mapFacets(
1495
+ raw: RawProductFacets | null | undefined,
1496
+ currency: string | undefined
1497
+ ): CatalogFacets | undefined {
1498
+ if (raw === null || raw === undefined) return undefined;
1499
+ const price = raw.price;
1500
+ const availability = raw.availability;
1501
+ // **The one signal that says whose tree and whose counts these are.** Contract 3.8.0 adds
1502
+ // `parentId` on a category term and the ancestor roll-ups together, so a term that can place itself
1503
+ // is a term that has already been counted up — and the panel must not sum on top of that, since the
1504
+ // platform's number is deduplicated and a sum over siblings is not (a product in Cups and in Bowls
1505
+ // is one product and two counts).
1506
+ //
1507
+ // 3.8.0 omits `parentId` for a **root**, so a scope whose categories are all roots carries none and
1508
+ // reads here as unplaced — which costs the category read below and changes nothing else: a family
1509
+ // with no parent/child pair has nothing to place and nothing to roll up either way. Every tree with
1510
+ // an actual child carries that child's `parentId`, and a reported child's parent is always in the
1511
+ // same list, so there is no partial placement to get wrong.
1512
+ const placed = (raw.categories ?? []).some((term) => term.parentId !== undefined);
1513
+ return {
1514
+ ...(price === null || price === undefined
1515
+ ? {}
1516
+ : {
1517
+ price: {
1518
+ min: fromMinorUnits(price.min ?? 0, currency),
1519
+ max: fromMinorUnits(price.max ?? 0, currency),
1520
+ // Counts, not amounts: the buckets are already on the platform's own span, so they
1521
+ // pass through as they are; absent or empty on the wire means no histogram at all.
1522
+ ...(Array.isArray(price.histogram) && price.histogram.length > 0
1523
+ ? { histogram: price.histogram.map((count) => Math.max(0, Math.trunc(count ?? 0))) }
1524
+ : {}),
1525
+ },
1526
+ }),
1527
+ categories: mapFacetTerms(raw.categories, placed),
1528
+ ...(placed ? { categoryCounts: 'rolled-up' as const } : {}),
1529
+ collections: mapFacetTerms(raw.collections),
1530
+ ...(availability === null || availability === undefined
1531
+ ? {}
1532
+ : {
1533
+ availability: {
1534
+ in_stock: availability.in_stock ?? 0,
1535
+ out_of_stock: availability.out_of_stock ?? 0,
1536
+ },
1537
+ }),
1538
+ options: (raw.options ?? [])
1539
+ .filter((option) => typeof option.key === 'string' && option.key !== '')
1540
+ .map((option) => {
1541
+ const kind = storefrontOptionKind(option.kind);
1542
+ return {
1543
+ key: option.key!,
1544
+ name: option.name ?? option.key!,
1545
+ // Carried so a panel reads the same fact the product page does. What a group *draws* is
1546
+ // decided by its values (`parts/groups.ts`'s `facetTypeFor`) — the same evidence
1547
+ // `optionDisplayType` goes by on the product page, so one option cannot be dots here and
1548
+ // pills there: a `color` option the store set no colours for has nothing to put in a dot.
1549
+ kind,
1550
+ ...(kind === 'custom' && option.metadata ? { metadata: option.metadata } : {}),
1551
+ values: (option.values ?? [])
1552
+ .filter((value) => typeof value.value === 'string' && value.value !== '')
1553
+ .map((value) => ({
1554
+ value: value.value!,
1555
+ label: value.label ?? value.value!,
1556
+ // Truthiness, not `!== undefined`: the field is nullable on the wire, and
1557
+ // `CatalogFacetOptionValue.swatch` is `string | undefined`, so an explicit `null`
1558
+ // would otherwise be written into it and reach a dot as `backgroundColor: null`. The
1559
+ // same test the product mapping uses, on the same field.
1560
+ ...(value.swatch ? { swatch: value.swatch } : {}),
1561
+ count: value.count ?? 0,
1562
+ })),
1563
+ };
1564
+ }),
1565
+ ...(() => {
1566
+ const toggles = (raw.toggles ?? [])
1567
+ .filter((toggle) => typeof toggle.key === 'string' && toggle.key !== '')
1568
+ .map((toggle) => ({
1569
+ key: toggle.key!,
1570
+ label: toggle.label ?? toggle.key!,
1571
+ count: toggle.count ?? 0,
1572
+ }));
1573
+ return toggles.length > 0 ? { toggles } : {};
1574
+ })(),
1575
+ };
1576
+ }
1577
+
1578
+ /**
1579
+ * `placed` carries the platform's own `parentId` through (categories only), **normalising 3.8.0's
1580
+ * absent-means-root into the explicit `null`** this theme's view type uses: once any term in the
1581
+ * family is placed, every term in it is, so a root has to say so rather than look unplaced. Outside a
1582
+ * placed family the key is deliberately left off — an absent `parentId` means "this source cannot
1583
+ * place the term", which the panel renders flat (see `CatalogFacetTerm.parentId`).
1584
+ */
1585
+ function mapFacetTerms(
1586
+ raw: RawFacetTerm[] | null | undefined,
1587
+ placed = false
1588
+ ): CatalogFacets['categories'] {
1589
+ return (raw ?? [])
1590
+ .filter((term) => typeof term.slug === 'string' && term.slug !== '')
1591
+ .map((term) => ({
1592
+ id: term.id ?? term.slug!,
1593
+ slug: term.slug!,
1594
+ title: term.title ?? term.slug!,
1595
+ count: term.count ?? 0,
1596
+ ...(placed ? { parentId: term.parentId ?? null } : {}),
1597
+ }));
1598
+ }
1599
+
1600
+ // ---------------------------------------------------------------------------------------------
1601
+ // Collection selectors — a slug goes straight to the gateway, an id needs a lookup first
1602
+ // ---------------------------------------------------------------------------------------------
1603
+
1604
+ /**
1605
+ * The slug to ask `/catalog/v1/collections/{slug}/products` for, or `null` when
1606
+ * there is nothing to ask about.
1607
+ *
1608
+ * `{ slug }` needs no lookup. `{ id }` — what a CMS `reference` field stores,
1609
+ * and all a depth-0 read or a page builder draft overlay carries — is resolved
1610
+ * through the collection list's `filter` query (`field:op:value` tokens), because
1611
+ * the gateway has no by-id collection route. A gateway that does not honour the
1612
+ * token answers with some other collection or with nothing; either way an
1613
+ * unmatched id resolves to `null`, so the block shows its empty state and, in
1614
+ * the editor, its "publish to load products" hint — never an error.
1615
+ */
1616
+ async function resolveCollectionSlug(
1617
+ client: EldraClient,
1618
+ selector: StorefrontCollectionSelector | null,
1619
+ signal: AbortSignal
1620
+ ): Promise<string | null> {
1621
+ if (selector === null) return null;
1622
+ if ('slug' in selector) return selector.slug || null;
1623
+ const raw = (await client.catalog.listCollections(
1624
+ { limit: 1, filter: [`id:eq:${selector.id}`] },
1625
+ { signal }
1626
+ )) as unknown as { data?: RawCollectionItem[] | null };
1627
+ const match = (raw.data ?? []).find((item) => item.id === selector.id);
1628
+ return match?.slug ?? null;
1629
+ }
1630
+
1631
+ /**
1632
+ * "More like this", built from what the storefront contract actually offers.
1633
+ *
1634
+ * There is no relatedness endpoint and no `relatedTo` filter field — the token
1635
+ * this used to send was refused outright — so the nearest honest answer is the
1636
+ * product's own category: read the product, then ask the product list for that
1637
+ * category through the documented `categoryId` query parameter (`GET
1638
+ * /catalog/v1/products/list`), with the product itself dropped from the result.
1639
+ * A product with no category, or a category with nothing else in it, falls back
1640
+ * to the newest active products, which is what the carousel showed before any
1641
+ * of this was filtered at all. One extra row is requested so removing the
1642
+ * current product still leaves a full carousel.
1643
+ */
1644
+ async function relatedProducts(
1645
+ client: EldraClient,
1646
+ handle: string | null,
1647
+ limit: number,
1648
+ signal: AbortSignal
1649
+ ): Promise<StorefrontProductListItem[]> {
1650
+ if (!handle) return [];
1651
+ const current = (await client.catalog.getProduct(
1652
+ handle,
1653
+ {},
1654
+ { signal }
1655
+ )) as unknown as RawProductDetails;
1656
+ const categoryId = typeof current.categoryId === 'string' ? current.categoryId : undefined;
1657
+ const list = async (query: Record<string, unknown>): Promise<StorefrontProductListItem[]> => {
1658
+ const raw = (await client.catalog.listProducts(
1659
+ { pageSize: limit + 1, sort: ['-createdAt'], filter: [STATUS_ACTIVE], ...query },
1660
+ { signal }
1661
+ )) as unknown as RawProductList;
1662
+ return (raw.data ?? [])
1663
+ .filter((item) => item.slug !== handle)
1664
+ .slice(0, limit)
1665
+ .map(mapProductListItem);
1666
+ };
1667
+ const sameCategory = categoryId === undefined ? [] : await list({ categoryId });
1668
+ return sameCategory.length > 0 ? sameCategory : await list({});
1669
+ }
1670
+
1671
+ /**
1672
+ * The batched volatile read behind `catalog.volatileByIds`: the live price, compare-at price,
1673
+ * availability and stock line for the products a page is already showing.
1674
+ *
1675
+ * One products-list request per chunk of ids (`chunkIds`, 50 at a time), each asking for exactly
1676
+ * that chunk through a single repeatable `id:in:a,b,c` token — the same `filter` grammar and the
1677
+ * same `id` field every other read in this file uses. The rows come back through
1678
+ * `mapProductListItem`, so a refreshed price is derived exactly the way the card's prerendered one
1679
+ * was (`minPrice`/`compareAtPrice`/`status`) and the two can never disagree about what a price is.
1680
+ *
1681
+ * **No `status:eq:ACTIVE`.** Every other list read here filters the catalogue down to what a
1682
+ * shopper may buy; this one must not. Availability is one of the values being refreshed, so a
1683
+ * product that has just gone inactive has to come back *saying so* — filtered out, it would be
1684
+ * indistinguishable from a product the refresh could not see, and the page would keep showing it
1685
+ * in stock until the next rebuild.
1686
+ *
1687
+ * A chunk whose ids cannot survive the token grammar makes no request at all: asking without the
1688
+ * token would read the whole catalogue and answer with somebody else's products.
1689
+ */
1690
+ async function volatileSnapshots(
1691
+ client: EldraClient,
1692
+ ids: readonly string[],
1693
+ signal?: AbortSignal
1694
+ ): Promise<VolatileSnapshot[]> {
1695
+ const rows = await productRowsByIds(client, ids, signal);
1696
+ return rows.map((item) => ({
1697
+ // Deliberately no `inventory`: the products list carries none, and an absent key means
1698
+ // "unknown, keep what the page already shows" rather than "nothing left".
1699
+ id: item.productId,
1700
+ price: item.price,
1701
+ available: item.available,
1702
+ stock: item.stock,
1703
+ }));
1704
+ }
1705
+
1706
+ /**
1707
+ * The catalogue rows for a set of **catalog product ids**, mapped the ordinary way
1708
+ * (`mapProductListItem`). One products-list request per chunk of 50 (`chunkIds`), each asking for
1709
+ * exactly that chunk through a single repeatable `id:in:a,b,c` token.
1710
+ *
1711
+ * Shared by the volatile refresh above (which keeps only the volatile values) and by the search
1712
+ * enrichment below (which also wants the thumbnail), so a price is derived one way whichever read
1713
+ * asked for it. A chunk whose ids cannot survive the token grammar makes no request at all: asking
1714
+ * without the token would read the whole catalogue and answer with somebody else's products.
1715
+ */
1716
+ async function productRowsByIds(
1717
+ client: EldraClient,
1718
+ ids: readonly string[],
1719
+ signal?: AbortSignal
1720
+ ): Promise<StorefrontProductListItem[]> {
1721
+ const requests = chunkIds(ids)
1722
+ .map((chunk) => ({ chunk, filter: inFilter('id', chunk) }))
1723
+ .filter(({ filter }) => filter.length > 0)
1724
+ .map(async ({ chunk, filter }) => {
1725
+ const raw = (await client.catalog.listProducts(
1726
+ { pageSize: chunk.length, filter },
1727
+ // The page's own refresh passes none (`refresh.ts` owns that life cycle); the search read
1728
+ // below passes its own, so a superseded query's request is abandoned with it.
1729
+ signal === undefined ? undefined : { signal }
1730
+ )) as unknown as RawProductList;
1731
+ return raw.data ?? [];
1732
+ });
1733
+ const pages = await Promise.all(requests);
1734
+ return pages.flat().map(mapProductListItem);
1735
+ }
1736
+
1737
+ /**
1738
+ * The products a search found, filled in from the catalogue.
1739
+ *
1740
+ * A search result is a title, a kind and a destination. It carries no money and no image at all, so
1741
+ * `mapSearchResponse` has nothing to map either from — and a product row with no price renders as
1742
+ * no price (`StorefrontSearchProduct`), a product row with no image as a placeholder. So the
1743
+ * catalogue is asked, once, for every product the search found: `productRowsByIds` is the same
1744
+ * batched `id:in:` products-list read the volatile refresh uses, and the price that comes back is
1745
+ * derived exactly the way a card's prerendered one is (`mapProductListItem`'s
1746
+ * `minPrice`/`compareAtPrice`/`status`), so the two can never disagree about what a price is.
1747
+ *
1748
+ * **It is asked by `sourceId`.** A `PRODUCT` result carries two ids: `id` names the search-index row
1749
+ * and `sourceId` names the catalog product. Asking `filter=id:in:<row id>` answers zero rows every
1750
+ * time — which is exactly what shipped, and why every suggestion and every search result card went
1751
+ * out with no price and no thumbnail while the request itself looked perfectly healthy.
1752
+ *
1753
+ * Four fields are taken from the catalogue row and the rest of the search result is kept: the title
1754
+ * is the index's (it is what the query matched, and what the panel highlights) and the destination
1755
+ * is the index's `targetUrl`, already sanitised.
1756
+ *
1757
+ * It is part of the search read rather than a refresh registered after it, because the refresh
1758
+ * cannot reach a search: it only takes results whose first load ran under the prerender
1759
+ * (`createGatewayResult`'s `ranUnderPrerender`), and a search the shopper types runs long after
1760
+ * hydration. One search, two requests, both awaited before the response is published — a row that
1761
+ * appeared priceless and corrected itself a moment later would be a worse answer than a row that
1762
+ * arrived right.
1763
+ *
1764
+ * **Fail-soft, the way every other read here is.** No products in the response, a read that did not
1765
+ * come back, or a found id the catalogue did not answer about, all leave that product at
1766
+ * `price: null` — which the suggestion panel renders without a price and the results page renders no
1767
+ * card for. A zero is never published: suggestions with no price are worth more than suggestions
1768
+ * with the wrong one.
1769
+ *
1770
+ * Only the read itself is inside the `try`, and only a *read* failure is swallowed (`isReadFailure`):
1771
+ * a bug in the mapping or the merge must surface as an error, not as a page where every row quietly
1772
+ * lost its price. An abort needs no handling beyond not throwing — the caller drops the whole answer
1773
+ * when its signal fired.
1774
+ */
1775
+ async function enrichedSearchResponse(
1776
+ client: EldraClient,
1777
+ response: StorefrontSearchResponse,
1778
+ signal: AbortSignal
1779
+ ): Promise<StorefrontSearchResponse> {
1780
+ const ids = collectVolatileTargets(response);
1781
+ if (ids.length === 0) return response;
1782
+ let rows: StorefrontProductListItem[];
1783
+ try {
1784
+ rows = await productRowsByIds(client, ids, signal);
1785
+ } catch (caught) {
1786
+ if (!isReadFailure(caught)) throw caught;
1787
+ if (!isAbort(caught)) {
1788
+ console.warn('[eldra] search results could not be priced:', errorMessage(caught));
1789
+ }
1790
+ return response;
1791
+ }
1792
+ if (rows.length === 0) return response;
1793
+ const byId = new Map(rows.map((row) => [row.productId, row]));
1794
+ return {
1795
+ ...response,
1796
+ products: response.products.map((product) => {
1797
+ const row = byId.get(product.productId);
1798
+ if (row === undefined) return product;
1799
+ return {
1800
+ ...product,
1801
+ price: row.price,
1802
+ featuredImage: row.featuredImage ?? null,
1803
+ available: row.available,
1804
+ stock: row.stock,
1805
+ };
1806
+ }),
1807
+ };
1808
+ }
1809
+
1810
+ /** A superseded query's own request being dropped — `AbortController.abort()` reaches `fetch` as a
1811
+ * `DOMException` named `AbortError` in every runtime this theme runs in. */
1812
+ function isAbort(caught: unknown): boolean {
1813
+ return caught instanceof Error && caught.name === 'AbortError';
1814
+ }
1815
+
1816
+ /**
1817
+ * Whether a rejection from a gateway read is the **read** failing — something a storefront degrades
1818
+ * around — rather than a bug in this file, which must not be swallowed into a silently priceless
1819
+ * page.
1820
+ *
1821
+ * `EldraHttpError` is the gateway refusing or erroring, and an abort is a request this code dropped
1822
+ * on purpose. A `TypeError` is what `fetch` itself rejects with when the call never completed
1823
+ * (offline, DNS, CORS); it is also the shape of an ordinary programming mistake, so it counts as a
1824
+ * read failure *and* is warned about rather than passing unnoticed. Everything else —
1825
+ * `ReferenceError`, `RangeError`, `SyntaxError`, a thrown non-error — is this code being wrong, and
1826
+ * is re-thrown.
1827
+ */
1828
+ function isReadFailure(caught: unknown): boolean {
1829
+ return caught instanceof EldraHttpError || isAbort(caught) || caught instanceof TypeError;
1830
+ }
1831
+
1832
+ /**
1833
+ * The product detail page's own volatile refresh — the one result that cannot go through the
1834
+ * batched read. The batch answers from the products list, which carries no inventory at all, and
1835
+ * the one page in the theme whose stock line is about a *variant* is this one, so it re-reads its
1836
+ * own product: that read is the only one that knows the variant-level `inventory`.
1837
+ *
1838
+ * The snapshot is keyed by the id the page is *showing*, not by the fresh read's own `productId`:
1839
+ * they are the same id in every ordinary case, and keying by the fresh one would answer about a
1840
+ * product the page cannot find whenever they are not.
1841
+ */
1842
+ async function detailSnapshots(
1843
+ client: EldraClient,
1844
+ handle: string | null,
1845
+ current: unknown
1846
+ ): Promise<VolatileSnapshot[]> {
1847
+ const [id] = collectVolatileTargets(current);
1848
+ if (handle === null || handle === '' || id === undefined) return [];
1849
+ const raw = (await client.catalog.getProduct(handle, {})) as unknown as RawProductDetails;
1850
+ // The refresh is the half of the design that matters on a prerendered page: the build-time read
1851
+ // gave the stock the product had when the page was generated, and this corrects it after mount.
1852
+ // No category tree: this read is for the refresh's four volatile values and nothing else, and a
1853
+ // trail is content — it is already on the page from the build (`VolatileKey`).
1854
+ const fresh = mapProductDetails(raw, await readStock(client, raw), null);
1855
+ return [
1856
+ {
1857
+ id,
1858
+ price: fresh.price,
1859
+ available: fresh.available,
1860
+ stock: fresh.stock,
1861
+ inventory: fresh.inventory,
1862
+ },
1863
+ ];
1864
+ }
1865
+
1866
+ // ---------------------------------------------------------------------------------------------
1867
+ // createGatewayStorefront
1868
+ // ---------------------------------------------------------------------------------------------
1869
+
1870
+ export interface GatewayStorefrontOptions {
1871
+ route: StorefrontRoute;
1872
+ formsEndpoint?: string;
1873
+ /**
1874
+ * What the store sells in (`StorefrontCommerce`) — the platform's own answer, which only the app
1875
+ * layer can read (`app/plugins/eldra-storefront.ts`, off the runtime config). Omitted — a
1876
+ * Storybook story, a spec that only wants a mapping — the storefront reports `null`, and every
1877
+ * price renders as a number with no symbol.
1878
+ */
1879
+ commerce?: StorefrontCommerce | null;
1880
+ /**
1881
+ * The app layer's prerender/refresh abilities. Omitted — Storybook, a spec that only wants a
1882
+ * mapping — every result loads client-side the way it always did, and nothing refreshes.
1883
+ */
1884
+ runtime?: StorefrontRuntime;
1885
+ /**
1886
+ * The active content locale, read fresh on every call (`app/plugins/eldra-storefront.ts` derives
1887
+ * it from the route, so it follows a language switch). Every catalog, search and order read goes
1888
+ * out with it, and it is part of each result's cache key — see `withContentLocale` and
1889
+ * `GatewayResultOptions.locale`. Omitted — a story, a mapping spec, a single-locale store — and
1890
+ * nothing changes: no `locale` parameter and no key suffix, exactly as before.
1891
+ */
1892
+ locale?: () => string | undefined;
1893
+ }
1894
+
1895
+ /**
1896
+ * The same client, with the active content locale on every read whose answer is **text a merchant
1897
+ * wrote**: products, collections, categories, search, an order's line titles.
1898
+ *
1899
+ * Wrapped once here rather than threaded through the twenty-odd call sites below — including the
1900
+ * module-level helpers that take a `client` of their own — because the rule is one rule, and a
1901
+ * read that forgot it would silently serve a visitor on `/is-IS/...` the default language's copy
1902
+ * while everything around it was translated. A caller that passes its own `locale` still wins;
1903
+ * nothing in this file does, and that is the escape hatch for a read that must not be localized.
1904
+ *
1905
+ * `inventory` is deliberately untouched: stock counts carry no language.
1906
+ */
1907
+ function withContentLocale(client: EldraClient, locale: () => string | undefined): EldraClient {
1908
+ const q = <T extends object | undefined>(options: T): T => {
1909
+ const value = locale();
1910
+ return (value === undefined ? options : { locale: value, ...(options ?? {}) }) as T;
1911
+ };
1912
+ const catalog = client.catalog;
1913
+ const orders = client.orders;
1914
+ return {
1915
+ ...client,
1916
+ catalog: {
1917
+ ...catalog,
1918
+ listProducts: (options, context) => catalog.listProducts(q(options), context),
1919
+ getProduct: (productId, options, context) =>
1920
+ catalog.getProduct(productId, q(options), context),
1921
+ listCategories: (options, context) => catalog.listCategories(q(options), context),
1922
+ listCollections: (options, context) => catalog.listCollections(q(options), context),
1923
+ getCollection: (slug, options, context) => catalog.getCollection(slug, q(options), context),
1924
+ listCollectionProducts: (slug, options, context) =>
1925
+ catalog.listCollectionProducts(slug, q(options), context),
1926
+ search: (query, options, context) => catalog.search(query, q(options), context),
1927
+ },
1928
+ orders: {
1929
+ ...orders,
1930
+ get: (orderId, options, context) => orders.get(orderId, q(options), context),
1931
+ },
1932
+ };
1933
+ }
1934
+
1935
+ export function createGatewayStorefront(
1936
+ rawClient: EldraClient,
1937
+ options: GatewayStorefrontOptions
1938
+ ): StorefrontSource {
1939
+ const runtime = options.runtime;
1940
+ const locale = options.locale;
1941
+ // Every read below — and every module-level helper it hands this client to — carries the page's
1942
+ // content locale. See `withContentLocale`.
1943
+ const client = locale === undefined ? rawClient : withContentLocale(rawClient, locale);
1944
+ // What the store sells in, which is the scale every price parameter and the facets' own span are
1945
+ // expressed in (`CatalogFilterQuery`, `mapFacets`). `undefined` for a store that published none —
1946
+ // the same answer `<Price>` renders a plain number for, and the same two-decimal fallback.
1947
+ const currency = options.commerce?.currency;
1948
+
1949
+ /**
1950
+ * The store's category tree, read at most once for the life of this storefront and only when
1951
+ * something actually needs it: a category filter to resolve, a product page's breadcrumb trail, or
1952
+ * a category facet the platform could not place its own terms in (`readCategories`).
1953
+ *
1954
+ * The in-flight read is what is cached, so a product page and a grid asking at once share one
1955
+ * request; a failure drops the cache so the next read tries again rather than inheriting the first
1956
+ * one's error. Which callers swallow that failure and which let it through is on `readCategories`.
1957
+ *
1958
+ * It is read on the **server** during a prerender, inside the same `useAsyncData` the product or
1959
+ * collection read runs under, so a generated product page carries its trail in the page payload
1960
+ * and the browser fetches nothing to draw the crumb.
1961
+ */
1962
+ let categories: Promise<CategoryIndex> | null = null;
1963
+ const categoriesOnce = (): Promise<CategoryIndex> => {
1964
+ categories ??= readCategories(client).catch((caught: unknown) => {
1965
+ categories = null;
1966
+ throw caught;
1967
+ });
1968
+ return categories;
1969
+ };
1970
+
1971
+ /**
1972
+ * Collection slugs → catalog ids, memoised for the life of this storefront, asked for only the
1973
+ * slugs it does not already know (`readCollectionIds`). The catalogue-wide read is the only scope
1974
+ * whose `collection` clause goes out as a parameter, and a shopper ticking a third collection
1975
+ * should not re-ask about the two already resolved.
1976
+ */
1977
+ const collectionIds = new Map<string, string>();
1978
+ const collectionIdsFor = async (
1979
+ slugs: readonly string[]
1980
+ ): Promise<ReadonlyMap<string, string>> => {
1981
+ const missing = slugs.filter((slug) => slug !== '' && !collectionIds.has(slug));
1982
+ if (missing.length > 0) {
1983
+ for (const [slug, id] of await readCollectionIds(client, missing)) {
1984
+ collectionIds.set(slug, id);
1985
+ }
1986
+ }
1987
+ return collectionIds;
1988
+ };
1989
+
1990
+ /**
1991
+ * One read, two scopes. `collectionProducts` asks a collection's own product list and
1992
+ * `products` asks the catalogue-wide one; what differs is the endpoint, the `collection`
1993
+ * clause (a parameter on one, nothing to send on the other) and therefore `unfilterable`.
1994
+ * Everything a shopper can see — the filtered page, the filtered `total`, the facets the panel
1995
+ * draws from, the category tree completed into them — is the same code on purpose, because the
1996
+ * same block renders both.
1997
+ */
1998
+ const productListResult = (
1999
+ /**
2000
+ * **Every source this result is keyed by**, which is the whole of why it is a parameter: the key
2001
+ * is how the hydrating browser finds the value the build left for it, so a collection-scoped read
2002
+ * is keyed by its selector as well as its options and the catalogue-wide one by its options
2003
+ * alone. Dropping the selector made two different collections on one page share a key.
2004
+ */
2005
+ sources: Array<Ref<unknown>>,
2006
+ opts: Ref<{
2007
+ page: number;
2008
+ pageSize: number;
2009
+ sort?: string;
2010
+ filters?: Record<string, string[]>;
2011
+ /** A category page's own scope — the catalogue-wide read only; see
2012
+ * `StorefrontCatalog.products`. */
2013
+ categoryPath?: string;
2014
+ }>,
2015
+ scope: {
2016
+ method: string;
2017
+ /** `null` for the catalogue-wide read; a slug resolver for a collection-scoped one. */
2018
+ slug: (signal: AbortSignal) => Promise<string | null | false>;
2019
+ unfilterable?: readonly string[];
2020
+ unsortable?: readonly string[];
2021
+ collectionIdsFor?: (slugs: readonly string[]) => Promise<ReadonlyMap<string, string>>;
2022
+ }
2023
+ ): StorefrontResult<StorefrontCollectionProducts> =>
2024
+ createGatewayResult(
2025
+ sources,
2026
+ async (signal) => {
2027
+ const slug = await scope.slug(signal);
2028
+ if (slug === null) return null;
2029
+ const { page, pageSize, sort, filters, categoryPath } = opts.value;
2030
+ const gatewaySort = sort === undefined ? undefined : GATEWAY_SORT[sort];
2031
+ // The shopper's facets are the endpoint's own query parameters (contract 3.7.0, see
2032
+ // `CatalogFilterQuery`), so one request answers the filtered page, the filtered `total`
2033
+ // and — with `facets=true` — the counts the panel draws its groups from, over the whole
2034
+ // scope rather than the rows this read could reach.
2035
+ const filterQuery = await catalogFilterQuery(
2036
+ filters,
2037
+ currency,
2038
+ categoriesOnce,
2039
+ scope.collectionIdsFor
2040
+ );
2041
+ if (categoryPath !== undefined && categoryPath !== '') {
2042
+ // **A category page's own scope**, resolved after the shopper's filters so the two can be
2043
+ // intersected rather than OR-ed: `categoryId` is an OR over a list, so a ticked value
2044
+ // outside this subtree would widen the page past its own category. A path no category
2045
+ // occupies answers `null` — the grid's empty state — never the unscoped catalogue.
2046
+ const scoped = scopeCategoryIds(await categoriesOnce(), categoryPath, filterQuery);
2047
+ if (scoped === null) return null;
2048
+ filterQuery.categoryId = scoped;
2049
+ }
2050
+ const query = {
2051
+ page,
2052
+ pageSize,
2053
+ sort: gatewaySort === undefined ? undefined : [gatewaySort],
2054
+ ...filterQuery,
2055
+ facets: true,
2056
+ };
2057
+ const raw = (slug === false
2058
+ ? await client.catalog.listProducts(
2059
+ // The catalogue-wide list answers every product the merchant has, drafts included,
2060
+ // unless it is told otherwise — the collection route filters by status itself.
2061
+ { ...query, filter: [STATUS_ACTIVE] },
2062
+ { signal }
2063
+ )
2064
+ : await client.catalog.listCollectionProducts(slug, query, {
2065
+ signal,
2066
+ })) as unknown as RawProductList;
2067
+ // The facets pass through as the platform sent them. A family it did not place and did not
2068
+ // count up is **not** completed from the category list here: a synthesised parent row is a
2069
+ // filter such a gateway cannot honour, and the panel keeps that family flat instead (see
2070
+ // `parts/groups.ts`'s `rawValuesFor`). The only thing the category read is spent on is a
2071
+ // `category` *filter*'s slug→id lookup and a product's breadcrumb trail.
2072
+ const facets = mapFacets(raw.facets, currency);
2073
+ return {
2074
+ items: (raw.data ?? []).map(mapProductListItem),
2075
+ total: raw.meta.total,
2076
+ ...(scope.unfilterable === undefined ? {} : { unfilterable: scope.unfilterable }),
2077
+ ...(scope.unsortable === undefined ? {} : { unsortable: scope.unsortable }),
2078
+ ...(facets === undefined ? {} : { facets }),
2079
+ };
2080
+ },
2081
+ { method: scope.method, runtime, locale, volatile: 'batch' }
2082
+ );
2083
+
2084
+ const catalog: StorefrontCatalog = {
2085
+ product: (handle) =>
2086
+ createGatewayResult(
2087
+ [handle],
2088
+ async (signal) => {
2089
+ if (!handle.value) return null;
2090
+ const raw = (await client.catalog.getProduct(
2091
+ handle.value,
2092
+ {},
2093
+ { signal }
2094
+ )) as unknown as RawProductDetails;
2095
+ // Stock and the category tree in parallel: neither needs the other, and the trail must not
2096
+ // add a serial round trip to every product page. The tree's failure is swallowed here — a
2097
+ // product page without a category crumb is a product page, while a product page that 500s
2098
+ // because the category list was unreachable is not — which is the opposite of what the
2099
+ // `category` *filter* does with the same read (`readCategories`).
2100
+ const [stock, tree] = await Promise.all([
2101
+ readStock(client, raw, signal),
2102
+ categoriesOnce().catch(() => null),
2103
+ ]);
2104
+ return mapProductDetails(raw, stock, tree);
2105
+ },
2106
+ {
2107
+ method: 'catalog.product',
2108
+ runtime,
2109
+ locale,
2110
+ volatile: (current) => detailSnapshots(client, handle.value, current),
2111
+ }
2112
+ ),
2113
+ collection: (handle) =>
2114
+ createGatewayResult(
2115
+ [handle],
2116
+ async (signal) => {
2117
+ if (!handle.value) return null;
2118
+ const raw = (await client.catalog.getCollection(
2119
+ handle.value,
2120
+ {},
2121
+ { signal }
2122
+ )) as unknown as RawCollectionItem;
2123
+ return mapCollectionItem(raw);
2124
+ },
2125
+ { method: 'catalog.collection', runtime, locale }
2126
+ ),
2127
+ /**
2128
+ * The category page's own read. There is no endpoint that takes a path — the catalog answers
2129
+ * `{id, slug, title, parentId}` rows and no trail — so this is the **whole category list**
2130
+ * (already memoised for the trail and the `category` filter, so a category page pays for it
2131
+ * once however many blocks ask) walked into a placed category.
2132
+ *
2133
+ * The failure is **not** swallowed, unlike the trail's: a category page with no category is not
2134
+ * a page, so the block's error branch is the honest surface rather than an empty grid under a
2135
+ * blank heading.
2136
+ */
2137
+ category: (path) =>
2138
+ createGatewayResult(
2139
+ [path],
2140
+ async () => {
2141
+ if (!path.value) return null;
2142
+ return placeCategory(await categoriesOnce(), path.value);
2143
+ },
2144
+ { method: 'catalog.category', runtime, locale }
2145
+ ),
2146
+ collectionProducts: (collection, opts) => {
2147
+ // `collection` is a source of this result as well as of its key, so a block that re-points the
2148
+ // grid at another collection re-reads under a key of its own — which is why the selector is
2149
+ // read off `collection.value` inside the fetcher rather than resolved once here.
2150
+ const result = productListResult([collection, opts], opts, {
2151
+ method: 'catalog.collectionProducts',
2152
+ slug: (signal) => resolveCollectionSlug(client, collection.value, signal),
2153
+ // The one source this scope cannot narrow by is declared rather than dropped: see
2154
+ // `COLLECTION_SCOPE_UNFILTERABLE`.
2155
+ unfilterable: COLLECTION_SCOPE_UNFILTERABLE,
2156
+ // `best-selling` on this scope too — see `GATEWAY_UNSORTABLE`.
2157
+ unsortable: GATEWAY_UNSORTABLE,
2158
+ });
2159
+ return result;
2160
+ },
2161
+ // `false` for the slug: not "no scope" (which is `null`, and answers nothing) but "the whole
2162
+ // catalogue", which is a different endpoint. Nothing is `unfilterable` here — that list does take
2163
+ // a `collectionId`, so the `collection` group filters for real (`StorefrontCatalog.products`).
2164
+ // `best-selling` is still `unsortable`, the same as the collection-scoped read: this list has no
2165
+ // more sales data to order by than the other one does (`GATEWAY_UNSORTABLE`).
2166
+ products: (opts) =>
2167
+ productListResult([opts], opts, {
2168
+ method: 'catalog.products',
2169
+ slug: () => Promise.resolve(false as const),
2170
+ collectionIdsFor,
2171
+ unsortable: GATEWAY_UNSORTABLE,
2172
+ }),
2173
+ related: (handle, limit) =>
2174
+ createGatewayResult(
2175
+ [handle],
2176
+ (signal) => relatedProducts(client, handle.value, limit, signal),
2177
+ { method: 'catalog.related', runtime, locale, keyArgs: [limit], volatile: 'batch' }
2178
+ ),
2179
+ byHandles: (handles) =>
2180
+ createGatewayResult(
2181
+ [handles],
2182
+ async (signal) => {
2183
+ const filter = inFilter('slug', handles.value);
2184
+ if (filter.length === 0) return [];
2185
+ const raw = (await client.catalog.listProducts(
2186
+ { pageSize: handles.value.length, filter: [...filter, STATUS_ACTIVE] },
2187
+ { signal }
2188
+ )) as unknown as RawProductList;
2189
+ return (raw.data ?? []).map(mapProductListItem);
2190
+ },
2191
+ { method: 'catalog.byHandles', runtime, locale, volatile: 'batch' }
2192
+ ),
2193
+ volatileByIds: (ids) => volatileSnapshots(client, ids),
2194
+ notifyBackInStock: (input) =>
2195
+ postToEndpoint(options.formsEndpoint, { kind: 'notifyBackInStock', ...input }),
2196
+ };
2197
+
2198
+ const search: StorefrontSearch = {
2199
+ run: (query) =>
2200
+ createGatewayResult(
2201
+ [query],
2202
+ async (signal) => {
2203
+ if (!query.value)
2204
+ return {
2205
+ query: query.value,
2206
+ total: 0,
2207
+ products: [],
2208
+ articles: [],
2209
+ pages: [],
2210
+ suggestion: null,
2211
+ };
2212
+ const raw = (await client.catalog.search(
2213
+ query.value,
2214
+ {},
2215
+ { signal }
2216
+ )) as unknown as RawSearchResponse;
2217
+ // The search index carries neither prices nor images; `enrichedSearchResponse` reads
2218
+ // both from the catalogue before this result is published. See its own comment.
2219
+ return await enrichedSearchResponse(client, mapSearchResponse(raw, query.value), signal);
2220
+ },
2221
+ { method: 'search.run', runtime, locale }
2222
+ ),
2223
+ };
2224
+
2225
+ const orders: StorefrontOrders = {
2226
+ current: (token) =>
2227
+ createGatewayResult(
2228
+ [token],
2229
+ async (signal) => {
2230
+ if (!token.value) return null;
2231
+ const raw = (await client.orders.get(token.value, {}, { signal })) as unknown as RawOrder;
2232
+ return mapOrder(raw);
2233
+ },
2234
+ { method: 'orders.current', runtime, locale }
2235
+ ),
2236
+ };
2237
+
2238
+ const forms: StorefrontForms = {
2239
+ subscribe: (input) => postToEndpoint(options.formsEndpoint, { kind: 'subscribe', ...input }),
2240
+ sendMessage: (input) =>
2241
+ postToEndpoint(options.formsEndpoint, { kind: 'sendMessage', ...input }),
2242
+ };
2243
+
2244
+ return {
2245
+ ready: ref(true),
2246
+ commerce: options.commerce ?? null,
2247
+ route: options.route,
2248
+ catalog,
2249
+ cart: createCartStore(createGatewayCartOps(client)),
2250
+ search,
2251
+ orders,
2252
+ forms,
2253
+ wishlist: createWishlistStore(),
2254
+ history: createHistoryStore(),
2255
+ };
2256
+ }