@warp-drive/core 5.8.0-alpha.9 → 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 (258) hide show
  1. package/README.md +22 -38
  2. package/declarations/configure.d.ts +1 -1
  3. package/declarations/graph/-private/-edge-definition.d.ts +12 -2
  4. package/declarations/index.d.ts +14 -9
  5. package/declarations/reactive/-private/default-mode.d.ts +1 -1
  6. package/declarations/reactive/-private/fields/extension.d.ts +1 -1
  7. package/declarations/reactive/-private/fields/managed-array.d.ts +2 -2
  8. package/declarations/reactive/-private/fields/managed-object.d.ts +1 -1
  9. package/declarations/reactive/-private/record.d.ts +10 -1
  10. package/declarations/reactive/-private.d.ts +1 -0
  11. package/declarations/reactive.d.ts +11 -7
  12. package/declarations/request/-private/types.d.ts +1 -1
  13. package/declarations/signals/-leaked.d.ts +2 -0
  14. package/declarations/signals/-private.d.ts +6 -0
  15. package/declarations/{store/-private/new-core-tmp → signals}/promise-state.d.ts +1 -1
  16. package/declarations/{store/-private/new-core-tmp → signals}/request-state.d.ts +6 -6
  17. package/declarations/{store/-private/new-core-tmp → signals}/request-subscription.d.ts +4 -4
  18. package/declarations/store/-private/cache-handler/types.d.ts +2 -16
  19. package/declarations/store/-private/caches/instance-cache.d.ts +1 -1
  20. package/declarations/store/-private/managers/cache-manager.d.ts +1 -14
  21. package/declarations/store/-private/managers/notification-manager.d.ts +1 -1
  22. package/declarations/store/-private/record-arrays/legacy-many-array.d.ts +1 -1
  23. package/declarations/store/-private/record-arrays/resource-array.d.ts +1 -1
  24. package/declarations/store/-private/store-service.d.ts +2 -2
  25. package/declarations/store/-private.d.ts +0 -6
  26. package/declarations/store/deprecated/-private.d.ts +2 -2
  27. package/declarations/store/deprecated/store.d.ts +1 -1
  28. package/declarations/store.d.ts +1 -0
  29. package/declarations/types/cache.d.ts +2 -2
  30. package/declarations/types/record.d.ts +132 -0
  31. package/declarations/types/request.d.ts +22 -8
  32. package/declarations/types/schema/fields.d.ts +26 -13
  33. package/declarations/types/schema/schema-service.d.ts +4 -4
  34. package/declarations/types/spec/document.d.ts +34 -0
  35. package/dist/configure-DPUFCemT.js +1940 -0
  36. package/dist/configure.js +2 -1
  37. package/dist/{request-oqoLC9rz.js → future-BKkJJkj7.js} +1 -48
  38. package/dist/graph/-private.js +15 -5
  39. package/dist/{index-B1cSRj-N.js → index-CQP2NSqg.js} +63 -1812
  40. package/dist/index.js +5 -5
  41. package/dist/reactive/-private.js +1 -1
  42. package/dist/reactive.js +4 -129
  43. package/dist/request.js +49 -1
  44. package/dist/signals/-leaked.js +1 -0
  45. package/dist/store/-private.js +1 -2
  46. package/dist/symbols-3C1OkYtZ.js +39 -0
  47. package/dist/types/-private.js +1 -1
  48. package/dist/types/record.js +127 -0
  49. package/dist/types/request.js +11 -7
  50. package/dist/unpkg/dev/-leaked-Co0EI6Go.js +1939 -0
  51. package/dist/unpkg/dev/build-config/babel-macros.js +1 -0
  52. package/dist/unpkg/dev/build-config/canary-features.js +1 -0
  53. package/dist/unpkg/dev/build-config/debugging.js +1 -0
  54. package/dist/unpkg/dev/build-config/deprecations.js +1 -0
  55. package/dist/unpkg/dev/build-config/env.js +1 -0
  56. package/dist/unpkg/dev/build-config/macros.js +1 -0
  57. package/dist/unpkg/dev/build-config.js +1 -0
  58. package/dist/unpkg/dev/configure.js +1 -0
  59. package/dist/unpkg/dev/future-DFfOzSoe.js +672 -0
  60. package/dist/unpkg/dev/graph/-private.js +3132 -0
  61. package/dist/unpkg/dev/index-BzcBOnw9.js +9392 -0
  62. package/dist/unpkg/dev/index.js +6 -0
  63. package/dist/unpkg/dev/reactive/-private.js +1 -0
  64. package/dist/unpkg/dev/reactive.js +3 -0
  65. package/dist/unpkg/dev/request.js +49 -0
  66. package/dist/unpkg/dev/runtime-E1M51_-O.js +135 -0
  67. package/dist/unpkg/dev/signals/-leaked.js +1 -0
  68. package/dist/unpkg/dev/store/-private.js +55 -0
  69. package/dist/unpkg/dev/store.js +558 -0
  70. package/dist/unpkg/dev/types/-private.js +69 -0
  71. package/dist/unpkg/dev/types/cache/aliases.js +0 -0
  72. package/dist/unpkg/dev/types/cache/change.js +0 -0
  73. package/dist/unpkg/dev/types/cache/mutations.js +0 -0
  74. package/dist/unpkg/dev/types/cache/operations.js +0 -0
  75. package/dist/unpkg/dev/types/cache/relationship.js +0 -0
  76. package/dist/unpkg/dev/types/cache.js +0 -0
  77. package/dist/unpkg/dev/types/graph.js +0 -0
  78. package/dist/unpkg/dev/types/identifier.js +61 -0
  79. package/dist/unpkg/dev/types/json/raw.js +0 -0
  80. package/dist/unpkg/dev/types/params.js +0 -0
  81. package/dist/unpkg/dev/types/record.js +191 -0
  82. package/dist/unpkg/dev/types/request.js +77 -0
  83. package/dist/unpkg/dev/types/runtime.js +34 -0
  84. package/dist/unpkg/dev/types/schema/concepts.js +0 -0
  85. package/dist/unpkg/dev/types/schema/fields.js +505 -0
  86. package/dist/unpkg/dev/types/schema/fields.type-test.js +0 -0
  87. package/dist/unpkg/dev/types/schema/schema-service.js +0 -0
  88. package/dist/unpkg/dev/types/spec/document.js +0 -0
  89. package/dist/unpkg/dev/types/spec/error.js +0 -0
  90. package/dist/unpkg/dev/types/spec/json-api-raw.js +0 -0
  91. package/dist/unpkg/dev/types/symbols.js +84 -0
  92. package/dist/unpkg/dev/types/utils.js +0 -0
  93. package/dist/unpkg/dev/types.js +0 -0
  94. package/dist/unpkg/dev/utils/string.js +91 -0
  95. package/dist/unpkg/dev-deprecated/-leaked-DjMeRqdU.js +1939 -0
  96. package/dist/unpkg/dev-deprecated/-private-3C1OkYtZ.js +39 -0
  97. package/dist/unpkg/dev-deprecated/build-config/babel-macros.js +1 -0
  98. package/dist/unpkg/dev-deprecated/build-config/canary-features.js +1 -0
  99. package/dist/unpkg/dev-deprecated/build-config/debugging.js +1 -0
  100. package/dist/unpkg/dev-deprecated/build-config/deprecations.js +1 -0
  101. package/dist/unpkg/dev-deprecated/build-config/env.js +1 -0
  102. package/dist/unpkg/dev-deprecated/build-config/macros.js +1 -0
  103. package/dist/unpkg/dev-deprecated/build-config.js +1 -0
  104. package/dist/unpkg/dev-deprecated/configure.js +1 -0
  105. package/dist/unpkg/dev-deprecated/future-DFfOzSoe.js +672 -0
  106. package/dist/unpkg/dev-deprecated/graph/-private.js +3327 -0
  107. package/dist/unpkg/dev-deprecated/index-6TnTv-WG.js +10007 -0
  108. package/dist/unpkg/dev-deprecated/index.js +5 -0
  109. package/dist/unpkg/dev-deprecated/reactive/-private.js +1 -0
  110. package/dist/unpkg/dev-deprecated/reactive.js +3 -0
  111. package/dist/unpkg/dev-deprecated/request.js +49 -0
  112. package/dist/unpkg/dev-deprecated/runtime-DAu5b0IR.js +135 -0
  113. package/dist/unpkg/dev-deprecated/signals/-leaked.js +1 -0
  114. package/dist/unpkg/dev-deprecated/store/-private.js +1 -0
  115. package/dist/unpkg/dev-deprecated/store.js +558 -0
  116. package/dist/unpkg/dev-deprecated/types/-private.js +69 -0
  117. package/dist/unpkg/dev-deprecated/types/cache/aliases.js +0 -0
  118. package/dist/unpkg/dev-deprecated/types/cache/change.js +0 -0
  119. package/dist/unpkg/dev-deprecated/types/cache/mutations.js +0 -0
  120. package/dist/unpkg/dev-deprecated/types/cache/operations.js +0 -0
  121. package/dist/unpkg/dev-deprecated/types/cache/relationship.js +0 -0
  122. package/dist/unpkg/dev-deprecated/types/cache.js +0 -0
  123. package/dist/unpkg/dev-deprecated/types/graph.js +0 -0
  124. package/dist/unpkg/dev-deprecated/types/identifier.js +61 -0
  125. package/dist/unpkg/dev-deprecated/types/json/raw.js +0 -0
  126. package/dist/unpkg/dev-deprecated/types/params.js +0 -0
  127. package/dist/unpkg/dev-deprecated/types/record.js +191 -0
  128. package/dist/unpkg/dev-deprecated/types/request.js +77 -0
  129. package/dist/unpkg/dev-deprecated/types/runtime.js +34 -0
  130. package/dist/unpkg/dev-deprecated/types/schema/concepts.js +0 -0
  131. package/dist/unpkg/dev-deprecated/types/schema/fields.js +505 -0
  132. package/dist/unpkg/dev-deprecated/types/schema/fields.type-test.js +0 -0
  133. package/dist/unpkg/dev-deprecated/types/schema/schema-service.js +0 -0
  134. package/dist/unpkg/dev-deprecated/types/spec/document.js +0 -0
  135. package/dist/unpkg/dev-deprecated/types/spec/error.js +0 -0
  136. package/dist/unpkg/dev-deprecated/types/spec/json-api-raw.js +0 -0
  137. package/dist/unpkg/dev-deprecated/types/symbols.js +84 -0
  138. package/dist/unpkg/dev-deprecated/types/utils.js +0 -0
  139. package/dist/unpkg/dev-deprecated/types.js +0 -0
  140. package/dist/unpkg/dev-deprecated/utils/string.js +91 -0
  141. package/dist/unpkg/prod/-leaked-DUONXQDB.js +1676 -0
  142. package/dist/unpkg/prod/-private-sql1_mdx.js +39 -0
  143. package/dist/unpkg/prod/build-config/babel-macros.js +1 -0
  144. package/dist/unpkg/prod/build-config/canary-features.js +1 -0
  145. package/dist/unpkg/prod/build-config/debugging.js +1 -0
  146. package/dist/unpkg/prod/build-config/deprecations.js +1 -0
  147. package/dist/unpkg/prod/build-config/env.js +1 -0
  148. package/dist/unpkg/prod/build-config/macros.js +1 -0
  149. package/dist/unpkg/prod/build-config.js +1 -0
  150. package/dist/unpkg/prod/configure.js +2 -0
  151. package/dist/unpkg/prod/graph/-private.js +2235 -0
  152. package/dist/unpkg/prod/handler-EU_8ncB2.js +1619 -0
  153. package/dist/unpkg/prod/index.js +483 -0
  154. package/dist/unpkg/prod/promise-cache-DIT8Ypjq.js +19 -0
  155. package/dist/unpkg/prod/reactive/-private.js +1 -0
  156. package/dist/unpkg/prod/reactive.js +30 -0
  157. package/dist/unpkg/prod/request-BrJSCG6r.js +421 -0
  158. package/dist/unpkg/prod/request.js +2 -0
  159. package/dist/unpkg/prod/schema-BSkHyoWz.js +5219 -0
  160. package/dist/unpkg/prod/signals/-leaked.js +1 -0
  161. package/dist/unpkg/prod/store/-private.js +126 -0
  162. package/dist/unpkg/prod/store.js +437 -0
  163. package/dist/unpkg/prod/types/-private.js +49 -0
  164. package/dist/unpkg/prod/types/cache/aliases.js +0 -0
  165. package/dist/unpkg/prod/types/cache/change.js +0 -0
  166. package/dist/unpkg/prod/types/cache/mutations.js +0 -0
  167. package/dist/unpkg/prod/types/cache/operations.js +0 -0
  168. package/dist/unpkg/prod/types/cache/relationship.js +0 -0
  169. package/dist/unpkg/prod/types/cache.js +0 -0
  170. package/dist/unpkg/prod/types/graph.js +0 -0
  171. package/dist/unpkg/prod/types/identifier.js +61 -0
  172. package/dist/unpkg/prod/types/json/raw.js +0 -0
  173. package/dist/unpkg/prod/types/params.js +0 -0
  174. package/dist/unpkg/prod/types/record.js +191 -0
  175. package/dist/unpkg/prod/types/request.js +77 -0
  176. package/dist/unpkg/prod/types/runtime.js +34 -0
  177. package/dist/unpkg/prod/types/schema/concepts.js +0 -0
  178. package/dist/unpkg/prod/types/schema/fields.js +505 -0
  179. package/dist/unpkg/prod/types/schema/fields.type-test.js +0 -0
  180. package/dist/unpkg/prod/types/schema/schema-service.js +0 -0
  181. package/dist/unpkg/prod/types/spec/document.js +0 -0
  182. package/dist/unpkg/prod/types/spec/error.js +0 -0
  183. package/dist/unpkg/prod/types/spec/json-api-raw.js +0 -0
  184. package/dist/unpkg/prod/types/symbols.js +84 -0
  185. package/dist/unpkg/prod/types/utils.js +0 -0
  186. package/dist/unpkg/prod/types.js +0 -0
  187. package/dist/unpkg/prod/utils/string.js +72 -0
  188. package/dist/unpkg/prod-deprecated/-leaked-DRNv9VIX.js +1676 -0
  189. package/dist/unpkg/prod-deprecated/-private-3C1OkYtZ.js +39 -0
  190. package/dist/unpkg/prod-deprecated/build-config/babel-macros.js +1 -0
  191. package/dist/unpkg/prod-deprecated/build-config/canary-features.js +1 -0
  192. package/dist/unpkg/prod-deprecated/build-config/debugging.js +1 -0
  193. package/dist/unpkg/prod-deprecated/build-config/deprecations.js +1 -0
  194. package/dist/unpkg/prod-deprecated/build-config/env.js +1 -0
  195. package/dist/unpkg/prod-deprecated/build-config/macros.js +1 -0
  196. package/dist/unpkg/prod-deprecated/build-config.js +1 -0
  197. package/dist/unpkg/prod-deprecated/configure.js +2 -0
  198. package/dist/unpkg/prod-deprecated/graph/-private.js +2408 -0
  199. package/dist/unpkg/prod-deprecated/handler-CCIu4sQ3.js +334 -0
  200. package/dist/unpkg/prod-deprecated/hooks-Dv4Np0MY.js +26 -0
  201. package/dist/unpkg/prod-deprecated/index.js +483 -0
  202. package/dist/unpkg/prod-deprecated/promise-cache-DIT8Ypjq.js +19 -0
  203. package/dist/unpkg/prod-deprecated/reactive/-private.js +1 -0
  204. package/dist/unpkg/prod-deprecated/reactive.js +5 -0
  205. package/dist/unpkg/prod-deprecated/request-BrJSCG6r.js +421 -0
  206. package/dist/unpkg/prod-deprecated/request.js +2 -0
  207. package/dist/unpkg/prod-deprecated/schema-CJcjHv0E.js +6939 -0
  208. package/dist/unpkg/prod-deprecated/signals/-leaked.js +1 -0
  209. package/dist/unpkg/prod-deprecated/store/-private.js +88 -0
  210. package/dist/unpkg/prod-deprecated/store.js +437 -0
  211. package/dist/unpkg/prod-deprecated/types/-private.js +49 -0
  212. package/dist/unpkg/prod-deprecated/types/cache/aliases.js +0 -0
  213. package/dist/unpkg/prod-deprecated/types/cache/change.js +0 -0
  214. package/dist/unpkg/prod-deprecated/types/cache/mutations.js +0 -0
  215. package/dist/unpkg/prod-deprecated/types/cache/operations.js +0 -0
  216. package/dist/unpkg/prod-deprecated/types/cache/relationship.js +0 -0
  217. package/dist/unpkg/prod-deprecated/types/cache.js +0 -0
  218. package/dist/unpkg/prod-deprecated/types/graph.js +0 -0
  219. package/dist/unpkg/prod-deprecated/types/identifier.js +61 -0
  220. package/dist/unpkg/prod-deprecated/types/json/raw.js +0 -0
  221. package/dist/unpkg/prod-deprecated/types/params.js +0 -0
  222. package/dist/unpkg/prod-deprecated/types/record.js +191 -0
  223. package/dist/unpkg/prod-deprecated/types/request.js +77 -0
  224. package/dist/unpkg/prod-deprecated/types/runtime.js +34 -0
  225. package/dist/unpkg/prod-deprecated/types/schema/concepts.js +0 -0
  226. package/dist/unpkg/prod-deprecated/types/schema/fields.js +505 -0
  227. package/dist/unpkg/prod-deprecated/types/schema/fields.type-test.js +0 -0
  228. package/dist/unpkg/prod-deprecated/types/schema/schema-service.js +0 -0
  229. package/dist/unpkg/prod-deprecated/types/spec/document.js +0 -0
  230. package/dist/unpkg/prod-deprecated/types/spec/error.js +0 -0
  231. package/dist/unpkg/prod-deprecated/types/spec/json-api-raw.js +0 -0
  232. package/dist/unpkg/prod-deprecated/types/symbols.js +84 -0
  233. package/dist/unpkg/prod-deprecated/types/utils.js +0 -0
  234. package/dist/unpkg/prod-deprecated/types.js +0 -0
  235. package/dist/unpkg/prod-deprecated/utils/string.js +72 -0
  236. package/logos/README.md +2 -2
  237. package/logos/logo-yellow-slab.svg +1 -0
  238. package/logos/word-mark-black.svg +1 -0
  239. package/logos/word-mark-white.svg +1 -0
  240. package/package.json +11 -3
  241. package/declarations/store/-private/new-core-tmp/expensive-subscription.d.ts +0 -24
  242. package/dist/configure-C3x8YXzL.js +0 -181
  243. package/logos/NCC-1701-a-blue.svg +0 -4
  244. package/logos/NCC-1701-a-gold.svg +0 -4
  245. package/logos/NCC-1701-a-gold_100.svg +0 -1
  246. package/logos/NCC-1701-a-gold_base-64.txt +0 -1
  247. package/logos/NCC-1701-a.svg +0 -4
  248. package/logos/docs-badge.svg +0 -2
  249. package/logos/ember-data-logo-dark.svg +0 -12
  250. package/logos/ember-data-logo-light.svg +0 -12
  251. package/logos/social1.png +0 -0
  252. package/logos/social2.png +0 -0
  253. package/logos/warp-drive-logo-dark.svg +0 -4
  254. package/logos/warp-drive-logo-gold.svg +0 -4
  255. /package/declarations/{store/-private/new-core-tmp → signals}/reactivity/configure.d.ts +0 -0
  256. /package/declarations/{store/-private/new-core-tmp → signals}/reactivity/internal.d.ts +0 -0
  257. /package/declarations/{store/-private/new-core-tmp → signals}/reactivity/signal.d.ts +0 -0
  258. /package/dist/{symbols-sql1_mdx.js → unpkg/dev/-private-sql1_mdx.js} +0 -0
