@pnp/cli-microsoft365 6.8.0-beta.74dea8a → 6.8.0-beta.85a1ca9

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 (80) hide show
  1. package/dist/Command.js +6 -0
  2. package/dist/chili/chili.js +298 -0
  3. package/dist/chili/index.js +20 -0
  4. package/dist/cli/Cli.js +2 -2
  5. package/dist/m365/app/commands/permission/permission-add.js +279 -0
  6. package/dist/m365/app/commands.js +1 -0
  7. package/dist/m365/commands/commands.js +1 -0
  8. package/dist/m365/commands/setup.js +180 -0
  9. package/dist/m365/commands/setupPresets.js +25 -0
  10. package/dist/m365/spfx/commands/project/project-upgrade/upgrade-1.15.2.js +2 -0
  11. package/dist/m365/spfx/commands/spfx-doctor.js +14 -30
  12. package/dist/m365/spo/commands/applicationcustomizer/applicationcustomizer-remove.js +146 -0
  13. package/dist/m365/spo/commands/listitem/listitem-batch-set.js +308 -0
  14. package/dist/m365/spo/commands/page/page-section-add.js +2 -3
  15. package/dist/m365/spo/commands/tenant/tenant-applicationcustomizer-get.js +30 -39
  16. package/dist/m365/spo/commands/tenant/tenant-applicationcustomizer-list.js +47 -0
  17. package/dist/m365/spo/commands/tenant/tenant-applicationcustomizer-remove.js +151 -0
  18. package/dist/m365/spo/commands/tenant/tenant-commandset-remove.js +152 -0
  19. package/dist/m365/spo/commands/tenant/tenant-commandset-set.js +203 -0
  20. package/dist/m365/spo/commands.js +6 -0
  21. package/dist/utils/formatting.js +35 -11
  22. package/dist/utils/pid.js +5 -0
  23. package/docs/docs/cmd/app/permission/permission-add.md +53 -0
  24. package/docs/docs/cmd/flow/environment/environment-list.md +18 -0
  25. package/docs/docs/cmd/flow/flow-get.md +20 -0
  26. package/docs/docs/cmd/flow/flow-list.md +17 -0
  27. package/docs/docs/cmd/planner/plan/plan-get.md +1 -1
  28. package/docs/docs/cmd/planner/plan/plan-list.md +1 -1
  29. package/docs/docs/cmd/planner/roster/roster-add.md +2 -1
  30. package/docs/docs/cmd/planner/roster/roster-get.md +1 -1
  31. package/docs/docs/cmd/planner/roster/roster-remove.md +2 -1
  32. package/docs/docs/cmd/planner/task/task-set.md +1 -1
  33. package/docs/docs/cmd/purview/retentionevent/retentionevent-add.md +6 -7
  34. package/docs/docs/cmd/purview/retentionevent/retentionevent-get.md +6 -7
  35. package/docs/docs/cmd/purview/retentionevent/retentionevent-list.md +4 -4
  36. package/docs/docs/cmd/purview/retentionevent/retentionevent-remove.md +4 -4
  37. package/docs/docs/cmd/purview/retentioneventtype/retentioneventtype-add.md +10 -10
  38. package/docs/docs/cmd/purview/retentioneventtype/retentioneventtype-get.md +11 -11
  39. package/docs/docs/cmd/purview/retentioneventtype/retentioneventtype-list.md +10 -10
  40. package/docs/docs/cmd/purview/retentioneventtype/retentioneventtype-remove.md +10 -10
  41. package/docs/docs/cmd/purview/retentioneventtype/retentioneventtype-set.md +10 -10
  42. package/docs/docs/cmd/purview/retentionlabel/retentionlabel-add.md +12 -12
  43. package/docs/docs/cmd/purview/retentionlabel/retentionlabel-get.md +8 -9
  44. package/docs/docs/cmd/purview/retentionlabel/retentionlabel-list.md +8 -9
  45. package/docs/docs/cmd/purview/retentionlabel/retentionlabel-remove.md +8 -8
  46. package/docs/docs/cmd/purview/retentionlabel/retentionlabel-set.md +8 -8
  47. package/docs/docs/cmd/setup.md +86 -0
  48. package/docs/docs/cmd/spo/applicationcustomizer/applicationcustomizer-add.md +1 -1
  49. package/docs/docs/cmd/spo/applicationcustomizer/applicationcustomizer-remove.md +77 -0
  50. package/docs/docs/cmd/spo/commandset/commandset-set.md +1 -1
  51. package/docs/docs/cmd/spo/contenttype/contenttype-set.md +2 -2
  52. package/docs/docs/cmd/spo/customaction/customaction-add.md +1 -1
  53. package/docs/docs/cmd/spo/customaction/customaction-set.md +1 -1
  54. package/docs/docs/cmd/spo/folder/folder-copy.md +1 -1
  55. package/docs/docs/cmd/spo/listitem/listitem-batch-set.md +67 -0
  56. package/docs/docs/cmd/spo/tenant/tenant-applicationcustomizer-add.md +1 -1
  57. package/docs/docs/cmd/spo/tenant/tenant-applicationcustomizer-list.md +103 -0
  58. package/docs/docs/cmd/spo/tenant/tenant-applicationcustomizer-remove.md +49 -0
  59. package/docs/docs/cmd/spo/tenant/tenant-commandset-remove.md +49 -0
  60. package/docs/docs/cmd/spo/tenant/tenant-commandset-set.md +57 -0
  61. package/docs/docs/cmd/teams/tab/tab-remove.md +1 -1
  62. package/docs/docs/cmd/version.md +1 -1
  63. package/docs/docs/cmd/yammer/group/group-list.md +42 -0
  64. package/docs/docs/cmd/yammer/message/message-add.md +32 -0
  65. package/docs/docs/cmd/yammer/message/message-get.md +32 -0
  66. package/docs/docs/cmd/yammer/message/message-list.md +34 -0
  67. package/docs/docs/cmd/yammer/network/network-list.md +70 -0
  68. package/docs/docs/cmd/yammer/report/report-activitycounts.md +7 -0
  69. package/docs/docs/cmd/yammer/report/report-activityusercounts.md +7 -0
  70. package/docs/docs/cmd/yammer/report/report-activityuserdetail.md +7 -0
  71. package/docs/docs/cmd/yammer/report/report-deviceusagedistributionusercounts.md +7 -0
  72. package/docs/docs/cmd/yammer/report/report-deviceusageusercounts.md +7 -0
  73. package/docs/docs/cmd/yammer/report/report-deviceusageuserdetail.md +7 -0
  74. package/docs/docs/cmd/yammer/report/report-groupsactivitycounts.md +7 -0
  75. package/docs/docs/cmd/yammer/report/report-groupsactivitydetail.md +7 -0
  76. package/docs/docs/cmd/yammer/report/report-groupsactivitygroupcounts.md +7 -0
  77. package/docs/docs/cmd/yammer/user/user-get.md +55 -0
  78. package/docs/docs/cmd/yammer/user/user-list.md +55 -0
  79. package/docs/docs/cmd/yammer/yammer-search.md +15 -3
  80. package/package.json +2 -1
