@replohq/canopy-sdk 0.15.0 → 0.16.0-beta.pr-24057.1.3c7b61d
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/editor/select-mode/fiber.js +28 -5
- package/editor/select-mode/fiber.js.map +2 -2
- package/env.d.ts +0 -5
- package/env.js +15 -9
- package/env.js.map +2 -2
- package/loaders/collection-loader.js +2 -0
- package/loaders/collection-loader.js.map +2 -2
- package/loaders/collection-products-loader.js +2 -0
- package/loaders/collection-products-loader.js.map +2 -2
- package/loaders/invoke-loader-server.js +5 -0
- package/loaders/invoke-loader-server.js.map +2 -2
- package/loaders/invoke-loader.d.ts +3 -0
- package/loaders/invoke-loader.js +5 -0
- package/loaders/invoke-loader.js.map +2 -2
- package/loaders/preview-placeholder.d.ts +25 -0
- package/loaders/preview-placeholder.js +222 -0
- package/loaders/preview-placeholder.js.map +7 -0
- package/loaders/product-loader.js +2 -0
- package/loaders/product-loader.js.map +2 -2
- package/package.json +1 -5
|
@@ -17,6 +17,20 @@ function isReactInternalFrame(fileName) {
|
|
|
17
17
|
return pattern.test(fileName);
|
|
18
18
|
});
|
|
19
19
|
}
|
|
20
|
+
const REACT_INTERNAL_METHOD_PATTERNS = [
|
|
21
|
+
/(?:^|\.)jsxDEV(?:Impl)?$/,
|
|
22
|
+
/(?:^|\.)jsxs?$/,
|
|
23
|
+
/(?:^|\.)react_stack_bottom_frame$/,
|
|
24
|
+
/(?:^|\.)fakeJSXCallSite$/
|
|
25
|
+
];
|
|
26
|
+
function isReactInternalMethod(methodName) {
|
|
27
|
+
if (!methodName) {
|
|
28
|
+
return false;
|
|
29
|
+
}
|
|
30
|
+
return REACT_INTERNAL_METHOD_PATTERNS.some((pattern) => {
|
|
31
|
+
return pattern.test(methodName);
|
|
32
|
+
});
|
|
33
|
+
}
|
|
20
34
|
function parseDebugStackSource(debugStack) {
|
|
21
35
|
let stackText = null;
|
|
22
36
|
if (typeof debugStack === "string") {
|
|
@@ -35,17 +49,26 @@ function parseDebugStackSource(debugStack) {
|
|
|
35
49
|
if (!line) {
|
|
36
50
|
continue;
|
|
37
51
|
}
|
|
38
|
-
const
|
|
52
|
+
const framedMatch = line.match(/^at\s+(.+?)\s+\((.*):(\d+):(\d+)\)$/);
|
|
53
|
+
const stackFrameMatch = framedMatch ?? line.match(/^at\s+(?:.*\()?(.*):(\d+):(\d+)\)?$/) ?? line.match(/^(.*):(\d+):(\d+)$/);
|
|
39
54
|
if (!stackFrameMatch) {
|
|
40
55
|
continue;
|
|
41
56
|
}
|
|
42
|
-
const
|
|
43
|
-
const
|
|
44
|
-
const
|
|
57
|
+
const methodName = framedMatch ? framedMatch[1].trim() : null;
|
|
58
|
+
const fileOffset = framedMatch ? 2 : 1;
|
|
59
|
+
const fileName = stackFrameMatch[fileOffset]?.trim();
|
|
60
|
+
const lineNumber = Number.parseInt(
|
|
61
|
+
stackFrameMatch[fileOffset + 1] ?? "",
|
|
62
|
+
10
|
|
63
|
+
);
|
|
64
|
+
const columnNumber = Number.parseInt(
|
|
65
|
+
stackFrameMatch[fileOffset + 2] ?? "",
|
|
66
|
+
10
|
|
67
|
+
);
|
|
45
68
|
if (!fileName || !Number.isFinite(lineNumber) || !Number.isFinite(columnNumber)) {
|
|
46
69
|
continue;
|
|
47
70
|
}
|
|
48
|
-
if (isReactInternalFrame(fileName)) {
|
|
71
|
+
if (isReactInternalFrame(fileName) || isReactInternalMethod(methodName)) {
|
|
49
72
|
continue;
|
|
50
73
|
}
|
|
51
74
|
return {
|
|
@@ -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\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 const stackFrameMatch =\n line.match(/^at\\s+(?:.*\\()?(.*):(\\d+):(\\d+)\\)?$/) ??\n line.match(/^(.*):(\\d+):(\\d+)$/);\n\n if (!stackFrameMatch) {\n continue;\n }\n\n const fileName = stackFrameMatch[1]?.trim();\n const lineNumber = Number.parseInt(stackFrameMatch[2] ?? \"\", 10);\n const columnNumber = Number.parseInt(stackFrameMatch[3] ?? \"\", 10);\n\n if (\n !fileName ||\n !Number.isFinite(lineNumber) ||\n !Number.isFinite(columnNumber)\n ) {\n continue;\n }\n\n if (isReactInternalFrame(fileName)) {\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;AAmClB,MAAM,wBAAwB;AAC9B,MAAM,4BAA4B;AAClC,MAAM,+BAA+B;AAkBrC,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;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;AAAA,EACT;AAEA,aAAW,WAAW,UAAU,MAAM,IAAI,GAAG;AAC3C,UAAM,OAAO,QAAQ,KAAK;AAC1B,QAAI,CAAC,MAAM;AACT;AAAA,IACF;
|
|
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;AAmClB,MAAM,wBAAwB;AAC9B,MAAM,4BAA4B;AAClC,MAAM,+BAA+B;AAkBrC,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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,MAAM,iBAAiB,YAAY;AAC5C,iBAAS,eAAe,iBAAiB,MAAM,YAAY;AAAA,MAC7D;AACA,UAAI,OAAO,MAAM,YAAY,YAAY;AACvC,iBAAS,UAAU,iBAAiB,MAAM,OAAO;AAAA,MACnD;AACA,UAAI,OAAO,MAAM,WAAW,YAAY;AACtC,iBAAS,SAAS,iBAAiB,MAAM,MAAM;AAAA,MACjD;AAAA,IACF;AAAA,EACF;AAGA,MAAI,CAAC,SAAS,SAAS;AACrB,UAAM,eAAe,QAAQ,UAAU;AAAA,MACrC;AAAA,IACF;AACA,QAAI,eAAe,CAAC,GAAG;AACrB,eAAS,UAAU,aAAa,CAAC,EAAE,KAAK;AAAA,IAC1C;AAAA,EACF;AAEA,SAAO;AACT;AAOO,SAAS,iBAAiB,IAAqB;AACpD,MAAI,OAAO,OAAO,YAAY;AAC5B,WAAO;AAAA,EACT;AAGA,QAAM,SAAS,GAAG,SAAS;AAG3B,MAAI,OAAO,WAAW,GAAG,KAAK,OAAO,WAAW,UAAU,GAAG;AAE3D,UAAM,aAAa,OAAO,MAAM,yBAAyB;AACzD,QAAI,YAAY;AACd,aAAO,WAAW,CAAC,EAAG,KAAK;AAAA,IAC7B;AAGA,UAAM,uBAAuB,OAAO,MAAM,8BAA8B;AACxE,QAAI,sBAAsB;AACxB,aAAO,qBAAqB,CAAC,EAAG,KAAK;AAAA,IACvC;AAAA,EACF;AAGA,MAAI,OAAO,SAAS,KAAK;AACvB,WAAO,GAAG,OAAO,MAAM,GAAG,GAAG,CAAC;AAAA,EAChC;AAEA,SAAO;AACT;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/env.d.ts
CHANGED
|
@@ -11,10 +11,5 @@ type Env = {
|
|
|
11
11
|
/** Shared secret sent in X-Replo-Resolver-Auth for server-to-server cart calls. */
|
|
12
12
|
CART_AUTH_SECRET?: string;
|
|
13
13
|
};
|
|
14
|
-
declare const fetchCloudflareContext: () => Promise<import("@opennextjs/cloudflare").CloudflareContext<IncomingRequestCfProperties, ExecutionContext>>;
|
|
15
|
-
type CloudflareContextPromise = ReturnType<typeof fetchCloudflareContext>;
|
|
16
|
-
declare global {
|
|
17
|
-
var canopyCloudflareContextPromise: CloudflareContextPromise | undefined;
|
|
18
|
-
}
|
|
19
14
|
export declare const getEnv: () => Promise<Env>;
|
|
20
15
|
export {};
|
package/env.js
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
|
+
import { promises as fs } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
1
3
|
import { getCloudflareContext } from "@opennextjs/cloudflare";
|
|
4
|
+
import JSONC from "tiny-jsonc";
|
|
2
5
|
import { z } from "zod";
|
|
3
6
|
const envSchema = z.object({
|
|
4
7
|
CANOPY_API_HOST: z.string().min(1),
|
|
@@ -12,17 +15,20 @@ const envSchema = z.object({
|
|
|
12
15
|
REPLO_INTERNAL_REVALIDATE_SECRET: z.string().optional(),
|
|
13
16
|
CART_AUTH_SECRET: z.string().optional()
|
|
14
17
|
});
|
|
15
|
-
const
|
|
16
|
-
const
|
|
17
|
-
|
|
18
|
-
return globalThis.canopyCloudflareContextPromise ??= fetchCloudflareContext().catch((error) => {
|
|
19
|
-
globalThis.canopyCloudflareContextPromise = void 0;
|
|
20
|
-
throw error;
|
|
21
|
-
});
|
|
18
|
+
const wranglerConfigSchema = z.object({ vars: envSchema });
|
|
19
|
+
const isDeployedWorker = () => {
|
|
20
|
+
return process.env.NODE_ENV === "production" && process.env.BUILD_ENV !== "build" && process.env.NEXT_PHASE !== "phase-production-build";
|
|
22
21
|
};
|
|
23
22
|
const getEnv = async () => {
|
|
24
|
-
|
|
25
|
-
|
|
23
|
+
if (isDeployedWorker()) {
|
|
24
|
+
const { env } = await getCloudflareContext({ async: true });
|
|
25
|
+
return envSchema.parse(env);
|
|
26
|
+
}
|
|
27
|
+
const raw = await fs.readFile(
|
|
28
|
+
path.join(process.cwd(), "wrangler.jsonc"),
|
|
29
|
+
"utf8"
|
|
30
|
+
);
|
|
31
|
+
return wranglerConfigSchema.parse(JSONC.parse(raw)).vars;
|
|
26
32
|
};
|
|
27
33
|
export {
|
|
28
34
|
getEnv
|
package/env.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../env.ts"],
|
|
4
|
-
"sourcesContent": ["import { getCloudflareContext } from \"@opennextjs/cloudflare\";\nimport { z } from \"zod\";\n\ntype Env = {\n CANOPY_API_HOST: string;\n PROJECT_ID: string;\n\n // 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 // NOTE (Gabe 2025-06-26): If there's no Shopify integration these will be\n // undefined.\n SHOPIFY_URL?: string;\n // NOTE (Gabe 2025-06-26): Even if there's an integration, if we haven't been\n // given elevated scope this may be null.\n SHOPIFY_STOREFRONT_ACCESS_TOKEN?: string | null;\n STRIPE_CONNECT_ACCOUNT_ID?: string | null;\n CHECKOUT_PROVIDER?: \"shopify\" | \"stripe\" | \"none\";\n\n REPLO_INTERNAL_REVALIDATE_SECRET?: string;\n /** Shared secret sent in X-Replo-Resolver-Auth for server-to-server cart calls. */\n CART_AUTH_SECRET?: string;\n};\n\nconst envSchema = z.object({\n CANOPY_API_HOST: z.string().min(1),\n PROJECT_ID: z.uuid(),\n ANALYTICS_FIRE_API_URL: z.string().optional(),\n REPLO_ANALYTICS_PIXEL_URL: z.string().optional(),\n SHOPIFY_URL: z.string().optional(),\n SHOPIFY_STOREFRONT_ACCESS_TOKEN: z.string().nullish(),\n STRIPE_CONNECT_ACCOUNT_ID: z.string().nullish(),\n CHECKOUT_PROVIDER: z.enum([\"shopify\", \"stripe\", \"none\"]).optional(),\n REPLO_INTERNAL_REVALIDATE_SECRET: z.string().optional(),\n CART_AUTH_SECRET: z.string().optional(),\n});\n\nconst
|
|
5
|
-
"mappings": "AAAA,SAAS,4BAA4B;AACrC,SAAS,SAAS;AAiClB,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,aAAa,EAAE,OAAO,EAAE,SAAS;AAAA,EACjC,iCAAiC,EAAE,OAAO,EAAE,QAAQ;AAAA,EACpD,2BAA2B,EAAE,OAAO,EAAE,QAAQ;AAAA,EAC9C,mBAAmB,EAAE,KAAK,CAAC,WAAW,UAAU,MAAM,CAAC,EAAE,SAAS;AAAA,EAClE,kCAAkC,EAAE,OAAO,EAAE,SAAS;AAAA,EACtD,kBAAkB,EAAE,OAAO,EAAE,SAAS;AACxC,CAAC;AAED,MAAM,
|
|
4
|
+
"sourcesContent": ["import { promises as fs } from \"node:fs\";\nimport path from \"node:path\";\n\nimport { 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 // NOTE (Gabe 2025-06-26): If there's no Shopify integration these will be\n // undefined.\n SHOPIFY_URL?: string;\n // NOTE (Gabe 2025-06-26): Even if there's an integration, if we haven't been\n // given elevated scope this may be null.\n SHOPIFY_STOREFRONT_ACCESS_TOKEN?: string | null;\n STRIPE_CONNECT_ACCOUNT_ID?: string | null;\n CHECKOUT_PROVIDER?: \"shopify\" | \"stripe\" | \"none\";\n\n REPLO_INTERNAL_REVALIDATE_SECRET?: string;\n /** Shared secret sent in X-Replo-Resolver-Auth for server-to-server cart calls. */\n CART_AUTH_SECRET?: string;\n};\n\nconst envSchema = z.object({\n CANOPY_API_HOST: z.string().min(1),\n PROJECT_ID: z.uuid(),\n ANALYTICS_FIRE_API_URL: z.string().optional(),\n REPLO_ANALYTICS_PIXEL_URL: z.string().optional(),\n SHOPIFY_URL: z.string().optional(),\n SHOPIFY_STOREFRONT_ACCESS_TOKEN: z.string().nullish(),\n STRIPE_CONNECT_ACCOUNT_ID: z.string().nullish(),\n CHECKOUT_PROVIDER: z.enum([\"shopify\", \"stripe\", \"none\"]).optional(),\n REPLO_INTERNAL_REVALIDATE_SECRET: z.string().optional(),\n CART_AUTH_SECRET: z.string().optional(),\n});\n\nconst wranglerConfigSchema = z.object({ vars: envSchema });\n\n// NOTE (Cole, 2026-07-28, REPL-29501): SSR and prerender read wrangler.jsonc\n// directly because concurrent workerd instances race on shared SQLite state. Only\n// a deployed worker uses its runtime-injected Cloudflare context.\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 const raw = await fs.readFile(\n path.join(process.cwd(), \"wrangler.jsonc\"),\n \"utf8\",\n );\n return wranglerConfigSchema.parse(JSONC.parse(raw)).vars;\n};\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,YAAY,UAAU;AAC/B,OAAO,UAAU;AAEjB,SAAS,4BAA4B;AACrC,OAAO,WAAW;AAClB,SAAS,SAAS;AAiClB,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,aAAa,EAAE,OAAO,EAAE,SAAS;AAAA,EACjC,iCAAiC,EAAE,OAAO,EAAE,QAAQ;AAAA,EACpD,2BAA2B,EAAE,OAAO,EAAE,QAAQ;AAAA,EAC9C,mBAAmB,EAAE,KAAK,CAAC,WAAW,UAAU,MAAM,CAAC,EAAE,SAAS;AAAA,EAClE,kCAAkC,EAAE,OAAO,EAAE,SAAS;AAAA,EACtD,kBAAkB,EAAE,OAAO,EAAE,SAAS;AACxC,CAAC;AAED,MAAM,uBAAuB,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC;AAKzD,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;AACA,QAAM,MAAM,MAAM,GAAG;AAAA,IACnB,KAAK,KAAK,QAAQ,IAAI,GAAG,gBAAgB;AAAA,IACzC;AAAA,EACF;AACA,SAAO,qBAAqB,MAAM,MAAM,MAAM,GAAG,CAAC,EAAE;AACtD;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -5,6 +5,7 @@ import { useSuspenseQuery } from "@tanstack/react-query";
|
|
|
5
5
|
import { invokeLoader } from "./invoke-loader";
|
|
6
6
|
import { LoaderErrorBoundary } from "./loader-error-boundary";
|
|
7
7
|
import { fullCollectionSchema } from "./loader-schemas";
|
|
8
|
+
import { useReportPreviewPlaceholderRender } from "./preview-placeholder";
|
|
8
9
|
function CollectionLoaderInner({
|
|
9
10
|
loaderKey,
|
|
10
11
|
handle,
|
|
@@ -21,6 +22,7 @@ function CollectionLoaderInner({
|
|
|
21
22
|
return fullCollectionSchema.parse(loadedData);
|
|
22
23
|
}
|
|
23
24
|
});
|
|
25
|
+
useReportPreviewPlaceholderRender(queryResult.data);
|
|
24
26
|
return /* @__PURE__ */ jsx(Fragment, { children: children(queryResult.data) });
|
|
25
27
|
}
|
|
26
28
|
function CollectionLoader({
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../loaders/collection-loader.tsx"],
|
|
4
|
-
"sourcesContent": ["\"use client\";\n\nimport type { ReactNode } from \"react\";\nimport type { FullCollection } from \"./loader-schemas\";\n\nimport { Suspense } from \"react\";\n\nimport { useSuspenseQuery } from \"@tanstack/react-query\";\n\nimport { invokeLoader } from \"./invoke-loader\";\nimport { LoaderErrorBoundary } from \"./loader-error-boundary\";\nimport { fullCollectionSchema } from \"./loader-schemas\";\n\ntype CollectionLoaderProps = {\n loaderKey: string;\n handle?: string;\n collectionGid?: string;\n children: (data: FullCollection) => ReactNode;\n fallback?: ReactNode;\n};\n\nfunction CollectionLoaderInner({\n loaderKey,\n handle,\n collectionGid,\n children,\n}: Omit<CollectionLoaderProps, \"fallback\">) {\n const queryResult = useSuspenseQuery({\n queryKey: [loaderKey, { handle, collectionGid }],\n queryFn: async () => {\n const loadedData = await invokeLoader({\n loaderKey,\n args: { handle, collectionGid },\n });\n return fullCollectionSchema.parse(loadedData);\n },\n });\n\n return <>{children(queryResult.data)}</>;\n}\n\nexport function CollectionLoader({\n loaderKey,\n handle,\n collectionGid,\n children,\n fallback,\n}: CollectionLoaderProps) {\n return (\n <LoaderErrorBoundary\n fallback={fallback ?? null}\n resetKey={`${loaderKey}:${handle ?? \"\"}:${collectionGid ?? \"\"}`}\n >\n <Suspense fallback={fallback ?? null}>\n <CollectionLoaderInner\n loaderKey={loaderKey}\n handle={handle}\n collectionGid={collectionGid}\n >\n {children}\n </CollectionLoaderInner>\n </Suspense>\n </LoaderErrorBoundary>\n );\n}\n"],
|
|
5
|
-
"mappings": ";
|
|
4
|
+
"sourcesContent": ["\"use client\";\n\nimport type { ReactNode } from \"react\";\nimport type { FullCollection } from \"./loader-schemas\";\n\nimport { Suspense } from \"react\";\n\nimport { useSuspenseQuery } from \"@tanstack/react-query\";\n\nimport { invokeLoader } from \"./invoke-loader\";\nimport { LoaderErrorBoundary } from \"./loader-error-boundary\";\nimport { fullCollectionSchema } from \"./loader-schemas\";\nimport { useReportPreviewPlaceholderRender } from \"./preview-placeholder\";\n\ntype CollectionLoaderProps = {\n loaderKey: string;\n handle?: string;\n collectionGid?: string;\n children: (data: FullCollection) => ReactNode;\n fallback?: ReactNode;\n};\n\nfunction CollectionLoaderInner({\n loaderKey,\n handle,\n collectionGid,\n children,\n}: Omit<CollectionLoaderProps, \"fallback\">) {\n const queryResult = useSuspenseQuery({\n queryKey: [loaderKey, { handle, collectionGid }],\n queryFn: async () => {\n const loadedData = await invokeLoader({\n loaderKey,\n args: { handle, collectionGid },\n });\n return fullCollectionSchema.parse(loadedData);\n },\n });\n useReportPreviewPlaceholderRender(queryResult.data);\n\n return <>{children(queryResult.data)}</>;\n}\n\nexport function CollectionLoader({\n loaderKey,\n handle,\n collectionGid,\n children,\n fallback,\n}: CollectionLoaderProps) {\n return (\n <LoaderErrorBoundary\n fallback={fallback ?? null}\n resetKey={`${loaderKey}:${handle ?? \"\"}:${collectionGid ?? \"\"}`}\n >\n <Suspense fallback={fallback ?? null}>\n <CollectionLoaderInner\n loaderKey={loaderKey}\n handle={handle}\n collectionGid={collectionGid}\n >\n {children}\n </CollectionLoaderInner>\n </Suspense>\n </LoaderErrorBoundary>\n );\n}\n"],
|
|
5
|
+
"mappings": ";AAwCS;AAnCT,SAAS,gBAAgB;AAEzB,SAAS,wBAAwB;AAEjC,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B;AACpC,SAAS,4BAA4B;AACrC,SAAS,yCAAyC;AAUlD,SAAS,sBAAsB;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAA4C;AAC1C,QAAM,cAAc,iBAAiB;AAAA,IACnC,UAAU,CAAC,WAAW,EAAE,QAAQ,cAAc,CAAC;AAAA,IAC/C,SAAS,YAAY;AACnB,YAAM,aAAa,MAAM,aAAa;AAAA,QACpC;AAAA,QACA,MAAM,EAAE,QAAQ,cAAc;AAAA,MAChC,CAAC;AACD,aAAO,qBAAqB,MAAM,UAAU;AAAA,IAC9C;AAAA,EACF,CAAC;AACD,oCAAkC,YAAY,IAAI;AAElD,SAAO,gCAAG,mBAAS,YAAY,IAAI,GAAE;AACvC;AAEO,SAAS,iBAAiB;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAA0B;AACxB,SACE;AAAA,IAAC;AAAA;AAAA,MACC,UAAU,YAAY;AAAA,MACtB,UAAU,GAAG,SAAS,IAAI,UAAU,EAAE,IAAI,iBAAiB,EAAE;AAAA,MAE7D,8BAAC,YAAS,UAAU,YAAY,MAC9B;AAAA,QAAC;AAAA;AAAA,UACC;AAAA,UACA;AAAA,UACA;AAAA,UAEC;AAAA;AAAA,MACH,GACF;AAAA;AAAA,EACF;AAEJ;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -5,6 +5,7 @@ import { useSuspenseQuery } from "@tanstack/react-query";
|
|
|
5
5
|
import { invokeLoader } from "./invoke-loader";
|
|
6
6
|
import { LoaderErrorBoundary } from "./loader-error-boundary";
|
|
7
7
|
import { paginatedProductsSchema } from "./loader-schemas";
|
|
8
|
+
import { useReportPreviewPlaceholderRender } from "./preview-placeholder";
|
|
8
9
|
function CollectionProductsLoaderInner({
|
|
9
10
|
loaderKey,
|
|
10
11
|
collectionGid,
|
|
@@ -22,6 +23,7 @@ function CollectionProductsLoaderInner({
|
|
|
22
23
|
return paginatedProductsSchema.parse(loadedData);
|
|
23
24
|
}
|
|
24
25
|
});
|
|
26
|
+
useReportPreviewPlaceholderRender(queryResult.data);
|
|
25
27
|
return /* @__PURE__ */ jsx(Fragment, { children: children(queryResult.data) });
|
|
26
28
|
}
|
|
27
29
|
function CollectionProductsLoader({
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../loaders/collection-products-loader.tsx"],
|
|
4
|
-
"sourcesContent": ["\"use client\";\n\nimport type { ReactNode } from \"react\";\nimport type { PaginatedProducts } from \"./loader-schemas\";\n\nimport { Suspense } from \"react\";\n\nimport { useSuspenseQuery } from \"@tanstack/react-query\";\n\nimport { invokeLoader } from \"./invoke-loader\";\nimport { LoaderErrorBoundary } from \"./loader-error-boundary\";\nimport { paginatedProductsSchema } from \"./loader-schemas\";\n\ntype CollectionProductsLoaderProps = {\n loaderKey: string;\n collectionGid: string;\n first?: number;\n after?: string;\n children: (data: PaginatedProducts) => ReactNode;\n fallback?: ReactNode;\n};\n\nfunction CollectionProductsLoaderInner({\n loaderKey,\n collectionGid,\n first,\n after,\n children,\n}: Omit<CollectionProductsLoaderProps, \"fallback\">) {\n const queryResult = useSuspenseQuery({\n queryKey: [loaderKey, { collectionGid, first, after }],\n queryFn: async () => {\n const loadedData = await invokeLoader({\n loaderKey,\n args: { collectionGid, first, after },\n });\n return paginatedProductsSchema.parse(loadedData);\n },\n });\n\n return <>{children(queryResult.data)}</>;\n}\n\nexport function CollectionProductsLoader({\n loaderKey,\n collectionGid,\n first,\n after,\n children,\n fallback,\n}: CollectionProductsLoaderProps) {\n return (\n <LoaderErrorBoundary\n fallback={fallback ?? null}\n resetKey={`${loaderKey}:${collectionGid}:${first ?? \"\"}:${after ?? \"\"}`}\n >\n <Suspense fallback={fallback ?? null}>\n <CollectionProductsLoaderInner\n loaderKey={loaderKey}\n collectionGid={collectionGid}\n first={first}\n after={after}\n >\n {children}\n </CollectionProductsLoaderInner>\n </Suspense>\n </LoaderErrorBoundary>\n );\n}\n"],
|
|
5
|
-
"mappings": ";
|
|
4
|
+
"sourcesContent": ["\"use client\";\n\nimport type { ReactNode } from \"react\";\nimport type { PaginatedProducts } from \"./loader-schemas\";\n\nimport { Suspense } from \"react\";\n\nimport { useSuspenseQuery } from \"@tanstack/react-query\";\n\nimport { invokeLoader } from \"./invoke-loader\";\nimport { LoaderErrorBoundary } from \"./loader-error-boundary\";\nimport { paginatedProductsSchema } from \"./loader-schemas\";\nimport { useReportPreviewPlaceholderRender } from \"./preview-placeholder\";\n\ntype CollectionProductsLoaderProps = {\n loaderKey: string;\n collectionGid: string;\n first?: number;\n after?: string;\n children: (data: PaginatedProducts) => ReactNode;\n fallback?: ReactNode;\n};\n\nfunction CollectionProductsLoaderInner({\n loaderKey,\n collectionGid,\n first,\n after,\n children,\n}: Omit<CollectionProductsLoaderProps, \"fallback\">) {\n const queryResult = useSuspenseQuery({\n queryKey: [loaderKey, { collectionGid, first, after }],\n queryFn: async () => {\n const loadedData = await invokeLoader({\n loaderKey,\n args: { collectionGid, first, after },\n });\n return paginatedProductsSchema.parse(loadedData);\n },\n });\n useReportPreviewPlaceholderRender(queryResult.data);\n\n return <>{children(queryResult.data)}</>;\n}\n\nexport function CollectionProductsLoader({\n loaderKey,\n collectionGid,\n first,\n after,\n children,\n fallback,\n}: CollectionProductsLoaderProps) {\n return (\n <LoaderErrorBoundary\n fallback={fallback ?? null}\n resetKey={`${loaderKey}:${collectionGid}:${first ?? \"\"}:${after ?? \"\"}`}\n >\n <Suspense fallback={fallback ?? null}>\n <CollectionProductsLoaderInner\n loaderKey={loaderKey}\n collectionGid={collectionGid}\n first={first}\n after={after}\n >\n {children}\n </CollectionProductsLoaderInner>\n </Suspense>\n </LoaderErrorBoundary>\n );\n}\n"],
|
|
5
|
+
"mappings": ";AA0CS;AArCT,SAAS,gBAAgB;AAEzB,SAAS,wBAAwB;AAEjC,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B;AACpC,SAAS,+BAA+B;AACxC,SAAS,yCAAyC;AAWlD,SAAS,8BAA8B;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAAoD;AAClD,QAAM,cAAc,iBAAiB;AAAA,IACnC,UAAU,CAAC,WAAW,EAAE,eAAe,OAAO,MAAM,CAAC;AAAA,IACrD,SAAS,YAAY;AACnB,YAAM,aAAa,MAAM,aAAa;AAAA,QACpC;AAAA,QACA,MAAM,EAAE,eAAe,OAAO,MAAM;AAAA,MACtC,CAAC;AACD,aAAO,wBAAwB,MAAM,UAAU;AAAA,IACjD;AAAA,EACF,CAAC;AACD,oCAAkC,YAAY,IAAI;AAElD,SAAO,gCAAG,mBAAS,YAAY,IAAI,GAAE;AACvC;AAEO,SAAS,yBAAyB;AAAA,EACvC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAAkC;AAChC,SACE;AAAA,IAAC;AAAA;AAAA,MACC,UAAU,YAAY;AAAA,MACtB,UAAU,GAAG,SAAS,IAAI,aAAa,IAAI,SAAS,EAAE,IAAI,SAAS,EAAE;AAAA,MAErE,8BAAC,YAAS,UAAU,YAAY,MAC9B;AAAA,QAAC;AAAA;AAAA,UACC;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UAEC;AAAA;AAAA,MACH,GACF;AAAA;AAAA,EACF;AAEJ;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { unstable_cache } from "next/cache";
|
|
2
2
|
import { getCanopyApiGateway } from "../gateways/canopy-api";
|
|
3
|
+
import { resolvePreviewPlaceholderData } from "./preview-placeholder";
|
|
3
4
|
const DEFAULT_REVALIDATE_SECONDS = 60;
|
|
4
5
|
function buildStableCacheKeyParts({
|
|
5
6
|
loaderKey,
|
|
@@ -15,6 +16,10 @@ async function invokeLoaderServer({
|
|
|
15
16
|
args,
|
|
16
17
|
revalidateSeconds = DEFAULT_REVALIDATE_SECONDS
|
|
17
18
|
}) {
|
|
19
|
+
const placeholderData = resolvePreviewPlaceholderData({ loaderKey, args });
|
|
20
|
+
if (placeholderData !== null) {
|
|
21
|
+
return placeholderData;
|
|
22
|
+
}
|
|
18
23
|
const cacheKeyParts = buildStableCacheKeyParts({ loaderKey, args });
|
|
19
24
|
return unstable_cache(
|
|
20
25
|
async () => {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../loaders/invoke-loader-server.ts"],
|
|
4
|
-
"sourcesContent": ["import { unstable_cache } from \"next/cache\";\n\nimport { getCanopyApiGateway } from \"../gateways/canopy-api\";\n\nconst DEFAULT_REVALIDATE_SECONDS = 60;\n\nfunction buildStableCacheKeyParts({\n loaderKey,\n args,\n}: {\n loaderKey: string;\n args: Record<string, unknown>;\n}): string[] {\n const sortedArgsJson = JSON.stringify(\n Object.entries(args)\n .sort(([keyA], [keyB]) => keyA.localeCompare(keyB))\n .map(([key, value]) => [key, value]),\n );\n return [\"loader\", loaderKey, sortedArgsJson];\n}\n\n/**\n * Server-only loader invocation that calls the canopy-api gateway directly.\n * Used by PrefetchedLoaders to seed the React Query cache during SSR.\n *\n * Results are cached via Next.js `unstable_cache` so repeated SSR renders\n * for the same loader+args return instantly without a network round-trip\n * to canopy-api. The canopy-api's own in-memory cache still acts as a second\n * layer for cold starts and cross-instance sharing.\n *\n * @param revalidateSeconds - How long (in seconds) the cached result is\n * considered fresh. Defaults to 60. Set to `false` to cache indefinitely\n * (use tag-based invalidation via `revalidateTag` to purge).\n */\nexport async function invokeLoaderServer({\n loaderKey,\n args,\n revalidateSeconds = DEFAULT_REVALIDATE_SECONDS,\n}: {\n loaderKey: string;\n args: Record<string, unknown>;\n revalidateSeconds?: number | false;\n}) {\n const cacheKeyParts = buildStableCacheKeyParts({ loaderKey, args });\n\n return unstable_cache(\n async () => {\n const gateway = await getCanopyApiGateway();\n const response = await gateway.invokeLoader({ loaderKey, args });\n return response.data;\n },\n cacheKeyParts,\n {\n revalidate: revalidateSeconds,\n tags: [`loader:${loaderKey}`, ...cacheKeyParts],\n },\n )();\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,sBAAsB;AAE/B,SAAS,2BAA2B;
|
|
4
|
+
"sourcesContent": ["import { unstable_cache } from \"next/cache\";\n\nimport { getCanopyApiGateway } from \"../gateways/canopy-api\";\nimport { resolvePreviewPlaceholderData } from \"./preview-placeholder\";\n\nconst DEFAULT_REVALIDATE_SECONDS = 60;\n\nfunction buildStableCacheKeyParts({\n loaderKey,\n args,\n}: {\n loaderKey: string;\n args: Record<string, unknown>;\n}): string[] {\n const sortedArgsJson = JSON.stringify(\n Object.entries(args)\n .sort(([keyA], [keyB]) => keyA.localeCompare(keyB))\n .map(([key, value]) => [key, value]),\n );\n return [\"loader\", loaderKey, sortedArgsJson];\n}\n\n/**\n * Server-only loader invocation that calls the canopy-api gateway directly.\n * Used by PrefetchedLoaders to seed the React Query cache during SSR.\n *\n * Results are cached via Next.js `unstable_cache` so repeated SSR renders\n * for the same loader+args return instantly without a network round-trip\n * to canopy-api. The canopy-api's own in-memory cache still acts as a second\n * layer for cold starts and cross-instance sharing.\n *\n * @param revalidateSeconds - How long (in seconds) the cached result is\n * considered fresh. Defaults to 60. Set to `false` to cache indefinitely\n * (use tag-based invalidation via `revalidateTag` to purge).\n */\nexport async function invokeLoaderServer({\n loaderKey,\n args,\n revalidateSeconds = DEFAULT_REVALIDATE_SECONDS,\n}: {\n loaderKey: string;\n args: Record<string, unknown>;\n revalidateSeconds?: number | false;\n}) {\n // Dev-server previews of an unfilled dynamic route prefetch sample data\n // instead of fetching \u2014 a real fetch with the literal bracket param can only\n // 404, and the thrown error marks the whole preview frame as broken. Kept\n // outside unstable_cache so sample data never enters the loader cache.\n const placeholderData = resolvePreviewPlaceholderData({ loaderKey, args });\n if (placeholderData !== null) {\n return placeholderData;\n }\n const cacheKeyParts = buildStableCacheKeyParts({ loaderKey, args });\n\n return unstable_cache(\n async () => {\n const gateway = await getCanopyApiGateway();\n const response = await gateway.invokeLoader({ loaderKey, args });\n return response.data;\n },\n cacheKeyParts,\n {\n revalidate: revalidateSeconds,\n tags: [`loader:${loaderKey}`, ...cacheKeyParts],\n },\n )();\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,sBAAsB;AAE/B,SAAS,2BAA2B;AACpC,SAAS,qCAAqC;AAE9C,MAAM,6BAA6B;AAEnC,SAAS,yBAAyB;AAAA,EAChC;AAAA,EACA;AACF,GAGa;AACX,QAAM,iBAAiB,KAAK;AAAA,IAC1B,OAAO,QAAQ,IAAI,EAChB,KAAK,CAAC,CAAC,IAAI,GAAG,CAAC,IAAI,MAAM,KAAK,cAAc,IAAI,CAAC,EACjD,IAAI,CAAC,CAAC,KAAK,KAAK,MAAM,CAAC,KAAK,KAAK,CAAC;AAAA,EACvC;AACA,SAAO,CAAC,UAAU,WAAW,cAAc;AAC7C;AAeA,eAAsB,mBAAmB;AAAA,EACvC;AAAA,EACA;AAAA,EACA,oBAAoB;AACtB,GAIG;AAKD,QAAM,kBAAkB,8BAA8B,EAAE,WAAW,KAAK,CAAC;AACzE,MAAI,oBAAoB,MAAM;AAC5B,WAAO;AAAA,EACT;AACA,QAAM,gBAAgB,yBAAyB,EAAE,WAAW,KAAK,CAAC;AAElE,SAAO;AAAA,IACL,YAAY;AACV,YAAM,UAAU,MAAM,oBAAoB;AAC1C,YAAM,WAAW,MAAM,QAAQ,aAAa,EAAE,WAAW,KAAK,CAAC;AAC/D,aAAO,SAAS;AAAA,IAClB;AAAA,IACA;AAAA,IACA;AAAA,MACE,YAAY;AAAA,MACZ,MAAM,CAAC,UAAU,SAAS,IAAI,GAAG,aAAa;AAAA,IAChD;AAAA,EACF,EAAE;AACJ;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -7,6 +7,9 @@ export declare function isLoaderInvokeError(error: unknown): error is LoaderInvo
|
|
|
7
7
|
* Invokes a data loader. During SSR, calls the canopy-api gateway directly.
|
|
8
8
|
* In the browser, dynamically imports a server action so React 19 never sees
|
|
9
9
|
* the "use server" reference during render.
|
|
10
|
+
*
|
|
11
|
+
* In an editor iframe previewing an unfilled dynamic route, returns sample
|
|
12
|
+
* data instead of fetching — see `preview-placeholder.ts`.
|
|
10
13
|
*/
|
|
11
14
|
export declare function invokeLoader({ loaderKey, args, }: {
|
|
12
15
|
loaderKey: string;
|
package/loaders/invoke-loader.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { CanopyError } from "../lib/canopy-error";
|
|
2
|
+
import { resolvePreviewPlaceholderData } from "./preview-placeholder";
|
|
2
3
|
class LoaderInvokeError extends CanopyError {
|
|
3
4
|
}
|
|
4
5
|
function isLoaderInvokeError(error) {
|
|
@@ -8,6 +9,10 @@ async function invokeLoader({
|
|
|
8
9
|
loaderKey,
|
|
9
10
|
args
|
|
10
11
|
}) {
|
|
12
|
+
const placeholderData = resolvePreviewPlaceholderData({ loaderKey, args });
|
|
13
|
+
if (placeholderData !== null) {
|
|
14
|
+
return placeholderData;
|
|
15
|
+
}
|
|
11
16
|
try {
|
|
12
17
|
if (typeof window === "undefined") {
|
|
13
18
|
const { getCanopyApiGateway } = await import("../gateways/canopy-api");
|
|
@@ -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\";\n\n/** Scoped error for loader invocation failures. */\nexport class LoaderInvokeError extends CanopyError {}\n\nexport function isLoaderInvokeError(\n error: unknown,\n): error is LoaderInvokeError {\n return error instanceof LoaderInvokeError;\n}\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 */\nexport async function invokeLoader({\n loaderKey,\n args,\n}: {\n loaderKey: string;\n args: Record<string, unknown>;\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;
|
|
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\nexport function isLoaderInvokeError(\n error: unknown,\n): error is LoaderInvokeError {\n return error instanceof LoaderInvokeError;\n}\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;AAE7C,SAAS,oBACd,OAC4B;AAC5B,SAAO,iBAAiB;AAC1B;AAUA,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
|
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export declare function hasUnfilledRouteParam(args: Record<string, unknown>): boolean;
|
|
2
|
+
/**
|
|
3
|
+
* Sample data for a loader invoked with an unfilled dynamic-route param, or
|
|
4
|
+
* null when the invocation should proceed normally.
|
|
5
|
+
*
|
|
6
|
+
* On the server, substitution happens only on dev servers (`next dev` — how
|
|
7
|
+
* every sandbox preview runs); production builds keep fetching so bracket
|
|
8
|
+
* URLs keep their real miss/404 semantics. Substituting during SSR keeps the
|
|
9
|
+
* doomed fetch from erroring the dev overlay mid-stream. In the browser,
|
|
10
|
+
* substitution happens only inside an editor iframe.
|
|
11
|
+
*/
|
|
12
|
+
export declare function resolvePreviewPlaceholderData({ loaderKey, args, }: {
|
|
13
|
+
loaderKey: string;
|
|
14
|
+
args: Record<string, unknown>;
|
|
15
|
+
}): unknown;
|
|
16
|
+
/** Whether loader output is one of this module's sample fixtures. */
|
|
17
|
+
export declare function isPreviewPlaceholderData(data: unknown): boolean;
|
|
18
|
+
/**
|
|
19
|
+
* Notify the embedding editor when a loader component rendered sample data.
|
|
20
|
+
* The single reporting path: inspecting rendered data (rather than hooking
|
|
21
|
+
* loader invocation) covers client fetches and SSR-hydrated data alike —
|
|
22
|
+
* hydration never re-invokes the loader on the client. Receivers treat the
|
|
23
|
+
* message as idempotent, so no dedupe is needed.
|
|
24
|
+
*/
|
|
25
|
+
export declare function useReportPreviewPlaceholderRender(data: unknown): void;
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
import { useEffect } from "react";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { DATA_LOADER_KEYS } from "./loader-keys";
|
|
4
|
+
const PLACEHOLDER_RENDER_MESSAGE_TYPE = "replo:preview:placeholder-render";
|
|
5
|
+
const UNFILLED_ROUTE_PARAM_RE = /^\[{1,2}(?:\.\.\.)?[^\]]+\]{1,2}$/;
|
|
6
|
+
const SAMPLE_ID_PREFIX = "replo-sample-";
|
|
7
|
+
const SAMPLE_SIZES = [
|
|
8
|
+
{ value: "Small", priceAmount: "42.00" },
|
|
9
|
+
{ value: "Medium", priceAmount: "46.00" },
|
|
10
|
+
{ value: "Large", priceAmount: "50.00" }
|
|
11
|
+
];
|
|
12
|
+
const SAMPLE_COLORS = [
|
|
13
|
+
{ value: "Slate", swatchColor: "#64748b" },
|
|
14
|
+
{ value: "Sand", swatchColor: "#d6bc8a" }
|
|
15
|
+
];
|
|
16
|
+
const SOLD_OUT_COMBINATION = { size: "Large", color: "Sand" };
|
|
17
|
+
function toSampleSlug(value) {
|
|
18
|
+
return value.toLowerCase().replace(/\s+/g, "-");
|
|
19
|
+
}
|
|
20
|
+
const SAMPLE_VARIANTS = SAMPLE_SIZES.flatMap(
|
|
21
|
+
(size) => {
|
|
22
|
+
return SAMPLE_COLORS.map((color) => {
|
|
23
|
+
const isSoldOut = size.value === SOLD_OUT_COMBINATION.size && color.value === SOLD_OUT_COMBINATION.color;
|
|
24
|
+
const slug = `${toSampleSlug(size.value)}-${toSampleSlug(color.value)}`;
|
|
25
|
+
return {
|
|
26
|
+
id: `replo-sample-variant-${slug}`,
|
|
27
|
+
title: `${size.value} / ${color.value}`,
|
|
28
|
+
availableForSale: !isSoldOut,
|
|
29
|
+
sku: `REPLO-SAMPLE-${slug.toUpperCase()}`,
|
|
30
|
+
selectedOptions: [
|
|
31
|
+
{ name: "Size", value: size.value },
|
|
32
|
+
{ name: "Color", value: color.value }
|
|
33
|
+
],
|
|
34
|
+
image: null,
|
|
35
|
+
price: { amount: size.priceAmount, currencyCode: "USD" },
|
|
36
|
+
// Every variant is "on sale" so strikethrough pricing renders.
|
|
37
|
+
compareAtPrice: { amount: "56.00", currencyCode: "USD" },
|
|
38
|
+
sellingPlanIds: []
|
|
39
|
+
};
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
);
|
|
43
|
+
const SAMPLE_PRODUCT = {
|
|
44
|
+
id: "replo-sample-product",
|
|
45
|
+
handle: "sample-product",
|
|
46
|
+
title: "Sample product",
|
|
47
|
+
description: "This is sample product data for previewing this page. Open the page from a real product link to see live details. Sizes, colors, sale pricing, and a sold-out variant are included so every part of the layout has something to show.",
|
|
48
|
+
descriptionHtml: "<p>This is sample product data for previewing this page. Open the page from a real product link to see live details.</p><p>The sample includes:</p><ul><li>Three sizes and two colors to try the option pickers</li><li>Sale pricing with a compare-at price</li><li>One sold-out combination (Large / Sand)</li></ul>",
|
|
49
|
+
availableForSale: true,
|
|
50
|
+
featuredImage: null,
|
|
51
|
+
// `id` is optional in the schema but always present on real data, and
|
|
52
|
+
// generated pages key option lists on it — omit it and previews log React
|
|
53
|
+
// "missing key" console errors, which the dev overlay counts as page errors.
|
|
54
|
+
options: [
|
|
55
|
+
{
|
|
56
|
+
id: "replo-sample-option-size",
|
|
57
|
+
name: "Size",
|
|
58
|
+
values: SAMPLE_SIZES.map((size) => size.value),
|
|
59
|
+
optionValues: SAMPLE_SIZES.map((size) => ({
|
|
60
|
+
id: `replo-sample-option-value-${toSampleSlug(size.value)}`,
|
|
61
|
+
value: size.value,
|
|
62
|
+
swatch: null
|
|
63
|
+
}))
|
|
64
|
+
},
|
|
65
|
+
{
|
|
66
|
+
id: "replo-sample-option-color",
|
|
67
|
+
name: "Color",
|
|
68
|
+
values: SAMPLE_COLORS.map((color) => color.value),
|
|
69
|
+
optionValues: SAMPLE_COLORS.map((color) => ({
|
|
70
|
+
id: `replo-sample-option-value-${toSampleSlug(color.value)}`,
|
|
71
|
+
value: color.value,
|
|
72
|
+
swatch: { color: color.swatchColor, imageUrl: null }
|
|
73
|
+
}))
|
|
74
|
+
}
|
|
75
|
+
],
|
|
76
|
+
variants: SAMPLE_VARIANTS,
|
|
77
|
+
images: [],
|
|
78
|
+
media: [],
|
|
79
|
+
vendor: "Sample Supply Co.",
|
|
80
|
+
productType: "Sample",
|
|
81
|
+
tags: ["sample-data", "new-arrival", "bestseller"],
|
|
82
|
+
sellingPlanGroups: [],
|
|
83
|
+
metafields: []
|
|
84
|
+
};
|
|
85
|
+
const SAMPLE_COLLECTION = {
|
|
86
|
+
id: "replo-sample-collection",
|
|
87
|
+
handle: "sample-collection",
|
|
88
|
+
title: "Sample collection",
|
|
89
|
+
descriptionHtml: "<p>This is sample collection data for previewing this page.</p>",
|
|
90
|
+
image: null
|
|
91
|
+
};
|
|
92
|
+
const SAMPLE_GRID_CARDS = [
|
|
93
|
+
{
|
|
94
|
+
slug: "range",
|
|
95
|
+
title: "Sample product with a price range",
|
|
96
|
+
minAmount: "42.00",
|
|
97
|
+
maxAmount: "50.00",
|
|
98
|
+
compareAtAmount: "0.0",
|
|
99
|
+
availableForSale: true
|
|
100
|
+
},
|
|
101
|
+
{
|
|
102
|
+
slug: "sale",
|
|
103
|
+
title: "Sample product on sale",
|
|
104
|
+
minAmount: "42.00",
|
|
105
|
+
maxAmount: "42.00",
|
|
106
|
+
compareAtAmount: "56.00",
|
|
107
|
+
availableForSale: true
|
|
108
|
+
},
|
|
109
|
+
{
|
|
110
|
+
slug: "sold-out",
|
|
111
|
+
title: "Sample product that sold out",
|
|
112
|
+
minAmount: "46.00",
|
|
113
|
+
maxAmount: "46.00",
|
|
114
|
+
compareAtAmount: "0.0",
|
|
115
|
+
availableForSale: false
|
|
116
|
+
}
|
|
117
|
+
];
|
|
118
|
+
const SAMPLE_PAGINATED_PRODUCTS = {
|
|
119
|
+
products: SAMPLE_GRID_CARDS.map((card) => ({
|
|
120
|
+
id: `replo-sample-product-${card.slug}`,
|
|
121
|
+
handle: `sample-product-${card.slug}`,
|
|
122
|
+
title: card.title,
|
|
123
|
+
availableForSale: card.availableForSale,
|
|
124
|
+
featuredImage: null,
|
|
125
|
+
options: [
|
|
126
|
+
{
|
|
127
|
+
id: `replo-sample-option-color-${card.slug}`,
|
|
128
|
+
name: "Color",
|
|
129
|
+
values: SAMPLE_COLORS.map((color) => color.value),
|
|
130
|
+
optionValues: SAMPLE_COLORS.map((color) => ({
|
|
131
|
+
id: `replo-sample-option-value-${card.slug}-${toSampleSlug(color.value)}`,
|
|
132
|
+
value: color.value,
|
|
133
|
+
swatch: { color: color.swatchColor, imageUrl: null }
|
|
134
|
+
}))
|
|
135
|
+
}
|
|
136
|
+
],
|
|
137
|
+
variants: SAMPLE_COLORS.map((color) => ({
|
|
138
|
+
id: `replo-sample-variant-${card.slug}-${toSampleSlug(color.value)}`,
|
|
139
|
+
title: color.value,
|
|
140
|
+
availableForSale: card.availableForSale,
|
|
141
|
+
sku: `REPLO-SAMPLE-${card.slug.toUpperCase()}-${toSampleSlug(color.value).toUpperCase()}`,
|
|
142
|
+
selectedOptions: [{ name: "Color", value: color.value }],
|
|
143
|
+
image: null,
|
|
144
|
+
price: { amount: card.minAmount, currencyCode: "USD" },
|
|
145
|
+
compareAtPrice: Number(card.compareAtAmount) > 0 ? { amount: card.compareAtAmount, currencyCode: "USD" } : null
|
|
146
|
+
})),
|
|
147
|
+
minPrice: { amount: card.minAmount, currencyCode: "USD" },
|
|
148
|
+
maxPrice: { amount: card.maxAmount, currencyCode: "USD" },
|
|
149
|
+
compareAtMinPrice: { amount: card.compareAtAmount, currencyCode: "USD" },
|
|
150
|
+
compareAtMaxPrice: { amount: card.compareAtAmount, currencyCode: "USD" }
|
|
151
|
+
})),
|
|
152
|
+
pageInfo: { hasNextPage: false, endCursor: null }
|
|
153
|
+
};
|
|
154
|
+
const PLACEHOLDER_DATA_BY_LOADER_KEY = {
|
|
155
|
+
[DATA_LOADER_KEYS.SHOPIFY_PRODUCT]: SAMPLE_PRODUCT,
|
|
156
|
+
[DATA_LOADER_KEYS.REPLO_PRODUCT]: SAMPLE_PRODUCT,
|
|
157
|
+
[DATA_LOADER_KEYS.SHOPIFY_COLLECTION]: SAMPLE_COLLECTION,
|
|
158
|
+
[DATA_LOADER_KEYS.SHOPIFY_COLLECTION_PRODUCTS]: SAMPLE_PAGINATED_PRODUCTS
|
|
159
|
+
};
|
|
160
|
+
function isUnfilledRouteParamValue(value) {
|
|
161
|
+
if (UNFILLED_ROUTE_PARAM_RE.test(value)) {
|
|
162
|
+
return true;
|
|
163
|
+
}
|
|
164
|
+
try {
|
|
165
|
+
return UNFILLED_ROUTE_PARAM_RE.test(decodeURIComponent(value));
|
|
166
|
+
} catch {
|
|
167
|
+
return false;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
function hasUnfilledRouteParam(args) {
|
|
171
|
+
return Object.values(args).some(
|
|
172
|
+
(value) => typeof value === "string" && isUnfilledRouteParamValue(value)
|
|
173
|
+
);
|
|
174
|
+
}
|
|
175
|
+
function resolvePreviewPlaceholderData({
|
|
176
|
+
loaderKey,
|
|
177
|
+
args
|
|
178
|
+
}) {
|
|
179
|
+
if (!hasUnfilledRouteParam(args)) {
|
|
180
|
+
return null;
|
|
181
|
+
}
|
|
182
|
+
const placeholderData = PLACEHOLDER_DATA_BY_LOADER_KEY[loaderKey];
|
|
183
|
+
if (placeholderData === void 0) {
|
|
184
|
+
return null;
|
|
185
|
+
}
|
|
186
|
+
if (typeof window === "undefined") {
|
|
187
|
+
return process.env.NODE_ENV === "development" ? placeholderData : null;
|
|
188
|
+
}
|
|
189
|
+
return window.parent === window ? null : placeholderData;
|
|
190
|
+
}
|
|
191
|
+
const placeholderIdSchema = z.object({ id: z.string() });
|
|
192
|
+
const placeholderProductsSchema = z.object({
|
|
193
|
+
products: z.array(z.object({ id: z.string() })).min(1)
|
|
194
|
+
});
|
|
195
|
+
function isPreviewPlaceholderData(data) {
|
|
196
|
+
const withId = placeholderIdSchema.safeParse(data);
|
|
197
|
+
if (withId.success) {
|
|
198
|
+
return withId.data.id.startsWith(SAMPLE_ID_PREFIX);
|
|
199
|
+
}
|
|
200
|
+
const withProducts = placeholderProductsSchema.safeParse(data);
|
|
201
|
+
return withProducts.success && (withProducts.data.products[0]?.id.startsWith(SAMPLE_ID_PREFIX) ?? false);
|
|
202
|
+
}
|
|
203
|
+
function useReportPreviewPlaceholderRender(data) {
|
|
204
|
+
useEffect(() => {
|
|
205
|
+
if (window.parent !== window && isPreviewPlaceholderData(data)) {
|
|
206
|
+
window.parent.postMessage(
|
|
207
|
+
{
|
|
208
|
+
type: PLACEHOLDER_RENDER_MESSAGE_TYPE,
|
|
209
|
+
route: window.location.pathname
|
|
210
|
+
},
|
|
211
|
+
"*"
|
|
212
|
+
);
|
|
213
|
+
}
|
|
214
|
+
}, [data]);
|
|
215
|
+
}
|
|
216
|
+
export {
|
|
217
|
+
hasUnfilledRouteParam,
|
|
218
|
+
isPreviewPlaceholderData,
|
|
219
|
+
resolvePreviewPlaceholderData,
|
|
220
|
+
useReportPreviewPlaceholderRender
|
|
221
|
+
};
|
|
222
|
+
//# sourceMappingURL=preview-placeholder.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../loaders/preview-placeholder.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Sample-data substitution for previewing dynamic routes inside the editor.\n *\n * When the editor previews an unfilled Next.js dynamic route (the literal\n * `/products/[handle]` URL), the page receives the bracket token itself as its\n * param, every lookup misses, and the preview 404s. Loader invocations detect\n * that exact case \u2014 editor iframe + a bracket-token arg \u2014 and substitute a\n * type-correct sample fixture so the page renders its real layout with sample\n * data. A `replo:preview:placeholder-render` message tells the embedding\n * editor the preview is showing sample data (mirrors `replo:preview:status`\n * from NextErrorReporter).\n *\n * Substitution is gated to editor iframes only: production traffic to a\n * bracket URL still misses lookups and 404s, so this can never soft-404 a\n * published site.\n */\nimport type {\n FullCollection,\n FullProduct,\n PaginatedProducts,\n} from \"./loader-schemas\";\n\nimport { useEffect } from \"react\";\n\nimport { z } from \"zod\";\n\nimport { DATA_LOADER_KEYS } from \"./loader-keys\";\n\nconst PLACEHOLDER_RENDER_MESSAGE_TYPE = \"replo:preview:placeholder-render\";\n\n// Matches a literal Next.js dynamic segment passed through as a param value:\n// `[handle]`, `[...slug]`, or `[[...slug]]`.\nconst UNFILLED_ROUTE_PARAM_RE = /^\\[{1,2}(?:\\.\\.\\.)?[^\\]]+\\]{1,2}$/;\n\n// Every fixture id carries this prefix so substituted data is recognizable\n// after it round-trips through SSR + React Query hydration (where the client\n// never re-invokes the loader and can't observe the substitution directly).\nconst SAMPLE_ID_PREFIX = \"replo-sample-\";\n\n// The sample option matrix. Sizes carry the price so switching variants\n// visibly updates pricing; colors carry swatches so pickers render them.\nconst SAMPLE_SIZES = [\n { value: \"Small\", priceAmount: \"42.00\" },\n { value: \"Medium\", priceAmount: \"46.00\" },\n { value: \"Large\", priceAmount: \"50.00\" },\n];\nconst SAMPLE_COLORS = [\n { value: \"Slate\", swatchColor: \"#64748b\" },\n { value: \"Sand\", swatchColor: \"#d6bc8a\" },\n];\n// One sold-out combination so disabled buttons / \"Sold out\" states render.\nconst SOLD_OUT_COMBINATION = { size: \"Large\", color: \"Sand\" };\n\nfunction toSampleSlug(value: string): string {\n return value.toLowerCase().replace(/\\s+/g, \"-\");\n}\n\n// Generated as the full size x color cartesian product: agent-built pages\n// match every selected-options combination to a variant, and a combination\n// with no variant breaks their pickers mid-interaction.\nconst SAMPLE_VARIANTS: FullProduct[\"variants\"] = SAMPLE_SIZES.flatMap(\n (size) => {\n return SAMPLE_COLORS.map((color) => {\n const isSoldOut =\n size.value === SOLD_OUT_COMBINATION.size &&\n color.value === SOLD_OUT_COMBINATION.color;\n const slug = `${toSampleSlug(size.value)}-${toSampleSlug(color.value)}`;\n return {\n id: `replo-sample-variant-${slug}`,\n title: `${size.value} / ${color.value}`,\n availableForSale: !isSoldOut,\n sku: `REPLO-SAMPLE-${slug.toUpperCase()}`,\n selectedOptions: [\n { name: \"Size\", value: size.value },\n { name: \"Color\", value: color.value },\n ],\n image: null,\n price: { amount: size.priceAmount, currencyCode: \"USD\" },\n // Every variant is \"on sale\" so strikethrough pricing renders.\n compareAtPrice: { amount: \"56.00\", currencyCode: \"USD\" },\n sellingPlanIds: [],\n };\n });\n },\n);\n\nconst SAMPLE_PRODUCT: FullProduct = {\n id: \"replo-sample-product\",\n handle: \"sample-product\",\n title: \"Sample product\",\n description:\n \"This is sample product data for previewing this page. Open the page from a real product link to see live details. Sizes, colors, sale pricing, and a sold-out variant are included so every part of the layout has something to show.\",\n descriptionHtml:\n \"<p>This is sample product data for previewing this page. Open the page from a real product link to see live details.</p><p>The sample includes:</p><ul><li>Three sizes and two colors to try the option pickers</li><li>Sale pricing with a compare-at price</li><li>One sold-out combination (Large / Sand)</li></ul>\",\n availableForSale: true,\n featuredImage: null,\n // `id` is optional in the schema but always present on real data, and\n // generated pages key option lists on it \u2014 omit it and previews log React\n // \"missing key\" console errors, which the dev overlay counts as page errors.\n options: [\n {\n id: \"replo-sample-option-size\",\n name: \"Size\",\n values: SAMPLE_SIZES.map((size) => size.value),\n optionValues: SAMPLE_SIZES.map((size) => ({\n id: `replo-sample-option-value-${toSampleSlug(size.value)}`,\n value: size.value,\n swatch: null,\n })),\n },\n {\n id: \"replo-sample-option-color\",\n name: \"Color\",\n values: SAMPLE_COLORS.map((color) => color.value),\n optionValues: SAMPLE_COLORS.map((color) => ({\n id: `replo-sample-option-value-${toSampleSlug(color.value)}`,\n value: color.value,\n swatch: { color: color.swatchColor, imageUrl: null },\n })),\n },\n ],\n variants: SAMPLE_VARIANTS,\n images: [],\n media: [],\n vendor: \"Sample Supply Co.\",\n productType: \"Sample\",\n tags: [\"sample-data\", \"new-arrival\", \"bestseller\"],\n sellingPlanGroups: [],\n metafields: [],\n};\n\nconst SAMPLE_COLLECTION: FullCollection = {\n id: \"replo-sample-collection\",\n handle: \"sample-collection\",\n title: \"Sample collection\",\n descriptionHtml:\n \"<p>This is sample collection data for previewing this page.</p>\",\n image: null,\n};\n\n// Three grid cards, each exercising a distinct card state: a price range, a\n// compare-at sale (grids gate strikethroughs on `amount > 0`, per the loader\n// contract where \"0.0\" means no discount), and a sold-out product.\nconst SAMPLE_GRID_CARDS = [\n {\n slug: \"range\",\n title: \"Sample product with a price range\",\n minAmount: \"42.00\",\n maxAmount: \"50.00\",\n compareAtAmount: \"0.0\",\n availableForSale: true,\n },\n {\n slug: \"sale\",\n title: \"Sample product on sale\",\n minAmount: \"42.00\",\n maxAmount: \"42.00\",\n compareAtAmount: \"56.00\",\n availableForSale: true,\n },\n {\n slug: \"sold-out\",\n title: \"Sample product that sold out\",\n minAmount: \"46.00\",\n maxAmount: \"46.00\",\n compareAtAmount: \"0.0\",\n availableForSale: false,\n },\n];\n\nconst SAMPLE_PAGINATED_PRODUCTS: PaginatedProducts = {\n products: SAMPLE_GRID_CARDS.map((card) => ({\n id: `replo-sample-product-${card.slug}`,\n handle: `sample-product-${card.slug}`,\n title: card.title,\n availableForSale: card.availableForSale,\n featuredImage: null,\n options: [\n {\n id: `replo-sample-option-color-${card.slug}`,\n name: \"Color\",\n values: SAMPLE_COLORS.map((color) => color.value),\n optionValues: SAMPLE_COLORS.map((color) => ({\n id: `replo-sample-option-value-${card.slug}-${toSampleSlug(color.value)}`,\n value: color.value,\n swatch: { color: color.swatchColor, imageUrl: null },\n })),\n },\n ],\n variants: SAMPLE_COLORS.map((color) => ({\n id: `replo-sample-variant-${card.slug}-${toSampleSlug(color.value)}`,\n title: color.value,\n availableForSale: card.availableForSale,\n sku: `REPLO-SAMPLE-${card.slug.toUpperCase()}-${toSampleSlug(color.value).toUpperCase()}`,\n selectedOptions: [{ name: \"Color\", value: color.value }],\n image: null,\n price: { amount: card.minAmount, currencyCode: \"USD\" },\n compareAtPrice:\n Number(card.compareAtAmount) > 0\n ? { amount: card.compareAtAmount, currencyCode: \"USD\" }\n : null,\n })),\n minPrice: { amount: card.minAmount, currencyCode: \"USD\" },\n maxPrice: { amount: card.maxAmount, currencyCode: \"USD\" },\n compareAtMinPrice: { amount: card.compareAtAmount, currencyCode: \"USD\" },\n compareAtMaxPrice: { amount: card.compareAtAmount, currencyCode: \"USD\" },\n })),\n pageInfo: { hasNextPage: false, endCursor: null },\n};\n\nconst PLACEHOLDER_DATA_BY_LOADER_KEY: Record<string, unknown> = {\n [DATA_LOADER_KEYS.SHOPIFY_PRODUCT]: SAMPLE_PRODUCT,\n [DATA_LOADER_KEYS.REPLO_PRODUCT]: SAMPLE_PRODUCT,\n [DATA_LOADER_KEYS.SHOPIFY_COLLECTION]: SAMPLE_COLLECTION,\n [DATA_LOADER_KEYS.SHOPIFY_COLLECTION_PRODUCTS]: SAMPLE_PAGINATED_PRODUCTS,\n};\n\nfunction isUnfilledRouteParamValue(value: string): boolean {\n if (UNFILLED_ROUTE_PARAM_RE.test(value)) {\n return true;\n }\n // Next.js hands params over URL-encoded, so the literal `[handle]` segment\n // arrives as `%5Bhandle%5D`.\n try {\n return UNFILLED_ROUTE_PARAM_RE.test(decodeURIComponent(value));\n } catch {\n return false;\n }\n}\n\nexport function hasUnfilledRouteParam(args: Record<string, unknown>): boolean {\n return Object.values(args).some(\n (value) => typeof value === \"string\" && isUnfilledRouteParamValue(value),\n );\n}\n\n/**\n * Sample data for a loader invoked with an unfilled dynamic-route param, or\n * null when the invocation should proceed normally.\n *\n * On the server, substitution happens only on dev servers (`next dev` \u2014 how\n * every sandbox preview runs); production builds keep fetching so bracket\n * URLs keep their real miss/404 semantics. Substituting during SSR keeps the\n * doomed fetch from erroring the dev overlay mid-stream. In the browser,\n * substitution happens only inside an editor iframe.\n */\nexport function resolvePreviewPlaceholderData({\n loaderKey,\n args,\n}: {\n loaderKey: string;\n args: Record<string, unknown>;\n}): unknown {\n if (!hasUnfilledRouteParam(args)) {\n return null;\n }\n const placeholderData = PLACEHOLDER_DATA_BY_LOADER_KEY[loaderKey];\n if (placeholderData === undefined) {\n return null;\n }\n if (typeof window === \"undefined\") {\n return process.env.NODE_ENV === \"development\" ? placeholderData : null;\n }\n return window.parent === window ? null : placeholderData;\n}\n\nconst placeholderIdSchema = z.object({ id: z.string() });\nconst placeholderProductsSchema = z.object({\n products: z.array(z.object({ id: z.string() })).min(1),\n});\n\n/** Whether loader output is one of this module's sample fixtures. */\nexport function isPreviewPlaceholderData(data: unknown): boolean {\n const withId = placeholderIdSchema.safeParse(data);\n if (withId.success) {\n return withId.data.id.startsWith(SAMPLE_ID_PREFIX);\n }\n const withProducts = placeholderProductsSchema.safeParse(data);\n return (\n withProducts.success &&\n (withProducts.data.products[0]?.id.startsWith(SAMPLE_ID_PREFIX) ?? false)\n );\n}\n\n/**\n * Notify the embedding editor when a loader component rendered sample data.\n * The single reporting path: inspecting rendered data (rather than hooking\n * loader invocation) covers client fetches and SSR-hydrated data alike \u2014\n * hydration never re-invokes the loader on the client. Receivers treat the\n * message as idempotent, so no dedupe is needed.\n */\nexport function useReportPreviewPlaceholderRender(data: unknown) {\n // eslint-disable-next-line replo/no-use-effect -- Posts to the embedding editor window, an external system.\n useEffect(() => {\n if (window.parent !== window && isPreviewPlaceholderData(data)) {\n window.parent.postMessage(\n {\n type: PLACEHOLDER_RENDER_MESSAGE_TYPE,\n route: window.location.pathname,\n },\n \"*\",\n );\n }\n }, [data]);\n}\n"],
|
|
5
|
+
"mappings": "AAsBA,SAAS,iBAAiB;AAE1B,SAAS,SAAS;AAElB,SAAS,wBAAwB;AAEjC,MAAM,kCAAkC;AAIxC,MAAM,0BAA0B;AAKhC,MAAM,mBAAmB;AAIzB,MAAM,eAAe;AAAA,EACnB,EAAE,OAAO,SAAS,aAAa,QAAQ;AAAA,EACvC,EAAE,OAAO,UAAU,aAAa,QAAQ;AAAA,EACxC,EAAE,OAAO,SAAS,aAAa,QAAQ;AACzC;AACA,MAAM,gBAAgB;AAAA,EACpB,EAAE,OAAO,SAAS,aAAa,UAAU;AAAA,EACzC,EAAE,OAAO,QAAQ,aAAa,UAAU;AAC1C;AAEA,MAAM,uBAAuB,EAAE,MAAM,SAAS,OAAO,OAAO;AAE5D,SAAS,aAAa,OAAuB;AAC3C,SAAO,MAAM,YAAY,EAAE,QAAQ,QAAQ,GAAG;AAChD;AAKA,MAAM,kBAA2C,aAAa;AAAA,EAC5D,CAAC,SAAS;AACR,WAAO,cAAc,IAAI,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UAAU,yBAAyB,IAAI,GAAG;AAC9D,aAAO,OAAO;AAAA,QACZ;AAAA,UACE,MAAM;AAAA,UACN,OAAO,OAAO,SAAS;AAAA,QACzB;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAAA,EACF,GAAG,CAAC,IAAI,CAAC;AACX;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -5,6 +5,7 @@ import { useSuspenseQuery } from "@tanstack/react-query";
|
|
|
5
5
|
import { invokeLoader } from "./invoke-loader";
|
|
6
6
|
import { LoaderErrorBoundary } from "./loader-error-boundary";
|
|
7
7
|
import { fullProductSchema } from "./loader-schemas";
|
|
8
|
+
import { useReportPreviewPlaceholderRender } from "./preview-placeholder";
|
|
8
9
|
import { buildProductLoaderArgs } from "./product-loader-args";
|
|
9
10
|
function ProductLoaderInner({
|
|
10
11
|
loaderKey,
|
|
@@ -18,6 +19,7 @@ function ProductLoaderInner({
|
|
|
18
19
|
return fullProductSchema.parse(loadedData);
|
|
19
20
|
}
|
|
20
21
|
});
|
|
22
|
+
useReportPreviewPlaceholderRender(queryResult.data);
|
|
21
23
|
return /* @__PURE__ */ jsx(Fragment, { children: children(queryResult.data) });
|
|
22
24
|
}
|
|
23
25
|
function ProductLoader({
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../loaders/product-loader.tsx"],
|
|
4
|
-
"sourcesContent": ["\"use client\";\n\nimport type { ReactNode } from \"react\";\nimport type { FullProduct } from \"./loader-schemas\";\nimport type { ProductLoaderArgs } from \"./product-loader-args\";\n\nimport { Suspense } from \"react\";\n\nimport { useSuspenseQuery } from \"@tanstack/react-query\";\n\nimport { invokeLoader } from \"./invoke-loader\";\nimport { LoaderErrorBoundary } from \"./loader-error-boundary\";\nimport { fullProductSchema } from \"./loader-schemas\";\nimport { buildProductLoaderArgs } from \"./product-loader-args\";\n\ntype ProductLoaderProps = ProductLoaderArgs & {\n loaderKey: string;\n children: (data: FullProduct) => ReactNode;\n fallback?: ReactNode;\n};\n\nfunction ProductLoaderInner({\n loaderKey,\n args,\n children,\n}: {\n loaderKey: string;\n args: ProductLoaderArgs;\n children: (data: FullProduct) => ReactNode;\n}) {\n const queryResult = useSuspenseQuery({\n queryKey: [loaderKey, args],\n queryFn: async () => {\n const loadedData = await invokeLoader({ loaderKey, args });\n return fullProductSchema.parse(loadedData);\n },\n });\n\n return <>{children(queryResult.data)}</>;\n}\n\nexport function ProductLoader({\n loaderKey,\n handle,\n productId,\n productMetafieldIdentifiers,\n variantMetafieldIdentifiers,\n children,\n fallback,\n}: ProductLoaderProps) {\n const args = buildProductLoaderArgs({\n handle,\n productId,\n productMetafieldIdentifiers,\n variantMetafieldIdentifiers,\n });\n\n return (\n <LoaderErrorBoundary\n fallback={fallback ?? null}\n resetKey={`${loaderKey}:${JSON.stringify(args)}`}\n >\n <Suspense fallback={fallback ?? null}>\n <ProductLoaderInner loaderKey={loaderKey} args={args}>\n {children}\n </ProductLoaderInner>\n </Suspense>\n </LoaderErrorBoundary>\n );\n}\n"],
|
|
5
|
-
"mappings": ";
|
|
4
|
+
"sourcesContent": ["\"use client\";\n\nimport type { ReactNode } from \"react\";\nimport type { FullProduct } from \"./loader-schemas\";\nimport type { ProductLoaderArgs } from \"./product-loader-args\";\n\nimport { Suspense } from \"react\";\n\nimport { useSuspenseQuery } from \"@tanstack/react-query\";\n\nimport { invokeLoader } from \"./invoke-loader\";\nimport { LoaderErrorBoundary } from \"./loader-error-boundary\";\nimport { fullProductSchema } from \"./loader-schemas\";\nimport { useReportPreviewPlaceholderRender } from \"./preview-placeholder\";\nimport { buildProductLoaderArgs } from \"./product-loader-args\";\n\ntype ProductLoaderProps = ProductLoaderArgs & {\n loaderKey: string;\n children: (data: FullProduct) => ReactNode;\n fallback?: ReactNode;\n};\n\nfunction ProductLoaderInner({\n loaderKey,\n args,\n children,\n}: {\n loaderKey: string;\n args: ProductLoaderArgs;\n children: (data: FullProduct) => ReactNode;\n}) {\n const queryResult = useSuspenseQuery({\n queryKey: [loaderKey, args],\n queryFn: async () => {\n const loadedData = await invokeLoader({ loaderKey, args });\n return fullProductSchema.parse(loadedData);\n },\n });\n useReportPreviewPlaceholderRender(queryResult.data);\n\n return <>{children(queryResult.data)}</>;\n}\n\nexport function ProductLoader({\n loaderKey,\n handle,\n productId,\n productMetafieldIdentifiers,\n variantMetafieldIdentifiers,\n children,\n fallback,\n}: ProductLoaderProps) {\n const args = buildProductLoaderArgs({\n handle,\n productId,\n productMetafieldIdentifiers,\n variantMetafieldIdentifiers,\n });\n\n return (\n <LoaderErrorBoundary\n fallback={fallback ?? null}\n resetKey={`${loaderKey}:${JSON.stringify(args)}`}\n >\n <Suspense fallback={fallback ?? null}>\n <ProductLoaderInner loaderKey={loaderKey} args={args}>\n {children}\n </ProductLoaderInner>\n </Suspense>\n </LoaderErrorBoundary>\n );\n}\n"],
|
|
5
|
+
"mappings": ";AAwCS;AAlCT,SAAS,gBAAgB;AAEzB,SAAS,wBAAwB;AAEjC,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B;AACpC,SAAS,yBAAyB;AAClC,SAAS,yCAAyC;AAClD,SAAS,8BAA8B;AAQvC,SAAS,mBAAmB;AAAA,EAC1B;AAAA,EACA;AAAA,EACA;AACF,GAIG;AACD,QAAM,cAAc,iBAAiB;AAAA,IACnC,UAAU,CAAC,WAAW,IAAI;AAAA,IAC1B,SAAS,YAAY;AACnB,YAAM,aAAa,MAAM,aAAa,EAAE,WAAW,KAAK,CAAC;AACzD,aAAO,kBAAkB,MAAM,UAAU;AAAA,IAC3C;AAAA,EACF,CAAC;AACD,oCAAkC,YAAY,IAAI;AAElD,SAAO,gCAAG,mBAAS,YAAY,IAAI,GAAE;AACvC;AAEO,SAAS,cAAc;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAAuB;AACrB,QAAM,OAAO,uBAAuB;AAAA,IAClC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AAED,SACE;AAAA,IAAC;AAAA;AAAA,MACC,UAAU,YAAY;AAAA,MACtB,UAAU,GAAG,SAAS,IAAI,KAAK,UAAU,IAAI,CAAC;AAAA,MAE9C,8BAAC,YAAS,UAAU,YAAY,MAC9B,8BAAC,sBAAmB,WAAsB,MACvC,UACH,GACF;AAAA;AAAA,EACF;AAEJ;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@replohq/canopy-sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.16.0-beta.pr-24057.1.3c7b61d",
|
|
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,
|
|
@@ -27,10 +27,6 @@
|
|
|
27
27
|
"react": ">=18.2.0",
|
|
28
28
|
"react-dom": ">=18.2.0"
|
|
29
29
|
},
|
|
30
|
-
"publishConfig": {
|
|
31
|
-
"registry": "https://registry.npmjs.org/",
|
|
32
|
-
"access": "restricted"
|
|
33
|
-
},
|
|
34
30
|
"engines": {
|
|
35
31
|
"node": "22.x"
|
|
36
32
|
}
|