@merchi/cart 1.4.33 → 1.4.35

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.
@@ -33,6 +33,7 @@ import { makeProduct } from './utilities/product';
33
33
  import { getSavedCheckoutCustomer, saveCheckoutAddress } from './utilities/local_storage';
34
34
  import { makeUser } from './utilities/user';
35
35
  import { persistTestCheckoutFlag, readTestCheckoutFlag } from './utilities/test_checkout';
36
+ import { reportAddCartItemFailure } from './utilities/reportFailure';
36
37
  import { appendJobSourceToFormData, captureAndReadJobSource, cartNeedsSourceUpdate, jobSourceFieldsForApi } from './utilities/job_source';
37
38
  import { jsx as _jsx } from "react/jsx-runtime";
38
39
  var CartContext = /*#__PURE__*/createContext({
@@ -1002,7 +1003,7 @@ var CartProvider = function CartProvider(_ref) {
1002
1003
  case 5:
1003
1004
  _context12.p = 5;
1004
1005
  _t8 = _context12.v;
1005
- onError(_t8);
1006
+ reportAddCartItemFailure(_t8, onError);
1006
1007
  case 6:
1007
1008
  _context12.p = 6;
1008
1009
  setFetchingCart(false);
@@ -2,6 +2,7 @@ function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present,
2
2
  function _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); } r ? i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2)); }, _regeneratorDefine2(e, r, n, t); }
3
3
  function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }
4
4
  function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; }
