@plasmicpkgs/commerce-commercetools 0.0.2

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.
Files changed (38) hide show
  1. package/LICENSE.md +21 -0
  2. package/README.md +1 -0
  3. package/dist/cart/index.d.ts +2 -0
  4. package/dist/cart/use-add-item.d.ts +5 -0
  5. package/dist/cart/use-cart.d.ts +13 -0
  6. package/dist/client.d.ts +3 -0
  7. package/dist/commerce-commercetools.cjs.development.js +1734 -0
  8. package/dist/commerce-commercetools.cjs.development.js.map +1 -0
  9. package/dist/commerce-commercetools.cjs.production.min.js +2 -0
  10. package/dist/commerce-commercetools.cjs.production.min.js.map +1 -0
  11. package/dist/commerce-commercetools.esm.js +1722 -0
  12. package/dist/commerce-commercetools.esm.js.map +1 -0
  13. package/dist/commercetools.d.ts +5 -0
  14. package/dist/const.d.ts +4 -0
  15. package/dist/fetcher.d.ts +3 -0
  16. package/dist/index.d.ts +5 -0
  17. package/dist/index.js +8 -0
  18. package/dist/product/use-product.d.ts +12 -0
  19. package/dist/product/use-search.d.ts +26 -0
  20. package/dist/provider.d.ts +47 -0
  21. package/dist/registerCommerceProvider.d.ts +11 -0
  22. package/dist/registerable.d.ts +6 -0
  23. package/dist/site/use-brands.d.ts +11 -0
  24. package/dist/site/use-categories.d.ts +11 -0
  25. package/dist/types/cart.d.ts +24 -0
  26. package/dist/types/index.d.ts +4 -0
  27. package/dist/types/product.d.ts +14 -0
  28. package/dist/types/site.d.ts +7 -0
  29. package/dist/utils/cart-active.d.ts +4 -0
  30. package/dist/utils/cart-cookie.d.ts +3 -0
  31. package/dist/utils/cart-create.d.ts +4 -0
  32. package/dist/utils/common.d.ts +2 -0
  33. package/dist/utils/cookies.d.ts +3 -0
  34. package/dist/utils/get-sort-variables.d.ts +2 -0
  35. package/dist/utils/index.d.ts +7 -0
  36. package/dist/utils/localized-string.d.ts +2 -0
  37. package/dist/utils/normalize.d.ts +21 -0
  38. package/package.json +48 -0