package/dist/Command.js CHANGED
@@ -420,6 +420,12 @@ class Command {
420
420
  return;
421
421
  }
422
422
  const lowerCaseValue = value.toLowerCase().trim();
423
+ if (lowerCaseValue === '@meid' || lowerCaseValue === '@meusername') {
424
+ const isAppOnlyAccessToken = accessToken_1.accessToken.isAppOnlyAccessToken(Auth_1.default.service.accessTokens[Auth_1.default.defaultResource].accessToken);
425
+ if (isAppOnlyAccessToken) {
426
+ throw `It's not possible to use ${value} with application permissions`;
427
+ }
428
+ }
423
429
  if (lowerCaseValue === '@meid') {
424
430
  args.options[option] = accessToken_1.accessToken.getUserIdFromAccessToken(token);
425
431
  }
@@ -0,0 +1,298 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.chili = void 0;
13
+ const fs = require("fs");
14
+ const inquirer = require("inquirer");
15
+ const ora = require("ora");
16
+ const path = require("path");
17
+ const Cli_1 = require("../cli/Cli");
18
+ const request_1 = require("../request");
19
+ const settingsNames_1 = require("../settingsNames");
20
+ const md_1 = require("../utils/md");
21
+ const mendableApiKey = 'd3313d54-6f8e-40e0-90d3-4095019d4be7';
22
+ let showHelp = false;
23
+ let debug = false;
24
+ let promptForRating = true;
25
+ let conversationId = 0;
26
+ let initialPrompt = '';
27
+ let history = [];
28
+ const cli = Cli_1.Cli.getInstance();
29
+ const showSpinner = cli.getSettingWithDefaultValue(settingsNames_1.settingsNames.showSpinner, true) && typeof global.it === 'undefined';
30
+ request_1.default.logger = {
31
+ /* c8 ignore next 3 */
32
+ log: (msg) => console.log(msg),
33
+ logRaw: (msg) => console.log(msg),
34
+ logToStderr: (msg) => console.error(msg)
35
+ };
36
+ request_1.default.debug = debug;
37
+ function getPromptFromArgs(args) {
38
+ showHelp = args.indexOf('--help') > -1 || args.indexOf('-h') > -1;
39
+ if (showHelp) {
40
+ const commandsFolder = path.join(__dirname, '..', 'm365');
41
+ const pathChunks = [commandsFolder, '..', '..', 'docs', 'docs', 'user-guide', 'chili.md'];
42
+ const helpFilePath = path.join(...pathChunks);
43
+ if (fs.existsSync(helpFilePath)) {
44
+ let helpContents = fs.readFileSync(helpFilePath, 'utf8');
45
+ helpContents = md_1.md.md2plain(helpContents, path.join(commandsFolder, '..', '..', 'docs'));
46
+ console.log(helpContents);
47
+ return '';
48
+ }
49
+ else {
50
+ console.error('Help file not found');
51
+ return '';
52
+ }
53
+ }
54
+ else {
55
+ // reset to default. needed for tests
56
+ showHelp = false;
57
+ }
58
+ const debugPos = args.indexOf('--debug');
59
+ if (debugPos > -1) {
60
+ debug = true;
61
+ request_1.default.debug = true;
62
+ args.splice(debugPos, 1);
63
+ }
64
+ else {
65
+ // reset to default. needed for tests
66
+ debug = false;
67
+ }
68
+ const noRatingPos = args.indexOf('--no-rating');
69
+ if (noRatingPos > -1) {
70
+ promptForRating = false;
71
+ args.splice(noRatingPos, 1);
72
+ }
73
+ else {
74
+ // reset to default. needed for tests
75
+ promptForRating = true;
76
+ }
77
+ return args.join(' ');
78
+ }
79
+ function startConversation(args) {
80
+ return __awaiter(this, void 0, void 0, function* () {
81
+ history = [];
82
+ initialPrompt = getPromptFromArgs(args);
83
+ if (showHelp) {
84
+ return;
85
+ }
86
+ conversationId = yield getConversationId();
87
+ if (!initialPrompt) {
88
+ initialPrompt = yield promptForPrompt();
89
+ }
90
+ yield runConversationTurn(conversationId, initialPrompt);
91
+ });
92
+ }
93
+ function promptForPrompt() {
94
+ return __awaiter(this, void 0, void 0, function* () {
95
+ const answer = yield inquirer.prompt([{
96
+ type: 'input',
97
+ name: 'prompt',
98
+ message: '🌶️ How can I help you?'
99
+ }]);
100
+ return answer.prompt;
101
+ });
102
+ }
103
+ function runConversationTurn(conversationId, question) {
104
+ return __awaiter(this, void 0, void 0, function* () {
105
+ console.log('');
106
+ const spinner = ora('Searching documentation...');
107
+ /* c8 ignore next 3 */
108
+ if (showSpinner) {
109
+ spinner.start();
110
+ }
111
+ const response = yield runMendableChat(conversationId, question);
112
+ history.push({
113
+ prompt: question,
114
+ response: response.answer.text
115
+ });
116
+ /* c8 ignore next 3 */
117
+ if (showSpinner) {
118
+ spinner.stop();
119
+ }
120
+ console.log(md_1.md.md2plain(response.answer.text, ''));
121
+ console.log('');
122
+ console.log('Source:');
123
+ // remove duplicates
124
+ const sources = response.sources.filter((src, index, self) => index === self.findIndex(s => s.link === src.link));
125
+ sources.forEach(src => console.log(`⬥ ${src.link}`));
126
+ console.log('');
127
+ if (promptForRating) {
128
+ try {
129
+ yield rateResponse(response.message_id);
130
+ }
131
+ catch (err) {
132
+ if (debug) {
133
+ console.error(`An error has occurred while rating the response: ${err}`);
134
+ }
135
+ }
136
+ console.log('');
137
+ }
138
+ const result = yield inquirer.prompt([{
139
+ type: 'list',
140
+ name: 'chat',
141
+ message: 'What would you like to do next?',
142
+ choices: [
143
+ {
144
+ name: '📝 I want to know more',
145
+ value: 'ask'
146
+ },
147
+ {
148
+ name: '👋 I know enough. Thanks!',
149
+ value: 'end'
150
+ },
151
+ {
152
+ name: '🔄 I want to ask about something else',
153
+ value: 'new'
154
+ }
155
+ ]
156
+ }]);
157
+ switch (result.chat) {
158
+ case 'ask':
159
+ const prompt = yield promptForPrompt();
160
+ return yield runConversationTurn(conversationId, prompt);
161
+ case 'end':
162
+ yield endConversation(conversationId);
163
+ console.log('');
164
+ console.log('🌶️ Bye!');
165
+ return;
166
+ case 'new':
167
+ initialPrompt = '';
168
+ return startConversation([]);
169
+ }
170
+ });
171
+ }
172
+ function rateResponse(messageId) {
173
+ return __awaiter(this, void 0, void 0, function* () {
174
+ const result = yield inquirer.prompt([{
175
+ type: 'list',
176
+ name: 'rating',
177
+ message: 'Was this helpful?',
178
+ choices: [
179
+ {
180
+ name: '👍 Yes',
181
+ value: 1
182
+ },
183
+ {
184
+ name: '👎 No',
185
+ value: -1
186
+ },
187
+ {
188
+ name: '🤔 Not sure/skip',
189
+ value: 0
190
+ }
191
+ ]
192
+ }]);
193
+ if (result.rating === 0) {
194
+ return;
195
+ }
196
+ console.log('Thanks for letting us know! 😊');
197
+ const requestOptions = {
198
+ url: 'https://api.mendable.ai/v0/rateMessage',
199
+ headers: {
200
+ 'content-type': 'application/json',
201
+ 'x-anonymous': true
202
+ },
203
+ responseType: 'json',
204
+ data: {
205
+ // eslint-disable-next-line camelcase
206
+ api_key: mendableApiKey,
207
+ // eslint-disable-next-line camelcase
208
+ conversation_id: conversationId,
209
+ // eslint-disable-next-line camelcase
210
+ message_id: messageId,
211
+ // eslint-disable-next-line camelcase
212
+ rating_value: result.rating
213
+ }
214
+ };
215
+ const spinner = ora('Sending rating...');
216
+ /* c8 ignore next 3 */
217
+ if (showSpinner) {
218
+ spinner.start();
219
+ }
220
+ yield request_1.default.post(requestOptions);
221
+ /* c8 ignore next 3 */
222
+ if (showSpinner) {
223
+ spinner.stop();
224
+ }
225
+ });
226
+ }
227
+ function endConversation(conversationId) {
228
+ return __awaiter(this, void 0, void 0, function* () {
229
+ const requestOptions = {
230
+ url: 'https://api.mendable.ai/v0/endConversation',
231
+ headers: {
232
+ 'content-type': 'application/json',
233
+ 'x-anonymous': true
234
+ },
235
+ responseType: 'json',
236
+ data: {
237
+ // eslint-disable-next-line camelcase
238
+ api_key: mendableApiKey,
239
+ // eslint-disable-next-line camelcase
240
+ conversation_id: conversationId
241
+ }
242
+ };
243
+ const spinner = ora('Ending conversation...');
244
+ /* c8 ignore next 3 */
245
+ if (showSpinner) {
246
+ spinner.start();
247
+ }
248
+ yield request_1.default.post(requestOptions);
249
+ /* c8 ignore next 3 */
250
+ if (showSpinner) {
251
+ spinner.stop();
252
+ }
253
+ });
254
+ }
255
+ function runMendableChat(conversationId, question) {
256
+ return __awaiter(this, void 0, void 0, function* () {
257
+ const requestOptions = {
258
+ url: 'https://api.mendable.ai/v0/mendableChat',
259
+ headers: {
260
+ 'content-type': 'application/json',
261
+ 'x-anonymous': true
262
+ },
263
+ responseType: 'json',
264
+ data: {
265
+ // eslint-disable-next-line camelcase
266
+ api_key: mendableApiKey,
267
+ // eslint-disable-next-line camelcase
268
+ conversation_id: conversationId,
269
+ question,
270
+ history,
271
+ shouldStream: false
272
+ }
273
+ };
274
+ return yield request_1.default.post(requestOptions);
275
+ });
276
+ }
277
+ function getConversationId() {
278
+ return __awaiter(this, void 0, void 0, function* () {
279
+ const requestOptions = {
280
+ url: 'https://api.mendable.ai/v0/newConversation',
281
+ headers: {
282
+ 'content-type': 'application/json',
283
+ 'x-anonymous': true
284
+ },
285
+ responseType: 'json',
286
+ data: {
287
+ // eslint-disable-next-line camelcase
288
+ api_key: mendableApiKey
289
+ }
290
+ };
291
+ const response = yield request_1.default.post(requestOptions);
292
+ return response.conversation_id;
293
+ });
294
+ }
295
+ exports.chili = {
296
+ startConversation
297
+ };
298
+ //# sourceMappingURL=chili.js.map
@@ -0,0 +1,20 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
4
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
5
+ return new (P || (P = Promise))(function (resolve, reject) {
6
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
7
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
8
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
9
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
10
+ });
11
+ };
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ const chili_1 = require("./chili");
14
+ try {
15
+ (() => __awaiter(void 0, void 0, void 0, function* () { return yield chili_1.chili.startConversation(process.argv.slice(2)); }))();
16
+ }
17
+ catch (err) {
18
+ console.error(`🛑 An error has occurred while searching documentation: ${err}`);
19
+ }
20
+ //# sourceMappingURL=index.js.map
package/dist/cli/Cli.js CHANGED
@@ -783,7 +783,7 @@ class Cli {
783
783
  console.error(message, ...optionalParams);
784
784
  }
