@warp-drive/legacy 5.6.0-alpha.11

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 (211) hide show
  1. package/CHANGELOG.md +1 -0
  2. package/LICENSE.md +23 -0
  3. package/README.md +54 -0
  4. package/addon-main.cjs +5 -0
  5. package/declarations/adapter/-private/build-url-mixin.d.ts +34 -0
  6. package/declarations/adapter/-private/build-url-mixin.d.ts.map +1 -0
  7. package/declarations/adapter/-private/fastboot-interface.d.ts +9 -0
  8. package/declarations/adapter/-private/fastboot-interface.d.ts.map +1 -0
  9. package/declarations/adapter/-private/utils/continue-on-reject.d.ts +8 -0
  10. package/declarations/adapter/-private/utils/continue-on-reject.d.ts.map +1 -0
  11. package/declarations/adapter/-private/utils/determine-body-promise.d.ts +5 -0
  12. package/declarations/adapter/-private/utils/determine-body-promise.d.ts.map +1 -0
  13. package/declarations/adapter/-private/utils/fetch.d.ts +9 -0
  14. package/declarations/adapter/-private/utils/fetch.d.ts.map +1 -0
  15. package/declarations/adapter/-private/utils/parse-response-headers.d.ts +2 -0
  16. package/declarations/adapter/-private/utils/parse-response-headers.d.ts.map +1 -0
  17. package/declarations/adapter/-private/utils/serialize-into-hash.d.ts +7 -0
  18. package/declarations/adapter/-private/utils/serialize-into-hash.d.ts.map +1 -0
  19. package/declarations/adapter/-private/utils/serialize-query-params.d.ts +6 -0
  20. package/declarations/adapter/-private/utils/serialize-query-params.d.ts.map +1 -0
  21. package/declarations/adapter/-private.d.ts +6 -0
  22. package/declarations/adapter/-private.d.ts.map +1 -0
  23. package/declarations/adapter/error.d.ts +188 -0
  24. package/declarations/adapter/error.d.ts.map +1 -0
  25. package/declarations/adapter/json-api.d.ts +234 -0
  26. package/declarations/adapter/json-api.d.ts.map +1 -0
  27. package/declarations/adapter/rest.d.ts +823 -0
  28. package/declarations/adapter/rest.d.ts.map +1 -0
  29. package/declarations/adapter.d.ts +801 -0
  30. package/declarations/adapter.d.ts.map +1 -0
  31. package/declarations/compat/-private.d.ts +14 -0
  32. package/declarations/compat/-private.d.ts.map +1 -0
  33. package/declarations/compat/builders/find-all.d.ts +33 -0
  34. package/declarations/compat/builders/find-all.d.ts.map +1 -0
  35. package/declarations/compat/builders/find-record.d.ts +54 -0
  36. package/declarations/compat/builders/find-record.d.ts.map +1 -0
  37. package/declarations/compat/builders/query.d.ts +61 -0
  38. package/declarations/compat/builders/query.d.ts.map +1 -0
  39. package/declarations/compat/builders/save-record.d.ts +32 -0
  40. package/declarations/compat/builders/save-record.d.ts.map +1 -0
  41. package/declarations/compat/builders/utils.d.ts +4 -0
  42. package/declarations/compat/builders/utils.d.ts.map +1 -0
  43. package/declarations/compat/builders.d.ts +15 -0
  44. package/declarations/compat/builders.d.ts.map +1 -0
  45. package/declarations/compat/legacy-network-handler/fetch-manager.d.ts +47 -0
  46. package/declarations/compat/legacy-network-handler/fetch-manager.d.ts.map +1 -0
  47. package/declarations/compat/legacy-network-handler/identifier-has-id.d.ts +3 -0
  48. package/declarations/compat/legacy-network-handler/identifier-has-id.d.ts.map +1 -0
  49. package/declarations/compat/legacy-network-handler/legacy-data-fetch.d.ts +12 -0
  50. package/declarations/compat/legacy-network-handler/legacy-data-fetch.d.ts.map +1 -0
  51. package/declarations/compat/legacy-network-handler/legacy-data-utils.d.ts +6 -0
  52. package/declarations/compat/legacy-network-handler/legacy-data-utils.d.ts.map +1 -0
  53. package/declarations/compat/legacy-network-handler/legacy-network-handler.d.ts +3 -0
  54. package/declarations/compat/legacy-network-handler/legacy-network-handler.d.ts.map +1 -0
  55. package/declarations/compat/legacy-network-handler/minimum-adapter-interface.d.ts +527 -0
  56. package/declarations/compat/legacy-network-handler/minimum-adapter-interface.d.ts.map +1 -0
  57. package/declarations/compat/legacy-network-handler/minimum-serializer-interface.d.ts +224 -0
  58. package/declarations/compat/legacy-network-handler/minimum-serializer-interface.d.ts.map +1 -0
  59. package/declarations/compat/legacy-network-handler/serializer-response.d.ts +7 -0
  60. package/declarations/compat/legacy-network-handler/serializer-response.d.ts.map +1 -0
  61. package/declarations/compat/legacy-network-handler/snapshot-record-array.d.ts +89 -0
  62. package/declarations/compat/legacy-network-handler/snapshot-record-array.d.ts.map +1 -0
  63. package/declarations/compat/legacy-network-handler/snapshot.d.ts +237 -0
  64. package/declarations/compat/legacy-network-handler/snapshot.d.ts.map +1 -0
  65. package/declarations/compat/utils.d.ts +138 -0
  66. package/declarations/compat/utils.d.ts.map +1 -0
  67. package/declarations/compat.d.ts +134 -0
  68. package/declarations/compat.d.ts.map +1 -0
  69. package/declarations/model/-private/attr.d.ts +165 -0
  70. package/declarations/model/-private/attr.d.ts.map +1 -0
  71. package/declarations/model/-private/attr.type-test.d.ts +2 -0
  72. package/declarations/model/-private/attr.type-test.d.ts.map +1 -0
  73. package/declarations/model/-private/belongs-to.d.ts +173 -0
  74. package/declarations/model/-private/belongs-to.d.ts.map +1 -0
  75. package/declarations/model/-private/belongs-to.type-test.d.ts +2 -0
  76. package/declarations/model/-private/belongs-to.type-test.d.ts.map +1 -0
  77. package/declarations/model/-private/debug/assert-polymorphic-type.d.ts +6 -0
  78. package/declarations/model/-private/debug/assert-polymorphic-type.d.ts.map +1 -0
  79. package/declarations/model/-private/errors.d.ts +290 -0
  80. package/declarations/model/-private/errors.d.ts.map +1 -0
  81. package/declarations/model/-private/has-many.d.ts +164 -0
  82. package/declarations/model/-private/has-many.d.ts.map +1 -0
  83. package/declarations/model/-private/has-many.type-test.d.ts +2 -0
  84. package/declarations/model/-private/has-many.type-test.d.ts.map +1 -0
  85. package/declarations/model/-private/hooks.d.ts +11 -0
  86. package/declarations/model/-private/hooks.d.ts.map +1 -0
  87. package/declarations/model/-private/legacy-relationships-support.d.ts +57 -0
  88. package/declarations/model/-private/legacy-relationships-support.d.ts.map +1 -0
  89. package/declarations/model/-private/model-for-mixin.d.ts +4 -0
  90. package/declarations/model/-private/model-for-mixin.d.ts.map +1 -0
  91. package/declarations/model/-private/model-methods.d.ts +35 -0
  92. package/declarations/model/-private/model-methods.d.ts.map +1 -0
  93. package/declarations/model/-private/model.d.ts +1270 -0
  94. package/declarations/model/-private/model.d.ts.map +1 -0
  95. package/declarations/model/-private/model.type-test.d.ts +2 -0
  96. package/declarations/model/-private/model.type-test.d.ts.map +1 -0
  97. package/declarations/model/-private/notify-changes.d.ts +5 -0
  98. package/declarations/model/-private/notify-changes.d.ts.map +1 -0
  99. package/declarations/model/-private/promise-belongs-to.d.ts +40 -0
  100. package/declarations/model/-private/promise-belongs-to.d.ts.map +1 -0
  101. package/declarations/model/-private/promise-many-array.d.ts +126 -0
  102. package/declarations/model/-private/promise-many-array.d.ts.map +1 -0
  103. package/declarations/model/-private/promise-proxy-base.d.ts +3 -0
  104. package/declarations/model/-private/promise-proxy-base.d.ts.map +1 -0
  105. package/declarations/model/-private/record-state.d.ts +78 -0
  106. package/declarations/model/-private/record-state.d.ts.map +1 -0
  107. package/declarations/model/-private/references/belongs-to.d.ts +495 -0
  108. package/declarations/model/-private/references/belongs-to.d.ts.map +1 -0
  109. package/declarations/model/-private/references/has-many.d.ts +504 -0
  110. package/declarations/model/-private/references/has-many.d.ts.map +1 -0
  111. package/declarations/model/-private/schema-provider.d.ts +63 -0
  112. package/declarations/model/-private/schema-provider.d.ts.map +1 -0
  113. package/declarations/model/-private/type-utils.d.ts +57 -0
  114. package/declarations/model/-private/type-utils.d.ts.map +1 -0
  115. package/declarations/model/-private/util.d.ts +6 -0
  116. package/declarations/model/-private/util.d.ts.map +1 -0
  117. package/declarations/model/-private.d.ts +8 -0
  118. package/declarations/model/-private.d.ts.map +1 -0
  119. package/declarations/model/migration-support.d.ts +287 -0
  120. package/declarations/model/migration-support.d.ts.map +1 -0
  121. package/declarations/model/migration-support.type-test.d.ts +2 -0
  122. package/declarations/model/migration-support.type-test.d.ts.map +1 -0
  123. package/declarations/model.d.ts +50 -0
  124. package/declarations/model.d.ts.map +1 -0
  125. package/declarations/serializer/-private/embedded-records-mixin.d.ts +97 -0
  126. package/declarations/serializer/-private/embedded-records-mixin.d.ts.map +1 -0
  127. package/declarations/serializer/-private/transforms/boolean.d.ts +47 -0
  128. package/declarations/serializer/-private/transforms/boolean.d.ts.map +1 -0
  129. package/declarations/serializer/-private/transforms/boolean.type-test.d.ts +2 -0
  130. package/declarations/serializer/-private/transforms/boolean.type-test.d.ts.map +1 -0
  131. package/declarations/serializer/-private/transforms/date.d.ts +28 -0
  132. package/declarations/serializer/-private/transforms/date.d.ts.map +1 -0
  133. package/declarations/serializer/-private/transforms/number.d.ts +29 -0
  134. package/declarations/serializer/-private/transforms/number.d.ts.map +1 -0
  135. package/declarations/serializer/-private/transforms/string.d.ts +29 -0
  136. package/declarations/serializer/-private/transforms/string.d.ts.map +1 -0
  137. package/declarations/serializer/-private/transforms/transform.d.ts +119 -0
  138. package/declarations/serializer/-private/transforms/transform.d.ts.map +1 -0
  139. package/declarations/serializer/-private/utils.d.ts +4 -0
  140. package/declarations/serializer/-private/utils.d.ts.map +1 -0
  141. package/declarations/serializer/json-api.d.ts +496 -0
  142. package/declarations/serializer/json-api.d.ts.map +1 -0
  143. package/declarations/serializer/json.d.ts +1047 -0
  144. package/declarations/serializer/json.d.ts.map +1 -0
  145. package/declarations/serializer/rest.d.ts +554 -0
  146. package/declarations/serializer/rest.d.ts.map +1 -0
  147. package/declarations/serializer/transform.d.ts +6 -0
  148. package/declarations/serializer/transform.d.ts.map +1 -0
  149. package/declarations/serializer.d.ts +258 -0
  150. package/declarations/serializer.d.ts.map +1 -0
  151. package/dist/-private-DFfBszo5.js +1182 -0
  152. package/dist/-private-DFfBszo5.js.map +1 -0
  153. package/dist/adapter/-private.js +1 -0
  154. package/dist/adapter/-private.js.map +1 -0
  155. package/dist/adapter/error.js +254 -0
  156. package/dist/adapter/error.js.map +1 -0
  157. package/dist/adapter/json-api.js +129 -0
  158. package/dist/adapter/json-api.js.map +1 -0
  159. package/dist/adapter/rest.js +1262 -0
  160. package/dist/adapter/rest.js.map +1 -0
  161. package/dist/adapter.js +1284 -0
  162. package/dist/adapter.js.map +1 -0
  163. package/dist/compat/-private.js +1 -0
  164. package/dist/compat/-private.js.map +1 -0
  165. package/dist/compat/builders.js +292 -0
  166. package/dist/compat/builders.js.map +1 -0
  167. package/dist/compat/utils.js +225 -0
  168. package/dist/compat/utils.js.map +1 -0
  169. package/dist/compat.js +999 -0
  170. package/dist/compat.js.map +1 -0
  171. package/dist/errors-D74uk36r.js +2541 -0
  172. package/dist/errors-D74uk36r.js.map +1 -0
  173. package/dist/json-BCH3fil7.js +1349 -0
  174. package/dist/json-BCH3fil7.js.map +1 -0
  175. package/dist/model/-private.js +2 -0
  176. package/dist/model/-private.js.map +1 -0
  177. package/dist/model/migration-support.js +453 -0
  178. package/dist/model/migration-support.js.map +1 -0
  179. package/dist/model.js +736 -0
  180. package/dist/model.js.map +1 -0
  181. package/dist/runtime-BPCpkOf1-BKOwiRJp.js +65 -0
  182. package/dist/runtime-BPCpkOf1-BKOwiRJp.js.map +1 -0
  183. package/dist/schema-provider-CXFLTMjg.js +2228 -0
  184. package/dist/schema-provider-CXFLTMjg.js.map +1 -0
  185. package/dist/serialize-into-hash-BxfqWC8u.js +260 -0
  186. package/dist/serialize-into-hash-BxfqWC8u.js.map +1 -0
  187. package/dist/serializer/json-api.js +514 -0
  188. package/dist/serializer/json-api.js.map +1 -0
  189. package/dist/serializer/json.js +6 -0
  190. package/dist/serializer/json.js.map +1 -0
  191. package/dist/serializer/rest.js +1245 -0
  192. package/dist/serializer/rest.js.map +1 -0
  193. package/dist/serializer/transform.js +313 -0
  194. package/dist/serializer/transform.js.map +1 -0
  195. package/dist/serializer.js +252 -0
  196. package/dist/serializer.js.map +1 -0
  197. package/logos/NCC-1701-a-blue.svg +4 -0
  198. package/logos/NCC-1701-a-gold.svg +4 -0
  199. package/logos/NCC-1701-a-gold_100.svg +1 -0
  200. package/logos/NCC-1701-a-gold_base-64.txt +1 -0
  201. package/logos/NCC-1701-a.svg +4 -0
  202. package/logos/README.md +4 -0
  203. package/logos/docs-badge.svg +2 -0
  204. package/logos/ember-data-logo-dark.svg +12 -0
  205. package/logos/ember-data-logo-light.svg +12 -0
  206. package/logos/github-header.svg +444 -0
  207. package/logos/social1.png +0 -0
  208. package/logos/social2.png +0 -0
  209. package/logos/warp-drive-logo-dark.svg +4 -0
  210. package/logos/warp-drive-logo-gold.svg +4 -0
  211. package/package.json +72 -0
