@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
@@ -2054,10 +2054,10 @@
2054
2054
  if (isPlainObject(actual)) {
2055
2055
  actual = expand(actual);
2056
2056
  }
2057
- return deepEqual3(expected, actual);
2057
+ return deepEqual4(expected, actual);
2058
2058
  };
2059
2059
  var expand = (input) => Object.entries(input).reduce((acc, [k, v]) => set(acc, k, v), {});
2060
- function deepEqual3(expected, actual) {
2060
+ function deepEqual4(expected, actual) {
2061
2061
  debug("deepEqual comparing", typeof expected, expected, typeof actual, actual);
2062
2062
  if (expected instanceof RegExp) {
2063
2063
  return expected.test(actual);
@@ -2066,13 +2066,13 @@
2066
2066
  if (expected.length !== actual.length) {
2067
2067
  return false;
2068
2068
  }
2069
- return expected.every((expVal, idx) => deepEqual3(expVal, actual[idx]));
2069
+ return expected.every((expVal, idx) => deepEqual4(expVal, actual[idx]));
2070
2070
  }
2071
2071
  if (isPlainObject(expected) && isPlainObject(actual)) {
2072
2072
  const allKeys = Array.from(
2073
2073
  new Set(Object.keys(expected).concat(Object.keys(actual)))
2074
2074
  );
2075
- return allKeys.every((key) => deepEqual3(expected[key], actual[key]));
2075
+ return allKeys.every((key) => deepEqual4(expected[key], actual[key]));
2076
2076
  }
2077
2077
  return expected === actual;
2078
2078
  }
@@ -39492,7 +39492,7 @@ ${this.pendingMocks().join("\n")}`
39492
39492
  }
39493
39493
  return true;
39494
39494
  }
39495
- module.exports = function deepEqual3(a, b, opts) {
39495
+ module.exports = function deepEqual4(a, b, opts) {
39496
39496
  return internalDeepEqual(a, b, opts, getSideChannel());
39497
39497
  };
39498
39498
  }
@@ -44975,8 +44975,8 @@ ${this.pendingMocks().join("\n")}`
44975
44975
  const toRadian = (deg) => deg * (Math.PI / 180);
44976
44976
  const dLat = toRadian(dst.latitude - src.latitude);
44977
44977
  const dLon = toRadian(dst.longitude - src.longitude);
44978
- 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);
44979
- var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
44978
+ 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);
44979
+ const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
44980
44980
  return RADIUS_OF_EARTH_IN_KM * c * 1e3;
44981
44981
  };
44982
44982
 
@@ -44989,9 +44989,7 @@ ${this.pendingMocks().join("\n")}`
44989
44989
  var parseQueryExpression = (predicate) => {
44990
44990
  if (Array.isArray(predicate)) {
44991
44991
  const callbacks = predicate.map((item) => generateMatchFunc(item));
44992
- return (target, variables) => {
44993
- return callbacks.every((callback) => callback(target, variables));
44994
- };
44992
+ return (target, variables) => callbacks.every((callback) => callback(target, variables));
44995
44993
  } else {
44996
44994
  return generateMatchFunc(predicate);
44997
44995
  }
@@ -45031,60 +45029,66 @@ ${this.pendingMocks().join("\n")}`
45031
45029
  }
45032
45030
  return obj[val.value];
45033
45031
  };
45034
- var getLexer = (value) => {
45035
- 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);
45036
- };
45032
+ 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);
45037
45033
  var generateMatchFunc = (predicate) => {
45038
45034
  const lexer = getLexer(predicate);
45039
- const parser = new import_pratt.Parser(lexer).builder().nud("IDENTIFIER", 100, (t) => {
45040
- return {
45035
+ const parser = new import_pratt.Parser(lexer).builder().nud(
45036
+ "IDENTIFIER",
45037
+ 100,
45038
+ (t) => ({
45041
45039
  type: "identifier",
45042
45040
  value: t.token.match,
45043
45041
  pos: t.token.strpos()
45044
- };
45045
- }).nud("VARIABLE", 100, (t) => {
45046
- return {
45042
+ })
45043
+ ).nud(
45044
+ "BOOLEAN",
45045
+ 1,
45046
+ (t) => ({
45047
+ type: "boolean",
45048
+ value: t.token.match === "true" ? true : false,
45049
+ pos: t.token.strpos()
45050
+ })
45051
+ ).nud(
45052
+ "VARIABLE",
45053
+ 100,
45054
+ (t) => ({
45047
45055
  type: "var",
45048
45056
  value: t.token.groups[1],
45049
45057
  pos: t.token.strpos()
45050
- };
45051
- }).nud("STRING", 100, (t) => {
45052
- return {
45058
+ })
45059
+ ).nud(
45060
+ "STRING",
45061
+ 100,
45062
+ (t) => ({
45053
45063
  type: "string",
45054
45064
  value: t.token.groups[1],
45055
45065
  pos: t.token.strpos()
45056
- };
45057
- }).nud("INT", 1, (t) => {
45058
- return {
45066
+ })
45067
+ ).nud(
45068
+ "INT",
45069
+ 1,
45070
+ (t) => ({
45059
45071
  type: "int",
45060
45072
  value: parseInt(t.token.match, 10),
45061
45073
  pos: t.token.strpos()
45062
- };
45063
- }).nud("FLOAT", 1, (t) => {
45064
- return {
45074
+ })
45075
+ ).nud(
45076
+ "FLOAT",
45077
+ 1,
45078
+ (t) => ({
45065
45079
  type: "float",
45066
45080
  value: parseFloat(t.token.match),
45067
45081
  pos: t.token.strpos()
45068
- };
45069
- }).nud("NOT", 100, ({ bp }) => {
45082
+ })
45083
+ ).nud("NOT", 100, ({ bp }) => {
45070
45084
  const expr = parser.parse({ terminals: [bp - 1] });
45071
- return (obj) => {
45072
- return !expr(obj);
45073
- };
45074
- }).nud("EMPTY", 10, ({ bp }) => {
45075
- return "empty";
45076
- }).nud("DEFINED", 10, ({ bp }) => {
45077
- return "defined";
45078
- }).led("AND", 5, ({ left, bp }) => {
45085
+ return (obj) => !expr(obj);
45086
+ }).nud("EMPTY", 10, ({ bp }) => "empty").nud("DEFINED", 10, ({ bp }) => "defined").led("AND", 5, ({ left, bp }) => {
45079
45087
  const expr = parser.parse({ terminals: [bp - 1] });
45080
- return (obj) => {
45081
- return left(obj) && expr(obj);
45082
- };
45088
+ return (obj) => left(obj) && expr(obj);
45083
45089
  }).led("OR", 5, ({ left, token, bp }) => {
45084
45090
  const expr = parser.parse({ terminals: [bp - 1] });
45085
- return (obj, vars) => {
45086
- return left(obj, vars) || expr(obj, vars);
45087
- };
45091
+ return (obj, vars) => left(obj, vars) || expr(obj, vars);
45088
45092
  }).led("COMMA", 1, ({ left, token, bp }) => {
45089
45093
  const expr = parser.parse({ terminals: [bp - 1] });
45090
45094
  if (Array.isArray(expr)) {
@@ -45119,33 +45123,23 @@ ${this.pendingMocks().join("\n")}`
45119
45123
  }).led("!=", 20, ({ left, bp }) => {
45120
45124
  const expr = parser.parse({ terminals: [bp - 1] });
45121
45125
  validateSymbol(expr);
45122
- return (obj, vars) => {
45123
- return resolveValue(obj, left) !== resolveSymbol(expr, vars);
45124
- };
45126
+ return (obj, vars) => resolveValue(obj, left) !== resolveSymbol(expr, vars);
45125
45127
  }).led(">", 20, ({ left, bp }) => {
45126
45128
  const expr = parser.parse({ terminals: [bp - 1] });
45127
45129
  validateSymbol(expr);
45128
- return (obj, vars) => {
45129
- return resolveValue(obj, left) > resolveSymbol(expr, vars);
45130
- };
45130
+ return (obj, vars) => resolveValue(obj, left) > resolveSymbol(expr, vars);
45131
45131
  }).led(">=", 20, ({ left, bp }) => {
45132
45132
  const expr = parser.parse({ terminals: [bp - 1] });
45133
45133
  validateSymbol(expr);
45134
- return (obj, vars) => {
45135
- return resolveValue(obj, left) >= resolveSymbol(expr, vars);
45136
- };
45134
+ return (obj, vars) => resolveValue(obj, left) >= resolveSymbol(expr, vars);
45137
45135
  }).led("<", 20, ({ left, bp }) => {
45138
45136
  const expr = parser.parse({ terminals: [bp - 1] });
45139
45137
  validateSymbol(expr);
45140
- return (obj, vars) => {
45141
- return resolveValue(obj, left) < resolveSymbol(expr, vars);
45142
- };
45138
+ return (obj, vars) => resolveValue(obj, left) < resolveSymbol(expr, vars);
45143
45139
  }).led("<=", 20, ({ left, bp }) => {
45144
45140
  const expr = parser.parse({ terminals: [bp - 1] });
45145
45141
  validateSymbol(expr);
45146
- return (obj, vars) => {
45147
- return resolveValue(obj, left) <= resolveSymbol(expr, vars);
45148
- };
45142
+ return (obj, vars) => resolveValue(obj, left) <= resolveSymbol(expr, vars);
45149
45143
  }).led("IS", 20, ({ left, bp }) => {
45150
45144
  let invert = false;
45151
45145
  const next = lexer.peek();
@@ -45277,6 +45271,51 @@ ${this.pendingMocks().join("\n")}`
45277
45271
  }
45278
45272
  };
45279
45273
 
45274
+ // node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/wrapper.mjs
45275
+ var import_dist = __toESM(require_dist(), 1);
45276
+ var v1 = import_dist.default.v1;
45277
+ var v3 = import_dist.default.v3;
45278
+ var v4 = import_dist.default.v4;
45279
+ var v5 = import_dist.default.v5;
45280
+ var NIL = import_dist.default.NIL;
45281
+ var version = import_dist.default.version;
45282
+ var validate = import_dist.default.validate;
45283
+ var stringify = import_dist.default.stringify;
45284
+ var parse = import_dist.default.parse;
45285
+
45286
+ // src/helpers.ts
45287
+ var getBaseResourceProperties = () => ({
45288
+ id: v4(),
45289
+ createdAt: new Date().toISOString(),
45290
+ lastModifiedAt: new Date().toISOString(),
45291
+ version: 0
45292
+ });
45293
+ var nestedLookup = (obj, path) => {
45294
+ if (!path || path === "") {
45295
+ return obj;
45296
+ }
45297
+ const parts = path.split(".");
45298
+ let val = obj;
45299
+ for (let i = 0; i < parts.length; i++) {
45300
+ const part = parts[i];
45301
+ if (val == void 0) {
45302
+ return void 0;
45303
+ }
45304
+ val = val[part];
45305
+ }
45306
+ return val;
45307
+ };
45308
+ var QueryParamsAsArray = (input) => {
45309
+ if (input == void 0) {
45310
+ return [];
45311
+ }
45312
+ if (Array.isArray(input)) {
45313
+ return input;
45314
+ }
45315
+ return [input];
45316
+ };
45317
+ var cloneObject = (o) => JSON.parse(JSON.stringify(o));
45318
+
45280
45319
  // src/storage.ts
45281
45320
  var AbstractStorage = class {
45282
45321
  };
@@ -45319,13 +45358,11 @@ ${this.pendingMocks().join("\n")}`
45319
45358
  this.projects[project.key] = project;
45320
45359
  return project;
45321
45360
  };
45322
- this.getProject = (projectKey) => {
45323
- return this.addProject(projectKey);
45324
- };
45361
+ this.getProject = (projectKey) => this.addProject(projectKey);
45325
45362
  this.expand = (projectKey, obj, clause) => {
45326
45363
  if (!clause)
45327
45364
  return obj;
45328
- const newObj = JSON.parse(JSON.stringify(obj));
45365
+ const newObj = cloneObject(obj);
45329
45366
  if (Array.isArray(clause)) {
45330
45367
  clause.forEach((c) => {
45331
45368
  this._resolveResource(projectKey, newObj, c);
@@ -45403,12 +45440,10 @@ ${this.pendingMocks().join("\n")}`
45403
45440
  }
45404
45441
  }
45405
45442
  }
45406
- assertStorage(typeId) {
45407
- }
45408
45443
  all(projectKey, typeId) {
45409
45444
  const store = this.forProjectKey(projectKey)[typeId];
45410
45445
  if (store) {
45411
- return Array.from(store.values());
45446
+ return Array.from(store.values()).map(cloneObject);
45412
45447
  }
45413
45448
  return [];
45414
45449
  }
@@ -45418,13 +45453,14 @@ ${this.pendingMocks().join("\n")}`
45418
45453
  (_a = store[typeId]) == null ? void 0 : _a.set(obj.id, obj);
45419
45454
  const resource = this.get(projectKey, typeId, obj.id, params);
45420
45455
  (0, import_assert.default)(resource, `resource of type ${typeId} with id ${obj.id} not created`);
45421
- return resource;
45456
+ return cloneObject(resource);
45422
45457
  }
45423
45458
  get(projectKey, typeId, id, params = {}) {
45424
45459
  var _a;
45425
45460
  const resource = (_a = this.forProjectKey(projectKey)[typeId]) == null ? void 0 : _a.get(id);
45426
45461
  if (resource) {
45427
- return this.expand(projectKey, resource, params.expand);
45462
+ const clone = cloneObject(resource);
45463
+ return this.expand(projectKey, clone, params.expand);
45428
45464
  }
45429
45465
  return null;
45430
45466
  }
@@ -45437,7 +45473,8 @@ ${this.pendingMocks().join("\n")}`
45437
45473
  const resources = Array.from(resourceStore.values());
45438
45474
  const resource = resources.find((e) => e.key === key);
45439
45475
  if (resource) {
45440
- return this.expand(projectKey, resource, params.expand);
45476
+ const clone = cloneObject(resource);
45477
+ return this.expand(projectKey, clone, params.expand);
45441
45478
  }
45442
45479
  return null;
45443
45480
  }
@@ -45475,24 +45512,20 @@ ${this.pendingMocks().join("\n")}`
45475
45512
  const limit = params.limit || 20;
45476
45513
  resources = resources.slice(offset, offset + limit);
45477
45514
  if (params.expand !== void 0) {
45478
- resources = resources.map((resource) => {
45479
- return this.expand(projectKey, resource, params.expand);
45480
- });
45515
+ resources = resources.map(
45516
+ (resource) => this.expand(projectKey, resource, params.expand)
45517
+ );
45481
45518
  }
45482
45519
  return {
45483
45520
  count: totalResources,
45484
45521
  total: resources.length,
45485
45522
  offset,
45486
45523
  limit,
45487
- results: resources
45524
+ results: resources.map(cloneObject)
45488
45525
  };
45489
45526
  }
45490
45527
  search(projectKey, typeId, params) {
45491
- const store = this.forProjectKey(projectKey)[typeId];
45492
- if (!store) {
45493
- throw new Error("No type");
45494
- }
45495
- let resources = Array.from(store.values());
45528
+ let resources = this.all(projectKey, typeId);
45496
45529
  if (params.where) {
45497
45530
  try {
45498
45531
  const filterFunc = parseQueryExpression(params.where);
@@ -45512,9 +45545,9 @@ ${this.pendingMocks().join("\n")}`
45512
45545
  const limit = params.limit || 20;
45513
45546
  resources = resources.slice(offset, offset + limit);
45514
45547
  if (params.expand !== void 0) {
45515
- resources = resources.map((resource) => {
45516
- return this.expand(projectKey, resource, params.expand);
45517
- });
45548
+ resources = resources.map(
45549
+ (resource) => this.expand(projectKey, resource, params.expand)
45550
+ );
45518
45551
  }
45519
45552
  return {
45520
45553
  count: totalResources,
@@ -45715,52 +45748,6 @@ ${this.pendingMocks().join("\n")}`
45715
45748
  }
45716
45749
  };
45717
45750
 
45718
- // node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/wrapper.mjs
45719
- var import_dist = __toESM(require_dist(), 1);
45720
- var v1 = import_dist.default.v1;
45721
- var v3 = import_dist.default.v3;
45722
- var v4 = import_dist.default.v4;
45723
- var v5 = import_dist.default.v5;
45724
- var NIL = import_dist.default.NIL;
45725
- var version = import_dist.default.version;
45726
- var validate = import_dist.default.validate;
45727
- var stringify = import_dist.default.stringify;
45728
- var parse = import_dist.default.parse;
45729
-
45730
- // src/helpers.ts
45731
- var getBaseResourceProperties = () => {
45732
- return {
45733
- id: v4(),
45734
- createdAt: new Date().toISOString(),
45735
- lastModifiedAt: new Date().toISOString(),
45736
- version: 0
45737
- };
45738
- };
45739
- var nestedLookup = (obj, path) => {
45740
- if (!path || path === "") {
45741
- return obj;
45742
- }
45743
- const parts = path.split(".");
45744
- let val = obj;
45745
- for (let i = 0; i < parts.length; i++) {
45746
- const part = parts[i];
45747
- if (val == void 0) {
45748
- return void 0;
45749
- }
45750
- val = val[part];
45751
- }
45752
- return val;
45753
- };
45754
- var QueryParamsAsArray = (input) => {
45755
- if (input == void 0) {
45756
- return [];
45757
- }
45758
- if (Array.isArray(input)) {
45759
- return input;
45760
- }
45761
- return [input];
45762
- };
45763
-
45764
45751
  // src/projectAPI.ts
45765
45752
  var ProjectAPI = class {
45766
45753
  constructor(projectKey, services, storage) {
@@ -45812,9 +45799,6 @@ ${this.pendingMocks().join("\n")}`
45812
45799
  var DEFAULT_API_HOSTNAME = /^https:\/\/api\..*?\.commercetools.com:443$/;
45813
45800
  var DEFAULT_AUTH_HOSTNAME = /^https:\/\/auth\..*?\.commercetools.com:443$/;
45814
45801
 
45815
- // src/services/abstract.ts
45816
- var import_express2 = __toESM(require_express2());
45817
-
45818
45802
  // src/repositories/helpers.ts
45819
45803
  var createAddress = (base, projectKey, storage) => {
45820
45804
  if (!base)
@@ -45852,12 +45836,10 @@ ${this.pendingMocks().join("\n")}`
45852
45836
  fields: draft.fields
45853
45837
  };
45854
45838
  };
45855
- var createPrice = (draft) => {
45856
- return {
45857
- id: v4(),
45858
- value: createTypedMoney(draft.value)
45859
- };
45860
- };
45839
+ var createPrice = (draft) => ({
45840
+ id: v4(),
45841
+ value: createTypedMoney(draft.value)
45842
+ });
45861
45843
  var createTypedMoney = (value) => {
45862
45844
  let fractionDigits = 2;
45863
45845
  switch (value.currencyCode.toUpperCase()) {
@@ -45939,128 +45921,38 @@ ${this.pendingMocks().join("\n")}`
45939
45921
  id: resource == null ? void 0 : resource.id
45940
45922
  };
45941
45923
  };
45942
- var getRepositoryContext = (request) => {
45943
- return {
45944
- projectKey: request.params.projectKey,
45945
- storeKey: request.params.storeKey
45946
- };
45947
- };
45924
+ var getRepositoryContext = (request) => ({
45925
+ projectKey: request.params.projectKey,
45926
+ storeKey: request.params.storeKey
45927
+ });
45948
45928
 
