@usequeek/theme-kit 0.1.27 → 0.1.29

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/README.md CHANGED
@@ -346,6 +346,32 @@ export default function ProductPage({ product, metafieldDefinitions }: ProductPa
346
346
  nothing visible to show.
347
347
  - MAY: compose your own layout with the exported `EntryCard` and `renderValue`
348
348
  from the same module instead of placing the section.
349
+ - Collections, blog posts and product variants carry custom fields too. Each
350
+ arrives as `metafields` on the resource — `collection.metafields`,
351
+ `post.metafields` (blog posts only, `type=post`; pages, galleries and policies
352
+ carry none) and `variant.metafields` (inside `product.variants`) — keyed
353
+ `namespace.key` (`custom.fabric`), always an object (`{}` when none), and only
354
+ with the definitions the merchant marked storefront-visible. A new definition
355
+ is private until the merchant makes it visible, so a value you cannot see is
356
+ not an error. Labels come from the page's definitions: `metafieldDefinitions`
357
+ on the collection and post pages (`CollectionPageProps`, `PostPageProps`),
358
+ `variantMetafieldDefinitions` on the product page. Place the matching section
359
+ (all optional props, every one renders nothing when there is nothing visible):
360
+
361
+ ```tsx
362
+ <CollectionMetafields collection={collection} definitions={metafieldDefinitions} />
363
+ <PostMetafields post={post} definitions={metafieldDefinitions} />
364
+ <VariantMetafields variant={selectedVariant} definitions={variantMetafieldDefinitions} />
365
+ // or any owner through the one component behind them:
366
+ <Metafields owner="collection" metafields={collection.metafields} definitions={metafieldDefinitions} />
367
+ ```
368
+
369
+ `owner` is `'product' | 'variant' | 'collection' | 'post'`. All owners emit the
370
+ same `core-metafields*` classes, so the styling you wrote for the product
371
+ section already covers them; off the product the root also carries
372
+ `core-metafields--collection` / `--post` / `--variant` for owner-specific
373
+ rules. Definitions are found under the value's own `namespace.key` handle, or
374
+ under the bare key for a map keyed that way.
349
375
  - Style only: the section emits `core-metafields*` classes (`core-metafields`,
350
376
  `__field`, `__label`, `__value`, `__text`, `__link`, `__image`, `__pre`,
351
377
  `__list`, `__list-item`, `__entry-card`, `__entry-title`, `__entry-field`,
@@ -0,0 +1,277 @@
1
+ 'use client';
2
+
3
+ import { roundAmount } from '../utils/format';
4
+ import { gtagPush } from './gtag';
5
+
6
+ /**
7
+ * The one place a storefront announces a shopping event.
8
+ *
9
+ * trackStorefrontEvent('product_added_to_cart', { currency, value, items });
10
+ *
11
+ * Code that emits an event never calls a provider SDK. Providers subscribe:
12
+ * the Google Analytics subscriber is registered below, once, as soon as this
13
+ * module loads; the host registers any other provider with `onStorefrontEvent`.
14
+ *
15
+ * The bus is synchronous. A subscriber that throws is isolated: the page and
16
+ * the other subscribers carry on. With no `window` (server render) an event is
17
+ * a no-op, so emitting is always safe.
18
+ *
19
+ * No customer field travels on the bus: product ids, names, prices, quantities,
20
+ * value, currency, the order number and `paid` only. That is enforced at runtime,
21
+ * not just in the types: every event is rebuilt from its known keys before any
22
+ * subscriber sees it, so an extra key on the payload or on an item (line text,
23
+ * an email, a phone) never reaches a subscriber or `dataLayer`.
24
+ *
25
+ * Register subscribers on the client (an effect, or client module load), never
26
+ * in a server render body: on the server `onStorefrontEvent` is a no-op.
27
+ */
28
+
29
+ export interface StorefrontEventItem {
30
+ item_id: string;
31
+ item_name: string;
32
+ /** The unit price actually charged, after discounts. Providers sum price * quantity as revenue. */
33
+ price: number;
34
+ quantity: number;
35
+ }
36
+
37
+ export interface StorefrontEventMap {
38
+ product_viewed: { currency: string; value: number; items: StorefrontEventItem[] };
39
+ /** Scrubbed by the bus before any subscriber sees it (see `scrubSearchTerm`). */
40
+ search_submitted: { search_term: string };
41
+ product_added_to_cart: { currency: string; value: number; items: StorefrontEventItem[] };
42
+ checkout_started: { currency: string; value: number; num_items: number; items: StorefrontEventItem[] };
43
+ checkout_completed: {
44
+ /** The human order number, never the order UUID. */
45
+ order_no: string;
46
+ currency: string;
47
+ /** The order's grand total (what the customer paid), tax and shipping included. */
48
+ value: number;
49
+ /** False for an order still awaiting online payment. */
50
+ paid: boolean;
51
+ items: StorefrontEventItem[];
52
+ /** Items after discounts, excluding tax and shipping. GA4 `purchase.value` uses it
53
+ * when finite, otherwise the sum of price * quantity of `items`. */
54
+ subtotal?: number;
55
+ /** Tax and shipping amounts of the order, when known. GA4 takes them as separate parameters. */
56
+ tax?: number;
57
+ shipping?: number;
58
+ };
59
+ }
60
+
61
+ export type StorefrontEventName = keyof StorefrontEventMap;
62
+
63
+ export type StorefrontEvent = {
64
+ [K in StorefrontEventName]: { name: K; data: StorefrontEventMap[K] };
65
+ }[StorefrontEventName];
66
+
67
+ /** A handler may be async; a rejection is caught and logged like a throw. */
68
+ export type StorefrontEventHandler = (event: StorefrontEvent) => void | Promise<unknown>;
69
+
70
+ const SEARCH_TERM_MAX_LENGTH = 100;
71
+ const SEARCH_TERM_MAX_DIGITS = 6;
72
+
73
+ /**
74
+ * Cleans a shopper's search text before it can reach any provider. Returns
75
+ * `null` when the event must be dropped entirely: empty, an `@` (or `%40`)
76
+ * anywhere (an email address), or 7 or more digits IN TOTAL anywhere in the
77
+ * text (a phone, card or order number; "in total" rather than "consecutive" is
78
+ * the stricter rule, so `0803 123 4567` and `08-03-12-34-567` are both dropped).
79
+ * The text is NFKC-normalised first, so full-width `@`, small `﹫`, superscript
80
+ * and circled digits count as what they look like. The checks run on the full
81
+ * trimmed text, then the result is capped at 100 characters.
82
+ */
83
+ export function scrubSearchTerm(raw: unknown): string | null {
84
+ if (typeof raw !== 'string') {
85
+ return null;
86
+ }
87
+
88
+ const trimmed = raw.normalize('NFKC').trim();
89
+
90
+ if (trimmed === '' || trimmed.includes('@') || /%40/i.test(trimmed)) {
91
+ return null;
92
+ }
93
+
94
+ if ((trimmed.match(/\p{N}/gu) ?? []).length > SEARCH_TERM_MAX_DIGITS) {
95
+ return null;
96
+ }
97
+
98
+ const capped = Array.from(trimmed).slice(0, SEARCH_TERM_MAX_LENGTH).join('').trim();
99
+
100
+ return capped === '' ? null : capped;
101
+ }
102
+
103
+ const handlers = new Set<StorefrontEventHandler>();
104
+
105
+ /**
106
+ * Subscribes to every storefront event. Returns the unsubscribe function.
107
+ * Without a `window` (server render) nothing is stored and the unsubscribe is a no-op.
108
+ */
109
+ export function onStorefrontEvent(handler: StorefrontEventHandler): () => void {
110
+ if (typeof window === 'undefined') {
111
+ return () => {};
112
+ }
113
+
114
+ handlers.add(handler);
115
+
116
+ return () => {
117
+ handlers.delete(handler);
118
+ };
119
+ }
120
+
121
+ function normalizeItems(items: unknown): StorefrontEventItem[] {
122
+ if (!Array.isArray(items)) {
123
+ return [];
124
+ }
125
+
126
+ return items.map((item: Partial<StorefrontEventItem> | null) => ({
127
+ item_id: String(item?.item_id ?? ''),
128
+ item_name: String(item?.item_name ?? ''),
129
+ price: Number(item?.price),
130
+ quantity: Number(item?.quantity),
131
+ }));
132
+ }
133
+
134
+ /** Rebuilds an event from its known keys only, so nothing extra reaches a subscriber. */
135
+ function normalizeEvent<K extends StorefrontEventName>(name: K, data: StorefrontEventMap[K]): StorefrontEvent | null {
136
+ const raw = (data ?? {}) as Record<string, unknown>;
137
+
138
+ switch (name) {
139
+ case 'search_submitted': {
140
+ const term = scrubSearchTerm(raw.search_term);
141
+
142
+ return term === null ? null : { name: 'search_submitted', data: { search_term: term } };
143
+ }
144
+ case 'product_viewed':
145
+ case 'product_added_to_cart':
146
+ return {
147
+ name,
148
+ data: {
149
+ currency: String(raw.currency ?? ''),
150
+ value: roundAmount(Number(raw.value)),
151
+ items: normalizeItems(raw.items),
152
+ },
153
+ } as StorefrontEvent;
154
+ case 'checkout_started':
155
+ return {
156
+ name: 'checkout_started',
157
+ data: {
158
+ currency: String(raw.currency ?? ''),
159
+ value: roundAmount(Number(raw.value)),
160
+ num_items: Number(raw.num_items),
161
+ items: normalizeItems(raw.items),
162
+ },
163
+ };
164
+ case 'checkout_completed': {
165
+ const extras = (key: 'subtotal' | 'tax' | 'shipping'): Partial<Record<typeof key, number>> =>
166
+ typeof raw[key] === 'number' ? { [key]: roundAmount(raw[key] as number) } : {};
167
+
168
+ return {
169
+ name: 'checkout_completed',
170
+ data: {
171
+ order_no: String(raw.order_no ?? ''),
172
+ currency: String(raw.currency ?? ''),
173
+ value: roundAmount(Number(raw.value)),
174
+ paid: raw.paid === true,
175
+ items: normalizeItems(raw.items),
176
+ ...extras('subtotal'),
177
+ ...extras('tax'),
178
+ ...extras('shipping'),
179
+ },
180
+ };
181
+ }
182
+ default:
183
+ return null;
184
+ }
185
+ }
186
+
187
+ function logSubscriberError(name: string, error: unknown): void {
188
+ if (process.env.NODE_ENV !== 'production') {
189
+ console.error('[storefront-events] a subscriber threw on', name, error);
190
+ }
191
+ }
192
+
193
+ export function trackStorefrontEvent<K extends StorefrontEventName>(name: K, data: StorefrontEventMap[K]): void {
194
+ if (typeof window === 'undefined') {
195
+ return;
196
+ }
197
+
198
+ const event = normalizeEvent(name, data);
199
+
200
+ if (event === null) {
201
+ return;
202
+ }
203
+
204
+ for (const handler of [...handlers]) {
205
+ try {
206
+ const result = handler(event);
207
+
208
+ if (result && typeof (result as Promise<unknown>).catch === 'function') {
209
+ (result as Promise<unknown>).catch((error: unknown) => logSubscriberError(name, error));
210
+ }
211
+ } catch (error) {
212
+ logSubscriberError(name, error);
213
+ }
214
+ }
215
+ }
216
+
217
+ const finite = (value: number): boolean => Number.isFinite(value);
218
+
219
+ /** `{ value }` when it is a real number, nothing otherwise: GA gets no `NaN`. */
220
+ const valueParam = (value: number): { value: number } | Record<string, never> => (finite(value) ? { value } : {});
221
+
222
+ /**
223
+ * Google Analytics 4. Not gated on consent here: Consent Mode (see
224
+ * analytics.tsx) decides whether gtag.js transmits anything for a denied
225
+ * visitor, so events are pushed unconditionally and Google's library filters.
226
+ *
227
+ * `purchase.value` follows Google's reference: the sum of price * quantity of
228
+ * the items (after discounts), excluding shipping and tax, which go in their own
229
+ * parameters. The event's `subtotal` is used when given; the payload `value`
230
+ * (grand total) is never sent to GA as the purchase value.
231
+ */
232
+ function googleAnalyticsSubscriber(event: StorefrontEvent): void {
233
+ switch (event.name) {
234
+ case 'product_viewed':
235
+ gtagPush('event', 'view_item', { currency: event.data.currency, ...valueParam(event.data.value), items: event.data.items });
236
+ return;
237
+ case 'search_submitted':
238
+ gtagPush('event', 'search', { search_term: event.data.search_term });
239
+ return;
240
+ case 'product_added_to_cart':
241
+ gtagPush('event', 'add_to_cart', { currency: event.data.currency, ...valueParam(event.data.value), items: event.data.items });
242
+ return;
243
+ case 'checkout_started':
244
+ gtagPush('event', 'begin_checkout', { currency: event.data.currency, ...valueParam(event.data.value), items: event.data.items });
245
+ return;
246
+ case 'checkout_completed': {
247
+ const { order_no, currency, items, subtotal, tax, shipping } = event.data;
248
+ const value =
249
+ typeof subtotal === 'number' && finite(subtotal)
250
+ ? subtotal
251
+ : roundAmount(items.reduce((sum, item) => sum + item.price * item.quantity, 0));
252
+
253
+ gtagPush('event', 'purchase', {
254
+ transaction_id: order_no,
255
+ ...valueParam(value),
256
+ currency,
257
+ ...(typeof tax === 'number' && finite(tax) ? { tax } : {}),
258
+ ...(typeof shipping === 'number' && finite(shipping) ? { shipping } : {}),
259
+ items,
260
+ });
261
+ }
262
+ }
263
+ }
264
+
265
+ let googleAnalyticsRegistered = false;
266
+
267
+ /** Idempotent; runs once at module load so GA is live whenever the bus is used. */
268
+ export function registerGoogleAnalyticsSubscriber(): void {
269
+ if (googleAnalyticsRegistered) {
270
+ return;
271
+ }
272
+
273
+ googleAnalyticsRegistered = true;
274
+ handlers.add(googleAnalyticsSubscriber);
275
+ }
276
+
277
+ registerGoogleAnalyticsSubscriber();
package/client.ts CHANGED
@@ -27,6 +27,7 @@ export * from './components/checkout/default-checkout-shell';
27
27
  export * from './components/checkout/checkout-contact';
28
28
  export * from './components/checkout/policy-links';
29
29
  export * from './apps/follow-card';
30
+ export * from './apps/storefront-events';
30
31
  export * from './apps/subscribe-form';
31
32
  export * from './api/collections';
32
33
  export * from './api/orders';
@@ -1,9 +1,11 @@
1
1
  import type { JSX } from 'react';
2
+ import type { Collection, Post } from '../types/page';
2
3
  import type {
3
4
  MetafieldScalar,
4
5
  MetafieldValue,
5
6
  MetaobjectEntry,
6
7
  Product,
8
+ ProductVariant,
7
9
  } from '../types/product';
8
10
  import { formatDisplayDate } from '../utils/format';
9
11
 
@@ -12,6 +14,9 @@ export interface ProductMetafieldDefinitionLabels {
12
14
  [key: string]: { name: string; type: string };
13
15
  }
14
16
 
17
+ /** What a custom-field section hangs off — the owner types the public API serves values for. */
18
+ export type MetafieldOwner = 'product' | 'variant' | 'collection' | 'post';
19
+
15
20
  /** Props for {@link ProductMetafields}. */
16
21
  export interface ProductMetafieldsProps {
17
22
  product: Product;
@@ -46,13 +51,25 @@ export function humaniseMetafieldKey(key: string): string {
46
51
  return words.charAt(0).toUpperCase() + words.slice(1);
47
52
  }
48
53
 
54
+ /**
55
+ * A definition is found under the value's own key (`custom.fabric`, how the API
56
+ * keys every presented value) or, for a bare-keyed map, under the part after
57
+ * the namespace (`fabric`).
58
+ */
59
+ function definitionFor(key: string, definitions?: ProductMetafieldDefinitionLabels): { name: string; type: string } | undefined {
60
+ if (!definitions) return undefined;
61
+ const dot = key.indexOf('.');
62
+
63
+ return definitions[key] ?? (dot > 0 ? definitions[key.slice(dot + 1)] : undefined);
64
+ }
65
+
49
66
  function labelFor(key: string, definitions?: ProductMetafieldDefinitionLabels): string {
50
- const name = definitions?.[key]?.name?.trim();
67
+ const name = definitionFor(key, definitions)?.name?.trim();
51
68
  return name && name !== '' ? name : humaniseMetafieldKey(key);
52
69
  }
53
70
 
54
71
  function typeFor(key: string, definitions?: ProductMetafieldDefinitionLabels): string {
55
- return definitions?.[key]?.type ?? '';
72
+ return definitionFor(key, definitions)?.type ?? '';
56
73
  }
57
74
 
58
75
  function isVisibleScalar(value: MetafieldScalar): boolean {
@@ -207,21 +224,45 @@ export function renderValue(value: MetafieldValue, fieldKey: string, label: stri
207
224
  return renderScalar(value as MetafieldScalar, fieldKey, label, type);
208
225
  }
209
226
 
227
+ const SECTION_LABELS: Record<MetafieldOwner, string> = {
228
+ product: 'Product details',
229
+ variant: 'Variant details',
230
+ collection: 'Collection details',
231
+ post: 'Post details',
232
+ };
233
+
234
+ /** Props for {@link Metafields}. */
235
+ export interface MetafieldsProps {
236
+ /** What the values belong to: sets the section's accessible name and, off the product, a `core-metafields--<owner>` class. */
237
+ owner: MetafieldOwner;
238
+ /** The owner's presented `metafields` (`product.metafields`, `collection.metafields`, …). */
239
+ metafields?: Record<string, MetafieldValue>;
240
+ /** The page's `metafieldDefinitions` (`variantMetafieldDefinitions` for variants) — labels and types. */
241
+ definitions?: ProductMetafieldDefinitionLabels;
242
+ }
243
+
210
244
  /**
211
- * Place this on the product page to show the product's custom fields.
212
- * Renders nothing when there are none to show.
245
+ * The one custom-fields section behind every owner. Renders the owner's
246
+ * presented values (all types, linked metaobject entries as cards) under their
247
+ * definition labels, and nothing when there is no visible value. Same
248
+ * `core-metafields*` markup for every owner, so a theme's existing styling
249
+ * covers collections, posts and variants too; off the product the root also
250
+ * carries `core-metafields--<owner>` for owner-specific rules.
213
251
  *
214
252
  * @example
215
- * <ProductMetafields product={product} definitions={metafieldDefinitions} />
253
+ * <Metafields owner="collection" metafields={collection.metafields} definitions={metafieldDefinitions} />
216
254
  */
217
- export function ProductMetafields({ product, definitions }: ProductMetafieldsProps): JSX.Element | null {
218
- const metafields = product.metafields && typeof product.metafields === 'object' ? product.metafields : {};
219
- const visible = Object.entries(metafields).filter(([, value]) => isVisibleValue(value as MetafieldValue));
255
+ export function Metafields({ owner, metafields, definitions }: MetafieldsProps): JSX.Element | null {
256
+ const values = metafields && typeof metafields === 'object' && !Array.isArray(metafields) ? metafields : {};
257
+ const visible = Object.entries(values).filter(([, value]) => isVisibleValue(value as MetafieldValue));
220
258
 
221
259
  if (visible.length === 0) return null;
222
260
 
223
261
  return (
224
- <section className="core-metafields" aria-label="Product details">
262
+ <section
263
+ className={owner === 'product' ? 'core-metafields' : `core-metafields core-metafields--${owner}`}
264
+ aria-label={SECTION_LABELS[owner]}
265
+ >
225
266
  {visible.map(([key, value]) => (
226
267
  <div className="core-metafields__field" key={key}>
227
268
  <h3 className="core-metafields__label">{labelFor(key, definitions)}</h3>
@@ -233,3 +274,45 @@ export function ProductMetafields({ product, definitions }: ProductMetafieldsPro
233
274
  </section>
234
275
  );
235
276
  }
277
+
278
+ /**
279
+ * Place this on the product page to show the product's custom fields.
280
+ * Renders nothing when there are none to show.
281
+ *
282
+ * @example
283
+ * <ProductMetafields product={product} definitions={metafieldDefinitions} />
284
+ */
285
+ export function ProductMetafields({ product, definitions }: ProductMetafieldsProps): JSX.Element | null {
286
+ return <Metafields owner="product" metafields={product.metafields} definitions={definitions} />;
287
+ }
288
+
289
+ /**
290
+ * Place this on the collection page to show the collection's custom fields.
291
+ *
292
+ * @example
293
+ * <CollectionMetafields collection={collection} definitions={metafieldDefinitions} />
294
+ */
295
+ export function CollectionMetafields({ collection, definitions }: { collection: Collection; definitions?: ProductMetafieldDefinitionLabels }): JSX.Element | null {
296
+ return <Metafields owner="collection" metafields={collection.metafields} definitions={definitions} />;
297
+ }
298
+
299
+ /**
300
+ * Place this on the blog post page to show the post's custom fields.
301
+ *
302
+ * @example
303
+ * <PostMetafields post={post} definitions={metafieldDefinitions} />
304
+ */
305
+ export function PostMetafields({ post, definitions }: { post: Post; definitions?: ProductMetafieldDefinitionLabels }): JSX.Element | null {
306
+ return <Metafields owner="post" metafields={post.metafields} definitions={definitions} />;
307
+ }
308
+
309
+ /**
310
+ * Show one variant's custom fields (the selected variant on the product page).
311
+ * `definitions` is the page's `variantMetafieldDefinitions`.
312
+ *
313
+ * @example
314
+ * <VariantMetafields variant={selectedVariant} definitions={variantMetafieldDefinitions} />
315
+ */
316
+ export function VariantMetafields({ variant, definitions }: { variant: Pick<ProductVariant, 'metafields'>; definitions?: ProductMetafieldDefinitionLabels }): JSX.Element | null {
317
+ return <Metafields owner="variant" metafields={variant.metafields} definitions={definitions} />;
318
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usequeek/theme-kit",
3
- "version": "0.1.27",
3
+ "version": "0.1.29",
4
4
  "private": false,
5
5
  "license": "MIT",
6
6
  "description": "The runtime a Queek storefront theme is built on: hooks, stores, page renderer, navigation, shared blocks and locale strings.",
@@ -70,7 +70,7 @@ const SSR_TIMEOUT_MS = 8_000;
70
70
  * safety net, not the primary mechanism — `POST /api/revalidate?tag=…` from the
71
71
  * API is what makes an edit show up immediately.
72
72
  */
73
- function resolveCachePolicy(vendorSlug: string, path: string): RequestCachePolicy | null {
73
+ function resolveCachePolicy(vendorSlug: string, path: string, query?: RequestOptions['query']): RequestCachePolicy | null {
74
74
  const vendor = `v:${vendorSlug}`;
75
75
  const policy = (revalidate: number, suffix: string, extra?: string): RequestCachePolicy => ({
76
76
  revalidate,
@@ -102,10 +102,17 @@ function resolveCachePolicy(vendorSlug: string, path: string): RequestCachePolic
102
102
  const product = /^\/products\/([^/]+)(?:\/related)?$/.exec(path);
103
103
  if (product) return policy(60, 'products', `product:${product[1]}`);
104
104
 
105
- // Product metafield definitions (the labels/types the core-owned
106
- // <ProductMetafields /> section renders values under). Merchant-edited,
107
- // shared across visitors — cached like pages, busted by revalidation.
108
- if (path === '/metafield-definitions') return policy(300, 'metafields');
105
+ // Metafield definitions (the labels/types the core-owned custom-field
106
+ // sections render values under), one owner type per read (`owner_type`,
107
+ // product when absent — its tags stay exactly as before). Merchant-edited,
108
+ // shared across visitors — cached like pages, busted by revalidation. A read
109
+ // that names its owner type also carries a per-owner tag, so entries for
110
+ // different owners are never one cache entry; the plain `metafields` tag
111
+ // still clears them all.
112
+ if (path === '/metafield-definitions') {
113
+ const owner = String(query?.owner_type ?? '');
114
+ return /^[a-z_]+$/.test(owner) ? policy(300, 'metafields', `metafields:${owner}`) : policy(300, 'metafields');
115
+ }
109
116
 
110
117
  // Metaobject definitions (storefront-visible types + their field labels)
111
118
  // and entry lists/detail reads for the `metaobjects` block and its entry
@@ -212,7 +219,7 @@ export function createServerStoreClient(vendorSlug: string, origin?: string): {
212
219
  timeoutMs: SSR_TIMEOUT_MS,
213
220
  cachePolicy: (await isPreviewRender())
214
221
  ? null
215
- : withLocaleCachePolicy(resolveCachePolicy(vendorSlug, path), code),
222
+ : withLocaleCachePolicy(resolveCachePolicy(vendorSlug, path, query), code),
216
223
  },
217
224
  buildHeaders(),
218
225
  );
@@ -5,8 +5,8 @@ import { createJSONStorage, persist } from 'zustand/middleware';
5
5
  import type { CartAddon, CartItem } from '../types/cart';
6
6
  import type { Product, ProductVariant } from '../types/product';
7
7
  import { toast } from './toast-store';
8
- import { normalizeCurrencyCode, PLATFORM_DEFAULT_CURRENCY } from '../utils/format';
9
- import { pushAddToCart } from '../apps/analytics-events';
8
+ import { normalizeCurrencyCode, PLATFORM_DEFAULT_CURRENCY, roundAmount } from '../utils/format';
9
+ import { trackStorefrontEvent } from '../apps/storefront-events';
10
10
  import { getActivePlatform, platformScopedStorage } from '../sdk/platform';
11
11
  import { productRequiresVariant } from '../utils/match-variant';
12
12
  import { readLineText } from './line-text-store';
@@ -154,10 +154,7 @@ export const useCartStore = create<CartState>()(
154
154
  showCart: true,
155
155
  });
156
156
  }
157
- pushAddToCart(
158
- { item_id: product.id, item_name: product.title, price: unitPrice, quantity: Math.max(1, quantity) },
159
- get().currency,
160
- );
157
+ const addedQuantity = Math.max(1, quantity);
161
158
 
162
159
  set((state) => {
163
160
  const existing = state.items.findIndex(
@@ -196,6 +193,12 @@ export const useCartStore = create<CartState>()(
196
193
  ],
197
194
  };
198
195
  });
196
+
197
+ trackStorefrontEvent('product_added_to_cart', {
198
+ currency: get().currency,
199
+ value: roundAmount(unitPrice * addedQuantity),
200
+ items: [{ item_id: product.id, item_name: product.title, price: unitPrice, quantity: addedQuantity }],
201
+ });
199
202
  },
200
203
  removeItem: (id, shopId) => {
201
204
  set((state) => ({
package/types/page.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { Block } from './block';
2
2
  import type { ImageVariants, MediaIndex } from './media';
3
- import type { Product } from './product';
3
+ import type { MetafieldValue, Product } from './product';
4
4
 
5
5
  export type PageType = 'page' | 'post' | 'gallery' | 'policy';
6
6
 
@@ -72,6 +72,10 @@ export interface Post extends Page {
72
72
  reading_time?: number | null;
73
73
  author?: PostAuthor | null;
74
74
  related?: Post[];
75
+ /** Presented post metafields keyed `namespace.key` — only storefront-visible
76
+ * definitions; `{}` when none. Absent on payloads that predate post custom
77
+ * fields. Render them with `<PostMetafields />`. */
78
+ metafields?: Record<string, MetafieldValue>;
75
79
  }
76
80
 
77
81
  export interface Collection {
@@ -85,4 +89,8 @@ export interface Collection {
85
89
  mode: string | null;
86
90
  products_count: number;
87
91
  products?: Product[];
92
+ /** Presented collection metafields keyed `namespace.key` — only
93
+ * storefront-visible definitions; `{}` when none. Absent on payloads that
94
+ * predate collection custom fields. Render them with `<CollectionMetafields />`. */
95
+ metafields?: Record<string, MetafieldValue>;
88
96
  }
package/types/product.ts CHANGED
@@ -122,6 +122,10 @@ export interface ProductVariant {
122
122
  weight: string | null;
123
123
  position: number | null;
124
124
  is_active: boolean;
125
+ /** Presented variant metafields keyed `namespace.key` — only the
126
+ * definitions the merchant marked storefront-visible. Absent on payloads
127
+ * that predate variant custom fields. */
128
+ metafields?: Record<string, MetafieldValue>;
125
129
  }
126
130
 
127
131
  export interface ProductAddonItem {
package/types/theme.ts CHANGED
@@ -27,6 +27,12 @@ export interface BlogPageProps {
27
27
 
28
28
  export interface PostPageProps {
29
29
  post: Post;
30
+ /**
31
+ * Post metafield definitions keyed `namespace.key` — the labels (and types)
32
+ * `<PostMetafields />` renders `post.metafields` under. OPTIONAL: themes
33
+ * that destructure `{ post }` keep compiling.
34
+ */
35
+ metafieldDefinitions?: Record<string, { name: string; type: string }>;
30
36
  }
31
37
 
32
38
  export interface CollectionsPageProps {
@@ -73,6 +79,12 @@ export interface CollectionPageProps {
73
79
  collection: Collection;
74
80
  products: Product[];
75
81
  pagination?: Pagination;
82
+ /**
83
+ * Collection metafield definitions keyed `namespace.key` — the labels (and
84
+ * types) `<CollectionMetafields />` renders `collection.metafields` under.
85
+ * OPTIONAL: themes that destructure `{ collection, products }` keep compiling.
86
+ */
87
+ metafieldDefinitions?: Record<string, { name: string; type: string }>;
76
88
  }
77
89
 
78
90
  export interface ProductPageProps {
@@ -84,6 +96,11 @@ export interface ProductPageProps {
84
96
  * compiling; unknown keys fall back to a humanised key label.
85
97
  */
86
98
  metafieldDefinitions?: Record<string, { name: string; type: string }>;
99
+ /**
100
+ * Variant metafield definitions keyed `namespace.key` — the labels (and
101
+ * types) `<VariantMetafields />` renders `variant.metafields` under. OPTIONAL.
102
+ */
103
+ variantMetafieldDefinitions?: Record<string, { name: string; type: string }>;
87
104
  }
88
105
 
89
106
  export interface GalleryPageProps {
package/types/vendor.ts CHANGED
@@ -225,7 +225,13 @@ export interface StorefrontConfig {
225
225
  }>;
226
226
  apps?: {
227
227
  whatsapp_chat?: { enabled?: boolean; number?: string; message?: string; position?: string; bottom_offset?: number };
228
- analytics?: { enabled?: boolean; ga_id?: string };
228
+ analytics?: {
229
+ enabled?: boolean;
230
+ ga_id?: string;
231
+ meta_pixel_id?: string;
232
+ tiktok_pixel_id?: string;
233
+ pinterest_tag_id?: string;
234
+ };
229
235
  follow_card?: { enabled?: boolean; display?: 'floating' | 'footer' | 'block'; position?: string };
230
236
  subscribe?: {
231
237
  enabled?: boolean;
package/utils/format.ts CHANGED
@@ -172,6 +172,15 @@ export function formatMoney(
172
172
  }
173
173
 
174
174
  /** A whole-number percentage string, e.g. `toPercent(12.4)` is `"12%"`. */
175
+ /**
176
+ * The one rounding for an amount the kit computes (event values, line totals):
177
+ * three decimals, enough for KWD/BHD/OMR, and it strips float noise such as
178
+ * 59.970000000000006. A non-finite input stays non-finite so callers can omit it.
179
+ */
180
+ export function roundAmount(amount: number): number {
181
+ return Number(amount.toFixed(3));
182
+ }
183
+
175
184
  export function toPercent(value: number): string {
176
185
  return `${Math.max(0, Math.round(value))}%`;
177
186
  }
@@ -199,18 +199,22 @@ function normalizeCategories(raw: LegacyProductLike): ProductCategory[] {
199
199
  }, []);
200
200
  }
201
201
 
202
- function normalizeMetafields(raw: LegacyProductLike): Record<string, MetafieldValue> {
203
- // Explicit whitelist like every other field above: without this the
204
- // presented metafields (incl. linked metaobject entries) are dropped at
205
- // runtime and <ProductMetafields /> renders nothing at every call site.
206
- const source = raw.metafields;
202
+ /** The presented `metafields` map of any owner, or null when the payload carries none. */
203
+ function presentedMetafields(source: unknown): Record<string, MetafieldValue> | null {
207
204
  if (!source || typeof source !== 'object' || Array.isArray(source)) {
208
- return {};
205
+ return null;
209
206
  }
210
207
 
211
208
  return source as Record<string, MetafieldValue>;
212
209
  }
213
210
 
211
+ function normalizeMetafields(raw: LegacyProductLike): Record<string, MetafieldValue> {
212
+ // Explicit whitelist like every other field above: without this the
213
+ // presented metafields (incl. linked metaobject entries) are dropped at
214
+ // runtime and <ProductMetafields /> renders nothing at every call site.
215
+ return presentedMetafields(raw.metafields) ?? {};
216
+ }
217
+
214
218
  function cleanUrl(value: unknown): string | null {
215
219
  return typeof value === 'string' && value !== '' ? value : null;
216
220
  }
@@ -322,7 +326,10 @@ export function normalizeProduct(raw: LegacyProductLike): Product {
322
326
  categories: normalizeCategories(raw),
323
327
  options: normalizeOptions(raw),
324
328
  variants: Array.isArray(raw.variants)
325
- ? raw.variants.map((variant, index) => ({
329
+ ? raw.variants.map((variant, index) => {
330
+ const variantMetafields = presentedMetafields(variant.metafields);
331
+
332
+ return {
326
333
  id: String(variant.id ?? `variant-${index}`),
327
334
  sku: variant.sku ?? null,
328
335
  barcode: typeof variant.barcode === 'string' && variant.barcode !== '' ? variant.barcode : null,
@@ -343,7 +350,11 @@ export function normalizeProduct(raw: LegacyProductLike): Product {
343
350
  weight: variant.weight ?? null,
344
351
  position: variant.position ?? index,
345
352
  is_active: toBool(variant.is_active, true),
346
- }))
353
+ // Same whitelist reason as the product's: a payload without the key
354
+ // keeps the variant's shape exactly as before.
355
+ ...(variantMetafields ? { metafields: variantMetafields } : {}),
356
+ };
357
+ })
347
358
  : [],
348
359
  addons: raw.addons ?? [],
349
360
  reviews: raw.reviews ?? [],
@@ -1,32 +0,0 @@
1
- 'use client';
2
-
3
- import { gtagPush } from './gtag';
4
-
5
- /**
6
- * Not gated on consent here — Consent Mode (see analytics.tsx) is what
7
- * decides whether gtag.js actually transmits anything for a denied visitor.
8
- * Callers push events unconditionally; Google's library filters them.
9
- */
10
- interface GaItem {
11
- item_id: string;
12
- item_name: string;
13
- price: number;
14
- quantity?: number;
15
- }
16
-
17
- export function pushViewItem(item: GaItem, currency: string): void {
18
- gtagPush('event', 'view_item', { currency, value: item.price, items: [item] });
19
- }
20
-
21
- export function pushAddToCart(item: GaItem, currency: string): void {
22
- gtagPush('event', 'add_to_cart', { currency, value: item.price * (item.quantity ?? 1), items: [item] });
23
- }
24
-
25
- export function pushPurchase(args: { transactionId: string; value: number; currency: string; items: GaItem[] }): void {
26
- gtagPush('event', 'purchase', {
27
- transaction_id: args.transactionId,
28
- value: args.value,
29
- currency: args.currency,
30
- items: args.items,
31
- });
32
- }