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

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 (202) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +98 -10
  3. package/dist/abi/canvas-live.d.ts +49 -0
  4. package/dist/abi/canvas-live.js +88 -0
  5. package/dist/abi/cart.d.ts +48 -0
  6. package/dist/abi/cart.js +256 -0
  7. package/dist/abi/convert.d.ts +126 -0
  8. package/dist/abi/convert.js +493 -0
  9. package/dist/abi/data-api.d.ts +11 -0
  10. package/dist/abi/data-api.js +178 -0
  11. package/dist/abi/jcs.d.ts +6 -0
  12. package/dist/abi/jcs.js +28 -0
  13. package/dist/abi/page-data.d.ts +198 -0
  14. package/dist/abi/page-data.js +577 -0
  15. package/dist/abi/page.d.ts +23 -0
  16. package/dist/abi/page.js +46 -0
  17. package/dist/abi/referrals.d.ts +23 -0
  18. package/dist/abi/referrals.js +89 -0
  19. package/dist/abi/rewards.d.ts +27 -0
  20. package/dist/abi/rewards.js +82 -0
  21. package/dist/abi/seo.d.ts +47 -0
  22. package/dist/abi/seo.js +68 -0
  23. package/dist/abi/shell.d.ts +22 -0
  24. package/dist/abi/shell.js +10 -0
  25. package/dist/abi/wire.d.ts +38 -0
  26. package/dist/abi/wire.js +84 -0
  27. package/dist/build.d.ts +113 -0
  28. package/dist/build.js +294 -0
  29. package/dist/client.d.ts +19 -0
  30. package/dist/client.js +76 -0
  31. package/dist/contract.d.ts +6 -0
  32. package/dist/contract.js +6 -0
  33. package/dist/headless/ai.d.ts +132 -0
  34. package/dist/headless/ai.js +99 -0
  35. package/dist/headless/hooks.d.ts +273 -0
  36. package/dist/headless/hooks.js +533 -0
  37. package/dist/headless/i18n.d.ts +13 -0
  38. package/dist/headless/i18n.js +45 -0
  39. package/dist/headless/index.d.ts +36 -0
  40. package/dist/headless/index.js +38 -0
  41. package/dist/headless/money.d.ts +25 -0
  42. package/dist/headless/money.js +61 -0
  43. package/dist/headless/page.d.ts +43 -0
  44. package/dist/headless/page.js +53 -0
  45. package/dist/headless/platform.d.ts +55 -0
  46. package/dist/headless/platform.js +77 -0
  47. package/dist/headless/primitives/cart.d.ts +90 -0
  48. package/dist/headless/primitives/cart.js +153 -0
  49. package/dist/headless/primitives/collection.d.ts +68 -0
  50. package/dist/headless/primitives/collection.js +80 -0
  51. package/dist/headless/primitives/product.d.ts +101 -0
  52. package/dist/headless/primitives/product.js +117 -0
  53. package/dist/headless/primitives/storefront.d.ts +106 -0
  54. package/dist/headless/primitives/storefront.js +186 -0
  55. package/dist/headless/primitives/util.d.ts +19 -0
  56. package/dist/headless/primitives/util.js +42 -0
  57. package/dist/headless/strings.d.ts +9 -0
  58. package/dist/headless/strings.js +186 -0
  59. package/dist/headless/structured-data.d.ts +31 -0
  60. package/dist/headless/structured-data.js +57 -0
  61. package/dist/headless/theme.d.ts +99 -0
  62. package/dist/headless/theme.js +54 -0
  63. package/dist/index.d.ts +20 -0
  64. package/dist/index.js +18 -553
  65. package/dist/runtime/data/StoreProvider.d.ts +56 -0
  66. package/dist/runtime/data/StoreProvider.js +308 -0
  67. package/dist/runtime/data/handle.d.ts +14 -0
  68. package/dist/runtime/data/handle.js +16 -0
  69. package/dist/runtime/data/routes.d.ts +87 -0
  70. package/dist/runtime/data/routes.js +154 -0
  71. package/dist/runtime/data/to-ui.d.ts +237 -0
  72. package/dist/runtime/data/to-ui.js +759 -0
  73. package/dist/runtime/entries/register.d.ts +9 -0
  74. package/dist/runtime/entries/register.js +9 -0
  75. package/dist/runtime/entries/sections.d.ts +16 -0
  76. package/dist/runtime/entries/sections.js +19 -0
  77. package/dist/{types → runtime/kit}/SectionTree.d.ts +2 -1
  78. package/dist/runtime/kit/SectionTree.js +100 -0
  79. package/dist/runtime/kit/analytics.d.ts +63 -0
  80. package/dist/runtime/kit/analytics.js +233 -0
  81. package/dist/runtime/kit/cart.d.ts +167 -0
  82. package/dist/runtime/kit/cart.js +544 -0
  83. package/dist/{types → runtime/kit}/composition.d.ts +1 -1
  84. package/dist/runtime/kit/composition.js +3 -0
  85. package/dist/{types → runtime/kit}/config.d.ts +2 -2
  86. package/dist/runtime/kit/config.js +6 -0
  87. package/dist/runtime/kit/consent.d.ts +29 -0
  88. package/dist/runtime/kit/consent.js +159 -0
  89. package/dist/runtime/kit/contract/content.d.ts +164 -0
  90. package/dist/runtime/kit/contract/content.js +83 -0
  91. package/dist/runtime/kit/contract/field-types.d.ts +290 -0
  92. package/dist/runtime/kit/contract/field-types.js +129 -0
  93. package/dist/runtime/kit/contract/groups.d.ts +230 -0
  94. package/dist/runtime/kit/contract/groups.js +402 -0
  95. package/dist/runtime/kit/contract/index.d.ts +33 -0
  96. package/dist/runtime/kit/contract/index.js +33 -0
  97. package/dist/runtime/kit/contract/transform.d.ts +82 -0
  98. package/dist/runtime/kit/contract/transform.js +133 -0
  99. package/dist/runtime/kit/contract/validate.d.ts +67 -0
  100. package/dist/runtime/kit/contract/validate.js +388 -0
  101. package/dist/{types → runtime/kit}/data.d.ts +276 -7
  102. package/dist/runtime/kit/data.js +1117 -0
  103. package/dist/{types → runtime/kit}/defineSection.d.ts +1 -1
  104. package/dist/runtime/kit/defineSection.js +10 -0
  105. package/dist/{types → runtime/kit}/dynamic-source.d.ts +4 -4
  106. package/dist/runtime/kit/dynamic-source.js +143 -0
  107. package/dist/runtime/kit/index.d.ts +24 -0
  108. package/dist/runtime/kit/index.js +24 -0
  109. package/dist/{types → runtime/kit}/jsx-to-json.d.ts +1 -1
  110. package/dist/runtime/kit/jsx-to-json.js +28 -0
  111. package/dist/{types → runtime/kit}/mount.d.ts +25 -4
  112. package/dist/runtime/kit/mount.js +124 -0
  113. package/dist/{types → runtime/kit}/registry.d.ts +1 -1
  114. package/dist/runtime/kit/registry.js +12 -0
  115. package/dist/{types → runtime/kit}/ssg.d.ts +9 -3
  116. package/dist/runtime/kit/ssg.js +56 -0
  117. package/dist/{types → runtime/kit}/storefront.d.ts +206 -7
  118. package/dist/runtime/kit/storefront.js +723 -0
  119. package/dist/{types → runtime/kit}/theme-context.d.ts +8 -2
  120. package/dist/runtime/kit/theme-context.js +25 -0
  121. package/dist/runtime/kit/types.d.ts +142 -0
  122. package/dist/runtime/kit/types.js +1 -0
  123. package/dist/runtime/platform/TrackingPixels.d.ts +14 -0
  124. package/dist/runtime/platform/TrackingPixels.js +63 -0
  125. package/dist/runtime/platform/environment.d.ts +68 -0
  126. package/dist/runtime/platform/environment.js +85 -0
  127. package/dist/runtime/platform/locale.d.ts +27 -0
  128. package/dist/runtime/platform/locale.js +42 -0
  129. package/dist/runtime/platform/route-analytics.d.ts +15 -0
  130. package/dist/runtime/platform/route-analytics.js +72 -0
  131. package/dist/runtime/platform/safe-href.d.ts +25 -0
  132. package/dist/runtime/platform/safe-href.js +69 -0
  133. package/dist/runtime/platform/safe-values.d.ts +37 -0
  134. package/dist/runtime/platform/safe-values.js +140 -0
  135. package/dist/runtime/render/SectionRenderer.d.ts +4 -0
  136. package/dist/runtime/render/SectionRenderer.js +111 -0
  137. package/dist/runtime/render/listing-query.d.ts +47 -0
  138. package/dist/runtime/render/listing-query.js +114 -0
  139. package/dist/runtime/render/localized-copy.d.ts +86 -0
  140. package/dist/runtime/render/localized-copy.js +129 -0
  141. package/dist/runtime/render/product-listing.d.ts +11 -0
  142. package/dist/runtime/render/product-listing.js +240 -0
  143. package/dist/runtime/render/section-actions.d.ts +44 -0
  144. package/dist/runtime/render/section-actions.js +169 -0
  145. package/dist/runtime/render/starter.d.ts +11 -0
  146. package/dist/runtime/render/starter.js +81 -0
  147. package/dist/runtime/seo/head.d.ts +87 -0
  148. package/dist/runtime/seo/head.js +224 -0
  149. package/dist/runtime/seo/structured-data.d.ts +22 -0
  150. package/dist/runtime/seo/structured-data.js +115 -0
  151. package/dist/runtime/shell/PageShell.d.ts +18 -0
  152. package/dist/runtime/shell/PageShell.js +113 -0
  153. package/dist/runtime/shell/RuntimeBridge.d.ts +14 -0
  154. package/dist/runtime/shell/RuntimeBridge.js +82 -0
  155. package/dist/runtime/shell/overlay-state.d.ts +31 -0
  156. package/dist/runtime/shell/overlay-state.js +59 -0
  157. package/dist/runtime/shell/preview-mode.d.ts +2 -0
  158. package/dist/runtime/shell/preview-mode.js +11 -0
  159. package/dist/runtime/shell/spa-router.d.ts +14 -0
  160. package/dist/runtime/shell/spa-router.js +76 -0
  161. package/dist/runtime/shell/url-redirects.d.ts +6 -0
  162. package/dist/runtime/shell/url-redirects.js +37 -0
  163. package/dist/runtime/slots.d.ts +74 -0
  164. package/dist/runtime/slots.js +16 -0
  165. package/dist/runtime.d.ts +34 -0
  166. package/dist/runtime.js +40 -0
  167. package/dist/sdk/index.d.ts +24 -0
  168. package/dist/sdk/index.js +24 -0
  169. package/dist/sdk/referrals.d.ts +62 -0
  170. package/dist/sdk/referrals.js +20 -0
  171. package/dist/sdk/rewards.d.ts +85 -0
  172. package/dist/sdk/rewards.js +29 -0
  173. package/dist/sdk/runtime-context.d.ts +120 -0
  174. package/dist/sdk/runtime-context.js +73 -0
  175. package/dist/sdk/schema.d.ts +197 -0
  176. package/dist/sdk/schema.js +121 -0
  177. package/dist/sdk/server-render.d.ts +8 -0
  178. package/dist/sdk/server-render.js +12 -0
  179. package/dist/sdk/store-lookup.d.ts +27 -0
  180. package/dist/sdk/store-lookup.js +29 -0
  181. package/dist/sdk/store.d.ts +115 -0
  182. package/dist/sdk/store.js +1 -0
  183. package/dist/sdk/sx.d.ts +40 -0
  184. package/dist/sdk/sx.js +112 -0
  185. package/dist/sdk/theme.d.ts +152 -0
  186. package/dist/sdk/theme.js +10 -0
  187. package/dist/sdk/types.d.ts +395 -0
  188. package/dist/sdk/types.js +7 -0
  189. package/dist/server.d.ts +65 -0
  190. package/dist/server.js +370 -0
  191. package/docs/headless-api.md +220 -0
  192. package/package.json +77 -23
  193. package/dist/index.js.map +0 -1
  194. package/dist/ssg-BZ5FYTw7.js +0 -1802
  195. package/dist/ssg-BZ5FYTw7.js.map +0 -1
  196. package/dist/ssg.js +0 -8
  197. package/dist/ssg.js.map +0 -1
  198. package/dist/types/cart.d.ts +0 -86
  199. package/dist/types/editor.d.ts +0 -5
  200. package/dist/types/index.d.ts +0 -20
  201. package/dist/types/preview-bridge.d.ts +0 -9
  202. package/dist/types/types.d.ts +0 -44
