@esri/hub-common 9.14.0 → 9.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (295) hide show
  1. package/dist/es2017/ArcGISContext.js +72 -26
  2. package/dist/es2017/ArcGISContext.js.map +1 -1
  3. package/dist/es2017/ArcGISContextManager.js +20 -9
  4. package/dist/es2017/ArcGISContextManager.js.map +1 -1
  5. package/dist/es2017/Hub.js +70 -0
  6. package/dist/es2017/Hub.js.map +1 -0
  7. package/dist/es2017/HubError.js +34 -0
  8. package/dist/es2017/HubError.js.map +1 -0
  9. package/dist/es2017/collections.js +23 -0
  10. package/dist/es2017/collections.js.map +1 -1
  11. package/dist/es2017/content/_internal.js +12 -0
  12. package/dist/es2017/content/_internal.js.map +1 -1
  13. package/dist/es2017/content/index.js +42 -18
  14. package/dist/es2017/content/index.js.map +1 -1
  15. package/dist/es2017/core/helpers/PropertyMapper.js +95 -0
  16. package/dist/es2017/core/helpers/PropertyMapper.js.map +1 -0
  17. package/dist/es2017/core/index.js +3 -0
  18. package/dist/es2017/core/index.js.map +1 -0
  19. package/dist/es2017/core/traits/WithBannerImage.js +1 -0
  20. package/dist/es2017/core/traits/WithBannerImage.js.map +1 -0
  21. package/dist/es2017/core/traits/WithLayout.js +1 -0
  22. package/dist/es2017/core/traits/WithLayout.js.map +1 -0
  23. package/dist/es2017/core/traits/WithSlug.js +1 -0
  24. package/dist/es2017/core/traits/WithSlug.js.map +1 -0
  25. package/dist/es2017/core/traits/index.js +4 -0
  26. package/dist/es2017/core/traits/index.js.map +1 -0
  27. package/dist/es2017/core/types/IContentEnrichments.js +1 -0
  28. package/dist/es2017/core/types/IContentEnrichments.js.map +1 -0
  29. package/dist/es2017/core/types/IHubContent.js +1 -0
  30. package/dist/es2017/core/types/IHubContent.js.map +1 -0
  31. package/dist/es2017/core/types/IHubEntityBase.js +1 -0
  32. package/dist/es2017/core/types/IHubEntityBase.js.map +1 -0
  33. package/dist/es2017/core/types/IHubEntityManager.js +1 -0
  34. package/dist/es2017/core/types/IHubEntityManager.js.map +1 -0
  35. package/dist/es2017/core/types/IHubEvent.js +1 -0
  36. package/dist/es2017/core/types/IHubEvent.js.map +1 -0
  37. package/dist/es2017/core/types/IHubImage.js +1 -0
  38. package/dist/es2017/core/types/IHubImage.js.map +1 -0
  39. package/dist/es2017/core/types/IHubInitiative.js +1 -0
  40. package/dist/es2017/core/types/IHubInitiative.js.map +1 -0
  41. package/dist/es2017/core/types/IHubItemEntity.js +1 -0
  42. package/dist/es2017/core/types/IHubItemEntity.js.map +1 -0
  43. package/dist/es2017/core/types/IHubLayout.js +1 -0
  44. package/dist/es2017/core/types/IHubLayout.js.map +1 -0
  45. package/dist/es2017/core/types/IHubPage.js +1 -0
  46. package/dist/es2017/core/types/IHubPage.js.map +1 -0
  47. package/dist/es2017/core/types/IHubProject.js +1 -0
  48. package/dist/es2017/core/types/IHubProject.js.map +1 -0
  49. package/dist/es2017/core/types/IHubSite.js +1 -0
  50. package/dist/es2017/core/types/IHubSite.js.map +1 -0
  51. package/dist/es2017/core/types/IHubTimeline.js +1 -0
  52. package/dist/es2017/core/types/IHubTimeline.js.map +1 -0
  53. package/dist/es2017/core/types/IItemEnrichments.js +1 -0
  54. package/dist/es2017/core/types/IItemEnrichments.js.map +1 -0
  55. package/dist/es2017/core/types/index.js +15 -0
  56. package/dist/es2017/core/types/index.js.map +1 -0
  57. package/dist/es2017/index.js +11 -6
  58. package/dist/es2017/index.js.map +1 -1
  59. package/dist/es2017/items/fail-safe-update.js +2 -2
  60. package/dist/es2017/items/fail-safe-update.js.map +1 -1
  61. package/dist/es2017/items/get-model-from-options.js +2 -2
  62. package/dist/es2017/items/get-model-from-options.js.map +1 -1
  63. package/dist/es2017/items/index.js +2 -3
  64. package/dist/es2017/items/index.js.map +1 -1
  65. package/dist/es2017/items/slugs.js +92 -0
  66. package/dist/es2017/items/slugs.js.map +1 -0
  67. package/dist/es2017/models/index.js +98 -0
  68. package/dist/es2017/models/index.js.map +1 -0
  69. package/dist/es2017/{items/serialize-model.js → models/serializeModel.js} +1 -1
  70. package/dist/es2017/models/serializeModel.js.map +1 -0
  71. package/dist/es2017/projects/HubProjectManager.js +115 -0
  72. package/dist/es2017/projects/HubProjectManager.js.map +1 -0
  73. package/dist/es2017/projects/HubProjects.js +194 -0
  74. package/dist/es2017/projects/HubProjects.js.map +1 -0
  75. package/dist/es2017/projects/index.js +3 -0
  76. package/dist/es2017/projects/index.js.map +1 -0
  77. package/dist/es2017/utils/dasherize.js +25 -0
  78. package/dist/es2017/utils/dasherize.js.map +1 -0
  79. package/dist/es2017/utils/index.js +1 -0
  80. package/dist/es2017/utils/index.js.map +1 -1
  81. package/dist/esm/ArcGISContext.js +76 -26
  82. package/dist/esm/ArcGISContext.js.map +1 -1
  83. package/dist/esm/ArcGISContextManager.js +20 -9
  84. package/dist/esm/ArcGISContextManager.js.map +1 -1
  85. package/dist/esm/Hub.js +89 -0
  86. package/dist/esm/Hub.js.map +1 -0
  87. package/dist/esm/HubError.js +40 -0
  88. package/dist/esm/HubError.js.map +1 -0
  89. package/dist/esm/collections.js +23 -0
  90. package/dist/esm/collections.js.map +1 -1
  91. package/dist/esm/content/_internal.js +14 -0
  92. package/dist/esm/content/_internal.js.map +1 -1
  93. package/dist/esm/content/index.js +42 -18
  94. package/dist/esm/content/index.js.map +1 -1
  95. package/dist/esm/core/helpers/PropertyMapper.js +97 -0
  96. package/dist/esm/core/helpers/PropertyMapper.js.map +1 -0
  97. package/dist/esm/core/index.js +3 -0
  98. package/dist/esm/core/index.js.map +1 -0
  99. package/dist/esm/core/traits/WithBannerImage.js +1 -0
  100. package/dist/esm/core/traits/WithBannerImage.js.map +1 -0
  101. package/dist/esm/core/traits/WithLayout.js +1 -0
  102. package/dist/esm/core/traits/WithLayout.js.map +1 -0
  103. package/dist/esm/core/traits/WithSlug.js +1 -0
  104. package/dist/esm/core/traits/WithSlug.js.map +1 -0
  105. package/dist/esm/core/traits/index.js +4 -0
  106. package/dist/esm/core/traits/index.js.map +1 -0
  107. package/dist/esm/core/types/IContentEnrichments.js +1 -0
  108. package/dist/esm/core/types/IContentEnrichments.js.map +1 -0
  109. package/dist/esm/core/types/IHubContent.js +1 -0
  110. package/dist/esm/core/types/IHubContent.js.map +1 -0
  111. package/dist/esm/core/types/IHubEntityBase.js +1 -0
  112. package/dist/esm/core/types/IHubEntityBase.js.map +1 -0
  113. package/dist/esm/core/types/IHubEntityManager.js +1 -0
  114. package/dist/esm/core/types/IHubEntityManager.js.map +1 -0
  115. package/dist/esm/core/types/IHubEvent.js +1 -0
  116. package/dist/esm/core/types/IHubEvent.js.map +1 -0
  117. package/dist/esm/core/types/IHubImage.js +1 -0
  118. package/dist/esm/core/types/IHubImage.js.map +1 -0
  119. package/dist/esm/core/types/IHubInitiative.js +1 -0
  120. package/dist/esm/core/types/IHubInitiative.js.map +1 -0
  121. package/dist/esm/core/types/IHubItemEntity.js +1 -0
  122. package/dist/esm/core/types/IHubItemEntity.js.map +1 -0
  123. package/dist/esm/core/types/IHubLayout.js +1 -0
  124. package/dist/esm/core/types/IHubLayout.js.map +1 -0
  125. package/dist/esm/core/types/IHubPage.js +1 -0
  126. package/dist/esm/core/types/IHubPage.js.map +1 -0
  127. package/dist/esm/core/types/IHubProject.js +1 -0
  128. package/dist/esm/core/types/IHubProject.js.map +1 -0
  129. package/dist/esm/core/types/IHubSite.js +1 -0
  130. package/dist/esm/core/types/IHubSite.js.map +1 -0
  131. package/dist/esm/core/types/IHubTimeline.js +1 -0
  132. package/dist/esm/core/types/IHubTimeline.js.map +1 -0
  133. package/dist/esm/core/types/IItemEnrichments.js +1 -0
  134. package/dist/esm/core/types/IItemEnrichments.js.map +1 -0
  135. package/dist/esm/core/types/index.js +15 -0
  136. package/dist/esm/core/types/index.js.map +1 -0
  137. package/dist/esm/index.js +11 -6
  138. package/dist/esm/index.js.map +1 -1
  139. package/dist/esm/items/fail-safe-update.js +2 -2
  140. package/dist/esm/items/fail-safe-update.js.map +1 -1
  141. package/dist/esm/items/get-model-from-options.js +2 -2
  142. package/dist/esm/items/get-model-from-options.js.map +1 -1
  143. package/dist/esm/items/index.js +2 -3
  144. package/dist/esm/items/index.js.map +1 -1
  145. package/dist/esm/items/slugs.js +93 -0
  146. package/dist/esm/items/slugs.js.map +1 -0
  147. package/dist/esm/models/index.js +99 -0
  148. package/dist/esm/models/index.js.map +1 -0
  149. package/dist/esm/{items/serialize-model.js → models/serializeModel.js} +1 -1
  150. package/dist/esm/models/serializeModel.js.map +1 -0
  151. package/dist/esm/projects/HubProjectManager.js +142 -0
  152. package/dist/esm/projects/HubProjectManager.js.map +1 -0
  153. package/dist/esm/projects/HubProjects.js +225 -0
  154. package/dist/esm/projects/HubProjects.js.map +1 -0
  155. package/dist/esm/projects/index.js +3 -0
  156. package/dist/esm/projects/index.js.map +1 -0
  157. package/dist/esm/utils/dasherize.js +25 -0
  158. package/dist/esm/utils/dasherize.js.map +1 -0
  159. package/dist/esm/utils/index.js +1 -0
  160. package/dist/esm/utils/index.js.map +1 -1
  161. package/dist/node/ArcGISContext.js +72 -26
  162. package/dist/node/ArcGISContext.js.map +1 -1
  163. package/dist/node/ArcGISContextManager.js +20 -9
  164. package/dist/node/ArcGISContextManager.js.map +1 -1
  165. package/dist/node/Hub.js +74 -0
  166. package/dist/node/Hub.js.map +1 -0
  167. package/dist/node/HubError.js +37 -0
  168. package/dist/node/HubError.js.map +1 -0
  169. package/dist/node/collections.js +24 -1
  170. package/dist/node/collections.js.map +1 -1
  171. package/dist/node/content/_internal.js +13 -1
  172. package/dist/node/content/_internal.js.map +1 -1
  173. package/dist/node/content/index.js +42 -18
  174. package/dist/node/content/index.js.map +1 -1
  175. package/dist/node/core/helpers/PropertyMapper.js +101 -0
  176. package/dist/node/core/helpers/PropertyMapper.js.map +1 -0
  177. package/dist/node/core/index.js +6 -0
  178. package/dist/node/core/index.js.map +1 -0
  179. package/dist/node/core/traits/WithBannerImage.js +3 -0
  180. package/dist/node/core/traits/WithBannerImage.js.map +1 -0
  181. package/dist/node/core/traits/WithLayout.js +3 -0
  182. package/dist/node/core/traits/WithLayout.js.map +1 -0
  183. package/dist/node/core/traits/WithSlug.js +3 -0
  184. package/dist/node/core/traits/WithSlug.js.map +1 -0
  185. package/dist/node/core/traits/index.js +7 -0
  186. package/dist/node/core/traits/index.js.map +1 -0
  187. package/dist/node/core/types/IContentEnrichments.js +3 -0
  188. package/dist/node/core/types/IContentEnrichments.js.map +1 -0
  189. package/dist/node/core/types/IHubContent.js +3 -0
  190. package/dist/node/core/types/IHubContent.js.map +1 -0
  191. package/dist/node/core/types/IHubEntityBase.js +3 -0
  192. package/dist/node/core/types/IHubEntityBase.js.map +1 -0
  193. package/dist/node/core/types/IHubEntityManager.js +3 -0
  194. package/dist/node/core/types/IHubEntityManager.js.map +1 -0
  195. package/dist/node/core/types/IHubEvent.js +3 -0
  196. package/dist/node/core/types/IHubEvent.js.map +1 -0
  197. package/dist/node/core/types/IHubImage.js +3 -0
  198. package/dist/node/core/types/IHubImage.js.map +1 -0
  199. package/dist/node/core/types/IHubInitiative.js +3 -0
  200. package/dist/node/core/types/IHubInitiative.js.map +1 -0
  201. package/dist/node/core/types/IHubItemEntity.js +3 -0
  202. package/dist/node/core/types/IHubItemEntity.js.map +1 -0
  203. package/dist/node/core/types/IHubLayout.js +3 -0
  204. package/dist/node/core/types/IHubLayout.js.map +1 -0
  205. package/dist/node/core/types/IHubPage.js +3 -0
  206. package/dist/node/core/types/IHubPage.js.map +1 -0
  207. package/dist/node/core/types/IHubProject.js +3 -0
  208. package/dist/node/core/types/IHubProject.js.map +1 -0
  209. package/dist/node/core/types/IHubSite.js +3 -0
  210. package/dist/node/core/types/IHubSite.js.map +1 -0
  211. package/dist/node/core/types/IHubTimeline.js +3 -0
  212. package/dist/node/core/types/IHubTimeline.js.map +1 -0
  213. package/dist/node/core/types/IItemEnrichments.js +3 -0
  214. package/dist/node/core/types/IItemEnrichments.js.map +1 -0
  215. package/dist/node/core/types/index.js +18 -0
  216. package/dist/node/core/types/index.js.map +1 -0
  217. package/dist/node/index.js +12 -6
  218. package/dist/node/index.js.map +1 -1
  219. package/dist/node/items/fail-safe-update.js +3 -3
  220. package/dist/node/items/fail-safe-update.js.map +1 -1
  221. package/dist/node/items/get-model-from-options.js +3 -3
  222. package/dist/node/items/get-model-from-options.js.map +1 -1
  223. package/dist/node/items/index.js +2 -3
  224. package/dist/node/items/index.js.map +1 -1
  225. package/dist/node/items/slugs.js +99 -0
  226. package/dist/node/items/slugs.js.map +1 -0
  227. package/dist/node/models/index.js +106 -0
  228. package/dist/node/models/index.js.map +1 -0
  229. package/dist/node/{items/serialize-model.js → models/serializeModel.js} +1 -1
  230. package/dist/node/models/serializeModel.js.map +1 -0
  231. package/dist/node/projects/HubProjectManager.js +119 -0
  232. package/dist/node/projects/HubProjectManager.js.map +1 -0
  233. package/dist/node/projects/HubProjects.js +201 -0
  234. package/dist/node/projects/HubProjects.js.map +1 -0
  235. package/dist/node/projects/index.js +6 -0
  236. package/dist/node/projects/index.js.map +1 -0
  237. package/dist/node/utils/dasherize.js +29 -0
  238. package/dist/node/utils/dasherize.js.map +1 -0
  239. package/dist/node/utils/index.js +1 -0
  240. package/dist/node/utils/index.js.map +1 -1
  241. package/dist/types/ArcGISContext.d.ts +197 -13
  242. package/dist/types/ArcGISContextManager.d.ts +21 -4
  243. package/dist/types/Hub.d.ts +72 -0
  244. package/dist/types/HubError.d.ts +17 -0
  245. package/dist/types/collections.d.ts +12 -0
  246. package/dist/types/content/_internal.d.ts +66 -38
  247. package/dist/types/content/index.d.ts +17 -8
  248. package/dist/types/core/helpers/PropertyMapper.d.ts +69 -0
  249. package/dist/types/core/index.d.ts +2 -0
  250. package/dist/types/core/traits/WithBannerImage.d.ts +30 -0
  251. package/dist/types/core/traits/WithLayout.d.ts +54 -0
  252. package/dist/types/core/traits/WithSlug.d.ts +15 -0
  253. package/dist/types/core/traits/index.d.ts +3 -0
  254. package/dist/types/core/types/IContentEnrichments.d.ts +10 -0
  255. package/dist/types/core/types/IHubContent.d.ts +77 -0
  256. package/dist/types/core/types/IHubEntityBase.d.ts +41 -0
  257. package/dist/types/core/types/IHubEntityManager.d.ts +33 -0
  258. package/dist/types/core/types/IHubEvent.d.ts +10 -0
  259. package/dist/types/core/types/IHubImage.d.ts +25 -0
  260. package/dist/types/core/types/IHubInitiative.d.ts +8 -0
  261. package/dist/types/core/types/IHubItemEntity.d.ts +42 -0
  262. package/dist/types/core/types/IHubLayout.d.ts +20 -0
  263. package/dist/types/core/types/IHubPage.d.ts +8 -0
  264. package/dist/types/core/types/IHubProject.d.ts +15 -0
  265. package/dist/types/core/types/IHubSite.d.ts +11 -0
  266. package/dist/types/core/types/IHubTimeline.d.ts +41 -0
  267. package/dist/types/core/types/IItemEnrichments.d.ts +23 -0
  268. package/dist/types/core/types/index.d.ts +14 -0
  269. package/dist/types/index.d.ts +11 -6
  270. package/dist/types/items/index.d.ts +2 -3
  271. package/dist/types/items/slugs.d.ts +43 -0
  272. package/dist/types/models/index.d.ts +42 -0
  273. package/dist/types/{items/serialize-model.d.ts → models/serializeModel.d.ts} +0 -0
  274. package/dist/types/projects/HubProjectManager.d.ts +81 -0
  275. package/dist/types/projects/HubProjects.d.ts +31 -0
  276. package/dist/types/projects/index.d.ts +2 -0
  277. package/dist/types/search/types.d.ts +2 -0
  278. package/dist/types/types.d.ts +2 -92
  279. package/dist/types/utils/dasherize.d.ts +17 -0
  280. package/dist/types/utils/index.d.ts +1 -0
  281. package/dist/umd/common.umd.js +2062 -1114
  282. package/dist/umd/common.umd.js.map +1 -1
  283. package/dist/umd/common.umd.min.js +1 -1
  284. package/dist/umd/common.umd.min.js.map +1 -1
  285. package/package.json +1 -1
  286. package/dist/es2017/items/get-model.js +0 -19
  287. package/dist/es2017/items/get-model.js.map +0 -1
  288. package/dist/es2017/items/serialize-model.js.map +0 -1
  289. package/dist/esm/items/get-model.js +0 -19
  290. package/dist/esm/items/get-model.js.map +0 -1
  291. package/dist/esm/items/serialize-model.js.map +0 -1
  292. package/dist/node/items/get-model.js +0 -23
  293. package/dist/node/items/get-model.js.map +0 -1
  294. package/dist/node/items/serialize-model.js.map +0 -1
  295. package/dist/types/items/get-model.d.ts +0 -8
