@tanqory/theme-kit 0.1.0 → 2.0.0-alpha.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +125 -10
- package/dist/abi/canvas-live.d.ts +67 -0
- package/dist/abi/canvas-live.js +154 -0
- package/dist/abi/cart.d.ts +59 -0
- package/dist/abi/cart.js +387 -0
- package/dist/abi/convert.d.ts +344 -0
- package/dist/abi/convert.js +1278 -0
- package/dist/abi/data-api.d.ts +15 -0
- package/dist/abi/data-api.js +209 -0
- package/dist/abi/jcs.d.ts +6 -0
- package/dist/abi/jcs.js +28 -0
- package/dist/abi/labels.d.ts +3 -0
- package/dist/abi/labels.js +34 -0
- package/dist/abi/page-data.d.ts +256 -0
- package/dist/abi/page-data.js +678 -0
- package/dist/abi/page.d.ts +28 -0
- package/dist/abi/page.js +57 -0
- package/dist/abi/referrals.d.ts +23 -0
- package/dist/abi/referrals.js +89 -0
- package/dist/abi/rewards.d.ts +27 -0
- package/dist/abi/rewards.js +82 -0
- package/dist/abi/seo.d.ts +47 -0
- package/dist/abi/seo.js +68 -0
- package/dist/abi/shell.d.ts +23 -0
- package/dist/abi/shell.js +10 -0
- package/dist/abi/state-pack.d.ts +17 -0
- package/dist/abi/state-pack.js +43 -0
- package/dist/abi/wire.d.ts +38 -0
- package/dist/abi/wire.js +84 -0
- package/dist/build.d.ts +116 -0
- package/dist/build.js +310 -0
- package/dist/client.d.ts +19 -0
- package/dist/client.js +87 -0
- package/dist/contract.d.ts +6 -0
- package/dist/contract.js +6 -0
- package/dist/headless/ai.d.ts +132 -0
- package/dist/headless/ai.js +99 -0
- package/dist/headless/hooks.d.ts +276 -0
- package/dist/headless/hooks.js +540 -0
- package/dist/headless/i18n.d.ts +13 -0
- package/dist/headless/i18n.js +45 -0
- package/dist/headless/index.d.ts +37 -0
- package/dist/headless/index.js +38 -0
- package/dist/headless/money.d.ts +25 -0
- package/dist/headless/money.js +61 -0
- package/dist/headless/page.d.ts +43 -0
- package/dist/headless/page.js +53 -0
- package/dist/headless/platform.d.ts +55 -0
- package/dist/headless/platform.js +77 -0
- package/dist/headless/primitives/cart.d.ts +90 -0
- package/dist/headless/primitives/cart.js +153 -0
- package/dist/headless/primitives/collection.d.ts +68 -0
- package/dist/headless/primitives/collection.js +80 -0
- package/dist/headless/primitives/product.d.ts +101 -0
- package/dist/headless/primitives/product.js +117 -0
- package/dist/headless/primitives/storefront.d.ts +106 -0
- package/dist/headless/primitives/storefront.js +186 -0
- package/dist/headless/primitives/util.d.ts +19 -0
- package/dist/headless/primitives/util.js +42 -0
- package/dist/headless/strings.d.ts +9 -0
- package/dist/headless/strings.js +190 -0
- package/dist/headless/structured-data.d.ts +31 -0
- package/dist/headless/structured-data.js +57 -0
- package/dist/headless/theme.d.ts +99 -0
- package/dist/headless/theme.js +54 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.js +18 -553
- package/dist/runtime/data/StoreProvider.d.ts +84 -0
- package/dist/runtime/data/StoreProvider.js +373 -0
- package/dist/runtime/data/handle.d.ts +14 -0
- package/dist/runtime/data/handle.js +16 -0
- package/dist/runtime/data/routes.d.ts +87 -0
- package/dist/runtime/data/routes.js +158 -0
- package/dist/runtime/data/to-ui.d.ts +281 -0
- package/dist/runtime/data/to-ui.js +977 -0
- package/dist/runtime/entries/register.d.ts +9 -0
- package/dist/runtime/entries/register.js +9 -0
- package/dist/runtime/entries/sections.d.ts +16 -0
- package/dist/runtime/entries/sections.js +19 -0
- package/dist/{types → runtime/kit}/SectionTree.d.ts +2 -1
- package/dist/runtime/kit/SectionTree.js +100 -0
- package/dist/runtime/kit/analytics.d.ts +63 -0
- package/dist/runtime/kit/analytics.js +250 -0
- package/dist/runtime/kit/cart.d.ts +215 -0
- package/dist/runtime/kit/cart.js +545 -0
- package/dist/{types → runtime/kit}/composition.d.ts +1 -1
- package/dist/runtime/kit/composition.js +3 -0
- package/dist/{types → runtime/kit}/config.d.ts +2 -2
- package/dist/runtime/kit/config.js +6 -0
- package/dist/runtime/kit/consent.d.ts +29 -0
- package/dist/runtime/kit/consent.js +159 -0
- package/dist/runtime/kit/contract/content.d.ts +199 -0
- package/dist/runtime/kit/contract/content.js +106 -0
- package/dist/runtime/kit/contract/field-types.d.ts +337 -0
- package/dist/runtime/kit/contract/field-types.js +206 -0
- package/dist/runtime/kit/contract/groups.d.ts +230 -0
- package/dist/runtime/kit/contract/groups.js +402 -0
- package/dist/runtime/kit/contract/index.d.ts +33 -0
- package/dist/runtime/kit/contract/index.js +33 -0
- package/dist/runtime/kit/contract/transform.d.ts +82 -0
- package/dist/runtime/kit/contract/transform.js +133 -0
- package/dist/runtime/kit/contract/validate.d.ts +75 -0
- package/dist/runtime/kit/contract/validate.js +480 -0
- package/dist/runtime/kit/data.d.ts +720 -0
- package/dist/runtime/kit/data.js +1117 -0
- package/dist/{types → runtime/kit}/defineSection.d.ts +1 -1
- package/dist/runtime/kit/defineSection.js +10 -0
- package/dist/{types → runtime/kit}/dynamic-source.d.ts +40 -18
- package/dist/runtime/kit/dynamic-source.js +294 -0
- package/dist/runtime/kit/index.d.ts +24 -0
- package/dist/runtime/kit/index.js +24 -0
- package/dist/{types → runtime/kit}/jsx-to-json.d.ts +1 -1
- package/dist/runtime/kit/jsx-to-json.js +28 -0
- package/dist/{types → runtime/kit}/mount.d.ts +25 -4
- package/dist/runtime/kit/mount.js +124 -0
- package/dist/{types → runtime/kit}/registry.d.ts +1 -1
- package/dist/runtime/kit/registry.js +12 -0
- package/dist/{types → runtime/kit}/ssg.d.ts +9 -3
- package/dist/runtime/kit/ssg.js +56 -0
- package/dist/runtime/kit/storefront.d.ts +639 -0
- package/dist/runtime/kit/storefront.js +723 -0
- package/dist/{types → runtime/kit}/theme-context.d.ts +8 -2
- package/dist/runtime/kit/theme-context.js +25 -0
- package/dist/runtime/kit/types.d.ts +147 -0
- package/dist/runtime/kit/types.js +1 -0
- package/dist/runtime/platform/TrackingPixels.d.ts +14 -0
- package/dist/runtime/platform/TrackingPixels.js +63 -0
- package/dist/runtime/platform/environment.d.ts +68 -0
- package/dist/runtime/platform/environment.js +85 -0
- package/dist/runtime/platform/locale.d.ts +27 -0
- package/dist/runtime/platform/locale.js +42 -0
- package/dist/runtime/platform/route-analytics.d.ts +15 -0
- package/dist/runtime/platform/route-analytics.js +72 -0
- package/dist/runtime/platform/safe-href.d.ts +25 -0
- package/dist/runtime/platform/safe-href.js +69 -0
- package/dist/runtime/platform/safe-values.d.ts +37 -0
- package/dist/runtime/platform/safe-values.js +140 -0
- package/dist/runtime/render/SectionRenderer.d.ts +4 -0
- package/dist/runtime/render/SectionRenderer.js +166 -0
- package/dist/runtime/render/listing-query.d.ts +52 -0
- package/dist/runtime/render/listing-query.js +122 -0
- package/dist/runtime/render/localized-copy.d.ts +86 -0
- package/dist/runtime/render/localized-copy.js +129 -0
- package/dist/runtime/render/product-listing.d.ts +11 -0
- package/dist/runtime/render/product-listing.js +243 -0
- package/dist/runtime/render/section-actions.d.ts +66 -0
- package/dist/runtime/render/section-actions.js +202 -0
- package/dist/runtime/render/starter.d.ts +11 -0
- package/dist/runtime/render/starter.js +81 -0
- package/dist/runtime/seo/head.d.ts +115 -0
- package/dist/runtime/seo/head.js +281 -0
- package/dist/runtime/seo/structured-data.d.ts +83 -0
- package/dist/runtime/seo/structured-data.js +252 -0
- package/dist/runtime/shell/PageShell.d.ts +18 -0
- package/dist/runtime/shell/PageShell.js +113 -0
- package/dist/runtime/shell/RuntimeBridge.d.ts +14 -0
- package/dist/runtime/shell/RuntimeBridge.js +93 -0
- package/dist/runtime/shell/overlay-state.d.ts +31 -0
- package/dist/runtime/shell/overlay-state.js +59 -0
- package/dist/runtime/shell/preview-mode.d.ts +2 -0
- package/dist/runtime/shell/preview-mode.js +11 -0
- package/dist/runtime/shell/spa-router.d.ts +14 -0
- package/dist/runtime/shell/spa-router.js +76 -0
- package/dist/runtime/shell/url-redirects.d.ts +6 -0
- package/dist/runtime/shell/url-redirects.js +37 -0
- package/dist/runtime/slots.d.ts +74 -0
- package/dist/runtime/slots.js +16 -0
- package/dist/runtime.d.ts +34 -0
- package/dist/runtime.js +40 -0
- package/dist/sdk/app-block.d.ts +29 -0
- package/dist/sdk/app-block.js +22 -0
- package/dist/sdk/index.d.ts +26 -0
- package/dist/sdk/index.js +26 -0
- package/dist/sdk/referrals.d.ts +62 -0
- package/dist/sdk/referrals.js +20 -0
- package/dist/sdk/rewards.d.ts +85 -0
- package/dist/sdk/rewards.js +29 -0
- package/dist/sdk/runtime-context.d.ts +202 -0
- package/dist/sdk/runtime-context.js +73 -0
- package/dist/sdk/schema.d.ts +206 -0
- package/dist/sdk/schema.js +121 -0
- package/dist/sdk/server-render.d.ts +8 -0
- package/dist/sdk/server-render.js +12 -0
- package/dist/sdk/store-lookup.d.ts +27 -0
- package/dist/sdk/store-lookup.js +29 -0
- package/dist/sdk/store.d.ts +149 -0
- package/dist/sdk/store.js +5 -0
- package/dist/sdk/sx.d.ts +40 -0
- package/dist/sdk/sx.js +112 -0
- package/dist/sdk/theme.d.ts +191 -0
- package/dist/sdk/theme.js +10 -0
- package/dist/sdk/types.d.ts +757 -0
- package/dist/sdk/types.js +7 -0
- package/dist/server.d.ts +111 -0
- package/dist/server.js +533 -0
- package/docs/headless-api.md +220 -0
- package/package.json +76 -22
- package/dist/index.js.map +0 -1
- package/dist/ssg-BZ5FYTw7.js +0 -1802
- package/dist/ssg-BZ5FYTw7.js.map +0 -1
- package/dist/ssg.js +0 -8
- package/dist/ssg.js.map +0 -1
- package/dist/types/cart.d.ts +0 -86
- package/dist/types/data.d.ts +0 -357
- package/dist/types/editor.d.ts +0 -5
- package/dist/types/index.d.ts +0 -20
- package/dist/types/preview-bridge.d.ts +0 -9
- package/dist/types/storefront.d.ts +0 -333
- package/dist/types/types.d.ts +0 -44
package/dist/ssg-BZ5FYTw7.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ssg-BZ5FYTw7.js","sources":["../src/theme-context.tsx","../src/registry.ts","../src/SectionTree.tsx","../src/storefront.ts","../src/data.tsx","../src/cart.tsx","../src/ssg.tsx"],"sourcesContent":["import { createContext, useContext, type ReactNode } from 'react'\n\ntype Settings = Record<string, unknown>\ntype Locale = Record<string, string>\n\nconst SettingsContext = createContext<Settings>({})\nconst LocaleContext = createContext<Locale>({})\n\n/** Provides global settings values + locale strings to the whole theme. */\nexport function ThemeProvider({\n settings = {},\n locale = {},\n children,\n}: {\n settings?: Settings\n locale?: Locale\n children: ReactNode\n}): JSX.Element {\n return (\n <SettingsContext.Provider value={settings}>\n <LocaleContext.Provider value={locale}>{children}</LocaleContext.Provider>\n </SettingsContext.Provider>\n )\n}\n\n/** Read global theme settings (values from config/settings.json). */\nexport function useSettings(): Settings {\n return useContext(SettingsContext)\n}\n\n/** Translate a key against the active locale (falls back to the key). */\nexport function useT(): (key: string) => string {\n const locale = useContext(LocaleContext)\n return (key) => locale[key] ?? key\n}\n","import type { SectionDef } from './types'\n\nconst registry = new Map<string, SectionDef>()\n\nexport function registerSections(defs: SectionDef[]): void {\n for (const def of defs) registry.set(def.name, def)\n}\n\nexport function getSection(name: string): SectionDef | undefined {\n return registry.get(name)\n}\n\n/** All registered sections — the editor uses this to build its inserter. */\nexport function allSections(): SectionDef[] {\n return [...registry.values()]\n}\n","import type { SectionDef, ContentNode } from './types'\nimport { getSection } from './registry'\n\n/** Apply attribute defaults from the section definition onto a node's settings. */\nfunction resolveAttributes(def: SectionDef, settings?: Record<string, unknown>): Record<string, any> {\n const out: Record<string, any> = { ...(settings ?? {}) }\n for (const [key, spec] of Object.entries(def.attributes ?? {})) {\n if (out[key] === undefined && spec.default !== undefined) out[key] = spec.default\n }\n return out\n}\n\n/** Tolerate both child-block shapes. Templates written by older editor\n * builds carry blocks as an OBJECT MAP keyed by id (the studio editor's\n * internal shape) instead of theme-kit's array — `blocks.map` on that\n * object crashed the ENTIRE storefront render (\"o.map is not a function\").\n * A malformed template must degrade to \"blocks don't render\", never to a\n * dead page. */\nfunction normalizeBlocks(\n blocks: ContentNode['blocks'] | Record<string, ContentNode>,\n order?: string[],\n): ContentNode[] {\n if (Array.isArray(blocks)) return blocks\n if (blocks && typeof blocks === 'object') {\n // Build the node list + a lookup keyed by BOTH the map key and the block's\n // own id — the editor's `order` array references the map key (\"0\"..\"n\"),\n // but be tolerant of templates that order by block id.\n const nodes: ContentNode[] = []\n const byRef = new Map<string, ContentNode>()\n for (const [key, raw] of Object.entries(blocks)) {\n if (!raw || typeof raw !== 'object' || typeof (raw as ContentNode).type !== 'string') continue\n const node = { ...(raw as ContentNode), id: (raw as ContentNode).id ?? key }\n nodes.push(node)\n byRef.set(key, node)\n if (node.id) byRef.set(node.id as string, node)\n }\n // The map's key order is NOT the merchant's arrangement — the editor stores\n // the real order in `order`. Honour it (then append any stragglers).\n if (Array.isArray(order) && order.length) {\n const ordered: ContentNode[] = []\n const used = new Set<ContentNode>()\n for (const ref of order) {\n const n = byRef.get(ref)\n if (n && !used.has(n)) {\n ordered.push(n)\n used.add(n)\n }\n }\n for (const n of nodes) if (!used.has(n)) ordered.push(n)\n return ordered\n }\n return nodes\n }\n return []\n}\n\nfunction RenderNode({\n node,\n path,\n}: {\n node: ContentNode\n /** Dotted index path from the tree root — `\"0\"`, `\"0.1\"`, etc. Read by the\n * editor preview bridge to identify which section the visitor clicked. */\n path: string\n}): JSX.Element | null {\n const def = getSection(node.type)\n if (!def) {\n console.warn(`[tanqory] unknown section \"${node.type}\"`)\n return null\n }\n const Comp = def.component\n const attributes = resolveAttributes(def, node.settings)\n // Wrap each rendered section in a CSS-transparent tag so the editor preview\n // bridge can resolve clicks back to the JSON node (via data-tq-section-id /\n // data-tq-path) without sections having to opt in. `display: contents`\n // means the wrapper participates in layout as if it weren't there.\n return (\n <div\n data-tq-section-id={node.id}\n data-tq-section-type={node.type}\n data-tq-path={path}\n style={{ display: 'contents' }}\n >\n <Comp attributes={attributes}>\n {normalizeBlocks(node.blocks, (node as ContentNode & { order?: string[] }).order).map(\n (child, i) => (\n <RenderNode key={child.id ?? i} node={child} path={`${path}.${i}`} />\n ),\n )}\n </Comp>\n </div>\n )\n}\n\n/**\n * The heart: render a JSON content tree → React. The editor and the storefront\n * both render through this — content stays JSON, never HTML.\n */\nexport function SectionTree({ tree }: { tree: ContentNode[] }): JSX.Element {\n return (\n <>\n {tree.map((node, i) => (\n <RenderNode key={node.id ?? i} node={node} path={String(i)} />\n ))}\n </>\n )\n}\n","/**\n * Storefront API extensions for the live data layer.\n *\n * `data.tsx` boots a small homepage prefetch (collections + products + page +\n * localization) and exposes a raw `graphql()` escape hatch. This module layers\n * the REST of the Shopify-Storefront-compatible surface on top of that same\n * requester so a theme can build EVERY page Shopify themes build:\n *\n * - Navigation menus (header/footer, recursive)\n * - Blog + articles\n * - Search + predictive search (autocomplete)\n * - Product recommendations\n * - Metaobjects (custom content)\n * - Shop info + legal policies\n * - Full customer account flow (login / register / orders / addresses)\n *\n * Every field hit here ALREADY EXISTS on tanqory-platform-store-api's Storefront\n * GraphQL schema (`POST /api/v1/stores/{id}/graphql`). These methods attach to\n * the LIVE DataApi only — mock data leaves them undefined, so themes feature-\n * detect (`data.search?.(...)`, `data.customer?.login(...)`).\n *\n * Token storage: the customer flow returns/accepts a `customerAccessToken`\n * (Shopify-compatible). The theme persists it (localStorage) and passes it\n * back — exactly like the cart's `cartId`. `customerTokenStore` is a tiny\n * localStorage helper for the common case.\n */\nimport type { Money, Product } from './data'\n\ntype GraphqlFn = <T = unknown>(query: string, variables?: Record<string, unknown>) => Promise<T>\n\n/** Normalizers injected from data.tsx (avoids a runtime import cycle). */\nexport interface StorefrontHelpers {\n normalizeProduct: (node: any) => Product\n}\n\n// ───────────────────────── Shared shapes ─────────────────────────\n\nexport interface Image {\n url: string\n altText?: string\n}\nexport interface Seo {\n title?: string | null\n description?: string | null\n}\n\n// ───────────────────────── Navigation ────────────────────────────\n\nexport type MenuItemType =\n | 'FRONTPAGE'\n | 'COLLECTION'\n | 'COLLECTIONS'\n | 'PRODUCT'\n | 'CATALOG'\n | 'PAGE'\n | 'BLOG'\n | 'ARTICLE'\n | 'SEARCH'\n | 'SHOP_POLICY'\n | 'HTTP'\n\nexport interface MenuItem {\n id: string\n title: string\n url: string | null\n type: MenuItemType\n resourceId?: string | null\n items: MenuItem[]\n}\nexport interface Menu {\n id: string\n handle: string\n title: string\n items: MenuItem[]\n}\n\n// ───────────────────────── Blog / Article ────────────────────────\n\nexport interface Article {\n id: string\n handle: string\n title: string\n excerpt?: string | null\n contentHtml: string\n image?: Image | null\n author?: string | null\n publishedAt?: string\n tags: string[]\n blogHandle?: string\n}\nexport interface Blog {\n id: string\n handle: string\n title: string\n articles: Article[]\n}\n\n// ───────────────────────── Pagination + filters ──────────────────\n\n/** Relay-style page info — drives \"load more\" / infinite scroll. */\nexport interface PageInfo {\n hasNextPage: boolean\n hasPreviousPage: boolean\n startCursor: string | null\n endCursor: string | null\n}\n/** A faceted filter (price / vendor / type / option) available in a result set. */\nexport interface Filter {\n id: string\n label: string\n type: string\n values: Array<{ id: string; label: string; count: number; input: string }>\n}\n\nconst EMPTY_PAGE_INFO: PageInfo = {\n hasNextPage: false,\n hasPreviousPage: false,\n startCursor: null,\n endCursor: null,\n}\nfunction normalizePageInfo(n: any): PageInfo {\n if (!n) return EMPTY_PAGE_INFO\n return {\n hasNextPage: Boolean(n.hasNextPage),\n hasPreviousPage: Boolean(n.hasPreviousPage),\n startCursor: n.startCursor ?? null,\n endCursor: n.endCursor ?? null,\n }\n}\nfunction normalizeFilters(arr: any): Filter[] {\n return (arr ?? []).map((f: any) => ({\n id: f.id,\n label: f.label,\n type: f.type,\n values: (f.values ?? []).map((v: any) => ({\n id: v.id,\n label: v.label,\n count: Number(v.count ?? 0),\n input: typeof v.input === 'string' ? v.input : JSON.stringify(v.input),\n })),\n }))\n}\n\n// ───────────────────────── Search ────────────────────────────────\n\nexport interface SearchResults {\n totalCount: number\n products: Product[]\n pages: Array<{ handle: string; title: string }>\n articles: Article[]\n /** Faceted filters available for this result set (product results). */\n filters: Filter[]\n pageInfo: PageInfo\n}\n/** A page of products from a collection (collection page + faceted filtering). */\nexport interface CollectionProductsPage {\n products: Product[]\n filters: Filter[]\n pageInfo: PageInfo\n}\nexport interface PredictiveSearchResults {\n queries: string[]\n products: Product[]\n collections: Array<{ handle: string; title: string; image?: Image | null }>\n pages: Array<{ handle: string; title: string }>\n articles: Article[]\n}\n\n// ───────────────────────── Metaobjects ───────────────────────────\n\nexport interface MetaobjectField {\n key: string\n value: string | null\n type: string\n}\nexport interface Metaobject {\n id: string\n handle: string\n type: string\n fields: MetaobjectField[]\n /** Convenience map: field key → value. */\n values: Record<string, string | null>\n}\n\n// ───────────────────────── Shop / policies ───────────────────────\n\nexport interface ShopPolicy {\n handle: string\n title: string\n url: string\n body?: string\n}\nexport interface Shop {\n name: string\n description?: string | null\n brand?: {\n logo?: Image | null\n slogan?: string | null\n shortDescription?: string | null\n } | null\n /** Custom shop metafields (\"namespace.key\" → value) for dynamic sources. */\n metafields?: Record<string, string | null>\n policies: {\n privacy?: ShopPolicy | null\n refund?: ShopPolicy | null\n termsOfService?: ShopPolicy | null\n shipping?: ShopPolicy | null\n subscription?: ShopPolicy | null\n }\n /** Cookie-consent banner config (Settings → Customer privacy). */\n cookieBanner?: {\n enabled: boolean\n dataSharingTitle?: string | null\n dataSharingVisible?: boolean\n } | null\n}\n\n// ───────────────────────── Customer ──────────────────────────────\n\nexport interface CustomerAddress {\n id: string\n firstName?: string | null\n lastName?: string | null\n company?: string | null\n address1?: string | null\n address2?: string | null\n city?: string | null\n province?: string | null\n country?: string | null\n zip?: string | null\n phone?: string | null\n formatted: string[]\n}\nexport interface Customer {\n id: string\n email?: string | null\n firstName?: string | null\n lastName?: string | null\n displayName: string\n phone?: string | null\n acceptsMarketing: boolean\n numberOfOrders: number\n defaultAddress?: CustomerAddress | null\n addresses: CustomerAddress[]\n}\nexport interface OrderLineItem {\n title: string\n variantTitle?: string | null\n quantity: number\n image?: Image | null\n totalPrice: Money\n}\nexport interface Order {\n id: string\n name: string\n orderNumber: number\n processedAt: string\n financialStatus?: string | null\n fulfillmentStatus: string\n totalPrice: Money\n statusUrl: string\n lineItems: OrderLineItem[]\n}\nexport interface CustomerAddressInput {\n firstName?: string\n lastName?: string\n company?: string\n address1?: string\n address2?: string\n city?: string\n province?: string\n country?: string\n zip?: string\n phone?: string\n}\n/** Login/register/renew result. `token` present on success; `errors` on failure. */\nexport interface AuthResult {\n token: string | null\n expiresAt: string | null\n errors: string[]\n}\nexport interface MutationResult<T = void> {\n ok: boolean\n errors: string[]\n data?: T\n}\n\n/** Customer account flow — Shopify-compatible token model. Live-only. */\nexport interface CustomerApi {\n /** Email + password → access token. Persist `token` (e.g. via customerTokenStore). */\n login(email: string, password: string): Promise<AuthResult>\n /** Invalidate the access token server-side. */\n logout(token: string): Promise<void>\n /** Extend a token nearing expiry. */\n renew(token: string): Promise<AuthResult>\n /** Create an account. Returns the new customer + (no token — call login next). */\n register(input: {\n email: string\n password: string\n firstName?: string\n lastName?: string\n phone?: string\n acceptsMarketing?: boolean\n }): Promise<MutationResult<Customer>>\n /** Current customer (account page). null when the token is invalid/expired. */\n get(token: string): Promise<Customer | null>\n /** Order history. */\n orders(token: string, opts?: { first?: number }): Promise<Order[]>\n /** Guest order lookup — orderNumber + email (no account needed). */\n orderByLookup(orderNumber: string, email: string): Promise<Order | null>\n createAddress(token: string, address: CustomerAddressInput): Promise<MutationResult<{ id: string }>>\n updateAddress(token: string, id: string, address: CustomerAddressInput): Promise<MutationResult>\n deleteAddress(token: string, id: string): Promise<MutationResult>\n setDefaultAddress(token: string, addressId: string): Promise<MutationResult>\n}\n\n/** The full set of live-only methods this module attaches to a DataApi. */\nexport interface StorefrontExtensions {\n /** Shop info + legal policies (prefetched at boot). null = mock data. */\n shop?: Shop | null\n /** A navigation menu by handle. `main-menu` + `footer` are prefetched at boot\n * (sync); other handles return null until `fetchMenu()` caches them. */\n menu?: (handle: string) => Menu | null\n /** Fetch (and cache) an arbitrary menu by handle. */\n fetchMenu?: (handle: string) => Promise<Menu | null>\n /** Full-text search across products, pages and articles (paginated + faceted). */\n search?: (\n query: string,\n opts?: {\n first?: number\n after?: string\n types?: Array<'PRODUCT' | 'PAGE' | 'ARTICLE'>\n },\n ) => Promise<SearchResults>\n /** Autocomplete suggestions (header search dropdown). */\n predictiveSearch?: (query: string, opts?: { limit?: number }) => Promise<PredictiveSearchResults>\n /** Products in a collection — paginated, sortable, faceted (collection page). */\n collectionProducts?: (\n handle: string,\n opts?: {\n first?: number\n after?: string\n sortKey?: 'TITLE' | 'PRICE' | 'BEST_SELLING' | 'CREATED' | 'MANUAL' | 'COLLECTION_DEFAULT'\n reverse?: boolean\n filters?: Array<Record<string, unknown>>\n },\n ) => Promise<CollectionProductsPage>\n /** \"You may also like\" — related products for a product node id. */\n productRecommendations?: (productId: string) => Promise<Product[]>\n /** A blog with its articles. */\n blogByHandle?: (handle: string, opts?: { articles?: number }) => Promise<Blog | null>\n /** A single article within a blog. */\n articleByHandle?: (blogHandle: string, articleHandle: string) => Promise<Article | null>\n /** A metaobject (custom content) by type + handle. */\n metaobject?: (type: string, handle: string) => Promise<Metaobject | null>\n /** All ACTIVE metaobjects of a type. */\n metaobjects?: (type: string, opts?: { first?: number }) => Promise<Metaobject[]>\n /** Customer account flow (login/register/orders/addresses). */\n customer?: CustomerApi\n}\n\n// ───────────────────────── GraphQL fragments ─────────────────────\n\nconst MENU_FIELDS = /* GraphQL */ `\n fragment MenuFields on Menu {\n id\n handle\n title\n items {\n ...MenuItemFields\n items { ...MenuItemFields items { ...MenuItemFields } }\n }\n }\n fragment MenuItemFields on MenuItem { id title url type resourceId }\n`\n\nconst ARTICLE_FIELDS = /* GraphQL */ `\n fragment ArticleFields on Article {\n id\n handle\n title\n excerpt\n contentHtml\n image { url altText }\n author: authorV2 { name }\n publishedAt\n tags\n }\n`\n\nconst PRODUCT_CARD = /* GraphQL */ `\n fragment ProductCard on Product {\n id\n handle\n title\n availableForSale\n vendor\n productType\n tags\n featuredImage { url altText }\n priceRange { minVariantPrice { amount currencyCode } }\n compareAtPriceRange { maxVariantPrice { amount currencyCode } }\n firstAvailableVariant { id }\n }\n`\n\nconst CUSTOMER_FIELDS = /* GraphQL */ `\n fragment AddressFields on MailingAddress {\n id firstName lastName company address1 address2 city province country zip phone\n formatted(withName: true)\n }\n fragment CustomerFields on Customer {\n id email firstName lastName displayName phone acceptsMarketing numberOfOrders\n defaultAddress { ...AddressFields }\n addresses(first: 20) { nodes { ...AddressFields } }\n }\n`\n\nconst ORDER_FIELDS = /* GraphQL */ `\n fragment OrderFields on Order {\n id name orderNumber processedAt financialStatus fulfillmentStatus statusUrl\n currentTotalPrice { amount currencyCode }\n lineItems(first: 50) {\n nodes {\n title variantTitle quantity\n discountedTotalPrice { amount currencyCode }\n variant { image { url altText } }\n }\n }\n }\n`\n\n// ───────────────────────── Normalizers ───────────────────────────\n\nconst ZERO: Money = { amount: '0', currencyCode: 'USD' }\n\nfunction img(node: any): Image | null {\n if (!node || !node.url) return null\n return node.altText ? { url: node.url, altText: node.altText } : { url: node.url }\n}\n\nfunction normalizeMenuItem(n: any): MenuItem {\n return {\n id: n.id,\n title: n.title,\n url: n.url ?? null,\n type: n.type,\n resourceId: n.resourceId ?? null,\n items: (n.items ?? []).map(normalizeMenuItem),\n }\n}\nfunction normalizeMenu(n: any): Menu | null {\n if (!n) return null\n return { id: n.id, handle: n.handle, title: n.title, items: (n.items ?? []).map(normalizeMenuItem) }\n}\n\nfunction normalizeArticle(n: any, blogHandle?: string): Article {\n return {\n id: n.id,\n handle: n.handle,\n title: n.title,\n excerpt: n.excerpt ?? null,\n contentHtml: n.contentHtml ?? '',\n image: img(n.image),\n author: n.author?.name ?? null,\n ...(n.publishedAt ? { publishedAt: n.publishedAt } : {}),\n tags: n.tags ?? [],\n ...(blogHandle ? { blogHandle } : {}),\n }\n}\n\nfunction normalizeMetaobject(n: any): Metaobject {\n const fields: MetaobjectField[] = (n.fields ?? []).map((f: any) => ({\n key: f.key,\n value: f.value ?? null,\n type: f.type,\n }))\n const values: Record<string, string | null> = {}\n for (const f of fields) values[f.key] = f.value\n return { id: n.id, handle: n.handle, type: n.type, fields, values }\n}\n\nfunction normalizeAddress(n: any): CustomerAddress {\n return {\n id: n.id,\n firstName: n.firstName ?? null,\n lastName: n.lastName ?? null,\n company: n.company ?? null,\n address1: n.address1 ?? null,\n address2: n.address2 ?? null,\n city: n.city ?? null,\n province: n.province ?? null,\n country: n.country ?? null,\n zip: n.zip ?? null,\n phone: n.phone ?? null,\n formatted: n.formatted ?? [],\n }\n}\nfunction normalizeCustomer(n: any): Customer {\n return {\n id: n.id,\n email: n.email ?? null,\n firstName: n.firstName ?? null,\n lastName: n.lastName ?? null,\n displayName: n.displayName ?? '',\n phone: n.phone ?? null,\n acceptsMarketing: Boolean(n.acceptsMarketing),\n numberOfOrders: Number(n.numberOfOrders ?? 0),\n defaultAddress: n.defaultAddress ? normalizeAddress(n.defaultAddress) : null,\n addresses: (n.addresses?.nodes ?? []).map(normalizeAddress),\n }\n}\nfunction normalizeOrder(n: any): Order {\n return {\n id: n.id,\n name: n.name,\n orderNumber: Number(n.orderNumber ?? 0),\n processedAt: n.processedAt,\n financialStatus: n.financialStatus ?? null,\n fulfillmentStatus: n.fulfillmentStatus ?? 'UNFULFILLED',\n totalPrice: n.currentTotalPrice ?? ZERO,\n statusUrl: n.statusUrl ?? '',\n lineItems: (n.lineItems?.nodes ?? []).map((li: any) => ({\n title: li.title,\n variantTitle: li.variantTitle ?? null,\n quantity: Number(li.quantity ?? 0),\n image: img(li.variant?.image),\n totalPrice: li.discountedTotalPrice ?? ZERO,\n })),\n }\n}\nfunction normalizeShopPolicy(n: any): ShopPolicy | null {\n if (!n) return null\n return { handle: n.handle, title: n.title, url: n.url, ...(n.body ? { body: n.body } : {}) }\n}\nfunction normalizeShop(n: any): Shop | null {\n if (!n) return null\n return {\n name: n.name,\n description: n.description ?? null,\n brand: n.brand\n ? {\n logo: img(n.brand.logo),\n slogan: n.brand.slogan ?? null,\n shortDescription: n.brand.shortDescription ?? null,\n }\n : null,\n policies: {\n privacy: normalizeShopPolicy(n.privacyPolicy),\n refund: normalizeShopPolicy(n.refundPolicy),\n termsOfService: normalizeShopPolicy(n.termsOfService),\n shipping: normalizeShopPolicy(n.shippingPolicy),\n subscription: normalizeShopPolicy(n.subscriptionPolicy),\n },\n cookieBanner: n.cookieBanner\n ? {\n enabled: Boolean(n.cookieBanner.enabled),\n dataSharingTitle: n.cookieBanner.dataSharingTitle ?? null,\n dataSharingVisible: n.cookieBanner.dataSharingVisible !== false,\n }\n : null,\n }\n}\n\n/** UserError[] → message strings. */\nfunction errs(arr: any): string[] {\n return (arr ?? []).map((e: any) => e?.message).filter((m: any): m is string => Boolean(m))\n}\n\n// ─── Bootstrap fields (merged into data.tsx's boot query) ─────────\n\n/** GraphQL selection for shop + the two standard menus, spliced into the\n * homepage bootstrap so the layout (nav + footer + policies) renders sync. */\nexport const BOOTSTRAP_SHOP_MENU = /* GraphQL */ `\n shop {\n name\n description\n brand { logo { url altText } slogan shortDescription }\n privacyPolicy { handle title url }\n refundPolicy { handle title url }\n termsOfService { handle title url }\n shippingPolicy { handle title url }\n subscriptionPolicy { handle title url }\n cookieBanner { enabled dataSharingTitle dataSharingVisible }\n }\n mainMenu: menu(handle: \"main-menu\") { ...MenuFields }\n footerMenu: menu(handle: \"footer\") { ...MenuFields }\n`\n/** Fragment defs the bootstrap query must include when it uses BOOTSTRAP_SHOP_MENU. */\nexport const BOOTSTRAP_SHOP_MENU_FRAGMENTS = MENU_FIELDS\n\n/** Pull shop + the prefetched menus out of a bootstrap response. */\nexport function readBootstrapShopMenu(boot: any): {\n shop: Shop | null\n menus: Map<string, Menu>\n} {\n const menus = new Map<string, Menu>()\n const main = normalizeMenu(boot?.mainMenu)\n if (main) menus.set('main-menu', main)\n const footer = normalizeMenu(boot?.footerMenu)\n if (footer) menus.set('footer', footer)\n return { shop: normalizeShop(boot?.shop), menus }\n}\n\n// ───────────────────────── Factory ───────────────────────────────\n\n/**\n * Build the live storefront extension methods on top of a `graphql()` requester.\n * `menuCache` is shared with the boot-prefetched menus so `fetchMenu()` warms\n * the same map that the sync `menu()` reads.\n */\nexport function createStorefrontMethods(\n graphql: GraphqlFn,\n helpers: StorefrontHelpers,\n menuCache: Map<string, Menu>,\n): Required<Omit<StorefrontExtensions, 'shop' | 'menu'>> {\n const { normalizeProduct } = helpers\n\n const fetchMenu = async (handle: string): Promise<Menu | null> => {\n const cached = menuCache.get(handle)\n if (cached) return cached\n const res = await graphql<{ menu: any }>(\n `${MENU_FIELDS}\\n query Menu($handle: String!) { menu(handle: $handle) { ...MenuFields } }`,\n { handle },\n )\n const menu = normalizeMenu(res?.menu)\n if (menu) menuCache.set(handle, menu)\n return menu\n }\n\n const search: NonNullable<StorefrontExtensions['search']> = async (query, opts) => {\n const res = await graphql<{ search: any }>(\n `${PRODUCT_CARD}${ARTICLE_FIELDS}\n query Search($query: String!, $first: Int!, $after: String, $types: [SearchType!]) {\n search(query: $query, first: $first, after: $after, types: $types) {\n totalCount\n productFilters { id label type values { id label count input } }\n pageInfo { hasNextPage hasPreviousPage startCursor endCursor }\n nodes {\n __typename\n ... on Product { ...ProductCard }\n ... on Page { handle title }\n ... on Article { ...ArticleFields }\n }\n }\n }`,\n { query, first: opts?.first ?? 24, after: opts?.after ?? null, types: opts?.types ?? null },\n )\n const s = res?.search ?? {}\n const nodes: any[] = s.nodes ?? []\n return {\n totalCount: Number(s.totalCount ?? 0),\n products: nodes.filter((n) => n.__typename === 'Product').map(normalizeProduct),\n pages: nodes\n .filter((n) => n.__typename === 'Page')\n .map((n) => ({ handle: n.handle, title: n.title })),\n articles: nodes.filter((n) => n.__typename === 'Article').map((n) => normalizeArticle(n)),\n filters: normalizeFilters(s.productFilters),\n pageInfo: normalizePageInfo(s.pageInfo),\n }\n }\n\n const collectionProducts: NonNullable<StorefrontExtensions['collectionProducts']> = async (\n handle,\n opts,\n ) => {\n const res = await graphql<{ collection: any }>(\n `${PRODUCT_CARD}\n query CollectionProducts(\n $handle: String!, $first: Int!, $after: String,\n $sortKey: ProductCollectionSortKey, $reverse: Boolean, $filters: [ProductFilterInput!]\n ) {\n collection(handle: $handle) {\n products(first: $first, after: $after, sortKey: $sortKey, reverse: $reverse, filters: $filters) {\n nodes { ...ProductCard }\n filters { id label type values { id label count input } }\n pageInfo { hasNextPage hasPreviousPage startCursor endCursor }\n }\n }\n }`,\n {\n handle,\n first: opts?.first ?? 24,\n after: opts?.after ?? null,\n sortKey: opts?.sortKey ?? null,\n reverse: opts?.reverse ?? null,\n filters: opts?.filters ?? null,\n },\n )\n const c = res?.collection?.products ?? {}\n return {\n products: (c.nodes ?? []).map(normalizeProduct),\n filters: normalizeFilters(c.filters),\n pageInfo: normalizePageInfo(c.pageInfo),\n }\n }\n\n const predictiveSearch: NonNullable<StorefrontExtensions['predictiveSearch']> = async (\n query,\n opts,\n ) => {\n const res = await graphql<{ predictiveSearch: any }>(\n `${PRODUCT_CARD}${ARTICLE_FIELDS}\n query Predictive($query: String!, $limit: Int!) {\n predictiveSearch(query: $query, limit: $limit) {\n queries { text }\n products { ...ProductCard }\n collections { handle title image { url altText } }\n pages { handle title }\n articles { ...ArticleFields }\n }\n }`,\n { query, limit: opts?.limit ?? 4 },\n )\n const ps = res?.predictiveSearch ?? {}\n return {\n queries: (ps.queries ?? []).map((q: any) => q.text),\n products: (ps.products ?? []).map(normalizeProduct),\n collections: (ps.collections ?? []).map((c: any) => ({\n handle: c.handle,\n title: c.title,\n image: img(c.image),\n })),\n pages: (ps.pages ?? []).map((p: any) => ({ handle: p.handle, title: p.title })),\n articles: (ps.articles ?? []).map((a: any) => normalizeArticle(a)),\n }\n }\n\n const productRecommendations: NonNullable<\n StorefrontExtensions['productRecommendations']\n > = async (productId) => {\n const res = await graphql<{ productRecommendations: any[] }>(\n `${PRODUCT_CARD}\n query Recs($productId: ID!) {\n productRecommendations(productId: $productId) { ...ProductCard }\n }`,\n { productId },\n )\n return (res?.productRecommendations ?? []).map(normalizeProduct)\n }\n\n const blogByHandle: NonNullable<StorefrontExtensions['blogByHandle']> = async (handle, opts) => {\n const res = await graphql<{ blog: any }>(\n `${ARTICLE_FIELDS}\n query Blog($handle: String!, $first: Int!) {\n blog(handle: $handle) {\n id handle title\n articles(first: $first) { nodes { ...ArticleFields } }\n }\n }`,\n { handle, first: opts?.articles ?? 20 },\n )\n const b = res?.blog\n if (!b) return null\n return {\n id: b.id,\n handle: b.handle,\n title: b.title,\n articles: (b.articles?.nodes ?? []).map((a: any) => normalizeArticle(a, b.handle)),\n }\n }\n\n const articleByHandle: NonNullable<StorefrontExtensions['articleByHandle']> = async (\n blogHandle,\n articleHandle,\n ) => {\n const res = await graphql<{ article: any }>(\n `${ARTICLE_FIELDS}\n query Article($handle: ArticleHandleInput!) {\n article(handle: $handle) { ...ArticleFields }\n }`,\n { handle: { blogHandle, articleHandle } },\n )\n return res?.article ? normalizeArticle(res.article, blogHandle) : null\n }\n\n const metaobject: NonNullable<StorefrontExtensions['metaobject']> = async (type, handle) => {\n const res = await graphql<{ metaobject: any }>(\n `query Metaobject($handle: MetaobjectHandleInput!) {\n metaobject(handle: $handle) { id handle type fields { key value type } }\n }`,\n { handle: { type, handle } },\n )\n return res?.metaobject ? normalizeMetaobject(res.metaobject) : null\n }\n\n const metaobjects: NonNullable<StorefrontExtensions['metaobjects']> = async (type, opts) => {\n const res = await graphql<{ metaobjects: any }>(\n `query Metaobjects($type: String!, $first: Int!) {\n metaobjects(type: $type, first: $first) {\n nodes { id handle type fields { key value type } }\n }\n }`,\n { type, first: opts?.first ?? 50 },\n )\n return (res?.metaobjects?.nodes ?? []).map(normalizeMetaobject)\n }\n\n // ─── Customer account flow ──────────────────────────────────────\n\n const customer: CustomerApi = {\n async login(email, password) {\n const res = await graphql<{ customerAccessTokenCreate: any }>(\n `mutation Login($input: CustomerAccessTokenCreateInput!) {\n customerAccessTokenCreate(input: $input) {\n customerAccessToken { accessToken expiresAt }\n customerUserErrors { message }\n }\n }`,\n { input: { email, password } },\n )\n const p = res?.customerAccessTokenCreate\n return {\n token: p?.customerAccessToken?.accessToken ?? null,\n expiresAt: p?.customerAccessToken?.expiresAt ?? null,\n errors: errs(p?.customerUserErrors),\n }\n },\n async logout(token) {\n await graphql(\n `mutation Logout($t: String!) {\n customerAccessTokenDelete(customerAccessToken: $t) { deletedAccessToken userErrors { message } }\n }`,\n { t: token },\n )\n },\n async renew(token) {\n const res = await graphql<{ customerAccessTokenRenew: any }>(\n `mutation Renew($t: String!) {\n customerAccessTokenRenew(customerAccessToken: $t) {\n customerAccessToken { accessToken expiresAt }\n userErrors { message }\n }\n }`,\n { t: token },\n )\n const p = res?.customerAccessTokenRenew\n return {\n token: p?.customerAccessToken?.accessToken ?? null,\n expiresAt: p?.customerAccessToken?.expiresAt ?? null,\n errors: errs(p?.userErrors),\n }\n },\n async register(input) {\n const res = await graphql<{ customerCreate: any }>(\n `${CUSTOMER_FIELDS}\n mutation Register($input: CustomerCreateInput!) {\n customerCreate(input: $input) {\n customer { ...CustomerFields }\n customerUserErrors { message }\n }\n }`,\n { input },\n )\n const p = res?.customerCreate\n const errors = errs(p?.customerUserErrors)\n return {\n ok: Boolean(p?.customer) && errors.length === 0,\n errors,\n ...(p?.customer ? { data: normalizeCustomer(p.customer) } : {}),\n }\n },\n async get(token) {\n const res = await graphql<{ customer: any }>(\n `${CUSTOMER_FIELDS}\n query Me($t: String) { customer(customerAccessToken: $t) { ...CustomerFields } }`,\n { t: token },\n )\n return res?.customer ? normalizeCustomer(res.customer) : null\n },\n async orders(token, opts) {\n const res = await graphql<{ customer: any }>(\n `${ORDER_FIELDS}\n query Orders($t: String, $first: Int!) {\n customer(customerAccessToken: $t) {\n orders(first: $first, sortKey: PROCESSED_AT, reverse: true) { nodes { ...OrderFields } }\n }\n }`,\n { t: token, first: opts?.first ?? 20 },\n )\n return (res?.customer?.orders?.nodes ?? []).map(normalizeOrder)\n },\n async orderByLookup(orderNumber, email) {\n const res = await graphql<{ orderByLookup: any }>(\n `${ORDER_FIELDS}\n query Lookup($n: String!, $e: String!) {\n orderByLookup(orderNumber: $n, email: $e) { ...OrderFields }\n }`,\n { n: orderNumber, e: email },\n )\n return res?.orderByLookup ? normalizeOrder(res.orderByLookup) : null\n },\n async createAddress(token, address) {\n const res = await graphql<{ customerAddressCreate: any }>(\n `mutation AddrCreate($t: String!, $a: MailingAddressInput!) {\n customerAddressCreate(customerAccessToken: $t, address: $a) {\n customerAddress { id }\n customerUserErrors { message }\n }\n }`,\n { t: token, a: address },\n )\n const p = res?.customerAddressCreate\n const errors = errs(p?.customerUserErrors)\n return {\n ok: Boolean(p?.customerAddress?.id) && errors.length === 0,\n errors,\n ...(p?.customerAddress?.id ? { data: { id: p.customerAddress.id as string } } : {}),\n }\n },\n async updateAddress(token, id, address) {\n const res = await graphql<{ customerAddressUpdate: any }>(\n `mutation AddrUpdate($t: String!, $id: ID!, $a: MailingAddressInput!) {\n customerAddressUpdate(customerAccessToken: $t, id: $id, address: $a) {\n customerAddress { id }\n customerUserErrors { message }\n }\n }`,\n { t: token, id, a: address },\n )\n const errors = errs(res?.customerAddressUpdate?.customerUserErrors)\n return { ok: errors.length === 0, errors }\n },\n async deleteAddress(token, id) {\n const res = await graphql<{ customerAddressDelete: any }>(\n `mutation AddrDelete($t: String!, $id: ID!) {\n customerAddressDelete(customerAccessToken: $t, id: $id) {\n deletedCustomerAddressId\n customerUserErrors { message }\n }\n }`,\n { t: token, id },\n )\n const errors = errs(res?.customerAddressDelete?.customerUserErrors)\n return { ok: errors.length === 0, errors }\n },\n async setDefaultAddress(token, addressId) {\n const res = await graphql<{ customerDefaultAddressUpdate: any }>(\n `mutation AddrDefault($t: String!, $id: ID!) {\n customerDefaultAddressUpdate(customerAccessToken: $t, addressId: $id) {\n customer { id }\n customerUserErrors { message }\n }\n }`,\n { t: token, id: addressId },\n )\n const errors = errs(res?.customerDefaultAddressUpdate?.customerUserErrors)\n return { ok: errors.length === 0, errors }\n },\n }\n\n return {\n fetchMenu,\n search,\n collectionProducts,\n predictiveSearch,\n productRecommendations,\n blogByHandle,\n articleByHandle,\n metaobject,\n metaobjects,\n customer,\n }\n}\n\n// ───────────────────────── Token storage helper ──────────────────\n\nconst CUSTOMER_TOKEN_KEY = 'tq-customer-token'\n\n/** Tiny localStorage helper for the customer access token (SSR-safe no-ops). */\nexport const customerTokenStore = {\n get(): string | null {\n if (typeof localStorage === 'undefined') return null\n return localStorage.getItem(CUSTOMER_TOKEN_KEY)\n },\n set(token: string): void {\n if (typeof localStorage === 'undefined') return\n localStorage.setItem(CUSTOMER_TOKEN_KEY, token)\n },\n clear(): void {\n if (typeof localStorage === 'undefined') return\n localStorage.removeItem(CUSTOMER_TOKEN_KEY)\n },\n}\n","import { createContext, useContext, type ReactNode } from 'react'\nimport {\n type StorefrontExtensions,\n type Menu,\n type MenuItem,\n type MenuItemType,\n type Article,\n type Blog,\n type Shop,\n createStorefrontMethods,\n BOOTSTRAP_SHOP_MENU,\n BOOTSTRAP_SHOP_MENU_FRAGMENTS,\n readBootstrapShopMenu,\n} from './storefront'\n\nexport interface Money {\n amount: string\n currencyCode: string\n}\nexport interface ProductOption {\n name: string\n values: string[]\n}\nexport interface ImageRef {\n url: string\n altText?: string\n}\n/** SEO snapshot (Product/Page/Article). */\nexport interface Seo {\n title?: string | null\n description?: string | null\n}\n/** Per-variant cart quantity bounds (wholesale / case-of-N). Storefront cart enforces these. */\nexport interface QuantityRule {\n minimum: number\n maximum: number | null\n increment: number\n}\n/** Per-unit pricing (\"$2.50 / 100ml\"). */\nexport interface UnitPriceMeasurement {\n measuredType: string\n quantityValue: number\n quantityUnit: string\n referenceValue: number\n referenceUnit: string\n}\n/** Pickup / in-store stock for one location. */\nexport interface StoreAvailability {\n available: boolean\n quantityAvailable: number\n pickUpTime?: string | null\n location: { id: string; name: string }\n}\nexport interface SellingPlanOption {\n name: string\n value: string\n}\nexport interface SellingPlan {\n id: string\n name: string\n description?: string | null\n recurringDeliveries: boolean\n options: SellingPlanOption[]\n}\nexport interface SellingPlanGroup {\n name: string\n appName?: string | null\n options: Array<{ name: string; values: string[] }>\n sellingPlans: SellingPlan[]\n}\nexport interface ProductVariant {\n id: string\n title: string\n price: Money\n /** \"Was\" price — present when the variant is on sale (compareAtPrice > price). */\n compareAtPrice?: Money | null\n availableForSale: boolean\n selectedOptions?: { name: string; value: string }[]\n image?: ImageRef | null\n /** Stock-keeping unit. Only after `fetchProduct()`. */\n sku?: string | null\n /** Cart quantity bounds (min/max/increment). */\n quantityRule?: QuantityRule\n /** Per-unit price (\"$2.50 / 100ml\") for measured products. */\n unitPrice?: Money | null\n unitPriceMeasurement?: UnitPriceMeasurement | null\n /** Pickup availability per location (only after `fetchProduct()`). */\n storeAvailability?: StoreAvailability[]\n}\nexport interface Product {\n /** Storefront GraphQL node id (present for live data). */\n id?: string\n handle: string\n title: string\n price: Money\n /** Range \"was\" price (max compareAtPrice across variants) — sale badge on cards. */\n compareAtPrice?: Money | null\n featuredImage?: ImageRef | null\n /** Default purchasable variant id (`firstAvailableVariant`) — enough to add\n * to cart from a grid/card without loading the full variant list. */\n variantId?: string\n availableForSale?: boolean\n /** Catalog facets (card badges / filtering). Present from boot. */\n vendor?: string | null\n productType?: string | null\n tags?: string[]\n /** Long description — only populated by `fetchProduct()` (PDP). */\n description?: string\n /** Image gallery — only after `fetchProduct()` (PDP). */\n images?: ImageRef[]\n /** Option definitions (Size, Color…) — only after `fetchProduct()`. */\n options?: ProductOption[]\n /** Full variant list — only after `fetchProduct()` (PDP). */\n variants?: ProductVariant[]\n /** Subscription / selling-plan groups — only after `fetchProduct()`. */\n sellingPlanGroups?: SellingPlanGroup[]\n /** Requested custom metafields (\"namespace.key\" → value) — pass identifiers to fetchProduct(). */\n metafields?: Record<string, string | null>\n /** SEO override — only after `fetchProduct()`. */\n seo?: Seo | null\n}\nexport interface Collection {\n handle: string\n title: string\n /** Optional hero image; falls back to first product's featuredImage. */\n image?: { url?: string; altText?: string } | null\n products: Product[]\n /** Custom metafields (\"namespace.key\" → value) for dynamic sources. */\n metafields?: Record<string, string | null>\n}\nexport interface Page {\n handle: string\n title: string\n /** HTML body — rendered via dangerouslySetInnerHTML by the PageBody section. */\n body: string\n bodySummary?: string\n author?: string | null\n publishedAt?: string\n updatedAt?: string\n}\n\n/**\n * The data interface every block consumes. Themes provide an implementation.\n *\n * Core read methods (collections/products/pages/localization) are always\n * present. The Shopify-compatible extensions (shop, menus, search, blog,\n * recommendations, metaobjects, customer account) come from `StorefrontExtensions`\n * and are LIVE-ONLY — undefined under mock data, so themes feature-detect them\n * (`data.search?.(...)`, `data.customer?.login(...)`).\n */\nexport interface DataApi extends StorefrontExtensions {\n collectionByHandle: (handle: string) => Collection | null\n /** All known collections (used by CollectionList). */\n allCollections: () => Collection[]\n /**\n * List every navigation menu the store has (Dashboard → Navigation), for the\n * editor's `link_list` picker. Identity only (handle/title/count) — fetch a\n * menu's items with `fetchMenu(handle)`. Optional: older payloads may omit it.\n */\n listMenus?: () => Promise<Array<{ handle: string; title: string; itemsCount: number }>>\n /** Connected tracking pixels (Settings → Customer events) to inject on the\n * storefront. Optional — older payloads / mock mode return []. */\n pixels?: () => Promise<\n Array<{\n id: string\n name: string\n provider: string | null\n providerPixelId: string | null\n code: string | null\n }>\n >\n /** Physical store locations (Settings → Locations) for a store-locator. */\n locations?: () => Promise<\n Array<{\n id: string\n name: string\n code: string | null\n address: {\n country: string | null\n address: string | null\n city: string | null\n province: string | null\n postalCode: string | null\n phone: string | null\n } | null\n }>\n >\n /**\n * Look up a single product by its handle. Returns null when the handle\n * isn't found. Required by FeaturedProduct / ProductDetails sections\n * (ported from the canonical examples/react theme in PR #2).\n */\n productByHandle: (handle: string) => Product | null\n /**\n * Look up a Page by handle (the storefront's `/pages/<handle>` content).\n * Returns null if the handle wasn't prefetched at boot or the merchant\n * hasn't published a page with that handle. Live data prefetches only the\n * page matching the current URL, so other handles return null even when\n * they exist in the backend — themes should only call this for the page\n * the user is on.\n */\n pageByHandle: (handle: string) => Page | null\n /** Localization snapshot — what markets/countries the store has live.\n * null = mock data; the country switcher should hide itself. */\n localization: Localization | null\n /**\n * Raw GraphQL escape hatch against the same storefront endpoint the live\n * data source was booted with. Present ONLY for live data — undefined for\n * mock data. Powers post-boot interactions (the cart's mutations live here).\n */\n graphql?: <T = unknown>(query: string, variables?: Record<string, unknown>) => Promise<T>\n /**\n * Fetch a single product WITH its full options + variants on demand (for the\n * product page's variant picker). Live data hits the backend; mock data\n * resolves synchronously from the prefetched cache. Returns null if missing.\n */\n fetchProduct?: (\n handle: string,\n opts?: { metafields?: Array<{ namespace: string; key: string }> },\n ) => Promise<Product | null>\n /**\n * Fetch the shop's custom metafields by identifier (for dynamic sources).\n * Live data queries `shop { metafields(identifiers) }`; mock data returns {}\n * (no metafields offline). Result keys are \"namespace.key\".\n */\n fetchShopMetafields?: (\n identifiers: Array<{ namespace: string; key: string }>,\n ) => Promise<Record<string, string | null>>\n /**\n * Fetch a collection's custom metafields by identifier (for dynamic sources).\n * Result keys are \"namespace.key\".\n */\n fetchCollectionMetafields?: (\n handle: string,\n identifiers: Array<{ namespace: string; key: string }>,\n ) => Promise<Record<string, string | null>>\n /**\n * The raw serializable bootstrap payload this live DataApi was built from\n * (null for mock data). The SSG step embeds it into the page as\n * `window.__TQ_STATE__` so the client can rebuild the identical DataApi\n * synchronously at hydration via createLiveDataFromSnapshot — SSR markup and\n * the client's first render match by construction.\n */\n getSnapshot?: () => unknown\n}\n\n/** Country/market shape mirrored from storefront GraphQL `Localization`. */\nexport interface LocalizedCurrency {\n isoCode: string\n name?: string\n symbol?: string\n}\nexport interface LocalizedMarket {\n id: string\n handle: string\n name: string\n}\nexport interface LocalizedCountry {\n isoCode: string\n name: string\n currency: LocalizedCurrency\n market: LocalizedMarket | null\n}\n/** A language the store has published (dashboard → Markets / Languages). */\nexport interface LocalizedLanguage {\n isoCode: string\n name: string\n}\nexport interface Localization {\n /** Currently-active country (resolved from the request's X-Tanqory-Country). */\n country: LocalizedCountry\n /** Every country the store has an active Market for — what the picker shows. */\n availableCountries: LocalizedCountry[]\n /**\n * Currently-active language + every language the store has PUBLISHED. These\n * are STORE/dashboard data (the merchant's published locales), not a theme\n * config list — the theme only ships the translations. Optional so older live\n * payloads (countries only) still satisfy the type; the picker falls back to a\n * single default when absent.\n */\n language?: LocalizedLanguage\n availableLanguages?: LocalizedLanguage[]\n}\n\nconst DataContext = createContext<DataApi | null>(null)\n\n/** Wraps the app with a theme-provided data source (mock or live). */\nexport function DataProvider({ value, children }: { value: DataApi; children: ReactNode }): JSX.Element {\n return <DataContext.Provider value={value}>{children}</DataContext.Provider>\n}\n\nexport function useData(): DataApi {\n const ctx = useContext(DataContext)\n if (!ctx) throw new Error('useData must be used within <DataProvider>')\n return ctx\n}\n\n/** Build an offline data source from fixture collections (theme passes its JSON). */\nexport function createMockData(collections: Collection[]): DataApi {\n // Flatten products from every collection once; subsequent lookups are O(1)\n // by handle. A product appearing in multiple collections returns the first\n // occurrence — matching the storefront's \"canonical product page\" semantics.\n const productsByHandle = new Map<string, Product>()\n const allProducts: Product[] = []\n for (const c of collections) {\n for (const p of c.products) {\n if (!productsByHandle.has(p.handle)) {\n productsByHandle.set(p.handle, p)\n allProducts.push(p)\n }\n }\n }\n\n // ── Offline fixtures so EVERY Shopify-parity object resolves in mock mode ──\n // The live source (createLiveData) serves these from the Storefront GraphQL\n // API; mock mode must mirror the same shapes so a developer can build header\n // menus, blog, search, customer + shop sections fully offline (no store).\n const mkItem = (id: string, title: string, url: string, type: MenuItemType = 'HTTP'): MenuItem =>\n ({ id, title, url, type, items: [] })\n const mkMenu = (handle: string, title: string, items: MenuItem[]): Menu =>\n ({ id: `mock/menu/${handle}`, handle, title, items })\n\n const mainMenu = mkMenu('main-menu', 'Main menu', [\n { ...mkItem('mm-shop', 'Shop', '/collections/all', 'COLLECTIONS'),\n // submenu: the store's collections, so the header dropdown is real data\n items: collections.slice(0, 6).map((c, i) => mkItem(`mm-shop-${i}`, c.title, `/collections/${c.handle}`, 'COLLECTION')) },\n mkItem('mm-collections', 'Collections', '/collections', 'CATALOG'),\n mkItem('mm-about', 'About', '/pages/about', 'PAGE'),\n mkItem('mm-journal', 'Journal', '/blogs/news', 'BLOG'),\n ])\n const menus = new Map<string, Menu>([\n ['main-menu', mainMenu],\n ['footer', mkMenu('footer', 'Footer', [\n mkItem('fm-privacy', 'Privacy policy', '/policies/privacy-policy', 'SHOP_POLICY'),\n mkItem('fm-contact', 'Contact', '/pages/contact', 'PAGE'),\n ])],\n ['footer-shop', mkMenu('footer-shop', 'Shop', [\n mkItem('fs-all', 'All products', '/collections/all'),\n mkItem('fs-new', 'New arrivals', '/collections/new'),\n mkItem('fs-sale', 'Sale', '/collections/sale'),\n mkItem('fs-gift', 'Gift cards', '/products/gift-card'),\n ])],\n ['footer-help', mkMenu('footer-help', 'Help', [\n mkItem('fh-contact', 'Contact', '/pages/contact'),\n mkItem('fh-ship', 'Shipping', '/pages/shipping'),\n mkItem('fh-returns', 'Returns', '/pages/returns'),\n mkItem('fh-faq', 'FAQ', '/pages/faq'),\n ])],\n ['footer-company', mkMenu('footer-company', 'Company', [\n mkItem('fc-about', 'About', '/pages/about'),\n mkItem('fc-journal', 'Journal', '/blogs/news'),\n mkItem('fc-sustain', 'Sustainability', '/pages/sustainability'),\n mkItem('fc-press', 'Press', '/pages/press'),\n ])],\n ])\n\n const articles: Article[] = [\n {\n id: 'mock/article/welcome',\n handle: 'welcome',\n title: 'Welcome to the shop',\n excerpt: 'A quick hello and what to expect.',\n contentHtml: '<p>Welcome — this is mock article content for local development.</p>',\n image: null,\n author: 'Studio',\n publishedAt: '2024-01-01T00:00:00.000Z',\n tags: ['news'],\n blogHandle: 'news',\n },\n {\n id: 'mock/article/behind-the-design',\n handle: 'behind-the-design',\n title: 'Behind the design',\n excerpt: 'How this starter theme is built.',\n contentHtml: '<p>Built with Tanqory theme-kit sections.</p>',\n image: null,\n author: 'Studio',\n publishedAt: '2024-01-02T00:00:00.000Z',\n tags: ['design'],\n blogHandle: 'news',\n },\n ]\n const blog: Blog = { id: 'mock/blog/news', handle: 'news', title: 'News', articles }\n\n const shop: Shop = {\n name: 'nova',\n description: 'A clean starter storefront powered by Tanqory.',\n brand: { logo: null, slogan: 'Modern essentials', shortDescription: 'Starter theme' },\n policies: {\n privacy: { handle: 'privacy-policy', title: 'Privacy policy', url: '/policies/privacy-policy', body: '<p>Mock privacy policy.</p>' },\n refund: { handle: 'refund-policy', title: 'Refund policy', url: '/policies/refund-policy', body: '<p>Mock refund policy.</p>' },\n termsOfService: { handle: 'terms-of-service', title: 'Terms of service', url: '/policies/terms-of-service', body: '<p>Mock terms of service.</p>' },\n shipping: { handle: 'shipping-policy', title: 'Shipping policy', url: '/policies/shipping-policy', body: '<p>Mock shipping policy.</p>' },\n subscription: null,\n },\n cookieBanner: { enabled: true, dataSharingTitle: 'Do not sell or share my personal information', dataSharingVisible: true },\n }\n\n const EMPTY_PI = { hasNextPage: false, hasPreviousPage: false, startCursor: null, endCursor: null }\n const match = (q: string) => {\n const needle = q.trim().toLowerCase()\n return needle ? allProducts.filter((p) => p.title.toLowerCase().includes(needle)) : []\n }\n\n return {\n collectionByHandle: (handle) => collections.find((c) => c.handle === handle) ?? null,\n allCollections: () => collections,\n productByHandle: (handle) => productsByHandle.get(handle) ?? null,\n pageByHandle: () => null,\n // Localization mirrors what the store DASHBOARD (Markets) would publish —\n // NOT a theme config list. Countries carry their currency; languages are the\n // store's published locales. The live source fills this from store-api.\n localization: {\n country: { isoCode: 'TH', name: 'Thailand', currency: { isoCode: 'THB', symbol: '฿' }, market: null },\n availableCountries: [\n { isoCode: 'TH', name: 'Thailand', currency: { isoCode: 'THB', symbol: '฿' }, market: null },\n { isoCode: 'US', name: 'United States', currency: { isoCode: 'USD', symbol: '$' }, market: null },\n { isoCode: 'JP', name: 'Japan', currency: { isoCode: 'JPY', symbol: '¥' }, market: null },\n { isoCode: 'SG', name: 'Singapore', currency: { isoCode: 'SGD', symbol: 'S$' }, market: null },\n { isoCode: 'GB', name: 'United Kingdom', currency: { isoCode: 'GBP', symbol: '£' }, market: null },\n ],\n language: { isoCode: 'en', name: 'English' },\n availableLanguages: [\n { isoCode: 'en', name: 'English' },\n { isoCode: 'th', name: 'ไทย' },\n { isoCode: 'ja', name: '日本語' },\n ],\n },\n\n // ── Shopify-parity extensions, served offline from the fixtures above so\n // themes built against `useData()` behave the same in mock + live. ──\n shop,\n menu: (handle) => menus.get(handle) ?? null,\n fetchMenu: async (handle) => menus.get(handle) ?? null,\n listMenus: async () =>\n Array.from(menus.values()).map((m) => ({\n handle: m.handle,\n title: m.title,\n itemsCount: m.items.length,\n })),\n pixels: async () => [],\n locations: async () => [],\n search: async (query, opts) => {\n const types = opts?.types ?? ['PRODUCT', 'PAGE', 'ARTICLE']\n const products = types.includes('PRODUCT') ? match(query) : []\n const arts = types.includes('ARTICLE')\n ? articles.filter((a) => a.title.toLowerCase().includes(query.trim().toLowerCase()))\n : []\n return { totalCount: products.length + arts.length, products, pages: [], articles: arts, filters: [], pageInfo: EMPTY_PI }\n },\n predictiveSearch: async (query, opts) => {\n const products = match(query).slice(0, opts?.limit ?? 4)\n return {\n queries: products.slice(0, 3).map((p) => p.title),\n products,\n collections: collections\n .filter((c) => c.title.toLowerCase().includes(query.trim().toLowerCase()))\n .slice(0, 3)\n .map((c) => ({ handle: c.handle, title: c.title, image: null })),\n pages: [],\n articles: [],\n }\n },\n collectionProducts: async (handle, opts) => {\n const c = collections.find((x) => x.handle === handle)\n return { products: (c?.products ?? []).slice(0, opts?.first ?? 24), filters: [], pageInfo: EMPTY_PI }\n },\n productRecommendations: async (productId) => allProducts.filter((p) => p.id !== productId).slice(0, 4),\n blogByHandle: async (handle) => (handle === blog.handle ? blog : null),\n articleByHandle: async (blogHandle, articleHandle) =>\n blogHandle === blog.handle ? articles.find((a) => a.handle === articleHandle) ?? null : null,\n metaobject: async () => null,\n metaobjects: async () => [],\n customer: {\n login: async () => ({ token: null, expiresAt: null, errors: ['Customer accounts need live data (mock mode).'] }),\n logout: async () => {},\n renew: async () => ({ token: null, expiresAt: null, errors: ['Customer accounts need live data (mock mode).'] }),\n register: async () => ({ ok: false, errors: ['Customer accounts need live data (mock mode).'] }),\n get: async () => null,\n orders: async () => [],\n orderByLookup: async () => null,\n createAddress: async () => ({ ok: false, errors: ['mock mode'] }),\n updateAddress: async () => ({ ok: false, errors: ['mock mode'] }),\n deleteAddress: async () => ({ ok: false, errors: ['mock mode'] }),\n setDefaultAddress: async () => ({ ok: false, errors: ['mock mode'] }),\n },\n }\n}\n\n/**\n * Live data source backed by the Tanqory Storefront GraphQL API.\n *\n * const data = await createLiveData({\n * endpoint: 'https://api-do-sgp1.tanqory.com',\n * storeId: '<store-uuid>',\n * token: '<publishable-storefront-token>',\n * prefetch: { collectionLimit: 20, productLimitPerCollection: 24 },\n * })\n *\n * Returns the same `DataApi` shape as `createMockData` (sync read methods)\n * by pre-fetching collections + their products at boot and serving every\n * subsequent lookup from an in-memory cache. The trade-off: a single GraphQL\n * round-trip at boot, then zero network on render — exactly what the SSG\n * step + first hydration need.\n *\n * Per-handle pages (e.g. /products/<handle>) that miss the prefetch can\n * still be fetched lazily via `dataApi.refresh()` (TODO) — for now, raise\n * `prefetch.productLimitPerCollection` to cover the catalogue size.\n */\nexport interface LiveDataOptions {\n /** Base URL of the store-api (e.g. https://api-do-sgp1.tanqory.com). */\n endpoint: string\n /** Store UUID (the `:storeId` path param). */\n storeId: string\n /** Publishable storefront token — passed as `x-publishable-key`. */\n token?: string\n /**\n * ISO 3166 alpha-2 (e.g. \"TH\", \"SG\", \"US\"). When set, the backend resolves\n * the matching Market for this country, applies its currency + exchange\n * rate, and returns Money fields in that currency. Falls back to store\n * base currency if no Market matches the country.\n */\n country?: string\n /** Optional fetch override (testing / SSR). */\n fetcher?: typeof fetch\n /**\n * Page handle (from `/pages/<handle>`) to fetch alongside the homepage\n * bootstrap. The theme entry resolves the current URL once at boot and\n * passes the matching handle here so the PageBody section can read\n * `dataApi.pageByHandle(handle)` synchronously during hydration.\n */\n pageHandle?: string\n /** Tune how much to load at boot. */\n prefetch?: {\n /** Max collections to fetch (default 20). */\n collectionLimit?: number\n /** Max products to inline under each collection (default 24). */\n productLimitPerCollection?: number\n /** Max products to fetch at the top level (default 24) — these power the\n * synthesized `featured` / `all` virtual collections when the store has\n * no real collections yet. */\n topProductLimit?: number\n }\n}\n\n// Bootstrap fetches BOTH collections AND a flat product list. The flat list\n// powers a synthesized \"featured\" virtual collection when the store has live\n// products but the merchant hasn't built a real collection yet — without it,\n// a brand-new merchant's first Active product would never appear on the\n// storefront (collections-only bootstrap = empty homepage).\n// Shared product-card selection for every grid/list. Scalars + featuredImage +\n// price + compareAtPrice (sale badge) + facets (vendor/type/tags) — all cheap\n// (cost 0–1). Heavy fields (gallery, variants, metafields, sellingPlans,\n// storeAvailability) stay on the PDP query only.\nconst PRODUCT_CARD_FIELDS = /* GraphQL */ `\n fragment ProductCardBoot on Product {\n id\n handle\n title\n availableForSale\n vendor\n productType\n tags\n featuredImage { url altText }\n priceRange { minVariantPrice { amount currencyCode } }\n compareAtPriceRange { maxVariantPrice { amount currencyCode } }\n firstAvailableVariant { id }\n }\n`\n\nconst COLLECTIONS_QUERY = /* GraphQL */ `\n ${BOOTSTRAP_SHOP_MENU_FRAGMENTS}\n ${PRODUCT_CARD_FIELDS}\n query NovaBootstrap($first: Int!, $productFirst: Int!, $productsTop: Int!, $pageHandle: String) {\n ${BOOTSTRAP_SHOP_MENU}\n page(handle: $pageHandle) {\n handle\n title\n body\n bodySummary\n author\n publishedAt\n updatedAt\n }\n collections(first: $first) {\n edges {\n node {\n id\n handle\n title\n image { url altText }\n products(first: $productFirst) {\n edges {\n node { ...ProductCardBoot }\n }\n }\n }\n }\n }\n products(first: $productsTop) {\n edges {\n node { ...ProductCardBoot }\n }\n }\n localization {\n country {\n isoCode\n name\n currency { isoCode name symbol }\n market { id handle name }\n }\n availableCountries {\n isoCode\n name\n currency { isoCode name symbol }\n market { id handle name }\n }\n language { isoCode name }\n availableLanguages { isoCode name }\n }\n }\n`\n\n// Reduced bootstrap. `localization` and the nested `collections.products` are\n// non-nullable in the storefront schema, so if a cell errors on either (e.g. an\n// older / partially-broken store-api) GraphQL nulls the ENTIRE response and the\n// whole boot falls back to mock. This variant drops both optional pieces so the\n// essentials — shop, menus, page, collections, top products — still load.\nconst SAFE_COLLECTIONS_QUERY = /* GraphQL */ `\n ${BOOTSTRAP_SHOP_MENU_FRAGMENTS}\n ${PRODUCT_CARD_FIELDS}\n query NovaBootstrapSafe($first: Int!, $productsTop: Int!, $pageHandle: String) {\n ${BOOTSTRAP_SHOP_MENU}\n page(handle: $pageHandle) {\n handle\n title\n body\n bodySummary\n author\n publishedAt\n updatedAt\n }\n collections(first: $first) {\n edges {\n node {\n id\n handle\n title\n image { url altText }\n }\n }\n }\n products(first: $productsTop) {\n edges {\n node { ...ProductCardBoot }\n }\n }\n }\n`\n\ninterface GqlMoney { amount: string; currencyCode: string }\ntype GqlImg = { url?: string; altText?: string | null } | null | undefined\ninterface GqlProductNode {\n id: string\n handle: string\n title: string\n availableForSale?: boolean\n vendor?: string | null\n productType?: string | null\n tags?: string[]\n featuredImage?: GqlImg\n priceRange?: { minVariantPrice?: GqlMoney }\n compareAtPriceRange?: { maxVariantPrice?: GqlMoney } | null\n firstAvailableVariant?: { id: string } | null\n}\ninterface GqlCollectionNode {\n id: string\n handle: string\n title: string\n image?: GqlImg\n products: { edges: Array<{ node: GqlProductNode }> }\n}\ninterface GqlPageNode {\n handle: string\n title: string\n body: string\n bodySummary?: string | null\n author?: string | null\n publishedAt?: string | null\n updatedAt?: string | null\n}\ninterface BootstrapData {\n collections: { edges: Array<{ node: GqlCollectionNode }> }\n products: { edges: Array<{ node: GqlProductNode }> }\n page: GqlPageNode | null\n localization: {\n country: LocalizedCountry\n availableCountries: LocalizedCountry[]\n language?: LocalizedLanguage\n availableLanguages?: LocalizedLanguage[]\n }\n /** Shop info + the two standard menus — parsed by readBootstrapShopMenu. */\n shop?: unknown\n mainMenu?: unknown\n footerMenu?: unknown\n}\n\nfunction normalizeImage(img: GqlImg): { url: string; altText?: string } | null {\n if (!img || !img.url) return null\n return {\n url: img.url,\n ...(img.altText ? { altText: img.altText } : {}),\n }\n}\n\nfunction normalizeProduct(p: GqlProductNode): Product {\n const price = p.priceRange?.minVariantPrice ?? { amount: '0', currencyCode: 'USD' }\n // Only surface compareAtPrice when it's a REAL sale (was > now) — the backend\n // returns the range even when equal, which would render a pointless strikethrough.\n const compareAt = p.compareAtPriceRange?.maxVariantPrice\n const onSale = compareAt && Number(compareAt.amount) > Number(price.amount)\n return {\n id: p.id,\n handle: p.handle,\n title: p.title,\n price,\n featuredImage: normalizeImage(p.featuredImage),\n ...(onSale ? { compareAtPrice: compareAt } : {}),\n ...(p.vendor ? { vendor: p.vendor } : {}),\n ...(p.productType ? { productType: p.productType } : {}),\n ...(p.tags?.length ? { tags: p.tags } : {}),\n ...(p.firstAvailableVariant?.id ? { variantId: p.firstAvailableVariant.id } : {}),\n ...(typeof p.availableForSale === 'boolean' ? { availableForSale: p.availableForSale } : {}),\n }\n}\n\nfunction normalizeCollection(c: GqlCollectionNode): Collection {\n return {\n handle: c.handle,\n title: c.title,\n image: normalizeImage(c.image),\n // Nested products are optional — the reduced bootstrap (used when a cell\n // errors on the nested products field) omits them.\n products: (c.products?.edges ?? []).map((e) => normalizeProduct(e.node)),\n }\n}\n\n// Single-product fetch (PDP) — full options + variants for the variant picker.\n// Kept out of the bootstrap (variants(first:100) @cost=100/product would blow\n// the cost budget) and fetched lazily only on the product page.\nconst PRODUCT_QUERY = /* GraphQL */ `\n query NovaProduct($handle: String!, $identifiers: [MetafieldIdentifier!]!) {\n product(handle: $handle) {\n id\n handle\n title\n description\n vendor\n productType\n tags\n availableForSale\n featuredImage { url altText }\n images(first: 20) { nodes { url altText } }\n priceRange { minVariantPrice { amount currencyCode } }\n compareAtPriceRange { maxVariantPrice { amount currencyCode } }\n options(first: 10) { name values }\n seo { title description }\n variants(first: 50) {\n nodes {\n id\n title\n availableForSale\n sku\n price { amount currencyCode }\n compareAtPrice { amount currencyCode }\n image { url altText }\n selectedOptions { name value }\n unitPrice { amount currencyCode }\n unitPriceMeasurement { measuredType quantityValue quantityUnit referenceValue referenceUnit }\n quantityRule { minimum maximum increment }\n storeAvailability(first: 5) {\n nodes { available quantityAvailable pickUpTime location { id name } }\n }\n }\n }\n sellingPlanGroups(first: 5) {\n nodes {\n name\n appName\n options { name values }\n sellingPlans(first: 10) {\n nodes { id name description recurringDeliveries options { name value } }\n }\n }\n }\n metafields(identifiers: $identifiers) { namespace key value }\n firstAvailableVariant { id }\n }\n }\n`\n\ninterface GqlVariantNode {\n id: string\n title: string\n availableForSale: boolean\n sku?: string | null\n price?: GqlMoney\n compareAtPrice?: GqlMoney | null\n image?: GqlImg\n selectedOptions?: Array<{ name: string; value: string }>\n unitPrice?: GqlMoney | null\n unitPriceMeasurement?: UnitPriceMeasurement | null\n quantityRule?: QuantityRule\n storeAvailability?: {\n nodes: Array<{\n available: boolean\n quantityAvailable: number\n pickUpTime?: string | null\n location: { id: string; name: string }\n }>\n }\n}\ninterface GqlSellingPlanGroupNode {\n name: string\n appName?: string | null\n options?: Array<{ name: string; values: string[] }>\n sellingPlans?: { nodes: Array<{\n id: string\n name: string\n description?: string | null\n recurringDeliveries: boolean\n options?: Array<{ name: string; value: string }>\n }> }\n}\ninterface GqlProductDetailNode extends GqlProductNode {\n description?: string | null\n images?: { nodes: GqlImg[] }\n options?: Array<{ name: string; values: string[] }>\n seo?: { title?: string | null; description?: string | null } | null\n variants?: { nodes: GqlVariantNode[] }\n sellingPlanGroups?: { nodes: GqlSellingPlanGroupNode[] }\n metafields?: Array<{ namespace: string; key: string; value: string | null } | null>\n}\n\nfunction normalizeProductDetail(p: GqlProductDetailNode): Product {\n const base = normalizeProduct(p)\n const variants: ProductVariant[] = (p.variants?.nodes ?? []).map((v) => ({\n id: v.id,\n title: v.title,\n price: v.price ?? base.price,\n ...(v.compareAtPrice && Number(v.compareAtPrice.amount) > Number((v.price ?? base.price).amount)\n ? { compareAtPrice: v.compareAtPrice }\n : {}),\n availableForSale: v.availableForSale,\n ...(v.sku ? { sku: v.sku } : {}),\n ...(v.selectedOptions?.length ? { selectedOptions: v.selectedOptions } : {}),\n image: normalizeImage(v.image),\n ...(v.unitPrice ? { unitPrice: v.unitPrice } : {}),\n ...(v.unitPriceMeasurement ? { unitPriceMeasurement: v.unitPriceMeasurement } : {}),\n ...(v.quantityRule ? { quantityRule: v.quantityRule } : {}),\n ...(v.storeAvailability?.nodes?.length\n ? {\n storeAvailability: v.storeAvailability.nodes.map((s) => ({\n available: s.available,\n quantityAvailable: s.quantityAvailable,\n pickUpTime: s.pickUpTime ?? null,\n location: s.location,\n })),\n }\n : {}),\n }))\n const images: ImageRef[] = (p.images?.nodes ?? [])\n .map(normalizeImage)\n .filter((i): i is ImageRef => i !== null)\n const sellingPlanGroups: SellingPlanGroup[] = (p.sellingPlanGroups?.nodes ?? []).map((g) => ({\n name: g.name,\n appName: g.appName ?? null,\n options: g.options ?? [],\n sellingPlans: (g.sellingPlans?.nodes ?? []).map((sp) => ({\n id: sp.id,\n name: sp.name,\n description: sp.description ?? null,\n recurringDeliveries: sp.recurringDeliveries,\n options: sp.options ?? [],\n })),\n }))\n const metafields: Record<string, string | null> = {}\n for (const m of p.metafields ?? []) {\n if (m) metafields[`${m.namespace}.${m.key}`] = m.value\n }\n return {\n ...base,\n ...(p.description ? { description: p.description } : {}),\n ...(images.length ? { images } : {}),\n ...(p.options?.length ? { options: p.options } : {}),\n ...(p.seo ? { seo: { title: p.seo.title ?? null, description: p.seo.description ?? null } } : {}),\n ...(variants.length ? { variants } : {}),\n ...(sellingPlanGroups.length ? { sellingPlanGroups } : {}),\n ...(Object.keys(metafields).length ? { metafields } : {}),\n }\n}\n\ntype GraphqlRequester = <T = unknown>(\n query: string,\n variables?: Record<string, unknown>,\n) => Promise<T>\n\n/**\n * One request path for the bootstrap AND every post-boot interaction (the\n * cart's mutations, the PDP's lazy product fetch) — same endpoint, same\n * publishable-key + country headers, same error handling.\n */\nfunction makeGraphqlRequest(opts: LiveDataOptions): GraphqlRequester {\n const maybeFetch = opts.fetcher ?? (globalThis.fetch as typeof fetch | undefined)\n if (!maybeFetch) {\n throw new Error('[theme-kit] createLiveData: fetch is not available in this environment')\n }\n // Capture into a definitely-defined const so the narrowing survives into the\n // graphqlRequest closure below (TS drops `!undefined` narrowing across scopes).\n const f: typeof fetch = maybeFetch\n const endpoint = opts.endpoint.replace(/\\/$/, '')\n const url = `${endpoint}/api/v1/stores/${encodeURIComponent(opts.storeId)}/graphql`\n return async function graphqlRequest<T = unknown>(\n query: string,\n variables?: Record<string, unknown>,\n ): Promise<T> {\n const res = await f(url, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n ...(opts.token ? { 'x-publishable-key': opts.token } : {}),\n // X-Tanqory-Country triggers backend Market resolution; if the store\n // has an active Market with this country, Money.currencyCode + amount\n // come back already-converted in the target currency.\n ...(opts.country ? { 'x-tanqory-country': opts.country.toUpperCase() } : {}),\n },\n body: JSON.stringify({ query, variables }),\n })\n if (!res.ok) {\n throw new Error(\n `[theme-kit] GraphQL HTTP ${res.status} from ${url} — ${await res.text().catch(() => '')}`,\n )\n }\n const json = (await res.json()) as { data?: T; errors?: Array<{ message: string }> }\n if (json.errors?.length) {\n const msg = json.errors.map((e) => e.message).join('; ')\n // Partial success: GraphQL nulls the failed field(s) but still returns the\n // rest of `data`. Only fail hard when NOTHING came back — otherwise log and\n // use what we got, so one flaky field (e.g. `localization` on an older\n // cell) can't blank the entire storefront / fall the whole boot to mock.\n if (json.data == null) {\n throw new Error(`[theme-kit] GraphQL errors: ${msg}`)\n }\n if (typeof console !== 'undefined') {\n // eslint-disable-next-line no-console\n console.warn(`[theme-kit] GraphQL partial errors (using partial data): ${msg}`)\n }\n }\n return json.data as T\n }\n}\n\nexport async function createLiveData(opts: LiveDataOptions): Promise<DataApi> {\n const graphqlRequest = makeGraphqlRequest(opts)\n // Defaults stay under store-api's GraphQL cost budget (1000). Cost formula\n // for the bootstrap query: 3*N + 4*N*M + 4*T (N = collectionLimit,\n // M = productLimitPerCollection, T = topProductLimit). 10 + 10 + 24 = 526\n // — plenty of headroom for a homepage prefetch. Bump in opts.prefetch only\n // if you're sure the store's cost-budget limit is higher than 1000.\n const collectionLimit = opts.prefetch?.collectionLimit ?? 10\n const productLimitPerCollection = opts.prefetch?.productLimitPerCollection ?? 10\n const topProductLimit = opts.prefetch?.topProductLimit ?? 24\n\n let boot: BootstrapData | undefined\n try {\n boot = await graphqlRequest<BootstrapData>(COLLECTIONS_QUERY, {\n first: collectionLimit,\n productFirst: productLimitPerCollection,\n productsTop: topProductLimit,\n pageHandle: opts.pageHandle ?? null,\n })\n } catch (err) {\n // The full query nulls out entirely if the cell errors on an optional field\n // (localization, nested collection products). Retry once with the reduced\n // query so the storefront still renders real shop/menus/collections/products\n // instead of falling all the way back to mock.\n if (typeof console !== 'undefined') {\n // eslint-disable-next-line no-console\n console.warn(\n `[theme-kit] full bootstrap failed, retrying without optional fields: ${(err as Error).message}`,\n )\n }\n boot = await graphqlRequest<BootstrapData>(SAFE_COLLECTIONS_QUERY, {\n first: collectionLimit,\n productsTop: topProductLimit,\n pageHandle: opts.pageHandle ?? null,\n })\n }\n return buildLiveData(boot, graphqlRequest, opts)\n}\n\n/**\n * Build a live DataApi SYNCHRONOUSLY from a previously-fetched bootstrap\n * payload (`data.getSnapshot()`, serialized into the SSG HTML as\n * `window.__TQ_STATE__` by the prerender step). This is what makes hydration\n * deterministic: the client's first render uses the EXACT data the server\n * rendered with — no network round-trip, no drift, no mock fallback — and\n * mount()'s `revalidate` swaps in fresh data after hydration (SWR).\n */\nexport function createLiveDataFromSnapshot(snapshot: unknown, opts: LiveDataOptions): DataApi {\n const graphqlRequest = makeGraphqlRequest(opts)\n return buildLiveData((snapshot ?? undefined) as BootstrapData | undefined, graphqlRequest, opts)\n}\n\n/** Assemble the DataApi from a bootstrap payload + a live requester. Shared by\n * createLiveData (fetches the bootstrap) and createLiveDataFromSnapshot\n * (reuses the serialized one) so both paths render identically. */\nfunction buildLiveData(\n boot: BootstrapData | undefined,\n graphqlRequest: GraphqlRequester,\n opts: LiveDataOptions,\n): DataApi {\n const productLimitPerCollection = opts.prefetch?.productLimitPerCollection ?? 10\n const collections: Collection[] = (boot?.collections.edges ?? []).map((e) =>\n normalizeCollection(e.node),\n )\n const topProducts: Product[] = (boot?.products.edges ?? []).map((e) =>\n normalizeProduct(e.node),\n )\n\n // Themes commonly reference `featured` / `frontpage` / `all` as their homepage\n // collection. Synthesize one when the merchant hasn't created a real\n // collection yet but DOES have Active products — otherwise their first\n // product would never appear on the storefront. Also ensure `allProducts`\n // is wired even when no products exist outside of collections.\n if (topProducts.length > 0 && !collections.some((c) => c.handle === 'featured')) {\n collections.unshift({\n handle: 'featured',\n title: 'Featured',\n image: topProducts[0].featuredImage ?? null,\n products: topProducts.slice(0, productLimitPerCollection),\n })\n }\n // Mirror as `all` too — many themes (incl. our nova templates) reference it.\n if (topProducts.length > 0 && !collections.some((c) => c.handle === 'all')) {\n collections.push({\n handle: 'all',\n title: 'All products',\n image: topProducts[0].featuredImage ?? null,\n products: topProducts,\n })\n }\n\n // Reuse the createMockData factory — same cache shape, same DataApi.\n // It also indexes products by handle so productByHandle() works even for\n // products fetched only via the top-level products() query.\n const data = createMockData(collections)\n const pageNode = boot?.page\n if (pageNode) {\n // Cache only the page that matched the URL. pageByHandle returns null\n // for everything else — themes should only call it for the current page.\n const page: Page = {\n handle: pageNode.handle,\n title: pageNode.title,\n body: pageNode.body,\n ...(pageNode.bodySummary ? { bodySummary: pageNode.bodySummary } : {}),\n ...(pageNode.author ? { author: pageNode.author } : {}),\n ...(pageNode.publishedAt ? { publishedAt: pageNode.publishedAt } : {}),\n ...(pageNode.updatedAt ? { updatedAt: pageNode.updatedAt } : {}),\n }\n data.pageByHandle = (handle) => (handle === page.handle ? page : null)\n }\n const loc = boot?.localization\n if (loc) {\n // Only expose the localization payload when the store actually has Markets\n // (availableCountries non-empty). With zero markets, leave `null` so the\n // theme's country picker hides itself instead of showing a hardcoded list\n // that doesn't match what the merchant has configured.\n data.localization =\n loc.availableCountries.length > 0\n ? {\n country: loc.country,\n availableCountries: loc.availableCountries,\n // Published languages come straight from the store (StoreLanguage →\n // SDL `availableLanguages`); the theme just renders the picker.\n language: loc.language,\n availableLanguages: loc.availableLanguages,\n }\n : null\n }\n\n // Post-boot capabilities: the raw GraphQL escape hatch (cart mutations live\n // on top of this) and an on-demand single-product fetch (PDP variant picker).\n data.graphql = graphqlRequest\n data.fetchProduct = async (\n handle: string,\n fpOpts?: { metafields?: Array<{ namespace: string; key: string }> },\n ): Promise<Product | null> => {\n // Never reject: a failed detail fetch (cost budget, cold cell, network)\n // must degrade to the prefetched card data, not crash the product page\n // with an unhandled rejection mid-hydration.\n try {\n const res = await graphqlRequest<{ product: GqlProductDetailNode | null }>(PRODUCT_QUERY, {\n handle,\n identifiers: fpOpts?.metafields ?? [],\n })\n return res?.product ? normalizeProductDetail(res.product) : null\n } catch (err) {\n if (typeof console !== 'undefined') {\n // eslint-disable-next-line no-console\n console.warn(`[theme-kit] fetchProduct(${handle}) failed: ${(err as Error).message}`)\n }\n return null\n }\n }\n\n // Dynamic-source metafields for the shop + a collection. Both query the\n // storefront's `metafields(identifiers)` (Shop/Collection both expose it) and\n // flatten to a \"namespace.key\" → value map the resolver reads.\n type GqlMf = { namespace: string; key: string; value: string | null } | null\n const toMfMap = (arr: GqlMf[] | undefined): Record<string, string | null> => {\n const out: Record<string, string | null> = {}\n for (const m of arr ?? []) if (m) out[`${m.namespace}.${m.key}`] = m.value\n return out\n }\n data.fetchShopMetafields = async (identifiers) => {\n if (!identifiers.length) return {}\n const res = await graphqlRequest<{ shop: { metafields: GqlMf[] } | null }>(\n `query NovaShopMetafields($identifiers: [MetafieldIdentifier!]!) {\n shop { metafields(identifiers: $identifiers) { namespace key value } }\n }`,\n { identifiers },\n )\n return toMfMap(res?.shop?.metafields)\n }\n data.fetchCollectionMetafields = async (handle, identifiers) => {\n if (!identifiers.length || !handle) return {}\n const res = await graphqlRequest<{ collection: { metafields: GqlMf[] } | null }>(\n `query NovaCollectionMetafields($handle: String!, $identifiers: [MetafieldIdentifier!]!) {\n collection(handle: $handle) { metafields(identifiers: $identifiers) { namespace key value } }\n }`,\n { handle, identifiers },\n )\n return toMfMap(res?.collection?.metafields)\n }\n\n // ─── Shopify-compatible storefront extensions ───────────────────\n // Shop info + the two standard menus came back in the bootstrap → expose\n // them synchronously (the layout's header/footer render at hydration).\n const { shop, menus } = readBootstrapShopMenu(boot)\n data.shop = shop\n data.menu = (handle: string) => menus.get(handle) ?? null\n // The rest (search, blog, recommendations, metaobjects, customer account)\n // are lazy — attach them on the same requester. fetchMenu shares `menus` so\n // a later fetch warms the same cache the sync menu() reads.\n Object.assign(\n data,\n createStorefrontMethods(graphqlRequest, { normalizeProduct }, menus),\n )\n // List every store menu (Dashboard → Navigation) for the editor's link_list\n // picker — the storefront `menus` query (id/handle/title/itemsCount).\n data.listMenus = async () => {\n const res = await graphqlRequest<{\n menus: Array<{ handle: string; title: string; itemsCount: number }>\n }>(`query NovaMenus { menus { handle title itemsCount } }`)\n return res?.menus ?? []\n }\n data.pixels = async () => {\n const res = await graphqlRequest<{\n customPixels: Array<{\n id: string\n name: string\n provider: string | null\n providerPixelId: string | null\n code: string | null\n }>\n }>(`query NovaPixels { customPixels { id name provider providerPixelId code } }`)\n return res?.customPixels ?? []\n }\n data.locations = async () => {\n const res = await graphqlRequest<{\n locations: Array<{\n id: string\n name: string\n code: string | null\n address: {\n country: string | null\n address: string | null\n city: string | null\n province: string | null\n postalCode: string | null\n phone: string | null\n } | null\n }>\n }>(\n `query NovaLocations { locations { id name code address { country address city province postalCode phone } } }`,\n )\n return res?.locations ?? []\n }\n // The raw serializable bootstrap this DataApi was built from. entry-server\n // embeds it into the SSG HTML (window.__TQ_STATE__) so the client can\n // rebuild the SAME DataApi synchronously at hydration — see\n // createLiveDataFromSnapshot. null when there was no live bootstrap.\n data.getSnapshot = () => boot ?? null\n return data\n}\n\n// ─── Deterministic money formatting ─────────────────────────────────────────\n// Intl.NumberFormat's currency output depends on the environment's ICU data\n// (the build pod's Node vs each visitor's browser can format the SAME Money\n// differently, e.g. \"THB 120.00\" vs \"฿120.00\") — which breaks SSR hydration\n// (React #425 text mismatch). Format manually instead: identical output\n// everywhere, by construction.\nconst CURRENCY_FORMAT: Record<string, { symbol: string; decimals: number }> = {\n THB: { symbol: '฿', decimals: 2 },\n USD: { symbol: '$', decimals: 2 },\n EUR: { symbol: '€', decimals: 2 },\n GBP: { symbol: '£', decimals: 2 },\n JPY: { symbol: '¥', decimals: 0 },\n KRW: { symbol: '₩', decimals: 0 },\n VND: { symbol: '₫', decimals: 0 },\n IDR: { symbol: 'Rp', decimals: 0 },\n SGD: { symbol: 'S$', decimals: 2 },\n HKD: { symbol: 'HK$', decimals: 2 },\n TWD: { symbol: 'NT$', decimals: 2 },\n AUD: { symbol: 'A$', decimals: 2 },\n NZD: { symbol: 'NZ$', decimals: 2 },\n CAD: { symbol: 'CA$', decimals: 2 },\n CNY: { symbol: 'CN¥', decimals: 2 },\n INR: { symbol: '₹', decimals: 2 },\n MYR: { symbol: 'RM', decimals: 2 },\n PHP: { symbol: '₱', decimals: 2 },\n}\n\nexport function formatMoney(money: Money): string {\n const n = Number(money.amount)\n if (!Number.isFinite(n)) return `${money.amount} ${money.currencyCode}`\n const info = CURRENCY_FORMAT[money.currencyCode]\n const decimals = info?.decimals ?? 2\n const [int, frac] = Math.abs(n).toFixed(decimals).split('.')\n const grouped = int.replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',')\n const num = `${n < 0 ? '-' : ''}${grouped}${frac ? `.${frac}` : ''}`\n return info ? `${info.symbol}${num}` : `${num} ${money.currencyCode}`\n}\n","import {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useRef,\n useState,\n type ReactNode,\n} from 'react'\nimport { useData, type Money } from './data'\n\n/**\n * Client-side shopping cart for storefront themes.\n *\n * Backed by the Tanqory Storefront GraphQL cart API (Shopify-compatible:\n * `cartCreate` / `cartLinesAdd` / `cartLinesUpdate` / `cartLinesRemove`,\n * merchandise = Variant). The cart id is persisted in localStorage so the\n * cart survives reloads; line data is always sourced from the backend (the\n * single source of truth) and reconciled after every mutation.\n *\n * Two drivers, picked automatically:\n * - LIVE — when `useData().graphql` exists (createLiveData). Real mutations.\n * - MOCK — when it doesn't (createMockData: editor preview / offline dev).\n * An in-memory cart so +/- / remove still demonstrate correctly.\n *\n * SSR/SSG-safe: the provider renders an empty cart on the server AND on the\n * first client render (`ready === false`), then hydrates from localStorage +\n * backend in a post-mount effect — so there's never a hydration mismatch.\n */\n\nconst STORAGE_KEY = 'tq-cart-id'\nconst DEFAULT_CURRENCY = 'USD'\n// Shopify-ism: single-variant products name their lone variant \"Default Title\".\n// Hide it so single-variant lines don't show a meaningless variant subtitle.\nconst DEFAULT_VARIANT_TITLE = 'Default Title'\n\nexport interface CartLine {\n /** Cart line id — the handle used for update/remove. */\n id: string\n /** The purchasable variant (merchandise) id. */\n variantId: string\n quantity: number\n /** Product title shown in the cart. */\n title: string\n /** Variant title (e.g. \"Black / M\"); empty for single-variant products. */\n variantTitle?: string\n image?: { url: string; altText?: string } | null\n /** Per-unit price. */\n price: Money\n /** Line subtotal (price × quantity). */\n lineSubtotal: Money\n /** Product handle for linking back to the PDP. */\n productHandle?: string\n}\n\n/** A discount code applied to the cart (`applicable=false` when it didn't qualify). */\nexport interface AppliedDiscountCode {\n code: string\n applicable: boolean\n}\n/** A gift card applied to the cart — masked (only last 4 chars ever leave the API). */\nexport interface AppliedGiftCard {\n id: string\n lastCharacters: string\n amountUsed: Money\n balance: Money\n}\n\nexport interface CartState {\n id: string | null\n lines: CartLine[]\n subtotal: Money\n /** Final amount after discounts + gift cards (cost.totalAmount). */\n total: Money\n totalQuantity: number\n checkoutUrl: string | null\n /** Discount codes applied to the cart. */\n discountCodes: AppliedDiscountCode[]\n /** Total savings across all discount allocations — null when nothing's discounted. */\n discountAmount: Money | null\n /** Gift cards applied to the cart. */\n appliedGiftCards: AppliedGiftCard[]\n /** True while a mutation/bootstrap is in flight. */\n loading: boolean\n /** True once the client has hydrated cart state post-mount. */\n ready: boolean\n error: string | null\n}\n\nexport interface AddToCartInput {\n variantId: string\n quantity?: number\n /** Display data — used only by the in-memory MOCK driver (editor/offline). */\n product?: {\n title: string\n price: Money\n image?: { url: string; altText?: string } | null\n handle?: string\n variantTitle?: string\n }\n}\n\nexport interface CartApi extends CartState {\n add: (input: AddToCartInput) => Promise<void>\n updateQuantity: (lineId: string, quantity: number) => Promise<void>\n remove: (lineId: string) => Promise<void>\n clear: () => Promise<void>\n /** Apply discount codes (replaces the current set; [] clears them). LIVE only. */\n applyDiscountCodes: (codes: string[]) => Promise<void>\n /** Apply gift card codes to the cart. LIVE only. */\n applyGiftCardCodes: (codes: string[]) => Promise<void>\n /** Remove applied gift cards by id. LIVE only. */\n removeGiftCards: (ids: string[]) => Promise<void>\n}\n\n// ─── Money helpers (amounts are decimal strings) ──────────────────\n\nfunction money(amount: number, currencyCode: string): Money {\n return { amount: amount.toFixed(2), currencyCode }\n}\nfunction multiply(price: Money, qty: number): Money {\n return money(Number(price.amount) * qty, price.currencyCode)\n}\nfunction sumLines(lines: CartLine[]): Money {\n const currencyCode = lines[0]?.lineSubtotal.currencyCode ?? DEFAULT_CURRENCY\n const total = lines.reduce((acc, l) => acc + Number(l.lineSubtotal.amount), 0)\n return money(total, currencyCode)\n}\nfunction countQty(lines: CartLine[]): number {\n return lines.reduce((acc, l) => acc + l.quantity, 0)\n}\n\n// ─── GraphQL (LIVE driver) ────────────────────────────────────────\n\nconst CART_FRAGMENT = /* GraphQL */ `\n fragment CartFields on Cart {\n id\n checkoutUrl\n totalQuantity\n cost {\n subtotalAmount { amount currencyCode }\n totalAmount { amount currencyCode }\n }\n discountCodes { code applicable }\n discountAllocations {\n ... on CartCodeDiscountAllocation { code discountedAmount { amount currencyCode } }\n ... on CartAutomaticDiscountAllocation { title discountedAmount { amount currencyCode } }\n ... on CartCustomDiscountAllocation { title discountedAmount { amount currencyCode } }\n }\n appliedGiftCards {\n id\n lastCharacters\n amountUsed { amount currencyCode }\n balance { amount currencyCode }\n }\n lines(first: 100) {\n nodes {\n id\n quantity\n cost {\n subtotalAmount { amount currencyCode }\n amountPerQuantity { amount currencyCode }\n }\n merchandise {\n ... on Variant {\n id\n title\n image { url altText }\n price { amount currencyCode }\n product { handle title featuredImage { url altText } }\n }\n }\n }\n }\n }\n`\nconst CART_QUERY = /* GraphQL */ `\n query Cart($id: ID!) { cart(id: $id) { ...CartFields } }\n ${CART_FRAGMENT}\n`\nconst CART_CREATE = /* GraphQL */ `\n mutation CartCreate($lines: [CartLineInput!]!) {\n cartCreate(input: { lines: $lines }) { cart { ...CartFields } userErrors { message } }\n }\n ${CART_FRAGMENT}\n`\nconst CART_LINES_ADD = /* GraphQL */ `\n mutation CartLinesAdd($cartId: ID!, $lines: [CartLineInput!]!) {\n cartLinesAdd(cartId: $cartId, lines: $lines) { cart { ...CartFields } userErrors { message } }\n }\n ${CART_FRAGMENT}\n`\nconst CART_LINES_UPDATE = /* GraphQL */ `\n mutation CartLinesUpdate($cartId: ID!, $lines: [CartLineUpdateInput!]!) {\n cartLinesUpdate(cartId: $cartId, lines: $lines) { cart { ...CartFields } userErrors { message } }\n }\n ${CART_FRAGMENT}\n`\nconst CART_LINES_REMOVE = /* GraphQL */ `\n mutation CartLinesRemove($cartId: ID!, $lineIds: [ID!]!) {\n cartLinesRemove(cartId: $cartId, lineIds: $lineIds) { cart { ...CartFields } userErrors { message } }\n }\n ${CART_FRAGMENT}\n`\nconst CART_DISCOUNT_CODES = /* GraphQL */ `\n mutation CartDiscountCodesUpdate($cartId: ID!, $discountCodes: [String!]) {\n cartDiscountCodesUpdate(cartId: $cartId, discountCodes: $discountCodes) {\n cart { ...CartFields } userErrors { message }\n }\n }\n ${CART_FRAGMENT}\n`\nconst CART_GIFTCARD_UPDATE = /* GraphQL */ `\n mutation CartGiftCardCodesUpdate($cartId: ID!, $giftCardCodes: [String!]!) {\n cartGiftCardCodesUpdate(cartId: $cartId, giftCardCodes: $giftCardCodes) {\n cart { ...CartFields } userErrors { message }\n }\n }\n ${CART_FRAGMENT}\n`\nconst CART_GIFTCARD_REMOVE = /* GraphQL */ `\n mutation CartGiftCardCodesRemove($cartId: ID!, $appliedGiftCardIds: [ID!]!) {\n cartGiftCardCodesRemove(cartId: $cartId, appliedGiftCardIds: $appliedGiftCardIds) {\n cart { ...CartFields } userErrors { message }\n }\n }\n ${CART_FRAGMENT}\n`\n\ninterface GqlCart {\n id: string\n checkoutUrl: string\n totalQuantity: number\n cost: { subtotalAmount: Money; totalAmount: Money }\n discountCodes?: Array<{ code: string; applicable: boolean }>\n discountAllocations?: Array<{ discountedAmount: Money; code?: string; title?: string }>\n appliedGiftCards?: Array<{\n id: string\n lastCharacters: string\n amountUsed: Money\n balance: Money\n }>\n lines: {\n nodes: Array<{\n id: string\n quantity: number\n cost: { subtotalAmount: Money; amountPerQuantity: Money }\n merchandise: {\n id: string\n title?: string\n image?: { url: string; altText?: string | null } | null\n price: Money\n product?: {\n handle: string\n title: string\n featuredImage?: { url: string; altText?: string | null } | null\n } | null\n }\n }>\n }\n}\ninterface CartMutationPayload {\n cart: GqlCart | null\n userErrors: Array<{ message: string }>\n}\n\nfunction normalizeImage(\n img: { url: string; altText?: string | null } | null | undefined,\n): { url: string; altText?: string } | null {\n if (!img || !img.url) return null\n return { url: img.url, ...(img.altText ? { altText: img.altText } : {}) }\n}\n\n/** GqlCart → the cart fields we keep in state (loading/ready/error added by caller). */\nfunction normalizeCart(c: GqlCart): Omit<CartState, 'loading' | 'ready' | 'error'> {\n const lines: CartLine[] = c.lines.nodes.map((n) => {\n const m = n.merchandise\n const variantTitle =\n m.title && m.title !== DEFAULT_VARIANT_TITLE ? m.title : undefined\n return {\n id: n.id,\n variantId: m.id,\n quantity: n.quantity,\n title: m.product?.title ?? m.title ?? 'Item',\n ...(variantTitle ? { variantTitle } : {}),\n image: normalizeImage(m.image) ?? normalizeImage(m.product?.featuredImage),\n price: n.cost.amountPerQuantity ?? m.price,\n lineSubtotal: n.cost.subtotalAmount ?? multiply(m.price, n.quantity),\n ...(m.product?.handle ? { productHandle: m.product.handle } : {}),\n }\n })\n const subtotal = c.cost?.subtotalAmount ?? sumLines(lines)\n // Sum every discount allocation (code + automatic) into one \"you saved\" figure.\n const allocations = c.discountAllocations ?? []\n const discountAmount =\n allocations.length > 0\n ? money(\n allocations.reduce((acc, a) => acc + Number(a.discountedAmount.amount), 0),\n allocations[0].discountedAmount.currencyCode,\n )\n : null\n return {\n id: c.id,\n lines,\n subtotal,\n total: c.cost?.totalAmount ?? subtotal,\n totalQuantity: c.totalQuantity ?? countQty(lines),\n checkoutUrl: c.checkoutUrl ?? null,\n discountCodes: (c.discountCodes ?? []).map((d) => ({ code: d.code, applicable: d.applicable })),\n discountAmount,\n appliedGiftCards: (c.appliedGiftCards ?? []).map((g) => ({\n id: g.id,\n lastCharacters: g.lastCharacters,\n amountUsed: g.amountUsed,\n balance: g.balance,\n })),\n }\n}\n\n// ─── Context ──────────────────────────────────────────────────────\n\nconst EMPTY: CartState = {\n id: null,\n lines: [],\n subtotal: { amount: '0.00', currencyCode: DEFAULT_CURRENCY },\n total: { amount: '0.00', currencyCode: DEFAULT_CURRENCY },\n totalQuantity: 0,\n checkoutUrl: null,\n discountCodes: [],\n discountAmount: null,\n appliedGiftCards: [],\n loading: false,\n ready: false,\n error: null,\n}\n\nconst CartContext = createContext<CartApi | null>(null)\n\nfunction readStoredCartId(): string | null {\n if (typeof window === 'undefined') return null\n try {\n return window.localStorage.getItem(STORAGE_KEY)\n } catch {\n return null\n }\n}\nfunction writeStoredCartId(id: string | null): void {\n if (typeof window === 'undefined') return\n try {\n if (id) window.localStorage.setItem(STORAGE_KEY, id)\n else window.localStorage.removeItem(STORAGE_KEY)\n } catch {\n /* private mode etc. */\n }\n}\n\nexport function CartProvider({ children }: { children: ReactNode }): JSX.Element {\n const data = useData()\n const gql = data.graphql\n const isLive = typeof gql === 'function'\n\n const [state, setState] = useState<CartState>(EMPTY)\n // Mirror state in a ref so async callbacks read the current cart id / lines\n // without re-creating the callbacks on every change.\n const ref = useRef(state)\n ref.current = state\n\n const applyCart = useCallback((c: GqlCart) => {\n const next = normalizeCart(c)\n writeStoredCartId(next.id)\n setState((s) => ({ ...s, ...next, loading: false, error: null }))\n }, [])\n\n const setLocal = useCallback((lines: CartLine[]) => {\n setState((s) => ({\n ...s,\n lines,\n subtotal: sumLines(lines),\n total: sumLines(lines),\n totalQuantity: countQty(lines),\n loading: false,\n error: null,\n }))\n }, [])\n\n // Hydrate after mount (client-only): restore the saved cart from the backend.\n useEffect(() => {\n let cancelled = false\n async function hydrate(): Promise<void> {\n const id = readStoredCartId()\n if (isLive && gql && id) {\n try {\n const res = await gql<{ cart: GqlCart | null }>(CART_QUERY, { id })\n if (cancelled) return\n if (res.cart) {\n const next = normalizeCart(res.cart)\n setState((s) => ({ ...s, ...next, ready: true }))\n return\n }\n // Cart expired / not found — drop the stale id.\n writeStoredCartId(null)\n } catch {\n // Leave the cart empty but mark ready so the UI stops loading.\n }\n }\n if (!cancelled) setState((s) => ({ ...s, ready: true }))\n }\n void hydrate()\n return () => {\n cancelled = true\n }\n }, [isLive, gql])\n\n const add = useCallback<CartApi['add']>(\n async (input) => {\n const quantity = input.quantity ?? 1\n if (quantity < 1) return\n if (isLive && gql) {\n setState((s) => ({ ...s, loading: true }))\n try {\n const lines = [{ merchandiseId: input.variantId, quantity }]\n if (!ref.current.id) {\n const res = await gql<{ cartCreate: CartMutationPayload }>(CART_CREATE, { lines })\n const payload = res.cartCreate\n if (payload.cart) applyCart(payload.cart)\n else throw new Error(payload.userErrors[0]?.message ?? 'Could not create cart')\n } else {\n const res = await gql<{ cartLinesAdd: CartMutationPayload }>(CART_LINES_ADD, {\n cartId: ref.current.id,\n lines,\n })\n const payload = res.cartLinesAdd\n if (payload.cart) applyCart(payload.cart)\n else throw new Error(payload.userErrors[0]?.message ?? 'Could not add to cart')\n }\n } catch (e) {\n setState((s) => ({ ...s, loading: false, error: (e as Error).message }))\n }\n return\n }\n // MOCK driver — merge by variant id using the supplied display data.\n const p = input.product\n if (!p) return\n const existing = ref.current.lines.find((l) => l.variantId === input.variantId)\n let lines: CartLine[]\n if (existing) {\n lines = ref.current.lines.map((l) =>\n l.variantId === input.variantId\n ? { ...l, quantity: l.quantity + quantity, lineSubtotal: multiply(l.price, l.quantity + quantity) }\n : l,\n )\n } else {\n lines = [\n ...ref.current.lines,\n {\n id: `mock-${input.variantId}`,\n variantId: input.variantId,\n quantity,\n title: p.title,\n ...(p.variantTitle ? { variantTitle: p.variantTitle } : {}),\n image: p.image ?? null,\n price: p.price,\n lineSubtotal: multiply(p.price, quantity),\n ...(p.handle ? { productHandle: p.handle } : {}),\n },\n ]\n }\n setLocal(lines)\n },\n [isLive, gql, applyCart, setLocal],\n )\n\n const remove = useCallback<CartApi['remove']>(\n async (lineId) => {\n const optimistic = ref.current.lines.filter((l) => l.id !== lineId)\n setLocal(optimistic)\n if (isLive && gql && ref.current.id) {\n try {\n const res = await gql<{ cartLinesRemove: CartMutationPayload }>(CART_LINES_REMOVE, {\n cartId: ref.current.id,\n lineIds: [lineId],\n })\n if (res.cartLinesRemove.cart) applyCart(res.cartLinesRemove.cart)\n } catch (e) {\n setState((s) => ({ ...s, error: (e as Error).message }))\n }\n }\n },\n [isLive, gql, applyCart, setLocal],\n )\n\n const updateQuantity = useCallback<CartApi['updateQuantity']>(\n async (lineId, quantity) => {\n if (quantity <= 0) {\n await remove(lineId)\n return\n }\n // Optimistic local update for a snappy stepper, reconciled below (live).\n const optimistic = ref.current.lines.map((l) =>\n l.id === lineId ? { ...l, quantity, lineSubtotal: multiply(l.price, quantity) } : l,\n )\n setLocal(optimistic)\n if (isLive && gql && ref.current.id) {\n try {\n const res = await gql<{ cartLinesUpdate: CartMutationPayload }>(CART_LINES_UPDATE, {\n cartId: ref.current.id,\n lines: [{ id: lineId, quantity }],\n })\n if (res.cartLinesUpdate.cart) applyCart(res.cartLinesUpdate.cart)\n } catch (e) {\n setState((s) => ({ ...s, error: (e as Error).message }))\n }\n }\n },\n [isLive, gql, applyCart, setLocal, remove],\n )\n\n const clear = useCallback<CartApi['clear']>(async () => {\n const ids = ref.current.lines.map((l) => l.id)\n setLocal([])\n if (isLive && gql && ref.current.id && ids.length > 0) {\n try {\n const res = await gql<{ cartLinesRemove: CartMutationPayload }>(CART_LINES_REMOVE, {\n cartId: ref.current.id,\n lineIds: ids,\n })\n if (res.cartLinesRemove.cart) applyCart(res.cartLinesRemove.cart)\n } catch (e) {\n setState((s) => ({ ...s, error: (e as Error).message }))\n }\n }\n }, [isLive, gql, applyCart, setLocal])\n\n // Shared runner for the discount/gift-card mutations — all return the updated\n // cart + userErrors, all reconcile via applyCart. LIVE-only (cart-level\n // promotions need the backend; the MOCK driver has no concept of them).\n const runCartMutation = useCallback(\n async (query: string, field: string, variables: Record<string, unknown>) => {\n if (!isLive || !gql || !ref.current.id) return\n setState((s) => ({ ...s, loading: true }))\n try {\n const res = await gql<Record<string, CartMutationPayload>>(query, {\n cartId: ref.current.id,\n ...variables,\n })\n const payload = res[field]\n if (payload?.cart) applyCart(payload.cart)\n else throw new Error(payload?.userErrors[0]?.message ?? 'Cart update failed')\n } catch (e) {\n setState((s) => ({ ...s, loading: false, error: (e as Error).message }))\n }\n },\n [isLive, gql, applyCart],\n )\n\n const applyDiscountCodes = useCallback<CartApi['applyDiscountCodes']>(\n (codes) => runCartMutation(CART_DISCOUNT_CODES, 'cartDiscountCodesUpdate', { discountCodes: codes }),\n [runCartMutation],\n )\n const applyGiftCardCodes = useCallback<CartApi['applyGiftCardCodes']>(\n (codes) => runCartMutation(CART_GIFTCARD_UPDATE, 'cartGiftCardCodesUpdate', { giftCardCodes: codes }),\n [runCartMutation],\n )\n const removeGiftCards = useCallback<CartApi['removeGiftCards']>(\n (ids) => runCartMutation(CART_GIFTCARD_REMOVE, 'cartGiftCardCodesRemove', { appliedGiftCardIds: ids }),\n [runCartMutation],\n )\n\n const value: CartApi = {\n ...state,\n add,\n updateQuantity,\n remove,\n clear,\n applyDiscountCodes,\n applyGiftCardCodes,\n removeGiftCards,\n }\n return <CartContext.Provider value={value}>{children}</CartContext.Provider>\n}\n\nexport function useCart(): CartApi {\n const ctx = useContext(CartContext)\n if (!ctx) throw new Error('useCart must be used within <CartProvider>')\n return ctx\n}\n","import { type FC, type ReactNode } from 'react'\nimport { renderToString } from 'react-dom/server'\n\nimport { registerSections } from './registry'\nimport { SectionTree } from './SectionTree'\nimport { DataProvider } from './data'\nimport { CartProvider } from './cart'\nimport { ThemeProvider } from './theme-context'\nimport type { SectionDef, PageDoc, ContentNode } from './types'\nimport type { MountOptions } from './mount'\n\n// Server-side render entry (SSG). Produces the storefront HTML string at BUILD\n// time so the published page ships real content in <div id=\"root\">…</div>\n// (SEO + fast first paint) instead of an empty CSR shell. The client then\n// hydrates the same tree (see mount.tsx). Storefront only — preview/edit planes\n// stay client-only.\n\nfunction defaultsOf<T>(map: Record<string, unknown>): T[] {\n return Object.values(map).map((m) => (m as { default: T }).default)\n}\n\nfunction pickByName<T>(map: Record<string, unknown>, name: string): T | undefined {\n const hit = Object.entries(map).find(\n ([key]) => key.endsWith(`/${name}.json`) || key.endsWith(`/${name}.tsx`),\n )\n return hit ? (hit[1] as { default: T }).default : undefined\n}\n\n/** Render a theme page to an HTML string (same tree mount() renders client-side). */\nexport function renderStorefrontHTML(opts: MountOptions): string {\n registerSections(defaultsOf<SectionDef>(opts.sections))\n\n const shells = opts.shell ? defaultsOf<FC<{ children: ReactNode }>>(opts.shell) : []\n const Shell: FC<{ children: ReactNode }> = shells[0] ?? (({ children }) => <>{children}</>)\n const pageDoc = pickByName<PageDoc>(opts.pages, opts.page ?? 'index') ?? { sections: [] }\n\n return renderToString(\n <DataProvider value={opts.data}>\n <ThemeProvider settings={opts.settings} locale={opts.locale}>\n <CartProvider>\n <Shell>\n <SectionTree tree={pageDoc.sections} />\n </Shell>\n </CartProvider>\n </ThemeProvider>\n </DataProvider>,\n )\n}\n\n/**\n * Render ONE section to an HTML string for the editor's \"Add section\" preview —\n * no Shell/layout, no page routing, no client SPA boot. This is the fast path\n * (Shopify-style): the runtime server-renders just the requested section with\n * the theme's providers + data and returns instant HTML. Block-composed sections\n * are seeded with their preset blocks so they aren't empty.\n */\nexport function renderSectionPreviewHTML(\n opts: Pick<MountOptions, 'sections' | 'data' | 'settings' | 'locale'>,\n type: string,\n settingsOverride?: Record<string, unknown>,\n): string {\n const defs = defaultsOf<SectionDef>(opts.sections)\n registerSections(defs)\n\n const def = defs.find((d) => (d as { name?: string }).name === type)\n const presetBlocks = ((def as { presets?: Array<{ blocks?: ContentNode[] }> } | undefined)\n ?.presets?.[0]?.blocks ?? []) as ContentNode[]\n const node = {\n type,\n id: 'preview',\n settings: settingsOverride ?? {},\n blocks: presetBlocks.map((b, i) => ({\n type: b.type,\n id: `preview-${i}`,\n settings: b.settings ?? {},\n })),\n } as ContentNode\n\n return renderToString(\n <DataProvider value={opts.data}>\n <ThemeProvider settings={opts.settings} locale={opts.locale}>\n <CartProvider>\n <SectionTree tree={[node]} />\n </CartProvider>\n </ThemeProvider>\n </DataProvider>,\n )\n}\n"],"names":["normalizeProduct","normalizeImage","img","money","lines"],"mappings":";;;AAKA,MAAM,kBAAkB,cAAwB,EAAE;AAClD,MAAM,gBAAgB,cAAsB,EAAE;AAGvC,SAAS,cAAc;AAAA,EAC5B,WAAW,CAAA;AAAA,EACX,SAAS,CAAA;AAAA,EACT;AACF,GAIgB;AACd,SACE,oBAAC,gBAAgB,UAAhB,EAAyB,OAAO,UAC/B,UAAA,oBAAC,cAAc,UAAd,EAAuB,OAAO,QAAS,UAAS,GACnD;AAEJ;AAGO,SAAS,cAAwB;AACtC,SAAO,WAAW,eAAe;AACnC;AAGO,SAAS,OAAgC;AAC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U,CAAA;AAC5B,QAAM,OAAO;AAAA,IACX;AAAA,IACA,IAAI;AAAA,IACJ,UAAU,oBAAoB,CAAA;AAAA,IAC9B,QAAQ,aAAa,IAAI,CAAC,GAAG,OAAO;AAAA,MAClC,MAAM,EAAE;AAAA,MACR,IAAI,WAAW,CAAC;AAAA,MAChB,UAAU,EAAE,YAAY,CAAA;AAAA,IAAC,EACzB;AAAA,EAAA;AAGJ,SAAO;AAAA,IACL,oBAAC,gBAAa,OAAO,KAAK,MACxB,UAAA,oBAAC,eAAA,EAAc,UAAU,KAAK,UAAU,QAAQ,KAAK,QACnD,UAAA,oBAAC,cAAA,EACC,UAAA,oBAAC,aAAA,EAAY,MAAM,CAAC,IAAI,EAAA,CAAG,EAAA,CAC7B,EAAA,CACF,EAAA,CACF;AAAA,EAAA;AAEJ;"}
|
package/dist/ssg.js
DELETED
package/dist/ssg.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ssg.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;"}
|
package/dist/types/cart.d.ts
DELETED
|
@@ -1,86 +0,0 @@
|
|
|
1
|
-
import { type ReactNode } from 'react';
|
|
2
|
-
import { type Money } from './data';
|
|
3
|
-
export interface CartLine {
|
|
4
|
-
/** Cart line id — the handle used for update/remove. */
|
|
5
|
-
id: string;
|
|
6
|
-
/** The purchasable variant (merchandise) id. */
|
|
7
|
-
variantId: string;
|
|
8
|
-
quantity: number;
|
|
9
|
-
/** Product title shown in the cart. */
|
|
10
|
-
title: string;
|
|
11
|
-
/** Variant title (e.g. "Black / M"); empty for single-variant products. */
|
|
12
|
-
variantTitle?: string;
|
|
13
|
-
image?: {
|
|
14
|
-
url: string;
|
|
15
|
-
altText?: string;
|
|
16
|
-
} | null;
|
|
17
|
-
/** Per-unit price. */
|
|
18
|
-
price: Money;
|
|
19
|
-
/** Line subtotal (price × quantity). */
|
|
20
|
-
lineSubtotal: Money;
|
|
21
|
-
/** Product handle for linking back to the PDP. */
|
|
22
|
-
productHandle?: string;
|
|
23
|
-
}
|
|
24
|
-
/** A discount code applied to the cart (`applicable=false` when it didn't qualify). */
|
|
25
|
-
export interface AppliedDiscountCode {
|
|
26
|
-
code: string;
|
|
27
|
-
applicable: boolean;
|
|
28
|
-
}
|
|
29
|
-
/** A gift card applied to the cart — masked (only last 4 chars ever leave the API). */
|
|
30
|
-
export interface AppliedGiftCard {
|
|
31
|
-
id: string;
|
|
32
|
-
lastCharacters: string;
|
|
33
|
-
amountUsed: Money;
|
|
34
|
-
balance: Money;
|
|
35
|
-
}
|
|
36
|
-
export interface CartState {
|
|
37
|
-
id: string | null;
|
|
38
|
-
lines: CartLine[];
|
|
39
|
-
subtotal: Money;
|
|
40
|
-
/** Final amount after discounts + gift cards (cost.totalAmount). */
|
|
41
|
-
total: Money;
|
|
42
|
-
totalQuantity: number;
|
|
43
|
-
checkoutUrl: string | null;
|
|
44
|
-
/** Discount codes applied to the cart. */
|
|
45
|
-
discountCodes: AppliedDiscountCode[];
|
|
46
|
-
/** Total savings across all discount allocations — null when nothing's discounted. */
|
|
47
|
-
discountAmount: Money | null;
|
|
48
|
-
/** Gift cards applied to the cart. */
|
|
49
|
-
appliedGiftCards: AppliedGiftCard[];
|
|
50
|
-
/** True while a mutation/bootstrap is in flight. */
|
|
51
|
-
loading: boolean;
|
|
52
|
-
/** True once the client has hydrated cart state post-mount. */
|
|
53
|
-
ready: boolean;
|
|
54
|
-
error: string | null;
|
|
55
|
-
}
|
|
56
|
-
export interface AddToCartInput {
|
|
57
|
-
variantId: string;
|
|
58
|
-
quantity?: number;
|
|
59
|
-
/** Display data — used only by the in-memory MOCK driver (editor/offline). */
|
|
60
|
-
product?: {
|
|
61
|
-
title: string;
|
|
62
|
-
price: Money;
|
|
63
|
-
image?: {
|
|
64
|
-
url: string;
|
|
65
|
-
altText?: string;
|
|
66
|
-
} | null;
|
|
67
|
-
handle?: string;
|
|
68
|
-
variantTitle?: string;
|
|
69
|
-
};
|
|
70
|
-
}
|
|
71
|
-
export interface CartApi extends CartState {
|
|
72
|
-
add: (input: AddToCartInput) => Promise<void>;
|
|
73
|
-
updateQuantity: (lineId: string, quantity: number) => Promise<void>;
|
|
74
|
-
remove: (lineId: string) => Promise<void>;
|
|
75
|
-
clear: () => Promise<void>;
|
|
76
|
-
/** Apply discount codes (replaces the current set; [] clears them). LIVE only. */
|
|
77
|
-
applyDiscountCodes: (codes: string[]) => Promise<void>;
|
|
78
|
-
/** Apply gift card codes to the cart. LIVE only. */
|
|
79
|
-
applyGiftCardCodes: (codes: string[]) => Promise<void>;
|
|
80
|
-
/** Remove applied gift cards by id. LIVE only. */
|
|
81
|
-
removeGiftCards: (ids: string[]) => Promise<void>;
|
|
82
|
-
}
|
|
83
|
-
export declare function CartProvider({ children }: {
|
|
84
|
-
children: ReactNode;
|
|
85
|
-
}): JSX.Element;
|
|
86
|
-
export declare function useCart(): CartApi;
|