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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (233) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +128 -10
  3. package/dist/abi/canvas-live.d.ts +72 -0
  4. package/dist/abi/canvas-live.js +159 -0
  5. package/dist/abi/cart.d.ts +60 -0
  6. package/dist/abi/cart.js +396 -0
  7. package/dist/abi/convert.d.ts +360 -0
  8. package/dist/abi/convert.js +1330 -0
  9. package/dist/abi/data-api.d.ts +15 -0
  10. package/dist/abi/data-api.js +213 -0
  11. package/dist/abi/jcs.d.ts +6 -0
  12. package/dist/abi/jcs.js +28 -0
  13. package/dist/abi/labels.d.ts +3 -0
  14. package/dist/abi/labels.js +34 -0
  15. package/dist/abi/page-data.d.ts +264 -0
  16. package/dist/abi/page-data.js +746 -0
  17. package/dist/abi/page.d.ts +28 -0
  18. package/dist/abi/page.js +57 -0
  19. package/dist/abi/referrals.d.ts +23 -0
  20. package/dist/abi/referrals.js +89 -0
  21. package/dist/abi/rewards.d.ts +27 -0
  22. package/dist/abi/rewards.js +82 -0
  23. package/dist/abi/seo.d.ts +47 -0
  24. package/dist/abi/seo.js +68 -0
  25. package/dist/abi/shell.d.ts +23 -0
  26. package/dist/abi/shell.js +10 -0
  27. package/dist/abi/state-pack.d.ts +17 -0
  28. package/dist/abi/state-pack.js +43 -0
  29. package/dist/abi/wire.d.ts +46 -0
  30. package/dist/abi/wire.js +114 -0
  31. package/dist/build.d.ts +121 -0
  32. package/dist/build.js +401 -0
  33. package/dist/chunks.d.ts +23 -0
  34. package/dist/chunks.js +41 -0
  35. package/dist/client.d.ts +26 -0
  36. package/dist/client.js +101 -0
  37. package/dist/contract.d.ts +6 -0
  38. package/dist/contract.js +6 -0
  39. package/dist/headless/ai.d.ts +132 -0
  40. package/dist/headless/ai.js +99 -0
  41. package/dist/headless/hooks.d.ts +276 -0
  42. package/dist/headless/hooks.js +544 -0
  43. package/dist/headless/i18n.d.ts +13 -0
  44. package/dist/headless/i18n.js +45 -0
  45. package/dist/headless/index.d.ts +44 -0
  46. package/dist/headless/index.js +48 -0
  47. package/dist/headless/lazy-component.d.ts +72 -0
  48. package/dist/headless/lazy-component.js +225 -0
  49. package/dist/headless/lazy-section.d.ts +38 -0
  50. package/dist/headless/lazy-section.js +97 -0
  51. package/dist/headless/model.d.ts +73 -0
  52. package/dist/headless/model.js +115 -0
  53. package/dist/headless/money.d.ts +17 -0
  54. package/dist/headless/money.js +63 -0
  55. package/dist/headless/page.d.ts +45 -0
  56. package/dist/headless/page.js +53 -0
  57. package/dist/headless/platform.d.ts +55 -0
  58. package/dist/headless/platform.js +77 -0
  59. package/dist/headless/primitives/cart.d.ts +90 -0
  60. package/dist/headless/primitives/cart.js +153 -0
  61. package/dist/headless/primitives/collection.d.ts +68 -0
  62. package/dist/headless/primitives/collection.js +80 -0
  63. package/dist/headless/primitives/product.d.ts +101 -0
  64. package/dist/headless/primitives/product.js +117 -0
  65. package/dist/headless/primitives/storefront.d.ts +106 -0
  66. package/dist/headless/primitives/storefront.js +187 -0
  67. package/dist/headless/primitives/util.d.ts +19 -0
  68. package/dist/headless/primitives/util.js +42 -0
  69. package/dist/headless/strings.d.ts +9 -0
  70. package/dist/headless/strings.js +198 -0
  71. package/dist/headless/structured-data.d.ts +31 -0
  72. package/dist/headless/structured-data.js +57 -0
  73. package/dist/headless/tanqory-money.generated.d.ts +493 -0
  74. package/dist/headless/tanqory-money.generated.js +507 -0
  75. package/dist/headless/theme.d.ts +109 -0
  76. package/dist/headless/theme.js +62 -0
  77. package/dist/index.d.ts +21 -0
  78. package/dist/index.js +21 -553
  79. package/dist/runtime/data/StoreProvider.d.ts +84 -0
  80. package/dist/runtime/data/StoreProvider.js +380 -0
  81. package/dist/runtime/data/handle.d.ts +14 -0
  82. package/dist/runtime/data/handle.js +16 -0
  83. package/dist/runtime/data/routes.d.ts +87 -0
  84. package/dist/runtime/data/routes.js +158 -0
  85. package/dist/runtime/data/to-ui.d.ts +286 -0
  86. package/dist/runtime/data/to-ui.js +1009 -0
  87. package/dist/runtime/entries/register.d.ts +9 -0
  88. package/dist/runtime/entries/register.js +9 -0
  89. package/dist/runtime/entries/sections.d.ts +16 -0
  90. package/dist/runtime/entries/sections.js +19 -0
  91. package/dist/{types → runtime/kit}/SectionTree.d.ts +2 -1
  92. package/dist/runtime/kit/SectionTree.js +100 -0
  93. package/dist/runtime/kit/analytics.d.ts +63 -0
  94. package/dist/runtime/kit/analytics.js +250 -0
  95. package/dist/runtime/kit/cart.d.ts +222 -0
  96. package/dist/runtime/kit/cart.js +545 -0
  97. package/dist/{types → runtime/kit}/composition.d.ts +1 -1
  98. package/dist/runtime/kit/composition.js +3 -0
  99. package/dist/{types → runtime/kit}/config.d.ts +2 -2
  100. package/dist/runtime/kit/config.js +6 -0
  101. package/dist/runtime/kit/consent.d.ts +29 -0
  102. package/dist/runtime/kit/consent.js +159 -0
  103. package/dist/runtime/kit/contract/content.d.ts +213 -0
  104. package/dist/runtime/kit/contract/content.js +119 -0
  105. package/dist/runtime/kit/contract/field-types.d.ts +360 -0
  106. package/dist/runtime/kit/contract/field-types.js +216 -0
  107. package/dist/runtime/kit/contract/groups.d.ts +230 -0
  108. package/dist/runtime/kit/contract/groups.js +402 -0
  109. package/dist/runtime/kit/contract/index.d.ts +33 -0
  110. package/dist/runtime/kit/contract/index.js +33 -0
  111. package/dist/runtime/kit/contract/transform.d.ts +82 -0
  112. package/dist/runtime/kit/contract/transform.js +133 -0
  113. package/dist/runtime/kit/contract/validate.d.ts +77 -0
  114. package/dist/runtime/kit/contract/validate.js +520 -0
  115. package/dist/runtime/kit/data.d.ts +732 -0
  116. package/dist/runtime/kit/data.js +1131 -0
  117. package/dist/{types → runtime/kit}/defineSection.d.ts +1 -1
  118. package/dist/runtime/kit/defineSection.js +10 -0
  119. package/dist/runtime/kit/dynamic-source.d.ts +118 -0
  120. package/dist/runtime/kit/dynamic-source.js +311 -0
  121. package/dist/runtime/kit/index.d.ts +24 -0
  122. package/dist/runtime/kit/index.js +24 -0
  123. package/dist/{types → runtime/kit}/jsx-to-json.d.ts +1 -1
  124. package/dist/runtime/kit/jsx-to-json.js +28 -0
  125. package/dist/{types → runtime/kit}/mount.d.ts +25 -4
  126. package/dist/runtime/kit/mount.js +124 -0
  127. package/dist/{types → runtime/kit}/registry.d.ts +1 -1
  128. package/dist/runtime/kit/registry.js +12 -0
  129. package/dist/{types → runtime/kit}/ssg.d.ts +9 -3
  130. package/dist/runtime/kit/ssg.js +56 -0
  131. package/dist/runtime/kit/storefront.d.ts +652 -0
  132. package/dist/runtime/kit/storefront.js +723 -0
  133. package/dist/{types → runtime/kit}/theme-context.d.ts +8 -2
  134. package/dist/runtime/kit/theme-context.js +25 -0
  135. package/dist/runtime/kit/types.d.ts +155 -0
  136. package/dist/runtime/kit/types.js +1 -0
  137. package/dist/runtime/platform/TrackingPixels.d.ts +14 -0
  138. package/dist/runtime/platform/TrackingPixels.js +63 -0
  139. package/dist/runtime/platform/environment.d.ts +68 -0
  140. package/dist/runtime/platform/environment.js +85 -0
  141. package/dist/runtime/platform/locale.d.ts +27 -0
  142. package/dist/runtime/platform/locale.js +42 -0
  143. package/dist/runtime/platform/route-analytics.d.ts +15 -0
  144. package/dist/runtime/platform/route-analytics.js +72 -0
  145. package/dist/runtime/platform/safe-href.d.ts +25 -0
  146. package/dist/runtime/platform/safe-href.js +69 -0
  147. package/dist/runtime/platform/safe-values.d.ts +37 -0
  148. package/dist/runtime/platform/safe-values.js +140 -0
  149. package/dist/runtime/render/SectionRenderer.d.ts +4 -0
  150. package/dist/runtime/render/SectionRenderer.js +199 -0
  151. package/dist/runtime/render/listing-query.d.ts +52 -0
  152. package/dist/runtime/render/listing-query.js +122 -0
  153. package/dist/runtime/render/localized-copy.d.ts +86 -0
  154. package/dist/runtime/render/localized-copy.js +129 -0
  155. package/dist/runtime/render/product-listing.d.ts +11 -0
  156. package/dist/runtime/render/product-listing.js +243 -0
  157. package/dist/runtime/render/resolved.d.ts +47 -0
  158. package/dist/runtime/render/resolved.js +80 -0
  159. package/dist/runtime/render/section-actions.d.ts +67 -0
  160. package/dist/runtime/render/section-actions.js +205 -0
  161. package/dist/runtime/render/starter.d.ts +11 -0
  162. package/dist/runtime/render/starter.js +96 -0
  163. package/dist/runtime/seo/head.d.ts +115 -0
  164. package/dist/runtime/seo/head.js +281 -0
  165. package/dist/runtime/seo/structured-data.d.ts +83 -0
  166. package/dist/runtime/seo/structured-data.js +252 -0
  167. package/dist/runtime/shell/PageShell.d.ts +18 -0
  168. package/dist/runtime/shell/PageShell.js +118 -0
  169. package/dist/runtime/shell/RuntimeBridge.d.ts +18 -0
  170. package/dist/runtime/shell/RuntimeBridge.js +124 -0
  171. package/dist/runtime/shell/overlay-state.d.ts +31 -0
  172. package/dist/runtime/shell/overlay-state.js +59 -0
  173. package/dist/runtime/shell/preview-mode.d.ts +2 -0
  174. package/dist/runtime/shell/preview-mode.js +11 -0
  175. package/dist/runtime/shell/spa-router.d.ts +14 -0
  176. package/dist/runtime/shell/spa-router.js +76 -0
  177. package/dist/runtime/shell/url-redirects.d.ts +6 -0
  178. package/dist/runtime/shell/url-redirects.js +37 -0
  179. package/dist/runtime/slots.d.ts +74 -0
  180. package/dist/runtime/slots.js +16 -0
  181. package/dist/runtime.d.ts +34 -0
  182. package/dist/runtime.js +40 -0
  183. package/dist/sdk/app-block.d.ts +29 -0
  184. package/dist/sdk/app-block.js +22 -0
  185. package/dist/sdk/font-hooks.d.ts +7 -0
  186. package/dist/sdk/font-hooks.js +21 -0
  187. package/dist/sdk/fonts.d.ts +144 -0
  188. package/dist/sdk/fonts.js +241 -0
  189. package/dist/sdk/index.d.ts +32 -0
  190. package/dist/sdk/index.js +36 -0
  191. package/dist/sdk/motion-hooks.d.ts +23 -0
  192. package/dist/sdk/motion-hooks.js +46 -0
  193. package/dist/sdk/motion.d.ts +78 -0
  194. package/dist/sdk/motion.js +292 -0
  195. package/dist/sdk/referrals.d.ts +62 -0
  196. package/dist/sdk/referrals.js +20 -0
  197. package/dist/sdk/rewards.d.ts +85 -0
  198. package/dist/sdk/rewards.js +29 -0
  199. package/dist/sdk/runtime-context.d.ts +230 -0
  200. package/dist/sdk/runtime-context.js +73 -0
  201. package/dist/sdk/schema.d.ts +249 -0
  202. package/dist/sdk/schema.js +168 -0
  203. package/dist/sdk/server-render.d.ts +8 -0
  204. package/dist/sdk/server-render.js +12 -0
  205. package/dist/sdk/store-lookup.d.ts +32 -0
  206. package/dist/sdk/store-lookup.js +48 -0
  207. package/dist/sdk/store.d.ts +164 -0
  208. package/dist/sdk/store.js +5 -0
  209. package/dist/sdk/sx.d.ts +45 -0
  210. package/dist/sdk/sx.js +117 -0
  211. package/dist/sdk/theme.d.ts +212 -0
  212. package/dist/sdk/theme.js +27 -0
  213. package/dist/sdk/types.d.ts +789 -0
  214. package/dist/sdk/types.js +7 -0
  215. package/dist/server.d.ts +112 -0
  216. package/dist/server.js +589 -0
  217. package/dist/vite-chunks.d.ts +10 -0
  218. package/dist/vite-chunks.js +44 -0
  219. package/docs/headless-api.md +250 -0
  220. package/package.json +72 -26
  221. package/dist/index.js.map +0 -1
  222. package/dist/ssg-BZ5FYTw7.js +0 -1802
  223. package/dist/ssg-BZ5FYTw7.js.map +0 -1
  224. package/dist/ssg.js +0 -8
  225. package/dist/ssg.js.map +0 -1
  226. package/dist/types/cart.d.ts +0 -86
  227. package/dist/types/data.d.ts +0 -357
  228. package/dist/types/dynamic-source.d.ts +0 -84
  229. package/dist/types/editor.d.ts +0 -5
  230. package/dist/types/index.d.ts +0 -20
  231. package/dist/types/preview-bridge.d.ts +0 -9
  232. package/dist/types/storefront.d.ts +0 -333
  233. package/dist/types/types.d.ts +0 -44
