create-abcart-theme 0.0.0-stage → 0.10.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 (253) hide show
  1. package/CHANGELOG.md +127 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +2 -0
  4. package/README.md +64 -2
  5. package/bin/create-abcart-theme.mjs +4 -0
  6. package/package.json +47 -4
  7. package/src/args.mjs +113 -0
  8. package/src/banner.mjs +21 -0
  9. package/src/cli.mjs +119 -0
  10. package/src/create.mjs +82 -0
  11. package/src/package-manager.mjs +32 -0
  12. package/src/style.mjs +17 -0
  13. package/templates/default/.agents/skills/shopify-theme-asset-collector/SKILL.md +125 -0
  14. package/templates/default/.agents/skills/shopify-theme-asset-collector/scripts/collect_public_assets.py +370 -0
  15. package/templates/default/.agents/skills/wocart-docs/SKILL.md +146 -0
  16. package/templates/default/.agents/skills/wocart-theme-from-design/SKILL.md +58 -0
  17. package/templates/default/.agents/skills/wocart-theme-from-design/references/inputs-and-rights.md +47 -0
  18. package/templates/default/.agents/skills/wocart-theme-from-design/references/layout-rtl-and-phone.md +36 -0
  19. package/templates/default/.agents/skills/wocart-theme-from-design/references/measure-the-design.md +60 -0
  20. package/templates/default/.agents/skills/wocart-theme-from-design/references/tokens-sections-content.md +103 -0
  21. package/templates/default/.agents/skills/wocart-theme-from-design/references/verify-and-report.md +102 -0
  22. package/templates/default/.agents/skills/wocart-theme-from-design/scripts/compare-design.cjs +230 -0
  23. package/templates/default/.agents/skills/wocart-theme-from-design/scripts/qa-pages.cjs +219 -0
  24. package/templates/default/.dev.vars.example +12 -0
  25. package/templates/default/AGENTS.md +240 -0
  26. package/templates/default/README.md +184 -0
  27. package/templates/default/_gitignore +11 -0
  28. package/templates/default/astro.config.mjs +85 -0
  29. package/templates/default/package.json +36 -0
  30. package/templates/default/public/fonts/OFL.txt +96 -0
  31. package/templates/default/public/fonts/alexandria-arabic.woff2 +0 -0
  32. package/templates/default/public/fonts/fraunces-latin.woff2 +0 -0
  33. package/templates/default/src/actions/index.ts +22 -0
  34. package/templates/default/src/components/cart/AddToCartButton.astro +45 -0
  35. package/templates/default/src/components/cart/CartDrawer.astro +47 -0
  36. package/templates/default/src/components/cart/CartSummary.astro +11 -0
  37. package/templates/default/src/components/cart/FreeShipping.astro +7 -0
  38. package/templates/default/src/components/checkout/CheckoutMain.astro +29 -0
  39. package/templates/default/src/components/checkout/OrderForm.astro +280 -0
  40. package/templates/default/src/components/checkout/ThankYouMain.astro +68 -0
  41. package/templates/default/src/components/landing/LandingImages.astro +51 -0
  42. package/templates/default/src/components/landing/LandingOrder.astro +46 -0
  43. package/templates/default/src/components/landing/LandingProduct.astro +41 -0
  44. package/templates/default/src/components/listing/ListingMain.astro +93 -0
  45. package/templates/default/src/components/listing/PageMain.astro +52 -0
  46. package/templates/default/src/components/listing/Pagination.astro +31 -0
  47. package/templates/default/src/components/listing/SortControl.astro +35 -0
  48. package/templates/default/src/components/product/BuyBox.astro +96 -0
  49. package/templates/default/src/components/product/Description.astro +24 -0
  50. package/templates/default/src/components/product/Gallery.astro +66 -0
  51. package/templates/default/src/components/product/MobileBuyBar.astro +29 -0
  52. package/templates/default/src/components/product/OfferChoice.astro +66 -0
  53. package/templates/default/src/components/product/ProductMain.astro +40 -0
  54. package/templates/default/src/components/product/ProductReviews.astro +72 -0
  55. package/templates/default/src/components/product/RelatedProducts.astro +30 -0
  56. package/templates/default/src/components/product/blocks/BenefitsBlock.astro +13 -0
  57. package/templates/default/src/components/product/blocks/CollapsibleBlock.astro +20 -0
  58. package/templates/default/src/components/product/blocks/DescriptionBlock.astro +19 -0
  59. package/templates/default/src/components/product/blocks/DetailsBlock.astro +33 -0
  60. package/templates/default/src/components/product/blocks/GalleryBlock.astro +12 -0
  61. package/templates/default/src/components/product/blocks/OrderBlock.astro +30 -0
  62. package/templates/default/src/components/product/blocks/PriceBlock.astro +23 -0
  63. package/templates/default/src/components/product/blocks/RatingBlock.astro +16 -0
  64. package/templates/default/src/components/product/blocks/StockBlock.astro +22 -0
  65. package/templates/default/src/components/product/blocks/TextBlock.astro +11 -0
  66. package/templates/default/src/components/product/blocks/TitleBlock.astro +20 -0
  67. package/templates/default/src/components/reviews/ReviewCard.astro +46 -0
  68. package/templates/default/src/components/reviews/ReviewForm.astro +113 -0
  69. package/templates/default/src/components/reviews/VoiceNote.astro +60 -0
  70. package/templates/default/src/components/sections/CollectionCards.astro +65 -0
  71. package/templates/default/src/components/sections/Countdown.astro +57 -0
  72. package/templates/default/src/components/sections/Faq.astro +44 -0
  73. package/templates/default/src/components/sections/FeaturedProduct.astro +71 -0
  74. package/templates/default/src/components/sections/Hero.astro +99 -0
  75. package/templates/default/src/components/sections/ImageBanner.astro +46 -0
  76. package/templates/default/src/components/sections/ProductGrid.astro +47 -0
  77. package/templates/default/src/components/sections/RichText.astro +35 -0
  78. package/templates/default/src/components/sections/Steps.astro +46 -0
  79. package/templates/default/src/components/sections/Testimonials.astro +57 -0
  80. package/templates/default/src/components/shell/Footer.astro +80 -0
  81. package/templates/default/src/components/shell/Header.astro +89 -0
  82. package/templates/default/src/components/shell/LanguageMenu.astro +33 -0
  83. package/templates/default/src/components/shell/MobileMenu.astro +65 -0
  84. package/templates/default/src/components/shell/SearchDialog.astro +19 -0
  85. package/templates/default/src/components/shell/TopBar.astro +54 -0
  86. package/templates/default/src/components/shell/WhatsAppWidget.astro +111 -0
  87. package/templates/default/src/components/store/ContactMain.astro +79 -0
  88. package/templates/default/src/components/store/SearchMain.astro +56 -0
  89. package/templates/default/src/components/store/TrackOrderMain.astro +161 -0
  90. package/templates/default/src/components/surface/Area.astro +20 -0
  91. package/templates/default/src/components/surface/PreviewBridge.astro +24 -0
  92. package/templates/default/src/components/surface/Sections.astro +35 -0
  93. package/templates/default/src/components/ui/Breadcrumbs.astro +36 -0
  94. package/templates/default/src/components/ui/Button.astro +45 -0
  95. package/templates/default/src/components/ui/EditorPlaceholder.astro +24 -0
  96. package/templates/default/src/components/ui/Icon.astro +93 -0
  97. package/templates/default/src/components/ui/Logo.astro +36 -0
  98. package/templates/default/src/components/ui/Photo.astro +46 -0
  99. package/templates/default/src/components/ui/Price.astro +24 -0
  100. package/templates/default/src/components/ui/ProductCard.astro +41 -0
  101. package/templates/default/src/components/ui/Rating.astro +22 -0
  102. package/templates/default/src/components/ui/Section.astro +34 -0
  103. package/templates/default/src/components/ui/SectionHeading.astro +19 -0
  104. package/templates/default/src/env.d.ts +23 -0
  105. package/templates/default/src/layouts/StoreLayout.astro +145 -0
  106. package/templates/default/src/lib/browser-copy.ts +37 -0
  107. package/templates/default/src/lib/context.ts +89 -0
  108. package/templates/default/src/lib/coupon-notice.ts +47 -0
  109. package/templates/default/src/lib/i18n.ts +32 -0
  110. package/templates/default/src/lib/images.ts +38 -0
  111. package/templates/default/src/lib/listing-query.ts +41 -0
  112. package/templates/default/src/lib/money.ts +16 -0
  113. package/templates/default/src/lib/motion.ts +16 -0
  114. package/templates/default/src/lib/nav.ts +26 -0
  115. package/templates/default/src/lib/offer-tiles.ts +105 -0
  116. package/templates/default/src/lib/order-outcome.ts +66 -0
  117. package/templates/default/src/lib/otp-message.ts +21 -0
  118. package/templates/default/src/lib/products.ts +38 -0
  119. package/templates/default/src/lib/review-refusals.ts +31 -0
  120. package/templates/default/src/lib/store.ts +31 -0
  121. package/templates/default/src/lib/whatsapp.ts +29 -0
  122. package/templates/default/src/middleware.ts +23 -0
  123. package/templates/default/src/pages/404.astro +22 -0
  124. package/templates/default/src/pages/api/abandoned/convert.ts +4 -0
  125. package/templates/default/src/pages/api/abandoned/upsert.ts +4 -0
  126. package/templates/default/src/pages/api/cart/validate.ts +4 -0
  127. package/templates/default/src/pages/api/communes/[wilayaId].ts +4 -0
  128. package/templates/default/src/pages/api/otp/send.ts +4 -0
  129. package/templates/default/src/pages/api/otp/verify.ts +4 -0
  130. package/templates/default/src/pages/api/reviews/[productId].ts +3 -0
  131. package/templates/default/src/pages/api/reviews/eligibility.ts +3 -0
  132. package/templates/default/src/pages/api/reviews/submit.ts +3 -0
  133. package/templates/default/src/pages/api/reviews/upload.ts +3 -0
  134. package/templates/default/src/pages/category/[slug].astro +20 -0
  135. package/templates/default/src/pages/checkout.astro +25 -0
  136. package/templates/default/src/pages/collections/[handle].astro +20 -0
  137. package/templates/default/src/pages/contact.astro +17 -0
  138. package/templates/default/src/pages/index.astro +9 -0
  139. package/templates/default/src/pages/lp/[slug].astro +47 -0
  140. package/templates/default/src/pages/pages/[slug].astro +16 -0
  141. package/templates/default/src/pages/products/[handle].astro +37 -0
  142. package/templates/default/src/pages/products/index.astro +15 -0
  143. package/templates/default/src/pages/robots.txt.ts +9 -0
  144. package/templates/default/src/pages/search.astro +19 -0
  145. package/templates/default/src/pages/sitemap.xml.ts +12 -0
  146. package/templates/default/src/pages/thank-you.astro +33 -0
  147. package/templates/default/src/pages/track-order.astro +17 -0
  148. package/templates/default/src/pages/wocart-preview.astro +43 -0
  149. package/templates/default/src/pages/wocart-revalidate.ts +10 -0
  150. package/templates/default/src/pages/wocart-styles.css.ts +5 -0
  151. package/templates/default/src/pages/wocart-theme.json.ts +5 -0
  152. package/templates/default/src/scripts/cart.ts +371 -0
  153. package/templates/default/src/scripts/checkout/coupon.ts +96 -0
  154. package/templates/default/src/scripts/checkout/delivery.ts +86 -0
  155. package/templates/default/src/scripts/checkout/form.ts +54 -0
  156. package/templates/default/src/scripts/checkout/otp.ts +106 -0
  157. package/templates/default/src/scripts/checkout/picker.ts +169 -0
  158. package/templates/default/src/scripts/checkout/quote.ts +169 -0
  159. package/templates/default/src/scripts/checkout/submit.ts +113 -0
  160. package/templates/default/src/scripts/checkout/tracking.ts +74 -0
  161. package/templates/default/src/scripts/countdown.ts +29 -0
  162. package/templates/default/src/scripts/events.ts +4 -0
  163. package/templates/default/src/scripts/hero.ts +49 -0
  164. package/templates/default/src/scripts/listing.ts +13 -0
  165. package/templates/default/src/scripts/order-form.ts +100 -0
  166. package/templates/default/src/scripts/product.ts +306 -0
  167. package/templates/default/src/scripts/public-config.ts +79 -0
  168. package/templates/default/src/scripts/reviews.ts +358 -0
  169. package/templates/default/src/scripts/site.ts +131 -0
  170. package/templates/default/src/scripts/thank-you.ts +11 -0
  171. package/templates/default/src/scripts/voice-note.ts +94 -0
  172. package/templates/default/src/styles/base.css +1030 -0
  173. package/templates/default/src/styles/checkout.css +1111 -0
  174. package/templates/default/src/styles/global.css +12 -0
  175. package/templates/default/src/styles/product.css +871 -0
  176. package/templates/default/src/styles/reviews.css +533 -0
  177. package/templates/default/src/styles/sections.css +931 -0
  178. package/templates/default/src/styles/shell.css +970 -0
  179. package/templates/default/src/styles/tokens.css +583 -0
  180. package/templates/default/src/theme/api-routes.ts +10 -0
  181. package/templates/default/src/theme/content/catalog.ts +117 -0
  182. package/templates/default/src/theme/content/checkout.ts +168 -0
  183. package/templates/default/src/theme/content/editor.ts +21 -0
  184. package/templates/default/src/theme/content/index.ts +45 -0
  185. package/templates/default/src/theme/content/reviews.ts +76 -0
  186. package/templates/default/src/theme/content/shell.ts +59 -0
  187. package/templates/default/src/theme/content/types.ts +12 -0
  188. package/templates/default/src/theme/documents/catalog.json +11 -0
  189. package/templates/default/src/theme/documents/category.json +11 -0
  190. package/templates/default/src/theme/documents/checkout.json +11 -0
  191. package/templates/default/src/theme/documents/collection.json +11 -0
  192. package/templates/default/src/theme/documents/contact.json +11 -0
  193. package/templates/default/src/theme/documents/footer.area.json +11 -0
  194. package/templates/default/src/theme/documents/header.area.json +16 -0
  195. package/templates/default/src/theme/documents/home.json +313 -0
  196. package/templates/default/src/theme/documents/landing.json +8 -0
  197. package/templates/default/src/theme/documents/page.json +11 -0
  198. package/templates/default/src/theme/documents/product.json +125 -0
  199. package/templates/default/src/theme/documents/search.json +11 -0
  200. package/templates/default/src/theme/documents/thank-you.json +11 -0
  201. package/templates/default/src/theme/documents/track-order.json +11 -0
  202. package/templates/default/src/theme/fields.ts +61 -0
  203. package/templates/default/src/theme/key.ts +11 -0
  204. package/templates/default/src/theme/labels.ts +231 -0
  205. package/templates/default/src/theme/locales.ts +11 -0
  206. package/templates/default/src/theme/palette.ts +14 -0
  207. package/templates/default/src/theme/sections/collection-cards.ts +65 -0
  208. package/templates/default/src/theme/sections/faq.ts +74 -0
  209. package/templates/default/src/theme/sections/featured-product.ts +42 -0
  210. package/templates/default/src/theme/sections/hero.ts +47 -0
  211. package/templates/default/src/theme/sections/image-banner.ts +25 -0
  212. package/templates/default/src/theme/sections/index.ts +40 -0
  213. package/templates/default/src/theme/sections/landing.ts +150 -0
  214. package/templates/default/src/theme/sections/listing.ts +84 -0
  215. package/templates/default/src/theme/sections/product-grid.ts +42 -0
  216. package/templates/default/src/theme/sections/product.ts +297 -0
  217. package/templates/default/src/theme/sections/rich-text.ts +39 -0
  218. package/templates/default/src/theme/sections/shared.ts +54 -0
  219. package/templates/default/src/theme/sections/shell.ts +85 -0
  220. package/templates/default/src/theme/sections/store-pages.ts +101 -0
  221. package/templates/default/src/theme/sections/testimonials.ts +61 -0
  222. package/templates/default/src/theme/sections/thank-you.ts +35 -0
  223. package/templates/default/src/theme/settings.ts +124 -0
  224. package/templates/default/src/theme/theme.ts +65 -0
  225. package/templates/default/tests/fixtures/canvas-tote.json +62 -0
  226. package/templates/default/tests/fixtures/linen-shirt.json +128 -0
  227. package/templates/default/tests/unit/checkout.test.ts +241 -0
  228. package/templates/default/tests/unit/contract.test.ts +169 -0
  229. package/templates/default/tests/unit/contrast.test.ts +68 -0
  230. package/templates/default/tests/unit/copy.test.ts +101 -0
  231. package/templates/default/tests/unit/design-values.test.ts +95 -0
  232. package/templates/default/tests/unit/editability.test.ts +180 -0
  233. package/templates/default/tests/unit/fixtures.ts +91 -0
  234. package/templates/default/tests/unit/footer.test.ts +54 -0
  235. package/templates/default/tests/unit/guards.test.ts +340 -0
  236. package/templates/default/tests/unit/images.test.ts +26 -0
  237. package/templates/default/tests/unit/landing.test.ts +151 -0
  238. package/templates/default/tests/unit/languages.test.ts +42 -0
  239. package/templates/default/tests/unit/middleware.test.ts +53 -0
  240. package/templates/default/tests/unit/offer-tiles.test.ts +75 -0
  241. package/templates/default/tests/unit/render.ts +38 -0
  242. package/templates/default/tests/unit/reviews.test.ts +25 -0
  243. package/templates/default/tests/unit/rules.test.ts +59 -0
  244. package/templates/default/tests/unit/source.ts +75 -0
  245. package/templates/default/tests/unit/store-pages.test.ts +147 -0
  246. package/templates/default/tests/unit/studio.test.ts +202 -0
  247. package/templates/default/tests/unit/testimonials.test.ts +52 -0
  248. package/templates/default/tests/unit/thank-you.test.ts +52 -0
  249. package/templates/default/tests/unit/tracking.test.ts +29 -0
  250. package/templates/default/tests/unit/voice-note.test.ts +42 -0
  251. package/templates/default/tsconfig.json +13 -0
  252. package/templates/default/vitest.config.ts +15 -0
  253. package/templates/default/wrangler.jsonc +17 -0
