@warp-drive/legacy 5.8.0-beta.0 → 5.8.0-beta.1

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