@aws-amplify/datastore 4.7.6-api-v6-models.b3abc9b.0 → 5.0.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 (187) hide show
  1. package/README.md +4 -0
  2. package/lib/authModeStrategies/defaultAuthStrategy.js +3 -2
  3. package/lib/authModeStrategies/index.js +3 -3
  4. package/lib/authModeStrategies/multiAuthStrategy.js +38 -53
  5. package/lib/datastore/datastore.d.ts +4 -5
  6. package/lib/datastore/datastore.js +929 -1284
  7. package/lib/index.d.ts +1 -1
  8. package/lib/index.js +26 -13
  9. package/lib/predicates/index.js +54 -69
  10. package/lib/predicates/next.d.ts +2 -2
  11. package/lib/predicates/next.js +313 -462
  12. package/lib/predicates/sort.js +24 -28
  13. package/lib/ssr/index.js +2 -2
  14. package/lib/storage/adapter/AsyncStorageAdapter.js +120 -342
  15. package/lib/storage/adapter/AsyncStorageDatabase.js +217 -421
  16. package/lib/storage/adapter/InMemoryStore.js +28 -51
  17. package/lib/storage/adapter/InMemoryStore.native.js +5 -3
  18. package/lib/storage/adapter/IndexedDBAdapter.js +466 -871
  19. package/lib/storage/adapter/StorageAdapterBase.js +180 -330
  20. package/lib/storage/adapter/getDefaultAdapter/index.js +8 -10
  21. package/lib/storage/adapter/getDefaultAdapter/index.native.js +5 -4
  22. package/lib/storage/adapter/index.js +0 -1
  23. package/lib/storage/relationship.js +177 -253
  24. package/lib/storage/storage.d.ts +4 -4
  25. package/lib/storage/storage.js +255 -433
  26. package/lib/sync/datastoreConnectivity.d.ts +2 -2
  27. package/lib/sync/datastoreConnectivity.js +29 -39
  28. package/lib/sync/datastoreReachability/index.d.ts +1 -3
  29. package/lib/sync/datastoreReachability/index.js +3 -3
  30. package/lib/sync/datastoreReachability/index.native.d.ts +1 -3
  31. package/lib/sync/datastoreReachability/index.native.js +4 -5
  32. package/lib/sync/index.d.ts +2 -2
  33. package/lib/sync/index.js +522 -827
  34. package/lib/sync/merger.js +31 -63
  35. package/lib/sync/outbox.js +148 -232
  36. package/lib/sync/processors/errorMaps.d.ts +1 -1
  37. package/lib/sync/processors/errorMaps.js +30 -47
  38. package/lib/sync/processors/mutation.d.ts +2 -2
  39. package/lib/sync/processors/mutation.js +343 -502
  40. package/lib/sync/processors/subscription.d.ts +5 -2
  41. package/lib/sync/processors/subscription.js +283 -437
  42. package/lib/sync/processors/sync.d.ts +2 -2
  43. package/lib/sync/processors/sync.js +279 -404
  44. package/lib/sync/utils.d.ts +5 -4
  45. package/lib/sync/utils.js +267 -320
  46. package/lib/tsconfig.tsbuildinfo +1 -0
  47. package/lib/types.d.ts +138 -140
  48. package/lib/types.js +17 -24
  49. package/lib/util.d.ts +9 -17
  50. package/lib/util.js +387 -511
  51. package/lib-esm/authModeStrategies/defaultAuthStrategy.js +1 -2
  52. package/lib-esm/authModeStrategies/index.js +0 -1
  53. package/lib-esm/authModeStrategies/multiAuthStrategy.js +35 -52
  54. package/lib-esm/datastore/datastore.d.ts +4 -5
  55. package/lib-esm/datastore/datastore.js +888 -1247
  56. package/lib-esm/index.d.ts +1 -1
  57. package/lib-esm/index.js +6 -7
  58. package/lib-esm/predicates/index.js +53 -70
  59. package/lib-esm/predicates/next.d.ts +2 -2
  60. package/lib-esm/predicates/next.js +306 -459
  61. package/lib-esm/predicates/sort.js +23 -28
  62. package/lib-esm/ssr/index.js +1 -2
  63. package/lib-esm/storage/adapter/AsyncStorageAdapter.js +111 -338
  64. package/lib-esm/storage/adapter/AsyncStorageDatabase.js +212 -416
  65. package/lib-esm/storage/adapter/InMemoryStore.js +27 -52
  66. package/lib-esm/storage/adapter/InMemoryStore.native.js +0 -1
  67. package/lib-esm/storage/adapter/IndexedDBAdapter.js +438 -866
  68. package/lib-esm/storage/adapter/StorageAdapterBase.js +173 -325
  69. package/lib-esm/storage/adapter/getDefaultAdapter/index.js +2 -6
  70. package/lib-esm/storage/adapter/getDefaultAdapter/index.native.js +1 -2
  71. package/lib-esm/storage/adapter/index.js +1 -1
  72. package/lib-esm/storage/relationship.js +173 -251
  73. package/lib-esm/storage/storage.d.ts +4 -4
  74. package/lib-esm/storage/storage.js +242 -424
  75. package/lib-esm/sync/datastoreConnectivity.d.ts +2 -2
  76. package/lib-esm/sync/datastoreConnectivity.js +28 -39
  77. package/lib-esm/sync/datastoreReachability/index.d.ts +1 -3
  78. package/lib-esm/sync/datastoreReachability/index.js +2 -3
  79. package/lib-esm/sync/datastoreReachability/index.native.d.ts +1 -3
  80. package/lib-esm/sync/datastoreReachability/index.native.js +3 -4
  81. package/lib-esm/sync/index.d.ts +2 -2
  82. package/lib-esm/sync/index.js +502 -812
  83. package/lib-esm/sync/merger.js +28 -61
  84. package/lib-esm/sync/outbox.js +143 -228
  85. package/lib-esm/sync/processors/errorMaps.d.ts +1 -1
  86. package/lib-esm/sync/processors/errorMaps.js +32 -50
  87. package/lib-esm/sync/processors/mutation.d.ts +2 -2
  88. package/lib-esm/sync/processors/mutation.js +329 -490
  89. package/lib-esm/sync/processors/subscription.d.ts +5 -2
  90. package/lib-esm/sync/processors/subscription.js +266 -421
  91. package/lib-esm/sync/processors/sync.d.ts +2 -2
  92. package/lib-esm/sync/processors/sync.js +271 -397
  93. package/lib-esm/sync/utils.d.ts +5 -4
  94. package/lib-esm/sync/utils.js +252 -307
  95. package/lib-esm/tsconfig.tsbuildinfo +1 -0
  96. package/lib-esm/types.d.ts +138 -140
  97. package/lib-esm/types.js +16 -25
  98. package/lib-esm/util.d.ts +9 -17
  99. package/lib-esm/util.js +335 -497
  100. package/package.json +31 -26
  101. package/src/authModeStrategies/multiAuthStrategy.ts +15 -12
  102. package/src/datastore/datastore.ts +36 -35
  103. package/src/predicates/sort.ts +3 -1
  104. package/src/storage/adapter/InMemoryStore.ts +1 -1
  105. package/src/storage/adapter/IndexedDBAdapter.ts +2 -2
  106. package/src/storage/adapter/StorageAdapterBase.ts +2 -2
  107. package/src/storage/adapter/getDefaultAdapter/index.ts +1 -4
  108. package/src/storage/storage.ts +29 -24
  109. package/src/sync/datastoreConnectivity.ts +6 -6
  110. package/src/sync/datastoreReachability/index.native.ts +5 -3
  111. package/src/sync/datastoreReachability/index.ts +1 -1
  112. package/src/sync/index.ts +79 -89
  113. package/src/sync/processors/errorMaps.ts +7 -7
  114. package/src/sync/processors/mutation.ts +19 -13
  115. package/src/sync/processors/subscription.ts +221 -295
  116. package/src/sync/processors/sync.ts +11 -8
  117. package/src/sync/utils.ts +30 -15
  118. package/src/types.ts +4 -8
  119. package/src/util.ts +46 -9
  120. package/lib/.tsbuildinfo +0 -3
  121. package/lib/authModeStrategies/defaultAuthStrategy.js.map +0 -1
  122. package/lib/authModeStrategies/index.js.map +0 -1
  123. package/lib/authModeStrategies/multiAuthStrategy.js.map +0 -1
  124. package/lib/datastore/datastore.js.map +0 -1
  125. package/lib/index.js.map +0 -1
  126. package/lib/predicates/index.js.map +0 -1
  127. package/lib/predicates/next.js.map +0 -1
  128. package/lib/predicates/sort.js.map +0 -1
  129. package/lib/ssr/index.js.map +0 -1
  130. package/lib/storage/adapter/AsyncStorageAdapter.js.map +0 -1
  131. package/lib/storage/adapter/AsyncStorageDatabase.js.map +0 -1
  132. package/lib/storage/adapter/InMemoryStore.js.map +0 -1
  133. package/lib/storage/adapter/InMemoryStore.native.js.map +0 -1
  134. package/lib/storage/adapter/IndexedDBAdapter.js.map +0 -1
  135. package/lib/storage/adapter/StorageAdapterBase.js.map +0 -1
  136. package/lib/storage/adapter/getDefaultAdapter/index.js.map +0 -1
  137. package/lib/storage/adapter/getDefaultAdapter/index.native.js.map +0 -1
  138. package/lib/storage/adapter/index.js.map +0 -1
  139. package/lib/storage/relationship.js.map +0 -1
  140. package/lib/storage/storage.js.map +0 -1
  141. package/lib/sync/datastoreConnectivity.js.map +0 -1
  142. package/lib/sync/datastoreReachability/index.js.map +0 -1
  143. package/lib/sync/datastoreReachability/index.native.js.map +0 -1
  144. package/lib/sync/index.js.map +0 -1
  145. package/lib/sync/merger.js.map +0 -1
  146. package/lib/sync/outbox.js.map +0 -1
  147. package/lib/sync/processors/errorMaps.js.map +0 -1
  148. package/lib/sync/processors/mutation.js.map +0 -1
  149. package/lib/sync/processors/subscription.js.map +0 -1
  150. package/lib/sync/processors/sync.js.map +0 -1
  151. package/lib/sync/utils.js.map +0 -1
  152. package/lib/types.js.map +0 -1
  153. package/lib/util.js.map +0 -1
  154. package/lib-esm/.tsbuildinfo +0 -3
  155. package/lib-esm/authModeStrategies/defaultAuthStrategy.js.map +0 -1
  156. package/lib-esm/authModeStrategies/index.js.map +0 -1
  157. package/lib-esm/authModeStrategies/multiAuthStrategy.js.map +0 -1
  158. package/lib-esm/datastore/datastore.js.map +0 -1
  159. package/lib-esm/index.js.map +0 -1
  160. package/lib-esm/predicates/index.js.map +0 -1
  161. package/lib-esm/predicates/next.js.map +0 -1
  162. package/lib-esm/predicates/sort.js.map +0 -1
  163. package/lib-esm/ssr/index.js.map +0 -1
  164. package/lib-esm/storage/adapter/AsyncStorageAdapter.js.map +0 -1
  165. package/lib-esm/storage/adapter/AsyncStorageDatabase.js.map +0 -1
  166. package/lib-esm/storage/adapter/InMemoryStore.js.map +0 -1
  167. package/lib-esm/storage/adapter/InMemoryStore.native.js.map +0 -1
  168. package/lib-esm/storage/adapter/IndexedDBAdapter.js.map +0 -1
  169. package/lib-esm/storage/adapter/StorageAdapterBase.js.map +0 -1
  170. package/lib-esm/storage/adapter/getDefaultAdapter/index.js.map +0 -1
  171. package/lib-esm/storage/adapter/getDefaultAdapter/index.native.js.map +0 -1
  172. package/lib-esm/storage/adapter/index.js.map +0 -1
  173. package/lib-esm/storage/relationship.js.map +0 -1
  174. package/lib-esm/storage/storage.js.map +0 -1
  175. package/lib-esm/sync/datastoreConnectivity.js.map +0 -1
  176. package/lib-esm/sync/datastoreReachability/index.js.map +0 -1
  177. package/lib-esm/sync/datastoreReachability/index.native.js.map +0 -1
  178. package/lib-esm/sync/index.js.map +0 -1
  179. package/lib-esm/sync/merger.js.map +0 -1
  180. package/lib-esm/sync/outbox.js.map +0 -1
  181. package/lib-esm/sync/processors/errorMaps.js.map +0 -1
  182. package/lib-esm/sync/processors/mutation.js.map +0 -1
  183. package/lib-esm/sync/processors/subscription.js.map +0 -1
  184. package/lib-esm/sync/processors/sync.js.map +0 -1
  185. package/lib-esm/sync/utils.js.map +0 -1
  186. package/lib-esm/types.js.map +0 -1
  187. package/lib-esm/util.js.map +0 -1