@@ -0,0 +1,1182 @@
1
+ import { SOURCE, waitFor, coerceId } from '@warp-drive/core/store/-private';
2
+ import { warn } from '@ember/debug';
3
+ import { createDeferred } from '@warp-drive/core/request';
4
+ import { getOrSetGlobal } from '@warp-drive/core/types/-private';
5
+ import { macroCondition, getGlobalConfig } from '@embroider/macros';
6
+
7
+ /**
8
+ SnapshotRecordArray is not directly instantiable.
9
+ Instances are provided to consuming application's
10
+ adapters for certain `findAll` requests.
11
+
12
+ @class SnapshotRecordArray
13
+ @public
14
+ */
15
+ class SnapshotRecordArray {
16
+ /**
17
+ SnapshotRecordArray is not directly instantiable.
18
+ Instances are provided to consuming application's
19
+ adapters and serializers for certain requests.
20
+ @private
21
+ @constructor
22
+ @param {Store} store
23
+ @param {String} type
24
+ @param options
25
+ */
26
+ constructor(store, type, options = {}) {
27
+ this.__store = store;
28
+ /**
29
+ An array of snapshots
30
+ @private
31
+ @property _snapshots
32
+ @type {Array}
33
+ */
34
+ this._snapshots = null;
35
+
36
+ /**
37
+ The modelName of the underlying records for the snapshots in the array, as a Model
38
+ @property modelName
39
+ @public
40
+ @type {Model}
41
+ */
42
+ this.modelName = type;
43
+
44
+ /**
45
+ A hash of adapter options passed into the store method for this request.
46
+ Example
47
+ ```js [app/adapters/post.js]
48
+ import MyCustomAdapter from './custom-adapter';
49
+ export default class PostAdapter extends MyCustomAdapter {
50
+ findAll(store, type, sinceToken, snapshotRecordArray) {
51
+ if (snapshotRecordArray.adapterOptions.subscribe) {
52
+ // ...
53
+ }
54
+ // ...
55
+ }
56
+ }
57
+ ```
58
+ @property adapterOptions
59
+ @public
60
+ @type {Object}
61
+ */
62
+ this.adapterOptions = options.adapterOptions;
63
+
64
+ /**
65
+ The relationships to include for this request.
66
+ Example
67
+ ```js [app/adapters/application.js]
68
+ import Adapter from '@ember-data/adapter';
69
+ export default class ApplicationAdapter extends Adapter {
70
+ findAll(store, type, snapshotRecordArray) {
71
+ let url = `/${type.modelName}?include=${encodeURIComponent(snapshotRecordArray.include)}`;
72
+ return fetch(url).then((response) => response.json())
73
+ }
74
+ }
75
+ ```
76
+ @property include
77
+ @public
78
+ @type {String|Array}
79
+ */
80
+ this.include = options.include;
81
+ }
82
+
83
+ /**
84
+ An array of records
85
+ @property _recordArray
86
+ @private
87
+ @type {Array}
88
+ */
89
+ get _recordArray() {
90
+ return this.__store.peekAll(this.modelName);
91
+ }
92
+
93
+ /**
94
+ Number of records in the array
95
+ Example
96
+ ```js [app/adapters/post.js]
97
+ import JSONAPIAdapter from '@ember-data/adapter/json-api';
98
+ export default class PostAdapter extends JSONAPIAdapter {
99
+ shouldReloadAll(store, snapshotRecordArray) {
100
+ return !snapshotRecordArray.length;
101
+ }
102
+ });
103
+ ```
104
+ @property length
105
+ @public
106
+ @type {Number}
107
+ */
108
+ get length() {
109
+ return this._recordArray.length;
110
+ }
111
+
112
+ /**
113
+ Get snapshots of the underlying record array
114
+ Example
115
+ ```js [app/adapters/post.js]
116
+ import JSONAPIAdapter from '@ember-data/adapter/json-api';
117
+ export default class PostAdapter extends JSONAPIAdapter {
118
+ shouldReloadAll(store, snapshotArray) {
119
+ let snapshots = snapshotArray.snapshots();
120
+ return snapshots.any(function(ticketSnapshot) {
121
+ let timeDiff = moment().diff(ticketSnapshot.attr('lastAccessedAt'), 'minutes');
122
+ if (timeDiff > 20) {
123
+ return true;
124
+ } else {
125
+ return false;
126
+ }
127
+ });
128
+ }
129
+ }
130
+ ```
131
+ @public
132
+ @return {Array} Array of snapshots
133
+ */
134
+ snapshots() {
135
+ if (this._snapshots !== null) {
136
+ return this._snapshots;
137
+ }
138
+ upgradeStore(this.__store);
139
+ const {
140
+ _fetchManager
141
+ } = this.__store;
142
+ this._snapshots = this._recordArray[SOURCE].map(identifier => _fetchManager.createSnapshot(identifier));
143
+ return this._snapshots;
144
+ }
145
+ }
146
+ function assertIdentifierHasId(identifier) {
147
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
148
+ if (!test) {
149
+ throw new Error(`Attempted to schedule a fetch for a record without an id.`);
150
+ }
151
+ })(identifier && identifier.id !== null) : {};
152
+ }
153
+ function iterateData(data, fn) {
154
+ if (Array.isArray(data)) {
155
+ return data.map(fn);
156
+ } else {
157
+ return fn(data, 0);
158
+ }
159
+ }
160
+ function payloadIsNotBlank(adapterPayload) {
161
+ if (Array.isArray(adapterPayload)) {
162
+ return true;
163
+ } else {
164
+ return Object.keys(adapterPayload || {}).length !== 0;
165
+ }
166
+ }
167
+
168
+ /**
169
+ This is a helper method that validates a JSON API top-level document
170
+
171
+ The format of a document is described here:
172
+ http://jsonapi.org/format/#document-top-level
173
+
174
+ @internal
175
+ */
176
+ function validateDocumentStructure(doc) {
177
+ if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
178
+ const errors = [];
179
+ if (!doc || typeof doc !== 'object') {
180
+ errors.push('Top level of a JSON API document must be an object');
181
+ } else {
182
+ if (!('data' in doc) && !('errors' in doc) && !('meta' in doc)) {
183
+ errors.push('One or more of the following keys must be present: "data", "errors", "meta".');
184
+ } else {
185
+ if ('data' in doc && 'errors' in doc) {
186
+ errors.push('Top level keys "errors" and "data" cannot both be present in a JSON API document');
187
+ }
188
+ }
189
+ if ('data' in doc) {
190
+ if (!(doc.data === null || Array.isArray(doc.data) || typeof doc.data === 'object')) {
191
+ errors.push('data must be null, an object, or an array');
192
+ }
193
+ }
194
+ if ('meta' in doc) {
195
+ if (typeof doc.meta !== 'object') {
196
+ errors.push('meta must be an object');
197
+ }
198
+ }
199
+ if ('errors' in doc) {
200
+ if (!Array.isArray(doc.errors)) {
201
+ errors.push('errors must be an array');
202
+ }
203
+ }
204
+ if ('links' in doc) {
205
+ if (typeof doc.links !== 'object') {
206
+ errors.push('links must be an object');
207
+ }
208
+ }
209
+ if ('jsonapi' in doc) {
210
+ if (typeof doc.jsonapi !== 'object') {
211
+ errors.push('jsonapi must be an object');
212
+ }
213
+ }
214
+ if ('included' in doc) {
215
+ if (typeof doc.included !== 'object') {
216
+ errors.push('included must be an array');
217
+ }
218
+ }
219
+ }
220
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
221
+ if (!test) {
222
+ throw new Error(`Response must be normalized to a valid JSON API document:\n\t* ${errors.join('\n\t* ')}`);
223
+ }
224
+ })(errors.length === 0) : {};
225
+ }
226
+ }
227
+ function normalizeResponseHelper(serializer, store, modelClass, payload, id, requestType) {
228
+ const normalizedResponse = serializer ? serializer.normalizeResponse(store, modelClass, payload, id, requestType) : payload;
229
+ validateDocumentStructure(normalizedResponse);
230
+ return normalizedResponse;
231
+ }
232
+
233
+ /**
234
+ Snapshot is not directly instantiable.
235
+ Instances are provided to a consuming application's
236
+ adapters and serializers for certain requests.
237
+
238
+ Snapshots are only available when using `@ember-data/legacy-compat`
239
+ for legacy compatibility with adapters and serializers.
240
+
241
+ @class Snapshot
242
+ @public
243
+ */
244
+ class Snapshot {
245
+ /**
246
+ * @constructor
247
+ * @private
248
+ * @param options
249
+ * @param identifier
250
+ * @param _store
251
+ */
252
+ constructor(options, identifier, store) {
253
+ this._store = store;
254
+ this.__attributes = null;
255
+ this._belongsToRelationships = Object.create(null);
256
+ this._belongsToIds = Object.create(null);
257
+ this._hasManyRelationships = Object.create(null);
258
+ this._hasManyIds = Object.create(null);
259
+ const hasRecord = !!store._instanceCache.peek(identifier);
260
+ this.modelName = identifier.type;
261
+
262
+ /**
263
+ The unique RecordIdentifier associated with this Snapshot.
264
+ @property identifier
265
+ @public
266
+ @type {StableRecordIdentifier}
267
+ */
268
+ this.identifier = identifier;
269
+
270
+ /*
271
+ If the we do not yet have a record, then we are
272
+ likely a snapshot being provided to a find request, so we
273
+ populate __attributes lazily. Else, to preserve the "moment
274
+ in time" in which a snapshot is created, we greedily grab
275
+ the values.
276
+ */
277
+ if (hasRecord) {
278
+ // eslint-disable-next-line @typescript-eslint/no-unused-expressions
279
+ this._attributes;
280
+ }
281
+
282
+ /**
283
+ The id of the snapshot's underlying record
284
+ Example
285
+ ```javascript
286
+ // store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' });
287
+ postSnapshot.id; // => '1'
288
+ ```
289
+ @property id
290
+ @type {String}
291
+ @public
292
+ */
293
+ this.id = identifier.id;
294
+
295
+ /**
296
+ A hash of adapter options
297
+ @property adapterOptions
298
+ @type {Object}
299
+ @public
300
+ */
301
+ this.adapterOptions = options.adapterOptions;
302
+
303
+ /**
304
+ If `include` was passed to the options hash for the request, the value
305
+ would be available here.
306
+ @property include
307
+ @type {String|Array}
308
+ @public
309
+ */
310
+ this.include = options.include;
311
+
312
+ /**
313
+ The name of the type of the underlying record for this snapshot, as a string.
314
+ @property modelName
315
+ @type {String}
316
+ @public
317
+ */
318
+ this.modelName = identifier.type;
319
+ if (hasRecord) {
320
+ const cache = this._store.cache;
321
+ this._changedAttributes = cache.changedAttrs(identifier);
322
+ }
323
+ }
324
+
325
+ /**
326
+ The underlying record for this snapshot. Can be used to access methods and
327
+ properties defined on the record.
328
+ Example
329
+ ```javascript
330
+ let json = snapshot.record.toJSON();
331
+ ```
332
+ @property record
333
+ @type {Model}
334
+ @public
335
+ */
336
+ get record() {
337
+ const record = this._store.peekRecord(this.identifier);
338
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
339
+ if (!test) {
340
+ throw new Error(`Record ${this.identifier.type} ${this.identifier.id} (${this.identifier.lid}) is not yet loaded and thus cannot be accessed from the Snapshot during serialization`);
341
+ }
342
+ })(record !== null) : {};
343
+ return record;
344
+ }
345
+ get _attributes() {
346
+ if (this.__attributes !== null) {
347
+ return this.__attributes;
348
+ }
349
+ const attributes = this.__attributes = Object.create(null);
350
+ const {
351
+ identifier
352
+ } = this;
353
+ const attrs = this._store.schema.fields(identifier);
354
+ const cache = this._store.cache;
355
+ attrs.forEach((field, keyName) => {
356
+ if (field.kind === 'attribute') {
357
+ attributes[keyName] = cache.getAttr(identifier, keyName);
358
+ }
359
+ });
360
+ return attributes;
361
+ }
362
+ get isNew() {
363
+ const cache = this._store.cache;
364
+ return cache?.isNew(this.identifier) || false;
365
+ }
366
+
367
+ /**
368
+ Returns the value of an attribute.
369
+ Example
370
+ ```javascript
371
+ // store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' });
372
+ postSnapshot.attr('author'); // => 'Tomster'
373
+ postSnapshot.attr('title'); // => 'Ember.js rocks'
374
+ ```
375
+ Note: Values are loaded eagerly and cached when the snapshot is created.
376
+ @param {String} keyName
377
+ @return {Object} The attribute value or undefined
378
+ @public
379
+ */
380
+ attr(keyName) {
381
+ if (keyName in this._attributes) {
382
+ return this._attributes[keyName];
383
+ }
384
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
385
+ {
386
+ throw new Error(`Model '${this.identifier.lid}' has no attribute named '${keyName}' defined.`);
387
+ }
388
+ })() : {};
389
+ }
390
+
391
+ /**
392
+ Returns all attributes and their corresponding values.
393
+ Example
394
+ ```javascript
395
+ // store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' });
396
+ postSnapshot.attributes(); // => { author: 'Tomster', title: 'Ember.js rocks' }
397
+ ```
398
+ @return {Object} All attributes of the current snapshot
399
+ @public
400
+ */
401
+ attributes() {
402
+ return {
403
+ ...this._attributes
404
+ };
405
+ }
406
+
407
+ /**
408
+ Returns all changed attributes and their old and new values.
409
+ Example
410
+ ```javascript
411
+ // store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' });
412
+ postModel.set('title', 'Ember.js rocks!');
413
+ postSnapshot.changedAttributes(); // => { title: ['Ember.js rocks', 'Ember.js rocks!'] }
414
+ ```
415
+ @return {Object} All changed attributes of the current snapshot
416
+ @public
417
+ */
418
+ changedAttributes() {
419
+ const changedAttributes = Object.create(null);
420
+ if (!this._changedAttributes) {
421
+ return changedAttributes;
422
+ }
423
+ const changedAttributeKeys = Object.keys(this._changedAttributes);
424
+ for (let i = 0, length = changedAttributeKeys.length; i < length; i++) {
425
+ const key = changedAttributeKeys[i];
426
+ changedAttributes[key] = this._changedAttributes[key].slice();
427
+ }
428
+ return changedAttributes;
429
+ }
430
+
431
+ /**
432
+ Returns the current value of a belongsTo relationship.
433
+ `belongsTo` takes an optional hash of options as a second parameter,
434
+ currently supported options are:
435
+ - `id`: set to `true` if you only want the ID of the related record to be
436
+ returned.
437
+ Example
438
+ ```javascript
439
+ // store.push('post', { id: 1, title: 'Hello World' });
440
+ // store.createRecord('comment', { body: 'Lorem ipsum', post: post });
441
+ commentSnapshot.belongsTo('post'); // => Snapshot
442
+ commentSnapshot.belongsTo('post', { id: true }); // => '1'
443
+ // store.push('comment', { id: 1, body: 'Lorem ipsum' });
444
+ commentSnapshot.belongsTo('post'); // => undefined
445
+ ```
446
+ Calling `belongsTo` will return a new Snapshot as long as there's any known
447
+ data for the relationship available, such as an ID. If the relationship is
448
+ known but unset, `belongsTo` will return `null`. If the contents of the
449
+ relationship is unknown `belongsTo` will return `undefined`.
450
+ Note: Relationships are loaded lazily and cached upon first access.
451
+ @param {String} keyName
452
+ @param {Object} [options]
453
+ @public
454
+ @return {(Snapshot|String|null|undefined)} A snapshot or ID of a known
455
+ relationship or null if the relationship is known but unset. undefined
456
+ will be returned if the contents of the relationship is unknown.
457
+ */
458
+ belongsTo(keyName, options) {
459
+ const returnModeIsId = !!(options && options.id);
460
+ let result;
461
+ const store = this._store;
462
+ if (returnModeIsId === true && keyName in this._belongsToIds) {
463
+ return this._belongsToIds[keyName];
464
+ }
465
+ if (returnModeIsId === false && keyName in this._belongsToRelationships) {
466
+ return this._belongsToRelationships[keyName];
467
+ }
468
+ const relationshipMeta = store.schema.fields({
469
+ type: this.modelName
470
+ }).get(keyName);
471
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
472
+ if (!test) {
473
+ throw new Error(`Model '${this.identifier.lid}' has no belongsTo relationship named '${keyName}' defined.`);
474
+ }
475
+ })(relationshipMeta && relationshipMeta.kind === 'belongsTo') : {};
476
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
477
+ if (!test) {
478
+ throw new Error(`snapshot.belongsTo only supported when using a cache that supports the graph`);
479
+ }
480
+ })(this._store._graph) : {};
481
+ const {
482
+ identifier
483
+ } = this;
484
+ if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
485
+ const relationship = this._store.schema.fields(identifier)?.get(keyName);
486
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
487
+ if (!test) {
488
+ throw new Error(`You looked up the ${keyName} belongsTo relationship for { type: ${identifier.type}, id: ${identifier.id || ''}, lid: ${identifier.lid} but no such relationship was found.`);
489
+ }
490
+ })(relationship) : {};
491
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
492
+ if (!test) {
493
+ throw new Error(`You looked up the ${keyName} belongsTo relationship for { type: ${identifier.type}, id: ${identifier.id || ''}, lid: ${identifier.lid} but that relationship is a hasMany.`);
494
+ }
495
+ })(relationship.kind === 'belongsTo') : {};
496
+ }
497
+ const value = this._store.cache.getRelationship(identifier, keyName);
498
+ const data = value && value.data;
499
+ const inverseIdentifier = data ? store.identifierCache.getOrCreateRecordIdentifier(data) : null;
500
+ if (value && value.data !== undefined) {
501
+ const cache = store.cache;
502
+ if (inverseIdentifier && !cache.isDeleted(inverseIdentifier)) {
503
+ if (returnModeIsId) {
504
+ result = inverseIdentifier.id;
505
+ } else {
506
+ result = store._fetchManager.createSnapshot(inverseIdentifier);
507
+ }
508
+ } else {
509
+ result = null;
510
+ }
511
+ }
512
+ if (returnModeIsId) {
513
+ this._belongsToIds[keyName] = result;
514
+ } else {
515
+ this._belongsToRelationships[keyName] = result;
516
+ }
517
+ return result;
518
+ }
519
+
520
+ /**
521
+ Returns the current value of a hasMany relationship.
522
+ `hasMany` takes an optional hash of options as a second parameter,
523
+ currently supported options are:
524
+ - `ids`: set to `true` if you only want the IDs of the related records to be
525
+ returned.
526
+ Example
527
+ ```javascript
528
+ // store.push('post', { id: 1, title: 'Hello World', comments: [2, 3] });
529
+ postSnapshot.hasMany('comments'); // => [Snapshot, Snapshot]
530
+ postSnapshot.hasMany('comments', { ids: true }); // => ['2', '3']
531
+ // store.push('post', { id: 1, title: 'Hello World' });
532
+ postSnapshot.hasMany('comments'); // => undefined
533
+ ```
534
+ Note: Relationships are loaded lazily and cached upon first access.
535
+ @param {String} keyName
536
+ @param {Object} [options]
537
+ @public
538
+ @return {(Array|undefined)} An array of snapshots or IDs of a known
539
+ relationship or an empty array if the relationship is known but unset.
540
+ undefined will be returned if the contents of the relationship is unknown.
541
+ */
542
+ hasMany(keyName, options) {
543
+ const returnModeIsIds = !!(options && options.ids);
544
+ let results;
545
+ const cachedIds = this._hasManyIds[keyName];
546
+ const cachedSnapshots = this._hasManyRelationships[keyName];
547
+ if (returnModeIsIds === true && keyName in this._hasManyIds) {
548
+ return cachedIds;
549
+ }
550
+ if (returnModeIsIds === false && keyName in this._hasManyRelationships) {
551
+ return cachedSnapshots;
552
+ }
553
+ const store = this._store;
554
+ const relationshipMeta = store.schema.fields({
555
+ type: this.modelName
556
+ }).get(keyName);
557
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
558
+ if (!test) {
559
+ throw new Error(`Model '${this.identifier.lid}' has no hasMany relationship named '${keyName}' defined.`);
560
+ }
561
+ })(relationshipMeta && relationshipMeta.kind === 'hasMany') : {};
562
+
563
+ // TODO @runspired it seems this code branch would not work with CUSTOM_MODEL_CLASSes
564
+ // this check is not a regression in behavior because relationships don't currently
565
+ // function without access to intimate API contracts between RecordData and Model.
566
+ // This is a requirement we should fix as soon as the relationship layer does not require
567
+ // this intimate API usage.
568
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
569
+ if (!test) {
570
+ throw new Error(`snapshot.hasMany only supported when using a cache that supports the graph`);
571
+ }
572
+ })(this._store._graph) : {};
573
+ const {
574
+ identifier
575
+ } = this;
576
+ if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
577
+ const relationship = this._store.schema.fields(identifier)?.get(keyName);
578
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
579
+ if (!test) {
580
+ throw new Error(`You looked up the ${keyName} hasMany relationship for { type: ${identifier.type}, id: ${identifier.id || ''}, lid: ${identifier.lid} but no such relationship was found.`);
581
+ }
582
+ })(relationship) : {};
583
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
584
+ if (!test) {
585
+ throw new Error(`You looked up the ${keyName} hasMany relationship for { type: ${identifier.type}, id: ${identifier.id || ''}, lid: ${identifier.lid} but that relationship is a belongsTo.`);
586
+ }
587
+ })(relationship.kind === 'hasMany') : {};
588
+ }
589
+ const value = this._store.cache.getRelationship(identifier, keyName);
590
+ if (value.data) {
591
+ results = [];
592
+ value.data.forEach(member => {
593
+ const inverseIdentifier = store.identifierCache.getOrCreateRecordIdentifier(member);
594
+ const cache = store.cache;
595
+ if (!cache.isDeleted(inverseIdentifier)) {
596
+ if (returnModeIsIds) {
597
+ results.push(inverseIdentifier.id);
598
+ } else {
599
+ results.push(store._fetchManager.createSnapshot(inverseIdentifier));
600
+ }
601
+ }
602
+ });
603
+ }
604
+
605
+ // we assign even if `undefined` so that we don't reprocess the relationship
606
+ // on next access. This works with the `keyName in` checks above.
607
+ if (returnModeIsIds) {
608
+ this._hasManyIds[keyName] = results;
609
+ } else {
610
+ this._hasManyRelationships[keyName] = results;
611
+ }
612
+ return results;
613
+ }
614
+
615
+ /**
616
+ Iterates through all the attributes of the model, calling the passed
617
+ function on each attribute.
618
+ Example
619
+ ```javascript
620
+ snapshot.eachAttribute(function(name, meta) {
621
+ // ...
622
+ });
623
+ ```
624
+ @param {Function} callback the callback to execute
625
+ @param {Object} [binding] the value to which the callback's `this` should be bound
626
+ @public
627
+ */
628
+ eachAttribute(callback, binding) {
629
+ const fields = this._store.schema.fields(this.identifier);
630
+ fields.forEach((field, key) => {
631
+ if (field.kind === 'attribute') {
632
+ callback.call(binding, key, field);
633
+ }
634
+ });
635
+ }
636
+
637
+ /**
638
+ Iterates through all the relationships of the model, calling the passed
639
+ function on each relationship.
640
+ Example
641
+ ```javascript
642
+ snapshot.eachRelationship(function(name, relationship) {
643
+ // ...
644
+ });
645
+ ```
646
+ @param {Function} callback the callback to execute
647
+ @param {Object} [binding] the value to which the callback's `this` should be bound
648
+ @public
649
+ */
650
+ eachRelationship(callback, binding) {
651
+ const fields = this._store.schema.fields(this.identifier);
652
+ fields.forEach((field, key) => {
653
+ if (field.kind === 'belongsTo' || field.kind === 'hasMany') {
654
+ callback.call(binding, key, field);
655
+ }
656
+ });
657
+ }
658
+
659
+ /**
660
+ Serializes the snapshot using the serializer for the model.
661
+ Example
662
+ ```js [app/adapters/application.js]
663
+ import Adapter from '@ember-data/adapter';
664
+ export default Adapter.extend({
665
+ createRecord(store, type, snapshot) {
666
+ let data = snapshot.serialize({ includeId: true });
667
+ let url = `/${type.modelName}`;
668
+ return fetch(url, {
669
+ method: 'POST',
670
+ body: data,
671
+ }).then((response) => response.json())
672
+ }
673
+ });
674
+ ```
675
+ @param {Object} options
676
+ @return {Object} an object whose values are primitive JSON values only
677
+ @public
678
+ */
679
+ serialize(options) {
680
+ upgradeStore(this._store);
681
+ const serializer = this._store.serializerFor(this.modelName);
682
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
683
+ if (!test) {
684
+ throw new Error(`Cannot serialize record, no serializer found`);
685
+ }
686
+ })(serializer) : {};
687
+ return serializer.serialize(this, options);
688
+ }
689
+ }
690
+ const SaveOp = getOrSetGlobal('SaveOp', Symbol('SaveOp'));
691
+ class FetchManager {
692
+ // fetches pending in the runloop, waiting to be coalesced
693
+
694
+ constructor(store) {
695
+ this._store = store;
696
+ // used to keep track of all the find requests that need to be coalesced
697
+ this._pendingFetch = new Map();
698
+ this.requestCache = store.getRequestStateService();
699
+ this.isDestroyed = false;
700
+ }
701
+ createSnapshot(identifier, options = {}) {
702
+ return new Snapshot(options, identifier, this._store);
703
+ }
704
+
705
+ /**
706
+ This method is called by `record.save`, and gets passed a
707
+ resolver for the promise that `record.save` returns.
708
+ It schedules saving to happen at the end of the run loop.
709
+ @internal
710
+ */
711
+ scheduleSave(identifier, options) {
712
+ const resolver = createDeferred();
713
+ const query = {
714
+ op: 'saveRecord',
715
+ recordIdentifier: identifier,
716
+ options
717
+ };
718
+ const queryRequest = {
719
+ data: [query]
720
+ };
721
+ const snapshot = this.createSnapshot(identifier, options);
722
+ const pendingSaveItem = {
723
+ snapshot: snapshot,
724
+ resolver: resolver,
725
+ identifier,
726
+ options,
727
+ queryRequest
728
+ };
729
+ const monitored = this.requestCache._enqueue(resolver.promise, pendingSaveItem.queryRequest);
730
+ _flushPendingSave(this._store, pendingSaveItem);
731
+ return monitored;
732
+ }
733
+ scheduleFetch(identifier, options, request) {
734
+ const query = {
735
+ op: 'findRecord',
736
+ recordIdentifier: identifier,
737
+ options
738
+ };
739
+ const queryRequest = {
740
+ data: [query]
741
+ };
742
+ const pendingFetch = this.getPendingFetch(identifier, options);
743
+ if (pendingFetch) {
744
+ return pendingFetch;
745
+ }
746
+ const modelName = identifier.type;
747
+ const resolver = createDeferred();
748
+ const pendingFetchItem = {
749
+ identifier,
750
+ resolver,
751
+ options,
752
+ queryRequest
753
+ };
754
+ const resolverPromise = resolver.promise;
755
+ const store = this._store;
756
+ const isInitialLoad = !store._instanceCache.recordIsLoaded(identifier); // we don't use isLoading directly because we are the request
757
+
758
+ const monitored = this.requestCache._enqueue(resolverPromise, pendingFetchItem.queryRequest);
759
+ let promise = monitored.then(payload => {
760
+ // ensure that regardless of id returned we assign to the correct record
761
+ if (payload.data && !Array.isArray(payload.data)) {
762
+ payload.data.lid = identifier.lid;
763
+ }
764
+
765
+ // additional data received in the payload
766
+ // may result in the merging of identifiers (and thus records)
767
+ const potentiallyNewIm = store._push(payload, options.reload);
768
+ if (potentiallyNewIm && !Array.isArray(potentiallyNewIm)) {
769
+ return potentiallyNewIm;
770
+ }
771
+ return identifier;
772
+ }, error => {
773
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
774
+ if (!test) {
775
+ throw new Error(`Async Leak Detected: Expected the store to not be destroyed`);
776
+ }
777
+ })(!store.isDestroyed) : {};
778
+ const cache = store.cache;
779
+ if (!cache || cache.isEmpty(identifier) || isInitialLoad) {
780
+ let isReleasable = true;
781
+ if (store._graph) {
782
+ const graph = store._graph;
783
+ if (!cache) {
784
+ isReleasable = graph.isReleasable(identifier);
785
+ if (!isReleasable) {
786
+ graph.unload(identifier, true);
787
+ }
788
+ }
789
+ }
790
+ if (cache || isReleasable) {
791
+ store._enableAsyncFlush = true;
792
+ store._instanceCache.unloadRecord(identifier);
793
+ store._enableAsyncFlush = null;
794
+ }
795
+ }
796
+ throw error;
797
+ });
798
+ if (this._pendingFetch.size === 0) {
799
+ void new Promise(resolve => setTimeout(resolve, 0)).then(() => {
800
+ this.flushAllPendingFetches();
801
+ });
802
+ }
803
+ const fetchesByType = this._pendingFetch;
804
+ let fetchesById = fetchesByType.get(modelName);
805
+ if (!fetchesById) {
806
+ fetchesById = new Map();
807
+ fetchesByType.set(modelName, fetchesById);
808
+ }
809
+ let requestsForIdentifier = fetchesById.get(identifier);
810
+ if (!requestsForIdentifier) {
811
+ requestsForIdentifier = [];
812
+ fetchesById.set(identifier, requestsForIdentifier);
813
+ }
814
+ requestsForIdentifier.push(pendingFetchItem);
815
+ if (macroCondition(getGlobalConfig().WarpDrive.env.TESTING)) {
816
+ if (!request.disableTestWaiter) {
817
+ promise = waitFor(promise);
818
+ }
819
+ }
820
+ pendingFetchItem.promise = promise;
821
+ return promise;
822
+ }
823
+ getPendingFetch(identifier, options) {
824
+ const pendingFetches = this._pendingFetch.get(identifier.type)?.get(identifier);
825
+
826
+ // We already have a pending fetch for this
827
+ if (pendingFetches) {
828
+ const matchingPendingFetch = pendingFetches.find(fetch => isSameRequest(options, fetch.options));
829
+ if (matchingPendingFetch) {
830
+ return matchingPendingFetch.promise;
831
+ }
832
+ }
833
+ }
834
+ flushAllPendingFetches() {
835
+ if (this.isDestroyed) {
836
+ return;
837
+ }
838
+ const store = this._store;
839
+ this._pendingFetch.forEach((fetchItem, type) => _flushPendingFetchForType(store, fetchItem, type));
840
+ this._pendingFetch.clear();
841
+ }
842
+ fetchDataIfNeededForIdentifier(identifier, options = {}, request) {
843
+ // pre-loading will change the isEmpty value
844
+ const isEmpty = _isEmpty(this._store._instanceCache, identifier);
845
+ const isLoading = _isLoading(this._store._instanceCache, identifier);
846
+ let promise;
847
+ if (isEmpty) {
848
+ assertIdentifierHasId(identifier);
849
+ if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
850
+ promise = this.scheduleFetch(identifier, Object.assign({}, options, {
851
+ reload: true
852
+ }), request);
853
+ } else {
854
+ options.reload = true;
855
+ promise = this.scheduleFetch(identifier, options, request);
856
+ }
857
+ } else if (isLoading) {
858
+ promise = this.getPendingFetch(identifier, options);
859
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
860
+ if (!test) {
861
+ throw new Error(`Expected to find a pending request for a record in the loading state, but found none`);
862
+ }
863
+ })(promise) : {};
864
+ } else {
865
+ promise = Promise.resolve(identifier);
866
+ }
867
+ return promise;
868
+ }
869
+ destroy() {
870
+ this.isDestroyed = true;
871
+ }
872
+ }
873
+ function _isEmpty(instanceCache, identifier) {
874
+ const cache = instanceCache.cache;
875
+ if (!cache) {
876
+ return true;
877
+ }
878
+ const isNew = cache.isNew(identifier);
879
+ const isDeleted = cache.isDeleted(identifier);
880
+ const isEmpty = cache.isEmpty(identifier);
881
+ return (!isNew || isDeleted) && isEmpty;
882
+ }
883
+ function _isLoading(cache, identifier) {
884
+ const req = cache.store.getRequestStateService();
885
+ // const fulfilled = req.getLastRequestForRecord(identifier);
886
+ const isLoaded = cache.recordIsLoaded(identifier);
887
+ return !isLoaded &&
888
+ // fulfilled === null &&
889
+ req.getPendingRequestsForRecord(identifier).some(r => r.type === 'query');
890
+ }
891
+ function includesSatisfies(current, existing) {
892
+ // if we have no includes we are good
893
+ if (!current?.length) {
894
+ return true;
895
+ }
896
+
897
+ // if we are here we have includes,
898
+ // and if existing has no includes then we will need a new request
899
+ if (!existing?.length) {
900
+ return false;
901
+ }
902
+ const arrCurrent = (Array.isArray(current) ? current : current.split(',')).sort();
903
+ const arrExisting = (Array.isArray(existing) ? existing : existing.split(',')).sort();
904
+
905
+ // includes are identical
906
+ if (arrCurrent.join(',') === arrExisting.join(',')) {
907
+ return true;
908
+ }
909
+
910
+ // if all of current includes are in existing includes then we are good
911
+ // so if we find one that is not in existing then we need a new request
912
+ for (let i = 0; i < arrCurrent.length; i++) {
913
+ if (!arrExisting.includes(arrCurrent[i])) {
914
+ return false;
915
+ }
916
+ }
917
+ return true;
918
+ }
919
+ function optionsSatisfies(current, existing) {
920
+ return !current || current === existing || Object.keys(current).length === 0;
921
+ }
922
+
923
+ // this function helps resolve whether we have a pending request that we should use instead
924
+ function isSameRequest(options = {}, existingOptions = {}) {
925
+ return optionsSatisfies(options.adapterOptions, existingOptions.adapterOptions) && includesSatisfies(options.include, existingOptions.include);
926
+ }
927
+ function _findMany(store, adapter, modelName, snapshots) {
928
+ const modelClass = store.modelFor(modelName); // `adapter.findMany` gets the modelClass still
929
+ const promise = Promise.resolve().then(() => {
930
+ const ids = snapshots.map(s => s.id);
931
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
932
+ if (!test) {
933
+ throw new Error(`Cannot fetch a record without an id`);
934
+ }
935
+ })(ids.every(v => v !== null)) : {};
936
+ // eslint-disable-next-line @typescript-eslint/unbound-method
937
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
938
+ if (!test) {
939
+ throw new Error(`Expected this adapter to implement findMany for coalescing`);
940
+ }
941
+ })(adapter.findMany) : {};
942
+ const ret = adapter.findMany(store, modelClass, ids, snapshots);
943
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
944
+ if (!test) {
945
+ throw new Error('adapter.findMany returned undefined, this was very likely a mistake');
946
+ }
947
+ })(ret !== undefined) : {};
948
+ return ret;
949
+ });
950
+ return promise.then(adapterPayload => {
951
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
952
+ if (!test) {
953
+ throw new Error(`You made a 'findMany' request for '${modelName}' records with ids '[${snapshots.map(s => s.id).join(',')}]', but the adapter's response did not have any data`);
954
+ }
955
+ })(!!payloadIsNotBlank(adapterPayload)) : {};
956
+ const serializer = store.serializerFor(modelName);
957
+ const payload = normalizeResponseHelper(serializer, store, modelClass, adapterPayload, null, 'findMany');
958
+ return payload;
959
+ });
960
+ }
961
+ function rejectFetchedItems(fetchMap, snapshots, error) {
962
+ for (let i = 0, l = snapshots.length; i < l; i++) {
963
+ const snapshot = snapshots[i];
964
+ const pair = fetchMap.get(snapshot);
965
+ if (pair) {
966
+ pair.resolver.reject(error || new Error(`Expected: '<${snapshot.modelName}:${snapshot.id}>' to be present in the adapter provided payload, but it was not found.`));
967
+ }
968
+ }
969
+ }
970
+ function handleFoundRecords(store, fetchMap, snapshots, coalescedPayload) {
971
+ /*
972
+ It is possible that the same ID is included multiple times
973
+ via multiple snapshots. This happens when more than one
974
+ options hash was supplied, each of which must be uniquely
975
+ accounted for.
976
+ However, since we can't map from response to a specific
977
+ options object, we resolve all snapshots by id with
978
+ the first response we see.
979
+ */
980
+ const snapshotsById = new Map();
981
+ for (let i = 0; i < snapshots.length; i++) {
982
+ const id = snapshots[i].id;
983
+ let snapshotGroup = snapshotsById.get(id);
984
+ if (!snapshotGroup) {
985
+ snapshotGroup = [];
986
+ snapshotsById.set(id, snapshotGroup);
987
+ }
988
+ snapshotGroup.push(snapshots[i]);
989
+ }
990
+ const included = Array.isArray(coalescedPayload.included) ? coalescedPayload.included : [];
991
+
992
+ // resolve found records
993
+ const resources = coalescedPayload.data;
994
+ for (let i = 0, l = resources.length; i < l; i++) {
995
+ const resource = resources[i];
996
+ const snapshotGroup = snapshotsById.get(resource.id);
997
+ snapshotsById.delete(resource.id);
998
+ if (!snapshotGroup) {
999
+ // TODO consider whether this should be a deprecation/assertion
1000
+ included.push(resource);
1001
+ } else {
1002
+ snapshotGroup.forEach(snapshot => {
1003
+ const pair = fetchMap.get(snapshot);
1004
+ const resolver = pair.resolver;
1005
+ resolver.resolve({
1006
+ data: resource
1007
+ });
1008
+ });
1009
+ }
1010
+ }
1011
+ if (included.length > 0) {
1012
+ store._push({
1013
+ data: null,
1014
+ included
1015
+ }, true);
1016
+ }
1017
+ if (snapshotsById.size === 0) {
1018
+ return;
1019
+ }
1020
+
1021
+ // reject missing records
1022
+ const rejected = [];
1023
+ snapshotsById.forEach(snapshotArray => {
1024
+ rejected.push(...snapshotArray);
1025
+ });
1026
+ warn('Ember Data expected to find records with the following ids in the adapter response from findMany but they were missing: [ "' + [...snapshotsById.values()].map(r => r[0].id).join('", "') + '" ]', {
1027
+ id: 'ds.store.missing-records-from-adapter'
1028
+ });
1029
+ rejectFetchedItems(fetchMap, rejected);
1030
+ }
1031
+ function _fetchRecord(store, adapter, fetchItem) {
1032
+ const identifier = fetchItem.identifier;
1033
+ const modelName = identifier.type;
1034
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1035
+ if (!test) {
1036
+ throw new Error(`You tried to find a record but you have no adapter (for ${modelName})`);
1037
+ }
1038
+ })(adapter) : {};
1039
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1040
+ if (!test) {
1041
+ throw new Error(`You tried to find a record but your adapter (for ${modelName}) does not implement 'findRecord'`);
1042
+ }
1043
+ })(typeof adapter.findRecord === 'function') : {};
1044
+ const snapshot = store._fetchManager.createSnapshot(identifier, fetchItem.options);
1045
+ const klass = store.modelFor(identifier.type);
1046
+ const id = identifier.id;
1047
+ let promise = Promise.resolve().then(() => {
1048
+ return adapter.findRecord(store, klass, identifier.id, snapshot);
1049
+ });
1050
+ promise = promise.then(adapterPayload => {
1051
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1052
+ if (!test) {
1053
+ throw new Error(`Async Leak Detected: Expected the store to not be destroyed`);
1054
+ }
1055
+ })(!(store.isDestroyed || store.isDestroying)) : {};
1056
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1057
+ if (!test) {
1058
+ throw new Error(`You made a 'findRecord' request for a '${modelName}' with id '${id}', but the adapter's response did not have any data`);
1059
+ }
1060
+ })(!!payloadIsNotBlank(adapterPayload)) : {};
1061
+ const serializer = store.serializerFor(modelName);
1062
+ const payload = normalizeResponseHelper(serializer, store, klass, adapterPayload, id, 'findRecord');
1063
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1064
+ if (!test) {
1065
+ throw new Error(`Ember Data expected the primary data returned from a 'findRecord' response to be an object but instead it found an array.`);
1066
+ }
1067
+ })(!Array.isArray(payload.data)) : {};
1068
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1069
+ if (!test) {
1070
+ throw new Error(`The 'findRecord' request for ${modelName}:${id} resolved indicating success but contained no primary data. To indicate a 404 not found you should either reject the promise returned by the adapter's findRecord method or throw a NotFoundError.`);
1071
+ }
1072
+ })('data' in payload && payload.data !== null && typeof payload.data === 'object') : {};
1073
+ warn(`You requested a record of type '${modelName}' with id '${id}' but the adapter returned a payload with primary data having an id of '${payload.data.id}'. Use 'store.findRecord()' when the requested id is the same as the one returned by the adapter. In other cases use 'store.queryRecord()' instead.`, coerceId(payload.data.id) === coerceId(id), {
1074
+ id: 'ds.store.findRecord.id-mismatch'
1075
+ });
1076
+ return payload;
1077
+ });
1078
+ fetchItem.resolver.resolve(promise);
1079
+ }
1080
+ function _processCoalescedGroup(store, fetchMap, group, adapter, modelName) {
1081
+ if (group.length > 1) {
1082
+ _findMany(store, adapter, modelName, group).then(payloads => {
1083
+ handleFoundRecords(store, fetchMap, group, payloads);
1084
+ }).catch(error => {
1085
+ rejectFetchedItems(fetchMap, group, error);
1086
+ });
1087
+ } else if (group.length === 1) {
1088
+ _fetchRecord(store, adapter, fetchMap.get(group[0]));
1089
+ } else {
1090
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1091
+ {
1092
+ throw new Error("You cannot return an empty array from adapter's method groupRecordsForFindMany");
1093
+ }
1094
+ })() : {};
1095
+ }
1096
+ }
1097
+ function _flushPendingFetchForType(store, pendingFetchMap, modelName) {
1098
+ const adapter = store.adapterFor(modelName);
1099
+ const shouldCoalesce = !!adapter.findMany && adapter.coalesceFindRequests;
1100
+ if (shouldCoalesce) {
1101
+ const pendingFetchItems = [];
1102
+ pendingFetchMap.forEach((requestsForIdentifier, identifier) => {
1103
+ if (requestsForIdentifier.length > 1) {
1104
+ return;
1105
+ }
1106
+
1107
+ // remove this entry from the map so it's not processed again
1108
+ pendingFetchMap.delete(identifier);
1109
+ pendingFetchItems.push(requestsForIdentifier[0]);
1110
+ });
1111
+ const totalItems = pendingFetchItems.length;
1112
+ if (totalItems > 1) {
1113
+ const snapshots = new Array(totalItems);
1114
+ const fetchMap = new Map();
1115
+ for (let i = 0; i < totalItems; i++) {
1116
+ const fetchItem = pendingFetchItems[i];
1117
+ snapshots[i] = store._fetchManager.createSnapshot(fetchItem.identifier, fetchItem.options);
1118
+ fetchMap.set(snapshots[i], fetchItem);
1119
+ }
1120
+ let groups;
1121
+ if (adapter.groupRecordsForFindMany) {
1122
+ groups = adapter.groupRecordsForFindMany(store, snapshots);
1123
+ } else {
1124
+ groups = [snapshots];
1125
+ }
1126
+ for (let i = 0, l = groups.length; i < l; i++) {
1127
+ _processCoalescedGroup(store, fetchMap, groups[i], adapter, modelName);
1128
+ }
1129
+ } else if (totalItems === 1) {
1130
+ _fetchRecord(store, adapter, pendingFetchItems[0]);
1131
+ }
1132
+ }
1133
+ pendingFetchMap.forEach(pendingFetchItems => {
1134
+ pendingFetchItems.forEach(pendingFetchItem => {
1135
+ _fetchRecord(store, adapter, pendingFetchItem);
1136
+ });
1137
+ });
1138
+ }
1139
+ function _flushPendingSave(store, pending) {
1140
+ const {
1141
+ snapshot,
1142
+ resolver,
1143
+ identifier,
1144
+ options
1145
+ } = pending;
1146
+ const adapter = store.adapterFor(identifier.type);
1147
+ const operation = options[SaveOp];
1148
+ const modelName = snapshot.modelName;
1149
+ const modelClass = store.modelFor(modelName);
1150
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1151
+ if (!test) {
1152
+ throw new Error(`You tried to update a record but you have no adapter (for ${modelName})`);
1153
+ }
1154
+ })(adapter) : {};
1155
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1156
+ if (!test) {
1157
+ throw new Error(`You tried to update a record but your adapter (for ${modelName}) does not implement '${operation}'`);
1158
+ }
1159
+ })(typeof adapter[operation] === 'function') : {};
1160
+ let promise = Promise.resolve().then(() => adapter[operation](store, modelClass, snapshot));
1161
+ const serializer = store.serializerFor(modelName);
1162
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1163
+ if (!test) {
1164
+ throw new Error(`Your adapter's '${operation}' method must return a value, but it returned 'undefined'`);
1165
+ }
1166
+ })(promise !== undefined) : {};
1167
+ promise = promise.then(adapterPayload => {
1168
+ if (adapterPayload) {
1169
+ return normalizeResponseHelper(serializer, store, modelClass, adapterPayload, snapshot.id, operation);
1170
+ }
1171
+ });
1172
+ resolver.resolve(promise);
1173
+ }
1174
+
1175
+ /**
1176
+ * Utilities - often temporary - for maintaining backwards compatibility with
1177
+ * older parts of EmberData.
1178
+ *
1179
+ @module
1180
+ */
1181
+ function upgradeStore(store) {}
1182
+ export { FetchManager as F, SaveOp as S, assertIdentifierHasId as a, SnapshotRecordArray as b, Snapshot as c, iterateData as i, normalizeResponseHelper as n, payloadIsNotBlank as p, upgradeStore as u };