@labdigital/commercetools-mock 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/README.md +8 -0
  2. package/dist/index.d.ts +18 -17
  3. package/dist/index.global.js +1751 -1664
  4. package/dist/index.global.js.map +1 -1
  5. package/dist/index.js +1773 -1684
  6. package/dist/index.js.map +1 -1
  7. package/dist/index.mjs +1966 -1877
  8. package/dist/index.mjs.map +1 -1
  9. package/package.json +28 -20
  10. package/src/constants.ts +4 -2
  11. package/src/ctMock.ts +19 -84
  12. package/src/helpers.ts +9 -10
  13. package/src/index.test.ts +1 -1
  14. package/src/lib/haversine.ts +2 -2
  15. package/src/lib/masking.ts +3 -1
  16. package/src/lib/predicateParser.test.ts +16 -0
  17. package/src/lib/predicateParser.ts +94 -86
  18. package/src/lib/projectionSearchFilter.test.ts +28 -36
  19. package/src/lib/projectionSearchFilter.ts +86 -102
  20. package/src/oauth/store.ts +3 -3
  21. package/src/priceSelector.test.ts +18 -35
  22. package/src/priceSelector.ts +6 -9
  23. package/src/product-projection-search.ts +51 -57
  24. package/src/repositories/abstract.ts +85 -41
  25. package/src/repositories/cart-discount.ts +1 -1
  26. package/src/repositories/cart.ts +36 -31
  27. package/src/repositories/category.ts +17 -19
  28. package/src/repositories/channel.ts +1 -1
  29. package/src/repositories/custom-object.ts +35 -22
  30. package/src/repositories/customer-group.ts +1 -1
  31. package/src/repositories/customer.ts +39 -1
  32. package/src/repositories/discount-code.ts +1 -1
  33. package/src/repositories/errors.ts +9 -11
  34. package/src/repositories/extension.ts +13 -11
  35. package/src/repositories/helpers.ts +8 -13
  36. package/src/repositories/index.ts +59 -0
  37. package/src/repositories/inventory-entry.ts +1 -1
  38. package/src/repositories/order.ts +6 -6
  39. package/src/repositories/payment.ts +3 -3
  40. package/src/repositories/product-discount.ts +1 -1
  41. package/src/repositories/product-projection.ts +1 -0
  42. package/src/repositories/product-type.ts +29 -34
  43. package/src/repositories/product.ts +124 -80
  44. package/src/repositories/project.ts +10 -27
  45. package/src/repositories/shipping-method.ts +15 -17
  46. package/src/repositories/shopping-list.ts +2 -2
  47. package/src/repositories/state.ts +9 -9
  48. package/src/repositories/store.ts +2 -2
  49. package/src/repositories/subscription.ts +1 -1
  50. package/src/repositories/tax-category.ts +4 -4
  51. package/src/repositories/type.ts +12 -14
  52. package/src/repositories/zone.ts +5 -6
  53. package/src/server.ts +5 -0
  54. package/src/services/abstract.ts +44 -11
  55. package/src/services/cart-discount.ts +2 -3
  56. package/src/services/cart.test.ts +8 -10
  57. package/src/services/cart.ts +8 -11
  58. package/src/services/category.test.ts +1 -2
  59. package/src/services/category.ts +2 -3
  60. package/src/services/channel.ts +2 -3
  61. package/src/services/custom-object.test.ts +5 -5
  62. package/src/services/custom-object.ts +2 -3
  63. package/src/services/customer-group.ts +2 -3
  64. package/src/services/customer.test.ts +136 -0
  65. package/src/services/customer.ts +2 -3
  66. package/src/services/discount-code.ts +2 -3
  67. package/src/services/extension.ts +2 -3
  68. package/src/services/index.ts +74 -0
  69. package/src/services/inventory-entry.test.ts +8 -12
  70. package/src/services/inventory-entry.ts +2 -3
  71. package/src/services/my-cart.ts +3 -4
  72. package/src/services/my-customer.ts +2 -3
  73. package/src/services/my-order.ts +3 -4
  74. package/src/services/my-payment.ts +2 -3
  75. package/src/services/order.test.ts +4 -6
  76. package/src/services/order.ts +2 -3
  77. package/src/services/payment.ts +2 -3
  78. package/src/services/product-discount.ts +2 -3
  79. package/src/services/product-projection.test.ts +76 -8
  80. package/src/services/product-projection.ts +2 -3
  81. package/src/services/product-type.ts +2 -3
  82. package/src/services/product.test.ts +199 -89
  83. package/src/services/product.ts +2 -3
  84. package/src/services/project.ts +3 -3
  85. package/src/services/shipping-method.ts +2 -3
  86. package/src/services/shopping-list.ts +2 -3
  87. package/src/services/state.ts +2 -3
  88. package/src/services/store.test.ts +11 -2
  89. package/src/services/store.ts +2 -3
  90. package/src/services/subscription.ts +2 -3
  91. package/src/services/tax-category.ts +2 -3
  92. package/src/services/type.ts +2 -3
  93. package/src/services/zone.ts +2 -3
  94. package/src/storage.ts +23 -30
  95. package/src/types.ts +46 -6
package/dist/index.js CHANGED
@@ -70,8 +70,8 @@ var haversineDistance = (src, dst) => {
70
70
  const toRadian = (deg) => deg * (Math.PI / 180);
71
71
  const dLat = toRadian(dst.latitude - src.latitude);
72
72
  const dLon = toRadian(dst.longitude - src.longitude);
73
- var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(toRadian(src.latitude)) * Math.cos(toRadian(dst.latitude)) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
74
- var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
73
+ const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(toRadian(src.latitude)) * Math.cos(toRadian(dst.latitude)) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
74
+ const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
75
75
  return RADIUS_OF_EARTH_IN_KM * c * 1e3;
76
76
  };
77
77
 
