@replohq/canopy-sdk 0.2.1 → 0.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,4 +1,4 @@
1
- import { priceSchema, metafieldSchema, imageSchema, selectedOptionSchema, mediaSchema, productOptionSchema, productSchema } from '../../../../../chunk-46YU2W6T.mjs';
1
+ import { priceSchema, metafieldSchema, imageSchema, selectedOptionSchema, mediaSchema, productOptionSchema, productSchema } from '../../../../../chunk-7WEM5FUJ.mjs';
2
2
  import { sellingPlanGroupSchema } from '../../../../../chunk-4TZVNC3W.mjs';
3
3
  import { z } from 'zod';
4
4
 
@@ -330,6 +330,8 @@ export declare const DESIGN_LIBRARY_PREVIEW_MESSAGE_TYPE = "replo:design-library
330
330
  export declare const designLibraryPreviewFontSchema: z.ZodObject<{
331
331
  family: z.ZodString;
332
332
  cssVar: z.ZodString;
333
+ faceUrl: z.ZodOptional<z.ZodString>;
334
+ format: z.ZodOptional<z.ZodString>;
333
335
  }, z.core.$strip>;
334
336
  export declare const designLibraryPreviewMessageSchema: z.ZodObject<{
335
337
  type: z.ZodLiteral<"replo:design-library:applyOverrides">;
@@ -337,6 +339,8 @@ export declare const designLibraryPreviewMessageSchema: z.ZodObject<{
337
339
  fonts: z.ZodArray<z.ZodObject<{
338
340
  family: z.ZodString;
339
341
  cssVar: z.ZodString;
342
+ faceUrl: z.ZodOptional<z.ZodString>;
343
+ format: z.ZodOptional<z.ZodString>;
340
344
  }, z.core.$strip>>;
341
345
  defaultFontCssVar: z.ZodNullable<z.ZodString>;
342
346
  }, z.core.$strip>;
@@ -102,7 +102,9 @@ var globalsCssSnapshotSchema = z.object({
102
102
  var DESIGN_LIBRARY_PREVIEW_MESSAGE_TYPE = "replo:design-library:applyOverrides";
103
103
  var designLibraryPreviewFontSchema = z.object({
104
104
  family: z.string(),
105
- cssVar: z.string()
105
+ cssVar: z.string(),
106
+ faceUrl: z.string().optional(),
107
+ format: z.string().optional()
106
108
  }).describe("DesignLibraryPreviewFont");
107
109
  var designLibraryPreviewMessageSchema = z.object({
108
110
  type: z.literal(DESIGN_LIBRARY_PREVIEW_MESSAGE_TYPE),
@@ -22,3 +22,29 @@ export type ReploScriptEntry = {
22
22
  src?: string;
23
23
  body?: string;
24
24
  };
25
+ export type ConsentAction = "accept" | "reject" | "update" | "withdraw";
26
+ export type ConsentRecordRequest = {
27
+ consentId: string;
28
+ projectId: string;
29
+ decidedAt: number;
30
+ action: ConsentAction;
31
+ categories: {
32
+ [x: string]: boolean;
33
+ };
34
+ consentMode: ConsentMode;
35
+ policyVersion: number;
36
+ };
37
+ export type ConsentEventMessage = {
38
+ consentId: string;
39
+ projectId: string;
40
+ decidedAt: number;
41
+ action: ConsentAction;
42
+ categories: {
43
+ [x: string]: boolean;
44
+ };
45
+ consentMode: ConsentMode;
46
+ policyVersion: number;
47
+ useragent: string;
48
+ referrer: string;
49
+ ipCountry: string;
50
+ };
@@ -400,6 +400,29 @@ export declare const intelligemsExperienceSchema: z.ZodObject<{
400
400
  category: z.ZodOptional<z.ZodString>;
401
401
  status: z.ZodOptional<z.ZodString>;
402
402
  }, z.core.$strip>;
403
+ export declare const customerIoSegmentSchema: z.ZodObject<{
404
+ id: z.ZodString;
405
+ name: z.ZodOptional<z.ZodString>;
406
+ description: z.ZodOptional<z.ZodString>;
407
+ type: z.ZodOptional<z.ZodString>;
408
+ }, z.core.$strip>;
409
+ export declare const customerIoCampaignSchema: z.ZodObject<{
410
+ id: z.ZodString;
411
+ name: z.ZodOptional<z.ZodString>;
412
+ type: z.ZodOptional<z.ZodString>;
413
+ active: z.ZodOptional<z.ZodBoolean>;
414
+ }, z.core.$strip>;
415
+ export declare const customerIoBroadcastSchema: z.ZodObject<{
416
+ id: z.ZodString;
417
+ name: z.ZodOptional<z.ZodString>;
418
+ active: z.ZodOptional<z.ZodBoolean>;
419
+ }, z.core.$strip>;
420
+ export declare const vwoCampaignSchema: z.ZodObject<{
421
+ id: z.ZodString;
422
+ name: z.ZodOptional<z.ZodString>;
423
+ type: z.ZodOptional<z.ZodString>;
424
+ status: z.ZodOptional<z.ZodString>;
425
+ }, z.core.$strip>;
403
426
  export declare const okendoReviewSchema: z.ZodObject<{
404
427
  id: z.ZodString;
405
428
  title: z.ZodOptional<z.ZodString>;
@@ -410,6 +433,16 @@ export declare const okendoReviewSchema: z.ZodObject<{
410
433
  dateCreated: z.ZodOptional<z.ZodString>;
411
434
  status: z.ZodOptional<z.ZodString>;
412
435
  }, z.core.$strip>;
436
+ export declare const looxReviewSchema: z.ZodObject<{
437
+ id: z.ZodString;
438
+ title: z.ZodOptional<z.ZodString>;
439
+ body: z.ZodOptional<z.ZodString>;
440
+ rating: z.ZodOptional<z.ZodNumber>;
441
+ productName: z.ZodOptional<z.ZodString>;
442
+ reviewerName: z.ZodOptional<z.ZodString>;
443
+ dateCreated: z.ZodOptional<z.ZodString>;
444
+ status: z.ZodOptional<z.ZodString>;
445
+ }, z.core.$strip>;
413
446
  export declare const planSchema: z.ZodObject<{
414
447
  id: z.ZodString;
415
448
  name: z.ZodOptional<z.ZodString>;
@@ -800,6 +833,61 @@ declare const OBJECT_TYPE_REGISTRY: {
800
833
  }, z.core.$strip>;
801
834
  mentionable: true;
802
835
  };
836
+ customerIoSegment: {
837
+ type: string;
838
+ displayName: string;
839
+ identifiers: {
840
+ primaryId: string;
841
+ };
842
+ canonicalSchema: z.ZodObject<{
843
+ id: z.ZodString;
844
+ name: z.ZodOptional<z.ZodString>;
845
+ description: z.ZodOptional<z.ZodString>;
846
+ type: z.ZodOptional<z.ZodString>;
847
+ }, z.core.$strip>;
848
+ mentionable: true;
849
+ };
850
+ customerIoCampaign: {
851
+ type: string;
852
+ displayName: string;
853
+ identifiers: {
854
+ primaryId: string;
855
+ };
856
+ canonicalSchema: z.ZodObject<{
857
+ id: z.ZodString;
858
+ name: z.ZodOptional<z.ZodString>;
859
+ type: z.ZodOptional<z.ZodString>;
860
+ active: z.ZodOptional<z.ZodBoolean>;
861
+ }, z.core.$strip>;
862
+ mentionable: true;
863
+ };
864
+ customerIoBroadcast: {
865
+ type: string;
866
+ displayName: string;
867
+ identifiers: {
868
+ primaryId: string;
869
+ };
870
+ canonicalSchema: z.ZodObject<{
871
+ id: z.ZodString;
872
+ name: z.ZodOptional<z.ZodString>;
873
+ active: z.ZodOptional<z.ZodBoolean>;
874
+ }, z.core.$strip>;
875
+ mentionable: true;
876
+ };
877
+ vwoCampaign: {
878
+ type: string;
879
+ displayName: string;
880
+ identifiers: {
881
+ primaryId: string;
882
+ };
883
+ canonicalSchema: z.ZodObject<{
884
+ id: z.ZodString;
885
+ name: z.ZodOptional<z.ZodString>;
886
+ type: z.ZodOptional<z.ZodString>;
887
+ status: z.ZodOptional<z.ZodString>;
888
+ }, z.core.$strip>;
889
+ mentionable: true;
890
+ };
803
891
  levantaProduct: {
804
892
  type: string;
805
893
  displayName: string;
@@ -844,6 +932,24 @@ declare const OBJECT_TYPE_REGISTRY: {
844
932
  }, z.core.$strip>;
845
933
  mentionable: true;
846
934
  };
935
+ looxReview: {
936
+ type: string;
937
+ displayName: string;
938
+ identifiers: {
939
+ primaryId: string;
940
+ };
941
+ canonicalSchema: z.ZodObject<{
942
+ id: z.ZodString;
943
+ title: z.ZodOptional<z.ZodString>;
944
+ body: z.ZodOptional<z.ZodString>;
945
+ rating: z.ZodOptional<z.ZodNumber>;
946
+ productName: z.ZodOptional<z.ZodString>;
947
+ reviewerName: z.ZodOptional<z.ZodString>;
948
+ dateCreated: z.ZodOptional<z.ZodString>;
949
+ status: z.ZodOptional<z.ZodString>;
950
+ }, z.core.$strip>;
951
+ mentionable: true;
952
+ };
847
953
  plan: {
848
954
  type: string;
849
955
  displayName: string;
@@ -1,2 +1,2 @@
1
- export { assetSchema, collectionSchema, externalVideoSchema, getObjectTypeDefinition, imageSchema, integrationSchema, intelligemsExperienceSchema, levantaAffiliateLinkSchema, levantaProductSchema, mediaImageSchema, mediaSchema, metafieldSchema, okendoReviewSchema, optionValueSchema, optionValueSwatchSchema, opusClipSchema, opusCollectionSchema, opusProjectSchema, pageSchema, planSchema, previewImageSchema, priceSchema, productOptionSchema, productSchema, registryItemSchema, segmentSourceSchema, selectedOptionSchema, transformReploProductToCanonical, variantSchema, videoSchema, videoSourceSchema } from '../../chunk-46YU2W6T.mjs';
1
+ export { assetSchema, collectionSchema, customerIoBroadcastSchema, customerIoCampaignSchema, customerIoSegmentSchema, externalVideoSchema, getObjectTypeDefinition, imageSchema, integrationSchema, intelligemsExperienceSchema, levantaAffiliateLinkSchema, levantaProductSchema, looxReviewSchema, mediaImageSchema, mediaSchema, metafieldSchema, okendoReviewSchema, optionValueSchema, optionValueSwatchSchema, opusClipSchema, opusCollectionSchema, opusProjectSchema, pageSchema, planSchema, previewImageSchema, priceSchema, productOptionSchema, productSchema, registryItemSchema, segmentSourceSchema, selectedOptionSchema, transformReploProductToCanonical, variantSchema, videoSchema, videoSourceSchema, vwoCampaignSchema } from '../../chunk-7WEM5FUJ.mjs';
2
2
  import '../../chunk-4TZVNC3W.mjs';
@@ -299,6 +299,29 @@ var intelligemsExperienceSchema = z.object({
299
299
  category: z.string().optional(),
300
300
  status: z.string().optional()
301
301
  }).describe("IntelligemsExperience");
302
+ var customerIoSegmentSchema = z.object({
303
+ id: z.string().describe("customerIoSegment primaryId"),
304
+ name: z.string().optional(),
305
+ description: z.string().optional(),
306
+ type: z.string().optional()
307
+ }).describe("CustomerIoSegment");
308
+ var customerIoCampaignSchema = z.object({
309
+ id: z.string().describe("customerIoCampaign primaryId"),
310
+ name: z.string().optional(),
311
+ type: z.string().optional(),
312
+ active: z.boolean().optional()
313
+ }).describe("CustomerIoCampaign");
314
+ var customerIoBroadcastSchema = z.object({
315
+ id: z.string().describe("customerIoBroadcast primaryId"),
316
+ name: z.string().optional(),
317
+ active: z.boolean().optional()
318
+ }).describe("CustomerIoBroadcast");
319
+ var vwoCampaignSchema = z.object({
320
+ id: z.string(),
321
+ name: z.string().optional(),
322
+ type: z.string().optional(),
323
+ status: z.string().optional()
324
+ }).describe("VwoCampaign");
302
325
  var okendoReviewSchema = z.object({
303
326
  id: z.string(),
304
327
  title: z.string().optional(),
@@ -309,6 +332,16 @@ var okendoReviewSchema = z.object({
309
332
  dateCreated: z.string().optional(),
310
333
  status: z.string().optional()
311
334
  }).describe("OkendoReview");
335
+ var looxReviewSchema = z.object({
336
+ id: z.string(),
337
+ title: z.string().optional(),
338
+ body: z.string().optional(),
339
+ rating: z.number().optional(),
340
+ productName: z.string().optional(),
341
+ reviewerName: z.string().optional(),
342
+ dateCreated: z.string().optional(),
343
+ status: z.string().optional()
344
+ }).describe("LooxReview");
312
345
  var planSchema = z.object({
313
346
  id: z.string(),
314
347
  name: z.string().optional(),
@@ -435,6 +468,42 @@ var OBJECT_TYPE_REGISTRY = {
435
468
  canonicalSchema: intelligemsExperienceSchema,
436
469
  mentionable: true
437
470
  },
471
+ customerIoSegment: {
472
+ type: "customerIoSegment",
473
+ displayName: "Customer.io Segment",
474
+ identifiers: {
475
+ primaryId: "id"
476
+ },
477
+ canonicalSchema: customerIoSegmentSchema,
478
+ mentionable: true
479
+ },
480
+ customerIoCampaign: {
481
+ type: "customerIoCampaign",
482
+ displayName: "Customer.io Campaign",
483
+ identifiers: {
484
+ primaryId: "id"
485
+ },
486
+ canonicalSchema: customerIoCampaignSchema,
487
+ mentionable: true
488
+ },
489
+ customerIoBroadcast: {
490
+ type: "customerIoBroadcast",
491
+ displayName: "Customer.io Broadcast",
492
+ identifiers: {
493
+ primaryId: "id"
494
+ },
495
+ canonicalSchema: customerIoBroadcastSchema,
496
+ mentionable: true
497
+ },
498
+ vwoCampaign: {
499
+ type: "vwoCampaign",
500
+ displayName: "VWO Campaign",
501
+ identifiers: {
502
+ primaryId: "id"
503
+ },
504
+ canonicalSchema: vwoCampaignSchema,
505
+ mentionable: true
506
+ },
438
507
  levantaProduct: {
439
508
  type: "levantaProduct",
440
509
  displayName: "Levanta Product",
@@ -453,6 +522,15 @@ var OBJECT_TYPE_REGISTRY = {
453
522
  canonicalSchema: okendoReviewSchema,
454
523
  mentionable: true
455
524
  },
525
+ looxReview: {
526
+ type: "looxReview",
527
+ displayName: "Loox Review",
528
+ identifiers: {
529
+ primaryId: "id"
530
+ },
531
+ canonicalSchema: looxReviewSchema,
532
+ mentionable: true
533
+ },
456
534
  plan: {
457
535
  type: "plan",
458
536
  displayName: "Plan",
@@ -535,4 +613,4 @@ function transformReploProductToCanonical(product) {
535
613
  };
536
614
  }
537
615
 
538
- export { assetSchema, collectionSchema, externalVideoSchema, getObjectTypeDefinition, imageSchema, integrationSchema, intelligemsExperienceSchema, levantaAffiliateLinkSchema, levantaProductSchema, mediaImageSchema, mediaSchema, metafieldSchema, okendoReviewSchema, optionValueSchema, optionValueSwatchSchema, opusClipSchema, opusCollectionSchema, opusProjectSchema, pageSchema, planSchema, previewImageSchema, priceSchema, productOptionSchema, productSchema, registryItemSchema, segmentSourceSchema, selectedOptionSchema, transformReploProductToCanonical, variantSchema, videoSchema, videoSourceSchema };
616
+ export { assetSchema, collectionSchema, customerIoBroadcastSchema, customerIoCampaignSchema, customerIoSegmentSchema, externalVideoSchema, getObjectTypeDefinition, imageSchema, integrationSchema, intelligemsExperienceSchema, levantaAffiliateLinkSchema, levantaProductSchema, looxReviewSchema, mediaImageSchema, mediaSchema, metafieldSchema, okendoReviewSchema, optionValueSchema, optionValueSwatchSchema, opusClipSchema, opusCollectionSchema, opusProjectSchema, pageSchema, planSchema, previewImageSchema, priceSchema, productOptionSchema, productSchema, registryItemSchema, segmentSourceSchema, selectedOptionSchema, transformReploProductToCanonical, variantSchema, videoSchema, videoSourceSchema, vwoCampaignSchema };
@@ -0,0 +1,9 @@
1
+ import type { ConsentAction } from "../_vendor/schemas/generated/consent";
2
+ import type { ConsentCategories } from "./cookie";
3
+ export declare function deriveConsentAction({ previous, next, }: {
4
+ previous: {
5
+ decidedAt: number | null;
6
+ categories: ConsentCategories;
7
+ };
8
+ next: ConsentCategories;
9
+ }): ConsentAction;
@@ -0,0 +1,25 @@
1
+ const NON_NECESSARY_CATEGORIES = [
2
+ "analytics",
3
+ "marketing",
4
+ "preferences",
5
+ "sale_of_data"
6
+ ];
7
+ function deriveConsentAction({
8
+ previous,
9
+ next
10
+ }) {
11
+ const anyGranted = NON_NECESSARY_CATEGORIES.some(
12
+ (category) => next[category]
13
+ );
14
+ if (previous.decidedAt === null) {
15
+ return anyGranted ? "accept" : "reject";
16
+ }
17
+ if (!anyGranted) {
18
+ return "withdraw";
19
+ }
20
+ return "update";
21
+ }
22
+ export {
23
+ deriveConsentAction
24
+ };
25
+ //# sourceMappingURL=consent-action.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../consent/consent-action.ts"],
4
+ "sourcesContent": ["import type { ConsentAction, ConsentCategory } from \"schemas/generated/consent\";\nimport type { ConsentCategories } from \"./cookie\";\n\n/**\n * Pure mapping from a consent decision (previous state vs the resulting state)\n * to the legal-record `action` written to the proof-of-consent audit log.\n *\n * Only non-necessary categories matter (`necessary` is always granted). The\n * mapping is:\n * - first decision (`decidedAt === null`), some category granted -> \"accept\"\n * - first decision, nothing granted -> \"reject\"\n * - later decision that leaves nothing granted -> \"withdraw\"\n * - any other later change -> \"update\"\n *\n * `withdraw` is reserved for going from some consent to none (the GDPR\n * withdrawal right); a partial reduction that still leaves something granted is\n * an `update`.\n */\nconst NON_NECESSARY_CATEGORIES: Exclude<ConsentCategory, \"necessary\">[] = [\n \"analytics\",\n \"marketing\",\n \"preferences\",\n \"sale_of_data\",\n];\n\nexport function deriveConsentAction({\n previous,\n next,\n}: {\n previous: { decidedAt: number | null; categories: ConsentCategories };\n next: ConsentCategories;\n}): ConsentAction {\n const anyGranted = NON_NECESSARY_CATEGORIES.some(\n (category) => next[category],\n );\n\n if (previous.decidedAt === null) {\n return anyGranted ? \"accept\" : \"reject\";\n }\n if (!anyGranted) {\n return \"withdraw\";\n }\n return \"update\";\n}\n"],
5
+ "mappings": "AAkBA,MAAM,2BAAoE;AAAA,EACxE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,SAAS,oBAAoB;AAAA,EAClC;AAAA,EACA;AACF,GAGkB;AAChB,QAAM,aAAa,yBAAyB;AAAA,IAC1C,CAAC,aAAa,KAAK,QAAQ;AAAA,EAC7B;AAEA,MAAI,SAAS,cAAc,MAAM;AAC/B,WAAO,aAAa,WAAW;AAAA,EACjC;AACA,MAAI,CAAC,YAAY;AACf,WAAO;AAAA,EACT;AACA,SAAO;AACT;",
6
+ "names": []
7
+ }
@@ -0,0 +1,22 @@
1
+ import type { ConsentAction, ConsentMode } from "../_vendor/schemas/generated/consent";
2
+ import type { ConsentCategories } from "./cookie";
3
+ /**
4
+ * Records a proof-of-consent decision by forwarding it to analytics-fire.
5
+ *
6
+ * Runs server-side — exactly like the cart's actions — so the browser never needs
7
+ * the project id or the analytics-fire URL: both are read from the worker env
8
+ * here via `getEnv()`. The visitor's user-agent / referrer / coarse geo come from
9
+ * the incoming request headers and are forwarded so analytics-fire derives them
10
+ * the same way it does for the legacy pixel.
11
+ *
12
+ * Best-effort and self-disabling: no-ops when analytics-fire isn't configured
13
+ * (e.g. lean local dev) and never throws into the page.
14
+ */
15
+ export declare function recordConsentAction(decision: {
16
+ consentId: string;
17
+ action: ConsentAction;
18
+ /** Full resulting consent state (all categories), not a diff. */
19
+ categories: ConsentCategories;
20
+ consentMode: ConsentMode;
21
+ decidedAt: number;
22
+ }): Promise<void>;
@@ -0,0 +1,37 @@
1
+ "use server";
2
+ import { headers } from "next/headers";
3
+ import { getEnv } from "../env";
4
+ const CONSENT_POLICY_VERSION = 1;
5
+ async function recordConsentAction(decision) {
6
+ try {
7
+ const { PROJECT_ID, ANALYTICS_FIRE_API_URL } = await getEnv();
8
+ if (!ANALYTICS_FIRE_API_URL) {
9
+ return;
10
+ }
11
+ const incoming = await headers();
12
+ const body = {
13
+ consentId: decision.consentId,
14
+ projectId: PROJECT_ID,
15
+ decidedAt: decision.decidedAt,
16
+ action: decision.action,
17
+ categories: decision.categories,
18
+ consentMode: decision.consentMode,
19
+ policyVersion: CONSENT_POLICY_VERSION
20
+ };
21
+ await fetch(`${ANALYTICS_FIRE_API_URL}/api/v1/consent`, {
22
+ method: "POST",
23
+ headers: {
24
+ "content-type": "application/json",
25
+ "user-agent": incoming.get("user-agent") ?? "",
26
+ referer: incoming.get("referer") ?? "",
27
+ "cf-ipcountry": incoming.get("cf-ipcountry") ?? ""
28
+ },
29
+ body: JSON.stringify(body)
30
+ });
31
+ } catch {
32
+ }
33
+ }
34
+ export {
35
+ recordConsentAction
36
+ };
37
+ //# sourceMappingURL=consent-actions.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../consent/consent-actions.ts"],
4
+ "sourcesContent": ["\"use server\";\n\nimport type {\n ConsentAction,\n ConsentMode,\n ConsentRecordRequest,\n} from \"schemas/generated/consent\";\nimport type { ConsentCategories } from \"./cookie\";\n\nimport { headers } from \"next/headers\";\n\nimport { getEnv } from \"../env\";\n\n// Bumped when the banner copy or category set changes. Lives here (server-side)\n// so the site layout never has to carry a policy version.\nconst CONSENT_POLICY_VERSION = 1;\n\n/**\n * Records a proof-of-consent decision by forwarding it to analytics-fire.\n *\n * Runs server-side \u2014 exactly like the cart's actions \u2014 so the browser never needs\n * the project id or the analytics-fire URL: both are read from the worker env\n * here via `getEnv()`. The visitor's user-agent / referrer / coarse geo come from\n * the incoming request headers and are forwarded so analytics-fire derives them\n * the same way it does for the legacy pixel.\n *\n * Best-effort and self-disabling: no-ops when analytics-fire isn't configured\n * (e.g. lean local dev) and never throws into the page.\n */\nexport async function recordConsentAction(decision: {\n consentId: string;\n action: ConsentAction;\n /** Full resulting consent state (all categories), not a diff. */\n categories: ConsentCategories;\n consentMode: ConsentMode;\n decidedAt: number;\n}) {\n // Best-effort and total: never reject (the caller fire-and-forgets it), even if\n // the Cloudflare env / request context is unavailable.\n try {\n const { PROJECT_ID, ANALYTICS_FIRE_API_URL } = await getEnv();\n if (!ANALYTICS_FIRE_API_URL) {\n return;\n }\n\n const incoming = await headers();\n const body: ConsentRecordRequest = {\n consentId: decision.consentId,\n projectId: PROJECT_ID,\n decidedAt: decision.decidedAt,\n action: decision.action,\n categories: decision.categories,\n consentMode: decision.consentMode,\n policyVersion: CONSENT_POLICY_VERSION,\n };\n\n await fetch(`${ANALYTICS_FIRE_API_URL}/api/v1/consent`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n \"user-agent\": incoming.get(\"user-agent\") ?? \"\",\n referer: incoming.get(\"referer\") ?? \"\",\n \"cf-ipcountry\": incoming.get(\"cf-ipcountry\") ?? \"\",\n },\n body: JSON.stringify(body),\n });\n } catch {\n // Consent logging must never surface an error in the page.\n }\n}\n"],
5
+ "mappings": ";AASA,SAAS,eAAe;AAExB,SAAS,cAAc;AAIvB,MAAM,yBAAyB;AAc/B,eAAsB,oBAAoB,UAOvC;AAGD,MAAI;AACF,UAAM,EAAE,YAAY,uBAAuB,IAAI,MAAM,OAAO;AAC5D,QAAI,CAAC,wBAAwB;AAC3B;AAAA,IACF;AAEA,UAAM,WAAW,MAAM,QAAQ;AAC/B,UAAM,OAA6B;AAAA,MACjC,WAAW,SAAS;AAAA,MACpB,WAAW;AAAA,MACX,WAAW,SAAS;AAAA,MACpB,QAAQ,SAAS;AAAA,MACjB,YAAY,SAAS;AAAA,MACrB,aAAa,SAAS;AAAA,MACtB,eAAe;AAAA,IACjB;AAEA,UAAM,MAAM,GAAG,sBAAsB,mBAAmB;AAAA,MACtD,QAAQ;AAAA,MACR,SAAS;AAAA,QACP,gBAAgB;AAAA,QAChB,cAAc,SAAS,IAAI,YAAY,KAAK;AAAA,QAC5C,SAAS,SAAS,IAAI,SAAS,KAAK;AAAA,QACpC,gBAAgB,SAAS,IAAI,cAAc,KAAK;AAAA,MAClD;AAAA,MACA,MAAM,KAAK,UAAU,IAAI;AAAA,IAC3B,CAAC;AAAA,EACH,QAAQ;AAAA,EAER;AACF;",
6
+ "names": []
7
+ }
@@ -1,5 +1,5 @@
1
1
  import type { ConsentCategory, ConsentMode } from "../_vendor/schemas/generated/consent";
2
- import type { ConsentCategories, ConsentSeed } from "./cookie";
2
+ import type { ConsentCategories } from "./cookie";
3
3
  /**
4
4
  * Framework-agnostic, cookie-backed consent store. Lives as a single module
5
5
  * singleton so `ReploScripts`, the site's consent banner, and `AnalyticsProvider`
@@ -8,19 +8,21 @@ import type { ConsentCategories, ConsentSeed } from "./cookie";
8
8
  *
9
9
  * Consent-dependent work (script injection, banner visibility) happens on the
10
10
  * client (effects / post-mount), so there is no SSR/hydration mismatch. The
11
- * server-seeded `window.__REPLO_CONSENT__` (see ./server) only lets the first
12
- * client snapshot reflect the cookie without a flash.
11
+ * client reads the (non-httpOnly) consent cookie directly, so no server seed is
12
+ * needed. The whole-site `mode` comes from the `data-replo-consent-mode`
13
+ * attribute on `<html>`.
13
14
  */
14
15
  export interface ConsentState {
15
16
  mode: ConsentMode;
16
17
  categories: ConsentCategories;
17
18
  /** Epoch ms when the visitor last made a choice, or null if undecided. */
18
19
  decidedAt: number | null;
19
- }
20
- declare global {
21
- interface Window {
22
- __REPLO_CONSENT__?: ConsentSeed;
23
- }
20
+ /**
21
+ * Persistent pseudonymous per-browser id linking a visitor's consent history.
22
+ * Absent until the first `commit()` (and on legacy pre-id cookies, until the
23
+ * next interaction lazily backfills it).
24
+ */
25
+ consentId?: string;
24
26
  }
25
27
  export declare const consentStore: {
26
28
  getSnapshot(): ConsentState;
@@ -1,5 +1,7 @@
1
1
  "use client";
2
2
  import { useSyncExternalStore } from "react";
3
+ import { deriveConsentAction } from "./consent-action";
4
+ import { recordConsentAction } from "./consent-actions";
3
5
  import {
4
6
  CONSENT_COOKIE_MAX_AGE_SECONDS,
5
7
  CONSENT_COOKIE_NAME,
@@ -28,10 +30,6 @@ function resolveMode() {
28
30
  if (typeof window === "undefined") {
29
31
  return "off";
30
32
  }
31
- const seedMode = window.__REPLO_CONSENT__?.mode;
32
- if (isConsentMode(seedMode)) {
33
- return seedMode;
34
- }
35
33
  const attribute = document.documentElement.dataset.reploConsentMode;
36
34
  return isConsentMode(attribute) ? attribute : "off";
37
35
  }
@@ -51,24 +49,21 @@ function computeSnapshot() {
51
49
  preferences: fromCookie.categories.preferences,
52
50
  sale_of_data: fromCookie.categories.sale_of_data
53
51
  },
54
- decidedAt: fromCookie.decidedAt
55
- };
56
- }
57
- const seed = window.__REPLO_CONSENT__;
58
- if (seed) {
59
- return {
60
- mode,
61
- categories: { ...DENIED_CATEGORIES, ...seed.categories, necessary: true },
62
- decidedAt: seed.decidedAt
52
+ decidedAt: fromCookie.decidedAt,
53
+ consentId: fromCookie.consentId
63
54
  };
64
55
  }
65
56
  return { mode, categories: DENIED_CATEGORIES, decidedAt: null };
66
57
  }
67
- function writeCookie(categories, decidedAt) {
58
+ function writeCookie(categories, decidedAt, consentId) {
68
59
  if (typeof document === "undefined") {
69
60
  return;
70
61
  }
71
- const value = serializeConsentCookieValue({ categories, decidedAt });
62
+ const value = serializeConsentCookieValue({
63
+ categories,
64
+ decidedAt,
65
+ consentId
66
+ });
72
67
  document.cookie = `${CONSENT_COOKIE_NAME}=${value}; path=/; max-age=${CONSENT_COOKIE_MAX_AGE_SECONDS}; SameSite=Lax`;
73
68
  }
74
69
  function notify() {
@@ -79,18 +74,37 @@ function notify() {
79
74
  function commit(categories) {
80
75
  const previous = consentStore.getSnapshot();
81
76
  const decidedAt = Date.now();
82
- writeCookie(categories, decidedAt);
77
+ const consentId = previous.consentId ?? crypto.randomUUID();
78
+ const resultingCategories = {
79
+ ...categories,
80
+ necessary: true
81
+ };
82
+ writeCookie(categories, decidedAt, consentId);
83
83
  snapshot = {
84
84
  mode: previous.mode,
85
- categories: { ...categories, necessary: true },
86
- decidedAt
85
+ categories: resultingCategories,
86
+ decidedAt,
87
+ consentId
87
88
  };
88
89
  notify();
89
90
  const wasDowngrade = previous.decidedAt !== null && TOGGLEABLE_CATEGORIES.some((category) => {
90
91
  return previous.categories[category] && !categories[category];
91
92
  });
92
- if (wasDowngrade && typeof window !== "undefined") {
93
- window.location.reload();
93
+ const reloadIfDowngraded = () => {
94
+ if (wasDowngrade && typeof window !== "undefined") {
95
+ window.location.reload();
96
+ }
97
+ };
98
+ if (previous.mode !== "off") {
99
+ void recordConsentAction({
100
+ consentId,
101
+ action: deriveConsentAction({ previous, next: resultingCategories }),
102
+ categories: resultingCategories,
103
+ consentMode: previous.mode,
104
+ decidedAt
105
+ }).finally(reloadIfDowngraded);
106
+ } else {
107
+ reloadIfDowngraded();
94
108
  }
95
109
  }
96
110
  const consentStore = {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../consent/consent-store.ts"],
4
- "sourcesContent": ["\"use client\";\n\nimport type { ConsentCategory, ConsentMode } from \"schemas/generated/consent\";\nimport type { ConsentCategories, ConsentSeed } from \"./cookie\";\n\nimport { useSyncExternalStore } from \"react\";\n\nimport {\n CONSENT_COOKIE_MAX_AGE_SECONDS,\n CONSENT_COOKIE_NAME,\n DENIED_CATEGORIES,\n GRANTED_CATEGORIES,\n parseConsentCookie,\n serializeConsentCookieValue,\n} from \"./cookie\";\n\n/**\n * Framework-agnostic, cookie-backed consent store. Lives as a single module\n * singleton so `ReploScripts`, the site's consent banner, and `AnalyticsProvider`\n * all share the same state regardless of where they sit in the React tree \u2014 no\n * provider-ancestor relationship is required.\n *\n * Consent-dependent work (script injection, banner visibility) happens on the\n * client (effects / post-mount), so there is no SSR/hydration mismatch. The\n * server-seeded `window.__REPLO_CONSENT__` (see ./server) only lets the first\n * client snapshot reflect the cookie without a flash.\n */\n\nexport interface ConsentState {\n mode: ConsentMode;\n categories: ConsentCategories;\n /** Epoch ms when the visitor last made a choice, or null if undecided. */\n decidedAt: number | null;\n}\n\n// The non-necessary categories a visitor can grant or revoke. `necessary` is\n// always granted and never toggled.\nconst TOGGLEABLE_CATEGORIES: Exclude<ConsentCategory, \"necessary\">[] = [\n \"analytics\",\n \"marketing\",\n \"preferences\",\n \"sale_of_data\",\n];\n\ndeclare global {\n interface Window {\n __REPLO_CONSENT__?: ConsentSeed;\n }\n}\n\n// A stable reference for SSR / first hydration render. Consent-dependent DOM is\n// only produced on the client, so this constant never causes a mismatch.\nconst SERVER_SNAPSHOT: ConsentState = Object.freeze({\n mode: \"off\",\n categories: DENIED_CATEGORIES,\n decidedAt: null,\n});\n\nconst listeners = new Set<() => void>();\nlet snapshot: ConsentState | null = null;\n\nfunction isConsentMode(value: string | null | undefined): value is ConsentMode {\n return value === \"off\" || value === \"simple\" || value === \"per-category\";\n}\n\nfunction resolveMode(): ConsentMode {\n if (typeof window === \"undefined\") {\n return \"off\";\n }\n const seedMode = window.__REPLO_CONSENT__?.mode;\n if (isConsentMode(seedMode)) {\n return seedMode;\n }\n const attribute = document.documentElement.dataset.reploConsentMode;\n return isConsentMode(attribute) ? attribute : \"off\";\n}\n\nfunction computeSnapshot(): ConsentState {\n if (typeof window === \"undefined\") {\n return SERVER_SNAPSHOT;\n }\n\n const mode = resolveMode();\n\n const fromCookie = parseConsentCookie(document.cookie);\n if (fromCookie) {\n return {\n mode,\n categories: {\n necessary: true,\n analytics: fromCookie.categories.analytics,\n marketing: fromCookie.categories.marketing,\n preferences: fromCookie.categories.preferences,\n sale_of_data: fromCookie.categories.sale_of_data,\n },\n decidedAt: fromCookie.decidedAt,\n };\n }\n\n const seed = window.__REPLO_CONSENT__;\n if (seed) {\n return {\n mode,\n categories: { ...DENIED_CATEGORIES, ...seed.categories, necessary: true },\n decidedAt: seed.decidedAt,\n };\n }\n\n return { mode, categories: DENIED_CATEGORIES, decidedAt: null };\n}\n\nfunction writeCookie(categories: ConsentCategories, decidedAt: number) {\n if (typeof document === \"undefined\") {\n return;\n }\n const value = serializeConsentCookieValue({ categories, decidedAt });\n document.cookie = `${CONSENT_COOKIE_NAME}=${value}; path=/; max-age=${CONSENT_COOKIE_MAX_AGE_SECONDS}; SameSite=Lax`;\n}\n\nfunction notify() {\n for (const listener of listeners) {\n listener();\n }\n}\n\nfunction commit(categories: ConsentCategories) {\n const previous = consentStore.getSnapshot();\n const decidedAt = Date.now();\n writeCookie(categories, decidedAt);\n snapshot = {\n mode: previous.mode,\n categories: { ...categories, necessary: true },\n decidedAt,\n };\n notify();\n\n // Revocation cannot unload an already-loaded vendor. If the visitor had\n // previously decided and is now turning a granted category off, reload so the\n // page renders without those scripts.\n const wasDowngrade =\n previous.decidedAt !== null &&\n TOGGLEABLE_CATEGORIES.some((category) => {\n return previous.categories[category] && !categories[category];\n });\n if (wasDowngrade && typeof window !== \"undefined\") {\n window.location.reload();\n }\n}\n\nexport const consentStore = {\n getSnapshot(): ConsentState {\n if (!snapshot) {\n snapshot = computeSnapshot();\n }\n return snapshot;\n },\n getServerSnapshot(): ConsentState {\n return SERVER_SNAPSHOT;\n },\n subscribe(listener: () => void): () => void {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n /** Grant every consent category. */\n accept() {\n commit(GRANTED_CATEGORIES);\n },\n /** Deny every non-necessary category. */\n reject() {\n commit(DENIED_CATEGORIES);\n },\n /** Set a subset of categories, leaving the rest at their current value. */\n updateCategories(next: Partial<ConsentCategories>) {\n const current = consentStore.getSnapshot().categories;\n commit({ ...current, ...next, necessary: true });\n },\n /** Test-only: reset cached state so the next read recomputes. */\n reset() {\n snapshot = null;\n },\n};\n\nexport interface UseConsentResult extends ConsentState {\n accept(): void;\n reject(): void;\n updateCategories(next: Partial<ConsentCategories>): void;\n}\n\nexport function useConsent(): UseConsentResult {\n const state = useSyncExternalStore(\n consentStore.subscribe,\n consentStore.getSnapshot,\n consentStore.getServerSnapshot,\n );\n return {\n ...state,\n accept: consentStore.accept,\n reject: consentStore.reject,\n updateCategories: consentStore.updateCategories,\n };\n}\n\n/**\n * Whether a script requiring `requiredConsent` is allowed to load right now.\n * `mode === \"off\"` always allows; otherwise every required category must be\n * granted. An empty requirement list is always allowed.\n */\nexport function isConsentAllowed({\n state,\n requiredConsent,\n}: {\n state: ConsentState;\n requiredConsent: ConsentCategory[];\n}): boolean {\n if (state.mode === \"off\") {\n return true;\n }\n if (requiredConsent.length === 0) {\n return true;\n }\n return requiredConsent.every((category) => state.categories[category]);\n}\n"],
5
- "mappings": ";AAKA,SAAS,4BAA4B;AAErC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAuBP,MAAM,wBAAiE;AAAA,EACrE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAUA,MAAM,kBAAgC,OAAO,OAAO;AAAA,EAClD,MAAM;AAAA,EACN,YAAY;AAAA,EACZ,WAAW;AACb,CAAC;AAED,MAAM,YAAY,oBAAI,IAAgB;AACtC,IAAI,WAAgC;AAEpC,SAAS,cAAc,OAAwD;AAC7E,SAAO,UAAU,SAAS,UAAU,YAAY,UAAU;AAC5D;AAEA,SAAS,cAA2B;AAClC,MAAI,OAAO,WAAW,aAAa;AACjC,WAAO;AAAA,EACT;AACA,QAAM,WAAW,OAAO,mBAAmB;AAC3C,MAAI,cAAc,QAAQ,GAAG;AAC3B,WAAO;AAAA,EACT;AACA,QAAM,YAAY,SAAS,gBAAgB,QAAQ;AACnD,SAAO,cAAc,SAAS,IAAI,YAAY;AAChD;AAEA,SAAS,kBAAgC;AACvC,MAAI,OAAO,WAAW,aAAa;AACjC,WAAO;AAAA,EACT;AAEA,QAAM,OAAO,YAAY;AAEzB,QAAM,aAAa,mBAAmB,SAAS,MAAM;AACrD,MAAI,YAAY;AACd,WAAO;AAAA,MACL;AAAA,MACA,YAAY;AAAA,QACV,WAAW;AAAA,QACX,WAAW,WAAW,WAAW;AAAA,QACjC,WAAW,WAAW,WAAW;AAAA,QACjC,aAAa,WAAW,WAAW;AAAA,QACnC,cAAc,WAAW,WAAW;AAAA,MACtC;AAAA,MACA,WAAW,WAAW;AAAA,IACxB;AAAA,EACF;AAEA,QAAM,OAAO,OAAO;AACpB,MAAI,MAAM;AACR,WAAO;AAAA,MACL;AAAA,MAC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AS;AACP,WAAO,iBAAiB;AAAA,EAC1B;AAAA;AAAA,EAEA,iBAAiB,MAAkC;AACjD,UAAM,UAAU,aAAa,YAAY,EAAE;AAC3C,WAAO,EAAE,GAAG,SAAS,GAAG,MAAM,WAAW,KAAK,CAAC;AAAA,EACjD;AAAA;AAAA,EAEA,QAAQ;AACN,eAAW;AAAA,EACb;AACF;AAQO,SAAS,aAA+B;AAC7C,QAAM,QAAQ;AAAA,IACZ,aAAa;AAAA,IACb,aAAa;AAAA,IACb,aAAa;AAAA,EACf;AACA,SAAO;AAAA,IACL,GAAG;AAAA,IACH,QAAQ,aAAa;AAAA,IACrB,QAAQ,aAAa;AAAA,IACrB,kBAAkB,aAAa;AAAA,EACjC;AACF;AAOO,SAAS,iBAAiB;AAAA,EAC/B;AAAA,EACA;AACF,GAGY;AACV,MAAI,MAAM,SAAS,OAAO;AACxB,WAAO;AAAA,EACT;AACA,MAAI,gBAAgB,WAAW,GAAG;AAChC,WAAO;AAAA,EACT;AACA,SAAO,gBAAgB,MAAM,CAAC,aAAa,MAAM,WAAW,QAAQ,CAAC;AACvE;",
4
+ "sourcesContent": ["\"use client\";\n\nimport type { ConsentCategory, ConsentMode } from \"schemas/generated/consent\";\nimport type { ConsentCategories } from \"./cookie\";\n\nimport { useSyncExternalStore } from \"react\";\n\nimport { deriveConsentAction } from \"./consent-action\";\nimport { recordConsentAction } from \"./consent-actions\";\nimport {\n CONSENT_COOKIE_MAX_AGE_SECONDS,\n CONSENT_COOKIE_NAME,\n DENIED_CATEGORIES,\n GRANTED_CATEGORIES,\n parseConsentCookie,\n serializeConsentCookieValue,\n} from \"./cookie\";\n\n/**\n * Framework-agnostic, cookie-backed consent store. Lives as a single module\n * singleton so `ReploScripts`, the site's consent banner, and `AnalyticsProvider`\n * all share the same state regardless of where they sit in the React tree \u2014 no\n * provider-ancestor relationship is required.\n *\n * Consent-dependent work (script injection, banner visibility) happens on the\n * client (effects / post-mount), so there is no SSR/hydration mismatch. The\n * client reads the (non-httpOnly) consent cookie directly, so no server seed is\n * needed. The whole-site `mode` comes from the `data-replo-consent-mode`\n * attribute on `<html>`.\n */\n\nexport interface ConsentState {\n mode: ConsentMode;\n categories: ConsentCategories;\n /** Epoch ms when the visitor last made a choice, or null if undecided. */\n decidedAt: number | null;\n /**\n * Persistent pseudonymous per-browser id linking a visitor's consent history.\n * Absent until the first `commit()` (and on legacy pre-id cookies, until the\n * next interaction lazily backfills it).\n */\n consentId?: string;\n}\n\n// The non-necessary categories a visitor can grant or revoke. `necessary` is\n// always granted and never toggled.\nconst TOGGLEABLE_CATEGORIES: Exclude<ConsentCategory, \"necessary\">[] = [\n \"analytics\",\n \"marketing\",\n \"preferences\",\n \"sale_of_data\",\n];\n\n// A stable reference for SSR / first hydration render. Consent-dependent DOM is\n// only produced on the client, so this constant never causes a mismatch.\nconst SERVER_SNAPSHOT: ConsentState = Object.freeze({\n mode: \"off\",\n categories: DENIED_CATEGORIES,\n decidedAt: null,\n});\n\nconst listeners = new Set<() => void>();\nlet snapshot: ConsentState | null = null;\n\nfunction isConsentMode(value: string | null | undefined): value is ConsentMode {\n return value === \"off\" || value === \"simple\" || value === \"per-category\";\n}\n\nfunction resolveMode(): ConsentMode {\n if (typeof window === \"undefined\") {\n return \"off\";\n }\n const attribute = document.documentElement.dataset.reploConsentMode;\n return isConsentMode(attribute) ? attribute : \"off\";\n}\n\nfunction computeSnapshot(): ConsentState {\n if (typeof window === \"undefined\") {\n return SERVER_SNAPSHOT;\n }\n\n const mode = resolveMode();\n\n const fromCookie = parseConsentCookie(document.cookie);\n if (fromCookie) {\n return {\n mode,\n categories: {\n necessary: true,\n analytics: fromCookie.categories.analytics,\n marketing: fromCookie.categories.marketing,\n preferences: fromCookie.categories.preferences,\n sale_of_data: fromCookie.categories.sale_of_data,\n },\n decidedAt: fromCookie.decidedAt,\n consentId: fromCookie.consentId,\n };\n }\n\n return { mode, categories: DENIED_CATEGORIES, decidedAt: null };\n}\n\nfunction writeCookie(\n categories: ConsentCategories,\n decidedAt: number,\n consentId: string,\n) {\n if (typeof document === \"undefined\") {\n return;\n }\n const value = serializeConsentCookieValue({\n categories,\n decidedAt,\n consentId,\n });\n document.cookie = `${CONSENT_COOKIE_NAME}=${value}; path=/; max-age=${CONSENT_COOKIE_MAX_AGE_SECONDS}; SameSite=Lax`;\n}\n\nfunction notify() {\n for (const listener of listeners) {\n listener();\n }\n}\n\nfunction commit(categories: ConsentCategories) {\n const previous = consentStore.getSnapshot();\n const decidedAt = Date.now();\n // Reuse the visitor's existing id, or mint one on the first decision (also\n // lazily backfills legacy pre-id cookies). `crypto.randomUUID` is available in\n // every browser we target and on the server (where commit() never runs).\n const consentId = previous.consentId ?? crypto.randomUUID();\n const resultingCategories: ConsentCategories = {\n ...categories,\n necessary: true,\n };\n writeCookie(categories, decidedAt, consentId);\n snapshot = {\n mode: previous.mode,\n categories: resultingCategories,\n decidedAt,\n consentId,\n };\n notify();\n\n // Revocation cannot unload an already-loaded vendor. If the visitor had\n // previously decided and is now turning a granted category off, reload so the\n // page renders without those scripts. Deferred until after the audit record is\n // sent so the reload doesn't cancel the in-flight server action.\n const wasDowngrade =\n previous.decidedAt !== null &&\n TOGGLEABLE_CATEGORIES.some((category) => {\n return previous.categories[category] && !categories[category];\n });\n const reloadIfDowngraded = () => {\n if (wasDowngrade && typeof window !== \"undefined\") {\n window.location.reload();\n }\n };\n\n // Proof-of-consent audit record (ungated by consent, but only on managed\n // sites). On `mode === \"off\"` there is no banner/consent UX, so a\n // `setTrackingConsent()` call from a third-party script would only produce\n // meaningless `consent_mode: \"off\"` noise \u2014 skip it. Egress runs through a\n // server action (like the cart) so the client never needs the project id or\n // analytics-fire URL.\n if (previous.mode !== \"off\") {\n void recordConsentAction({\n consentId,\n action: deriveConsentAction({ previous, next: resultingCategories }),\n categories: resultingCategories,\n consentMode: previous.mode,\n decidedAt,\n }).finally(reloadIfDowngraded);\n } else {\n reloadIfDowngraded();\n }\n}\n\nexport const consentStore = {\n getSnapshot(): ConsentState {\n if (!snapshot) {\n snapshot = computeSnapshot();\n }\n return snapshot;\n },\n getServerSnapshot(): ConsentState {\n return SERVER_SNAPSHOT;\n },\n subscribe(listener: () => void): () => void {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n /** Grant every consent category. */\n accept() {\n commit(GRANTED_CATEGORIES);\n },\n /** Deny every non-necessary category. */\n reject() {\n commit(DENIED_CATEGORIES);\n },\n /** Set a subset of categories, leaving the rest at their current value. */\n updateCategories(next: Partial<ConsentCategories>) {\n const current = consentStore.getSnapshot().categories;\n commit({ ...current, ...next, necessary: true });\n },\n /** Test-only: reset cached state so the next read recomputes. */\n reset() {\n snapshot = null;\n },\n};\n\nexport interface UseConsentResult extends ConsentState {\n accept(): void;\n reject(): void;\n updateCategories(next: Partial<ConsentCategories>): void;\n}\n\nexport function useConsent(): UseConsentResult {\n const state = useSyncExternalStore(\n consentStore.subscribe,\n consentStore.getSnapshot,\n consentStore.getServerSnapshot,\n );\n return {\n ...state,\n accept: consentStore.accept,\n reject: consentStore.reject,\n updateCategories: consentStore.updateCategories,\n };\n}\n\n/**\n * Whether a script requiring `requiredConsent` is allowed to load right now.\n * `mode === \"off\"` always allows; otherwise every required category must be\n * granted. An empty requirement list is always allowed.\n */\nexport function isConsentAllowed({\n state,\n requiredConsent,\n}: {\n state: ConsentState;\n requiredConsent: ConsentCategory[];\n}): boolean {\n if (state.mode === \"off\") {\n return true;\n }\n if (requiredConsent.length === 0) {\n return true;\n }\n return requiredConsent.every((category) => state.categories[category]);\n}\n"],
5
+ "mappings": ";AAKA,SAAS,4BAA4B;AAErC,SAAS,2BAA2B;AACpC,SAAS,2BAA2B;AACpC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AA8BP,MAAM,wBAAiE;AAAA,EACrE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAIA,MAAM,kBAAgC,OAAO,OAAO;AAAA,EAClD,MAAM;A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;AAAA,EAEA,QAAQ;AACN,eAAW;AAAA,EACb;AACF;AAQO,SAAS,aAA+B;AAC7C,QAAM,QAAQ;AAAA,IACZ,aAAa;AAAA,IACb,aAAa;AAAA,IACb,aAAa;AAAA,EACf;AACA,SAAO;AAAA,IACL,GAAG;AAAA,IACH,QAAQ,aAAa;AAAA,IACrB,QAAQ,aAAa;AAAA,IACrB,kBAAkB,aAAa;AAAA,EACjC;AACF;AAOO,SAAS,iBAAiB;AAAA,EAC/B;AAAA,EACA;AACF,GAGY;AACV,MAAI,MAAM,SAAS,OAAO;AACxB,WAAO;AAAA,EACT;AACA,MAAI,gBAAgB,WAAW,GAAG;AAChC,WAAO;AAAA,EACT;AACA,SAAO,gBAAgB,MAAM,CAAC,aAAa,MAAM,WAAW,QAAQ,CAAC;AACvE;",
6
6
  "names": []
7
7
  }
@@ -1,7 +1,7 @@
1
- import type { ConsentCategory, ConsentMode } from "../_vendor/schemas/generated/consent";
1
+ import type { ConsentCategory } from "../_vendor/schemas/generated/consent";
2
2
  /**
3
- * Pure (non-React, framework-agnostic) consent cookie helpers, shared by the
4
- * client store (`consent-store.ts`) and the server seed reader (`server.ts`).
3
+ * Pure (non-React, framework-agnostic) consent cookie helpers used by the client
4
+ * store (`consent-store.ts`).
5
5
  */
6
6
  export declare const CONSENT_COOKIE_NAME = "replo_consent";
7
7
  export declare const CONSENT_COOKIE_VERSION = 1;
@@ -11,6 +11,8 @@ export type ConsentCategories = Record<ConsentCategory, boolean>;
11
11
  export interface ConsentCookiePayload {
12
12
  version: number;
13
13
  decidedAt: number;
14
+ /** Persistent pseudonymous per-browser id; absent on pre-id (legacy) cookies. */
15
+ consentId?: string;
14
16
  categories: {
15
17
  analytics: boolean;
16
18
  marketing: boolean;
@@ -18,11 +20,6 @@ export interface ConsentCookiePayload {
18
20
  sale_of_data: boolean;
19
21
  };
20
22
  }
21
- export interface ConsentSeed {
22
- mode: ConsentMode;
23
- categories: ConsentCategories;
24
- decidedAt: number | null;
25
- }
26
23
  export declare const DENIED_CATEGORIES: ConsentCategories;
27
24
  export declare const GRANTED_CATEGORIES: ConsentCategories;
28
25
  /**
@@ -32,7 +29,8 @@ export declare const GRANTED_CATEGORIES: ConsentCategories;
32
29
  */
33
30
  export declare function parseConsentCookie(rawCookie: string | undefined): ConsentCookiePayload | null;
34
31
  /** Serialize categories into the JSON-encoded cookie value (not the full Set-Cookie line). */
35
- export declare function serializeConsentCookieValue({ categories, decidedAt, }: {
32
+ export declare function serializeConsentCookieValue({ categories, decidedAt, consentId, }: {
36
33
  categories: ConsentCategories;
37
34
  decidedAt: number;
35
+ consentId?: string;
38
36
  }): string;
package/consent/cookie.js CHANGED
@@ -6,6 +6,7 @@ const CONSENT_COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 180;
6
6
  const persistedCookieSchema = z.object({
7
7
  version: z.literal(CONSENT_COOKIE_VERSION),
8
8
  decidedAt: z.number().optional(),
9
+ consentId: z.string().optional(),
9
10
  categories: z.object({
10
11
  analytics: z.unknown().optional(),
11
12
  marketing: z.unknown().optional(),
@@ -43,10 +44,11 @@ function parseConsentCookie(rawCookie) {
43
44
  if (!result.success) {
44
45
  return null;
45
46
  }
46
- const { decidedAt, categories } = result.data;
47
+ const { decidedAt, categories, consentId } = result.data;
47
48
  return {
48
49
  version: CONSENT_COOKIE_VERSION,
49
50
  decidedAt: decidedAt ?? Date.now(),
51
+ consentId,
50
52
  categories: {
51
53
  analytics: Boolean(categories.analytics),
52
54
  marketing: Boolean(categories.marketing),
@@ -57,11 +59,13 @@ function parseConsentCookie(rawCookie) {
57
59
  }
58
60
  function serializeConsentCookieValue({
59
61
  categories,
60
- decidedAt
62
+ decidedAt,
63
+ consentId
61
64
  }) {
62
65
  const payload = {
63
66
  version: CONSENT_COOKIE_VERSION,
64
67
  decidedAt,
68
+ consentId,
65
69
  categories: {
66
70
  analytics: categories.analytics,
67
71
  marketing: categories.marketing,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../consent/cookie.ts"],
4
- "sourcesContent": ["import type { ConsentCategory, ConsentMode } from \"schemas/generated/consent\";\n\nimport { parseJsonOrNull } from \"replo-utils/lib/json\";\nimport { z } from \"zod\";\n\n/**\n * Pure (non-React, framework-agnostic) consent cookie helpers, shared by the\n * client store (`consent-store.ts`) and the server seed reader (`server.ts`).\n */\n\nexport const CONSENT_COOKIE_NAME = \"replo_consent\";\nexport const CONSENT_COOKIE_VERSION = 1;\nexport const CONSENT_COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 180; // 180 days\n\n// Validates the untrusted JSON cookie payload at the parse boundary. A stale\n// version (or any shape mismatch) fails `safeParse`, so the caller treats the\n// visitor as undecided and re-prompts.\nconst persistedCookieSchema = z.object({\n version: z.literal(CONSENT_COOKIE_VERSION),\n decidedAt: z.number().optional(),\n categories: z.object({\n analytics: z.unknown().optional(),\n marketing: z.unknown().optional(),\n preferences: z.unknown().optional(),\n sale_of_data: z.unknown().optional(),\n }),\n});\n\nexport type ConsentCategories = Record<ConsentCategory, boolean>;\n\n/** Persisted cookie payload. `necessary` is always granted and never stored. */\nexport interface ConsentCookiePayload {\n version: number;\n decidedAt: number;\n categories: {\n analytics: boolean;\n marketing: boolean;\n preferences: boolean;\n sale_of_data: boolean;\n };\n}\n\nexport interface ConsentSeed {\n mode: ConsentMode;\n categories: ConsentCategories;\n decidedAt: number | null;\n}\n\nexport const DENIED_CATEGORIES: ConsentCategories = {\n necessary: true,\n analytics: false,\n marketing: false,\n preferences: false,\n sale_of_data: false,\n};\n\nexport const GRANTED_CATEGORIES: ConsentCategories = {\n necessary: true,\n analytics: true,\n marketing: true,\n preferences: true,\n sale_of_data: true,\n};\n\n/**\n * Parse a raw `document.cookie` (or a single cookie value) into a payload.\n * Returns null for missing, malformed, or stale-version cookies so callers\n * treat the visitor as undecided and re-prompt.\n */\nexport function parseConsentCookie(\n rawCookie: string | undefined,\n): ConsentCookiePayload | null {\n if (!rawCookie) {\n return null;\n }\n const match = rawCookie\n .split(\"; \")\n .find((entry) => entry.startsWith(`${CONSENT_COOKIE_NAME}=`));\n const encoded = match\n ? match.slice(CONSENT_COOKIE_NAME.length + 1)\n : rawCookie;\n\n // A tampered/corrupted cookie (bad percent-encoding) must not throw \u2014 that\n // would crash the client snapshot or the server seed read. Treat as undecided.\n let decoded: string;\n try {\n decoded = decodeURIComponent(encoded);\n } catch {\n return null;\n }\n\n const result = persistedCookieSchema.safeParse(parseJsonOrNull(decoded));\n if (!result.success) {\n return null;\n }\n const { decidedAt, categories } = result.data;\n\n return {\n version: CONSENT_COOKIE_VERSION,\n decidedAt: decidedAt ?? Date.now(),\n categories: {\n analytics: Boolean(categories.analytics),\n marketing: Boolean(categories.marketing),\n preferences: Boolean(categories.preferences),\n sale_of_data: Boolean(categories.sale_of_data),\n },\n };\n}\n\n/** Serialize categories into the JSON-encoded cookie value (not the full Set-Cookie line). */\nexport function serializeConsentCookieValue({\n categories,\n decidedAt,\n}: {\n categories: ConsentCategories;\n decidedAt: number;\n}): string {\n const payload: ConsentCookiePayload = {\n version: CONSENT_COOKIE_VERSION,\n decidedAt,\n categories: {\n analytics: categories.analytics,\n marketing: categories.marketing,\n preferences: categories.preferences,\n sale_of_data: categories.sale_of_data,\n },\n };\n return encodeURIComponent(JSON.stringify(payload));\n}\n"],
5
- "mappings": "AAEA,SAAS,uBAAuB;AAChC,SAAS,SAAS;AAOX,MAAM,sBAAsB;AAC5B,MAAM,yBAAyB;AAC/B,MAAM,iCAAiC,KAAK,KAAK,KAAK;AAK7D,MAAM,wBAAwB,EAAE,OAAO;AAAA,EACrC,SAAS,EAAE,QAAQ,sBAAsB;AAAA,EACzC,WAAW,EAAE,OAAO,EAAE,SAAS;AAAA,EAC/B,YAAY,EAAE,OAAO;AAAA,IACnB,WAAW,EAAE,QAAQ,EAAE,SAAS;AAAA,IAChC,WAAW,EAAE,QAAQ,EAAE,SAAS;AAAA,IAChC,aAAa,EAAE,QAAQ,EAAE,SAAS;AAAA,IAClC,c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AAA,IAC3B;AAAA,EACF;AACA,SAAO,mBAAmB,KAAK,UAAU,OAAO,CAAC;AACnD;",
4
+ "sourcesContent": ["import type { ConsentCategory } from \"schemas/generated/consent\";\n\nimport { parseJsonOrNull } from \"replo-utils/lib/json\";\nimport { z } from \"zod\";\n\n/**\n * Pure (non-React, framework-agnostic) consent cookie helpers used by the client\n * store (`consent-store.ts`).\n */\n\nexport const CONSENT_COOKIE_NAME = \"replo_consent\";\nexport const CONSENT_COOKIE_VERSION = 1;\nexport const CONSENT_COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 180; // 180 days\n\n// Validates the untrusted JSON cookie payload at the parse boundary. A stale\n// version (or any shape mismatch) fails `safeParse`, so the caller treats the\n// visitor as undecided and re-prompts.\n//\n// `consentId` is OPTIONAL on purpose: it was added after v1 shipped, and we must\n// NOT bump `CONSENT_COOKIE_VERSION` to introduce it. Bumping would fail this\n// `safeParse` for every existing cookie, re-showing the banner and dropping the\n// visitor's prior decision. Optional keeps v1 cookies valid; `commit()` lazily\n// backfills the id on the next interaction.\nconst persistedCookieSchema = z.object({\n version: z.literal(CONSENT_COOKIE_VERSION),\n decidedAt: z.number().optional(),\n consentId: z.string().optional(),\n categories: z.object({\n analytics: z.unknown().optional(),\n marketing: z.unknown().optional(),\n preferences: z.unknown().optional(),\n sale_of_data: z.unknown().optional(),\n }),\n});\n\nexport type ConsentCategories = Record<ConsentCategory, boolean>;\n\n/** Persisted cookie payload. `necessary` is always granted and never stored. */\nexport interface ConsentCookiePayload {\n version: number;\n decidedAt: number;\n /** Persistent pseudonymous per-browser id; absent on pre-id (legacy) cookies. */\n consentId?: string;\n categories: {\n analytics: boolean;\n marketing: boolean;\n preferences: boolean;\n sale_of_data: boolean;\n };\n}\n\nexport const DENIED_CATEGORIES: ConsentCategories = {\n necessary: true,\n analytics: false,\n marketing: false,\n preferences: false,\n sale_of_data: false,\n};\n\nexport const GRANTED_CATEGORIES: ConsentCategories = {\n necessary: true,\n analytics: true,\n marketing: true,\n preferences: true,\n sale_of_data: true,\n};\n\n/**\n * Parse a raw `document.cookie` (or a single cookie value) into a payload.\n * Returns null for missing, malformed, or stale-version cookies so callers\n * treat the visitor as undecided and re-prompt.\n */\nexport function parseConsentCookie(\n rawCookie: string | undefined,\n): ConsentCookiePayload | null {\n if (!rawCookie) {\n return null;\n }\n const match = rawCookie\n .split(\"; \")\n .find((entry) => entry.startsWith(`${CONSENT_COOKIE_NAME}=`));\n const encoded = match\n ? match.slice(CONSENT_COOKIE_NAME.length + 1)\n : rawCookie;\n\n // A tampered/corrupted cookie (bad percent-encoding) must not throw \u2014 that\n // would crash the client snapshot or the server seed read. Treat as undecided.\n let decoded: string;\n try {\n decoded = decodeURIComponent(encoded);\n } catch {\n return null;\n }\n\n const result = persistedCookieSchema.safeParse(parseJsonOrNull(decoded));\n if (!result.success) {\n return null;\n }\n const { decidedAt, categories, consentId } = result.data;\n\n return {\n version: CONSENT_COOKIE_VERSION,\n decidedAt: decidedAt ?? Date.now(),\n consentId,\n categories: {\n analytics: Boolean(categories.analytics),\n marketing: Boolean(categories.marketing),\n preferences: Boolean(categories.preferences),\n sale_of_data: Boolean(categories.sale_of_data),\n },\n };\n}\n\n/** Serialize categories into the JSON-encoded cookie value (not the full Set-Cookie line). */\nexport function serializeConsentCookieValue({\n categories,\n decidedAt,\n consentId,\n}: {\n categories: ConsentCategories;\n decidedAt: number;\n consentId?: string;\n}): string {\n const payload: ConsentCookiePayload = {\n version: CONSENT_COOKIE_VERSION,\n decidedAt,\n consentId,\n categories: {\n analytics: categories.analytics,\n marketing: categories.marketing,\n preferences: categories.preferences,\n sale_of_data: categories.sale_of_data,\n },\n };\n return encodeURIComponent(JSON.stringify(payload));\n}\n"],
5
+ "mappings": "AAEA,SAAS,uBAAuB;AAChC,SAAS,SAAS;AAOX,MAAM,sBAAsB;AAC5B,MAAM,yBAAyB;AAC/B,MAAM,iCAAiC,KAAK,KAAK,KAAK;AAW7D,MAAM,wBAAwB,EAAE,OAAO;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A,MACvC,aAAa,QAAQ,WAAW,WAAW;AAAA,MAC3C,cAAc,QAAQ,WAAW,YAAY;AAAA,IAC/C;AAAA,EACF;AACF;AAGO,SAAS,4BAA4B;AAAA,EAC1C;AAAA,EACA;AAAA,EACA;AACF,GAIW;AACT,QAAM,UAAgC;AAAA,IACpC,SAAS;AAAA,IACT;AAAA,IACA;AAAA,IACA,YAAY;AAAA,MACV,WAAW,WAAW;AAAA,MACtB,WAAW,WAAW;AAAA,MACtB,aAAa,WAAW;AAAA,MACxB,cAAc,WAAW;AAAA,IAC3B;AAAA,EACF;AACA,SAAO,mBAAmB,KAAK,UAAU,OAAO,CAAC;AACnD;",
6
6
  "names": []
7
7
  }
@@ -3,9 +3,13 @@ import { useEffect, useRef } from "react";
3
3
  import { buildGoogleFontsCssUrl } from "../../_vendor/replo-utils/lib/google-fonts.mjs";
4
4
  import { designLibraryPreviewMessageSchema } from "../../_vendor/schemas/designLibrary.mjs";
5
5
  const FONT_LINK_DATA_KEY = "reploDesignLibraryFont";
6
+ function escapeCssString(value) {
7
+ return value.replace(/\\/gu, "\\\\").replace(/'/gu, "\\'");
8
+ }
6
9
  function DesignLibraryPreview() {
7
10
  const ownedKeys = useRef(null);
8
11
  const ownedFontLinks = useRef(null);
12
+ const ownedFontFaces = useRef(null);
9
13
  const ownsDefaultFont = useRef(false);
10
14
  useEffect(() => {
11
15
  const handleMessage = (event) => {
@@ -15,7 +19,7 @@ function DesignLibraryPreview() {
15
19
  const root = document.documentElement;
16
20
  const nextVars = { ...cssVars };
17
21
  for (const font of fonts) {
18
- nextVars[font.cssVar] = `'${font.family}'`;
22
+ nextVars[font.cssVar] = `'${escapeCssString(font.family)}'`;
19
23
  }
20
24
  const owned = ownedKeys.current ?? /* @__PURE__ */ new Set();
21
25
  for (const key of owned) {
@@ -25,9 +29,11 @@ function DesignLibraryPreview() {
25
29
  for (const [key, value] of Object.entries(nextVars)) {
26
30
  root.style.setProperty(key, value);
27
31
  }
32
+ const customFonts = fonts.filter((font) => Boolean(font.faceUrl));
33
+ const googleFonts = fonts.filter((font) => !font.faceUrl);
28
34
  const links = ownedFontLinks.current ?? /* @__PURE__ */ new Map();
29
35
  const nextHrefs = new Set(
30
- fonts.map((font) => buildGoogleFontsCssUrl(font.family))
36
+ googleFonts.map((font) => buildGoogleFontsCssUrl(font.family))
31
37
  );
32
38
  for (const [href, link] of links) {
33
39
  if (!nextHrefs.has(href)) {
@@ -45,6 +51,27 @@ function DesignLibraryPreview() {
45
51
  links.set(href, link);
46
52
  }
47
53
  ownedFontLinks.current = links;
54
+ const faces = ownedFontFaces.current ?? /* @__PURE__ */ new Map();
55
+ const nextFamilies = new Set(customFonts.map((font) => font.family));
56
+ for (const [family, entry] of faces) {
57
+ if (!nextFamilies.has(family)) {
58
+ entry.style.remove();
59
+ faces.delete(family);
60
+ }
61
+ }
62
+ for (const font of customFonts) {
63
+ if (!font.faceUrl) continue;
64
+ const existing = faces.get(font.family);
65
+ if (existing?.url === font.faceUrl) continue;
66
+ existing?.style.remove();
67
+ const style = document.createElement("style");
68
+ style.dataset[FONT_LINK_DATA_KEY] = "";
69
+ const format = font.format ? ` format('${escapeCssString(font.format)}')` : "";
70
+ style.textContent = `@font-face{font-family:'${escapeCssString(font.family)}';font-weight:400;font-style:normal;src:url('${escapeCssString(font.faceUrl)}')${format};font-display:swap;}`;
71
+ document.head.append(style);
72
+ faces.set(font.family, { url: font.faceUrl, style });
73
+ }
74
+ ownedFontFaces.current = faces;
48
75
  if (defaultFontCssVar) {
49
76
  root.style.setProperty("font-family", `var(${defaultFontCssVar})`);
50
77
  ownsDefaultFont.current = true;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../editor/design-library-preview/DesignLibraryPreview.tsx"],
4
- "sourcesContent": ["\"use client\";\n\nimport { useEffect, useRef } from \"react\";\n\nimport { buildGoogleFontsCssUrl } from \"replo-utils/lib/google-fonts\";\nimport { designLibraryPreviewMessageSchema } from \"schemas/designLibrary\";\n\nconst FONT_LINK_DATA_KEY = \"reploDesignLibraryFont\";\n\nexport function DesignLibraryPreview() {\n // NOTE (Ben, 2026-06-03): The custom-property keys we set last time, so on the\n // next message we remove only the ones we own that the new override set drops.\n const ownedKeys = useRef<Set<string> | null>(null);\n // NOTE (Ben, 2026-06-05): The Google Font <link> hrefs we injected, keyed by\n // href so we de-dupe and remove only our own when the override set changes.\n const ownedFontLinks = useRef<Map<string, HTMLLinkElement> | null>(null);\n // NOTE (Ben, 2026-06-05): Whether we set the document default font-family, so\n // we can clear just that.\n const ownsDefaultFont = useRef(false);\n\n // eslint-disable-next-line replo/no-use-effect -- Subscribes to window message events from the parent editor.\n useEffect(() => {\n const handleMessage = (event: MessageEvent) => {\n const parsed = designLibraryPreviewMessageSchema.safeParse(event.data);\n if (!parsed.success) return;\n const { cssVars, fonts, defaultFontCssVar } = parsed.data;\n const root = document.documentElement;\n\n // --- CSS variable overrides (colors + font role vars) ---\n const nextVars: Record<string, string> = { ...cssVars };\n for (const font of fonts) {\n nextVars[font.cssVar] = `'${font.family}'`;\n }\n const owned = ownedKeys.current ?? new Set();\n for (const key of owned) {\n if (!(key in nextVars)) root.style.removeProperty(key);\n }\n ownedKeys.current = new Set(Object.keys(nextVars));\n for (const [key, value] of Object.entries(nextVars)) {\n root.style.setProperty(key, value);\n }\n\n // --- Google Font stylesheets ---\n const links = ownedFontLinks.current ?? new Map();\n const nextHrefs = new Set(\n fonts.map((font) => buildGoogleFontsCssUrl(font.family)),\n );\n for (const [href, link] of links) {\n if (!nextHrefs.has(href)) {\n link.remove();\n links.delete(href);\n }\n }\n for (const href of nextHrefs) {\n if (links.has(href)) continue;\n const link = document.createElement(\"link\");\n link.rel = \"stylesheet\";\n link.href = href;\n link.dataset[FONT_LINK_DATA_KEY] = \"\";\n document.head.append(link);\n links.set(href, link);\n }\n ownedFontLinks.current = links;\n\n // --- Document default font ---\n if (defaultFontCssVar) {\n root.style.setProperty(\"font-family\", `var(${defaultFontCssVar})`);\n ownsDefaultFont.current = true;\n } else if (ownsDefaultFont.current) {\n root.style.removeProperty(\"font-family\");\n ownsDefaultFont.current = false;\n }\n };\n window.addEventListener(\"message\", handleMessage);\n return () => {\n window.removeEventListener(\"message\", handleMessage);\n };\n }, []);\n\n return null;\n}\n"],
5
- "mappings": ";AAEA,SAAS,WAAW,cAAc;AAElC,SAAS,8BAA8B;AACvC,SAAS,yCAAyC;AAElD,MAAM,qBAAqB;AAEpB,SAAS,uBAAuB;AAGrC,QAAM,YAAY,OAA2B,IAAI;AAGjD,QAAM,iBAAiB,OAA4C,IAAI;AAGvE,QAAM,kBAAkB,OAAO,KAAK;AAGpC,YAAU,MAAM;AACd,UAAM,gBAAgB,CAAC,UAAwB;AAC7C,YAAM,SAAS,kCAAkC,UAAU,MAAM,IAAI;AACrE,UAAI,CAAC,OAAO,QAAS;AACrB,YAAM,EAAE,SAAS,OAAO,kBAAkB,IAAI,OAAO;AACrD,YAAM,OAAO,SAAS;AAGtB,YAAM,WAAmC,EAAE,GAAG,QAAQ;AACtD,iBAAW,QAAQ,OAAO;AACxB,iBAAS,KAAK,MAAM,IAAI,IAAI,KAAK,MAAM;AAAA,MACzC;AACA,YAAM,QAAQ,UAAU,WAAW,oBAAI,IAAI;AAC3C,iBAAW,OAAO,OAAO;AACvB,YAAI,EAAE,OAAO,UAAW,MAAK,MAAM,eAAe,GAAG;AAAA,MACvD;AACA,gBAAU,UAAU,IAAI,IAAI,OAAO,KAAK,QAAQ,CAAC;AACjD,iBAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,QAAQ,GAAG;AACnD,aAAK,MAAM,YAAY,KAAK,KAAK;AAAA,MACnC;AAGA,YAAM,QAAQ,eAAe,WAAW,oBAAI,IAAI;AAChD,YAAM,YAAY,IAAI;AAAA,QACpB,MAAM,IAAI,CAAC,SAAS,uBAAuB,KAAK,MAAM,CAAC;AAAA,MACzD;AACA,iBAAW,CAAC,MAAM,IAAI,KAAK,OAAO;AAChC,YAAI,CAAC,UAAU,IAAI,IAAI,GAAG;AACxB,eAAK,OAAO;AACZ,gBAAM,OAAO,IAAI;AAAA,QACnB;AAAA,MACF;AACA,iBAAW,QAAQ,WAAW;AAC5B,YAAI,MAAM,IAAI,IAAI,EAAG;AACrB,cAAM,OAAO,SAAS,cAAc,MAAM;AAC1C,aAAK,MAAM;AACX,aAAK,OAAO;AACZ,aAAK,QAAQ,kBAAkB,IAAI;AACnC,iBAAS,KAAK,OAAO,IAAI;AACzB,cAAM,IAAI,MAAM,IAAI;AAAA,MACtB;AACA,qBAAe,UAAU;AAGzB,UAAI,mBAAmB;AACrB,aAAK,MAAM,YAAY,eAAe,OAAO,iBAAiB,GAAG;AACjE,wBAAgB,UAAU;AAAA,MAC5B,WAAW,gBAAgB,SAAS;AAClC,aAAK,MAAM,eAAe,aAAa;AACvC,wBAAgB,UAAU;AAAA,MAC5B;AAAA,IACF;AACA,WAAO,iBAAiB,WAAW,aAAa;AAChD,WAAO,MAAM;AACX,aAAO,oBAAoB,WAAW,aAAa;AAAA,IACrD;AAAA,EACF,GAAG,CAAC,CAAC;AAEL,SAAO;AACT;",
4
+ "sourcesContent": ["\"use client\";\n\nimport { useEffect, useRef } from \"react\";\n\nimport { buildGoogleFontsCssUrl } from \"replo-utils/lib/google-fonts\";\nimport { designLibraryPreviewMessageSchema } from \"schemas/designLibrary\";\n\nconst FONT_LINK_DATA_KEY = \"reploDesignLibraryFont\";\n\nfunction escapeCssString(value: string): string {\n return value.replace(/\\\\/gu, \"\\\\\\\\\").replace(/'/gu, \"\\\\'\");\n}\n\nexport function DesignLibraryPreview() {\n // NOTE (Ben, 2026-06-03): The custom-property keys we set last time, so on the\n // next message we remove only the ones we own that the new override set drops.\n const ownedKeys = useRef<Set<string> | null>(null);\n // NOTE (Ben, 2026-06-05): The Google Font <link> hrefs we injected, keyed by\n // href so we de-dupe and remove only our own when the override set changes.\n const ownedFontLinks = useRef<Map<string, HTMLLinkElement> | null>(null);\n // NOTE (Ben, 2026-06-05): The @font-face <style> nodes for uploaded custom\n // fonts, keyed by family with the URL we injected, so we de-dupe, re-inject\n // when a family's asset URL changes (re-upload), and remove only our own when\n // the override set changes.\n const ownedFontFaces = useRef<Map<\n string,\n { url: string; style: HTMLStyleElement }\n > | null>(null);\n // NOTE (Ben, 2026-06-05): Whether we set the document default font-family, so\n // we can clear just that.\n const ownsDefaultFont = useRef(false);\n\n // eslint-disable-next-line replo/no-use-effect -- Subscribes to window message events from the parent editor.\n useEffect(() => {\n const handleMessage = (event: MessageEvent) => {\n const parsed = designLibraryPreviewMessageSchema.safeParse(event.data);\n if (!parsed.success) return;\n const { cssVars, fonts, defaultFontCssVar } = parsed.data;\n const root = document.documentElement;\n\n // --- CSS variable overrides (colors + font role vars) ---\n const nextVars: Record<string, string> = { ...cssVars };\n for (const font of fonts) {\n nextVars[font.cssVar] = `'${escapeCssString(font.family)}'`;\n }\n const owned = ownedKeys.current ?? new Set();\n for (const key of owned) {\n if (!(key in nextVars)) root.style.removeProperty(key);\n }\n ownedKeys.current = new Set(Object.keys(nextVars));\n for (const [key, value] of Object.entries(nextVars)) {\n root.style.setProperty(key, value);\n }\n\n // Custom uploaded fonts carry a faceUrl; Google fonts don't.\n const customFonts = fonts.filter((font) => Boolean(font.faceUrl));\n const googleFonts = fonts.filter((font) => !font.faceUrl);\n\n // --- Google Font stylesheets (<link> to the CDN) ---\n const links = ownedFontLinks.current ?? new Map();\n const nextHrefs = new Set(\n googleFonts.map((font) => buildGoogleFontsCssUrl(font.family)),\n );\n for (const [href, link] of links) {\n if (!nextHrefs.has(href)) {\n link.remove();\n links.delete(href);\n }\n }\n for (const href of nextHrefs) {\n if (links.has(href)) continue;\n const link = document.createElement(\"link\");\n link.rel = \"stylesheet\";\n link.href = href;\n link.dataset[FONT_LINK_DATA_KEY] = \"\";\n document.head.append(link);\n links.set(href, link);\n }\n ownedFontLinks.current = links;\n\n // --- Custom uploaded fonts (@font-face from the asset URL) ---\n const faces = ownedFontFaces.current ?? new Map();\n const nextFamilies = new Set(customFonts.map((font) => font.family));\n for (const [family, entry] of faces) {\n if (!nextFamilies.has(family)) {\n entry.style.remove();\n faces.delete(family);\n }\n }\n for (const font of customFonts) {\n if (!font.faceUrl) continue;\n const existing = faces.get(font.family);\n // Re-upload reuses the family but changes the asset URL; replace the\n // stale node rather than skipping it.\n if (existing?.url === font.faceUrl) continue;\n existing?.style.remove();\n const style = document.createElement(\"style\");\n style.dataset[FONT_LINK_DATA_KEY] = \"\";\n const format = font.format\n ? ` format('${escapeCssString(font.format)}')`\n : \"\";\n style.textContent = `@font-face{font-family:'${escapeCssString(font.family)}';font-weight:400;font-style:normal;src:url('${escapeCssString(font.faceUrl)}')${format};font-display:swap;}`;\n document.head.append(style);\n faces.set(font.family, { url: font.faceUrl, style });\n }\n ownedFontFaces.current = faces;\n\n // --- Document default font ---\n if (defaultFontCssVar) {\n root.style.setProperty(\"font-family\", `var(${defaultFontCssVar})`);\n ownsDefaultFont.current = true;\n } else if (ownsDefaultFont.current) {\n root.style.removeProperty(\"font-family\");\n ownsDefaultFont.current = false;\n }\n };\n window.addEventListener(\"message\", handleMessage);\n return () => {\n window.removeEventListener(\"message\", handleMessage);\n };\n }, []);\n\n return null;\n}\n"],
5
+ "mappings": ";AAEA,SAAS,WAAW,cAAc;AAElC,SAAS,8BAA8B;AACvC,SAAS,yCAAyC;AAElD,MAAM,qBAAqB;AAE3B,SAAS,gBAAgB,OAAuB;AAC9C,SAAO,MAAM,QAAQ,QAAQ,MAAM,EAAE,QAAQ,OAAO,KAAK;AAC3D;AAEO,SAAS,uBAAuB;AAGrC,QAAM,YAAY,OAA2B,IAAI;AAGjD,QAAM,iBAAiB,OAA4C,IAAI;AAKvE,QAAM,iBAAiB,OAGb,IAAI;AAGd,QAAM,kBAAkB,OAAO,KAAK;AAGpC,YAAU,MAAM;AACd,UAAM,gBAAgB,CAAC,UAAwB;AAC7C,YAAM,SAAS,kCAAkC,UAAU,MAAM,IAAI;AACrE,UAAI,CAAC,OAAO,QAA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ECT_ID: string;
4
+ ANALYTICS_FIRE_API_URL?: string;
4
5
  SHOPIFY_URL?: string;
5
6
  SHOPIFY_STOREFRONT_ACCESS_TOKEN?: string | null;
6
7
  STRIPE_CONNECT_ACCOUNT_ID?: string | null;
package/env.js CHANGED
@@ -3,6 +3,7 @@ import { z } from "zod";
3
3
  const envSchema = z.object({
4
4
  CANOPY_API_HOST: z.string().min(1),
5
5
  PROJECT_ID: z.string().uuid(),
6
+ ANALYTICS_FIRE_API_URL: z.string().optional(),
6
7
  SHOPIFY_URL: z.string().optional(),
7
8
  SHOPIFY_STOREFRONT_ACCESS_TOKEN: z.string().nullable().optional(),
8
9
  STRIPE_CONNECT_ACCOUNT_ID: z.string().nullable().optional(),
package/env.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../env.ts"],
4
- "sourcesContent": ["import { getCloudflareContext } from \"@opennextjs/cloudflare\";\nimport { z } from \"zod\";\n\ntype Env = {\n CANOPY_API_HOST: string;\n PROJECT_ID: string;\n\n // NOTE (Gabe 2025-06-26): If there's no Shopify integration these will be\n // undefined.\n SHOPIFY_URL?: string;\n // NOTE (Gabe 2025-06-26): Even if there's an integration, if we haven't been\n // given elevated scope this may be null.\n SHOPIFY_STOREFRONT_ACCESS_TOKEN?: string | null;\n STRIPE_CONNECT_ACCOUNT_ID?: string | null;\n CHECKOUT_PROVIDER?: \"shopify\" | \"stripe\" | \"none\";\n\n REPLO_INTERNAL_REVALIDATE_SECRET?: string;\n /** Shared secret sent in X-Replo-Resolver-Auth for server-to-server cart calls. */\n CART_AUTH_SECRET?: string;\n};\n\nconst envSchema = z.object({\n CANOPY_API_HOST: z.string().min(1),\n PROJECT_ID: z.string().uuid(),\n SHOPIFY_URL: z.string().optional(),\n SHOPIFY_STOREFRONT_ACCESS_TOKEN: z.string().nullable().optional(),\n STRIPE_CONNECT_ACCOUNT_ID: z.string().nullable().optional(),\n CHECKOUT_PROVIDER: z.enum([\"shopify\", \"stripe\", \"none\"]).optional(),\n REPLO_INTERNAL_REVALIDATE_SECRET: z.string().optional(),\n CART_AUTH_SECRET: z.string().optional(),\n});\n\nexport const getEnv = async (): Promise<Env> => {\n const { env } = await getCloudflareContext({ async: true });\n return envSchema.parse(env);\n};\n"],
5
- "mappings": "AAAA,SAAS,4BAA4B;AACrC,SAAS,SAAS;AAoBlB,MAAM,YAAY,EAAE,OAAO;AAAA,EACzB,iBAAiB,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACjC,YAAY,EAAE,OAAO,EAAE,KAAK;AAAA,EAC5B,aAAa,EAAE,OAAO,EAAE,SAAS;AAAA,EACjC,iCAAiC,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS;AAAA,EAChE,2BAA2B,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS;AAAA,EAC1D,mBAAmB,EAAE,KAAK,CAAC,WAAW,UAAU,MAAM,CAAC,EAAE,SAAS;AAAA,EAClE,kCAAkC,EAAE,OAAO,EAAE,SAAS;AAAA,EACtD,kBAAkB,EAAE,OAAO,EAAE,SAAS;AACxC,CAAC;AAEM,MAAM,SAAS,YAA0B;AAC9C,QAAM,EAAE,IAAI,IAAI,MAAM,qBAAqB,EAAE,OAAO,KAAK,CAAC;AAC1D,SAAO,UAAU,MAAM,GAAG;AAC5B;",
4
+ "sourcesContent": ["import { getCloudflareContext } from \"@opennextjs/cloudflare\";\nimport { z } from \"zod\";\n\ntype Env = {\n CANOPY_API_HOST: string;\n PROJECT_ID: string;\n\n // Base URL of analytics-fire (e.g. https://data.replo.app). Read server-side by\n // the consent action (`consent/consent-actions.ts`) to forward proof-of-consent\n // records. Optional: absent in environments where the audit pipeline isn't\n // wired (e.g. local dev), where consent recording simply no-ops.\n ANALYTICS_FIRE_API_URL?: string;\n\n // NOTE (Gabe 2025-06-26): If there's no Shopify integration these will be\n // undefined.\n SHOPIFY_URL?: string;\n // NOTE (Gabe 2025-06-26): Even if there's an integration, if we haven't been\n // given elevated scope this may be null.\n SHOPIFY_STOREFRONT_ACCESS_TOKEN?: string | null;\n STRIPE_CONNECT_ACCOUNT_ID?: string | null;\n CHECKOUT_PROVIDER?: \"shopify\" | \"stripe\" | \"none\";\n\n REPLO_INTERNAL_REVALIDATE_SECRET?: string;\n /** Shared secret sent in X-Replo-Resolver-Auth for server-to-server cart calls. */\n CART_AUTH_SECRET?: string;\n};\n\nconst envSchema = z.object({\n CANOPY_API_HOST: z.string().min(1),\n PROJECT_ID: z.string().uuid(),\n ANALYTICS_FIRE_API_URL: z.string().optional(),\n SHOPIFY_URL: z.string().optional(),\n SHOPIFY_STOREFRONT_ACCESS_TOKEN: z.string().nullable().optional(),\n STRIPE_CONNECT_ACCOUNT_ID: z.string().nullable().optional(),\n CHECKOUT_PROVIDER: z.enum([\"shopify\", \"stripe\", \"none\"]).optional(),\n REPLO_INTERNAL_REVALIDATE_SECRET: z.string().optional(),\n CART_AUTH_SECRET: z.string().optional(),\n});\n\nexport const getEnv = async (): Promise<Env> => {\n const { env } = await getCloudflareContext({ async: true });\n return envSchema.parse(env);\n};\n"],
5
+ "mappings": "AAAA,SAAS,4BAA4B;AACrC,SAAS,SAAS;AA0BlB,MAAM,YAAY,EAAE,OAAO;AAAA,EACzB,iBAAiB,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACjC,YAAY,EAAE,OAAO,EAAE,KAAK;AAAA,EAC5B,wBAAwB,EAAE,OAAO,EAAE,SAAS;AAAA,EAC5C,aAAa,EAAE,OAAO,EAAE,SAAS;AAAA,EACjC,iCAAiC,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS;AAAA,EAChE,2BAA2B,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS;AAAA,EAC1D,mBAAmB,EAAE,KAAK,CAAC,WAAW,UAAU,MAAM,CAAC,EAAE,SAAS;AAAA,EAClE,kCAAkC,EAAE,OAAO,EAAE,SAAS;AAAA,EACtD,kBAAkB,EAAE,OAAO,EAAE,SAAS;AACxC,CAAC;AAEM,MAAM,SAAS,YAA0B;AAC9C,QAAM,EAAE,IAAI,IAAI,MAAM,qBAAqB,EAAE,OAAO,KAAK,CAAC;AAC1D,SAAO,UAAU,MAAM,GAAG;AAC5B;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@replohq/canopy-sdk",
3
- "version": "0.2.1",
3
+ "version": "0.3.1",
4
4
  "description": "Replo Canopy SDK — cart, analytics, data loaders, and editor runtime for agent-built Next.js sites.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -1,12 +0,0 @@
1
- import type { ConsentMode } from "../_vendor/schemas/generated/consent";
2
- import type { ConsentSeed } from "./cookie";
3
- /**
4
- * Server-only: reads the `replo_consent` cookie via `next/headers` so the layout
5
- * can serialize it into `window.__REPLO_CONSENT__`, letting the client consent
6
- * store hydrate without a banner flash. `cookies()` is async in Next 15+, so this
7
- * helper (and the layout that awaits it) must be async.
8
- *
9
- * Importing `next/headers` makes this module server-only; do not re-export it from
10
- * the client `consent` barrel.
11
- */
12
- export declare function readConsentSeed(mode?: ConsentMode): Promise<ConsentSeed>;
package/consent/server.js DELETED
@@ -1,29 +0,0 @@
1
- import { cookies } from "next/headers";
2
- import {
3
- CONSENT_COOKIE_NAME,
4
- DENIED_CATEGORIES,
5
- parseConsentCookie
6
- } from "./cookie";
7
- async function readConsentSeed(mode = "off") {
8
- const cookieStore = await cookies();
9
- const raw = cookieStore.get(CONSENT_COOKIE_NAME)?.value;
10
- const parsed = parseConsentCookie(raw);
11
- if (!parsed) {
12
- return { mode, categories: DENIED_CATEGORIES, decidedAt: null };
13
- }
14
- return {
15
- mode,
16
- categories: {
17
- necessary: true,
18
- analytics: parsed.categories.analytics,
19
- marketing: parsed.categories.marketing,
20
- preferences: parsed.categories.preferences,
21
- sale_of_data: parsed.categories.sale_of_data
22
- },
23
- decidedAt: parsed.decidedAt
24
- };
25
- }
26
- export {
27
- readConsentSeed
28
- };
29
- //# sourceMappingURL=server.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../consent/server.ts"],
4
- "sourcesContent": ["import type { ConsentMode } from \"schemas/generated/consent\";\nimport type { ConsentSeed } from \"./cookie\";\n\nimport { cookies } from \"next/headers\";\n\nimport {\n CONSENT_COOKIE_NAME,\n DENIED_CATEGORIES,\n parseConsentCookie,\n} from \"./cookie\";\n\n/**\n * Server-only: reads the `replo_consent` cookie via `next/headers` so the layout\n * can serialize it into `window.__REPLO_CONSENT__`, letting the client consent\n * store hydrate without a banner flash. `cookies()` is async in Next 15+, so this\n * helper (and the layout that awaits it) must be async.\n *\n * Importing `next/headers` makes this module server-only; do not re-export it from\n * the client `consent` barrel.\n */\nexport async function readConsentSeed(\n mode: ConsentMode = \"off\",\n): Promise<ConsentSeed> {\n const cookieStore = await cookies();\n const raw = cookieStore.get(CONSENT_COOKIE_NAME)?.value;\n const parsed = parseConsentCookie(raw);\n\n if (!parsed) {\n return { mode, categories: DENIED_CATEGORIES, decidedAt: null };\n }\n\n return {\n mode,\n categories: {\n necessary: true,\n analytics: parsed.categories.analytics,\n marketing: parsed.categories.marketing,\n preferences: parsed.categories.preferences,\n sale_of_data: parsed.categories.sale_of_data,\n },\n decidedAt: parsed.decidedAt,\n };\n}\n"],
5
- "mappings": "AAGA,SAAS,eAAe;AAExB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAWP,eAAsB,gBACpB,OAAoB,OACE;AACtB,QAAM,cAAc,MAAM,QAAQ;AAClC,QAAM,MAAM,YAAY,IAAI,mBAAmB,GAAG;AAClD,QAAM,SAAS,mBAAmB,GAAG;AAErC,MAAI,CAAC,QAAQ;AACX,WAAO,EAAE,MAAM,YAAY,mBAAmB,WAAW,KAAK;AAAA,EAChE;AAEA,SAAO;AAAA,IACL;AAAA,IACA,YAAY;AAAA,MACV,WAAW;AAAA,MACX,WAAW,OAAO,WAAW;AAAA,MAC7B,WAAW,OAAO,WAAW;AAAA,MAC7B,aAAa,OAAO,WAAW;AAAA,MAC/B,cAAc,OAAO,WAAW;AAAA,IAClC;AAAA,IACA,WAAW,OAAO;AAAA,EACpB;AACF;",
6
- "names": []
7
- }