@warp-drive/legacy 5.9.0-beta.0 → 5.9.0-beta.2

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 (468) hide show
  1. package/README.md +6 -0
  2. package/dist/-private-DQ6Iap2t.js +193 -0
  3. package/dist/-private-DQ6Iap2t.js.map +1 -0
  4. package/dist/-private-DccRZQsm.js +904 -0
  5. package/dist/-private-DccRZQsm.js.map +1 -0
  6. package/dist/adapter/-private.d.ts +33 -0
  7. package/dist/adapter/-private.d.ts.map +1 -0
  8. package/dist/adapter/-private.js +3 -1
  9. package/dist/adapter/error.d.ts +2 -0
  10. package/dist/adapter/error.js +425 -311
  11. package/dist/adapter/error.js.map +1 -0
  12. package/{declarations → dist}/adapter/json-api.d.ts +31 -19
  13. package/dist/adapter/json-api.d.ts.map +1 -0
  14. package/dist/adapter/json-api.js +265 -131
  15. package/dist/adapter/json-api.js.map +1 -0
  16. package/dist/adapter/rest.d.ts +2 -0
  17. package/dist/adapter/rest.js +937 -1100
  18. package/dist/adapter/rest.js.map +1 -0
  19. package/dist/adapter-CARrK3-8.d.ts +784 -0
  20. package/dist/adapter-CARrK3-8.d.ts.map +1 -0
  21. package/dist/adapter-eYo2pIuM.js +1130 -0
  22. package/dist/adapter-eYo2pIuM.js.map +1 -0
  23. package/dist/adapter.d.ts +2 -0
  24. package/dist/adapter.js +1 -1251
  25. package/dist/compat/-private.d.ts +2 -0
  26. package/dist/compat/-private.js +3 -1
  27. package/dist/compat/builders.d.ts +169 -0
  28. package/dist/compat/builders.d.ts.map +1 -0
  29. package/dist/compat/builders.js +205 -246
  30. package/dist/compat/builders.js.map +1 -0
  31. package/dist/compat/extensions.d.ts +2 -0
  32. package/dist/compat/extensions.js +271 -233
  33. package/dist/compat/extensions.js.map +1 -0
  34. package/dist/compat/utils.d.ts +151 -0
  35. package/dist/compat/utils.d.ts.map +1 -0
  36. package/dist/compat/utils.js +189 -194
  37. package/dist/compat/utils.js.map +1 -0
  38. package/dist/compat-BbNNmTM-.d.ts +1386 -0
  39. package/dist/compat-BbNNmTM-.d.ts.map +1 -0
  40. package/dist/compat-DcHVxuuZ.js +734 -0
  41. package/dist/compat-DcHVxuuZ.js.map +1 -0
  42. package/dist/compat.d.ts +2 -0
  43. package/dist/compat.js +1 -1019
  44. package/dist/error-CzkyXr1Q.d.ts +435 -0
  45. package/dist/error-CzkyXr1Q.d.ts.map +1 -0
  46. package/dist/errors-BEEsrHbl.js +2134 -0
  47. package/dist/errors-BEEsrHbl.js.map +1 -0
  48. package/dist/extensions-DumNm4dA.d.ts +102 -0
  49. package/dist/extensions-DumNm4dA.d.ts.map +1 -0
  50. package/dist/index.d.ts +243 -0
  51. package/dist/index.d.ts.map +1 -0
  52. package/dist/index.js +271 -188
  53. package/dist/index.js.map +1 -0
  54. package/dist/json-BXNPTlcH.js +1106 -0
  55. package/dist/json-BXNPTlcH.js.map +1 -0
  56. package/dist/model/-private.d.ts +3 -0
  57. package/dist/model/-private.js +3 -1
  58. package/dist/model/migration-support.d.ts +335 -0
  59. package/dist/model/migration-support.d.ts.map +1 -0
  60. package/dist/model/migration-support.js +506 -564
  61. package/dist/model/migration-support.js.map +1 -0
  62. package/dist/model-62hn5_PD.d.ts +3107 -0
  63. package/dist/model-62hn5_PD.d.ts.map +1 -0
  64. package/dist/model-DcXZdNMu.js +683 -0
  65. package/dist/model-DcXZdNMu.js.map +1 -0
  66. package/dist/model-fragments-DSqu0ptR.js +334 -0
  67. package/dist/model-fragments-DSqu0ptR.js.map +1 -0
  68. package/dist/model-fragments.d.ts +294 -0
  69. package/dist/model-fragments.d.ts.map +1 -0
  70. package/dist/model-fragments.js +2 -75
  71. package/dist/model.d.ts +404 -0
  72. package/dist/model.d.ts.map +1 -0
  73. package/dist/model.js +3 -666
  74. package/{declarations/adapter/rest.d.ts → dist/rest-0NhtexIq.d.ts} +187 -103
  75. package/dist/rest-0NhtexIq.d.ts.map +1 -0
  76. package/dist/runtime--fcdnjmJ-DMTJ0Kb3.js +53 -0
  77. package/dist/runtime--fcdnjmJ-DMTJ0Kb3.js.map +1 -0
  78. package/dist/schema-provider-H4zNXtry.js +1929 -0
  79. package/dist/schema-provider-H4zNXtry.js.map +1 -0
  80. package/{declarations → dist}/serializer/json-api.d.ts +4 -1
  81. package/dist/serializer/json-api.d.ts.map +1 -0
  82. package/dist/serializer/json-api.js +527 -514
  83. package/dist/serializer/json-api.js.map +1 -0
  84. package/{declarations → dist}/serializer/json.d.ts +3 -0
  85. package/dist/serializer/json.d.ts.map +1 -0
  86. package/dist/serializer/json.js +3 -6
  87. package/{declarations/serializer/-private/embedded-records-mixin.d.ts → dist/serializer/rest.d.ts} +56 -1
  88. package/dist/serializer/rest.d.ts.map +1 -0
  89. package/dist/serializer/rest.js +958 -1200
  90. package/dist/serializer/rest.js.map +1 -0
  91. package/dist/serializer/transform.d.ts +313 -0
  92. package/dist/serializer/transform.d.ts.map +1 -0
  93. package/dist/serializer/transform.js +283 -260
  94. package/dist/serializer/transform.js.map +1 -0
  95. package/dist/serializer.d.ts +151 -0
  96. package/dist/serializer.d.ts.map +1 -0
  97. package/dist/serializer.js +205 -208
  98. package/dist/serializer.js.map +1 -0
  99. package/dist/store-C4qYzXei.js +473 -0
  100. package/dist/store-C4qYzXei.js.map +1 -0
  101. package/dist/store.d.ts +13 -0
  102. package/dist/store.d.ts.map +1 -0
  103. package/dist/store.js +1 -635
  104. package/dist/unpkg/dev/-private-CrEyBE-B.js +189 -0
  105. package/dist/unpkg/dev/-private-CrEyBE-B.js.map +1 -0
  106. package/dist/unpkg/dev/-private-vOhxVExH.js +896 -0
  107. package/dist/unpkg/dev/-private-vOhxVExH.js.map +1 -0
  108. package/dist/unpkg/dev/adapter/-private.js +3 -1
  109. package/dist/unpkg/dev/adapter/error.js +424 -310
  110. package/dist/unpkg/dev/adapter/error.js.map +1 -0
  111. package/dist/unpkg/dev/adapter/json-api.js +239 -245
  112. package/dist/unpkg/dev/adapter/json-api.js.map +1 -0
  113. package/dist/unpkg/dev/adapter/rest.js +935 -1098
  114. package/dist/unpkg/dev/adapter/rest.js.map +1 -0
  115. package/dist/unpkg/dev/adapter-oLwyr47q.js +1129 -0
  116. package/dist/unpkg/dev/adapter-oLwyr47q.js.map +1 -0
  117. package/dist/unpkg/dev/adapter.js +1 -1250
  118. package/dist/unpkg/dev/compat/-private.js +3 -1
  119. package/dist/unpkg/dev/compat/builders.js +204 -248
  120. package/dist/unpkg/dev/compat/builders.js.map +1 -0
  121. package/dist/unpkg/dev/compat/extensions.js +270 -232
  122. package/dist/unpkg/dev/compat/extensions.js.map +1 -0
  123. package/dist/unpkg/dev/compat/utils.js +188 -193
  124. package/dist/unpkg/dev/compat/utils.js.map +1 -0
  125. package/dist/unpkg/dev/compat-D48B8sXv.js +825 -0
  126. package/dist/unpkg/dev/compat-D48B8sXv.js.map +1 -0
  127. package/dist/unpkg/dev/compat.js +1 -1145
  128. package/dist/unpkg/dev/errors-8GnRWcxo.js +2127 -0
  129. package/dist/unpkg/dev/errors-8GnRWcxo.js.map +1 -0
  130. package/dist/unpkg/dev/index.js +270 -190
  131. package/dist/unpkg/dev/index.js.map +1 -0
  132. package/dist/unpkg/dev/json-DDJji3V3.js +1104 -0
  133. package/dist/unpkg/dev/json-DDJji3V3.js.map +1 -0
  134. package/dist/unpkg/dev/model/-private.js +3 -1
  135. package/dist/unpkg/dev/model/migration-support.js +483 -537
  136. package/dist/unpkg/dev/model/migration-support.js.map +1 -0
  137. package/dist/unpkg/dev/model-LK7ethC5.js +655 -0
  138. package/dist/unpkg/dev/model-LK7ethC5.js.map +1 -0
  139. package/dist/unpkg/dev/model-fragments-DSqu0ptR.js +334 -0
  140. package/dist/unpkg/dev/model-fragments-DSqu0ptR.js.map +1 -0
  141. package/dist/unpkg/dev/model-fragments.js +2 -75
  142. package/dist/unpkg/dev/model.js +3 -677
  143. package/dist/unpkg/dev/runtime--fcdnjmJ-DMTJ0Kb3.js +53 -0
  144. package/dist/unpkg/dev/runtime--fcdnjmJ-DMTJ0Kb3.js.map +1 -0
  145. package/dist/unpkg/dev/schema-provider-CRzoMoTO.js +1834 -0
  146. package/dist/unpkg/dev/schema-provider-CRzoMoTO.js.map +1 -0
  147. package/dist/unpkg/dev/serializer/json-api.js +514 -629
  148. package/dist/unpkg/dev/serializer/json-api.js.map +1 -0
  149. package/dist/unpkg/dev/serializer/json.js +3 -4
  150. package/dist/unpkg/dev/serializer/rest.js +954 -1197
  151. package/dist/unpkg/dev/serializer/rest.js.map +1 -0
  152. package/dist/unpkg/dev/serializer/transform.js +283 -260
  153. package/dist/unpkg/dev/serializer/transform.js.map +1 -0
  154. package/dist/unpkg/dev/serializer.js +205 -208
  155. package/dist/unpkg/dev/serializer.js.map +1 -0
  156. package/dist/unpkg/dev/store-D_V8-HQl.js +472 -0
  157. package/dist/unpkg/dev/store-D_V8-HQl.js.map +1 -0
  158. package/dist/unpkg/dev/store.js +1 -635
  159. package/dist/unpkg/dev/util-dSKEgQDp.js +12 -0
  160. package/dist/unpkg/dev/util-dSKEgQDp.js.map +1 -0
  161. package/dist/unpkg/dev/utils-DYC9utVJ.js +11 -0
  162. package/dist/unpkg/dev/utils-DYC9utVJ.js.map +1 -0
  163. package/dist/unpkg/dev-deprecated/-private-CrEyBE-B.js +189 -0
  164. package/dist/unpkg/dev-deprecated/-private-CrEyBE-B.js.map +1 -0
  165. package/dist/unpkg/dev-deprecated/-private-vOhxVExH.js +896 -0
  166. package/dist/unpkg/dev-deprecated/-private-vOhxVExH.js.map +1 -0
  167. package/dist/unpkg/dev-deprecated/adapter/-private.js +3 -1
  168. package/dist/unpkg/dev-deprecated/adapter/error.js +424 -310
  169. package/dist/unpkg/dev-deprecated/adapter/error.js.map +1 -0
  170. package/dist/unpkg/dev-deprecated/adapter/json-api.js +239 -245
  171. package/dist/unpkg/dev-deprecated/adapter/json-api.js.map +1 -0
  172. package/dist/unpkg/dev-deprecated/adapter/rest.js +935 -1098
  173. package/dist/unpkg/dev-deprecated/adapter/rest.js.map +1 -0
  174. package/dist/unpkg/dev-deprecated/adapter-oLwyr47q.js +1129 -0
  175. package/dist/unpkg/dev-deprecated/adapter-oLwyr47q.js.map +1 -0
  176. package/dist/unpkg/dev-deprecated/adapter.js +1 -1250
  177. package/dist/unpkg/dev-deprecated/compat/-private.js +3 -1
  178. package/dist/unpkg/dev-deprecated/compat/builders.js +204 -248
  179. package/dist/unpkg/dev-deprecated/compat/builders.js.map +1 -0
  180. package/dist/unpkg/dev-deprecated/compat/extensions.js +270 -232
  181. package/dist/unpkg/dev-deprecated/compat/extensions.js.map +1 -0
  182. package/dist/unpkg/dev-deprecated/compat/utils.js +188 -193
  183. package/dist/unpkg/dev-deprecated/compat/utils.js.map +1 -0
  184. package/dist/unpkg/dev-deprecated/compat-DGSurLh7.js +825 -0
  185. package/dist/unpkg/dev-deprecated/compat-DGSurLh7.js.map +1 -0
  186. package/dist/unpkg/dev-deprecated/compat.js +1 -1145
  187. package/dist/unpkg/dev-deprecated/errors-0ydn94s0.js +2128 -0
  188. package/dist/unpkg/dev-deprecated/errors-0ydn94s0.js.map +1 -0
  189. package/dist/unpkg/dev-deprecated/index.js +270 -189
  190. package/dist/unpkg/dev-deprecated/index.js.map +1 -0
  191. package/dist/unpkg/dev-deprecated/json-DDJji3V3.js +1104 -0
  192. package/dist/unpkg/dev-deprecated/json-DDJji3V3.js.map +1 -0
  193. package/dist/unpkg/dev-deprecated/model/-private.js +3 -1
  194. package/dist/unpkg/dev-deprecated/model/migration-support.js +494 -554
  195. package/dist/unpkg/dev-deprecated/model/migration-support.js.map +1 -0
  196. package/dist/unpkg/dev-deprecated/model-C1ts6Mod.js +660 -0
  197. package/dist/unpkg/dev-deprecated/model-C1ts6Mod.js.map +1 -0
  198. package/dist/unpkg/dev-deprecated/model-fragments-DSqu0ptR.js +334 -0
  199. package/dist/unpkg/dev-deprecated/model-fragments-DSqu0ptR.js.map +1 -0
  200. package/dist/unpkg/dev-deprecated/model-fragments.js +2 -75
  201. package/dist/unpkg/dev-deprecated/model.js +3 -681
  202. package/dist/unpkg/dev-deprecated/runtime--fcdnjmJ-DMTJ0Kb3.js +53 -0
  203. package/dist/unpkg/dev-deprecated/runtime--fcdnjmJ-DMTJ0Kb3.js.map +1 -0
  204. package/dist/unpkg/dev-deprecated/schema-provider-D2ESMsA8.js +1835 -0
  205. package/dist/unpkg/dev-deprecated/schema-provider-D2ESMsA8.js.map +1 -0
  206. package/dist/unpkg/dev-deprecated/serializer/json-api.js +514 -629
  207. package/dist/unpkg/dev-deprecated/serializer/json-api.js.map +1 -0
  208. package/dist/unpkg/dev-deprecated/serializer/json.js +3 -4
  209. package/dist/unpkg/dev-deprecated/serializer/rest.js +954 -1197
  210. package/dist/unpkg/dev-deprecated/serializer/rest.js.map +1 -0
  211. package/dist/unpkg/dev-deprecated/serializer/transform.js +283 -260
  212. package/dist/unpkg/dev-deprecated/serializer/transform.js.map +1 -0
  213. package/dist/unpkg/dev-deprecated/serializer.js +205 -208
  214. package/dist/unpkg/dev-deprecated/serializer.js.map +1 -0
  215. package/dist/unpkg/dev-deprecated/store-BX7GvXC_.js +472 -0
  216. package/dist/unpkg/dev-deprecated/store-BX7GvXC_.js.map +1 -0
  217. package/dist/unpkg/dev-deprecated/store.js +1 -635
  218. package/dist/unpkg/dev-deprecated/util-9mgEBJ3W.js +18 -0
  219. package/dist/unpkg/dev-deprecated/util-9mgEBJ3W.js.map +1 -0
  220. package/dist/unpkg/dev-deprecated/utils-Cl86-e7F.js +17 -0
  221. package/dist/unpkg/dev-deprecated/utils-Cl86-e7F.js.map +1 -0
  222. package/dist/unpkg/prod/-private-B4bxoTuK.js +160 -0
  223. package/dist/unpkg/prod/-private-B4bxoTuK.js.map +1 -0
  224. package/dist/unpkg/prod/-private-SfXkkHKd.js +745 -0
  225. package/dist/unpkg/prod/-private-SfXkkHKd.js.map +1 -0
  226. package/dist/unpkg/prod/adapter/-private.js +3 -1
  227. package/dist/unpkg/prod/adapter/error.js +421 -305
  228. package/dist/unpkg/prod/adapter/error.js.map +1 -0
  229. package/dist/unpkg/prod/adapter/json-api.js +236 -240
  230. package/dist/unpkg/prod/adapter/json-api.js.map +1 -0
  231. package/dist/unpkg/prod/adapter/rest.js +911 -1061
  232. package/dist/unpkg/prod/adapter/rest.js.map +1 -0
  233. package/dist/unpkg/prod/adapter-DQ9UA7FC.js +1111 -0
  234. package/dist/unpkg/prod/adapter-DQ9UA7FC.js.map +1 -0
  235. package/dist/unpkg/prod/adapter.js +1 -1217
  236. package/dist/unpkg/prod/compat/-private.js +3 -1
  237. package/dist/unpkg/prod/compat/builders.js +165 -183
  238. package/dist/unpkg/prod/compat/builders.js.map +1 -0
  239. package/dist/unpkg/prod/compat/extensions.js +258 -222
  240. package/dist/unpkg/prod/compat/extensions.js.map +1 -0
  241. package/dist/unpkg/prod/compat/utils.js +185 -188
  242. package/dist/unpkg/prod/compat/utils.js.map +1 -0
  243. package/dist/unpkg/prod/compat-DxiVkCUb.js +547 -0
  244. package/dist/unpkg/prod/compat-DxiVkCUb.js.map +1 -0
  245. package/dist/unpkg/prod/compat.js +1 -725
  246. package/dist/unpkg/prod/errors-CVXWrUjP.js +1977 -0
  247. package/dist/unpkg/prod/errors-CVXWrUjP.js.map +1 -0
  248. package/dist/unpkg/prod/index.js +249 -146
  249. package/dist/unpkg/prod/index.js.map +1 -0
  250. package/dist/unpkg/prod/json-BD1kRTfB.js +1080 -0
  251. package/dist/unpkg/prod/json-BD1kRTfB.js.map +1 -0
  252. package/dist/unpkg/prod/model/-private.js +3 -1
  253. package/dist/unpkg/prod/model/migration-support.js +479 -530
  254. package/dist/unpkg/prod/model/migration-support.js.map +1 -0
  255. package/dist/unpkg/prod/model-D3WMsNNE.js +603 -0
  256. package/dist/unpkg/prod/model-D3WMsNNE.js.map +1 -0
  257. package/dist/unpkg/prod/model-fragments-DSqu0ptR.js +334 -0
  258. package/dist/unpkg/prod/model-fragments-DSqu0ptR.js.map +1 -0
  259. package/dist/unpkg/prod/model-fragments.js +2 -75
  260. package/dist/unpkg/prod/model.js +3 -592
  261. package/dist/unpkg/prod/runtime--fcdnjmJ-DMTJ0Kb3.js +53 -0
  262. package/dist/unpkg/prod/runtime--fcdnjmJ-DMTJ0Kb3.js.map +1 -0
  263. package/dist/unpkg/prod/schema-provider-_pimTZ3P.js +1622 -0
  264. package/dist/unpkg/prod/schema-provider-_pimTZ3P.js.map +1 -0
  265. package/dist/unpkg/prod/serializer/json-api.js +497 -587
  266. package/dist/unpkg/prod/serializer/json-api.js.map +1 -0
  267. package/dist/unpkg/prod/serializer/json.js +3 -4
  268. package/dist/unpkg/prod/serializer/rest.js +938 -1167
  269. package/dist/unpkg/prod/serializer/rest.js.map +1 -0
  270. package/dist/unpkg/prod/serializer/transform.js +283 -260
  271. package/dist/unpkg/prod/serializer/transform.js.map +1 -0
  272. package/dist/unpkg/prod/serializer.js +205 -208
  273. package/dist/unpkg/prod/serializer.js.map +1 -0
  274. package/dist/unpkg/prod/store-RGGc1ilN.js +392 -0
  275. package/dist/unpkg/prod/store-RGGc1ilN.js.map +1 -0
  276. package/dist/unpkg/prod/store.js +1 -503
  277. package/dist/unpkg/prod/util-dSKEgQDp.js +12 -0
  278. package/dist/unpkg/prod/util-dSKEgQDp.js.map +1 -0
  279. package/dist/unpkg/prod/utils-DYC9utVJ.js +11 -0
  280. package/dist/unpkg/prod/utils-DYC9utVJ.js.map +1 -0
  281. package/dist/unpkg/prod-deprecated/-private-B4bxoTuK.js +160 -0
  282. package/dist/unpkg/prod-deprecated/-private-B4bxoTuK.js.map +1 -0
  283. package/dist/unpkg/prod-deprecated/-private-SfXkkHKd.js +745 -0
  284. package/dist/unpkg/prod-deprecated/-private-SfXkkHKd.js.map +1 -0
  285. package/dist/unpkg/prod-deprecated/adapter/-private.js +3 -1
  286. package/dist/unpkg/prod-deprecated/adapter/error.js +421 -305
  287. package/dist/unpkg/prod-deprecated/adapter/error.js.map +1 -0
  288. package/dist/unpkg/prod-deprecated/adapter/json-api.js +236 -240
  289. package/dist/unpkg/prod-deprecated/adapter/json-api.js.map +1 -0
  290. package/dist/unpkg/prod-deprecated/adapter/rest.js +911 -1061
  291. package/dist/unpkg/prod-deprecated/adapter/rest.js.map +1 -0
  292. package/{declarations/adapter.d.ts → dist/unpkg/prod-deprecated/adapter-DQ9UA7FC.js} +451 -110
  293. package/dist/unpkg/prod-deprecated/adapter-DQ9UA7FC.js.map +1 -0
  294. package/dist/unpkg/prod-deprecated/adapter.js +1 -1217
  295. package/dist/unpkg/prod-deprecated/compat/-private.js +3 -1
  296. package/dist/unpkg/prod-deprecated/compat/builders.js +165 -183
  297. package/dist/unpkg/prod-deprecated/compat/builders.js.map +1 -0
  298. package/dist/unpkg/prod-deprecated/compat/extensions.js +258 -222
  299. package/dist/unpkg/prod-deprecated/compat/extensions.js.map +1 -0
  300. package/dist/unpkg/prod-deprecated/compat/utils.js +185 -188
  301. package/dist/unpkg/prod-deprecated/compat/utils.js.map +1 -0
  302. package/dist/unpkg/prod-deprecated/compat-DxiVkCUb.js +547 -0
  303. package/dist/unpkg/prod-deprecated/compat-DxiVkCUb.js.map +1 -0
  304. package/dist/unpkg/prod-deprecated/compat.js +1 -725
  305. package/dist/unpkg/prod-deprecated/errors-9LXqpfRd.js +1978 -0
  306. package/dist/unpkg/prod-deprecated/errors-9LXqpfRd.js.map +1 -0
  307. package/dist/unpkg/prod-deprecated/index.js +249 -145
  308. package/dist/unpkg/prod-deprecated/index.js.map +1 -0
  309. package/dist/unpkg/prod-deprecated/json-BD1kRTfB.js +1080 -0
  310. package/dist/unpkg/prod-deprecated/json-BD1kRTfB.js.map +1 -0
  311. package/dist/unpkg/prod-deprecated/model/-private.js +3 -1
  312. package/dist/unpkg/prod-deprecated/model/migration-support.js +490 -547
  313. package/dist/unpkg/prod-deprecated/model/migration-support.js.map +1 -0
  314. package/dist/unpkg/prod-deprecated/model-aiVrr1fz.js +604 -0
  315. package/dist/unpkg/prod-deprecated/model-aiVrr1fz.js.map +1 -0
  316. package/dist/unpkg/prod-deprecated/model-fragments-DSqu0ptR.js +334 -0
  317. package/dist/unpkg/prod-deprecated/model-fragments-DSqu0ptR.js.map +1 -0
  318. package/dist/unpkg/prod-deprecated/model-fragments.js +2 -75
  319. package/dist/unpkg/prod-deprecated/model.js +3 -595
  320. package/dist/unpkg/prod-deprecated/runtime--fcdnjmJ-DMTJ0Kb3.js +53 -0
  321. package/dist/unpkg/prod-deprecated/runtime--fcdnjmJ-DMTJ0Kb3.js.map +1 -0
  322. package/dist/unpkg/prod-deprecated/schema-provider-DyfSd9Cv.js +1635 -0
  323. package/dist/unpkg/prod-deprecated/schema-provider-DyfSd9Cv.js.map +1 -0
  324. package/dist/unpkg/prod-deprecated/serializer/json-api.js +497 -587
  325. package/dist/unpkg/prod-deprecated/serializer/json-api.js.map +1 -0
  326. package/dist/unpkg/prod-deprecated/serializer/json.js +3 -4
  327. package/dist/unpkg/prod-deprecated/serializer/rest.js +938 -1167
  328. package/dist/unpkg/prod-deprecated/serializer/rest.js.map +1 -0
  329. package/dist/unpkg/prod-deprecated/serializer/transform.js +283 -260
  330. package/dist/unpkg/prod-deprecated/serializer/transform.js.map +1 -0
  331. package/dist/unpkg/prod-deprecated/serializer.js +205 -208
  332. package/dist/unpkg/prod-deprecated/serializer.js.map +1 -0
  333. package/dist/unpkg/prod-deprecated/store-0L2CkYzh.js +392 -0
  334. package/dist/unpkg/prod-deprecated/store-0L2CkYzh.js.map +1 -0
  335. package/dist/unpkg/prod-deprecated/store.js +1 -503
  336. package/dist/unpkg/prod-deprecated/util-CQQdHX3n.js +14 -0
  337. package/dist/unpkg/prod-deprecated/util-CQQdHX3n.js.map +1 -0
  338. package/dist/unpkg/prod-deprecated/utils-BMI_JwFP.js +13 -0
  339. package/dist/unpkg/prod-deprecated/utils-BMI_JwFP.js.map +1 -0
  340. package/dist/util-Bnx8nm-D.js +29 -0
  341. package/dist/util-Bnx8nm-D.js.map +1 -0
  342. package/dist/utils-ZAytYep8.js +28 -0
  343. package/dist/utils-ZAytYep8.js.map +1 -0
  344. package/package.json +21 -25
  345. package/declarations/adapter/-private/build-url-mixin.d.ts +0 -33
  346. package/declarations/adapter/-private/fastboot-interface.d.ts +0 -8
  347. package/declarations/adapter/-private/utils/continue-on-reject.d.ts +0 -1
  348. package/declarations/adapter/-private/utils/determine-body-promise.d.ts +0 -4
  349. package/declarations/adapter/-private/utils/fetch.d.ts +0 -8
  350. package/declarations/adapter/-private/utils/parse-response-headers.d.ts +0 -1
  351. package/declarations/adapter/-private/utils/serialize-into-hash.d.ts +0 -6
  352. package/declarations/adapter/-private/utils/serialize-query-params.d.ts +0 -5
  353. package/declarations/adapter/-private.d.ts +0 -5
  354. package/declarations/adapter/error.d.ts +0 -215
  355. package/declarations/compat/-private.d.ts +0 -13
  356. package/declarations/compat/builders/find-all.d.ts +0 -35
  357. package/declarations/compat/builders/find-record.d.ts +0 -56
  358. package/declarations/compat/builders/query.d.ts +0 -66
  359. package/declarations/compat/builders/save-record.d.ts +0 -34
  360. package/declarations/compat/builders/utils.d.ts +0 -3
  361. package/declarations/compat/builders.d.ts +0 -14
  362. package/declarations/compat/extensions.d.ts +0 -59
  363. package/declarations/compat/legacy-network-handler/fetch-manager.d.ts +0 -55
  364. package/declarations/compat/legacy-network-handler/identifier-has-id.d.ts +0 -2
  365. package/declarations/compat/legacy-network-handler/legacy-data-fetch.d.ts +0 -11
  366. package/declarations/compat/legacy-network-handler/legacy-data-utils.d.ts +0 -5
  367. package/declarations/compat/legacy-network-handler/legacy-network-handler.d.ts +0 -2
  368. package/declarations/compat/legacy-network-handler/minimum-adapter-interface.d.ts +0 -524
  369. package/declarations/compat/legacy-network-handler/minimum-serializer-interface.d.ts +0 -213
  370. package/declarations/compat/legacy-network-handler/serializer-response.d.ts +0 -6
  371. package/declarations/compat/legacy-network-handler/snapshot-record-array.d.ts +0 -110
  372. package/declarations/compat/legacy-network-handler/snapshot.d.ts +0 -255
  373. package/declarations/compat/utils.d.ts +0 -137
  374. package/declarations/compat.d.ts +0 -157
  375. package/declarations/index.d.ts +0 -102
  376. package/declarations/model/-private/attr.d.ts +0 -170
  377. package/declarations/model/-private/belongs-to.d.ts +0 -174
  378. package/declarations/model/-private/debug/assert-polymorphic-type.d.ts +0 -5
  379. package/declarations/model/-private/errors.d.ts +0 -289
  380. package/declarations/model/-private/has-many.d.ts +0 -162
  381. package/declarations/model/-private/hooks.d.ts +0 -10
  382. package/declarations/model/-private/legacy-relationships-support.d.ts +0 -47
  383. package/declarations/model/-private/model-for-mixin.d.ts +0 -3
  384. package/declarations/model/-private/model-methods.d.ts +0 -39
  385. package/declarations/model/-private/model.d.ts +0 -1228
  386. package/declarations/model/-private/notify-changes.d.ts +0 -4
  387. package/declarations/model/-private/promise-belongs-to.d.ts +0 -40
  388. package/declarations/model/-private/promise-many-array.d.ts +0 -106
  389. package/declarations/model/-private/record-state.d.ts +0 -58
  390. package/declarations/model/-private/references/belongs-to.d.ts +0 -488
  391. package/declarations/model/-private/references/has-many.d.ts +0 -498
  392. package/declarations/model/-private/schema-provider.d.ts +0 -56
  393. package/declarations/model/-private/type-utils.d.ts +0 -57
  394. package/declarations/model/-private/util.d.ts +0 -5
  395. package/declarations/model/-private.d.ts +0 -8
  396. package/declarations/model/migration-support.d.ts +0 -280
  397. package/declarations/model-fragments/extensions/fragment-array.d.ts +0 -16
  398. package/declarations/model-fragments/extensions/fragment.d.ts +0 -15
  399. package/declarations/model-fragments/hooks/model-for.d.ts +0 -20
  400. package/declarations/model-fragments/index.d.ts +0 -5
  401. package/declarations/model-fragments/instance-initializers/fragment-extensions.d.ts +0 -9
  402. package/declarations/model-fragments/utilities/with-array-defaults.d.ts +0 -15
  403. package/declarations/model-fragments/utilities/with-fragment-array-defaults.d.ts +0 -20
  404. package/declarations/model-fragments/utilities/with-fragment-defaults.d.ts +0 -19
  405. package/declarations/model-fragments/utilities/with-legacy.d.ts +0 -3
  406. package/declarations/model-fragments.d.ts +0 -9
  407. package/declarations/model.d.ts +0 -49
  408. package/declarations/serializer/-private/transforms/boolean.d.ts +0 -47
  409. package/declarations/serializer/-private/transforms/date.d.ts +0 -28
  410. package/declarations/serializer/-private/transforms/number.d.ts +0 -29
  411. package/declarations/serializer/-private/transforms/string.d.ts +0 -29
  412. package/declarations/serializer/-private/transforms/transform.d.ts +0 -118
  413. package/declarations/serializer/-private/utils.d.ts +0 -3
  414. package/declarations/serializer/rest.d.ts +0 -51
  415. package/declarations/serializer/transform.d.ts +0 -5
  416. package/declarations/serializer.d.ts +0 -254
  417. package/declarations/store/-private.d.ts +0 -223
  418. package/declarations/store.d.ts +0 -3
  419. package/dist/-private-BG3bMiKp.js +0 -1211
  420. package/dist/errors-Cz5KrzBk.js +0 -2566
  421. package/dist/hooks-D6diaM34.js +0 -74
  422. package/dist/json-ChdEfB0X.js +0 -1259
  423. package/dist/model-for-CqXsIKws.js +0 -221
  424. package/dist/runtime-BPCpkOf1-BKOwiRJp.js +0 -65
  425. package/dist/schema-provider-DJCV_6AF.js +0 -2295
  426. package/dist/serialize-into-hash-DPZYoF-i.js +0 -261
  427. package/dist/unpkg/dev/-private-DtjBbEgy.js +0 -1206
  428. package/dist/unpkg/dev/errors-DmGGJr3T.js +0 -2562
  429. package/dist/unpkg/dev/hooks-CkYiE6Ud.js +0 -73
  430. package/dist/unpkg/dev/json-Cu1LNgmQ.js +0 -1256
  431. package/dist/unpkg/dev/model-for-CqXsIKws.js +0 -221
  432. package/dist/unpkg/dev/runtime-BPCpkOf1-BKOwiRJp.js +0 -65
  433. package/dist/unpkg/dev/schema-provider-DDVYxmUV.js +0 -2186
  434. package/dist/unpkg/dev/serialize-into-hash-B2xDbuo5.js +0 -259
  435. package/dist/unpkg/dev/util-DvanW33H.js +0 -20
  436. package/dist/unpkg/dev/utils-BhvS1iTS.js +0 -8
  437. package/dist/unpkg/dev-deprecated/-private-DtjBbEgy.js +0 -1206
  438. package/dist/unpkg/dev-deprecated/errors-Spt6ubMd.js +0 -2565
  439. package/dist/unpkg/dev-deprecated/hooks-DOXegvhL.js +0 -73
  440. package/dist/unpkg/dev-deprecated/json-Cu1LNgmQ.js +0 -1256
  441. package/dist/unpkg/dev-deprecated/model-for-CqXsIKws.js +0 -221
  442. package/dist/unpkg/dev-deprecated/runtime-BPCpkOf1-BKOwiRJp.js +0 -65
  443. package/dist/unpkg/dev-deprecated/schema-provider-BP6_8N-V.js +0 -2211
  444. package/dist/unpkg/dev-deprecated/serialize-into-hash-B2xDbuo5.js +0 -259
  445. package/dist/unpkg/dev-deprecated/util-CWr5WQOT.js +0 -24
  446. package/dist/unpkg/dev-deprecated/utils-C9PJehtL.js +0 -12
  447. package/dist/unpkg/prod/-private-BdyZaGEh.js +0 -971
  448. package/dist/unpkg/prod/errors-BGVFCBmi.js +0 -2314
  449. package/dist/unpkg/prod/hooks-BztVA_x0.js +0 -41
  450. package/dist/unpkg/prod/json-BWrZ5546.js +0 -1243
  451. package/dist/unpkg/prod/model-for-CqXsIKws.js +0 -221
  452. package/dist/unpkg/prod/runtime-BPCpkOf1-BKOwiRJp.js +0 -65
  453. package/dist/unpkg/prod/schema-provider-DJtD_8jZ.js +0 -1861
  454. package/dist/unpkg/prod/serialize-into-hash-DGlzQteF.js +0 -215
  455. package/dist/unpkg/prod/util-DvanW33H.js +0 -20
  456. package/dist/unpkg/prod/utils-BhvS1iTS.js +0 -8
  457. package/dist/unpkg/prod-deprecated/-private-BdyZaGEh.js +0 -971
  458. package/dist/unpkg/prod-deprecated/errors-CdDaK81x.js +0 -2317
  459. package/dist/unpkg/prod-deprecated/hooks-yId87yyG.js +0 -41
  460. package/dist/unpkg/prod-deprecated/json-BWrZ5546.js +0 -1243
  461. package/dist/unpkg/prod-deprecated/model-for-CqXsIKws.js +0 -221
  462. package/dist/unpkg/prod-deprecated/runtime-BPCpkOf1-BKOwiRJp.js +0 -65
  463. package/dist/unpkg/prod-deprecated/schema-provider-CjX55uSY.js +0 -1904
  464. package/dist/unpkg/prod-deprecated/serialize-into-hash-DGlzQteF.js +0 -215
  465. package/dist/unpkg/prod-deprecated/util-B6cn-i93.js +0 -23
  466. package/dist/unpkg/prod-deprecated/utils-BUWwQwCh.js +0 -11
  467. package/dist/util-Dul6TZts.js +0 -35
  468. package/dist/utils-Cqw9eRj5.js +0 -23
