@eldrajs/theme-cli 0.0.0 → 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 +26 -1
  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 +50 -2
  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,1017 @@
1
+ import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
2
+ import { seedLayout } from '@eldrajs/vite-plugin-theme';
3
+ import { starterPages, starterTemplateRoles, starterTemplates } from '../../app/templates';
4
+
5
+ /**
6
+ * A mock Eldra gateway for the starter's own `nuxi generate` + static-serve tests — the same
7
+ * shape `packages/theme-nuxt/test/mockGateway.ts` takes, extended with the **catalog** endpoints
8
+ * the storefront reads (`app/storefront/gateway.ts`) and with a settable answer delay, so a
9
+ * browser driving the generated site can observe the post-hydration refresh while it is in
10
+ * flight.
11
+ *
12
+ * Two roles in one server, deliberately: `nuxi generate` reads the CMS route templates and the
13
+ * catalog through it, and the **browser** then reads the catalog through the same origin, so the
14
+ * request list a test collects is the whole conversation a real visitor's page has.
15
+ *
16
+ * The route templates are the starter's own (`app/templates.ts`'s `starterTemplates()`, laid out
17
+ * by `@eldrajs/vite-plugin-theme`'s `seedLayout`), with the `header`/`footer` role nodes resolved
18
+ * to ordinary block nodes carrying `starterTemplateRoles()`'s data — a role resolves to the site's
19
+ * own reusable component, which a mock gateway has no concept of, and the rendered page must still
20
+ * carry the navigation and footer a real one does (`navigation` creates a storefront result of its
21
+ * own, so leaving it out would change the very ordering these tests are about). Everything else —
22
+ * which blocks a product page carries, which fields the catalog seed strips — is exactly what Core
23
+ * seeds a real site with.
24
+ *
25
+ * **Three Core behaviours are encoded by hand here**, because a mock has no Core to ask. Each is a
26
+ * second copy of a rule that really lives in Core, so if Core changes one the generated page
27
+ * renders as `data-eldra-invalid-layout` — silently — and a reader has to rediscover why:
28
+ *
29
+ * 1. a `reusable` role node resolves to the site's own header/footer component
30
+ * (`routeTemplateEntries`);
31
+ * 2. a seed node carrying `templates`/`bindings` becomes a `template-block` node naming its
32
+ * `apiId`, its block entry addressed by uuid (`routeTemplateEntries`);
33
+ * 3. a CMS **page** document is a **version-2** layout envelope of ordinary `block` nodes, and a
34
+ * no-parent page whose slug is `home` is the site root `/` (`pageEntries`);
35
+ * 4. a theme's **page seed** becomes such a page — one per `pageSeeds[]` entry, its blocks in the
36
+ * seed's own order, each `@header`/`@footer` placement resolved to the site's own role
37
+ * component and each `required` block's node carrying `locked: true` (`pageEntries`).
38
+ */
39
+
40
+ export const ORG_ID = '3fa85f64-5717-4562-b3fc-2c963f66afa6';
41
+
42
+ /** A stable v4-shaped uuid per block index — a layout node's `entryId` must be one. */
43
+ const blockUuid = (index: number): string =>
44
+ `${String(index + 1).padStart(8, '0')}-0000-4000-8000-000000000000`;
45
+
46
+ /** The home page's block entries start here, so a page block id can never collide with a
47
+ * template block id — the mount counter keys by entry id. */
48
+ const PAGE_BLOCK_UUID_OFFSET = 100;
49
+
50
+ interface MockVariant {
51
+ id: string;
52
+ sku: string;
53
+ price: number;
54
+ compareAtPrice?: number;
55
+ status: string;
56
+ }
57
+
58
+ interface MockProduct {
59
+ id: string;
60
+ slug: string;
61
+ title: string;
62
+ status: string;
63
+ categoryId: string;
64
+ minPrice: number;
65
+ maxPrice: number;
66
+ compareAtPrice?: number;
67
+ variants: MockVariant[];
68
+ }
69
+
70
+ const product = (
71
+ slug: string,
72
+ title: string,
73
+ price: number,
74
+ extra: Partial<MockProduct> = {}
75
+ ): MockProduct => ({
76
+ id: `prod-${slug}`,
77
+ slug,
78
+ title,
79
+ status: 'ACTIVE',
80
+ categoryId: 'cat-cups',
81
+ minPrice: price,
82
+ maxPrice: price,
83
+ variants: [{ id: `var-${slug}`, sku: slug.toUpperCase(), price, status: 'ACTIVE' }],
84
+ ...extra,
85
+ });
86
+
87
+ /** The product every assertion is written about, plus enough siblings for a full carousel. */
88
+ export const PRODUCT_HANDLE = 'ash-glaze-mug';
89
+ export const COLLECTION_HANDLE = 'the-winter-edit';
90
+
91
+ export const PRODUCTS: MockProduct[] = [
92
+ product(PRODUCT_HANDLE, 'Ash glaze mug', 42),
93
+ product('cedar-serving-board', 'Cedar serving board', 68),
94
+ product('flax-tea-towel', 'Flax tea towel', 24),
95
+ product('stoneware-bowl', 'Stoneware bowl', 36),
96
+ product('brass-candle-holder', 'Brass candle holder', 52),
97
+ product('linen-napkin-set', 'Linen napkin set', 44),
98
+ product('walnut-spoon', 'Walnut spoon', 18),
99
+ ];
100
+
101
+ /**
102
+ * A cart a browser is already carrying — the shopper state a reload restores before anything on
103
+ * the page has mounted.
104
+ *
105
+ * The id is what `@eldrajs/sdk`'s `createCartSession` keeps in `localStorage` under `eldra.cartId`,
106
+ * so seeding that key and loading a page is exactly a shopper's second visit: the cart store's
107
+ * `init()` reads the id during the storefront plugin's `setup`, asks for this cart, and the answer
108
+ * lands some time after the page has hydrated. Two lines, so the header's count pill reads a number
109
+ * no empty cart could produce.
110
+ */
111
+ export const SEEDED_CART_ID = 'aa11bb22-0000-4000-8000-000000000000';
112
+ export const SEEDED_CART_QUANTITY = 2;
113
+
114
+ function seededCart(): Record<string, unknown> {
115
+ const row = PRODUCTS[0]!;
116
+ const unit = row.minPrice;
117
+ return {
118
+ id: SEEDED_CART_ID,
119
+ currency: 'ISK',
120
+ items: [
121
+ {
122
+ id: 'cart-line-1',
123
+ productId: row.id,
124
+ productSlug: row.slug,
125
+ variantId: row.variants[0]!.id,
126
+ title: row.title,
127
+ price: unit,
128
+ quantity: SEEDED_CART_QUANTITY,
129
+ },
130
+ ],
131
+ totals: {
132
+ subtotal: unit * SEEDED_CART_QUANTITY,
133
+ discount: 0,
134
+ taxAmount: 0,
135
+ total: unit * SEEDED_CART_QUANTITY,
136
+ },
137
+ };
138
+ }
139
+
140
+ /**
141
+ * **Which public-contract shape the catalog half of this fixture answers**, because the two shapes of
142
+ * the category facet are a *pair* and modelling one half of each would be a gateway that does not
143
+ * exist:
144
+ *
145
+ * - `'3.8.0'` (the default, and the platform this theme targets) — the facet's category terms carry
146
+ * `parentId`, their counts are **rolled up** over each subtree, and a `categoryId` filter matches
147
+ * the **whole subtree**. The filter panel nests the family and offers parent rows.
148
+ * - `'3.7.0'` — flat facet terms (no `parentId`), counts over **assigned** categories only, and a
149
+ * `categoryId` filter matching **direct membership** only. The panel keeps the family flat and
150
+ * offers no parent row, which is the only honest answer: a `Tableware` row here would be a filter
151
+ * this gateway cannot honour.
152
+ *
153
+ * The earlier version of this fixture answered flat facets *and* an expanding filter — no real
154
+ * gateway is in that state, and the combination hid exactly the defect the flat fallback exists to
155
+ * prevent.
156
+ */
157
+ export type MockCatalogContract = '3.7.0' | '3.8.0';
158
+
159
+ let catalogContract: MockCatalogContract = '3.8.0';
160
+
161
+ /** Switches the contract the catalog endpoints answer. Per-process, so a spec that changes it puts it
162
+ * back; `startMockGateway` resets it for the server it starts. */
163
+ export function setMockCatalogContract(contract: MockCatalogContract): void {
164
+ catalogContract = contract;
165
+ }
166
+
167
+ /**
168
+ * The store's categories — what `GET /catalog/v1/categories` answers, which is how a `?category=`
169
+ * slug becomes the `categoryId` the list takes **and** where a product's breadcrumb trail comes from.
170
+ * Answered the same way under both contracts: the category *list* has always carried `parentId`, and
171
+ * it is the trail's only source.
172
+ *
173
+ * Two levels, because one level cannot prove a trail: `Tableware` holds `Cups`, every product sits in
174
+ * `Cups`, and a prerendered product page therefore has to render `Tableware / Cups` from this read
175
+ * alone.
176
+ */
177
+ interface MockCategory {
178
+ id: string;
179
+ slug: string;
180
+ title: string;
181
+ parentId: string | null;
182
+ }
183
+
184
+ const CATEGORIES: MockCategory[] = [
185
+ { id: 'cat-tableware', slug: 'tableware', title: 'Tableware', parentId: null },
186
+ { id: 'cat-cups', slug: 'cups', title: 'Cups', parentId: 'cat-tableware' },
187
+ ];
188
+
189
+ const CATEGORY_BY_ID = new Map(CATEGORIES.map((row) => [row.id, row]));
190
+
191
+ /** A product's own category and every ancestor above it, which is what a `categoryId` filter matches
192
+ * against and what the facet counts a product under. */
193
+ function categoryChainOf(row: { categoryId: string }): string[] {
194
+ const chain: string[] = [];
195
+ let id: string | null = row.categoryId;
196
+ while (id !== null && !chain.includes(id)) {
197
+ chain.push(id);
198
+ id = CATEGORY_BY_ID.get(id)?.parentId ?? null;
199
+ }
200
+ return chain;
201
+ }
202
+
203
+ const COLLECTIONS = [
204
+ {
205
+ id: 'col-winter',
206
+ slug: COLLECTION_HANDLE,
207
+ title: 'The winter edit',
208
+ description: 'Warm tableware for the darkest months.',
209
+ productCount: PRODUCTS.length,
210
+ },
211
+ ];
212
+
213
+ const detailOf = (row: MockProduct): Record<string, unknown> => ({
214
+ id: row.id,
215
+ slug: row.slug,
216
+ title: row.title,
217
+ status: row.status,
218
+ categoryId: row.categoryId,
219
+ // The field the public contract names for the trail's starting point, beside the one `related`
220
+ // already read. Both, with the same value, is what a live response looks like.
221
+ primaryCategoryId: row.categoryId,
222
+ categoryIds: [row.categoryId],
223
+ description: { text: `${row.title} — thrown by hand, glazed in ash.` },
224
+ mediaLinks: [],
225
+ options: [],
226
+ variants: row.variants,
227
+ });
228
+
229
+ const listItemOf = (row: MockProduct): Record<string, unknown> => ({
230
+ id: row.id,
231
+ slug: row.slug,
232
+ title: row.title,
233
+ status: row.status,
234
+ minPrice: row.minPrice,
235
+ maxPrice: row.maxPrice,
236
+ ...(row.compareAtPrice === undefined ? {} : { compareAtPrice: row.compareAtPrice }),
237
+ totalVariants: row.variants.length,
238
+ });
239
+
240
+ /**
241
+ * `POST /inventory/v1/stock/availability`'s answer: every variant the request named, in stock.
242
+ *
243
+ * The product page reads it alongside the catalogue response (`app/storefront/gateway.ts`), so
244
+ * without it the generated site would exercise the fail-soft path on every product — a 404 in the
245
+ * browser console and no inventory ever read, which is not what a deployed site does. `stockOf` is
246
+ * what a test changes to make a variant sold out.
247
+ */
248
+ const availabilityOf = (body: unknown): Record<string, unknown> => {
249
+ const items = (body as { items?: Array<{ variantId?: unknown }> } | null)?.items ?? [];
250
+ return {
251
+ items: items.flatMap((item) =>
252
+ typeof item.variantId === 'string'
253
+ ? [
254
+ {
255
+ variantId: item.variantId,
256
+ locationId: 'loc-default',
257
+ available: true,
258
+ allowBackorder: false,
259
+ availableQuantity: 24,
260
+ },
261
+ ]
262
+ : []
263
+ ),
264
+ };
265
+ };
266
+
267
+ /** The request body of a POST, as JSON — only `availabilityOf` needs one. */
268
+ async function readJsonBody(req: IncomingMessage): Promise<unknown> {
269
+ const chunks: Buffer[] = [];
270
+ for await (const chunk of req) chunks.push(chunk as Buffer);
271
+ if (chunks.length === 0) return null;
272
+ try {
273
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'));
274
+ } catch {
275
+ return null;
276
+ }
277
+ }
278
+
279
+ const listResponse = (
280
+ data: unknown[],
281
+ extra: Record<string, unknown> = {}
282
+ ): Record<string, unknown> => ({
283
+ data,
284
+ meta: {
285
+ hasNext: false,
286
+ hasPrev: false,
287
+ page: 1,
288
+ pageSize: 100,
289
+ rows: data.length,
290
+ total: (extra.total as number | undefined) ?? data.length,
291
+ totalPages: 1,
292
+ },
293
+ ...(extra.facets === undefined ? {} : { facets: extra.facets }),
294
+ });
295
+
296
+ /**
297
+ * The header a **deployed** site holds, rather than the seed a theme ships.
298
+ *
299
+ * The seed ships no links at all — a theme cannot know an organisation's own collections, products
300
+ * or pages, so `pages/*.page.json` leaves the field empty and an author fills it in Studio. These
301
+ * rows are therefore this file's own fixture, not the seed's content, and they are what makes the
302
+ * generate's link resolution observable: a merchant who has authored a header is the only one who
303
+ * has hrefs to bake.
304
+ *
305
+ * What a site stores is a `{_type, id}` target — Core resolves a handle to an id when an author
306
+ * picks a destination — so that is the shape here. Four rows stand for the four answers the
307
+ * resolver can give: a collection this gateway serves, a product it serves, an ordinary URL that
308
+ * needs no catalog at all, and a target it has never heard of, which must render as a label and no
309
+ * anchor.
310
+ *
311
+ * A fifth row carries `children`, which is what makes it a mega-menu trigger rather than a link —
312
+ * the only shape whose geometry can be measured in a real browser. It is last, so the four answers
313
+ * above keep the document order the href assertions read.
314
+ */
315
+ export const LINKED_HEADER_LABELS = {
316
+ collection: 'The winter edit',
317
+ product: 'Ash glaze mug',
318
+ url: 'Journal',
319
+ missing: 'Discontinued',
320
+ mega: 'Everything',
321
+ megaChild: 'All of it',
322
+ } as const;
323
+
324
+ /**
325
+ * `overrides` is how a single page gets a header state the others do not have. The collection
326
+ * template takes `transparentOverHero`, because what that state does to the bar — and to an open
327
+ * mega-menu's own ground — is a computed colour, answerable only in a real browser and only on a
328
+ * page whose header actually carries the field.
329
+ */
330
+ function linkedHeaderData(
331
+ data: Record<string, unknown>,
332
+ overrides: Record<string, unknown> = {}
333
+ ): Record<string, unknown> {
334
+ return {
335
+ ...data,
336
+ ...overrides,
337
+ links: [
338
+ {
339
+ kind: 'collection',
340
+ target: { _type: 'collection', id: COLLECTIONS[0]!.id },
341
+ label: LINKED_HEADER_LABELS.collection,
342
+ },
343
+ {
344
+ kind: 'product',
345
+ target: { _type: 'product', id: PRODUCTS[0]!.id },
346
+ label: LINKED_HEADER_LABELS.product,
347
+ },
348
+ { kind: 'url', url: '/journal', label: LINKED_HEADER_LABELS.url },
349
+ {
350
+ kind: 'collection',
351
+ target: { _type: 'collection', id: 'col-deleted' },
352
+ label: LINKED_HEADER_LABELS.missing,
353
+ },
354
+ {
355
+ kind: 'collection',
356
+ target: { _type: 'collection', id: COLLECTIONS[0]!.id },
357
+ label: LINKED_HEADER_LABELS.mega,
358
+ children: [
359
+ {
360
+ kind: 'collection',
361
+ target: { _type: 'collection', id: COLLECTIONS[0]!.id },
362
+ group: 'Shop',
363
+ label: LINKED_HEADER_LABELS.megaChild,
364
+ },
365
+ ],
366
+ },
367
+ ],
368
+ };
369
+ }
370
+
371
+ /**
372
+ * The starter's own seeds, as the CMS route-template entries a deployed site holds.
373
+ *
374
+ * Two shapes differ from `seedLayout`'s output, both because a seed is an *input* Core rewrites
375
+ * when it creates the template: a `reusable` role node resolves to the site's own header/footer
376
+ * component, which a mock has none of, and a node carrying `templates`/`bindings` becomes a
377
+ * `template-block` node naming its `apiId` (an ordinary `block` node takes neither key —
378
+ * `@eldrajs/theme-core`'s layout validator refuses it, and the whole page then renders as
379
+ * `data-eldra-invalid-layout`).
380
+ *
381
+ * The collection template also carries one block the seed does not: a `product-carousel` over the
382
+ * same collection its grid shows, which is an ordinary thing for a merchant to put there and the
383
+ * shape that catches a refresh asking about one product twice — the grid and the carousel are
384
+ * different blocks, so they arrive in different lazily-imported chunks and therefore in different
385
+ * refresh bursts, both about exactly the same products.
386
+ */
387
+ function routeTemplateEntries(): Array<{ id: string; data: Record<string, unknown> }> {
388
+ return starterTemplates()
389
+ .filter((seed) => seed.schemaApiId !== 'home')
390
+ .map((seed) => {
391
+ const layout = seedLayout(seed);
392
+ const roles = starterTemplateRoles();
393
+ const extra =
394
+ seed.schemaApiId === 'catalog:collection'
395
+ ? [
396
+ {
397
+ id: 'collection-more',
398
+ apiId: 'product-carousel',
399
+ data: {
400
+ heading: 'More from this edit',
401
+ variant: 'collection',
402
+ sourceCollection: { _type: 'collection', slug: COLLECTION_HANDLE },
403
+ limit: '8',
404
+ showSwatches: true,
405
+ background: 'none',
406
+ },
407
+ },
408
+ ]
409
+ : [];
410
+ const blocks = [
411
+ {
412
+ id: 'role-header',
413
+ apiId: roles.header.apiId,
414
+ data: linkedHeaderData(roles.header.data, {
415
+ transparentOverHero: seed.schemaApiId === 'catalog:collection',
416
+ }),
417
+ },
418
+ ...seed.blocks,
419
+ ...extra,
420
+ { id: 'role-footer', apiId: roles.footer.apiId, data: roles.footer.data },
421
+ ];
422
+ const apiIdOf = new Map(blocks.map((block) => [block.id, block.apiId]));
423
+ // A layout node addresses its block entry by **uuid** (`@eldrajs/theme-core`'s layout
424
+ // validator), while a seed names its blocks by a readable id; Core mints the entry when it
425
+ // creates the template. One deterministic uuid per seed block id stands in for that.
426
+ const entryIdOf = new Map(blocks.map((block, index) => [block.id, blockUuid(index)]));
427
+ return {
428
+ id: `rt-${seed.schemaApiId.replace('catalog:', '')}`,
429
+ data: {
430
+ title: seed.title,
431
+ routePattern: seed.routePattern,
432
+ schemaApiId: seed.schemaApiId,
433
+ // A category is addressed by its whole canonical path, so its template's parameter — and
434
+ // therefore its `slugField` — is `path` rather than `slug`. Core derives this from the
435
+ // target, and `resolveRoute` refuses a template whose field and parameter disagree, so
436
+ // getting it wrong here fails the generate rather than quietly serving nothing.
437
+ slugField: seed.schemaApiId === 'catalog:category' ? 'path' : 'slug',
438
+ layout: {
439
+ ...layout,
440
+ root: {
441
+ ...layout.root,
442
+ children: withExtraNodes(layout.root.children ?? [], extra).map((node) => {
443
+ const entryId = entryIdOf.get(node.id);
444
+ const base = node.type === 'reusable' ? { id: node.id, type: 'block' } : node;
445
+ return 'templates' in base || 'bindings' in base
446
+ ? { ...base, entryId, type: 'template-block', apiId: apiIdOf.get(node.id) }
447
+ : { ...base, entryId };
448
+ }),
449
+ },
450
+ },
451
+ blocks: blocks.map((block) => ({
452
+ id: entryIdOf.get(block.id),
453
+ schemaApiId: block.apiId,
454
+ data: block.data,
455
+ })),
456
+ },
457
+ };
458
+ });
459
+ }
460
+
461
+ /** The extra blocks' nodes, placed where Core would place them: after the seed's own, before the
462
+ * footer role. */
463
+ function withExtraNodes<T>(children: readonly T[], extra: ReadonlyArray<{ id: string }>): T[] {
464
+ if (extra.length === 0) return [...children];
465
+ const footerAt = children.findIndex((node) => (node as { id?: unknown }).id === 'role-footer');
466
+ const at = footerAt === -1 ? children.length : footerAt;
467
+ const nodes = extra.map((block) => ({ id: block.id, type: 'block' }) as T);
468
+ return [...children.slice(0, at), ...nodes, ...children.slice(at)];
469
+ }
470
+
471
+ /**
472
+ * The starter's own home seed, as the CMS **page** entry a deployed site holds — the control every
473
+ * route-template assertion is read against.
474
+ *
475
+ * A static route resolves to a `page` and no `template`, so `app/pages/[...slug].vue` hands
476
+ * `EldraLayout` no `templateEntry` and the layout takes its page branch: a v2 page document of
477
+ * ordinary `block` nodes. That is exactly the shape the deployed site's `/` has, down to the
478
+ * `product-carousel` it carries, which is what makes it a fair comparison for a product page's
479
+ * template-block leaves.
480
+ *
481
+ * Core behaviour **3** of the three this file hand-encodes (module header): the `version: 2`
482
+ * envelope and the ordinary `block` children are Core's *page* layout shape, not `seedLayout`'s
483
+ * (which emits `version: 1` and the role nodes a route template takes), and `slug: 'home'` with no
484
+ * parent is what `@eldrajs/theme-core`'s `resolvePagePath` turns into `/`. Get the envelope wrong
485
+ * and the page renders as `data-eldra-invalid-layout`; get the slug wrong and it never prerenders.
486
+ */
487
+ export const HOME_PAGE_PATH = '/';
488
+
489
+ /**
490
+ * **Two locales, deliberately.** `@eldrajs/theme-nuxt` serves the default locale at `/` and every
491
+ * other supported one under a path prefix, so a two-locale organisation is what makes the generated
492
+ * artifact contain both halves of that rule — the unprefixed site *and* a prefixed copy of every
493
+ * content path. A static host answers 404 for a path it has no file for, however well the app
494
+ * would have rendered it, so only a real `nuxi generate` can see that half go missing.
495
+ *
496
+ * `en-US` is the default, so every existing request assertion holds unchanged: an unprefixed read
497
+ * carries no `locale` at all, exactly as it did before locales existed.
498
+ */
499
+ export const DEFAULT_LOCALE = 'en-US';
500
+ export const PREFIXED_LOCALE = 'is-IS';
501
+
502
+ /** The paths the theme's own page seeds serve, which the generate must emit a file for. */
503
+ export const SEEDED_PAGE_PATHS = starterPages().map((seed) => `/${seed.page.slug}`);
504
+
505
+ /** One page document: a v2 envelope of ordinary `block` nodes over the blocks given. A node with
506
+ * `locked` is one Core created from a seed's `required` block — stored on the node, and the reason
507
+ * `@eldrajs/theme-core`'s layout validator has to admit the key. */
508
+ function pageEntry(
509
+ id: string,
510
+ title: string,
511
+ slug: string,
512
+ blocks: ReadonlyArray<{
513
+ id: string;
514
+ apiId: string;
515
+ data: Record<string, unknown>;
516
+ locked?: true;
517
+ }>,
518
+ uuidOffset: number
519
+ ): { id: string; data: Record<string, unknown> } {
520
+ const entryIdOf = new Map(
521
+ blocks.map((block, index) => [block.id, blockUuid(uuidOffset + index)])
522
+ );
523
+ return {
524
+ id,
525
+ data: {
526
+ title,
527
+ slug,
528
+ layout: {
529
+ version: 2,
530
+ root: {
531
+ id: 'root',
532
+ type: 'flex',
533
+ layout: { direction: { normal: 'column' } },
534
+ children: blocks.map((block) => ({
535
+ id: block.id,
536
+ type: 'block',
537
+ entryId: entryIdOf.get(block.id),
538
+ ...(block.locked === true ? { locked: true } : {}),
539
+ })),
540
+ },
541
+ },
542
+ blocks: blocks.map((block) => ({
543
+ id: entryIdOf.get(block.id),
544
+ schemaApiId: block.apiId,
545
+ data: block.data,
546
+ })),
547
+ },
548
+ };
549
+ }
550
+
551
+ function pageEntries(): Array<{ id: string; data: Record<string, unknown> }> {
552
+ const seed = starterTemplates().find((candidate) => candidate.schemaApiId === 'home');
553
+ if (seed === undefined) throw new Error('mockGateway: the starter no longer seeds a home page');
554
+ const roles = starterTemplateRoles();
555
+ const home = [
556
+ { id: 'role-header', apiId: roles.header.apiId, data: linkedHeaderData(roles.header.data) },
557
+ ...seed.blocks,
558
+ { id: 'role-footer', apiId: roles.footer.apiId, data: roles.footer.data },
559
+ ];
560
+ return [
561
+ // No parent and the slug `home` is the site root — see `resolvePagePath`.
562
+ pageEntry('page-home', seed.title, 'home', home, PAGE_BLOCK_UUID_OFFSET),
563
+ ...seededPageEntries(roles),
564
+ ];
565
+ }
566
+
567
+ /**
568
+ * The theme's own page seeds as the CMS page entries a deployed site holds — `/cart`, `/wishlist`,
569
+ * `/search` and `/products`. The first three were code routes under `app/pages/` until the theme
570
+ * started seeding them; `/products` never was, and is the one that also proves a static page and a
571
+ * route template can share a path prefix (`/products` beside `/products/:slug`).
572
+ *
573
+ * Core behaviour **4** of the four this file hand-encodes (module header): a `@header`/`@footer`
574
+ * placement resolves to the site's own role component (a mock has none, so the role's block data is
575
+ * inlined where the placement stands, exactly as `routeTemplateEntries` does it), and a `required`
576
+ * block's node is created `locked: true`. Get the first wrong and the generated page carries no
577
+ * header; get the second wrong and nothing fails here — which is the point of writing it down, since
578
+ * the key has to survive `@eldrajs/theme-core`'s layout validator for the page to render at all.
579
+ */
580
+ function seededPageEntries(
581
+ roles: ReturnType<typeof starterTemplateRoles>
582
+ ): Array<{ id: string; data: Record<string, unknown> }> {
583
+ return starterPages().map((seed, seedIndex) => {
584
+ const blocks = seed.blocks.map((entry, index) => {
585
+ if ('role' in entry) {
586
+ const role = roles[entry.role]!;
587
+ return {
588
+ id: `role-${entry.role}`,
589
+ apiId: role.apiId,
590
+ data: entry.role === 'header' ? linkedHeaderData(role.data) : role.data,
591
+ };
592
+ }
593
+ return {
594
+ id: `${seed.page.slug}-${index}`,
595
+ apiId: entry.apiId,
596
+ data: entry.data,
597
+ ...(entry.required === true ? { locked: true as const } : {}),
598
+ };
599
+ });
600
+ return pageEntry(
601
+ `page-${seed.page.slug}`,
602
+ seed.title,
603
+ seed.page.slug,
604
+ blocks,
605
+ // One uuid range per page, after the home page's, so no two pages' block
606
+ // entry ids collide — the mount counter keys by entry id.
607
+ PAGE_BLOCK_UUID_OFFSET + 100 * (seedIndex + 1)
608
+ );
609
+ });
610
+ }
611
+
612
+ /**
613
+ * **The storefront filter parameters, as the catalog list declares them** (contract 3.7.0): the
614
+ * half of the shopper's facets a generated page's grid actually sends. `minPrice`/`maxPrice` are
615
+ * inclusive and in minor units — this store sells in krónur, which have none, so they read as the
616
+ * same numbers the shopper typed — `categoryId`/`collectionId` are repeatable and OR'd, `option` is
617
+ * a repeatable `<key>:<value>`, and `availability` is one of two values read off `availabilityOf`
618
+ * (every variant of every product in this fixture is in stock).
619
+ */
620
+ interface ProductQuery {
621
+ minPrice?: number;
622
+ maxPrice?: number;
623
+ categoryIds: string[];
624
+ collectionIds: string[];
625
+ availability?: string;
626
+ options: Array<{ key: string; value: string }>;
627
+ }
628
+
629
+ /** Which filter family a clause belongs to, for the one rule a facet count obeys. */
630
+ type FilterFamily = 'price' | 'category' | 'collection' | 'availability' | `option:${string}`;
631
+
632
+ function parseProductQuery(url: URL): ProductQuery {
633
+ const bound = (name: string): number | undefined => {
634
+ const raw = url.searchParams.get(name);
635
+ if (raw === null) return undefined;
636
+ const value = Number(raw);
637
+ return Number.isFinite(value) ? value : undefined;
638
+ };
639
+ return {
640
+ minPrice: bound('minPrice'),
641
+ maxPrice: bound('maxPrice'),
642
+ categoryIds: url.searchParams.getAll('categoryId'),
643
+ collectionIds: url.searchParams.getAll('collectionId'),
644
+ availability: url.searchParams.get('availability') ?? undefined,
645
+ options: url.searchParams.getAll('option').flatMap((token) => {
646
+ const at = token.indexOf(':');
647
+ return at <= 0 ? [] : [{ key: token.slice(0, at), value: token.slice(at + 1) }];
648
+ }),
649
+ };
650
+ }
651
+
652
+ /** Every variant of every product in this fixture is in stock (see `availabilityOf`). */
653
+ const inStock = (_row: MockProduct): boolean => true;
654
+
655
+ /** Which collections a product is in — this fixture has one, holding everything. */
656
+ const collectionsOf = (_row: MockProduct): string[] => COLLECTIONS.map((row) => row.id);
657
+
658
+ /**
659
+ * One product against the query, with one family optionally left out — which is the whole of the
660
+ * "a facet count ignores its own filter" rule the real platform applies.
661
+ */
662
+ function matchesProductQuery(
663
+ row: MockProduct,
664
+ query: ProductQuery,
665
+ ignore?: FilterFamily
666
+ ): boolean {
667
+ if (ignore !== 'price') {
668
+ if (query.minPrice !== undefined && row.maxPrice < query.minPrice) return false;
669
+ if (query.maxPrice !== undefined && row.minPrice > query.maxPrice) return false;
670
+ }
671
+ if (ignore !== 'category' && query.categoryIds.length > 0) {
672
+ // On 3.8.0 a `categoryId` matches the product's own category **or any ancestor of it** — the
673
+ // subtree match that makes a parent row a filter worth offering. On 3.7.0 it matches direct
674
+ // membership only, which is why the panel offers no parent row there at all.
675
+ const reachable = catalogContract === '3.8.0' ? categoryChainOf(row) : [row.categoryId];
676
+ if (!query.categoryIds.some((id) => reachable.includes(id))) return false;
677
+ }
678
+ if (ignore !== 'collection' && query.collectionIds.length > 0) {
679
+ if (!collectionsOf(row).some((id) => query.collectionIds.includes(id))) return false;
680
+ }
681
+ if (ignore !== 'availability' && query.availability !== undefined) {
682
+ if ((query.availability === 'in_stock') !== inStock(row)) return false;
683
+ }
684
+ for (const { key, value } of query.options) {
685
+ if (ignore === `option:${key}`) continue;
686
+ // No product in this fixture declares a variant option, so any option clause matches nothing.
687
+ if (value !== '') return false;
688
+ }
689
+ return true;
690
+ }
691
+
692
+ /**
693
+ * The `facets` object `facets=true` asks for: the scope's price bounds and its category, collection
694
+ * and availability counts, each counted with its own family's filter left out. There are no option
695
+ * axes in this fixture, so `options` is empty rather than invented.
696
+ */
697
+ function facetsOf(rows: MockProduct[], query: ProductQuery): Record<string, unknown> {
698
+ const scope = (ignore: FilterFamily): MockProduct[] =>
699
+ rows.filter((row) => matchesProductQuery(row, query, ignore));
700
+ const prices = scope('price').map((row) => row.minPrice);
701
+ const categoryScope = scope('category');
702
+ const collectionScope = scope('collection');
703
+ const availabilityScope = scope('availability');
704
+ const categoryIds = [...new Set(rows.map((row) => row.categoryId))];
705
+ return {
706
+ price: {
707
+ min: prices.length === 0 ? 0 : Math.min(...prices),
708
+ max: prices.length === 0 ? 0 : Math.max(...prices),
709
+ },
710
+ // 3.8.0: every reported category *and its ancestors*, depth-first, `parentId` present (omitted
711
+ // for a root, as the contract omits it) and each count the whole subtree's — a product counted
712
+ // once per term however many of its categories lead there. 3.7.0: the assigned categories only,
713
+ // flat, counted directly. See `MockCatalogContract`.
714
+ categories: categoryFacet(categoryIds, categoryScope),
715
+ collections: COLLECTIONS.map((collection) => ({
716
+ id: collection.id,
717
+ slug: collection.slug,
718
+ title: collection.title,
719
+ count: collectionScope.filter((row) => collectionsOf(row).includes(collection.id)).length,
720
+ })),
721
+ availability: {
722
+ in_stock: availabilityScope.filter(inStock).length,
723
+ out_of_stock: availabilityScope.filter((row) => !inStock(row)).length,
724
+ },
725
+ options: [],
726
+ };
727
+ }
728
+
729
+ /** `field:op:value` tokens, as much of the grammar as the storefront actually sends. */
730
+ /** The `categories` facet in whichever shape the active contract answers (`MockCatalogContract`). */
731
+ function categoryFacet(
732
+ assigned: readonly string[],
733
+ scope: readonly MockProduct[]
734
+ ): Array<Record<string, unknown>> {
735
+ const term = (id: string, count: number): Record<string, unknown> => {
736
+ const row = CATEGORY_BY_ID.get(id);
737
+ return {
738
+ id,
739
+ slug: row?.slug ?? id,
740
+ title: row?.title ?? id,
741
+ count,
742
+ // The contract omits the key for a root rather than sending `null`.
743
+ ...(catalogContract === '3.8.0' && row?.parentId != null ? { parentId: row.parentId } : {}),
744
+ };
745
+ };
746
+ if (catalogContract === '3.7.0') {
747
+ return assigned.map((id) => term(id, scope.filter((row) => row.categoryId === id).length));
748
+ }
749
+ // Depth-first by title over the reported set: every assigned category plus every ancestor above it.
750
+ const reported = new Set<string>();
751
+ for (const id of assigned)
752
+ for (const step of categoryChainOf({ categoryId: id })) reported.add(step);
753
+ const childrenOf = (parentId: string | null): MockCategory[] =>
754
+ CATEGORIES.filter((row) => reported.has(row.id) && row.parentId === parentId).sort((a, b) =>
755
+ a.title.localeCompare(b.title)
756
+ );
757
+ const out: Array<Record<string, unknown>> = [];
758
+ const walk = (parentId: string | null): void => {
759
+ for (const row of childrenOf(parentId)) {
760
+ // Rolled up: a product in the subtree counts once towards this term.
761
+ out.push(term(row.id, scope.filter((p) => categoryChainOf(p).includes(row.id)).length));
762
+ walk(row.id);
763
+ }
764
+ };
765
+ walk(null);
766
+ return out;
767
+ }
768
+
769
+ function matchesFilters(row: MockProduct, filters: string[]): boolean {
770
+ for (const token of filters) {
771
+ const [field, op, ...rest] = token.split(':');
772
+ const value = rest.join(':');
773
+ const actual = field === 'id' ? row.id : field === 'slug' ? row.slug : row.status;
774
+ if (op === 'eq' && actual !== value) return false;
775
+ if (op === 'in' && !value.split(',').includes(actual)) return false;
776
+ }
777
+ return true;
778
+ }
779
+
780
+ export interface MockGateway {
781
+ server: Server;
782
+ url: string;
783
+ /** `pathname + search` of every request, in order. */
784
+ requests: string[];
785
+ /** Milliseconds every `/catalog/v1/**` answer is held back. Settable between phases. */
786
+ catalogDelayMs: number;
787
+ /**
788
+ * Milliseconds every `/shopping-cart/v1/**` answer is held back. Settable between phases, and
789
+ * the reason it exists: the cart read a restored cart id triggers is issued during the
790
+ * storefront plugin's `setup` and must still be **in flight** while the page hydrates, which is
791
+ * the window any un-gated read of the cart's `pending` flag would render differently in. On a
792
+ * loopback server with no delay that window is a millisecond wide, so a spec about it would pass
793
+ * or fail by timing rather than by behaviour.
794
+ */
795
+ cartDelayMs: number;
796
+ /**
797
+ * One pathname this gateway answers with a 500 instead of its real answer, or `null` for none.
798
+ *
799
+ * A storefront's reads fail one at a time in the wild — a gateway under load answers one of them
800
+ * 500 and the rest normally — and that is a different thing from a 404: a 404 is "there is no
801
+ * such object", a 500 is "nobody could be asked". Only a failure this narrow can show what a
802
+ * build does with the difference, which is what `test/prerenderFailure.spec.ts` is about.
803
+ */
804
+ failPath: string | null;
805
+ /** Forget every request recorded so far — call between the generate and the browser run. */
806
+ reset(): void;
807
+ close(): Promise<void>;
808
+ }
809
+
810
+ export function startMockGateway(
811
+ options: { catalogContract?: MockCatalogContract; failPath?: string } = {}
812
+ ): Promise<MockGateway> {
813
+ setMockCatalogContract(options.catalogContract ?? '3.8.0');
814
+ return new Promise((resolve) => {
815
+ const requests: string[] = [];
816
+ const state = {
817
+ catalogDelayMs: 0,
818
+ cartDelayMs: 0,
819
+ failPath: options.failPath ?? null,
820
+ } as { catalogDelayMs: number; cartDelayMs: number; failPath: string | null };
821
+ const templates = routeTemplateEntries();
822
+ const pages = pageEntries();
823
+
824
+ const server = createServer((req, res) => {
825
+ void handle(req, res);
826
+ });
827
+
828
+ const handle = async (req: IncomingMessage, res: ServerResponse): Promise<void> => {
829
+ const url = new URL(req.url ?? '/', 'http://localhost');
830
+ // The browser reads this origin cross-origin; the SDK sends `X-Org-Id`, which makes every
831
+ // read a preflighted request.
832
+ res.setHeader('access-control-allow-origin', '*');
833
+ res.setHeader('access-control-allow-headers', '*');
834
+ res.setHeader('access-control-allow-methods', 'GET,POST,PATCH,DELETE,OPTIONS');
835
+ if (req.method === 'OPTIONS') {
836
+ res.statusCode = 204;
837
+ res.end();
838
+ return;
839
+ }
840
+ requests.push(url.pathname + url.search);
841
+ res.setHeader('content-type', 'application/json');
842
+ res.setHeader('cache-control', 'no-store');
843
+
844
+ const answer = (body: unknown, status = 200): void => {
845
+ const send = (): void => {
846
+ res.statusCode = status;
847
+ res.end(JSON.stringify(body));
848
+ };
849
+ const delay = url.pathname.startsWith('/catalog/v1/')
850
+ ? state.catalogDelayMs
851
+ : url.pathname.startsWith('/shopping-cart/v1/')
852
+ ? state.cartDelayMs
853
+ : 0;
854
+ if (delay > 0) {
855
+ setTimeout(send, delay);
856
+ return;
857
+ }
858
+ send();
859
+ };
860
+
861
+ // The one read this gateway has been told to fail (`MockGateway.failPath`). Before the
862
+ // org-id guard and before every route below, because the point is a failure that reaches the
863
+ // caller whatever it was asking for.
864
+ if (state.failPath !== null && url.pathname === state.failPath) {
865
+ answer({ error: 'mock gateway failure' }, 500);
866
+ return;
867
+ }
868
+
869
+ // The platform's own config is **not** org-scoped (`orgScoped: false` in the SDK), so it is
870
+ // answered before the org-id guard below — it carries no `X-Org-Id` and a real gateway does
871
+ // not ask for one. `client.checkout.url()` reads it to build the cart hand-off, which is the
872
+ // one thing a restored cart asks for beyond the cart itself; without an answer here that
873
+ // read is a 400 in the browser's console on every page with a cart in it.
874
+ if (url.pathname === '/platform/v1/config') {
875
+ answer({ checkoutUrl: 'https://checkout.example' });
876
+ return;
877
+ }
878
+
879
+ if (req.headers['x-org-id'] !== ORG_ID) {
880
+ answer({ error: 'missing org id' }, 400);
881
+ return;
882
+ }
883
+
884
+ const filters = url.searchParams.getAll('filter');
885
+ const segments = url.pathname.split('/').filter(Boolean);
886
+
887
+ if (url.pathname.startsWith('/organization/v1/')) {
888
+ // What the store sells in. `@eldrajs/theme-nuxt` reads this once per build and puts it on
889
+ // `runtimeConfig.public.eldra.commerce`, which is where every price on a generated page
890
+ // takes its currency from.
891
+ //
892
+ // **ISK, deliberately not USD.** A dollar-priced fixture would render identically whether
893
+ // the platform's answer reached the page or nothing did — the one thing the generated-site
894
+ // tests are here to tell apart. A zero-decimal currency makes it visible twice over: the
895
+ // symbol differs *and* the minor-unit scale does.
896
+ answer({
897
+ id: ORG_ID,
898
+ name: 'Northwind Goods',
899
+ features: [
900
+ { feature: 'CMS', enabled: true },
901
+ { feature: 'ECOMMERCE', enabled: true },
902
+ ],
903
+ commerce: { currency: 'ISK', taxInclusivePricing: true, defaultTaxRate: 0.24 },
904
+ locales: { default: DEFAULT_LOCALE, supported: [DEFAULT_LOCALE, PREFIXED_LOCALE] },
905
+ });
906
+ } else if (url.pathname === '/cms/v1/schema/page/entry') {
907
+ answer(listResponse(pages));
908
+ } else if (url.pathname.startsWith('/cms/v1/schema/page/entry/')) {
909
+ const id = segments[segments.length - 1];
910
+ const page = pages.find((entry) => entry.id === id);
911
+ answer(page ?? {}, page === undefined ? 404 : 200);
912
+ } else if (url.pathname === '/cms/v1/schema/route-template/entry') {
913
+ answer(listResponse(templates));
914
+ } else if (url.pathname.startsWith('/cms/v1/schema/route-template/entry/')) {
915
+ const id = segments[segments.length - 1];
916
+ const template = templates.find((entry) => entry.id === id);
917
+ answer(template ?? {}, template === undefined ? 404 : 200);
918
+ } else if (url.pathname === '/catalog/v1/categories') {
919
+ // The whole list, which is what the endpoint answers, what the storefront resolves a
920
+ // `?category=<slug>` against before it can send a `categoryId`, and the only place a
921
+ // product's ancestors exist.
922
+ answer(CATEGORIES);
923
+ } else if (url.pathname === '/catalog/v1/products/list') {
924
+ const pageSize = Number(url.searchParams.get('pageSize') ?? '100');
925
+ const query = parseProductQuery(url);
926
+ const matching = PRODUCTS.filter(
927
+ (row) => matchesFilters(row, filters) && matchesProductQuery(row, query)
928
+ );
929
+ const rows = matching.slice(0, Number.isFinite(pageSize) && pageSize > 0 ? pageSize : 100);
930
+ answer(
931
+ listResponse(rows.map(listItemOf), {
932
+ total: matching.length,
933
+ ...(url.searchParams.get('facets') === 'true'
934
+ ? { facets: facetsOf(PRODUCTS, query) }
935
+ : {}),
936
+ })
937
+ );
938
+ } else if (url.pathname === '/inventory/v1/stock/availability') {
939
+ answer(availabilityOf(await readJsonBody(req)));
940
+ } else if (segments[0] === 'shopping-cart' && segments[2] === 'cart') {
941
+ // The one cart this mock knows, and only by the id a test seeded. Any other id is a cart
942
+ // the gateway has forgotten — which the store answers by clearing `eldra.cartId` and
943
+ // carrying on with an empty cart, so a stale seed cannot silently look like a live one.
944
+ const id = decodeURIComponent(segments[3] ?? '');
945
+ answer(id === SEEDED_CART_ID ? seededCart() : {}, id === SEEDED_CART_ID ? 200 : 404);
946
+ } else if (url.pathname === '/catalog/v1/collections') {
947
+ answer(listResponse(COLLECTIONS));
948
+ } else if (
949
+ segments[0] === 'catalog' &&
950
+ segments[2] === 'collections' &&
951
+ segments[4] === 'products'
952
+ ) {
953
+ const collection = COLLECTIONS.find((row) => row.slug === decodeURIComponent(segments[3]));
954
+ if (collection === undefined) answer({}, 404);
955
+ else {
956
+ // The shopper's facets are the endpoint's own parameters, so the filtering, the `total`
957
+ // and the `facets` counts all happen here rather than in the theme.
958
+ const query = parseProductQuery(url);
959
+ const matching = PRODUCTS.filter((row) => matchesProductQuery(row, query));
960
+ answer(
961
+ listResponse(matching.map(listItemOf), {
962
+ total: matching.length,
963
+ ...(url.searchParams.get('facets') === 'true'
964
+ ? { facets: facetsOf(PRODUCTS, query) }
965
+ : {}),
966
+ })
967
+ );
968
+ }
969
+ } else if (segments[0] === 'catalog' && segments[2] === 'collections') {
970
+ const collection = COLLECTIONS.find((row) => row.slug === decodeURIComponent(segments[3]));
971
+ answer(collection ?? {}, collection === undefined ? 404 : 200);
972
+ } else if (segments[0] === 'catalog' && segments[2] === 'products') {
973
+ const row = PRODUCTS.find(
974
+ (candidate) => candidate.slug === decodeURIComponent(segments[3])
975
+ );
976
+ answer(row === undefined ? {} : detailOf(row), row === undefined ? 404 : 200);
977
+ } else {
978
+ answer({}, 404);
979
+ }
980
+ };
981
+
982
+ server.listen(0, '127.0.0.1', () => {
983
+ const address = server.address();
984
+ if (typeof address !== 'object' || address === null) return;
985
+ resolve({
986
+ server,
987
+ url: `http://127.0.0.1:${address.port}`,
988
+ requests,
989
+ get catalogDelayMs() {
990
+ return state.catalogDelayMs;
991
+ },
992
+ set catalogDelayMs(value: number) {
993
+ state.catalogDelayMs = value;
994
+ },
995
+ get cartDelayMs() {
996
+ return state.cartDelayMs;
997
+ },
998
+ set cartDelayMs(value: number) {
999
+ state.cartDelayMs = value;
1000
+ },
1001
+ get failPath() {
1002
+ return state.failPath;
1003
+ },
1004
+ set failPath(value: string | null) {
1005
+ state.failPath = value;
1006
+ },
1007
+ reset() {
1008
+ requests.length = 0;
1009
+ },
1010
+ close: () =>
1011
+ new Promise<void>((done, fail) =>
1012
+ server.close((error) => (error ? fail(error) : done()))
1013
+ ),
1014
+ });
1015
+ });
1016
+ });
1017
+ }