5
+ import { CART_FAILURE_SOURCES, reportCartFailure } from './reportFailure';
5
6
  var urlToFile = /*#__PURE__*/function () {
6
7
  var _ref = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(url, filename, type) {
7
8
  var res, buf;
@@ -44,17 +45,23 @@ var urlToFilePdf = /*#__PURE__*/function () {
44
45
  return _ref2.apply(this, arguments);
45
46
  };
46
47
  }();
48
+ function publicInvoicePdfFilename(invoice) {
49
+ var _invoice$domain;
50
+ var id = invoice === null || invoice === void 0 ? void 0 : invoice.id;
51
+ var emailDomain = invoice === null || invoice === void 0 || (_invoice$domain = invoice.domain) === null || _invoice$domain === void 0 ? void 0 : _invoice$domain.emailDomain;
52
+ return emailDomain ? "".concat(emailDomain, "-invoice-").concat(id, ".pdf") : "invoice-".concat(id, ".pdf");
53
+ }
47
54
  export function generatePublicInvoicePdf(_x6, _x7, _x8) {
48
55
  return _generatePublicInvoicePdf.apply(this, arguments);
49
56
  }
50
57
  function _generatePublicInvoicePdf() {
51
58
  _generatePublicInvoicePdf = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(apiUrl, invoice, receipt) {
52
- var id, domain, queryString, fetchOptions, uri, response, r, pdf, url, doc, anchor, _t;
59
+ var id, filename, queryString, fetchOptions, uri, response, r, pdf, url, doc, anchor, _t;
53
60
  return _regenerator().w(function (_context3) {
54
61
  while (1) switch (_context3.p = _context3.n) {
55
62
  case 0:
56
63
  id = invoice.id;
57
- domain = invoice.domain.emailDomain;
64
+ filename = publicInvoicePdfFilename(invoice);
58
65
  queryString = new URLSearchParams({
59
66
  invoice_token: invoice.invoiceToken
60
67
  }).toString();
@@ -79,7 +86,7 @@ function _generatePublicInvoicePdf() {
79
86
  case 4:
80
87
  r = _context3.v;
81
88
  _context3.n = 5;
82
- return urlToFilePdf("data:application/pdf;base64,".concat(r.pdf), "".concat(domain, "-invoice-").concat(id, ".pdf"));
89
+ return urlToFilePdf("data:application/pdf;base64,".concat(r.pdf), filename);
83
90
  case 5:
84
91
  pdf = _context3.v;
85
92
  url = URL.createObjectURL(pdf);
@@ -102,6 +109,7 @@ function _generatePublicInvoicePdf() {
102
109
  case 6:
103
110
  _context3.p = 6;
104
111
  _t = _context3.v;
112
+ reportCartFailure(_t, CART_FAILURE_SOURCES.invoicePdf);
105
113
  throw _t;
106
114
  case 7:
107
115
  return _context3.a(2);
@@ -0,0 +1,150 @@
1
+ function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = !1, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = !0, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), !0), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, "Generator"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); }
2
+ function _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); } r ? i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2)); }, _regeneratorDefine2(e, r, n, t); }
3
+ function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }
4
+ function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; }
5
+ import { generatePublicInvoicePdf } from './invoice';
6
+ function pdfResponse() {
7
+ return {
8
+ ok: true,
9
+ json: function () {
10
+ var _json = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
11
+ return _regenerator().w(function (_context) {
12
+ while (1) switch (_context.n) {
13
+ case 0:
14
+ return _context.a(2, {
15
+ pdf: 'JVBERi0x'
16
+ });
17
+ }
18
+ }, _callee);
19
+ }));
20
+ function json() {
21
+ return _json.apply(this, arguments);
22
+ }
23
+ return json;
24
+ }()
25
+ };
26
+ }
27
+ function dataUrlResponse() {
28
+ return {
29
+ ok: true,
30
+ arrayBuffer: function () {
31
+ var _arrayBuffer = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2() {
32
+ return _regenerator().w(function (_context2) {
33
+ while (1) switch (_context2.n) {
34
+ case 0:
35
+ return _context2.a(2, new Uint8Array([1, 2, 3]).buffer);
36
+ }
37
+ }, _callee2);
38
+ }));
39
+ function arrayBuffer() {
40
+ return _arrayBuffer.apply(this, arguments);
41
+ }
42
+ return arrayBuffer;
43
+ }()
44
+ };
45
+ }
46
+ describe('generatePublicInvoicePdf filename', function () {
47
+ var clicks = [];
48
+ beforeEach(function () {
49
+ clicks.length = 0;
50
+ if (typeof URL.createObjectURL !== 'function') {
51
+ URL.createObjectURL = function () {
52
+ return 'blob:invoice';
53
+ };
54
+ }
55
+ jest.spyOn(URL, 'createObjectURL').mockReturnValue('blob:invoice');
56
+ jest.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function () {
57
+ clicks.push(this.download);
58
+ });
59
+ global.fetch = jest.fn(/*#__PURE__*/function () {
60
+ var _ref = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(input) {
61
+ var url;
62
+ return _regenerator().w(function (_context3) {
63
+ while (1) switch (_context3.n) {
64
+ case 0:
65
+ url = String(input);
66
+ if (!url.startsWith('data:')) {
67
+ _context3.n = 1;
68
+ break;
69
+ }
70
+ return _context3.a(2, dataUrlResponse());
71
+ case 1:
72
+ return _context3.a(2, pdfResponse());
73
+ }
74
+ }, _callee3);
75
+ }));
76
+ return function (_x) {
77
+ return _ref.apply(this, arguments);
78
+ };
79
+ }());
80
+ });
81
+ afterEach(function () {
82
+ jest.restoreAllMocks();
83
+ });
84
+ it('downloads when domain is missing, using a fallback filename', /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4() {
85
+ var result;
86
+ return _regenerator().w(function (_context4) {
87
+ while (1) switch (_context4.n) {
88
+ case 0:
89
+ _context4.n = 1;
90
+ return generatePublicInvoicePdf('https://api.example/', {
91
+ id: 42,
92
+ invoiceToken: 'token',
93
+ domain: null
94
+ });
95
+ case 1:
96
+ result = _context4.v;
97
+ expect(result).toEqual({
98
+ success: true
99
+ });
100
+ expect(clicks).toEqual(['invoice-42.pdf']);
101
+ case 2:
102
+ return _context4.a(2);
103
+ }
104
+ }, _callee4);
105
+ })));
106
+ it('uses the fallback filename when domain or emailDomain is absent', /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5() {
107
+ return _regenerator().w(function (_context5) {
108
+ while (1) switch (_context5.n) {
109
+ case 0:
110
+ _context5.n = 1;
111
+ return generatePublicInvoicePdf('https://api.example/', {
112
+ id: 3,
113
+ invoiceToken: 'token'
114
+ });
115
+ case 1:
116
+ _context5.n = 2;
117
+ return generatePublicInvoicePdf('https://api.example/', {
118
+ id: 4,
119
+ invoiceToken: 'token',
120
+ domain: {
121
+ emailDomain: ''
122
+ }
123
+ });
124
+ case 2:
125
+ expect(clicks).toEqual(['invoice-3.pdf', 'invoice-4.pdf']);
126
+ case 3:
127
+ return _context5.a(2);
128
+ }
129
+ }, _callee5);
130
+ })));
131
+ it('keeps the email domain in the filename when it is present', /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee6() {
132
+ return _regenerator().w(function (_context6) {
133
+ while (1) switch (_context6.n) {
134
+ case 0:
135
+ _context6.n = 1;
136
+ return generatePublicInvoicePdf('https://api.example/', {
137
+ id: 7,
138
+ invoiceToken: 'token',
139
+ domain: {
140
+ emailDomain: 'shop.example'
141
+ }
142
+ });
143
+ case 1:
144
+ expect(clicks).toEqual(['shop.example-invoice-7.pdf']);
145
+ case 2:
146
+ return _context6.a(2);
147
+ }
148
+ }, _callee6);
149
+ })));
150
+ });
@@ -0,0 +1,193 @@
1
+ function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = !1, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = !0, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), !0), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, "Generator"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); }
2
+ function _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); } r ? i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2)); }, _regeneratorDefine2(e, r, n, t); }
3
+ function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }
4
+ function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; }
5
+ import { configureFrontendErrors } from '@merchi/error-catch';
6
+ import { generatePublicInvoicePdf } from './invoice';
7
+ function apiError(statusCode, message) {
8
+ var error = new Error(message);
9
+ error.name = 'ApiError';
10
+ return Object.assign(error, {
11
+ statusCode: statusCode,
12
+ errorCode: 3,
13
+ errorMessage: message
14
+ });
15
+ }
16
+ describe('generatePublicInvoicePdf error reporting', function () {
17
+ var events = [];
18
+ beforeEach(function () {
19
+ events.length = 0;
20
+ configureFrontendErrors({
21
+ endpoint: 'https://api.merchi.co/v6/frontend-errors',
22
+ application: 'merchi-storefront-1',
23
+ enabled: true,
24
+ dedupeWindowMs: 0,
25
+ transport: function transport(_endpoint, event) {
26
+ events.push(event);
27
+ }
28
+ });
29
+ global.fetch = jest.fn(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
30
+ return _regenerator().w(function (_context) {
31
+ while (1) switch (_context.n) {
32
+ case 0:
33
+ throw new TypeError('network down');
34
+ case 1:
35
+ return _context.a(2);
36
+ }
37
+ }, _callee);
38
+ })));
39
+ });
40
+ it('reports an unexpected failure and still rejects with the original error', /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2() {
41
+ var _events$;
42
+ return _regenerator().w(function (_context2) {
43
+ while (1) switch (_context2.n) {
44
+ case 0:
45
+ _context2.n = 1;
46
+ return expect(generatePublicInvoicePdf('https://api.example/', {
47
+ id: 42,
48
+ invoiceToken: 'token',
49
+ domain: {
50
+ emailDomain: 'shop.example'
51
+ }
52
+ })).rejects.toThrow('network down');
53
+ case 1:
54
+ expect(events.map(function (event) {
55
+ return event.digest;
56
+ })).toEqual(['cart.invoicePdf']);
57
+ expect((_events$ = events[0]) === null || _events$ === void 0 ? void 0 : _events$.errorType).toBe('TypeError');
58
+ case 2:
59
+ return _context2.a(2);
60
+ }
61
+ }, _callee2);
62
+ })));
63
+ it('normalises a non-Error rejection instead of dropping it', /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4() {
64
+ return _regenerator().w(function (_context4) {
65
+ while (1) switch (_context4.n) {
66
+ case 0:
67
+ global.fetch = jest.fn(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3() {
68
+ return _regenerator().w(function (_context3) {
69
+ while (1) switch (_context3.n) {
70
+ case 0:
71
+ throw 'pdf failed';
72
+ case 1:
73
+ return _context3.a(2);
74
+ }
75
+ }, _callee3);
76
+ })));
77
+ _context4.n = 1;
78
+ return expect(generatePublicInvoicePdf('https://api.example/', {
79
+ id: 42,
80
+ invoiceToken: 'token',
81
+ domain: null
82
+ })).rejects.toBe('pdf failed');
83
+ case 1:
84
+ expect(events[0]).toMatchObject({
85
+ digest: 'cart.invoicePdf',
86
+ errorType: 'NonErrorException',
87
+ message: 'pdf failed'
88
+ });
89
+ case 2:
90
+ return _context4.a(2);
91
+ }
92
+ }, _callee4);
93
+ })));
94
+ it('reports a non-OK PDF response and still rejects', /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee6() {
95
+ return _regenerator().w(function (_context6) {
96
+ while (1) switch (_context6.n) {
97
+ case 0:
98
+ global.fetch = jest.fn(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5() {
99
+ return _regenerator().w(function (_context5) {
100
+ while (1) switch (_context5.n) {
101
+ case 0:
102
+ return _context5.a(2, {
103
+ ok: false,
104
+ status: 500
105
+ });
106
+ }
107
+ }, _callee5);
108
+ })));
109
+ _context6.n = 1;
110
+ return expect(generatePublicInvoicePdf('https://api.example/', {
111
+ id: 9,
112
+ invoiceToken: 'token',
113
+ domain: {
114
+ emailDomain: 'shop.example'
115
+ }
116
+ })).rejects.toThrow('Error fetching PDF.');
117
+ case 1:
118
+ expect(events[0]).toMatchObject({
119
+ digest: 'cart.invoicePdf',
120
+ errorType: 'Error',
121
+ message: 'Error fetching PDF.'
122
+ });
123
+ case 2:
124
+ return _context6.a(2);
125
+ }
126
+ }, _callee6);
127
+ })));
128
+ it('redacts a non-Error object rejection', /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee8() {
129
+ var _events$2, _events$3;
130
+ return _regenerator().w(function (_context8) {
131
+ while (1) switch (_context8.n) {
132
+ case 0:
133
+ global.fetch = jest.fn(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee7() {
134
+ return _regenerator().w(function (_context7) {
135
+ while (1) switch (_context7.n) {
136
+ case 0:
137
+ throw {
138
+ customerEmail: 'person@example.com'
139
+ };
140
+ case 1:
141
+ return _context7.a(2);
142
+ }
143
+ }, _callee7);
144
+ })));
145
+ _context8.n = 1;
146
+ return expect(generatePublicInvoicePdf('https://api.example/', {
147
+ id: 42,
148
+ invoiceToken: 'token',
149
+ domain: null
150
+ })).rejects.toEqual({
151
+ customerEmail: 'person@example.com'
152
+ });
153
+ case 1:
154
+ expect((_events$2 = events[0]) === null || _events$2 === void 0 ? void 0 : _events$2.errorType).toBe('NonErrorException');
155
+ expect((_events$3 = events[0]) === null || _events$3 === void 0 ? void 0 : _events$3.message).toBe('Non-Error exception');
156
+ expect(JSON.stringify(events[0])).not.toContain('person@example.com');
157
+ case 2:
158
+ return _context8.a(2);
159
+ }
160
+ }, _callee8);
161
+ })));
162
+ it('skips expected client errors and still rejects', /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee0() {
163
+ var error;
164
+ return _regenerator().w(function (_context0) {
165
+ while (1) switch (_context0.n) {
166
+ case 0:
167
+ error = apiError(409, 'invoice token rejected');
168
+ global.fetch = jest.fn(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee9() {
169
+ return _regenerator().w(function (_context9) {
170
+ while (1) switch (_context9.n) {
171
+ case 0:
172
+ throw error;
173
+ case 1:
174
+ return _context9.a(2);
175
+ }
176
+ }, _callee9);
177
+ })));
178
+ _context0.n = 1;
179
+ return expect(generatePublicInvoicePdf('https://api.example/', {
180
+ id: 42,
181
+ invoiceToken: 'token',
182
+ domain: {
183
+ emailDomain: 'shop.example'
184
+ }
185
+ })).rejects.toBe(error);
186
+ case 1:
187
+ expect(events).toEqual([]);
188
+ case 2:
189
+ return _context0.a(2);
190
+ }
191
+ }, _callee0);
192
+ })));
193
+ });
@@ -0,0 +1,38 @@
1
+ import { captureUnexpected } from '@merchi/error-catch';
2
+
3
+ /**
4
+ * Call-site tags recorded on the error-catch event.
5
+ *
6
+ * `CaptureContext.source` only accepts the error-catch enum (`manual`,
7
+ * `window_error`, `unhandled_rejection`, `react_error_boundary`). Any other
8
+ * string is coerced to `manual` and dropped, so the call site is sent as
9
+ * `digest`, which the collector already stores.
10
+ */
11
+ export var CART_FAILURE_SOURCES = {
12
+ addItem: 'cart.addItem',
13
+ invoicePdf: 'cart.invoicePdf'
14
+ };
15
+ /**
16
+ * Report an unexpected cart failure.
17
+ *
18
+ * `captureUnexpected` normalises non-Error rejections and skips expected
19
+ * Merchi client errors (4xx / client error codes). The call is a no-op until
20
+ * the host configures `@merchi/error-catch`, and a failure inside reporting
21
+ * never replaces the original error.
22
+ */
23
+ export function reportCartFailure(error, source) {
24
+ try {
25
+ captureUnexpected(error, {
26
+ source: 'manual',
27
+ digest: source
28
+ });
29
+ } catch (_unused) {
30
+ // Reporting must not replace the original failure.
31
+ }
32
+ }
33
+
34
+ /** Report an add-to-cart failure, then invoke the existing callback. */
35
+ export function reportAddCartItemFailure(error, onError) {
36
+ reportCartFailure(error, CART_FAILURE_SOURCES.addItem);
37
+ onError(error);
38
+ }
@@ -0,0 +1,83 @@
1
+ import { configureFrontendErrors } from '@merchi/error-catch';
2
+ import { reportAddCartItemFailure } from './reportFailure';
3
+ function apiError(statusCode, message) {
4
+ var error = new Error(message);
5
+ error.name = 'ApiError';
6
+ return Object.assign(error, {
7
+ statusCode: statusCode,
8
+ errorCode: 3,
9
+ errorMessage: message
10
+ });
11
+ }
12
+ describe('reportAddCartItemFailure', function () {
13
+ var events = [];
14
+ beforeEach(function () {
15
+ events.length = 0;
16
+ configureFrontendErrors({
17
+ endpoint: 'https://api.merchi.co/v6/frontend-errors',
18
+ application: 'merchi-storefront-1',
19
+ enabled: true,
20
+ dedupeWindowMs: 0,
21
+ transport: function transport(_endpoint, event) {
22
+ events.push(event);
23
+ }
24
+ });
25
+ });
26
+ it('reports an unexpected add-to-cart failure and still calls onError', function () {
27
+ var error = new TypeError('cart item create failed');
28
+ var onError = jest.fn();
29
+ reportAddCartItemFailure(error, onError);
30
+ expect(onError).toHaveBeenCalledTimes(1);
31
+ expect(onError).toHaveBeenCalledWith(error);
32
+ expect(events[0]).toMatchObject({
33
+ digest: 'cart.addItem',
34
+ errorType: 'TypeError',
35
+ message: 'cart item create failed',
36
+ source: 'manual'
37
+ });
38
+ });
39
+ it('normalises a non-Error rejection and forwards the original value', function () {
40
+ var onError = jest.fn();
41
+ reportAddCartItemFailure('stock check failed', onError);
42
+ expect(onError).toHaveBeenCalledWith('stock check failed');
43
+ expect(events[0]).toMatchObject({
44
+ digest: 'cart.addItem',
45
+ errorType: 'NonErrorException',
46
+ message: 'stock check failed'
47
+ });
48
+ });
49
+ it('skips an expected client error and still calls onError', function () {
50
+ var error = apiError(422, 'quantity unavailable');
51
+ var onError = jest.fn();
52
+ reportAddCartItemFailure(error, onError);
53
+ expect(onError).toHaveBeenCalledWith(error);
54
+ expect(events).toEqual([]);
55
+ });
56
+ it('reports a server error', function () {
57
+ var error = apiError(500, 'cart service down');
58
+ var onError = jest.fn();
59
+ reportAddCartItemFailure(error, onError);
60
+ expect(onError).toHaveBeenCalledWith(error);
61
+ expect(events[0]).toMatchObject({
62
+ digest: 'cart.addItem',
63
+ errorType: 'ApiError',
64
+ message: 'cart service down'
65
+ });
66
+ });
67
+ });
68
+ describe('reportCartFailure before error-catch is configured', function () {
69
+ it('does not throw and does not create a reporter', function () {
70
+ jest.isolateModules(function () {
71
+ var errorCatch = require('@merchi/error-catch');
72
+ var reporting = require('./reportFailure');
73
+ var onError = jest.fn();
74
+ var error = new TypeError('boom');
75
+ expect(function () {
76
+ reporting.reportCartFailure(error, 'cart.invoicePdf');
77
+ reporting.reportAddCartItemFailure('plain failure', onError);
78
+ }).not.toThrow();
79
+ expect(onError).toHaveBeenCalledWith('plain failure');
80
+ expect(errorCatch.getDefaultFrontendErrorReporter()).toBeUndefined();
81
+ });
82
+ });
83
+ });
@@ -14,6 +14,7 @@ export var FieldType = /*#__PURE__*/function (FieldType) {
14
14
  FieldType[FieldType["TURNAROUND_TIME"] = 12] = "TURNAROUND_TIME";
15
15
  FieldType[FieldType["COLOUR_EXTRACT"] = 13] = "COLOUR_EXTRACT";
16
16
  FieldType[FieldType["AREA"] = 14] = "AREA";
17
+ FieldType[FieldType["EMBROIDERY"] = 16] = "EMBROIDERY";
17
18
  return FieldType;
18
19
  }({});