@@ -1,2566 +0,0 @@
1
- import { Context } from '@warp-drive/core/reactive/-private';
2
- import { memoized, defineSignal, defineNonEnumerableSignal, notifyInternalSignal } from '@warp-drive/core/signals/-leaked';
3
- import { assertPrivateStore, isResourceKey, recordIdentifierFor, isPrivateStore, storeFor, fastPush, createLegacyManyArray } from '@warp-drive/core/store/-private';
4
- import { getOrSetGlobal } from '@warp-drive/core/types/-private';
5
- import { EnableHydration } from '@warp-drive/core/types/request';
6
- import { u as upgradeStore } from "./-private-BG3bMiKp.js";
7
- import { computed, get } from '@ember/object';
8
- import PromiseProxyMixin from '@ember/object/promise-proxy-mixin';
9
- import ObjectProxy from '@ember/object/proxy';
10
- import { macroCondition, getGlobalConfig } from '@embroider/macros';
11
- import { d as decorateMethodV2, a as decorateFieldV2, i as initializeDeferredDecorator } from "./runtime-BPCpkOf1-BKOwiRJp.js";
12
- import { A } from '@ember/array';
13
- import ArrayProxy from '@ember/array/proxy';
14
- import { mapBy, not } from '@ember/object/computed';
15
- const PromiseObject = ObjectProxy.extend(PromiseProxyMixin);
16
- const LegacyPromiseProxy = Symbol.for('LegacyPromiseProxy');
17
-
18
- // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/no-extraneous-class
19
-
20
- const Extended = PromiseObject;
21
-
22
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
23
-
24
- /**
25
- A PromiseBelongsTo is a PromiseObject that also proxies certain method calls
26
- to the underlying belongsTo model.
27
- Right now we proxy:
28
- * `reload()`
29
- @class PromiseBelongsTo
30
- @private
31
- */
32
- class PromiseBelongsTo extends Extended {
33
- get id() {
34
- const {
35
- key,
36
- legacySupport
37
- } = this._belongsToState;
38
- const ref = legacySupport.referenceFor('belongsTo', key);
39
- return ref.id();
40
- }
41
-
42
- // we don't proxy meta because we would need to proxy it to the relationship state container
43
- // however, meta on relationships does not trigger change notifications.
44
- // if you need relationship meta, you should do `record.belongsTo(relationshipName).meta()`
45
- static {
46
- decorateMethodV2(this.prototype, "id", [memoized]);
47
- }
48
- get meta() {
49
- // eslint-disable-next-line no-constant-condition
50
- {
51
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
52
- {
53
- throw new Error('You attempted to access meta on the promise for the async belongsTo relationship ' + `${this._belongsToState.modelName}:${this._belongsToState.key}'.` + '\nUse `record.belongsTo(relationshipName).meta()` instead.');
54
- }
55
- })() : {};
56
- }
57
- return;
58
- }
59
- static {
60
- decorateMethodV2(this.prototype, "meta", [computed()]);
61
- }
62
- async reload(options) {
63
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
64
- if (!test) {
65
- throw new Error('You are trying to reload an async belongsTo before it has been created');
66
- }
67
- })(this.content !== undefined) : {};
68
- const {
69
- key,
70
- legacySupport
71
- } = this._belongsToState;
72
- await legacySupport.reloadBelongsTo(key, options);
73
- return this;
74
- }
75
- }
76
- PromiseBelongsTo.prototype[LegacyPromiseProxy] = true;
77
-
78
- /**
79
- This class is returned as the result of accessing an async hasMany relationship
80
- on an instance of a Model extending from `@ember-data/model`.
81
-
82
- A PromiseManyArray is an iterable proxy that allows templates to consume related
83
- ManyArrays and update once their contents are no longer pending.
84
-
85
- In your JS code you should resolve the promise first.
86
-
87
- ```js
88
- const comments = await post.comments;
89
- ```
90
-
91
- @public
92
- */
93
- class PromiseManyArray {
94
- constructor(promise, content) {
95
- this._update(promise, content);
96
- this.isDestroyed = false;
97
- this[LegacyPromiseProxy] = true;
98
- }
99
-
100
- /**
101
- * Retrieve the length of the content
102
- * @public
103
- */
104
- get length() {
105
- // shouldn't be needed, but ends up being needed
106
- // for computed chains even in 4.x
107
- if (macroCondition(getGlobalConfig().WarpDrive.deprecations.DEPRECATE_COMPUTED_CHAINS)) {
108
- // eslint-disable-next-line @typescript-eslint/no-unused-expressions
109
- this['[]'];
110
- }
111
- return this.content ? this.content.length : 0;
112
- }
113
-
114
- // this will error if someone tries to call
115
- // A(identifierArray) since it is not configurable
116
- // which is preferrable to the `meta` override we used
117
- // before which required importing all of Ember
118
- static {
119
- decorateMethodV2(this.prototype, "length", [memoized]);
120
- }
121
- get '[]'() {
122
- // ember-source < 3.23 (e.g. 3.20 lts)
123
- // requires that the tag `'[]'` be notified
124
- // on the ArrayProxy in order for `{{#each}}`
125
- // to recompute. We entangle content.
126
- return this.content?.length && this.content;
127
- }
128
-
129
- /**
130
- * Iterate the proxied content. Called by the glimmer iterator in #each
131
- * We do not guarantee that forEach will always be available. This
132
- * may eventually be made to use Symbol.Iterator once glimmer supports it.
133
- *
134
- * @param cb
135
- * @return
136
- * @private
137
- */
138
- static {
139
- decorateMethodV2(this.prototype, '[]', [memoized]);
140
- }
141
- forEach(cb) {
142
- if (this.content && this.length) {
143
- this.content.forEach(cb);
144
- }
145
- }
146
-
147
- /**
148
- * Reload the relationship
149
- * @public
150
- */
151
- reload(options) {
152
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
153
- if (!test) {
154
- throw new Error('You are trying to reload an async manyArray before it has been created');
155
- }
156
- })(this.content) : {};
157
- void this.content.reload(options);
158
- return this;
159
- }
160
-
161
- //---- Properties/Methods from the PromiseProxyMixin that we will keep as our API
162
-
163
- /**
164
- * Whether the loading promise is still pending
165
- *
166
- * @public
167
- */
168
-
169
- /**
170
- * Whether the loading promise rejected
171
- *
172
- * @public
173
- */
174
-
175
- /**
176
- * Whether the loading promise succeeded
177
- *
178
- * @public
179
- */
180
-
181
- /**
182
- * Whether the loading promise completed (resolved or rejected)
183
- *
184
- * @public
185
- */
186
-
187
- /**
188
- * chain this promise
189
- *
190
- * @public
191
- */
192
- then(success, rejected) {
193
- return this.promise.then(success, rejected);
194
- }
195
-
196
- /**
197
- * catch errors thrown by this promise
198
- * @public
199
- */
200
- catch(cb) {
201
- return this.promise.catch(cb);
202
- }
203
-
204
- /**
205
- * run cleanup after this promise completes
206
- *
207
- * @public
208
- */
209
- finally(cb) {
210
- return this.promise.finally(cb);
211
- }
212
-
213
- //---- Methods on EmberObject that we should keep
214
-
215
- destroy() {
216
- this.isDestroyed = true;
217
- this.content = null;
218
- this.promise = null;
219
- }
220
-
221
- //---- Methods/Properties on ManyArray that we own and proxy to
222
-
223
- /**
224
- * Retrieve the links for this relationship
225
- * @public
226
- */
227
- get links() {
228
- return this.content ? this.content.links : undefined;
229
- }
230
-
231
- /**
232
- * Retrieve the meta for this relationship
233
- * @public
234
- */
235
- static {
236
- decorateMethodV2(this.prototype, "links", [memoized]);
237
- }
238
- get meta() {
239
- return this.content ? this.content.meta : undefined;
240
- }
241
-
242
- //---- Our own stuff
243
-
244
- /** @internal */
245
- static {
246
- decorateMethodV2(this.prototype, "meta", [memoized]);
247
- }
248
- _update(promise, content) {
249
- if (content !== undefined) {
250
- this.content = content;
251
- }
252
- this.promise = tapPromise(this, promise);
253
- }
254
- static create({
255
- promise,
256
- content
257
- }) {
258
- return new this(promise, content);
259
- }
260
- }
261
- defineSignal(PromiseManyArray.prototype, 'content', null);
262
- defineSignal(PromiseManyArray.prototype, 'isPending', false);
263
- defineSignal(PromiseManyArray.prototype, 'isRejected', false);
264
- defineSignal(PromiseManyArray.prototype, 'isFulfilled', false);
265
- defineSignal(PromiseManyArray.prototype, 'isSettled', false);
266
- function tapPromise(proxy, promise) {
267
- proxy.isPending = true;
268
- proxy.isSettled = false;
269
- proxy.isFulfilled = false;
270
- proxy.isRejected = false;
271
- return Promise.resolve(promise).then(content => {
272
- proxy.isPending = false;
273
- proxy.isFulfilled = true;
274
- proxy.isSettled = true;
275
- proxy.content = content;
276
- return content;
277
- }, error => {
278
- proxy.isPending = false;
279
- proxy.isFulfilled = false;
280
- proxy.isRejected = true;
281
- proxy.isSettled = true;
282
- throw error;
283
- });
284
- }
285
-
286
- /*
287
- Assert that `addedRecord` has a valid type so it can be added to the
288
- relationship of the `record`.
289
-
290
- The assert basically checks if the `addedRecord` can be added to the
291
- relationship (specified via `relationshipMeta`) of the `record`.
292
-
293
- This utility should only be used internally, as both record parameters must
294
- be stable record identifiers and the `relationshipMeta` needs to be the meta
295
- information about the relationship, retrieved via
296
- `record.relationshipFor(key)`.
297
- */
298
- let assertPolymorphicType;
299
- if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
300
- // eslint-disable-next-line @typescript-eslint/no-shadow
301
- assertPolymorphicType = function assertPolymorphicType(parentIdentifier, parentDefinition, addedIdentifier, store) {
302
- if (parentDefinition.inverseIsImplicit) {
303
- return;
304
- }
305
- if (parentDefinition.isPolymorphic) {
306
- const meta = store.schema.fields(addedIdentifier)?.get(parentDefinition.inverseKey);
307
- if (meta) {
308
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
309
- if (!test) {
310
- throw new Error(`Expected the schema for the field ${parentDefinition.inverseKey} on ${addedIdentifier.type} to be for a legacy relationship`);
311
- }
312
- })(meta.kind === 'belongsTo' || meta.kind === 'hasMany') : {};
313
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
314
- if (!test) {
315
- throw new Error(`The schema for the relationship '${parentDefinition.inverseKey}' on '${addedIdentifier.type}' type does not implement '${parentDefinition.type}' and thus cannot be assigned to the '${parentDefinition.key}' relationship in '${parentIdentifier.type}'. The definition should specify 'as: "${parentDefinition.type}"' in options.`);
316
- }
317
- })(meta?.options?.as === parentDefinition.type) : {};
318
- }
319
- }
320
- };
321
- }
322
- function isResourceIdentiferWithRelatedLinks$1(value) {
323
- return Boolean(value && value.links && value.links.related);
324
- }
325
- /**
326
- A `HasManyReference` is a low-level API that allows access
327
- and manipulation of a hasMany relationship.
328
-
329
- It is especially useful when you're dealing with `async` relationships
330
- from `@warp-drive/legacy/model` as it allows synchronous access to
331
- the relationship data if loaded, as well as APIs for loading, reloading
332
- the data or accessing available information without triggering a load.
333
-
334
- It may also be useful when using `sync` relationships with `@warp-drive/legacy/model`
335
- that need to be loaded/reloaded with more precise timing than marking the
336
- relationship as `async` and relying on autofetch would have allowed.
337
-
338
- However,keep in mind that marking a relationship as `async: false` will introduce
339
- bugs into your application if the data is not always guaranteed to be available
340
- by the time the relationship is accessed. Ergo, it is recommended when using this
341
- approach to utilize `links` for unloaded relationship state instead of identifiers.
342
-
343
- Reference APIs are entangled with the relationship's underlying state,
344
- thus any getters or cached properties that utilize these will properly
345
- invalidate if the relationship state changes.
346
-
347
- References are "stable", meaning that multiple calls to retrieve the reference
348
- for a given relationship will always return the same HasManyReference.
349
-
350
- @class HasManyReference
351
- @public
352
- */
353
- class HasManyReference {
354
- /**
355
- * The field name on the parent record for this has-many relationship.
356
- *
357
- * @property key
358
- * @type {String}
359
- * @public
360
- */
361
-
362
- /**
363
- * The type of resource this relationship will contain.
364
- *
365
- * @property type
366
- * @type {String}
367
- * @public
368
- */
369
-
370
- // unsubscribe tokens given to us by the notification manager
371
- ___token;
372
- ___identifier;
373
- ___relatedTokenMap;
374
- constructor(store, graph, parentIdentifier, hasManyRelationship, key) {
375
- this.graph = graph;
376
- this.key = key;
377
- this.hasManyRelationship = hasManyRelationship;
378
- this.type = hasManyRelationship.definition.type;
379
- this.store = store;
380
- this.___identifier = parentIdentifier;
381
- this.___token = store.notifications.subscribe(parentIdentifier, (_, bucket, notifiedKey) => {
382
- if (bucket === 'relationships' && notifiedKey === key) {
383
- this._ref++;
384
- }
385
- });
386
- this.___relatedTokenMap = new Map();
387
- // TODO inverse
388
- }
389
-
390
- /**
391
- * This method should never be called by user code.
392
- *
393
- * @internal
394
- */
395
- destroy() {
396
- this.store.notifications.unsubscribe(this.___token);
397
- this.___relatedTokenMap.forEach(token => {
398
- this.store.notifications.unsubscribe(token);
399
- });
400
- this.___relatedTokenMap.clear();
401
- }
402
-
403
- /**
404
- * An array of identifiers for the records that this reference refers to.
405
- *
406
- * @property identifiers
407
- * @type {ResourceKey[]}
408
- * @public
409
- */
410
- get identifiers() {
411
- ensureRefCanSubscribe(this);
412
- // eslint-disable-next-line @typescript-eslint/no-unused-expressions
413
- this._ref;
414
- const resource = this._resource();
415
- const map = this.___relatedTokenMap;
416
- this.___relatedTokenMap = new Map();
417
- if (resource && resource.data) {
418
- return resource.data.map(resourceIdentifier => {
419
- const identifier = this.store.cacheKeyManager.getOrCreateRecordIdentifier(resourceIdentifier);
420
- let token = map.get(identifier);
421
- if (token) {
422
- map.delete(identifier);
423
- } else {
424
- token = this.store.notifications.subscribe(identifier, (_, bucket, notifiedKey) => {
425
- if (bucket === 'identity' || bucket === 'attributes' && notifiedKey === 'id') {
426
- this._ref++;
427
- }
428
- });
429
- }
430
- this.___relatedTokenMap.set(identifier, token);
431
- return identifier;
432
- });
433
- }
434
- map.forEach(token => {
435
- this.store.notifications.unsubscribe(token);
436
- });
437
- map.clear();
438
- return [];
439
- }
440
- static {
441
- decorateMethodV2(this.prototype, "identifiers", [memoized]);
442
- }
443
- _resource() {
444
- const cache = this.store.cache;
445
- return cache.getRelationship(this.___identifier, this.key);
446
- }
447
-
448
- /**
449
- This returns a string that represents how the reference will be
450
- looked up when it is loaded. If the relationship has a link it will
451
- use the "link" otherwise it defaults to "id".
452
- Example
453
- ```js [app/models/post.js]
454
- import { Model, hasMany } from '@warp-drive/legacy/model';
455
- export default class PostModel extends Model {
456
- @hasMany('comment', { async: true, inverse: null }) comments;
457
- }
458
- ```
459
- ```javascript
460
- let post = store.push({
461
- data: {
462
- type: 'post',
463
- id: 1,
464
- relationships: {
465
- comments: {
466
- data: [{ type: 'comment', id: 1 }]
467
- }
468
- }
469
- }
470
- });
471
- let commentsRef = post.hasMany('comments');
472
- // get the identifier of the reference
473
- if (commentsRef.remoteType() === "ids") {
474
- let ids = commentsRef.ids();
475
- } else if (commentsRef.remoteType() === "link") {
476
- let link = commentsRef.link();
477
- }
478
- ```
479
- @public
480
- @return The name of the remote type. This should either be `link` or `ids`
481
- */
482
- remoteType() {
483
- const value = this._resource();
484
- if (value && value.links && value.links.related) {
485
- return 'link';
486
- }
487
- return 'ids';
488
- }
489
-
490
- /**
491
- `ids()` returns an array of the record IDs in this relationship.
492
- Example
493
- ```js [app/models/post.js]
494
- import { Model, hasMany } from '@warp-drive/legacy/model';
495
- export default class PostModel extends Model {
496
- @hasMany('comment', { async: true, inverse: null }) comments;
497
- }
498
- ```
499
- ```javascript
500
- let post = store.push({
501
- data: {
502
- type: 'post',
503
- id: 1,
504
- relationships: {
505
- comments: {
506
- data: [{ type: 'comment', id: 1 }]
507
- }
508
- }
509
- }
510
- });
511
- let commentsRef = post.hasMany('comments');
512
- commentsRef.ids(); // ['1']
513
- ```
514
- @public
515
- @return The ids in this has-many relationship
516
- */
517
- ids() {
518
- return this.identifiers.map(identifier => identifier.id);
519
- }
520
-
521
- /**
522
- The link WarpDrive will use to fetch or reload this belongs-to
523
- relationship. By default it uses only the "related" resource linkage.
524
- Example
525
- ```javascript
526
- // models/blog.js
527
- import { Model, belongsTo } from '@warp-drive/legacy/model';
528
- export default Model.extend({
529
- user: belongsTo('user', { async: true, inverse: null })
530
- });
531
- let blog = store.push({
532
- data: {
533
- type: 'blog',
534
- id: 1,
535
- relationships: {
536
- user: {
537
- links: {
538
- related: '/articles/1/author'
539
- }
540
- }
541
- }
542
- }
543
- });
544
- let userRef = blog.belongsTo('user');
545
- // get the identifier of the reference
546
- if (userRef.remoteType() === "link") {
547
- let link = userRef.link();
548
- }
549
- ```
550
- @public
551
- @return The link WarpDrive will use to fetch or reload this belongs-to relationship.
552
- */
553
- link() {
554
- const resource = this._resource();
555
- if (isResourceIdentiferWithRelatedLinks$1(resource)) {
556
- if (resource.links) {
557
- const related = resource.links.related;
558
- return !related || typeof related === 'string' ? related : related.href;
559
- }
560
- }
561
- return null;
562
- }
563
-
564
- /**
565
- * any links that have been received for this relationship
566
- *
567
- * @public
568
- * @return
569
- */
570
- links() {
571
- const resource = this._resource();
572
- return resource && resource.links ? resource.links : null;
573
- }
574
-
575
- /**
576
- The meta data for the has-many relationship.
577
- Example
578
- ```javascript
579
- // models/blog.js
580
- import { Model, hasMany } from '@warp-drive/legacy/model';
581
- export default Model.extend({
582
- users: hasMany('user', { async: true, inverse: null })
583
- });
584
- let blog = store.push({
585
- data: {
586
- type: 'blog',
587
- id: 1,
588
- relationships: {
589
- users: {
590
- links: {
591
- related: {
592
- href: '/articles/1/authors'
593
- },
594
- },
595
- meta: {
596
- lastUpdated: 1458014400000
597
- }
598
- }
599
- }
600
- }
601
- });
602
- let usersRef = blog.hasMany('user');
603
- usersRef.meta() // { lastUpdated: 1458014400000 }
604
- ```
605
- @public
606
- @return The meta information for the belongs-to relationship.
607
- */
608
- meta() {
609
- let meta = null;
610
- const resource = this._resource();
611
- if (resource && resource.meta && typeof resource.meta === 'object') {
612
- meta = resource.meta;
613
- }
614
- return meta;
615
- }
616
-
617
- /**
618
- `push` can be used to update the data in the relationship and WarpDrive
619
- will treat the new data as the canonical value of this relationship on
620
- the backend. An empty array will signify the canonical value should be
621
- empty.
622
- Example model
623
- ```js [app/models/post.js]
624
- import { Model, hasMany } from '@warp-drive/legacy/model';
625
- export default class PostModel extends Model {
626
- @hasMany('comment', { async: true, inverse: null }) comments;
627
- }
628
- ```
629
- Setup some initial state, note we haven't loaded the comments yet:
630
- ```js
631
- const post = store.push({
632
- data: {
633
- type: 'post',
634
- id: '1',
635
- relationships: {
636
- comments: {
637
- data: [{ type: 'comment', id: '1' }]
638
- }
639
- }
640
- }
641
- });
642
- const commentsRef = post.hasMany('comments');
643
- commentsRef.ids(); // ['1']
644
- ```
645
- Update the state using `push`, note we can do this even without
646
- having loaded these comments yet by providing resource identifiers.
647
- Both full resources and resource identifiers are supported.
648
- ```js
649
- await commentsRef.push({
650
- data: [
651
- { type: 'comment', id: '2' },
652
- { type: 'comment', id: '3' },
653
- ]
654
- });
655
- commentsRef.ids(); // ['2', '3']
656
- ```
657
- For convenience, you can also pass in an array of resources or resource identifiers
658
- without wrapping them in the `data` property:
659
- ```js
660
- await commentsRef.push([
661
- { type: 'comment', id: '4' },
662
- { type: 'comment', id: '5' },
663
- ]);
664
- commentsRef.ids(); // ['4', '5']
665
- ```
666
- When using the `data` property, you may also include other resource data via included,
667
- as well as provide new links and meta to the relationship.
668
- ```js
669
- await commentsRef.push({
670
- links: {
671
- related: '/posts/1/comments'
672
- },
673
- meta: {
674
- total: 2
675
- },
676
- data: [
677
- { type: 'comment', id: '4' },
678
- { type: 'comment', id: '5' },
679
- ],
680
- included: [
681
- { type: 'other-thing', id: '1', attributes: { foo: 'bar' },
682
- ]
683
- });
684
- ```
685
- By default, the store will attempt to fetch any unloaded records before resolving
686
- the returned promise with the ManyArray.
687
- Alternatively, pass `true` as the second argument to avoid fetching unloaded records
688
- and instead the promise will resolve with void without attempting to fetch. This is
689
- particularly useful if you want to update the state of the relationship without
690
- forcing the load of all of the associated records.
691
- @public
692
- @param doc a JSONAPI document object describing the new value of this relationship.
693
- @param skipFetch [optional] if `true`, do not attempt to fetch unloaded records
694
- */
695
- async push(doc, skipFetch) {
696
- const {
697
- store
698
- } = this;
699
- const dataDoc = Array.isArray(doc) ? {
700
- data: doc
701
- } : doc;
702
- const isResourceData = Array.isArray(dataDoc.data) && dataDoc.data.length > 0 && isMaybeResource(dataDoc.data[0]);
703
-
704
- // enforce that one of links, meta or data is present
705
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
706
- if (!test) {
707
- throw new Error(`You must provide at least one of 'links', 'meta' or 'data' when calling hasManyReference.push`);
708
- }
709
- })('links' in dataDoc || 'meta' in dataDoc || 'data' in dataDoc) : {};
710
- const identifiers = !Array.isArray(dataDoc.data) ? [] : isResourceData ? store._push(dataDoc, true) : dataDoc.data.map(i => store.cacheKeyManager.getOrCreateRecordIdentifier(i));
711
- const {
712
- identifier
713
- } = this.hasManyRelationship;
714
- if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
715
- const relationshipMeta = this.hasManyRelationship.definition;
716
- identifiers.forEach(added => {
717
- assertPolymorphicType(identifier, relationshipMeta, added, store);
718
- });
719
- }
720
- const newData = {};
721
- // only set data if it was passed in
722
- if (Array.isArray(dataDoc.data)) {
723
- newData.data = identifiers;
724
- }
725
- if ('links' in dataDoc) {
726
- newData.links = dataDoc.links;
727
- }
728
- if ('meta' in dataDoc) {
729
- newData.meta = dataDoc.meta;
730
- }
731
- assertPrivateStore(store);
732
- store._join(() => {
733
- this.graph.push({
734
- op: 'updateRelationship',
735
- record: identifier,
736
- field: this.key,
737
- value: newData
738
- });
739
- });
740
- if (!skipFetch) return this.load();
741
- }
742
- _isLoaded() {
743
- const hasRelationshipDataProperty = this.hasManyRelationship.state.hasReceivedData;
744
- if (!hasRelationshipDataProperty) {
745
- return false;
746
- }
747
- const relationship = this.graph.getData(this.hasManyRelationship.identifier, this.key);
748
- return relationship.data ? relationship.data.every(identifier => {
749
- assertPrivateStore(this.store);
750
- return this.store._instanceCache.recordIsLoaded(identifier, true) === true;
751
- }) : false;
752
- }
753
-
754
- /**
755
- `value()` synchronously returns the current value of the has-many
756
- relationship. Unlike `record.relationshipName`, calling
757
- `value()` on a reference does not trigger a fetch if the async
758
- relationship is not yet loaded. If the relationship is not loaded
759
- it will always return `null`.
760
- Example
761
- ```js [app/models/post.js]
762
- import { Model, hasMany } from '@warp-drive/legacy/model';
763
- export default class PostModel extends Model {
764
- @hasMany('comment', { async: true, inverse: null }) comments;
765
- }
766
- ```
767
- ```javascript
768
- let post = store.push({
769
- data: {
770
- type: 'post',
771
- id: 1,
772
- relationships: {
773
- comments: {
774
- data: [{ type: 'comment', id: 1 }]
775
- }
776
- }
777
- }
778
- });
779
- let commentsRef = post.hasMany('comments');
780
- post.comments.then(function(comments) {
781
- commentsRef.value() === comments
782
- })
783
- ```
784
- @public
785
- */
786
- value() {
787
- const support = LEGACY_SUPPORT.get(this.___identifier);
788
- if (!ensureRefCanSubscribe(this)) {
789
- // eslint-disable-next-line @typescript-eslint/no-unused-expressions
790
- this._ref;
791
- return null;
792
- }
793
- return support.getManyArray(this.key);
794
- }
795
-
796
- /**
797
- Loads the relationship if it is not already loaded. If the
798
- relationship is already loaded this method does not trigger a new
799
- load. This causes a request to the specified
800
- relationship link or reloads all items currently in the relationship.
801
- Example
802
- ```js [app/models/post.js]
803
- import { Model, hasMany } from '@warp-drive/legacy/model';
804
- export default class PostModel extends Model {
805
- @hasMany('comment', { async: true, inverse: null }) comments;
806
- }
807
- ```
808
- ```javascript
809
- let post = store.push({
810
- data: {
811
- type: 'post',
812
- id: 1,
813
- relationships: {
814
- comments: {
815
- data: [{ type: 'comment', id: 1 }]
816
- }
817
- }
818
- }
819
- });
820
- let commentsRef = post.hasMany('comments');
821
- commentsRef.load().then(function(comments) {
822
- //...
823
- });
824
- ```
825
- You may also pass in an options object whose properties will be
826
- fed forward. This enables you to pass `adapterOptions` into the
827
- request given to the adapter via the reference.
828
- Example
829
- ```javascript
830
- commentsRef.load({ adapterOptions: { isPrivate: true } })
831
- .then(function(comments) {
832
- //...
833
- });
834
- ```
835
- ```js [app/adapters/comment.js]
836
- export default ApplicationAdapter.extend({
837
- findMany(store, type, id, snapshots) {
838
- // In the adapter you will have access to adapterOptions.
839
- let adapterOptions = snapshots[0].adapterOptions;
840
- }
841
- });
842
- ```
843
- @public
844
- @param options the options to pass in.
845
- @return a promise that resolves with the ManyArray in
846
- this has-many relationship.
847
- */
848
- async load(options) {
849
- const support = LEGACY_SUPPORT.get(this.___identifier);
850
- const fetchSyncRel = !this.hasManyRelationship.definition.isAsync && !areAllInverseRecordsLoaded(this.store, this._resource());
851
- return fetchSyncRel ? support.reloadHasMany(this.key, options) :
852
- // we cast to fix the return type since typescript and eslint don't understand async functions
853
- // properly
854
- support.getHasMany(this.key, options);
855
- }
856
-
857
- /**
858
- Reloads this has-many relationship. This causes a request to the specified
859
- relationship link or reloads all items currently in the relationship.
860
- Example
861
- ```js [app/models/post.js]
862
- import { Model, hasMany } from '@warp-drive/legacy/model';
863
- export default class PostModel extends Model {
864
- @hasMany('comment', { async: true, inverse: null }) comments;
865
- }
866
- ```
867
- ```javascript
868
- let post = store.push({
869
- data: {
870
- type: 'post',
871
- id: 1,
872
- relationships: {
873
- comments: {
874
- data: [{ type: 'comment', id: 1 }]
875
- }
876
- }
877
- }
878
- });
879
- let commentsRef = post.hasMany('comments');
880
- commentsRef.reload().then(function(comments) {
881
- //...
882
- });
883
- ```
884
- You may also pass in an options object whose properties will be
885
- fed forward. This enables you to pass `adapterOptions` into the
886
- request given to the adapter via the reference. A full example
887
- can be found in the `load` method.
888
- Example
889
- ```javascript
890
- commentsRef.reload({ adapterOptions: { isPrivate: true } })
891
- ```
892
- @public
893
- @param options the options to pass in.
894
- @return a promise that resolves with the ManyArray in this has-many relationship.
895
- */
896
- reload(options) {
897
- const support = LEGACY_SUPPORT.get(this.___identifier);
898
- return support.reloadHasMany(this.key, options);
899
- }
900
- }
901
- defineNonEnumerableSignal(HasManyReference.prototype, '_ref', 0);
902
- function isMaybeResource(object) {
903
- const keys = Object.keys(object).filter(k => k !== 'id' && k !== 'type' && k !== 'lid');
904
- return keys.length > 0;
905
- }
906
- function ensureRefCanSubscribe(rel) {
907
- const loaded = rel._isLoaded();
908
- if (!loaded) {
909
- // subscribe to changes
910
- // for when we are not loaded yet
911
- //
912
- // because the graph optimizes the case where a relationship has never been subscribed,
913
- // we force accessed to be true here. When we make the graph public we should create a
914
- // subscribe/unsubscribe API
915
- const edge = rel.graph.get(rel.___identifier, rel.key);
916
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
917
- if (!test) {
918
- throw new Error(`Expected a hasMany relationship for ${rel.___identifier.type}:${rel.key}`);
919
- }
920
- })('accessed' in edge) : {};
921
- edge.accessed = true;
922
- return false;
923
- }
924
- return true;
925
- }
926
- function isResourceIdentiferWithRelatedLinks(value) {
927
- return Boolean(value && value.links && value.links.related);
928
- }
929
-
930
- /**
931
- A `BelongsToReference` is a low-level API that allows access
932
- and manipulation of a belongsTo relationship.
933
-
934
- It is especially useful when you're dealing with `async` relationships
935
- from `@warp-drive/legacy/model` as it allows synchronous access to
936
- the relationship data if loaded, as well as APIs for loading, reloading
937
- the data or accessing available information without triggering a load.
938
-
939
- It may also be useful when using `sync` relationships with `@warp-drive/legacy/model`
940
- that need to be loaded/reloaded with more precise timing than marking the
941
- relationship as `async` and relying on autofetch would have allowed.
942
-
943
- However,keep in mind that marking a relationship as `async: false` will introduce
944
- bugs into your application if the data is not always guaranteed to be available
945
- by the time the relationship is accessed. Ergo, it is recommended when using this
946
- approach to utilize `links` for unloaded relationship state instead of identifiers.
947
-
948
- Reference APIs are entangled with the relationship's underlying state,
949
- thus any getters or cached properties that utilize these will properly
950
- invalidate if the relationship state changes.
951
-
952
- References are "stable", meaning that multiple calls to retrieve the reference
953
- for a given relationship will always return the same HasManyReference.
954
-
955
- @public
956
- */
957
- class BelongsToReference {
958
- /**
959
- * The field name on the parent record for this has-many relationship.
960
- *
961
- */
962
-
963
- /**
964
- * The type of resource this relationship will contain.
965
- *
966
- */
967
-
968
- // unsubscribe tokens given to us by the notification manager
969
-
970
- constructor(store, graph, parentIdentifier, belongsToRelationship, key) {
971
- this.graph = graph;
972
- this.key = key;
973
- this.belongsToRelationship = belongsToRelationship;
974
- this.type = belongsToRelationship.definition.type;
975
- this.store = store;
976
- this.___identifier = parentIdentifier;
977
- this.___relatedToken = null;
978
- this.___token = store.notifications.subscribe(parentIdentifier, (_, bucket, notifiedKey) => {
979
- if (bucket === 'relationships' && notifiedKey === key) {
980
- this._ref++;
981
- }
982
- });
983
-
984
- // TODO inverse
985
- }
986
- destroy() {
987
- // TODO @feature we need the notification manager often enough
988
- // we should potentially just expose it fully public
989
- this.store.notifications.unsubscribe(this.___token);
990
- this.___token = null;
991
- if (this.___relatedToken) {
992
- this.store.notifications.unsubscribe(this.___relatedToken);
993
- this.___relatedToken = null;
994
- }
995
- }
996
-
997
- /**
998
- * The identifier of the record that this reference refers to.
999
- * `null` if no related record is known.
1000
- *
1001
- */
1002
- get identifier() {
1003
- if (this.___relatedToken) {
1004
- this.store.notifications.unsubscribe(this.___relatedToken);
1005
- this.___relatedToken = null;
1006
- }
1007
- const resource = this._resource();
1008
- if (resource && resource.data) {
1009
- const identifier = this.store.cacheKeyManager.getOrCreateRecordIdentifier(resource.data);
1010
- this.___relatedToken = this.store.notifications.subscribe(identifier, (_, bucket, notifiedKey) => {
1011
- if (bucket === 'identity' || bucket === 'attributes' && notifiedKey === 'id') {
1012
- this._ref++;
1013
- }
1014
- });
1015
- return identifier;
1016
- }
1017
- return null;
1018
- }
1019
-
1020
- /**
1021
- The `id` of the record that this reference refers to. Together, the
1022
- `type()` and `id()` methods form a composite key for the identity
1023
- map. This can be used to access the id of an async relationship
1024
- without triggering a fetch that would normally happen if you
1025
- attempted to use `record.relationship.id`.
1026
- Example
1027
- ```javascript
1028
- // models/blog.js
1029
- import { Model, belongsTo } from '@warp-drive/legacy/model';
1030
- export default class BlogModel extends Model {
1031
- @belongsTo('user', { async: true, inverse: null }) user;
1032
- }
1033
- let blog = store.push({
1034
- data: {
1035
- type: 'blog',
1036
- id: 1,
1037
- relationships: {
1038
- user: {
1039
- data: { type: 'user', id: 1 }
1040
- }
1041
- }
1042
- }
1043
- });
1044
- let userRef = blog.belongsTo('user');
1045
- // get the identifier of the reference
1046
- if (userRef.remoteType() === "id") {
1047
- let id = userRef.id();
1048
- }
1049
- ```
1050
- @public
1051
- @return The id of the record in this belongsTo relationship.
1052
- */
1053
- static {
1054
- decorateMethodV2(this.prototype, "identifier", [memoized]);
1055
- }
1056
- id() {
1057
- return this.identifier?.id || null;
1058
- }
1059
-
1060
- /**
1061
- The link WarpDrive will use to fetch or reload this belongs-to
1062
- relationship. By default it uses only the "related" resource linkage.
1063
- Example
1064
- ```javascript
1065
- // models/blog.js
1066
- import { Model, belongsTo } from '@warp-drive/legacy/model';
1067
- export default Model.extend({
1068
- user: belongsTo('user', { async: true, inverse: null })
1069
- });
1070
- let blog = store.push({
1071
- data: {
1072
- type: 'blog',
1073
- id: 1,
1074
- relationships: {
1075
- user: {
1076
- links: {
1077
- related: '/articles/1/author'
1078
- }
1079
- }
1080
- }
1081
- }
1082
- });
1083
- let userRef = blog.belongsTo('user');
1084
- // get the identifier of the reference
1085
- if (userRef.remoteType() === "link") {
1086
- let link = userRef.link();
1087
- }
1088
- ```
1089
- @public
1090
- @return The link WarpDrive will use to fetch or reload this belongs-to relationship.
1091
- */
1092
- link() {
1093
- const resource = this._resource();
1094
- if (isResourceIdentiferWithRelatedLinks(resource)) {
1095
- if (resource.links) {
1096
- const related = resource.links.related;
1097
- return !related || typeof related === 'string' ? related : related.href;
1098
- }
1099
- }
1100
- return null;
1101
- }
1102
-
1103
- /**
1104
- * any links that have been received for this relationship
1105
- *
1106
- * @public
1107
- * @return
1108
- */
1109
- links() {
1110
- const resource = this._resource();
1111
- return resource && resource.links ? resource.links : null;
1112
- }
1113
-
1114
- /**
1115
- The meta data for the belongs-to relationship.
1116
- Example
1117
- ```javascript
1118
- // models/blog.js
1119
- import { Model, belongsTo } from '@warp-drive/legacy/model';
1120
- export default Model.extend({
1121
- user: belongsTo('user', { async: true, inverse: null })
1122
- });
1123
- let blog = store.push({
1124
- data: {
1125
- type: 'blog',
1126
- id: 1,
1127
- relationships: {
1128
- user: {
1129
- links: {
1130
- related: {
1131
- href: '/articles/1/author'
1132
- },
1133
- },
1134
- meta: {
1135
- lastUpdated: 1458014400000
1136
- }
1137
- }
1138
- }
1139
- }
1140
- });
1141
- let userRef = blog.belongsTo('user');
1142
- userRef.meta() // { lastUpdated: 1458014400000 }
1143
- ```
1144
- @public
1145
- @return The meta information for the belongs-to relationship.
1146
- */
1147
- meta() {
1148
- let meta = null;
1149
- const resource = this._resource();
1150
- if (resource && resource.meta && typeof resource.meta === 'object') {
1151
- meta = resource.meta;
1152
- }
1153
- return meta;
1154
- }
1155
- _resource() {
1156
- // eslint-disable-next-line @typescript-eslint/no-unused-expressions
1157
- this._ref; // subscribe
1158
- const cache = this.store.cache;
1159
- return cache.getRelationship(this.___identifier, this.key);
1160
- }
1161
-
1162
- /**
1163
- This returns a string that represents how the reference will be
1164
- looked up when it is loaded. If the relationship has a link it will
1165
- use the "link" otherwise it defaults to "id".
1166
- Example
1167
- ```js [app/models/post.js]
1168
- import Model, { hasMany } from '@warp-drive/legacy/model';
1169
- export default class PostModel extends Model {
1170
- @hasMany('comment', { async: true, inverse: null }) comments;
1171
- }
1172
- ```
1173
- ```javascript
1174
- let post = store.push({
1175
- data: {
1176
- type: 'post',
1177
- id: 1,
1178
- relationships: {
1179
- comments: {
1180
- data: [{ type: 'comment', id: 1 }]
1181
- }
1182
- }
1183
- }
1184
- });
1185
- let commentsRef = post.hasMany('comments');
1186
- // get the identifier of the reference
1187
- if (commentsRef.remoteType() === "ids") {
1188
- let ids = commentsRef.ids();
1189
- } else if (commentsRef.remoteType() === "link") {
1190
- let link = commentsRef.link();
1191
- }
1192
- ```
1193
- @public
1194
- @return The name of the remote type. This should either be `link` or `id`
1195
- */
1196
- remoteType() {
1197
- const value = this._resource();
1198
- if (isResourceIdentiferWithRelatedLinks(value)) {
1199
- return 'link';
1200
- }
1201
- return 'id';
1202
- }
1203
-
1204
- /**
1205
- `push` can be used to update the data in the relationship and WarpDrive
1206
- will treat the new data as the canonical value of this relationship on
1207
- the backend. A value of `null` (e.g. `{ data: null }`) can be passed to
1208
- clear the relationship.
1209
- Example model
1210
- ```js [app/models/blog.js]
1211
- import { Model, belongsTo } from '@warp-drive/legacy/model';
1212
- export default class BlogModel extends Model {
1213
- @belongsTo('user', { async: true, inverse: null }) user;
1214
- }
1215
- ```
1216
- Setup some initial state, note we haven't loaded the user yet:
1217
- ```js
1218
- const blog = store.push({
1219
- data: {
1220
- type: 'blog',
1221
- id: '1',
1222
- relationships: {
1223
- user: {
1224
- data: { type: 'user', id: '1' }
1225
- }
1226
- }
1227
- }
1228
- });
1229
- const userRef = blog.belongsTo('user');
1230
- userRef.id(); // '1'
1231
- ```
1232
- Update the state using `push`, note we can do this even without
1233
- having loaded the user yet by providing a resource-identifier.
1234
- Both full a resource and a resource-identifier are supported.
1235
- ```js
1236
- await userRef.push({
1237
- data: {
1238
- type: 'user',
1239
- id: '2',
1240
- }
1241
- });
1242
- userRef.id(); // '2'
1243
- ```
1244
- You may also pass in links and meta fore the relationship, and sideload
1245
- additional resources that might be required.
1246
- ```js
1247
- await userRef.push({
1248
- data: {
1249
- type: 'user',
1250
- id: '2',
1251
- },
1252
- links: {
1253
- related: '/articles/1/author'
1254
- },
1255
- meta: {
1256
- lastUpdated: Date.now()
1257
- },
1258
- included: [
1259
- {
1260
- type: 'user-preview',
1261
- id: '2',
1262
- attributes: {
1263
- username: '@runspired'
1264
- }
1265
- }
1266
- ]
1267
- });
1268
- ```
1269
- By default, the store will attempt to fetch the record if it is not loaded or its
1270
- resource data is not included in the call to `push` before resolving the returned
1271
- promise with the new state..
1272
- Alternatively, pass `true` as the second argument to avoid fetching unloaded records
1273
- and instead the promise will resolve with void without attempting to fetch. This is
1274
- particularly useful if you want to update the state of the relationship without
1275
- forcing the load of all of the associated record.
1276
- @public
1277
- @param doc a JSONAPI document object describing the new value of this relationship.
1278
- @param skipFetch [optional] if `true`, do not attempt to fetch unloaded records
1279
- @return a promise that resolves with the record in this belongs-to relationship after the push has completed.
1280
- */
1281
- async push(doc, skipFetch) {
1282
- const {
1283
- store
1284
- } = this;
1285
- const isResourceData = doc.data && isMaybeResource(doc.data);
1286
- const added = isResourceData ? store._push(doc, true) : doc.data ? store.cacheKeyManager.getOrCreateRecordIdentifier(doc.data) : null;
1287
- const {
1288
- identifier
1289
- } = this.belongsToRelationship;
1290
- if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
1291
- if (added) {
1292
- assertPolymorphicType(identifier, this.belongsToRelationship.definition, added, store);
1293
- }
1294
- }
1295
- const newData = {};
1296
-
1297
- // only set data if it was passed in
1298
- if (doc.data || doc.data === null) {
1299
- newData.data = added;
1300
- }
1301
- if ('links' in doc) {
1302
- newData.links = doc.links;
1303
- }
1304
- if ('meta' in doc) {
1305
- newData.meta = doc.meta;
1306
- }
1307
- assertPrivateStore(store);
1308
- store._join(() => {
1309
- this.graph.push({
1310
- op: 'updateRelationship',
1311
- record: identifier,
1312
- field: this.key,
1313
- value: newData
1314
- });
1315
- });
1316
- if (!skipFetch) return this.load();
1317
- }
1318
-
1319
- /**
1320
- `value()` synchronously returns the current value of the belongs-to
1321
- relationship. Unlike `record.relationshipName`, calling
1322
- `value()` on a reference does not trigger a fetch if the async
1323
- relationship is not yet loaded. If the relationship is not loaded
1324
- it will always return `null`.
1325
- Example
1326
- ```javascript
1327
- // models/blog.js
1328
- import { Model, belongsTo } from '@warp-drive/legacy/model';
1329
- export default class BlogModel extends Model {
1330
- @belongsTo('user', { async: true, inverse: null }) user;
1331
- }
1332
- let blog = store.push({
1333
- data: {
1334
- type: 'blog',
1335
- id: 1,
1336
- relationships: {
1337
- user: {
1338
- data: { type: 'user', id: 1 }
1339
- }
1340
- }
1341
- }
1342
- });
1343
- let userRef = blog.belongsTo('user');
1344
- userRef.value(); // null
1345
- // provide data for reference
1346
- userRef.push({
1347
- data: {
1348
- type: 'user',
1349
- id: 1,
1350
- attributes: {
1351
- username: "@user"
1352
- }
1353
- }
1354
- }).then(function(user) {
1355
- userRef.value(); // user
1356
- });
1357
- ```
1358
- @public
1359
- @return the record in this relationship
1360
- */
1361
- value() {
1362
- const resource = this._resource();
1363
- return resource && resource.data ? this.store.peekRecord(resource.data) : null;
1364
- }
1365
-
1366
- /**
1367
- Loads a record in a belongs-to relationship if it is not already
1368
- loaded. If the relationship is already loaded this method does not
1369
- trigger a new load.
1370
- Example
1371
- ```javascript
1372
- // models/blog.js
1373
- import { Model, belongsTo } from '@warp-drive/legacy/model';
1374
- export default class BlogModel extends Model {
1375
- @belongsTo('user', { async: true, inverse: null }) user;
1376
- }
1377
- let blog = store.push({
1378
- data: {
1379
- type: 'blog',
1380
- id: 1,
1381
- relationships: {
1382
- user: {
1383
- data: { type: 'user', id: 1 }
1384
- }
1385
- }
1386
- }
1387
- });
1388
- let userRef = blog.belongsTo('user');
1389
- userRef.value(); // null
1390
- userRef.load().then(function(user) {
1391
- userRef.value() === user
1392
- });
1393
- ```
1394
- You may also pass in an options object whose properties will be
1395
- fed forward. This enables you to pass `adapterOptions` into the
1396
- request given to the adapter via the reference.
1397
- Example
1398
- ```javascript
1399
- userRef.load({ adapterOptions: { isPrivate: true } }).then(function(user) {
1400
- userRef.value() === user;
1401
- });
1402
- ```
1403
- ```js [app/adapters/user.js]
1404
- import Adapter from '@warp-drive/legacy/adapter';
1405
- export default class UserAdapter extends Adapter {
1406
- findRecord(store, type, id, snapshot) {
1407
- // In the adapter you will have access to adapterOptions.
1408
- let adapterOptions = snapshot.adapterOptions;
1409
- }
1410
- });
1411
- ```
1412
- @public
1413
- @param options the options to pass in.
1414
- @return a promise that resolves with the record in this belongs-to relationship.
1415
- */
1416
- async load(options) {
1417
- const support = LEGACY_SUPPORT.get(this.___identifier);
1418
- const fetchSyncRel = !this.belongsToRelationship.definition.isAsync && !areAllInverseRecordsLoaded(this.store, this._resource());
1419
- return fetchSyncRel ? support.reloadBelongsTo(this.key, options).then(() => this.value()) :
1420
- // we cast to fix the return type since typescript and eslint don't understand async functions
1421
- // properly
1422
- support.getBelongsTo(this.key, options);
1423
- }
1424
-
1425
- /**
1426
- Triggers a reload of the value in this relationship. If the
1427
- remoteType is `"link"` WarpDrive will use the relationship link to
1428
- reload the relationship. Otherwise it will reload the record by its
1429
- id.
1430
- Example
1431
- ```javascript
1432
- // models/blog.js
1433
- import { Model, belongsTo } from '@warp-drive/legacy/model';
1434
- export default class BlogModel extends Model {
1435
- @belongsTo('user', { async: true, inverse: null }) user;
1436
- }
1437
- let blog = store.push({
1438
- data: {
1439
- type: 'blog',
1440
- id: 1,
1441
- relationships: {
1442
- user: {
1443
- data: { type: 'user', id: 1 }
1444
- }
1445
- }
1446
- }
1447
- });
1448
- let userRef = blog.belongsTo('user');
1449
- userRef.reload().then(function(user) {
1450
- userRef.value() === user
1451
- });
1452
- ```
1453
- You may also pass in an options object whose properties will be
1454
- fed forward. This enables you to pass `adapterOptions` into the
1455
- request given to the adapter via the reference. A full example
1456
- can be found in the `load` method.
1457
- Example
1458
- ```javascript
1459
- userRef.reload({ adapterOptions: { isPrivate: true } })
1460
- ```
1461
- @public
1462
- @param options the options to pass in.
1463
- @return a promise that resolves with the record in this belongs-to relationship after the reload has completed.
1464
- */
1465
- reload(options) {
1466
- const support = LEGACY_SUPPORT.get(this.___identifier);
1467
- return support.reloadBelongsTo(this.key, options).then(() => this.value());
1468
- }
1469
- }
1470
- defineNonEnumerableSignal(BelongsToReference.prototype, '_ref', 0);
1471
- const LEGACY_SUPPORT = getOrSetGlobal('LEGACY_SUPPORT', new Map());
1472
- function lookupLegacySupport(record) {
1473
- const identifier = recordIdentifierFor(record);
1474
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1475
- if (!test) {
1476
- throw new Error(`Expected a record`);
1477
- }
1478
- })(identifier) : {};
1479
- let support = LEGACY_SUPPORT.get(identifier);
1480
- if (!support) {
1481
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1482
- if (!test) {
1483
- throw new Error(`Memory Leak Detected`);
1484
- }
1485
- })(!record.isDestroyed && !record.isDestroying) : {};
1486
- support = new LegacySupport(record, identifier);
1487
- LEGACY_SUPPORT.set(identifier, support);
1488
- }
1489
- return support;
1490
- }
1491
-
1492
- /**
1493
- * @hideconstructor
1494
- */
1495
- class LegacySupport {
1496
- /** @internal */
1497
-
1498
- /** @internal */
1499
-
1500
- /** @internal */
1501
-
1502
- /** @internal */
1503
-
1504
- /** @internal */
1505
-
1506
- /** @internal */
1507
-
1508
- /** @internal */
1509
-
1510
- /** @internal */
1511
-
1512
- /** @internal */
1513
-
1514
- /** @internal */
1515
-
1516
- /** @internal */
1517
-
1518
- constructor(record, identifier) {
1519
- this.record = record;
1520
- this.store = isPrivateStore(storeFor(record, false));
1521
- this.identifier = identifier;
1522
- this.cache = this.store.cache;
1523
- if (this.store._graph) {
1524
- this.graph = this.store._graph;
1525
- }
1526
- this._manyArrayCache = Object.create(null);
1527
- this._relationshipPromisesCache = Object.create(null);
1528
- this._relationshipProxyCache = Object.create(null);
1529
- this._pending = Object.create(null);
1530
- this.references = Object.create(null);
1531
- }
1532
-
1533
- /** @private */
1534
- _syncArray(array) {
1535
- // It’s possible the parent side of the relationship may have been destroyed by this point
1536
- if (this.isDestroyed || this.isDestroying) {
1537
- return;
1538
- }
1539
- const currentState = array[Context].source;
1540
- const identifier = this.identifier;
1541
- const [identifiers, jsonApi] = this._getCurrentState(identifier, array.key);
1542
- if (jsonApi.meta) {
1543
- array.meta = jsonApi.meta;
1544
- }
1545
- if (jsonApi.links) {
1546
- array.links = jsonApi.links;
1547
- }
1548
- currentState.length = 0;
1549
- fastPush(currentState, identifiers);
1550
- }
1551
- mutate(mutation) {
1552
- this.cache.mutate(mutation);
1553
- }
1554
- _findBelongsTo(key, resource, relationship, options) {
1555
- const name = getRealFieldName(this, key);
1556
-
1557
- // TODO @runspired follow up if parent isNew then we should not be attempting load here
1558
- // TODO @runspired follow up on whether this should be in the relationship requests cache
1559
- return this._findBelongsToByJsonApiResource(resource, this.identifier, relationship, options).then(identifier => handleCompletedRelationshipRequest(this, name, relationship, identifier), e => handleCompletedRelationshipRequest(this, name, relationship, null, e));
1560
- }
1561
- reloadBelongsTo(key, options) {
1562
- const loadingPromise = this._relationshipPromisesCache[key];
1563
- if (loadingPromise) {
1564
- return loadingPromise;
1565
- }
1566
- const name = getRealFieldName(this, key);
1567
- const resource = this.store.cache.getRelationship(this.identifier, name);
1568
- const relationship = this.graph.get(this.identifier, name);
1569
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1570
- if (!test) {
1571
- throw new Error(`Expected ${key === name ? name : `${key} (source: ${name})`} to be a belongs-to relationship`);
1572
- }
1573
- })(isBelongsTo(relationship)) : {};
1574
- relationship.state.hasFailedLoadAttempt = false;
1575
- relationship.state.shouldForceReload = true;
1576
- const promise = this._findBelongsTo(name, resource, relationship, options);
1577
- if (this._relationshipProxyCache[name]) {
1578
- // @ts-expect-error
1579
- return this._updatePromiseProxyFor('belongsTo', name, {
1580
- promise
1581
- });
1582
- }
1583
- return promise;
1584
- }
1585
- getBelongsTo(key, options) {
1586
- const {
1587
- identifier
1588
- } = this;
1589
- const name = getRealFieldName(this, key);
1590
- const resource = this.store.cache.getRelationship(this.identifier, name);
1591
- const relatedIdentifier = resource && resource.data ? resource.data : null;
1592
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1593
- if (!test) {
1594
- throw new Error(`Expected a stable identifier`);
1595
- }
1596
- })(!relatedIdentifier || isResourceKey(relatedIdentifier)) : {};
1597
- const store = this.store;
1598
- const relationship = this.graph.get(this.identifier, name);
1599
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1600
- if (!test) {
1601
- throw new Error(`Expected ${key === name ? name : `${key} (source: ${name})`} to be a belongs-to relationship`);
1602
- }
1603
- })(isBelongsTo(relationship)) : {};
1604
- const isAsync = relationship.definition.isAsync;
1605
- const _belongsToState = {
1606
- key,
1607
- store,
1608
- legacySupport: this,
1609
- modelName: relationship.definition.type
1610
- };
1611
- if (isAsync) {
1612
- if (relationship.state.hasFailedLoadAttempt) {
1613
- return this._relationshipProxyCache[name];
1614
- }
1615
- const promise = this._findBelongsTo(name, resource, relationship, options);
1616
- const isLoaded = relatedIdentifier && store._instanceCache.recordIsLoaded(relatedIdentifier);
1617
- return this._updatePromiseProxyFor('belongsTo', name, {
1618
- promise,
1619
- content: isLoaded ? store._instanceCache.getRecord(relatedIdentifier) : null,
1620
- _belongsToState
1621
- });
1622
- } else {
1623
- if (relatedIdentifier === null) {
1624
- return null;
1625
- } else {
1626
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1627
- if (!test) {
1628
- throw new Error(`You looked up the '${key === name ? name : `${key} (source: ${name})`}' relationship on a '${identifier.type}' with id ${identifier.id || 'null'} but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (\`belongsTo(<type>, { async: true, inverse: <inverse> })\`)`);
1629
- }
1630
- })(store._instanceCache.recordIsLoaded(relatedIdentifier, true)) : {};
1631
- return store._instanceCache.getRecord(relatedIdentifier);
1632
- }
1633
- }
1634
- }
1635
- setDirtyBelongsTo(key, value) {
1636
- const name = getRealFieldName(this, key);
1637
- return this.cache.mutate({
1638
- op: 'replaceRelatedRecord',
1639
- record: this.identifier,
1640
- field: name,
1641
- value: extractIdentifierFromRecord(value)
1642
- },
1643
- // @ts-expect-error
1644
- true);
1645
- }
1646
- _getCurrentState(identifier, field) {
1647
- const jsonApi = this.cache.getRelationship(identifier, field);
1648
- const cache = this.store._instanceCache;
1649
- const identifiers = [];
1650
- if (jsonApi.data) {
1651
- for (let i = 0; i < jsonApi.data.length; i++) {
1652
- const relatedIdentifier = jsonApi.data[i];
1653
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1654
- if (!test) {
1655
- throw new Error(`Expected a stable identifier`);
1656
- }
1657
- })(isResourceKey(relatedIdentifier)) : {};
1658
- if (cache.recordIsLoaded(relatedIdentifier, true)) {
1659
- identifiers.push(relatedIdentifier);
1660
- }
1661
- }
1662
- }
1663
- return [identifiers, jsonApi];
1664
- }
1665
- getManyArray(key, definition) {
1666
- const name = getRealFieldName(this, key);
1667
- if (this.graph) {
1668
- let manyArray = this._manyArrayCache[name];
1669
- if (!definition) {
1670
- definition = this.graph.get(this.identifier, name).definition;
1671
- }
1672
- if (!manyArray) {
1673
- const [identifiers, doc] = this._getCurrentState(this.identifier, name);
1674
- const field = getField(this, name);
1675
- manyArray = createLegacyManyArray({
1676
- store: this.store,
1677
- // @ts-expect-error Typescript doesn't have a way for us to thread the generic backwards so it infers unknown instead of T
1678
- manager: this,
1679
- source: identifiers,
1680
- type: definition.type,
1681
- isLoaded: !definition.isAsync,
1682
- editable: true,
1683
- isAsync: definition.isAsync,
1684
- isPolymorphic: definition.isPolymorphic,
1685
- field: field,
1686
- identifier: this.identifier,
1687
- links: doc.links || null,
1688
- meta: doc.meta || null
1689
- });
1690
- this._manyArrayCache[name] = manyArray;
1691
- }
1692
- return manyArray;
1693
- }
1694
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1695
- {
1696
- throw new Error('hasMany only works with the JSONAPICache');
1697
- }
1698
- })() : {};
1699
- }
1700
- fetchAsyncHasMany(key, relationship, manyArray, options) {
1701
- const name = getRealFieldName(this, key);
1702
- if (this.graph) {
1703
- let loadingPromise = this._relationshipPromisesCache[name];
1704
- if (loadingPromise) {
1705
- return loadingPromise;
1706
- }
1707
- const jsonApi = this.cache.getRelationship(this.identifier, name);
1708
- const promise = this._findHasManyByJsonApiResource(jsonApi, this.identifier, relationship, options);
1709
- if (!promise) {
1710
- manyArray.isLoaded = true;
1711
- return Promise.resolve(manyArray);
1712
- }
1713
- loadingPromise = promise.then(() => handleCompletedRelationshipRequest(this, name, relationship, manyArray), e => handleCompletedRelationshipRequest(this, name, relationship, manyArray, e));
1714
- this._relationshipPromisesCache[name] = loadingPromise;
1715
- return loadingPromise;
1716
- }
1717
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1718
- {
1719
- throw new Error('hasMany only works with the JSONAPICache');
1720
- }
1721
- })() : {};
1722
- }
1723
- reloadHasMany(key, options) {
1724
- const name = getRealFieldName(this, key);
1725
- if (this.graph) {
1726
- const loadingPromise = this._relationshipPromisesCache[name];
1727
- if (loadingPromise) {
1728
- return loadingPromise;
1729
- }
1730
- const relationship = this.graph.get(this.identifier, name);
1731
- const {
1732
- definition,
1733
- state
1734
- } = relationship;
1735
- state.hasFailedLoadAttempt = false;
1736
- state.shouldForceReload = true;
1737
- const manyArray = this.getManyArray(name, definition);
1738
- const promise = this.fetchAsyncHasMany(name, relationship, manyArray, options);
1739
- if (this._relationshipProxyCache[name]) {
1740
- return this._updatePromiseProxyFor('hasMany', name, {
1741
- promise
1742
- });
1743
- }
1744
- return promise;
1745
- }
1746
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1747
- {
1748
- throw new Error(`hasMany only works with the JSONAPICache`);
1749
- }
1750
- })() : {};
1751
- }
1752
- getHasMany(key, options) {
1753
- const name = getRealFieldName(this, key);
1754
- if (this.graph) {
1755
- const relationship = this.graph.get(this.identifier, name);
1756
- const {
1757
- definition,
1758
- state
1759
- } = relationship;
1760
- const manyArray = this.getManyArray(name, definition);
1761
- if (definition.isAsync) {
1762
- if (state.hasFailedLoadAttempt) {
1763
- return this._relationshipProxyCache[name];
1764
- }
1765
- const promise = this.fetchAsyncHasMany(name, relationship, manyArray, options);
1766
- return this._updatePromiseProxyFor('hasMany', name, {
1767
- promise,
1768
- content: manyArray
1769
- });
1770
- } else {
1771
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1772
- if (!test) {
1773
- throw new Error(`You looked up the '${key === name ? name : `${key} (source: ${name})`}' relationship on a '${this.identifier.type}' with id ${this.identifier.id || 'null'} but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async ('hasMany(<type>, { async: true, inverse: <inverse> })')`);
1774
- }
1775
- })(!anyUnloaded(this.store, relationship)) : {};
1776
- return manyArray;
1777
- }
1778
- }
1779
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1780
- {
1781
- throw new Error(`hasMany only works with the JSONAPICache`);
1782
- }
1783
- })() : {};
1784
- }
1785
- _updatePromiseProxyFor(kind, key, args) {
1786
- let promiseProxy = this._relationshipProxyCache[key];
1787
- if (kind === 'hasMany') {
1788
- const {
1789
- promise,
1790
- content
1791
- } = args;
1792
- if (promiseProxy) {
1793
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1794
- if (!test) {
1795
- throw new Error(`Expected a PromiseManyArray`);
1796
- }
1797
- })('_update' in promiseProxy) : {};
1798
- promiseProxy._update(promise, content);
1799
- } else {
1800
- promiseProxy = this._relationshipProxyCache[key] = new PromiseManyArray(promise, content);
1801
- }
1802
- return promiseProxy;
1803
- }
1804
- if (promiseProxy) {
1805
- const {
1806
- promise,
1807
- content
1808
- } = args;
1809
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1810
- if (!test) {
1811
- throw new Error(`Expected a PromiseBelongsTo`);
1812
- }
1813
- })('_belongsToState' in promiseProxy) : {};
1814
- if (content !== undefined) {
1815
- promiseProxy.set('content', content);
1816
- }
1817
- void promiseProxy.set('promise', promise);
1818
- } else {
1819
- promiseProxy = PromiseBelongsTo.create(args);
1820
- this._relationshipProxyCache[key] = promiseProxy;
1821
- }
1822
- return promiseProxy;
1823
- }
1824
- referenceFor(kind, key) {
1825
- const name = getRealFieldName(this, key);
1826
- let reference = this.references[name];
1827
- if (!reference) {
1828
- if (!this.graph) {
1829
- // TODO @runspired while this feels odd, it is not a regression in capability because we do
1830
- // not today support references pulling from RecordDatas other than our own
1831
- // because of the intimate API access involved. This is something we will need to redesign.
1832
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1833
- {
1834
- throw new Error(`snapshot.belongsTo only supported when using the JSONAPICache`);
1835
- }
1836
- })() : {};
1837
- }
1838
- const {
1839
- graph,
1840
- identifier
1841
- } = this;
1842
- const relationship = graph.get(identifier, name);
1843
- if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
1844
- if (kind) {
1845
- const modelName = identifier.type;
1846
- const actualRelationshipKind = relationship.definition.kind;
1847
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1848
- if (!test) {
1849
- throw new Error(`You tried to get the '${key === name ? name : `${key} (source: ${name})`}' relationship on a '${modelName}' via record.${kind}('${key}'), but the relationship is of kind '${actualRelationshipKind}'. Use record.${actualRelationshipKind}('${key}') instead.`);
1850
- }
1851
- })(actualRelationshipKind === kind) : {};
1852
- }
1853
- }
1854
- const relationshipKind = relationship.definition.kind;
1855
- if (relationshipKind === 'belongsTo') {
1856
- reference = new BelongsToReference(this.store, graph, identifier, relationship, key);
1857
- } else if (relationshipKind === 'hasMany') {
1858
- reference = new HasManyReference(this.store, graph, identifier, relationship, key);
1859
- }
1860
- this.references[name] = reference;
1861
- }
1862
- return reference;
1863
- }
1864
- _findHasManyByJsonApiResource(resource, parentIdentifier, relationship, options = {}) {
1865
- if (this.graph) {
1866
- if (!resource) {
1867
- return;
1868
- }
1869
- const {
1870
- definition,
1871
- state
1872
- } = relationship;
1873
- upgradeStore(this.store);
1874
- const adapter = this.store.adapterFor?.(definition.type);
1875
- const {
1876
- isStale,
1877
- hasDematerializedInverse,
1878
- hasReceivedData,
1879
- isEmpty,
1880
- shouldForceReload
1881
- } = state;
1882
- const allInverseRecordsAreLoaded = areAllInverseRecordsLoaded(this.store, resource);
1883
- const identifiers = resource.data;
1884
- const shouldFindViaLink = resource.links && resource.links.related && (typeof adapter?.findHasMany === 'function' || typeof identifiers === 'undefined') && (shouldForceReload || hasDematerializedInverse || isStale || !allInverseRecordsAreLoaded && !isEmpty);
1885
- const field = this.store.schema.fields({
1886
- type: definition.inverseType
1887
- }).get(definition.key);
1888
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1889
- if (!test) {
1890
- throw new Error(`Expected a hasMany field definition for ${definition.inverseType}.${definition.key}`);
1891
- }
1892
- })(field && field.kind === 'hasMany') : {};
1893
- const request = {
1894
- useLink: shouldFindViaLink,
1895
- field,
1896
- links: resource.links,
1897
- meta: resource.meta,
1898
- options,
1899
- record: parentIdentifier
1900
- };
1901
-
1902
- // fetch via link
1903
- if (shouldFindViaLink) {
1904
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1905
- if (!test) {
1906
- throw new Error(`Expected collection to be an array`);
1907
- }
1908
- })(!identifiers || Array.isArray(identifiers)) : {};
1909
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1910
- if (!test) {
1911
- throw new Error(`Expected stable identifiers`);
1912
- }
1913
- })(!identifiers || identifiers.every(isResourceKey)) : {};
1914
- const req = field.options.linksMode ? {
1915
- url: getRelatedLink(resource),
1916
- op: 'findHasMany',
1917
- method: 'GET',
1918
- records: identifiers || [],
1919
- data: request,
1920
- [EnableHydration]: false
1921
- } : {
1922
- op: 'findHasMany',
1923
- records: identifiers || [],
1924
- data: request,
1925
- cacheOptions: {
1926
- [Symbol.for('wd:skip-cache')]: true
1927
- }
1928
- };
1929
- return this.store.request(req);
1930
- }
1931
- const preferLocalCache = hasReceivedData && !isEmpty;
1932
- const hasLocalPartialData = hasDematerializedInverse || isEmpty && Array.isArray(identifiers) && identifiers.length > 0;
1933
- const attemptLocalCache = !shouldForceReload && !isStale && (preferLocalCache || hasLocalPartialData);
1934
- if (attemptLocalCache && allInverseRecordsAreLoaded) {
1935
- return;
1936
- }
1937
- const hasData = hasReceivedData && !isEmpty;
1938
- if (attemptLocalCache || hasData || hasLocalPartialData) {
1939
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1940
- if (!test) {
1941
- throw new Error(`Expected collection to be an array`);
1942
- }
1943
- })(Array.isArray(identifiers)) : {};
1944
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1945
- if (!test) {
1946
- throw new Error(`Expected stable identifiers`);
1947
- }
1948
- })(identifiers.every(isResourceKey)) : {};
1949
- options.reload = options.reload || !attemptLocalCache || undefined;
1950
- return this.store.request({
1951
- op: 'findHasMany',
1952
- records: identifiers,
1953
- data: request,
1954
- cacheOptions: {
1955
- [Symbol.for('wd:skip-cache')]: true
1956
- }
1957
- });
1958
- }
1959
-
1960
- // we were explicitly told we have no data and no links.
1961
- // TODO if the relationshipIsStale, should we hit the adapter anyway?
1962
- return;
1963
- }
1964
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1965
- {
1966
- throw new Error(`hasMany only works with the JSONAPICache`);
1967
- }
1968
- })() : {};
1969
- }
1970
- _findBelongsToByJsonApiResource(resource, parentIdentifier, relationship, options = {}) {
1971
- if (!resource) {
1972
- return Promise.resolve(null);
1973
- }
1974
- const key = relationship.definition.key;
1975
- const name = getRealFieldName(this, key);
1976
-
1977
- // interleaved promises mean that we MUST cache this here
1978
- // in order to prevent infinite re-render if the request
1979
- // fails.
1980
- if (this._pending[name]) {
1981
- return this._pending[name];
1982
- }
1983
- const identifier = resource.data ? resource.data : null;
1984
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1985
- if (!test) {
1986
- throw new Error(`Expected a stable identifier`);
1987
- }
1988
- })(!identifier || isResourceKey(identifier)) : {};
1989
- const {
1990
- isStale,
1991
- hasDematerializedInverse,
1992
- hasReceivedData,
1993
- isEmpty,
1994
- shouldForceReload
1995
- } = relationship.state;
1996
- const allInverseRecordsAreLoaded = areAllInverseRecordsLoaded(this.store, resource);
1997
- const shouldFindViaLink = resource.links?.related && (shouldForceReload || hasDematerializedInverse || isStale || !allInverseRecordsAreLoaded && !isEmpty);
1998
- const field = this.store.schema.fields(this.identifier).get(relationship.definition.key);
1999
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2000
- if (!test) {
2001
- throw new Error(`Attempted to access a belongsTo relationship but no definition exists for it`);
2002
- }
2003
- })(field && field.kind === 'belongsTo') : {};
2004
- const request = {
2005
- useLink: shouldFindViaLink,
2006
- field,
2007
- links: resource.links,
2008
- meta: resource.meta,
2009
- options,
2010
- record: parentIdentifier
2011
- };
2012
-
2013
- // fetch via link
2014
- if (shouldFindViaLink) {
2015
- const req = field.options.linksMode ? {
2016
- url: getRelatedLink(resource),
2017
- op: 'findBelongsTo',
2018
- method: 'GET',
2019
- records: identifier ? [identifier] : [],
2020
- data: request,
2021
- [EnableHydration]: false
2022
- } : {
2023
- op: 'findBelongsTo',
2024
- records: identifier ? [identifier] : [],
2025
- data: request,
2026
- cacheOptions: {
2027
- [Symbol.for('wd:skip-cache')]: true
2028
- }
2029
- };
2030
- const future = this.store.request(req);
2031
- this._pending[name] = future.then(doc => field.options.linksMode ? doc.content.data : doc.content).finally(() => {
2032
- this._pending[name] = undefined;
2033
- });
2034
- return this._pending[name];
2035
- }
2036
- const preferLocalCache = hasReceivedData && allInverseRecordsAreLoaded && !isEmpty;
2037
- const hasLocalPartialData = hasDematerializedInverse || isEmpty && resource.data;
2038
- // null is explicit empty, undefined is "we don't know anything"
2039
- const localDataIsEmpty = !identifier;
2040
- const attemptLocalCache = !shouldForceReload && !isStale && (preferLocalCache || hasLocalPartialData);
2041
-
2042
- // we dont need to fetch and are empty
2043
- if (attemptLocalCache && localDataIsEmpty) {
2044
- return Promise.resolve(null);
2045
- }
2046
-
2047
- // we dont need to fetch because we are local state
2048
- const resourceIsLocal = identifier?.id === null;
2049
- if (attemptLocalCache && allInverseRecordsAreLoaded || resourceIsLocal) {
2050
- return Promise.resolve(identifier);
2051
- }
2052
-
2053
- // we may need to fetch
2054
- if (identifier) {
2055
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2056
- if (!test) {
2057
- throw new Error(`Cannot fetch belongs-to relationship with no information`);
2058
- }
2059
- })(identifier) : {};
2060
- options.reload = options.reload || !attemptLocalCache || undefined;
2061
- this._pending[name] = this.store.request({
2062
- op: 'findBelongsTo',
2063
- records: [identifier],
2064
- data: request,
2065
- cacheOptions: {
2066
- [Symbol.for('wd:skip-cache')]: true
2067
- }
2068
- }).then(doc => doc.content).finally(() => {
2069
- this._pending[name] = undefined;
2070
- });
2071
- return this._pending[name];
2072
- }
2073
-
2074
- // we were explicitly told we have no data and no links.
2075
- // TODO if the relationshipIsStale, should we hit the adapter anyway?
2076
- return Promise.resolve(null);
2077
- }
2078
- destroy() {
2079
- this.isDestroying = true;
2080
- let cache = this._manyArrayCache;
2081
- this._manyArrayCache = Object.create(null);
2082
- Object.keys(cache).forEach(key => {
2083
- cache[key].destroy();
2084
- });
2085
- cache = this._relationshipProxyCache;
2086
- this._relationshipProxyCache = Object.create(null);
2087
- Object.keys(cache).forEach(key => {
2088
- const proxy = cache[key];
2089
- if (proxy.destroy) {
2090
- proxy.destroy();
2091
- }
2092
- });
2093
- cache = this.references;
2094
- this.references = Object.create(null);
2095
- Object.keys(cache).forEach(key => {
2096
- cache[key].destroy();
2097
- });
2098
- this.isDestroyed = true;
2099
- }
2100
- }
2101
- function getRelatedLink(resource) {
2102
- const related = resource.links?.related;
2103
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2104
- if (!test) {
2105
- throw new Error(`Expected a related link`);
2106
- }
2107
- })(related) : {};
2108
- return typeof related === 'object' ? related.href : related;
2109
- }
2110
- function handleCompletedRelationshipRequest(recordExt, key, relationship, value, error) {
2111
- delete recordExt._relationshipPromisesCache[key];
2112
- relationship.state.shouldForceReload = false;
2113
- const isHasMany = relationship.definition.kind === 'hasMany';
2114
- if (isHasMany) {
2115
- // we don't notify the record property here to avoid refetch
2116
- // only the many array
2117
- notifyInternalSignal(value[Context].signal);
2118
- }
2119
- if (error) {
2120
- relationship.state.hasFailedLoadAttempt = true;
2121
- const proxy = recordExt._relationshipProxyCache[key];
2122
- // belongsTo relationships are sometimes unloaded
2123
- // when a load fails, in this case we need
2124
- // to make sure that we aren't proxying
2125
- // to destroyed content
2126
- // for the sync belongsTo reload case there will be no proxy
2127
- // for the async reload case there will be no proxy if the ui
2128
- // has never been accessed
2129
- if (proxy && !isHasMany) {
2130
- // @ts-expect-error unsure why this is not resolving the boolean but async belongsTo is weird
2131
- if (proxy.content && proxy.content.isDestroying) {
2132
- proxy.set('content', null);
2133
- }
2134
- recordExt.store.notifications._flush();
2135
- }
2136
- throw error;
2137
- }
2138
- if (isHasMany) {
2139
- value.isLoaded = true;
2140
- } else {
2141
- recordExt.store.notifications._flush();
2142
- }
2143
- relationship.state.hasFailedLoadAttempt = false;
2144
- // only set to not stale if no error is thrown
2145
- relationship.state.isStale = false;
2146
- return isHasMany || !value ? value : recordExt.store.peekRecord(value);
2147
- }
2148
- function extractIdentifierFromRecord(record) {
2149
- if (!record) {
2150
- return null;
2151
- }
2152
- return recordIdentifierFor(record);
2153
- }
2154
- function anyUnloaded(store, relationship) {
2155
- assertPrivateStore(store);
2156
- const graph = store._graph;
2157
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2158
- if (!test) {
2159
- throw new Error(`Expected a Graph instance to be available`);
2160
- }
2161
- })(graph) : {};
2162
- const relationshipData = graph.getData(relationship.identifier, relationship.definition.key);
2163
- const state = relationshipData.data;
2164
- const cache = store._instanceCache;
2165
- const unloaded = state?.find(s => {
2166
- const isLoaded = cache.recordIsLoaded(s, true);
2167
- return !isLoaded;
2168
- });
2169
- return unloaded || false;
2170
- }
2171
- function areAllInverseRecordsLoaded(store, resource) {
2172
- assertPrivateStore(store);
2173
- const instanceCache = store._instanceCache;
2174
- const identifiers = resource.data;
2175
- if (Array.isArray(identifiers)) {
2176
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2177
- if (!test) {
2178
- throw new Error(`Expected stable identifiers`);
2179
- }
2180
- })(identifiers.every(isResourceKey)) : {};
2181
- // treat as collection
2182
- // check for unloaded records
2183
- return identifiers.every(identifier => instanceCache.recordIsLoaded(identifier));
2184
- }
2185
-
2186
- // treat as single resource
2187
- if (!identifiers) return true;
2188
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2189
- if (!test) {
2190
- throw new Error(`Expected stable identifiers`);
2191
- }
2192
- })(isResourceKey(identifiers)) : {};
2193
- return instanceCache.recordIsLoaded(identifiers);
2194
- }
2195
- function isBelongsTo(relationship) {
2196
- return relationship.definition.kind === 'belongsTo';
2197
- }
2198
- function getField(context, key) {
2199
- const {
2200
- identifier,
2201
- store
2202
- } = context;
2203
- return store.schema.fields(identifier).get(key) ?? store.schema.cacheFields?.(identifier).get(key);
2204
- }
2205
- function getRealFieldName(context, key) {
2206
- const field = getField(context, key);
2207
- return field ? field.sourceKey ?? field.name : key;
2208
- }
2209
-
2210
- // we force the type here to our own construct because mixin and extend patterns
2211
- // lose generic signatures. We also do this because we need to Omit `clear` from
2212
- // the type of ArrayProxy as we override it's signature.
2213
- const ArrayProxyWithCustomOverrides = ArrayProxy;
2214
-
2215
- /**
2216
- Holds validation errors for a given record, organized by attribute names.
2217
-
2218
- This class is not directly instantiable.
2219
-
2220
- Every `Model` has an `errors` property that is an instance of
2221
- `Errors`. This can be used to display validation error
2222
- messages returned from the server when a `record.save()` rejects.
2223
-
2224
- For Example, if you had a `User` model that looked like this:
2225
-
2226
- ```js [app/models/user.js]
2227
- import { Model, attr } from '@warp-drive/legacy/model';
2228
-
2229
- export default class UserModel extends Model {
2230
- @attr('string') username;
2231
- @attr('string') email;
2232
- }
2233
- ```
2234
- And you attempted to save a record that did not validate on the backend:
2235
-
2236
- ```javascript
2237
- let user = store.createRecord('user', {
2238
- username: 'tomster',
2239
- email: 'invalidEmail'
2240
- });
2241
- user.save();
2242
- ```
2243
-
2244
- Your backend would be expected to return an error response that described
2245
- the problem, so that error messages can be generated on the app.
2246
-
2247
- API responses will be translated into instances of `Errors` differently,
2248
- depending on the specific combination of adapter and serializer used. You
2249
- may want to check the documentation or the source code of the libraries
2250
- that you are using, to know how they expect errors to be communicated.
2251
-
2252
- Errors can be displayed to the user by accessing their property name
2253
- to get an array of all the error objects for that property. Each
2254
- error object is a JavaScript object with two keys:
2255
-
2256
- - `message` A string containing the error message from the backend
2257
- - `attribute` The name of the property associated with this error message
2258
-
2259
- ```handlebars
2260
- <label>Username: <Input @value={{@model.username}} /> </label>
2261
- {{#each @model.errors.username as |error|}}
2262
- <div class="error">
2263
- {{error.message}}
2264
- </div>
2265
- {{/each}}
2266
-
2267
- <label>Email: <Input @value={{@model.email}} /> </label>
2268
- {{#each @model.errors.email as |error|}}
2269
- <div class="error">
2270
- {{error.message}}
2271
- </div>
2272
- {{/each}}
2273
- ```
2274
-
2275
- You can also access the special `messages` property on the error
2276
- object to get an array of all the error strings.
2277
-
2278
- ```handlebars
2279
- {{#each @model.errors.messages as |message|}}
2280
- <div class="error">
2281
- {{message}}
2282
- </div>
2283
- {{/each}}
2284
- ```
2285
-
2286
- @class Errors
2287
- @public
2288
- */
2289
- class Errors extends ArrayProxyWithCustomOverrides {
2290
- /**
2291
- @property errorsByAttributeName
2292
- @type {MapWithDefault}
2293
- @private
2294
- */
2295
- get errorsByAttributeName() {
2296
- return new Map();
2297
- }
2298
-
2299
- /**
2300
- Returns errors for a given attribute
2301
- ```javascript
2302
- let user = store.createRecord('user', {
2303
- username: 'tomster',
2304
- email: 'invalidEmail'
2305
- });
2306
- user.save().catch(function(){
2307
- user.errors.errorsFor('email'); // returns:
2308
- // [{attribute: "email", message: "Doesn't look like a valid email."}]
2309
- });
2310
- ```
2311
- @public
2312
- @param {String} attribute
2313
- @return {Array}
2314
- */
2315
- static {
2316
- decorateMethodV2(this.prototype, "errorsByAttributeName", [computed()]);
2317
- }
2318
- errorsFor(attribute) {
2319
- const map = this.errorsByAttributeName;
2320
- let errors = map.get(attribute);
2321
- if (errors === undefined) {
2322
- errors = A();
2323
- map.set(attribute, errors);
2324
- }
2325
-
2326
- // Errors may be a native array with extensions turned on. Since we access
2327
- // the array via a method, and not a computed or using `Ember.get`, it does
2328
- // not entangle properly with autotracking, so we entangle manually by
2329
- // getting the `[]` property.
2330
- get(errors, '[]');
2331
- return errors;
2332
- }
2333
-
2334
- /**
2335
- An array containing all of the error messages for this
2336
- record. This is useful for displaying all errors to the user.
2337
- ```handlebars
2338
- {{#each @model.errors.messages as |message|}}
2339
- <div class="error">
2340
- {{message}}
2341
- </div>
2342
- {{/each}}
2343
- ```
2344
- @property messages
2345
- @public
2346
- @type {Array}
2347
- */
2348
- static {
2349
- decorateFieldV2(this.prototype, "messages", [mapBy('content', 'message')]);
2350
- }
2351
- #messages = (initializeDeferredDecorator(this, "messages"), void 0);
2352
- /**
2353
- @property content
2354
- @type {Array}
2355
- @private
2356
- */
2357
- get content() {
2358
- return A();
2359
- }
2360
-
2361
- /**
2362
- @private
2363
- */
2364
- static {
2365
- decorateMethodV2(this.prototype, "content", [computed()]);
2366
- }
2367
- unknownProperty(attribute) {
2368
- const errors = this.errorsFor(attribute);
2369
- if (errors.length === 0) {
2370
- return undefined;
2371
- }
2372
- return errors;
2373
- }
2374
-
2375
- /**
2376
- Total number of errors.
2377
- @property length
2378
- @type {Number}
2379
- @public
2380
- @readonly
2381
- */
2382
-
2383
- /**
2384
- `true` if we have no errors.
2385
- @property isEmpty
2386
- @type {Boolean}
2387
- @public
2388
- @readonly
2389
- */
2390
- static {
2391
- decorateFieldV2(this.prototype, "isEmpty", [not('length')]);
2392
- }
2393
- #isEmpty = (initializeDeferredDecorator(this, "isEmpty"), void 0);
2394
- /**
2395
- Manually adds errors to the record. This will trigger the `becameInvalid` event/ lifecycle method on
2396
- the record and transition the record into an `invalid` state.
2397
- Example
2398
- ```javascript
2399
- let errors = user.errors;
2400
- // add multiple errors
2401
- errors.add('password', [
2402
- 'Must be at least 12 characters',
2403
- 'Must contain at least one symbol',
2404
- 'Cannot contain your name'
2405
- ]);
2406
- errors.errorsFor('password');
2407
- // =>
2408
- // [
2409
- // { attribute: 'password', message: 'Must be at least 12 characters' },
2410
- // { attribute: 'password', message: 'Must contain at least one symbol' },
2411
- // { attribute: 'password', message: 'Cannot contain your name' },
2412
- // ]
2413
- // add a single error
2414
- errors.add('username', 'This field is required');
2415
- errors.errorsFor('username');
2416
- // =>
2417
- // [
2418
- // { attribute: 'username', message: 'This field is required' },
2419
- // ]
2420
- ```
2421
- @public
2422
- @param {String} attribute - the property name of an attribute or relationship
2423
- @param {string[]|string} messages - an error message or array of error messages for the attribute
2424
- */
2425
- add(attribute, messages) {
2426
- const errors = this._findOrCreateMessages(attribute, messages);
2427
- this.addObjects(errors);
2428
- this.errorsFor(attribute).addObjects(errors);
2429
- this.__record.currentState.notify('isValid');
2430
- this.notifyPropertyChange(attribute);
2431
- }
2432
-
2433
- /**
2434
- @private
2435
- */
2436
- _findOrCreateMessages(attribute, messages) {
2437
- const errors = this.errorsFor(attribute);
2438
- const messagesArray = Array.isArray(messages) ? messages : [messages];
2439
- const _messages = new Array(messagesArray.length);
2440
- for (let i = 0; i < messagesArray.length; i++) {
2441
- const message = messagesArray[i];
2442
- const err = errors.findBy('message', message);
2443
- if (err) {
2444
- _messages[i] = err;
2445
- } else {
2446
- _messages[i] = {
2447
- attribute: attribute,
2448
- message
2449
- };
2450
- }
2451
- }
2452
- return _messages;
2453
- }
2454
-
2455
- /**
2456
- Manually removes all errors for a given member from the record.
2457
- This will transition the record into a `valid` state, and
2458
- triggers the `becameValid` event and lifecycle method.
2459
- Example:
2460
- ```javascript
2461
- let errors = user.errors;
2462
- errors.add('phone', ['error-1', 'error-2']);
2463
- errors.errorsFor('phone');
2464
- // =>
2465
- // [
2466
- // { attribute: 'phone', message: 'error-1' },
2467
- // { attribute: 'phone', message: 'error-2' },
2468
- // ]
2469
- errors.remove('phone');
2470
- errors.errorsFor('phone');
2471
- // => undefined
2472
- ```
2473
- @public
2474
- @param {String} member - the property name of an attribute or relationship
2475
- */
2476
- remove(attribute) {
2477
- if (this.isEmpty) {
2478
- return;
2479
- }
2480
- const content = this.rejectBy('attribute', attribute);
2481
- this.content.setObjects(content);
2482
-
2483
- // Although errorsByAttributeName.delete is technically enough to sync errors state, we also
2484
- // must mutate the array as well for autotracking
2485
- const errors = this.errorsFor(attribute);
2486
- for (let i = 0; i < errors.length; i++) {
2487
- if (errors[i].attribute === attribute) {
2488
- // .replace from Ember.NativeArray is necessary. JS splice will not work.
2489
- errors.replace(i, 1);
2490
- }
2491
- }
2492
- this.errorsByAttributeName.delete(attribute);
2493
- this.__record.currentState.notify('isValid');
2494
- this.notifyPropertyChange(attribute);
2495
- this.notifyPropertyChange('length');
2496
- }
2497
-
2498
- /**
2499
- Manually clears all errors for the record.
2500
- This will transition the record into a `valid` state, and
2501
- will trigger the `becameValid` event and lifecycle method.
2502
- Example:
2503
- ```javascript
2504
- let errors = user.errors;
2505
- errors.add('username', ['error-a']);
2506
- errors.add('phone', ['error-1', 'error-2']);
2507
- errors.errorsFor('username');
2508
- // =>
2509
- // [
2510
- // { attribute: 'username', message: 'error-a' },
2511
- // ]
2512
- errors.errorsFor('phone');
2513
- // =>
2514
- // [
2515
- // { attribute: 'phone', message: 'error-1' },
2516
- // { attribute: 'phone', message: 'error-2' },
2517
- // ]
2518
- errors.clear();
2519
- errors.errorsFor('username');
2520
- // => undefined
2521
- errors.errorsFor('phone');
2522
- // => undefined
2523
- errors.messages
2524
- // => []
2525
- ```
2526
- @public
2527
- */
2528
- clear() {
2529
- if (this.isEmpty) {
2530
- return;
2531
- }
2532
- const errorsByAttributeName = this.errorsByAttributeName;
2533
- const attributes = [];
2534
- errorsByAttributeName.forEach(function (_, attribute) {
2535
- attributes.push(attribute);
2536
- });
2537
- errorsByAttributeName.clear();
2538
- attributes.forEach(attribute => {
2539
- this.notifyPropertyChange(attribute);
2540
- });
2541
- this.__record.currentState.notify('isValid');
2542
- super.clear();
2543
- }
2544
-
2545
- /**
2546
- Checks if there are error messages for the given attribute.
2547
- ```js [app/controllers/user/edit.js]
2548
- export default class UserEditController extends Controller {
2549
- @action
2550
- save(user) {
2551
- if (user.errors.has('email')) {
2552
- return alert('Please update your email before attempting to save.');
2553
- }
2554
- user.save();
2555
- }
2556
- }
2557
- ```
2558
- @public
2559
- @param {String} attribute
2560
- @return {Boolean} true if there some errors on given attribute
2561
- */
2562
- has(attribute) {
2563
- return this.errorsFor(attribute).length > 0;
2564
- }
2565
- }
2566
- export { Errors as E, LEGACY_SUPPORT as L, PromiseBelongsTo as P, PromiseManyArray as a, lookupLegacySupport as l };