45949
- // src/services/abstract.ts
45950
- var AbstractService = class {
45951
- constructor(parent) {
45952
- this.createStatusCode = 201;
45929
+ // src/services/project.ts
45930
+ var ProjectService = class {
45931
+ constructor(parent, repository) {
45932
+ this.repository = repository;
45953
45933
  this.registerRoutes(parent);
45954
45934
  }
45955
- extraRoutes(router) {
45956
- }
45957
45935
  registerRoutes(parent) {
45958
- const basePath = this.getBasePath();
45959
- const router = (0, import_express2.Router)({ mergeParams: true });
45960
- this.extraRoutes(router);
45961
- router.get("/", this.get.bind(this));
45962
- router.get("/key=:key", this.getWithKey.bind(this));
45963
- router.get("/:id", this.getWithId.bind(this));
45964
- router.delete("/key=:key", this.deletewithKey.bind(this));
45965
- router.delete("/:id", this.deletewithId.bind(this));
45966
- router.post("/", this.post.bind(this));
45967
- router.post("/key=:key", this.postWithKey.bind(this));
45968
- router.post("/:id", this.postWithId.bind(this));
45969
- parent.use(`/${basePath}`, router);
45936
+ parent.get("", this.get.bind(this));
45937
+ parent.post("", this.post.bind(this));
45970
45938
  }
45971
45939
  get(request, response) {
45972
- const limit = this._parseParam(request.query.limit);
45973
- const offset = this._parseParam(request.query.offset);
45974
- const result = this.repository.query(getRepositoryContext(request), {
45975
- expand: this._parseParam(request.query.expand),
45976
- where: this._parseParam(request.query.where),
45977
- limit: limit !== void 0 ? Number(limit) : void 0,
45978
- offset: offset !== void 0 ? Number(offset) : void 0
45979
- });
45980
- return response.status(200).send(result);
45981
- }
45982
- getWithId(request, response) {
45983
- const result = this._expandWithId(request, request.params["id"]);
45984
- if (!result) {
45985
- return response.status(404).send();
45986
- }
45987
- return response.status(200).send(result);
45988
- }
45989
- getWithKey(request, response) {
45990
- const result = this.repository.getByKey(
45991
- getRepositoryContext(request),
45992
- request.params["key"],
45993
- { expand: this._parseParam(request.query.expand) }
45994
- );
45995
- if (!result)
45996
- return response.status(404).send();
45997
- return response.status(200).send(result);
45998
- }
45999
- deletewithId(request, response) {
46000
- const result = this.repository.delete(
46001
- getRepositoryContext(request),
46002
- request.params["id"],
46003
- {
46004
- expand: this._parseParam(request.query.expand)
46005
- }
46006
- );
46007
- if (!result) {
46008
- return response.status(404).send("Not found");
46009
- }
46010
- return response.status(200).send(result);
46011
- }
46012
- deletewithKey(request, response) {
46013
- return response.status(500).send("Not implemented");
45940
+ const project = this.repository.get(getRepositoryContext(request));
45941
+ return response.status(200).send(project);
46014
45942
  }
46015
45943
  post(request, response) {
46016
- const draft = request.body;
46017
- const resource = this.repository.create(
46018
- getRepositoryContext(request),
46019
- draft
46020
- );
46021
- const result = this._expandWithId(request, resource.id);
46022
- return response.status(this.createStatusCode).send(result);
46023
- }
46024
- postWithId(request, response) {
46025
45944
  const updateRequest = request.body;
46026
- const resource = this.repository.get(
46027
- getRepositoryContext(request),
46028
- request.params["id"]
46029
- );
46030
- if (!resource) {
46031
- return response.status(404).send("Not found");
46032
- }
46033
- if (resource.version !== updateRequest.version) {
46034
- return response.status(409).send("Concurrent modification");
45945
+ const project = this.repository.get(getRepositoryContext(request));
45946
+ if (!project) {
45947
+ return response.status(404).send({});
46035
45948
  }
46036
- const updatedResource = this.repository.processUpdateActions(
45949
+ this.repository.processUpdateActions(
46037
45950
  getRepositoryContext(request),
46038
- resource,
45951
+ project,
45952
+ updateRequest.version,
46039
45953
  updateRequest.actions
46040
45954
  );
46041
- const result = this._expandWithId(request, updatedResource.id);
46042
- return response.status(200).send(result);
46043
- }
46044
- postWithKey(request, response) {
46045
- return response.status(500).send("Not implemented");
46046
- }
46047
- _expandWithId(request, resourceId) {
46048
- const result = this.repository.get(
46049
- getRepositoryContext(request),
46050
- resourceId,
46051
- {
46052
- expand: this._parseParam(request.query.expand)
46053
- }
46054
- );
46055
- return result;
46056
- }
46057
- _parseParam(value) {
46058
- if (Array.isArray(value)) {
46059
- return value;
46060
- } else if (value !== void 0) {
46061
- return [`${value}`];
46062
- }
46063
- return void 0;
45955
+ return response.status(200).send({});
46064
45956
  }
46065
45957
  };
46066
45958
 
@@ -46068,14 +45960,16 @@ ${this.pendingMocks().join("\n")}`
46068
45960
  var import_deep_equal = __toESM(require_deep_equal());
46069
45961
 
46070
45962
  // src/repositories/errors.ts
46071
- var checkConcurrentModification = (resource, expectedVersion) => {
46072
- if (resource.version === expectedVersion)
45963
+ var checkConcurrentModification = (currentVersion, expectedVersion, identifier) => {
45964
+ if (currentVersion === expectedVersion)
46073
45965
  return;
46074
- const identifier = resource.id ? resource.id : resource.key;
45966
+ console.error(
45967
+ `Object ${identifier} has a different version than expected. Expected: ${expectedVersion} - Actual: ${currentVersion}.`
45968
+ );
46075
45969
  throw new CommercetoolsError(
46076
45970
  {
46077
- message: `Object ${identifier} has a different version than expected. Expected: ${expectedVersion} - Actual: ${resource.version}.`,
46078
- currentVersion: resource.version,
45971
+ message: `Object ${identifier} has a different version than expected. Expected: ${expectedVersion} - Actual: ${currentVersion}.`,
45972
+ currentVersion,
46079
45973
  code: "ConcurrentModification"
46080
45974
  },
46081
45975
  409
@@ -46088,20 +45982,28 @@ ${this.pendingMocks().join("\n")}`
46088
45982
  this.actions = {};
46089
45983
  this._storage = storage;
46090
45984
  }
46091
- processUpdateActions(context, resource, actions) {
46092
- const modifiedResource = JSON.parse(JSON.stringify(resource));
45985
+ processUpdateActions(context, resource, version2, actions) {
45986
+ const updatedResource = cloneObject(resource);
45987
+ const identifier = resource.id ? resource.id : resource.key;
46093
45988
  actions.forEach((action) => {
46094
45989
  const updateFunc = this.actions[action.action];
46095
45990
  if (!updateFunc) {
46096
45991
  console.error(`No mock implemented for update action ${action.action}`);
46097
- return;
45992
+ throw new Error(
45993
+ `No mock implemented for update action ${action.action}`
45994
+ );
45995
+ }
45996
+ const beforeUpdate = cloneObject(resource);
45997
+ updateFunc(context, updatedResource, action);
45998
+ if (!(0, import_deep_equal.default)(beforeUpdate, updatedResource)) {
45999
+ checkConcurrentModification(resource.version, version2, identifier);
46000
+ updatedResource.version += 1;
46098
46001
  }
46099
- updateFunc(context, modifiedResource, action);
46100
46002
  });
46101
- if (!(0, import_deep_equal.default)(modifiedResource, resource)) {
46102
- this.save(context, modifiedResource);
46003
+ if (resource.version != updatedResource.version) {
46004
+ this.saveUpdate(context, version2, updatedResource);
46103
46005
  }
46104
- const result = this.postProcessResource(modifiedResource);
46006
+ const result = this.postProcessResource(updatedResource);
46105
46007
  if (!result) {
46106
46008
  throw new Error("invalid post process action");
46107
46009
  }
@@ -46114,7 +46016,6 @@ ${this.pendingMocks().join("\n")}`
46114
46016
  var AbstractResourceRepository = class extends AbstractRepository {
46115
46017
  constructor(storage) {
46116
46018
  super(storage);
46117
- this._storage.assertStorage(this.getTypeId());
46118
46019
  }
46119
46020
  query(context, params = {}) {
46120
46021
  const result = this._storage.query(context.projectKey, this.getTypeId(), {
@@ -46127,8 +46028,13 @@ ${this.pendingMocks().join("\n")}`
46127
46028
  return result;
46128
46029
  }
46129
46030
  get(context, id, params = {}) {
46130
- const resource = this._storage.get(context.projectKey, this.getTypeId(), id, params);
46131
- return this.postProcessResource(resource);
46031
+ const resource = this._storage.get(
46032
+ context.projectKey,
46033
+ this.getTypeId(),
46034
+ id,
46035
+ params
46036
+ );
46037
+ return resource ? this.postProcessResource(resource) : null;
46132
46038
  }
46133
46039
  getByKey(context, key, params = {}) {
46134
46040
  const resource = this._storage.getByKey(
@@ -46137,7 +46043,7 @@ ${this.pendingMocks().join("\n")}`
46137
46043
  key,
46138
46044
  params
46139
46045
  );
46140
- return this.postProcessResource(resource);
46046
+ return resource ? this.postProcessResource(resource) : null;
46141
46047
  }
46142
46048
  delete(context, id, params = {}) {
46143
46049
  const resource = this._storage.delete(
@@ -46146,117 +46052,34 @@ ${this.pendingMocks().join("\n")}`
46146
46052
  id,
46147
46053
  params
46148
46054
  );
46149
- return this.postProcessResource(resource);
46055
+ return resource ? this.postProcessResource(resource) : null;
46150
46056
  }
46151
- save(context, resource) {
46152
- const current = this.get(context, resource.id);
46153
- if (current) {
46154
- checkConcurrentModification(current, resource.version);
46155
- } else {
46156
- if (resource.version !== 0) {
46157
- throw new CommercetoolsError(
46158
- {
46159
- code: "InvalidOperation",
46160
- message: "version on create must be 0"
46161
- },
46162
- 400
46163
- );
46164
- }
46165
- }
46166
- resource.version += 1;
46057
+ saveNew(context, resource) {
46058
+ resource.version = 1;
46167
46059
  this._storage.add(context.projectKey, this.getTypeId(), resource);
46168
46060
  }
46169
- };
46170
-
46171
- // src/repositories/cart-discount.ts
46172
- var CartDiscountRepository = class extends AbstractResourceRepository {
46173
- constructor() {
46174
- super(...arguments);
46175
- this.actions = {
46176
- setKey: (context, resource, { key }) => {
46177
- resource.key = key;
46178
- },
46179
- setDescription: (context, resource, { description }) => {
46180
- resource.description = description;
46181
- },
46182
- setValidFrom: (context, resource, { validFrom }) => {
46183
- resource.validFrom = validFrom;
46184
- },
46185
- setValidUntil: (context, resource, { validUntil }) => {
46186
- resource.validUntil = validUntil;
46187
- },
46188
- setValidFromAndUntil: (context, resource, { validFrom, validUntil }) => {
46189
- resource.validFrom = validFrom;
46190
- resource.validUntil = validUntil;
46191
- },
46192
- changeSortOrder: (context, resource, { sortOrder }) => {
46193
- resource.sortOrder = sortOrder;
46194
- },
46195
- changeIsActive: (context, resource, { isActive }) => {
46196
- resource.isActive = isActive;
46197
- }
46198
- };
46199
- }
46200
- getTypeId() {
46201
- return "cart-discount";
46202
- }
46203
- create(context, draft) {
46204
- const resource = {
46205
- ...getBaseResourceProperties(),
46206
- key: draft.key,
46207
- description: draft.description,
46208
- cartPredicate: draft.cartPredicate,
46209
- isActive: draft.isActive || false,
46210
- name: draft.name,
46211
- references: [],
46212
- target: draft.target,
46213
- requiresDiscountCode: draft.requiresDiscountCode || false,
46214
- sortOrder: draft.sortOrder,
46215
- stackingMode: draft.stackingMode || "Stacking",
46216
- validFrom: draft.validFrom,
46217
- validUntil: draft.validUntil,
46218
- value: this.transformValueDraft(draft.value)
46219
- };
46220
- this.save(context, resource);
46221
- return resource;
46222
- }
46223
- transformValueDraft(value) {
46224
- switch (value.type) {
46225
- case "absolute": {
46226
- return {
46227
- type: "absolute",
46228
- money: value.money.map(createTypedMoney)
46229
- };
46230
- }
46231
- case "fixed": {
46232
- return {
46233
- type: "fixed",
46234
- money: value.money.map(createTypedMoney)
46235
- };
46236
- }
46237
- case "giftLineItem": {
46238
- return {
46239
- ...value
46240
- };
46241
- }
46242
- case "relative": {
46243
- return {
46244
- ...value
46245
- };
46246
- }
46061
+ saveUpdate(context, version2, resource) {
46062
+ const current = this._storage.get(
46063
+ context.projectKey,
46064
+ this.getTypeId(),
46065
+ resource.id
46066
+ );
46067
+ if (!current) {
46068
+ throw new CommercetoolsError(
46069
+ {
46070
+ code: "ResourceNotFound",
46071
+ message: "Resource not found while updating"
46072
+ },
46073
+ 400
46074
+ );
46247
46075
  }
46248
- return value;
46249
- }
46250
- };
46251
-
46252
- // src/services/cart-discount.ts
46253
- var CartDiscountService = class extends AbstractService {
46254
- constructor(parent, storage) {
46255
- super(parent);
46256
- this.repository = new CartDiscountRepository(storage);
46257
- }
46258
- getBasePath() {
46259
- return "cart-discounts";
46076
+ checkConcurrentModification(current.version, version2, resource.id);
46077
+ if (current.version === resource.version) {
46078
+ throw new Error("Internal error: no changes to save");
46079
+ }
46080
+ resource.lastModifiedAt = new Date().toISOString();
46081
+ this._storage.add(context.projectKey, this.getTypeId(), resource);
46082
+ return resource;
46260
46083
  }
46261
46084
  };
46262
46085
 
@@ -46268,7 +46091,6 @@ ${this.pendingMocks().join("\n")}`
46268
46091
  addLineItem: (context, resource, { productId, variantId, sku, quantity = 1 }) => {
46269
46092
  var _a;
46270
46093
  let product = null;
46271
- let variant;
46272
46094
  if (productId && variantId) {
46273
46095
  product = this._storage.get(
46274
46096
  context.projectKey,
@@ -46292,7 +46114,7 @@ ${this.pendingMocks().join("\n")}`
46292
46114
  message: sku ? `A product containing a variant with SKU '${sku}' not found.` : `A product with ID '${productId}' not found.`
46293
46115
  });
46294
46116
  }
46295
- variant = [
46117
+ const variant = [
46296
46118
  product.masterData.current.masterVariant,
46297
46119
  ...product.masterData.current.variants
46298
46120
  ].find((x) => {
@@ -46369,7 +46191,9 @@ ${this.pendingMocks().join("\n")}`
46369
46191
  }
46370
46192
  const shouldDelete = !quantity || quantity >= lineItem.quantity;
46371
46193
  if (shouldDelete) {
46372
- resource.lineItems = resource.lineItems.filter((x) => x.id !== lineItemId);
46194
+ resource.lineItems = resource.lineItems.filter(
46195
+ (x) => x.id !== lineItemId
46196
+ );
46373
46197
  } else {
46374
46198
  resource.lineItems.map((x) => {
46375
46199
  if (x.id === lineItemId && quantity) {
@@ -46385,19 +46209,24 @@ ${this.pendingMocks().join("\n")}`
46385
46209
  resource.billingAddress = address;
46386
46210
  },
46387
46211
  setShippingMethod: (context, resource, { shippingMethod }) => {
46388
- const resolvedType = this._storage.getByResourceIdentifier(
46389
- context.projectKey,
46390
- shippingMethod
46391
- );
46392
- if (!resolvedType) {
46393
- throw new Error(`Type ${shippingMethod} not found`);
46394
- }
46395
- resource.shippingInfo = {
46396
- shippingMethod: {
46397
- typeId: "shipping-method",
46398
- id: resolvedType.id
46212
+ if (shippingMethod) {
46213
+ const method = this._storage.getByResourceIdentifier(
46214
+ context.projectKey,
46215
+ shippingMethod
46216
+ );
46217
+ if (!method) {
46218
+ throw new Error(`Type ${shippingMethod} not found`);
46399
46219
  }
46400
- };
46220
+ resource.shippingInfo = {
46221
+ shippingMethod: {
46222
+ typeId: "shipping-method",
46223
+ id: method.id
46224
+ },
46225
+ shippingMethodName: method.name
46226
+ };
46227
+ } else {
46228
+ resource.shippingInfo = void 0;
46229
+ }
46401
46230
  },
46402
46231
  setCountry: (context, resource, { country }) => {
46403
46232
  resource.country = country;
@@ -46441,7 +46270,6 @@ ${this.pendingMocks().join("\n")}`
46441
46270
  this.draftLineItemtoLineItem = (projectKey, draftLineItem, currency, country) => {
46442
46271
  const { productId, quantity, variantId, sku } = draftLineItem;
46443
46272
  let product = null;
46444
- let variant;
46445
46273
  if (productId && variantId) {
46446
46274
  product = this._storage.get(projectKey, "product", productId, {});
46447
46275
  } else if (sku) {
@@ -46460,7 +46288,7 @@ ${this.pendingMocks().join("\n")}`
46460
46288
  message: sku ? `A product containing a variant with SKU '${sku}' not found.` : `A product with ID '${productId}' not found.`
46461
46289
  });
46462
46290
  }
46463
- variant = [
46291
+ const variant = [
46464
46292
  product.masterData.current.masterVariant,
46465
46293
  ...product.masterData.current.variants
46466
46294
  ].find((x) => {
@@ -46541,7 +46369,7 @@ ${this.pendingMocks().join("\n")}`
46541
46369
  )
46542
46370
  };
46543
46371
  resource.totalPrice.centAmount = calculateCartTotalPrice(resource);
46544
- this.save(context, resource);
46372
+ this.saveNew(context, resource);
46545
46373
  return resource;
46546
46374
  }
46547
46375
  getActiveCart(projectKey) {
@@ -46571,313 +46399,84 @@ ${this.pendingMocks().join("\n")}`
46571
46399
  var calculateLineItemTotalPrice = (lineItem) => lineItem.price.value.centAmount * lineItem.quantity;
46572
46400
  var calculateCartTotalPrice = (cart) => cart.lineItems.reduce((cur, item) => cur + item.totalPrice.centAmount, 0);
46573
46401
 
46574
- // src/repositories/order.ts
46575
- var import_assert2 = __toESM(__require("assert"));
46576
- var OrderRepository = class extends AbstractResourceRepository {
46402
+ // src/repositories/cart-discount.ts
46403
+ var CartDiscountRepository = class extends AbstractResourceRepository {
46577
46404
  constructor() {
46578
46405
  super(...arguments);
46579
46406
  this.actions = {
46580
- addPayment: (context, resource, { payment }) => {
46581
- const resolvedPayment = this._storage.getByResourceIdentifier(
46582
- context.projectKey,
46583
- payment
46584
- );
46585
- if (!resolvedPayment) {
46586
- throw new Error(`Payment ${payment.id} not found`);
46587
- }
46588
- if (!resource.paymentInfo) {
46589
- resource.paymentInfo = {
46590
- payments: []
46591
- };
46592
- }
46593
- resource.paymentInfo.payments.push({
46594
- typeId: "payment",
46595
- id: payment.id
46596
- });
46597
- },
46598
- changeOrderState: (context, resource, { orderState }) => {
46599
- resource.orderState = orderState;
46600
- },
46601
- changePaymentState: (context, resource, { paymentState }) => {
46602
- resource.paymentState = paymentState;
46603
- },
46604
- transitionState: (context, resource, { state }) => {
46605
- const resolvedType = this._storage.getByResourceIdentifier(
46606
- context.projectKey,
46607
- state
46608
- );
46609
- if (!resolvedType) {
46610
- throw new Error(
46611
- `No state found with key=${state.key} or id=${state.key}`
46612
- );
46613
- }
46614
- resource.state = { typeId: "state", id: resolvedType.id };
46615
- },
46616
- setBillingAddress: (context, resource, { address }) => {
46617
- resource.billingAddress = address;
46618
- },
46619
- setCustomerEmail: (context, resource, { email }) => {
46620
- resource.customerEmail = email;
46407
+ setKey: (context, resource, { key }) => {
46408
+ resource.key = key;
46621
46409
  },
46622
- setCustomField: (context, resource, { name, value }) => {
46623
- if (!resource.custom) {
46624
- throw new Error("Resource has no custom field");
46625
- }
46626
- resource.custom.fields[name] = value;
46410
+ setDescription: (context, resource, { description }) => {
46411
+ resource.description = description;
46627
46412
  },
46628
- setCustomType: (context, resource, { type, fields }) => {
46629
- if (!type) {
46630
- resource.custom = void 0;
46631
- } else {
46632
- const resolvedType = this._storage.getByResourceIdentifier(
46633
- context.projectKey,
46634
- type
46635
- );
46636
- if (!resolvedType) {
46637
- throw new Error(`Type ${type} not found`);
46638
- }
46639
- resource.custom = {
46640
- type: {
46641
- typeId: "type",
46642
- id: resolvedType.id
46643
- },
46644
- fields: fields || []
46645
- };
46646
- }
46413
+ setValidFrom: (context, resource, { validFrom }) => {
46414
+ resource.validFrom = validFrom;
46647
46415
  },
46648
- setLocale: (context, resource, { locale }) => {
46649
- resource.locale = locale;
46416
+ setValidUntil: (context, resource, { validUntil }) => {
46417
+ resource.validUntil = validUntil;
46650
46418
  },
46651
- setOrderNumber: (context, resource, { orderNumber }) => {
46652
- resource.orderNumber = orderNumber;
46419
+ setValidFromAndUntil: (context, resource, { validFrom, validUntil }) => {
46420
+ resource.validFrom = validFrom;
46421
+ resource.validUntil = validUntil;
46653
46422
  },
46654
- setShippingAddress: (context, resource, { address }) => {
46655
- resource.shippingAddress = address;
46423
+ changeSortOrder: (context, resource, { sortOrder }) => {
46424
+ resource.sortOrder = sortOrder;
46656
46425
  },
46657
- setStore: (context, resource, { store }) => {
46658
- if (!store)
46659
- return;
46660
- const resolvedType = this._storage.getByResourceIdentifier(
46661
- context.projectKey,
46662
- store
46663
- );
46664
- if (!resolvedType) {
46665
- throw new Error(`No store found with key=${store.key}`);
46666
- }
46667
- const storeReference = resolvedType;
46668
- resource.store = {
46669
- typeId: "store",
46670
- key: storeReference.key
46671
- };
46426
+ changeIsActive: (context, resource, { isActive }) => {
46427
+ resource.isActive = isActive;
46672
46428
  }
46673
46429
  };
46674
46430
  }
46675
46431
  getTypeId() {
46676
- return "order";
46432
+ return "cart-discount";
46677
46433
  }
46678
46434
  create(context, draft) {
46679
- (0, import_assert2.default)(draft.cart, "draft.cart is missing");
46680
- return this.createFromCart(
46681
- context,
46682
- {
46683
- id: draft.cart.id,
46684
- typeId: "cart"
46685
- },
46686
- draft.orderNumber
46687
- );
46688
- }
46689
- createFromCart(context, cartReference, orderNumber) {
46690
- const cart = this._storage.getByResourceIdentifier(
46691
- context.projectKey,
46692
- cartReference
46693
- );
46694
- if (!cart) {
46695
- throw new Error("Cannot find cart");
46696
- }
46697
- const resource = {
46698
- ...getBaseResourceProperties(),
46699
- orderNumber,
46700
- cart: cartReference,
46701
- orderState: "Open",
46702
- lineItems: [],
46703
- customLineItems: [],
46704
- totalPrice: cart.totalPrice,
46705
- refusedGifts: [],
46706
- origin: "Customer",
46707
- syncInfo: [],
46708
- store: context.storeKey ? {
46709
- key: context.storeKey,
46710
- typeId: "store"
46711
- } : void 0,
46712
- lastMessageSequenceNumber: 0
46713
- };
46714
- this.save(context, resource);
46715
- return resource;
46716
- }
46717
- import(context, draft) {
46718
- var _a, _b;
46719
- (0, import_assert2.default)(this, "OrderRepository not valid");
46720
46435
  const resource = {
46721
46436
  ...getBaseResourceProperties(),
46722
- billingAddress: draft.billingAddress,
46723
- shippingAddress: draft.shippingAddress,
46724
- custom: createCustomFields(
46725
- draft.custom,
46726
- context.projectKey,
46727
- this._storage
46728
- ),
46729
- customerEmail: draft.customerEmail,
46730
- lastMessageSequenceNumber: 0,
46731
- orderNumber: draft.orderNumber,
46732
- orderState: draft.orderState || "Open",
46733
- origin: draft.origin || "Customer",
46734
- paymentState: draft.paymentState,
46735
- refusedGifts: [],
46736
- store: resolveStoreReference(
46737
- draft.store,
46738
- context.projectKey,
46739
- this._storage
46740
- ),
46741
- syncInfo: [],
46742
- lineItems: ((_a = draft.lineItems) == null ? void 0 : _a.map(
46743
- (item) => this.lineItemFromImportDraft.bind(this)(context, item)
46744
- )) || [],
46745
- customLineItems: ((_b = draft.customLineItems) == null ? void 0 : _b.map(
46746
- (item) => this.customLineItemFromImportDraft.bind(this)(context, item)
46747
- )) || [],
46748
- totalPrice: {
46749
- type: "centPrecision",
46750
- ...draft.totalPrice,
46751
- fractionDigits: 2
46752
- }
46437
+ key: draft.key,
46438
+ description: draft.description,
46439
+ cartPredicate: draft.cartPredicate,
46440
+ isActive: draft.isActive || false,
46441
+ name: draft.name,
46442
+ references: [],
46443
+ target: draft.target,
46444
+ requiresDiscountCode: draft.requiresDiscountCode || false,
46445
+ sortOrder: draft.sortOrder,
46446
+ stackingMode: draft.stackingMode || "Stacking",
46447
+ validFrom: draft.validFrom,
46448
+ validUntil: draft.validUntil,
46449
+ value: this.transformValueDraft(draft.value)
46753
46450
  };
46754
- this.save(context, resource);
46451
+ this.saveNew(context, resource);
46755
46452
  return resource;
46756
46453
  }
46757
- lineItemFromImportDraft(context, draft) {
46758
- let product;
46759
- let variant;
46760
- if (draft.variant.sku) {
46761
- variant = {
46762
- id: 0,
46763
- sku: draft.variant.sku
46764
- };
46765
- var items = this._storage.query(context.projectKey, "product", {
46766
- where: [
46767
- `masterData(current(masterVariant(sku="${draft.variant.sku}"))) or masterData(current(variants(sku="${draft.variant.sku}")))`
46768
- ]
46769
- });
46770
- if (items.count !== 1) {
46771
- throw new CommercetoolsError({
46772
- code: "General",
46773
- message: `A product containing a variant with SKU '${draft.variant.sku}' not found.`
46774
- });
46454
+ transformValueDraft(value) {
46455
+ switch (value.type) {
46456
+ case "absolute": {
46457
+ return {
46458
+ type: "absolute",
46459
+ money: value.money.map(createTypedMoney)
46460
+ };
46775
46461
  }
46776
- product = items.results[0];
46777
- if (product.masterData.current.masterVariant.sku === draft.variant.sku) {
46778
- variant = product.masterData.current.masterVariant;
46779
- } else {
46780
- variant = product.masterData.current.variants.find(
46781
- (v) => v.sku === draft.variant.sku
46782
- );
46462
+ case "fixed": {
46463
+ return {
46464
+ type: "fixed",
46465
+ money: value.money.map(createTypedMoney)
46466
+ };
46783
46467
  }
46784
- if (!variant) {
46785
- throw new Error("Internal state error");
46468
+ case "giftLineItem": {
46469
+ return {
46470
+ ...value
46471
+ };
46786
46472
  }
46787
- } else {
46788
- throw new Error("No product found");
46789
- }
46790
- const lineItem = {
46791
- ...getBaseResourceProperties(),
46792
- custom: createCustomFields(
46793
- draft.custom,
46794
- context.projectKey,
46795
- this._storage
46796
- ),
46797
- discountedPricePerQuantity: [],
46798
- lineItemMode: "Standard",
46799
- name: draft.name,
46800
- price: createPrice(draft.price),
46801
- priceMode: "Platform",
46802
- productId: product.id,
46803
- productType: product.productType,
46804
- quantity: draft.quantity,
46805
- state: draft.state || [],
46806
- taxRate: draft.taxRate,
46807
- totalPrice: createTypedMoney(draft.price.value),
46808
- variant: {
46809
- id: variant.id,
46810
- sku: variant.sku,
46811
- price: createPrice(draft.price)
46473
+ case "relative": {
46474
+ return {
46475
+ ...value
46476
+ };
46812
46477
  }
46813
- };
46814
- return lineItem;
46815
- }
46816
- customLineItemFromImportDraft(context, draft) {
46817
- const lineItem = {
46818
- ...getBaseResourceProperties(),
46819
- custom: createCustomFields(
46820
- draft.custom,
46821
- context.projectKey,
46822
- this._storage
46823
- ),
46824
- discountedPricePerQuantity: [],
46825
- money: createTypedMoney(draft.money),
46826
- name: draft.name,
46827
- quantity: draft.quantity,
46828
- slug: draft.slug,
46829
- state: [],
46830
- totalPrice: createTypedMoney(draft.money)
46831
- };
46832
- return lineItem;
46833
- }
46834
- getWithOrderNumber(context, orderNumber, params = {}) {
46835
- const result = this._storage.query(context.projectKey, this.getTypeId(), {
46836
- ...params,
46837
- where: [`orderNumber="${orderNumber}"`]
46838
- });
46839
- if (result.count === 1) {
46840
- return result.results[0];
46841
46478
  }
46842
- if (result.count > 1) {
46843
- throw new Error("Duplicate order numbers");
46844
- }
46845
- return;
46846
- }
46847
- };
46848
-
46849
- // src/services/cart.ts
46850
- var CartService = class extends AbstractService {
46851
- constructor(parent, storage) {
46852
- super(parent);
46853
- this.repository = new CartRepository(storage);
46854
- this.orderRepository = new OrderRepository(storage);
46855
- }
46856
- getBasePath() {
46857
- return "carts";
46858
- }
46859
- extraRoutes(parent) {
46860
- parent.post("/replicate", (request, response) => {
46861
- const context = getRepositoryContext(request);
46862
- const cartOrOrder = request.body.reference.typeId === "order" ? this.orderRepository.get(context, request.body.reference.id) : this.repository.get(context, request.body.reference.id);
46863
- if (!cartOrOrder) {
46864
- return response.status(400).send();
46865
- }
46866
- const cartDraft = {
46867
- ...cartOrOrder,
46868
- currency: cartOrOrder.totalPrice.currencyCode,
46869
- discountCodes: [],
46870
- lineItems: cartOrOrder.lineItems.map((lineItem) => {
46871
- return {
46872
- ...lineItem,
46873
- variantId: lineItem.variant.id,
46874
- sku: lineItem.variant.sku
46875
- };
46876
- })
46877
- };
46878
- const newCart = this.repository.create(context, cartDraft);
46879
- return response.status(200).send(newCart);
46880
- });
46479
+ return value;
46881
46480
  }
46882
46481
  };
46883
46482
 
@@ -46974,43 +46573,30 @@ ${this.pendingMocks().join("\n")}`
46974
46573
  externalId: draft.externalId || "",
46975
46574
  parent: draft.parent ? { typeId: "category", id: draft.parent.id } : void 0,
46976
46575
  ancestors: [],
46977
- assets: ((_a = draft.assets) == null ? void 0 : _a.map((d) => {
46978
- return {
46979
- id: v4(),
46980
- name: d.name,
46981
- description: d.description,
46982
- sources: d.sources,
46983
- tags: d.tags,
46984
- key: d.key,
46985
- custom: createCustomFields(
46986
- draft.custom,
46987
- context.projectKey,
46988
- this._storage
46989
- )
46990
- };
46991
- })) || [],
46576
+ assets: ((_a = draft.assets) == null ? void 0 : _a.map((d) => ({
46577
+ id: v4(),
46578
+ name: d.name,
46579
+ description: d.description,
46580
+ sources: d.sources,
46581
+ tags: d.tags,
46582
+ key: d.key,
46583
+ custom: createCustomFields(
46584
+ draft.custom,
46585
+ context.projectKey,
46586
+ this._storage
46587
+ )
46588
+ }))) || [],
46992
46589
  custom: createCustomFields(
46993
46590
  draft.custom,
46994
46591
  context.projectKey,
46995
46592
  this._storage
46996
46593
  )
46997
46594
  };
46998
- this.save(context, resource);
46595
+ this.saveNew(context, resource);
46999
46596
  return resource;
47000
46597
  }
47001
46598
  };
47002
46599
 
47003
- // src/services/category.ts
47004
- var CategoryServices = class extends AbstractService {
47005
- constructor(parent, storage) {
47006
- super(parent);
47007
- this.repository = new CategoryRepository(storage);
47008
- }
47009
- getBasePath() {
47010
- return "categories";
47011
- }
47012
- };
47013
-
47014
46600
  // src/repositories/channel.ts
47015
46601
  var ChannelRepository = class extends AbstractResourceRepository {
47016
46602
  constructor() {
@@ -47076,19 +46662,130 @@ ${this.pendingMocks().join("\n")}`
47076
46662
  this._storage
47077
46663
  )
47078
46664
  };
47079
- this.save(context, resource);
46665
+ this.saveNew(context, resource);
47080
46666
  return resource;
47081
46667
  }
47082
46668
  };
47083
46669
 
47084
- // src/services/channel.ts
47085
- var ChannelService = class extends AbstractService {
47086
- constructor(parent, storage) {
47087
- super(parent);
47088
- this.repository = new ChannelRepository(storage);
46670
+ // src/repositories/custom-object.ts
46671
+ var CustomObjectRepository = class extends AbstractResourceRepository {
46672
+ getTypeId() {
46673
+ return "key-value-document";
47089
46674
  }
47090
- getBasePath() {
47091
- return "channels";
46675
+ create(context, draft) {
46676
+ const current = this.getWithContainerAndKey(
46677
+ context,
46678
+ draft.container,
46679
+ draft.key
46680
+ );
46681
+ if (current) {
46682
+ if (draft.version) {
46683
+ checkConcurrentModification(current.version, draft.version, current.id);
46684
+ } else {
46685
+ draft.version = current.version;
46686
+ }
46687
+ if (draft.value !== current.value) {
46688
+ const updated = cloneObject(current);
46689
+ updated.value = draft.value;
46690
+ updated.version += 1;
46691
+ this.saveUpdate(context, draft.version, updated);
46692
+ return updated;
46693
+ }
46694
+ return current;
46695
+ } else {
46696
+ if (draft.version) {
46697
+ throw new CommercetoolsError(
46698
+ {
46699
+ code: "InvalidOperation",
46700
+ message: "version on create must be 0"
46701
+ },
46702
+ 400
46703
+ );
46704
+ }
46705
+ const baseProperties = getBaseResourceProperties();
46706
+ const resource = {
46707
+ ...baseProperties,
46708
+ container: draft.container,
46709
+ key: draft.key,
46710
+ value: draft.value
46711
+ };
46712
+ this.saveNew(context, resource);
46713
+ return resource;
46714
+ }
46715
+ }
46716
+ getWithContainerAndKey(context, container, key) {
46717
+ const items = this._storage.all(
46718
+ context.projectKey,
46719
+ this.getTypeId()
46720
+ );
46721
+ return items.find(
46722
+ (item) => item.container === container && item.key === key
46723
+ );
46724
+ }
46725
+ };
46726
+
46727
+ // src/repositories/customer.ts
46728
+ var CustomerRepository = class extends AbstractResourceRepository {
46729
+ constructor() {
46730
+ super(...arguments);
46731
+ this.actions = {
46732
+ changeEmail: (_context, resource, { email }) => {
46733
+ resource.email = email;
46734
+ },
46735
+ setAuthenticationMode: (_context, resource, { authMode, password }) => {
46736
+ if (resource.authenticationMode === authMode) {
46737
+ throw new CommercetoolsError(
46738
+ {
46739
+ code: "InvalidInput",
46740
+ message: `The customer is already using the '${resource.authenticationMode}' authentication mode.`
46741
+ },
46742
+ 400
46743
+ );
46744
+ }
46745
+ resource.authenticationMode = authMode;
46746
+ if (authMode === "ExternalAuth") {
46747
+ delete resource.password;
46748
+ return;
46749
+ }
46750
+ if (authMode === "Password") {
46751
+ resource.password = password ? Buffer.from(password).toString("base64") : void 0;
46752
+ return;
46753
+ }
46754
+ throw new CommercetoolsError(
46755
+ {
46756
+ code: "InvalidJsonInput",
46757
+ message: "Request body does not contain valid JSON.",
46758
+ detailedErrorMessage: `actions -> authMode: Invalid enum value: '${authMode}'. Expected one of: 'Password','ExternalAuth'`
46759
+ },
46760
+ 400
46761
+ );
46762
+ }
46763
+ };
46764
+ }
46765
+ getTypeId() {
46766
+ return "customer";
46767
+ }
46768
+ create(context, draft) {
46769
+ const resource = {
46770
+ ...getBaseResourceProperties(),
46771
+ email: draft.email,
46772
+ password: draft.password ? Buffer.from(draft.password).toString("base64") : void 0,
46773
+ isEmailVerified: draft.isEmailVerified || false,
46774
+ addresses: []
46775
+ };
46776
+ this.saveNew(context, resource);
46777
+ return resource;
46778
+ }
46779
+ getMe(context) {
46780
+ const results = this._storage.query(
46781
+ context.projectKey,
46782
+ this.getTypeId(),
46783
+ {}
46784
+ );
46785
+ if (results.count > 0) {
46786
+ return results.results[0];
46787
+ }
46788
+ return;
47092
46789
  }
47093
46790
  };
47094
46791
 
@@ -47140,183 +46837,13 @@ ${this.pendingMocks().join("\n")}`
47140
46837
  this._storage
47141
46838
  )
47142
46839
  };
47143
- this.save(context, resource);
46840
+ this.saveNew(context, resource);
47144
46841
  return resource;
47145
46842
  }
47146
46843
  };
47147
46844
 
47148
- // src/services/customer-group.ts
47149
- var CustomerGroupService = class extends AbstractService {
47150
- constructor(parent, storage) {
47151
- super(parent);
47152
- this.repository = new CustomerGroupRepository(storage);
47153
- }
47154
- getBasePath() {
47155
- return "customer-groups";
47156
- }
47157
- };
47158
-
47159
- // src/repositories/customer.ts
47160
- var CustomerRepository = class extends AbstractResourceRepository {
47161
- constructor() {
47162
- super(...arguments);
47163
- this.actions = {
47164
- changeEmail: (_context, resource, { email }) => {
47165
- resource.email = email;
47166
- }
47167
- };
47168
- }
47169
- getTypeId() {
47170
- return "customer";
47171
- }
47172
- create(context, draft) {
47173
- const resource = {
47174
- ...getBaseResourceProperties(),
47175
- email: draft.email,
47176
- password: draft.password ? Buffer.from(draft.password).toString("base64") : void 0,
47177
- isEmailVerified: draft.isEmailVerified || false,
47178
- addresses: []
47179
- };
47180
- this.save(context, resource);
47181
- return resource;
47182
- }
47183
- getMe(context) {
47184
- const results = this._storage.query(
47185
- context.projectKey,
47186
- this.getTypeId(),
47187
- {}
47188
- );
47189
- if (results.count > 0) {
47190
- return results.results[0];
47191
- }
47192
- return;
47193
- }
47194
- };
47195
-
47196
- // src/services/customer.ts
47197
- var CustomerService = class extends AbstractService {
47198
- constructor(parent, storage) {
47199
- super(parent);
47200
- this.repository = new CustomerRepository(storage);
47201
- }
47202
- getBasePath() {
47203
- return "customers";
47204
- }
47205
- extraRoutes(parent) {
47206
- parent.post("/password-token", (request, response) => {
47207
- const customer = this.repository.query(getRepositoryContext(request), {
47208
- where: [`email="${request.body.email}"`]
47209
- });
47210
- const ttlMinutes = request.params.ttlMinutes ? +request.params.ttlMinutes : 34560;
47211
- const { version: version2, ...rest } = getBaseResourceProperties();
47212
- return response.status(200).send({
47213
- ...rest,
47214
- customerId: customer.results[0].id,
47215
- expiresAt: new Date(Date.now() + ttlMinutes * 60).toISOString(),
47216
- value: v4()
47217
- });
47218
- });
47219
- }
47220
- };
47221
-
47222
- // src/repositories/custom-object.ts
47223
- var CustomObjectRepository = class extends AbstractResourceRepository {
47224
- getTypeId() {
47225
- return "key-value-document";
47226
- }
47227
- create(context, draft) {
47228
- const current = this.getWithContainerAndKey(
47229
- context,
47230
- draft.container,
47231
- draft.key
47232
- );
47233
- const baseProperties = getBaseResourceProperties();
47234
- if (current) {
47235
- baseProperties.id = current.id;
47236
- if (!draft.version) {
47237
- draft.version = current.version;
47238
- }
47239
- checkConcurrentModification(current, draft.version);
47240
- if (draft.value === current.value) {
47241
- return current;
47242
- }
47243
- baseProperties.version = current.version;
47244
- } else {
47245
- if (draft.version) {
47246
- baseProperties.version = draft.version;
47247
- }
47248
- }
47249
- const resource = {
47250
- ...baseProperties,
47251
- container: draft.container,
47252
- key: draft.key,
47253
- value: draft.value
47254
- };
47255
- this.save(context, resource);
47256
- return resource;
47257
- }
47258
- getWithContainerAndKey(context, container, key) {
47259
- const items = this._storage.all(
47260
- context.projectKey,
47261
- this.getTypeId()
47262
- );
47263
- return items.find((item) => item.container === container && item.key === key);
47264
- }
47265
- };
47266
-
47267
- // src/services/custom-object.ts
47268
- var CustomObjectService = class extends AbstractService {
47269
- constructor(parent, storage) {
47270
- super(parent);
47271
- this.repository = new CustomObjectRepository(storage);
47272
- }
47273
- getBasePath() {
47274
- return "custom-objects";
47275
- }
47276
- extraRoutes(router) {
47277
- router.get("/:container/:key", this.getWithContainerAndKey.bind(this));
47278
- router.post("/:container/:key", this.createWithContainerAndKey.bind(this));
47279
- router.delete("/:container/:key", this.deleteWithContainerAndKey.bind(this));
47280
- }
47281
- getWithContainerAndKey(request, response) {
47282
- const result = this.repository.getWithContainerAndKey(
47283
- getRepositoryContext(request),
47284
- request.params.container,
47285
- request.params.key
47286
- );
47287
- if (!result) {
47288
- return response.status(404).send("Not Found");
47289
- }
47290
- return response.status(200).send(result);
47291
- }
47292
- createWithContainerAndKey(request, response) {
47293
- const draft = {
47294
- ...request.body,
47295
- key: request.params.key,
47296
- container: request.params.container
47297
- };
47298
- const result = this.repository.create(getRepositoryContext(request), draft);
47299
- return response.status(200).send(result);
47300
- }
47301
- deleteWithContainerAndKey(request, response) {
47302
- const current = this.repository.getWithContainerAndKey(
47303
- getRepositoryContext(request),
47304
- request.params.container,
47305
- request.params.key
47306
- );
47307
- if (!current) {
47308
- return response.status(404).send("Not Found");
47309
- }
47310
- const result = this.repository.delete(
47311
- getRepositoryContext(request),
47312
- current.id
47313
- );
47314
- return response.status(200).send(result);
47315
- }
47316
- };
47317
-
47318
- // src/repositories/discount-code.ts
47319
- var DiscountCodeRepository = class extends AbstractResourceRepository {
46845
+ // src/repositories/discount-code.ts
46846
+ var DiscountCodeRepository = class extends AbstractResourceRepository {
47320
46847
  constructor() {
47321
46848
  super(...arguments);
47322
46849
  this.actions = {
@@ -47411,26 +46938,15 @@ ${this.pendingMocks().join("\n")}`
47411
46938
  this._storage
47412
46939
  )
47413
46940
  };
47414
- this.save(context, resource);
46941
+ this.saveNew(context, resource);
47415
46942
  return resource;
47416
46943
  }
47417
46944
  };
47418
46945
 
47419
- // src/services/discount-code.ts
47420
- var DiscountCodeService = class extends AbstractService {
47421
- constructor(parent, storage) {
47422
- super(parent);
47423
- this.repository = new DiscountCodeRepository(storage);
47424
- }
47425
- getBasePath() {
47426
- return "discount-codes";
47427
- }
47428
- };
47429
-
47430
46946
  // src/lib/masking.ts
47431
46947
  var maskSecretValue = (resource, path) => {
47432
46948
  const parts = path.split(".");
47433
- const clone = JSON.parse(JSON.stringify(resource));
46949
+ const clone = cloneObject(resource);
47434
46950
  let val = clone;
47435
46951
  const target = parts.pop();
47436
46952
  for (let i = 0; i < parts.length; i++) {
@@ -47471,16 +46987,14 @@ ${this.pendingMocks().join("\n")}`
47471
46987
  postProcessResource(resource) {
47472
46988
  var _a;
47473
46989
  if (resource) {
47474
- if (resource.destination.type === "HTTP" && ((_a = resource.destination.authentication) == null ? void 0 : _a.type) === "AuthorizationHeader") {
46990
+ const extension = resource;
46991
+ if (extension.destination.type === "HTTP" && ((_a = extension.destination.authentication) == null ? void 0 : _a.type) === "AuthorizationHeader") {
47475
46992
  return maskSecretValue(
47476
- resource,
46993
+ extension,
47477
46994
  "destination.authentication.headerValue"
47478
46995
  );
47479
- } else if (resource.destination.type == "AWSLambda") {
47480
- return maskSecretValue(
47481
- resource,
47482
- "destination.accessSecret"
47483
- );
46996
+ } else if (extension.destination.type == "AWSLambda") {
46997
+ return maskSecretValue(resource, "destination.accessSecret");
47484
46998
  }
47485
46999
  }
47486
47000
  return resource;
@@ -47493,22 +47007,11 @@ ${this.pendingMocks().join("\n")}`
47493
47007
  destination: draft.destination,
47494
47008
  triggers: draft.triggers
47495
47009
  };
47496
- this.save(context, resource);
47010
+ this.saveNew(context, resource);
47497
47011
  return resource;
47498
47012
  }
47499
47013
  };
47500
47014
 
47501
- // src/services/extension.ts
47502
- var ExtensionServices = class extends AbstractService {
47503
- constructor(parent, storage) {
47504
- super(parent);
47505
- this.repository = new ExtensionRepository(storage);
47506
- }
47507
- getBasePath() {
47508
- return "extensions";
47509
- }
47510
- };
47511
-
47512
47015
  // src/repositories/inventory-entry.ts
47513
47016
  var InventoryEntryRepository = class extends AbstractResourceRepository {
47514
47017
  constructor() {
@@ -47575,50 +47078,298 @@ ${this.pendingMocks().join("\n")}`
47575
47078
  this._storage
47576
47079
  )
47577
47080
  };
47578
- this.save(context, resource);
47081
+ this.saveNew(context, resource);
47579
47082
  return resource;
47580
47083
  }
47581
47084
  };
47582
47085
 
47583
- // src/services/inventory-entry.ts
47584
- var InventoryEntryService = class extends AbstractService {
47585
- constructor(parent, storage) {
47586
- super(parent);
47587
- this.repository = new InventoryEntryRepository(storage);
47086
+ // src/repositories/my-order.ts
47087
+ var import_assert3 = __toESM(__require("assert"));
47088
+
47089
+ // src/repositories/order.ts
47090
+ var import_assert2 = __toESM(__require("assert"));
47091
+ var OrderRepository = class extends AbstractResourceRepository {
47092
+ constructor() {
47093
+ super(...arguments);
47094
+ this.actions = {
47095
+ addPayment: (context, resource, { payment }) => {
47096
+ const resolvedPayment = this._storage.getByResourceIdentifier(
47097
+ context.projectKey,
47098
+ payment
47099
+ );
47100
+ if (!resolvedPayment) {
47101
+ throw new Error(`Payment ${payment.id} not found`);
47102
+ }
47103
+ if (!resource.paymentInfo) {
47104
+ resource.paymentInfo = {
47105
+ payments: []
47106
+ };
47107
+ }
47108
+ resource.paymentInfo.payments.push({
47109
+ typeId: "payment",
47110
+ id: payment.id
47111
+ });
47112
+ },
47113
+ changeOrderState: (context, resource, { orderState }) => {
47114
+ resource.orderState = orderState;
47115
+ },
47116
+ changePaymentState: (context, resource, { paymentState }) => {
47117
+ resource.paymentState = paymentState;
47118
+ },
47119
+ transitionState: (context, resource, { state }) => {
47120
+ const resolvedType = this._storage.getByResourceIdentifier(
47121
+ context.projectKey,
47122
+ state
47123
+ );
47124
+ if (!resolvedType) {
47125
+ throw new Error(
47126
+ `No state found with key=${state.key} or id=${state.key}`
47127
+ );
47128
+ }
47129
+ resource.state = { typeId: "state", id: resolvedType.id };
47130
+ },
47131
+ setBillingAddress: (context, resource, { address }) => {
47132
+ resource.billingAddress = address;
47133
+ },
47134
+ setCustomerEmail: (context, resource, { email }) => {
47135
+ resource.customerEmail = email;
47136
+ },
47137
+ setCustomField: (context, resource, { name, value }) => {
47138
+ if (!resource.custom) {
47139
+ throw new Error("Resource has no custom field");
47140
+ }
47141
+ resource.custom.fields[name] = value;
47142
+ },
47143
+ setCustomType: (context, resource, { type, fields }) => {
47144
+ if (!type) {
47145
+ resource.custom = void 0;
47146
+ } else {
47147
+ const resolvedType = this._storage.getByResourceIdentifier(
47148
+ context.projectKey,
47149
+ type
47150
+ );
47151
+ if (!resolvedType) {
47152
+ throw new Error(`Type ${type} not found`);
47153
+ }
47154
+ resource.custom = {
47155
+ type: {
47156
+ typeId: "type",
47157
+ id: resolvedType.id
47158
+ },
47159
+ fields: fields || []
47160
+ };
47161
+ }
47162
+ },
47163
+ setLocale: (context, resource, { locale }) => {
47164
+ resource.locale = locale;
47165
+ },
47166
+ setOrderNumber: (context, resource, { orderNumber }) => {
47167
+ resource.orderNumber = orderNumber;
47168
+ },
47169
+ setShippingAddress: (context, resource, { address }) => {
47170
+ resource.shippingAddress = address;
47171
+ },
47172
+ setStore: (context, resource, { store }) => {
47173
+ if (!store)
47174
+ return;
47175
+ const resolvedType = this._storage.getByResourceIdentifier(
47176
+ context.projectKey,
47177
+ store
47178
+ );
47179
+ if (!resolvedType) {
47180
+ throw new Error(`No store found with key=${store.key}`);
47181
+ }
47182
+ const storeReference = resolvedType;
47183
+ resource.store = {
47184
+ typeId: "store",
47185
+ key: storeReference.key
47186
+ };
47187
+ }
47188
+ };
47588
47189
  }
47589
- getBasePath() {
47590
- return "inventory";
47190
+ getTypeId() {
47191
+ return "order";
47591
47192
  }
47592
- };
47593
-
47594
- // src/services/my-cart.ts
47595
- var import_express3 = __toESM(require_express2());
47596
- var MyCartService = class extends AbstractService {
47597
- constructor(parent, storage) {
47598
- super(parent);
47599
- this.repository = new CartRepository(storage);
47193
+ create(context, draft) {
47194
+ (0, import_assert2.default)(draft.cart, "draft.cart is missing");
47195
+ return this.createFromCart(
47196
+ context,
47197
+ {
47198
+ id: draft.cart.id,
47199
+ typeId: "cart"
47200
+ },
47201
+ draft.orderNumber
47202
+ );
47600
47203
  }
47601
- getBasePath() {
47602
- return "me";
47204
+ createFromCart(context, cartReference, orderNumber) {
47205
+ const cart = this._storage.getByResourceIdentifier(
47206
+ context.projectKey,
47207
+ cartReference
47208
+ );
47209
+ if (!cart) {
47210
+ throw new Error("Cannot find cart");
47211
+ }
47212
+ const resource = {
47213
+ ...getBaseResourceProperties(),
47214
+ orderNumber,
47215
+ cart: cartReference,
47216
+ orderState: "Open",
47217
+ lineItems: [],
47218
+ customLineItems: [],
47219
+ totalPrice: cart.totalPrice,
47220
+ refusedGifts: [],
47221
+ origin: "Customer",
47222
+ syncInfo: [],
47223
+ store: context.storeKey ? {
47224
+ key: context.storeKey,
47225
+ typeId: "store"
47226
+ } : void 0,
47227
+ lastMessageSequenceNumber: 0
47228
+ };
47229
+ this.saveNew(context, resource);
47230
+ return resource;
47603
47231
  }
47604
- registerRoutes(parent) {
47605
- const basePath = this.getBasePath();
47606
- const router = (0, import_express3.Router)({ mergeParams: true });
47607
- this.extraRoutes(router);
47608
- router.get("/active-cart", this.activeCart.bind(this));
47609
- router.get("/carts/", this.get.bind(this));
47610
- router.get("/carts/:id", this.getWithId.bind(this));
47611
- router.delete("/carts/:id", this.deletewithId.bind(this));
47612
- router.post("/carts/", this.post.bind(this));
47613
- router.post("/carts/:id", this.postWithId.bind(this));
47614
- parent.use(`/${basePath}`, router);
47232
+ import(context, draft) {
47233
+ var _a, _b;
47234
+ (0, import_assert2.default)(this, "OrderRepository not valid");
47235
+ const resource = {
47236
+ ...getBaseResourceProperties(),
47237
+ billingAddress: draft.billingAddress,
47238
+ shippingAddress: draft.shippingAddress,
47239
+ custom: createCustomFields(
47240
+ draft.custom,
47241
+ context.projectKey,
47242
+ this._storage
47243
+ ),
47244
+ customerEmail: draft.customerEmail,
47245
+ lastMessageSequenceNumber: 0,
47246
+ orderNumber: draft.orderNumber,
47247
+ orderState: draft.orderState || "Open",
47248
+ origin: draft.origin || "Customer",
47249
+ paymentState: draft.paymentState,
47250
+ refusedGifts: [],
47251
+ store: resolveStoreReference(
47252
+ draft.store,
47253
+ context.projectKey,
47254
+ this._storage
47255
+ ),
47256
+ syncInfo: [],
47257
+ lineItems: ((_a = draft.lineItems) == null ? void 0 : _a.map(
47258
+ (item) => this.lineItemFromImportDraft.bind(this)(context, item)
47259
+ )) || [],
47260
+ customLineItems: ((_b = draft.customLineItems) == null ? void 0 : _b.map(
47261
+ (item) => this.customLineItemFromImportDraft.bind(this)(context, item)
47262
+ )) || [],
47263
+ totalPrice: {
47264
+ type: "centPrecision",
47265
+ ...draft.totalPrice,
47266
+ fractionDigits: 2
47267
+ }
47268
+ };
47269
+ this.saveNew(context, resource);
47270
+ return resource;
47615
47271
  }
47616
- activeCart(request, response) {
47617
- const resource = this.repository.getActiveCart(request.params.projectKey);
47618
- if (!resource) {
47619
- return response.status(404).send("Not found");
47272
+ lineItemFromImportDraft(context, draft) {
47273
+ let product;
47274
+ let variant;
47275
+ if (draft.variant.sku) {
47276
+ variant = {
47277
+ id: 0,
47278
+ sku: draft.variant.sku
47279
+ };
47280
+ const items = this._storage.query(context.projectKey, "product", {
47281
+ where: [
47282
+ `masterData(current(masterVariant(sku="${draft.variant.sku}"))) or masterData(current(variants(sku="${draft.variant.sku}")))`
47283
+ ]
47284
+ });
47285
+ if (items.count !== 1) {
47286
+ throw new CommercetoolsError({
47287
+ code: "General",
47288
+ message: `A product containing a variant with SKU '${draft.variant.sku}' not found.`
47289
+ });
47290
+ }
47291
+ product = items.results[0];
47292
+ if (product.masterData.current.masterVariant.sku === draft.variant.sku) {
47293
+ variant = product.masterData.current.masterVariant;
47294
+ } else {
47295
+ variant = product.masterData.current.variants.find(
47296
+ (v) => v.sku === draft.variant.sku
47297
+ );
47298
+ }
47299
+ if (!variant) {
47300
+ throw new Error("Internal state error");
47301
+ }
47302
+ } else {
47303
+ throw new Error("No product found");
47620
47304
  }
47621
- return response.status(200).send(resource);
47305
+ const lineItem = {
47306
+ ...getBaseResourceProperties(),
47307
+ custom: createCustomFields(
47308
+ draft.custom,
47309
+ context.projectKey,
47310
+ this._storage
47311
+ ),
47312
+ discountedPricePerQuantity: [],
47313
+ lineItemMode: "Standard",
47314
+ name: draft.name,
47315
+ price: createPrice(draft.price),
47316
+ priceMode: "Platform",
47317
+ productId: product.id,
47318
+ productType: product.productType,
47319
+ quantity: draft.quantity,
47320
+ state: draft.state || [],
47321
+ taxRate: draft.taxRate,
47322
+ totalPrice: createTypedMoney(draft.price.value),
47323
+ variant: {
47324
+ id: variant.id,
47325
+ sku: variant.sku,
47326
+ price: createPrice(draft.price)
47327
+ }
47328
+ };
47329
+ return lineItem;
47330
+ }
47331
+ customLineItemFromImportDraft(context, draft) {
47332
+ const lineItem = {
47333
+ ...getBaseResourceProperties(),
47334
+ custom: createCustomFields(
47335
+ draft.custom,
47336
+ context.projectKey,
47337
+ this._storage
47338
+ ),
47339
+ discountedPricePerQuantity: [],
47340
+ money: createTypedMoney(draft.money),
47341
+ name: draft.name,
47342
+ quantity: draft.quantity,
47343
+ slug: draft.slug,
47344
+ state: [],
47345
+ totalPrice: createTypedMoney(draft.money)
47346
+ };
47347
+ return lineItem;
47348
+ }
47349
+ getWithOrderNumber(context, orderNumber, params = {}) {
47350
+ const result = this._storage.query(context.projectKey, this.getTypeId(), {
47351
+ ...params,
47352
+ where: [`orderNumber="${orderNumber}"`]
47353
+ });
47354
+ if (result.count === 1) {
47355
+ return result.results[0];
47356
+ }
47357
+ if (result.count > 1) {
47358
+ throw new Error("Duplicate order numbers");
47359
+ }
47360
+ return;
47361
+ }
47362
+ };
47363
+
47364
+ // src/repositories/my-order.ts
47365
+ var MyOrderRepository = class extends OrderRepository {
47366
+ create(context, draft) {
47367
+ (0, import_assert3.default)(draft.id, "draft.id is missing");
47368
+ const cartIdentifier = {
47369
+ id: draft.id,
47370
+ typeId: "cart"
47371
+ };
47372
+ return this.createFromCart(context, cartIdentifier);
47622
47373
  }
47623
47374
  };
47624
47375
 
@@ -47719,98 +47470,210 @@ ${this.pendingMocks().join("\n")}`
47719
47470
  this._storage
47720
47471
  )
47721
47472
  };
47722
- this.save(context, resource);
47473
+ this.saveNew(context, resource);
47723
47474
  return resource;
47724
47475
  }
47725
47476
  };
47726
47477
 
47727
- // src/services/my-payment.ts
47728
- var MyPaymentService = class extends AbstractService {
47729
- constructor(parent, storage) {
47730
- super(parent);
47731
- this.repository = new PaymentRepository(storage);
47732
- }
47733
- getBasePath() {
47734
- return "me/payments";
47735
- }
47736
- };
47737
-
47738
- // src/services/order.ts
47739
- var OrderService = class extends AbstractService {
47740
- constructor(parent, storage) {
47741
- super(parent);
47742
- this.repository = new OrderRepository(storage);
47743
- }
47744
- getBasePath() {
47745
- return "orders";
47746
- }
47747
- extraRoutes(router) {
47748
- router.post("/import", this.import.bind(this));
47749
- router.get("/order-number=:orderNumber", this.getWithOrderNumber.bind(this));
47750
- }
47751
- import(request, response) {
47752
- const importDraft = request.body;
47753
- const resource = this.repository.import(
47754
- getRepositoryContext(request),
47755
- importDraft
47756
- );
47757
- return response.status(200).send(resource);
47758
- }
47759
- getWithOrderNumber(request, response) {
47760
- const resource = this.repository.getWithOrderNumber(
47761
- getRepositoryContext(request),
47762
- request.params.orderNumber,
47763
- request.query
47764
- );
47765
- if (resource) {
47766
- return response.status(200).send(resource);
47767
- }
47768
- return response.status(404).send("Not found");
47769
- }
47770
- };
47771
-
47772
- // src/services/payment.ts
47773
- var PaymentService = class extends AbstractService {
47774
- constructor(parent, storage) {
47775
- super(parent);
47776
- this.repository = new PaymentRepository(storage);
47777
- }
47778
- getBasePath() {
47779
- return "payments";
47780
- }
47781
- };
47782
-
47783
- // src/repositories/product-discount.ts
47784
- var ProductDiscountRepository = class extends AbstractResourceRepository {
47478
+ // src/repositories/product.ts
47479
+ var import_deep_equal2 = __toESM(require_deep_equal());
47480
+ var ProductRepository = class extends AbstractResourceRepository {
47785
47481
  constructor() {
47786
47482
  super(...arguments);
47787
47483
  this.actions = {
47788
- setKey: (context, resource, { key }) => {
47789
- resource.key = key;
47790
- },
47791
- setDescription: (context, resource, { description }) => {
47792
- if (description && Object.keys(description).length > 0) {
47793
- resource.description = description;
47794
- } else {
47795
- resource.description = void 0;
47796
- }
47797
- },
47798
- changeName: (context, resource, { name }) => {
47799
- resource.name = name;
47800
- },
47801
- changeValue: (context, resource, { value }) => {
47802
- resource.value = this.transformValueDraft(value);
47484
+ publish: (context, resource, { scope }) => {
47485
+ resource.masterData.current = resource.masterData.staged;
47486
+ resource.masterData.published = true;
47487
+ checkForStagedChanges(resource);
47803
47488
  },
47804
- changePredicate: (context, resource, { predicate }) => {
47805
- resource.predicate = predicate;
47489
+ unpublish: (context, resource) => {
47490
+ resource.masterData.published = false;
47491
+ checkForStagedChanges(resource);
47806
47492
  },
47807
- changeSortOrder: (context, resource, { sortOrder }) => {
47808
- resource.sortOrder = sortOrder;
47493
+ setAttribute: (context, resource, { variantId, sku, name, value, staged }) => {
47494
+ const setAttr = (data) => {
47495
+ const { variant, isMasterVariant, variantIndex } = getVariant(
47496
+ data,
47497
+ variantId,
47498
+ sku
47499
+ );
47500
+ if (!variant) {
47501
+ throw new Error(
47502
+ `Variant with id ${variantId} or sku ${sku} not found on product ${resource.id}`
47503
+ );
47504
+ }
47505
+ if (!variant.attributes) {
47506
+ variant.attributes = [];
47507
+ }
47508
+ const existingAttr = variant.attributes.find(
47509
+ (attr) => attr.name === name
47510
+ );
47511
+ if (existingAttr) {
47512
+ existingAttr.value = value;
47513
+ } else {
47514
+ variant.attributes.push({
47515
+ name,
47516
+ value
47517
+ });
47518
+ }
47519
+ if (isMasterVariant) {
47520
+ data.masterVariant = variant;
47521
+ } else {
47522
+ data.variants[variantIndex] = variant;
47523
+ }
47524
+ };
47525
+ const onlyStaged = staged !== void 0 ? staged : true;
47526
+ setAttr(resource.masterData.staged);
47527
+ if (!onlyStaged) {
47528
+ setAttr(resource.masterData.current);
47529
+ }
47530
+ checkForStagedChanges(resource);
47531
+ return resource;
47809
47532
  },
47810
- changeIsActive: (context, resource, { isActive }) => {
47811
- resource.isActive = isActive;
47533
+ "setDescription": (context, resource, { description, staged }) => {
47534
+ const onlyStaged = staged !== void 0 ? staged : true;
47535
+ resource.masterData.staged.description = description;
47536
+ if (!onlyStaged) {
47537
+ resource.masterData.current.description = description;
47538
+ }
47539
+ checkForStagedChanges(resource);
47540
+ return resource;
47812
47541
  },
47813
- setValidFrom: (context, resource, { validFrom }) => {
47542
+ "setKey": (context, resource, { key }) => {
47543
+ resource.key = key;
47544
+ return resource;
47545
+ }
47546
+ };
47547
+ }
47548
+ getTypeId() {
47549
+ return "product";
47550
+ }
47551
+ create(context, draft) {
47552
+ var _a;
47553
+ if (!draft.masterVariant) {
47554
+ throw new Error("Missing master variant");
47555
+ }
47556
+ let productType = void 0;
47557
+ try {
47558
+ productType = getReferenceFromResourceIdentifier(
47559
+ draft.productType,
47560
+ context.projectKey,
47561
+ this._storage
47562
+ );
47563
+ } catch (err) {
47564
+ console.warn(
47565
+ `Error resolving product-type '${draft.productType.id}'. This will be throw an error in later releases.`
47566
+ );
47567
+ productType = {
47568
+ typeId: "product-type",
47569
+ id: draft.productType.id || ""
47570
+ };
47571
+ }
47572
+ const productData = {
47573
+ name: draft.name,
47574
+ slug: draft.slug,
47575
+ categories: [],
47576
+ masterVariant: variantFromDraft(1, draft.masterVariant),
47577
+ variants: ((_a = draft.variants) == null ? void 0 : _a.map(
47578
+ (variant, index) => variantFromDraft(index + 2, variant)
47579
+ )) ?? [],
47580
+ searchKeywords: draft.searchKeywords ?? {}
47581
+ };
47582
+ const resource = {
47583
+ ...getBaseResourceProperties(),
47584
+ key: draft.key,
47585
+ productType,
47586
+ masterData: {
47587
+ current: productData,
47588
+ staged: productData,
47589
+ hasStagedChanges: false,
47590
+ published: draft.publish ?? false
47591
+ }
47592
+ };
47593
+ this.saveNew(context, resource);
47594
+ return resource;
47595
+ }
47596
+ };
47597
+ var checkForStagedChanges = (product) => {
47598
+ if (!product.masterData.staged) {
47599
+ product.masterData.staged = product.masterData.current;
47600
+ }
47601
+ if ((0, import_deep_equal2.default)(product.masterData.current, product.masterData.staged)) {
47602
+ product.masterData.hasStagedChanges = false;
47603
+ } else {
47604
+ product.masterData.hasStagedChanges = true;
47605
+ }
47606
+ };
47607
+ var getVariant = (productData, variantId, sku) => {
47608
+ const variants = [productData.masterVariant, ...productData.variants];
47609
+ const foundVariant = variants.find((variant) => {
47610
+ if (variantId) {
47611
+ return variant.id === variantId;
47612
+ }
47613
+ if (sku) {
47614
+ return variant.sku === sku;
47615
+ }
47616
+ return false;
47617
+ });
47618
+ const isMasterVariant = foundVariant === productData.masterVariant;
47619
+ return {
47620
+ variant: foundVariant,
47621
+ isMasterVariant,
47622
+ variantIndex: !isMasterVariant && foundVariant ? productData.variants.indexOf(foundVariant) : -1
47623
+ };
47624
+ };
47625
+ var variantFromDraft = (variantId, variant) => {
47626
+ var _a;
47627
+ return {
47628
+ id: variantId,
47629
+ sku: variant == null ? void 0 : variant.sku,
47630
+ attributes: (variant == null ? void 0 : variant.attributes) ?? [],
47631
+ prices: (_a = variant == null ? void 0 : variant.prices) == null ? void 0 : _a.map(priceFromDraft),
47632
+ assets: [],
47633
+ images: []
47634
+ };
47635
+ };
47636
+ var priceFromDraft = (draft) => ({
47637
+ id: v4(),
47638
+ value: {
47639
+ currencyCode: draft.value.currencyCode,
47640
+ centAmount: draft.value.centAmount,
47641
+ fractionDigits: 2,
47642
+ type: "centPrecision"
47643
+ }
47644
+ });
47645
+
47646
+ // src/repositories/product-discount.ts
47647
+ var ProductDiscountRepository = class extends AbstractResourceRepository {
47648
+ constructor() {
47649
+ super(...arguments);
47650
+ this.actions = {
47651
+ setKey: (context, resource, { key }) => {
47652
+ resource.key = key;
47653
+ },
47654
+ setDescription: (context, resource, { description }) => {
47655
+ if (description && Object.keys(description).length > 0) {
47656
+ resource.description = description;
47657
+ } else {
47658
+ resource.description = void 0;
47659
+ }
47660
+ },
47661
+ changeName: (context, resource, { name }) => {
47662
+ resource.name = name;
47663
+ },
47664
+ changeValue: (context, resource, { value }) => {
47665
+ resource.value = this.transformValueDraft(value);
47666
+ },
47667
+ changePredicate: (context, resource, { predicate }) => {
47668
+ resource.predicate = predicate;
47669
+ },
47670
+ changeSortOrder: (context, resource, { sortOrder }) => {
47671
+ resource.sortOrder = sortOrder;
47672
+ },
47673
+ changeIsActive: (context, resource, { isActive }) => {
47674
+ resource.isActive = isActive;
47675
+ },
47676
+ setValidFrom: (context, resource, { validFrom }) => {
47814
47677
  resource.validFrom = validFrom;
47815
47678
  },
47816
47679
  setValidUntil: (context, resource, { validUntil }) => {
@@ -47839,7 +47702,7 @@ ${this.pendingMocks().join("\n")}`
47839
47702
  validUntil: draft.validUntil,
47840
47703
  references: []
47841
47704
  };
47842
- this.save(context, resource);
47705
+ this.saveNew(context, resource);
47843
47706
  return resource;
47844
47707
  }
47845
47708
  transformValueDraft(value) {
@@ -47876,52 +47739,23 @@ ${this.pendingMocks().join("\n")}`
47876
47739
  }
47877
47740
  };
47878
47741
 
47879
- // src/services/product-discount.ts
47880
- var ProductDiscountService = class extends AbstractService {
47881
- constructor(parent, storage) {
47882
- super(parent);
47883
- this.repository = new ProductDiscountRepository(storage);
47884
- }
47885
- getBasePath() {
47886
- return "product-discounts";
47887
- }
47888
- extraRoutes(router) {
47889
- router.get("/key=:key", this.getWithKey.bind(this));
47890
- }
47891
- getWithKey(request, response) {
47892
- const resource = this.repository.getWithKey(
47893
- getRepositoryContext(request),
47894
- request.params.key
47895
- );
47896
- if (resource) {
47897
- return response.status(200).send(resource);
47898
- }
47899
- return response.status(404).send("Not found");
47900
- }
47901
- };
47902
-
47903
47742
  // src/lib/projectionSearchFilter.ts
47904
47743
  var import_perplex2 = __toESM(require_perplex());
47905
47744
  var import_pratt2 = __toESM(require_lib5());
47906
- var parseFilterExpression = (filter, staged) => {
47745
+ var parseFilterExpression = (filter) => {
47907
47746
  const exprFunc = generateMatchFunc2(filter);
47908
47747
  const [source] = filter.split(":", 1);
47909
47748
  if (source.startsWith("variants.")) {
47910
- return filterVariants(source, staged, exprFunc);
47749
+ return filterVariants(source, exprFunc);
47911
47750
  }
47912
47751
  return filterProduct(source, exprFunc);
47913
47752
  };
47914
- var getLexer2 = (value) => {
47915
- 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);
47916
- };
47753
+ 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);
47917
47754
  var parseFilter = (filter) => {
47918
47755
  const lexer = getLexer2(filter);
47919
- const parser = new import_pratt2.default(lexer).builder().nud("IDENTIFIER", 100, (t) => {
47920
- return t.token.match;
47921
- }).led(":", 100, ({ left, bp }) => {
47922
- let parsed = parser.parse({ terminals: [bp - 1] });
47923
- let expressions;
47924
- expressions = !Array.isArray(parsed) ? [parsed] : parsed;
47756
+ const parser = new import_pratt2.default(lexer).builder().nud("IDENTIFIER", 100, (t) => t.token.match).led(":", 100, ({ left, bp }) => {
47757
+ const parsed = parser.parse({ terminals: [bp - 1] });
47758
+ const expressions = !Array.isArray(parsed) ? [parsed] : parsed;
47925
47759
  const unique = new Set(expressions.map((expr) => expr.type));
47926
47760
  if (unique.size > 1) {
47927
47761
  throw new Error("Invalid expression");
@@ -47936,9 +47770,7 @@ ${this.pendingMocks().join("\n")}`
47936
47770
  }
47937
47771
  return {
47938
47772
  type: "FilterExpression",
47939
- match: (obj) => {
47940
- return obj === e.value;
47941
- }
47773
+ match: (obj) => obj === e.value
47942
47774
  };
47943
47775
  })
47944
47776
  };
@@ -47948,39 +47780,41 @@ ${this.pendingMocks().join("\n")}`
47948
47780
  type: expressions[0].type,
47949
47781
  children: expressions
47950
47782
  };
47951
- }).nud("STRING", 20, (t) => {
47952
- return {
47783
+ }).nud(
47784
+ "STRING",
47785
+ 20,
47786
+ (t) => ({
47953
47787
  type: "Symbol",
47954
47788
  kind: "string",
47955
47789
  value: t.token.groups[1]
47956
- };
47957
- }).nud("INT", 5, (t) => {
47958
- return {
47790
+ })
47791
+ ).nud(
47792
+ "INT",
47793
+ 5,
47794
+ (t) => ({
47959
47795
  type: "Symbol",
47960
47796
  kind: "int",
47961
47797
  value: parseInt(t.token.match, 10)
47962
- };
47963
- }).nud("STAR", 5, (t) => {
47964
- return {
47965
- type: "Symbol",
47966
- kind: "any",
47967
- value: null
47968
- };
47969
- }).nud("EXISTS", 10, ({ bp }) => {
47970
- return {
47798
+ })
47799
+ ).nud("STAR", 5, (_) => ({
47800
+ type: "Symbol",
47801
+ kind: "any",
47802
+ value: null
47803
+ })).nud(
47804
+ "EXISTS",
47805
+ 10,
47806
+ ({ bp }) => ({
47971
47807
  type: "FilterExpression",
47972
- match: (obj) => {
47973
- return obj !== void 0;
47974
- }
47975
- };
47976
- }).nud("MISSING", 10, ({ bp }) => {
47977
- return {
47808
+ match: (obj) => obj !== void 0
47809
+ })
47810
+ ).nud(
47811
+ "MISSING",
47812
+ 10,
47813
+ ({ bp }) => ({
47978
47814
  type: "FilterExpression",
47979
- match: (obj) => {
47980
- return obj === void 0;
47981
- }
47982
- };
47983
- }).led("COMMA", 200, ({ left, token, bp }) => {
47815
+ match: (obj) => obj === void 0
47816
+ })
47817
+ ).led("COMMA", 200, ({ left, token, bp }) => {
47984
47818
  const expr = parser.parse({ terminals: [bp - 1] });
47985
47819
  if (Array.isArray(expr)) {
47986
47820
  return [left, ...expr];
@@ -48005,21 +47839,13 @@ ${this.pendingMocks().join("\n")}`
48005
47839
  return ranges.map((range) => {
48006
47840
  let func = void 0;
48007
47841
  if (range.start !== null && range.stop !== null) {
48008
- func = (obj) => {
48009
- return obj >= range.start && obj <= range.stop;
48010
- };
47842
+ func = (obj) => obj >= range.start && obj <= range.stop;
48011
47843
  } else if (range.start === null && range.stop !== null) {
48012
- func = (obj) => {
48013
- return obj <= range.stop;
48014
- };
47844
+ func = (obj) => obj <= range.stop;
48015
47845
  } else if (range.start !== null && range.stop === null) {
48016
- func = (obj) => {
48017
- return obj >= range.start;
48018
- };
47846
+ func = (obj) => obj >= range.start;
48019
47847
  } else {
48020
- func = (obj) => {
48021
- return true;
48022
- };
47848
+ func = (obj) => true;
48023
47849
  }
48024
47850
  return {
48025
47851
  type: "RangeExpression",
@@ -48034,8 +47860,6 @@ ${this.pendingMocks().join("\n")}`
48034
47860
  var generateMatchFunc2 = (filter) => {
48035
47861
  const result = parseFilter(filter);
48036
47862
  if (!result) {
48037
- const lines = filter.split("\n");
48038
- const column = lines[lines.length - 1].length;
48039
47863
  throw new Error(`Syntax error while parsing '${filter}'.`);
48040
47864
  }
48041
47865
  if (result.type == "TermExpression") {
@@ -48056,29 +47880,25 @@ ${this.pendingMocks().join("\n")}`
48056
47880
  }
48057
47881
  return parseFilter(filter);
48058
47882
  };
48059
- var filterProduct = (source, exprFunc) => {
48060
- return (p, markMatchingVariants) => {
48061
- const value = nestedLookup(p, source);
48062
- return exprFunc(value);
48063
- };
47883
+ var filterProduct = (source, exprFunc) => (p, markMatchingVariants) => {
47884
+ const value = nestedLookup(p, source);
47885
+ return exprFunc(value);
48064
47886
  };
48065
- var filterVariants = (source, staged, exprFunc) => {
48066
- return (p, markMatchingVariants) => {
48067
- const [, ...paths] = source.split(".");
48068
- const path = paths.join(".");
48069
- const variants = getVariants(p, staged);
48070
- for (const variant of variants) {
48071
- const value = resolveVariantValue(variant, path);
48072
- if (exprFunc(value)) {
48073
- if (markMatchingVariants) {
48074
- variants.forEach((v) => v.isMatchingVariant = false);
48075
- variant.isMatchingVariant = true;
48076
- }
48077
- return true;
47887
+ var filterVariants = (source, exprFunc) => (p, markMatchingVariants) => {
47888
+ const [, ...paths] = source.split(".");
47889
+ const path = paths.join(".");
47890
+ const variants = getVariants(p);
47891
+ for (const variant of variants) {
47892
+ const value = resolveVariantValue(variant, path);
47893
+ if (exprFunc(value)) {
47894
+ if (markMatchingVariants) {
47895
+ variants.forEach((v) => v.isMatchingVariant = false);
47896
+ variant.isMatchingVariant = true;
48078
47897
  }
47898
+ return true;
48079
47899
  }
48080
- return false;
48081
- };
47900
+ }
47901
+ return false;
48082
47902
  };
48083
47903
  var resolveVariantValue = (obj, path) => {
48084
47904
  if (path === void 0) {
@@ -48103,27 +47923,22 @@ ${this.pendingMocks().join("\n")}`
48103
47923
  }
48104
47924
  return nestedLookup(obj, path);
48105
47925
  };
48106
- var getVariants = (p, staged) => {
48107
- var _a, _b, _c, _d;
48108
- return [
48109
- staged ? (_a = p.masterData.staged) == null ? void 0 : _a.masterVariant : (_b = p.masterData.current) == null ? void 0 : _b.masterVariant,
48110
- ...staged ? (_c = p.masterData.staged) == null ? void 0 : _c.variants : (_d = p.masterData.current) == null ? void 0 : _d.variants
48111
- ];
48112
- };
47926
+ var getVariants = (p) => [
47927
+ p.masterVariant,
47928
+ ...p.variants ?? []
47929
+ ];
48113
47930
 
48114
47931
  // src/priceSelector.ts
48115
47932
  var applyPriceSelector = (products, selector) => {
48116
- var _a, _b, _c, _d, _e;
47933
+ var _a;
48117
47934
  validatePriceSelector(selector);
48118
47935
  for (const product of products) {
48119
47936
  const variants = [
48120
- (_a = product.masterData.staged) == null ? void 0 : _a.masterVariant,
48121
- ...((_b = product.masterData.staged) == null ? void 0 : _b.variants) || [],
48122
- (_c = product.masterData.current) == null ? void 0 : _c.masterVariant,
48123
- ...((_d = product.masterData.current) == null ? void 0 : _d.variants) || []
47937
+ product.masterVariant,
47938
+ ...product.variants ?? []
48124
47939
  ].filter((x) => x != void 0);
48125
47940
  for (const variant of variants) {
48126
- const scopedPrices = ((_e = variant.prices) == null ? void 0 : _e.filter((p) => priceSelectorFilter(p, selector))) ?? [];
47941
+ const scopedPrices = ((_a = variant.prices) == null ? void 0 : _a.filter((p) => priceSelectorFilter(p, selector))) ?? [];
48127
47942
  if (scopedPrices.length > 0) {
48128
47943
  const price = scopedPrices[0];
48129
47944
  variant.scopedPriceDiscounted = false;
@@ -48169,8 +47984,13 @@ ${this.pendingMocks().join("\n")}`
48169
47984
  this._storage = storage;
48170
47985
  }
48171
47986
  search(projectKey, params) {
48172
- let resources = this._storage.all(projectKey, "product").map((r) => JSON.parse(JSON.stringify(r)));
48173
- let markMatchingVariant = params.markMatchingVariants ?? false;
47987
+ let resources = this._storage.all(projectKey, "product").map((r) => this.transform(r, params.staged ?? false)).filter((p) => p !== null).filter((p) => {
47988
+ if (!params.staged) {
47989
+ return p.published;
47990
+ }
47991
+ return true;
47992
+ });
47993
+ const markMatchingVariant = params.markMatchingVariants ?? false;
48174
47994
  applyPriceSelector(resources, {
48175
47995
  country: params.priceCountry,
48176
47996
  channel: params.priceChannel,
@@ -48179,13 +47999,12 @@ ${this.pendingMocks().join("\n")}`
48179
47999
  });
48180
48000
  if (params.filter) {
48181
48001
  try {
48182
- const filters = params.filter.map(
48183
- (f) => parseFilterExpression(f, params.staged ?? false)
48184
- );
48002
+ const filters = params.filter.map(parseFilterExpression);
48185
48003
  resources = resources.filter(
48186
48004
  (resource) => filters.every((f) => f(resource, markMatchingVariant))
48187
48005
  );
48188
48006
  } catch (err) {
48007
+ console.error(err);
48189
48008
  throw new CommercetoolsError(
48190
48009
  {
48191
48010
  code: "InvalidInput",
@@ -48198,9 +48017,7 @@ ${this.pendingMocks().join("\n")}`
48198
48017
  const facets = this.getFacets(params, resources);
48199
48018
  if (params["filter.query"]) {
48200
48019
  try {
48201
- const filters = params["filter.query"].map(
48202
- (f) => parseFilterExpression(f, params.staged ?? false)
48203
- );
48020
+ const filters = params["filter.query"].map(parseFilterExpression);
48204
48021
  resources = resources.filter(
48205
48022
  (resource) => filters.every((f) => f(resource, markMatchingVariant))
48206
48023
  );
@@ -48214,26 +48031,28 @@ ${this.pendingMocks().join("\n")}`
48214
48031
  );
48215
48032
  }
48216
48033
  }
48217
- const totalResources = resources.length;
48218
- const offset = params.offset || 0;
48219
- const limit = params.limit || 20;
48220
- resources = resources.slice(offset, offset + limit);
48221
48034
  if (params.expand !== void 0) {
48222
- resources = resources.map((resource) => {
48223
- return this._storage.expand(projectKey, resource, params.expand);
48224
- });
48035
+ resources = resources.map(
48036
+ (resource) => this._storage.expand(projectKey, resource, params.expand)
48037
+ );
48225
48038
  }
48039
+ const totalResults = resources.length;
48040
+ const offset = params.offset || 0;
48041
+ const limit = params.limit || 20;
48042
+ const results = resources.slice(offset, offset + limit);
48226
48043
  return {
48227
- count: totalResources,
48228
- total: resources.length,
48044
+ count: totalResults,
48045
+ total: results.length,
48229
48046
  offset,
48230
48047
  limit,
48231
- results: resources.map(this.transform),
48048
+ results,
48232
48049
  facets
48233
48050
  };
48234
48051
  }
48235
- transform(product) {
48236
- const obj = product.masterData.current;
48052
+ transform(product, staged) {
48053
+ const obj = !staged ? product.masterData.current : product.masterData.staged;
48054
+ if (!obj)
48055
+ return null;
48237
48056
  return {
48238
48057
  id: product.id,
48239
48058
  createdAt: product.createdAt,
@@ -48247,7 +48066,9 @@ ${this.pendingMocks().join("\n")}`
48247
48066
  categories: obj.categories,
48248
48067
  masterVariant: obj.masterVariant,
48249
48068
  variants: obj.variants,
48250
- productType: product.productType
48069
+ productType: product.productType,
48070
+ hasStagedChanges: product.masterData.hasStagedChanges,
48071
+ published: product.masterData.published
48251
48072
  };
48252
48073
  }
48253
48074
  getFacets(params, products) {
@@ -48258,28 +48079,26 @@ ${this.pendingMocks().join("\n")}`
48258
48079
  for (const facet of params.facet) {
48259
48080
  const expression = generateFacetFunc(facet);
48260
48081
  if (expression.type === "TermExpression") {
48261
- result[facet] = this.termFacet(expression.source, products, staged);
48082
+ result[facet] = this.termFacet(expression.source, products);
48262
48083
  }
48263
48084
  if (expression.type === "RangeExpression") {
48264
48085
  result[expression.source] = this.rangeFacet(
48265
48086
  expression.source,
48266
48087
  expression.children,
48267
- products,
48268
- staged
48088
+ products
48269
48089
  );
48270
48090
  }
48271
48091
  if (expression.type === "FilterExpression") {
48272
48092
  result[expression.source] = this.filterFacet(
48273
48093
  expression.source,
48274
48094
  expression.children,
48275
- products,
48276
- staged
48095
+ products
48277
48096
  );
48278
48097
  }
48279
48098
  }
48280
48099
  return result;
48281
48100
  }
48282
- termFacet(facet, products, staged) {
48101
+ termFacet(facet, products) {
48283
48102
  const result = {
48284
48103
  type: "terms",
48285
48104
  dataType: "text",
@@ -48291,7 +48110,7 @@ ${this.pendingMocks().join("\n")}`
48291
48110
  const terms = {};
48292
48111
  if (facet.startsWith("variants.")) {
48293
48112
  products.forEach((p) => {
48294
- const variants = getVariants(p, staged);
48113
+ const variants = getVariants(p);
48295
48114
  variants.forEach((v) => {
48296
48115
  result.total++;
48297
48116
  let value = resolveVariantValue(v, facet);
@@ -48324,11 +48143,11 @@ ${this.pendingMocks().join("\n")}`
48324
48143
  }
48325
48144
  return result;
48326
48145
  }
48327
- filterFacet(source, filters, products, staged) {
48146
+ filterFacet(source, filters, products) {
48328
48147
  let count = 0;
48329
48148
  if (source.startsWith("variants.")) {
48330
48149
  for (const p of products) {
48331
- for (const v of getVariants(p, staged)) {
48150
+ for (const v of getVariants(p)) {
48332
48151
  const val = resolveVariantValue(v, source);
48333
48152
  if (filters == null ? void 0 : filters.some((f) => f.match(val))) {
48334
48153
  count++;
@@ -48343,12 +48162,12 @@ ${this.pendingMocks().join("\n")}`
48343
48162
  count
48344
48163
  };
48345
48164
  }
48346
- rangeFacet(source, ranges, products, staged) {
48165
+ rangeFacet(source, ranges, products) {
48347
48166
  const counts = (ranges == null ? void 0 : ranges.map((range) => {
48348
48167
  if (source.startsWith("variants.")) {
48349
48168
  const values = [];
48350
48169
  for (const p of products) {
48351
- for (const v of getVariants(p, staged)) {
48170
+ for (const v of getVariants(p)) {
48352
48171
  const val = resolveVariantValue(v, source);
48353
48172
  if (val === void 0) {
48354
48173
  continue;
@@ -48419,209 +48238,24 @@ ${this.pendingMocks().join("\n")}`
48419
48238
  facet: QueryParamsAsArray(query.facet),
48420
48239
  offset: query.offset ? Number(query.offset) : void 0,
48421
48240
  limit: query.limit ? Number(query.limit) : void 0,
48422
- expand: QueryParamsAsArray(query.expand)
48241
+ expand: QueryParamsAsArray(query.expand),
48242
+ staged: query.staged === "true"
48423
48243
  });
48424
48244
  return results;
48425
48245
  }
48426
48246
  };
48427
48247
 
48428
- // src/services/product-projection.ts
48429
- var ProductProjectionService = class extends AbstractService {
48430
- constructor(parent, storage) {
48431
- super(parent);
48432
- this.repository = new ProductProjectionRepository(storage);
48433
- }
48434
- getBasePath() {
48435
- return "product-projections";
48436
- }
48437
- extraRoutes(router) {
48438
- router.get("/search", this.search.bind(this));
48439
- }
48440
- search(request, response) {
48441
- const resource = this.repository.search(
48442
- getRepositoryContext(request),
48443
- request.query
48444
- );
48445
- return response.status(200).send(resource);
48446
- }
48447
- };
48448
-
48449
- // src/repositories/product.ts
48450
- var ProductRepository = class extends AbstractResourceRepository {
48451
- constructor() {
48452
- super(...arguments);
48453
- this.actions = {
48454
- publish: (context, resource, { scope }) => {
48455
- if (resource.masterData.staged) {
48456
- resource.masterData.current = resource.masterData.staged;
48457
- resource.masterData.staged = void 0;
48458
- }
48459
- resource.masterData.hasStagedChanges = false;
48460
- resource.masterData.published = true;
48461
- },
48462
- setAttribute: (context, resource, { variantId, sku, name, value, staged }) => {
48463
- const isStaged = staged !== void 0 ? staged : false;
48464
- const productData = getProductData(resource, isStaged);
48465
- const { variant, isMasterVariant, variantIndex } = getVariant(
48466
- productData,
48467
- variantId,
48468
- sku
48469
- );
48470
- if (!variant) {
48471
- throw new Error(
48472
- `Variant with id ${variantId} or sku ${sku} not found on product ${resource.id}`
48473
- );
48474
- }
48475
- if (!variant.attributes) {
48476
- variant.attributes = [];
48477
- }
48478
- const existingAttr = variant.attributes.find((attr) => attr.name === name);
48479
- if (existingAttr) {
48480
- existingAttr.value = value;
48481
- } else {
48482
- variant.attributes.push({
48483
- name,
48484
- value
48485
- });
48486
- }
48487
- if (isStaged) {
48488
- resource.masterData.staged = productData;
48489
- if (isMasterVariant) {
48490
- resource.masterData.staged.masterVariant = variant;
48491
- } else {
48492
- resource.masterData.staged.variants[variantIndex] = variant;
48493
- }
48494
- resource.masterData.hasStagedChanges = true;
48495
- } else {
48496
- resource.masterData.current = productData;
48497
- if (isMasterVariant) {
48498
- resource.masterData.current.masterVariant = variant;
48499
- } else {
48500
- resource.masterData.current.variants[variantIndex] = variant;
48501
- }
48502
- }
48503
- }
48504
- };
48505
- }
48506
- getTypeId() {
48507
- return "product";
48508
- }
48509
- create(context, draft) {
48510
- var _a;
48511
- if (!draft.masterVariant) {
48512
- throw new Error("Missing master variant");
48513
- }
48514
- let productType = void 0;
48515
- try {
48516
- productType = getReferenceFromResourceIdentifier(
48517
- draft.productType,
48518
- context.projectKey,
48519
- this._storage
48520
- );
48521
- } catch (err) {
48522
- console.warn(
48523
- `Error resolving product-type '${draft.productType.id}'. This will be throw an error in later releases.`
48524
- );
48525
- productType = {
48526
- typeId: "product-type",
48527
- id: draft.productType.id || ""
48528
- };
48529
- }
48530
- const productData = {
48531
- name: draft.name,
48532
- slug: draft.slug,
48533
- categories: [],
48534
- masterVariant: variantFromDraft(1, draft.masterVariant),
48535
- variants: ((_a = draft.variants) == null ? void 0 : _a.map((variant, index) => {
48536
- return variantFromDraft(index + 2, variant);
48537
- })) ?? [],
48538
- searchKeywords: draft.searchKeywords
48539
- };
48540
- const resource = {
48541
- ...getBaseResourceProperties(),
48542
- productType,
48543
- masterData: {
48544
- current: draft.publish ? productData : void 0,
48545
- staged: draft.publish ? void 0 : productData,
48546
- hasStagedChanges: draft.publish ?? true,
48547
- published: draft.publish ?? false
48548
- }
48549
- };
48550
- this.save(context, resource);
48551
- return resource;
48552
- }
48553
- };
48554
- var getProductData = (product, staged) => {
48555
- if (!staged && product.masterData.current) {
48556
- return product.masterData.current;
48557
- }
48558
- return product.masterData.staged;
48559
- };
48560
- var getVariant = (productData, variantId, sku) => {
48561
- const variants = [productData.masterVariant, ...productData.variants];
48562
- const foundVariant = variants.find((variant) => {
48563
- if (variantId) {
48564
- return variant.id === variantId;
48565
- }
48566
- if (sku) {
48567
- return variant.sku === sku;
48568
- }
48569
- return false;
48570
- });
48571
- const isMasterVariant = foundVariant === productData.masterVariant;
48572
- return {
48573
- variant: foundVariant,
48574
- isMasterVariant,
48575
- variantIndex: !isMasterVariant && foundVariant ? productData.variants.indexOf(foundVariant) : -1
48576
- };
48577
- };
48578
- var variantFromDraft = (variantId, variant) => {
48579
- var _a;
48580
- return {
48581
- id: variantId,
48582
- sku: variant == null ? void 0 : variant.sku,
48583
- attributes: (variant == null ? void 0 : variant.attributes) ?? [],
48584
- prices: (_a = variant == null ? void 0 : variant.prices) == null ? void 0 : _a.map(priceFromDraft),
48585
- assets: [],
48586
- images: []
48587
- };
48588
- };
48589
- var priceFromDraft = (draft) => {
48590
- return {
48591
- id: v4(),
48592
- value: {
48593
- currencyCode: draft.value.currencyCode,
48594
- centAmount: draft.value.centAmount,
48595
- fractionDigits: 2,
48596
- type: "centPrecision"
48597
- }
48598
- };
48599
- };
48600
-
48601
- // src/services/product.ts
48602
- var ProductService = class extends AbstractService {
48603
- constructor(parent, storage) {
48604
- super(parent);
48605
- this.repository = new ProductRepository(storage);
48606
- }
48607
- getBasePath() {
48608
- return "products";
48609
- }
48610
- };
48611
-
48612
48248
  // src/repositories/product-type.ts
48613
48249
  var ProductTypeRepository = class extends AbstractResourceRepository {
48614
48250
  constructor() {
48615
48251
  super(...arguments);
48616
- this.attributeDefinitionFromAttributeDefinitionDraft = (_context, draft) => {
48617
- return {
48618
- ...draft,
48619
- attributeConstraint: draft.attributeConstraint ?? "None",
48620
- inputHint: draft.inputHint ?? "SingleLine",
48621
- inputTip: draft.inputTip && Object.keys(draft.inputTip).length > 0 ? draft.inputTip : void 0,
48622
- isSearchable: draft.isSearchable ?? true
48623
- };
48624
- };
48252
+ this.attributeDefinitionFromAttributeDefinitionDraft = (_context, draft) => ({
48253
+ ...draft,
48254
+ attributeConstraint: draft.attributeConstraint ?? "None",
48255
+ inputHint: draft.inputHint ?? "SingleLine",
48256
+ inputTip: draft.inputTip && Object.keys(draft.inputTip).length > 0 ? draft.inputTip : void 0,
48257
+ isSearchable: draft.isSearchable ?? true
48258
+ });
48625
48259
  this.actions = {
48626
48260
  changeLocalizedEnumValueLabel: (context, resource, {
48627
48261
  attributeName,
@@ -48664,7 +48298,9 @@ ${this.pendingMocks().join("\n")}`
48664
48298
  },
48665
48299
  changeAttributeOrder: (context, resource, { attributes }) => {
48666
48300
  var _a;
48667
- const attrs = new Map((_a = resource.attributes) == null ? void 0 : _a.map((item) => [item.name, item]));
48301
+ const attrs = new Map(
48302
+ (_a = resource.attributes) == null ? void 0 : _a.map((item) => [item.name, item])
48303
+ );
48668
48304
  const result = [];
48669
48305
  let current = resource.attributes;
48670
48306
  attributes.forEach((iAttr) => {
@@ -48673,9 +48309,7 @@ ${this.pendingMocks().join("\n")}`
48673
48309
  throw new Error("New attr");
48674
48310
  }
48675
48311
  result.push(attr);
48676
- current = current == null ? void 0 : current.filter((f) => {
48677
- return f.name !== iAttr.name;
48678
- });
48312
+ current = current == null ? void 0 : current.filter((f) => f.name !== iAttr.name);
48679
48313
  });
48680
48314
  resource.attributes = result;
48681
48315
  if (current) {
@@ -48684,25 +48318,21 @@ ${this.pendingMocks().join("\n")}`
48684
48318
  },
48685
48319
  removeAttributeDefinition: (context, resource, { name }) => {
48686
48320
  var _a;
48687
- resource.attributes = (_a = resource.attributes) == null ? void 0 : _a.filter((f) => {
48688
- return f.name !== name;
48689
- });
48321
+ resource.attributes = (_a = resource.attributes) == null ? void 0 : _a.filter((f) => f.name !== name);
48690
48322
  },
48691
48323
  removeEnumValues: (context, resource, { attributeName, keys }) => {
48692
48324
  var _a;
48693
48325
  (_a = resource.attributes) == null ? void 0 : _a.forEach((attr) => {
48694
48326
  if (attr.name == attributeName) {
48695
48327
  if (attr.type.name == "enum") {
48696
- attr.type.values = attr.type.values.filter((v) => {
48697
- return !keys.includes(v.key);
48698
- });
48328
+ attr.type.values = attr.type.values.filter(
48329
+ (v) => !keys.includes(v.key)
48330
+ );
48699
48331
  }
48700
48332
  if (attr.type.name == "set") {
48701
48333
  if (attr.type.elementType.name == "enum") {
48702
48334
  attr.type.elementType.values = attr.type.elementType.values.filter(
48703
- (v) => {
48704
- return !keys.includes(v.key);
48705
- }
48335
+ (v) => !keys.includes(v.key)
48706
48336
  );
48707
48337
  }
48708
48338
  }
@@ -48724,7 +48354,7 @@ ${this.pendingMocks().join("\n")}`
48724
48354
  (a) => this.attributeDefinitionFromAttributeDefinitionDraft(context, a)
48725
48355
  )
48726
48356
  };
48727
- this.save(context, resource);
48357
+ this.saveNew(context, resource);
48728
48358
  return resource;
48729
48359
  }
48730
48360
  getWithKey(context, key) {
@@ -48741,30 +48371,6 @@ ${this.pendingMocks().join("\n")}`
48741
48371
  }
48742
48372
  };
48743
48373
 
48744
- // src/services/product-type.ts
48745
- var ProductTypeService = class extends AbstractService {
48746
- constructor(parent, storage) {
48747
- super(parent);
48748
- this.repository = new ProductTypeRepository(storage);
48749
- }
48750
- getBasePath() {
48751
- return "product-types";
48752
- }
48753
- extraRoutes(router) {
48754
- router.get("/key=:key", this.getWithKey.bind(this));
48755
- }
48756
- getWithKey(request, response) {
48757
- const resource = this.repository.getWithKey(
48758
- getRepositoryContext(request),
48759
- request.params.key
48760
- );
48761
- if (resource) {
48762
- return response.status(200).send(resource);
48763
- }
48764
- return response.status(404).send("Not found");
48765
- }
48766
- };
48767
-
48768
48374
  // src/repositories/project.ts
48769
48375
  var ProjectRepository = class extends AbstractRepository {
48770
48376
  constructor() {
@@ -48826,64 +48432,21 @@ ${this.pendingMocks().join("\n")}`
48826
48432
  }
48827
48433
  postProcessResource(resource) {
48828
48434
  if (resource) {
48829
- return maskSecretValue(
48830
- resource,
48831
- "externalOAuth.authorizationHeader"
48832
- );
48435
+ return maskSecretValue(resource, "externalOAuth.authorizationHeader");
48833
48436
  }
48834
48437
  return resource;
48835
48438
  }
48836
- save(context, resource) {
48837
- const current = this.get(context);
48838
- if (current) {
48839
- checkConcurrentModification(current, resource.version);
48840
- } else {
48841
- if (resource.version !== 0) {
48842
- throw new CommercetoolsError(
48843
- {
48844
- code: "InvalidOperation",
48845
- message: "version on create must be 0"
48846
- },
48847
- 400
48848
- );
48849
- }
48850
- }
48851
- resource.version += 1;
48439
+ saveNew(context, resource) {
48440
+ resource.version = 1;
48852
48441
  this._storage.saveProject(resource);
48853
48442
  }
48854
- };
48855
-
48856
- // src/services/project.ts
48857
- var ProjectService = class {
48858
- constructor(parent, storage) {
48859
- this.repository = new ProjectRepository(storage);
48860
- this.registerRoutes(parent);
48861
- }
48862
- registerRoutes(parent) {
48863
- parent.get("", this.get.bind(this));
48864
- parent.post("", this.post.bind(this));
48865
- }
48866
- get(request, response) {
48867
- const project = this.repository.get(getRepositoryContext(request));
48868
- return response.status(200).send(project);
48869
- }
48870
- post(request, response) {
48871
- const updateRequest = request.body;
48872
- const project = this.repository.get(getRepositoryContext(request));
48873
- if (!project) {
48874
- return response.status(404).send({});
48875
- }
48876
- this.repository.processUpdateActions(
48877
- getRepositoryContext(request),
48878
- project,
48879
- updateRequest.actions
48880
- );
48881
- return response.status(200).send({});
48443
+ saveUpdate(context, version2, resource) {
48444
+ this._storage.saveProject(resource);
48882
48445
  }
48883
48446
  };
48884
48447
 
48885
48448
  // src/repositories/shipping-method.ts
48886
- var import_deep_equal2 = __toESM(require_deep_equal());
48449
+ var import_deep_equal3 = __toESM(require_deep_equal());
48887
48450
  var ShippingMethodRepository = class extends AbstractResourceRepository {
48888
48451
  constructor() {
48889
48452
  super(...arguments);
@@ -48899,13 +48462,11 @@ ${this.pendingMocks().join("\n")}`
48899
48462
  shippingRates: (_a = draft.shippingRates) == null ? void 0 : _a.map(this._transformShippingRate)
48900
48463
  };
48901
48464
  };
48902
- this._transformShippingRate = (rate) => {
48903
- return {
48904
- price: createTypedMoney(rate.price),
48905
- freeAbove: rate.freeAbove && createTypedMoney(rate.freeAbove),
48906
- tiers: rate.tiers || []
48907
- };
48908
- };
48465
+ this._transformShippingRate = (rate) => ({
48466
+ price: createTypedMoney(rate.price),
48467
+ freeAbove: rate.freeAbove && createTypedMoney(rate.freeAbove),
48468
+ tiers: rate.tiers || []
48469
+ });
48909
48470
  this.actions = {
48910
48471
  addShippingRate: (_context, resource, { shippingRate, zone }) => {
48911
48472
  const rate = this._transformShippingRate(shippingRate);
@@ -48927,9 +48488,9 @@ ${this.pendingMocks().join("\n")}`
48927
48488
  const rate = this._transformShippingRate(shippingRate);
48928
48489
  resource.zoneRates.forEach((zoneRate) => {
48929
48490
  if (zoneRate.zone.id === zone.id) {
48930
- zoneRate.shippingRates = zoneRate.shippingRates.filter((otherRate) => {
48931
- return !(0, import_deep_equal2.default)(rate, otherRate);
48932
- });
48491
+ zoneRate.shippingRates = zoneRate.shippingRates.filter(
48492
+ (otherRate) => !(0, import_deep_equal3.default)(rate, otherRate)
48493
+ );
48933
48494
  }
48934
48495
  });
48935
48496
  },
@@ -48948,9 +48509,9 @@ ${this.pendingMocks().join("\n")}`
48948
48509
  });
48949
48510
  },
48950
48511
  removeZone: (_context, resource, { zone }) => {
48951
- resource.zoneRates = resource.zoneRates.filter((zoneRate) => {
48952
- return zoneRate.zone.id !== zone.id;
48953
- });
48512
+ resource.zoneRates = resource.zoneRates.filter(
48513
+ (zoneRate) => zoneRate.zone.id !== zone.id
48514
+ );
48954
48515
  },
48955
48516
  setKey: (_context, resource, { key }) => {
48956
48517
  resource.key = key;
@@ -49015,26 +48576,11 @@ ${this.pendingMocks().join("\n")}`
49015
48576
  this._storage
49016
48577
  )
49017
48578
  };
49018
- this.save(context, resource);
48579
+ this.saveNew(context, resource);
49019
48580
  return resource;
49020
48581
  }
49021
48582
  };
49022
48583
 
49023
- // src/services/shipping-method.ts
49024
- var ShippingMethodService = class extends AbstractService {
49025
- constructor(parent, storage) {
49026
- super(parent);
49027
- this.repository = new ShippingMethodRepository(storage);
49028
- this.registerRoutes(parent);
49029
- }
49030
- getBasePath() {
49031
- return "shipping-methods";
49032
- }
49033
- extraRoutes(parent) {
49034
- parent.get("/matching-cart", this.get.bind(this));
49035
- }
49036
- };
49037
-
49038
48584
  // src/repositories/shopping-list.ts
49039
48585
  var ShoppingListRepository = class extends AbstractResourceRepository {
49040
48586
  getTypeId() {
@@ -49068,22 +48614,11 @@ ${this.pendingMocks().join("\n")}`
49068
48614
  ) : void 0,
49069
48615
  store: ((_b = draft.store) == null ? void 0 : _b.key) ? { typeId: "store", key: draft.store.key } : void 0
49070
48616
  };
49071
- this.save(context, resource);
48617
+ this.saveNew(context, resource);
49072
48618
  return resource;
49073
48619
  }
49074
48620
  };
49075
48621
 
49076
- // src/services/shopping-list.ts
49077
- var ShoppingListService = class extends AbstractService {
49078
- constructor(parent, storage) {
49079
- super(parent);
49080
- this.repository = new ShoppingListRepository(storage);
49081
- }
49082
- getBasePath() {
49083
- return "shopping-lists";
49084
- }
49085
- };
49086
-
49087
48622
  // src/repositories/state.ts
49088
48623
  var StateRepository = class extends AbstractResourceRepository {
49089
48624
  constructor() {
@@ -49102,12 +48637,12 @@ ${this.pendingMocks().join("\n")}`
49102
48637
  resource.roles = roles;
49103
48638
  },
49104
48639
  setTransitions: (context, resource, { transitions }) => {
49105
- resource.transitions = transitions == null ? void 0 : transitions.map((resourceId) => {
49106
- return {
48640
+ resource.transitions = transitions == null ? void 0 : transitions.map(
48641
+ (resourceId) => ({
49107
48642
  id: resourceId.id || "",
49108
48643
  typeId: "state"
49109
- };
49110
- });
48644
+ })
48645
+ );
49111
48646
  }
49112
48647
  };
49113
48648
  }
@@ -49124,22 +48659,11 @@ ${this.pendingMocks().join("\n")}`
49124
48659
  (t) => getReferenceFromResourceIdentifier(t, context.projectKey, this._storage)
49125
48660
  )
49126
48661
  };
49127
- this.save(context, resource);
48662
+ this.saveNew(context, resource);
49128
48663
  return resource;
49129
48664
  }
49130
48665
  };
49131
48666
 
49132
- // src/services/state.ts
49133
- var StateService = class extends AbstractService {
49134
- constructor(parent, storage) {
49135
- super(parent);
49136
- this.repository = new StateRepository(storage);
49137
- }
49138
- getBasePath() {
49139
- return "states";
49140
- }
49141
- };
49142
-
49143
48667
  // src/repositories/store.ts
49144
48668
  var StoreRepository = class extends AbstractResourceRepository {
49145
48669
  constructor() {
@@ -49201,7 +48725,7 @@ ${this.pendingMocks().join("\n")}`
49201
48725
  this._storage
49202
48726
  )
49203
48727
  };
49204
- this.save(context, resource);
48728
+ this.saveNew(context, resource);
49205
48729
  return resource;
49206
48730
  }
49207
48731
  transformChannels(context, channels) {
@@ -49229,30 +48753,6 @@ ${this.pendingMocks().join("\n")}`
49229
48753
  }
49230
48754
  };
49231
48755
 
49232
- // src/services/store.ts
49233
- var StoreService = class extends AbstractService {
49234
- constructor(parent, storage) {
49235
- super(parent);
49236
- this.repository = new StoreRepository(storage);
49237
- }
49238
- getBasePath() {
49239
- return "stores";
49240
- }
49241
- extraRoutes(router) {
49242
- router.get("/key=:key", this.getWithKey.bind(this));
49243
- }
49244
- getWithKey(request, response) {
49245
- const resource = this.repository.getWithKey(
49246
- getRepositoryContext(request),
49247
- request.params.key
49248
- );
49249
- if (resource) {
49250
- return response.status(200).send(resource);
49251
- }
49252
- return response.status(404).send("Not found");
49253
- }
49254
- };
49255
-
49256
48756
  // src/repositories/subscription.ts
49257
48757
  var SubscriptionRepository = class extends AbstractResourceRepository {
49258
48758
  getTypeId() {
@@ -49284,22 +48784,11 @@ ${this.pendingMocks().join("\n")}`
49284
48784
  messages: draft.messages || [],
49285
48785
  status: "Healthy"
49286
48786
  };
49287
- this.save(context, resource);
48787
+ this.saveNew(context, resource);
49288
48788
  return resource;
49289
48789
  }
49290
48790
  };
49291
48791
 
49292
- // src/services/subscription.ts
49293
- var SubscriptionService = class extends AbstractService {
49294
- constructor(parent, storage) {
49295
- super(parent);
49296
- this.repository = new SubscriptionRepository(storage);
49297
- }
49298
- getBasePath() {
49299
- return "subscriptions";
49300
- }
49301
- };
49302
-
49303
48792
  // src/repositories/tax-category.ts
49304
48793
  var TaxCategoryRepository = class extends AbstractResourceRepository {
49305
48794
  constructor() {
@@ -49320,9 +48809,9 @@ ${this.pendingMocks().join("\n")}`
49320
48809
  if (resource.rates === void 0) {
49321
48810
  resource.rates = [];
49322
48811
  }
49323
- resource.rates = resource.rates.filter((taxRate) => {
49324
- return taxRate.id !== taxRateId;
49325
- });
48812
+ resource.rates = resource.rates.filter(
48813
+ (taxRate) => taxRate.id !== taxRateId
48814
+ );
49326
48815
  },
49327
48816
  replaceTaxRate: (context, resource, { taxRateId, taxRate }) => {
49328
48817
  if (resource.rates === void 0) {
@@ -49357,7 +48846,7 @@ ${this.pendingMocks().join("\n")}`
49357
48846
  ...draft,
49358
48847
  rates: ((_a = draft.rates) == null ? void 0 : _a.map(this.taxRateFromTaxRateDraft)) || []
49359
48848
  };
49360
- this.save(context, resource);
48849
+ this.saveNew(context, resource);
49361
48850
  return resource;
49362
48851
  }
49363
48852
  getWithKey(context, key) {
@@ -49374,30 +48863,6 @@ ${this.pendingMocks().join("\n")}`
49374
48863
  }
49375
48864
  };
49376
48865
 
49377
- // src/services/tax-category.ts
49378
- var TaxCategoryService = class extends AbstractService {
49379
- constructor(parent, storage) {
49380
- super(parent);
49381
- this.repository = new TaxCategoryRepository(storage);
49382
- }
49383
- getBasePath() {
49384
- return "tax-categories";
49385
- }
49386
- extraRoutes(router) {
49387
- router.get("/key=:key", this.getWithKey.bind(this));
49388
- }
49389
- getWithKey(request, response) {
49390
- const resource = this.repository.getWithKey(
49391
- getRepositoryContext(request),
49392
- request.params.key
49393
- );
49394
- if (resource) {
49395
- return response.status(200).send(resource);
49396
- }
49397
- return response.status(404).send("Not found");
49398
- }
49399
- };
49400
-
49401
48866
  // src/repositories/type.ts
49402
48867
  var import_lodash = __toESM(require_lodash());
49403
48868
  var TypeRepository = class extends AbstractResourceRepository {
@@ -49408,9 +48873,9 @@ ${this.pendingMocks().join("\n")}`
49408
48873
  resource.fieldDefinitions.push(fieldDefinition);
49409
48874
  },
49410
48875
  removeFieldDefinition: (context, resource, { fieldName }) => {
49411
- resource.fieldDefinitions = resource.fieldDefinitions.filter((f) => {
49412
- return f.name !== fieldName;
49413
- });
48876
+ resource.fieldDefinitions = resource.fieldDefinitions.filter(
48877
+ (f) => f.name !== fieldName
48878
+ );
49414
48879
  },
49415
48880
  setDescription: (context, resource, { description }) => {
49416
48881
  resource.description = description;
@@ -49430,9 +48895,7 @@ ${this.pendingMocks().join("\n")}`
49430
48895
  throw new Error("New field");
49431
48896
  }
49432
48897
  result.push(field);
49433
- current = current.filter((f) => {
49434
- return f.name !== fieldName;
49435
- });
48898
+ current = current.filter((f) => f.name !== fieldName);
49436
48899
  });
49437
48900
  if ((0, import_lodash.isEqual)(
49438
48901
  fieldNames,
@@ -49498,22 +48961,11 @@ ${this.pendingMocks().join("\n")}`
49498
48961
  fieldDefinitions: draft.fieldDefinitions || [],
49499
48962
  description: draft.description
49500
48963
  };
49501
- this.save(context, resource);
48964
+ this.saveNew(context, resource);
49502
48965
  return resource;
49503
48966
  }
49504
48967
  };
49505
48968
 
49506
- // src/services/type.ts
49507
- var TypeService = class extends AbstractService {
49508
- constructor(parent, storage) {
49509
- super(parent);
49510
- this.repository = new TypeRepository(storage);
49511
- }
49512
- getBasePath() {
49513
- return "types";
49514
- }
49515
- };
49516
-
49517
48969
  // src/repositories/zone.ts
49518
48970
  var ZoneRepository = class extends AbstractResourceRepository {
49519
48971
  constructor() {
@@ -49523,9 +48975,9 @@ ${this.pendingMocks().join("\n")}`
49523
48975
  resource.locations.push(location);
49524
48976
  },
49525
48977
  removeLocation: (context, resource, { location }) => {
49526
- resource.locations = resource.locations.filter((loc) => {
49527
- return !(loc.country === location.country && loc.state === location.state);
49528
- });
48978
+ resource.locations = resource.locations.filter(
48979
+ (loc) => !(loc.country === location.country && loc.state === location.state)
48980
+ );
49529
48981
  },
49530
48982
  changeName: (context, resource, { name }) => {
49531
48983
  resource.name = name;
@@ -49549,28 +49001,417 @@ ${this.pendingMocks().join("\n")}`
49549
49001
  name: draft.name,
49550
49002
  description: draft.description
49551
49003
  };
49552
- this.save(context, resource);
49004
+ this.saveNew(context, resource);
49553
49005
  return resource;
49554
49006
  }
49555
49007
  };
49556
49008
 
49557
- // src/services/zone.ts
49558
- var ZoneService = class extends AbstractService {
49559
- constructor(parent, storage) {
49009
+ // src/repositories/index.ts
49010
+ var createRepositories = (storage) => ({
49011
+ category: new CategoryRepository(storage),
49012
+ cart: new CartRepository(storage),
49013
+ "cart-discount": new CartDiscountRepository(storage),
49014
+ customer: new CustomerRepository(storage),
49015
+ channel: new ChannelRepository(storage),
49016
+ "customer-group": new CustomerGroupRepository(storage),
49017
+ "discount-code": new DiscountCodeRepository(storage),
49018
+ extension: new ExtensionRepository(storage),
49019
+ "inventory-entry": new InventoryEntryRepository(storage),
49020
+ "key-value-document": new CustomObjectRepository(storage),
49021
+ order: new OrderRepository(storage),
49022
+ payment: new PaymentRepository(storage),
49023
+ "my-cart": new CartRepository(storage),
49024
+ "my-order": new MyOrderRepository(storage),
49025
+ "my-customer": new CustomerRepository(storage),
49026
+ "my-payment": new PaymentRepository(storage),
49027
+ "shipping-method": new ShippingMethodRepository(storage),
49028
+ "product-type": new ProductTypeRepository(storage),
49029
+ product: new ProductRepository(storage),
49030
+ project: new ProjectRepository(storage),
49031
+ "product-discount": new ProductDiscountRepository(storage),
49032
+ "product-projection": new ProductProjectionRepository(storage),
49033
+ "shopping-list": new ShoppingListRepository(storage),
49034
+ state: new StateRepository(storage),
49035
+ store: new StoreRepository(storage),
49036
+ subscription: new SubscriptionRepository(storage),
49037
+ "tax-category": new TaxCategoryRepository(storage),
49038
+ type: new TypeRepository(storage),
49039
+ zone: new ZoneRepository(storage)
49040
+ });
49041
+
49042
+ // src/services/abstract.ts
49043
+ var import_express2 = __toESM(require_express2());
49044
+ var AbstractService = class {
49045
+ constructor(parent) {
49046
+ this.createStatusCode = 201;
49047
+ this.registerRoutes(parent);
49048
+ }
49049
+ extraRoutes(router) {
49050
+ }
49051
+ registerRoutes(parent) {
49052
+ const basePath = this.getBasePath();
49053
+ const router = (0, import_express2.Router)({ mergeParams: true });
49054
+ this.extraRoutes(router);
49055
+ router.get("/", this.get.bind(this));
49056
+ router.get("/key=:key", this.getWithKey.bind(this));
49057
+ router.get("/:id", this.getWithId.bind(this));
49058
+ router.delete("/key=:key", this.deleteWithKey.bind(this));
49059
+ router.delete("/:id", this.deleteWithId.bind(this));
49060
+ router.post("/", this.post.bind(this));
49061
+ router.post("/key=:key", this.postWithKey.bind(this));
49062
+ router.post("/:id", this.postWithId.bind(this));
49063
+ parent.use(`/${basePath}`, router);
49064
+ }
49065
+ get(request, response) {
49066
+ const limit = this._parseParam(request.query.limit);
49067
+ const offset = this._parseParam(request.query.offset);
49068
+ const result = this.repository.query(getRepositoryContext(request), {
49069
+ expand: this._parseParam(request.query.expand),
49070
+ where: this._parseParam(request.query.where),
49071
+ limit: limit !== void 0 ? Number(limit) : void 0,
49072
+ offset: offset !== void 0 ? Number(offset) : void 0
49073
+ });
49074
+ return response.status(200).send(result);
49075
+ }
49076
+ getWithId(request, response) {
49077
+ const result = this._expandWithId(request, request.params["id"]);
49078
+ if (!result) {
49079
+ return response.status(404).send();
49080
+ }
49081
+ return response.status(200).send(result);
49082
+ }
49083
+ getWithKey(request, response) {
49084
+ const result = this.repository.getByKey(
49085
+ getRepositoryContext(request),
49086
+ request.params["key"],
49087
+ { expand: this._parseParam(request.query.expand) }
49088
+ );
49089
+ if (!result)
49090
+ return response.status(404).send();
49091
+ return response.status(200).send(result);
49092
+ }
49093
+ deleteWithId(request, response) {
49094
+ const result = this.repository.delete(
49095
+ getRepositoryContext(request),
49096
+ request.params["id"],
49097
+ {
49098
+ expand: this._parseParam(request.query.expand)
49099
+ }
49100
+ );
49101
+ if (!result) {
49102
+ return response.status(404).send("Not found");
49103
+ }
49104
+ return response.status(200).send(result);
49105
+ }
49106
+ deleteWithKey(request, response) {
49107
+ const resource = this.repository.getByKey(
49108
+ getRepositoryContext(request),
49109
+ request.params["key"]
49110
+ );
49111
+ if (!resource) {
49112
+ return response.status(404).send("Not found");
49113
+ }
49114
+ const result = this.repository.delete(
49115
+ getRepositoryContext(request),
49116
+ resource.id,
49117
+ {
49118
+ expand: this._parseParam(request.query.expand)
49119
+ }
49120
+ );
49121
+ if (!result) {
49122
+ return response.status(404).send("Not found");
49123
+ }
49124
+ return response.status(200).send(result);
49125
+ }
49126
+ post(request, response) {
49127
+ const draft = request.body;
49128
+ const resource = this.repository.create(
49129
+ getRepositoryContext(request),
49130
+ draft
49131
+ );
49132
+ const result = this._expandWithId(request, resource.id);
49133
+ return response.status(this.createStatusCode).send(result);
49134
+ }
49135
+ postWithId(request, response) {
49136
+ const updateRequest = request.body;
49137
+ const resource = this.repository.get(
49138
+ getRepositoryContext(request),
49139
+ request.params["id"]
49140
+ );
49141
+ if (!resource) {
49142
+ return response.status(404).send("Not found");
49143
+ }
49144
+ const updatedResource = this.repository.processUpdateActions(
49145
+ getRepositoryContext(request),
49146
+ resource,
49147
+ updateRequest.version,
49148
+ updateRequest.actions
49149
+ );
49150
+ const result = this._expandWithId(request, updatedResource.id);
49151
+ return response.status(200).send(result);
49152
+ }
49153
+ postWithKey(request, response) {
49154
+ const updateRequest = request.body;
49155
+ const resource = this.repository.getByKey(
49156
+ getRepositoryContext(request),
49157
+ request.params["key"]
49158
+ );
49159
+ if (!resource) {
49160
+ return response.status(404).send("Not found");
49161
+ }
49162
+ const updatedResource = this.repository.processUpdateActions(
49163
+ getRepositoryContext(request),
49164
+ resource,
49165
+ updateRequest.version,
49166
+ updateRequest.actions
49167
+ );
49168
+ const result = this._expandWithId(request, updatedResource.id);
49169
+ return response.status(200).send(result);
49170
+ }
49171
+ _expandWithId(request, resourceId) {
49172
+ const result = this.repository.get(
49173
+ getRepositoryContext(request),
49174
+ resourceId,
49175
+ {
49176
+ expand: this._parseParam(request.query.expand)
49177
+ }
49178
+ );
49179
+ return result;
49180
+ }
49181
+ _parseParam(value) {
49182
+ if (Array.isArray(value)) {
49183
+ return value;
49184
+ } else if (value !== void 0) {
49185
+ return [`${value}`];
49186
+ }
49187
+ return void 0;
49188
+ }
49189
+ };
49190
+
49191
+ // src/services/cart.ts
49192
+ var CartService = class extends AbstractService {
49193
+ constructor(parent, cartRepository, orderRepository) {
49560
49194
  super(parent);
49561
- this.repository = new ZoneRepository(storage);
49195
+ this.repository = cartRepository;
49196
+ this.orderRepository = orderRepository;
49562
49197
  }
49563
49198
  getBasePath() {
49564
- return "zones";
49199
+ return "carts";
49200
+ }
49201
+ extraRoutes(parent) {
49202
+ parent.post("/replicate", (request, response) => {
49203
+ const context = getRepositoryContext(request);
49204
+ const cartOrOrder = request.body.reference.typeId === "order" ? this.orderRepository.get(context, request.body.reference.id) : this.repository.get(context, request.body.reference.id);
49205
+ if (!cartOrOrder) {
49206
+ return response.status(400).send();
49207
+ }
49208
+ const cartDraft = {
49209
+ ...cartOrOrder,
49210
+ currency: cartOrOrder.totalPrice.currencyCode,
49211
+ discountCodes: [],
49212
+ lineItems: cartOrOrder.lineItems.map((lineItem) => ({
49213
+ ...lineItem,
49214
+ variantId: lineItem.variant.id,
49215
+ sku: lineItem.variant.sku
49216
+ }))
49217
+ };
49218
+ const newCart = this.repository.create(context, cartDraft);
49219
+ return response.status(200).send(newCart);
49220
+ });
49221
+ }
49222
+ };
49223
+
49224
+ // src/services/cart-discount.ts
49225
+ var CartDiscountService = class extends AbstractService {
49226
+ constructor(parent, repository) {
49227
+ super(parent);
49228
+ this.repository = repository;
49229
+ }
49230
+ getBasePath() {
49231
+ return "cart-discounts";
49232
+ }
49233
+ };
49234
+
49235
+ // src/services/category.ts
49236
+ var CategoryServices = class extends AbstractService {
49237
+ constructor(parent, repository) {
49238
+ super(parent);
49239
+ this.repository = repository;
49240
+ }
49241
+ getBasePath() {
49242
+ return "categories";
49243
+ }
49244
+ };
49245
+
49246
+ // src/services/channel.ts
49247
+ var ChannelService = class extends AbstractService {
49248
+ constructor(parent, repository) {
49249
+ super(parent);
49250
+ this.repository = repository;
49251
+ }
49252
+ getBasePath() {
49253
+ return "channels";
49254
+ }
49255
+ };
49256
+
49257
+ // src/services/custom-object.ts
49258
+ var CustomObjectService = class extends AbstractService {
49259
+ constructor(parent, repository) {
49260
+ super(parent);
49261
+ this.repository = repository;
49262
+ }
49263
+ getBasePath() {
49264
+ return "custom-objects";
49265
+ }
49266
+ extraRoutes(router) {
49267
+ router.get("/:container/:key", this.getWithContainerAndKey.bind(this));
49268
+ router.post("/:container/:key", this.createWithContainerAndKey.bind(this));
49269
+ router.delete("/:container/:key", this.deleteWithContainerAndKey.bind(this));
49270
+ }
49271
+ getWithContainerAndKey(request, response) {
49272
+ const result = this.repository.getWithContainerAndKey(
49273
+ getRepositoryContext(request),
49274
+ request.params.container,
49275
+ request.params.key
49276
+ );
49277
+ if (!result) {
49278
+ return response.status(404).send("Not Found");
49279
+ }
49280
+ return response.status(200).send(result);
49281
+ }
49282
+ createWithContainerAndKey(request, response) {
49283
+ const draft = {
49284
+ ...request.body,
49285
+ key: request.params.key,
49286
+ container: request.params.container
49287
+ };
49288
+ const result = this.repository.create(getRepositoryContext(request), draft);
49289
+ return response.status(200).send(result);
49290
+ }
49291
+ deleteWithContainerAndKey(request, response) {
49292
+ const current = this.repository.getWithContainerAndKey(
49293
+ getRepositoryContext(request),
49294
+ request.params.container,
49295
+ request.params.key
49296
+ );
49297
+ if (!current) {
49298
+ return response.status(404).send("Not Found");
49299
+ }
49300
+ const result = this.repository.delete(
49301
+ getRepositoryContext(request),
49302
+ current.id
49303
+ );
49304
+ return response.status(200).send(result);
49305
+ }
49306
+ };
49307
+
49308
+ // src/services/customer.ts
49309
+ var CustomerService = class extends AbstractService {
49310
+ constructor(parent, repository) {
49311
+ super(parent);
49312
+ this.repository = repository;
49313
+ }
49314
+ getBasePath() {
49315
+ return "customers";
49316
+ }
49317
+ extraRoutes(parent) {
49318
+ parent.post("/password-token", (request, response) => {
49319
+ const customer = this.repository.query(getRepositoryContext(request), {
49320
+ where: [`email="${request.body.email}"`]
49321
+ });
49322
+ const ttlMinutes = request.params.ttlMinutes ? +request.params.ttlMinutes : 34560;
49323
+ const { version: version2, ...rest } = getBaseResourceProperties();
49324
+ return response.status(200).send({
49325
+ ...rest,
49326
+ customerId: customer.results[0].id,
49327
+ expiresAt: new Date(Date.now() + ttlMinutes * 60).toISOString(),
49328
+ value: v4()
49329
+ });
49330
+ });
49331
+ }
49332
+ };
49333
+
49334
+ // src/services/customer-group.ts
49335
+ var CustomerGroupService = class extends AbstractService {
49336
+ constructor(parent, repository) {
49337
+ super(parent);
49338
+ this.repository = repository;
49339
+ }
49340
+ getBasePath() {
49341
+ return "customer-groups";
49342
+ }
49343
+ };
49344
+
49345
+ // src/services/discount-code.ts
49346
+ var DiscountCodeService = class extends AbstractService {
49347
+ constructor(parent, repository) {
49348
+ super(parent);
49349
+ this.repository = repository;
49350
+ }
49351
+ getBasePath() {
49352
+ return "discount-codes";
49353
+ }
49354
+ };
49355
+
49356
+ // src/services/extension.ts
49357
+ var ExtensionServices = class extends AbstractService {
49358
+ constructor(parent, repository) {
49359
+ super(parent);
49360
+ this.repository = repository;
49361
+ }
49362
+ getBasePath() {
49363
+ return "extensions";
49364
+ }
49365
+ };
49366
+
49367
+ // src/services/inventory-entry.ts
49368
+ var InventoryEntryService = class extends AbstractService {
49369
+ constructor(parent, repository) {
49370
+ super(parent);
49371
+ this.repository = repository;
49372
+ }
49373
+ getBasePath() {
49374
+ return "inventory";
49375
+ }
49376
+ };
49377
+
49378
+ // src/services/my-cart.ts
49379
+ var import_express3 = __toESM(require_express2());
49380
+ var MyCartService = class extends AbstractService {
49381
+ constructor(parent, repository) {
49382
+ super(parent);
49383
+ this.repository = repository;
49384
+ }
49385
+ getBasePath() {
49386
+ return "me";
49387
+ }
49388
+ registerRoutes(parent) {
49389
+ const basePath = this.getBasePath();
49390
+ const router = (0, import_express3.Router)({ mergeParams: true });
49391
+ this.extraRoutes(router);
49392
+ router.get("/active-cart", this.activeCart.bind(this));
49393
+ router.get("/carts/", this.get.bind(this));
49394
+ router.get("/carts/:id", this.getWithId.bind(this));
49395
+ router.delete("/carts/:id", this.deleteWithId.bind(this));
49396
+ router.post("/carts/", this.post.bind(this));
49397
+ router.post("/carts/:id", this.postWithId.bind(this));
49398
+ parent.use(`/${basePath}`, router);
49399
+ }
49400
+ activeCart(request, response) {
49401
+ const resource = this.repository.getActiveCart(request.params.projectKey);
49402
+ if (!resource) {
49403
+ return response.status(404).send("Not found");
49404
+ }
49405
+ return response.status(200).send(resource);
49565
49406
  }
49566
49407
  };
49567
49408
 
49568
49409
  // src/services/my-customer.ts
49569
49410
  var import_express4 = __toESM(require_express2());
49570
49411
  var MyCustomerService = class extends AbstractService {
49571
- constructor(parent, storage) {
49412
+ constructor(parent, repository) {
49572
49413
  super(parent);
49573
- this.repository = new CustomerRepository(storage);
49414
+ this.repository = repository;
49574
49415
  }
49575
49416
  getBasePath() {
49576
49417
  return "me";
@@ -49623,25 +49464,10 @@ ${this.pendingMocks().join("\n")}`
49623
49464
 
49624
49465
  // src/services/my-order.ts
49625
49466
  var import_express5 = __toESM(require_express2());
49626
-
49627
- // src/repositories/my-order.ts
49628
- var import_assert3 = __toESM(__require("assert"));
49629
- var MyOrderRepository = class extends OrderRepository {
49630
- create(context, draft) {
49631
- (0, import_assert3.default)(draft.id, "draft.id is missing");
49632
- const cartIdentifier = {
49633
- id: draft.id,
49634
- typeId: "cart"
49635
- };
49636
- return this.createFromCart(context, cartIdentifier);
49637
- }
49638
- };
49639
-
49640
- // src/services/my-order.ts
49641
49467
  var MyOrderService = class extends AbstractService {
49642
- constructor(parent, storage) {
49468
+ constructor(parent, repository) {
49643
49469
  super(parent);
49644
- this.repository = new MyOrderRepository(storage);
49470
+ this.repository = repository;
49645
49471
  }
49646
49472
  getBasePath() {
49647
49473
  return "me";
@@ -49652,13 +49478,314 @@ ${this.pendingMocks().join("\n")}`
49652
49478
  this.extraRoutes(router);
49653
49479
  router.get("/orders/", this.get.bind(this));
49654
49480
  router.get("/orders/:id", this.getWithId.bind(this));
49655
- router.delete("/orders/:id", this.deletewithId.bind(this));
49481
+ router.delete("/orders/:id", this.deleteWithId.bind(this));
49656
49482
  router.post("/orders/", this.post.bind(this));
49657
49483
  router.post("/orders/:id", this.postWithId.bind(this));
49658
49484
  parent.use(`/${basePath}`, router);
49659
49485
  }
49660
49486
  };
49661
49487
 
49488
+ // src/services/my-payment.ts
49489
+ var MyPaymentService = class extends AbstractService {
49490
+ constructor(parent, repository) {
49491
+ super(parent);
49492
+ this.repository = repository;
49493
+ }
49494
+ getBasePath() {
49495
+ return "me/payments";
49496
+ }
49497
+ };
49498
+
49499
+ // src/services/order.ts
49500
+ var OrderService = class extends AbstractService {
49501
+ constructor(parent, repository) {
49502
+ super(parent);
49503
+ this.repository = repository;
49504
+ }
49505
+ getBasePath() {
49506
+ return "orders";
49507
+ }
49508
+ extraRoutes(router) {
49509
+ router.post("/import", this.import.bind(this));
49510
+ router.get("/order-number=:orderNumber", this.getWithOrderNumber.bind(this));
49511
+ }
49512
+ import(request, response) {
49513
+ const importDraft = request.body;
49514
+ const resource = this.repository.import(
49515
+ getRepositoryContext(request),
49516
+ importDraft
49517
+ );
49518
+ return response.status(200).send(resource);
49519
+ }
49520
+ getWithOrderNumber(request, response) {
49521
+ const resource = this.repository.getWithOrderNumber(
49522
+ getRepositoryContext(request),
49523
+ request.params.orderNumber,
49524
+ request.query
49525
+ );
49526
+ if (resource) {
49527
+ return response.status(200).send(resource);
49528
+ }
49529
+ return response.status(404).send("Not found");
49530
+ }
49531
+ };
49532
+
49533
+ // src/services/payment.ts
49534
+ var PaymentService = class extends AbstractService {
49535
+ constructor(parent, repository) {
49536
+ super(parent);
49537
+ this.repository = repository;
49538
+ }
49539
+ getBasePath() {
49540
+ return "payments";
49541
+ }
49542
+ };
49543
+
49544
+ // src/services/product.ts
49545
+ var ProductService = class extends AbstractService {
49546
+ constructor(parent, repository) {
49547
+ super(parent);
49548
+ this.repository = repository;
49549
+ }
49550
+ getBasePath() {
49551
+ return "products";
49552
+ }
49553
+ };
49554
+
49555
+ // src/services/product-discount.ts
49556
+ var ProductDiscountService = class extends AbstractService {
49557
+ constructor(parent, repository) {
49558
+ super(parent);
49559
+ this.repository = repository;
49560
+ }
49561
+ getBasePath() {
49562
+ return "product-discounts";
49563
+ }
49564
+ extraRoutes(router) {
49565
+ router.get("/key=:key", this.getWithKey.bind(this));
49566
+ }
49567
+ getWithKey(request, response) {
49568
+ const resource = this.repository.getWithKey(
49569
+ getRepositoryContext(request),
49570
+ request.params.key
49571
+ );
49572
+ if (resource) {
49573
+ return response.status(200).send(resource);
49574
+ }
49575
+ return response.status(404).send("Not found");
49576
+ }
49577
+ };
49578
+
49579
+ // src/services/product-projection.ts
49580
+ var ProductProjectionService = class extends AbstractService {
49581
+ constructor(parent, repository) {
49582
+ super(parent);
49583
+ this.repository = repository;
49584
+ }
49585
+ getBasePath() {
49586
+ return "product-projections";
49587
+ }
49588
+ extraRoutes(router) {
49589
+ router.get("/search", this.search.bind(this));
49590
+ }
49591
+ search(request, response) {
49592
+ const resource = this.repository.search(
49593
+ getRepositoryContext(request),
49594
+ request.query
49595
+ );
49596
+ return response.status(200).send(resource);
49597
+ }
49598
+ };
49599
+
49600
+ // src/services/product-type.ts
49601
+ var ProductTypeService = class extends AbstractService {
49602
+ constructor(parent, repository) {
49603
+ super(parent);
49604
+ this.repository = repository;
49605
+ }
49606
+ getBasePath() {
49607
+ return "product-types";
49608
+ }
49609
+ extraRoutes(router) {
49610
+ router.get("/key=:key", this.getWithKey.bind(this));
49611
+ }
49612
+ getWithKey(request, response) {
49613
+ const resource = this.repository.getWithKey(
49614
+ getRepositoryContext(request),
49615
+ request.params.key
49616
+ );
49617
+ if (resource) {
49618
+ return response.status(200).send(resource);
49619
+ }
49620
+ return response.status(404).send("Not found");
49621
+ }
49622
+ };
49623
+
49624
+ // src/services/shipping-method.ts
49625
+ var ShippingMethodService = class extends AbstractService {
49626
+ constructor(parent, repository) {
49627
+ super(parent);
49628
+ this.repository = repository;
49629
+ this.registerRoutes(parent);
49630
+ }
49631
+ getBasePath() {
49632
+ return "shipping-methods";
49633
+ }
49634
+ extraRoutes(parent) {
49635
+ parent.get("/matching-cart", this.get.bind(this));
49636
+ }
49637
+ };
49638
+
49639
+ // src/services/shopping-list.ts
49640
+ var ShoppingListService = class extends AbstractService {
49641
+ constructor(parent, repository) {
49642
+ super(parent);
49643
+ this.repository = repository;
49644
+ }
49645
+ getBasePath() {
49646
+ return "shopping-lists";
49647
+ }
49648
+ };
49649
+
49650
+ // src/services/state.ts
49651
+ var StateService = class extends AbstractService {
49652
+ constructor(parent, repository) {
49653
+ super(parent);
49654
+ this.repository = repository;
49655
+ }
49656
+ getBasePath() {
49657
+ return "states";
49658
+ }
49659
+ };
49660
+
49661
+ // src/services/store.ts
49662
+ var StoreService = class extends AbstractService {
49663
+ constructor(parent, repository) {
49664
+ super(parent);
49665
+ this.repository = repository;
49666
+ }
49667
+ getBasePath() {
49668
+ return "stores";
49669
+ }
49670
+ extraRoutes(router) {
49671
+ router.get("/key=:key", this.getWithKey.bind(this));
49672
+ }
49673
+ getWithKey(request, response) {
49674
+ const resource = this.repository.getWithKey(
49675
+ getRepositoryContext(request),
49676
+ request.params.key
49677
+ );
49678
+ if (resource) {
49679
+ return response.status(200).send(resource);
49680
+ }
49681
+ return response.status(404).send("Not found");
49682
+ }
49683
+ };
49684
+
49685
+ // src/services/subscription.ts
49686
+ var SubscriptionService = class extends AbstractService {
49687
+ constructor(parent, repository) {
49688
+ super(parent);
49689
+ this.repository = repository;
49690
+ }
49691
+ getBasePath() {
49692
+ return "subscriptions";
49693
+ }
49694
+ };
49695
+
49696
+ // src/services/tax-category.ts
49697
+ var TaxCategoryService = class extends AbstractService {
49698
+ constructor(parent, repository) {
49699
+ super(parent);
49700
+ this.repository = repository;
49701
+ }
49702
+ getBasePath() {
49703
+ return "tax-categories";
49704
+ }
49705
+ extraRoutes(router) {
49706
+ router.get("/key=:key", this.getWithKey.bind(this));
49707
+ }
49708
+ getWithKey(request, response) {
49709
+ const resource = this.repository.getWithKey(
49710
+ getRepositoryContext(request),
49711
+ request.params.key
49712
+ );
49713
+ if (resource) {
49714
+ return response.status(200).send(resource);
49715
+ }
49716
+ return response.status(404).send("Not found");
49717
+ }
49718
+ };
49719
+
49720
+ // src/services/type.ts
49721
+ var TypeService = class extends AbstractService {
49722
+ constructor(parent, repository) {
49723
+ super(parent);
49724
+ this.repository = repository;
49725
+ }
49726
+ getBasePath() {
49727
+ return "types";
49728
+ }
49729
+ };
49730
+
49731
+ // src/services/zone.ts
49732
+ var ZoneService = class extends AbstractService {
49733
+ constructor(parent, repository) {
49734
+ super(parent);
49735
+ this.repository = repository;
49736
+ }
49737
+ getBasePath() {
49738
+ return "zones";
49739
+ }
49740
+ };
49741
+
49742
+ // src/services/index.ts
49743
+ var createServices = (router, repos) => ({
49744
+ category: new CategoryServices(router, repos["category"]),
49745
+ cart: new CartService(router, repos["cart"], repos["order"]),
49746
+ "cart-discount": new CartDiscountService(router, repos["cart-discount"]),
49747
+ customer: new CustomerService(router, repos["customer"]),
49748
+ channel: new ChannelService(router, repos["channel"]),
49749
+ "customer-group": new CustomerGroupService(router, repos["customer-group"]),
49750
+ "discount-code": new DiscountCodeService(router, repos["discount-code"]),
49751
+ extension: new ExtensionServices(router, repos["extension"]),
49752
+ "inventory-entry": new InventoryEntryService(
49753
+ router,
49754
+ repos["inventory-entry"]
49755
+ ),
49756
+ "key-value-document": new CustomObjectService(
49757
+ router,
49758
+ repos["key-value-document"]
49759
+ ),
49760
+ order: new OrderService(router, repos["order"]),
49761
+ payment: new PaymentService(router, repos["payment"]),
49762
+ "my-cart": new MyCartService(router, repos["my-cart"]),
49763
+ "my-order": new MyOrderService(router, repos["my-order"]),
49764
+ "my-customer": new MyCustomerService(router, repos["my-customer"]),
49765
+ "my-payment": new MyPaymentService(router, repos["my-payment"]),
49766
+ "shipping-method": new ShippingMethodService(
49767
+ router,
49768
+ repos["shipping-method"]
49769
+ ),
49770
+ "product-type": new ProductTypeService(router, repos["product-type"]),
49771
+ product: new ProductService(router, repos["product"]),
49772
+ "product-discount": new ProductDiscountService(
49773
+ router,
49774
+ repos["product-discount"]
49775
+ ),
49776
+ "product-projection": new ProductProjectionService(
49777
+ router,
49778
+ repos["product-projection"]
49779
+ ),
49780
+ "shopping-list": new ShoppingListService(router, repos["shopping-list"]),
49781
+ state: new StateService(router, repos["state"]),
49782
+ store: new StoreService(router, repos["store"]),
49783
+ subscription: new SubscriptionService(router, repos["subscription"]),
49784
+ "tax-category": new TaxCategoryService(router, repos["tax-category"]),
49785
+ type: new TypeService(router, repos["type"]),
49786
+ zone: new ZoneService(router, repos["zone"])
49787
+ });
49788
+
49662
49789
  // src/ctMock.ts
49663
49790
  var DEFAULT_OPTIONS = {
49664
49791
  enableAuthentication: false,
@@ -49673,6 +49800,7 @@ ${this.pendingMocks().join("\n")}`
49673
49800
  this._nockScopes = { auth: void 0, api: void 0 };
49674
49801
  this.options = { ...DEFAULT_OPTIONS, ...options };
49675
49802
  this._services = {};
49803
+ this._repositories = {};
49676
49804
  this._projectService = void 0;
49677
49805
  this._storage = new InMemoryStorage();
49678
49806
  this._oauth2 = new OAuth2Server({
@@ -49706,9 +49834,8 @@ ${this.pendingMocks().join("\n")}`
49706
49834
  );
49707
49835
  }
49708
49836
  runServer(port = 3e3, options) {
49709
- const app = this.createApp(options);
49710
- const server = app.listen(port, () => {
49711
- console.log(`Mock server listening at http://localhost:${port}`);
49837
+ const server = this.app.listen(port, () => {
49838
+ console.info(`Mock server listening at http://localhost:${port}`);
49712
49839
  });
49713
49840
  server.keepAliveTimeout = 60 * 1e3;
49714
49841
  }
@@ -49731,52 +49858,12 @@ ${this.pendingMocks().join("\n")}`
49731
49858
  app.use("/:projectKey", projectRouter);
49732
49859
  app.use("/:projectKey/in-store/key=:storeKey", projectRouter);
49733
49860
  }
49734
- this._projectService = new ProjectService(projectRouter, this._storage);
49735
- this._services = {
49736
- category: new CategoryServices(projectRouter, this._storage),
49737
- cart: new CartService(projectRouter, this._storage),
49738
- "cart-discount": new CartDiscountService(projectRouter, this._storage),
49739
- customer: new CustomerService(projectRouter, this._storage),
49740
- channel: new ChannelService(projectRouter, this._storage),
49741
- "customer-group": new CustomerGroupService(projectRouter, this._storage),
49742
- "discount-code": new DiscountCodeService(projectRouter, this._storage),
49743
- extension: new ExtensionServices(projectRouter, this._storage),
49744
- "inventory-entry": new InventoryEntryService(
49745
- projectRouter,
49746
- this._storage
49747
- ),
49748
- "key-value-document": new CustomObjectService(
49749
- projectRouter,
49750
- this._storage
49751
- ),
49752
- order: new OrderService(projectRouter, this._storage),
49753
- payment: new PaymentService(projectRouter, this._storage),
49754
- "my-cart": new MyCartService(projectRouter, this._storage),
49755
- "my-order": new MyOrderService(projectRouter, this._storage),
49756
- "my-customer": new MyCustomerService(projectRouter, this._storage),
49757
- "my-payment": new MyPaymentService(projectRouter, this._storage),
49758
- "shipping-method": new ShippingMethodService(
49759
- projectRouter,
49760
- this._storage
49761
- ),
49762
- "product-type": new ProductTypeService(projectRouter, this._storage),
49763
- product: new ProductService(projectRouter, this._storage),
49764
- "product-discount": new ProductDiscountService(
49765
- projectRouter,
49766
- this._storage
49767
- ),
49768
- "product-projection": new ProductProjectionService(
49769
- projectRouter,
49770
- this._storage
49771
- ),
49772
- "shopping-list": new ShoppingListService(projectRouter, this._storage),
49773
- state: new StateService(projectRouter, this._storage),
49774
- store: new StoreService(projectRouter, this._storage),
49775
- subscription: new SubscriptionService(projectRouter, this._storage),
49776
- "tax-category": new TaxCategoryService(projectRouter, this._storage),
49777
- type: new TypeService(projectRouter, this._storage),
49778
- zone: new ZoneService(projectRouter, this._storage)
49779
- };
49861
+ this._repositories = createRepositories(this._storage);
49862
+ this._projectService = new ProjectService(
49863
+ projectRouter,
49864
+ this._repositories.project
49865
+ );
49866
+ this._services = createServices(projectRouter, this._repositories);
49780
49867
  app.use((err, req, resp, next) => {
49781
49868
  if (err instanceof CommercetoolsError) {
49782
49869
  return resp.status(err.statusCode).send({