@@ -0,0 +1,545 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { createContext, useCallback, useContext, useEffect, useRef, useState, } from 'react';
3
+ import { useData } from './data.js';
4
+ /**
5
+ * Client-side shopping cart for storefront themes.
6
+ *
7
+ * Backed by the Tanqory Storefront GraphQL cart API (commerce-standard:
8
+ * `cartCreate` / `cartLinesAdd` / `cartLinesUpdate` / `cartLinesRemove`,
9
+ * merchandise = Variant). The cart id is persisted in localStorage so the
10
+ * cart survives reloads; line data is always sourced from the backend (the
11
+ * single source of truth) and reconciled after every mutation.
12
+ *
13
+ * Two drivers, picked automatically:
14
+ * - LIVE — when `useData().graphql` exists (createLiveData). Real mutations.
15
+ * - MOCK — when it doesn't (createMockData: editor preview / offline dev).
16
+ * An in-memory cart so +/- / remove still demonstrate correctly.
17
+ *
18
+ * SSR/SSG-safe: the provider renders an empty cart on the server AND on the
19
+ * first client render (`ready === false`), then hydrates from localStorage +
20
+ * backend in a post-mount effect — so there's never a hydration mismatch.
21
+ */
22
+ const STORAGE_KEY = 'tq-cart-id';
23
+ const DEFAULT_CURRENCY = 'USD';
24
+ // commerce-standard: single-variant products name their lone variant "Default Title".
25
+ // Hide it so single-variant lines don't show a meaningless variant subtitle.
26
+ const DEFAULT_VARIANT_TITLE = 'Default Title';
27
+ // ─── Money helpers (amounts are decimal strings) ──────────────────
28
+ /** The number of fraction digits a Money string carries — what the backend
29
+ * formats for that currency (0 for JPY/KRW, 3 for KWD/BHD, 2 for most). A
30
+ * fixed `toFixed(2)` printed "¥5000.00" and rounded a 3-decimal currency. */
31
+ function decimalsOf(amount) {
32
+ return (amount?.split('.')[1] ?? '').length;
33
+ }
34
+ function money(amount, currencyCode, decimals = 2) {
35
+ return { amount: amount.toFixed(decimals), currencyCode };
36
+ }
37
+ function multiply(price, qty) {
38
+ return money(Number(price.amount) * qty, price.currencyCode, decimalsOf(price.amount));
39
+ }
40
+ function sumLines(lines) {
41
+ const first = lines[0]?.lineSubtotal;
42
+ const currencyCode = first?.currencyCode ?? DEFAULT_CURRENCY;
43
+ const total = lines.reduce((acc, l) => acc + Number(l.lineSubtotal.amount), 0);
44
+ return money(total, currencyCode, first ? decimalsOf(first.amount) : 2);
45
+ }
46
+ function countQty(lines) {
47
+ return lines.reduce((acc, l) => acc + l.quantity, 0);
48
+ }
49
+ // ─── GraphQL (LIVE driver) ────────────────────────────────────────
50
+ const CART_FRAGMENT = /* GraphQL */ `
51
+ fragment CartFields on Cart {
52
+ id
53
+ checkoutUrl
54
+ totalQuantity
55
+ note
56
+ attributes { key value }
57
+ cost {
58
+ subtotalAmount { amount currencyCode }
59
+ totalAmount { amount currencyCode }
60
+ totalTaxAmount { amount currencyCode }
61
+ totalDutyAmount { amount currencyCode }
62
+ }
63
+ discountCodes { code applicable }
64
+ discountAllocations {
65
+ ... on CartCodeDiscountAllocation { code discountedAmount { amount currencyCode } }
66
+ ... on CartAutomaticDiscountAllocation { title discountedAmount { amount currencyCode } }
67
+ ... on CartCustomDiscountAllocation { title discountedAmount { amount currencyCode } }
68
+ }
69
+ appliedGiftCards {
70
+ id
71
+ lastCharacters
72
+ amountUsed { amount currencyCode }
73
+ balance { amount currencyCode }
74
+ }
75
+ lines(first: 100) {
76
+ nodes {
77
+ id
78
+ quantity
79
+ attributes { key value }
80
+ discountAllocations {
81
+ ... on CartCodeDiscountAllocation { code discountedAmount { amount currencyCode } }
82
+ ... on CartAutomaticDiscountAllocation { title discountedAmount { amount currencyCode } }
83
+ ... on CartCustomDiscountAllocation { title discountedAmount { amount currencyCode } }
84
+ }
85
+ sellingPlanAllocation {
86
+ sellingPlan { id name }
87
+ checkoutChargeAmount { amount currencyCode }
88
+ remainingBalanceChargeAmount { amount currencyCode }
89
+ }
90
+ cost {
91
+ subtotalAmount { amount currencyCode }
92
+ amountPerQuantity { amount currencyCode }
93
+ }
94
+ merchandise {
95
+ ... on Variant {
96
+ id
97
+ title
98
+ image { url altText }
99
+ price { amount currencyCode }
100
+ product { handle title featuredImage { url altText } }
101
+ }
102
+ }
103
+ }
104
+ }
105
+ }
106
+ `;
107
+ const CART_QUERY = /* GraphQL */ `
108
+ query Cart($id: ID!) { cart(id: $id) { ...CartFields } }
109
+ ${CART_FRAGMENT}
110
+ `;
111
+ const CART_CREATE = /* GraphQL */ `
112
+ mutation CartCreate($lines: [CartLineInput!]!) {
113
+ cartCreate(input: { lines: $lines }) { cart { ...CartFields } userErrors { message } }
114
+ }
115
+ ${CART_FRAGMENT}
116
+ `;
117
+ const CART_LINES_ADD = /* GraphQL */ `
118
+ mutation CartLinesAdd($cartId: ID!, $lines: [CartLineInput!]!) {
119
+ cartLinesAdd(cartId: $cartId, lines: $lines) { cart { ...CartFields } userErrors { message } }
120
+ }
121
+ ${CART_FRAGMENT}
122
+ `;
123
+ const CART_LINES_UPDATE = /* GraphQL */ `
124
+ mutation CartLinesUpdate($cartId: ID!, $lines: [CartLineUpdateInput!]!) {
125
+ cartLinesUpdate(cartId: $cartId, lines: $lines) { cart { ...CartFields } userErrors { message } }
126
+ }
127
+ ${CART_FRAGMENT}
128
+ `;
129
+ const CART_LINES_REMOVE = /* GraphQL */ `
130
+ mutation CartLinesRemove($cartId: ID!, $lineIds: [ID!]!) {
131
+ cartLinesRemove(cartId: $cartId, lineIds: $lineIds) { cart { ...CartFields } userErrors { message } }
132
+ }
133
+ ${CART_FRAGMENT}
134
+ `;
135
+ const CART_DISCOUNT_CODES = /* GraphQL */ `
136
+ mutation CartDiscountCodesUpdate($cartId: ID!, $discountCodes: [String!]) {
137
+ cartDiscountCodesUpdate(cartId: $cartId, discountCodes: $discountCodes) {
138
+ cart { ...CartFields } userErrors { message }
139
+ }
140
+ }
141
+ ${CART_FRAGMENT}
142
+ `;
143
+ const CART_GIFTCARD_UPDATE = /* GraphQL */ `
144
+ mutation CartGiftCardCodesUpdate($cartId: ID!, $giftCardCodes: [String!]!) {
145
+ cartGiftCardCodesUpdate(cartId: $cartId, giftCardCodes: $giftCardCodes) {
146
+ cart { ...CartFields } userErrors { message }
147
+ }
148
+ }
149
+ ${CART_FRAGMENT}
150
+ `;
151
+ const CART_GIFTCARD_REMOVE = /* GraphQL */ `
152
+ mutation CartGiftCardCodesRemove($cartId: ID!, $appliedGiftCardIds: [ID!]!) {
153
+ cartGiftCardCodesRemove(cartId: $cartId, appliedGiftCardIds: $appliedGiftCardIds) {
154
+ cart { ...CartFields } userErrors { message }
155
+ }
156
+ }
157
+ ${CART_FRAGMENT}
158
+ `;
159
+ const CART_NOTE_UPDATE = /* GraphQL */ `
160
+ mutation CartNoteUpdate($cartId: ID!, $note: String) {
161
+ cartNoteUpdate(cartId: $cartId, note: $note) {
162
+ cart { ...CartFields } userErrors { message }
163
+ }
164
+ }
165
+ ${CART_FRAGMENT}
166
+ `;
167
+ const CART_ATTRIBUTES_UPDATE = /* GraphQL */ `
168
+ mutation CartAttributesUpdate($cartId: ID!, $attributes: [AttributeInput!]!) {
169
+ cartAttributesUpdate(cartId: $cartId, attributes: $attributes) {
170
+ cart { ...CartFields } userErrors { message }
171
+ }
172
+ }
173
+ ${CART_FRAGMENT}
174
+ `;
175
+ function normalizeImage(img) {
176
+ if (!img || !img.url)
177
+ return null;
178
+ return { url: img.url, ...(img.altText ? { altText: img.altText } : {}) };
179
+ }
180
+ /** GqlCart → the cart fields we keep in state (loading/ready/error added by caller). */
181
+ function normalizeCart(c) {
182
+ const lines = c.lines.nodes.map((n) => {
183
+ const m = n.merchandise;
184
+ const variantTitle = m.title && m.title !== DEFAULT_VARIANT_TITLE ? m.title : undefined;
185
+ return {
186
+ id: n.id,
187
+ variantId: m.id,
188
+ quantity: n.quantity,
189
+ title: m.product?.title ?? m.title ?? 'Item',
190
+ ...(variantTitle ? { variantTitle } : {}),
191
+ image: normalizeImage(m.image) ?? normalizeImage(m.product?.featuredImage),
192
+ price: n.cost.amountPerQuantity ?? m.price,
193
+ lineSubtotal: n.cost.subtotalAmount ?? multiply(m.price, n.quantity),
194
+ ...(m.product?.handle ? { productHandle: m.product.handle } : {}),
195
+ ...(n.attributes?.length ? { attributes: n.attributes.map((a) => ({ key: a.key, value: a.value ?? null })) } : {}),
196
+ ...(n.discountAllocations?.length
197
+ ? { discountAllocations: n.discountAllocations.map((d) => ({ title: d.title ?? null, code: d.code ?? null, amount: d.discountedAmount ?? money(0, m.price?.currencyCode ?? 'USD', decimalsOf(m.price?.amount)) })) }
198
+ : {}),
199
+ ...(n.sellingPlanAllocation?.sellingPlan
200
+ ? { sellingPlanAllocation: {
201
+ sellingPlanId: n.sellingPlanAllocation.sellingPlan.id,
202
+ sellingPlanName: n.sellingPlanAllocation.sellingPlan.name,
203
+ checkoutCharge: n.sellingPlanAllocation.checkoutChargeAmount ?? null,
204
+ remainingBalance: n.sellingPlanAllocation.remainingBalanceChargeAmount ?? null,
205
+ } }
206
+ : {}),
207
+ };
208
+ });
209
+ const subtotal = c.cost?.subtotalAmount ?? sumLines(lines);
210
+ // Sum every discount allocation (code + automatic) into one "you saved" figure.
211
+ const allocations = c.discountAllocations ?? [];
212
+ const discountAmount = allocations.length > 0
213
+ ? money(allocations.reduce((acc, a) => acc + Number(a.discountedAmount.amount), 0), allocations[0].discountedAmount.currencyCode, decimalsOf(allocations[0].discountedAmount.amount))
214
+ : null;
215
+ return {
216
+ id: c.id,
217
+ lines,
218
+ subtotal,
219
+ total: c.cost?.totalAmount ?? subtotal,
220
+ tax: c.cost?.totalTaxAmount ?? null,
221
+ duty: c.cost?.totalDutyAmount ?? null,
222
+ note: c.note ?? null,
223
+ attributes: (c.attributes ?? []).map((a) => ({ key: a.key, value: a.value ?? null })),
224
+ totalQuantity: c.totalQuantity ?? countQty(lines),
225
+ checkoutUrl: c.checkoutUrl ?? null,
226
+ discountCodes: (c.discountCodes ?? []).map((d) => ({ code: d.code, applicable: d.applicable })),
227
+ discountAmount,
228
+ ...(allocations.length ? { discountAllocations: allocations.map((a) => ({ title: a.title ?? null, code: a.code ?? null, amount: a.discountedAmount })) } : {}),
229
+ appliedGiftCards: (c.appliedGiftCards ?? []).map((g) => ({
230
+ id: g.id,
231
+ lastCharacters: g.lastCharacters,
232
+ amountUsed: g.amountUsed,
233
+ balance: g.balance,
234
+ })),
235
+ };
236
+ }
237
+ // ─── Context ──────────────────────────────────────────────────────
238
+ const EMPTY = {
239
+ id: null,
240
+ lines: [],
241
+ subtotal: { amount: '0.00', currencyCode: DEFAULT_CURRENCY },
242
+ total: { amount: '0.00', currencyCode: DEFAULT_CURRENCY },
243
+ totalQuantity: 0,
244
+ checkoutUrl: null,
245
+ discountCodes: [],
246
+ discountAmount: null,
247
+ appliedGiftCards: [],
248
+ loading: false,
249
+ ready: false,
250
+ error: null,
251
+ };
252
+ /** Exported so another cart driver (lib/abi/cart.tsx, Theme ABI v2) can provide the same `useCart()`. */
253
+ export const CartContext = createContext(null);
254
+ function readStoredCartId() {
255
+ if (typeof window === 'undefined')
256
+ return null;
257
+ try {
258
+ return window.localStorage.getItem(STORAGE_KEY);
259
+ }
260
+ catch {
261
+ return null;
262
+ }
263
+ }
264
+ function writeStoredCartId(id) {
265
+ if (typeof window === 'undefined')
266
+ return;
267
+ try {
268
+ if (id)
269
+ window.localStorage.setItem(STORAGE_KEY, id);
270
+ else
271
+ window.localStorage.removeItem(STORAGE_KEY);
272
+ }
273
+ catch {
274
+ /* private mode etc. */
275
+ }
276
+ }
277
+ export function CartProvider({ children }) {
278
+ const data = useData();
279
+ const gql = data.graphql;
280
+ const isLive = typeof gql === 'function';
281
+ const [state, setState] = useState(EMPTY);
282
+ // Mirror state in a ref so async callbacks read the current cart id / lines
283
+ // without re-creating the callbacks on every change.
284
+ const ref = useRef(state);
285
+ ref.current = state;
286
+ // The cart id as soon as the backend assigns it — `ref.current.id` only
287
+ // catches up on the next render, which is too late for a second `add()`
288
+ // that is already waiting on the first one's cartCreate.
289
+ const idRef = useRef(state.id);
290
+ // One cartCreate at a time: two adds racing before the first response would
291
+ // each create a cart and the last one to store its id would orphan the other.
292
+ const createInFlight = useRef(null);
293
+ const applyCart = useCallback((c) => {
294
+ const next = normalizeCart(c);
295
+ idRef.current = next.id;
296
+ writeStoredCartId(next.id);
297
+ setState((s) => ({ ...s, ...next, loading: false, error: null }));
298
+ }, []);
299
+ const setLocal = useCallback((lines) => {
300
+ setState((s) => ({
301
+ ...s,
302
+ lines,
303
+ subtotal: sumLines(lines),
304
+ total: sumLines(lines),
305
+ totalQuantity: countQty(lines),
306
+ loading: false,
307
+ error: null,
308
+ }));
309
+ }, []);
310
+ // Hydrate after mount (client-only): restore the saved cart from the backend.
311
+ useEffect(() => {
312
+ let cancelled = false;
313
+ async function hydrate() {
314
+ const id = readStoredCartId();
315
+ if (isLive && gql && id) {
316
+ try {
317
+ const res = await gql(CART_QUERY, { id });
318
+ if (cancelled)
319
+ return;
320
+ if (res.cart) {
321
+ const next = normalizeCart(res.cart);
322
+ idRef.current = next.id;
323
+ setState((s) => ({ ...s, ...next, ready: true }));
324
+ return;
325
+ }
326
+ // Cart expired / not found — drop the stale id.
327
+ writeStoredCartId(null);
328
+ }
329
+ catch {
330
+ // Leave the cart empty but mark ready so the UI stops loading.
331
+ }
332
+ }
333
+ if (!cancelled)
334
+ setState((s) => ({ ...s, ready: true }));
335
+ }
336
+ void hydrate();
337
+ return () => {
338
+ cancelled = true;
339
+ };
340
+ }, [isLive, gql]);
341
+ const add = useCallback(async (input) => {
342
+ const quantity = input.quantity ?? 1;
343
+ if (quantity < 1)
344
+ return false;
345
+ if (isLive && gql) {
346
+ setState((s) => ({ ...s, loading: true }));
347
+ try {
348
+ const lines = [{ merchandiseId: input.variantId, quantity }];
349
+ // Another add is creating the cart right now: wait for it, then add
350
+ // to THAT cart instead of creating a second one.
351
+ if (createInFlight.current) {
352
+ try {
353
+ await createInFlight.current;
354
+ }
355
+ catch {
356
+ /* the creator reports its own failure; we try again below */
357
+ }
358
+ }
359
+ if (!idRef.current) {
360
+ const create = (async () => {
361
+ const res = await gql(CART_CREATE, { lines });
362
+ const payload = res.cartCreate;
363
+ if (payload.cart)
364
+ applyCart(payload.cart);
365
+ else
366
+ throw new Error(payload.userErrors[0]?.message ?? 'Could not create cart');
367
+ })();
368
+ createInFlight.current = create;
369
+ try {
370
+ await create;
371
+ }
372
+ finally {
373
+ if (createInFlight.current === create)
374
+ createInFlight.current = null;
375
+ }
376
+ }
377
+ else {
378
+ const res = await gql(CART_LINES_ADD, {
379
+ cartId: idRef.current,
380
+ lines,
381
+ });
382
+ const payload = res.cartLinesAdd;
383
+ if (payload.cart)
384
+ applyCart(payload.cart);
385
+ else
386
+ throw new Error(payload.userErrors[0]?.message ?? 'Could not add to cart');
387
+ }
388
+ return true;
389
+ }
390
+ catch (e) {
391
+ setState((s) => ({ ...s, loading: false, error: e.message }));
392
+ return false;
393
+ }
394
+ }
395
+ // MOCK driver — merge by variant id using the supplied display data.
396
+ const p = input.product;
397
+ if (!p)
398
+ return false;
399
+ const existing = ref.current.lines.find((l) => l.variantId === input.variantId);
400
+ let lines;
401
+ if (existing) {
402
+ lines = ref.current.lines.map((l) => l.variantId === input.variantId
403
+ ? { ...l, quantity: l.quantity + quantity, lineSubtotal: multiply(l.price, l.quantity + quantity) }
404
+ : l);
405
+ }
406
+ else {
407
+ lines = [
408
+ ...ref.current.lines,
409
+ {
410
+ id: `mock-${input.variantId}`,
411
+ variantId: input.variantId,
412
+ quantity,
413
+ title: p.title,
414
+ ...(p.variantTitle ? { variantTitle: p.variantTitle } : {}),
415
+ image: p.image ?? null,
416
+ price: p.price,
417
+ lineSubtotal: multiply(p.price, quantity),
418
+ ...(p.handle ? { productHandle: p.handle } : {}),
419
+ },
420
+ ];
421
+ }
422
+ setLocal(lines);
423
+ return true;
424
+ }, [isLive, gql, applyCart, setLocal]);
425
+ // An optimistic edit the backend did not confirm is undone: the drawer must
426
+ // show what the cart actually holds, or a "removed" line comes back at checkout.
427
+ const rollback = useCallback((previous, message) => {
428
+ setLocal(previous);
429
+ setState((s) => ({ ...s, error: message }));
430
+ }, [setLocal]);
431
+ const remove = useCallback(async (lineId) => {
432
+ const previous = ref.current.lines;
433
+ const optimistic = previous.filter((l) => l.id !== lineId);
434
+ setLocal(optimistic);
435
+ if (isLive && gql && idRef.current) {
436
+ try {
437
+ const res = await gql(CART_LINES_REMOVE, {
438
+ cartId: idRef.current,
439
+ lineIds: [lineId],
440
+ });
441
+ const payload = res.cartLinesRemove;
442
+ if (payload.cart)
443
+ applyCart(payload.cart);
444
+ else
445
+ rollback(previous, payload.userErrors[0]?.message ?? 'Could not remove from cart');
446
+ }
447
+ catch (e) {
448
+ rollback(previous, e.message);
449
+ }
450
+ }
451
+ }, [isLive, gql, applyCart, setLocal, rollback]);
452
+ const updateQuantity = useCallback(async (lineId, quantity) => {
453
+ if (quantity <= 0) {
454
+ await remove(lineId);
455
+ return;
456
+ }
457
+ // Optimistic local update for a snappy stepper, reconciled below (live).
458
+ const previous = ref.current.lines;
459
+ const optimistic = previous.map((l) => l.id === lineId ? { ...l, quantity, lineSubtotal: multiply(l.price, quantity) } : l);
460
+ setLocal(optimistic);
461
+ if (isLive && gql && idRef.current) {
462
+ try {
463
+ const res = await gql(CART_LINES_UPDATE, {
464
+ cartId: idRef.current,
465
+ lines: [{ id: lineId, quantity }],
466
+ });
467
+ const payload = res.cartLinesUpdate;
468
+ if (payload.cart)
469
+ applyCart(payload.cart);
470
+ else
471
+ rollback(previous, payload.userErrors[0]?.message ?? 'Could not update quantity');
472
+ }
473
+ catch (e) {
474
+ rollback(previous, e.message);
475
+ }
476
+ }
477
+ }, [isLive, gql, applyCart, setLocal, remove, rollback]);
478
+ const clear = useCallback(async () => {
479
+ const previous = ref.current.lines;
480
+ const ids = previous.map((l) => l.id);
481
+ setLocal([]);
482
+ if (isLive && gql && idRef.current && ids.length > 0) {
483
+ try {
484
+ const res = await gql(CART_LINES_REMOVE, {
485
+ cartId: idRef.current,
486
+ lineIds: ids,
487
+ });
488
+ const payload = res.cartLinesRemove;
489
+ if (payload.cart)
490
+ applyCart(payload.cart);
491
+ else
492
+ rollback(previous, payload.userErrors[0]?.message ?? 'Could not clear cart');
493
+ }
494
+ catch (e) {
495
+ rollback(previous, e.message);
496
+ }
497
+ }
498
+ }, [isLive, gql, applyCart, setLocal, rollback]);
499
+ // Shared runner for the discount/gift-card mutations — all return the updated
500
+ // cart + userErrors, all reconcile via applyCart. LIVE-only (cart-level
501
+ // promotions need the backend; the MOCK driver has no concept of them).
502
+ const runCartMutation = useCallback(async (query, field, variables) => {
503
+ if (!isLive || !gql || !idRef.current)
504
+ return;
505
+ setState((s) => ({ ...s, loading: true }));
506
+ try {
507
+ const res = await gql(query, {
508
+ cartId: idRef.current,
509
+ ...variables,
510
+ });
511
+ const payload = res[field];
512
+ if (payload?.cart)
513
+ applyCart(payload.cart);
514
+ else
515
+ throw new Error(payload?.userErrors[0]?.message ?? 'Cart update failed');
516
+ }
517
+ catch (e) {
518
+ setState((s) => ({ ...s, loading: false, error: e.message }));
519
+ }
520
+ }, [isLive, gql, applyCart]);
521
+ const applyDiscountCodes = useCallback((codes) => runCartMutation(CART_DISCOUNT_CODES, 'cartDiscountCodesUpdate', { discountCodes: codes }), [runCartMutation]);
522
+ const applyGiftCardCodes = useCallback((codes) => runCartMutation(CART_GIFTCARD_UPDATE, 'cartGiftCardCodesUpdate', { giftCardCodes: codes }), [runCartMutation]);
523
+ const removeGiftCards = useCallback((ids) => runCartMutation(CART_GIFTCARD_REMOVE, 'cartGiftCardCodesRemove', { appliedGiftCardIds: ids }), [runCartMutation]);
524
+ const updateNote = useCallback((note) => runCartMutation(CART_NOTE_UPDATE, 'cartNoteUpdate', { note }), [runCartMutation]);
525
+ const updateAttributes = useCallback((attributes) => runCartMutation(CART_ATTRIBUTES_UPDATE, 'cartAttributesUpdate', { attributes }), [runCartMutation]);
526
+ const value = {
527
+ ...state,
528
+ add,
529
+ updateQuantity,
530
+ remove,
531
+ clear,
532
+ applyDiscountCodes,
533
+ applyGiftCardCodes,
534
+ removeGiftCards,
535
+ updateNote,
536
+ updateAttributes,
537
+ };
538
+ return _jsx(CartContext.Provider, { value: value, children: children });
539
+ }
540
+ export function useCart() {
541
+ const ctx = useContext(CartContext);
542
+ if (!ctx)
543
+ throw new Error('useCart must be used within <CartProvider>');
544
+ return ctx;
545
+ }
@@ -1,5 +1,5 @@
1
1
  import type { FC, ReactNode } from 'react';
