@replohq/sdk 1.2.3 → 1.3.1

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.
@@ -1,5 +1,7 @@
1
1
  import { isConsentAllowed } from "../consent/consent-store";
2
+ import { snippetScriptId } from "../consent/script-registration-store";
2
3
  import { ConvergeSink } from "./sinks/converge-sink";
4
+ import { ElevarSink } from "./sinks/elevar-sink";
3
5
  import { GA4Sink } from "./sinks/ga4-sink";
4
6
  import { MetaSink } from "./sinks/meta-sink";
5
7
  import { NorthbeamSink } from "./sinks/northbeam-sink";
@@ -20,6 +22,15 @@ const PROVIDER_SINK_FACTORIES = {
20
22
  Northbeam: () => new NorthbeamSink(),
21
23
  Converge: () => new ConvergeSink()
22
24
  };
25
+ const SNIPPET_PROVIDER_SINK_FACTORIES = {
26
+ [snippetScriptId("Elevar")]: () => new ElevarSink()
27
+ };
28
+ function findSinkFactory(script) {
29
+ if (script.type === "snippet") {
30
+ return SNIPPET_PROVIDER_SINK_FACTORIES[script.id] ?? null;
31
+ }
32
+ return PROVIDER_SINK_FACTORIES[script.type] ?? null;
33
+ }
23
34
  function getAnalyticsSinks({
24
35
  consent,
25
36
  registeredScripts,
@@ -34,10 +45,11 @@ function getAnalyticsSinks({
34
45
  sinks.push(new ReploSink());
35
46
  }
36
47
  const shopifyOwnsCheckout = checkoutProvider === "shopify";
37
- const addedTypes = /* @__PURE__ */ new Set();
48
+ const addedProviders = /* @__PURE__ */ new Set();
38
49
  for (const script of registeredScripts) {
39
- const factory = PROVIDER_SINK_FACTORIES[script.type];
40
- if (!factory || addedTypes.has(script.type)) {
50
+ const providerKey = script.type === "snippet" ? script.id : script.type;
51
+ const factory = findSinkFactory(script);
52
+ if (!factory || addedProviders.has(providerKey)) {
41
53
  continue;
42
54
  }
43
55
  if (isConsentAllowed({
@@ -48,7 +60,7 @@ function getAnalyticsSinks({
48
60
  sinks.push(
49
61
  shopifyOwnsCheckout ? gateShopifyOwnedFunnelEvents(sink) : sink
50
62
  );
51
- addedTypes.add(script.type);
63
+ addedProviders.add(providerKey);
52
64
  }
53
65
  }
54
66
  return sinks;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../analytics/get-analytics-sinks.ts"],
4
- "sourcesContent": ["import type { ReploScriptType } from \"schemas/generated/consent\";\nimport type { ConsentState } from \"../consent/consent-store\";\nimport type { RegisteredScript } from \"../consent/script-registration-store\";\nimport type { CheckoutProvider } from \"../lib/integration-utils\";\nimport type { AnalyticsSink } from \"./analytics-sink\";\n\nimport { isConsentAllowed } from \"../consent/consent-store\";\nimport { ConvergeSink } from \"./sinks/converge-sink\";\nimport { GA4Sink } from \"./sinks/ga4-sink\";\nimport { MetaSink } from \"./sinks/meta-sink\";\nimport { NorthbeamSink } from \"./sinks/northbeam-sink\";\nimport { PinterestSink } from \"./sinks/pinterest-sink\";\nimport { RedditSink } from \"./sinks/reddit-sink\";\nimport { ReploSink } from \"./sinks/replo-sink\";\nimport { SnapchatSink } from \"./sinks/snapchat-sink\";\nimport { TikTokSink } from \"./sinks/tiktok-sink\";\nimport { WindowSink } from \"./sinks/window-sink\";\nimport { gateShopifyOwnedFunnelEvents } from \"./utils/shopify-funnel-gate\";\n\n/**\n * Named providers that have a corresponding ecommerce-event sink. The other\n * managed providers (GoogleTagManager, Hotjar, MicrosoftClarity, Segment,\n * Gorgias) and generic `snippet`/`custom` entries load scripts but do not map\n * to `AnalyticsSink` events today, so they never produce a sink here.\n */\nconst PROVIDER_SINK_FACTORIES: Partial<\n Record<ReploScriptType, () => AnalyticsSink>\n> = {\n GA4: () => new GA4Sink(),\n Meta: () => new MetaSink(),\n TikTok: () => new TikTokSink(),\n Snapchat: () => new SnapchatSink(),\n Pinterest: () => new PinterestSink(),\n Reddit: () => new RedditSink(),\n Northbeam: () => new NorthbeamSink(),\n Converge: () => new ConvergeSink(),\n};\n\n/**\n * Builds the set of analytics sinks that may fire given the current consent\n * state and which managed scripts are registered on the page.\n *\n * Consent gates data egress, not in-page plumbing:\n * - `WindowSink` is a local `CustomEvent` bus (no data leaves the device), so it\n * always ships regardless of consent. Its consumers self-gate: managed pixels\n * are already gated at the injection layer (they never mount without consent,\n * so they never subscribe), and unmanaged custom scripts are the author's\n * responsibility.\n * - `ReploSink` forwards into Replo's first-party analytics pipeline (real\n * egress / processing), so it counts as `analytics`-category tracking and is\n * gated by that consent. It is an implicit sink this scaffold always ships\n * (not tied to a registered entry) and is never editable in the miniapp.\n * Under a delegated platform, `analytics` reflects that platform's answer.\n *\n * Third-party provider sinks are created only when a matching `<ReploScripts>`\n * entry is registered AND its required consent is granted.\n */\nexport function getAnalyticsSinks({\n consent,\n registeredScripts,\n checkoutProvider,\n}: {\n consent: ConsentState;\n registeredScripts: RegisteredScript[];\n checkoutProvider?: CheckoutProvider;\n}): AnalyticsSink[] {\n const sinks: AnalyticsSink[] = [new WindowSink()];\n\n const firstPartyAllowed = isConsentAllowed({\n state: consent,\n requiredConsent: [\"analytics\"],\n });\n if (firstPartyAllowed) {\n sinks.push(new ReploSink());\n }\n\n // When Shopify hosts checkout, its native channels report the checkout-funnel\n // events to ad platforms server-side. Suppress those events on third-party\n // storefront pixels so they don't double-count Shopify's copy.\n const shopifyOwnsCheckout = checkoutProvider === \"shopify\";\n\n const addedTypes = new Set<ReploScriptType>();\n for (const script of registeredScripts) {\n const factory = PROVIDER_SINK_FACTORIES[script.type];\n if (!factory || addedTypes.has(script.type)) {\n continue;\n }\n if (\n isConsentAllowed({\n state: consent,\n requiredConsent: script.requiredConsent,\n })\n ) {\n const sink = factory();\n sinks.push(\n shopifyOwnsCheckout ? gateShopifyOwnedFunnelEvents(sink) : sink,\n );\n addedTypes.add(script.type);\n }\n }\n\n return sinks;\n}\n"],
5
- "mappings": "AAMA,SAAS,wBAAwB;AACjC,SAAS,oBAAoB;AAC7B,SAAS,eAAe;AACxB,SAAS,gBAAgB;AACzB,SAAS,qBAAqB;AAC9B,SAAS,qBAAqB;AAC9B,SA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"../consent/consent-store\";\nimport type { RegisteredScript } from \"../consent/script-registration-store\";\nimport type { CheckoutProvider } from \"../lib/integration-utils\";\nimport type { AnalyticsSink } from \"./analytics-sink\";\n\nimport { isConsentAllowed } from \"../consent/consent-store\";\nimport { snippetScriptId } from \"../consent/script-registration-store\";\nimport { ConvergeSink } from \"./sinks/converge-sink\";\nimport { ElevarSink } from \"./sinks/elevar-sink\";\nimport { GA4Sink } from \"./sinks/ga4-sink\";\nimport { MetaSink } from \"./sinks/meta-sink\";\nimport { NorthbeamSink } from \"./sinks/northbeam-sink\";\nimport { PinterestSink } from \"./sinks/pinterest-sink\";\nimport { RedditSink } from \"./sinks/reddit-sink\";\nimport { ReploSink } from \"./sinks/replo-sink\";\nimport { SnapchatSink } from \"./sinks/snapchat-sink\";\nimport { TikTokSink } from \"./sinks/tiktok-sink\";\nimport { WindowSink } from \"./sinks/window-sink\";\nimport { gateShopifyOwnedFunnelEvents } from \"./utils/shopify-funnel-gate\";\n\n/**\n * Named providers that have a corresponding ecommerce-event sink. The other\n * managed providers (GoogleTagManager, Hotjar, MicrosoftClarity, Segment,\n * Gorgias) and `custom` entries load scripts but do not map to\n * `AnalyticsSink` events today, so they never produce a sink here.\n */\nconst PROVIDER_SINK_FACTORIES: Partial<\n Record<ReploScriptType, () => AnalyticsSink>\n> = {\n GA4: () => new GA4Sink(),\n Meta: () => new MetaSink(),\n TikTok: () => new TikTokSink(),\n Snapchat: () => new SnapchatSink(),\n Pinterest: () => new PinterestSink(),\n Reddit: () => new RedditSink(),\n Northbeam: () => new NorthbeamSink(),\n Converge: () => new ConvergeSink(),\n};\n\n/**\n * Snippet providers share the `snippet` type, so their sinks key on the\n * registration id instead. Elevar's pasted snippet only forwards what the page\n * pushes to its data layer, and this sink is what pushes it.\n */\nconst SNIPPET_PROVIDER_SINK_FACTORIES: Record<string, () => AnalyticsSink> = {\n [snippetScriptId(\"Elevar\")]: () => new ElevarSink(),\n};\n\nfunction findSinkFactory(script: RegisteredScript) {\n if (script.type === \"snippet\") {\n return SNIPPET_PROVIDER_SINK_FACTORIES[script.id] ?? null;\n }\n return PROVIDER_SINK_FACTORIES[script.type] ?? null;\n}\n\n/**\n * Builds the set of analytics sinks that may fire given the current consent\n * state and which managed scripts are registered on the page.\n *\n * Consent gates data egress, not in-page plumbing:\n * - `WindowSink` is a local `CustomEvent` bus (no data leaves the device), so it\n * always ships regardless of consent. Its consumers self-gate: managed pixels\n * are already gated at the injection layer (they never mount without consent,\n * so they never subscribe), and unmanaged custom scripts are the author's\n * responsibility.\n * - `ReploSink` forwards into Replo's first-party analytics pipeline (real\n * egress / processing), so it counts as `analytics`-category tracking and is\n * gated by that consent. It is an implicit sink this scaffold always ships\n * (not tied to a registered entry) and is never editable in the miniapp.\n * Under a delegated platform, `analytics` reflects that platform's answer.\n *\n * Third-party provider sinks are created only when a matching `<ReploScripts>`\n * entry is registered AND its required consent is granted.\n */\nexport function getAnalyticsSinks({\n consent,\n registeredScripts,\n checkoutProvider,\n}: {\n consent: ConsentState;\n registeredScripts: RegisteredScript[];\n checkoutProvider?: CheckoutProvider;\n}): AnalyticsSink[] {\n const sinks: AnalyticsSink[] = [new WindowSink()];\n\n const firstPartyAllowed = isConsentAllowed({\n state: consent,\n requiredConsent: [\"analytics\"],\n });\n if (firstPartyAllowed) {\n sinks.push(new ReploSink());\n }\n\n // When Shopify hosts checkout, its native channels report the checkout-funnel\n // events to ad platforms server-side. Suppress those events on third-party\n // storefront pixels so they don't double-count Shopify's copy.\n const shopifyOwnsCheckout = checkoutProvider === \"shopify\";\n\n // One sink per provider: typed providers dedupe on type, snippet providers\n // on their registration id.\n const addedProviders = new Set<string>();\n for (const script of registeredScripts) {\n const providerKey = script.type === \"snippet\" ? script.id : script.type;\n const factory = findSinkFactory(script);\n if (!factory || addedProviders.has(providerKey)) {\n continue;\n }\n if (\n isConsentAllowed({\n state: consent,\n requiredConsent: script.requiredConsent,\n })\n ) {\n const sink = factory();\n sinks.push(\n shopifyOwnsCheckout ? gate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,QAAM,sBAAsB,qBAAqB;AAIjD,QAAM,iBAAiB,oBAAI,IAAY;AACvC,aAAW,UAAU,mBAAmB;AACtC,UAAM,cAAc,OAAO,SAAS,YAAY,OAAO,KAAK,OAAO;AACnE,UAAM,UAAU,gBAAgB,MAAM;AACtC,QAAI,CAAC,WAAW,eAAe,IAAI,WAAW,GAAG;AAC/C;AAAA,IACF;AACA,QACE,iBAAiB;AAAA,MACf,OAAO;AAAA,MACP,iBAAiB,OAAO;AAAA,IAC1B,CAAC,GACD;AACA,YAAM,OAAO,QAAQ;AACrB,YAAM;AAAA,QACJ,sBAAsB,6BAA6B,IAAI,IAAI;AAAA,MAC7D;AACA,qBAAe,IAAI,WAAW;AAAA,IAChC;AAAA,EACF;AAEA,SAAO;AACT;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,38 @@
1
+ import type { AnalyticsSink, DataPayload } from "../analytics-sink";
2
+ import type { PageMetadata } from "../utils/navigation-tracker";
3
+ type ElevarUserProperties = {
4
+ visitor_type: "guest" | "logged_in";
5
+ };
6
+ type ElevarDataLayerEvent = {
7
+ event: string;
8
+ user_properties: ElevarUserProperties;
9
+ cart_total?: string;
10
+ ecommerce: Record<string, unknown>;
11
+ };
12
+ declare global {
13
+ interface Window {
14
+ ElevarDataLayer?: ElevarDataLayerEvent[];
15
+ ElevarInvalidateContext?: () => void;
16
+ }
17
+ }
18
+ /**
19
+ * Pushes Elevar's `dl_*` data layer events for a storefront whose Elevar
20
+ * headless snippet is installed as a `snippet` script entry. The snippet only
21
+ * forwards what the page pushes to `window.ElevarDataLayer`, and a Replo page
22
+ * (unlike a Shopify theme) pushes nothing on its own.
23
+ */
24
+ export declare class ElevarSink implements AnalyticsSink {
25
+ constructor();
26
+ private pushEcommerceEvent;
27
+ private pushProductEvent;
28
+ pageView(metadata?: PageMetadata): Promise<void>;
29
+ purchase(): Promise<void>;
30
+ click(): Promise<void>;
31
+ productViewed(payload: DataPayload): Promise<void>;
32
+ addToCart(payload: DataPayload): Promise<void>;
33
+ removeFromCart(payload: DataPayload): Promise<void>;
34
+ viewCart({ data }: DataPayload): Promise<void>;
35
+ startCheckout({ data }: DataPayload): Promise<void>;
36
+ viewCollection({ data }: DataPayload): Promise<void>;
37
+ }
38
+ export {};
@@ -0,0 +1,260 @@
1
+ import { z } from "zod";
2
+ const GUEST_USER_PROPERTIES = { visitor_type: "guest" };
3
+ const FALLBACK_CURRENCY_CODE = "USD";
4
+ const nonEmptyStringSchema = z.union([z.string().min(1), z.number().finite().transform(String)]).optional().catch(void 0);
5
+ const finiteNumberSchema = z.union([
6
+ z.number().finite(),
7
+ z.string().trim().min(1).transform(Number).pipe(z.number().finite())
8
+ ]).optional().catch(void 0);
9
+ const analyticsProductSchema = z.object({
10
+ productId: nonEmptyStringSchema,
11
+ productTitle: nonEmptyStringSchema,
12
+ variantId: nonEmptyStringSchema,
13
+ variantTitle: nonEmptyStringSchema,
14
+ variantSku: nonEmptyStringSchema,
15
+ price: finiteNumberSchema,
16
+ currency: nonEmptyStringSchema,
17
+ quantity: finiteNumberSchema
18
+ });
19
+ const checkoutLineSchema = z.object({
20
+ quantity: finiteNumberSchema,
21
+ merchandise: z.object({
22
+ id: nonEmptyStringSchema,
23
+ title: nonEmptyStringSchema,
24
+ sku: nonEmptyStringSchema,
25
+ price: z.object({
26
+ amount: finiteNumberSchema,
27
+ currencyCode: nonEmptyStringSchema
28
+ }).optional(),
29
+ product: z.object({ id: nonEmptyStringSchema, title: nonEmptyStringSchema }).optional()
30
+ }).optional()
31
+ });
32
+ const productListSchema = z.array(z.unknown()).optional().catch(void 0);
33
+ const cartPayloadSchema = z.object({
34
+ currency: nonEmptyStringSchema,
35
+ currencyCode: nonEmptyStringSchema,
36
+ subtotal: finiteNumberSchema,
37
+ totalPrice: z.object({ amount: finiteNumberSchema }).optional(),
38
+ lineItems: productListSchema
39
+ });
40
+ const collectionPayloadSchema = z.object({
41
+ currency: nonEmptyStringSchema,
42
+ currencyCode: nonEmptyStringSchema,
43
+ products: productListSchema
44
+ });
45
+ function formatMoney(amount) {
46
+ return amount.toFixed(2);
47
+ }
48
+ function legacyResourceId(id) {
49
+ return id.replace(/^gid:\/\/shopify\/\w+\//, "");
50
+ }
51
+ function parseCheckoutLine(line) {
52
+ const parsed = checkoutLineSchema.safeParse(line);
53
+ if (!parsed.success || !parsed.data.merchandise) {
54
+ return null;
55
+ }
56
+ const { merchandise, quantity } = parsed.data;
57
+ return {
58
+ productId: merchandise.product?.id,
59
+ productTitle: merchandise.product?.title,
60
+ variantId: merchandise.id,
61
+ variantTitle: merchandise.title,
62
+ variantSku: merchandise.sku,
63
+ price: merchandise.price?.amount,
64
+ currency: merchandise.price?.currencyCode,
65
+ quantity
66
+ };
67
+ }
68
+ function parseAnalyticsProduct(value) {
69
+ const parsed = analyticsProductSchema.safeParse(value);
70
+ if (!parsed.success) {
71
+ return null;
72
+ }
73
+ return parsed.data.productId ? parsed.data : parseCheckoutLine(value);
74
+ }
75
+ function toElevarProduct(product, options) {
76
+ const productId = product.productId;
77
+ if (!productId) {
78
+ return null;
79
+ }
80
+ const variantId = product.variantId ?? productId;
81
+ return {
82
+ id: product.variantSku ?? legacyResourceId(variantId),
83
+ name: product.productTitle ?? "",
84
+ brand: "",
85
+ category: "",
86
+ variant: product.variantTitle ?? "",
87
+ price: formatMoney(product.price ?? 0),
88
+ ...options.withQuantity ? { quantity: String(product.quantity ?? 1) } : {},
89
+ ...options.position === void 0 ? {} : { position: String(options.position) },
90
+ list: options.list,
91
+ product_id: legacyResourceId(productId),
92
+ variant_id: legacyResourceId(variantId),
93
+ compare_at_price: "0.0",
94
+ image: ""
95
+ };
96
+ }
97
+ function toElevarProducts(products, options) {
98
+ const parsedProducts = products.map(parseAnalyticsProduct).filter((product) => product !== null);
99
+ const currencyCode = options.currency ?? parsedProducts.find((product) => product.currency)?.currency ?? FALLBACK_CURRENCY_CODE;
100
+ const elevarProducts = parsedProducts.map((product, index) => {
101
+ return toElevarProduct(product, { ...options, position: index + 1 });
102
+ }).filter((product) => product !== null);
103
+ return { products: elevarProducts, currencyCode };
104
+ }
105
+ function pushToElevarDataLayer(event) {
106
+ if (typeof window === "undefined") {
107
+ return;
108
+ }
109
+ window.ElevarDataLayer = window.ElevarDataLayer ?? [];
110
+ window.ElevarDataLayer.push(event);
111
+ }
112
+ let lastUserDataUrl = null;
113
+ function pushUserData() {
114
+ lastUserDataUrl = window.location.href;
115
+ pushToElevarDataLayer({
116
+ event: "dl_user_data",
117
+ cart_total: formatMoney(0),
118
+ user_properties: GUEST_USER_PROPERTIES,
119
+ ecommerce: {
120
+ currencyCode: FALLBACK_CURRENCY_CODE,
121
+ cart_contents: { products: [] }
122
+ }
123
+ });
124
+ }
125
+ function ensureUserDataForCurrentPage() {
126
+ if (typeof window === "undefined" || lastUserDataUrl === window.location.href) {
127
+ return;
128
+ }
129
+ pushUserData();
130
+ }
131
+ class ElevarSink {
132
+ constructor() {
133
+ ensureUserDataForCurrentPage();
134
+ }
135
+ pushEcommerceEvent(event, ecommerce, cartTotal) {
136
+ ensureUserDataForCurrentPage();
137
+ pushToElevarDataLayer({
138
+ event,
139
+ user_properties: GUEST_USER_PROPERTIES,
140
+ ...cartTotal === void 0 ? {} : { cart_total: cartTotal },
141
+ ecommerce
142
+ });
143
+ }
144
+ pushProductEvent(event, action, { data }, options) {
145
+ const product = parseAnalyticsProduct(data);
146
+ const elevarProduct = product && toElevarProduct(product, {
147
+ list: "",
148
+ withQuantity: options.withQuantity
149
+ });
150
+ if (!elevarProduct) {
151
+ console.warn(`[analytics] skipped Elevar ${event}: no product id`);
152
+ return;
153
+ }
154
+ if (options.withUrl) {
155
+ elevarProduct.url = window.location.href;
156
+ }
157
+ this.pushEcommerceEvent(event, {
158
+ currencyCode: product.currency ?? FALLBACK_CURRENCY_CODE,
159
+ [action]: {
160
+ actionField: action === "detail" ? { list: window.location.pathname, action } : { list: window.location.pathname },
161
+ products: [elevarProduct]
162
+ }
163
+ });
164
+ }
165
+ async pageView(metadata) {
166
+ if (typeof window === "undefined") {
167
+ return;
168
+ }
169
+ if (metadata?.navigationType === "soft" && lastUserDataUrl !== window.location.href) {
170
+ window.ElevarInvalidateContext?.();
171
+ }
172
+ ensureUserDataForCurrentPage();
173
+ }
174
+ async purchase() {
175
+ }
176
+ async click() {
177
+ }
178
+ async productViewed(payload) {
179
+ this.pushProductEvent("dl_view_item", "detail", payload, {
180
+ withQuantity: false
181
+ });
182
+ }
183
+ async addToCart(payload) {
184
+ this.pushProductEvent("dl_add_to_cart", "add", payload, {
185
+ withQuantity: true,
186
+ withUrl: true
187
+ });
188
+ }
189
+ async removeFromCart(payload) {
190
+ this.pushProductEvent("dl_remove_from_cart", "remove", payload, {
191
+ withQuantity: true
192
+ });
193
+ }
194
+ async viewCart({ data }) {
195
+ const cart = cartPayloadSchema.safeParse(data);
196
+ if (!cart.success) {
197
+ return;
198
+ }
199
+ const { products, currencyCode } = toElevarProducts(
200
+ cart.data.lineItems ?? [],
201
+ {
202
+ list: "",
203
+ withQuantity: true,
204
+ currency: cart.data.currency ?? cart.data.currencyCode
205
+ }
206
+ );
207
+ this.pushEcommerceEvent(
208
+ "dl_view_cart",
209
+ {
210
+ currencyCode,
211
+ actionField: { list: "Shopping Cart" },
212
+ impressions: products
213
+ },
214
+ formatMoney(cart.data.subtotal ?? cart.data.totalPrice?.amount ?? 0)
215
+ );
216
+ }
217
+ async startCheckout({ data }) {
218
+ const cart = cartPayloadSchema.safeParse(data);
219
+ if (!cart.success) {
220
+ return;
221
+ }
222
+ const { products, currencyCode } = toElevarProducts(
223
+ cart.data.lineItems ?? [],
224
+ {
225
+ list: "",
226
+ withQuantity: true,
227
+ currency: cart.data.currencyCode ?? cart.data.currency
228
+ }
229
+ );
230
+ this.pushEcommerceEvent("dl_begin_checkout", {
231
+ currencyCode,
232
+ checkout: {
233
+ actionField: { step: "1", action: "checkout" },
234
+ products
235
+ }
236
+ });
237
+ }
238
+ async viewCollection({ data }) {
239
+ const collection = collectionPayloadSchema.safeParse(data);
240
+ if (!collection.success) {
241
+ return;
242
+ }
243
+ const { products, currencyCode } = toElevarProducts(
244
+ collection.data.products ?? [],
245
+ {
246
+ list: window.location.pathname,
247
+ withQuantity: false,
248
+ currency: collection.data.currency ?? collection.data.currencyCode
249
+ }
250
+ );
251
+ this.pushEcommerceEvent("dl_view_item_list", {
252
+ currencyCode,
253
+ impressions: products
254
+ });
255
+ }
256
+ }
257
+ export {
258
+ ElevarSink
259
+ };
260
+ //# sourceMappingURL=elevar-sink.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../analytics/sinks/elevar-sink.ts"],
4
+ "sourcesContent": ["import type { AnalyticsSink, DataPayload } from \"../analytics-sink\";\nimport type { PageMetadata } from \"../utils/navigation-tracker\";\n\nimport { z } from \"zod\";\n\n/**\n * Elevar's data layer contract for headless storefronts:\n * https://docs.getelevar.com/docs/headless-implementing-the-data-layer\n * Every value is a string, `dl_user_data` must precede every other event on a\n * page, and events are only processed when pushed to `window.ElevarDataLayer`.\n */\ntype ElevarProduct = {\n id: string;\n name: string;\n brand: string;\n category: string;\n variant: string;\n price: string;\n quantity?: string;\n position?: string;\n list: string;\n product_id: string;\n variant_id: string;\n compare_at_price: string;\n image: string;\n url?: string;\n};\n\ntype ElevarUserProperties = { visitor_type: \"guest\" | \"logged_in\" };\n\ntype ElevarDataLayerEvent = {\n event: string;\n user_properties: ElevarUserProperties;\n cart_total?: string;\n ecommerce: Record<string, unknown>;\n};\n\ndeclare global {\n interface Window {\n ElevarDataLayer?: ElevarDataLayerEvent[];\n ElevarInvalidateContext?: () => void;\n }\n}\n\n// The storefront has no customer identity to hand Elevar; logged-in customer\n// fields come from the merchant's Shopify source on Elevar's side.\nconst GUEST_USER_PROPERTIES: ElevarUserProperties = { visitor_type: \"guest\" };\n\n// Matches the cart provider's own fallback when a cart has no currency yet.\nconst FALLBACK_CURRENCY_CODE = \"USD\";\n\nconst nonEmptyStringSchema = z\n .union([z.string().min(1), z.number().finite().transform(String)])\n .optional()\n .catch(undefined);\nconst finiteNumberSchema = z\n .union([\n z.number().finite(),\n z.string().trim().min(1).transform(Number).pipe(z.number().finite()),\n ])\n .optional()\n .catch(undefined);\n\n/** The flat product fields the SDK's cart provider and product-view hook emit. */\nconst analyticsProductSchema = z.object({\n productId: nonEmptyStringSchema,\n productTitle: nonEmptyStringSchema,\n variantId: nonEmptyStringSchema,\n variantTitle: nonEmptyStringSchema,\n variantSku: nonEmptyStringSchema,\n price: finiteNumberSchema,\n currency: nonEmptyStringSchema,\n quantity: finiteNumberSchema,\n});\n\n/** The nested line shape the starter site's checkout button emits. */\nconst checkoutLineSchema = z.object({\n quantity: finiteNumberSchema,\n merchandise: z\n .object({\n id: nonEmptyStringSchema,\n title: nonEmptyStringSchema,\n sku: nonEmptyStringSchema,\n price: z\n .object({\n amount: finiteNumberSchema,\n currencyCode: nonEmptyStringSchema,\n })\n .optional(),\n product: z\n .object({ id: nonEmptyStringSchema, title: nonEmptyStringSchema })\n .optional(),\n })\n .optional(),\n});\n\nconst productListSchema = z.array(z.unknown()).optional().catch(undefined);\n\nconst cartPayloadSchema = z.object({\n currency: nonEmptyStringSchema,\n currencyCode: nonEmptyStringSchema,\n subtotal: finiteNumberSchema,\n totalPrice: z.object({ amount: finiteNumberSchema }).optional(),\n lineItems: productListSchema,\n});\n\nconst collectionPayloadSchema = z.object({\n currency: nonEmptyStringSchema,\n currencyCode: nonEmptyStringSchema,\n products: productListSchema,\n});\n\ntype AnalyticsProduct = z.infer<typeof analyticsProductSchema>;\n\nfunction formatMoney(amount: number) {\n return amount.toFixed(2);\n}\n\n// Elevar's Shopify destinations key on legacy numeric ids, while the cart\n// carries Storefront API GIDs (`gid://shopify/ProductVariant/123`).\nfunction legacyResourceId(id: string) {\n return id.replace(/^gid:\\/\\/shopify\\/\\w+\\//, \"\");\n}\n\nfunction parseCheckoutLine(line: unknown): AnalyticsProduct | null {\n const parsed = checkoutLineSchema.safeParse(line);\n if (!parsed.success || !parsed.data.merchandise) {\n return null;\n }\n const { merchandise, quantity } = parsed.data;\n return {\n productId: merchandise.product?.id,\n productTitle: merchandise.product?.title,\n variantId: merchandise.id,\n variantTitle: merchandise.title,\n variantSku: merchandise.sku,\n price: merchandise.price?.amount,\n currency: merchandise.price?.currencyCode,\n quantity,\n };\n}\n\nfunction parseAnalyticsProduct(value: unknown): AnalyticsProduct | null {\n const parsed = analyticsProductSchema.safeParse(value);\n if (!parsed.success) {\n return null;\n }\n return parsed.data.productId ? parsed.data : parseCheckoutLine(value);\n}\n\n/**\n * Brand, category, compare-at price, image, and the originating collection\n * path are not part of Replo's analytics payloads today, so they carry the\n * empty-value fallbacks Elevar's spec prescribes.\n */\nfunction toElevarProduct(\n product: AnalyticsProduct,\n options: { list: string; withQuantity: boolean; position?: number },\n): ElevarProduct | null {\n const productId = product.productId;\n if (!productId) {\n return null;\n }\n const variantId = product.variantId ?? productId;\n return {\n id: product.variantSku ?? legacyResourceId(variantId),\n name: product.productTitle ?? \"\",\n brand: \"\",\n category: \"\",\n variant: product.variantTitle ?? \"\",\n price: formatMoney(product.price ?? 0),\n ...(options.withQuantity\n ? { quantity: String(product.quantity ?? 1) }\n : {}),\n ...(options.position === undefined\n ? {}\n : { position: String(options.position) }),\n list: options.list,\n product_id: legacyResourceId(productId),\n variant_id: legacyResourceId(variantId),\n compare_at_price: \"0.0\",\n image: \"\",\n };\n}\n\nfunction toElevarProducts(\n products: unknown[],\n options: { list: string; withQuantity: boolean; currency?: string },\n): { products: ElevarProduct[]; currencyCode: string } {\n const parsedProducts = products\n .map(parseAnalyticsProduct)\n .filter((product): product is AnalyticsProduct => product !== null);\n const currencyCode =\n options.currency ??\n parsedProducts.find((product) => product.currency)?.currency ??\n FALLBACK_CURRENCY_CODE;\n const elevarProducts = parsedProducts\n .map((product, index) => {\n return toElevarProduct(product, { ...options, position: index + 1 });\n })\n .filter((product): product is ElevarProduct => product !== null);\n return { products: elevarProducts, currencyCode };\n}\n\nfunction pushToElevarDataLayer(event: ElevarDataLayerEvent) {\n if (typeof window === \"undefined\") {\n return;\n }\n window.ElevarDataLayer = window.ElevarDataLayer ?? [];\n window.ElevarDataLayer.push(event);\n}\n\n// Sinks are rebuilt whenever consent or script registration changes, so the\n// \"already announced this page\" marker lives outside the instance; otherwise\n// every rebuild would push a second `dl_user_data` for the same page.\nlet lastUserDataUrl: string | null = null;\n\nfunction pushUserData() {\n lastUserDataUrl = window.location.href;\n // Cart contents live in the cart provider's React state, which the sink\n // cannot read, so the base event reports an empty cart. Cart totals reach\n // Elevar on `dl_view_cart` instead.\n pushToElevarDataLayer({\n event: \"dl_user_data\",\n cart_total: formatMoney(0),\n user_properties: GUEST_USER_PROPERTIES,\n ecommerce: {\n currencyCode: FALLBACK_CURRENCY_CODE,\n cart_contents: { products: [] },\n },\n });\n}\n\nfunction ensureUserDataForCurrentPage() {\n if (\n typeof window === \"undefined\" ||\n lastUserDataUrl === window.location.href\n ) {\n return;\n }\n pushUserData();\n}\n\n/**\n * Pushes Elevar's `dl_*` data layer events for a storefront whose Elevar\n * headless snippet is installed as a `snippet` script entry. The snippet only\n * forwards what the page pushes to `window.ElevarDataLayer`, and a Replo page\n * (unlike a Shopify theme) pushes nothing on its own.\n */\nexport class ElevarSink implements AnalyticsSink {\n constructor() {\n // The snippet registers after the initial pageview has already been\n // broadcast, so the sink announces the page it was created on itself.\n ensureUserDataForCurrentPage();\n }\n\n private pushEcommerceEvent(\n event: string,\n ecommerce: Record<string, unknown>,\n cartTotal?: string,\n ) {\n ensureUserDataForCurrentPage();\n pushToElevarDataLayer({\n event,\n user_properties: GUEST_USER_PROPERTIES,\n ...(cartTotal === undefined ? {} : { cart_total: cartTotal }),\n ecommerce,\n });\n }\n\n private pushProductEvent(\n event: string,\n action: \"detail\" | \"add\" | \"remove\",\n { data }: DataPayload,\n options: { withQuantity: boolean; withUrl?: boolean },\n ) {\n const product = parseAnalyticsProduct(data);\n const elevarProduct =\n product &&\n toElevarProduct(product, {\n list: \"\",\n withQuantity: options.withQuantity,\n });\n if (!elevarProduct) {\n console.warn(`[analytics] skipped Elevar ${event}: no product id`);\n return;\n }\n if (options.withUrl) {\n // The add-to-cart payload has no product URL; the page the shopper added\n // from is the closest available stand-in.\n elevarProduct.url = window.location.href;\n }\n this.pushEcommerceEvent(event, {\n currencyCode: product.currency ?? FALLBACK_CURRENCY_CODE,\n [action]: {\n actionField:\n action === \"detail\"\n ? { list: window.location.pathname, action }\n : { list: window.location.pathname },\n products: [elevarProduct],\n },\n });\n }\n\n async pageView(metadata?: PageMetadata) {\n if (typeof window === \"undefined\") {\n return;\n }\n // A repeated pageView for the current URL must not invalidate Elevar's\n // context and re-announce the page.\n if (\n metadata?.navigationType === \"soft\" &&\n lastUserDataUrl !== window.location.href\n ) {\n window.ElevarInvalidateContext?.();\n }\n ensureUserDataForCurrentPage();\n }\n\n async purchase() {\n // Orders complete on Shopify-hosted checkout, where the merchant's Elevar\n // Shopify source reports dl_purchase; a storefront copy would double count.\n }\n\n async click() {\n // Replo's click event carries no product, so there is no dl_select_item to build.\n }\n\n async productViewed(payload: DataPayload) {\n this.pushProductEvent(\"dl_view_item\", \"detail\", payload, {\n withQuantity: false,\n });\n }\n\n async addToCart(payload: DataPayload) {\n this.pushProductEvent(\"dl_add_to_cart\", \"add\", payload, {\n withQuantity: true,\n withUrl: true,\n });\n }\n\n async removeFromCart(payload: DataPayload) {\n this.pushProductEvent(\"dl_remove_from_cart\", \"remove\", payload, {\n withQuantity: true,\n });\n }\n\n async viewCart({ data }: DataPayload) {\n const cart = cartPayloadSchema.safeParse(data);\n if (!cart.success) {\n return;\n }\n const { products, currencyCode } = toElevarProducts(\n cart.data.lineItems ?? [],\n {\n list: \"\",\n withQuantity: true,\n currency: cart.data.currency ?? cart.data.currencyCode,\n },\n );\n this.pushEcommerceEvent(\n \"dl_view_cart\",\n {\n currencyCode,\n actionField: { list: \"Shopping Cart\" },\n impressions: products,\n },\n formatMoney(cart.data.subtotal ?? cart.data.totalPrice?.amount ?? 0),\n );\n }\n\n async startCheckout({ data }: DataPayload) {\n const cart = cartPayloadSchema.safeParse(data);\n if (!cart.success) {\n return;\n }\n const { products, currencyCode } = toElevarProducts(\n cart.data.lineItems ?? [],\n {\n list: \"\",\n withQuantity: true,\n currency: cart.data.currencyCode ?? cart.data.currency,\n },\n );\n this.pushEcommerceEvent(\"dl_begin_checkout\", {\n currencyCode,\n checkout: {\n actionField: { step: \"1\", action: \"checkout\" },\n products,\n },\n });\n }\n\n async viewCollection({ data }: DataPayload) {\n const collection = collectionPayloadSchema.safeParse(data);\n if (!collection.success) {\n return;\n }\n const { products, currencyCode } = toElevarProducts(\n collection.data.products ?? [],\n {\n list: window.location.pathname,\n withQuantity: false,\n currency: collection.data.currency ?? collection.data.currencyCode,\n },\n );\n this.pushEcommerceEvent(\"dl_view_item_list\", {\n currencyCode,\n impressions: products,\n });\n }\n}\n"],
5
+ "mappings": "AAGA,SAAS,SAAS;AA2ClB,MAAM,wBAA8C,EAAE,cAAc,QAAQ;AAG5E,MAAM,yBAAyB;AAE/B,MAAM,uBAAuB,EAC1B,MAAM,CAAC,EAAE,OAAO,EAAE,IAAI,CAAC,GAAG,EAAE,OAAO,EAAE,OAAO,EAAE,UAAU,MAAM,CAAC,CAAC,EAChE,SAAS,EACT,MAAM,MAAS;AAClB,MAAM,qBAAqB,EACxB,MAAM;AAAA,EACL,EAAE,OAAO,EAAE,OAAO;AAAA,EAClB,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,EAAE,UAAU,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC;AACrE,CAAC,EACA,SAAS,EACT,MAAM,MAAS;AAGlB,MAAM,yBAAyB,EAAE,OAAO;AAAA,EACtC,WAAW;AAAA,EACX,cAAc;AAAA,EACd,WAAW;AAAA,EACX,cAAc;AAAA,EACd,YAAY;AAAA,EACZ,OAAO;AAAA,EACP,UAAU;AAAA,EACV,UAAU;AACZ,CAAC;AAGD,MAAM,qBAAqB,EAAE,OAAO;AAA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Y,KAAK,KAAK,YAAY,UAAU,CAAC;AAAA,IACrE;AAAA,EACF;AAAA,EAEA,MAAM,cAAc,EAAE,KAAK,GAAgB;AACzC,UAAM,OAAO,kBAAkB,UAAU,IAAI;AAC7C,QAAI,CAAC,KAAK,SAAS;AACjB;AAAA,IACF;AACA,UAAM,EAAE,UAAU,aAAa,IAAI;AAAA,MACjC,KAAK,KAAK,aAAa,CAAC;AAAA,MACxB;AAAA,QACE,MAAM;AAAA,QACN,cAAc;AAAA,QACd,UAAU,KAAK,KAAK,gBAAgB,KAAK,KAAK;AAAA,MAChD;AAAA,IACF;AACA,SAAK,mBAAmB,qBAAqB;AAAA,MAC3C;AAAA,MACA,UAAU;AAAA,QACR,aAAa,EAAE,MAAM,KAAK,QAAQ,WAAW;AAAA,QAC7C;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AAAA,EAEA,MAAM,eAAe,EAAE,KAAK,GAAgB;AAC1C,UAAM,aAAa,wBAAwB,UAAU,IAAI;AACzD,QAAI,CAAC,WAAW,SAAS;AACvB;AAAA,IACF;AACA,UAAM,EAAE,UAAU,aAAa,IAAI;AAAA,MACjC,WAAW,KAAK,YAAY,CAAC;AAAA,MAC7B;AAAA,QACE,MAAM,OAAO,SAAS;AAAA,QACtB,cAAc;AAAA,QACd,UAAU,WAAW,KAAK,YAAY,WAAW,KAAK;AAAA,MACxD;AAAA,IACF;AACA,SAAK,mBAAmB,qBAAqB;AAAA,MAC3C;AAAA,MACA,aAAa;AAAA,IACf,CAAC;AAAA,EACH;AACF;",
6
+ "names": []
7
+ }
@@ -13,7 +13,11 @@ import {
13
13
  } from "./consent-platform";
14
14
  import { isConsentAllowed, useConsent } from "./consent-store";
15
15
  import { injectScriptDescriptors } from "./inject-script-descriptors";
16
- import { registerScript, unregisterScript } from "./script-registration-store";
16
+ import {
17
+ registerScript,
18
+ snippetScriptId,
19
+ unregisterScript
20
+ } from "./script-registration-store";
17
21
  import { buildScriptTags, defaultConsentFor } from "./script-snippets";
18
22
  import { installConsentWindowApi } from "./window-api";
19
23
  function scriptId(entry) {
@@ -21,7 +25,7 @@ function scriptId(entry) {
21
25
  return `custom:${entry.id}`;
22
26
  }
23
27
  if (entry.type === "snippet") {
24
- return `snippet:${entry.id}`;
28
+ return snippetScriptId(entry.id);
25
29
  }
26
30
  if (entry.type === "consentPlatform") {
27
31
  return `consent-platform:${entry.id}`;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../consent/replo-scripts.tsx"],
4
- "sourcesContent": ["\"use client\";\n\nimport type {\n ConsentCategory,\n ReploScriptEntry,\n ScriptTagDescriptor,\n} from \"schemas/generated/consent\";\nimport type { RegisteredScript } from \"./script-registration-store\";\n\nimport { Component } from \"react\";\n\nimport {\n activateBlockedScripts,\n buildGrantMarker,\n enableConsentDelegation,\n findConsentPlatform,\n findDelegatedPlatform,\n getBlockingAttributes,\n isConsentPlatformEntry,\n OPTIONAL_CONSENT_CATEGORIES,\n} from \"./consent-platform\";\nimport { isConsentAllowed, useConsent } from \"./consent-store\";\nimport { injectScriptDescriptors } from \"./inject-script-descriptors\";\nimport { registerScript, unregisterScript } from \"./script-registration-store\";\nimport { buildScriptTags, defaultConsentFor } from \"./script-snippets\";\nimport { installConsentWindowApi } from \"./window-api\";\n\n/**\n * Stable identity for an entry, used as React key and DOM dedupe key. `snippet`\n * and `custom` entries key on their `id`; identifier providers on type+id.\n */\nfunction scriptId(entry: ReploScriptEntry): string {\n if (entry.type === \"custom\") {\n return `custom:${entry.id}`;\n }\n if (entry.type === \"snippet\") {\n return `snippet:${entry.id}`;\n }\n if (entry.type === \"consentPlatform\") {\n return `consent-platform:${entry.id}`;\n }\n return `${entry.type}:${entry.identifier}`;\n}\n\nfunction requiredConsentFor(entry: ReploScriptEntry): ConsentCategory[] {\n if (entry.type === \"custom\" || entry.type === \"snippet\") {\n return entry.requiredConsent;\n }\n // Platform entries are filtered out before render; arms exist for the types.\n if (entry.type === \"consentPlatform\" || entry.type === \"Cookiebot\") {\n return [];\n }\n return entry.requiredConsent ?? defaultConsentFor(entry.type);\n}\n\n/**\n * Resolves an entry to the concrete tags to inject. An identifier provider may\n * resolve to multiple tags (GA4 = external loader + inline config); a `snippet`\n * entry injects its pasted body inline; a `custom` entry is a single external\n * `src` or inline `body`.\n */\nfunction descriptorsFor(entry: ReploScriptEntry): ScriptTagDescriptor[] {\n if (entry.type === \"custom\") {\n if (entry.src) {\n return [{ kind: \"external\", src: entry.src }];\n }\n if (entry.body) {\n return [{ kind: \"inline\", body: entry.body }];\n }\n return [];\n }\n if (entry.type === \"snippet\") {\n return [{ kind: \"inline\", body: entry.body, module: entry.module }];\n }\n // Platform entries load from their platform config rather than per-entry.\n if (entry.type === \"consentPlatform\" || entry.type === \"Cookiebot\") {\n return [];\n }\n return buildScriptTags({ type: entry.type, identifier: entry.identifier });\n}\n\n/**\n * Injects the resolved tags into `document.head` once a caller has decided\n * consent allows it. Reused both for author-managed `ReploScripts` entries and\n * for the implicit Replo first-party pixel.\n *\n * DOM insertion (not JSX) is required because inline `<script>` bodies set via\n * React's `dangerouslySetInnerHTML` never execute. Each node is tagged with\n * `data-replo-script-id` (plus a per-tag index) so re-renders and React Strict\n * Mode double-invokes do not double-inject.\n */\ntype InjectedScriptProps = {\n baseId: string;\n descriptors: ScriptTagDescriptor[];\n /** Used under a delegated platform to derive the attributes that gate the tag. */\n requiredConsent?: ConsentCategory[];\n};\n\nexport class InjectedScript extends Component<InjectedScriptProps> {\n componentDidMount() {\n const { baseId, descriptors, requiredConsent = [] } = this.props;\n const platform = findDelegatedPlatform();\n const blockingAttributes = platform\n ? getBlockingAttributes(platform, requiredConsent)\n : {};\n const blockedByPlatform = \"type\" in blockingAttributes;\n const createdNodes = injectScriptDescriptors({\n baseId,\n descriptors,\n extraAttributes: blockingAttributes,\n });\n\n // Cookiebot may finish its startup scan before late consent-gated tags mount.\n if (blockedByPlatform && createdNodes.length > 0) {\n activateBlockedScripts();\n }\n // NOTE (Ryan, 2026-09-02): Executed scripts stay mounted because removing their nodes cannot unload the vendor.\n }\n\n render() {\n return null;\n }\n}\n\nclass ScriptRegistration extends Component<{ script: RegisteredScript }> {\n componentDidMount() {\n registerScript(this.props.script);\n }\n\n componentWillUnmount() {\n unregisterScript(this.props.script.id);\n }\n\n render() {\n return null;\n }\n}\n\nfunction ManagedScript({ entry }: { entry: ReploScriptEntry }) {\n const consent = useConsent();\n const requiredConsent = requiredConsentFor(entry);\n const id = scriptId(entry);\n const isBlockedByNativeConsent =\n !findDelegatedPlatform() &&\n !isConsentAllowed({ state: consent, requiredConsent });\n\n return (\n <>\n <ScriptRegistration\n key={`${id}:${requiredConsent.join(\",\")}`}\n script={{ id, type: entry.type, requiredConsent }}\n />\n {!isBlockedByNativeConsent && (\n <InjectedScript\n baseId={id}\n descriptors={descriptorsFor(entry)}\n requiredConsent={requiredConsent}\n />\n )}\n </>\n );\n}\n\nclass ConsentWindowApi extends Component {\n private uninstall = () => {};\n\n componentDidMount() {\n this.uninstall = installConsentWindowApi();\n }\n\n componentWillUnmount() {\n this.uninstall();\n }\n\n render() {\n return null;\n }\n}\n\n/**\n * The single registry component for all managed tracking scripts on the site.\n * Authored once in `app/layout.tsx`; the agent/miniapp only edit the `scripts`\n * array. Each entry registers itself and is gated + injected per consent.\n *\n * A consent-platform entry (`Cookiebot`, or a generic `consentPlatform`) takes\n * over consent site-wide: scripts carry the platform's blocking attributes, its\n * loader injects after them so its startup scan sees the full set, and Replo's\n * own gates follow the platform instead of the native banner.\n */\nexport function ReploScripts({ scripts }: { scripts: ReploScriptEntry[] }) {\n // The earlier-mounted first-party pixel needs delegation before mount lifecycles run.\n const platform = findConsentPlatform(scripts);\n if (platform) {\n enableConsentDelegation(platform);\n }\n\n // The loader renders last so every blocked tag mounts before its startup scan.\n return (\n <>\n <ConsentWindowApi />\n {scripts\n .filter((entry) => !isConsentPlatformEntry(entry))\n .map((entry) => (\n <ManagedScript key={scriptId(entry)} entry={entry} />\n ))}\n {platform &&\n !platform.isCookiebot &&\n OPTIONAL_CONSENT_CATEGORIES.map((category) => (\n <InjectedScript\n key={category}\n baseId={`consent-platform:${platform.id}:grant:${category}`}\n descriptors={[buildGrantMarker(category)]}\n requiredConsent={[category]}\n />\n ))}\n {platform && (\n <InjectedScript\n baseId={`consent-platform:${platform.id}`}\n descriptors={platform.loader}\n />\n )}\n </>\n );\n}\n"],
5
- "mappings": ";AAmJI,mBACE,KADF;AA1IJ,SAAS,iBAAiB;AAE1B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,kBAAkB,kBAAkB;AAC7C,SAAS,+BAA+B;AACxC,SAAS,gBAAgB,wBAAwB;AACjD,SAAS,iBAAiB,yBAAyB;AACnD,SAAS,+BAA+B;AAMxC,SAAS,SAAS,OAAiC;AACjD,MAAI,MAAM,SAAS,UAAU;AAC3B,WAAO,UAAU,MAAM,EAAE;AAAA,EAC3B;AACA,MAAI,MAAM,SAAS,WAAW;AAC5B,WAAO,WAAW,MAAM,EAAE;AAAA,EAC5B;AACA,MAAI,MAAM,SAAS,mBAAmB;AACpC,WAAO,oBAAoB,MAAM,EAAE;AAAA,EACrC;AACA,SAAO,GAAG,MAAM,IAAI,IAAI,MAAM,UAAU;AAC1C;AAEA,SAAS,mBAAmB,OAA4C;AACtE,MAAI,MAAM,SAAS,YAAY,MAAM,SAAS,WAAW;AACvD,WAAO,MAAM;AAAA,EACf;AAEA,MAAI,MAAM,SAAS,qBAAqB,MAAM,SAAS,aAAa;AAClE,WAAO,CAAC;AAAA,EACV;AACA,SAAO,MAAM,mBAAmB,kBAAkB,MAAM,IAAI;AAC9D;AAQA,SAAS,eAAe,OAAgD;AACtE,MAAI,MAAM,SAAS,UAAU;AAC3B,QAAI,MAAM,KAAK;AACb,aAAO,CAAC,EAAE,MAAM,YAAY,KAAK,MAAM,IAAI,CAAC;AAAA,IAC9C;AACA,QAAI,MA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sourcesContent": ["\"use client\";\n\nimport type {\n ConsentCategory,\n ReploScriptEntry,\n ScriptTagDescriptor,\n} from \"schemas/generated/consent\";\nimport type { RegisteredScript } from \"./script-registration-store\";\n\nimport { Component } from \"react\";\n\nimport {\n activateBlockedScripts,\n buildGrantMarker,\n enableConsentDelegation,\n findConsentPlatform,\n findDelegatedPlatform,\n getBlockingAttributes,\n isConsentPlatformEntry,\n OPTIONAL_CONSENT_CATEGORIES,\n} from \"./consent-platform\";\nimport { isConsentAllowed, useConsent } from \"./consent-store\";\nimport { injectScriptDescriptors } from \"./inject-script-descriptors\";\nimport {\n registerScript,\n snippetScriptId,\n unregisterScript,\n} from \"./script-registration-store\";\nimport { buildScriptTags, defaultConsentFor } from \"./script-snippets\";\nimport { installConsentWindowApi } from \"./window-api\";\n\n/**\n * Stable identity for an entry, used as React key and DOM dedupe key. `snippet`\n * and `custom` entries key on their `id`; identifier providers on type+id.\n */\nfunction scriptId(entry: ReploScriptEntry): string {\n if (entry.type === \"custom\") {\n return `custom:${entry.id}`;\n }\n if (entry.type === \"snippet\") {\n return snippetScriptId(entry.id);\n }\n if (entry.type === \"consentPlatform\") {\n return `consent-platform:${entry.id}`;\n }\n return `${entry.type}:${entry.identifier}`;\n}\n\nfunction requiredConsentFor(entry: ReploScriptEntry): ConsentCategory[] {\n if (entry.type === \"custom\" || entry.type === \"snippet\") {\n return entry.requiredConsent;\n }\n // Platform entries are filtered out before render; arms exist for the types.\n if (entry.type === \"consentPlatform\" || entry.type === \"Cookiebot\") {\n return [];\n }\n return entry.requiredConsent ?? defaultConsentFor(entry.type);\n}\n\n/**\n * Resolves an entry to the concrete tags to inject. An identifier provider may\n * resolve to multiple tags (GA4 = external loader + inline config); a `snippet`\n * entry injects its pasted body inline; a `custom` entry is a single external\n * `src` or inline `body`.\n */\nfunction descriptorsFor(entry: ReploScriptEntry): ScriptTagDescriptor[] {\n if (entry.type === \"custom\") {\n if (entry.src) {\n return [{ kind: \"external\", src: entry.src }];\n }\n if (entry.body) {\n return [{ kind: \"inline\", body: entry.body }];\n }\n return [];\n }\n if (entry.type === \"snippet\") {\n return [{ kind: \"inline\", body: entry.body, module: entry.module }];\n }\n // Platform entries load from their platform config rather than per-entry.\n if (entry.type === \"consentPlatform\" || entry.type === \"Cookiebot\") {\n return [];\n }\n return buildScriptTags({ type: entry.type, identifier: entry.identifier });\n}\n\n/**\n * Injects the resolved tags into `document.head` once a caller has decided\n * consent allows it. Reused both for author-managed `ReploScripts` entries and\n * for the implicit Replo first-party pixel.\n *\n * DOM insertion (not JSX) is required because inline `<script>` bodies set via\n * React's `dangerouslySetInnerHTML` never execute. Each node is tagged with\n * `data-replo-script-id` (plus a per-tag index) so re-renders and React Strict\n * Mode double-invokes do not double-inject.\n */\ntype InjectedScriptProps = {\n baseId: string;\n descriptors: ScriptTagDescriptor[];\n /** Used under a delegated platform to derive the attributes that gate the tag. */\n requiredConsent?: ConsentCategory[];\n};\n\nexport class InjectedScript extends Component<InjectedScriptProps> {\n componentDidMount() {\n const { baseId, descriptors, requiredConsent = [] } = this.props;\n const platform = findDelegatedPlatform();\n const blockingAttributes = platform\n ? getBlockingAttributes(platform, requiredConsent)\n : {};\n const blockedByPlatform = \"type\" in blockingAttributes;\n const createdNodes = injectScriptDescriptors({\n baseId,\n descriptors,\n extraAttributes: blockingAttributes,\n });\n\n // Cookiebot may finish its startup scan before late consent-gated tags mount.\n if (blockedByPlatform && createdNodes.length > 0) {\n activateBlockedScripts();\n }\n // NOTE (Ryan, 2026-09-02): Executed scripts stay mounted because removing their nodes cannot unload the vendor.\n }\n\n render() {\n return null;\n }\n}\n\nclass ScriptRegistration extends Component<{ script: RegisteredScript }> {\n componentDidMount() {\n registerScript(this.props.script);\n }\n\n componentWillUnmount() {\n unregisterScript(this.props.script.id);\n }\n\n render() {\n return null;\n }\n}\n\nfunction ManagedScript({ entry }: { entry: ReploScriptEntry }) {\n const consent = useConsent();\n const requiredConsent = requiredConsentFor(entry);\n const id = scriptId(entry);\n const isBlockedByNativeConsent =\n !findDelegatedPlatform() &&\n !isConsentAllowed({ state: consent, requiredConsent });\n\n return (\n <>\n <ScriptRegistration\n key={`${id}:${requiredConsent.join(\",\")}`}\n script={{ id, type: entry.type, requiredConsent }}\n />\n {!isBlockedByNativeConsent && (\n <InjectedScript\n baseId={id}\n descriptors={descriptorsFor(entry)}\n requiredConsent={requiredConsent}\n />\n )}\n </>\n );\n}\n\nclass ConsentWindowApi extends Component {\n private uninstall = () => {};\n\n componentDidMount() {\n this.uninstall = installConsentWindowApi();\n }\n\n componentWillUnmount() {\n this.uninstall();\n }\n\n render() {\n return null;\n }\n}\n\n/**\n * The single registry component for all managed tracking scripts on the site.\n * Authored once in `app/layout.tsx`; the agent/miniapp only edit the `scripts`\n * array. Each entry registers itself and is gated + injected per consent.\n *\n * A consent-platform entry (`Cookiebot`, or a generic `consentPlatform`) takes\n * over consent site-wide: scripts carry the platform's blocking attributes, its\n * loader injects after them so its startup scan sees the full set, and Replo's\n * own gates follow the platform instead of the native banner.\n */\nexport function ReploScripts({ scripts }: { scripts: ReploScriptEntry[] }) {\n // The earlier-mounted first-party pixel needs delegation before mount lifecycles run.\n const platform = findConsentPlatform(scripts);\n if (platform) {\n enableConsentDelegation(platform);\n }\n\n // The loader renders last so every blocked tag mounts before its startup scan.\n return (\n <>\n <ConsentWindowApi />\n {scripts\n .filter((entry) => !isConsentPlatformEntry(entry))\n .map((entry) => (\n <ManagedScript key={scriptId(entry)} entry={entry} />\n ))}\n {platform &&\n !platform.isCookiebot &&\n OPTIONAL_CONSENT_CATEGORIES.map((category) => (\n <InjectedScript\n key={category}\n baseId={`consent-platform:${platform.id}:grant:${category}`}\n descriptors={[buildGrantMarker(category)]}\n requiredConsent={[category]}\n />\n ))}\n {platform && (\n <InjectedScript\n baseId={`consent-platform:${platform.id}`}\n descriptors={platform.loader}\n />\n )}\n </>\n );\n}\n"],
5
+ "mappings": ";AAuJI,mBACE,KADF;AA9IJ,SAAS,iBAAiB;AAE1B;AAA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ACjC;AAAA;AAAA,IACF;AAAA,KAEJ;AAEJ;AAEA,MAAM,yBAAyB,UAAU;AAAA,EAC/B,YAAY,MAAM;AAAA,EAAC;AAAA,EAE3B,oBAAoB;AAClB,SAAK,YAAY,wBAAwB;AAAA,EAC3C;AAAA,EAEA,uBAAuB;AACrB,SAAK,UAAU;AAAA,EACjB;AAAA,EAEA,SAAS;AACP,WAAO;AAAA,EACT;AACF;AAYO,SAAS,aAAa,EAAE,QAAQ,GAAoC;AAEzE,QAAM,WAAW,oBAAoB,OAAO;AAC5C,MAAI,UAAU;AACZ,4BAAwB,QAAQ;AAAA,EAClC;AAGA,SACE,iCACE;AAAA,wBAAC,oBAAiB;AAAA,IACjB,QACE,OAAO,CAAC,UAAU,CAAC,uBAAuB,KAAK,CAAC,EAChD,IAAI,CAAC,UACJ,oBAAC,iBAAoC,SAAjB,SAAS,KAAK,CAAiB,CACpD;AAAA,IACF,YACC,CAAC,SAAS,eACV,4BAA4B,IAAI,CAAC,aAC/B;AAAA,MAAC;AAAA;AAAA,QAEC,QAAQ,oBAAoB,SAAS,EAAE,UAAU,QAAQ;AAAA,QACzD,aAAa,CAAC,iBAAiB,QAAQ,CAAC;AAAA,QACxC,iBAAiB,CAAC,QAAQ;AAAA;AAAA,MAHrB;AAAA,IAIP,CACD;AAAA,IACF,YACC;AAAA,MAAC;AAAA;AAAA,QACC,QAAQ,oBAAoB,SAAS,EAAE;AAAA,QACvC,aAAa,SAAS;AAAA;AAAA,IACxB;AAAA,KAEJ;AAEJ;",
6
6
  "names": []
7
7
  }
@@ -11,6 +11,12 @@ export interface RegisteredScript {
11
11
  type: ReploScriptType;
12
12
  requiredConsent: ConsentCategory[];
13
13
  }
14
+ /**
15
+ * Registration id of a `snippet` entry. Snippet providers have no distinct
16
+ * `type`, so both `ReploScripts` (registering) and the analytics sink factory
17
+ * (matching) identify them by this id.
18
+ */
19
+ export declare function snippetScriptId(entryId: string): string;
14
20
  export declare const scriptRegistrationStore: {
15
21
  register(script: RegisteredScript): void;
16
22
  unregister(id: string): void;
@@ -1,5 +1,8 @@
1
1
  "use client";
2
2
  import { useSyncExternalStore } from "react";
3
+ function snippetScriptId(entryId) {
4
+ return `snippet:${entryId}`;
5
+ }
3
6
  const registry = /* @__PURE__ */ new Map();
4
7
  const listeners = /* @__PURE__ */ new Set();
5
8
  let snapshot = [];
@@ -55,6 +58,7 @@ function useRegisteredScripts() {
55
58
  export {
56
59
  registerScript,
57
60
  scriptRegistrationStore,
61
+ snippetScriptId,
58
62
  unregisterScript,
59
63
  useRegisteredScripts
60
64
  };
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../consent/script-registration-store.ts"],
4
- "sourcesContent": ["\"use client\";\n\nimport type {\n ConsentCategory,\n ReploScriptType,\n} from \"schemas/generated/consent\";\n\nimport { useSyncExternalStore } from \"react\";\n\n/**\n * Tracks which managed scripts are currently mounted on the page. Each\n * `ReploScripts` entry registers itself here on mount, so the analytics provider\n * can create sinks only for providers that are actually present (and consented),\n * without importing a static list. Like the consent store, this is a singleton\n * rather than React context so it works regardless of tree position.\n */\n\nexport interface RegisteredScript {\n id: string;\n type: ReploScriptType;\n requiredConsent: ConsentCategory[];\n}\n\nconst registry = new Map<string, RegisteredScript>();\nconst listeners = new Set<() => void>();\n\n// useSyncExternalStore requires a referentially-stable snapshot between emits.\nlet snapshot: RegisteredScript[] = [];\n\nconst SERVER_SNAPSHOT: RegisteredScript[] = [];\n\nfunction emit() {\n snapshot = [...registry.values()];\n for (const listener of listeners) {\n listener();\n }\n}\n\nexport const scriptRegistrationStore = {\n register(script: RegisteredScript) {\n registry.set(script.id, script);\n emit();\n },\n unregister(id: string) {\n if (registry.delete(id)) {\n emit();\n }\n },\n getSnapshot(): RegisteredScript[] {\n return snapshot;\n },\n getServerSnapshot(): RegisteredScript[] {\n return SERVER_SNAPSHOT;\n },\n subscribe(listener: () => void): () => void {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n /** Test-only: clear the registry between cases. */\n reset() {\n registry.clear();\n listeners.clear();\n snapshot = [];\n },\n};\n\nexport function registerScript(script: RegisteredScript) {\n scriptRegistrationStore.register(script);\n}\n\nexport function unregisterScript(id: string) {\n scriptRegistrationStore.unregister(id);\n}\n\nexport function useRegisteredScripts(): RegisteredScript[] {\n return useSyncExternalStore(\n scriptRegistrationStore.subscribe,\n scriptRegistrationStore.getSnapshot,\n scriptRegistrationStore.getServerSnapshot,\n );\n}\n"],
5
- "mappings": ";AAOA,SAAS,4BAA4B;AAgBrC,MAAM,WAAW,oBAAI,IAA8B;AACnD,MAAM,YAAY,oBAAI,IAAgB;AAGtC,IAAI,WAA+B,CAAC;AAEpC,MAAM,kBAAsC,CAAC;AAE7C,SAAS,OAAO;AACd,aAAW,CAAC,GAAG,SAAS,OAAO,CAAC;AAChC,aAAW,YAAY,WAAW;AAChC,aAAS;AAAA,EACX;AACF;AAEO,MAAM,0BAA0B;AAAA,EACrC,SAAS,QAA0B;AACjC,aAAS,IAAI,OAAO,IAAI,MAAM;AAC9B,SAAK;AAAA,EACP;AAAA,EACA,WAAW,IAAY;AACrB,QAAI,SAAS,OAAO,EAAE,GAAG;AACvB,WAAK;AAAA,IACP;AAAA,EACF;AAAA,EACA,cAAkC;AAChC,WAAO;AAAA,EACT;AAAA,EACA,oBAAwC;AACtC,WAAO;AAAA,EACT;AAAA,EACA,UAAU,UAAkC;AAC1C,cAAU,IAAI,QAAQ;AACtB,WAAO,MAAM;AACX,gBAAU,OAAO,QAAQ;AAAA,IAC3B;AAAA,EACF;AAAA;AAAA,EAEA,QAAQ;AACN,aAAS,MAAM;AACf,cAAU,MAAM;AAChB,eAAW,CAAC;AAAA,EACd;AACF;AAEO,SAAS,eAAe,QAA0B;AACvD,0BAAwB,SAAS,MAAM;AACzC;AAEO,SAAS,iBAAiB,IAAY;AAC3C,0BAAwB,WAAW,EAAE;AACvC;AAEO,SAAS,uBAA2C;AACzD,SAAO;AAAA,IACL,wBAAwB;AAAA,IACxB,wBAAwB;AAAA,IACxB,wBAAwB;AAAA,EAC1B;AACF;",
4
+ "sourcesContent": ["\"use client\";\n\nimport type {\n ConsentCategory,\n ReploScriptType,\n} from \"schemas/generated/consent\";\n\nimport { useSyncExternalStore } from \"react\";\n\n/**\n * Tracks which managed scripts are currently mounted on the page. Each\n * `ReploScripts` entry registers itself here on mount, so the analytics provider\n * can create sinks only for providers that are actually present (and consented),\n * without importing a static list. Like the consent store, this is a singleton\n * rather than React context so it works regardless of tree position.\n */\n\nexport interface RegisteredScript {\n id: string;\n type: ReploScriptType;\n requiredConsent: ConsentCategory[];\n}\n\n/**\n * Registration id of a `snippet` entry. Snippet providers have no distinct\n * `type`, so both `ReploScripts` (registering) and the analytics sink factory\n * (matching) identify them by this id.\n */\nexport function snippetScriptId(entryId: string) {\n return `snippet:${entryId}`;\n}\n\nconst registry = new Map<string, RegisteredScript>();\nconst listeners = new Set<() => void>();\n\n// useSyncExternalStore requires a referentially-stable snapshot between emits.\nlet snapshot: RegisteredScript[] = [];\n\nconst SERVER_SNAPSHOT: RegisteredScript[] = [];\n\nfunction emit() {\n snapshot = [...registry.values()];\n for (const listener of listeners) {\n listener();\n }\n}\n\nexport const scriptRegistrationStore = {\n register(script: RegisteredScript) {\n registry.set(script.id, script);\n emit();\n },\n unregister(id: string) {\n if (registry.delete(id)) {\n emit();\n }\n },\n getSnapshot(): RegisteredScript[] {\n return snapshot;\n },\n getServerSnapshot(): RegisteredScript[] {\n return SERVER_SNAPSHOT;\n },\n subscribe(listener: () => void): () => void {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n /** Test-only: clear the registry between cases. */\n reset() {\n registry.clear();\n listeners.clear();\n snapshot = [];\n },\n};\n\nexport function registerScript(script: RegisteredScript) {\n scriptRegistrationStore.register(script);\n}\n\nexport function unregisterScript(id: string) {\n scriptRegistrationStore.unregister(id);\n}\n\nexport function useRegisteredScripts(): RegisteredScript[] {\n return useSyncExternalStore(\n scriptRegistrationStore.subscribe,\n scriptRegistrationStore.getSnapshot,\n scriptRegistrationStore.getServerSnapshot,\n );\n}\n"],
5
+ "mappings": ";AAOA,SAAS,4BAA4B;AAqB9B,SAAS,gBAAgB,SAAiB;AAC/C,SAAO,WAAW,OAAO;AAC3B;AAEA,MAAM,WAAW,oBAAI,IAA8B;AACnD,MAAM,YAAY,oBAAI,IAAgB;AAGtC,IAAI,WAA+B,CAAC;AAEpC,MAAM,kBAAsC,CAAC;AAE7C,SAAS,OAAO;AACd,aAAW,CAAC,GAAG,SAAS,OAAO,CAAC;AAChC,aAAW,YAAY,WAAW;AAChC,aAAS;AAAA,EACX;AACF;AAEO,MAAM,0BAA0B;AAAA,EACrC,SAAS,QAA0B;AACjC,aAAS,IAAI,OAAO,IAAI,MAAM;AAC9B,SAAK;AAAA,EACP;AAAA,EACA,WAAW,IAAY;AACrB,QAAI,SAAS,OAAO,EAAE,GAAG;AACvB,WAAK;AAAA,IACP;AAAA,EACF;AAAA,EACA,cAAkC;AAChC,WAAO;AAAA,EACT;AAAA,EACA,oBAAwC;AACtC,WAAO;AAAA,EACT;AAAA,EACA,UAAU,UAAkC;AAC1C,cAAU,IAAI,QAAQ;AACtB,WAAO,MAAM;AACX,gBAAU,OAAO,QAAQ;AAAA,IAC3B;AAAA,EACF;AAAA;AAAA,EAEA,QAAQ;AACN,aAAS,MAAM;AACf,cAAU,MAAM;AAChB,eAAW,CAAC;AAAA,EACd;AACF;AAEO,SAAS,eAAe,QAA0B;AACvD,0BAAwB,SAAS,MAAM;AACzC;AAEO,SAAS,iBAAiB,IAAY;AAC3C,0BAAwB,WAAW,EAAE;AACvC;AAEO,SAAS,uBAA2C;AACzD,SAAO;AAAA,IACL,wBAAwB;AAAA,IACxB,wBAAwB;AAAA,IACxB,wBAAwB;AAAA,EAC1B;AACF;",
6
6
  "names": []
7
7
  }
@@ -97,7 +97,11 @@ If you're running locally, make sure the canopy-api cloudflare worker is running
97
97
  const response = await this._post(`${this.baseUrl}/api/v1/loaders/invoke`, {
98
98
  projectId: env.PROJECT_ID,
99
99
  loaderKey,
100
- args
100
+ args,
101
+ // The builder preview must render a product the merchant hasn't launched
102
+ // yet; a published storefront must not. Only the sandbox dev server sets
103
+ // IS_REPLO_SANDBOX, so it is what separates the two.
104
+ includeInactiveProducts: Boolean(process.env.IS_REPLO_SANDBOX)
101
105
  });
102
106
  if (!response.ok) {
103
107
  const errorBody = await response.text().catch(() => "");
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../gateways/canopy-api.ts"],
4
- "sourcesContent": ["import type { Cart } from \"../cart/cart-schema\";\n\nimport { z } from \"zod\";\n\nimport { cartSchema } from \"../cart/cart-schema\";\nimport { getEnv } from \"../env\";\nimport { CanopyError } from \"../lib/canopy-error\";\nimport { buildBaseUrl } from \"../lib/url-utils\";\n\ntype CanopyApiGatewayErrorConfig = {\n message: string;\n statusCode?: number;\n cause?: unknown;\n additionalData?: Record<string, unknown>;\n};\n\nexport class CanopyApiGatewayError extends CanopyError {\n statusCode: number;\n\n constructor(config: CanopyApiGatewayErrorConfig) {\n const resolvedStatusCode = config.statusCode ?? 500;\n super({\n message: config.message,\n cause: config.cause,\n additionalData: {\n ...config.additionalData,\n statusCode: resolvedStatusCode,\n },\n });\n this.statusCode = resolvedStatusCode;\n }\n}\n\nclass UnknownCanopyApiError extends CanopyApiGatewayError {\n constructor(config: Omit<CanopyApiGatewayErrorConfig, \"statusCode\">) {\n super({ ...config, statusCode: 502 });\n }\n}\n\nconst loaderInvokeResponseSchema = z.object({\n data: z.unknown(),\n meta: z\n .object({\n cache: z.object({\n hit: z.boolean(),\n ttlSeconds: z.number(),\n }),\n })\n .optional(),\n});\n\nclass CanopyApiGateway {\n private apiHost: string;\n private baseUrl: string;\n constructor(apiHost: string) {\n this.apiHost = apiHost;\n this.baseUrl = buildBaseUrl(apiHost);\n }\n\n private static readonly REQUEST_TIMEOUT_MILLISECONDS = 10_000;\n\n static async setup() {\n const env = await getEnv();\n\n return new CanopyApiGateway(env.CANOPY_API_HOST);\n }\n\n private async _post(url: string, body: unknown) {\n const abortController = new AbortController();\n const timeoutId = setTimeout(() => {\n abortController.abort();\n }, CanopyApiGateway.REQUEST_TIMEOUT_MILLISECONDS);\n\n try {\n return await fetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n signal: abortController.signal,\n });\n } catch (error) {\n let message = `Failed to POST to canopy-api at ${url}: ${error}`;\n if (process.env.NODE_ENV !== \"production\") {\n message += `\\n\\napiHost: ${this.apiHost}\\nIf you're running locally, make sure the canopy-api cloudflare worker is running. You may need to restart the dev server.`;\n }\n throw new UnknownCanopyApiError({ message, cause: error });\n } finally {\n clearTimeout(timeoutId);\n }\n }\n\n private async _get(url: string) {\n const abortController = new AbortController();\n const timeoutId = setTimeout(() => {\n abortController.abort();\n }, CanopyApiGateway.REQUEST_TIMEOUT_MILLISECONDS);\n\n try {\n return await fetch(url, { signal: abortController.signal });\n } catch (error) {\n let message = `Failed to GET from canopy-api at ${url}: ${error}`;\n if (process.env.NODE_ENV !== \"production\") {\n message += `\\n\\napiHost: ${this.apiHost}\\nIf you're running locally, make sure the canopy-api cloudflare worker is running. You may need to restart the dev server.`;\n }\n throw new UnknownCanopyApiError({ message, cause: error });\n } finally {\n clearTimeout(timeoutId);\n }\n }\n\n async invokeLoader({\n loaderKey,\n args,\n }: {\n loaderKey: string;\n args: Record<string, unknown>;\n }) {\n const env = await getEnv();\n const response = await this._post(`${this.baseUrl}/api/v1/loaders/invoke`, {\n projectId: env.PROJECT_ID,\n loaderKey,\n args,\n });\n\n if (!response.ok) {\n const errorBody = await response.text().catch(() => \"\");\n throw new CanopyApiGatewayError({\n message: `Failed to invoke loader ${loaderKey}: ${response.status} ${response.statusText}${errorBody ? ` \u2014 ${errorBody}` : \"\"}`,\n statusCode: response.status,\n });\n }\n\n return loaderInvokeResponseSchema.parse(await response.json());\n }\n\n // ---------------------------------------------------------------------------\n // Cart operations (canopy-api-backed ExternalCart)\n // ---------------------------------------------------------------------------\n\n private async _cartPost(\n path: string,\n body: Record<string, unknown>,\n ): Promise<Cart> {\n const env = await getEnv();\n const url = `${this.baseUrl}/api/v1/cart${path}`;\n\n const abortController = new AbortController();\n const timeoutId = setTimeout(() => {\n abortController.abort();\n }, CanopyApiGateway.REQUEST_TIMEOUT_MILLISECONDS);\n\n let response: Response;\n try {\n response = await fetch(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ ...body, projectId: env.PROJECT_ID }),\n signal: abortController.signal,\n });\n } catch (error) {\n throw new UnknownCanopyApiError({\n message: `Failed to POST cart operation to ${url}: ${error}`,\n cause: error,\n });\n } finally {\n clearTimeout(timeoutId);\n }\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n throw new CanopyApiGatewayError({\n message: `Cart operation ${path} failed: ${response.status} ${response.statusText} \u2014 ${text}`,\n statusCode: response.status,\n });\n }\n\n // Legacy cast - may or may not be necessary\n // eslint-disable-next-line replo/no-as-cast\n const json = (await response.json()) as { data: unknown };\n return cartSchema.parse(json.data);\n }\n\n async cartGet({ cartId }: { cartId: string }): Promise<Cart | null> {\n try {\n return await this._cartPost(\"/get\", { cartId });\n } catch (error) {\n if (error instanceof CanopyApiGatewayError && error.statusCode === 404) {\n return null;\n }\n throw error;\n }\n }\n\n async cartCreate(options?: {\n lines?: {\n merchandiseId: string;\n quantity: number;\n attributes?: { key: string; value: string }[];\n sellingPlanId?: string | null;\n }[];\n discountCodes?: string[];\n }): Promise<Cart> {\n return this._cartPost(\"/create\", {\n lines: options?.lines,\n discountCodes: options?.discountCodes,\n });\n }\n\n async cartAddLines({\n cartId,\n lines,\n }: {\n cartId: string;\n lines: {\n merchandiseId: string;\n quantity: number;\n attributes?: { key: string; value: string }[];\n sellingPlanId?: string | null;\n }[];\n }): Promise<Cart> {\n return this._cartPost(\"/add-lines\", { cartId, lines });\n }\n\n async cartUpdateLines({\n cartId,\n lines,\n }: {\n cartId: string;\n lines: {\n lineId: string;\n quantity: number;\n attributes?: { key: string; value: string }[];\n sellingPlanId?: string | null;\n }[];\n }): Promise<Cart> {\n return this._cartPost(\"/update-lines\", { cartId, lines });\n }\n\n async cartRemoveLines({\n cartId,\n lineIds,\n }: {\n cartId: string;\n lineIds: string[];\n }): Promise<Cart> {\n return this._cartPost(\"/remove-lines\", { cartId, lineIds });\n }\n\n async cartUpdateDiscountCodes({\n cartId,\n discountCodes,\n }: {\n cartId: string;\n discountCodes: string[];\n }): Promise<Cart> {\n return this._cartPost(\"/update-discount-codes\", { cartId, discountCodes });\n }\n}\n\nexport async function getCanopyApiGateway() {\n return CanopyApiGateway.setup();\n}\n"],
5
- "mappings": "AAEA,SAAS,SAAS;AAElB,SAAS,kBAAkB;AAC3B,SAAS,cAAc;AACvB,SAAS,mBAAmB;AAC5B,SAAS,oBAAoB;AAStB,MAAM,8BAA8B,YAAY;AAAA,EACrD;AAAA,EAEA,YAAY,QAAqC;AAC/C,UAAM,qBAAqB,OAAO,cAAc;AAChD,UAAM;AAAA,MACJ,SAAS,OAAO;AAAA,MAChB,OAAO,OAAO;AAAA,MACd,gBAAgB;AAAA,QACd,GAAG,OAAO;AAAA,QACV,YAAY;AAAA,MACd;AAAA,IACF,CAAC;AACD,SAAK,aAAa;AAAA,EACpB;AACF;AAEA,MAAM,8BAA8B,sBAAsB;AAAA,EACxD,YAAY,QAAyD;AACnE,UAAM,EAAE,GAAG,QAAQ,YAAY,IAAI,CAAC;AAAA,EACtC;AACF;AAEA,MAAM,6BAA6B,EAAE,OAAO;AAAA,EAC1C,MAAM,EAAE,QAAQ;AAAA,EAChB,MAAM,EACH,OAAO;AAAA,IACN,OAAO,EAAE,OAAO;AAAA,MACd,KAAK,EAAE,QAAQ;AAAA,MACf,YAAY,EAAE,OAAO;AAAA,IACvB,CAAC;AAAA,EACH,CAAC,EACA,SAAS;AACd,CAAC;AAED,MAAM,iBAAiB;AAAA,EACb;AAAA,EACA;AAAA,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AA,EAC5D;AAAA,EAEA,MAAM,wBAAwB;AAAA,IAC5B;AAAA,IACA;AAAA,EACF,GAGkB;AAChB,WAAO,KAAK,UAAU,0BAA0B,EAAE,QAAQ,cAAc,CAAC;AAAA,EAC3E;AACF;AAEA,eAAsB,sBAAsB;AAC1C,SAAO,iBAAiB,MAAM;AAChC;",
4
+ "sourcesContent": ["import type { Cart } from \"../cart/cart-schema\";\n\nimport { z } from \"zod\";\n\nimport { cartSchema } from \"../cart/cart-schema\";\nimport { getEnv } from \"../env\";\nimport { CanopyError } from \"../lib/canopy-error\";\nimport { buildBaseUrl } from \"../lib/url-utils\";\n\ntype CanopyApiGatewayErrorConfig = {\n message: string;\n statusCode?: number;\n cause?: unknown;\n additionalData?: Record<string, unknown>;\n};\n\nexport class CanopyApiGatewayError extends CanopyError {\n statusCode: number;\n\n constructor(config: CanopyApiGatewayErrorConfig) {\n const resolvedStatusCode = config.statusCode ?? 500;\n super({\n message: config.message,\n cause: config.cause,\n additionalData: {\n ...config.additionalData,\n statusCode: resolvedStatusCode,\n },\n });\n this.statusCode = resolvedStatusCode;\n }\n}\n\nclass UnknownCanopyApiError extends CanopyApiGatewayError {\n constructor(config: Omit<CanopyApiGatewayErrorConfig, \"statusCode\">) {\n super({ ...config, statusCode: 502 });\n }\n}\n\nconst loaderInvokeResponseSchema = z.object({\n data: z.unknown(),\n meta: z\n .object({\n cache: z.object({\n hit: z.boolean(),\n ttlSeconds: z.number(),\n }),\n })\n .optional(),\n});\n\nclass CanopyApiGateway {\n private apiHost: string;\n private baseUrl: string;\n constructor(apiHost: string) {\n this.apiHost = apiHost;\n this.baseUrl = buildBaseUrl(apiHost);\n }\n\n private static readonly REQUEST_TIMEOUT_MILLISECONDS = 10_000;\n\n static async setup() {\n const env = await getEnv();\n\n return new CanopyApiGateway(env.CANOPY_API_HOST);\n }\n\n private async _post(url: string, body: unknown) {\n const abortController = new AbortController();\n const timeoutId = setTimeout(() => {\n abortController.abort();\n }, CanopyApiGateway.REQUEST_TIMEOUT_MILLISECONDS);\n\n try {\n return await fetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n signal: abortController.signal,\n });\n } catch (error) {\n let message = `Failed to POST to canopy-api at ${url}: ${error}`;\n if (process.env.NODE_ENV !== \"production\") {\n message += `\\n\\napiHost: ${this.apiHost}\\nIf you're running locally, make sure the canopy-api cloudflare worker is running. You may need to restart the dev server.`;\n }\n throw new UnknownCanopyApiError({ message, cause: error });\n } finally {\n clearTimeout(timeoutId);\n }\n }\n\n private async _get(url: string) {\n const abortController = new AbortController();\n const timeoutId = setTimeout(() => {\n abortController.abort();\n }, CanopyApiGateway.REQUEST_TIMEOUT_MILLISECONDS);\n\n try {\n return await fetch(url, { signal: abortController.signal });\n } catch (error) {\n let message = `Failed to GET from canopy-api at ${url}: ${error}`;\n if (process.env.NODE_ENV !== \"production\") {\n message += `\\n\\napiHost: ${this.apiHost}\\nIf you're running locally, make sure the canopy-api cloudflare worker is running. You may need to restart the dev server.`;\n }\n throw new UnknownCanopyApiError({ message, cause: error });\n } finally {\n clearTimeout(timeoutId);\n }\n }\n\n async invokeLoader({\n loaderKey,\n args,\n }: {\n loaderKey: string;\n args: Record<string, unknown>;\n }) {\n const env = await getEnv();\n const response = await this._post(`${this.baseUrl}/api/v1/loaders/invoke`, {\n projectId: env.PROJECT_ID,\n loaderKey,\n args,\n // The builder preview must render a product the merchant hasn't launched\n // yet; a published storefront must not. Only the sandbox dev server sets\n // IS_REPLO_SANDBOX, so it is what separates the two.\n includeInactiveProducts: Boolean(process.env.IS_REPLO_SANDBOX),\n });\n\n if (!response.ok) {\n const errorBody = await response.text().catch(() => \"\");\n throw new CanopyApiGatewayError({\n message: `Failed to invoke loader ${loaderKey}: ${response.status} ${response.statusText}${errorBody ? ` \u2014 ${errorBody}` : \"\"}`,\n statusCode: response.status,\n });\n }\n\n return loaderInvokeResponseSchema.parse(await response.json());\n }\n\n // ---------------------------------------------------------------------------\n // Cart operations (canopy-api-backed ExternalCart)\n // ---------------------------------------------------------------------------\n\n private async _cartPost(\n path: string,\n body: Record<string, unknown>,\n ): Promise<Cart> {\n const env = await getEnv();\n const url = `${this.baseUrl}/api/v1/cart${path}`;\n\n const abortController = new AbortController();\n const timeoutId = setTimeout(() => {\n abortController.abort();\n }, CanopyApiGateway.REQUEST_TIMEOUT_MILLISECONDS);\n\n let response: Response;\n try {\n response = await fetch(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ ...body, projectId: env.PROJECT_ID }),\n signal: abortController.signal,\n });\n } catch (error) {\n throw new UnknownCanopyApiError({\n message: `Failed to POST cart operation to ${url}: ${error}`,\n cause: error,\n });\n } finally {\n clearTimeout(timeoutId);\n }\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n throw new CanopyApiGatewayError({\n message: `Cart operation ${path} failed: ${response.status} ${response.statusText} \u2014 ${text}`,\n statusCode: response.status,\n });\n }\n\n // Legacy cast - may or may not be necessary\n // eslint-disable-next-line replo/no-as-cast\n const json = (await response.json()) as { data: unknown };\n return cartSchema.parse(json.data);\n }\n\n async cartGet({ cartId }: { cartId: string }): Promise<Cart | null> {\n try {\n return await this._cartPost(\"/get\", { cartId });\n } catch (error) {\n if (error instanceof CanopyApiGatewayError && error.statusCode === 404) {\n return null;\n }\n throw error;\n }\n }\n\n async cartCreate(options?: {\n lines?: {\n merchandiseId: string;\n quantity: number;\n attributes?: { key: string; value: string }[];\n sellingPlanId?: string | null;\n }[];\n discountCodes?: string[];\n }): Promise<Cart> {\n return this._cartPost(\"/create\", {\n lines: options?.lines,\n discountCodes: options?.discountCodes,\n });\n }\n\n async cartAddLines({\n cartId,\n lines,\n }: {\n cartId: string;\n lines: {\n merchandiseId: string;\n quantity: number;\n attributes?: { key: string; value: string }[];\n sellingPlanId?: string | null;\n }[];\n }): Promise<Cart> {\n return this._cartPost(\"/add-lines\", { cartId, lines });\n }\n\n async cartUpdateLines({\n cartId,\n lines,\n }: {\n cartId: string;\n lines: {\n lineId: string;\n quantity: number;\n attributes?: { key: string; value: string }[];\n sellingPlanId?: string | null;\n }[];\n }): Promise<Cart> {\n return this._cartPost(\"/update-lines\", { cartId, lines });\n }\n\n async cartRemoveLines({\n cartId,\n lineIds,\n }: {\n cartId: string;\n lineIds: string[];\n }): Promise<Cart> {\n return this._cartPost(\"/remove-lines\", { cartId, lineIds });\n }\n\n async cartUpdateDiscountCodes({\n cartId,\n discountCodes,\n }: {\n cartId: string;\n discountCodes: string[];\n }): Promise<Cart> {\n return this._cartPost(\"/update-discount-codes\", { cartId, discountCodes });\n }\n}\n\nexport async function getCanopyApiGateway() {\n return CanopyApiGateway.setup();\n}\n"],
5
+ "mappings": "AAEA,SAAS,SAAS;AAElB,SAAS,kBAAkB;AAC3B,SAAS,cAAc;AACvB,SAAS,mBAAmB;AAC5B,SAAS,oBAAoB;AAStB,MAAM,8BAA8B,YAAY;AAAA,EACrD;AAAA,EAEA,YAAY,QAAqC;AAC/C,UAAM,qBAAqB,OAAO,cAAc;AAChD,UAAM;AAAA,MACJ,SAAS,OAAO;AAAA,MAChB,OAAO,OAAO;AAAA,MACd,gBAAgB;AAAA,QACd,GAAG,OAAO;AAAA,QACV,YAAY;AAAA,MACd;AAAA,IACF,CAAC;AACD,SAAK,aAAa;AAAA,EACpB;AACF;AAEA,MAAM,8BAA8B,sBAAsB;AAAA,EACxD,YAAY,QAAyD;AACnE,UAAM,EAAE,GAAG,QAAQ,YAAY,IAAI,CAAC;AAAA,EACtC;AACF;AAEA,MAAM,6BAA6B,EAAE,OAAO;AAAA,EAC1C,MAAM,EAAE,QAAQ;AAAA,EAChB,MAAM,EACH,OAAO;AAAA,IACN,OAAO,EAAE,OAAO;AAAA,MACd,KAAK,EAAE,QAAQ;AAAA,MACf,YAAY,EAAE,OAAO;AAAA,IACvB,CAAC;AAAA,EACH,CAAC,EACA,SAAS;AACd,CAAC;AAED,MAAM,iBAAiB;AAAA,EACb;AAAA,E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AAAA,EACF,GAGkB;AAChB,WAAO,KAAK,UAAU,iBAAiB,EAAE,QAAQ,QAAQ,CAAC;AAAA,EAC5D;AAAA,EAEA,MAAM,wBAAwB;AAAA,IAC5B;AAAA,IACA;AAAA,EACF,GAGkB;AAChB,WAAO,KAAK,UAAU,0BAA0B,EAAE,QAAQ,cAAc,CAAC;AAAA,EAC3E;AACF;AAEA,eAAsB,sBAAsB;AAC1C,SAAO,iBAAiB,MAAM;AAChC;",
6
6
  "names": []
7
7
  }
@@ -1,7 +1,7 @@
1
1
  export const BUILD_METADATA = {
2
2
  "packageName": "@replohq/sdk",
3
- "version": "1.2.3",
3
+ "version": "1.3.1",
4
4
  "branch": "HEAD",
5
- "commit": "8bbee68d9aafb3c6dc7fcb3216a20bb46b70ba8a",
6
- "builtAt": "2026-09-04T19:41:23.624Z"
5
+ "commit": "302ac40cbc8324340e402864bed7b955020c6196",
6
+ "builtAt": "2026-09-05T00:51:07.446Z"
7
7
  };
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@replohq/sdk",
3
- "version": "1.2.3",
3
+ "version": "1.3.1",
4
4
  "reploBuild": {
5
5
  "packageName": "@replohq/sdk",
6
- "version": "1.2.3",
6
+ "version": "1.3.1",
7
7
  "branch": "HEAD",
8
- "commit": "8bbee68d9aafb3c6dc7fcb3216a20bb46b70ba8a",
9
- "builtAt": "2026-09-04T19:41:23.624Z"
8
+ "commit": "302ac40cbc8324340e402864bed7b955020c6196",
9
+ "builtAt": "2026-09-05T00:51:07.446Z"
10
10
  },
11
11
  "description": "Replo SDK — cart, analytics, and data loaders for agent-built Next.js sites.",
12
12
  "license": "SEE LICENSE IN LICENSE",