@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,577 @@
1
+ import * as convert from './convert.js';
2
+ import { searchOrder } from './data-api.js';
3
+ import { filterRequests, listingQueryOf, stateFromQuery } from '../runtime/render/listing-query.js';
4
+ /** Hard limits (theme-abi-v2.md §8). The host enforces them; the theme plans inside them. */
5
+ const MAX_DATA_CALLS = 4;
6
+ /** Products per listing request — the page size platform/runtime/render/product-listing.ts asks for. */
7
+ const LISTING_FIRST = 24;
8
+ /** Product tags are the merchant's internal labels, never a shopper filter (product-listing.ts). */
9
+ const HIDDEN_FACETS = new Set(['filter.tag']);
10
+ /**
11
+ * The listing state of this request (`?sort=` and `?filter.*=`, platform/runtime/render/listing-query.ts):
12
+ * only on the collection route. `sort` may also arrive as the ABI's query-derived route param.
13
+ * Cache-safe for the same reason as the search query: a request with a query string is neither served
14
+ * from nor stored in the shared cache (§5.1).
15
+ */
16
+ export function listingQueryOfRequest(ctx) {
17
+ if (ctx.route.kind !== 'collection')
18
+ return '';
19
+ let search;
20
+ try {
21
+ search = new URL(ctx.request.url).searchParams;
22
+ }
23
+ catch {
24
+ search = new URLSearchParams();
25
+ }
26
+ const sort = ctx.route.params['sort'];
27
+ if (typeof sort === 'string' && sort && !search.has('sort'))
28
+ search.set('sort', sort);
29
+ return listingQueryOf(search);
30
+ }
31
+ /** Results per type the search page loads — the same page size sections/SearchResults.tsx asks the browser wire for. */
32
+ const SEARCH_FIRST = 48;
33
+ const normQuery = (q) => q.trim().toLowerCase();
34
+ /**
35
+ * The search query of this request: the `q` route param (theme-abi-v2.md §2.1), else — for a
36
+ * gateway that does not forward it yet — the `q` of the request's own query string. Only on the
37
+ * search route. Shopper-typed text: every place that prints it escapes it (React does).
38
+ * Reading the raw query is cache-safe: a request with any query string is neither served from nor
39
+ * stored in the shared cache (§5.1).
40
+ */
41
+ export function searchQueryOf(ctx) {
42
+ if (ctx.route.kind !== 'search')
43
+ return null;
44
+ const param = ctx.route.params['q'];
45
+ if (typeof param === 'string')
46
+ return param;
47
+ try {
48
+ return new URL(ctx.request.url).searchParams.get('q');
49
+ }
50
+ catch {
51
+ return null;
52
+ }
53
+ }
54
+ /**
55
+ * The search page's sort (`?sort=`, the ABI's query-derived `sort` route param on the search kind):
56
+ * a sort id lib/abi/data-api.ts `searchOrder` knows, else null (relevance). Only on the search route.
57
+ */
58
+ export function searchSortOf(ctx) {
59
+ if (ctx.route.kind !== 'search')
60
+ return null;
61
+ let sort = ctx.route.params['sort'];
62
+ if (typeof sort !== 'string') {
63
+ try {
64
+ sort = new URL(ctx.request.url).searchParams.get('sort') ?? undefined;
65
+ }
66
+ catch {
67
+ sort = undefined;
68
+ }
69
+ }
70
+ return searchOrder(sort) ? sort : null;
71
+ }
72
+ /**
73
+ * The variant a product URL names (`/products/<handle>?variant=<id>`): a shared link, or checkout's way
74
+ * back to the product. Only on the product route; the section opens on it only when it is a variant
75
+ * of that product (ProductDetails ignores any other id). Read from the request's own query string:
76
+ * a request with a query is never served from or stored in the shared cache (§5.1).
77
+ */
78
+ export function variantOf(ctx) {
79
+ if (ctx.route.kind !== 'product')
80
+ return null;
81
+ let v = ctx.route.params['variant'];
82
+ if (typeof v !== 'string') {
83
+ try {
84
+ v = new URL(ctx.request.url).searchParams.get('variant');
85
+ }
86
+ catch {
87
+ v = null;
88
+ }
89
+ }
90
+ const id = typeof v === 'string' ? v.trim() : '';
91
+ return id && id.length <= 200 && /^[A-Za-z0-9_:/.\-]+$/.test(id) ? id : null;
92
+ }
93
+ /** The reasons the platform router sends a cart permalink it could not open to `/cart?cart_link=` with. */
94
+ const CART_LINK_REASONS = new Set(['unavailable', 'failed']);
95
+ /**
96
+ * Why a cart permalink (`/cart/<variant>:<qty>`) landed on the cart page: the router's
97
+ * `?cart_link=` reason (apps/storefront/router/cart-permalink.mjs), else null. Only on the cart
98
+ * route, and only a reason the router sends. The cart route is a private response already (§5).
99
+ */
100
+ export function cartLinkOf(ctx) {
101
+ if (ctx.route.kind !== 'cart')
102
+ return null;
103
+ try {
104
+ const reason = new URL(ctx.request.url).searchParams.get('cart_link');
105
+ return reason && CART_LINK_REASONS.has(reason) ? reason : null;
106
+ }
107
+ catch {
108
+ return null;
109
+ }
110
+ }
111
+ /**
112
+ * The route params the page renders with: the route's own, plus `q` (`searchQueryOf`), its `sort`
113
+ * (`searchSortOf`) and `cart_link` (`cartLinkOf`) when only the request's query string has them.
114
+ * They travel in the page state, so the hydrating browser builds the same location.
115
+ */
116
+ export function pageParamsOf(ctx, searchQuery, searchSort = null) {
117
+ const params = { ...ctx.route.params };
118
+ if (searchQuery !== null && params['q'] === undefined)
119
+ params['q'] = searchQuery;
120
+ // the sort the page was loaded with — the same id the browser's store keys its search on
121
+ if (searchSort !== null && params['sort'] === undefined)
122
+ params['sort'] = searchSort;
123
+ const cartLink = cartLinkOf(ctx);
124
+ if (cartLink !== null)
125
+ params['cart_link'] = cartLink;
126
+ const variant = variantOf(ctx);
127
+ if (variant !== null)
128
+ params['variant'] = variant;
129
+ return params;
130
+ }
131
+ const RESOURCE_KINDS = new Set(['collection', 'product', 'menu', 'page', 'blog']);
132
+ /** Capability each route kind's snapshot resource needs (capability-security §2 / render-context Capability). */
133
+ const RESOURCE_CAPABILITY = {
134
+ product: 'data:catalog', collection: 'data:catalog', collections: 'data:catalog',
135
+ page: 'data:content', blog: 'data:content', article: 'data:content', policy: 'data:content',
136
+ search: 'data:search', cart: 'data:cart', customer: 'data:customer',
137
+ };
138
+ /** Capability each round-2 call needs. */
139
+ const NEED_CAPABILITY = {
140
+ collection: 'data:catalog', product: 'data:catalog', page: 'data:content', blog: 'data:content', menu: 'data:shop',
141
+ };
142
+ /** Sections that call `allCollections()`. */
143
+ /** Sections that show recommendations for the route's product. */
144
+ const SHOWS_RECOMMENDATIONS = new Set(['product-recommendations']);
145
+ const LISTS_ALL_COLLECTIONS = new Set(['collection-list', 'collection-links', 'not-found', 'search-results', 'cart-items']);
146
+ function walk(nodes, visit) {
147
+ for (const n of nodes) {
148
+ visit(n);
149
+ if (Array.isArray(n.blocks))
150
+ walk(n.blocks, visit);
151
+ }
152
+ }
153
+ /** Resource settings on this page (effective value = node setting, else the attribute default). */
154
+ export function pageNeeds(nodes, defs) {
155
+ const needs = [];
156
+ /** The menu handles the header shows: when every one is empty the drawer lists the collections instead. */
157
+ const headerMenus = [];
158
+ let listsCollections = false;
159
+ let showsLocale = false;
160
+ let showsAccount = false;
161
+ let showsRecommendations = false;
162
+ walk(nodes, (n) => {
163
+ const def = defs(n.type);
164
+ if (!def)
165
+ return;
166
+ if (LISTS_ALL_COLLECTIONS.has(n.type))
167
+ listsCollections = true;
168
+ if (SHOWS_RECOMMENDATIONS.has(n.type))
169
+ showsRecommendations = true;
170
+ const settings = (n.settings ?? {});
171
+ // The header's locale control and the footer's region control (on by default) both list countries.
172
+ if ((n.type === 'header' || n.type === 'footer') && (settings.showLocale ?? def.attributes?.showLocale?.default) === true)
173
+ showsLocale = true;
174
+ if (n.type === 'header' && (settings.showAccount ?? def.attributes?.showAccount?.default) !== false)
175
+ showsAccount = true;
176
+ for (const [key, spec] of Object.entries(def.attributes ?? {})) {
177
+ if (!RESOURCE_KINDS.has(spec.type))
178
+ continue;
179
+ const value = settings[key] ?? spec.default;
180
+ if (typeof value !== 'string' || !value.trim())
181
+ continue;
182
+ needs.push({ kind: spec.type, handle: value.trim(), ref: `${n.id}.${key}` });
183
+ if (n.type === 'header' && spec.type === 'menu')
184
+ headerMenus.push(value.trim());
185
+ }
186
+ });
187
+ return { needs, listsCollections, showsLocale, showsAccount, showsRecommendations, headerMenus };
188
+ }
189
+ function languageName(code, inLanguage) {
190
+ try {
191
+ return new Intl.DisplayNames([inLanguage], { type: 'language' }).of(code) ?? code;
192
+ }
193
+ catch {
194
+ return code;
195
+ }
196
+ }
197
+ function regionName(code, inLanguage) {
198
+ try {
199
+ return new Intl.DisplayNames([inLanguage], { type: 'region' }).of(code) ?? code;
200
+ }
201
+ catch {
202
+ return code;
203
+ }
204
+ }
205
+ /**
206
+ * `ctx.locale` → Nova's Localization. `locale.country` is a personalising input (§2): it is read
207
+ * only when the page shows the country switcher, and the caller hints `vary: ['x-tq-country']`
208
+ * for exactly that case. Otherwise the country stays blank and nothing on the page depends on it.
209
+ */
210
+ export function localizationOf(ctx, shipsTo, readCountry) {
211
+ const lang = ctx.locale.language;
212
+ const currency = { isoCode: ctx.locale.currency };
213
+ const market = { id: ctx.locale.market, handle: ctx.locale.market, name: ctx.locale.market };
214
+ const country = readCountry ? ctx.locale.country : '';
215
+ const languages = [...new Set(ctx.locale.availableLanguages)];
216
+ const language = (l) => ({ isoCode: l, name: languageName(l, l) });
217
+ // The store's active markets, when the platform names them (`ctx.locale.markets`, optional): each
218
+ // country gets its own market, currency and languages. Absent ⇒ one market for every country.
219
+ const byCountry = new Map();
220
+ for (const m of marketsOf(ctx)) {
221
+ const own = { id: m.id, handle: m.id, name: m.id };
222
+ const langs = [...new Set(m.languages)].filter((l) => languages.length === 0 || languages.includes(l));
223
+ for (const c of m.countries) {
224
+ const iso = c.toUpperCase();
225
+ if (!/^[A-Z]{2}$/.test(iso) || byCountry.has(iso))
226
+ continue;
227
+ byCountry.set(iso, { isoCode: iso, name: regionName(iso, lang), currency: { isoCode: m.currency }, market: own, ...(langs.length ? { availableLanguages: langs.map(language) } : {}) });
228
+ }
229
+ }
230
+ const countryOf = (c) => byCountry.get(c) ?? { isoCode: c, name: c ? regionName(c, lang) : '', currency, market };
231
+ const countries = byCountry.size ? [...byCountry.keys()] : shipsTo;
232
+ return {
233
+ country: country ? countryOf(country) : { isoCode: '', name: '', currency, market },
234
+ availableCountries: readCountry ? countries.map(countryOf) : [],
235
+ language: language(lang),
236
+ availableLanguages: languages.map(language),
237
+ };
238
+ }
239
+ /** `ctx.locale.markets`, read defensively: only well-formed entries; [] when the platform sends none. */
240
+ export function marketsOf(ctx) {
241
+ const raw = ctx.locale.markets;
242
+ if (!Array.isArray(raw))
243
+ return [];
244
+ const strings = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === 'string' && x.length > 0) : []);
245
+ return raw.flatMap((m) => {
246
+ const r = m;
247
+ if (!r || typeof r.id !== 'string' || !r.id || typeof r.currency !== 'string' || !/^[A-Z]{3}$/.test(r.currency))
248
+ return [];
249
+ return [{ id: r.id, currency: r.currency, countries: strings(r.countries), languages: strings(r.languages) }];
250
+ });
251
+ }
252
+ /** Load a page's data through `ctx.data`. */
253
+ export async function loadPageData(ctx, nodes, defs,
254
+ /** Menu handles named by GLOBAL settings (header/footer menu pickers), not by a node. */
255
+ settingMenus = [],
256
+ /**
257
+ * The search query this page renders (`searchQueryOf`). When the snapshot answered a different
258
+ * query — a gateway that does not forward `q` as a route param answers the empty one — the
259
+ * search is run once in round 2, so the server HTML holds the results the browser would show.
260
+ */
261
+ searchQuery = null,
262
+ /** The search sort of this request (`searchSortOf`); null = relevance. */
263
+ searchSort = null,
264
+ /** The collection listing's URL state (`listingQueryOfRequest`); '' = none. */
265
+ listingQuery = '',
266
+ /**
267
+ * What the theme asks the plan for regardless of its section types (`RenderOptions.storefront.plan`), and the
268
+ * data calls the caller makes beside this plan in round 1 (`reservedCalls`). Absent: the plan reads only the
269
+ * section conventions (`pageNeeds`), exactly as before.
270
+ */
271
+ plan) {
272
+ const found = pageNeeds(nodes, defs);
273
+ const { needs, headerMenus } = found;
274
+ const listsAll = found.listsCollections || plan?.collections === true;
275
+ const showsLocale = found.showsLocale || plan?.localization === true;
276
+ const showsAccount = found.showsAccount || plan?.account === true;
277
+ const showsRecommendations = found.showsRecommendations || plan?.recommendations === true;
278
+ for (const handle of settingMenus)
279
+ needs.push({ kind: 'menu', handle, ref: `settings.${handle}` });
280
+ let calls = plan?.reservedCalls ?? 0;
281
+ const can = (cap) => ctx.capabilities.has(cap);
282
+ // §3 (rev 2026-10-07, IA-2): snapshot() never throws for a denied capability — the resource comes
283
+ // back null and `denied` names the capability. Hosts built before that revision (conformance
284
+ // runner 1966cca among them) still throw, so when the route's resource capability is not in
285
+ // ctx.capabilities Nova does not ask for it at all: shop + menus in one round, and the template
286
+ // renders its "nothing here" state. Either way nothing outside the grant is ever called.
287
+ const resourceCap = RESOURCE_CAPABILITY[ctx.route.kind];
288
+ let snapshot;
289
+ if (!resourceCap || can(resourceCap)) {
290
+ calls++;
291
+ // Opt-in answers (Theme ABI, storefront-query rev 2.19): the collection page's facets, and the
292
+ // product page's collections (its breadcrumb). Asked for only on the route that shows them.
293
+ const optIn = ctx.route.kind === 'collection' ? { facets: true } : ctx.route.kind === 'product' ? { productCollections: true } : {};
294
+ // `policyLinks` (theme-abi alpha.14): the store's published policies on every page — the footer lists
295
+ // them when its legal menu is empty, and the cookie banner links the privacy policy only when published.
296
+ // A data plane from before that member refuses an unknown option (strict `opts`): ask once more without it,
297
+ // and the footer and banner keep today's behaviour.
298
+ const ask = (extra) => ctx.data.snapshot({ resolve: 'all', ...optIn, ...extra });
299
+ try {
300
+ snapshot = await ask({ policyLinks: true });
301
+ }
302
+ catch (e) {
303
+ const name = e?.name;
304
+ if (name === 'DataLimitError' || name === 'CapabilityError')
305
+ throw e;
306
+ calls++;
307
+ snapshot = await ask({});
308
+ }
309
+ }
310
+ else {
311
+ calls += 2;
312
+ const [shopRecord, menuList] = await Promise.all([ctx.data.shop.get(), ctx.data.shop.menus()]);
313
+ snapshot = {
314
+ shop: shopRecord,
315
+ menus: Object.fromEntries(menuList.map((m) => [m.handle, m])),
316
+ resource: { kind: 'not_found' },
317
+ refs: {},
318
+ pixels: [],
319
+ };
320
+ }
321
+ const products = {};
322
+ const collections = {};
323
+ const pages = {};
324
+ const blogs = {};
325
+ const articles = {};
326
+ const menus = {};
327
+ const policies = [];
328
+ let collectionList = null;
329
+ let search = null;
330
+ let policyHandle = null;
331
+ let cart = null;
332
+ for (const m of Object.values(snapshot.menus ?? {}))
333
+ menus[m.handle] = convert.menu(m);
334
+ const putProduct = (p) => { if (p)
335
+ products[p.handle] = convert.product(p); };
336
+ const putCollection = (c) => {
337
+ if (!c)
338
+ return;
339
+ const nc = convert.collection(c);
340
+ collections[c.handle] = nc;
341
+ for (const p of c.products?.nodes ?? [])
342
+ if (!products[p.handle])
343
+ products[p.handle] = convert.product(p);
344
+ };
345
+ // A `catalog.collections()` entry is a CARD: the platform sends it with an empty product page
346
+ // (`products.nodes: []`, the real `totalCount`). It must never replace a collection a section
347
+ // loaded with its products — that emptied the featured collection on every page that also lists
348
+ // collections (home with a collection list, the cart), and the section then rendered nothing.
349
+ const putCard = (c) => { if (!collections[c.handle])
350
+ collections[c.handle] = convert.collection(c); };
351
+ /** A listed card answers a collection need only when it carries the products (or there are none). */
352
+ const cardAnswers = (handle) => collectionList?.some((c) => c.handle === handle && ((c.products?.length ?? 0) > 0 || c.productsCount === 0)) ?? false;
353
+ const putPage = (p) => { if (p)
354
+ pages[p.handle] = convert.page(p); };
355
+ const putBlog = (b) => {
356
+ if (!b)
357
+ return;
358
+ blogs[b.handle] = convert.blog(b);
359
+ for (const a of b.articles?.nodes ?? [])
360
+ articles[`${b.handle}/${a.handle}`] = { ...convert.article(a), blogHandle: b.handle };
361
+ };
362
+ const putArticle = (a, blogHandle) => { if (a)
363
+ articles[`${blogHandle}/${a.handle}`] = { ...convert.article(a), blogHandle }; };
364
+ const r = snapshot.resource;
365
+ switch (r.kind) {
366
+ case 'product':
367
+ putProduct(r.product);
368
+ break;
369
+ case 'collection':
370
+ putCollection(r.collection);
371
+ break;
372
+ case 'collections':
373
+ if (r.collections) {
374
+ collectionList = r.collections.nodes.map(convert.collection);
375
+ r.collections.nodes.forEach(putCard);
376
+ }
377
+ break;
378
+ case 'page':
379
+ putPage(r.page);
380
+ break;
381
+ case 'blog':
382
+ putBlog(r.blog);
383
+ break;
384
+ case 'article':
385
+ putBlog(r.blog);
386
+ if (r.article)
387
+ putArticle(r.article, r.blog?.handle ?? ctx.route.blogHandle ?? '');
388
+ break;
389
+ case 'policy':
390
+ if (r.policy) {
391
+ policies.push(r.policy);
392
+ policyHandle = r.policy.handle;
393
+ }
394
+ break;
395
+ // The snapshot applies the route's `sort` param (rev 2.19). When the sort came only from the URL (a gateway
396
+ // that does not forward it), the snapshot's order is relevance: it is not used, and round 2 asks for the sort.
397
+ case 'search':
398
+ if (r.result && (!searchSort || typeof ctx.route.params['sort'] === 'string')) {
399
+ search = { query: r.result.query, ...(searchSort ? { sort: searchSort } : {}), result: convert.searchResults(r.result) };
400
+ r.result.products.nodes.forEach(putProduct);
401
+ }
402
+ break;
403
+ case 'cart':
404
+ cart = r.cart;
405
+ break;
406
+ default: break;
407
+ }
408
+ // refs the platform resolved (`${nodeId}.${settingKey}`)
409
+ const missing = [];
410
+ for (const need of needs) {
411
+ if (need.kind === 'menu' && menus[need.handle])
412
+ continue;
413
+ const has = Object.prototype.hasOwnProperty.call(snapshot.refs ?? {}, need.ref);
414
+ if (has) {
415
+ const v = snapshot.refs[need.ref];
416
+ if (v && need.kind === 'collection')
417
+ putCollection(v);
418
+ else if (v && need.kind === 'product')
419
+ putProduct(v);
420
+ else if (v && need.kind === 'menu')
421
+ menus[need.handle] = convert.menu(v);
422
+ else if (v && need.kind === 'page')
423
+ putPage(v);
424
+ else if (v && need.kind === 'blog')
425
+ putBlog(v);
426
+ continue;
427
+ }
428
+ if (need.kind === 'collection' && collections[need.handle])
429
+ continue;
430
+ if (need.kind === 'product' && products[need.handle])
431
+ continue;
432
+ if (need.kind === 'page' && pages[need.handle])
433
+ continue;
434
+ if (need.kind === 'blog' && blogs[need.handle])
435
+ continue;
436
+ if (!missing.some((m) => m.kind === need.kind && m.handle === need.handle))
437
+ missing.push(need);
438
+ }
439
+ // A header whose menu has no items (a new store's empty `main-menu`) lists the store's collections in
440
+ // its mobile drawer, so they are loaded too. Decided on what round 1 answered: a menu it did not
441
+ // answer is fetched in round 2 alongside, and may well be empty.
442
+ const headerMenuEmpty = headerMenus.length > 0 && headerMenus.every((h) => !(menus[h]?.items?.length));
443
+ const listsCollections = listsAll || headerMenuEmpty;
444
+ // round 2 — started together (one round), never past the hard call limit
445
+ const round = [];
446
+ const unresolved = [];
447
+ const take = () => (calls < MAX_DATA_CALLS ? (calls++, true) : false);
448
+ const missingMenus = missing.filter((m) => m.kind === 'menu').map((m) => m.handle);
449
+ if (missingMenus.length) {
450
+ if (take())
451
+ round.push(ctx.data.shop.menus(missingMenus).then((list) => { for (const m of list)
452
+ menus[m.handle] = convert.menu(m); }));
453
+ else
454
+ unresolved.push(...missingMenus.map((h) => `menu:${h}`));
455
+ }
456
+ const wantQuery = ctx.route.kind === 'search' ? (searchQuery ?? '').trim() : '';
457
+ const order = searchOrder(searchSort);
458
+ if (wantQuery && normQuery(search?.query ?? '') !== normQuery(wantQuery) && can('data:search')) {
459
+ if (take()) {
460
+ round.push(ctx.data.catalog.search({ query: wantQuery, first: SEARCH_FIRST, types: ['product', 'page', 'article'], ...(order ? { sortKey: order.sortKey, ...(order.reverse ? { reverse: true } : {}) } : {}) }).then((r) => {
461
+ // Keyed by the query (and sort) the page asked for, so `searchSync(q, sort)` matches on server and browser alike.
462
+ search = { query: wantQuery, ...(searchSort ? { sort: searchSort } : {}), result: convert.searchResults(r) };
463
+ r.products.nodes.forEach(putProduct);
464
+ }).catch((e) => {
465
+ // A breach or a missing capability is the host's to report (entry.abi.tsx). Anything else —
466
+ // a shopper query the data plane refuses (over 1,024 code units ⇒ invalid_argument) — must
467
+ // not take the page down: the search renders its "no results" state. The empty answer is
468
+ // recorded for this query so the browser's first render is the same "no results", not a
469
+ // skeleton that differs from the server HTML.
470
+ const name = e?.name;
471
+ if (name === 'DataLimitError' || name === 'CapabilityError')
472
+ throw e;
473
+ ctx.log.warn('page data: search unavailable', { error: String(e?.message ?? e) });
474
+ const none = { nodes: [], pageInfo: { hasNextPage: false } };
475
+ search = { query: wantQuery, ...(searchSort ? { sort: searchSort } : {}), result: convert.searchResults({ query: wantQuery, products: none, pages: none, articles: none, collections: none }) };
476
+ }));
477
+ }
478
+ else
479
+ unresolved.push('search');
480
+ }
481
+ // A shared filtered collection URL: the first filtered page, when one request answers it.
482
+ let listingSeed = null;
483
+ const listed = ctx.route.kind === 'collection' && ctx.route.handle ? collections[ctx.route.handle] : undefined;
484
+ if (listingQuery && listed && can('data:catalog')) {
485
+ const facets = (listed.filters ?? []).filter((f) => !HIDDEN_FACETS.has(f.id));
486
+ const requests = filterRequests(stateFromQuery(listingQuery, facets), facets, 2);
487
+ const only = requests.length === 1 ? requests[0] : null;
488
+ const filters = only ? convert.abiFilters(only) : [];
489
+ if (only && filters.length) {
490
+ const handle = listed.handle;
491
+ if (take()) {
492
+ round.push(ctx.data.catalog.collection(handle, { productsFirst: LISTING_FIRST, filters }).then((c) => {
493
+ if (!c)
494
+ return;
495
+ listingSeed = { handle, key: JSON.stringify(only), products: (c.products?.nodes ?? []).map(convert.product), pageInfo: { hasNextPage: Boolean(c.products?.pageInfo?.hasNextPage), endCursor: c.products?.pageInfo?.endCursor ?? null } };
496
+ }));
497
+ }
498
+ else
499
+ unresolved.push(`listing:${handle}`);
500
+ }
501
+ }
502
+ const recommendations = {};
503
+ const recFor = ctx.route.kind === 'product' ? ctx.route.handle : undefined;
504
+ if (showsRecommendations && recFor && products[recFor] && can('data:products.recommendations')) {
505
+ if (take())
506
+ round.push(ctx.data.catalog.recommendations(recFor, 'related', 8).then((list) => { recommendations[recFor] = list.map(convert.product); }));
507
+ else
508
+ unresolved.push(`recommendations:${recFor}`);
509
+ }
510
+ if (listsCollections && !collectionList && can('data:catalog')) {
511
+ if (take())
512
+ round.push(ctx.data.catalog.collections({ first: 50 }).then((c) => { collectionList = c.nodes.map(convert.collection); c.nodes.forEach(putCard); }));
513
+ else
514
+ unresolved.push('collections');
515
+ }
516
+ for (const need of missing) {
517
+ if (need.kind === 'menu')
518
+ continue;
519
+ if (need.kind === 'collection' && cardAnswers(need.handle))
520
+ continue;
521
+ const call = need.kind === 'collection' ? () => ctx.data.catalog.collection(need.handle).then(putCollection)
522
+ : need.kind === 'product' ? () => ctx.data.catalog.product(need.handle).then(putProduct)
523
+ : need.kind === 'page' ? () => ctx.data.content.page(need.handle).then(putPage)
524
+ : () => ctx.data.content.blog(need.handle).then(putBlog);
525
+ if (!can(NEED_CAPABILITY[need.kind]))
526
+ unresolved.push(`${need.kind}:${need.handle}`);
527
+ else if (take())
528
+ round.push(call());
529
+ else
530
+ unresolved.push(`${need.kind}:${need.handle}`);
531
+ }
532
+ if (round.length)
533
+ await Promise.all(round);
534
+ const denied = snapshot.denied ?? [];
535
+ if (denied.length)
536
+ ctx.log.info('page data: capabilities denied by the store grant', { denied });
537
+ if (unresolved.length)
538
+ ctx.log.warn('page data: resources left unresolved inside the data-call limit', { unresolved });
539
+ return {
540
+ route: ctx.route.kind,
541
+ shop: convert.shop(snapshot.shop, policies, ctx.locale.country ?? ''),
542
+ menus,
543
+ products,
544
+ collections,
545
+ collectionList,
546
+ pages,
547
+ blogs,
548
+ articles,
549
+ search,
550
+ listingSeed,
551
+ recommendations,
552
+ policyHandle,
553
+ accountUrls: ctx.route.kind === 'customer'
554
+ ? { orders: ctx.data.customer.accountUrl('orders'), addresses: ctx.data.customer.accountUrl('addresses'), profile: ctx.data.customer.accountUrl('profile') }
555
+ : null,
556
+ cart,
557
+ localization: localizationOf(ctx, snapshot.shop.shipsToCountries ?? [], showsLocale),
558
+ // A personalising input (§2): read only when the account menu renders; the caller varies on it.
559
+ signedIn: showsAccount ? ctx.request.isSignedIn : null,
560
+ unresolved,
561
+ routeMissing: routeMissingOf(ctx.route, { products, collections, pages, blogs, policies }),
562
+ };
563
+ }
564
+ function routeMissingOf(route, found) {
565
+ const h = route.handle;
566
+ if (!h)
567
+ return false;
568
+ switch (route.kind) {
569
+ case 'product': return !found.products[h];
570
+ case 'collection': return !found.collections[h];
571
+ case 'page': return !found.pages[h];
572
+ case 'blog': return !found.blogs[h];
573
+ // The snapshot answers a policy route with the store's PUBLISHED policy for the handle, else null.
574
+ case 'policy': return found.policies.length === 0;
575
+ default: return false;
576
+ }
577
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The ABI page as Nova's runtime reads it — shared by the server entry and the browser entry so
3
+ * both build the identical tree.
4
+ */
5
+ import type { ContentNode } from '../runtime/kit/types.js';
6
+ /** The ABI's PageDoc regions → the flat section list, regions in template order, each node tagged with its area. */
7
+ export declare function nodesOf(regions: readonly {
8
+ region?: string;
9
+ id?: string;
10
+ sections: readonly unknown[];
11
+ }[]): ContentNode[];
12
+ /**
13
+ * The route names a resource the store does not have (unknown page, collection, product, blog):
14
+ * the page answers 404, so the shopper sees the theme's not-found section in place of the
15
+ * template's main sections (which would otherwise render nothing). Header and footer stay.
16
+ * Live pages only — the editor canvas keeps the template it is editing.
17
+ */
18
+ export declare function notFoundTree(nodes: readonly ContentNode[]): ContentNode[];
19
+ /**
20
+ * The location (path + query) the store layer routes on: the canonical path, plus `q` (and its
21
+ * `sort`) on search, a listing's sort / filters, `cart_link` on the cart and `variant` on a product (page-data.ts pageParamsOf).
22
+ */
23
+ export declare function locationOf(canonical: string, params: Readonly<Record<string, string>>, listing?: string): string;
@@ -0,0 +1,46 @@
1
+ import { getThemeBundle } from '../runtime/slots.js';
2
+ /** The theme's `templates/404.json`, from the bundle the entry handed the runtime (`ThemeBundle.templates`). */
3
+ function notFoundTemplate() {
4
+ const hit = Object.entries(getThemeBundle().templates).find(([path]) => /(^|\/)404\.json$/.test(path));
5
+ return (hit?.[1]?.default ?? {});
6
+ }
7
+ /** Region → the layout area the runtime's SectionTree splits on (header zone → <main> → footer zone). */
8
+ const AREA = { announcement: 'header', header: 'header', footer: 'footer' };
9
+ /** The ABI's PageDoc regions → the flat section list, regions in template order, each node tagged with its area. */
10
+ export function nodesOf(regions) {
11
+ return regions.flatMap((r) => r.sections.map((n) => ({ ...n, area: AREA[r.region ?? r.id ?? ''] ?? 'template' })));
12
+ }
13
+ /**
14
+ * The route names a resource the store does not have (unknown page, collection, product, blog):
15
+ * the page answers 404, so the shopper sees the theme's not-found section in place of the
16
+ * template's main sections (which would otherwise render nothing). Header and footer stay.
17
+ * Live pages only — the editor canvas keeps the template it is editing.
18
+ */
19
+ export function notFoundTree(nodes) {
20
+ const section = (notFoundTemplate().sections ?? []).find((s) => s.type === 'not-found');
21
+ const main = { type: 'not-found', id: 'route-missing', settings: { ...(section?.settings ?? {}) }, area: 'template' };
22
+ return [...nodes.filter((n) => n.area === 'header'), main, ...nodes.filter((n) => n.area === 'footer')];
23
+ }
24
+ /**
25
+ * The location (path + query) the store layer routes on: the canonical path, plus `q` (and its
26
+ * `sort`) on search, a listing's sort / filters, `cart_link` on the cart and `variant` on a product (page-data.ts pageParamsOf).
27
+ */
28
+ export function locationOf(canonical, params, listing = '') {
29
+ let path = '/';
30
+ try {
31
+ path = new URL(canonical).pathname || '/';
32
+ }
33
+ catch {
34
+ path = '/';
35
+ }
36
+ if (typeof params.q === 'string' && params.q) {
37
+ const sort = typeof params.sort === 'string' && params.sort ? `&sort=${encodeURIComponent(params.sort)}` : '';
38
+ return `${path}?q=${encodeURIComponent(params.q)}${sort}`;
39
+ }
40
+ // A collection page's sort / filters (listing-query.ts): the listing reads them from the location.
41
+ const cartLink = typeof params.cart_link === 'string' && params.cart_link ? `cart_link=${encodeURIComponent(params.cart_link)}` : '';
42
+ // A product URL's `?variant=` (page-data.ts variantOf): the product page opens on that variant.
43
+ const variant = typeof params.variant === 'string' && params.variant ? `variant=${encodeURIComponent(params.variant)}` : '';
44
+ const query = [listing, cartLink, variant].filter(Boolean).join('&');
45
+ return query ? `${path}?${query}` : path;
46
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The referral program over Theme ABI v2 (army #7751): `useReferrals()` driven by the data ops `referral.state` and
3
+ * `referral.offer` (the `?ref=` code) and the actions `referral.claim` and `referral.invite`, which the host answers
4
+ * from studio-accounts (`/account/referrals/*`) with the shopper's session. A `?ref=CODE` visit keeps the code for
5
+ * the session (sessionStorage) and in the first-party session cookie `tanqory_ref`, a claimed friend code in
6
+ * `tanqory_ref_claim`; studio-checkouts reads both (the `ref` attribute, the friend's code applied). Browser only;
7
+ * a host without the ops, or referrals off, is the same as off.
8
+ */
9
+ import { type ReactNode } from 'react';
10
+ import { type FriendOffer, type ReferralState } from '../sdk/referrals.js';
11
+ import type { AbiRemote } from './wire.js';
12
+ export declare const REF_COOKIE = "tanqory_ref";
13
+ export declare const CLAIM_COOKIE = "tanqory_ref_claim";
14
+ /** The `?ref=` code of this visit, else the one kept earlier this session; kept for the session either way. */
15
+ export declare function keepRefCode(search: string): string | null;
16
+ /** The `referral.state` answer when it is the shopper's own link, else null. */
17
+ export declare function referralStateOf(data: unknown): ReferralState | null;
18
+ /** The `referral.offer` answer when it is an offer for this shopper, else null. */
19
+ export declare function friendOfferOf(data: unknown, claimedCode: string | null): FriendOffer | null;
20
+ export declare function AbiReferralsProvider({ remote, children }: {
21
+ remote: AbiRemote | null;
22
+ children: ReactNode;
23
+ }): JSX.Element;