breeze-client 2.2.2 → 3.0.0

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 (299) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +83 -63
  3. package/adapters/abstract-data-service-adapter.d.ts +120 -0
  4. package/adapters/abstract-data-service-adapter.js +395 -0
  5. package/adapters/abstract-data-service-adapter.js.map +1 -0
  6. package/adapters/adapter-ajax-fetch.d.ts +12 -0
  7. package/adapters/adapter-ajax-fetch.js +13 -0
  8. package/adapters/adapter-ajax-fetch.js.map +1 -0
  9. package/{adapter-ajax-post → adapters}/adapter-ajax-post.d.ts +40 -36
  10. package/{fesm2022/breeze-client-adapter-ajax-post.mjs → adapters/adapter-ajax-post.js} +80 -82
  11. package/adapters/adapter-ajax-post.js.map +1 -0
  12. package/{adapter-ajax-fetch → adapters}/adapter-core.d.ts +4 -4
  13. package/{fesm2022/breeze-client-adapter-uri-builder-json.mjs → adapters/adapter-core.js} +48 -91
  14. package/adapters/adapter-core.js.map +1 -0
  15. package/adapters/adapter-data-service-webapi.d.ts +9 -0
  16. package/{fesm2022/breeze-client-adapter-data-service-webapi.mjs → adapters/adapter-data-service-webapi.js} +105 -107
  17. package/adapters/adapter-data-service-webapi.js.map +1 -0
  18. package/adapters/adapter-model-library-backing-store.d.ts +32 -0
  19. package/adapters/adapter-model-library-backing-store.js +321 -0
  20. package/adapters/adapter-model-library-backing-store.js.map +1 -0
  21. package/adapters/adapter-uri-builder-json.d.ts +11 -0
  22. package/adapters/adapter-uri-builder-json.js +40 -0
  23. package/adapters/adapter-uri-builder-json.js.map +1 -0
  24. package/adapters/http.d.ts +52 -0
  25. package/adapters/http.js +202 -0
  26. package/adapters/http.js.map +1 -0
  27. package/angular/adapter-angular-httpclient.d.ts +21 -0
  28. package/angular/adapter-angular-httpclient.js +70 -0
  29. package/angular/adapter-angular-httpclient.js.map +1 -0
  30. package/breeze.d.ts +215 -0
  31. package/breeze.js +141 -0
  32. package/breeze.js.map +1 -0
  33. package/config/config.d.ts +212 -0
  34. package/config/config.js +392 -0
  35. package/config/config.js.map +1 -0
  36. package/config/configure.d.ts +66 -0
  37. package/config/configure.js +46 -0
  38. package/config/configure.js.map +1 -0
  39. package/config/default-adapters.d.ts +1 -0
  40. package/config/default-adapters.js +40 -0
  41. package/config/default-adapters.js.map +1 -0
  42. package/config/interface-registry.d.ts +191 -0
  43. package/config/interface-registry.js +5 -0
  44. package/config/interface-registry.js.map +1 -0
  45. package/{src → core}/assert-param.d.ts +52 -60
  46. package/core/assert-param.js +390 -0
  47. package/core/assert-param.js.map +1 -0
  48. package/core/core.d.ts +285 -0
  49. package/core/core.js +772 -0
  50. package/core/core.js.map +1 -0
  51. package/core/enum.d.ts +116 -0
  52. package/core/enum.js +167 -0
  53. package/core/enum.js.map +1 -0
  54. package/core/event.d.ts +169 -0
  55. package/core/event.js +338 -0
  56. package/core/event.js.map +1 -0
  57. package/entity/array.d.ts +3 -0
  58. package/entity/array.js +4 -0
  59. package/entity/array.js.map +1 -0
  60. package/entity/complex-array.d.ts +17 -0
  61. package/entity/complex-array.js +104 -0
  62. package/entity/complex-array.js.map +1 -0
  63. package/entity/default-property-interceptor.d.ts +1 -0
  64. package/entity/default-property-interceptor.js +496 -0
  65. package/entity/default-property-interceptor.js.map +1 -0
  66. package/{src → entity}/entity-action.d.ts +36 -42
  67. package/entity/entity-action.js +45 -0
  68. package/entity/entity-action.js.map +1 -0
  69. package/entity/entity-aspect.d.ts +457 -0
  70. package/entity/entity-aspect.js +1262 -0
  71. package/entity/entity-aspect.js.map +1 -0
  72. package/entity/entity-base.d.ts +55 -0
  73. package/entity/entity-base.js +41 -0
  74. package/entity/entity-base.js.map +1 -0
  75. package/entity/entity-group.d.ts +1 -0
  76. package/entity/entity-group.js +224 -0
  77. package/entity/entity-group.js.map +1 -0
  78. package/entity/entity-key.d.ts +95 -0
  79. package/entity/entity-key.js +189 -0
  80. package/entity/entity-key.js.map +1 -0
  81. package/{src → entity}/entity-state.d.ts +112 -84
  82. package/entity/entity-state.js +135 -0
  83. package/entity/entity-state.js.map +1 -0
  84. package/entity/key-generator.d.ts +57 -0
  85. package/entity/key-generator.js +155 -0
  86. package/entity/key-generator.js.map +1 -0
  87. package/entity/observable-array.d.ts +25 -0
  88. package/entity/observable-array.js +230 -0
  89. package/entity/observable-array.js.map +1 -0
  90. package/entity/primitive-array.d.ts +12 -0
  91. package/entity/primitive-array.js +71 -0
  92. package/entity/primitive-array.js.map +1 -0
  93. package/entity/relation-array.d.ts +24 -0
  94. package/entity/relation-array.js +176 -0
  95. package/entity/relation-array.js.map +1 -0
  96. package/entity/unattached-children-map.d.ts +1 -0
  97. package/entity/unattached-children-map.js +105 -0
  98. package/entity/unattached-children-map.js.map +1 -0
  99. package/generate-entity-classes.js +1176 -0
  100. package/manager/entity-manager.d.ts +801 -0
  101. package/manager/entity-manager.js +2395 -0
  102. package/manager/entity-manager.js.map +1 -0
  103. package/{src → manager}/save-options.d.ts +48 -42
  104. package/manager/save-options.js +51 -0
  105. package/manager/save-options.js.map +1 -0
  106. package/{src → metadata}/data-service.d.ts +229 -184
  107. package/metadata/data-service.js +246 -0
  108. package/metadata/data-service.js.map +1 -0
  109. package/metadata/data-type.d.ts +122 -0
  110. package/metadata/data-type.js +465 -0
  111. package/metadata/data-type.js.map +1 -0
  112. package/metadata/entity-metadata.d.ts +1193 -0
  113. package/metadata/entity-metadata.js +2502 -0
  114. package/metadata/entity-metadata.js.map +1 -0
  115. package/{src → metadata}/local-query-comparison-options.d.ts +65 -59
  116. package/metadata/local-query-comparison-options.js +69 -0
  117. package/metadata/local-query-comparison-options.js.map +1 -0
  118. package/{src → metadata}/naming-convention.d.ts +75 -72
  119. package/metadata/naming-convention.js +97 -0
  120. package/metadata/naming-convention.js.map +1 -0
  121. package/mixins/mixin-get-entity-graph.d.ts +63 -0
  122. package/{fesm2022/breeze-client-mixin-get-entity-graph.mjs → mixins/mixin-get-entity-graph.js} +331 -253
  123. package/mixins/mixin-get-entity-graph.js.map +1 -0
  124. package/mixins/mixin-save-queuing.d.ts +98 -0
  125. package/{fesm2022/breeze-client-mixin-save-queuing.mjs → mixins/mixin-save-queuing.js} +493 -365
  126. package/mixins/mixin-save-queuing.js.map +1 -0
  127. package/package.json +63 -94
  128. package/query/entity-query.d.ts +521 -0
  129. package/query/entity-query.js +1149 -0
  130. package/query/entity-query.js.map +1 -0
  131. package/{src → query}/mapping-context.d.ts +44 -46
  132. package/query/mapping-context.js +412 -0
  133. package/query/mapping-context.js.map +1 -0
  134. package/query/predicate.d.ts +394 -0
  135. package/query/predicate.js +1294 -0
  136. package/query/predicate.js.map +1 -0
  137. package/query/property-path.d.ts +252 -0
  138. package/query/property-path.js +2 -0
  139. package/query/property-path.js.map +1 -0
  140. package/{src → query}/query-options.d.ts +143 -119
  141. package/query/query-options.js +180 -0
  142. package/query/query-options.js.map +1 -0
  143. package/rxjs/breeze-rxjs.d.ts +72 -0
  144. package/rxjs/breeze-rxjs.js +117 -0
  145. package/rxjs/breeze-rxjs.js.map +1 -0
  146. package/validation/validate.d.ts +583 -0
  147. package/validation/validate.js +961 -0
  148. package/validation/validate.js.map +1 -0
  149. package/{src → validation}/validation-options.d.ts +67 -63
  150. package/validation/validation-options.js +70 -0
  151. package/validation/validation-options.js.map +1 -0
  152. package/adapter-ajax-angularjs/adapter-ajax-angularjs.d.ts +0 -17
  153. package/adapter-ajax-angularjs/adapter-core.d.ts +0 -4
  154. package/adapter-ajax-angularjs/index.d.ts +0 -5
  155. package/adapter-ajax-fetch/adapter-ajax-fetch.d.ts +0 -18
  156. package/adapter-ajax-fetch/index.d.ts +0 -5
  157. package/adapter-ajax-httpclient/adapter-ajax-httpclient.d.ts +0 -13
  158. package/adapter-ajax-httpclient/adapter-core.d.ts +0 -4
  159. package/adapter-ajax-httpclient/index.d.ts +0 -5
  160. package/adapter-ajax-jquery/adapter-ajax-jquery.d.ts +0 -15
  161. package/adapter-ajax-jquery/index.d.ts +0 -5
  162. package/adapter-ajax-post/index.d.ts +0 -5
  163. package/adapter-data-service-odata/adapter-core.d.ts +0 -4
  164. package/adapter-data-service-odata/adapter-data-service-odata.d.ts +0 -17
  165. package/adapter-data-service-odata/index.d.ts +0 -5
  166. package/adapter-data-service-webapi/adapter-data-service-webapi.d.ts +0 -15
  167. package/adapter-data-service-webapi/index.d.ts +0 -5
  168. package/adapter-model-library-backing-store/adapter-model-library-backing-store.d.ts +0 -10
  169. package/adapter-model-library-backing-store/index.d.ts +0 -5
  170. package/adapter-model-library-ko/adapter-model-library-ko.d.ts +0 -10
  171. package/adapter-model-library-ko/index.d.ts +0 -5
  172. package/adapter-uri-builder-json/adapter-core.d.ts +0 -4
  173. package/adapter-uri-builder-json/adapter-uri-builder-json.d.ts +0 -8
  174. package/adapter-uri-builder-json/index.d.ts +0 -5
  175. package/adapter-uri-builder-odata/adapter-core.d.ts +0 -4
  176. package/adapter-uri-builder-odata/adapter-uri-builder-odata.d.ts +0 -8
  177. package/adapter-uri-builder-odata/index.d.ts +0 -5
  178. package/esm2022/adapter-ajax-angularjs/adapter-ajax-angularjs.mjs +0 -135
  179. package/esm2022/adapter-ajax-angularjs/adapter-core.mjs +0 -49
  180. package/esm2022/adapter-ajax-angularjs/breeze-client-adapter-ajax-angularjs.mjs +0 -5
  181. package/esm2022/adapter-ajax-fetch/adapter-ajax-fetch.mjs +0 -135
  182. package/esm2022/adapter-ajax-fetch/adapter-core.mjs +0 -49
  183. package/esm2022/adapter-ajax-fetch/breeze-client-adapter-ajax-fetch.mjs +0 -5
  184. package/esm2022/adapter-ajax-httpclient/adapter-ajax-httpclient.mjs +0 -139
  185. package/esm2022/adapter-ajax-httpclient/adapter-core.mjs +0 -49
  186. package/esm2022/adapter-ajax-httpclient/breeze-client-adapter-ajax-httpclient.mjs +0 -5
  187. package/esm2022/adapter-ajax-jquery/adapter-ajax-jquery.mjs +0 -107
  188. package/esm2022/adapter-ajax-jquery/breeze-client-adapter-ajax-jquery.mjs +0 -5
  189. package/esm2022/adapter-ajax-post/adapter-ajax-post.mjs +0 -77
  190. package/esm2022/adapter-ajax-post/breeze-client-adapter-ajax-post.mjs +0 -5
  191. package/esm2022/adapter-data-service-odata/adapter-core.mjs +0 -49
  192. package/esm2022/adapter-data-service-odata/adapter-data-service-odata.mjs +0 -461
  193. package/esm2022/adapter-data-service-odata/breeze-client-adapter-data-service-odata.mjs +0 -5
  194. package/esm2022/adapter-data-service-webapi/adapter-data-service-webapi.mjs +0 -100
  195. package/esm2022/adapter-data-service-webapi/breeze-client-adapter-data-service-webapi.mjs +0 -5
  196. package/esm2022/adapter-model-library-backing-store/adapter-model-library-backing-store.mjs +0 -269
  197. package/esm2022/adapter-model-library-backing-store/breeze-client-adapter-model-library-backing-store.mjs +0 -5
  198. package/esm2022/adapter-model-library-ko/adapter-model-library-ko.mjs +0 -241
  199. package/esm2022/adapter-model-library-ko/breeze-client-adapter-model-library-ko.mjs +0 -5
  200. package/esm2022/adapter-uri-builder-json/adapter-core.mjs +0 -49
  201. package/esm2022/adapter-uri-builder-json/adapter-uri-builder-json.mjs +0 -37
  202. package/esm2022/adapter-uri-builder-json/breeze-client-adapter-uri-builder-json.mjs +0 -5
  203. package/esm2022/adapter-uri-builder-odata/adapter-core.mjs +0 -49
  204. package/esm2022/adapter-uri-builder-odata/adapter-uri-builder-odata.mjs +0 -191
  205. package/esm2022/adapter-uri-builder-odata/breeze-client-adapter-uri-builder-odata.mjs +0 -5
  206. package/esm2022/breeze-client.mjs +0 -5
  207. package/esm2022/index.mjs +0 -2
  208. package/esm2022/mixin-get-entity-graph/breeze-client-mixin-get-entity-graph.mjs +0 -5
  209. package/esm2022/mixin-get-entity-graph/mixin-get-entity-graph.mjs +0 -269
  210. package/esm2022/mixin-save-queuing/breeze-client-mixin-save-queuing.mjs +0 -5
  211. package/esm2022/mixin-save-queuing/mixin-save-queuing.mjs +0 -421
  212. package/esm2022/src/abstract-data-service-adapter.mjs +0 -325
  213. package/esm2022/src/array.mjs +0 -4
  214. package/esm2022/src/assert-param.mjs +0 -330
  215. package/esm2022/src/breeze.mjs +0 -85
  216. package/esm2022/src/complex-array.mjs +0 -117
  217. package/esm2022/src/config.mjs +0 -232
  218. package/esm2022/src/core.mjs +0 -712
  219. package/esm2022/src/csdl-metadata-parser.mjs +0 -385
  220. package/esm2022/src/data-service.mjs +0 -221
  221. package/esm2022/src/data-type.mjs +0 -510
  222. package/esm2022/src/default-property-interceptor.mjs +0 -460
  223. package/esm2022/src/entity-action.mjs +0 -45
  224. package/esm2022/src/entity-aspect.mjs +0 -897
  225. package/esm2022/src/entity-group.mjs +0 -192
  226. package/esm2022/src/entity-key.mjs +0 -125
  227. package/esm2022/src/entity-manager.mjs +0 -2163
  228. package/esm2022/src/entity-metadata.mjs +0 -2242
  229. package/esm2022/src/entity-query.mjs +0 -1024
  230. package/esm2022/src/entity-state.mjs +0 -107
  231. package/esm2022/src/enum.mjs +0 -143
  232. package/esm2022/src/event.mjs +0 -264
  233. package/esm2022/src/interface-registry.mjs +0 -39
  234. package/esm2022/src/key-generator.mjs +0 -110
  235. package/esm2022/src/local-query-comparison-options.mjs +0 -65
  236. package/esm2022/src/mapping-context.mjs +0 -411
  237. package/esm2022/src/naming-convention.mjs +0 -92
  238. package/esm2022/src/observable-array.mjs +0 -183
  239. package/esm2022/src/predicate.mjs +0 -1259
  240. package/esm2022/src/primitive-array.mjs +0 -85
  241. package/esm2022/src/query-options.mjs +0 -152
  242. package/esm2022/src/relation-array.mjs +0 -173
  243. package/esm2022/src/save-options.mjs +0 -41
  244. package/esm2022/src/unattached-children-map.mjs +0 -56
  245. package/esm2022/src/validate.mjs +0 -995
  246. package/esm2022/src/validation-options.mjs +0 -64
  247. package/fesm2022/breeze-client-adapter-ajax-angularjs.mjs +0 -190
  248. package/fesm2022/breeze-client-adapter-ajax-angularjs.mjs.map +0 -1
  249. package/fesm2022/breeze-client-adapter-ajax-fetch.mjs +0 -190
  250. package/fesm2022/breeze-client-adapter-ajax-fetch.mjs.map +0 -1
  251. package/fesm2022/breeze-client-adapter-ajax-httpclient.mjs +0 -194
  252. package/fesm2022/breeze-client-adapter-ajax-httpclient.mjs.map +0 -1
  253. package/fesm2022/breeze-client-adapter-ajax-jquery.mjs +0 -114
  254. package/fesm2022/breeze-client-adapter-ajax-jquery.mjs.map +0 -1
  255. package/fesm2022/breeze-client-adapter-ajax-post.mjs.map +0 -1
  256. package/fesm2022/breeze-client-adapter-data-service-odata.mjs +0 -516
  257. package/fesm2022/breeze-client-adapter-data-service-odata.mjs.map +0 -1
  258. package/fesm2022/breeze-client-adapter-data-service-webapi.mjs.map +0 -1
  259. package/fesm2022/breeze-client-adapter-model-library-backing-store.mjs +0 -276
  260. package/fesm2022/breeze-client-adapter-model-library-backing-store.mjs.map +0 -1
  261. package/fesm2022/breeze-client-adapter-model-library-ko.mjs +0 -248
  262. package/fesm2022/breeze-client-adapter-model-library-ko.mjs.map +0 -1
  263. package/fesm2022/breeze-client-adapter-uri-builder-json.mjs.map +0 -1
  264. package/fesm2022/breeze-client-adapter-uri-builder-odata.mjs +0 -246
  265. package/fesm2022/breeze-client-adapter-uri-builder-odata.mjs.map +0 -1
  266. package/fesm2022/breeze-client-mixin-get-entity-graph.mjs.map +0 -1
  267. package/fesm2022/breeze-client-mixin-save-queuing.mjs.map +0 -1
  268. package/fesm2022/breeze-client.mjs +0 -14144
  269. package/fesm2022/breeze-client.mjs.map +0 -1
  270. package/index.d.ts +0 -1
  271. package/mixin-get-entity-graph/index.d.ts +0 -5
  272. package/mixin-get-entity-graph/mixin-get-entity-graph.d.ts +0 -31
  273. package/mixin-save-queuing/index.d.ts +0 -5
  274. package/mixin-save-queuing/mixin-save-queuing.d.ts +0 -32
  275. package/src/abstract-data-service-adapter.d.ts +0 -84
  276. package/src/array.d.ts +0 -3
  277. package/src/breeze.d.ts +0 -139
  278. package/src/complex-array.d.ts +0 -13
  279. package/src/config.d.ts +0 -104
  280. package/src/core.d.ts +0 -164
  281. package/src/csdl-metadata-parser.d.ts +0 -7
  282. package/src/data-type.d.ts +0 -89
  283. package/src/default-property-interceptor.d.ts +0 -4
  284. package/src/entity-aspect.d.ts +0 -332
  285. package/src/entity-group.d.ts +0 -28
  286. package/src/entity-key.d.ts +0 -77
  287. package/src/entity-manager.d.ts +0 -680
  288. package/src/entity-metadata.d.ts +0 -988
  289. package/src/entity-query.d.ts +0 -444
  290. package/src/enum.d.ts +0 -100
  291. package/src/event.d.ts +0 -142
  292. package/src/interface-registry.d.ts +0 -150
  293. package/src/key-generator.d.ts +0 -12
  294. package/src/observable-array.d.ts +0 -52
  295. package/src/predicate.d.ts +0 -376
  296. package/src/primitive-array.d.ts +0 -7
  297. package/src/relation-array.d.ts +0 -18
  298. package/src/unattached-children-map.d.ts +0 -19
  299. package/src/validate.d.ts +0 -650