@@ -0,0 +1,75 @@
1
+ /**
2
+ * The offer tiles the shopper chooses between: what the SDK prices, laid out
3
+ * in the order and with the flags the product page shows.
4
+ */
5
+ import { describe, expect, it } from "vitest";
6
+ import type { Offer, QuantityPricing } from "@abcart/storefront";
7
+ import { offerTiles } from "../../src/lib/offer-tiles";
8
+
9
+ const offer = (over: Partial<Offer>): Offer => ({
10
+ id: "o1",
11
+ name: "Offer",
12
+ discountType: "free",
13
+ triggerQuantity: 2,
14
+ triggerVariantId: null,
15
+ rewardQuantity: 1,
16
+ rewardProductId: "p-gift",
17
+ rewardProductName: "Bib",
18
+ rewardVariantId: null,
19
+ rewardVariantLabel: null,
20
+ rewardUnitPrice: 1200,
21
+ ...over,
22
+ });
23
+ const pricing = (tiers: QuantityPricing["tiers"], over: Partial<QuantityPricing> = {}): QuantityPricing => ({ offerId: "qp", name: "Quantity", triggerVariantId: null, tiers, ...over });
24
+
25
+ describe("offer tiles", () => {
26
+ it("are none for a product without offers: the page shows a quantity stepper", () => {
27
+ expect(offerTiles({ offers: [], quantityPricing: null }, 2400, null)).toEqual([]);
28
+ });
29
+
30
+ it("start with one piece at the catalog price, then each offer by its quantity", () => {
31
+ const tiles = offerTiles({ offers: [offer({ id: "ship", discountType: "free_shipping", triggerQuantity: 3, rewardQuantity: 0, rewardProductId: null }), offer({ id: "gift" })], quantityPricing: null }, 2400, 2900);
32
+ expect(tiles.map((tile) => [tile.kind, tile.quantity, tile.offerId])).toEqual([
33
+ ["single", 1, ""],
34
+ ["free", 2, "gift"],
35
+ ["free_shipping", 3, "ship"],
36
+ ]);
37
+ expect(tiles[0]).toMatchObject({ price: 2400, compare: 2900, saving: 0 });
38
+ });
39
+
40
+ it("price a gift offer by the SDK: the pieces paid, the gift's worth saved, the gift named", () => {
41
+ const [, gift] = offerTiles({ offers: [offer({})], quantityPricing: null }, 2400, null);
42
+ expect(gift).toMatchObject({ price: 4800, saving: 1200, freeShipping: false, reward: { quantity: 1, productName: "Bib", variantLabel: null } });
43
+ });
44
+
45
+ it("mark free delivery, which saves nothing on the pieces", () => {
46
+ const [, ship] = offerTiles({ offers: [offer({ discountType: "free_shipping", rewardQuantity: 0, rewardProductId: null })], quantityPricing: null }, 2400, null);
47
+ expect(ship).toMatchObject({ freeShipping: true, saving: 0, reward: null });
48
+ });
49
+
50
+ it("show quantity pricing as fixed-price tiles, with the price of one piece and what each saves", () => {
51
+ const tiles = offerTiles({ offers: [], quantityPricing: pricing([{ quantity: 3, price: 2100, freeShipping: true }, { quantity: 2, price: 1600, freeShipping: false }]) }, 900, null);
52
+ expect(tiles.map((tile) => [tile.kind, tile.quantity, tile.price, tile.perUnit, tile.saving, tile.fixedPrice, tile.offerId])).toEqual([
53
+ ["single", 1, 900, null, 0, false, ""],
54
+ ["tier", 2, 1600, 800, 200, true, "qp"],
55
+ ["tier", 3, 2100, 700, 600, true, "qp"],
56
+ ]);
57
+ expect(tiles[2]).toMatchObject({ freeShipping: true, compare: 2700 });
58
+ });
59
+
60
+ it("let a tier for one piece stand in for the catalog price", () => {
61
+ const tiles = offerTiles({ offers: [], quantityPricing: pricing([{ quantity: 1, price: 850, freeShipping: false }, { quantity: 2, price: 1500, freeShipping: false }]) }, 900, null);
62
+ expect(tiles.map((tile) => tile.kind)).toEqual(["tier", "tier"]);
63
+ });
64
+
65
+ it("flag one tile only, the one that saves the most money", () => {
66
+ const tiles = offerTiles({ offers: [offer({ id: "a" }), offer({ id: "b", triggerQuantity: 3, rewardQuantity: 2 })], quantityPricing: null }, 2400, null);
67
+ expect(tiles.filter((tile) => tile.best).map((tile) => tile.offerId)).toEqual(["b"]);
68
+ expect(offerTiles({ offers: [offer({ discountType: "free_shipping", rewardQuantity: 0, rewardProductId: null })], quantityPricing: null }, 2400, null).some((tile) => tile.best)).toBe(false);
69
+ });
70
+
71
+ it("keep the variant an offer is tied to, so the page shows it only for that variant", () => {
72
+ const [, tied] = offerTiles({ offers: [offer({ triggerVariantId: "v-blue" })], quantityPricing: null }, 2400, null);
73
+ expect(tied?.variantId).toBe("v-blue");
74
+ });
75
+ });
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Renders a page document through the SDK's reference renderer, the way a
3
+ * storefront page does, for a shopper or in the editor's preview. Shared by
4
+ * the contract and the editability tests.
5
+ */
6
+ import { experimental_AstroContainer as AstroContainer } from "astro/container";
7
+ import { createReadCache } from "@abcart/theme/astro";
8
+ import type { StoreClient } from "@abcart/storefront/server";
9
+ import Sections from "../../src/components/surface/Sections.astro";
10
+ import { storeContext, storeDouble } from "./fixtures";
11
+
12
+ /** The route parameters each page renders with, as its route gives them. */
13
+ export const PARAMS: Record<string, Record<string, string>> = {
14
+ product: { handle: "linen-shirt" },
15
+ collection: { surface: "collection", handle: "best-sellers" },
16
+ category: { surface: "category", slug: "clothes" },
17
+ catalog: { surface: "catalog" },
18
+ page: { slug: "terms" },
19
+ "thank-you": { orderNumber: "ORD-20261031-0007", total: "4800" },
20
+ landing: { slug: "lp-shirt", surface: "landing" },
21
+ };
22
+
23
+ export async function render(surface: string, document: unknown, options: { preview?: boolean; client?: StoreClient; locale?: string } = {}) {
24
+ const container = await AstroContainer.create();
25
+ const store = storeContext(options.locale ?? "ar", options.client ?? storeDouble());
26
+ const issues: string[] = [];
27
+ const warn = console.warn;
28
+ console.warn = (...args: unknown[]) => issues.push(args.join(" "));
29
+ try {
30
+ const html = await container.renderToString(Sections, {
31
+ props: { surface, document, params: PARAMS[surface], reads: createReadCache(), preview: options.preview ?? false },
32
+ locals: { store } as unknown as App.Locals,
33
+ });
34
+ return { html, issues };
35
+ } finally {
36
+ console.warn = warn;
37
+ }
38
+ }
@@ -0,0 +1,25 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { REVIEW_REFUSAL_CODES } from "@abcart/storefront";
3
+ import { REVIEW_FORM_COPY } from "../../src/lib/browser-copy";
4
+ import { reviewRefusalWords } from "../../src/lib/review-refusals";
5
+ import { content } from "../../src/theme/content";
6
+
7
+ describe("what a review refusal says", () => {
8
+ it("words every code the platform names, in every language, each its own way, and embeds the words in the form", () => {
9
+ const keys = REVIEW_REFUSAL_CODES.map((code) => reviewRefusalWords(code, "find"));
10
+ expect(keys).not.toContain("reviews.errorGeneric");
11
+ expect(new Set(keys).size).toBe(REVIEW_REFUSAL_CODES.length);
12
+ for (const key of keys) {
13
+ expect(REVIEW_FORM_COPY).toContain(key);
14
+ for (const locale of ["ar", "fr", "en"] as const) expect(content[locale][key], `${locale} ${key}`).toBeTruthy();
15
+ }
16
+ });
17
+
18
+ it("reads a malformed review at submit as text too short, and anything unknown or unanswered as the general sentence", () => {
19
+ expect(reviewRefusalWords("VALIDATION_FAILED", "submit")).toBe("reviews.tooShort");
20
+ expect(reviewRefusalWords("VALIDATION_FAILED", "find")).toBe("reviews.errorOrderFormat");
21
+ expect(reviewRefusalWords("A_CODE_FROM_A_NEWER_SERVER", "upload")).toBe("reviews.errorGeneric");
22
+ expect(reviewRefusalWords(null, "submit")).toBe("reviews.errorGeneric");
23
+ expect(reviewRefusalWords("hasOwnProperty", "find")).toBe("reviews.errorGeneric");
24
+ });
25
+ });
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Rules the theme keeps because a store showed them broken: a person's name
3
+ * keeps its own direction; the add-to-cart confirmation never covers the open
4
+ * drawer; a phone rule names its token `-narrow`; a row of cards fills its
5
+ * row instead of leaving empty columns beside the last card.
6
+ */
7
+ import { describe, expect, it } from "vitest";
8
+ import { code, files } from "./source";
9
+
10
+ const sheet = (path: string) => files.find((file) => file.path === path)!.text;
11
+
12
+ /** Every block that styles the selector: the base rule and each media query. */
13
+ function ruleBodies(css: string, selector: string): string {
14
+ const escaped = selector.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
15
+ const pattern = new RegExp(`(^|\\s)${escaped}\\s*\\{([^}]*)\\}`, "gm");
16
+ return [...css.matchAll(pattern)].map((match) => match[2]).join("\n");
17
+ }
18
+
19
+ describe("rules a store showed broken", () => {
20
+ it("gives every reviewer name its own direction, so a Latin name's full stop stays after it", () => {
21
+ const offenders: string[] = [];
22
+ for (const file of code.filter((item) => item.path.endsWith(".astro"))) {
23
+ file.text.split("\n").forEach((line, index) => {
24
+ if (/\{[a-zA-Z?.]*customerName\}/.test(line) && !/dir="auto"/.test(line)) offenders.push(`${file.path}:${index + 1}`);
25
+ });
26
+ }
27
+ expect(offenders).toEqual([]);
28
+ });
29
+
30
+ it("shows the add-to-cart confirmation only when no drawer opens over it", () => {
31
+ const cart = code.find((file) => file.path === "scripts/cart.ts")!.text;
32
+ expect(cart).toMatch(/if \(findDrawer\(\)\) openDrawer\(\);\s*else showToast\(tr\("cart\.added"/);
33
+ });
34
+
35
+ it("names every phone-width design token -narrow", () => {
36
+ const tokens = sheet("styles/tokens.css");
37
+ expect(tokens.match(/--[a-z0-9-]+-phone:/g) ?? []).toEqual([]);
38
+ });
39
+
40
+ it("never ends a token name in a number: a second value for a role gets a role name", () => {
41
+ const tokens = sheet("styles/tokens.css");
42
+ expect(tokens.match(/--[a-z0-9-]*-\d+:/g) ?? []).toEqual([]);
43
+ });
44
+
45
+ it("fills a row of testimonials and reviews instead of leaving empty columns beside it", () => {
46
+ expect(ruleBodies(sheet("styles/sections.css"), ".testimonials")).toMatch(/repeat\(auto-fit,/);
47
+ expect(ruleBodies(sheet("styles/reviews.css"), ".reviews-grid")).toMatch(/repeat\(auto-fit,/);
48
+ });
49
+ });
50
+
51
+ describe("the phone gallery", () => {
52
+ it("shows its thumbnails on a phone, beside or under the photo, and hides only its arrows", () => {
53
+ const sheet = files.find((file) => file.path === "styles/product.css")!.text;
54
+ const phone = /@media \(max-width: 899px\) \{([\s\S]*?)\n\}\n/.exec(sheet)?.[1] ?? "";
55
+ expect(phone).not.toMatch(/\.gallery__thumbs[^{]*\{\s*display: none/);
56
+ expect(phone).toMatch(/\.gallery--side \.gallery__thumbs/);
57
+ expect(phone).toMatch(/\.gallery--below \.gallery__thumbs/);
58
+ });
59
+ });
@@ -0,0 +1,75 @@
1
+ /**
2
+ * The theme's shipped source under `src/` (tests and build output left out),
3
+ * read once: the one walker every guard and the copy checks agree on.
4
+ */
5
+ import { readFileSync, readdirSync } from "node:fs";
6
+ import { join, relative, resolve, sep } from "node:path";
7
+
8
+ export const ROOT = resolve(__dirname, "../..");
9
+ const SRC = join(ROOT, "src");
10
+
11
+ export interface SourceFile {
12
+ /** The path under `src/`, with forward slashes. */
13
+ path: string;
14
+ text: string;
15
+ }
16
+
17
+ function walk(dir: string, out: string[] = []): string[] {
18
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
19
+ const full = join(dir, entry.name);
20
+ if (entry.isDirectory()) {
21
+ if (!["node_modules", "dist", "__tests__"].includes(entry.name)) walk(full, out);
22
+ } else if (/\.(ts|astro|css|json)$/.test(entry.name) && !entry.name.includes(".test.")) {
23
+ out.push(full);
24
+ }
25
+ }
26
+ return out;
27
+ }
28
+
29
+ export const files: SourceFile[] = walk(SRC).map((full) => ({ path: relative(SRC, full).split(sep).join("/"), text: readFileSync(full, "utf8") }));
30
+ export const code = files.filter((file) => /\.(ts|astro)$/.test(file.path));
31
+
32
+ /** What a shopper's browser downloads: the scripts, and the `<script>` blocks Astro bundles. */
33
+ const browserSources = (): SourceFile[] => {
34
+ const out: SourceFile[] = [];
35
+ for (const file of code) {
36
+ if (file.path.startsWith("scripts/")) out.push(file);
37
+ if (file.path.endsWith(".astro")) {
38
+ for (const [, attributes, body] of file.text.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/g)) {
39
+ if (!/\bis:inline\b|type="application\/json"/.test(attributes ?? "")) out.push({ path: `${file.path} <script>`, text: body ?? "" });
40
+ }
41
+ }
42
+ }
43
+ return out;
44
+ };
45
+
46
+ /** Runtime imports only: `import type` and `type` names left out. */
47
+ export function runtimeImports(text: string): { from: string; names: string[] }[] {
48
+ return [...text.matchAll(/import\s+(type\s+)?(?:\{([^}]*)\}|\*\s+as\s+\w+|\w+)?\s*(?:,\s*\{([^}]*)\})?\s*(?:from\s*)?["']([^"']+)["']/g)]
49
+ .filter((match) => !match[1])
50
+ .map((match) => ({
51
+ from: match[4] ?? "",
52
+ names: `${match[2] ?? ""},${match[3] ?? ""}`.split(",").map((name) => name.trim()).filter((name) => name && !name.startsWith("type ")),
53
+ }));
54
+ }
55
+
56
+ /** Every module a browser source pulls in, followed through the theme's own `@/` imports. */
57
+ export function browserModuleGraph(): Map<string, SourceFile> {
58
+ const byPath = new Map(code.map((file) => [file.path, file]));
59
+ const resolveLocal = (from: string) => {
60
+ const base = from.replace(/^@\//, "");
61
+ return [base, `${base}.ts`, `${base}/index.ts`].find((candidate) => byPath.has(candidate));
62
+ };
63
+ const seen = new Map<string, SourceFile>();
64
+ const queue = browserSources();
65
+ while (queue.length > 0) {
66
+ const file = queue.shift()!;
67
+ if (seen.has(file.path)) continue;
68
+ seen.set(file.path, file);
69
+ for (const { from } of runtimeImports(file.text)) {
70
+ const local = from.startsWith("@/") ? resolveLocal(from) : undefined;
71
+ if (local) queue.push(byPath.get(local)!);
72
+ }
73
+ }
74
+ return seen;
75
+ }
@@ -0,0 +1,147 @@
1
+ /**
2
+ * The store's own pages — contact, search, order tracking, checkout — are
3
+ * surfaces the merchant edits like any other. Contact shows only what the
4
+ * store has: its WhatsApp from the App, its phone, email and address from its
5
+ * own details, the merchant's hours and note in the page's language. Every
6
+ * WhatsApp link carries the page's message, in the theme's words until the
7
+ * merchant writes theirs.
8
+ */
9
+ import { describe, expect, it } from "vitest";
10
+ import { experimental_AstroContainer as AstroContainer } from "astro/container";
11
+ import { createReadCache } from "@abcart/theme/astro";
12
+ import { schemeClass } from "@abcart/theme";
13
+ import type { StoreConfig, StoreWhatsAppWidget } from "@abcart/storefront";
14
+ import Sections from "../../src/components/surface/Sections.astro";
15
+ import { content } from "../../src/theme/content";
16
+ import { landingPage, storeContext, storeDouble } from "./fixtures";
17
+
18
+ const WIDGET: StoreWhatsAppWidget = {
19
+ href: "https://wa.me/213551234567",
20
+ agentName: null,
21
+ caption: null,
22
+ avatarUrl: null,
23
+ welcomeMessage: null,
24
+ launcherLabel: null,
25
+ ctaLabel: null,
26
+ prefillGeneral: null,
27
+ prefillProduct: null,
28
+ thankYouButtonLabel: null,
29
+ prefillThankYou: null,
30
+ accent: "whatsapp",
31
+ position: "right",
32
+ attention: false,
33
+ surfaces: { home: true, catalog: true, product: true, pages: true, thankYou: true, checkout: true, landing: true },
34
+ };
35
+
36
+ async function render(surface: string, options: { locale?: string; document?: unknown; params?: Record<string, string>; config?: Partial<StoreConfig>; search?: (text: string) => unknown } = {}) {
37
+ const client = storeDouble();
38
+ const searched: string[] = [];
39
+ (client.products as unknown as { search: unknown }).search = async (text: string) => {
40
+ searched.push(text);
41
+ return options.search?.(text) ?? { items: [], hasNext: false, total: 0 };
42
+ };
43
+ const container = await AstroContainer.create();
44
+ const html = await container.renderToString(Sections, {
45
+ props: { surface, document: options.document ?? null, params: { surface, ...options.params }, reads: createReadCache() },
46
+ locals: { store: storeContext(options.locale ?? "fr", client, options.config) } as unknown as App.Locals,
47
+ request: new Request(`https://boutique.test/${options.locale ?? "fr"}/${surface}`),
48
+ });
49
+ return { html, searched };
50
+ }
51
+
52
+ const contact = (props: Record<string, unknown>) => ({ version: 1, surface: "contact", sections: [{ id: "contact-main", type: "contact-main", props }] });
53
+ const hrefs = (html: string) => [...html.matchAll(/href="([^"]*)"/g)].map((match) => match[1]!.replaceAll("&amp;", "&"));
54
+
55
+ describe("the contact page", () => {
56
+ it("shows each way to reach the store it has, from the store's own details", async () => {
57
+ const { html } = await render("contact", { config: { whatsapp: WIDGET, contact: { phone: "0551 23 45 67", email: "bonjour@boutique.dz", address: "Bab Ezzouar, Alger" } } });
58
+ const whatsapp = hrefs(html).find((href) => href.startsWith(WIDGET.href))!;
59
+ expect(new URL(whatsapp).searchParams.get("text")).toBe(content.fr["whatsapp.general"]);
60
+ expect(hrefs(html)).toEqual(expect.arrayContaining(["tel:0551234567", "mailto:bonjour@boutique.dz"]));
61
+ expect(html).toContain("Bab Ezzouar, Alger");
62
+ expect(html).not.toContain('class="contact-none"');
63
+ });
64
+
65
+ it("claims no hours the merchant did not write, and says when the store set no way at all", async () => {
66
+ const { html } = await render("contact");
67
+ expect(html).not.toContain(content.fr["contact.hoursTitle"]);
68
+ expect(html).toContain('class="contact-none"');
69
+ });
70
+
71
+ it("shows the merchant's hours and note in the page's language", async () => {
72
+ const { html } = await render("contact", { document: contact({ hours: { ar: "من السبت إلى الخميس", fr: "Du samedi au jeudi, 9 h – 18 h" }, note: { fr: "Fermé les jours fériés." } }) });
73
+ expect(html).toContain(content.fr["contact.hoursTitle"]);
74
+ expect(html).toContain("Du samedi au jeudi, 9 h – 18 h");
75
+ expect(html).toContain("Fermé les jours fériés.");
76
+ expect(html).not.toContain("من السبت");
77
+ });
78
+
79
+ it("lists the store's pages beneath, unless the merchant hides them", async () => {
80
+ expect(hrefs((await render("contact")).html)).toContain("/fr/pages/terms");
81
+ expect(hrefs((await render("contact", { document: contact({ showPages: false }) })).html)).not.toContain("/fr/pages/terms");
82
+ });
83
+ });
84
+
85
+ describe("the search page", () => {
86
+ it("lists what the platform finds for the shopper's words, and asks nothing for none", async () => {
87
+ const found = await render("search", { params: { q: " bodies " } });
88
+ expect(found.searched).toEqual(["bodies"]);
89
+ expect(found.html).toContain('action="/fr/search"');
90
+ const none = await render("search");
91
+ expect(none.searched).toEqual([]);
92
+ expect(none.html).toContain(content.fr["search.hint"]);
93
+ });
94
+ });
95
+
96
+ describe("the order-tracking and checkout pages", () => {
97
+ it("ask for the order's number and phone, with the merchant's title", async () => {
98
+ const { html } = await render("track-order", { document: { version: 1, surface: "track-order", sections: [{ id: "track-order-main", type: "track-order-main", props: { title: { fr: "Où est ma commande ?" } } }] } });
99
+ expect(html).toContain("Où est ma commande ?");
100
+ expect(html).toContain('name="orderNumber"');
101
+ expect(html).toContain('name="phone"');
102
+ });
103
+
104
+ it("place the basket's order form under the merchant's title", async () => {
105
+ const { html } = await render("checkout", { document: { version: 1, surface: "checkout", sections: [{ id: "checkout-main", type: "checkout-main", props: { title: { fr: "Finaliser" } } }] } });
106
+ expect(html).toContain("Finaliser");
107
+ expect(html).toContain("<form");
108
+ });
109
+ });
110
+
111
+ describe("every WhatsApp link", () => {
112
+ it("starts the chat on the page's subject, in the merchant's words when they wrote some", async () => {
113
+ const container = await AstroContainer.create();
114
+ const { default: StoreLayout } = await import("../../src/layouts/StoreLayout.astro");
115
+ const store = storeContext("fr", storeDouble(), { whatsapp: { ...WIDGET, prefillProduct: "Bonjour, {product} ?" } });
116
+ const html = await container.renderToString(StoreLayout, {
117
+ props: { whatsappProduct: landingPage.product!.name },
118
+ locals: { store } as unknown as App.Locals,
119
+ request: new Request("https://boutique.test/fr/products/shirt"),
120
+ });
121
+ const launcher = /<a class="wa__cta" href="([^"]+)"/.exec(html)![1]!.replaceAll("&amp;", "&");
122
+ expect(new URL(launcher).searchParams.get("text")).toBe(`Bonjour, ${landingPage.product!.name} ?`);
123
+ // A link elsewhere on the page is about the store, not the product.
124
+ const footer = hrefs(html).filter((href) => href.startsWith(WIDGET.href) && href !== launcher);
125
+ expect(footer.length).toBeGreaterThan(0);
126
+ for (const href of footer) expect(new URL(href).searchParams.get("text")).toBe(content.fr["whatsapp.general"]);
127
+ });
128
+ });
129
+
130
+ describe("the page's colors", () => {
131
+ async function bodyOf(themeSettings: Record<string, unknown>) {
132
+ const container = await AstroContainer.create();
133
+ const { default: StoreLayout } = await import("../../src/layouts/StoreLayout.astro");
134
+ const html = await container.renderToString(StoreLayout, {
135
+ locals: { store: storeContext("ar", storeDouble(), { themeSettings }) } as unknown as App.Locals,
136
+ request: new Request("https://boutique.test/"),
137
+ });
138
+ return /<body class="([^"]*)"/.exec(html)![1]!;
139
+ }
140
+
141
+ it("wear the scheme the merchant picks for the page, the light one until they do", async () => {
142
+ expect(await bodyOf({})).toContain(schemeClass("light"));
143
+ const dark = await bodyOf({ pageScheme: "dark" });
144
+ expect(dark).toContain(schemeClass("dark"));
145
+ expect(dark).not.toContain(schemeClass("light"));
146
+ });
147
+ });
@@ -0,0 +1,202 @@
1
+ /**
2
+ * What Wocart Studio needs from this theme, checked with real Ed25519 keys
3
+ * the way Studio signs them: the manifest it reads, the preview it frames and
4
+ * the revalidation a publish sends. A token for another store, another theme
5
+ * or the other use is refused; a deployment without the key answers 404.
6
+ */
7
+ import { readFileSync, readdirSync } from "node:fs";
8
+ import { join, relative, resolve, sep } from "node:path";
9
+ import { beforeAll, describe, expect, it, vi } from "vitest";
10
+ import type { APIContext, MiddlewareNext } from "astro";
11
+ import { experimental_AstroContainer as AstroContainer } from "astro/container";
12
+ import { THEME_KEY, THEME_VERSION } from "../../src/theme/key";
13
+ import { storeContext, testConfig } from "./fixtures";
14
+
15
+ const env = vi.hoisted(() => ({ WOCART_PREVIEW_KEY: undefined as string | undefined }));
16
+ vi.mock("astro:env/server", () => ({
17
+ COD_SERVER_URL: "http://localhost:8787",
18
+ STORE_API_KEY: "test-key",
19
+ get WOCART_PREVIEW_KEY() {
20
+ return env.WOCART_PREVIEW_KEY;
21
+ },
22
+ }));
23
+
24
+ const revalidate = await import("../../src/pages/wocart-revalidate");
25
+ const manifestRoute = await import("../../src/pages/wocart-theme.json");
26
+ const { onRequest } = await import("../../src/middleware");
27
+ const { default: PreviewPage } = await import("../../src/pages/wocart-preview.astro");
28
+
29
+ const STORE = "https://boutique.test";
30
+ const EDITOR = "https://studio.example.test";
31
+ let privateKey: CryptoKey;
32
+
33
+ const b64url = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
34
+ const encodeJson = (value: unknown) => b64url(new TextEncoder().encode(JSON.stringify(value)));
35
+ async function sign(payload: Record<string, unknown>) {
36
+ const head = encodeJson({ alg: "EdDSA", typ: "JWT" });
37
+ const body = encodeJson(payload);
38
+ const signature = new Uint8Array(await crypto.subtle.sign({ name: "Ed25519" }, privateKey, new TextEncoder().encode(`${head}.${body}`)));
39
+ return `${head}.${body}.${b64url(signature)}`;
40
+ }
41
+ const now = () => Math.floor(Date.now() / 1000);
42
+ const previewPass = (over: Record<string, unknown> = {}) => ({ aud: STORE, theme: THEME_KEY, editor: EDITOR, iat: now(), exp: now() + 600, ...over });
43
+ const revalidation = (over: Record<string, unknown> = {}) => ({ aud: STORE, theme: THEME_KEY, use: "revalidate", iat: now(), exp: now() + 120, ...over });
44
+
45
+ async function withoutKey<T>(run: () => Promise<T>): Promise<T> {
46
+ const key = env.WOCART_PREVIEW_KEY;
47
+ env.WOCART_PREVIEW_KEY = undefined;
48
+ try {
49
+ return await run();
50
+ } finally {
51
+ env.WOCART_PREVIEW_KEY = key;
52
+ }
53
+ }
54
+
55
+ async function publish(authorization?: string) {
56
+ const invalidate = vi.fn(async () => {});
57
+ const request = new Request(`${STORE}/wocart-revalidate`, { method: "POST", headers: authorization ? { Authorization: authorization } : {} });
58
+ const response = await revalidate.POST({ request, cache: { invalidate } } as unknown as APIContext);
59
+ return { response, invalidate };
60
+ }
61
+
62
+ /** How Studio frames a preview: `GET /wocart-preview?token=…&surface=…`. */
63
+ const previewRequest = (token?: string) => new Request(`${STORE}/wocart-preview?surface=home${token ? `&token=${token}` : ""}`);
64
+
65
+ /** The preview as the theme's middleware opens it, against a store that answers its config. */
66
+ async function openPreview(token?: string) {
67
+ const fetchSpy = vi.spyOn(globalThis, "fetch").mockImplementation(async () => Response.json({ data: testConfig("ar") }));
68
+ try {
69
+ const request = previewRequest(token);
70
+ const locals: Partial<App.Locals> = {};
71
+ const next = vi.fn(async () => new Response("page"));
72
+ const context = { isPrerendered: false, url: new URL(request.url), request, locals, redirect: () => new Response(null, { status: 302 }) };
73
+ const response = await onRequest(context as unknown as APIContext, next as unknown as MiddlewareNext);
74
+ return { response: response as Response, next, preview: locals.preview };
75
+ } finally {
76
+ fetchSpy.mockRestore();
77
+ }
78
+ }
79
+
80
+ beforeAll(async () => {
81
+ const pair = (await crypto.subtle.generateKey({ name: "Ed25519" }, true, ["sign", "verify"])) as CryptoKeyPair;
82
+ privateKey = pair.privateKey;
83
+ env.WOCART_PREVIEW_KEY = JSON.stringify(await crypto.subtle.exportKey("jwk", pair.publicKey));
84
+ });
85
+
86
+ describe("the manifest Studio reads", () => {
87
+ it("names this theme and version, and is built once, at build time", async () => {
88
+ const response = (manifestRoute.GET as () => Response)();
89
+ const manifest = await response.json();
90
+ expect(manifest).toMatchObject({ key: THEME_KEY, version: THEME_VERSION, preview: true });
91
+ expect(manifestRoute.prerender).toBe(true);
92
+ });
93
+
94
+ it("carries the version package.json carries, so a release names one thing", () => {
95
+ const pkg = JSON.parse(readFileSync(resolve(__dirname, "../../package.json"), "utf8"));
96
+ expect(THEME_VERSION).toBe(pkg.version);
97
+ });
98
+ });
99
+
100
+ describe("the preview Studio frames", () => {
101
+ it("opens for a pass Studio signed for this store and theme", async () => {
102
+ const { next, preview } = await openPreview(await sign(previewPass()));
103
+ expect(next).toHaveBeenCalledWith();
104
+ expect(preview?.claims.editor).toBe(EDITOR);
105
+ expect(preview?.draft.surface).toBe("home");
106
+ });
107
+
108
+ it("refuses a pass for another theme, a revalidation token, or none", async () => {
109
+ for (const token of [await sign(previewPass({ theme: "another-theme" })), await sign(revalidation()), undefined]) {
110
+ const { response, next, preview } = await openPreview(token);
111
+ expect(response.status).toBeGreaterThanOrEqual(400);
112
+ expect(next).not.toHaveBeenCalled();
113
+ expect(preview).toBeUndefined();
114
+ }
115
+ });
116
+
117
+ it("renders the draft with every section marked and the editor's bridge, never cached", async () => {
118
+ const token = await sign(previewPass());
119
+ const { preview } = await openPreview(token);
120
+ if (!preview) throw new Error("the pass was refused");
121
+ const container = await AstroContainer.create();
122
+ const response = await container.renderToResponse(PreviewPage, {
123
+ request: previewRequest(token),
124
+ locals: { store: storeContext("ar"), preview } as unknown as App.Locals,
125
+ });
126
+ const html = await response.text();
127
+ expect(response.status).toBe(200);
128
+ expect(response.headers.get("Cache-Control")).toMatch(/no-store/);
129
+ expect(html.match(/<!--wocart:start id=/g)?.length ?? 0).toBeGreaterThan(3);
130
+ expect(html).toContain(EDITOR);
131
+ });
132
+
133
+ it("is a 404 on a deployment without the key", async () => {
134
+ const { response, preview } = await withoutKey(async () => openPreview(await sign(previewPass())));
135
+ expect(response.status).toBe(404);
136
+ expect(preview).toBeUndefined();
137
+ });
138
+ });
139
+
140
+ describe("the revalidation a publish sends", () => {
141
+ it("drops every cached page for the platform's revalidation token", async () => {
142
+ const { response, invalidate } = await publish(`Bearer ${await sign(revalidation())}`);
143
+ expect(response.status).toBe(204);
144
+ expect(response.headers.get("Cache-Control")).toBe("no-store");
145
+ expect(invalidate).toHaveBeenCalledWith({ tags: ["pages"] });
146
+ });
147
+
148
+ it("drops nothing for a preview pass, another store's or theme's token, or none", async () => {
149
+ for (const token of [await sign(previewPass()), await sign(revalidation({ aud: "https://other.test" })), await sign(revalidation({ theme: "another-theme" }))]) {
150
+ const { response, invalidate } = await publish(`Bearer ${token}`);
151
+ expect(response.status).toBe(403);
152
+ expect(invalidate).not.toHaveBeenCalled();
153
+ }
154
+ const { response, invalidate } = await publish();
155
+ expect(response.status).toBe(401);
156
+ expect(invalidate).not.toHaveBeenCalled();
157
+ });
158
+
159
+ it("is a 404 on a deployment without the key", async () => {
160
+ const { response, invalidate } = await withoutKey(async () => publish(`Bearer ${await sign(revalidation())}`));
161
+ expect(response.status).toBe(404);
162
+ expect(invalidate).not.toHaveBeenCalled();
163
+ });
164
+
165
+ it("answers only POST, and is never prerendered", async () => {
166
+ const response = (revalidate.ALL as () => Response)();
167
+ expect(response.status).toBe(405);
168
+ expect(revalidate.prerender).toBe(false);
169
+ });
170
+
171
+ it("reaches every cached page: each page route rule carries the SDK's pages tag, never its spelling", () => {
172
+ const config = readFileSync(resolve(__dirname, "../../astro.config.mjs"), "utf8");
173
+ const rules = config.slice(config.indexOf("routeRules: {"), config.indexOf("\n },", config.indexOf("routeRules: {")));
174
+ const routes = [...rules.matchAll(/"([^"]+)":\s*\{[^}]*tags:\s*\[([^\]]*)\]/g)].map((match) => ({ route: match[1]!, tags: match[2]! }));
175
+ expect(routes.length).toBeGreaterThan(5);
176
+ expect(routes.filter((rule) => !rule.route.startsWith("/api/") && !rule.tags.includes("PAGES_CACHE_TAG")).map((rule) => rule.route)).toEqual([]);
177
+ expect(rules).not.toContain('"pages"');
178
+ expect(config).toMatch(/import \{ PAGES_CACHE_TAG \} from "@wocart\/storefront\/server";/);
179
+ });
180
+ });
181
+
182
+ describe("what a publish reaches", () => {
183
+ /** Routes a shopper's own request decides — a search, a basket, an order — and the contact page the siblings leave uncached too. */
184
+ const UNCACHED = ["/search", "/checkout", "/thank-you", "/track-order", "/contact"];
185
+ const config = readFileSync(resolve(__dirname, "../../astro.config.mjs"), "utf8");
186
+ const rules = new Map([...config.matchAll(/"(\/[^"]*)":\s*\{[^}]*tags:\s*\[([^\]]*)\]/g)].map((match) => [match[1]!, match[2]!]));
187
+ const pagesDir = resolve(__dirname, "../../src/pages");
188
+ const walk = (dir: string): string[] => readdirSync(dir, { withFileTypes: true }).flatMap((entry) => (entry.isDirectory() ? walk(join(dir, entry.name)) : [join(dir, entry.name)]));
189
+ /** Every route that renders a composed surface, as routeRules names it. */
190
+ const composed = walk(pagesDir)
191
+ .filter((file) => file.endsWith(".astro") && !file.endsWith("wocart-preview.astro") && readFileSync(file, "utf8").includes("<Sections"))
192
+ .map((file) => `/${relative(pagesDir, file).split(sep).join("/").replace(/\.astro$/, "").replace(/(^|\/)index$/, "")}`);
193
+
194
+ it("finds the composed routes, so the check means something", () => {
195
+ expect(composed.length).toBeGreaterThanOrEqual(12);
196
+ });
197
+
198
+ it("caches every composed route under the pages tag, unless a shopper's own request decides the page", () => {
199
+ expect(composed.filter((route) => !UNCACHED.includes(route) && !rules.get(route)?.includes("PAGES_CACHE_TAG"))).toEqual([]);
200
+ expect(UNCACHED.filter((route) => !composed.includes(route) || rules.has(route))).toEqual([]);
201
+ });
202
+ });