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