2
- import type { SectionDef } from './types';
2
+ import type { SectionDef } from './types.js';
3
3
  /**
4
4
  * A section used inside a *page composition* takes `settings` (literal) + nested
5
5
  * children — never `attributes`. `tag(SectionDef)` returns it typed for that
@@ -0,0 +1,3 @@
1
+ export function tag(def) {
2
+ return def.component;
3
+ }
@@ -3,7 +3,7 @@ export interface ThemeConfig {
3
3
  routes: Record<string, string>;
4
4
  data: {
5
5
  mode: 'mock' | 'live';
6
- /** Cell store-api base, e.g. https://api-do-sgp1.tanqory.com (live mode). */
6
+ /** Cell store-api base, e.g. https://api.example.com (live mode). */
7
7
  endpoint?: string | undefined;
8
8
  /** Store UUID to preview against (live mode). */
9
9
  storeId?: string | undefined;
@@ -13,7 +13,7 @@ export interface ThemeConfig {
13
13
  tokens?: string;
14
14
  }
15
15
  export declare function defineTheme(config: ThemeConfig): ThemeConfig;
16
- import type { AttrSpec } from './types';
16
+ import type { AttrSpec } from './types.js';
17
17
  /** Global theme settings schema (drives the editor's "Theme settings" panel). */