package/lib-esm/util.js CHANGED
@@ -1,14 +1,11 @@
1
- import { __assign, __awaiter, __generator, __read, __spread, __values } from "tslib";
2
1
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
2
  // SPDX-License-Identifier: Apache-2.0
4
- import { Buffer } from 'buffer';
5
3
  import { monotonicFactory } from 'ulid';
6
- import { v4 as uuid } from 'uuid';
4
+ import { amplifyUuid, AmplifyUrl, WordArray, } from '@aws-amplify/core/internals/utils';
7
5
  import { produce, applyPatches } from 'immer';
8
6
  import { isPredicateGroup, isPredicateObj, SortDirection, isModelAttributeKey, isModelAttributePrimaryKey, isModelAttributeCompositeKey, LimitTimerRaceResolvedValues, } from './types';
9
- import { WordArray } from 'amazon-cognito-identity-js';
10
7
  import { ModelSortPredicateCreator } from './predicates';
11
- export var ID = 'id';
8
+ export const ID = 'id';
12
9
  /**
13
10
  * Used by the Async Storage Adapter to concatenate key values
14
11
  * for a record. For instance, if a model has the following keys:
@@ -16,14 +13,14 @@ export var ID = 'id';
16
13
  * we concatenate the `customId` and `createdAt` as:
17
14
  * `12-234-5#2022-09-28T00:00:00.000Z`
18
15
  */
19
- export var DEFAULT_PRIMARY_KEY_VALUE_SEPARATOR = '#';
16
+ export const DEFAULT_PRIMARY_KEY_VALUE_SEPARATOR = '#';
20
17
  /**
21
18
  * Used for generating spinal-cased index name from an array of
22
19
  * key field names.
23
20
  * E.g. for keys `[id, title]` => 'id-title'
24
21
  */
25
- export var IDENTIFIER_KEY_SEPARATOR = '-';
26
- export var errorMessages = {
22
+ export const IDENTIFIER_KEY_SEPARATOR = '-';
23
+ export const errorMessages = {
27
24
  idEmptyString: 'An index field cannot contain an empty string value',
28
25
  queryByPkWithCompositeKeyPresent: 'Models with composite primary keys cannot be queried by a single key value. Use object literal syntax for composite keys instead: https://docs.amplify.aws/lib/datastore/advanced-workflows/q/platform/js/#querying-records-with-custom-primary-keys',
29
26
  deleteByPkWithCompositeKeyPresent: 'Models with composite primary keys cannot be deleted by a single key value, unless using a predicate. Use object literal syntax for composite keys instead: https://docs.amplify.aws/lib/datastore/advanced-workflows/q/platform/js/#querying-records-with-custom-primary-keys',
@@ -36,23 +33,22 @@ export var NAMESPACES;
36
33
  NAMESPACES["SYNC"] = "sync";
37
34
  NAMESPACES["STORAGE"] = "storage";
38
35
  })(NAMESPACES || (NAMESPACES = {}));
39
- var DATASTORE = NAMESPACES.DATASTORE;
40
- var USER = NAMESPACES.USER;
41
- var SYNC = NAMESPACES.SYNC;
42
- var STORAGE = NAMESPACES.STORAGE;
36
+ const DATASTORE = NAMESPACES.DATASTORE;
37
+ const USER = NAMESPACES.USER;
38
+ const SYNC = NAMESPACES.SYNC;
39
+ const STORAGE = NAMESPACES.STORAGE;
43
40
  export { USER, SYNC, STORAGE, DATASTORE };
