@jay-framework/wix-cart 0.19.7 → 0.21.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.
@@ -1,675 +1,66 @@
1
1
  import { createJayContext, useGlobalContext } from "@jay-framework/runtime";
2
2
  import { registerReactiveGlobalContext, createSignal, useReactive, createEvent } from "@jay-framework/component";
3
- import { WIX_CLIENT_CONTEXT } from "@jay-framework/wix-server-client/client";
4
- import { currentCart } from "@wix/ecom";
3
+ import { wixFetch, WIX_CLIENT_CONTEXT } from "@jay-framework/wix-server-client/client";
5
4
  import { makeJayStackComponent, makeJayInit } from "@jay-framework/fullstack-component";
6
5
  import { patch, REPLACE } from "@jay-framework/json-patch";
7
- let currentCartInstance;
8
- function getCurrentCartClient(wixClient) {
9
- if (!currentCartInstance) {
10
- currentCartInstance = wixClient.use(currentCart);
11
- }
12
- return currentCartInstance;
13
- }
14
- const SDKRequestToRESTRequestRenameMap = {
15
- _id: "id",
16
- _createdDate: "createdDate",
17
- _updatedDate: "updatedDate"
18
- };
19
- const RESTResponseToSDKResponseRenameMap = {
20
- id: "_id",
21
- createdDate: "_createdDate",
22
- updatedDate: "_updatedDate"
23
- };
24
- function renameAllNestedKeys(payload, renameMap, ignorePaths) {
25
- const isIgnored = (path) => ignorePaths.includes(path);
26
- const traverse = (obj, path) => {
27
- if (Array.isArray(obj)) {
28
- obj.forEach((item) => {
29
- traverse(item, path);
30
- });
31
- } else if (typeof obj === "object" && obj !== null) {
32
- const objAsRecord = obj;
33
- Object.keys(objAsRecord).forEach((key) => {
34
- const newPath = path === "" ? key : `${path}.${key}`;
35
- if (isIgnored(newPath)) {
36
- return;
37
- }
38
- const transformedKey = renameKey(key, renameMap);
39
- if (transformedKey !== key && !(transformedKey in objAsRecord)) {
40
- objAsRecord[transformedKey] = objAsRecord[key];
41
- delete objAsRecord[key];
42
- }
43
- traverse(objAsRecord[transformedKey], newPath);
44
- });
45
- }
46
- };
47
- traverse(payload, "");
48
- return payload;
49
- }
50
- function renameKey(key, renameMap) {
51
- let transformedKey;
52
- if (key.includes(".")) {
53
- const parts = key.split(".");
54
- const transformedParts = parts.map((part) => renameMap[part] ?? part);
55
- transformedKey = transformedParts.join(".");
56
- } else {
57
- transformedKey = renameMap[key] ?? key;
58
- }
59
- return transformedKey;
60
- }
61
- function renameKeysFromSDKRequestToRESTRequest(payload, ignorePaths = []) {
62
- return renameAllNestedKeys(payload, SDKRequestToRESTRequestRenameMap, ignorePaths);
63
- }
64
- function renameKeysFromRESTResponseToSDKResponse(payload, ignorePaths = []) {
65
- return renameAllNestedKeys(payload, RESTResponseToSDKResponseRenameMap, ignorePaths);
66
- }
67
- function transformRESTTimestampToSDKTimestamp(val) {
68
- return val ? new Date(val) : void 0;
69
- }
70
- function transformPath(obj, { path, isRepeated, isMap }, transformFn) {
71
- const pathParts = path.split(".");
72
- if (pathParts.length === 1 && path in obj) {
73
- obj[path] = isRepeated ? obj[path].map(transformFn) : isMap ? Object.fromEntries(Object.entries(obj[path]).map(([key, value]) => [key, transformFn(value)])) : transformFn(obj[path]);
74
- return obj;
75
- }
76
- const [first, ...rest] = pathParts;
77
- if (first.endsWith("{}")) {
78
- const cleanPath = first.slice(0, -2);
79
- obj[cleanPath] = Object.fromEntries(Object.entries(obj[cleanPath]).map(([key, value]) => [
80
- key,
81
- transformPath(value, { path: rest.join("."), isRepeated, isMap }, transformFn)
82
- ]));
83
- } else if (Array.isArray(obj[first])) {
84
- obj[first] = obj[first].map((item) => transformPath(item, { path: rest.join("."), isRepeated, isMap }, transformFn));
85
- } else if (first in obj && typeof obj[first] === "object" && obj[first] !== null) {
86
- obj[first] = transformPath(obj[first], { path: rest.join("."), isRepeated, isMap }, transformFn);
87
- } else if (first === "*") {
88
- Object.keys(obj).reduce((acc, curr) => {
89
- acc[curr] = transformPath(obj[curr], { path: rest.join("."), isRepeated, isMap }, transformFn);
90
- return acc;
91
- }, obj);
92
- }
93
- return obj;
94
- }
95
- function transformPaths(obj, transformations) {
96
- return transformations.reduce((acc, { paths, transformFn }) => paths.reduce((transformerAcc, path) => transformPath(transformerAcc, path, transformFn), acc), obj);
6
+ async function getCurrentCart(client) {
7
+ return wixFetch(client, "/ecom/v1/carts/current", { method: "GET" });
97
8
  }
98
- function EventDefinition(type, isDomainEvent = false, transformations = (x) => x) {
99
- return () => ({
100
- __type: "event-definition",
101
- type,
102
- isDomainEvent,
103
- transformations
9
+ async function addToCurrentCart(client, lineItems) {
10
+ return wixFetch(client, "/ecom/v1/carts/current/add-to-cart", {
11
+ method: "POST",
12
+ body: { lineItems }
104
13
  });
105
14
  }
106
- function constantCase(input) {
107
- return split(input).map((part) => part.toLocaleUpperCase()).join("_");
108
- }
109
- const SPLIT_LOWER_UPPER_RE = /([\p{Ll}\d])(\p{Lu})/gu;
110
- const SPLIT_UPPER_UPPER_RE = /(\p{Lu})([\p{Lu}][\p{Ll}])/gu;
111
- const SPLIT_REPLACE_VALUE = "$1\0$2";
112
- const DEFAULT_STRIP_REGEXP = /[^\p{L}\d]+/giu;
113
- function split(value) {
114
- let result = value.trim();
115
- result = result.replace(SPLIT_LOWER_UPPER_RE, SPLIT_REPLACE_VALUE).replace(SPLIT_UPPER_UPPER_RE, SPLIT_REPLACE_VALUE);
116
- result = result.replace(DEFAULT_STRIP_REGEXP, "\0");
117
- let start = 0;
118
- let end = result.length;
119
- while (result.charAt(start) === "\0") {
120
- start++;
121
- }
122
- if (start === end) {
123
- return [];
124
- }
125
- while (result.charAt(end - 1) === "\0") {
126
- end--;
127
- }
128
- return result.slice(start, end).split(/\0/g);
129
- }
130
- const isValidationError = (httpClientError) => "validationError" in (httpClientError.response?.data?.details ?? {});
131
- const isApplicationError = (httpClientError) => "applicationError" in (httpClientError.response?.data?.details ?? {});
132
- const isClientError = (httpClientError) => (httpClientError.response?.status ?? -1) >= 400 && (httpClientError.response?.status ?? -1) < 500;
133
- function transformError(httpClientError, pathsToArguments = {
134
- explicitPathsToArguments: {},
135
- spreadPathsToArguments: {},
136
- singleArgumentUnchanged: false
137
- }, argumentNames = []) {
138
- if (typeof httpClientError !== "object" || httpClientError === null) {
139
- throw httpClientError;
140
- }
141
- if (isValidationError(httpClientError)) {
142
- return buildValidationError(httpClientError, pathsToArguments, argumentNames);
143
- }
144
- if (isApplicationError(httpClientError)) {
145
- return buildApplicationError(httpClientError);
146
- }
147
- if (isClientError(httpClientError)) {
148
- const status = httpClientError.response?.status;
149
- const statusText = httpClientError.response?.statusText ?? "UNKNOWN";
150
- const message = httpClientError.response?.data?.message ?? statusText;
151
- const details = {
152
- applicationError: {
153
- description: statusText,
154
- code: constantCase(statusText),
155
- data: {}
156
- },
157
- requestId: httpClientError.requestId
158
- };
159
- return wrapError(httpClientError, {
160
- message: JSON.stringify({
161
- message,
162
- details
163
- }, null, 2),
164
- extraProperties: {
165
- details,
166
- status
167
- }
168
- });
169
- }
170
- return buildSystemError(httpClientError);
171
- }
172
- const buildValidationError = (httpClientError, pathsToArguments, argumentNames) => {
173
- const validationErrorResponse = httpClientError.response?.data;
174
- const requestId = httpClientError.requestId;
175
- const { fieldViolations } = validationErrorResponse.details.validationError;
176
- const transformedFieldViolations = violationsWithRenamedFields(pathsToArguments, fieldViolations, argumentNames)?.sort((a, b) => a.field < b.field ? -1 : 1);
177
- const message = `INVALID_ARGUMENT: ${transformedFieldViolations?.map(({ field, description }) => `"${field}" ${description}`)?.join(", ")}`;
178
- const details = {
179
- validationError: { fieldViolations: transformedFieldViolations },
180
- requestId
181
- };
182
- return wrapError(httpClientError, {
183
- message: JSON.stringify({ message, details }, null, 2),
184
- extraProperties: {
185
- details,
186
- status: httpClientError.response?.status,
187
- requestId
188
- }
189
- });
190
- };
191
- const wrapError = (baseError, { message, extraProperties }) => {
192
- return Object.assign(baseError, {
193
- ...extraProperties,
194
- message
195
- });
196
- };
197
- const buildApplicationError = (httpClientError) => {
198
- const status = httpClientError.response?.status;
199
- const statusText = httpClientError.response?.statusText ?? "UNKNOWN";
200
- const message = httpClientError.response?.data?.message ?? statusText;
201
- const description = httpClientError.response?.data?.details?.applicationError?.description ?? statusText;
202
- const code = httpClientError.response?.data?.details?.applicationError?.code ?? constantCase(statusText);
203
- const data = httpClientError.response?.data?.details?.applicationError?.data ?? {};
204
- const combinedMessage = message === description ? message : `${message}: ${description}`;
205
- const details = {
206
- applicationError: {
207
- description,
208
- code,
209
- data
210
- },
211
- requestId: httpClientError.requestId
212
- };
213
- return wrapError(httpClientError, {
214
- message: JSON.stringify({ message: combinedMessage, details }, null, 2),
215
- extraProperties: {
216
- details,
217
- status,
218
- requestId: httpClientError.requestId
219
- }
15
+ async function removeLineItemsFromCurrentCart(client, lineItemIds) {
16
+ return wixFetch(client, "/ecom/v1/carts/current/remove-line-items", {
17
+ method: "POST",
18
+ body: { lineItemIds }
220
19
  });
221
- };
222
- const buildSystemError = (httpClientError) => {
223
- const message = httpClientError.requestId ? `System error occurred, request-id: ${httpClientError.requestId}` : `System error occurred: ${JSON.stringify(httpClientError)}`;
224
- return wrapError(httpClientError, {
225
- message,
226
- extraProperties: {
227
- requestId: httpClientError.requestId,
228
- status: httpClientError.response?.status,
229
- code: constantCase(httpClientError.response?.statusText ?? "UNKNOWN"),
230
- ...!httpClientError.response && {
231
- runtimeError: httpClientError
232
- }
233
- }
234
- });
235
- };
236
- const violationsWithRenamedFields = ({ spreadPathsToArguments, explicitPathsToArguments, singleArgumentUnchanged }, fieldViolations, argumentNames) => {
237
- const allPathsToArguments = {
238
- ...spreadPathsToArguments,
239
- ...explicitPathsToArguments
240
- };
241
- const allPathsToArgumentsKeys = Object.keys(allPathsToArguments);
242
- return fieldViolations?.filter((fieldViolation) => {
243
- const containedInAMoreSpecificViolationField = fieldViolations.some((anotherViolation) => anotherViolation.field.length > fieldViolation.field.length && anotherViolation.field.startsWith(fieldViolation.field) && allPathsToArgumentsKeys.includes(anotherViolation.field));
244
- return !containedInAMoreSpecificViolationField;
245
- }).map((fieldViolation) => {
246
- const exactMatchArgumentExpression = explicitPathsToArguments[fieldViolation.field];
247
- if (exactMatchArgumentExpression) {
248
- return {
249
- ...fieldViolation,
250
- field: withRenamedArgument(exactMatchArgumentExpression, argumentNames)
251
- };
252
- }
253
- const longestPartialPathMatch = allPathsToArgumentsKeys?.sort((a, b) => b.length - a.length)?.find((path) => fieldViolation.field.startsWith(path));
254
- if (longestPartialPathMatch) {
255
- const partialMatchArgumentExpression = allPathsToArguments[longestPartialPathMatch];
256
- if (partialMatchArgumentExpression) {
257
- return {
258
- ...fieldViolation,
259
- field: fieldViolation.field.replace(longestPartialPathMatch, withRenamedArgument(partialMatchArgumentExpression, argumentNames))
260
- };
261
- }
262
- }
263
- if (singleArgumentUnchanged) {
264
- return {
265
- ...fieldViolation,
266
- field: `${argumentNames[0]}.${fieldViolation.field}`
267
- };
268
- }
269
- return fieldViolation;
270
- });
271
- };
272
- const withRenamedArgument = (fieldValue, argumentNames) => {
273
- const argIndex = getArgumentIndex(fieldValue);
274
- if (argIndex !== null && typeof argIndex !== "undefined") {
275
- return fieldValue.replace(`$[${argIndex}]`, argumentNames[argIndex]);
276
- }
277
- return fieldValue;
278
- };
279
- const getArgumentIndex = (s) => {
280
- const match = s.match(/\$\[(?<argIndex>\d+)\]/);
281
- return match && match.groups && Number(match.groups.argIndex);
282
- };
283
- var wixContext = {};
284
- function resolveContext() {
285
- const oldContext = typeof $wixContext !== "undefined" && $wixContext.initWixModules ? $wixContext.initWixModules : typeof globalThis.__wix_context__ !== "undefined" && globalThis.__wix_context__.initWixModules ? globalThis.__wix_context__.initWixModules : void 0;
286
- if (oldContext) {
287
- return {
288
- // @ts-expect-error
289
- initWixModules(modules, elevated) {
290
- return runWithoutContext(() => oldContext(modules, elevated));
291
- },
292
- fetchWithAuth() {
293
- throw new Error("fetchWithAuth is not available in this context");
294
- },
295
- graphql() {
296
- throw new Error("graphql is not available in this context");
297
- }
298
- };
299
- }
300
- const contextualClient = typeof $wixContext !== "undefined" ? $wixContext.client : typeof wixContext.client !== "undefined" ? wixContext.client : typeof globalThis.__wix_context__ !== "undefined" ? globalThis.__wix_context__.client : void 0;
301
- const elevatedClient = typeof $wixContext !== "undefined" ? $wixContext.elevatedClient : typeof wixContext.elevatedClient !== "undefined" ? wixContext.elevatedClient : typeof globalThis.__wix_context__ !== "undefined" ? globalThis.__wix_context__.elevatedClient : void 0;
302
- if (!contextualClient && !elevatedClient) {
303
- return;
304
- }
305
- return {
306
- initWixModules(wixModules, elevated) {
307
- if (elevated) {
308
- if (!elevatedClient) {
309
- throw new Error("An elevated client is required to use elevated modules. Make sure to initialize the Wix context with an elevated client before using elevated SDK modules");
310
- }
311
- return runWithoutContext(() => elevatedClient.use(wixModules));
312
- }
313
- if (!contextualClient) {
314
- throw new Error("Wix context is not available. Make sure to initialize the Wix context before using SDK modules");
315
- }
316
- return runWithoutContext(() => contextualClient.use(wixModules));
317
- },
318
- fetchWithAuth: (urlOrRequest, requestInit) => {
319
- if (!contextualClient) {
320
- throw new Error("Wix context is not available. Make sure to initialize the Wix context before using SDK modules");
321
- }
322
- return contextualClient.fetchWithAuth(urlOrRequest, requestInit);
323
- },
324
- getAuth() {
325
- if (!contextualClient) {
326
- throw new Error("Wix context is not available. Make sure to initialize the Wix context before using SDK modules");
327
- }
328
- return contextualClient.auth;
329
- },
330
- async graphql(query, variables, opts) {
331
- if (!contextualClient) {
332
- throw new Error("Wix context is not available. Make sure to initialize the Wix context before using SDK modules");
333
- }
334
- return contextualClient.graphql(query, variables, opts);
335
- }
336
- };
337
- }
338
- function runWithoutContext(fn) {
339
- const globalContext = globalThis.__wix_context__;
340
- const moduleContext = {
341
- client: wixContext.client,
342
- elevatedClient: wixContext.elevatedClient
343
- };
344
- let closureContext;
345
- globalThis.__wix_context__ = void 0;
346
- wixContext.client = void 0;
347
- wixContext.elevatedClient = void 0;
348
- if (typeof $wixContext !== "undefined") {
349
- closureContext = {
350
- client: $wixContext?.client,
351
- elevatedClient: $wixContext?.elevatedClient
352
- };
353
- delete $wixContext.client;
354
- delete $wixContext.elevatedClient;
355
- }
356
- try {
357
- return fn();
358
- } finally {
359
- globalThis.__wix_context__ = globalContext;
360
- wixContext.client = moduleContext.client;
361
- wixContext.elevatedClient = moduleContext.elevatedClient;
362
- if (typeof $wixContext !== "undefined") {
363
- $wixContext.client = closureContext.client;
364
- $wixContext.elevatedClient = closureContext.elevatedClient;
365
- }
366
- }
367
20
  }
368
- function contextualizeRESTModuleV2(restModule, elevated) {
369
- return (...args) => {
370
- const context = resolveContext();
371
- if (!context) {
372
- return restModule.apply(void 0, args);
21
+ async function updateCurrentCartLineItemQuantity(client, lineItems) {
22
+ return wixFetch(client, "/ecom/v1/carts/current/update-line-items-quantity", {
23
+ method: "POST",
24
+ body: {
25
+ lineItems: lineItems.map((item) => ({
26
+ id: item._id,
27
+ quantity: item.quantity
28
+ }))
373
29
  }
374
- return context.initWixModules(restModule, elevated).apply(void 0, args);
375
- };
376
- }
377
- function contextualizeEventDefinitionModuleV2(eventDefinition) {
378
- const contextualMethod = (...args) => {
379
- const context = resolveContext();
380
- if (!context) {
381
- return () => {
382
- return {
383
- slug: eventDefinition.type
384
- };
385
- };
386
- }
387
- return context.initWixModules(eventDefinition).apply(void 0, args);
388
- };
389
- contextualMethod.__type = eventDefinition.__type;
390
- contextualMethod.type = eventDefinition.type;
391
- contextualMethod.isDomainEvent = eventDefinition.isDomainEvent;
392
- contextualMethod.transformations = eventDefinition.transformations;
393
- return contextualMethod;
394
- }
395
- function createRESTModule(descriptor, elevated = false) {
396
- return contextualizeRESTModuleV2(descriptor, elevated);
397
- }
398
- function resolveUrl(opts) {
399
- const domain = resolveDomain(opts.host);
400
- const mappings = resolveMappingsByDomain(domain, opts.domainToMappings);
401
- const path = injectDataIntoProtoPath(opts.protoPath, opts.data || {});
402
- return resolvePathFromMappings(path, mappings);
403
- }
404
- const DOMAINS = ["wix.com", "editorx.com"];
405
- const USER_DOMAIN = "_";
406
- const REGEX_CAPTURE_DOMAINS = new RegExp(`\\.(${DOMAINS.join("|")})$`);
407
- const WIX_API_DOMAINS = ["42.wixprod.net", "uw2-edt-1.wixprod.net"];
408
- const DEV_WIX_CODE_DOMAIN = "dev.wix-code.com";
409
- const REGEX_CAPTURE_PROTO_FIELD = /{(.*)}/;
410
- const REGEX_CAPTURE_API_DOMAINS = new RegExp(`\\.(${WIX_API_DOMAINS.join("|")})$`);
411
- const REGEX_CAPTURE_DEV_WIX_CODE_DOMAIN = new RegExp(`.*\\.${DEV_WIX_CODE_DOMAIN}$`);
412
- function resolveDomain(host) {
413
- const resolvedHost = fixHostExceptions(host);
414
- return resolvedHost.replace(REGEX_CAPTURE_DOMAINS, "._base_domain_").replace(REGEX_CAPTURE_API_DOMAINS, "._api_base_domain_").replace(REGEX_CAPTURE_DEV_WIX_CODE_DOMAIN, "*.dev.wix-code.com");
415
- }
416
- function fixHostExceptions(host) {
417
- return host.replace("create.editorx.com", "editor.editorx.com");
418
- }
419
- function resolveMappingsByDomain(domain, domainToMappings) {
420
- const mappings = domainToMappings[domain] || domainToMappings[USER_DOMAIN];
421
- if (mappings) {
422
- return mappings;
423
- }
424
- const rootDomainMappings = resolveRootDomain(domain, domainToMappings);
425
- if (!rootDomainMappings) {
426
- if (isBaseDomain(domain)) {
427
- return domainToMappings[wwwBaseDomain];
428
- }
429
- }
430
- return rootDomainMappings ?? [];
431
- }
432
- function resolveRootDomain(domain, domainToMappings) {
433
- return Object.entries(domainToMappings).find(([entryDomain]) => {
434
- const [, ...rooDomainSegments] = domain.split(".");
435
- return rooDomainSegments.join(".") === entryDomain;
436
- })?.[1];
437
- }
438
- function isBaseDomain(domain) {
439
- return !!domain.match(/\._base_domain_$/);
440
- }
441
- const wwwBaseDomain = "www._base_domain_";
442
- function injectDataIntoProtoPath(protoPath, data) {
443
- return protoPath.split("/").map((path) => maybeProtoPathToData(path, data)).join("/");
444
- }
445
- function maybeProtoPathToData(protoPath, data) {
446
- const protoRegExpMatch = protoPath.match(REGEX_CAPTURE_PROTO_FIELD) || [];
447
- const field = protoRegExpMatch[1];
448
- if (field) {
449
- const suffix = protoPath.replace(protoRegExpMatch[0], "");
450
- return findByPath(data, field, protoPath, suffix);
451
- }
452
- return protoPath;
453
- }
454
- function findByPath(obj, path, defaultValue, suffix) {
455
- let result = obj;
456
- for (const field of path.split(".")) {
457
- if (!result) {
458
- return defaultValue;
459
- }
460
- result = result[field];
461
- }
462
- return `${result}${suffix}`;
463
- }
464
- function resolvePathFromMappings(protoPath, mappings) {
465
- const mapping = mappings?.find((m) => protoPath.startsWith(m.destPath));
466
- if (!mapping) {
467
- return protoPath;
468
- }
469
- return mapping.srcPath + protoPath.slice(mapping.destPath.length);
30
+ });
470
31
  }
471
- function createEventModule(eventDefinition) {
472
- return contextualizeEventDefinitionModuleV2(eventDefinition);
32
+ async function updateCurrentCart(client, cartInfo) {
33
+ return wixFetch(client, "/ecom/v1/carts/current", {
34
+ method: "PATCH",
35
+ body: { cartInfo }
36
+ });
473
37
  }
474
- function resolveWixHeadlessV1RedirectSessionServiceUrl(opts) {
475
- const domainToMappings = {
476
- "www._base_domain_": [
477
- {
478
- srcPath: "/_api/redirects-api",
479
- destPath: ""
480
- }
481
- ],
482
- "www.wixapis.com": [
483
- {
484
- srcPath: "/_api/redirects-api",
485
- destPath: ""
486
- },
487
- {
488
- srcPath: "/redirect-session",
489
- destPath: ""
490
- },
491
- {
492
- srcPath: "/headless/v1/redirect-session",
493
- destPath: "/v1/redirect-session"
494
- }
495
- ],
496
- "*.dev.wix-code.com": [
497
- {
498
- srcPath: "/headless/v1/redirect-session",
499
- destPath: "/v1/redirect-session"
500
- }
501
- ],
502
- _: [
503
- {
504
- srcPath: "/headless/v1/redirect-session",
505
- destPath: "/v1/redirect-session"
506
- }
507
- ]
508
- };
509
- return resolveUrl(Object.assign(opts, { domainToMappings }));
38
+ async function removeCouponFromCurrentCart(client) {
39
+ return wixFetch(client, "/ecom/v1/carts/current/remove-coupon", {
40
+ method: "POST",
41
+ body: {}
42
+ });
510
43
  }
511
- var PACKAGE_NAME = "@wix/auto_sdk_redirects_redirects";
512
- function createRedirectSession(payload) {
513
- function __createRedirectSession({ host }) {
514
- const metadata = {
515
- entityFqdn: "wix.headless.v1.redirect_session",
516
- method: "POST",
517
- methodFqn: "wix.headless.v1.RedirectSessionService.CreateRedirectSession",
518
- packageName: PACKAGE_NAME,
519
- migrationOptions: {
520
- optInTransformResponse: true
521
- },
522
- url: resolveWixHeadlessV1RedirectSessionServiceUrl({
523
- protoPath: "/v1/redirect-session",
524
- data: payload,
525
- host
526
- }),
527
- data: payload
528
- };
529
- return metadata;
530
- }
531
- return __createRedirectSession;
44
+ async function estimateCurrentCartTotals(client) {
45
+ return wixFetch(client, "/ecom/v1/carts/current/estimate-totals", {
46
+ method: "POST",
47
+ body: {}
48
+ });
532
49
  }
533
- var LocationType = /* @__PURE__ */ ((LocationType2) => {
534
- LocationType2["UNDEFINED"] = "UNDEFINED";
535
- LocationType2["OWNER_BUSINESS"] = "OWNER_BUSINESS";
536
- LocationType2["OWNER_CUSTOM"] = "OWNER_CUSTOM";
537
- LocationType2["CUSTOM"] = "CUSTOM";
538
- return LocationType2;
539
- })(LocationType || {});
540
- var Prompt = /* @__PURE__ */ ((Prompt2) => {
541
- Prompt2["login"] = "login";
542
- Prompt2["none"] = "none";
543
- Prompt2["consent"] = "consent";
544
- Prompt2["select_account"] = "select_account";
545
- return Prompt2;
546
- })(Prompt || {});
547
- var MembersAccountSection = /* @__PURE__ */ ((MembersAccountSection2) => {
548
- MembersAccountSection2["ACCOUNT_INFO"] = "ACCOUNT_INFO";
549
- MembersAccountSection2["BOOKINGS"] = "BOOKINGS";
550
- MembersAccountSection2["ORDERS"] = "ORDERS";
551
- MembersAccountSection2["SUBSCRIPTIONS"] = "SUBSCRIPTIONS";
552
- MembersAccountSection2["EVENTS"] = "EVENTS";
553
- return MembersAccountSection2;
554
- })(MembersAccountSection || {});
555
- var AttachPagesResponseStatus = /* @__PURE__ */ ((AttachPagesResponseStatus2) => {
556
- AttachPagesResponseStatus2["UNKNOWN"] = "UNKNOWN";
557
- AttachPagesResponseStatus2["SUCCESS"] = "SUCCESS";
558
- AttachPagesResponseStatus2["NO_ACTION"] = "NO_ACTION";
559
- AttachPagesResponseStatus2["ERROR"] = "ERROR";
560
- return AttachPagesResponseStatus2;
561
- })(AttachPagesResponseStatus || {});
562
- var CallbackType = /* @__PURE__ */ ((CallbackType2) => {
563
- CallbackType2["UNKNOWN"] = "UNKNOWN";
564
- CallbackType2["LOGOUT"] = "LOGOUT";
565
- CallbackType2["CHECKOUT"] = "CHECKOUT";
566
- CallbackType2["AUTHORIZE"] = "AUTHORIZE";
567
- return CallbackType2;
568
- })(CallbackType || {});
569
- var Status = /* @__PURE__ */ ((Status2) => {
570
- Status2["UNKNOWN"] = "UNKNOWN";
571
- Status2["SUCCESS"] = "SUCCESS";
572
- Status2["ERROR"] = "ERROR";
573
- return Status2;
574
- })(Status || {});
575
- var WebhookIdentityType = /* @__PURE__ */ ((WebhookIdentityType2) => {
576
- WebhookIdentityType2["UNKNOWN"] = "UNKNOWN";
577
- WebhookIdentityType2["ANONYMOUS_VISITOR"] = "ANONYMOUS_VISITOR";
578
- WebhookIdentityType2["MEMBER"] = "MEMBER";
579
- WebhookIdentityType2["WIX_USER"] = "WIX_USER";
580
- WebhookIdentityType2["APP"] = "APP";
581
- return WebhookIdentityType2;
582
- })(WebhookIdentityType || {});
583
- async function createRedirectSession2(options) {
584
- const { httpClient, sideEffects } = arguments[1];
585
- const payload = renameKeysFromSDKRequestToRESTRequest({
586
- bookingsCheckout: options?.bookingsCheckout,
587
- ecomCheckout: options?.ecomCheckout,
588
- eventsCheckout: options?.eventsCheckout,
589
- paidPlansCheckout: options?.paidPlansCheckout,
590
- login: options?.login,
591
- logout: options?.logout,
592
- auth: options?.auth,
593
- storesProduct: options?.storesProduct,
594
- bookingsBook: options?.bookingsBook,
595
- callbacks: options?.callbacks,
596
- preferences: options?.preferences,
597
- origin: options?.origin
50
+ async function createCheckoutFromCurrentCart(client) {
51
+ return wixFetch(client, "/ecom/v1/carts/current/create-checkout", {
52
+ method: "POST",
53
+ body: {}
598
54
  });
599
- const reqOpts = createRedirectSession(payload);
600
- sideEffects?.onSiteCall?.();
601
- try {
602
- const result = await httpClient.request(reqOpts);
603
- sideEffects?.onSuccess?.(result);
604
- return renameKeysFromRESTResponseToSDKResponse(result.data);
605
- } catch (err) {
606
- const transformedError = transformError(
607
- err,
608
- {
609
- spreadPathsToArguments: {},
610
- explicitPathsToArguments: {
611
- bookingsCheckout: "$[0].bookingsCheckout",
612
- ecomCheckout: "$[0].ecomCheckout",
613
- eventsCheckout: "$[0].eventsCheckout",
614
- paidPlansCheckout: "$[0].paidPlansCheckout",
615
- login: "$[0].login",
616
- logout: "$[0].logout",
617
- auth: "$[0].auth",
618
- storesProduct: "$[0].storesProduct",
619
- bookingsBook: "$[0].bookingsBook",
620
- callbacks: "$[0].callbacks",
621
- preferences: "$[0].preferences",
622
- origin: "$[0].origin"
623
- },
624
- singleArgumentUnchanged: false
625
- },
626
- ["options"]
627
- );
628
- sideEffects?.onError?.(err);
629
- throw transformedError;
630
- }
631
55
  }
632
- function createRedirectSession3(httpClient) {
633
- return (options) => createRedirectSession2(
634
- options,
635
- // @ts-ignore
636
- { httpClient }
637
- );
56
+ async function createRedirectSession(client, options) {
57
+ return wixFetch(client, "/redirects-api/v1/redirect-session", {
58
+ method: "POST",
59
+ body: options
60
+ });
638
61
  }
639
- var onRedirectSessionCreated = EventDefinition(
640
- "wix.headless.v1.redirect_session_created",
641
- true,
642
- (event) => renameKeysFromRESTResponseToSDKResponse(
643
- transformPaths(event, [
644
- {
645
- transformFn: transformRESTTimestampToSDKTimestamp,
646
- paths: [{ path: "metadata.eventTime" }]
647
- }
648
- ])
649
- )
650
- )();
651
- var createRedirectSession4 = /* @__PURE__ */ createRESTModule(createRedirectSession3);
652
- var onRedirectSessionCreated2 = createEventModule(
653
- onRedirectSessionCreated
654
- );
655
- const redirects = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
656
- __proto__: null,
657
- AttachPagesResponseStatus,
658
- CallbackType,
659
- LocationType,
660
- MembersAccountSection,
661
- Prompt,
662
- Status,
663
- WebhookIdentityType,
664
- createRedirectSession: createRedirectSession4,
665
- onRedirectSessionCreated: onRedirectSessionCreated2
666
- }, Symbol.toStringTag, { value: "Module" }));
667
- let redirectsInstance;
668
- function getRedirectsClient(wixClient) {
669
- if (!redirectsInstance) {
670
- redirectsInstance = wixClient.use(redirects);
671
- }
672
- return redirectsInstance;
62
+ function stripWixMediaResize(url) {
63
+ return url.replace(/\/v1\/(?:fit|fill|crop)\/[^/]+\/file\.\w+$/, "");
673
64
  }
674
65
  function parseWixMediaUrl(url) {
675
66
  if (!url) return null;
@@ -707,7 +98,10 @@ function formatWixMediaUrl(_id, url, resize) {
707
98
  }
708
99
  }
709
100
  if ((url == null ? void 0 : url.startsWith("http://")) || (url == null ? void 0 : url.startsWith("https://"))) {
710
- return url;
101
+ return stripWixMediaResize(url) + resizeFragment;
102
+ }
103
+ if (_id) {
104
+ return `https://static.wixstatic.com/media/${_id}${resizeFragment}`;
711
105
  }
712
106
  return "";
713
107
  }
@@ -719,16 +113,21 @@ function mapLineItem(item) {
719
113
  const variantParts = descriptionLines.filter((line) => line.name?.translated).map(
720
114
  (line) => `${line.name?.translated}: ${line.colorInfo?.translated || line.plainText?.translated || ""}`
721
115
  );
722
- const slug = item.url?.split("/").pop() || "";
116
+ const rawUrl = item.url;
117
+ const urlString = typeof rawUrl === "string" ? rawUrl : rawUrl?.relativePath || rawUrl?.url || "";
118
+ const slug = urlString.split("/").pop() || "";
119
+ const rawImage = item.image;
120
+ const imageUrl = typeof rawImage === "string" ? rawImage : rawImage?.url || "";
121
+ const imageId = typeof rawImage === "string" ? "" : rawImage?.id || "";
723
122
  return {
724
- lineItemId: item._id || "",
123
+ lineItemId: item._id || item.id || "",
725
124
  productId: catalogRef?.catalogItemId || "",
726
125
  productName: item.productName?.translated || item.productName?.original || "",
727
126
  productUrl: slug ? `/products/${slug}` : "",
728
127
  variantName: variantParts.join(" / "),
729
128
  sku: physicalProperties?.sku || "",
730
129
  image: {
731
- url: formatWixMediaUrl("", item.image || ""),
130
+ url: formatWixMediaUrl(imageId, imageUrl),
732
131
  altText: item.productName?.translated || ""
733
132
  },
734
133
  quantity: item.quantity || 1,
@@ -806,7 +205,7 @@ function mapCartToState(cart) {
806
205
  const lineItems = (cart.lineItems || []).map(mapLineItem);
807
206
  const appliedCoupon = cart.appliedDiscounts?.find((d) => d.coupon?.code)?.coupon?.code || "";
808
207
  return {
809
- cartId: cart._id || "",
208
+ cartId: cart._id || cart.id || "",
810
209
  isEmpty: lineItems.length === 0,
811
210
  lineItems,
812
211
  summary: mapCartSummary(cart),
@@ -846,10 +245,10 @@ function isCartNotFoundError(error) {
846
245
  if (message.includes("not found") && message.includes("cart")) return true;
847
246
  return false;
848
247
  }
849
- async function getCurrentCartOrNull(cartClient) {
248
+ async function getCurrentCartOrNull(wixClient) {
850
249
  try {
851
- const response = await cartClient.getCurrentCart();
852
- return response ?? null;
250
+ const response = await getCurrentCart(wixClient);
251
+ return response.cart ?? null;
853
252
  } catch (error) {
854
253
  if (isCartNotFoundError(error)) {
855
254
  return null;
@@ -857,9 +256,9 @@ async function getCurrentCartOrNull(cartClient) {
857
256
  throw error;
858
257
  }
859
258
  }
860
- async function estimateCurrentCartTotalsOrNull(cartClient) {
259
+ async function estimateCurrentCartTotalsOrNull(wixClient) {
861
260
  try {
862
- const response = await cartClient.estimateCurrentCartTotals({});
261
+ const response = await estimateCurrentCartTotals(wixClient);
863
262
  return response ?? null;
864
263
  } catch (error) {
865
264
  if (isCartNotFoundError(error)) {
@@ -881,7 +280,7 @@ function mapEstimateTotalsToState(estimate) {
881
280
  const discountAmount = parseFloat(priceSummary?.discount?.amount || "0");
882
281
  const hasTax = parseFloat(taxSummary?.totalTax?.amount || "0") > 0;
883
282
  return {
884
- cartId: cart._id || "",
283
+ cartId: cart._id || cart.id || "",
885
284
  isEmpty: lineItems.length === 0,
886
285
  lineItems,
887
286
  summary: {
@@ -915,8 +314,6 @@ const WIX_CART_CONTEXT = createJayContext("wix:cart");
915
314
  function provideWixCartContext(thankYouUrl = "/thank-you") {
916
315
  const wixClientContext = useGlobalContext(WIX_CLIENT_CONTEXT);
917
316
  const wixClient = wixClientContext.client;
918
- const cartClient = getCurrentCartClient(wixClient);
919
- const redirectsClient = getRedirectsClient(wixClient);
920
317
  const cartContext = registerReactiveGlobalContext(WIX_CART_CONTEXT, () => {
921
318
  const [itemCount, setItemCount] = createSignal(0);
922
319
  const [hasItems, setHasItems] = createSignal(false);
@@ -930,77 +327,74 @@ function provideWixCartContext(thankYouUrl = "/thank-you") {
930
327
  });
931
328
  }
932
329
  async function refreshCartIndicator() {
933
- const cart = await getCurrentCartOrNull(cartClient);
330
+ const cart = await getCurrentCartOrNull(wixClient);
934
331
  updateIndicatorFromCart(cart);
935
332
  }
936
333
  async function getEstimatedCart() {
937
- const estimate = await estimateCurrentCartTotalsOrNull(cartClient);
334
+ const estimate = await estimateCurrentCartTotalsOrNull(wixClient);
938
335
  return mapEstimateTotalsToState(estimate);
939
336
  }
940
337
  async function addToCart(productId, quantity = 1, options) {
941
338
  console.log(`[WixCart] Adding to cart: ${productId} x ${quantity}`, options);
339
+ const catalogOptions = {};
340
+ if (options?.variantId) catalogOptions.variantId = options.variantId;
341
+ if (options?.modifiers) catalogOptions.options = options.modifiers;
342
+ if (options?.customTextFields)
343
+ catalogOptions.customTextFields = options.customTextFields;
942
344
  const lineItem = {
943
345
  catalogReference: {
944
346
  catalogItemId: productId,
945
347
  appId: WIX_STORES_APP_ID,
946
- options: {
947
- variantId: options?.variantId,
948
- options: options?.modifiers,
949
- customTextFields: options?.customTextFields
950
- }
348
+ ...Object.keys(catalogOptions).length > 0 ? { options: catalogOptions } : {}
951
349
  },
952
350
  quantity
953
351
  };
954
- const result = await cartClient.addToCurrentCart({
955
- lineItems: [lineItem]
956
- });
352
+ const result = await addToCurrentCart(wixClient, [lineItem]);
957
353
  updateIndicatorFromCart(result.cart ?? null);
958
354
  onItemAddedToCart.emit();
959
355
  return { cartState: mapCartToState(result.cart ?? null) };
960
356
  }
961
357
  async function removeLineItems(lineItemIds) {
962
- const result = await cartClient.removeLineItemsFromCurrentCart(lineItemIds);
358
+ const result = await removeLineItemsFromCurrentCart(wixClient, lineItemIds);
963
359
  updateIndicatorFromCart(result.cart ?? null);
964
360
  return { cartState: mapCartToState(result.cart ?? null) };
965
361
  }
966
362
  async function updateLineItemQuantity(lineItemId, quantity) {
967
363
  let result;
968
364
  if (quantity === 0) {
969
- result = await cartClient.removeLineItemsFromCurrentCart([lineItemId]);
365
+ result = await removeLineItemsFromCurrentCart(wixClient, [lineItemId]);
970
366
  } else {
971
- result = await cartClient.updateCurrentCartLineItemQuantity([
972
- { _id: lineItemId, quantity }
973
- ]);
367
+ result = await updateCurrentCartLineItemQuantity(wixClient, [{ _id: lineItemId, quantity }]);
974
368
  }
975
369
  updateIndicatorFromCart(result.cart ?? null);
976
370
  return { cartState: mapCartToState(result.cart ?? null) };
977
371
  }
978
372
  async function clearCart() {
979
- const cart = await getCurrentCartOrNull(cartClient);
373
+ const cart = await getCurrentCartOrNull(wixClient);
980
374
  if (cart?.lineItems?.length) {
981
375
  const lineItemIds = cart.lineItems.map((item) => item._id || "").filter(Boolean);
982
376
  if (lineItemIds.length > 0) {
983
- await cartClient.removeLineItemsFromCurrentCart(lineItemIds);
377
+ await removeLineItemsFromCurrentCart(wixClient, lineItemIds);
984
378
  }
985
379
  }
986
380
  setItemCount(0);
987
381
  setHasItems(false);
988
382
  }
989
383
  async function applyCoupon(couponCode) {
990
- const result = await cartClient.updateCurrentCart({ couponCode });
384
+ const result = await updateCurrentCart(wixClient, { couponCode });
991
385
  updateIndicatorFromCart(result ?? null);
992
386
  return { cartState: mapCartToState(result ?? null) };
993
387
  }
994
388
  async function removeCoupon() {
995
- const result = await cartClient.removeCouponFromCurrentCart();
389
+ const result = await removeCouponFromCurrentCart(wixClient);
996
390
  updateIndicatorFromCart(result.cart ?? null);
997
391
  return { cartState: mapCartToState(result.cart ?? null) };
998
392
  }
999
393
  async function checkout() {
1000
- const { checkoutId } = await cartClient.createCheckoutFromCurrentCart({});
394
+ const { checkoutId } = await createCheckoutFromCurrentCart(wixClient);
1001
395
  if (!checkoutId) throw new Error("Failed to create checkout from cart");
1002
396
  const postFlowUrl = window.location.origin + thankYouUrl;
1003
- const { redirectSession } = await redirectsClient.createRedirectSession({
397
+ const { redirectSession } = await createRedirectSession(wixClient, {
1004
398
  ecomCheckout: { checkoutId },
1005
399
  callbacks: { postFlowUrl }
1006
400
  });