@warp-drive/legacy 5.6.0-alpha.11

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