@replohq/canopy-sdk 0.12.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/_vendor/replo-utils/lib/errors.d.ts +83 -0
- package/_vendor/replo-utils/lib/fonts.mjs +2 -40
- package/_vendor/replo-utils/lib/json.mjs +1 -1
- package/_vendor/replo-utils/lib/misc.mjs +2 -2
- package/_vendor/schemas/agentTools/customIntegrations/loaders/levanta.d.ts +49 -0
- package/_vendor/schemas/agentTools/customIntegrations/loaders/levanta.mjs +36 -0
- package/_vendor/schemas/agentTools/customIntegrations/loaders/product.d.ts +340 -0
- package/_vendor/schemas/agentTools/customIntegrations/loaders/product.mjs +51 -0
- package/_vendor/schemas/agentTools/customIntegrations/loaders/yotpo.d.ts +37 -0
- package/_vendor/schemas/agentTools/customIntegrations/loaders/yotpo.mjs +37 -0
- package/{cart/cart-schema.js → _vendor/schemas/cart.mjs} +17 -26
- package/_vendor/schemas/designLibrary.d.ts +4 -4
- package/_vendor/schemas/errors.d.ts +438 -0
- package/_vendor/schemas/errors.mjs +932 -0
- package/_vendor/schemas/generated/errors.d.ts +61 -0
- package/_vendor/schemas/generated/selectMode.d.ts +102 -0
- package/{loaders/loader-keys.d.ts → _vendor/schemas/loaderKeys.d.ts} +4 -4
- package/{loaders/loader-keys.js → _vendor/schemas/loaderKeys.mjs} +7 -8
- package/_vendor/schemas/objectType.d.ts +1038 -0
- package/_vendor/schemas/objectType.mjs +2 -0
- package/_vendor/schemas/registry.d.ts +539 -0
- package/_vendor/schemas/sandboxFiles.d.ts +36 -0
- package/_vendor/schemas/savedStyles.d.ts +2 -2
- package/_vendor/schemas/selectMode.d.ts +471 -0
- package/_vendor/schemas/selectMode.mjs +120 -4
- package/_vendor/schemas/sellingPlan.d.ts +60 -0
- package/_vendor/schemas/sellingPlan.mjs +1 -0
- package/cart/buy-now-action.js +3 -3
- package/cart/buy-now-action.js.map +2 -2
- package/cart/cart-provider.js +2 -2
- package/cart/cart-provider.js.map +2 -2
- package/cart/cart-types.d.ts +2 -1
- package/cart/cart-types.js.map +2 -2
- package/cart/hooks/use-add-to-cart.js +1 -1
- package/cart/hooks/use-add-to-cart.js.map +2 -2
- package/cart/hooks/use-buy-now.js +2 -2
- package/cart/hooks/use-buy-now.js.map +2 -2
- package/cart/utils/variant-to-cart-line.d.ts +1 -2
- package/cart/utils/variant-to-cart-line.js.map +1 -1
- package/chunk-4XLTENDR.mjs +33 -0
- package/chunk-A7EUNWRQ.mjs +765 -0
- package/{chunk-ME5W2TJM.mjs → chunk-OCB5XQYL.mjs} +2 -2
- package/chunk-QFYIXADC.mjs +42 -0
- package/editor/LinkInterceptor.js +4 -0
- package/editor/LinkInterceptor.js.map +2 -2
- package/editor/select-mode/EditorSelection.js +74 -1
- package/editor/select-mode/EditorSelection.js.map +2 -2
- package/editor/select-mode/descriptor/elementDescriptor.d.ts +13 -2
- package/editor/select-mode/descriptor/elementDescriptor.js +19 -31
- package/editor/select-mode/descriptor/elementDescriptor.js.map +2 -2
- package/editor/select-mode/descriptor/styleExtraction.d.ts +3 -0
- package/editor/select-mode/descriptor/styleExtraction.js +271 -0
- package/editor/select-mode/descriptor/styleExtraction.js.map +7 -0
- package/editor/select-mode/displayModeStore.d.ts +10 -0
- package/editor/select-mode/displayModeStore.js +47 -0
- package/editor/select-mode/displayModeStore.js.map +7 -0
- package/editor/select-mode/fast-refresh-relay.d.ts +3 -0
- package/editor/select-mode/fast-refresh-relay.js +35 -0
- package/editor/select-mode/fast-refresh-relay.js.map +7 -0
- package/editor/select-mode/fiber.d.ts +17 -0
- package/editor/select-mode/fiber.js +103 -34
- package/editor/select-mode/fiber.js.map +2 -2
- package/editor/select-mode/hooks/useEditModeStateMachine.d.ts +20 -0
- package/editor/select-mode/hooks/useEditModeStateMachine.js +226 -0
- package/editor/select-mode/hooks/useEditModeStateMachine.js.map +7 -0
- package/editor/select-mode/hooks/useOptimisticOverrides.d.ts +20 -0
- package/editor/select-mode/hooks/useOptimisticOverrides.js +284 -0
- package/editor/select-mode/hooks/useOptimisticOverrides.js.map +7 -0
- package/editor/select-mode/hooks/useParentMessaging.d.ts +17 -2
- package/editor/select-mode/hooks/useParentMessaging.js +66 -1
- package/editor/select-mode/hooks/useParentMessaging.js.map +2 -2
- package/editor/select-mode/hooks/useSelectModeController.js +5 -6
- package/editor/select-mode/hooks/useSelectModeController.js.map +2 -2
- package/editor/select-mode/hooks/useSelectionHover.js +16 -1
- package/editor/select-mode/hooks/useSelectionHover.js.map +2 -2
- package/editor/select-mode/hooks/useSelectionInteractions.d.ts +7 -2
- package/editor/select-mode/hooks/useSelectionInteractions.js +57 -18
- package/editor/select-mode/hooks/useSelectionInteractions.js.map +2 -2
- package/editor/select-mode/hooks/useSiblingResolution.d.ts +6 -0
- package/editor/select-mode/hooks/useSiblingResolution.js +59 -0
- package/editor/select-mode/hooks/useSiblingResolution.js.map +7 -0
- package/editor/select-mode/inlineTextMarks.d.ts +6 -0
- package/editor/select-mode/inlineTextMarks.js +25 -0
- package/editor/select-mode/inlineTextMarks.js.map +7 -0
- package/editor/select-mode/interactions/selectionGeometry.js +4 -0
- package/editor/select-mode/interactions/selectionGeometry.js.map +2 -2
- package/editor/select-mode/selectionFrame.d.ts +5 -0
- package/editor/select-mode/selectionFrame.js +25 -1
- package/editor/select-mode/selectionFrame.js.map +2 -2
- package/editor/select-mode/symbolicate.js +32 -10
- package/editor/select-mode/symbolicate.js.map +2 -2
- package/editor/select-mode/tiptapInlineEditor.d.ts +23 -0
- package/editor/select-mode/tiptapInlineEditor.js +120 -0
- package/editor/select-mode/tiptapInlineEditor.js.map +7 -0
- package/gateways/canopy-api.d.ts +3 -3
- package/gateways/canopy-api.js +3 -3
- package/gateways/canopy-api.js.map +2 -2
- package/loaders/collection-loader.d.ts +1 -1
- package/loaders/collection-loader.js +1 -1
- package/loaders/collection-loader.js.map +2 -2
- package/loaders/collection-products-loader.d.ts +1 -1
- package/loaders/collection-products-loader.js +1 -1
- package/loaders/collection-products-loader.js.map +2 -2
- package/loaders/invoke-loader.d.ts +2 -2
- package/loaders/invoke-loader.js +2 -2
- package/loaders/invoke-loader.js.map +2 -2
- package/loaders/levanta-product-loader.d.ts +1 -1
- package/loaders/levanta-product-loader.js +1 -1
- package/loaders/levanta-product-loader.js.map +2 -2
- package/loaders/okendo-reviews-loader.js +1 -1
- package/loaders/okendo-reviews-loader.js.map +2 -2
- package/loaders/prefetch-loaders.d.ts +1 -1
- package/loaders/prefetch-loaders.js.map +1 -1
- package/loaders/product-loader.d.ts +1 -1
- package/loaders/product-loader.js +1 -1
- package/loaders/product-loader.js.map +2 -2
- package/loaders/rebuy-recommendations-loader.js +1 -1
- package/loaders/rebuy-recommendations-loader.js.map +2 -2
- package/loaders/yotpo-review-aggregate-loader.d.ts +1 -1
- package/loaders/yotpo-review-aggregate-loader.js +1 -1
- package/loaders/yotpo-review-aggregate-loader.js.map +2 -2
- package/loaders/yotpo-reviews-loader.d.ts +1 -1
- package/loaders/yotpo-reviews-loader.js +1 -1
- package/loaders/yotpo-reviews-loader.js.map +2 -2
- package/package.json +9 -1
- package/cart/cart-schema.js.map +0 -7
- package/lib/canopy-error.d.ts +0 -25
- package/lib/canopy-error.js +0 -24
- package/lib/canopy-error.js.map +0 -7
- package/loaders/loader-keys.js.map +0 -7
- package/loaders/loader-schemas.d.ts +0 -755
- package/loaders/loader-schemas.js +0 -257
- package/loaders/loader-schemas.js.map +0 -7
- package/{cart/cart-schema.d.ts → _vendor/schemas/cart.d.ts} +0 -0
- package/{chunk-NCKKAFF7.mjs → chunk-ILGEM42C.mjs} +7 -7
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { exhaustiveSwitch } from '../../chunk-ME5W2TJM.mjs';
|
|
2
1
|
import { parseJsonOrNull } from '../../chunk-VKO7P3ED.mjs';
|
|
3
|
-
import '../../chunk-
|
|
2
|
+
import { exhaustiveSwitch } from '../../chunk-OCB5XQYL.mjs';
|
|
3
|
+
import '../../chunk-ILGEM42C.mjs';
|
|
4
4
|
import '../../chunk-FNTGY7I5.mjs';
|
|
5
5
|
import { z } from 'zod';
|
|
6
6
|
|
|
@@ -12,6 +12,7 @@ function parseSchemaOrNull(value, schema) {
|
|
|
12
12
|
var SELECT_MODE_SELECTABLE_ATTRIBUTE = "data-replo-selectable";
|
|
13
13
|
var SELECT_MODE_SELECTABLE_PAYLOAD_ATTRIBUTE = "data-replo-selectable-payload";
|
|
14
14
|
var displayModeSchema = z.enum(["browse", "selection"]).describe("DisplayMode");
|
|
15
|
+
var selectModeInlineTextStatusSchema = z.enum(["editable", "dynamic"]).nullable().describe("SelectModeInlineTextStatus");
|
|
15
16
|
var selectModeTextMetricsSchema = z.object({
|
|
16
17
|
tightWidth: z.number(),
|
|
17
18
|
lineCount: z.number(),
|
|
@@ -27,6 +28,12 @@ var selectModeSourceLocationSchema = z.object({
|
|
|
27
28
|
columnNumber: z.number().optional(),
|
|
28
29
|
componentName: z.string().optional()
|
|
29
30
|
}).describe("SelectModeSourceLocation");
|
|
31
|
+
var selectModeFiberChainEntrySchema = z.object({
|
|
32
|
+
sourceLocation: selectModeSourceLocationSchema,
|
|
33
|
+
tagName: z.string().optional(),
|
|
34
|
+
componentName: z.string().optional(),
|
|
35
|
+
props: z.record(z.string(), z.unknown()).optional()
|
|
36
|
+
}).describe("SelectModeFiberChainEntry");
|
|
30
37
|
var selectModeBoundingRectSchema = z.object({
|
|
31
38
|
x: z.number(),
|
|
32
39
|
y: z.number(),
|
|
@@ -41,6 +48,21 @@ var selectModeSelectionRectSchema = z.object({
|
|
|
41
48
|
id: z.string(),
|
|
42
49
|
rect: selectModeBoundingRectSchema
|
|
43
50
|
}).describe("SelectModeSelectionRect");
|
|
51
|
+
var selectModeStyleAtRuleSchema = z.object({
|
|
52
|
+
type: z.string(),
|
|
53
|
+
text: z.string()
|
|
54
|
+
}).describe("SelectModeStyleAtRule");
|
|
55
|
+
var selectModeStyleVariantSchema = z.object({
|
|
56
|
+
atRules: z.array(selectModeStyleAtRuleSchema),
|
|
57
|
+
pseudo: z.string().nullable()
|
|
58
|
+
}).describe("SelectModeStyleVariant");
|
|
59
|
+
var selectModeDefinedStyleSchema = z.object({
|
|
60
|
+
property: z.string(),
|
|
61
|
+
variant: selectModeStyleVariantSchema.nullable(),
|
|
62
|
+
className: z.string().nullable(),
|
|
63
|
+
raw: z.string(),
|
|
64
|
+
resolved: z.string()
|
|
65
|
+
}).describe("SelectModeDefinedStyle");
|
|
44
66
|
function transformRect({
|
|
45
67
|
rect,
|
|
46
68
|
offset
|
|
@@ -81,8 +103,12 @@ var selectedElementSchema = z.object({
|
|
|
81
103
|
rect: selectModeBoundingRectSchema,
|
|
82
104
|
textMetrics: selectModeTextMetricsSchema.nullable(),
|
|
83
105
|
outerHTML: z.string(),
|
|
106
|
+
definedStyles: z.array(selectModeDefinedStyleSchema).default([]),
|
|
107
|
+
inheritedStyles: z.record(z.string(), z.string()).default({}),
|
|
84
108
|
clickPosition: selectModeClickPositionSchema,
|
|
85
|
-
sourceLocation: selectModeSourceLocationSchema.optional()
|
|
109
|
+
sourceLocation: selectModeSourceLocationSchema.optional(),
|
|
110
|
+
fiberChain: z.array(selectModeFiberChainEntrySchema).default([]),
|
|
111
|
+
siblingSelectors: z.array(z.string()).default([])
|
|
86
112
|
}).describe("SelectedElement");
|
|
87
113
|
var selectablePlanDataSchema = z.object({
|
|
88
114
|
kind: z.literal("plan"),
|
|
@@ -125,6 +151,29 @@ function readSelectablePayload(rawPayload) {
|
|
|
125
151
|
}
|
|
126
152
|
return parseSchemaOrNull(parsedPayload, selectableDataPayloadSchema);
|
|
127
153
|
}
|
|
154
|
+
var selectModeOptimisticUpdatePayloadSchema = z.discriminatedUnion("kind", [
|
|
155
|
+
z.object({
|
|
156
|
+
kind: z.literal("css"),
|
|
157
|
+
property: z.string(),
|
|
158
|
+
value: z.string().nullable()
|
|
159
|
+
}),
|
|
160
|
+
z.object({
|
|
161
|
+
kind: z.literal("content"),
|
|
162
|
+
innerHTML: z.string()
|
|
163
|
+
}),
|
|
164
|
+
z.object({
|
|
165
|
+
kind: z.literal("attribute"),
|
|
166
|
+
name: z.string(),
|
|
167
|
+
value: z.string()
|
|
168
|
+
})
|
|
169
|
+
]).describe("SelectModeOptimisticUpdatePayload");
|
|
170
|
+
var selectModeTiptapActiveMarksSchema = z.object({
|
|
171
|
+
bold: z.boolean(),
|
|
172
|
+
italic: z.boolean(),
|
|
173
|
+
underline: z.boolean(),
|
|
174
|
+
strike: z.boolean()
|
|
175
|
+
}).describe("SelectModeTiptapActiveMarks");
|
|
176
|
+
var selectModeFormatCommandSchema = z.enum(["toggleBold", "toggleItalic", "toggleUnderline", "toggleStrike"]).describe("SelectModeFormatCommand");
|
|
128
177
|
var selectModeSelectionTypeSchema = z.enum(["none", "element", "area", "drag"]).describe("SelectModeSelectionType");
|
|
129
178
|
var selectModeSelectionSchema = z.discriminatedUnion("type", [
|
|
130
179
|
z.object({ type: z.literal("none") }),
|
|
@@ -159,6 +208,46 @@ var selectModeParentMessageSchema = z.discriminatedUnion("type", [
|
|
|
159
208
|
z.object({
|
|
160
209
|
type: z.literal("replo:select:setSelectionType"),
|
|
161
210
|
selectionType: selectModeSelectionTypeSchema
|
|
211
|
+
}),
|
|
212
|
+
z.object({
|
|
213
|
+
type: z.literal("replo:select:applyOptimisticUpdate"),
|
|
214
|
+
editId: z.string(),
|
|
215
|
+
payload: selectModeOptimisticUpdatePayloadSchema,
|
|
216
|
+
targetMode: z.enum(["primary", "group"])
|
|
217
|
+
}),
|
|
218
|
+
z.object({
|
|
219
|
+
type: z.literal("replo:select:markCommitted"),
|
|
220
|
+
editId: z.string(),
|
|
221
|
+
sessionId: z.string()
|
|
222
|
+
}),
|
|
223
|
+
z.object({
|
|
224
|
+
type: z.literal("replo:select:resolveSessionOverrides"),
|
|
225
|
+
sessionId: z.string(),
|
|
226
|
+
outcome: z.enum(["persisted", "failed"])
|
|
227
|
+
}),
|
|
228
|
+
z.object({
|
|
229
|
+
type: z.literal("replo:select:revertOverride"),
|
|
230
|
+
editId: z.string()
|
|
231
|
+
}),
|
|
232
|
+
z.object({
|
|
233
|
+
type: z.literal("replo:select:enterEditMode")
|
|
234
|
+
}),
|
|
235
|
+
z.object({
|
|
236
|
+
type: z.literal("replo:select:exitEditMode")
|
|
237
|
+
}),
|
|
238
|
+
z.object({
|
|
239
|
+
type: z.literal("replo:select:formatCommand"),
|
|
240
|
+
command: selectModeFormatCommandSchema
|
|
241
|
+
}),
|
|
242
|
+
z.object({
|
|
243
|
+
type: z.literal("replo:select:resolveEditRequest"),
|
|
244
|
+
editId: z.string(),
|
|
245
|
+
allowed: z.boolean()
|
|
246
|
+
}),
|
|
247
|
+
z.object({
|
|
248
|
+
type: z.literal("replo:select:requestSymbolicate"),
|
|
249
|
+
requestId: z.string(),
|
|
250
|
+
element: selectedElementSchema
|
|
162
251
|
})
|
|
163
252
|
]).describe("SelectModeParentMessage");
|
|
164
253
|
var selectModeIframeMessageSchema = z.discriminatedUnion("type", [
|
|
@@ -191,7 +280,34 @@ var selectModeIframeMessageSchema = z.discriminatedUnion("type", [
|
|
|
191
280
|
type: z.literal("replo:select:areaSelected"),
|
|
192
281
|
rect: selectModeBoundingRectSchema,
|
|
193
282
|
items: z.array(selectableDataSchema)
|
|
283
|
+
}),
|
|
284
|
+
z.object({
|
|
285
|
+
type: z.literal("replo:select:doubleClicked"),
|
|
286
|
+
editId: z.string(),
|
|
287
|
+
element: selectedElementSchema
|
|
288
|
+
}),
|
|
289
|
+
z.object({
|
|
290
|
+
type: z.literal("replo:select:textCommitted"),
|
|
291
|
+
editId: z.string(),
|
|
292
|
+
html: z.string(),
|
|
293
|
+
json: z.record(z.string(), z.unknown()),
|
|
294
|
+
originalInnerHTML: z.string()
|
|
295
|
+
}),
|
|
296
|
+
z.object({
|
|
297
|
+
type: z.literal("replo:select:editorStateUpdate"),
|
|
298
|
+
activeMarks: selectModeTiptapActiveMarksSchema,
|
|
299
|
+
// Whether an inline text edit is currently open. Lets the parent show the
|
|
300
|
+
// inline formatting controls (and live mark state) only while editing.
|
|
301
|
+
isEditing: z.boolean()
|
|
302
|
+
}),
|
|
303
|
+
z.object({
|
|
304
|
+
type: z.literal("replo:select:fastRefreshComplete")
|
|
305
|
+
}),
|
|
306
|
+
z.object({
|
|
307
|
+
type: z.literal("replo:select:symbolicateResult"),
|
|
308
|
+
requestId: z.string(),
|
|
309
|
+
element: selectedElementSchema
|
|
194
310
|
})
|
|
195
311
|
]).describe("SelectModeIframeMessage");
|
|
196
312
|
|
|
197
|
-
export { SELECT_MODE_SELECTABLE_ATTRIBUTE, SELECT_MODE_SELECTABLE_PAYLOAD_ATTRIBUTE, displayModeSchema, getIframeOffset, readSelectablePayload, selectModeBoundingRectSchema, selectModeClickPositionSchema, selectModeIframeMessageSchema, selectModeParentMessageSchema, selectModeSelectionRectSchema, selectModeSelectionSchema, selectModeSelectionTypeSchema, selectModeSourceLocationSchema, selectModeTextMetricsSchema, selectableDataPayloadSchema, selectableDataSchema, selectablePlanDataSchema, selectablePlanPayloadSchema, selectedElementSchema, transformPoint, transformRect, transformSelectableData };
|
|
313
|
+
export { SELECT_MODE_SELECTABLE_ATTRIBUTE, SELECT_MODE_SELECTABLE_PAYLOAD_ATTRIBUTE, displayModeSchema, getIframeOffset, readSelectablePayload, selectModeBoundingRectSchema, selectModeClickPositionSchema, selectModeDefinedStyleSchema, selectModeFiberChainEntrySchema, selectModeFormatCommandSchema, selectModeIframeMessageSchema, selectModeInlineTextStatusSchema, selectModeOptimisticUpdatePayloadSchema, selectModeParentMessageSchema, selectModeSelectionRectSchema, selectModeSelectionSchema, selectModeSelectionTypeSchema, selectModeSourceLocationSchema, selectModeStyleAtRuleSchema, selectModeStyleVariantSchema, selectModeTextMetricsSchema, selectModeTiptapActiveMarksSchema, selectableDataPayloadSchema, selectableDataSchema, selectablePlanDataSchema, selectablePlanPayloadSchema, selectedElementSchema, transformPoint, transformRect, transformSelectableData };
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
export declare const sellingPlanPriceAdjustmentSchema: z.ZodObject<{
|
|
3
|
+
value: z.ZodNumber;
|
|
4
|
+
valueType: z.ZodEnum<{
|
|
5
|
+
price: "price";
|
|
6
|
+
percentage: "percentage";
|
|
7
|
+
fixedAmount: "fixedAmount";
|
|
8
|
+
}>;
|
|
9
|
+
}, z.core.$strip>;
|
|
10
|
+
export declare const sellingPlanOptionValueSchema: z.ZodObject<{
|
|
11
|
+
name: z.ZodOptional<z.ZodString>;
|
|
12
|
+
value: z.ZodString;
|
|
13
|
+
}, z.core.$strip>;
|
|
14
|
+
export declare const sellingPlanSchema: z.ZodObject<{
|
|
15
|
+
id: z.ZodString;
|
|
16
|
+
name: z.ZodString;
|
|
17
|
+
description: z.ZodNullable<z.ZodString>;
|
|
18
|
+
optionValues: z.ZodArray<z.ZodObject<{
|
|
19
|
+
name: z.ZodOptional<z.ZodString>;
|
|
20
|
+
value: z.ZodString;
|
|
21
|
+
}, z.core.$strip>>;
|
|
22
|
+
priceAdjustments: z.ZodArray<z.ZodObject<{
|
|
23
|
+
value: z.ZodNumber;
|
|
24
|
+
valueType: z.ZodEnum<{
|
|
25
|
+
price: "price";
|
|
26
|
+
percentage: "percentage";
|
|
27
|
+
fixedAmount: "fixedAmount";
|
|
28
|
+
}>;
|
|
29
|
+
}, z.core.$strip>>;
|
|
30
|
+
appId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
31
|
+
price: z.ZodOptional<z.ZodString>;
|
|
32
|
+
externalId: z.ZodNullable<z.ZodString>;
|
|
33
|
+
}, z.core.$strip>;
|
|
34
|
+
export declare const sellingPlanGroupSchema: z.ZodObject<{
|
|
35
|
+
appId: z.ZodNullable<z.ZodString>;
|
|
36
|
+
options: z.ZodArray<z.ZodObject<{
|
|
37
|
+
name: z.ZodString;
|
|
38
|
+
values: z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNull]>>;
|
|
39
|
+
}, z.core.$strip>>;
|
|
40
|
+
sellingPlans: z.ZodArray<z.ZodObject<{
|
|
41
|
+
id: z.ZodString;
|
|
42
|
+
name: z.ZodString;
|
|
43
|
+
description: z.ZodNullable<z.ZodString>;
|
|
44
|
+
optionValues: z.ZodArray<z.ZodObject<{
|
|
45
|
+
name: z.ZodOptional<z.ZodString>;
|
|
46
|
+
value: z.ZodString;
|
|
47
|
+
}, z.core.$strip>>;
|
|
48
|
+
priceAdjustments: z.ZodArray<z.ZodObject<{
|
|
49
|
+
value: z.ZodNumber;
|
|
50
|
+
valueType: z.ZodEnum<{
|
|
51
|
+
price: "price";
|
|
52
|
+
percentage: "percentage";
|
|
53
|
+
fixedAmount: "fixedAmount";
|
|
54
|
+
}>;
|
|
55
|
+
}, z.core.$strip>>;
|
|
56
|
+
appId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
57
|
+
price: z.ZodOptional<z.ZodString>;
|
|
58
|
+
externalId: z.ZodNullable<z.ZodString>;
|
|
59
|
+
}, z.core.$strip>>;
|
|
60
|
+
}, z.core.$strip>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { sellingPlanGroupSchema, sellingPlanOptionValueSchema, sellingPlanPriceAdjustmentSchema, sellingPlanSchema } from '../../chunk-4XLTENDR.mjs';
|
package/cart/buy-now-action.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
"use server";
|
|
2
2
|
import { headers } from "next/headers";
|
|
3
|
+
import { ReploError } from "../_vendor/schemas/errors.mjs";
|
|
3
4
|
import { v4 as uuidv4 } from "uuid";
|
|
4
5
|
import { z } from "zod";
|
|
5
6
|
import { getEnv } from "../env";
|
|
6
|
-
import { CanopyError } from "../lib/canopy-error";
|
|
7
7
|
import { getCheckoutProvider } from "../lib/integration-utils";
|
|
8
8
|
import { buildBaseUrl } from "../lib/url-utils";
|
|
9
9
|
import { createCartAction } from "./cart-actions";
|
|
10
10
|
import { REPLO_ATTRIBUTION_PROPERTY } from "./cart-types";
|
|
11
|
-
class BuyNowError extends
|
|
11
|
+
class BuyNowError extends ReploError {
|
|
12
12
|
}
|
|
13
|
-
class BuyNowCartCreationError extends
|
|
13
|
+
class BuyNowCartCreationError extends ReploError {
|
|
14
14
|
}
|
|
15
15
|
async function buyNowAction(input) {
|
|
16
16
|
const { lineItems, discountCodes, pageUrl } = input;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../cart/buy-now-action.ts"],
|
|
4
|
-
"sourcesContent": ["\"use server\";\n\nimport type { CartLineAttribute } from \"./cart-types\";\n\nimport { headers } from \"next/headers\";\n\nimport {
|
|
5
|
-
"mappings": ";AAIA,SAAS,eAAe;AAExB,SAAS,MAAM,cAAc;AAC7B,SAAS,SAAS;AAElB,SAAS,cAAc;AACvB,SAAS,
|
|
4
|
+
"sourcesContent": ["\"use server\";\n\nimport type { CartLineAttribute } from \"./cart-types\";\n\nimport { headers } from \"next/headers\";\n\nimport { ReploError } from \"schemas/errors\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport { z } from \"zod\";\n\nimport { getEnv } from \"../env\";\nimport { getCheckoutProvider } from \"../lib/integration-utils\";\nimport { buildBaseUrl } from \"../lib/url-utils\";\nimport { createCartAction } from \"./cart-actions\";\nimport { REPLO_ATTRIBUTION_PROPERTY } from \"./cart-types\";\n\nclass BuyNowError extends ReploError {}\nclass BuyNowCartCreationError extends ReploError {}\n\n/**\n * Server action that handles the full buy-now flow:\n * 1. For Shopify: creates a cart via the canopy-api-backed gateway, returns checkoutUrl.\n * 2. For Stripe: creates a Stripe checkout session via canopy-api, returns session URL.\n *\n * Variant IDs are expected to already be Storefront GIDs (from data loader output).\n * No internal\u2192external ID mapping is needed.\n */\nexport async function buyNowAction(input: {\n lineItems: {\n variantId: string;\n quantity: number;\n sellingPlanId: string | null;\n properties: CartLineAttribute[];\n }[];\n discountCodes: string[];\n pageUrl: string;\n}): Promise<{ redirectUrl: string }> {\n const { lineItems, discountCodes, pageUrl } = input;\n\n const headersList = await headers();\n const host = headersList.get(\"host\");\n if (!host) {\n throw new BuyNowError({ message: \"Missing host header\" });\n }\n const forwardedProto = headersList.get(\"x-forwarded-proto\");\n const protocol = forwardedProto?.split(\",\")[0]?.trim() ?? \"https\";\n const origin = `${protocol}://${host}`;\n\n const checkoutProvider = await getCheckoutProvider();\n\n const cartLines = lineItems.map((item) => {\n const hasReploAttribution = item.properties.some(\n (prop) => prop.key === REPLO_ATTRIBUTION_PROPERTY.key,\n );\n const properties = hasReploAttribution\n ? item.properties\n : [REPLO_ATTRIBUTION_PROPERTY, ...item.properties];\n\n return {\n id: item.variantId,\n quantity: item.quantity,\n sellingPlanId: item.sellingPlanId,\n properties,\n };\n });\n\n if (checkoutProvider === \"stripe\") {\n const env = await getEnv();\n const isSameOrigin = (() => {\n try {\n return Boolean(pageUrl) && new URL(pageUrl).origin === origin;\n } catch {\n return false;\n }\n })();\n const safePageUrl = isSameOrigin ? pageUrl : origin;\n const cancelUrl = safePageUrl;\n const returnUrl = safePageUrl;\n const temporaryCartId = uuidv4();\n\n const body = {\n cartId: temporaryCartId,\n lines: cartLines.map((line) => ({\n variantId: line.id,\n quantity: line.quantity,\n properties: line.properties,\n })),\n projectId: env.PROJECT_ID,\n successUrl: `${origin}/checkout/success?return_url=${encodeURIComponent(returnUrl)}`,\n cancelUrl,\n returnUrl,\n };\n\n const canopyApiUrl = `${buildBaseUrl(env.CANOPY_API_HOST)}/api/v1/stripe-checkout/create-session`;\n const response = await fetch(canopyApiUrl, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n throw new BuyNowCartCreationError({\n message: \"Failed to create Stripe checkout session for buy now\",\n additionalData: {\n status: response.status,\n statusText: response.statusText,\n },\n });\n }\n\n const data = z.object({ url: z.string() }).safeParse(await response.json());\n if (!data.success) {\n throw new BuyNowCartCreationError({\n message: \"Stripe checkout session response missing redirect URL\",\n cause: data.error,\n });\n }\n return { redirectUrl: data.data.url };\n }\n\n // Shopify and other integrations: create cart via canopy-api-backed gateway\n const cart = await createCartAction({\n lines: cartLines,\n skipStoringCart: true,\n discountCodes: discountCodes.length > 0 ? discountCodes : undefined,\n });\n\n if (!cart?.checkoutUrl) {\n throw new BuyNowCartCreationError({\n message: \"Failed to create cart or get checkout URL\",\n additionalData: { lineItems, discountCodes },\n });\n }\n\n const checkoutUrl = new URL(cart.checkoutUrl, origin);\n return { redirectUrl: checkoutUrl.toString() };\n}\n"],
|
|
5
|
+
"mappings": ";AAIA,SAAS,eAAe;AAExB,SAAS,kBAAkB;AAC3B,SAAS,MAAM,cAAc;AAC7B,SAAS,SAAS;AAElB,SAAS,cAAc;AACvB,SAAS,2BAA2B;AACpC,SAAS,oBAAoB;AAC7B,SAAS,wBAAwB;AACjC,SAAS,kCAAkC;AAE3C,MAAM,oBAAoB,WAAW;AAAC;AACtC,MAAM,gCAAgC,WAAW;AAAC;AAUlD,eAAsB,aAAa,OASE;AACnC,QAAM,EAAE,WAAW,eAAe,QAAQ,IAAI;AAE9C,QAAM,cAAc,MAAM,QAAQ;AAClC,QAAM,OAAO,YAAY,IAAI,MAAM;AACnC,MAAI,CAAC,MAAM;AACT,UAAM,IAAI,YAAY,EAAE,SAAS,sBAAsB,CAAC;AAAA,EAC1D;AACA,QAAM,iBAAiB,YAAY,IAAI,mBAAmB;AAC1D,QAAM,WAAW,gBAAgB,MAAM,GAAG,EAAE,CAAC,GAAG,KAAK,KAAK;AAC1D,QAAM,SAAS,GAAG,QAAQ,MAAM,IAAI;AAEpC,QAAM,mBAAmB,MAAM,oBAAoB;AAEnD,QAAM,YAAY,UAAU,IAAI,CAAC,SAAS;AACxC,UAAM,sBAAsB,KAAK,WAAW;AAAA,MAC1C,CAAC,SAAS,KAAK,QAAQ,2BAA2B;AAAA,IACpD;AACA,UAAM,aAAa,sBACf,KAAK,aACL,CAAC,4BAA4B,GAAG,KAAK,UAAU;AAEnD,WAAO;AAAA,MACL,IAAI,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SAAS;AAAA,QACT,OAAO,KAAK;AAAA,MACd,CAAC;AAAA,IACH;AACA,WAAO,EAAE,aAAa,KAAK,KAAK,IAAI;AAAA,EACtC;AAGA,QAAM,OAAO,MAAM,iBAAiB;AAAA,IAClC,OAAO;AAAA,IACP,iBAAiB;AAAA,IACjB,eAAe,cAAc,SAAS,IAAI,gBAAgB;AAAA,EAC5D,CAAC;AAED,MAAI,CAAC,MAAM,aAAa;AACtB,UAAM,IAAI,wBAAwB;AAAA,MAChC,SAAS;AAAA,MACT,gBAAgB,EAAE,WAAW,cAAc;AAAA,IAC7C,CAAC;AAAA,EACH;AAEA,QAAM,cAAc,IAAI,IAAI,KAAK,aAAa,MAAM;AACpD,SAAO,EAAE,aAAa,YAAY,SAAS,EAAE;AAC/C;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/cart/cart-provider.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { jsx } from "react/jsx-runtime";
|
|
3
3
|
import React from "react";
|
|
4
|
+
import { ReploError } from "../_vendor/schemas/errors.mjs";
|
|
4
5
|
import { v4 as uuidv4 } from "uuid";
|
|
5
6
|
import { useAnalyticsOptional } from "../analytics/analytics-provider";
|
|
6
|
-
import { CanopyError } from "../lib/canopy-error";
|
|
7
7
|
import {
|
|
8
8
|
addToCartAction,
|
|
9
9
|
createCartAction,
|
|
@@ -13,7 +13,7 @@ import {
|
|
|
13
13
|
updateCartLineItemAction
|
|
14
14
|
} from "./cart-actions";
|
|
15
15
|
import { createOptimisticSellingPlanAllocation } from "./utils/variant-to-cart-line";
|
|
16
|
-
class CartContextError extends
|
|
16
|
+
class CartContextError extends ReploError {
|
|
17
17
|
}
|
|
18
18
|
const isEditorMode = () => {
|
|
19
19
|
if (typeof window === "undefined") {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../cart/cart-provider.tsx"],
|
|
4
|
-
"sourcesContent": ["/**\n * Use useCart() hook to access cart UI state (itemsCount, isCartOpen, openCart, closeCart). For adding products to cart, use useAddToCart. For buy now functionality, use useBuyNow.\n * @module\n */\n\"use client\";\n\nimport type { Cart, CartLine, CartLinePayload } from \"./cart-types\";\n\nimport React from \"react\";\n\nimport { v4 as uuidv4 } from \"uuid\";\n\nimport { useAnalyticsOptional } from \"../analytics/analytics-provider\";\nimport { CanopyError } from \"../lib/canopy-error\";\nimport {\n addToCartAction,\n createCartAction,\n getOrCreateCartAction,\n removeCartLineItemsAction,\n updateCartDiscountCodesAction,\n updateCartLineItemAction,\n} from \"./cart-actions\";\nimport { createOptimisticSellingPlanAllocation } from \"./utils/variant-to-cart-line\";\n\nclass CartContextError extends CanopyError {}\n\n/**\n * Detects if the app is running in editor mode (iframe).\n *\n * @returns True if running in an iframe (editor mode)\n */\nconst isEditorMode = () => {\n if (typeof window === \"undefined\") {\n return false;\n }\n\n return window.parent !== window;\n};\n\n// Global promise to prevent multiple cart creation attempts\nlet cartCreationPromise: Promise<Cart | null> | null = null;\n\n/**\n * Client-side cart operation to add a line item. Used in editor mode.\n * Merges with existing lines if they match by merchandise ID and selling plan.\n *\n * @param cart - The cart to add the line to\n * @param line - The cart line payload to add\n * @returns The updated cart\n */\nfunction addLineToCart(cart: Cart, line: CartLinePayload): Cart {\n const existingLineIndex = cart.lines.findIndex((existingLine) => {\n return (\n existingLine.merchandise?.id === line.id &&\n // Distinguish by selling plan to avoid merging subscription with one-time\n (line.sellingPlanId ?? null) ===\n (existingLine.sellingPlanAllocation?.sellingPlan.id ?? null)\n );\n });\n\n if (existingLineIndex >= 0) {\n // Update existing line\n const updatedLines = [...cart.lines];\n updatedLines[existingLineIndex] = {\n ...updatedLines[existingLineIndex]!,\n quantity: updatedLines[existingLineIndex]!.quantity + line.quantity,\n };\n return { ...cart, lines: updatedLines };\n } else {\n const optimisticSellingPlanAllocation =\n line.sellingPlanId && line.merchandise\n ? createOptimisticSellingPlanAllocation({\n merchandise: line.merchandise,\n sellingPlanId: line.sellingPlanId,\n currencyCode: cart.cost?.currencyCode ?? \"USD\",\n })\n : null;\n\n const newLine: CartLine = {\n id: `temp-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`,\n quantity: line.quantity,\n merchandise: line.merchandise ?? null,\n attributes: line.properties ?? [],\n sellingPlanAllocation: optimisticSellingPlanAllocation,\n };\n return { ...cart, lines: [newLine, ...cart.lines] };\n }\n}\n\n/**\n * Client-side cart operation to update a line item. Used in editor mode.\n *\n * @param cart - The cart containing the line to update\n * @param line - The cart line payload with updated values\n * @returns The updated cart\n */\nfunction updateLineInCart(cart: Cart, line: CartLinePayload): Cart {\n const updatedLines = cart.lines.map((existingLine) => {\n return existingLine.id === line.id\n ? { ...existingLine, quantity: line.quantity }\n : existingLine;\n });\n return { ...cart, lines: updatedLines };\n}\n\n/**\n * Client-side cart operation to remove a line item. Used in editor mode.\n *\n * @param cart - The cart containing the line to remove\n * @param lineId - The ID of the line to remove\n * @returns The updated cart\n */\nfunction removeLineFromCart(cart: Cart, lineId: string): Cart {\n const updatedLines = cart.lines.filter((line) => line.id !== lineId);\n return { ...cart, lines: updatedLines };\n}\n\n/**\n * Internal cart context type with full functionality.\n * This is for internal use only - external code should use the limited CartContextType.\n */\nexport interface CartContextTypeInternal {\n /** The current cart (can be null) */\n cartData: Cart | null;\n /** Array of cart line items */\n lineItems: CartLine[];\n /** Total price of all items */\n subtotal: number;\n /** Total number of items in cart */\n itemsCount: number;\n /** Currency code for the cart */\n currencyCode: string;\n /** Function to add items to cart */\n addToCart: (\n lines: CartLinePayload[],\n openCartAfterAdd?: boolean,\n ) => Promise<void>;\n /** Function to update cart item quantity */\n updateCartItem: (line: CartLinePayload) => Promise<void>;\n /** Function to remove item from cart */\n removeCartItem: (lineId: string) => Promise<void>;\n /** Function to update discount codes on cart */\n updateDiscountCodes: (discountCodes: string[]) => Promise<void>;\n /** Function to create cart and checkout immediately */\n buyNow: (\n lines: CartLinePayload[],\n discountCodes?: string[],\n ) => Promise<Cart | null>;\n /** URL to redirect to checkout */\n checkoutUrl: string;\n /** Whether the cart UI is open */\n isCartOpen: boolean;\n /** Function to open the cart UI */\n openCart: () => void;\n /** Function to close the cart UI */\n closeCart: () => void;\n}\n\n// NOTE (Gabe, 2026-01-08): We intentionally duplicate properties from CartContextTypeInternal\n// rather than using Pick<> so that TypeDoc generates expanded documentation for each property.\n/**\n * Public cart context type for LLM use.\n * For adding products to cart, use useAddToCart.\n * For buy now functionality, use useBuyNow.\n */\nexport interface CartContextType {\n /** Total number of items in cart */\n itemsCount: number;\n /** Whether the cart UI is open */\n isCartOpen: boolean;\n /** Function to open the cart UI */\n openCart: () => void;\n /** Function to close the cart UI */\n closeCart: () => void;\n /** Function to update discount codes on cart */\n updateDiscountCodes: (discountCodes: string[]) => Promise<void>;\n}\n\nconst CartContext = React.createContext<CartContextTypeInternal | undefined>(\n undefined,\n);\n\n/**\n * Provider component that manages global cart state and operations. Handles both\n * server-side cart synchronization and client-side optimistic updates. Supports\n * editor mode for preview environments.\n *\n * @returns A context provider wrapping the children with cart functionality\n */\nexport function CartProvider({\n children,\n cart,\n}: React.PropsWithChildren<{\n /** Initial cart data from the server (can be null) */\n cart: Cart | null;\n}>) {\n const [cartData, setCartData] = React.useState<Cart | null>(cart);\n const [isCartOpen, setIsCartOpen] = React.useState(false);\n const hasInitialized = React.useRef(false);\n const analytics = useAnalyticsOptional();\n\n // Initialize cart on mount\n // eslint-disable-next-line replo/no-use-effect -- Legacy effect - may or may not be necessary\n React.useEffect(() => {\n // Early exit if already initialized\n if (hasInitialized.current) {\n return;\n }\n\n // If there's already a creation in progress, attach to it\n if (cartCreationPromise) {\n void cartCreationPromise.then((cart) => {\n if (cart) {\n setCartData(cart);\n }\n });\n return;\n }\n\n // Mark as initialized to prevent duplicate calls\n hasInitialized.current = true;\n\n // Get existing cart or create new one\n cartCreationPromise = getOrCreateCartAction()\n .then((cart) => {\n if (cart) {\n setCartData(cart);\n } else {\n console.warn(\n \"[Replo] Failed to get or create cart on the server. Reach out to support@replo.app if this persists.\",\n );\n }\n return cart;\n })\n .catch((error) => {\n console.error(\"[Replo] Error getting or creating cart:\", error);\n return null;\n })\n .finally(() => {\n // Reset the promise after completion\n cartCreationPromise = null;\n });\n }, []);\n\n // Derived values - handle null cart gracefully\n const lineItems = cartData?.lines ?? [];\n\n const subtotal =\n cartData?.lines.reduce((sum, lineItem) => {\n if (lineItem.quantity > 0 && lineItem.merchandise) {\n sum += lineItem.merchandise.price * lineItem.quantity;\n }\n return sum;\n }, 0) ?? 0;\n\n const itemsCount =\n cartData?.lines.reduce((sum, lineItem) => {\n if (lineItem.quantity > 0) {\n sum += lineItem.quantity;\n }\n return sum;\n }, 0) ?? 0;\n\n // Cart UI state functions\n const openCart = React.useCallback(() => {\n setIsCartOpen(true);\n\n if (analytics) {\n void analytics.viewCart({\n data: {\n itemCount: itemsCount,\n subtotal,\n currency: cartData?.cost.currencyCode,\n lineItems: cartData?.lines.flatMap((item) => {\n if (!item.merchandise) {\n return [];\n }\n return [\n {\n productId: item.merchandise.product.id,\n variantId: item.merchandise.id,\n quantity: item.quantity,\n price: item.merchandise.price,\n },\n ];\n }),\n },\n });\n }\n }, [analytics, cartData, itemsCount, subtotal]);\n\n const closeCart = React.useCallback(() => {\n setIsCartOpen(false);\n }, []);\n\n // Track the latest update request to avoid updating with stale responses\n const latestUpdateRequestId = React.useRef<string | null>(null);\n\n const addToCart = async (\n lines: CartLinePayload[],\n openCartAfterAdd: boolean = true,\n ) => {\n // If no cart exists, we can't add to it\n if (!cartData) {\n console.warn(\n \"[Replo] Cannot add to cart: no cart exists. Reach out to support@replo.app if this persists.\",\n );\n return;\n }\n\n // Optimistic update - use functional form to avoid stale state\n setCartData((currentCart) => {\n if (!currentCart) {\n return null;\n }\n let updatedCart = { ...currentCart };\n for (const line of lines) {\n updatedCart = addLineToCart(updatedCart, line);\n }\n return updatedCart;\n });\n\n if (openCartAfterAdd) {\n openCart();\n }\n\n if (analytics) {\n for (const line of lines) {\n if (!line.merchandise) {\n continue;\n }\n void analytics.addToCart({\n data: {\n productId: line.merchandise.product.id,\n variantId: line.merchandise.id,\n quantity: line.quantity,\n price: line.merchandise.price,\n currency: cartData?.cost.currencyCode,\n productTitle: line.merchandise.product.title,\n variantTitle: line.merchandise.title,\n },\n });\n }\n }\n\n // Direct server update (no debouncing)\n const serverCart = await addToCartAction(lines, cartData.id);\n if (serverCart) {\n setCartData(serverCart);\n } else {\n console.warn(\n \"[Replo] Failed to add item to cart on server. Cart may be out of sync. Reach out to support@replo.app if this persists.\",\n );\n }\n };\n\n const updateCartItem = async (line: CartLinePayload) => {\n // If no cart exists, we can't update it\n if (!cartData) {\n console.warn(\n \"[Replo] Cannot update cart item: no cart exists. Reach out to support@replo.app if this persists.\",\n );\n return;\n }\n\n // Generate a unique request ID for this update\n const requestId = uuidv4();\n latestUpdateRequestId.current = requestId;\n\n // Optimistic update - use functional form to avoid stale state\n setCartData((currentCart) => {\n if (!currentCart) {\n return null;\n }\n return updateLineInCart(currentCart, line);\n });\n\n // Server update\n const serverCart = await updateCartLineItemAction(line, cartData.id);\n\n // Only update if this is still the latest request\n if (latestUpdateRequestId.current === requestId) {\n if (serverCart) {\n setCartData(serverCart);\n } else {\n console.warn(\n \"[Replo] Failed to update cart item on server. Cart may be out of sync. Reach out to support@replo.app if this persists.\",\n );\n }\n }\n };\n\n const removeCartItem = async (lineId: string) => {\n if (!cartData) {\n console.warn(\n \"[Replo] Cannot remove cart item: no cart exists. Reach out to support@replo.app if this persists.\",\n );\n return;\n }\n\n const itemToRemove = cartData.lines.find((item) => item.id === lineId);\n if (analytics && itemToRemove && itemToRemove.merchandise) {\n void analytics.removeFromCart({\n data: {\n productId: itemToRemove.merchandise.product.id,\n variantId: itemToRemove.merchandise.id,\n quantity: itemToRemove.quantity,\n price: itemToRemove.merchandise.price,\n currency: cartData.cost.currencyCode,\n productTitle: itemToRemove.merchandise.product.title,\n variantTitle: itemToRemove.merchandise.title,\n },\n });\n }\n\n // Optimistic update - use functional form to avoid stale state\n setCartData((currentCart) => {\n if (!currentCart) {\n return null;\n }\n return removeLineFromCart(currentCart, lineId);\n });\n\n // Direct server update (no debouncing)\n const serverCart = await removeCartLineItemsAction([lineId], cartData.id);\n if (serverCart) {\n setCartData(serverCart);\n } else {\n console.warn(\n \"[Replo] Failed to remove cart item on server. Cart may be out of sync. Reach out to support@replo.app if this persists.\",\n );\n }\n };\n\n const updateDiscountCodes = async (discountCodes: string[]) => {\n // If no cart exists, we can't update discount codes\n if (!cartData) {\n console.warn(\n \"[Replo] Cannot update discount codes: no cart exists. Reach out to support@replo.app if this persists.\",\n );\n return;\n }\n\n // Optimistic update - use functional form to avoid stale state\n setCartData((currentCart) => {\n if (!currentCart) {\n return null;\n }\n return {\n ...currentCart,\n discountCodes: discountCodes.map((code) => ({\n code,\n applicable: true,\n })),\n };\n });\n\n // Server update\n const serverCart = await updateCartDiscountCodesAction(\n discountCodes,\n cartData.id,\n );\n if (serverCart) {\n setCartData(serverCart);\n } else {\n console.warn(\n \"[Replo] Failed to update discount codes on server. Cart may be out of sync. Reach out to support@replo.app if this persists.\",\n );\n }\n };\n\n const buyNow = async (lines: CartLinePayload[], discountCodes?: string[]) => {\n // Create a new cart with the specified lines and discount codes\n const cart = await createCartAction({\n lines,\n skipStoringCart: true,\n discountCodes,\n });\n if (cart) {\n return cart;\n } else {\n console.warn(\n \"[Replo] Failed to create cart for buy now. Reach out to support@replo.app if this persists.\",\n );\n return null;\n }\n };\n\n const checkoutUrl: string = (() => {\n if (isEditorMode()) {\n return \"/\";\n }\n\n return cartData?.checkoutUrl ?? \"/\";\n })();\n\n return (\n <CartContext.Provider\n value={{\n cartData,\n lineItems,\n subtotal,\n itemsCount,\n currencyCode: cartData?.cost.currencyCode ?? \"USD\",\n addToCart,\n updateCartItem,\n removeCartItem,\n updateDiscountCodes,\n buyNow,\n checkoutUrl,\n isCartOpen,\n openCart,\n closeCart,\n }}\n >\n {children}\n </CartContext.Provider>\n );\n}\n\n/**\n * @deprecated For internal use only. Use useAddToCart or useBuyNow\n * for cart operations. Use useCart for cart UI state (itemsCount, openCart, closeCart).\n */\nexport function useCartInternal(): CartContextTypeInternal {\n const context = React.useContext(CartContext);\n if (context === undefined) {\n throw new CartContextError({\n message: \"useCartInternal must be used within a CartProvider\",\n });\n }\n return context;\n}\n\n/**\n * Hook to access cart UI state and controls. For adding products to cart,\n * use useAddToCart. For buy now functionality, use useBuyNow.\n *\n * @example\n * ```tsx\n * import { useCart } from \"canopy-sdk/cart/cart-provider\";\n *\n * function MyComponent() {\n * const { itemsCount, openCart } = useCart();\n * ...\n * }\n * ```\n * @throws Error if used outside of a CartProvider\n */\nexport function useCart(): CartContextType {\n const context = React.useContext(CartContext);\n if (context === undefined) {\n throw new CartContextError({\n message: \"useCart must be used within a CartProvider\",\n });\n }\n return {\n itemsCount: context.itemsCount,\n isCartOpen: context.isCartOpen,\n openCart: context.openCart,\n closeCart: context.closeCart,\n updateDiscountCodes: context.updateDiscountCodes,\n };\n}\n"],
|
|
5
|
-
"mappings": ";AAifI;AAzeJ,OAAO,WAAW;AAElB,SAAS,MAAM,cAAc;AAE7B,SAAS,4BAA4B;AACrC
|
|
4
|
+
"sourcesContent": ["/**\n * Use useCart() hook to access cart UI state (itemsCount, isCartOpen, openCart, closeCart). For adding products to cart, use useAddToCart. For buy now functionality, use useBuyNow.\n * @module\n */\n\"use client\";\n\nimport type { Cart, CartLine, CartLinePayload } from \"./cart-types\";\n\nimport React from \"react\";\n\nimport { ReploError } from \"schemas/errors\";\nimport { v4 as uuidv4 } from \"uuid\";\n\nimport { useAnalyticsOptional } from \"../analytics/analytics-provider\";\nimport {\n addToCartAction,\n createCartAction,\n getOrCreateCartAction,\n removeCartLineItemsAction,\n updateCartDiscountCodesAction,\n updateCartLineItemAction,\n} from \"./cart-actions\";\nimport { createOptimisticSellingPlanAllocation } from \"./utils/variant-to-cart-line\";\n\nclass CartContextError extends ReploError {}\n\n/**\n * Detects if the app is running in editor mode (iframe).\n *\n * @returns True if running in an iframe (editor mode)\n */\nconst isEditorMode = () => {\n if (typeof window === \"undefined\") {\n return false;\n }\n\n return window.parent !== window;\n};\n\n// Global promise to prevent multiple cart creation attempts\nlet cartCreationPromise: Promise<Cart | null> | null = null;\n\n/**\n * Client-side cart operation to add a line item. Used in editor mode.\n * Merges with existing lines if they match by merchandise ID and selling plan.\n *\n * @param cart - The cart to add the line to\n * @param line - The cart line payload to add\n * @returns The updated cart\n */\nfunction addLineToCart(cart: Cart, line: CartLinePayload): Cart {\n const existingLineIndex = cart.lines.findIndex((existingLine) => {\n return (\n existingLine.merchandise?.id === line.id &&\n // Distinguish by selling plan to avoid merging subscription with one-time\n (line.sellingPlanId ?? null) ===\n (existingLine.sellingPlanAllocation?.sellingPlan.id ?? null)\n );\n });\n\n if (existingLineIndex >= 0) {\n // Update existing line\n const updatedLines = [...cart.lines];\n updatedLines[existingLineIndex] = {\n ...updatedLines[existingLineIndex]!,\n quantity: updatedLines[existingLineIndex]!.quantity + line.quantity,\n };\n return { ...cart, lines: updatedLines };\n } else {\n const optimisticSellingPlanAllocation =\n line.sellingPlanId && line.merchandise\n ? createOptimisticSellingPlanAllocation({\n merchandise: line.merchandise,\n sellingPlanId: line.sellingPlanId,\n currencyCode: cart.cost?.currencyCode ?? \"USD\",\n })\n : null;\n\n const newLine: CartLine = {\n id: `temp-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`,\n quantity: line.quantity,\n merchandise: line.merchandise ?? null,\n attributes: line.properties ?? [],\n sellingPlanAllocation: optimisticSellingPlanAllocation,\n };\n return { ...cart, lines: [newLine, ...cart.lines] };\n }\n}\n\n/**\n * Client-side cart operation to update a line item. Used in editor mode.\n *\n * @param cart - The cart containing the line to update\n * @param line - The cart line payload with updated values\n * @returns The updated cart\n */\nfunction updateLineInCart(cart: Cart, line: CartLinePayload): Cart {\n const updatedLines = cart.lines.map((existingLine) => {\n return existingLine.id === line.id\n ? { ...existingLine, quantity: line.quantity }\n : existingLine;\n });\n return { ...cart, lines: updatedLines };\n}\n\n/**\n * Client-side cart operation to remove a line item. Used in editor mode.\n *\n * @param cart - The cart containing the line to remove\n * @param lineId - The ID of the line to remove\n * @returns The updated cart\n */\nfunction removeLineFromCart(cart: Cart, lineId: string): Cart {\n const updatedLines = cart.lines.filter((line) => line.id !== lineId);\n return { ...cart, lines: updatedLines };\n}\n\n/**\n * Internal cart context type with full functionality.\n * This is for internal use only - external code should use the limited CartContextType.\n */\nexport interface CartContextTypeInternal {\n /** The current cart (can be null) */\n cartData: Cart | null;\n /** Array of cart line items */\n lineItems: CartLine[];\n /** Total price of all items */\n subtotal: number;\n /** Total number of items in cart */\n itemsCount: number;\n /** Currency code for the cart */\n currencyCode: string;\n /** Function to add items to cart */\n addToCart: (\n lines: CartLinePayload[],\n openCartAfterAdd?: boolean,\n ) => Promise<void>;\n /** Function to update cart item quantity */\n updateCartItem: (line: CartLinePayload) => Promise<void>;\n /** Function to remove item from cart */\n removeCartItem: (lineId: string) => Promise<void>;\n /** Function to update discount codes on cart */\n updateDiscountCodes: (discountCodes: string[]) => Promise<void>;\n /** Function to create cart and checkout immediately */\n buyNow: (\n lines: CartLinePayload[],\n discountCodes?: string[],\n ) => Promise<Cart | null>;\n /** URL to redirect to checkout */\n checkoutUrl: string;\n /** Whether the cart UI is open */\n isCartOpen: boolean;\n /** Function to open the cart UI */\n openCart: () => void;\n /** Function to close the cart UI */\n closeCart: () => void;\n}\n\n// NOTE (Gabe, 2026-01-08): We intentionally duplicate properties from CartContextTypeInternal\n// rather than using Pick<> so that TypeDoc generates expanded documentation for each property.\n/**\n * Public cart context type for LLM use.\n * For adding products to cart, use useAddToCart.\n * For buy now functionality, use useBuyNow.\n */\nexport interface CartContextType {\n /** Total number of items in cart */\n itemsCount: number;\n /** Whether the cart UI is open */\n isCartOpen: boolean;\n /** Function to open the cart UI */\n openCart: () => void;\n /** Function to close the cart UI */\n closeCart: () => void;\n /** Function to update discount codes on cart */\n updateDiscountCodes: (discountCodes: string[]) => Promise<void>;\n}\n\nconst CartContext = React.createContext<CartContextTypeInternal | undefined>(\n undefined,\n);\n\n/**\n * Provider component that manages global cart state and operations. Handles both\n * server-side cart synchronization and client-side optimistic updates. Supports\n * editor mode for preview environments.\n *\n * @returns A context provider wrapping the children with cart functionality\n */\nexport function CartProvider({\n children,\n cart,\n}: React.PropsWithChildren<{\n /** Initial cart data from the server (can be null) */\n cart: Cart | null;\n}>) {\n const [cartData, setCartData] = React.useState<Cart | null>(cart);\n const [isCartOpen, setIsCartOpen] = React.useState(false);\n const hasInitialized = React.useRef(false);\n const analytics = useAnalyticsOptional();\n\n // Initialize cart on mount\n // eslint-disable-next-line replo/no-use-effect -- Legacy effect - may or may not be necessary\n React.useEffect(() => {\n // Early exit if already initialized\n if (hasInitialized.current) {\n return;\n }\n\n // If there's already a creation in progress, attach to it\n if (cartCreationPromise) {\n void cartCreationPromise.then((cart) => {\n if (cart) {\n setCartData(cart);\n }\n });\n return;\n }\n\n // Mark as initialized to prevent duplicate calls\n hasInitialized.current = true;\n\n // Get existing cart or create new one\n cartCreationPromise = getOrCreateCartAction()\n .then((cart) => {\n if (cart) {\n setCartData(cart);\n } else {\n console.warn(\n \"[Replo] Failed to get or create cart on the server. Reach out to support@replo.app if this persists.\",\n );\n }\n return cart;\n })\n .catch((error) => {\n console.error(\"[Replo] Error getting or creating cart:\", error);\n return null;\n })\n .finally(() => {\n // Reset the promise after completion\n cartCreationPromise = null;\n });\n }, []);\n\n // Derived values - handle null cart gracefully\n const lineItems = cartData?.lines ?? [];\n\n const subtotal =\n cartData?.lines.reduce((sum, lineItem) => {\n if (lineItem.quantity > 0 && lineItem.merchandise) {\n sum += lineItem.merchandise.price * lineItem.quantity;\n }\n return sum;\n }, 0) ?? 0;\n\n const itemsCount =\n cartData?.lines.reduce((sum, lineItem) => {\n if (lineItem.quantity > 0) {\n sum += lineItem.quantity;\n }\n return sum;\n }, 0) ?? 0;\n\n // Cart UI state functions\n const openCart = React.useCallback(() => {\n setIsCartOpen(true);\n\n if (analytics) {\n void analytics.viewCart({\n data: {\n itemCount: itemsCount,\n subtotal,\n currency: cartData?.cost.currencyCode,\n lineItems: cartData?.lines.flatMap((item) => {\n if (!item.merchandise) {\n return [];\n }\n return [\n {\n productId: item.merchandise.product.id,\n variantId: item.merchandise.id,\n quantity: item.quantity,\n price: item.merchandise.price,\n },\n ];\n }),\n },\n });\n }\n }, [analytics, cartData, itemsCount, subtotal]);\n\n const closeCart = React.useCallback(() => {\n setIsCartOpen(false);\n }, []);\n\n // Track the latest update request to avoid updating with stale responses\n const latestUpdateRequestId = React.useRef<string | null>(null);\n\n const addToCart = async (\n lines: CartLinePayload[],\n openCartAfterAdd: boolean = true,\n ) => {\n // If no cart exists, we can't add to it\n if (!cartData) {\n console.warn(\n \"[Replo] Cannot add to cart: no cart exists. Reach out to support@replo.app if this persists.\",\n );\n return;\n }\n\n // Optimistic update - use functional form to avoid stale state\n setCartData((currentCart) => {\n if (!currentCart) {\n return null;\n }\n let updatedCart = { ...currentCart };\n for (const line of lines) {\n updatedCart = addLineToCart(updatedCart, line);\n }\n return updatedCart;\n });\n\n if (openCartAfterAdd) {\n openCart();\n }\n\n if (analytics) {\n for (const line of lines) {\n if (!line.merchandise) {\n continue;\n }\n void analytics.addToCart({\n data: {\n productId: line.merchandise.product.id,\n variantId: line.merchandise.id,\n quantity: line.quantity,\n price: line.merchandise.price,\n currency: cartData?.cost.currencyCode,\n productTitle: line.merchandise.product.title,\n variantTitle: line.merchandise.title,\n },\n });\n }\n }\n\n // Direct server update (no debouncing)\n const serverCart = await addToCartAction(lines, cartData.id);\n if (serverCart) {\n setCartData(serverCart);\n } else {\n console.warn(\n \"[Replo] Failed to add item to cart on server. Cart may be out of sync. Reach out to support@replo.app if this persists.\",\n );\n }\n };\n\n const updateCartItem = async (line: CartLinePayload) => {\n // If no cart exists, we can't update it\n if (!cartData) {\n console.warn(\n \"[Replo] Cannot update cart item: no cart exists. Reach out to support@replo.app if this persists.\",\n );\n return;\n }\n\n // Generate a unique request ID for this update\n const requestId = uuidv4();\n latestUpdateRequestId.current = requestId;\n\n // Optimistic update - use functional form to avoid stale state\n setCartData((currentCart) => {\n if (!currentCart) {\n return null;\n }\n return updateLineInCart(currentCart, line);\n });\n\n // Server update\n const serverCart = await updateCartLineItemAction(line, cartData.id);\n\n // Only update if this is still the latest request\n if (latestUpdateRequestId.current === requestId) {\n if (serverCart) {\n setCartData(serverCart);\n } else {\n console.warn(\n \"[Replo] Failed to update cart item on server. Cart may be out of sync. Reach out to support@replo.app if this persists.\",\n );\n }\n }\n };\n\n const removeCartItem = async (lineId: string) => {\n if (!cartData) {\n console.warn(\n \"[Replo] Cannot remove cart item: no cart exists. Reach out to support@replo.app if this persists.\",\n );\n return;\n }\n\n const itemToRemove = cartData.lines.find((item) => item.id === lineId);\n if (analytics && itemToRemove && itemToRemove.merchandise) {\n void analytics.removeFromCart({\n data: {\n productId: itemToRemove.merchandise.product.id,\n variantId: itemToRemove.merchandise.id,\n quantity: itemToRemove.quantity,\n price: itemToRemove.merchandise.price,\n currency: cartData.cost.currencyCode,\n productTitle: itemToRemove.merchandise.product.title,\n variantTitle: itemToRemove.merchandise.title,\n },\n });\n }\n\n // Optimistic update - use functional form to avoid stale state\n setCartData((currentCart) => {\n if (!currentCart) {\n return null;\n }\n return removeLineFromCart(currentCart, lineId);\n });\n\n // Direct server update (no debouncing)\n const serverCart = await removeCartLineItemsAction([lineId], cartData.id);\n if (serverCart) {\n setCartData(serverCart);\n } else {\n console.warn(\n \"[Replo] Failed to remove cart item on server. Cart may be out of sync. Reach out to support@replo.app if this persists.\",\n );\n }\n };\n\n const updateDiscountCodes = async (discountCodes: string[]) => {\n // If no cart exists, we can't update discount codes\n if (!cartData) {\n console.warn(\n \"[Replo] Cannot update discount codes: no cart exists. Reach out to support@replo.app if this persists.\",\n );\n return;\n }\n\n // Optimistic update - use functional form to avoid stale state\n setCartData((currentCart) => {\n if (!currentCart) {\n return null;\n }\n return {\n ...currentCart,\n discountCodes: discountCodes.map((code) => ({\n code,\n applicable: true,\n })),\n };\n });\n\n // Server update\n const serverCart = await updateCartDiscountCodesAction(\n discountCodes,\n cartData.id,\n );\n if (serverCart) {\n setCartData(serverCart);\n } else {\n console.warn(\n \"[Replo] Failed to update discount codes on server. Cart may be out of sync. Reach out to support@replo.app if this persists.\",\n );\n }\n };\n\n const buyNow = async (lines: CartLinePayload[], discountCodes?: string[]) => {\n // Create a new cart with the specified lines and discount codes\n const cart = await createCartAction({\n lines,\n skipStoringCart: true,\n discountCodes,\n });\n if (cart) {\n return cart;\n } else {\n console.warn(\n \"[Replo] Failed to create cart for buy now. Reach out to support@replo.app if this persists.\",\n );\n return null;\n }\n };\n\n const checkoutUrl: string = (() => {\n if (isEditorMode()) {\n return \"/\";\n }\n\n return cartData?.checkoutUrl ?? \"/\";\n })();\n\n return (\n <CartContext.Provider\n value={{\n cartData,\n lineItems,\n subtotal,\n itemsCount,\n currencyCode: cartData?.cost.currencyCode ?? \"USD\",\n addToCart,\n updateCartItem,\n removeCartItem,\n updateDiscountCodes,\n buyNow,\n checkoutUrl,\n isCartOpen,\n openCart,\n closeCart,\n }}\n >\n {children}\n </CartContext.Provider>\n );\n}\n\n/**\n * @deprecated For internal use only. Use useAddToCart or useBuyNow\n * for cart operations. Use useCart for cart UI state (itemsCount, openCart, closeCart).\n */\nexport function useCartInternal(): CartContextTypeInternal {\n const context = React.useContext(CartContext);\n if (context === undefined) {\n throw new CartContextError({\n message: \"useCartInternal must be used within a CartProvider\",\n });\n }\n return context;\n}\n\n/**\n * Hook to access cart UI state and controls. For adding products to cart,\n * use useAddToCart. For buy now functionality, use useBuyNow.\n *\n * @example\n * ```tsx\n * import { useCart } from \"canopy-sdk/cart/cart-provider\";\n *\n * function MyComponent() {\n * const { itemsCount, openCart } = useCart();\n * ...\n * }\n * ```\n * @throws Error if used outside of a CartProvider\n */\nexport function useCart(): CartContextType {\n const context = React.useContext(CartContext);\n if (context === undefined) {\n throw new CartContextError({\n message: \"useCart must be used within a CartProvider\",\n });\n }\n return {\n itemsCount: context.itemsCount,\n isCartOpen: context.isCartOpen,\n openCart: context.openCart,\n closeCart: context.closeCart,\n updateDiscountCodes: context.updateDiscountCodes,\n };\n}\n"],
|
|
5
|
+
"mappings": ";AAifI;AAzeJ,OAAO,WAAW;AAElB,SAAS,kBAAkB;AAC3B,SAAS,MAAM,cAAc;AAE7B,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,6CAA6C;AAEtD,MAAM,yBAAyB,WAAW;AAAC;AAO3C,MAAM,eAAe,MAAM;AACzB,MAAI,OAAO,WAAW,aAAa;AACjC,WAAO;AAAA,EACT;AAEA,SAAO,OAAO,WAAW;AAC3B;AAGA,IAAI,sBAAmD;AAUvD,SAAS,cAAc,MAAY,MAA6B;AAC9D,QAAM,oBAAoB,KAAK,MAAM,UAAU,CAAC,iBAAiB;AAC/D,WACE,aAAa,aAAa,OAAO,KAAK;AAAA,KAErC,KAAK,iBAAiB,WACpB,aAAa,uBAAuB,YAAY,MAAM;AAAA,EAE7D,CAAC;AAED,MAAI,qBAAqB,GAAG;AAE1B,UAAM,eAAe,CAAC,GAAG,KAAK,KAAK;AACnC,iBAAa,iBAAiB,IAAI;AAAA,MAChC,GAAG,aAAa,iBAAiB;AAAA,MACjC,UAAU,aAAa,iBAAiB,EAAG,WAAW,KAAK;AAAA,IAC7D;AACA,WAAO,EAAE,GAAG,MAAM,OAAO,aAAa;AAAA,EACxC,OAAO;AACL,UAAM,kCACJ,KAAK,iBAAiB,KAAK,cACvB,sCAAsC;AAAA,MACpC,aAAa,KAAK;AAAA,MAClB,eAAe,KAAK;AAAA,MACpB,cAAc,KAAK,MAAM,gBAAgB;AAAA,IAC3C,CAAC,IACD;AAEN,UAAM,UAAoB;AAAA,MACxB,IAAI,QAAQ,KAAK,IAAI,CAAC,IAAI,KAAK,OAAO,EA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AAI,YAAY,QAAW;AACzB,UAAM,IAAI,iBAAiB;AAAA,MACzB,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AACA,SAAO;AAAA,IACL,YAAY,QAAQ;AAAA,IACpB,YAAY,QAAQ;AAAA,IACpB,UAAU,QAAQ;AAAA,IAClB,WAAW,QAAQ;AAAA,IACnB,qBAAqB,QAAQ;AAAA,EAC/B;AACF;",
|
|
6
6
|
"names": ["cart"]
|
|
7
7
|
}
|
package/cart/cart-types.d.ts
CHANGED
|
@@ -2,8 +2,9 @@
|
|
|
2
2
|
* TypeScript types for cart data structures. Use these types when working with cart data, but don't import from this module directly in components - use the cart hooks instead.
|
|
3
3
|
* @module
|
|
4
4
|
*/
|
|
5
|
-
import type {
|
|
5
|
+
import type { sellingPlanGroupSchema } from "../_vendor/schemas/sellingPlan";
|
|
6
6
|
import { z } from "zod";
|
|
7
|
+
export type SellingPlanGroup = z.infer<typeof sellingPlanGroupSchema>;
|
|
7
8
|
export interface CartItem {
|
|
8
9
|
merchandiseId: string;
|
|
9
10
|
quantity: number;
|
package/cart/cart-types.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../cart/cart-types.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * TypeScript types for cart data structures. Use these types when working with cart data, but don't import from this module directly in components - use the cart hooks instead.\n * @module\n */\n\nimport type {
|
|
5
|
-
"mappings": "AAOA,SAAS,SAAS;
|
|
4
|
+
"sourcesContent": ["/**\n * TypeScript types for cart data structures. Use these types when working with cart data, but don't import from this module directly in components - use the cart hooks instead.\n * @module\n */\n\nimport type { sellingPlanGroupSchema } from \"schemas/sellingPlan\";\n\nimport { z } from \"zod\";\n\nexport type SellingPlanGroup = z.infer<typeof sellingPlanGroupSchema>;\n\nexport interface CartItem {\n merchandiseId: string;\n quantity: number;\n}\n\nexport interface Image {\n url: string;\n altText: string | null;\n}\n\nexport interface CartLineMerchandise {\n id: string;\n product: {\n id: string;\n title: string;\n sellingPlanGroups?: SellingPlanGroup[];\n };\n title: string;\n price: number;\n compareAtPrice?: number | null;\n image: Image | null;\n selectedOptions: {\n name: string;\n value: string;\n }[];\n}\n\nexport interface CartLineAttribute {\n key: string;\n value: string | number | boolean;\n}\n\nexport const cartLineAttributeSchema = z.object({\n key: z.string(),\n value: z.union([z.string(), z.number(), z.boolean()]),\n});\n\nexport const cartLineAttributesSchema = z.array(cartLineAttributeSchema);\n\n/** Replo attribution property added to cart/buy-now line items for order attribution in Shopify. */\nexport const REPLO_ATTRIBUTION_PROPERTY: CartLineAttribute = {\n key: \"_replo\",\n value: \"true\",\n};\n\nexport interface SellingPlanPriceAdjustment {\n compareAtPrice: {\n amount: number;\n currencyCode: string;\n };\n perDeliveryPrice: {\n amount: number;\n currencyCode: string;\n };\n price: {\n amount: number;\n currencyCode: string;\n };\n unitPrice: {\n amount: number;\n currencyCode: string;\n } | null;\n}\n\nexport interface SellingPlanAllocation {\n sellingPlan: {\n id: string;\n name: string;\n description: string | null;\n };\n priceAdjustments: SellingPlanPriceAdjustment[];\n checkoutChargeAmount: {\n amount: number;\n currencyCode: string;\n };\n remainingBalanceChargeAmount: {\n amount: number;\n currencyCode: string;\n };\n}\n\n/**\n * Common cart line attribute keys for type safety\n */\nexport type CartLineAttributeKey =\n // Bundle attributes\n | \"bundleId\"\n | \"bundleDiscount\"\n | \"isBundleItem\"\n // Special item attributes\n | \"isSpecialItem\"\n | \"specialInstructions\"\n // Custom attributes (allow any string for extensibility)\n | string;\n\nexport interface CartLine {\n id: string;\n quantity: number;\n /**\n * Null when this is an optimistic line whose merchandise couldn't be\n * resolved from the query cache or passed explicitly. Consumers should\n * render a skeleton/loading state in that case; the line is replaced\n * with real merchandise once the server roundtrip lands.\n */\n merchandise: CartLineMerchandise | null;\n attributes: CartLineAttribute[];\n sellingPlanAllocation?: SellingPlanAllocation | null;\n}\n\nexport interface CartCost {\n subtotalAmount: number;\n totalAmount: number;\n currencyCode: string;\n}\n\nexport interface CartWarning {\n code: string;\n message: string;\n target?: string;\n}\n\n/**\n * Represents a discount code applied to a cart.\n */\nexport interface CartDiscountCode {\n /** The discount code string */\n code: string;\n /**\n * Whether the discount code is applicable to the current cart.\n * A code may not be applicable due to:\n * - Cart contents not meeting product/collection eligibility\n * - Minimum purchase amount not met\n * - Code expired or usage limits reached\n * - Customer restrictions\n * - Conflicting discount rules\n */\n applicable: boolean;\n}\n\nexport interface Cart {\n id: string;\n lines: CartLine[];\n cost: CartCost;\n checkoutUrl?: string;\n warnings?: CartWarning[];\n discountCodes?: CartDiscountCode[];\n}\n\nexport interface CartLinePayload {\n id: string;\n quantity: number;\n merchandise?: CartLineMerchandise;\n properties?: CartLineAttribute[];\n sellingPlanId?: string | null;\n}\n\nexport interface AddToCartPayload {\n lines: CartLinePayload[];\n cartId: string;\n}\n\nexport interface UpdateCartLineItemPayload {\n line: CartLinePayload;\n cartId: string;\n}\n\nexport interface RemoveFromCartPayload {\n lineIds: string[];\n cartId: string;\n}\n\nexport interface UpdateCartDiscountCodesPayload {\n cartId: string;\n discountCodes: string[];\n}\n"],
|
|
5
|
+
"mappings": "AAOA,SAAS,SAAS;AAoCX,MAAM,0BAA0B,EAAE,OAAO;AAAA,EAC9C,KAAK,EAAE,OAAO;AAAA,EACd,OAAO,EAAE,MAAM,CAAC,EAAE,OAAO,GAAG,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC,CAAC;AACtD,CAAC;AAEM,MAAM,2BAA2B,EAAE,MAAM,uBAAuB;AAGhE,MAAM,6BAAgD;AAAA,EAC3D,KAAK;AAAA,EACL,OAAO;AACT;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import React from "react";
|
|
3
3
|
import { useQueryClient } from "@tanstack/react-query";
|
|
4
|
-
import { DATA_LOADER_KEYS } from "../../
|
|
4
|
+
import { DATA_LOADER_KEYS } from "../../_vendor/schemas/loaderKeys.mjs";
|
|
5
5
|
import { useCartInternal } from "../cart-provider";
|
|
6
6
|
import { REPLO_ATTRIBUTION_PROPERTY } from "../cart-types";
|
|
7
7
|
const PRODUCT_LOADER_KEYS = [
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../cart/hooks/use-add-to-cart.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Hook for adding items to cart using merchandiseId directly (e.g. variant GIDs from data loaders).\n * Merchandise display data for optimistic UI is auto-resolved from the React Query cache.\n * @module\n */\n\"use client\";\n\nimport type { QueryClient } from \"@tanstack/react-query\";\nimport type { Product } from \"
|
|
5
|
-
"mappings": ";AAWA,OAAO,WAAW;AAElB,SAAS,sBAAsB;
|
|
4
|
+
"sourcesContent": ["/**\n * Hook for adding items to cart using merchandiseId directly (e.g. variant GIDs from data loaders).\n * Merchandise display data for optimistic UI is auto-resolved from the React Query cache.\n * @module\n */\n\"use client\";\n\nimport type { QueryClient } from \"@tanstack/react-query\";\nimport type { Product } from \"schemas/objectType\";\nimport type { CartLineAttribute, CartLineMerchandise } from \"../cart-types\";\n\nimport React from \"react\";\n\nimport { useQueryClient } from \"@tanstack/react-query\";\nimport { DATA_LOADER_KEYS } from \"schemas/loaderKeys\";\n\nimport { useCartInternal } from \"../cart-provider\";\nimport { REPLO_ATTRIBUTION_PROPERTY } from \"../cart-types\";\n\ntype ProductListLike = { products: Product[] };\n\n/**\n * Describes a single item to add to the cart. Uses the merchandiseId\n * (e.g. a variant GID) directly from data loader output. Product\n * display data for optimistic UI is resolved automatically from the\n * React Query cache for both single-product loaders (e.g. ProductLoader)\n * and product-list loaders (e.g. CollectionProductsLoader,\n * RebuyRecommendationsLoader). Pass `merchandise` explicitly to bypass\n * the cache lookup when the variant is known but its product was not\n * loaded via a supported loader.\n */\nexport interface AddToCartItem {\n /** The cart-addressable merchandise ID (e.g. `product.variants[N].id` from loader output). */\n merchandiseId: string;\n quantity?: number;\n sellingPlanId?: string | null;\n /** Custom line item properties (appear on the order). */\n properties?: CartLineAttribute[];\n merchandise?: CartLineMerchandise;\n}\n\n/**\n * Loaders whose cached value is a single Product. Scanned for variant\n * matches first since they carry the richest product data.\n */\nconst PRODUCT_LOADER_KEYS = [\n DATA_LOADER_KEYS.SHOPIFY_PRODUCT,\n DATA_LOADER_KEYS.REPLO_PRODUCT,\n] as const;\n\nconst PRODUCT_LIST_LOADER_KEYS = [\n DATA_LOADER_KEYS.SHOPIFY_COLLECTION_PRODUCTS,\n DATA_LOADER_KEYS.REBUY_RECOMMENDATIONS,\n] as const;\n\nfunction getMerchandiseFromProduct({\n product,\n merchandiseId,\n}: {\n product: Product;\n merchandiseId: string;\n}): CartLineMerchandise | undefined {\n if (!product.variants) {\n return undefined;\n }\n\n const matchingVariant = product.variants.find(\n (variant) => variant.id === merchandiseId,\n );\n\n if (!matchingVariant) {\n return undefined;\n }\n\n const image = matchingVariant.image ?? product.featuredImage ?? null;\n return {\n id: merchandiseId,\n product: {\n id: product.id,\n title: product.title ?? \"\",\n sellingPlanGroups: product.sellingPlanGroups ?? [],\n },\n title: matchingVariant.title ?? \"\",\n price: matchingVariant.price\n ? Number.parseFloat(matchingVariant.price.amount)\n : 0,\n compareAtPrice: matchingVariant.compareAtPrice\n ? Number.parseFloat(matchingVariant.compareAtPrice.amount)\n : null,\n image: image ? { url: image.url, altText: image.altText } : null,\n selectedOptions: matchingVariant.selectedOptions ?? [],\n };\n}\n\nexport function findMerchandiseInQueryCache({\n queryClient,\n merchandiseId,\n}: {\n queryClient: QueryClient;\n merchandiseId: string;\n}): CartLineMerchandise | undefined {\n for (const loaderKey of PRODUCT_LOADER_KEYS) {\n const productQueries = queryClient.getQueriesData<Product>({\n queryKey: [loaderKey],\n });\n\n for (const [, productData] of productQueries) {\n if (!productData) {\n continue;\n }\n\n const merchandise = getMerchandiseFromProduct({\n product: productData,\n merchandiseId,\n });\n if (merchandise) {\n return merchandise;\n }\n }\n }\n\n for (const loaderKey of PRODUCT_LIST_LOADER_KEYS) {\n const productListQueries = queryClient.getQueriesData<ProductListLike>({\n queryKey: [loaderKey],\n });\n\n for (const [, productListData] of productListQueries) {\n for (const product of productListData?.products ?? []) {\n const merchandise = getMerchandiseFromProduct({\n product,\n merchandiseId,\n });\n if (merchandise) {\n return merchandise;\n }\n }\n }\n }\n\n return undefined;\n}\n\n/**\n * Hook for adding items to cart using merchandise IDs from data loader output.\n *\n * This is the primary hook for adding items to cart in the data-loader\n * architecture. It works with the resolver-backed CartGateway so the scaffold\n * never needs direct integration credentials.\n *\n * Merchandise display data (title, price, image) for optimistic cart UI is\n * auto-resolved from the React Query cache for both single-product loaders\n * (e.g. `ProductLoader`) and product-list loaders (e.g.\n * `CollectionProductsLoader`, `RebuyRecommendationsLoader`). Just pass the\n * merchandiseId. Pass `merchandise` explicitly only when the variant is\n * known but its product was not loaded via a supported loader.\n *\n * @example\n * ```tsx\n * import { useAddToCart } from \"canopy-sdk/cart/hooks/use-add-to-cart\";\n *\n * function AddToCartButton({ variant }) {\n * const { addToCart, isAdding } = useAddToCart();\n *\n * return (\n * <button\n * disabled={!variant.availableForSale || isAdding}\n * onClick={() => {\n * addToCart([{ merchandiseId: variant.id, quantity: 1 }]);\n * }}\n * >\n * {isAdding ? \"Adding...\" : \"Add to Cart\"}\n * </button>\n * );\n * }\n * ```\n */\nexport function useAddToCart() {\n const cart = useCartInternal();\n const queryClient = useQueryClient();\n const [isAdding, setIsAdding] = React.useState(false);\n\n const addToCart = React.useCallback(\n async (items: AddToCartItem[], openCartAfterAdd = true) => {\n setIsAdding(true);\n try {\n const cartLines = items.map((item) => {\n const hasReploAttribution = item.properties?.some(\n (prop) => prop.key === REPLO_ATTRIBUTION_PROPERTY.key,\n );\n const properties = hasReploAttribution\n ? item.properties ?? []\n : [REPLO_ATTRIBUTION_PROPERTY, ...(item.properties ?? [])];\n\n const merchandise =\n item.merchandise ??\n findMerchandiseInQueryCache({\n queryClient,\n merchandiseId: item.merchandiseId,\n });\n\n return {\n id: item.merchandiseId,\n quantity: item.quantity ?? 1,\n sellingPlanId: item.sellingPlanId ?? undefined,\n properties,\n merchandise,\n };\n });\n\n await cart.addToCart(cartLines, openCartAfterAdd);\n } finally {\n setIsAdding(false);\n }\n },\n [cart, queryClient],\n );\n\n return { addToCart, isAdding };\n}\n"],
|
|
5
|
+
"mappings": ";AAWA,OAAO,WAAW;AAElB,SAAS,sBAAsB;AAC/B,SAAS,wBAAwB;AAEjC,SAAS,uBAAuB;AAChC,SAAS,kCAAkC;AA4B3C,MAAM,sBAAsB;AAAA,EAC1B,iBAAiB;AAAA,EACjB,iBAAiB;AACnB;AAEA,MAAM,2BAA2B;AAAA,EAC/B,iBAAiB;AAAA,EACjB,iBAAiB;AACnB;AAEA,SAAS,0BAA0B;AAAA,EACjC;AAAA,EACA;AACF,GAGoC;AAClC,MAAI,CAAC,QAAQ,UAAU;AACrB,WAAO;AAAA,EACT;AAEA,QAAM,kBAAkB,QAAQ,SAAS;AAAA,IACvC,CAAC,YAAY,QAAQ,OAAO;AAAA,EAC9B;AAEA,MAAI,CAAC,iBAAiB;AACpB,WAAO;AAAA,EACT;AAEA,QAAM,QAAQ,gBAAgB,SAAS,QAAQ,iBAAiB;AAChE,SAAO;AAAA,IACL,IAAI;AAAA,IACJ,SAAS;AAAA,MACP,IAAI,QAAQ;AAAA,MACZ,OAAO,QAAQ,SAAS;AAAA,MACxB,mBAAmB,QAAQ,qBAAqB,CAAC;AAAA,IACnD;AAAA,IACA,OAAO,gBAAgB,SAAS;AAAA,IAChC,OAAO,gBAAgB,QACnB,OAAO,WAAW,gBAAgB,MAAM,MAAM,IAC9C;AAAA,IACJ,gBAAgB,gBAAgB,iBAC5B,OAAO,WAAW,gBAAgB,eAAe,MAAM,IACvD;AAAA,IACJ,OAAO,QAAQ,EAAE,KAAK,MAAM,KAAK,SAAS,MAAM,QAAQ,IAAI;AAAA,IAC5D,iBAAiB,gBAAgB,mBAAmB,CAAC;AAA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4BAA4B;AAAA,YAC1B;AAAA,YACA,eAAe,KAAK;AAAA,UACtB,CAAC;AAEH,iBAAO;AAAA,YACL,IAAI,KAAK;AAAA,YACT,UAAU,KAAK,YAAY;AAAA,YAC3B,eAAe,KAAK,iBAAiB;AAAA,YACrC;AAAA,YACA;AAAA,UACF;AAAA,QACF,CAAC;AAED,cAAM,KAAK,UAAU,WAAW,gBAAgB;AAAA,MAClD,UAAE;AACA,oBAAY,KAAK;AAAA,MACnB;AAAA,IACF;AAAA,IACA,CAAC,MAAM,WAAW;AAAA,EACpB;AAEA,SAAO,EAAE,WAAW,SAAS;AAC/B;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import React from "react";
|
|
3
|
+
import { ReploError } from "../../_vendor/schemas/errors.mjs";
|
|
3
4
|
import { useClientValue } from "../../hooks/use-client-value";
|
|
4
|
-
import { CanopyError } from "../../lib/canopy-error";
|
|
5
5
|
import { buyNowAction } from "../buy-now-action";
|
|
6
6
|
const REPLO_LOCAL_STORAGE_SESSION_KEY = "_replo_sid";
|
|
7
7
|
const REPLO_SESSION_ID_KEY = "rsid";
|
|
8
8
|
const REPLO_CLIENT_ID_KEY = "rclid";
|
|
9
|
-
class ProductHasNoVariantsError extends
|
|
9
|
+
class ProductHasNoVariantsError extends ReploError {
|
|
10
10
|
}
|
|
11
11
|
function useBuyNow() {
|
|
12
12
|
const reploSessionString = useClientValue(
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../cart/hooks/use-buy-now.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Use useBuyNow() hook to create \"Buy Now\" buttons that skip the cart and go directly to checkout.\n * Calls a server action to create the cart/checkout session, then redirects the browser.\n * @module\n */\n\"use client\";\n\nimport React from \"react\";\n\nimport {
|
|
5
|
-
"mappings": ";AAOA,OAAO,WAAW;AAElB,SAAS,sBAAsB;AAC/B,SAAS,
|
|
4
|
+
"sourcesContent": ["/**\n * Use useBuyNow() hook to create \"Buy Now\" buttons that skip the cart and go directly to checkout.\n * Calls a server action to create the cart/checkout session, then redirects the browser.\n * @module\n */\n\"use client\";\n\nimport React from \"react\";\n\nimport { ReploError } from \"schemas/errors\";\n\nimport { useClientValue } from \"../../hooks/use-client-value\";\nimport { buyNowAction } from \"../buy-now-action\";\n\n// Analytics constants - defined locally to avoid dependency on analytics-client package\nconst REPLO_LOCAL_STORAGE_SESSION_KEY = \"_replo_sid\";\nconst REPLO_SESSION_ID_KEY = \"rsid\";\nconst REPLO_CLIENT_ID_KEY = \"rclid\";\n\n// Analytics session data type - defined locally to avoid dependency\ninterface AnalyticsSessionData {\n sessionId: string;\n reploId: string;\n expiresAt: number;\n createdAt: number;\n conversionsCounter: number;\n isEntryPage: boolean;\n}\n\nclass ProductHasNoVariantsError extends ReploError {}\n\nexport interface VariantBuyNowInfo {\n variantId: string;\n quantity?: number;\n sellingPlanId?: string | null;\n}\n\n/**\n * React hook that returns a `buyNow` function for express checkout flows.\n * Handles creating the cart/checkout session server-side and redirecting\n * the browser to checkout.\n *\n * @example\n *\n * ```tsx\n * import { useBuyNow } from \"canopy-sdk/cart/hooks/use-buy-now\";\n *\n * function MyComponent({ selectedVariant, selectedSellingPlan, quantity }) {\n * const { buyNow } = useBuyNow();\n *\n * return (\n * <Button\n * disabled={!selectedVariant?.availableForSale}\n * onClick={async () => {\n * if (selectedVariant) {\n * await buyNow(\n * [\n * {\n * variantId: selectedVariant.id,\n * quantity,\n * sellingPlanId: selectedSellingPlan?.id,\n * },\n * ],\n * { discountCodes: [\"SUMMER2024\"] }\n * );\n * }\n * }}\n * >\n * Shop Now\n * </Button>\n * );\n * }\n * ```\n *\n * @returns Object containing the buyNow function\n */\nexport function useBuyNow() {\n const reploSessionString = useClientValue(\n () => localStorage.getItem(REPLO_LOCAL_STORAGE_SESSION_KEY),\n null,\n );\n\n const buyNow = React.useCallback(\n async (\n variants: VariantBuyNowInfo[],\n options?: { discountCodes?: string[] },\n ) => {\n if (!variants || variants.length === 0) {\n throw new ProductHasNoVariantsError({\n message: \"No variants provided\",\n });\n }\n\n const { redirectUrl } = await buyNowAction({\n lineItems: variants.map((variant) => ({\n variantId: variant.variantId,\n quantity: variant.quantity ?? 1,\n sellingPlanId: variant.sellingPlanId ?? null,\n properties: [],\n })),\n discountCodes: options?.discountCodes ?? [],\n pageUrl: window.location.href,\n });\n\n const url = new URL(redirectUrl);\n\n // Only append tracking params for non-Stripe checkout URLs (e.g. Shopify).\n // Stripe checkout URLs should not be modified with extra query params.\n const isStripeCheckout = url.hostname.endsWith(\"stripe.com\");\n if (!isStripeCheckout) {\n const currentParams = new URLSearchParams(window.location.search);\n for (const [key, value] of currentParams.entries()) {\n if (!url.searchParams.has(key)) {\n url.searchParams.set(key, value);\n }\n }\n\n if (reploSessionString) {\n try {\n const sessionData: AnalyticsSessionData =\n JSON.parse(reploSessionString);\n if (sessionData.sessionId && sessionData.reploId) {\n url.searchParams.set(REPLO_SESSION_ID_KEY, sessionData.sessionId);\n url.searchParams.set(REPLO_CLIENT_ID_KEY, sessionData.reploId);\n }\n } catch {\n // Ignore invalid session data\n }\n }\n }\n\n window.location.href = url.toString();\n },\n [reploSessionString],\n );\n\n return { buyNow };\n}\n"],
|
|
5
|
+
"mappings": ";AAOA,OAAO,WAAW;AAElB,SAAS,kBAAkB;AAE3B,SAAS,sBAAsB;AAC/B,SAAS,oBAAoB;AAG7B,MAAM,kCAAkC;AACxC,MAAM,uBAAuB;AAC7B,MAAM,sBAAsB;AAY5B,MAAM,kCAAkC,WAAW;AAAC;AA+C7C,SAAS,YAAY;AAC1B,QAAM,qBAAqB;AAAA,IACzB,MAAM,aAAa,QAAQ,+BAA+B;AAAA,IAC1D;AAAA,EACF;AAEA,QAAM,SAAS,MAAM;AAAA,IACnB,OACE,UACA,YACG;AACH,UAAI,CAAC,YAAY,SAAS,WAAW,GAAG;AACtC,cAAM,IAAI,0BAA0B;AAAA,UAClC,SAAS;AAAA,QACX,CAAC;AAAA,MACH;AAEA,YAAM,EAAE,YAAY,IAAI,MAAM,aAAa;AAAA,QACzC,WAAW,SAAS,IAAI,CAAC,aAAa;AAAA,UACpC,WAAW,QAAQ;AAAA,UACnB,UAAU,QAAQ,YAAY;AAAA,UAC9B,eAAe,QAAQ,iBAAiB;AAAA,UACxC,YAAY,CAAC;AAAA,QACf,EAAE;AAAA,QACF,eAAe,SAAS,iBAAiB,CAAC;AAAA,QAC1C,SAAS,OAAO,SAAS;AAAA,MAC3B,CAAC;AAED,YAAM,MAAM,IAAI,IAAI,WAAW;AAI/B,YAAM,mBAAmB,IAAI,SAAS,SAAS,YAAY;AAC3D,UAAI,CAAC,kBAAkB;AACrB,cAAM,gBAAgB,IAAI,gBAAgB,OAAO,SAAS,MAAM;AAChE,mBAAW,CAAC,KAAK,KAAK,KAAK,cAAc,QAAQ,GAAG;AAClD,cAAI,CAAC,IAAI,aAAa,IAAI,GAAG,GAAG;AAC9B,gBAAI,aAAa,IAAI,KAAK,KAAK;AAAA,UACjC;AAAA,QACF;AAEA,YAAI,oBAAoB;AACtB,cAAI;AACF,kBAAM,cACJ,KAAK,MAAM,kBAAkB;AAC/B,gBAAI,YAAY,aAAa,YAAY,SAAS;AAChD,kBAAI,aAAa,IAAI,sBAAsB,YAAY,SAAS;AAChE,kBAAI,aAAa,IAAI,qBAAqB,YAAY,OAAO;AAAA,YAC/D;AAAA,UACF,QAAQ;AAAA,UAER;AAAA,QACF;AAAA,MACF;AAEA,aAAO,SAAS,OAAO,IAAI,SAAS;AAAA,IACtC;AAAA,IACA,CAAC,kBAAkB;AAAA,EACrB;AAEA,SAAO,EAAE,OAAO;AAClB;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import type { SellingPlanGroup } from "
|
|
2
|
-
import type { CartLine, CartLineAttribute, CartLineMerchandise, CartLinePayload, SellingPlanAllocation } from "../cart-types";
|
|
1
|
+
import type { CartLine, CartLineAttribute, CartLineMerchandise, CartLinePayload, SellingPlanAllocation, SellingPlanGroup } from "../cart-types";
|
|
3
2
|
interface ProductVariant {
|
|
4
3
|
id: string;
|
|
5
4
|
externalId?: string;
|