@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.
Files changed (210) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +125 -10
  3. package/dist/abi/canvas-live.d.ts +67 -0
  4. package/dist/abi/canvas-live.js +154 -0
  5. package/dist/abi/cart.d.ts +59 -0
  6. package/dist/abi/cart.js +387 -0
  7. package/dist/abi/convert.d.ts +344 -0
  8. package/dist/abi/convert.js +1278 -0
  9. package/dist/abi/data-api.d.ts +15 -0
  10. package/dist/abi/data-api.js +209 -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 +256 -0
  16. package/dist/abi/page-data.js +678 -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 +38 -0
  30. package/dist/abi/wire.js +84 -0
  31. package/dist/build.d.ts +116 -0
  32. package/dist/build.js +310 -0
  33. package/dist/client.d.ts +19 -0
  34. package/dist/client.js +87 -0
  35. package/dist/contract.d.ts +6 -0
  36. package/dist/contract.js +6 -0
  37. package/dist/headless/ai.d.ts +132 -0
  38. package/dist/headless/ai.js +99 -0
  39. package/dist/headless/hooks.d.ts +276 -0
  40. package/dist/headless/hooks.js +540 -0
  41. package/dist/headless/i18n.d.ts +13 -0
  42. package/dist/headless/i18n.js +45 -0
  43. package/dist/headless/index.d.ts +37 -0
  44. package/dist/headless/index.js +38 -0
  45. package/dist/headless/money.d.ts +25 -0
  46. package/dist/headless/money.js +61 -0
  47. package/dist/headless/page.d.ts +43 -0
  48. package/dist/headless/page.js +53 -0
  49. package/dist/headless/platform.d.ts +55 -0
  50. package/dist/headless/platform.js +77 -0
  51. package/dist/headless/primitives/cart.d.ts +90 -0
  52. package/dist/headless/primitives/cart.js +153 -0
  53. package/dist/headless/primitives/collection.d.ts +68 -0
  54. package/dist/headless/primitives/collection.js +80 -0
  55. package/dist/headless/primitives/product.d.ts +101 -0
  56. package/dist/headless/primitives/product.js +117 -0
  57. package/dist/headless/primitives/storefront.d.ts +106 -0
  58. package/dist/headless/primitives/storefront.js +186 -0
  59. package/dist/headless/primitives/util.d.ts +19 -0
  60. package/dist/headless/primitives/util.js +42 -0
  61. package/dist/headless/strings.d.ts +9 -0
  62. package/dist/headless/strings.js +190 -0
  63. package/dist/headless/structured-data.d.ts +31 -0
  64. package/dist/headless/structured-data.js +57 -0
  65. package/dist/headless/theme.d.ts +99 -0
  66. package/dist/headless/theme.js +54 -0
  67. package/dist/index.d.ts +20 -0
  68. package/dist/index.js +18 -553
  69. package/dist/runtime/data/StoreProvider.d.ts +84 -0
  70. package/dist/runtime/data/StoreProvider.js +373 -0
  71. package/dist/runtime/data/handle.d.ts +14 -0
  72. package/dist/runtime/data/handle.js +16 -0
  73. package/dist/runtime/data/routes.d.ts +87 -0
  74. package/dist/runtime/data/routes.js +158 -0
  75. package/dist/runtime/data/to-ui.d.ts +281 -0
  76. package/dist/runtime/data/to-ui.js +977 -0
  77. package/dist/runtime/entries/register.d.ts +9 -0
  78. package/dist/runtime/entries/register.js +9 -0
  79. package/dist/runtime/entries/sections.d.ts +16 -0
  80. package/dist/runtime/entries/sections.js +19 -0
  81. package/dist/{types → runtime/kit}/SectionTree.d.ts +2 -1
  82. package/dist/runtime/kit/SectionTree.js +100 -0
  83. package/dist/runtime/kit/analytics.d.ts +63 -0
  84. package/dist/runtime/kit/analytics.js +250 -0
  85. package/dist/runtime/kit/cart.d.ts +215 -0
  86. package/dist/runtime/kit/cart.js +545 -0
  87. package/dist/{types → runtime/kit}/composition.d.ts +1 -1
  88. package/dist/runtime/kit/composition.js +3 -0
  89. package/dist/{types → runtime/kit}/config.d.ts +2 -2
  90. package/dist/runtime/kit/config.js +6 -0
  91. package/dist/runtime/kit/consent.d.ts +29 -0
  92. package/dist/runtime/kit/consent.js +159 -0
  93. package/dist/runtime/kit/contract/content.d.ts +199 -0
  94. package/dist/runtime/kit/contract/content.js +106 -0
  95. package/dist/runtime/kit/contract/field-types.d.ts +337 -0
  96. package/dist/runtime/kit/contract/field-types.js +206 -0
  97. package/dist/runtime/kit/contract/groups.d.ts +230 -0
  98. package/dist/runtime/kit/contract/groups.js +402 -0
  99. package/dist/runtime/kit/contract/index.d.ts +33 -0
  100. package/dist/runtime/kit/contract/index.js +33 -0
  101. package/dist/runtime/kit/contract/transform.d.ts +82 -0
  102. package/dist/runtime/kit/contract/transform.js +133 -0
  103. package/dist/runtime/kit/contract/validate.d.ts +75 -0
  104. package/dist/runtime/kit/contract/validate.js +480 -0
  105. package/dist/runtime/kit/data.d.ts +720 -0
  106. package/dist/runtime/kit/data.js +1117 -0
  107. package/dist/{types → runtime/kit}/defineSection.d.ts +1 -1
  108. package/dist/runtime/kit/defineSection.js +10 -0
  109. package/dist/{types → runtime/kit}/dynamic-source.d.ts +40 -18
  110. package/dist/runtime/kit/dynamic-source.js +294 -0
  111. package/dist/runtime/kit/index.d.ts +24 -0
  112. package/dist/runtime/kit/index.js +24 -0
  113. package/dist/{types → runtime/kit}/jsx-to-json.d.ts +1 -1
  114. package/dist/runtime/kit/jsx-to-json.js +28 -0
  115. package/dist/{types → runtime/kit}/mount.d.ts +25 -4
  116. package/dist/runtime/kit/mount.js +124 -0
  117. package/dist/{types → runtime/kit}/registry.d.ts +1 -1
  118. package/dist/runtime/kit/registry.js +12 -0
  119. package/dist/{types → runtime/kit}/ssg.d.ts +9 -3
  120. package/dist/runtime/kit/ssg.js +56 -0
  121. package/dist/runtime/kit/storefront.d.ts +639 -0
  122. package/dist/runtime/kit/storefront.js +723 -0
  123. package/dist/{types → runtime/kit}/theme-context.d.ts +8 -2
  124. package/dist/runtime/kit/theme-context.js +25 -0
  125. package/dist/runtime/kit/types.d.ts +147 -0
  126. package/dist/runtime/kit/types.js +1 -0
  127. package/dist/runtime/platform/TrackingPixels.d.ts +14 -0
  128. package/dist/runtime/platform/TrackingPixels.js +63 -0
  129. package/dist/runtime/platform/environment.d.ts +68 -0
  130. package/dist/runtime/platform/environment.js +85 -0
  131. package/dist/runtime/platform/locale.d.ts +27 -0
  132. package/dist/runtime/platform/locale.js +42 -0
  133. package/dist/runtime/platform/route-analytics.d.ts +15 -0
  134. package/dist/runtime/platform/route-analytics.js +72 -0
  135. package/dist/runtime/platform/safe-href.d.ts +25 -0
  136. package/dist/runtime/platform/safe-href.js +69 -0
  137. package/dist/runtime/platform/safe-values.d.ts +37 -0
  138. package/dist/runtime/platform/safe-values.js +140 -0
  139. package/dist/runtime/render/SectionRenderer.d.ts +4 -0
  140. package/dist/runtime/render/SectionRenderer.js +166 -0
  141. package/dist/runtime/render/listing-query.d.ts +52 -0
  142. package/dist/runtime/render/listing-query.js +122 -0
  143. package/dist/runtime/render/localized-copy.d.ts +86 -0
  144. package/dist/runtime/render/localized-copy.js +129 -0
  145. package/dist/runtime/render/product-listing.d.ts +11 -0
  146. package/dist/runtime/render/product-listing.js +243 -0
  147. package/dist/runtime/render/section-actions.d.ts +66 -0
  148. package/dist/runtime/render/section-actions.js +202 -0
  149. package/dist/runtime/render/starter.d.ts +11 -0
  150. package/dist/runtime/render/starter.js +81 -0
  151. package/dist/runtime/seo/head.d.ts +115 -0
  152. package/dist/runtime/seo/head.js +281 -0
  153. package/dist/runtime/seo/structured-data.d.ts +83 -0
  154. package/dist/runtime/seo/structured-data.js +252 -0
  155. package/dist/runtime/shell/PageShell.d.ts +18 -0
  156. package/dist/runtime/shell/PageShell.js +113 -0
  157. package/dist/runtime/shell/RuntimeBridge.d.ts +14 -0
  158. package/dist/runtime/shell/RuntimeBridge.js +93 -0
  159. package/dist/runtime/shell/overlay-state.d.ts +31 -0
  160. package/dist/runtime/shell/overlay-state.js +59 -0
  161. package/dist/runtime/shell/preview-mode.d.ts +2 -0
  162. package/dist/runtime/shell/preview-mode.js +11 -0
  163. package/dist/runtime/shell/spa-router.d.ts +14 -0
  164. package/dist/runtime/shell/spa-router.js +76 -0
  165. package/dist/runtime/shell/url-redirects.d.ts +6 -0
  166. package/dist/runtime/shell/url-redirects.js +37 -0
  167. package/dist/runtime/slots.d.ts +74 -0
  168. package/dist/runtime/slots.js +16 -0
  169. package/dist/runtime.d.ts +34 -0
  170. package/dist/runtime.js +40 -0
  171. package/dist/sdk/app-block.d.ts +29 -0
  172. package/dist/sdk/app-block.js +22 -0
  173. package/dist/sdk/index.d.ts +26 -0
  174. package/dist/sdk/index.js +26 -0
  175. package/dist/sdk/referrals.d.ts +62 -0
  176. package/dist/sdk/referrals.js +20 -0
  177. package/dist/sdk/rewards.d.ts +85 -0
  178. package/dist/sdk/rewards.js +29 -0
  179. package/dist/sdk/runtime-context.d.ts +202 -0
  180. package/dist/sdk/runtime-context.js +73 -0
  181. package/dist/sdk/schema.d.ts +206 -0
  182. package/dist/sdk/schema.js +121 -0
  183. package/dist/sdk/server-render.d.ts +8 -0
  184. package/dist/sdk/server-render.js +12 -0
  185. package/dist/sdk/store-lookup.d.ts +27 -0
  186. package/dist/sdk/store-lookup.js +29 -0
  187. package/dist/sdk/store.d.ts +149 -0
  188. package/dist/sdk/store.js +5 -0
  189. package/dist/sdk/sx.d.ts +40 -0
  190. package/dist/sdk/sx.js +112 -0
  191. package/dist/sdk/theme.d.ts +191 -0
  192. package/dist/sdk/theme.js +10 -0
  193. package/dist/sdk/types.d.ts +757 -0
  194. package/dist/sdk/types.js +7 -0
  195. package/dist/server.d.ts +111 -0
  196. package/dist/server.js +533 -0
  197. package/docs/headless-api.md +220 -0
  198. package/package.json +76 -22
  199. package/dist/index.js.map +0 -1
  200. package/dist/ssg-BZ5FYTw7.js +0 -1802
  201. package/dist/ssg-BZ5FYTw7.js.map +0 -1
  202. package/dist/ssg.js +0 -8
  203. package/dist/ssg.js.map +0 -1
  204. package/dist/types/cart.d.ts +0 -86
  205. package/dist/types/data.d.ts +0 -357
  206. package/dist/types/editor.d.ts +0 -5
  207. package/dist/types/index.d.ts +0 -20
  208. package/dist/types/preview-bridge.d.ts +0 -9
  209. package/dist/types/storefront.d.ts +0 -333
  210. package/dist/types/types.d.ts +0 -44
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The v1 page shell in the glob-map shape `mount()` takes, plus `sectionModules()` (./sections.ts), re-exported
3
+ * here for the callers that import it from this module.
4
+ */
5
+ import PageShell from '../shell/PageShell.js';
6
+ export { sectionModules } from './sections.js';
7
+ export declare function shellModules(): Record<string, {
8
+ default: typeof PageShell;
9
+ }>;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The v1 page shell in the glob-map shape `mount()` takes, plus `sectionModules()` (./sections.ts), re-exported
3
+ * here for the callers that import it from this module.
4
+ */
5
+ import PageShell from '../shell/PageShell.js';
6
+ export { sectionModules } from './sections.js';
7
+ export function shellModules() {
8
+ return { './runtime/PageShell.tsx': { default: PageShell } };
9
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * What the runtime registers, in the glob-map shape `mount()` / `renderStorefrontHTML()` take
3
+ * (`{ path: { default } }`).
4
+ *
5
+ * Every theme section renders through SectionRenderer (`raw`: it receives the saved node). Custom
6
+ * `sections/*.tsx` (`defineSection` from the old API — the AI section generator writes them) register LAST,
7
+ * so one with the same name overrides the theme's section — which is also what studio-api's catalog does.
8
+ *
9
+ * Kept apart from `shellModules()` (./register.ts): the ABI entries (`createRender`, `hydrate`) need only the
10
+ * sections, and importing the v1 page shell put its router, the runtime barrel and `react-dom/server` into
11
+ * every theme's browser bundle.
12
+ */
13
+ import type { SectionDef } from '../kit/types.js';
14
+ export declare function sectionModules(): Record<string, {
15
+ default: SectionDef;
16
+ }>;
@@ -0,0 +1,19 @@
1
+ import { SectionRenderer } from '../render/SectionRenderer.js';
2
+ import { getThemeBundle } from '../slots.js';
3
+ export function sectionModules() {
4
+ const { theme, customSections } = getThemeBundle();
5
+ const own = theme.sections.map((s) => ({
6
+ name: s.id,
7
+ title: s.id,
8
+ category: s.category,
9
+ ...(s.zone !== 'main' ? { area: s.zone, role: 'layout' } : {}),
10
+ raw: true,
11
+ presets: (s.presets ?? []).map((p) => ({ name: p.name, settings: p.settings, blocks: (p.blocks ?? []).map((b) => ({ type: b.type, settings: b.settings ?? {} })) })),
12
+ component: SectionRenderer,
13
+ }));
14
+ const custom = Object.entries(customSections).filter(([, m]) => m.default?.name);
15
+ return {
16
+ ...Object.fromEntries(own.map((d) => [`./theme/${d.name}`, { default: d }])),
17
+ ...Object.fromEntries(custom),
18
+ };
19
+ }
@@ -1,4 +1,5 @@
1
- import type { ContentNode } from './types';
1
+ import type { ContentNode } from './types.js';
2
+ export declare function usePageTree(): ContentNode[] | null;
2
3
  /**
3
4
  * The heart: render a JSON content tree → React. The editor and the storefront
4
5
  * both render through this — content stays JSON, never HTML.
@@ -0,0 +1,100 @@
1
+ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { createContext, useContext } from 'react';
3
+ import { getSection } from './registry.js';
4
+ /** Apply attribute defaults from the section definition onto a node's settings. */
5
+ function resolveAttributes(def, settings) {
6
+ const out = { ...(settings ?? {}) };
7
+ for (const [key, spec] of Object.entries(def.attributes ?? {})) {
8
+ if (out[key] === undefined && spec.default !== undefined)
9
+ out[key] = spec.default;
10
+ }
11
+ return out;
12
+ }
13
+ /** Tolerate both child-block shapes. Templates written by older editor
14
+ * builds carry blocks as an OBJECT MAP keyed by id (the studio editor's
15
+ * internal shape) instead of theme-kit's array — `blocks.map` on that
16
+ * object crashed the ENTIRE storefront render ("o.map is not a function").
17
+ * A malformed template must degrade to "blocks don't render", never to a
18
+ * dead page. */
19
+ function normalizeBlocks(blocks, order) {
20
+ if (Array.isArray(blocks))
21
+ return blocks;
22
+ if (blocks && typeof blocks === 'object') {
23
+ // Build the node list + a lookup keyed by BOTH the map key and the block's
24
+ // own id — the editor's `order` array references the map key ("0".."n"),
25
+ // but be tolerant of templates that order by block id.
26
+ const nodes = [];
27
+ const byRef = new Map();
28
+ for (const [key, raw] of Object.entries(blocks)) {
29
+ if (!raw || typeof raw !== 'object' || typeof raw.type !== 'string')
30
+ continue;
31
+ const node = { ...raw, id: raw.id ?? key };
32
+ nodes.push(node);
33
+ byRef.set(key, node);
34
+ if (node.id)
35
+ byRef.set(node.id, node);
36
+ }
37
+ // The map's key order is NOT the merchant's arrangement — the editor stores
38
+ // the real order in `order`. Honour it (then append any stragglers).
39
+ if (Array.isArray(order) && order.length) {
40
+ const ordered = [];
41
+ const used = new Set();
42
+ for (const ref of order) {
43
+ const n = byRef.get(ref);
44
+ if (n && !used.has(n)) {
45
+ ordered.push(n);
46
+ used.add(n);
47
+ }
48
+ }
49
+ for (const n of nodes)
50
+ if (!used.has(n))
51
+ ordered.push(n);
52
+ return ordered;
53
+ }
54
+ return nodes;
55
+ }
56
+ return [];
57
+ }
58
+ function RenderNode({ node, path, }) {
59
+ const def = getSection(node.type);
60
+ if (!def) {
61
+ console.warn(`[tanqory] unknown section "${node.type}"`);
62
+ return null;
63
+ }
64
+ const Comp = def.component;
65
+ if (def.raw) {
66
+ // A raw section resolves its own settings and blocks; give it the node with
67
+ // the blocks normalised to an ordered array, and nothing pre-rendered.
68
+ const blocks = normalizeBlocks(node.blocks, node.order);
69
+ return (_jsx("div", { "data-tq-node": node.id, "data-tq-section-type": node.type, "data-tq-path": path, "data-tq-region": node.region, className: "tq-node", children: _jsx(Comp, { attributes: node.settings ?? {}, node: { ...node, blocks } }) }));
70
+ }
71
+ const attributes = resolveAttributes(def, node.settings);
72
+ // Wrap each rendered section in a CSS-transparent tag so the editor preview
73
+ // bridge can resolve clicks back to the JSON node (via data-tq-section-id /
74
+ // data-tq-path) without sections having to opt in. `display: contents`
75
+ // means the wrapper participates in layout as if it weren't there.
76
+ return (_jsx("div", { "data-tq-node": node.id, "data-tq-section-type": node.type, "data-tq-path": path, "data-tq-region": node.region, className: "tq-node", children: _jsx(Comp, { attributes: attributes, children: normalizeBlocks(node.blocks, node.order).map((child, i) => (_jsx(RenderNode, { node: child, path: `${path}.${i}` }, child.id ?? i))) }) }));
77
+ }
78
+ /** The page's resolved section list, for a section whose rendering depends on its neighbours (a header over a hero). */
79
+ const PageTreeContext = createContext(null);
80
+ export function usePageTree() {
81
+ return useContext(PageTreeContext);
82
+ }
83
+ /**
84
+ * The heart: render a JSON content tree → React. The editor and the storefront
85
+ * both render through this — content stays JSON, never HTML.
86
+ */
87
+ export function SectionTree({ tree }) {
88
+ const render = (node, i) => _jsx(RenderNode, { node: node, path: String(i) }, node.id ?? i);
89
+ // A page with chrome renders as header zone → <main> → footer zone, so the
90
+ // skip link has a target and the header and footer are not inside <main>. A
91
+ // tree with no chrome (one section in a preview) renders flat.
92
+ const areaOf = (node) => node.area ?? getSection(node.type)?.area;
93
+ if (!tree.some((n) => areaOf(n) === 'header' || areaOf(n) === 'footer'))
94
+ return _jsx(_Fragment, { children: tree.map(render) });
95
+ const indexed = tree.map((node, i) => ({ node, i }));
96
+ const head = indexed.filter(({ node }) => areaOf(node) === 'header');
97
+ const foot = indexed.filter(({ node }) => areaOf(node) === 'footer');
98
+ const body = indexed.filter(({ node }) => areaOf(node) !== 'header' && areaOf(node) !== 'footer');
99
+ return (_jsxs(PageTreeContext.Provider, { value: tree, children: [head.map(({ node, i }) => render(node, i)), _jsx("main", { id: "main", tabIndex: -1, children: body.map(({ node, i }) => render(node, i)) }), foot.map(({ node, i }) => render(node, i))] }));
100
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Storefront analytics — emit customer events to store-api's analytics pipeline
3
+ * so the merchant's dashboards (sessions, device type, reports, live view)
4
+ * populate. The batch is POSTed SAME-ORIGIN to `/api/v1/analytics/events/batch`
5
+ * (the edge worker forwards it to the store's cell — no CORS); the endpoint is
6
+ * public. Payload matches store-api's EventBatchSchema exactly:
7
+ * { storeId, sessionId, visitorId (all UUIDs), events[1..50], context }
8
+ *
9
+ * The theme creates ONE analytics instance for the real storefront (never in the
10
+ * editor/preview plane) and calls `pageViewed()` on each route + the product/
11
+ * cart/checkout emitters from the matching sections.
12
+ *
13
+ * CUSTOMER EVENTS (standard web-pixel): every `track()` also publishes to
14
+ * a client-side bus so the merchant's CONNECTED pixels (Settings → Customer
15
+ * events, injected by the theme's TrackingPixels) can react to live shopper
16
+ * actions. A pixel subscribes with `window.tqAnalytics.subscribe(name, cb)`.
17
+ * Bus delivery is gated on MARKETING consent (pixels are tracking); the internal
18
+ * telemetry POST is gated separately on ANALYTICS consent.
19
+ */
20
+ /** store-api SessionEventType values we emit from the storefront. */
21
+ export type StorefrontEventType = 'PAGE_VIEWED' | 'COLLECTION_VIEWED' | 'PRODUCT_VIEWED' | 'PRODUCT_ADDED_TO_CART' | 'PRODUCT_REMOVED_FROM_CART' | 'CART_VIEWED' | 'CHECKOUT_STARTED' | 'SEARCH_SUBMITTED';
22
+ /** The normalized event delivered to pixel subscribers on the client bus. */
23
+ export interface StorefrontEvent {
24
+ /** Unique per emission (UUID). */
25
+ id: string;
26
+ /** Lowercase contract name, e.g. `product_added_to_cart`. */
27
+ name: string;
28
+ /** The store-api SessionEventType. */
29
+ type: StorefrontEventType;
30
+ /** ISO-8601. */
31
+ timestamp: string;
32
+ /** Event-specific payload (product id, query, quantity…). */
33
+ data: Record<string, unknown>;
34
+ /** Session context (userAgent, referrer, utm, screen, locale, timezone). */
35
+ context: Record<string, unknown>;
36
+ }
37
+ export interface Analytics {
38
+ /** Queue an event; flushes automatically at batchSize / on page hide. */
39
+ track(type: StorefrontEventType, properties?: Record<string, unknown>): void;
40
+ /** Convenience for the current page. */
41
+ pageViewed(properties?: Record<string, unknown>): void;
42
+ /** Force-send the queued events now. */
43
+ flush(): void;
44
+ /** Subscribe to customer events (for pixels/apps). See `subscribe()`. */
45
+ subscribe(eventName: string, cb: (e: StorefrontEvent) => void): () => void;
46
+ }
47
+ export interface AnalyticsOptions {
48
+ storeId: string;
49
+ endpoint?: string;
50
+ batchSize?: number;
51
+ /** Optional consent gate — return false to drop events (GDPR). Defaults to on. */
52
+ consent?: () => boolean;
53
+ }
54
+ /**
55
+ * Subscribe a pixel (or app) to storefront customer events. Pass a contract
56
+ * name (`product_added_to_cart`, `checkout_started`, …) or `all_events` for
57
+ * every event. Recently-fired events replay immediately, so a pixel injected
58
+ * mid-session still receives them. Returns an unsubscribe fn.
59
+ */
60
+ export declare function subscribe(eventName: string, cb: (e: StorefrontEvent) => void): () => void;
61
+ /** The storefront's active analytics instance (or a no-op before creation). */
62
+ export declare function getAnalytics(): Analytics;
63
+ export declare function createAnalytics(opts: AnalyticsOptions): Analytics;
@@ -0,0 +1,250 @@
1
+ /**
2
+ * Storefront analytics — emit customer events to store-api's analytics pipeline
3
+ * so the merchant's dashboards (sessions, device type, reports, live view)
4
+ * populate. The batch is POSTed SAME-ORIGIN to `/api/v1/analytics/events/batch`
5
+ * (the edge worker forwards it to the store's cell — no CORS); the endpoint is
6
+ * public. Payload matches store-api's EventBatchSchema exactly:
7
+ * { storeId, sessionId, visitorId (all UUIDs), events[1..50], context }
8
+ *
9
+ * The theme creates ONE analytics instance for the real storefront (never in the
10
+ * editor/preview plane) and calls `pageViewed()` on each route + the product/
11
+ * cart/checkout emitters from the matching sections.
12
+ *
13
+ * CUSTOMER EVENTS (standard web-pixel): every `track()` also publishes to
14
+ * a client-side bus so the merchant's CONNECTED pixels (Settings → Customer
15
+ * events, injected by the theme's TrackingPixels) can react to live shopper
16
+ * actions. A pixel subscribes with `window.tqAnalytics.subscribe(name, cb)`.
17
+ * Bus delivery is gated on MARKETING consent (pixels are tracking); the internal
18
+ * telemetry POST is gated separately on ANALYTICS consent.
19
+ */
20
+ import { hasConsent } from './consent.js';
21
+ const VISITOR_KEY = 'tq-visitor-id';
22
+ const SESSION_KEY = 'tq-session';
23
+ const SESSION_TTL_MS = 30 * 60 * 1000;
24
+ const DEFAULT_ENDPOINT = '/api/v1/analytics/events/batch';
25
+ const NOOP = { track() { }, pageViewed() { }, flush() { }, subscribe: () => () => { } };
26
+ // ── Customer-event bus (standard web-pixel) ─────────────────────────────
27
+ // Module-scoped so the injected `window.tqAnalytics.subscribe` and the active
28
+ // analytics instance share one stream. Pixels load AFTER the first events fire,
29
+ // so a small buffer replays recent events to late subscribers.
30
+ const ALL_EVENTS = 'all_events';
31
+ const REPLAY_MAX = 50;
32
+ const busSubscribers = new Map();
33
+ const busReplay = [];
34
+ function busPublish(evt) {
35
+ // Pixels are marketing/tracking — deliver (and retain) only once the shopper
36
+ // allows it. Pre-consent events are never buffered (privacy-safe).
37
+ if (!hasConsent('marketing'))
38
+ return;
39
+ busReplay.push(evt);
40
+ if (busReplay.length > REPLAY_MAX)
41
+ busReplay.shift();
42
+ const fire = (set) => {
43
+ if (!set)
44
+ return;
45
+ for (const cb of set) {
46
+ try {
47
+ cb(evt);
48
+ }
49
+ catch {
50
+ /* one pixel throwing must never break the others or the page */
51
+ }
52
+ }
53
+ };
54
+ fire(busSubscribers.get(evt.name));
55
+ fire(busSubscribers.get(ALL_EVENTS));
56
+ }
57
+ /**
58
+ * Subscribe a pixel (or app) to storefront customer events. Pass a contract
59
+ * name (`product_added_to_cart`, `checkout_started`, …) or `all_events` for
60
+ * every event. Recently-fired events replay immediately, so a pixel injected
61
+ * mid-session still receives them. Returns an unsubscribe fn.
62
+ */
63
+ export function subscribe(eventName, cb) {
64
+ let set = busSubscribers.get(eventName);
65
+ if (!set) {
66
+ set = new Set();
67
+ busSubscribers.set(eventName, set);
68
+ }
69
+ set.add(cb);
70
+ for (const e of busReplay) {
71
+ if (eventName === ALL_EVENTS || e.name === eventName) {
72
+ try {
73
+ cb(e);
74
+ }
75
+ catch {
76
+ /* ignore */
77
+ }
78
+ }
79
+ }
80
+ return () => {
81
+ set?.delete(cb);
82
+ };
83
+ }
84
+ // The active instance, so any section can emit via getAnalytics() without the
85
+ // theme threading the instance through props/context.
86
+ let activeAnalytics = NOOP;
87
+ /** The storefront's active analytics instance (or a no-op before creation). */
88
+ export function getAnalytics() {
89
+ return activeAnalytics;
90
+ }
91
+ function uuid() {
92
+ const c = globalThis.crypto;
93
+ if (c?.randomUUID)
94
+ return c.randomUUID();
95
+ // RFC4122-ish fallback for the rare browser without crypto.randomUUID.
96
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (ch) => {
97
+ const r = (Math.random() * 16) | 0;
98
+ return (ch === 'x' ? r : (r & 0x3) | 0x8).toString(16);
99
+ });
100
+ }
101
+ function persistentId(key) {
102
+ try {
103
+ let v = localStorage.getItem(key);
104
+ if (!v) {
105
+ v = uuid();
106
+ localStorage.setItem(key, v);
107
+ }
108
+ return v;
109
+ }
110
+ catch {
111
+ return uuid();
112
+ }
113
+ }
114
+ /** Rolling 30-minute session id (the commerce standard/GA-style). Refreshed on each event. */
115
+ function sessionId() {
116
+ const now = Date.now();
117
+ try {
118
+ const raw = localStorage.getItem(SESSION_KEY);
119
+ if (raw) {
120
+ const s = JSON.parse(raw);
121
+ if (s.id && now - s.at < SESSION_TTL_MS) {
122
+ localStorage.setItem(SESSION_KEY, JSON.stringify({ id: s.id, at: now }));
123
+ return s.id;
124
+ }
125
+ }
126
+ const id = uuid();
127
+ localStorage.setItem(SESSION_KEY, JSON.stringify({ id, at: now }));
128
+ return id;
129
+ }
130
+ catch {
131
+ return uuid();
132
+ }
133
+ }
134
+ /** The token of the shopper's cart (cart.tsx keeps its id, `gid://…/Cart/<token>?key=<key>`, in 'tq-cart-id'). */
135
+ function cartTokenOf() {
136
+ try {
137
+ const id = localStorage.getItem('tq-cart-id') ?? '';
138
+ const token = /\/Cart\/([^/?#]+)/.exec(id)?.[1] ?? null;
139
+ return token && /^c1-[0-9a-f]{32}$/.test(token) ? token : null;
140
+ }
141
+ catch {
142
+ return null;
143
+ }
144
+ }
145
+ function buildContext() {
146
+ const params = new URLSearchParams(location.search);
147
+ const utm = {};
148
+ for (const [k, dest] of [
149
+ ['utm_source', 'source'],
150
+ ['utm_medium', 'medium'],
151
+ ['utm_campaign', 'campaign'],
152
+ ['utm_term', 'term'],
153
+ ['utm_content', 'content'],
154
+ ]) {
155
+ const v = params.get(k);
156
+ if (v)
157
+ utm[dest] = v;
158
+ }
159
+ return {
160
+ userAgent: navigator.userAgent,
161
+ referrer: document.referrer || '',
162
+ ...(Object.keys(utm).length ? { utm } : {}),
163
+ screen: { width: window.screen.width, height: window.screen.height },
164
+ locale: navigator.language,
165
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
166
+ // The shopper's marketing consent (consent.ts, GPC included): only a visit that allows it may start a product
167
+ // browse email (the platform's Messaging automations).
168
+ consent: { marketing: hasConsent('marketing') },
169
+ // The visit's cart, by its token only (never the cart's key): the cell ties the visit to the cart, and so to the
170
+ // customer the cart belongs to (a signed-in shopper's cart), which is how a product browse email knows who browsed.
171
+ ...(cartTokenOf() ? { cartToken: cartTokenOf() } : {}),
172
+ };
173
+ }
174
+ export function createAnalytics(opts) {
175
+ if (typeof window === 'undefined' || !opts.storeId)
176
+ return NOOP;
177
+ const endpoint = opts.endpoint ?? DEFAULT_ENDPOINT;
178
+ const batchSize = opts.batchSize ?? 10;
179
+ const consent = opts.consent ?? (() => true);
180
+ const queue = [];
181
+ const send = () => {
182
+ if (!queue.length || !consent()) {
183
+ queue.length = 0;
184
+ return;
185
+ }
186
+ const batch = {
187
+ storeId: opts.storeId,
188
+ sessionId: sessionId(),
189
+ visitorId: persistentId(VISITOR_KEY),
190
+ events: queue.splice(0, 50),
191
+ context: buildContext(),
192
+ };
193
+ const body = JSON.stringify(batch);
194
+ try {
195
+ if (navigator.sendBeacon) {
196
+ navigator.sendBeacon(endpoint, new Blob([body], { type: 'application/json' }));
197
+ }
198
+ else {
199
+ void fetch(endpoint, {
200
+ method: 'POST',
201
+ headers: { 'content-type': 'application/json' },
202
+ body,
203
+ keepalive: true,
204
+ }).catch(() => { });
205
+ }
206
+ }
207
+ catch {
208
+ /* best-effort telemetry — never throw into the storefront */
209
+ }
210
+ };
211
+ const track = (type, properties = {}) => {
212
+ // Publish to the pixel bus FIRST (its own marketing-consent gate), so
213
+ // marketing pixels still fire even when analytics telemetry is declined.
214
+ busPublish({
215
+ id: uuid(),
216
+ name: type.toLowerCase(),
217
+ type,
218
+ timestamp: new Date().toISOString(),
219
+ data: properties,
220
+ context: buildContext(),
221
+ });
222
+ // Internal telemetry POST — gated on analytics consent.
223
+ if (!consent())
224
+ return;
225
+ queue.push({
226
+ eventName: type.toLowerCase(),
227
+ eventType: type,
228
+ timestamp: new Date().toISOString(),
229
+ properties,
230
+ });
231
+ if (queue.length >= batchSize)
232
+ send();
233
+ };
234
+ window.addEventListener('visibilitychange', () => {
235
+ if (document.visibilityState === 'hidden')
236
+ send();
237
+ });
238
+ window.addEventListener('pagehide', send);
239
+ window.tqAnalytics ??= {
240
+ subscribe,
241
+ };
242
+ const api = {
243
+ track,
244
+ pageViewed: (properties = {}) => track('PAGE_VIEWED', { pageUrl: location.href, pageTitle: document.title, ...properties }),
245
+ flush: send,
246
+ subscribe,
247
+ };
248
+ activeAnalytics = api;
249
+ return api;
250
+ }