@esri/solution-deployer 3.0.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/esm/deploySolutionItems.js +1 -1
  2. package/dist/esm/deploySolutionItems.js.map +1 -1
  3. package/package.json +13 -13
  4. package/dist/node/deploySolutionFromTemplate.d.ts +0 -48
  5. package/dist/node/deploySolutionFromTemplate.js +0 -332
  6. package/dist/node/deploySolutionFromTemplate.js.map +0 -1
  7. package/dist/node/deploySolutionItems.d.ts +0 -224
  8. package/dist/node/deploySolutionItems.js +0 -850
  9. package/dist/node/deploySolutionItems.js.map +0 -1
  10. package/dist/node/deployer.d.ts +0 -34
  11. package/dist/node/deployer.js +0 -102
  12. package/dist/node/deployer.js.map +0 -1
  13. package/dist/node/deployerUtils.d.ts +0 -47
  14. package/dist/node/deployerUtils.js +0 -124
  15. package/dist/node/deployerUtils.js.map +0 -1
  16. package/dist/node/helpers/post-process.d.ts +0 -29
  17. package/dist/node/helpers/post-process.js +0 -62
  18. package/dist/node/helpers/post-process.js.map +0 -1
  19. package/dist/node/helpers/share-templates-to-groups.d.ts +0 -24
  20. package/dist/node/helpers/share-templates-to-groups.js +0 -65
  21. package/dist/node/helpers/share-templates-to-groups.js.map +0 -1
  22. package/dist/node/helpers/sortTemplates.d.ts +0 -23
  23. package/dist/node/helpers/sortTemplates.js +0 -15
  24. package/dist/node/helpers/sortTemplates.js.map +0 -1
  25. package/dist/node/index.d.ts +0 -24
  26. package/dist/node/index.js +0 -28
  27. package/dist/node/index.js.map +0 -1
  28. package/dist/node/module-map.d.ts +0 -23
  29. package/dist/node/module-map.js +0 -195
  30. package/dist/node/module-map.js.map +0 -1
  31. package/dist/umd/deployer/src/deploySolutionFromTemplate.d.ts +0 -48
  32. package/dist/umd/deployer/src/deploySolutionItems.d.ts +0 -224
  33. package/dist/umd/deployer/src/deployer.d.ts +0 -34
  34. package/dist/umd/deployer/src/deployerUtils.d.ts +0 -47
  35. package/dist/umd/deployer/src/helpers/post-process.d.ts +0 -29
  36. package/dist/umd/deployer/src/helpers/share-templates-to-groups.d.ts +0 -24
  37. package/dist/umd/deployer/src/helpers/sortTemplates.d.ts +0 -23
  38. package/dist/umd/deployer/src/index.d.ts +0 -24
  39. package/dist/umd/deployer/src/module-map.d.ts +0 -23
  40. package/dist/umd/deployer.umd.js +0 -1710
  41. package/dist/umd/deployer.umd.js.map +0 -1
  42. package/dist/umd/deployer.umd.min.js +0 -19
  43. package/dist/umd/deployer.umd.min.js.map +0 -1
