@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,56 @@
1
+ /**
2
+ * The store context Nova's adapters read (`ui/adapters` StoreContext), built
3
+ * from the theme's data layer.
4
+ *
5
+ * Sync first: everything the bootstrap payload already holds (shop, menus,
6
+ * collections, products, the route's page) is mapped during render, so the
7
+ * server markup and the client's first render agree. What the bootstrap lacks
8
+ * is requested and loaded after render, into a cache keyed by WHAT was asked —
9
+ * `collection-products:<handle>`, `search:<query>` — never by a boolean. A soft
10
+ * navigation to another handle therefore reads another key: the previous
11
+ * page's data cannot render under the new URL.
12
+ */
13
+ import { type ReactNode } from 'react';
14
+ import type { StoreContext } from '../../sdk/index.js';
15
+ import type * as UI from '../../sdk/index.js';
16
+ type Loader = () => Promise<unknown>;
17
+ interface Entry {
18
+ status: 'loading' | 'done' | 'error';
19
+ value?: unknown;
20
+ }
21
+ /** The resource cache: read during render, filled after it. */
22
+ declare class Resources {
23
+ private cache;
24
+ private wanted;
25
+ constructor(seed?: Record<string, unknown>);
26
+ /** The loaded value, or undefined — and ask for it when it has not been asked for. */
27
+ get<T>(key: string, load: Loader | undefined): T | undefined;
28
+ status(key: string): Entry['status'] | 'idle';
29
+ /** Start every requested load; `changed` runs once per settled load. */
30
+ flush(changed: () => void): void;
31
+ /** Replace a key's value (a listing's next page). */
32
+ put(key: string, value: unknown): void;
33
+ }
34
+ export interface StoreValue {
35
+ ctx: StoreContext;
36
+ resources: Resources;
37
+ /** Re-render the page after a load settles. */
38
+ bump: () => void;
39
+ /** Pathname + search of the current route. */
40
+ location: string;
41
+ settings: Record<string, unknown>;
42
+ }
43
+ export declare function useStore(): StoreValue | null;
44
+ /** An image setting holds a URL. Its size comes from the URL when it carries one, else 4:3 (MediaFrame's own fallback). */
45
+ export declare function imageFromUrl(url: string): UI.Image | null;
46
+ /** A known non-default sort id, else '' (relevance). */
47
+ export declare const searchSortOf: (sort: string | null | undefined) => string;
48
+ /** Which page of the account area (`data.accountUrl(path)`) an `/account*` path opens. */
49
+ export declare function accountPageOf(pathname: string): 'orders' | 'addresses' | 'profile';
50
+ export declare function StoreProvider({ location, locale, settings, children }: {
51
+ location: string;
52
+ locale: string;
53
+ settings: Record<string, unknown>;
54
+ children: ReactNode;
55
+ }): JSX.Element;
56
+ export {};
@@ -0,0 +1,308 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ /**
3
+ * The store context Nova's adapters read (`ui/adapters` StoreContext), built
4
+ * from the theme's data layer.
5
+ *
6
+ * Sync first: everything the bootstrap payload already holds (shop, menus,
7
+ * collections, products, the route's page) is mapped during render, so the
8
+ * server markup and the client's first render agree. What the bootstrap lacks
9
+ * is requested and loaded after render, into a cache keyed by WHAT was asked —
10
+ * `collection-products:<handle>`, `search:<query>` — never by a boolean. A soft
11
+ * navigation to another handle therefore reads another key: the previous
12
+ * page's data cannot render under the new URL.
13
+ */
14
+ import { createContext, useContext, useEffect, useMemo, useRef, useState } from 'react';
15
+ import { getThemeBundle } from '../slots.js';
16
+ import { useData } from '../kit/data.js';
17
+ import { useCart } from '../kit/cart.js';
18
+ import { matchRoute } from './routes.js';
19
+ import { hasDecided, getConsentMode, isConsentArmed, onConsentChange, onConsentModeChange } from '../kit/consent.js';
20
+ import * as map from './to-ui.js';
21
+ import { usePreviewMode } from '../shell/preview-mode.js';
22
+ /** The resource cache: read during render, filled after it. */
23
+ class Resources {
24
+ constructor(seed) {
25
+ this.cache = new Map();
26
+ this.wanted = new Map();
27
+ for (const [key, value] of Object.entries(seed ?? {}))
28
+ if (value != null)
29
+ this.cache.set(key, { status: 'done', value });
30
+ }
31
+ /** The loaded value, or undefined — and ask for it when it has not been asked for. */
32
+ get(key, load) {
33
+ const hit = this.cache.get(key);
34
+ if (hit)
35
+ return hit.status === 'done' ? hit.value : undefined;
36
+ if (load)
37
+ this.wanted.set(key, load);
38
+ return undefined;
39
+ }
40
+ status(key) {
41
+ return this.cache.get(key)?.status ?? 'idle';
42
+ }
43
+ /** Start every requested load; `changed` runs once per settled load. */
44
+ flush(changed) {
45
+ for (const [key, load] of this.wanted) {
46
+ if (this.cache.has(key))
47
+ continue;
48
+ this.cache.set(key, { status: 'loading' });
49
+ load()
50
+ .then((value) => this.cache.set(key, { status: 'done', value }))
51
+ .catch(() => this.cache.set(key, { status: 'error' }))
52
+ .finally(changed);
53
+ }
54
+ this.wanted.clear();
55
+ }
56
+ /** Replace a key's value (a listing's next page). */
57
+ put(key, value) {
58
+ this.cache.set(key, { status: 'done', value });
59
+ }
60
+ }
61
+ const StoreCtx = createContext(null);
62
+ export function useStore() {
63
+ return useContext(StoreCtx);
64
+ }
65
+ /** An image setting holds a URL. Its size comes from the URL when it carries one, else 4:3 (MediaFrame's own fallback). */
66
+ export function imageFromUrl(url) {
67
+ const src = url.trim();
68
+ if (!src)
69
+ return null;
70
+ let width = 1200;
71
+ let height = 900;
72
+ const svg = /^data:image\/svg\+xml/.test(src) ? decodeURIComponent(src) : '';
73
+ const w = /\bwidth="(\d+)"/.exec(svg)?.[1] ?? new URLSearchParams(src.split('?')[1] ?? '').get('width');
74
+ const h = /\bheight="(\d+)"/.exec(svg)?.[1] ?? new URLSearchParams(src.split('?')[1] ?? '').get('height');
75
+ if (w && h && Number(w) > 0 && Number(h) > 0) {
76
+ width = Number(w);
77
+ height = Number(h);
78
+ }
79
+ return { src, width, height, alt: '' };
80
+ }
81
+ /** A read-through map: `ctx.menus['main-menu']` resolves on access. */
82
+ function lookup(resolve) {
83
+ return new Proxy({}, {
84
+ get: (_t, key) => (typeof key === 'string' && key ? resolve(key) : undefined),
85
+ has: (_t, key) => typeof key === 'string' && resolve(key) !== undefined,
86
+ });
87
+ }
88
+ const PRODUCTS_PER_REQUEST = 24;
89
+ /** The handle the platform gives the store's privacy policy (lib/abi/convert.ts POLICY_SLOT). */
90
+ const PRIVACY_POLICY = 'privacy-policy';
91
+ /**
92
+ * The search page's sort control (`?sort=`). Relevance is the platform's default order; the others
93
+ * are the orders the data plane answers for search (Theme ABI `catalog.search` `sortKey`). The ids
94
+ * match lib/abi/data-api.ts `SEARCH_ORDER`, which keys the server-loaded result the same way.
95
+ */
96
+ const SEARCH_SORT_IDS = ['relevance', 'price-asc', 'price-desc', 'title-asc', 'created-desc'];
97
+ const SEARCH_SORT_LABELS = {
98
+ en: { relevance: 'Relevance', 'price-asc': 'Price, low to high', 'price-desc': 'Price, high to low', 'title-asc': 'Name, A–Z', 'created-desc': 'Newest' },
99
+ th: { relevance: 'ความเกี่ยวข้อง', 'price-asc': 'ราคา ต่ำไปสูง', 'price-desc': 'ราคา สูงไปต่ำ', 'title-asc': 'ชื่อ ก–ฮ', 'created-desc': 'ใหม่ล่าสุด' },
100
+ ar: { relevance: 'الأكثر صلة', 'price-asc': 'السعر، من الأقل إلى الأعلى', 'price-desc': 'السعر، من الأعلى إلى الأقل', 'title-asc': 'الاسم، أ–ي', 'created-desc': 'الأحدث' },
101
+ };
102
+ /** A known non-default sort id, else '' (relevance). */
103
+ export const searchSortOf = (sort) => (sort && sort !== 'relevance' && SEARCH_SORT_IDS.includes(sort) ? sort : '');
104
+ /** Which page of the account area (`data.accountUrl(path)`) an `/account*` path opens. */
105
+ export function accountPageOf(pathname) {
106
+ const sub = pathname.replace(/^\/account\/?/, '').split('/')[0];
107
+ return sub === 'orders' || sub === 'addresses' ? sub : 'profile';
108
+ }
109
+ export function StoreProvider({ location, locale, settings, children }) {
110
+ const data = useData();
111
+ const cart = useCart();
112
+ const labels = getThemeBundle().theme.labels(locale);
113
+ const [, setVersion] = useState(0);
114
+ // One cache for the page's lifetime. The post-hydration revalidation swaps in
115
+ // a new data source seconds after the first loads were issued; starting clean
116
+ // then re-sent every query a second time for the same answers.
117
+ const resources = useRef(null);
118
+ resources.current ??= new Resources(data.preloaded);
119
+ const cache = resources.current;
120
+ const bump = useRef(() => setVersion((v) => v + 1)).current;
121
+ // Consent is the shopper's own stored answer and a per-request verdict: the
122
+ // server cannot know either, so both are read after mount (first render = closed).
123
+ const [consent, setConsentState] = useState({ enabled: false, answered: true });
124
+ const preview = usePreviewMode();
125
+ useEffect(() => {
126
+ // Theme ABI v2: the platform owns consent. Ask it after hydration (never in the server render,
127
+ // so every page stays cacheable), and never on a preview render — the merchant is editing,
128
+ // not shopping, and the banner covered the canvas.
129
+ if (data.consent) {
130
+ if (preview)
131
+ return;
132
+ let alive = true;
133
+ data.consent
134
+ .get()
135
+ .then((r) => {
136
+ // The merchant's banner settings decide where it shows (map.consentBannerShows); absent = as before.
137
+ const required = r.bannerRequired && map.consentBannerShows(r, data.shop?.consentBanner);
138
+ if (alive)
139
+ setConsentState({ enabled: required, answered: r.known || !required });
140
+ })
141
+ .catch(() => {
142
+ /* no readout ⇒ no banner; the platform's default applies */
143
+ });
144
+ // The shopper's choice in the banner (RuntimeBridge `consent.decide`) answers it for this page.
145
+ const offChoice = onConsentChange(() => setConsentState((c) => ({ ...c, answered: true })));
146
+ return () => {
147
+ alive = false;
148
+ offChoice();
149
+ };
150
+ }
151
+ const read = () => setConsentState({ enabled: isConsentArmed() && getConsentMode() !== 'NONE', answered: hasDecided() });
152
+ read();
153
+ const offMode = onConsentModeChange(read);
154
+ const offChoice = onConsentChange(read);
155
+ return () => {
156
+ offMode();
157
+ offChoice();
158
+ };
159
+ }, [data.consent, preview]);
160
+ // The banner links the privacy policy only when the store has published it. A page other than
161
+ // that policy's own does not carry it, so it is asked for once, when the banner is armed.
162
+ const [privacyFetched, setPrivacyFetched] = useState(undefined);
163
+ // The page's list of published policies (Theme ABI `Shop.policyLinks`) or the merchant's own link
164
+ // already answers it: no request.
165
+ const shopLinks = data.shop;
166
+ const privacyKnown = Boolean(map.toPolicies(data.shop)[PRIVACY_POLICY]) || Array.isArray(shopLinks?.policyLinks) || Boolean(shopLinks?.consentBanner?.privacyLinkUrl);
167
+ useEffect(() => {
168
+ if (!consent.enabled || privacyKnown || privacyFetched !== undefined || !data.fetchPolicy)
169
+ return;
170
+ let alive = true;
171
+ data.fetchPolicy(PRIVACY_POLICY).then((p) => { if (alive)
172
+ setPrivacyFetched(map.toPolicy(p) ?? null); }, () => { if (alive)
173
+ setPrivacyFetched(null); });
174
+ return () => {
175
+ alive = false;
176
+ };
177
+ }, [consent.enabled, privacyKnown, privacyFetched, data]);
178
+ // Loads requested during this render start once it has committed.
179
+ useEffect(() => cache.flush(bump));
180
+ const pathname = location.split('?')[0] || '/';
181
+ const search = new URLSearchParams(location.split('?')[1] ?? '');
182
+ const query = search.get('q') ?? '';
183
+ const searchSort = searchSortOf(search.get('sort'));
184
+ const route = matchRoute(pathname);
185
+ const shop = useMemo(() => map.toShop(data.shop, { shopName: str(settings.shopName), logo: str(settings.logo) }), [data.shop, settings.shopName, settings.logo]);
186
+ const ctx = (() => {
187
+ const product = (handle) => {
188
+ const full = cache.get(`product:${handle}`, data.fetchProduct ? () => data.fetchProduct(handle) : undefined);
189
+ const raw = full ?? data.productByHandle?.(handle) ?? null;
190
+ return raw ? map.toProduct(raw) : undefined;
191
+ };
192
+ const collection = (handle) => {
193
+ const base = data.collectionByHandle?.(handle) ?? null;
194
+ const page = cache.get(`collection-products:${handle}`, data.collectionProducts ? () => data.collectionProducts(handle, { first: PRODUCTS_PER_REQUEST }) : undefined);
195
+ if (!base)
196
+ return undefined;
197
+ // The bootstrap is baked at build time: a collection whose products were
198
+ // assigned later is an empty shell there. Live products win once loaded.
199
+ const products = page?.products?.length ? page.products : base.products;
200
+ return map.toCollection(base, { products });
201
+ };
202
+ const menu = (handle) => {
203
+ const sync = data.menu?.(handle) ?? null;
204
+ const raw = sync ?? cache.get(`menu:${handle}`, data.fetchMenu ? () => data.fetchMenu(handle) : undefined);
205
+ return map.toMenu(raw ?? null) ?? undefined;
206
+ };
207
+ const blog = (handle) => {
208
+ const raw = cache.get(`blog:${handle}`, data.blogByHandle ? () => data.blogByHandle(handle, { articles: 12 }) : undefined);
209
+ return map.toBlog(raw ?? null) ?? undefined;
210
+ };
211
+ // The landing page is in the bootstrap; any other is fetched (soft navigation).
212
+ const page = (handle) => map.toPage(data.pageByHandle?.(handle) ?? cache.get(`page:${handle}`, data.fetchPage ? () => data.fetchPage(handle) : undefined) ?? null) ?? undefined;
213
+ const currentProduct = route.template === 'product' && route.handle ? product(route.handle) : undefined;
214
+ const currentCollection = route.template === 'collection' && route.handle ? collection(route.handle) : undefined;
215
+ const productCollections = (route.template === 'product' && route.handle
216
+ ? (cache.get(`product:${route.handle}`, undefined) ?? data.productByHandle?.(route.handle) ?? null)?.collections
217
+ : undefined) ?? [];
218
+ const currentProductCollection = productCollections.find((c) => c && c.handle && c.title) ?? null;
219
+ const currentPage = route.template === 'page' && route.handle ? page(route.handle) : undefined;
220
+ const currentBlog = route.blogHandle ? blog(route.blogHandle) : route.template === 'blog' && route.handle ? blog(route.handle) : undefined;
221
+ const currentArticle = route.template === 'article' && route.blogHandle && route.handle
222
+ ? map.toArticle(cache.get(`article:${route.blogHandle}/${route.handle}`, data.articleByHandle ? () => data.articleByHandle(route.blogHandle, route.handle) : undefined) ?? null, route.blogHandle) ?? undefined
223
+ : undefined;
224
+ const policies = map.toPolicies(data.shop);
225
+ if (privacyFetched && !policies[privacyFetched.handle])
226
+ policies[privacyFetched.handle] = privacyFetched;
227
+ const searchRaw = route.template === 'search' && query
228
+ ? cache.get(searchSort ? `search:${query}|${searchSort}` : `search:${query}`, data.search ? () => data.search(query, { first: PRODUCTS_PER_REQUEST, ...(searchSort ? { sort: searchSort } : {}) }) : undefined)
229
+ : undefined;
230
+ const ctx = {
231
+ shop,
232
+ menus: lookup(menu),
233
+ images: lookup((url) => imageFromUrl(url) ?? undefined),
234
+ videos: lookup((url) => (url.trim() ? { src: url.trim() } : undefined)),
235
+ cart: map.toCartSummary(cart),
236
+ localization: map.toLocalization(data.localization),
237
+ breadcrumbs: map.toBreadcrumbs({
238
+ pathname,
239
+ labels,
240
+ // On a product page: the first collection the platform names for the product (Theme ABI `Product.collections`).
241
+ collection: currentCollection ? { handle: route.handle ?? '', title: currentCollection.title } : (currentProductCollection ?? null),
242
+ product: currentProduct,
243
+ page: currentPage,
244
+ blog: currentBlog,
245
+ article: currentArticle,
246
+ policy: route.template === 'policy' && route.handle ? policies[route.handle] : null,
247
+ }),
248
+ consentEnabled: consent.enabled,
249
+ consentAnswered: consent.answered,
250
+ brandColor: str(settings.colorPrimary),
251
+ collections: lookup(collection),
252
+ currentCollection,
253
+ products: lookup(product),
254
+ currentProduct,
255
+ ...(route.template === 'product' && search.get('variant') ? { currentVariantId: search.get('variant') } : {}),
256
+ pages: lookup(page),
257
+ // No shopper history or consent-backed tracking exists yet: the section waits for the platform.
258
+ recentlyViewed: null,
259
+ newestCollections: (data.allCollections?.() ?? []).slice(0, 8).map((c) => map.toCollection(c)),
260
+ currentPage,
261
+ currentArticle,
262
+ currentBlog: currentBlog ? { title: currentBlog.title, url: currentBlog.url } : undefined,
263
+ currentTag: route.tag,
264
+ blogs: lookup(blog),
265
+ reviews: null,
266
+ ugcFeed: null,
267
+ currentCart: map.toCart(cart),
268
+ checkoutUrl: cart.checkoutUrl ?? '/checkout',
269
+ cartLink: route.template === 'cart' ? search.get('cart_link') : null,
270
+ searchQuery: query,
271
+ searchResults: searchRaw ? map.toSearchResults(query, searchRaw) : null,
272
+ searchSortOptions: query ? SEARCH_SORT_IDS.map((id) => ({ id, label: (SEARCH_SORT_LABELS[(locale || 'en').split('-')[0]] ?? SEARCH_SORT_LABELS.en)[id] })) : [],
273
+ searchSort: searchSort || 'relevance',
274
+ account: null,
275
+ // The account slot's Account BFF URL (Theme ABI v2 §4), on the customer route only: `/account/orders` and
276
+ // `/account/addresses` open those pages of the account area, every other `/account*` path its profile.
277
+ ...(data.accountUrl ? { accountUrl: data.accountUrl(accountPageOf(pathname)) } : {}),
278
+ // The platform's native form endpoint (ABI §1): a newsletter / contact form posts to its own page.
279
+ ...(data.formEndpoint ? { newsletterEndpoint: data.formEndpoint, contactEndpoint: data.formEndpoint } : {}),
280
+ ...(data.formResult ? { formResult: data.formResult } : {}),
281
+ policies,
282
+ currentPolicy: route.template === 'policy' && route.handle ? (policies[route.handle] ?? null) : null,
283
+ };
284
+ // Loaded only when a section reads them: every page would otherwise fetch
285
+ // the store's locations and the product's recommendations for nothing.
286
+ Object.defineProperties(ctx, {
287
+ recommendations: {
288
+ enumerable: true,
289
+ get: () => {
290
+ if (!currentProduct?.id)
291
+ return undefined;
292
+ const list = cache.get(`recommendations:${currentProduct.id}`, data.productRecommendations ? () => data.productRecommendations(currentProduct.id) : undefined);
293
+ return list ? { related: map.toProducts(list), complementary: [] } : undefined;
294
+ },
295
+ },
296
+ locations: {
297
+ enumerable: true,
298
+ get: () => map.toLocations(cache.get('locations', data.locations ? () => data.locations() : undefined) ?? null),
299
+ },
300
+ });
301
+ return ctx;
302
+ })();
303
+ const value = useMemo(() => ({ ctx, resources: cache, bump, location, settings }), [ctx, cache, bump, location, settings]);
304
+ return _jsx(StoreCtx.Provider, { value: value, children: children });
305
+ }
306
+ function str(v) {
307
+ return typeof v === 'string' && v.trim() ? v.trim() : undefined;
308
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * A handle read out of `location.pathname` is percent-encoded — the stored
3
+ * handle is not. A Thai or CJK handle ("เสื้อยืด") arrives as "%E0%B9%80…",
4
+ * matches nothing, and the route silently falls back to whatever record is
5
+ * first — the wrong product, or a blank page. Decode every handle taken from
6
+ * a URL.
7
+ *
8
+ * Malformed input (a stray `%` in a handle) keeps the raw segment rather than
9
+ * throwing URIError, which would take the whole render down.
10
+ */
11
+ export declare function decodeHandle(raw: string): string;
12
+ export declare function decodeHandle(raw: string | undefined): string | undefined;
13
+ /** First capture of `re` against the current pathname, decoded. SSR-safe. */
14
+ export declare function handleFromPath(re: RegExp): string | undefined;
@@ -0,0 +1,16 @@
1
+ export function decodeHandle(raw) {
2
+ if (raw === undefined)
3
+ return undefined;
4
+ try {
5
+ return decodeURIComponent(raw);
6
+ }
7
+ catch {
8
+ return raw;
9
+ }
10
+ }
11
+ /** First capture of `re` against the current pathname, decoded. SSR-safe. */
12
+ export function handleFromPath(re) {
13
+ if (typeof window === 'undefined')
14
+ return undefined;
15
+ return decodeHandle(window.location.pathname.match(re)?.[1]);
16
+ }
@@ -0,0 +1,87 @@
1
+ /** The resource a URL addresses, if it addresses one. */
2
+ export interface RouteMatch {
3
+ /** Base template name — a file under `templates/<name>.json`. */
4
+ template: string;
5
+ /** Resource kind, for the record types that carry a `templateSuffix`. */
6
+ resource?: 'product' | 'collection' | 'page' | 'blog' | 'article' | 'policy';
7
+ /** Decoded handle of the addressed resource. */
8
+ handle?: string;
9
+ /** Blog handle, for article routes (`/blogs/<blog>/<article>`). */
10
+ blogHandle?: string;
11
+ /** Decoded tag, for a blog filtered by tag (`/blogs/<blog>/tagged/<tag>`). */
12
+ tag?: string;
13
+ }
14
+ /**
15
+ * Match a URL pathname to a template + the resource it addresses.
16
+ *
17
+ * Order matters: `/blogs/<blog>/<article>` must be tested BEFORE
18
+ * `/blogs/<handle>` so the blog list doesn't shadow article detail.
19
+ */
20
+ export declare function matchRoute(pathname: string): RouteMatch;
21
+ /** Base template name for a pathname. */
22
+ export declare function resolveTemplate(pathname: string): string;
23
+ /** The handle a pathname addresses for a given resource kind, else undefined. */
24
+ export declare function routeHandle(pathname: string, resource: NonNullable<RouteMatch['resource']>): string | undefined;
25
+ /**
26
+ * The detail-route handle variables the bootstrap query should prefetch, so a
27
+ * record's `templateSuffix` is known before the template is chosen.
28
+ */
29
+ export declare function detailHandles(pathname: string): {
30
+ pageHandle?: string;
31
+ productHandle?: string;
32
+ collectionHandle?: string;
33
+ policyBodies?: boolean;
34
+ };
35
+ /**
36
+ * `<base>.<suffix>` when the theme ships that template file, else `<base>`.
37
+ *
38
+ * `templateExists` is injected rather than globbed here so the entry and the
39
+ * layout can each pass the glob they already hold, and so this module stays
40
+ * testable without Vite.
41
+ */
42
+ export declare function variantOf(base: string, suffix: string | null | undefined, templateExists: (name: string) => boolean): string;
43
+ /** Minimal shape of the data layer this module needs to read a templateSuffix. */
44
+ export interface TemplateSuffixSource {
45
+ productByHandle: (handle: string) => {
46
+ templateSuffix?: string | null;
47
+ } | null;
48
+ collectionByHandle: (handle: string) => {
49
+ templateSuffix?: string | null;
50
+ } | null;
51
+ pageByHandle: (handle: string) => {
52
+ templateSuffix?: string | null;
53
+ } | null;
54
+ }
55
+ /**
56
+ * The template to actually render for a pathname, including the merchant's
57
+ * per-resource template assignment (`templateSuffix`).
58
+ *
59
+ * This is the function the SPA router was missing: soft navigation looked up
60
+ * the BASE template only, so a product assigned `product.bundle` rendered
61
+ * `product` once the shopper arrived by clicking rather than by URL.
62
+ *
63
+ * Blog and article suffixes are resolved asynchronously by the caller (they are
64
+ * not in the sync bootstrap), so they are left at their base here.
65
+ */
66
+ export declare function resolvePageTemplate(pathname: string, data: TemplateSuffixSource, templateExists: (name: string) => boolean): string;
67
+ /** The async lookups a blog or article template variant needs. */
68
+ export interface AsyncSuffixSource {
69
+ blogByHandle?: (handle: string, opts?: {
70
+ articles?: number;
71
+ }) => Promise<{
72
+ templateSuffix?: string | null;
73
+ } | null | undefined>;
74
+ articleByHandle?: (blogHandle: string, articleHandle: string) => Promise<{
75
+ templateSuffix?: string | null;
76
+ } | null | undefined>;
77
+ fetchPage?: (handle: string) => Promise<{
78
+ templateSuffix?: string | null;
79
+ } | null | undefined>;
80
+ }
81
+ /**
82
+ * Blog and article records — and any page but the landing one — are not in the sync bootstrap, so their
83
+ * `templateSuffix` (`blog.featured`, `article.longform`) is looked up here —
84
+ * by the server before it renders, and by the SPA router before it swaps the
85
+ * tree. Any other route keeps the template it already resolved.
86
+ */
87
+ export declare function resolveAsyncVariant(route: RouteMatch, resolved: string, data: AsyncSuffixSource, templateExists: (name: string) => boolean): Promise<string>;
@@ -0,0 +1,154 @@
1
+ /**
2
+ * The theme's ONE route table.
3
+ *
4
+ * `resolveTemplate` used to exist twice, byte-for-byte, in `browser-entry.tsx` and
5
+ * `layouts/layout.tsx`, each with a comment asking the next person to keep them
6
+ * in sync. They drive different things — the entry picks the template to mount,
7
+ * the layout picks the template to swap in on a soft navigation — so a route
8
+ * added to one and not the other renders a 404 on exactly one of the two paths.
9
+ *
10
+ * Route matching lives here. Anything that needs "what does this URL mean" reads
11
+ * it from this module.
12
+ */
13
+ import { decodeHandle } from './handle.js';
14
+ /** Strip the trailing slash(es) from a pathname, keeping "/" itself. */
15
+ function normalize(pathname) {
16
+ return pathname !== '/' ? pathname.replace(/\/+$/, '') || '/' : '/';
17
+ }
18
+ /**
19
+ * Match a URL pathname to a template + the resource it addresses.
20
+ *
21
+ * Order matters: `/blogs/<blog>/<article>` must be tested BEFORE
22
+ * `/blogs/<handle>` so the blog list doesn't shadow article detail.
23
+ */
24
+ export function matchRoute(pathname) {
25
+ const p = normalize(pathname);
26
+ if (p === '/')
27
+ return { template: 'index' };
28
+ if (p === '/cart')
29
+ return { template: 'cart' };
30
+ if (p === '/search')
31
+ return { template: 'search' };
32
+ if (p === '/contact')
33
+ return { template: 'contact' };
34
+ if (p === '/404')
35
+ return { template: '404' };
36
+ if (p === '/collections')
37
+ return { template: 'list-collections' };
38
+ let m;
39
+ if ((m = p.match(/^\/collections\/([^/]+)$/)))
40
+ return { template: 'collection', resource: 'collection', handle: decodeHandle(m[1]) };
41
+ if ((m = p.match(/^\/products\/([^/]+)$/)))
42
+ return { template: 'product', resource: 'product', handle: decodeHandle(m[1]) };
43
+ if ((m = p.match(/^\/pages\/([^/]+)$/)))
44
+ return { template: 'page', resource: 'page', handle: decodeHandle(m[1]) };
45
+ // Shop policies (Settings) — a menu item of type "Policy" links to
46
+ // /policies/<handle> (privacy-policy, refund-policy, …).
47
+ if ((m = p.match(/^\/policies\/([^/]+)$/)))
48
+ return { template: 'policy', resource: 'policy', handle: decodeHandle(m[1]) };
49
+ // Customer account — /account and its sub-routes (login, orders, addresses).
50
+ if (p === '/account' || /^\/account\/[^/]+/.test(p))
51
+ return { template: 'account' };
52
+ // A blog filtered to one tag — the blog's own template, narrowed.
53
+ if ((m = p.match(/^\/blogs\/([^/]+)\/tagged\/([^/]+)$/)))
54
+ return { template: 'blog', resource: 'blog', handle: decodeHandle(m[1]), tag: decodeHandle(m[2]) };
55
+ if ((m = p.match(/^\/blogs\/([^/]+)\/([^/]+)$/)))
56
+ return {
57
+ template: 'article',
58
+ resource: 'article',
59
+ blogHandle: decodeHandle(m[1]),
60
+ handle: decodeHandle(m[2]),
61
+ };
62
+ if ((m = p.match(/^\/blogs\/([^/]+)$/)))
63
+ return { template: 'blog', resource: 'blog', handle: decodeHandle(m[1]) };
64
+ return { template: '404' };
65
+ }
66
+ /** Base template name for a pathname. */
67
+ export function resolveTemplate(pathname) {
68
+ return matchRoute(pathname).template;
69
+ }
70
+ /** The handle a pathname addresses for a given resource kind, else undefined. */
71
+ export function routeHandle(pathname, resource) {
72
+ const match = matchRoute(pathname);
73
+ return match.resource === resource ? match.handle : undefined;
74
+ }
75
+ /**
76
+ * The detail-route handle variables the bootstrap query should prefetch, so a
77
+ * record's `templateSuffix` is known before the template is chosen.
78
+ */
79
+ export function detailHandles(pathname) {
80
+ const m = matchRoute(pathname);
81
+ if (m.resource === 'policy')
82
+ return { policyBodies: true };
83
+ if (m.resource === 'page' && m.handle)
84
+ return { pageHandle: m.handle };
85
+ if (m.resource === 'product' && m.handle)
86
+ return { productHandle: m.handle };
87
+ if (m.resource === 'collection' && m.handle)
88
+ return { collectionHandle: m.handle };
89
+ return {};
90
+ }
91
+ /**
92
+ * `<base>.<suffix>` when the theme ships that template file, else `<base>`.
93
+ *
94
+ * `templateExists` is injected rather than globbed here so the entry and the
95
+ * layout can each pass the glob they already hold, and so this module stays
96
+ * testable without Vite.
97
+ */
98
+ export function variantOf(base, suffix, templateExists) {
99
+ const candidate = suffix ? `${base}.${suffix}` : base;
100
+ return templateExists(candidate) ? candidate : base;
101
+ }
102
+ /**
103
+ * The template to actually render for a pathname, including the merchant's
104
+ * per-resource template assignment (`templateSuffix`).
105
+ *
106
+ * This is the function the SPA router was missing: soft navigation looked up
107
+ * the BASE template only, so a product assigned `product.bundle` rendered
108
+ * `product` once the shopper arrived by clicking rather than by URL.
109
+ *
110
+ * Blog and article suffixes are resolved asynchronously by the caller (they are
111
+ * not in the sync bootstrap), so they are left at their base here.
112
+ */
113
+ export function resolvePageTemplate(pathname, data, templateExists) {
114
+ const m = matchRoute(pathname);
115
+ if (!m.resource || !m.handle)
116
+ return m.template;
117
+ let suffix;
118
+ if (m.resource === 'product')
119
+ suffix = data.productByHandle(m.handle)?.templateSuffix;
120
+ else if (m.resource === 'collection')
121
+ suffix = data.collectionByHandle(m.handle)?.templateSuffix;
122
+ else if (m.resource === 'page')
123
+ suffix = data.pageByHandle(m.handle)?.templateSuffix;
124
+ else
125
+ return m.template;
126
+ return variantOf(m.template, suffix, templateExists);
127
+ }
128
+ /**
129
+ * Blog and article records — and any page but the landing one — are not in the sync bootstrap, so their
130
+ * `templateSuffix` (`blog.featured`, `article.longform`) is looked up here —
131
+ * by the server before it renders, and by the SPA router before it swaps the
132
+ * tree. Any other route keeps the template it already resolved.
133
+ */
134
+ export async function resolveAsyncVariant(route, resolved, data, templateExists) {
135
+ try {
136
+ if (route.resource === 'article' && route.blogHandle && route.handle && data.articleByHandle) {
137
+ const a = await data.articleByHandle(route.blogHandle, route.handle);
138
+ return variantOf('article', a?.templateSuffix, templateExists);
139
+ }
140
+ if (route.resource === 'page' && route.handle && data.fetchPage) {
141
+ const p = await data.fetchPage(route.handle);
142
+ return variantOf('page', p?.templateSuffix, templateExists);
143
+ }
144
+ if (route.resource === 'blog' && route.handle && data.blogByHandle) {
145
+ // The same request the blog's sections make (12 posts), so it is answered once.
146
+ const b = await data.blogByHandle(route.handle, { articles: 12 });
147
+ return variantOf('blog', b?.templateSuffix, templateExists);
148
+ }
149
+ }
150
+ catch {
151
+ /* an unreachable record keeps its base template */
152
+ }
153
+ return resolved;
154
+ }