@warp-drive/legacy 5.8.0-alpha.4 → 5.8.0-alpha.40

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