@esri/solution-common 5.2.3 → 5.2.4

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 (192) hide show
  1. package/dist/cjs/completeItem.d.ts +29 -0
  2. package/dist/cjs/completeItem.js +92 -0
  3. package/dist/cjs/completeItem.js.map +1 -0
  4. package/dist/cjs/create-hub-request-options.d.ts +29 -0
  5. package/dist/cjs/create-hub-request-options.js +64 -0
  6. package/dist/cjs/create-hub-request-options.js.map +1 -0
  7. package/dist/cjs/deleteHelpers/deleteEmptyGroups.d.ts +24 -0
  8. package/dist/cjs/deleteHelpers/deleteEmptyGroups.js +42 -0
  9. package/dist/cjs/deleteHelpers/deleteEmptyGroups.js.map +1 -0
  10. package/dist/cjs/deleteHelpers/deleteGroupIfEmpty.d.ts +27 -0
  11. package/dist/cjs/deleteHelpers/deleteGroupIfEmpty.js +97 -0
  12. package/dist/cjs/deleteHelpers/deleteGroupIfEmpty.js.map +1 -0
  13. package/dist/cjs/deleteHelpers/deleteSolutionContents.d.ts +38 -0
  14. package/dist/cjs/deleteHelpers/deleteSolutionContents.js +130 -0
  15. package/dist/cjs/deleteHelpers/deleteSolutionContents.js.map +1 -0
  16. package/dist/cjs/deleteHelpers/deleteSolutionFolder.d.ts +29 -0
  17. package/dist/cjs/deleteHelpers/deleteSolutionFolder.js +79 -0
  18. package/dist/cjs/deleteHelpers/deleteSolutionFolder.js.map +1 -0
  19. package/dist/cjs/deleteHelpers/deleteSolutionItem.d.ts +30 -0
  20. package/dist/cjs/deleteHelpers/deleteSolutionItem.js +54 -0
  21. package/dist/cjs/deleteHelpers/deleteSolutionItem.js.map +1 -0
  22. package/dist/cjs/deleteHelpers/index.d.ts +22 -0
  23. package/dist/cjs/deleteHelpers/index.js +26 -0
  24. package/dist/cjs/deleteHelpers/index.js.map +1 -0
  25. package/dist/cjs/deleteHelpers/reconstructBuildOrderIds.d.ts +27 -0
  26. package/dist/cjs/deleteHelpers/reconstructBuildOrderIds.js +34 -0
  27. package/dist/cjs/deleteHelpers/reconstructBuildOrderIds.js.map +1 -0
  28. package/dist/cjs/deleteHelpers/removeItems.d.ts +34 -0
  29. package/dist/cjs/deleteHelpers/removeItems.js +112 -0
  30. package/dist/cjs/deleteHelpers/removeItems.js.map +1 -0
  31. package/dist/cjs/deleteHelpers/reportProgress.d.ts +27 -0
  32. package/dist/cjs/deleteHelpers/reportProgress.js +46 -0
  33. package/dist/cjs/deleteHelpers/reportProgress.js.map +1 -0
  34. package/dist/cjs/deleteSolution.d.ts +55 -0
  35. package/dist/cjs/deleteSolution.js +107 -0
  36. package/dist/cjs/deleteSolution.js.map +1 -0
  37. package/dist/cjs/dependencies.d.ts +26 -0
  38. package/dist/cjs/dependencies.js +171 -0
  39. package/dist/cjs/dependencies.js.map +1 -0
  40. package/dist/cjs/featureServiceHelpers.d.ts +799 -0
  41. package/dist/cjs/featureServiceHelpers.js +2438 -0
  42. package/dist/cjs/featureServiceHelpers.js.map +1 -0
  43. package/dist/cjs/formHelpers.d.ts +41 -0
  44. package/dist/cjs/formHelpers.js +78 -0
  45. package/dist/cjs/formHelpers.js.map +1 -0
  46. package/dist/cjs/generalHelpers.d.ts +433 -0
  47. package/dist/cjs/generalHelpers.js +925 -0
  48. package/dist/cjs/generalHelpers.js.map +1 -0
  49. package/dist/cjs/get-subscription-info.d.ts +27 -0
  50. package/dist/cjs/get-subscription-info.js +39 -0
  51. package/dist/cjs/get-subscription-info.js.map +1 -0
  52. package/dist/cjs/getDeletableSolutionInfo.d.ts +29 -0
  53. package/dist/cjs/getDeletableSolutionInfo.js +53 -0
  54. package/dist/cjs/getDeletableSolutionInfo.js.map +1 -0
  55. package/dist/cjs/getItemTypeAbbrev.d.ts +19 -0
  56. package/dist/cjs/getItemTypeAbbrev.js +186 -0
  57. package/dist/cjs/getItemTypeAbbrev.js.map +1 -0
  58. package/dist/cjs/getSolutionSummary.d.ts +27 -0
  59. package/dist/cjs/getSolutionSummary.js +101 -0
  60. package/dist/cjs/getSolutionSummary.js.map +1 -0
  61. package/dist/cjs/index.d.ts +46 -0
  62. package/dist/cjs/index.js +50 -0
  63. package/dist/cjs/index.js.map +1 -0
  64. package/dist/cjs/interfaces.d.ts +1362 -0
  65. package/dist/cjs/interfaces.js +77 -0
  66. package/dist/cjs/interfaces.js.map +1 -0
  67. package/dist/cjs/libConnectors.d.ts +73 -0
  68. package/dist/cjs/libConnectors.js +115 -0
  69. package/dist/cjs/libConnectors.js.map +1 -0
  70. package/dist/cjs/migrations/apply-schema.d.ts +24 -0
  71. package/dist/cjs/migrations/apply-schema.js +36 -0
  72. package/dist/cjs/migrations/apply-schema.js.map +1 -0
  73. package/dist/cjs/migrations/is-legacy-solution.d.ts +24 -0
  74. package/dist/cjs/migrations/is-legacy-solution.js +40 -0
  75. package/dist/cjs/migrations/is-legacy-solution.js.map +1 -0
  76. package/dist/cjs/migrations/upgrade-three-dot-one.d.ts +27 -0
  77. package/dist/cjs/migrations/upgrade-three-dot-one.js +49 -0
  78. package/dist/cjs/migrations/upgrade-three-dot-one.js.map +1 -0
  79. package/dist/cjs/migrations/upgrade-three-dot-zero.d.ts +27 -0
  80. package/dist/cjs/migrations/upgrade-three-dot-zero.js +43 -0
  81. package/dist/cjs/migrations/upgrade-three-dot-zero.js.map +1 -0
  82. package/dist/cjs/migrations/upgrade-two-dot-five.d.ts +24 -0
  83. package/dist/cjs/migrations/upgrade-two-dot-five.js +73 -0
  84. package/dist/cjs/migrations/upgrade-two-dot-five.js.map +1 -0
  85. package/dist/cjs/migrations/upgrade-two-dot-four.d.ts +24 -0
  86. package/dist/cjs/migrations/upgrade-two-dot-four.js +72 -0
  87. package/dist/cjs/migrations/upgrade-two-dot-four.js.map +1 -0
  88. package/dist/cjs/migrations/upgrade-two-dot-one.d.ts +7 -0
  89. package/dist/cjs/migrations/upgrade-two-dot-one.js +39 -0
  90. package/dist/cjs/migrations/upgrade-two-dot-one.js.map +1 -0
  91. package/dist/cjs/migrations/upgrade-two-dot-seven.d.ts +23 -0
  92. package/dist/cjs/migrations/upgrade-two-dot-seven.js +58 -0
  93. package/dist/cjs/migrations/upgrade-two-dot-seven.js.map +1 -0
  94. package/dist/cjs/migrations/upgrade-two-dot-six.d.ts +27 -0
  95. package/dist/cjs/migrations/upgrade-two-dot-six.js +61 -0
  96. package/dist/cjs/migrations/upgrade-two-dot-six.js.map +1 -0
  97. package/dist/cjs/migrations/upgrade-two-dot-three.d.ts +23 -0
  98. package/dist/cjs/migrations/upgrade-two-dot-three.js +55 -0
  99. package/dist/cjs/migrations/upgrade-two-dot-three.js.map +1 -0
  100. package/dist/cjs/migrations/upgrade-two-dot-two.d.ts +23 -0
  101. package/dist/cjs/migrations/upgrade-two-dot-two.js +58 -0
  102. package/dist/cjs/migrations/upgrade-two-dot-two.js.map +1 -0
  103. package/dist/cjs/migrations/upgrade-two-dot-zero.d.ts +44 -0
  104. package/dist/cjs/migrations/upgrade-two-dot-zero.js +95 -0
  105. package/dist/cjs/migrations/upgrade-two-dot-zero.js.map +1 -0
  106. package/dist/cjs/migrator.d.ts +25 -0
  107. package/dist/cjs/migrator.js +77 -0
  108. package/dist/cjs/migrator.js.map +1 -0
  109. package/dist/cjs/package.json +3 -0
  110. package/dist/cjs/resourceHelpers.d.ts +191 -0
  111. package/dist/cjs/resourceHelpers.js +384 -0
  112. package/dist/cjs/resourceHelpers.js.map +1 -0
  113. package/dist/cjs/resources/add-resource-from-blob.d.ts +26 -0
  114. package/dist/cjs/resources/add-resource-from-blob.js +52 -0
  115. package/dist/cjs/resources/add-resource-from-blob.js.map +1 -0
  116. package/dist/cjs/resources/addMetadataFromBlob.d.ts +25 -0
  117. package/dist/cjs/resources/addMetadataFromBlob.js +43 -0
  118. package/dist/cjs/resources/addMetadataFromBlob.js.map +1 -0
  119. package/dist/cjs/resources/convert-item-resource-to-storage-resource.d.ts +32 -0
  120. package/dist/cjs/resources/convert-item-resource-to-storage-resource.js +70 -0
  121. package/dist/cjs/resources/convert-item-resource-to-storage-resource.js.map +1 -0
  122. package/dist/cjs/resources/convert-storage-resource-to-item-resource.d.ts +29 -0
  123. package/dist/cjs/resources/convert-storage-resource-to-item-resource.js +70 -0
  124. package/dist/cjs/resources/convert-storage-resource-to-item-resource.js.map +1 -0
  125. package/dist/cjs/resources/copyAssociatedFiles.d.ts +67 -0
  126. package/dist/cjs/resources/copyAssociatedFiles.js +304 -0
  127. package/dist/cjs/resources/copyAssociatedFiles.js.map +1 -0
  128. package/dist/cjs/resources/copyDataIntoItem.d.ts +33 -0
  129. package/dist/cjs/resources/copyDataIntoItem.js +62 -0
  130. package/dist/cjs/resources/copyDataIntoItem.js.map +1 -0
  131. package/dist/cjs/resources/copyMetadataIntoItem.d.ts +26 -0
  132. package/dist/cjs/resources/copyMetadataIntoItem.js +46 -0
  133. package/dist/cjs/resources/copyMetadataIntoItem.js.map +1 -0
  134. package/dist/cjs/resources/copyResourceIntoZip.d.ts +33 -0
  135. package/dist/cjs/resources/copyResourceIntoZip.js +78 -0
  136. package/dist/cjs/resources/copyResourceIntoZip.js.map +1 -0
  137. package/dist/cjs/resources/copyZipIntoItem.d.ts +25 -0
  138. package/dist/cjs/resources/copyZipIntoItem.js +54 -0
  139. package/dist/cjs/resources/copyZipIntoItem.js.map +1 -0
  140. package/dist/cjs/resources/createCopyResults.d.ts +25 -0
  141. package/dist/cjs/resources/createCopyResults.js +36 -0
  142. package/dist/cjs/resources/createCopyResults.js.map +1 -0
  143. package/dist/cjs/resources/get-blob.d.ts +26 -0
  144. package/dist/cjs/resources/get-blob.js +27 -0
  145. package/dist/cjs/resources/get-blob.js.map +1 -0
  146. package/dist/cjs/resources/getItemResourcesFilesFromPaths.d.ts +24 -0
  147. package/dist/cjs/resources/getItemResourcesFilesFromPaths.js +49 -0
  148. package/dist/cjs/resources/getItemResourcesFilesFromPaths.js.map +1 -0
  149. package/dist/cjs/resources/getItemResourcesPaths.d.ts +26 -0
  150. package/dist/cjs/resources/getItemResourcesPaths.js +76 -0
  151. package/dist/cjs/resources/getItemResourcesPaths.js.map +1 -0
  152. package/dist/cjs/resources/index.d.ts +29 -0
  153. package/dist/cjs/resources/index.js +33 -0
  154. package/dist/cjs/resources/index.js.map +1 -0
  155. package/dist/cjs/resources/solution-resource.d.ts +35 -0
  156. package/dist/cjs/resources/solution-resource.js +31 -0
  157. package/dist/cjs/resources/solution-resource.js.map +1 -0
  158. package/dist/cjs/resources/transform-resource-paths-to-solution-resources.d.ts +56 -0
  159. package/dist/cjs/resources/transform-resource-paths-to-solution-resources.js +146 -0
  160. package/dist/cjs/resources/transform-resource-paths-to-solution-resources.js.map +1 -0
  161. package/dist/cjs/restHelpers.d.ts +607 -0
  162. package/dist/cjs/restHelpers.js +1954 -0
  163. package/dist/cjs/restHelpers.js.map +1 -0
  164. package/dist/cjs/restHelpersGet.d.ts +288 -0
  165. package/dist/cjs/restHelpersGet.js +804 -0
  166. package/dist/cjs/restHelpersGet.js.map +1 -0
  167. package/dist/cjs/sharing/index.d.ts +16 -0
  168. package/dist/cjs/sharing/index.js +20 -0
  169. package/dist/cjs/sharing/index.js.map +1 -0
  170. package/dist/cjs/sharing/share-item-to-groups.d.ts +26 -0
  171. package/dist/cjs/sharing/share-item-to-groups.js +44 -0
  172. package/dist/cjs/sharing/share-item-to-groups.js.map +1 -0
  173. package/dist/cjs/templatization.d.ts +139 -0
  174. package/dist/cjs/templatization.js +316 -0
  175. package/dist/cjs/templatization.js.map +1 -0
  176. package/dist/cjs/trackingHelpers.d.ts +116 -0
  177. package/dist/cjs/trackingHelpers.js +217 -0
  178. package/dist/cjs/trackingHelpers.js.map +1 -0
  179. package/dist/cjs/velocityHelpers.d.ts +57 -0
  180. package/dist/cjs/velocityHelpers.js +135 -0
  181. package/dist/cjs/velocityHelpers.js.map +1 -0
  182. package/dist/cjs/workflowHelpers.d.ts +37 -0
  183. package/dist/cjs/workflowHelpers.js +77 -0
  184. package/dist/cjs/workflowHelpers.js.map +1 -0
  185. package/dist/cjs/workforceHelpers.d.ts +115 -0
  186. package/dist/cjs/workforceHelpers.js +749 -0
  187. package/dist/cjs/workforceHelpers.js.map +1 -0
  188. package/dist/cjs/zip-utils.d.ts +76 -0
  189. package/dist/cjs/zip-utils.js +142 -0
  190. package/dist/cjs/zip-utils.js.map +1 -0
  191. package/dist/esm/package.json +3 -0
  192. package/package.json +2 -2