@@ -0,0 +1,759 @@
1
+ import { matchRoute } from './routes.js';
2
+ import { safeHref } from '../platform/safe-href.js';
3
+ import { resolveLogo } from '../platform/safe-values.js';
4
+ // ── URLs (the canonical forms of app/data/routes.ts) ─────────────────────────────
5
+ const seg = (handle) => encodeURIComponent(handle);
6
+ export const productUrl = (handle) => `/products/${seg(handle)}`;
7
+ export const collectionUrl = (handle) => `/collections/${seg(handle)}`;
8
+ export const pageUrl = (handle) => `/pages/${seg(handle)}`;
9
+ export const blogUrl = (handle) => `/blogs/${seg(handle)}`;
10
+ export const articleUrl = (blogHandle, articleHandle) => `/blogs/${seg(blogHandle)}/${seg(articleHandle)}`;
11
+ export const policyUrl = (handle) => `/policies/${seg(handle)}`;
12
+ const dim = (n) => (typeof n === 'number' && Number.isFinite(n) && n > 0 ? Math.round(n) : 0);
13
+ /**
14
+ * A runtime image → Image, or null when there is no URL.
15
+ *
16
+ * `width`/`height` are required by the UI type but optional in the runtime (the
17
+ * offline fixture, collection images, article images and the theme logo setting
18
+ * carry none). An unknown dimension is `0` — "unknown", never a guessed size.
19
+ * UI images are CSS-sized (`width:100%; height:100%; object-fit`), and a
20
+ * `0 / 0` aspect-ratio is invalid CSS, so the frame keeps its own ratio.
21
+ */
22
+ export function toImage(img) {
23
+ if (!img || typeof img.url !== 'string' || !img.url.trim())
24
+ return null;
25
+ const alt = typeof img.altText === 'string' && img.altText.trim() ? img.altText : undefined;
26
+ return { src: img.url, ...(alt ? { alt } : {}), width: dim(img.width), height: dim(img.height) };
27
+ }
28
+ /** Decimal string → number, keeping every digit the source sent. null when absent or not a number. */
29
+ export function toMoney(m) {
30
+ if (!m || typeof m.currencyCode !== 'string' || !m.currencyCode)
31
+ return null;
32
+ const raw = typeof m.amount === 'number' ? m.amount : typeof m.amount === 'string' && m.amount.trim() !== '' ? Number(m.amount) : NaN;
33
+ if (!Number.isFinite(raw))
34
+ return null;
35
+ return { amount: raw, currencyCode: m.currencyCode };
36
+ }
37
+ /**
38
+ * A required Money the source could not supply. The UI type has no null here,
39
+ * so this is the ONE place a zero is written — `amount: 0` in the currency we
40
+ * do know. Callers only reach it when the runtime itself had no price.
41
+ */
42
+ function requiredMoney(m, currencyCode) {
43
+ return m ?? { amount: 0, currencyCode };
44
+ }
45
+ /** compareAt only when it is a real sale (was > now) — the runtime's own rule for product cards. */
46
+ function saleOnly(compareAt, price) {
47
+ if (!compareAt || !price)
48
+ return null;
49
+ return compareAt.currencyCode === price.currencyCode && compareAt.amount > price.amount ? compareAt : null;
50
+ }
51
+ function minMax(list) {
52
+ if (!list.length)
53
+ return null;
54
+ let min = list[0];
55
+ let max = list[0];
56
+ for (const m of list) {
57
+ if (m.currencyCode !== min.currencyCode)
58
+ continue;
59
+ if (m.amount < min.amount)
60
+ min = m;
61
+ if (m.amount > max.amount)
62
+ max = m;
63
+ }
64
+ return { min, max };
65
+ }
66
+ const str = (v) => (typeof v === 'string' && v.trim() !== '' ? v : undefined);
67
+ // ── Products ────────────────────────────────────────────────────────────────
68
+ /**
69
+ * A runtime variant → ProductVariant.
70
+ *
71
+ * `quantityAvailable` is the on-hand count only when it LIMITS a purchase:
72
+ * `inventoryPolicy: CONTINUE` sells past zero, so there is no cap, and a
73
+ * negative count under DENY means nothing is purchasable (0). Unknown — no
74
+ * count, or a count that does not limit — is an ABSENT key, never 0 or null.
75
+ */
76
+ export function toVariant(v, fallbackCurrency = '') {
77
+ const price = toMoney(v?.price);
78
+ const currency = price?.currencyCode ?? fallbackCurrency;
79
+ const qty = v?.inventoryQuantity;
80
+ const quantityAvailable = v?.inventoryPolicy === 'CONTINUE' ? undefined : typeof qty === 'number' && Number.isFinite(qty) ? Math.max(0, Math.floor(qty)) : undefined;
81
+ const sku = str(v?.sku);
82
+ return {
83
+ id: v?.id ?? '',
84
+ title: v?.title ?? '',
85
+ ...(sku ? { sku } : {}),
86
+ price: requiredMoney(price, currency),
87
+ compareAtPrice: saleOnly(toMoney(v?.compareAtPrice), price),
88
+ available: v?.availableForSale === true,
89
+ ...(quantityAvailable !== undefined ? { quantityAvailable } : {}),
90
+ selectedOptions: (v?.selectedOptions ?? []).filter((o) => o && typeof o.name === 'string').map((o) => ({ name: o.name, value: o.value ?? '' })),
91
+ image: toImage(v?.image),
92
+ };
93
+ }
94
+ /**
95
+ * A runtime product → Product.
96
+ *
97
+ * The runtime has two product shapes: the CARD (bootstrap, collection pages,
98
+ * search, recommendations) with one price, one compare-at and no variants; and
99
+ * the DETAIL (`fetchProduct`) with options + variants. Ranges come from the
100
+ * variants when they are there. On a card the runtime knows only the minimum
101
+ * price and the maximum compare-at, so both ends of each range are that one
102
+ * value — see the data-gap notes in the report.
103
+ */
104
+ export function toProduct(p) {
105
+ const handle = p?.handle ?? '';
106
+ const cardPrice = toMoney(p?.price);
107
+ const currency = cardPrice?.currencyCode ?? toMoney(p?.variants?.[0]?.price)?.currencyCode ?? '';
108
+ const variants = (p?.variants ?? []).filter(Boolean).map((v) => toVariant(v, currency));
109
+ const variantPrices = minMax(variants.map((v) => v.price).filter((m) => m.currencyCode));
110
+ const min = variantPrices?.min ?? requiredMoney(cardPrice, currency);
111
+ // A card has no variants: its max comes from the card's own range, else it is one price.
112
+ const priceRange = variantPrices ?? { min, max: toMoney(p?.priceMax) ?? min };
113
+ const variantCompare = minMax(variants.map((v) => v.compareAtPrice).filter((m) => Boolean(m)));
114
+ const cardCompare = saleOnly(toMoney(p?.compareAtPrice), cardPrice);
115
+ const compareAtPriceRange = variantCompare ?? (cardCompare ? { min: cardCompare, max: cardCompare } : null);
116
+ const featuredImage = toImage(p?.featuredImage);
117
+ const gallery = (p?.images ?? []).map(toImage).filter((i) => Boolean(i));
118
+ const images = gallery.length ? gallery : featuredImage ? [featuredImage] : [];
119
+ const available = typeof p?.availableForSale === 'boolean'
120
+ ? p.availableForSale
121
+ : variants.length
122
+ ? variants.some((v) => v.available)
123
+ : true; // the runtime omits the flag only on offline fixtures, which are all purchasable
124
+ const vendor = str(p?.vendor);
125
+ const productType = str(p?.productType);
126
+ return {
127
+ // The offline fixture has no ids; the handle is the product's stable key there.
128
+ id: p?.id ?? handle,
129
+ handle,
130
+ title: p?.title ?? '',
131
+ ...(vendor ? { vendor } : {}),
132
+ ...(productType ? { productType } : {}),
133
+ ...(typeof p?.description === 'string' ? { description: p.description } : {}),
134
+ ...(typeof p?.descriptionHtml === 'string' ? { descriptionHtml: p.descriptionHtml } : {}),
135
+ url: productUrl(handle),
136
+ featuredImage: featuredImage ?? images[0] ?? null,
137
+ images,
138
+ options: (p?.options ?? []).filter((o) => o && typeof o.name === 'string').map((o) => ({ name: o.name, values: [...(o.values ?? [])] })),
139
+ variants,
140
+ priceRange,
141
+ compareAtPriceRange,
142
+ available,
143
+ ...(p?.tags?.length ? { tags: [...p.tags] } : {}),
144
+ ...(typeof p?.lowStockThreshold === 'number' ? { lowStockThreshold: p.lowStockThreshold } : {}),
145
+ // No source: the runtime has no merchant badge field and no reviews source.
146
+ badge: null,
147
+ rating: null,
148
+ };
149
+ }
150
+ export const toProducts = (list) => (list ?? []).filter(Boolean).map(toProduct);
151
+ /** Products by handle, for StoreContext.products. */
152
+ export function toProductMap(list) {
153
+ const out = {};
154
+ for (const p of toProducts(list))
155
+ if (p.handle && !out[p.handle])
156
+ out[p.handle] = p;
157
+ return out;
158
+ }
159
+ // ── Collections ─────────────────────────────────────────────────────────────
160
+ /**
161
+ * A runtime collection → Collection.
162
+ *
163
+ * `products`: pass the live page (`collectionProducts(...).products`) when you
164
+ * have it. Otherwise the bootstrap cache is used ONLY when it actually has
165
+ * products — an empty cached list can be a shell baked before products were
166
+ * assigned, so it maps to `products: undefined` ("not loaded"), not "empty".
167
+ * Pass `products: []` to state that the collection is known to be empty.
168
+ */
169
+ export function toCollection(c, opts = {}) {
170
+ const handle = c?.handle ?? '';
171
+ const source = opts.products ?? (c?.products?.length ? c.products : null);
172
+ const products = source ? toProducts(source) : undefined;
173
+ const description = str(c?.description ?? undefined);
174
+ return {
175
+ id: c?.id ?? handle,
176
+ handle,
177
+ title: c?.title ?? '',
178
+ ...(description ? { description } : {}),
179
+ url: collectionUrl(handle),
180
+ image: toImage(c?.image),
181
+ productsCount: typeof c?.productsCount === 'number' ? c.productsCount : (products?.length ?? 0),
182
+ ...(products ? { products } : {}),
183
+ };
184
+ }
185
+ /** Collections by handle, for StoreContext.collections (card-level: no product lists). */
186
+ export function toCollectionMap(list, opts = {}) {
187
+ const out = {};
188
+ for (const c of list ?? []) {
189
+ if (!c?.handle || out[c.handle])
190
+ continue;
191
+ const mapped = toCollection(c);
192
+ if (!opts.withProducts)
193
+ delete mapped.products;
194
+ out[c.handle] = mapped;
195
+ }
196
+ return out;
197
+ }
198
+ /**
199
+ * A menu URL the theme can render, or null.
200
+ *
201
+ * Unsafe schemes are dropped (app/platform/safe-href). A menu item that points at one of
202
+ * the store's own resources (any type but HTTP) — or at one of `storeHosts` —
203
+ * may still arrive as an absolute store URL; it becomes a same-origin path so
204
+ * soft navigation and the active rule both work. A genuine external HTTP link
205
+ * is kept absolute.
206
+ */
207
+ export function toMenuHref(url, type, storeHosts = []) {
208
+ const safe = safeHref(url);
209
+ if (!safe)
210
+ return null;
211
+ if (!/^(https?:)?\/\//i.test(safe))
212
+ return safe;
213
+ let parsed;
214
+ try {
215
+ parsed = new URL(safe, 'https://placeholder.invalid');
216
+ }
217
+ catch {
218
+ return null;
219
+ }
220
+ const hosts = storeHosts.map((h) => h.toLowerCase());
221
+ const internal = (type != null && type !== 'HTTP') || hosts.includes(parsed.host.toLowerCase()) || hosts.includes(parsed.hostname.toLowerCase());
222
+ return internal ? `${parsed.pathname || '/'}${parsed.search}${parsed.hash}` : safe;
223
+ }
224
+ /** How specifically `url` matches `here`: path length, or -1. Same rule as the layout's nav. */
225
+ function matchLength(url, here) {
226
+ if (!url || !here || /^[a-z][a-z0-9+.-]*:|^\/\//i.test(url))
227
+ return -1;
228
+ const path = url.split(/[?#]/)[0] || '/';
229
+ if (path === '/')
230
+ return here === '/' ? 1 : -1;
231
+ const p = path.replace(/\/+$/, '');
232
+ return here === p || here.startsWith(`${p}/`) ? p.length : -1;
233
+ }
234
+ function toMenuItems(items, opts) {
235
+ const here = opts.currentPath ? opts.currentPath.split(/[?#]/)[0].replace(/(.)\/+$/, '$1') : '';
236
+ const mapped = (items ?? []).filter((it) => it && typeof it.title === 'string').map((it) => {
237
+ const url = toMenuHref(it.url, it.type, opts.storeHosts);
238
+ const children = toMenuItems(it.items, opts);
239
+ return { title: it.title, url, ...(children.length ? { items: children } : {}) };
240
+ });
241
+ if (here) {
242
+ let best = -1;
243
+ let bestLen = -1;
244
+ mapped.forEach((m, i) => {
245
+ const len = matchLength(m.url, here);
246
+ if (len > bestLen) {
247
+ best = i;
248
+ bestLen = len;
249
+ }
250
+ });
251
+ if (best >= 0)
252
+ mapped[best] = { ...mapped[best], active: true };
253
+ }
254
+ return mapped;
255
+ }
256
+ /** A runtime menu → Menu (recursive, every level). null when there is no menu. */
257
+ export function toMenu(menu, opts = {}) {
258
+ if (!menu)
259
+ return null;
260
+ return { handle: menu.handle ?? '', title: menu.title ?? '', items: toMenuItems(menu.items, opts) };
261
+ }
262
+ /** Menus by handle, for StoreContext.menus. Missing menus are left out. */
263
+ export function toMenuMap(menus, opts = {}) {
264
+ const out = {};
265
+ for (const m of menus) {
266
+ const mapped = toMenu(m, opts);
267
+ if (mapped && mapped.handle)
268
+ out[mapped.handle] = mapped;
269
+ }
270
+ return out;
271
+ }
272
+ // ── Shop ────────────────────────────────────────────────────────────────────
273
+ /** Storefront SDL payment enums → the UI's payment marks. Anything else has no mark and is left out. */
274
+ const PAYMENT_MARKS = {
275
+ VISA: 'visa',
276
+ MASTERCARD: 'mastercard',
277
+ AMERICAN_EXPRESS: 'amex',
278
+ AMEX: 'amex',
279
+ JCB: 'jcb',
280
+ DISCOVER: 'discover',
281
+ DINERS_CLUB: 'diners-club',
282
+ DINERS: 'diners-club',
283
+ UNIONPAY: 'unionpay',
284
+ UNION_PAY: 'unionpay',
285
+ CHINA_UNION_PAY: 'unionpay',
286
+ PAYPAL: 'paypal',
287
+ APPLE_PAY: 'apple-pay',
288
+ GOOGLE_PAY: 'google-pay',
289
+ ANDROID_PAY: 'google-pay',
290
+ PROMPTPAY: 'promptpay',
291
+ PROMPT_PAY: 'promptpay',
292
+ TRUEMONEY: 'truemoney',
293
+ TRUE_MONEY: 'truemoney',
294
+ };
295
+ export function toPaymentMethods(settings) {
296
+ const codes = [...(settings?.acceptedCardBrands ?? []), ...(settings?.supportedDigitalWallets ?? [])];
297
+ const out = [];
298
+ for (const c of codes) {
299
+ const mark = typeof c === 'string' ? PAYMENT_MARKS[c.toUpperCase()] : undefined;
300
+ if (mark && !out.includes(mark))
301
+ out.push(mark);
302
+ }
303
+ return out;
304
+ }
305
+ /** Dashboard network slugs the design draws a mark for → its network key. */
306
+ const SOCIAL_MARKS = {
307
+ instagram: 'instagram',
308
+ facebook: 'facebook',
309
+ twitter: 'x',
310
+ x: 'x',
311
+ tiktok: 'tiktok',
312
+ youtube: 'youtube',
313
+ };
314
+ /** Display names of the dashboard's other networks; an unknown slug is shown capitalised. */
315
+ const SOCIAL_NAMES = {
316
+ threads: 'Threads',
317
+ pinterest: 'Pinterest',
318
+ tumblr: 'Tumblr',
319
+ snapchat: 'Snapchat',
320
+ vimeo: 'Vimeo',
321
+ linkedin: 'LinkedIn',
322
+ spotify: 'Spotify',
323
+ whatsapp: 'WhatsApp',
324
+ kakaotalk: 'KakaoTalk',
325
+ };
326
+ const httpsUrl = (v) => {
327
+ if (typeof v !== 'string')
328
+ return undefined;
329
+ try {
330
+ const u = new URL(v);
331
+ return u.protocol === 'https:' && u.hostname ? u.href : undefined;
332
+ }
333
+ catch {
334
+ return undefined;
335
+ }
336
+ };
337
+ /**
338
+ * Settings → Social → the design's drawn networks (`social`) and the rest (`otherSocial`, generic
339
+ * link mark). Only https: URLs; one link per network, the first wins. Empty → both absent.
340
+ */
341
+ export function toSocial(links) {
342
+ const social = {};
343
+ const otherSocial = [];
344
+ for (const l of links ?? []) {
345
+ const platform = typeof l?.platform === 'string' ? l.platform.trim().toLowerCase() : '';
346
+ const url = httpsUrl(l?.url);
347
+ if (!platform || !url)
348
+ continue;
349
+ const mark = SOCIAL_MARKS[platform];
350
+ if (mark) {
351
+ if (!social[mark])
352
+ social[mark] = url;
353
+ }
354
+ else if (!otherSocial.some((o) => o.platform === platform)) {
355
+ otherSocial.push({ platform, label: SOCIAL_NAMES[platform] ?? platform.charAt(0).toUpperCase() + platform.slice(1), url });
356
+ }
357
+ }
358
+ return {
359
+ ...(Object.keys(social).length ? { social } : {}),
360
+ ...(otherSocial.length ? { otherSocial } : {}),
361
+ };
362
+ }
363
+ /**
364
+ * The shop + the theme's Brand settings → Shop.
365
+ *
366
+ * Name: the store name (Settings › General), else the theme's `shopName` setting
367
+ * (a fallback only — D-13). Logo: the theme's
368
+ * `logo` setting, else Settings → Brand (the same precedence as
369
+ * app/platform/safe-values `resolveLogo`, which this reuses).
370
+ */
371
+ export function toShop(shop, settings = {}) {
372
+ const name = str(shop?.name)?.trim() ?? str(settings.shopName)?.trim() ?? '';
373
+ const resolved = resolveLogo({ logo: settings.logo ?? '' }, shop?.brand ?? null);
374
+ // Dimensions are known only when the logo is the brand's own image.
375
+ const brandLogo = shop?.brand?.logo;
376
+ const logo = resolved
377
+ ? toImage({
378
+ url: resolved.url,
379
+ altText: resolved.altText,
380
+ ...(brandLogo && brandLogo.url === resolved.url ? { width: brandLogo.width, height: brandLogo.height } : {}),
381
+ })
382
+ : null;
383
+ const email = str(shop?.email ?? undefined);
384
+ const phone = str(shop?.phone ?? undefined);
385
+ const paymentMethods = toPaymentMethods(shop?.paymentSettings);
386
+ const freeShipping = toMoney(shop?.freeShippingThreshold ?? null);
387
+ return {
388
+ name,
389
+ logo,
390
+ ...(email ? { email } : {}),
391
+ ...(phone ? { phone } : {}),
392
+ ...(shop?.taxesIncluded === true ? { taxesIncluded: true } : {}),
393
+ ...(freeShipping && freeShipping.currencyCode ? { freeShippingThreshold: freeShipping } : {}),
394
+ ...(shop?.signInLinks === false ? { signInLinks: false } : {}),
395
+ ...(shop?.policyLinks ? { policyLinks: shop.policyLinks.map((p) => ({ handle: p.handle, title: p.title, url: p.url })) } : {}),
396
+ ...(shop?.consentBanner ? { consentBanner: shop.consentBanner } : {}),
397
+ ...toSocial(shop?.socialLinks),
398
+ ...(shop?.paymentSettings ? { paymentMethods } : {}),
399
+ };
400
+ }
401
+ // ── Localization ────────────────────────────────────────────────────────────
402
+ function englishLanguageName(code) {
403
+ try {
404
+ const names = new Intl.DisplayNames(['en'], { type: 'language' });
405
+ const n = names.of(code);
406
+ return n && n !== code ? n : undefined;
407
+ }
408
+ catch {
409
+ return undefined;
410
+ }
411
+ }
412
+ function currencySymbol(currency) {
413
+ if (currency?.symbol)
414
+ return currency.symbol;
415
+ const code = currency?.isoCode;
416
+ if (!code)
417
+ return '';
418
+ try {
419
+ const part = new Intl.NumberFormat('en', { style: 'currency', currency: code, currencyDisplay: 'narrowSymbol' })
420
+ .formatToParts(0)
421
+ .find((p) => p.type === 'currency');
422
+ return part?.value ?? code;
423
+ }
424
+ catch {
425
+ return code;
426
+ }
427
+ }
428
+ function toMarket(country, language) {
429
+ const code = language?.isoCode ?? '';
430
+ const english = code ? englishLanguageName(code) : undefined;
431
+ return {
432
+ countryCode: country?.isoCode ?? '',
433
+ country: country?.name ?? '',
434
+ currencyCode: country?.currency?.isoCode ?? '',
435
+ currencySymbol: currencySymbol(country?.currency),
436
+ languageCode: code,
437
+ language: language?.name ?? '',
438
+ ...(english ? { languageEnglish: english } : {}),
439
+ };
440
+ }
441
+ /**
442
+ * Localization → Localization, or null (no Markets: the picker hides).
443
+ *
444
+ * The runtime publishes countries and languages as two independent lists —
445
+ * every published language is available in every country — so `available` is
446
+ * their product. `current` is always included in `available`.
447
+ */
448
+ export function toLocalization(loc) {
449
+ if (!loc || !loc.country)
450
+ return null;
451
+ const countries = loc.availableCountries?.length ? loc.availableCountries : [loc.country];
452
+ const languages = loc.availableLanguages?.length ? loc.availableLanguages : loc.language ? [loc.language] : [null];
453
+ // The choices are the store's countries. A visitor's own country that the store does not sell to is not one of
454
+ // them: offering it (and making it "current") showed a one-market store a country picker for a country it
455
+ // cannot sell to. The current market is then the store's first country, and a one-market store shows no control.
456
+ const sells = countries.some((c) => c.isoCode === loc.country.isoCode);
457
+ const current = toMarket(sells ? loc.country : countries[0], loc.language ?? languages[0]);
458
+ const available = [];
459
+ const key = (m) => `${m.countryCode}|${m.languageCode}`;
460
+ const seen = new Set();
461
+ for (const c of countries) {
462
+ // A market that names its own languages offers only those; otherwise every published language.
463
+ const own = c.availableLanguages?.length ? c.availableLanguages : languages;
464
+ for (const l of own) {
465
+ const m = toMarket(c, l);
466
+ if (!seen.has(key(m))) {
467
+ seen.add(key(m));
468
+ available.push(m);
469
+ }
470
+ }
471
+ }
472
+ if (!seen.has(key(current)))
473
+ available.unshift(current);
474
+ return { current, available };
475
+ }
476
+ // ── Cart ────────────────────────────────────────────────────────────────────
477
+ export function toCartSummary(cart) {
478
+ const lines = cart?.lines ?? [];
479
+ const counted = lines.reduce((n, l) => n + (Number.isFinite(l?.quantity) ? l.quantity : 0), 0);
480
+ return { itemCount: typeof cart?.totalQuantity === 'number' ? cart.totalQuantity : counted, lineCount: lines.length };
481
+ }
482
+ /**
483
+ * One cart line → CartLine.
484
+ *
485
+ * A line carries id + title + image + price, its product as handle + title, and
486
+ * — when the cart source sends the whole variant (Theme ABI v2) — its options,
487
+ * compare-at and availability. No vendor and no stock. `variant.available` is
488
+ * true unless the source says otherwise: the backend accepted the line, and it
489
+ * refuses unpurchasable merchandise at add/update time.
490
+ */
491
+ export function toCartLine(line) {
492
+ const price = toMoney(line?.price);
493
+ const currency = price?.currencyCode ?? toMoney(line?.lineSubtotal)?.currencyCode ?? '';
494
+ const handle = line?.productHandle ?? '';
495
+ const quantity = Number.isFinite(line?.quantity) ? line.quantity : 0;
496
+ // A real sale only (was > now); the line's was-total is that per-unit price × quantity.
497
+ const compareAt = saleOnly(toMoney(line?.compareAtPrice), price);
498
+ return {
499
+ id: line?.id ?? '',
500
+ quantity,
501
+ product: { title: line?.title ?? '', handle, url: handle ? productUrl(handle) : '' },
502
+ variant: {
503
+ id: line?.variantId ?? '',
504
+ title: line?.variantTitle ?? '',
505
+ price: requiredMoney(price, currency),
506
+ compareAtPrice: compareAt,
507
+ available: line?.availableForSale !== false,
508
+ // A cart line never carries a stock count (Theme ABI: CartLine.merchandise has none) — absent.
509
+ selectedOptions: (line?.selectedOptions ?? []).filter((o) => o && typeof o.name === 'string').map((o) => ({ name: o.name, value: o.value ?? '' })),
510
+ image: toImage(line?.image),
511
+ },
512
+ cost: {
513
+ total: requiredMoney(toMoney(line?.lineSubtotal), currency),
514
+ compareAtTotal: compareAt ? { amount: Math.round(compareAt.amount * quantity * 1e6) / 1e6, currencyCode: compareAt.currencyCode } : null,
515
+ },
516
+ };
517
+ }
518
+ /** The full cart (cart page). `discounts` is left out: the runtime keeps no per-code amount. */
519
+ export function toCart(cart) {
520
+ const lines = (cart?.lines ?? []).filter(Boolean).map(toCartLine);
521
+ const subtotal = toMoney(cart?.subtotal);
522
+ const currency = subtotal?.currencyCode ?? lines[0]?.cost.total.currencyCode ?? '';
523
+ const note = str(cart?.note ?? undefined);
524
+ return {
525
+ id: cart?.id ?? '',
526
+ lines,
527
+ ...(note ? { note } : {}),
528
+ itemCount: toCartSummary(cart).itemCount,
529
+ subtotal: requiredMoney(subtotal, currency),
530
+ total: requiredMoney(toMoney(cart?.total) ?? subtotal, currency),
531
+ };
532
+ }
533
+ // ── Content ─────────────────────────────────────────────────────────────────
534
+ /** A page → the UI's page-body shape (StoreContext.currentPage / pages). */
535
+ export function toPage(page) {
536
+ if (!page)
537
+ return null;
538
+ return { title: page.title ?? '', html: page.body ?? '' };
539
+ }
540
+ /**
541
+ * An article → Article, or null when its blog is unknown (no URL can be built —
542
+ * search results arrive without one). Pass the blog handle when the caller
543
+ * knows it.
544
+ */
545
+ export function toArticle(a, blogHandle) {
546
+ if (!a)
547
+ return null;
548
+ const blog = str(a.blogHandle) ?? str(blogHandle);
549
+ if (!blog || !a.handle)
550
+ return null;
551
+ const excerpt = str(a.excerpt ?? undefined);
552
+ const author = str(a.author ?? undefined);
553
+ return {
554
+ id: a.id ?? a.handle,
555
+ handle: a.handle,
556
+ title: a.title ?? '',
557
+ ...(excerpt ? { excerpt } : {}),
558
+ ...(typeof a.contentHtml === 'string' ? { contentHtml: a.contentHtml } : {}),
559
+ url: articleUrl(blog, a.handle),
560
+ image: toImage(a.image),
561
+ ...(author ? { author } : {}),
562
+ publishedAt: a.publishedAt ?? '',
563
+ ...(a.tags?.length ? { tags: [...a.tags] } : {}),
564
+ blogHandle: blog,
565
+ };
566
+ }
567
+ export function toBlog(blog) {
568
+ if (!blog || !blog.handle)
569
+ return null;
570
+ return {
571
+ id: blog.id ?? blog.handle,
572
+ handle: blog.handle,
573
+ title: blog.title ?? '',
574
+ url: blogUrl(blog.handle),
575
+ articles: (blog.articles ?? []).map((a) => toArticle(a, blog.handle)).filter((a) => Boolean(a)),
576
+ };
577
+ }
578
+ /**
579
+ * A shop policy → Policy. The URL is the theme's own policy route (the runtime's
580
+ * `url` may be absolute). `bodyHtml` is '' when the payload carries no body.
581
+ */
582
+ export function toPolicy(p) {
583
+ if (!p || !p.handle)
584
+ return null;
585
+ return { handle: p.handle, title: p.title ?? '', bodyHtml: p.body ?? '', url: policyUrl(p.handle) };
586
+ }
587
+ /** Every published policy by handle, for StoreContext.policies. */
588
+ export function toPolicies(shop) {
589
+ const out = {};
590
+ const ps = shop?.policies;
591
+ for (const p of [ps?.privacy, ps?.refund, ps?.termsOfService, ps?.shipping, ps?.subscription]) {
592
+ const mapped = toPolicy(p);
593
+ if (mapped)
594
+ out[mapped.handle] = mapped;
595
+ }
596
+ return out;
597
+ }
598
+ /** Store locations. The platform returns a postal address only — no hours, email, image or coordinates. */
599
+ export function toLocations(list) {
600
+ return (list ?? []).filter(Boolean).map((l) => {
601
+ const a = l.address;
602
+ const cityLine = [a?.city, a?.province, a?.postalCode].filter((s) => Boolean(s && s.trim())).join(' ');
603
+ const address = [a?.address, cityLine, a?.country].filter((s) => Boolean(s && s.trim()));
604
+ const phone = str(a?.phone ?? undefined);
605
+ return { id: l.id ?? '', name: l.name ?? '', address, ...(phone ? { phone } : {}) };
606
+ });
607
+ }
608
+ // ── Search + listing ────────────────────────────────────────────────────────
609
+ /**
610
+ * Search → SearchResults. `total` is the backend's count across every type.
611
+ * Articles whose blog is unknown are left out (see toArticle).
612
+ */
613
+ export function toSearchResults(query, r) {
614
+ return {
615
+ query: query ?? '',
616
+ products: toProducts(r?.products),
617
+ articles: (r?.articles ?? []).map((a) => toArticle(a)).filter((a) => Boolean(a)),
618
+ pages: (r?.pages ?? []).filter((p) => p && p.handle).map((p) => ({ title: p.title ?? '', url: pageUrl(p.handle) })),
619
+ total: typeof r?.totalCount === 'number' ? r.totalCount : 0,
620
+ };
621
+ }
622
+ /**
623
+ * Listing filters → Facets. List filters map value-for-value; `active` is set
624
+ * for the values whose `input` the shopper has applied. A PRICE_RANGE filter
625
+ * becomes a price facet only when its input carries the store's bounds and a
626
+ * currency is known.
627
+ */
628
+ export function toFacets(filters, opts = {}) {
629
+ const active = new Set(opts.activeInputs ?? []);
630
+ const out = [];
631
+ for (const f of filters ?? []) {
632
+ if (!f)
633
+ continue;
634
+ if (f.type === 'PRICE_RANGE') {
635
+ const bounds = priceOf(f.values?.[0]?.input);
636
+ if (!bounds || !opts.currencyCode)
637
+ continue;
638
+ const applied = [...active].map(priceOf).find(Boolean);
639
+ out.push({
640
+ id: f.id,
641
+ label: f.label,
642
+ type: 'price',
643
+ range: {
644
+ min: bounds.min ?? 0,
645
+ max: bounds.max ?? bounds.min ?? 0,
646
+ ...(applied?.min != null ? { from: applied.min } : {}),
647
+ ...(applied?.max != null ? { to: applied.max } : {}),
648
+ currencyCode: opts.currencyCode,
649
+ },
650
+ });
651
+ continue;
652
+ }
653
+ out.push({
654
+ id: f.id,
655
+ label: f.label,
656
+ type: 'list',
657
+ values: (f.values ?? []).map((v) => ({ id: v.id, label: v.label, count: Number.isFinite(v.count) ? v.count : 0, active: active.has(v.input) })),
658
+ });
659
+ }
660
+ return out;
661
+ }
662
+ function priceOf(input) {
663
+ if (!input)
664
+ return null;
665
+ try {
666
+ const parsed = JSON.parse(input);
667
+ const p = parsed?.price;
668
+ if (!p || typeof p !== 'object')
669
+ return null;
670
+ const min = typeof p.min === 'number' ? p.min : undefined;
671
+ const max = typeof p.max === 'number' ? p.max : undefined;
672
+ return min == null && max == null ? null : { min, max };
673
+ }
674
+ catch {
675
+ return null;
676
+ }
677
+ }
678
+ /**
679
+ * The trail for a route. The last item is the current page and carries no URL.
680
+ * A route whose own title is unknown returns [] rather than a trail that ends
681
+ * on a link — the breadcrumbs section then renders nothing.
682
+ */
683
+ export function toBreadcrumbs(input) {
684
+ const home = str(input?.labels?.home);
685
+ if (!home)
686
+ return [];
687
+ const m = matchRoute(input.pathname || '/');
688
+ const root = { title: home, url: '/' };
689
+ const title = (t) => str(t?.title);
690
+ const label = (l) => (str(l) ? [root, { title: l }] : []);
691
+ switch (m.template) {
692
+ case 'index':
693
+ return [{ title: home }];
694
+ case 'list-collections':
695
+ return label(input.labels.collections);
696
+ case 'search':
697
+ return label(input.labels.search);
698
+ case 'cart':
699
+ return label(input.labels.cart);
700
+ case 'account':
701
+ return label(input.labels.account);
702
+ case 'collection': {
703
+ const t = title(input.collection);
704
+ if (!t)
705
+ return [];
706
+ const mid = str(input.labels.collections) ? [{ title: input.labels.collections, url: '/collections' }] : [];
707
+ return [root, ...mid, { title: t }];
708
+ }
709
+ case 'product': {
710
+ const t = title(input.product);
711
+ if (!t)
712
+ return [];
713
+ const c = input.collection;
714
+ const via = c?.handle && str(c.title) ? [{ title: c.title, url: collectionUrl(c.handle) }] : [];
715
+ return [root, ...via, { title: t }];
716
+ }
717
+ case 'page': {
718
+ const t = title(input.page);
719
+ return t ? [root, { title: t }] : [];
720
+ }
721
+ case 'policy': {
722
+ const t = title(input.policy);
723
+ return t ? [root, { title: t }] : [];
724
+ }
725
+ case 'blog': {
726
+ const t = title(input.blog);
727
+ return t ? [root, { title: t }] : [];
728
+ }
729
+ case 'article': {
730
+ const t = title(input.article);
731
+ if (!t)
732
+ return [];
733
+ const b = title(input.blog);
734
+ const via = b && m.blogHandle ? [{ title: b, url: blogUrl(m.blogHandle) }] : [];
735
+ return [root, ...via, { title: t }];
736
+ }
737
+ default:
738
+ return [];
739
+ }
740
+ }
741
+ /**
742
+ * Whether the cookie banner shows to a shopper who has not decided yet (Settings › Customer privacy,
743
+ * contract rev 2): the platform's legal floor first (EEA, UK, unknown location — or a platform that
744
+ * does not say), then the merchant's switch — everywhere with "Use automated settings", else only in
745
+ * the regions the merchant chose. No merchant config (older data) = shown, as before.
746
+ */
747
+ export function consentBannerShows(readout, banner) {
748
+ if (readout.regionRequiresBanner !== false)
749
+ return true;
750
+ if (!banner)
751
+ return true;
752
+ if (!banner.enabled)
753
+ return false;
754
+ if (banner.automated)
755
+ return true;
756
+ const country = readout.geo?.country?.toUpperCase();
757
+ const region = readout.geo?.region?.toUpperCase();
758
+ return Boolean((country && banner.regions.includes(country)) || (region && banner.regions.includes(region)));
759
+ }