@jay-framework/wix-cart 0.22.2 → 0.24.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/dist/index.js DELETED
@@ -1,547 +0,0 @@
1
- import { registerService, getService } from "@jay-framework/stack-server-runtime";
2
- import { createJayService, makeJayStackComponent, RenderPipeline, makeJayInit } from "@jay-framework/fullstack-component";
3
- import { createJayContext, useGlobalContext } from "@jay-framework/runtime";
4
- import { registerReactiveGlobalContext, createSignal, useReactive, createEvent } from "@jay-framework/component";
5
- import { wixFetch, WIX_CLIENT_CONTEXT, WIX_CLIENT_SERVICE } from "@jay-framework/wix-server-client";
6
- import * as fs from "fs";
7
- import * as path from "path";
8
- import * as yaml from "js-yaml";
9
- const WIX_CART_SERVICE = createJayService("Wix Cart Service");
10
- function provideWixCartService(wixClient) {
11
- const service = { wixClient };
12
- registerService(WIX_CART_SERVICE, service);
13
- return service;
14
- }
15
- async function getCurrentCart(client) {
16
- return wixFetch(client, "/ecom/v1/carts/current", { method: "GET" });
17
- }
18
- async function addToCurrentCart(client, lineItems) {
19
- return wixFetch(client, "/ecom/v1/carts/current/add-to-cart", {
20
- method: "POST",
21
- body: { lineItems }
22
- });
23
- }
24
- async function removeLineItemsFromCurrentCart(client, lineItemIds) {
25
- return wixFetch(client, "/ecom/v1/carts/current/remove-line-items", {
26
- method: "POST",
27
- body: { lineItemIds }
28
- });
29
- }
30
- async function updateCurrentCartLineItemQuantity(client, lineItems) {
31
- return wixFetch(client, "/ecom/v1/carts/current/update-line-items-quantity", {
32
- method: "POST",
33
- body: {
34
- lineItems: lineItems.map((item) => ({
35
- id: item._id,
36
- quantity: item.quantity
37
- }))
38
- }
39
- });
40
- }
41
- async function updateCurrentCart(client, cartInfo) {
42
- return wixFetch(client, "/ecom/v1/carts/current", {
43
- method: "PATCH",
44
- body: { cartInfo }
45
- });
46
- }
47
- async function removeCouponFromCurrentCart(client) {
48
- return wixFetch(client, "/ecom/v1/carts/current/remove-coupon", {
49
- method: "POST",
50
- body: {}
51
- });
52
- }
53
- async function estimateCurrentCartTotals(client) {
54
- return wixFetch(client, "/ecom/v1/carts/current/estimate-totals", {
55
- method: "POST",
56
- body: {}
57
- });
58
- }
59
- async function createCheckoutFromCurrentCart(client) {
60
- return wixFetch(client, "/ecom/v1/carts/current/create-checkout", {
61
- method: "POST",
62
- body: {}
63
- });
64
- }
65
- async function createRedirectSession(client, options) {
66
- return wixFetch(client, "/redirects-api/v1/redirect-session", {
67
- method: "POST",
68
- body: options
69
- });
70
- }
71
- function stripWixMediaResize(url) {
72
- return url.replace(/\/v1\/(?:fit|fill|crop)\/[^/]+\/file\.\w+$/, "");
73
- }
74
- function parseWixMediaUrl(url) {
75
- if (!url) return null;
76
- const match = url.match(
77
- /^wix:(image|video|document|audio):\/\/v1\/([^/]+)\/([^#]+)(?:#(.*))?$/
78
- );
79
- if (!match) return null;
80
- const [, type, mediaId, fileName, hashParams] = match;
81
- const result = {
82
- type,
83
- mediaId,
84
- fileName: decodeURIComponent(fileName)
85
- };
86
- if (hashParams) {
87
- const params = new URLSearchParams(hashParams);
88
- const originWidth = params.get("originWidth");
89
- const originHeight = params.get("originHeight");
90
- if (originWidth) result.originWidth = parseInt(originWidth, 10);
91
- if (originHeight) result.originHeight = parseInt(originHeight, 10);
92
- const posterUri = params.get("posterUri");
93
- const posterWidth = params.get("posterWidth");
94
- const posterHeight = params.get("posterHeight");
95
- if (posterUri) result.posterUri = decodeURIComponent(posterUri);
96
- if (posterWidth) result.posterWidth = parseInt(posterWidth, 10);
97
- if (posterHeight) result.posterHeight = parseInt(posterHeight, 10);
98
- }
99
- return result;
100
- }
101
- function formatWixMediaUrl(_id, url, resize) {
102
- const resizeFragment = "";
103
- if (url == null ? void 0 : url.startsWith("wix:")) {
104
- const parsed = parseWixMediaUrl(url);
105
- if (parsed) {
106
- return `https://static.wixstatic.com/media/${parsed.mediaId}${resizeFragment}`;
107
- }
108
- }
109
- if ((url == null ? void 0 : url.startsWith("http://")) || (url == null ? void 0 : url.startsWith("https://"))) {
110
- return stripWixMediaResize(url) + resizeFragment;
111
- }
112
- if (_id) {
113
- return `https://static.wixstatic.com/media/${_id}${resizeFragment}`;
114
- }
115
- return "";
116
- }
117
- function mapLineItem(item) {
118
- const catalogRef = item.catalogReference;
119
- const physicalProperties = item.physicalProperties;
120
- const priceData = item.price;
121
- const descriptionLines = item.descriptionLines || [];
122
- const variantParts = descriptionLines.filter((line) => line.name?.translated).map(
123
- (line) => `${line.name?.translated}: ${line.colorInfo?.translated || line.plainText?.translated || ""}`
124
- );
125
- const rawUrl = item.url;
126
- const urlString = typeof rawUrl === "string" ? rawUrl : rawUrl?.relativePath || rawUrl?.url || "";
127
- const slug = urlString.split("/").pop() || "";
128
- const rawImage = item.image;
129
- const imageUrl = typeof rawImage === "string" ? rawImage : rawImage?.url || "";
130
- const imageId = typeof rawImage === "string" ? "" : rawImage?.id || "";
131
- return {
132
- lineItemId: item._id || item.id || "",
133
- productId: catalogRef?.catalogItemId || "",
134
- productName: item.productName?.translated || item.productName?.original || "",
135
- productUrl: slug ? `/products/${slug}` : "",
136
- variantName: variantParts.join(" / "),
137
- sku: physicalProperties?.sku || "",
138
- image: {
139
- url: formatWixMediaUrl(imageId, imageUrl),
140
- altText: item.productName?.translated || ""
141
- },
142
- quantity: item.quantity || 1,
143
- unitPrice: {
144
- amount: priceData?.amount || "0",
145
- formattedAmount: priceData?.formattedAmount || ""
146
- },
147
- lineTotal: {
148
- amount: item.lineItemPrice?.amount || "0",
149
- formattedAmount: item.lineItemPrice?.formattedAmount || ""
150
- },
151
- lineDiscount: {
152
- amount: "0",
153
- formattedAmount: ""
154
- },
155
- hasDiscount: false
156
- };
157
- }
158
- function calculateTotalDiscount(appliedDiscounts) {
159
- if (!appliedDiscounts) return 0;
160
- return appliedDiscounts.reduce(
161
- (sum, d) => sum + parseFloat(d.merchantDiscount?.amount?.amount || "0"),
162
- 0
163
- );
164
- }
165
- function calculateItemCount(lineItems) {
166
- if (!lineItems) return 0;
167
- return lineItems.reduce((sum, item) => sum + (item.quantity || 0), 0);
168
- }
169
- function getEmptySummary() {
170
- return {
171
- itemCount: 0,
172
- subtotal: { amount: "0", formattedAmount: "$0.00" },
173
- discount: { amount: "0", formattedAmount: "" },
174
- hasDiscount: false,
175
- estimatedTax: { amount: "0", formattedAmount: "" },
176
- showTax: false,
177
- estimatedTotal: { amount: "0", formattedAmount: "$0.00" },
178
- currency: "USD"
179
- };
180
- }
181
- function mapCartSummary(cart) {
182
- if (!cart) {
183
- return getEmptySummary();
184
- }
185
- const totalDiscount = calculateTotalDiscount(cart.appliedDiscounts);
186
- const itemCount = calculateItemCount(cart.lineItems);
187
- return {
188
- itemCount,
189
- subtotal: {
190
- amount: "0",
191
- formattedAmount: "$0.00"
192
- },
193
- discount: {
194
- amount: totalDiscount.toString(),
195
- formattedAmount: totalDiscount > 0 ? `-$${totalDiscount.toFixed(2)}` : ""
196
- },
197
- hasDiscount: totalDiscount > 0,
198
- estimatedTax: {
199
- amount: "0",
200
- formattedAmount: ""
201
- },
202
- showTax: false,
203
- estimatedTotal: {
204
- amount: "0",
205
- formattedAmount: "$0.00"
206
- },
207
- currency: cart.currency || "USD"
208
- };
209
- }
210
- function mapCartToState(cart) {
211
- if (!cart) {
212
- return getEmptyCartState();
213
- }
214
- const lineItems = (cart.lineItems || []).map(mapLineItem);
215
- const appliedCoupon = cart.appliedDiscounts?.find((d) => d.coupon?.code)?.coupon?.code || "";
216
- return {
217
- cartId: cart._id || cart.id || "",
218
- isEmpty: lineItems.length === 0,
219
- lineItems,
220
- summary: mapCartSummary(cart),
221
- appliedCoupon,
222
- hasAppliedCoupon: !!appliedCoupon
223
- };
224
- }
225
- function getEmptyCartState() {
226
- return {
227
- cartId: "",
228
- isEmpty: true,
229
- lineItems: [],
230
- summary: getEmptySummary(),
231
- appliedCoupon: "",
232
- hasAppliedCoupon: false
233
- };
234
- }
235
- function mapCartToIndicator(cart) {
236
- if (!cart || !cart.lineItems?.length) {
237
- return {
238
- itemCount: 0,
239
- hasItems: false
240
- };
241
- }
242
- const itemCount = calculateItemCount(cart.lineItems);
243
- return {
244
- itemCount,
245
- hasItems: itemCount > 0
246
- };
247
- }
248
- function isCartNotFoundError(error) {
249
- const err = error;
250
- if (err?.response?.status === 404) return true;
251
- if (err?.status === 404) return true;
252
- if (err?.code === 404) return true;
253
- const message = err?.message?.toLowerCase() || "";
254
- if (message.includes("not found") && message.includes("cart")) return true;
255
- return false;
256
- }
257
- async function getCurrentCartOrNull(wixClient) {
258
- try {
259
- const response = await getCurrentCart(wixClient);
260
- return response.cart ?? null;
261
- } catch (error) {
262
- if (isCartNotFoundError(error)) {
263
- return null;
264
- }
265
- throw error;
266
- }
267
- }
268
- async function estimateCurrentCartTotalsOrNull(wixClient) {
269
- try {
270
- const response = await estimateCurrentCartTotals(wixClient);
271
- return response ?? null;
272
- } catch (error) {
273
- if (isCartNotFoundError(error)) {
274
- return null;
275
- }
276
- throw error;
277
- }
278
- }
279
- function mapEstimateTotalsToState(estimate) {
280
- if (!estimate?.cart) {
281
- return getEmptyCartState();
282
- }
283
- const cart = estimate.cart;
284
- const lineItems = (cart.lineItems || []).map(mapLineItem);
285
- const appliedCoupon = cart.appliedDiscounts?.find((d) => d.coupon?.code)?.coupon?.code || "";
286
- const itemCount = lineItems.reduce((sum, item) => sum + item.quantity, 0);
287
- const priceSummary = estimate.priceSummary;
288
- const taxSummary = estimate.taxSummary;
289
- const discountAmount = parseFloat(priceSummary?.discount?.amount || "0");
290
- const hasTax = parseFloat(taxSummary?.totalTax?.amount || "0") > 0;
291
- return {
292
- cartId: cart._id || cart.id || "",
293
- isEmpty: lineItems.length === 0,
294
- lineItems,
295
- summary: {
296
- itemCount,
297
- subtotal: {
298
- amount: priceSummary?.subtotal?.amount || "0",
299
- formattedAmount: priceSummary?.subtotal?.formattedAmount || "$0.00"
300
- },
301
- discount: {
302
- amount: discountAmount.toString(),
303
- formattedAmount: priceSummary?.discount?.formattedAmount || ""
304
- },
305
- hasDiscount: discountAmount > 0,
306
- estimatedTax: {
307
- amount: taxSummary?.totalTax?.amount || "0",
308
- formattedAmount: taxSummary?.totalTax?.formattedAmount || ""
309
- },
310
- showTax: hasTax,
311
- estimatedTotal: {
312
- amount: priceSummary?.total?.amount || priceSummary?.subtotal?.amount || "0",
313
- formattedAmount: priceSummary?.total?.formattedAmount || priceSummary?.subtotal?.formattedAmount || "$0.00"
314
- },
315
- currency: cart.currency || "USD"
316
- },
317
- appliedCoupon,
318
- hasAppliedCoupon: !!appliedCoupon
319
- };
320
- }
321
- const WIX_STORES_APP_ID = "215238eb-22a5-4c36-9e7b-e7c08025e04e";
322
- const WIX_CART_CONTEXT = createJayContext("wix:cart");
323
- function provideWixCartContext(thankYouUrl = "/thank-you") {
324
- const wixClientContext = useGlobalContext(WIX_CLIENT_CONTEXT);
325
- const wixClient = wixClientContext.client;
326
- const cartContext = registerReactiveGlobalContext(WIX_CART_CONTEXT, () => {
327
- const [itemCount, setItemCount] = createSignal(0);
328
- const [hasItems, setHasItems] = createSignal(false);
329
- const reactive = useReactive();
330
- const onItemAddedToCart = createEvent();
331
- function updateIndicatorFromCart(cart) {
332
- const indicator = mapCartToIndicator(cart);
333
- reactive.batchReactions(() => {
334
- setItemCount(indicator.itemCount);
335
- setHasItems(indicator.hasItems);
336
- });
337
- }
338
- async function refreshCartIndicator() {
339
- const cart = await getCurrentCartOrNull(wixClient);
340
- updateIndicatorFromCart(cart);
341
- }
342
- async function getEstimatedCart() {
343
- const estimate = await estimateCurrentCartTotalsOrNull(wixClient);
344
- return mapEstimateTotalsToState(estimate);
345
- }
346
- async function addToCart(productId, quantity = 1, options) {
347
- console.log(`[WixCart] Adding to cart: ${productId} x ${quantity}`, options);
348
- const catalogOptions = {};
349
- if (options?.variantId) catalogOptions.variantId = options.variantId;
350
- if (options?.modifiers) catalogOptions.options = options.modifiers;
351
- if (options?.customTextFields)
352
- catalogOptions.customTextFields = options.customTextFields;
353
- const lineItem = {
354
- catalogReference: {
355
- catalogItemId: productId,
356
- appId: WIX_STORES_APP_ID,
357
- ...Object.keys(catalogOptions).length > 0 ? { options: catalogOptions } : {}
358
- },
359
- quantity
360
- };
361
- const result = await addToCurrentCart(wixClient, [lineItem]);
362
- updateIndicatorFromCart(result.cart ?? null);
363
- onItemAddedToCart.emit();
364
- return { cartState: mapCartToState(result.cart ?? null) };
365
- }
366
- async function removeLineItems(lineItemIds) {
367
- const result = await removeLineItemsFromCurrentCart(wixClient, lineItemIds);
368
- updateIndicatorFromCart(result.cart ?? null);
369
- return { cartState: mapCartToState(result.cart ?? null) };
370
- }
371
- async function updateLineItemQuantity(lineItemId, quantity) {
372
- let result;
373
- if (quantity === 0) {
374
- result = await removeLineItemsFromCurrentCart(wixClient, [lineItemId]);
375
- } else {
376
- result = await updateCurrentCartLineItemQuantity(wixClient, [{ _id: lineItemId, quantity }]);
377
- }
378
- updateIndicatorFromCart(result.cart ?? null);
379
- return { cartState: mapCartToState(result.cart ?? null) };
380
- }
381
- async function clearCart() {
382
- const cart = await getCurrentCartOrNull(wixClient);
383
- if (cart?.lineItems?.length) {
384
- const lineItemIds = cart.lineItems.map((item) => item._id || "").filter(Boolean);
385
- if (lineItemIds.length > 0) {
386
- await removeLineItemsFromCurrentCart(wixClient, lineItemIds);
387
- }
388
- }
389
- setItemCount(0);
390
- setHasItems(false);
391
- }
392
- async function applyCoupon(couponCode) {
393
- const result = await updateCurrentCart(wixClient, { couponCode });
394
- updateIndicatorFromCart(result ?? null);
395
- return { cartState: mapCartToState(result ?? null) };
396
- }
397
- async function removeCoupon() {
398
- const result = await removeCouponFromCurrentCart(wixClient);
399
- updateIndicatorFromCart(result.cart ?? null);
400
- return { cartState: mapCartToState(result.cart ?? null) };
401
- }
402
- async function checkout() {
403
- const { checkoutId } = await createCheckoutFromCurrentCart(wixClient);
404
- if (!checkoutId) throw new Error("Failed to create checkout from cart");
405
- const postFlowUrl = window.location.origin + thankYouUrl;
406
- const { redirectSession } = await createRedirectSession(wixClient, {
407
- ecomCheckout: { checkoutId },
408
- callbacks: { postFlowUrl }
409
- });
410
- if (!redirectSession?.fullUrl) {
411
- throw new Error("Failed to create checkout redirect session");
412
- }
413
- return redirectSession.fullUrl;
414
- }
415
- return {
416
- cartIndicator: {
417
- itemCount,
418
- hasItems
419
- },
420
- refreshCartIndicator,
421
- getEstimatedCart,
422
- addToCart,
423
- removeLineItems,
424
- updateLineItemQuantity,
425
- clearCart,
426
- applyCoupon,
427
- removeCoupon,
428
- checkout,
429
- onItemAddedToCart
430
- };
431
- });
432
- console.log("[wix-cart] Client cart context initialized (reactive)");
433
- return cartContext;
434
- }
435
- async function renderFastChanging$2(_props, _wixCart) {
436
- const Pipeline = RenderPipeline.for();
437
- return Pipeline.ok(null).toPhaseOutput(() => ({
438
- viewState: {
439
- itemCount: 0,
440
- hasItems: false,
441
- isLoading: true,
442
- justAdded: false
443
- },
444
- carryForward: {}
445
- }));
446
- }
447
- const cartIndicator = makeJayStackComponent().withProps().withServices(WIX_CART_SERVICE).withFastRender(renderFastChanging$2);
448
- function createEmptyCartViewState() {
449
- return {
450
- isEmpty: true,
451
- isLoading: true,
452
- isCheckingOut: false,
453
- lineItems: [],
454
- summary: {
455
- itemCount: 0,
456
- subtotal: { amount: "0", formattedAmount: "$0.00" },
457
- discount: { amount: "0", formattedAmount: "" },
458
- hasDiscount: false,
459
- estimatedTax: { amount: "0", formattedAmount: "" },
460
- showTax: false,
461
- estimatedTotal: { amount: "0", formattedAmount: "$0.00" },
462
- currency: "USD"
463
- },
464
- coupon: {
465
- code: "",
466
- isApplying: false,
467
- appliedCode: "",
468
- hasAppliedCoupon: false,
469
- errorMessage: "",
470
- hasError: false
471
- }
472
- };
473
- }
474
- async function renderSlowlyChanging(_props, _wixCart) {
475
- const Pipeline = RenderPipeline.for();
476
- return Pipeline.ok(null).toPhaseOutput(() => ({
477
- viewState: {
478
- cartId: "",
479
- emptyCartMessage: "Your cart is empty"
480
- },
481
- carryForward: {}
482
- }));
483
- }
484
- async function renderFastChanging$1(_props, _slowCarryForward, _wixCart) {
485
- const Pipeline = RenderPipeline.for();
486
- return Pipeline.ok(null).toPhaseOutput(() => ({
487
- viewState: createEmptyCartViewState(),
488
- carryForward: {}
489
- }));
490
- }
491
- const cartPage = makeJayStackComponent().withProps().withServices(WIX_CART_SERVICE).withSlowlyRender(renderSlowlyChanging).withFastRender(renderFastChanging$1);
492
- async function renderFastChanging(_props, _wixCart) {
493
- const Pipeline = RenderPipeline.for();
494
- return Pipeline.ok(null).toPhaseOutput(() => ({
495
- viewState: {
496
- isOpen: false
497
- },
498
- carryForward: {}
499
- }));
500
- }
501
- const miniCart = makeJayStackComponent().withProps().withServices(WIX_CART_SERVICE).withFastRender(renderFastChanging);
502
- function loadWixCartConfig() {
503
- const configPath = path.join(process.cwd(), "config", ".wix-cart.yaml");
504
- const defaults = {
505
- urls: { thankYou: "/thank-you" }
506
- };
507
- if (!fs.existsSync(configPath)) return defaults;
508
- try {
509
- const raw = yaml.load(fs.readFileSync(configPath, "utf-8"));
510
- return {
511
- urls: {
512
- thankYou: raw?.urls?.thankYou || defaults.urls.thankYou
513
- }
514
- };
515
- } catch {
516
- return defaults;
517
- }
518
- }
519
- const init = makeJayInit().withServer(async () => {
520
- console.log("[wix-cart] Initializing Wix Cart service...");
521
- const wixClient = getService(WIX_CLIENT_SERVICE);
522
- const config = loadWixCartConfig();
523
- provideWixCartService(wixClient);
524
- console.log("[wix-cart] Server initialization complete");
525
- return {
526
- enableClientCart: true,
527
- thankYouUrl: config.urls.thankYou
528
- };
529
- });
530
- export {
531
- WIX_CART_CONTEXT,
532
- WIX_CART_SERVICE,
533
- cartIndicator,
534
- cartPage,
535
- estimateCurrentCartTotalsOrNull,
536
- getCurrentCartOrNull,
537
- getEmptyCartState,
538
- init,
539
- mapCartSummary,
540
- mapCartToIndicator,
541
- mapCartToState,
542
- mapEstimateTotalsToState,
543
- mapLineItem,
544
- miniCart,
545
- provideWixCartContext,
546
- provideWixCartService
547
- };