@@ -0,0 +1,2395 @@
1
+ import { core, arraySlice } from '../core/core.js';
2
+ import { assertParam, assertConfig } from '../core/assert-param.js';
3
+ import { config, setDefaultAdapters } from '../config/config.js';
4
+ import { BreezeEvent } from '../core/event.js';
5
+ import { EntityAspect, peekProperty } from '../entity/entity-aspect.js';
6
+ import { MetadataStore, EntityType, DataProperty, AutoGeneratedKeyType, entityTypeForCtor } from '../metadata/entity-metadata.js';
7
+ import { EntityKey } from '../entity/entity-key.js';
8
+ import { observableArray } from '../entity/observable-array.js';
9
+ import { EntityAction } from '../entity/entity-action.js';
10
+ import { EntityState } from '../entity/entity-state.js';
11
+ import { DataService } from '../metadata/data-service.js';
12
+ import { DataType } from '../metadata/data-type.js';
13
+ import { ValidationError } from '../validation/validate.js';
14
+ import { ValidationOptions } from '../validation/validation-options.js';
15
+ import { QueryOptions, MergeStrategy, FetchStrategy } from '../query/query-options.js';
16
+ import { SaveOptions } from './save-options.js';
17
+ import { KeyGenerator } from '../entity/key-generator.js';
18
+ import { EntityGroup } from '../entity/entity-group.js';
19
+ import { MappingContext } from '../query/mapping-context.js';
20
+ import { EntityQuery } from '../query/entity-query.js';
21
+ import { UnattachedChildrenMap } from '../entity/unattached-children-map.js';
22
+ import { serverDefaultAdapters } from '../config/default-adapters.js';
23
+ /** The RFC 9457 `type` URIs a Breeze server sends on {@link ServerError.problemType}.
24
+
25
+ A problem type is a stable identifier for a *kind* of failure, which is what a status code often
26
+ is not: `409` covers both a concurrency conflict and a duplicate key, and the two call for
27
+ different recovery. */
28
+ export const ProblemTypes = {
29
+ /** A row was changed or deleted by someone else after this client read it. */
30
+ concurrencyConflict: "https://breeze.github.io/problems/concurrency-conflict",
31
+ /** The save was rejected by validation; see `entityErrors`. */
32
+ entityErrors: "https://breeze.github.io/problems/entity-errors",
33
+ /** An unhandled exception on the server. */
34
+ serverError: "https://breeze.github.io/problems/server-error",
35
+ };
36
+ /** Whether an error is an optimistic concurrency conflict - a row changed or deleted by someone
37
+ else after this client read it.
38
+
39
+ ```ts
40
+ try {
41
+ await em.saveChanges();
42
+ } catch (e) {
43
+ if (isConcurrencyError(e)) {
44
+ // re-read and let the user decide; retrying the same save would fail the same way
45
+ }
46
+ }
47
+ ```
48
+
49
+ This is exact rather than approximate: it is true only when the server said so with
50
+ {@link ProblemTypes.concurrencyConflict}, never inferred from the status code or the message. A
51
+ `409` from a duplicate key is not a concurrency conflict, and matching on message text breaks
52
+ when the ORM, database or server version changes.
53
+
54
+ A Breeze .NET server sends this for EF Core's `DbUpdateConcurrencyException` and NHibernate's
55
+ `StaleObjectStateException`. A server that does not send a `type` - any pre-3.0 Breeze server, and
56
+ most non-Breeze ones - returns false here, and there is nothing reliable to use instead.
57
+
58
+ When the conflict names the rows involved, they are on `entityErrors` with the entities attached:
59
+
60
+ ```ts
61
+ const stale = (e.entityErrors ?? [])
62
+ .filter(ee => ee.errorName === "ConcurrencyError")
63
+ .map(ee => ee.entity);
64
+ ```
65
+ @param error The rejection value from a Breeze call - typically a {@link SaveError}.
66
+ @returns true if the server identified this as a concurrency conflict. */
67
+ export function isConcurrencyError(error) {
68
+ return !!error && error.problemType === ProblemTypes.concurrencyConflict;
69
+ }
70
+ /**
71
+ Instances of the EntityManager contain and manage collections of entities, either retrieved from a backend datastore or created on the client.
72
+ */
73
+ export class EntityManager {
74
+ // events
75
+ /**
76
+ A {@link BreezeEvent} that fires whenever a change to any entity in this EntityManager occurs. __Read Only__
77
+
78
+ @eventArgs -
79
+ - entityAction - The {@link EntityAction} that occured.
80
+ - entity - The entity that changed. Undefined for {@link EntityAction.Clear}, which affects every entity in the manager.
81
+ - args - Additional information about this event. This will differ based on the entityAction.
82
+
83
+ ```ts
84
+ const em = new EntityManager({ serviceName: "breeze/NorthwindIBModel" });
85
+ em.entityChanged.subscribe(changeArgs => {
86
+ // This code will be executed any time any entity within the entityManager
87
+ // is added, modified, deleted or detached for any reason.
88
+ const action = changeArgs.entityAction;
89
+ const entity = changeArgs.entity;
90
+ // .. do something to this entity when it is changed.
91
+ });
92
+ ```
93
+ @event
94
+ */
95
+ entityChanged;
96
+ /**
97
+ An {@link BreezeEvent} that fires whenever validationErrors change for any entity in this EntityManager. __Read Only__
98
+ @eventArgs -
99
+ - entity - The entity on which the validation errors have been added or removed.
100
+ - added - An array containing any newly added {@link ValidationError}s
101
+ - removed - An array containing any newly removed {@link ValidationError}s. This is those errors that have been 'fixed'
102
+
103
+ ```ts
104
+ const em = new EntityManager({ serviceName: "breeze/NorthwindIBModel" });
105
+ em.validationErrorsChanged.subscribe(changeArgs => {
106
+ // This code will be executed any time any entity within the entityManager
107
+ // experiences a change to its validationErrors collection.
108
+ const entity = changeArgs.entity;
109
+ const errorsAdded = changeArgs.added;
110
+ const errorsCleared = changeArgs.removed;
111
+ // ... do something interesting with the entity.
112
+ });
113
+ ```
114
+ @event
115
+ */
116
+ validationErrorsChanged;
117
+ /**
118
+ A {@link BreezeEvent} that fires whenever an EntityManager transitions to or from having changes. __Read Only__
119
+ @eventArgs -
120
+ - entityManager - The EntityManager whose 'hasChanges' status has changed.
121
+ - hasChanges - Whether or not this EntityManager has changes.
122
+
123
+ ```ts
124
+ const em = new EntityManager({ serviceName: "breeze/NorthwindIBModel" });
125
+ em.hasChangesChanged.subscribe(args => {
126
+ const hasChanges = args.hasChanges;
127
+ const entityManager = args.entityManager;
128
+ });
129
+ ```
130
+ @event
131
+ */
132
+ hasChangesChanged;
133
+ /** @hidden @internal */
134
+ _pendingPubs; // TODO: refine later
135
+ /** @hidden @internal */
136
+ // Deferred to the end of a load: recomputing hasChanges scans the cache, so it is done once
137
+ // when the load finishes rather than per entity. See _notifyStateChange.
138
+ _hasChangesAction;
139
+ /** @hidden @internal */
140
+ _hasChanges;
141
+ /** @hidden @internal Keyed by qualified entityType name. */
142
+ _entityGroupMap;
143
+ /** @hidden @internal */
144
+ _unattachedChildrenMap;
145
+ /** @hidden @internal */
146
+ _inKeyFixup;
147
+ /** Functions a {@link DataServiceAdapter} uses to build the save request: `unwrapInstance` turns an
148
+ entity or complex object into a plain object with server property names, `unwrapOriginalValues`
149
+ does the same for its original values, and `unwrapChangedValues` for the current values of its
150
+ changed properties. For adapter authors; applications do not normally need it. */
151
+ helper = {
152
+ /** Turns an entity or complex object into a plain object keyed by server property names. */
153
+ unwrapInstance: unwrapInstance,
154
+ /** The same, for the original values of an entity's changed properties. */
155
+ unwrapOriginalValues: unwrapOriginalValues,
156
+ /** The same, for the current values of an entity's changed properties. */
157
+ unwrapChangedValues: unwrapChangedValues
158
+ };
159
+ /**
160
+ EntityManager constructor.
161
+
162
+ At its most basic an EntityManager can be constructed with just a service name
163
+ ```ts
164
+ const entityManager = new EntityManager("breeze/NorthwindIBModel");
165
+ ```
166
+
167
+ This is the same as calling it with the following configuration object
168
+ ```ts
169
+ const entityManager = new EntityManager({ serviceName: "breeze/NorthwindIBModel" });
170
+ ```
171
+
172
+ Usually however, configuration objects will contain more than just the 'serviceName';
173
+ ```ts
174
+ const metadataStore = new MetadataStore();
175
+ const entityManager = new EntityManager({
176
+ serviceName: "breeze/NorthwindIBModel",
177
+ metadataStore: metadataStore
178
+ });
179
+ ```
180
+
181
+ or
182
+ ```ts
183
+ const queryOptions = new QueryOptions({
184
+ mergeStrategy: MergeStrategy.OverwriteChanges,
185
+ fetchStrategy: FetchStrategy.FromServer
186
+ });
187
+ const validationOptions = new ValidationOptions({
188
+ validateOnAttach: true,
189
+ validateOnSave: true,
190
+ validateOnQuery: false
191
+ });
192
+ const entityManager = new EntityManager({
193
+ serviceName: "breeze/NorthwindIBModel",
194
+ queryOptions: queryOptions,
195
+ validationOptions: validationOptions
196
+ });
197
+ ```
198
+ @param emConfig - Configuration settings or a service name.
199
+ */
200
+ constructor(emConfig) {
201
+ if (arguments.length > 1) {
202
+ throw new Error("The EntityManager ctor has a single optional argument that is either a 'serviceName' or a configuration object.");
203
+ }
204
+ let config;
205
+ if (arguments.length === 0) {
206
+ config = { serviceName: "" };
207
+ }
208
+ else if (typeof emConfig === 'string') {
209
+ config = { serviceName: emConfig };
210
+ }
211
+ else {
212
+ config = emConfig || {};
213
+ }
214
+ EntityManager._updateWithConfig(this, config, true);
215
+ // Given a real value here rather than left undefined, because `core.using` restores a
216
+ // property it found undefined by *deleting* it. These two are scoped with `core.using` on
217
+ // every createEntity, query merge and rejectChanges, so the manager was having a property
218
+ // added and removed several times per entity - which is what puts an object into V8's
219
+ // dictionary-properties mode, permanently, for every property it has. Reads of
220
+ // `metadataStore`, `queryOptions` and the rest then cost about 20x what they should.
221
+ this.isLoading = false;
222
+ this.isRejectingChanges = false;
223
+ this.entityChanged = new BreezeEvent("entityChanged", this);
224
+ this.validationErrorsChanged = new BreezeEvent("validationErrorsChanged", this);
225
+ this.hasChangesChanged = new BreezeEvent("hasChangesChanged", this);
226
+ this.clear();
227
+ }
228
+ /**
229
+ General purpose property set method. Any of the properties in the {@link EntityManagerConfig}
230
+ may be set.
231
+ ```ts
232
+ // assume em1 is a previously created EntityManager
233
+ // where we want to change some of its settings.
234
+ em1.setProperties( {
235
+ serviceName: "breeze/foo"
236
+ });
237
+ ```
238
+ @param config - An object containing the selected properties and values to set.
239
+ */
240
+ setProperties(config) {
241
+ EntityManager._updateWithConfig(this, config, false);
242
+ }
243
+ /** @hidden @internal */
244
+ static _updateWithConfig(em, config, isCtor) {
245
+ let defaultQueryOptions = isCtor ? QueryOptions.defaultInstance : em.queryOptions;
246
+ let defaultSaveOptions = isCtor ? SaveOptions.defaultInstance : em.saveOptions;
247
+ let defaultValidationOptions = isCtor ? ValidationOptions.defaultInstance : em.validationOptions;
248
+ let configParam = assertConfig(config)
249
+ .whereParam("serviceName").isOptional().isString()
250
+ .whereParam("dataService").isOptional().isInstanceOf(DataService)
251
+ .whereParam("queryOptions").isInstanceOf(QueryOptions).isOptional().withDefault(defaultQueryOptions)
252
+ .whereParam("saveOptions").isInstanceOf(SaveOptions).isOptional().withDefault(defaultSaveOptions)
253
+ .whereParam("validationOptions").isInstanceOf(ValidationOptions).isOptional().withDefault(defaultValidationOptions)
254
+ .whereParam("keyGeneratorCtor").isFunction().isOptional();
255
+ if (isCtor) {
256
+ configParam = configParam
257
+ .whereParam("metadataStore").isInstanceOf(MetadataStore).isOptional().withDefault(new MetadataStore());
258
+ }
259
+ configParam.applyAll(em);
260
+ // insure that entityManager's options versions are completely populated
261
+ core.updateWithDefaults(em.queryOptions, defaultQueryOptions);
262
+ core.updateWithDefaults(em.saveOptions, defaultSaveOptions);
263
+ core.updateWithDefaults(em.validationOptions, defaultValidationOptions);
264
+ if (config.serviceName) {
265
+ // Use the store's DataService for this service when it has one (added with addDataService, by fetchMetadata or
266
+ // from imported metadata), so that its settings - hasServerMetadata among them - apply to this manager.
267
+ em.dataService = em.metadataStore.getDataService(em.serviceName) || new DataService({
268
+ serviceName: em.serviceName
269
+ });
270
+ }
271
+ em.serviceName = em.dataService && em.dataService.serviceName;
272
+ em.keyGeneratorCtor = em.keyGeneratorCtor || KeyGenerator;
273
+ if (isCtor || config.keyGeneratorCtor) {
274
+ em.keyGenerator = new em.keyGeneratorCtor();
275
+ }
276
+ }
277
+ /**
278
+ Creates a new entity of a specified type and optionally initializes it. By default the new entity is created with an EntityState of Added
279
+ but you can also optionally specify an EntityState. An EntityState of 'Detached' will insure that the entity is created but not yet added
280
+ to the EntityManager.
281
+ ```ts
282
+ // assume em1 is an EntityManager containing a number of preexisting entities.
283
+ // create and add an entity. Passing the registered class types the result:
284
+ const emp1 = em1.createEntity(Employee); // Employee
285
+ // create and add an initialized entity;
286
+ const emp2 = em1.createEntity(Employee, { lastName: "Smith", firstName: "John" });
287
+ // create and attach (not add) an initialized entity
288
+ const emp3 = em1.createEntity(Employee, { employeeID: 435, lastName: "Smith", firstName: "John" }, EntityState.Unchanged);
289
+ // create but don't attach an entity;
290
+ const emp4 = em1.createEntity(Employee, { employeeID: 435, lastName: "Smith", firstName: "John" }, EntityState.Detached);
291
+ // with the constructor, initialValues is checked: a property Employee does not declare,
292
+ // such as a misspelling, is a compile error rather than a value silently ignored
293
+ em1.createEntity(Employee, { lastNmae: "Smith" }); // error
294
+
295
+ // the type name and the EntityType both still work, and return Entity:
296
+ const emp5 = em1.createEntity("Employee", { lastName: "Smith" });
297
+ ```
298
+
299
+ The constructor overload needs the class to have been registered with
300
+ {@link MetadataStore.registerEntityTypeCtor}; that is what tells Breeze which type it stands
301
+ for. An unregistered class throws. See the Typed entities guide.
302
+ @param entityCtor - A constructor registered for the EntityType to create.
303
+ @param typeName - The name of the EntityType for which an instance should be created.
304
+ @param entityType - The EntityType of the type for which an instance should be created.
305
+ @param initialValues - (default=null) Configuration object of the properties to set immediately after creation.
306
+ With the constructor overload it is typed as {@link InitialValues}, so a property the class does
307
+ not declare is a compile error.
308
+ @param entityState - (default = {@link EntityState.Added}) The EntityState of the entity after being created and added to this EntityManager.
309
+ @param mergeStrategy - (default = {@link MergeStrategy.Disallowed}) - How to handle conflicts if an entity with the same key already exists within this EntityManager.
310
+ @returns {Entity} A new Entity of the specified type.
311
+ */
312
+ createEntity(entityType, initialValues, entityState, mergeStrategy) {
313
+ // A constructor stands for its type *name*, which is then looked up in this manager's own
314
+ // MetadataStore. Using the EntityType hanging off the constructor's prototype would tie the
315
+ // call to whichever store the class was registered with, and a manager with an equivalent
316
+ // store - a copy, or one built from the same metadata - would fail deep inside attachEntity
317
+ // with a store-mismatch error.
318
+ if (typeof entityType === "function") {
319
+ entityType = entityTypeForCtor(entityType).name;
320
+ }
321
+ assertParam(entityType, "entityType").isString().or().isInstanceOf(EntityType).check();
322
+ assertParam(entityState, "entityState").isEnumOf(EntityState).isOptional().check();
323
+ assertParam(mergeStrategy, "mergeStrategy").isEnumOf(MergeStrategy).isOptional().check();
324
+ let et = (typeof entityType === "string") ? this.metadataStore._getStructuralType(entityType) : entityType;
325
+ entityState = entityState || EntityState.Added;
326
+ let entity = {};
327
+ core.using(this, "isLoading", true, function () {
328
+ entity = et.createEntity(initialValues);
329
+ });
330
+ if (entityState !== EntityState.Detached) {
331
+ // The two enums were checked above; no need for attachEntity to check them again.
332
+ entity = this._attachEntity(entity, entityState, mergeStrategy || MergeStrategy.Disallowed);
333
+ }
334
+ return entity;
335
+ }
336
+ /**
337
+ Creates a new EntityManager and imports a previously exported result into it.
338
+ ```ts
339
+ // assume em1 is an EntityManager containing a number of preexisting entities.
340
+ const bundle = em1.exportEntities() as string;
341
+ // can be stored via the web storage api
342
+ window.localStorage.setItem("myEntityManager", bundle);
343
+ // assume the code below occurs in a different session.
344
+ const bundleFromStorage = window.localStorage.getItem("myEntityManager");
345
+ // and imported
346
+ const em2 = EntityManager.importEntities(bundleFromStorage);
347
+ // em2 will now have a complete copy of what was in em1
348
+ ```
349
+ @param exportedString - The result of a previous 'exportEntities' call as a string
350
+ @param exportedData - The result of a previous 'exportEntities' call as an Object.
351
+ @param config - A configuration object.
352
+ @param config.mergeStrategy - A {@link MergeStrategy} to use when
353
+ merging into an existing EntityManager.
354
+ @param config.metadataVersionFn - A function called with `{ metadataVersion, metadataStoreName }` from the
355
+ import bundle, for version checking; throw from it to reject the import. Only called when the bundle was
356
+ exported without its metadata.
357
+ @returns A new EntityManager. Note that the return value of this method call is different from that
358
+ provided by the same named method on an EntityManager instance. Use that method if you need additional information
359
+ regarding the imported entities.
360
+ */
361
+ static importEntities(exported, config) {
362
+ let em = new EntityManager();
363
+ em.importEntities(exported, config);
364
+ return em;
365
+ }
366
+ // instance methods
367
+ /**
368
+ Calls {@link EntityAspect.acceptChanges} on every changed entity in this EntityManager.
369
+ */
370
+ acceptChanges() {
371
+ this.getChanges().map(function (entity) {
372
+ return entity.entityAspect._checkOperation("acceptChanges");
373
+ }).forEach(function (aspect) {
374
+ aspect.acceptChanges();
375
+ });
376
+ }
377
+ /**
378
+ Exports selected entities, all entities of selected types, or an entire EntityManager cache.
379
+
380
+ This method takes a snapshot of an EntityManager that can be stored offline or held in memory.
381
+ Use the {@link EntityManager.importEntities} method to restore or merge the snapshot
382
+ into another EntityManager at some later time.
383
+ ```ts
384
+ // let em1 be an EntityManager containing a number of existing entities.
385
+ // export every entity in em1.
386
+ const bundle = em1.exportEntities() as string;
387
+ // save to the browser's local storage
388
+ window.localStorage.setItem("myEntityManager", bundle);
389
+ // later retrieve the export
390
+ const bundleFromStorage = window.localStorage.getItem("myEntityManager");
391
+ // import the retrieved export bundle into another manager
392
+ const em2 = em1.createEmptyCopy();
393
+ em2.importEntities(bundleFromStorage);
394
+ // em2 now has a complete, faithful copy of the entities that were in em1
395
+ ```
396
+
397
+ You can also control exactly which entities are exported.
398
+ ```ts
399
+ // get em1's unsaved changes (an array) and export them.
400
+ const changes = em1.getChanges();
401
+ const bundle = em1.exportEntities(changes);
402
+ // merge these entities into em2 which may contains some of the same entities.
403
+ // do NOT overwrite the entities in em2 if they themselves have unsaved changes.
404
+ em2.importEntities(bundle, { mergeStrategy: MergeStrategy.PreserveChanges });
405
+ ```
406
+
407
+ Metadata are included in an export by default. You may want to exclude the metadata
408
+ especially if you're exporting just a few entities for local storage.
409
+ ```ts
410
+ const bundle = em1.exportEntities(arrayOfSelectedEntities, { includeMetadata: false }) as string;
411
+ window.localStorage.setItem("goodStuff", bundle);
412
+ ```
413
+
414
+ You may still express this option as a boolean value although this older syntax is deprecated.
415
+ ```ts
416
+ // Exclude the metadata (deprecated syntax)
417
+ const bundle = em1.exportEntities(arrayOfSelectedEntities, false);
418
+ ```
419
+
420
+ You can export all entities of one or more specified EntityTypes, by name.
421
+ ```ts
422
+ // Export all Customer and Employee entities (and also exclude metadata)
423
+ const bundle = em1.exportEntities(['Customer', 'Employee'], { includeMetadata: false });
424
+ ```
425
+
426
+ All of the above examples return an export bundle as a string which is the default format.
427
+ You can export the bundle as JSON if you prefer by setting the `asString` option to false.
428
+ ```ts
429
+ // Export all Customer and Employee entities as JSON and exclude the metadata
430
+ const bundle = em1.exportEntities(['Customer', 'Employee'],
431
+ { asString: false, includeMetadata: false });
432
+ // store JSON bundle somewhere ... perhaps indexDb ... and later import as we do here.
433
+ em2.importEntities(bundle);
434
+ ```
435
+ @param entities - The entities to export, or the types of the entities to export - as registered
436
+ classes, {@link EntityType}s or type names. All entities are exported if this parameter is
437
+ omitted or null.
438
+ @param exportConfig - Export configuration options or a boolean
439
+ - asString - (boolean) - If true (default), return export bundle as a string.
440
+ - includeMetadata - (boolean) - If true (default), include metadata in the export bundle.
441
+ @returns The export bundle either serialized as a string (default) or as a JSON object.
442
+ The bundle contains the metadata (unless excluded) and the entity data grouped by type.
443
+ The entity data include property values, change-state, and temporary key mappings (if any).
444
+
445
+ The export bundle internals are deliberately undocumented. This Breeze-internal representation of entity data is
446
+ suitable for export, storage, and import. The schema and contents of the bundle may change in future versions of Breeze.
447
+ Manipulate it at your own risk with appropriate caution.
448
+ */
449
+ exportEntities(entities, exportConfig) {
450
+ // A registered class stands for its type name, as it does for getEntities.
451
+ if (Array.isArray(entities) && typeof entities[0] === "function") {
452
+ entities = entities.map(ctor => entityTypeForCtor(ctor).name);
453
+ }
454
+ assertParam(entities, "entities").isArray().isEntity()
455
+ .or().isNonEmptyArray().isInstanceOf(EntityType)
456
+ .or().isNonEmptyArray().isString()
457
+ .or().isOptional().check();
458
+ // assertParam(exportConfig, "exportConfig").isObject()
459
+ // .or().isBoolean()
460
+ // .or().isOptional().check();
461
+ if (exportConfig == null) {
462
+ exportConfig = { includeMetadata: true, asString: true };
463
+ }
464
+ else if (typeof exportConfig === 'boolean') { // deprecated
465
+ exportConfig = { includeMetadata: exportConfig, asString: true };
466
+ }
467
+ assertConfig(exportConfig)
468
+ .whereParam("asString").isBoolean().isOptional().withDefault(true)
469
+ .whereParam("includeMetadata").isBoolean().isOptional().withDefault(true)
470
+ .applyAll(exportConfig);
471
+ let exportBundle = exportEntityGroups(this, entities); // classes were resolved to names above
472
+ let json = core.extend({}, exportBundle, ["tempKeys", "entityGroupMap"]);
473
+ if (exportConfig.includeMetadata) {
474
+ json = core.extend(json, this, ["dataService", "saveOptions", "queryOptions", "validationOptions"]);
475
+ json.metadataStore = this.metadataStore.exportMetadata();
476
+ }
477
+ else {
478
+ json.metadataVersion = MetadataStore.metadataVersion;
479
+ json.metadataStoreName = this.metadataStore.name;
480
+ }
481
+ let result = exportConfig.asString ? JSON.stringify(json, null, config.stringifyPad) : json;
482
+ return result;
483
+ }
484
+ /**
485
+ Imports a previously exported result into this EntityManager.
486
+
487
+ This method can be used to make a complete copy of any previously created entityManager, even if created
488
+ in a previous session and stored in localStorage. The static version of this method performs a
489
+ very similar process.
490
+ ```ts
491
+ // assume em1 is an EntityManager containing a number of existing entities.
492
+ const bundle = em1.exportEntities();
493
+ // bundle can be stored in window.localStorage or just held in memory.
494
+ const em2 = new EntityManager({
495
+ serviceName: em1.serviceName,
496
+ metadataStore: em1.metadataStore
497
+ });
498
+ em2.importEntities(bundle);
499
+ // em2 will now have a complete copy of what was in em1
500
+ ```
501
+
502
+ It can also be used to merge the contents of a previously created EntityManager with an
503
+ existing EntityManager with control over how the two are merged.
504
+ ```ts
505
+ const bundle = em1.exportEntities();
506
+ // assume em2 is another entityManager containing some of the same entities possibly with modifications.
507
+ em2.importEntities(bundle, { mergeStrategy: MergeStrategy.PreserveChanges });
508
+ // em2 will now contain all of the entities from both em1 and em2. Any em2 entities with previously
509
+ // made modifications will not have been touched, but all other entities from em1 will have been imported.
510
+ ```
511
+ @param exportedString - The result of a previous 'export' call.
512
+ @param importConfig - A configuration object.
513
+ @param importConfig.mergeStrategy - A {@link MergeStrategy} to use when
514
+ merging into an existing EntityManager.
515
+ @param importConfig.metadataVersionFn - A function called with `{ metadataVersion, metadataStoreName }` from the
516
+ import bundle, for version checking; throw from it to reject the import. Only called when the bundle was
517
+ exported without its metadata.
518
+ @returns result
519
+ - result.entities {Array of Entities} The entities that were imported.
520
+ - result.tempKeyMapping {Object} For each temporary key in the bundle, the temporary {@link EntityKey} the entity has in this manager - see {@link ITempKeyMap}.
521
+ */
522
+ importEntities(exported, importConfig) {
523
+ importConfig = importConfig || {};
524
+ assertConfig(importConfig)
525
+ .whereParam("mergeStrategy").isEnumOf(MergeStrategy).isOptional().withDefault(this.queryOptions.mergeStrategy)
526
+ .whereParam("metadataVersionFn").isFunction().isOptional()
527
+ .whereParam("mergeAdds").isBoolean().isOptional()
528
+ .applyAll(importConfig);
529
+ let json = (typeof exported === "string") ? JSON.parse(exported) : exported;
530
+ if (json.metadataStore) {
531
+ this.metadataStore.importMetadata(json.metadataStore);
532
+ // the || clause is for backwards compat with an earlier serialization format.
533
+ this.dataService = (json.dataService && DataService.fromJSON(json.dataService)) || new DataService({ serviceName: json.serviceName });
534
+ this.saveOptions = new SaveOptions(json.saveOptions);
535
+ this.queryOptions = QueryOptions.fromJSON(json.queryOptions);
536
+ this.validationOptions = new ValidationOptions(json.validationOptions);
537
+ }
538
+ else {
539
+ importConfig.metadataVersionFn && importConfig.metadataVersionFn({
540
+ metadataVersion: json.metadataVersion,
541
+ metadataStoreName: json.metadataStoreName
542
+ });
543
+ }
544
+ let tempKeyMap = {};
545
+ json.tempKeys.forEach((k) => {
546
+ let oldKey = EntityKey.fromJSON(k, this.metadataStore);
547
+ // try to use oldKey if not already used in this keyGenerator.
548
+ tempKeyMap[oldKey.toString()] = new EntityKey(oldKey.entityType, this.keyGenerator.generateTempKeyValue(oldKey.entityType, oldKey.values[0]));
549
+ });
550
+ let entitiesToLink = [];
551
+ let impConfig = importConfig;
552
+ impConfig.tempKeyMap = tempKeyMap;
553
+ core.wrapExecution(() => {
554
+ this._pendingPubs = [];
555
+ }, (state) => {
556
+ this._pendingPubs.forEach((fn) => fn());
557
+ this._pendingPubs = undefined;
558
+ this._hasChangesAction && this._hasChangesAction();
559
+ }, () => {
560
+ core.objectForEach(json.entityGroupMap, (entityTypeName, jsonGroup) => {
561
+ let entityType = this.metadataStore._getStructuralType(entityTypeName, false);
562
+ let targetEntityGroup = findOrCreateEntityGroup(this, entityType);
563
+ let entities = importEntityGroup(targetEntityGroup, jsonGroup, impConfig);
564
+ if (entities && entities.length) {
565
+ entitiesToLink = entitiesToLink.concat(entities);
566
+ }
567
+ });
568
+ entitiesToLink.forEach((entity) => {
569
+ if (!entity.entityAspect.entityState.isDeleted()) {
570
+ this._linkRelatedEntities(entity);
571
+ }
572
+ });
573
+ });
574
+ return {
575
+ entities: entitiesToLink,
576
+ tempKeyMapping: tempKeyMap
577
+ };
578
+ }
579
+ /**
580
+ Clears this EntityManager's cache but keeps all other settings. Note that this
581
+ method is not as fast as creating a new EntityManager via 'new EntityManager'.
582
+ This is because clear actually detaches all of the entities from the EntityManager.
583
+ ```ts
584
+ // assume em1 is an EntityManager containing a number of existing entities.
585
+ em1.clear();
586
+ // em1 is will now contain no entities, but all other setting will be maintained.
587
+ ```
588
+ */
589
+ clear() {
590
+ // The constructor calls clear() before _entityGroupMap is assigned, so this runs
591
+ // once with it undefined. core.objectMap used to absorb that; Map.values() does not.
592
+ Array.from(this._entityGroupMap?.values() ?? [])
593
+ .map(entityGroup => entityGroup._checkOperation('clear'))
594
+ .forEach(entityGroup => entityGroup._clear());
595
+ this._entityGroupMap = new Map();
596
+ this._unattachedChildrenMap = new UnattachedChildrenMap();
597
+ this.keyGenerator = new this.keyGeneratorCtor();
598
+ this.entityChanged.publish({ entityAction: EntityAction.Clear });
599
+ this._setHasChanges(false);
600
+ }
601
+ /**
602
+ Creates an empty copy of this EntityManager but with the same DataService, MetadataStore, QueryOptions, SaveOptions, ValidationOptions, etc.
603
+ ```ts
604
+ // assume em1 is an EntityManager containing a number of existing entities.
605
+ const em2 = em1.createEmptyCopy();
606
+ // em2 is a new EntityManager with all of em1's settings
607
+ // but no entities.
608
+ ```
609
+ @returns A new EntityManager.
610
+ */
611
+ createEmptyCopy() {
612
+ let copy = new EntityManager(core.extend({}, this, ["dataService", "metadataStore", "queryOptions", "saveOptions", "validationOptions", "keyGeneratorCtor"]));
613
+ return copy;
614
+ }
615
+ /**
616
+ Attaches an entity to this EntityManager with an {@link EntityState} of 'Added'.
617
+ ```ts
618
+ // assume em1 is an EntityManager containing a number of existing entities.
619
+ const cust1 = em1.createEntity(Customer, { companyName: "Acme" }, EntityState.Detached);
620
+ em1.addEntity(cust1); // returns cust1, a Customer
621
+ ```
622
+
623
+ Note that this is the same as using 'attachEntity' with an {@link EntityState} of 'Added'.
624
+
625
+ ```ts
626
+ // assume em1 is an EntityManager containing a number of existing entities.
627
+ const cust1 = em1.createEntity(Customer, { companyName: "Acme" }, EntityState.Detached);
628
+ em1.attachEntity(cust1, EntityState.Added);
629
+ ```
630
+ @param entity - The entity to add.
631
+ @returns The added entity.
632
+ */
633
+ addEntity(entity) {
634
+ return this.attachEntity(entity, EntityState.Added);
635
+ }
636
+ /**
637
+ Attaches an entity to this EntityManager with a specified {@link EntityState}.
638
+ ```ts
639
+ // assume em1 is an EntityManager containing a number of existing entities.
640
+ const cust1 = em1.createEntity(Customer, { companyName: "Acme" }, EntityState.Detached);
641
+ em1.attachEntity(cust1, EntityState.Added); // returns cust1, a Customer
642
+ ```
643
+ @param entity - The entity to add.
644
+ @param entityState - (default=EntityState.Unchanged) The EntityState of the newly attached entity. If omitted this defaults to EntityState.Unchanged.
645
+ @param mergeStrategy - (default = MergeStrategy.Disallowed) How the specified entity should be merged into the EntityManager if this EntityManager already contains an entity with the same key.
646
+ @returns The attached entity.
647
+ */
648
+ attachEntity(entity, entityState, mergeStrategy) {
649
+ assertParam(entity, "entity").isRequired().check();
650
+ // Before the enum checks, so that an unregistered entity is still reported ahead of a bad
651
+ // entityState, as it was when this was one method. _attachEntity repeats it for its internal
652
+ // callers and it early-exits on anything that has an entityType, which is everything here.
653
+ this.metadataStore._checkEntityType(entity);
654
+ let esSymbol = assertParam(entityState, "entityState").isEnumOf(EntityState).isOptional().check(EntityState.Unchanged);
655
+ let msSymbol = assertParam(mergeStrategy, "mergeStrategy").isEnumOf(MergeStrategy).isOptional().check(MergeStrategy.Disallowed);
656
+ return this._attachEntity(entity, esSymbol, msSymbol);
657
+ }
658
+ /**
659
+ * What `attachEntity` does once its arguments have been checked.
660
+ *
661
+ * `createEntity` checks the same `entityState` and `mergeStrategy` a moment earlier and then
662
+ * called the public method, so every created entity paid for the three `assertParam` chains
663
+ * twice. Callers inside Breeze already hold a real entity and resolved enum values, so they
664
+ * come in here instead. Everything the *entity* is checked for - a known type, a matching
665
+ * metadata store, not already attached elsewhere - still happens below, because those depend
666
+ * on this manager rather than on the caller getting its arguments right.
667
+ *
668
+ * @hidden @internal
669
+ */
670
+ _attachEntity(entity, esSymbol, msSymbol) {
671
+ this.metadataStore._checkEntityType(entity);
672
+ if (entity.entityType.metadataStore !== this.metadataStore) {
673
+ throw new Error("Cannot attach this entity because the EntityType (" + entity.entityType.name +
674
+ ") and MetadataStore associated with this entity does not match this EntityManager's MetadataStore.");
675
+ }
676
+ let aspect = entity.entityAspect;
677
+ if (aspect) {
678
+ // to avoid reattaching an entity in progress
679
+ if (aspect._inProcessEntity)
680
+ return aspect._inProcessEntity;
681
+ }
682
+ else {
683
+ // this occur's when attaching an entity created via new instead of via createEntity.
684
+ aspect = new EntityAspect(entity);
685
+ }
686
+ let manager = aspect.entityManager;
687
+ if (manager) {
688
+ if (manager === this) {
689
+ return entity;
690
+ }
691
+ else {
692
+ throw new Error("This entity already belongs to another EntityManager");
693
+ }
694
+ }
695
+ let attachedEntity = {};
696
+ core.using(this, "isLoading", true, () => {
697
+ if (esSymbol.isAdded()) {
698
+ checkEntityKey(this, entity);
699
+ }
700
+ // attachedEntity === entity EXCEPT in the case of a merge.
701
+ attachedEntity = this._attachEntityCore(entity, esSymbol, msSymbol);
702
+ aspect._inProcessEntity = attachedEntity;
703
+ try {
704
+ // entity ( not attachedEntity) is deliberate here.
705
+ attachRelatedEntities(this, entity, esSymbol, msSymbol);
706
+ }
707
+ finally {
708
+ // insure that _inProcessEntity is cleared.
709
+ aspect._inProcessEntity = undefined;
710
+ }
711
+ });
712
+ if (this.validationOptions.validateOnAttach) {
713
+ attachedEntity.entityAspect.validateEntity();
714
+ }
715
+ if (!esSymbol.isUnchanged()) {
716
+ this._notifyStateChange(attachedEntity, true);
717
+ }
718
+ this.entityChanged.publish({ entityAction: EntityAction.Attach, entity: attachedEntity });
719
+ return attachedEntity;
720
+ }
721
+ /**
722
+ Detaches an entity from this EntityManager.
723
+ ```ts
724
+ // assume em1 is an EntityManager containing a number of existing entities.
725
+ // assume cust1 is a customer Entity previously attached to em1
726
+ em1.detachEntity(cust1);
727
+ // em1 will now no longer contain cust1 and cust1 will have an
728
+ // entityAspect.entityState of EntityState.Detached
729
+ ```
730
+ @param entity - The entity to detach.
731
+ @returns Whether the entity could be detached. This will return false if the entity is already detached or was never attached.
732
+ */
733
+ detachEntity(entity) {
734
+ assertParam(entity, "entity").isEntity().check();
735
+ let aspect = entity.entityAspect;
736
+ if (!aspect) {
737
+ // no aspect means in couldn't appear in any group
738
+ return false;
739
+ }
740
+ if (aspect.entityManager !== this) {
741
+ throw new Error("This entity does not belong to this EntityManager.");
742
+ }
743
+ return aspect.setDetached();
744
+ }
745
+ /**
746
+ Fetches the metadata associated with the EntityManager's current 'serviceName'. This call
747
+ occurs internally before the first query to any service if the metadata hasn't already been
748
+ loaded. __Async__
749
+
750
+ Usually you will not actually process the results of a fetchMetadata call directly, but will instead
751
+ ask for the metadata from the EntityManager after the fetchMetadata call returns.
752
+ ```ts
753
+ const em1 = new EntityManager("breeze/NorthwindIBModel");
754
+ await em1.fetchMetadata();
755
+ const metadataStore = em1.metadataStore;
756
+ // do something with the metadata
757
+ ```
758
+
759
+ @param callback - Deprecated. Function called on success.
760
+ @param errorCallback - Deprecated. Function called on failure.
761
+ @returns {Promise}
762
+ - schema {Object} The raw Schema object from metadata provider - Because this schema will differ depending on the metadata provider
763
+ it is usually better to access metadata via the 'metadataStore' property of the EntityManager instead of using this 'raw' data.
764
+ */
765
+ fetchMetadata(dataService, callback, errorCallback) {
766
+ if (typeof (dataService) === "function") {
767
+ // legacy support for when dataService was not an arg. i.e. first arg was callback
768
+ errorCallback = callback;
769
+ callback = dataService;
770
+ dataService = undefined;
771
+ }
772
+ else {
773
+ assertParam(dataService, "dataService").isInstanceOf(DataService).isOptional().check();
774
+ assertParam(callback, "callback").isFunction().isOptional().check();
775
+ assertParam(errorCallback, "errorCallback").isFunction().isOptional().check();
776
+ }
777
+ let promise = this.metadataStore.fetchMetadata(dataService || this.dataService);
778
+ return promiseWithCallbacks(promise, callback, errorCallback);
779
+ }
780
+ /**
781
+ Executes the specified query. __Async__
782
+
783
+ ```ts
784
+ const em = new EntityManager(serviceName);
785
+ const query = EntityQuery.from(Order);
786
+ const data = await em.executeQuery(query);
787
+ const orders = data.results; // Order[], because the query was built from the class
788
+ ```
789
+
790
+ The `callback` and `errorCallback` arguments are deprecated. They still work, but the
791
+ promise is the supported form and the callbacks will be removed in a future major version.
792
+
793
+ This method is the same as calling the {@link EntityQuery} 'execute' method.
794
+ ```ts
795
+ const em = new EntityManager(serviceName);
796
+ const data = await EntityQuery.from(Order).using(em).execute();
797
+ const orders = data.results; // Order[]
798
+ ```
799
+ @param query - The {@link EntityQuery} or query string to execute.
800
+ @param callback - Deprecated. Function called on success.
801
+ @param errorCallback - Deprecated. Function called on failure.
802
+ @returns Promise of
803
+ - results - An array of entities
804
+ - retrievedEntities - A array of all of the entities returned by the query. Differs from results (above) when .expand() is used.
805
+ - query - The original {@link EntityQuery} or query string
806
+ - entityManager - The EntityManager.
807
+ - httpResponse - The {@link HttpResponse} returned from the server.
808
+ - inlineCount - Only available if 'inlineCount(true)' was applied to the query. Returns the count of
809
+ items that would have been returned by the query before applying any skip or take operators, but after any filter/where predicates
810
+ would have been applied.
811
+ */
812
+ executeQuery(query, callback, errorCallback) {
813
+ assertParam(query, "query").isInstanceOf(EntityQuery).or().isString().check();
814
+ assertParam(callback, "callback").isFunction().isOptional().check();
815
+ assertParam(errorCallback, "errorCallback").isFunction().isOptional().check();
816
+ let promise;
817
+ // 'resolve' methods create a new typed object with all of its properties fully resolved against a list of sources.
818
+ // Thought about creating a 'normalized' query with these 'resolved' objects
819
+ // but decided not to because the 'query' may not be an EntityQuery (it can be a string) and hence might not have a queryOptions or dataServices property on it.
820
+ let queryOptions = QueryOptions.resolve([query.queryOptions, this.queryOptions, QueryOptions.defaultInstance]);
821
+ let dataService = DataService.resolve([query.dataService, this.dataService]);
822
+ if ((!dataService.hasServerMetadata) || this.metadataStore.hasMetadataFor(dataService.serviceName)) {
823
+ promise = executeQueryCore(this, query, queryOptions, dataService);
824
+ }
825
+ else {
826
+ promise = this.fetchMetadata(dataService).then(() => {
827
+ return executeQueryCore(this, query, queryOptions, dataService);
828
+ });
829
+ }
830
+ return promiseWithCallbacks(promise, callback, errorCallback);
831
+ }
832
+ /**
833
+ Executes the specified query against this EntityManager's local cache.
834
+
835
+ Because this method is executed immediately there is no need for a promise or a callback
836
+ ```ts
837
+ const em = new EntityManager(serviceName);
838
+ const query = EntityQuery.from(Order);
839
+ const orders = em.executeQueryLocally(query); // Order[]
840
+ ```
841
+
842
+ Note that this can also be accomplished using the 'executeQuery' method with
843
+ a FetchStrategy of FromLocalCache and making use of the Promise or callback
844
+ ```ts
845
+ const em = new EntityManager(serviceName);
846
+ const query = EntityQuery.from(Order).using(FetchStrategy.FromLocalCache);
847
+ const data = await em.executeQuery(query);
848
+ const orders = data.results; // Order[]
849
+ ```
850
+ @param query - The {@link EntityQuery} to execute.
851
+ @returns {Array of Entity} Array of entities from cache that satisfy the query
852
+ */
853
+ executeQueryLocally(query) {
854
+ return executeQueryLocallyCore(this, query).results;
855
+ }
856
+ /**
857
+ Saves either a list of specified entities or all changed entities within this EntityManager. If there are no changes to any of the entities
858
+ specified then there will be no server side call made but a valid 'empty' saveResult will still be returned. __Async__
859
+
860
+ Often we will be saving all of the entities within an EntityManager that are either added, modified or deleted
861
+ and we will let the 'saveChanges' call determine which entities these are.
862
+ ```ts
863
+ // assume em1 is an EntityManager containing a number of preexisting entities.
864
+ // This could include added, modified and deleted entities.
865
+ // A failed save rejects, so the await throws.
866
+ const saveResult = await em1.saveChanges();
867
+ const savedEntities = saveResult.entities;
868
+ const keyMappings = saveResult.keyMappings;
869
+ ```
870
+
871
+ But we can also control exactly which entities to save and can specify specific SaveOptions
872
+
873
+ ```ts
874
+ // save only the changed customers
875
+ const saveOptions = new SaveOptions({ allowConcurrentSaves: true });
876
+ const saveResult = await em1.saveChanges(em1.getChanges(Customer), saveOptions);
877
+ ```
878
+
879
+ The `callback` and `errorCallback` arguments are deprecated. They still work, but the
880
+ promise is the supported form and the callbacks will be removed in a future major version.
881
+
882
+ @param entities - The list of entities to save.
883
+ Every entity in that list will be sent to the server, whether changed or unchanged,
884
+ as long as it is attached to this EntityManager.
885
+ If this parameter is omitted, null or empty (the usual case),
886
+ every entity with pending changes in this EntityManager will be saved.
887
+ @param saveOptions - {@link SaveOptions} for the save - will default to
888
+ {@link EntityManager.saveOptions} if null.
889
+ @param callback - Deprecated. Function called on success.
890
+ @param errorCallback - Deprecated. Function called on failure.
891
+ @returns {Promise} Promise
892
+ */
893
+ saveChanges(entities, saveOptions, callback, errorCallback) {
894
+ assertParam(entities, "entities").isOptional().isArray().isEntity().check();
895
+ assertParam(saveOptions, "saveOptions").isInstanceOf(SaveOptions).isOptional().check();
896
+ assertParam(callback, "callback").isFunction().isOptional().check();
897
+ assertParam(errorCallback, "errorCallback").isFunction().isOptional().check();
898
+ saveOptions = saveOptions || this.saveOptions || SaveOptions.defaultInstance;
899
+ let entitiesToSave = getEntitiesToSave(this, entities ? entities : undefined);
900
+ if (entitiesToSave.length === 0) {
901
+ let result = { entities: [], keyMappings: [] };
902
+ if (callback)
903
+ callback(result);
904
+ return Promise.resolve(result);
905
+ }
906
+ if (!saveOptions.allowConcurrentSaves) {
907
+ let anyPendingSaves = entitiesToSave.some(function (entity) {
908
+ return entity.entityAspect.isBeingSaved;
909
+ });
910
+ if (anyPendingSaves) {
911
+ let err = new Error("Concurrent saves not allowed - SaveOptions.allowConcurrentSaves is false");
912
+ if (errorCallback)
913
+ errorCallback(err);
914
+ return Promise.reject(err);
915
+ }
916
+ }
917
+ clearServerErrors(entitiesToSave);
918
+ const rejectInvalid = (valError) => {
919
+ if (errorCallback)
920
+ errorCallback(valError);
921
+ return Promise.reject(valError);
922
+ };
923
+ // With an async validator, the save waits for it. The entities count as being saved from here,
924
+ // so a second saveChanges while this one waits is refused, as it would be once this is sent.
925
+ // Without one, nothing here waits, exactly as before.
926
+ if (this.validationOptions.validateOnSave && hasAsyncValidators(entitiesToSave)) {
927
+ markIsBeingSaved(entitiesToSave, true);
928
+ return this.saveChangesValidateOnClientAsync(entitiesToSave).then(valError => {
929
+ markIsBeingSaved(entitiesToSave, false);
930
+ return valError ? rejectInvalid(valError) : this._sendSave(entitiesToSave, saveOptions, callback, errorCallback);
931
+ }, err => {
932
+ markIsBeingSaved(entitiesToSave, false);
933
+ return rejectInvalid(err);
934
+ });
935
+ }
936
+ let valError = this.saveChangesValidateOnClient(entitiesToSave);
937
+ if (valError)
938
+ return rejectInvalid(valError);
939
+ return this._sendSave(entitiesToSave, saveOptions, callback, errorCallback);
940
+ }
941
+ /** The part of saveChanges after validation: send the entities, and merge what comes back.
942
+ @hidden @internal */
943
+ _sendSave(entitiesToSave, saveOptions, callback, errorCallback) {
944
+ let dataService = DataService.resolve([saveOptions.dataService, this.dataService]);
945
+ let saveContext = {
946
+ entityManager: this,
947
+ dataService: dataService,
948
+ processSavedEntities: processSavedEntities,
949
+ resourceName: saveOptions.resourceName || this.saveOptions.resourceName || "SaveChanges"
950
+ };
951
+ // TODO: need to check that if we are doing a partial save that all entities whose temp keys
952
+ // are referenced are also in the partial save group
953
+ let saveBundle = { entities: entitiesToSave, saveOptions: saveOptions };
954
+ try { // Guard against exception thrown in dataservice adapter before it goes async
955
+ updateConcurrencyProperties(entitiesToSave);
956
+ return dataService.adapterInstance.saveChanges(saveContext, saveBundle)
957
+ .then(saveSuccess).then((r) => r, saveFail);
958
+ }
959
+ catch (err) {
960
+ // undo the marking by updateConcurrencyProperties
961
+ markIsBeingSaved(entitiesToSave, false);
962
+ if (errorCallback)
963
+ errorCallback(err);
964
+ return Promise.reject(err);
965
+ }
966
+ function saveSuccess(saveResult) {
967
+ let em = saveContext.entityManager;
968
+ markIsBeingSaved(entitiesToSave, false);
969
+ let savedEntities = saveContext.processSavedEntities(saveResult);
970
+ saveResult.entities = savedEntities;
971
+ // update _hasChanges after save.
972
+ em._setHasChanges();
973
+ // can't do this anymore because other changes might have been made while saved entities in flight.
974
+ // let hasChanges = (isFullSave && haveSameContents(entitiesToSave, savedEntities)) ? false : null;
975
+ // em._setHasChanges(hasChanges);
976
+ if (callback)
977
+ callback(saveResult);
978
+ return Promise.resolve(saveResult);
979
+ }
980
+ function processSavedEntities(saveResult) {
981
+ let savedEntities = saveResult.entities;
982
+ let deletedKeys = saveResult.deletedKeys || [];
983
+ if (savedEntities.length === 0 && deletedKeys.length === 0) {
984
+ return [];
985
+ }
986
+ let keyMappings = saveResult.keyMappings;
987
+ let em = saveContext.entityManager;
988
+ // must occur outside of isLoading block
989
+ fixupKeys(em, keyMappings);
990
+ core.using(em, "isLoading", true, () => {
991
+ let mappingContext = new MappingContext({
992
+ query: undefined, // tells visitAndMerge this is a save instead of a query
993
+ entityManager: em,
994
+ mergeOptions: { mergeStrategy: MergeStrategy.OverwriteChanges },
995
+ dataService: dataService
996
+ });
997
+ // The visitAndMerge operation has been optimized so that we do not actually perform a merge if the
998
+ // the save operation did not actually return the entity - i.e. during some updates and deletes.
999
+ savedEntities = mappingContext.visitAndMerge(savedEntities, { nodeType: "root" });
1000
+ });
1001
+ // detach any entities found in the em that appear in the deletedKeys list.
1002
+ deletedKeys.forEach(key => {
1003
+ let entityType = em.metadataStore._getStructuralType(key.entityTypeName);
1004
+ let ekey = new EntityKey(entityType, key.keyValues);
1005
+ let entity = em.getEntityByKey(ekey);
1006
+ if (entity) {
1007
+ entity.entityAspect.setDetached();
1008
+ }
1009
+ });
1010
+ return savedEntities;
1011
+ }
1012
+ function saveFail(serverError) {
1013
+ markIsBeingSaved(entitiesToSave, false);
1014
+ let clientError = processServerErrors(saveContext, serverError);
1015
+ if (errorCallback)
1016
+ errorCallback(clientError);
1017
+ return Promise.reject(clientError);
1018
+ }
1019
+ }
1020
+ /**
1021
+ Run the "saveChanges" pre-save client validation logic.
1022
+
1023
+ This is NOT a general purpose validation method.
1024
+ It is intended for utilities that must know if saveChanges
1025
+ would reject the save due to client validation errors.
1026
+
1027
+ It only validates entities if the EntityManager's
1028
+ {@link ValidationOptions}.validateOnSave is true.
1029
+
1030
+ @param entitiesToSave {Array of Entity} The list of entities to save (to validate).
1031
+ @returns {Error} Validation error or null if no error
1032
+ */
1033
+ saveChangesValidateOnClient(entitiesToSave) {
1034
+ if (this.validationOptions.validateOnSave) {
1035
+ let failedEntities = entitiesToSave.filter(function (entity) {
1036
+ let aspect = entity.entityAspect;
1037
+ let isValid = aspect.entityState.isDeleted() || aspect.validateEntity();
1038
+ return !isValid;
1039
+ });
1040
+ if (failedEntities.length > 0) {
1041
+ let valError = new Error("Client side validation errors encountered - see the entityErrors collection on this object for more detail");
1042
+ valError.entityErrors = createEntityErrors(failedEntities);
1043
+ return valError; // TODO: type this.
1044
+ }
1045
+ }
1046
+ return null;
1047
+ }
1048
+ /**
1049
+ The check {@link EntityManager.saveChangesValidateOnClient} makes, with async validators run too:
1050
+ each entity is validated with {@link EntityAspect.validateEntityAsync}. `saveChanges` uses this
1051
+ in its place when any of the entities it saves has an async validator.
1052
+ @param entitiesToSave - The entities to validate.
1053
+ @returns A promise of the error `saveChanges` would reject with, or null.
1054
+ */
1055
+ async saveChangesValidateOnClientAsync(entitiesToSave) {
1056
+ if (!this.validationOptions.validateOnSave)
1057
+ return null;
1058
+ const valid = await Promise.all(entitiesToSave.map(entity => entity.entityAspect.entityState.isDeleted() || entity.entityAspect.validateEntityAsync()));
1059
+ const failedEntities = entitiesToSave.filter((entity, ix) => !valid[ix]);
1060
+ if (failedEntities.length === 0)
1061
+ return null;
1062
+ const valError = new Error("Client side validation errors encountered - see the entityErrors collection on this object for more detail");
1063
+ valError.entityErrors = createEntityErrors(failedEntities);
1064
+ return valError;
1065
+ }
1066
+ /** @hidden @internal */
1067
+ _findEntityGroup(entityType) {
1068
+ return this._entityGroupMap.get(entityType.name);
1069
+ }
1070
+ /**
1071
+ Attempts to locate an entity within this EntityManager by its [EntityKey].
1072
+ @param entityKey - The {@link EntityKey} of the Entity to be located.
1073
+ @param type - The {@link EntityType} for this key.
1074
+ @param typeName - The EntityType name for this key.
1075
+ @param keyValues - The values for this key - will usually just be a single value; an array is only needed for multipart keys.
1076
+ @returns An Entity or null;
1077
+ */
1078
+ getEntityByKey(...args) {
1079
+ let entityKey = createEntityKey(this, args).entityKey;
1080
+ let entityTypes = entityKey._subtypes || [entityKey.entityType];
1081
+ let e;
1082
+ // hack use of some to simulate mapFirst logic.
1083
+ entityTypes.some((et) => {
1084
+ let group = this._findEntityGroup(et);
1085
+ // group version of findEntityByKey doesn't care about entityType
1086
+ e = group && group.findEntityByKey(entityKey);
1087
+ return e != null;
1088
+ });
1089
+ return e || null;
1090
+ }
1091
+ /**
1092
+ Attempts to fetch an entity from the server by its {@link EntityKey} with
1093
+ an option to check the local cache first. Note the this EntityManager's queryOptions.mergeStrategy
1094
+ will be used to merge any server side entity returned by this method.
1095
+ ```ts
1096
+ // assume em1 is an EntityManager containing a number of preexisting entities,
1097
+ // and that Employee is registered with its MetadataStore.
1098
+ const result = await em1.fetchEntityByKey(Employee, 1);
1099
+ const employee = result.entity; // Employee | null
1100
+ const entityKey = result.entityKey;
1101
+ const fromCache = result.fromCache;
1102
+ // look in the cache first, and query the server only if it is not there
1103
+ const { entity } = await em1.fetchEntityByKey(Employee, 1, true);
1104
+ ```
1105
+
1106
+ A type name, an EntityType or an {@link EntityKey} also works; the result's `entity` is then a plain Entity.
1107
+ ```ts
1108
+ const result = await em1.fetchEntityByKey("Employee", 1);
1109
+ ```
1110
+ @param typeName - The EntityType name for this key.
1111
+ @param entityType - The EntityType for this key.
1112
+ @param keyValues - The values for this key - will usually just be a single value; an array is only needed for multipart keys.
1113
+ @param entityKey - The {@link EntityKey} of the Entity to be located.
1114
+ @param checkLocalCacheFirst - (default = false) - Whether to check this EntityManager first before going to the server. By default, the query will NOT do this.
1115
+ @returns {Promise}
1116
+ - Properties on the promise success result
1117
+ - entity {Object} The entity found, or null if there is none. (Before 3.0 this was undefined; see UPGRADE.md.)
1118
+ - entityKey {EntityKey} The entityKey of the entity to fetch.
1119
+ - fromCache {Boolean} Whether this entity was fetched from the server or was found in the local cache.
1120
+ */
1121
+ fetchEntityByKey(...args) {
1122
+ let dataService = DataService.resolve([this.dataService]);
1123
+ if ((!dataService.hasServerMetadata) || this.metadataStore.hasMetadataFor(dataService.serviceName)) {
1124
+ return fetchEntityByKeyCore(this, args);
1125
+ }
1126
+ else {
1127
+ return this.fetchMetadata(dataService).then(() => {
1128
+ return fetchEntityByKeyCore(this, args);
1129
+ });
1130
+ }
1131
+ }
1132
+ /**
1133
+ [Deprecated] - Attempts to locate an entity within this EntityManager by its {@link EntityKey}.
1134
+ ```ts
1135
+ // assume em1 is an EntityManager containing a number of preexisting entities.
1136
+ const employeeType = em1.metadataStore.getAsEntityType("Employee");
1137
+ const employeeKey = new EntityKey(employeeType, 1);
1138
+ const employee = em1.findEntityByKey(employeeKey);
1139
+ // employee will either be an entity or null.
1140
+ ```
1141
+ @deprecated Use getEntityByKey instead
1142
+ @param entityKey - The {@link EntityKey} of the Entity to be located.
1143
+ @returns An Entity or null;
1144
+ */
1145
+ findEntityByKey(entityKey) {
1146
+ return this.getEntityByKey(entityKey);
1147
+ }
1148
+ /**
1149
+ Generates a temporary key for the specified entity. This is used to insure that newly
1150
+ created entities have unique keys and to register that these keys are temporary and
1151
+ need to be automatically replaced with 'real' key values once these entities are saved.
1152
+
1153
+ The {@link EntityManager.keyGeneratorCtor} property is used internally by this method to actually generate
1154
+ the keys - See the KeyGenerator interface interface description to see
1155
+ how a custom key generator can be plugged in.
1156
+ ```ts
1157
+ // assume em1 is an EntityManager containing a number of preexisting entities.
1158
+ const customer = em1.createEntity(Customer, { companyName: "Acme" }, EntityState.Detached);
1159
+ const customerId = em1.generateTempKeyValue(customer);
1160
+ // customer.customerID is now set to a newly generated unique id value.
1161
+ // This property will change again after a successful save of the customer.
1162
+ em1.addEntity(customer);
1163
+ await em1.saveChanges();
1164
+ // customer.customerID !== customerId, because the server will have generated
1165
+ // a new id and the client will have been updated with this new id.
1166
+ ```
1167
+ @param entity - The Entity to generate a key for.
1168
+ @returns The new key value
1169
+ */
1170
+ generateTempKeyValue(entity) {
1171
+ // TODO - check if this entity is attached to this EntityManager.
1172
+ assertParam(entity, "entity").isEntity().check();
1173
+ let entityType = entity.entityType;
1174
+ let nextKeyValue = this.keyGenerator.generateTempKeyValue(entityType);
1175
+ let keyProp = entityType.keyProperties[0];
1176
+ entity.setProperty(keyProp.name, nextKeyValue);
1177
+ entity.entityAspect.hasTempKey = true;
1178
+ return nextKeyValue;
1179
+ }
1180
+ /**
1181
+ Returns whether there are any changed entities of the specified {@link EntityType}s. A 'changed' Entity has
1182
+ has an {@link EntityState} of either Added, Modified or Deleted.
1183
+
1184
+ This method can be used to determine if an EntityManager has any changes
1185
+ ```ts
1186
+ // assume em1 is an EntityManager containing a number of preexisting entities.
1187
+ if (em1.hasChanges()) {
1188
+ // do something interesting
1189
+ }
1190
+ ```
1191
+
1192
+ or if it has any changes on to a specific {@link EntityType}.
1193
+ ```ts
1194
+ // assume em1 is an EntityManager containing a number of preexisting entities.
1195
+ if (em1.hasChanges(Customer)) {
1196
+ // do something interesting
1197
+ }
1198
+ ```
1199
+
1200
+ or to a collection of {@link EntityType}s, named or given as EntityTypes
1201
+ ```ts
1202
+ // assume em1 is an EntityManager containing a number of preexisting entities.
1203
+ if (em1.hasChanges(["Customer", "Order"])) {
1204
+ // do something interesting
1205
+ }
1206
+ ```
1207
+ @param entityTypes - The {@link EntityType} or EntityTypes for which 'changed' entities will be found.
1208
+ @param entityTypeNames - The {@link EntityType} name or names for which 'changed' entities will be found.
1209
+ @returns Whether there are any changed entities that match the types specified..
1210
+ */
1211
+ hasChanges(entityTypes) {
1212
+ if (!this._hasChanges)
1213
+ return false;
1214
+ if (entityTypes === undefined)
1215
+ return this._hasChanges;
1216
+ return this._hasChangesCore(entityTypes);
1217
+ }
1218
+ /** @hidden @internal */
1219
+ // backdoor to "really" check for changes.
1220
+ _hasChangesCore(entityTypes) {
1221
+ let ets = checkEntityTypes(this, entityTypes);
1222
+ let entityGroups = getEntityGroups(this, ets);
1223
+ return entityGroups.some(function (eg) {
1224
+ return eg && eg.hasChanges();
1225
+ });
1226
+ }
1227
+ /**
1228
+ Returns a array of all changed entities of the specified {@link EntityType}s. A 'changed' Entity has
1229
+ has an {@link EntityState} of either Added, Modified or Deleted.
1230
+
1231
+ This method can be used to get all of the changed entities within an EntityManager
1232
+ ```ts
1233
+ // assume em1 is an EntityManager containing a number of preexisting entities.
1234
+ const changedEntities = em1.getChanges();
1235
+ ```
1236
+
1237
+ or you can specify that you only want the changes on a specific {@link EntityType}
1238
+ ```ts
1239
+ // assume em1 is an EntityManager containing a number of preexisting entities.
1240
+ const changedCustomers = em1.getChanges(Customer); // Customer[], from the registered class
1241
+ ```
1242
+
1243
+ or to a collection of {@link EntityType}s, named or given as EntityTypes
1244
+ ```ts
1245
+ // assume em1 is an EntityManager containing a number of preexisting entities.
1246
+ const changedCustomersAndOrders = em1.getChanges(["Customer", "Order"]); // Entity[]
1247
+ ```
1248
+ @param entityTypes - The {@link EntityType} or EntityTypes for which 'changed' entities will be found.
1249
+ @param entityTypeNames - The {@link EntityType} name or names for which 'changed' entities will be found.
1250
+ @returns An array of Entities
1251
+ */
1252
+ getChanges(entityTypes) {
1253
+ let ets = checkEntityTypes(this, entityTypes);
1254
+ return getChangesCore(this, ets);
1255
+ }
1256
+ /**
1257
+ Rejects (reverses the effects) all of the additions, modifications and deletes from this EntityManager.
1258
+ Calls {@link EntityAspect.rejectChanges} on every changed entity in this EntityManager.
1259
+ ```ts
1260
+ // assume em1 is an EntityManager containing a number of preexisting entities.
1261
+ const entities = em1.rejectChanges();
1262
+ ```
1263
+ @returns The entities whose changes were rejected. These entities will all have EntityStates of
1264
+ either 'Unchanged' or 'Detached'
1265
+ */
1266
+ rejectChanges() {
1267
+ if (!this._hasChanges)
1268
+ return [];
1269
+ let changes = getChangesCore(this);
1270
+ // next line stops individual reject changes from each calling _hasChangesCore
1271
+ let aspects = changes.map(function (e) {
1272
+ return e.entityAspect._checkOperation("rejectChanges");
1273
+ });
1274
+ this._hasChanges = false;
1275
+ aspects.forEach(function (aspect) {
1276
+ aspect.rejectChanges();
1277
+ });
1278
+ this.hasChangesChanged.publish({ entityManager: this, hasChanges: false });
1279
+ return changes;
1280
+ }
1281
+ /**
1282
+ Returns a array of all entities of the specified {@link EntityType}s with the specified {@link EntityState}s.
1283
+
1284
+ This method can be used to get all of the entities within an EntityManager
1285
+ ```ts
1286
+ // assume em1 is an EntityManager containing a number of preexisting entities.
1287
+ const entities = em1.getEntities();
1288
+ ```
1289
+
1290
+ or you can specify that you only want the entities of a specific {@link EntityType}
1291
+ ```ts
1292
+ // assume em1 is an EntityManager containing a number of preexisting entities.
1293
+ const customers = em1.getEntities(Customer); // Customer[]
1294
+ ```
1295
+
1296
+ or of a collection of {@link EntityType}s, named or given as EntityTypes
1297
+ ```ts
1298
+ // assume em1 is an EntityManager containing a number of preexisting entities.
1299
+ const customersAndOrders = em1.getEntities(["Customer", "Order"]); // Entity[]
1300
+ ```
1301
+
1302
+ You can also ask for entities with a particular {@link EntityState} or EntityStates.
1303
+ ```ts
1304
+ // assume em1 is an EntityManager containing a number of preexisting entities.
1305
+ const addedCustomers = em1.getEntities(Customer, EntityState.Added); // Customer[]
1306
+ const addedOrModifiedOrders = em1.getEntities(Order, [EntityState.Added, EntityState.Modified]);
1307
+ ```
1308
+
1309
+ @param entityTypeName - The {@link EntityType} name or names for which entities will be found.
1310
+ If this parameter is omitted, all EntityTypes are searched.
1311
+ @param entityTypes - The {@link EntityType} or EntityTypes for which entities will be found.
1312
+ If this parameter is omitted, all EntityTypes are searched.
1313
+ @param entityStates - The {@link EntityState}s for which entities will be found.
1314
+ If this parameter is omitted, entities of all EntityStates are returned.
1315
+ @returns An array of Entities
1316
+ */
1317
+ getEntities(entityTypes, entityStates) {
1318
+ let entTypes = checkEntityTypes(this, entityTypes);
1319
+ assertParam(entityStates, "entityStates").isOptional().isEnumOf(EntityState).or().isNonEmptyArray().isEnumOf(EntityState).check();
1320
+ let states = validateEntityStates(this, entityStates);
1321
+ return getEntitiesCore(this, entTypes, states);
1322
+ }
1323
+ // protected methods
1324
+ /** @hidden @internal */
1325
+ _notifyStateChange(entity, needsSave) {
1326
+ let ecArgs = { entityAction: EntityAction.EntityStateChange, entity: entity };
1327
+ if (needsSave) {
1328
+ if (!this._hasChanges)
1329
+ this._setHasChanges(true);
1330
+ }
1331
+ else {
1332
+ // Called when rejecting a change or merging an unchanged record: the manager may have just
1333
+ // become clean, and finding out means _hasChangesCore scanning the whole cache. During a
1334
+ // query or import that would run once per entity, so it is deferred to the end of the load
1335
+ // and done once.
1336
+ //
1337
+ // Only that is deferred. The event below belongs to THIS entity and is published now:
1338
+ // deferring it dropped it, because the deferred closure is built once (note the `||`) and
1339
+ // so captured the first entity's arguments and published for that one alone. Every entity
1340
+ // after the first reported nothing - and only when the manager happened to already have
1341
+ // changes, since otherwise this branch is skipped entirely.
1342
+ if (this._hasChanges) {
1343
+ if (this.isLoading) {
1344
+ this._hasChangesAction = this._hasChangesAction || (() => this._setHasChanges(null));
1345
+ }
1346
+ else {
1347
+ this._setHasChanges();
1348
+ }
1349
+ }
1350
+ }
1351
+ this.entityChanged.publish(ecArgs);
1352
+ }
1353
+ /**
1354
+ * `null` means recompute it from the cache, which is the expensive case.
1355
+ * @hidden @internal
1356
+ */
1357
+ _setHasChanges(hasChanges) {
1358
+ if (hasChanges == null)
1359
+ hasChanges = this._hasChangesCore();
1360
+ let hadChanges = this._hasChanges;
1361
+ this._hasChanges = hasChanges;
1362
+ if (hasChanges !== hadChanges) {
1363
+ this.hasChangesChanged.publish({ entityManager: this, hasChanges: hasChanges });
1364
+ }
1365
+ this._hasChangesAction = undefined;
1366
+ }
1367
+ /** @hidden @internal */
1368
+ _linkRelatedEntities(entity) {
1369
+ let em = this;
1370
+ let entityAspect = entity.entityAspect;
1371
+ // we do not want entityState to change as a result of linkage.
1372
+ core.using(em, "isLoading", true, function () {
1373
+ let unattachedMap = em._unattachedChildrenMap;
1374
+ let entityKey = entityAspect.getKey();
1375
+ let entityType = entityKey.entityType;
1376
+ while (entityType) {
1377
+ let keystring = entityKey.toString(entityType);
1378
+ // attach any unattachedChildren
1379
+ let tuples = unattachedMap.getTuplesByString(keystring);
1380
+ if (tuples) {
1381
+ tuples.slice(0).forEach(function (tpl) {
1382
+ let unattachedChildren = tpl.children.filter(function (e) {
1383
+ return e.entityAspect.entityState !== EntityState.Detached;
1384
+ });
1385
+ let childToParentNp;
1386
+ let parentToChildNp;
1387
+ // np is usually childToParentNp
1388
+ // except with unidirectional 1-n where it is parentToChildNp;
1389
+ let np = tpl.navigationProperty;
1390
+ let inverseNp = np.inverse;
1391
+ if (inverseNp) {
1392
+ // bidirectional
1393
+ childToParentNp = np;
1394
+ parentToChildNp = inverseNp;
1395
+ if (parentToChildNp.isScalar) {
1396
+ let onlyChild = unattachedChildren[0];
1397
+ entity.setProperty(parentToChildNp.name, onlyChild);
1398
+ onlyChild.setProperty(childToParentNp.name, entity);
1399
+ }
1400
+ else {
1401
+ let currentChildren = entity.getProperty(parentToChildNp.name);
1402
+ unattachedChildren.forEach(function (child) {
1403
+ currentChildren.push(child);
1404
+ child.setProperty(childToParentNp.name, entity);
1405
+ });
1406
+ }
1407
+ unattachedMap.removeChildren(keystring, childToParentNp);
1408
+ }
1409
+ else {
1410
+ // unidirectional
1411
+ // if (np.isScalar || np.parentType !== entity.entityType) {
1412
+ if (np.isScalar) {
1413
+ // n -> 1 eg: child: OrderDetail parent: Product
1414
+ // 1 -> 1 eg child: Employee parent: Employee ( only Manager, no DirectReports property)
1415
+ childToParentNp = np;
1416
+ unattachedChildren.forEach(function (child) {
1417
+ child.setProperty(childToParentNp.name, entity);
1418
+ });
1419
+ unattachedMap.removeChildren(keystring, childToParentNp);
1420
+ }
1421
+ else {
1422
+ // 1 -> n eg: parent: Region child: Terr
1423
+ parentToChildNp = np;
1424
+ let currentChildren = entity.getProperty(parentToChildNp.name);
1425
+ unattachedChildren.forEach(function (child) {
1426
+ // we know if can't already be there.
1427
+ observableArray.pushUnchecked(currentChildren, child);
1428
+ });
1429
+ // Deliberately NOT removeChildren, unlike the three branches above. The tuple
1430
+ // stays in the map for the life of the manager, which does hold its children
1431
+ // against collection - but it is what re-links them if this parent is detached
1432
+ // and a new one with the same key attached, because a unidirectional child has
1433
+ // no navigation property of its own to rebuild the collection from. Removing it
1434
+ // leaves the re-attached parent with an empty collection. Measured: it produces
1435
+ // no duplicates, since a given parent key is linked once.
1436
+ }
1437
+ }
1438
+ });
1439
+ }
1440
+ entityType = entityType.baseEntityType; // look for relationships up the hierarchy
1441
+ }
1442
+ // now add to unattachedMap if needed.
1443
+ entity.entityType.navigationProperties.forEach(function (np) {
1444
+ if (np.isScalar) {
1445
+ let value = entity.getProperty(np.name);
1446
+ // property is already linked up
1447
+ if (value)
1448
+ return;
1449
+ }
1450
+ // first determine if np contains a parent or child
1451
+ // having a parentKey means that this is a child
1452
+ // if a parent then no need for more work because children will attach to it.
1453
+ let parentKey = entityAspect.getParentKey(np);
1454
+ if (parentKey) {
1455
+ // check for empty keys - meaning that parent id's are not yet set.
1456
+ if (parentKey._isEmpty())
1457
+ return;
1458
+ // if a child - look for parent in the em cache
1459
+ if (np.invForeignKeyNames.length) {
1460
+ // np relates to non-PK property of parent entity
1461
+ const query = new EntityQuery(parentKey.entityType.defaultResourceName).where(np.invForeignKeyNames[0], 'eq', parentKey.values[0]);
1462
+ const qresult = em.executeQueryLocally(query);
1463
+ if (qresult.length === 1) {
1464
+ let parent = qresult[0];
1465
+ entity.setProperty(np.name, parent);
1466
+ }
1467
+ }
1468
+ else {
1469
+ // np relates to PK of parent entity
1470
+ let parent = em.getEntityByKey(parentKey);
1471
+ if (parent) {
1472
+ // if found hook it up
1473
+ entity.setProperty(np.name, parent);
1474
+ }
1475
+ else {
1476
+ // else add parent to unresolvedParentMap;
1477
+ unattachedMap.addChild(parentKey, np, entity);
1478
+ }
1479
+ }
1480
+ }
1481
+ else if (np.inverse && np.inverse.invForeignKeyNames.length) {
1482
+ // np relates to non-PK property of parent entity; query entities by FK
1483
+ const akValue = entity.getProperty(np.inverse.invForeignKeyNames[0]);
1484
+ const query = new EntityQuery(np.entityType.defaultResourceName).where(np.invForeignKeyNames[0], 'eq', akValue);
1485
+ const qresult = em.executeQueryLocally(query);
1486
+ qresult.forEach((child) => {
1487
+ child.setProperty(np.inverse.name, entity);
1488
+ });
1489
+ }
1490
+ });
1491
+ // handle unidirectional 1-x where we set x.fk
1492
+ entity.entityType.foreignKeyProperties.forEach(function (fkProp) {
1493
+ let invNp = fkProp.inverseNavigationProperty;
1494
+ if (!invNp)
1495
+ return;
1496
+ // unidirectional fk props only
1497
+ let fkValue = entity.getProperty(fkProp.name);
1498
+ let parentKey = new EntityKey(invNp.parentType, [fkValue]);
1499
+ let parent = em.getEntityByKey(parentKey);
1500
+ if (parent) {
1501
+ if (invNp.isScalar) {
1502
+ parent.setProperty(invNp.name, entity);
1503
+ }
1504
+ else {
1505
+ if (em.isLoading) {
1506
+ observableArray.pushUnchecked(parent.getProperty(invNp.name), entity);
1507
+ }
1508
+ else {
1509
+ parent.getProperty(invNp.name).push(entity);
1510
+ }
1511
+ }
1512
+ }
1513
+ else {
1514
+ // else add parent to unresolvedParentMap;
1515
+ unattachedMap.addChild(parentKey, invNp, entity);
1516
+ }
1517
+ });
1518
+ });
1519
+ }
1520
+ /** @hidden @internal */
1521
+ _attachEntityCore(entity, entityState, mergeStrategy) {
1522
+ let group = findOrCreateEntityGroup(this, entity.entityType);
1523
+ let attachedEntity = group.attachEntity(entity, entityState, mergeStrategy);
1524
+ this._linkRelatedEntities(attachedEntity);
1525
+ return attachedEntity;
1526
+ }
1527
+ /** @hidden @internal */
1528
+ _updateFkVal(fkProp, oldValue, newValue) {
1529
+ let group = this._entityGroupMap.get(fkProp.parentType.name);
1530
+ if (!group)
1531
+ return;
1532
+ group._updateFkVal(fkProp, oldValue, newValue);
1533
+ }
1534
+ }
1535
+ EntityManager.prototype._$typeName = "EntityManager";
1536
+ BreezeEvent.bubbleEvent(EntityManager.prototype);
1537
+ // The adapters an EntityManager falls back to when none is registered (see default-adapters.ts).
1538
+ // Installed by this module, which every bundle that talks to a server contains, rather than by
1539
+ // an import for effect, which a bundler may drop. See "sideEffects" in CHANGES-DEV.md.
1540
+ setDefaultAdapters(serverDefaultAdapters);
1541
+ /** Whether any of these entities has an async validator, on its type, a property, or a complex type
1542
+ it holds. Looked up once per type: validators can be added at any time, so it is not cached. */
1543
+ function hasAsyncValidators(entities) {
1544
+ const seen = new Set();
1545
+ const typeHasAsync = (stype) => {
1546
+ if (seen.has(stype))
1547
+ return false;
1548
+ seen.add(stype);
1549
+ if (stype.getAllValidators().some(v => v.isAsync))
1550
+ return true;
1551
+ return stype.getProperties().some((p) => p.getAllValidators().some((v) => v.isAsync) ||
1552
+ (p.isComplexProperty && typeHasAsync(p.dataType)));
1553
+ };
1554
+ return entities.some(e => !e.entityAspect.entityState.isDeleted() && typeHasAsync(e.entityType));
1555
+ }
1556
+ function clearServerErrors(entities) {
1557
+ entities.forEach(function (entity) {
1558
+ let serverKeys = [];
1559
+ let aspect = entity.entityAspect;
1560
+ core.objectForEach(aspect._validationErrors, function (key, ve) {
1561
+ if (ve.isServerError)
1562
+ serverKeys.push(key);
1563
+ });
1564
+ if (serverKeys.length === 0)
1565
+ return;
1566
+ aspect._processValidationOpAndPublish(function () {
1567
+ serverKeys.forEach(function (key) {
1568
+ aspect._removeValidationError(key);
1569
+ });
1570
+ });
1571
+ });
1572
+ }
1573
+ function createEntityErrors(entities) {
1574
+ let entityErrors = [];
1575
+ entities.forEach((entity) => {
1576
+ core.objectForEach(entity.entityAspect._validationErrors, function (key, ve) {
1577
+ let cfg = core.extend({
1578
+ entity: entity,
1579
+ // An error added with addValidationError has no validator. Reading one threw a TypeError,
1580
+ // which replaced the whole validation error - and its entityErrors - with "Cannot read
1581
+ // properties of undefined". Such an error is named by its key.
1582
+ errorName: ve.validator ? ve.validator.name : ve.key
1583
+ }, ve, ["errorMessage", "propertyName", "isServerError", "custom"]);
1584
+ entityErrors.push(cfg);
1585
+ });
1586
+ });
1587
+ return entityErrors;
1588
+ }
1589
+ function processServerErrors(saveContext, saveError) {
1590
+ // converting ISaveErrorFromServer -> ISaveError
1591
+ let serverErrors = saveError.entityErrors;
1592
+ if (!serverErrors)
1593
+ return saveError;
1594
+ let entityManager = saveContext.entityManager;
1595
+ let metadataStore = entityManager.metadataStore;
1596
+ let entityErrors = serverErrors.map((serr) => {
1597
+ let entity = null;
1598
+ let entityType;
1599
+ if (serr.keyValues) {
1600
+ entityType = metadataStore._getStructuralType(serr.entityTypeName);
1601
+ let ekey = new EntityKey(entityType, serr.keyValues);
1602
+ entity = entityManager.getEntityByKey(ekey);
1603
+ }
1604
+ if (entityType && entity) {
1605
+ let context = serr.propertyName ?
1606
+ {
1607
+ propertyName: serr.propertyName,
1608
+ property: entityType.getProperty(serr.propertyName) || undefined
1609
+ } : {};
1610
+ let key = ValidationError.getKey(serr.errorName || serr.errorMessage, serr.propertyName);
1611
+ let ve = new ValidationError(null, context, serr.errorMessage, key);
1612
+ ve.isServerError = true;
1613
+ entity.entityAspect.addValidationError(ve);
1614
+ }
1615
+ let entityError = core.extend({
1616
+ entity: entity,
1617
+ isServerError: true
1618
+ }, serr, ["errorName", "errorMessage", "propertyName", "custom"]);
1619
+ return entityError;
1620
+ });
1621
+ // converting ISaveErrorFromServer -> ISaveError
1622
+ saveError.entityErrors = entityErrors;
1623
+ return saveError;
1624
+ }
1625
+ function fetchEntityByKeyCore(em, args) {
1626
+ let tpl = createEntityKey(em, args);
1627
+ let entityKey = tpl.entityKey;
1628
+ let checkLocalCacheFirst = tpl.remainingArgs.length === 0 ? false : !!tpl.remainingArgs[0];
1629
+ let entity = null;
1630
+ let foundIt = false;
1631
+ if (checkLocalCacheFirst) {
1632
+ entity = em.getEntityByKey(entityKey);
1633
+ foundIt = entity != null;
1634
+ if (entity != null &&
1635
+ // null the entity if it is deleted and we should exclude deleted entities
1636
+ !em.queryOptions.includeDeleted && entity.entityAspect.entityState.isDeleted()) {
1637
+ entity = null;
1638
+ // but resume looking if we'd overwrite deleted entity with a remote entity
1639
+ // note: em.queryOptions is always fully resolved by now
1640
+ foundIt = em.queryOptions.mergeStrategy !== MergeStrategy.OverwriteChanges;
1641
+ }
1642
+ }
1643
+ if (foundIt) {
1644
+ return Promise.resolve({ entity: entity, entityKey: entityKey, fromCache: true });
1645
+ }
1646
+ else {
1647
+ return EntityQuery.fromEntityKey(entityKey).using(em).execute().then(function (data) {
1648
+ entity = (data.results.length === 0) ? null : data.results[0];
1649
+ return Promise.resolve({ entity: entity, entityKey: entityKey, fromCache: false });
1650
+ });
1651
+ }
1652
+ }
1653
+ // private fns
1654
+ // takes in entityTypes as either strings or entityTypes or arrays of either
1655
+ // and returns either an entityType or an array of entityTypes or throws an error
1656
+ function checkEntityTypes(em, entityTypes) {
1657
+ // A registered constructor stands for its type name, which is resolved against this manager's
1658
+ // own store - see the note in createEntity. Normalized before the assertions, so the rest of
1659
+ // this, and every caller, is the 2.x path unchanged.
1660
+ if (typeof entityTypes === "function") {
1661
+ entityTypes = entityTypeForCtor(entityTypes).name;
1662
+ }
1663
+ else if (Array.isArray(entityTypes) && entityTypes.some(t => typeof t === "function")) {
1664
+ entityTypes = entityTypes.map(t => typeof t === "function" ? entityTypeForCtor(t).name : t);
1665
+ }
1666
+ assertParam(entityTypes, "entityTypes").isString().isOptional().or().isNonEmptyArray().isString()
1667
+ .or().isInstanceOf(EntityType).or().isNonEmptyArray().isInstanceOf(EntityType).check();
1668
+ let resultTypes;
1669
+ if (typeof entityTypes === "string") {
1670
+ resultTypes = em.metadataStore._getStructuralType(entityTypes, false);
1671
+ }
1672
+ else if (Array.isArray(entityTypes) && typeof entityTypes[0] === "string") {
1673
+ resultTypes = entityTypes.map(function (etName) {
1674
+ return em.metadataStore._getStructuralType(etName, false);
1675
+ });
1676
+ }
1677
+ else {
1678
+ resultTypes = entityTypes;
1679
+ }
1680
+ return resultTypes;
1681
+ }
1682
+ function getChangesCore(em, entityTypes) {
1683
+ let entityGroups = getEntityGroups(em, entityTypes);
1684
+ // TODO: think about writing a core.mapMany method if we see more of these.
1685
+ let selected = [];
1686
+ entityGroups.forEach(function (eg) {
1687
+ // eg may be undefined or null
1688
+ if (!eg)
1689
+ return;
1690
+ let entities = eg.getChanges();
1691
+ if (selected && selected.length) {
1692
+ selected = selected.concat(entities);
1693
+ }
1694
+ else {
1695
+ selected = entities;
1696
+ }
1697
+ });
1698
+ return selected;
1699
+ }
1700
+ function getEntitiesCore(em, entityTypes, entityStates) {
1701
+ let entityGroups = getEntityGroups(em, entityTypes);
1702
+ // TODO: think about writing a core.mapMany method if we see more of these.
1703
+ let selected = [];
1704
+ entityGroups.forEach(function (eg) {
1705
+ // eg may be undefined or null
1706
+ if (!eg)
1707
+ return;
1708
+ let entities = eg.getEntities(entityStates);
1709
+ if (selected && selected.length) {
1710
+ selected = selected.concat(entities);
1711
+ }
1712
+ else {
1713
+ selected = entities;
1714
+ }
1715
+ });
1716
+ return selected;
1717
+ }
1718
+ function createEntityKey(em, args) {
1719
+ if (args[0] instanceof EntityKey) {
1720
+ return { entityKey: args[0], remainingArgs: arraySlice(args, 1) };
1721
+ }
1722
+ if (args.length >= 2) {
1723
+ let entityType;
1724
+ try {
1725
+ entityType = (typeof args[0] === 'string') ? em.metadataStore._getStructuralType(args[0], false)
1726
+ : (typeof args[0] === 'function') ? em.metadataStore._getStructuralType(entityTypeForCtor(args[0]).name, false) : args[0];
1727
+ }
1728
+ catch (e) { /* not a type: the error below says what is expected */ }
1729
+ if (entityType instanceof EntityType) {
1730
+ // Outside the try: an error about the key values - a name that is not part of the key, a key
1731
+ // property with no value - says more than the one below.
1732
+ return { entityKey: new EntityKey(entityType, args[1]), remainingArgs: arraySlice(args, 2) };
1733
+ }
1734
+ }
1735
+ throw new Error("Must supply an EntityKey OR an EntityType name or EntityType followed by a key value or an array of key values.");
1736
+ }
1737
+ function markIsBeingSaved(entities, flag) {
1738
+ entities.forEach(function (entity) {
1739
+ entity.entityAspect.isBeingSaved = flag;
1740
+ });
1741
+ }
1742
+ function exportEntityGroups(em, entitiesOrEntityTypes) {
1743
+ let entityGroupMap;
1744
+ let first = entitiesOrEntityTypes && entitiesOrEntityTypes[0];
1745
+ // check if array
1746
+ if (first) {
1747
+ // group entities by entityType and
1748
+ // create 'groups' that look like entityGroups.
1749
+ entityGroupMap = new Map();
1750
+ if (first.entityType) {
1751
+ let entities = entitiesOrEntityTypes;
1752
+ // assume "entities" is an array of entities;
1753
+ entities.forEach(function (e) {
1754
+ if (e.entityAspect.entityState === EntityState.Detached) {
1755
+ throw new Error("Unable to export an entity with an EntityState of 'Detached'");
1756
+ }
1757
+ let group = entityGroupMap.get(e.entityType.name);
1758
+ if (!group) {
1759
+ group = {};
1760
+ group.entityType = e.entityType;
1761
+ group._entities = [];
1762
+ entityGroupMap.set(e.entityType.name, group);
1763
+ }
1764
+ group._entities.push(e);
1765
+ });
1766
+ }
1767
+ else {
1768
+ // assume "entities" is an array of EntityTypes (or names)
1769
+ let entityTypes = checkEntityTypes(em, entitiesOrEntityTypes);
1770
+ if (entityTypes != null) {
1771
+ entityTypes.forEach((et) => {
1772
+ let group = em._entityGroupMap.get(et.name);
1773
+ if (group && group._entities.length) {
1774
+ entityGroupMap.set(et.name, group);
1775
+ }
1776
+ });
1777
+ }
1778
+ }
1779
+ }
1780
+ else if (entitiesOrEntityTypes && entitiesOrEntityTypes.length === 0) {
1781
+ // empty array = export nothing
1782
+ entityGroupMap = new Map();
1783
+ }
1784
+ else {
1785
+ entityGroupMap = em._entityGroupMap;
1786
+ }
1787
+ let tempKeys = [];
1788
+ // the exported shape is a plain object: this is the serialized wire format,
1789
+ // and JSON.stringify(new Map()) would produce '{}'.
1790
+ let newGroupMap = {};
1791
+ entityGroupMap.forEach((entityGroup, entityTypeName) => {
1792
+ newGroupMap[entityTypeName] = exportEntityGroup(entityGroup, tempKeys);
1793
+ });
1794
+ return { entityGroupMap: newGroupMap, tempKeys: tempKeys };
1795
+ }
1796
+ function exportEntityGroup(entityGroup, tempKeys) {
1797
+ let resultGroup = {};
1798
+ let entityType = entityGroup.entityType;
1799
+ let dps = entityType.dataProperties;
1800
+ let serializerFn = getSerializerFn(entityType);
1801
+ let rawEntities = [];
1802
+ entityGroup._entities.forEach((entity) => {
1803
+ if (entity) {
1804
+ let rawEntity = structuralObjectToJson(entity, dps, serializerFn, tempKeys);
1805
+ rawEntities.push(rawEntity);
1806
+ }
1807
+ });
1808
+ resultGroup.entities = rawEntities;
1809
+ return resultGroup;
1810
+ }
1811
+ function structuralObjectToJson(so, dps, serializerFn, tempKeys) {
1812
+ let result = {};
1813
+ dps.forEach(function (dp) {
1814
+ let dpName = dp.name;
1815
+ let value = so.getProperty(dpName);
1816
+ if (value == null && dp.defaultValue == null)
1817
+ return;
1818
+ if (value && dp.isComplexProperty) {
1819
+ let coDps = dp.dataType.dataProperties;
1820
+ value = core.map(value, function (v) {
1821
+ return structuralObjectToJson(v, coDps, serializerFn);
1822
+ });
1823
+ }
1824
+ else {
1825
+ value = serializerFn ? serializerFn(dp, value) : value;
1826
+ if (dp.isUnmapped) {
1827
+ value = core.toJSONSafe(value, core.toJSONSafeReplacer);
1828
+ }
1829
+ }
1830
+ if (value === undefined)
1831
+ return;
1832
+ result[dpName] = value;
1833
+ });
1834
+ // if (so.entityAspect) {
1835
+ if (EntityAspect.isEntity(so)) {
1836
+ let aspect = so.entityAspect;
1837
+ let entityState = aspect.entityState;
1838
+ let newAspect = {
1839
+ tempNavPropNames: exportTempKeyInfo(aspect, tempKeys || []),
1840
+ entityState: entityState.name
1841
+ };
1842
+ if (aspect.extraMetadata) {
1843
+ newAspect.extraMetadata = aspect.extraMetadata;
1844
+ }
1845
+ if (entityState.isModified() || entityState.isDeleted()) {
1846
+ newAspect.originalValuesMap = aspect.originalValues;
1847
+ }
1848
+ result.entityAspect = newAspect;
1849
+ }
1850
+ else {
1851
+ let aspect = so.complexAspect;
1852
+ let newAspect = {};
1853
+ if (aspect.originalValues && !core.isEmpty(aspect.originalValues)) {
1854
+ newAspect.originalValuesMap = aspect.originalValues;
1855
+ }
1856
+ result.complexAspect = newAspect;
1857
+ }
1858
+ return result;
1859
+ }
1860
+ function exportTempKeyInfo(entityAspect, tempKeys) {
1861
+ let entity = entityAspect.entity;
1862
+ if (entityAspect.hasTempKey) {
1863
+ tempKeys.push(entityAspect.getKey().toJSON());
1864
+ }
1865
+ // create map for this entity with foreignKeys that are 'temporary'
1866
+ // map -> key: tempKey, value: fkPropName
1867
+ let tempNavPropNames = [];
1868
+ entity.entityType.navigationProperties.forEach(function (np) {
1869
+ if (np.relatedDataProperties) {
1870
+ let relatedValue = entity.getProperty(np.name);
1871
+ if (relatedValue && relatedValue.entityAspect.hasTempKey) {
1872
+ tempNavPropNames.push(np.name);
1873
+ }
1874
+ }
1875
+ });
1876
+ return tempNavPropNames;
1877
+ }
1878
+ function importEntityGroup(entityGroup, jsonGroup, importConfig) {
1879
+ let tempKeyMap = importConfig.tempKeyMap;
1880
+ let mergeAdds = !!importConfig.mergeAdds;
1881
+ let entityType = entityGroup.entityType;
1882
+ let mergeStrategy = importConfig.mergeStrategy;
1883
+ let targetEntity;
1884
+ let em = entityGroup.entityManager;
1885
+ let entityChanged = em.entityChanged;
1886
+ let entitiesToLink = [];
1887
+ let rawValueFn = DataProperty.getRawValueFromClient;
1888
+ jsonGroup.entities.forEach(function (rawEntity) {
1889
+ let newAspect = rawEntity.entityAspect;
1890
+ let entityKey = entityType.getEntityKeyFromRawEntity(rawEntity, rawValueFn);
1891
+ let entityState = EntityState.fromName(newAspect.entityState);
1892
+ if (!entityState || entityState === EntityState.Detached) {
1893
+ throw new Error("Only entities with a non detached entity state may be imported.");
1894
+ }
1895
+ // Merge if raw entity is in cache UNLESS this is a new entity w/ a temp key
1896
+ // Cannot safely merge such entities even if could match temp key to an entity in cache.
1897
+ // Can enable merge of entities w/temp key using "mergeAdds" - use at your own risk!
1898
+ let newTempKey = !mergeAdds && entityState.isAdded() && getMappedKey(tempKeyMap, entityKey);
1899
+ targetEntity = newTempKey ? undefined : entityGroup.findEntityByKey(entityKey);
1900
+ if (targetEntity) {
1901
+ if (mergeStrategy === MergeStrategy.SkipMerge) {
1902
+ // deliberate fall thru
1903
+ }
1904
+ else if (mergeStrategy === MergeStrategy.Disallowed) {
1905
+ throw new Error("A MergeStrategy of 'Disallowed' prevents " + entityKey.toString() + " from being merged");
1906
+ }
1907
+ else {
1908
+ let targetEntityState = targetEntity.entityAspect.entityState;
1909
+ let wasUnchanged = targetEntityState.isUnchanged();
1910
+ if (mergeStrategy === MergeStrategy.OverwriteChanges || wasUnchanged) {
1911
+ entityType._updateTargetFromRaw(targetEntity, rawEntity, rawValueFn);
1912
+ targetEntity.entityAspect.setEntityState(entityState);
1913
+ entityChanged.publish({ entityAction: EntityAction.MergeOnImport, entity: targetEntity });
1914
+ }
1915
+ }
1916
+ }
1917
+ else {
1918
+ targetEntity = entityType._createInstanceCore();
1919
+ entityType._updateTargetFromRaw(targetEntity, rawEntity, rawValueFn);
1920
+ if (newTempKey) {
1921
+ targetEntity.entityAspect.hasTempKey = true;
1922
+ // fixup pk
1923
+ targetEntity.setProperty(entityType.keyProperties[0].name, newTempKey.values[0]);
1924
+ // fixup foreign keys
1925
+ // This is safe because the entity is detached here and therefore originalValues will not be updated.
1926
+ if (newAspect.tempNavPropNames) {
1927
+ newAspect.tempNavPropNames.forEach(function (npName) {
1928
+ let np = entityType.getNavigationProperty(npName);
1929
+ let fkPropName = np.relatedDataProperties[0].name;
1930
+ let oldFkValue = targetEntity.getProperty(fkPropName);
1931
+ let fk = new EntityKey(np.entityType, [oldFkValue]);
1932
+ let newFk = getMappedKey(tempKeyMap, fk);
1933
+ targetEntity.setProperty(fkPropName, newFk.values[0]);
1934
+ });
1935
+ }
1936
+ }
1937
+ // Now performed in attachEntity
1938
+ targetEntity = entityGroup.attachEntity(targetEntity, entityState);
1939
+ entityChanged.publish({ entityAction: EntityAction.AttachOnImport, entity: targetEntity });
1940
+ if (!entityState.isUnchanged()) {
1941
+ em._notifyStateChange(targetEntity, true);
1942
+ }
1943
+ }
1944
+ entitiesToLink.push(targetEntity);
1945
+ });
1946
+ return entitiesToLink;
1947
+ }
1948
+ function getMappedKey(tempKeyMap, entityKey) {
1949
+ let newKey = tempKeyMap[entityKey.toString()];
1950
+ if (newKey)
1951
+ return newKey;
1952
+ let subtypes = entityKey._subtypes;
1953
+ if (!subtypes)
1954
+ return null;
1955
+ for (let i = 0, j = subtypes.length; i < j; i++) {
1956
+ newKey = tempKeyMap[entityKey.toString(subtypes[i])];
1957
+ if (newKey)
1958
+ return newKey;
1959
+ }
1960
+ return null;
1961
+ }
1962
+ function promiseWithCallbacks(promise, callback, errorCallback) {
1963
+ promise = promise.then(function (data) {
1964
+ if (callback)
1965
+ callback(data);
1966
+ return Promise.resolve(data);
1967
+ }, function (error) {
1968
+ if (errorCallback)
1969
+ errorCallback(error);
1970
+ return Promise.reject(error);
1971
+ });
1972
+ return promise;
1973
+ }
1974
+ function getEntitiesToSave(em, entities) {
1975
+ let entitiesToSave;
1976
+ if (entities) {
1977
+ entitiesToSave = entities.filter(function (e) {
1978
+ if (e.entityAspect.entityManager !== em) {
1979
+ throw new Error("Only entities in this entityManager may be saved");
1980
+ }
1981
+ return !e.entityAspect.entityState.isDetached();
1982
+ });
1983
+ }
1984
+ else {
1985
+ entitiesToSave = em.getChanges();
1986
+ }
1987
+ return entitiesToSave;
1988
+ }
1989
+ function fixupKeys(em, keyMappings) {
1990
+ em._inKeyFixup = true;
1991
+ keyMappings.forEach(function (km) {
1992
+ let group = em._entityGroupMap.get(km.entityTypeName);
1993
+ if (!group) {
1994
+ throw new Error("Unable to locate the following fully qualified EntityType name: " + km.entityTypeName);
1995
+ }
1996
+ group._fixupKey(km.tempValue, km.realValue);
1997
+ });
1998
+ em._inKeyFixup = false;
1999
+ }
2000
+ function getEntityGroups(em, entityTypes) {
2001
+ let groupMap = em._entityGroupMap;
2002
+ if (entityTypes) {
2003
+ return core.toArray(entityTypes).map(function (et) {
2004
+ if (et instanceof EntityType) {
2005
+ return groupMap.get(et.name);
2006
+ }
2007
+ else {
2008
+ throw new Error("The EntityManager.getChanges() 'entityTypes' parameter must be either an entityType or an array of entityTypes or null");
2009
+ }
2010
+ });
2011
+ }
2012
+ else {
2013
+ return Array.from(groupMap.values());
2014
+ }
2015
+ }
2016
+ function checkEntityKey(em, entity) {
2017
+ let ek = entity.entityAspect.getKey();
2018
+ // return properties that are = to defaultValues
2019
+ let keyPropsWithDefaultValues = core.arrayZip(entity.entityType.keyProperties, ek.values, function (kp, kv) {
2020
+ return (kp.defaultValue === kv) ? kp : null;
2021
+ }).filter(function (kp) {
2022
+ return kp !== null;
2023
+ });
2024
+ if (keyPropsWithDefaultValues.length) {
2025
+ if (entity.entityType.autoGeneratedKeyType !== AutoGeneratedKeyType.None) {
2026
+ em.generateTempKeyValue(entity);
2027
+ }
2028
+ else {
2029
+ // we will allow attaches of entities where only part of the key is set.
2030
+ if (keyPropsWithDefaultValues.length === ek.values.length) {
2031
+ throw new Error("Cannot attach an object of type (" + entity.entityType.name + ") to an EntityManager without first setting its key or setting its entityType 'AutoGeneratedKeyType' property to something other than 'None'");
2032
+ }
2033
+ }
2034
+ }
2035
+ }
2036
+ function validateEntityStates(em, entityStates) {
2037
+ if (!entityStates)
2038
+ return [];
2039
+ let entStates = core.toArray(entityStates);
2040
+ entStates.forEach((es) => {
2041
+ if (!(es instanceof EntityState)) {
2042
+ throw new Error("The EntityManager.getChanges() 'entityStates' parameter must either be null, an entityState or an array of entityStates");
2043
+ }
2044
+ });
2045
+ return entStates;
2046
+ }
2047
+ function attachRelatedEntities(em, entity, entityState, mergeStrategy) {
2048
+ let navProps = entity.entityType.navigationProperties;
2049
+ navProps.forEach(function (np) {
2050
+ // A collection that has never been read has nothing to cascade to. Reading it would create
2051
+ // the array for every collection of every entity attached.
2052
+ let related = np.isScalar ? entity.getProperty(np.name) : peekProperty(entity, np.name);
2053
+ if (np.isScalar) {
2054
+ if (!related)
2055
+ return;
2056
+ em.attachEntity(related, entityState, mergeStrategy);
2057
+ }
2058
+ else {
2059
+ if (!related)
2060
+ return;
2061
+ related.forEach(function (e) {
2062
+ em.attachEntity(e, entityState, mergeStrategy);
2063
+ });
2064
+ }
2065
+ });
2066
+ }
2067
+ // returns a promise
2068
+ function executeQueryCore(em, query, queryOptions, dataService) {
2069
+ try {
2070
+ let results;
2071
+ let metadataStore = em.metadataStore;
2072
+ if (metadataStore.isEmpty() && dataService.hasServerMetadata) {
2073
+ throw new Error("cannot execute _executeQueryCore until metadataStore is populated.");
2074
+ }
2075
+ if (queryOptions.fetchStrategy === FetchStrategy.FromLocalCache) {
2076
+ try {
2077
+ if (typeof query === 'string') {
2078
+ throw new Error("cannot execute 'string' EntityQuery locally.");
2079
+ }
2080
+ let qr = executeQueryLocallyCore(em, query);
2081
+ return Promise.resolve({ results: qr.results, entityManager: em, inlineCount: qr.inlineCount, query: query });
2082
+ }
2083
+ catch (e) {
2084
+ return Promise.reject(e);
2085
+ }
2086
+ }
2087
+ let mappingContext = new MappingContext({
2088
+ query: query,
2089
+ entityManager: em,
2090
+ dataService: dataService,
2091
+ mergeOptions: {
2092
+ mergeStrategy: queryOptions.mergeStrategy,
2093
+ noTracking: !!query.noTrackingEnabled,
2094
+ includeDeleted: queryOptions.includeDeleted
2095
+ }
2096
+ });
2097
+ let validateOnQuery = em.validationOptions.validateOnQuery;
2098
+ return dataService.adapterInstance.executeQuery(mappingContext).then(function (data) {
2099
+ let result = core.wrapExecution(function () {
2100
+ let state = { isLoading: em.isLoading };
2101
+ em.isLoading = true;
2102
+ em._pendingPubs = [];
2103
+ return state;
2104
+ }, function (state) {
2105
+ // cleanup
2106
+ em.isLoading = state.isLoading;
2107
+ em._pendingPubs.forEach(function (fn) {
2108
+ fn();
2109
+ });
2110
+ em._pendingPubs = undefined;
2111
+ em._hasChangesAction && em._hasChangesAction();
2112
+ mappingContext = undefined;
2113
+ // A materialization error thrown below needs no help here: wrapExecution rethrows it,
2114
+ // which rejects this promise. This cleanup used to return Promise.reject(state.error)
2115
+ // as well; nothing received that second promise, so it was an unhandled rejection.
2116
+ }, function () {
2117
+ let nodes = dataService.jsonResultsAdapter.extractResults(data);
2118
+ nodes = core.toArray(nodes);
2119
+ results = mappingContext.visitAndMerge(nodes, { nodeType: "root" });
2120
+ if (validateOnQuery) {
2121
+ results.forEach(function (r) {
2122
+ // anon types and simple types will not have an entityAspect.
2123
+ r.entityAspect && r.entityAspect.validateEntity();
2124
+ });
2125
+ }
2126
+ mappingContext.processDeferred();
2127
+ // if query has expand clauses walk each of the 'results' and mark the expanded props as loaded.
2128
+ if (query instanceof EntityQuery) {
2129
+ markLoadedNavProps(results, query);
2130
+ }
2131
+ let retrievedEntities = core.objectMap(mappingContext.refMap);
2132
+ return { results: results, query: query, entityManager: em, httpResponse: data.httpResponse, inlineCount: data.inlineCount, retrievedEntities: retrievedEntities };
2133
+ });
2134
+ return Promise.resolve(result);
2135
+ }, function (e) {
2136
+ if (e) {
2137
+ e.query = query;
2138
+ e.entityManager = em;
2139
+ }
2140
+ return Promise.reject(e);
2141
+ });
2142
+ }
2143
+ catch (e) {
2144
+ if (e) {
2145
+ e.query = query;
2146
+ }
2147
+ return Promise.reject(e);
2148
+ }
2149
+ }
2150
+ function markLoadedNavProps(entities, query) {
2151
+ if (query.noTrackingEnabled)
2152
+ return;
2153
+ let expandClause = query.expandClause;
2154
+ if (expandClause == null)
2155
+ return;
2156
+ expandClause.propertyPaths.forEach(function (propertyPath) {
2157
+ let propNames = propertyPath.split('.');
2158
+ markLoadedNavPath(entities, propNames);
2159
+ });
2160
+ }
2161
+ function markLoadedNavPath(entities, propNames) {
2162
+ let propName = propNames[0];
2163
+ entities.forEach((entity) => {
2164
+ let ea = entity.entityAspect;
2165
+ if (!ea)
2166
+ return; // entity may not be a 'real' entity in the case of a projection.
2167
+ ea._markAsLoaded(propName);
2168
+ if (propNames.length === 1)
2169
+ return;
2170
+ let next = entity.getProperty(propName);
2171
+ if (!next)
2172
+ return; // no children to process.
2173
+ // strange logic because nonscalar nav values are NOT really arrays
2174
+ // otherwise we could use Array.isArray
2175
+ if (!next.arrayChanged)
2176
+ next = [next];
2177
+ markLoadedNavPath(next, propNames.slice(1));
2178
+ });
2179
+ }
2180
+ function updateConcurrencyProperties(entities) {
2181
+ let candidates = entities.filter((e) => {
2182
+ e.entityAspect.isBeingSaved = true;
2183
+ return e.entityAspect.entityState.isModified()
2184
+ && e.entityType.concurrencyProperties.length > 0;
2185
+ });
2186
+ if (candidates.length === 0)
2187
+ return;
2188
+ candidates.forEach(function (c) {
2189
+ c.entityType.concurrencyProperties.forEach(function (cp) {
2190
+ updateConcurrencyProperty(c, cp);
2191
+ });
2192
+ });
2193
+ }
2194
+ function updateConcurrencyProperty(entity, property) {
2195
+ // check if property has already been updated
2196
+ if (entity.entityAspect.originalValues[property.name])
2197
+ return;
2198
+ let value = entity.getProperty(property.name);
2199
+ let dataType = property.dataType;
2200
+ if (!value)
2201
+ value = dataType.defaultValue;
2202
+ if (dataType.isNumeric) {
2203
+ entity.setProperty(property.name, value + 1);
2204
+ }
2205
+ else if (dataType.getConcurrencyValue) {
2206
+ // DataType has its own implementation
2207
+ let nextValue = dataType.getConcurrencyValue(value);
2208
+ entity.setProperty(property.name, nextValue);
2209
+ }
2210
+ else if (dataType === DataType.Binary) {
2211
+ // best guess - that this is a timestamp column and is computed on the server during save
2212
+ // - so no need to set it here.
2213
+ return;
2214
+ }
2215
+ else {
2216
+ // this just leaves DataTypes of Boolean, String and Byte - none of which should be the
2217
+ // type for a concurrency column.
2218
+ // NOTE: thought about just returning here but would rather be safe for now.
2219
+ throw new Error("Unable to update the value of concurrency property before saving: " + property.name);
2220
+ }
2221
+ }
2222
+ function findOrCreateEntityGroup(em, entityType) {
2223
+ let group = em._entityGroupMap.get(entityType.name);
2224
+ if (!group) {
2225
+ group = new EntityGroup(em, entityType);
2226
+ em._entityGroupMap.set(entityType.name, group);
2227
+ }
2228
+ return group;
2229
+ }
2230
+ function findOrCreateEntityGroups(em, entityType) {
2231
+ let entityTypes = entityType.getSelfAndSubtypes();
2232
+ return entityTypes.map((et) => {
2233
+ return findOrCreateEntityGroup(em, et);
2234
+ });
2235
+ }
2236
+ function unwrapInstance(structObj, transformFn) {
2237
+ let rawObject = {};
2238
+ let stype = EntityAspect.isEntity(structObj) ? structObj.entityType : structObj.complexType;
2239
+ let serializerFn = getSerializerFn(stype);
2240
+ let unmapped = {};
2241
+ stype.dataProperties.forEach(function (dp) {
2242
+ if (dp.isComplexProperty) {
2243
+ rawObject[dp.nameOnServer] = core.map(structObj.getProperty(dp.name), function (co) {
2244
+ return unwrapInstance(co, transformFn);
2245
+ });
2246
+ }
2247
+ else {
2248
+ let val = structObj.getProperty(dp.name);
2249
+ val = transformFn ? transformFn(dp, val) : val;
2250
+ if (val === undefined)
2251
+ return;
2252
+ val = serializerFn ? serializerFn(dp, val) : val;
2253
+ if (val !== undefined) {
2254
+ if (dp.isUnmapped) {
2255
+ unmapped[dp.nameOnServer] = core.toJSONSafe(val, core.toJSONSafeReplacer);
2256
+ }
2257
+ else {
2258
+ rawObject[dp.nameOnServer] = val;
2259
+ }
2260
+ }
2261
+ }
2262
+ });
2263
+ if (!core.isEmpty(unmapped)) {
2264
+ // TODO: review this.
2265
+ rawObject.__unmapped = unmapped;
2266
+ }
2267
+ return rawObject;
2268
+ }
2269
+ function unwrapOriginalValues(target, metadataStore, transformFn) {
2270
+ let stype = EntityAspect.isEntity(target) ? target.entityType : target.complexType;
2271
+ let aspect = EntityAspect.isEntity(target) ? target.entityAspect : target.complexAspect;
2272
+ let fn = metadataStore.namingConvention.clientPropertyNameToServer;
2273
+ let result = {};
2274
+ core.objectForEach(aspect.originalValues, function (propName, val) {
2275
+ let prop = stype.getProperty(propName);
2276
+ val = transformFn ? transformFn(prop, val) : val;
2277
+ if (val !== undefined) {
2278
+ result[fn(propName, prop)] = val;
2279
+ }
2280
+ });
2281
+ stype.complexProperties.forEach(function (cp) {
2282
+ let nextTarget = target.getProperty(cp.name);
2283
+ if (cp.isScalar) {
2284
+ let unwrappedCo = unwrapOriginalValues(nextTarget, metadataStore, transformFn);
2285
+ if (!core.isEmpty(unwrappedCo)) {
2286
+ result[fn(cp.name, cp)] = unwrappedCo;
2287
+ }
2288
+ }
2289
+ else {
2290
+ let unwrappedCos = nextTarget.map((item) => {
2291
+ return unwrapOriginalValues(item, metadataStore, transformFn);
2292
+ });
2293
+ result[fn(cp.name, cp)] = unwrappedCos;
2294
+ }
2295
+ });
2296
+ return result;
2297
+ }
2298
+ function unwrapChangedValues(entity, metadataStore, transformFn) {
2299
+ let stype = entity.entityType;
2300
+ let serializerFn = getSerializerFn(stype);
2301
+ let fn = metadataStore.namingConvention.clientPropertyNameToServer;
2302
+ let result = {};
2303
+ core.objectForEach(entity.entityAspect.originalValues, function (propName, value) {
2304
+ let prop = stype.getProperty(propName);
2305
+ let val = entity.getProperty(propName);
2306
+ val = transformFn ? transformFn(prop, val) : val;
2307
+ if (val === undefined)
2308
+ return;
2309
+ val = serializerFn ? serializerFn(prop, val) : val;
2310
+ if (val !== undefined) {
2311
+ result[fn(propName, prop)] = val;
2312
+ }
2313
+ });
2314
+ // any change to any complex object or array of complex objects returns the ENTIRE
2315
+ // current complex object or complex object array. This is by design. Complex Objects
2316
+ // are atomic.
2317
+ stype.complexProperties.forEach((cp) => {
2318
+ if (cpHasOriginalValues(entity, cp)) {
2319
+ let coOrCos = entity.getProperty(cp.name);
2320
+ result[fn(cp.name, cp)] = core.map(coOrCos, function (co) {
2321
+ return unwrapInstance(co, transformFn);
2322
+ });
2323
+ }
2324
+ });
2325
+ return result;
2326
+ }
2327
+ function cpHasOriginalValues(structuralObject, cp) {
2328
+ let coOrCos = structuralObject.getProperty(cp.name);
2329
+ if (cp.isScalar) {
2330
+ return coHasOriginalValues(coOrCos);
2331
+ }
2332
+ else {
2333
+ // this occurs when a nonscalar co array has had cos added or removed.
2334
+ if (observableArray.hasOriginalValues(coOrCos))
2335
+ return true;
2336
+ return coOrCos.some(function (co) {
2337
+ return coHasOriginalValues(co);
2338
+ });
2339
+ }
2340
+ }
2341
+ function executeQueryLocallyCore(em, query) {
2342
+ assertParam(query, "query").isInstanceOf(EntityQuery).check();
2343
+ let metadataStore = em.metadataStore;
2344
+ let entityType = query._getFromEntityType(metadataStore, true);
2345
+ // there may be multiple groups is this is a base entity type.
2346
+ let groups = findOrCreateEntityGroups(em, entityType);
2347
+ // filter then order then skip then take
2348
+ let filterFunc = query.wherePredicate && query.wherePredicate.toFunction({ entityType: entityType });
2349
+ let queryOptions = QueryOptions.resolve([query.queryOptions, em.queryOptions, QueryOptions.defaultInstance]);
2350
+ let includeDeleted = queryOptions.includeDeleted === true;
2351
+ let newFilterFunc = function (entity) {
2352
+ return entity && (includeDeleted || !entity.entityAspect.entityState.isDeleted()) && (filterFunc ? filterFunc(entity) : true);
2353
+ };
2354
+ let result = [];
2355
+ // TODO: mapMany
2356
+ groups.forEach((group) => {
2357
+ let entities = group._entities.filter(newFilterFunc);
2358
+ if (entities.length) {
2359
+ result = result.length ? result.concat(entities) : entities;
2360
+ }
2361
+ });
2362
+ let orderByComparer = query.orderByClause && query.orderByClause.getComparer(entityType);
2363
+ if (orderByComparer) {
2364
+ result.sort(orderByComparer);
2365
+ }
2366
+ let inlineCount = query.inlineCountEnabled ? result.length : undefined;
2367
+ let skipCount = query.skipCount;
2368
+ if (skipCount) {
2369
+ result = result.slice(skipCount);
2370
+ }
2371
+ let takeCount = query.takeCount;
2372
+ if (takeCount) {
2373
+ result = result.slice(0, takeCount);
2374
+ }
2375
+ let selectClause = query.selectClause;
2376
+ if (selectClause) {
2377
+ // named as a remote query's results are named
2378
+ let selectFn = selectClause.toFunction({ entityType: entityType });
2379
+ result = result.map(selectFn);
2380
+ }
2381
+ return { results: result, inlineCount: inlineCount };
2382
+ }
2383
+ function coHasOriginalValues(co) {
2384
+ // next line checks all non complex properties of the co.
2385
+ if (!core.isEmpty(co.complexAspect.originalValues))
2386
+ return true;
2387
+ // now need to recursively check each of the cps
2388
+ return co.complexType.complexProperties.some(function (cp) {
2389
+ return cpHasOriginalValues(co, cp);
2390
+ });
2391
+ }
2392
+ function getSerializerFn(stype) {
2393
+ return stype.serializerFn || (stype.metadataStore && stype.metadataStore.serializerFn);
2394
+ }
2395
+ //# sourceMappingURL=entity-manager.js.map