@replohq/canopy-sdk 1.0.2 → 1.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/_vendor/replo-utils/lib/posthogReplay.d.ts +9 -1
- package/_vendor/replo-utils/lib/posthogReplay.mjs +82 -4
- package/_vendor/schemas/loaderKeys.mjs +1 -4
- package/cart/utils/variant-to-cart-line.d.ts +1 -52
- package/cart/utils/variant-to-cart-line.js +1 -58
- package/cart/utils/variant-to-cart-line.js.map +2 -2
- package/editor/posthog-relay.d.ts +1 -0
- package/editor/posthog-relay.js +3 -0
- package/editor/posthog-relay.js.map +2 -2
- package/editor/select-mode/fiber.d.ts +6 -26
- package/editor/select-mode/fiber.js +1 -56
- package/editor/select-mode/fiber.js.map +2 -2
- package/editor/select-mode/symbolicate.d.ts +0 -1
- package/editor/select-mode/symbolicate.js +1 -5
- package/editor/select-mode/symbolicate.js.map +2 -2
- package/env.d.ts +0 -4
- package/env.js +1 -5
- package/env.js.map +2 -2
- package/gateways/canopy-api.d.ts +0 -1
- package/gateways/canopy-api.js +1 -5
- package/gateways/canopy-api.js.map +2 -2
- package/lib/shopify-utils.d.ts +0 -6
- package/lib/shopify-utils.js +0 -4
- package/lib/shopify-utils.js.map +2 -2
- package/loaders/invoke-loader.d.ts +0 -1
- package/loaders/invoke-loader.js +1 -5
- package/loaders/invoke-loader.js.map +2 -2
- package/loaders/loader-keys.d.ts +0 -19
- package/loaders/loader-keys.js +1 -4
- package/loaders/loader-keys.js.map +2 -2
- package/package.json +1 -2
|
@@ -18,6 +18,8 @@ interface PostHogReplayWindow {
|
|
|
18
18
|
};
|
|
19
19
|
addEventListener(type: "message", listener: PostHogReplayMessageListener): void;
|
|
20
20
|
removeEventListener(type: "message", listener: PostHogReplayMessageListener): void;
|
|
21
|
+
setTimeout(listener: () => void, timeout: number): number;
|
|
22
|
+
clearTimeout(timeoutId: number): void;
|
|
21
23
|
}
|
|
22
24
|
declare global {
|
|
23
25
|
interface Window {
|
|
@@ -29,7 +31,13 @@ declare global {
|
|
|
29
31
|
export declare function requestChildPostHogReplaySnapshots({ targetWindow, }: {
|
|
30
32
|
targetWindow: PostHogReplayWindow;
|
|
31
33
|
}): void;
|
|
32
|
-
export declare function
|
|
34
|
+
export declare function startPostHogReplaySnapshotCascade({ isRecordingStarted, targetWindow, onReady, }: {
|
|
35
|
+
isRecordingStarted: () => boolean;
|
|
36
|
+
targetWindow: PostHogReplayWindow;
|
|
37
|
+
onReady?: () => void;
|
|
38
|
+
}): () => void;
|
|
39
|
+
export declare function startChildPostHogReplaySnapshotRelay({ isRecordingStarted, targetWindow, }: {
|
|
40
|
+
isRecordingStarted: () => boolean;
|
|
33
41
|
targetWindow: PostHogReplayWindow;
|
|
34
42
|
}): () => void;
|
|
35
43
|
export {};
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
// ../replo-utils/lib/posthogReplay.ts
|
|
2
2
|
var POSTHOG_REPLAY_SNAPSHOT_REQUEST = "posthog:replay:request-full-snapshot";
|
|
3
|
+
var POSTHOG_REPLAY_READY_POLL_INTERVAL_MS = 100;
|
|
4
|
+
var POSTHOG_REPLAY_READY_POLL_TIMEOUT_MS = 1e4;
|
|
3
5
|
function requestChildPostHogReplaySnapshots({
|
|
4
6
|
targetWindow
|
|
5
7
|
}) {
|
|
@@ -11,8 +13,12 @@ function requestChildPostHogReplaySnapshots({
|
|
|
11
13
|
}
|
|
12
14
|
}
|
|
13
15
|
function takePostHogReplayFullSnapshot({
|
|
16
|
+
isRecordingStarted,
|
|
14
17
|
targetWindow
|
|
15
18
|
}) {
|
|
19
|
+
if (!isRecordingStarted()) {
|
|
20
|
+
return false;
|
|
21
|
+
}
|
|
16
22
|
const takeFullSnapshot = targetWindow.__PosthogExtensions__?.rrweb?.record.takeFullSnapshot;
|
|
17
23
|
if (!takeFullSnapshot) {
|
|
18
24
|
return false;
|
|
@@ -24,20 +30,92 @@ function takePostHogReplayFullSnapshot({
|
|
|
24
30
|
return false;
|
|
25
31
|
}
|
|
26
32
|
}
|
|
33
|
+
function startPostHogReplaySnapshotCascade({
|
|
34
|
+
isRecordingStarted,
|
|
35
|
+
targetWindow,
|
|
36
|
+
onReady
|
|
37
|
+
}) {
|
|
38
|
+
const replayReadyPollDeadline = Date.now() + POSTHOG_REPLAY_READY_POLL_TIMEOUT_MS;
|
|
39
|
+
let timeoutId;
|
|
40
|
+
let stopCascading;
|
|
41
|
+
const startCascadingWhenReady = () => {
|
|
42
|
+
const record = targetWindow.__PosthogExtensions__?.rrweb?.record;
|
|
43
|
+
const takeFullSnapshot = record?.takeFullSnapshot;
|
|
44
|
+
if (!record || !takeFullSnapshot || !isRecordingStarted()) {
|
|
45
|
+
if (Date.now() < replayReadyPollDeadline) {
|
|
46
|
+
timeoutId = targetWindow.setTimeout(
|
|
47
|
+
startCascadingWhenReady,
|
|
48
|
+
POSTHOG_REPLAY_READY_POLL_INTERVAL_MS
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
const takeFullSnapshotAndCascade = () => {
|
|
54
|
+
takeFullSnapshot();
|
|
55
|
+
requestChildPostHogReplaySnapshots({ targetWindow });
|
|
56
|
+
};
|
|
57
|
+
record.takeFullSnapshot = takeFullSnapshotAndCascade;
|
|
58
|
+
stopCascading = () => {
|
|
59
|
+
if (record.takeFullSnapshot === takeFullSnapshotAndCascade) {
|
|
60
|
+
record.takeFullSnapshot = takeFullSnapshot;
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
onReady?.();
|
|
64
|
+
};
|
|
65
|
+
startCascadingWhenReady();
|
|
66
|
+
return () => {
|
|
67
|
+
if (timeoutId !== void 0) {
|
|
68
|
+
targetWindow.clearTimeout(timeoutId);
|
|
69
|
+
}
|
|
70
|
+
stopCascading?.();
|
|
71
|
+
};
|
|
72
|
+
}
|
|
27
73
|
function startChildPostHogReplaySnapshotRelay({
|
|
74
|
+
isRecordingStarted,
|
|
28
75
|
targetWindow
|
|
29
76
|
}) {
|
|
77
|
+
if (targetWindow.parent === targetWindow) {
|
|
78
|
+
return () => {
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
let hasPendingSnapshotRequest = false;
|
|
82
|
+
let isSnapshotCascadeReady = false;
|
|
83
|
+
let stopCascadingSnapshots = () => {
|
|
84
|
+
};
|
|
85
|
+
const startCascadingSnapshots = () => {
|
|
86
|
+
stopCascadingSnapshots();
|
|
87
|
+
isSnapshotCascadeReady = false;
|
|
88
|
+
stopCascadingSnapshots = startPostHogReplaySnapshotCascade({
|
|
89
|
+
isRecordingStarted,
|
|
90
|
+
targetWindow,
|
|
91
|
+
onReady: () => {
|
|
92
|
+
isSnapshotCascadeReady = true;
|
|
93
|
+
if (hasPendingSnapshotRequest) {
|
|
94
|
+
hasPendingSnapshotRequest = false;
|
|
95
|
+
takePostHogReplayFullSnapshot({ isRecordingStarted, targetWindow });
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
});
|
|
99
|
+
};
|
|
100
|
+
startCascadingSnapshots();
|
|
30
101
|
const onMessage = (event) => {
|
|
31
102
|
if (event.source !== targetWindow.parent || event.data !== POSTHOG_REPLAY_SNAPSHOT_REQUEST) {
|
|
32
103
|
return;
|
|
33
104
|
}
|
|
34
|
-
if (!takePostHogReplayFullSnapshot({ targetWindow })) {
|
|
105
|
+
if (!takePostHogReplayFullSnapshot({ isRecordingStarted, targetWindow })) {
|
|
106
|
+
hasPendingSnapshotRequest = true;
|
|
107
|
+
startCascadingSnapshots();
|
|
35
108
|
return;
|
|
36
109
|
}
|
|
37
|
-
|
|
110
|
+
if (!isSnapshotCascadeReady) {
|
|
111
|
+
requestChildPostHogReplaySnapshots({ targetWindow });
|
|
112
|
+
}
|
|
38
113
|
};
|
|
39
114
|
targetWindow.addEventListener("message", onMessage);
|
|
40
|
-
return () =>
|
|
115
|
+
return () => {
|
|
116
|
+
stopCascadingSnapshots();
|
|
117
|
+
targetWindow.removeEventListener("message", onMessage);
|
|
118
|
+
};
|
|
41
119
|
}
|
|
42
120
|
|
|
43
|
-
export { POSTHOG_REPLAY_SNAPSHOT_REQUEST, requestChildPostHogReplaySnapshots, startChildPostHogReplaySnapshotRelay };
|
|
121
|
+
export { POSTHOG_REPLAY_SNAPSHOT_REQUEST, requestChildPostHogReplaySnapshots, startChildPostHogReplaySnapshotRelay, startPostHogReplaySnapshotCascade };
|
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
import { z } from 'zod';
|
|
2
|
-
|
|
3
1
|
// loaders/loader-keys.ts
|
|
4
2
|
var DATA_LOADER_KEYS = {
|
|
5
3
|
SHOPIFY_PRODUCT: "shopify_storefront.product",
|
|
@@ -19,6 +17,5 @@ var DATA_LOADER_KEYS = {
|
|
|
19
17
|
CONTENTFUL_ENTRY: "contentful.entry",
|
|
20
18
|
CONTENTFUL_ENTRIES: "contentful.entries"
|
|
21
19
|
};
|
|
22
|
-
var dataLoaderKeySchema = z.enum(Object.values(DATA_LOADER_KEYS));
|
|
23
20
|
|
|
24
|
-
export { DATA_LOADER_KEYS
|
|
21
|
+
export { DATA_LOADER_KEYS };
|
|
@@ -1,54 +1,4 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
import type { CartLine, CartLineAttribute, CartLineMerchandise, CartLinePayload, SellingPlanAllocation } from "../cart-types";
|
|
3
|
-
interface ProductVariant {
|
|
4
|
-
id: string;
|
|
5
|
-
externalId?: string;
|
|
6
|
-
title: string;
|
|
7
|
-
price: number;
|
|
8
|
-
originalPrice: number | null;
|
|
9
|
-
optionValues?: {
|
|
10
|
-
id: string;
|
|
11
|
-
value: string;
|
|
12
|
-
color: string | null;
|
|
13
|
-
image: string | null;
|
|
14
|
-
imageUrls: string[];
|
|
15
|
-
referenceType: "SHOPIFY" | "REPLO";
|
|
16
|
-
}[];
|
|
17
|
-
}
|
|
18
|
-
export interface VariantToCartLineProduct {
|
|
19
|
-
id: string;
|
|
20
|
-
title: string;
|
|
21
|
-
featuredMedia?: {
|
|
22
|
-
type: string;
|
|
23
|
-
url: string;
|
|
24
|
-
alt?: string;
|
|
25
|
-
} | null;
|
|
26
|
-
sellingPlanGroups?: SellingPlanGroup[];
|
|
27
|
-
}
|
|
28
|
-
interface VariantToCartLineOptions {
|
|
29
|
-
quantity?: number;
|
|
30
|
-
properties?: CartLineAttribute[];
|
|
31
|
-
sellingPlanId?: string | null;
|
|
32
|
-
pricing?: {
|
|
33
|
-
compareAtPrice: number;
|
|
34
|
-
discountPercentage: number;
|
|
35
|
-
};
|
|
36
|
-
bundle?: {
|
|
37
|
-
bundleId: string;
|
|
38
|
-
bundleDiscount: number;
|
|
39
|
-
};
|
|
40
|
-
includeMerchandise?: boolean;
|
|
41
|
-
product?: VariantToCartLineProduct;
|
|
42
|
-
}
|
|
43
|
-
/**
|
|
44
|
-
* Converts a product variant to a cart line payload.
|
|
45
|
-
* This is the primary function for creating cart lines from variants.
|
|
46
|
-
*
|
|
47
|
-
* When a ProductVariant has both `price` and `originalPrice`, the function will
|
|
48
|
-
* automatically calculate and include pricing attributes (compareAtPrice and discountPercentage)
|
|
49
|
-
* unless explicitly overridden in the options.
|
|
50
|
-
*/
|
|
51
|
-
export declare function variantToCartLine(variant: ProductVariant, options?: VariantToCartLineOptions): CartLinePayload;
|
|
1
|
+
import type { CartLine, CartLineMerchandise, SellingPlanAllocation } from "../cart-types";
|
|
52
2
|
/**
|
|
53
3
|
* Gets a specific attribute value from a cart line.
|
|
54
4
|
*
|
|
@@ -122,4 +72,3 @@ export declare function createOptimisticSellingPlanAllocation({ merchandise, sel
|
|
|
122
72
|
sellingPlanId: string | null;
|
|
123
73
|
currencyCode?: string;
|
|
124
74
|
}): SellingPlanAllocation | null;
|
|
125
|
-
export {};
|
|
@@ -1,6 +1,4 @@
|
|
|
1
1
|
import { fromMajorUnitsToMinorUnits } from "../../_vendor/schemas/money.mjs";
|
|
2
|
-
import { convertLegacyResourceIdToGraphQLId } from "../../lib/shopify-utils";
|
|
3
|
-
import { formatSellingPlanId } from "./cart-utils";
|
|
4
2
|
function applyPriceAdjustment(variantPrice, adjustment, currencyCode) {
|
|
5
3
|
switch (adjustment.valueType) {
|
|
6
4
|
// NOTE (Max, 2026-08-03): variantPrice is integer minor units, but the
|
|
@@ -27,60 +25,6 @@ function applyPriceAdjustment(variantPrice, adjustment, currencyCode) {
|
|
|
27
25
|
);
|
|
28
26
|
}
|
|
29
27
|
}
|
|
30
|
-
function variantToCartLine(variant, options) {
|
|
31
|
-
const quantity = options?.quantity ?? 1;
|
|
32
|
-
const baseProperties = options?.properties ?? [];
|
|
33
|
-
const sellingPlanId = formatSellingPlanId(options?.sellingPlanId ?? null);
|
|
34
|
-
const additionalProperties = [];
|
|
35
|
-
if (options?.bundle) {
|
|
36
|
-
additionalProperties.push(
|
|
37
|
-
...createBundleAttributes(
|
|
38
|
-
options.bundle.bundleId,
|
|
39
|
-
options.bundle.bundleDiscount
|
|
40
|
-
)
|
|
41
|
-
);
|
|
42
|
-
}
|
|
43
|
-
const allProperties = [...baseProperties, ...additionalProperties];
|
|
44
|
-
const cartLine = {
|
|
45
|
-
id: variant.externalId ? convertLegacyResourceIdToGraphQLId(variant.externalId, "ProductVariant") : variant.id,
|
|
46
|
-
quantity,
|
|
47
|
-
properties: allProperties,
|
|
48
|
-
sellingPlanId
|
|
49
|
-
};
|
|
50
|
-
if (options?.includeMerchandise && options.product) {
|
|
51
|
-
const { product } = options;
|
|
52
|
-
cartLine.merchandise = {
|
|
53
|
-
id: variant.externalId ? convertLegacyResourceIdToGraphQLId(
|
|
54
|
-
variant.externalId,
|
|
55
|
-
"ProductVariant"
|
|
56
|
-
) : variant.id,
|
|
57
|
-
product: {
|
|
58
|
-
id: product.id,
|
|
59
|
-
title: product.title,
|
|
60
|
-
sellingPlanGroups: product.sellingPlanGroups
|
|
61
|
-
},
|
|
62
|
-
title: variant.title ?? `${product.title} - ${variant.id}`,
|
|
63
|
-
price: variant.price ?? 0,
|
|
64
|
-
compareAtPrice: variant.originalPrice,
|
|
65
|
-
image: product.featuredMedia?.type === "image" ? {
|
|
66
|
-
url: product.featuredMedia.url,
|
|
67
|
-
altText: product.featuredMedia.alt ?? product.title
|
|
68
|
-
} : null,
|
|
69
|
-
selectedOptions: variant.optionValues?.map((opt) => ({
|
|
70
|
-
name: opt.value,
|
|
71
|
-
value: opt.value
|
|
72
|
-
})) ?? []
|
|
73
|
-
};
|
|
74
|
-
}
|
|
75
|
-
return cartLine;
|
|
76
|
-
}
|
|
77
|
-
function createBundleAttributes(bundleId, bundleDiscount) {
|
|
78
|
-
return [
|
|
79
|
-
{ key: "bundleId", value: bundleId },
|
|
80
|
-
{ key: "bundleDiscount", value: bundleDiscount },
|
|
81
|
-
{ key: "isBundleItem", value: true }
|
|
82
|
-
];
|
|
83
|
-
}
|
|
84
28
|
function getCartLineAttribute(cartLine, key) {
|
|
85
29
|
return cartLine.attributes.find((attr) => attr.key === key)?.value;
|
|
86
30
|
}
|
|
@@ -213,7 +157,6 @@ export {
|
|
|
213
157
|
getCartLineBundleInfo,
|
|
214
158
|
getCartLinePricing,
|
|
215
159
|
getCartLineSpecialInfo,
|
|
216
|
-
getCartLineSubscriptionInfo
|
|
217
|
-
variantToCartLine
|
|
160
|
+
getCartLineSubscriptionInfo
|
|
218
161
|
};
|
|
219
162
|
//# sourceMappingURL=variant-to-cart-line.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../cart/utils/variant-to-cart-line.ts"],
|
|
4
|
-
"sourcesContent": ["import type { SellingPlanGroup } from \"../../loaders/loader-schemas\";\nimport type {\n CartLine,\n CartLineAttribute,\n CartLineMerchandise,\n CartLinePayload,\n SellingPlanAllocation,\n} from \"../cart-types\";\n\nimport { fromMajorUnitsToMinorUnits } from \"schemas/money\";\n\nimport { convertLegacyResourceIdToGraphQLId } from \"../../lib/shopify-utils\";\nimport { formatSellingPlanId } from \"./cart-utils\";\n\n// TODO: Temporary \u2014 minimal local type after removing features/product. Replace with loader/canonical variant type when data loaders are in place.\ninterface ProductVariant {\n id: string;\n externalId?: string;\n title: string;\n price: number;\n originalPrice: number | null;\n optionValues?: {\n id: string;\n value: string;\n color: string | null;\n image: string | null;\n imageUrls: string[];\n referenceType: \"SHOPIFY\" | \"REPLO\";\n }[];\n}\n\n// TODO: Temporary \u2014 inlined from removed features/product/utils/pricing-utils. Keep until cart uses canonical product/loader types.\nfunction applyPriceAdjustment(\n variantPrice: number,\n adjustment: {\n value: number;\n valueType: \"percentage\" | \"fixedAmount\" | \"price\";\n },\n currencyCode: string,\n): number {\n switch (adjustment.valueType) {\n // NOTE (Max, 2026-08-03): variantPrice is integer minor units, but the\n // loader emits money-typed adjustments as decimal major units (its\n // storefront contract), so the price/fixedAmount arms convert here at the\n // cart boundary. Percentage is unitless and needs no conversion.\n case \"price\":\n return fromMajorUnitsToMinorUnits({\n amount: adjustment.value,\n currencyCode,\n });\n case \"percentage\":\n return Math.max(\n 0,\n Math.round(variantPrice * (1 - adjustment.value / 100)),\n );\n case \"fixedAmount\":\n return Math.max(\n 0,\n variantPrice -\n fromMajorUnitsToMinorUnits({\n amount: adjustment.value,\n currencyCode,\n }),\n );\n }\n}\n\n// === Variant to Cart Line Conversion ===\n\nexport interface VariantToCartLineProduct {\n id: string;\n title: string;\n featuredMedia?: {\n type: string;\n url: string;\n alt?: string;\n } | null;\n sellingPlanGroups?: SellingPlanGroup[];\n}\n\ninterface VariantToCartLineOptions {\n quantity?: number;\n properties?: CartLineAttribute[];\n sellingPlanId?: string | null;\n pricing?: {\n compareAtPrice: number;\n discountPercentage: number;\n };\n bundle?: {\n bundleId: string;\n bundleDiscount: number;\n };\n includeMerchandise?: boolean;\n product?: VariantToCartLineProduct;\n}\n\n/**\n * Converts a product variant to a cart line payload.\n * This is the primary function for creating cart lines from variants.\n *\n * When a ProductVariant has both `price` and `originalPrice`, the function will\n * automatically calculate and include pricing attributes (compareAtPrice and discountPercentage)\n * unless explicitly overridden in the options.\n */\nexport function variantToCartLine(\n variant: ProductVariant,\n options?: VariantToCartLineOptions,\n): CartLinePayload {\n const quantity = options?.quantity ?? 1;\n const baseProperties = options?.properties ?? [];\n const sellingPlanId = formatSellingPlanId(options?.sellingPlanId ?? null);\n\n // Create additional properties based on options\n const additionalProperties: CartLineAttribute[] = [];\n\n if (options?.bundle) {\n additionalProperties.push(\n ...createBundleAttributes(\n options.bundle.bundleId,\n options.bundle.bundleDiscount,\n ),\n );\n }\n\n const allProperties = [...baseProperties, ...additionalProperties];\n\n const cartLine: CartLinePayload = {\n id: variant.externalId\n ? convertLegacyResourceIdToGraphQLId(variant.externalId, \"ProductVariant\")\n : variant.id,\n quantity,\n properties: allProperties,\n sellingPlanId,\n };\n\n // Add merchandise if requested and we have product data\n if (options?.includeMerchandise && options.product) {\n const { product } = options;\n\n cartLine.merchandise = {\n id: variant.externalId\n ? convertLegacyResourceIdToGraphQLId(\n variant.externalId,\n \"ProductVariant\",\n )\n : variant.id,\n product: {\n id: product.id,\n title: product.title,\n sellingPlanGroups: product.sellingPlanGroups,\n },\n title: variant.title ?? `${product.title} - ${variant.id}`,\n price: variant.price ?? 0,\n compareAtPrice: variant.originalPrice,\n image:\n product.featuredMedia?.type === \"image\"\n ? {\n url: product.featuredMedia.url,\n altText: product.featuredMedia.alt ?? product.title,\n }\n : null,\n selectedOptions:\n variant.optionValues?.map((opt) => ({\n name: opt.value,\n value: opt.value,\n })) ?? [],\n };\n }\n\n return cartLine;\n}\n\n// === Cart Attributes Functions ===\n\n/**\n * Creates cart line attributes for bundle items.\n *\n * @param bundleId - The ID of the bundle\n * @param bundleDiscount - The discount amount for the bundle\n * @returns Array of cart line attributes for bundle metadata\n */\nfunction createBundleAttributes(\n bundleId: string,\n bundleDiscount: number,\n): CartLineAttribute[] {\n return [\n { key: \"bundleId\", value: bundleId },\n { key: \"bundleDiscount\", value: bundleDiscount },\n { key: \"isBundleItem\", value: true },\n ];\n}\n\n// === Cart Line Utilities ===\n\n/**\n * Gets a specific attribute value from a cart line.\n *\n * @param cartLine - The cart line to get the attribute from\n * @param key - The attribute key to retrieve\n * @returns The attribute value, or undefined if not found\n */\nexport function getCartLineAttribute(\n cartLine: CartLine,\n key: string,\n): string | number | boolean | undefined {\n return cartLine.attributes.find((attr: CartLineAttribute) => attr.key === key)\n ?.value;\n}\n\n/**\n * Calculates pricing information for a cart line, including discounts and\n * selling plan adjustments.\n *\n * @param cartLine - The cart line to calculate pricing for\n * @returns Object containing compareAtPrice, discountPercentage, hasDiscount, sellingPlanAdjustedPrice, and finalPrice\n */\nexport function getCartLinePricing(cartLine: CartLine) {\n if (!cartLine.merchandise) {\n return {\n compareAtPrice: 0,\n discountPercentage: 0,\n hasDiscount: false,\n sellingPlanAdjustedPrice: 0,\n finalPrice: 0,\n };\n }\n\n const compareAtPrice = cartLine.merchandise.compareAtPrice ?? 0;\n const currentPrice = cartLine.merchandise.price;\n const discountPercentage =\n compareAtPrice > currentPrice\n ? ((compareAtPrice - currentPrice) / compareAtPrice) * 100\n : 0;\n const hasDiscount = compareAtPrice > currentPrice;\n\n let sellingPlanAdjustedPrice = cartLine.merchandise.price;\n if (\n cartLine.sellingPlanAllocation &&\n cartLine.sellingPlanAllocation.priceAdjustments.length > 0 &&\n cartLine.sellingPlanAllocation.priceAdjustments[0]?.price\n ) {\n // Use the price from the first price adjustment, which represents the selling plan price\n sellingPlanAdjustedPrice =\n cartLine.sellingPlanAllocation.priceAdjustments[0]!.price.amount;\n }\n\n return {\n compareAtPrice,\n discountPercentage,\n hasDiscount: hasDiscount,\n sellingPlanAdjustedPrice,\n finalPrice: sellingPlanAdjustedPrice,\n };\n}\n\n/**\n * Extracts bundle information from cart line attributes.\n *\n * @param cartLine - The cart line to get bundle info from\n * @returns Object containing bundle ID, discount, and whether it's a bundle item\n */\nexport function getCartLineBundleInfo(cartLine: CartLine) {\n // Legacy cast - may or may not be necessary\n // eslint-disable-next-line replo/no-as-cast\n const bundleId = getCartLineAttribute(cartLine, \"bundleId\") as string;\n const bundleDiscount = Number(\n getCartLineAttribute(cartLine, \"bundleDiscount\") ?? 0,\n );\n // Legacy cast - may or may not be necessary\n // eslint-disable-next-line replo/no-as-cast\n const isBundleItem = getCartLineAttribute(\n cartLine,\n \"isBundleItem\",\n ) as boolean;\n\n return {\n bundleId: bundleId ?? null,\n bundleDiscount,\n isBundleItem: isBundleItem ?? false,\n };\n}\n\n/**\n * Extracts special item information from cart line attributes.\n *\n * @param cartLine - The cart line to get special info from\n * @returns Object containing whether it's a special item and any special instructions\n */\nexport function getCartLineSpecialInfo(cartLine: CartLine) {\n // Legacy cast - may or may not be necessary\n // eslint-disable-next-line replo/no-as-cast\n const isSpecialItem = getCartLineAttribute(\n cartLine,\n \"isSpecialItem\",\n ) as boolean;\n // Legacy cast - may or may not be necessary\n // eslint-disable-next-line replo/no-as-cast\n const specialInstructions = getCartLineAttribute(\n cartLine,\n \"specialInstructions\",\n ) as string;\n\n return {\n isSpecialItem: isSpecialItem ?? false,\n specialInstructions: specialInstructions\n ? specialInstructions.split(\"|\")\n : [],\n };\n}\n\n/**\n * Extracts subscription (selling plan) information from a cart line.\n *\n * @param cartLine - The cart line to get subscription info from\n * @returns Object containing isSubscription, frequency, discount, and sellingPlan\n */\nexport function getCartLineSubscriptionInfo(cartLine: CartLine) {\n if (cartLine.sellingPlanAllocation) {\n return {\n isSubscription: true,\n frequency: cartLine.sellingPlanAllocation.sellingPlan.name,\n discount: 0, // Shopify calculates this from price adjustments when available\n sellingPlan: cartLine.sellingPlanAllocation.sellingPlan,\n };\n }\n\n // No subscription if no sellingPlanAllocation\n return {\n isSubscription: false,\n frequency: null,\n discount: 0,\n sellingPlan: null,\n };\n}\n\n/**\n * Creates an optimistic selling plan allocation using product data.\n * This matches the exact structure that Shopify returns so the UI doesn't need conditional logic.\n */\nexport function createOptimisticSellingPlanAllocation({\n merchandise,\n sellingPlanId,\n currencyCode = \"USD\",\n}: {\n merchandise: CartLineMerchandise;\n sellingPlanId: string | null;\n currencyCode?: string;\n}): SellingPlanAllocation | null {\n const { product, price: variantPrice } = merchandise;\n\n if (!sellingPlanId || !product.sellingPlanGroups) {\n return null;\n }\n\n // Find the selling plan in the product's selling plan groups\n for (const group of product.sellingPlanGroups) {\n const sellingPlan = group.sellingPlans.find(\n (sp) => sp.id === sellingPlanId,\n );\n if (sellingPlan) {\n return {\n sellingPlan: {\n id: sellingPlan.id,\n name: sellingPlan.name,\n description: sellingPlan.description,\n },\n priceAdjustments: sellingPlan.priceAdjustments.map((adj) => {\n const adjustedPrice =\n variantPrice !== undefined\n ? applyPriceAdjustment(variantPrice, adj, currencyCode)\n : 0;\n\n return {\n compareAtPrice: {\n amount: variantPrice ?? 0,\n currencyCode,\n },\n perDeliveryPrice: {\n amount: adjustedPrice,\n currencyCode,\n },\n price: {\n amount: adjustedPrice,\n currencyCode,\n },\n unitPrice: null,\n };\n }),\n checkoutChargeAmount: {\n amount: 0,\n currencyCode,\n },\n remainingBalanceChargeAmount: {\n amount: 0,\n currencyCode,\n },\n };\n }\n }\n\n return null;\n}\n"],
|
|
5
|
-
"mappings": "
|
|
4
|
+
"sourcesContent": ["import type {\n CartLine,\n CartLineAttribute,\n CartLineMerchandise,\n SellingPlanAllocation,\n} from \"../cart-types\";\n\nimport { fromMajorUnitsToMinorUnits } from \"schemas/money\";\n\n// TODO: Temporary \u2014 inlined from removed features/product/utils/pricing-utils. Keep until cart uses canonical product/loader types.\nfunction applyPriceAdjustment(\n variantPrice: number,\n adjustment: {\n value: number;\n valueType: \"percentage\" | \"fixedAmount\" | \"price\";\n },\n currencyCode: string,\n): number {\n switch (adjustment.valueType) {\n // NOTE (Max, 2026-08-03): variantPrice is integer minor units, but the\n // loader emits money-typed adjustments as decimal major units (its\n // storefront contract), so the price/fixedAmount arms convert here at the\n // cart boundary. Percentage is unitless and needs no conversion.\n case \"price\":\n return fromMajorUnitsToMinorUnits({\n amount: adjustment.value,\n currencyCode,\n });\n case \"percentage\":\n return Math.max(\n 0,\n Math.round(variantPrice * (1 - adjustment.value / 100)),\n );\n case \"fixedAmount\":\n return Math.max(\n 0,\n variantPrice -\n fromMajorUnitsToMinorUnits({\n amount: adjustment.value,\n currencyCode,\n }),\n );\n }\n}\n\n// === Cart Line Utilities ===\n\n/**\n * Gets a specific attribute value from a cart line.\n *\n * @param cartLine - The cart line to get the attribute from\n * @param key - The attribute key to retrieve\n * @returns The attribute value, or undefined if not found\n */\nexport function getCartLineAttribute(\n cartLine: CartLine,\n key: string,\n): string | number | boolean | undefined {\n return cartLine.attributes.find((attr: CartLineAttribute) => attr.key === key)\n ?.value;\n}\n\n/**\n * Calculates pricing information for a cart line, including discounts and\n * selling plan adjustments.\n *\n * @param cartLine - The cart line to calculate pricing for\n * @returns Object containing compareAtPrice, discountPercentage, hasDiscount, sellingPlanAdjustedPrice, and finalPrice\n */\nexport function getCartLinePricing(cartLine: CartLine) {\n if (!cartLine.merchandise) {\n return {\n compareAtPrice: 0,\n discountPercentage: 0,\n hasDiscount: false,\n sellingPlanAdjustedPrice: 0,\n finalPrice: 0,\n };\n }\n\n const compareAtPrice = cartLine.merchandise.compareAtPrice ?? 0;\n const currentPrice = cartLine.merchandise.price;\n const discountPercentage =\n compareAtPrice > currentPrice\n ? ((compareAtPrice - currentPrice) / compareAtPrice) * 100\n : 0;\n const hasDiscount = compareAtPrice > currentPrice;\n\n let sellingPlanAdjustedPrice = cartLine.merchandise.price;\n if (\n cartLine.sellingPlanAllocation &&\n cartLine.sellingPlanAllocation.priceAdjustments.length > 0 &&\n cartLine.sellingPlanAllocation.priceAdjustments[0]?.price\n ) {\n // Use the price from the first price adjustment, which represents the selling plan price\n sellingPlanAdjustedPrice =\n cartLine.sellingPlanAllocation.priceAdjustments[0]!.price.amount;\n }\n\n return {\n compareAtPrice,\n discountPercentage,\n hasDiscount: hasDiscount,\n sellingPlanAdjustedPrice,\n finalPrice: sellingPlanAdjustedPrice,\n };\n}\n\n/**\n * Extracts bundle information from cart line attributes.\n *\n * @param cartLine - The cart line to get bundle info from\n * @returns Object containing bundle ID, discount, and whether it's a bundle item\n */\nexport function getCartLineBundleInfo(cartLine: CartLine) {\n // Legacy cast - may or may not be necessary\n // eslint-disable-next-line replo/no-as-cast\n const bundleId = getCartLineAttribute(cartLine, \"bundleId\") as string;\n const bundleDiscount = Number(\n getCartLineAttribute(cartLine, \"bundleDiscount\") ?? 0,\n );\n // Legacy cast - may or may not be necessary\n // eslint-disable-next-line replo/no-as-cast\n const isBundleItem = getCartLineAttribute(\n cartLine,\n \"isBundleItem\",\n ) as boolean;\n\n return {\n bundleId: bundleId ?? null,\n bundleDiscount,\n isBundleItem: isBundleItem ?? false,\n };\n}\n\n/**\n * Extracts special item information from cart line attributes.\n *\n * @param cartLine - The cart line to get special info from\n * @returns Object containing whether it's a special item and any special instructions\n */\nexport function getCartLineSpecialInfo(cartLine: CartLine) {\n // Legacy cast - may or may not be necessary\n // eslint-disable-next-line replo/no-as-cast\n const isSpecialItem = getCartLineAttribute(\n cartLine,\n \"isSpecialItem\",\n ) as boolean;\n // Legacy cast - may or may not be necessary\n // eslint-disable-next-line replo/no-as-cast\n const specialInstructions = getCartLineAttribute(\n cartLine,\n \"specialInstructions\",\n ) as string;\n\n return {\n isSpecialItem: isSpecialItem ?? false,\n specialInstructions: specialInstructions\n ? specialInstructions.split(\"|\")\n : [],\n };\n}\n\n/**\n * Extracts subscription (selling plan) information from a cart line.\n *\n * @param cartLine - The cart line to get subscription info from\n * @returns Object containing isSubscription, frequency, discount, and sellingPlan\n */\nexport function getCartLineSubscriptionInfo(cartLine: CartLine) {\n if (cartLine.sellingPlanAllocation) {\n return {\n isSubscription: true,\n frequency: cartLine.sellingPlanAllocation.sellingPlan.name,\n discount: 0, // Shopify calculates this from price adjustments when available\n sellingPlan: cartLine.sellingPlanAllocation.sellingPlan,\n };\n }\n\n // No subscription if no sellingPlanAllocation\n return {\n isSubscription: false,\n frequency: null,\n discount: 0,\n sellingPlan: null,\n };\n}\n\n/**\n * Creates an optimistic selling plan allocation using product data.\n * This matches the exact structure that Shopify returns so the UI doesn't need conditional logic.\n */\nexport function createOptimisticSellingPlanAllocation({\n merchandise,\n sellingPlanId,\n currencyCode = \"USD\",\n}: {\n merchandise: CartLineMerchandise;\n sellingPlanId: string | null;\n currencyCode?: string;\n}): SellingPlanAllocation | null {\n const { product, price: variantPrice } = merchandise;\n\n if (!sellingPlanId || !product.sellingPlanGroups) {\n return null;\n }\n\n // Find the selling plan in the product's selling plan groups\n for (const group of product.sellingPlanGroups) {\n const sellingPlan = group.sellingPlans.find(\n (sp) => sp.id === sellingPlanId,\n );\n if (sellingPlan) {\n return {\n sellingPlan: {\n id: sellingPlan.id,\n name: sellingPlan.name,\n description: sellingPlan.description,\n },\n priceAdjustments: sellingPlan.priceAdjustments.map((adj) => {\n const adjustedPrice =\n variantPrice !== undefined\n ? applyPriceAdjustment(variantPrice, adj, currencyCode)\n : 0;\n\n return {\n compareAtPrice: {\n amount: variantPrice ?? 0,\n currencyCode,\n },\n perDeliveryPrice: {\n amount: adjustedPrice,\n currencyCode,\n },\n price: {\n amount: adjustedPrice,\n currencyCode,\n },\n unitPrice: null,\n };\n }),\n checkoutChargeAmount: {\n amount: 0,\n currencyCode,\n },\n remainingBalanceChargeAmount: {\n amount: 0,\n currencyCode,\n },\n };\n }\n }\n\n return null;\n}\n"],
|
|
5
|
+
"mappings": "AAOA,SAAS,kCAAkC;AAG3C,SAAS,qBACP,cACA,YAIA,cACQ;AACR,UAAQ,WAAW,WAAW;AAAA;AAAA;AAAA;AAAA;AAAA,IAK5B,KAAK;AACH,aAAO,2BAA2B;AAAA,QAChC,QAAQ,WAAW;AAAA,QACnB;AAAA,MACF,CAAC;AAAA,IACH,KAAK;AACH,aAAO,KAAK;AAAA,QACV;AAAA,QACA,KAAK,MAAM,gBAAgB,IAAI,WAAW,QAAQ,IAAI;AAAA,MACxD;AAAA,IACF,KAAK;AACH,aAAO,KAAK;AAAA,QACV;AAAA,QACA,eACE,2BAA2B;AAAA,UACzB,QAAQ,WAAW;AAAA,UACn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R;AAAA,QACF;AAAA,QACA,8BAA8B;AAAA,UAC5B,QAAQ;AAAA,UACR;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/editor/posthog-relay.js
CHANGED
|
@@ -56,6 +56,9 @@ function initPostHogRelay() {
|
|
|
56
56
|
function PostHogRelay() {
|
|
57
57
|
useEffect(() => {
|
|
58
58
|
const stopRelayingSnapshotRequests = startChildPostHogReplaySnapshotRelay({
|
|
59
|
+
isRecordingStarted: () => {
|
|
60
|
+
return window.posthog?.sessionRecordingStarted() ?? false;
|
|
61
|
+
},
|
|
59
62
|
targetWindow: window
|
|
60
63
|
});
|
|
61
64
|
void initPostHogRelay();
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../editor/posthog-relay.tsx"],
|
|
4
|
-
"sourcesContent": ["\"use client\";\n\n/**\n * PostHog Cross-Origin Iframe Relay\n *\n * Initializes PostHog inside the sandbox iframe as a \"relay\" - it captures DOM\n * mutations via rrweb and sends them to the parent window's PostHog instance\n * via postMessage, enabling session recordings to include iframe content.\n */\nimport { useEffect } from \"react\";\n\nimport { startChildPostHogReplaySnapshotRelay } from \"replo-utils/lib/posthogReplay\";\n\nconst POSTHOG_API_KEY = \"phc_dRETsj85vNkKrvQQszEFRBibH5kUF9l7rbjACuKPanZ\";\nconst POSTHOG_API_HOST = \"https://d99bbtllqsaif.cloudfront.net\";\n\ninterface PostHog {\n init: (apiKey: string, config: Record<string, unknown>) => void;\n}\n\ndeclare global {\n interface Window {\n posthog?: PostHog;\n }\n}\n\nlet initPromise: Promise<void> | null = null;\n\nfunction loadPostHogScript() {\n return new Promise<void>((resolve) => {\n if (window.posthog) {\n resolve();\n return;\n }\n\n const script = document.createElement(\"script\");\n script.src = `${POSTHOG_API_HOST}/static/array.js`;\n script.async = true;\n script.addEventListener(\"load\", () => resolve());\n script.addEventListener(\"error\", () => {\n resolve();\n console.warn(\"[PostHog Relay] Failed to load PostHog script\");\n });\n document.head.append(script);\n });\n}\n\nfunction initPostHogRelay() {\n if (window.self === window.top) {\n return Promise.resolve();\n }\n\n if (initPromise) {\n return initPromise;\n }\n\n initPromise = (async () => {\n await loadPostHogScript();\n\n if (!window.posthog) {\n initPromise = null;\n console.warn(\"[PostHog Relay] PostHog not available after script load\");\n return;\n }\n\n window.posthog.init(POSTHOG_API_KEY, {\n api_host: POSTHOG_API_HOST,\n persistence: \"localStorage\",\n autocapture: false,\n // (Noah, 2026-07-14, REPL-29305): Disable performance capture \u2014 its PerformanceObserver\n // relays a non-cloneable PerformanceServerTiming across the iframe boundary via postMessage,\n // throwing a DataCloneError in the preview. Matches the bedrock-sdk relay.\n capture_performance: false,\n capture_pageview: false,\n session_recording: {\n recordCrossOriginIframes: true,\n // NOTE (Nick, 2026-02-02, REPL-23284): Disable canvas recording to prevent SecurityError on tainted canvases\n captureCanvas: { recordCanvas: false },\n },\n });\n })();\n\n return initPromise;\n}\n\nexport default function PostHogRelay() {\n // eslint-disable-next-line replo/no-use-effect -- External replay script and cross-frame listener lifecycle.\n useEffect(() => {\n const stopRelayingSnapshotRequests = startChildPostHogReplaySnapshotRelay({\n targetWindow: window,\n });\n void initPostHogRelay();\n return stopRelayingSnapshotRequests;\n }, []);\n\n return null;\n}\n"],
|
|
5
|
-
"mappings": ";AASA,SAAS,iBAAiB;AAE1B,SAAS,4CAA4C;AAErD,MAAM,kBAAkB;AACxB,MAAM,mBAAmB;
|
|
4
|
+
"sourcesContent": ["\"use client\";\n\n/**\n * PostHog Cross-Origin Iframe Relay\n *\n * Initializes PostHog inside the sandbox iframe as a \"relay\" - it captures DOM\n * mutations via rrweb and sends them to the parent window's PostHog instance\n * via postMessage, enabling session recordings to include iframe content.\n */\nimport { useEffect } from \"react\";\n\nimport { startChildPostHogReplaySnapshotRelay } from \"replo-utils/lib/posthogReplay\";\n\nconst POSTHOG_API_KEY = \"phc_dRETsj85vNkKrvQQszEFRBibH5kUF9l7rbjACuKPanZ\";\nconst POSTHOG_API_HOST = \"https://d99bbtllqsaif.cloudfront.net\";\n\ninterface PostHog {\n init: (apiKey: string, config: Record<string, unknown>) => void;\n sessionRecordingStarted: () => boolean;\n}\n\ndeclare global {\n interface Window {\n posthog?: PostHog;\n }\n}\n\nlet initPromise: Promise<void> | null = null;\n\nfunction loadPostHogScript() {\n return new Promise<void>((resolve) => {\n if (window.posthog) {\n resolve();\n return;\n }\n\n const script = document.createElement(\"script\");\n script.src = `${POSTHOG_API_HOST}/static/array.js`;\n script.async = true;\n script.addEventListener(\"load\", () => resolve());\n script.addEventListener(\"error\", () => {\n resolve();\n console.warn(\"[PostHog Relay] Failed to load PostHog script\");\n });\n document.head.append(script);\n });\n}\n\nfunction initPostHogRelay() {\n if (window.self === window.top) {\n return Promise.resolve();\n }\n\n if (initPromise) {\n return initPromise;\n }\n\n initPromise = (async () => {\n await loadPostHogScript();\n\n if (!window.posthog) {\n initPromise = null;\n console.warn(\"[PostHog Relay] PostHog not available after script load\");\n return;\n }\n\n window.posthog.init(POSTHOG_API_KEY, {\n api_host: POSTHOG_API_HOST,\n persistence: \"localStorage\",\n autocapture: false,\n // (Noah, 2026-07-14, REPL-29305): Disable performance capture \u2014 its PerformanceObserver\n // relays a non-cloneable PerformanceServerTiming across the iframe boundary via postMessage,\n // throwing a DataCloneError in the preview. Matches the bedrock-sdk relay.\n capture_performance: false,\n capture_pageview: false,\n session_recording: {\n recordCrossOriginIframes: true,\n // NOTE (Nick, 2026-02-02, REPL-23284): Disable canvas recording to prevent SecurityError on tainted canvases\n captureCanvas: { recordCanvas: false },\n },\n });\n })();\n\n return initPromise;\n}\n\nexport default function PostHogRelay() {\n // eslint-disable-next-line replo/no-use-effect -- External replay script and cross-frame listener lifecycle.\n useEffect(() => {\n const stopRelayingSnapshotRequests = startChildPostHogReplaySnapshotRelay({\n isRecordingStarted: () => {\n return window.posthog?.sessionRecordingStarted() ?? false;\n },\n targetWindow: window,\n });\n void initPostHogRelay();\n return stopRelayingSnapshotRequests;\n }, []);\n\n return null;\n}\n"],
|
|
5
|
+
"mappings": ";AASA,SAAS,iBAAiB;AAE1B,SAAS,4CAA4C;AAErD,MAAM,kBAAkB;AACxB,MAAM,mBAAmB;AAazB,IAAI,cAAoC;AAExC,SAAS,oBAAoB;AAC3B,SAAO,IAAI,QAAc,CAAC,YAAY;AACpC,QAAI,OAAO,SAAS;AAClB,cAAQ;AACR;AAAA,IACF;AAEA,UAAM,SAAS,SAAS,cAAc,QAAQ;AAC9C,WAAO,MAAM,GAAG,gBAAgB;AAChC,WAAO,QAAQ;AACf,WAAO,iBAAiB,QAAQ,MAAM,QAAQ,CAAC;AAC/C,WAAO,iBAAiB,SAAS,MAAM;AACrC,cAAQ;AACR,cAAQ,KAAK,+CAA+C;AAAA,IAC9D,CAAC;AACD,aAAS,KAAK,OAAO,MAAM;AAAA,EAC7B,CAAC;AACH;AAEA,SAAS,mBAAmB;AAC1B,MAAI,OAAO,SAAS,OAAO,KAAK;AAC9B,WAAO,QAAQ,QAAQ;AAAA,EACzB;AAEA,MAAI,aAAa;AACf,WAAO;AAAA,EACT;AAEA,iBAAe,YAAY;AACzB,UAAM,kBAAkB;AAExB,QAAI,CAAC,OAAO,SAAS;AACnB,oBAAc;AACd,cAAQ,KAAK,yDAAyD;AACtE;AAAA,IACF;AAEA,WAAO,QAAQ,KAAK,iBAAiB;AAAA,MACnC,UAAU;AAAA,MACV,aAAa;AAAA,MACb,aAAa;AAAA;AAAA;AAAA;AAAA,MAIb,qBAAqB;AAAA,MACrB,kBAAkB;AAAA,MAClB,mBAAmB;AAAA,QACjB,0BAA0B;AAAA;AAAA,QAE1B,eAAe,EAAE,cAAc,MAAM;AAAA,MACvC;AAAA,IACF,CAAC;AAAA,EACH,GAAG;AAEH,SAAO;AACT;AAEe,SAAR,eAAgC;AAErC,YAAU,MAAM;AACd,UAAM,+BAA+B,qCAAqC;AAAA,MACxE,oBAAoB,MAAM;AACxB,eAAO,OAAO,SAAS,wBAAwB,KAAK;AAAA,MACtD;AAAA,MACA,cAAc;AAAA,IAChB,CAAC;AACD,SAAK,iBAAiB;AACtB,WAAO;AAAA,EACT,GAAG,CAAC,CAAC;AAEL,SAAO;AACT;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,16 +1,3 @@
|
|
|
1
|
-
export interface SourceLocation {
|
|
2
|
-
filePath: string;
|
|
3
|
-
lineNumber: number;
|
|
4
|
-
columnNumber?: number;
|
|
5
|
-
componentName?: string;
|
|
6
|
-
}
|
|
7
|
-
export interface EventHandlers {
|
|
8
|
-
onClick?: string;
|
|
9
|
-
onMouseEnter?: string;
|
|
10
|
-
onMouseLeave?: string;
|
|
11
|
-
onFocus?: string;
|
|
12
|
-
onBlur?: string;
|
|
13
|
-
}
|
|
14
1
|
export interface ReactFiber {
|
|
15
2
|
_debugSource?: {
|
|
16
3
|
fileName: string;
|
|
@@ -37,7 +24,12 @@ export declare function findDebugSourceReact19(fiber: ReactFiber): {
|
|
|
37
24
|
source: ReactFiber["_debugSource"];
|
|
38
25
|
componentName?: string;
|
|
39
26
|
} | null;
|
|
40
|
-
export declare function getSourceLocation(element: HTMLElement):
|
|
27
|
+
export declare function getSourceLocation(element: HTMLElement): {
|
|
28
|
+
filePath: string;
|
|
29
|
+
lineNumber: number;
|
|
30
|
+
columnNumber: number | undefined;
|
|
31
|
+
componentName: string | undefined;
|
|
32
|
+
} | undefined;
|
|
41
33
|
export declare function getHostSourceIdentity(element: HTMLElement): {
|
|
42
34
|
filePath: string;
|
|
43
35
|
lineNumber: number;
|
|
@@ -55,15 +47,3 @@ export declare function getFiberChain(element: HTMLElement): {
|
|
|
55
47
|
componentName: string | undefined;
|
|
56
48
|
props: Record<string, unknown> | undefined;
|
|
57
49
|
}[];
|
|
58
|
-
/**
|
|
59
|
-
* Extract event handlers from React fiber or DOM element
|
|
60
|
-
*
|
|
61
|
-
* @author Kevin O'Connell 2026-04-17
|
|
62
|
-
*/
|
|
63
|
-
export declare function extractEventHandlers(element: HTMLElement): EventHandlers;
|
|
64
|
-
/**
|
|
65
|
-
* Convert a function to a readable string representation
|
|
66
|
-
*
|
|
67
|
-
* @author Kevin O'Connell 2026-04-17
|
|
68
|
-
*/
|
|
69
|
-
export declare function stringifyHandler(fn: unknown): string;
|
|
@@ -294,68 +294,13 @@ function getFiberChain(element) {
|
|
|
294
294
|
}
|
|
295
295
|
return fiberChain;
|
|
296
296
|
}
|
|
297
|
-
function extractEventHandlers(element) {
|
|
298
|
-
const handlers = {};
|
|
299
|
-
const fiber = getFiberFromElement(element);
|
|
300
|
-
if (fiber) {
|
|
301
|
-
const props = fiber.memoizedProps ?? fiber.pendingProps;
|
|
302
|
-
if (props) {
|
|
303
|
-
if (typeof props.onClick === "function") {
|
|
304
|
-
handlers.onClick = stringifyHandler(props.onClick);
|
|
305
|
-
}
|
|
306
|
-
if (typeof props.onMouseEnter === "function") {
|
|
307
|
-
handlers.onMouseEnter = stringifyHandler(props.onMouseEnter);
|
|
308
|
-
}
|
|
309
|
-
if (typeof props.onMouseLeave === "function") {
|
|
310
|
-
handlers.onMouseLeave = stringifyHandler(props.onMouseLeave);
|
|
311
|
-
}
|
|
312
|
-
if (typeof props.onFocus === "function") {
|
|
313
|
-
handlers.onFocus = stringifyHandler(props.onFocus);
|
|
314
|
-
}
|
|
315
|
-
if (typeof props.onBlur === "function") {
|
|
316
|
-
handlers.onBlur = stringifyHandler(props.onBlur);
|
|
317
|
-
}
|
|
318
|
-
}
|
|
319
|
-
}
|
|
320
|
-
if (!handlers.onClick) {
|
|
321
|
-
const onClickMatch = element.outerHTML.match(
|
|
322
|
-
/onClick={([^}]+(?:{[^}]*}[^}]*)*)}/
|
|
323
|
-
);
|
|
324
|
-
if (onClickMatch?.[1]) {
|
|
325
|
-
handlers.onClick = onClickMatch[1].trim();
|
|
326
|
-
}
|
|
327
|
-
}
|
|
328
|
-
return handlers;
|
|
329
|
-
}
|
|
330
|
-
function stringifyHandler(fn) {
|
|
331
|
-
if (typeof fn !== "function") {
|
|
332
|
-
return "";
|
|
333
|
-
}
|
|
334
|
-
const source = fn.toString();
|
|
335
|
-
if (source.startsWith("(") || source.startsWith("function")) {
|
|
336
|
-
const arrowMatch = source.match(/^\(\)\s*=>\s*([\S\s]+)$/);
|
|
337
|
-
if (arrowMatch) {
|
|
338
|
-
return arrowMatch[1].trim();
|
|
339
|
-
}
|
|
340
|
-
const arrowWithParamsMatch = source.match(/^\([^)]*\)\s*=>\s*([\S\s]+)$/);
|
|
341
|
-
if (arrowWithParamsMatch) {
|
|
342
|
-
return arrowWithParamsMatch[1].trim();
|
|
343
|
-
}
|
|
344
|
-
}
|
|
345
|
-
if (source.length > 200) {
|
|
346
|
-
return `${source.slice(0, 200)}...`;
|
|
347
|
-
}
|
|
348
|
-
return source;
|
|
349
|
-
}
|
|
350
297
|
export {
|
|
351
|
-
extractEventHandlers,
|
|
352
298
|
findDebugSource,
|
|
353
299
|
findDebugSourceReact19,
|
|
354
300
|
getComponentName,
|
|
355
301
|
getFiberChain,
|
|
356
302
|
getFiberFromElement,
|
|
357
303
|
getHostSourceIdentity,
|
|
358
|
-
getSourceLocation
|
|
359
|
-
stringifyHandler
|
|
304
|
+
getSourceLocation
|
|
360
305
|
};
|
|
361
306
|
//# sourceMappingURL=fiber.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../editor/select-mode/fiber.ts"],
|
|
4
|
-
"sourcesContent": ["// =============================================================================\n// React Fiber / Source Location Utilities\n// =============================================================================\n\nimport { z } from \"zod\";\n\nexport interface SourceLocation {\n filePath: string;\n lineNumber: number;\n columnNumber?: number;\n componentName?: string;\n}\n\nexport interface EventHandlers {\n onClick?: string;\n onMouseEnter?: string;\n onMouseLeave?: string;\n onFocus?: string;\n onBlur?: string;\n}\n\nexport interface ReactFiber {\n _debugSource?: {\n fileName: string;\n lineNumber: number;\n columnNumber?: number;\n };\n _debugStack?: unknown;\n _debugOwner?: ReactFiber;\n type?:\n | { name?: string; displayName?: string }\n | string\n | ((...args: unknown[]) => unknown)\n | null;\n return?: ReactFiber | null;\n memoizedProps?: Record<string, unknown>;\n pendingProps?: Record<string, unknown>;\n}\n\nconst MAX_FIBER_CHAIN_DEPTH = 80;\nconst MAX_SERIALIZED_PROP_COUNT = 24;\nconst MAX_SERIALIZED_STRING_LENGTH = 500;\n\ninterface ReactFiberWithHandlers extends ReactFiber {\n memoizedProps?: Record<string, unknown>;\n pendingProps?: Record<string, unknown>;\n}\n\n// Frames produced by React's own JSX runtime \u2014 these come first in\n// `_debugStack.stack` because the `Error` is constructed inside `jsxDEV`. We\n// want the frame *above* them, which is the actual JSX call site.\n//\n// Turbopack rewrites `node_modules/next/dist/compiled/react-server-dom-*` and\n// friends into mangled chunk paths like\n// `_next/static/chunks/<hash>_next_dist_compiled_react-server-dom-turbopack_<hash>._.js`,\n// so we match both the human-readable module paths and the chunk-name forms.\n// Without this, `_debugStack`'s top frame inside React's RSC runtime gets\n// surfaced as the \"host\" source location for every text node on the page \u2014\n// which then symbolicates back to bundled React, not user code.\nconst REACT_INTERNAL_FRAME_PATTERNS = [\n /react.*jsx-dev-runtime/,\n /react.*jsx-runtime/,\n /react-dom\\//,\n /react\\/cjs\\/react\\./,\n /react-server-dom/,\n /react_server_dom/,\n /next[/_.]dist[/_.]compiled/,\n /\\/node_modules\\/(next|react|react-dom)\\//,\n];\n\nfunction isReactInternalFrame(fileName: string): boolean {\n return REACT_INTERNAL_FRAME_PATTERNS.some((pattern) => {\n return pattern.test(fileName);\n });\n}\n\n// React constructs the `_debugStack` Error inside its JSX runtime (`jsxDEV`,\n// `jsx`, `jsxs`), so those frames sit *above* the real JSX call site we want.\n// The file-based check above skips them when their path is recognizable, but\n// Turbopack mangles the client JSX-runtime chunk to an opaque name like\n// `node_modules__pnpm_<hash>._.js` (no \"react\"/\"jsx-dev-runtime\" substring),\n// so the top `jsxDEV` frame slips through and gets surfaced as the element's\n// source \u2014 which then symbolicates back to bundled React, not user code.\n// Matching by function name is stable across Turbopack's chunk hashing.\n// NOTE (Noah, 2026-07-27): Only bites client components; server-component\n// frames carry a recognizable `react-server-dom-*` path.\nconst REACT_INTERNAL_METHOD_PATTERNS = [\n /(?:^|\\.)jsxDEV(?:Impl)?$/,\n /(?:^|\\.)jsxs?$/,\n /(?:^|\\.)react_stack_bottom_frame$/,\n /(?:^|\\.)fakeJSXCallSite$/,\n];\n\nfunction isReactInternalMethod(methodName: string | null): boolean {\n if (!methodName) {\n return false;\n }\n return REACT_INTERNAL_METHOD_PATTERNS.some((pattern) => {\n return pattern.test(methodName);\n });\n}\n\nfunction parseDebugStackSource(\n debugStack: unknown,\n): ReactFiber[\"_debugSource\"] | null {\n let stackText: string | null = null;\n\n if (typeof debugStack === \"string\") {\n stackText = debugStack;\n } else if (\n typeof debugStack === \"object\" &&\n debugStack &&\n \"stack\" in debugStack\n ) {\n // Legacy cast - may or may not be necessary\n // eslint-disable-next-line replo/no-as-cast\n const stack = (debugStack as { stack?: unknown }).stack;\n if (typeof stack === \"string\") {\n stackText = stack;\n }\n }\n\n if (!stackText) {\n return null;\n }\n\n for (const rawLine of stackText.split(\"\\n\")) {\n const line = rawLine.trim();\n if (!line) {\n continue;\n }\n\n // Prefer the framed form `at <method> (<file>:<line>:<col>)` so we can\n // read the function name and skip React's JSX-runtime frames even when\n // Turbopack has mangled their chunk file name beyond recognition.\n const framedMatch = line.match(/^at\\s+(.+?)\\s+\\((.*):(\\d+):(\\d+)\\)$/);\n const stackFrameMatch =\n framedMatch ??\n line.match(/^at\\s+(?:.*\\()?(.*):(\\d+):(\\d+)\\)?$/) ??\n line.match(/^(.*):(\\d+):(\\d+)$/);\n\n if (!stackFrameMatch) {\n continue;\n }\n\n const methodName = framedMatch ? framedMatch[1]!.trim() : null;\n const fileOffset = framedMatch ? 2 : 1;\n const fileName = stackFrameMatch[fileOffset]?.trim();\n const lineNumber = Number.parseInt(\n stackFrameMatch[fileOffset + 1] ?? \"\",\n 10,\n );\n const columnNumber = Number.parseInt(\n stackFrameMatch[fileOffset + 2] ?? \"\",\n 10,\n );\n\n if (\n !fileName ||\n !Number.isFinite(lineNumber) ||\n !Number.isFinite(columnNumber)\n ) {\n continue;\n }\n\n if (isReactInternalFrame(fileName) || isReactInternalMethod(methodName)) {\n continue;\n }\n\n return {\n fileName,\n lineNumber,\n columnNumber,\n };\n }\n\n return null;\n}\n\nexport function getFiberFromElement(element: HTMLElement): ReactFiber | null {\n if (!element || typeof element !== \"object\") {\n return null;\n }\n\n const symbolKeys = Object.getOwnPropertySymbols(element);\n const fiberSymbolKey = symbolKeys.find((symbolKey) => {\n return symbolKey.toString().includes(\"reactFiber\");\n });\n if (fiberSymbolKey) {\n return (\n // Legacy cast - may or may not be necessary\n // eslint-disable-next-line replo/no-as-cast\n (element as unknown as Record<symbol, ReactFiber>)[fiberSymbolKey] ?? null\n );\n }\n\n const keys = Object.keys(element);\n const fiberKey = keys.find((key) => key.startsWith(\"__reactFiber$\"));\n if (fiberKey) {\n // Legacy cast - may or may not be necessary\n // eslint-disable-next-line replo/no-as-cast\n return (element as unknown as Record<string, ReactFiber>)[fiberKey] ?? null;\n }\n const instanceKey = keys.find((key) => {\n return key.startsWith(\"__reactInternalInstance$\");\n });\n if (instanceKey) {\n return (\n // Legacy cast - may or may not be necessary\n // eslint-disable-next-line replo/no-as-cast\n (element as unknown as Record<string, ReactFiber>)[instanceKey] ?? null\n );\n }\n\n const possibleFiberKey = keys.find((key) => {\n if (!key.startsWith(\"__react\")) {\n return false;\n }\n // Legacy cast - may or may not be necessary\n // eslint-disable-next-line replo/no-as-cast\n const value = (element as unknown as Record<string, unknown>)[key];\n return value && typeof value === \"object\" && \"_debugSource\" in value;\n });\n\n if (possibleFiberKey) {\n return (\n // Legacy cast - may or may not be necessary\n // eslint-disable-next-line replo/no-as-cast\n (element as unknown as Record<string, ReactFiber>)[possibleFiberKey] ??\n null\n );\n }\n\n return null;\n}\n\nexport function getComponentName(\n fiber: ReactFiber | null | undefined,\n): string | undefined {\n if (!fiber?.type) {\n return undefined;\n }\n\n if (typeof fiber.type === \"string\") {\n return undefined;\n }\n\n if (typeof fiber.type === \"function\") {\n return fiber.type.name || undefined;\n }\n\n if (typeof fiber.type === \"object\") {\n return fiber.type.displayName ?? fiber.type.name ?? undefined;\n }\n\n return undefined;\n}\n\nexport function findDebugSource(\n fiber: ReactFiber,\n maxDepth = 50,\n): { source: ReactFiber[\"_debugSource\"]; componentName?: string } | null {\n let current: ReactFiber | null | undefined = fiber;\n let depth = 0;\n\n while (current && depth < maxDepth) {\n if (current._debugSource) {\n return {\n source: current._debugSource,\n componentName: getComponentName(current),\n };\n }\n\n if (current._debugOwner?._debugSource) {\n return {\n source: current._debugOwner._debugSource,\n componentName: getComponentName(current._debugOwner),\n };\n }\n\n current = current.return;\n depth++;\n }\n\n return null;\n}\n\n// React 19 removed `fiber._debugSource`. The only per-element source pointer\n// left is `fiber._debugStack`, an `Error` constructed inside `jsxDEV` at the\n// JSX call site. We pull the topmost non-React frame out of that stack; it\n// references a compiled SSR/client chunk (e.g. `.next-dev/.../ssr/*.js`).\n// `symbolicateSelectedElement` later resolves those compiled frames to\n// original `.tsx` locations via Next.js's `/__nextjs_original-stack-frames`\n// dev-server endpoint.\nexport function findDebugSourceReact19(\n fiber: ReactFiber,\n): { source: ReactFiber[\"_debugSource\"]; componentName?: string } | null {\n let current: ReactFiber | null | undefined = fiber;\n let depth = 0;\n const maxDepth = 50;\n\n while (current && depth < maxDepth) {\n const debugStackSource =\n parseDebugStackSource(current._debugStack) ??\n parseDebugStackSource(current._debugOwner?._debugStack);\n if (debugStackSource) {\n return {\n source: debugStackSource,\n componentName: getComponentName(current),\n };\n }\n\n current = current.return;\n depth++;\n }\n\n return null;\n}\n\nexport function getSourceLocation(\n element: HTMLElement,\n): SourceLocation | undefined {\n let currentElement: HTMLElement | null = element;\n\n while (currentElement) {\n const fiber = getFiberFromElement(currentElement);\n if (fiber) {\n const debugInfo = findDebugSource(fiber) ?? findDebugSourceReact19(fiber);\n if (debugInfo?.source) {\n return {\n filePath: debugInfo.source.fileName,\n lineNumber: debugInfo.source.lineNumber,\n columnNumber: debugInfo.source.columnNumber,\n componentName: debugInfo.componentName ?? undefined,\n };\n }\n }\n\n currentElement = currentElement.parentElement;\n }\n\n return undefined;\n}\n\nfunction getDebugSource(\n fiber: ReactFiber,\n): ReactFiber[\"_debugSource\"] | undefined {\n const debugInfo = findDebugSource(fiber) ?? findDebugSourceReact19(fiber);\n return debugInfo?.source;\n}\n\nfunction getTagName(fiber: ReactFiber): string | undefined {\n return z.string().safeParse(fiber.type).data?.toLowerCase();\n}\n\nexport function getHostSourceIdentity(element: HTMLElement) {\n const fiber = getFiberFromElement(element);\n if (!fiber) {\n return null;\n }\n const source = getDebugSource(fiber);\n if (!source) {\n return null;\n }\n return {\n filePath: source.fileName,\n lineNumber: source.lineNumber,\n columnNumber: source.columnNumber,\n tagName: element.tagName.toLowerCase(),\n };\n}\n\nfunction getSerializablePropValue(value: unknown): unknown {\n if (\n value === null ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n return value;\n }\n\n if (typeof value === \"string\") {\n return value.length > MAX_SERIALIZED_STRING_LENGTH\n ? `${value.slice(0, MAX_SERIALIZED_STRING_LENGTH)}...`\n : value;\n }\n\n if (Array.isArray(value)) {\n return value.slice(0, 20).map(getSerializablePropValue);\n }\n\n if (typeof value === \"object\") {\n return \"[object]\";\n }\n\n return undefined;\n}\n\nfunction getSerializableProps(\n props: Record<string, unknown> | undefined,\n): Record<string, unknown> | undefined {\n if (!props) {\n return undefined;\n }\n\n const serializedProps: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(props).slice(\n 0,\n MAX_SERIALIZED_PROP_COUNT,\n )) {\n if (\n key === \"children\" ||\n key === \"ref\" ||\n key.startsWith(\"on\") ||\n typeof value === \"function\" ||\n typeof value === \"symbol\"\n ) {\n continue;\n }\n\n const serializableValue = getSerializablePropValue(value);\n if (serializableValue !== undefined) {\n serializedProps[key] = serializableValue;\n }\n }\n\n return Object.keys(serializedProps).length > 0 ? serializedProps : undefined;\n}\n\nexport function getFiberChain(element: HTMLElement) {\n const rootFiber = getFiberFromElement(element);\n const fiberChain = [];\n const seenKeys = new Set<string>();\n let currentFiber: ReactFiber | null | undefined = rootFiber;\n let depth = 0;\n\n while (currentFiber && depth < MAX_FIBER_CHAIN_DEPTH) {\n const source = getDebugSource(currentFiber);\n if (source) {\n const tagName = getTagName(currentFiber);\n const componentName = getComponentName(currentFiber);\n const key = [\n source.fileName,\n source.lineNumber,\n source.columnNumber ?? \"\",\n tagName ?? \"\",\n componentName ?? \"\",\n ].join(\":\");\n\n if (!seenKeys.has(key)) {\n seenKeys.add(key);\n fiberChain.push({\n sourceLocation: {\n filePath: source.fileName,\n lineNumber: source.lineNumber,\n columnNumber: source.columnNumber,\n componentName,\n },\n tagName,\n componentName,\n props: getSerializableProps(\n currentFiber.memoizedProps ?? currentFiber.pendingProps,\n ),\n });\n }\n }\n\n currentFiber = currentFiber.return;\n depth += 1;\n }\n\n return fiberChain;\n}\n\n/**\n * Extract event handlers from React fiber or DOM element\n *\n * @author Kevin O'Connell 2026-04-17\n */\nexport function extractEventHandlers(element: HTMLElement): EventHandlers {\n const handlers: EventHandlers = {};\n\n // Try to get handlers from React fiber\n // Legacy cast - may or may not be necessary\n // eslint-disable-next-line replo/no-as-cast\n const fiber = getFiberFromElement(element) as ReactFiberWithHandlers | null;\n if (fiber) {\n const props = fiber.memoizedProps ?? fiber.pendingProps;\n if (props) {\n // Extract onClick handler\n if (typeof props.onClick === \"function\") {\n handlers.onClick = stringifyHandler(props.onClick);\n }\n\n // Extract other handlers\n if (typeof props.onMouseEnter === \"function\") {\n handlers.onMouseEnter = stringifyHandler(props.onMouseEnter);\n }\n if (typeof props.onMouseLeave === \"function\") {\n handlers.onMouseLeave = stringifyHandler(props.onMouseLeave);\n }\n if (typeof props.onFocus === \"function\") {\n handlers.onFocus = stringifyHandler(props.onFocus);\n }\n if (typeof props.onBlur === \"function\") {\n handlers.onBlur = stringifyHandler(props.onBlur);\n }\n }\n }\n\n // Fallback: try to parse from outerHTML (less reliable)\n if (!handlers.onClick) {\n const onClickMatch = element.outerHTML.match(\n /onClick={([^}]+(?:{[^}]*}[^}]*)*)}/,\n );\n if (onClickMatch?.[1]) {\n handlers.onClick = onClickMatch[1].trim();\n }\n }\n\n return handlers;\n}\n\n/**\n * Convert a function to a readable string representation\n *\n * @author Kevin O'Connell 2026-04-17\n */\nexport function stringifyHandler(fn: unknown): string {\n if (typeof fn !== \"function\") {\n return \"\";\n }\n\n // Get function source\n const source = fn.toString();\n\n // Clean up arrow functions\n if (source.startsWith(\"(\") || source.startsWith(\"function\")) {\n // For arrow functions like () => setCount(c => c + 1)\n const arrowMatch = source.match(/^\\(\\)\\s*=>\\s*([\\S\\s]+)$/);\n if (arrowMatch) {\n return arrowMatch[1]!.trim();\n }\n\n // For arrow functions with params like (e) => handleClick(e)\n const arrowWithParamsMatch = source.match(/^\\([^)]*\\)\\s*=>\\s*([\\S\\s]+)$/);\n if (arrowWithParamsMatch) {\n return arrowWithParamsMatch[1]!.trim();\n }\n }\n\n // Return truncated source for regular functions\n if (source.length > 200) {\n return `${source.slice(0, 200)}...`;\n }\n\n return source;\n}\n"],
|
|
5
|
-
"mappings": "AAIA,SAAS,SAAS;
|
|
4
|
+
"sourcesContent": ["// =============================================================================\n// React Fiber / Source Location Utilities\n// =============================================================================\n\nimport { z } from \"zod\";\n\nexport interface ReactFiber {\n _debugSource?: {\n fileName: string;\n lineNumber: number;\n columnNumber?: number;\n };\n _debugStack?: unknown;\n _debugOwner?: ReactFiber;\n type?:\n | { name?: string; displayName?: string }\n | string\n | ((...args: unknown[]) => unknown)\n | null;\n return?: ReactFiber | null;\n memoizedProps?: Record<string, unknown>;\n pendingProps?: Record<string, unknown>;\n}\n\nconst MAX_FIBER_CHAIN_DEPTH = 80;\nconst MAX_SERIALIZED_PROP_COUNT = 24;\nconst MAX_SERIALIZED_STRING_LENGTH = 500;\n\n// Frames produced by React's own JSX runtime \u2014 these come first in\n// `_debugStack.stack` because the `Error` is constructed inside `jsxDEV`. We\n// want the frame *above* them, which is the actual JSX call site.\n//\n// Turbopack rewrites `node_modules/next/dist/compiled/react-server-dom-*` and\n// friends into mangled chunk paths like\n// `_next/static/chunks/<hash>_next_dist_compiled_react-server-dom-turbopack_<hash>._.js`,\n// so we match both the human-readable module paths and the chunk-name forms.\n// Without this, `_debugStack`'s top frame inside React's RSC runtime gets\n// surfaced as the \"host\" source location for every text node on the page \u2014\n// which then symbolicates back to bundled React, not user code.\nconst REACT_INTERNAL_FRAME_PATTERNS = [\n /react.*jsx-dev-runtime/,\n /react.*jsx-runtime/,\n /react-dom\\//,\n /react\\/cjs\\/react\\./,\n /react-server-dom/,\n /react_server_dom/,\n /next[/_.]dist[/_.]compiled/,\n /\\/node_modules\\/(next|react|react-dom)\\//,\n];\n\nfunction isReactInternalFrame(fileName: string): boolean {\n return REACT_INTERNAL_FRAME_PATTERNS.some((pattern) => {\n return pattern.test(fileName);\n });\n}\n\n// React constructs the `_debugStack` Error inside its JSX runtime (`jsxDEV`,\n// `jsx`, `jsxs`), so those frames sit *above* the real JSX call site we want.\n// The file-based check above skips them when their path is recognizable, but\n// Turbopack mangles the client JSX-runtime chunk to an opaque name like\n// `node_modules__pnpm_<hash>._.js` (no \"react\"/\"jsx-dev-runtime\" substring),\n// so the top `jsxDEV` frame slips through and gets surfaced as the element's\n// source \u2014 which then symbolicates back to bundled React, not user code.\n// Matching by function name is stable across Turbopack's chunk hashing.\n// NOTE (Noah, 2026-07-27): Only bites client components; server-component\n// frames carry a recognizable `react-server-dom-*` path.\nconst REACT_INTERNAL_METHOD_PATTERNS = [\n /(?:^|\\.)jsxDEV(?:Impl)?$/,\n /(?:^|\\.)jsxs?$/,\n /(?:^|\\.)react_stack_bottom_frame$/,\n /(?:^|\\.)fakeJSXCallSite$/,\n];\n\nfunction isReactInternalMethod(methodName: string | null): boolean {\n if (!methodName) {\n return false;\n }\n return REACT_INTERNAL_METHOD_PATTERNS.some((pattern) => {\n return pattern.test(methodName);\n });\n}\n\nfunction parseDebugStackSource(\n debugStack: unknown,\n): ReactFiber[\"_debugSource\"] | null {\n let stackText: string | null = null;\n\n if (typeof debugStack === \"string\") {\n stackText = debugStack;\n } else if (\n typeof debugStack === \"object\" &&\n debugStack &&\n \"stack\" in debugStack\n ) {\n // Legacy cast - may or may not be necessary\n // eslint-disable-next-line replo/no-as-cast\n const stack = (debugStack as { stack?: unknown }).stack;\n if (typeof stack === \"string\") {\n stackText = stack;\n }\n }\n\n if (!stackText) {\n return null;\n }\n\n for (const rawLine of stackText.split(\"\\n\")) {\n const line = rawLine.trim();\n if (!line) {\n continue;\n }\n\n // Prefer the framed form `at <method> (<file>:<line>:<col>)` so we can\n // read the function name and skip React's JSX-runtime frames even when\n // Turbopack has mangled their chunk file name beyond recognition.\n const framedMatch = line.match(/^at\\s+(.+?)\\s+\\((.*):(\\d+):(\\d+)\\)$/);\n const stackFrameMatch =\n framedMatch ??\n line.match(/^at\\s+(?:.*\\()?(.*):(\\d+):(\\d+)\\)?$/) ??\n line.match(/^(.*):(\\d+):(\\d+)$/);\n\n if (!stackFrameMatch) {\n continue;\n }\n\n const methodName = framedMatch ? framedMatch[1]!.trim() : null;\n const fileOffset = framedMatch ? 2 : 1;\n const fileName = stackFrameMatch[fileOffset]?.trim();\n const lineNumber = Number.parseInt(\n stackFrameMatch[fileOffset + 1] ?? \"\",\n 10,\n );\n const columnNumber = Number.parseInt(\n stackFrameMatch[fileOffset + 2] ?? \"\",\n 10,\n );\n\n if (\n !fileName ||\n !Number.isFinite(lineNumber) ||\n !Number.isFinite(columnNumber)\n ) {\n continue;\n }\n\n if (isReactInternalFrame(fileName) || isReactInternalMethod(methodName)) {\n continue;\n }\n\n return {\n fileName,\n lineNumber,\n columnNumber,\n };\n }\n\n return null;\n}\n\nexport function getFiberFromElement(element: HTMLElement): ReactFiber | null {\n if (!element || typeof element !== \"object\") {\n return null;\n }\n\n const symbolKeys = Object.getOwnPropertySymbols(element);\n const fiberSymbolKey = symbolKeys.find((symbolKey) => {\n return symbolKey.toString().includes(\"reactFiber\");\n });\n if (fiberSymbolKey) {\n return (\n // Legacy cast - may or may not be necessary\n // eslint-disable-next-line replo/no-as-cast\n (element as unknown as Record<symbol, ReactFiber>)[fiberSymbolKey] ?? null\n );\n }\n\n const keys = Object.keys(element);\n const fiberKey = keys.find((key) => key.startsWith(\"__reactFiber$\"));\n if (fiberKey) {\n // Legacy cast - may or may not be necessary\n // eslint-disable-next-line replo/no-as-cast\n return (element as unknown as Record<string, ReactFiber>)[fiberKey] ?? null;\n }\n const instanceKey = keys.find((key) => {\n return key.startsWith(\"__reactInternalInstance$\");\n });\n if (instanceKey) {\n return (\n // Legacy cast - may or may not be necessary\n // eslint-disable-next-line replo/no-as-cast\n (element as unknown as Record<string, ReactFiber>)[instanceKey] ?? null\n );\n }\n\n const possibleFiberKey = keys.find((key) => {\n if (!key.startsWith(\"__react\")) {\n return false;\n }\n // Legacy cast - may or may not be necessary\n // eslint-disable-next-line replo/no-as-cast\n const value = (element as unknown as Record<string, unknown>)[key];\n return value && typeof value === \"object\" && \"_debugSource\" in value;\n });\n\n if (possibleFiberKey) {\n return (\n // Legacy cast - may or may not be necessary\n // eslint-disable-next-line replo/no-as-cast\n (element as unknown as Record<string, ReactFiber>)[possibleFiberKey] ??\n null\n );\n }\n\n return null;\n}\n\nexport function getComponentName(\n fiber: ReactFiber | null | undefined,\n): string | undefined {\n if (!fiber?.type) {\n return undefined;\n }\n\n if (typeof fiber.type === \"string\") {\n return undefined;\n }\n\n if (typeof fiber.type === \"function\") {\n return fiber.type.name || undefined;\n }\n\n if (typeof fiber.type === \"object\") {\n return fiber.type.displayName ?? fiber.type.name ?? undefined;\n }\n\n return undefined;\n}\n\nexport function findDebugSource(\n fiber: ReactFiber,\n maxDepth = 50,\n): { source: ReactFiber[\"_debugSource\"]; componentName?: string } | null {\n let current: ReactFiber | null | undefined = fiber;\n let depth = 0;\n\n while (current && depth < maxDepth) {\n if (current._debugSource) {\n return {\n source: current._debugSource,\n componentName: getComponentName(current),\n };\n }\n\n if (current._debugOwner?._debugSource) {\n return {\n source: current._debugOwner._debugSource,\n componentName: getComponentName(current._debugOwner),\n };\n }\n\n current = current.return;\n depth++;\n }\n\n return null;\n}\n\n// React 19 removed `fiber._debugSource`. The only per-element source pointer\n// left is `fiber._debugStack`, an `Error` constructed inside `jsxDEV` at the\n// JSX call site. We pull the topmost non-React frame out of that stack; it\n// references a compiled SSR/client chunk (e.g. `.next-dev/.../ssr/*.js`).\n// `symbolicateSelectedElement` later resolves those compiled frames to\n// original `.tsx` locations via Next.js's `/__nextjs_original-stack-frames`\n// dev-server endpoint.\nexport function findDebugSourceReact19(\n fiber: ReactFiber,\n): { source: ReactFiber[\"_debugSource\"]; componentName?: string } | null {\n let current: ReactFiber | null | undefined = fiber;\n let depth = 0;\n const maxDepth = 50;\n\n while (current && depth < maxDepth) {\n const debugStackSource =\n parseDebugStackSource(current._debugStack) ??\n parseDebugStackSource(current._debugOwner?._debugStack);\n if (debugStackSource) {\n return {\n source: debugStackSource,\n componentName: getComponentName(current),\n };\n }\n\n current = current.return;\n depth++;\n }\n\n return null;\n}\n\nexport function getSourceLocation(element: HTMLElement) {\n let currentElement: HTMLElement | null = element;\n\n while (currentElement) {\n const fiber = getFiberFromElement(currentElement);\n if (fiber) {\n const debugInfo = findDebugSource(fiber) ?? findDebugSourceReact19(fiber);\n if (debugInfo?.source) {\n return {\n filePath: debugInfo.source.fileName,\n lineNumber: debugInfo.source.lineNumber,\n columnNumber: debugInfo.source.columnNumber,\n componentName: debugInfo.componentName ?? undefined,\n };\n }\n }\n\n currentElement = currentElement.parentElement;\n }\n\n return undefined;\n}\n\nfunction getDebugSource(\n fiber: ReactFiber,\n): ReactFiber[\"_debugSource\"] | undefined {\n const debugInfo = findDebugSource(fiber) ?? findDebugSourceReact19(fiber);\n return debugInfo?.source;\n}\n\nfunction getTagName(fiber: ReactFiber): string | undefined {\n return z.string().safeParse(fiber.type).data?.toLowerCase();\n}\n\nexport function getHostSourceIdentity(element: HTMLElement) {\n const fiber = getFiberFromElement(element);\n if (!fiber) {\n return null;\n }\n const source = getDebugSource(fiber);\n if (!source) {\n return null;\n }\n return {\n filePath: source.fileName,\n lineNumber: source.lineNumber,\n columnNumber: source.columnNumber,\n tagName: element.tagName.toLowerCase(),\n };\n}\n\nfunction getSerializablePropValue(value: unknown): unknown {\n if (\n value === null ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n return value;\n }\n\n if (typeof value === \"string\") {\n return value.length > MAX_SERIALIZED_STRING_LENGTH\n ? `${value.slice(0, MAX_SERIALIZED_STRING_LENGTH)}...`\n : value;\n }\n\n if (Array.isArray(value)) {\n return value.slice(0, 20).map(getSerializablePropValue);\n }\n\n if (typeof value === \"object\") {\n return \"[object]\";\n }\n\n return undefined;\n}\n\nfunction getSerializableProps(\n props: Record<string, unknown> | undefined,\n): Record<string, unknown> | undefined {\n if (!props) {\n return undefined;\n }\n\n const serializedProps: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(props).slice(\n 0,\n MAX_SERIALIZED_PROP_COUNT,\n )) {\n if (\n key === \"children\" ||\n key === \"ref\" ||\n key.startsWith(\"on\") ||\n typeof value === \"function\" ||\n typeof value === \"symbol\"\n ) {\n continue;\n }\n\n const serializableValue = getSerializablePropValue(value);\n if (serializableValue !== undefined) {\n serializedProps[key] = serializableValue;\n }\n }\n\n return Object.keys(serializedProps).length > 0 ? serializedProps : undefined;\n}\n\nexport function getFiberChain(element: HTMLElement) {\n const rootFiber = getFiberFromElement(element);\n const fiberChain = [];\n const seenKeys = new Set<string>();\n let currentFiber: ReactFiber | null | undefined = rootFiber;\n let depth = 0;\n\n while (currentFiber && depth < MAX_FIBER_CHAIN_DEPTH) {\n const source = getDebugSource(currentFiber);\n if (source) {\n const tagName = getTagName(currentFiber);\n const componentName = getComponentName(currentFiber);\n const key = [\n source.fileName,\n source.lineNumber,\n source.columnNumber ?? \"\",\n tagName ?? \"\",\n componentName ?? \"\",\n ].join(\":\");\n\n if (!seenKeys.has(key)) {\n seenKeys.add(key);\n fiberChain.push({\n sourceLocation: {\n filePath: source.fileName,\n lineNumber: source.lineNumber,\n columnNumber: source.columnNumber,\n componentName,\n },\n tagName,\n componentName,\n props: getSerializableProps(\n currentFiber.memoizedProps ?? currentFiber.pendingProps,\n ),\n });\n }\n }\n\n currentFiber = currentFiber.return;\n depth += 1;\n }\n\n return fiberChain;\n}\n"],
|
|
5
|
+
"mappings": "AAIA,SAAS,SAAS;AAoBlB,MAAM,wBAAwB;AAC9B,MAAM,4BAA4B;AAClC,MAAM,+BAA+B;AAarC,MAAM,gCAAgC;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,SAAS,qBAAqB,UAA2B;AACvD,SAAO,8BAA8B,KAAK,CAAC,YAAY;AACrD,WAAO,QAAQ,KAAK,QAAQ;AAAA,EAC9B,CAAC;AACH;AAYA,MAAM,iCAAiC;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,SAAS,sBAAsB,YAAoC;AACjE,MAAI,CAAC,YAAY;AACf,WAAO;AAAA,EACT;AACA,SAAO,+BAA+B,KAAK,CAAC,YAAY;AACtD,WAAO,QAAQ,KAAK,UAAU;AAAA,EAChC,CAAC;AACH;AAEA,SAAS,sBACP,YACmC;AACnC,MAAI,YAA2B;AAE/B,MAAI,OAAO,eAAe,UAAU;AAClC,gBAAY;AAAA,EACd,WACE,OAAO,eAAe,YACtB,cACA,WAAW,YACX;AAGA,UAAM,QAAS,WAAmC;AAClD,QAAI,OAAO,UAAU,UAAU;AAC7B,kBAAY;AAAA,IACd;AAAA,EACF;AAEA,MAAI,CAAC,WAAW;AACd,WAAO;AA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pD,UAAM,SAAS,eAAe,YAAY;AAC1C,QAAI,QAAQ;AACV,YAAM,UAAU,WAAW,YAAY;AACvC,YAAM,gBAAgB,iBAAiB,YAAY;AACnD,YAAM,MAAM;AAAA,QACV,OAAO;AAAA,QACP,OAAO;AAAA,QACP,OAAO,gBAAgB;AAAA,QACvB,WAAW;AAAA,QACX,iBAAiB;AAAA,MACnB,EAAE,KAAK,GAAG;AAEV,UAAI,CAAC,SAAS,IAAI,GAAG,GAAG;AACtB,iBAAS,IAAI,GAAG;AAChB,mBAAW,KAAK;AAAA,UACd,gBAAgB;AAAA,YACd,UAAU,OAAO;AAAA,YACjB,YAAY,OAAO;AAAA,YACnB,cAAc,OAAO;AAAA,YACrB;AAAA,UACF;AAAA,UACA;AAAA,UACA;AAAA,UACA,OAAO;AAAA,YACL,aAAa,iBAAiB,aAAa;AAAA,UAC7C;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF;AAEA,mBAAe,aAAa;AAC5B,aAAS;AAAA,EACX;AAEA,SAAO;AACT;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,3 +1,2 @@
|
|
|
1
1
|
import type { SelectedElement } from "../../_vendor/schemas/generated/selectMode";
|
|
2
2
|
export declare function symbolicateSelectedElement(selectedElement: SelectedElement): Promise<SelectedElement>;
|
|
3
|
-
export declare function symbolicateSelectedElements(elements: SelectedElement[]): Promise<SelectedElement[]>;
|
|
@@ -193,11 +193,7 @@ async function symbolicateSelectedElement(selectedElement) {
|
|
|
193
193
|
fiberChain
|
|
194
194
|
};
|
|
195
195
|
}
|
|
196
|
-
async function symbolicateSelectedElements(elements) {
|
|
197
|
-
return Promise.all(elements.map(symbolicateSelectedElement));
|
|
198
|
-
}
|
|
199
196
|
export {
|
|
200
|
-
symbolicateSelectedElement
|
|
201
|
-
symbolicateSelectedElements
|
|
197
|
+
symbolicateSelectedElement
|
|
202
198
|
};
|
|
203
199
|
//# sourceMappingURL=symbolicate.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../editor/select-mode/symbolicate.ts"],
|
|
4
|
-
"sourcesContent": ["import type {\n SelectedElement,\n SelectModeFiberChainEntry,\n SelectModeSourceLocation,\n} from \"schemas/generated/selectMode\";\n\n/**\n * Runtime source-attribution for React 19 + Next.js Turbopack.\n *\n * React 19 removed `fiber._debugSource`; the only per-element source pointer\n * left is `fiber._debugStack`, whose `.stack` references compiled SSR/client\n * chunks. We POST those compiled frames to Next.js's dev-only\n * `/__nextjs_original-stack-frames` endpoint, which symbolicates them through\n * Turbopack's in-memory source maps \u2014 the same mechanism the Next error\n * overlay uses (see `next/dist/server/dev/middleware-turbopack.js`).\n */\n\ntype NextStackFrame = {\n file: string | null;\n methodName: string | null;\n arguments: string[];\n // Next.js's `/__nextjs_original-stack-frames` reads these as `line1`/`column1`\n // (1-based) in the request body \u2014 same field names it uses in the response.\n // Sending `lineNumber`/`column` is silently dropped on the server side.\n line1: number | null;\n column1: number | null;\n};\n\ntype ResolvedFrame = {\n file: string | null;\n line1?: number | null;\n column1?: number | null;\n methodName?: string | null;\n ignored?: boolean;\n arguments?: string[];\n};\n\ntype OriginalStackFrameResponse = {\n originalStackFrame: ResolvedFrame | null;\n originalCodeFrame: string | null;\n};\n\ntype SettledResponseEntry =\n | { status: \"fulfilled\"; value: OriginalStackFrameResponse }\n | { status: \"rejected\"; reason: string };\n\nconst SYMBOLICATE_ENDPOINT = \"/__nextjs_original-stack-frames\";\n\nfunction isLikelyCompiledLocation(\n location: SelectModeSourceLocation | undefined,\n): boolean {\n if (!location) {\n return false;\n }\n const filePath = location.filePath;\n return (\n filePath.includes(\".next\") ||\n filePath.includes(\"/chunks/\") ||\n filePath.includes(\"webpack-internal:\") ||\n filePath.includes(\"turbopack:\") ||\n filePath.endsWith(\".js\") ||\n filePath.startsWith(\"about:\")\n );\n}\n\n// A resolved source that lives in a dependency or framework internal is never\n// the user's own code. The canonical case is Next's `<Image>`, whose rendered\n// `<img>` symbolicates to\n// `.../node_modules/next/src/client/image-component.tsx` \u2014 useless as an edit\n// target. We skip these and keep walking the ownership chain toward the user's\n// call site. See (Noah, 2026-07-09, REPL-29098).\nfunction isDependencyOrInternalPath(filePath: string): boolean {\n return (\n filePath.includes(\"node_modules\") ||\n filePath.includes(\"/dist/compiled/\") ||\n filePath.startsWith(\"about:\")\n );\n}\n\n// React 19 fibers for server-rendered (RSC) elements carry a `_debugStack`\n// whose top frame points at an SSR chunk (e.g. `about://React/Server/file://\n// .../.next-dev/.../server/chunks/ssr/*.js`). The endpoint resolves those\n// against the server bundler context; client chunks go through the client\n// bundler context. Mis-routing returns the compiled chunk unchanged.\nfunction isServerChunk(filePath: string): boolean {\n return (\n filePath.startsWith(\"about://React/Server\") ||\n filePath.includes(\"/server/chunks/\") ||\n filePath.includes(\".next-dev/dev/server/\") ||\n filePath.includes(\".next/server/\")\n );\n}\n\n// Matches the `/_next/static/...` tail of a browser chunk URL's pathname.\n// Capture group 1 is the `/static/...` segment that lives under the dist dir\n// on disk. Mirrors `regexNextStatic` in\n// `next/dist/server/lib/parse-stack.js`.\nconst NEXT_STATIC_PATH_PATTERN = /\\/_next(\\/static\\/.+)/;\n\n// Absolute path to the dev dist dir (e.g.\n// `/workspace/dev/website/.next-dev/dev`). Next.js define-injects this into\n// dev client bundles (see the `__NEXT_DIST_DIR` define in\n// `next/dist/build/define-env.ts`); because canopy-sdk is transpiled into the\n// host Next app, the replacement reaches this reference too. Outside a Next\n// dev client build the value is absent, so we bail and leave the URL as-is.\nfunction getNextDistDir(): string | null {\n try {\n const distDir = process.env.__NEXT_DIST_DIR;\n return typeof distDir === \"string\" && distDir.length > 0 ? distDir : null;\n } catch {\n return null;\n }\n}\n\n// Turbopack's `/__nextjs_original-stack-frames` backend only resolves source\n// maps for `file://` (or bare filesystem) paths \u2014 it rejects browser chunk\n// URLs (`https://host/_next/static/chunks/X.js`) with \"Unknown url scheme\",\n// which is why client-component frames never symbolicated in the sandbox\n// (everything is served over https) even though it worked for RSC frames that\n// already carry filesystem paths. Rewrite the URL to the on-disk dist path the\n// same way Next's own server-side stack parser does, so the endpoint can map\n// it back to the user's `.tsx`.\nfunction rewriteBrowserChunkUrlToDistPath(filePath: string): string {\n if (!/^https?:\\/\\//.test(filePath)) {\n return filePath;\n }\n const distDir = getNextDistDir();\n if (!distDir) {\n return filePath;\n }\n let url: URL;\n try {\n url = new URL(filePath);\n } catch {\n return filePath;\n }\n const staticPathMatch = NEXT_STATIC_PATH_PATTERN.exec(url.pathname);\n if (!staticPathMatch?.[1]) {\n return filePath;\n }\n const normalizedDistDir = distDir.replace(/\\\\/g, \"/\").replace(/\\/$/, \"\");\n return `file://${normalizedDistDir}${staticPathMatch[1]}${url.search}`;\n}\n\n// React 19's `_debugStack.stack` for RSC components wraps the SSR chunk URL\n// in an `about://React/Server/` prefix and appends a `?<digits>` cache-buster\n// (e.g. `about://React/Server/file:///.../[root-of-the-server]__abc._.js?21`).\n// Turbopack's source-map lookup matches against the bare chunk URL; with\n// either decoration in place it returns the compiled chunk unchanged. Client\n// components instead carry a plain browser chunk URL, which Turbopack rejects\n// outright unless rewritten to its on-disk `file://` path.\nfunction normalizeFilePathForSymbolicator(filePath: string): string {\n let normalized = filePath;\n if (normalized.startsWith(\"about://React/Server/\")) {\n normalized = normalized.slice(\"about://React/Server/\".length);\n }\n normalized = normalized.replace(/\\?\\d+$/, \"\");\n return rewriteBrowserChunkUrlToDistPath(normalized);\n}\n\nfunction toNextStackFrame(location: SelectModeSourceLocation): NextStackFrame {\n return {\n file: normalizeFilePathForSymbolicator(location.filePath),\n methodName: location.componentName ?? null,\n arguments: [],\n line1: location.lineNumber,\n column1: location.columnNumber ?? null,\n };\n}\n\nfunction extractResolvedFrame(\n entry: SettledResponseEntry | null,\n): ResolvedFrame | null {\n if (!entry || entry.status !== \"fulfilled\") {\n return null;\n }\n return entry.value?.originalStackFrame ?? null;\n}\n\nasync function postFrames({\n frames,\n isServer,\n}: {\n frames: NextStackFrame[];\n isServer: boolean;\n}): Promise<(SettledResponseEntry | null)[]> {\n if (frames.length === 0) {\n return [];\n }\n try {\n const response = await fetch(SYMBOLICATE_ENDPOINT, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({\n frames,\n isServer,\n isEdgeServer: false,\n isAppDirectory: true,\n }),\n });\n if (!response.ok) {\n console.log(\"[selectMode] symbolicate: endpoint returned non-OK status\", {\n status: response.status,\n isServer,\n });\n return frames.map(() => null);\n }\n const parsed: unknown = await response.json();\n if (Array.isArray(parsed)) {\n // Promise.allSettled-shaped entries; see\n // node_modules/next/dist/server/dev/middleware-turbopack.js.\n // Legacy cast - the runtime shape isn't exported as a type.\n // eslint-disable-next-line replo/no-as-cast\n return parsed as (SettledResponseEntry | null)[];\n }\n return frames.map(() => null);\n } catch (error) {\n console.log(\"[selectMode] symbolicate: fetch failed\", {\n isServer,\n error,\n });\n return frames.map(() => null);\n }\n}\n\nasync function symbolicateFrames(\n frames: NextStackFrame[],\n): Promise<(SettledResponseEntry | null)[]> {\n const serverIndices: number[] = [];\n const clientIndices: number[] = [];\n for (const [index, frame] of frames.entries()) {\n if (frame.file && isServerChunk(frame.file)) {\n serverIndices.push(index);\n } else {\n clientIndices.push(index);\n }\n }\n\n const [serverResults, clientResults] = await Promise.all([\n postFrames({\n frames: serverIndices.map((index) => frames[index]!),\n isServer: true,\n }),\n postFrames({\n frames: clientIndices.map((index) => frames[index]!),\n isServer: false,\n }),\n ]);\n\n const merged: (SettledResponseEntry | null)[] = frames.map(() => null);\n for (const [position, index] of serverIndices.entries()) {\n merged[index] = serverResults[position] ?? null;\n }\n for (const [position, index] of clientIndices.entries()) {\n merged[index] = clientResults[position] ?? null;\n }\n return merged;\n}\n\nfunction applyResolved({\n original,\n frame,\n}: {\n original: SelectModeSourceLocation;\n frame: ResolvedFrame | null;\n}): SelectModeSourceLocation {\n if (!frame || !frame.file || frame.line1 == null) {\n return original;\n }\n return {\n filePath: frame.file,\n lineNumber: frame.line1,\n columnNumber: frame.column1 ?? undefined,\n componentName: original.componentName,\n };\n}\n\n// The innermost chain entry that is a usable edit target: already-symbolicated\n// (still-compiled frames failed to resolve and are useless) and outside\n// dependency/framework code. See (Noah, 2026-07-09, REPL-29098).\nfunction findUserSourceLocation(\n fiberChain: SelectModeFiberChainEntry[],\n): SelectModeSourceLocation | undefined {\n return fiberChain.find((entry) => {\n return (\n !isLikelyCompiledLocation(entry.sourceLocation) &&\n !isDependencyOrInternalPath(entry.sourceLocation.filePath)\n );\n })?.sourceLocation;\n}\n\nexport async function symbolicateSelectedElement(\n selectedElement: SelectedElement,\n): Promise<SelectedElement> {\n const targets: {\n location: SelectModeSourceLocation;\n apply: (next: SelectModeSourceLocation) => void;\n }[] = [];\n\n const fiberChain: SelectModeFiberChainEntry[] =\n selectedElement.fiberChain.map((entry) => ({ ...entry }));\n for (const entry of fiberChain) {\n if (isLikelyCompiledLocation(entry.sourceLocation)) {\n targets.push({\n location: entry.sourceLocation,\n apply: (next) => {\n entry.sourceLocation = next;\n },\n });\n }\n }\n\n let sourceLocation = selectedElement.sourceLocation;\n // With a chain present `sourceLocation` is re-derived from it below, so\n // targeting it here would just duplicate the chain head's round trip.\n if (\n fiberChain.length === 0 &&\n sourceLocation &&\n isLikelyCompiledLocation(sourceLocation)\n ) {\n const captured = sourceLocation;\n targets.push({\n location: captured,\n apply: (next) => {\n sourceLocation = next;\n },\n });\n }\n\n if (targets.length === 0) {\n return selectedElement;\n }\n\n const resolved = await symbolicateFrames(\n targets.map((target) => toNextStackFrame(target.location)),\n );\n\n for (const [index, target] of targets.entries()) {\n const frame = extractResolvedFrame(resolved[index] ?? null);\n target.apply(applyResolved({ original: target.location, frame }));\n }\n\n if (fiberChain.length > 0) {\n // Fall back to the chain head so we never regress to attributing nothing.\n sourceLocation =\n findUserSourceLocation(fiberChain) ?? fiberChain[0]!.sourceLocation;\n }\n\n return {\n ...selectedElement,\n sourceLocation,\n fiberChain,\n };\n}\n\nexport async function symbolicateSelectedElements(\n elements: SelectedElement[],\n): Promise<SelectedElement[]> {\n return Promise.all(elements.map(symbolicateSelectedElement));\n}\n"],
|
|
5
|
-
"mappings": "AA8CA,MAAM,uBAAuB;AAE7B,SAAS,yBACP,UACS;AACT,MAAI,CAAC,UAAU;AACb,WAAO;AAAA,EACT;AACA,QAAM,WAAW,SAAS;AAC1B,SACE,SAAS,SAAS,OAAO,KACzB,SAAS,SAAS,UAAU,KAC5B,SAAS,SAAS,mBAAmB,KACrC,SAAS,SAAS,YAAY,KAC9B,SAAS,SAAS,KAAK,KACvB,SAAS,WAAW,QAAQ;AAEhC;AAQA,SAAS,2BAA2B,UAA2B;AAC7D,SACE,SAAS,SAAS,cAAc,KAChC,SAAS,SAAS,iBAAiB,KACnC,SAAS,WAAW,QAAQ;AAEhC;AAOA,SAAS,cAAc,UAA2B;AAChD,SACE,SAAS,WAAW,sBAAsB,KAC1C,SAAS,SAAS,iBAAiB,KACnC,SAAS,SAAS,uBAAuB,KACzC,SAAS,SAAS,eAAe;AAErC;AAMA,MAAM,2BAA2B;AAQjC,SAAS,iBAAgC;AACvC,MAAI;AACF,UAAM,UAAU,QAAQ,IAAI;AAC5B,WAAO,OAAO,YAAY,YAAY,QAAQ,SAAS,IAAI,UAAU;AAAA,EACvE,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAUA,SAAS,iCAAiC,UAA0B;AAClE,MAAI,CAAC,eAAe,KAAK,QAAQ,GAAG;AAClC,WAAO;AAAA,EACT;AACA,QAAM,UAAU,eAAe;AAC/B,MAAI,CAAC,SAAS;AACZ,WAAO;AAAA,EACT;AACA,MAAI;AACJ,MAAI;AACF,UAAM,IAAI,IAAI,QAAQ;AAAA,EACxB,QAAQ;AACN,WAAO;AAAA,EACT;AACA,QAAM,kBAAkB,yBAAyB,KAAK,IAAI,QAAQ;AAClE,MAAI,CAAC,kBAAkB,CAAC,GAAG;AACzB,WAAO;AAAA,EACT;AACA,QAAM,oBAAoB,QAA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AAuB,UAAU,KAAK,WAAW,CAAC,EAAG;AAAA,EACzD;AAEA,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,IACA;AAAA,EACF;AACF;
|
|
4
|
+
"sourcesContent": ["import type {\n SelectedElement,\n SelectModeFiberChainEntry,\n SelectModeSourceLocation,\n} from \"schemas/generated/selectMode\";\n\n/**\n * Runtime source-attribution for React 19 + Next.js Turbopack.\n *\n * React 19 removed `fiber._debugSource`; the only per-element source pointer\n * left is `fiber._debugStack`, whose `.stack` references compiled SSR/client\n * chunks. We POST those compiled frames to Next.js's dev-only\n * `/__nextjs_original-stack-frames` endpoint, which symbolicates them through\n * Turbopack's in-memory source maps \u2014 the same mechanism the Next error\n * overlay uses (see `next/dist/server/dev/middleware-turbopack.js`).\n */\n\ntype NextStackFrame = {\n file: string | null;\n methodName: string | null;\n arguments: string[];\n // Next.js's `/__nextjs_original-stack-frames` reads these as `line1`/`column1`\n // (1-based) in the request body \u2014 same field names it uses in the response.\n // Sending `lineNumber`/`column` is silently dropped on the server side.\n line1: number | null;\n column1: number | null;\n};\n\ntype ResolvedFrame = {\n file: string | null;\n line1?: number | null;\n column1?: number | null;\n methodName?: string | null;\n ignored?: boolean;\n arguments?: string[];\n};\n\ntype OriginalStackFrameResponse = {\n originalStackFrame: ResolvedFrame | null;\n originalCodeFrame: string | null;\n};\n\ntype SettledResponseEntry =\n | { status: \"fulfilled\"; value: OriginalStackFrameResponse }\n | { status: \"rejected\"; reason: string };\n\nconst SYMBOLICATE_ENDPOINT = \"/__nextjs_original-stack-frames\";\n\nfunction isLikelyCompiledLocation(\n location: SelectModeSourceLocation | undefined,\n): boolean {\n if (!location) {\n return false;\n }\n const filePath = location.filePath;\n return (\n filePath.includes(\".next\") ||\n filePath.includes(\"/chunks/\") ||\n filePath.includes(\"webpack-internal:\") ||\n filePath.includes(\"turbopack:\") ||\n filePath.endsWith(\".js\") ||\n filePath.startsWith(\"about:\")\n );\n}\n\n// A resolved source that lives in a dependency or framework internal is never\n// the user's own code. The canonical case is Next's `<Image>`, whose rendered\n// `<img>` symbolicates to\n// `.../node_modules/next/src/client/image-component.tsx` \u2014 useless as an edit\n// target. We skip these and keep walking the ownership chain toward the user's\n// call site. See (Noah, 2026-07-09, REPL-29098).\nfunction isDependencyOrInternalPath(filePath: string): boolean {\n return (\n filePath.includes(\"node_modules\") ||\n filePath.includes(\"/dist/compiled/\") ||\n filePath.startsWith(\"about:\")\n );\n}\n\n// React 19 fibers for server-rendered (RSC) elements carry a `_debugStack`\n// whose top frame points at an SSR chunk (e.g. `about://React/Server/file://\n// .../.next-dev/.../server/chunks/ssr/*.js`). The endpoint resolves those\n// against the server bundler context; client chunks go through the client\n// bundler context. Mis-routing returns the compiled chunk unchanged.\nfunction isServerChunk(filePath: string): boolean {\n return (\n filePath.startsWith(\"about://React/Server\") ||\n filePath.includes(\"/server/chunks/\") ||\n filePath.includes(\".next-dev/dev/server/\") ||\n filePath.includes(\".next/server/\")\n );\n}\n\n// Matches the `/_next/static/...` tail of a browser chunk URL's pathname.\n// Capture group 1 is the `/static/...` segment that lives under the dist dir\n// on disk. Mirrors `regexNextStatic` in\n// `next/dist/server/lib/parse-stack.js`.\nconst NEXT_STATIC_PATH_PATTERN = /\\/_next(\\/static\\/.+)/;\n\n// Absolute path to the dev dist dir (e.g.\n// `/workspace/dev/website/.next-dev/dev`). Next.js define-injects this into\n// dev client bundles (see the `__NEXT_DIST_DIR` define in\n// `next/dist/build/define-env.ts`); because canopy-sdk is transpiled into the\n// host Next app, the replacement reaches this reference too. Outside a Next\n// dev client build the value is absent, so we bail and leave the URL as-is.\nfunction getNextDistDir(): string | null {\n try {\n const distDir = process.env.__NEXT_DIST_DIR;\n return typeof distDir === \"string\" && distDir.length > 0 ? distDir : null;\n } catch {\n return null;\n }\n}\n\n// Turbopack's `/__nextjs_original-stack-frames` backend only resolves source\n// maps for `file://` (or bare filesystem) paths \u2014 it rejects browser chunk\n// URLs (`https://host/_next/static/chunks/X.js`) with \"Unknown url scheme\",\n// which is why client-component frames never symbolicated in the sandbox\n// (everything is served over https) even though it worked for RSC frames that\n// already carry filesystem paths. Rewrite the URL to the on-disk dist path the\n// same way Next's own server-side stack parser does, so the endpoint can map\n// it back to the user's `.tsx`.\nfunction rewriteBrowserChunkUrlToDistPath(filePath: string): string {\n if (!/^https?:\\/\\//.test(filePath)) {\n return filePath;\n }\n const distDir = getNextDistDir();\n if (!distDir) {\n return filePath;\n }\n let url: URL;\n try {\n url = new URL(filePath);\n } catch {\n return filePath;\n }\n const staticPathMatch = NEXT_STATIC_PATH_PATTERN.exec(url.pathname);\n if (!staticPathMatch?.[1]) {\n return filePath;\n }\n const normalizedDistDir = distDir.replace(/\\\\/g, \"/\").replace(/\\/$/, \"\");\n return `file://${normalizedDistDir}${staticPathMatch[1]}${url.search}`;\n}\n\n// React 19's `_debugStack.stack` for RSC components wraps the SSR chunk URL\n// in an `about://React/Server/` prefix and appends a `?<digits>` cache-buster\n// (e.g. `about://React/Server/file:///.../[root-of-the-server]__abc._.js?21`).\n// Turbopack's source-map lookup matches against the bare chunk URL; with\n// either decoration in place it returns the compiled chunk unchanged. Client\n// components instead carry a plain browser chunk URL, which Turbopack rejects\n// outright unless rewritten to its on-disk `file://` path.\nfunction normalizeFilePathForSymbolicator(filePath: string): string {\n let normalized = filePath;\n if (normalized.startsWith(\"about://React/Server/\")) {\n normalized = normalized.slice(\"about://React/Server/\".length);\n }\n normalized = normalized.replace(/\\?\\d+$/, \"\");\n return rewriteBrowserChunkUrlToDistPath(normalized);\n}\n\nfunction toNextStackFrame(location: SelectModeSourceLocation): NextStackFrame {\n return {\n file: normalizeFilePathForSymbolicator(location.filePath),\n methodName: location.componentName ?? null,\n arguments: [],\n line1: location.lineNumber,\n column1: location.columnNumber ?? null,\n };\n}\n\nfunction extractResolvedFrame(\n entry: SettledResponseEntry | null,\n): ResolvedFrame | null {\n if (!entry || entry.status !== \"fulfilled\") {\n return null;\n }\n return entry.value?.originalStackFrame ?? null;\n}\n\nasync function postFrames({\n frames,\n isServer,\n}: {\n frames: NextStackFrame[];\n isServer: boolean;\n}): Promise<(SettledResponseEntry | null)[]> {\n if (frames.length === 0) {\n return [];\n }\n try {\n const response = await fetch(SYMBOLICATE_ENDPOINT, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({\n frames,\n isServer,\n isEdgeServer: false,\n isAppDirectory: true,\n }),\n });\n if (!response.ok) {\n console.log(\"[selectMode] symbolicate: endpoint returned non-OK status\", {\n status: response.status,\n isServer,\n });\n return frames.map(() => null);\n }\n const parsed: unknown = await response.json();\n if (Array.isArray(parsed)) {\n // Promise.allSettled-shaped entries; see\n // node_modules/next/dist/server/dev/middleware-turbopack.js.\n // Legacy cast - the runtime shape isn't exported as a type.\n // eslint-disable-next-line replo/no-as-cast\n return parsed as (SettledResponseEntry | null)[];\n }\n return frames.map(() => null);\n } catch (error) {\n console.log(\"[selectMode] symbolicate: fetch failed\", {\n isServer,\n error,\n });\n return frames.map(() => null);\n }\n}\n\nasync function symbolicateFrames(\n frames: NextStackFrame[],\n): Promise<(SettledResponseEntry | null)[]> {\n const serverIndices: number[] = [];\n const clientIndices: number[] = [];\n for (const [index, frame] of frames.entries()) {\n if (frame.file && isServerChunk(frame.file)) {\n serverIndices.push(index);\n } else {\n clientIndices.push(index);\n }\n }\n\n const [serverResults, clientResults] = await Promise.all([\n postFrames({\n frames: serverIndices.map((index) => frames[index]!),\n isServer: true,\n }),\n postFrames({\n frames: clientIndices.map((index) => frames[index]!),\n isServer: false,\n }),\n ]);\n\n const merged: (SettledResponseEntry | null)[] = frames.map(() => null);\n for (const [position, index] of serverIndices.entries()) {\n merged[index] = serverResults[position] ?? null;\n }\n for (const [position, index] of clientIndices.entries()) {\n merged[index] = clientResults[position] ?? null;\n }\n return merged;\n}\n\nfunction applyResolved({\n original,\n frame,\n}: {\n original: SelectModeSourceLocation;\n frame: ResolvedFrame | null;\n}): SelectModeSourceLocation {\n if (!frame || !frame.file || frame.line1 == null) {\n return original;\n }\n return {\n filePath: frame.file,\n lineNumber: frame.line1,\n columnNumber: frame.column1 ?? undefined,\n componentName: original.componentName,\n };\n}\n\n// The innermost chain entry that is a usable edit target: already-symbolicated\n// (still-compiled frames failed to resolve and are useless) and outside\n// dependency/framework code. See (Noah, 2026-07-09, REPL-29098).\nfunction findUserSourceLocation(\n fiberChain: SelectModeFiberChainEntry[],\n): SelectModeSourceLocation | undefined {\n return fiberChain.find((entry) => {\n return (\n !isLikelyCompiledLocation(entry.sourceLocation) &&\n !isDependencyOrInternalPath(entry.sourceLocation.filePath)\n );\n })?.sourceLocation;\n}\n\nexport async function symbolicateSelectedElement(\n selectedElement: SelectedElement,\n): Promise<SelectedElement> {\n const targets: {\n location: SelectModeSourceLocation;\n apply: (next: SelectModeSourceLocation) => void;\n }[] = [];\n\n const fiberChain: SelectModeFiberChainEntry[] =\n selectedElement.fiberChain.map((entry) => ({ ...entry }));\n for (const entry of fiberChain) {\n if (isLikelyCompiledLocation(entry.sourceLocation)) {\n targets.push({\n location: entry.sourceLocation,\n apply: (next) => {\n entry.sourceLocation = next;\n },\n });\n }\n }\n\n let sourceLocation = selectedElement.sourceLocation;\n // With a chain present `sourceLocation` is re-derived from it below, so\n // targeting it here would just duplicate the chain head's round trip.\n if (\n fiberChain.length === 0 &&\n sourceLocation &&\n isLikelyCompiledLocation(sourceLocation)\n ) {\n const captured = sourceLocation;\n targets.push({\n location: captured,\n apply: (next) => {\n sourceLocation = next;\n },\n });\n }\n\n if (targets.length === 0) {\n return selectedElement;\n }\n\n const resolved = await symbolicateFrames(\n targets.map((target) => toNextStackFrame(target.location)),\n );\n\n for (const [index, target] of targets.entries()) {\n const frame = extractResolvedFrame(resolved[index] ?? null);\n target.apply(applyResolved({ original: target.location, frame }));\n }\n\n if (fiberChain.length > 0) {\n // Fall back to the chain head so we never regress to attributing nothing.\n sourceLocation =\n findUserSourceLocation(fiberChain) ?? fiberChain[0]!.sourceLocation;\n }\n\n return {\n ...selectedElement,\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,GAAG;AAAA,IACH;AAAA,IACA;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/env.d.ts
CHANGED
|
@@ -3,11 +3,7 @@ type Env = {
|
|
|
3
3
|
PROJECT_ID: string;
|
|
4
4
|
ANALYTICS_FIRE_API_URL?: string;
|
|
5
5
|
REPLO_ANALYTICS_PIXEL_URL?: string;
|
|
6
|
-
SHOPIFY_URL?: string;
|
|
7
|
-
SHOPIFY_STOREFRONT_ACCESS_TOKEN?: string | null;
|
|
8
|
-
STRIPE_CONNECT_ACCOUNT_ID?: string | null;
|
|
9
6
|
CHECKOUT_PROVIDER?: "shopify" | "stripe" | "none";
|
|
10
|
-
REPLO_INTERNAL_REVALIDATE_SECRET?: string;
|
|
11
7
|
};
|
|
12
8
|
export declare const getEnv: () => Promise<Env>;
|
|
13
9
|
export {};
|
package/env.js
CHANGED
|
@@ -6,11 +6,7 @@ const envSchema = z.object({
|
|
|
6
6
|
PROJECT_ID: z.uuid(),
|
|
7
7
|
ANALYTICS_FIRE_API_URL: z.string().optional(),
|
|
8
8
|
REPLO_ANALYTICS_PIXEL_URL: z.string().optional(),
|
|
9
|
-
|
|
10
|
-
SHOPIFY_STOREFRONT_ACCESS_TOKEN: z.string().nullish(),
|
|
11
|
-
STRIPE_CONNECT_ACCOUNT_ID: z.string().nullish(),
|
|
12
|
-
CHECKOUT_PROVIDER: z.enum(["shopify", "stripe", "none"]).optional(),
|
|
13
|
-
REPLO_INTERNAL_REVALIDATE_SECRET: z.string().optional()
|
|
9
|
+
CHECKOUT_PROVIDER: z.enum(["shopify", "stripe", "none"]).optional()
|
|
14
10
|
});
|
|
15
11
|
const wranglerConfigSchema = z.object({ vars: envSchema });
|
|
16
12
|
const isDeployedWorker = () => {
|
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 JSONC from \"tiny-jsonc\";\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 // Base URL of the Replo first-party analytics pixel CDN (e.g.\n // https://pixel.replo.app). `<ReploFirstPartyPixel>` loads\n // `${REPLO_ANALYTICS_PIXEL_URL}/latest.js` into the page once analytics consent\n // is granted; the browser fetches it directly. Optional: absent when the pixel\n // isn't configured (e.g. lean local dev), where the pixel simply isn't injected.\n REPLO_ANALYTICS_PIXEL_URL?: string;\n\n
|
|
5
|
-
"mappings": "AAAA,SAAS,4BAA4B;AACrC,OAAO,WAAW;AAClB,SAAS,SAAS;
|
|
4
|
+
"sourcesContent": ["import { getCloudflareContext } from \"@opennextjs/cloudflare\";\nimport JSONC from \"tiny-jsonc\";\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 // Base URL of the Replo first-party analytics pixel CDN (e.g.\n // https://pixel.replo.app). `<ReploFirstPartyPixel>` loads\n // `${REPLO_ANALYTICS_PIXEL_URL}/latest.js` into the page once analytics consent\n // is granted; the browser fetches it directly. Optional: absent when the pixel\n // isn't configured (e.g. lean local dev), where the pixel simply isn't injected.\n REPLO_ANALYTICS_PIXEL_URL?: string;\n\n CHECKOUT_PROVIDER?: \"shopify\" | \"stripe\" | \"none\";\n};\n\nconst envSchema = z.object({\n CANOPY_API_HOST: z.string().min(1),\n PROJECT_ID: z.uuid(),\n ANALYTICS_FIRE_API_URL: z.string().optional(),\n REPLO_ANALYTICS_PIXEL_URL: z.string().optional(),\n CHECKOUT_PROVIDER: z.enum([\"shopify\", \"stripe\", \"none\"]).optional(),\n});\n\nconst wranglerConfigSchema = z.object({ vars: envSchema });\n\n// NOTE (Cole, 2026-07-28, REPL-29501): outside the deployed worker, read wrangler.jsonc directly \u2014 concurrent workerd boots race on the shared .wrangler/state SQLite (SQLITE_BUSY).\nconst isDeployedWorker = () => {\n return (\n process.env.NODE_ENV === \"production\" &&\n process.env.BUILD_ENV !== \"build\" &&\n process.env.NEXT_PHASE !== \"phase-production-build\"\n );\n};\n\nexport const getEnv = async (): Promise<Env> => {\n if (isDeployedWorker()) {\n const { env } = await getCloudflareContext({ async: true });\n return envSchema.parse(env);\n }\n // NOTE (Cole, 2026-07-29, REPL-29501): client chunks bundle this module (integration-utils has client consumers). A static node:fs broke those chunks in 0.16.3, and a computed specifier fails Turbopack too (\"expression is too dynamic\") \u2014 only the ignore-annotated literal import compiles; postbuild.mjs asserts the annotation survives into dist.\n const { promises: fs }: typeof import(\"node:fs\") = await import(\n /* turbopackIgnore: true */ /* webpackIgnore: true */ \"node:fs\"\n );\n const raw = await fs.readFile(`${process.cwd()}/wrangler.jsonc`, \"utf8\");\n return wranglerConfigSchema.parse(JSONC.parse(raw)).vars;\n};\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,4BAA4B;AACrC,OAAO,WAAW;AAClB,SAAS,SAAS;AAsBlB,MAAM,YAAY,EAAE,OAAO;AAAA,EACzB,iBAAiB,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACjC,YAAY,EAAE,KAAK;AAAA,EACnB,wBAAwB,EAAE,OAAO,EAAE,SAAS;AAAA,EAC5C,2BAA2B,EAAE,OAAO,EAAE,SAAS;AAAA,EAC/C,mBAAmB,EAAE,KAAK,CAAC,WAAW,UAAU,MAAM,CAAC,EAAE,SAAS;AACpE,CAAC;AAED,MAAM,uBAAuB,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC;AAGzD,MAAM,mBAAmB,MAAM;AAC7B,SACE,QAAQ,IAAI,aAAa,gBACzB,QAAQ,IAAI,cAAc,WAC1B,QAAQ,IAAI,eAAe;AAE/B;AAEO,MAAM,SAAS,YAA0B;AAC9C,MAAI,iBAAiB,GAAG;AACtB,UAAM,EAAE,IAAI,IAAI,MAAM,qBAAqB,EAAE,OAAO,KAAK,CAAC;AAC1D,WAAO,UAAU,MAAM,GAAG;AAAA,EAC5B;AAEA,QAAM,EAAE,UAAU,GAAG,IAA8B,MAAM;AAAA;AAAA;AAAA,IACD;AAAA,EACxD;AACA,QAAM,MAAM,MAAM,GAAG,SAAS,GAAG,QAAQ,IAAI,CAAC,mBAAmB,MAAM;AACvE,SAAO,qBAAqB,MAAM,MAAM,MAAM,GAAG,CAAC,EAAE;AACtD;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/gateways/canopy-api.d.ts
CHANGED
|
@@ -10,7 +10,6 @@ export declare class CanopyApiGatewayError extends CanopyError {
|
|
|
10
10
|
statusCode: number;
|
|
11
11
|
constructor(config: CanopyApiGatewayErrorConfig);
|
|
12
12
|
}
|
|
13
|
-
export declare function isCanopyApiGatewayError(error: unknown): error is CanopyApiGatewayError;
|
|
14
13
|
declare class CanopyApiGateway {
|
|
15
14
|
private apiHost;
|
|
16
15
|
private baseUrl;
|
package/gateways/canopy-api.js
CHANGED
|
@@ -18,9 +18,6 @@ class CanopyApiGatewayError extends CanopyError {
|
|
|
18
18
|
this.statusCode = resolvedStatusCode;
|
|
19
19
|
}
|
|
20
20
|
}
|
|
21
|
-
function isCanopyApiGatewayError(error) {
|
|
22
|
-
return error instanceof CanopyApiGatewayError;
|
|
23
|
-
}
|
|
24
21
|
class UnknownCanopyApiError extends CanopyApiGatewayError {
|
|
25
22
|
constructor(config) {
|
|
26
23
|
super({ ...config, statusCode: 502 });
|
|
@@ -195,7 +192,6 @@ async function getCanopyApiGateway() {
|
|
|
195
192
|
}
|
|
196
193
|
export {
|
|
197
194
|
CanopyApiGatewayError,
|
|
198
|
-
getCanopyApiGateway
|
|
199
|
-
isCanopyApiGatewayError
|
|
195
|
+
getCanopyApiGateway
|
|
200
196
|
};
|
|
201
197
|
//# sourceMappingURL=canopy-api.js.map
|
|
@@ -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\
|
|
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;
|
|
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,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9
|
*/
|
|
10
10
|
export declare function convertLegacyResourceIdToGraphQLId(id: string, type: "Product" | "ProductVariant"): string;
|
|
11
|
-
/**
|
|
12
|
-
* Converts a Shopify GraphQL ID to a legacy resource ID
|
|
13
|
-
* @param id - The full Shopify GID (e.g., "gid://shopify/ProductVariant/123456")
|
|
14
|
-
* @returns The legacy resource ID (e.g., "123456")
|
|
15
|
-
*/
|
|
16
|
-
export declare function convertGraphQLIdToLegacyResourceId(id: string): string;
|
package/lib/shopify-utils.js
CHANGED
|
@@ -1,11 +1,7 @@
|
|
|
1
1
|
function convertLegacyResourceIdToGraphQLId(id, type) {
|
|
2
2
|
return `gid://shopify/${type}/${id}`;
|
|
3
3
|
}
|
|
4
|
-
function convertGraphQLIdToLegacyResourceId(id) {
|
|
5
|
-
return id.split("/").pop() ?? id;
|
|
6
|
-
}
|
|
7
4
|
export {
|
|
8
|
-
convertGraphQLIdToLegacyResourceId,
|
|
9
5
|
convertLegacyResourceIdToGraphQLId
|
|
10
6
|
};
|
|
11
7
|
//# sourceMappingURL=shopify-utils.js.map
|
package/lib/shopify-utils.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../lib/shopify-utils.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Utility functions for working with Shopify IDs and GIDs\n */\n\n/**\n * Converts a legacy resource ID to a Shopify GraphQL ID\n * @param id - The legacy resource ID (e.g., \"123456\")\n * @param type - The Shopify resource type\n * @returns The full Shopify GID (e.g., \"gid://shopify/ProductVariant/123456\")\n */\nexport function convertLegacyResourceIdToGraphQLId(\n id: string,\n type: \"Product\" | \"ProductVariant\",\n): string {\n return `gid://shopify/${type}/${id}`;\n}\n
|
|
5
|
-
"mappings": "AAUO,SAAS,mCACd,IACA,MACQ;AACR,SAAO,iBAAiB,IAAI,IAAI,EAAE;AACpC;
|
|
4
|
+
"sourcesContent": ["/**\n * Utility functions for working with Shopify IDs and GIDs\n */\n\n/**\n * Converts a legacy resource ID to a Shopify GraphQL ID\n * @param id - The legacy resource ID (e.g., \"123456\")\n * @param type - The Shopify resource type\n * @returns The full Shopify GID (e.g., \"gid://shopify/ProductVariant/123456\")\n */\nexport function convertLegacyResourceIdToGraphQLId(\n id: string,\n type: \"Product\" | \"ProductVariant\",\n): string {\n return `gid://shopify/${type}/${id}`;\n}\n"],
|
|
5
|
+
"mappings": "AAUO,SAAS,mCACd,IACA,MACQ;AACR,SAAO,iBAAiB,IAAI,IAAI,EAAE;AACpC;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -2,7 +2,6 @@ import { CanopyError } from "../lib/canopy-error";
|
|
|
2
2
|
/** Scoped error for loader invocation failures. */
|
|
3
3
|
export declare class LoaderInvokeError extends CanopyError {
|
|
4
4
|
}
|
|
5
|
-
export declare function isLoaderInvokeError(error: unknown): error is LoaderInvokeError;
|
|
6
5
|
/**
|
|
7
6
|
* Invokes a data loader. During SSR, calls the canopy-api gateway directly.
|
|
8
7
|
* In the browser, dynamically imports a server action so React 19 never sees
|
package/loaders/invoke-loader.js
CHANGED
|
@@ -2,9 +2,6 @@ import { CanopyError } from "../lib/canopy-error";
|
|
|
2
2
|
import { resolvePreviewPlaceholderData } from "./preview-placeholder";
|
|
3
3
|
class LoaderInvokeError extends CanopyError {
|
|
4
4
|
}
|
|
5
|
-
function isLoaderInvokeError(error) {
|
|
6
|
-
return error instanceof LoaderInvokeError;
|
|
7
|
-
}
|
|
8
5
|
async function invokeLoader({
|
|
9
6
|
loaderKey,
|
|
10
7
|
args
|
|
@@ -35,7 +32,6 @@ async function invokeLoader({
|
|
|
35
32
|
}
|
|
36
33
|
export {
|
|
37
34
|
LoaderInvokeError,
|
|
38
|
-
invokeLoader
|
|
39
|
-
isLoaderInvokeError
|
|
35
|
+
invokeLoader
|
|
40
36
|
};
|
|
41
37
|
//# sourceMappingURL=invoke-loader.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../loaders/invoke-loader.ts"],
|
|
4
|
-
"sourcesContent": ["import { CanopyError } from \"../lib/canopy-error\";\nimport { resolvePreviewPlaceholderData } from \"./preview-placeholder\";\n\n/** Scoped error for loader invocation failures. */\nexport class LoaderInvokeError extends CanopyError {}\n\
|
|
5
|
-
"mappings": "AAAA,SAAS,mBAAmB;AAC5B,SAAS,qCAAqC;AAGvC,MAAM,0BAA0B,YAAY;AAAC;
|
|
4
|
+
"sourcesContent": ["import { CanopyError } from \"../lib/canopy-error\";\nimport { resolvePreviewPlaceholderData } from \"./preview-placeholder\";\n\n/** Scoped error for loader invocation failures. */\nexport class LoaderInvokeError extends CanopyError {}\n\n/**\n * Invokes a data loader. During SSR, calls the canopy-api gateway directly.\n * In the browser, dynamically imports a server action so React 19 never sees\n * the \"use server\" reference during render.\n *\n * In an editor iframe previewing an unfilled dynamic route, returns sample\n * data instead of fetching \u2014 see `preview-placeholder.ts`.\n */\nexport async function invokeLoader({\n loaderKey,\n args,\n}: {\n loaderKey: string;\n args: Record<string, unknown>;\n}) {\n const placeholderData = resolvePreviewPlaceholderData({ loaderKey, args });\n if (placeholderData !== null) {\n return placeholderData;\n }\n try {\n if (typeof window === \"undefined\") {\n const { getCanopyApiGateway } = await import(\"../gateways/canopy-api\");\n const gateway = await getCanopyApiGateway();\n const response = await gateway.invokeLoader({ loaderKey, args });\n return response.data;\n }\n\n const { invokeLoaderAction } = await import(\"./invoke-loader-action\");\n return await invokeLoaderAction({ loaderKey, args });\n } catch (error) {\n if (error instanceof LoaderInvokeError) {\n throw error;\n }\n throw new LoaderInvokeError({\n message: `Loader ${loaderKey} failed: ${error instanceof Error ? error.message : String(error)}`,\n cause: error,\n additionalData: { loaderKey },\n });\n }\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,mBAAmB;AAC5B,SAAS,qCAAqC;AAGvC,MAAM,0BAA0B,YAAY;AAAC;AAUpD,eAAsB,aAAa;AAAA,EACjC;AAAA,EACA;AACF,GAGG;AACD,QAAM,kBAAkB,8BAA8B,EAAE,WAAW,KAAK,CAAC;AACzE,MAAI,oBAAoB,MAAM;AAC5B,WAAO;AAAA,EACT;AACA,MAAI;AACF,QAAI,OAAO,WAAW,aAAa;AACjC,YAAM,EAAE,oBAAoB,IAAI,MAAM,OAAO,wBAAwB;AACrE,YAAM,UAAU,MAAM,oBAAoB;AAC1C,YAAM,WAAW,MAAM,QAAQ,aAAa,EAAE,WAAW,KAAK,CAAC;AAC/D,aAAO,SAAS;AAAA,IAClB;AAEA,UAAM,EAAE,mBAAmB,IAAI,MAAM,OAAO,wBAAwB;AACpE,WAAO,MAAM,mBAAmB,EAAE,WAAW,KAAK,CAAC;AAAA,EACrD,SAAS,OAAO;AACd,QAAI,iBAAiB,mBAAmB;AACtC,YAAM;AAAA,IACR;AACA,UAAM,IAAI,kBAAkB;AAAA,MAC1B,SAAS,UAAU,SAAS,YAAY,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA,MAC9F,OAAO;AAAA,MACP,gBAAgB,EAAE,UAAU;AAAA,IAC9B,CAAC;AAAA,EACH;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/loaders/loader-keys.d.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { z } from "zod";
|
|
2
1
|
/**
|
|
3
2
|
* Shared data-loader key constants. Loader components and prefetch queries
|
|
4
3
|
* import from here so the strings are never duplicated across a generated site.
|
|
@@ -29,21 +28,3 @@ export declare const DATA_LOADER_KEYS: {
|
|
|
29
28
|
readonly CONTENTFUL_ENTRIES: "contentful.entries";
|
|
30
29
|
};
|
|
31
30
|
export type DataLoaderKey = (typeof DATA_LOADER_KEYS)[keyof typeof DATA_LOADER_KEYS];
|
|
32
|
-
export declare const dataLoaderKeySchema: z.ZodEnum<{
|
|
33
|
-
"shopify_storefront.product": "shopify_storefront.product";
|
|
34
|
-
"shopify_storefront.collection": "shopify_storefront.collection";
|
|
35
|
-
"shopify_storefront.collection_products": "shopify_storefront.collection_products";
|
|
36
|
-
"replo_products.product": "replo_products.product";
|
|
37
|
-
"okendo.product_reviews": "okendo.product_reviews";
|
|
38
|
-
"okendo.product_review_aggregate": "okendo.product_review_aggregate";
|
|
39
|
-
"rebuy.recommendations": "rebuy.recommendations";
|
|
40
|
-
"levanta_products.product": "levanta_products.product";
|
|
41
|
-
"smile_io.vip_tiers": "smile_io.vip_tiers";
|
|
42
|
-
"smile_io.earning_rules": "smile_io.earning_rules";
|
|
43
|
-
"smile_io.rewards": "smile_io.rewards";
|
|
44
|
-
"yotpo.product_reviews": "yotpo.product_reviews";
|
|
45
|
-
"yotpo.product_review_aggregate": "yotpo.product_review_aggregate";
|
|
46
|
-
"statsig.experiment": "statsig.experiment";
|
|
47
|
-
"contentful.entry": "contentful.entry";
|
|
48
|
-
"contentful.entries": "contentful.entries";
|
|
49
|
-
}>;
|
package/loaders/loader-keys.js
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { z } from "zod";
|
|
2
1
|
const DATA_LOADER_KEYS = {
|
|
3
2
|
SHOPIFY_PRODUCT: "shopify_storefront.product",
|
|
4
3
|
SHOPIFY_COLLECTION: "shopify_storefront.collection",
|
|
@@ -17,9 +16,7 @@ const DATA_LOADER_KEYS = {
|
|
|
17
16
|
CONTENTFUL_ENTRY: "contentful.entry",
|
|
18
17
|
CONTENTFUL_ENTRIES: "contentful.entries"
|
|
19
18
|
};
|
|
20
|
-
const dataLoaderKeySchema = z.enum(Object.values(DATA_LOADER_KEYS));
|
|
21
19
|
export {
|
|
22
|
-
DATA_LOADER_KEYS
|
|
23
|
-
dataLoaderKeySchema
|
|
20
|
+
DATA_LOADER_KEYS
|
|
24
21
|
};
|
|
25
22
|
//# sourceMappingURL=loader-keys.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../loaders/loader-keys.ts"],
|
|
4
|
-
"sourcesContent": ["
|
|
5
|
-
"mappings": "
|
|
4
|
+
"sourcesContent": ["// NOTE (Ryan, 2026-07-23, REPL-27611): Canonical loader-key constants for the\n// published-page surface. canopy-sdk owns this copy so nothing shipped to a\n// generated site imports from `schemas`. The backend keeps its own copy in\n// `schemas/loaderKeys.ts` (consumed by the integration registry + tool\n// metadata, which cannot depend on canopy-sdk without a cycle); the two are\n// kept in lockstep by the drift guard in `loader-keys.spec.ts`.\n\n/**\n * Shared data-loader key constants. Loader components and prefetch queries\n * import from here so the strings are never duplicated across a generated site.\n *\n * These keys serve double duty: they identify which backend loader to invoke\n * AND are used as React Query cache key prefixes. Loader components internally\n * construct queryKey as `[loaderKey, args]`.\n *\n * Naming convention: `<integration>.<objectType>` or\n * `<integration>.<objectType>_<qualifier>`.\n */\nexport const DATA_LOADER_KEYS = {\n SHOPIFY_PRODUCT: \"shopify_storefront.product\",\n SHOPIFY_COLLECTION: \"shopify_storefront.collection\",\n SHOPIFY_COLLECTION_PRODUCTS: \"shopify_storefront.collection_products\",\n REPLO_PRODUCT: \"replo_products.product\",\n OKENDO_PRODUCT_REVIEWS: \"okendo.product_reviews\",\n OKENDO_PRODUCT_REVIEW_AGGREGATE: \"okendo.product_review_aggregate\",\n REBUY_RECOMMENDATIONS: \"rebuy.recommendations\",\n LEVANTA_PRODUCT: \"levanta_products.product\",\n SMILE_IO_VIP_TIERS: \"smile_io.vip_tiers\",\n SMILE_IO_EARNING_RULES: \"smile_io.earning_rules\",\n SMILE_IO_REWARDS: \"smile_io.rewards\",\n YOTPO_PRODUCT_REVIEWS: \"yotpo.product_reviews\",\n YOTPO_PRODUCT_REVIEW_AGGREGATE: \"yotpo.product_review_aggregate\",\n STATSIG_EXPERIMENT: \"statsig.experiment\",\n CONTENTFUL_ENTRY: \"contentful.entry\",\n CONTENTFUL_ENTRIES: \"contentful.entries\",\n} as const;\n\nexport type DataLoaderKey =\n (typeof DATA_LOADER_KEYS)[keyof typeof DATA_LOADER_KEYS];\n"],
|
|
5
|
+
"mappings": "AAkBO,MAAM,mBAAmB;AAAA,EAC9B,iBAAiB;AAAA,EACjB,oBAAoB;AAAA,EACpB,6BAA6B;AAAA,EAC7B,eAAe;AAAA,EACf,wBAAwB;AAAA,EACxB,iCAAiC;AAAA,EACjC,uBAAuB;AAAA,EACvB,iBAAiB;AAAA,EACjB,oBAAoB;AAAA,EACpB,wBAAwB;AAAA,EACxB,kBAAkB;AAAA,EAClB,uBAAuB;AAAA,EACvB,gCAAgC;AAAA,EAChC,oBAAoB;AAAA,EACpB,kBAAkB;AAAA,EAClB,oBAAoB;AACtB;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@replohq/canopy-sdk",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.4",
|
|
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,
|
|
@@ -21,7 +21,6 @@
|
|
|
21
21
|
"peerDependencies": {
|
|
22
22
|
"@opennextjs/cloudflare": ">=1.0.0",
|
|
23
23
|
"@tanstack/react-query": ">=5.0.0",
|
|
24
|
-
"@tanstack/react-query-next-experimental": ">=5.0.0",
|
|
25
24
|
"@types/react": ">=18.2.0",
|
|
26
25
|
"@types/react-dom": ">=18.2.0",
|
|
27
26
|
"next": ">=15.0.0",
|