@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,1947 @@
1
+ import { getOwner } from '@ember/application';
2
+ import EmberObject from '@ember/object';
3
+ import { recordIdentifierFor, storeFor } from '@warp-drive/core';
4
+ import { assertPrivateStore, notifyInternalSignal, peekInternalSignal, withSignalStore, recordIdentifierFor as recordIdentifierFor$1, gate, memoized, defineSignal, coerceId, entangleSignal, defineGate } from '@warp-drive/core/store/-private';
5
+ import { RecordStore } from '@warp-drive/core/types/symbols';
6
+ import { l as lookupLegacySupport, L as LEGACY_SUPPORT, E as Errors } from "./errors-CG1SPYVg.js";
7
+ import { u as upgradeStore, F as FetchManager } from "./-private-Cvf_97EG.js";
8
+ import { cacheFor } from '@ember/object/internals';
9
+ import { Context } from '@warp-drive/core/reactive/-private';
10
+ import { d as decorateMethodV2 } from "./runtime-BPCpkOf1-BKOwiRJp.js";
11
+ import { n as normalizeModelName } from "./util-B6cn-i93.js";
12
+ function rollbackAttributes() {
13
+ const {
14
+ currentState
15
+ } = this;
16
+ const {
17
+ isNew
18
+ } = currentState;
19
+ const store = this[RecordStore];
20
+ assertPrivateStore(store);
21
+ store._join(() => {
22
+ store.cache.rollbackAttrs(recordIdentifierFor(this));
23
+ this.errors.clear();
24
+ currentState.cleanErrorRequests();
25
+ if (isNew) {
26
+ this.unloadRecord();
27
+ }
28
+ });
29
+ }
30
+ function unloadRecord() {
31
+ if (this.currentState.isNew && (this.isDestroyed || this.isDestroying)) {
32
+ return;
33
+ }
34
+ this[RecordStore].unloadRecord(this);
35
+ }
36
+ function belongsTo(prop) {
37
+ return lookupLegacySupport(this).referenceFor('belongsTo', prop);
38
+ }
39
+ function hasMany(prop) {
40
+ return lookupLegacySupport(this).referenceFor('hasMany', prop);
41
+ }
42
+ function reload(options = {}) {
43
+ {
44
+ return _reload.call(this, options);
45
+ }
46
+ }
47
+ function _reload(options = {}) {
48
+ options.isReloading = true;
49
+ options.reload = true;
50
+ const identifier = recordIdentifierFor(this);
51
+ this.isReloading = true;
52
+ const promise = this[RecordStore].request({
53
+ op: 'findRecord',
54
+ data: {
55
+ options,
56
+ record: identifier
57
+ },
58
+ cacheOptions: {
59
+ [Symbol.for('wd:skip-cache')]: true
60
+ }
61
+ }).then(() => this).finally(() => {
62
+ this.isReloading = false;
63
+ });
64
+ return promise;
65
+ }
66
+ function changedAttributes() {
67
+ return this[RecordStore].cache.changedAttrs(recordIdentifierFor(this));
68
+ }
69
+ function serialize(options) {
70
+ upgradeStore(this[RecordStore]);
71
+ return this[RecordStore].serializeRecord(this, options);
72
+ }
73
+ function deleteRecord() {
74
+ // ensure we've populated currentState prior to deleting a new record
75
+ if (this.currentState) {
76
+ this[RecordStore].deleteRecord(this);
77
+ }
78
+ }
79
+ function save(options) {
80
+ {
81
+ return _save.call(this, options);
82
+ }
83
+ }
84
+ function _save(options) {
85
+ let promise;
86
+ if (this.currentState.isNew && this.currentState.isDeleted) {
87
+ promise = Promise.resolve(this);
88
+ } else {
89
+ this.errors.clear();
90
+ promise = this[RecordStore].saveRecord(this, options);
91
+ }
92
+ return promise;
93
+ }
94
+ function destroyRecord(options) {
95
+ {
96
+ return _destroyRecord.call(this, options);
97
+ }
98
+ }
99
+ function _destroyRecord(options) {
100
+ const {
101
+ isNew
102
+ } = this.currentState;
103
+ this.deleteRecord();
104
+ if (isNew) {
105
+ return Promise.resolve(this);
106
+ }
107
+ return this.save(options).then(_ => {
108
+ this.unloadRecord();
109
+ return this;
110
+ });
111
+ }
112
+ function createSnapshot() {
113
+ const store = this[RecordStore];
114
+ if (!store._fetchManager) {
115
+ store._fetchManager = new FetchManager(store);
116
+ }
117
+
118
+ // @ts-expect-error Typescript isn't able to curry narrowed args that are divorced from each other.
119
+ return store._fetchManager.createSnapshot(recordIdentifierFor(this));
120
+ }
121
+ function notifyChanges(identifier, value, key, record, store) {
122
+ switch (value) {
123
+ case 'added':
124
+ case 'attributes':
125
+ if (key) {
126
+ notifyAttribute(store, identifier, key, record);
127
+ } else {
128
+ record.eachAttribute(name => {
129
+ notifyAttribute(store, identifier, name, record);
130
+ });
131
+ }
132
+ break;
133
+ case 'relationships':
134
+ if (key) {
135
+ const meta = record.constructor.relationshipsByName.get(key);
136
+ notifyRelationship(identifier, key, record, meta);
137
+ } else {
138
+ record.eachRelationship((name, meta) => {
139
+ notifyRelationship(identifier, name, record, meta);
140
+ });
141
+ }
142
+ break;
143
+ case 'identity':
144
+ notifyInternalSignal(peekInternalSignal(withSignalStore(record), 'id'));
145
+ break;
146
+ }
147
+ }
148
+ function notifyRelationship(identifier, key, record, meta) {
149
+ if (meta.kind === 'belongsTo') {
150
+ record.notifyPropertyChange(key);
151
+ } else if (meta.kind === 'hasMany') {
152
+ const support = LEGACY_SUPPORT.get(identifier);
153
+ const manyArray = support && support._manyArrayCache[key];
154
+ const hasPromise = support && support._relationshipPromisesCache[key];
155
+ if (manyArray && hasPromise) {
156
+ // do nothing, we will notify the ManyArray directly
157
+ // once the fetch has completed.
158
+ return;
159
+ }
160
+ if (manyArray) {
161
+ notifyInternalSignal(manyArray[Context].signal);
162
+ if (meta.options.async) {
163
+ record.notifyPropertyChange(key);
164
+ }
165
+ }
166
+ }
167
+ }
168
+ function notifyAttribute(store, identifier, key, record) {
169
+ const currentValue = cacheFor(record, key);
170
+ const cache = store.cache;
171
+ if (currentValue !== cache.getAttr(identifier, key)) {
172
+ record.notifyPropertyChange(key);
173
+ }
174
+ }
175
+ const SOURCE_POINTER_REGEXP = /^\/?data\/(attributes|relationships)\/(.*)/;
176
+ const SOURCE_POINTER_PRIMARY_REGEXP = /^\/?data/;
177
+ const PRIMARY_ATTRIBUTE_KEY = 'base';
178
+ function isInvalidError(error) {
179
+ return !!error && error instanceof Error && 'isAdapterError' in error && error.isAdapterError === true && 'code' in error && error.code === 'InvalidError';
180
+ }
181
+
182
+ /**
183
+ Historically WarpDrive managed a state machine
184
+ for each record, the localState for which
185
+ was reflected onto Model.
186
+
187
+ This implements the flags and stateName for backwards compat
188
+ with the state tree that used to be possible (listed below).
189
+
190
+ stateName and dirtyType are candidates for deprecation.
191
+
192
+ root
193
+ empty
194
+ deleted // hidden from stateName
195
+ preloaded // hidden from stateName
196
+
197
+ loading
198
+ empty // hidden from stateName
199
+ preloaded // hidden from stateName
200
+
201
+ loaded
202
+ saved
203
+ updated
204
+ uncommitted
205
+ invalid
206
+ inFlight
207
+ created
208
+ uncommitted
209
+ invalid
210
+ inFlight
211
+
212
+ deleted
213
+ saved
214
+ new // hidden from stateName
215
+ uncommitted
216
+ invalid
217
+ inFlight
218
+
219
+ @hideconstructor
220
+ @private
221
+ */
222
+ class RecordState {
223
+ /** @internal */
224
+
225
+ /** @internal */
226
+
227
+ /** @internal */
228
+
229
+ /** @internal */
230
+
231
+ /** @internal */
232
+
233
+ /** @internal */
234
+
235
+ /** @internal */
236
+
237
+ /** @internal */
238
+
239
+ /** @internal */
240
+
241
+ /** @internal */
242
+
243
+ /** @internal */
244
+
245
+ constructor(record) {
246
+ const store = storeFor(record, false);
247
+ const identity = recordIdentifierFor$1(record);
248
+ this.identifier = identity;
249
+ this.record = record;
250
+ this.cache = store.cache;
251
+ this.pendingCount = 0;
252
+ this.fulfilledCount = 0;
253
+ this.rejectedCount = 0;
254
+ this._errorRequests = [];
255
+ this._lastError = null;
256
+ const requests = store.getRequestStateService();
257
+ const notifications = store.notifications;
258
+ const handleRequest = req => {
259
+ if (req.type === 'mutation') {
260
+ switch (req.state) {
261
+ case 'pending':
262
+ this.isSaving = true;
263
+ break;
264
+ case 'rejected':
265
+ this.isSaving = false;
266
+ this._lastError = req;
267
+ if (!(req.response && isInvalidError(req.response.data))) {
268
+ this._errorRequests.push(req);
269
+ }
270
+ notifyErrorsStateChanged(this);
271
+ break;
272
+ case 'fulfilled':
273
+ this._errorRequests = [];
274
+ this._lastError = null;
275
+ this.isSaving = false;
276
+ this.notify('isDirty');
277
+ notifyErrorsStateChanged(this);
278
+ break;
279
+ }
280
+ } else {
281
+ switch (req.state) {
282
+ case 'pending':
283
+ this.pendingCount++;
284
+ this.notify('isLoading');
285
+ break;
286
+ case 'rejected':
287
+ this.pendingCount--;
288
+ this._lastError = req;
289
+ if (!(req.response && isInvalidError(req.response.data))) {
290
+ this._errorRequests.push(req);
291
+ }
292
+ this.notify('isLoading');
293
+ notifyErrorsStateChanged(this);
294
+ break;
295
+ case 'fulfilled':
296
+ this.pendingCount--;
297
+ this.fulfilledCount++;
298
+ this.notify('isLoading');
299
+ this.notify('isDirty');
300
+ notifyErrorsStateChanged(this);
301
+ this._errorRequests = [];
302
+ this._lastError = null;
303
+ break;
304
+ }
305
+ }
306
+ };
307
+ requests.subscribeForRecord(identity, handleRequest);
308
+
309
+ // we instantiate lazily
310
+ // so we grab anything we don't have yet
311
+ const lastRequest = requests.getLastRequestForRecord(identity);
312
+ if (lastRequest) {
313
+ handleRequest(lastRequest);
314
+ }
315
+ this.handler = notifications.subscribe(identity, (identifier, type, key) => {
316
+ switch (type) {
317
+ case 'state':
318
+ this.notify('isSaved');
319
+ this.notify('isNew');
320
+ this.notify('isDeleted');
321
+ this.notify('isDirty');
322
+ break;
323
+ case 'attributes':
324
+ this.notify('isEmpty');
325
+ this.notify('isDirty');
326
+ break;
327
+ case 'errors':
328
+ this.updateInvalidErrors(this.record.errors);
329
+ this.notify('isValid');
330
+ break;
331
+ }
332
+ });
333
+ }
334
+
335
+ /** @internal */
336
+ destroy() {
337
+ storeFor(this.record, false).notifications.unsubscribe(this.handler);
338
+ }
339
+
340
+ /** @internal */
341
+ notify(key) {
342
+ const signals = withSignalStore(this);
343
+ const signal = peekInternalSignal(signals, key);
344
+ if (signal) {
345
+ notifyInternalSignal(signal);
346
+ }
347
+ }
348
+
349
+ /** @internal */
350
+ updateInvalidErrors(errors) {
351
+ const jsonApiErrors = this.cache.getErrors(this.identifier);
352
+ errors.clear();
353
+ for (let i = 0; i < jsonApiErrors.length; i++) {
354
+ const error = jsonApiErrors[i];
355
+ if (error.source && error.source.pointer) {
356
+ const keyMatch = error.source.pointer.match(SOURCE_POINTER_REGEXP);
357
+ let key;
358
+ if (keyMatch) {
359
+ key = keyMatch[2];
360
+ } else if (error.source.pointer.search(SOURCE_POINTER_PRIMARY_REGEXP) !== -1) {
361
+ key = PRIMARY_ATTRIBUTE_KEY;
362
+ }
363
+ if (key) {
364
+ const errMsg = error.detail || error.title;
365
+ errors.add(key, errMsg);
366
+ }
367
+ }
368
+ }
369
+ }
370
+
371
+ /** @internal */
372
+ cleanErrorRequests() {
373
+ this.notify('isValid');
374
+ this.notify('isError');
375
+ this.notify('adapterError');
376
+ this._errorRequests = [];
377
+ this._lastError = null;
378
+ }
379
+ get isLoading() {
380
+ return !this.isLoaded && this.pendingCount > 0 && this.fulfilledCount === 0;
381
+ }
382
+ static {
383
+ decorateMethodV2(this.prototype, "isLoading", [gate]);
384
+ }
385
+ get isLoaded() {
386
+ if (this.isNew) {
387
+ return true;
388
+ }
389
+ return this.fulfilledCount > 0 || !this.isEmpty;
390
+ }
391
+ static {
392
+ decorateMethodV2(this.prototype, "isLoaded", [gate]);
393
+ }
394
+ get isSaved() {
395
+ const rd = this.cache;
396
+ if (this.isDeleted) {
397
+ return rd.isDeletionCommitted(this.identifier);
398
+ }
399
+ if (this.isNew || this.isEmpty || !this.isValid || this.isDirty || this.isLoading) {
400
+ return false;
401
+ }
402
+ return true;
403
+ }
404
+ static {
405
+ decorateMethodV2(this.prototype, "isSaved", [gate]);
406
+ }
407
+ get isEmpty() {
408
+ const rd = this.cache;
409
+ return !this.isNew && rd.isEmpty(this.identifier);
410
+ }
411
+ static {
412
+ decorateMethodV2(this.prototype, "isEmpty", [gate]);
413
+ }
414
+ get isNew() {
415
+ const rd = this.cache;
416
+ return rd.isNew(this.identifier);
417
+ }
418
+ static {
419
+ decorateMethodV2(this.prototype, "isNew", [gate]);
420
+ }
421
+ get isDeleted() {
422
+ const rd = this.cache;
423
+ return rd.isDeleted(this.identifier);
424
+ }
425
+ static {
426
+ decorateMethodV2(this.prototype, "isDeleted", [gate]);
427
+ }
428
+ get isValid() {
429
+ return this.record.errors.length === 0;
430
+ }
431
+ static {
432
+ decorateMethodV2(this.prototype, "isValid", [gate]);
433
+ }
434
+ get isDirty() {
435
+ const rd = this.cache;
436
+ if (this.isEmpty || rd.isDeletionCommitted(this.identifier) || this.isDeleted && this.isNew) {
437
+ return false;
438
+ }
439
+ return this.isDeleted || this.isNew || rd.hasChangedAttrs(this.identifier);
440
+ }
441
+ static {
442
+ decorateMethodV2(this.prototype, "isDirty", [gate]);
443
+ }
444
+ get isError() {
445
+ const errorReq = this._errorRequests[this._errorRequests.length - 1];
446
+ if (!errorReq) {
447
+ return false;
448
+ } else {
449
+ return true;
450
+ }
451
+ }
452
+ static {
453
+ decorateMethodV2(this.prototype, "isError", [gate]);
454
+ }
455
+ get adapterError() {
456
+ const request = this._lastError;
457
+ if (!request) {
458
+ return null;
459
+ }
460
+ return request.state === 'rejected' && request.response.data;
461
+ }
462
+ static {
463
+ decorateMethodV2(this.prototype, "adapterError", [gate]);
464
+ }
465
+ get isPreloaded() {
466
+ return !this.isEmpty && this.isLoading;
467
+ }
468
+ static {
469
+ decorateMethodV2(this.prototype, "isPreloaded", [memoized]);
470
+ }
471
+ get stateName() {
472
+ // we might be empty while loading so check this first
473
+ if (this.isLoading) {
474
+ return 'root.loading';
475
+
476
+ // got nothing yet or were unloaded
477
+ } else if (this.isEmpty) {
478
+ return 'root.empty';
479
+
480
+ // deleted substates
481
+ } else if (this.isDeleted) {
482
+ if (this.isSaving) {
483
+ return 'root.deleted.inFlight';
484
+ } else if (this.isSaved) {
485
+ // TODO ensure isSaved isn't true from previous requests
486
+ return 'root.deleted.saved';
487
+ } else if (!this.isValid) {
488
+ return 'root.deleted.invalid';
489
+ } else {
490
+ return 'root.deleted.uncommitted';
491
+ }
492
+
493
+ // loaded.created substates
494
+ } else if (this.isNew) {
495
+ if (this.isSaving) {
496
+ return 'root.loaded.created.inFlight';
497
+ } else if (!this.isValid) {
498
+ return 'root.loaded.created.invalid';
499
+ }
500
+ return 'root.loaded.created.uncommitted';
501
+
502
+ // loaded.updated substates
503
+ } else if (this.isSaving) {
504
+ return 'root.loaded.updated.inFlight';
505
+ } else if (!this.isValid) {
506
+ return 'root.loaded.updated.invalid';
507
+ } else if (this.isDirty) {
508
+ return 'root.loaded.updated.uncommitted';
509
+
510
+ // if nothing remains, we are loaded saved!
511
+ } else {
512
+ return 'root.loaded.saved';
513
+ }
514
+ }
515
+ static {
516
+ decorateMethodV2(this.prototype, "stateName", [memoized]);
517
+ }
518
+ get dirtyType() {
519
+ // we might be empty while loading so check this first
520
+ if (this.isLoading || this.isEmpty) {
521
+ return '';
522
+
523
+ // deleted substates
524
+ } else if (this.isDirty && this.isDeleted) {
525
+ return 'deleted';
526
+
527
+ // loaded.created substates
528
+ } else if (this.isNew) {
529
+ return 'created';
530
+
531
+ // loaded.updated substates
532
+ } else if (this.isSaving || !this.isValid || this.isDirty) {
533
+ return 'updated';
534
+
535
+ // if nothing remains, we are loaded saved!
536
+ } else {
537
+ return '';
538
+ }
539
+ }
540
+ static {
541
+ decorateMethodV2(this.prototype, "dirtyType", [memoized]);
542
+ }
543
+ }
544
+ defineSignal(RecordState.prototype, 'isSaving', false);
545
+ function notifyErrorsStateChanged(state) {
546
+ state.notify('isValid');
547
+ state.notify('isError');
548
+ state.notify('adapterError');
549
+ }
550
+
551
+ /*
552
+ * This decorator allows us to lazily compute
553
+ * an expensive getter on first-access and thereafter
554
+ * never recompute it.
555
+ */
556
+ function computeOnce(target, propertyName, desc) {
557
+ const cache = new WeakMap();
558
+ // eslint-disable-next-line @typescript-eslint/unbound-method
559
+ const getter = desc.get;
560
+ desc.get = function () {
561
+ let meta = cache.get(this);
562
+ if (!meta) {
563
+ meta = {
564
+ hasComputed: false,
565
+ value: undefined
566
+ };
567
+ cache.set(this, meta);
568
+ }
569
+ if (!meta.hasComputed) {
570
+ meta.value = getter.call(this);
571
+ meta.hasComputed = true;
572
+ }
573
+ return meta.value;
574
+ };
575
+ return desc;
576
+ }
577
+ /**
578
+ * Base class from which Models can be defined.
579
+ *
580
+ * ::: code-group
581
+ *
582
+ * ```js [app/models/user.js]
583
+ * import { Model, attr, belongsTo, hasMany } from '@warp-drive/legacy/model';
584
+ *
585
+ * export default class User extends Model {
586
+ * @attr name;
587
+ * @attr('number') age;
588
+ * @hasMany('post', { async: true, inverse: null }) posts;
589
+ * @belongsTo('group', { async: false, inverse: 'users' }) group;
590
+ * }
591
+ * ```
592
+ *
593
+ * ```ts [app/models/user.ts]
594
+ * import { Model, attr, belongsTo, hasMany, type AsyncHasMany } from '@warp-drive/legacy/model';
595
+ * import type { NumberTransform } from '@ember-data/serializer/transform';
596
+ * import type Group from './group';
597
+ * import type Post from './post';
598
+ *
599
+ * export default class User extends Model {
600
+ * @attr declare name: string;
601
+ *
602
+ * @attr<NumberTransform>('number')
603
+ * declare age: number;
604
+ *
605
+ * @hasMany('post', { async: true, inverse: null })
606
+ * declare posts: AsyncHasMany<Post>;
607
+ *
608
+ * @belongsTo('group', { async: false, inverse: 'users' })
609
+ * declare group: Group | null;
610
+ * }
611
+ * ```
612
+ *
613
+ * :::
614
+ *
615
+ * Models both define the schema for a resource type and provide
616
+ * the class to use as the reactive object for data of resource
617
+ * of that type.
618
+ *
619
+ * @public
620
+ * @noInheritDoc
621
+ * @hideconstructor
622
+ * @legacy
623
+ */
624
+ class Model extends EmberObject {
625
+ /** @internal */
626
+ init(options) {
627
+ const createProps = options._createProps;
628
+ const _secretInit = options._secretInit;
629
+ options._createProps = null;
630
+ options._secretInit = null;
631
+ const store = this.store = _secretInit.store;
632
+ super.init(options);
633
+ this[RecordStore] = store;
634
+ const identity = _secretInit.identifier;
635
+ _secretInit.cb(this, identity, _secretInit.store);
636
+ this.___recordState = null;
637
+ this.setProperties(createProps);
638
+ const notifications = store.notifications;
639
+ this.___private_notifications = notifications.subscribe(identity, (identifier, type, field) => {
640
+ notifyChanges(identifier, type, field, this, store);
641
+ });
642
+ }
643
+
644
+ /** @private */
645
+ // @ts-expect-error destroy should not return a value, but ember's types force it to
646
+ destroy() {
647
+ const identifier = recordIdentifierFor(this);
648
+ this.___recordState?.destroy();
649
+ const store = storeFor(this, false);
650
+ store.notifications.unsubscribe(this.___private_notifications);
651
+ const support = LEGACY_SUPPORT.get(identifier);
652
+ if (support) {
653
+ support.destroy();
654
+ LEGACY_SUPPORT.delete(identifier);
655
+ }
656
+ super.destroy();
657
+ }
658
+
659
+ /**
660
+ If this property is `true` the record is in the `empty`
661
+ state. Empty is the first state all records enter after they have
662
+ been created. Most records created by the store will quickly
663
+ transition to the `loading` state if data needs to be fetched from
664
+ the server or the `created` state if the record is created on the
665
+ client. A record can also enter the empty state if the adapter is
666
+ unable to locate the record.
667
+ @property isEmpty
668
+ @public
669
+ @readonly
670
+ */
671
+ get isEmpty() {
672
+ return this.currentState.isEmpty;
673
+ }
674
+
675
+ /**
676
+ If this property is `true` the record is in the `loading` state. A
677
+ record enters this state when the store asks the adapter for its
678
+ data. It remains in this state until the adapter provides the
679
+ requested data.
680
+ @property isLoading
681
+ @public
682
+ @readonly
683
+ */
684
+ static {
685
+ decorateMethodV2(this.prototype, "isEmpty", [memoized]);
686
+ }
687
+ get isLoading() {
688
+ return this.currentState.isLoading;
689
+ }
690
+
691
+ /**
692
+ If this property is `true` the record is in the `loaded` state. A
693
+ record enters this state when its data is populated. Most of a
694
+ record's lifecycle is spent inside substates of the `loaded`
695
+ state.
696
+ Example
697
+ ```javascript
698
+ let record = store.createRecord('model');
699
+ record.isLoaded; // true
700
+ const { content: { data: model } } = await store.request(findRecord({ type: 'model', id: '1' }));
701
+ model.isLoaded;
702
+ ```
703
+ @property isLoaded
704
+ @public
705
+ @readonly
706
+ */
707
+ static {
708
+ decorateMethodV2(this.prototype, "isLoading", [memoized]);
709
+ }
710
+ get isLoaded() {
711
+ return this.currentState.isLoaded;
712
+ }
713
+
714
+ /**
715
+ If this property is `true` the record is in the `dirty` state. The
716
+ record has local changes that have not yet been saved by the
717
+ adapter. This includes records that have been created (but not yet
718
+ saved) or deleted.
719
+ Example
720
+ ```javascript
721
+ let record = store.createRecord('model');
722
+ record.hasDirtyAttributes; // true
723
+ const { content: { data: model } } = await store.request(findRecord({ type: 'model', id: '1' }));
724
+ model.hasDirtyAttributes; // false
725
+ model.foo = 'some value';
726
+ model.hasDirtyAttributes; // true
727
+ ```
728
+ @since 1.13.0
729
+ @property hasDirtyAttributes
730
+ @public
731
+ @readonly
732
+ */
733
+ static {
734
+ decorateMethodV2(this.prototype, "isLoaded", [memoized]);
735
+ }
736
+ get hasDirtyAttributes() {
737
+ return this.currentState.isDirty;
738
+ }
739
+
740
+ /**
741
+ If this property is `true` the record is in the `saving` state. A
742
+ record enters the saving state when `save` is called, but the
743
+ adapter has not yet acknowledged that the changes have been
744
+ persisted to the backend.
745
+ Example
746
+ ```javascript
747
+ let record = store.createRecord('model');
748
+ record.isSaving; // false
749
+ let promise = record.save();
750
+ record.isSaving; // true
751
+ promise.then(function() {
752
+ record.isSaving; // false
753
+ });
754
+ ```
755
+ @property isSaving
756
+ @public
757
+ @readonly
758
+ */
759
+ static {
760
+ decorateMethodV2(this.prototype, "hasDirtyAttributes", [memoized]);
761
+ }
762
+ get isSaving() {
763
+ return this.currentState.isSaving;
764
+ }
765
+
766
+ /**
767
+ If this property is `true` the record is in the `deleted` state
768
+ and has been marked for deletion. When `isDeleted` is true and
769
+ `hasDirtyAttributes` is true, the record is deleted locally but the deletion
770
+ was not yet persisted. When `isSaving` is true, the change is
771
+ in-flight. When both `hasDirtyAttributes` and `isSaving` are false, the
772
+ change has persisted.
773
+ Example
774
+ ```javascript
775
+ let record = store.createRecord('model');
776
+ record.isDeleted; // false
777
+ record.deleteRecord();
778
+ // Locally deleted
779
+ record.isDeleted; // true
780
+ record.hasDirtyAttributes; // true
781
+ record.isSaving; // false
782
+ // Persisting the deletion
783
+ let promise = record.save();
784
+ record.isDeleted; // true
785
+ record.isSaving; // true
786
+ // Deletion Persisted
787
+ promise.then(function() {
788
+ record.isDeleted; // true
789
+ record.isSaving; // false
790
+ record.hasDirtyAttributes; // false
791
+ });
792
+ ```
793
+ @property isDeleted
794
+ @public
795
+ @readonly
796
+ */
797
+ static {
798
+ decorateMethodV2(this.prototype, "isSaving", [memoized]);
799
+ }
800
+ get isDeleted() {
801
+ return this.currentState.isDeleted;
802
+ }
803
+
804
+ /**
805
+ If this property is `true` the record is in the `new` state. A
806
+ record will be in the `new` state when it has been created on the
807
+ client and the adapter has not yet report that it was successfully
808
+ saved.
809
+ Example
810
+ ```javascript
811
+ let record = store.createRecord('model');
812
+ record.isNew; // true
813
+ record.save().then(function(model) {
814
+ model.isNew; // false
815
+ });
816
+ ```
817
+ @property isNew
818
+ @public
819
+ @readonly
820
+ */
821
+ static {
822
+ decorateMethodV2(this.prototype, "isDeleted", [memoized]);
823
+ }
824
+ get isNew() {
825
+ return this.currentState.isNew;
826
+ }
827
+
828
+ /**
829
+ If this property is `true` the record is in the `valid` state.
830
+ A record will be in the `valid` state when the adapter did not report any
831
+ server-side validation failures.
832
+ @property isValid
833
+ @public
834
+ @readonly
835
+ */
836
+ static {
837
+ decorateMethodV2(this.prototype, "isNew", [memoized]);
838
+ }
839
+ get isValid() {
840
+ return this.currentState.isValid;
841
+ }
842
+
843
+ /**
844
+ If the record is in the dirty state this property will report what
845
+ kind of change has caused it to move into the dirty
846
+ state. Possible values are:
847
+ - `created` The record has been created by the client and not yet saved to the adapter.
848
+ - `updated` The record has been updated by the client and not yet saved to the adapter.
849
+ - `deleted` The record has been deleted by the client and not yet saved to the adapter.
850
+ Example
851
+ ```javascript
852
+ let record = store.createRecord('model');
853
+ record.dirtyType; // 'created'
854
+ ```
855
+ @property dirtyType
856
+ @public
857
+ @readonly
858
+ */
859
+ static {
860
+ decorateMethodV2(this.prototype, "isValid", [memoized]);
861
+ }
862
+ get dirtyType() {
863
+ return this.currentState.dirtyType;
864
+ }
865
+
866
+ /**
867
+ If `true` the adapter reported that it was unable to save local
868
+ changes to the backend for any reason other than a server-side
869
+ validation error.
870
+ Example
871
+ ```javascript
872
+ record.isError; // false
873
+ record.set('foo', 'valid value');
874
+ record.save().then(null, function() {
875
+ record.isError; // true
876
+ });
877
+ ```
878
+ @property isError
879
+ @public
880
+ @readonly
881
+ */
882
+ static {
883
+ decorateMethodV2(this.prototype, "dirtyType", [memoized]);
884
+ }
885
+ get isError() {
886
+ return this.currentState.isError;
887
+ }
888
+ static {
889
+ decorateMethodV2(this.prototype, "isError", [memoized]);
890
+ }
891
+ set isError(v) {}
892
+
893
+ /**
894
+ If `true` the store is attempting to reload the record from the adapter.
895
+ Example
896
+ ```javascript
897
+ record.isReloading; // false
898
+ record.reload();
899
+ record.isReloading; // true
900
+ ```
901
+ @property isReloading
902
+ @public
903
+ @readonly
904
+ */
905
+
906
+ /**
907
+ All ember models have an id property. This is an identifier
908
+ managed by an external source. These are always coerced to be
909
+ strings before being used internally. Note when declaring the
910
+ attributes for a model it is an error to declare an id
911
+ attribute.
912
+ ```javascript
913
+ let record = store.createRecord('model');
914
+ record.id; // null
915
+ const { content: { data: model } } = await store.request(findRecord({ type: 'model', id: '1' }));
916
+ model.id; // '1'
917
+ ```
918
+ @property id
919
+ @public
920
+ */
921
+ get id() {
922
+ // this guard exists, because some dev-only deprecation code
923
+ // (addListener via validatePropertyInjections) invokes toString before the
924
+ // object is real.
925
+
926
+ return recordIdentifierFor(this).id;
927
+ }
928
+ static {
929
+ decorateMethodV2(this.prototype, "id", [gate]);
930
+ }
931
+ set id(id) {
932
+ const normalizedId = coerceId(id);
933
+ const identifier = recordIdentifierFor(this);
934
+ const didChange = normalizedId !== identifier.id;
935
+ assertPrivateStore(this.store);
936
+ if (normalizedId !== null && didChange) {
937
+ this.store._instanceCache.setRecordId(identifier, normalizedId);
938
+ this.store.notifications.notify(identifier, 'identity', null);
939
+ }
940
+ }
941
+ toString() {
942
+ return `<model::${this.constructor.modelName}:${this.id}>`;
943
+ }
944
+
945
+ /**
946
+ @property currentState
947
+ @private
948
+ */
949
+ // TODO we can probably make this a computeOnce
950
+ // we likely do not need to notify the currentState root anymore
951
+ get currentState() {
952
+ // descriptors are called with the wrong `this` context during mergeMixins
953
+ // when using legacy/classic ember classes. Basically: lazy in prod and eager in dev.
954
+ // so we do this to try to steer folks to the nicer "dont user currentState"
955
+ // error.
956
+ {
957
+ if (!this.___recordState) {
958
+ this.___recordState = new RecordState(this);
959
+ }
960
+ }
961
+ return this.___recordState;
962
+ }
963
+ static {
964
+ decorateMethodV2(this.prototype, "currentState", [gate]);
965
+ }
966
+ set currentState(_v) {
967
+ throw new Error('cannot set currentState');
968
+ }
969
+
970
+ /**
971
+ The store service instance which created this record instance
972
+ @property store
973
+ @public
974
+ */
975
+
976
+ /**
977
+ When the record is in the `invalid` state this object will contain
978
+ any errors returned by the adapter. When present the errors hash
979
+ contains keys corresponding to the invalid property names
980
+ and values which are arrays of Javascript objects with two keys:
981
+ - `message` A string containing the error message from the backend
982
+ - `attribute` The name of the property associated with this error message
983
+ ```javascript
984
+ record.errors.length; // 0
985
+ record.set('foo', 'invalid value');
986
+ record.save().catch(function() {
987
+ record.errors.foo;
988
+ // [{message: 'foo should be a number.', attribute: 'foo'}]
989
+ });
990
+ ```
991
+ The `errors` property is useful for displaying error messages to
992
+ the user.
993
+ ```handlebars
994
+ <label>Username: <Input @value={{@model.username}} /> </label>
995
+ {{#each @model.errors.username as |error|}}
996
+ <div class="error">
997
+ {{error.message}}
998
+ </div>
999
+ {{/each}}
1000
+ <label>Email: <Input @value={{@model.email}} /> </label>
1001
+ {{#each @model.errors.email as |error|}}
1002
+ <div class="error">
1003
+ {{error.message}}
1004
+ </div>
1005
+ {{/each}}
1006
+ ```
1007
+ You can also access the special `messages` property on the error
1008
+ object to get an array of all the error strings.
1009
+ ```handlebars
1010
+ {{#each @model.errors.messages as |message|}}
1011
+ <div class="error">
1012
+ {{message}}
1013
+ </div>
1014
+ {{/each}}
1015
+ ```
1016
+ @property errors
1017
+ @public
1018
+ */
1019
+ get errors() {
1020
+ const errors = Errors.create({
1021
+ __record: this
1022
+ });
1023
+ this.currentState.updateInvalidErrors(errors);
1024
+ return errors;
1025
+ }
1026
+
1027
+ /**
1028
+ This property holds the `AdapterError` object with which
1029
+ last adapter operation was rejected.
1030
+ @property adapterError
1031
+ @public
1032
+ */
1033
+ static {
1034
+ decorateMethodV2(this.prototype, "errors", [computeOnce]);
1035
+ }
1036
+ get adapterError() {
1037
+ return this.currentState.adapterError;
1038
+ }
1039
+ static {
1040
+ decorateMethodV2(this.prototype, "adapterError", [memoized]);
1041
+ }
1042
+ set adapterError(v) {
1043
+ throw new Error(`adapterError is not directly settable`);
1044
+ }
1045
+
1046
+ /*
1047
+ We hook the default implementation to ensure
1048
+ our tagged properties are properly notified
1049
+ as well. We still super for everything because
1050
+ sync observers require a direct call occuring
1051
+ to trigger their flush. We wouldn't need to
1052
+ super in 4.0+ where sync observers are removed.
1053
+ */
1054
+ // @ts-expect-error no return is necessary, but Ember's types are forcing it
1055
+ notifyPropertyChange(prop) {
1056
+ const signals = withSignalStore(this);
1057
+ entangleSignal(signals, this, prop, undefined);
1058
+ super.notifyPropertyChange(prop);
1059
+ }
1060
+
1061
+ /** @internal */
1062
+ attr() {}
1063
+
1064
+ /**
1065
+ Given a callback, iterates over each of the relationships in the model,
1066
+ invoking the callback with the name of each relationship and its relationship
1067
+ descriptor.
1068
+ The callback method you provide should have the following signature (all
1069
+ parameters are optional):
1070
+ ```javascript
1071
+ function(name, descriptor);
1072
+ ```
1073
+ - `name` the name of the current property in the iteration
1074
+ - `descriptor` the meta object that describes this relationship
1075
+ The relationship descriptor argument is an object with the following properties.
1076
+ - **name** <span class="type">String</span> the name of this relationship on the Model
1077
+ - **kind** <span class="type">String</span> "hasMany" or "belongsTo"
1078
+ - **options** <span class="type">Object</span> the original options hash passed when the relationship was declared
1079
+ - **parentType** <span class="type">Model</span> the type of the Model that owns this relationship
1080
+ - **type** <span class="type">String</span> the type name of the related Model
1081
+ Note that in addition to a callback, you can also pass an optional target
1082
+ object that will be set as `this` on the context.
1083
+ Example
1084
+ ```js [app/serializers/application.js]
1085
+ import JSONSerializer from '@ember-data/serializer/json';
1086
+ export default class ApplicationSerializer extends JSONSerializer {
1087
+ serialize(record, options) {
1088
+ let json = {};
1089
+ record.eachRelationship(function(name, descriptor) {
1090
+ if (descriptor.kind === 'hasMany') {
1091
+ let serializedHasManyName = name.toUpperCase() + '_IDS';
1092
+ json[serializedHasManyName] = record.get(name).map(r => r.id);
1093
+ }
1094
+ });
1095
+ return json;
1096
+ }
1097
+ }
1098
+ ```
1099
+ @public
1100
+ @param callback the callback to invoke
1101
+ @param binding the value to which the callback's `this` should be bound
1102
+ */
1103
+ eachRelationship(callback, binding) {
1104
+ this.constructor.eachRelationship(callback, binding);
1105
+ }
1106
+ relationshipFor(name) {
1107
+ return this.constructor.relationshipsByName.get(name);
1108
+ }
1109
+ inverseFor(name) {
1110
+ return this.constructor.inverseFor(name, storeFor(this, false));
1111
+ }
1112
+ eachAttribute(callback, binding) {
1113
+ this.constructor.eachAttribute(callback, binding);
1114
+ }
1115
+
1116
+ /**
1117
+ * @internal
1118
+ */
1119
+ static isModel = true;
1120
+
1121
+ /**
1122
+ Represents the model's class name as a string. This can be used to look up the model's class name through
1123
+ `Store`'s modelFor method.
1124
+ `modelName` is generated for you by WarpDrive. It will be a lowercased, dasherized string.
1125
+ For example:
1126
+ ```javascript
1127
+ store.modelFor('post').modelName; // 'post'
1128
+ store.modelFor('blog-post').modelName; // 'blog-post'
1129
+ ```
1130
+ The most common place you'll want to access `modelName` is in your serializer's `payloadKeyFromModelName` method. For example, to change payload
1131
+ keys to underscore (instead of dasherized), you might use the following code:
1132
+ ```javascript
1133
+ import RESTSerializer from '@ember-data/serializer/rest';
1134
+ import { underscore } from '<app-name>/utils/string-utils';
1135
+ export default const PostSerializer = RESTSerializer.extend({
1136
+ payloadKeyFromModelName(modelName) {
1137
+ return underscore(modelName);
1138
+ }
1139
+ });
1140
+ ```
1141
+ @property modelName
1142
+ @public
1143
+ @readonly
1144
+ */
1145
+ static modelName = null;
1146
+
1147
+ /*
1148
+ These class methods below provide relationship
1149
+ introspection abilities about relationships.
1150
+ A note about the computed properties contained here:
1151
+ **These properties are effectively sealed once called for the first time.**
1152
+ To avoid repeatedly doing expensive iteration over a model's fields, these
1153
+ values are computed once and then cached for the remainder of the runtime of
1154
+ your application.
1155
+ If your application needs to modify a class after its initial definition
1156
+ (for example, using `reopen()` to add additional attributes), make sure you
1157
+ do it before using your model with the store, which uses these properties
1158
+ extensively.
1159
+ */
1160
+
1161
+ /**
1162
+ For a given relationship name, returns the model type of the relationship.
1163
+ For example, if you define a model like this:
1164
+ ```js [app/models/post.js]
1165
+ import { Model, hasMany } from '@warp-drive/legacy/model';
1166
+ export default class PostModel extends Model {
1167
+ @hasMany('comment') comments;
1168
+ }
1169
+ ```
1170
+ Calling `store.modelFor('post').typeForRelationship('comments', store)` will return `Comment`.
1171
+ @public
1172
+ @param name the name of the relationship
1173
+ @param store an instance of Store
1174
+ @return the type of the relationship, or undefined
1175
+ */
1176
+ static typeForRelationship(name, store) {
1177
+ const relationship = this.relationshipsByName.get(name);
1178
+ return relationship && store.modelFor(relationship.type);
1179
+ }
1180
+ static get inverseMap() {
1181
+ return Object.create(null);
1182
+ }
1183
+
1184
+ /**
1185
+ Find the relationship which is the inverse of the one asked for.
1186
+ For example, if you define models like this:
1187
+ ```js [app/models/post.js]
1188
+ import { Model, hasMany } from '@warp-drive/legacy/model';
1189
+ export default class PostModel extends Model {
1190
+ @hasMany('message') comments;
1191
+ }
1192
+ ```
1193
+ ```js [app/models/message.js]
1194
+ import { Model, belongsTo } from '@warp-drive/legacy/model';
1195
+ export default class MessageModel extends Model {
1196
+ @belongsTo('post') owner;
1197
+ }
1198
+ ```
1199
+ ``` js
1200
+ store.modelFor('post').inverseFor('comments', store) // { type: 'message', name: 'owner', kind: 'belongsTo' }
1201
+ store.modelFor('message').inverseFor('owner', store) // { type: 'post', name: 'comments', kind: 'hasMany' }
1202
+ ```
1203
+ @public
1204
+ @param name the name of the relationship
1205
+ @param store
1206
+ @return the inverse relationship, or null
1207
+ */
1208
+ static {
1209
+ decorateMethodV2(this, "inverseMap", [computeOnce]);
1210
+ }
1211
+ static inverseFor(name, store) {
1212
+ const inverseMap = this.inverseMap;
1213
+ if (inverseMap[name]) {
1214
+ return inverseMap[name];
1215
+ } else {
1216
+ const inverse = this._findInverseFor(name, store);
1217
+ inverseMap[name] = inverse;
1218
+ return inverse;
1219
+ }
1220
+ }
1221
+
1222
+ //Calculate the inverse, ignoring the cache
1223
+ static _findInverseFor(name, store) {
1224
+ const relationship = this.relationshipsByName.get(name);
1225
+ if (!relationship) {
1226
+ return null;
1227
+ }
1228
+ const {
1229
+ options
1230
+ } = relationship;
1231
+ if (options.inverse === null) {
1232
+ return null;
1233
+ }
1234
+ const schemaExists = store.schema.hasResource(relationship);
1235
+ if (!schemaExists) {
1236
+ return null;
1237
+ }
1238
+ const inverseField = store.schema.fields(relationship).get(options.inverse);
1239
+ return inverseField || null;
1240
+ }
1241
+
1242
+ /**
1243
+ The model's relationships as a map, keyed on the type of the
1244
+ relationship. The value of each entry is an array containing a descriptor
1245
+ for each relationship with that type, describing the name of the relationship
1246
+ as well as the type.
1247
+ For example, given the following model definition:
1248
+ ```js [app/models/blog.js]
1249
+ import { Model, belongsTo, hasMany } from '@warp-drive/legacy/model';
1250
+ export default class BlogModel extends Model {
1251
+ @hasMany('user') users;
1252
+ @belongsTo('user') owner;
1253
+ @hasMany('post') posts;
1254
+ }
1255
+ ```
1256
+ This computed property would return a map describing these
1257
+ relationships, like this:
1258
+ ```javascript
1259
+ import Blog from 'app/models/blog';
1260
+ import User from 'app/models/user';
1261
+ import Post from 'app/models/post';
1262
+ let relationships = Blog.relationships;
1263
+ relationships.user;
1264
+ //=> [ { name: 'users', kind: 'hasMany' },
1265
+ // { name: 'owner', kind: 'belongsTo' } ]
1266
+ relationships.post;
1267
+ //=> [ { name: 'posts', kind: 'hasMany' } ]
1268
+ ```
1269
+ @property relationships
1270
+ @public
1271
+ @readonly
1272
+ */
1273
+
1274
+ static get relationships() {
1275
+ const map = new Map();
1276
+ const relationshipsByName = this.relationshipsByName;
1277
+
1278
+ // Loop through each computed property on the class
1279
+ relationshipsByName.forEach(desc => {
1280
+ const {
1281
+ type
1282
+ } = desc;
1283
+ if (!map.has(type)) {
1284
+ map.set(type, []);
1285
+ }
1286
+ map.get(type).push(desc);
1287
+ });
1288
+ return map;
1289
+ }
1290
+
1291
+ /**
1292
+ A hash containing lists of the model's relationships, grouped
1293
+ by the relationship kind. For example, given a model with this
1294
+ definition:
1295
+ ```js [app/models/blog.js]
1296
+ import { Model, belongsTo, hasMany } from '@warp-drive/legacy/model';
1297
+ export default class BlogModel extends Model {
1298
+ @hasMany('user') users;
1299
+ @belongsTo('user') owner;
1300
+ @hasMany('post') posts;
1301
+ }
1302
+ ```
1303
+ This property would contain the following:
1304
+ ```javascript
1305
+ import Blog from 'app/models/blog';
1306
+ let relationshipNames = Blog.relationshipNames;
1307
+ relationshipNames.hasMany;
1308
+ //=> ['users', 'posts']
1309
+ relationshipNames.belongsTo;
1310
+ //=> ['owner']
1311
+ ```
1312
+ @property relationshipNames
1313
+ @public
1314
+ @readonly
1315
+ */
1316
+ static {
1317
+ decorateMethodV2(this, "relationships", [computeOnce]);
1318
+ }
1319
+ static get relationshipNames() {
1320
+ const names = {
1321
+ hasMany: [],
1322
+ belongsTo: []
1323
+ };
1324
+ this.eachComputedProperty((name, meta) => {
1325
+ if (isRelationshipSchema(meta)) {
1326
+ names[meta.kind].push(name);
1327
+ }
1328
+ });
1329
+ return names;
1330
+ }
1331
+
1332
+ /**
1333
+ An array of types directly related to a model. Each type will be
1334
+ included once, regardless of the number of relationships it has with
1335
+ the model.
1336
+ For example, given a model with this definition:
1337
+ ```js [app/models/blog.js]
1338
+ import { Model, belongsTo, hasMany } from '@warp-drive/legacy/model';
1339
+ export default class BlogModel extends Model {
1340
+ @hasMany('user') users;
1341
+ @belongsTo('user') owner;
1342
+ @hasMany('post') posts;
1343
+ }
1344
+ ```
1345
+ This property would contain the following:
1346
+ ```javascript
1347
+ import Blog from 'app/models/blog';
1348
+ let relatedTypes = Blog.relatedTypes');
1349
+ //=> ['user', 'post']
1350
+ ```
1351
+ @property relatedTypes
1352
+ @public
1353
+ @readonly
1354
+ */
1355
+ static {
1356
+ decorateMethodV2(this, "relationshipNames", [computeOnce]);
1357
+ }
1358
+ static get relatedTypes() {
1359
+ const types = [];
1360
+ const rels = this.relationshipsObject;
1361
+ const relationships = Object.keys(rels);
1362
+
1363
+ // create an array of the unique types involved
1364
+ // in relationships
1365
+ for (let i = 0; i < relationships.length; i++) {
1366
+ const name = relationships[i];
1367
+ const meta = rels[name];
1368
+ const modelName = meta.type;
1369
+ if (!types.includes(modelName)) {
1370
+ types.push(modelName);
1371
+ }
1372
+ }
1373
+ return types;
1374
+ }
1375
+
1376
+ /**
1377
+ A map whose keys are the relationships of a model and whose values are
1378
+ relationship descriptors.
1379
+ For example, given a model with this
1380
+ definition:
1381
+ ```js [app/models/blog.js]
1382
+ import { Model, belongsTo, hasMany } from '@warp-drive/legacy/model';
1383
+ export default class BlogModel extends Model {
1384
+ @hasMany('user') users;
1385
+ @belongsTo('user') owner;
1386
+ @hasMany('post') posts;
1387
+ }
1388
+ ```
1389
+ This property would contain the following:
1390
+ ```javascript
1391
+ import Blog from 'app/models/blog';
1392
+ let relationshipsByName = Blog.relationshipsByName;
1393
+ relationshipsByName.users;
1394
+ //=> { name: 'users', kind: 'hasMany', type: 'user', options: Object }
1395
+ relationshipsByName.owner;
1396
+ //=> { name: 'owner', kind: 'belongsTo', type: 'user', options: Object }
1397
+ ```
1398
+ @property relationshipsByName
1399
+ @public
1400
+ @readonly
1401
+ */
1402
+ static {
1403
+ decorateMethodV2(this, "relatedTypes", [computeOnce]);
1404
+ }
1405
+ static get relationshipsByName() {
1406
+ const map = new Map();
1407
+ const rels = this.relationshipsObject;
1408
+ const relationships = Object.keys(rels);
1409
+ for (let i = 0; i < relationships.length; i++) {
1410
+ const name = relationships[i];
1411
+ const value = rels[name];
1412
+ map.set(value.name, value);
1413
+ }
1414
+ return map;
1415
+ }
1416
+ static {
1417
+ decorateMethodV2(this, "relationshipsByName", [computeOnce]);
1418
+ }
1419
+ static get relationshipsObject() {
1420
+ const relationships = Object.create(null);
1421
+ this.modelName;
1422
+ this.eachComputedProperty((name, meta) => {
1423
+ if (!isRelationshipSchema(meta)) {
1424
+ return;
1425
+ }
1426
+ // TODO deprecate key being here
1427
+ meta.key = name;
1428
+ meta.name = name;
1429
+ relationships[name] = meta;
1430
+ });
1431
+ return relationships;
1432
+ }
1433
+
1434
+ /**
1435
+ A map whose keys are the fields of the model and whose values are strings
1436
+ describing the kind of the field. A model's fields are the union of all of its
1437
+ attributes and relationships.
1438
+ For example:
1439
+ ```js [app/models/blog.js]
1440
+ import { Model, attr, belongsTo, hasMany } from '@warp-drive/legacy/model';
1441
+ export default class BlogModel extends Model {
1442
+ @hasMany('user') users;
1443
+ @belongsTo('user') owner;
1444
+ @hasMany('post') posts;
1445
+ @attr('string') title;
1446
+ }
1447
+ ```
1448
+ ```js
1449
+ import Blog from 'app/models/blog'
1450
+ let fields = Blog.fields;
1451
+ fields.forEach(function(kind, field) {
1452
+ // do thing
1453
+ });
1454
+ // prints:
1455
+ // users, hasMany
1456
+ // owner, belongsTo
1457
+ // posts, hasMany
1458
+ // title, attribute
1459
+ ```
1460
+ @property fields
1461
+ @public
1462
+ @readonly
1463
+ */
1464
+ static {
1465
+ decorateMethodV2(this, "relationshipsObject", [computeOnce]);
1466
+ }
1467
+ static get fields() {
1468
+ const map = new Map();
1469
+ this.eachComputedProperty((name, meta) => {
1470
+ if (isRelationshipSchema(meta)) {
1471
+ map.set(name, meta.kind);
1472
+ } else if (isAttributeSchema(meta)) {
1473
+ map.set(name, 'attribute');
1474
+ }
1475
+ });
1476
+ return map;
1477
+ }
1478
+
1479
+ /**
1480
+ Given a callback, iterates over each of the relationships in the model,
1481
+ invoking the callback with the name of each relationship and its relationship
1482
+ descriptor.
1483
+ @public
1484
+ @param {Function} callback the callback to invoke
1485
+ @param {any} binding the value to which the callback's `this` should be bound
1486
+ */
1487
+ static {
1488
+ decorateMethodV2(this, "fields", [computeOnce]);
1489
+ }
1490
+ static eachRelationship(callback, binding) {
1491
+ this.relationshipsByName.forEach((relationship, name) => {
1492
+ callback.call(binding, name, relationship);
1493
+ });
1494
+ }
1495
+
1496
+ /**
1497
+ Given a callback, iterates over each of the types related to a model,
1498
+ invoking the callback with the related type's class. Each type will be
1499
+ returned just once, regardless of how many different relationships it has
1500
+ with a model.
1501
+ @public
1502
+ @param {Function} callback the callback to invoke
1503
+ @param {any} binding the value to which the callback's `this` should be bound
1504
+ */
1505
+ static eachRelatedType(callback, binding) {
1506
+ const relationshipTypes = this.relatedTypes;
1507
+ for (let i = 0; i < relationshipTypes.length; i++) {
1508
+ const type = relationshipTypes[i];
1509
+ callback.call(binding, type);
1510
+ }
1511
+ }
1512
+
1513
+ /**
1514
+ *
1515
+ * @private
1516
+ * @deprecated
1517
+ */
1518
+ static determineRelationshipType(knownSide, store) {
1519
+ const knownKey = knownSide.name;
1520
+ const knownKind = knownSide.kind;
1521
+ const inverse = this.inverseFor(knownKey, store);
1522
+ // let key;
1523
+
1524
+ if (!inverse) {
1525
+ return knownKind === 'belongsTo' ? 'oneToNone' : 'manyToNone';
1526
+ }
1527
+
1528
+ // key = inverse.name;
1529
+ const otherKind = inverse.kind;
1530
+ if (otherKind === 'belongsTo') {
1531
+ return knownKind === 'belongsTo' ? 'oneToOne' : 'manyToOne';
1532
+ } else {
1533
+ return knownKind === 'belongsTo' ? 'oneToMany' : 'manyToMany';
1534
+ }
1535
+ }
1536
+
1537
+ /**
1538
+ A map whose keys are the attributes of the model (properties
1539
+ described by attr) and whose values are the meta object for the
1540
+ property.
1541
+ Example
1542
+ ```js [app/models/person.js]
1543
+ import { Model, attr } from '@warp-drive/legacy/model';
1544
+ export default class PersonModel extends Model {
1545
+ @attr('string') firstName;
1546
+ @attr('string') lastName;
1547
+ @attr('date') birthday;
1548
+ }
1549
+ ```
1550
+ ```javascript
1551
+ import Person from 'app/models/person'
1552
+ let attributes = Person.attributes
1553
+ attributes.forEach(function(meta, name) {
1554
+ // do thing
1555
+ });
1556
+ // prints:
1557
+ // firstName {type: "string", kind: 'attribute', options: Object, parentType: function, name: "firstName"}
1558
+ // lastName {type: "string", kind: 'attribute', options: Object, parentType: function, name: "lastName"}
1559
+ // birthday {type: "date", kind: 'attribute', options: Object, parentType: function, name: "birthday"}
1560
+ ```
1561
+ @property attributes
1562
+ @public
1563
+ @readonly
1564
+ */
1565
+ static get attributes() {
1566
+ const map = new Map();
1567
+ this.eachComputedProperty((name, meta) => {
1568
+ if (isAttributeSchema(meta)) {
1569
+ // TODO deprecate key being here
1570
+ meta.key = name;
1571
+ meta.name = name;
1572
+ map.set(name, meta);
1573
+ }
1574
+ });
1575
+ return map;
1576
+ }
1577
+
1578
+ /**
1579
+ A map whose keys are the attributes of the model (properties
1580
+ described by attr) and whose values are type of transformation
1581
+ applied to each attribute. This map does not include any
1582
+ attributes that do not have an transformation type.
1583
+ Example
1584
+ ```js [app/models/person.js]
1585
+ import { Model, attr } from '@warp-drive/legacy/model';
1586
+ export default class PersonModel extends Model {
1587
+ @attr firstName;
1588
+ @attr('string') lastName;
1589
+ @attr('date') birthday;
1590
+ }
1591
+ ```
1592
+ ```javascript
1593
+ import Person from 'app/models/person';
1594
+ let transformedAttributes = Person.transformedAttributes
1595
+ transformedAttributes.forEach(function(field, type) {
1596
+ // do thing
1597
+ });
1598
+ // prints:
1599
+ // lastName string
1600
+ // birthday date
1601
+ ```
1602
+ @property transformedAttributes
1603
+ @public
1604
+ @readonly
1605
+ */
1606
+ static {
1607
+ decorateMethodV2(this, "attributes", [computeOnce]);
1608
+ }
1609
+ static get transformedAttributes() {
1610
+ const map = new Map();
1611
+ this.eachAttribute((name, meta) => {
1612
+ if (meta.type) {
1613
+ map.set(name, meta.type);
1614
+ }
1615
+ });
1616
+ return map;
1617
+ }
1618
+
1619
+ /**
1620
+ Iterates through the attributes of the model, calling the passed function on each
1621
+ attribute.
1622
+ The callback method you provide should have the following signature (all
1623
+ parameters are optional):
1624
+ ```javascript
1625
+ function(name, meta);
1626
+ ```
1627
+ - `name` the name of the current property in the iteration
1628
+ - `meta` the meta object for the attribute property in the iteration
1629
+ Note that in addition to a callback, you can also pass an optional target
1630
+ object that will be set as `this` on the context.
1631
+ Example
1632
+ ```javascript
1633
+ import { Model, attr } from '@warp-drive/legacy/model';
1634
+ class PersonModel extends Model {
1635
+ @attr('string') firstName;
1636
+ @attr('string') lastName;
1637
+ @attr('date') birthday;
1638
+ }
1639
+ PersonModel.eachAttribute(function(name, meta) {
1640
+ // do thing
1641
+ });
1642
+ // prints:
1643
+ // firstName {type: "string", kind: 'attribute', options: Object, parentType: function, name: "firstName"}
1644
+ // lastName {type: "string", kind: 'attribute', options: Object, parentType: function, name: "lastName"}
1645
+ // birthday {type: "date", kind: 'attribute', options: Object, parentType: function, name: "birthday"}
1646
+ ```
1647
+ @public
1648
+ @param {Function} callback The callback to execute
1649
+ @param {Object} [binding] the value to which the callback's `this` should be bound
1650
+ */
1651
+ static {
1652
+ decorateMethodV2(this, "transformedAttributes", [computeOnce]);
1653
+ }
1654
+ static eachAttribute(callback, binding) {
1655
+ this.attributes.forEach((meta, name) => {
1656
+ callback.call(binding, name, meta);
1657
+ });
1658
+ }
1659
+
1660
+ /**
1661
+ Iterates through the transformedAttributes of the model, calling
1662
+ the passed function on each attribute. Note the callback will not be
1663
+ called for any attributes that do not have an transformation type.
1664
+ The callback method you provide should have the following signature (all
1665
+ parameters are optional):
1666
+ ```javascript
1667
+ function(name, type);
1668
+ ```
1669
+ - `name` the name of the current property in the iteration
1670
+ - `type` a string containing the name of the type of transformed
1671
+ applied to the attribute
1672
+ Note that in addition to a callback, you can also pass an optional target
1673
+ object that will be set as `this` on the context.
1674
+ Example
1675
+ ```javascript
1676
+ import { Model, attr } from '@warp-drive/legacy/model';
1677
+ let Person = Model.extend({
1678
+ firstName: attr(),
1679
+ lastName: attr('string'),
1680
+ birthday: attr('date')
1681
+ });
1682
+ Person.eachTransformedAttribute(function(name, type) {
1683
+ // do thing
1684
+ });
1685
+ // prints:
1686
+ // lastName string
1687
+ // birthday date
1688
+ ```
1689
+ @public
1690
+ @param {Function} callback The callback to execute
1691
+ @param {Object} [binding] the value to which the callback's `this` should be bound
1692
+ */
1693
+ static eachTransformedAttribute(callback, binding) {
1694
+ this.transformedAttributes.forEach((type, name) => {
1695
+ callback.call(binding, name, type);
1696
+ });
1697
+ }
1698
+
1699
+ /**
1700
+ Returns the name of the model class.
1701
+ @public
1702
+ */
1703
+ static toString() {
1704
+ return `model:${this.modelName}`;
1705
+ }
1706
+ }
1707
+
1708
+ // @ts-expect-error TS doesn't know how to do `this` function overloads
1709
+ Model.prototype.save = save;
1710
+ // @ts-expect-error TS doesn't know how to do `this` function overloads
1711
+ Model.prototype.destroyRecord = destroyRecord;
1712
+ Model.prototype.unloadRecord = unloadRecord;
1713
+ Model.prototype.hasMany = hasMany;
1714
+ Model.prototype.belongsTo = belongsTo;
1715
+ Model.prototype.serialize = serialize;
1716
+ Model.prototype._createSnapshot = createSnapshot;
1717
+ Model.prototype.deleteRecord = deleteRecord;
1718
+ Model.prototype.changedAttributes = changedAttributes;
1719
+ Model.prototype.rollbackAttributes = rollbackAttributes;
1720
+ Model.prototype.reload = reload;
1721
+ defineGate(Model.prototype, 'isReloading', {
1722
+ get() {
1723
+ return this._isReloading ?? false;
1724
+ },
1725
+ set(v) {
1726
+ this._isReloading = v;
1727
+ },
1728
+ configurable: true,
1729
+ // @ts-expect-error specially handled prop
1730
+ isLocal: true
1731
+ });
1732
+ function restoreDeprecatedModelRequestBehaviors(ModelKlass) {
1733
+ // @ts-expect-error TS doesn't know how to do `this` function overloads
1734
+ ModelKlass.prototype.save = _save;
1735
+ // @ts-expect-error TS doesn't know how to do `this` function overloads
1736
+ ModelKlass.prototype.destroyRecord = _destroyRecord;
1737
+ ModelKlass.prototype.reload = _reload;
1738
+ defineGate(Model.prototype, 'isReloading', {
1739
+ get() {
1740
+ return this._isReloading ?? false;
1741
+ },
1742
+ set(v) {
1743
+ this._isReloading = v;
1744
+ },
1745
+ // @ts-expect-error specially handled prop
1746
+ isLocal: true
1747
+ });
1748
+ }
1749
+
1750
+ // this is required to prevent `init` from passing
1751
+ // the values initialized during create to `setUnknownProperty`
1752
+ Model.prototype._createProps = null;
1753
+ Model.prototype._secretInit = null;
1754
+ function isRelationshipSchema(meta) {
1755
+ const hasKind = typeof meta === 'object' && meta !== null && 'kind' in meta && 'options' in meta;
1756
+ return hasKind && (meta.kind === 'hasMany' || meta.kind === 'belongsTo');
1757
+ }
1758
+ function isAttributeSchema(meta) {
1759
+ return typeof meta === 'object' && meta !== null && 'kind' in meta && meta.kind === 'attribute';
1760
+ }
1761
+
1762
+ /*
1763
+ In case someone defined a relationship to a mixin, for example:
1764
+ ```ts
1765
+ class CommentModel extends Model {
1766
+ @belongsTo('commentable', { polymorphic: true }) owner;
1767
+ }
1768
+
1769
+ let Commentable = Mixin.create({
1770
+ @hasMany('comment') comments;
1771
+ });
1772
+ ```
1773
+ we want to look up a Commentable class which has all the necessary
1774
+ relationship meta data. Thus, we look up the mixin and create a mock
1775
+ Model, so we can access the relationship CPs of the mixin (`comments`)
1776
+ in this case
1777
+ */
1778
+ function modelForMixin(store, normalizedModelName) {
1779
+ const owner = getOwner(store);
1780
+ const MaybeMixin = owner.factoryFor(`mixin:${normalizedModelName}`);
1781
+ const mixin = MaybeMixin && MaybeMixin.class;
1782
+ if (mixin) {
1783
+ const ModelForMixin = Model.extend(mixin);
1784
+ ModelForMixin.__isMixin = true;
1785
+ ModelForMixin.__mixin = mixin;
1786
+ //Cache the class as a model
1787
+ owner.register(`model:${normalizedModelName}`, ModelForMixin);
1788
+ }
1789
+ return owner.factoryFor(`model:${normalizedModelName}`);
1790
+ }
1791
+ class ModelSchemaProvider {
1792
+ /** @internal */
1793
+
1794
+ /** @internal */
1795
+
1796
+ /** @internal */
1797
+
1798
+ constructor(store) {
1799
+ this.store = store;
1800
+ this._schemas = new Map();
1801
+ this._typeMisses = new Set();
1802
+ }
1803
+ resourceTypes() {
1804
+ return Array.from(this._schemas.keys());
1805
+ }
1806
+ hasTrait(type) {
1807
+ return false;
1808
+ }
1809
+ resourceHasTrait(resource, trait) {
1810
+ return false;
1811
+ }
1812
+ transformation(field) {}
1813
+ derivation(field) {}
1814
+ hashFn(field) {}
1815
+ resource(resource) {
1816
+ const type = normalizeModelName(resource.type);
1817
+ if (!this._schemas.has(type)) {
1818
+ this._loadModelSchema(type);
1819
+ }
1820
+ return this._schemas.get(type).schema;
1821
+ }
1822
+ registerResources(schemas) {}
1823
+ registerResource(schema) {}
1824
+ registerTransformation(transform) {}
1825
+ registerDerivation(derivation) {}
1826
+ registerHashFn(hashFn) {}
1827
+ /** @internal */
1828
+ _loadModelSchema(type) {
1829
+ const modelClass = this.store.modelFor(type);
1830
+ const attributeMap = modelClass.attributes;
1831
+ const attributes = Object.create(null);
1832
+ attributeMap.forEach((meta, name) => attributes[name] = meta);
1833
+ const relationships = modelClass.relationshipsObject || null;
1834
+ const fields = new Map();
1835
+ for (const attr of Object.values(attributes)) {
1836
+ fields.set(attr.name, attr);
1837
+ }
1838
+ for (const rel of Object.values(relationships)) {
1839
+ fields.set(rel.name, rel);
1840
+ }
1841
+ const schema = {
1842
+ legacy: true,
1843
+ identity: {
1844
+ name: 'id',
1845
+ kind: '@id'
1846
+ },
1847
+ type,
1848
+ fields: Array.from(fields.values())
1849
+ };
1850
+ const internalSchema = {
1851
+ schema,
1852
+ attributes,
1853
+ relationships,
1854
+ fields
1855
+ };
1856
+ this._schemas.set(type, internalSchema);
1857
+ return internalSchema;
1858
+ }
1859
+ fields(resource) {
1860
+ const type = normalizeModelName(resource.type);
1861
+ if (!this._schemas.has(type)) {
1862
+ this._loadModelSchema(type);
1863
+ }
1864
+ return this._schemas.get(type).fields;
1865
+ }
1866
+ hasResource(resource) {
1867
+ const type = normalizeModelName(resource.type);
1868
+ if (this._schemas.has(type)) {
1869
+ return true;
1870
+ }
1871
+ if (this._typeMisses.has(type)) {
1872
+ return false;
1873
+ }
1874
+ const factory = getModelFactory(this.store, type);
1875
+ const exists = factory !== null;
1876
+ if (!exists) {
1877
+ this._typeMisses.add(type);
1878
+ return false;
1879
+ }
1880
+ return true;
1881
+ }
1882
+ }
1883
+ {
1884
+ ModelSchemaProvider.prototype.doesTypeExist = function (type) {
1885
+ return this.hasResource({
1886
+ type
1887
+ });
1888
+ };
1889
+ ModelSchemaProvider.prototype.attributesDefinitionFor = function (resource) {
1890
+ const type = normalizeModelName(resource.type);
1891
+
1892
+ // @ts-expect-error intentional use of internal API
1893
+ if (!this._schemas.has(type)) {
1894
+ // @ts-expect-error intentional use of internal API
1895
+ this._loadModelSchema(type);
1896
+ }
1897
+
1898
+ // @ts-expect-error intentional use of internal API
1899
+ return this._schemas.get(type).attributes;
1900
+ };
1901
+ ModelSchemaProvider.prototype.relationshipsDefinitionFor = function (resource) {
1902
+ const type = normalizeModelName(resource.type);
1903
+
1904
+ // @ts-expect-error intentional use of internal API
1905
+ if (!this._schemas.has(type)) {
1906
+ // @ts-expect-error intentional use of internal API
1907
+ this._loadModelSchema(type);
1908
+ }
1909
+
1910
+ // @ts-expect-error intentional use of internal API
1911
+ return this._schemas.get(type).relationships;
1912
+ };
1913
+ }
1914
+ function buildSchema(store) {
1915
+ return new ModelSchemaProvider(store);
1916
+ }
1917
+ function getModelFactory(store, type) {
1918
+ if (!store._modelFactoryCache) {
1919
+ store._modelFactoryCache = Object.create(null);
1920
+ }
1921
+ const cache = store._modelFactoryCache;
1922
+ let factory = cache[type];
1923
+ if (!factory) {
1924
+ const owner = getOwner(store);
1925
+ factory = owner.factoryFor(`model:${type}`);
1926
+ if (!factory) {
1927
+ //Support looking up mixins as base types for polymorphic relationships
1928
+ factory = modelForMixin(store, type);
1929
+ }
1930
+ if (!factory) {
1931
+ // we don't cache misses in case someone wants to register a missing model
1932
+ return null;
1933
+ }
1934
+ const klass = factory.class;
1935
+ if (klass.isModel) {
1936
+ const hasOwnModelNameSet = klass.modelName && Object.prototype.hasOwnProperty.call(klass, 'modelName');
1937
+ if (!hasOwnModelNameSet) {
1938
+ Object.defineProperty(klass, 'modelName', {
1939
+ value: type
1940
+ });
1941
+ }
1942
+ }
1943
+ cache[type] = factory;
1944
+ }
1945
+ return factory;
1946
+ }
1947
+ export { Model as M, RecordState as R, _save as _, save as a, buildSchema as b, _reload as c, reload as d, _destroyRecord as e, destroyRecord as f, getModelFactory as g, hasMany as h, deleteRecord as i, changedAttributes as j, belongsTo as k, createSnapshot as l, restoreDeprecatedModelRequestBehaviors as m, rollbackAttributes as r, serialize as s, unloadRecord as u };