@warp-drive/legacy 5.8.0-alpha.9 → 5.8.0-beta.1

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 (200) hide show
  1. package/README.md +14 -27
  2. package/declarations/adapter/error.d.ts +7 -7
  3. package/declarations/adapter/json-api.d.ts +2 -2
  4. package/declarations/adapter/rest.d.ts +21 -104
  5. package/declarations/adapter.d.ts +2 -2
  6. package/declarations/compat/builders/find-all.d.ts +6 -6
  7. package/declarations/compat/builders/find-record.d.ts +8 -8
  8. package/declarations/compat/builders/query.d.ts +12 -12
  9. package/declarations/compat/legacy-network-handler/minimum-serializer-interface.d.ts +16 -24
  10. package/declarations/compat/utils.d.ts +13 -13
  11. package/declarations/compat.d.ts +31 -5
  12. package/declarations/index.d.ts +25 -8
  13. package/declarations/model/-private/legacy-relationships-support.d.ts +2 -2
  14. package/declarations/model/-private/model.d.ts +10 -51
  15. package/declarations/model/-private/promise-many-array.d.ts +0 -18
  16. package/declarations/model/-private/references/belongs-to.d.ts +18 -28
  17. package/declarations/model/-private/references/has-many.d.ts +13 -15
  18. package/declarations/model/migration-support.d.ts +42 -19
  19. package/declarations/model-fragments/extensions/fragment-array.d.ts +16 -0
  20. package/declarations/model-fragments/extensions/fragment.d.ts +15 -0
  21. package/declarations/model-fragments/hooks/model-for.d.ts +20 -0
  22. package/declarations/model-fragments/index.d.ts +5 -0
  23. package/declarations/model-fragments/instance-initializers/fragment-extensions.d.ts +9 -0
  24. package/declarations/model-fragments/utilities/with-array-defaults.d.ts +15 -0
  25. package/declarations/model-fragments/utilities/with-fragment-array-defaults.d.ts +20 -0
  26. package/declarations/model-fragments/utilities/with-fragment-defaults.d.ts +19 -0
  27. package/declarations/model-fragments/utilities/with-legacy.d.ts +3 -0
  28. package/declarations/model-fragments.d.ts +9 -0
  29. package/declarations/model.d.ts +2 -2
  30. package/declarations/serializer/-private/embedded-records-mixin.d.ts +1 -1
  31. package/declarations/serializer/json-api.d.ts +7 -6
  32. package/declarations/serializer/json.d.ts +3 -3
  33. package/declarations/serializer.d.ts +5 -6
  34. package/dist/{-private-B1pSSN52.js → -private-BG3bMiKp.js} +2 -1
  35. package/dist/adapter/-private.js +1 -1
  36. package/dist/adapter/error.js +9 -9
  37. package/dist/adapter/json-api.js +1 -1
  38. package/dist/adapter/rest.js +33 -117
  39. package/dist/adapter.js +2 -2
  40. package/dist/compat/-private.js +1 -1
  41. package/dist/compat/builders.js +26 -26
  42. package/dist/compat/utils.js +13 -14
  43. package/dist/compat.js +28 -8
  44. package/dist/{errors-COviC59J.js → errors-Cz5KrzBk.js} +113 -120
  45. package/dist/{hooks-Bp8SIQBU.js → hooks-D6diaM34.js} +1 -1
  46. package/dist/index.js +25 -8
  47. package/dist/{json-ksWOHRfq.js → json-ChdEfB0X.js} +12 -27
  48. package/dist/model/-private.js +1 -1
  49. package/dist/model/migration-support.js +55 -25
  50. package/dist/model-for-CqXsIKws.js +221 -0
  51. package/dist/model-fragments.js +76 -0
  52. package/dist/model.js +3 -3
  53. package/dist/{schema-provider-JlCneqZH.js → schema-provider-DJCV_6AF.js} +44 -87
  54. package/dist/{serialize-into-hash-BnYvPex3.js → serialize-into-hash-DPZYoF-i.js} +1 -1
  55. package/dist/serializer/json-api.js +18 -45
  56. package/dist/serializer/json.js +1 -1
  57. package/dist/serializer/rest.js +10 -10
  58. package/dist/serializer.js +5 -6
  59. package/dist/store.js +2 -1
  60. package/dist/unpkg/dev/-private-DtjBbEgy.js +1206 -0
  61. package/dist/unpkg/dev/adapter/-private.js +1 -0
  62. package/dist/unpkg/dev/adapter/error.js +335 -0
  63. package/dist/unpkg/dev/adapter/json-api.js +271 -0
  64. package/dist/unpkg/dev/adapter/rest.js +1171 -0
  65. package/dist/unpkg/dev/adapter.js +1252 -0
  66. package/dist/unpkg/dev/compat/-private.js +1 -0
  67. package/dist/unpkg/dev/compat/builders.js +275 -0
  68. package/dist/unpkg/dev/compat/extensions.js +242 -0
  69. package/dist/unpkg/dev/compat/utils.js +223 -0
  70. package/dist/unpkg/dev/compat.js +1147 -0
  71. package/dist/unpkg/dev/errors-DmGGJr3T.js +2562 -0
  72. package/dist/unpkg/dev/hooks-CkYiE6Ud.js +73 -0
  73. package/dist/unpkg/dev/index.js +197 -0
  74. package/dist/unpkg/dev/json-Cu1LNgmQ.js +1256 -0
  75. package/dist/unpkg/dev/model/-private.js +1 -0
  76. package/dist/unpkg/dev/model/migration-support.js +553 -0
  77. package/dist/unpkg/dev/model-for-CqXsIKws.js +221 -0
  78. package/dist/unpkg/dev/model-fragments.js +76 -0
  79. package/dist/unpkg/dev/model.js +678 -0
  80. package/dist/unpkg/dev/runtime-BPCpkOf1-BKOwiRJp.js +65 -0
  81. package/dist/unpkg/dev/schema-provider-DDVYxmUV.js +2186 -0
  82. package/dist/unpkg/dev/serialize-into-hash-B2xDbuo5.js +259 -0
  83. package/dist/unpkg/dev/serializer/json-api.js +649 -0
  84. package/dist/unpkg/dev/serializer/json.js +4 -0
  85. package/dist/unpkg/dev/serializer/rest.js +1242 -0
  86. package/dist/unpkg/dev/serializer/transform.js +278 -0
  87. package/dist/unpkg/dev/serializer.js +248 -0
  88. package/dist/unpkg/dev/store.js +637 -0
  89. package/dist/unpkg/dev/util-DvanW33H.js +20 -0
  90. package/dist/unpkg/dev/utils-BhvS1iTS.js +8 -0
  91. package/dist/unpkg/dev-deprecated/-private-DtjBbEgy.js +1206 -0
  92. package/dist/unpkg/dev-deprecated/adapter/-private.js +1 -0
  93. package/dist/unpkg/dev-deprecated/adapter/error.js +335 -0
  94. package/dist/unpkg/dev-deprecated/adapter/json-api.js +271 -0
  95. package/dist/unpkg/dev-deprecated/adapter/rest.js +1171 -0
  96. package/dist/unpkg/dev-deprecated/adapter.js +1252 -0
  97. package/dist/unpkg/dev-deprecated/compat/-private.js +1 -0
  98. package/dist/unpkg/dev-deprecated/compat/builders.js +275 -0
  99. package/dist/unpkg/dev-deprecated/compat/extensions.js +242 -0
  100. package/dist/unpkg/dev-deprecated/compat/utils.js +223 -0
  101. package/dist/unpkg/dev-deprecated/compat.js +1147 -0
  102. package/dist/unpkg/dev-deprecated/errors-Spt6ubMd.js +2565 -0
  103. package/dist/unpkg/dev-deprecated/hooks-DOXegvhL.js +73 -0
  104. package/dist/unpkg/dev-deprecated/index.js +196 -0
  105. package/dist/unpkg/dev-deprecated/json-Cu1LNgmQ.js +1256 -0
  106. package/dist/unpkg/dev-deprecated/model/-private.js +1 -0
  107. package/dist/unpkg/dev-deprecated/model/migration-support.js +570 -0
  108. package/dist/unpkg/dev-deprecated/model-for-CqXsIKws.js +221 -0
  109. package/dist/unpkg/dev-deprecated/model-fragments.js +76 -0
  110. package/dist/unpkg/dev-deprecated/model.js +682 -0
  111. package/dist/unpkg/dev-deprecated/runtime-BPCpkOf1-BKOwiRJp.js +65 -0
  112. package/dist/unpkg/dev-deprecated/schema-provider-BP6_8N-V.js +2211 -0
  113. package/dist/unpkg/dev-deprecated/serialize-into-hash-B2xDbuo5.js +259 -0
  114. package/dist/unpkg/dev-deprecated/serializer/json-api.js +649 -0
  115. package/dist/unpkg/dev-deprecated/serializer/json.js +4 -0
  116. package/dist/unpkg/dev-deprecated/serializer/rest.js +1242 -0
  117. package/dist/unpkg/dev-deprecated/serializer/transform.js +278 -0
  118. package/dist/unpkg/dev-deprecated/serializer.js +248 -0
  119. package/dist/unpkg/dev-deprecated/store.js +637 -0
  120. package/dist/unpkg/dev-deprecated/util-CWr5WQOT.js +24 -0
  121. package/dist/unpkg/dev-deprecated/utils-C9PJehtL.js +12 -0
  122. package/dist/unpkg/prod/-private-BdyZaGEh.js +971 -0
  123. package/dist/unpkg/prod/adapter/-private.js +1 -0
  124. package/dist/unpkg/prod/adapter/error.js +330 -0
  125. package/dist/unpkg/prod/adapter/json-api.js +266 -0
  126. package/dist/unpkg/prod/adapter/rest.js +1134 -0
  127. package/dist/unpkg/prod/adapter.js +1219 -0
  128. package/dist/unpkg/prod/compat/-private.js +1 -0
  129. package/dist/unpkg/prod/compat/builders.js +210 -0
  130. package/dist/unpkg/prod/compat/extensions.js +232 -0
  131. package/dist/unpkg/prod/compat/utils.js +218 -0
  132. package/dist/unpkg/prod/compat.js +727 -0
  133. package/dist/unpkg/prod/errors-BGVFCBmi.js +2314 -0
  134. package/dist/unpkg/prod/hooks-BztVA_x0.js +41 -0
  135. package/dist/unpkg/prod/index.js +151 -0
  136. package/dist/unpkg/prod/json-BWrZ5546.js +1243 -0
  137. package/dist/unpkg/prod/model/-private.js +1 -0
  138. package/dist/unpkg/prod/model/migration-support.js +546 -0
  139. package/dist/unpkg/prod/model-for-CqXsIKws.js +221 -0
  140. package/dist/unpkg/prod/model-fragments.js +76 -0
  141. package/dist/unpkg/prod/model.js +593 -0
  142. package/dist/unpkg/prod/runtime-BPCpkOf1-BKOwiRJp.js +65 -0
  143. package/dist/unpkg/prod/schema-provider-DJtD_8jZ.js +1861 -0
  144. package/dist/unpkg/prod/serialize-into-hash-DGlzQteF.js +215 -0
  145. package/dist/unpkg/prod/serializer/json-api.js +592 -0
  146. package/dist/unpkg/prod/serializer/json.js +4 -0
  147. package/dist/unpkg/prod/serializer/rest.js +1210 -0
  148. package/dist/unpkg/prod/serializer/transform.js +278 -0
  149. package/dist/unpkg/prod/serializer.js +248 -0
  150. package/dist/unpkg/prod/store.js +505 -0
  151. package/dist/unpkg/prod/util-DvanW33H.js +20 -0
  152. package/dist/unpkg/prod/utils-BhvS1iTS.js +8 -0
  153. package/dist/unpkg/prod-deprecated/-private-BdyZaGEh.js +971 -0
  154. package/dist/unpkg/prod-deprecated/adapter/-private.js +1 -0
  155. package/dist/unpkg/prod-deprecated/adapter/error.js +330 -0
  156. package/dist/unpkg/prod-deprecated/adapter/json-api.js +266 -0
  157. package/dist/unpkg/prod-deprecated/adapter/rest.js +1134 -0
  158. package/dist/unpkg/prod-deprecated/adapter.js +1219 -0
  159. package/dist/unpkg/prod-deprecated/compat/-private.js +1 -0
  160. package/dist/unpkg/prod-deprecated/compat/builders.js +210 -0
  161. package/dist/unpkg/prod-deprecated/compat/extensions.js +232 -0
  162. package/dist/unpkg/prod-deprecated/compat/utils.js +218 -0
  163. package/dist/unpkg/prod-deprecated/compat.js +727 -0
  164. package/dist/unpkg/prod-deprecated/errors-CdDaK81x.js +2317 -0
  165. package/dist/unpkg/prod-deprecated/hooks-yId87yyG.js +41 -0
  166. package/dist/unpkg/prod-deprecated/index.js +150 -0
  167. package/dist/unpkg/prod-deprecated/json-BWrZ5546.js +1243 -0
  168. package/dist/unpkg/prod-deprecated/model/-private.js +1 -0
  169. package/dist/unpkg/prod-deprecated/model/migration-support.js +563 -0
  170. package/dist/unpkg/prod-deprecated/model-for-CqXsIKws.js +221 -0
  171. package/dist/unpkg/prod-deprecated/model-fragments.js +76 -0
  172. package/dist/unpkg/prod-deprecated/model.js +596 -0
  173. package/dist/unpkg/prod-deprecated/runtime-BPCpkOf1-BKOwiRJp.js +65 -0
  174. package/dist/unpkg/prod-deprecated/schema-provider-CjX55uSY.js +1904 -0
  175. package/dist/unpkg/prod-deprecated/serialize-into-hash-DGlzQteF.js +215 -0
  176. package/dist/unpkg/prod-deprecated/serializer/json-api.js +592 -0
  177. package/dist/unpkg/prod-deprecated/serializer/json.js +4 -0
  178. package/dist/unpkg/prod-deprecated/serializer/rest.js +1210 -0
  179. package/dist/unpkg/prod-deprecated/serializer/transform.js +278 -0
  180. package/dist/unpkg/prod-deprecated/serializer.js +248 -0
  181. package/dist/unpkg/prod-deprecated/store.js +505 -0
  182. package/dist/unpkg/prod-deprecated/util-B6cn-i93.js +23 -0
  183. package/dist/unpkg/prod-deprecated/utils-BUWwQwCh.js +11 -0
  184. package/logos/README.md +2 -2
  185. package/logos/logo-yellow-slab.svg +1 -0
  186. package/logos/word-mark-black.svg +1 -0
  187. package/logos/word-mark-white.svg +1 -0
  188. package/package.json +14 -6
  189. package/logos/NCC-1701-a-blue.svg +0 -4
  190. package/logos/NCC-1701-a-gold.svg +0 -4
  191. package/logos/NCC-1701-a-gold_100.svg +0 -1
  192. package/logos/NCC-1701-a-gold_base-64.txt +0 -1
  193. package/logos/NCC-1701-a.svg +0 -4
  194. package/logos/docs-badge.svg +0 -2
  195. package/logos/ember-data-logo-dark.svg +0 -12
  196. package/logos/ember-data-logo-light.svg +0 -12
  197. package/logos/social1.png +0 -0
  198. package/logos/social2.png +0 -0
  199. package/logos/warp-drive-logo-dark.svg +0 -4
  200. package/logos/warp-drive-logo-gold.svg +0 -4