19
20
  export function isSelectable(fieldType) {
@@ -51,6 +52,22 @@ export function valueString(variation) {
51
52
  return colours ? "".concat(fileLabel, " (").concat(colours, ")") : fileLabel;
52
53
  }
53
54
  return variationFiles.length > 1 ? 'uploaded files' : 'uploaded file';
55
+ } else if (field.fieldType === FieldType.EMBROIDERY) {
56
+ try {
57
+ var parsed = JSON.parse(String(value || ''));
58
+ var parts = [];
59
+ if (parsed !== null && parsed !== void 0 && parsed.text) parts.push(parsed.text);
60
+ if (parsed !== null && parsed !== void 0 && parsed.widthMm && parsed !== null && parsed !== void 0 && parsed.heightMm) {
61
+ parts.push("".concat(parsed.widthMm, " \xD7 ").concat(parsed.heightMm, " mm"));
62
+ }
63
+ if (Array.isArray(parsed === null || parsed === void 0 ? void 0 : parsed.colours) && parsed.colours.length) {
64
+ parts.push(parsed.colours.length === 1 ? '1 colour' : "".concat(parsed.colours.length, " colours"));
65
+ }
66
+ if (parts.length) return parts.join(' · ');
67
+ } catch (_unused) {
68
+ // Fall through to the raw value.
69
+ }
70
+ return value;
54
71
  } else if (field.fieldType === FieldType.AREA) {
55
72
  return formatAreaSummary(value, localePrefersImperial() ? 'imperial' : 'metric', field.areaUnit || 'mm') || value;
56
73
  }