44
- export var exhaustiveCheck = function (obj, throwOnError) {
45
- if (throwOnError === void 0) { throwOnError = true; }
41
+ export const exhaustiveCheck = (obj, throwOnError = true) => {
46
42
  if (throwOnError) {
47
- throw new Error("Invalid " + obj);
43
+ throw new Error(`Invalid ${obj}`);
48
44
  }
49
45
  };
50
- export var isNullOrUndefined = function (val) {
46
+ export const isNullOrUndefined = (val) => {
51
47
  return typeof val === 'undefined' || val === undefined || val === null;
52
48
  };
53
- export var validatePredicate = function (model, groupType, predicatesOrGroups) {
54
- var filterType;
55
- var isNegation = false;
49
+ export const validatePredicate = (model, groupType, predicatesOrGroups) => {
50
+ let filterType;
51
+ let isNegation = false;
56
52
  if (predicatesOrGroups.length === 0) {
57
53
  return true;
58
54
  }
@@ -68,23 +64,23 @@ export var validatePredicate = function (model, groupType, predicatesOrGroups) {
68
64
  filterType = 'some';
69
65
  break;
70
66
  default:
71
- throw new Error("Invalid " + groupType);
67
+ throw new Error(`Invalid ${groupType}`);
72
68
  }
73
- var result = predicatesOrGroups[filterType](function (predicateOrGroup) {
69
+ const result = predicatesOrGroups[filterType](predicateOrGroup => {
74
70
  if (isPredicateObj(predicateOrGroup)) {
75
- var field = predicateOrGroup.field, operator = predicateOrGroup.operator, operand = predicateOrGroup.operand;
76
- var value = model[field];
71
+ const { field, operator, operand } = predicateOrGroup;
72
+ const value = model[field];
77
73
  return validatePredicateField(value, operator, operand);
78
74
  }
79
75
  if (isPredicateGroup(predicateOrGroup)) {
80
- var type = predicateOrGroup.type, predicates = predicateOrGroup.predicates;
76
+ const { type, predicates } = predicateOrGroup;
81
77
  return validatePredicate(model, type, predicates);
82
78
  }
83
79
  throw new Error('Not a predicate or group');
84
80
  });
85
81
  return isNegation ? !result : result;
86
82
  };
87
- export var validatePredicateField = function (value, operator, operand) {
83
+ export const validatePredicateField = (value, operator, operand) => {
88
84
  switch (operator) {
89
85
  case 'ne':
90
86
  return value !== operand;
@@ -99,7 +95,7 @@ export var validatePredicateField = function (value, operator, operand) {
99
95
  case 'gt':
100
96
  return value > operand;
101
97
  case 'between':
102
- var _c = __read(operand, 2), min = _c[0], max = _c[1];
98
+ const [min, max] = operand;
103
99
  return value >= min && value <= max;
104
100
  case 'beginsWith':
105
101
  return (!isNullOrUndefined(value) &&
@@ -114,21 +110,21 @@ export var validatePredicateField = function (value, operator, operand) {
114
110
  return false;
115
111
  }
116
112
  };
117
- export var isModelConstructor = function (obj) {
113
+ export const isModelConstructor = (obj) => {
118
114
  return (obj && typeof obj.copyOf === 'function');
119
115
  };
120
- var nonModelClasses = new WeakSet();
116
+ const nonModelClasses = new WeakSet();
121
117
  export function registerNonModelClass(clazz) {
122
118
  nonModelClasses.add(clazz);
123
119
  }
124
- export var isNonModelConstructor = function (obj) {
120
+ export const isNonModelConstructor = (obj) => {
125
121
  return nonModelClasses.has(obj);
126
122
  };
127
- var topologicallySortedModels = new WeakMap();
128
- export var traverseModel = function (srcModelName, instance, namespace, modelInstanceCreator, getModelConstructorByModelName) {
129
- var modelConstructor = getModelConstructorByModelName(namespace.name, srcModelName);
130
- var result = [];
131
- var newInstance = modelConstructor.copyOf(instance, function () { });
123
+ const topologicallySortedModels = new WeakMap();
124
+ export const traverseModel = (srcModelName, instance, namespace, modelInstanceCreator, getModelConstructorByModelName) => {
125
+ const modelConstructor = getModelConstructorByModelName(namespace.name, srcModelName);
126
+ const result = [];
127
+ const newInstance = modelConstructor.copyOf(instance, () => { });
132
128
  result.unshift({
133
129
  modelName: srcModelName,
134
130
  item: newInstance,
@@ -137,38 +133,29 @@ export var traverseModel = function (srcModelName, instance, namespace, modelIns
137
133
  if (!topologicallySortedModels.has(namespace)) {
138
134
  topologicallySortedModels.set(namespace, Array.from(namespace.modelTopologicalOrdering.keys()));
139
135
  }
140
- var sortedModels = topologicallySortedModels.get(namespace);
141
- result.sort(function (a, b) {
136
+ const sortedModels = topologicallySortedModels.get(namespace);
137
+ result.sort((a, b) => {
142
138
  return (sortedModels.indexOf(a.modelName) - sortedModels.indexOf(b.modelName));
143
139
  });
144
140
  return result;
145
141
  };
146
- var privateModeCheckResult;
147
- export var isPrivateMode = function () {
148
- return new Promise(function (resolve) {
149
- var dbname = uuid();
150
- var db;
151
- var isPrivate = function () {
142
+ let privateModeCheckResult;
143
+ export const isPrivateMode = () => {
144
+ return new Promise(resolve => {
145
+ const dbname = amplifyUuid();
146
+ let db;
147
+ const isPrivate = () => {
152
148
  privateModeCheckResult = false;
153
149
  resolve(true);
154
150
  };
155
- var isNotPrivate = function () { return __awaiter(void 0, void 0, void 0, function () {
156
- return __generator(this, function (_c) {
157
- switch (_c.label) {
158
- case 0:
159
- if (!(db && db.result && typeof db.result.close === 'function')) return [3 /*break*/, 2];
160
- return [4 /*yield*/, db.result.close()];
161
- case 1:
162
- _c.sent();
163
- _c.label = 2;
164
- case 2: return [4 /*yield*/, indexedDB.deleteDatabase(dbname)];
165
- case 3:
166
- _c.sent();
167
- privateModeCheckResult = true;
168
- return [2 /*return*/, resolve(false)];
169
- }
170
- });
171
- }); };
151
+ const isNotPrivate = async () => {
152
+ if (db && db.result && typeof db.result.close === 'function') {
153
+ await db.result.close();
154
+ }
155
+ await indexedDB.deleteDatabase(dbname);
156
+ privateModeCheckResult = true;
157
+ return resolve(false);
158
+ };
172
159
  if (privateModeCheckResult === true) {
173
160
  return isNotPrivate();
174
161
  }
@@ -182,7 +169,7 @@ export var isPrivateMode = function () {
182
169
  db.onsuccess = isNotPrivate;
183
170
  });
184
171
  };
185
- var safariCompatabilityModeResult;
172
+ let safariCompatabilityModeResult;
186
173
  /**
187
174
  * Whether the browser's implementation of IndexedDB breaks on array lookups
188
175
  * against composite indexes whose keypath contains a single column.
@@ -193,91 +180,99 @@ var safariCompatabilityModeResult;
193
180
  * In all known, modern Safari browsers as of Q4 2022, the query against an index like
194
181
  * this will *always* return `undefined`. So, the index needs to be created as a scalar.
195
182
  */
196
- export var isSafariCompatabilityMode = function () { return __awaiter(void 0, void 0, void 0, function () {
197
- var dbName_1, storeName_1, indexName_1, db_1, rwTx, rwStore, result, error_1;
198
- return __generator(this, function (_c) {
199
- switch (_c.label) {
200
- case 0:
201
- _c.trys.push([0, 6, , 7]);
202
- dbName_1 = uuid();
203
- storeName_1 = 'indexedDBFeatureProbeStore';
204
- indexName_1 = 'idx';
205
- if (indexedDB === null)
206
- return [2 /*return*/, false];
207
- if (safariCompatabilityModeResult !== undefined) {
208
- return [2 /*return*/, safariCompatabilityModeResult];
209
- }
210
- return [4 /*yield*/, new Promise(function (resolve) {
211
- var dbOpenRequest = indexedDB.open(dbName_1);
212
- dbOpenRequest.onerror = function () { return resolve(false); };
213
- dbOpenRequest.onsuccess = function () {
214
- var db = dbOpenRequest.result;
215
- resolve(db);
216
- };
217
- dbOpenRequest.onupgradeneeded = function (event) {
218
- var _c;
219
- var db = (_c = event === null || event === void 0 ? void 0 : event.target) === null || _c === void 0 ? void 0 : _c.result;
220
- db.onerror = function () { return resolve(false); };
221
- var store = db.createObjectStore(storeName_1, {
222
- autoIncrement: true,
223
- });
224
- store.createIndex(indexName_1, ['id']);
225
- };
226
- })];
227
- case 1:
228
- db_1 = _c.sent();
229
- if (!db_1) {
230
- throw new Error('Could not open probe DB');
231
- }
232
- rwTx = db_1.transaction(storeName_1, 'readwrite');
233
- rwStore = rwTx.objectStore(storeName_1);
234
- rwStore.add({
235
- id: 1,
183
+ export const isSafariCompatabilityMode = async () => {
184
+ try {
185
+ const dbName = amplifyUuid();
186
+ const storeName = 'indexedDBFeatureProbeStore';
187
+ const indexName = 'idx';
188
+ if (indexedDB === null)
189
+ return false;
190
+ if (safariCompatabilityModeResult !== undefined) {
191
+ return safariCompatabilityModeResult;
192
+ }
193
+ const db = await new Promise(resolve => {
194
+ const dbOpenRequest = indexedDB.open(dbName);
195
+ dbOpenRequest.onerror = () => resolve(false);
196
+ dbOpenRequest.onsuccess = () => {
197
+ const db = dbOpenRequest.result;
198
+ resolve(db);
199
+ };
200
+ dbOpenRequest.onupgradeneeded = (event) => {
201
+ const db = event?.target?.result;
202
+ db.onerror = () => resolve(false);
203
+ const store = db.createObjectStore(storeName, {
204
+ autoIncrement: true,
236
205
  });
237
- rwTx.commit();
238
- return [4 /*yield*/, new Promise(function (resolve) {
239
- var tx = db_1.transaction(storeName_1, 'readonly');
240
- var store = tx.objectStore(storeName_1);
241
- var index = store.index(indexName_1);
242
- var getRequest = index.get([1]);
243
- getRequest.onerror = function () { return resolve(false); };
244
- getRequest.onsuccess = function (event) {
245
- var _c;
246
- resolve((_c = event === null || event === void 0 ? void 0 : event.target) === null || _c === void 0 ? void 0 : _c.result);
247
- };
248
- })];
249
- case 2:
250
- result = _c.sent();
251
- if (!(db_1 && typeof db_1.close === 'function')) return [3 /*break*/, 4];
252
- return [4 /*yield*/, db_1.close()];
253
- case 3:
254
- _c.sent();
255
- _c.label = 4;
256
- case 4: return [4 /*yield*/, indexedDB.deleteDatabase(dbName_1)];
257
- case 5:
258
- _c.sent();
259
- if (result === undefined) {
260
- safariCompatabilityModeResult = true;
261
- }
262
- else {
263
- safariCompatabilityModeResult = false;
264
- }
265
- return [3 /*break*/, 7];
266
- case 6:
267
- error_1 = _c.sent();
268
- safariCompatabilityModeResult = false;
269
- return [3 /*break*/, 7];
270
- case 7: return [2 /*return*/, safariCompatabilityModeResult];
206
+ store.createIndex(indexName, ['id']);
207
+ };
208
+ });
209
+ if (!db) {
210
+ throw new Error('Could not open probe DB');
271
211
  }
272
- });
273
- }); };
274
- var randomBytes = function (nBytes) {
275
- return Buffer.from(new WordArray().random(nBytes).toString(), 'hex');
212
+ const rwTx = db.transaction(storeName, 'readwrite');
213
+ const rwStore = rwTx.objectStore(storeName);
214
+ rwStore.add({
215
+ id: 1,
216
+ });
217
+ rwTx.commit();
218
+ const result = await new Promise(resolve => {
219
+ const tx = db.transaction(storeName, 'readonly');
220
+ const store = tx.objectStore(storeName);
221
+ const index = store.index(indexName);
222
+ const getRequest = index.get([1]);
223
+ getRequest.onerror = () => resolve(false);
224
+ getRequest.onsuccess = (event) => {
225
+ resolve(event?.target?.result);
226
+ };
227
+ });
228
+ if (db && typeof db.close === 'function') {
229
+ await db.close();
230
+ }
231
+ await indexedDB.deleteDatabase(dbName);
232
+ if (result === undefined) {
233
+ safariCompatabilityModeResult = true;
234
+ }
235
+ else {
236
+ safariCompatabilityModeResult = false;
237
+ }
238
+ }
239
+ catch (error) {
240
+ safariCompatabilityModeResult = false;
241
+ }
242
+ return safariCompatabilityModeResult;
276
243
  };
277
- var prng = function () { return randomBytes(1).readUInt8(0) / 0xff; };
244
+ const HEX_TO_SHORT = {};
245
+ for (let i = 0; i < 256; i++) {
246
+ let encodedByte = i.toString(16).toLowerCase();
247
+ if (encodedByte.length === 1) {
248
+ encodedByte = `0${encodedByte}`;
249
+ }
250
+ HEX_TO_SHORT[encodedByte] = i;
251
+ }
252
+ const getBytesFromHex = (encoded) => {
253
+ if (encoded.length % 2 !== 0) {
254
+ throw new Error('Hex encoded strings must have an even number length');
255
+ }
256
+ const out = new Uint8Array(encoded.length / 2);
257
+ for (let i = 0; i < encoded.length; i += 2) {
258
+ const encodedByte = encoded.slice(i, i + 2).toLowerCase();
259
+ if (encodedByte in HEX_TO_SHORT) {
260
+ out[i / 2] = HEX_TO_SHORT[encodedByte];
261
+ }
262
+ else {
263
+ throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`);
264
+ }
265
+ }
266
+ return out;
267
+ };
268
+ const randomBytes = (nBytes) => {
269
+ const str = new WordArray().random(nBytes).toString();
270
+ return getBytesFromHex(str);
271
+ };
272
+ const prng = () => randomBytes(1)[0] / 0xff;
278
273
  export function monotonicUlidFactory(seed) {
279
- var ulid = monotonicFactory(prng);
280
- return function () {
274
+ const ulid = monotonicFactory(prng);
275
+ return () => {
281
276
  return ulid(seed);
282
277
  };
283
278
  }
@@ -305,29 +300,18 @@ export function getNow() {
305
300
  }
306
301
  export function sortCompareFunction(sortPredicates) {
307
302
  return function compareFunction(a, b) {
308
- var e_1, _c;
309
- try {
310
- // enable multi-field sort by iterating over predicates until
311
- // a comparison returns -1 or 1
312
- for (var sortPredicates_1 = __values(sortPredicates), sortPredicates_1_1 = sortPredicates_1.next(); !sortPredicates_1_1.done; sortPredicates_1_1 = sortPredicates_1.next()) {
313
- var predicate = sortPredicates_1_1.value;
314
- var field = predicate.field, sortDirection = predicate.sortDirection;
315
- // reverse result when direction is descending
316
- var sortMultiplier = sortDirection === SortDirection.ASCENDING ? 1 : -1;
317
- if (a[field] < b[field]) {
318
- return -1 * sortMultiplier;
319
- }
320
- if (a[field] > b[field]) {
321
- return 1 * sortMultiplier;
322
- }
303
+ // enable multi-field sort by iterating over predicates until
304
+ // a comparison returns -1 or 1
305
+ for (const predicate of sortPredicates) {
306
+ const { field, sortDirection } = predicate;
307
+ // reverse result when direction is descending
308
+ const sortMultiplier = sortDirection === SortDirection.ASCENDING ? 1 : -1;
309
+ if (a[field] < b[field]) {
310
+ return -1 * sortMultiplier;
323
311
  }
324
- }
325
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
326
- finally {
327
- try {
328
- if (sortPredicates_1_1 && !sortPredicates_1_1.done && (_c = sortPredicates_1.return)) _c.call(sortPredicates_1);
312
+ if (a[field] > b[field]) {
313
+ return 1 * sortMultiplier;
329
314
  }
330
- finally { if (e_1) throw e_1.error; }
331
315
  }
332
316
  return 0;
333
317
  };
@@ -337,12 +321,10 @@ export function sortCompareFunction(sortPredicates) {
337
321
  // returns true if equal by value
338
322
  // if nullish is true, treat undefined and null values as equal
339
323
  // to normalize for GQL response values for undefined fields
340
- export function valuesEqual(valA, valB, nullish) {
341
- var e_2, _c;
342
- if (nullish === void 0) { nullish = false; }
343
- var a = valA;
344
- var b = valB;
345
- var nullishCompare = function (_a, _b) {
324
+ export function valuesEqual(valA, valB, nullish = false) {
325
+ let a = valA;
326
+ let b = valB;
327
+ const nullishCompare = (_a, _b) => {
346
328
  return ((_a === undefined || _a === null) && (_b === undefined || _b === null));
347
329
  };
348
330
  // if one of the values is a primitive and the other is an object
@@ -363,15 +345,15 @@ export function valuesEqual(valA, valB, nullish) {
363
345
  return false;
364
346
  }
365
347
  if (a instanceof Set && b instanceof Set) {
366
- a = __spread(a);
367
- b = __spread(b);
348
+ a = [...a];
349
+ b = [...b];
368
350
  }
369
351
  if (a instanceof Map && b instanceof Map) {
370
352
  a = Object.fromEntries(a);
371
353
  b = Object.fromEntries(b);
372
354
  }
373
- var aKeys = Object.keys(a);
374
- var bKeys = Object.keys(b);
355
+ const aKeys = Object.keys(a);
356
+ const bKeys = Object.keys(b);
375
357
  // last condition is to ensure that [] !== [null] even if nullish. However [undefined] === [null] when nullish
376
358
  if (aKeys.length !== bKeys.length && (!nullish || Array.isArray(a))) {
377
359
  return false;
@@ -379,23 +361,13 @@ export function valuesEqual(valA, valB, nullish) {
379
361
  // iterate through the longer set of keys
380
362
  // e.g., for a nullish comparison of a={ a: 1 } and b={ a: 1, b: null }
381
363
  // we want to iterate through bKeys
382
- var keys = aKeys.length >= bKeys.length ? aKeys : bKeys;
383
- try {
384
- for (var keys_1 = __values(keys), keys_1_1 = keys_1.next(); !keys_1_1.done; keys_1_1 = keys_1.next()) {
385
- var key = keys_1_1.value;
386
- var aVal = a[key];
387
- var bVal = b[key];
388
- if (!valuesEqual(aVal, bVal, nullish)) {
389
- return false;
390
- }
391
- }
392
- }
393
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
394
- finally {
395
- try {
396
- if (keys_1_1 && !keys_1_1.done && (_c = keys_1.return)) _c.call(keys_1);
364
+ const keys = aKeys.length >= bKeys.length ? aKeys : bKeys;
365
+ for (const key of keys) {
366
+ const aVal = a[key];
367
+ const bVal = b[key];
368
+ if (!valuesEqual(aVal, bVal, nullish)) {
369
+ return false;
397
370
  }
398
- finally { if (e_2) throw e_2.error; }
399
371
  }
400
372
  return true;
401
373
  }
@@ -409,15 +381,15 @@ export function valuesEqual(valA, valB, nullish) {
409
381
  export function inMemoryPagination(records, pagination) {
410
382
  if (pagination && records.length > 1) {
411
383
  if (pagination.sort) {
412
- var sortPredicates = ModelSortPredicateCreator.getPredicates(pagination.sort);
384
+ const sortPredicates = ModelSortPredicateCreator.getPredicates(pagination.sort);
413
385
  if (sortPredicates.length) {
414
- var compareFn = sortCompareFunction(sortPredicates);
386
+ const compareFn = sortCompareFunction(sortPredicates);
415
387
  records.sort(compareFn);
416
388
  }
417
389
  }
418
- var _c = pagination.page, page = _c === void 0 ? 0 : _c, _d = pagination.limit, limit = _d === void 0 ? 0 : _d;
419
- var start = Math.max(0, page * limit) || 0;
420
- var end = limit > 0 ? start + limit : records.length;
390
+ const { page = 0, limit = 0 } = pagination;
391
+ const start = Math.max(0, page * limit) || 0;
392
+ const end = limit > 0 ? start + limit : records.length;
421
393
  return records.slice(start, end);
422
394
  }
423
395
  return records;
@@ -429,43 +401,13 @@ export function inMemoryPagination(records, pagination) {
429
401
  * return Promise<boolean>: `true` for a matching item, `false` otherwise.
430
402
  * @returns A `Promise<boolean>`, `true` if "some" items match; `false` otherwise.
431
403
  */
432
- export function asyncSome(items, matches) {
433
- return __awaiter(this, void 0, void 0, function () {
434
- var items_1, items_1_1, item, e_3_1;
435
- var e_3, _c;
436
- return __generator(this, function (_d) {
437
- switch (_d.label) {
438
- case 0:
439
- _d.trys.push([0, 5, 6, 7]);
440
- items_1 = __values(items), items_1_1 = items_1.next();
441
- _d.label = 1;
442
- case 1:
443
- if (!!items_1_1.done) return [3 /*break*/, 4];
444
- item = items_1_1.value;
445
- return [4 /*yield*/, matches(item)];
446
- case 2:
447
- if (_d.sent()) {
448
- return [2 /*return*/, true];
449
- }
450
- _d.label = 3;
451
- case 3:
452
- items_1_1 = items_1.next();
453
- return [3 /*break*/, 1];
454
- case 4: return [3 /*break*/, 7];
455
- case 5:
456
- e_3_1 = _d.sent();
457
- e_3 = { error: e_3_1 };
458
- return [3 /*break*/, 7];
459
- case 6:
460
- try {
461
- if (items_1_1 && !items_1_1.done && (_c = items_1.return)) _c.call(items_1);
462
- }
463
- finally { if (e_3) throw e_3.error; }
464
- return [7 /*endfinally*/];
465
- case 7: return [2 /*return*/, false];
466
- }
467
- });
468
- });
404
+ export async function asyncSome(items, matches) {
405
+ for (const item of items) {
406
+ if (await matches(item)) {
407
+ return true;
408
+ }
409
+ }
410
+ return false;
469
411
  }
470
412
  /**
471
413
  * An `aysnc` implementation of `Array.every()`. Returns as soon as a non-match is found.
@@ -474,43 +416,13 @@ export function asyncSome(items, matches) {
474
416
  * return Promise<boolean>: `true` for a matching item, `false` otherwise.
475
417
  * @returns A `Promise<boolean>`, `true` if every item matches; `false` otherwise.
476
418
  */
477
- export function asyncEvery(items, matches) {
478
- return __awaiter(this, void 0, void 0, function () {
479
- var items_2, items_2_1, item, e_4_1;
480
- var e_4, _c;
481
- return __generator(this, function (_d) {
482
- switch (_d.label) {
483
- case 0:
484
- _d.trys.push([0, 5, 6, 7]);
485
- items_2 = __values(items), items_2_1 = items_2.next();
486
- _d.label = 1;
487
- case 1:
488
- if (!!items_2_1.done) return [3 /*break*/, 4];
489
- item = items_2_1.value;
490
- return [4 /*yield*/, matches(item)];
491
- case 2:
492
- if (!(_d.sent())) {
493
- return [2 /*return*/, false];
494
- }
495
- _d.label = 3;
496
- case 3:
497
- items_2_1 = items_2.next();
498
- return [3 /*break*/, 1];
499
- case 4: return [3 /*break*/, 7];
500
- case 5:
501
- e_4_1 = _d.sent();
502
- e_4 = { error: e_4_1 };
503
- return [3 /*break*/, 7];
504
- case 6:
505
- try {
506
- if (items_2_1 && !items_2_1.done && (_c = items_2.return)) _c.call(items_2);
507
- }
508
- finally { if (e_4) throw e_4.error; }
509
- return [7 /*endfinally*/];
510
- case 7: return [2 /*return*/, true];
511
- }
512
- });
513
- });
419
+ export async function asyncEvery(items, matches) {
420
+ for (const item of items) {
421
+ if (!(await matches(item))) {
422
+ return false;
423
+ }
424
+ }
425
+ return true;
514
426
  }
515
427
  /**
516
428
  * An `async` implementation of `Array.filter()`. Returns after all items have been filtered.
@@ -520,162 +432,114 @@ export function asyncEvery(items, matches) {
520
432
  * return Promise<boolean>: `true` for a matching item, `false` otherwise.
521
433
  * @returns A `Promise<T>` of matching items.
522
434
  */
523
- export function asyncFilter(items, matches) {
524
- return __awaiter(this, void 0, void 0, function () {
525
- var results, items_3, items_3_1, item, e_5_1;
526
- var e_5, _c;
527
- return __generator(this, function (_d) {
528
- switch (_d.label) {
529
- case 0:
530
- results = [];
531
- _d.label = 1;
532
- case 1:
533
- _d.trys.push([1, 6, 7, 8]);
534
- items_3 = __values(items), items_3_1 = items_3.next();
535
- _d.label = 2;
536
- case 2:
537
- if (!!items_3_1.done) return [3 /*break*/, 5];
538
- item = items_3_1.value;
539
- return [4 /*yield*/, matches(item)];
540
- case 3:
541
- if (_d.sent()) {
542
- results.push(item);
543
- }
544
- _d.label = 4;
545
- case 4:
546
- items_3_1 = items_3.next();
547
- return [3 /*break*/, 2];
548
- case 5: return [3 /*break*/, 8];
549
- case 6:
550
- e_5_1 = _d.sent();
551
- e_5 = { error: e_5_1 };
552
- return [3 /*break*/, 8];
553
- case 7:
554
- try {
555
- if (items_3_1 && !items_3_1.done && (_c = items_3.return)) _c.call(items_3);
556
- }
557
- finally { if (e_5) throw e_5.error; }
558
- return [7 /*endfinally*/];
559
- case 8: return [2 /*return*/, results];
560
- }
561
- });
562
- });
435
+ export async function asyncFilter(items, matches) {
436
+ const results = [];
437
+ for (const item of items) {
438
+ if (await matches(item)) {
439
+ results.push(item);
440
+ }
441
+ }
442
+ return results;
563
443
  }
564
- export var isAWSDate = function (val) {
444
+ export const isAWSDate = (val) => {
565
445
  return !!/^\d{4}-\d{2}-\d{2}(Z|[+-]\d{2}:\d{2}($|:\d{2}))?$/.exec(val);
566
446
  };
567
- export var isAWSTime = function (val) {
447
+ export const isAWSTime = (val) => {
568
448
  return !!/^\d{2}:\d{2}(:\d{2}(.\d+)?)?(Z|[+-]\d{2}:\d{2}($|:\d{2}))?$/.exec(val);
569
449
  };
570
- export var isAWSDateTime = function (val) {
450
+ export const isAWSDateTime = (val) => {
571
451
  return !!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(.\d+)?)?(Z|[+-]\d{2}:\d{2}($|:\d{2}))?$/.exec(val);
572
452
  };
573
- export var isAWSTimestamp = function (val) {
453
+ export const isAWSTimestamp = (val) => {
574
454
  return !!/^\d+$/.exec(String(val));
575
455
  };
576
- export var isAWSEmail = function (val) {
456
+ export const isAWSEmail = (val) => {
577
457
  return !!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.exec(val);
578
458
  };
579
- export var isAWSJSON = function (val) {
459
+ export const isAWSJSON = (val) => {
580
460
  try {
581
461
  JSON.parse(val);
582
462
  return true;
583
463
  }
584
- catch (_c) {
464
+ catch {
585
465
  return false;
586
466
  }
587
467
  };
588
- export var isAWSURL = function (val) {
468
+ export const isAWSURL = (val) => {
589
469
  try {
590
- return !!new URL(val);
470
+ return !!new AmplifyUrl(val);
591
471
  }
592
- catch (_c) {
472
+ catch {
593
473
  return false;
594
474
  }
595
475
  };
596
- export var isAWSPhone = function (val) {
476
+ export const isAWSPhone = (val) => {
597
477
  return !!/^\+?\d[\d\s-]+$/.exec(val);
598
478
  };
599
- export var isAWSIPAddress = function (val) {
479
+ export const isAWSIPAddress = (val) => {
600
480
  return !!/((^((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))$)|(^((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?$))$/.exec(val);
601
481
  };
602
- var DeferredPromise = /** @class */ (function () {
603
- function DeferredPromise() {
604
- var self = this;
605
- this.promise = new Promise(function (resolve, reject) {
482
+ export class DeferredPromise {
483
+ constructor() {
484
+ const self = this;
485
+ this.promise = new Promise((resolve, reject) => {
606
486
  self.resolve = resolve;
607
487
  self.reject = reject;
608
488
  });
609
489
  }
610
- return DeferredPromise;
611
- }());
612
- export { DeferredPromise };
613
- var DeferredCallbackResolver = /** @class */ (function () {
614
- function DeferredCallbackResolver(options) {
490
+ }
491
+ export class DeferredCallbackResolver {
492
+ constructor(options) {
615
493
  this.limitPromise = new DeferredPromise();
616
494
  this.raceInFlight = false;
617
- this.callback = function () { };
618
- this.defaultErrorHandler = function (msg) {
619
- if (msg === void 0) { msg = 'DeferredCallbackResolver error'; }
495
+ this.callback = () => { };
496
+ this.defaultErrorHandler = (msg = 'DeferredCallbackResolver error') => {
620
497
  throw new Error(msg);
621
498
  };
622
499
  this.callback = options.callback;
623
500
  this.errorHandler = options.errorHandler || this.defaultErrorHandler;
624
501
  this.maxInterval = options.maxInterval || 2000;
625
502
  }
626
- DeferredCallbackResolver.prototype.startTimer = function () {
627
- var _this = this;
628
- this.timerPromise = new Promise(function (resolve, reject) {
629
- _this.timer = setTimeout(function () {
503
+ startTimer() {
504
+ this.timerPromise = new Promise((resolve, reject) => {
505
+ this.timer = setTimeout(() => {
630
506
  resolve(LimitTimerRaceResolvedValues.TIMER);
631
- }, _this.maxInterval);
632
- });
633
- };
634
- DeferredCallbackResolver.prototype.racePromises = function () {
635
- return __awaiter(this, void 0, void 0, function () {
636
- var winner, err_1;
637
- return __generator(this, function (_c) {
638
- switch (_c.label) {
639
- case 0:
640
- _c.trys.push([0, 2, 3, 4]);
641
- this.raceInFlight = true;
642
- this.startTimer();
643
- return [4 /*yield*/, Promise.race([
644
- this.timerPromise,
645
- this.limitPromise.promise,
646
- ])];
647
- case 1:
648
- winner = _c.sent();
649
- this.callback();
650
- return [3 /*break*/, 4];
651
- case 2:
652
- err_1 = _c.sent();
653
- this.errorHandler(err_1);
654
- return [3 /*break*/, 4];
655
- case 3:
656
- // reset for the next race
657
- this.clear();
658
- this.raceInFlight = false;
659
- this.limitPromise = new DeferredPromise();
660
- return [2 /*return*/, winner];
661
- case 4: return [2 /*return*/];
662
- }
663
- });
507
+ }, this.maxInterval);
664
508
  });
665
- };
666
- DeferredCallbackResolver.prototype.start = function () {
509
+ }
510
+ async racePromises() {
511
+ let winner;
512
+ try {
513
+ this.raceInFlight = true;
514
+ this.startTimer();
515
+ winner = await Promise.race([
516
+ this.timerPromise,
517
+ this.limitPromise.promise,
518
+ ]);
519
+ this.callback();
520
+ }
521
+ catch (err) {
522
+ this.errorHandler(err);
523
+ }
524
+ finally {
525
+ // reset for the next race
526
+ this.clear();
527
+ this.raceInFlight = false;
528
+ this.limitPromise = new DeferredPromise();
529
+ return winner;
530
+ }
531
+ }
532
+ start() {
667
533
  if (!this.raceInFlight)
668
534
  this.racePromises();
669
- };
670
- DeferredCallbackResolver.prototype.clear = function () {
535
+ }
536
+ clear() {
671
537
  clearTimeout(this.timer);
672
- };
673
- DeferredCallbackResolver.prototype.resolve = function () {
538
+ }
539
+ resolve() {
674
540
  this.limitPromise.resolve(LimitTimerRaceResolvedValues.LIMIT);
675
- };
676
- return DeferredCallbackResolver;
677
- }());
678
- export { DeferredCallbackResolver };
541
+ }
542
+ }
679
543
  /**
680
544
  * merge two sets of patches created by immer produce.
681
545
  * newPatches take precedent over oldPatches for patches modifying the same path.
@@ -694,17 +558,17 @@ export { DeferredCallbackResolver };
694
558
  * @return merged patches
695
559
  */
696
560
  export function mergePatches(originalSource, oldPatches, newPatches) {
697
- var patchesToMerge = oldPatches.concat(newPatches);
698
- var patches;
699
- produce(originalSource, function (draft) {
561
+ const patchesToMerge = oldPatches.concat(newPatches);
562
+ let patches;
563
+ produce(originalSource, draft => {
700
564
  applyPatches(draft, patchesToMerge);
701
- }, function (p) {
565
+ }, p => {
702
566
  patches = p;
703
567
  });
704
568
  return patches;
705
569
  }
706
- export var getStorename = function (namespace, modelName) {
707
- var storeName = namespace + "_" + modelName;
570
+ export const getStorename = (namespace, modelName) => {
571
+ const storeName = `${namespace}_${modelName}`;
708
572
  return storeName;
709
573
  };
710
574
  //#region Key Utils
@@ -740,73 +604,70 @@ export var getStorename = function (namespace, modelName) {
740
604
 
741
605
  See 'processCompositeKeys' test in util.test.ts for more examples
742
606
  */
743
- export var processCompositeKeys = function (attributes) {
744
- var extractCompositeSortKey = function (_c) {
745
- var
746
- // ignore the HK (fields[0]) we only need to include the composite sort key fields[1...n]
747
- _d = __read(_c.properties.fields), sortKeyFields = _d.slice(1);
748
- return sortKeyFields;
749
- };
750
- var compositeKeyFields = attributes
607
+ export const processCompositeKeys = (attributes) => {
608
+ const extractCompositeSortKey = ({ properties: {
609
+ // ignore the HK (fields[0]) we only need to include the composite sort key fields[1...n]
610
+ fields: [, ...sortKeyFields], }, }) => sortKeyFields;
611
+ const compositeKeyFields = attributes
751
612
  .filter(isModelAttributeCompositeKey)
752
613
  .map(extractCompositeSortKey);
753
614
  /*
754
615
  if 2 sets of fields have any intersecting fields => combine them into 1 union set
755
616
  e.g., ['a', 'b', 'c'] and ['a', 'b', 'd'] => ['a', 'b', 'c', 'd']
756
617
  */
757
- var combineIntersecting = function (fields) {
758
- return fields.reduce(function (combined, sortKeyFields) {
759
- var sortKeyFieldsSet = new Set(sortKeyFields);
760
- if (combined.length === 0) {
761
- combined.push(sortKeyFieldsSet);
762
- return combined;
763
- }
764
- // does the current set share values with another set we've already added to `combined`?
765
- var intersectingSetIdx = combined.findIndex(function (existingSet) {
766
- return __spread(existingSet).some(function (f) { return sortKeyFieldsSet.has(f); });
767
- });
768
- if (intersectingSetIdx > -1) {
769
- var union = new Set(__spread(combined[intersectingSetIdx], sortKeyFieldsSet));
770
- // combine the current set with the intersecting set we found above
771
- combined[intersectingSetIdx] = union;
772
- }
773
- else {
774
- // none of the sets in `combined` have intersecting values with the current set
775
- combined.push(sortKeyFieldsSet);
776
- }
618
+ const combineIntersecting = (fields) => fields.reduce((combined, sortKeyFields) => {
619
+ const sortKeyFieldsSet = new Set(sortKeyFields);
620
+ if (combined.length === 0) {
621
+ combined.push(sortKeyFieldsSet);
777
622
  return combined;
778
- }, []);
779
- };
780
- var initial = combineIntersecting(compositeKeyFields);
623
+ }
624
+ // does the current set share values with another set we've already added to `combined`?
625
+ const intersectingSetIdx = combined.findIndex(existingSet => {
626
+ return [...existingSet].some(f => sortKeyFieldsSet.has(f));
627
+ });
628
+ if (intersectingSetIdx > -1) {
629
+ const union = new Set([
630
+ ...combined[intersectingSetIdx],
631
+ ...sortKeyFieldsSet,
632
+ ]);
633
+ // combine the current set with the intersecting set we found above
634
+ combined[intersectingSetIdx] = union;
635
+ }
636
+ else {
637
+ // none of the sets in `combined` have intersecting values with the current set
638
+ combined.push(sortKeyFieldsSet);
639
+ }
640
+ return combined;
641
+ }, []);
642
+ const initial = combineIntersecting(compositeKeyFields);
781
643
  // a single pass pay not be enough to correctly combine all the fields
782
644
  // call the function once more to get a final merged list of sets
783
- var combined = combineIntersecting(initial);
645
+ const combined = combineIntersecting(initial);
784
646
  return combined;
785
647
  };
786
- export var extractKeyIfExists = function (modelDefinition) {
787
- var _c;
788
- var keyAttribute = (_c = modelDefinition === null || modelDefinition === void 0 ? void 0 : modelDefinition.attributes) === null || _c === void 0 ? void 0 : _c.find(isModelAttributeKey);
648
+ export const extractKeyIfExists = (modelDefinition) => {
649
+ const keyAttribute = modelDefinition?.attributes?.find(isModelAttributeKey);
789
650
  return keyAttribute;
790
651
  };
791
- export var extractPrimaryKeyFieldNames = function (modelDefinition) {
792
- var keyAttribute = extractKeyIfExists(modelDefinition);
652
+ export const extractPrimaryKeyFieldNames = (modelDefinition) => {
653
+ const keyAttribute = extractKeyIfExists(modelDefinition);
793
654
  if (keyAttribute && isModelAttributePrimaryKey(keyAttribute)) {
794
655
  return keyAttribute.properties.fields;
795
656
  }
796
657
  return [ID];
797
658
  };
798
- export var extractPrimaryKeyValues = function (model, keyFields) {
799
- return keyFields.map(function (key) { return model[key]; });
659
+ export const extractPrimaryKeyValues = (model, keyFields) => {
660
+ return keyFields.map(key => model[key]);
800
661
  };
801
- export var extractPrimaryKeysAndValues = function (model, keyFields) {
802
- var primaryKeysAndValues = {};
803
- keyFields.forEach(function (key) { return (primaryKeysAndValues[key] = model[key]); });
662
+ export const extractPrimaryKeysAndValues = (model, keyFields) => {
663
+ const primaryKeysAndValues = {};
664
+ keyFields.forEach(key => (primaryKeysAndValues[key] = model[key]));
804
665
  return primaryKeysAndValues;
805
666
  };
806
667
  // IdentifierFields<ManagedIdentifier>
807
668
  // Default behavior without explicit @primaryKey defined
808
- export var isIdManaged = function (modelDefinition) {
809
- var keyAttribute = extractKeyIfExists(modelDefinition);
669
+ export const isIdManaged = (modelDefinition) => {
670
+ const keyAttribute = extractKeyIfExists(modelDefinition);
810
671
  if (keyAttribute && isModelAttributePrimaryKey(keyAttribute)) {
811
672
  return false;
812
673
  }
@@ -814,26 +675,25 @@ export var isIdManaged = function (modelDefinition) {
814
675
  };
815
676
  // IdentifierFields<OptionallyManagedIdentifier>
816
677
  // @primaryKey with explicit `id` in the PK. Single key or composite
817
- export var isIdOptionallyManaged = function (modelDefinition) {
818
- var keyAttribute = extractKeyIfExists(modelDefinition);
678
+ export const isIdOptionallyManaged = (modelDefinition) => {
679
+ const keyAttribute = extractKeyIfExists(modelDefinition);
819
680
  if (keyAttribute && isModelAttributePrimaryKey(keyAttribute)) {
820
681
  return keyAttribute.properties.fields[0] === ID;
821
682
  }
822
683
  return false;
823
684
  };
824
- export var establishRelationAndKeys = function (namespace) {
825
- var relationship = {};
826
- var keys = {};
827
- Object.keys(namespace.models).forEach(function (mKey) {
828
- var e_6, _c;
685
+ export const establishRelationAndKeys = (namespace) => {
686
+ const relationship = {};
687
+ const keys = {};
688
+ Object.keys(namespace.models).forEach((mKey) => {
829
689
  relationship[mKey] = { indexes: [], relationTypes: [] };
830
690
  keys[mKey] = {};
831
- var model = namespace.models[mKey];
832
- Object.keys(model.fields).forEach(function (attr) {
833
- var fieldAttribute = model.fields[attr];
691
+ const model = namespace.models[mKey];
692
+ Object.keys(model.fields).forEach((attr) => {
693
+ const fieldAttribute = model.fields[attr];
834
694
  if (typeof fieldAttribute.type === 'object' &&
835
695
  'model' in fieldAttribute.type) {
836
- var connectionType = fieldAttribute.association.connectionType;
696
+ const connectionType = fieldAttribute.association.connectionType;
837
697
  relationship[mKey].relationTypes.push({
838
698
  fieldName: fieldAttribute.name,
839
699
  modelName: fieldAttribute.type.model,
@@ -843,15 +703,12 @@ export var establishRelationAndKeys = function (namespace) {
843
703
  associatedWith: fieldAttribute.association['associatedWith'],
844
704
  });
845
705
  if (connectionType === 'BELONGS_TO') {
846
- var targetNames = extractTargetNamesFromSrc(fieldAttribute.association);
706
+ const targetNames = extractTargetNamesFromSrc(fieldAttribute.association);
847
707
  if (targetNames) {
848
- var idxName_1 = indexNameFromKeys(targetNames);
849
- var idxExists = relationship[mKey].indexes.find(function (_c) {
850
- var _d = __read(_c, 1), index = _d[0];
851
- return index === idxName_1;
852
- });
708
+ const idxName = indexNameFromKeys(targetNames);
709
+ const idxExists = relationship[mKey].indexes.find(([index]) => index === idxName);
853
710
  if (!idxExists) {
854
- relationship[mKey].indexes.push([idxName_1, targetNames]);
711
+ relationship[mKey].indexes.push([idxName, targetNames]);
855
712
  }
856
713
  }
857
714
  }
@@ -859,37 +716,21 @@ export var establishRelationAndKeys = function (namespace) {
859
716
  });
860
717
  if (model.attributes) {
861
718
  keys[mKey].compositeKeys = processCompositeKeys(model.attributes);
862
- var _loop_1 = function (attribute) {
719
+ for (const attribute of model.attributes) {
863
720
  if (!isModelAttributeKey(attribute)) {
864
- return "continue";
721
+ continue;
865
722
  }
866
- var fields = attribute.properties.fields;
723
+ const { fields } = attribute.properties;
867
724
  if (isModelAttributePrimaryKey(attribute)) {
868
725
  keys[mKey].primaryKey = fields;
869
- return "continue";
726
+ continue;
870
727
  }
871
728
  // create indexes for all other keys
872
- var idxName = indexNameFromKeys(fields);
873
- var idxExists = relationship[mKey].indexes.find(function (_c) {
874
- var _d = __read(_c, 1), index = _d[0];
875
- return index === idxName;
876
- });
729
+ const idxName = indexNameFromKeys(fields);
730
+ const idxExists = relationship[mKey].indexes.find(([index]) => index === idxName);
877
731
  if (!idxExists) {
878
732
  relationship[mKey].indexes.push([idxName, fields]);
879
733
  }
880
- };
881
- try {
882
- for (var _d = __values(model.attributes), _e = _d.next(); !_e.done; _e = _d.next()) {
883
- var attribute = _e.value;
884
- _loop_1(attribute);
885
- }
886
- }
887
- catch (e_6_1) { e_6 = { error: e_6_1 }; }
888
- finally {
889
- try {
890
- if (_e && !_e.done && (_c = _d.return)) _c.call(_d);
891
- }
892
- finally { if (e_6) throw e_6.error; }
893
734
  }
894
735
  }
895
736
  // set 'id' as the PK for models without a custom PK explicitly defined
@@ -905,29 +746,26 @@ export var establishRelationAndKeys = function (namespace) {
905
746
  });
906
747
  return [relationship, keys];
907
748
  };
908
- export var getIndex = function (rel, src) {
909
- var indexName;
910
- rel.some(function (relItem) {
749
+ export const getIndex = (rel, src) => {
750
+ let indexName;
751
+ rel.some((relItem) => {
911
752
  if (relItem.modelName === src) {
912
- var targetNames = extractTargetNamesFromSrc(relItem);
753
+ const targetNames = extractTargetNamesFromSrc(relItem);
913
754
  indexName = targetNames && indexNameFromKeys(targetNames);
914
755
  return true;
915
756
  }
916
757
  });
917
758
  return indexName;
918
759
  };
919
- export var getIndexFromAssociation = function (indexes, src) {
920
- var indexName;
760
+ export const getIndexFromAssociation = (indexes, src) => {
761
+ let indexName;
921
762
  if (Array.isArray(src)) {
922
763
  indexName = indexNameFromKeys(src);
923
764
  }
924
765
  else {
925
766
  indexName = src;
926
767
  }
927
- var associationIndex = indexes.find(function (_c) {
928
- var _d = __read(_c, 1), idxName = _d[0];
929
- return idxName === indexName;
930
- });
768
+ const associationIndex = indexes.find(([idxName]) => idxName === indexName);
931
769
  return associationIndex && associationIndex[0];
932
770
  };
933
771
  /**
@@ -937,9 +775,9 @@ the single field `targetName` has been replaced with an array of `targetNames`.
937
775
  * @param src {RelationType | ModelAssociation | undefined}
938
776
  * @returns array of targetNames, or `undefined`
939
777
  */
940
- export var extractTargetNamesFromSrc = function (src) {
941
- var targetName = src === null || src === void 0 ? void 0 : src.targetName;
942
- var targetNames = src === null || src === void 0 ? void 0 : src.targetNames;
778
+ export const extractTargetNamesFromSrc = (src) => {
779
+ const targetName = src?.targetName;
780
+ const targetNames = src?.targetNames;
943
781
  if (Array.isArray(targetNames)) {
944
782
  return targetNames;
945
783
  }
@@ -952,24 +790,23 @@ export var extractTargetNamesFromSrc = function (src) {
952
790
  };
953
791
  // Generates spinal-cased index name from an array of key field names
954
792
  // E.g. for keys `[id, title]` => 'id-title'
955
- export var indexNameFromKeys = function (keys) {
956
- return keys.reduce(function (prev, cur, idx) {
793
+ export const indexNameFromKeys = (keys) => {
794
+ return keys.reduce((prev, cur, idx) => {
957
795
  if (idx === 0) {
958
796
  return cur;
959
797
  }
960
- return "" + prev + IDENTIFIER_KEY_SEPARATOR + cur;
798
+ return `${prev}${IDENTIFIER_KEY_SEPARATOR}${cur}`;
961
799
  }, '');
962
800
  };
963
- export var keysEqual = function (keysA, keysB) {
801
+ export const keysEqual = (keysA, keysB) => {
964
802
  if (keysA.length !== keysB.length) {
965
803
  return false;
966
804
  }
967
- return keysA.every(function (key, idx) { return key === keysB[idx]; });
805
+ return keysA.every((key, idx) => key === keysB[idx]);
968
806
  };
969
807
  // Returns primary keys for a model
970
- export var getIndexKeys = function (namespace, modelName) {
971
- var _c, _d;
972
- var keyPath = (_d = (_c = namespace === null || namespace === void 0 ? void 0 : namespace.keys) === null || _c === void 0 ? void 0 : _c[modelName]) === null || _d === void 0 ? void 0 : _d.primaryKey;
808
+ export const getIndexKeys = (namespace, modelName) => {
809
+ const keyPath = namespace?.keys?.[modelName]?.primaryKey;
973
810
  if (keyPath) {
974
811
  return keyPath;
975
812
  }
@@ -988,15 +825,16 @@ export var getIndexKeys = function (namespace, modelName) {
988
825
  * @param definition modelDefinition to inspect.
989
826
  * @returns An object mapping `createdAt` and `updatedAt` to their field names.
990
827
  */
991
- export var getTimestampFields = function (definition) {
992
- var _c, _d;
993
- var modelAttributes = (_c = definition.attributes) === null || _c === void 0 ? void 0 : _c.find(function (attr) { return attr.type === 'model'; });
994
- var timestampFieldsMap = (_d = modelAttributes === null || modelAttributes === void 0 ? void 0 : modelAttributes.properties) === null || _d === void 0 ? void 0 : _d.timestamps;
995
- var defaultFields = {
828
+ export const getTimestampFields = (definition) => {
829
+ const modelAttributes = definition.attributes?.find(attr => attr.type === 'model');
830
+ const timestampFieldsMap = modelAttributes?.properties?.timestamps;
831
+ const defaultFields = {
996
832
  createdAt: 'createdAt',
997
833
  updatedAt: 'updatedAt',
998
834
  };
999
- var customFields = timestampFieldsMap || {};
1000
- return __assign(__assign({}, defaultFields), customFields);
835
+ const customFields = timestampFieldsMap || {};
836
+ return {
837
+ ...defaultFields,
838
+ ...customFields,
839
+ };
1001
840
  };
1002
- //# sourceMappingURL=util.js.map