@@ -0,0 +1,2235 @@
1
+ import { getOrSetGlobal, peekTransient, setTransient } from '../types/-private.js';
2
+ function getStore(wrapper) {
3
+ return wrapper._store;
4
+ }
5
+ function expandingGet(cache, key1, key2) {
6
+ const mainCache = cache[key1] = cache[key1] || Object.create(null);
7
+ return mainCache[key2];
8
+ }
9
+ function expandingSet(cache, key1, key2, value) {
10
+ const mainCache = cache[key1] = cache[key1] || Object.create(null);
11
+ mainCache[key2] = value;
12
+ }
13
+ function checkIfNew(store, resourceKey) {
14
+ if (!resourceKey.id) {
15
+ return true;
16
+ }
17
+ return store.cache.isNew(resourceKey);
18
+ }
19
+ function isBelongsTo(relationship) {
20
+ return relationship.definition.kind === 'belongsTo';
21
+ }
22
+ function isImplicit(relationship) {
23
+ return relationship.definition.isImplicit;
24
+ }
25
+ function isHasMany(relationship) {
26
+ return relationship.definition.kind === 'hasMany';
27
+ }
28
+ function forAllRelatedIdentifiers(rel, cb) {
29
+ if (isBelongsTo(rel)) {
30
+ if (rel.remoteState) {
31
+ cb(rel.remoteState);
32
+ }
33
+ if (rel.localState && rel.localState !== rel.remoteState) {
34
+ cb(rel.localState);
35
+ }
36
+ } else if (isHasMany(rel)) {
37
+ // TODO
38
+ // rel.remoteMembers.forEach(cb);
39
+ // might be simpler if performance is not a concern
40
+ for (let i = 0; i < rel.remoteState.length; i++) {
41
+ const inverseIdentifier = rel.remoteState[i];
42
+ cb(inverseIdentifier);
43
+ }
44
+ rel.additions?.forEach(cb);
45
+ } else {
46
+ rel.localMembers.forEach(cb);
47
+ rel.remoteMembers.forEach(inverseIdentifier => {
48
+ if (!rel.localMembers.has(inverseIdentifier)) {
49
+ cb(inverseIdentifier);
50
+ }
51
+ });
52
+ }
53
+ }
54
+
55
+ /*
56
+ Removes the given identifier from BOTH remote AND local state.
57
+
58
+ This method is useful when either a deletion or a rollback on a new record
59
+ needs to entirely purge itself from an inverse relationship.
60
+ */
61
+ function removeIdentifierCompletelyFromRelationship(graph, relationship, value, silenceNotifications) {
62
+ if (isBelongsTo(relationship)) {
63
+ if (relationship.remoteState === value) {
64
+ relationship.remoteState = null;
65
+ }
66
+ if (relationship.localState === value) {
67
+ relationship.localState = null;
68
+ // This allows dematerialized inverses to be rematerialized
69
+ // we shouldn't be notifying here though, figure out where
70
+ // a notification was missed elsewhere.
71
+ {
72
+ notifyChange(graph, relationship);
73
+ }
74
+ }
75
+ } else if (isHasMany(relationship)) {
76
+ relationship.remoteMembers.delete(value);
77
+ relationship.additions?.delete(value);
78
+ const wasInRemovals = relationship.removals?.delete(value);
79
+ const canonicalIndex = relationship.remoteState.indexOf(value);
80
+ if (canonicalIndex !== -1) {
81
+ relationship.remoteState.splice(canonicalIndex, 1);
82
+ }
83
+ if (!wasInRemovals) {
84
+ const currentIndex = relationship.localState?.indexOf(value);
85
+ if (currentIndex !== -1 && currentIndex !== undefined) {
86
+ relationship.localState.splice(currentIndex, 1);
87
+ // This allows dematerialized inverses to be rematerialized
88
+ // we shouldn't be notifying here though, figure out where
89
+ // a notification was missed elsewhere.
90
+ {
91
+ notifyChange(graph, relationship);
92
+ }
93
+ }
94
+ }
95
+ } else {
96
+ relationship.remoteMembers.delete(value);
97
+ relationship.localMembers.delete(value);
98
+ }
99
+ }
100
+ function notifyChange(graph, relationship) {
101
+ if (!relationship.accessed) {
102
+ return;
103
+ }
104
+ const resourceKey = relationship.identifier;
105
+ const key = relationship.definition.key;
106
+ if (resourceKey === graph._removing) {
107
+ return;
108
+ }
109
+ graph.store.notifyChange(resourceKey, 'relationships', key);
110
+ }
111
+ function isLegacyField(field) {
112
+ return field.kind === 'belongsTo' || field.kind === 'hasMany';
113
+ }
114
+ function temporaryConvertToLegacy(field) {
115
+ return {
116
+ kind: field.kind === 'resource' ? 'belongsTo' : 'hasMany',
117
+ name: field.name,
118
+ type: field.type,
119
+ options: Object.assign({}, {
120
+ async: false,
121
+ inverse: null,
122
+ resetOnRemoteUpdate: false
123
+ }, field.options)
124
+ };
125
+ }
126
+
127
+ /**
128
+ *
129
+ * Given RHS (Right Hand Side)
130
+ *
131
+ * ```ts
132
+ * class User extends Model {
133
+ * @hasMany('animal', { async: false, inverse: 'owner' }) pets;
134
+ * }
135
+ * ```
136
+ *
137
+ * Given LHS (Left Hand Side)
138
+ *
139
+ * ```ts
140
+ * class Animal extends Model {
141
+ * @belongsTo('user', { async: false, inverse: 'pets' }) owner;
142
+ * }
143
+ * ```
144
+ *
145
+ * The UpgradedMeta for the RHS would be:
146
+ *
147
+ * ```ts
148
+ * {
149
+ * kind: 'hasMany',
150
+ * key: 'pets',
151
+ * type: 'animal',
152
+ * isAsync: false,
153
+ * isImplicit: false,
154
+ * isCollection: true,
155
+ * isPolymorphic: false,
156
+ * inverseKind: 'belongsTo',
157
+ * inverseKey: 'owner',
158
+ * inverseType: 'user',
159
+ * inverseIsAsync: false,
160
+ * inverseIsImplicit: false,
161
+ * inverseIsCollection: false,
162
+ * inverseIsPolymorphic: false,
163
+ * }
164
+ * ```
165
+ *
166
+ * The UpgradeMeta for the LHS would be:
167
+ *
168
+ * ```ts
169
+ * {
170
+ * kind: 'belongsTo',
171
+ * key: 'owner',
172
+ * type: 'user',
173
+ * isAsync: false,
174
+ * isImplicit: false,
175
+ * isCollection: false,
176
+ * isPolymorphic: false,
177
+ * inverseKind: 'hasMany',
178
+ * inverseKey: 'pets',
179
+ * inverseType: 'animal',
180
+ * inverseIsAsync: false,
181
+ * inverseIsImplicit: false,
182
+ * inverseIsCollection: true,
183
+ * inverseIsPolymorphic: false,
184
+ * }
185
+ * ```
186
+ *
187
+ * @private
188
+ */
189
+
190
+ const BOOL_LATER = null;
191
+ const STR_LATER = '';
192
+ const IMPLICIT_KEY_RAND = Date.now();
193
+ function implicitKeyFor(type, key) {
194
+ return `implicit-${type}:${key}${IMPLICIT_KEY_RAND}`;
195
+ }
196
+ function syncMeta(definition, inverseDefinition) {
197
+ definition.inverseKind = inverseDefinition.kind;
198
+ definition.inverseKey = inverseDefinition.key;
199
+ definition.inverseName = inverseDefinition.name;
200
+ definition.inverseType = inverseDefinition.type;
201
+ definition.inverseIsAsync = inverseDefinition.isAsync;
202
+ definition.inverseIsCollection = inverseDefinition.isCollection;
203
+ definition.inverseIsPolymorphic = inverseDefinition.isPolymorphic;
204
+ definition.inverseIsImplicit = inverseDefinition.isImplicit;
205
+ definition.inverseIsLinksMode = inverseDefinition.isLinksMode;
206
+ const resetOnRemoteUpdate = definition.resetOnRemoteUpdate === false || inverseDefinition.resetOnRemoteUpdate === false ? false : true;
207
+ definition.resetOnRemoteUpdate = resetOnRemoteUpdate;
208
+ inverseDefinition.resetOnRemoteUpdate = resetOnRemoteUpdate;
209
+ }
210
+ function upgradeMeta(meta) {
211
+ if (!isLegacyField(meta)) {
212
+ meta = temporaryConvertToLegacy(meta);
213
+ }
214
+ const niceMeta = {};
215
+ const options = meta.options;
216
+ niceMeta.kind = meta.kind;
217
+ niceMeta.key = meta.sourceKey ?? meta.name;
218
+ niceMeta.name = meta.name;
219
+ niceMeta.type = meta.type;
220
+ niceMeta.isAsync = options.async;
221
+ niceMeta.isImplicit = false;
222
+ niceMeta.isCollection = meta.kind === 'hasMany';
223
+ niceMeta.isPolymorphic = options && !!options.polymorphic;
224
+ niceMeta.isLinksMode = options.linksMode ?? false;
225
+ niceMeta.inverseKey = options && options.inverse || STR_LATER;
226
+ niceMeta.inverseName = options && options.inverse || STR_LATER;
227
+ niceMeta.inverseType = STR_LATER;
228
+ niceMeta.inverseIsAsync = BOOL_LATER;
229
+ niceMeta.inverseIsImplicit = options && options.inverse === null || BOOL_LATER;
230
+ niceMeta.inverseIsCollection = BOOL_LATER;
231
+ niceMeta.inverseIsLinksMode = BOOL_LATER;
232
+
233
+ // prettier-ignore
234
+ niceMeta.resetOnRemoteUpdate = !isLegacyField(meta) ? false : meta.options?.linksMode ? false : meta.options?.resetOnRemoteUpdate === false ? false : true;
235
+ return niceMeta;
236
+ }
237
+ function isLHS(info, type, key) {
238
+ const isSelfReferential = info.isSelfReferential;
239
+ const isRelationship = key === info.lhs_relationshipName;
240
+ if (isRelationship === true) {
241
+ return isSelfReferential === true ||
242
+ // itself
243
+ type === info.lhs_baseModelName ||
244
+ // base or non-polymorphic
245
+ // if the other side is polymorphic then we need to scan our modelNames
246
+ info.rhs_isPolymorphic && info.lhs_modelNames.includes(type) // polymorphic
247
+ ;
248
+ }
249
+ return false;
250
+ }
251
+ function upgradeDefinition(graph, key, propertyName, isImplicit = false) {
252
+ const cache = graph._definitionCache;
253
+ const storeWrapper = graph.store;
254
+ const polymorphicLookup = graph._potentialPolymorphicTypes;
255
+ const {
256
+ type
257
+ } = key;
258
+ let cached = /*#__NOINLINE__*/expandingGet(cache, type, propertyName);
259
+
260
+ // CASE: We have a cached resolution (null if no relationship exists)
261
+ if (cached !== undefined) {
262
+ return cached;
263
+ }
264
+ const relationships = storeWrapper.schema.fields(key);
265
+ const relationshipsBySourceKey = storeWrapper.schema.cacheFields?.(key) ?? relationships;
266
+ const meta = relationshipsBySourceKey.get(propertyName);
267
+ if (!meta) {
268
+ // TODO potentially we should just be permissive here since this is an implicit relationship
269
+ // and not require the lookup table to be populated
270
+ if (polymorphicLookup[type]) {
271
+ const altTypes = Object.keys(polymorphicLookup[type]);
272
+ for (let i = 0; i < altTypes.length; i++) {
273
+ const _cached = expandingGet(cache, altTypes[i], propertyName);
274
+ if (_cached) {
275
+ /*#__NOINLINE__*/expandingSet(cache, type, propertyName, _cached);
276
+ _cached.rhs_modelNames.push(type);
277
+ return _cached;
278
+ }
279
+ }
280
+ }
281
+ cache[type][propertyName] = null;
282
+ return null;
283
+ }
284
+ const definition = /*#__NOINLINE__*/upgradeMeta(meta);
285
+ let inverseDefinition;
286
+ let inverseKey;
287
+ const inverseType = definition.type;
288
+
289
+ // CASE: Inverse is explicitly null
290
+ if (definition.inverseKey === null) {
291
+ inverseDefinition = null;
292
+ } else {
293
+ inverseKey = /*#__NOINLINE__*/inverseForRelationship(getStore(storeWrapper), key, propertyName);
294
+
295
+ // CASE: If we are polymorphic, and we declared an inverse that is non-null
296
+ // we must assume that the lack of inverseKey means that there is no
297
+ // concrete type as the baseType, so we must construct and artificial
298
+ // placeholder
299
+ if (!inverseKey && definition.isPolymorphic && definition.inverseKey) {
300
+ inverseDefinition = {
301
+ kind: 'belongsTo',
302
+ // this must be updated when we find the first belongsTo or hasMany definition that matches
303
+ key: definition.inverseKey,
304
+ name: definition.inverseName,
305
+ type: type,
306
+ isAsync: false,
307
+ // this must be updated when we find the first belongsTo or hasMany definition that matches
308
+ isImplicit: false,
309
+ isCollection: false,
310
+ // this must be updated when we find the first belongsTo or hasMany definition that matches
311
+ isPolymorphic: false
312
+ }; // the rest of the fields are populated by syncMeta
313
+
314
+ // CASE: Inverse resolves to null
315
+ } else if (!inverseKey) {
316
+ inverseDefinition = null;
317
+ } else {
318
+ // CASE: We have an explicit inverse or were able to resolve one
319
+ // for the inverse we use "name" for lookup not "sourceKey"
320
+ const inverseDefinitions = storeWrapper.schema.fields({
321
+ type: inverseType
322
+ });
323
+ const metaFromInverse = inverseDefinitions.get(inverseKey);
324
+ inverseDefinition = upgradeMeta(metaFromInverse);
325
+ }
326
+ }
327
+
328
+ // CASE: We have no inverse
329
+ if (!inverseDefinition) {
330
+ // polish off meta
331
+ inverseKey = /*#__NOINLINE__*/implicitKeyFor(type, propertyName);
332
+ inverseDefinition = {
333
+ kind: 'implicit',
334
+ key: inverseKey,
335
+ type: type,
336
+ isAsync: false,
337
+ isImplicit: true,
338
+ isCollection: true,
339
+ // with implicits any number of records could point at us
340
+ isPolymorphic: false
341
+ }; // the rest of the fields are populated by syncMeta
342
+
343
+ syncMeta(definition, inverseDefinition);
344
+ syncMeta(inverseDefinition, definition);
345
+ const info = {
346
+ lhs_key: `${type}:${propertyName}`,
347
+ lhs_modelNames: [type],
348
+ lhs_baseModelName: type,
349
+ lhs_relationshipName: propertyName,
350
+ lhs_definition: definition,
351
+ lhs_isPolymorphic: definition.isPolymorphic,
352
+ rhs_key: inverseDefinition.key,
353
+ rhs_modelNames: [inverseType],
354
+ rhs_baseModelName: inverseType,
355
+ rhs_relationshipName: inverseDefinition.key,
356
+ rhs_definition: inverseDefinition,
357
+ rhs_isPolymorphic: false,
358
+ hasInverse: false,
359
+ isSelfReferential: type === inverseType,
360
+ // this could be wrong if we are self-referential but also polymorphic
361
+ isReflexive: false // we can't be reflexive if we don't define an inverse
362
+ };
363
+ expandingSet(cache, inverseType, inverseKey, info);
364
+ expandingSet(cache, type, propertyName, info);
365
+ return info;
366
+ }
367
+
368
+ // CASE: We do have an inverse
369
+ const baseType = inverseDefinition.type;
370
+ cached = expandingGet(cache, baseType, propertyName) || expandingGet(cache, inverseType, inverseKey);
371
+ if (cached) {
372
+ const _isLHS = cached.lhs_baseModelName === baseType;
373
+ const modelNames = _isLHS ? cached.lhs_modelNames : cached.rhs_modelNames;
374
+ // make this lookup easier in the future by caching the key
375
+ modelNames.push(type);
376
+ expandingSet(cache, type, propertyName, cached);
377
+ return cached;
378
+ }
379
+
380
+ // this is our first time so polish off the metas
381
+ syncMeta(definition, inverseDefinition);
382
+ syncMeta(inverseDefinition, definition);
383
+ const lhs_modelNames = [type];
384
+ if (type !== baseType) {
385
+ lhs_modelNames.push(baseType);
386
+ }
387
+ const isSelfReferential = baseType === inverseType;
388
+ const info = {
389
+ lhs_key: `${baseType}:${propertyName}`,
390
+ lhs_modelNames,
391
+ lhs_baseModelName: baseType,
392
+ lhs_relationshipName: propertyName,
393
+ lhs_definition: definition,
394
+ lhs_isPolymorphic: definition.isPolymorphic,
395
+ rhs_key: `${inverseType}:${inverseKey}`,
396
+ rhs_modelNames: [inverseType],
397
+ rhs_baseModelName: inverseType,
398
+ rhs_relationshipName: inverseKey,
399
+ rhs_definition: inverseDefinition,
400
+ rhs_isPolymorphic: inverseDefinition.isPolymorphic,
401
+ hasInverse: true,
402
+ isSelfReferential,
403
+ isReflexive: isSelfReferential && propertyName === inverseKey
404
+ };
405
+
406
+ // Create entries for the baseModelName as well as modelName to speed up
407
+ // inverse lookups
408
+ expandingSet(cache, baseType, propertyName, info);
409
+ expandingSet(cache, type, propertyName, info);
410
+
411
+ // Greedily populate the inverse
412
+ expandingSet(cache, inverseType, inverseKey, info);
413
+ return info;
414
+ }
415
+ function inverseForRelationship(store, resourceKey, key) {
416
+ const fields = store.schema.fields(resourceKey);
417
+ const definition = fields.get(key);
418
+ if (!definition) {
419
+ return null;
420
+ }
421
+ return definition.options.inverse;
422
+ }
423
+
424
+ /*
425
+ case many:1
426
+ ========
427
+ In a bi-directional graph with Many:1 edges, adding a value
428
+ results in up-to 3 discrete value transitions, while removing
429
+ a value is only 2 transitions.
430
+
431
+ For adding C to A
432
+ If: A <<-> B, C <->> D is the initial state,
433
+ and: B <->> A <<-> C, D is the final state
434
+
435
+ then we would undergo the following transitions.
436
+
437
+ add C to A
438
+ remove C from D
439
+ add A to C
440
+
441
+ For removing B from A
442
+ If: A <<-> B, C <->> D is the initial state,
443
+ and: A, B, C <->> D is the final state
444
+
445
+ then we would undergo the following transitions.
446
+
447
+ remove B from A
448
+ remove A from B
449
+
450
+ case many:many
451
+ ===========
452
+ In a bi-directional graph with Many:Many edges, adding or
453
+ removing a value requires only 2 value transitions.
454
+
455
+ For Adding
456
+ If: A<<->>B, C<<->>D is the initial state (double arrows representing the many side)
457
+ And: D<<->>C<<->>A<<->>B is the final state
458
+
459
+ Then we would undergo two transitions.
460
+
461
+ add C to A.
462
+ add A to C
463
+
464
+ For Removing
465
+ If: A<<->>B, C<<->>D is the initial state (double arrows representing the many side)
466
+ And: A, B, C<<->>D is the final state
467
+
468
+ Then we would undergo two transitions.
469
+
470
+ remove B from A
471
+ remove A from B
472
+
473
+ case many:?
474
+ ========
475
+ In a uni-directional graph with Many:? edges (modeled in WarpDrive with `inverse:null`) with
476
+ artificial (implicit) inverses, replacing a value results in 2 discrete value transitions.
477
+ This is because a Many:? relationship is effectively Many:Many.
478
+ */
479
+ function replaceRelatedRecords(graph, op, isRemote) {
480
+ if (isRemote) {
481
+ replaceRelatedRecordsRemote(graph, op, isRemote);
482
+ } else {
483
+ replaceRelatedRecordsLocal(graph, op, isRemote);
484
+ }
485
+ }
486
+ function replaceRelatedRecordsLocal(graph, op, isRemote) {
487
+ const resourceKeys = op.value;
488
+ const relationship = graph.get(op.record, op.field);
489
+ relationship.state.hasReceivedData = true;
490
+ const {
491
+ additions,
492
+ removals
493
+ } = relationship;
494
+ const {
495
+ inverseKey,
496
+ type
497
+ } = relationship.definition;
498
+ const {
499
+ record
500
+ } = op;
501
+ const wasDirty = relationship.isDirty;
502
+ let localBecameDirty = false;
503
+ const onAdd = resourceKey => {
504
+ // Since we are diffing against the remote state, we check
505
+ // if our previous local state did not contain this ResourceKey
506
+ const removalsHas = removals?.has(resourceKey);
507
+ if (removalsHas || !additions?.has(resourceKey)) {
508
+ if (type !== resourceKey.type) {
509
+ graph.registerPolymorphicType(type, resourceKey.type);
510
+ }
511
+
512
+ // we've added a record locally that wasn't in the local state before
513
+ localBecameDirty = true;
514
+ addToInverse(graph, resourceKey, inverseKey, op.record, isRemote);
515
+ if (removalsHas) {
516
+ removals.delete(resourceKey);
517
+ }
518
+ }
519
+ };
520
+ const onRemove = resourceKey => {
521
+ // Since we are diffing against the remote state, we check
522
+ // if our previous local state had contained this ResourceKey
523
+ const additionsHas = additions?.has(resourceKey);
524
+ if (additionsHas || !removals?.has(resourceKey)) {
525
+ // we've removed a record locally that was in the local state before
526
+ localBecameDirty = true;
527
+ removeFromInverse(graph, resourceKey, inverseKey, record, isRemote);
528
+ if (additionsHas) {
529
+ additions.delete(resourceKey);
530
+ }
531
+ }
532
+ };
533
+ const diff = diffCollection(resourceKeys, relationship, onAdd, onRemove);
534
+
535
+ // any additions no longer in the local state
536
+ // also need to be removed from the inverse
537
+ if (additions && additions.size > 0) {
538
+ additions.forEach(resourceKey => {
539
+ if (!diff.add.has(resourceKey)) {
540
+ localBecameDirty = true;
541
+ onRemove(resourceKey);
542
+ }
543
+ });
544
+ }
545
+
546
+ // any removals no longer in the local state
547
+ // also need to be added back to the inverse
548
+ if (removals && removals.size > 0) {
549
+ removals.forEach(resourceKey => {
550
+ if (!diff.del.has(resourceKey)) {
551
+ localBecameDirty = true;
552
+ onAdd(resourceKey);
553
+ }
554
+ });
555
+ }
556
+ const becameDirty = diff.changed || localBecameDirty;
557
+ relationship.additions = diff.add;
558
+ relationship.removals = diff.del;
559
+ relationship.localState = diff.finalState;
560
+
561
+ // we only notify if the localState changed and were not already dirty before
562
+ // because if we were already dirty then we have already notified
563
+ if (becameDirty && !wasDirty) {
564
+ notifyChange(graph, relationship);
565
+ }
566
+ }
567
+ function replaceRelatedRecordsRemote(graph, op, isRemote) {
568
+ const resourceKeys = op.value;
569
+ const relationship = graph.get(op.record, op.field);
570
+ if (isRemote) {
571
+ graph._addToTransaction(relationship);
572
+ }
573
+ const wasDirty = relationship.isDirty;
574
+ // if this is our first time receiving data
575
+ // we need to mark the relationship as dirty
576
+ // so that non-materializing APIs like `hasManyReference.value()`
577
+ // will get notified and updated.
578
+ if (!relationship.state.hasReceivedData) {
579
+ relationship.isDirty = true;
580
+ }
581
+ relationship.state.hasReceivedData = true;
582
+
583
+ // cache existing state
584
+ const {
585
+ definition
586
+ } = relationship;
587
+ const {
588
+ type
589
+ } = relationship.definition;
590
+ const diff = diffCollection(resourceKeys, relationship, resourceKey => {
591
+ if (type !== resourceKey.type) {
592
+ graph.registerPolymorphicType(type, resourceKey.type);
593
+ }
594
+ // commit additions
595
+ // TODO build this into the diff?
596
+ // because we are not dirty if this was a committed local addition
597
+ if (relationship.additions?.has(resourceKey)) {
598
+ relationship.additions.delete(resourceKey);
599
+ }
600
+ addToInverse(graph, resourceKey, definition.inverseKey, op.record, isRemote);
601
+ }, resourceKey => {
602
+ // commit removals
603
+ // TODO build this into the diff?
604
+ // because we are not dirty if this was a committed local addition
605
+ if (relationship.removals?.has(resourceKey)) {
606
+ relationship.removals.delete(resourceKey);
607
+ }
608
+ removeFromInverse(graph, resourceKey, definition.inverseKey, op.record, isRemote);
609
+ });
610
+
611
+ // replace existing state
612
+ relationship.remoteMembers = diff.finalSet;
613
+ relationship.remoteState = diff.finalState;
614
+
615
+ // changed also indicates a change in order
616
+ if (diff.changed) {
617
+ relationship.isDirty = true;
618
+ }
619
+
620
+ // TODO unsure if we need this but it
621
+ // may allow us to more efficiently patch
622
+ // the associated ManyArray
623
+ relationship._diff = diff;
624
+ if (relationship.isDirty && !wasDirty) {
625
+ flushCanonical(graph, relationship);
626
+ }
627
+ }
628
+ function addToInverse(graph, resourceKey, key, value, isRemote) {
629
+ const relationship = graph.get(resourceKey, key);
630
+ const {
631
+ type
632
+ } = relationship.definition;
633
+ if (type !== value.type) {
634
+ graph.registerPolymorphicType(type, value.type);
635
+ }
636
+ if (isBelongsTo(relationship)) {
637
+ relationship.state.hasReceivedData = true;
638
+ relationship.state.isEmpty = false;
639
+ if (isRemote) {
640
+ graph._addToTransaction(relationship);
641
+ if (relationship.remoteState !== null) {
642
+ removeFromInverse(graph, relationship.remoteState, relationship.definition.inverseKey, resourceKey, isRemote);
643
+ }
644
+ relationship.remoteState = value;
645
+ }
646
+ if (relationship.localState !== value) {
647
+ if (!isRemote && relationship.localState) {
648
+ removeFromInverse(graph, relationship.localState, relationship.definition.inverseKey, resourceKey, isRemote);
649
+ }
650
+ relationship.localState = value;
651
+ notifyChange(graph, relationship);
652
+ }
653
+ } else if (isHasMany(relationship)) {
654
+ if (isRemote) {
655
+ // TODO this needs to alert stuffs
656
+ // And patch state better
657
+ // This is almost definitely wrong
658
+ // WARNING WARNING WARNING
659
+
660
+ if (!relationship.remoteMembers.has(value)) {
661
+ graph._addToTransaction(relationship);
662
+ relationship.remoteState.push(value);
663
+ relationship.remoteMembers.add(value);
664
+ if (relationship.additions?.has(value)) {
665
+ relationship.additions.delete(value);
666
+ } else {
667
+ relationship.isDirty = true;
668
+ relationship.state.hasReceivedData = true;
669
+ flushCanonical(graph, relationship);
670
+ }
671
+ }
672
+ } else {
673
+ // if we are not dirty but have a null localState then we
674
+ // are mutating a relationship that has never been fetched
675
+ // so we initialize localState to an empty array
676
+ if (!relationship.isDirty && !relationship.localState) {
677
+ relationship.localState = [];
678
+ }
679
+ if (_add(graph, resourceKey, relationship, value, null, isRemote)) {
680
+ notifyChange(graph, relationship);
681
+ }
682
+ }
683
+ } else {
684
+ if (isRemote) {
685
+ if (!relationship.remoteMembers.has(value)) {
686
+ relationship.remoteMembers.add(value);
687
+ relationship.localMembers.add(value);
688
+ }
689
+ } else {
690
+ if (!relationship.localMembers.has(value)) {
691
+ relationship.localMembers.add(value);
692
+ }
693
+ }
694
+ }
695
+ }
696
+ function notifyInverseOfPotentialMaterialization(graph, resourceKey, key, value, isRemote) {
697
+ const relationship = graph.get(resourceKey, key);
698
+ if (isHasMany(relationship) && isRemote && relationship.remoteMembers.has(value)) {
699
+ notifyChange(graph, relationship);
700
+ }
701
+ }
702
+ function removeFromInverse(graph, resourceKey, key, value, isRemote) {
703
+ const relationship = graph.get(resourceKey, key);
704
+ if (isBelongsTo(relationship)) {
705
+ relationship.state.isEmpty = true;
706
+ if (isRemote) {
707
+ graph._addToTransaction(relationship);
708
+ relationship.remoteState = null;
709
+ }
710
+ if (relationship.localState === value) {
711
+ relationship.localState = null;
712
+ notifyChange(graph, relationship);
713
+ }
714
+ } else if (isHasMany(relationship)) {
715
+ if (isRemote) {
716
+ graph._addToTransaction(relationship);
717
+ if (_removeRemote(relationship, value)) {
718
+ notifyChange(graph, relationship);
719
+ }
720
+ } else {
721
+ if (_removeLocal(relationship, value)) {
722
+ notifyChange(graph, relationship);
723
+ }
724
+ }
725
+ } else {
726
+ if (isRemote) {
727
+ relationship.remoteMembers.delete(value);
728
+ relationship.localMembers.delete(value);
729
+ } else {
730
+ if (value && relationship.localMembers.has(value)) {
731
+ relationship.localMembers.delete(value);
732
+ }
733
+ }
734
+ }
735
+ }
736
+ function flushCanonical(graph, rel) {
737
+ if (rel.accessed) {
738
+ graph._scheduleLocalSync(rel);
739
+ }
740
+ }
741
+ function replaceRelatedRecord(graph, op, isRemote = false) {
742
+ const relationship = graph.get(op.record, op.field);
743
+ if (isRemote) {
744
+ graph._addToTransaction(relationship);
745
+ }
746
+ const {
747
+ definition,
748
+ state
749
+ } = relationship;
750
+ const prop = isRemote ? 'remoteState' : 'localState';
751
+ const existingState = relationship[prop];
752
+
753
+ /*
754
+ case 1:1
755
+ ========
756
+ In a bi-directional graph with 1:1 edges, replacing a value
757
+ results in up-to 4 discrete value transitions.
758
+ If: A <-> B, C <-> D is the initial state,
759
+ and: A <-> C, B, D is the final state
760
+ then we would undergo the following 4 transitions.
761
+ remove A from B
762
+ add C to A
763
+ remove C from D
764
+ add A to C
765
+ case 1:many
766
+ ===========
767
+ In a bi-directional graph with 1:Many edges, replacing a value
768
+ results in up-to 3 discrete value transitions.
769
+ If: A<->>B<<->D, C<<->D is the initial state (double arrows representing the many side)
770
+ And: A<->>C<<->D, B<<->D is the final state
771
+ Then we would undergo three transitions.
772
+ remove A from B
773
+ add C to A.
774
+ add A to C
775
+ case 1:?
776
+ ========
777
+ In a uni-directional graph with 1:? edges (modeled in WarpDrive with `inverse:null`) with
778
+ artificial (implicit) inverses, replacing a value results in up-to 3 discrete value transitions.
779
+ This is because a 1:? relationship is effectively 1:many.
780
+ If: A->B, C->B is the initial state
781
+ And: A->C, C->B is the final state
782
+ Then we would undergo three transitions.
783
+ Remove A from B
784
+ Add C to A
785
+ Add A to C
786
+ */
787
+
788
+ // nothing for us to do
789
+ if (op.value === existingState) {
790
+ // if we were empty before but now know we are empty this needs to be true
791
+ state.hasReceivedData = true;
792
+ // if this is a remote update we still sync
793
+ if (isRemote) {
794
+ const {
795
+ localState
796
+ } = relationship;
797
+ // don't sync if localState is a new record and our remoteState is null
798
+ if (localState && checkIfNew(graph._realStore, localState) && !existingState) {
799
+ return;
800
+ }
801
+ if (existingState && localState === existingState) {
802
+ notifyInverseOfPotentialMaterialization(graph, existingState, definition.inverseKey, op.record, isRemote);
803
+ }
804
+ }
805
+ return;
806
+ }
807
+
808
+ // remove this value from the inverse if required
809
+ if (existingState) {
810
+ removeFromInverse(graph, existingState, definition.inverseKey, op.record, isRemote);
811
+ }
812
+
813
+ // update value to the new value
814
+ relationship[prop] = op.value;
815
+ state.hasReceivedData = true;
816
+ state.isEmpty = op.value === null;
817
+ state.isStale = false;
818
+ state.hasFailedLoadAttempt = false;
819
+ if (op.value) {
820
+ if (definition.type !== op.value.type) {
821
+ // assert(
822
+ // `The '<${definition.inverseType}>.${op.field}' relationship expects only '${definition.type}' records since it is not polymorphic. Received a Record of type '${op.value.type}'`,
823
+ // definition.isPolymorphic
824
+ // );
825
+
826
+ // TODO this should now handle the deprecation warning if isPolymorphic is not set
827
+ // but the record does turn out to be polymorphic
828
+ // this should still assert if the user is relying on legacy inheritance/mixins to
829
+ // provide polymorphic behavior and has not yet added the polymorphic flags
830
+
831
+ graph.registerPolymorphicType(definition.type, op.value.type);
832
+ }
833
+ addToInverse(graph, op.value, definition.inverseKey, op.record, isRemote);
834
+ }
835
+ if (isRemote) {
836
+ const {
837
+ localState,
838
+ remoteState
839
+ } = relationship;
840
+ if (localState && checkIfNew(graph._realStore, localState) && !remoteState) {
841
+ return;
842
+ }
843
+ // when localState does not match the new remoteState and
844
+ // localState === existingState then we had no local mutation
845
+ // and we can safely sync the new remoteState to local
846
+ if (localState !== remoteState && localState === existingState) {
847
+ relationship.localState = remoteState;
848
+ notifyChange(graph, relationship);
849
+ // But when localState does not match the new remoteState and
850
+ // and localState !== existingState then we know we have a local mutation
851
+ // that has not been persisted yet.
852
+ }
853
+ } else {
854
+ notifyChange(graph, relationship);
855
+ }
856
+ }
857
+ function _compare(priorLocalState, finalState, finalSet, prevState, prevSet, onAdd, onDel, remoteClearsLocal) {
858
+ const finalLength = finalState.length;
859
+ const prevLength = prevState.length;
860
+ const iterationLength = Math.max(finalLength, prevLength);
861
+ const equalLength = priorLocalState ? finalLength === priorLocalState.length : finalLength === prevLength;
862
+ let remoteOrderChanged = finalSet.size !== prevSet.size;
863
+ let changed = priorLocalState ? finalSet.size !== priorLocalState.length : remoteOrderChanged;
864
+ const added = new Set();
865
+ const removed = new Set();
866
+ const priorLocalLength = priorLocalState?.length ?? 0;
867
+ for (let i = 0; i < iterationLength; i++) {
868
+ let member;
869
+
870
+ // accumulate anything added
871
+ if (i < finalLength) {
872
+ member = finalState[i];
873
+ if (!prevSet.has(member)) {
874
+ // Avoid unnecessarily notifying a change that already exists locally
875
+ if (i < priorLocalLength) {
876
+ const priorLocalMember = priorLocalState[i];
877
+ if (priorLocalMember !== member) {
878
+ changed = true;
879
+ }
880
+ }
881
+ added.add(member);
882
+ onAdd(member);
883
+ }
884
+ }
885
+
886
+ // accumulate anything removed
887
+ if (i < prevLength) {
888
+ const prevMember = prevState[i];
889
+
890
+ // detect reordering
891
+ if (equalLength && member !== prevMember) {
892
+ // the new remote order does not match the current remote order
893
+ // indicating a change in membership or reordering
894
+ remoteOrderChanged = true;
895
+ // however: if the new remote order matches the current local order
896
+ // we can disregard the change notification generation so long as
897
+ // we are not configured to reset on remote update (which is deprecated)
898
+
899
+ if (i < priorLocalLength) {
900
+ const priorLocalMember = priorLocalState[i];
901
+ if (priorLocalMember !== member) {
902
+ changed = true;
903
+ }
904
+ } else if (i < finalLength) {
905
+ // if we have exceeded the length of priorLocalState and we are within the range
906
+ // of the finalState then we must have changed
907
+
908
+ changed = true;
909
+ }
910
+
911
+ // if remote order hasn't changed but local order differs
912
+ // and we are configured to reset on remote update (which is deprecated)
913
+ // then we still need to mark the relationship as changed
914
+ }
915
+ if (!finalSet.has(prevMember)) {
916
+ // if we are within finalLength, we can only be "changed" if we've already exceeded
917
+ // the index range of priorLocalState, as otherwise the previous member may still
918
+ // be removed.
919
+ //
920
+ // prior local: [1, 2, 3, 4]
921
+ // final state: [1, 2, 3]
922
+ // prev remote state: [1, 2, 5, 3, 4]
923
+ // i === 2
924
+ // prevMember === 5
925
+ // !finalSet.has(prevMember) === true
926
+ //
927
+ // because we will become changed at i===3,
928
+ // we do not need to worry about becoming changed at i===2
929
+ // as the arrays until now are still the same
930
+ //
931
+ // prior local: [1, 2, 3]
932
+ // final state: [1, 2, 3, 4]
933
+ // prev remote state: [1, 2, 5, 3, 4]
934
+ // i === 2
935
+ // prevMember === 5
936
+ // !finalSet.has(prevMember) === true
937
+ //
938
+ // because we will become changed at i===3
939
+ // we do not need to worry about becoming changed at i===2
940
+ //
941
+ // prior local: [1, 2, 3]
942
+ // final state: [1, 2, 3]
943
+ // prev remote state: [1, 2, 5, 3, 4]
944
+ // i === 2
945
+ // prevMember === 5
946
+ // !finalSet.has(prevMember) === true
947
+ //
948
+ // because we have same length and same membership order
949
+ // we do not need to worry about becoming changed at i===2
950
+ //
951
+ // if you do not have a priorLocalState you can't be changed
952
+ // ergo, we never need to set changed in this branch.
953
+ // this log can still be useful for debugging.
954
+
955
+ //
956
+ // we do still set remoteOrderChanged as it has
957
+ remoteOrderChanged = true;
958
+ removed.add(prevMember);
959
+ onDel(prevMember);
960
+ }
961
+ }
962
+ }
963
+ return {
964
+ add: added,
965
+ del: removed,
966
+ finalState,
967
+ finalSet,
968
+ changed,
969
+ remoteOrderChanged
970
+ };
971
+ }
972
+ function diffCollection(finalState, relationship, onAdd, onDel) {
973
+ const finalSet = new Set(finalState);
974
+ const {
975
+ localState: priorLocalState,
976
+ remoteState,
977
+ remoteMembers
978
+ } = relationship;
979
+ return _compare(priorLocalState, finalState, finalSet, remoteState, remoteMembers, onAdd, onDel, relationship.definition.resetOnRemoteUpdate);
980
+ }
981
+ function computeLocalState(storage) {
982
+ if (!storage.isDirty) {
983
+ return storage.localState;
984
+ }
985
+ const state = storage.remoteState.slice();
986
+ storage.removals?.forEach(v => {
987
+ const index = state.indexOf(v);
988
+ state.splice(index, 1);
989
+ });
990
+ storage.additions?.forEach(v => {
991
+ state.push(v);
992
+ });
993
+ storage.localState = state;
994
+ storage.isDirty = false;
995
+ return state;
996
+ }
997
+
998
+ /**
999
+ * A function which attempts to add a value to the local state of a collection
1000
+ * relationship, and returns true if the value was added, or false if it was
1001
+ * already present.
1002
+ *
1003
+ * It will not generate a notification, will not update the relationships to dirty,
1004
+ * and will not update the inverse relationships, making it suitable for use as
1005
+ * an internal util to perform the just the addition to a specific side of a
1006
+ * relationship.
1007
+ *
1008
+ * @internal
1009
+ */
1010
+ function _add(graph, record, relationship, value, index, isRemote) {
1011
+ return !isRemote ? _addLocal(graph, record, relationship, value, index) : _addRemote(graph, record, relationship, value, index);
1012
+ }
1013
+ function _addRemote(graph, record, relationship, value, index) {
1014
+ const {
1015
+ remoteMembers,
1016
+ additions,
1017
+ removals,
1018
+ remoteState
1019
+ } = relationship;
1020
+ if (remoteMembers.has(value)) {
1021
+ return false;
1022
+ }
1023
+
1024
+ // add to the remote state
1025
+ remoteMembers.add(value);
1026
+ const hasValidIndex = index !== null && index >= 0 && index < remoteState.length;
1027
+ if (hasValidIndex) {
1028
+ remoteState.splice(index, 0, value);
1029
+ } else {
1030
+ remoteState.push(value);
1031
+ }
1032
+
1033
+ // remove from additions if present
1034
+ if (additions?.has(value)) {
1035
+ additions.delete(value);
1036
+
1037
+ // nothing more to do this was our state already
1038
+ return false;
1039
+ }
1040
+
1041
+ // if the relationship already needs to recalc, we don't bother
1042
+ // attempting to patch the localState
1043
+ if (relationship.isDirty) {
1044
+ return true;
1045
+ }
1046
+
1047
+ // if we have existing localState
1048
+ // we attempt to patch it without blowing it away
1049
+ // as this is more efficient than recomputing
1050
+ // it allows us to preserve local ordering
1051
+ // to a small extent. Local ordering should not
1052
+ // be relied upon as any remote change could blow it away
1053
+ if (relationship.localState) {
1054
+ if (!hasValidIndex) {
1055
+ relationship.localState.push(value);
1056
+ } else if (index === 0) {
1057
+ relationship.localState.unshift(value);
1058
+ } else if (!removals?.size) {
1059
+ relationship.localState.splice(index, 0, value);
1060
+ } else {
1061
+ relationship.isDirty = true;
1062
+ }
1063
+ }
1064
+ return true;
1065
+ }
1066
+ function _addLocal(graph, record, relationship, value, index) {
1067
+ const {
1068
+ remoteMembers,
1069
+ removals
1070
+ } = relationship;
1071
+ let additions = relationship.additions;
1072
+ const hasPresence = remoteMembers.has(value) || additions?.has(value);
1073
+ if (hasPresence && !removals?.has(value)) {
1074
+ return false;
1075
+ }
1076
+ if (removals?.has(value)) {
1077
+ removals.delete(value);
1078
+ } else {
1079
+ if (!additions) {
1080
+ additions = relationship.additions = new Set();
1081
+ }
1082
+ relationship.state.hasReceivedData = true;
1083
+ additions.add(value);
1084
+ const {
1085
+ type
1086
+ } = relationship.definition;
1087
+ if (type !== value.type) {
1088
+ graph.registerPolymorphicType(value.type, type);
1089
+ }
1090
+ }
1091
+
1092
+ // if we have existing localState
1093
+ // and we have an index
1094
+ // apply the change, as this is more efficient
1095
+ // than recomputing localState and
1096
+ // it allows us to preserve local ordering
1097
+ // to a small extend. Local ordering should not
1098
+ // be relied upon as any remote change will blow it away
1099
+ if (relationship.localState) {
1100
+ if (index !== null) {
1101
+ relationship.localState.splice(index, 0, value);
1102
+ } else {
1103
+ relationship.localState.push(value);
1104
+ }
1105
+ }
1106
+ return true;
1107
+ }
1108
+ function _remove(graph, record, relationship, value, index, isRemote) {
1109
+ return !isRemote ? _removeLocal(relationship, value) : _removeRemote(relationship, value);
1110
+ }
1111
+ function _removeLocal(relationship, value) {
1112
+ const {
1113
+ remoteMembers,
1114
+ additions
1115
+ } = relationship;
1116
+ let removals = relationship.removals;
1117
+ const hasPresence = remoteMembers.has(value) || additions?.has(value);
1118
+ if (!hasPresence || removals?.has(value)) {
1119
+ return false;
1120
+ }
1121
+ if (additions?.has(value)) {
1122
+ additions.delete(value);
1123
+ } else {
1124
+ if (!removals) {
1125
+ removals = relationship.removals = new Set();
1126
+ }
1127
+ removals.add(value);
1128
+ }
1129
+
1130
+ // if we have existing localState
1131
+ // apply the change, as this is more efficient
1132
+ // than recomputing localState and
1133
+ // it allows us to preserve local ordering
1134
+ // to a small extend. Local ordering should not
1135
+ // be relied upon as any remote change will blow it away
1136
+ if (relationship.localState) {
1137
+ const index = relationship.localState.indexOf(value);
1138
+ relationship.localState.splice(index, 1);
1139
+ }
1140
+ return true;
1141
+ }
1142
+ function _removeRemote(relationship, value) {
1143
+ const {
1144
+ remoteMembers,
1145
+ additions,
1146
+ removals,
1147
+ remoteState
1148
+ } = relationship;
1149
+ if (!remoteMembers.has(value)) {
1150
+ return false;
1151
+ }
1152
+
1153
+ // remove from remote state
1154
+ remoteMembers.delete(value);
1155
+ let index = remoteState.indexOf(value);
1156
+ remoteState.splice(index, 1);
1157
+
1158
+ // remove from removals if present
1159
+ if (removals?.has(value)) {
1160
+ removals.delete(value);
1161
+
1162
+ // nothing more to do this was our state already
1163
+ return false;
1164
+ }
1165
+
1166
+ // if we have existing localState
1167
+ // and we have an index
1168
+ // apply the change, as this is more efficient
1169
+ // than recomputing localState and
1170
+ // it allows us to preserve local ordering
1171
+ // to a small extend. Local ordering should not
1172
+ // be relied upon as any remote change will blow it away
1173
+ if (relationship.localState) {
1174
+ index = relationship.localState.indexOf(value);
1175
+ relationship.localState.splice(index, 1);
1176
+ }
1177
+ return true;
1178
+ }
1179
+ function rollbackRelationship(graph, key, field, relationship) {
1180
+ if (isBelongsTo(relationship)) {
1181
+ replaceRelatedRecord(graph, {
1182
+ record: key,
1183
+ field,
1184
+ value: relationship.remoteState
1185
+ }, false);
1186
+ } else {
1187
+ replaceRelatedRecords(graph, {
1188
+ record: key,
1189
+ field,
1190
+ value: relationship.remoteState.slice()
1191
+ }, false);
1192
+
1193
+ // when the change was a "reorder" only we wont have generated
1194
+ // a notification yet.
1195
+ // if we give rollback a unique operation we can use the ability of
1196
+ // diff to report a separate `remoteOrderChanged` flag to trigger this
1197
+ // if needed to avoid the duplicate.
1198
+ notifyChange(graph, relationship);
1199
+ }
1200
+ }
1201
+ function createState() {
1202
+ return {
1203
+ hasReceivedData: false,
1204
+ isEmpty: true,
1205
+ isStale: false,
1206
+ hasFailedLoadAttempt: false,
1207
+ shouldForceReload: false,
1208
+ hasDematerializedInverse: false
1209
+ };
1210
+ }
1211
+ function createCollectionEdge(definition, identifier) {
1212
+ return {
1213
+ definition,
1214
+ identifier,
1215
+ state: createState(),
1216
+ remoteMembers: new Set(),
1217
+ remoteState: [],
1218
+ additions: null,
1219
+ removals: null,
1220
+ meta: null,
1221
+ links: null,
1222
+ localState: null,
1223
+ isDirty: false,
1224
+ transactionRef: 0,
1225
+ accessed: false,
1226
+ _diff: undefined
1227
+ };
1228
+ }
1229
+ const cp = structuredClone;
1230
+ function legacyGetCollectionRelationshipData(source, getRemoteState) {
1231
+ source.accessed = true;
1232
+ const payload = {};
1233
+ if (source.state.hasReceivedData) {
1234
+ payload.data = getRemoteState ? source.remoteState.slice() : computeLocalState(source);
1235
+ }
1236
+ if (source.links) {
1237
+ payload.links = cp(source.links);
1238
+ }
1239
+ if (source.meta) {
1240
+ payload.meta = cp(source.meta);
1241
+ }
1242
+ return payload;
1243
+ }
1244
+
1245
+ /**
1246
+ Implicit relationships are relationships which have not been declared but the inverse side exists on
1247
+ another record somewhere
1248
+
1249
+ For example consider the following two models
1250
+
1251
+ ::: code-group
1252
+
1253
+ ```js [./models/comment.js]
1254
+ import { Model, attr } from '@warp-drive/legacy/model';
1255
+
1256
+ export default class Comment extends Model {
1257
+ @attr text;
1258
+ }
1259
+ ```
1260
+
1261
+ ```js [./models/post.js]
1262
+ import { Model, attr, hasMany } from '@warp-drive/legacy/model';
1263
+
1264
+ export default class Post extends Model {
1265
+ @attr title;
1266
+ @hasMany('comment', { async: true, inverse: null }) comments;
1267
+ }
1268
+ ```
1269
+
1270
+ :::
1271
+
1272
+ Then we would have a implicit 'post' relationship for the comment record in order
1273
+ to be do things like remove the comment from the post if the comment were to be deleted.
1274
+ */
1275
+
1276
+ function createImplicitEdge(definition, identifier) {
1277
+ return {
1278
+ definition,
1279
+ identifier,
1280
+ localMembers: new Set(),
1281
+ remoteMembers: new Set()
1282
+ };
1283
+ }
1284
+
1285
+ /**
1286
+ * Stores the data for one side of a "single" resource relationship.
1287
+ *
1288
+ * @private
1289
+ */
1290
+
1291
+ function createResourceEdge(definition, identifier) {
1292
+ return {
1293
+ definition,
1294
+ identifier,
1295
+ state: createState(),
1296
+ transactionRef: 0,
1297
+ localState: null,
1298
+ remoteState: null,
1299
+ meta: null,
1300
+ links: null,
1301
+ accessed: false
1302
+ };
1303
+ }
1304
+ function legacyGetResourceRelationshipData(source, getRemoteState) {
1305
+ source.accessed = true;
1306
+ let data;
1307
+ const payload = {};
1308
+ if (getRemoteState && source.remoteState) {
1309
+ data = source.remoteState;
1310
+ } else if (!getRemoteState && source.localState) {
1311
+ data = source.localState;
1312
+ }
1313
+ if ((getRemoteState && source.remoteState === null || source.localState === null) && source.state.hasReceivedData) {
1314
+ data = null;
1315
+ }
1316
+ if (source.links) {
1317
+ payload.links = source.links;
1318
+ }
1319
+ if (data !== undefined) {
1320
+ payload.data = data;
1321
+ }
1322
+ if (source.meta) {
1323
+ payload.meta = source.meta;
1324
+ }
1325
+ return payload;
1326
+ }
1327
+ function addToRelatedRecords(graph, op, isRemote) {
1328
+ const {
1329
+ record,
1330
+ value,
1331
+ index
1332
+ } = op;
1333
+ const relationship = graph.get(record, op.field);
1334
+ const _isBelongsTo = isBelongsTo(relationship);
1335
+ if (isRemote && _isBelongsTo) {
1336
+ if (value !== relationship.remoteState) {
1337
+ const newOp = {
1338
+ record,
1339
+ field: op.field,
1340
+ value: value
1341
+ };
1342
+ return replaceRelatedRecord(graph, newOp, isRemote);
1343
+ }
1344
+ return;
1345
+ }
1346
+
1347
+ // if we are not dirty but have a null localState then we
1348
+ // are mutating a relationship that has never been fetched
1349
+ // so we initialize localState to an empty array
1350
+ if (!relationship.isDirty && !relationship.localState) {
1351
+ relationship.localState = [];
1352
+ }
1353
+ if (Array.isArray(value)) {
1354
+ for (let i = 0; i < value.length; i++) {
1355
+ addRelatedRecord(graph, relationship, record, value[i], index !== undefined ? index + i : null, isRemote);
1356
+ }
1357
+ } else {
1358
+ addRelatedRecord(graph, relationship, record, value, index ?? null, isRemote);
1359
+ }
1360
+ notifyChange(graph, relationship);
1361
+ }
1362
+ function addRelatedRecord(graph, relationship, record, value, index, isRemote) {
1363
+ if (_add(graph, record, relationship, value, index, isRemote)) {
1364
+ addToInverse(graph, value, relationship.definition.inverseKey, record, isRemote);
1365
+ }
1366
+ }
1367
+ function mergeIdentifier(graph, op, relationships) {
1368
+ Object.keys(relationships).forEach(key => {
1369
+ const rel = relationships[key];
1370
+ if (!rel) {
1371
+ return;
1372
+ }
1373
+ mergeIdentifierForRelationship(graph, op, rel);
1374
+ });
1375
+ }
1376
+ function mergeIdentifierForRelationship(graph, op, rel) {
1377
+ rel.identifier = op.value;
1378
+ forAllRelatedIdentifiers(rel, identifier => {
1379
+ const inverse = graph.get(identifier, rel.definition.inverseKey);
1380
+ mergeInRelationship(graph, inverse, op);
1381
+ });
1382
+ }
1383
+ function mergeInRelationship(graph, rel, op) {
1384
+ if (isBelongsTo(rel)) {
1385
+ mergeBelongsTo(graph, rel, op);
1386
+ } else if (isHasMany(rel)) {
1387
+ mergeHasMany(graph, rel, op);
1388
+ } else {
1389
+ mergeImplicit(graph, rel, op);
1390
+ }
1391
+ }
1392
+ function mergeBelongsTo(graph, rel, op) {
1393
+ if (rel.remoteState === op.record) {
1394
+ rel.remoteState = op.value;
1395
+ }
1396
+ if (rel.localState === op.record) {
1397
+ rel.localState = op.value;
1398
+ notifyChange(graph, rel);
1399
+ }
1400
+ }
1401
+ function mergeHasMany(graph, rel, op) {
1402
+ if (rel.remoteMembers.has(op.record)) {
1403
+ rel.remoteMembers.delete(op.record);
1404
+ rel.remoteMembers.add(op.value);
1405
+ const index = rel.remoteState.indexOf(op.record);
1406
+ rel.remoteState.splice(index, 1, op.value);
1407
+ rel.isDirty = true;
1408
+ }
1409
+ if (rel.additions?.has(op.record)) {
1410
+ rel.additions.delete(op.record);
1411
+ rel.additions.add(op.value);
1412
+ rel.isDirty = true;
1413
+ }
1414
+ if (rel.removals?.has(op.record)) {
1415
+ rel.removals.delete(op.record);
1416
+ rel.removals.add(op.value);
1417
+ rel.isDirty = true;
1418
+ }
1419
+ if (rel.isDirty) {
1420
+ notifyChange(graph, rel);
1421
+ }
1422
+ }
1423
+ function mergeImplicit(graph, rel, op) {
1424
+ if (rel.remoteMembers.has(op.record)) {
1425
+ rel.remoteMembers.delete(op.record);
1426
+ rel.remoteMembers.add(op.value);
1427
+ }
1428
+ if (rel.localMembers.has(op.record)) {
1429
+ rel.localMembers.delete(op.record);
1430
+ rel.localMembers.add(op.value);
1431
+ }
1432
+ }
1433
+ function removeFromRelatedRecords(graph, op, isRemote) {
1434
+ const {
1435
+ record,
1436
+ value
1437
+ } = op;
1438
+ const relationship = graph.get(record, op.field);
1439
+ const _isBelongsTo = isBelongsTo(relationship);
1440
+ if (isRemote && _isBelongsTo) {
1441
+ if (value === relationship.remoteState) {
1442
+ const newOp = {
1443
+ record,
1444
+ field: op.field,
1445
+ value: null
1446
+ };
1447
+ return replaceRelatedRecord(graph, newOp, isRemote);
1448
+ }
1449
+ return;
1450
+ }
1451
+ if (Array.isArray(value)) {
1452
+ for (let i = 0; i < value.length; i++) {
1453
+ removeRelatedRecord(graph, record, relationship, value[i], op.index ?? null, isRemote);
1454
+ }
1455
+ } else {
1456
+ removeRelatedRecord(graph, record, relationship, value, op.index ?? null, isRemote);
1457
+ }
1458
+ notifyChange(graph, relationship);
1459
+ }
1460
+ function removeRelatedRecord(graph, record, relationship, value, index, isRemote) {
1461
+ if (_remove(graph, record, relationship, value, index, isRemote)) {
1462
+ removeFromInverse(graph, value, relationship.definition.inverseKey, record, isRemote);
1463
+ }
1464
+ }
1465
+
1466
+ /*
1467
+ This method normalizes a link to an "links object". If the passed link is
1468
+ already an object it's returned without any modifications.
1469
+
1470
+ See http://jsonapi.org/format/#document-links for more information.
1471
+ */
1472
+ function _normalizeLink(link) {
1473
+ switch (typeof link) {
1474
+ case 'object':
1475
+ return link;
1476
+ case 'string':
1477
+ return {
1478
+ href: link
1479
+ };
1480
+ }
1481
+ }
1482
+
1483
+ /*
1484
+ Updates the "canonical" or "remote" state of a relationship, replacing any existing
1485
+ state and blowing away any local changes (excepting new records).
1486
+ */
1487
+ function updateRelationshipOperation(graph, op) {
1488
+ const relationship = graph.get(op.record, op.field);
1489
+ const {
1490
+ definition,
1491
+ state,
1492
+ identifier
1493
+ } = relationship;
1494
+ const {
1495
+ isCollection
1496
+ } = definition;
1497
+ const payload = op.value;
1498
+ let hasRelationshipDataProperty = false;
1499
+ let hasUpdatedLink = false;
1500
+ if (payload.meta) {
1501
+ relationship.meta = payload.meta;
1502
+ }
1503
+ if (payload.data !== undefined) {
1504
+ hasRelationshipDataProperty = true;
1505
+ if (isCollection) {
1506
+ // TODO deprecate this case. We
1507
+ // have tests saying we support it.
1508
+ if (payload.data === null) {
1509
+ payload.data = [];
1510
+ }
1511
+ const cache = graph.store.cacheKeyManager;
1512
+ graph.update({
1513
+ op: 'replaceRelatedRecords',
1514
+ record: identifier,
1515
+ field: op.field,
1516
+ value: upgradeIdentifiers(payload.data, cache)
1517
+ }, true);
1518
+ } else {
1519
+ graph.update({
1520
+ op: 'replaceRelatedRecord',
1521
+ record: identifier,
1522
+ field: op.field,
1523
+ value: payload.data ? graph.store.cacheKeyManager.upgradeIdentifier(payload.data) : null
1524
+ }, true);
1525
+ }
1526
+ } else if (definition.isAsync === false && !state.hasReceivedData) {
1527
+ hasRelationshipDataProperty = true;
1528
+ if (isCollection) {
1529
+ graph.update({
1530
+ op: 'replaceRelatedRecords',
1531
+ record: identifier,
1532
+ field: op.field,
1533
+ value: []
1534
+ }, true);
1535
+ } else {
1536
+ graph.update({
1537
+ op: 'replaceRelatedRecord',
1538
+ record: identifier,
1539
+ field: op.field,
1540
+ value: null
1541
+ }, true);
1542
+ }
1543
+ }
1544
+ if (payload.links) {
1545
+ const originalLinks = relationship.links;
1546
+ relationship.links = payload.links;
1547
+ if (payload.links.related) {
1548
+ const relatedLink = _normalizeLink(payload.links.related);
1549
+ const currentLink = originalLinks && originalLinks.related ? _normalizeLink(originalLinks.related) : null;
1550
+ const currentLinkHref = currentLink ? currentLink.href : null;
1551
+ if (relatedLink && relatedLink.href && relatedLink.href !== currentLinkHref) {
1552
+ hasUpdatedLink = true;
1553
+ }
1554
+ }
1555
+ }
1556
+
1557
+ /*
1558
+ Data being pushed into the relationship might contain only data or links,
1559
+ or a combination of both.
1560
+ IF contains only data
1561
+ IF contains both links and data
1562
+ state.isEmpty -> true if is empty array (has-many) or is null (belongs-to)
1563
+ state.hasReceivedData -> true
1564
+ hasDematerializedInverse -> false
1565
+ state.isStale -> false
1566
+ allInverseRecordsAreLoaded -> run-check-to-determine
1567
+ IF contains only links
1568
+ state.isStale -> true
1569
+ */
1570
+ relationship.state.hasFailedLoadAttempt = false;
1571
+ if (hasRelationshipDataProperty) {
1572
+ const relationshipIsEmpty = payload.data === null || Array.isArray(payload.data) && payload.data.length === 0;
1573
+
1574
+ // we don't need to notify here as the update op we pushed in above will notify once
1575
+ // membership is in the correct state.
1576
+ relationship.state.hasReceivedData = true;
1577
+ relationship.state.isStale = false;
1578
+ relationship.state.hasDematerializedInverse = false;
1579
+ relationship.state.isEmpty = relationshipIsEmpty;
1580
+ } else if (hasUpdatedLink) {
1581
+ // only notify stale if we have not previously received membership data.
1582
+ // within this same transaction
1583
+ // this prevents refetching when only one side of the relationship in the
1584
+ // payload contains the info while the other side contains just a link
1585
+ // this only works when the side with just a link is a belongsTo, as we
1586
+ // don't know if a hasMany has full information or not.
1587
+ // see #7049 for context.
1588
+ if (isCollection || !relationship.state.hasReceivedData || isStaleTransaction(relationship.transactionRef, graph._transaction)) {
1589
+ relationship.state.isStale = true;
1590
+ notifyChange(graph, relationship);
1591
+ } else {
1592
+ relationship.state.isStale = false;
1593
+ }
1594
+ }
1595
+ }
1596
+ function isStaleTransaction(relationshipTransactionId, graphTransactionId) {
1597
+ return relationshipTransactionId === 0 ||
1598
+ // relationship has never notified
1599
+ graphTransactionId === null ||
1600
+ // we are not in a transaction
1601
+ relationshipTransactionId < graphTransactionId // we are not part of the current transaction
1602
+ ;
1603
+ }
1604
+ function upgradeIdentifiers(arr, cache) {
1605
+ for (let i = 0; i < arr.length; i++) {
1606
+ arr[i] = cache.upgradeIdentifier(arr[i]);
1607
+ }
1608
+ return arr;
1609
+ }
1610
+ const Graphs = getOrSetGlobal('Graphs', new Map());
1611
+ /*
1612
+ * Graph acts as the cache for relationship data. It allows for
1613
+ * us to ask about and update relationships for a given Identifier
1614
+ * without requiring other objects for that Identifier to be
1615
+ * instantiated (such as `RecordData` or a `Record`)
1616
+ *
1617
+ * This also allows for us to make more substantive changes to relationships
1618
+ * with increasingly minor alterations to other portions of the internals
1619
+ * over time.
1620
+ *
1621
+ * The graph is made up of nodes and edges. Each unique identifier gets
1622
+ * its own node, which is a dictionary with a list of that node's edges
1623
+ * (or connections) to other nodes. In `Model` terms, a node represents a
1624
+ * record instance, with each key (an edge) in the dictionary correlating
1625
+ * to either a `hasMany` or `belongsTo` field on that record instance.
1626
+ *
1627
+ * The value for each key, or `edge` is the identifier(s) the node relates
1628
+ * to in the graph from that key.
1629
+ */
1630
+ class Graph {
1631
+ constructor(store) {
1632
+ this._definitionCache = Object.create(null);
1633
+ this._metaCache = Object.create(null);
1634
+ this._potentialPolymorphicTypes = Object.create(null);
1635
+ this.identifiers = new Map();
1636
+ this.store = store;
1637
+ this._realStore = store._store;
1638
+ this.isDestroyed = false;
1639
+ this._willSyncRemote = false;
1640
+ this._willSyncLocal = false;
1641
+ this._pushedUpdates = {
1642
+ belongsTo: undefined,
1643
+ hasMany: undefined,
1644
+ deletions: []
1645
+ };
1646
+ this._updatedRelationships = new Set();
1647
+ this._transaction = null;
1648
+ this._removing = null;
1649
+ this.silenceNotifications = false;
1650
+ }
1651
+ has(resourceKey, propertyName) {
1652
+ const relationships = this.identifiers.get(resourceKey);
1653
+ if (!relationships) {
1654
+ return false;
1655
+ }
1656
+ return relationships[propertyName] !== undefined;
1657
+ }
1658
+ getDefinition(resourceKey, propertyName) {
1659
+ let defs = this._metaCache[resourceKey.type];
1660
+ let meta = defs?.[propertyName];
1661
+ if (!meta) {
1662
+ const info = /*#__NOINLINE__*/upgradeDefinition(this, resourceKey, propertyName);
1663
+
1664
+ // if (info.rhs_definition?.kind === 'implicit') {
1665
+ // we should possibly also do this
1666
+ // but it would result in being extremely permissive for other relationships by accident
1667
+ // this.registerPolymorphicType(info.rhs_baseModelName, identifier.type);
1668
+ // }
1669
+
1670
+ meta = /*#__NOINLINE__*/isLHS(info, resourceKey.type, propertyName) ? info.lhs_definition : info.rhs_definition;
1671
+ defs = this._metaCache[resourceKey.type] = defs || {};
1672
+ defs[propertyName] = meta;
1673
+ }
1674
+ return meta;
1675
+ }
1676
+ get(resourceKey, propertyName) {
1677
+ let relationships = this.identifiers.get(resourceKey);
1678
+ if (!relationships) {
1679
+ relationships = Object.create(null);
1680
+ this.identifiers.set(resourceKey, relationships);
1681
+ }
1682
+ let relationship = relationships[propertyName];
1683
+ if (!relationship) {
1684
+ const meta = this.getDefinition(resourceKey, propertyName);
1685
+ if (meta.kind === 'belongsTo') {
1686
+ relationship = relationships[propertyName] = createResourceEdge(meta, resourceKey);
1687
+ } else if (meta.kind === 'hasMany') {
1688
+ relationship = relationships[propertyName] = createCollectionEdge(meta, resourceKey);
1689
+ } else {
1690
+ relationship = relationships[propertyName] = createImplicitEdge(meta, resourceKey);
1691
+ }
1692
+ }
1693
+ return relationship;
1694
+ }
1695
+ getData(resourceKey, propertyName) {
1696
+ const relationship = this.get(resourceKey, propertyName);
1697
+ if (isBelongsTo(relationship)) {
1698
+ return legacyGetResourceRelationshipData(relationship, false);
1699
+ }
1700
+ return legacyGetCollectionRelationshipData(relationship, false);
1701
+ }
1702
+ getRemoteData(resourceKey, propertyName) {
1703
+ const relationship = this.get(resourceKey, propertyName);
1704
+ if (isBelongsTo(relationship)) {
1705
+ return legacyGetResourceRelationshipData(relationship, true);
1706
+ }
1707
+ return legacyGetCollectionRelationshipData(relationship, true);
1708
+ }
1709
+
1710
+ /*
1711
+ * Allows for the graph to dynamically discover polymorphic connections
1712
+ * without needing to walk prototype chains.
1713
+ *
1714
+ * Used by edges when an added `type` does not match the expected `type`
1715
+ * for that edge.
1716
+ *
1717
+ * Currently we assert before calling this. For a public API we will want
1718
+ * to call out to the schema manager to ask if we should consider these
1719
+ * types as equivalent for a given relationship.
1720
+ */
1721
+ registerPolymorphicType(type1, type2) {
1722
+ const typeCache = this._potentialPolymorphicTypes;
1723
+ let t1 = typeCache[type1];
1724
+ if (!t1) {
1725
+ t1 = typeCache[type1] = Object.create(null);
1726
+ }
1727
+ t1[type2] = true;
1728
+ let t2 = typeCache[type2];
1729
+ if (!t2) {
1730
+ t2 = typeCache[type2] = Object.create(null);
1731
+ }
1732
+ t2[type1] = true;
1733
+ }
1734
+ isReleasable(resourceKey) {
1735
+ const relationships = this.identifiers.get(resourceKey);
1736
+ if (!relationships) {
1737
+ return true;
1738
+ }
1739
+ const keys = Object.keys(relationships);
1740
+ for (let i = 0; i < keys.length; i++) {
1741
+ const relationship = relationships[keys[i]];
1742
+ // account for previously unloaded relationships
1743
+ // typically from a prior deletion of a record that pointed to this one implicitly
1744
+ if (relationship === undefined) {
1745
+ continue;
1746
+ }
1747
+ if (relationship.definition.inverseIsAsync && !checkIfNew(this._realStore, resourceKey)) {
1748
+ return false;
1749
+ }
1750
+ }
1751
+ return true;
1752
+ }
1753
+ unload(resourceKey, silenceNotifications) {
1754
+ const relationships = this.identifiers.get(resourceKey);
1755
+ if (relationships) {
1756
+ // cleans up the graph but retains some nodes
1757
+ // to allow for rematerialization
1758
+ Object.keys(relationships).forEach(key => {
1759
+ const rel = relationships[key];
1760
+ if (!rel) {
1761
+ return;
1762
+ }
1763
+ /*#__NOINLINE__*/
1764
+ destroyRelationship(this, rel, silenceNotifications);
1765
+ if (/*#__NOINLINE__*/isImplicit(rel)) {
1766
+ // @ts-expect-error
1767
+ relationships[key] = undefined;
1768
+ }
1769
+ });
1770
+ }
1771
+ }
1772
+ _isDirty(resourceKey, field) {
1773
+ const relationships = this.identifiers.get(resourceKey);
1774
+ if (!relationships) {
1775
+ return false;
1776
+ }
1777
+ const relationship = relationships[field];
1778
+ if (!relationship) {
1779
+ return false;
1780
+ }
1781
+ if (isBelongsTo(relationship)) {
1782
+ return relationship.localState !== relationship.remoteState;
1783
+ } else if (isHasMany(relationship)) {
1784
+ const hasAdditions = relationship.additions !== null && relationship.additions.size > 0;
1785
+ const hasRemovals = relationship.removals !== null && relationship.removals.size > 0;
1786
+ return hasAdditions || hasRemovals || isReordered(relationship);
1787
+ }
1788
+ return false;
1789
+ }
1790
+ getChanged(resourceKey) {
1791
+ const relationships = this.identifiers.get(resourceKey);
1792
+ const changed = new Map();
1793
+ if (!relationships) {
1794
+ return changed;
1795
+ }
1796
+ const keys = Object.keys(relationships);
1797
+ for (let i = 0; i < keys.length; i++) {
1798
+ const field = keys[i];
1799
+ const relationship = relationships[field];
1800
+ if (!relationship) {
1801
+ continue;
1802
+ }
1803
+ if (isBelongsTo(relationship)) {
1804
+ if (relationship.localState !== relationship.remoteState) {
1805
+ changed.set(field, {
1806
+ kind: 'resource',
1807
+ remoteState: relationship.remoteState,
1808
+ localState: relationship.localState
1809
+ });
1810
+ }
1811
+ } else if (isHasMany(relationship)) {
1812
+ const hasAdditions = relationship.additions !== null && relationship.additions.size > 0;
1813
+ const hasRemovals = relationship.removals !== null && relationship.removals.size > 0;
1814
+ const reordered = isReordered(relationship);
1815
+ if (hasAdditions || hasRemovals || reordered) {
1816
+ changed.set(field, {
1817
+ kind: 'collection',
1818
+ additions: new Set(relationship.additions),
1819
+ removals: new Set(relationship.removals),
1820
+ remoteState: relationship.remoteState,
1821
+ localState: legacyGetCollectionRelationshipData(relationship, false).data || [],
1822
+ reordered
1823
+ });
1824
+ }
1825
+ }
1826
+ }
1827
+ return changed;
1828
+ }
1829
+ hasChanged(resourceKey) {
1830
+ const relationships = this.identifiers.get(resourceKey);
1831
+ if (!relationships) {
1832
+ return false;
1833
+ }
1834
+ const keys = Object.keys(relationships);
1835
+ for (let i = 0; i < keys.length; i++) {
1836
+ if (this._isDirty(resourceKey, keys[i])) {
1837
+ return true;
1838
+ }
1839
+ }
1840
+ return false;
1841
+ }
1842
+ rollback(resourceKey) {
1843
+ const relationships = this.identifiers.get(resourceKey);
1844
+ const changed = [];
1845
+ if (!relationships) {
1846
+ return changed;
1847
+ }
1848
+ const keys = Object.keys(relationships);
1849
+ for (let i = 0; i < keys.length; i++) {
1850
+ const field = keys[i];
1851
+ const relationship = relationships[field];
1852
+ if (!relationship) {
1853
+ continue;
1854
+ }
1855
+ if (this._isDirty(resourceKey, field)) {
1856
+ rollbackRelationship(this, resourceKey, field, relationship);
1857
+ changed.push(field);
1858
+ }
1859
+ }
1860
+ return changed;
1861
+ }
1862
+ remove(resourceKey) {
1863
+ this._removing = resourceKey;
1864
+ this.unload(resourceKey);
1865
+ this.identifiers.delete(resourceKey);
1866
+ this._removing = null;
1867
+ }
1868
+
1869
+ /*
1870
+ * Remote state changes
1871
+ */
1872
+ push(op) {
1873
+ if (op.op === 'deleteRecord') {
1874
+ this._pushedUpdates.deletions.push(op);
1875
+ } else {
1876
+ const definition = this.getDefinition(op.record, op.field);
1877
+ addPending(this._pushedUpdates, definition, op);
1878
+ }
1879
+ if (!this._willSyncRemote) {
1880
+ this._willSyncRemote = true;
1881
+ const store = getStore(this.store);
1882
+ if (!store._cbs) {
1883
+ store._run(() => this._flushRemoteQueue());
1884
+ } else {
1885
+ store._schedule('coalesce', () => this._flushRemoteQueue());
1886
+ }
1887
+ }
1888
+ }
1889
+
1890
+ /*
1891
+ * Local state changes
1892
+ */
1893
+
1894
+ update(op, isRemote = false) {
1895
+ switch (op.op) {
1896
+ case 'mergeIdentifiers':
1897
+ {
1898
+ const relationships = this.identifiers.get(op.record);
1899
+ if (relationships) {
1900
+ /*#__NOINLINE__*/mergeIdentifier(this, op, relationships);
1901
+ }
1902
+ break;
1903
+ }
1904
+ case 'update':
1905
+ case 'updateRelationship':
1906
+ /*#__NOINLINE__*/updateRelationshipOperation(this, op);
1907
+ break;
1908
+ case 'deleteRecord':
1909
+ {
1910
+ const identifier = op.record;
1911
+ const relationships = this.identifiers.get(identifier);
1912
+ if (relationships) {
1913
+ Object.keys(relationships).forEach(key => {
1914
+ const rel = relationships[key];
1915
+ if (!rel) {
1916
+ return;
1917
+ }
1918
+ // works together with the has check
1919
+ // @ts-expect-error
1920
+ relationships[key] = undefined;
1921
+ /*#__NOINLINE__*/
1922
+ removeCompletelyFromInverse(this, rel);
1923
+ });
1924
+ this.identifiers.delete(identifier);
1925
+ }
1926
+ break;
1927
+ }
1928
+ case 'replaceRelatedRecord':
1929
+ /*#__NOINLINE__*/replaceRelatedRecord(this, op, isRemote);
1930
+ break;
1931
+ case 'add':
1932
+ /*#__NOINLINE__*/addToRelatedRecords(this, op, isRemote);
1933
+ break;
1934
+ case 'remove':
1935
+ /*#__NOINLINE__*/removeFromRelatedRecords(this, op, isRemote);
1936
+ break;
1937
+ case 'replaceRelatedRecords':
1938
+ /*#__NOINLINE__*/replaceRelatedRecords(this, op, isRemote);
1939
+ break;
1940
+ }
1941
+ }
1942
+ _scheduleLocalSync(relationship) {
1943
+ this._updatedRelationships.add(relationship);
1944
+ if (!this._willSyncLocal) {
1945
+ this._willSyncLocal = true;
1946
+ getStore(this.store)._schedule('sync', () => this._flushLocalQueue());
1947
+ }
1948
+ }
1949
+ _flushRemoteQueue() {
1950
+ if (!this._willSyncRemote) {
1951
+ return;
1952
+ }
1953
+ let transactionRef = peekTransient('transactionRef') ?? 0;
1954
+ this._transaction = ++transactionRef;
1955
+ setTransient('transactionRef', transactionRef);
1956
+ this._willSyncRemote = false;
1957
+ const updates = this._pushedUpdates;
1958
+ const {
1959
+ deletions,
1960
+ hasMany,
1961
+ belongsTo
1962
+ } = updates;
1963
+ updates.deletions = [];
1964
+ updates.hasMany = undefined;
1965
+ updates.belongsTo = undefined;
1966
+ for (let i = 0; i < deletions.length; i++) {
1967
+ this.update(deletions[i], true);
1968
+ }
1969
+ if (hasMany) {
1970
+ flushPending(this, hasMany);
1971
+ }
1972
+ if (belongsTo) {
1973
+ flushPending(this, belongsTo);
1974
+ }
1975
+ this._transaction = null;
1976
+ }
1977
+ _addToTransaction(relationship) {
1978
+ relationship.transactionRef = this._transaction;
1979
+ }
1980
+ _flushLocalQueue() {
1981
+ if (!this._willSyncLocal) {
1982
+ return;
1983
+ }
1984
+ if (this.silenceNotifications) {
1985
+ this.silenceNotifications = false;
1986
+ this._updatedRelationships = new Set();
1987
+ return;
1988
+ }
1989
+ this._willSyncLocal = false;
1990
+ const updated = this._updatedRelationships;
1991
+ this._updatedRelationships = new Set();
1992
+ updated.forEach(rel => notifyChange(this, rel));
1993
+ }
1994
+ destroy() {
1995
+ Graphs.delete(this.store);
1996
+ this.identifiers.clear();
1997
+ this.store = null;
1998
+ this.isDestroyed = true;
1999
+ }
2000
+ }
2001
+ function flushPending(graph, ops) {
2002
+ for (const type of ops.values()) {
2003
+ for (const opList of type.values()) {
2004
+ flushPendingList(graph, opList);
2005
+ }
2006
+ }
2007
+ }
2008
+ function flushPendingList(graph, opList) {
2009
+ for (let i = 0; i < opList.length; i++) {
2010
+ graph.update(opList[i], true);
2011
+ }
2012
+ }
2013
+
2014
+ // Handle dematerialization for relationship `rel`. In all cases, notify the
2015
+ // relationship of the dematerialization: this is done so the relationship can
2016
+ // notify its inverse which needs to update state
2017
+ //
2018
+ // If the inverse is sync, unloading this record is treated as a client-side
2019
+ // delete, so we remove the inverse records from this relationship to
2020
+ // disconnect the graph. Because it's not async, we don't need to keep around
2021
+ // the identifier as an id-wrapper for references
2022
+ function destroyRelationship(graph, rel, silenceNotifications) {
2023
+ if (isImplicit(rel)) {
2024
+ if (graph.isReleasable(rel.identifier)) {
2025
+ /*#__NOINLINE__*/removeCompletelyFromInverse(graph, rel);
2026
+ }
2027
+ return;
2028
+ }
2029
+ const {
2030
+ identifier
2031
+ } = rel;
2032
+ const {
2033
+ inverseKey
2034
+ } = rel.definition;
2035
+ if (!rel.definition.inverseIsImplicit) {
2036
+ /*#__NOINLINE__*/forAllRelatedIdentifiers(rel, inverseIdentifer => /*#__NOINLINE__*/notifyInverseOfDematerialization(graph, inverseIdentifer, inverseKey, identifier, silenceNotifications));
2037
+ }
2038
+ if (!rel.definition.inverseIsImplicit && !rel.definition.inverseIsAsync) {
2039
+ rel.state.isStale = true;
2040
+ /*#__NOINLINE__*/
2041
+ clearRelationship(rel);
2042
+
2043
+ // necessary to clear relationships in the ui from dematerialized records
2044
+ // hasMany is managed by Model which calls `retreiveLatest` after
2045
+ // dematerializing the resource-cache instance.
2046
+ // but sync belongsTo requires this since they don't have a proxy to update.
2047
+ // so we have to notify so it will "update" to null.
2048
+ // we should discuss whether we still care about this, probably fine to just
2049
+ // leave the ui relationship populated since the record is destroyed and
2050
+ // internally we've fully cleaned up.
2051
+ if (!rel.definition.isAsync && !silenceNotifications) {
2052
+ /*#__NOINLINE__*/notifyChange(graph, rel);
2053
+ }
2054
+ }
2055
+ }
2056
+ function notifyInverseOfDematerialization(graph, inverseIdentifier, inverseKey, resourceKey, silenceNotifications) {
2057
+ if (!graph.has(inverseIdentifier, inverseKey)) {
2058
+ return;
2059
+ }
2060
+ const relationship = graph.get(inverseIdentifier, inverseKey);
2061
+
2062
+ // For remote members, it is possible that inverseRecordData has already been associated to
2063
+ // to another record. For such cases, do not dematerialize the inverseRecordData
2064
+ if (!isBelongsTo(relationship) || !relationship.localState || resourceKey === relationship.localState) {
2065
+ /*#__NOINLINE__*/removeDematerializedInverse(graph, relationship, resourceKey, silenceNotifications);
2066
+ }
2067
+ }
2068
+ function clearRelationship(relationship) {
2069
+ if (isBelongsTo(relationship)) {
2070
+ relationship.localState = null;
2071
+ relationship.remoteState = null;
2072
+ relationship.state.hasReceivedData = false;
2073
+ relationship.state.isEmpty = true;
2074
+ } else {
2075
+ relationship.remoteMembers.clear();
2076
+ relationship.remoteState = [];
2077
+ relationship.additions = null;
2078
+ relationship.removals = null;
2079
+ relationship.localState = null;
2080
+ }
2081
+ }
2082
+ function removeDematerializedInverse(graph, relationship, inverseIdentifier, silenceNotifications) {
2083
+ if (isBelongsTo(relationship)) {
2084
+ const localInverse = relationship.localState;
2085
+ if (!relationship.definition.isAsync || localInverse && checkIfNew(graph._realStore, localInverse)) {
2086
+ // unloading inverse of a sync relationship is treated as a client-side
2087
+ // delete, so actually remove the models don't merely invalidate the cp
2088
+ // cache.
2089
+ // if the record being unloaded only exists on the client, we similarly
2090
+ // treat it as a client side delete
2091
+ if (relationship.localState === localInverse && localInverse !== null) {
2092
+ relationship.localState = null;
2093
+ }
2094
+ if (relationship.remoteState === localInverse && localInverse !== null) {
2095
+ relationship.remoteState = null;
2096
+ relationship.state.hasReceivedData = true;
2097
+ relationship.state.isEmpty = true;
2098
+ if (relationship.localState && !checkIfNew(graph._realStore, relationship.localState)) {
2099
+ relationship.localState = null;
2100
+ }
2101
+ }
2102
+ } else {
2103
+ relationship.state.hasDematerializedInverse = true;
2104
+ }
2105
+ if (!silenceNotifications) {
2106
+ notifyChange(graph, relationship);
2107
+ }
2108
+ } else {
2109
+ if (!relationship.definition.isAsync || inverseIdentifier && checkIfNew(graph._realStore, inverseIdentifier)) {
2110
+ // unloading inverse of a sync relationship is treated as a client-side
2111
+ // delete, so actually remove the models don't merely invalidate the cp
2112
+ // cache.
2113
+ // if the record being unloaded only exists on the client, we similarly
2114
+ // treat it as a client side delete
2115
+ /*#__NOINLINE__*/
2116
+ removeIdentifierCompletelyFromRelationship(graph, relationship, inverseIdentifier);
2117
+ } else {
2118
+ relationship.state.hasDematerializedInverse = true;
2119
+ }
2120
+ if (!silenceNotifications) {
2121
+ notifyChange(graph, relationship);
2122
+ }
2123
+ }
2124
+ }
2125
+ function removeCompletelyFromInverse(graph, relationship) {
2126
+ const {
2127
+ identifier
2128
+ } = relationship;
2129
+ const {
2130
+ inverseKey
2131
+ } = relationship.definition;
2132
+ forAllRelatedIdentifiers(relationship, inverseIdentifier => {
2133
+ if (graph.has(inverseIdentifier, inverseKey)) {
2134
+ removeIdentifierCompletelyFromRelationship(graph, graph.get(inverseIdentifier, inverseKey), identifier);
2135
+ }
2136
+ });
2137
+ if (isBelongsTo(relationship)) {
2138
+ if (!relationship.definition.isAsync) {
2139
+ clearRelationship(relationship);
2140
+ }
2141
+ relationship.localState = null;
2142
+ } else if (isHasMany(relationship)) {
2143
+ if (!relationship.definition.isAsync) {
2144
+ clearRelationship(relationship);
2145
+ notifyChange(graph, relationship);
2146
+ }
2147
+ } else {
2148
+ relationship.remoteMembers.clear();
2149
+ relationship.localMembers.clear();
2150
+ }
2151
+ }
2152
+ function addPending(cache, definition, op) {
2153
+ const cacheForKind = cache[definition.kind] = cache[definition.kind] || new Map();
2154
+ let cacheForType = cacheForKind.get(definition.inverseType);
2155
+ if (!cacheForType) {
2156
+ cacheForType = new Map();
2157
+ cacheForKind.set(definition.inverseType, cacheForType);
2158
+ }
2159
+ let cacheForField = cacheForType.get(op.field);
2160
+ if (!cacheForField) {
2161
+ cacheForField = [];
2162
+ cacheForType.set(op.field, cacheForField);
2163
+ }
2164
+ cacheForField.push(op);
2165
+ }
2166
+ function isReordered(relationship) {
2167
+ // if we are dirty we are never re-ordered because accessing
2168
+ // the state would flush away any reordering.
2169
+ if (relationship.isDirty) {
2170
+ return false;
2171
+ }
2172
+ const {
2173
+ remoteState,
2174
+ localState,
2175
+ additions,
2176
+ removals
2177
+ } = relationship;
2178
+ if (localState === null) {
2179
+ // the relationship has never been accessed, so it hasn't been reordered either
2180
+ return false;
2181
+ }
2182
+ for (let i = 0, j = 0; i < remoteState.length; i++) {
2183
+ const member = remoteState[i];
2184
+ const localMember = localState[j];
2185
+ if (member !== localMember) {
2186
+ if (removals && removals.has(member)) {
2187
+ // dont increment j because we want to skip this
2188
+ continue;
2189
+ }
2190
+ if (additions && additions.has(localMember)) {
2191
+ // increment j to skip this localMember
2192
+ // decrement i to repeat this remoteMember
2193
+ j++;
2194
+ i--;
2195
+ continue;
2196
+ }
2197
+ return true;
2198
+ }
2199
+
2200
+ // if we made it here, increment j
2201
+ j++;
2202
+ }
2203
+ return false;
2204
+ }
2205
+
2206
+ /**
2207
+ Provides a performance tuned normalized graph for intelligently managing relationships between resources based on identity
2208
+
2209
+ While this Graph is abstract, it currently is a private implementation required as a peer-dependency by the {json:api} Cache Implementation.
2210
+
2211
+ We intend to make this Graph public API after some additional iteration during the 5.x timeframe, until then all APIs should be considered experimental and unstable, not fit for direct application or 3rd party library usage.
2212
+
2213
+ @module
2214
+ */
2215
+
2216
+ function isStore(maybeStore) {
2217
+ return maybeStore._instanceCache !== undefined;
2218
+ }
2219
+ function getWrapper(store) {
2220
+ return isStore(store) ? store._instanceCache._storeWrapper : store;
2221
+ }
2222
+ function peekGraph(store) {
2223
+ return Graphs.get(getWrapper(store));
2224
+ }
2225
+ function graphFor(store) {
2226
+ const wrapper = getWrapper(store);
2227
+ let graph = Graphs.get(wrapper);
2228
+ if (!graph) {
2229
+ graph = new Graph(wrapper);
2230
+ Graphs.set(wrapper, graph);
2231
+ getStore(wrapper)._graph = graph;
2232
+ }
2233
+ return graph;
2234
+ }
2235
+ export { graphFor, isBelongsTo, peekGraph };