@@ -19,6 +19,7 @@ var _product = require("./utilities/product");
19
19
  var _local_storage = require("./utilities/local_storage");
20
20
  var _user = require("./utilities/user");
21
21
  var _test_checkout = require("./utilities/test_checkout");
22
+ var _reportFailure = require("./utilities/reportFailure");
22
23
  var _job_source = require("./utilities/job_source");
23
24
  var _jsxRuntime = require("react/jsx-runtime");
24
25
  function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, "default": e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t9 in e) "default" !== _t9 && {}.hasOwnProperty.call(e, _t9) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t9)) && (i.get || i.set) ? o(f, _t9, i) : f[_t9] = e[_t9]); return f; })(e, t); }
@@ -1008,7 +1009,7 @@ var CartProvider = function CartProvider(_ref) {
1008
1009
  case 5:
1009
1010
  _context12.p = 5;
1010
1011
  _t8 = _context12.v;
1011
- onError(_t8);
1012
+ (0, _reportFailure.reportAddCartItemFailure)(_t8, onError);
1012
1013
  case 6:
1013
1014
  _context12.p = 6;
1014
1015
  setFetchingCart(false);
@@ -4,6 +4,7 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.generatePublicInvoicePdf = generatePublicInvoicePdf;
7
+ var _reportFailure = require("./reportFailure");
7
8
  function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = !1, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = !0, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), !0), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, "Generator"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); }
8
9
  function _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); } r ? i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2)); }, _regeneratorDefine2(e, r, n, t); }
9
10
  function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }
@@ -50,17 +51,23 @@ var urlToFilePdf = /*#__PURE__*/function () {
50
51
  return _ref2.apply(this, arguments);
51
52
  };
52
53
  }();
54
+ function publicInvoicePdfFilename(invoice) {
55
+ var _invoice$domain;
56
+ var id = invoice === null || invoice === void 0 ? void 0 : invoice.id;
57
+ var emailDomain = invoice === null || invoice === void 0 || (_invoice$domain = invoice.domain) === null || _invoice$domain === void 0 ? void 0 : _invoice$domain.emailDomain;
58
+ return emailDomain ? "".concat(emailDomain, "-invoice-").concat(id, ".pdf") : "invoice-".concat(id, ".pdf");
59
+ }
53
60
  function generatePublicInvoicePdf(_x6, _x7, _x8) {
54
61
  return _generatePublicInvoicePdf.apply(this, arguments);
55
62
  }