@@ -0,0 +1,1722 @@
1
+ import registerGlobalContext from '@plasmicapp/host/registerGlobalContext';
2
+ import React, { useMemo, useCallback } from 'react';
3
+ import { useCart, useCommerce as useCommerce$1, getCommerceProvider as getCommerceProvider$1 } from '@plasmicpkgs/commerce';
4
+ import Cookies from 'js-cookie';
5
+ import { createApiBuilderFromCtpClient } from '@commercetools/platform-sdk';
6
+ import { ClientBuilder } from '@commercetools/sdk-client-v2';
7
+ import { usePlasmicQueryData } from '@plasmicapp/query';
8
+
9
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
10
+ try {
11
+ var info = gen[key](arg);
12
+ var value = info.value;
13
+ } catch (error) {
14
+ reject(error);
15
+ return;
16
+ }
17
+
18
+ if (info.done) {
19
+ resolve(value);
20
+ } else {
21
+ Promise.resolve(value).then(_next, _throw);
22
+ }
23
+ }
24
+
25
+ function _asyncToGenerator(fn) {
26
+ return function () {
27
+ var self = this,
28
+ args = arguments;
29
+ return new Promise(function (resolve, reject) {
30
+ var gen = fn.apply(self, args);
31
+
32
+ function _next(value) {
33
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
34
+ }
35
+
36
+ function _throw(err) {
37
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
38
+ }
39
+
40
+ _next(undefined);
41
+ });
42
+ };
43
+ }
44
+
45
+ function _extends() {
46
+ _extends = Object.assign || function (target) {
47
+ for (var i = 1; i < arguments.length; i++) {
48
+ var source = arguments[i];
49
+
50
+ for (var key in source) {
51
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
52
+ target[key] = source[key];
53
+ }
54
+ }
55
+ }
56
+
57
+ return target;
58
+ };
59
+
60
+ return _extends.apply(this, arguments);
61
+ }
62
+
63
+ function createCommonjsModule(fn, module) {
64
+ return module = { exports: {} }, fn(module, module.exports), module.exports;
65
+ }
66
+
67
+ var runtime_1 = /*#__PURE__*/createCommonjsModule(function (module) {
68
+ /**
69
+ * Copyright (c) 2014-present, Facebook, Inc.
70
+ *
71
+ * This source code is licensed under the MIT license found in the
72
+ * LICENSE file in the root directory of this source tree.
73
+ */
74
+ var runtime = function (exports) {
75
+
76
+ var Op = Object.prototype;
77
+ var hasOwn = Op.hasOwnProperty;
78
+ var undefined$1; // More compressible than void 0.
79
+
80
+ var $Symbol = typeof Symbol === "function" ? Symbol : {};
81
+ var iteratorSymbol = $Symbol.iterator || "@@iterator";
82
+ var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
83
+ var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
84
+
85
+ function define(obj, key, value) {
86
+ Object.defineProperty(obj, key, {
87
+ value: value,
88
+ enumerable: true,
89
+ configurable: true,
90
+ writable: true
91
+ });
92
+ return obj[key];
93
+ }
94
+
95
+ try {
96
+ // IE 8 has a broken Object.defineProperty that only works on DOM objects.
97
+ define({}, "");
98
+ } catch (err) {
99
+ define = function define(obj, key, value) {
100
+ return obj[key] = value;
101
+ };
102
+ }
103
+
104
+ function wrap(innerFn, outerFn, self, tryLocsList) {
105
+ // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
106
+ var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
107
+ var generator = Object.create(protoGenerator.prototype);
108
+ var context = new Context(tryLocsList || []); // The ._invoke method unifies the implementations of the .next,
109
+ // .throw, and .return methods.
110
+
111
+ generator._invoke = makeInvokeMethod(innerFn, self, context);
112
+ return generator;
113
+ }
114
+
115
+ exports.wrap = wrap; // Try/catch helper to minimize deoptimizations. Returns a completion
116
+ // record like context.tryEntries[i].completion. This interface could
117
+ // have been (and was previously) designed to take a closure to be
118
+ // invoked without arguments, but in all the cases we care about we
119
+ // already have an existing method we want to call, so there's no need
120
+ // to create a new function object. We can even get away with assuming
121
+ // the method takes exactly one argument, since that happens to be true
122
+ // in every case, so we don't have to touch the arguments object. The
123
+ // only additional allocation required is the completion record, which
124
+ // has a stable shape and so hopefully should be cheap to allocate.
125
+
126
+ function tryCatch(fn, obj, arg) {
127
+ try {
128
+ return {
129
+ type: "normal",
130
+ arg: fn.call(obj, arg)
131
+ };
132
+ } catch (err) {
133
+ return {
134
+ type: "throw",
135
+ arg: err
136
+ };
137
+ }
138
+ }
139
+
140
+ var GenStateSuspendedStart = "suspendedStart";
141
+ var GenStateSuspendedYield = "suspendedYield";
142
+ var GenStateExecuting = "executing";
143
+ var GenStateCompleted = "completed"; // Returning this object from the innerFn has the same effect as
144
+ // breaking out of the dispatch switch statement.
145
+
146
+ var ContinueSentinel = {}; // Dummy constructor functions that we use as the .constructor and
147
+ // .constructor.prototype properties for functions that return Generator
148
+ // objects. For full spec compliance, you may wish to configure your
149
+ // minifier not to mangle the names of these two functions.
150
+
151
+ function Generator() {}
152
+
153
+ function GeneratorFunction() {}
154
+
155
+ function GeneratorFunctionPrototype() {} // This is a polyfill for %IteratorPrototype% for environments that
156
+ // don't natively support it.
157
+
158
+
159
+ var IteratorPrototype = {};
160
+ define(IteratorPrototype, iteratorSymbol, function () {
161
+ return this;
162
+ });
163
+ var getProto = Object.getPrototypeOf;
164
+ var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
165
+
166
+ if (NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
167
+ // This environment has a native %IteratorPrototype%; use it instead
168
+ // of the polyfill.
169
+ IteratorPrototype = NativeIteratorPrototype;
170
+ }
171
+
172
+ var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
173
+ GeneratorFunction.prototype = GeneratorFunctionPrototype;
174
+ define(Gp, "constructor", GeneratorFunctionPrototype);
175
+ define(GeneratorFunctionPrototype, "constructor", GeneratorFunction);
176
+ GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"); // Helper for defining the .next, .throw, and .return methods of the
177
+ // Iterator interface in terms of a single ._invoke method.
178
+
179
+ function defineIteratorMethods(prototype) {
180
+ ["next", "throw", "return"].forEach(function (method) {
181
+ define(prototype, method, function (arg) {
182
+ return this._invoke(method, arg);
183
+ });
184
+ });
185
+ }
186
+
187
+ exports.isGeneratorFunction = function (genFun) {
188
+ var ctor = typeof genFun === "function" && genFun.constructor;
189
+ return ctor ? ctor === GeneratorFunction || // For the native GeneratorFunction constructor, the best we can
190
+ // do is to check its .name property.
191
+ (ctor.displayName || ctor.name) === "GeneratorFunction" : false;
192
+ };
193
+
194
+ exports.mark = function (genFun) {
195
+ if (Object.setPrototypeOf) {
196
+ Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
197
+ } else {
198
+ genFun.__proto__ = GeneratorFunctionPrototype;
199
+ define(genFun, toStringTagSymbol, "GeneratorFunction");
200
+ }
201
+
202
+ genFun.prototype = Object.create(Gp);
203
+ return genFun;
204
+ }; // Within the body of any async function, `await x` is transformed to
205
+ // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
206
+ // `hasOwn.call(value, "__await")` to determine if the yielded value is
207
+ // meant to be awaited.
208
+
209
+
210
+ exports.awrap = function (arg) {
211
+ return {
212
+ __await: arg
213
+ };
214
+ };
215
+
216
+ function AsyncIterator(generator, PromiseImpl) {
217
+ function invoke(method, arg, resolve, reject) {
218
+ var record = tryCatch(generator[method], generator, arg);
219
+
220
+ if (record.type === "throw") {
221
+ reject(record.arg);
222
+ } else {
223
+ var result = record.arg;
224
+ var value = result.value;
225
+
226
+ if (value && typeof value === "object" && hasOwn.call(value, "__await")) {
227
+ return PromiseImpl.resolve(value.__await).then(function (value) {
228
+ invoke("next", value, resolve, reject);
229
+ }, function (err) {
230
+ invoke("throw", err, resolve, reject);
231
+ });
232
+ }
233
+
234
+ return PromiseImpl.resolve(value).then(function (unwrapped) {
235
+ // When a yielded Promise is resolved, its final value becomes
236
+ // the .value of the Promise<{value,done}> result for the
237
+ // current iteration.
238
+ result.value = unwrapped;
239
+ resolve(result);
240
+ }, function (error) {
241
+ // If a rejected Promise was yielded, throw the rejection back
242
+ // into the async generator function so it can be handled there.
243
+ return invoke("throw", error, resolve, reject);
244
+ });
245
+ }
246
+ }
247
+
248
+ var previousPromise;
249
+
250
+ function enqueue(method, arg) {
251
+ function callInvokeWithMethodAndArg() {
252
+ return new PromiseImpl(function (resolve, reject) {
253
+ invoke(method, arg, resolve, reject);
254
+ });
255
+ }
256
+
257
+ return previousPromise = // If enqueue has been called before, then we want to wait until
258
+ // all previous Promises have been resolved before calling invoke,
259
+ // so that results are always delivered in the correct order. If
260
+ // enqueue has not been called before, then it is important to
261
+ // call invoke immediately, without waiting on a callback to fire,
262
+ // so that the async generator function has the opportunity to do
263
+ // any necessary setup in a predictable way. This predictability
264
+ // is why the Promise constructor synchronously invokes its
265
+ // executor callback, and why async functions synchronously
266
+ // execute code before the first await. Since we implement simple
267
+ // async functions in terms of async generators, it is especially
268
+ // important to get this right, even though it requires care.
269
+ previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, // Avoid propagating failures to Promises returned by later
270
+ // invocations of the iterator.
271
+ callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
272
+ } // Define the unified helper method that is used to implement .next,
273
+ // .throw, and .return (see defineIteratorMethods).
274
+
275
+
276
+ this._invoke = enqueue;
277
+ }
278
+
279
+ defineIteratorMethods(AsyncIterator.prototype);
280
+ define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
281
+ return this;
282
+ });
283
+ exports.AsyncIterator = AsyncIterator; // Note that simple async functions are implemented on top of
284
+ // AsyncIterator objects; they just return a Promise for the value of
285
+ // the final result produced by the iterator.
286
+
287
+ exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
288
+ if (PromiseImpl === void 0) PromiseImpl = Promise;
289
+ var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
290
+ return exports.isGeneratorFunction(outerFn) ? iter // If outerFn is a generator, return the full iterator.
291
+ : iter.next().then(function (result) {
292
+ return result.done ? result.value : iter.next();
293
+ });
294
+ };
295
+
296
+ function makeInvokeMethod(innerFn, self, context) {
297
+ var state = GenStateSuspendedStart;
298
+ return function invoke(method, arg) {
299
+ if (state === GenStateExecuting) {
300
+ throw new Error("Generator is already running");
301
+ }
302
+
303
+ if (state === GenStateCompleted) {
304
+ if (method === "throw") {
305
+ throw arg;
306
+ } // Be forgiving, per 25.3.3.3.3 of the spec:
307
+ // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
308
+
309
+
310
+ return doneResult();
311
+ }
312
+
313
+ context.method = method;
314
+ context.arg = arg;
315
+
316
+ while (true) {
317
+ var delegate = context.delegate;
318
+
319
+ if (delegate) {
320
+ var delegateResult = maybeInvokeDelegate(delegate, context);
321
+
322
+ if (delegateResult) {
323
+ if (delegateResult === ContinueSentinel) continue;
324
+ return delegateResult;
325
+ }
326
+ }
327
+
328
+ if (context.method === "next") {
329
+ // Setting context._sent for legacy support of Babel's
330
+ // function.sent implementation.
331
+ context.sent = context._sent = context.arg;
332
+ } else if (context.method === "throw") {
333
+ if (state === GenStateSuspendedStart) {
334
+ state = GenStateCompleted;
335
+ throw context.arg;
336
+ }
337
+
338
+ context.dispatchException(context.arg);
339
+ } else if (context.method === "return") {
340
+ context.abrupt("return", context.arg);
341
+ }
342
+
343
+ state = GenStateExecuting;
344
+ var record = tryCatch(innerFn, self, context);
345
+
346
+ if (record.type === "normal") {
347
+ // If an exception is thrown from innerFn, we leave state ===
348
+ // GenStateExecuting and loop back for another invocation.
349
+ state = context.done ? GenStateCompleted : GenStateSuspendedYield;
350
+
351
+ if (record.arg === ContinueSentinel) {
352
+ continue;
353
+ }
354
+
355
+ return {
356
+ value: record.arg,
357
+ done: context.done
358
+ };
359
+ } else if (record.type === "throw") {
360
+ state = GenStateCompleted; // Dispatch the exception by looping back around to the
361
+ // context.dispatchException(context.arg) call above.
362
+
363
+ context.method = "throw";
364
+ context.arg = record.arg;
365
+ }
366
+ }
367
+ };
368
+ } // Call delegate.iterator[context.method](context.arg) and handle the
369
+ // result, either by returning a { value, done } result from the
370
+ // delegate iterator, or by modifying context.method and context.arg,
371
+ // setting context.delegate to null, and returning the ContinueSentinel.
372
+
373
+
374
+ function maybeInvokeDelegate(delegate, context) {
375
+ var method = delegate.iterator[context.method];
376
+
377
+ if (method === undefined$1) {
378
+ // A .throw or .return when the delegate iterator has no .throw
379
+ // method always terminates the yield* loop.
380
+ context.delegate = null;
381
+
382
+ if (context.method === "throw") {
383
+ // Note: ["return"] must be used for ES3 parsing compatibility.
384
+ if (delegate.iterator["return"]) {
385
+ // If the delegate iterator has a return method, give it a
386
+ // chance to clean up.
387
+ context.method = "return";
388
+ context.arg = undefined$1;
389
+ maybeInvokeDelegate(delegate, context);
390
+
391
+ if (context.method === "throw") {
392
+ // If maybeInvokeDelegate(context) changed context.method from
393
+ // "return" to "throw", let that override the TypeError below.
394
+ return ContinueSentinel;
395
+ }
396
+ }
397
+
398
+ context.method = "throw";
399
+ context.arg = new TypeError("The iterator does not provide a 'throw' method");
400
+ }
401
+
402
+ return ContinueSentinel;
403
+ }
404
+
405
+ var record = tryCatch(method, delegate.iterator, context.arg);
406
+
407
+ if (record.type === "throw") {
408
+ context.method = "throw";
409
+ context.arg = record.arg;
410
+ context.delegate = null;
411
+ return ContinueSentinel;
412
+ }
413
+
414
+ var info = record.arg;
415
+
416
+ if (!info) {
417
+ context.method = "throw";
418
+ context.arg = new TypeError("iterator result is not an object");
419
+ context.delegate = null;
420
+ return ContinueSentinel;
421
+ }
422
+
423
+ if (info.done) {
424
+ // Assign the result of the finished delegate to the temporary
425
+ // variable specified by delegate.resultName (see delegateYield).
426
+ context[delegate.resultName] = info.value; // Resume execution at the desired location (see delegateYield).
427
+
428
+ context.next = delegate.nextLoc; // If context.method was "throw" but the delegate handled the
429
+ // exception, let the outer generator proceed normally. If
430
+ // context.method was "next", forget context.arg since it has been
431
+ // "consumed" by the delegate iterator. If context.method was
432
+ // "return", allow the original .return call to continue in the
433
+ // outer generator.
434
+
435
+ if (context.method !== "return") {
436
+ context.method = "next";
437
+ context.arg = undefined$1;
438
+ }
439
+ } else {
440
+ // Re-yield the result returned by the delegate method.
441
+ return info;
442
+ } // The delegate iterator is finished, so forget it and continue with
443
+ // the outer generator.
444
+
445
+
446
+ context.delegate = null;
447
+ return ContinueSentinel;
448
+ } // Define Generator.prototype.{next,throw,return} in terms of the
449
+ // unified ._invoke helper method.
450
+
451
+
452
+ defineIteratorMethods(Gp);
453
+ define(Gp, toStringTagSymbol, "Generator"); // A Generator should always return itself as the iterator object when the
454
+ // @@iterator function is called on it. Some browsers' implementations of the
455
+ // iterator prototype chain incorrectly implement this, causing the Generator
456
+ // object to not be returned from this call. This ensures that doesn't happen.
457
+ // See https://github.com/facebook/regenerator/issues/274 for more details.
458
+
459
+ define(Gp, iteratorSymbol, function () {
460
+ return this;
461
+ });
462
+ define(Gp, "toString", function () {
463
+ return "[object Generator]";
464
+ });
465
+
466
+ function pushTryEntry(locs) {
467
+ var entry = {
468
+ tryLoc: locs[0]
469
+ };
470
+
471
+ if (1 in locs) {
472
+ entry.catchLoc = locs[1];
473
+ }
474
+
475
+ if (2 in locs) {
476
+ entry.finallyLoc = locs[2];
477
+ entry.afterLoc = locs[3];
478
+ }
479
+
480
+ this.tryEntries.push(entry);
481
+ }
482
+
483
+ function resetTryEntry(entry) {
484
+ var record = entry.completion || {};
485
+ record.type = "normal";
486
+ delete record.arg;
487
+ entry.completion = record;
488
+ }
489
+
490
+ function Context(tryLocsList) {
491
+ // The root entry object (effectively a try statement without a catch
492
+ // or a finally block) gives us a place to store values thrown from
493
+ // locations where there is no enclosing try statement.
494
+ this.tryEntries = [{
495
+ tryLoc: "root"
496
+ }];
497
+ tryLocsList.forEach(pushTryEntry, this);
498
+ this.reset(true);
499
+ }
500
+
501
+ exports.keys = function (object) {
502
+ var keys = [];
503
+
504
+ for (var key in object) {
505
+ keys.push(key);
506
+ }
507
+
508
+ keys.reverse(); // Rather than returning an object with a next method, we keep
509
+ // things simple and return the next function itself.
510
+
511
+ return function next() {
512
+ while (keys.length) {
513
+ var key = keys.pop();
514
+
515
+ if (key in object) {
516
+ next.value = key;
517
+ next.done = false;
518
+ return next;
519
+ }
520
+ } // To avoid creating an additional object, we just hang the .value
521
+ // and .done properties off the next function object itself. This
522
+ // also ensures that the minifier will not anonymize the function.
523
+
524
+
525
+ next.done = true;
526
+ return next;
527
+ };
528
+ };
529
+
530
+ function values(iterable) {
531
+ if (iterable) {
532
+ var iteratorMethod = iterable[iteratorSymbol];
533
+
534
+ if (iteratorMethod) {
535
+ return iteratorMethod.call(iterable);
536
+ }
537
+
538
+ if (typeof iterable.next === "function") {
539
+ return iterable;
540
+ }
541
+
542
+ if (!isNaN(iterable.length)) {
543
+ var i = -1,
544
+ next = function next() {
545
+ while (++i < iterable.length) {
546
+ if (hasOwn.call(iterable, i)) {
547
+ next.value = iterable[i];
548
+ next.done = false;
549
+ return next;
550
+ }
551
+ }
552
+
553
+ next.value = undefined$1;
554
+ next.done = true;
555
+ return next;
556
+ };
557
+
558
+ return next.next = next;
559
+ }
560
+ } // Return an iterator with no values.
561
+
562
+
563
+ return {
564
+ next: doneResult
565
+ };
566
+ }
567
+
568
+ exports.values = values;
569
+
570
+ function doneResult() {
571
+ return {
572
+ value: undefined$1,
573
+ done: true
574
+ };
575
+ }
576
+
577
+ Context.prototype = {
578
+ constructor: Context,
579
+ reset: function reset(skipTempReset) {
580
+ this.prev = 0;
581
+ this.next = 0; // Resetting context._sent for legacy support of Babel's
582
+ // function.sent implementation.
583
+
584
+ this.sent = this._sent = undefined$1;
585
+ this.done = false;
586
+ this.delegate = null;
587
+ this.method = "next";
588
+ this.arg = undefined$1;
589
+ this.tryEntries.forEach(resetTryEntry);
590
+
591
+ if (!skipTempReset) {
592
+ for (var name in this) {
593
+ // Not sure about the optimal order of these conditions:
594
+ if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) {
595
+ this[name] = undefined$1;
596
+ }
597
+ }
598
+ }
599
+ },
600
+ stop: function stop() {
601
+ this.done = true;
602
+ var rootEntry = this.tryEntries[0];
603
+ var rootRecord = rootEntry.completion;
604
+
605
+ if (rootRecord.type === "throw") {
606
+ throw rootRecord.arg;
607
+ }
608
+
609
+ return this.rval;
610
+ },
611
+ dispatchException: function dispatchException(exception) {
612
+ if (this.done) {
613
+ throw exception;
614
+ }
615
+
616
+ var context = this;
617
+
618
+ function handle(loc, caught) {
619
+ record.type = "throw";
620
+ record.arg = exception;
621
+ context.next = loc;
622
+
623
+ if (caught) {
624
+ // If the dispatched exception was caught by a catch block,
625
+ // then let that catch block handle the exception normally.
626
+ context.method = "next";
627
+ context.arg = undefined$1;
628
+ }
629
+
630
+ return !!caught;
631
+ }
632
+
633
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
634
+ var entry = this.tryEntries[i];
635
+ var record = entry.completion;
636
+
637
+ if (entry.tryLoc === "root") {
638
+ // Exception thrown outside of any try block that could handle
639
+ // it, so set the completion value of the entire function to
640
+ // throw the exception.
641
+ return handle("end");
642
+ }
643
+
644
+ if (entry.tryLoc <= this.prev) {
645
+ var hasCatch = hasOwn.call(entry, "catchLoc");
646
+ var hasFinally = hasOwn.call(entry, "finallyLoc");
647
+
648
+ if (hasCatch && hasFinally) {
649
+ if (this.prev < entry.catchLoc) {
650
+ return handle(entry.catchLoc, true);
651
+ } else if (this.prev < entry.finallyLoc) {
652
+ return handle(entry.finallyLoc);
653
+ }
654
+ } else if (hasCatch) {
655
+ if (this.prev < entry.catchLoc) {
656
+ return handle(entry.catchLoc, true);
657
+ }
658
+ } else if (hasFinally) {
659
+ if (this.prev < entry.finallyLoc) {
660
+ return handle(entry.finallyLoc);
661
+ }
662
+ } else {
663
+ throw new Error("try statement without catch or finally");
664
+ }
665
+ }
666
+ }
667
+ },
668
+ abrupt: function abrupt(type, arg) {
669
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
670
+ var entry = this.tryEntries[i];
671
+
672
+ if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
673
+ var finallyEntry = entry;
674
+ break;
675
+ }
676
+ }
677
+
678
+ if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) {
679
+ // Ignore the finally entry if control is not jumping to a
680
+ // location outside the try/catch block.
681
+ finallyEntry = null;
682
+ }
683
+
684
+ var record = finallyEntry ? finallyEntry.completion : {};
685
+ record.type = type;
686
+ record.arg = arg;
687
+
688
+ if (finallyEntry) {
689
+ this.method = "next";
690
+ this.next = finallyEntry.finallyLoc;
691
+ return ContinueSentinel;
692
+ }
693
+
694
+ return this.complete(record);
695
+ },
696
+ complete: function complete(record, afterLoc) {
697
+ if (record.type === "throw") {
698
+ throw record.arg;
699
+ }
700
+
701
+ if (record.type === "break" || record.type === "continue") {
702
+ this.next = record.arg;
703
+ } else if (record.type === "return") {
704
+ this.rval = this.arg = record.arg;
705
+ this.method = "return";
706
+ this.next = "end";
707
+ } else if (record.type === "normal" && afterLoc) {
708
+ this.next = afterLoc;
709
+ }
710
+
711
+ return ContinueSentinel;
712
+ },
713
+ finish: function finish(finallyLoc) {
714
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
715
+ var entry = this.tryEntries[i];
716
+
717
+ if (entry.finallyLoc === finallyLoc) {
718
+ this.complete(entry.completion, entry.afterLoc);
719
+ resetTryEntry(entry);
720
+ return ContinueSentinel;
721
+ }
722
+ }
723
+ },
724
+ "catch": function _catch(tryLoc) {
725
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
726
+ var entry = this.tryEntries[i];
727
+
728
+ if (entry.tryLoc === tryLoc) {
729
+ var record = entry.completion;
730
+
731
+ if (record.type === "throw") {
732
+ var thrown = record.arg;
733
+ resetTryEntry(entry);
734
+ }
735
+
736
+ return thrown;
737
+ }
738
+ } // The context.catch method must only be called with a location
739
+ // argument that corresponds to a known catch block.
740
+
741
+
742
+ throw new Error("illegal catch attempt");
743
+ },
744
+ delegateYield: function delegateYield(iterable, resultName, nextLoc) {
745
+ this.delegate = {
746
+ iterator: values(iterable),
747
+ resultName: resultName,
748
+ nextLoc: nextLoc
749
+ };
750
+
751
+ if (this.method === "next") {
752
+ // Deliberately forget the last sent value so that we don't
753
+ // accidentally pass it on to the delegate.
754
+ this.arg = undefined$1;
755
+ }
756
+
757
+ return ContinueSentinel;
758
+ }
759
+ }; // Regardless of whether this script is executing as a CommonJS module
760
+ // or not, return the runtime object so that we can declare the variable
761
+ // regeneratorRuntime in the outer scope, which allows this module to be
762
+ // injected easily by `bin/regenerator --include-runtime script.js`.
763
+
764
+ return exports;
765
+ }( // If this script is executing as a CommonJS module, use module.exports
766
+ // as the regeneratorRuntime namespace. Otherwise create a new empty
767
+ // object. Either way, the resulting object will be used to initialize
768
+ // the regeneratorRuntime variable at the top of this file.
769
+ module.exports );
770
+
771
+ try {
772
+ regeneratorRuntime = runtime;
773
+ } catch (accidentalStrictMode) {
774
+ // This module should not be running in strict mode, so the above
775
+ // assignment should always work unless something is misconfigured. Just
776
+ // in case runtime.js accidentally runs in strict mode, in modern engines
777
+ // we can explicitly access globalThis. In older engines we can escape
778
+ // strict mode using a global Function call. This could conceivably fail
779
+ // if a Content Security Policy forbids using Function, but in that case
780
+ // the proper solution is to fix the accidental strict mode problem. If
781
+ // you've misconfigured your bundler to force strict mode and applied a
782
+ // CSP to forbid Function, and you're not willing to fix either of those
783
+ // problems, please detail your unique predicament in a GitHub issue.
784
+ if (typeof globalThis === "object") {
785
+ globalThis.regeneratorRuntime = runtime;
786
+ } else {
787
+ Function("r", "regeneratorRuntime = r")(runtime);
788
+ }
789
+ }
790
+ });
791
+
792
+ var getSortVariables = function getSortVariables(sort, isCategory) {
793
+
794
+ var output = undefined;
795
+
796
+ switch (sort) {
797
+ case 'price-asc':
798
+ output = 'price asc';
799
+ break;
800
+
801
+ case 'price-desc':
802
+ output = 'price desc';
803
+ break;
804
+
805
+ case 'trending-desc':
806
+ // default option
807
+ output = undefined;
808
+ break;
809
+
810
+ case 'latest-desc':
811
+ output = 'createdAt desc';
812
+ break;
813
+ }
814
+
815
+ return output;
816
+ };
817
+
818
+ var COMMERCETOOLS_COOKIE_EXPIRE = 30;
819
+ var COMMERCETOOLS_CART_COOKIE = 'commercetools_cart';
820
+
821
+ var options = {
822
+ expires: COMMERCETOOLS_COOKIE_EXPIRE,
823
+ sameSite: "none",
824
+ secure: true
825
+ };
826
+ var getCookies = function getCookies(name) {
827
+ var cookie = Cookies.get(name);
828
+ return cookie ? JSON.parse(cookie) : undefined;
829
+ };
830
+ var setCookies = function setCookies(name, value) {
831
+ return Cookies.set(name, JSON.stringify(value), options);
832
+ };
833
+ var removeCookies = function removeCookies(name) {
834
+ return Cookies.remove(name);
835
+ };
836
+
837
+ var getCartId = function getCartId() {
838
+ return getCookies(COMMERCETOOLS_CART_COOKIE);
839
+ };
840
+ var setCartId = function setCartId(id) {
841
+ return setCookies(COMMERCETOOLS_CART_COOKIE, id);
842
+ };
843
+ var removeCartCookie = function removeCartCookie() {
844
+ return removeCookies(COMMERCETOOLS_CART_COOKIE);
845
+ };
846
+
847
+ var createCart = /*#__PURE__*/function () {
848
+ var _ref = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee(fetch) {
849
+ var draft, cart;
850
+ return runtime_1.wrap(function _callee$(_context) {
851
+ while (1) {
852
+ switch (_context.prev = _context.next) {
853
+ case 0:
854
+ draft = {
855
+ currency: 'USD',
856
+ country: 'US'
857
+ };
858
+ _context.next = 3;
859
+ return fetch({
860
+ query: 'carts',
861
+ method: 'post',
862
+ body: draft
863
+ });
864
+
865
+ case 3:
866
+ cart = _context.sent;
867
+
868
+ if (!cart.body) {
869
+ removeCartCookie();
870
+ } else {
871
+ setCartId(cart.body.id);
872
+ }
873
+
874
+ return _context.abrupt("return", cart.body);
875
+
876
+ case 6:
877
+ case "end":
878
+ return _context.stop();
879
+ }
880
+ }
881
+ }, _callee);
882
+ }));
883
+
884
+ return function createCart(_x) {
885
+ return _ref.apply(this, arguments);
886
+ };
887
+ }();
888
+
889
+ var getActiveCart = /*#__PURE__*/function () {
890
+ var _ref = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee(fetch) {
891
+ var cartId, activeCart;
892
+ return runtime_1.wrap(function _callee$(_context) {
893
+ while (1) {
894
+ switch (_context.prev = _context.next) {
895
+ case 0:
896
+ cartId = getCartId();
897
+
898
+ if (!cartId) {
899
+ _context.next = 7;
900
+ break;
901
+ }
902
+
903
+ _context.next = 4;
904
+ return fetch({
905
+ query: 'carts',
906
+ method: 'get',
907
+ variables: {
908
+ id: cartId
909
+ }
910
+ });
911
+
912
+ case 4:
913
+ activeCart = _context.sent.body;
914
+ _context.next = 10;
915
+ break;
916
+
917
+ case 7:
918
+ _context.next = 9;
919
+ return createCart(fetch);
920
+
921
+ case 9:
922
+ activeCart = _context.sent;
923
+
924
+ case 10:
925
+ if (!activeCart) {
926
+ removeCartCookie();
927
+ } else {
928
+ setCartId(activeCart.id);
929
+ }
930
+
931
+ return _context.abrupt("return", activeCart);
932
+
933
+ case 12:
934
+ case "end":
935
+ return _context.stop();
936
+ }
937
+ }
938
+ }, _callee);
939
+ }));
940
+
941
+ return function getActiveCart(_x) {
942
+ return _ref.apply(this, arguments);
943
+ };
944
+ }();
945
+
946
+ var getLocalizedString = function getLocalizedString(localizedString, locale) {
947
+ return !localizedString || !locale ? undefined : locale in localizedString ? localizedString[locale] : Object.values(localizedString)[0];
948
+ };
949
+
950
+ var withoutNils = function withoutNils(xs) {
951
+ return xs.filter(function (x) {
952
+ return x != null;
953
+ });
954
+ };
955
+ var dedup = function dedup(xs) {
956
+ return [].concat(new Set(xs));
957
+ };
958
+
959
+ var currencyCode = 'USD';
960
+
961
+ var stringify = function stringify(value) {
962
+ return typeof value === 'string' ? value : JSON.stringify(value);
963
+ };
964
+
965
+ var money = function money(price) {
966
+ return price ? {
967
+ value: price.centAmount / 100,
968
+ currencyCode: price.currencyCode
969
+ } : {
970
+ value: -1.0,
971
+ currencyCode: currencyCode
972
+ };
973
+ };
974
+
975
+ var normalizeProductOption = function normalizeProductOption(option) {
976
+ return {
977
+ __typename: 'MultipleChoiceOption',
978
+ id: option.name,
979
+ displayName: option.name,
980
+ values: dedup(Array.isArray(option.value) ? option.value : [option.value]).map(function (val) {
981
+ if (option.name.match(/colou?r/gi) && /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/i.test(val)) {
982
+ return {
983
+ label: stringify(val),
984
+ hexColors: [val]
985
+ };
986
+ } else {
987
+ return {
988
+ label: stringify(val)
989
+ };
990
+ }
991
+ })
992
+ };
993
+ };
994
+
995
+ var normalizeProductImages = function normalizeProductImages(images) {
996
+ return images.map(function (image) {
997
+ return _extends({
998
+ url: image.url
999
+ }, image.label ? {
1000
+ alt: image.label
1001
+ } : {}, {
1002
+ width: image.dimensions.w,
1003
+ height: image.dimensions.h
1004
+ });
1005
+ });
1006
+ };
1007
+
1008
+ var normalizeProductVariant = function normalizeProductVariant(variant) {
1009
+ var _variant$prices$find$, _variant$prices, _variant$prices$find, _variant$prices2, _variant$prices2$, _variant$sku, _variant$attributes$m, _variant$attributes;
1010
+
1011
+ var price = money((_variant$prices$find$ = (_variant$prices = variant.prices) == null ? void 0 : (_variant$prices$find = _variant$prices.find(function (price) {
1012
+ return price.value.currencyCode === currencyCode;
1013
+ })) == null ? void 0 : _variant$prices$find.value) != null ? _variant$prices$find$ : (_variant$prices2 = variant.prices) == null ? void 0 : (_variant$prices2$ = _variant$prices2[0]) == null ? void 0 : _variant$prices2$.value).value;
1014
+ return {
1015
+ id: "" + variant.id,
1016
+ name: "" + variant.id,
1017
+ sku: (_variant$sku = variant.sku) != null ? _variant$sku : '',
1018
+ price: price,
1019
+ options: (_variant$attributes$m = (_variant$attributes = variant.attributes) == null ? void 0 : _variant$attributes.map(function (attribute) {
1020
+ return normalizeProductOption({
1021
+ name: attribute.name,
1022
+ value: attribute.value.key
1023
+ });
1024
+ })) != null ? _variant$attributes$m : [],
1025
+ requiresShipping: false,
1026
+ listPrice: price
1027
+ };
1028
+ };
1029
+
1030
+ var normalizeProduct = function normalizeProduct(product, locale) {
1031
+ var _getLocalizedString, _getLocalizedString2, _product$masterVarian, _product$masterVarian2, _product$masterVarian3, _product$masterVarian4, _product$masterVarian5;
1032
+
1033
+ return {
1034
+ id: product.id,
1035
+ name: (_getLocalizedString = getLocalizedString(product.name, locale)) != null ? _getLocalizedString : "",
1036
+ slug: getLocalizedString(product.slug, locale),
1037
+ path: "/" + getLocalizedString(product.slug, locale),
1038
+ description: (_getLocalizedString2 = getLocalizedString(product.description, locale)) != null ? _getLocalizedString2 : '',
1039
+ price: money((_product$masterVarian = (_product$masterVarian2 = product.masterVariant.prices) == null ? void 0 : (_product$masterVarian3 = _product$masterVarian2.find(function (price) {
1040
+ return price.value.currencyCode === currencyCode;
1041
+ })) == null ? void 0 : _product$masterVarian3.value) != null ? _product$masterVarian : (_product$masterVarian4 = product.masterVariant.prices) == null ? void 0 : (_product$masterVarian5 = _product$masterVarian4[0]) == null ? void 0 : _product$masterVarian5.value),
1042
+ images: normalizeProductImages(withoutNils([].concat(product.masterVariant.images ? product.masterVariant.images : [], product.variants.flatMap(function (variant) {
1043
+ return variant.images;
1044
+ })))),
1045
+ variants: [product.masterVariant].concat(product.variants).map(normalizeProductVariant),
1046
+ options: withoutNils([].concat(product.masterVariant.attributes ? product.masterVariant.attributes : [], product.variants.flatMap(function (variant) {
1047
+ return variant.attributes;
1048
+ }))).reduce(function (groupedAttributes, attribute) {
1049
+ var groupedAttribute = groupedAttributes.find(function (gAttr) {
1050
+ return gAttr.name === attribute.name;
1051
+ });
1052
+
1053
+ if (groupedAttribute) {
1054
+ groupedAttribute.value.push(stringify(attribute.value.key));
1055
+ } else {
1056
+ groupedAttributes.push({
1057
+ name: attribute.name,
1058
+ value: [stringify(attribute.value.key)]
1059
+ });
1060
+ }
1061
+
1062
+ return groupedAttributes;
1063
+ }, []).map(normalizeProductOption)
1064
+ };
1065
+ };
1066
+
1067
+ var normalizeLineItem = function normalizeLineItem(lineItem, locale) {
1068
+ var _getLocalizedString3, _lineItem$variant$att, _lineItem$variant$att2;
1069
+
1070
+ return {
1071
+ id: lineItem.id,
1072
+ variantId: "" + lineItem.variant.id,
1073
+ productId: lineItem.productId,
1074
+ name: (_getLocalizedString3 = getLocalizedString(lineItem.name, locale)) != null ? _getLocalizedString3 : "",
1075
+ path: '',
1076
+ quantity: lineItem.quantity,
1077
+ discounts: [],
1078
+ variant: normalizeProductVariant(lineItem.variant),
1079
+ options: (_lineItem$variant$att = (_lineItem$variant$att2 = lineItem.variant.attributes) == null ? void 0 : _lineItem$variant$att2.map(function (attribute) {
1080
+ return {
1081
+ id: attribute.name,
1082
+ name: attribute.name,
1083
+ value: attribute.value.key
1084
+ };
1085
+ })) != null ? _lineItem$variant$att : []
1086
+ };
1087
+ };
1088
+
1089
+ var normalizeCart = function normalizeCart(cart, locale) {
1090
+ return {
1091
+ id: cart.id,
1092
+ customerId: cart.customerId,
1093
+ email: cart.customerEmail,
1094
+ createdAt: cart.createdAt,
1095
+ currency: {
1096
+ code: currencyCode
1097
+ },
1098
+ taxesIncluded: cart.taxMode !== 'Disabled',
1099
+ lineItems: cart.lineItems.map(function (item) {
1100
+ return normalizeLineItem(item, locale);
1101
+ }),
1102
+ lineItemsSubtotalPrice: 0,
1103
+ subtotalPrice: money(cart.totalPrice).value,
1104
+ totalPrice: money(cart.totalPrice).value,
1105
+ discounts: []
1106
+ };
1107
+ };
1108
+ var normalizeCategory = function normalizeCategory(category, locale) {
1109
+ var _getLocalizedString4, _getLocalizedString5;
1110
+
1111
+ return {
1112
+ id: category.id,
1113
+ name: (_getLocalizedString4 = getLocalizedString(category.name, locale)) != null ? _getLocalizedString4 : "",
1114
+ slug: (_getLocalizedString5 = getLocalizedString(category.slug, locale)) != null ? _getLocalizedString5 : "",
1115
+ path: "/" + getLocalizedString(category.slug, locale)
1116
+ };
1117
+ };
1118
+
1119
+ var handler = {
1120
+ fetchOptions: {
1121
+ method: "get",
1122
+ query: "productProjections"
1123
+ },
1124
+ fetcher: function fetcher(_ref) {
1125
+ return _asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee() {
1126
+ var _search;
1127
+
1128
+ var input, options, fetch, provider, search, categoryId, sort, count, response;
1129
+ return runtime_1.wrap(function _callee$(_context) {
1130
+ while (1) {
1131
+ switch (_context.prev = _context.next) {
1132
+ case 0:
1133
+ input = _ref.input, options = _ref.options, fetch = _ref.fetch, provider = _ref.provider;
1134
+ search = input.search, categoryId = input.categoryId, sort = input.sort, count = input.count;
1135
+ _context.next = 4;
1136
+ return fetch(_extends({}, options, {
1137
+ variables: _extends({
1138
+ expand: ['masterData.current'],
1139
+ sort: getSortVariables(sort),
1140
+ limit: count
1141
+ }, search ? {
1142
+ search: (_search = {}, _search["text." + (provider == null ? void 0 : provider.locale)] = search, _search)
1143
+ } : {}, categoryId ? {
1144
+ filters: "categories.id: subtree(\"" + categoryId + "\")"
1145
+ } : {})
1146
+ }));
1147
+
1148
+ case 4:
1149
+ response = _context.sent;
1150
+ return _context.abrupt("return", {
1151
+ products: response.body.results.map(function (product) {
1152
+ return normalizeProduct(product, provider.locale);
1153
+ }),
1154
+ found: response.body.count > 0
1155
+ });
1156
+
1157
+ case 6:
1158
+ case "end":
1159
+ return _context.stop();
1160
+ }
1161
+ }
1162
+ }, _callee);
1163
+ }))();
1164
+ },
1165
+ useHook: function useHook(_ref2) {
1166
+ var useData = _ref2.useData;
1167
+ return function (input) {
1168
+ if (input === void 0) {
1169
+ input = {};
1170
+ }
1171
+
1172
+ return useData({
1173
+ input: [['search', input.search], ['categoryId', input.categoryId], ['brandId', input.brandId], ['sort', input.sort], ['locale', input.locale], ['count', input.count]],
1174
+ swrOptions: _extends({
1175
+ revalidateOnFocus: false
1176
+ }, input.swrOptions)
1177
+ });
1178
+ };
1179
+ }
1180
+ };
1181
+
1182
+ var handler$1 = {
1183
+ fetchOptions: {
1184
+ query: "productProjections",
1185
+ method: "get"
1186
+ },
1187
+ fetcher: function fetcher(_ref) {
1188
+ return _asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee() {
1189
+ var input, options, fetch, provider, id, product;
1190
+ return runtime_1.wrap(function _callee$(_context) {
1191
+ while (1) {
1192
+ switch (_context.prev = _context.next) {
1193
+ case 0:
1194
+ input = _ref.input, options = _ref.options, fetch = _ref.fetch, provider = _ref.provider;
1195
+ id = input.id;
1196
+
1197
+ if (id) {
1198
+ _context.next = 4;
1199
+ break;
1200
+ }
1201
+
1202
+ return _context.abrupt("return", null);
1203
+
1204
+ case 4:
1205
+ _context.next = 6;
1206
+ return fetch(_extends({}, options, {
1207
+ variables: {
1208
+ id: id
1209
+ }
1210
+ }));
1211
+
1212
+ case 6:
1213
+ product = _context.sent;
1214
+ return _context.abrupt("return", product.body ? normalizeProduct(product.body, provider.locale) : null);
1215
+
1216
+ case 8:
1217
+ case "end":
1218
+ return _context.stop();
1219
+ }
1220
+ }
1221
+ }, _callee);
1222
+ }))();
1223
+ },
1224
+ useHook: function useHook(_ref2) {
1225
+ var useData = _ref2.useData;
1226
+ return function (input) {
1227
+ if (input === void 0) {
1228
+ input = {};
1229
+ }
1230
+
1231
+ return useData({
1232
+ input: [['id', input.id]],
1233
+ swrOptions: _extends({
1234
+ revalidateOnFocus: false
1235
+ }, input.swrOptions)
1236
+ });
1237
+ };
1238
+ }
1239
+ };
1240
+
1241
+ var handler$2 = {
1242
+ fetchOptions: {
1243
+ query: "cart",
1244
+ method: "get"
1245
+ },
1246
+ fetcher: function fetcher(_ref) {
1247
+ return _asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee() {
1248
+ var fetch, provider, activeCart;
1249
+ return runtime_1.wrap(function _callee$(_context) {
1250
+ while (1) {
1251
+ switch (_context.prev = _context.next) {
1252
+ case 0:
1253
+ fetch = _ref.fetch, provider = _ref.provider;
1254
+ _context.next = 3;
1255
+ return getActiveCart(fetch);
1256
+
1257
+ case 3:
1258
+ activeCart = _context.sent;
1259
+ return _context.abrupt("return", activeCart ? normalizeCart(activeCart, provider.locale) : null);
1260
+
1261
+ case 5:
1262
+ case "end":
1263
+ return _context.stop();
1264
+ }
1265
+ }
1266
+ }, _callee);
1267
+ }))();
1268
+ },
1269
+ useHook: function useHook(_ref2) {
1270
+ var useData = _ref2.useData;
1271
+ return function (input) {
1272
+ var response = useData({
1273
+ swrOptions: _extends({
1274
+ revalidateOnFocus: false
1275
+ }, input == null ? void 0 : input.swrOptions)
1276
+ });
1277
+ return useMemo(function () {
1278
+ return Object.create(response, {
1279
+ isEmpty: {
1280
+ get: function get() {
1281
+ var _response$data$lineIt, _response$data;
1282
+
1283
+ return ((_response$data$lineIt = (_response$data = response.data) == null ? void 0 : _response$data.lineItems.length) != null ? _response$data$lineIt : 0) <= 0;
1284
+ },
1285
+ enumerable: true
1286
+ }
1287
+ });
1288
+ }, [response]);
1289
+ };
1290
+ }
1291
+ };
1292
+
1293
+ var handler$3 = {
1294
+ fetchOptions: {
1295
+ query: "cart",
1296
+ method: "post"
1297
+ },
1298
+ fetcher: function fetcher(_ref) {
1299
+ return _asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee() {
1300
+ var _item$quantity;
1301
+
1302
+ var item, fetch, provider, activeCart, lineItem, updatedCart;
1303
+ return runtime_1.wrap(function _callee$(_context) {
1304
+ while (1) {
1305
+ switch (_context.prev = _context.next) {
1306
+ case 0:
1307
+ item = _ref.input, fetch = _ref.fetch, provider = _ref.provider;
1308
+ _context.next = 3;
1309
+ return getActiveCart(fetch);
1310
+
1311
+ case 3:
1312
+ activeCart = _context.sent;
1313
+
1314
+ if (!(item.quantity && (!Number.isInteger(item.quantity) || item.quantity < 1) || !activeCart)) {
1315
+ _context.next = 6;
1316
+ break;
1317
+ }
1318
+
1319
+ return _context.abrupt("return", undefined);
1320
+
1321
+ case 6:
1322
+ lineItem = {
1323
+ version: activeCart.version,
1324
+ actions: [{
1325
+ action: 'addLineItem',
1326
+ variantId: +item.variantId,
1327
+ productId: item.productId,
1328
+ quantity: (_item$quantity = item.quantity) != null ? _item$quantity : 1
1329
+ }]
1330
+ };
1331
+ _context.next = 9;
1332
+ return fetch({
1333
+ query: 'carts',
1334
+ method: 'post',
1335
+ variables: {
1336
+ id: activeCart.id
1337
+ },
1338
+ body: lineItem
1339
+ });
1340
+
1341
+ case 9:
1342
+ updatedCart = _context.sent;
1343
+
1344
+ if (updatedCart.body) {
1345
+ setCartId(updatedCart.body.id);
1346
+ } else {
1347
+ removeCartCookie();
1348
+ }
1349
+
1350
+ return _context.abrupt("return", updatedCart.body ? normalizeCart(updatedCart.body, provider.locale) : undefined);
1351
+
1352
+ case 12:
1353
+ case "end":
1354
+ return _context.stop();
1355
+ }
1356
+ }
1357
+ }, _callee);
1358
+ }))();
1359
+ },
1360
+ useHook: function useHook(_ref2) {
1361
+ var fetch = _ref2.fetch;
1362
+ return function () {
1363
+ var _useCart = useCart(),
1364
+ mutate = _useCart.mutate;
1365
+
1366
+ return useCallback( /*#__PURE__*/function () {
1367
+ var _addItem = _asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee2(input) {
1368
+ var data;
1369
+ return runtime_1.wrap(function _callee2$(_context2) {
1370
+ while (1) {
1371
+ switch (_context2.prev = _context2.next) {
1372
+ case 0:
1373
+ _context2.next = 2;
1374
+ return fetch({
1375
+ input: input
1376
+ });
1377
+
1378
+ case 2:
1379
+ data = _context2.sent;
1380
+ _context2.next = 5;
1381
+ return mutate(data, false);
1382
+
1383
+ case 5:
1384
+ return _context2.abrupt("return", data);
1385
+
1386
+ case 6:
1387
+ case "end":
1388
+ return _context2.stop();
1389
+ }
1390
+ }
1391
+ }, _callee2);
1392
+ }));
1393
+
1394
+ function addItem(_x) {
1395
+ return _addItem.apply(this, arguments);
1396
+ }
1397
+
1398
+ return addItem;
1399
+ }(), [fetch, mutate]);
1400
+ };
1401
+ }
1402
+ };
1403
+
1404
+ var handler$4 = {
1405
+ fetchOptions: {
1406
+ query: "categories",
1407
+ method: "get"
1408
+ },
1409
+ fetcher: function fetcher(_ref) {
1410
+ return _asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee() {
1411
+ var input, options, fetch, provider, categoryId, categories, category;
1412
+ return runtime_1.wrap(function _callee$(_context) {
1413
+ while (1) {
1414
+ switch (_context.prev = _context.next) {
1415
+ case 0:
1416
+ input = _ref.input, options = _ref.options, fetch = _ref.fetch, provider = _ref.provider;
1417
+ categoryId = input.categoryId;
1418
+
1419
+ if (categoryId) {
1420
+ _context.next = 9;
1421
+ break;
1422
+ }
1423
+
1424
+ _context.next = 5;
1425
+ return fetch(_extends({}, options));
1426
+
1427
+ case 5:
1428
+ categories = _context.sent;
1429
+ return _context.abrupt("return", categories.body ? categories.body.results.map(function (category) {
1430
+ return normalizeCategory(category, provider.locale);
1431
+ }) : []);
1432
+
1433
+ case 9:
1434
+ _context.next = 11;
1435
+ return fetch(_extends({}, options, {
1436
+ variables: _extends({}, categoryId ? {
1437
+ id: categoryId
1438
+ } : {})
1439
+ }));
1440
+
1441
+ case 11:
1442
+ category = _context.sent;
1443
+ return _context.abrupt("return", category.body ? [normalizeCategory(category.body, provider.locale)] : []);
1444
+
1445
+ case 13:
1446
+ case "end":
1447
+ return _context.stop();
1448
+ }
1449
+ }
1450
+ }, _callee);
1451
+ }))();
1452
+ },
1453
+ useHook: function useHook(_ref2) {
1454
+ var useData = _ref2.useData;
1455
+ return function (input) {
1456
+ var response = useData({
1457
+ input: [["categoryId", input == null ? void 0 : input.categoryId]],
1458
+ swrOptions: _extends({
1459
+ revalidateOnFocus: false
1460
+ }, input == null ? void 0 : input.swrOptions)
1461
+ });
1462
+ return useMemo(function () {
1463
+ return Object.create(response, {
1464
+ isEmpty: {
1465
+ get: function get() {
1466
+ var _response$data$length, _response$data;
1467
+
1468
+ return ((_response$data$length = (_response$data = response.data) == null ? void 0 : _response$data.length) != null ? _response$data$length : 0) <= 0;
1469
+ },
1470
+ enumerable: true
1471
+ }
1472
+ });
1473
+ }, [response]);
1474
+ };
1475
+ }
1476
+ };
1477
+
1478
+ var handler$5 = {
1479
+ fetchOptions: {
1480
+ query: ""
1481
+ },
1482
+ fetcher: function fetcher(_ref) {
1483
+ return _asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee() {
1484
+ return runtime_1.wrap(function _callee$(_context) {
1485
+ while (1) {
1486
+ switch (_context.prev = _context.next) {
1487
+ case 0:
1488
+ return _context.abrupt("return", null);
1489
+
1490
+ case 2:
1491
+ case "end":
1492
+ return _context.stop();
1493
+ }
1494
+ }
1495
+ }, _callee);
1496
+ }))();
1497
+ },
1498
+ useHook: function useHook(_ref2) {
1499
+ var useData = _ref2.useData;
1500
+ return function (input) {
1501
+ var response = useData({
1502
+ swrOptions: _extends({
1503
+ revalidateOnFocus: false
1504
+ }, input == null ? void 0 : input.swrOptions)
1505
+ });
1506
+ return useMemo(function () {
1507
+ return Object.create(response, {
1508
+ isEmpty: {
1509
+ get: function get() {
1510
+ var _response$data$length, _response$data;
1511
+
1512
+ return ((_response$data$length = (_response$data = response.data) == null ? void 0 : _response$data.length) != null ? _response$data$length : 0) <= 0;
1513
+ },
1514
+ enumerable: true
1515
+ }
1516
+ });
1517
+ }, [response]);
1518
+ };
1519
+ }
1520
+ };
1521
+
1522
+ var initCommercetoolsSDKClient = function initCommercetoolsSDKClient(creds) {
1523
+ var scopes = ["manage_project:" + creds.projectKey]; // Configure authMiddlewareOptions
1524
+
1525
+ var authMiddlewareOptions = {
1526
+ host: "https://auth." + creds.region + ".commercetools.com",
1527
+ projectKey: creds.clientSecret,
1528
+ credentials: {
1529
+ clientId: creds.clientId,
1530
+ clientSecret: creds.clientSecret
1531
+ },
1532
+ scopes: scopes,
1533
+ fetch: fetch
1534
+ }; // Configure httpMiddlewareOptions
1535
+
1536
+ var httpMiddlewareOptions = {
1537
+ host: "https://api." + creds.region + ".commercetools.com",
1538
+ fetch: fetch
1539
+ }; // Export the ClientBuilder
1540
+
1541
+ return new ClientBuilder().withProjectKey(creds.projectKey).withClientCredentialsFlow(authMiddlewareOptions).withHttpMiddleware(httpMiddlewareOptions).build();
1542
+ };
1543
+
1544
+ var getFetcher = function getFetcher(creds) {
1545
+ var client = initCommercetoolsSDKClient(creds);
1546
+ var apiRoot = createApiBuilderFromCtpClient(client).withProjectKey({
1547
+ projectKey: creds.projectKey
1548
+ });
1549
+ return /*#__PURE__*/function () {
1550
+ var _ref2 = _asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee(_ref) {
1551
+ var method, variables, query, body, queryBuilder;
1552
+ return runtime_1.wrap(function _callee$(_context) {
1553
+ while (1) {
1554
+ switch (_context.prev = _context.next) {
1555
+ case 0:
1556
+ method = _ref.method, variables = _ref.variables, query = _ref.query, body = _ref.body;
1557
+ queryBuilder = apiRoot;
1558
+
1559
+ if (query) {
1560
+ queryBuilder = queryBuilder[query]();
1561
+ }
1562
+
1563
+ if (variables != null && variables.id) {
1564
+ queryBuilder = queryBuilder.withId({
1565
+ ID: variables.id
1566
+ });
1567
+ }
1568
+
1569
+ if (variables != null && variables.search) {
1570
+ queryBuilder = queryBuilder.search();
1571
+ }
1572
+
1573
+ _context.next = 7;
1574
+ return queryBuilder[method]({
1575
+ body: body,
1576
+ queryArgs: _extends({
1577
+ expand: variables == null ? void 0 : variables.expand,
1578
+ limit: variables == null ? void 0 : variables.limit
1579
+ }, variables != null && variables.sort ? {
1580
+ sort: variables.sort
1581
+ } : {}, variables != null && variables.search ? variables.search : {}, variables != null && variables.filters ? {
1582
+ filter: variables.filters
1583
+ } : {}, variables != null && variables.where ? {
1584
+ where: variables.where
1585
+ } : {})
1586
+ }).execute();
1587
+
1588
+ case 7:
1589
+ return _context.abrupt("return", _context.sent);
1590
+
1591
+ case 8:
1592
+ case "end":
1593
+ return _context.stop();
1594
+ }
1595
+ }
1596
+ }, _callee);
1597
+ }));
1598
+
1599
+ return function (_x) {
1600
+ return _ref2.apply(this, arguments);
1601
+ };
1602
+ }();
1603
+ };
1604
+
1605
+ var getCommercetoolsProvider = function getCommercetoolsProvider(creds, locale) {
1606
+ return {
1607
+ locale: locale,
1608
+ cartCookie: COMMERCETOOLS_CART_COOKIE,
1609
+ cart: {
1610
+ useCart: handler$2,
1611
+ useAddItem: handler$3
1612
+ },
1613
+ fetcher: getFetcher(creds),
1614
+ products: {
1615
+ useSearch: handler,
1616
+ useProduct: handler$1
1617
+ },
1618
+ site: {
1619
+ useCategories: handler$4,
1620
+ useBrands: handler$5
1621
+ }
1622
+ };
1623
+ };
1624
+
1625
+ var useCommerce = function useCommerce() {
1626
+ return useCommerce$1();
1627
+ };
1628
+ var getCommerceProvider = function getCommerceProvider(creds, locale) {
1629
+ return getCommerceProvider$1(getCommercetoolsProvider(creds, locale));
1630
+ };
1631
+
1632
+ var commerceProviderMeta = {
1633
+ name: "plasmic-commerce-commercetools-provider",
1634
+ displayName: "Commercetools Provider",
1635
+ props: {
1636
+ projectKey: {
1637
+ type: "string",
1638
+ defaultValue: "plasmic-demo"
1639
+ },
1640
+ clientId: {
1641
+ type: "string",
1642
+ defaultValue: "B4hmK61xvz5LvdSDtsFmcflM"
1643
+ },
1644
+ clientSecret: {
1645
+ type: "string",
1646
+ defaultValue: "KhzjcjSu1Oul4aomSmOsLZOCZKbvfHqx"
1647
+ },
1648
+ region: {
1649
+ type: "choice",
1650
+ options: ["us-central1.gcp", "us-east-2.aws", "europe-west1.gcp", "eu-central-1.aws", "australia-southeast1.gcp"],
1651
+ defaultValue: "us-central1.gcp"
1652
+ }
1653
+ },
1654
+ importPath: "@plasmicpkgs/commercetools",
1655
+ importName: "CommerceProviderComponent"
1656
+ };
1657
+ function CommerceProviderComponent(props) {
1658
+ var children = props.children,
1659
+ projectKey = props.projectKey,
1660
+ clientId = props.clientId,
1661
+ clientSecret = props.clientSecret,
1662
+ region = props.region;
1663
+ var creds = {
1664
+ projectKey: projectKey,
1665
+ clientId: clientId,
1666
+ clientSecret: clientSecret,
1667
+ region: region
1668
+ };
1669
+
1670
+ var _usePlasmicQueryData = usePlasmicQueryData(JSON.stringify({
1671
+ creds: creds
1672
+ }) + "locale", /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee() {
1673
+ var fetcher, project;
1674
+ return runtime_1.wrap(function _callee$(_context) {
1675
+ while (1) {
1676
+ switch (_context.prev = _context.next) {
1677
+ case 0:
1678
+ fetcher = getFetcher(creds);
1679
+ _context.next = 3;
1680
+ return fetcher({
1681
+ method: "get"
1682
+ });
1683
+
1684
+ case 3:
1685
+ project = _context.sent;
1686
+ return _context.abrupt("return", project.body ? project.body.languages[0] : undefined);
1687
+
1688
+ case 5:
1689
+ case "end":
1690
+ return _context.stop();
1691
+ }
1692
+ }
1693
+ }, _callee);
1694
+ }))),
1695
+ locale = _usePlasmicQueryData.data,
1696
+ error = _usePlasmicQueryData.error,
1697
+ isLoading = _usePlasmicQueryData.isLoading;
1698
+
1699
+ var CommerceProvider = getCommerceProvider(creds, locale != null ? locale : "");
1700
+
1701
+ if (isLoading) {
1702
+ return null;
1703
+ } else if (error || !locale) {
1704
+ throw new Error(error ? error.message : "Project language not found");
1705
+ }
1706
+
1707
+ return React.createElement(CommerceProvider, null, children);
1708
+ }
1709
+ function registerCommerceProvider(loader, customCommerceProviderMeta) {
1710
+ var doRegisterComponent = function doRegisterComponent() {
1711
+ return loader ? loader.registerGlobalContext.apply(loader, arguments) : registerGlobalContext.apply(void 0, arguments);
1712
+ };
1713
+
1714
+ doRegisterComponent(CommerceProviderComponent, customCommerceProviderMeta != null ? customCommerceProviderMeta : commerceProviderMeta);
1715
+ }
1716
+
1717
+ function registerAll(loader) {
1718
+ registerCommerceProvider(loader);
1719
+ }
1720
+
1721
+ export { CommerceProviderComponent, commerceProviderMeta, getCommerceProvider, registerAll, registerCommerceProvider, useCommerce };
1722
+ //# sourceMappingURL=commerce-commercetools.esm.js.map