@ember-data/model 4.12.8 → 4.13.0-alpha.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 (91) hide show
  1. package/README.md +19 -0
  2. package/addon-main.cjs +5 -0
  3. package/blueprints/model/index.js +18 -5
  4. package/blueprints/model-test/index.js +16 -10
  5. package/blueprints/model-test/qunit-files/__root__/__path__/__test__.js +4 -5
  6. package/dist/-private.js +2 -0
  7. package/dist/-private.js.map +1 -0
  8. package/dist/has-many-CshPdrqR.js +842 -0
  9. package/dist/has-many-CshPdrqR.js.map +1 -0
  10. package/dist/hooks-DCYCaSEL.js +75 -0
  11. package/dist/hooks-DCYCaSEL.js.map +1 -0
  12. package/dist/hooks.js +2 -0
  13. package/dist/hooks.js.map +1 -0
  14. package/dist/index.js +4 -0
  15. package/{addon → dist}/index.js.map +1 -1
  16. package/{addon/has-many-d45aa09e.js → dist/legacy-relationships-support-D5m0xTYg.js} +5532 -5533
  17. package/dist/legacy-relationships-support-D5m0xTYg.js.map +1 -0
  18. package/dist/migration-support.js +210 -0
  19. package/dist/migration-support.js.map +1 -0
  20. package/dist/schema-provider-m94yB7iS.js +294 -0
  21. package/dist/schema-provider-m94yB7iS.js.map +1 -0
  22. package/ember-data-logo-dark.svg +12 -0
  23. package/ember-data-logo-light.svg +12 -0
  24. package/package.json +78 -44
  25. package/unstable-preview-types/-private/attr.d.ts +175 -0
  26. package/unstable-preview-types/-private/attr.d.ts.map +1 -0
  27. package/unstable-preview-types/-private/attr.type-test.d.ts +4 -0
  28. package/unstable-preview-types/-private/attr.type-test.d.ts.map +1 -0
  29. package/unstable-preview-types/-private/belongs-to.d.ts +180 -0
  30. package/unstable-preview-types/-private/belongs-to.d.ts.map +1 -0
  31. package/unstable-preview-types/-private/belongs-to.type-test.d.ts +4 -0
  32. package/unstable-preview-types/-private/belongs-to.type-test.d.ts.map +1 -0
  33. package/unstable-preview-types/-private/debug/assert-polymorphic-type.d.ts +8 -0
  34. package/unstable-preview-types/-private/debug/assert-polymorphic-type.d.ts.map +1 -0
  35. package/unstable-preview-types/-private/deprecated-promise-proxy.d.ts +5 -0
  36. package/unstable-preview-types/-private/deprecated-promise-proxy.d.ts.map +1 -0
  37. package/unstable-preview-types/-private/errors.d.ts +303 -0
  38. package/unstable-preview-types/-private/errors.d.ts.map +1 -0
  39. package/unstable-preview-types/-private/has-many.d.ts +169 -0
  40. package/unstable-preview-types/-private/has-many.d.ts.map +1 -0
  41. package/unstable-preview-types/-private/has-many.type-test.d.ts +4 -0
  42. package/unstable-preview-types/-private/has-many.type-test.d.ts.map +1 -0
  43. package/unstable-preview-types/-private/hooks.d.ts +13 -0
  44. package/unstable-preview-types/-private/hooks.d.ts.map +1 -0
  45. package/unstable-preview-types/-private/legacy-relationships-support.d.ts +60 -0
  46. package/unstable-preview-types/-private/legacy-relationships-support.d.ts.map +1 -0
  47. package/unstable-preview-types/-private/many-array.d.ts +196 -0
  48. package/unstable-preview-types/-private/many-array.d.ts.map +1 -0
  49. package/unstable-preview-types/-private/model-for-mixin.d.ts +6 -0
  50. package/unstable-preview-types/-private/model-for-mixin.d.ts.map +1 -0
  51. package/unstable-preview-types/-private/model-methods.d.ts +37 -0
  52. package/unstable-preview-types/-private/model-methods.d.ts.map +1 -0
  53. package/unstable-preview-types/-private/model.d.ts +1305 -0
  54. package/unstable-preview-types/-private/model.d.ts.map +1 -0
  55. package/unstable-preview-types/-private/model.type-test.d.ts +4 -0
  56. package/unstable-preview-types/-private/model.type-test.d.ts.map +1 -0
  57. package/unstable-preview-types/-private/notify-changes.d.ts +8 -0
  58. package/unstable-preview-types/-private/notify-changes.d.ts.map +1 -0
  59. package/unstable-preview-types/-private/promise-belongs-to.d.ts +46 -0
  60. package/unstable-preview-types/-private/promise-belongs-to.d.ts.map +1 -0
  61. package/unstable-preview-types/-private/promise-many-array.d.ts +130 -0
  62. package/unstable-preview-types/-private/promise-many-array.d.ts.map +1 -0
  63. package/unstable-preview-types/-private/record-state.d.ts +90 -0
  64. package/unstable-preview-types/-private/record-state.d.ts.map +1 -0
  65. package/unstable-preview-types/-private/references/belongs-to.d.ts +503 -0
  66. package/unstable-preview-types/-private/references/belongs-to.d.ts.map +1 -0
  67. package/unstable-preview-types/-private/references/has-many.d.ts +515 -0
  68. package/unstable-preview-types/-private/references/has-many.d.ts.map +1 -0
  69. package/unstable-preview-types/-private/relationship-meta.d.ts +35 -0
  70. package/unstable-preview-types/-private/relationship-meta.d.ts.map +1 -0
  71. package/unstable-preview-types/-private/schema-provider.d.ts +64 -0
  72. package/unstable-preview-types/-private/schema-provider.d.ts.map +1 -0
  73. package/unstable-preview-types/-private/type-utils.d.ts +64 -0
  74. package/unstable-preview-types/-private/type-utils.d.ts.map +1 -0
  75. package/unstable-preview-types/-private/util.d.ts +8 -0
  76. package/unstable-preview-types/-private/util.d.ts.map +1 -0
  77. package/unstable-preview-types/-private.d.ts +13 -0
  78. package/unstable-preview-types/-private.d.ts.map +1 -0
  79. package/unstable-preview-types/hooks.d.ts +5 -0
  80. package/unstable-preview-types/hooks.d.ts.map +1 -0
  81. package/unstable-preview-types/index.d.ts +78 -0
  82. package/unstable-preview-types/index.d.ts.map +1 -0
  83. package/unstable-preview-types/migration-support.d.ts +56 -0
  84. package/unstable-preview-types/migration-support.d.ts.map +1 -0
  85. package/addon/-private.js +0 -95
  86. package/addon/-private.js.map +0 -1
  87. package/addon/has-many-d45aa09e.js.map +0 -1
  88. package/addon/index.js +0 -1
  89. package/addon-main.js +0 -93
  90. package/blueprints/model-test/mocha-files/__root__/__path__/__test__.js +0 -18
  91. package/blueprints/model-test/mocha-rfc-232-files/__root__/__path__/__test__.js +0 -15