56
63
  function _generatePublicInvoicePdf() {
57
64
  _generatePublicInvoicePdf = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(apiUrl, invoice, receipt) {
58
- var id, domain, queryString, fetchOptions, uri, response, r, pdf, url, doc, anchor, _t;
65
+ var id, filename, queryString, fetchOptions, uri, response, r, pdf, url, doc, anchor, _t;
59
66
  return _regenerator().w(function (_context3) {
60
67
  while (1) switch (_context3.p = _context3.n) {
61
68
  case 0:
62
69
  id = invoice.id;
63
- domain = invoice.domain.emailDomain;
70
+ filename = publicInvoicePdfFilename(invoice);
64
71
  queryString = new URLSearchParams({
65
72
  invoice_token: invoice.invoiceToken
66
73
  }).toString();
@@ -85,7 +92,7 @@ function _generatePublicInvoicePdf() {
85
92
  case 4:
86
93
  r = _context3.v;
87
94
  _context3.n = 5;
88
- return urlToFilePdf("data:application/pdf;base64,".concat(r.pdf), "".concat(domain, "-invoice-").concat(id, ".pdf"));
95
+ return urlToFilePdf("data:application/pdf;base64,".concat(r.pdf), filename);
89
96
  case 5:
90
97
  pdf = _context3.v;
91
98
  url = URL.createObjectURL(pdf);
@@ -108,6 +115,7 @@ function _generatePublicInvoicePdf() {
108
115
  case 6:
109
116
  _context3.p = 6;
110
117
  _t = _context3.v;
118
+ (0, _reportFailure.reportCartFailure)(_t, _reportFailure.CART_FAILURE_SOURCES.invoicePdf);
111
119
  throw _t;
112
120
  case 7:
113
121
  return _context3.a(2);
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Call-site tags recorded on the error-catch event.
3
+ *
4
+ * `CaptureContext.source` only accepts the error-catch enum (`manual`,
5
+ * `window_error`, `unhandled_rejection`, `react_error_boundary`). Any other
6
+ * string is coerced to `manual` and dropped, so the call site is sent as
7
+ * `digest`, which the collector already stores.
8
+ */
9
+ export declare const CART_FAILURE_SOURCES: {
10
+ readonly addItem: "cart.addItem";
11
+ readonly invoicePdf: "cart.invoicePdf";
12
+ };
13
+ export type CartFailureSource = (typeof CART_FAILURE_SOURCES)[keyof typeof CART_FAILURE_SOURCES];
14
+ /**
15
+ * Report an unexpected cart failure.
16
+ *
17
+ * `captureUnexpected` normalises non-Error rejections and skips expected
18
+ * Merchi client errors (4xx / client error codes). The call is a no-op until
19
+ * the host configures `@merchi/error-catch`, and a failure inside reporting
20
+ * never replaces the original error.
21
+ */
22
+ export declare function reportCartFailure(error: unknown, source: CartFailureSource): void;
23
+ /** Report an add-to-cart failure, then invoke the existing callback. */
24
+ export declare function reportAddCartItemFailure(error: unknown, onError: (error: any) => void): void;
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.CART_FAILURE_SOURCES = void 0;
7
+ exports.reportAddCartItemFailure = reportAddCartItemFailure;
8
+ exports.reportCartFailure = reportCartFailure;
9
+ var _errorCatch = require("@merchi/error-catch");
10
+ /**
11
+ * Call-site tags recorded on the error-catch event.
12
+ *
13
+ * `CaptureContext.source` only accepts the error-catch enum (`manual`,
14
+ * `window_error`, `unhandled_rejection`, `react_error_boundary`). Any other
15
+ * string is coerced to `manual` and dropped, so the call site is sent as
16
+ * `digest`, which the collector already stores.
17
+ */
18
+ var CART_FAILURE_SOURCES = exports.CART_FAILURE_SOURCES = {
19
+ addItem: 'cart.addItem',
20
+ invoicePdf: 'cart.invoicePdf'
21
+ };
22
+ /**
23
+ * Report an unexpected cart failure.
24
+ *
25
+ * `captureUnexpected` normalises non-Error rejections and skips expected
26
+ * Merchi client errors (4xx / client error codes). The call is a no-op until
27
+ * the host configures `@merchi/error-catch`, and a failure inside reporting
28
+ * never replaces the original error.
29
+ */
30
+ function reportCartFailure(error, source) {
31
+ try {
32
+ (0, _errorCatch.captureUnexpected)(error, {
33
+ source: 'manual',
34
+ digest: source
35
+ });
36
+ } catch (_unused) {
37
+ // Reporting must not replace the original failure.
38
+ }
39
+ }
40
+
41
+ /** Report an add-to-cart failure, then invoke the existing callback. */
42
+ function reportAddCartItemFailure(error, onError) {
43
+ reportCartFailure(error, CART_FAILURE_SOURCES.addItem);
44
+ onError(error);
45
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -12,7 +12,8 @@ export declare enum FieldType {
12
12
  COLOUR_SELECT = 11,
13
13
  TURNAROUND_TIME = 12,
14
14
  COLOUR_EXTRACT = 13,
15
- AREA = 14
15
+ AREA = 14,
16
+ EMBROIDERY = 16
16
17
  }
17
18
  export declare function isSelectable(fieldType: number): boolean;
18
19
  export declare function valueString(variation: any): any;
@@ -22,6 +22,7 @@ var FieldType = exports.FieldType = /*#__PURE__*/function (FieldType) {
22
22
  FieldType[FieldType["TURNAROUND_TIME"] = 12] = "TURNAROUND_TIME";
23
23
  FieldType[FieldType["COLOUR_EXTRACT"] = 13] = "COLOUR_EXTRACT";
24
24
  FieldType[FieldType["AREA"] = 14] = "AREA";
25
+ FieldType[FieldType["EMBROIDERY"] = 16] = "EMBROIDERY";
25
26
  return FieldType;
26
27
  }({});
27
28
  function isSelectable(fieldType) {
@@ -59,6 +60,22 @@ function valueString(variation) {
59
60
  return colours ? "".concat(fileLabel, " (").concat(colours, ")") : fileLabel;
60
61
  }
61
62
  return variationFiles.length > 1 ? 'uploaded files' : 'uploaded file';
63
+ } else if (field.fieldType === FieldType.EMBROIDERY) {
64
+ try {
65
+ var parsed = JSON.parse(String(value || ''));
66
+ var parts = [];
67
+ if (parsed !== null && parsed !== void 0 && parsed.text) parts.push(parsed.text);
68
+ if (parsed !== null && parsed !== void 0 && parsed.widthMm && parsed !== null && parsed !== void 0 && parsed.heightMm) {
69
+ parts.push("".concat(parsed.widthMm, " \xD7 ").concat(parsed.heightMm, " mm"));
70
+ }
71
+ if (Array.isArray(parsed === null || parsed === void 0 ? void 0 : parsed.colours) && parsed.colours.length) {
72
+ parts.push(parsed.colours.length === 1 ? '1 colour' : "".concat(parsed.colours.length, " colours"));
73
+ }
74
+ if (parts.length) return parts.join(' · ');
75
+ } catch (_unused) {
76
+ // Fall through to the raw value.
77
+ }
78
+ return value;
62
79
  } else if (field.fieldType === FieldType.AREA) {
63
80
  return (0, _area.formatAreaSummary)(value, (0, _area.localePrefersImperial)() ? 'imperial' : 'metric', field.areaUnit || 'mm') || value;
64
81
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@merchi/cart",
3
- "version": "1.4.33",
3
+ "version": "1.4.35",
4
4
  "description": "Merchi's cart",
5
5
  "source": "src/index.ts",
6
6
  "main": "lib/index.js",
@@ -93,20 +93,21 @@
93
93
  "@fortawesome/fontawesome-svg-core": "6.4.2",
94
94
  "@fortawesome/free-solid-svg-icons": "6.4.2",
95
95
  "@fortawesome/react-fontawesome": "^0.2.0",
96
+ "@merchi/error-catch": "^0.1.2",
97
+ "@merchi/invoice": "^1.3.6",
98
+ "@merchi/product-form": "^1.19.39",
99
+ "@merchi/product-form-sdk": "^1.0.27",
100
+ "@merchi/sdk": "^1.42.16",
96
101
  "@stripe/react-stripe-js": "^2.3.0",
97
102
  "@stripe/stripe-js": "^2.1.6",
98
103
  "browser-or-node": "^3.0.0-pre.0",
99
104
  "js-cookie": "^3.0.5",
100
105
  "lodash": "^4.17.21",
101
- "@merchi/product-form": "^1.19.37",
102
- "@merchi/product-form-sdk": "^1.0.26",
103
- "@merchi/sdk": "^1.42.15",
104
106
  "react-country-region-selector": "^3.6.1",
105
107
  "react-hook-form": "7.45.4",
106
108
  "react-icons": "^4.10.1",
107
109
  "react-square-web-payments-sdk": "^3.2.1",
108
110
  "react-transition-group": "^4.4.5",
109
- "reactstrap": "^9.2.2",
110
- "@merchi/invoice": "^1.3.6"
111
+ "reactstrap": "^9.2.2"
111
112
  }
112
113
  }
@@ -21,6 +21,7 @@ import {
21
21
  } from './utilities/local_storage';
22
22
  import { makeUser } from './utilities/user';
23
23
  import { persistTestCheckoutFlag, readTestCheckoutFlag } from './utilities/test_checkout';
24
+ import { reportAddCartItemFailure } from './utilities/reportFailure';
24
25
  import {
25
26
  appendJobSourceToFormData,
26
27
  captureAndReadJobSource,
@@ -853,7 +854,7 @@ const CartProvider = ({
853
854
  const itemJson = await item.toJson();
854
855
  onSuccess(itemJson);
855
856
  } catch(e: any) {
856
- onError(e);
857
+ reportAddCartItemFailure(e, onError);
857
858
  } finally {
858
859
  setFetchingCart(false);
859
860
  }
@@ -0,0 +1,74 @@
1
+ import { generatePublicInvoicePdf } from './invoice';
2
+
3
+ function pdfResponse() {
4
+ return {
5
+ ok: true,
6
+ json: async () => ({ pdf: 'JVBERi0x' }),
7
+ };
8
+ }
9
+
10
+ function dataUrlResponse() {
11
+ return {
12
+ ok: true,
13
+ arrayBuffer: async () => new Uint8Array([1, 2, 3]).buffer,
14
+ };
15
+ }
16
+
17
+ describe('generatePublicInvoicePdf filename', () => {
18
+ const clicks: string[] = [];
19
+
20
+ beforeEach(() => {
21
+ clicks.length = 0;
22
+ if (typeof URL.createObjectURL !== 'function') {
23
+ URL.createObjectURL = () => 'blob:invoice';
24
+ }
25
+ jest.spyOn(URL, 'createObjectURL').mockReturnValue('blob:invoice');
26
+ jest.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) {
27
+ clicks.push(this.download);
28
+ });
29
+ global.fetch = jest.fn(async (input: RequestInfo | URL) => {
30
+ const url = String(input);
31
+ if (url.startsWith('data:')) return dataUrlResponse();
32
+ return pdfResponse();
33
+ }) as unknown as typeof fetch;
34
+ });
35
+
36
+ afterEach(() => {
37
+ jest.restoreAllMocks();
38
+ });
39
+
40
+ it('downloads when domain is missing, using a fallback filename', async () => {
41
+ const result = await generatePublicInvoicePdf('https://api.example/', {
42
+ id: 42,
43
+ invoiceToken: 'token',
44
+ domain: null,
45
+ });
46
+
47
+ expect(result).toEqual({ success: true });
48
+ expect(clicks).toEqual(['invoice-42.pdf']);
49
+ });
50
+
51
+ it('uses the fallback filename when domain or emailDomain is absent', async () => {
52
+ await generatePublicInvoicePdf('https://api.example/', {
53
+ id: 3,
54
+ invoiceToken: 'token',
55
+ });
56
+ await generatePublicInvoicePdf('https://api.example/', {
57
+ id: 4,
58
+ invoiceToken: 'token',
59
+ domain: { emailDomain: '' },
60
+ });
61
+
62
+ expect(clicks).toEqual(['invoice-3.pdf', 'invoice-4.pdf']);
63
+ });
64
+
65
+ it('keeps the email domain in the filename when it is present', async () => {
66
+ await generatePublicInvoicePdf('https://api.example/', {
67
+ id: 7,
68
+ invoiceToken: 'token',
69
+ domain: { emailDomain: 'shop.example' },
70
+ });
71
+
72
+ expect(clicks).toEqual(['shop.example-invoice-7.pdf']);
73
+ });
74
+ });
@@ -1,3 +1,5 @@
1
+ import { CART_FAILURE_SOURCES, reportCartFailure } from './reportFailure';
2
+
1
3
  const urlToFile = async (url: string, filename: string, type: string) => {
2
4
  const res = await fetch(url);
3
5
  const buf = await res.arrayBuffer();
@@ -9,9 +11,15 @@ const urlToFilePdf = async (url: string, filename: string) => {
9
11
  return file;
10
12
  };
11
13
 
14
+ function publicInvoicePdfFilename(invoice: any): string {
15
+ const id = invoice?.id;
16
+ const emailDomain = invoice?.domain?.emailDomain;
17
+ return emailDomain ? `${emailDomain}-invoice-${id}.pdf` : `invoice-${id}.pdf`;
18
+ }
19
+
12
20
  export async function generatePublicInvoicePdf(apiUrl: string, invoice: any, receipt?: boolean) {
13
21
  const id = invoice.id;
14
- const domain = invoice.domain.emailDomain;
22
+ const filename = publicInvoicePdfFilename(invoice);
15
23
 
16
24
  const queryString = new URLSearchParams({
17
25
  invoice_token: invoice.invoiceToken
@@ -35,7 +43,7 @@ export async function generatePublicInvoicePdf(apiUrl: string, invoice: any, rec
35
43
  const r = await response.json();
36
44
  const pdf = await urlToFilePdf(
37
45
  `data:application/pdf;base64,${r.pdf}`,
38
- `${domain}-invoice-${id}.pdf`
46
+ filename
39
47
  );
40
48
 
41
49
  const url = URL.createObjectURL(pdf);
@@ -55,6 +63,7 @@ export async function generatePublicInvoicePdf(apiUrl: string, invoice: any, rec
55
63
 
56
64
  return { success: true };
57
65
  } catch (e: any) {
66
+ reportCartFailure(e, CART_FAILURE_SOURCES.invoicePdf);
58
67
  throw e;
59
68
  }
60
69
  }
@@ -0,0 +1,114 @@
1
+ import {
2
+ configureFrontendErrors,
3
+ type FrontendErrorEvent,
4
+ } from '@merchi/error-catch';
5
+ import { generatePublicInvoicePdf } from './invoice';
6
+
7
+ function apiError(statusCode: number, message: string) {
8
+ const error = new Error(message);
9
+ error.name = 'ApiError';
10
+ return Object.assign(error, {
11
+ statusCode,
12
+ errorCode: 3,
13
+ errorMessage: message,
14
+ });
15
+ }
16
+
17
+ describe('generatePublicInvoicePdf error reporting', () => {
18
+ const events: FrontendErrorEvent[] = [];
19
+
20
+ beforeEach(() => {
21
+ events.length = 0;
22
+ configureFrontendErrors({
23
+ endpoint: 'https://api.merchi.co/v6/frontend-errors',
24
+ application: 'merchi-storefront-1',
25
+ enabled: true,
26
+ dedupeWindowMs: 0,
27
+ transport: (_endpoint, event) => {
28
+ events.push(event);
29
+ },
30
+ });
31
+ global.fetch = jest.fn(async () => {
32
+ throw new TypeError('network down');
33
+ }) as unknown as typeof fetch;
34
+ });
35
+
36
+ it('reports an unexpected failure and still rejects with the original error', async () => {
37
+ await expect(generatePublicInvoicePdf('https://api.example/', {
38
+ id: 42,
39
+ invoiceToken: 'token',
40
+ domain: { emailDomain: 'shop.example' },
41
+ })).rejects.toThrow('network down');
42
+
43
+ expect(events.map((event) => event.digest)).toEqual(['cart.invoicePdf']);
44
+ expect(events[0]?.errorType).toBe('TypeError');
45
+ });
46
+
47
+ it('normalises a non-Error rejection instead of dropping it', async () => {
48
+ global.fetch = jest.fn(async () => {
49
+ throw 'pdf failed';
50
+ }) as unknown as typeof fetch;
51
+
52
+ await expect(generatePublicInvoicePdf('https://api.example/', {
53
+ id: 42,
54
+ invoiceToken: 'token',
55
+ domain: null,
56
+ })).rejects.toBe('pdf failed');
57
+
58
+ expect(events[0]).toMatchObject({
59
+ digest: 'cart.invoicePdf',
60
+ errorType: 'NonErrorException',
61
+ message: 'pdf failed',
62
+ });
63
+ });
64
+
65
+ it('reports a non-OK PDF response and still rejects', async () => {
66
+ global.fetch = jest.fn(async () => ({
67
+ ok: false,
68
+ status: 500,
69
+ })) as unknown as typeof fetch;
70
+
71
+ await expect(generatePublicInvoicePdf('https://api.example/', {
72
+ id: 9,
73
+ invoiceToken: 'token',
74
+ domain: { emailDomain: 'shop.example' },
75
+ })).rejects.toThrow('Error fetching PDF.');
76
+
77
+ expect(events[0]).toMatchObject({
78
+ digest: 'cart.invoicePdf',
79
+ errorType: 'Error',
80
+ message: 'Error fetching PDF.',
81
+ });
82
+ });
83
+
84
+ it('redacts a non-Error object rejection', async () => {
85
+ global.fetch = jest.fn(async () => {
86
+ throw { customerEmail: 'person@example.com' };
87
+ }) as unknown as typeof fetch;
88
+
89
+ await expect(generatePublicInvoicePdf('https://api.example/', {
90
+ id: 42,
91
+ invoiceToken: 'token',
92
+ domain: null,
93
+ })).rejects.toEqual({ customerEmail: 'person@example.com' });
94
+
95
+ expect(events[0]?.errorType).toBe('NonErrorException');
96
+ expect(events[0]?.message).toBe('Non-Error exception');
97
+ expect(JSON.stringify(events[0])).not.toContain('person@example.com');
98
+ });
99
+
100
+ it('skips expected client errors and still rejects', async () => {
101
+ const error = apiError(409, 'invoice token rejected');
102
+ global.fetch = jest.fn(async () => {
103
+ throw error;
104
+ }) as unknown as typeof fetch;
105
+
106
+ await expect(generatePublicInvoicePdf('https://api.example/', {
107
+ id: 42,
108
+ invoiceToken: 'token',
109
+ domain: { emailDomain: 'shop.example' },
110
+ })).rejects.toBe(error);
111
+
112
+ expect(events).toEqual([]);
113
+ });
114
+ });
@@ -0,0 +1,104 @@
1
+ import {
2
+ configureFrontendErrors,
3
+ type FrontendErrorEvent,
4
+ } from '@merchi/error-catch';
5
+ import { reportAddCartItemFailure, reportCartFailure } from './reportFailure';
6
+
7
+ function apiError(statusCode: number, message: string) {
8
+ const error = new Error(message);
9
+ error.name = 'ApiError';
10
+ return Object.assign(error, {
11
+ statusCode,
12
+ errorCode: 3,
13
+ errorMessage: message,
14
+ });
15
+ }
16
+
17
+ describe('reportAddCartItemFailure', () => {
18
+ const events: FrontendErrorEvent[] = [];
19
+
20
+ beforeEach(() => {
21
+ events.length = 0;
22
+ configureFrontendErrors({
23
+ endpoint: 'https://api.merchi.co/v6/frontend-errors',
24
+ application: 'merchi-storefront-1',
25
+ enabled: true,
26
+ dedupeWindowMs: 0,
27
+ transport: (_endpoint, event) => {
28
+ events.push(event);
29
+ },
30
+ });
31
+ });
32
+
33
+ it('reports an unexpected add-to-cart failure and still calls onError', () => {
34
+ const error = new TypeError('cart item create failed');
35
+ const onError = jest.fn();
36
+
37
+ reportAddCartItemFailure(error, onError);
38
+
39
+ expect(onError).toHaveBeenCalledTimes(1);
40
+ expect(onError).toHaveBeenCalledWith(error);
41
+ expect(events[0]).toMatchObject({
42
+ digest: 'cart.addItem',
43
+ errorType: 'TypeError',
44
+ message: 'cart item create failed',
45
+ source: 'manual',
46
+ });
47
+ });
48
+
49
+ it('normalises a non-Error rejection and forwards the original value', () => {
50
+ const onError = jest.fn();
51
+
52
+ reportAddCartItemFailure('stock check failed', onError);
53
+
54
+ expect(onError).toHaveBeenCalledWith('stock check failed');
55
+ expect(events[0]).toMatchObject({
56
+ digest: 'cart.addItem',
57
+ errorType: 'NonErrorException',
58
+ message: 'stock check failed',
59
+ });
60
+ });
61
+
62
+ it('skips an expected client error and still calls onError', () => {
63
+ const error = apiError(422, 'quantity unavailable');
64
+ const onError = jest.fn();
65
+
66
+ reportAddCartItemFailure(error, onError);
67
+
68
+ expect(onError).toHaveBeenCalledWith(error);
69
+ expect(events).toEqual([]);
70
+ });
71
+
72
+ it('reports a server error', () => {
73
+ const error = apiError(500, 'cart service down');
74
+ const onError = jest.fn();
75
+
76
+ reportAddCartItemFailure(error, onError);
77
+
78
+ expect(onError).toHaveBeenCalledWith(error);
79
+ expect(events[0]).toMatchObject({
80
+ digest: 'cart.addItem',
81
+ errorType: 'ApiError',
82
+ message: 'cart service down',
83
+ });
84
+ });
85
+ });
86
+
87
+ describe('reportCartFailure before error-catch is configured', () => {
88
+ it('does not throw and does not create a reporter', () => {
89
+ jest.isolateModules(() => {
90
+ const errorCatch = require('@merchi/error-catch');
91
+ const reporting = require('./reportFailure');
92
+ const onError = jest.fn();
93
+ const error = new TypeError('boom');
94
+
95
+ expect(() => {
96
+ reporting.reportCartFailure(error, 'cart.invoicePdf');
97
+ reporting.reportAddCartItemFailure('plain failure', onError);
98
+ }).not.toThrow();
99
+
100
+ expect(onError).toHaveBeenCalledWith('plain failure');
101
+ expect(errorCatch.getDefaultFrontendErrorReporter()).toBeUndefined();
102
+ });
103
+ });
104
+ });
@@ -0,0 +1,45 @@
1
+ import { captureUnexpected } from '@merchi/error-catch';
2
+
3
+ /**
4
+ * Call-site tags recorded on the error-catch event.
5
+ *
6
+ * `CaptureContext.source` only accepts the error-catch enum (`manual`,
7
+ * `window_error`, `unhandled_rejection`, `react_error_boundary`). Any other
8
+ * string is coerced to `manual` and dropped, so the call site is sent as
9
+ * `digest`, which the collector already stores.
10
+ */
11
+ export const CART_FAILURE_SOURCES = {
12
+ addItem: 'cart.addItem',
13
+ invoicePdf: 'cart.invoicePdf',
14
+ } as const;
15
+
16
+ export type CartFailureSource =
17
+ (typeof CART_FAILURE_SOURCES)[keyof typeof CART_FAILURE_SOURCES];
18
+
19
+ /**
20
+ * Report an unexpected cart failure.
21
+ *
22
+ * `captureUnexpected` normalises non-Error rejections and skips expected
23
+ * Merchi client errors (4xx / client error codes). The call is a no-op until
24
+ * the host configures `@merchi/error-catch`, and a failure inside reporting
25
+ * never replaces the original error.
26
+ */
27
+ export function reportCartFailure(error: unknown, source: CartFailureSource): void {
28
+ try {
29
+ captureUnexpected(error, {
30
+ source: 'manual',
31
+ digest: source,
32
+ });
33
+ } catch {
34
+ // Reporting must not replace the original failure.
35
+ }
36
+ }
37
+
38
+ /** Report an add-to-cart failure, then invoke the existing callback. */
39
+ export function reportAddCartItemFailure(
40
+ error: unknown,
41
+ onError: (error: any) => void,
42
+ ): void {
43
+ reportCartFailure(error, CART_FAILURE_SOURCES.addItem);
44
+ onError(error);
45
+ }
@@ -15,6 +15,7 @@ export enum FieldType {
15
15
  TURNAROUND_TIME = 12,
16
16
  COLOUR_EXTRACT = 13,
17
17
  AREA = 14,
18
+ EMBROIDERY = 16,
18
19
  }
19
20
 
20
21
 
@@ -67,6 +68,24 @@ export function valueString(variation: any) {
67
68
  return colours ? `${fileLabel} (${colours})` : fileLabel;
68
69
  }
69
70
  return variationFiles.length > 1 ? 'uploaded files' : 'uploaded file';
71
+ } else if (field.fieldType === FieldType.EMBROIDERY) {
72
+ try {
73
+ const parsed = JSON.parse(String(value || ''));
74
+ const parts = [];
75
+ if (parsed?.text) parts.push(parsed.text);
76
+ if (parsed?.widthMm && parsed?.heightMm) {
77
+ parts.push(`${parsed.widthMm} × ${parsed.heightMm} mm`);
78
+ }
79
+ if (Array.isArray(parsed?.colours) && parsed.colours.length) {
80
+ parts.push(
81
+ parsed.colours.length === 1 ? '1 colour' : `${parsed.colours.length} colours`
82
+ );
83
+ }
84
+ if (parts.length) return parts.join(' · ');
85
+ } catch {
86
+ // Fall through to the raw value.
87
+ }
88
+ return value;
70
89
  } else if (field.fieldType === FieldType.AREA) {
71
90
  return (
72
91
  formatAreaSummary(