@@ -1,5 +1,5 @@
1
1
  /* @preserve
2
- * @esri/hub-common - v9.13.2 - Tue Jan 25 2022 00:14:10 GMT+0000 (Coordinated Universal Time)
2
+ * @esri/hub-common - v9.16.0 - Wed Feb 16 2022 23:41:40 GMT+0000 (Coordinated Universal Time)
3
3
  * Copyright (c) 2022 Environmental Systems Research Institute, Inc.
4
4
  * Apache-2.0
5
5
  */
@@ -2988,6 +2988,31 @@
2988
2988
  }
2989
2989
  }
2990
2990
 
2991
+ /**
2992
+ * Dasherize a string
2993
+ *
2994
+ * ```javascript
2995
+ * import { dasherize } from '@esri/hub-common';
2996
+ * dasherize('innerHTML'); // 'inner-html'
2997
+ * dasherize('action_name'); // 'action-name'
2998
+ * dasherize('css-class-name'); // 'css-class-name'
2999
+ * dasherize('my favorite items'); // 'my-favorite-items'
3000
+ * dasherize('privateDocs/ownerInvoice'; // 'private-docs/owner-invoice'
3001
+ * ```
3002
+ *
3003
+ * Extracted and modified from Ember.js source code - MIT license
3004
+ * @param value
3005
+ * @returns
3006
+ */
3007
+ function dasherize(value) {
3008
+ var DECAMELIZE_REGEXP = /([a-z\d])([A-Z])/g;
3009
+ var DASHERIZE_REGEXP = /[ _]/g;
3010
+ return value
3011
+ .replace(DECAMELIZE_REGEXP, "$1_$2")
3012
+ .toLowerCase()
3013
+ .replace(DASHERIZE_REGEXP, "-");
3014
+ }
3015
+
2991
3016
  /**
2992
3017
  * Checks for fundamental privilege required by all access checks
2993
3018
  * @param {IUser} user
@@ -3255,6 +3280,76 @@
3255
3280
  });
3256
3281
  }
3257
3282
 
3283
+ /* Copyright (c) 2018 Environmental Systems Research Institute, Inc.
3284
+ * Apache-2.0 */
3285
+ /**
3286
+ * ```js
3287
+ * import { createItemInFolder } from "@esri/arcgis-rest-portal";
3288
+ * //
3289
+ * createItemInFolder({
3290
+ * item: {
3291
+ * title: "The Amazing Voyage",
3292
+ * type: "Web Map"
3293
+ * },
3294
+ * folderId: 'fe8',
3295
+ * authentication
3296
+ * })
3297
+ * ```
3298
+ * Create an item in a folder. See the [REST Documentation](https://developers.arcgis.com/rest/users-groups-and-items/add-item.htm) for more information.
3299
+ *
3300
+ * @param requestOptions = Options for the request
3301
+ */
3302
+ function createItemInFolder(requestOptions) {
3303
+ if (requestOptions.multipart && !requestOptions.filename) {
3304
+ return Promise.reject(new Error("The filename is required for a multipart request."));
3305
+ }
3306
+ return determineOwner(requestOptions).then(function (owner) {
3307
+ var baseUrl = getPortalUrl$1(requestOptions) + "/content/users/" + owner;
3308
+ var url = baseUrl + "/addItem";
3309
+ if (requestOptions.folderId) {
3310
+ url = baseUrl + "/" + requestOptions.folderId + "/addItem";
3311
+ }
3312
+ requestOptions.params = __assign(__assign({}, requestOptions.params), serializeItem(requestOptions.item));
3313
+ // serialize the item into something Portal will accept
3314
+ var options = appendCustomParams(requestOptions, [
3315
+ "owner",
3316
+ "folderId",
3317
+ "file",
3318
+ "dataUrl",
3319
+ "text",
3320
+ "async",
3321
+ "multipart",
3322
+ "filename",
3323
+ "overwrite"
3324
+ ], {
3325
+ params: __assign({}, requestOptions.params)
3326
+ });
3327
+ return request(url, options);
3328
+ });
3329
+ }
3330
+ /**
3331
+ * ```js
3332
+ * import { createItem } from "@esri/arcgis-rest-portal";
3333
+ * //
3334
+ * createItem({
3335
+ * item: {
3336
+ * title: "The Amazing Voyage",
3337
+ * type: "Web Map"
3338
+ * },
3339
+ * authentication
3340
+ * })
3341
+ * ```
3342
+ * Create an Item in the user's root folder. See the [REST Documentation](https://developers.arcgis.com/rest/users-groups-and-items/add-item.htm) for more information.
3343
+ *
3344
+ * @param requestOptions - Options for the request
3345
+ * @returns A Promise that creates an item.
3346
+ */
3347
+ function createItem(requestOptions) {
3348
+ // delegate to createItemInFolder placing in the root of the filestore
3349
+ var options = __assign({ folderId: null }, requestOptions);
3350
+ return createItemInFolder(options);
3351
+ }
3352
+
3258
3353
  /* Copyright (c) 2018 Environmental Systems Research Institute, Inc.
3259
3354
  * Apache-2.0 */
3260
3355
  /**
@@ -5063,185 +5158,730 @@
5063
5158
  return _getHubUrlFromPortalHostname(getPortalApiUrl(urlOrObject));
5064
5159
  }
5065
5160
 
5066
- /* Copyright (c) 2018 Environmental Systems Research Institute, Inc.
5067
- * Apache-2.0 */
5068
5161
  /**
5069
- * A thin wrapper around [`UserSession.completeOAuth2()`](https://esri.github.io/arcgis-rest-js/api/auth/UserSession/#completeOAuth2) that sets search tags and other relevant metadata for newly created community users.
5162
+ * Hash of Hub API end points so updates
5163
+ * are centralized
5070
5164
  */