@@ -84,9 +84,7 @@ var PredicateError = class {
84
84
  var parseQueryExpression = (predicate) => {
85
85
  if (Array.isArray(predicate)) {
86
86
  const callbacks = predicate.map((item) => generateMatchFunc(item));
87
- return (target, variables) => {
88
- return callbacks.every((callback) => callback(target, variables));
89
- };
87
+ return (target, variables) => callbacks.every((callback) => callback(target, variables));
90
88
  } else {
91
89
  return generateMatchFunc(predicate);
92
90
  }
@@ -126,60 +124,66 @@ var resolveValue = (obj, val) => {
126
124
  }
127
125
  return obj[val.value];
128
126
  };
129
- var getLexer = (value) => {
130
- return new import_perplex.default(value).token("AND", /and(?![-_a-z0-9]+)/i).token("OR", /or(?![-_a-z0-9]+)/i).token("NOT", /not(?![-_a-z0-9]+)/i).token("WITHIN", /within(?![-_a-z0-9]+)/i).token("IN", /in(?![-_a-z0-9]+)/i).token("MATCHES_IGNORE_CASE", /matches\s+ignore\s+case(?![-_a-z0-9]+)/i).token("CONTAINS", /contains(?![-_a-z0-9]+)/i).token("ALL", /all(?![-_a-z0-9]+)/i).token("ANY", /any(?![-_a-z0-9]+)/i).token("EMPTY", /empty(?![-_a-z0-9]+)/i).token("IS", /is(?![-_a-z0-9]+)/i).token("DEFINED", /defined(?![-_a-z0-9]+)/i).token("FLOAT", /\d+\.\d+/).token("INT", /\d+/).token("VARIABLE", /:([-_A-Za-z0-9]+)/).token("IDENTIFIER", /[-_A-Za-z0-9]+/).token("STRING", /"((?:\\.|[^"\\])*)"/).token("STRING", /'((?:\\.|[^'\\])*)'/).token("COMMA", ",").token("(", "(").token(")", ")").token(">=", ">=").token("<=", "<=").token(">", ">").token("<", "<").token("!=", "!=").token("=", "=").token('"', '"').token("WS", /\s+/, true);
131
- };
127
+ var getLexer = (value) => new import_perplex.default(value).token("AND", /and(?![-_a-z0-9]+)/i).token("OR", /or(?![-_a-z0-9]+)/i).token("NOT", /not(?![-_a-z0-9]+)/i).token("WITHIN", /within(?![-_a-z0-9]+)/i).token("IN", /in(?![-_a-z0-9]+)/i).token("MATCHES_IGNORE_CASE", /matches\s+ignore\s+case(?![-_a-z0-9]+)/i).token("CONTAINS", /contains(?![-_a-z0-9]+)/i).token("ALL", /all(?![-_a-z0-9]+)/i).token("ANY", /any(?![-_a-z0-9]+)/i).token("EMPTY", /empty(?![-_a-z0-9]+)/i).token("IS", /is(?![-_a-z0-9]+)/i).token("DEFINED", /defined(?![-_a-z0-9]+)/i).token("FLOAT", /\d+\.\d+/).token("INT", /\d+/).token("VARIABLE", /:([-_A-Za-z0-9]+)/).token("BOOLEAN", /(true|false)/).token("IDENTIFIER", /[-_A-Za-z0-9]+/).token("STRING", /"((?:\\.|[^"\\])*)"/).token("STRING", /'((?:\\.|[^'\\])*)'/).token("COMMA", ",").token("(", "(").token(")", ")").token(">=", ">=").token("<=", "<=").token(">", ">").token("<", "<").token("!=", "!=").token("=", "=").token('"', '"').token("WS", /\s+/, true);
132
128
  var generateMatchFunc = (predicate) => {
133
129
  const lexer = getLexer(predicate);
134
- const parser = new import_pratt.Parser(lexer).builder().nud("IDENTIFIER", 100, (t) => {
135
- return {
130
+ const parser = new import_pratt.Parser(lexer).builder().nud(
131
+ "IDENTIFIER",
132
+ 100,
133
+ (t) => ({
136
134
  type: "identifier",
137
135
  value: t.token.match,
138
136
  pos: t.token.strpos()
139
- };
140
- }).nud("VARIABLE", 100, (t) => {
141
- return {
137
+ })
138
+ ).nud(
139
+ "BOOLEAN",
140
+ 1,
141
+ (t) => ({
142
+ type: "boolean",
143
+ value: t.token.match === "true" ? true : false,
144
+ pos: t.token.strpos()
145
+ })
146
+ ).nud(
147
+ "VARIABLE",
148
+ 100,
149
+ (t) => ({
142
150
  type: "var",
143
151
  value: t.token.groups[1],
144
152
  pos: t.token.strpos()
145
- };
146
- }).nud("STRING", 100, (t) => {
147
- return {
153
+ })
154
+ ).nud(
155
+ "STRING",
156
+ 100,
157
+ (t) => ({
148
158
  type: "string",
149
159
  value: t.token.groups[1],
150
160
  pos: t.token.strpos()
151
- };
152
- }).nud("INT", 1, (t) => {
153
- return {
161
+ })
162
+ ).nud(
163
+ "INT",
164
+ 1,
165
+ (t) => ({
154
166
  type: "int",
155
167
  value: parseInt(t.token.match, 10),
156
168
  pos: t.token.strpos()
157
- };
158
- }).nud("FLOAT", 1, (t) => {
159
- return {
169
+ })
170
+ ).nud(
171
+ "FLOAT",
172
+ 1,
173
+ (t) => ({
160
174
  type: "float",
161
175
  value: parseFloat(t.token.match),
162
176
  pos: t.token.strpos()
163
- };
164
- }).nud("NOT", 100, ({ bp }) => {
177
+ })
178
+ ).nud("NOT", 100, ({ bp }) => {
165
179
  const expr = parser.parse({ terminals: [bp - 1] });
166
- return (obj) => {
167
- return !expr(obj);
168
- };
169
- }).nud("EMPTY", 10, ({ bp }) => {
170
- return "empty";
171
- }).nud("DEFINED", 10, ({ bp }) => {
172
- return "defined";
173
- }).led("AND", 5, ({ left, bp }) => {
180
+ return (obj) => !expr(obj);
181
+ }).nud("EMPTY", 10, ({ bp }) => "empty").nud("DEFINED", 10, ({ bp }) => "defined").led("AND", 5, ({ left, bp }) => {
174
182
  const expr = parser.parse({ terminals: [bp - 1] });
175
- return (obj) => {
176
- return left(obj) && expr(obj);
177
- };
183
+ return (obj) => left(obj) && expr(obj);
178
184
  }).led("OR", 5, ({ left, token, bp }) => {
179
185
  const expr = parser.parse({ terminals: [bp - 1] });
180
- return (obj, vars) => {
181
- return left(obj, vars) || expr(obj, vars);
182
- };
186
+ return (obj, vars) => left(obj, vars) || expr(obj, vars);
183
187
  }).led("COMMA", 1, ({ left, token, bp }) => {
184
188
  const expr = parser.parse({ terminals: [bp - 1] });
185
189
  if (Array.isArray(expr)) {
@@ -214,33 +218,23 @@ var generateMatchFunc = (predicate) => {
214
218
  }).led("!=", 20, ({ left, bp }) => {
215
219
  const expr = parser.parse({ terminals: [bp - 1] });
216
220
  validateSymbol(expr);
217
- return (obj, vars) => {
218
- return resolveValue(obj, left) !== resolveSymbol(expr, vars);
219
- };
221
+ return (obj, vars) => resolveValue(obj, left) !== resolveSymbol(expr, vars);
220
222
  }).led(">", 20, ({ left, bp }) => {
221
223
  const expr = parser.parse({ terminals: [bp - 1] });
222
224
  validateSymbol(expr);
223
- return (obj, vars) => {
224
- return resolveValue(obj, left) > resolveSymbol(expr, vars);
225
- };
225
+ return (obj, vars) => resolveValue(obj, left) > resolveSymbol(expr, vars);
226
226
  }).led(">=", 20, ({ left, bp }) => {
227
227
  const expr = parser.parse({ terminals: [bp - 1] });
228
228
  validateSymbol(expr);
229
- return (obj, vars) => {
230
- return resolveValue(obj, left) >= resolveSymbol(expr, vars);
231
- };
229
+ return (obj, vars) => resolveValue(obj, left) >= resolveSymbol(expr, vars);
232
230
  }).led("<", 20, ({ left, bp }) => {
233
231
  const expr = parser.parse({ terminals: [bp - 1] });
234
232
  validateSymbol(expr);
235
- return (obj, vars) => {
236
- return resolveValue(obj, left) < resolveSymbol(expr, vars);
237
- };
233
+ return (obj, vars) => resolveValue(obj, left) < resolveSymbol(expr, vars);
238
234
  }).led("<=", 20, ({ left, bp }) => {
239
235
  const expr = parser.parse({ terminals: [bp - 1] });
240
236
  validateSymbol(expr);
241
- return (obj, vars) => {
242
- return resolveValue(obj, left) <= resolveSymbol(expr, vars);
243
- };
237
+ return (obj, vars) => resolveValue(obj, left) <= resolveSymbol(expr, vars);
244
238
  }).led("IS", 20, ({ left, bp }) => {
245
239
  let invert = false;
246
240
  const next = lexer.peek();
@@ -372,6 +366,40 @@ var CommercetoolsError = class extends Error {
372
366
  }
373
367
  };
374
368
 
369
+ // src/helpers.ts
370
+ var import_uuid = require("uuid");
371
+ var getBaseResourceProperties = () => ({
372
+ id: (0, import_uuid.v4)(),
373
+ createdAt: new Date().toISOString(),
374
+ lastModifiedAt: new Date().toISOString(),
375
+ version: 0
376
+ });
377
+ var nestedLookup = (obj, path) => {
378
+ if (!path || path === "") {
379
+ return obj;
380
+ }
381
+ const parts = path.split(".");
382
+ let val = obj;
383
+ for (let i = 0; i < parts.length; i++) {
384
+ const part = parts[i];
385
+ if (val == void 0) {
386
+ return void 0;
387
+ }
388
+ val = val[part];
389
+ }
390
+ return val;
391
+ };
392
+ var QueryParamsAsArray = (input) => {
393
+ if (input == void 0) {
394
+ return [];
395
+ }
396
+ if (Array.isArray(input)) {
397
+ return input;
398
+ }
399
+ return [input];
400
+ };
401
+ var cloneObject = (o) => JSON.parse(JSON.stringify(o));
402
+
375
403
  // src/storage.ts
376
404
  var AbstractStorage = class {
377
405
  };
@@ -414,13 +442,11 @@ var InMemoryStorage = class extends AbstractStorage {
414
442
  this.projects[project.key] = project;
415
443
  return project;
416
444
  };
417
- this.getProject = (projectKey) => {
418
- return this.addProject(projectKey);
419
- };
445
+ this.getProject = (projectKey) => this.addProject(projectKey);
420
446
  this.expand = (projectKey, obj, clause) => {
421
447
  if (!clause)
422
448
  return obj;
423
- const newObj = JSON.parse(JSON.stringify(obj));
449
+ const newObj = cloneObject(obj);
424
450
  if (Array.isArray(clause)) {
425
451
  clause.forEach((c) => {
426
452
  this._resolveResource(projectKey, newObj, c);
@@ -498,12 +524,10 @@ var InMemoryStorage = class extends AbstractStorage {
498
524
  }
499
525
  }
500
526
  }
501
- assertStorage(typeId) {
502
- }
503
527
  all(projectKey, typeId) {
504
528
  const store = this.forProjectKey(projectKey)[typeId];
505
529
  if (store) {
506
- return Array.from(store.values());
530
+ return Array.from(store.values()).map(cloneObject);
507
531
  }
508
532
  return [];
509
533
  }
@@ -513,13 +537,14 @@ var InMemoryStorage = class extends AbstractStorage {
513
537
  (_a = store[typeId]) == null ? void 0 : _a.set(obj.id, obj);
514
538
  const resource = this.get(projectKey, typeId, obj.id, params);
515
539
  (0, import_assert.default)(resource, `resource of type ${typeId} with id ${obj.id} not created`);
516
- return resource;
540
+ return cloneObject(resource);
517
541
  }
518
542
  get(projectKey, typeId, id, params = {}) {
519
543
  var _a;
520
544
  const resource = (_a = this.forProjectKey(projectKey)[typeId]) == null ? void 0 : _a.get(id);
521
545
  if (resource) {
522
- return this.expand(projectKey, resource, params.expand);
546
+ const clone = cloneObject(resource);
547
+ return this.expand(projectKey, clone, params.expand);
523
548
  }
524
549
  return null;
525
550
  }
@@ -532,7 +557,8 @@ var InMemoryStorage = class extends AbstractStorage {
532
557
  const resources = Array.from(resourceStore.values());
533
558
  const resource = resources.find((e) => e.key === key);
534
559
  if (resource) {
535
- return this.expand(projectKey, resource, params.expand);
560
+ const clone = cloneObject(resource);
561
+ return this.expand(projectKey, clone, params.expand);
536
562
  }
537
563
  return null;
538
564
  }
@@ -570,24 +596,20 @@ var InMemoryStorage = class extends AbstractStorage {
570
596
  const limit = params.limit || 20;
571
597
  resources = resources.slice(offset, offset + limit);
572
598
  if (params.expand !== void 0) {
573
- resources = resources.map((resource) => {
574
- return this.expand(projectKey, resource, params.expand);
575
- });
599
+ resources = resources.map(
600
+ (resource) => this.expand(projectKey, resource, params.expand)
601
+ );
576
602
  }
577
603
  return {
578
604
  count: totalResources,
579
605
  total: resources.length,
580
606
  offset,
581
607
  limit,
582
- results: resources
608
+ results: resources.map(cloneObject)
583
609
  };
584
610
  }
585
611
  search(projectKey, typeId, params) {
586
- const store = this.forProjectKey(projectKey)[typeId];
587
- if (!store) {
588
- throw new Error("No type");
589
- }
590
- let resources = Array.from(store.values());
612
+ let resources = this.all(projectKey, typeId);
591
613
  if (params.where) {
592
614
  try {
593
615
  const filterFunc = parseQueryExpression(params.where);
@@ -607,9 +629,9 @@ var InMemoryStorage = class extends AbstractStorage {
607
629
  const limit = params.limit || 20;
608
630
  resources = resources.slice(offset, offset + limit);
609
631
  if (params.expand !== void 0) {
610
- resources = resources.map((resource) => {
611
- return this.expand(projectKey, resource, params.expand);
612
- });
632
+ resources = resources.map(
633
+ (resource) => this.expand(projectKey, resource, params.expand)
634
+ );
613
635
  }
614
636
  return {
615
637
  count: totalResources,
@@ -810,41 +832,6 @@ var OAuth2Server = class {
810
832
  }
811
833
  };
812
834
 
813
- // src/helpers.ts
814
- var import_uuid = require("uuid");
815
- var getBaseResourceProperties = () => {
816
- return {
817
- id: (0, import_uuid.v4)(),
818
- createdAt: new Date().toISOString(),
819
- lastModifiedAt: new Date().toISOString(),
820
- version: 0
821
- };
822
- };
823
- var nestedLookup = (obj, path) => {
824
- if (!path || path === "") {
825
- return obj;
826
- }
827
- const parts = path.split(".");
828
- let val = obj;
829
- for (let i = 0; i < parts.length; i++) {
830
- const part = parts[i];
831
- if (val == void 0) {
832
- return void 0;
833
- }
834
- val = val[part];
835
- }
836
- return val;
837
- };
838
- var QueryParamsAsArray = (input) => {
839
- if (input == void 0) {
840
- return [];
841
- }
842
- if (Array.isArray(input)) {
843
- return input;
844
- }
845
- return [input];
846
- };
847
-
848
835
  // src/projectAPI.ts
849
836
  var ProjectAPI = class {
850
837
  constructor(projectKey, services, storage) {
@@ -896,9 +883,6 @@ var copyHeaders = (headers) => {
896
883
  var DEFAULT_API_HOSTNAME = /^https:\/\/api\..*?\.commercetools.com:443$/;
897
884
  var DEFAULT_AUTH_HOSTNAME = /^https:\/\/auth\..*?\.commercetools.com:443$/;
898
885
 
899
- // src/services/abstract.ts
900
- var import_express2 = require("express");
901
-
902
886
  // src/repositories/helpers.ts
903
887
  var import_uuid2 = require("uuid");
904
888
  var createAddress = (base, projectKey, storage) => {
@@ -937,12 +921,10 @@ var createCustomFields = (draft, projectKey, storage) => {
937
921
  fields: draft.fields
938
922
  };
939
923
  };
940
- var createPrice = (draft) => {
941
- return {
942
- id: (0, import_uuid2.v4)(),
943
- value: createTypedMoney(draft.value)
944
- };
945
- };
924
+ var createPrice = (draft) => ({
925
+ id: (0, import_uuid2.v4)(),
926
+ value: createTypedMoney(draft.value)
927
+ });
946
928
  var createTypedMoney = (value) => {
947
929
  let fractionDigits = 2;
948
930
  switch (value.currencyCode.toUpperCase()) {
@@ -1024,143 +1006,58 @@ var getReferenceFromResourceIdentifier = (resourceIdentifier, projectKey, storag
1024
1006
  id: resource == null ? void 0 : resource.id
1025
1007
  };
1026
1008
  };
1027
- var getRepositoryContext = (request) => {
1028
- return {
1029
- projectKey: request.params.projectKey,
1030
- storeKey: request.params.storeKey
1031
- };
1032
- };
1009
+ var getRepositoryContext = (request) => ({
1010
+ projectKey: request.params.projectKey,
1011
+ storeKey: request.params.storeKey
1012
+ });
1033
1013
 
1034
- // src/services/abstract.ts
1035
- var AbstractService = class {
1036
- constructor(parent) {
1037
- this.createStatusCode = 201;
1014
+ // src/services/project.ts
1015
+ var ProjectService = class {
1016
+ constructor(parent, repository) {
1017
+ this.repository = repository;
1038
1018
  this.registerRoutes(parent);
1039
1019
  }
1040
- extraRoutes(router) {
1041
- }
1042
1020
  registerRoutes(parent) {
1043
- const basePath = this.getBasePath();
1044
- const router = (0, import_express2.Router)({ mergeParams: true });
1045
- this.extraRoutes(router);
1046
- router.get("/", this.get.bind(this));
1047
- router.get("/key=:key", this.getWithKey.bind(this));
1048
- router.get("/:id", this.getWithId.bind(this));
1049
- router.delete("/key=:key", this.deletewithKey.bind(this));
1050
- router.delete("/:id", this.deletewithId.bind(this));
1051
- router.post("/", this.post.bind(this));
1052
- router.post("/key=:key", this.postWithKey.bind(this));
1053
- router.post("/:id", this.postWithId.bind(this));
1054
- parent.use(`/${basePath}`, router);
1021
+ parent.get("", this.get.bind(this));
1022
+ parent.post("", this.post.bind(this));
1055
1023
  }
1056
1024
  get(request, response) {
1057
- const limit = this._parseParam(request.query.limit);
1058
- const offset = this._parseParam(request.query.offset);
1059
- const result = this.repository.query(getRepositoryContext(request), {
1060
- expand: this._parseParam(request.query.expand),
1061
- where: this._parseParam(request.query.where),
1062
- limit: limit !== void 0 ? Number(limit) : void 0,
1063
- offset: offset !== void 0 ? Number(offset) : void 0
1064
- });
1065
- return response.status(200).send(result);
1066
- }
1067
- getWithId(request, response) {
1068
- const result = this._expandWithId(request, request.params["id"]);
1069
- if (!result) {
1070
- return response.status(404).send();
1071
- }
1072
- return response.status(200).send(result);
1073
- }
1074
- getWithKey(request, response) {
1075
- const result = this.repository.getByKey(
1076
- getRepositoryContext(request),
1077
- request.params["key"],
1078
- { expand: this._parseParam(request.query.expand) }
1079
- );
1080
- if (!result)
1081
- return response.status(404).send();
1082
- return response.status(200).send(result);
1083
- }
1084
- deletewithId(request, response) {
1085
- const result = this.repository.delete(
1086
- getRepositoryContext(request),
1087
- request.params["id"],
1088
- {
1089
- expand: this._parseParam(request.query.expand)
1090
- }
1091
- );
1092
- if (!result) {
1093
- return response.status(404).send("Not found");
1094
- }
1095
- return response.status(200).send(result);
1096
- }
1097
- deletewithKey(request, response) {
1098
- return response.status(500).send("Not implemented");
1025
+ const project = this.repository.get(getRepositoryContext(request));
1026
+ return response.status(200).send(project);
1099
1027
  }
1100
1028
  post(request, response) {
1101
- const draft = request.body;
1102
- const resource = this.repository.create(
1103
- getRepositoryContext(request),
1104
- draft
1105
- );
1106
- const result = this._expandWithId(request, resource.id);
1107
- return response.status(this.createStatusCode).send(result);
1108
- }
1109
- postWithId(request, response) {
1110
1029
  const updateRequest = request.body;
1111
- const resource = this.repository.get(
1112
- getRepositoryContext(request),
1113
- request.params["id"]
1114
- );
1115
- if (!resource) {
1116
- return response.status(404).send("Not found");
1117
- }
1118
- if (resource.version !== updateRequest.version) {
1119
- return response.status(409).send("Concurrent modification");
1030
+ const project = this.repository.get(getRepositoryContext(request));
1031
+ if (!project) {
1032
+ return response.status(404).send({});
1120
1033
  }
1121
- const updatedResource = this.repository.processUpdateActions(
1034
+ this.repository.processUpdateActions(
1122
1035
  getRepositoryContext(request),
1123
- resource,
1036
+ project,
1037
+ updateRequest.version,
1124
1038
  updateRequest.actions
1125
1039
  );
1126
- const result = this._expandWithId(request, updatedResource.id);
1127
- return response.status(200).send(result);
1128
- }
1129
- postWithKey(request, response) {
1130
- return response.status(500).send("Not implemented");
1131
- }
1132
- _expandWithId(request, resourceId) {
1133
- const result = this.repository.get(
1134
- getRepositoryContext(request),
1135
- resourceId,
1136
- {
1137
- expand: this._parseParam(request.query.expand)
1138
- }
1139
- );
1140
- return result;
1141
- }
1142
- _parseParam(value) {
1143
- if (Array.isArray(value)) {
1144
- return value;
1145
- } else if (value !== void 0) {
1146
- return [`${value}`];
1147
- }
1148
- return void 0;
1040
+ return response.status(200).send({});
1149
1041
  }
1150
1042
  };
1151
1043
 
1044
+ // src/repositories/cart.ts
1045
+ var import_uuid3 = require("uuid");
1046
+
1152
1047
  // src/repositories/abstract.ts
1153
1048
  var import_deep_equal = __toESM(require("deep-equal"));
1154
1049
 
1155
1050
  // src/repositories/errors.ts
1156
- var checkConcurrentModification = (resource, expectedVersion) => {
1157
- if (resource.version === expectedVersion)
1051
+ var checkConcurrentModification = (currentVersion, expectedVersion, identifier) => {
1052
+ if (currentVersion === expectedVersion)
1158
1053
  return;
1159
- const identifier = resource.id ? resource.id : resource.key;
1054
+ console.error(
1055
+ `Object ${identifier} has a different version than expected. Expected: ${expectedVersion} - Actual: ${currentVersion}.`
1056
+ );
1160
1057
  throw new CommercetoolsError(
1161
1058
  {
1162
- message: `Object ${identifier} has a different version than expected. Expected: ${expectedVersion} - Actual: ${resource.version}.`,
1163
- currentVersion: resource.version,
1059
+ message: `Object ${identifier} has a different version than expected. Expected: ${expectedVersion} - Actual: ${currentVersion}.`,
1060
+ currentVersion,
1164
1061
  code: "ConcurrentModification"
1165
1062
  },
1166
1063
  409
@@ -1173,20 +1070,28 @@ var AbstractRepository = class {
1173
1070
  this.actions = {};
1174
1071
  this._storage = storage;
1175
1072
  }
1176
- processUpdateActions(context, resource, actions) {
1177
- const modifiedResource = JSON.parse(JSON.stringify(resource));
1073
+ processUpdateActions(context, resource, version, actions) {
1074
+ const updatedResource = cloneObject(resource);
1075
+ const identifier = resource.id ? resource.id : resource.key;
1178
1076
  actions.forEach((action) => {
1179
1077
  const updateFunc = this.actions[action.action];
1180
1078
  if (!updateFunc) {
1181
1079
  console.error(`No mock implemented for update action ${action.action}`);
1182
- return;
1080
+ throw new Error(
1081
+ `No mock implemented for update action ${action.action}`
1082
+ );
1083
+ }
1084
+ const beforeUpdate = cloneObject(resource);
1085
+ updateFunc(context, updatedResource, action);
1086
+ if (!(0, import_deep_equal.default)(beforeUpdate, updatedResource)) {
1087
+ checkConcurrentModification(resource.version, version, identifier);
1088
+ updatedResource.version += 1;
1183
1089
  }
1184
- updateFunc(context, modifiedResource, action);
1185
1090
  });
1186
- if (!(0, import_deep_equal.default)(modifiedResource, resource)) {
1187
- this.save(context, modifiedResource);
1091
+ if (resource.version != updatedResource.version) {
1092
+ this.saveUpdate(context, version, updatedResource);
1188
1093
  }
1189
- const result = this.postProcessResource(modifiedResource);
1094
+ const result = this.postProcessResource(updatedResource);
1190
1095
  if (!result) {
1191
1096
  throw new Error("invalid post process action");
1192
1097
  }
@@ -1199,7 +1104,6 @@ var AbstractRepository = class {
1199
1104
  var AbstractResourceRepository = class extends AbstractRepository {
1200
1105
  constructor(storage) {
1201
1106
  super(storage);
1202
- this._storage.assertStorage(this.getTypeId());
1203
1107
  }
1204
1108
  query(context, params = {}) {
1205
1109
  const result = this._storage.query(context.projectKey, this.getTypeId(), {
@@ -1212,8 +1116,13 @@ var AbstractResourceRepository = class extends AbstractRepository {
1212
1116
  return result;
1213
1117
  }
1214
1118
  get(context, id, params = {}) {
1215
- const resource = this._storage.get(context.projectKey, this.getTypeId(), id, params);
1216
- return this.postProcessResource(resource);
1119
+ const resource = this._storage.get(
1120
+ context.projectKey,
1121
+ this.getTypeId(),
1122
+ id,
1123
+ params
1124
+ );
1125
+ return resource ? this.postProcessResource(resource) : null;
1217
1126
  }
1218
1127
  getByKey(context, key, params = {}) {
1219
1128
  const resource = this._storage.getByKey(
@@ -1222,7 +1131,7 @@ var AbstractResourceRepository = class extends AbstractRepository {
1222
1131
  key,
1223
1132
  params
1224
1133
  );
1225
- return this.postProcessResource(resource);
1134
+ return resource ? this.postProcessResource(resource) : null;
1226
1135
  }
1227
1136
  delete(context, id, params = {}) {
1228
1137
  const resource = this._storage.delete(
@@ -1231,122 +1140,38 @@ var AbstractResourceRepository = class extends AbstractRepository {
1231
1140
  id,
1232
1141
  params
1233
1142
  );
1234
- return this.postProcessResource(resource);
1143
+ return resource ? this.postProcessResource(resource) : null;
1235
1144
  }
1236
- save(context, resource) {
1237
- const current = this.get(context, resource.id);
1238
- if (current) {
1239
- checkConcurrentModification(current, resource.version);
1240
- } else {
1241
- if (resource.version !== 0) {
1242
- throw new CommercetoolsError(
1243
- {
1244
- code: "InvalidOperation",
1245
- message: "version on create must be 0"
1246
- },
1247
- 400
1248
- );
1249
- }
1145
+ saveNew(context, resource) {
1146
+ resource.version = 1;
1147
+ this._storage.add(context.projectKey, this.getTypeId(), resource);
1148
+ }
1149
+ saveUpdate(context, version, resource) {
1150
+ const current = this._storage.get(
1151
+ context.projectKey,
1152
+ this.getTypeId(),
1153
+ resource.id
1154
+ );
1155
+ if (!current) {
1156
+ throw new CommercetoolsError(
1157
+ {
1158
+ code: "ResourceNotFound",
1159
+ message: "Resource not found while updating"
1160
+ },
1161
+ 400
1162
+ );
1250
1163
  }
1251
- resource.version += 1;
1164
+ checkConcurrentModification(current.version, version, resource.id);
1165
+ if (current.version === resource.version) {
1166
+ throw new Error("Internal error: no changes to save");
1167
+ }
1168
+ resource.lastModifiedAt = new Date().toISOString();
1252
1169
  this._storage.add(context.projectKey, this.getTypeId(), resource);
1253
- }
1254
- };
1255
-
1256
- // src/repositories/cart-discount.ts
1257
- var CartDiscountRepository = class extends AbstractResourceRepository {
1258
- constructor() {
1259
- super(...arguments);
1260
- this.actions = {
1261
- setKey: (context, resource, { key }) => {
1262
- resource.key = key;
1263
- },
1264
- setDescription: (context, resource, { description }) => {
1265
- resource.description = description;
1266
- },
1267
- setValidFrom: (context, resource, { validFrom }) => {
1268
- resource.validFrom = validFrom;
1269
- },
1270
- setValidUntil: (context, resource, { validUntil }) => {
1271
- resource.validUntil = validUntil;
1272
- },
1273
- setValidFromAndUntil: (context, resource, { validFrom, validUntil }) => {
1274
- resource.validFrom = validFrom;
1275
- resource.validUntil = validUntil;
1276
- },
1277
- changeSortOrder: (context, resource, { sortOrder }) => {
1278
- resource.sortOrder = sortOrder;
1279
- },
1280
- changeIsActive: (context, resource, { isActive }) => {
1281
- resource.isActive = isActive;
1282
- }
1283
- };
1284
- }
1285
- getTypeId() {
1286
- return "cart-discount";
1287
- }
1288
- create(context, draft) {
1289
- const resource = {
1290
- ...getBaseResourceProperties(),
1291
- key: draft.key,
1292
- description: draft.description,
1293
- cartPredicate: draft.cartPredicate,
1294
- isActive: draft.isActive || false,
1295
- name: draft.name,
1296
- references: [],
1297
- target: draft.target,
1298
- requiresDiscountCode: draft.requiresDiscountCode || false,
1299
- sortOrder: draft.sortOrder,
1300
- stackingMode: draft.stackingMode || "Stacking",
1301
- validFrom: draft.validFrom,
1302
- validUntil: draft.validUntil,
1303
- value: this.transformValueDraft(draft.value)
1304
- };
1305
- this.save(context, resource);
1306
- return resource;
1307
- }
1308
- transformValueDraft(value) {
1309
- switch (value.type) {
1310
- case "absolute": {
1311
- return {
1312
- type: "absolute",
1313
- money: value.money.map(createTypedMoney)
1314
- };
1315
- }
1316
- case "fixed": {
1317
- return {
1318
- type: "fixed",
1319
- money: value.money.map(createTypedMoney)
1320
- };
1321
- }
1322
- case "giftLineItem": {
1323
- return {
1324
- ...value
1325
- };
1326
- }
1327
- case "relative": {
1328
- return {
1329
- ...value
1330
- };
1331
- }
1332
- }
1333
- return value;
1334
- }
1335
- };
1336
-
1337
- // src/services/cart-discount.ts
1338
- var CartDiscountService = class extends AbstractService {
1339
- constructor(parent, storage) {
1340
- super(parent);
1341
- this.repository = new CartDiscountRepository(storage);
1342
- }
1343
- getBasePath() {
1344
- return "cart-discounts";
1170
+ return resource;
1345
1171
  }
1346
1172
  };
1347
1173
 
1348
1174
  // src/repositories/cart.ts
1349
- var import_uuid3 = require("uuid");
1350
1175
  var CartRepository = class extends AbstractResourceRepository {
1351
1176
  constructor() {
1352
1177
  super(...arguments);
@@ -1354,7 +1179,6 @@ var CartRepository = class extends AbstractResourceRepository {
1354
1179
  addLineItem: (context, resource, { productId, variantId, sku, quantity = 1 }) => {
1355
1180
  var _a;
1356
1181
  let product = null;
1357
- let variant;
1358
1182
  if (productId && variantId) {
1359
1183
  product = this._storage.get(
1360
1184
  context.projectKey,
@@ -1378,7 +1202,7 @@ var CartRepository = class extends AbstractResourceRepository {
1378
1202
  message: sku ? `A product containing a variant with SKU '${sku}' not found.` : `A product with ID '${productId}' not found.`
1379
1203
  });
1380
1204
  }
1381
- variant = [
1205
+ const variant = [
1382
1206
  product.masterData.current.masterVariant,
1383
1207
  ...product.masterData.current.variants
1384
1208
  ].find((x) => {
@@ -1455,7 +1279,9 @@ var CartRepository = class extends AbstractResourceRepository {
1455
1279
  }
1456
1280
  const shouldDelete = !quantity || quantity >= lineItem.quantity;
1457
1281
  if (shouldDelete) {
1458
- resource.lineItems = resource.lineItems.filter((x) => x.id !== lineItemId);
1282
+ resource.lineItems = resource.lineItems.filter(
1283
+ (x) => x.id !== lineItemId
1284
+ );
1459
1285
  } else {
1460
1286
  resource.lineItems.map((x) => {
1461
1287
  if (x.id === lineItemId && quantity) {
@@ -1471,19 +1297,24 @@ var CartRepository = class extends AbstractResourceRepository {
1471
1297
  resource.billingAddress = address;
1472
1298
  },
1473
1299
  setShippingMethod: (context, resource, { shippingMethod }) => {
1474
- const resolvedType = this._storage.getByResourceIdentifier(
1475
- context.projectKey,
1476
- shippingMethod
1477
- );
1478
- if (!resolvedType) {
1479
- throw new Error(`Type ${shippingMethod} not found`);
1480
- }
1481
- resource.shippingInfo = {
1482
- shippingMethod: {
1483
- typeId: "shipping-method",
1484
- id: resolvedType.id
1300
+ if (shippingMethod) {
1301
+ const method = this._storage.getByResourceIdentifier(
1302
+ context.projectKey,
1303
+ shippingMethod
1304
+ );
1305
+ if (!method) {
1306
+ throw new Error(`Type ${shippingMethod} not found`);
1485
1307
  }
1486
- };
1308
+ resource.shippingInfo = {
1309
+ shippingMethod: {
1310
+ typeId: "shipping-method",
1311
+ id: method.id
1312
+ },
1313
+ shippingMethodName: method.name
1314
+ };
1315
+ } else {
1316
+ resource.shippingInfo = void 0;
1317
+ }
1487
1318
  },
1488
1319
  setCountry: (context, resource, { country }) => {
1489
1320
  resource.country = country;
@@ -1527,7 +1358,6 @@ var CartRepository = class extends AbstractResourceRepository {
1527
1358
  this.draftLineItemtoLineItem = (projectKey, draftLineItem, currency, country) => {
1528
1359
  const { productId, quantity, variantId, sku } = draftLineItem;
1529
1360
  let product = null;
1530
- let variant;
1531
1361
  if (productId && variantId) {
1532
1362
  product = this._storage.get(projectKey, "product", productId, {});
1533
1363
  } else if (sku) {
@@ -1546,7 +1376,7 @@ var CartRepository = class extends AbstractResourceRepository {
1546
1376
  message: sku ? `A product containing a variant with SKU '${sku}' not found.` : `A product with ID '${productId}' not found.`
1547
1377
  });
1548
1378
  }
1549
- variant = [
1379
+ const variant = [
1550
1380
  product.masterData.current.masterVariant,
1551
1381
  ...product.masterData.current.variants
1552
1382
  ].find((x) => {
@@ -1627,7 +1457,7 @@ var CartRepository = class extends AbstractResourceRepository {
1627
1457
  )
1628
1458
  };
1629
1459
  resource.totalPrice.centAmount = calculateCartTotalPrice(resource);
1630
- this.save(context, resource);
1460
+ this.saveNew(context, resource);
1631
1461
  return resource;
1632
1462
  }
1633
1463
  getActiveCart(projectKey) {
@@ -1657,313 +1487,84 @@ var selectPrice = ({
1657
1487
  var calculateLineItemTotalPrice = (lineItem) => lineItem.price.value.centAmount * lineItem.quantity;
1658
1488
  var calculateCartTotalPrice = (cart) => cart.lineItems.reduce((cur, item) => cur + item.totalPrice.centAmount, 0);
1659
1489
 
1660
- // src/repositories/order.ts
1661
- var import_assert2 = __toESM(require("assert"));
1662
- var OrderRepository = class extends AbstractResourceRepository {
1490
+ // src/repositories/cart-discount.ts
1491
+ var CartDiscountRepository = class extends AbstractResourceRepository {
1663
1492
  constructor() {
1664
1493
  super(...arguments);
1665
1494
  this.actions = {
1666
- addPayment: (context, resource, { payment }) => {
1667
- const resolvedPayment = this._storage.getByResourceIdentifier(
1668
- context.projectKey,
1669
- payment
1670
- );
1671
- if (!resolvedPayment) {
1672
- throw new Error(`Payment ${payment.id} not found`);
1673
- }
1674
- if (!resource.paymentInfo) {
1675
- resource.paymentInfo = {
1676
- payments: []
1677
- };
1678
- }
1679
- resource.paymentInfo.payments.push({
1680
- typeId: "payment",
1681
- id: payment.id
1682
- });
1683
- },
1684
- changeOrderState: (context, resource, { orderState }) => {
1685
- resource.orderState = orderState;
1686
- },
1687
- changePaymentState: (context, resource, { paymentState }) => {
1688
- resource.paymentState = paymentState;
1689
- },
1690
- transitionState: (context, resource, { state }) => {
1691
- const resolvedType = this._storage.getByResourceIdentifier(
1692
- context.projectKey,
1693
- state
1694
- );
1695
- if (!resolvedType) {
1696
- throw new Error(
1697
- `No state found with key=${state.key} or id=${state.key}`
1698
- );
1699
- }
1700
- resource.state = { typeId: "state", id: resolvedType.id };
1701
- },
1702
- setBillingAddress: (context, resource, { address }) => {
1703
- resource.billingAddress = address;
1704
- },
1705
- setCustomerEmail: (context, resource, { email }) => {
1706
- resource.customerEmail = email;
1495
+ setKey: (context, resource, { key }) => {
1496
+ resource.key = key;
1707
1497
  },
1708
- setCustomField: (context, resource, { name, value }) => {
1709
- if (!resource.custom) {
1710
- throw new Error("Resource has no custom field");
1711
- }
1712
- resource.custom.fields[name] = value;
1498
+ setDescription: (context, resource, { description }) => {
1499
+ resource.description = description;
1713
1500
  },
1714
- setCustomType: (context, resource, { type, fields }) => {
1715
- if (!type) {
1716
- resource.custom = void 0;
1717
- } else {
1718
- const resolvedType = this._storage.getByResourceIdentifier(
1719
- context.projectKey,
1720
- type
1721
- );
1722
- if (!resolvedType) {
1723
- throw new Error(`Type ${type} not found`);
1724
- }
1725
- resource.custom = {
1726
- type: {
1727
- typeId: "type",
1728
- id: resolvedType.id
1729
- },
1730
- fields: fields || []
1731
- };
1732
- }
1501
+ setValidFrom: (context, resource, { validFrom }) => {
1502
+ resource.validFrom = validFrom;
1733
1503
  },
1734
- setLocale: (context, resource, { locale }) => {
1735
- resource.locale = locale;
1504
+ setValidUntil: (context, resource, { validUntil }) => {
1505
+ resource.validUntil = validUntil;
1736
1506
  },
1737
- setOrderNumber: (context, resource, { orderNumber }) => {
1738
- resource.orderNumber = orderNumber;
1507
+ setValidFromAndUntil: (context, resource, { validFrom, validUntil }) => {
1508
+ resource.validFrom = validFrom;
1509
+ resource.validUntil = validUntil;
1739
1510
  },
1740
- setShippingAddress: (context, resource, { address }) => {
1741
- resource.shippingAddress = address;
1511
+ changeSortOrder: (context, resource, { sortOrder }) => {
1512
+ resource.sortOrder = sortOrder;
1742
1513
  },
1743
- setStore: (context, resource, { store }) => {
1744
- if (!store)
1745
- return;
1746
- const resolvedType = this._storage.getByResourceIdentifier(
1747
- context.projectKey,
1748
- store
1749
- );
1750
- if (!resolvedType) {
1751
- throw new Error(`No store found with key=${store.key}`);
1752
- }
1753
- const storeReference = resolvedType;
1754
- resource.store = {
1755
- typeId: "store",
1756
- key: storeReference.key
1757
- };
1514
+ changeIsActive: (context, resource, { isActive }) => {
1515
+ resource.isActive = isActive;
1758
1516
  }
1759
1517
  };
1760
1518
  }
1761
1519
  getTypeId() {
1762
- return "order";
1520
+ return "cart-discount";
1763
1521
  }
1764
1522
  create(context, draft) {
1765
- (0, import_assert2.default)(draft.cart, "draft.cart is missing");
1766
- return this.createFromCart(
1767
- context,
1768
- {
1769
- id: draft.cart.id,
1770
- typeId: "cart"
1771
- },
1772
- draft.orderNumber
1773
- );
1774
- }
1775
- createFromCart(context, cartReference, orderNumber) {
1776
- const cart = this._storage.getByResourceIdentifier(
1777
- context.projectKey,
1778
- cartReference
1779
- );
1780
- if (!cart) {
1781
- throw new Error("Cannot find cart");
1782
- }
1783
1523
  const resource = {
1784
1524
  ...getBaseResourceProperties(),
1785
- orderNumber,
1786
- cart: cartReference,
1787
- orderState: "Open",
1788
- lineItems: [],
1789
- customLineItems: [],
1790
- totalPrice: cart.totalPrice,
1791
- refusedGifts: [],
1792
- origin: "Customer",
1793
- syncInfo: [],
1794
- store: context.storeKey ? {
1795
- key: context.storeKey,
1796
- typeId: "store"
1797
- } : void 0,
1798
- lastMessageSequenceNumber: 0
1525
+ key: draft.key,
1526
+ description: draft.description,
1527
+ cartPredicate: draft.cartPredicate,
1528
+ isActive: draft.isActive || false,
1529
+ name: draft.name,
1530
+ references: [],
1531
+ target: draft.target,
1532
+ requiresDiscountCode: draft.requiresDiscountCode || false,
1533
+ sortOrder: draft.sortOrder,
1534
+ stackingMode: draft.stackingMode || "Stacking",
1535
+ validFrom: draft.validFrom,
1536
+ validUntil: draft.validUntil,
1537
+ value: this.transformValueDraft(draft.value)
1799
1538
  };
1800
- this.save(context, resource);
1539
+ this.saveNew(context, resource);
1801
1540
  return resource;
1802
1541
  }
1803
- import(context, draft) {
1804
- var _a, _b;
1805
- (0, import_assert2.default)(this, "OrderRepository not valid");
1806
- const resource = {
1807
- ...getBaseResourceProperties(),
1808
- billingAddress: draft.billingAddress,
1809
- shippingAddress: draft.shippingAddress,
1810
- custom: createCustomFields(
1811
- draft.custom,
1812
- context.projectKey,
1813
- this._storage
1814
- ),
1815
- customerEmail: draft.customerEmail,
1816
- lastMessageSequenceNumber: 0,
1817
- orderNumber: draft.orderNumber,
1818
- orderState: draft.orderState || "Open",
1819
- origin: draft.origin || "Customer",
1820
- paymentState: draft.paymentState,
1821
- refusedGifts: [],
1822
- store: resolveStoreReference(
1823
- draft.store,
1824
- context.projectKey,
1825
- this._storage
1826
- ),
1827
- syncInfo: [],
1828
- lineItems: ((_a = draft.lineItems) == null ? void 0 : _a.map(
1829
- (item) => this.lineItemFromImportDraft.bind(this)(context, item)
1830
- )) || [],
1831
- customLineItems: ((_b = draft.customLineItems) == null ? void 0 : _b.map(
1832
- (item) => this.customLineItemFromImportDraft.bind(this)(context, item)
1833
- )) || [],
1834
- totalPrice: {
1835
- type: "centPrecision",
1836
- ...draft.totalPrice,
1837
- fractionDigits: 2
1838
- }
1839
- };
1840
- this.save(context, resource);
1841
- return resource;
1842
- }
1843
- lineItemFromImportDraft(context, draft) {
1844
- let product;
1845
- let variant;
1846
- if (draft.variant.sku) {
1847
- variant = {
1848
- id: 0,
1849
- sku: draft.variant.sku
1850
- };
1851
- var items = this._storage.query(context.projectKey, "product", {
1852
- where: [
1853
- `masterData(current(masterVariant(sku="${draft.variant.sku}"))) or masterData(current(variants(sku="${draft.variant.sku}")))`
1854
- ]
1855
- });
1856
- if (items.count !== 1) {
1857
- throw new CommercetoolsError({
1858
- code: "General",
1859
- message: `A product containing a variant with SKU '${draft.variant.sku}' not found.`
1860
- });
1542
+ transformValueDraft(value) {
1543
+ switch (value.type) {
1544
+ case "absolute": {
1545
+ return {
1546
+ type: "absolute",
1547
+ money: value.money.map(createTypedMoney)
1548
+ };
1861
1549
  }
1862
- product = items.results[0];
1863
- if (product.masterData.current.masterVariant.sku === draft.variant.sku) {
1864
- variant = product.masterData.current.masterVariant;
1865
- } else {
1866
- variant = product.masterData.current.variants.find(
1867
- (v) => v.sku === draft.variant.sku
1868
- );
1550
+ case "fixed": {
1551
+ return {
1552
+ type: "fixed",
1553
+ money: value.money.map(createTypedMoney)
1554
+ };
1869
1555
  }
1870
- if (!variant) {
1871
- throw new Error("Internal state error");
1556
+ case "giftLineItem": {
1557
+ return {
1558
+ ...value
1559
+ };
1872
1560
  }
1873
- } else {
1874
- throw new Error("No product found");
1875
- }
1876
- const lineItem = {
1877
- ...getBaseResourceProperties(),
1878
- custom: createCustomFields(
1879
- draft.custom,
1880
- context.projectKey,
1881
- this._storage
1882
- ),
1883
- discountedPricePerQuantity: [],
1884
- lineItemMode: "Standard",
1885
- name: draft.name,
1886
- price: createPrice(draft.price),
1887
- priceMode: "Platform",
1888
- productId: product.id,
1889
- productType: product.productType,
1890
- quantity: draft.quantity,
1891
- state: draft.state || [],
1892
- taxRate: draft.taxRate,
1893
- totalPrice: createTypedMoney(draft.price.value),
1894
- variant: {
1895
- id: variant.id,
1896
- sku: variant.sku,
1897
- price: createPrice(draft.price)
1561
+ case "relative": {
1562
+ return {
1563
+ ...value
1564
+ };
1898
1565
  }
1899
- };
1900
- return lineItem;
1901
- }
1902
- customLineItemFromImportDraft(context, draft) {
1903
- const lineItem = {
1904
- ...getBaseResourceProperties(),
1905
- custom: createCustomFields(
1906
- draft.custom,
1907
- context.projectKey,
1908
- this._storage
1909
- ),
1910
- discountedPricePerQuantity: [],
1911
- money: createTypedMoney(draft.money),
1912
- name: draft.name,
1913
- quantity: draft.quantity,
1914
- slug: draft.slug,
1915
- state: [],
1916
- totalPrice: createTypedMoney(draft.money)
1917
- };
1918
- return lineItem;
1919
- }
1920
- getWithOrderNumber(context, orderNumber, params = {}) {
1921
- const result = this._storage.query(context.projectKey, this.getTypeId(), {
1922
- ...params,
1923
- where: [`orderNumber="${orderNumber}"`]
1924
- });
1925
- if (result.count === 1) {
1926
- return result.results[0];
1927
1566
  }
1928
- if (result.count > 1) {
1929
- throw new Error("Duplicate order numbers");
1930
- }
1931
- return;
1932
- }
1933
- };
1934
-
1935
- // src/services/cart.ts
1936
- var CartService = class extends AbstractService {
1937
- constructor(parent, storage) {
1938
- super(parent);
1939
- this.repository = new CartRepository(storage);
1940
- this.orderRepository = new OrderRepository(storage);
1941
- }
1942
- getBasePath() {
1943
- return "carts";
1944
- }
1945
- extraRoutes(parent) {
1946
- parent.post("/replicate", (request, response) => {
1947
- const context = getRepositoryContext(request);
1948
- const cartOrOrder = request.body.reference.typeId === "order" ? this.orderRepository.get(context, request.body.reference.id) : this.repository.get(context, request.body.reference.id);
1949
- if (!cartOrOrder) {
1950
- return response.status(400).send();
1951
- }
1952
- const cartDraft = {
1953
- ...cartOrOrder,
1954
- currency: cartOrOrder.totalPrice.currencyCode,
1955
- discountCodes: [],
1956
- lineItems: cartOrOrder.lineItems.map((lineItem) => {
1957
- return {
1958
- ...lineItem,
1959
- variantId: lineItem.variant.id,
1960
- sku: lineItem.variant.sku
1961
- };
1962
- })
1963
- };
1964
- const newCart = this.repository.create(context, cartDraft);
1965
- return response.status(200).send(newCart);
1966
- });
1567
+ return value;
1967
1568
  }
1968
1569
  };
1969
1570
 
@@ -2061,43 +1662,30 @@ var CategoryRepository = class extends AbstractResourceRepository {
2061
1662
  externalId: draft.externalId || "",
2062
1663
  parent: draft.parent ? { typeId: "category", id: draft.parent.id } : void 0,
2063
1664
  ancestors: [],
2064
- assets: ((_a = draft.assets) == null ? void 0 : _a.map((d) => {
2065
- return {
2066
- id: (0, import_uuid4.v4)(),
2067
- name: d.name,
2068
- description: d.description,
2069
- sources: d.sources,
2070
- tags: d.tags,
2071
- key: d.key,
2072
- custom: createCustomFields(
2073
- draft.custom,
2074
- context.projectKey,
2075
- this._storage
2076
- )
2077
- };
2078
- })) || [],
1665
+ assets: ((_a = draft.assets) == null ? void 0 : _a.map((d) => ({
1666
+ id: (0, import_uuid4.v4)(),
1667
+ name: d.name,
1668
+ description: d.description,
1669
+ sources: d.sources,
1670
+ tags: d.tags,
1671
+ key: d.key,
1672
+ custom: createCustomFields(
1673
+ draft.custom,
1674
+ context.projectKey,
1675
+ this._storage
1676
+ )
1677
+ }))) || [],
2079
1678
  custom: createCustomFields(
2080
1679
  draft.custom,
2081
1680
  context.projectKey,
2082
1681
  this._storage
2083
1682
  )
2084
1683
  };
2085
- this.save(context, resource);
1684
+ this.saveNew(context, resource);
2086
1685
  return resource;
2087
1686
  }
2088
1687
  };
2089
1688
 
2090
- // src/services/category.ts
2091
- var CategoryServices = class extends AbstractService {
2092
- constructor(parent, storage) {
2093
- super(parent);
2094
- this.repository = new CategoryRepository(storage);
2095
- }
2096
- getBasePath() {
2097
- return "categories";
2098
- }
2099
- };
2100
-
2101
1689
  // src/repositories/channel.ts
2102
1690
  var ChannelRepository = class extends AbstractResourceRepository {
2103
1691
  constructor() {
@@ -2163,93 +1751,103 @@ var ChannelRepository = class extends AbstractResourceRepository {
2163
1751
  this._storage
2164
1752
  )
2165
1753
  };
2166
- this.save(context, resource);
1754
+ this.saveNew(context, resource);
2167
1755
  return resource;
2168
1756
  }
2169
1757
  };
2170
1758
 
2171
- // src/services/channel.ts
2172
- var ChannelService = class extends AbstractService {
2173
- constructor(parent, storage) {
2174
- super(parent);
2175
- this.repository = new ChannelRepository(storage);
1759
+ // src/repositories/custom-object.ts
1760
+ var CustomObjectRepository = class extends AbstractResourceRepository {
1761
+ getTypeId() {
1762
+ return "key-value-document";
2176
1763
  }
2177
- getBasePath() {
2178
- return "channels";
1764
+ create(context, draft) {
1765
+ const current = this.getWithContainerAndKey(
1766
+ context,
1767
+ draft.container,
1768
+ draft.key
1769
+ );
1770
+ if (current) {
1771
+ if (draft.version) {
1772
+ checkConcurrentModification(current.version, draft.version, current.id);
1773
+ } else {
1774
+ draft.version = current.version;
1775
+ }
1776
+ if (draft.value !== current.value) {
1777
+ const updated = cloneObject(current);
1778
+ updated.value = draft.value;
1779
+ updated.version += 1;
1780
+ this.saveUpdate(context, draft.version, updated);
1781
+ return updated;
1782
+ }
1783
+ return current;
1784
+ } else {
1785
+ if (draft.version) {
1786
+ throw new CommercetoolsError(
1787
+ {
1788
+ code: "InvalidOperation",
1789
+ message: "version on create must be 0"
1790
+ },
1791
+ 400
1792
+ );
1793
+ }
1794
+ const baseProperties = getBaseResourceProperties();
1795
+ const resource = {
1796
+ ...baseProperties,
1797
+ container: draft.container,
1798
+ key: draft.key,
1799
+ value: draft.value
1800
+ };
1801
+ this.saveNew(context, resource);
1802
+ return resource;
1803
+ }
1804
+ }
1805
+ getWithContainerAndKey(context, container, key) {
1806
+ const items = this._storage.all(
1807
+ context.projectKey,
1808
+ this.getTypeId()
1809
+ );
1810
+ return items.find(
1811
+ (item) => item.container === container && item.key === key
1812
+ );
2179
1813
  }
2180
1814
  };
2181
1815
 
2182
- // src/repositories/customer-group.ts
2183
- var CustomerGroupRepository = class extends AbstractResourceRepository {
1816
+ // src/repositories/customer.ts
1817
+ var CustomerRepository = class extends AbstractResourceRepository {
2184
1818
  constructor() {
2185
1819
  super(...arguments);
2186
1820
  this.actions = {
2187
- setKey: (context, resource, { key }) => {
2188
- resource.key = key;
2189
- },
2190
- changeName: (context, resource, { name }) => {
2191
- resource.name = name;
1821
+ changeEmail: (_context, resource, { email }) => {
1822
+ resource.email = email;
2192
1823
  },
2193
- setCustomType: (context, resource, { type, fields }) => {
2194
- if (type) {
2195
- resource.custom = createCustomFields(
2196
- { type, fields },
2197
- context.projectKey,
2198
- this._storage
1824
+ setAuthenticationMode: (_context, resource, { authMode, password }) => {
1825
+ if (resource.authenticationMode === authMode) {
1826
+ throw new CommercetoolsError(
1827
+ {
1828
+ code: "InvalidInput",
1829
+ message: `The customer is already using the '${resource.authenticationMode}' authentication mode.`
1830
+ },
1831
+ 400
2199
1832
  );
2200
- } else {
2201
- resource.custom = void 0;
2202
1833
  }
2203
- },
2204
- setCustomField: (context, resource, { name, value }) => {
2205
- if (!resource.custom) {
1834
+ resource.authenticationMode = authMode;
1835
+ if (authMode === "ExternalAuth") {
1836
+ delete resource.password;
2206
1837
  return;
2207
1838
  }
2208
- if (value === null) {
2209
- delete resource.custom.fields[name];
2210
- } else {
2211
- resource.custom.fields[name] = value;
1839
+ if (authMode === "Password") {
1840
+ resource.password = password ? Buffer.from(password).toString("base64") : void 0;
1841
+ return;
2212
1842
  }
2213
- }
2214
- };
2215
- }
2216
- getTypeId() {
2217
- return "customer";
2218
- }
2219
- create(context, draft) {
2220
- const resource = {
2221
- ...getBaseResourceProperties(),
2222
- key: draft.key,
2223
- name: draft.groupName,
2224
- custom: createCustomFields(
2225
- draft.custom,
2226
- context.projectKey,
2227
- this._storage
2228
- )
2229
- };
2230
- this.save(context, resource);
2231
- return resource;
2232
- }
2233
- };
2234
-
2235
- // src/services/customer-group.ts
2236
- var CustomerGroupService = class extends AbstractService {
2237
- constructor(parent, storage) {
2238
- super(parent);
2239
- this.repository = new CustomerGroupRepository(storage);
2240
- }
2241
- getBasePath() {
2242
- return "customer-groups";
2243
- }
2244
- };
2245
-
2246
- // src/repositories/customer.ts
2247
- var CustomerRepository = class extends AbstractResourceRepository {
2248
- constructor() {
2249
- super(...arguments);
2250
- this.actions = {
2251
- changeEmail: (_context, resource, { email }) => {
2252
- resource.email = email;
1843
+ throw new CommercetoolsError(
1844
+ {
1845
+ code: "InvalidJsonInput",
1846
+ message: "Request body does not contain valid JSON.",
1847
+ detailedErrorMessage: `actions -> authMode: Invalid enum value: '${authMode}'. Expected one of: 'Password','ExternalAuth'`
1848
+ },
1849
+ 400
1850
+ );
2253
1851
  }
2254
1852
  };
2255
1853
  }
@@ -2264,7 +1862,7 @@ var CustomerRepository = class extends AbstractResourceRepository {
2264
1862
  isEmailVerified: draft.isEmailVerified || false,
2265
1863
  addresses: []
2266
1864
  };
2267
- this.save(context, resource);
1865
+ this.saveNew(context, resource);
2268
1866
  return resource;
2269
1867
  }
2270
1868
  getMe(context) {
@@ -2280,127 +1878,57 @@ var CustomerRepository = class extends AbstractResourceRepository {
2280
1878
  }
2281
1879
  };
2282
1880
 
2283
- // src/services/customer.ts
2284
- var import_uuid5 = require("uuid");
2285
- var CustomerService = class extends AbstractService {
2286
- constructor(parent, storage) {
2287
- super(parent);
2288
- this.repository = new CustomerRepository(storage);
2289
- }
2290
- getBasePath() {
2291
- return "customers";
2292
- }
2293
- extraRoutes(parent) {
2294
- parent.post("/password-token", (request, response) => {
2295
- const customer = this.repository.query(getRepositoryContext(request), {
2296
- where: [`email="${request.body.email}"`]
2297
- });
2298
- const ttlMinutes = request.params.ttlMinutes ? +request.params.ttlMinutes : 34560;
2299
- const { version, ...rest } = getBaseResourceProperties();
2300
- return response.status(200).send({
2301
- ...rest,
2302
- customerId: customer.results[0].id,
2303
- expiresAt: new Date(Date.now() + ttlMinutes * 60).toISOString(),
2304
- value: (0, import_uuid5.v4)()
2305
- });
2306
- });
1881
+ // src/repositories/customer-group.ts
1882
+ var CustomerGroupRepository = class extends AbstractResourceRepository {
1883
+ constructor() {
1884
+ super(...arguments);
1885
+ this.actions = {
1886
+ setKey: (context, resource, { key }) => {
1887
+ resource.key = key;
1888
+ },
1889
+ changeName: (context, resource, { name }) => {
1890
+ resource.name = name;
1891
+ },
1892
+ setCustomType: (context, resource, { type, fields }) => {
1893
+ if (type) {
1894
+ resource.custom = createCustomFields(
1895
+ { type, fields },
1896
+ context.projectKey,
1897
+ this._storage
1898
+ );
1899
+ } else {
1900
+ resource.custom = void 0;
1901
+ }
1902
+ },
1903
+ setCustomField: (context, resource, { name, value }) => {
1904
+ if (!resource.custom) {
1905
+ return;
1906
+ }
1907
+ if (value === null) {
1908
+ delete resource.custom.fields[name];
1909
+ } else {
1910
+ resource.custom.fields[name] = value;
1911
+ }
1912
+ }
1913
+ };
2307
1914
  }
2308
- };
2309
-
2310
- // src/repositories/custom-object.ts
2311
- var CustomObjectRepository = class extends AbstractResourceRepository {
2312
1915
  getTypeId() {
2313
- return "key-value-document";
1916
+ return "customer";
2314
1917
  }
2315
1918
  create(context, draft) {
2316
- const current = this.getWithContainerAndKey(
2317
- context,
2318
- draft.container,
2319
- draft.key
2320
- );
2321
- const baseProperties = getBaseResourceProperties();
2322
- if (current) {
2323
- baseProperties.id = current.id;
2324
- if (!draft.version) {
2325
- draft.version = current.version;
2326
- }
2327
- checkConcurrentModification(current, draft.version);
2328
- if (draft.value === current.value) {
2329
- return current;
2330
- }
2331
- baseProperties.version = current.version;
2332
- } else {
2333
- if (draft.version) {
2334
- baseProperties.version = draft.version;
2335
- }
2336
- }
2337
1919
  const resource = {
2338
- ...baseProperties,
2339
- container: draft.container,
1920
+ ...getBaseResourceProperties(),
2340
1921
  key: draft.key,
2341
- value: draft.value
1922
+ name: draft.groupName,
1923
+ custom: createCustomFields(
1924
+ draft.custom,
1925
+ context.projectKey,
1926
+ this._storage
1927
+ )
2342
1928
  };
2343
- this.save(context, resource);
1929
+ this.saveNew(context, resource);
2344
1930
  return resource;
2345
1931
  }
2346
- getWithContainerAndKey(context, container, key) {
2347
- const items = this._storage.all(
2348
- context.projectKey,
2349
- this.getTypeId()
2350
- );
2351
- return items.find((item) => item.container === container && item.key === key);
2352
- }
2353
- };
2354
-
2355
- // src/services/custom-object.ts
2356
- var CustomObjectService = class extends AbstractService {
2357
- constructor(parent, storage) {
2358
- super(parent);
2359
- this.repository = new CustomObjectRepository(storage);
2360
- }
2361
- getBasePath() {
2362
- return "custom-objects";
2363
- }
2364
- extraRoutes(router) {
2365
- router.get("/:container/:key", this.getWithContainerAndKey.bind(this));
2366
- router.post("/:container/:key", this.createWithContainerAndKey.bind(this));
2367
- router.delete("/:container/:key", this.deleteWithContainerAndKey.bind(this));
2368
- }
2369
- getWithContainerAndKey(request, response) {
2370
- const result = this.repository.getWithContainerAndKey(
2371
- getRepositoryContext(request),
2372
- request.params.container,
2373
- request.params.key
2374
- );
2375
- if (!result) {
2376
- return response.status(404).send("Not Found");
2377
- }
2378
- return response.status(200).send(result);
2379
- }
2380
- createWithContainerAndKey(request, response) {
2381
- const draft = {
2382
- ...request.body,
2383
- key: request.params.key,
2384
- container: request.params.container
2385
- };
2386
- const result = this.repository.create(getRepositoryContext(request), draft);
2387
- return response.status(200).send(result);
2388
- }
2389
- deleteWithContainerAndKey(request, response) {
2390
- const current = this.repository.getWithContainerAndKey(
2391
- getRepositoryContext(request),
2392
- request.params.container,
2393
- request.params.key
2394
- );
2395
- if (!current) {
2396
- return response.status(404).send("Not Found");
2397
- }
2398
- const result = this.repository.delete(
2399
- getRepositoryContext(request),
2400
- current.id
2401
- );
2402
- return response.status(200).send(result);
2403
- }
2404
1932
  };
2405
1933
 
2406
1934
  // src/repositories/discount-code.ts
@@ -2499,26 +2027,15 @@ var DiscountCodeRepository = class extends AbstractResourceRepository {
2499
2027
  this._storage
2500
2028
  )
2501
2029
  };
2502
- this.save(context, resource);
2030
+ this.saveNew(context, resource);
2503
2031
  return resource;
2504
2032
  }
2505
2033
  };
2506
2034
 
2507
- // src/services/discount-code.ts
2508
- var DiscountCodeService = class extends AbstractService {
2509
- constructor(parent, storage) {
2510
- super(parent);
2511
- this.repository = new DiscountCodeRepository(storage);
2512
- }
2513
- getBasePath() {
2514
- return "discount-codes";
2515
- }
2516
- };
2517
-
2518
2035
  // src/lib/masking.ts
2519
2036
  var maskSecretValue = (resource, path) => {
2520
2037
  const parts = path.split(".");
2521
- const clone = JSON.parse(JSON.stringify(resource));
2038
+ const clone = cloneObject(resource);
2522
2039
  let val = clone;
2523
2040
  const target = parts.pop();
2524
2041
  for (let i = 0; i < parts.length; i++) {
@@ -2559,16 +2076,14 @@ var ExtensionRepository = class extends AbstractResourceRepository {
2559
2076
  postProcessResource(resource) {
2560
2077
  var _a;
2561
2078
  if (resource) {
2562
- if (resource.destination.type === "HTTP" && ((_a = resource.destination.authentication) == null ? void 0 : _a.type) === "AuthorizationHeader") {
2079
+ const extension = resource;
2080
+ if (extension.destination.type === "HTTP" && ((_a = extension.destination.authentication) == null ? void 0 : _a.type) === "AuthorizationHeader") {
2563
2081
  return maskSecretValue(
2564
- resource,
2082
+ extension,
2565
2083
  "destination.authentication.headerValue"
2566
2084
  );
2567
- } else if (resource.destination.type == "AWSLambda") {
2568
- return maskSecretValue(
2569
- resource,
2570
- "destination.accessSecret"
2571
- );
2085
+ } else if (extension.destination.type == "AWSLambda") {
2086
+ return maskSecretValue(resource, "destination.accessSecret");
2572
2087
  }
2573
2088
  }
2574
2089
  return resource;
@@ -2581,22 +2096,11 @@ var ExtensionRepository = class extends AbstractResourceRepository {
2581
2096
  destination: draft.destination,
2582
2097
  triggers: draft.triggers
2583
2098
  };
2584
- this.save(context, resource);
2099
+ this.saveNew(context, resource);
2585
2100
  return resource;
2586
2101
  }
2587
2102
  };
2588
2103
 
2589
- // src/services/extension.ts
2590
- var ExtensionServices = class extends AbstractService {
2591
- constructor(parent, storage) {
2592
- super(parent);
2593
- this.repository = new ExtensionRepository(storage);
2594
- }
2595
- getBasePath() {
2596
- return "extensions";
2597
- }
2598
- };
2599
-
2600
2104
  // src/repositories/inventory-entry.ts
2601
2105
  var InventoryEntryRepository = class extends AbstractResourceRepository {
2602
2106
  constructor() {
@@ -2663,68 +2167,65 @@ var InventoryEntryRepository = class extends AbstractResourceRepository {
2663
2167
  this._storage
2664
2168
  )
2665
2169
  };
2666
- this.save(context, resource);
2170
+ this.saveNew(context, resource);
2667
2171
  return resource;
2668
2172
  }
2669
2173
  };
2670
2174
 
2671
- // src/services/inventory-entry.ts
2672
- var InventoryEntryService = class extends AbstractService {
2673
- constructor(parent, storage) {
2674
- super(parent);
2675
- this.repository = new InventoryEntryRepository(storage);
2676
- }
2677
- getBasePath() {
2678
- return "inventory";
2679
- }
2680
- };
2681
-
2682
- // src/services/my-cart.ts
2683
- var import_express3 = require("express");
2684
- var MyCartService = class extends AbstractService {
2685
- constructor(parent, storage) {
2686
- super(parent);
2687
- this.repository = new CartRepository(storage);
2688
- }
2689
- getBasePath() {
2690
- return "me";
2691
- }
2692
- registerRoutes(parent) {
2693
- const basePath = this.getBasePath();
2694
- const router = (0, import_express3.Router)({ mergeParams: true });
2695
- this.extraRoutes(router);
2696
- router.get("/active-cart", this.activeCart.bind(this));
2697
- router.get("/carts/", this.get.bind(this));
2698
- router.get("/carts/:id", this.getWithId.bind(this));
2699
- router.delete("/carts/:id", this.deletewithId.bind(this));
2700
- router.post("/carts/", this.post.bind(this));
2701
- router.post("/carts/:id", this.postWithId.bind(this));
2702
- parent.use(`/${basePath}`, router);
2703
- }
2704
- activeCart(request, response) {
2705
- const resource = this.repository.getActiveCart(request.params.projectKey);
2706
- if (!resource) {
2707
- return response.status(404).send("Not found");
2708
- }
2709
- return response.status(200).send(resource);
2710
- }
2711
- };
2175
+ // src/repositories/my-order.ts
2176
+ var import_assert3 = __toESM(require("assert"));
2712
2177
 
2713
- // src/repositories/payment.ts
2714
- var import_uuid6 = require("uuid");
2715
- var PaymentRepository = class extends AbstractResourceRepository {
2178
+ // src/repositories/order.ts
2179
+ var import_assert2 = __toESM(require("assert"));
2180
+ var OrderRepository = class extends AbstractResourceRepository {
2716
2181
  constructor() {
2717
2182
  super(...arguments);
2718
- this.transactionFromTransactionDraft = (draft, context) => ({
2719
- ...draft,
2720
- id: (0, import_uuid6.v4)(),
2721
- amount: createTypedMoney(draft.amount),
2722
- custom: createCustomFields(draft.custom, context.projectKey, this._storage)
2723
- });
2724
2183
  this.actions = {
2725
- setCustomField: (context, resource, { name, value }) => {
2726
- if (!resource.custom) {
2727
- throw new Error("Resource has no custom field");
2184
+ addPayment: (context, resource, { payment }) => {
2185
+ const resolvedPayment = this._storage.getByResourceIdentifier(
2186
+ context.projectKey,
2187
+ payment
2188
+ );
2189
+ if (!resolvedPayment) {
2190
+ throw new Error(`Payment ${payment.id} not found`);
2191
+ }
2192
+ if (!resource.paymentInfo) {
2193
+ resource.paymentInfo = {
2194
+ payments: []
2195
+ };
2196
+ }
2197
+ resource.paymentInfo.payments.push({
2198
+ typeId: "payment",
2199
+ id: payment.id
2200
+ });
2201
+ },
2202
+ changeOrderState: (context, resource, { orderState }) => {
2203
+ resource.orderState = orderState;
2204
+ },
2205
+ changePaymentState: (context, resource, { paymentState }) => {
2206
+ resource.paymentState = paymentState;
2207
+ },
2208
+ transitionState: (context, resource, { state }) => {
2209
+ const resolvedType = this._storage.getByResourceIdentifier(
2210
+ context.projectKey,
2211
+ state
2212
+ );
2213
+ if (!resolvedType) {
2214
+ throw new Error(
2215
+ `No state found with key=${state.key} or id=${state.key}`
2216
+ );
2217
+ }
2218
+ resource.state = { typeId: "state", id: resolvedType.id };
2219
+ },
2220
+ setBillingAddress: (context, resource, { address }) => {
2221
+ resource.billingAddress = address;
2222
+ },
2223
+ setCustomerEmail: (context, resource, { email }) => {
2224
+ resource.customerEmail = email;
2225
+ },
2226
+ setCustomField: (context, resource, { name, value }) => {
2227
+ if (!resource.custom) {
2228
+ throw new Error("Resource has no custom field");
2728
2229
  }
2729
2230
  resource.custom.fields[name] = value;
2730
2231
  },
@@ -2748,126 +2249,490 @@ var PaymentRepository = class extends AbstractResourceRepository {
2748
2249
  };
2749
2250
  }
2750
2251
  },
2751
- addTransaction: (context, resource, { transaction }) => {
2752
- resource.transactions = [
2753
- ...resource.transactions,
2754
- this.transactionFromTransactionDraft(transaction, context)
2755
- ];
2252
+ setLocale: (context, resource, { locale }) => {
2253
+ resource.locale = locale;
2756
2254
  },
2757
- changeTransactionState: (_context, resource, { transactionId, state }) => {
2758
- const index = resource.transactions.findIndex(
2759
- (e) => e.id === transactionId
2760
- );
2761
- const updatedTransaction = {
2762
- ...resource.transactions[index],
2763
- state
2764
- };
2765
- resource.transactions[index] = updatedTransaction;
2255
+ setOrderNumber: (context, resource, { orderNumber }) => {
2256
+ resource.orderNumber = orderNumber;
2766
2257
  },
2767
- transitionState: (context, resource, { state }) => {
2768
- const stateObj = this._storage.getByResourceIdentifier(
2258
+ setShippingAddress: (context, resource, { address }) => {
2259
+ resource.shippingAddress = address;
2260
+ },
2261
+ setStore: (context, resource, { store }) => {
2262
+ if (!store)
2263
+ return;
2264
+ const resolvedType = this._storage.getByResourceIdentifier(
2769
2265
  context.projectKey,
2770
- state
2266
+ store
2771
2267
  );
2772
- if (!stateObj) {
2773
- throw new Error(`State ${state} not found`);
2268
+ if (!resolvedType) {
2269
+ throw new Error(`No store found with key=${store.key}`);
2774
2270
  }
2775
- resource.paymentStatus.state = {
2776
- typeId: "state",
2777
- id: stateObj.id,
2778
- obj: stateObj
2271
+ const storeReference = resolvedType;
2272
+ resource.store = {
2273
+ typeId: "store",
2274
+ key: storeReference.key
2779
2275
  };
2780
2276
  }
2781
2277
  };
2782
2278
  }
2783
2279
  getTypeId() {
2784
- return "payment";
2280
+ return "order";
2785
2281
  }
2786
2282
  create(context, draft) {
2283
+ (0, import_assert2.default)(draft.cart, "draft.cart is missing");
2284
+ return this.createFromCart(
2285
+ context,
2286
+ {
2287
+ id: draft.cart.id,
2288
+ typeId: "cart"
2289
+ },
2290
+ draft.orderNumber
2291
+ );
2292
+ }
2293
+ createFromCart(context, cartReference, orderNumber) {
2294
+ const cart = this._storage.getByResourceIdentifier(
2295
+ context.projectKey,
2296
+ cartReference
2297
+ );
2298
+ if (!cart) {
2299
+ throw new Error("Cannot find cart");
2300
+ }
2787
2301
  const resource = {
2788
2302
  ...getBaseResourceProperties(),
2789
- amountPlanned: createTypedMoney(draft.amountPlanned),
2790
- paymentMethodInfo: draft.paymentMethodInfo,
2791
- paymentStatus: draft.paymentStatus ? {
2792
- ...draft.paymentStatus,
2793
- state: draft.paymentStatus.state ? getReferenceFromResourceIdentifier(
2794
- draft.paymentStatus.state,
2795
- context.projectKey,
2796
- this._storage
2797
- ) : void 0
2798
- } : {},
2799
- transactions: (draft.transactions || []).map(
2800
- (t) => this.transactionFromTransactionDraft(t, context)
2303
+ orderNumber,
2304
+ cart: cartReference,
2305
+ orderState: "Open",
2306
+ lineItems: [],
2307
+ customLineItems: [],
2308
+ totalPrice: cart.totalPrice,
2309
+ refusedGifts: [],
2310
+ origin: "Customer",
2311
+ syncInfo: [],
2312
+ store: context.storeKey ? {
2313
+ key: context.storeKey,
2314
+ typeId: "store"
2315
+ } : void 0,
2316
+ lastMessageSequenceNumber: 0
2317
+ };
2318
+ this.saveNew(context, resource);
2319
+ return resource;
2320
+ }
2321
+ import(context, draft) {
2322
+ var _a, _b;
2323
+ (0, import_assert2.default)(this, "OrderRepository not valid");
2324
+ const resource = {
2325
+ ...getBaseResourceProperties(),
2326
+ billingAddress: draft.billingAddress,
2327
+ shippingAddress: draft.shippingAddress,
2328
+ custom: createCustomFields(
2329
+ draft.custom,
2330
+ context.projectKey,
2331
+ this._storage
2801
2332
  ),
2802
- interfaceInteractions: (draft.interfaceInteractions || []).map(
2803
- (interaction) => createCustomFields(interaction, context.projectKey, this._storage)
2333
+ customerEmail: draft.customerEmail,
2334
+ lastMessageSequenceNumber: 0,
2335
+ orderNumber: draft.orderNumber,
2336
+ orderState: draft.orderState || "Open",
2337
+ origin: draft.origin || "Customer",
2338
+ paymentState: draft.paymentState,
2339
+ refusedGifts: [],
2340
+ store: resolveStoreReference(
2341
+ draft.store,
2342
+ context.projectKey,
2343
+ this._storage
2344
+ ),
2345
+ syncInfo: [],
2346
+ lineItems: ((_a = draft.lineItems) == null ? void 0 : _a.map(
2347
+ (item) => this.lineItemFromImportDraft.bind(this)(context, item)
2348
+ )) || [],
2349
+ customLineItems: ((_b = draft.customLineItems) == null ? void 0 : _b.map(
2350
+ (item) => this.customLineItemFromImportDraft.bind(this)(context, item)
2351
+ )) || [],
2352
+ totalPrice: {
2353
+ type: "centPrecision",
2354
+ ...draft.totalPrice,
2355
+ fractionDigits: 2
2356
+ }
2357
+ };
2358
+ this.saveNew(context, resource);
2359
+ return resource;
2360
+ }
2361
+ lineItemFromImportDraft(context, draft) {
2362
+ let product;
2363
+ let variant;
2364
+ if (draft.variant.sku) {
2365
+ variant = {
2366
+ id: 0,
2367
+ sku: draft.variant.sku
2368
+ };
2369
+ const items = this._storage.query(context.projectKey, "product", {
2370
+ where: [
2371
+ `masterData(current(masterVariant(sku="${draft.variant.sku}"))) or masterData(current(variants(sku="${draft.variant.sku}")))`
2372
+ ]
2373
+ });
2374
+ if (items.count !== 1) {
2375
+ throw new CommercetoolsError({
2376
+ code: "General",
2377
+ message: `A product containing a variant with SKU '${draft.variant.sku}' not found.`
2378
+ });
2379
+ }
2380
+ product = items.results[0];
2381
+ if (product.masterData.current.masterVariant.sku === draft.variant.sku) {
2382
+ variant = product.masterData.current.masterVariant;
2383
+ } else {
2384
+ variant = product.masterData.current.variants.find(
2385
+ (v) => v.sku === draft.variant.sku
2386
+ );
2387
+ }
2388
+ if (!variant) {
2389
+ throw new Error("Internal state error");
2390
+ }
2391
+ } else {
2392
+ throw new Error("No product found");
2393
+ }
2394
+ const lineItem = {
2395
+ ...getBaseResourceProperties(),
2396
+ custom: createCustomFields(
2397
+ draft.custom,
2398
+ context.projectKey,
2399
+ this._storage
2804
2400
  ),
2401
+ discountedPricePerQuantity: [],
2402
+ lineItemMode: "Standard",
2403
+ name: draft.name,
2404
+ price: createPrice(draft.price),
2405
+ priceMode: "Platform",
2406
+ productId: product.id,
2407
+ productType: product.productType,
2408
+ quantity: draft.quantity,
2409
+ state: draft.state || [],
2410
+ taxRate: draft.taxRate,
2411
+ totalPrice: createTypedMoney(draft.price.value),
2412
+ variant: {
2413
+ id: variant.id,
2414
+ sku: variant.sku,
2415
+ price: createPrice(draft.price)
2416
+ }
2417
+ };
2418
+ return lineItem;
2419
+ }
2420
+ customLineItemFromImportDraft(context, draft) {
2421
+ const lineItem = {
2422
+ ...getBaseResourceProperties(),
2805
2423
  custom: createCustomFields(
2806
2424
  draft.custom,
2807
2425
  context.projectKey,
2808
2426
  this._storage
2809
- )
2427
+ ),
2428
+ discountedPricePerQuantity: [],
2429
+ money: createTypedMoney(draft.money),
2430
+ name: draft.name,
2431
+ quantity: draft.quantity,
2432
+ slug: draft.slug,
2433
+ state: [],
2434
+ totalPrice: createTypedMoney(draft.money)
2810
2435
  };
2811
- this.save(context, resource);
2812
- return resource;
2436
+ return lineItem;
2437
+ }
2438
+ getWithOrderNumber(context, orderNumber, params = {}) {
2439
+ const result = this._storage.query(context.projectKey, this.getTypeId(), {
2440
+ ...params,
2441
+ where: [`orderNumber="${orderNumber}"`]
2442
+ });
2443
+ if (result.count === 1) {
2444
+ return result.results[0];
2445
+ }
2446
+ if (result.count > 1) {
2447
+ throw new Error("Duplicate order numbers");
2448
+ }
2449
+ return;
2813
2450
  }
2814
2451
  };
2815
2452
 
2816
- // src/services/my-payment.ts
2817
- var MyPaymentService = class extends AbstractService {
2818
- constructor(parent, storage) {
2819
- super(parent);
2820
- this.repository = new PaymentRepository(storage);
2821
- }
2822
- getBasePath() {
2823
- return "me/payments";
2453
+ // src/repositories/my-order.ts
2454
+ var MyOrderRepository = class extends OrderRepository {
2455
+ create(context, draft) {
2456
+ (0, import_assert3.default)(draft.id, "draft.id is missing");
2457
+ const cartIdentifier = {
2458
+ id: draft.id,
2459
+ typeId: "cart"
2460
+ };
2461
+ return this.createFromCart(context, cartIdentifier);
2824
2462
  }
2825
2463
  };
2826
2464
 
2827
- // src/services/order.ts
2828
- var OrderService = class extends AbstractService {
2829
- constructor(parent, storage) {
2830
- super(parent);
2831
- this.repository = new OrderRepository(storage);
2465
+ // src/repositories/payment.ts
2466
+ var import_uuid5 = require("uuid");
2467
+ var PaymentRepository = class extends AbstractResourceRepository {
2468
+ constructor() {
2469
+ super(...arguments);
2470
+ this.transactionFromTransactionDraft = (draft, context) => ({
2471
+ ...draft,
2472
+ id: (0, import_uuid5.v4)(),
2473
+ amount: createTypedMoney(draft.amount),
2474
+ custom: createCustomFields(draft.custom, context.projectKey, this._storage)
2475
+ });
2476
+ this.actions = {
2477
+ setCustomField: (context, resource, { name, value }) => {
2478
+ if (!resource.custom) {
2479
+ throw new Error("Resource has no custom field");
2480
+ }
2481
+ resource.custom.fields[name] = value;
2482
+ },
2483
+ setCustomType: (context, resource, { type, fields }) => {
2484
+ if (!type) {
2485
+ resource.custom = void 0;
2486
+ } else {
2487
+ const resolvedType = this._storage.getByResourceIdentifier(
2488
+ context.projectKey,
2489
+ type
2490
+ );
2491
+ if (!resolvedType) {
2492
+ throw new Error(`Type ${type} not found`);
2493
+ }
2494
+ resource.custom = {
2495
+ type: {
2496
+ typeId: "type",
2497
+ id: resolvedType.id
2498
+ },
2499
+ fields: fields || []
2500
+ };
2501
+ }
2502
+ },
2503
+ addTransaction: (context, resource, { transaction }) => {
2504
+ resource.transactions = [
2505
+ ...resource.transactions,
2506
+ this.transactionFromTransactionDraft(transaction, context)
2507
+ ];
2508
+ },
2509
+ changeTransactionState: (_context, resource, { transactionId, state }) => {
2510
+ const index = resource.transactions.findIndex(
2511
+ (e) => e.id === transactionId
2512
+ );
2513
+ const updatedTransaction = {
2514
+ ...resource.transactions[index],
2515
+ state
2516
+ };
2517
+ resource.transactions[index] = updatedTransaction;
2518
+ },
2519
+ transitionState: (context, resource, { state }) => {
2520
+ const stateObj = this._storage.getByResourceIdentifier(
2521
+ context.projectKey,
2522
+ state
2523
+ );
2524
+ if (!stateObj) {
2525
+ throw new Error(`State ${state} not found`);
2526
+ }
2527
+ resource.paymentStatus.state = {
2528
+ typeId: "state",
2529
+ id: stateObj.id,
2530
+ obj: stateObj
2531
+ };
2532
+ }
2533
+ };
2832
2534
  }
2833
- getBasePath() {
2834
- return "orders";
2535
+ getTypeId() {
2536
+ return "payment";
2835
2537
  }
2836
- extraRoutes(router) {
2837
- router.post("/import", this.import.bind(this));
2838
- router.get("/order-number=:orderNumber", this.getWithOrderNumber.bind(this));
2538
+ create(context, draft) {
2539
+ const resource = {
2540
+ ...getBaseResourceProperties(),
2541
+ amountPlanned: createTypedMoney(draft.amountPlanned),
2542
+ paymentMethodInfo: draft.paymentMethodInfo,
2543
+ paymentStatus: draft.paymentStatus ? {
2544
+ ...draft.paymentStatus,
2545
+ state: draft.paymentStatus.state ? getReferenceFromResourceIdentifier(
2546
+ draft.paymentStatus.state,
2547
+ context.projectKey,
2548
+ this._storage
2549
+ ) : void 0
2550
+ } : {},
2551
+ transactions: (draft.transactions || []).map(
2552
+ (t) => this.transactionFromTransactionDraft(t, context)
2553
+ ),
2554
+ interfaceInteractions: (draft.interfaceInteractions || []).map(
2555
+ (interaction) => createCustomFields(interaction, context.projectKey, this._storage)
2556
+ ),
2557
+ custom: createCustomFields(
2558
+ draft.custom,
2559
+ context.projectKey,
2560
+ this._storage
2561
+ )
2562
+ };
2563
+ this.saveNew(context, resource);
2564
+ return resource;
2839
2565
  }
2840
- import(request, response) {
2841
- const importDraft = request.body;
2842
- const resource = this.repository.import(
2843
- getRepositoryContext(request),
2844
- importDraft
2845
- );
2846
- return response.status(200).send(resource);
2566
+ };
2567
+
2568
+ // src/repositories/product.ts
2569
+ var import_uuid6 = require("uuid");
2570
+ var import_deep_equal2 = __toESM(require("deep-equal"));
2571
+ var ProductRepository = class extends AbstractResourceRepository {
2572
+ constructor() {
2573
+ super(...arguments);
2574
+ this.actions = {
2575
+ publish: (context, resource, { scope }) => {
2576
+ resource.masterData.current = resource.masterData.staged;
2577
+ resource.masterData.published = true;
2578
+ checkForStagedChanges(resource);
2579
+ },
2580
+ unpublish: (context, resource) => {
2581
+ resource.masterData.published = false;
2582
+ checkForStagedChanges(resource);
2583
+ },
2584
+ setAttribute: (context, resource, { variantId, sku, name, value, staged }) => {
2585
+ const setAttr = (data) => {
2586
+ const { variant, isMasterVariant, variantIndex } = getVariant(
2587
+ data,
2588
+ variantId,
2589
+ sku
2590
+ );
2591
+ if (!variant) {
2592
+ throw new Error(
2593
+ `Variant with id ${variantId} or sku ${sku} not found on product ${resource.id}`
2594
+ );
2595
+ }
2596
+ if (!variant.attributes) {
2597
+ variant.attributes = [];
2598
+ }
2599
+ const existingAttr = variant.attributes.find(
2600
+ (attr) => attr.name === name
2601
+ );
2602
+ if (existingAttr) {
2603
+ existingAttr.value = value;
2604
+ } else {
2605
+ variant.attributes.push({
2606
+ name,
2607
+ value
2608
+ });
2609
+ }
2610
+ if (isMasterVariant) {
2611
+ data.masterVariant = variant;
2612
+ } else {
2613
+ data.variants[variantIndex] = variant;
2614
+ }
2615
+ };
2616
+ const onlyStaged = staged !== void 0 ? staged : true;
2617
+ setAttr(resource.masterData.staged);
2618
+ if (!onlyStaged) {
2619
+ setAttr(resource.masterData.current);
2620
+ }
2621
+ checkForStagedChanges(resource);
2622
+ return resource;
2623
+ },
2624
+ "setDescription": (context, resource, { description, staged }) => {
2625
+ const onlyStaged = staged !== void 0 ? staged : true;
2626
+ resource.masterData.staged.description = description;
2627
+ if (!onlyStaged) {
2628
+ resource.masterData.current.description = description;
2629
+ }
2630
+ checkForStagedChanges(resource);
2631
+ return resource;
2632
+ },
2633
+ "setKey": (context, resource, { key }) => {
2634
+ resource.key = key;
2635
+ return resource;
2636
+ }
2637
+ };
2847
2638
  }
2848
- getWithOrderNumber(request, response) {
2849
- const resource = this.repository.getWithOrderNumber(
2850
- getRepositoryContext(request),
2851
- request.params.orderNumber,
2852
- request.query
2853
- );
2854
- if (resource) {
2855
- return response.status(200).send(resource);
2639
+ getTypeId() {
2640
+ return "product";
2641
+ }
2642
+ create(context, draft) {
2643
+ var _a;
2644
+ if (!draft.masterVariant) {
2645
+ throw new Error("Missing master variant");
2856
2646
  }
2857
- return response.status(404).send("Not found");
2647
+ let productType = void 0;
2648
+ try {
2649
+ productType = getReferenceFromResourceIdentifier(
2650
+ draft.productType,
2651
+ context.projectKey,
2652
+ this._storage
2653
+ );
2654
+ } catch (err) {
2655
+ console.warn(
2656
+ `Error resolving product-type '${draft.productType.id}'. This will be throw an error in later releases.`
2657
+ );
2658
+ productType = {
2659
+ typeId: "product-type",
2660
+ id: draft.productType.id || ""
2661
+ };
2662
+ }
2663
+ const productData = {
2664
+ name: draft.name,
2665
+ slug: draft.slug,
2666
+ categories: [],
2667
+ masterVariant: variantFromDraft(1, draft.masterVariant),
2668
+ variants: ((_a = draft.variants) == null ? void 0 : _a.map(
2669
+ (variant, index) => variantFromDraft(index + 2, variant)
2670
+ )) ?? [],
2671
+ searchKeywords: draft.searchKeywords ?? {}
2672
+ };
2673
+ const resource = {
2674
+ ...getBaseResourceProperties(),
2675
+ key: draft.key,
2676
+ productType,
2677
+ masterData: {
2678
+ current: productData,
2679
+ staged: productData,
2680
+ hasStagedChanges: false,
2681
+ published: draft.publish ?? false
2682
+ }
2683
+ };
2684
+ this.saveNew(context, resource);
2685
+ return resource;
2858
2686
  }
2859
2687
  };
2860
-
2861
- // src/services/payment.ts
2862
- var PaymentService = class extends AbstractService {
2863
- constructor(parent, storage) {
2864
- super(parent);
2865
- this.repository = new PaymentRepository(storage);
2688
+ var checkForStagedChanges = (product) => {
2689
+ if (!product.masterData.staged) {
2690
+ product.masterData.staged = product.masterData.current;
2866
2691
  }
2867
- getBasePath() {
2868
- return "payments";
2692
+ if ((0, import_deep_equal2.default)(product.masterData.current, product.masterData.staged)) {
2693
+ product.masterData.hasStagedChanges = false;
2694
+ } else {
2695
+ product.masterData.hasStagedChanges = true;
2869
2696
  }
2870
2697
  };
2698
+ var getVariant = (productData, variantId, sku) => {
2699
+ const variants = [productData.masterVariant, ...productData.variants];
2700
+ const foundVariant = variants.find((variant) => {
2701
+ if (variantId) {
2702
+ return variant.id === variantId;
2703
+ }
2704
+ if (sku) {
2705
+ return variant.sku === sku;
2706
+ }
2707
+ return false;
2708
+ });
2709
+ const isMasterVariant = foundVariant === productData.masterVariant;
2710
+ return {
2711
+ variant: foundVariant,
2712
+ isMasterVariant,
2713
+ variantIndex: !isMasterVariant && foundVariant ? productData.variants.indexOf(foundVariant) : -1
2714
+ };
2715
+ };
2716
+ var variantFromDraft = (variantId, variant) => {
2717
+ var _a;
2718
+ return {
2719
+ id: variantId,
2720
+ sku: variant == null ? void 0 : variant.sku,
2721
+ attributes: (variant == null ? void 0 : variant.attributes) ?? [],
2722
+ prices: (_a = variant == null ? void 0 : variant.prices) == null ? void 0 : _a.map(priceFromDraft),
2723
+ assets: [],
2724
+ images: []
2725
+ };
2726
+ };
2727
+ var priceFromDraft = (draft) => ({
2728
+ id: (0, import_uuid6.v4)(),
2729
+ value: {
2730
+ currencyCode: draft.value.currencyCode,
2731
+ centAmount: draft.value.centAmount,
2732
+ fractionDigits: 2,
2733
+ type: "centPrecision"
2734
+ }
2735
+ });
2871
2736
 
2872
2737
  // src/repositories/product-discount.ts
2873
2738
  var ProductDiscountRepository = class extends AbstractResourceRepository {
@@ -2928,7 +2793,7 @@ var ProductDiscountRepository = class extends AbstractResourceRepository {
2928
2793
  validUntil: draft.validUntil,
2929
2794
  references: []
2930
2795
  };
2931
- this.save(context, resource);
2796
+ this.saveNew(context, resource);
2932
2797
  return resource;
2933
2798
  }
2934
2799
  transformValueDraft(value) {
@@ -2965,52 +2830,23 @@ var ProductDiscountRepository = class extends AbstractResourceRepository {
2965
2830
  }
2966
2831
  };
2967
2832
 
2968
- // src/services/product-discount.ts
2969
- var ProductDiscountService = class extends AbstractService {
2970
- constructor(parent, storage) {
2971
- super(parent);
2972
- this.repository = new ProductDiscountRepository(storage);
2973
- }
2974
- getBasePath() {
2975
- return "product-discounts";
2976
- }
2977
- extraRoutes(router) {
2978
- router.get("/key=:key", this.getWithKey.bind(this));
2979
- }
2980
- getWithKey(request, response) {
2981
- const resource = this.repository.getWithKey(
2982
- getRepositoryContext(request),
2983
- request.params.key
2984
- );
2985
- if (resource) {
2986
- return response.status(200).send(resource);
2987
- }
2988
- return response.status(404).send("Not found");
2989
- }
2990
- };
2991
-
2992
- // src/lib/projectionSearchFilter.ts
2993
- var import_perplex2 = __toESM(require("perplex"));
2994
- var import_pratt2 = __toESM(require("pratt"));
2995
- var parseFilterExpression = (filter, staged) => {
2996
- const exprFunc = generateMatchFunc2(filter);
2997
- const [source] = filter.split(":", 1);
2998
- if (source.startsWith("variants.")) {
2999
- return filterVariants(source, staged, exprFunc);
2833
+ // src/lib/projectionSearchFilter.ts
2834
+ var import_perplex2 = __toESM(require("perplex"));
2835
+ var import_pratt2 = __toESM(require("pratt"));
2836
+ var parseFilterExpression = (filter) => {
2837
+ const exprFunc = generateMatchFunc2(filter);
2838
+ const [source] = filter.split(":", 1);
2839
+ if (source.startsWith("variants.")) {
2840
+ return filterVariants(source, exprFunc);
3000
2841
  }
3001
2842
  return filterProduct(source, exprFunc);
3002
2843
  };
3003
- var getLexer2 = (value) => {
3004
- return new import_perplex2.default(value).token("MISSING", /missing(?![-_a-z0-9]+)/i).token("EXISTS", /exists(?![-_a-z0-9]+)/i).token("RANGE", /range(?![-_a-z0-9]+)/i).token("TO", /to(?![-_a-z0-9]+)/i).token("IDENTIFIER", /[-_\.a-z]+/i).token("FLOAT", /\d+\.\d+/).token("INT", /\d+/).token("STRING", /"((?:\\.|[^"\\])*)"/).token("STRING", /'((?:\\.|[^'\\])*)'/).token("COMMA", ",").token("STAR", "*").token("(", "(").token(":", ":").token(")", ")").token('"', '"').token("WS", /\s+/, true);
3005
- };
2844
+ var getLexer2 = (value) => new import_perplex2.default(value).token("MISSING", /missing(?![-_a-z0-9]+)/i).token("EXISTS", /exists(?![-_a-z0-9]+)/i).token("RANGE", /range(?![-_a-z0-9]+)/i).token("TO", /to(?![-_a-z0-9]+)/i).token("IDENTIFIER", /[-_.a-z]+/i).token("FLOAT", /\d+\.\d+/).token("INT", /\d+/).token("STRING", /"((?:\\.|[^"\\])*)"/).token("STRING", /'((?:\\.|[^'\\])*)'/).token("COMMA", ",").token("STAR", "*").token("(", "(").token(":", ":").token(")", ")").token('"', '"').token("WS", /\s+/, true);
3006
2845
  var parseFilter = (filter) => {
3007
2846
  const lexer = getLexer2(filter);
3008
- const parser = new import_pratt2.default(lexer).builder().nud("IDENTIFIER", 100, (t) => {
3009
- return t.token.match;
3010
- }).led(":", 100, ({ left, bp }) => {
3011
- let parsed = parser.parse({ terminals: [bp - 1] });
3012
- let expressions;
3013
- expressions = !Array.isArray(parsed) ? [parsed] : parsed;
2847
+ const parser = new import_pratt2.default(lexer).builder().nud("IDENTIFIER", 100, (t) => t.token.match).led(":", 100, ({ left, bp }) => {
2848
+ const parsed = parser.parse({ terminals: [bp - 1] });
2849
+ const expressions = !Array.isArray(parsed) ? [parsed] : parsed;
3014
2850
  const unique = new Set(expressions.map((expr) => expr.type));
3015
2851
  if (unique.size > 1) {
3016
2852
  throw new Error("Invalid expression");
@@ -3025,9 +2861,7 @@ var parseFilter = (filter) => {
3025
2861
  }
3026
2862
  return {
3027
2863
  type: "FilterExpression",
3028
- match: (obj) => {
3029
- return obj === e.value;
3030
- }
2864
+ match: (obj) => obj === e.value
3031
2865
  };
3032
2866
  })
3033
2867
  };
@@ -3037,39 +2871,41 @@ var parseFilter = (filter) => {
3037
2871
  type: expressions[0].type,
3038
2872
  children: expressions
3039
2873
  };
3040
- }).nud("STRING", 20, (t) => {
3041
- return {
2874
+ }).nud(
2875
+ "STRING",
2876
+ 20,
2877
+ (t) => ({
3042
2878
  type: "Symbol",
3043
2879
  kind: "string",
3044
2880
  value: t.token.groups[1]
3045
- };
3046
- }).nud("INT", 5, (t) => {
3047
- return {
2881
+ })
2882
+ ).nud(
2883
+ "INT",
2884
+ 5,
2885
+ (t) => ({
3048
2886
  type: "Symbol",
3049
2887
  kind: "int",
3050
2888
  value: parseInt(t.token.match, 10)
3051
- };
3052
- }).nud("STAR", 5, (t) => {
3053
- return {
3054
- type: "Symbol",
3055
- kind: "any",
3056
- value: null
3057
- };
3058
- }).nud("EXISTS", 10, ({ bp }) => {
3059
- return {
2889
+ })
2890
+ ).nud("STAR", 5, (_) => ({
2891
+ type: "Symbol",
2892
+ kind: "any",
2893
+ value: null
2894
+ })).nud(
2895
+ "EXISTS",
2896
+ 10,
2897
+ ({ bp }) => ({
3060
2898
  type: "FilterExpression",
3061
- match: (obj) => {
3062
- return obj !== void 0;
3063
- }
3064
- };
3065
- }).nud("MISSING", 10, ({ bp }) => {
3066
- return {
2899
+ match: (obj) => obj !== void 0
2900
+ })
2901
+ ).nud(
2902
+ "MISSING",
2903
+ 10,
2904
+ ({ bp }) => ({
3067
2905
  type: "FilterExpression",
3068
- match: (obj) => {
3069
- return obj === void 0;
3070
- }
3071
- };
3072
- }).led("COMMA", 200, ({ left, token, bp }) => {
2906
+ match: (obj) => obj === void 0
2907
+ })
2908
+ ).led("COMMA", 200, ({ left, token, bp }) => {
3073
2909
  const expr = parser.parse({ terminals: [bp - 1] });
3074
2910
  if (Array.isArray(expr)) {
3075
2911
  return [left, ...expr];
@@ -3094,21 +2930,13 @@ var parseFilter = (filter) => {
3094
2930
  return ranges.map((range) => {
3095
2931
  let func = void 0;
3096
2932
  if (range.start !== null && range.stop !== null) {
3097
- func = (obj) => {
3098
- return obj >= range.start && obj <= range.stop;
3099
- };
2933
+ func = (obj) => obj >= range.start && obj <= range.stop;
3100
2934
  } else if (range.start === null && range.stop !== null) {
3101
- func = (obj) => {
3102
- return obj <= range.stop;
3103
- };
2935
+ func = (obj) => obj <= range.stop;
3104
2936
  } else if (range.start !== null && range.stop === null) {
3105
- func = (obj) => {
3106
- return obj >= range.start;
3107
- };
2937
+ func = (obj) => obj >= range.start;
3108
2938
  } else {
3109
- func = (obj) => {
3110
- return true;
3111
- };
2939
+ func = (obj) => true;
3112
2940
  }
3113
2941
  return {
3114
2942
  type: "RangeExpression",
@@ -3123,8 +2951,6 @@ var parseFilter = (filter) => {
3123
2951
  var generateMatchFunc2 = (filter) => {
3124
2952
  const result = parseFilter(filter);
3125
2953
  if (!result) {
3126
- const lines = filter.split("\n");
3127
- const column = lines[lines.length - 1].length;
3128
2954
  throw new Error(`Syntax error while parsing '${filter}'.`);
3129
2955
  }
3130
2956
  if (result.type == "TermExpression") {
@@ -3145,29 +2971,25 @@ var generateFacetFunc = (filter) => {
3145
2971
  }
3146
2972
  return parseFilter(filter);
3147
2973
  };
3148
- var filterProduct = (source, exprFunc) => {
3149
- return (p, markMatchingVariants) => {
3150
- const value = nestedLookup(p, source);
3151
- return exprFunc(value);
3152
- };
2974
+ var filterProduct = (source, exprFunc) => (p, markMatchingVariants) => {
2975
+ const value = nestedLookup(p, source);
2976
+ return exprFunc(value);
3153
2977
  };
3154
- var filterVariants = (source, staged, exprFunc) => {
3155
- return (p, markMatchingVariants) => {
3156
- const [, ...paths] = source.split(".");
3157
- const path = paths.join(".");
3158
- const variants = getVariants(p, staged);
3159
- for (const variant of variants) {
3160
- const value = resolveVariantValue(variant, path);
3161
- if (exprFunc(value)) {
3162
- if (markMatchingVariants) {
3163
- variants.forEach((v) => v.isMatchingVariant = false);
3164
- variant.isMatchingVariant = true;
3165
- }
3166
- return true;
2978
+ var filterVariants = (source, exprFunc) => (p, markMatchingVariants) => {
2979
+ const [, ...paths] = source.split(".");
2980
+ const path = paths.join(".");
2981
+ const variants = getVariants(p);
2982
+ for (const variant of variants) {
2983
+ const value = resolveVariantValue(variant, path);
2984
+ if (exprFunc(value)) {
2985
+ if (markMatchingVariants) {
2986
+ variants.forEach((v) => v.isMatchingVariant = false);
2987
+ variant.isMatchingVariant = true;
3167
2988
  }
2989
+ return true;
3168
2990
  }
3169
- return false;
3170
- };
2991
+ }
2992
+ return false;
3171
2993
  };
3172
2994
  var resolveVariantValue = (obj, path) => {
3173
2995
  if (path === void 0) {
@@ -3192,27 +3014,22 @@ var resolveVariantValue = (obj, path) => {
3192
3014
  }
3193
3015
  return nestedLookup(obj, path);
3194
3016
  };
3195
- var getVariants = (p, staged) => {
3196
- var _a, _b, _c, _d;
3197
- return [
3198
- staged ? (_a = p.masterData.staged) == null ? void 0 : _a.masterVariant : (_b = p.masterData.current) == null ? void 0 : _b.masterVariant,
3199
- ...staged ? (_c = p.masterData.staged) == null ? void 0 : _c.variants : (_d = p.masterData.current) == null ? void 0 : _d.variants
3200
- ];
3201
- };
3017
+ var getVariants = (p) => [
3018
+ p.masterVariant,
3019
+ ...p.variants ?? []
3020
+ ];
3202
3021
 
3203
3022
  // src/priceSelector.ts
3204
3023
  var applyPriceSelector = (products, selector) => {
3205
- var _a, _b, _c, _d, _e;
3024
+ var _a;
3206
3025
  validatePriceSelector(selector);
3207
3026
  for (const product of products) {
3208
3027
  const variants = [
3209
- (_a = product.masterData.staged) == null ? void 0 : _a.masterVariant,
3210
- ...((_b = product.masterData.staged) == null ? void 0 : _b.variants) || [],
3211
- (_c = product.masterData.current) == null ? void 0 : _c.masterVariant,
3212
- ...((_d = product.masterData.current) == null ? void 0 : _d.variants) || []
3028
+ product.masterVariant,
3029
+ ...product.variants ?? []
3213
3030
  ].filter((x) => x != void 0);
3214
3031
  for (const variant of variants) {
3215
- const scopedPrices = ((_e = variant.prices) == null ? void 0 : _e.filter((p) => priceSelectorFilter(p, selector))) ?? [];
3032
+ const scopedPrices = ((_a = variant.prices) == null ? void 0 : _a.filter((p) => priceSelectorFilter(p, selector))) ?? [];
3216
3033
  if (scopedPrices.length > 0) {
3217
3034
  const price = scopedPrices[0];
3218
3035
  variant.scopedPriceDiscounted = false;
@@ -3258,8 +3075,13 @@ var ProductProjectionSearch = class {
3258
3075
  this._storage = storage;
3259
3076
  }
3260
3077
  search(projectKey, params) {
3261
- let resources = this._storage.all(projectKey, "product").map((r) => JSON.parse(JSON.stringify(r)));
3262
- let markMatchingVariant = params.markMatchingVariants ?? false;
3078
+ let resources = this._storage.all(projectKey, "product").map((r) => this.transform(r, params.staged ?? false)).filter((p) => p !== null).filter((p) => {
3079
+ if (!params.staged) {
3080
+ return p.published;
3081
+ }
3082
+ return true;
3083
+ });
3084
+ const markMatchingVariant = params.markMatchingVariants ?? false;
3263
3085
  applyPriceSelector(resources, {
3264
3086
  country: params.priceCountry,
3265
3087
  channel: params.priceChannel,
@@ -3268,13 +3090,12 @@ var ProductProjectionSearch = class {
3268
3090
  });
3269
3091
  if (params.filter) {
3270
3092
  try {
3271
- const filters = params.filter.map(
3272
- (f) => parseFilterExpression(f, params.staged ?? false)
3273
- );
3093
+ const filters = params.filter.map(parseFilterExpression);
3274
3094
  resources = resources.filter(
3275
3095
  (resource) => filters.every((f) => f(resource, markMatchingVariant))
3276
3096
  );
3277
3097
  } catch (err) {
3098
+ console.error(err);
3278
3099
  throw new CommercetoolsError(
3279
3100
  {
3280
3101
  code: "InvalidInput",
@@ -3287,9 +3108,7 @@ var ProductProjectionSearch = class {
3287
3108
  const facets = this.getFacets(params, resources);
3288
3109
  if (params["filter.query"]) {
3289
3110
  try {
3290
- const filters = params["filter.query"].map(
3291
- (f) => parseFilterExpression(f, params.staged ?? false)
3292
- );
3111
+ const filters = params["filter.query"].map(parseFilterExpression);
3293
3112
  resources = resources.filter(
3294
3113
  (resource) => filters.every((f) => f(resource, markMatchingVariant))
3295
3114
  );
@@ -3303,26 +3122,28 @@ var ProductProjectionSearch = class {
3303
3122
  );
3304
3123
  }
3305
3124
  }
3306
- const totalResources = resources.length;
3307
- const offset = params.offset || 0;
3308
- const limit = params.limit || 20;
3309
- resources = resources.slice(offset, offset + limit);
3310
3125
  if (params.expand !== void 0) {
3311
- resources = resources.map((resource) => {
3312
- return this._storage.expand(projectKey, resource, params.expand);
3313
- });
3126
+ resources = resources.map(
3127
+ (resource) => this._storage.expand(projectKey, resource, params.expand)
3128
+ );
3314
3129
  }
3130
+ const totalResults = resources.length;
3131
+ const offset = params.offset || 0;
3132
+ const limit = params.limit || 20;
3133
+ const results = resources.slice(offset, offset + limit);
3315
3134
  return {
3316
- count: totalResources,
3317
- total: resources.length,
3135
+ count: totalResults,
3136
+ total: results.length,
3318
3137
  offset,
3319
3138
  limit,
3320
- results: resources.map(this.transform),
3139
+ results,
3321
3140
  facets
3322
3141
  };
3323
3142
  }
3324
- transform(product) {
3325
- const obj = product.masterData.current;
3143
+ transform(product, staged) {
3144
+ const obj = !staged ? product.masterData.current : product.masterData.staged;
3145
+ if (!obj)
3146
+ return null;
3326
3147
  return {
3327
3148
  id: product.id,
3328
3149
  createdAt: product.createdAt,
@@ -3336,7 +3157,9 @@ var ProductProjectionSearch = class {
3336
3157
  categories: obj.categories,
3337
3158
  masterVariant: obj.masterVariant,
3338
3159
  variants: obj.variants,
3339
- productType: product.productType
3160
+ productType: product.productType,
3161
+ hasStagedChanges: product.masterData.hasStagedChanges,
3162
+ published: product.masterData.published
3340
3163
  };
3341
3164
  }
3342
3165
  getFacets(params, products) {
@@ -3347,28 +3170,26 @@ var ProductProjectionSearch = class {
3347
3170
  for (const facet of params.facet) {
3348
3171
  const expression = generateFacetFunc(facet);
3349
3172
  if (expression.type === "TermExpression") {
3350
- result[facet] = this.termFacet(expression.source, products, staged);
3173
+ result[facet] = this.termFacet(expression.source, products);
3351
3174
  }
3352
3175
  if (expression.type === "RangeExpression") {
3353
3176
  result[expression.source] = this.rangeFacet(
3354
3177
  expression.source,
3355
3178
  expression.children,
3356
- products,
3357
- staged
3179
+ products
3358
3180
  );
3359
3181
  }
3360
3182
  if (expression.type === "FilterExpression") {
3361
3183
  result[expression.source] = this.filterFacet(
3362
3184
  expression.source,
3363
3185
  expression.children,
3364
- products,
3365
- staged
3186
+ products
3366
3187
  );
3367
3188
  }
3368
3189
  }
3369
3190
  return result;
3370
3191
  }
3371
- termFacet(facet, products, staged) {
3192
+ termFacet(facet, products) {
3372
3193
  const result = {
3373
3194
  type: "terms",
3374
3195
  dataType: "text",
@@ -3380,7 +3201,7 @@ var ProductProjectionSearch = class {
3380
3201
  const terms = {};
3381
3202
  if (facet.startsWith("variants.")) {
3382
3203
  products.forEach((p) => {
3383
- const variants = getVariants(p, staged);
3204
+ const variants = getVariants(p);
3384
3205
  variants.forEach((v) => {
3385
3206
  result.total++;
3386
3207
  let value = resolveVariantValue(v, facet);
@@ -3413,11 +3234,11 @@ var ProductProjectionSearch = class {
3413
3234
  }
3414
3235
  return result;
3415
3236
  }
3416
- filterFacet(source, filters, products, staged) {
3237
+ filterFacet(source, filters, products) {
3417
3238
  let count = 0;
3418
3239
  if (source.startsWith("variants.")) {
3419
3240
  for (const p of products) {
3420
- for (const v of getVariants(p, staged)) {
3241
+ for (const v of getVariants(p)) {
3421
3242
  const val = resolveVariantValue(v, source);
3422
3243
  if (filters == null ? void 0 : filters.some((f) => f.match(val))) {
3423
3244
  count++;
@@ -3432,12 +3253,12 @@ var ProductProjectionSearch = class {
3432
3253
  count
3433
3254
  };
3434
3255
  }
3435
- rangeFacet(source, ranges, products, staged) {
3256
+ rangeFacet(source, ranges, products) {
3436
3257
  const counts = (ranges == null ? void 0 : ranges.map((range) => {
3437
3258
  if (source.startsWith("variants.")) {
3438
3259
  const values = [];
3439
3260
  for (const p of products) {
3440
- for (const v of getVariants(p, staged)) {
3261
+ for (const v of getVariants(p)) {
3441
3262
  const val = resolveVariantValue(v, source);
3442
3263
  if (val === void 0) {
3443
3264
  continue;
@@ -3508,210 +3329,24 @@ var ProductProjectionRepository = class extends AbstractResourceRepository {
3508
3329
  facet: QueryParamsAsArray(query.facet),
3509
3330
  offset: query.offset ? Number(query.offset) : void 0,
3510
3331
  limit: query.limit ? Number(query.limit) : void 0,
3511
- expand: QueryParamsAsArray(query.expand)
3332
+ expand: QueryParamsAsArray(query.expand),
3333
+ staged: query.staged === "true"
3512
3334
  });
3513
3335
  return results;
3514
3336
  }
3515
3337
  };
3516
3338
 
3517
- // src/services/product-projection.ts
3518
- var ProductProjectionService = class extends AbstractService {
3519
- constructor(parent, storage) {
3520
- super(parent);
3521
- this.repository = new ProductProjectionRepository(storage);
3522
- }
3523
- getBasePath() {
3524
- return "product-projections";
3525
- }
3526
- extraRoutes(router) {
3527
- router.get("/search", this.search.bind(this));
3528
- }
3529
- search(request, response) {
3530
- const resource = this.repository.search(
3531
- getRepositoryContext(request),
3532
- request.query
3533
- );
3534
- return response.status(200).send(resource);
3535
- }
3536
- };
3537
-
3538
- // src/repositories/product.ts
3539
- var import_uuid7 = require("uuid");
3540
- var ProductRepository = class extends AbstractResourceRepository {
3541
- constructor() {
3542
- super(...arguments);
3543
- this.actions = {
3544
- publish: (context, resource, { scope }) => {
3545
- if (resource.masterData.staged) {
3546
- resource.masterData.current = resource.masterData.staged;
3547
- resource.masterData.staged = void 0;
3548
- }
3549
- resource.masterData.hasStagedChanges = false;
3550
- resource.masterData.published = true;
3551
- },
3552
- setAttribute: (context, resource, { variantId, sku, name, value, staged }) => {
3553
- const isStaged = staged !== void 0 ? staged : false;
3554
- const productData = getProductData(resource, isStaged);
3555
- const { variant, isMasterVariant, variantIndex } = getVariant(
3556
- productData,
3557
- variantId,
3558
- sku
3559
- );
3560
- if (!variant) {
3561
- throw new Error(
3562
- `Variant with id ${variantId} or sku ${sku} not found on product ${resource.id}`
3563
- );
3564
- }
3565
- if (!variant.attributes) {
3566
- variant.attributes = [];
3567
- }
3568
- const existingAttr = variant.attributes.find((attr) => attr.name === name);
3569
- if (existingAttr) {
3570
- existingAttr.value = value;
3571
- } else {
3572
- variant.attributes.push({
3573
- name,
3574
- value
3575
- });
3576
- }
3577
- if (isStaged) {
3578
- resource.masterData.staged = productData;
3579
- if (isMasterVariant) {
3580
- resource.masterData.staged.masterVariant = variant;
3581
- } else {
3582
- resource.masterData.staged.variants[variantIndex] = variant;
3583
- }
3584
- resource.masterData.hasStagedChanges = true;
3585
- } else {
3586
- resource.masterData.current = productData;
3587
- if (isMasterVariant) {
3588
- resource.masterData.current.masterVariant = variant;
3589
- } else {
3590
- resource.masterData.current.variants[variantIndex] = variant;
3591
- }
3592
- }
3593
- }
3594
- };
3595
- }
3596
- getTypeId() {
3597
- return "product";
3598
- }
3599
- create(context, draft) {
3600
- var _a;
3601
- if (!draft.masterVariant) {
3602
- throw new Error("Missing master variant");
3603
- }
3604
- let productType = void 0;
3605
- try {
3606
- productType = getReferenceFromResourceIdentifier(
3607
- draft.productType,
3608
- context.projectKey,
3609
- this._storage
3610
- );
3611
- } catch (err) {
3612
- console.warn(
3613
- `Error resolving product-type '${draft.productType.id}'. This will be throw an error in later releases.`
3614
- );
3615
- productType = {
3616
- typeId: "product-type",
3617
- id: draft.productType.id || ""
3618
- };
3619
- }
3620
- const productData = {
3621
- name: draft.name,
3622
- slug: draft.slug,
3623
- categories: [],
3624
- masterVariant: variantFromDraft(1, draft.masterVariant),
3625
- variants: ((_a = draft.variants) == null ? void 0 : _a.map((variant, index) => {
3626
- return variantFromDraft(index + 2, variant);
3627
- })) ?? [],
3628
- searchKeywords: draft.searchKeywords
3629
- };
3630
- const resource = {
3631
- ...getBaseResourceProperties(),
3632
- productType,
3633
- masterData: {
3634
- current: draft.publish ? productData : void 0,
3635
- staged: draft.publish ? void 0 : productData,
3636
- hasStagedChanges: draft.publish ?? true,
3637
- published: draft.publish ?? false
3638
- }
3639
- };
3640
- this.save(context, resource);
3641
- return resource;
3642
- }
3643
- };
3644
- var getProductData = (product, staged) => {
3645
- if (!staged && product.masterData.current) {
3646
- return product.masterData.current;
3647
- }
3648
- return product.masterData.staged;
3649
- };
3650
- var getVariant = (productData, variantId, sku) => {
3651
- const variants = [productData.masterVariant, ...productData.variants];
3652
- const foundVariant = variants.find((variant) => {
3653
- if (variantId) {
3654
- return variant.id === variantId;
3655
- }
3656
- if (sku) {
3657
- return variant.sku === sku;
3658
- }
3659
- return false;
3660
- });
3661
- const isMasterVariant = foundVariant === productData.masterVariant;
3662
- return {
3663
- variant: foundVariant,
3664
- isMasterVariant,
3665
- variantIndex: !isMasterVariant && foundVariant ? productData.variants.indexOf(foundVariant) : -1
3666
- };
3667
- };
3668
- var variantFromDraft = (variantId, variant) => {
3669
- var _a;
3670
- return {
3671
- id: variantId,
3672
- sku: variant == null ? void 0 : variant.sku,
3673
- attributes: (variant == null ? void 0 : variant.attributes) ?? [],
3674
- prices: (_a = variant == null ? void 0 : variant.prices) == null ? void 0 : _a.map(priceFromDraft),
3675
- assets: [],
3676
- images: []
3677
- };
3678
- };
3679
- var priceFromDraft = (draft) => {
3680
- return {
3681
- id: (0, import_uuid7.v4)(),
3682
- value: {
3683
- currencyCode: draft.value.currencyCode,
3684
- centAmount: draft.value.centAmount,
3685
- fractionDigits: 2,
3686
- type: "centPrecision"
3687
- }
3688
- };
3689
- };
3690
-
3691
- // src/services/product.ts
3692
- var ProductService = class extends AbstractService {
3693
- constructor(parent, storage) {
3694
- super(parent);
3695
- this.repository = new ProductRepository(storage);
3696
- }
3697
- getBasePath() {
3698
- return "products";
3699
- }
3700
- };
3701
-
3702
3339
  // src/repositories/product-type.ts
3703
3340
  var ProductTypeRepository = class extends AbstractResourceRepository {
3704
3341
  constructor() {
3705
3342
  super(...arguments);
3706
- this.attributeDefinitionFromAttributeDefinitionDraft = (_context, draft) => {
3707
- return {
3708
- ...draft,
3709
- attributeConstraint: draft.attributeConstraint ?? "None",
3710
- inputHint: draft.inputHint ?? "SingleLine",
3711
- inputTip: draft.inputTip && Object.keys(draft.inputTip).length > 0 ? draft.inputTip : void 0,
3712
- isSearchable: draft.isSearchable ?? true
3713
- };
3714
- };
3343
+ this.attributeDefinitionFromAttributeDefinitionDraft = (_context, draft) => ({
3344
+ ...draft,
3345
+ attributeConstraint: draft.attributeConstraint ?? "None",
3346
+ inputHint: draft.inputHint ?? "SingleLine",
3347
+ inputTip: draft.inputTip && Object.keys(draft.inputTip).length > 0 ? draft.inputTip : void 0,
3348
+ isSearchable: draft.isSearchable ?? true
3349
+ });
3715
3350
  this.actions = {
3716
3351
  changeLocalizedEnumValueLabel: (context, resource, {
3717
3352
  attributeName,
@@ -3754,7 +3389,9 @@ var ProductTypeRepository = class extends AbstractResourceRepository {
3754
3389
  },
3755
3390
  changeAttributeOrder: (context, resource, { attributes }) => {
3756
3391
  var _a;
3757
- const attrs = new Map((_a = resource.attributes) == null ? void 0 : _a.map((item) => [item.name, item]));
3392
+ const attrs = new Map(
3393
+ (_a = resource.attributes) == null ? void 0 : _a.map((item) => [item.name, item])
3394
+ );
3758
3395
  const result = [];
3759
3396
  let current = resource.attributes;
3760
3397
  attributes.forEach((iAttr) => {
@@ -3763,9 +3400,7 @@ var ProductTypeRepository = class extends AbstractResourceRepository {
3763
3400
  throw new Error("New attr");
3764
3401
  }
3765
3402
  result.push(attr);
3766
- current = current == null ? void 0 : current.filter((f) => {
3767
- return f.name !== iAttr.name;
3768
- });
3403
+ current = current == null ? void 0 : current.filter((f) => f.name !== iAttr.name);
3769
3404
  });
3770
3405
  resource.attributes = result;
3771
3406
  if (current) {
@@ -3774,25 +3409,21 @@ var ProductTypeRepository = class extends AbstractResourceRepository {
3774
3409
  },
3775
3410
  removeAttributeDefinition: (context, resource, { name }) => {
3776
3411
  var _a;
3777
- resource.attributes = (_a = resource.attributes) == null ? void 0 : _a.filter((f) => {
3778
- return f.name !== name;
3779
- });
3412
+ resource.attributes = (_a = resource.attributes) == null ? void 0 : _a.filter((f) => f.name !== name);
3780
3413
  },
3781
3414
  removeEnumValues: (context, resource, { attributeName, keys }) => {
3782
3415
  var _a;
3783
3416
  (_a = resource.attributes) == null ? void 0 : _a.forEach((attr) => {
3784
3417
  if (attr.name == attributeName) {
3785
3418
  if (attr.type.name == "enum") {
3786
- attr.type.values = attr.type.values.filter((v) => {
3787
- return !keys.includes(v.key);
3788
- });
3419
+ attr.type.values = attr.type.values.filter(
3420
+ (v) => !keys.includes(v.key)
3421
+ );
3789
3422
  }
3790
3423
  if (attr.type.name == "set") {
3791
3424
  if (attr.type.elementType.name == "enum") {
3792
3425
  attr.type.elementType.values = attr.type.elementType.values.filter(
3793
- (v) => {
3794
- return !keys.includes(v.key);
3795
- }
3426
+ (v) => !keys.includes(v.key)
3796
3427
  );
3797
3428
  }
3798
3429
  }
@@ -3814,7 +3445,7 @@ var ProductTypeRepository = class extends AbstractResourceRepository {
3814
3445
  (a) => this.attributeDefinitionFromAttributeDefinitionDraft(context, a)
3815
3446
  )
3816
3447
  };
3817
- this.save(context, resource);
3448
+ this.saveNew(context, resource);
3818
3449
  return resource;
3819
3450
  }
3820
3451
  getWithKey(context, key) {
@@ -3831,30 +3462,6 @@ var ProductTypeRepository = class extends AbstractResourceRepository {
3831
3462
  }
3832
3463
  };
3833
3464
 
3834
- // src/services/product-type.ts
3835
- var ProductTypeService = class extends AbstractService {
3836
- constructor(parent, storage) {
3837
- super(parent);
3838
- this.repository = new ProductTypeRepository(storage);
3839
- }
3840
- getBasePath() {
3841
- return "product-types";
3842
- }
3843
- extraRoutes(router) {
3844
- router.get("/key=:key", this.getWithKey.bind(this));
3845
- }
3846
- getWithKey(request, response) {
3847
- const resource = this.repository.getWithKey(
3848
- getRepositoryContext(request),
3849
- request.params.key
3850
- );
3851
- if (resource) {
3852
- return response.status(200).send(resource);
3853
- }
3854
- return response.status(404).send("Not found");
3855
- }
3856
- };
3857
-
3858
3465
  // src/repositories/project.ts
3859
3466
  var ProjectRepository = class extends AbstractRepository {
3860
3467
  constructor() {
@@ -3916,64 +3523,21 @@ var ProjectRepository = class extends AbstractRepository {
3916
3523
  }
3917
3524
  postProcessResource(resource) {
3918
3525
  if (resource) {
3919
- return maskSecretValue(
3920
- resource,
3921
- "externalOAuth.authorizationHeader"
3922
- );
3526
+ return maskSecretValue(resource, "externalOAuth.authorizationHeader");
3923
3527
  }
3924
3528
  return resource;
3925
3529
  }
3926
- save(context, resource) {
3927
- const current = this.get(context);
3928
- if (current) {
3929
- checkConcurrentModification(current, resource.version);
3930
- } else {
3931
- if (resource.version !== 0) {
3932
- throw new CommercetoolsError(
3933
- {
3934
- code: "InvalidOperation",
3935
- message: "version on create must be 0"
3936
- },
3937
- 400
3938
- );
3939
- }
3940
- }
3941
- resource.version += 1;
3530
+ saveNew(context, resource) {
3531
+ resource.version = 1;
3532
+ this._storage.saveProject(resource);
3533
+ }
3534
+ saveUpdate(context, version, resource) {
3942
3535
  this._storage.saveProject(resource);
3943
3536
  }
3944
- };
3945
-
3946
- // src/services/project.ts
3947
- var ProjectService = class {
3948
- constructor(parent, storage) {
3949
- this.repository = new ProjectRepository(storage);
3950
- this.registerRoutes(parent);
3951
- }
3952
- registerRoutes(parent) {
3953
- parent.get("", this.get.bind(this));
3954
- parent.post("", this.post.bind(this));
3955
- }
3956
- get(request, response) {
3957
- const project = this.repository.get(getRepositoryContext(request));
3958
- return response.status(200).send(project);
3959
- }
3960
- post(request, response) {
3961
- const updateRequest = request.body;
3962
- const project = this.repository.get(getRepositoryContext(request));
3963
- if (!project) {
3964
- return response.status(404).send({});
3965
- }
3966
- this.repository.processUpdateActions(
3967
- getRepositoryContext(request),
3968
- project,
3969
- updateRequest.actions
3970
- );
3971
- return response.status(200).send({});
3972
- }
3973
3537
  };
3974
3538
 
3975
3539
  // src/repositories/shipping-method.ts
3976
- var import_deep_equal2 = __toESM(require("deep-equal"));
3540
+ var import_deep_equal3 = __toESM(require("deep-equal"));
3977
3541
  var ShippingMethodRepository = class extends AbstractResourceRepository {
3978
3542
  constructor() {
3979
3543
  super(...arguments);
@@ -3989,13 +3553,11 @@ var ShippingMethodRepository = class extends AbstractResourceRepository {
3989
3553
  shippingRates: (_a = draft.shippingRates) == null ? void 0 : _a.map(this._transformShippingRate)
3990
3554
  };
3991
3555
  };
3992
- this._transformShippingRate = (rate) => {
3993
- return {
3994
- price: createTypedMoney(rate.price),
3995
- freeAbove: rate.freeAbove && createTypedMoney(rate.freeAbove),
3996
- tiers: rate.tiers || []
3997
- };
3998
- };
3556
+ this._transformShippingRate = (rate) => ({
3557
+ price: createTypedMoney(rate.price),
3558
+ freeAbove: rate.freeAbove && createTypedMoney(rate.freeAbove),
3559
+ tiers: rate.tiers || []
3560
+ });
3999
3561
  this.actions = {
4000
3562
  addShippingRate: (_context, resource, { shippingRate, zone }) => {
4001
3563
  const rate = this._transformShippingRate(shippingRate);
@@ -4017,9 +3579,9 @@ var ShippingMethodRepository = class extends AbstractResourceRepository {
4017
3579
  const rate = this._transformShippingRate(shippingRate);
4018
3580
  resource.zoneRates.forEach((zoneRate) => {
4019
3581
  if (zoneRate.zone.id === zone.id) {
4020
- zoneRate.shippingRates = zoneRate.shippingRates.filter((otherRate) => {
4021
- return !(0, import_deep_equal2.default)(rate, otherRate);
4022
- });
3582
+ zoneRate.shippingRates = zoneRate.shippingRates.filter(
3583
+ (otherRate) => !(0, import_deep_equal3.default)(rate, otherRate)
3584
+ );
4023
3585
  }
4024
3586
  });
4025
3587
  },
@@ -4038,9 +3600,9 @@ var ShippingMethodRepository = class extends AbstractResourceRepository {
4038
3600
  });
4039
3601
  },
4040
3602
  removeZone: (_context, resource, { zone }) => {
4041
- resource.zoneRates = resource.zoneRates.filter((zoneRate) => {
4042
- return zoneRate.zone.id !== zone.id;
4043
- });
3603
+ resource.zoneRates = resource.zoneRates.filter(
3604
+ (zoneRate) => zoneRate.zone.id !== zone.id
3605
+ );
4044
3606
  },
4045
3607
  setKey: (_context, resource, { key }) => {
4046
3608
  resource.key = key;
@@ -4105,26 +3667,11 @@ var ShippingMethodRepository = class extends AbstractResourceRepository {
4105
3667
  this._storage
4106
3668
  )
4107
3669
  };
4108
- this.save(context, resource);
3670
+ this.saveNew(context, resource);
4109
3671
  return resource;
4110
3672
  }
4111
3673
  };
4112
3674
 
4113
- // src/services/shipping-method.ts
4114
- var ShippingMethodService = class extends AbstractService {
4115
- constructor(parent, storage) {
4116
- super(parent);
4117
- this.repository = new ShippingMethodRepository(storage);
4118
- this.registerRoutes(parent);
4119
- }
4120
- getBasePath() {
4121
- return "shipping-methods";
4122
- }
4123
- extraRoutes(parent) {
4124
- parent.get("/matching-cart", this.get.bind(this));
4125
- }
4126
- };
4127
-
4128
3675
  // src/repositories/shopping-list.ts
4129
3676
  var ShoppingListRepository = class extends AbstractResourceRepository {
4130
3677
  getTypeId() {
@@ -4158,22 +3705,11 @@ var ShoppingListRepository = class extends AbstractResourceRepository {
4158
3705
  ) : void 0,
4159
3706
  store: ((_b = draft.store) == null ? void 0 : _b.key) ? { typeId: "store", key: draft.store.key } : void 0
4160
3707
  };
4161
- this.save(context, resource);
3708
+ this.saveNew(context, resource);
4162
3709
  return resource;
4163
3710
  }
4164
3711
  };
4165
3712
 
4166
- // src/services/shopping-list.ts
4167
- var ShoppingListService = class extends AbstractService {
4168
- constructor(parent, storage) {
4169
- super(parent);
4170
- this.repository = new ShoppingListRepository(storage);
4171
- }
4172
- getBasePath() {
4173
- return "shopping-lists";
4174
- }
4175
- };
4176
-
4177
3713
  // src/repositories/state.ts
4178
3714
  var StateRepository = class extends AbstractResourceRepository {
4179
3715
  constructor() {
@@ -4192,12 +3728,12 @@ var StateRepository = class extends AbstractResourceRepository {
4192
3728
  resource.roles = roles;
4193
3729
  },
4194
3730
  setTransitions: (context, resource, { transitions }) => {
4195
- resource.transitions = transitions == null ? void 0 : transitions.map((resourceId) => {
4196
- return {
3731
+ resource.transitions = transitions == null ? void 0 : transitions.map(
3732
+ (resourceId) => ({
4197
3733
  id: resourceId.id || "",
4198
3734
  typeId: "state"
4199
- };
4200
- });
3735
+ })
3736
+ );
4201
3737
  }
4202
3738
  };
4203
3739
  }
@@ -4214,22 +3750,11 @@ var StateRepository = class extends AbstractResourceRepository {
4214
3750
  (t) => getReferenceFromResourceIdentifier(t, context.projectKey, this._storage)
4215
3751
  )
4216
3752
  };
4217
- this.save(context, resource);
3753
+ this.saveNew(context, resource);
4218
3754
  return resource;
4219
3755
  }
4220
3756
  };
4221
3757
 
4222
- // src/services/state.ts
4223
- var StateService = class extends AbstractService {
4224
- constructor(parent, storage) {
4225
- super(parent);
4226
- this.repository = new StateRepository(storage);
4227
- }
4228
- getBasePath() {
4229
- return "states";
4230
- }
4231
- };
4232
-
4233
3758
  // src/repositories/store.ts
4234
3759
  var StoreRepository = class extends AbstractResourceRepository {
4235
3760
  constructor() {
@@ -4291,7 +3816,7 @@ var StoreRepository = class extends AbstractResourceRepository {
4291
3816
  this._storage
4292
3817
  )
4293
3818
  };
4294
- this.save(context, resource);
3819
+ this.saveNew(context, resource);
4295
3820
  return resource;
4296
3821
  }
4297
3822
  transformChannels(context, channels) {
@@ -4319,30 +3844,6 @@ var StoreRepository = class extends AbstractResourceRepository {
4319
3844
  }
4320
3845
  };
4321
3846
 
4322
- // src/services/store.ts
4323
- var StoreService = class extends AbstractService {
4324
- constructor(parent, storage) {
4325
- super(parent);
4326
- this.repository = new StoreRepository(storage);
4327
- }
4328
- getBasePath() {
4329
- return "stores";
4330
- }
4331
- extraRoutes(router) {
4332
- router.get("/key=:key", this.getWithKey.bind(this));
4333
- }
4334
- getWithKey(request, response) {
4335
- const resource = this.repository.getWithKey(
4336
- getRepositoryContext(request),
4337
- request.params.key
4338
- );
4339
- if (resource) {
4340
- return response.status(200).send(resource);
4341
- }
4342
- return response.status(404).send("Not found");
4343
- }
4344
- };
4345
-
4346
3847
  // src/repositories/subscription.ts
4347
3848
  var SubscriptionRepository = class extends AbstractResourceRepository {
4348
3849
  getTypeId() {
@@ -4374,30 +3875,19 @@ var SubscriptionRepository = class extends AbstractResourceRepository {
4374
3875
  messages: draft.messages || [],
4375
3876
  status: "Healthy"
4376
3877
  };
4377
- this.save(context, resource);
3878
+ this.saveNew(context, resource);
4378
3879
  return resource;
4379
3880
  }
4380
3881
  };
4381
3882
 
4382
- // src/services/subscription.ts
4383
- var SubscriptionService = class extends AbstractService {
4384
- constructor(parent, storage) {
4385
- super(parent);
4386
- this.repository = new SubscriptionRepository(storage);
4387
- }
4388
- getBasePath() {
4389
- return "subscriptions";
4390
- }
4391
- };
4392
-
4393
3883
  // src/repositories/tax-category.ts
4394
- var import_uuid8 = require("uuid");
3884
+ var import_uuid7 = require("uuid");
4395
3885
  var TaxCategoryRepository = class extends AbstractResourceRepository {
4396
3886
  constructor() {
4397
3887
  super(...arguments);
4398
3888
  this.taxRateFromTaxRateDraft = (draft) => ({
4399
3889
  ...draft,
4400
- id: (0, import_uuid8.v4)(),
3890
+ id: (0, import_uuid7.v4)(),
4401
3891
  amount: draft.amount || 0
4402
3892
  });
4403
3893
  this.actions = {
@@ -4411,9 +3901,9 @@ var TaxCategoryRepository = class extends AbstractResourceRepository {
4411
3901
  if (resource.rates === void 0) {
4412
3902
  resource.rates = [];
4413
3903
  }
4414
- resource.rates = resource.rates.filter((taxRate) => {
4415
- return taxRate.id !== taxRateId;
4416
- });
3904
+ resource.rates = resource.rates.filter(
3905
+ (taxRate) => taxRate.id !== taxRateId
3906
+ );
4417
3907
  },
4418
3908
  replaceTaxRate: (context, resource, { taxRateId, taxRate }) => {
4419
3909
  if (resource.rates === void 0) {
@@ -4448,7 +3938,7 @@ var TaxCategoryRepository = class extends AbstractResourceRepository {
4448
3938
  ...draft,
4449
3939
  rates: ((_a = draft.rates) == null ? void 0 : _a.map(this.taxRateFromTaxRateDraft)) || []
4450
3940
  };
4451
- this.save(context, resource);
3941
+ this.saveNew(context, resource);
4452
3942
  return resource;
4453
3943
  }
4454
3944
  getWithKey(context, key) {
@@ -4465,30 +3955,6 @@ var TaxCategoryRepository = class extends AbstractResourceRepository {
4465
3955
  }
4466
3956
  };
4467
3957
 
4468
- // src/services/tax-category.ts
4469
- var TaxCategoryService = class extends AbstractService {
4470
- constructor(parent, storage) {
4471
- super(parent);
4472
- this.repository = new TaxCategoryRepository(storage);
4473
- }
4474
- getBasePath() {
4475
- return "tax-categories";
4476
- }
4477
- extraRoutes(router) {
4478
- router.get("/key=:key", this.getWithKey.bind(this));
4479
- }
4480
- getWithKey(request, response) {
4481
- const resource = this.repository.getWithKey(
4482
- getRepositoryContext(request),
4483
- request.params.key
4484
- );
4485
- if (resource) {
4486
- return response.status(200).send(resource);
4487
- }
4488
- return response.status(404).send("Not found");
4489
- }
4490
- };
4491
-
4492
3958
  // src/repositories/type.ts
4493
3959
  var import_lodash = require("lodash");
4494
3960
  var TypeRepository = class extends AbstractResourceRepository {
@@ -4499,9 +3965,9 @@ var TypeRepository = class extends AbstractResourceRepository {
4499
3965
  resource.fieldDefinitions.push(fieldDefinition);
4500
3966
  },
4501
3967
  removeFieldDefinition: (context, resource, { fieldName }) => {
4502
- resource.fieldDefinitions = resource.fieldDefinitions.filter((f) => {
4503
- return f.name !== fieldName;
4504
- });
3968
+ resource.fieldDefinitions = resource.fieldDefinitions.filter(
3969
+ (f) => f.name !== fieldName
3970
+ );
4505
3971
  },
4506
3972
  setDescription: (context, resource, { description }) => {
4507
3973
  resource.description = description;
@@ -4521,9 +3987,7 @@ var TypeRepository = class extends AbstractResourceRepository {
4521
3987
  throw new Error("New field");
4522
3988
  }
4523
3989
  result.push(field);
4524
- current = current.filter((f) => {
4525
- return f.name !== fieldName;
4526
- });
3990
+ current = current.filter((f) => f.name !== fieldName);
4527
3991
  });
4528
3992
  if ((0, import_lodash.isEqual)(
4529
3993
  fieldNames,
@@ -4589,22 +4053,11 @@ var TypeRepository = class extends AbstractResourceRepository {
4589
4053
  fieldDefinitions: draft.fieldDefinitions || [],
4590
4054
  description: draft.description
4591
4055
  };
4592
- this.save(context, resource);
4056
+ this.saveNew(context, resource);
4593
4057
  return resource;
4594
4058
  }
4595
4059
  };
4596
4060
 
4597
- // src/services/type.ts
4598
- var TypeService = class extends AbstractService {
4599
- constructor(parent, storage) {
4600
- super(parent);
4601
- this.repository = new TypeRepository(storage);
4602
- }
4603
- getBasePath() {
4604
- return "types";
4605
- }
4606
- };
4607
-
4608
4061
  // src/repositories/zone.ts
4609
4062
  var ZoneRepository = class extends AbstractResourceRepository {
4610
4063
  constructor() {
@@ -4614,9 +4067,9 @@ var ZoneRepository = class extends AbstractResourceRepository {
4614
4067
  resource.locations.push(location);
4615
4068
  },
4616
4069
  removeLocation: (context, resource, { location }) => {
4617
- resource.locations = resource.locations.filter((loc) => {
4618
- return !(loc.country === location.country && loc.state === location.state);
4619
- });
4070
+ resource.locations = resource.locations.filter(
4071
+ (loc) => !(loc.country === location.country && loc.state === location.state)
4072
+ );
4620
4073
  },
4621
4074
  changeName: (context, resource, { name }) => {
4622
4075
  resource.name = name;
@@ -4640,28 +4093,418 @@ var ZoneRepository = class extends AbstractResourceRepository {
4640
4093
  name: draft.name,
4641
4094
  description: draft.description
4642
4095
  };
4643
- this.save(context, resource);
4096
+ this.saveNew(context, resource);
4644
4097
  return resource;
4645
4098
  }
4646
4099
  };
4647
4100
 
4648
- // src/services/zone.ts
4649
- var ZoneService = class extends AbstractService {
4650
- constructor(parent, storage) {
4101
+ // src/repositories/index.ts
4102
+ var createRepositories = (storage) => ({
4103
+ category: new CategoryRepository(storage),
4104
+ cart: new CartRepository(storage),
4105
+ "cart-discount": new CartDiscountRepository(storage),
4106
+ customer: new CustomerRepository(storage),
4107
+ channel: new ChannelRepository(storage),
4108
+ "customer-group": new CustomerGroupRepository(storage),
4109
+ "discount-code": new DiscountCodeRepository(storage),
4110
+ extension: new ExtensionRepository(storage),
4111
+ "inventory-entry": new InventoryEntryRepository(storage),
4112
+ "key-value-document": new CustomObjectRepository(storage),
4113
+ order: new OrderRepository(storage),
4114
+ payment: new PaymentRepository(storage),
4115
+ "my-cart": new CartRepository(storage),
4116
+ "my-order": new MyOrderRepository(storage),
4117
+ "my-customer": new CustomerRepository(storage),
4118
+ "my-payment": new PaymentRepository(storage),
4119
+ "shipping-method": new ShippingMethodRepository(storage),
4120
+ "product-type": new ProductTypeRepository(storage),
4121
+ product: new ProductRepository(storage),
4122
+ project: new ProjectRepository(storage),
4123
+ "product-discount": new ProductDiscountRepository(storage),
4124
+ "product-projection": new ProductProjectionRepository(storage),
4125
+ "shopping-list": new ShoppingListRepository(storage),
4126
+ state: new StateRepository(storage),
4127
+ store: new StoreRepository(storage),
4128
+ subscription: new SubscriptionRepository(storage),
4129
+ "tax-category": new TaxCategoryRepository(storage),
4130
+ type: new TypeRepository(storage),
4131
+ zone: new ZoneRepository(storage)
4132
+ });
4133
+
4134
+ // src/services/abstract.ts
4135
+ var import_express2 = require("express");
4136
+ var AbstractService = class {
4137
+ constructor(parent) {
4138
+ this.createStatusCode = 201;
4139
+ this.registerRoutes(parent);
4140
+ }
4141
+ extraRoutes(router) {
4142
+ }
4143
+ registerRoutes(parent) {
4144
+ const basePath = this.getBasePath();
4145
+ const router = (0, import_express2.Router)({ mergeParams: true });
4146
+ this.extraRoutes(router);
4147
+ router.get("/", this.get.bind(this));
4148
+ router.get("/key=:key", this.getWithKey.bind(this));
4149
+ router.get("/:id", this.getWithId.bind(this));
4150
+ router.delete("/key=:key", this.deleteWithKey.bind(this));
4151
+ router.delete("/:id", this.deleteWithId.bind(this));
4152
+ router.post("/", this.post.bind(this));
4153
+ router.post("/key=:key", this.postWithKey.bind(this));
4154
+ router.post("/:id", this.postWithId.bind(this));
4155
+ parent.use(`/${basePath}`, router);
4156
+ }
4157
+ get(request, response) {
4158
+ const limit = this._parseParam(request.query.limit);
4159
+ const offset = this._parseParam(request.query.offset);
4160
+ const result = this.repository.query(getRepositoryContext(request), {
4161
+ expand: this._parseParam(request.query.expand),
4162
+ where: this._parseParam(request.query.where),
4163
+ limit: limit !== void 0 ? Number(limit) : void 0,
4164
+ offset: offset !== void 0 ? Number(offset) : void 0
4165
+ });
4166
+ return response.status(200).send(result);
4167
+ }
4168
+ getWithId(request, response) {
4169
+ const result = this._expandWithId(request, request.params["id"]);
4170
+ if (!result) {
4171
+ return response.status(404).send();
4172
+ }
4173
+ return response.status(200).send(result);
4174
+ }
4175
+ getWithKey(request, response) {
4176
+ const result = this.repository.getByKey(
4177
+ getRepositoryContext(request),
4178
+ request.params["key"],
4179
+ { expand: this._parseParam(request.query.expand) }
4180
+ );
4181
+ if (!result)
4182
+ return response.status(404).send();
4183
+ return response.status(200).send(result);
4184
+ }
4185
+ deleteWithId(request, response) {
4186
+ const result = this.repository.delete(
4187
+ getRepositoryContext(request),
4188
+ request.params["id"],
4189
+ {
4190
+ expand: this._parseParam(request.query.expand)
4191
+ }
4192
+ );
4193
+ if (!result) {
4194
+ return response.status(404).send("Not found");
4195
+ }
4196
+ return response.status(200).send(result);
4197
+ }
4198
+ deleteWithKey(request, response) {
4199
+ const resource = this.repository.getByKey(
4200
+ getRepositoryContext(request),
4201
+ request.params["key"]
4202
+ );
4203
+ if (!resource) {
4204
+ return response.status(404).send("Not found");
4205
+ }
4206
+ const result = this.repository.delete(
4207
+ getRepositoryContext(request),
4208
+ resource.id,
4209
+ {
4210
+ expand: this._parseParam(request.query.expand)
4211
+ }
4212
+ );
4213
+ if (!result) {
4214
+ return response.status(404).send("Not found");
4215
+ }
4216
+ return response.status(200).send(result);
4217
+ }
4218
+ post(request, response) {
4219
+ const draft = request.body;
4220
+ const resource = this.repository.create(
4221
+ getRepositoryContext(request),
4222
+ draft
4223
+ );
4224
+ const result = this._expandWithId(request, resource.id);
4225
+ return response.status(this.createStatusCode).send(result);
4226
+ }
4227
+ postWithId(request, response) {
4228
+ const updateRequest = request.body;
4229
+ const resource = this.repository.get(
4230
+ getRepositoryContext(request),
4231
+ request.params["id"]
4232
+ );
4233
+ if (!resource) {
4234
+ return response.status(404).send("Not found");
4235
+ }
4236
+ const updatedResource = this.repository.processUpdateActions(
4237
+ getRepositoryContext(request),
4238
+ resource,
4239
+ updateRequest.version,
4240
+ updateRequest.actions
4241
+ );
4242
+ const result = this._expandWithId(request, updatedResource.id);
4243
+ return response.status(200).send(result);
4244
+ }
4245
+ postWithKey(request, response) {
4246
+ const updateRequest = request.body;
4247
+ const resource = this.repository.getByKey(
4248
+ getRepositoryContext(request),
4249
+ request.params["key"]
4250
+ );
4251
+ if (!resource) {
4252
+ return response.status(404).send("Not found");
4253
+ }
4254
+ const updatedResource = this.repository.processUpdateActions(
4255
+ getRepositoryContext(request),
4256
+ resource,
4257
+ updateRequest.version,
4258
+ updateRequest.actions
4259
+ );
4260
+ const result = this._expandWithId(request, updatedResource.id);
4261
+ return response.status(200).send(result);
4262
+ }
4263
+ _expandWithId(request, resourceId) {
4264
+ const result = this.repository.get(
4265
+ getRepositoryContext(request),
4266
+ resourceId,
4267
+ {
4268
+ expand: this._parseParam(request.query.expand)
4269
+ }
4270
+ );
4271
+ return result;
4272
+ }
4273
+ _parseParam(value) {
4274
+ if (Array.isArray(value)) {
4275
+ return value;
4276
+ } else if (value !== void 0) {
4277
+ return [`${value}`];
4278
+ }
4279
+ return void 0;
4280
+ }
4281
+ };
4282
+
4283
+ // src/services/cart.ts
4284
+ var CartService = class extends AbstractService {
4285
+ constructor(parent, cartRepository, orderRepository) {
4651
4286
  super(parent);
4652
- this.repository = new ZoneRepository(storage);
4287
+ this.repository = cartRepository;
4288
+ this.orderRepository = orderRepository;
4653
4289
  }
4654
4290
  getBasePath() {
4655
- return "zones";
4291
+ return "carts";
4292
+ }
4293
+ extraRoutes(parent) {
4294
+ parent.post("/replicate", (request, response) => {
4295
+ const context = getRepositoryContext(request);
4296
+ const cartOrOrder = request.body.reference.typeId === "order" ? this.orderRepository.get(context, request.body.reference.id) : this.repository.get(context, request.body.reference.id);
4297
+ if (!cartOrOrder) {
4298
+ return response.status(400).send();
4299
+ }
4300
+ const cartDraft = {
4301
+ ...cartOrOrder,
4302
+ currency: cartOrOrder.totalPrice.currencyCode,
4303
+ discountCodes: [],
4304
+ lineItems: cartOrOrder.lineItems.map((lineItem) => ({
4305
+ ...lineItem,
4306
+ variantId: lineItem.variant.id,
4307
+ sku: lineItem.variant.sku
4308
+ }))
4309
+ };
4310
+ const newCart = this.repository.create(context, cartDraft);
4311
+ return response.status(200).send(newCart);
4312
+ });
4313
+ }
4314
+ };
4315
+
4316
+ // src/services/cart-discount.ts
4317
+ var CartDiscountService = class extends AbstractService {
4318
+ constructor(parent, repository) {
4319
+ super(parent);
4320
+ this.repository = repository;
4321
+ }
4322
+ getBasePath() {
4323
+ return "cart-discounts";
4324
+ }
4325
+ };
4326
+
4327
+ // src/services/category.ts
4328
+ var CategoryServices = class extends AbstractService {
4329
+ constructor(parent, repository) {
4330
+ super(parent);
4331
+ this.repository = repository;
4332
+ }
4333
+ getBasePath() {
4334
+ return "categories";
4335
+ }
4336
+ };
4337
+
4338
+ // src/services/channel.ts
4339
+ var ChannelService = class extends AbstractService {
4340
+ constructor(parent, repository) {
4341
+ super(parent);
4342
+ this.repository = repository;
4343
+ }
4344
+ getBasePath() {
4345
+ return "channels";
4346
+ }
4347
+ };
4348
+
4349
+ // src/services/custom-object.ts
4350
+ var CustomObjectService = class extends AbstractService {
4351
+ constructor(parent, repository) {
4352
+ super(parent);
4353
+ this.repository = repository;
4354
+ }
4355
+ getBasePath() {
4356
+ return "custom-objects";
4357
+ }
4358
+ extraRoutes(router) {
4359
+ router.get("/:container/:key", this.getWithContainerAndKey.bind(this));
4360
+ router.post("/:container/:key", this.createWithContainerAndKey.bind(this));
4361
+ router.delete("/:container/:key", this.deleteWithContainerAndKey.bind(this));
4362
+ }
4363
+ getWithContainerAndKey(request, response) {
4364
+ const result = this.repository.getWithContainerAndKey(
4365
+ getRepositoryContext(request),
4366
+ request.params.container,
4367
+ request.params.key
4368
+ );
4369
+ if (!result) {
4370
+ return response.status(404).send("Not Found");
4371
+ }
4372
+ return response.status(200).send(result);
4373
+ }
4374
+ createWithContainerAndKey(request, response) {
4375
+ const draft = {
4376
+ ...request.body,
4377
+ key: request.params.key,
4378
+ container: request.params.container
4379
+ };
4380
+ const result = this.repository.create(getRepositoryContext(request), draft);
4381
+ return response.status(200).send(result);
4382
+ }
4383
+ deleteWithContainerAndKey(request, response) {
4384
+ const current = this.repository.getWithContainerAndKey(
4385
+ getRepositoryContext(request),
4386
+ request.params.container,
4387
+ request.params.key
4388
+ );
4389
+ if (!current) {
4390
+ return response.status(404).send("Not Found");
4391
+ }
4392
+ const result = this.repository.delete(
4393
+ getRepositoryContext(request),
4394
+ current.id
4395
+ );
4396
+ return response.status(200).send(result);
4397
+ }
4398
+ };
4399
+
4400
+ // src/services/customer.ts
4401
+ var import_uuid8 = require("uuid");
4402
+ var CustomerService = class extends AbstractService {
4403
+ constructor(parent, repository) {
4404
+ super(parent);
4405
+ this.repository = repository;
4406
+ }
4407
+ getBasePath() {
4408
+ return "customers";
4409
+ }
4410
+ extraRoutes(parent) {
4411
+ parent.post("/password-token", (request, response) => {
4412
+ const customer = this.repository.query(getRepositoryContext(request), {
4413
+ where: [`email="${request.body.email}"`]
4414
+ });
4415
+ const ttlMinutes = request.params.ttlMinutes ? +request.params.ttlMinutes : 34560;
4416
+ const { version, ...rest } = getBaseResourceProperties();
4417
+ return response.status(200).send({
4418
+ ...rest,
4419
+ customerId: customer.results[0].id,
4420
+ expiresAt: new Date(Date.now() + ttlMinutes * 60).toISOString(),
4421
+ value: (0, import_uuid8.v4)()
4422
+ });
4423
+ });
4424
+ }
4425
+ };
4426
+
4427
+ // src/services/customer-group.ts
4428
+ var CustomerGroupService = class extends AbstractService {
4429
+ constructor(parent, repository) {
4430
+ super(parent);
4431
+ this.repository = repository;
4432
+ }
4433
+ getBasePath() {
4434
+ return "customer-groups";
4435
+ }
4436
+ };
4437
+
4438
+ // src/services/discount-code.ts
4439
+ var DiscountCodeService = class extends AbstractService {
4440
+ constructor(parent, repository) {
4441
+ super(parent);
4442
+ this.repository = repository;
4443
+ }
4444
+ getBasePath() {
4445
+ return "discount-codes";
4446
+ }
4447
+ };
4448
+
4449
+ // src/services/extension.ts
4450
+ var ExtensionServices = class extends AbstractService {
4451
+ constructor(parent, repository) {
4452
+ super(parent);
4453
+ this.repository = repository;
4454
+ }
4455
+ getBasePath() {
4456
+ return "extensions";
4457
+ }
4458
+ };
4459
+
4460
+ // src/services/inventory-entry.ts
4461
+ var InventoryEntryService = class extends AbstractService {
4462
+ constructor(parent, repository) {
4463
+ super(parent);
4464
+ this.repository = repository;
4465
+ }
4466
+ getBasePath() {
4467
+ return "inventory";
4468
+ }
4469
+ };
4470
+
4471
+ // src/services/my-cart.ts
4472
+ var import_express3 = require("express");
4473
+ var MyCartService = class extends AbstractService {
4474
+ constructor(parent, repository) {
4475
+ super(parent);
4476
+ this.repository = repository;
4477
+ }
4478
+ getBasePath() {
4479
+ return "me";
4480
+ }
4481
+ registerRoutes(parent) {
4482
+ const basePath = this.getBasePath();
4483
+ const router = (0, import_express3.Router)({ mergeParams: true });
4484
+ this.extraRoutes(router);
4485
+ router.get("/active-cart", this.activeCart.bind(this));
4486
+ router.get("/carts/", this.get.bind(this));
4487
+ router.get("/carts/:id", this.getWithId.bind(this));
4488
+ router.delete("/carts/:id", this.deleteWithId.bind(this));
4489
+ router.post("/carts/", this.post.bind(this));
4490
+ router.post("/carts/:id", this.postWithId.bind(this));
4491
+ parent.use(`/${basePath}`, router);
4492
+ }
4493
+ activeCart(request, response) {
4494
+ const resource = this.repository.getActiveCart(request.params.projectKey);
4495
+ if (!resource) {
4496
+ return response.status(404).send("Not found");
4497
+ }
4498
+ return response.status(200).send(resource);
4656
4499
  }
4657
4500
  };
4658
4501
 
4659
4502
  // src/services/my-customer.ts
4660
4503
  var import_express4 = require("express");
4661
4504
  var MyCustomerService = class extends AbstractService {
4662
- constructor(parent, storage) {
4505
+ constructor(parent, repository) {
4663
4506
  super(parent);
4664
- this.repository = new CustomerRepository(storage);
4507
+ this.repository = repository;
4665
4508
  }
4666
4509
  getBasePath() {
4667
4510
  return "me";
@@ -4714,25 +4557,10 @@ var MyCustomerService = class extends AbstractService {
4714
4557
 
4715
4558
  // src/services/my-order.ts
4716
4559
  var import_express5 = require("express");
4717
-
4718
- // src/repositories/my-order.ts
4719
- var import_assert3 = __toESM(require("assert"));
4720
- var MyOrderRepository = class extends OrderRepository {
4721
- create(context, draft) {
4722
- (0, import_assert3.default)(draft.id, "draft.id is missing");
4723
- const cartIdentifier = {
4724
- id: draft.id,
4725
- typeId: "cart"
4726
- };
4727
- return this.createFromCart(context, cartIdentifier);
4728
- }
4729
- };
4730
-
4731
- // src/services/my-order.ts
4732
4560
  var MyOrderService = class extends AbstractService {
4733
- constructor(parent, storage) {
4561
+ constructor(parent, repository) {
4734
4562
  super(parent);
4735
- this.repository = new MyOrderRepository(storage);
4563
+ this.repository = repository;
4736
4564
  }
4737
4565
  getBasePath() {
4738
4566
  return "me";
@@ -4743,13 +4571,314 @@ var MyOrderService = class extends AbstractService {
4743
4571
  this.extraRoutes(router);
4744
4572
  router.get("/orders/", this.get.bind(this));
4745
4573
  router.get("/orders/:id", this.getWithId.bind(this));
4746
- router.delete("/orders/:id", this.deletewithId.bind(this));
4574
+ router.delete("/orders/:id", this.deleteWithId.bind(this));
4747
4575
  router.post("/orders/", this.post.bind(this));
4748
4576
  router.post("/orders/:id", this.postWithId.bind(this));
4749
4577
  parent.use(`/${basePath}`, router);
4750
4578
  }
4751
4579
  };
4752
4580
 
4581
+ // src/services/my-payment.ts
4582
+ var MyPaymentService = class extends AbstractService {
4583
+ constructor(parent, repository) {
4584
+ super(parent);
4585
+ this.repository = repository;
4586
+ }
4587
+ getBasePath() {
4588
+ return "me/payments";
4589
+ }
4590
+ };
4591
+
4592
+ // src/services/order.ts
4593
+ var OrderService = class extends AbstractService {
4594
+ constructor(parent, repository) {
4595
+ super(parent);
4596
+ this.repository = repository;
4597
+ }
4598
+ getBasePath() {
4599
+ return "orders";
4600
+ }
4601
+ extraRoutes(router) {
4602
+ router.post("/import", this.import.bind(this));
4603
+ router.get("/order-number=:orderNumber", this.getWithOrderNumber.bind(this));
4604
+ }
4605
+ import(request, response) {
4606
+ const importDraft = request.body;
4607
+ const resource = this.repository.import(
4608
+ getRepositoryContext(request),
4609
+ importDraft
4610
+ );
4611
+ return response.status(200).send(resource);
4612
+ }
4613
+ getWithOrderNumber(request, response) {
4614
+ const resource = this.repository.getWithOrderNumber(
4615
+ getRepositoryContext(request),
4616
+ request.params.orderNumber,
4617
+ request.query
4618
+ );
4619
+ if (resource) {
4620
+ return response.status(200).send(resource);
4621
+ }
4622
+ return response.status(404).send("Not found");
4623
+ }
4624
+ };
4625
+
4626
+ // src/services/payment.ts
4627
+ var PaymentService = class extends AbstractService {
4628
+ constructor(parent, repository) {
4629
+ super(parent);
4630
+ this.repository = repository;
4631
+ }
4632
+ getBasePath() {
4633
+ return "payments";
4634
+ }
4635
+ };
4636
+
4637
+ // src/services/product.ts
4638
+ var ProductService = class extends AbstractService {
4639
+ constructor(parent, repository) {
4640
+ super(parent);
4641
+ this.repository = repository;
4642
+ }
4643
+ getBasePath() {
4644
+ return "products";
4645
+ }
4646
+ };
4647
+
4648
+ // src/services/product-discount.ts
4649
+ var ProductDiscountService = class extends AbstractService {
4650
+ constructor(parent, repository) {
4651
+ super(parent);
4652
+ this.repository = repository;
4653
+ }
4654
+ getBasePath() {
4655
+ return "product-discounts";
4656
+ }
4657
+ extraRoutes(router) {
4658
+ router.get("/key=:key", this.getWithKey.bind(this));
4659
+ }
4660
+ getWithKey(request, response) {
4661
+ const resource = this.repository.getWithKey(
4662
+ getRepositoryContext(request),
4663
+ request.params.key
4664
+ );
4665
+ if (resource) {
4666
+ return response.status(200).send(resource);
4667
+ }
4668
+ return response.status(404).send("Not found");
4669
+ }
4670
+ };
4671
+
4672
+ // src/services/product-projection.ts
4673
+ var ProductProjectionService = class extends AbstractService {
4674
+ constructor(parent, repository) {
4675
+ super(parent);
4676
+ this.repository = repository;
4677
+ }
4678
+ getBasePath() {
4679
+ return "product-projections";
4680
+ }
4681
+ extraRoutes(router) {
4682
+ router.get("/search", this.search.bind(this));
4683
+ }
4684
+ search(request, response) {
4685
+ const resource = this.repository.search(
4686
+ getRepositoryContext(request),
4687
+ request.query
4688
+ );
4689
+ return response.status(200).send(resource);
4690
+ }
4691
+ };
4692
+
4693
+ // src/services/product-type.ts
4694
+ var ProductTypeService = class extends AbstractService {
4695
+ constructor(parent, repository) {
4696
+ super(parent);
4697
+ this.repository = repository;
4698
+ }
4699
+ getBasePath() {
4700
+ return "product-types";
4701
+ }
4702
+ extraRoutes(router) {
4703
+ router.get("/key=:key", this.getWithKey.bind(this));
4704
+ }
4705
+ getWithKey(request, response) {
4706
+ const resource = this.repository.getWithKey(
4707
+ getRepositoryContext(request),
4708
+ request.params.key
4709
+ );
4710
+ if (resource) {
4711
+ return response.status(200).send(resource);
4712
+ }
4713
+ return response.status(404).send("Not found");
4714
+ }
4715
+ };
4716
+
4717
+ // src/services/shipping-method.ts
4718
+ var ShippingMethodService = class extends AbstractService {
4719
+ constructor(parent, repository) {
4720
+ super(parent);
4721
+ this.repository = repository;
4722
+ this.registerRoutes(parent);
4723
+ }
4724
+ getBasePath() {
4725
+ return "shipping-methods";
4726
+ }
4727
+ extraRoutes(parent) {
4728
+ parent.get("/matching-cart", this.get.bind(this));
4729
+ }
4730
+ };
4731
+
4732
+ // src/services/shopping-list.ts
4733
+ var ShoppingListService = class extends AbstractService {
4734
+ constructor(parent, repository) {
4735
+ super(parent);
4736
+ this.repository = repository;
4737
+ }
4738
+ getBasePath() {
4739
+ return "shopping-lists";
4740
+ }
4741
+ };
4742
+
4743
+ // src/services/state.ts
4744
+ var StateService = class extends AbstractService {
4745
+ constructor(parent, repository) {
4746
+ super(parent);
4747
+ this.repository = repository;
4748
+ }
4749
+ getBasePath() {
4750
+ return "states";
4751
+ }
4752
+ };
4753
+
4754
+ // src/services/store.ts
4755
+ var StoreService = class extends AbstractService {
4756
+ constructor(parent, repository) {
4757
+ super(parent);
4758
+ this.repository = repository;
4759
+ }
4760
+ getBasePath() {
4761
+ return "stores";
4762
+ }
4763
+ extraRoutes(router) {
4764
+ router.get("/key=:key", this.getWithKey.bind(this));
4765
+ }
4766
+ getWithKey(request, response) {
4767
+ const resource = this.repository.getWithKey(
4768
+ getRepositoryContext(request),
4769
+ request.params.key
4770
+ );
4771
+ if (resource) {
4772
+ return response.status(200).send(resource);
4773
+ }
4774
+ return response.status(404).send("Not found");
4775
+ }
4776
+ };
4777
+
4778
+ // src/services/subscription.ts
4779
+ var SubscriptionService = class extends AbstractService {
4780
+ constructor(parent, repository) {
4781
+ super(parent);
4782
+ this.repository = repository;
4783
+ }
4784
+ getBasePath() {
4785
+ return "subscriptions";
4786
+ }
4787
+ };
4788
+
4789
+ // src/services/tax-category.ts
4790
+ var TaxCategoryService = class extends AbstractService {
4791
+ constructor(parent, repository) {
4792
+ super(parent);
4793
+ this.repository = repository;
4794
+ }
4795
+ getBasePath() {
4796
+ return "tax-categories";
4797
+ }
4798
+ extraRoutes(router) {
4799
+ router.get("/key=:key", this.getWithKey.bind(this));
4800
+ }
4801
+ getWithKey(request, response) {
4802
+ const resource = this.repository.getWithKey(
4803
+ getRepositoryContext(request),
4804
+ request.params.key
4805
+ );
4806
+ if (resource) {
4807
+ return response.status(200).send(resource);
4808
+ }
4809
+ return response.status(404).send("Not found");
4810
+ }
4811
+ };
4812
+
4813
+ // src/services/type.ts
4814
+ var TypeService = class extends AbstractService {
4815
+ constructor(parent, repository) {
4816
+ super(parent);
4817
+ this.repository = repository;
4818
+ }
4819
+ getBasePath() {
4820
+ return "types";
4821
+ }
4822
+ };
4823
+
4824
+ // src/services/zone.ts
4825
+ var ZoneService = class extends AbstractService {
4826
+ constructor(parent, repository) {
4827
+ super(parent);
4828
+ this.repository = repository;
4829
+ }
4830
+ getBasePath() {
4831
+ return "zones";
4832
+ }
4833
+ };
4834
+
4835
+ // src/services/index.ts
4836
+ var createServices = (router, repos) => ({
4837
+ category: new CategoryServices(router, repos["category"]),
4838
+ cart: new CartService(router, repos["cart"], repos["order"]),
4839
+ "cart-discount": new CartDiscountService(router, repos["cart-discount"]),
4840
+ customer: new CustomerService(router, repos["customer"]),
4841
+ channel: new ChannelService(router, repos["channel"]),
4842
+ "customer-group": new CustomerGroupService(router, repos["customer-group"]),
4843
+ "discount-code": new DiscountCodeService(router, repos["discount-code"]),
4844
+ extension: new ExtensionServices(router, repos["extension"]),
4845
+ "inventory-entry": new InventoryEntryService(
4846
+ router,
4847
+ repos["inventory-entry"]
4848
+ ),
4849
+ "key-value-document": new CustomObjectService(
4850
+ router,
4851
+ repos["key-value-document"]
4852
+ ),
4853
+ order: new OrderService(router, repos["order"]),
4854
+ payment: new PaymentService(router, repos["payment"]),
4855
+ "my-cart": new MyCartService(router, repos["my-cart"]),
4856
+ "my-order": new MyOrderService(router, repos["my-order"]),
4857
+ "my-customer": new MyCustomerService(router, repos["my-customer"]),
4858
+ "my-payment": new MyPaymentService(router, repos["my-payment"]),
4859
+ "shipping-method": new ShippingMethodService(
4860
+ router,
4861
+ repos["shipping-method"]
4862
+ ),
4863
+ "product-type": new ProductTypeService(router, repos["product-type"]),
4864
+ product: new ProductService(router, repos["product"]),
4865
+ "product-discount": new ProductDiscountService(
4866
+ router,
4867
+ repos["product-discount"]
4868
+ ),
4869
+ "product-projection": new ProductProjectionService(
4870
+ router,
4871
+ repos["product-projection"]
4872
+ ),
4873
+ "shopping-list": new ShoppingListService(router, repos["shopping-list"]),
4874
+ state: new StateService(router, repos["state"]),
4875
+ store: new StoreService(router, repos["store"]),
4876
+ subscription: new SubscriptionService(router, repos["subscription"]),
4877
+ "tax-category": new TaxCategoryService(router, repos["tax-category"]),
4878
+ type: new TypeService(router, repos["type"]),
4879
+ zone: new ZoneService(router, repos["zone"])
4880
+ });
4881
+
4753
4882
  // src/ctMock.ts
4754
4883
  var DEFAULT_OPTIONS = {
4755
4884
  enableAuthentication: false,
@@ -4764,6 +4893,7 @@ var CommercetoolsMock = class {
4764
4893
  this._nockScopes = { auth: void 0, api: void 0 };
4765
4894
  this.options = { ...DEFAULT_OPTIONS, ...options };
4766
4895
  this._services = {};
4896
+ this._repositories = {};
4767
4897
  this._projectService = void 0;
4768
4898
  this._storage = new InMemoryStorage();
4769
4899
  this._oauth2 = new OAuth2Server({
@@ -4797,9 +4927,8 @@ var CommercetoolsMock = class {
4797
4927
  );
4798
4928
  }
4799
4929
  runServer(port = 3e3, options) {
4800
- const app = this.createApp(options);
4801
- const server = app.listen(port, () => {
4802
- console.log(`Mock server listening at http://localhost:${port}`);
4930
+ const server = this.app.listen(port, () => {
4931
+ console.info(`Mock server listening at http://localhost:${port}`);
4803
4932
  });
4804
4933
  server.keepAliveTimeout = 60 * 1e3;
4805
4934
  }
@@ -4822,52 +4951,12 @@ var CommercetoolsMock = class {
4822
4951
  app.use("/:projectKey", projectRouter);
4823
4952
  app.use("/:projectKey/in-store/key=:storeKey", projectRouter);
4824
4953
  }
4825
- this._projectService = new ProjectService(projectRouter, this._storage);
4826
- this._services = {
4827
- category: new CategoryServices(projectRouter, this._storage),
4828
- cart: new CartService(projectRouter, this._storage),
4829
- "cart-discount": new CartDiscountService(projectRouter, this._storage),
4830
- customer: new CustomerService(projectRouter, this._storage),
4831
- channel: new ChannelService(projectRouter, this._storage),
4832
- "customer-group": new CustomerGroupService(projectRouter, this._storage),
4833
- "discount-code": new DiscountCodeService(projectRouter, this._storage),
4834
- extension: new ExtensionServices(projectRouter, this._storage),
4835
- "inventory-entry": new InventoryEntryService(
4836
- projectRouter,
4837
- this._storage
4838
- ),
4839
- "key-value-document": new CustomObjectService(
4840
- projectRouter,
4841
- this._storage
4842
- ),
4843
- order: new OrderService(projectRouter, this._storage),
4844
- payment: new PaymentService(projectRouter, this._storage),
4845
- "my-cart": new MyCartService(projectRouter, this._storage),
4846
- "my-order": new MyOrderService(projectRouter, this._storage),
4847
- "my-customer": new MyCustomerService(projectRouter, this._storage),
4848
- "my-payment": new MyPaymentService(projectRouter, this._storage),
4849
- "shipping-method": new ShippingMethodService(
4850
- projectRouter,
4851
- this._storage
4852
- ),
4853
- "product-type": new ProductTypeService(projectRouter, this._storage),
4854
- product: new ProductService(projectRouter, this._storage),
4855
- "product-discount": new ProductDiscountService(
4856
- projectRouter,
4857
- this._storage
4858
- ),
4859
- "product-projection": new ProductProjectionService(
4860
- projectRouter,
4861
- this._storage
4862
- ),
4863
- "shopping-list": new ShoppingListService(projectRouter, this._storage),
4864
- state: new StateService(projectRouter, this._storage),
4865
- store: new StoreService(projectRouter, this._storage),
4866
- subscription: new SubscriptionService(projectRouter, this._storage),
4867
- "tax-category": new TaxCategoryService(projectRouter, this._storage),
4868
- type: new TypeService(projectRouter, this._storage),
4869
- zone: new ZoneService(projectRouter, this._storage)
4870
- };
4954
+ this._repositories = createRepositories(this._storage);
4955
+ this._projectService = new ProjectService(
4956
+ projectRouter,
4957
+ this._repositories.project
4958
+ );
4959
+ this._services = createServices(projectRouter, this._repositories);
4871
4960
  app.use((err, req, resp, next) => {
4872
4961
  if (err instanceof CommercetoolsError) {
4873
4962
  return resp.status(err.statusCode).send({