785
785
  }
786
- static prompt(options) {
786
+ static prompt(options, answers) {
787
787
  return __awaiter(this, void 0, void 0, function* () {
788
788
  const inquirer = require('inquirer');
789
789
  const cli = Cli.getInstance();
@@ -792,7 +792,7 @@ class Cli {
792
792
  if (spinnerSpinning) {
793
793
  cli.spinner.stop();
794
794
  }
795
- const response = yield inquirer.prompt(options);
795
+ const response = yield inquirer.prompt(options, answers);
796
796
  // Restart the spinner if it was running before the prompt
797
797
  /* c8 ignore next 3 */
798
798
  if (spinnerSpinning) {
@@ -0,0 +1,279 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
12
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
13
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
14
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
15
+ };
16
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
17
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
18
+ var m = o[Symbol.asyncIterator], i;
19
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
20
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
21
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
22
+ };
23
+ var _AppPermissionAddCommand_instances, _AppPermissionAddCommand_initTelemetry, _AppPermissionAddCommand_initOptions, _AppPermissionAddCommand_initOptionSets;
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ const request_1 = require("../../../../request");
26
+ const formatting_1 = require("../../../../utils/formatting");
27
+ const odata_1 = require("../../../../utils/odata");
28
+ const AppCommand_1 = require("../../../base/AppCommand");
29
+ const commands_1 = require("../../commands");
30
+ var ScopeType;
31
+ (function (ScopeType) {
32
+ ScopeType["Role"] = "Role";
33
+ ScopeType["Scope"] = "Scope";
34
+ })(ScopeType || (ScopeType = {}));
35
+ class AppPermissionAddCommand extends AppCommand_1.default {
36
+ get name() {
37
+ return commands_1.default.PERMISSION_ADD;
38
+ }
39
+ get description() {
40
+ return 'Adds the specified application and/or delegated permissions to the current AAD app API permissions';
41
+ }
42
+ constructor() {
43
+ super();
44
+ _AppPermissionAddCommand_instances.add(this);
45
+ __classPrivateFieldGet(this, _AppPermissionAddCommand_instances, "m", _AppPermissionAddCommand_initTelemetry).call(this);
46
+ __classPrivateFieldGet(this, _AppPermissionAddCommand_instances, "m", _AppPermissionAddCommand_initOptions).call(this);
47
+ __classPrivateFieldGet(this, _AppPermissionAddCommand_instances, "m", _AppPermissionAddCommand_initOptionSets).call(this);
48
+ }
49
+ commandAction(logger, args) {
50
+ return __awaiter(this, void 0, void 0, function* () {
51
+ try {
52
+ const appObject = yield this.getAppObject();
53
+ const servicePrincipals = yield odata_1.odata.getAllItems(`${this.resource}/v1.0/myorganization/servicePrincipals?$select=appId,appRoles,id,oauth2PermissionScopes,servicePrincipalNames`);
54
+ const appPermissions = [];
55
+ if (args.options.delegatedPermission) {
56
+ const delegatedPermissions = this.getRequiredResourceAccessForApis(servicePrincipals, args.options.delegatedPermission, ScopeType.Scope, appPermissions, logger);
57
+ this.addPermissionsToResourceArray(delegatedPermissions, appObject.requiredResourceAccess);
58
+ }
59
+ if (args.options.applicationPermission) {
60
+ const applicationPermissions = this.getRequiredResourceAccessForApis(servicePrincipals, args.options.applicationPermission, ScopeType.Role, appPermissions, logger);
61
+ this.addPermissionsToResourceArray(applicationPermissions, appObject.requiredResourceAccess);
62
+ }
63
+ const addPermissionsRequestOptions = {
64
+ url: `${this.resource}/v1.0/myorganization/applications/${appObject.id}`,
65
+ headers: {
66
+ accept: 'application/json;odata.metadata=none'
67
+ },
68
+ responseType: 'json',
69
+ data: {
70
+ requiredResourceAccess: appObject.requiredResourceAccess
71
+ }
72
+ };
73
+ yield request_1.default.patch(addPermissionsRequestOptions);
74
+ if (args.options.grantAdminConsent) {
75
+ const appServicePrincipal = servicePrincipals.find(sp => sp.appId === this.appId);
76
+ yield this.grantAdminConsent(appServicePrincipal, appPermissions, logger);
77
+ }
78
+ }
79
+ catch (err) {
80
+ this.handleRejectedODataJsonPromise(err);
81
+ }
82
+ });
83
+ }
84
+ getAppObject() {
85
+ return __awaiter(this, void 0, void 0, function* () {
86
+ const apps = yield odata_1.odata.getAllItems(`${this.resource}/v1.0/myorganization/applications?$filter=appId eq '${formatting_1.formatting.encodeQueryParameter(this.appId)}'&$select=id,requiredResourceAccess`);
87
+ if (apps.length === 0) {
88
+ throw `App with id ${this.appId} not found in Azure Active Directory`;
89
+ }
90
+ return apps[0];
91
+ });
92
+ }
93
+ addPermissionsToResourceArray(permissions, existingArray) {
94
+ permissions.forEach(resolvedRequiredResource => {
95
+ const requiredResource = existingArray.find(api => api.resourceAppId === resolvedRequiredResource.resourceAppId);
96
+ if (requiredResource) {
97
+ // make sure that permission does not yet exist on the app or it will be added twice
98
+ resolvedRequiredResource.resourceAccess.forEach(resAccess => {
99
+ if (!requiredResource.resourceAccess.some(res => res.id === resAccess.id)) {
100
+ requiredResource.resourceAccess.push(resAccess);
101
+ }
102
+ });
103
+ }
104
+ else {
105
+ existingArray.push(resolvedRequiredResource);
106
+ }
107
+ });
108
+ }
109
+ getRequiredResourceAccessForApis(servicePrincipals, apis, scopeType, appPermissions, logger) {
110
+ const resolvedApis = [];
111
+ const requestedApis = apis.split(' ').map(a => a.trim());
112
+ requestedApis.forEach(api => {
113
+ const pos = api.lastIndexOf('/');
114
+ const permissionName = api.substring(pos + 1);
115
+ const servicePrincipalName = api.substring(0, pos);
116
+ if (this.verbose) {
117
+ logger.logToStderr(`Resolving ${api}...`);
118
+ logger.logToStderr(`Permission name: ${permissionName}`);
119
+ logger.logToStderr(`Service principal name: ${servicePrincipalName}`);
120
+ }
121
+ const servicePrincipal = servicePrincipals.find(sp => (sp.servicePrincipalNames.indexOf(servicePrincipalName) > -1 ||
122
+ sp.servicePrincipalNames.indexOf(`${servicePrincipalName}/`) > -1));
123
+ if (!servicePrincipal) {
124
+ throw `Service principal ${servicePrincipalName} not found`;
125
+ }
126
+ let permission = undefined;
127
+ if (scopeType === ScopeType.Scope) {
128
+ permission = servicePrincipal.oauth2PermissionScopes.find(scope => scope.value === permissionName);
129
+ }
130
+ else if (scopeType === ScopeType.Role) {
131
+ permission = servicePrincipal.appRoles.find(scope => scope.value === permissionName);
132
+ }
133
+ if (!permission) {
134
+ throw `Permission ${permissionName} for service principal ${servicePrincipalName} not found`;
135
+ }
136
+ let resolvedApi = resolvedApis.find(a => a.resourceAppId === servicePrincipal.appId);
137
+ if (!resolvedApi) {
138
+ resolvedApi = {
139
+ resourceAppId: servicePrincipal.appId,
140
+ resourceAccess: []
141
+ };
142
+ resolvedApis.push(resolvedApi);
143
+ }
144
+ const resourceAccessPermission = {
145
+ id: permission.id,
146
+ type: scopeType
147
+ };
148
+ resolvedApi.resourceAccess.push(resourceAccessPermission);
149
+ this.updateAppPermissions(servicePrincipal.id, resourceAccessPermission, permission.value, appPermissions);
150
+ });
151
+ return resolvedApis;
152
+ }
153
+ updateAppPermissions(spId, resourceAccessPermission, oAuth2PermissionValue, appPermissions) {
154
+ let existingPermission = appPermissions.find(oauth => oauth.resourceId === spId);
155
+ if (!existingPermission) {
156
+ existingPermission = {
157
+ resourceId: spId,
158
+ resourceAccess: [],
159
+ scope: []
160
+ };
161
+ appPermissions.push(existingPermission);
162
+ }
163
+ if (resourceAccessPermission.type === ScopeType.Scope && oAuth2PermissionValue && !existingPermission.scope.find(scp => scp === oAuth2PermissionValue)) {
164
+ existingPermission.scope.push(oAuth2PermissionValue);
165
+ }
166
+ if (!existingPermission.resourceAccess.find(res => res.id === resourceAccessPermission.id)) {
167
+ existingPermission.resourceAccess.push(resourceAccessPermission);
168
+ }
169
+ }
170
+ grantAdminConsent(servicePrincipal, appPermissions, logger) {
171
+ var _a, appPermissions_1, appPermissions_1_1;
172
+ var _b, e_1, _c, _d, _e, e_2, _f, _g;
173
+ return __awaiter(this, void 0, void 0, function* () {
174
+ try {
175
+ for (_a = true, appPermissions_1 = __asyncValues(appPermissions); appPermissions_1_1 = yield appPermissions_1.next(), _b = appPermissions_1_1.done, !_b;) {
176
+ _d = appPermissions_1_1.value;
177
+ _a = false;
178
+ try {
179
+ const permission = _d;
180
+ if (permission.scope.length > 0) {
181
+ if (this.verbose) {
182
+ logger.logToStderr(`Granting consent for delegated permission(s) with resourceId ${permission.resourceId} and scope(s) ${permission.scope.join(' ')}`);
183
+ }
184
+ yield this.grantOAuth2Permission(servicePrincipal.id, permission.resourceId, permission.scope.join(' '));
185
+ }
186
+ try {
187
+ for (var _h = true, _j = (e_2 = void 0, __asyncValues(permission.resourceAccess.filter(acc => acc.type === ScopeType.Role))), _k; _k = yield _j.next(), _e = _k.done, !_e;) {
188
+ _g = _k.value;
189
+ _h = false;
190
+ try {
191
+ const access = _g;
192
+ if (this.verbose) {
193
+ logger.logToStderr(`Granting consent for application permission with resourceId ${permission.resourceId} and appRoleId ${access.id}`);
194
+ }
195
+ yield this.addRoleToServicePrincipal(servicePrincipal.id, permission.resourceId, access.id);
196
+ }
197
+ finally {
198
+ _h = true;
199
+ }
200
+ }
201
+ }
202
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
203
+ finally {
204
+ try {
205
+ if (!_h && !_e && (_f = _j.return)) yield _f.call(_j);
206
+ }
207
+ finally { if (e_2) throw e_2.error; }
208
+ }
209
+ }
210
+ finally {
211
+ _a = true;
212
+ }
213
+ }
214
+ }
215
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
216
+ finally {
217
+ try {
218
+ if (!_a && !_b && (_c = appPermissions_1.return)) yield _c.call(appPermissions_1);
219
+ }
220
+ finally { if (e_1) throw e_1.error; }
221
+ }
222
+ });
223
+ }
224
+ grantOAuth2Permission(servicePricipalId, resourceId, scope) {
225
+ return __awaiter(this, void 0, void 0, function* () {
226
+ const grantAdminConsentApplicationRequestOptions = {
227
+ url: `${this.resource}/v1.0/myorganization/oauth2PermissionGrants`,
228
+ headers: {
229
+ accept: 'application/json;odata.metadata=none'
230
+ },
231
+ responseType: 'json',
232
+ data: {
233
+ clientId: servicePricipalId,
234
+ consentType: 'AllPrincipals',
235
+ principalId: null,
236
+ resourceId: resourceId,
237
+ scope: scope
238
+ }
239
+ };
240
+ return request_1.default.post(grantAdminConsentApplicationRequestOptions);
241
+ });
242
+ }
243
+ addRoleToServicePrincipal(servicePrincipalId, resourceId, appRoleId) {
244
+ return __awaiter(this, void 0, void 0, function* () {
245
+ const requestOptions = {
246
+ url: `${this.resource}/v1.0/myorganization/servicePrincipals/${servicePrincipalId}/appRoleAssignments`,
247
+ headers: {
248
+ 'content-type': 'application/json'
249
+ },
250
+ responseType: 'json',
251
+ data: {
252
+ appRoleId: appRoleId,
253
+ principalId: servicePrincipalId,
254
+ resourceId: resourceId
255
+ }
256
+ };
257
+ return request_1.default.post(requestOptions);
258
+ });
259
+ }
260
+ }
261
+ _AppPermissionAddCommand_instances = new WeakSet(), _AppPermissionAddCommand_initTelemetry = function _AppPermissionAddCommand_initTelemetry() {
262
+ this.telemetry.push((args) => {
263
+ Object.assign(this.telemetryProperties, {
264
+ appId: typeof args.options.appId !== 'undefined',
265
+ applicationPermission: typeof args.options.applicationPermission !== 'undefined',
266
+ delegatedPermission: typeof args.options.delegatedPermission !== 'undefined',
267
+ grantAdminConsent: !!args.options.grantAdminConsent
268
+ });
269
+ });
270
+ }, _AppPermissionAddCommand_initOptions = function _AppPermissionAddCommand_initOptions() {
271
+ this.options.unshift({ option: '--appId [appId]' }, { option: '--applicationPermission [applicationPermission]' }, { option: '--delegatedPermission [delegatedPermission]' }, { option: '--grantAdminConsent' });
272
+ }, _AppPermissionAddCommand_initOptionSets = function _AppPermissionAddCommand_initOptionSets() {
273
+ this.optionSets.push({
274
+ options: ['applicationPermission', 'delegatedPermission'],
275
+ runsWhen: (args) => args.options.delegatedPermission === undefined && args.options.applicationPermission === undefined
276
+ });
277
+ };
278
+ module.exports = new AppPermissionAddCommand();
279
+ //# sourceMappingURL=permission-add.js.map
@@ -4,6 +4,7 @@ const prefix = 'app';
4
4
  exports.default = {
5
5
  GET: `${prefix} get`,
6
6
  OPEN: `${prefix} open`,
7
+ PERMISSION_ADD: `${prefix} permission add`,
7
8
  PERMISSION_LIST: `${prefix} permission list`
8
9
  };
9
10
  //# sourceMappingURL=commands.js.map
@@ -5,6 +5,7 @@ exports.default = {
5
5
  LOGIN: `login`,
6
6
  LOGOUT: `logout`,
7
7
  REQUEST: `request`,
8
+ SETUP: `setup`,
8
9
  STATUS: `status`,
9
10
  VERSION: 'version'
10
11
  };