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