18
18
  export type SettingsSchema = Record<string, AttrSpec>;
19
19
  export declare function defineSettings(schema: SettingsSchema): SettingsSchema;
@@ -0,0 +1,6 @@
1
+ export function defineTheme(config) {
2
+ return config;
3
+ }
4
+ export function defineSettings(schema) {
5
+ return schema;
6
+ }
@@ -0,0 +1,29 @@
1
+ export interface Consent {
2
+ analytics: boolean;
3
+ marketing: boolean;
4
+ }
5
+ export type ConsentMode = 'OPT_IN' | 'OPT_OUT' | 'NONE';
6
+ /** Set the mode from an authoritative (live) verdict. The ONLY way the gate opens — components must not call it. */
7
+ export declare function setConsentMode(m: ConsentMode): void;
8
+ /** Force the gate closed (OPT_IN) and un-armed — the SSG boot, until the live answer arrives. */
9
+ export declare function holdConsentClosed(): void;
10
+ export declare function getConsentMode(): ConsentMode;
11
+ export declare function isConsentArmed(): boolean;
12
+ /** Subscribe to mode/armed changes (banner display); returns an unsubscribe fn. */
13
+ export declare function onConsentModeChange(cb: () => void): () => void;
14
+ /** Back-compat for callers that only know a boolean: true → OPT_IN, false → NONE. */
15
+ export declare function setBannerRequired(v: boolean): void;
16
+ export declare function isBannerRequired(): boolean;
17
+ /**
18
+ * The mode for a loaded shop. The server's `cookieBanner.mode` is authoritative; an older API that only sends `enabled`
19
+ * is read as before (enabled → OPT_IN); anything missing or unrecognised is OPT_IN, never permissive.
20
+ */
21
+ export declare function consentModeFromShop(shop: unknown): ConsentMode;
22
+ /** The stored decision, or null when the shopper hasn't chosen yet. */
23
+ export declare function getConsent(): Consent | null;
24
+ export declare function hasDecided(): boolean;
25
+ export declare function setConsent(c: Consent): void;
26
+ /** True when `purpose` may run right now (see gate semantics above). */
27
+ export declare function hasConsent(purpose: keyof Consent): boolean;
28
+ /** Subscribe to consent changes; returns an unsubscribe fn. */
29
+ export declare function onConsentChange(cb: (c: Consent) => void): () => void;