@tanqory/theme-kit 0.1.0 → 2.0.0-alpha.17

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 (210) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +125 -10
  3. package/dist/abi/canvas-live.d.ts +67 -0
  4. package/dist/abi/canvas-live.js +154 -0
  5. package/dist/abi/cart.d.ts +59 -0
  6. package/dist/abi/cart.js +387 -0
  7. package/dist/abi/convert.d.ts +344 -0
  8. package/dist/abi/convert.js +1278 -0
  9. package/dist/abi/data-api.d.ts +15 -0
  10. package/dist/abi/data-api.js +209 -0
  11. package/dist/abi/jcs.d.ts +6 -0
  12. package/dist/abi/jcs.js +28 -0
  13. package/dist/abi/labels.d.ts +3 -0
  14. package/dist/abi/labels.js +34 -0
  15. package/dist/abi/page-data.d.ts +256 -0
  16. package/dist/abi/page-data.js +678 -0
  17. package/dist/abi/page.d.ts +28 -0
  18. package/dist/abi/page.js +57 -0
  19. package/dist/abi/referrals.d.ts +23 -0
  20. package/dist/abi/referrals.js +89 -0
  21. package/dist/abi/rewards.d.ts +27 -0
  22. package/dist/abi/rewards.js +82 -0
  23. package/dist/abi/seo.d.ts +47 -0
  24. package/dist/abi/seo.js +68 -0
  25. package/dist/abi/shell.d.ts +23 -0
  26. package/dist/abi/shell.js +10 -0
  27. package/dist/abi/state-pack.d.ts +17 -0
  28. package/dist/abi/state-pack.js +43 -0
  29. package/dist/abi/wire.d.ts +38 -0
  30. package/dist/abi/wire.js +84 -0
  31. package/dist/build.d.ts +116 -0
  32. package/dist/build.js +310 -0
  33. package/dist/client.d.ts +19 -0
  34. package/dist/client.js +87 -0
  35. package/dist/contract.d.ts +6 -0
  36. package/dist/contract.js +6 -0
  37. package/dist/headless/ai.d.ts +132 -0
  38. package/dist/headless/ai.js +99 -0
  39. package/dist/headless/hooks.d.ts +276 -0
  40. package/dist/headless/hooks.js +540 -0
  41. package/dist/headless/i18n.d.ts +13 -0
  42. package/dist/headless/i18n.js +45 -0
  43. package/dist/headless/index.d.ts +37 -0
  44. package/dist/headless/index.js +38 -0
  45. package/dist/headless/money.d.ts +25 -0
  46. package/dist/headless/money.js +61 -0
  47. package/dist/headless/page.d.ts +43 -0
  48. package/dist/headless/page.js +53 -0
  49. package/dist/headless/platform.d.ts +55 -0
  50. package/dist/headless/platform.js +77 -0
  51. package/dist/headless/primitives/cart.d.ts +90 -0
  52. package/dist/headless/primitives/cart.js +153 -0
  53. package/dist/headless/primitives/collection.d.ts +68 -0
  54. package/dist/headless/primitives/collection.js +80 -0
  55. package/dist/headless/primitives/product.d.ts +101 -0
  56. package/dist/headless/primitives/product.js +117 -0
  57. package/dist/headless/primitives/storefront.d.ts +106 -0
  58. package/dist/headless/primitives/storefront.js +186 -0
  59. package/dist/headless/primitives/util.d.ts +19 -0
  60. package/dist/headless/primitives/util.js +42 -0
  61. package/dist/headless/strings.d.ts +9 -0
  62. package/dist/headless/strings.js +190 -0
  63. package/dist/headless/structured-data.d.ts +31 -0
  64. package/dist/headless/structured-data.js +57 -0
  65. package/dist/headless/theme.d.ts +99 -0
  66. package/dist/headless/theme.js +54 -0
  67. package/dist/index.d.ts +20 -0
  68. package/dist/index.js +18 -553
  69. package/dist/runtime/data/StoreProvider.d.ts +84 -0
  70. package/dist/runtime/data/StoreProvider.js +373 -0
  71. package/dist/runtime/data/handle.d.ts +14 -0
  72. package/dist/runtime/data/handle.js +16 -0
  73. package/dist/runtime/data/routes.d.ts +87 -0
  74. package/dist/runtime/data/routes.js +158 -0
  75. package/dist/runtime/data/to-ui.d.ts +281 -0
  76. package/dist/runtime/data/to-ui.js +977 -0
  77. package/dist/runtime/entries/register.d.ts +9 -0
  78. package/dist/runtime/entries/register.js +9 -0
  79. package/dist/runtime/entries/sections.d.ts +16 -0
  80. package/dist/runtime/entries/sections.js +19 -0
  81. package/dist/{types → runtime/kit}/SectionTree.d.ts +2 -1
  82. package/dist/runtime/kit/SectionTree.js +100 -0
  83. package/dist/runtime/kit/analytics.d.ts +63 -0
  84. package/dist/runtime/kit/analytics.js +250 -0
  85. package/dist/runtime/kit/cart.d.ts +215 -0
  86. package/dist/runtime/kit/cart.js +545 -0
  87. package/dist/{types → runtime/kit}/composition.d.ts +1 -1
  88. package/dist/runtime/kit/composition.js +3 -0
  89. package/dist/{types → runtime/kit}/config.d.ts +2 -2
  90. package/dist/runtime/kit/config.js +6 -0
  91. package/dist/runtime/kit/consent.d.ts +29 -0
  92. package/dist/runtime/kit/consent.js +159 -0
  93. package/dist/runtime/kit/contract/content.d.ts +199 -0
  94. package/dist/runtime/kit/contract/content.js +106 -0
  95. package/dist/runtime/kit/contract/field-types.d.ts +337 -0
  96. package/dist/runtime/kit/contract/field-types.js +206 -0
  97. package/dist/runtime/kit/contract/groups.d.ts +230 -0
  98. package/dist/runtime/kit/contract/groups.js +402 -0
  99. package/dist/runtime/kit/contract/index.d.ts +33 -0
  100. package/dist/runtime/kit/contract/index.js +33 -0
  101. package/dist/runtime/kit/contract/transform.d.ts +82 -0
  102. package/dist/runtime/kit/contract/transform.js +133 -0
  103. package/dist/runtime/kit/contract/validate.d.ts +75 -0
  104. package/dist/runtime/kit/contract/validate.js +480 -0
  105. package/dist/runtime/kit/data.d.ts +720 -0
  106. package/dist/runtime/kit/data.js +1117 -0
  107. package/dist/{types → runtime/kit}/defineSection.d.ts +1 -1
  108. package/dist/runtime/kit/defineSection.js +10 -0
  109. package/dist/{types → runtime/kit}/dynamic-source.d.ts +40 -18
  110. package/dist/runtime/kit/dynamic-source.js +294 -0
  111. package/dist/runtime/kit/index.d.ts +24 -0
  112. package/dist/runtime/kit/index.js +24 -0
  113. package/dist/{types → runtime/kit}/jsx-to-json.d.ts +1 -1
  114. package/dist/runtime/kit/jsx-to-json.js +28 -0
  115. package/dist/{types → runtime/kit}/mount.d.ts +25 -4
  116. package/dist/runtime/kit/mount.js +124 -0
  117. package/dist/{types → runtime/kit}/registry.d.ts +1 -1
  118. package/dist/runtime/kit/registry.js +12 -0
  119. package/dist/{types → runtime/kit}/ssg.d.ts +9 -3
  120. package/dist/runtime/kit/ssg.js +56 -0
  121. package/dist/runtime/kit/storefront.d.ts +639 -0
  122. package/dist/runtime/kit/storefront.js +723 -0
  123. package/dist/{types → runtime/kit}/theme-context.d.ts +8 -2
  124. package/dist/runtime/kit/theme-context.js +25 -0
  125. package/dist/runtime/kit/types.d.ts +147 -0
  126. package/dist/runtime/kit/types.js +1 -0
  127. package/dist/runtime/platform/TrackingPixels.d.ts +14 -0
  128. package/dist/runtime/platform/TrackingPixels.js +63 -0
  129. package/dist/runtime/platform/environment.d.ts +68 -0
  130. package/dist/runtime/platform/environment.js +85 -0
  131. package/dist/runtime/platform/locale.d.ts +27 -0
  132. package/dist/runtime/platform/locale.js +42 -0
  133. package/dist/runtime/platform/route-analytics.d.ts +15 -0
  134. package/dist/runtime/platform/route-analytics.js +72 -0
  135. package/dist/runtime/platform/safe-href.d.ts +25 -0
  136. package/dist/runtime/platform/safe-href.js +69 -0
  137. package/dist/runtime/platform/safe-values.d.ts +37 -0
  138. package/dist/runtime/platform/safe-values.js +140 -0
  139. package/dist/runtime/render/SectionRenderer.d.ts +4 -0
  140. package/dist/runtime/render/SectionRenderer.js +166 -0
  141. package/dist/runtime/render/listing-query.d.ts +52 -0
  142. package/dist/runtime/render/listing-query.js +122 -0
  143. package/dist/runtime/render/localized-copy.d.ts +86 -0
  144. package/dist/runtime/render/localized-copy.js +129 -0
  145. package/dist/runtime/render/product-listing.d.ts +11 -0
  146. package/dist/runtime/render/product-listing.js +243 -0
  147. package/dist/runtime/render/section-actions.d.ts +66 -0
  148. package/dist/runtime/render/section-actions.js +202 -0
  149. package/dist/runtime/render/starter.d.ts +11 -0
  150. package/dist/runtime/render/starter.js +81 -0
  151. package/dist/runtime/seo/head.d.ts +115 -0
  152. package/dist/runtime/seo/head.js +281 -0
  153. package/dist/runtime/seo/structured-data.d.ts +83 -0
  154. package/dist/runtime/seo/structured-data.js +252 -0
  155. package/dist/runtime/shell/PageShell.d.ts +18 -0
  156. package/dist/runtime/shell/PageShell.js +113 -0
  157. package/dist/runtime/shell/RuntimeBridge.d.ts +14 -0
  158. package/dist/runtime/shell/RuntimeBridge.js +93 -0
  159. package/dist/runtime/shell/overlay-state.d.ts +31 -0
  160. package/dist/runtime/shell/overlay-state.js +59 -0
  161. package/dist/runtime/shell/preview-mode.d.ts +2 -0
  162. package/dist/runtime/shell/preview-mode.js +11 -0
  163. package/dist/runtime/shell/spa-router.d.ts +14 -0
  164. package/dist/runtime/shell/spa-router.js +76 -0
  165. package/dist/runtime/shell/url-redirects.d.ts +6 -0
  166. package/dist/runtime/shell/url-redirects.js +37 -0
  167. package/dist/runtime/slots.d.ts +74 -0
  168. package/dist/runtime/slots.js +16 -0
  169. package/dist/runtime.d.ts +34 -0
  170. package/dist/runtime.js +40 -0
  171. package/dist/sdk/app-block.d.ts +29 -0
  172. package/dist/sdk/app-block.js +22 -0
  173. package/dist/sdk/index.d.ts +26 -0
  174. package/dist/sdk/index.js +26 -0
  175. package/dist/sdk/referrals.d.ts +62 -0
  176. package/dist/sdk/referrals.js +20 -0
  177. package/dist/sdk/rewards.d.ts +85 -0
  178. package/dist/sdk/rewards.js +29 -0
  179. package/dist/sdk/runtime-context.d.ts +202 -0
  180. package/dist/sdk/runtime-context.js +73 -0
  181. package/dist/sdk/schema.d.ts +206 -0
  182. package/dist/sdk/schema.js +121 -0
  183. package/dist/sdk/server-render.d.ts +8 -0
  184. package/dist/sdk/server-render.js +12 -0
  185. package/dist/sdk/store-lookup.d.ts +27 -0
  186. package/dist/sdk/store-lookup.js +29 -0
  187. package/dist/sdk/store.d.ts +149 -0
  188. package/dist/sdk/store.js +5 -0
  189. package/dist/sdk/sx.d.ts +40 -0
  190. package/dist/sdk/sx.js +112 -0
  191. package/dist/sdk/theme.d.ts +191 -0
  192. package/dist/sdk/theme.js +10 -0
  193. package/dist/sdk/types.d.ts +757 -0
  194. package/dist/sdk/types.js +7 -0
  195. package/dist/server.d.ts +111 -0
  196. package/dist/server.js +533 -0
  197. package/docs/headless-api.md +220 -0
  198. package/package.json +76 -22
  199. package/dist/index.js.map +0 -1
  200. package/dist/ssg-BZ5FYTw7.js +0 -1802
  201. package/dist/ssg-BZ5FYTw7.js.map +0 -1
  202. package/dist/ssg.js +0 -8
  203. package/dist/ssg.js.map +0 -1
  204. package/dist/types/cart.d.ts +0 -86
  205. package/dist/types/data.d.ts +0 -357
  206. package/dist/types/editor.d.ts +0 -5
  207. package/dist/types/index.d.ts +0 -20
  208. package/dist/types/preview-bridge.d.ts +0 -9
  209. package/dist/types/storefront.d.ts +0 -333
  210. package/dist/types/types.d.ts +0 -44