5071
- /* istanbul ignore next */
5072
- function completeOAuth2(options, win) {
5073
- if (win === void 0) { win = window; }
5074
- var match = win.location.href.match(/access_token=(.+)&expires_in=.+&username=([^&]+)/);
5075
- var token = match[1];
5076
- var user = decodeURIComponent(match[2]);
5077
- var baseUrl = "https://www.arcgis.com/sharing/rest/community/users/" + user;
5078
- return request(baseUrl, {
5079
- params: { token: token },
5080
- httpMethod: "GET"
5081
- }).then(function (response) {
5082
- if (Date.now() - response.created < 5000) {
5083
- return request(baseUrl + "/update", {
5084
- params: {
5085
- token: token,
5086
- tags: ["hubRole:participant", "org:" + response.orgId],
5087
- access: "public"
5088
- }
5089
- }).then(function () {
5090
- return UserSession.completeOAuth2(options);
5091
- });
5165
+ var hubApiEndpoints = {
5166
+ domains: "/api/v3/domains",
5167
+ search: "/api/v3/datasets",
5168
+ discussions: "/api/discussions/v1",
5169
+ };
5170
+ /**
5171
+ * Abstraction that holds a `UserSession`, along with
5172
+ * getters to streamline access to various platform
5173
+ * urls, and common constructs like `IRequestOptions`,
5174
+ * `IUserRequestOptions` etc.
5175
+ *
5176
+ * Instances are intended to be immutable, but this is not directly enforced.
5177
+ *
5178
+ * In most circumstances, this class should be created by
5179
+ * the ArcGISContextManager class.
5180
+ */
5181
+ var ArcGISContext = /** @class */ (function () {
5182
+ /**
5183
+ * Create a new instance of `ArcGISContext`.
5184
+ *
5185
+ * @param opts
5186
+ */
5187
+ function ArcGISContext(opts) {
5188
+ this._portalUrl = "https://www.arcgis.com";
5189
+ this.id = opts.id;
5190
+ this._portalUrl = opts.portalUrl;
5191
+ this._hubUrl = opts.hubUrl;
5192
+ if (opts.authentication) {
5193
+ this._authentication = opts.authentication;
5092
5194
  }
5093
- else {
5094
- return UserSession.completeOAuth2(options);
5195
+ if (opts.portalSelf) {
5196
+ this._portalSelf = opts.portalSelf;
5197
+ }
5198
+ if (opts.currentUser) {
5199
+ this._currentUser = opts.currentUser;
5200
+ }
5201
+ if (opts.properties) {
5202
+ this._properties = opts.properties;
5095
5203
  }
5204
+ }
5205
+ Object.defineProperty(ArcGISContext.prototype, "session", {
5206
+ /**
5207
+ * Return the UserSession if authenticated
5208
+ */
5209
+ get: function () {
5210
+ return this._authentication;
5211
+ },
5212
+ enumerable: false,
5213
+ configurable: true
5096
5214
  });
5097
- }
5098
-
5099
- var app$1 = [
5100
- "Application",
5101
- "City Engine Web Scene",
5102
- "CityEngine Web Scene",
5103
- "Dashboard",
5104
- "Insights Page",
5105
- "Insights Workbook",
5106
- "Operation View",
5107
- "Web Mapping Application",
5108
- "StoryMap",
5109
- "Web Experience",
5110
- "Urban Model",
5111
- ];
5112
- var dataset$1 = [
5113
- "CSV Collection",
5114
- "CSV",
5115
- "Feature Collection Template",
5116
- "Feature Collection",
5117
- "Feature Layer",
5118
- "Feature Service",
5119
- "File Geodatabase",
5120
- "GeoJSON",
5121
- "GeoJson",
5122
- "KML Collection",
5123
- "KML",
5124
- "Microsoft Excel",
5125
- "Raster Layer",
5126
- "Shapefile",
5127
- "Stream Service",
5128
- "Table",
5129
- ];
5130
- var document$1 = [
5131
- "CAD Drawing",
5132
- "Document Link",
5133
- "Hub Page",
5134
- "Site Page",
5135
- "Image",
5136
- "iWork Keynote",
5137
- "iWork Numbers",
5138
- "iWork Pages",
5139
- "Microsoft Powerpoint",
5140
- "Microsoft Visio",
5141
- "Microsoft Word",
5142
- "Notebook",
5143
- "PDF",
5144
- "Pro Map",
5145
- "Report Template",
5146
- ];
5147
- var event$1 = ["Hub Event"];
5148
- var feedback$1 = ["Form", "Quick Capture Project"];
5149
- var initiative$1 = ["Hub Initiative"];
5150
- var solution = ["Solution"];
5151
- var template = ["Hub Initiative Template"];
5152
- var map$1 = [
5153
- "Image Collection",
5154
- "Image Service",
5155
- "Map Service Layer",
5156
- "Map Service",
5157
- "Scene Service",
5158
- "Scene Layer",
5159
- "Vector Tile Service",
5160
- "Web Map Service",
5161
- "Web Map Tile Service",
5162
- "Web Map",
5163
- "Web Scene",
5164
- "WFS",
5165
- "WMS",
5166
- "WMTS",
5167
- ];
5168
- var other$1 = [
5169
- "360 VR Experience",
5170
- "AppBuilder Widget Package",
5171
- "Application Configuration",
5172
- "ArcPad Package",
5173
- "Code Attachment",
5174
- "Code Sample",
5175
- "Desktop Add In",
5176
- "Desktop Application Template",
5177
- "Desktop Application",
5178
- "Desktop Style",
5179
- "Explorer Add In",
5180
- "Explorer Layer",
5181
- "Geocoding Service",
5182
- "Geometry Service",
5183
- "Geoprocessing Package",
5184
- "Geoprocessing Sample",
5185
- "Geoprocessing Service",
5186
- "Layer File",
5187
- "Layer Package",
5188
- "Layer Template",
5189
- "Layer",
5190
- "Layout",
5191
- "Locator Package",
5192
- "Map Area",
5193
- "Map Document",
5194
- "Map Package",
5195
- "Map Service Definition",
5196
- "Map Template",
5197
- "Mobile Application",
5198
- "Mobile Map Package",
5199
- "Native Application",
5200
- "Network Analysis Service",
5201
- "Operations Dashboard Add In",
5202
- "Project Package",
5203
- "Project Template",
5204
- "Raster Function Template",
5205
- "Rule Package",
5206
- "Scene Package",
5207
- "Service Definition",
5208
- "SQLite Geodatabase",
5209
- "Style",
5210
- "Tile Package",
5211
- "Vector Tile Package",
5212
- "Workflow Manager Package",
5213
- ];
5214
- var site$1 = ["Hub Site Application", "Site Application"];
5215
- var collections = {
5216
- app: app$1,
5217
- dataset: dataset$1,
5218
- document: document$1,
5219
- event: event$1,
5220
- feedback: feedback$1,
5221
- initiative: initiative$1,
5222
- template: template,
5223
- solution: solution,
5224
- map: map$1,
5225
- other: other$1,
5226
- site: site$1,
5227
- };
5228
-
5229
- var app = collections.app, dataset = collections.dataset, document = collections.document, event = collections.event, feedback = collections.feedback, initiative = collections.initiative, map = collections.map, other = collections.other, site = collections.site;
5230
- var downloadableTypes = [
5231
- "360 VR Experience",
5232
- "Application",
5233
- "CityEngine Web Scene",
5234
- "Code Sample",
5235
- "CSV Collection",
5236
- "CSV",
5237
- "CAD Drawing",
5238
- "Desktop Application",
5239
- "Desktop Application Template",
5240
- "Desktop Style",
5241
- "File Geodatabase",
5242
- "GeoJson",
5243
- "Geoprocessing Package",
5244
- "Geoprocessing Sample",
5215
+ Object.defineProperty(ArcGISContext.prototype, "isAuthenticated", {
5216
+ /**
5217
+ * Return boolean indicating if authenticatio is present
5218
+ */
5219
+ get: function () {
5220
+ return !!this._authentication;
5221
+ },
5222
+ enumerable: false,
5223
+ configurable: true
5224
+ });
5225
+ Object.defineProperty(ArcGISContext.prototype, "userRequestOptions", {
5226
+ /**
5227
+ * Return `IUserRequestOptions`, which is used for REST-JS
5228
+ * functions which require authentication information.
5229
+ *
5230
+ * If context is not authenticated, this function will throw
5231
+ */
5232
+ get: function () {
5233
+ if (this.isAuthenticated) {
5234
+ return {
5235
+ authentication: this._authentication,
5236
+ portal: this.sharingApiUrl,
5237
+ };
5238
+ }
5239
+ },
5240
+ enumerable: false,
5241
+ configurable: true
5242
+ });
5243
+ Object.defineProperty(ArcGISContext.prototype, "requestOptions", {
5244
+ /**
5245
+ * Return `IRequestOptions`, which is used by REST-JS functions
5246
+ * which *may* use authentication information if provided.
5247
+ *
5248
+ * If context is not authenticated, this function just returns
5249
+ * the `portal` property, which informs REST-JS what Sharing API
5250
+ * instance to use (i.e. AGO, Enterprise etc)
5251
+ */
5252
+ get: function () {
5253
+ var ro = {
5254
+ portal: this.sharingApiUrl,
5255
+ };
5256
+ if (this.isAuthenticated) {
5257
+ ro = {
5258
+ authentication: this._authentication,
5259
+ portal: this.sharingApiUrl,
5260
+ };
5261
+ }
5262
+ return ro;
5263
+ },
5264
+ enumerable: false,
5265
+ configurable: true
5266
+ });
5267
+ Object.defineProperty(ArcGISContext.prototype, "hubRequestOptions", {
5268
+ /**
5269
+ * Return a `IHubRequestOptions` object
5270
+ */
5271
+ get: function () {
5272
+ // We may add more logic around what is returned in some corner cases
5273
+ if (this.isAuthenticated) {
5274
+ return {
5275
+ authentication: this.session,
5276
+ isPortal: this.isPortal,
5277
+ portalSelf: this.portal,
5278
+ hubApiUrl: this.hubUrl,
5279
+ };
5280
+ }
5281
+ },
5282
+ enumerable: false,
5283
+ configurable: true
5284
+ });
5285
+ Object.defineProperty(ArcGISContext.prototype, "portalUrl", {
5286
+ /**
5287
+ * Return the portal url i.e. https://www.arcgis.com
5288
+ *
5289
+ * If authenticated @ ArcGIS Online, it will return
5290
+ * the https://org.env.arcgis.com
5291
+ *
5292
+ * If authenticated @ ArcGIS Enterprise, it will return
5293
+ * https://{portalHostname}/{webadaptor}
5294
+ */
5295
+ get: function () {
5296
+ if (this.isAuthenticated) {
5297
+ if (this.isPortal) {
5298
+ return "https://" + this._portalSelf.portalHostname;
5299
+ }
5300
+ else {
5301
+ return "https://" + this._portalSelf.urlKey + "." + this._portalSelf.customBaseUrl;
5302
+ }
5303
+ }
5304
+ else {
5305
+ return this._portalUrl;
5306
+ }
5307
+ },
5308
+ enumerable: false,
5309
+ configurable: true
5310
+ });
5311
+ Object.defineProperty(ArcGISContext.prototype, "sharingApiUrl", {
5312
+ /**
5313
+ * Returns the url to the sharing api composed from portalUrl
5314
+ * i.e. https://myorg.maps.arcgis.com/sharing/rest
5315
+ */
5316
+ get: function () {
5317
+ return this.portalUrl + "/sharing/rest";
5318
+ },
5319
+ enumerable: false,
5320
+ configurable: true
5321
+ });
5322
+ Object.defineProperty(ArcGISContext.prototype, "hubUrl", {
5323
+ /**
5324
+ * Returns the Hub url, based on the portalUrl
5325
+ *
5326
+ * For ArcGIS Enterprise this will return `undefined`
5327
+ */
5328
+ get: function () {
5329
+ return this._hubUrl;
5330
+ },
5331
+ enumerable: false,
5332
+ configurable: true
5333
+ });
5334
+ Object.defineProperty(ArcGISContext.prototype, "isPortal", {
5335
+ /**
5336
+ * Returns boolean indicating if the backing system
5337
+ * is ArcGIS Enterprise (formerly ArcGIS Portal) or not
5338
+ */
5339
+ get: function () {
5340
+ return this._portalSelf
5341
+ ? this._portalSelf.isPortal
5342
+ : this._portalUrl.indexOf("arcgis.com") === -1;
5343
+ },
5344
+ enumerable: false,
5345
+ configurable: true
5346
+ });
5347
+ Object.defineProperty(ArcGISContext.prototype, "discussionsServiceUrl", {
5348
+ /**
5349
+ * Returns the discussions API URL
5350
+ */
5351
+ get: function () {
5352
+ if (this._hubUrl) {
5353
+ return "" + this._hubUrl + hubApiEndpoints.discussions;
5354
+ }
5355
+ },
5356
+ enumerable: false,
5357
+ configurable: true
5358
+ });
5359
+ Object.defineProperty(ArcGISContext.prototype, "hubSearchServiceUrl", {
5360
+ /**
5361
+ * Returns the Hub Search API URL
5362
+ */
5363
+ get: function () {
5364
+ if (this._hubUrl) {
5365
+ return "" + this._hubUrl + hubApiEndpoints.search;
5366
+ }
5367
+ },
5368
+ enumerable: false,
5369
+ configurable: true
5370
+ });
5371
+ Object.defineProperty(ArcGISContext.prototype, "domainServiceUrl", {
5372
+ /**
5373
+ * Returns Hub Domain Service URL
5374
+ */
5375
+ get: function () {
5376
+ if (this._hubUrl) {
5377
+ return "" + this._hubUrl + hubApiEndpoints.domains;
5378
+ }
5379
+ },
5380
+ enumerable: false,
5381
+ configurable: true
5382
+ });
5383
+ Object.defineProperty(ArcGISContext.prototype, "eventsConfig", {
5384
+ /**
5385
+ * Returns the Events configuration object from portal/self
5386
+ *
5387
+ * `{serviceId: '3ef..', publicViewId: 'bc3...'}`
5388
+ */
5389
+ get: function () {
5390
+ if (this._portalSelf) {
5391
+ return getProp(this._portalSelf, "portalProperties.hub.settings.events");
5392
+ }
5393
+ },
5394
+ enumerable: false,
5395
+ configurable: true
5396
+ });
5397
+ Object.defineProperty(ArcGISContext.prototype, "hubEnabled", {
5398
+ /**
5399
+ * Returns boolean indicating if the current user
5400
+ * belongs to an organization that has licensed
5401
+ * ArcGIS Hub
5402
+ */
5403
+ get: function () {
5404
+ return getWithDefault$1(this._portalSelf, "portalProperties.hub.enabled", false);
5405
+ },
5406
+ enumerable: false,
5407
+ configurable: true
5408
+ });
5409
+ Object.defineProperty(ArcGISContext.prototype, "communityOrgId", {
5410
+ /**
5411
+ * Return the Hub Community Org Id, if defined
5412
+ */
5413
+ get: function () {
5414
+ if (this._portalSelf) {
5415
+ return getProp(this._portalSelf, "portalProperties.hub.settings.communityOrg.orgId");
5416
+ }
5417
+ },
5418
+ enumerable: false,
5419
+ configurable: true
5420
+ });
5421
+ Object.defineProperty(ArcGISContext.prototype, "communityOrgHostname", {
5422
+ /**
5423
+ * Returns the Hub Community Org Hostname, if defined
5424
+ *
5425
+ * i.e. c-org.maps.arcgis.com
5426
+ */
5427
+ get: function () {
5428
+ if (this._portalSelf) {
5429
+ return getProp(this._portalSelf, "portalProperties.hub.settings.communityOrg.portalHostname");
5430
+ }
5431
+ },
5432
+ enumerable: false,
5433
+ configurable: true
5434
+ });
5435
+ Object.defineProperty(ArcGISContext.prototype, "communityOrgUrl", {
5436
+ /**
5437
+ * Returns the Hub Community Org url
5438
+ *
5439
+ * i.e. https://c-org.maps.arcgis.com
5440
+ */
5441
+ get: function () {
5442
+ if (this.communityOrgHostname) {
5443
+ return "https://" + this.communityOrgHostname;
5444
+ }
5445
+ },
5446
+ enumerable: false,
5447
+ configurable: true
5448
+ });
5449
+ Object.defineProperty(ArcGISContext.prototype, "helperServices", {
5450
+ /**
5451
+ * Returns the hash of helper services from portal self
5452
+ */
5453
+ get: function () {
5454
+ if (this._portalSelf) {
5455
+ return this._portalSelf.helperServices;
5456
+ }
5457
+ },
5458
+ enumerable: false,
5459
+ configurable: true
5460
+ });
5461
+ Object.defineProperty(ArcGISContext.prototype, "currentUser", {
5462
+ /**
5463
+ * Returns the current user as IUser
5464
+ */
5465
+ get: function () {
5466
+ return this._currentUser;
5467
+ },
5468
+ enumerable: false,
5469
+ configurable: true
5470
+ });
5471
+ Object.defineProperty(ArcGISContext.prototype, "portal", {
5472
+ /**
5473
+ * Returns the portal object as IPortal
5474
+ */
5475
+ get: function () {
5476
+ return this._portalSelf;
5477
+ },
5478
+ enumerable: false,
5479
+ configurable: true
5480
+ });
5481
+ Object.defineProperty(ArcGISContext.prototype, "properties", {
5482
+ /**
5483
+ * Return the properties hash that was passed in.
5484
+ * Useful for app-specific context such as the active
5485
+ * Site for ArcGIS Hub
5486
+ */
5487
+ get: function () {
5488
+ return this._properties;
5489
+ },
5490
+ enumerable: false,
5491
+ configurable: true
5492
+ });
5493
+ return ArcGISContext;
5494
+ }());
5495
+
5496
+ /**
5497
+ * The manager exposes context (`IArcGISContext`), which combines a `UserSession` with
5498
+ * the `portal/self` and `user/self` responses to provide a central lookup for platform
5499
+ * information, api urls, and other useful properties for developers such as IRequestOptions
5500
+ * IUserRequestOptions, IHubRequestOptions etc.
5501
+ *
5502
+ * The context is exposed on gthe `.context` property, and as the authentication changes
5503
+ * the `.context` is re-created. This is done to allow web frameworks to watch for
5504
+ * changes on that single property, instead of having to leverage observers or events
5505
+ * for change detection.
5506
+ *
5507
+ * Please see the [ArcGISContext Guide](/hub.js/guides/context) for additional information.
5508
+ *
5509
+ */
5510
+ var ArcGISContextManager = /** @class */ (function () {
5511
+ /**
5512
+ * Private constructor. Use `ArcGISContextManager.create(...)` to
5513
+ * instantiate an instance
5514
+ * @param opts
5515
+ */
5516
+ function ArcGISContextManager(opts) {
5517
+ this._portalUrl = "https://www.arcgis.com";
5518
+ this._logLevel = exports.Level.error;
5519
+ // Having a unique id makes debugging easier
5520
+ this.id = new Date().getTime();
5521
+ if (opts.logLevel) {
5522
+ this._logLevel = opts.logLevel;
5523
+ }
5524
+ Logger.setLogLevel(this._logLevel);
5525
+ Logger.debug("ArcGISContextManager:ctor: Creating " + this.id);
5526
+ if (opts.properties) {
5527
+ this._properties = opts.properties;
5528
+ }
5529
+ if (opts.authentication) {
5530
+ this._authentication = opts.authentication;
5531
+ this._portalUrl = this._authentication.portal.replace("/sharing/rest", "");
5532
+ this._hubUrl = getHubApiFromPortalUrl(this._portalUrl);
5533
+ }
5534
+ else if (opts.portalUrl) {
5535
+ this._portalUrl = opts.portalUrl;
5536
+ this._hubUrl = getHubApiFromPortalUrl(this._portalUrl);
5537
+ }
5538
+ else {
5539
+ this._hubUrl = getHubApiFromPortalUrl(this._portalUrl);
5540
+ }
5541
+ if (opts.portal) {
5542
+ this._portalSelf = cloneObject$1(opts.portal);
5543
+ }
5544
+ if (opts.currentUser) {
5545
+ this._currentUser = cloneObject$1(opts.currentUser);
5546
+ }
5547
+ }
5548
+ /**
5549
+ * Used to create a new instance of the ArcGISContext class.
5550
+ *
5551
+ * ```js
5552
+ * const ctxMgr = await ArcGISContextManager.create();
5553
+ * ```
5554
+ *
5555
+ * @param opts
5556
+ * @returns
5557
+ */
5558
+ ArcGISContextManager.create = function (opts) {
5559
+ if (opts === void 0) { opts = {}; }
5560
+ return __awaiter(this, void 0, void 0, function () {
5561
+ var ctx;
5562
+ return __generator(this, function (_a) {
5563
+ switch (_a.label) {
5564
+ case 0:
5565
+ ctx = new ArcGISContextManager(opts);
5566
+ return [4 /*yield*/, ctx.initialize()];
5567
+ case 1:
5568
+ _a.sent();
5569
+ return [2 /*return*/, ctx];
5570
+ }
5571
+ });
5572
+ });
5573
+ };
5574
+ /**
5575
+ * Set the Authentication (UserSession) for the context.
5576
+ * This should be called when a user signs into a running
5577
+ * application.
5578
+ * @param auth
5579
+ */
5580
+ ArcGISContextManager.prototype.setAuthentication = function (auth) {
5581
+ return __awaiter(this, void 0, void 0, function () {
5582
+ return __generator(this, function (_a) {
5583
+ switch (_a.label) {
5584
+ case 0:
5585
+ this._authentication = auth;
5586
+ this._portalUrl = auth.portal.replace("/sharing/rest", "");
5587
+ return [4 /*yield*/, this.initialize()];
5588
+ case 1:
5589
+ _a.sent();
5590
+ return [2 /*return*/];
5591
+ }
5592
+ });
5593
+ });
5594
+ };
5595
+ /**
5596
+ * Set the properties hash and re-create the context
5597
+ * @param properties
5598
+ */
5599
+ ArcGISContextManager.prototype.setProperties = function (properties) {
5600
+ this._properties = properties;
5601
+ this._context = new ArcGISContext(this.contextOpts);
5602
+ };
5603
+ /**
5604
+ * Clear the Authentication (UserSession). This should be
5605
+ * called when a user signs out of an application, but
5606
+ * the application continues running
5607
+ */
5608
+ ArcGISContextManager.prototype.clearAuthentication = function () {
5609
+ // Reset the portalUrl from the org url to the base url
5610
+ // for ArcGIS Enterprise, we just leave the _portalUrl as-is
5611
+ if (!this._context.isPortal) {
5612
+ this._portalUrl = getPortalBaseFromOrgUrl(this._portalUrl);
5613
+ }
5614
+ // Clear the auth, portalSelf and currentUser props
5615
+ this._authentication = null;
5616
+ this._portalSelf = null;
5617
+ this._currentUser = null;
5618
+ this._context = new ArcGISContext(this.contextOpts);
5619
+ };
5620
+ Object.defineProperty(ArcGISContextManager.prototype, "context", {
5621
+ /**
5622
+ * Return a reference to the current state.
5623
+ * When `.setAuthentication()` or `.clearAuthenentication()` are
5624
+ * called, the state will be re-created. This is done so frameworks
5625
+ * like React or Ember can detect changes.
5626
+ */
5627
+ get: function () {
5628
+ return this._context;
5629
+ },
5630
+ enumerable: false,
5631
+ configurable: true
5632
+ });
5633
+ /**
5634
+ * If we have a UserSession, fetch portal/self and
5635
+ * store that along with current user
5636
+ */
5637
+ ArcGISContextManager.prototype.initialize = function () {
5638
+ return __awaiter(this, void 0, void 0, function () {
5639
+ var username, requests, _a, portal, user, ex_1, msg;
5640
+ return __generator(this, function (_b) {
5641
+ switch (_b.label) {
5642
+ case 0:
5643
+ if (!(this._authentication && (!this._portalSelf || !this._currentUser))) return [3 /*break*/, 4];
5644
+ Logger.debug("ArcGISContextManager-" + this.id + ": Initializing");
5645
+ username = this._authentication.username;
5646
+ requests = [
5647
+ getSelf({ authentication: this._authentication }),
5648
+ getUser({ username: username, authentication: this._authentication }),
5649
+ ];
5650
+ _b.label = 1;
5651
+ case 1:
5652
+ _b.trys.push([1, 3, , 4]);
5653
+ return [4 /*yield*/, Promise.all(requests)];
5654
+ case 2:
5655
+ _a = _b.sent(), portal = _a[0], user = _a[1];
5656
+ this._portalSelf = portal;
5657
+ this._currentUser = user;
5658
+ Logger.debug("ArcGISContextManager-" + this.id + ": received portalSelf and currentUser");
5659
+ return [3 /*break*/, 4];
5660
+ case 3:
5661
+ ex_1 = _b.sent();
5662
+ msg = "ArcGISContextManager could not fetch portal & user for \"" + this._authentication.username + "\" using " + this._authentication.portal + ".";
5663
+ Logger.error(msg);
5664
+ // tslint:disable-next-line:no-console
5665
+ console.error(msg);
5666
+ throw ex_1;
5667
+ case 4:
5668
+ Logger.debug("ArcGISContextManager-" + this.id + ": updating context");
5669
+ // update the context
5670
+ this._context = new ArcGISContext(this.contextOpts);
5671
+ return [2 /*return*/];
5672
+ }
5673
+ });
5674
+ });
5675
+ };
5676
+ Object.defineProperty(ArcGISContextManager.prototype, "contextOpts", {
5677
+ /**
5678
+ * Getter to streamline the creation of updated Context instances
5679
+ */
5680
+ get: function () {
5681
+ var contextOpts = {
5682
+ id: this.id,
5683
+ portalUrl: this._portalUrl,
5684
+ hubUrl: this._hubUrl,
5685
+ properties: this._properties,
5686
+ };
5687
+ if (this._authentication) {
5688
+ contextOpts.authentication = this._authentication;
5689
+ }
5690
+ if (this._portalSelf) {
5691
+ contextOpts.portalSelf = this._portalSelf;
5692
+ }
5693
+ if (this._currentUser) {
5694
+ contextOpts.currentUser = this._currentUser;
5695
+ }
5696
+ return contextOpts;
5697
+ },
5698
+ enumerable: false,
5699
+ configurable: true
5700
+ });
5701
+ return ArcGISContextManager;
5702
+ }());
5703
+
5704
+ /* Copyright (c) 2018 Environmental Systems Research Institute, Inc.
5705
+ * Apache-2.0 */
5706
+ /**
5707
+ * A thin wrapper around [`UserSession.completeOAuth2()`](https://esri.github.io/arcgis-rest-js/api/auth/UserSession/#completeOAuth2) that sets search tags and other relevant metadata for newly created community users.
5708
+ */
5709
+ /* istanbul ignore next */
5710
+ function completeOAuth2(options, win) {
5711
+ if (win === void 0) { win = window; }
5712
+ var match = win.location.href.match(/access_token=(.+)&expires_in=.+&username=([^&]+)/);
5713
+ var token = match[1];
5714
+ var user = decodeURIComponent(match[2]);
5715
+ var baseUrl = "https://www.arcgis.com/sharing/rest/community/users/" + user;
5716
+ return request(baseUrl, {
5717
+ params: { token: token },
5718
+ httpMethod: "GET"
5719
+ }).then(function (response) {
5720
+ if (Date.now() - response.created < 5000) {
5721
+ return request(baseUrl + "/update", {
5722
+ params: {
5723
+ token: token,
5724
+ tags: ["hubRole:participant", "org:" + response.orgId],
5725
+ access: "public"
5726
+ }
5727
+ }).then(function () {
5728
+ return UserSession.completeOAuth2(options);
5729
+ });
5730
+ }
5731
+ else {
5732
+ return UserSession.completeOAuth2(options);
5733
+ }
5734
+ });
5735
+ }
5736
+
5737
+ var app$1 = [
5738
+ "Application",
5739
+ "City Engine Web Scene",
5740
+ "CityEngine Web Scene",
5741
+ "Dashboard",
5742
+ "Insights Page",
5743
+ "Insights Workbook",
5744
+ "Operation View",
5745
+ "Web Mapping Application",
5746
+ "StoryMap",
5747
+ "Web Experience",
5748
+ "Urban Model",
5749
+ ];
5750
+ var dataset$1 = [
5751
+ "CSV Collection",
5752
+ "CSV",
5753
+ "Feature Collection Template",
5754
+ "Feature Collection",
5755
+ "Feature Layer",
5756
+ "Feature Service",
5757
+ "File Geodatabase",
5758
+ "GeoJSON",
5759
+ "GeoJson",
5760
+ "KML Collection",
5761
+ "KML",
5762
+ "Microsoft Excel",
5763
+ "Raster Layer",
5764
+ "Shapefile",
5765
+ "Stream Service",
5766
+ "Table",
5767
+ ];
5768
+ var document$1 = [
5769
+ "CAD Drawing",
5770
+ "Document Link",
5771
+ "Hub Page",
5772
+ "Site Page",
5773
+ "Image",
5774
+ "iWork Keynote",
5775
+ "iWork Numbers",
5776
+ "iWork Pages",
5777
+ "Microsoft Powerpoint",
5778
+ "Microsoft Visio",
5779
+ "Microsoft Word",
5780
+ "Notebook",
5781
+ "PDF",
5782
+ "Pro Map",
5783
+ "Report Template",
5784
+ ];
5785
+ var event$1 = ["Hub Event"];
5786
+ var feedback$1 = ["Form", "Quick Capture Project"];
5787
+ var initiative$1 = ["Hub Initiative"];
5788
+ var solution = ["Solution"];
5789
+ var template = ["Hub Initiative Template"];
5790
+ var map$1 = [
5791
+ "Image Collection",
5792
+ "Image Service",
5793
+ "Map Service Layer",
5794
+ "Map Service",
5795
+ "Scene Service",
5796
+ "Scene Layer",
5797
+ "Vector Tile Service",
5798
+ "Web Map Service",
5799
+ "Web Map Tile Service",
5800
+ "Web Map",
5801
+ "Web Scene",
5802
+ "WFS",
5803
+ "WMS",
5804
+ "WMTS",
5805
+ ];
5806
+ var other$1 = [
5807
+ "360 VR Experience",
5808
+ "AppBuilder Widget Package",
5809
+ "Application Configuration",
5810
+ "ArcPad Package",
5811
+ "Code Attachment",
5812
+ "Code Sample",
5813
+ "Desktop Add In",
5814
+ "Desktop Application Template",
5815
+ "Desktop Application",
5816
+ "Desktop Style",
5817
+ "Explorer Add In",
5818
+ "Explorer Layer",
5819
+ "Geocoding Service",
5820
+ "Geometry Service",
5821
+ "Geoprocessing Package",
5822
+ "Geoprocessing Sample",
5823
+ "Geoprocessing Service",
5824
+ "Layer File",
5825
+ "Layer Package",
5826
+ "Layer Template",
5827
+ "Layer",
5828
+ "Layout",
5829
+ "Locator Package",
5830
+ "Map Area",
5831
+ "Map Document",
5832
+ "Map Package",
5833
+ "Map Service Definition",
5834
+ "Map Template",
5835
+ "Mobile Application",
5836
+ "Mobile Map Package",
5837
+ "Native Application",
5838
+ "Network Analysis Service",
5839
+ "Operations Dashboard Add In",
5840
+ "Project Package",
5841
+ "Project Template",
5842
+ "Raster Function Template",
5843
+ "Rule Package",
5844
+ "Scene Package",
5845
+ "Service Definition",
5846
+ "SQLite Geodatabase",
5847
+ "Style",
5848
+ "Tile Package",
5849
+ "Vector Tile Package",
5850
+ "Workflow Manager Package",
5851
+ ];
5852
+ var site$1 = ["Hub Site Application", "Site Application"];
5853
+ // TODO: remove this at the next breaking change
5854
+ // it's only here to support deprecated categories
5855
+ var collections = {
5856
+ app: app$1,
5857
+ dataset: dataset$1,
5858
+ document: document$1,
5859
+ event: event$1,
5860
+ feedback: feedback$1,
5861
+ initiative: initiative$1,
5862
+ template: template,
5863
+ solution: solution,
5864
+ map: map$1,
5865
+ other: other$1,
5866
+ site: site$1,
5867
+ };
5868
+
5869
+ var app = collections.app, dataset = collections.dataset, document = collections.document, event = collections.event, feedback = collections.feedback, initiative = collections.initiative, map = collections.map, other = collections.other, site = collections.site;
5870
+ var downloadableTypes = [
5871
+ "360 VR Experience",
5872
+ "Application",
5873
+ "CityEngine Web Scene",
5874
+ "Code Sample",
5875
+ "CSV Collection",
5876
+ "CSV",
5877
+ "CAD Drawing",
5878
+ "Desktop Application",
5879
+ "Desktop Application Template",
5880
+ "Desktop Style",
5881
+ "File Geodatabase",
5882
+ "GeoJson",
5883
+ "Geoprocessing Package",
5884
+ "Geoprocessing Sample",
5245
5885
  "Image",
5246
5886
  "iWork Keynote",
5247
5887
  "iWork Numbers",
@@ -5788,7 +6428,22 @@
5788
6428
  geometry: geometry,
5789
6429
  };
5790
6430
  };
6431
+ var MAX_SIZE = 5000000;
6432
+ /**
6433
+ * Returns whether or not an item is a proxied csv
6434
+ *
6435
+ * @param item
6436
+ * @param requestOptions Hub Request Options (including whether we're in portal)
6437
+ * @returns
6438
+ */
6439
+ var isProxiedCSV = function (item, requestOptions) {
6440
+ return !requestOptions.isPortal &&
6441
+ item.access === "public" &&
6442
+ item.type === "CSV" &&
6443
+ item.size <= MAX_SIZE;
6444
+ };
5791
6445
 
6446
+ // private helper functions
5792
6447
  function collectionToFamily(collection) {
5793
6448
  var overrides = {
5794
6449
  other: "content",
@@ -6395,7 +7050,7 @@
6395
7050
  }
6396
7051
  /**
6397
7052
  * returns a new content that has the specified type and
6398
- * and updated related properties like normalizedType, family, etc
7053
+ * and updated related properties like, family, etc
6399
7054
  * @param content orignal content
6400
7055
  * @param type new type
6401
7056
  * @returns new content
@@ -6406,9 +7061,8 @@
6406
7061
  var family = getFamily(normalizedType);
6407
7062
  var contentTypeIcon = getContentTypeIcon(normalizedType);
6408
7063
  var contentTypeLabel = getContentTypeLabel(normalizedType, content.isProxied);
6409
- // TODO: don't we need to update content.item.type too?
6410
- var updated = __assign(__assign({}, content), { type: type,
6411
- family: family,
7064
+ var updated = __assign(__assign({}, content), { type: normalizedType, family: family,
7065
+ // TODO: remove this at next breaking change now that it has been deprecated
6412
7066
  normalizedType: normalizedType,
6413
7067
  contentTypeIcon: contentTypeIcon,
6414
7068
  contentTypeLabel: contentTypeLabel });
@@ -6419,23 +7073,26 @@
6419
7073
  });
6420
7074
  };
6421
7075
  /**
6422
- * Compute the content type icon based on the normalizedType
6423
- * @param normalizedType
7076
+ * Compute the content type icon based on the content type
7077
+ * @param content type
6424
7078
  * @returns content type icon
6425
7079
  */
6426
- var getContentTypeIcon = function (normalizedType) {
7080
+ var getContentTypeIcon = function (contentType) {
6427
7081
  var _a;
6428
- var type = camelize(normalizedType || "");
7082
+ var type = camelize(contentType || "");
6429
7083
  var iconMap = {
6430
7084
  appbuilderExtension: "file",
6431
7085
  appbuilderWidgetPackage: "widgets-source",
6432
7086
  application: "web",
7087
+ applicationConfiguration: "app-gear",
6433
7088
  arcgisProMap: "desktop",
6434
7089
  cadDrawing: "file-cad",
6435
7090
  cityEngineWebScene: "urban-model",
6436
7091
  codeAttachment: "file-code",
7092
+ codeSample: "file-code",
6437
7093
  colorSet: "palette",
6438
7094
  contentCategorySet: "label",
7095
+ csv: "file-csv",
6439
7096
  cSV: "file-csv",
6440
7097
  cSVCollection: "file-csv",
6441
7098
  dashboard: "dashboard",
@@ -6457,8 +7114,8 @@
6457
7114
  geoprocessingService: "file",
6458
7115
  globeLayer: "layers",
6459
7116
  globeService: "file",
6460
- hubInitiative: "mountain-summit-nocap",
6461
- hubInitiativeTemplate: "initiative-template-outlines-thick",
7117
+ hubInitiative: "initiative",
7118
+ hubInitiativeTemplate: "initiative-template",
6462
7119
  hubPage: "browser",
6463
7120
  hubSiteApplication: "web",
6464
7121
  image: "file-image",
@@ -6474,6 +7131,7 @@
6474
7131
  kMLCollection: "data",
6475
7132
  layer: "layers",
6476
7133
  layerPackage: "layers",
7134
+ layerTemplate: "file",
6477
7135
  locatorPackage: "file",
6478
7136
  mapArea: "file",
6479
7137
  mapDocument: "map-contents",
@@ -6496,6 +7154,7 @@
6496
7154
  orthoMappingTemplate: "file",
6497
7155
  pDF: "file-pdf",
6498
7156
  quickCaptureProject: "mobile",
7157
+ rasterFunctionTemplate: "file",
6499
7158
  rasterLayer: "map",
6500
7159
  realTimeAnalytic: "file",
6501
7160
  relationalDatabaseConnection: "file",
@@ -6504,19 +7163,23 @@
6504
7163
  sceneService: "urban-model",
6505
7164
  serviceDefinition: "file",
6506
7165
  shapefile: "data",
6507
- solution: "solutions",
7166
+ solution: "puzzle-piece",
6508
7167
  sqliteGeodatabase: "file",
6509
7168
  statisticalDataCollection: "file",
7169
+ storymap: "tour",
6510
7170
  storyMap: "tour",
7171
+ storymapTheme: "palette",
6511
7172
  symbolSet: "file",
6512
7173
  table: "table",
6513
7174
  urbanModel: "urban-model",
7175
+ vectorTilePackage: "file-shape",
6514
7176
  vectorTileService: "map",
6515
7177
  visioDocument: "conditional-rules",
6516
7178
  webExperience: "apps",
6517
7179
  webMap: "map",
6518
7180
  webMappingApplication: "apps",
6519
7181
  webScene: "urban-model",
7182
+ wfs: "map",
6520
7183
  wFS: "map",
6521
7184
  wMS: "map",
6522
7185
  wMTS: "map",
@@ -6527,12 +7190,12 @@
6527
7190
  };
6528
7191
  /**
6529
7192
  * Compute the content type label
6530
- * @param normalizedType
7193
+ * @param contentType
6531
7194
  * @param isProxied
6532
7195
  * @returns content type label
6533
7196
  */
6534
- var getContentTypeLabel = function (normalizedType, isProxied) {
6535
- return isProxied ? "CSV" : camelize(normalizedType || "");
7197
+ var getContentTypeLabel = function (contentType, isProxied) {
7198
+ return isProxied ? "CSV" : camelize(contentType || "");
6536
7199
  };
6537
7200
  /**
6538
7201
  * returns a new content that has the specified hubId and updated identifier
@@ -6625,8 +7288,8 @@
6625
7288
  var getSolutionUrl = function (content) {
6626
7289
  var _a;
6627
7290
  var hubUrl;
6628
- var normalizedType = content.normalizedType, identifier = content.identifier;
6629
- if (normalizedType === "Solution") {
7291
+ var type = content.type, identifier = content.identifier;
7292
+ if (type === "Solution") {
6630
7293
  // NOTE: as per the above spreadsheet,
6631
7294
  // solution types are now in the Template family
6632
7295
  // but we don't send them to the route for initiative templates
@@ -6643,10 +7306,25 @@
6643
7306
  // TODO: we check both "Hub Page" and "Site Page" because we don't know whether the site is a portal or not
6644
7307
  // In the future, the site object will have a site.isPortal() function that we can leverage
6645
7308
  // instead of hardcoding the types here.
6646
- // TODO: should this be based on normalizedType instead?
6647
7309
  var isPageContent = function (content) {
6648
7310
  return includes(["Hub Page", "Site Page"], content.type);
6649
7311
  };
7312
+ // proxied csv helpers
7313
+ /**
7314
+ * If an item is a proxied csv, returns the url for the proxying feature layer.
7315
+ * If the item is not a proxied csv, returns undefined.
7316
+ *
7317
+ * @param item
7318
+ * @param requestOptions Hub Request Options (including whether we're in portal)
7319
+ * @returns
7320
+ */
7321
+ var getProxyUrl = function (item, requestOptions) {
7322
+ var result;
7323
+ if (isProxiedCSV(item, requestOptions)) {
7324
+ result = requestOptions.hubApiUrl + "/datasets/" + item.id + "_0/FeatureServer/0";
7325
+ }
7326
+ return result;
7327
+ };
6650
7328
 
6651
7329
  /**
6652
7330
  * Implementation of atob() according to the HTML and Infra specs, except that
@@ -7296,27 +7974,132 @@
7296
7974
  *
7297
7975
  * @returns {IConsolidatedResult} The operations attempted, whether they were successful and any errors
7298
7976
  */
7299
- function addUsersToGroup(groupId, allUsers, primaryRO, email, secondaryRO) {
7300
- // Extract requesting user
7301
- var requestingUser = cloneObject$1(getWithDefault$1(primaryRO, "portalSelf.user", {}));
7302
- requestingUser.cOrgId = getProp(primaryRO, "portalSelf.portalProperties.hub.settings.communityOrg.orgId");
7303
- // Context for each process segment
7304
- var context = {
7305
- groupId: groupId,
7306
- allUsers: allUsers,
7307
- primaryRO: primaryRO,
7308
- email: email,
7309
- secondaryRO: secondaryRO,
7310
- requestingUser: requestingUser,
7311
- usersToAutoAdd: _getAutoAddUsers(allUsers, requestingUser),
7312
- usersToInvite: _getInviteUsers(allUsers, requestingUser),
7313
- usersToEmail: _getEmailUsers(allUsers, requestingUser, getProp(email, "copyMe"))
7977
+ function addUsersToGroup(groupId, allUsers, primaryRO, email, secondaryRO) {
7978
+ // Extract requesting user
7979
+ var requestingUser = cloneObject$1(getWithDefault$1(primaryRO, "portalSelf.user", {}));
7980
+ requestingUser.cOrgId = getProp(primaryRO, "portalSelf.portalProperties.hub.settings.communityOrg.orgId");
7981
+ // Context for each process segment
7982
+ var context = {
7983
+ groupId: groupId,
7984
+ allUsers: allUsers,
7985
+ primaryRO: primaryRO,
7986
+ email: email,
7987
+ secondaryRO: secondaryRO,
7988
+ requestingUser: requestingUser,
7989
+ usersToAutoAdd: _getAutoAddUsers(allUsers, requestingUser),
7990
+ usersToInvite: _getInviteUsers(allUsers, requestingUser),
7991
+ usersToEmail: _getEmailUsers(allUsers, requestingUser, getProp(email, "copyMe"))
7992
+ };
7993
+ return _processAutoAdd(context)
7994
+ .then(_processInvite)
7995
+ .then(_processPrimaryEmail)
7996
+ .then(_processSecondaryEmail)
7997
+ .then(_consolidateResults);
7998
+ }
7999
+
8000
+ /**
8001
+ * Locales supported by the hub
8002
+ */
8003
+ var HUB_LOCALES = [
8004
+ "ar",
8005
+ "bs",
8006
+ "ca",
8007
+ "cs",
8008
+ "da",
8009
+ "de",
8010
+ "en",
8011
+ "es",
8012
+ "et",
8013
+ "el",
8014
+ "fi",
8015
+ "fr",
8016
+ "hr",
8017
+ "he",
8018
+ "hu",
8019
+ "it",
8020
+ "id",
8021
+ "ja",
8022
+ "ko",
8023
+ "lt",
8024
+ "lv",
8025
+ "nb",
8026
+ "nl",
8027
+ "pl",
8028
+ "pt",
8029
+ "pt-br",
8030
+ "pt-pt",
8031
+ "ro",
8032
+ "ru",
8033
+ "sl",
8034
+ "sr",
8035
+ "sv",
8036
+ "th",
8037
+ "tr",
8038
+ "uk",
8039
+ "vi",
8040
+ "zh",
8041
+ "zh-cn",
8042
+ "zh-tw",
8043
+ "zh-hk"
8044
+ ];
8045
+
8046
+ /**
8047
+ * Convert a requested locale into a locale we support.
8048
+ * i.e. en-ca => en
8049
+ * If the requested locale is not available, en will be returned
8050
+ * @param {string} requestedLocale Locale we want
8051
+ */
8052
+ function convertToWellKnownLocale(requestedLocale) {
8053
+ if (requestedLocale === void 0) { requestedLocale = "en"; }
8054
+ var wellKnownKey = "en";
8055
+ // ensure downcase
8056
+ requestedLocale = requestedLocale.toLowerCase();
8057
+ // see if it's in the hub translations as-is
8058
+ if (HUB_LOCALES.indexOf(requestedLocale) > -1) {
8059
+ wellKnownKey = requestedLocale;
8060
+ }
8061
+ else {
8062
+ // if we split the requested locale, see if we have the root in the list
8063
+ var parts = requestedLocale.split("-");
8064
+ if (parts.length > 1 && HUB_LOCALES.indexOf(parts[0]) > -1) {
8065
+ wellKnownKey = parts[0];
8066
+ }
8067
+ }
8068
+ return wellKnownKey;
8069
+ }
8070
+
8071
+ /**
8072
+ * Fetch the Hub translation file for a given locale
8073
+ * These are all public urls and should never require auth/tokens etc
8074
+ * @param {String} locale Locale code - i.e. `es`
8075
+ * @param {Object} portal Portal Self
8076
+ */
8077
+ function fetchHubTranslation(locale, portal, mode) {
8078
+ if (mode === void 0) { mode = "cors"; }
8079
+ var assetBase = getHubLocaleAssetUrl(portal);
8080
+ var url = (assetBase + "/locales/" + locale + ".json").toLocaleLowerCase();
8081
+ // to support web-tier auth, we must always send same-origin credentials
8082
+ var options = {
8083
+ method: "GET",
8084
+ credentials: "same-origin",
8085
+ mode: mode
7314
8086
  };
7315
- return _processAutoAdd(context)
7316
- .then(_processInvite)
7317
- .then(_processPrimaryEmail)
7318
- .then(_processSecondaryEmail)
7319
- .then(_consolidateResults);
8087
+ return fetch(url, options)
8088
+ .then(function (response) { return response.json(); })
8089
+ .catch(function (err) {
8090
+ throw Error("Attempt to fetch locale " + locale + " from " + url + " failed: " + JSON.stringify(err));
8091
+ });
8092
+ }
8093
+
8094
+ /**
8095
+ * Return the culture from the Hub Request Options
8096
+ * In priority order: user.culture, portal.culture, en-us
8097
+ * @param {IHubRequestOptions} hubRequestOptions
8098
+ */
8099
+ function getCulture(hubRequestOptions) {
8100
+ return (getProp(hubRequestOptions, "portalSelf.user.culture") ||
8101
+ getProp(hubRequestOptions, "portalSelf.culture") ||
8102
+ "en-us");
7320
8103
  }
7321
8104
 
7322
8105
  /**
@@ -7392,29 +8175,106 @@
7392
8175
  function failSafeUpdate(model, requestOptions) {
7393
8176
  var failSafedUpdate = failSafe(updateItem, {
7394
8177
  id: model.item.id,
7395
- success: true
8178
+ success: true,
7396
8179
  });
7397
8180
  var opts = Object.assign({ item: serializeModel(model) }, requestOptions);
7398
8181
  return failSafedUpdate(opts);
7399
8182
  }
7400
8183
 
7401
8184
  /**
7402
- * Gets the full item/data model for an item
7403
- * @param {string} id Id of the item to fetch
8185
+ * Gets the full item/data model for an item id
8186
+ * @param {string} id
7404
8187
  * @param {Object} requestOptions
7405
8188
  */
7406
8189
  function getModel(id, requestOptions) {
7407
8190
  return Promise.all([
7408
8191
  getItem(id, requestOptions),
7409
- getItemData(id, requestOptions)
8192
+ getItemData(id, requestOptions),
7410
8193
  ]).then(function (result) {
7411
8194
  // shape this into a model
7412
8195
  return {
7413
8196
  item: result[0],
7414
- data: result[1]
8197
+ data: result[1],
7415
8198
  };
7416
8199
  });
7417
8200
  }
8201
+ /**
8202
+ * Get a model by it's slug
8203
+ *
8204
+ * This uses the [Filter](https://developers.arcgis.com/rest/users-groups-and-items/search-reference.htm) option of the
8205
+ * to search for an item that has a typekeyword of `slug|{slug-value}`
8206
+ *
8207
+ * This is useful for applications that want to use human-readable urls instead
8208
+ * of using item ids.
8209
+ *
8210
+ * @param slug
8211
+ * @param requestOptions
8212
+ * @returns
8213
+ */
8214
+ function getModelBySlug(slug, requestOptions) {
8215
+ return getItemBySlug(slug, requestOptions)
8216
+ .then(function (item) {
8217
+ var prms = [Promise.resolve(item)];
8218
+ if (item) {
8219
+ prms.push(getItemData(item.id, requestOptions));
8220
+ }
8221
+ else {
8222
+ prms.push(Promise.resolve(null));
8223
+ }
8224
+ return Promise.all(prms);
8225
+ })
8226
+ .then(function (result) {
8227
+ if (result[0]) {
8228
+ return {
8229
+ item: result[0],
8230
+ data: result[1],
8231
+ };
8232
+ }
8233
+ else {
8234
+ return null;
8235
+ }
8236
+ });
8237
+ }
8238
+ /**
8239
+ * Create an item to back and IModel.
8240
+ *
8241
+ * @param {IModel}
8242
+ * @param {IRequestOptions} requestOptions
8243
+ * @returns {Promise<IModel>}
8244
+ */
8245
+ function createModel(model, requestOptions) {
8246
+ var clone = cloneObject$1(model);
8247
+ var item = cloneObject$1(model.item);
8248
+ item.data = cloneObject$1(model.data);
8249
+ var opts = __assign({ item: item }, requestOptions);
8250
+ return createItem(opts).then(function (response) {
8251
+ clone.item.id = response.id;
8252
+ clone.item.created = new Date().getTime();
8253
+ clone.item.modified = clone.item.created;
8254
+ return clone;
8255
+ });
8256
+ }
8257
+ /**
8258
+ * Update an IModel. Generic function that will be used across all
8259
+ * type-specific update functions
8260
+ *
8261
+ * @export
8262
+ * @param {IModel} "model" object (i.e. `{item:{...}, data:{...}}`)
8263
+ * @param {IRequestOptions} requestOptions
8264
+ * @returns {Promise<IModel>}
8265
+ */
8266
+ function updateModel(model, requestOptions) {
8267
+ var clone = cloneObject$1(model);
8268
+ var item = cloneObject$1(model.item);
8269
+ item.data = cloneObject$1(model.data);
8270
+ var opts = __assign({ item: item }, requestOptions);
8271
+ return updateItem(opts).then(function () {
8272
+ // update the modified prop
8273
+ // this won't be exact, but it will be very close
8274
+ clone.item.modified = new Date().getTime();
8275
+ return clone;
8276
+ });
8277
+ }
7418
8278
 
7419
8279
  /**
7420
8280
  * To streamline passing of either a model id or the model itself, we use this function
@@ -7435,7 +8295,7 @@
7435
8295
  if (options[idProp]) {
7436
8296
  var failSafeModel = failSafe(getModel, {
7437
8297
  item: { id: options[idProp] },
7438
- isMissing: true
8298
+ isMissing: true,
7439
8299
  });
7440
8300
  return failSafeModel(options[idProp], options);
7441
8301
  }
@@ -7960,28 +8820,284 @@
7960
8820
  }
7961
8821
 
7962
8822
  /**
7963
- * Interpolates handlebars-style placeholders on an object graph
7964
- * @param template
7965
- * @param settings
7966
- * @param transforms
8823
+ * Interpolates handlebars-style placeholders on an object graph
8824
+ * @param template
8825
+ * @param settings
8826
+ * @param transforms
8827
+ */
8828
+ function interpolate(template, settings, transforms) {
8829
+ return adlib(template, settings, transforms);
8830
+ }
8831
+
8832
+ /**
8833
+ * Interpolate the item id back into any {{appid}} instances
8834
+ * in the item. Allows for self-referencing in templates
8835
+ * @param {object} model Item Model
8836
+ */
8837
+ function interpolateItemId(model) {
8838
+ var settings = { item: { id: model.item.id }, appid: model.item.id };
8839
+ var transforms = {
8840
+ toISO: function (_, v) {
8841
+ return v;
8842
+ }
8843
+ };
8844
+ return interpolate(model, settings, transforms);
8845
+ }
8846
+
8847
+ /**
8848
+ * Replaces instances of item ids on an item model
8849
+ * @param {Object} obj Object graph to traverse
8850
+ * @param {string} itemId id to replace with `{{appid}}`
8851
+ */
8852
+ function replaceItemId(obj, itemId, replacement) {
8853
+ if (replacement === void 0) { replacement = "{{appid}}"; }
8854
+ var clone = cloneObject$1(obj);
8855
+ var re = new RegExp(itemId, "g");
8856
+ return deepStringReplace(clone, re, replacement);
8857
+ }
8858
+
8859
+ /**
8860
+ * Share an item to a set of groups
8861
+ * @param {String} itemId Iten Id to share to the groups
8862
+ * @param {Array} groups Array of group id's to which the item will be shared
8863
+ * @param {String} owner optional Owner username to determine which endpoint to hit
8864
+ * @param {*} requestOptions
8865
+ */
8866
+ function shareItemToGroups(itemId, groups, requestOptions, owner) {
8867
+ return Promise.all(groups.map(function (groupId) {
8868
+ var opt = Object.assign({}, { id: itemId, groupId: groupId }, requestOptions);
8869
+ if (owner) {
8870
+ opt.owner = owner;
8871
+ }
8872
+ return shareItemWithGroup(opt);
8873
+ }));
8874
+ }
8875
+
8876
+ /**
8877
+ * Given a model, determine if it is protected, and unprotect it if it is.
8878
+ * Otherwise, just resolve with the same result.
8879
+ * @param {Object} model Model Object
8880
+ * @param {IRequestOptions} requestOptions
8881
+ */
8882
+ function unprotectModel(model, requestOptions) {
8883
+ if (model.item.protected) {
8884
+ var opts = Object.assign({ id: model.item.id }, requestOptions);
8885
+ return unprotectItem(opts);
8886
+ }
8887
+ else {
8888
+ // act as though we did it
8889
+ return Promise.resolve({ success: true });
8890
+ }
8891
+ }
8892
+
8893
+ /**
8894
+ * Unshare an item from a set of groups
8895
+ * @param {String} itemId Item Id to unshare from groups
8896
+ * @param {Array} groups Array of group id's from which the item will be unshared
8897
+ * @param {String} owner optional Owner username to determine which endpoint to hit
8898
+ * @param {IRequestOptions} requestOptions
8899
+ */
8900
+ function unshareItemFromGroups(itemId, groups, requestOptions, owner) {
8901
+ return Promise.all(groups.map(function (groupId) {
8902
+ var opt = Object.assign({}, { id: itemId, groupId: groupId }, requestOptions);
8903
+ if (owner) {
8904
+ opt.owner = owner;
8905
+ }
8906
+ return unshareItemWithGroup(opt);
8907
+ }));
8908
+ }
8909
+
8910
+ /**
8911
+ * Check if a site/page exists with a specific name
8912
+ */
8913
+ function doesItemExistWithTitle(itemTitle, options, authMgr) {
8914
+ // if options have multiple properties, put them into one string separated with 'AND'
8915
+ var optionsQuery = Object.keys(options)
8916
+ .map(function (key) {
8917
+ return key + ":\"" + options[key] + "\"";
8918
+ })
8919
+ .join(" AND ");
8920
+ var opts = {
8921
+ q: "title:\"" + itemTitle + "\" AND " + optionsQuery,
8922
+ authentication: authMgr
8923
+ };
8924
+ return searchItems(opts)
8925
+ .then(function (searchResponse) { return searchResponse.results.length > 0; })
8926
+ .catch(function (e) {
8927
+ throw Error("Error in doesItemExistWithTitle " + e);
8928
+ });
8929
+ }
8930
+
8931
+ /**
8932
+ * Given a title, construct a site/page title that is unique
8933
+ * if that title exists, this fn will add a number on the end, and increment until
8934
+ * an available title is found
8935
+ * @param {string} title site/page title to ensure if unique
8936
+ * @param {object} options an object that can be passed in to the q, eg. typekeywords, type
8937
+ * @param {object} authMgr auth info tells the function what url to use for the "root" of the API,
8938
+ * if missing, it will search against PROD
8939
+ * @param {number} step Number to increment. Defaults to 0
8940
+ */
8941
+ function getUniqueItemTitle(title, options, authMgr, step) {
8942
+ if (step === void 0) { step = 0; }
8943
+ var combinedName = title;
8944
+ if (step) {
8945
+ combinedName = title + " " + step;
8946
+ }
8947
+ return doesItemExistWithTitle(combinedName, options, authMgr)
8948
+ .then(function (result) {
8949
+ if (result) {
8950
+ step++;
8951
+ return getUniqueItemTitle(title, options, authMgr, step);
8952
+ }
8953
+ else {
8954
+ return combinedName;
8955
+ }
8956
+ })
8957
+ .catch(function (e) {
8958
+ throw Error("Error in getUniqueItemTitle " + e);
8959
+ });
8960
+ }
8961
+
8962
+ var MAX_NUM = 100;
8963
+ /**
8964
+ * Fetches all the pages in a search request
8965
+ * @param {SearchFunction} searchFunc
8966
+ * @param {ISearchOptions} opts
8967
+ * @param {number} limit
8968
+ * @param {batchSize} number of concurrent requests at a time
8969
+ * @returns {Promise<SearchableType[]>}
8970
+ */
8971
+ function fetchAllPages(searchFunc, opts, limit, batchSize) {
8972
+ if (limit === void 0) { limit = -1; }
8973
+ var pageSize = opts.num || MAX_NUM;
8974
+ var firstStart = opts.start || 1;
8975
+ // If a limit is provided, we don't have to use the first request to get the
8976
+ // total count before sending things off to batch(). So instead we fake the first
8977
+ // response just to set things up.
8978
+ var promise = limit === -1
8979
+ ? searchFunc(__assign(__assign({}, opts), { num: pageSize, start: firstStart }))
8980
+ : Promise.resolve({
8981
+ nextStart: firstStart,
8982
+ total: limit,
8983
+ results: [],
8984
+ num: pageSize
8985
+ });
8986
+ return promise
8987
+ .then(function (firstResponse) {
8988
+ // no more requests needed, return the first response
8989
+ if (firstResponse.nextStart === -1)
8990
+ return [firstResponse];
8991
+ // generate batch requests for the remaining pages to fetch
8992
+ var starts = [];
8993
+ for (var i = firstResponse.nextStart; i <= firstResponse.total; i += pageSize) {
8994
+ starts.push(i);
8995
+ }
8996
+ var batchSearchFunc = function (start) {
8997
+ return searchFunc(__assign(__assign({}, opts), { start: start, num: pageSize }));
8998
+ };
8999
+ return batch(starts, batchSearchFunc, batchSize).then(function (responses) { return __spreadArrays([
9000
+ firstResponse
9001
+ ], responses); });
9002
+ })
9003
+ .then(function (responses) {
9004
+ // merge all the search results into a single array
9005
+ var results = responses.reduce(function (acc, response) { return __spreadArrays(acc, response.results); }, []);
9006
+ // discard results beyond the limit if applicable
9007
+ var clipLimit = limit === -1 ? results.length : limit;
9008
+ return results.slice(0, clipLimit);
9009
+ });
9010
+ }
9011
+
9012
+ // TODO: work out how to unify content slug fns
9013
+ // https: github.com/Esri/hub.js/blob/master/packages/common/src/content/index.ts#L301-L348
9014
+ /**
9015
+ * Create a slug, namespaced to an org
9016
+ * Typically used to lookup items by a human readable name in urls
9017
+ *
9018
+ * @param title
9019
+ * @param orgKey
9020
+ * @returns
7967
9021
  */
7968
- function interpolate(template, settings, transforms) {
7969
- return adlib(template, settings, transforms);
9022
+ function constructSlug(title, orgKey) {
9023
+ return orgKey.toLowerCase() + "-" + slugify(title);
7970
9024
  }
7971
-
7972
9025
  /**
7973
- * Interpolate the item id back into any {{appid}} instances
7974
- * in the item. Allows for self-referencing in templates
7975
- * @param {object} model Item Model
9026
+ * Adds/Updates the slug typekeyword
9027
+ * Returns a new array of keywords
9028
+ * @param typeKeywords
9029
+ * @param slug
9030
+ * @returns
7976
9031
  */
7977
- function interpolateItemId(model) {
7978
- var settings = { item: { id: model.item.id }, appid: model.item.id };
7979
- var transforms = {
7980
- toISO: function (_, v) {
7981
- return v;
7982
- }
9032
+ function setSlugKeyword(typeKeywords, slug) {
9033
+ // remove slug entry from array
9034
+ var removed = typeKeywords.filter(function (entry) {
9035
+ return !entry.startsWith("slug|");
9036
+ });
9037
+ // now add it
9038
+ removed.push("slug|" + slug);
9039
+ return removed;
9040
+ }
9041
+ /**
9042
+ * Get an item by searching for items with a typeKeyword like `slug|{slug-value}`
9043
+ *
9044
+ * For example, if you pass a slug `"snow-map"` into this function, it will
9045
+ * search for items with `slug|snow-map` in it's typeKeywords array,
9046
+ *
9047
+ * @param slug
9048
+ * @param requestOptions
9049
+ * @returns
9050
+ */
9051
+ function getItemBySlug(slug, requestOptions) {
9052
+ var opts = {
9053
+ q: "",
9054
+ filter: "typekeywords:\"slug|" + slug + "\"",
9055
+ authentication: requestOptions.authentication,
7983
9056
  };
7984
- return interpolate(model, settings, transforms);
9057
+ return searchItems(opts)
9058
+ .then(function (response) {
9059
+ if (response.results.length) {
9060
+ return response.results[0];
9061
+ }
9062
+ else {
9063
+ return null;
9064
+ }
9065
+ })
9066
+ .catch(function (e) {
9067
+ throw Error("Error in getItemBySlug " + e);
9068
+ });
9069
+ }
9070
+ /**
9071
+ * Given a slug, search for items using that slug, incrementing the slug name until
9072
+ * a unique value is found
9073
+ *
9074
+ * For example, if a slug of `"snow-map"` into this function and some item exists
9075
+ * with that slug, it would return `"snow-map-1"`.
9076
+ *
9077
+ * @param slug
9078
+ * @param requestOptions
9079
+ * @param step
9080
+ * @returns
9081
+ */
9082
+ function getUniqueSlug(slug, requestOptions, step) {
9083
+ if (step === void 0) { step = 0; }
9084
+ var combined = slug;
9085
+ if (step) {
9086
+ combined = slug + "-" + step;
9087
+ }
9088
+ return getItemBySlug(combined, requestOptions)
9089
+ .then(function (result) {
9090
+ if (result) {
9091
+ step++;
9092
+ return getUniqueSlug(slug, requestOptions, step);
9093
+ }
9094
+ else {
9095
+ return combined;
9096
+ }
9097
+ })
9098
+ .catch(function (e) {
9099
+ throw Error("Error in getUniqueSlug " + e);
9100
+ });
7985
9101
  }
7986
9102
 
7987
9103
  var itemPropsNotInTemplates = [
@@ -8028,167 +9144,514 @@
8028
9144
  }
8029
9145
 
8030
9146
  /**
8031
- * Replaces instances of item ids on an item model
8032
- * @param {Object} obj Object graph to traverse
8033
- * @param {string} itemId id to replace with `{{appid}}`
9147
+ * Manage forward and backward property mappings to
9148
+ * streamline conversion between the Hub entities, and
9149
+ * the backing IModel
8034
9150
  */
8035
- function replaceItemId(obj, itemId, replacement) {
8036
- if (replacement === void 0) { replacement = "{{appid}}"; }
8037
- var clone = cloneObject$1(obj);
8038
- var re = new RegExp(itemId, "g");
8039
- return deepStringReplace(clone, re, replacement);
9151
+ var PropertyMapper = /** @class */ (function () {
9152
+ /**
9153
+ * Pass in the mappings between the Entity and
9154
+ * it's backing structure (model or otherwise)
9155
+ * @param mappings
9156
+ */
9157
+ function PropertyMapper(mappings) {
9158
+ this.mappings = mappings;
9159
+ }
9160
+ /**
9161
+ * Map properties from a model on to the entity object.
9162
+ *
9163
+ * Used when constructing an entity can from a fetched model,
9164
+ * in which case the entity should be an empty object (`{}`).
9165
+ *
9166
+ * Can also be used to apply changes to an entity from a model,
9167
+ * in which case an existing entity can be passed in.
9168
+ * @param model
9169
+ * @param object
9170
+ * @returns
9171
+ */
9172
+ PropertyMapper.prototype.modelToObject = function (model, object) {
9173
+ return mapModelToObject(model, object, this.mappings);
9174
+ };
9175
+ /**
9176
+ * Map properties from an entity object onto a model.
9177
+ *
9178
+ * Typically the model will already exist, and this
9179
+ * method is used to transfer changes to the model
9180
+ * prior to storage.
9181
+ * @param object
9182
+ * @param model
9183
+ * @returns
9184
+ */
9185
+ PropertyMapper.prototype.objectToModel = function (object, model) {
9186
+ return mapObjectToModel(object, model, this.mappings);
9187
+ };
9188
+ return PropertyMapper;
9189
+ }());
9190
+ /**
9191
+ * Generic function to apply properties from an Object
9192
+ * (i.e. IHubProject) onto a Model that can be persisted to an Item
9193
+ * @param object
9194
+ * @param model
9195
+ * @param mappings
9196
+ * @returns
9197
+ */
9198
+ function mapObjectToModel(object, model, mappings) {
9199
+ return mapProps(object, "objectKey", model, "modelKey", mappings);
8040
9200
  }
8041
-
8042
9201
  /**
8043
- * Share an item to a set of groups
8044
- * @param {String} itemId Iten Id to share to the groups
8045
- * @param {Array} groups Array of group id's to which the item will be shared
8046
- * @param {String} owner optional Owner username to determine which endpoint to hit
8047
- * @param {*} requestOptions
9202
+ * Generic function to apply properties from a Model
9203
+ * onto an Object (i.e. IHubProject etc)
9204
+ * @param model
9205
+ * @param object
9206
+ * @param mappings
9207
+ * @returns
8048
9208
  */
8049
- function shareItemToGroups(itemId, groups, requestOptions, owner) {
8050
- return Promise.all(groups.map(function (groupId) {
8051
- var opt = Object.assign({}, { id: itemId, groupId: groupId }, requestOptions);
8052
- if (owner) {
8053
- opt.owner = owner;
9209
+ function mapModelToObject(model, object, mappings) {
9210
+ return mapProps(model, "modelKey", object, "objectKey", mappings);
9211
+ }
9212
+ /**
9213
+ * Internal function to map between objects
9214
+ * @param source
9215
+ * @param sourceKey
9216
+ * @param target
9217
+ * @param targetKey
9218
+ * @param mappings
9219
+ * @returns
9220
+ */
9221
+ function mapProps(source, sourceKey, target, targetKey, mappings) {
9222
+ // clone the target
9223
+ var clone = cloneObject$1(target);
9224
+ // walk the property map array
9225
+ mappings.forEach(function (entry) {
9226
+ // Verbose b/c typescript hates the use of property indexing with generics
9227
+ // i.e. entry<T>[sourceKey] make typescript angry
9228
+ var sourcePath = getProp(entry, sourceKey);
9229
+ var targetPath = getProp(entry, targetKey);
9230
+ // get the value from the source
9231
+ var sourceVal = getProp(source, sourcePath);
9232
+ // if it's not null or undefined
9233
+ if (sourceVal !== null && sourceVal !== undefined) {
9234
+ // set it
9235
+ deepSet(clone, targetPath, sourceVal);
8054
9236
  }
8055
- return shareItemWithGroup(opt);
8056
- }));
9237
+ });
9238
+ return clone;
8057
9239
  }
8058
9240
 
9241
+ var HUB_PROJECT_ITEM_TYPE = "Web Mapping Application";
8059
9242
  /**
8060
- * Given a model, determine if it is protected, and unprotect it if it is.
8061
- * Otherwise, just resolve with the same result.
8062
- * @param {Object} model Model Object
8063
- * @param {IRequestOptions} requestOptions
9243
+ * Default values of a IHubProject
8064
9244
  */
8065
- function unprotectModel(model, requestOptions) {
8066
- if (model.item.protected) {
8067
- var opts = Object.assign({ id: model.item.id }, requestOptions);
8068
- return unprotectItem(opts);
9245
+ var DEFAULT_PROJECT = {
9246
+ name: "No title provided",
9247
+ tags: [],
9248
+ typeKeywords: ["IHubProject", "HubProject"],
9249
+ };
9250
+ /**
9251
+ * Default values for a new HubProject Model
9252
+ */
9253
+ var DEFAULT_PROJECT_MODEL = {
9254
+ item: {
9255
+ type: HUB_PROJECT_ITEM_TYPE,
9256
+ title: "No Title Provided",
9257
+ description: "No Description Provided",
9258
+ snippet: "",
9259
+ tags: [],
9260
+ typeKeywords: [],
9261
+ properties: {
9262
+ slug: "",
9263
+ },
9264
+ },
9265
+ data: {
9266
+ display: "about",
9267
+ timeline: {},
9268
+ org: {},
9269
+ status: "inactive",
9270
+ contacts: [],
9271
+ schemaVersion: 1,
9272
+ },
9273
+ };
9274
+ /**
9275
+ * Returns an Array of IPropertyMap objects
9276
+ * We could define these directly, but since the
9277
+ * properties of IHubProject map directly to properties
9278
+ * on item or data, it's slightly less verbose to
9279
+ * generate the structure.
9280
+ * @returns
9281
+ */
9282
+ function getProjectPropertyMap() {
9283
+ var itemProps = [
9284
+ "created",
9285
+ "culture",
9286
+ "description",
9287
+ "extent",
9288
+ "id",
9289
+ "modified",
9290
+ "owner",
9291
+ "snippet",
9292
+ "tags",
9293
+ "typeKeywords",
9294
+ "url",
9295
+ "type",
9296
+ ];
9297
+ var dataProps = [
9298
+ "contacts",
9299
+ "display",
9300
+ "geometry",
9301
+ "headerImage",
9302
+ "layout",
9303
+ "location",
9304
+ "status",
9305
+ ];
9306
+ var map = [];
9307
+ itemProps.forEach(function (entry) {
9308
+ map.push({ objectKey: entry, modelKey: "item." + entry });
9309
+ });
9310
+ dataProps.forEach(function (entry) {
9311
+ map.push({ objectKey: entry, modelKey: "data." + entry });
9312
+ });
9313
+ // Deeper mappings
9314
+ map.push({
9315
+ objectKey: "slug",
9316
+ modelKey: "item.properties.slug",
9317
+ });
9318
+ map.push({
9319
+ objectKey: "orgUrlKey",
9320
+ modelKey: "item.properties.orgUrlKey",
9321
+ });
9322
+ map.push({
9323
+ objectKey: "name",
9324
+ modelKey: "item.title",
9325
+ });
9326
+ return map;
9327
+ }
9328
+ /**
9329
+ * Create a new Hub Project item
9330
+ *
9331
+ * Minimal properties are name and org
9332
+ *
9333
+ * @param project
9334
+ * @param requestOptions
9335
+ */
9336
+ function createProject(partialProject, requestOptions) {
9337
+ return __awaiter(this, void 0, void 0, function () {
9338
+ var project, _a, mapper, model, newProject;
9339
+ return __generator(this, function (_b) {
9340
+ switch (_b.label) {
9341
+ case 0:
9342
+ project = __assign(__assign({}, DEFAULT_PROJECT), partialProject);
9343
+ // Create a slug from the title if one is not passed in
9344
+ if (!project.slug) {
9345
+ project.slug = constructSlug(project.name, project.orgUrlKey);
9346
+ }
9347
+ // Ensure slug is unique
9348
+ _a = project;
9349
+ return [4 /*yield*/, getUniqueSlug(project.slug, requestOptions)];
9350
+ case 1:
9351
+ // Ensure slug is unique
9352
+ _a.slug = _b.sent();
9353
+ // add slug to keywords
9354
+ project.typeKeywords = setSlugKeyword(project.typeKeywords, project.slug);
9355
+ mapper = new PropertyMapper(getProjectPropertyMap());
9356
+ model = mapper.objectToModel(project, cloneObject$1(DEFAULT_PROJECT_MODEL));
9357
+ return [4 /*yield*/, createModel(model, requestOptions)];
9358
+ case 2:
9359
+ // create the item
9360
+ model = _b.sent();
9361
+ newProject = mapper.modelToObject(model, {});
9362
+ // and return it
9363
+ return [2 /*return*/, newProject];
9364
+ }
9365
+ });
9366
+ });
9367
+ }
9368
+ /**
9369
+ * Update a Hub Project
9370
+ * @param project
9371
+ * @param requestOptions
9372
+ */
9373
+ function updateProject(project, requestOptions) {
9374
+ return __awaiter(this, void 0, void 0, function () {
9375
+ var _a, model, mapper, modelToUpdate, updatedModel, updatedProject;
9376
+ return __generator(this, function (_b) {
9377
+ switch (_b.label) {
9378
+ case 0:
9379
+ // verify that the slug is unique
9380
+ // TODO: if the slug has not changed, we don't want to do this because
9381
+ // the existing item will cause this to increment
9382
+ _a = project;
9383
+ return [4 /*yield*/, getUniqueSlug(project.slug, requestOptions)];
9384
+ case 1:
9385
+ // verify that the slug is unique
9386
+ // TODO: if the slug has not changed, we don't want to do this because
9387
+ // the existing item will cause this to increment
9388
+ _a.slug = _b.sent();
9389
+ return [4 /*yield*/, getModel(project.id, requestOptions)];
9390
+ case 2:
9391
+ model = _b.sent();
9392
+ mapper = new PropertyMapper(getProjectPropertyMap());
9393
+ modelToUpdate = mapper.objectToModel(project, model);
9394
+ return [4 /*yield*/, updateModel(modelToUpdate, requestOptions)];
9395
+ case 3:
9396
+ updatedModel = _b.sent();
9397
+ updatedProject = mapper.modelToObject(updatedModel, project);
9398
+ // the casting is needed because modelToObject returns a `Partial<T>`
9399
+ // where as this function returns a `T`
9400
+ return [2 /*return*/, updatedProject];
9401
+ }
9402
+ });
9403
+ });
9404
+ }
9405
+ /**
9406
+ * Get a Hub Project by id or slug
9407
+ * @param identifier item id or slug
9408
+ * @param requestOptions
9409
+ */
9410
+ function getProject(identifier, requestOptions) {
9411
+ var getPrms;
9412
+ if (isGuid(identifier)) {
9413
+ // get item by id
9414
+ getPrms = getModel(identifier, requestOptions);
8069
9415
  }
8070
9416
  else {
8071
- // act as though we did it
8072
- return Promise.resolve({ success: true });
8073
- }
9417
+ // search for item using filter=typekeywords:slug|identifier
9418
+ getPrms = getModelBySlug(identifier, requestOptions);
9419
+ }
9420
+ return getPrms.then(function (model) {
9421
+ // transform the model into a HubProject
9422
+ var mapper = new PropertyMapper(getProjectPropertyMap());
9423
+ var project = mapper.modelToObject(model, {});
9424
+ return project;
9425
+ });
9426
+ }
9427
+ /**
9428
+ * Remove a Hub Project
9429
+ * @param id
9430
+ * @param requestOptions
9431
+ */
9432
+ function destroyProject(id, requestOptions) {
9433
+ return __awaiter(this, void 0, void 0, function () {
9434
+ var ro;
9435
+ return __generator(this, function (_a) {
9436
+ switch (_a.label) {
9437
+ case 0:
9438
+ ro = __assign(__assign({}, requestOptions), { id: id });
9439
+ return [4 /*yield*/, removeItem(ro)];
9440
+ case 1:
9441
+ _a.sent();
9442
+ return [2 /*return*/];
9443
+ }
9444
+ });
9445
+ });
8074
9446
  }
9447
+ // WIP: Need to resolve how best to execute this
9448
+ // i.e. delegate to searchContent or just do an item search
9449
+ // and convert to IHubProject objects.
9450
+ //
9451
+ // export async function searchProjects(
9452
+ // filter: Filter<"content">,
9453
+ // opts: IHubSearchOptions
9454
+ // ): Promise<ISearchResponse<IHubProject>> {
9455
+ // return _searchContent(filter, opts).then((results) => {
9456
+ // })
9457
+ // }
8075
9458
 
8076
9459
  /**
8077
- * Unshare an item from a set of groups
8078
- * @param {String} itemId Item Id to unshare from groups
8079
- * @param {Array} groups Array of group id's from which the item will be unshared
8080
- * @param {String} owner optional Owner username to determine which endpoint to hit
8081
- * @param {IRequestOptions} requestOptions
9460
+ * Centralized functions used to manage IHubProject instances
9461
+ *
9462
+ * This class is a convenience wrapper over util functions which
9463
+ * are also directly accessible for use in scenarios where
9464
+ * classes are inconvenient.
8082
9465
  */
8083
- function unshareItemFromGroups(itemId, groups, requestOptions, owner) {
8084
- return Promise.all(groups.map(function (groupId) {
8085
- var opt = Object.assign({}, { id: itemId, groupId: groupId }, requestOptions);
8086
- if (owner) {
8087
- opt.owner = owner;
9466
+ var HubProjectManager = /** @class */ (function () {
9467
+ /**
9468
+ * Private so we can employ a factory function should we need
9469
+ * async work during creation
9470
+ * @param contextOrManager
9471
+ */
9472
+ function HubProjectManager(contextOrManager) {
9473
+ if (contextOrManager instanceof ArcGISContextManager) {
9474
+ this._contextManager = contextOrManager;
8088
9475
  }
8089
- return unshareItemWithGroup(opt);
8090
- }));
8091
- }
9476
+ else {
9477
+ this._context = contextOrManager;
9478
+ }
9479
+ }
9480
+ /**
9481
+ * Factory function to construct a new HubProjectManager instance.
9482
+ *
9483
+ * Note: Used so that we could do async actions in the ctor.
9484
+ * @param contextOrManager
9485
+ * @returns
9486
+ */
9487
+ HubProjectManager.init = function (contextOrManager) {
9488
+ return new HubProjectManager(contextOrManager);
9489
+ };
9490
+ Object.defineProperty(HubProjectManager.prototype, "context", {
9491
+ /**
9492
+ * Getter to abstract how we store the context
9493
+ */
9494
+ get: function () {
9495
+ if (this._contextManager) {
9496
+ return this._contextManager.context;
9497
+ }
9498
+ else {
9499
+ return this._context;
9500
+ }
9501
+ },
9502
+ enumerable: false,
9503
+ configurable: true
9504
+ });
9505
+ /**
9506
+ * Create and store new project.
9507
+ *
9508
+ * Projects are stored as Items in the Sharing API
9509
+ * @param project
9510
+ * @param requestOptions
9511
+ * @returns
9512
+ */
9513
+ HubProjectManager.prototype.create = function (project, requestOptions) {
9514
+ return __awaiter(this, void 0, void 0, function () {
9515
+ return __generator(this, function (_a) {
9516
+ if (requestOptions || this.context.isAuthenticated) {
9517
+ // ammend in the orgUrlKey
9518
+ if (!project.orgUrlKey) {
9519
+ project.orgUrlKey = this.context.portal.urlKey;
9520
+ }
9521
+ return [2 /*return*/, createProject(project, requestOptions || this.context.userRequestOptions)];
9522
+ }
9523
+ else {
9524
+ throw new HubError("Create Project", "Creating Hub Projects requires authentication.");
9525
+ }
9526
+ });
9527
+ });
9528
+ };
9529
+ /**
9530
+ * Update a project
9531
+ * @param project
9532
+ * @param requestOptions
9533
+ * @returns
9534
+ */
9535
+ HubProjectManager.prototype.update = function (project, requestOptions) {
9536
+ return __awaiter(this, void 0, void 0, function () {
9537
+ return __generator(this, function (_a) {
9538
+ if (requestOptions || this.context.isAuthenticated) {
9539
+ return [2 /*return*/, updateProject(project, requestOptions || this.context.userRequestOptions)];
9540
+ }
9541
+ else {
9542
+ throw new HubError("Update Project", "Updating Hub Projects requires authentication.");
9543
+ }
9544
+ });
9545
+ });
9546
+ };
9547
+ /**
9548
+ * Destroy a project.
9549
+ * This permanently removes the backing Item
9550
+ * @param id
9551
+ * @param requestOptions
9552
+ * @returns
9553
+ */
9554
+ HubProjectManager.prototype.destroy = function (id, requestOptions) {
9555
+ return __awaiter(this, void 0, void 0, function () {
9556
+ return __generator(this, function (_a) {
9557
+ if (requestOptions || this.context.isAuthenticated) {
9558
+ return [2 /*return*/, destroyProject(id, requestOptions || this.context.userRequestOptions)];
9559
+ }
9560
+ else {
9561
+ throw new HubError("Destroy Project", "Destroying Hub Projects requires authentication.");
9562
+ }
9563
+ });
9564
+ });
9565
+ };
9566
+ /**
9567
+ * Fetch a Project via id or it's slug
9568
+ *
9569
+ * This function does not require a user to be
9570
+ * authenticated, but it does require an `IRequestOptions`
9571
+ * which contains the portal instance to communicate with
9572
+ * @param identifier
9573
+ * @param requestOptions
9574
+ * @returns
9575
+ */
9576
+ HubProjectManager.prototype.fetch = function (identifier, requestOptions) {
9577
+ return __awaiter(this, void 0, void 0, function () {
9578
+ return __generator(this, function (_a) {
9579
+ if (requestOptions || this.context.requestOptions) {
9580
+ return [2 /*return*/, getProject(identifier, requestOptions || this.context.requestOptions)];
9581
+ }
9582
+ else {
9583
+ throw new HubError("Get Project", "Can not retrieve context.requestOptions from Context Manager. HubProjectManager is configured incorrectly.");
9584
+ }
9585
+ });
9586
+ });
9587
+ };
9588
+ return HubProjectManager;
9589
+ }());
8092
9590
 
8093
9591
  /**
8094
- * Check if a site/page exists with a specific name
9592
+ * remote server error
8095
9593
  */
8096
- function doesItemExistWithTitle(itemTitle, options, authMgr) {
8097
- // if options have multiple properties, put them into one string separated with 'AND'
8098
- var optionsQuery = Object.keys(options)
8099
- .map(function (key) {
8100
- return key + ":\"" + options[key] + "\"";
8101
- })
8102
- .join(" AND ");
8103
- var opts = {
8104
- q: "title:\"" + itemTitle + "\" AND " + optionsQuery,
8105
- authentication: authMgr
8106
- };
8107
- return searchItems(opts)
8108
- .then(function (searchResponse) { return searchResponse.results.length > 0; })
8109
- .catch(function (e) {
8110
- throw Error("Error in doesItemExistWithTitle " + e);
8111
- });
8112
- }
8113
-
9594
+ var RemoteServerError = /** @class */ (function (_super) {
9595
+ __extends(RemoteServerError, _super);
9596
+ function RemoteServerError(message, url, status) {
9597
+ var _this = _super.call(this, message) || this;
9598
+ _this.status = status;
9599
+ _this.url = url;
9600
+ return _this;
9601
+ }
9602
+ return RemoteServerError;
9603
+ }(Error));
8114
9604
  /**
8115
- * Given a title, construct a site/page title that is unique
8116
- * if that title exists, this fn will add a number on the end, and increment until
8117
- * an available title is found
8118
- * @param {string} title site/page title to ensure if unique
8119
- * @param {object} options an object that can be passed in to the q, eg. typekeywords, type
8120
- * @param {object} authMgr auth info tells the function what url to use for the "root" of the API,
8121
- * if missing, it will search against PROD
8122
- * @param {number} step Number to increment. Defaults to 0
9605
+ * ```js
9606
+ * import { hubApiRequest } from "@esri/hub-common";
9607
+ * //
9608
+ * hubApiRequest(
9609
+ * "/datasets",
9610
+ * requestOptions
9611
+ * })
9612
+ * .then(response);
9613
+ * ```
9614
+ * make a request to the Hub API
9615
+ * @param route API route
9616
+ * @param requestOptions request options
8123
9617
  */
8124
- function getUniqueItemTitle(title, options, authMgr, step) {
8125
- if (step === void 0) { step = 0; }
8126
- var combinedName = title;
8127
- if (step) {
8128
- combinedName = title + " " + step;
9618
+ function hubApiRequest(route, requestOptions) {
9619
+ // merge in default request options
9620
+ var options = __assign({
9621
+ // why do we default to GET w/ our API?
9622
+ httpMethod: "GET" }, requestOptions);
9623
+ // use fetch override if any
9624
+ var _fetch = options.fetch || fetch;
9625
+ // merge in default headers
9626
+ var headers = __assign({ "Content-Type": "application/json" }, options.headers);
9627
+ // build query params/body based on requestOptions.params
9628
+ var query;
9629
+ var body;
9630
+ if (options.httpMethod === "GET") {
9631
+ // pass params in query string
9632
+ query = options.params;
8129
9633
  }
8130
- return doesItemExistWithTitle(combinedName, options, authMgr)
8131
- .then(function (result) {
8132
- if (result) {
8133
- step++;
8134
- return getUniqueItemTitle(title, options, authMgr, step);
9634
+ else {
9635
+ // pass params in request body
9636
+ body = JSON.stringify(options.params);
9637
+ }
9638
+ // build Hub API URL
9639
+ var url = buildUrl({
9640
+ host: getHubApiUrl(options),
9641
+ path: ("/api/v3/" + route).replace(/\/\//g, "/"),
9642
+ query: query,
9643
+ });
9644
+ return _fetch(url, {
9645
+ method: options.httpMethod,
9646
+ headers: headers,
9647
+ body: body,
9648
+ }).then(function (resp) {
9649
+ if (resp.ok) {
9650
+ return resp.json();
8135
9651
  }
8136
9652
  else {
8137
- return combinedName;
8138
- }
8139
- })
8140
- .catch(function (e) {
8141
- throw Error("Error in getUniqueItemTitle " + e);
8142
- });
8143
- }
8144
-
8145
- var MAX_NUM = 100;
8146
- /**
8147
- * Fetches all the pages in a search request
8148
- * @param {SearchFunction} searchFunc
8149
- * @param {ISearchOptions} opts
8150
- * @param {number} limit
8151
- * @param {batchSize} number of concurrent requests at a time
8152
- * @returns {Promise<SearchableType[]>}
8153
- */
8154
- function fetchAllPages(searchFunc, opts, limit, batchSize) {
8155
- if (limit === void 0) { limit = -1; }
8156
- var pageSize = opts.num || MAX_NUM;
8157
- var firstStart = opts.start || 1;
8158
- // If a limit is provided, we don't have to use the first request to get the
8159
- // total count before sending things off to batch(). So instead we fake the first
8160
- // response just to set things up.
8161
- var promise = limit === -1
8162
- ? searchFunc(__assign(__assign({}, opts), { num: pageSize, start: firstStart }))
8163
- : Promise.resolve({
8164
- nextStart: firstStart,
8165
- total: limit,
8166
- results: [],
8167
- num: pageSize
8168
- });
8169
- return promise
8170
- .then(function (firstResponse) {
8171
- // no more requests needed, return the first response
8172
- if (firstResponse.nextStart === -1)
8173
- return [firstResponse];
8174
- // generate batch requests for the remaining pages to fetch
8175
- var starts = [];
8176
- for (var i = firstResponse.nextStart; i <= firstResponse.total; i += pageSize) {
8177
- starts.push(i);
9653
+ throw new RemoteServerError(resp.statusText, url, resp.status);
8178
9654
  }
8179
- var batchSearchFunc = function (start) {
8180
- return searchFunc(__assign(__assign({}, opts), { start: start, num: pageSize }));
8181
- };
8182
- return batch(starts, batchSearchFunc, batchSize).then(function (responses) { return __spreadArrays([
8183
- firstResponse
8184
- ], responses); });
8185
- })
8186
- .then(function (responses) {
8187
- // merge all the search results into a single array
8188
- var results = responses.reduce(function (acc, response) { return __spreadArrays(acc, response.results); }, []);
8189
- // discard results beyond the limit if applicable
8190
- var clipLimit = limit === -1 ? results.length : limit;
8191
- return results.slice(0, clipLimit);
8192
9655
  });
8193
9656
  }
8194
9657
 
@@ -10416,226 +11879,54 @@
10416
11879
  var v3Value = indexValueToV3Value[indexValue];
10417
11880
  migratedConfigString = migratedConfigString.split(indexValue).join(v3Value);
10418
11881
  });
10419
- return JSON.parse(migratedConfigString);
10420
- }
10421
-
10422
- /**
10423
- * Upgrades the schema upgrades
10424
- * @param model IModel
10425
- */
10426
- function upgradeSiteSchema(model) {
10427
- if (getProp(model, "item.properties.schemaVersion") === SITE_SCHEMA_VERSION) {
10428
- return model;
10429
- }
10430
- else {
10431
- // apply upgrade functions in order...
10432
- model = _applySiteSchema(model);
10433
- model = _enforceLowercaseDomains(model);
10434
- model = _ensureCatalog(model);
10435
- model = _purgeNonGuidsFromCatalog(model);
10436
- model = _ensureTelemetry(model);
10437
- model = _migrateFeedConfig(model);
10438
- // WARNING - If you are writing a site schema migration,
10439
- // you probably need to apply it to site drafts as well!
10440
- // See https://github.com/Esri/hub.js/issues/498 for more details.
10441
- return model;
10442
- }
10443
- }
10444
-
10445
- /**
10446
- * Returns site model given various kinds of identifier
10447
- *
10448
- * @param identifier - a site item ID, site hostname, enterprise site slug, or full site URL
10449
- * @param hubRequestOptions
10450
- */
10451
- function fetchSite(identifier, hubRequestOptions) {
10452
- var prms;
10453
- if (isGuid(identifier)) {
10454
- prms = getSiteById(identifier, hubRequestOptions);
10455
- }
10456
- else {
10457
- var hostnameOrSlug = identifier;
10458
- // get down the the hostname
10459
- hostnameOrSlug = stripProtocol(hostnameOrSlug);
10460
- hostnameOrSlug = hostnameOrSlug.split("/")[0];
10461
- prms = lookupDomain(hostnameOrSlug, hubRequestOptions).then(function (_a) {
10462
- var siteId = _a.siteId;
10463
- return getSiteById(siteId, hubRequestOptions);
10464
- });
10465
- }
10466
- return prms;
10467
- }
10468
-
10469
- /**
10470
- * Locales supported by the hub
10471
- */
10472
- var HUB_LOCALES = [
10473
- "ar",
10474
- "bs",
10475
- "ca",
10476
- "cs",
10477
- "da",
10478
- "de",
10479
- "en",
10480
- "es",
10481
- "et",
10482
- "el",
10483
- "fi",
10484
- "fr",
10485
- "hr",
10486
- "he",
10487
- "hu",
10488
- "it",
10489
- "id",
10490
- "ja",
10491
- "ko",
10492
- "lt",
10493
- "lv",
10494
- "nb",
10495
- "nl",
10496
- "pl",
10497
- "pt",
10498
- "pt-br",
10499
- "pt-pt",
10500
- "ro",
10501
- "ru",
10502
- "sl",
10503
- "sr",
10504
- "sv",
10505
- "th",
10506
- "tr",
10507
- "uk",
10508
- "vi",
10509
- "zh",
10510
- "zh-cn",
10511
- "zh-tw",
10512
- "zh-hk"
10513
- ];
11882
+ return JSON.parse(migratedConfigString);
11883
+ }
10514
11884
 
10515
11885
  /**
10516
- * Convert a requested locale into a locale we support.
10517
- * i.e. en-ca => en
10518
- * If the requested locale is not available, en will be returned
10519
- * @param {string} requestedLocale Locale we want
11886
+ * Upgrades the schema upgrades
11887
+ * @param model IModel
10520
11888
  */
10521
- function convertToWellKnownLocale(requestedLocale) {
10522
- if (requestedLocale === void 0) { requestedLocale = "en"; }
10523
- var wellKnownKey = "en";
10524
- // ensure downcase
10525
- requestedLocale = requestedLocale.toLowerCase();
10526
- // see if it's in the hub translations as-is
10527
- if (HUB_LOCALES.indexOf(requestedLocale) > -1) {
10528
- wellKnownKey = requestedLocale;
11889
+ function upgradeSiteSchema(model) {
11890
+ if (getProp(model, "item.properties.schemaVersion") === SITE_SCHEMA_VERSION) {
11891
+ return model;
10529
11892
  }
10530
11893
  else {
10531
- // if we split the requested locale, see if we have the root in the list
10532
- var parts = requestedLocale.split("-");
10533
- if (parts.length > 1 && HUB_LOCALES.indexOf(parts[0]) > -1) {
10534
- wellKnownKey = parts[0];
10535
- }
11894
+ // apply upgrade functions in order...
11895
+ model = _applySiteSchema(model);
11896
+ model = _enforceLowercaseDomains(model);
11897
+ model = _ensureCatalog(model);
11898
+ model = _purgeNonGuidsFromCatalog(model);
11899
+ model = _ensureTelemetry(model);
11900
+ model = _migrateFeedConfig(model);
11901
+ // WARNING - If you are writing a site schema migration,
11902
+ // you probably need to apply it to site drafts as well!
11903
+ // See https://github.com/Esri/hub.js/issues/498 for more details.
11904
+ return model;
10536
11905
  }
10537
- return wellKnownKey;
10538
- }
10539
-
10540
- /**
10541
- * Fetch the Hub translation file for a given locale
10542
- * These are all public urls and should never require auth/tokens etc
10543
- * @param {String} locale Locale code - i.e. `es`
10544
- * @param {Object} portal Portal Self
10545
- */
10546
- function fetchHubTranslation(locale, portal, mode) {
10547
- if (mode === void 0) { mode = "cors"; }
10548
- var assetBase = getHubLocaleAssetUrl(portal);
10549
- var url = (assetBase + "/locales/" + locale + ".json").toLocaleLowerCase();
10550
- // to support web-tier auth, we must always send same-origin credentials
10551
- var options = {
10552
- method: "GET",
10553
- credentials: "same-origin",
10554
- mode: mode
10555
- };
10556
- return fetch(url, options)
10557
- .then(function (response) { return response.json(); })
10558
- .catch(function (err) {
10559
- throw Error("Attempt to fetch locale " + locale + " from " + url + " failed: " + JSON.stringify(err));
10560
- });
10561
- }
10562
-
10563
- /**
10564
- * Return the culture from the Hub Request Options
10565
- * In priority order: user.culture, portal.culture, en-us
10566
- * @param {IHubRequestOptions} hubRequestOptions
10567
- */
10568
- function getCulture(hubRequestOptions) {
10569
- return (getProp(hubRequestOptions, "portalSelf.user.culture") ||
10570
- getProp(hubRequestOptions, "portalSelf.culture") ||
10571
- "en-us");
10572
11906
  }
10573
11907
 
10574
11908
  /**
10575
- * remote server error
10576
- */
10577
- var RemoteServerError = /** @class */ (function (_super) {
10578
- __extends(RemoteServerError, _super);
10579
- function RemoteServerError(message, url, status) {
10580
- var _this = _super.call(this, message) || this;
10581
- _this.status = status;
10582
- _this.url = url;
10583
- return _this;
10584
- }
10585
- return RemoteServerError;
10586
- }(Error));
10587
- /**
10588
- * ```js
10589
- * import { hubApiRequest } from "@esri/hub-common";
10590
- * //
10591
- * hubApiRequest(
10592
- * "/datasets",
10593
- * requestOptions
10594
- * })
10595
- * .then(response);
10596
- * ```
10597
- * make a request to the Hub API
10598
- * @param route API route
10599
- * @param requestOptions request options
11909
+ * Returns site model given various kinds of identifier
11910
+ *
11911
+ * @param identifier - a site item ID, site hostname, enterprise site slug, or full site URL
11912
+ * @param hubRequestOptions
10600
11913
  */
10601
- function hubApiRequest(route, requestOptions) {
10602
- // merge in default request options
10603
- var options = __assign({
10604
- // why do we default to GET w/ our API?
10605
- httpMethod: "GET" }, requestOptions);
10606
- // use fetch override if any
10607
- var _fetch = options.fetch || fetch;
10608
- // merge in default headers
10609
- var headers = __assign({ "Content-Type": "application/json" }, options.headers);
10610
- // build query params/body based on requestOptions.params
10611
- var query;
10612
- var body;
10613
- if (options.httpMethod === "GET") {
10614
- // pass params in query string
10615
- query = options.params;
11914
+ function fetchSite(identifier, hubRequestOptions) {
11915
+ var prms;
11916
+ if (isGuid(identifier)) {
11917
+ prms = getSiteById(identifier, hubRequestOptions);
10616
11918
  }
10617
11919
  else {
10618
- // pass params in request body
10619
- body = JSON.stringify(options.params);
11920
+ var hostnameOrSlug = identifier;
11921
+ // get down the the hostname
11922
+ hostnameOrSlug = stripProtocol(hostnameOrSlug);
11923
+ hostnameOrSlug = hostnameOrSlug.split("/")[0];
11924
+ prms = lookupDomain(hostnameOrSlug, hubRequestOptions).then(function (_a) {
11925
+ var siteId = _a.siteId;
11926
+ return getSiteById(siteId, hubRequestOptions);
11927
+ });
10620
11928
  }
10621
- // build Hub API URL
10622
- var url = buildUrl({
10623
- host: getHubApiUrl(options),
10624
- path: ("/api/v3/" + route).replace(/\/\//g, "/"),
10625
- query: query,
10626
- });
10627
- return _fetch(url, {
10628
- method: options.httpMethod,
10629
- headers: headers,
10630
- body: body,
10631
- }).then(function (resp) {
10632
- if (resp.ok) {
10633
- return resp.json();
10634
- }
10635
- else {
10636
- throw new RemoteServerError(resp.statusText, url, resp.status);
10637
- }
10638
- });
11929
+ return prms;
10639
11930
  }
10640
11931
 
10641
11932
  /* Copyright (c) 2020 Environmental Systems Research Institute, Inc.
@@ -10672,587 +11963,190 @@
10672
11963
  return getRelatedItems(__assign({ id: fieldworkerId, relationshipType: "Service2Data", direction: "forward" }, requestOptions)).then(function (_a) {
10673
11964
  var featureService = _a.relatedItems[0];
10674
11965
  var model;
10675
- if (featureService) {
10676
- model = { item: featureService };
10677
- }
10678
- return model;
10679
- });
10680
- };
10681
-
10682
- /* Copyright (c) 2020 Environmental Systems Research Institute, Inc.
10683
- * Apache-2.0 */
10684
- /**
10685
- * Fetches a Survey's Stakeholder View for a given
10686
- * Form ID
10687
- * @param {string} formId A Form ID
10688
- * @param {IRequestOptions} requestOptions The request options
10689
- * @returns {Promise<IModel>}
10690
- */
10691
- var getStakeholderModel = function (formId, requestOptions) {
10692
- return getRelatedItems(__assign({ id: formId, relationshipType: "Survey2Data", direction: "forward" }, requestOptions)).then(function (_a) {
10693
- var stakeholderView = _a.relatedItems[0];
10694
- var model;
10695
- if (stakeholderView) {
10696
- model = { item: stakeholderView };
10697
- }
10698
- return model;
10699
- });
10700
- };
10701
-
10702
- /**
10703
- * Determines if the provided Feature Service item is a
10704
- * Fieldworker View
10705
- * @param {IItem} featureServiceItem
10706
- * @returns {boolean}
10707
- */
10708
- function isFieldworkerView(featureServiceItem) {
10709
- var hasTypekeyword = function (typeKeyword) {
10710
- return featureServiceItem.typeKeywords.indexOf(typeKeyword) > -1;
10711
- };
10712
- // Survey123 only recently added the "FieldworkerView" typekeyword
10713
- var isFieldworker = hasTypekeyword("FieldworkerView");
10714
- // we should support previously created fieldworkers too
10715
- if (!isFieldworker) {
10716
- var hasExpectedTypeKeywords = [
10717
- "Survey123",
10718
- "Feature Service",
10719
- "View Service",
10720
- ].every(hasTypekeyword);
10721
- isFieldworker =
10722
- hasExpectedTypeKeywords && !hasTypekeyword("StakeholderView");
10723
- }
10724
- return isFieldworker;
10725
- }
10726
-
10727
- /* Copyright (c) 2020 Environmental Systems Research Institute, Inc.
10728
- * Apache-2.0 */
10729
- /**
10730
- * Builds a dictionary of Survey items for the given Form model
10731
- * @param {string} formId The Form ID of the survey
10732
- * @param {IRequestOptions} requestOptions The request options
10733
- * @returns {Promise<IGetSurveyModelsResponse>}
10734
- */
10735
- var getSurveyModels = function (formItemOrId, requestOptions) {
10736
- var fieldworker;
10737
- var stakeholder;
10738
- var getForm = function () {
10739
- return typeof formItemOrId === "string"
10740
- ? getItem(formItemOrId, requestOptions)
10741
- : Promise.resolve(formItemOrId);
10742
- };
10743
- return getForm().then(function (form) {
10744
- var promises = [
10745
- // the primary input will be the fieldworker (if it exists), otherwise
10746
- // the source feature service.
10747
- getInputFeatureServiceModel(form.id, requestOptions),
10748
- getStakeholderModel(form.id, requestOptions),
10749
- ];
10750
- return Promise.all(promises)
10751
- .then(function (_a) {
10752
- var featureServiceOrFieldworkerModelResult = _a[0], stakeholderResult = _a[1];
10753
- stakeholder = stakeholderResult;
10754
- if (featureServiceOrFieldworkerModelResult &&
10755
- isFieldworkerView(featureServiceOrFieldworkerModelResult.item)) {
10756
- fieldworker = featureServiceOrFieldworkerModelResult;
10757
- // if the primary input is the fieldworker, fetch
10758
- // the source feature service
10759
- return getSourceFeatureServiceModelFromFieldworker(fieldworker.item.id, requestOptions);
10760
- }
10761
- else {
10762
- return featureServiceOrFieldworkerModelResult;
10763
- }
10764
- })
10765
- .then(function (featureService) {
10766
- return {
10767
- form: { item: form },
10768
- featureService: featureService,
10769
- fieldworker: fieldworker,
10770
- stakeholder: stakeholder,
10771
- };
10772
- });
10773
- });
10774
- };
10775
-
10776
- /**
10777
- * Hash of Hub API end points so updates
10778
- * are centralized
10779
- */
10780
- var hubApiEndpoints = {
10781
- domains: "/api/v3/domains",
10782
- search: "/api/v3/datasets",
10783
- discussions: "/api/discussions/v1",
11966
+ if (featureService) {
11967
+ model = { item: featureService };
11968
+ }
11969
+ return model;
11970
+ });
10784
11971
  };
11972
+
11973
+ /* Copyright (c) 2020 Environmental Systems Research Institute, Inc.
11974
+ * Apache-2.0 */
10785
11975
  /**
10786
- * ArcGISContext
10787
- *
10788
- * Abstraction that holds a UserSession, along with
10789
- * getters to streamline access to various platform
10790
- * urls, and common constructs like IRequestOptions
10791
- *
10792
- * Thin class just used to enable getters
10793
- *
10794
- * This class should not be used by anything other than
10795
- * the ArcGISContextManager class
11976
+ * Fetches a Survey's Stakeholder View for a given
11977
+ * Form ID
11978
+ * @param {string} formId A Form ID
11979
+ * @param {IRequestOptions} requestOptions The request options
11980
+ * @returns {Promise<IModel>}
10796
11981
  */
10797
- var ArcGISContext = /** @class */ (function () {
10798
- function ArcGISContext(opts) {
10799
- this._portalUrl = "https://www.arcgis.com";
10800
- this.id = opts.id;
10801
- this._portalUrl = opts.portalUrl;
10802
- this._hubUrl = opts.hubUrl;
10803
- if (opts.authentication) {
10804
- this._authentication = opts.authentication;
10805
- }
10806
- if (opts.portalSelf) {
10807
- this._portalSelf = opts.portalSelf;
10808
- }
10809
- if (opts.currentUser) {
10810
- this._currentUser = opts.currentUser;
11982
+ var getStakeholderModel = function (formId, requestOptions) {
11983
+ return getRelatedItems(__assign({ id: formId, relationshipType: "Survey2Data", direction: "forward" }, requestOptions)).then(function (_a) {
11984
+ var stakeholderView = _a.relatedItems[0];
11985
+ var model;
11986
+ if (stakeholderView) {
11987
+ model = { item: stakeholderView };
10811
11988
  }
10812
- }
10813
- Object.defineProperty(ArcGISContext.prototype, "session", {
10814
- /**
10815
- * Return the UserSession if authenticated
10816
- */
10817
- get: function () {
10818
- return this._authentication;
10819
- },
10820
- enumerable: false,
10821
- configurable: true
10822
- });
10823
- Object.defineProperty(ArcGISContext.prototype, "isAuthenticated", {
10824
- /**
10825
- * Return boolean indicating if authenticatio is present
10826
- */
10827
- get: function () {
10828
- return !!this._authentication;
10829
- },
10830
- enumerable: false,
10831
- configurable: true
10832
- });
10833
- Object.defineProperty(ArcGISContext.prototype, "userRequestOptions", {
10834
- /**
10835
- * Return `IUserRequestOptions`, which is used for REST-JS
10836
- * functions which require authentication information.
10837
- *
10838
- * If context is not authenticated, this function will throw
10839
- */
10840
- get: function () {
10841
- if (this.isAuthenticated) {
10842
- return {
10843
- authentication: this._authentication,
10844
- portal: this.sharingApiUrl,
10845
- };
10846
- }
10847
- },
10848
- enumerable: false,
10849
- configurable: true
10850
- });
10851
- Object.defineProperty(ArcGISContext.prototype, "requestOptions", {
10852
- /**
10853
- * Return `IRequestOptions`, which is used by REST-JS functions
10854
- * which *may* use authentication information if provided.
10855
- *
10856
- * If context is not authenticated, this function just returns
10857
- * the `portal` property, which informs REST-JS what Sharing API
10858
- * instance to use (i.e. AGO, Enterprise etc)
10859
- */
10860
- get: function () {
10861
- var ro = {
10862
- portal: this.sharingApiUrl,
10863
- };
10864
- if (this.isAuthenticated) {
10865
- ro = {
10866
- authentication: this._authentication,
10867
- portal: this.sharingApiUrl,
10868
- };
10869
- }
10870
- return ro;
10871
- },
10872
- enumerable: false,
10873
- configurable: true
10874
- });
10875
- Object.defineProperty(ArcGISContext.prototype, "hubRequestOptions", {
10876
- /**
10877
- * Return a `IHubRequestOptions` object
10878
- */
10879
- get: function () {
10880
- // We may add more logic around what is returned in some corner cases
10881
- return {
10882
- authentication: this.session,
10883
- isPortal: this.isPortal,
10884
- portalSelf: this.portal,
10885
- hubApiUrl: this.hubUrl,
10886
- };
10887
- },
10888
- enumerable: false,
10889
- configurable: true
10890
- });
10891
- Object.defineProperty(ArcGISContext.prototype, "portalUrl", {
10892
- /**
10893
- * Return the portal url.
10894
- *
10895
- * If authenticated @ ArcGIS Online, it will return
10896
- * the https://org.env.arcgis.com
10897
- *
10898
- * If authenticated @ ArcGIS Enterprise, it will return
10899
- * https://portalHostname, which includes the web adaptor
10900
- */
10901
- get: function () {
10902
- if (this.isAuthenticated) {
10903
- if (this.isPortal) {
10904
- return "https://" + this._portalSelf.portalHostname;
10905
- }
10906
- else {
10907
- return "https://" + this._portalSelf.urlKey + "." + this._portalSelf.customBaseUrl;
10908
- }
10909
- }
10910
- else {
10911
- return this._portalUrl;
10912
- }
10913
- },
10914
- enumerable: false,
10915
- configurable: true
10916
- });
10917
- Object.defineProperty(ArcGISContext.prototype, "sharingApiUrl", {
10918
- /**
10919
- * Returns the url to the sharing api
10920
- * i.e. https://myorg.maps.arcgis.com/sharing/rest
10921
- */
10922
- get: function () {
10923
- return this.portalUrl + "/sharing/rest";
10924
- },
10925
- enumerable: false,
10926
- configurable: true
10927
- });
10928
- Object.defineProperty(ArcGISContext.prototype, "hubUrl", {
10929
- get: function () {
10930
- return this._hubUrl;
10931
- },
10932
- enumerable: false,
10933
- configurable: true
10934
- });
10935
- Object.defineProperty(ArcGISContext.prototype, "isPortal", {
10936
- /**
10937
- * Returns boolean indicating if the backing system
10938
- * is ArcGIS Enterprise (formerly ArcGIS Portal) or not
10939
- */
10940
- get: function () {
10941
- return this._portalSelf
10942
- ? this._portalSelf.isPortal
10943
- : this._portalUrl.indexOf("arcgis.com") === -1;
10944
- },
10945
- enumerable: false,
10946
- configurable: true
10947
- });
10948
- Object.defineProperty(ArcGISContext.prototype, "discussionsServiceUrl", {
10949
- // Hub APIs
10950
- // ----------
10951
- // Discussions
10952
- get: function () {
10953
- if (this._hubUrl) {
10954
- return "" + this._hubUrl + hubApiEndpoints.discussions;
10955
- }
10956
- },
10957
- enumerable: false,
10958
- configurable: true
10959
- });
10960
- Object.defineProperty(ArcGISContext.prototype, "hubSearchServiceUrl", {
10961
- // Hub Search
10962
- get: function () {
10963
- if (this._hubUrl) {
10964
- return "" + this._hubUrl + hubApiEndpoints.search;
10965
- }
10966
- },
10967
- enumerable: false,
10968
- configurable: true
10969
- });
10970
- Object.defineProperty(ArcGISContext.prototype, "domainServiceUrl", {
10971
- // Domain
10972
- get: function () {
10973
- if (this._hubUrl) {
10974
- return "" + this._hubUrl + hubApiEndpoints.domains;
10975
- }
10976
- },
10977
- enumerable: false,
10978
- configurable: true
10979
- });
10980
- Object.defineProperty(ArcGISContext.prototype, "eventsConfig", {
10981
- // Events
10982
- // returns `{serviceId: '3ef..', publicViewId: 'bc3...'}
10983
- get: function () {
10984
- if (this._portalSelf) {
10985
- return getProp(this._portalSelf, "portalProperties.hub.settings.events");
10986
- }
10987
- },
10988
- enumerable: false,
10989
- configurable: true
10990
- });
10991
- Object.defineProperty(ArcGISContext.prototype, "hubEnabled", {
10992
- /**
10993
- * Returns boolean indicating if the current user
10994
- * belongs to an organization that has licensed
10995
- * ArcGIS Hub
10996
- */
10997
- get: function () {
10998
- return getWithDefault$1(this._portalSelf, "portalProperties.hub.enabled", false);
10999
- },
11000
- enumerable: false,
11001
- configurable: true
11002
- });
11003
- Object.defineProperty(ArcGISContext.prototype, "communityOrgId", {
11004
- /**
11005
- * Return Hub Community Org Id, if defined
11006
- */
11007
- get: function () {
11008
- if (this._portalSelf) {
11009
- return getProp(this._portalSelf, "portalProperties.hub.settings.communityOrg.orgId");
11010
- }
11011
- },
11012
- enumerable: false,
11013
- configurable: true
11014
- });
11015
- Object.defineProperty(ArcGISContext.prototype, "communityOrgHostname", {
11016
- get: function () {
11017
- if (this._portalSelf) {
11018
- return getProp(this._portalSelf, "portalProperties.hub.settings.communityOrg.portalHostname");
11019
- }
11020
- },
11021
- enumerable: false,
11022
- configurable: true
11989
+ return model;
11023
11990
  });
11024
- Object.defineProperty(ArcGISContext.prototype, "communityOrgUrl", {
11025
- get: function () {
11026
- if (this.communityOrgHostname) {
11027
- return "https://" + this.communityOrgHostname;
11991
+ };
11992
+
11993
+ /**
11994
+ * Determines if the provided Feature Service item is a
11995
+ * Fieldworker View
11996
+ * @param {IItem} featureServiceItem
11997
+ * @returns {boolean}
11998
+ */
11999
+ function isFieldworkerView(featureServiceItem) {
12000
+ var hasTypekeyword = function (typeKeyword) {
12001
+ return featureServiceItem.typeKeywords.indexOf(typeKeyword) > -1;
12002
+ };
12003
+ // Survey123 only recently added the "FieldworkerView" typekeyword
12004
+ var isFieldworker = hasTypekeyword("FieldworkerView");
12005
+ // we should support previously created fieldworkers too
12006
+ if (!isFieldworker) {
12007
+ var hasExpectedTypeKeywords = [
12008
+ "Survey123",
12009
+ "Feature Service",
12010
+ "View Service",
12011
+ ].every(hasTypekeyword);
12012
+ isFieldworker =
12013
+ hasExpectedTypeKeywords && !hasTypekeyword("StakeholderView");
12014
+ }
12015
+ return isFieldworker;
12016
+ }
12017
+
12018
+ /* Copyright (c) 2020 Environmental Systems Research Institute, Inc.
12019
+ * Apache-2.0 */
12020
+ /**
12021
+ * Builds a dictionary of Survey items for the given Form model
12022
+ * @param {string} formId The Form ID of the survey
12023
+ * @param {IRequestOptions} requestOptions The request options
12024
+ * @returns {Promise<IGetSurveyModelsResponse>}
12025
+ */
12026
+ var getSurveyModels = function (formItemOrId, requestOptions) {
12027
+ var fieldworker;
12028
+ var stakeholder;
12029
+ var getForm = function () {
12030
+ return typeof formItemOrId === "string"
12031
+ ? getItem(formItemOrId, requestOptions)
12032
+ : Promise.resolve(formItemOrId);
12033
+ };
12034
+ return getForm().then(function (form) {
12035
+ var promises = [
12036
+ // the primary input will be the fieldworker (if it exists), otherwise
12037
+ // the source feature service.
12038
+ getInputFeatureServiceModel(form.id, requestOptions),
12039
+ getStakeholderModel(form.id, requestOptions),
12040
+ ];
12041
+ return Promise.all(promises)
12042
+ .then(function (_a) {
12043
+ var featureServiceOrFieldworkerModelResult = _a[0], stakeholderResult = _a[1];
12044
+ stakeholder = stakeholderResult;
12045
+ if (featureServiceOrFieldworkerModelResult &&
12046
+ isFieldworkerView(featureServiceOrFieldworkerModelResult.item)) {
12047
+ fieldworker = featureServiceOrFieldworkerModelResult;
12048
+ // if the primary input is the fieldworker, fetch
12049
+ // the source feature service
12050
+ return getSourceFeatureServiceModelFromFieldworker(fieldworker.item.id, requestOptions);
11028
12051
  }
11029
- },
11030
- enumerable: false,
11031
- configurable: true
11032
- });
11033
- Object.defineProperty(ArcGISContext.prototype, "helperServices", {
11034
- // Platform API service urls are all in helperServices
11035
- // and not consistent to expose as urls
11036
- get: function () {
11037
- if (this._portalSelf) {
11038
- return this._portalSelf.helperServices;
12052
+ else {
12053
+ return featureServiceOrFieldworkerModelResult;
11039
12054
  }
11040
- },
11041
- enumerable: false,
11042
- configurable: true
11043
- });
11044
- Object.defineProperty(ArcGISContext.prototype, "currentUser", {
11045
- get: function () {
11046
- return this._currentUser;
11047
- },
11048
- enumerable: false,
11049
- configurable: true
11050
- });
11051
- Object.defineProperty(ArcGISContext.prototype, "portal", {
11052
- get: function () {
11053
- return this._portalSelf;
11054
- },
11055
- enumerable: false,
11056
- configurable: true
12055
+ })
12056
+ .then(function (featureService) {
12057
+ return {
12058
+ form: { item: form },
12059
+ featureService: featureService,
12060
+ fieldworker: fieldworker,
12061
+ stakeholder: stakeholder,
12062
+ };
12063
+ });
11057
12064
  });
11058
- return ArcGISContext;
11059
- }());
12065
+ };
11060
12066
 
11061
12067
  /**
11062
- * ArcGIS Context Manager
12068
+ * Hub class can be used as an entry point to managing
12069
+ * content, teams, sites, projects etc, in an organization's Hub.
11063
12070
  *
11064
- * The manager exposes context (`IArcGISContext`), which combines a `UserSession` with
11065
- * the `portal/self` and `user/self` responses to provide a central lookup for platform
11066
- * information, api urls, and other useful properties for developers such as IRequestOptions
11067
- * IUserRequestOptions, IHubRequestOptions etc.
12071
+ * ```js
12072
+ * import {Hub} from '@esri/hub-common';
12073
+ * // create a Hub instance, authenticating as a specific user
12074
+ * // working against arcgis online
12075
+ * const myHub = await Hub.create({authOptions: {username: "casey", password: "jones"}});
11068
12076
  *
11069
- * The context is exposed on gthe `.context` property, and as the authentication changes
11070
- * the `.context` is re-created. This is done to allow web frameworks to watch for
11071
- * changes on that single property, instead of having to leverage observers or events
11072
- * for change detection.
12077
+ * myHub.context.currentUser //=> {username: "casey", ...} as IUser
11073
12078
  *
11074
- * This is a work-in-progress, and will likely expand over time.
12079
+ * const projectStore = await myHub.getProjectStore();
12080
+ *
12081
+ * const pavingProject = await projectStore.create({name: "12th Street Paving"});
12082
+ * pavingProject.summary = "This is the 2024 planned paving of 12th Street, between 8th and 11th Ave";
12083
+ * await projectStore.update(pavingProject);
12084
+ * ```
11075
12085
  *
12086
+ * This is a convenience class. Hub Stores can be created
12087
+ * directly, or the underlying functions can be imported an used
12088
+ * as need for scenarios where these class structures introduce
12089
+ * unwanted complexity
11076
12090
  */
11077
- var ArcGISContextManager = /** @class */ (function () {
12091
+ var Hub = /** @class */ (function () {
11078
12092
  /**
11079
- * Private constructor. Use `ArcGISContextManager.create(...)` to
11080
- * instantiate an instance
11081
- * @param opts
12093
+ * Private so we can employ a factory function should we need
12094
+ * async work during creation
12095
+ * @param contextManager
11082
12096
  */
11083
- function ArcGISContextManager(opts) {
11084
- this._portalUrl = "https://www.arcgis.com";
11085
- this._logLevel = exports.Level.error;
11086
- // Having a unique id makes debugging easier
11087
- this.id = new Date().getTime();
11088
- if (opts.logLevel) {
11089
- this._logLevel = opts.logLevel;
11090
- }
11091
- Logger.setLogLevel(this._logLevel);
11092
- Logger.debug("ArcGISContextManager:ctor: Creating " + this.id);
11093
- if (opts.authentication) {
11094
- this._authentication = opts.authentication;
11095
- this._portalUrl = this._authentication.portal.replace("/sharing/rest", "");
11096
- this._hubUrl = getHubApiFromPortalUrl(this._portalUrl);
11097
- }
11098
- else if (opts.portalUrl) {
11099
- this._portalUrl = opts.portalUrl;
11100
- this._hubUrl = getHubApiFromPortalUrl(this._portalUrl);
11101
- }
11102
- else {
11103
- this._hubUrl = getHubApiFromPortalUrl(this._portalUrl);
11104
- }
11105
- if (opts.portal) {
11106
- this._portalSelf = cloneObject$1(opts.portal);
11107
- }
11108
- if (opts.currentUser) {
11109
- this._currentUser = cloneObject$1(opts.currentUser);
11110
- }
12097
+ function Hub(contextManager) {
12098
+ this._contextManager = contextManager;
11111
12099
  }
11112
12100
  /**
11113
- * Static async Factory
11114
- * @param opts
12101
+ * Factory function to construct a new HubProjectStore instance.
12102
+ *
12103
+ * Note: Used so that we could do async actions in the ctor.
12104
+ * @param contextManager
11115
12105
  * @returns
11116
12106
  */
11117
- ArcGISContextManager.create = function (opts) {
11118
- if (opts === void 0) { opts = {}; }
11119
- return __awaiter(this, void 0, void 0, function () {
11120
- var ctx;
11121
- return __generator(this, function (_a) {
11122
- switch (_a.label) {
11123
- case 0:
11124
- ctx = new ArcGISContextManager(opts);
11125
- return [4 /*yield*/, ctx.initialize()];
11126
- case 1:
11127
- _a.sent();
11128
- return [2 /*return*/, ctx];
11129
- }
11130
- });
11131
- });
11132
- };
11133
- /**
11134
- * Set the Authentication (UserSession) for the context.
11135
- * This should be called when a user signs into a running
11136
- * application.
11137
- * @param auth
11138
- */
11139
- ArcGISContextManager.prototype.setAuthentication = function (auth) {
12107
+ Hub.create = function (options) {
11140
12108
  return __awaiter(this, void 0, void 0, function () {
12109
+ var opts, mgr;
11141
12110
  return __generator(this, function (_a) {
11142
12111
  switch (_a.label) {
11143
12112
  case 0:
11144
- this._authentication = auth;
11145
- this._portalUrl = auth.portal.replace("/sharing/rest", "");
11146
- return [4 /*yield*/, this.initialize()];
12113
+ if (!options.contextManager) return [3 /*break*/, 1];
12114
+ return [2 /*return*/, new Hub(options.contextManager)];
11147
12115
  case 1:
11148
- _a.sent();
11149
- return [2 /*return*/];
12116
+ opts = options.managerOptions || {};
12117
+ return [4 /*yield*/, ArcGISContextManager.create(opts)];
12118
+ case 2:
12119
+ mgr = _a.sent();
12120
+ return [2 /*return*/, new Hub(mgr)];
11150
12121
  }
11151
12122
  });
11152
12123
  });
11153
12124
  };
11154
- /**
11155
- * Clear the Authentication (UserSession). This should be
11156
- * called when a user signs out of an application, but
11157
- * the application continues running
11158
- */
11159
- ArcGISContextManager.prototype.clearAuthentication = function () {
11160
- // Reset the portalUrl from the org url to the base url
11161
- // for ArcGIS Enterprise, we just leave the _portalUrl as-is
11162
- if (!this._context.isPortal) {
11163
- this._portalUrl = getPortalBaseFromOrgUrl(this._portalUrl);
11164
- }
11165
- // Clear the auth, portalSelf and currentUser props
11166
- this._authentication = null;
11167
- this._portalSelf = null;
11168
- this._currentUser = null;
11169
- this._context = new ArcGISContext({
11170
- id: this.id,
11171
- portalUrl: this._portalUrl,
11172
- hubUrl: this._hubUrl,
11173
- });
11174
- };
11175
- Object.defineProperty(ArcGISContextManager.prototype, "context", {
12125
+ Object.defineProperty(Hub.prototype, "context", {
11176
12126
  /**
11177
- * Return a reference to the current state.
11178
- * When `.setAuthentication()` or `.clearAuthenentication()` are
11179
- * called, the state will be re-created. This is done so frameworks
11180
- * like React or Ember can detect changes.
12127
+ * Getter to abstract the context manager
11181
12128
  */
11182
12129
  get: function () {
11183
- return this._context;
12130
+ return this._contextManager.context;
11184
12131
  },
11185
12132
  enumerable: false,
11186
12133
  configurable: true
11187
12134
  });
11188
- /**
11189
- * If we have a UserSession, fetch portal/self and
11190
- * store that along with current user
11191
- */
11192
- ArcGISContextManager.prototype.initialize = function () {
11193
- return __awaiter(this, void 0, void 0, function () {
11194
- var username, requests, _a, portal, user, ex_1, msg;
11195
- return __generator(this, function (_b) {
11196
- switch (_b.label) {
11197
- case 0:
11198
- if (!(this._authentication && (!this._portalSelf || !this._currentUser))) return [3 /*break*/, 4];
11199
- Logger.debug("ArcGISContextManager-" + this.id + ": Initializing");
11200
- username = this._authentication.username;
11201
- requests = [
11202
- getSelf({ authentication: this._authentication }),
11203
- getUser({ username: username, authentication: this._authentication }),
11204
- ];
11205
- _b.label = 1;
11206
- case 1:
11207
- _b.trys.push([1, 3, , 4]);
11208
- return [4 /*yield*/, Promise.all(requests)];
11209
- case 2:
11210
- _a = _b.sent(), portal = _a[0], user = _a[1];
11211
- this._portalSelf = portal;
11212
- this._currentUser = user;
11213
- Logger.debug("ArcGISContextManager-" + this.id + ": received portalSelf and currentUser");
11214
- return [3 /*break*/, 4];
11215
- case 3:
11216
- ex_1 = _b.sent();
11217
- msg = "ArcGISContextManager could not fetch portal & user for \"" + this._authentication.username + "\" using " + this._authentication.portal + ".";
11218
- Logger.error(msg);
11219
- // tslint:disable-next-line:no-console
11220
- console.error(msg);
11221
- throw ex_1;
11222
- case 4:
11223
- Logger.debug("ArcGISContextManager-" + this.id + ": updating context");
11224
- // update the context
11225
- this._context = new ArcGISContext(this.contextOpts);
11226
- return [2 /*return*/];
11227
- }
11228
- });
11229
- });
11230
- };
11231
- Object.defineProperty(ArcGISContextManager.prototype, "contextOpts", {
12135
+ Object.defineProperty(Hub.prototype, "projects", {
11232
12136
  /**
11233
- * Getter to streamline the creation of updated Context instances
12137
+ * Create a Project Store connected to the current Hub
12138
+ * @returns
11234
12139
  */
11235
12140
  get: function () {
11236
- var contextOpts = {
11237
- id: this.id,
11238
- portalUrl: this._portalUrl,
11239
- hubUrl: this._hubUrl,
11240
- };
11241
- if (this._authentication) {
11242
- contextOpts.authentication = this._authentication;
11243
- }
11244
- if (this._portalSelf) {
11245
- contextOpts.portalSelf = this._portalSelf;
11246
- }
11247
- if (this._currentUser) {
11248
- contextOpts.currentUser = this._currentUser;
12141
+ if (!this._projectManager) {
12142
+ this._projectManager = HubProjectManager.init(this._contextManager);
11249
12143
  }
11250
- return contextOpts;
12144
+ return this._projectManager;
11251
12145
  },
11252
12146
  enumerable: false,
11253
12147
  configurable: true
11254
12148
  });
11255
- return ArcGISContextManager;
12149
+ return Hub;
11256
12150
  }());
11257
12151
 
11258
12152
  /* Copyright (c) 2018-2020 Environmental Systems Research Institute, Inc.
@@ -11514,11 +12408,52 @@
11514
12408
  return msg;
11515
12409
  }
11516
12410
 
12411
+ /**
12412
+ * Generic Hub Error with an Error stack as well
12413
+ * as an optional serialized OperationStack.
12414
+ *
12415
+ * Also accepts a `rootCause` Error object
12416
+ */
12417
+ var HubError = /** @class */ (function (_super) {
12418
+ __extends(HubError, _super);
12419
+ /**
12420
+ * Creates an instance of HubError.
12421
+ * @param {string} operation
12422
+ * @param {string} [message]
12423
+ * @param {Error} [rootCause]
12424
+ * @memberof HubError
12425
+ */
12426
+ function HubError(operation, message, rootCause) {
12427
+ var _this = this;
12428
+ message = message || "UNKNOWN_ERROR";
12429
+ // if the rootCause has a .rootCause, use that so we don't deeply nest
12430
+ rootCause = getWithDefault$1(rootCause, "rootCause", rootCause);
12431
+ /* Skip coverage on super(...) as per:
12432
+ https://github.com/Microsoft/TypeScript/issues/13029
12433
+ https://github.com/SitePen/remap-istanbul/issues/106
12434
+ */
12435
+ /* istanbul ignore next */
12436
+ _this = _super.call(this, operation, message, rootCause) || this;
12437
+ _this.name = "HubError";
12438
+ // if the original error has a stack use it, otherwise create a new
12439
+ // stack. Note: a new Stack will make it look like the error origninated
12440
+ // in the HubError constructor. This is only an issue in tests but
12441
+ // it can be confusing to debug
12442
+ _this.stack = getWithDefault$1(rootCause, "stack", new Error().stack);
12443
+ return _this;
12444
+ }
12445
+ return HubError;
12446
+ }(OperationError));
12447
+
11517
12448
  exports.ArcGISContext = ArcGISContext;
11518
12449
  exports.ArcGISContextManager = ArcGISContextManager;
11519
12450
  exports.GLOBAL_EXTENT = GLOBAL_EXTENT;
11520
12451
  exports.HUB_CDN_URLMAP = HUB_CDN_URLMAP;
11521
12452
  exports.HUB_LOCALES = HUB_LOCALES;
12453
+ exports.HUB_PROJECT_ITEM_TYPE = HUB_PROJECT_ITEM_TYPE;
12454
+ exports.Hub = Hub;
12455
+ exports.HubError = HubError;
12456
+ exports.HubProjectManager = HubProjectManager;
11522
12457
  exports.Logger = Logger;
11523
12458
  exports.OperationError = OperationError;
11524
12459
  exports.OperationStack = OperationStack;
@@ -11588,6 +12523,7 @@
11588
12523
  exports.cloneObject = cloneObject$1;
11589
12524
  exports.completeOAuth2 = completeOAuth2;
11590
12525
  exports.compose = compose;
12526
+ exports.constructSlug = constructSlug;
11591
12527
  exports.convertContentDefinitionToFilter = convertContentDefinitionToFilter;
11592
12528
  exports.convertContentFilterToSearchOptions = convertContentFilterToSearchOptions;
11593
12529
  exports.convertPortalResponseToFacets = convertPortalResponseToFacets;
@@ -11596,7 +12532,10 @@
11596
12532
  exports.convertUrlsToAnchorTags = convertUrlsToAnchorTags;
11597
12533
  exports.createExtent = createExtent;
11598
12534
  exports.createId = createId;
12535
+ exports.createModel = createModel;
11599
12536
  exports.createOperationPipeline = createOperationPipeline;
12537
+ exports.createProject = createProject;
12538
+ exports.dasherize = dasherize;
11600
12539
  exports.datasetToContent = datasetToContent;
11601
12540
  exports.datasetToItem = datasetToItem;
11602
12541
  exports.deepFind = deepFind;
@@ -11604,6 +12543,7 @@
11604
12543
  exports.deepSet = deepSet;
11605
12544
  exports.deepStringReplace = deepStringReplace;
11606
12545
  exports.deleteProp = deleteProp;
12546
+ exports.destroyProject = destroyProject;
11607
12547
  exports.doesItemExistWithTitle = doesItemExistWithTitle;
11608
12548
  exports.domainExists = domainExists;
11609
12549
  exports.domainExistsPortal = domainExistsPortal;
@@ -11653,6 +12593,7 @@
11653
12593
  exports.getInputFeatureServiceModel = getInputFeatureServiceModel;
11654
12594
  exports.getItemApiUrl = getItemApiUrl;
11655
12595
  exports.getItemAssets = getItemAssets;
12596
+ exports.getItemBySlug = getItemBySlug;
11656
12597
  exports.getItemDataUrl = getItemDataUrl;
11657
12598
  exports.getItemHomeUrl = getItemHomeUrl;
11658
12599
  exports.getItemHubId = getItemHubId;
@@ -11661,14 +12602,17 @@
11661
12602
  exports.getItemThumbnailUrl = getItemThumbnailUrl;
11662
12603
  exports.getLayerIdFromUrl = getLayerIdFromUrl;
11663
12604
  exports.getModel = getModel;
12605
+ exports.getModelBySlug = getModelBySlug;
11664
12606
  exports.getModelFromOptions = getModelFromOptions;
11665
12607
  exports.getNextFunction = getNextFunction;
11666
12608
  exports.getOrgExtentAsBBox = getOrgExtentAsBBox;
11667
12609
  exports.getPortalApiUrl = getPortalApiUrl;
11668
12610
  exports.getPortalBaseFromOrgUrl = getPortalBaseFromOrgUrl;
11669
12611
  exports.getPortalUrl = getPortalUrl;
12612
+ exports.getProject = getProject;
11670
12613
  exports.getProp = getProp;
11671
12614
  exports.getProps = getProps;
12615
+ exports.getProxyUrl = getProxyUrl;
11672
12616
  exports.getServiceTypeFromUrl = getServiceTypeFromUrl;
11673
12617
  exports.getSession = getSession;
11674
12618
  exports.getSiteById = getSiteById;
@@ -11683,6 +12627,7 @@
11683
12627
  exports.getUniqueDomainName = getUniqueDomainName;
11684
12628
  exports.getUniqueDomainNamePortal = getUniqueDomainNamePortal;
11685
12629
  exports.getUniqueItemTitle = getUniqueItemTitle;
12630
+ exports.getUniqueSlug = getUniqueSlug;
11686
12631
  exports.getUserThumbnailUrl = getUserThumbnailUrl;
11687
12632
  exports.getWithDefault = getWithDefault$1;
11688
12633
  exports.hasBasePriv = hasBasePriv;
@@ -11748,6 +12693,7 @@
11748
12693
  exports.setContentSiteUrls = setContentSiteUrls;
11749
12694
  exports.setContentType = setContentType;
11750
12695
  exports.setProp = setProp;
12696
+ exports.setSlugKeyword = setSlugKeyword;
11751
12697
  exports.shareItemToGroups = shareItemToGroups;
11752
12698
  exports.slugify = slugify;
11753
12699
  exports.stringToBlob = stringToBlob;
@@ -11757,6 +12703,8 @@
11757
12703
  exports.unprotectModel = unprotectModel;
11758
12704
  exports.unshareItemFromGroups = unshareItemFromGroups;
11759
12705
  exports.updateDomain = updateDomain;
12706
+ exports.updateModel = updateModel;
12707
+ exports.updateProject = updateProject;
11760
12708
  exports.upgradeProtocol = upgradeProtocol;
11761
12709
  exports.upgradeSiteSchema = upgradeSiteSchema;
11762
12710
  exports.uploadResourcesFromUrl = uploadResourcesFromUrl;