@@ -0,0 +1,842 @@
1
+ import { computed } from '@ember/object';
2
+ import { recordIdentifierFor } from '@ember-data/store';
3
+ import { peekCache } from '@ember-data/store/-private';
4
+ import { k as isElementDescriptor, l as lookupLegacySupport } from "./legacy-relationships-support-D5m0xTYg.js";
5
+ import { macroCondition, getGlobalConfig } from '@embroider/macros';
6
+ import { deprecate, warn, inspect } from '@ember/debug';
7
+ import { singularize, dasherize } from '@ember-data/request-utils/string';
8
+ import { RecordStore } from '@warp-drive/core-types/symbols';
9
+
10
+ /**
11
+ @module @ember-data/model
12
+ */
13
+ function _attr(type, options) {
14
+ if (typeof type === 'object') {
15
+ options = type;
16
+ type = undefined;
17
+ } else {
18
+ options = options || {};
19
+ }
20
+ const meta = {
21
+ type: type,
22
+ kind: 'attribute',
23
+ isAttribute: true,
24
+ options: options,
25
+ key: null
26
+ };
27
+ return computed({
28
+ get(key) {
29
+ if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
30
+ if (['currentState'].includes(key)) {
31
+ throw new Error(`'${key}' is a reserved property name on instances of classes extending Model. Please choose a different property name for your attr on ${this.constructor.toString()}`);
32
+ }
33
+ }
34
+ if (this.isDestroyed || this.isDestroying) {
35
+ return;
36
+ }
37
+ return peekCache(this).getAttr(recordIdentifierFor(this), key);
38
+ },
39
+ set(key, value) {
40
+ if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
41
+ if (['currentState'].includes(key)) {
42
+ throw new Error(`'${key}' is a reserved property name on instances of classes extending Model. Please choose a different property name for your attr on ${this.constructor.toString()}`);
43
+ }
44
+ }
45
+ const identifier = recordIdentifierFor(this);
46
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
47
+ if (!test) {
48
+ throw new Error(`Attempted to set '${key}' on the deleted record ${identifier.type}:${identifier.id} (${identifier.lid})`);
49
+ }
50
+ })(!this.currentState.isDeleted) : {};
51
+ const cache = peekCache(this);
52
+ const currentValue = cache.getAttr(identifier, key);
53
+ if (currentValue !== value) {
54
+ cache.setAttr(identifier, key, value);
55
+ if (!this.isValid) {
56
+ const {
57
+ errors
58
+ } = this;
59
+ if (errors.get(key)) {
60
+ errors.remove(key);
61
+ this.currentState.cleanErrorRequests();
62
+ }
63
+ }
64
+ }
65
+ return value;
66
+ }
67
+ }).meta(meta);
68
+ }
69
+
70
+ // NOTE: Usage of Explicit ANY
71
+ // -------------------------------------------------------------------
72
+ // any is required here because we are the maximal not the minimal
73
+ // subset of options allowed. If we used unknown, object, or
74
+ // Record<string, unknown> we would get type errors when we try to
75
+ // assert against a more specific implementation with precise options.
76
+ // -------------------------------------------------------------------
77
+
78
+ // see note on Explicit ANY above
79
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
80
+
81
+ /**
82
+ * The return type of `void` is a lie to appease TypeScript. The actual return type
83
+ * is a descriptor, but typescript incorrectly insists that decorator functions return
84
+ * `void` or `any`.
85
+ *
86
+ * @typedoc
87
+ */
88
+
89
+ /**
90
+ `attr` defines an attribute on a [Model](/ember-data/release/classes/Model).
91
+ By default, attributes are passed through as-is, however you can specify an
92
+ optional type to have the value automatically transformed.
93
+ EmberData ships with four basic transform types: `string`, `number`,
94
+ `boolean` and `date`. You can define your own transforms by subclassing
95
+ [Transform](/ember-data/release/classes/Transform).
96
+
97
+ Note that you cannot use `attr` to define an attribute of `id`.
98
+
99
+ `attr` takes an optional hash as a second parameter, currently
100
+ supported options are:
101
+
102
+ - `defaultValue`: Pass a string or a function to be called to set the attribute
103
+ to a default value if and only if the key is absent from the payload response.
104
+
105
+ Example
106
+
107
+ ```app/models/user.js
108
+ import Model, { attr } from '@ember-data/model';
109
+
110
+ export default class UserModel extends Model {
111
+ @attr('string') username;
112
+ @attr('string') email;
113
+ @attr('boolean', { defaultValue: false }) verified;
114
+ }
115
+ ```
116
+
117
+ Default value can also be a function. This is useful it you want to return
118
+ a new object for each attribute.
119
+
120
+ ```app/models/user.js
121
+ import Model, { attr } from '@ember-data/model';
122
+
123
+ export default class UserModel extends Model {
124
+ @attr('string') username;
125
+ @attr('string') email;
126
+
127
+ @attr({
128
+ defaultValue() {
129
+ return {};
130
+ }
131
+ })
132
+ settings;
133
+ }
134
+ ```
135
+
136
+ The `options` hash is passed as second argument to a transforms'
137
+ `serialize` and `deserialize` method. This allows to configure a
138
+ transformation and adapt the corresponding value, based on the config:
139
+
140
+ ```app/models/post.js
141
+ import Model, { attr } from '@ember-data/model';
142
+
143
+ export default class PostModel extends Model {
144
+ @attr('text', {
145
+ uppercase: true
146
+ })
147
+ text;
148
+ }
149
+ ```
150
+
151
+ ```app/transforms/text.js
152
+ export default class TextTransform {
153
+ serialize(value, options) {
154
+ if (options.uppercase) {
155
+ return value.toUpperCase();
156
+ }
157
+
158
+ return value;
159
+ }
160
+
161
+ deserialize(value) {
162
+ return value;
163
+ }
164
+
165
+ static create() {
166
+ return new this();
167
+ }
168
+ }
169
+ ```
170
+
171
+ @method attr
172
+ @public
173
+ @static
174
+ @for @ember-data/model
175
+ @param {String|Object} type the attribute type
176
+ @param {Object} options a hash of options
177
+ @return {Attribute}
178
+ */
179
+
180
+ // see note on DataDecorator for why void
181
+ function attr(type, options, desc) {
182
+ const args = [type, options, desc];
183
+ // see note on DataDecorator for why void
184
+ return isElementDescriptor(args) ? _attr()(...args) : _attr(type, options);
185
+ }
186
+
187
+ // get: () => getT;
188
+ // // set: (value: Awaited<getT>) => void;
189
+ // set: (value: getT) => void;
190
+ // // init: () => getT;
191
+ // };
192
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
193
+ // BelongsToDecoratorObject<getT>;
194
+
195
+ function normalizeType$1(type) {
196
+ if (macroCondition(getGlobalConfig().WarpDrive.deprecations.DEPRECATE_RELATIONSHIPS_WITHOUT_TYPE)) {
197
+ if (!type) {
198
+ return;
199
+ }
200
+ }
201
+ if (macroCondition(getGlobalConfig().WarpDrive.deprecations.DEPRECATE_NON_STRICT_TYPES)) {
202
+ const result = singularize(dasherize(type));
203
+ deprecate(`The resource type '${type}' is not normalized. Update your application code to use '${result}' instead of '${type}'.`, /* inline-macro-config */getGlobalConfig().WarpDrive.deprecations.DISABLE_6X_DEPRECATIONS ? true : result === type, {
204
+ id: 'ember-data:deprecate-non-strict-types',
205
+ until: '6.0',
206
+ for: 'ember-data',
207
+ since: {
208
+ available: '4.13',
209
+ enabled: '5.3'
210
+ }
211
+ });
212
+ return result;
213
+ }
214
+ return type;
215
+ }
216
+ function _belongsTo(type, options) {
217
+ let opts = options;
218
+ let rawType = type;
219
+ if (macroCondition(getGlobalConfig().WarpDrive.deprecations.DEPRECATE_RELATIONSHIPS_WITHOUT_TYPE)) {
220
+ if (typeof type !== 'string' || !type.length) {
221
+ deprecate('belongsTo() must specify the string type of the related resource as the first parameter', false, {
222
+ id: 'ember-data:deprecate-non-strict-relationships',
223
+ for: 'ember-data',
224
+ until: '5.0',
225
+ since: {
226
+ enabled: '4.7',
227
+ available: '4.7'
228
+ }
229
+ });
230
+ if (typeof type === 'object') {
231
+ opts = type;
232
+ rawType = undefined;
233
+ } else {
234
+ opts = options;
235
+ rawType = type;
236
+ }
237
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
238
+ if (!test) {
239
+ throw new Error('The first argument to belongsTo must be a string representing a model type key, not an instance of ' + typeof rawType + ". E.g., to define a relation to the Person model, use belongsTo('person')");
240
+ }
241
+ })(typeof rawType === 'string' || typeof rawType === 'undefined') : {};
242
+ }
243
+ }
244
+ if (macroCondition(getGlobalConfig().WarpDrive.deprecations.DEPRECATE_RELATIONSHIPS_WITHOUT_ASYNC)) {
245
+ if (!opts || typeof opts.async !== 'boolean') {
246
+ opts = opts || {};
247
+ if (!('async' in opts)) {
248
+ // @ts-expect-error the inbound signature is strict to convince the user to use the non-deprecated signature
249
+ opts.async = true;
250
+ }
251
+ deprecate('belongsTo(<type>, <options>) must specify options.async as either `true` or `false`.', false, {
252
+ id: 'ember-data:deprecate-non-strict-relationships',
253
+ for: 'ember-data',
254
+ until: '5.0',
255
+ since: {
256
+ enabled: '4.7',
257
+ available: '4.7'
258
+ }
259
+ });
260
+ } else {
261
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
262
+ if (!test) {
263
+ throw new Error(`Expected belongsTo options.async to be a boolean`);
264
+ }
265
+ })(opts && typeof opts.async === 'boolean') : {};
266
+ }
267
+ } else {
268
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
269
+ if (!test) {
270
+ throw new Error(`Expected belongsTo options.async to be a boolean`);
271
+ }
272
+ })(opts && typeof opts.async === 'boolean') : {};
273
+ }
274
+ if (macroCondition(getGlobalConfig().WarpDrive.deprecations.DEPRECATE_RELATIONSHIPS_WITHOUT_INVERSE)) {
275
+ if (opts.inverse !== null && (typeof opts.inverse !== 'string' || opts.inverse.length === 0)) {
276
+ deprecate('belongsTo(<type>, <options>) must specify options.inverse as either `null` or the name of the field on the related resource type.', false, {
277
+ id: 'ember-data:deprecate-non-strict-relationships',
278
+ for: 'ember-data',
279
+ until: '5.0',
280
+ since: {
281
+ enabled: '4.7',
282
+ available: '4.7'
283
+ }
284
+ });
285
+ } else {
286
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
287
+ if (!test) {
288
+ throw new Error(`Expected belongsTo options.inverse to be either null or the string type of the related resource.`);
289
+ }
290
+ })(opts.inverse === null || typeof opts.inverse === 'string' && opts.inverse.length > 0) : {};
291
+ }
292
+ } else {
293
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
294
+ if (!test) {
295
+ throw new Error(`Expected belongsTo options.inverse to be either null or the string type of the related resource.`);
296
+ }
297
+ })(opts.inverse === null || typeof opts.inverse === 'string' && opts.inverse.length > 0) : {};
298
+ }
299
+ const meta = {
300
+ type: normalizeType$1(type),
301
+ options: opts,
302
+ kind: 'belongsTo',
303
+ name: '<Unknown BelongsTo>'
304
+ };
305
+ return computed({
306
+ get(key) {
307
+ // this is a legacy behavior we may not carry into a new model setup
308
+ // it's better to error on disconnected records so users find errors
309
+ // in their logic.
310
+ if (this.isDestroying || this.isDestroyed) {
311
+ return null;
312
+ }
313
+ const support = lookupLegacySupport(this);
314
+ if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
315
+ if (['currentState'].includes(key)) {
316
+ throw new Error(`'${key}' is a reserved property name on instances of classes extending Model. Please choose a different property name for your belongsTo on ${this.constructor.toString()}`);
317
+ }
318
+ if (Object.prototype.hasOwnProperty.call(options, 'serialize')) {
319
+ warn(`You provided a serialize option on the "${key}" property in the "${support.identifier.type}" class, this belongs in the serializer. See Serializer and it's implementations https://api.emberjs.com/ember-data/release/classes/Serializer`, false, {
320
+ id: 'ds.model.serialize-option-in-belongs-to'
321
+ });
322
+ }
323
+ if (Object.prototype.hasOwnProperty.call(options, 'embedded')) {
324
+ warn(`You provided an embedded option on the "${key}" property in the "${support.identifier.type}" class, this belongs in the serializer. See EmbeddedRecordsMixin https://api.emberjs.com/ember-data/release/classes/EmbeddedRecordsMixin`, false, {
325
+ id: 'ds.model.embedded-option-in-belongs-to'
326
+ });
327
+ }
328
+ }
329
+ return support.getBelongsTo(key);
330
+ },
331
+ set(key, value) {
332
+ const support = lookupLegacySupport(this);
333
+ if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
334
+ if (['currentState'].includes(key)) {
335
+ throw new Error(`'${key}' is a reserved property name on instances of classes extending Model. Please choose a different property name for your belongsTo on ${this.constructor.toString()}`);
336
+ }
337
+ }
338
+ this[RecordStore]._join(() => {
339
+ support.setDirtyBelongsTo(key, value);
340
+ });
341
+ return support.getBelongsTo(key);
342
+ }
343
+ }).meta(meta);
344
+ }
345
+
346
+ /**
347
+ `belongsTo` is used to define One-To-One and One-To-Many, and One-To-None
348
+ relationships on a [Model](/ember-data/release/classes/Model).
349
+
350
+ `belongsTo` takes a configuration hash as a second parameter, currently
351
+ supported options are:
352
+
353
+ - `async`: (*required*) A boolean value used to declare whether this is a sync (false) or async (true) relationship.
354
+ - `inverse`: (*required*) A string used to identify the inverse property on a related model, or `null`.
355
+ - `polymorphic`: (*optional*) A boolean value to mark the relationship as polymorphic
356
+ - `as`: (*optional*) A string used to declare the abstract type "this" record satisfies for polymorphism.
357
+
358
+ ### Examples
359
+
360
+ To declare a **one-to-many** (or many-to-many) relationship, use
361
+ `belongsTo` in combination with `hasMany`:
362
+
363
+ ```js
364
+ // app/models/comment.js
365
+ import Model, { belongsTo } from '@ember-data/model';
366
+
367
+ export default class Comment extends Model {
368
+ @belongsTo('post', { async: false, inverse: 'comments' }) post;
369
+ }
370
+
371
+ // app/models/post.js
372
+ import Model, { hasMany } from '@ember-data/model';
373
+
374
+ export default class Post extends Model {
375
+ @hasMany('comment', { async: false, inverse: 'post' }) comments;
376
+ }
377
+ ```
378
+
379
+ To declare a **one-to-one** relationship with managed inverses, use `belongsTo` for both sides:
380
+
381
+ ```js
382
+ // app/models/author.js
383
+ import Model, { belongsTo } from '@ember-data/model';
384
+
385
+ export default class Author extends Model {
386
+ @belongsTo('address', { async: true, inverse: 'owner' }) address;
387
+ }
388
+
389
+ // app/models/address.js
390
+ import Model, { belongsTo } from '@ember-data/model';
391
+
392
+ export default class Address extends Model {
393
+ @belongsTo('author', { async: true, inverse: 'address' }) owner;
394
+ }
395
+ ```
396
+
397
+ To declare a **one-to-one** relationship without managed inverses, use `belongsTo` for both sides
398
+ with `null` as the inverse:
399
+
400
+ ```js
401
+ // app/models/author.js
402
+ import Model, { belongsTo } from '@ember-data/model';
403
+
404
+ export default class Author extends Model {
405
+ @belongsTo('address', { async: true, inverse: null }) address;
406
+ }
407
+
408
+ // app/models/address.js
409
+ import Model, { belongsTo } from '@ember-data/model';
410
+
411
+ export default class Address extends Model {
412
+ @belongsTo('author', { async: true, inverse: null }) owner;
413
+ }
414
+ ```
415
+
416
+ To declare a one-to-none relationship between two models, use
417
+ `belongsTo` with inverse set to `null` on just one side::
418
+
419
+ ```js
420
+ // app/models/person.js
421
+ import Model, { belongsTo } from '@ember-data/model';
422
+
423
+ export default class Person extends Model {
424
+ @belongsTo('person', { async: false, inverse: null }) bestFriend;
425
+ }
426
+ ```
427
+
428
+ #### Sync vs Async Relationships
429
+
430
+ EmberData fulfills relationships using resource data available in
431
+ the cache.
432
+
433
+ Sync relationships point directly to the known related resources.
434
+
435
+ When a relationship is declared as async, if any of the known related
436
+ resources have not been loaded, they will be fetched. The property
437
+ on the record when accessed provides a promise that resolves once
438
+ all resources are loaded.
439
+
440
+ Async relationships may take advantage of links. On access, if the related
441
+ link has not been loaded, or if any known resources are not available in
442
+ the cache, the fresh state will be fetched using the link.
443
+
444
+ In contrast to async relationship, accessing a sync relationship
445
+ will error on access when any of the known related resources have
446
+ not been loaded.
447
+
448
+ If you are using `links` with sync relationships, you have to use
449
+ the BelongsTo reference API to fetch or refresh related resources
450
+ that aren't loaded. For instance, for a `bestFriend` relationship:
451
+
452
+ ```js
453
+ person.belongsTo('bestFriend').reload();
454
+ ```
455
+
456
+ #### Polymorphic Relationships
457
+
458
+ To declare a polymorphic relationship, use `hasMany` with the `polymorphic`
459
+ option set to `true`:
460
+
461
+ ```js
462
+ // app/models/comment.js
463
+ import Model, { belongsTo } from '@ember-data/model';
464
+
465
+ export default class Comment extends Model {
466
+ @belongsTo('commentable', { async: false, inverse: 'comments', polymorphic: true }) parent;
467
+ }
468
+ ```
469
+
470
+ `'commentable'` here is referred to as the "abstract type" for the polymorphic
471
+ relationship.
472
+
473
+ Polymorphic relationships with `inverse: null` will accept any type of record as their content.
474
+ Polymorphic relationships with `inverse` set to a string will only accept records with a matching
475
+ inverse relationships declaring itself as satisfying the abstract type.
476
+
477
+ Below, 'as' is used to declare the that 'post' record satisfies the abstract type 'commentable'
478
+ for this relationship.
479
+
480
+ ```js
481
+ // app/models/post.js
482
+ import Model, { hasMany } from '@ember-data/model';
483
+
484
+ export default class Post extends Model {
485
+ @hasMany('comment', { async: false, inverse: 'parent', as: 'commentable' }) comments;
486
+ }
487
+ ```
488
+
489
+ Note: every Model that declares an inverse to a polymorphic relationship must
490
+ declare itself exactly the same. This is because polymorphism is based on structural
491
+ traits.
492
+
493
+ Polymorphic to polymorphic relationships are supported. Both sides of the relationship
494
+ must be declared as polymorphic, and the `as` option must be used to declare the abstract
495
+ type each record satisfies on both sides.
496
+
497
+ @method belongsTo
498
+ @public
499
+ @static
500
+ @for @ember-data/model
501
+ @param {string} type (optional) the name of the related resource
502
+ @param {object} options (optional) a hash of options
503
+ @return {PropertyDescriptor} relationship
504
+ */
505
+
506
+ // export function belongsTo<K extends Promise<unknown>, T extends Awaited<K> = Awaited<K>>(
507
+ // type: TypeFromInstance<NoNull<T>>,
508
+ // options: RelationshipOptions<T, true>
509
+ // ): RelationshipDecorator<K>;
510
+
511
+ function belongsTo(type, options) {
512
+ if (macroCondition(!getGlobalConfig().WarpDrive.deprecations.DEPRECATE_RELATIONSHIPS_WITHOUT_TYPE)) {
513
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
514
+ if (!test) {
515
+ throw new Error(`belongsTo must be invoked with a type and options. Did you mean \`@belongsTo(<type>, { async: false, inverse: null })\`?`);
516
+ }
517
+ })(!isElementDescriptor(arguments)) : {};
518
+ return _belongsTo(type, options);
519
+ } else {
520
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
521
+ return isElementDescriptor(arguments) ?
522
+ // @ts-expect-error the inbound signature is strict to convince the user to use the non-deprecated signature
523
+ _belongsTo()(...arguments) : _belongsTo(type, options);
524
+ }
525
+ }
526
+
527
+ /**
528
+ @module @ember-data/model
529
+ */
530
+ function normalizeType(type) {
531
+ if (macroCondition(getGlobalConfig().WarpDrive.deprecations.DEPRECATE_RELATIONSHIPS_WITHOUT_TYPE)) {
532
+ if (!type) {
533
+ return;
534
+ }
535
+ }
536
+ if (macroCondition(getGlobalConfig().WarpDrive.deprecations.DEPRECATE_NON_STRICT_TYPES)) {
537
+ const result = singularize(dasherize(type));
538
+ deprecate(`The resource type '${type}' is not normalized. Update your application code to use '${result}' instead of '${type}'.`, /* inline-macro-config */getGlobalConfig().WarpDrive.deprecations.DISABLE_6X_DEPRECATIONS ? true : result === type, {
539
+ id: 'ember-data:deprecate-non-strict-types',
540
+ until: '6.0',
541
+ for: 'ember-data',
542
+ since: {
543
+ available: '4.13',
544
+ enabled: '5.3'
545
+ }
546
+ });
547
+ return result;
548
+ }
549
+ return type;
550
+ }
551
+ function _hasMany(type, options) {
552
+ if (macroCondition(getGlobalConfig().WarpDrive.deprecations.DEPRECATE_RELATIONSHIPS_WITHOUT_TYPE)) {
553
+ if (typeof type !== 'string' || !type.length) {
554
+ deprecate('hasMany(<type>, <options>) must specify the string type of the related resource as the first parameter', false, {
555
+ id: 'ember-data:deprecate-non-strict-relationships',
556
+ for: 'ember-data',
557
+ until: '5.0',
558
+ since: {
559
+ enabled: '4.7',
560
+ available: '4.7'
561
+ }
562
+ });
563
+ if (typeof type === 'object') {
564
+ options = type;
565
+ type = undefined;
566
+ }
567
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
568
+ if (!test) {
569
+ throw new Error(`The first argument to hasMany must be a string representing a model type key, not an instance of ${inspect(type)}. E.g., to define a relation to the Comment model, use hasMany('comment')`);
570
+ }
571
+ })(typeof type === 'string' || typeof type === 'undefined') : {};
572
+ }
573
+ }
574
+ if (macroCondition(getGlobalConfig().WarpDrive.deprecations.DEPRECATE_RELATIONSHIPS_WITHOUT_ASYNC)) {
575
+ if (!options || typeof options.async !== 'boolean') {
576
+ options = options || {};
577
+ if (!('async' in options)) {
578
+ // @ts-expect-error the inbound signature is strict to convince the user to use the non-deprecated signature
579
+ options.async = true;
580
+ }
581
+ deprecate('hasMany(<type>, <options>) must specify options.async as either `true` or `false`.', false, {
582
+ id: 'ember-data:deprecate-non-strict-relationships',
583
+ for: 'ember-data',
584
+ until: '5.0',
585
+ since: {
586
+ enabled: '4.7',
587
+ available: '4.7'
588
+ }
589
+ });
590
+ } else {
591
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
592
+ if (!test) {
593
+ throw new Error(`Expected hasMany options.async to be a boolean`);
594
+ }
595
+ })(options && typeof options.async === 'boolean') : {};
596
+ }
597
+ } else {
598
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
599
+ if (!test) {
600
+ throw new Error(`Expected hasMany options.async to be a boolean`);
601
+ }
602
+ })(options && typeof options.async === 'boolean') : {};
603
+ }
604
+ if (macroCondition(getGlobalConfig().WarpDrive.deprecations.DEPRECATE_RELATIONSHIPS_WITHOUT_INVERSE)) {
605
+ if (options.inverse !== null && (typeof options.inverse !== 'string' || options.inverse.length === 0)) {
606
+ deprecate('hasMany(<type>, <options>) must specify options.inverse as either `null` or the name of the field on the related resource type.', false, {
607
+ id: 'ember-data:deprecate-non-strict-relationships',
608
+ for: 'ember-data',
609
+ until: '5.0',
610
+ since: {
611
+ enabled: '4.7',
612
+ available: '4.7'
613
+ }
614
+ });
615
+ }
616
+ }
617
+
618
+ // Metadata about relationships is stored on the meta of
619
+ // the relationship. This is used for introspection and
620
+ // serialization. Note that `key` is populated lazily
621
+ // the first time the CP is called.
622
+ const meta = {
623
+ type: normalizeType(type),
624
+ options,
625
+ kind: 'hasMany',
626
+ name: '<Unknown BelongsTo>'
627
+ };
628
+ return computed({
629
+ get(key) {
630
+ if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
631
+ if (['currentState'].includes(key)) {
632
+ throw new Error(`'${key}' is a reserved property name on instances of classes extending Model. Please choose a different property name for your hasMany on ${this.constructor.toString()}`);
633
+ }
634
+ }
635
+ if (this.isDestroying || this.isDestroyed) {
636
+ return [];
637
+ }
638
+ return lookupLegacySupport(this).getHasMany(key);
639
+ },
640
+ set(key, records) {
641
+ if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
642
+ if (['currentState'].includes(key)) {
643
+ throw new Error(`'${key}' is a reserved property name on instances of classes extending Model. Please choose a different property name for your hasMany on ${this.constructor.toString()}`);
644
+ }
645
+ }
646
+ const support = lookupLegacySupport(this);
647
+ const manyArray = support.getManyArray(key);
648
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
649
+ if (!test) {
650
+ throw new Error(`You must pass an array of records to set a hasMany relationship`);
651
+ }
652
+ })(Array.isArray(records)) : {};
653
+ this[RecordStore]._join(() => {
654
+ manyArray.splice(0, manyArray.length, ...records);
655
+ });
656
+ return support.getHasMany(key);
657
+ }
658
+ }).meta(meta);
659
+ }
660
+
661
+ /**
662
+ `hasMany` is used to define Many-To-One and Many-To-Many, and Many-To-None
663
+ relationships on a [Model](/ember-data/release/classes/Model).
664
+
665
+ `hasMany` takes a configuration hash as a second parameter, currently
666
+ supported options are:
667
+
668
+ - `async`: (*required*) A boolean value used to declare whether this is a sync (false) or async (true) relationship.
669
+ - `inverse`: (*required*) A string used to identify the inverse property on a related model, or `null`.
670
+ - `polymorphic`: (*optional*) A boolean value to mark the relationship as polymorphic
671
+ - `as`: (*optional*) A string used to declare the abstract type "this" record satisfies for polymorphism.
672
+
673
+ ### Examples
674
+
675
+ To declare a **many-to-one** (or one-to-many) relationship, use
676
+ `belongsTo` in combination with `hasMany`:
677
+
678
+ ```js
679
+ // app/models/post.js
680
+ import Model, { hasMany } from '@ember-data/model';
681
+
682
+ export default class Post extends Model {
683
+ @hasMany('comment', { async: false, inverse: 'post' }) comments;
684
+ }
685
+
686
+
687
+ // app/models/comment.js
688
+ import Model, { belongsTo } from '@ember-data/model';
689
+
690
+ export default class Comment extends Model {
691
+ @belongsTo('post', { async: false, inverse: 'comments' }) post;
692
+ }
693
+ ```
694
+
695
+ To declare a **many-to-many** relationship with managed inverses, use `hasMany` for both sides:
696
+
697
+ ```js
698
+ // app/models/post.js
699
+ import Model, { hasMany } from '@ember-data/model';
700
+
701
+ export default class Post extends Model {
702
+ @hasMany('tag', { async: true, inverse: 'posts' }) tags;
703
+ }
704
+
705
+ // app/models/tag.js
706
+ import Model, { hasMany } from '@ember-data/model';
707
+
708
+ export default class Tag extends Model {
709
+ @hasMany('post', { async: true, inverse: 'tags' }) posts;
710
+ }
711
+ ```
712
+
713
+ To declare a **many-to-many** relationship without managed inverses, use `hasMany` for both sides
714
+ with `null` as the inverse:
715
+
716
+ ```js
717
+ // app/models/post.js
718
+ import Model, { hasMany } from '@ember-data/model';
719
+
720
+ export default class Post extends Model {
721
+ @hasMany('tag', { async: true, inverse: null }) tags;
722
+ }
723
+
724
+ // app/models/tag.js
725
+ import Model, { hasMany } from '@ember-data/model';
726
+
727
+ export default class Tag extends Model {
728
+ @hasMany('post', { async: true, inverse: null }) posts;
729
+ }
730
+ ```
731
+
732
+ To declare a many-to-none relationship between two models, use
733
+ `hasMany` with inverse set to `null` on just one side::
734
+
735
+ ```js
736
+ // app/models/post.js
737
+ import Model, { hasMany } from '@ember-data/model';
738
+
739
+ export default class Post extends Model {
740
+ @hasMany('category', { async: true, inverse: null }) categories;
741
+ }
742
+ ```
743
+
744
+ #### Sync vs Async Relationships
745
+
746
+ EmberData fulfills relationships using resource data available in
747
+ the cache.
748
+
749
+ Sync relationships point directly to the known related resources.
750
+
751
+ When a relationship is declared as async, if any of the known related
752
+ resources have not been loaded, they will be fetched. The property
753
+ on the record when accessed provides a promise that resolves once
754
+ all resources are loaded.
755
+
756
+ Async relationships may take advantage of links. On access, if the related
757
+ link has not been loaded, or if any known resources are not available in
758
+ the cache, the fresh state will be fetched using the link.
759
+
760
+ In contrast to async relationship, accessing a sync relationship
761
+ will error on access when any of the known related resources have
762
+ not been loaded.
763
+
764
+ If you are using `links` with sync relationships, you have to use
765
+ the HasMany reference API to fetch or refresh related resources
766
+ that aren't loaded. For instance, for a `comments` relationship:
767
+
768
+ ```js
769
+ post.hasMany('comments').reload();
770
+ ```
771
+
772
+ #### Polymorphic Relationships
773
+
774
+ To declare a polymorphic relationship, use `hasMany` with the `polymorphic`
775
+ option set to `true`:
776
+
777
+ ```js
778
+ // app/models/comment.js
779
+ import Model, { belongsTo } from '@ember-data/model';
780
+
781
+ export default class Comment extends Model {
782
+ @belongsTo('commentable', { async: false, inverse: 'comments', polymorphic: true }) parent;
783
+ }
784
+ ```
785
+
786
+ `'commentable'` here is referred to as the "abstract type" for the polymorphic
787
+ relationship.
788
+
789
+ Polymorphic relationships with `inverse: null` will accept any type of record as their content.
790
+ Polymorphic relationships with `inverse` set to a string will only accept records with a matching
791
+ inverse relationships declaring itself as satisfying the abstract type.
792
+
793
+ Below, 'as' is used to declare the that 'post' record satisfies the abstract type 'commentable'
794
+ for this relationship.
795
+
796
+ ```js
797
+ // app/models/post.js
798
+ import Model, { hasMany } from '@ember-data/model';
799
+
800
+ export default class Post extends Model {
801
+ @hasMany('comment', { async: false, inverse: 'parent', as: 'commentable' }) comments;
802
+ }
803
+ ```
804
+
805
+ Note: every Model that declares an inverse to a polymorphic relationship must
806
+ declare itself exactly the same. This is because polymorphism is based on structural
807
+ traits.
808
+
809
+ Polymorphic to polymorphic relationships are supported. Both sides of the relationship
810
+ must be declared as polymorphic, and the `as` option must be used to declare the abstract
811
+ type each record satisfies on both sides.
812
+
813
+ @method hasMany
814
+ @public
815
+ @static
816
+ @for @ember-data/model
817
+ @param {string} type (optional) the name of the related resource
818
+ @param {object} options (optional) a hash of options
819
+ @return {PropertyDescriptor} relationship
820
+ */
821
+
822
+ // export function hasMany<K extends Promise<unknown>, T extends Awaited<K> = Awaited<K>>(
823
+ // type: TypeFromInstance<NoNull<T>>,
824
+ // options: RelationshipOptions<T, true>
825
+ // ): RelationshipDecorator<K>;
826
+
827
+ function hasMany(type, options) {
828
+ if (macroCondition(!getGlobalConfig().WarpDrive.deprecations.DEPRECATE_RELATIONSHIPS_WITHOUT_TYPE)) {
829
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
830
+ if (!test) {
831
+ throw new Error(`hasMany must be invoked with a type and options. Did you mean \`@hasMany(<type>, { async: false, inverse: null })\`?`);
832
+ }
833
+ })(!isElementDescriptor(arguments)) : {};
834
+ return _hasMany(type, options);
835
+ } else {
836
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
837
+ return isElementDescriptor(arguments) ?
838
+ // @ts-expect-error the inbound signature is strict to convince the user to use the non-deprecated signature
839
+ _hasMany()(...arguments) : _hasMany(type, options);
840
+ }
841
+ }
842
+ export { attr as a, belongsTo as b, hasMany as h };