@@ -0,0 +1,1117 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { createContext, useContext } from 'react';
3
+ import { createStorefrontMethods, BOOTSTRAP_SHOP_MENU, BOOTSTRAP_SHOP_MENU_FRAGMENTS, readBootstrapShopMenu, } from './storefront.js';
4
+ /** Build a `recommendations` object from a product list (parity with the commerce standard
5
+ * `recommendations` legacy templating object, whose `.products` our API returns directly). */
6
+ export function toRecommendations(products, intent = 'related') {
7
+ return { products, productsCount: products.length, intent, performed: true };
8
+ }
9
+ const DataContext = createContext(null);
10
+ /**
11
+ * Handles are Unicode now (a Thai title no longer collapses to "4" or ""), and
12
+ * a theme reads the handle out of `location.pathname`, which hands it back
13
+ * PERCENT-ENCODED — "เสื้อยืด" arrives as "%E0%B9%80…". Our indexes are keyed by
14
+ * the real handle, so an exact lookup misses and the theme quietly renders a
15
+ * fallback: nova's PDP showed a different product's data, and computeHead fell
16
+ * back to the shop name, so every non-Latin product lost its SEO title.
17
+ *
18
+ * Fixing the themes is not enough — a marketplace theme ships its own copy of
19
+ * the code and cannot be force-updated. Normalizing here reaches every theme,
20
+ * old and new, on the next rebuild (theme-kit is part of the runtime's dist
21
+ * fingerprint). A handle can't contain `%`, so this is a no-op for one that is
22
+ * already decoded; malformed input falls back to the raw string.
23
+ */
24
+ function decodeHandle(handle) {
25
+ if (!handle || !handle.includes('%'))
26
+ return handle;
27
+ try {
28
+ return decodeURIComponent(handle);
29
+ }
30
+ catch {
31
+ return handle;
32
+ }
33
+ }
34
+ /** Wraps the app with a theme-provided data source (mock or live). */
35
+ export function DataProvider({ value, children }) {
36
+ return _jsx(DataContext.Provider, { value: value, children: children });
37
+ }
38
+ export function useData() {
39
+ const ctx = useContext(DataContext);
40
+ if (!ctx)
41
+ throw new Error('useData must be used within <DataProvider>');
42
+ return ctx;
43
+ }
44
+ /** Build an offline data source from fixture collections (theme passes its JSON). */
45
+ export function createMockData(input) {
46
+ const fixture = Array.isArray(input) ? { collections: input } : input;
47
+ const collections = fixture.collections ?? [];
48
+ // Flatten products from every collection once; subsequent lookups are O(1)
49
+ // by handle. A product appearing in multiple collections returns the first
50
+ // occurrence — matching the storefront's "canonical product page" semantics.
51
+ //
52
+ // Exception: the SAME product arrives in two shapes. Collection/top listings
53
+ // come from the card fragment, which carries no `seo`; the current route's
54
+ // product is fetched with `seo { title description keywords }` and appended
55
+ // afterwards. First-wins therefore indexed the seo-less card and dropped the
56
+ // detail copy, so computeHead() found no seo.title and fell back to
57
+ // "<product> — <shop>", emitting no description at all. Let the record that
58
+ // actually has SEO win, whatever order it arrives in.
59
+ const productsByHandle = new Map();
60
+ const allProducts = [];
61
+ for (const c of collections) {
62
+ for (const p of c.products) {
63
+ const prev = productsByHandle.get(p.handle);
64
+ if (!prev) {
65
+ productsByHandle.set(p.handle, p);
66
+ allProducts.push(p);
67
+ }
68
+ else if (!prev.seo && p.seo) {
69
+ productsByHandle.set(p.handle, p);
70
+ const i = allProducts.indexOf(prev);
71
+ if (i !== -1)
72
+ allProducts[i] = p;
73
+ }
74
+ }
75
+ }
76
+ // ── Offline fixtures so EVERY commerce-standard object resolves in mock mode ──
77
+ // The live source (createLiveData) serves these from the Storefront GraphQL
78
+ // API; mock mode must mirror the same shapes so a developer can build header
79
+ // menus, blog, search, customer + shop sections fully offline (no store).
80
+ const mkItem = (id, title, url, type = 'HTTP') => ({ id, title, url, type, items: [] });
81
+ const mkMenu = (handle, title, items) => ({ id: `mock/menu/${handle}`, handle, title, items });
82
+ const mainMenu = mkMenu('main-menu', 'Main menu', [
83
+ { ...mkItem('mm-shop', 'Shop', '/collections/all', 'COLLECTIONS'),
84
+ // submenu: the store's collections, so the header dropdown is real data
85
+ items: collections.slice(0, 6).map((c, i) => mkItem(`mm-shop-${i}`, c.title, `/collections/${c.handle}`, 'COLLECTION')) },
86
+ mkItem('mm-collections', 'Collections', '/collections', 'CATALOG'),
87
+ mkItem('mm-about', 'About', '/pages/about', 'PAGE'),
88
+ mkItem('mm-journal', 'Journal', '/blogs/news', 'BLOG'),
89
+ ]);
90
+ const menus = new Map([
91
+ ['main-menu', mainMenu],
92
+ ['footer', mkMenu('footer', 'Footer', [
93
+ mkItem('fm-privacy', 'Privacy policy', '/policies/privacy-policy', 'SHOP_POLICY'),
94
+ mkItem('fm-contact', 'Contact', '/pages/contact', 'PAGE'),
95
+ ])],
96
+ ['footer-shop', mkMenu('footer-shop', 'Shop', [
97
+ mkItem('fs-all', 'All products', '/collections/all'),
98
+ mkItem('fs-new', 'New arrivals', '/collections/new'),
99
+ mkItem('fs-sale', 'Sale', '/collections/sale'),
100
+ mkItem('fs-gift', 'Gift cards', '/products/gift-card'),
101
+ ])],
102
+ ['footer-help', mkMenu('footer-help', 'Help', [
103
+ mkItem('fh-contact', 'Contact', '/pages/contact'),
104
+ mkItem('fh-ship', 'Shipping', '/pages/shipping'),
105
+ mkItem('fh-returns', 'Returns', '/pages/returns'),
106
+ mkItem('fh-faq', 'FAQ', '/pages/faq'),
107
+ ])],
108
+ ['footer-company', mkMenu('footer-company', 'Company', [
109
+ mkItem('fc-about', 'About', '/pages/about'),
110
+ mkItem('fc-journal', 'Journal', '/blogs/news'),
111
+ mkItem('fc-sustain', 'Sustainability', '/pages/sustainability'),
112
+ mkItem('fc-press', 'Press', '/pages/press'),
113
+ ])],
114
+ ]);
115
+ for (const m of fixture.menus ?? [])
116
+ menus.set(m.handle, m);
117
+ const sampleArticles = [
118
+ {
119
+ id: 'mock/article/welcome',
120
+ handle: 'welcome',
121
+ title: 'Welcome to the shop',
122
+ excerpt: 'A quick hello and what to expect.',
123
+ contentHtml: '<p>Welcome — this is mock article content for local development.</p>',
124
+ image: null,
125
+ author: 'Studio',
126
+ publishedAt: '2024-01-01T00:00:00.000Z',
127
+ tags: ['news'],
128
+ blogHandle: 'news',
129
+ },
130
+ {
131
+ id: 'mock/article/behind-the-design',
132
+ handle: 'behind-the-design',
133
+ title: 'Behind the design',
134
+ excerpt: 'How this starter theme is built.',
135
+ contentHtml: '<p>Built with Tanqory theme-kit sections.</p>',
136
+ image: null,
137
+ author: 'Studio',
138
+ publishedAt: '2024-01-02T00:00:00.000Z',
139
+ tags: ['design'],
140
+ blogHandle: 'news',
141
+ },
142
+ ];
143
+ const blogs = fixture.blogs?.length
144
+ ? fixture.blogs.map((bl) => ({ ...bl, articles: bl.articles.map((a) => ({ ...a, blogHandle: a.blogHandle ?? bl.handle })) }))
145
+ : [{ id: 'mock/blog/news', handle: 'news', title: 'News', articles: sampleArticles }];
146
+ const articles = blogs.flatMap((bl) => bl.articles);
147
+ const blogFor = (handle) => blogs.find((bl) => bl.handle === handle || bl.handle === decodeHandle(handle)) ?? null;
148
+ const pages = fixture.pages ?? [];
149
+ const pageFor = (handle) => pages.find((pg) => pg.handle === handle || pg.handle === decodeHandle(handle)) ?? null;
150
+ const sampleShop = {
151
+ name: 'nova',
152
+ description: 'A clean starter storefront powered by Tanqory.',
153
+ brand: { logo: null, slogan: 'Modern essentials', shortDescription: 'Starter theme' },
154
+ policies: {
155
+ privacy: { handle: 'privacy-policy', title: 'Privacy policy', url: '/policies/privacy-policy', body: '<p>Mock privacy policy.</p>' },
156
+ refund: { handle: 'refund-policy', title: 'Refund policy', url: '/policies/refund-policy', body: '<p>Mock refund policy.</p>' },
157
+ termsOfService: { handle: 'terms-of-service', title: 'Terms of service', url: '/policies/terms-of-service', body: '<p>Mock terms of service.</p>' },
158
+ shipping: { handle: 'shipping-policy', title: 'Shipping policy', url: '/policies/shipping-policy', body: '<p>Mock shipping policy.</p>' },
159
+ subscription: null,
160
+ },
161
+ cookieBanner: { enabled: true, dataSharingTitle: 'Do not sell or share my personal information', dataSharingVisible: true },
162
+ };
163
+ const shop = fixture.shop
164
+ ? {
165
+ ...sampleShop,
166
+ ...fixture.shop,
167
+ brand: { ...sampleShop.brand, ...(fixture.shop.brand ?? {}) },
168
+ policies: { ...sampleShop.policies, ...(fixture.shop.policies ?? {}) },
169
+ }
170
+ : sampleShop;
171
+ const EMPTY_PI = { hasNextPage: false, hasPreviousPage: false, startCursor: null, endCursor: null };
172
+ const match = (q) => {
173
+ const needle = q.trim().toLowerCase();
174
+ return needle ? allProducts.filter((p) => p.title.toLowerCase().includes(needle)) : [];
175
+ };
176
+ return {
177
+ collectionByHandle: (handle) => collections.find((c) => c.handle === handle || c.handle === decodeHandle(handle)) ?? null,
178
+ allCollections: () => collections,
179
+ productByHandle: (handle) => productsByHandle.get(handle) ?? productsByHandle.get(decodeHandle(handle)) ?? null,
180
+ pageByHandle: (handle) => pageFor(handle),
181
+ // Localization mirrors what the store DASHBOARD (Markets) would publish —
182
+ // NOT a theme config list. Countries carry their currency; languages are the
183
+ // store's published locales. The live source fills this from store-api.
184
+ localization: fixture.localization ?? {
185
+ country: { isoCode: 'TH', name: 'Thailand', currency: { isoCode: 'THB', symbol: '฿' }, market: null },
186
+ availableCountries: [
187
+ { isoCode: 'TH', name: 'Thailand', currency: { isoCode: 'THB', symbol: '฿' }, market: null },
188
+ { isoCode: 'US', name: 'United States', currency: { isoCode: 'USD', symbol: '$' }, market: null },
189
+ { isoCode: 'JP', name: 'Japan', currency: { isoCode: 'JPY', symbol: '¥' }, market: null },
190
+ { isoCode: 'SG', name: 'Singapore', currency: { isoCode: 'SGD', symbol: 'S$' }, market: null },
191
+ { isoCode: 'GB', name: 'United Kingdom', currency: { isoCode: 'GBP', symbol: '£' }, market: null },
192
+ ],
193
+ language: { isoCode: 'en', name: 'English' },
194
+ availableLanguages: [
195
+ { isoCode: 'en', name: 'English' },
196
+ { isoCode: 'th', name: 'ไทย' },
197
+ { isoCode: 'ja', name: '日本語' },
198
+ ],
199
+ },
200
+ // ── commerce-standard extensions, served offline from the fixtures above so
201
+ // themes built against `useData()` behave the same in mock + live. ──
202
+ shop,
203
+ menu: (handle) => menus.get(handle) ?? menus.get(decodeHandle(handle)) ?? null,
204
+ fetchMenu: async (handle) => menus.get(handle) ?? menus.get(decodeHandle(handle)) ?? null,
205
+ notifyBackInStock: async () => 'subscribed',
206
+ listMenus: async () => Array.from(menus.values()).map((m) => ({
207
+ handle: m.handle,
208
+ title: m.title,
209
+ itemsCount: m.items.length,
210
+ })),
211
+ pixels: async () => [],
212
+ locations: async () => fixture.locations ?? [],
213
+ search: async (query, opts) => {
214
+ const types = opts?.types ?? ['PRODUCT', 'PAGE', 'ARTICLE'];
215
+ const products = types.includes('PRODUCT') ? match(query) : [];
216
+ const arts = types.includes('ARTICLE')
217
+ ? articles.filter((a) => a.title.toLowerCase().includes(query.trim().toLowerCase()))
218
+ : [];
219
+ const needle = query.trim().toLowerCase();
220
+ const pgs = types.includes('PAGE') && needle ? pages.filter((pg) => pg.title.toLowerCase().includes(needle)) : [];
221
+ return { totalCount: products.length + arts.length + pgs.length, products, pages: pgs, articles: arts, filters: [], pageInfo: EMPTY_PI };
222
+ },
223
+ predictiveSearch: async (query, opts) => {
224
+ const products = match(query).slice(0, opts?.limit ?? 4);
225
+ return {
226
+ queries: products.slice(0, 3).map((p) => p.title),
227
+ products,
228
+ collections: collections
229
+ .filter((c) => c.title.toLowerCase().includes(query.trim().toLowerCase()))
230
+ .slice(0, 3)
231
+ .map((c) => ({ handle: c.handle, title: c.title, image: null })),
232
+ pages: [],
233
+ articles: [],
234
+ };
235
+ },
236
+ collectionProducts: async (handle, opts) => {
237
+ const c = collections.find((x) => x.handle === handle);
238
+ const list = c?.products ?? [];
239
+ // Real cursor paging over the fixture, so "Load more" and numbered pages
240
+ // behave offline as they do live. The cursor is the offset.
241
+ const start = Math.max(0, Number(opts?.after ?? 0) || 0);
242
+ const end = start + (opts?.first ?? 24);
243
+ return {
244
+ products: list.slice(start, end),
245
+ filters: [],
246
+ pageInfo: {
247
+ hasNextPage: end < list.length,
248
+ hasPreviousPage: start > 0,
249
+ startCursor: String(start),
250
+ endCursor: String(Math.min(end, list.length)),
251
+ },
252
+ };
253
+ },
254
+ productRecommendations: async (productId) => {
255
+ const base = allProducts.find((p) => p.id === productId);
256
+ const picked = (base && fixture.recommendations?.[base.handle]) ?? [];
257
+ const listed = picked.flatMap((h) => productsByHandle.get(h) ?? []);
258
+ return listed.length ? listed : allProducts.filter((p) => p.id !== productId).slice(0, 4);
259
+ },
260
+ blogByHandle: async (handle) => blogFor(handle),
261
+ articleByHandle: async (blogHandle, articleHandle) => blogFor(blogHandle)?.articles.find((a) => a.handle === articleHandle || a.handle === decodeHandle(articleHandle)) ?? null,
262
+ metaobject: async () => null,
263
+ metaobjects: async () => [],
264
+ customer: {
265
+ login: async () => ({ token: null, expiresAt: null, errors: ['Customer accounts need live data (mock mode).'] }),
266
+ logout: async () => { },
267
+ renew: async () => ({ token: null, expiresAt: null, errors: ['Customer accounts need live data (mock mode).'] }),
268
+ register: async () => ({ ok: false, errors: ['Customer accounts need live data (mock mode).'] }),
269
+ get: async () => null,
270
+ orders: async () => [],
271
+ paymentMethods: async () => [],
272
+ orderByLookup: async () => null,
273
+ createAddress: async () => ({ ok: false, errors: ['mock mode'] }),
274
+ updateAddress: async () => ({ ok: false, errors: ['mock mode'] }),
275
+ deleteAddress: async () => ({ ok: false, errors: ['mock mode'] }),
276
+ setDefaultAddress: async () => ({ ok: false, errors: ['mock mode'] }),
277
+ },
278
+ };
279
+ }
280
+ // Bootstrap fetches BOTH collections AND a flat product list. The flat list
281
+ // powers a synthesized "featured" virtual collection when the store has live
282
+ // products but the merchant hasn't built a real collection yet — without it,
283
+ // a brand-new merchant's first Active product would never appear on the
284
+ // storefront (collections-only bootstrap = empty homepage).
285
+ // Shared product-card selection for every grid/list. Scalars + featuredImage +
286
+ // price + compareAtPrice (sale badge) + facets (vendor/type/tags) — all cheap
287
+ // (cost 0–1). Heavy fields (gallery, variants, metafields, sellingPlans,
288
+ // storeAvailability) stay on the PDP query only.
289
+ const PRODUCT_CARD_FIELDS = /* GraphQL */ `
290
+ fragment ProductCardBoot on Product {
291
+ id
292
+ handle
293
+ title
294
+ availableForSale
295
+ vendor
296
+ productType
297
+ tags
298
+ publishedAt
299
+ createdAt
300
+ onlineStoreUrl
301
+ featuredImage { url altText width height }
302
+ priceRange { minVariantPrice { amount currencyCode } maxVariantPrice { amount currencyCode } }
303
+ compareAtPriceRange { minVariantPrice { amount currencyCode } maxVariantPrice { amount currencyCode } }
304
+ firstAvailableVariant { id }
305
+ templateSuffix
306
+ }
307
+ `;
308
+ const COLLECTIONS_QUERY = /* GraphQL */ `
309
+ ${BOOTSTRAP_SHOP_MENU_FRAGMENTS}
310
+ ${PRODUCT_CARD_FIELDS}
311
+ query NovaBootstrap($first: Int!, $productFirst: Int!, $productsTop: Int!, $pageHandle: String, $productHandle: String, $collectionHandle: String, $policyBodies: Boolean = false) {
312
+ ${BOOTSTRAP_SHOP_MENU}
313
+ policyBodies: shop @include(if: $policyBodies) {
314
+ privacyPolicy { handle body }
315
+ refundPolicy { handle body }
316
+ termsOfService { handle body }
317
+ shippingPolicy { handle body }
318
+ subscriptionPolicy { handle body }
319
+ }
320
+ page(handle: $pageHandle) {
321
+ handle
322
+ title
323
+ body
324
+ bodySummary
325
+ author
326
+ publishedAt
327
+ updatedAt
328
+ templateSuffix
329
+ seo { title description keywords }
330
+ }
331
+ product(handle: $productHandle) { ...ProductCardBoot description seo { title description keywords } }
332
+ collection(handle: $collectionHandle) {
333
+ id
334
+ handle
335
+ title
336
+ description
337
+ image { url altText width height }
338
+ productsCount { count }
339
+ templateSuffix
340
+ seo { title description keywords }
341
+ }
342
+ collections(first: $first) {
343
+ edges {
344
+ node {
345
+ id
346
+ handle
347
+ title
348
+ image { url altText width height }
349
+ productsCount { count }
350
+ templateSuffix
351
+ products(first: $productFirst) {
352
+ edges {
353
+ node { ...ProductCardBoot }
354
+ }
355
+ }
356
+ }
357
+ }
358
+ }
359
+ products(first: $productsTop) {
360
+ edges {
361
+ node { ...ProductCardBoot }
362
+ }
363
+ }
364
+ localization {
365
+ country {
366
+ isoCode
367
+ name
368
+ currency { isoCode name symbol }
369
+ market { id handle name }
370
+ }
371
+ availableCountries {
372
+ isoCode
373
+ name
374
+ currency { isoCode name symbol }
375
+ market { id handle name }
376
+ }
377
+ language { isoCode name }
378
+ availableLanguages { isoCode name }
379
+ }
380
+ }
381
+ `;
382
+ // Reduced bootstrap. `localization` and the nested `collections.products` are
383
+ // non-nullable in the storefront schema, so if a cell errors on either (e.g. an
384
+ // older / partially-broken store-api) GraphQL nulls the ENTIRE response and the
385
+ // whole boot falls back to mock. This variant drops both optional pieces so the
386
+ // essentials — shop, menus, page, collections, top products — still load.
387
+ const SAFE_COLLECTIONS_QUERY = /* GraphQL */ `
388
+ ${BOOTSTRAP_SHOP_MENU_FRAGMENTS}
389
+ ${PRODUCT_CARD_FIELDS}
390
+ query NovaBootstrapSafe($first: Int!, $productsTop: Int!, $pageHandle: String, $productHandle: String, $collectionHandle: String, $policyBodies: Boolean = false) {
391
+ ${BOOTSTRAP_SHOP_MENU}
392
+ policyBodies: shop @include(if: $policyBodies) {
393
+ privacyPolicy { handle body }
394
+ refundPolicy { handle body }
395
+ termsOfService { handle body }
396
+ shippingPolicy { handle body }
397
+ subscriptionPolicy { handle body }
398
+ }
399
+ page(handle: $pageHandle) {
400
+ handle
401
+ title
402
+ body
403
+ bodySummary
404
+ author
405
+ publishedAt
406
+ updatedAt
407
+ templateSuffix
408
+ seo { title description keywords }
409
+ }
410
+ product(handle: $productHandle) { ...ProductCardBoot description seo { title description keywords } }
411
+ collection(handle: $collectionHandle) {
412
+ id
413
+ handle
414
+ title
415
+ description
416
+ image { url altText width height }
417
+ productsCount { count }
418
+ templateSuffix
419
+ seo { title description keywords }
420
+ }
421
+ collections(first: $first) {
422
+ edges {
423
+ node {
424
+ id
425
+ handle
426
+ title
427
+ image { url altText width height }
428
+ productsCount { count }
429
+ templateSuffix
430
+ }
431
+ }
432
+ }
433
+ products(first: $productsTop) {
434
+ edges {
435
+ node { ...ProductCardBoot }
436
+ }
437
+ }
438
+ }
439
+ `;
440
+ function normalizeImage(img) {
441
+ if (!img || !img.url)
442
+ return null;
443
+ const width = img.width ?? null;
444
+ const height = img.height ?? null;
445
+ return {
446
+ url: img.url,
447
+ ...(img.altText ? { altText: img.altText } : {}),
448
+ ...(width != null ? { width } : {}),
449
+ ...(height != null ? { height } : {}),
450
+ ...(width && height ? { aspectRatio: width / height } : {}),
451
+ };
452
+ }
453
+ function normalizeProduct(p) {
454
+ const price = p.priceRange?.minVariantPrice ?? { amount: '0', currencyCode: 'USD' };
455
+ // Only surface compareAtPrice when it's a REAL sale (was > now) — the backend
456
+ // returns the range even when equal, which would render a pointless strikethrough.
457
+ // The card pairs it with the LOWEST price, so it takes the lowest "was" too:
458
+ // the highest one (the dearest size's) turned a 22% sale into a "-49%" badge.
459
+ const compareAt = p.compareAtPriceRange?.minVariantPrice ?? p.compareAtPriceRange?.maxVariantPrice;
460
+ const onSale = compareAt && Number(compareAt.amount) > Number(price.amount);
461
+ return {
462
+ id: p.id,
463
+ handle: p.handle,
464
+ title: p.title,
465
+ price,
466
+ ...(p.priceRange?.maxVariantPrice && Number(p.priceRange.maxVariantPrice.amount) > Number(price.amount) ? { priceMax: p.priceRange.maxVariantPrice } : {}),
467
+ featuredImage: normalizeImage(p.featuredImage),
468
+ ...(onSale ? { compareAtPrice: compareAt } : {}),
469
+ ...(p.vendor ? { vendor: p.vendor } : {}),
470
+ ...(p.productType ? { productType: p.productType } : {}),
471
+ ...(p.tags?.length ? { tags: p.tags } : {}),
472
+ ...(p.publishedAt ? { publishedAt: p.publishedAt } : {}),
473
+ ...(p.createdAt ? { createdAt: p.createdAt } : {}),
474
+ ...(p.onlineStoreUrl ? { onlineStoreUrl: p.onlineStoreUrl } : {}),
475
+ ...(p.firstAvailableVariant?.id ? { variantId: p.firstAvailableVariant.id } : {}),
476
+ ...(typeof p.availableForSale === 'boolean' ? { availableForSale: p.availableForSale } : {}),
477
+ ...(p.templateSuffix ? { templateSuffix: p.templateSuffix } : {}),
478
+ ...(p.seo ? { seo: { title: p.seo.title ?? null, description: p.seo.description ?? null, keywords: p.seo.keywords ?? [] } } : {}),
479
+ // The route's own product carries its plain description (bootstrap) — the meta description fallback.
480
+ ...(p.description ? { description: p.description } : {}),
481
+ };
482
+ }
483
+ function normalizeCollection(c) {
484
+ return {
485
+ ...(c.id ? { id: c.id } : {}),
486
+ handle: c.handle,
487
+ title: c.title,
488
+ ...(c.description ? { description: c.description } : {}),
489
+ image: normalizeImage(c.image),
490
+ ...(typeof c.productsCount?.count === 'number'
491
+ ? { productsCount: c.productsCount.count }
492
+ : {}),
493
+ // Nested products are optional — the reduced bootstrap (used when a cell
494
+ // errors on the nested products field) omits them.
495
+ ...(c.templateSuffix ? { templateSuffix: c.templateSuffix } : {}),
496
+ ...(c.seo ? { seo: { title: c.seo.title ?? null, description: c.seo.description ?? null, keywords: c.seo.keywords ?? [] } } : {}),
497
+ products: (c.products?.edges ?? []).map((e) => normalizeProduct(e.node)),
498
+ };
499
+ }
500
+ // Single-product fetch (PDP) — full options + variants for the variant picker.
501
+ // Kept out of the bootstrap (variants(first:100) @cost=100/product would blow
502
+ // the cost budget) and fetched lazily only on the product page.
503
+ const PRODUCT_QUERY = /* GraphQL */ `
504
+ query NovaProduct($handle: String!, $identifiers: [MetafieldIdentifier!]!) {
505
+ product(handle: $handle) {
506
+ id
507
+ handle
508
+ title
509
+ description
510
+ descriptionHtml
511
+ vendor
512
+ productType
513
+ tags
514
+ availableForSale
515
+ isGiftCard
516
+ totalInventory
517
+ featuredImage { url altText width height }
518
+ images(first: 20) { nodes { url altText width height } }
519
+ media(first: 20) {
520
+ nodes {
521
+ __typename
522
+ ... on MediaImage { id alt image { url altText width height } }
523
+ ... on Video { id alt previewImage { url altText width height } sources { url mimeType format } }
524
+ ... on Model3d { id alt previewImage { url altText width height } sources { url mimeType format } }
525
+ ... on ExternalVideo { id alt host embedUrl previewImage { url altText width height } }
526
+ }
527
+ }
528
+ priceRange { minVariantPrice { amount currencyCode } maxVariantPrice { amount currencyCode } }
529
+ compareAtPriceRange { minVariantPrice { amount currencyCode } maxVariantPrice { amount currencyCode } }
530
+ options(first: 10) { name values }
531
+ collections(first: 10) { nodes { handle title } }
532
+ seo { title description keywords }
533
+ templateSuffix
534
+ variants(first: 50) {
535
+ nodes {
536
+ id
537
+ title
538
+ availableForSale
539
+ sku
540
+ barcode
541
+ inventoryQuantity
542
+ inventoryPolicy
543
+ requiresShipping
544
+ taxable
545
+ weight { value unit }
546
+ price { amount currencyCode }
547
+ compareAtPrice { amount currencyCode }
548
+ image { url altText width height }
549
+ selectedOptions { name value }
550
+ unitPrice { amount currencyCode }
551
+ unitPriceMeasurement { measuredType quantityValue quantityUnit referenceValue referenceUnit }
552
+ quantityRule { minimum maximum increment }
553
+ storeAvailability(first: 5) {
554
+ nodes { available quantityAvailable pickUpTime location { id name } }
555
+ }
556
+ }
557
+ }
558
+ sellingPlanGroups(first: 5) {
559
+ nodes {
560
+ name
561
+ appName
562
+ options { name values }
563
+ sellingPlans(first: 10) {
564
+ nodes { id name description recurringDeliveries options { name value } }
565
+ }
566
+ }
567
+ }
568
+ metafields(identifiers: $identifiers) { namespace key value }
569
+ firstAvailableVariant { id }
570
+ }
571
+ }
572
+ `;
573
+ function normalizeProductDetail(p) {
574
+ const base = normalizeProduct(p);
575
+ const variants = (p.variants?.nodes ?? []).map((v) => ({
576
+ id: v.id,
577
+ title: v.title,
578
+ price: v.price ?? base.price,
579
+ ...(v.compareAtPrice && Number(v.compareAtPrice.amount) > Number((v.price ?? base.price).amount)
580
+ ? { compareAtPrice: v.compareAtPrice }
581
+ : {}),
582
+ availableForSale: v.availableForSale,
583
+ ...(v.sku ? { sku: v.sku } : {}),
584
+ ...(v.barcode ? { barcode: v.barcode } : {}),
585
+ ...(typeof v.inventoryQuantity === 'number' ? { inventoryQuantity: v.inventoryQuantity } : {}),
586
+ ...(v.inventoryPolicy ? { inventoryPolicy: v.inventoryPolicy } : {}),
587
+ ...(typeof v.requiresShipping === 'boolean' ? { requiresShipping: v.requiresShipping } : {}),
588
+ ...(typeof v.taxable === 'boolean' ? { taxable: v.taxable } : {}),
589
+ ...(v.weight ? { weight: v.weight } : {}),
590
+ ...(v.selectedOptions?.length ? { selectedOptions: v.selectedOptions } : {}),
591
+ image: normalizeImage(v.image),
592
+ ...(v.unitPrice ? { unitPrice: v.unitPrice } : {}),
593
+ ...(v.unitPriceMeasurement ? { unitPriceMeasurement: v.unitPriceMeasurement } : {}),
594
+ ...(v.quantityRule ? { quantityRule: v.quantityRule } : {}),
595
+ ...(v.storeAvailability?.nodes?.length
596
+ ? {
597
+ storeAvailability: v.storeAvailability.nodes.map((s) => ({
598
+ available: s.available,
599
+ quantityAvailable: s.quantityAvailable,
600
+ pickUpTime: s.pickUpTime ?? null,
601
+ location: s.location,
602
+ })),
603
+ }
604
+ : {}),
605
+ }));
606
+ const images = (p.images?.nodes ?? [])
607
+ .map(normalizeImage)
608
+ .filter((i) => i !== null);
609
+ const TYPE_MAP = {
610
+ MediaImage: 'image',
611
+ Video: 'video',
612
+ Model3d: 'model_3d',
613
+ ExternalVideo: 'external_video',
614
+ };
615
+ const media = (p.media?.nodes ?? []).map((m) => ({
616
+ id: m.id,
617
+ type: TYPE_MAP[m.__typename] ?? 'image',
618
+ alt: m.alt ?? null,
619
+ ...(m.image ? { image: normalizeImage(m.image) } : {}),
620
+ ...(m.previewImage ? { previewImage: normalizeImage(m.previewImage) } : {}),
621
+ ...(m.sources?.length ? { sources: m.sources } : {}),
622
+ ...(m.host ? { host: m.host } : {}),
623
+ ...(m.embedUrl ? { embedUrl: m.embedUrl } : {}),
624
+ }));
625
+ const sellingPlanGroups = (p.sellingPlanGroups?.nodes ?? []).map((g) => ({
626
+ name: g.name,
627
+ appName: g.appName ?? null,
628
+ options: g.options ?? [],
629
+ sellingPlans: (g.sellingPlans?.nodes ?? []).map((sp) => ({
630
+ id: sp.id,
631
+ name: sp.name,
632
+ description: sp.description ?? null,
633
+ recurringDeliveries: sp.recurringDeliveries,
634
+ options: sp.options ?? [],
635
+ })),
636
+ }));
637
+ const metafields = {};
638
+ for (const m of p.metafields ?? []) {
639
+ if (m)
640
+ metafields[`${m.namespace}.${m.key}`] = m.value;
641
+ }
642
+ return {
643
+ ...base,
644
+ ...(p.description ? { description: p.description } : {}),
645
+ ...(p.descriptionHtml ? { descriptionHtml: p.descriptionHtml } : {}),
646
+ ...(typeof p.isGiftCard === 'boolean' ? { isGiftCard: p.isGiftCard } : {}),
647
+ ...(typeof p.totalInventory === 'number' ? { totalInventory: p.totalInventory } : {}),
648
+ ...(images.length ? { images } : {}),
649
+ ...(media.length ? { media } : {}),
650
+ ...(p.options?.length ? { options: p.options } : {}),
651
+ ...(p.seo ? { seo: { title: p.seo.title ?? null, description: p.seo.description ?? null, keywords: p.seo.keywords ?? [] } } : {}),
652
+ ...(variants.length ? { variants } : {}),
653
+ ...(sellingPlanGroups.length ? { sellingPlanGroups } : {}),
654
+ ...(p.collections?.nodes?.length
655
+ ? { collections: p.collections.nodes.map((c) => ({ handle: c.handle, title: c.title })) }
656
+ : {}),
657
+ ...(Object.keys(metafields).length ? { metafields } : {}),
658
+ };
659
+ }
660
+ /**
661
+ * One request path for the bootstrap AND every post-boot interaction (the
662
+ * cart's mutations, the PDP's lazy product fetch) — same endpoint, same
663
+ * publishable-key + country headers, same error handling.
664
+ */
665
+ function makeGraphqlRequest(opts) {
666
+ const maybeFetch = opts.fetcher ?? globalThis.fetch;
667
+ if (!maybeFetch) {
668
+ throw new Error('[theme-kit] createLiveData: fetch is not available in this environment');
669
+ }
670
+ // Capture into a definitely-defined const so the narrowing survives into the
671
+ // graphqlRequest closure below (TS drops `!undefined` narrowing across scopes).
672
+ const f = maybeFetch;
673
+ const endpoint = opts.endpoint.replace(/\/$/, '');
674
+ const url = `${endpoint}/api/v1/stores/${encodeURIComponent(opts.storeId)}/graphql`;
675
+ return async function graphqlRequest(query, variables) {
676
+ const res = await f(url, {
677
+ method: 'POST',
678
+ headers: {
679
+ 'content-type': 'application/json',
680
+ ...(opts.token ? { 'x-publishable-key': opts.token } : {}),
681
+ // X-Tanqory-Country triggers backend Market resolution; if the store
682
+ // has an active Market with this country, Money.currencyCode + amount
683
+ // come back already-converted in the target currency.
684
+ ...(opts.country ? { 'x-tanqory-country': opts.country.toUpperCase() } : {}),
685
+ // X-Tanqory-Lang triggers translation overlay: product/collection/page
686
+ // content comes back in this locale where the merchant has translations.
687
+ ...(opts.locale ? { 'x-tanqory-lang': opts.locale.toLowerCase() } : {}),
688
+ },
689
+ body: JSON.stringify({ query, variables }),
690
+ });
691
+ if (!res.ok) {
692
+ throw new Error(`[theme-kit] GraphQL HTTP ${res.status} from ${url} — ${await res.text().catch(() => '')}`);
693
+ }
694
+ const json = (await res.json());
695
+ if (json.errors?.length) {
696
+ const msg = json.errors.map((e) => e.message).join('; ');
697
+ // Partial success: GraphQL nulls the failed field(s) but still returns the
698
+ // rest of `data`. Only fail hard when NOTHING came back — otherwise log and
699
+ // use what we got, so one flaky field (e.g. `localization` on an older
700
+ // cell) can't blank the entire storefront / fall the whole boot to mock.
701
+ if (json.data == null) {
702
+ throw new Error(`[theme-kit] GraphQL errors: ${msg}`);
703
+ }
704
+ if (typeof console !== 'undefined') {
705
+ // eslint-disable-next-line no-console
706
+ console.warn(`[theme-kit] GraphQL partial errors (using partial data): ${msg}`);
707
+ }
708
+ }
709
+ return json.data;
710
+ };
711
+ }
712
+ export async function createLiveData(opts) {
713
+ const graphqlRequest = makeGraphqlRequest(opts);
714
+ // Defaults stay under store-api's GraphQL cost budget (1000). Cost formula
715
+ // for the bootstrap query: 3*N + 4*N*M + 4*T (N = collectionLimit,
716
+ // M = productLimitPerCollection, T = topProductLimit). 10 + 10 + 24 = 526
717
+ // — plenty of headroom for a homepage prefetch. Bump in opts.prefetch only
718
+ // if you're sure the store's cost-budget limit is higher than 1000.
719
+ const collectionLimit = opts.prefetch?.collectionLimit ?? 10;
720
+ const productLimitPerCollection = opts.prefetch?.productLimitPerCollection ?? 10;
721
+ const topProductLimit = opts.prefetch?.topProductLimit ?? 24;
722
+ let boot;
723
+ try {
724
+ boot = await graphqlRequest(COLLECTIONS_QUERY, {
725
+ first: collectionLimit,
726
+ productFirst: productLimitPerCollection,
727
+ productsTop: topProductLimit,
728
+ pageHandle: opts.pageHandle ?? null,
729
+ productHandle: opts.productHandle ?? null,
730
+ collectionHandle: opts.collectionHandle ?? null,
731
+ policyBodies: opts.policyBodies === true,
732
+ });
733
+ }
734
+ catch (err) {
735
+ // The full query nulls out entirely if the cell errors on an optional field
736
+ // (localization, nested collection products). Retry once with the reduced
737
+ // query so the storefront still renders real shop/menus/collections/products
738
+ // instead of falling all the way back to mock.
739
+ if (typeof console !== 'undefined') {
740
+ // eslint-disable-next-line no-console
741
+ console.warn(`[theme-kit] full bootstrap failed, retrying without optional fields: ${err.message}`);
742
+ }
743
+ boot = await graphqlRequest(SAFE_COLLECTIONS_QUERY, {
744
+ first: collectionLimit,
745
+ productsTop: topProductLimit,
746
+ pageHandle: opts.pageHandle ?? null,
747
+ productHandle: opts.productHandle ?? null,
748
+ collectionHandle: opts.collectionHandle ?? null,
749
+ policyBodies: opts.policyBodies === true,
750
+ });
751
+ }
752
+ return buildLiveData(boot, graphqlRequest, opts);
753
+ }
754
+ /**
755
+ * Build a live DataApi SYNCHRONOUSLY from a previously-fetched bootstrap
756
+ * payload (`data.getSnapshot()`, serialized into the SSG HTML as
757
+ * `window.__TQ_STATE__` by the prerender step). This is what makes hydration
758
+ * deterministic: the client's first render uses the EXACT data the server
759
+ * rendered with — no network round-trip, no drift, no mock fallback — and
760
+ * mount()'s `revalidate` swaps in fresh data after hydration (SWR).
761
+ */
762
+ export function createLiveDataFromSnapshot(snapshot, opts) {
763
+ const graphqlRequest = makeGraphqlRequest(opts);
764
+ return buildLiveData((snapshot ?? undefined), graphqlRequest, opts);
765
+ }
766
+ /** Assemble the DataApi from a bootstrap payload + a live requester. Shared by
767
+ * createLiveData (fetches the bootstrap) and createLiveDataFromSnapshot
768
+ * (reuses the serialized one) so both paths render identically. */
769
+ function buildLiveData(boot, graphqlRequest, opts) {
770
+ const productLimitPerCollection = opts.prefetch?.productLimitPerCollection ?? 10;
771
+ const collections = (boot?.collections.edges ?? []).map((e) => normalizeCollection(e.node));
772
+ const topProducts = (boot?.products.edges ?? []).map((e) => normalizeProduct(e.node));
773
+ // Index the current detail route's product/collection (prefetched by handle)
774
+ // so productByHandle/collectionByHandle resolve it even when it isn't in the
775
+ // top set — this is what lets the theme pick its templateSuffix variant.
776
+ if (boot?.product)
777
+ topProducts.push(normalizeProduct(boot.product));
778
+ // Themes commonly reference `featured` / `frontpage` / `all` as their homepage
779
+ // collection. Synthesize one when the merchant hasn't created a real
780
+ // collection yet but DOES have Active products — otherwise their first
781
+ // product would never appear on the storefront. Also ensure `allProducts`
782
+ // is wired even when no products exist outside of collections.
783
+ if (boot?.collection && !collections.some((c) => c.handle === boot.collection.handle)) {
784
+ collections.push(normalizeCollection(boot.collection));
785
+ }
786
+ // Only for a store with no collection at all: synthesized next to real ones,
787
+ // "Featured" showed up in every collection list as a collection the
788
+ // merchant never made (English title, first product's image).
789
+ const realCollections = collections.slice();
790
+ if (topProducts.length > 0 && collections.length === 0) {
791
+ collections.unshift({
792
+ handle: 'featured',
793
+ title: 'Featured',
794
+ image: topProducts[0].featuredImage ?? null,
795
+ products: topProducts.slice(0, productLimitPerCollection),
796
+ });
797
+ }
798
+ // Mirror as `all` too — many themes (incl. our nova templates) reference it.
799
+ if (topProducts.length > 0 && !collections.some((c) => c.handle === 'all')) {
800
+ collections.push({
801
+ handle: 'all',
802
+ title: 'All products',
803
+ image: topProducts[0].featuredImage ?? null,
804
+ products: topProducts,
805
+ });
806
+ }
807
+ // Reuse the createMockData factory — same cache shape, same DataApi.
808
+ // It also indexes products by handle so productByHandle() works even for
809
+ // products fetched only via the top-level products() query.
810
+ const data = createMockData(collections);
811
+ // `all` (and a stand-in `featured`) stay addressable by handle, but a list of
812
+ // the store's collections lists only the ones the merchant made.
813
+ if (realCollections.length > 0)
814
+ data.allCollections = () => realCollections;
815
+ const pageNode = boot?.page;
816
+ if (pageNode) {
817
+ // Cache only the page that matched the URL. pageByHandle returns null
818
+ // for everything else — themes should only call it for the current page.
819
+ const page = {
820
+ handle: pageNode.handle,
821
+ title: pageNode.title,
822
+ body: pageNode.body,
823
+ ...(pageNode.bodySummary ? { bodySummary: pageNode.bodySummary } : {}),
824
+ ...(pageNode.author ? { author: pageNode.author } : {}),
825
+ ...(pageNode.publishedAt ? { publishedAt: pageNode.publishedAt } : {}),
826
+ ...(pageNode.updatedAt ? { updatedAt: pageNode.updatedAt } : {}),
827
+ ...(pageNode.templateSuffix ? { templateSuffix: pageNode.templateSuffix } : {}),
828
+ };
829
+ data.pageByHandle = (handle) => handle === page.handle || decodeHandle(handle) === page.handle ? page : null;
830
+ }
831
+ const loc = boot?.localization;
832
+ if (loc) {
833
+ // Only expose the localization payload when the store actually has Markets
834
+ // (availableCountries non-empty). With zero markets, leave `null` so the
835
+ // theme's country picker hides itself instead of showing a hardcoded list
836
+ // that doesn't match what the merchant has configured.
837
+ data.localization =
838
+ loc.availableCountries.length > 0
839
+ ? {
840
+ country: loc.country,
841
+ availableCountries: loc.availableCountries,
842
+ // Published languages come straight from the store (StoreLanguage →
843
+ // SDL `availableLanguages`); the theme just renders the picker.
844
+ language: loc.language,
845
+ availableLanguages: loc.availableLanguages,
846
+ }
847
+ : null;
848
+ }
849
+ // Post-boot capabilities: the raw GraphQL escape hatch (cart mutations live
850
+ // on top of this) and an on-demand single-product fetch (PDP variant picker).
851
+ data.graphql = graphqlRequest;
852
+ data.fetchProduct = async (handle, fpOpts) => {
853
+ // Never reject: a failed detail fetch (cost budget, cold cell, network)
854
+ // must degrade to the prefetched card data, not crash the product page
855
+ // with an unhandled rejection mid-hydration.
856
+ try {
857
+ const res = await graphqlRequest(PRODUCT_QUERY, {
858
+ handle,
859
+ identifiers: fpOpts?.metafields ?? [],
860
+ });
861
+ return res?.product ? normalizeProductDetail(res.product) : null;
862
+ }
863
+ catch (err) {
864
+ if (typeof console !== 'undefined') {
865
+ // eslint-disable-next-line no-console
866
+ console.warn(`[theme-kit] fetchProduct(${handle}) failed: ${err.message}`);
867
+ }
868
+ return null;
869
+ }
870
+ };
871
+ const toMfMap = (arr) => {
872
+ const out = {};
873
+ for (const m of arr ?? [])
874
+ if (m)
875
+ out[`${m.namespace}.${m.key}`] = m.value;
876
+ return out;
877
+ };
878
+ data.fetchShopMetafields = async (identifiers) => {
879
+ if (!identifiers.length)
880
+ return {};
881
+ const res = await graphqlRequest(`query NovaShopMetafields($identifiers: [MetafieldIdentifier!]!) {
882
+ shop { metafields(identifiers: $identifiers) { namespace key value } }
883
+ }`, { identifiers });
884
+ return toMfMap(res?.shop?.metafields);
885
+ };
886
+ data.fetchCollectionMetafields = async (handle, identifiers) => {
887
+ if (!identifiers.length || !handle)
888
+ return {};
889
+ const res = await graphqlRequest(`query NovaCollectionMetafields($handle: String!, $identifiers: [MetafieldIdentifier!]!) {
890
+ collection(handle: $handle) { metafields(identifiers: $identifiers) { namespace key value } }
891
+ }`, { handle, identifiers });
892
+ return toMfMap(res?.collection?.metafields);
893
+ };
894
+ // ─── commerce-standard storefront extensions ───────────────────
895
+ // Shop info + the two standard menus came back in the bootstrap → expose
896
+ // them synchronously (the layout's header/footer render at hydration).
897
+ const { shop, menus } = readBootstrapShopMenu(boot);
898
+ data.shop = shop;
899
+ data.menu = (handle) => menus.get(handle) ?? menus.get(decodeHandle(handle)) ?? null;
900
+ // The rest (search, blog, recommendations, metaobjects, customer account)
901
+ // are lazy — attach them on the same requester. fetchMenu shares `menus` so
902
+ // a later fetch warms the same cache the sync menu() reads.
903
+ Object.assign(data, createStorefrontMethods(graphqlRequest, { normalizeProduct }, menus));
904
+ // One request per blog / article: the SPA router reads the record for its
905
+ // template variant and the section reads it for its posts — the same answer.
906
+ const memo = (fn, keyOf) => {
907
+ if (!fn)
908
+ return fn;
909
+ const inflight = new Map();
910
+ return (...a) => {
911
+ const k = keyOf(...a);
912
+ let p = inflight.get(k);
913
+ if (!p) {
914
+ p = fn(...a).catch((e) => {
915
+ inflight.delete(k);
916
+ throw e;
917
+ });
918
+ inflight.set(k, p);
919
+ }
920
+ return p;
921
+ };
922
+ };
923
+ data.blogByHandle = memo(data.blogByHandle, (h, o) => `${decodeHandle(h)}|${o?.articles ?? ''}`);
924
+ data.articleByHandle = memo(data.articleByHandle, (b, a) => `${decodeHandle(b)}/${decodeHandle(a)}`);
925
+ // The bootstrap carries only the landing page. A page reached by soft
926
+ // navigation is fetched here, and pageByHandle answers for it afterwards —
927
+ // its body and its template variant (page.contact) need the record.
928
+ const fetchedPages = new Map();
929
+ const landingPage = data.pageByHandle;
930
+ data.pageByHandle = (handle) => landingPage(handle) ?? fetchedPages.get(decodeHandle(handle)) ?? null;
931
+ data.fetchPage = async (handle) => {
932
+ const known = data.pageByHandle(handle);
933
+ if (known)
934
+ return known;
935
+ const res = await graphqlRequest(`query NovaPage($handle: String!) {
936
+ page(handle: $handle) { handle title body bodySummary author publishedAt updatedAt templateSuffix seo { title description keywords } }
937
+ }`, { handle: decodeHandle(handle) });
938
+ const n = res?.page;
939
+ if (!n)
940
+ return null;
941
+ const page = {
942
+ handle: n.handle,
943
+ title: n.title,
944
+ body: n.body ?? '',
945
+ ...(n.bodySummary ? { bodySummary: n.bodySummary } : {}),
946
+ ...(n.author ? { author: n.author } : {}),
947
+ ...(n.publishedAt ? { publishedAt: n.publishedAt } : {}),
948
+ ...(n.updatedAt ? { updatedAt: n.updatedAt } : {}),
949
+ ...(n.templateSuffix ? { templateSuffix: n.templateSuffix } : {}),
950
+ ...(n.seo ? { seo: n.seo } : {}),
951
+ };
952
+ fetchedPages.set(page.handle, page);
953
+ return page;
954
+ };
955
+ // List every store menu (Dashboard → Navigation) for the editor's link_list
956
+ // picker — the storefront `menus` query (id/handle/title/itemsCount).
957
+ data.listMenus = async () => {
958
+ const res = await graphqlRequest(`query NovaMenus { menus { handle title itemsCount } }`);
959
+ return res?.menus ?? [];
960
+ };
961
+ data.notifyBackInStock = async (input) => {
962
+ const f = opts.fetcher ?? globalThis.fetch;
963
+ if (!f)
964
+ throw new Error('[theme-kit] notifyBackInStock: fetch is not available');
965
+ const res = await f(`${opts.endpoint.replace(/\/$/, '')}/api/v1/stores/${encodeURIComponent(opts.storeId)}/storefront/back-in-stock`, {
966
+ method: 'POST',
967
+ headers: {
968
+ 'content-type': 'application/json',
969
+ ...(opts.token ? { 'x-publishable-key': opts.token } : {}),
970
+ },
971
+ body: JSON.stringify({
972
+ // store-api wants the bare UUID; tolerate a `gid://…/<uuid>` form
973
+ variantId: input.variantId.split('/').pop(),
974
+ email: input.email,
975
+ ...(input.locale ? { locale: input.locale } : {}),
976
+ ...(input.country ? { country: input.country.toUpperCase() } : {}),
977
+ }),
978
+ });
979
+ if (!res.ok)
980
+ throw new Error(`[theme-kit] notify-me HTTP ${res.status}`);
981
+ const json = (await res.json().catch(() => ({})));
982
+ return json.status === 'available' ? 'available' : 'subscribed';
983
+ };
984
+ data.pixels = async () => {
985
+ const res = await graphqlRequest(`query NovaPixels { customPixels { id name provider providerPixelId code } }`);
986
+ return res?.customPixels ?? [];
987
+ };
988
+ data.locations = async () => {
989
+ const res = await graphqlRequest(`query NovaLocations { locations { id name code address { country address city province postalCode phone } } }`);
990
+ return res?.locations ?? [];
991
+ };
992
+ // The raw serializable bootstrap this DataApi was built from. entry-server
993
+ // embeds it into the SSG HTML (window.__TQ_STATE__) so the client can
994
+ // rebuild the SAME DataApi synchronously at hydration — see
995
+ // createLiveDataFromSnapshot. null when there was no live bootstrap.
996
+ data.getSnapshot = () => boot ?? null;
997
+ return data;
998
+ }
999
+ // ─── Deterministic money formatting ─────────────────────────────────────────
1000
+ // Intl.NumberFormat's currency output depends on the environment's ICU data
1001
+ // (the build pod's Node vs each visitor's browser can format the SAME Money
1002
+ // differently, e.g. "THB 120.00" vs "฿120.00") — which breaks SSR hydration
1003
+ // (React #425 text mismatch). Format manually instead: identical output
1004
+ // everywhere, by construction.
1005
+ const CURRENCY_FORMAT = {
1006
+ THB: { symbol: '฿', decimals: 2 },
1007
+ USD: { symbol: '$', decimals: 2 },
1008
+ EUR: { symbol: '€', decimals: 2 },
1009
+ GBP: { symbol: '£', decimals: 2 },
1010
+ JPY: { symbol: '¥', decimals: 0 },
1011
+ KRW: { symbol: '₩', decimals: 0 },
1012
+ VND: { symbol: '₫', decimals: 0 },
1013
+ IDR: { symbol: 'Rp', decimals: 0 },
1014
+ SGD: { symbol: 'S$', decimals: 2 },
1015
+ HKD: { symbol: 'HK$', decimals: 2 },
1016
+ TWD: { symbol: 'NT$', decimals: 2 },
1017
+ AUD: { symbol: 'A$', decimals: 2 },
1018
+ NZD: { symbol: 'NZ$', decimals: 2 },
1019
+ CAD: { symbol: 'CA$', decimals: 2 },
1020
+ CNY: { symbol: 'CN¥', decimals: 2 },
1021
+ INR: { symbol: '₹', decimals: 2 },
1022
+ MYR: { symbol: 'RM', decimals: 2 },
1023
+ PHP: { symbol: '₱', decimals: 2 },
1024
+ };
1025
+ /** The grouped numeric part of a Money, without symbol or code.
1026
+ * `stripZeros` drops a `.00`-style fraction (`money_without_trailing_zeros`). */
1027
+ function moneyDigits(money, stripZeros = false) {
1028
+ const n = Number(money.amount);
1029
+ if (!Number.isFinite(n))
1030
+ return null;
1031
+ const info = CURRENCY_FORMAT[money.currencyCode];
1032
+ const decimals = info?.decimals ?? 2;
1033
+ let [int, frac] = Math.abs(n).toFixed(decimals).split('.');
1034
+ if (stripZeros && frac && /^0+$/.test(frac))
1035
+ frac = '';
1036
+ const grouped = int.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
1037
+ return `${n < 0 ? '-' : ''}${grouped}${frac ? `.${frac}` : ''}`;
1038
+ }
1039
+ /** standard `money` — symbol + amount (e.g. "฿120.00"). */
1040
+ export function formatMoney(money) {
1041
+ const num = moneyDigits(money);
1042
+ if (num === null)
1043
+ return `${money.amount} ${money.currencyCode}`;
1044
+ const info = CURRENCY_FORMAT[money.currencyCode];
1045
+ return info ? `${info.symbol}${num}` : `${num} ${money.currencyCode}`;
1046
+ }
1047
+ /** standard `money_with_currency` — symbol + amount + ISO code (e.g. "฿120.00 THB"). */
1048
+ export function formatMoneyWithCurrency(money) {
1049
+ const num = moneyDigits(money);
1050
+ if (num === null)
1051
+ return `${money.amount} ${money.currencyCode}`;
1052
+ const info = CURRENCY_FORMAT[money.currencyCode];
1053
+ return info
1054
+ ? `${info.symbol}${num} ${money.currencyCode}`
1055
+ : `${num} ${money.currencyCode}`;
1056
+ }
1057
+ /** standard `money_without_currency` — bare grouped amount (e.g. "120.00"). */
1058
+ export function formatMoneyWithoutCurrency(money) {
1059
+ return moneyDigits(money) ?? `${money.amount}`;
1060
+ }
1061
+ /** standard `money_without_trailing_zeros` — symbol + amount, dropping a `.00`
1062
+ * fraction (e.g. "฿120", but "฿120.50" stays). */
1063
+ export function formatMoneyWithoutTrailingZeros(money) {
1064
+ const num = moneyDigits(money, true);
1065
+ if (num === null)
1066
+ return `${money.amount} ${money.currencyCode}`;
1067
+ const info = CURRENCY_FORMAT[money.currencyCode];
1068
+ return info ? `${info.symbol}${num}` : `${num} ${money.currencyCode}`;
1069
+ }
1070
+ /** standard `date` / `time_tag` — format an ISO date deterministically (identical
1071
+ * output on server + client to keep SSR hydration stable). Defaults to a medium
1072
+ * date; pass Intl options to customize. */
1073
+ export function formatDate(input, opts = { year: 'numeric', month: 'short', day: 'numeric' }, locale = 'en-US') {
1074
+ if (!input)
1075
+ return '';
1076
+ const d = input instanceof Date ? input : new Date(input);
1077
+ if (Number.isNaN(d.getTime()))
1078
+ return '';
1079
+ try {
1080
+ return new Intl.DateTimeFormat(locale, { ...opts, timeZone: 'UTC' }).format(d);
1081
+ }
1082
+ catch {
1083
+ return d.toISOString().slice(0, 10);
1084
+ }
1085
+ }
1086
+ /** standard `weight_with_unit` — format a variant weight (e.g. "1.5 kg"). */
1087
+ export function formatWeight(weight) {
1088
+ if (!weight || !Number.isFinite(weight.value))
1089
+ return '';
1090
+ const unit = { GRAMS: 'g', KILOGRAMS: 'kg', OUNCES: 'oz', POUNDS: 'lb' }[weight.unit] ?? weight.unit.toLowerCase();
1091
+ const n = Number.isInteger(weight.value) ? weight.value : Number(weight.value.toFixed(2));
1092
+ return `${n} ${unit}`;
1093
+ }
1094
+ /** standard `image_url` — append CDN transform params (width/height/crop) to an
1095
+ * image URL. No-op when the src is empty or no transform is requested. React
1096
+ * themes render the `<img>` themselves, so there is no separate `image_tag`. */
1097
+ export function imageUrl(src, opts = {}) {
1098
+ if (!src)
1099
+ return '';
1100
+ const { width, height, crop } = opts;
1101
+ if (!width && !height && !crop)
1102
+ return src;
1103
+ try {
1104
+ const url = new URL(src, 'https://cdn.tanqory.com');
1105
+ if (width)
1106
+ url.searchParams.set('width', String(width));
1107
+ if (height)
1108
+ url.searchParams.set('height', String(height));
1109
+ if (crop)
1110
+ url.searchParams.set('crop', crop);
1111
+ // Preserve relative URLs (return path+query) vs absolute.
1112
+ return /^https?:\/\//i.test(src) ? url.toString() : `${url.pathname}${url.search}`;
1113
+ }
1114
+ catch {
1115
+ return src;
1116
+ }
1117
+ }