@@ -1,850 +0,0 @@
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._getGroupUpdates = exports._estimateDeploymentCost = exports._createItemFromTemplateWhenReady = exports._findExistingItem = exports._findExistingItemByKeyword = exports._updateTemplateDictionaryById = exports._handleExistingItems = exports._updateTemplateDictionaryForError = exports._setFields = exports._updateTemplateDictionary = exports._setTypekeywordForExisting = exports._useExistingItems = exports._reuseDeployedItems = exports._getViews = exports._getViewHash = exports._updateViewTemplates = exports._evaluateSharedViewSources = exports._flagPatchItemsForPostProcessing = exports.deploySolutionItems = void 0;
19
- const tslib_1 = require("tslib");
20
- /**
21
- * Manages deployment of items via the REST API.
22
- *
23
- * @module deployItems
24
- */
25
- const common = tslib_1.__importStar(require("@esri/solution-common"));
26
- const module_map_1 = require("./module-map");
27
- const UNSUPPORTED = null;
28
- // ------------------------------------------------------------------------------------------------------------------ //
29
- /**
30
- * Deploys a set of items defined by templates.
31
- *
32
- * @param portalSharingUrl Server/sharing
33
- * @param storageItemId Id of storage item
34
- * @param templates A collection of AGO item templates
35
- * @param storageAuthentication Credentials for the organization with the source items
36
- * @param templateDictionary Hash of facts: org URL, adlib replacements
37
- * @param deployedSolutionId Id of deployed Solution item
38
- * @param destinationAuthentication Credentials for the destination organization
39
- * @param options Options to tune deployment
40
- * @returns A promise that will resolve with the list of information about the created items
41
- */
42
- function deploySolutionItems(portalSharingUrl, storageItemId, templates, storageAuthentication, templateDictionary, deployedSolutionId, destinationAuthentication, options) {
43
- return new Promise((resolve, reject) => {
44
- // Prepare feedback mechanism
45
- const totalEstimatedCost = _estimateDeploymentCost(templates) + 1; // solution items, plus avoid divide by 0
46
- let percentDone = 10; // allow for previous deployment work
47
- const progressPercentStep = (99 - percentDone) / totalEstimatedCost; // leave some % for caller for wrapup
48
- const failedTemplateItemIds = [];
49
- const deployedItemIds = [];
50
- let statusOK = true;
51
- // TODO: move to separate fn
52
- const itemProgressCallback = (itemId, status, costUsed, createdItemId // supplied when status is EItemProgressStatus.Created or .Finished
53
- ) => {
54
- percentDone += progressPercentStep * costUsed;
55
- /* istanbul ignore else */
56
- if (options.progressCallback) {
57
- if (status === common.EItemProgressStatus.Finished) {
58
- const event = {
59
- event: common.SItemProgressStatus[status],
60
- data: itemId
61
- };
62
- options.progressCallback(Math.round(percentDone), options.jobId, event);
63
- }
64
- else {
65
- options.progressCallback(Math.round(percentDone), options.jobId);
66
- }
67
- }
68
- /* istanbul ignore if */
69
- if (options.consoleProgress) {
70
- console.log(Date.now(), itemId, options.jobId ?? "", common.SItemProgressStatus[status], percentDone.toFixed(0) + "%", costUsed, createdItemId ? "==> " + createdItemId : "");
71
- }
72
- if (status === common.EItemProgressStatus.Created) {
73
- deployedItemIds.push(createdItemId);
74
- }
75
- else if (status === common.EItemProgressStatus.Failed) {
76
- failedTemplateItemIds.push(itemId);
77
- console.error("Item " + itemId + " has failed");
78
- statusOK = false;
79
- }
80
- return statusOK;
81
- // ---------------------------------------------------------------------------------------------------------------
82
- };
83
- // portal does not allow views of a single source to be created at the same time
84
- if (common.getProp(templateDictionary, "organization.isPortal")) {
85
- templates = _evaluateSharedViewSources(templates);
86
- }
87
- // Create an ordered graph of the templates so that dependencies are created before the items that need them.
88
- // Because cycles are permitted, we also keep track of items that need to be patched later because their
89
- // dependencies are necessarily created after they are created.
90
- const { buildOrder, itemsToBePatched } = common.topologicallySortItems(templates);
91
- // For each item in order from no dependencies to dependent on other items,
92
- // * replace template symbols using template dictionary
93
- // * create item in destination group
94
- // * add created item's id into the template dictionary
95
- const awaitAllItems = [];
96
- const reuseItemsDef = _reuseDeployedItems(templates, options.enableItemReuse ?? false, templateDictionary, destinationAuthentication);
97
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
98
- reuseItemsDef.then(() => {
99
- const useExistingItemsDef = _useExistingItems(templates, common.getProp(templateDictionary, "params.useExisting"), templateDictionary, destinationAuthentication);
100
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
101
- useExistingItemsDef.then(() => {
102
- templates = common.setNamesAndTitles(templates, templateDictionary.solutionItemId);
103
- buildOrder.forEach((id) => {
104
- // Get the item's template out of the list of templates
105
- const template = common.findTemplateInList(templates, id);
106
- awaitAllItems.push(_createItemFromTemplateWhenReady(template, common.generateStorageFilePaths(portalSharingUrl, storageItemId, template.resources, options.storageVersion), storageAuthentication, templateDictionary, destinationAuthentication, itemProgressCallback));
107
- });
108
- // Wait until all items have been created
109
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
110
- Promise.all(awaitAllItems).then((clonedSolutionItems) => {
111
- if (failedTemplateItemIds.length === 0) {
112
- // Do we have any items to be patched (i.e., they refer to dependencies using the template id rather
113
- // than the cloned id because the item had to be created before the dependency)? Flag these items
114
- // for post processing in the list of clones.
115
- _flagPatchItemsForPostProcessing(itemsToBePatched, templateDictionary, clonedSolutionItems);
116
- resolve(clonedSolutionItems);
117
- }
118
- else {
119
- // Delete created items
120
- const progressOptions = {
121
- consoleProgress: true
122
- };
123
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
124
- common
125
- .deleteSolutionByComponents(deployedSolutionId, deployedItemIds, templates, templateDictionary, destinationAuthentication, progressOptions)
126
- .then(() => reject(common.failWithIds(failedTemplateItemIds)));
127
- }
128
- });
129
- });
130
- }, e => {
131
- console.error(e);
132
- reject(common.fail(e));
133
- });
134
- });
135
- }
136
- exports.deploySolutionItems = deploySolutionItems;
137
- /**
138
- * For each item to be patched, convert it to its cloned id and mark the item as needing post processing.
139
- *
140
- * @param itemsToBePatched List of items that need to have their dependencies patched
141
- * @param templateDictionary Hash of facts: org URL, adlib replacements
142
- * @param templates A collection of AGO item templates
143
- * @private
144
- */
145
- function _flagPatchItemsForPostProcessing(itemsToBePatched, templateDictionary, templates) {
146
- let itemIdsToBePatched = Object.keys(itemsToBePatched);
147
- /* istanbul ignore else */
148
- if (itemIdsToBePatched.length > 0) {
149
- // Replace the ids of the items to be patched (which are template ids) with their cloned versions
150
- itemIdsToBePatched = itemIdsToBePatched.map(id => templateDictionary[id].itemId);
151
- // Make sure that the items to be patched are flagged for post processing
152
- templates.forEach(item => {
153
- /* istanbul ignore else */
154
- if (itemIdsToBePatched.includes(item.id)) {
155
- item.postProcess = true;
156
- }
157
- });
158
- }
159
- }
160
- exports._flagPatchItemsForPostProcessing = _flagPatchItemsForPostProcessing;
161
- /**
162
- * Portal does not allow views of a single source to be created at the same time.
163
- *
164
- * Update view templates with an array of other view template ids that it should wait on.
165
- *
166
- * @param templates a collection of AGO item templates
167
- *
168
- * @returns An updated array of item templates
169
- * @private
170
- */
171
- function _evaluateSharedViewSources(templates) {
172
- // update the templates so we can defer the deployment when more than one view shares the same source
173
- // these are not classic dependencies but are in some ways similar
174
- const views = _getViews(templates);
175
- _updateViewTemplates(templates, views);
176
- const viewHash = _getViewHash(views);
177
- let processed = [];
178
- const visited = [];
179
- Object.keys(viewHash).forEach(k => {
180
- const _views = viewHash[k];
181
- _views.forEach(cv => {
182
- const template = common.findTemplateInList(templates, cv);
183
- const syncViews = common.getProp(template, "properties.syncViews");
184
- /* istanbul ignore else */
185
- if (visited.indexOf(template.itemId) > -1) {
186
- processed = processed.concat(syncViews);
187
- }
188
- /* istanbul ignore else */
189
- if (syncViews && syncViews.length > 0) {
190
- // when a view has multiple dependencies we need to retain the syncViews if they have been set already...
191
- common.setProp(template, "properties.syncViews", common.cloneObject(processed));
192
- }
193
- /* istanbul ignore else */
194
- if (processed.indexOf(cv) < 0) {
195
- processed.push(cv);
196
- }
197
- /* istanbul ignore else */
198
- if (visited.indexOf(template.itemId) < 0) {
199
- visited.push(template.itemId);
200
- }
201
- });
202
- processed = [];
203
- });
204
- return templates;
205
- }
206
- exports._evaluateSharedViewSources = _evaluateSharedViewSources;
207
- /**
208
- * Add a syncViews array to each template that will hold all other view ids that
209
- * have the same FS dependency.
210
- * These arrays will be processed later to only contain ids that each view will need to wait on.
211
- *
212
- * @param templates a collection of AGO item templates
213
- * @param views an array of view template details
214
- *
215
- * @returns An updated array of item templates
216
- * @private
217
- */
218
- function _updateViewTemplates(templates, views) {
219
- views.forEach(v => {
220
- v.dependencies.forEach((id) => {
221
- templates = templates.map(t => {
222
- /* istanbul ignore else */
223
- if (common.getProp(t, "properties.service.isView") &&
224
- t.dependencies.indexOf(id) > -1 &&
225
- t.itemId !== v.id) {
226
- /* istanbul ignore else */
227
- if (!Array.isArray(t.properties.syncViews)) {
228
- t.properties.syncViews = [];
229
- }
230
- /* istanbul ignore else */
231
- if (t.properties.syncViews.indexOf(v.id) < 0) {
232
- t.properties.syncViews.push(v.id);
233
- }
234
- }
235
- return t;
236
- });
237
- });
238
- });
239
- return templates;
240
- }
241
- exports._updateViewTemplates = _updateViewTemplates;
242
- /**
243
- * Get all view templates from the source templates collection
244
- *
245
- * @param views A collection of view ID and dependencies
246
- *
247
- * @returns an array of objects with the source FS id as the key and a list of views that are
248
- * dependant upon it
249
- *
250
- * @private
251
- */
252
- function _getViewHash(views) {
253
- const viewHash = {};
254
- views.forEach(v => {
255
- v.dependencies.forEach((d) => {
256
- /* istanbul ignore else */
257
- if (Object.keys(viewHash).indexOf(d) < 0) {
258
- viewHash[d] = [v.id];
259
- }
260
- else if (viewHash[d].indexOf(v.id) < 0) {
261
- viewHash[d].push(v.id);
262
- }
263
- });
264
- });
265
- return viewHash;
266
- }
267
- exports._getViewHash = _getViewHash;
268
- /**
269
- * Get all view templates from the source templates collection
270
- *
271
- * @param templates A collection of AGO item templates
272
- *
273
- * @returns an array with the view id and its dependencies
274
- *
275
- * @private
276
- */
277
- function _getViews(templates) {
278
- return templates.reduce((acc, v) => {
279
- /* istanbul ignore else */
280
- if (common.getProp(v, "properties.service.isView")) {
281
- acc.push({
282
- id: v.itemId,
283
- dependencies: v.dependencies
284
- });
285
- }
286
- return acc;
287
- }, []);
288
- }
289
- exports._getViews = _getViews;
290
- /**
291
- * Search for existing items and update the templateDictionary with key details
292
- *
293
- * @param templates A collection of AGO item templates
294
- * @param reuseItems Option to search for existing items
295
- * @param templateDictionary Hash of facts: org URL, adlib replacements, deferreds for dependencies
296
- * @param authentication Credentials for the requests
297
- *
298
- * @returns A Promise that will resolve once existing items have been evaluated
299
- *
300
- * @private
301
- */
302
- function _reuseDeployedItems(templates, reuseItems, templateDictionary, authentication) {
303
- return new Promise((resolve, reject) => {
304
- if (reuseItems) {
305
- const findItemsByKeywordResponse = _findExistingItemByKeyword(templates, templateDictionary, authentication);
306
- const existingItemsByKeyword = findItemsByKeywordResponse.existingItemsDefs;
307
- const existingItemInfos = findItemsByKeywordResponse.existingItemInfos;
308
- Promise.all(existingItemsByKeyword).then((existingItemsByKeywordResponse) => {
309
- const findExistingItemsByTag = _handleExistingItems(existingItemsByKeywordResponse, existingItemInfos, templateDictionary, authentication, true);
310
- const existingItemsByTag = findExistingItemsByTag.existingItemsDefs;
311
- const existingItemInfosByTag = findExistingItemsByTag.existingItemInfos;
312
- Promise.all(existingItemsByTag).then(existingItemsByTagResponse => {
313
- _handleExistingItems(existingItemsByTagResponse, existingItemInfosByTag, templateDictionary, authentication, false);
314
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
315
- _updateTemplateDictionary(templates, templateDictionary, authentication).then(resolve);
316
- }, e => reject(common.fail(e)));
317
- }, e => reject(common.fail(e)));
318
- }
319
- else {
320
- resolve(null);
321
- }
322
- });
323
- }
324
- exports._reuseDeployedItems = _reuseDeployedItems;
325
- /**
326
- * Search for existing items and update the templateDictionary with key details
327
- *
328
- * Subtle difference between _reuseDeployedItems and _useExistingItems
329
- * _reuseDeployedItems: will search all existing items based on specific type keywords
330
- * that would have been added by a previous deployment
331
- * _useExistingItems: will search for an existing item that the user provided
332
- * the item id for while configuring in the deployment app.
333
- * This type of item would not necessarily have been laid down by a previous deployment and
334
- * can thus not expect that it will have the type keywords
335
- *
336
- * @param templates A collection of AGO item templates
337
- * @param useExisting Option to search for existing items
338
- * @param templateDictionary Hash of facts: org URL, adlib replacements, deferreds for dependencies
339
- * @param authentication Credentials for the requests
340
- *
341
- * @returns A Promise that will resolve once existing items have been evaluated
342
- *
343
- * @private
344
- */
345
- function _useExistingItems(templates, useExisting, templateDictionary, authentication) {
346
- return new Promise(resolve => {
347
- if (useExisting) {
348
- const itemDefs = [];
349
- const sourceIdHash = {};
350
- const itemIds = [];
351
- Object.keys(templateDictionary.params).forEach(k => {
352
- const v = templateDictionary.params[k];
353
- /* istanbul ignore else */
354
- if (v.itemId && /[0-9A-F]{32}/i.test(k)) {
355
- _updateTemplateDictionaryById(templateDictionary, k, v.itemId, v);
356
- // need to check and set the typeKeyword if it doesn't exist on this service yet
357
- // when the user has passed in an itemId that does not come from a previous deployment
358
- itemDefs.push(common.getItemBase(v.itemId, authentication));
359
- sourceIdHash[v.itemId] = k;
360
- /* istanbul ignore else */
361
- if (itemIds.indexOf(k) < 0) {
362
- itemIds.push(k);
363
- }
364
- }
365
- });
366
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
367
- _setTypekeywordForExisting(itemDefs, sourceIdHash, authentication).then(() => {
368
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
369
- _updateTemplateDictionary(itemIds.map(id => common.getTemplateById(templates, id)), templateDictionary, authentication).then(resolve);
370
- });
371
- }
372
- else {
373
- resolve(null);
374
- }
375
- });
376
- }
377
- exports._useExistingItems = _useExistingItems;
378
- /**
379
- * Verify if the existing item has the source-<itemId> typeKeyword and set it if not
380
- * This allows items that did not come from deployment to be found for reuse after they
381
- * have been used once via a custom itemId param
382
- *
383
- * @param itemDefs
384
- * @param sourceIdHash key value pairs..actual itemId is the key and the source itemId is the value
385
- * @param authentication credentials for the requests
386
- *
387
- * @returns a promise to indicate when the requests are complete
388
- * @private
389
- */
390
- function _setTypekeywordForExisting(itemDefs, sourceIdHash, authentication) {
391
- return new Promise(resolve => {
392
- if (itemDefs.length > 0) {
393
- Promise.all(itemDefs).then(results => {
394
- const itemUpdateDefs = [];
395
- results.forEach(result => {
396
- const sourceId = sourceIdHash[result.id];
397
- /* istanbul ignore else */
398
- if (result && sourceId && result.typeKeywords) {
399
- const sourceKeyword = `source-${sourceId}`;
400
- const typeKeywords = result.typeKeywords;
401
- /* istanbul ignore else */
402
- if (typeKeywords.indexOf(sourceKeyword) < 0) {
403
- typeKeywords.push(sourceKeyword);
404
- const itemUpdate = { id: result.id, typeKeywords };
405
- itemUpdateDefs.push(common.updateItem(itemUpdate, authentication));
406
- }
407
- }
408
- });
409
- // wait for updates to finish before we resolve
410
- if (itemUpdateDefs.length > 0) {
411
- Promise.all(itemUpdateDefs).then(resolve, () => resolve(undefined));
412
- }
413
- else {
414
- resolve(undefined);
415
- }
416
- }, () => resolve(undefined));
417
- }
418
- else {
419
- resolve(undefined);
420
- }
421
- });
422
- }
423
- exports._setTypekeywordForExisting = _setTypekeywordForExisting;
424
- /**
425
- * Update the templateDictionary with key details by item type
426
- *
427
- * @param templates A collection of AGO item templates
428
- * @param templateDictionary Hash of facts: org URL, adlib replacements, deferreds for dependencies
429
- *
430
- * @private
431
- */
432
- function _updateTemplateDictionary(templates, templateDictionary, authentication) {
433
- return new Promise(resolve => {
434
- const defs = [];
435
- const urls = [];
436
- const types = [];
437
- const ids = [];
438
- templates.forEach(t => {
439
- const templateInfo = templateDictionary[t.itemId];
440
- /* istanbul ignore else */
441
- if (templateInfo && templateInfo.url && templateInfo.itemId) {
442
- /* istanbul ignore else */
443
- if (t.item.type === "Feature Service") {
444
- const enterpriseIDMapping = common.getProp(templateDictionary, `params.${t.itemId}.enterpriseIDMapping`);
445
- Object.assign(templateDictionary[t.itemId], common.getLayerSettings(common.getLayersAndTables(t), templateInfo.url, templateInfo.itemId, enterpriseIDMapping));
446
- // if the service has veiws keep track of the fields so we can use them to
447
- // compare with the view fields
448
- /* istanbul ignore else */
449
- if (common.getProp(t, "properties.service.hasViews")) {
450
- common._updateTemplateDictionaryFields(t, templateDictionary, false);
451
- }
452
- }
453
- // for fs query with its url...for non fs query the item
454
- // this is to verify situations where we have a stale search index that will
455
- // say some items exist when they don't really exist
456
- // searching the services url or with the item id will return an error when this condition occurs
457
- /* istanbul ignore else */
458
- if (urls.indexOf(templateInfo.url) < 0) {
459
- defs.push(t.item.type === "Feature Service"
460
- ? common.rest_request(templateInfo.url, { authentication })
461
- : common.getItemBase(templateInfo.itemId, authentication));
462
- urls.push(templateInfo.url);
463
- types.push(t.item.type);
464
- ids.push(templateInfo.itemId);
465
- }
466
- }
467
- });
468
- if (defs.length > 0) {
469
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
470
- Promise.all(defs.map(p => p.catch(e => e))).then(results => {
471
- /* istanbul ignore else */
472
- if (Array.isArray(results) && results.length > 0) {
473
- const fieldDefs = [];
474
- results.forEach((r, i) => {
475
- // a feature service result will contain a serviceItemId if it was successfully fetched
476
- if (r.serviceItemId && types[i] === "Feature Service") {
477
- Object.keys(templateDictionary).forEach(k => {
478
- const v = templateDictionary[k];
479
- /* istanbul ignore else */
480
- if (v.itemId && v.itemId === r.serviceItemId) {
481
- common.setDefaultSpatialReference(templateDictionary, k, r.spatialReference);
482
- // keep the extent values from these responses as well
483
- common.setCreateProp(templateDictionary, `${k}.defaultExtent`, r.fullExtent || r.initialExtent);
484
- const layerIds = (r.layers || []).map((l) => l.id);
485
- const tablesIds = (r.tables || []).map((t) => t.id);
486
- fieldDefs.push(common.getExistingLayersAndTables(urls[i], layerIds.concat(tablesIds), authentication));
487
- }
488
- });
489
- }
490
- else {
491
- /* istanbul ignore else */
492
- if (types[i] === "Feature Service" ||
493
- common.getProp(r, "response.error")) {
494
- // if an error is returned we need to clean up the templateDictionary
495
- templateDictionary = _updateTemplateDictionaryForError(templateDictionary, ids[i]);
496
- }
497
- }
498
- });
499
- if (fieldDefs.length > 0) {
500
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
501
- Promise.all(fieldDefs).then(layerTableResult => {
502
- layerTableResult.forEach(l => {
503
- l.forEach((ll) => {
504
- Object.keys(templateDictionary).forEach(k => {
505
- /* istanbul ignore else */
506
- if (templateDictionary[k].itemId === ll.serviceItemId) {
507
- let sourceId = "";
508
- Object.keys(templateDictionary).some(_k => {
509
- /* istanbul ignore else */
510
- if (templateDictionary[_k].itemId === ll.serviceItemId) {
511
- sourceId = _k;
512
- return true;
513
- }
514
- });
515
- const enterpriseIDMapping = common.getProp(templateDictionary, `params.${sourceId}.enterpriseIDMapping`);
516
- if (enterpriseIDMapping) {
517
- Object.keys(enterpriseIDMapping).forEach(id => {
518
- if (enterpriseIDMapping[id].toString() ===
519
- ll.id.toString()) {
520
- _setFields(templateDictionary, k, id, ll.fields);
521
- }
522
- });
523
- }
524
- else {
525
- _setFields(templateDictionary, k, ll.id, ll.fields);
526
- }
527
- }
528
- });
529
- });
530
- });
531
- resolve(null);
532
- });
533
- }
534
- else {
535
- resolve(null);
536
- }
537
- }
538
- else {
539
- resolve(null);
540
- }
541
- });
542
- }
543
- else {
544
- resolve(null);
545
- }
546
- });
547
- }
548
- exports._updateTemplateDictionary = _updateTemplateDictionary;
549
- /**
550
- * Add the fields from the source layer to the template dictionary for any required replacements
551
- *
552
- * @param templateDictionary Hash of facts: org URL, adlib replacements, deferreds for dependencies
553
- * @param itemId the id for the item
554
- * @param layerId the id for the layer
555
- * @param fields the fields to transfer
556
- *
557
- * @private
558
- */
559
- function _setFields(templateDictionary, itemId, layerId, fields) {
560
- const layerInfo = common.getProp(templateDictionary, `${itemId}.layer${layerId}`);
561
- /* istanbul ignore else */
562
- if (layerInfo && fields) {
563
- layerInfo.fields = fields;
564
- }
565
- }
566
- exports._setFields = _setFields;
567
- /**
568
- * In some cases an item id search will return a stale item reference
569
- * it will subsequently fail when we try to fetch the underlying service.
570
- *
571
- * We need to remove the item info that has been added to the template dictionary
572
- * and treat the item as we do other items that don't already exist on deployment.
573
- *
574
- * @param result the service request result
575
- * @param templateDictionary Hash of facts: org URL, adlib replacements, deferreds for dependencies
576
- *
577
- * @private
578
- */
579
- function _updateTemplateDictionaryForError(templateDictionary, itemId) {
580
- /* istanbul ignore else */
581
- if (itemId) {
582
- let removeKey = "";
583
- Object.keys(templateDictionary).some(k => {
584
- /* istanbul ignore else */
585
- if (templateDictionary[k].itemId === itemId) {
586
- removeKey = k;
587
- return true;
588
- }
589
- });
590
- /* istanbul ignore else */
591
- if (removeKey !== "") {
592
- delete templateDictionary[removeKey];
593
- }
594
- }
595
- return templateDictionary;
596
- }
597
- exports._updateTemplateDictionaryForError = _updateTemplateDictionaryForError;
598
- /**
599
- * Optionally search by tags and then update the templateDictionary based on the search results
600
- *
601
- * @param existingItemsResponse response object from search by typeKeyword and type
602
- * @param existingItemIds list of the template ids we have queried
603
- * @param templateDictionary Hash of facts: org URL, adlib replacements, deferreds for dependencies
604
- * @param authentication Credentials for the request
605
- * @param addTagQuery Boolean to indicate if a search by tag should happen
606
- * @returns IFindExistingItemsResponse object with promise that will resolve with an array of results
607
- * and an array of item ids
608
- * @private
609
- */
610
- function _handleExistingItems(existingItemsResponse, existingItemInfos, templateDictionary, authentication, addTagQuery) {
611
- // if items are not found by type keyword search by tag
612
- const existingItemsByTag = [Promise.resolve(null)];
613
- const existingItemInfosByTag = [undefined];
614
- /* istanbul ignore else */
615
- if (existingItemsResponse && Array.isArray(existingItemsResponse)) {
616
- existingItemsResponse.forEach((existingItem, i) => {
617
- /* istanbul ignore else */
618
- if (Array.isArray(existingItem?.results)) {
619
- let result;
620
- const results = existingItem.results;
621
- if (results.length === 1) {
622
- result = results[0];
623
- }
624
- else if (results.length > 1) {
625
- result = results.reduce((a, b) => a.created > b.created ? a : b);
626
- }
627
- else {
628
- if (addTagQuery && existingItemInfos[i]) {
629
- const itemInfo = existingItemInfos[i];
630
- const tagQuery = `tags:source-${itemInfo.itemId} type:${itemInfo.type} owner:${templateDictionary.user.username}`;
631
- existingItemsByTag.push(_findExistingItem(tagQuery, authentication));
632
- existingItemInfosByTag.push(existingItemInfos[i]);
633
- }
634
- }
635
- if (result) {
636
- const sourceId = existingItemInfos[i].itemId;
637
- /* istanbul ignore else */
638
- if (sourceId) {
639
- _updateTemplateDictionaryById(templateDictionary, sourceId, result.id, result);
640
- }
641
- }
642
- }
643
- });
644
- }
645
- return {
646
- existingItemsDefs: existingItemsByTag,
647
- existingItemInfos: existingItemInfosByTag
648
- };
649
- }
650
- exports._handleExistingItems = _handleExistingItems;
651
- //???
652
- function _updateTemplateDictionaryById(templateDictionary, sourceId, itemId, v) {
653
- templateDictionary[sourceId] = Object.assign(templateDictionary[sourceId] || {}, {
654
- def: Promise.resolve(common.generateEmptyCreationResponse(v.type, itemId)),
655
- itemId,
656
- name: v.name,
657
- title: v.title,
658
- url: v.url
659
- });
660
- }
661
- exports._updateTemplateDictionaryById = _updateTemplateDictionaryById;
662
- /**
663
- * Search items based on user query
664
- *
665
- * @param templates Templates to examine
666
- * @param templateDictionary Hash of facts: org URL, adlib replacements, deferreds for dependencies
667
- * @param authentication Credentials for the request
668
- * @returns IFindExistingItemsResponse object with promise that will resolve with an array of results
669
- * and an array of item ids
670
- * @private
671
- */
672
- function _findExistingItemByKeyword(templates, templateDictionary, authentication) {
673
- const existingItemsDefs = [];
674
- const existingItemInfos = [];
675
- templates.forEach(template => {
676
- if (template.item.type === "Group") {
677
- const userGroups = templateDictionary.user?.groups;
678
- /* istanbul ignore else */
679
- if (Array.isArray(userGroups)) {
680
- existingItemsDefs.push(Promise.resolve({
681
- results: userGroups
682
- .filter(g => g.tags.indexOf(`source-${template.itemId}`) > -1 || g.typeKeywords.indexOf(`source-${template.itemId}`) > -1)
683
- .map(g => {
684
- g.type = "Group";
685
- return g;
686
- }),
687
- sourceId: template.itemId
688
- }));
689
- }
690
- }
691
- else {
692
- existingItemsDefs.push(_findExistingItem(`typekeywords:source-${template.itemId} type:${template.item.type} owner:${templateDictionary.user.username}`, authentication));
693
- }
694
- existingItemInfos.push({
695
- itemId: template.itemId,
696
- type: template.item.type
697
- });
698
- });
699
- return {
700
- existingItemsDefs,
701
- existingItemInfos
702
- };
703
- }
704
- exports._findExistingItemByKeyword = _findExistingItemByKeyword;
705
- /**
706
- * Search items based on user query
707
- *
708
- * @param query Query string to use
709
- * @param authentication Credentials for the request
710
- * @returns A promise that will resolve with an array of results
711
- * @private
712
- */
713
- function _findExistingItem(query, authentication) {
714
- const searchOptions = {
715
- q: query,
716
- authentication: authentication,
717
- pagingParam: { start: 1, num: 100 }
718
- };
719
- return common.searchItems(searchOptions);
720
- }
721
- exports._findExistingItem = _findExistingItem;
722
- /**
723
- * Creates an item from a template once the item's dependencies have been created.
724
- *
725
- * @param template Template of item to deploy
726
- * @param resourceFilePaths URL, folder, and filename for each item resource/metadata/thumbnail
727
- * @param templateDictionary Hash of facts: org URL, adlib replacements, deferreds for dependencies
728
- * @param userSession Options for the request
729
- * @param itemProgressCallback Function for reporting progress updates from type-specific template handlers
730
- * @returns A promise that will resolve with the id of the deployed item (which is simply returned if it's
731
- * already in the templates list
732
- * @private
733
- */
734
- function _createItemFromTemplateWhenReady(template, resourceFilePaths, storageAuthentication, templateDictionary, destinationAuthentication, itemProgressCallback) {
735
- // ensure this is present
736
- template.dependencies = template.dependencies || [];
737
- // if there is no entry in the templateDictionary
738
- // or if we have a basic entry without the deferred request for its creation, add it
739
- if (!templateDictionary.hasOwnProperty(template.itemId) ||
740
- !common.getProp(templateDictionary[template.itemId], "def")) {
741
- let createResponse;
742
- let statusCode = common.EItemProgressStatus.Unknown;
743
- let itemHandler;
744
- templateDictionary[template.itemId] =
745
- templateDictionary[template.itemId] || {};
746
- // Save the deferred for the use of items that depend on this item being created first
747
- templateDictionary[template.itemId].def = new Promise(resolve => {
748
- // Wait until all of the item's dependencies are deployed
749
- const _awaitDependencies = template.dependencies.reduce((acc, id) => {
750
- const def = common.getProp(templateDictionary, `${id}.def`);
751
- // can't use maybePush as that clones the object, which does not work for Promises
752
- /* istanbul ignore else */
753
- if (def) {
754
- acc.push(def);
755
- }
756
- return acc;
757
- }, []);
758
- const syncViews = common.getProp(template, "properties.syncViews");
759
- const awaitDependencies = syncViews && syncViews.length > 0
760
- ? syncViews.reduce((acc, v) => {
761
- const def = common.getProp(templateDictionary, `${v}.def`);
762
- /* istanbul ignore else */
763
- if (def) {
764
- acc.push(def);
765
- }
766
- return acc;
767
- }, _awaitDependencies)
768
- : _awaitDependencies;
769
- Promise.all(awaitDependencies)
770
- .then(() => {
771
- // Find the conversion handler for this item type
772
- const templateType = template.type;
773
- itemHandler = module_map_1.moduleMap[templateType];
774
- if (!itemHandler || itemHandler === UNSUPPORTED) {
775
- if (itemHandler === UNSUPPORTED) {
776
- statusCode = common.EItemProgressStatus.Ignored;
777
- throw new Error();
778
- }
779
- else {
780
- statusCode = common.EItemProgressStatus.Failed;
781
- throw new Error();
782
- }
783
- }
784
- // Get the item's thumbnail
785
- return common.getThumbnailFromStorageItem(storageAuthentication, resourceFilePaths);
786
- })
787
- .then(thumbnail => {
788
- template.item.thumbnail = thumbnail;
789
- // Delegate the creation of the item to the handler
790
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
791
- return itemHandler.createItemFromTemplate(template, templateDictionary, destinationAuthentication, itemProgressCallback);
792
- })
793
- .then((response) => {
794
- if (response.id === "") {
795
- statusCode = common.EItemProgressStatus.Failed;
796
- throw new Error("handled"); // fails to create item
797
- }
798
- /* istanbul ignore else */
799
- createResponse = response;
800
- if (createResponse.item.item.url) {
801
- common.setCreateProp(templateDictionary, template.itemId + ".url", createResponse.item.item.url);
802
- }
803
- if (resourceFilePaths.length > 0) {
804
- // Copy resources, metadata, form
805
- return common.copyFilesFromStorageItem(storageAuthentication, resourceFilePaths, templateDictionary.folderId, createResponse.id, destinationAuthentication, createResponse.item);
806
- }
807
- else {
808
- return Promise.resolve(null);
809
- }
810
- })
811
- .then(() => {
812
- resolve(createResponse);
813
- })
814
- .catch(error => {
815
- if (!error || error.message !== "handled") {
816
- itemProgressCallback(template.itemId, statusCode === common.EItemProgressStatus.Unknown
817
- ? common.EItemProgressStatus.Failed
818
- : statusCode, 0);
819
- }
820
- // Item type not supported or fails to get item dependencies
821
- resolve(common.generateEmptyCreationResponse(template.type));
822
- });
823
- });
824
- }
825
- return templateDictionary[template.itemId].def;
826
- }
827
- exports._createItemFromTemplateWhenReady = _createItemFromTemplateWhenReady;
828
- /**
829
- * Accumulates the estimated deployment cost of a set of templates.
830
- *
831
- * @param templates Templates to examine
832
- * @returns Sum of estimated deployment costs
833
- * @private
834
- */
835
- function _estimateDeploymentCost(templates) {
836
- return templates.reduce((accumulatedEstimatedCost, template) => {
837
- return (accumulatedEstimatedCost + (template.estimatedDeploymentCostFactor || 1));
838
- }, 0);
839
- }
840
- exports._estimateDeploymentCost = _estimateDeploymentCost;
841
- //???
842
- // TODO: Return a Promise vs array of promises
843
- function _getGroupUpdates(template, authentication, templateDictionary) {
844
- const groups = template.groups || [];
845
- return groups.map((sourceGroupId) => {
846
- return common.shareItem(templateDictionary[sourceGroupId].itemId, template.itemId, authentication, common.isTrackingViewTemplate(template) ? templateDictionary.locationTracking.owner : undefined);
847
- });
848
- }
849
- exports._getGroupUpdates = _getGroupUpdates;
850
- //# sourceMappingURL=deploySolutionItems.js.map