@@ -0,0 +1,1954 @@
1
+ "use strict";
2
+ /** @license
3
+ * Copyright 2018 Esri
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports._getCreateServiceOptions = exports._countRelationships = exports._addItemMetadataFile = exports._addItemDataFile = exports.updateItemURL = exports.updateItemTemplateFromDictionary = exports.updateItemExtended = exports.updateGroup = exports.updateItem = exports.shareItem = exports.removeUsers = exports.reassignGroup = exports.searchGroupContents = exports.searchGroupAllContents = exports.searchAllGroups = exports.searchGroups = exports.searchAllItems = exports.searchItems = exports.removeItemOrGroup = exports.removeItem = exports.removeGroup = exports.removeFolder = exports.hasInvalidGroupDesignations = exports._parseAdminServiceData = exports.setWorkflowConfigurationZip = exports.getWorkflowConfigurationZip = exports.getFeatureServiceProperties = exports.getServiceLayersAndTables = exports.getRequest = exports._sortRelationships = exports.getLayerUpdates = exports.getLayers = exports.extractDependencies = exports.createUniqueGroup = exports.createUniqueFolder = exports.createItemWithData = exports.createFullItem = exports.createFeatureService = exports.convertExtent = exports.convertExtentWithFallback = exports._validateExtent = exports.convertToISearchOptions = exports.checkRequestStatus = exports.addToServiceDefinition = exports.addTokenToUrl = exports.addForwardItemRelationships = exports.addForwardItemRelationship = exports.getUserSession = exports.addItemData = exports.rest_request = void 0;
19
+ exports._updateItemURL = exports._updateIndexesForRelationshipKeyFields = exports._setItemProperties = exports._reportVariablesInItem = exports._lowercaseDomain = exports._getUpdate = exports._getContingentValuesUpdates = exports._getRelationshipUpdates = exports._getFallbackExtent = void 0;
20
+ /**
21
+ * Provides common functions involving the arcgis-rest-js library.
22
+ *
23
+ * @module restHelpers
24
+ */
25
+ const featureServiceHelpers_1 = require("./featureServiceHelpers");
26
+ const generalHelpers_1 = require("./generalHelpers");
27
+ const interfaces_1 = require("./interfaces");
28
+ const libConnectors_1 = require("./libConnectors");
29
+ const restHelpersGet_1 = require("./restHelpersGet");
30
+ const arcgis_rest_portal_1 = require("@esri/arcgis-rest-portal");
31
+ const arcgis_rest_request_1 = require("@esri/arcgis-rest-request");
32
+ const arcgis_rest_service_admin_1 = require("@esri/arcgis-rest-service-admin");
33
+ const workforceHelpers_1 = require("./workforceHelpers");
34
+ const templatization_1 = require("./templatization");
35
+ const trackingHelpers_1 = require("./trackingHelpers");
36
+ // ------------------------------------------------------------------------------------------------------------------ //
37
+ var arcgis_rest_request_2 = require("@esri/arcgis-rest-request");
38
+ Object.defineProperty(exports, "rest_request", { enumerable: true, get: function () { return arcgis_rest_request_2.request; } });
39
+ // ------------------------------------------------------------------------------------------------------------------ //
40
+ function addItemData(id, data, authentication) {
41
+ const addDataOptions = {
42
+ id,
43
+ data,
44
+ authentication
45
+ };
46
+ return (0, arcgis_rest_portal_1.addItemData)(addDataOptions);
47
+ }
48
+ exports.addItemData = addItemData;
49
+ ;
50
+ /**
51
+ * Creates a UserSession via a function so that the global arcgisSolution variable can access authentication.
52
+ *
53
+ * @param options See https://esri.github.io/arcgis-rest-js/api/auth/IUserSessionOptions/
54
+ * @returns UserSession
55
+ */
56
+ function getUserSession(options = {}) {
57
+ return new interfaces_1.UserSession(options);
58
+ }
59
+ exports.getUserSession = getUserSession;
60
+ /**
61
+ * Adds a forward relationship between two items.
62
+ *
63
+ * @param originItemId Origin of relationship
64
+ * @param destinationItemId Destination of relationship
65
+ * @param relationshipType Type of relationship
66
+ * @param authentication Credentials for the request
67
+ * @returns A Promise to add item resources.
68
+ */
69
+ function addForwardItemRelationship(originItemId, destinationItemId, relationshipType, authentication) {
70
+ return new Promise(resolve => {
71
+ const requestOptions = {
72
+ originItemId,
73
+ destinationItemId,
74
+ relationshipType,
75
+ authentication
76
+ };
77
+ (0, arcgis_rest_portal_1.addItemRelationship)(requestOptions).then(response => {
78
+ resolve({
79
+ success: response.success,
80
+ itemId: originItemId
81
+ });
82
+ }, () => {
83
+ resolve({
84
+ success: false,
85
+ itemId: originItemId
86
+ });
87
+ });
88
+ });
89
+ }
90
+ exports.addForwardItemRelationship = addForwardItemRelationship;
91
+ /**
92
+ * Adds forward relationships for an item.
93
+ *
94
+ * @param originItemId Origin of relationship
95
+ * @param destinationRelationships Destinations
96
+ * @param authentication Credentials for the request
97
+ * @returns A Promise to add item resources.
98
+ */
99
+ function addForwardItemRelationships(originItemId, destinationRelationships, authentication) {
100
+ return new Promise(resolve => {
101
+ // Set up relationships using updated relationship information
102
+ const relationshipPromises = new Array();
103
+ destinationRelationships.forEach(relationship => {
104
+ relationship.relatedItemIds.forEach(relatedItemId => {
105
+ relationshipPromises.push(addForwardItemRelationship(originItemId, relatedItemId, relationship.relationshipType, authentication));
106
+ });
107
+ });
108
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
109
+ Promise.all(relationshipPromises).then((responses) => resolve(responses));
110
+ });
111
+ }
112
+ exports.addForwardItemRelationships = addForwardItemRelationships;
113
+ /**
114
+ * Adds a token to the query parameters of a URL.
115
+ *
116
+ * @param url URL to use as base
117
+ * @param authentication Credentials to be used to generate token for URL
118
+ * @returns A promise that will resolve with the supplied URL with `token=<token>` added to its query params
119
+ * unless either the URL doesn't exist or the token can't be generated
120
+ */
121
+ function addTokenToUrl(url, authentication) {
122
+ return new Promise(resolve => {
123
+ if (!url || !authentication) {
124
+ resolve(url);
125
+ }
126
+ else {
127
+ authentication.getToken(url).then(token => {
128
+ /* istanbul ignore else */
129
+ if (token) {
130
+ url = (0, generalHelpers_1.appendQueryParam)(url, "token=" + token);
131
+ }
132
+ resolve(url);
133
+ }, () => resolve(url));
134
+ }
135
+ });
136
+ }
137
+ exports.addTokenToUrl = addTokenToUrl;
138
+ /**
139
+ * Calls addToDefinition for the service.
140
+ *
141
+ * Added retry due to some solutions failing to deploy in specific orgs/hives due to timeouts.
142
+ * On the first pass we will use the quicker sync request to add.
143
+ * If it fails we will use an async request that will avoid the timeout errors.
144
+ *
145
+ * @param url URL to use as base
146
+ * @param options the info to add to the services definition
147
+ * @param skipRetry a boolean to control if retry logic will be used. Defaults to false.
148
+ * @param useAsync a boolean to control if we will use an async request
149
+ * @returns A promise that will resolve when the request has completed
150
+ */
151
+ function addToServiceDefinition(url, options, skipRetry = false, useAsync = false) {
152
+ /* istanbul ignore else */
153
+ if (useAsync) {
154
+ options.params = { ...options.params, async: true };
155
+ }
156
+ return new Promise((resolve, reject) => {
157
+ (0, arcgis_rest_service_admin_1.addToServiceDefinition)(url, options).then((result) => {
158
+ checkRequestStatus(result, options.authentication).then(() => resolve(null), e => reject((0, generalHelpers_1.fail)(e)));
159
+ }, e => {
160
+ if (!skipRetry) {
161
+ addToServiceDefinition(url, options, true, true).then(() => resolve(null), e => reject(e));
162
+ }
163
+ else {
164
+ reject((0, generalHelpers_1.fail)(e));
165
+ }
166
+ });
167
+ });
168
+ }
169
+ exports.addToServiceDefinition = addToServiceDefinition;
170
+ /**
171
+ * When using an async request we need to poll the status url to know when the request has completed or failed.
172
+ *
173
+ * @param result the result returned from the addToDefinition request.
174
+ * This will contain a status url or the standard sync result.
175
+ * @param authentication Credentials to be used to generate token for URL
176
+ * @returns A promise that will resolve when the request has completed
177
+ */
178
+ function checkRequestStatus(result, authentication) {
179
+ return new Promise((resolve, reject) => {
180
+ const url = result.statusURL || result.statusUrl;
181
+ if (url) {
182
+ const checkStatus = setInterval(() => {
183
+ (0, arcgis_rest_request_1.request)(url, { authentication }).then(r => {
184
+ /* istanbul ignore else */
185
+ if (["completed", "success"].indexOf(r.status.toLowerCase()) > -1) {
186
+ clearInterval(checkStatus);
187
+ resolve();
188
+ }
189
+ else if (r.status.toLowerCase() === "failed") {
190
+ clearInterval(checkStatus);
191
+ reject(r);
192
+ }
193
+ }, e => {
194
+ clearInterval(checkStatus);
195
+ reject(e);
196
+ });
197
+ }, 2000);
198
+ }
199
+ else {
200
+ resolve();
201
+ }
202
+ });
203
+ }
204
+ exports.checkRequestStatus = checkRequestStatus;
205
+ /**
206
+ * Converts a general search into an ISearchOptions structure.
207
+ *
208
+ * @param search Search specified in one of three ways
209
+ * @returns Recast search
210
+ */
211
+ function convertToISearchOptions(search) {
212
+ // Convert the search into an ISearchOptions
213
+ let searchOptions = {
214
+ q: "",
215
+ start: 1,
216
+ num: 100
217
+ };
218
+ if (typeof search === "string") {
219
+ // Insert query into defaults
220
+ searchOptions.q = search;
221
+ }
222
+ else if (search instanceof arcgis_rest_portal_1.SearchQueryBuilder) {
223
+ // Insert query into defaults
224
+ searchOptions.q = search.toParam();
225
+ }
226
+ else { // search is ISearchOptions
227
+ searchOptions = {
228
+ ...searchOptions,
229
+ ...search // request
230
+ };
231
+ }
232
+ // Remove the sortField if it's "relevance"; that's the default option and is not meant to be specified
233
+ if (searchOptions.sortField === "relevance") {
234
+ delete searchOptions.sortField;
235
+ }
236
+ return searchOptions;
237
+ }
238
+ exports.convertToISearchOptions = convertToISearchOptions;
239
+ /**
240
+ * Simple validate function to ensure all coordinates are numbers
241
+ * In some cases orgs can have null or undefined coordinate values associated with the org extent
242
+ *
243
+ * @param extent the extent to validate
244
+ * @returns the provided extent or a default global extent if some coordinates are not numbers
245
+ * @private
246
+ */
247
+ function _validateExtent(extent) {
248
+ // in some cases orgs can have invalid extents defined
249
+ // this is a simple validate function that will ensure coordiantes are numbers
250
+ // using -179,-89,179,89 because the project call is returning "NaN" when using -180,-90,180,90
251
+ const hasInvalid = typeof extent.xmin !== "number" ||
252
+ typeof extent.xmax !== "number" ||
253
+ typeof extent.ymax !== "number" ||
254
+ typeof extent.ymin !== "number";
255
+ if (hasInvalid) {
256
+ extent.xmin = -179;
257
+ extent.xmax = 179;
258
+ extent.ymax = 89;
259
+ extent.ymin = -89;
260
+ extent.spatialReference = { wkid: 4326 };
261
+ }
262
+ return extent;
263
+ }
264
+ exports._validateExtent = _validateExtent;
265
+ /**
266
+ * If the request to convert the extent fails it has commonly been due to an invalid extent.
267
+ * This function will first attempt to use the provided extent. If it fails it will default to
268
+ * the source items extent and if that fails it will then use a default global extent.
269
+ *
270
+ * @param extent the extent to convert
271
+ * @param fallbackExtent the extent to convert if the main extent does not project to the outSR
272
+ * @param outSR the spatial reference to project to
273
+ * @param geometryServiceUrl the service url for the geometry service to use
274
+ * @param authentication the credentials for the requests
275
+ * @returns the extent projected to the provided spatial reference
276
+ * or the world extent projected to the provided spatial reference
277
+ * @private
278
+ */
279
+ function convertExtentWithFallback(extent, fallbackExtent, outSR, geometryServiceUrl, authentication) {
280
+ return new Promise((resolve, reject) => {
281
+ const defaultExtent = {
282
+ xmin: -179,
283
+ xmax: 179,
284
+ ymin: -89,
285
+ ymax: 89,
286
+ spatialReference: { wkid: 4326 }
287
+ };
288
+ convertExtent(_validateExtent(extent), outSR, geometryServiceUrl, authentication).then(extentResponse => {
289
+ // in some cases project will complete successfully but return "NaN" values
290
+ // check for this and call convert again if it does
291
+ const extentResponseString = JSON.stringify(extentResponse);
292
+ const validatedExtent = JSON.stringify(_validateExtent(extentResponse));
293
+ if (extentResponseString === validatedExtent) {
294
+ resolve(extentResponse);
295
+ }
296
+ else {
297
+ convertExtent(fallbackExtent || defaultExtent, outSR, geometryServiceUrl, authentication).then(resolve, e => reject((0, generalHelpers_1.fail)(e)));
298
+ }
299
+ },
300
+ // if convert fails try again with default global extent
301
+ () => {
302
+ convertExtent(defaultExtent, outSR, geometryServiceUrl, authentication).then(resolve, e => reject((0, generalHelpers_1.fail)(e)));
303
+ });
304
+ });
305
+ }
306
+ exports.convertExtentWithFallback = convertExtentWithFallback;
307
+ /**
308
+ * Converts an extent to a specified spatial reference.
309
+ *
310
+ * @param extent Extent object to check and (possibly) to project
311
+ * @param outSR Desired spatial reference
312
+ * @param geometryServiceUrl Path to geometry service providing `findTransformations` and `project` services
313
+ * @param authentication Credentials for the request
314
+ * @returns Original extent if it's already using outSR or the extents projected into the outSR
315
+ */
316
+ function convertExtent(extent, outSR, geometryServiceUrl, authentication) {
317
+ const _requestOptions = { authentication };
318
+ return new Promise((resolve, reject) => {
319
+ if (extent.spatialReference.wkid === outSR?.wkid || !outSR) {
320
+ resolve(extent);
321
+ }
322
+ else {
323
+ _requestOptions.params = {
324
+ f: "json",
325
+ inSR: extent.spatialReference.wkid,
326
+ outSR: outSR.wkid,
327
+ extentOfInterest: JSON.stringify(extent)
328
+ };
329
+ (0, arcgis_rest_request_1.request)((0, generalHelpers_1.checkUrlPathTermination)(geometryServiceUrl) + "findTransformations", _requestOptions).then(response => {
330
+ const transformations = response && response.transformations
331
+ ? response.transformations
332
+ : undefined;
333
+ let transformation;
334
+ if (transformations && transformations.length > 0) {
335
+ // if a forward single transformation is found use that...otherwise check for and use composite
336
+ transformation = transformations[0].wkid
337
+ ? transformations[0].wkid
338
+ : transformations[0].geoTransforms
339
+ ? transformations[0]
340
+ : undefined;
341
+ }
342
+ _requestOptions.params = {
343
+ f: "json",
344
+ outSR: outSR.wkid,
345
+ inSR: extent.spatialReference.wkid,
346
+ geometries: {
347
+ geometryType: "esriGeometryPoint",
348
+ geometries: [
349
+ { x: extent.xmin, y: extent.ymin },
350
+ { x: extent.xmax, y: extent.ymax }
351
+ ]
352
+ },
353
+ transformation: transformation
354
+ };
355
+ (0, arcgis_rest_request_1.request)((0, generalHelpers_1.checkUrlPathTermination)(geometryServiceUrl) + "project", _requestOptions).then(projectResponse => {
356
+ const projectGeom = projectResponse.geometries.length === 2
357
+ ? projectResponse.geometries
358
+ : undefined;
359
+ if (projectGeom) {
360
+ resolve({
361
+ xmin: projectGeom[0].x,
362
+ ymin: projectGeom[0].y,
363
+ xmax: projectGeom[1].x,
364
+ ymax: projectGeom[1].y,
365
+ spatialReference: outSR
366
+ });
367
+ }
368
+ else {
369
+ resolve(undefined);
370
+ }
371
+ }, e => reject((0, generalHelpers_1.fail)(e)));
372
+ }, e => reject((0, generalHelpers_1.fail)(e)));
373
+ }
374
+ });
375
+ }
376
+ exports.convertExtent = convertExtent;
377
+ /**
378
+ * Publishes a feature service as an AGOL item; it does not include its layers and tables
379
+ *
380
+ * @param newItemTemplate Template of item to be created
381
+ * @param authentication Credentials for the request
382
+ * @param templateDictionary Hash of facts: org URL, adlib replacements, user; .user.folders property contains a list
383
+ * @returns A promise that will resolve with an object reporting success and the Solution id
384
+ */
385
+ function createFeatureService(newItemTemplate, authentication, templateDictionary) {
386
+ return new Promise((resolve, reject) => {
387
+ // Create item
388
+ _getCreateServiceOptions(newItemTemplate, authentication, templateDictionary).then(createOptions => {
389
+ (0, arcgis_rest_service_admin_1.createFeatureService)(createOptions).then(createResponse => {
390
+ // Federated servers may have inconsistent casing, so lowerCase it
391
+ createResponse.encodedServiceURL = _lowercaseDomain(createResponse.encodedServiceURL);
392
+ createResponse.serviceurl = _lowercaseDomain(createResponse.serviceurl);
393
+ resolve(createResponse);
394
+ }, e => reject((0, generalHelpers_1.fail)(e)));
395
+ }, e => reject((0, generalHelpers_1.fail)(e)));
396
+ });
397
+ }
398
+ exports.createFeatureService = createFeatureService;
399
+ /**
400
+ * Publishes an item and its data, metadata, and resources as an AGOL item.
401
+ *
402
+ * @param itemInfo Item's `item` section
403
+ * @param folderId Id of folder to receive item; null indicates that the item goes into the root
404
+ * folder; ignored for Group item type
405
+ * @param destinationAuthentication Credentials for for requests to where the item is to be created
406
+ * @param itemThumbnailUrl URL to image to use for item thumbnail
407
+ * @param itemThumbnailAuthentication Credentials for requests to the thumbnail source
408
+ * @param dataFile Item's `data` section
409
+ * @param metadataFile Item's metadata file
410
+ * @param resourcesFiles Item's resources
411
+ * @param access Access to set for item: "public", "org", "private"
412
+ * @returns A promise that will resolve with an object reporting success or failure and the Solution id
413
+ */
414
+ function createFullItem(itemInfo, folderId, destinationAuthentication, itemThumbnailUrl, itemThumbnailAuthentication, dataFile, metadataFile, resourcesFiles, access = "private") {
415
+ return new Promise((resolve, reject) => {
416
+ // Create item
417
+ const createOptions = {
418
+ item: {
419
+ ...itemInfo
420
+ },
421
+ folderId,
422
+ authentication: destinationAuthentication
423
+ };
424
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
425
+ addTokenToUrl(itemThumbnailUrl, itemThumbnailAuthentication).then(updatedThumbnailUrl => {
426
+ /* istanbul ignore else */
427
+ if (updatedThumbnailUrl) {
428
+ createOptions.item.thumbnailUrl = (0, generalHelpers_1.appendQueryParam)(updatedThumbnailUrl, "w=400");
429
+ }
430
+ (0, arcgis_rest_portal_1.createItemInFolder)(createOptions).then(createResponse => {
431
+ if (createResponse.success) {
432
+ let accessDef;
433
+ // Set access if it is not AGOL default
434
+ // Set the access manually since the access value in createItem appears to be ignored
435
+ // Need to run serially; will not work reliably if done in parallel with adding the data section
436
+ if (access !== "private") {
437
+ const accessOptions = {
438
+ id: createResponse.id,
439
+ access: access === "public" ? "public" : "org",
440
+ authentication: destinationAuthentication
441
+ };
442
+ accessDef = (0, arcgis_rest_portal_1.setItemAccess)(accessOptions);
443
+ }
444
+ else {
445
+ accessDef = Promise.resolve({
446
+ itemId: createResponse.id
447
+ });
448
+ }
449
+ // Now add attached items
450
+ accessDef.then(() => {
451
+ const updateDefs = [];
452
+ // Add the data section
453
+ if (dataFile) {
454
+ updateDefs.push(_addItemDataFile(createResponse.id, dataFile, destinationAuthentication));
455
+ }
456
+ // Add the resources via a zip because AGO sometimes loses resources if many are added at the
457
+ // same time to the same item
458
+ if (Array.isArray(resourcesFiles) &&
459
+ resourcesFiles.length > 0) {
460
+ updateDefs.push(new Promise((rsrcResolve, rsrcReject) => {
461
+ (0, libConnectors_1.createZip)("resources.zip", resourcesFiles).then((zipfile) => {
462
+ const addResourceOptions = {
463
+ id: createResponse.id,
464
+ resource: zipfile,
465
+ authentication: destinationAuthentication,
466
+ params: {
467
+ archive: true
468
+ }
469
+ };
470
+ (0, arcgis_rest_portal_1.addItemResource)(addResourceOptions).then(rsrcResolve, rsrcReject);
471
+ }, rsrcReject);
472
+ }));
473
+ }
474
+ // Add the metadata section
475
+ if (metadataFile) {
476
+ updateDefs.push(_addItemMetadataFile(createResponse.id, metadataFile, destinationAuthentication));
477
+ }
478
+ // Wait until all adds are done
479
+ Promise.all(updateDefs).then(() => resolve(createResponse), e => reject((0, generalHelpers_1.fail)(e)));
480
+ }, e => reject((0, generalHelpers_1.fail)(e)));
481
+ }
482
+ else {
483
+ reject((0, generalHelpers_1.fail)());
484
+ }
485
+ }, e => reject((0, generalHelpers_1.fail)(e)));
486
+ });
487
+ });
488
+ }
489
+ exports.createFullItem = createFullItem;
490
+ /**
491
+ * Publishes an item and its data as an AGOL item.
492
+ *
493
+ * @param itemInfo Item's `item` section
494
+ * @param dataInfo Item's `data` section
495
+ * @param authentication Credentials for the request
496
+ * @param folderId Id of folder to receive item; null indicates that the item goes into the root
497
+ * folder; ignored for Group item type
498
+ * @param access Access to set for item: "public", "org", "private"
499
+ * @returns A promise that will resolve with an object reporting success and the Solution id
500
+ */
501
+ function createItemWithData(itemInfo, dataInfo, authentication, folderId, access = "private") {
502
+ return new Promise((resolve, reject) => {
503
+ // Create item
504
+ const createOptions = {
505
+ item: {
506
+ title: "_",
507
+ ...itemInfo,
508
+ data: dataInfo
509
+ },
510
+ folderId,
511
+ authentication: authentication
512
+ };
513
+ if (itemInfo.thumbnail) {
514
+ createOptions.params = {
515
+ // Pass thumbnail file in via params because item property is serialized, which discards a blob
516
+ thumbnail: itemInfo.thumbnail
517
+ };
518
+ delete createOptions.item.thumbnail;
519
+ }
520
+ (0, arcgis_rest_portal_1.createItemInFolder)(createOptions).then(createResponse => {
521
+ if (createResponse.success) {
522
+ if (access !== "private") {
523
+ // Set access if it is not AGOL default
524
+ // Set the access manually since the access value in createItem appears to be ignored
525
+ const accessOptions = {
526
+ id: createResponse.id,
527
+ access: access === "public" ? "public" : "org",
528
+ authentication: authentication
529
+ };
530
+ (0, arcgis_rest_portal_1.setItemAccess)(accessOptions).then(() => {
531
+ resolve({
532
+ folder: createResponse.folder,
533
+ id: createResponse.id,
534
+ success: true
535
+ });
536
+ }, e => reject((0, generalHelpers_1.fail)(e)));
537
+ }
538
+ else {
539
+ resolve({
540
+ folder: createResponse.folder,
541
+ id: createResponse.id,
542
+ success: true
543
+ });
544
+ }
545
+ }
546
+ else {
547
+ reject((0, generalHelpers_1.fail)());
548
+ }
549
+ }, e => reject((0, generalHelpers_1.fail)(e)));
550
+ });
551
+ }
552
+ exports.createItemWithData = createItemWithData;
553
+ /**
554
+ * Creates a folder using a numeric suffix to ensure uniqueness if necessary.
555
+ *
556
+ * @param title Folder title, used as-is if possible and with suffix otherwise
557
+ * @param templateDictionary Hash of facts: org URL, adlib replacements, user; .user.folders property contains a list
558
+ * of known folder names; function updates list with existing names not yet known, and creates .user.folders if it
559
+ * doesn't exist in the dictionary
560
+ * @param authentication Credentials for creating folder
561
+ * @returns Id of created folder
562
+ */
563
+ function createUniqueFolder(title, templateDictionary, authentication) {
564
+ return new Promise((resolve, reject) => {
565
+ // Get a title that is not already in use
566
+ const folderTitle = (0, generalHelpers_1.getUniqueTitle)(title, templateDictionary, "user.folders");
567
+ const folderCreationParam = {
568
+ title: folderTitle,
569
+ authentication: authentication
570
+ };
571
+ (0, arcgis_rest_portal_1.createFolder)(folderCreationParam).then(ok => resolve(ok), err => {
572
+ // If the name already exists, we'll try again
573
+ const errorDetails = (0, generalHelpers_1.getProp)(err, "response.error.details");
574
+ if (Array.isArray(errorDetails) && errorDetails.length > 0) {
575
+ const nameNotAvailMsg = "Folder title '" + folderTitle + "' not available.";
576
+ if (errorDetails.indexOf(nameNotAvailMsg) >= 0) {
577
+ // Create the user.folders property if it doesn't exist
578
+ /* istanbul ignore else */
579
+ if (!(0, generalHelpers_1.getProp)(templateDictionary, "user.folders")) {
580
+ (0, generalHelpers_1.setCreateProp)(templateDictionary, "user.folders", []);
581
+ }
582
+ templateDictionary.user.folders.push({
583
+ title: folderTitle
584
+ });
585
+ createUniqueFolder(title, templateDictionary, authentication).then(resolve, reject);
586
+ }
587
+ else {
588
+ reject(err);
589
+ }
590
+ }
591
+ else {
592
+ // Otherwise, error out
593
+ reject(err);
594
+ }
595
+ });
596
+ });
597
+ }
598
+ exports.createUniqueFolder = createUniqueFolder;
599
+ /**
600
+ * Creates a group using numeric suffix to ensure uniqueness.
601
+ *
602
+ * @param title Group title, used as-is if possible and with suffix otherwise
603
+ * @param templateDictionary Hash of facts: org URL, adlib replacements, user
604
+ * @param authentication Credentials for creating group
605
+ * @param owner Optional arg for the Tracking owner
606
+ * If the tracking owner is not the one deploying the solution
607
+ * tracker groups will be created under the deployment user but
608
+ * will be reassigned to the tracking owner.
609
+ * @returns Information about created group
610
+ */
611
+ function createUniqueGroup(title, groupItem, templateDictionary, authentication, owner) {
612
+ return new Promise((resolve, reject) => {
613
+ let groupsPromise;
614
+ // when working with tracker we need to consider the groups of the deploying user as well as the groups
615
+ // of the tracking user...must be unique for both
616
+ if (owner && owner !== authentication.username) {
617
+ groupsPromise = searchAllGroups(`(owner:${owner}) orgid:${templateDictionary.organization.id}`, authentication);
618
+ }
619
+ else {
620
+ groupsPromise = Promise.resolve([]);
621
+ }
622
+ // first get the tracker owner groups
623
+ groupsPromise.then(groups => {
624
+ templateDictionary["allGroups"] =
625
+ groups.concat((0, generalHelpers_1.getProp)(templateDictionary, "user.groups"));
626
+ // Get a title that is not already in use
627
+ groupItem.title = (0, generalHelpers_1.getUniqueTitle)(title, templateDictionary, "allGroups");
628
+ const groupCreationParam = {
629
+ group: groupItem,
630
+ authentication: authentication
631
+ };
632
+ (0, arcgis_rest_portal_1.createGroup)(groupCreationParam).then(resolve, err => {
633
+ // If the name already exists, we'll try again
634
+ const errorDetails = (0, generalHelpers_1.getProp)(err, "response.error.details");
635
+ if (Array.isArray(errorDetails) && errorDetails.length > 0) {
636
+ const nameNotAvailMsg = "You already have a group named '" +
637
+ groupItem.title +
638
+ "'. Try a different name.";
639
+ if (errorDetails.indexOf(nameNotAvailMsg) >= 0) {
640
+ templateDictionary.user.groups.push({
641
+ title: groupItem.title
642
+ });
643
+ createUniqueGroup(title, groupItem, templateDictionary, authentication).then(resolve, reject);
644
+ }
645
+ else {
646
+ reject(err);
647
+ }
648
+ }
649
+ else {
650
+ // Otherwise, error out
651
+ reject(err);
652
+ }
653
+ });
654
+ }, e => reject(e));
655
+ });
656
+ }
657
+ exports.createUniqueGroup = createUniqueGroup;
658
+ /**
659
+ * Gets the ids of the dependencies of an AGOL feature service item.
660
+ * Dependencies will only exist when the service is a view.
661
+ *
662
+ * @param itemTemplate Template of item to be created
663
+ * @param authentication Credentials for the request
664
+ * @returns A promise that will resolve a list of dependencies
665
+ */
666
+ function extractDependencies(itemTemplate, authentication) {
667
+ const dependencies = [];
668
+ return new Promise((resolve, reject) => {
669
+ // Get service dependencies when the item is a view
670
+ // This step is skipped for tracker views as they will already have a source service in the org
671
+ if (itemTemplate.properties.service.isView && itemTemplate.item.url && !(0, trackingHelpers_1.isTrackingViewTemplate)(itemTemplate)) {
672
+ (0, arcgis_rest_request_1.request)((0, generalHelpers_1.checkUrlPathTermination)(itemTemplate.item.url) + "sources?f=json", {
673
+ authentication: authentication
674
+ }).then(response => {
675
+ /* istanbul ignore else */
676
+ if (response && response.services) {
677
+ response.services.forEach((layer) => {
678
+ dependencies.push({
679
+ id: layer.serviceItemId,
680
+ name: layer.name
681
+ });
682
+ });
683
+ }
684
+ resolve(dependencies);
685
+ }, e => reject((0, generalHelpers_1.fail)(e)));
686
+ }
687
+ else if ((0, workforceHelpers_1.isWorkforceProject)(itemTemplate)) {
688
+ resolve((0, workforceHelpers_1.getWorkforceDependencies)(itemTemplate, dependencies));
689
+ }
690
+ else {
691
+ resolve(dependencies);
692
+ }
693
+ });
694
+ }
695
+ exports.extractDependencies = extractDependencies;
696
+ /**
697
+ * Get json info for the services layers
698
+ *
699
+ * @param serviceUrl the url for the service
700
+ * @param layerList list of base layer info
701
+ * @param authentication Credentials for the request
702
+ * @returns A promise that will resolve a list of dependencies
703
+ */
704
+ function getLayers(serviceUrl, layerList, authentication) {
705
+ return new Promise((resolve, reject) => {
706
+ if (layerList.length === 0) {
707
+ resolve([]);
708
+ }
709
+ // get the admin URL
710
+ serviceUrl = serviceUrl.replace("/rest/services", "/rest/admin/services");
711
+ const requestsDfd = [];
712
+ layerList.forEach(layer => {
713
+ const requestOptions = {
714
+ authentication: authentication
715
+ };
716
+ requestsDfd.push((0, arcgis_rest_request_1.request)((0, generalHelpers_1.checkUrlPathTermination)(serviceUrl) + layer["id"] + "?f=json", requestOptions));
717
+ });
718
+ // Wait until all layers are heard from
719
+ Promise.all(requestsDfd).then(layers => resolve(layers), e => reject((0, generalHelpers_1.fail)(e)));
720
+ });
721
+ }
722
+ exports.getLayers = getLayers;
723
+ /**
724
+ * Add additional options to a layers definition.
725
+ *
726
+ * @param args The IPostProcessArgs for the request(s)
727
+ * @param isPortal boolean to indicate if we are deploying to portal
728
+ *
729
+ * @returns An array of update instructions
730
+ * @private
731
+ */
732
+ function getLayerUpdates(args, isPortal) {
733
+ const adminUrl = args.itemTemplate.item.url.replace("rest/services", "rest/admin/services");
734
+ const updates = [];
735
+ const refresh = _getUpdate(adminUrl, null, null, args, "refresh");
736
+ updates.push(refresh);
737
+ Object.keys(args.objects).forEach(id => {
738
+ const obj = Object.assign({}, args.objects[id]);
739
+ // These properties cannot be set in the update definition when working with portal
740
+ if (isPortal) {
741
+ (0, generalHelpers_1.deleteProps)(obj, ["type", "id", "relationships", "sourceServiceFields"]);
742
+ }
743
+ // handle definition deletes
744
+ // removes previous editFieldsInfo fields if their names were changed
745
+ if (obj.hasOwnProperty("deleteFields")) {
746
+ updates.push(_getUpdate(adminUrl, id, obj, args, "delete"));
747
+ (0, generalHelpers_1.deleteProp)(obj, "deleteFields");
748
+ updates.push(_getUpdate(adminUrl, null, null, args, "refresh"));
749
+ }
750
+ });
751
+ // issue: #706
752
+ // Add source service relationships
753
+ // views will now always add all layers in a single call and will inherit the relationships from the source service
754
+ if (!args.itemTemplate.properties.service.isView) {
755
+ const relUpdates = _getRelationshipUpdates({
756
+ message: "updated layer relationships",
757
+ objects: args.objects,
758
+ itemTemplate: args.itemTemplate,
759
+ authentication: args.authentication
760
+ });
761
+ // issue: #724
762
+ // In portal the order the relationships are added needs to follow the layer order
763
+ // otherwise the relationship IDs will be reset
764
+ relUpdates.layers = _sortRelationships(args.itemTemplate.properties.layers, args.itemTemplate.properties.tables, relUpdates);
765
+ /* istanbul ignore else */
766
+ if (relUpdates.layers.length > 0) {
767
+ updates.push(_getUpdate(adminUrl, null, relUpdates, args, "add"));
768
+ updates.push(refresh);
769
+ }
770
+ // handle contingent values
771
+ const contingentValuesUpdates = _getContingentValuesUpdates({
772
+ message: "add layer contingent values",
773
+ objects: args.objects,
774
+ itemTemplate: args.itemTemplate,
775
+ authentication: args.authentication
776
+ });
777
+ /* istanbul ignore else */
778
+ if (contingentValuesUpdates.length > 0) {
779
+ contingentValuesUpdates.forEach(conUpdate => {
780
+ updates.push(_getUpdate(adminUrl + conUpdate.id, null, conUpdate.contingentValues, args, "add"));
781
+ });
782
+ }
783
+ }
784
+ return updates.length === 1 ? [] : updates;
785
+ }
786
+ exports.getLayerUpdates = getLayerUpdates;
787
+ /**
788
+ * Sorts relationships based on order of supporting layers and tables in the service definition
789
+ *
790
+ * @param layers the layers from the service
791
+ * @param tables the tables from the service
792
+ * @param relUpdates the relationships to add for the service
793
+ *
794
+ * @returns An array with relationships that have been sorted
795
+ * @private
796
+ */
797
+ function _sortRelationships(layers, tables, relUpdates) {
798
+ const ids = [].concat(layers.map((l) => l.id), tables.map((t) => t.id));
799
+ // In portal the order the relationships are added needs to follow the layer order
800
+ // otherwise the relationship IDs will be reset
801
+ const _relUpdateLayers = [];
802
+ ids.forEach(id => {
803
+ relUpdates.layers.some((relUpdate) => {
804
+ if (id === relUpdate.id) {
805
+ _relUpdateLayers.push(relUpdate);
806
+ return true;
807
+ }
808
+ else {
809
+ return false;
810
+ }
811
+ });
812
+ });
813
+ return _relUpdateLayers;
814
+ }
815
+ exports._sortRelationships = _sortRelationships;
816
+ /**
817
+ * Add additional options to a layers definition
818
+ *
819
+ * Added retry due to some solutions failing to deploy in specific orgs/hives
820
+ *
821
+ *
822
+ * @param Update will contain either add, update, or delete from service definition call
823
+ * @param skipRetry defaults to false. when true the retry logic will be ignored
824
+ * @returns A promise that will resolve when service definition call has completed
825
+ * @private
826
+ */
827
+ /* istanbul ignore else */
828
+ function getRequest(update, skipRetry = false, useAsync = false) {
829
+ return new Promise((resolve, reject) => {
830
+ const options = {
831
+ params: update.params,
832
+ authentication: update.args.authentication
833
+ };
834
+ /* istanbul ignore else */
835
+ if ((useAsync && update.url.indexOf("addToDefinition") > -1) ||
836
+ update.url.indexOf("updateDefinition") > -1 ||
837
+ update.url.indexOf("deleteFromDefinition") > -1) {
838
+ options.params = { ...options.params, async: true };
839
+ }
840
+ (0, arcgis_rest_request_1.request)(update.url, options).then(result => {
841
+ checkRequestStatus(result, options.authentication).then(() => resolve(null), e => reject((0, generalHelpers_1.fail)(e)));
842
+ }, (e) => {
843
+ if (!skipRetry) {
844
+ getRequest(update, true, true).then(() => resolve(), e => reject(e));
845
+ }
846
+ else {
847
+ reject(e);
848
+ }
849
+ });
850
+ });
851
+ }
852
+ exports.getRequest = getRequest;
853
+ /**
854
+ * Fills in missing data, including full layer and table definitions, in a feature services' definition.
855
+ *
856
+ * @param itemTemplate Feature service item, data, dependencies definition to be modified
857
+ * @param authentication Credentials for the request to AGOL
858
+ * @returns A promise that will resolve when fullItem has been updated
859
+ * @private
860
+ */
861
+ function getServiceLayersAndTables(itemTemplate, authentication) {
862
+ return new Promise((resolve, reject) => {
863
+ // To have enough information for reconstructing the service, we'll supplement
864
+ // the item and data sections with sections for the service, full layers, and
865
+ // full tables
866
+ // Extra steps must be taken for workforce version 2
867
+ const isWorkforceService = (0, workforceHelpers_1.isWorkforceProject)(itemTemplate);
868
+ // Get the service description
869
+ if (itemTemplate.item.url) {
870
+ getFeatureServiceProperties(itemTemplate.item.url, authentication, isWorkforceService).then(properties => {
871
+ itemTemplate.properties = properties;
872
+ resolve(itemTemplate);
873
+ }, e => reject((0, generalHelpers_1.fail)(e)));
874
+ }
875
+ else {
876
+ resolve(itemTemplate);
877
+ }
878
+ });
879
+ }
880
+ exports.getServiceLayersAndTables = getServiceLayersAndTables;
881
+ /**
882
+ * Get service properties for the given url and update key props
883
+ *
884
+ * @param serviceUrl the feature service url
885
+ * @param authentication Credentials for the request to AGOL
886
+ * @param workforceService boolean to indicate if extra workforce service steps should be handled
887
+ * @returns A promise that will resolve with the service properties
888
+ * @private
889
+ */
890
+ function getFeatureServiceProperties(serviceUrl, authentication, workforceService = false) {
891
+ return new Promise((resolve, reject) => {
892
+ const properties = {
893
+ service: {},
894
+ layers: [],
895
+ tables: []
896
+ };
897
+ // get the admin URL
898
+ serviceUrl = serviceUrl.replace("/rest/services", "/rest/admin/services");
899
+ // Get the service description
900
+ (0, arcgis_rest_request_1.request)(serviceUrl + "?f=json", {
901
+ authentication: authentication
902
+ }).then(serviceData => {
903
+ properties.service = _parseAdminServiceData(serviceData);
904
+ // Copy cacheMaxAge to top level so that AGO sees it when deploying the service
905
+ // serviceData may have set it if there isn't an adminServiceInfo
906
+ /* istanbul ignore else */
907
+ if (serviceData.adminServiceInfo?.cacheMaxAge) {
908
+ properties.service.cacheMaxAge =
909
+ serviceData.adminServiceInfo.cacheMaxAge;
910
+ }
911
+ // Move the layers and tables out of the service's data section
912
+ /* istanbul ignore else */
913
+ if (serviceData.layers) {
914
+ properties.layers = serviceData.layers;
915
+ // Fill in properties that the service layer doesn't provide
916
+ // and remove properties that should not exist in the template
917
+ properties.layers.forEach(layer => {
918
+ layer.serviceItemId = properties.service.serviceItemId;
919
+ layer.extent = null;
920
+ (0, featureServiceHelpers_1.removeLayerOptimization)(layer);
921
+ });
922
+ }
923
+ delete serviceData.layers;
924
+ /* istanbul ignore else */
925
+ if (serviceData.tables) {
926
+ properties.tables = serviceData.tables;
927
+ // Fill in properties that the service layer doesn't provide
928
+ properties.tables.forEach(table => {
929
+ table.serviceItemId = properties.service.serviceItemId;
930
+ table.extent = null;
931
+ });
932
+ }
933
+ delete serviceData.tables;
934
+ // Ensure solution items have unique indexes on relationship key fields
935
+ _updateIndexesForRelationshipKeyFields(properties);
936
+ (0, featureServiceHelpers_1.processContingentValues)(properties, serviceUrl, authentication).then(() => {
937
+ if (workforceService) {
938
+ (0, workforceHelpers_1.getWorkforceServiceInfo)(properties, serviceUrl, authentication).then(resolve, reject);
939
+ }
940
+ else {
941
+ resolve(properties);
942
+ }
943
+ }, (e) => reject((0, generalHelpers_1.fail)(e)));
944
+ }, (e) => reject((0, generalHelpers_1.fail)(e)));
945
+ });
946
+ }
947
+ exports.getFeatureServiceProperties = getFeatureServiceProperties;
948
+ /**
949
+ * Fetches the configuration of a workflow.
950
+ *
951
+ * @param itemId Id of the workflow item
952
+ * @param authentication Credentials for the request to AGOL
953
+ * @returns Promise resolving with the workflow configuration in a zip file
954
+ */
955
+ async function getWorkflowConfigurationZip(itemId, authentication) {
956
+ const user = await (0, restHelpersGet_1.getUser)(authentication);
957
+ const exportConfigUrl = `https://workflow.arcgis.com/${user.orgId}/admin/${itemId}/export`;
958
+ return (0, arcgis_rest_request_1.request)(exportConfigUrl, {
959
+ authentication,
960
+ headers: {
961
+ Host: "workflow.arcgis.com",
962
+ "Accept": "application/octet-stream",
963
+ "Authorization": `Bearer ${authentication.token}`,
964
+ "X-Esri-Authorization": `Bearer ${authentication.token}`
965
+ },
966
+ params: {
967
+ f: "zip"
968
+ }
969
+ });
970
+ }
971
+ exports.getWorkflowConfigurationZip = getWorkflowConfigurationZip;
972
+ /**
973
+ * Sets the configuration of a workflow.
974
+ *
975
+ * @param configurationZipFile Configuration files in a zip file
976
+ * @param itemId Id of the workflow item
977
+ * @param authentication Credentials for the request to AGOL
978
+ * @returns Promise resolving with the workflow configuration in a zip file
979
+ */
980
+ async function setWorkflowConfigurationZip(configurationZipFile, itemId, authentication) {
981
+ const user = await (0, restHelpersGet_1.getUser)(authentication);
982
+ const importConfigUrl = `https://workflow.arcgis.com/${user.orgId}/admin/${itemId}/import`;
983
+ return (0, arcgis_rest_request_1.request)(importConfigUrl, {
984
+ authentication,
985
+ headers: {
986
+ Host: "workflow.arcgis.com",
987
+ "Accept": "application/octet-stream",
988
+ "Authorization": `Bearer ${authentication.token}`,
989
+ "X-Esri-Authorization": `Bearer ${authentication.token}`
990
+ },
991
+ params: {
992
+ file: configurationZipFile
993
+ }
994
+ });
995
+ }
996
+ exports.setWorkflowConfigurationZip = setWorkflowConfigurationZip;
997
+ /**
998
+ * Parses the layers array and will filter subsets of Layers and Tables
999
+ * Layers and Tables are both returned in the layers array when we access a feature service from the admin api.
1000
+ *
1001
+ * @param adminData The data of the feature service
1002
+ * @returns A mutated version of the provided adminData
1003
+ * @private
1004
+ */
1005
+ function _parseAdminServiceData(adminData) {
1006
+ const layers = adminData.layers || [];
1007
+ const tables = adminData.tables || [];
1008
+ (0, generalHelpers_1.setCreateProp)(adminData, "layers", layers.filter(l => l.type === "Feature Layer"));
1009
+ // TODO understand if the concat is necessary.
1010
+ // Not sure if the admin api will ever actually return a tables collection here.
1011
+ (0, generalHelpers_1.setCreateProp)(adminData, "tables", tables.concat(layers.filter(l => l.type === "Table")));
1012
+ return adminData;
1013
+ }
1014
+ exports._parseAdminServiceData = _parseAdminServiceData;
1015
+ /**
1016
+ * livingatlas designation test.
1017
+ * These layers should not be templatized or depolyed
1018
+ *
1019
+ * @param groupDesignations the items group designations to evaluate
1020
+ * @returns A boolean indicating if the invalid designation is found in the item info
1021
+ */
1022
+ function hasInvalidGroupDesignations(groupDesignations) {
1023
+ const invalidGroupDesignations = ["livingatlas"];
1024
+ return groupDesignations
1025
+ ? invalidGroupDesignations.indexOf(groupDesignations) > -1
1026
+ : false;
1027
+ }
1028
+ exports.hasInvalidGroupDesignations = hasInvalidGroupDesignations;
1029
+ /**
1030
+ * Removes a folder from AGO.
1031
+ *
1032
+ * @param folderId Id of a folder to delete
1033
+ * @param authentication Credentials for the request to AGO
1034
+ * @returns A promise that will resolve with the result of the request
1035
+ */
1036
+ function removeFolder(folderId, authentication) {
1037
+ return new Promise((resolve, reject) => {
1038
+ const requestOptions = {
1039
+ folderId: folderId,
1040
+ authentication: authentication
1041
+ };
1042
+ (0, arcgis_rest_portal_1.removeFolder)(requestOptions).then(result => (result.success ? resolve(result) : reject(result)), reject);
1043
+ });
1044
+ }
1045
+ exports.removeFolder = removeFolder;
1046
+ /**
1047
+ * Removes a group from AGO.
1048
+ *
1049
+ * @param groupId Id of a group to delete
1050
+ * @param authentication Credentials for the request to AGO
1051
+ * @returns A promise that will resolve with the result of the request
1052
+ */
1053
+ function removeGroup(groupId, authentication) {
1054
+ return new Promise((resolve, reject) => {
1055
+ const requestOptions = {
1056
+ id: groupId,
1057
+ authentication: authentication
1058
+ };
1059
+ (0, arcgis_rest_portal_1.removeGroup)(requestOptions).then(result => (result.success ? resolve(result) : reject(result)), reject);
1060
+ });
1061
+ }
1062
+ exports.removeGroup = removeGroup;
1063
+ /**
1064
+ * Removes an item from AGO.
1065
+ *
1066
+ * @param itemId Id of an item to delete
1067
+ * @param authentication Credentials for the request to AGO
1068
+ * @param permanentDelete If true (the default), the item is permanently deleted; if false and the item type
1069
+ * supports the recycle bin, the item will be put into the recycle bin
1070
+ * @returns A promise that will resolve with the result of the request
1071
+ */
1072
+ function removeItem(itemId, authentication, permanentDelete = true) {
1073
+ return new Promise((resolve, reject) => {
1074
+ const requestOptions = {
1075
+ id: itemId,
1076
+ authentication: authentication,
1077
+ params: {
1078
+ permanentDelete
1079
+ }
1080
+ };
1081
+ (0, arcgis_rest_portal_1.removeItem)(requestOptions).then(result => (result.success ? resolve(result) : reject(result)), reject);
1082
+ });
1083
+ }
1084
+ exports.removeItem = removeItem;
1085
+ /**
1086
+ * Removes an item or group from AGO.
1087
+ *
1088
+ * @param itemId Id of an item or group to delete
1089
+ * @param authentication Credentials for the request to AGO
1090
+ * @param permanentDelete If true (the default), the item is permanently deleted; if false and the item type
1091
+ * supports the recycle bin, the item will be put into the recycle bin; note that this does not apply to groups
1092
+ * @returns A promise that will resolve with the result of the request
1093
+ */
1094
+ function removeItemOrGroup(itemId, authentication, permanentDelete = true) {
1095
+ return new Promise((resolve, reject) => {
1096
+ removeItem(itemId, authentication, permanentDelete).then(resolve, error => {
1097
+ removeGroup(itemId, authentication).then(resolve, () => reject(error));
1098
+ });
1099
+ });
1100
+ }
1101
+ exports.removeItemOrGroup = removeItemOrGroup;
1102
+ /**
1103
+ * Searches for items matching a query and that the caller has access to.
1104
+ *
1105
+ * @param search Search string (e.g., "q=redlands+map") or a more detailed structure that can include authentication
1106
+ * @returns Promise resolving with search results
1107
+ * @see https://developers.arcgis.com/rest/users-groups-and-items/search.htm
1108
+ */
1109
+ function searchItems(search) {
1110
+ return (0, arcgis_rest_portal_1.searchItems)(search);
1111
+ }
1112
+ exports.searchItems = searchItems;
1113
+ /**
1114
+ * Searches for items matching a query and that the caller has access to, continuing recursively until done.
1115
+ *
1116
+ * @param search Search string (e.g., "q=redlands+map") or a more detailed structure that can include authentication
1117
+ * @param accumulatedResponse Response built from previous requests
1118
+ * @returns Promise resolving with search results
1119
+ * @see https://developers.arcgis.com/rest/users-groups-and-items/search.htm
1120
+ */
1121
+ function searchAllItems(search, accumulatedResponse) {
1122
+ // Convert the search into an ISearchOptions
1123
+ const searchOptions = convertToISearchOptions(search);
1124
+ // Provide a base into which results can be concatenated
1125
+ const completeResponse = accumulatedResponse ? accumulatedResponse : {
1126
+ query: searchOptions.q,
1127
+ start: 1,
1128
+ num: 100,
1129
+ nextStart: -1,
1130
+ total: 0,
1131
+ results: []
1132
+ };
1133
+ return new Promise((resolve, reject) => {
1134
+ searchItems(search).then(response => {
1135
+ completeResponse.results = completeResponse.results.concat(response.results);
1136
+ completeResponse.num = completeResponse.total = completeResponse.results.length;
1137
+ if (response.nextStart > 0) {
1138
+ // Insert nextStart into next query
1139
+ searchOptions.start = response.nextStart;
1140
+ resolve(searchAllItems(searchOptions, completeResponse));
1141
+ }
1142
+ else {
1143
+ resolve(completeResponse);
1144
+ }
1145
+ }, e => reject(e));
1146
+ });
1147
+ }
1148
+ exports.searchAllItems = searchAllItems;
1149
+ /**
1150
+ * Searches for groups matching criteria.
1151
+ *
1152
+ * @param searchString Text for which to search, e.g., 'redlands+map', 'type:"Web Map" -type:"Web Mapping Application"'
1153
+ * @param authentication Credentials for the request to AGO
1154
+ * @param additionalSearchOptions Adjustments to search, such as tranche size
1155
+ * @returns A promise that will resolve with a structure with a tranche of results and
1156
+ * describing how many items are available
1157
+ * @see https://developers.arcgis.com/rest/users-groups-and-items/group-search.htm
1158
+ * @see https://developers.arcgis.com/rest/users-groups-and-items/search-reference.htm
1159
+ */
1160
+ function searchGroups(searchString, authentication, additionalSearchOptions) {
1161
+ const searchOptions = {
1162
+ q: searchString,
1163
+ params: {
1164
+ ...additionalSearchOptions
1165
+ },
1166
+ authentication: authentication
1167
+ };
1168
+ return (0, arcgis_rest_portal_1.searchGroups)(searchOptions);
1169
+ }
1170
+ exports.searchGroups = searchGroups;
1171
+ /**
1172
+ * Searches for groups matching criteria recurusively.
1173
+ *
1174
+ * @param searchString Text for which to search, e.g., 'redlands+map', 'type:"Web Map" -type:"Web Mapping Application"'
1175
+ * @param authentication Credentials for the request to AGO
1176
+ * @param groups List of groups that have been found from previous requests
1177
+ * @param inPagingParams The paging params for the recurisve searching
1178
+ *
1179
+ * @returns A promise that will resolve with all groups that meet the search criteria
1180
+ */
1181
+ function searchAllGroups(searchString, authentication, groups, inPagingParams) {
1182
+ const pagingParams = inPagingParams ? inPagingParams : {
1183
+ start: 1,
1184
+ num: 24
1185
+ };
1186
+ const additionalSearchOptions = {
1187
+ sortField: "title",
1188
+ sortOrder: "asc",
1189
+ ...pagingParams
1190
+ };
1191
+ // Provide a base onto which results can be concatenated
1192
+ let finalResults = groups ? groups : [];
1193
+ return new Promise((resolve, reject) => {
1194
+ searchGroups(searchString, authentication, additionalSearchOptions).then(response => {
1195
+ finalResults = finalResults.concat(response.results);
1196
+ if (response.nextStart > 0) {
1197
+ pagingParams.start = response.nextStart;
1198
+ resolve(searchAllGroups(searchString, authentication, finalResults, pagingParams));
1199
+ }
1200
+ else {
1201
+ resolve(finalResults);
1202
+ }
1203
+ }, e => reject(e));
1204
+ });
1205
+ }
1206
+ exports.searchAllGroups = searchAllGroups;
1207
+ /**
1208
+ * Searches for group contents matching criteria recursively.
1209
+ *
1210
+ * @param groupId Group whose contents are to be searched
1211
+ * @param searchString Text for which to search, e.g., 'redlands+map', 'type:"Web Map" -type:"Web Mapping Application"'
1212
+ * @param authentication Credentials for the request to AGO
1213
+ * @param additionalSearchOptions Adjustments to search, such as tranche size and categories of interest; categories
1214
+ * are supplied as an array: each array element consists of one or more categories to be ORed; array elements are ANDed
1215
+ * @param portalUrl Rest Url of the portal to perform the search
1216
+ * @param accumulatedResponse Response built from previous requests
1217
+ * @returns A promise that will resolve with a structure with a tranche of results and
1218
+ * describing how many items are available
1219
+ * @see https://developers.arcgis.com/rest/users-groups-and-items/group-content-search.htm
1220
+ * @see https://developers.arcgis.com/rest/users-groups-and-items/search-reference.htm
1221
+ */
1222
+ function searchGroupAllContents(groupId, searchString, authentication, additionalSearchOptions, portalUrl, accumulatedResponse) {
1223
+ additionalSearchOptions = additionalSearchOptions ? additionalSearchOptions : {};
1224
+ // Provide a base into which results can be concatenated
1225
+ const completeResponse = accumulatedResponse ? accumulatedResponse : {
1226
+ query: searchString,
1227
+ start: 1,
1228
+ num: 100,
1229
+ nextStart: -1,
1230
+ total: 0,
1231
+ results: []
1232
+ };
1233
+ // Remove the sortField if it's "relevance"; that's the default option and is not meant to be specified
1234
+ if (additionalSearchOptions.sortField === "relevance") {
1235
+ delete additionalSearchOptions.sortField;
1236
+ }
1237
+ return new Promise((resolve, reject) => {
1238
+ searchGroupContents(groupId, searchString, authentication, additionalSearchOptions, portalUrl).then(response => {
1239
+ completeResponse.results = completeResponse.results.concat(response.results);
1240
+ completeResponse.num = completeResponse.total = completeResponse.results.length;
1241
+ if (response.nextStart > 0) {
1242
+ additionalSearchOptions.start = response.nextStart;
1243
+ resolve(searchGroupAllContents(groupId, searchString, authentication, additionalSearchOptions, portalUrl, completeResponse));
1244
+ }
1245
+ else {
1246
+ resolve(completeResponse);
1247
+ }
1248
+ }, e => reject(e));
1249
+ });
1250
+ }
1251
+ exports.searchGroupAllContents = searchGroupAllContents;
1252
+ /**
1253
+ * Searches for group contents matching criteria.
1254
+ *
1255
+ * @param groupId Group whose contents are to be searched
1256
+ * @param searchString Text for which to search, e.g., 'redlands+map', 'type:"Web Map" -type:"Web Mapping Application"'
1257
+ * @param authentication Credentials for the request to AGO
1258
+ * @param additionalSearchOptions Adjustments to search, such as tranche size and categories of interest; categories
1259
+ * are supplied as an array: each array element consists of one or more categories to be ORed; array elements are ANDed
1260
+ * @param portalUrl Rest Url of the portal to perform the search
1261
+ * @returns A promise that will resolve with a structure with a tranche of results and
1262
+ * describing how many items are available
1263
+ * @see https://developers.arcgis.com/rest/users-groups-and-items/group-content-search.htm
1264
+ * @see https://developers.arcgis.com/rest/users-groups-and-items/search-reference.htm
1265
+ */
1266
+ function searchGroupContents(groupId, searchString, authentication, additionalSearchOptions, portalUrl) {
1267
+ const searchOptions = {
1268
+ groupId,
1269
+ q: searchString,
1270
+ params: Object.assign({
1271
+ num: 100
1272
+ }, additionalSearchOptions),
1273
+ authentication: authentication,
1274
+ portal: portalUrl
1275
+ };
1276
+ // If search options include `categories`, switch to new arcgis-rest-js format
1277
+ /* istanbul ignore else */
1278
+ if (Array.isArray(searchOptions.params.categories)) {
1279
+ searchOptions.params.categories = searchOptions.params.categories.map(andGroup => andGroup.split(","));
1280
+ }
1281
+ return (0, arcgis_rest_portal_1.searchGroupContent)(searchOptions);
1282
+ }
1283
+ exports.searchGroupContents = searchGroupContents;
1284
+ /**
1285
+ * Reassign ownership of a group
1286
+ *
1287
+ * @param groupId Group to remove users from
1288
+ * @param userName The new owner for the group
1289
+ * @param authentication Credentials for the request to
1290
+ *
1291
+ * @returns A promise that will resolve after the group ownership has been assigned
1292
+ *
1293
+ */
1294
+ function reassignGroup(groupId, userName, authentication) {
1295
+ const requestOptions = {
1296
+ authentication: authentication,
1297
+ params: {
1298
+ targetUsername: userName
1299
+ }
1300
+ };
1301
+ return (0, arcgis_rest_request_1.request)(`${authentication.portal}/community/groups/${groupId}/reassign`, requestOptions);
1302
+ }
1303
+ exports.reassignGroup = reassignGroup;
1304
+ /**
1305
+ * Remove users from a group
1306
+ *
1307
+ * @param groupId Group to remove users from
1308
+ * @param users List of users to remove from the group
1309
+ * @param authentication Credentials for the request to
1310
+ *
1311
+ * @returns A promise that will resolve after the users have been removed
1312
+ *
1313
+ */
1314
+ function removeUsers(groupId, users, authentication) {
1315
+ return (0, arcgis_rest_portal_1.removeGroupUsers)({
1316
+ id: groupId,
1317
+ users,
1318
+ authentication
1319
+ });
1320
+ }
1321
+ exports.removeUsers = removeUsers;
1322
+ /**
1323
+ * Shares an item to the defined group
1324
+ *
1325
+ * @param groupId Group to share with
1326
+ * @param id the item id to share with the group
1327
+ * @param destinationAuthentication Credentials for the request to AGO
1328
+ * @param owner owner of the group when sharing tracking items (can be different from the deploying user)
1329
+ *
1330
+ * @returns A promise that will resolve after the item has been shared
1331
+ *
1332
+ */
1333
+ function shareItem(groupId, id, destinationAuthentication, owner) {
1334
+ return new Promise((resolve, reject) => {
1335
+ const shareOptions = {
1336
+ groupId,
1337
+ id,
1338
+ authentication: destinationAuthentication
1339
+ };
1340
+ /* istanbul ignore else */
1341
+ if (owner) {
1342
+ shareOptions.owner = owner;
1343
+ }
1344
+ (0, arcgis_rest_portal_1.shareItemWithGroup)(shareOptions).then(() => resolve(null), (e) => reject((0, generalHelpers_1.fail)(e)));
1345
+ });
1346
+ }
1347
+ exports.shareItem = shareItem;
1348
+ /**
1349
+ * Updates an item.
1350
+ *
1351
+ * @param itemInfo The base info of an item; note that this content will be serialized, which doesn't work
1352
+ * for binary content
1353
+ * @param authentication Credentials for request
1354
+ * @param folderId Item's folder
1355
+ * @param additionalParams Updates that are put under the `params` property, which is not serialized
1356
+ * @return
1357
+ */
1358
+ function updateItem(itemInfo, authentication, folderId, additionalParams) {
1359
+ return new Promise((resolve, reject) => {
1360
+ const updateOptions = {
1361
+ item: itemInfo,
1362
+ folderId: folderId,
1363
+ authentication: authentication,
1364
+ params: {
1365
+ ...(additionalParams ?? {})
1366
+ }
1367
+ };
1368
+ (0, arcgis_rest_portal_1.updateItem)(updateOptions).then(response => (response.success ? resolve(response) : reject(response)), err => reject(err));
1369
+ });
1370
+ }
1371
+ exports.updateItem = updateItem;
1372
+ /**
1373
+ * Updates a group.
1374
+ *
1375
+ * @param groupInfo The base info of a group; note that this content will be serialized, which doesn't work
1376
+ * for binary content
1377
+ * @param authentication Credentials for request
1378
+ * @param additionalParams Updates that are put under the `params` property, which is not serialized
1379
+ * @returns A Promise that will resolve with the success/failure status of the request
1380
+ */
1381
+ function updateGroup(groupInfo, authentication, additionalParams) {
1382
+ return new Promise((resolve, reject) => {
1383
+ const updateOptions = {
1384
+ group: groupInfo,
1385
+ authentication,
1386
+ params: {
1387
+ ...(additionalParams ?? {})
1388
+ }
1389
+ };
1390
+ (0, arcgis_rest_portal_1.updateGroup)(updateOptions).then(response => (response.success ? resolve(response) : reject(response)), err => reject(err));
1391
+ });
1392
+ }
1393
+ exports.updateGroup = updateGroup;
1394
+ /**
1395
+ * Updates an item.
1396
+ *
1397
+ * @param itemInfo The base info of an item
1398
+ * @param data The items data section
1399
+ * @param authentication Credentials for requests
1400
+ * @param thumbnail optional thumbnail to update
1401
+ * @param access "public" or "org"
1402
+ * @return
1403
+ */
1404
+ function updateItemExtended(itemInfo, data, authentication, thumbnail, access, templateDictionary) {
1405
+ return new Promise((resolve, reject) => {
1406
+ const updateOptions = {
1407
+ item: itemInfo,
1408
+ params: {
1409
+ text: data || {} // AGO ignores update if `data` is empty
1410
+ },
1411
+ authentication: authentication
1412
+ };
1413
+ if (thumbnail) {
1414
+ updateOptions.params.thumbnail = thumbnail;
1415
+ }
1416
+ if ((0, trackingHelpers_1.isTrackingViewTemplate)(undefined, itemInfo) && templateDictionary) {
1417
+ updateOptions.owner = templateDictionary.locationTracking.owner;
1418
+ }
1419
+ (0, arcgis_rest_portal_1.updateItem)(updateOptions).then(result => {
1420
+ if (access && access !== "private") {
1421
+ // Set access if it is not AGOL default
1422
+ // Set the access manually since the access value in createItem appears to be ignored
1423
+ const accessOptions = {
1424
+ id: itemInfo.id,
1425
+ access: access === "public" ? "public" : "org",
1426
+ authentication: authentication
1427
+ };
1428
+ (0, arcgis_rest_portal_1.setItemAccess)(accessOptions).then(() => resolve(result), e => reject((0, generalHelpers_1.fail)(e)));
1429
+ }
1430
+ else {
1431
+ resolve(result);
1432
+ }
1433
+ }, e => reject((0, generalHelpers_1.fail)(e)));
1434
+ });
1435
+ }
1436
+ exports.updateItemExtended = updateItemExtended;
1437
+ /**
1438
+ * Update an item's base and data using a dictionary.
1439
+ *
1440
+ * @param {string} itemId The item ID
1441
+ * @param {any} templateDictionary The template dictionary
1442
+ * @param {UserSession} authentication The destination session info
1443
+ * @returns Promise resolving to successfulness of update
1444
+ */
1445
+ function updateItemTemplateFromDictionary(itemId, templateDictionary, authentication) {
1446
+ return new Promise((resolve, reject) => {
1447
+ // Fetch the items as stored in AGO
1448
+ Promise.all([
1449
+ (0, restHelpersGet_1.getItemBase)(itemId, authentication),
1450
+ (0, restHelpersGet_1.getItemDataAsJson)(itemId, authentication)
1451
+ ])
1452
+ .then(([item, data]) => {
1453
+ // Do they have any variables?
1454
+ if ((0, templatization_1.hasUnresolvedVariables)(item) || (0, templatization_1.hasUnresolvedVariables)(data)) {
1455
+ // Update if so
1456
+ const { item: updatedItem, data: updatedData } = (0, templatization_1.replaceInTemplate)({ item, data }, templateDictionary);
1457
+ _reportVariablesInItem(itemId, item.type, updatedItem, updatedData);
1458
+ return updateItemExtended(updatedItem, updatedData, authentication);
1459
+ }
1460
+ else {
1461
+ // Shortcut out if not
1462
+ return Promise.resolve({
1463
+ success: true,
1464
+ id: itemId
1465
+ });
1466
+ }
1467
+ })
1468
+ .then(result => resolve(result))
1469
+ .catch(error => reject(error));
1470
+ });
1471
+ }
1472
+ exports.updateItemTemplateFromDictionary = updateItemTemplateFromDictionary;
1473
+ /**
1474
+ * Updates the URL of an item.
1475
+ *
1476
+ * @param id AGOL id of item to update
1477
+ * @param url URL to assign to item's base section
1478
+ * @param authentication Credentials for the request
1479
+ * @returns A promise that will resolve with the item id when the item has been updated or an AGO-style JSON failure
1480
+ * response
1481
+ */
1482
+ function updateItemURL(id, url, authentication) {
1483
+ const numAttempts = 3;
1484
+ return _updateItemURL(id, url, authentication, numAttempts);
1485
+ }
1486
+ exports.updateItemURL = updateItemURL;
1487
+ // ------------------------------------------------------------------------------------------------------------------ //
1488
+ /**
1489
+ * Adds a data section to an item.
1490
+ *
1491
+ * @param itemId Id of item to receive data file
1492
+ * @param dataFile Data to be added
1493
+ * @param authentication Credentials for the request
1494
+ * @returns Promise reporting success or failure
1495
+ * @private
1496
+ */
1497
+ function _addItemDataFile(itemId, dataFile, authentication) {
1498
+ return new Promise((resolve, reject) => {
1499
+ const _addItemData = (data) => {
1500
+ addItemData(itemId, data, authentication).then(resolve, reject);
1501
+ };
1502
+ // Item data has to be submitted as text or JSON for those file types
1503
+ if (dataFile.type.startsWith("text/plain")) {
1504
+ (0, generalHelpers_1.blobToText)(dataFile).then(_addItemData, reject);
1505
+ }
1506
+ else if (dataFile.type === "application/json") {
1507
+ (0, generalHelpers_1.blobToJson)(dataFile).then(_addItemData, reject);
1508
+ }
1509
+ else {
1510
+ _addItemData(dataFile);
1511
+ }
1512
+ });
1513
+ }
1514
+ exports._addItemDataFile = _addItemDataFile;
1515
+ /**
1516
+ * Adds a metadata file to an item.
1517
+ *
1518
+ * @param itemId Id of item to receive data file
1519
+ * @param metadataFile Metadata to be added
1520
+ * @param authentication Credentials for the request
1521
+ * @returns Promise reporting success or failure
1522
+ * @private
1523
+ */
1524
+ function _addItemMetadataFile(itemId, metadataFile, authentication) {
1525
+ return new Promise((resolve, reject) => {
1526
+ const addMetadataOptions = {
1527
+ item: {
1528
+ id: itemId
1529
+ },
1530
+ params: {
1531
+ // Pass metadata in via params because item property is serialized, which discards a blob
1532
+ metadata: metadataFile
1533
+ },
1534
+ authentication: authentication
1535
+ };
1536
+ (0, arcgis_rest_portal_1.updateItem)(addMetadataOptions).then(resolve, reject);
1537
+ });
1538
+ }
1539
+ exports._addItemMetadataFile = _addItemMetadataFile;
1540
+ /**
1541
+ * Accumulates the number of relationships in a collection of layers.
1542
+ *
1543
+ * @param List of layers to examine
1544
+ * @returns The number of relationships
1545
+ * @private
1546
+ */
1547
+ function _countRelationships(layers) {
1548
+ const reducer = (accumulator, currentLayer) => accumulator +
1549
+ (currentLayer.relationships ? currentLayer.relationships.length : 0);
1550
+ return layers.reduce(reducer, 0);
1551
+ }
1552
+ exports._countRelationships = _countRelationships;
1553
+ /**
1554
+ * Gets the full definitions of the layers affiliated with a hosted service.
1555
+ *
1556
+ * @param serviceUrl URL to hosted service
1557
+ * @param layerList List of layers at that service...must contain id
1558
+ * @param authentication Credentials for the request
1559
+ * @returns A promise that will resolve with a list of the layers from the admin api
1560
+ * @private
1561
+ */
1562
+ function _getCreateServiceOptions(newItemTemplate, authentication, templateDictionary) {
1563
+ return new Promise((resolve, reject) => {
1564
+ const serviceInfo = newItemTemplate.properties;
1565
+ const folderId = templateDictionary.folderId;
1566
+ const isPortal = templateDictionary.isPortal;
1567
+ const itemId = newItemTemplate.itemId;
1568
+ (0, featureServiceHelpers_1.validateSpatialReferenceAndExtent)(serviceInfo, newItemTemplate, templateDictionary);
1569
+ const fallbackExtent = _getFallbackExtent(serviceInfo, templateDictionary);
1570
+ const params = {};
1571
+ const itemInfo = {
1572
+ title: newItemTemplate.item.title,
1573
+ name: newItemTemplate.item.name
1574
+ };
1575
+ const _item = {
1576
+ ...itemInfo,
1577
+ preserveLayerIds: true
1578
+ };
1579
+ const createOptions = {
1580
+ item: _item,
1581
+ folderId,
1582
+ params,
1583
+ authentication: authentication
1584
+ };
1585
+ createOptions.item = !(0, trackingHelpers_1.isTrackingViewTemplate)(newItemTemplate) ?
1586
+ _setItemProperties(createOptions.item, newItemTemplate, serviceInfo, params, isPortal) :
1587
+ (0, trackingHelpers_1.setTrackingOptions)(newItemTemplate, createOptions, templateDictionary);
1588
+ // project the portals extent to match that of the service
1589
+ convertExtentWithFallback(templateDictionary.organization.defaultExtent, fallbackExtent, serviceInfo.service.spatialReference, templateDictionary.organization.helperServices.geometry.url, authentication).then(extent => {
1590
+ templateDictionary[itemId].solutionExtent = extent;
1591
+ (0, featureServiceHelpers_1.setDefaultSpatialReference)(templateDictionary, itemId, extent.spatialReference);
1592
+ createOptions.item = (0, templatization_1.replaceInTemplate)(createOptions.item, templateDictionary);
1593
+ createOptions.params = (0, templatization_1.replaceInTemplate)(createOptions.params, templateDictionary);
1594
+ if (newItemTemplate.item.thumbnail) {
1595
+ // Pass thumbnail file in via params because item property is serialized, which discards a blob
1596
+ createOptions.params.thumbnail = newItemTemplate.item.thumbnail;
1597
+ }
1598
+ resolve(createOptions);
1599
+ }, e => reject((0, generalHelpers_1.fail)(e)));
1600
+ });
1601
+ }
1602
+ exports._getCreateServiceOptions = _getCreateServiceOptions;
1603
+ /**
1604
+ * When the services spatial reference does not match that of it's default extent
1605
+ * use the out SRs default extent if it exists in the templateDictionary
1606
+ * this should be set when adding a custom out wkid to the params before calling deploy
1607
+ * this will help avoid situations where the orgs default extent and default world extent
1608
+ * will not project successfully to the out SR
1609
+ *
1610
+ * @param serviceInfo the object that contains the spatial reference to evaluate
1611
+ * @param templateDictionary the template dictionary
1612
+ * @returns the extent to use as the fallback
1613
+ * @private
1614
+ */
1615
+ function _getFallbackExtent(serviceInfo, templateDictionary) {
1616
+ const serviceSR = serviceInfo.service.spatialReference;
1617
+ const serviceInfoWkid = (0, generalHelpers_1.getProp)(serviceInfo, "defaultExtent.spatialReference.wkid");
1618
+ const customDefaultExtent = (0, generalHelpers_1.getProp)(templateDictionary, "params.defaultExtent");
1619
+ return serviceInfoWkid && serviceInfoWkid === serviceSR.wkid
1620
+ ? serviceInfo.defaultExtent
1621
+ : customDefaultExtent
1622
+ ? customDefaultExtent
1623
+ : serviceInfo.defaultExtent;
1624
+ }
1625
+ exports._getFallbackExtent = _getFallbackExtent;
1626
+ /**
1627
+ * Add relationships to all layers in one call to retain fully functioning composite relationships
1628
+ *
1629
+ * @param args The IPostProcessArgs for the request(s)
1630
+ * @returns Any relationships that should be updated for the service
1631
+ * @private
1632
+ */
1633
+ function _getRelationshipUpdates(args) {
1634
+ const rels = {
1635
+ layers: []
1636
+ };
1637
+ Object.keys(args.objects).forEach((k) => {
1638
+ const obj = args.objects[k];
1639
+ /* istanbul ignore else */
1640
+ if (obj.relationships && obj.relationships.length > 0) {
1641
+ rels.layers.push({
1642
+ id: obj.id,
1643
+ relationships: obj.relationships
1644
+ });
1645
+ }
1646
+ (0, generalHelpers_1.deleteProp)(obj, "relationships");
1647
+ });
1648
+ return rels;
1649
+ }
1650
+ exports._getRelationshipUpdates = _getRelationshipUpdates;
1651
+ /**
1652
+ * Get the stored contingent values and structure them to be added to the services layers.
1653
+ *
1654
+ * @param args The IPostProcessArgs for the request(s)
1655
+ * @returns Any contingent values that should be added to the service.
1656
+ * @private
1657
+ */
1658
+ function _getContingentValuesUpdates(args) {
1659
+ const contingentValues = [];
1660
+ Object.keys(args.objects).forEach((k) => {
1661
+ const obj = args.objects[k];
1662
+ /* istanbul ignore else */
1663
+ if (obj.contingentValues) {
1664
+ contingentValues.push({
1665
+ id: obj.id,
1666
+ contingentValues: obj.contingentValues
1667
+ });
1668
+ }
1669
+ (0, generalHelpers_1.deleteProp)(obj, "contingentValues");
1670
+ });
1671
+ return contingentValues;
1672
+ }
1673
+ exports._getContingentValuesUpdates = _getContingentValuesUpdates;
1674
+ /**
1675
+ * Get refresh, add, update, or delete definition info
1676
+ *
1677
+ * @param url the base admin url for the service
1678
+ * @param id the id of the layer
1679
+ * @param obj parameters for the request
1680
+ * @param args various arguments to help support the request
1681
+ * @param type type of update the request will handle
1682
+ * @returns IUpdate that has the request url and arguments
1683
+ * @private
1684
+ */
1685
+ function _getUpdate(url, id, obj, args, type) {
1686
+ const ops = {
1687
+ delete: {
1688
+ url: (0, generalHelpers_1.checkUrlPathTermination)(url) + id + "/deleteFromDefinition",
1689
+ params: {
1690
+ deleteFromDefinition: {
1691
+ fields: obj && obj.hasOwnProperty("deleteFields") ? obj.deleteFields : []
1692
+ }
1693
+ }
1694
+ },
1695
+ update: {
1696
+ url: (0, generalHelpers_1.checkUrlPathTermination)(url) +
1697
+ (id ? `${id}/updateDefinition` : "updateDefinition"),
1698
+ params: {
1699
+ updateDefinition: obj
1700
+ }
1701
+ },
1702
+ add: {
1703
+ url: (0, generalHelpers_1.checkUrlPathTermination)(url) + "addToDefinition",
1704
+ params: {
1705
+ addToDefinition: obj
1706
+ }
1707
+ },
1708
+ refresh: {
1709
+ url: (0, generalHelpers_1.checkUrlPathTermination)(url) + "refresh",
1710
+ params: {
1711
+ f: "json"
1712
+ }
1713
+ }
1714
+ };
1715
+ return {
1716
+ url: ops[type].url,
1717
+ params: ops[type].params,
1718
+ args: args
1719
+ };
1720
+ }
1721
+ exports._getUpdate = _getUpdate;
1722
+ /**
1723
+ * Changes just the domain part of a URL to lowercase.
1724
+ *
1725
+ * @param url URL to modify
1726
+ * @return Adjusted URL
1727
+ * @see From `getServerRootUrl` in arcgis-rest-js' ArcGISIdentityManager.ts
1728
+ * @private
1729
+ */
1730
+ function _lowercaseDomain(url) {
1731
+ if (!url) {
1732
+ return url;
1733
+ }
1734
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1735
+ const [_, protocol, domainAndPath] = url.match(/(https?:\/\/)(.+)/);
1736
+ const [domain, ...path] = domainAndPath.split("/");
1737
+ // Only the domain is lowercased because in some cases an org id might be
1738
+ // in the path which cannot be lowercased.
1739
+ return `${protocol}${domain.toLowerCase()}/${path.join("/")}`;
1740
+ }
1741
+ exports._lowercaseDomain = _lowercaseDomain;
1742
+ /**
1743
+ * Checks the two main parts of an item for unresolved variables and reports any found.
1744
+ *
1745
+ * @param base Item's base section
1746
+ * @param data Item's data section
1747
+ * @private
1748
+ */
1749
+ function _reportVariablesInItem(itemId, itemType, base, data) {
1750
+ const getUnresolved = (v) => {
1751
+ return JSON.stringify(v).match(/{{.+?}}/gim);
1752
+ };
1753
+ // Provide feedback about any remaining unresolved variables
1754
+ /* istanbul ignore else */
1755
+ if (base && (0, templatization_1.hasUnresolvedVariables)(base)) {
1756
+ console.log(itemId +
1757
+ " (" +
1758
+ itemType +
1759
+ ") contains variables in base: " +
1760
+ JSON.stringify(getUnresolved(base)));
1761
+ }
1762
+ /* istanbul ignore else */
1763
+ if (data && (0, templatization_1.hasUnresolvedVariables)(data)) {
1764
+ console.log(itemId +
1765
+ " (" +
1766
+ itemType +
1767
+ ") contains variables in data: " +
1768
+ JSON.stringify(getUnresolved(data)));
1769
+ }
1770
+ }
1771
+ exports._reportVariablesInItem = _reportVariablesInItem;
1772
+ /**
1773
+ * Updates a feature service item.
1774
+ *
1775
+ * @param item Item to update
1776
+ * @param itemTemplate item template for the new item
1777
+ * @param serviceInfo Service information
1778
+ * @param params arcgis-rest-js params to update
1779
+ * @param isPortal Is the service hosted in a portal?
1780
+ * @returns Updated item
1781
+ * @private
1782
+ */
1783
+ function _setItemProperties(item, itemTemplate, serviceInfo, params, isPortal) {
1784
+ // Set the capabilities
1785
+ const portalCapabilities = [
1786
+ "Create",
1787
+ "Query",
1788
+ "Editing",
1789
+ "Update",
1790
+ "Delete",
1791
+ "Uploads",
1792
+ "Sync",
1793
+ "Extract"
1794
+ ];
1795
+ const capabilities = (0, generalHelpers_1.getProp)(serviceInfo, "service.capabilities") || (isPortal ? "" : []);
1796
+ item.capabilities = isPortal
1797
+ ? capabilities
1798
+ .split(",")
1799
+ .filter((c) => portalCapabilities.indexOf(c) > -1)
1800
+ .join(",")
1801
+ : capabilities;
1802
+ if (serviceInfo.service.capabilities) {
1803
+ serviceInfo.service.capabilities = item.capabilities;
1804
+ }
1805
+ // Handle index update for any pre-published solution items that
1806
+ // have non-unique indexes on relationship key fields
1807
+ _updateIndexesForRelationshipKeyFields(serviceInfo);
1808
+ // set create options item properties
1809
+ const keyProperties = [
1810
+ "isView",
1811
+ "sourceSchemaChangesAllowed",
1812
+ "isUpdatableView",
1813
+ "capabilities",
1814
+ "isMultiServicesView"
1815
+ ];
1816
+ const deleteKeys = ["layers", "tables"];
1817
+ /* istanbul ignore else */
1818
+ if (isPortal) {
1819
+ // removed for issue #423 causing FS to fail to create
1820
+ deleteKeys.push("adminServiceInfo");
1821
+ }
1822
+ const itemKeys = Object.keys(item);
1823
+ const serviceKeys = Object.keys(serviceInfo.service);
1824
+ serviceKeys.forEach(k => {
1825
+ /* istanbul ignore else */
1826
+ if (itemKeys.indexOf(k) === -1 && deleteKeys.indexOf(k) < 0) {
1827
+ item[k] = serviceInfo.service[k];
1828
+ // These need to be included via params otherwise...
1829
+ // addToDef calls fail when adding adminLayerInfo
1830
+ /* istanbul ignore else */
1831
+ if (serviceInfo.service.isView && keyProperties.indexOf(k) > -1) {
1832
+ params[k] = serviceInfo.service[k];
1833
+ }
1834
+ }
1835
+ });
1836
+ // Enable editor tracking on layer with related tables is not supported.
1837
+ /* istanbul ignore else */
1838
+ if (item.isMultiServicesView &&
1839
+ (0, generalHelpers_1.getProp)(item, "editorTrackingInfo.enableEditorTracking")) {
1840
+ item.editorTrackingInfo.enableEditorTracking = false;
1841
+ params["editorTrackingInfo"] = item.editorTrackingInfo;
1842
+ }
1843
+ /* istanbul ignore else */
1844
+ if (isPortal) {
1845
+ // portal will fail when initialExtent is defined but null
1846
+ // removed for issue #449 causing FS to fail to create on portal
1847
+ /* istanbul ignore else */
1848
+ if (Object.keys(item).indexOf("initialExtent") > -1 &&
1849
+ !item.initialExtent) {
1850
+ (0, generalHelpers_1.deleteProp)(item, "initialExtent");
1851
+ }
1852
+ }
1853
+ return item;
1854
+ }
1855
+ exports._setItemProperties = _setItemProperties;
1856
+ /**
1857
+ * Set isUnique as true for indexes that reference origin relationship keyFields.
1858
+ *
1859
+ * @param serviceInfo Service information
1860
+ * @private
1861
+ */
1862
+ function _updateIndexesForRelationshipKeyFields(serviceInfo) {
1863
+ const layersAndTables = (serviceInfo.layers || []).concat(serviceInfo.tables || []);
1864
+ layersAndTables.forEach(item => {
1865
+ const relationships = item.relationships;
1866
+ const indexes = item.indexes;
1867
+ /* istanbul ignore else */
1868
+ if (relationships &&
1869
+ relationships.length > 0 &&
1870
+ indexes &&
1871
+ indexes.length > 0) {
1872
+ const keyFields = relationships.reduce((acc, v) => {
1873
+ /* istanbul ignore else */
1874
+ if (v.role === "esriRelRoleOrigin" &&
1875
+ v.keyField &&
1876
+ acc.indexOf(v.keyField) < 0) {
1877
+ acc.push(v.keyField);
1878
+ }
1879
+ return acc;
1880
+ }, []);
1881
+ indexes.map(i => {
1882
+ /* istanbul ignore else */
1883
+ if (keyFields.some(k => {
1884
+ const regEx = new RegExp(`\\b${k}\\b`);
1885
+ return regEx.test(i.fields);
1886
+ })) {
1887
+ i.isUnique = true;
1888
+ }
1889
+ return i;
1890
+ });
1891
+ }
1892
+ });
1893
+ }
1894
+ exports._updateIndexesForRelationshipKeyFields = _updateIndexesForRelationshipKeyFields;
1895
+ /**
1896
+ * Updates the URL of an item.
1897
+ *
1898
+ * @param id AGOL id of item to update
1899
+ * @param url URL to assign to item's base section
1900
+ * @param authentication Credentials for the request
1901
+ * @param numAttempts Number of times to try to set the URL if AGO says that it updated the URL, but really didn't
1902
+ * @returns A promise that will resolve with the item id when the item has been updated or an AGO-style JSON failure
1903
+ * response
1904
+ * @private
1905
+ */
1906
+ function _updateItemURL(id, url, authentication, numAttempts = 1) {
1907
+ // Introduce a lag because AGO update appears to choke with rapid subsequent calls
1908
+ const msLag = 1000;
1909
+ return new Promise((resolve, reject) => {
1910
+ // Update the item's URL
1911
+ const options = { item: { id, url }, authentication: authentication };
1912
+ (0, arcgis_rest_portal_1.updateItem)(options).then(result => {
1913
+ if (!result.success) {
1914
+ reject((0, generalHelpers_1.fail)(result));
1915
+ }
1916
+ else {
1917
+ // Get the item to see if the URL really changed; we'll delay a bit before testing because AGO
1918
+ // has a timing problem with URL updates
1919
+ setTimeout(() => {
1920
+ (0, arcgis_rest_portal_1.getItem)(id, { authentication: authentication }).then(item => {
1921
+ const iBrace = item.url.indexOf("{");
1922
+ if (iBrace > -1) {
1923
+ console.warn(id + " has template variable: " + item.url.substr(iBrace));
1924
+ }
1925
+ if (url === item.url) {
1926
+ resolve(id);
1927
+ }
1928
+ else {
1929
+ // If it fails, try again if we have sufficient attempts remaining
1930
+ const errorMsg = "URL not updated for " +
1931
+ item.type +
1932
+ " " +
1933
+ item.id +
1934
+ ": " +
1935
+ item.url +
1936
+ " (" +
1937
+ numAttempts +
1938
+ ")";
1939
+ if (--numAttempts > 0) {
1940
+ _updateItemURL(id, url, authentication, numAttempts).then(resolve, reject);
1941
+ }
1942
+ else {
1943
+ console.error(id + ": " + errorMsg + "; FAILED");
1944
+ reject(errorMsg);
1945
+ }
1946
+ }
1947
+ }, e => reject((0, generalHelpers_1.fail)(e)));
1948
+ }, msLag);
1949
+ }
1950
+ }, e => reject((0, generalHelpers_1.fail)(e)));
1951
+ });
1952
+ }
1953
+ exports._updateItemURL = _updateItemURL;
1954
+ //# sourceMappingURL=restHelpers.js.map