@@ -0,0 +1,2314 @@
1
+ import { Context } from '@warp-drive/core/reactive/-private';
2
+ import { memoized, defineSignal, defineNonEnumerableSignal, notifyInternalSignal } from '@warp-drive/core/signals/-leaked';
3
+ import { assertPrivateStore, recordIdentifierFor, isPrivateStore, storeFor, fastPush, createLegacyManyArray } from '@warp-drive/core/store/-private';
4
+ import { getOrSetGlobal } from '@warp-drive/core/types/-private';
5
+ import { EnableHydration } from '@warp-drive/core/types/request';
6
+ import { u as upgradeStore } from "./-private-BdyZaGEh.js";
7
+ import { computed, get } from '@ember/object';
8
+ import PromiseProxyMixin from '@ember/object/promise-proxy-mixin';
9
+ import ObjectProxy from '@ember/object/proxy';
10
+ import { d as decorateMethodV2, a as decorateFieldV2, i as initializeDeferredDecorator } from "./runtime-BPCpkOf1-BKOwiRJp.js";
11
+ import { A } from '@ember/array';
12
+ import ArrayProxy from '@ember/array/proxy';
13
+ import { mapBy, not } from '@ember/object/computed';
14
+ const PromiseObject = ObjectProxy.extend(PromiseProxyMixin);
15
+ const LegacyPromiseProxy = Symbol.for('LegacyPromiseProxy');
16
+
17
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/no-extraneous-class
18
+
19
+ const Extended = PromiseObject;
20
+
21
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
22
+
23
+ /**
24
+ A PromiseBelongsTo is a PromiseObject that also proxies certain method calls
25
+ to the underlying belongsTo model.
26
+ Right now we proxy:
27
+ * `reload()`
28
+ @class PromiseBelongsTo
29
+ @private
30
+ */
31
+ class PromiseBelongsTo extends Extended {
32
+ get id() {
33
+ const {
34
+ key,
35
+ legacySupport
36
+ } = this._belongsToState;
37
+ const ref = legacySupport.referenceFor('belongsTo', key);
38
+ return ref.id();
39
+ }
40
+
41
+ // we don't proxy meta because we would need to proxy it to the relationship state container
42
+ // however, meta on relationships does not trigger change notifications.
43
+ // if you need relationship meta, you should do `record.belongsTo(relationshipName).meta()`
44
+ static {
45
+ decorateMethodV2(this.prototype, "id", [memoized]);
46
+ }
47
+ get meta() {
48
+ return;
49
+ }
50
+ static {
51
+ decorateMethodV2(this.prototype, "meta", [computed()]);
52
+ }
53
+ async reload(options) {
54
+ const {
55
+ key,
56
+ legacySupport
57
+ } = this._belongsToState;
58
+ await legacySupport.reloadBelongsTo(key, options);
59
+ return this;
60
+ }
61
+ }
62
+ PromiseBelongsTo.prototype[LegacyPromiseProxy] = true;
63
+
64
+ /**
65
+ This class is returned as the result of accessing an async hasMany relationship
66
+ on an instance of a Model extending from `@ember-data/model`.
67
+
68
+ A PromiseManyArray is an iterable proxy that allows templates to consume related
69
+ ManyArrays and update once their contents are no longer pending.
70
+
71
+ In your JS code you should resolve the promise first.
72
+
73
+ ```js
74
+ const comments = await post.comments;
75
+ ```
76
+
77
+ @public
78
+ */
79
+ class PromiseManyArray {
80
+ constructor(promise, content) {
81
+ this._update(promise, content);
82
+ this.isDestroyed = false;
83
+ this[LegacyPromiseProxy] = true;
84
+ }
85
+
86
+ /**
87
+ * Retrieve the length of the content
88
+ * @public
89
+ */
90
+ get length() {
91
+ // shouldn't be needed, but ends up being needed
92
+ // for computed chains even in 4.x
93
+
94
+ return this.content ? this.content.length : 0;
95
+ }
96
+
97
+ // this will error if someone tries to call
98
+ // A(identifierArray) since it is not configurable
99
+ // which is preferrable to the `meta` override we used
100
+ // before which required importing all of Ember
101
+ static {
102
+ decorateMethodV2(this.prototype, "length", [memoized]);
103
+ }
104
+ get '[]'() {
105
+ // ember-source < 3.23 (e.g. 3.20 lts)
106
+ // requires that the tag `'[]'` be notified
107
+ // on the ArrayProxy in order for `{{#each}}`
108
+ // to recompute. We entangle content.
109
+ return this.content?.length && this.content;
110
+ }
111
+
112
+ /**
113
+ * Iterate the proxied content. Called by the glimmer iterator in #each
114
+ * We do not guarantee that forEach will always be available. This
115
+ * may eventually be made to use Symbol.Iterator once glimmer supports it.
116
+ *
117
+ * @param cb
118
+ * @return
119
+ * @private
120
+ */
121
+ static {
122
+ decorateMethodV2(this.prototype, '[]', [memoized]);
123
+ }
124
+ forEach(cb) {
125
+ if (this.content && this.length) {
126
+ this.content.forEach(cb);
127
+ }
128
+ }
129
+
130
+ /**
131
+ * Reload the relationship
132
+ * @public
133
+ */
134
+ reload(options) {
135
+ void this.content.reload(options);
136
+ return this;
137
+ }
138
+
139
+ //---- Properties/Methods from the PromiseProxyMixin that we will keep as our API
140
+
141
+ /**
142
+ * Whether the loading promise is still pending
143
+ *
144
+ * @public
145
+ */
146
+
147
+ /**
148
+ * Whether the loading promise rejected
149
+ *
150
+ * @public
151
+ */
152
+
153
+ /**
154
+ * Whether the loading promise succeeded
155
+ *
156
+ * @public
157
+ */
158
+
159
+ /**
160
+ * Whether the loading promise completed (resolved or rejected)
161
+ *
162
+ * @public
163
+ */
164
+
165
+ /**
166
+ * chain this promise
167
+ *
168
+ * @public
169
+ */
170
+ then(success, rejected) {
171
+ return this.promise.then(success, rejected);
172
+ }
173
+
174
+ /**
175
+ * catch errors thrown by this promise
176
+ * @public
177
+ */
178
+ catch(cb) {
179
+ return this.promise.catch(cb);
180
+ }
181
+
182
+ /**
183
+ * run cleanup after this promise completes
184
+ *
185
+ * @public
186
+ */
187
+ finally(cb) {
188
+ return this.promise.finally(cb);
189
+ }
190
+
191
+ //---- Methods on EmberObject that we should keep
192
+
193
+ destroy() {
194
+ this.isDestroyed = true;
195
+ this.content = null;
196
+ this.promise = null;
197
+ }
198
+
199
+ //---- Methods/Properties on ManyArray that we own and proxy to
200
+
201
+ /**
202
+ * Retrieve the links for this relationship
203
+ * @public
204
+ */
205
+ get links() {
206
+ return this.content ? this.content.links : undefined;
207
+ }
208
+
209
+ /**
210
+ * Retrieve the meta for this relationship
211
+ * @public
212
+ */
213
+ static {
214
+ decorateMethodV2(this.prototype, "links", [memoized]);
215
+ }
216
+ get meta() {
217
+ return this.content ? this.content.meta : undefined;
218
+ }
219
+
220
+ //---- Our own stuff
221
+
222
+ /** @internal */
223
+ static {
224
+ decorateMethodV2(this.prototype, "meta", [memoized]);
225
+ }
226
+ _update(promise, content) {
227
+ if (content !== undefined) {
228
+ this.content = content;
229
+ }
230
+ this.promise = tapPromise(this, promise);
231
+ }
232
+ static create({
233
+ promise,
234
+ content
235
+ }) {
236
+ return new this(promise, content);
237
+ }
238
+ }
239
+ defineSignal(PromiseManyArray.prototype, 'content', null);
240
+ defineSignal(PromiseManyArray.prototype, 'isPending', false);
241
+ defineSignal(PromiseManyArray.prototype, 'isRejected', false);
242
+ defineSignal(PromiseManyArray.prototype, 'isFulfilled', false);
243
+ defineSignal(PromiseManyArray.prototype, 'isSettled', false);
244
+ function tapPromise(proxy, promise) {
245
+ proxy.isPending = true;
246
+ proxy.isSettled = false;
247
+ proxy.isFulfilled = false;
248
+ proxy.isRejected = false;
249
+ return Promise.resolve(promise).then(content => {
250
+ proxy.isPending = false;
251
+ proxy.isFulfilled = true;
252
+ proxy.isSettled = true;
253
+ proxy.content = content;
254
+ return content;
255
+ }, error => {
256
+ proxy.isPending = false;
257
+ proxy.isFulfilled = false;
258
+ proxy.isRejected = true;
259
+ proxy.isSettled = true;
260
+ throw error;
261
+ });
262
+ }
263
+ function isResourceIdentiferWithRelatedLinks$1(value) {
264
+ return Boolean(value && value.links && value.links.related);
265
+ }
266
+ /**
267
+ A `HasManyReference` is a low-level API that allows access
268
+ and manipulation of a hasMany relationship.
269
+
270
+ It is especially useful when you're dealing with `async` relationships
271
+ from `@warp-drive/legacy/model` as it allows synchronous access to
272
+ the relationship data if loaded, as well as APIs for loading, reloading
273
+ the data or accessing available information without triggering a load.
274
+
275
+ It may also be useful when using `sync` relationships with `@warp-drive/legacy/model`
276
+ that need to be loaded/reloaded with more precise timing than marking the
277
+ relationship as `async` and relying on autofetch would have allowed.
278
+
279
+ However,keep in mind that marking a relationship as `async: false` will introduce
280
+ bugs into your application if the data is not always guaranteed to be available
281
+ by the time the relationship is accessed. Ergo, it is recommended when using this
282
+ approach to utilize `links` for unloaded relationship state instead of identifiers.
283
+
284
+ Reference APIs are entangled with the relationship's underlying state,
285
+ thus any getters or cached properties that utilize these will properly
286
+ invalidate if the relationship state changes.
287
+
288
+ References are "stable", meaning that multiple calls to retrieve the reference
289
+ for a given relationship will always return the same HasManyReference.
290
+
291
+ @class HasManyReference
292
+ @public
293
+ */
294
+ class HasManyReference {
295
+ /**
296
+ * The field name on the parent record for this has-many relationship.
297
+ *
298
+ * @property key
299
+ * @type {String}
300
+ * @public
301
+ */
302
+
303
+ /**
304
+ * The type of resource this relationship will contain.
305
+ *
306
+ * @property type
307
+ * @type {String}
308
+ * @public
309
+ */
310
+
311
+ // unsubscribe tokens given to us by the notification manager
312
+ ___token;
313
+ ___identifier;
314
+ ___relatedTokenMap;
315
+ constructor(store, graph, parentIdentifier, hasManyRelationship, key) {
316
+ this.graph = graph;
317
+ this.key = key;
318
+ this.hasManyRelationship = hasManyRelationship;
319
+ this.type = hasManyRelationship.definition.type;
320
+ this.store = store;
321
+ this.___identifier = parentIdentifier;
322
+ this.___token = store.notifications.subscribe(parentIdentifier, (_, bucket, notifiedKey) => {
323
+ if (bucket === 'relationships' && notifiedKey === key) {
324
+ this._ref++;
325
+ }
326
+ });
327
+ this.___relatedTokenMap = new Map();
328
+ // TODO inverse
329
+ }
330
+
331
+ /**
332
+ * This method should never be called by user code.
333
+ *
334
+ * @internal
335
+ */
336
+ destroy() {
337
+ this.store.notifications.unsubscribe(this.___token);
338
+ this.___relatedTokenMap.forEach(token => {
339
+ this.store.notifications.unsubscribe(token);
340
+ });
341
+ this.___relatedTokenMap.clear();
342
+ }
343
+
344
+ /**
345
+ * An array of identifiers for the records that this reference refers to.
346
+ *
347
+ * @property identifiers
348
+ * @type {ResourceKey[]}
349
+ * @public
350
+ */
351
+ get identifiers() {
352
+ ensureRefCanSubscribe(this);
353
+ // eslint-disable-next-line @typescript-eslint/no-unused-expressions
354
+ this._ref;
355
+ const resource = this._resource();
356
+ const map = this.___relatedTokenMap;
357
+ this.___relatedTokenMap = new Map();
358
+ if (resource && resource.data) {
359
+ return resource.data.map(resourceIdentifier => {
360
+ const identifier = this.store.cacheKeyManager.getOrCreateRecordIdentifier(resourceIdentifier);
361
+ let token = map.get(identifier);
362
+ if (token) {
363
+ map.delete(identifier);
364
+ } else {
365
+ token = this.store.notifications.subscribe(identifier, (_, bucket, notifiedKey) => {
366
+ if (bucket === 'identity' || bucket === 'attributes' && notifiedKey === 'id') {
367
+ this._ref++;
368
+ }
369
+ });
370
+ }
371
+ this.___relatedTokenMap.set(identifier, token);
372
+ return identifier;
373
+ });
374
+ }
375
+ map.forEach(token => {
376
+ this.store.notifications.unsubscribe(token);
377
+ });
378
+ map.clear();
379
+ return [];
380
+ }
381
+ static {
382
+ decorateMethodV2(this.prototype, "identifiers", [memoized]);
383
+ }
384
+ _resource() {
385
+ const cache = this.store.cache;
386
+ return cache.getRelationship(this.___identifier, this.key);
387
+ }
388
+
389
+ /**
390
+ This returns a string that represents how the reference will be
391
+ looked up when it is loaded. If the relationship has a link it will
392
+ use the "link" otherwise it defaults to "id".
393
+ Example
394
+ ```js [app/models/post.js]
395
+ import { Model, hasMany } from '@warp-drive/legacy/model';
396
+ export default class PostModel extends Model {
397
+ @hasMany('comment', { async: true, inverse: null }) comments;
398
+ }
399
+ ```
400
+ ```javascript
401
+ let post = store.push({
402
+ data: {
403
+ type: 'post',
404
+ id: 1,
405
+ relationships: {
406
+ comments: {
407
+ data: [{ type: 'comment', id: 1 }]
408
+ }
409
+ }
410
+ }
411
+ });
412
+ let commentsRef = post.hasMany('comments');
413
+ // get the identifier of the reference
414
+ if (commentsRef.remoteType() === "ids") {
415
+ let ids = commentsRef.ids();
416
+ } else if (commentsRef.remoteType() === "link") {
417
+ let link = commentsRef.link();
418
+ }
419
+ ```
420
+ @public
421
+ @return The name of the remote type. This should either be `link` or `ids`
422
+ */
423
+ remoteType() {
424
+ const value = this._resource();
425
+ if (value && value.links && value.links.related) {
426
+ return 'link';
427
+ }
428
+ return 'ids';
429
+ }
430
+
431
+ /**
432
+ `ids()` returns an array of the record IDs in this relationship.
433
+ Example
434
+ ```js [app/models/post.js]
435
+ import { Model, hasMany } from '@warp-drive/legacy/model';
436
+ export default class PostModel extends Model {
437
+ @hasMany('comment', { async: true, inverse: null }) comments;
438
+ }
439
+ ```
440
+ ```javascript
441
+ let post = store.push({
442
+ data: {
443
+ type: 'post',
444
+ id: 1,
445
+ relationships: {
446
+ comments: {
447
+ data: [{ type: 'comment', id: 1 }]
448
+ }
449
+ }
450
+ }
451
+ });
452
+ let commentsRef = post.hasMany('comments');
453
+ commentsRef.ids(); // ['1']
454
+ ```
455
+ @public
456
+ @return The ids in this has-many relationship
457
+ */
458
+ ids() {
459
+ return this.identifiers.map(identifier => identifier.id);
460
+ }
461
+
462
+ /**
463
+ The link WarpDrive will use to fetch or reload this belongs-to
464
+ relationship. By default it uses only the "related" resource linkage.
465
+ Example
466
+ ```javascript
467
+ // models/blog.js
468
+ import { Model, belongsTo } from '@warp-drive/legacy/model';
469
+ export default Model.extend({
470
+ user: belongsTo('user', { async: true, inverse: null })
471
+ });
472
+ let blog = store.push({
473
+ data: {
474
+ type: 'blog',
475
+ id: 1,
476
+ relationships: {
477
+ user: {
478
+ links: {
479
+ related: '/articles/1/author'
480
+ }
481
+ }
482
+ }
483
+ }
484
+ });
485
+ let userRef = blog.belongsTo('user');
486
+ // get the identifier of the reference
487
+ if (userRef.remoteType() === "link") {
488
+ let link = userRef.link();
489
+ }
490
+ ```
491
+ @public
492
+ @return The link WarpDrive will use to fetch or reload this belongs-to relationship.
493
+ */
494
+ link() {
495
+ const resource = this._resource();
496
+ if (isResourceIdentiferWithRelatedLinks$1(resource)) {
497
+ if (resource.links) {
498
+ const related = resource.links.related;
499
+ return !related || typeof related === 'string' ? related : related.href;
500
+ }
501
+ }
502
+ return null;
503
+ }
504
+
505
+ /**
506
+ * any links that have been received for this relationship
507
+ *
508
+ * @public
509
+ * @return
510
+ */
511
+ links() {
512
+ const resource = this._resource();
513
+ return resource && resource.links ? resource.links : null;
514
+ }
515
+
516
+ /**
517
+ The meta data for the has-many relationship.
518
+ Example
519
+ ```javascript
520
+ // models/blog.js
521
+ import { Model, hasMany } from '@warp-drive/legacy/model';
522
+ export default Model.extend({
523
+ users: hasMany('user', { async: true, inverse: null })
524
+ });
525
+ let blog = store.push({
526
+ data: {
527
+ type: 'blog',
528
+ id: 1,
529
+ relationships: {
530
+ users: {
531
+ links: {
532
+ related: {
533
+ href: '/articles/1/authors'
534
+ },
535
+ },
536
+ meta: {
537
+ lastUpdated: 1458014400000
538
+ }
539
+ }
540
+ }
541
+ }
542
+ });
543
+ let usersRef = blog.hasMany('user');
544
+ usersRef.meta() // { lastUpdated: 1458014400000 }
545
+ ```
546
+ @public
547
+ @return The meta information for the belongs-to relationship.
548
+ */
549
+ meta() {
550
+ let meta = null;
551
+ const resource = this._resource();
552
+ if (resource && resource.meta && typeof resource.meta === 'object') {
553
+ meta = resource.meta;
554
+ }
555
+ return meta;
556
+ }
557
+
558
+ /**
559
+ `push` can be used to update the data in the relationship and WarpDrive
560
+ will treat the new data as the canonical value of this relationship on
561
+ the backend. An empty array will signify the canonical value should be
562
+ empty.
563
+ Example model
564
+ ```js [app/models/post.js]
565
+ import { Model, hasMany } from '@warp-drive/legacy/model';
566
+ export default class PostModel extends Model {
567
+ @hasMany('comment', { async: true, inverse: null }) comments;
568
+ }
569
+ ```
570
+ Setup some initial state, note we haven't loaded the comments yet:
571
+ ```js
572
+ const post = store.push({
573
+ data: {
574
+ type: 'post',
575
+ id: '1',
576
+ relationships: {
577
+ comments: {
578
+ data: [{ type: 'comment', id: '1' }]
579
+ }
580
+ }
581
+ }
582
+ });
583
+ const commentsRef = post.hasMany('comments');
584
+ commentsRef.ids(); // ['1']
585
+ ```
586
+ Update the state using `push`, note we can do this even without
587
+ having loaded these comments yet by providing resource identifiers.
588
+ Both full resources and resource identifiers are supported.
589
+ ```js
590
+ await commentsRef.push({
591
+ data: [
592
+ { type: 'comment', id: '2' },
593
+ { type: 'comment', id: '3' },
594
+ ]
595
+ });
596
+ commentsRef.ids(); // ['2', '3']
597
+ ```
598
+ For convenience, you can also pass in an array of resources or resource identifiers
599
+ without wrapping them in the `data` property:
600
+ ```js
601
+ await commentsRef.push([
602
+ { type: 'comment', id: '4' },
603
+ { type: 'comment', id: '5' },
604
+ ]);
605
+ commentsRef.ids(); // ['4', '5']
606
+ ```
607
+ When using the `data` property, you may also include other resource data via included,
608
+ as well as provide new links and meta to the relationship.
609
+ ```js
610
+ await commentsRef.push({
611
+ links: {
612
+ related: '/posts/1/comments'
613
+ },
614
+ meta: {
615
+ total: 2
616
+ },
617
+ data: [
618
+ { type: 'comment', id: '4' },
619
+ { type: 'comment', id: '5' },
620
+ ],
621
+ included: [
622
+ { type: 'other-thing', id: '1', attributes: { foo: 'bar' },
623
+ ]
624
+ });
625
+ ```
626
+ By default, the store will attempt to fetch any unloaded records before resolving
627
+ the returned promise with the ManyArray.
628
+ Alternatively, pass `true` as the second argument to avoid fetching unloaded records
629
+ and instead the promise will resolve with void without attempting to fetch. This is
630
+ particularly useful if you want to update the state of the relationship without
631
+ forcing the load of all of the associated records.
632
+ @public
633
+ @param doc a JSONAPI document object describing the new value of this relationship.
634
+ @param skipFetch [optional] if `true`, do not attempt to fetch unloaded records
635
+ */
636
+ async push(doc, skipFetch) {
637
+ const {
638
+ store
639
+ } = this;
640
+ const dataDoc = Array.isArray(doc) ? {
641
+ data: doc
642
+ } : doc;
643
+ const isResourceData = Array.isArray(dataDoc.data) && dataDoc.data.length > 0 && isMaybeResource(dataDoc.data[0]);
644
+ const identifiers = !Array.isArray(dataDoc.data) ? [] : isResourceData ? store._push(dataDoc, true) : dataDoc.data.map(i => store.cacheKeyManager.getOrCreateRecordIdentifier(i));
645
+ const {
646
+ identifier
647
+ } = this.hasManyRelationship;
648
+ const newData = {};
649
+ // only set data if it was passed in
650
+ if (Array.isArray(dataDoc.data)) {
651
+ newData.data = identifiers;
652
+ }
653
+ if ('links' in dataDoc) {
654
+ newData.links = dataDoc.links;
655
+ }
656
+ if ('meta' in dataDoc) {
657
+ newData.meta = dataDoc.meta;
658
+ }
659
+ assertPrivateStore(store);
660
+ store._join(() => {
661
+ this.graph.push({
662
+ op: 'updateRelationship',
663
+ record: identifier,
664
+ field: this.key,
665
+ value: newData
666
+ });
667
+ });
668
+ if (!skipFetch) return this.load();
669
+ }
670
+ _isLoaded() {
671
+ const hasRelationshipDataProperty = this.hasManyRelationship.state.hasReceivedData;
672
+ if (!hasRelationshipDataProperty) {
673
+ return false;
674
+ }
675
+ const relationship = this.graph.getData(this.hasManyRelationship.identifier, this.key);
676
+ return relationship.data ? relationship.data.every(identifier => {
677
+ assertPrivateStore(this.store);
678
+ return this.store._instanceCache.recordIsLoaded(identifier, true) === true;
679
+ }) : false;
680
+ }
681
+
682
+ /**
683
+ `value()` synchronously returns the current value of the has-many
684
+ relationship. Unlike `record.relationshipName`, calling
685
+ `value()` on a reference does not trigger a fetch if the async
686
+ relationship is not yet loaded. If the relationship is not loaded
687
+ it will always return `null`.
688
+ Example
689
+ ```js [app/models/post.js]
690
+ import { Model, hasMany } from '@warp-drive/legacy/model';
691
+ export default class PostModel extends Model {
692
+ @hasMany('comment', { async: true, inverse: null }) comments;
693
+ }
694
+ ```
695
+ ```javascript
696
+ let post = store.push({
697
+ data: {
698
+ type: 'post',
699
+ id: 1,
700
+ relationships: {
701
+ comments: {
702
+ data: [{ type: 'comment', id: 1 }]
703
+ }
704
+ }
705
+ }
706
+ });
707
+ let commentsRef = post.hasMany('comments');
708
+ post.comments.then(function(comments) {
709
+ commentsRef.value() === comments
710
+ })
711
+ ```
712
+ @public
713
+ */
714
+ value() {
715
+ const support = LEGACY_SUPPORT.get(this.___identifier);
716
+ if (!ensureRefCanSubscribe(this)) {
717
+ // eslint-disable-next-line @typescript-eslint/no-unused-expressions
718
+ this._ref;
719
+ return null;
720
+ }
721
+ return support.getManyArray(this.key);
722
+ }
723
+
724
+ /**
725
+ Loads the relationship if it is not already loaded. If the
726
+ relationship is already loaded this method does not trigger a new
727
+ load. This causes a request to the specified
728
+ relationship link or reloads all items currently in the relationship.
729
+ Example
730
+ ```js [app/models/post.js]
731
+ import { Model, hasMany } from '@warp-drive/legacy/model';
732
+ export default class PostModel extends Model {
733
+ @hasMany('comment', { async: true, inverse: null }) comments;
734
+ }
735
+ ```
736
+ ```javascript
737
+ let post = store.push({
738
+ data: {
739
+ type: 'post',
740
+ id: 1,
741
+ relationships: {
742
+ comments: {
743
+ data: [{ type: 'comment', id: 1 }]
744
+ }
745
+ }
746
+ }
747
+ });
748
+ let commentsRef = post.hasMany('comments');
749
+ commentsRef.load().then(function(comments) {
750
+ //...
751
+ });
752
+ ```
753
+ You may also pass in an options object whose properties will be
754
+ fed forward. This enables you to pass `adapterOptions` into the
755
+ request given to the adapter via the reference.
756
+ Example
757
+ ```javascript
758
+ commentsRef.load({ adapterOptions: { isPrivate: true } })
759
+ .then(function(comments) {
760
+ //...
761
+ });
762
+ ```
763
+ ```js [app/adapters/comment.js]
764
+ export default ApplicationAdapter.extend({
765
+ findMany(store, type, id, snapshots) {
766
+ // In the adapter you will have access to adapterOptions.
767
+ let adapterOptions = snapshots[0].adapterOptions;
768
+ }
769
+ });
770
+ ```
771
+ @public
772
+ @param options the options to pass in.
773
+ @return a promise that resolves with the ManyArray in
774
+ this has-many relationship.
775
+ */
776
+ async load(options) {
777
+ const support = LEGACY_SUPPORT.get(this.___identifier);
778
+ const fetchSyncRel = !this.hasManyRelationship.definition.isAsync && !areAllInverseRecordsLoaded(this.store, this._resource());
779
+ return fetchSyncRel ? support.reloadHasMany(this.key, options) :
780
+ // we cast to fix the return type since typescript and eslint don't understand async functions
781
+ // properly
782
+ support.getHasMany(this.key, options);
783
+ }
784
+
785
+ /**
786
+ Reloads this has-many relationship. This causes a request to the specified
787
+ relationship link or reloads all items currently in the relationship.
788
+ Example
789
+ ```js [app/models/post.js]
790
+ import { Model, hasMany } from '@warp-drive/legacy/model';
791
+ export default class PostModel extends Model {
792
+ @hasMany('comment', { async: true, inverse: null }) comments;
793
+ }
794
+ ```
795
+ ```javascript
796
+ let post = store.push({
797
+ data: {
798
+ type: 'post',
799
+ id: 1,
800
+ relationships: {
801
+ comments: {
802
+ data: [{ type: 'comment', id: 1 }]
803
+ }
804
+ }
805
+ }
806
+ });
807
+ let commentsRef = post.hasMany('comments');
808
+ commentsRef.reload().then(function(comments) {
809
+ //...
810
+ });
811
+ ```
812
+ You may also pass in an options object whose properties will be
813
+ fed forward. This enables you to pass `adapterOptions` into the
814
+ request given to the adapter via the reference. A full example
815
+ can be found in the `load` method.
816
+ Example
817
+ ```javascript
818
+ commentsRef.reload({ adapterOptions: { isPrivate: true } })
819
+ ```
820
+ @public
821
+ @param options the options to pass in.
822
+ @return a promise that resolves with the ManyArray in this has-many relationship.
823
+ */
824
+ reload(options) {
825
+ const support = LEGACY_SUPPORT.get(this.___identifier);
826
+ return support.reloadHasMany(this.key, options);
827
+ }
828
+ }
829
+ defineNonEnumerableSignal(HasManyReference.prototype, '_ref', 0);
830
+ function isMaybeResource(object) {
831
+ const keys = Object.keys(object).filter(k => k !== 'id' && k !== 'type' && k !== 'lid');
832
+ return keys.length > 0;
833
+ }
834
+ function ensureRefCanSubscribe(rel) {
835
+ const loaded = rel._isLoaded();
836
+ if (!loaded) {
837
+ // subscribe to changes
838
+ // for when we are not loaded yet
839
+ //
840
+ // because the graph optimizes the case where a relationship has never been subscribed,
841
+ // we force accessed to be true here. When we make the graph public we should create a
842
+ // subscribe/unsubscribe API
843
+ const edge = rel.graph.get(rel.___identifier, rel.key);
844
+ edge.accessed = true;
845
+ return false;
846
+ }
847
+ return true;
848
+ }
849
+ function isResourceIdentiferWithRelatedLinks(value) {
850
+ return Boolean(value && value.links && value.links.related);
851
+ }
852
+
853
+ /**
854
+ A `BelongsToReference` is a low-level API that allows access
855
+ and manipulation of a belongsTo relationship.
856
+
857
+ It is especially useful when you're dealing with `async` relationships
858
+ from `@warp-drive/legacy/model` as it allows synchronous access to
859
+ the relationship data if loaded, as well as APIs for loading, reloading
860
+ the data or accessing available information without triggering a load.
861
+
862
+ It may also be useful when using `sync` relationships with `@warp-drive/legacy/model`
863
+ that need to be loaded/reloaded with more precise timing than marking the
864
+ relationship as `async` and relying on autofetch would have allowed.
865
+
866
+ However,keep in mind that marking a relationship as `async: false` will introduce
867
+ bugs into your application if the data is not always guaranteed to be available
868
+ by the time the relationship is accessed. Ergo, it is recommended when using this
869
+ approach to utilize `links` for unloaded relationship state instead of identifiers.
870
+
871
+ Reference APIs are entangled with the relationship's underlying state,
872
+ thus any getters or cached properties that utilize these will properly
873
+ invalidate if the relationship state changes.
874
+
875
+ References are "stable", meaning that multiple calls to retrieve the reference
876
+ for a given relationship will always return the same HasManyReference.
877
+
878
+ @public
879
+ */
880
+ class BelongsToReference {
881
+ /**
882
+ * The field name on the parent record for this has-many relationship.
883
+ *
884
+ */
885
+
886
+ /**
887
+ * The type of resource this relationship will contain.
888
+ *
889
+ */
890
+
891
+ // unsubscribe tokens given to us by the notification manager
892
+
893
+ constructor(store, graph, parentIdentifier, belongsToRelationship, key) {
894
+ this.graph = graph;
895
+ this.key = key;
896
+ this.belongsToRelationship = belongsToRelationship;
897
+ this.type = belongsToRelationship.definition.type;
898
+ this.store = store;
899
+ this.___identifier = parentIdentifier;
900
+ this.___relatedToken = null;
901
+ this.___token = store.notifications.subscribe(parentIdentifier, (_, bucket, notifiedKey) => {
902
+ if (bucket === 'relationships' && notifiedKey === key) {
903
+ this._ref++;
904
+ }
905
+ });
906
+
907
+ // TODO inverse
908
+ }
909
+ destroy() {
910
+ // TODO @feature we need the notification manager often enough
911
+ // we should potentially just expose it fully public
912
+ this.store.notifications.unsubscribe(this.___token);
913
+ this.___token = null;
914
+ if (this.___relatedToken) {
915
+ this.store.notifications.unsubscribe(this.___relatedToken);
916
+ this.___relatedToken = null;
917
+ }
918
+ }
919
+
920
+ /**
921
+ * The identifier of the record that this reference refers to.
922
+ * `null` if no related record is known.
923
+ *
924
+ */
925
+ get identifier() {
926
+ if (this.___relatedToken) {
927
+ this.store.notifications.unsubscribe(this.___relatedToken);
928
+ this.___relatedToken = null;
929
+ }
930
+ const resource = this._resource();
931
+ if (resource && resource.data) {
932
+ const identifier = this.store.cacheKeyManager.getOrCreateRecordIdentifier(resource.data);
933
+ this.___relatedToken = this.store.notifications.subscribe(identifier, (_, bucket, notifiedKey) => {
934
+ if (bucket === 'identity' || bucket === 'attributes' && notifiedKey === 'id') {
935
+ this._ref++;
936
+ }
937
+ });
938
+ return identifier;
939
+ }
940
+ return null;
941
+ }
942
+
943
+ /**
944
+ The `id` of the record that this reference refers to. Together, the
945
+ `type()` and `id()` methods form a composite key for the identity
946
+ map. This can be used to access the id of an async relationship
947
+ without triggering a fetch that would normally happen if you
948
+ attempted to use `record.relationship.id`.
949
+ Example
950
+ ```javascript
951
+ // models/blog.js
952
+ import { Model, belongsTo } from '@warp-drive/legacy/model';
953
+ export default class BlogModel extends Model {
954
+ @belongsTo('user', { async: true, inverse: null }) user;
955
+ }
956
+ let blog = store.push({
957
+ data: {
958
+ type: 'blog',
959
+ id: 1,
960
+ relationships: {
961
+ user: {
962
+ data: { type: 'user', id: 1 }
963
+ }
964
+ }
965
+ }
966
+ });
967
+ let userRef = blog.belongsTo('user');
968
+ // get the identifier of the reference
969
+ if (userRef.remoteType() === "id") {
970
+ let id = userRef.id();
971
+ }
972
+ ```
973
+ @public
974
+ @return The id of the record in this belongsTo relationship.
975
+ */
976
+ static {
977
+ decorateMethodV2(this.prototype, "identifier", [memoized]);
978
+ }
979
+ id() {
980
+ return this.identifier?.id || null;
981
+ }
982
+
983
+ /**
984
+ The link WarpDrive will use to fetch or reload this belongs-to
985
+ relationship. By default it uses only the "related" resource linkage.
986
+ Example
987
+ ```javascript
988
+ // models/blog.js
989
+ import { Model, belongsTo } from '@warp-drive/legacy/model';
990
+ export default Model.extend({
991
+ user: belongsTo('user', { async: true, inverse: null })
992
+ });
993
+ let blog = store.push({
994
+ data: {
995
+ type: 'blog',
996
+ id: 1,
997
+ relationships: {
998
+ user: {
999
+ links: {
1000
+ related: '/articles/1/author'
1001
+ }
1002
+ }
1003
+ }
1004
+ }
1005
+ });
1006
+ let userRef = blog.belongsTo('user');
1007
+ // get the identifier of the reference
1008
+ if (userRef.remoteType() === "link") {
1009
+ let link = userRef.link();
1010
+ }
1011
+ ```
1012
+ @public
1013
+ @return The link WarpDrive will use to fetch or reload this belongs-to relationship.
1014
+ */
1015
+ link() {
1016
+ const resource = this._resource();
1017
+ if (isResourceIdentiferWithRelatedLinks(resource)) {
1018
+ if (resource.links) {
1019
+ const related = resource.links.related;
1020
+ return !related || typeof related === 'string' ? related : related.href;
1021
+ }
1022
+ }
1023
+ return null;
1024
+ }
1025
+
1026
+ /**
1027
+ * any links that have been received for this relationship
1028
+ *
1029
+ * @public
1030
+ * @return
1031
+ */
1032
+ links() {
1033
+ const resource = this._resource();
1034
+ return resource && resource.links ? resource.links : null;
1035
+ }
1036
+
1037
+ /**
1038
+ The meta data for the belongs-to relationship.
1039
+ Example
1040
+ ```javascript
1041
+ // models/blog.js
1042
+ import { Model, belongsTo } from '@warp-drive/legacy/model';
1043
+ export default Model.extend({
1044
+ user: belongsTo('user', { async: true, inverse: null })
1045
+ });
1046
+ let blog = store.push({
1047
+ data: {
1048
+ type: 'blog',
1049
+ id: 1,
1050
+ relationships: {
1051
+ user: {
1052
+ links: {
1053
+ related: {
1054
+ href: '/articles/1/author'
1055
+ },
1056
+ },
1057
+ meta: {
1058
+ lastUpdated: 1458014400000
1059
+ }
1060
+ }
1061
+ }
1062
+ }
1063
+ });
1064
+ let userRef = blog.belongsTo('user');
1065
+ userRef.meta() // { lastUpdated: 1458014400000 }
1066
+ ```
1067
+ @public
1068
+ @return The meta information for the belongs-to relationship.
1069
+ */
1070
+ meta() {
1071
+ let meta = null;
1072
+ const resource = this._resource();
1073
+ if (resource && resource.meta && typeof resource.meta === 'object') {
1074
+ meta = resource.meta;
1075
+ }
1076
+ return meta;
1077
+ }
1078
+ _resource() {
1079
+ // eslint-disable-next-line @typescript-eslint/no-unused-expressions
1080
+ this._ref; // subscribe
1081
+ const cache = this.store.cache;
1082
+ return cache.getRelationship(this.___identifier, this.key);
1083
+ }
1084
+
1085
+ /**
1086
+ This returns a string that represents how the reference will be
1087
+ looked up when it is loaded. If the relationship has a link it will
1088
+ use the "link" otherwise it defaults to "id".
1089
+ Example
1090
+ ```js [app/models/post.js]
1091
+ import Model, { hasMany } from '@warp-drive/legacy/model';
1092
+ export default class PostModel extends Model {
1093
+ @hasMany('comment', { async: true, inverse: null }) comments;
1094
+ }
1095
+ ```
1096
+ ```javascript
1097
+ let post = store.push({
1098
+ data: {
1099
+ type: 'post',
1100
+ id: 1,
1101
+ relationships: {
1102
+ comments: {
1103
+ data: [{ type: 'comment', id: 1 }]
1104
+ }
1105
+ }
1106
+ }
1107
+ });
1108
+ let commentsRef = post.hasMany('comments');
1109
+ // get the identifier of the reference
1110
+ if (commentsRef.remoteType() === "ids") {
1111
+ let ids = commentsRef.ids();
1112
+ } else if (commentsRef.remoteType() === "link") {
1113
+ let link = commentsRef.link();
1114
+ }
1115
+ ```
1116
+ @public
1117
+ @return The name of the remote type. This should either be `link` or `id`
1118
+ */
1119
+ remoteType() {
1120
+ const value = this._resource();
1121
+ if (isResourceIdentiferWithRelatedLinks(value)) {
1122
+ return 'link';
1123
+ }
1124
+ return 'id';
1125
+ }
1126
+
1127
+ /**
1128
+ `push` can be used to update the data in the relationship and WarpDrive
1129
+ will treat the new data as the canonical value of this relationship on
1130
+ the backend. A value of `null` (e.g. `{ data: null }`) can be passed to
1131
+ clear the relationship.
1132
+ Example model
1133
+ ```js [app/models/blog.js]
1134
+ import { Model, belongsTo } from '@warp-drive/legacy/model';
1135
+ export default class BlogModel extends Model {
1136
+ @belongsTo('user', { async: true, inverse: null }) user;
1137
+ }
1138
+ ```
1139
+ Setup some initial state, note we haven't loaded the user yet:
1140
+ ```js
1141
+ const blog = store.push({
1142
+ data: {
1143
+ type: 'blog',
1144
+ id: '1',
1145
+ relationships: {
1146
+ user: {
1147
+ data: { type: 'user', id: '1' }
1148
+ }
1149
+ }
1150
+ }
1151
+ });
1152
+ const userRef = blog.belongsTo('user');
1153
+ userRef.id(); // '1'
1154
+ ```
1155
+ Update the state using `push`, note we can do this even without
1156
+ having loaded the user yet by providing a resource-identifier.
1157
+ Both full a resource and a resource-identifier are supported.
1158
+ ```js
1159
+ await userRef.push({
1160
+ data: {
1161
+ type: 'user',
1162
+ id: '2',
1163
+ }
1164
+ });
1165
+ userRef.id(); // '2'
1166
+ ```
1167
+ You may also pass in links and meta fore the relationship, and sideload
1168
+ additional resources that might be required.
1169
+ ```js
1170
+ await userRef.push({
1171
+ data: {
1172
+ type: 'user',
1173
+ id: '2',
1174
+ },
1175
+ links: {
1176
+ related: '/articles/1/author'
1177
+ },
1178
+ meta: {
1179
+ lastUpdated: Date.now()
1180
+ },
1181
+ included: [
1182
+ {
1183
+ type: 'user-preview',
1184
+ id: '2',
1185
+ attributes: {
1186
+ username: '@runspired'
1187
+ }
1188
+ }
1189
+ ]
1190
+ });
1191
+ ```
1192
+ By default, the store will attempt to fetch the record if it is not loaded or its
1193
+ resource data is not included in the call to `push` before resolving the returned
1194
+ promise with the new state..
1195
+ Alternatively, pass `true` as the second argument to avoid fetching unloaded records
1196
+ and instead the promise will resolve with void without attempting to fetch. This is
1197
+ particularly useful if you want to update the state of the relationship without
1198
+ forcing the load of all of the associated record.
1199
+ @public
1200
+ @param doc a JSONAPI document object describing the new value of this relationship.
1201
+ @param skipFetch [optional] if `true`, do not attempt to fetch unloaded records
1202
+ @return a promise that resolves with the record in this belongs-to relationship after the push has completed.
1203
+ */
1204
+ async push(doc, skipFetch) {
1205
+ const {
1206
+ store
1207
+ } = this;
1208
+ const isResourceData = doc.data && isMaybeResource(doc.data);
1209
+ const added = isResourceData ? store._push(doc, true) : doc.data ? store.cacheKeyManager.getOrCreateRecordIdentifier(doc.data) : null;
1210
+ const {
1211
+ identifier
1212
+ } = this.belongsToRelationship;
1213
+ const newData = {};
1214
+
1215
+ // only set data if it was passed in
1216
+ if (doc.data || doc.data === null) {
1217
+ newData.data = added;
1218
+ }
1219
+ if ('links' in doc) {
1220
+ newData.links = doc.links;
1221
+ }
1222
+ if ('meta' in doc) {
1223
+ newData.meta = doc.meta;
1224
+ }
1225
+ assertPrivateStore(store);
1226
+ store._join(() => {
1227
+ this.graph.push({
1228
+ op: 'updateRelationship',
1229
+ record: identifier,
1230
+ field: this.key,
1231
+ value: newData
1232
+ });
1233
+ });
1234
+ if (!skipFetch) return this.load();
1235
+ }
1236
+
1237
+ /**
1238
+ `value()` synchronously returns the current value of the belongs-to
1239
+ relationship. Unlike `record.relationshipName`, calling
1240
+ `value()` on a reference does not trigger a fetch if the async
1241
+ relationship is not yet loaded. If the relationship is not loaded
1242
+ it will always return `null`.
1243
+ Example
1244
+ ```javascript
1245
+ // models/blog.js
1246
+ import { Model, belongsTo } from '@warp-drive/legacy/model';
1247
+ export default class BlogModel extends Model {
1248
+ @belongsTo('user', { async: true, inverse: null }) user;
1249
+ }
1250
+ let blog = store.push({
1251
+ data: {
1252
+ type: 'blog',
1253
+ id: 1,
1254
+ relationships: {
1255
+ user: {
1256
+ data: { type: 'user', id: 1 }
1257
+ }
1258
+ }
1259
+ }
1260
+ });
1261
+ let userRef = blog.belongsTo('user');
1262
+ userRef.value(); // null
1263
+ // provide data for reference
1264
+ userRef.push({
1265
+ data: {
1266
+ type: 'user',
1267
+ id: 1,
1268
+ attributes: {
1269
+ username: "@user"
1270
+ }
1271
+ }
1272
+ }).then(function(user) {
1273
+ userRef.value(); // user
1274
+ });
1275
+ ```
1276
+ @public
1277
+ @return the record in this relationship
1278
+ */
1279
+ value() {
1280
+ const resource = this._resource();
1281
+ return resource && resource.data ? this.store.peekRecord(resource.data) : null;
1282
+ }
1283
+
1284
+ /**
1285
+ Loads a record in a belongs-to relationship if it is not already
1286
+ loaded. If the relationship is already loaded this method does not
1287
+ trigger a new load.
1288
+ Example
1289
+ ```javascript
1290
+ // models/blog.js
1291
+ import { Model, belongsTo } from '@warp-drive/legacy/model';
1292
+ export default class BlogModel extends Model {
1293
+ @belongsTo('user', { async: true, inverse: null }) user;
1294
+ }
1295
+ let blog = store.push({
1296
+ data: {
1297
+ type: 'blog',
1298
+ id: 1,
1299
+ relationships: {
1300
+ user: {
1301
+ data: { type: 'user', id: 1 }
1302
+ }
1303
+ }
1304
+ }
1305
+ });
1306
+ let userRef = blog.belongsTo('user');
1307
+ userRef.value(); // null
1308
+ userRef.load().then(function(user) {
1309
+ userRef.value() === user
1310
+ });
1311
+ ```
1312
+ You may also pass in an options object whose properties will be
1313
+ fed forward. This enables you to pass `adapterOptions` into the
1314
+ request given to the adapter via the reference.
1315
+ Example
1316
+ ```javascript
1317
+ userRef.load({ adapterOptions: { isPrivate: true } }).then(function(user) {
1318
+ userRef.value() === user;
1319
+ });
1320
+ ```
1321
+ ```js [app/adapters/user.js]
1322
+ import Adapter from '@warp-drive/legacy/adapter';
1323
+ export default class UserAdapter extends Adapter {
1324
+ findRecord(store, type, id, snapshot) {
1325
+ // In the adapter you will have access to adapterOptions.
1326
+ let adapterOptions = snapshot.adapterOptions;
1327
+ }
1328
+ });
1329
+ ```
1330
+ @public
1331
+ @param options the options to pass in.
1332
+ @return a promise that resolves with the record in this belongs-to relationship.
1333
+ */
1334
+ async load(options) {
1335
+ const support = LEGACY_SUPPORT.get(this.___identifier);
1336
+ const fetchSyncRel = !this.belongsToRelationship.definition.isAsync && !areAllInverseRecordsLoaded(this.store, this._resource());
1337
+ return fetchSyncRel ? support.reloadBelongsTo(this.key, options).then(() => this.value()) :
1338
+ // we cast to fix the return type since typescript and eslint don't understand async functions
1339
+ // properly
1340
+ support.getBelongsTo(this.key, options);
1341
+ }
1342
+
1343
+ /**
1344
+ Triggers a reload of the value in this relationship. If the
1345
+ remoteType is `"link"` WarpDrive will use the relationship link to
1346
+ reload the relationship. Otherwise it will reload the record by its
1347
+ id.
1348
+ Example
1349
+ ```javascript
1350
+ // models/blog.js
1351
+ import { Model, belongsTo } from '@warp-drive/legacy/model';
1352
+ export default class BlogModel extends Model {
1353
+ @belongsTo('user', { async: true, inverse: null }) user;
1354
+ }
1355
+ let blog = store.push({
1356
+ data: {
1357
+ type: 'blog',
1358
+ id: 1,
1359
+ relationships: {
1360
+ user: {
1361
+ data: { type: 'user', id: 1 }
1362
+ }
1363
+ }
1364
+ }
1365
+ });
1366
+ let userRef = blog.belongsTo('user');
1367
+ userRef.reload().then(function(user) {
1368
+ userRef.value() === user
1369
+ });
1370
+ ```
1371
+ You may also pass in an options object whose properties will be
1372
+ fed forward. This enables you to pass `adapterOptions` into the
1373
+ request given to the adapter via the reference. A full example
1374
+ can be found in the `load` method.
1375
+ Example
1376
+ ```javascript
1377
+ userRef.reload({ adapterOptions: { isPrivate: true } })
1378
+ ```
1379
+ @public
1380
+ @param options the options to pass in.
1381
+ @return a promise that resolves with the record in this belongs-to relationship after the reload has completed.
1382
+ */
1383
+ reload(options) {
1384
+ const support = LEGACY_SUPPORT.get(this.___identifier);
1385
+ return support.reloadBelongsTo(this.key, options).then(() => this.value());
1386
+ }
1387
+ }
1388
+ defineNonEnumerableSignal(BelongsToReference.prototype, '_ref', 0);
1389
+ const LEGACY_SUPPORT = getOrSetGlobal('LEGACY_SUPPORT', new Map());
1390
+ function lookupLegacySupport(record) {
1391
+ const identifier = recordIdentifierFor(record);
1392
+ let support = LEGACY_SUPPORT.get(identifier);
1393
+ if (!support) {
1394
+ support = new LegacySupport(record, identifier);
1395
+ LEGACY_SUPPORT.set(identifier, support);
1396
+ }
1397
+ return support;
1398
+ }
1399
+
1400
+ /**
1401
+ * @hideconstructor
1402
+ */
1403
+ class LegacySupport {
1404
+ /** @internal */
1405
+
1406
+ /** @internal */
1407
+
1408
+ /** @internal */
1409
+
1410
+ /** @internal */
1411
+
1412
+ /** @internal */
1413
+
1414
+ /** @internal */
1415
+
1416
+ /** @internal */
1417
+
1418
+ /** @internal */
1419
+
1420
+ /** @internal */
1421
+
1422
+ /** @internal */
1423
+
1424
+ /** @internal */
1425
+
1426
+ constructor(record, identifier) {
1427
+ this.record = record;
1428
+ this.store = isPrivateStore(storeFor(record, false));
1429
+ this.identifier = identifier;
1430
+ this.cache = this.store.cache;
1431
+ if (this.store._graph) {
1432
+ this.graph = this.store._graph;
1433
+ }
1434
+ this._manyArrayCache = Object.create(null);
1435
+ this._relationshipPromisesCache = Object.create(null);
1436
+ this._relationshipProxyCache = Object.create(null);
1437
+ this._pending = Object.create(null);
1438
+ this.references = Object.create(null);
1439
+ }
1440
+
1441
+ /** @private */
1442
+ _syncArray(array) {
1443
+ // It’s possible the parent side of the relationship may have been destroyed by this point
1444
+ if (this.isDestroyed || this.isDestroying) {
1445
+ return;
1446
+ }
1447
+ const currentState = array[Context].source;
1448
+ const identifier = this.identifier;
1449
+ const [identifiers, jsonApi] = this._getCurrentState(identifier, array.key);
1450
+ if (jsonApi.meta) {
1451
+ array.meta = jsonApi.meta;
1452
+ }
1453
+ if (jsonApi.links) {
1454
+ array.links = jsonApi.links;
1455
+ }
1456
+ currentState.length = 0;
1457
+ fastPush(currentState, identifiers);
1458
+ }
1459
+ mutate(mutation) {
1460
+ this.cache.mutate(mutation);
1461
+ }
1462
+ _findBelongsTo(key, resource, relationship, options) {
1463
+ const name = getRealFieldName(this, key);
1464
+
1465
+ // TODO @runspired follow up if parent isNew then we should not be attempting load here
1466
+ // TODO @runspired follow up on whether this should be in the relationship requests cache
1467
+ return this._findBelongsToByJsonApiResource(resource, this.identifier, relationship, options).then(identifier => handleCompletedRelationshipRequest(this, name, relationship, identifier), e => handleCompletedRelationshipRequest(this, name, relationship, null, e));
1468
+ }
1469
+ reloadBelongsTo(key, options) {
1470
+ const loadingPromise = this._relationshipPromisesCache[key];
1471
+ if (loadingPromise) {
1472
+ return loadingPromise;
1473
+ }
1474
+ const name = getRealFieldName(this, key);
1475
+ const resource = this.store.cache.getRelationship(this.identifier, name);
1476
+ const relationship = this.graph.get(this.identifier, name);
1477
+ relationship.state.hasFailedLoadAttempt = false;
1478
+ relationship.state.shouldForceReload = true;
1479
+ const promise = this._findBelongsTo(name, resource, relationship, options);
1480
+ if (this._relationshipProxyCache[name]) {
1481
+ // @ts-expect-error
1482
+ return this._updatePromiseProxyFor('belongsTo', name, {
1483
+ promise
1484
+ });
1485
+ }
1486
+ return promise;
1487
+ }
1488
+ getBelongsTo(key, options) {
1489
+ const {
1490
+ identifier
1491
+ } = this;
1492
+ const name = getRealFieldName(this, key);
1493
+ const resource = this.store.cache.getRelationship(this.identifier, name);
1494
+ const relatedIdentifier = resource && resource.data ? resource.data : null;
1495
+ const store = this.store;
1496
+ const relationship = this.graph.get(this.identifier, name);
1497
+ const isAsync = relationship.definition.isAsync;
1498
+ const _belongsToState = {
1499
+ key,
1500
+ store,
1501
+ legacySupport: this,
1502
+ modelName: relationship.definition.type
1503
+ };
1504
+ if (isAsync) {
1505
+ if (relationship.state.hasFailedLoadAttempt) {
1506
+ return this._relationshipProxyCache[name];
1507
+ }
1508
+ const promise = this._findBelongsTo(name, resource, relationship, options);
1509
+ const isLoaded = relatedIdentifier && store._instanceCache.recordIsLoaded(relatedIdentifier);
1510
+ return this._updatePromiseProxyFor('belongsTo', name, {
1511
+ promise,
1512
+ content: isLoaded ? store._instanceCache.getRecord(relatedIdentifier) : null,
1513
+ _belongsToState
1514
+ });
1515
+ } else {
1516
+ if (relatedIdentifier === null) {
1517
+ return null;
1518
+ } else {
1519
+ return store._instanceCache.getRecord(relatedIdentifier);
1520
+ }
1521
+ }
1522
+ }
1523
+ setDirtyBelongsTo(key, value) {
1524
+ const name = getRealFieldName(this, key);
1525
+ return this.cache.mutate({
1526
+ op: 'replaceRelatedRecord',
1527
+ record: this.identifier,
1528
+ field: name,
1529
+ value: extractIdentifierFromRecord(value)
1530
+ },
1531
+ // @ts-expect-error
1532
+ true);
1533
+ }
1534
+ _getCurrentState(identifier, field) {
1535
+ const jsonApi = this.cache.getRelationship(identifier, field);
1536
+ const cache = this.store._instanceCache;
1537
+ const identifiers = [];
1538
+ if (jsonApi.data) {
1539
+ for (let i = 0; i < jsonApi.data.length; i++) {
1540
+ const relatedIdentifier = jsonApi.data[i];
1541
+ if (cache.recordIsLoaded(relatedIdentifier, true)) {
1542
+ identifiers.push(relatedIdentifier);
1543
+ }
1544
+ }
1545
+ }
1546
+ return [identifiers, jsonApi];
1547
+ }
1548
+ getManyArray(key, definition) {
1549
+ const name = getRealFieldName(this, key);
1550
+ if (this.graph) {
1551
+ let manyArray = this._manyArrayCache[name];
1552
+ if (!definition) {
1553
+ definition = this.graph.get(this.identifier, name).definition;
1554
+ }
1555
+ if (!manyArray) {
1556
+ const [identifiers, doc] = this._getCurrentState(this.identifier, name);
1557
+ const field = getField(this, name);
1558
+ manyArray = createLegacyManyArray({
1559
+ store: this.store,
1560
+ // @ts-expect-error Typescript doesn't have a way for us to thread the generic backwards so it infers unknown instead of T
1561
+ manager: this,
1562
+ source: identifiers,
1563
+ type: definition.type,
1564
+ isLoaded: !definition.isAsync,
1565
+ editable: true,
1566
+ isAsync: definition.isAsync,
1567
+ isPolymorphic: definition.isPolymorphic,
1568
+ field: field,
1569
+ identifier: this.identifier,
1570
+ links: doc.links || null,
1571
+ meta: doc.meta || null
1572
+ });
1573
+ this._manyArrayCache[name] = manyArray;
1574
+ }
1575
+ return manyArray;
1576
+ }
1577
+ }
1578
+ fetchAsyncHasMany(key, relationship, manyArray, options) {
1579
+ const name = getRealFieldName(this, key);
1580
+ if (this.graph) {
1581
+ let loadingPromise = this._relationshipPromisesCache[name];
1582
+ if (loadingPromise) {
1583
+ return loadingPromise;
1584
+ }
1585
+ const jsonApi = this.cache.getRelationship(this.identifier, name);
1586
+ const promise = this._findHasManyByJsonApiResource(jsonApi, this.identifier, relationship, options);
1587
+ if (!promise) {
1588
+ manyArray.isLoaded = true;
1589
+ return Promise.resolve(manyArray);
1590
+ }
1591
+ loadingPromise = promise.then(() => handleCompletedRelationshipRequest(this, name, relationship, manyArray), e => handleCompletedRelationshipRequest(this, name, relationship, manyArray, e));
1592
+ this._relationshipPromisesCache[name] = loadingPromise;
1593
+ return loadingPromise;
1594
+ }
1595
+ }
1596
+ reloadHasMany(key, options) {
1597
+ const name = getRealFieldName(this, key);
1598
+ if (this.graph) {
1599
+ const loadingPromise = this._relationshipPromisesCache[name];
1600
+ if (loadingPromise) {
1601
+ return loadingPromise;
1602
+ }
1603
+ const relationship = this.graph.get(this.identifier, name);
1604
+ const {
1605
+ definition,
1606
+ state
1607
+ } = relationship;
1608
+ state.hasFailedLoadAttempt = false;
1609
+ state.shouldForceReload = true;
1610
+ const manyArray = this.getManyArray(name, definition);
1611
+ const promise = this.fetchAsyncHasMany(name, relationship, manyArray, options);
1612
+ if (this._relationshipProxyCache[name]) {
1613
+ return this._updatePromiseProxyFor('hasMany', name, {
1614
+ promise
1615
+ });
1616
+ }
1617
+ return promise;
1618
+ }
1619
+ }
1620
+ getHasMany(key, options) {
1621
+ const name = getRealFieldName(this, key);
1622
+ if (this.graph) {
1623
+ const relationship = this.graph.get(this.identifier, name);
1624
+ const {
1625
+ definition,
1626
+ state
1627
+ } = relationship;
1628
+ const manyArray = this.getManyArray(name, definition);
1629
+ if (definition.isAsync) {
1630
+ if (state.hasFailedLoadAttempt) {
1631
+ return this._relationshipProxyCache[name];
1632
+ }
1633
+ const promise = this.fetchAsyncHasMany(name, relationship, manyArray, options);
1634
+ return this._updatePromiseProxyFor('hasMany', name, {
1635
+ promise,
1636
+ content: manyArray
1637
+ });
1638
+ } else {
1639
+ return manyArray;
1640
+ }
1641
+ }
1642
+ }
1643
+ _updatePromiseProxyFor(kind, key, args) {
1644
+ let promiseProxy = this._relationshipProxyCache[key];
1645
+ if (kind === 'hasMany') {
1646
+ const {
1647
+ promise,
1648
+ content
1649
+ } = args;
1650
+ if (promiseProxy) {
1651
+ promiseProxy._update(promise, content);
1652
+ } else {
1653
+ promiseProxy = this._relationshipProxyCache[key] = new PromiseManyArray(promise, content);
1654
+ }
1655
+ return promiseProxy;
1656
+ }
1657
+ if (promiseProxy) {
1658
+ const {
1659
+ promise,
1660
+ content
1661
+ } = args;
1662
+ if (content !== undefined) {
1663
+ promiseProxy.set('content', content);
1664
+ }
1665
+ void promiseProxy.set('promise', promise);
1666
+ } else {
1667
+ promiseProxy = PromiseBelongsTo.create(args);
1668
+ this._relationshipProxyCache[key] = promiseProxy;
1669
+ }
1670
+ return promiseProxy;
1671
+ }
1672
+ referenceFor(kind, key) {
1673
+ const name = getRealFieldName(this, key);
1674
+ let reference = this.references[name];
1675
+ if (!reference) {
1676
+ if (!this.graph) ;
1677
+ const {
1678
+ graph,
1679
+ identifier
1680
+ } = this;
1681
+ const relationship = graph.get(identifier, name);
1682
+ const relationshipKind = relationship.definition.kind;
1683
+ if (relationshipKind === 'belongsTo') {
1684
+ reference = new BelongsToReference(this.store, graph, identifier, relationship, key);
1685
+ } else if (relationshipKind === 'hasMany') {
1686
+ reference = new HasManyReference(this.store, graph, identifier, relationship, key);
1687
+ }
1688
+ this.references[name] = reference;
1689
+ }
1690
+ return reference;
1691
+ }
1692
+ _findHasManyByJsonApiResource(resource, parentIdentifier, relationship, options = {}) {
1693
+ if (this.graph) {
1694
+ if (!resource) {
1695
+ return;
1696
+ }
1697
+ const {
1698
+ definition,
1699
+ state
1700
+ } = relationship;
1701
+ upgradeStore(this.store);
1702
+ const adapter = this.store.adapterFor?.(definition.type);
1703
+ const {
1704
+ isStale,
1705
+ hasDematerializedInverse,
1706
+ hasReceivedData,
1707
+ isEmpty,
1708
+ shouldForceReload
1709
+ } = state;
1710
+ const allInverseRecordsAreLoaded = areAllInverseRecordsLoaded(this.store, resource);
1711
+ const identifiers = resource.data;
1712
+ const shouldFindViaLink = resource.links && resource.links.related && (typeof adapter?.findHasMany === 'function' || typeof identifiers === 'undefined') && (shouldForceReload || hasDematerializedInverse || isStale || !allInverseRecordsAreLoaded && !isEmpty);
1713
+ const field = this.store.schema.fields({
1714
+ type: definition.inverseType
1715
+ }).get(definition.key);
1716
+ const request = {
1717
+ useLink: shouldFindViaLink,
1718
+ field,
1719
+ links: resource.links,
1720
+ meta: resource.meta,
1721
+ options,
1722
+ record: parentIdentifier
1723
+ };
1724
+
1725
+ // fetch via link
1726
+ if (shouldFindViaLink) {
1727
+ const req = field.options.linksMode ? {
1728
+ url: getRelatedLink(resource),
1729
+ op: 'findHasMany',
1730
+ method: 'GET',
1731
+ records: identifiers || [],
1732
+ data: request,
1733
+ [EnableHydration]: false
1734
+ } : {
1735
+ op: 'findHasMany',
1736
+ records: identifiers || [],
1737
+ data: request,
1738
+ cacheOptions: {
1739
+ [Symbol.for('wd:skip-cache')]: true
1740
+ }
1741
+ };
1742
+ return this.store.request(req);
1743
+ }
1744
+ const preferLocalCache = hasReceivedData && !isEmpty;
1745
+ const hasLocalPartialData = hasDematerializedInverse || isEmpty && Array.isArray(identifiers) && identifiers.length > 0;
1746
+ const attemptLocalCache = !shouldForceReload && !isStale && (preferLocalCache || hasLocalPartialData);
1747
+ if (attemptLocalCache && allInverseRecordsAreLoaded) {
1748
+ return;
1749
+ }
1750
+ const hasData = hasReceivedData && !isEmpty;
1751
+ if (attemptLocalCache || hasData || hasLocalPartialData) {
1752
+ options.reload = options.reload || !attemptLocalCache || undefined;
1753
+ return this.store.request({
1754
+ op: 'findHasMany',
1755
+ records: identifiers,
1756
+ data: request,
1757
+ cacheOptions: {
1758
+ [Symbol.for('wd:skip-cache')]: true
1759
+ }
1760
+ });
1761
+ }
1762
+
1763
+ // we were explicitly told we have no data and no links.
1764
+ // TODO if the relationshipIsStale, should we hit the adapter anyway?
1765
+ return;
1766
+ }
1767
+ }
1768
+ _findBelongsToByJsonApiResource(resource, parentIdentifier, relationship, options = {}) {
1769
+ if (!resource) {
1770
+ return Promise.resolve(null);
1771
+ }
1772
+ const key = relationship.definition.key;
1773
+ const name = getRealFieldName(this, key);
1774
+
1775
+ // interleaved promises mean that we MUST cache this here
1776
+ // in order to prevent infinite re-render if the request
1777
+ // fails.
1778
+ if (this._pending[name]) {
1779
+ return this._pending[name];
1780
+ }
1781
+ const identifier = resource.data ? resource.data : null;
1782
+ const {
1783
+ isStale,
1784
+ hasDematerializedInverse,
1785
+ hasReceivedData,
1786
+ isEmpty,
1787
+ shouldForceReload
1788
+ } = relationship.state;
1789
+ const allInverseRecordsAreLoaded = areAllInverseRecordsLoaded(this.store, resource);
1790
+ const shouldFindViaLink = resource.links?.related && (shouldForceReload || hasDematerializedInverse || isStale || !allInverseRecordsAreLoaded && !isEmpty);
1791
+ const field = this.store.schema.fields(this.identifier).get(relationship.definition.key);
1792
+ const request = {
1793
+ useLink: shouldFindViaLink,
1794
+ field,
1795
+ links: resource.links,
1796
+ meta: resource.meta,
1797
+ options,
1798
+ record: parentIdentifier
1799
+ };
1800
+
1801
+ // fetch via link
1802
+ if (shouldFindViaLink) {
1803
+ const req = field.options.linksMode ? {
1804
+ url: getRelatedLink(resource),
1805
+ op: 'findBelongsTo',
1806
+ method: 'GET',
1807
+ records: identifier ? [identifier] : [],
1808
+ data: request,
1809
+ [EnableHydration]: false
1810
+ } : {
1811
+ op: 'findBelongsTo',
1812
+ records: identifier ? [identifier] : [],
1813
+ data: request,
1814
+ cacheOptions: {
1815
+ [Symbol.for('wd:skip-cache')]: true
1816
+ }
1817
+ };
1818
+ const future = this.store.request(req);
1819
+ this._pending[name] = future.then(doc => field.options.linksMode ? doc.content.data : doc.content).finally(() => {
1820
+ this._pending[name] = undefined;
1821
+ });
1822
+ return this._pending[name];
1823
+ }
1824
+ const preferLocalCache = hasReceivedData && allInverseRecordsAreLoaded && !isEmpty;
1825
+ const hasLocalPartialData = hasDematerializedInverse || isEmpty && resource.data;
1826
+ // null is explicit empty, undefined is "we don't know anything"
1827
+ const localDataIsEmpty = !identifier;
1828
+ const attemptLocalCache = !shouldForceReload && !isStale && (preferLocalCache || hasLocalPartialData);
1829
+
1830
+ // we dont need to fetch and are empty
1831
+ if (attemptLocalCache && localDataIsEmpty) {
1832
+ return Promise.resolve(null);
1833
+ }
1834
+
1835
+ // we dont need to fetch because we are local state
1836
+ const resourceIsLocal = identifier?.id === null;
1837
+ if (attemptLocalCache && allInverseRecordsAreLoaded || resourceIsLocal) {
1838
+ return Promise.resolve(identifier);
1839
+ }
1840
+
1841
+ // we may need to fetch
1842
+ if (identifier) {
1843
+ options.reload = options.reload || !attemptLocalCache || undefined;
1844
+ this._pending[name] = this.store.request({
1845
+ op: 'findBelongsTo',
1846
+ records: [identifier],
1847
+ data: request,
1848
+ cacheOptions: {
1849
+ [Symbol.for('wd:skip-cache')]: true
1850
+ }
1851
+ }).then(doc => doc.content).finally(() => {
1852
+ this._pending[name] = undefined;
1853
+ });
1854
+ return this._pending[name];
1855
+ }
1856
+
1857
+ // we were explicitly told we have no data and no links.
1858
+ // TODO if the relationshipIsStale, should we hit the adapter anyway?
1859
+ return Promise.resolve(null);
1860
+ }
1861
+ destroy() {
1862
+ this.isDestroying = true;
1863
+ let cache = this._manyArrayCache;
1864
+ this._manyArrayCache = Object.create(null);
1865
+ Object.keys(cache).forEach(key => {
1866
+ cache[key].destroy();
1867
+ });
1868
+ cache = this._relationshipProxyCache;
1869
+ this._relationshipProxyCache = Object.create(null);
1870
+ Object.keys(cache).forEach(key => {
1871
+ const proxy = cache[key];
1872
+ if (proxy.destroy) {
1873
+ proxy.destroy();
1874
+ }
1875
+ });
1876
+ cache = this.references;
1877
+ this.references = Object.create(null);
1878
+ Object.keys(cache).forEach(key => {
1879
+ cache[key].destroy();
1880
+ });
1881
+ this.isDestroyed = true;
1882
+ }
1883
+ }
1884
+ function getRelatedLink(resource) {
1885
+ const related = resource.links?.related;
1886
+ return typeof related === 'object' ? related.href : related;
1887
+ }
1888
+ function handleCompletedRelationshipRequest(recordExt, key, relationship, value, error) {
1889
+ delete recordExt._relationshipPromisesCache[key];
1890
+ relationship.state.shouldForceReload = false;
1891
+ const isHasMany = relationship.definition.kind === 'hasMany';
1892
+ if (isHasMany) {
1893
+ // we don't notify the record property here to avoid refetch
1894
+ // only the many array
1895
+ notifyInternalSignal(value[Context].signal);
1896
+ }
1897
+ if (error) {
1898
+ relationship.state.hasFailedLoadAttempt = true;
1899
+ const proxy = recordExt._relationshipProxyCache[key];
1900
+ // belongsTo relationships are sometimes unloaded
1901
+ // when a load fails, in this case we need
1902
+ // to make sure that we aren't proxying
1903
+ // to destroyed content
1904
+ // for the sync belongsTo reload case there will be no proxy
1905
+ // for the async reload case there will be no proxy if the ui
1906
+ // has never been accessed
1907
+ if (proxy && !isHasMany) {
1908
+ // @ts-expect-error unsure why this is not resolving the boolean but async belongsTo is weird
1909
+ if (proxy.content && proxy.content.isDestroying) {
1910
+ proxy.set('content', null);
1911
+ }
1912
+ recordExt.store.notifications._flush();
1913
+ }
1914
+ throw error;
1915
+ }
1916
+ if (isHasMany) {
1917
+ value.isLoaded = true;
1918
+ } else {
1919
+ recordExt.store.notifications._flush();
1920
+ }
1921
+ relationship.state.hasFailedLoadAttempt = false;
1922
+ // only set to not stale if no error is thrown
1923
+ relationship.state.isStale = false;
1924
+ return isHasMany || !value ? value : recordExt.store.peekRecord(value);
1925
+ }
1926
+ function extractIdentifierFromRecord(record) {
1927
+ if (!record) {
1928
+ return null;
1929
+ }
1930
+ return recordIdentifierFor(record);
1931
+ }
1932
+ function areAllInverseRecordsLoaded(store, resource) {
1933
+ assertPrivateStore(store);
1934
+ const instanceCache = store._instanceCache;
1935
+ const identifiers = resource.data;
1936
+ if (Array.isArray(identifiers)) {
1937
+ // treat as collection
1938
+ // check for unloaded records
1939
+ return identifiers.every(identifier => instanceCache.recordIsLoaded(identifier));
1940
+ }
1941
+
1942
+ // treat as single resource
1943
+ if (!identifiers) return true;
1944
+ return instanceCache.recordIsLoaded(identifiers);
1945
+ }
1946
+ function getField(context, key) {
1947
+ const {
1948
+ identifier,
1949
+ store
1950
+ } = context;
1951
+ return store.schema.fields(identifier).get(key) ?? store.schema.cacheFields?.(identifier).get(key);
1952
+ }
1953
+ function getRealFieldName(context, key) {
1954
+ const field = getField(context, key);
1955
+ return field ? field.sourceKey ?? field.name : key;
1956
+ }
1957
+
1958
+ // we force the type here to our own construct because mixin and extend patterns
1959
+ // lose generic signatures. We also do this because we need to Omit `clear` from
1960
+ // the type of ArrayProxy as we override it's signature.
1961
+ const ArrayProxyWithCustomOverrides = ArrayProxy;
1962
+
1963
+ /**
1964
+ Holds validation errors for a given record, organized by attribute names.
1965
+
1966
+ This class is not directly instantiable.
1967
+
1968
+ Every `Model` has an `errors` property that is an instance of
1969
+ `Errors`. This can be used to display validation error
1970
+ messages returned from the server when a `record.save()` rejects.
1971
+
1972
+ For Example, if you had a `User` model that looked like this:
1973
+
1974
+ ```js [app/models/user.js]
1975
+ import { Model, attr } from '@warp-drive/legacy/model';
1976
+
1977
+ export default class UserModel extends Model {
1978
+ @attr('string') username;
1979
+ @attr('string') email;
1980
+ }
1981
+ ```
1982
+ And you attempted to save a record that did not validate on the backend:
1983
+
1984
+ ```javascript
1985
+ let user = store.createRecord('user', {
1986
+ username: 'tomster',
1987
+ email: 'invalidEmail'
1988
+ });
1989
+ user.save();
1990
+ ```
1991
+
1992
+ Your backend would be expected to return an error response that described
1993
+ the problem, so that error messages can be generated on the app.
1994
+
1995
+ API responses will be translated into instances of `Errors` differently,
1996
+ depending on the specific combination of adapter and serializer used. You
1997
+ may want to check the documentation or the source code of the libraries
1998
+ that you are using, to know how they expect errors to be communicated.
1999
+
2000
+ Errors can be displayed to the user by accessing their property name
2001
+ to get an array of all the error objects for that property. Each
2002
+ error object is a JavaScript object with two keys:
2003
+
2004
+ - `message` A string containing the error message from the backend
2005
+ - `attribute` The name of the property associated with this error message
2006
+
2007
+ ```handlebars
2008
+ <label>Username: <Input @value={{@model.username}} /> </label>
2009
+ {{#each @model.errors.username as |error|}}
2010
+ <div class="error">
2011
+ {{error.message}}
2012
+ </div>
2013
+ {{/each}}
2014
+
2015
+ <label>Email: <Input @value={{@model.email}} /> </label>
2016
+ {{#each @model.errors.email as |error|}}
2017
+ <div class="error">
2018
+ {{error.message}}
2019
+ </div>
2020
+ {{/each}}
2021
+ ```
2022
+
2023
+ You can also access the special `messages` property on the error
2024
+ object to get an array of all the error strings.
2025
+
2026
+ ```handlebars
2027
+ {{#each @model.errors.messages as |message|}}
2028
+ <div class="error">
2029
+ {{message}}
2030
+ </div>
2031
+ {{/each}}
2032
+ ```
2033
+
2034
+ @class Errors
2035
+ @public
2036
+ */
2037
+ class Errors extends ArrayProxyWithCustomOverrides {
2038
+ /**
2039
+ @property errorsByAttributeName
2040
+ @type {MapWithDefault}
2041
+ @private
2042
+ */
2043
+ get errorsByAttributeName() {
2044
+ return new Map();
2045
+ }
2046
+
2047
+ /**
2048
+ Returns errors for a given attribute
2049
+ ```javascript
2050
+ let user = store.createRecord('user', {
2051
+ username: 'tomster',
2052
+ email: 'invalidEmail'
2053
+ });
2054
+ user.save().catch(function(){
2055
+ user.errors.errorsFor('email'); // returns:
2056
+ // [{attribute: "email", message: "Doesn't look like a valid email."}]
2057
+ });
2058
+ ```
2059
+ @public
2060
+ @param {String} attribute
2061
+ @return {Array}
2062
+ */
2063
+ static {
2064
+ decorateMethodV2(this.prototype, "errorsByAttributeName", [computed()]);
2065
+ }
2066
+ errorsFor(attribute) {
2067
+ const map = this.errorsByAttributeName;
2068
+ let errors = map.get(attribute);
2069
+ if (errors === undefined) {
2070
+ errors = A();
2071
+ map.set(attribute, errors);
2072
+ }
2073
+
2074
+ // Errors may be a native array with extensions turned on. Since we access
2075
+ // the array via a method, and not a computed or using `Ember.get`, it does
2076
+ // not entangle properly with autotracking, so we entangle manually by
2077
+ // getting the `[]` property.
2078
+ get(errors, '[]');
2079
+ return errors;
2080
+ }
2081
+
2082
+ /**
2083
+ An array containing all of the error messages for this
2084
+ record. This is useful for displaying all errors to the user.
2085
+ ```handlebars
2086
+ {{#each @model.errors.messages as |message|}}
2087
+ <div class="error">
2088
+ {{message}}
2089
+ </div>
2090
+ {{/each}}
2091
+ ```
2092
+ @property messages
2093
+ @public
2094
+ @type {Array}
2095
+ */
2096
+ static {
2097
+ decorateFieldV2(this.prototype, "messages", [mapBy('content', 'message')]);
2098
+ }
2099
+ #messages = (initializeDeferredDecorator(this, "messages"), void 0);
2100
+ /**
2101
+ @property content
2102
+ @type {Array}
2103
+ @private
2104
+ */
2105
+ get content() {
2106
+ return A();
2107
+ }
2108
+
2109
+ /**
2110
+ @private
2111
+ */
2112
+ static {
2113
+ decorateMethodV2(this.prototype, "content", [computed()]);
2114
+ }
2115
+ unknownProperty(attribute) {
2116
+ const errors = this.errorsFor(attribute);
2117
+ if (errors.length === 0) {
2118
+ return undefined;
2119
+ }
2120
+ return errors;
2121
+ }
2122
+
2123
+ /**
2124
+ Total number of errors.
2125
+ @property length
2126
+ @type {Number}
2127
+ @public
2128
+ @readonly
2129
+ */
2130
+
2131
+ /**
2132
+ `true` if we have no errors.
2133
+ @property isEmpty
2134
+ @type {Boolean}
2135
+ @public
2136
+ @readonly
2137
+ */
2138
+ static {
2139
+ decorateFieldV2(this.prototype, "isEmpty", [not('length')]);
2140
+ }
2141
+ #isEmpty = (initializeDeferredDecorator(this, "isEmpty"), void 0);
2142
+ /**
2143
+ Manually adds errors to the record. This will trigger the `becameInvalid` event/ lifecycle method on
2144
+ the record and transition the record into an `invalid` state.
2145
+ Example
2146
+ ```javascript
2147
+ let errors = user.errors;
2148
+ // add multiple errors
2149
+ errors.add('password', [
2150
+ 'Must be at least 12 characters',
2151
+ 'Must contain at least one symbol',
2152
+ 'Cannot contain your name'
2153
+ ]);
2154
+ errors.errorsFor('password');
2155
+ // =>
2156
+ // [
2157
+ // { attribute: 'password', message: 'Must be at least 12 characters' },
2158
+ // { attribute: 'password', message: 'Must contain at least one symbol' },
2159
+ // { attribute: 'password', message: 'Cannot contain your name' },
2160
+ // ]
2161
+ // add a single error
2162
+ errors.add('username', 'This field is required');
2163
+ errors.errorsFor('username');
2164
+ // =>
2165
+ // [
2166
+ // { attribute: 'username', message: 'This field is required' },
2167
+ // ]
2168
+ ```
2169
+ @public
2170
+ @param {String} attribute - the property name of an attribute or relationship
2171
+ @param {string[]|string} messages - an error message or array of error messages for the attribute
2172
+ */
2173
+ add(attribute, messages) {
2174
+ const errors = this._findOrCreateMessages(attribute, messages);
2175
+ this.addObjects(errors);
2176
+ this.errorsFor(attribute).addObjects(errors);
2177
+ this.__record.currentState.notify('isValid');
2178
+ this.notifyPropertyChange(attribute);
2179
+ }
2180
+
2181
+ /**
2182
+ @private
2183
+ */
2184
+ _findOrCreateMessages(attribute, messages) {
2185
+ const errors = this.errorsFor(attribute);
2186
+ const messagesArray = Array.isArray(messages) ? messages : [messages];
2187
+ const _messages = new Array(messagesArray.length);
2188
+ for (let i = 0; i < messagesArray.length; i++) {
2189
+ const message = messagesArray[i];
2190
+ const err = errors.findBy('message', message);
2191
+ if (err) {
2192
+ _messages[i] = err;
2193
+ } else {
2194
+ _messages[i] = {
2195
+ attribute: attribute,
2196
+ message
2197
+ };
2198
+ }
2199
+ }
2200
+ return _messages;
2201
+ }
2202
+
2203
+ /**
2204
+ Manually removes all errors for a given member from the record.
2205
+ This will transition the record into a `valid` state, and
2206
+ triggers the `becameValid` event and lifecycle method.
2207
+ Example:
2208
+ ```javascript
2209
+ let errors = user.errors;
2210
+ errors.add('phone', ['error-1', 'error-2']);
2211
+ errors.errorsFor('phone');
2212
+ // =>
2213
+ // [
2214
+ // { attribute: 'phone', message: 'error-1' },
2215
+ // { attribute: 'phone', message: 'error-2' },
2216
+ // ]
2217
+ errors.remove('phone');
2218
+ errors.errorsFor('phone');
2219
+ // => undefined
2220
+ ```
2221
+ @public
2222
+ @param {String} member - the property name of an attribute or relationship
2223
+ */
2224
+ remove(attribute) {
2225
+ if (this.isEmpty) {
2226
+ return;
2227
+ }
2228
+ const content = this.rejectBy('attribute', attribute);
2229
+ this.content.setObjects(content);
2230
+
2231
+ // Although errorsByAttributeName.delete is technically enough to sync errors state, we also
2232
+ // must mutate the array as well for autotracking
2233
+ const errors = this.errorsFor(attribute);
2234
+ for (let i = 0; i < errors.length; i++) {
2235
+ if (errors[i].attribute === attribute) {
2236
+ // .replace from Ember.NativeArray is necessary. JS splice will not work.
2237
+ errors.replace(i, 1);
2238
+ }
2239
+ }
2240
+ this.errorsByAttributeName.delete(attribute);
2241
+ this.__record.currentState.notify('isValid');
2242
+ this.notifyPropertyChange(attribute);
2243
+ this.notifyPropertyChange('length');
2244
+ }
2245
+
2246
+ /**
2247
+ Manually clears all errors for the record.
2248
+ This will transition the record into a `valid` state, and
2249
+ will trigger the `becameValid` event and lifecycle method.
2250
+ Example:
2251
+ ```javascript
2252
+ let errors = user.errors;
2253
+ errors.add('username', ['error-a']);
2254
+ errors.add('phone', ['error-1', 'error-2']);
2255
+ errors.errorsFor('username');
2256
+ // =>
2257
+ // [
2258
+ // { attribute: 'username', message: 'error-a' },
2259
+ // ]
2260
+ errors.errorsFor('phone');
2261
+ // =>
2262
+ // [
2263
+ // { attribute: 'phone', message: 'error-1' },
2264
+ // { attribute: 'phone', message: 'error-2' },
2265
+ // ]
2266
+ errors.clear();
2267
+ errors.errorsFor('username');
2268
+ // => undefined
2269
+ errors.errorsFor('phone');
2270
+ // => undefined
2271
+ errors.messages
2272
+ // => []
2273
+ ```
2274
+ @public
2275
+ */
2276
+ clear() {
2277
+ if (this.isEmpty) {
2278
+ return;
2279
+ }
2280
+ const errorsByAttributeName = this.errorsByAttributeName;
2281
+ const attributes = [];
2282
+ errorsByAttributeName.forEach(function (_, attribute) {
2283
+ attributes.push(attribute);
2284
+ });
2285
+ errorsByAttributeName.clear();
2286
+ attributes.forEach(attribute => {
2287
+ this.notifyPropertyChange(attribute);
2288
+ });
2289
+ this.__record.currentState.notify('isValid');
2290
+ super.clear();
2291
+ }
2292
+
2293
+ /**
2294
+ Checks if there are error messages for the given attribute.
2295
+ ```js [app/controllers/user/edit.js]
2296
+ export default class UserEditController extends Controller {
2297
+ @action
2298
+ save(user) {
2299
+ if (user.errors.has('email')) {
2300
+ return alert('Please update your email before attempting to save.');
2301
+ }
2302
+ user.save();
2303
+ }
2304
+ }
2305
+ ```
2306
+ @public
2307
+ @param {String} attribute
2308
+ @return {Boolean} true if there some errors on given attribute
2309
+ */
2310
+ has(attribute) {
2311
+ return this.errorsFor(attribute).length > 0;
2312
+ }
2313
+ }
2314
+ export { Errors as E, LEGACY_SUPPORT as L, PromiseBelongsTo as P, PromiseManyArray as a, lookupLegacySupport as l };