Initial commit

This commit is contained in:
2025-03-07 19:22:02 +01:00
commit 4a98255d83
55743 changed files with 5280367 additions and 0 deletions
+21
View File
@@ -0,0 +1,21 @@
Copyright (c) Microsoft Corporation.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+40
View File
@@ -0,0 +1,40 @@
# TeamsFx Core
The TeamsFx Core package implements shared capabilities for Teams Toolkit IDE Extensions and the CLI through API contracts defined in the [api](/packages/api).
## Data Collection.
The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the repository. There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft's privacy statement. Our privacy statement is located at https://go.microsoft.com/fwlink/?LinkID=824704. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices.
## Code of Conduct
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.
## Contributing
There are many ways in which you can participate in the project, for example:
- [Submit bugs and feature requests](https://github.com/OfficeDev/TeamsFx/issues), and help us verify as they are checked in
- Review [source code changes](https://github.com/OfficeDev/TeamsFx/pulls)
If you are interested in fixing issues and contributing directly to the code base, please see the [Contributing Guide](./CONTRIBUTING.md).
## Reporting Security Issues
**Please do not report security vulnerabilities through public GitHub issues.**
Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://msrc.microsoft.com/create-report).
If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the the [Microsoft Security Response Center PGP Key page](https://www.microsoft.com/en-us/msrc/pgp-key-msrc).
You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://www.microsoft.com/msrc).
## Trademarks
This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow [Microsoft's Trademark & Brand Guidelines](https://www.microsoft.com/en-us/legal/intellectualproperty/trademarks/usage/general). Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party's policies.
## License
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the [MIT](LICENSE.txt) license.
@@ -0,0 +1,129 @@
/// <reference types="node" />
import { AxiosInstance, AxiosResponse } from "axios";
import { ApiSecretRegistration, ApiSecretRegistrationUpdate } from "../component/driver/teamsApp/interfaces/ApiSecretRegistration";
import { AsyncAppValidationDetailsResponse } from "../component/driver/teamsApp/interfaces/AsyncAppValidationDetailsResponse";
import { AsyncAppValidationResponse } from "../component/driver/teamsApp/interfaces/AsyncAppValidationResponse";
import { AsyncAppValidationResultsResponse } from "../component/driver/teamsApp/interfaces/AsyncAppValidationResultsResponse";
import { OauthConfigurationId } from "../component/driver/teamsApp/interfaces/OauthConfigurationId";
import { OauthRegistration } from "../component/driver/teamsApp/interfaces/OauthRegistration";
import { IPublishingAppDenition } from "../component/driver/teamsApp/interfaces/appdefinitions/IPublishingAppDefinition";
import { IValidationResult } from "../component/driver/teamsApp/interfaces/appdefinitions/IValidationResult";
import { AppDefinition } from "../component/driver/teamsApp/interfaces/appdefinitions/appDefinition";
import { AppUser } from "../component/driver/teamsApp/interfaces/appdefinitions/appUser";
import { IBotRegistration } from "../component/resource/botService/appStudio/interfaces/IBotRegistration";
export declare class RetryHandler {
static RETRIES: number;
static Retry<T>(fn: () => Promise<T>): Promise<T | undefined>;
}
export declare class TeamsDevPortalClient {
regionEndpoint?: string;
getGlobalEndpoint(): string;
setRegionEndpoint(regionEndpoint: string): void;
setRegionEndpointByToken(authSvcToken: string): Promise<void>;
getEndpoint(): string;
/**
* Creates a new axios instance to call app studio to prevent setting the accessToken on global instance.
* @param {string} token
* @returns {AxiosInstance}
*/
createRequesterWithToken(token: string): AxiosInstance;
/**
* Import an app registration in app studio with the given archived file and returns the app definition.
* @param {string} token - access token
* @param {Buffer} file - Zip file with manifest.json and two icons
* @param {boolean} overwrite - whether to overrite the app if it already exists
* @returns {Promise<AppDefinition>}
*/
importApp(token: string, file: Buffer, overwrite?: boolean): Promise<AppDefinition>;
listApps(token: string): Promise<AppDefinition[]>;
deleteApp(appStudioToken: string, teamsAppId: string): Promise<boolean>;
getApp(token: string, teamsAppId: string): Promise<AppDefinition>;
getBotId(token: string, teamsAppId: string): Promise<string | undefined>;
getAppPackage(token: string, teamsAppId: string): Promise<any>;
/**
* Check if app exists in the user's organization by the Teams app id
* @param teamsAppId
* @param token
* @param logProvider
* @returns
*/
checkExistsInTenant(token: string, teamsAppId: string): Promise<boolean>;
/**
* Publish Teams app to Teams App Catalog
*/
publishTeamsApp(token: string, teamsAppId: string, file: Buffer): Promise<string>;
/**
* Update existed publish request
* @param teamsAppId
* @param file
* @param token
* @returns
*/
publishTeamsAppUpdate(token: string, teamsAppId: string, file: Buffer): Promise<string>;
/**
* Get Stagged Teams app from tenant app catalog
* @param teamsAppId manifest.id, which is externalId in app catalog.
* @param token
* @returns
*/
getStaggedApp(token: string, teamsAppId: string): Promise<IPublishingAppDenition | undefined>;
getUserList(token: string, teamsAppId: string): Promise<AppUser[] | undefined>;
checkPermission(token: string, teamsAppId: string, userObjectId: string): Promise<string>;
grantPermission(token: string, teamsAppId: string, newUser: AppUser): Promise<void>;
/**
* Send the app package for partner center validation
* @param file
* @param token
* @returns
*/
partnerCenterAppPackageValidation(token: string, file: Buffer): Promise<IValidationResult>;
checkUser(app: AppDefinition, newUser: AppUser): boolean;
/**
* Submit App Validation Request (In-App) for which App Definitions are stored at TDP.
* @param teamsAppId
* @param token
* @param timeoutSeconds
* @returns
*/
submitAppValidationRequest(token: string, teamsAppId: string): Promise<AsyncAppValidationResponse>;
/**
* Get App validation requests sumitted by the user
*/
getAppValidationRequestList(token: string, teamsAppId: string): Promise<AsyncAppValidationDetailsResponse>;
/**
* Get App validation results by provided app validation id
* @param appValidationId
* @param token
* @param timeoutSeconds
* @returns
*/
getAppValidationById(token: string, appValidationId: string): Promise<AsyncAppValidationResultsResponse>;
getSideloadingStatus(token: string): Promise<boolean | undefined>;
/**
* Create the Api Key registration.
* @param token
* @param apiKeyRegistration
*/
createApiKeyRegistration(token: string, apiKeyRegistration: ApiSecretRegistration): Promise<ApiSecretRegistration>;
/**
* Get the Api Key registration by Id.
* @param token
* @param apiSecretRegistrationId
*/
getApiKeyRegistrationById(token: string, apiSecretRegistrationId: string): Promise<ApiSecretRegistration>;
updateApiKeyRegistration(token: string, apiKeyRegistration: ApiSecretRegistrationUpdate, apiKeyRegistrationId: string): Promise<ApiSecretRegistrationUpdate>;
getOauthRegistrationById(token: string, oauthRegistrationId: string): Promise<OauthRegistration>;
createOauthRegistration(token: string, oauthRegistration: OauthRegistration): Promise<OauthConfigurationId>;
updateOauthRegistration(token: string, oauthRegistration: OauthRegistration, oauthRegistrationId: string): Promise<OauthRegistration>;
getBotRegistration(token: string, botId: string): Promise<IBotRegistration | undefined>;
listBots(token: string): Promise<IBotRegistration[] | undefined>;
deleteBot(token: string, botId: string): Promise<void>;
createBotRegistration(token: string, registration: IBotRegistration, checkExistence?: boolean): Promise<void>;
updateMessageEndpoint(token: string, botId: string, endpoint: string): Promise<void>;
updateBotRegistration(token: string, botReg: IBotRegistration): Promise<void>;
handleBotFrameworkError(e: any, apiName: string): void | undefined;
wrapResponse(e?: Error, response?: AxiosResponse<any, any>): any;
wrapException(e: any, apiName: string, name?: string, potentialReason?: string, disPlayMessage?: string, isUserError?: boolean, helpLink?: string): Error;
}
export declare const teamsDevPortalClient: TeamsDevPortalClient;
//# sourceMappingURL=teamsDevPortalClient.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"teamsDevPortalClient.d.ts","sourceRoot":"","sources":["../../src/client/teamsDevPortalClient.ts"],"names":[],"mappings":";AAKA,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AAkBrD,OAAO,EACL,qBAAqB,EACrB,2BAA2B,EAC5B,MAAM,+DAA+D,CAAC;AACvE,OAAO,EAAE,iCAAiC,EAAE,MAAM,2EAA2E,CAAC;AAC9H,OAAO,EAAE,0BAA0B,EAAE,MAAM,oEAAoE,CAAC;AAChH,OAAO,EAAE,iCAAiC,EAAE,MAAM,2EAA2E,CAAC;AAC9H,OAAO,EAAE,oBAAoB,EAAE,MAAM,8DAA8D,CAAC;AACpG,OAAO,EAAE,iBAAiB,EAAE,MAAM,2DAA2D,CAAC;AAC9F,OAAO,EAAE,sBAAsB,EAAE,MAAM,iFAAiF,CAAC;AACzH,OAAO,EAAE,iBAAiB,EAAE,MAAM,0EAA0E,CAAC;AAC7G,OAAO,EAAE,aAAa,EAAE,MAAM,sEAAsE,CAAC;AACrG,OAAO,EAAE,OAAO,EAAE,MAAM,gEAAgE,CAAC;AAGzF,OAAO,EAEL,gBAAgB,EACjB,MAAM,wEAAwE,CAAC;AAmBhF,qBAAa,YAAY;IACvB,OAAc,OAAO,S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KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC;IAcnF,uBAAuB,CAAC,CAAC,EAAE,GAAG,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS;IAclE,YAAY,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,QAAQ,CAAC,EAAE,aAAa,CAAC,GAAG,EAAE,GAAG,CAAC,GAAG,GAAG;IAQhE,aAAa,CACX,CAAC,EAAE,GAAG,EACN,OAAO,EAAE,MAAM,EACf,IAAI,SAA4D,EAChE,eAAe,SAA8D,EAC7E,cAAc,CAAC,EAAE,MAAM,EACvB,WAAW,UAAQ,EACnB,QAAQ,CAAC,EAAE,MAAM,GAChB,KAAK;CAgCT;AAED,eAAO,MAAM,oBAAoB,sBAA6B,CAAC"}
@@ -0,0 +1,938 @@
"use strict";
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.teamsDevPortalClient = exports.TeamsDevPortalClient = exports.RetryHandler = void 0;
const tslib_1 = require("tslib");
const hooks_1 = require("@feathersjs/hooks");
const teamsfx_api_1 = require("@microsoft/teamsfx-api");
const constants_1 = require("../common/constants");
const globalVars_1 = require("../common/globalVars");
const localizeUtils_1 = require("../common/localizeUtils");
const telemetry_1 = require("../common/telemetry");
const wrappedAxiosClient_1 = require("../common/wrappedAxiosClient");
const commonConstant_1 = require("../component/constant/commonConstant");
const constants_2 = require("../component/driver/teamsApp/constants");
const errors_1 = require("../component/driver/teamsApp/errors");
const ManifestUtils_1 = require("../component/driver/teamsApp/utils/ManifestUtils");
const IBotRegistration_1 = require("../component/resource/botService/appStudio/interfaces/IBotRegistration");
const common_1 = require("../component/resource/botService/common");
const constants_3 = require("../component/resource/botService/constants");
const errors_2 = require("../component/resource/botService/errors");
const messages_1 = require("../component/resource/botService/messages");
const strings_1 = require("../component/resource/botService/strings");
const teamsApp_1 = require("../error/teamsApp");
class RetryHandler {
static async Retry(fn) {
var _a, _b;
let retries = this.RETRIES;
let response;
while (retries > 0) {
retries = retries - 1;
try {
response = await fn();
return response;
}
catch (e) {
// Directly throw 404 error, keep trying for other status code e.g. 503 400
if (retries <= 0 || ((_a = e.response) === null || _a === void 0 ? void 0 : _a.status) == 404 || ((_b = e.response) === null || _b === void 0 ? void 0 : _b.status) == 409) {
throw e;
}
else {
await new Promise((resolve) => setTimeout(resolve, 5000));
}
}
}
}
}
exports.RetryHandler = RetryHandler;
RetryHandler.RETRIES = 6;
class TeamsDevPortalClient {
getGlobalEndpoint() {
if (process.env.APP_STUDIO_ENV && process.env.APP_STUDIO_ENV === "int") {
return "https://dev-int.teams.microsoft.com";
}
else {
return "https://dev.teams.microsoft.com";
}
}
setRegionEndpoint(regionEndpoint) {
this.regionEndpoint = regionEndpoint;
}
async setRegionEndpointByToken(authSvcToken) {
var _a, _b;
if (this.getGlobalEndpoint() === "https://dev-int.teams.microsoft.com") {
// Do not set region for INT env
return;
}
const requester = wrappedAxiosClient_1.WrappedAxiosClient.create({
baseURL: "https://authsvc.teams.microsoft.com",
});
requester.defaults.headers.common["Authorization"] = `Bearer ${authSvcToken}`;
requester.defaults.headers.common["Client-Source"] = "teamstoolkit";
const response = await RetryHandler.Retry(() => requester.post("/v1.0/users/region"));
this.regionEndpoint = (_b = (_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a.regionGtms) === null || _b === void 0 ? void 0 : _b.teamsDevPortal;
}
getEndpoint() {
return this.regionEndpoint || this.getGlobalEndpoint();
}
/**
* Creates a new axios instance to call app studio to prevent setting the accessToken on global instance.
* @param {string} token
* @returns {AxiosInstance}
*/
createRequesterWithToken(token) {
const instance = wrappedAxiosClient_1.WrappedAxiosClient.create({
baseURL: this.getEndpoint(),
});
instance.defaults.headers.common["Authorization"] = `Bearer ${token}`;
instance.defaults.headers.common["Client-Source"] = "teamstoolkit";
return instance;
}
/**
* Import an app registration in app studio with the given archived file and returns the app definition.
* @param {string} token - access token
* @param {Buffer} file - Zip file with manifest.json and two icons
* @param {boolean} overwrite - whether to overrite the app if it already exists
* @returns {Promise<AppDefinition>}
*/
async importApp(token, file, overwrite = false) {
var _a, _b, _c, _d, _e;
try {
const requester = this.createRequesterWithToken(token);
globalVars_1.TOOLS.logProvider.debug(`Sent API Request: ${this.getEndpoint()}/api/appdefinitions/v2/import`);
const response = await RetryHandler.Retry(() => requester.post(`/api/appdefinitions/v2/import`, file, {
headers: { "Content-Type": "application/zip" },
params: {
overwriteIfAppAlreadyExists: overwrite,
},
}));
if (response && response.data) {
const app = response.data;
globalVars_1.TOOLS.logProvider.debug(`Received data from Teams Developer Portal: ${JSON.stringify(app)}`);
return app;
}
else {
throw this.wrapException(new Error("cannot create teams app"), constants_2.APP_STUDIO_API_NAMES.CREATE_APP);
}
}
catch (e) {
if (((_a = e.response) === null || _a === void 0 ? void 0 : _a.status) === 409) {
throw this.wrapException(e, constants_2.APP_STUDIO_API_NAMES.CREATE_APP, errors_1.AppStudioError.TeamsAppCreateConflictError.name, errors_1.AppStudioError.TeamsAppCreateConflictError.message()[0], errors_1.AppStudioError.TeamsAppCreateConflictError.message()[1], true, constants_1.HelpLinks.SwitchTenant);
}
// Corner case: The provided app ID conflict with an existing published app
// See Developer Portal PR: 507264
if (((_b = e.response) === null || _b === void 0 ? void 0 : _b.status) == 422 &&
((_c = e.response) === null || _c === void 0 ? void 0 : _c.data.includes("App already exists and published"))) {
throw this.wrapException(e, constants_2.APP_STUDIO_API_NAMES.CREATE_APP, errors_1.AppStudioError.TeamsAppCreateConflictWithPublishedAppError.name, errors_1.AppStudioError.TeamsAppCreateConflictWithPublishedAppError.message()[0], errors_1.AppStudioError.TeamsAppCreateConflictWithPublishedAppError.message()[1], true);
}
// Corner case: App Id must be a GUID
if (((_d = e.response) === null || _d === void 0 ? void 0 : _d.status) === commonConstant_1.HttpStatusCode.BAD_REQUEST &&
((_e = e.response) === null || _e === void 0 ? void 0 : _e.data.includes("App Id must be a GUID"))) {
const manifest = ManifestUtils_1.manifestUtils.extractManifestFromArchivedFile(file);
if (manifest.isErr()) {
throw manifest.error;
}
else {
const teamsAppId = manifest.value.id;
throw this.wrapException(e, constants_2.APP_STUDIO_API_NAMES.CREATE_APP, errors_1.AppStudioError.InvalidTeamsAppIdError.name, errors_1.AppStudioError.InvalidTeamsAppIdError.message(teamsAppId)[0], errors_1.AppStudioError.InvalidTeamsAppIdError.message(teamsAppId)[1], true);
}
}
throw this.wrapException(e, constants_2.APP_STUDIO_API_NAMES.CREATE_APP);
}
}
async listApps(token) {
if (!this.regionEndpoint)
throw new Error("Failed to get region");
let requester;
try {
requester = this.createRequesterWithToken(token);
globalVars_1.TOOLS.logProvider.debug(`Sent API Request: GET ${this.regionEndpoint}/api/appdefinitions`);
const response = await RetryHandler.Retry(() => requester.get(`/api/appdefinitions`));
const apps = response === null || response === void 0 ? void 0 : response.data;
if (apps) {
return apps;
}
else {
globalVars_1.TOOLS.logProvider.error("Cannot get the app definitions");
}
}
catch (e) {
throw this.wrapException(e, constants_2.APP_STUDIO_API_NAMES.LIST_APPS);
}
throw this.wrapException(new Error("cannot get the app definitions"), constants_2.APP_STUDIO_API_NAMES.LIST_APPS);
}
async deleteApp(appStudioToken, teamsAppId) {
var _a;
if (!this.regionEndpoint)
throw new Error("Failed to get region");
let requester;
try {
requester = this.createRequesterWithToken(appStudioToken);
globalVars_1.TOOLS.logProvider.debug(`Sent API Request: DELETE ${this.getEndpoint()}/api/appdefinitions/${teamsAppId}`);
const response = await RetryHandler.Retry(() => requester.delete(`/api/appdefinitions/${teamsAppId}`));
if (response && response.data) {
const success = response.data;
if (success) {
return success;
}
else {
(_a = globalVars_1.TOOLS.logProvider) === null || _a === void 0 ? void 0 : _a.error("Cannot get the app definitions");
}
}
}
catch (e) {
throw this.wrapException(e, constants_2.APP_STUDIO_API_NAMES.DELETE_APP);
}
throw this.wrapException(new Error("cannot delete the app: " + teamsAppId), constants_2.APP_STUDIO_API_NAMES.DELETE_APP);
}
async getApp(token, teamsAppId) {
var _a;
let requester;
try {
requester = this.createRequesterWithToken(token);
globalVars_1.TOOLS.logProvider.debug(`Sent API Request: GET ${this.getEndpoint()}/api/appdefinitions/${teamsAppId}`);
const response = await RetryHandler.Retry(() => requester.get(`/api/appdefinitions/${teamsAppId}`));
if (response && response.data) {
const app = response.data;
if (app && app.teamsAppId && app.teamsAppId === teamsAppId) {
return app;
}
else {
(_a = globalVars_1.TOOLS.logProvider) === null || _a === void 0 ? void 0 : _a.error(`teamsAppId mismatch. Input: ${teamsAppId}. Got: ${app.teamsAppId}`);
}
}
}
catch (e) {
throw this.wrapException(e, constants_2.APP_STUDIO_API_NAMES.GET_APP);
}
throw this.wrapException(new Error(`cannot get the app definition with app ID ${teamsAppId}`), constants_2.APP_STUDIO_API_NAMES.GET_APP);
}
async getBotId(token, teamsAppId) {
var _a, _b;
const app = await this.getApp(token, teamsAppId);
if (((_a = app === null || app === void 0 ? void 0 : app.bots) === null || _a === void 0 ? void 0 : _a.length) && app.bots.length > 0) {
return app.bots[0].botId;
}
(_b = globalVars_1.TOOLS.logProvider) === null || _b === void 0 ? void 0 : _b.error(`botId not found. Input: ${teamsAppId}`);
return undefined;
}
async getAppPackage(token, teamsAppId) {
var _a, _b;
(_a = globalVars_1.TOOLS.logProvider) === null || _a === void 0 ? void 0 : _a.info("Downloading app package for app " + teamsAppId);
const requester = this.createRequesterWithToken(token);
try {
const response = await RetryHandler.Retry(() => requester.get(`/api/appdefinitions/${teamsAppId}/manifest`));
if (response && response.data) {
(_b = globalVars_1.TOOLS.logProvider) === null || _b === void 0 ? void 0 : _b.info("Download app package successfully");
return response.data;
}
else {
throw this.wrapException(new Error((0, localizeUtils_1.getLocalizedString)("plugins.appstudio.emptyAppPackage", teamsAppId)), constants_2.APP_STUDIO_API_NAMES.GET_APP_PACKAGE);
}
}
catch (e) {
throw this.wrapException(e, constants_2.APP_STUDIO_API_NAMES.GET_APP_PACKAGE);
}
}
/**
* Check if app exists in the user's organization by the Teams app id
* @param teamsAppId
* @param token
* @param logProvider
* @returns
*/
async checkExistsInTenant(token, teamsAppId) {
const requester = this.createRequesterWithToken(token);
try {
const response = await RetryHandler.Retry(() => requester.get(`/api/appdefinitions/manifest/${teamsAppId}`));
if (response && response.data) {
return response.data;
}
else {
return false;
}
}
catch (e) {
return false;
}
}
/**
* Publish Teams app to Teams App Catalog
*/
async publishTeamsApp(token, teamsAppId, file) {
var _a;
try {
const requester = this.createRequesterWithToken(token);
const response = await RetryHandler.Retry(() => requester.post("/api/publishing", file, {
headers: { "Content-Type": "application/zip" },
}));
if (response && response.data) {
if (response.data.error) {
// To avoid App Studio BadGateway error
// The app is actually published to app catalog.
if (response.data.error.code === "BadGateway") {
const appDefinition = await this.getStaggedApp(token, teamsAppId);
if (appDefinition) {
return appDefinition.teamsAppId;
}
}
// Corner case
// Fail if an app with the same external.id exists in the staged app entitlements
// App with same id already exists in the staged apps, Invoke UpdateAPI instead.
if (response.data.error.code == "Conflict" &&
((_a = response.data.error.innerError) === null || _a === void 0 ? void 0 : _a.code) == "AppDefinitionAlreadyExists") {
try {
return await this.publishTeamsAppUpdate(token, teamsAppId, file);
}
catch (e) {
if (e instanceof teamsApp_1.DeveloperPortalAPIFailedSystemError) {
throw this.wrapException(this.wrapResponse(undefined, response), constants_2.APP_STUDIO_API_NAMES.PUBLISH_APP, errors_1.AppStudioError.TeamsAppPublishConflictError.name, errors_1.AppStudioError.TeamsAppPublishConflictError.message(teamsAppId)[0], errors_1.AppStudioError.TeamsAppPublishConflictError.message(teamsAppId)[1]);
}
else {
throw e;
}
}
}
throw this.wrapException(this.wrapResponse(undefined, response), constants_2.APP_STUDIO_API_NAMES.PUBLISH_APP);
}
else {
return response.data.id;
}
}
else {
throw this.wrapException(this.wrapResponse(new Error("empty response"), response), constants_2.APP_STUDIO_API_NAMES.PUBLISH_APP, errors_1.AppStudioError.TeamsAppPublishFailedError.name, errors_1.AppStudioError.TeamsAppPublishFailedError.message(teamsAppId, "POST /api/publishing")[0], errors_1.AppStudioError.TeamsAppPublishFailedError.message(teamsAppId, "POST /api/publishing")[1]);
}
}
catch (e) {
if (e instanceof teamsfx_api_1.SystemError) {
throw e;
}
else {
throw this.wrapException(e, constants_2.APP_STUDIO_API_NAMES.PUBLISH_APP);
}
}
}
/**
* Update existed publish request
* @param teamsAppId
* @param file
* @param token
* @returns
*/
async publishTeamsAppUpdate(token, teamsAppId, file) {
var _a, _b;
try {
// Get App Definition from Teams App Catalog
const appDefinition = await this.getStaggedApp(token, teamsAppId);
const requester = this.createRequesterWithToken(token);
let response = null;
if (appDefinition) {
// update the existing app
response = await RetryHandler.Retry(() => requester.post(`/api/publishing/${appDefinition.teamsAppId}/appdefinitions`, file, {
headers: { "Content-Type": "application/zip" },
}));
}
else {
throw this.wrapException(new Error("API failed"), constants_2.APP_STUDIO_API_NAMES.GET_PUBLISHED_APP, errors_1.AppStudioError.TeamsAppPublishFailedError.name, errors_1.AppStudioError.TeamsAppPublishFailedError.message(teamsAppId, `GET /api/publishing/${teamsAppId}`)[0], errors_1.AppStudioError.TeamsAppPublishFailedError.message(teamsAppId, `GET /api/publishing/${teamsAppId}`)[1]);
}
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
const requestPath = `${(_a = response === null || response === void 0 ? void 0 : response.request) === null || _a === void 0 ? void 0 : _a.method} ${(_b = response === null || response === void 0 ? void 0 : response.request) === null || _b === void 0 ? void 0 : _b.path}`;
if (response && response.data) {
if (response.data.error || response.data.errorMessage) {
throw this.wrapException(this.wrapResponse(undefined, response), constants_2.APP_STUDIO_API_NAMES.UPDATE_PUBLISHED_APP);
}
else {
return response.data.teamsAppId;
}
}
else {
throw this.wrapException(new Error("empty response"), constants_2.APP_STUDIO_API_NAMES.UPDATE_PUBLISHED_APP, errors_1.AppStudioError.TeamsAppPublishFailedError.name, errors_1.AppStudioError.TeamsAppPublishFailedError.message(teamsAppId, requestPath)[0], errors_1.AppStudioError.TeamsAppPublishFailedError.message(teamsAppId, requestPath)[1]);
}
}
catch (error) {
if (error instanceof teamsApp_1.DeveloperPortalAPIFailedSystemError) {
throw error;
}
else {
throw this.wrapException(error, constants_2.APP_STUDIO_API_NAMES.UPDATE_PUBLISHED_APP);
}
}
}
/**
* Get Stagged Teams app from tenant app catalog
* @param teamsAppId manifest.id, which is externalId in app catalog.
* @param token
* @returns
*/
async getStaggedApp(token, teamsAppId) {
const requester = this.createRequesterWithToken(token);
try {
const response = await RetryHandler.Retry(() => requester.get(`/api/publishing/${teamsAppId}`));
if (response && response.data && response.data.value && response.data.value.length > 0) {
const appdefinitions = response.data.value[0].appDefinitions.map((item) => {
return {
lastModifiedDateTime: item.lastModifiedDateTime
? new Date(item.lastModifiedDateTime)
: null,
publishingState: item.publishingState,
teamsAppId: item.teamsAppId,
displayName: item.displayName,
};
});
return appdefinitions[appdefinitions.length - 1];
}
else {
return undefined;
}
}
catch (e) {
return undefined;
}
}
async getUserList(token, teamsAppId) {
const app = await this.getApp(token, teamsAppId);
return app.userList;
}
async checkPermission(token, teamsAppId, userObjectId) {
let userList;
try {
userList = await this.getUserList(token, teamsAppId);
}
catch (error) {
return constants_2.Constants.PERMISSIONS.noPermission;
}
const findUser = userList === null || userList === void 0 ? void 0 : userList.find((user) => user.aadId === userObjectId);
if (!findUser) {
return constants_2.Constants.PERMISSIONS.noPermission;
}
if (findUser.isAdministrator) {
return constants_2.Constants.PERMISSIONS.admin;
}
else {
return constants_2.Constants.PERMISSIONS.operative;
}
}
async grantPermission(token, teamsAppId, newUser) {
var _a;
const app = await this.getApp(token, teamsAppId);
if (this.checkUser(app, newUser)) {
return;
}
(_a = app.userList) === null || _a === void 0 ? void 0 : _a.push(newUser);
let requester;
try {
globalVars_1.TOOLS.logProvider.debug((0, localizeUtils_1.getLocalizedString)("core.common.SendingApiRequest", `${this.getEndpoint()}/api/appdefinitions/{teamsAppId}/owner`, JSON.stringify(app)));
requester = this.createRequesterWithToken(token);
const response = await RetryHandler.Retry(() => requester.post(`/api/appdefinitions/${teamsAppId}/owner`, app));
globalVars_1.TOOLS.logProvider.debug((0, localizeUtils_1.getLocalizedString)("core.common.ReceiveApiResponse", JSON.stringify(response === null || response === void 0 ? void 0 : response.data)));
if (!response || !response.data || !this.checkUser(response.data, newUser)) {
throw new Error(constants_2.ErrorMessages.GrantPermissionFailed);
}
}
catch (err) {
throw this.wrapException(err, constants_2.APP_STUDIO_API_NAMES.UPDATE_OWNER);
}
}
/**
* Send the app package for partner center validation
* @param file
* @param token
* @returns
*/
async partnerCenterAppPackageValidation(token, file) {
const requester = this.createRequesterWithToken(token);
try {
const response = await RetryHandler.Retry(() => requester.post("/api/appdefinitions/partnerCenterAppPackageValidation", file, {
headers: { "Content-Type": "application/zip" },
}));
return response === null || response === void 0 ? void 0 : response.data;
}
catch (e) {
throw this.wrapException(e, constants_2.APP_STUDIO_API_NAMES.VALIDATE_APP_PACKAGE);
}
}
checkUser(app, newUser) {
var _a;
const findUser = (_a = app.userList) === null || _a === void 0 ? void 0 : _a.findIndex((user) => user["aadId"] === newUser.aadId);
if (findUser != undefined && findUser >= 0) {
return true;
}
else {
return false;
}
}
/**
* Submit App Validation Request (In-App) for which App Definitions are stored at TDP.
* @param teamsAppId
* @param token
* @param timeoutSeconds
* @returns
*/
async submitAppValidationRequest(token, teamsAppId) {
const requester = this.createRequesterWithToken(token);
try {
const response = await RetryHandler.Retry(() => requester.post(`/api/v1.0/appvalidations/appdefinition/validate`, {
AppEnvironmentId: null,
appDefinitionId: teamsAppId,
}));
return response === null || response === void 0 ? void 0 : response.data;
}
catch (e) {
throw this.wrapException(e, constants_2.APP_STUDIO_API_NAMES.SUBMIT_APP_VALIDATION);
}
}
/**
* Get App validation requests sumitted by the user
*/
async getAppValidationRequestList(token, teamsAppId) {
const requester = this.createRequesterWithToken(token);
try {
const response = await RetryHandler.Retry(() => requester.get(`/api/v1.0/appvalidations/appdefinitions/${teamsAppId}`));
return response === null || response === void 0 ? void 0 : response.data;
}
catch (e) {
throw this.wrapException(e, constants_2.APP_STUDIO_API_NAMES.GET_APP_VALIDATION_REQUESTS);
}
}
/**
* Get App validation results by provided app validation id
* @param appValidationId
* @param token
* @param timeoutSeconds
* @returns
*/
async getAppValidationById(token, appValidationId) {
const requester = this.createRequesterWithToken(token);
try {
const response = await RetryHandler.Retry(() => requester.get(`/api/v1.0/appvalidations/${appValidationId}`));
return response === null || response === void 0 ? void 0 : response.data;
}
catch (e) {
throw this.wrapException(e, constants_2.APP_STUDIO_API_NAMES.GET_APP_VALIDATION_RESULT);
}
}
async getSideloadingStatus(token) {
var _a, _b, _c, _d, _e, _f, _g;
const apiName = "<check-sideloading-status>";
const apiPath = "/api/usersettings/mtUserAppPolicy";
const requester = this.createRequesterWithToken(token);
let response = undefined;
try {
response = (await RetryHandler.Retry(() => requester.get(apiPath)));
let result;
if (response.status >= 400) {
result = undefined;
}
else {
result = (_b = (_a = response.data) === null || _a === void 0 ? void 0 : _a.value) === null || _b === void 0 ? void 0 : _b.isSideloadingAllowed;
}
if (result !== undefined) {
(0, telemetry_1.sendTelemetryEvent)("TeamsDevPortalClient", telemetry_1.TelemetryEvent.CheckSideloading, {
[telemetry_1.TelemetryProperty.IsSideloadingAllowed]: result.toString() + "",
});
}
else {
(0, telemetry_1.sendTelemetryErrorEvent)("TeamsDevPortalClient", telemetry_1.TelemetryEvent.CheckSideloading, new teamsfx_api_1.SystemError("M365Account", "UnknownValue",
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
`AppStudio response code: ${response.status}, body: ${response.data}`), {
[telemetry_1.TelemetryProperty.CheckSideloadingStatusCode]: `${response.status}`,
[telemetry_1.TelemetryProperty.CheckSideloadingMethod]: "get",
[telemetry_1.TelemetryProperty.CheckSideloadingUrl]: apiName,
});
}
return result;
}
catch (error) {
(0, telemetry_1.sendTelemetryErrorEvent)("TeamsDevPortalClient", telemetry_1.TelemetryEvent.CheckSideloading, new teamsApp_1.CheckSideloadingPermissionFailedError(error, (_e = (_d = (_c = error.response) === null || _c === void 0 ? void 0 : _c.headers) === null || _d === void 0 ? void 0 : _d[constants_2.Constants.CORRELATION_ID]) !== null && _e !== void 0 ? _e : "", apiName, (0, localizeUtils_1.getDefaultString)("error.appstudio.apiFailed.reason.common", ((_f = error.response) === null || _f === void 0 ? void 0 : _f.data) ? `data: ${JSON.stringify(error.response.data)}` : "")), {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
[telemetry_1.TelemetryProperty.CheckSideloadingStatusCode]: `${(_g = error === null || error === void 0 ? void 0 : error.response) === null || _g === void 0 ? void 0 : _g.status}`,
[telemetry_1.TelemetryProperty.CheckSideloadingMethod]: "get",
[telemetry_1.TelemetryProperty.CheckSideloadingUrl]: apiName,
});
}
return undefined;
}
/**
* Create the Api Key registration.
* @param token
* @param apiKeyRegistration
*/
async createApiKeyRegistration(token, apiKeyRegistration) {
const requester = this.createRequesterWithToken(token);
try {
const response = await RetryHandler.Retry(() => requester.post("/api/v1.0/apiSecretRegistrations", apiKeyRegistration));
return response === null || response === void 0 ? void 0 : response.data;
}
catch (e) {
throw this.wrapException(e, constants_2.APP_STUDIO_API_NAMES.CREATE_API_KEY);
}
}
/**
* Get the Api Key registration by Id.
* @param token
* @param apiSecretRegistrationId
*/
async getApiKeyRegistrationById(token, apiSecretRegistrationId) {
const requester = this.createRequesterWithToken(token);
try {
const response = await RetryHandler.Retry(() => requester.get(`/api/v1.0/apiSecretRegistrations/${apiSecretRegistrationId}`));
return response === null || response === void 0 ? void 0 : response.data;
}
catch (e) {
throw this.wrapException(e, constants_2.APP_STUDIO_API_NAMES.GET_API_KEY);
}
}
async updateApiKeyRegistration(token, apiKeyRegistration, apiKeyRegistrationId) {
const requester = this.createRequesterWithToken(token);
try {
const response = await RetryHandler.Retry(() => requester.patch(`/api/v1.0/apiSecretRegistrations/${apiKeyRegistrationId}`, apiKeyRegistration));
return response === null || response === void 0 ? void 0 : response.data;
}
catch (e) {
throw this.wrapException(e, constants_2.APP_STUDIO_API_NAMES.UPDATE_API_KEY);
}
}
async getOauthRegistrationById(token, oauthRegistrationId) {
const requester = this.createRequesterWithToken(token);
try {
const response = await RetryHandler.Retry(() => requester.get(`/api/v1.0/oAuthConfigurations/${oauthRegistrationId}`));
return response === null || response === void 0 ? void 0 : response.data;
}
catch (e) {
throw this.wrapException(e, constants_2.APP_STUDIO_API_NAMES.GET_OAUTH);
}
}
async createOauthRegistration(token, oauthRegistration) {
const requester = this.createRequesterWithToken(token);
try {
const response = await RetryHandler.Retry(() => requester.post("/api/v1.0/oAuthConfigurations", oauthRegistration));
return response === null || response === void 0 ? void 0 : response.data;
}
catch (e) {
throw this.wrapException(e, constants_2.APP_STUDIO_API_NAMES.CREATE_OAUTH);
}
}
async updateOauthRegistration(token, oauthRegistration, oauthRegistrationId) {
const requester = this.createRequesterWithToken(token);
try {
const response = await RetryHandler.Retry(() => requester.patch(`/api/v1.0/oAuthConfigurations/${oauthRegistrationId}`, oauthRegistration));
return response === null || response === void 0 ? void 0 : response.data;
}
catch (e) {
throw this.wrapException(e, constants_2.APP_STUDIO_API_NAMES.UPDATE_OAUTH);
}
}
async getBotRegistration(token, botId) {
const requester = this.createRequesterWithToken(token);
try {
const response = await RetryHandler.Retry(() => requester.get(`/api/botframework/${botId}`));
if ((0, common_1.isHappyResponse)(response)) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return response.data; // response cannot be undefined as it's checked in isHappyResponse.
}
else {
// Defensive code and it should never reach here.
throw this.wrapException(this.wrapResponse(undefined, response), constants_2.APP_STUDIO_API_NAMES.GET_BOT, (0, localizeUtils_1.getDefaultString)("error.appstudio.apiFailed.name.common"), "Failed to get data");
}
}
catch (e) {
this.handleBotFrameworkError(e, constants_2.APP_STUDIO_API_NAMES.GET_BOT);
}
}
async listBots(token) {
const requester = this.createRequesterWithToken(token);
try {
const response = await RetryHandler.Retry(() => requester.get("/api/botframework"));
if ((0, common_1.isHappyResponse)(response)) {
return response.data; // response cannot be undefined as it's checked in isHappyResponse.
}
else {
// Defensive code and it should never reach here.
throw this.wrapException(this.wrapResponse(undefined, response), constants_2.APP_STUDIO_API_NAMES.LIST_BOT, (0, localizeUtils_1.getDefaultString)("error.appstudio.apiFailed.name.common"), "Failed to get data");
}
}
catch (e) {
this.handleBotFrameworkError(e, constants_2.APP_STUDIO_API_NAMES.LIST_BOT);
}
}
async deleteBot(token, botId) {
const requester = this.createRequesterWithToken(token);
try {
await RetryHandler.Retry(() => requester.delete(`/api/botframework/${botId}`));
}
catch (e) {
this.handleBotFrameworkError(e, constants_2.APP_STUDIO_API_NAMES.DELETE_BOT);
}
}
async createBotRegistration(token, registration, checkExistence = true) {
if (registration.botId && checkExistence) {
const botReg = await this.getBotRegistration(token, registration.botId);
if (botReg) {
globalVars_1.TOOLS.logProvider.info(messages_1.Messages.BotResourceExist("Appstudio"));
return;
}
}
const requester = this.createRequesterWithToken(token);
try {
const response = await RetryHandler.Retry(() => requester.post(`/api/botframework`, registration));
if (!(0, common_1.isHappyResponse)(response)) {
throw new errors_2.ProvisionError(strings_1.CommonStrings.APP_STUDIO_BOT_REGISTRATION);
}
}
catch (e) {
this.handleBotFrameworkError(e, constants_2.APP_STUDIO_API_NAMES.CREATE_BOT);
}
}
async updateMessageEndpoint(token, botId, endpoint) {
const botReg = await this.getBotRegistration(token, botId);
if (!botReg) {
throw new errors_2.BotRegistrationNotFoundError(botId);
}
botReg.messagingEndpoint = endpoint;
if (botReg.configuredChannels === undefined || botReg.configuredChannels.length === 0) {
botReg.configuredChannels = [IBotRegistration_1.BotChannelType.MicrosoftTeams];
}
await this.updateBotRegistration(token, botReg);
}
async updateBotRegistration(token, botReg) {
const requester = this.createRequesterWithToken(token);
try {
const response = await RetryHandler.Retry(() => requester.post(`/api/botframework/${botReg.botId}`, botReg));
if (!(0, common_1.isHappyResponse)(response)) {
throw new errors_2.ConfigUpdatingError(strings_1.ConfigNames.MESSAGE_ENDPOINT);
}
}
catch (e) {
this.handleBotFrameworkError(e, constants_2.APP_STUDIO_API_NAMES.UPDATE_BOT);
}
}
handleBotFrameworkError(e, apiName) {
var _a, _b, _c, _d;
if (((_a = e.response) === null || _a === void 0 ? void 0 : _a.status) === commonConstant_1.HttpStatusCode.NOTFOUND) {
return undefined; // Stands for NotFound.
}
else if (((_b = e.response) === null || _b === void 0 ? void 0 : _b.status) === commonConstant_1.HttpStatusCode.UNAUTHORIZED) {
throw new errors_2.BotFrameworkNotAllowedToAcquireTokenError();
}
else if (((_c = e.response) === null || _c === void 0 ? void 0 : _c.status) === commonConstant_1.HttpStatusCode.FORBIDDEN) {
throw new errors_2.BotFrameworkForbiddenResultError();
}
else if (((_d = e.response) === null || _d === void 0 ? void 0 : _d.status) === commonConstant_1.HttpStatusCode.TOOMANYREQS) {
throw new errors_2.BotFrameworkConflictResultError();
}
else {
e.teamsfxUrlName = constants_3.TeamsFxUrlNames[apiName];
throw this.wrapException(e, apiName);
}
}
wrapResponse(e, response) {
var _a;
const error = new Error((e === null || e === void 0 ? void 0 : e.message) || ((_a = response === null || response === void 0 ? void 0 : response.data.error) === null || _a === void 0 ? void 0 : _a.message) || (response === null || response === void 0 ? void 0 : response.data.errorMessage));
error.response = response;
error.request = response === null || response === void 0 ? void 0 : response.request;
return error;
}
wrapException(e, apiName, name = (0, localizeUtils_1.getDefaultString)("error.appstudio.apiFailed.name.common"), potentialReason = (0, localizeUtils_1.getDefaultString)("error.appstudio.apiFailed.reason.common"), disPlayMessage, isUserError = false, helpLink) {
var _a, _b, _c, _d, _e;
e.name = name;
const correlationId = (_b = (_a = e.response) === null || _a === void 0 ? void 0 : _a.headers) === null || _b === void 0 ? void 0 : _b[constants_2.Constants.CORRELATION_ID];
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
let extraData = `${potentialReason} ${((_c = e.response) === null || _c === void 0 ? void 0 : _c.data) ? `data: ${JSON.stringify(e.response.data)}` : ""}`;
// add status code in extra data if the message does not have it.
if (!((_d = e.message) === null || _d === void 0 ? void 0 : _d.toLowerCase().includes("status code")) && ((_e = e.response) === null || _e === void 0 ? void 0 : _e.status)) {
extraData = `Status code: ${e.response.status}. ${extraData}`;
}
let error;
if (isUserError) {
error = new teamsApp_1.DeveloperPortalAPIFailedUserError(e, correlationId, apiName, extraData, disPlayMessage, helpLink);
}
else {
error = new teamsApp_1.DeveloperPortalAPIFailedSystemError(e, correlationId, apiName, extraData, disPlayMessage);
}
return error;
}
}
tslib_1.__decorate([
(0, hooks_1.hooks)([(0, globalVars_1.ErrorContextMW)({ source: "Teams", component: "TeamsDevPortalClient" })]),
tslib_1.__metadata("design:type", Function),
tslib_1.__metadata("design:paramtypes", [String, Buffer, Object]),
tslib_1.__metadata("design:returntype", Promise)
], TeamsDevPortalClient.prototype, "importApp", null);
tslib_1.__decorate([
(0, hooks_1.hooks)([(0, globalVars_1.ErrorContextMW)({ source: "Teams", component: "TeamsDevPortalClient" })]),
tslib_1.__metadata("design:type", Function),
tslib_1.__metadata("design:paramtypes", [String]),
tslib_1.__metadata("design:returntype", Promise)
], TeamsDevPortalClient.prototype, "listApps", null);
tslib_1.__decorate([
(0, hooks_1.hooks)([(0, globalVars_1.ErrorContextMW)({ source: "Teams", component: "TeamsDevPortalClient" })]),
tslib_1.__metadata("design:type", Function),
tslib_1.__metadata("design:paramtypes", [String, String]),
tslib_1.__metadata("design:returntype", Promise)
], TeamsDevPortalClient.prototype, "deleteApp", null);
tslib_1.__decorate([
(0, hooks_1.hooks)([(0, globalVars_1.ErrorContextMW)({ source: "Teams", component: "TeamsDevPortalClient" })]),
tslib_1.__metadata("design:type", Function),
tslib_1.__metadata("design:paramtypes", [String, String]),
tslib_1.__metadata("design:returntype", Promise)
], TeamsDevPortalClient.prototype, "getApp", null);
tslib_1.__decorate([
(0, hooks_1.hooks)([(0, globalVars_1.ErrorContextMW)({ source: "Teams", component: "TeamsDevPortalClient" })]),
tslib_1.__metadata("design:type", Function),
tslib_1.__metadata("design:paramtypes", [String, String]),
tslib_1.__metadata("design:returntype", Promise)
], TeamsDevPortalClient.prototype, "getBotId", null);
tslib_1.__decorate([
(0, hooks_1.hooks)([(0, globalVars_1.ErrorContextMW)({ source: "Teams", component: "TeamsDevPortalClient" })]),
tslib_1.__metadata("design:type", Function),
tslib_1.__metadata("design:paramtypes", [String, String]),
tslib_1.__metadata("design:returntype", Promise)
], TeamsDevPortalClient.prototype, "getAppPackage", null);
tslib_1.__decorate([
(0, hooks_1.hooks)([(0, globalVars_1.ErrorContextMW)({ source: "Teams", component: "TeamsDevPortalClient" })]),
tslib_1.__metadata("design:type", Function),
tslib_1.__metadata("design:paramtypes", [String, String]),
tslib_1.__metadata("design:returntype", Promise)
], TeamsDevPortalClient.prototype, "checkExistsInTenant", null);
tslib_1.__decorate([
(0, hooks_1.hooks)([(0, globalVars_1.ErrorContextMW)({ source: "Teams", component: "TeamsDevPortalClient" })]),
tslib_1.__metadata("design:type", Function),
tslib_1.__metadata("design:paramtypes", [String, String, Buffer]),
tslib_1.__metadata("design:returntype", Promise)
], TeamsDevPortalClient.prototype, "publishTeamsApp", null);
tslib_1.__decorate([
(0, hooks_1.hooks)([(0, globalVars_1.ErrorContextMW)({ source: "Teams", component: "TeamsDevPortalClient" })]),
tslib_1.__metadata("design:type", Function),
tslib_1.__metadata("design:paramtypes", [String, String, Buffer]),
tslib_1.__metadata("design:returntype", Promise)
], TeamsDevPortalClient.prototype, "publishTeamsAppUpdate", null);
tslib_1.__decorate([
(0, hooks_1.hooks)([(0, globalVars_1.ErrorContextMW)({ source: "Teams", component: "TeamsDevPortalClient" })]),
tslib_1.__metadata("design:type", Function),
tslib_1.__metadata("design:paramtypes", [String, String]),
tslib_1.__metadata("design:returntype", Promise)
], TeamsDevPortalClient.prototype, "getStaggedApp", null);
tslib_1.__decorate([
(0, hooks_1.hooks)([(0, globalVars_1.ErrorContextMW)({ source: "Teams", component: "TeamsDevPortalClient" })]),
tslib_1.__metadata("design:type", Function),
tslib_1.__metadata("design:paramtypes", [String, String]),
tslib_1.__metadata("design:returntype", Promise)
], TeamsDevPortalClient.prototype, "getUserList", null);
tslib_1.__decorate([
(0, hooks_1.hooks)([(0, globalVars_1.ErrorContextMW)({ source: "Teams", component: "TeamsDevPortalClient" })]),
tslib_1.__metadata("design:type", Function),
tslib_1.__metadata("design:paramtypes", [String, String, String]),
tslib_1.__metadata("design:returntype", Promise)
], TeamsDevPortalClient.prototype, "checkPermission", null);
tslib_1.__decorate([
(0, hooks_1.hooks)([(0, globalVars_1.ErrorContextMW)({ source: "Teams", component: "TeamsDevPortalClient" })]),
tslib_1.__metadata("design:type", Function),
tslib_1.__metadata("design:paramtypes", [String, String, Object]),
tslib_1.__metadata("design:returntype", Promise)
], TeamsDevPortalClient.prototype, "grantPermission", null);
tslib_1.__decorate([
(0, hooks_1.hooks)([(0, globalVars_1.ErrorContextMW)({ source: "Teams", component: "TeamsDevPortalClient" })]),
tslib_1.__metadata("design:type", Function),
tslib_1.__metadata("design:paramtypes", [String, Buffer]),
tslib_1.__metadata("design:returntype", Promise)
], TeamsDevPortalClient.prototype, "partnerCenterAppPackageValidation", null);
tslib_1.__decorate([
(0, hooks_1.hooks)([(0, globalVars_1.ErrorContextMW)({ source: "Teams", component: "TeamsDevPortalClient" })]),
tslib_1.__metadata("design:type", Function),
tslib_1.__metadata("design:paramtypes", [String, String]),
tslib_1.__metadata("design:returntype", Promise)
], TeamsDevPortalClient.prototype, "submitAppValidationRequest", null);
tslib_1.__decorate([
(0, hooks_1.hooks)([(0, globalVars_1.ErrorContextMW)({ source: "Teams", component: "TeamsDevPortalClient" })]),
tslib_1.__metadata("design:type", Function),
tslib_1.__metadata("design:paramtypes", [String, String]),
tslib_1.__metadata("design:returntype", Promise)
], TeamsDevPortalClient.prototype, "getAppValidationRequestList", null);
tslib_1.__decorate([
(0, hooks_1.hooks)([(0, globalVars_1.ErrorContextMW)({ source: "Teams", component: "TeamsDevPortalClient" })]),
tslib_1.__metadata("design:type", Function),
tslib_1.__metadata("design:paramtypes", [String, String]),
tslib_1.__metadata("design:returntype", Promise)
], TeamsDevPortalClient.prototype, "getAppValidationById", null);
tslib_1.__decorate([
(0, hooks_1.hooks)([(0, globalVars_1.ErrorContextMW)({ source: "Teams", component: "TeamsDevPortalClient" })]),
tslib_1.__metadata("design:type", Function),
tslib_1.__metadata("design:paramtypes", [String]),
tslib_1.__metadata("design:returntype", Promise)
], TeamsDevPortalClient.prototype, "getSideloadingStatus", null);
tslib_1.__decorate([
(0, hooks_1.hooks)([(0, globalVars_1.ErrorContextMW)({ source: "Teams", component: "TeamsDevPortalClient" })]),
tslib_1.__metadata("design:type", Function),
tslib_1.__metadata("design:paramtypes", [String, Object]),
tslib_1.__metadata("design:returntype", Promise)
], TeamsDevPortalClient.prototype, "createApiKeyRegistration", null);
tslib_1.__decorate([
(0, hooks_1.hooks)([(0, globalVars_1.ErrorContextMW)({ source: "Teams", component: "TeamsDevPortalClient" })]),
tslib_1.__metadata("design:type", Function),
tslib_1.__metadata("design:paramtypes", [String, String]),
tslib_1.__metadata("design:returntype", Promise)
], TeamsDevPortalClient.prototype, "getApiKeyRegistrationById", null);
tslib_1.__decorate([
(0, hooks_1.hooks)([(0, globalVars_1.ErrorContextMW)({ source: "Teams", component: "TeamsDevPortalClient" })]),
tslib_1.__metadata("design:type", Function),
tslib_1.__metadata("design:paramtypes", [String, Object, String]),
tslib_1.__metadata("design:returntype", Promise)
], TeamsDevPortalClient.prototype, "updateApiKeyRegistration", null);
tslib_1.__decorate([
(0, hooks_1.hooks)([(0, globalVars_1.ErrorContextMW)({ source: "Teams", component: "TeamsDevPortalClient" })]),
tslib_1.__metadata("design:type", Function),
tslib_1.__metadata("design:paramtypes", [String, String]),
tslib_1.__metadata("design:returntype", Promise)
], TeamsDevPortalClient.prototype, "getOauthRegistrationById", null);
tslib_1.__decorate([
(0, hooks_1.hooks)([(0, globalVars_1.ErrorContextMW)({ source: "Teams", component: "TeamsDevPortalClient" })]),
tslib_1.__metadata("design:type", Function),
tslib_1.__metadata("design:paramtypes", [String, Object]),
tslib_1.__metadata("design:returntype", Promise)
], TeamsDevPortalClient.prototype, "createOauthRegistration", null);
tslib_1.__decorate([
(0, hooks_1.hooks)([(0, globalVars_1.ErrorContextMW)({ source: "Teams", component: "TeamsDevPortalClient" })]),
tslib_1.__metadata("design:type", Function),
tslib_1.__metadata("design:paramtypes", [String, Object, String]),
tslib_1.__metadata("design:returntype", Promise)
], TeamsDevPortalClient.prototype, "updateOauthRegistration", null);
tslib_1.__decorate([
(0, hooks_1.hooks)([(0, globalVars_1.ErrorContextMW)({ source: "Teams", component: "TeamsDevPortalClient" })]),
tslib_1.__metadata("design:type", Function),
tslib_1.__metadata("design:paramtypes", [String, String]),
tslib_1.__metadata("design:returntype", Promise)
], TeamsDevPortalClient.prototype, "getBotRegistration", null);
tslib_1.__decorate([
(0, hooks_1.hooks)([(0, globalVars_1.ErrorContextMW)({ source: "Teams", component: "TeamsDevPortalClient" })]),
tslib_1.__metadata("design:type", Function),
tslib_1.__metadata("design:paramtypes", [String]),
tslib_1.__metadata("design:returntype", Promise)
], TeamsDevPortalClient.prototype, "listBots", null);
tslib_1.__decorate([
(0, hooks_1.hooks)([(0, globalVars_1.ErrorContextMW)({ source: "Teams", component: "TeamsDevPortalClient" })]),
tslib_1.__metadata("design:type", Function),
tslib_1.__metadata("design:paramtypes", [String, String]),
tslib_1.__metadata("design:returntype", Promise)
], TeamsDevPortalClient.prototype, "deleteBot", null);
tslib_1.__decorate([
(0, hooks_1.hooks)([(0, globalVars_1.ErrorContextMW)({ source: "Teams", component: "TeamsDevPortalClient" })]),
tslib_1.__metadata("design:type", Function),
tslib_1.__metadata("design:paramtypes", [String, Object, Object]),
tslib_1.__metadata("design:returntype", Promise)
], TeamsDevPortalClient.prototype, "createBotRegistration", null);
tslib_1.__decorate([
(0, hooks_1.hooks)([(0, globalVars_1.ErrorContextMW)({ source: "Teams", component: "TeamsDevPortalClient" })]),
tslib_1.__metadata("design:type", Function),
tslib_1.__metadata("design:paramtypes", [String, String, String]),
tslib_1.__metadata("design:returntype", Promise)
], TeamsDevPortalClient.prototype, "updateMessageEndpoint", null);
tslib_1.__decorate([
(0, hooks_1.hooks)([(0, globalVars_1.ErrorContextMW)({ source: "Teams", component: "TeamsDevPortalClient" })]),
tslib_1.__metadata("design:type", Function),
tslib_1.__metadata("design:paramtypes", [String, Object]),
tslib_1.__metadata("design:returntype", Promise)
], TeamsDevPortalClient.prototype, "updateBotRegistration", null);
exports.TeamsDevPortalClient = TeamsDevPortalClient;
exports.teamsDevPortalClient = new TeamsDevPortalClient();
//# sourceMappingURL=teamsDevPortalClient.js.map
File diff suppressed because one or more lines are too long
+3
View File
@@ -0,0 +1,3 @@
import { AzureAccountProvider, FxError, Result, SubscriptionInfo, UserInteraction } from "@microsoft/teamsfx-api";
export declare function askSubscription(azureAccountProvider: AzureAccountProvider, ui: UserInteraction, activeSubscriptionId?: string): Promise<Result<SubscriptionInfo, FxError>>;
//# sourceMappingURL=azureUtils.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"azureUtils.d.ts","sourceRoot":"","sources":["../../src/common/azureUtils.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,oBAAoB,EACpB,OAAO,EAEP,MAAM,EACN,gBAAgB,EAGhB,eAAe,EAGhB,MAAM,wBAAwB,CAAC;AAGhC,wBAAsB,eAAe,CACnC,oBAAoB,EAAE,oBAAoB,EAC1C,EAAE,EAAE,eAAe,EACnB,oBAAoB,CAAC,EAAE,MAAM,GAC5B,OAAO,CAAC,MAAM,CAAC,gBAAgB,EAAE,OAAO,CAAC,CAAC,CAqD5C"}
+50
View File
@@ -0,0 +1,50 @@
"use strict";
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.askSubscription = void 0;
const teamsfx_api_1 = require("@microsoft/teamsfx-api");
const localizeUtils_1 = require("./localizeUtils");
async function askSubscription(azureAccountProvider, ui, activeSubscriptionId) {
const subscriptions = await azureAccountProvider.listSubscriptions();
if (subscriptions.length === 0) {
return (0, teamsfx_api_1.err)(new teamsfx_api_1.UserError("Core", "NoSubscriptionFound", (0, localizeUtils_1.getDefaultString)("error.NoSubscriptionFound"), (0, localizeUtils_1.getLocalizedString)("error.NoSubscriptionFound")));
}
let resultSub = subscriptions.find((sub) => sub.subscriptionId === activeSubscriptionId);
if (activeSubscriptionId === undefined || resultSub === undefined) {
let selectedSub = undefined;
if (subscriptions.length === 1) {
selectedSub = subscriptions[0];
}
else {
const options = subscriptions.map((sub) => {
return {
id: sub.subscriptionId,
label: sub.subscriptionName,
data: sub.tenantId,
};
});
const askRes = await ui.selectOption({
name: "subscription",
title: "Select a subscription",
options: options,
returnObject: true,
});
if (askRes.isErr())
return (0, teamsfx_api_1.err)(askRes.error);
const subItem = askRes.value.result;
selectedSub = {
subscriptionId: subItem.id,
subscriptionName: subItem.label,
tenantId: subItem.data,
};
}
if (selectedSub === undefined) {
return (0, teamsfx_api_1.err)(new teamsfx_api_1.SystemError("Core", "NoSubscriptionFound", (0, localizeUtils_1.getDefaultString)("error.NoSubscriptionFound"), (0, localizeUtils_1.getLocalizedString)("error.NoSubscriptionFound")));
}
resultSub = selectedSub;
}
return (0, teamsfx_api_1.ok)(resultSub);
}
exports.askSubscription = askSubscription;
//# sourceMappingURL=azureUtils.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"azureUtils.js","sourceRoot":"","sources":["../../src/common/azureUtils.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAElC,wDAWgC;AAChC,mDAAuE;AAEhE,KAAK,UAAU,eAAe,CACnC,oBAA0C,EAC1C,EAAmB,EACnB,oBAA6B;IAE7B,MAAM,aAAa,GAAuB,MAAM,oBAAoB,CAAC,iBAAiB,EAAE,CAAC;IAEzF,IAAI,aAAa,CAAC,MAAM,KAAK,CAAC,EAAE;QAC9B,OAAO,IAAA,iBAAG,EACR,IAAI,uBAAS,CACX,MAAM,EACN,qBAAqB,EACrB,IAAA,gCAAgB,EAAC,2BAA2B,CAAC,EAC7C,IAAA,kCAAkB,EAAC,2BAA2B,CAAC,CAChD,CACF,CAAC;KACH;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AA2B,CAAC,CAChD,CACF,CAAC;SACH;QACD,SAAS,GAAG,WAAW,CAAC;KACzB;IACD,OAAO,IAAA,gBAAE,EAAC,SAAS,CAAC,CAAC;AACvB,CAAC;AAzDD,0CAyDC"}
+41
View File
@@ -0,0 +1,41 @@
export declare class ConstantString {
static readonly UTF8Encoding = "utf-8";
static readonly DeploymentResourceType = "Microsoft.Resources/deployments";
static readonly DeploymentNotFound = "DeploymentNotFound";
static readonly RootFolder = "TeamsApps";
}
export declare class HelpLinks {
static readonly WhyNeedProvision = "https://aka.ms/teamsfx/whyneedprovision";
static readonly SwitchTenant = "https://aka.ms/teamsfx-switch-tenant";
}
export declare class VSCodeExtensionCommand {
static readonly showOutputChannel = "command:fx-extension.showOutputChannel";
static readonly openFolder = "command:fx-extension.openFolder";
static readonly openReadme = "command:fx-extension.openReadMe?%5B%22Notification%22%5D";
}
export declare class TeamsClientId {
static readonly MobileDesktop = "1fec8e78-bce4-4aaf-ab1b-5451cc387264";
static readonly Web = "5e3ce6c0-2b1f-4285-8d4b-75ee78787346";
}
export declare class OfficeClientId {
static readonly Desktop = "0ec893e0-5785-4de6-99da-4ed124e5296c";
static readonly Web1 = "4345a7b9-9a63-4910-a426-35363201d503";
static readonly Web2 = "4765445b-32c6-49b0-83e6-1d93765276ca";
}
export declare class OutlookClientId {
static readonly Desktop = "d3590ed6-52b3-4102-aeff-aad2292ab01c";
static readonly Web1 = "00000002-0000-0ff1-ce00-000000000000";
static readonly Web2 = "bc59ab01-8403-45c6-8796-ac3ef710b3e3";
static readonly Mobile = "27922004-5251-4030-b22d-91ecd9a37ea4";
}
export declare function getAllowedAppMaps(): Record<string, string>;
export declare function getResourceGroupInPortal(subscriptionId?: string, tenantId?: string, resourceGroupName?: string): string | undefined;
export declare function getAppStudioEndpoint(): string;
export declare const AuthSvcScopes: string[];
export declare const GraphScopes: string[];
export declare const GraphReadUserScopes: string[];
export declare const SPFxScopes: (tenant: string) => string[];
export declare const AzureScopes: string[];
export declare const AppStudioScopes: string[];
export declare const SpecParserSource = "SpecParser";
//# sourceMappingURL=constants.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../src/common/constants.ts"],"names":[],"mappings":"AAIA,qBAAa,cAAc;IACzB,MAAM,CAAC,QAAQ,CAAC,YAAY,WAAW;IACvC,MAAM,CAAC,QAAQ,CAAC,sBAAsB,qCAAqC;IAC3E,MAAM,CAAC,QAAQ,CAAC,kBAAkB,wBAAwB;IAC1D,MAAM,CAAC,QAAQ,CAAC,UAAU,eAAe;CAC1C;AAED,qBAAa,SAAS;IACpB,MAAM,CAAC,QAAQ,CAAC,gBAAgB,6CAA6C;IAC7E,MAAM,CAAC,QAAQ,CAAC,YAAY,0CAA0C;CACvE;AAED,qBAAa,sBAAsB;IACjC,MAAM,CAAC,QAAQ,CAAC,iBAAiB,4CAA4C;IAC7E,MAAM,CAAC,QAAQ,CAAC,UAAU,qCAAqC;IAC/D,MAAM,CAAC,QAAQ,CAAC,UAAU,8DAA8D;CACzF;AAED,qBAAa,aAAa;IACxB,MAAM,CAAC,QAAQ,CAAC,aAAa,0CAA0C;IACvE,MAAM,CAAC,QAAQ,CAAC,GAAG,0CAA0C;CAC9D;AAED,qBAAa,cAAc;IACzB,MAAM,CAAC,QAAQ,CAAC,OAAO,0CAA0C;IACjE,MAAM,CAAC,QAAQ,CAAC,IAAI,0CAA0C;IAC9D,MAAM,CAAC,QAAQ,CAAC,IAAI,0CAA0C;CAC/D;AAED,qBAAa,eAAe;IAC1B,MAAM,CAAC,QAAQ,CAAC,OAAO,0CAA0C;IACjE,MAAM,CAAC,QAAQ,CAAC,IAAI,0CAA0C;IAC9D,MAAM,CAAC,QAAQ,CAAC,IAAI,0CAA0C;IAC9D,MAAM,CAAC,QAAQ,CAAC,MAAM,0CAA0C;CACjE;AAED,wBAAgB,iBAAiB,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAW1D;AAGD,wBAAgB,wBAAwB,CACtC,cAAc,CAAC,EAAE,MAAM,EACvB,QAAQ,CAAC,EAAE,MAAM,EACjB,iBAAiB,CAAC,EAAE,MAAM,GACzB,MAAM,GAAG,SAAS,CAMpB;AACD,wBAAgB,oBAAoB,IAAI,MAAM,CAM7C;AAED,eAAO,MAAM,aAAa,UAAoD,CAAC;AAC/E,eAAO,MAAM,WAAW,UAAoE,CAAC;AAC7F,eAAO,MAAM,mBAAmB,UAAqD,CAAC;AACtF,eAAO,MAAM,UAAU,WAAY,MAAM,aAAwC,CAAC;AAClF,eAAO,MAAM,WAAW,UAA6D,CAAC;AACtF,eAAO,MAAM,eAAe,UAAyD,CAAC;AACtF,eAAO,MAAM,gBAAgB,eAAe,CAAC"}
+83
View File
@@ -0,0 +1,83 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpecParserSource = exports.AppStudioScopes = exports.AzureScopes = exports.SPFxScopes = exports.GraphReadUserScopes = exports.GraphScopes = exports.AuthSvcScopes = exports.getAppStudioEndpoint = exports.getResourceGroupInPortal = exports.getAllowedAppMaps = exports.OutlookClientId = exports.OfficeClientId = exports.TeamsClientId = exports.VSCodeExtensionCommand = exports.HelpLinks = exports.ConstantString = void 0;
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
const localizeUtils_1 = require("./localizeUtils");
class ConstantString {
}
exports.ConstantString = ConstantString;
ConstantString.UTF8Encoding = "utf-8";
ConstantString.DeploymentResourceType = "Microsoft.Resources/deployments";
ConstantString.DeploymentNotFound = "DeploymentNotFound";
ConstantString.RootFolder = "TeamsApps";
class HelpLinks {
}
exports.HelpLinks = HelpLinks;
HelpLinks.WhyNeedProvision = "https://aka.ms/teamsfx/whyneedprovision";
HelpLinks.SwitchTenant = "https://aka.ms/teamsfx-switch-tenant";
class VSCodeExtensionCommand {
}
exports.VSCodeExtensionCommand = VSCodeExtensionCommand;
VSCodeExtensionCommand.showOutputChannel = "command:fx-extension.showOutputChannel";
VSCodeExtensionCommand.openFolder = "command:fx-extension.openFolder";
VSCodeExtensionCommand.openReadme = "command:fx-extension.openReadMe?%5B%22Notification%22%5D";
class TeamsClientId {
}
exports.TeamsClientId = TeamsClientId;
TeamsClientId.MobileDesktop = "1fec8e78-bce4-4aaf-ab1b-5451cc387264";
TeamsClientId.Web = "5e3ce6c0-2b1f-4285-8d4b-75ee78787346";
class OfficeClientId {
}
exports.OfficeClientId = OfficeClientId;
OfficeClientId.Desktop = "0ec893e0-5785-4de6-99da-4ed124e5296c";
OfficeClientId.Web1 = "4345a7b9-9a63-4910-a426-35363201d503";
OfficeClientId.Web2 = "4765445b-32c6-49b0-83e6-1d93765276ca";
class OutlookClientId {
}
exports.OutlookClientId = OutlookClientId;
OutlookClientId.Desktop = "d3590ed6-52b3-4102-aeff-aad2292ab01c";
OutlookClientId.Web1 = "00000002-0000-0ff1-ce00-000000000000";
OutlookClientId.Web2 = "bc59ab01-8403-45c6-8796-ac3ef710b3e3";
OutlookClientId.Mobile = "27922004-5251-4030-b22d-91ecd9a37ea4";
function getAllowedAppMaps() {
return {
[TeamsClientId.MobileDesktop]: (0, localizeUtils_1.getLocalizedString)("core.common.TeamsMobileDesktopClientName"),
[TeamsClientId.Web]: (0, localizeUtils_1.getLocalizedString)("core.common.TeamsWebClientName"),
[OfficeClientId.Desktop]: (0, localizeUtils_1.getLocalizedString)("core.common.OfficeDesktopClientName"),
[OfficeClientId.Web1]: (0, localizeUtils_1.getLocalizedString)("core.common.OfficeWebClientName1"),
[OfficeClientId.Web2]: (0, localizeUtils_1.getLocalizedString)("core.common.OfficeWebClientName2"),
[OutlookClientId.Desktop]: (0, localizeUtils_1.getLocalizedString)("core.common.OutlookDesktopClientName"),
[OutlookClientId.Web1]: (0, localizeUtils_1.getLocalizedString)("core.common.OutlookWebClientName1"),
[OutlookClientId.Web2]: (0, localizeUtils_1.getLocalizedString)("core.common.OutlookWebClientName2"),
};
}
exports.getAllowedAppMaps = getAllowedAppMaps;
const AzurePortalUrl = "https://portal.azure.com";
function getResourceGroupInPortal(subscriptionId, tenantId, resourceGroupName) {
if (subscriptionId && tenantId && resourceGroupName) {
return `${AzurePortalUrl}/#@${tenantId}/resource/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}`;
}
else {
return undefined;
}
}
exports.getResourceGroupInPortal = getResourceGroupInPortal;
function getAppStudioEndpoint() {
if (process.env.APP_STUDIO_ENV && process.env.APP_STUDIO_ENV === "int") {
return "https://dev-int.teams.microsoft.com";
}
else {
return "https://dev.teams.microsoft.com";
}
}
exports.getAppStudioEndpoint = getAppStudioEndpoint;
exports.AuthSvcScopes = ["https://api.spaces.skype.com/Region.ReadWrite"];
exports.GraphScopes = ["Application.ReadWrite.All", "TeamsAppInstallation.ReadForUser"];
exports.GraphReadUserScopes = ["https://graph.microsoft.com/User.ReadBasic.All"];
const SPFxScopes = (tenant) => [`${tenant}/Sites.FullControl.All`];
exports.SPFxScopes = SPFxScopes;
exports.AzureScopes = ["https://management.core.windows.net/user_impersonation"];
exports.AppStudioScopes = [`${getAppStudioEndpoint()}/AppDefinitions.ReadWrite`];
exports.SpecParserSource = "SpecParser";
//# sourceMappingURL=constants.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/common/constants.ts"],"names":[],"mappings":";;;AAAA,uCAAuC;AACvC,kCAAkC;AAClC,mDAAqD;AAErD,MAAa,cAAc;;AAA3B,wCAKC;AAJiB,2BAAY,GAAG,OAAO,CAAC;AACvB,qCAAsB,GAAG,iCAAiC,CAAC;AAC3D,iCAAkB,GAAG,oBAAoB,CAAC;AAC1C,yBAAU,GAAG,WAAW,CAAC;AAG3C,MAAa,SAAS;;AAAtB,8BAGC;AAFiB,0BAAgB,GAAG,yCAAyC,CAAC;AAC7D,sBAAY,GAAG,sCAAsC,CAAC;AAGxE,MAAa,sBAAsB;;AAAnC,wDAIC;AAHiB,wCAAiB,GAAG,wCAAwC,CAAC;AAC7D,iCAAU,GAAG,iCAAiC,CAAC;AAC/C,iCAAU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E1B,IAAI,cAAc,IAAI,QAAQ,IAAI,iBAAiB,EAAE;QACnD,OAAO,GAAG,cAAc,MAAM,QAAQ,2BAA2B,cAAc,mBAAmB,iBAAiB,EAAE,CAAC;KACvH;SAAM;QACL,OAAO,SAAS,CAAC;KAClB;AACH,CAAC;AAVD,4DAUC;AACD,SAAgB,oBAAoB;IAClC,IAAI,OAAO,CAAC,GAAG,CAAC,cAAc,IAAI,OAAO,CAAC,GAAG,CAAC,cAAc,KAAK,KAAK,EAAE;QACtE,OAAO,qCAAqC,CAAC;KAC9C;SAAM;QACL,OAAO,iCAAiC,CAAC;KAC1C;AACH,CAAC;AAND,oDAMC;AAEY,QAAA,aAAa,GAAG,CAAC,+CAA+C,CAAC,CAAC;AAClE,QAAA,WAAW,GAAG,CAAC,2BAA2B,EAAE,kCAAkC,CAAC,CAAC;AAChF,QAAA,mBAAmB,GAAG,CAAC,gDAAgD,CAAC,CAAC;AAC/E,MAAM,UAAU,GAAG,CAAC,MAAc,EAAE,EAAE,CAAC,CAAC,GAAG,MAAM,wBAAwB,CAAC,CAAC;AAArE,QAAA,UAAU,cAA2D;AACrE,QAAA,WAAW,GAAG,CAAC,wDAAwD,CAAC,CAAC;AACzE,QAAA,eAAe,GAAG,CAAC,GAAG,oBAAoB,EAAE,2BAA2B,CAAC,CAAC;AACzE,QAAA,gBAAgB,GAAG,YAAY,CAAC"}
+7
View File
@@ -0,0 +1,7 @@
export declare class Correlator {
static setId(): string;
static run<T extends unknown[], R>(work: (...args: [...T]) => R, ...args: [...T]): R;
static runWithId<T extends unknown[], R>(id: string, work: (...args: [...T]) => R, ...args: [...T]): R;
static getId(): string;
}
//# sourceMappingURL=correlator.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"correlator.d.ts","sourceRoot":"","sources":["../../src/common/correlator.ts"],"names":[],"mappings":"AASA,qBAAa,UAAU;IACrB,MAAM,CAAC,KAAK,IAAI,MAAM;IAKtB,MAAM,CAAC,GAAG,CAAC,CAAC,SAAS,OAAO,EAAE,EAAE,CAAC,EAAE,IAAI,EAAE,CAAC,GAAG,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,EAAE,GAAG,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC;IAKpF,MAAM,CAAC,SAAS,CAAC,CAAC,SAAS,OAAO,EAAE,EAAE,CAAC,EACrC,EAAE,EAAE,MAAM,EACV,IAAI,EAAE,CAAC,GAAG,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,EAC5B,GAAG,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC,GACd,CAAC;IAKJ,MAAM,CAAC,KAAK,IAAI,MAAM;CAIvB"}
+30
View File
@@ -0,0 +1,30 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Correlator = void 0;
const tslib_1 = require("tslib");
const async_hooks_1 = require("async_hooks");
const uuid = tslib_1.__importStar(require("uuid"));
const asyncLocalStorage = new async_hooks_1.AsyncLocalStorage();
class Correlator {
static setId() {
const id = uuid.v4();
asyncLocalStorage.enterWith(id);
return id;
}
static run(work, ...args) {
const id = asyncLocalStorage.getStore() || uuid.v4();
return asyncLocalStorage.run(id, () => work(...args));
}
static runWithId(id, work, ...args) {
id = id ? id : uuid.v4();
return asyncLocalStorage.run(id, () => work(...args));
}
static getId() {
const store = asyncLocalStorage.getStore();
return store !== null && store !== void 0 ? store : "";
}
}
exports.Correlator = Correlator;
//# sourceMappingURL=correlator.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"correlator.js","sourceRoot":"","sources":["../../src/common/correlator.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAClC,YAAY,CAAC;;;;AAEb,6CAAgD;AAChD,mDAA6B;AAE7B,MAAM,iBAAiB,GAAG,IAAI,+BAAiB,EAAU,CAAC;AAE1D,MAAa,UAAU;IACrB,MAAM,CAAC,KAAK;QACV,MAAM,EAAE,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC;QACrB,iBAAiB,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC;QAChC,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,MAAM,CAAC,GAAG,CAAyB,IAA4B,EAAE,GAAG,IAAY;QAC9E,MAAM,EAAE,GAAG,iBAAiB,CAAC,QAAQ,EAAE,IAAI,IAAI,CAAC,EAAE,EAAE,CAAC;QACrD,OAAO,iBAAiB,CAAC,GAAG,CAAI,EAAE,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC;IAC3D,CAAC;IAED,MAAM,CAAC,SAAS,CACd,EAAU,EACV,IAA4B,EAC5B,GAAG,IAAY;QAEf,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,EAAE,CAAC;QACzB,OAAO,iBAAiB,CAAC,GAAG,CAAI,EAAE,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC;IAC3D,CAAC;IAED,MAAM,CAAC,KAAK;QACV,MAAM,KAAK,GAAG,iBAAiB,CAAC,QAAQ,EAAE,CAAC;QAC3C,OAAO,KAAK,aAAL,KAAK,cAAL,KAAK,GAAI,EAAE,CAAC;IACrB,CAAC;CACF;AAxBD,gCAwBC"}
+132
View File
@@ -0,0 +1,132 @@
export declare function isFeatureFlagEnabled(featureFlagName: string, defaultValue?: boolean): boolean;
export declare class FeatureFlagName {
static readonly CLIDotNet = "TEAMSFX_CLI_DOTNET";
static readonly OfficeAddin = "TEAMSFX_OFFICE_ADDIN";
static readonly OfficeMetaOS = "TEAMSFX_OFFICE_METAOS";
static readonly CopilotExtension = "DEVELOP_COPILOT_EXTENSION";
static readonly CopilotPlugin = "DEVELOP_COPILOT_PLUGIN";
static readonly SampleConfigBranch = "TEAMSFX_SAMPLE_CONFIG_BRANCH";
static readonly TestTool = "TEAMSFX_TEST_TOOL";
static readonly METestTool = "TEAMSFX_ME_TEST_TOOL";
static readonly TeamsFxRebranding = "TEAMSFX_REBRANDING";
static readonly TdpTemplateCliTest = "TEAMSFX_TDP_TEMPLATE_CLI_TEST";
static readonly AsyncAppValidation = "TEAMSFX_ASYNC_APP_VALIDATION";
static readonly NewProjectType = "TEAMSFX_NEW_PROJECT_TYPE";
static readonly ChatParticipant = "TEAMSFX_CHAT_PARTICIPANT";
static readonly ChatParticipantUIEntries = "TEAMSFX_CHAT_PARTICIPANT_ENTRIES";
static readonly SMEOAuth = "SME_OAUTH";
static readonly ShowDiagnostics = "TEAMSFX_SHOW_DIAGNOSTICS";
static readonly TelemetryTest = "TEAMSFX_TELEMETRY_TEST";
static readonly DevTunnelTest = "TEAMSFX_DEV_TUNNEL_TEST";
static readonly SyncManifest = "TEAMSFX_SYNC_MANIFEST";
static readonly EnvFileFunc = "TEAMSFX_ENV_FILE_FUNC";
static readonly KiotaIntegration = "TEAMSFX_KIOTA_INTEGRATION";
static readonly ApiPluginAAD = "TEAMSFX_API_PLUGIN_AAD";
static readonly CEAEnabled = "TEAMSFX_CEA_ENABLED";
static readonly MultiTenant = "TEAMSFX_MULTI_TENANT";
}
export interface FeatureFlag {
name: string;
defaultValue: string;
description?: string;
}
export declare class FeatureFlags {
static readonly CLIDotNet: {
name: string;
defaultValue: string;
};
static readonly CopilotExtension: {
name: string;
defaultValue: string;
};
static readonly CopilotPlugin: {
name: string;
defaultValue: string;
};
static readonly TestTool: {
name: string;
defaultValue: string;
};
static readonly METestTool: {
name: string;
defaultValue: string;
};
static readonly OfficeAddin: {
name: string;
defaultValue: string;
};
static readonly OfficeMetaOS: {
name: string;
defaultValue: string;
};
static readonly TdpTemplateCliTest: {
name: string;
defaultValue: string;
};
static readonly AsyncAppValidation: {
name: string;
defaultValue: string;
};
static readonly NewProjectType: {
name: string;
defaultValue: string;
};
static readonly ChatParticipant: {
name: string;
defaultValue: string;
};
static readonly ChatParticipantUIEntries: {
name: string;
defaultValue: string;
};
static readonly SMEOAuth: {
name: string;
defaultValue: string;
};
static readonly ShowDiagnostics: {
name: string;
defaultValue: string;
};
static readonly TelemetryTest: {
name: string;
defaultValue: string;
};
static readonly DevTunnelTest: {
name: string;
defaultValue: string;
};
static readonly SyncManifest: {
name: string;
defaultValue: string;
};
static readonly EnvFileFunc: {
name: string;
defaultValue: string;
};
static readonly KiotaIntegration: {
name: string;
defaultValue: string;
};
static readonly ApiPluginAAD: {
name: string;
defaultValue: string;
};
static readonly CEAEnabled: {
name: string;
defaultValue: string;
};
static readonly MultiTenant: {
name: string;
defaultValue: string;
};
}
export declare function isCopilotExtensionEnabled(): boolean;
export declare class FeatureFlagManager {
getBooleanValue(featureFlag: FeatureFlag): boolean;
setBooleanValue(featureFlag: FeatureFlag, value: boolean): void;
getStringValue(featureFlag: FeatureFlag): string;
list(): FeatureFlag[];
listEnabled(): string[];
}
export declare const featureFlagManager: FeatureFlagManager;
//# sourceMappingURL=featureFlags.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"featureFlags.d.ts","sourceRoot":"","sources":["../../src/common/featureFlags.ts"],"names":[],"mappings":"AAIA,wBAAgB,oBAAoB,CAAC,eAAe,EAAE,MAAM,EAAE,YAAY,UAAQ,GAAG,OAAO,CAO3F;AACD,qBAAa,eAAe;IAC1B,MAAM,CAAC,QAAQ,CAAC,SAAS,wBAAwB;IACjD,MAAM,CAAC,QAAQ,CAAC,WAAW,0BAA0B;IACrD,MAAM,CAAC,QAAQ,CAAC,YAAY,2BAA2B;IACvD,MAAM,CAAC,QAAQ,CAAC,gBAAgB,+BAA+B;IAC/D,MAAM,CAAC,QAAQ,CAAC,aAAa,4BAA4B;IACzD,MAAM,CAAC,QAAQ,CAAC,kBAAkB,kCAAkC;IACpE,MAAM,CAAC,QAAQ,CAAC,QAAQ,uBAAuB;IAC/C,MAAM,CAAC,QAAQ,CAAC,UAAU,0BAA0B;IACpD,MAAM,CAAC,QAAQ,CAAC,iBAAiB,wBAA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;IACF,MAAM,CAAC,QAAQ,CAAC,kBAAkB;;;MAGhC;IACF,MAAM,CAAC,QAAQ,CAAC,cAAc;;;MAAkE;IAChG,MAAM,CAAC,QAAQ,CAAC,eAAe;;;MAG7B;IACF,MAAM,CAAC,QAAQ,CAAC,wBAAwB;;;MAGtC;IACF,MAAM,CAAC,QAAQ,CAAC,QAAQ;;;MAA6D;IACrF,MAAM,CAAC,QAAQ,CAAC,eAAe;;;MAG7B;IACF,MAAM,CAAC,QAAQ,CAAC,aAAa;;;MAG3B;IACF,MAAM,CAAC,QAAQ,CAAC,aAAa;;;MAG3B;IACF,MAAM,CAAC,QAAQ,CAAC,YAAY;;;MAG1B;IACF,MAAM,CAAC,QAAQ,CAAC,WAAW;;;MAGzB;IACF,MAAM,CAAC,QAAQ,CAAC,gBAAgB;;;MAG9B;IACF,MAAM,CAAC,QAAQ,CAAC,YAAY;;;MAG1B;IACF,MAAM,CAAC,QAAQ,CAAC,UAAU;;;MAGxB;IACF,MAAM,CAAC,QAAQ,CAAC,WAAW;;;MAGzB;CACH;AAED,wBAAgB,yBAAyB,IAAI,OAAO,CAKnD;AAED,qBAAa,kBAAkB;IAC7B,eAAe,CAAC,WAAW,EAAE,WAAW,GAAG,OAAO;IAMlD,eAAe,CAAC,WAAW,EAAE,WAAW,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI;IAG/D,cAAc,CAAC,WAAW,EAAE,WAAW,GAAG,MAAM;IAGhD,IAAI,IAAI,WAAW,EAAE;IAGrB,WAAW,IAAI,MAAM,EAAE;CAKxB;AAED,eAAO,MAAM,kBAAkB,oBAA2B,CAAC"}
+143
View File
@@ -0,0 +1,143 @@
"use strict";
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.featureFlagManager = exports.FeatureFlagManager = exports.isCopilotExtensionEnabled = exports.FeatureFlags = exports.FeatureFlagName = exports.isFeatureFlagEnabled = void 0;
// Determine whether feature flag is enabled based on environment variable setting
function isFeatureFlagEnabled(featureFlagName, defaultValue = false) {
const flag = process.env[featureFlagName];
if (flag === undefined) {
return defaultValue; // allows consumer to set a default value when environment variable not set
}
else {
return flag === "1" || flag.toLowerCase() === "true"; // can enable feature flag by set environment variable value to "1" or "true"
}
}
exports.isFeatureFlagEnabled = isFeatureFlagEnabled;
class FeatureFlagName {
}
exports.FeatureFlagName = FeatureFlagName;
FeatureFlagName.CLIDotNet = "TEAMSFX_CLI_DOTNET";
FeatureFlagName.OfficeAddin = "TEAMSFX_OFFICE_ADDIN";
FeatureFlagName.OfficeMetaOS = "TEAMSFX_OFFICE_METAOS";
FeatureFlagName.CopilotExtension = "DEVELOP_COPILOT_EXTENSION";
FeatureFlagName.CopilotPlugin = "DEVELOP_COPILOT_PLUGIN";
FeatureFlagName.SampleConfigBranch = "TEAMSFX_SAMPLE_CONFIG_BRANCH";
FeatureFlagName.TestTool = "TEAMSFX_TEST_TOOL";
FeatureFlagName.METestTool = "TEAMSFX_ME_TEST_TOOL";
FeatureFlagName.TeamsFxRebranding = "TEAMSFX_REBRANDING";
FeatureFlagName.TdpTemplateCliTest = "TEAMSFX_TDP_TEMPLATE_CLI_TEST";
FeatureFlagName.AsyncAppValidation = "TEAMSFX_ASYNC_APP_VALIDATION";
FeatureFlagName.NewProjectType = "TEAMSFX_NEW_PROJECT_TYPE";
FeatureFlagName.ChatParticipant = "TEAMSFX_CHAT_PARTICIPANT";
FeatureFlagName.ChatParticipantUIEntries = "TEAMSFX_CHAT_PARTICIPANT_ENTRIES";
FeatureFlagName.SMEOAuth = "SME_OAUTH";
FeatureFlagName.ShowDiagnostics = "TEAMSFX_SHOW_DIAGNOSTICS";
FeatureFlagName.TelemetryTest = "TEAMSFX_TELEMETRY_TEST";
FeatureFlagName.DevTunnelTest = "TEAMSFX_DEV_TUNNEL_TEST";
FeatureFlagName.SyncManifest = "TEAMSFX_SYNC_MANIFEST";
FeatureFlagName.EnvFileFunc = "TEAMSFX_ENV_FILE_FUNC";
FeatureFlagName.KiotaIntegration = "TEAMSFX_KIOTA_INTEGRATION";
FeatureFlagName.ApiPluginAAD = "TEAMSFX_API_PLUGIN_AAD";
FeatureFlagName.CEAEnabled = "TEAMSFX_CEA_ENABLED";
FeatureFlagName.MultiTenant = "TEAMSFX_MULTI_TENANT";
class FeatureFlags {
}
exports.FeatureFlags = FeatureFlags;
FeatureFlags.CLIDotNet = { name: FeatureFlagName.CLIDotNet, defaultValue: "false" };
FeatureFlags.CopilotExtension = {
name: FeatureFlagName.CopilotExtension,
defaultValue: "false",
};
FeatureFlags.CopilotPlugin = {
name: FeatureFlagName.CopilotPlugin,
defaultValue: "false",
}; // old feature flag. Keep it for backwards compatibility.
FeatureFlags.TestTool = { name: FeatureFlagName.TestTool, defaultValue: "true" };
FeatureFlags.METestTool = { name: FeatureFlagName.METestTool, defaultValue: "true" };
FeatureFlags.OfficeAddin = { name: FeatureFlagName.OfficeAddin, defaultValue: "false" };
FeatureFlags.OfficeMetaOS = {
name: FeatureFlagName.OfficeMetaOS,
defaultValue: "false",
};
FeatureFlags.TdpTemplateCliTest = {
name: FeatureFlagName.TdpTemplateCliTest,
defaultValue: "false",
};
FeatureFlags.AsyncAppValidation = {
name: FeatureFlagName.AsyncAppValidation,
defaultValue: "true",
};
FeatureFlags.NewProjectType = { name: FeatureFlagName.NewProjectType, defaultValue: "true" };
FeatureFlags.ChatParticipant = {
name: FeatureFlagName.ChatParticipant,
defaultValue: "false",
};
FeatureFlags.ChatParticipantUIEntries = {
name: FeatureFlagName.ChatParticipantUIEntries,
defaultValue: "true",
};
FeatureFlags.SMEOAuth = { name: FeatureFlagName.SMEOAuth, defaultValue: "false" };
FeatureFlags.ShowDiagnostics = {
name: FeatureFlagName.ShowDiagnostics,
defaultValue: "false",
};
FeatureFlags.TelemetryTest = {
name: FeatureFlagName.TelemetryTest,
defaultValue: "false",
};
FeatureFlags.DevTunnelTest = {
name: FeatureFlagName.DevTunnelTest,
defaultValue: "false",
};
FeatureFlags.SyncManifest = {
name: FeatureFlagName.SyncManifest,
defaultValue: "false",
};
FeatureFlags.EnvFileFunc = {
name: FeatureFlagName.EnvFileFunc,
defaultValue: "true", // Set it to true for dogfooding.
};
FeatureFlags.KiotaIntegration = {
name: FeatureFlagName.KiotaIntegration,
defaultValue: "false",
};
FeatureFlags.ApiPluginAAD = {
name: FeatureFlagName.ApiPluginAAD,
defaultValue: "false",
};
FeatureFlags.CEAEnabled = {
name: FeatureFlagName.CEAEnabled,
defaultValue: "false",
};
FeatureFlags.MultiTenant = {
name: FeatureFlagName.MultiTenant,
defaultValue: "false",
};
function isCopilotExtensionEnabled() {
return (exports.featureFlagManager.getBooleanValue(FeatureFlags.CopilotExtension) ||
exports.featureFlagManager.getBooleanValue(FeatureFlags.CopilotPlugin));
}
exports.isCopilotExtensionEnabled = isCopilotExtensionEnabled;
class FeatureFlagManager {
getBooleanValue(featureFlag) {
return isFeatureFlagEnabled(featureFlag.name, featureFlag.defaultValue === "true" || featureFlag.defaultValue === "1");
}
setBooleanValue(featureFlag, value) {
process.env[featureFlag.name] = value ? "true" : "false";
}
getStringValue(featureFlag) {
return process.env[featureFlag.name] || featureFlag.defaultValue;
}
list() {
return Object.values(FeatureFlags);
}
listEnabled() {
return this.list()
.filter((f) => isFeatureFlagEnabled(f.name))
.map((f) => f.name);
}
}
exports.FeatureFlagManager = FeatureFlagManager;
exports.featureFlagManager = new FeatureFlagManager();
//# sourceMappingURL=featureFlags.js.map
@@ -0,0 +1 @@
{"version":3,"file":"featureFlags.js","sourceRoot":"","sources":["../../src/common/featureFlags.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAElC,kFAAkF;AAClF,SAAgB,oBAAoB,CAAC,eAAuB,EAAE,YAAY,GAAG,KAAK;IAChF,MAAM,IAAI,GAAG,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC;IAC1C,IAAI,IAAI,KAAK,SAAS,EAAE;QACtB,OAAO,YAAY,CAAC,CAAC,2EAA2E;KACjG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W,CAAC,IAAI,CAAC,IAAI,WAAW,CAAC,YAAY,CAAC;IACnE,CAAC;IACD,IAAI;QACF,OAAO,MAAM,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC;IACrC,CAAC;IACD,WAAW;QACT,OAAO,IAAI,CAAC,IAAI,EAAE;aACf,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,oBAAoB,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;aAC3C,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;IACxB,CAAC;CACF;AArBD,gDAqBC;AAEY,QAAA,kBAAkB,GAAG,IAAI,kBAAkB,EAAE,CAAC"}
+15
View File
@@ -0,0 +1,15 @@
/**
* Return a value.
*
* @param key A string.
* @return The stored value or `undefined`.
*/
export declare function globalStateGet(key: string, defaultValue?: any): Promise<any>;
/**
* Store a value. The value must be JSON-stringifyable.
*
* @param key A string.
* @param value A value. MUST not contain cyclic references.
*/
export declare function globalStateUpdate(key: string, value: any): Promise<void>;
//# sourceMappingURL=globalState.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"globalState.d.ts","sourceRoot":"","sources":["../../src/common/globalState.ts"],"names":[],"mappings":"AAaA;;;;;GAKG;AACH,wBAAsB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,CA+BlF;AAED;;;;;GAKG;AACH,wBAAsB,iBAAiB,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC,CA4B9E"}
+105
View File
@@ -0,0 +1,105 @@
"use strict";
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.globalStateUpdate = exports.globalStateGet = void 0;
const tslib_1 = require("tslib");
const os = tslib_1.__importStar(require("os"));
const path = tslib_1.__importStar(require("path"));
const fs = tslib_1.__importStar(require("fs-extra"));
const crypto_1 = tslib_1.__importDefault(require("crypto"));
const teamsfx_api_1 = require("@microsoft/teamsfx-api");
const proper_lockfile_1 = tslib_1.__importDefault(require("proper-lockfile"));
const utils_1 = require("./utils");
const GlobalStateFileName = "state.json";
/**
* Return a value.
*
* @param key A string.
* @return The stored value or `undefined`.
*/
async function globalStateGet(key, defaultValue) {
const filePath = getGlobalStateFile();
ensureGlobalStateFileExists(filePath);
const lockFileDir = getLockFolder(filePath);
const lockfilePath = path.join(lockFileDir, `${teamsfx_api_1.ConfigFolderName}.lock`);
await fs.ensureDir(lockFileDir);
const retryNum = 10;
for (let i = 0; i < retryNum; ++i) {
try {
await proper_lockfile_1.default.lock(filePath, { lockfilePath: lockfilePath });
let value = undefined;
try {
const config = await fs.readJSON(filePath);
value = config[key];
if (value === undefined) {
value = defaultValue;
}
}
finally {
await proper_lockfile_1.default.unlock(filePath, { lockfilePath: lockfilePath });
}
return value;
}
catch (e) {
if (e["code"] === "ELOCKED") {
await (0, utils_1.waitSeconds)(1);
continue;
}
return undefined;
}
}
}
exports.globalStateGet = globalStateGet;
/**
* Store a value. The value must be JSON-stringifyable.
*
* @param key A string.
* @param value A value. MUST not contain cyclic references.
*/
async function globalStateUpdate(key, value) {
const filePath = getGlobalStateFile();
ensureGlobalStateFileExists(filePath);
const lockFileDir = getLockFolder(filePath);
const lockfilePath = path.join(lockFileDir, `${teamsfx_api_1.ConfigFolderName}.lock`);
await fs.ensureDir(lockFileDir);
const retryNum = 10;
for (let i = 0; i < retryNum; ++i) {
try {
await proper_lockfile_1.default.lock(filePath, { lockfilePath: lockfilePath });
try {
const config = await fs.readJSON(filePath);
config[key] = value;
await fs.writeJson(filePath, config);
}
finally {
await proper_lockfile_1.default.unlock(filePath, { lockfilePath: lockfilePath });
}
break;
}
catch (e) {
if (e["code"] === "ELOCKED") {
await (0, utils_1.waitSeconds)(1);
continue;
}
throw e;
}
}
}
exports.globalStateUpdate = globalStateUpdate;
function getGlobalStateFile() {
const homeDir = os.homedir();
return path.join(homeDir, `.${teamsfx_api_1.ConfigFolderName}`, GlobalStateFileName);
}
function ensureGlobalStateFileExists(filePath) {
if (!fs.pathExistsSync(path.dirname(filePath))) {
fs.mkdirpSync(path.dirname(filePath));
}
if (!fs.existsSync(filePath)) {
fs.writeJSONSync(filePath, {});
}
}
function getLockFolder(projectPath) {
return path.join(os.tmpdir(), `${teamsfx_api_1.ProductName}-${crypto_1.default.createHash("sha256").update(projectPath).digest("hex")}`);
}
//# sourceMappingURL=globalState.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"globalState.js","sourceRoot":"","sources":["../../src/common/globalState.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;;AAElC,+CAAyB;AACzB,mDAA6B;AAC7B,qDAA+B;AAC/B,4DAA4B;AAC5B,wDAAuE;AACvE,8EAAyC;AACzC,mCAAsC;AAEtC,MAAM,mBAAmB,GAAG,YAAY,CAAC;AAEzC;;;;;GAKG;AACI,KAAK,UAAU,cAAc,CAAC,GAAW,EAAE,YAAkB;IAClE,MAAM,QAAQ,GAAG,kBAAkB,EAAE,CAAC;IACtC,2BAA2B,CAAC,QAAQ,CAAC,CAAC;IAEtC,MAAM,WAAW,GAAG,aAAa,CAAC,QAAQ,CAAC,CAAC;IAC5C,MAAM,YAAY,GAAG,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,GAAG,8BAAgB,OAAO,CAAC,CAAC;IACxE,MAAM,EAAE,CAAC,SAAS,CAAC,WAAW,CAAC,CAAC;IAEhC,MAAM,QAAQ,GAAG,EAAE,CAAC;IACpB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,EAAE,EAAE,CAAC,EAAE;QACjC,IAAI;YACF,MAAM,yBAAU,CAAC,IAAI,CAAC,QAAQ,EAAE,EAAE,YAAY,EAAE,YAAY,EAAE,CAAC,CAAC;YAChE,IAAI,KAAK,GAAQ,SAAS,CAAC;YAC3B,IA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 +1,34 @@
import { Middleware } from "@feathersjs/hooks";
import { Context, Tools } from "@microsoft/teamsfx-api";
export declare let TOOLS: Tools;
export declare let Locale: string | undefined;
export declare function setTools(tools: Tools): void;
export declare function setLocale(locale?: string): void;
declare class GlobalVars {
isVS?: boolean;
teamsAppId: string;
m365TenantId: string;
trackingId?: string;
ymlFilePath?: string;
envFilePath?: string;
stage: string;
source: ExternalSource;
component: string;
method: string;
}
export declare const globalVars: GlobalVars;
export interface ErrorContextOption {
component?: string;
source?: ExternalSource;
stage?: string;
method?: string;
reset?: boolean;
}
export declare function ErrorContextMW(option: ErrorContextOption): Middleware;
export declare function resetErrorContext(): void;
export declare function setErrorContext(option: ErrorContextOption): void;
export declare type ExternalSource = "Graph" | "Azure" | "Teams" | "BotFx" | "SPFx" | "DevTools" | "M365" | "";
export declare function createContext(): Context;
export declare const AadSet: Set<string>;
export {};
//# sourceMappingURL=globalVars.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"globalVars.d.ts","sourceRoot":"","sources":["../../src/common/globalVars.ts"],"names":[],"mappings":"AAGA,OAAO,EAAe,UAAU,EAAgB,MAAM,mBAAmB,CAAC;AAC1E,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,wBAAwB,CAAC;AAExD,eAAO,IAAI,KAAK,EAAE,KAAK,CAAC;AACxB,eAAO,IAAI,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC;AACtC,wBAAgB,QAAQ,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,CAE3C;AACD,wBAAgB,SAAS,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAE/C;AAED,cAAM,UAAU;IACd,IAAI,CAAC,EAAE,OAAO,CAAS;IACvB,UAAU,SAAM;IAChB,YAAY,SAAM;IAClB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,WAAW,CAAC,EAAE,MAAM,CAAC;IAGrB,KAAK,SAAM;IACX,MAAM,EAAE,cAAc,CAAM;IAC5B,SAAS,SAAM;IACf,MAAM,SAAM;CACb;AACD,eAAO,MAAM,UAAU,YAAmB,CAAC;AAE3C,MAAM,WAAW,kBAAkB;IACjC,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EAAE,cAAc,CAAC;IACxB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB;AAED,wBAAgB,cAAc,CAAC,MAAM,EAAE,kBAAkB,GAAG,UAAU,CASrE;AAED,wBAAgB,iBAAiB,IAAI,IAAI,CAKxC;AAED,wBAAgB,eAAe,CAAC,MAAM,EAAE,kBAAkB,GAAG,IAAI,CAQhE;AAED,oBAAY,cAAc,GACtB,OAAO,GACP,OAAO,GACP,OAAO,GACP,OAAO,GACP,MAAM,GACN,UAAU,GACV,MAAM,GACN,EAAE,CAAC;AAEP,wBAAgB,aAAa,IAAI,OAAO,CAQvC;AAED,eAAO,MAAM,MAAM,EAAE,GAAG,CAAC,MAAM,CAAqB,CAAC"}
+66
View File
@@ -0,0 +1,66 @@
"use strict";
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.AadSet = exports.createContext = exports.setErrorContext = exports.resetErrorContext = exports.ErrorContextMW = exports.globalVars = exports.setLocale = exports.setTools = exports.Locale = exports.TOOLS = void 0;
function setTools(tools) {
exports.TOOLS = tools;
}
exports.setTools = setTools;
function setLocale(locale) {
exports.Locale = locale;
}
exports.setLocale = setLocale;
class GlobalVars {
constructor() {
this.isVS = false;
this.teamsAppId = "";
this.m365TenantId = "";
//properties for error telemetry
this.stage = "";
this.source = "";
this.component = "";
this.method = "";
}
}
exports.globalVars = new GlobalVars();
function ErrorContextMW(option) {
return async (ctx, next) => {
option.method = ctx.method;
setErrorContext(option);
await next();
if (option.reset) {
resetErrorContext();
}
};
}
exports.ErrorContextMW = ErrorContextMW;
function resetErrorContext() {
exports.globalVars.stage = "";
exports.globalVars.source = "";
exports.globalVars.component = "";
exports.globalVars.method = "";
}
exports.resetErrorContext = resetErrorContext;
function setErrorContext(option) {
if (option.reset) {
resetErrorContext();
}
exports.globalVars.component = option.component || exports.globalVars.component;
exports.globalVars.source = option.source || exports.globalVars.source;
exports.globalVars.stage = option.stage || exports.globalVars.stage;
exports.globalVars.method = option.method || exports.globalVars.method;
}
exports.setErrorContext = setErrorContext;
function createContext() {
const context = {
userInteraction: exports.TOOLS.ui,
logProvider: exports.TOOLS.logProvider,
telemetryReporter: exports.TOOLS.telemetryReporter,
tokenProvider: exports.TOOLS.tokenProvider,
};
return context;
}
exports.createContext = createContext;
exports.AadSet = new Set();
//# sourceMappingURL=globalVars.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"globalVars.js","sourceRoot":"","sources":["../../src/common/globalVars.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAOlC,SAAgB,QAAQ,CAAC,KAAY;IACnC,aAAK,GAAG,KAAK,CAAC;AAChB,CAAC;AAFD,4BAEC;AACD,SAAgB,SAAS,CAAC,MAAe;IACvC,cAAM,GAAG,MAAM,CAAC;AAClB,CAAC;AAFD,8BAEC;AAED,MAAM,UAAU;IAAhB;QACE,SAAI,GAAa,KAAK,CAAC;QACvB,eAAU,GAAG,EAAE,CAAC;QAChB,iBAAY,GAAG,EAAE,CAAC;QAKlB,gCAAgC;QAChC,UAAK,GAAG,EAAE,CAAC;QACX,WAAM,GAAmB,EAAE,CAAC;QAC5B,cAAS,GAAG,EAAE,CAAC;QACf,WAAM,GAAG,EAAE,CAAC;IACd,CAAC;CAAA;AACY,QAAA,UAAU,GAAG,IAAI,UAAU,EAAE,CAAC;AAU3C,SAAgB,cAAc,CAAC,MAA0B;IACvD,OAAO,KAAK,EAAE,GAAgB,EAAE,IAAkB,EAAE,EAAE;QACpD,MAAM,CAAC,MAAM,GAAG,GAAG,CAAC,MA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ON(content: string): Result<any, FxError>;
readJSONFile(filePath: string): Promise<Result<any, FxError>>;
readJSONFileSync(filePath: string): Result<any, FxError>;
}
export declare const jsonUtils: JSONUtils;
export {};
//# sourceMappingURL=jsonUtils.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"jsonUtils.d.ts","sourceRoot":"","sources":["../../src/common/jsonUtils.ts"],"names":[],"mappings":"AAGA,OAAO,EAAO,OAAO,EAAM,MAAM,EAAE,MAAM,wBAAwB,CAAC;AAIlE,cAAM,SAAS;IACb,SAAS,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAAC,GAAG,EAAE,OAAO,CAAC;IAQ1C,YAAY,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;IAenE,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAAC,GAAG,EAAE,OAAO,CAAC;CAczD;AAED,eAAO,MAAM,SAAS,WAAkB,CAAC"}
+56
View File
@@ -0,0 +1,56 @@
"use strict";
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.jsonUtils = void 0;
const tslib_1 = require("tslib");
const teamsfx_api_1 = require("@microsoft/teamsfx-api");
const common_1 = require("../error/common");
const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
class JSONUtils {
parseJSON(content) {
try {
const obj = JSON.parse(content);
return (0, teamsfx_api_1.ok)(obj);
}
catch (e) {
return (0, teamsfx_api_1.err)(new common_1.JSONSyntaxError(content, e));
}
}
async readJSONFile(filePath) {
var _a;
try {
const res = await fs_extra_1.default.readJSON(filePath);
return (0, teamsfx_api_1.ok)(res);
}
catch (e) {
if (e.name === "SyntaxError") {
const error = new common_1.JSONSyntaxError(filePath, e);
return (0, teamsfx_api_1.err)(error);
}
else if ((_a = e.message) === null || _a === void 0 ? void 0 : _a.includes("no such file or directory")) {
return (0, teamsfx_api_1.err)(new common_1.FileNotFoundError("common", filePath));
}
return (0, teamsfx_api_1.err)(new common_1.ReadFileError(e, "common"));
}
}
readJSONFileSync(filePath) {
var _a;
try {
const res = fs_extra_1.default.readJSONSync(filePath);
return (0, teamsfx_api_1.ok)(res);
}
catch (e) {
if (e.name === "SyntaxError") {
const error = new common_1.JSONSyntaxError(filePath, e);
return (0, teamsfx_api_1.err)(error);
}
else if ((_a = e.message) === null || _a === void 0 ? void 0 : _a.includes("no such file or directory")) {
return (0, teamsfx_api_1.err)(new common_1.FileNotFoundError("common", filePath));
}
return (0, teamsfx_api_1.err)(new common_1.ReadFileError(e, "common"));
}
}
}
exports.jsonUtils = new JSONUtils();
//# sourceMappingURL=jsonUtils.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"jsonUtils.js","sourceRoot":"","sources":["../../src/common/jsonUtils.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;;AAElC,wDAAkE;AAClE,4CAAoF;AACpF,gEAA0B;AAE1B,MAAM,SAAS;IACb,SAAS,CAAC,OAAe;QACvB,IAAI;YACF,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YAChC,OAAO,IAAA,gBAAE,EAAC,GAAG,CAAC,CAAC;SAChB;QAAC,OAAO,CAAM,EAAE;YACf,OAAO,IAAA,iBAAG,EAAC,IAAI,wBAAe,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC;SAC7C;IACH,CAAC;IACD,KAAK,CAAC,YAAY,CAAC,QAAgB;;QACjC,IAAI;YACF,MAAM,GAAG,GAAG,MAAM,kBAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;YACxC,OAAO,IAAA,gBAAE,EAAC,GAAG,CAAC,CAAC;SAChB;QAAC,OAAO,CAAM,EAAE;YACf,IAAI,CAAC,CAAC,IAAI,KAAK,aAAa,EAAE;gBAC5B,MAAM,KAAK,GAAG,IAAI,wBAAe,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC;gBAC/C,OAAO,IAAA,iBAAG,EAAC,KAAK,CAAC,CAAC;aACnB;iBAAM,IAAI,MAAA,CAAC,CAAC,OAAO,0CAAE,QAAQ,CAAC,2BAA2B,CAAC,EAAE;gBAC3D,OAAO,IAAA,iBAAG,EAAC,IAAI,0BAAiB,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC,CAAC;aACvD;YACD,OAAO,IAAA,iBAAG,EAAC,IAAI,sBAAa,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAC,CAAC;SAC5C;IACH,CAAC;IAED,gBAAgB,CAAC,QAAgB;;QAC/B,IAAI;YACF,MAAM,GAAG,GAAG,kBAAE,CAAC,YAAY,CAAC,QAAQ,CAAC,CAAC;YACtC,OAAO,IAAA,gBAAE,EAAC,GAAG,CAAC,CAAC;SAChB;QAAC,OAAO,CAAM,EAAE;YACf,IAAI,CAAC,CAAC,IAAI,KAAK,aAAa,EAAE;gBAC5B,MAAM,KAAK,GAAG,IAAI,wBAAe,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC;gBAC/C,OAAO,IAAA,iBAAG,EAAC,KAAK,CAAC,CAAC;aACnB;iBAAM,IAAI,MAAA,CAAC,CAAC,OAAO,0CAAE,QAAQ,CAAC,2BAA2B,CAAC,EAAE;gBAC3D,OAAO,IAAA,iBAAG,EAAC,IAAI,0BAAiB,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC,CAAC;aACvD;YACD,OAAO,IAAA,iBAAG,EAAC,IAAI,sBAAa,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAC,CAAC;SAC5C;IACH,CAAC;CACF;AAEY,QAAA,SAAS,GAAG,IAAI,SAAS,EAAE,CAAC"}
+3
View File
@@ -0,0 +1,3 @@
export declare function getLocalizedString(key: string, ...params: any[]): string;
export declare function getDefaultString(key: string, ...params: any[]): string;
//# sourceMappingURL=localizeUtils.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"localizeUtils.d.ts","sourceRoot":"","sources":["../../src/common/localizeUtils.ts"],"names":[],"mappings":"AA4BA,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,GAAG,EAAE,GAAG,MAAM,CAWxE;AAED,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,GAAG,EAAE,GAAG,MAAM,CAOtE"}
+51
View File
@@ -0,0 +1,51 @@
"use strict";
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.getDefaultString = exports.getLocalizedString = void 0;
const tslib_1 = require("tslib");
const globalVars_1 = require("./globalVars");
const folder_1 = require("../folder");
const path = tslib_1.__importStar(require("path"));
const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
const util = tslib_1.__importStar(require("util"));
const LocaleStringMap = new Map();
function getLocaleJson(locale) {
locale = locale || "";
const jsonInMap = LocaleStringMap.get(locale);
if (jsonInMap)
return jsonInMap;
const nlsFileName = globalVars_1.Locale ? `package.nls.${globalVars_1.Locale}.json` : "package.nls.json";
let nlsFilePath = path.join((0, folder_1.getResourceFolder)(), nlsFileName);
if (!fs_extra_1.default.pathExistsSync(nlsFilePath)) {
// if nls file does not exist, just read the default one
nlsFilePath = path.join((0, folder_1.getResourceFolder)(), "package.nls.json");
}
const json = fs_extra_1.default.readJSONSync(nlsFilePath);
if (json) {
LocaleStringMap.set(locale, json);
}
return json;
}
function getLocalizedString(key, ...params) {
const json = getLocaleJson(globalVars_1.Locale);
let value = json[key];
if (value && params && params.length > 0) {
value = util.format(value, ...params);
}
if (!value) {
return getDefaultString(key, ...params);
}
return value || "";
}
exports.getLocalizedString = getLocalizedString;
function getDefaultString(key, ...params) {
const json = getLocaleJson("");
let value = json[key];
if (value && params && params.length > 0) {
value = util.format(value, ...params);
}
return value || "";
}
exports.getDefaultString = getDefaultString;
//# sourceMappingURL=localizeUtils.js.map
@@ -0,0 +1 @@
{"version":3,"file":"localizeU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K,EAAE,GAAG,MAAM,CAAC,CAAC;KACvC;IAED,IAAI,CAAC,KAAK,EAAE;QACV,OAAO,gBAAgB,CAAC,GAAG,EAAE,GAAG,MAAM,CAAC,CAAC;KACzC;IACD,OAAO,KAAK,IAAI,EAAE,CAAC;AACrB,CAAC;AAXD,gDAWC;AAED,SAAgB,gBAAgB,CAAC,GAAW,EAAE,GAAG,MAAa;IAC5D,MAAM,IAAI,GAAG,aAAa,CAAC,EAAE,CAAC,CAAC;IAC/B,IAAI,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC;IACtB,IAAI,KAAK,IAAI,MAAM,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE;QACxC,KAAK,GAAG,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,GAAG,MAAM,CAAC,CAAC;KACvC;IACD,OAAO,KAAK,IAAI,EAAE,CAAC;AACrB,CAAC;AAPD,4CAOC"}
@@ -0,0 +1,53 @@
export interface ResourcePermission {
name: string;
type: string;
resourceId: string | undefined;
roles: string[] | undefined;
}
export declare enum CollaborationState {
OK = "OK",
NotProvisioned = "NotProvisioned",
M365TenantNotMatch = "M365TenantNotMatch",
EmptyM365Tenant = "EmptyM365Tenant",
m365AccountNotSignedIn = "M365AccountNotSignedIn"
}
export interface CollaborationStateResult {
state: CollaborationState;
message?: string;
}
export interface ListCollaboratorResult {
state: CollaborationState;
message?: string;
collaborators?: Collaborator[];
error?: any;
}
export interface PermissionsResult {
state: CollaborationState;
message?: string;
userInfo?: Record<string, any>;
permissions?: ResourcePermission[];
}
export interface Collaborator {
userPrincipalName: string;
userObjectId: string;
isAadOwner: boolean;
teamsAppResourceId: string;
aadResourceId?: string;
}
export interface AadOwner {
userObjectId: string;
resourceId: string;
displayName: string;
userPrincipalName: string;
}
export interface TeamsAppAdmin {
userObjectId: string;
resourceId: string;
displayName: string;
userPrincipalName: string;
}
export interface AppIds {
teamsAppId?: string;
aadObjectId?: string;
}
//# sourceMappingURL=permissionInterface.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"permissionInterface.d.ts","sourceRoot":"","sources":["../../src/common/permissionInterface.ts"],"names":[],"mappings":"AAGA,MAAM,WAAW,kBAAkB;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,EAAE,MAAM,GAAG,SAAS,CAAC;IAC/B,KAAK,EAAE,MAAM,EAAE,GAAG,SAAS,CAAC;CAC7B;AAED,oBAAY,kBAAkB;IAC5B,EAAE,OAAO;IACT,cAAc,mBAAmB;IACjC,kBAAkB,uBAAuB;IACzC,eAAe,oBAAoB;IACnC,sBAAsB,2BAA2B;CAClD;AAED,MAAM,WAAW,wBAAwB;IACvC,KAAK,EAAE,kBAAkB,CAAC;IAC1B,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,sBAAsB;IACrC,KAAK,EAAE,kBAAkB,CAAC;IAC1B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,aAAa,CAAC,EAAE,YAAY,EAAE,CAAC;IAC/B,KAAK,CAAC,EAAE,GAAG,CAAC;CACb;AAED,MAAM,WAAW,iBAAiB;IAChC,KAAK,EAAE,kBAAkB,CAAC;IAC1B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAC/B,WAAW,CAAC,EAAE,kBAAkB,EAAE,CAAC;CACpC;AAED,MAAM,WAAW,YAAY;IAC3B,iBAAiB,EAAE,MAAM,CAAC;IAC1B,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,OAAO,CAAC;IACpB,kBAAkB,EAAE,MAAM,CAAC;IAC3B,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,MAAM,WAAW,QAAQ;IACvB,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;IACpB,iBAAiB,EAAE,MAAM,CAAC;CAC3B;AAED,MAAM,WAAW,aAAa;IAC5B,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;IACpB,iBAAiB,EAAE,MAAM,CAAC;CAC3B;AAED,MAAM,WAAW,MAAM;IACrB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB"}
@@ -0,0 +1,14 @@
"use strict";
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.CollaborationState = void 0;
var CollaborationState;
(function (CollaborationState) {
CollaborationState["OK"] = "OK";
CollaborationState["NotProvisioned"] = "NotProvisioned";
CollaborationState["M365TenantNotMatch"] = "M365TenantNotMatch";
CollaborationState["EmptyM365Tenant"] = "EmptyM365Tenant";
CollaborationState["m365AccountNotSignedIn"] = "M365AccountNotSignedIn";
})(CollaborationState = exports.CollaborationState || (exports.CollaborationState = {}));
//# sourceMappingURL=permissionInterface.js.map
@@ -0,0 +1 @@
{"version":3,"file":"permissionInterface.js","sourceRoot":"","sources":["../../src/common/permissionInterface.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AASlC,IAAY,kBAMX;AAND,WAAY,kBAAkB;IAC5B,+BAAS,CAAA;IACT,uDAAiC,CAAA;IACjC,+DAAyC,CAAA;IACzC,yDAAmC,CAAA;IACnC,uEAAiD,CAAA;AACnD,CAAC,EANW,kBAAkB,GAAlB,0BAAkB,KAAlB,0BAAkB,QAM7B"}
@@ -0,0 +1,19 @@
export declare enum OfficeManifestType {
XmlAddIn = 0,
MetaOsAddIn = 1
}
export declare function validateProjectSettings(projectSettings: any): string | undefined;
export declare function isValidProject(workspacePath?: string): boolean;
export declare function isValidOfficeAddInProject(workspacePath?: string): boolean;
export declare function isManifestOnlyOfficeAddinProject(workspacePath?: string): boolean;
export declare function fetchManifestList(workspacePath?: string, officeManifestType?: OfficeManifestType): string[] | undefined;
export declare function isOfficeXmlAddInManifest(inputFileName: string): boolean;
export declare function isOfficeMetaOsAddInManifest(inputFileName: string): boolean;
export declare function isValidProjectV3(workspacePath: string): boolean;
export declare function isValidProjectV2(workspacePath: string): boolean;
export declare function isVSProject(projectSettings?: any): boolean;
export declare function getProjectMetadata(rootPath?: string | undefined): {
version?: string;
projectId?: string;
} | undefined;
//# sourceMappingURL=projectSettingsHelper.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"projectSettingsHelper.d.ts","sourceRoot":"","sources":["../../src/common/projectSettingsHelper.ts"],"names":[],"mappings":"AASA,oBAAY,kBAAkB;IAC5B,QAAQ,IAAA;IACR,WAAW,IAAA;CACZ;AAED,wBAAgB,uBAAuB,CAAC,eAAe,EAAE,GAAG,GAAG,MAAM,GAAG,SAAS,CAsBhF;AAqBD,wBAAgB,cAAc,CAAC,aAAa,CAAC,EAAE,MAAM,GAAG,OAAO,CAO9D;AAED,wBAAgB,yBAAyB,CAAC,aAAa,CAAC,EAAE,MAAM,GAAG,OAAO,CAgBzE;AAED,wBAAgB,gCAAgC,CAAC,aAAa,CAAC,EAAE,MAAM,GAAG,OAAO,CAIhF;AAED,wBAAgB,iBAAiB,CAC/B,aAAa,CAAC,EAAE,MAAM,EACtB,kBAAkB,CAAC,EAAE,kBAAkB,GACtC,MAAM,EAAE,GAAG,SAAS,CAStB;AAED,wBAAgB,wBAAwB,CAAC,aAAa,EAAE,MAAM,GAAG,OAAO,CAKvE;AAED,wBAAgB,2BAA2B,CAAC,aAAa,EAAE,MAAM,GAAG,OAAO,CAK1E;AAED,wBAAgB,gBAAgB,CAAC,aAAa,EAAE,MAAM,GAAG,OAAO,CAU/D;AAED,wBAAgB,gBAAgB,CAAC,aAAa,EAAE,MAAM,GAAG,OAAO,CAS/D;AAED,wBAAgB,WAAW,CAAC,eAAe,CAAC,EAAE,GAAG,GAAG,OAAO,CAE1D;AAED,wBAAgB,kBAAkB,CAChC,QAAQ,CAAC,EAAE,MAAM,GAAG,SAAS,GAC5B;IAAE,OAAO,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,CAkBtD"}
@@ -0,0 +1,166 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getProjectMetadata = exports.isVSProject = exports.isValidProjectV2 = exports.isValidProjectV3 = exports.isOfficeMetaOsAddInManifest = exports.isOfficeXmlAddInManifest = exports.fetchManifestList = exports.isManifestOnlyOfficeAddinProject = exports.isValidOfficeAddInProject = exports.isValidProject = exports.validateProjectSettings = exports.OfficeManifestType = void 0;
const tslib_1 = require("tslib");
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
const teamsfx_api_1 = require("@microsoft/teamsfx-api");
const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
const path = tslib_1.__importStar(require("path"));
const versionMetadata_1 = require("./versionMetadata");
const pathUtils_1 = require("../component/utils/pathUtils");
const yaml_1 = require("yaml");
var OfficeManifestType;
(function (OfficeManifestType) {
OfficeManifestType[OfficeManifestType["XmlAddIn"] = 0] = "XmlAddIn";
OfficeManifestType[OfficeManifestType["MetaOsAddIn"] = 1] = "MetaOsAddIn";
})(OfficeManifestType = exports.OfficeManifestType || (exports.OfficeManifestType = {}));
function validateProjectSettings(projectSettings) {
var _a;
if (!projectSettings)
return "empty projectSettings";
if (!projectSettings.solutionSettings)
return undefined;
const solutionSettings = projectSettings.solutionSettings;
let validateRes = validateStringArray(solutionSettings.azureResources);
if (validateRes) {
return `solutionSettings.azureResources validation failed: ${validateRes}`;
}
validateRes = validateStringArray(solutionSettings.capabilities);
if (validateRes) {
return `solutionSettings.capabilities validation failed: ${validateRes}`;
}
validateRes = validateStringArray(solutionSettings.activeResourcePlugins);
if (validateRes) {
return `solutionSettings.activeResourcePlugins validation failed: ${validateRes}`;
}
if ((_a = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.solutionSettings) === null || _a === void 0 ? void 0 : _a.migrateFromV1) {
return "The project created before v2.0.0 is only supported in the Teams Toolkit before v3.4.0.";
}
return undefined;
}
exports.validateProjectSettings = validateProjectSettings;
function validateStringArray(arr, enums) {
if (!arr) {
return "is undefined";
}
if (!Array.isArray(arr)) {
return "is not array";
}
for (const element of arr) {
if (typeof element !== "string") {
return "array elements is not string type";
}
if (enums && !enums.includes(element)) {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
return `array elements is out of scope: ${enums}`;
}
}
return undefined;
}
function isValidProject(workspacePath) {
if (!workspacePath)
return false;
try {
return isValidProjectV3(workspacePath) || isValidProjectV2(workspacePath);
}
catch (e) {
return false;
}
}
exports.isValidProject = isValidProject;
function isValidOfficeAddInProject(workspacePath) {
const xmlManifestList = fetchManifestList(workspacePath, OfficeManifestType.XmlAddIn);
const metaOsManifestList = fetchManifestList(workspacePath, OfficeManifestType.MetaOsAddIn);
try {
if (xmlManifestList &&
xmlManifestList.length > 0 &&
(!metaOsManifestList || metaOsManifestList.length == 0)) {
return true;
}
else {
return false;
}
}
catch (e) {
return false;
}
}
exports.isValidOfficeAddInProject = isValidOfficeAddInProject;
function isManifestOnlyOfficeAddinProject(workspacePath) {
if (!workspacePath)
return false;
const srcPath = path.join(workspacePath, "src");
return !fs_extra_1.default.existsSync(srcPath);
}
exports.isManifestOnlyOfficeAddinProject = isManifestOnlyOfficeAddinProject;
function fetchManifestList(workspacePath, officeManifestType) {
if (!workspacePath)
return undefined;
const list = fs_extra_1.default.readdirSync(workspacePath);
const manifestList = list.filter((fileName) => officeManifestType == OfficeManifestType.XmlAddIn
? isOfficeXmlAddInManifest(fileName)
: isOfficeMetaOsAddInManifest(fileName));
return manifestList;
}
exports.fetchManifestList = fetchManifestList;
function isOfficeXmlAddInManifest(inputFileName) {
return (inputFileName.toLocaleLowerCase().indexOf("manifest") != -1 &&
inputFileName.toLocaleLowerCase().endsWith(".xml"));
}
exports.isOfficeXmlAddInManifest = isOfficeXmlAddInManifest;
function isOfficeMetaOsAddInManifest(inputFileName) {
return (inputFileName.toLocaleLowerCase().indexOf("manifest") != -1 &&
inputFileName.toLocaleLowerCase().endsWith(".json"));
}
exports.isOfficeMetaOsAddInManifest = isOfficeMetaOsAddInManifest;
function isValidProjectV3(workspacePath) {
if (isValidOfficeAddInProject(workspacePath)) {
return false;
}
const ymlFilePath = path.join(workspacePath, versionMetadata_1.MetadataV3.configFile);
const localYmlPath = path.join(workspacePath, versionMetadata_1.MetadataV3.localConfigFile);
if (fs_extra_1.default.pathExistsSync(ymlFilePath) || fs_extra_1.default.pathExistsSync(localYmlPath)) {
return true;
}
return false;
}
exports.isValidProjectV3 = isValidProjectV3;
function isValidProjectV2(workspacePath) {
const confFolderPath = path.resolve(workspacePath, `.${teamsfx_api_1.ConfigFolderName}`, "configs");
const settingsFile = path.resolve(confFolderPath, "projectSettings.json");
if (!fs_extra_1.default.existsSync(settingsFile)) {
return false;
}
const projectSettings = fs_extra_1.default.readJsonSync(settingsFile);
if (validateProjectSettings(projectSettings))
return false;
return true;
}
exports.isValidProjectV2 = isValidProjectV2;
function isVSProject(projectSettings) {
return (projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.programmingLanguage) === "csharp";
}
exports.isVSProject = isVSProject;
function getProjectMetadata(rootPath) {
if (!rootPath) {
return undefined;
}
try {
const ymlPath = pathUtils_1.pathUtils.getYmlFilePath(rootPath, "dev");
if (!ymlPath || !fs_extra_1.default.pathExistsSync(ymlPath)) {
return undefined;
}
const ymlContent = fs_extra_1.default.readFileSync(ymlPath, "utf-8");
const ymlObject = (0, yaml_1.parse)(ymlContent);
return {
projectId: (ymlObject === null || ymlObject === void 0 ? void 0 : ymlObject.projectId) ? ymlObject.projectId.toString() : "",
version: (ymlObject === null || ymlObject === void 0 ? void 0 : ymlObject.version) ? ymlObject.version.toString() : "",
};
}
catch (_a) {
return undefined;
}
}
exports.getProjectMetadata = getProjectMetadata;
//# sourceMappingURL=projectSettingsHelper.js.map
@@ -0,0 +1 @@
{"version":3,"file":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,OAAO,CAAC,CAAC;QACrD,MAAM,SAAS,GAAG,IAAA,YAAK,EAAC,UAAU,CAAC,CAAC;QACpC,OAAO;YACL,SAAS,EAAE,CAAA,SAAS,aAAT,SAAS,uBAAT,SAAS,CAAE,SAAS,EAAC,CAAC,CAAC,SAAS,CAAC,SAAS,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE;YACrE,OAAO,EAAE,CAAA,SAAS,aAAT,SAAS,uBAAT,SAAS,CAAE,OAAO,EAAC,CAAC,CAAC,SAAS,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE;SAChE,CAAC;KACH;IAAC,WAAM;QACN,OAAO,SAAS,CAAC;KAClB;AACH,CAAC;AApBD,gDAoBC"}
@@ -0,0 +1,40 @@
export declare enum TeamsfxConfigType {
projectSettingsJson = "projectSettings.json",
teamsappYml = "teamsapp.yml"
}
export declare const TeamsJsModule = "@microsoft/teams-js";
export declare const SPFxKey = "@microsoft/generator-sharepoint";
export declare enum TeamsfxVersionState {
Compatible = "compatible",
Upgradable = "upgradable",
Unsupported = "unsupported",
Invalid = "invalid"
}
export interface ProjectTypeResult {
isTeamsFx: boolean;
teamsfxConfigType?: TeamsfxConfigType;
teamsfxConfigVersion?: string;
teamsfxVersionState?: TeamsfxVersionState;
teamsfxProjectId?: string;
hasTeamsManifest: boolean;
manifestCapabilities?: string[];
manifestAppId?: string;
manifestVersion?: string;
dependsOnTeamsJs?: boolean;
isSPFx?: boolean;
officeAddinProjectType?: string;
lauguages: ("ts" | "js" | "csharp" | "java" | "python" | "c")[];
}
declare class ProjectTypeChecker {
scanFolder(currentPath: string, ignoreFolderName: string[], data: ProjectTypeResult, fileCallback: (filePath: string, data: ProjectTypeResult) => Promise<boolean>, maxDepth: number, currentDepth?: number): Promise<boolean>;
findManifestCallback(filePath: string, data: ProjectTypeResult): Promise<boolean>;
findProjectLanguateCallback(filePath: string, data: ProjectTypeResult): Promise<boolean>;
findTeamsFxCallback(filePath: string, data: ProjectTypeResult): Promise<boolean>;
findSPFxCallback(filePath: string, data: ProjectTypeResult): Promise<boolean>;
findOfficeAddinProject(filePath: string, data: ProjectTypeResult): boolean;
checkProjectType(projectPath: string): Promise<ProjectTypeResult>;
}
export declare function getCapabilities(manifest: any): string[];
export declare const projectTypeChecker: ProjectTypeChecker;
export {};
//# sourceMappingURL=projectTypeChecker.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"projectTypeChecker.d.ts","sourceRoot":"","sources":["../../src/common/projectTypeChecker.ts"],"names":[],"mappings":"AAUA,oBAAY,iBAAiB;IAC3B,mBAAmB,yBAAyB;IAC5C,WAAW,iBAAiB;CAC7B;AACD,eAAO,MAAM,aAAa,wBAAwB,CAAC;AAEnD,eAAO,MAAM,OAAO,oCAAoC,CAAC;AAEzD,oBAAY,mBAAmB;IAC7B,UAAU,eAAe;IACzB,UAAU,eAAe;IACzB,WAAW,gBAAgB;IAC3B,OAAO,YAAY;CACpB;AAED,MAAM,WAAW,iBAAiB;IAChC,SAAS,EAAE,OAAO,CAAC;IACnB,iBAAiB,CAAC,EAAE,iBAAiB,CAAC;IACtC,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,mBAAmB,CAAC,EAAE,mBAAmB,CAAC;IAC1C,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,gBAAgB,EAAE,OAAO,CAAC;IAC1B,oBAAoB,CAAC,EAAE,MAAM,EAAE,CAAC;IAChC,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,SAAS,EAAE,CAAC,IAAI,GAAG,IAAI,GAAG,QAAQ,GAAG,MAAM,GAAG,QAAQ,GAAG,GAAG,CAAC,EAAE,CAAC;CACjE;AAED,cAAM,kBAAkB;IAChB,UAAU,CACd,WAAW,EAAE,MAAM,EACnB,gBAAgB,EAAE,MAAM,EAAE,EAC1B,IAAI,EAAE,iBAAiB,EACvB,YAAY,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,iBAAiB,KAAK,OAAO,CAAC,OAAO,CAAC,EAC7E,QAAQ,EAAE,MAAM,EAChB,YAAY,SAAI;IAiCZ,oBAAoB,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,iBAAiB,GAAG,OAAO,CAAC,OAAO,CAAC;IAmBjF,2BAA2B,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,iBAAiB,GAAG,OAAO,CAAC,OAAO,CAAC;IAiCxF,mBAAmB,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,iBAAiB,GAAG,OAAO,CAAC,OAAO,CAAC;IAsDhF,gBAAgB,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,iBAAiB,GAAG,OAAO,CAAC,OAAO,CAAC;IAanF,sBAAsB,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,iBAAiB,GAAG,OAAO;IASpE,gBAAgB,CAAC,WAAW,EAAE,MAAM;CA6C3C;AACD,wBAAgB,eAAe,CAAC,QAAQ,EAAE,GAAG,GAAG,MAAM,EAAE,CAyCvD;AACD,eAAO,MAAM,kBAAkB,oBAA2B,CAAC"}
+244
View File
@@ -0,0 +1,244 @@
"use strict";
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.projectTypeChecker = exports.getCapabilities = exports.TeamsfxVersionState = exports.SPFxKey = exports.TeamsJsModule = exports.TeamsfxConfigType = void 0;
const tslib_1 = require("tslib");
const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
const path_1 = tslib_1.__importDefault(require("path"));
const semver_1 = tslib_1.__importDefault(require("semver"));
const yaml_1 = require("yaml");
const versionMetadata_1 = require("./versionMetadata");
const projectSettingsHelper_1 = require("./projectSettingsHelper");
var TeamsfxConfigType;
(function (TeamsfxConfigType) {
TeamsfxConfigType["projectSettingsJson"] = "projectSettings.json";
TeamsfxConfigType["teamsappYml"] = "teamsapp.yml";
})(TeamsfxConfigType = exports.TeamsfxConfigType || (exports.TeamsfxConfigType = {}));
exports.TeamsJsModule = "@microsoft/teams-js";
exports.SPFxKey = "@microsoft/generator-sharepoint";
var TeamsfxVersionState;
(function (TeamsfxVersionState) {
TeamsfxVersionState["Compatible"] = "compatible";
TeamsfxVersionState["Upgradable"] = "upgradable";
TeamsfxVersionState["Unsupported"] = "unsupported";
TeamsfxVersionState["Invalid"] = "invalid";
})(TeamsfxVersionState = exports.TeamsfxVersionState || (exports.TeamsfxVersionState = {}));
class ProjectTypeChecker {
async scanFolder(currentPath, ignoreFolderName, data, fileCallback, maxDepth, currentDepth = 0) {
const fileName = path_1.default.parse(currentPath).base;
if (ignoreFolderName.includes(fileName)) {
return true;
}
const res = await fileCallback(currentPath, data);
if (!res) {
return false;
}
const stat = await fs_extra_1.default.stat(currentPath);
if (stat.isDirectory()) {
if (currentDepth < maxDepth) {
const subFiles = await fs_extra_1.default.readdir(currentPath);
for (const subFile of subFiles) {
const subFilePath = path_1.default.join(currentPath, subFile);
const res = await this.scanFolder(subFilePath, ignoreFolderName, data, fileCallback, maxDepth, currentDepth + 1);
if (!res) {
return false;
}
}
}
}
return true;
}
async findManifestCallback(filePath, data) {
const fileName = path_1.default.parse(filePath).base;
if (fileName.toLowerCase().includes("manifest") && fileName.toLowerCase().endsWith(".json")) {
try {
const manifestContent = await fs_extra_1.default.readFile(filePath, "utf-8");
const manifestObject = JSON.parse(manifestContent);
const schemaLink = manifestObject["$schema"];
if (schemaLink && schemaLink.endsWith("/MicrosoftTeams.schema.json")) {
data.hasTeamsManifest = true;
data.manifestCapabilities = getCapabilities(manifestObject);
data.manifestAppId = manifestObject.id;
data.manifestVersion = manifestObject.manifestVersion;
return false;
}
}
catch (error) { }
}
return true;
}
async findProjectLanguateCallback(filePath, data) {
var _a;
const parsed = path_1.default.parse(filePath);
const fileName = parsed.base;
if (fileName === "tsconfig.json") {
data.lauguages.push("ts");
return false;
}
else if (fileName === "package.json") {
try {
const content = await fs_extra_1.default.readFile(filePath, "utf-8");
const json = JSON.parse(content);
if ((_a = json === null || json === void 0 ? void 0 : json.dependencies) === null || _a === void 0 ? void 0 : _a[exports.TeamsJsModule]) {
data.dependsOnTeamsJs = true;
}
const tsconfigExist = await fs_extra_1.default.pathExists(path_1.default.join(parsed.dir, "tsconfig.json"));
if (!tsconfigExist)
data.lauguages.push("js");
else
data.lauguages.push("ts");
return false;
}
catch (error) { }
}
else if (fileName.toLowerCase().endsWith(".csproj")) {
data.lauguages.push("csharp");
return false;
}
else if (fileName === "pom.xml" || fileName === "build.gradle") {
data.lauguages.push("java");
return false;
}
else if (fileName.toLowerCase() === "makefile") {
data.lauguages.push("c");
return false;
}
else if (fileName === "requirements.txt" || fileName === "pyproject.toml") {
data.lauguages.push("python");
return false;
}
return true;
}
async findTeamsFxCallback(filePath, data) {
const parsed = path_1.default.parse(filePath);
const fileName = parsed.base;
if (fileName === ".fx") {
const settingFile = path_1.default.join(filePath, "configs", "projectSettings.json");
const exists = await fs_extra_1.default.pathExists(settingFile);
if (exists) {
data.isTeamsFx = true;
data.teamsfxConfigType = TeamsfxConfigType.projectSettingsJson;
const json = await fs_extra_1.default.readJson(settingFile);
data.teamsfxConfigVersion = json.version;
data.teamsfxProjectId = json.projectId;
const solutionSettings = json.solutionSettings;
if (!solutionSettings ||
!(solutionSettings === null || solutionSettings === void 0 ? void 0 : solutionSettings.activeResourcePlugins) ||
!data.teamsfxConfigVersion) {
data.teamsfxVersionState = TeamsfxVersionState.Invalid;
}
else if (data.teamsfxConfigVersion) {
if (semver_1.default.gte(data.teamsfxConfigVersion, versionMetadata_1.MetadataV2.projectVersion) &&
semver_1.default.lte(data.teamsfxConfigVersion, versionMetadata_1.MetadataV2.projectMaxVersion)) {
data.teamsfxVersionState = TeamsfxVersionState.Upgradable;
}
else {
data.teamsfxVersionState = TeamsfxVersionState.Unsupported;
}
}
return false;
}
}
else if (fileName === versionMetadata_1.MetadataV3.configFile || fileName === versionMetadata_1.MetadataV3.localConfigFile) {
data.isTeamsFx = true;
data.teamsfxConfigType = TeamsfxConfigType.teamsappYml;
if (fileName === versionMetadata_1.MetadataV3.configFile) {
const yamlFileContent = await fs_extra_1.default.readFile(filePath, "utf8");
const appYaml = (0, yaml_1.parseDocument)(yamlFileContent);
data.teamsfxConfigVersion = appYaml.get("version");
data.teamsfxProjectId = appYaml.get("projectId");
if (!semver_1.default.valid(data.teamsfxConfigVersion) ||
semver_1.default.lt(data.teamsfxConfigVersion, versionMetadata_1.MetadataV3.unSupprotVersion)) {
data.teamsfxVersionState = TeamsfxVersionState.Compatible;
}
else {
data.teamsfxVersionState = TeamsfxVersionState.Unsupported;
}
}
else {
return true;
}
return false;
}
return true;
}
async findSPFxCallback(filePath, data) {
const parsed = path_1.default.parse(filePath);
const fileName = parsed.base;
if (fileName === ".yo-rc.json") {
const content = await fs_extra_1.default.readJson(filePath);
if (content[exports.SPFxKey]) {
data.isSPFx = true;
return false;
}
}
return true;
}
findOfficeAddinProject(filePath, data) {
if ((0, projectSettingsHelper_1.isValidOfficeAddInProject)(filePath)) {
data.officeAddinProjectType = "XML";
data.isTeamsFx = false;
return false;
}
return true;
}
async checkProjectType(projectPath) {
const result = {
isTeamsFx: false,
hasTeamsManifest: false,
dependsOnTeamsJs: false,
lauguages: [],
};
try {
await this.scanFolder(projectPath, ["node_modules", "bin", "build", "dist", ".vscode"], result, this.findManifestCallback, 2, 0);
await this.scanFolder(projectPath, ["node_modules", "bin", "build", "dist", ".vscode"], result, this.findProjectLanguateCallback, 2, 0);
//only scan direct sub folder
await this.scanFolder(projectPath, ["node_modules", "bin", "build", "dist", ".vscode"], result, this.findTeamsFxCallback, 1, 0);
await this.scanFolder(projectPath, ["node_modules", "bin", "build", "dist", ".vscode"], result, this.findSPFxCallback, 2, 0);
this.findOfficeAddinProject(projectPath, result);
}
catch (e) { }
return result;
}
}
function getCapabilities(manifest) {
var _a, _b, _c, _d;
const capabilities = [];
if (manifest.staticTabs && manifest.staticTabs.length > 0) {
capabilities.push("staticTab");
}
if (manifest.configurableTabs && manifest.configurableTabs.length > 0) {
capabilities.push("configurableTab");
}
if (manifest.bots && manifest.bots.length > 0) {
capabilities.push("bot");
}
if (manifest.composeExtensions && manifest.composeExtensions.length > 0) {
capabilities.push("composeExtension");
}
if (manifest.extensions && manifest.extensions.length > 0) {
capabilities.push("extension");
}
if (((_a = manifest.copilotExtensions) === null || _a === void 0 ? void 0 : _a.plugins) && manifest.copilotExtensions.plugins.length > 0) {
capabilities.push("plugin");
}
if (((_b = manifest.copilotExtensions) === null || _b === void 0 ? void 0 : _b.declarativeCopilots) &&
manifest.copilotExtensions.declarativeCopilots.length > 0) {
capabilities.push("copilotGpt");
}
if (((_c = manifest.copilotAgents) === null || _c === void 0 ? void 0 : _c.plugins) &&
manifest.copilotAgents.plugins.length > 0 &&
!capabilities.includes("plugin")) {
capabilities.push("plugin");
}
if (((_d = manifest.copilotAgents) === null || _d === void 0 ? void 0 : _d.declarativeAgents) &&
manifest.copilotAgents.declarativeAgents.length > 0 &&
!capabilities.includes("copilotGpt")) {
capabilities.push("copilotGpt");
}
return capabilities;
}
exports.getCapabilities = getCapabilities;
exports.projectTypeChecker = new ProjectTypeChecker();
//# sourceMappingURL=projectTypeChecker.js.map
File diff suppressed because one or more lines are too long
+4
View File
@@ -0,0 +1,4 @@
import { AxiosResponse, CancelToken } from "axios";
export declare function sendRequestWithRetry<T>(requestFn: () => Promise<AxiosResponse<T>>, tryLimits: number): Promise<AxiosResponse<T>>;
export declare function sendRequestWithTimeout<T>(requestFn: (cancelToken: CancelToken) => Promise<AxiosResponse<T>>, timeoutInMs: number, tryLimits?: number): Promise<AxiosResponse<T>>;
//# sourceMappingURL=requestUtils.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"requestUtils.d.ts","sourceRoot":"","sources":["../../src/common/requestUtils.ts"],"names":[],"mappings":"AAGA,OAAc,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,OAAO,CAAC;AAE1D,wBAAsB,oBAAoB,CAAC,CAAC,EAC1C,SAAS,EAAE,MAAM,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,EAC1C,SAAS,EAAE,MAAM,GAChB,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,CAwB3B;AACD,wBAAsB,sBAAsB,CAAC,CAAC,EAC5C,SAAS,EAAE,CAAC,WAAW,EAAE,WAAW,KAAK,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,EAClE,WAAW,EAAE,MAAM,EACnB,SAAS,SAAI,GACZ,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,CAe3B"}
+52
View File
@@ -0,0 +1,52 @@
"use strict";
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.sendRequestWithTimeout = exports.sendRequestWithRetry = void 0;
const tslib_1 = require("tslib");
const axios_1 = tslib_1.__importDefault(require("axios"));
async function sendRequestWithRetry(requestFn, tryLimits) {
var _a;
// !status means network error, see https://github.com/axios/axios/issues/383
const canTry = (status) => !status || (status >= 500 && status < 600);
let status;
let error;
for (let i = 0; i < tryLimits && canTry(status); i++) {
try {
const res = await requestFn();
if (res.status === 200 || res.status === 201) {
return res;
}
else {
error = new Error(`HTTP Request failed: ${JSON.stringify(res)}`);
}
status = res.status;
}
catch (e) {
error = e;
status = (_a = e === null || e === void 0 ? void 0 : e.response) === null || _a === void 0 ? void 0 : _a.status;
}
}
error !== null && error !== void 0 ? error : (error = new Error(`RequestWithRetry got bad tryLimits: ${tryLimits}`));
throw error;
}
exports.sendRequestWithRetry = sendRequestWithRetry;
async function sendRequestWithTimeout(requestFn, timeoutInMs, tryLimits = 1) {
const source = axios_1.default.CancelToken.source();
const timeout = setTimeout(() => {
source.cancel();
}, timeoutInMs);
try {
const res = await sendRequestWithRetry(() => requestFn(source.token), tryLimits);
clearTimeout(timeout);
return res;
}
catch (err) {
if (axios_1.default.isCancel(err)) {
throw new Error("Request timeout");
}
throw err;
}
}
exports.sendRequestWithTimeout = sendRequestWithTimeout;
//# sourceMappingURL=requestUtils.js.map
@@ -0,0 +1 @@
{"version":3,"file":"requestUtils.js","sourceRoot":"","sources":["../../src/common/requestUtils.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;;AAElC,0DAA0D;AAEnD,KAAK,UAAU,oBAAoB,CACxC,SAA0C,EAC1C,SAAiB;;IAEjB,6EAA6E;IAC7E,MAAM,MAAM,GAAG,CAAC,MAA0B,EAAE,EAAE,CAAC,CAAC,MAAM,IAAI,CAAC,MAAM,IAAI,GAAG,IAAI,MAAM,GAAG,GAAG,CAAC,CAAC;IAE1F,IAAI,MAA0B,CAAC;IAC/B,IAAI,KAAY,CAAC;IAEjB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,SAAS,IAAI,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC,EAAE,EAAE;QACpD,IAAI;YACF,MAAM,GAAG,GAAG,MAAM,SAAS,EAAE,CAAC;YAC9B,IAAI,GAAG,CAAC,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,MAAM,KAAK,GAAG,EAAE;gBAC5C,OAAO,GAAG,CAAC;aACZ;iBAAM;gBACL,KAAK,GAAG,IAAI,KAAK,CAAC,wBAAwB,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;aAClE;YACD,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC;SACrB;QAAC,OAAO,CAAM,EAAE;YACf,KAAK,GAAG,CAAC,CAAC;YACV,MAAM,GAAG,MAAA,CAAC,aAAD,CAAC,uBAAD,CAAC,CAAE,QAAQ,0CAAE,MAAM,CAAC;SAC9B;KACF;IAED,KAAK,aAAL,KAAK,cAAL,KAAK,IAAL,KAAK,GAAK,IAAI,KAAK,CAAC,uCAAuC,SAAS,EAAE,CAAC,EAAC;IACxE,MAAM,KAAK,CAAC;AACd,CAAC;AA3BD,oDA2BC;AACM,KAAK,UAAU,sBAAsB,CAC1C,SAAkE,EAClE,WAAmB,EACnB,SAAS,GAAG,CAAC;IAEb,MAAM,MAAM,GAAG,eAAK,CAAC,WAAW,CAAC,MAAM,EAAE,CAAC;IAC1C,MAAM,OAAO,GAAG,UAAU,CAAC,GAAG,EAAE;QAC9B,MAAM,CAAC,MAAM,EAAE,CAAC;IAClB,CAAC,EAAE,WAAW,CAAC,CAAC;IAChB,IAAI;QACF,MAAM,GAAG,GAAG,MAAM,oBAAoB,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,SAAS,CAAC,CAAC;QACjF,YAAY,CAAC,OAAO,CAAC,CAAC;QACtB,OAAO,GAAG,CAAC;KACZ;IAAC,OAAO,GAAY,EAAE;QACrB,IAAI,eAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE;YACvB,MAAM,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAC;SACpC;QACD,MAAM,GAAG,CAAC;KACX;AACH,CAAC;AAnBD,wDAmBC"}
+47
View File
@@ -0,0 +1,47 @@
export declare const SampleConfigTag = "v2.5.0";
export declare const SampleConfigBranchForPrerelease = "main";
export declare type SampleUrlInfo = {
owner: string;
repository: string;
ref: string;
dir: string;
};
export interface SampleConfig {
id: string;
onboardDate: Date;
title: string;
shortDescription: string;
fullDescription: string;
types: string[];
tags: string[];
time: string;
configuration: string;
suggested: boolean;
thumbnailPath: string;
gifUrl?: string;
maximumToolkitVersion?: string;
maximumCliVersion?: string;
minimumToolkitVersion?: string;
minimumCliVersion?: string;
downloadUrlInfo: SampleUrlInfo;
}
interface SampleCollection {
samples: SampleConfig[];
filterOptions: {
capabilities: string[];
languages: string[];
technologies: string[];
};
}
declare class SampleProvider {
private sampleCollection;
get SampleCollection(): Promise<SampleCollection>;
refreshSampleConfig(): Promise<SampleCollection>;
private fetchOnlineSampleConfig;
private parseOnlineSampleConfig;
getSampleReadmeHtml(sample: SampleConfig): Promise<string>;
private fetchRawFileContent;
}
export declare const sampleProvider: SampleProvider;
export {};
//# sourceMappingURL=samples.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"samples.d.ts","sourceRoot":"","sources":["../../src/common/samples.ts"],"names":[],"mappings":"AAeA,eAAO,MAAM,eAAe,WAAW,CAAC;AAExC,eAAO,MAAM,+BAA+B,SAAS,CAAC;AAEtD,oBAAY,aAAa,GAAG;IAC1B,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,MAAM,CAAC;IACnB,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;CACb,CAAC;AAEF,MAAM,WAAW,YAAY;IAC3B,EAAE,EAAE,MAAM,CAAC;IACX,WAAW,EAAE,IAAI,CAAC;IAClB,KAAK,EAAE,MAAM,CAAC;IACd,gBAAgB,EAAE,MAAM,CAAC;IACzB,eAAe,EAAE,MAAM,CAAC;IAExB,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,IAAI,EAAE,MAAM,EAAE,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,aAAa,EAAE,MAAM,CAAC;IACtB,SAAS,EAAE,OAAO,CAAC;IACnB,aAAa,EAAE,MAAM,CAAC;IACtB,MAAM,CAAC,EAAE,MAAM,CAAC;IAEhB,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAE3B,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,eAAe,EAAE,aAAa,CAAC;CAChC;AAED,UAAU,gBAAgB;IACxB,OAAO,EAAE,YAAY,EAAE,CAAC;IACxB,aAAa,EAAE;QACb,YAAY,EAAE,MAAM,EAAE,CAAC;QACvB,SAAS,EAAE,MAAM,EAAE,CAAC;QACpB,YAAY,EAAE,MAAM,EAAE,CAAC;KACxB,CAAC;CACH;AAOD,cAAM,cAAc;IAClB,OAAO,CAAC,gBAAgB,CAA+B;IAEvD,IAAW,gBAAgB,IAAI,OAAO,CAAC,gBAAgB,CAAC,CAKvD;IAEY,mBAAmB,IAAI,OAAO,CAAC,gBAAgB,CAAC;YAM/C,uBAAuB;IAsCrC,OAAO,CAAC,uBAAuB;IA4ClB,mBAAmB,CAAC,MAAM,EAAE,YAAY,GAAG,OAAO,CAAC,MAAM,CAAC;YA2BzD,mBAAmB;CAiBlC;AAED,eAAO,MAAM,cAAc,gBAAuB,CAAC"}
+144
View File
@@ -0,0 +1,144 @@
"use strict";
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.sampleProvider = exports.SampleConfigBranchForPrerelease = exports.SampleConfigTag = void 0;
const tslib_1 = require("tslib");
const axios_1 = tslib_1.__importDefault(require("axios"));
const hooks_1 = require("@feathersjs/hooks");
const globalVars_1 = require("./globalVars");
const common_1 = require("../error/common");
const featureFlags_1 = require("./featureFlags");
const requestUtils_1 = require("./requestUtils");
const packageJson = require("../../package.json");
const SampleConfigOwner = "OfficeDev";
const SampleConfigRepo = "TeamsFx-Samples";
const SampleConfigFile = ".config/samples-config-v3.json";
exports.SampleConfigTag = "v2.5.0";
// prerelease tag is always using a branch.
exports.SampleConfigBranchForPrerelease = "main";
class SampleProvider {
get SampleCollection() {
if (!this.sampleCollection) {
return this.refreshSampleConfig();
}
return Promise.resolve(this.sampleCollection);
}
async refreshSampleConfig() {
const { samplesConfig, ref } = await this.fetchOnlineSampleConfig();
this.sampleCollection = this.parseOnlineSampleConfig(samplesConfig, ref);
return this.sampleCollection;
}
async fetchOnlineSampleConfig() {
const version = packageJson.version;
const configBranchInEnv = process.env[featureFlags_1.FeatureFlagName.SampleConfigBranch];
let samplesConfig;
let ref = exports.SampleConfigTag;
// Set default value for branchOrTag
if (version.includes("alpha")) {
// daily build version always use 'dev' branch
ref = "dev";
}
else if (version.includes("beta")) {
// prerelease build version always use branch head for prerelease.
ref = exports.SampleConfigBranchForPrerelease;
}
else if (version.includes("rc")) {
// if there is a breaking change, the tag is not used by any stable version.
ref = exports.SampleConfigTag;
}
else {
// stable version uses the head of branch defined by feature flag when available
ref = exports.SampleConfigTag;
}
// Set branchOrTag value if branch in env is valid
if (configBranchInEnv) {
try {
const data = await this.fetchRawFileContent(configBranchInEnv);
ref = configBranchInEnv;
samplesConfig = data;
}
catch (e) { }
}
if (samplesConfig === undefined) {
samplesConfig = (await this.fetchRawFileContent(ref));
}
return { samplesConfig, ref };
}
parseOnlineSampleConfig(samplesConfig, ref) {
const samples = (samplesConfig === null || samplesConfig === void 0 ? void 0 : samplesConfig.samples.map((sample) => {
const isExternal = sample["downloadUrlInfo"] ? true : false;
let gifUrl = sample["gifPath"] !== undefined
? `https://raw.githubusercontent.com/${SampleConfigOwner}/${SampleConfigRepo}/${ref}/${sample["id"]}/${sample["gifPath"]}`
: undefined;
if (isExternal) {
const info = sample["downloadUrlInfo"];
gifUrl =
sample["gifPath"] !== undefined
? `https://raw.githubusercontent.com/${info.owner}/${info.repository}/${info.ref}/${info.dir}/${sample["gifPath"]}`
: undefined;
}
return Object.assign(Object.assign({}, sample), { onboardDate: new Date(sample["onboardDate"]), downloadUrlInfo: isExternal
? sample["downloadUrlInfo"]
: {
owner: SampleConfigOwner,
repository: SampleConfigRepo,
ref: ref,
dir: sample["id"],
}, gifUrl: gifUrl });
})) || [];
return {
samples,
filterOptions: {
capabilities: (samplesConfig === null || samplesConfig === void 0 ? void 0 : samplesConfig.filterOptions["capabilities"]) || [],
languages: (samplesConfig === null || samplesConfig === void 0 ? void 0 : samplesConfig.filterOptions["languages"]) || [],
technologies: (samplesConfig === null || samplesConfig === void 0 ? void 0 : samplesConfig.filterOptions["technologies"]) || [],
},
};
}
async getSampleReadmeHtml(sample) {
const urlInfo = sample.downloadUrlInfo;
const url = `https://api.github.com/repos/${urlInfo.owner}/${urlInfo.repository}/readme/${urlInfo.dir}/?ref=${urlInfo.ref}`;
try {
const readmeResponse = await (0, requestUtils_1.sendRequestWithTimeout)(async () => {
return await axios_1.default.get(url, {
headers: {
Accept: "application/vnd.github.html",
"X-GitHub-Api-Version": "2022-11-28",
},
});
}, 1000, 3);
if (readmeResponse && readmeResponse.data) {
return readmeResponse.data;
}
else {
return "";
}
}
catch (e) {
throw new common_1.AccessGithubError(url, "SampleProvider", e);
}
}
async fetchRawFileContent(branchOrTag) {
const url = `https://raw.githubusercontent.com/${SampleConfigOwner}/${SampleConfigRepo}/${branchOrTag}/${SampleConfigFile}`;
try {
const fileResponse = await (0, requestUtils_1.sendRequestWithTimeout)(async () => {
return await axios_1.default.get(url, { responseType: "json" });
}, 1000, 3);
if (fileResponse && fileResponse.data) {
return fileResponse.data;
}
}
catch (e) {
throw new common_1.AccessGithubError(url, "SampleProvider", e);
}
}
}
tslib_1.__decorate([
(0, hooks_1.hooks)([(0, globalVars_1.ErrorContextMW)({ component: "SampleProvider" })]),
tslib_1.__metadata("design:type", Function),
tslib_1.__metadata("design:paramtypes", [Object, String]),
tslib_1.__metadata("design:returntype", Object)
], SampleProvider.prototype, "parseOnlineSampleConfig", null);
exports.sampleProvider = new SampleProvider();
//# sourceMappingURL=samples.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"samples.js","sourceRoot":"","sources":["../../src/common/samples.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;;AAElC,0DAA0B;AAC1B,6CAA0C;AAC1C,6CAA8C;AAC9C,4CAAoD;AACpD,iDAAiD;AACjD,iDAAwD;AAExD,MAAM,WAAW,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC;AAElD,MAAM,iBAAiB,GAAG,WAAW,CAAC;AACtC,MAAM,gBAAgB,GAAG,iBAAiB,CAAC;AAC3C,MAAM,gBAAgB,GAAG,gCAAgC,CAAC;AAC7C,QAAA,eAAe,GAAG,Q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AAO,cAAc,CAAC,IAAc,CAAC;aACtC;iBAAM;gBACL,OAAO,EAAE,CAAC;aACX;SACF;QAAC,OAAO,CAAC,EAAE;YACV,MAAM,IAAI,0BAAiB,CAAC,GAAG,EAAE,gBAAgB,EAAE,CAAC,CAAC,CAAC;SACvD;IACH,CAAC;IAEO,KAAK,CAAC,mBAAmB,CAAC,WAAmB;QACnD,MAAM,GAAG,GAAG,qCAAqC,iBAAiB,IAAI,gBAAgB,IAAI,WAAW,IAAI,gBAAgB,EAAE,CAAC;QAC5H,IAAI;YACF,MAAM,YAAY,GAAG,MAAM,IAAA,qCAAsB,EAC/C,KAAK,IAAI,EAAE;gBACT,OAAO,MAAM,eAAK,CAAC,GAAG,CAAC,GAAG,EAAE,EAAE,YAAY,EAAE,MAAM,EAAE,CAAC,CAAC;YACxD,CAAC,EACD,IAAI,EACJ,CAAC,CACF,CAAC;YACF,IAAI,YAAY,IAAI,YAAY,CAAC,IAAI,EAAE;gBACrC,OAAO,YAAY,CAAC,IAAI,CAAC;aAC1B;SACF;QAAC,OAAO,CAAC,EAAE;YACV,MAAM,IAAI,0BAAiB,CAAC,GAAG,EAAE,gBAAgB,EAAE,CAAC,CAAC,CAAC;SACvD;IACH,CAAC;CACF;AAxFC;IADC,IAAA,aAAK,EAAC,CAAC,IAAA,2BAAc,EAAC,EAAE,SAAS,EAAE,gBAAgB,EAAE,CAAC,CAAC,CAAC;;;;6DA2CxD;AAgDU,QAAA,cAAc,GAAG,IAAI,cAAc,EAAE,CAAC"}
@@ -0,0 +1,22 @@
/**
* Bloom Filter is used to check whether a word is in the dictionary with less memory usage than normal hash map.
*/
export declare class BloomFilter {
private size;
private bitArray;
private numHashFunctions;
constructor();
private hash;
add(word: string): void;
contains(word: string): boolean;
static loadFromZipFile(zipFilename: string): BloomFilter;
}
declare class DictionaryMatcher {
bloomFilter: BloomFilter;
constructor();
match(text: string): "exact" | "contains" | "none";
}
export declare function trimNonAlphabetChars(token: string): string;
export declare const dictMatcher: DictionaryMatcher;
export {};
//# sourceMappingURL=dict.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"dict.d.ts","sourceRoot":"","sources":["../../../src/common/secretmasker/dict.ts"],"names":[],"mappings":"AAQA;;GAEG;AACH,qBAAa,WAAW;IACtB,OAAO,CAAC,IAAI,CAAa;IACzB,OAAO,CAAC,QAAQ,CAAa;IAC7B,OAAO,CAAC,gBAAgB,CAAK;;IAM7B,OAAO,CAAC,IAAI;IAML,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI;IAOvB,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO;WAqBxB,eAAe,CAAC,WAAW,EAAE,MAAM,GAAG,WAAW;CAmBhE;AAED,cAAM,iBAAiB;IACrB,WAAW,EAAE,WAAW,CAAC;;IAIzB,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,GAAG,UAAU,GAAG,MAAM;CAOnD;AAED,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAG1D;AAED,eAAO,MAAM,WAAW,mBAA0B,CAAC"}
+83
View File
@@ -0,0 +1,83 @@
"use strict";
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.dictMatcher = exports.trimNonAlphabetChars = exports.BloomFilter = void 0;
const tslib_1 = require("tslib");
const crypto = tslib_1.__importStar(require("crypto"));
const path = tslib_1.__importStar(require("path"));
const folder_1 = require("../../folder");
const adm_zip_1 = tslib_1.__importDefault(require("adm-zip"));
/**
* Bloom Filter is used to check whether a word is in the dictionary with less memory usage than normal hash map.
*/
class BloomFilter {
constructor() {
this.size = 100000000;
this.numHashFunctions = 7;
this.bitArray = new Uint8Array(this.size);
}
hash(word, seed) {
const hash = crypto.createHash("sha256");
hash.update(`${word}${seed}`);
return parseInt(hash.digest("hex").slice(0, 8), 16) % this.size;
}
add(word) {
for (let i = 0; i < this.numHashFunctions; i++) {
const index = this.hash(word, i);
this.bitArray[index] = 1;
}
}
contains(word) {
for (let i = 0; i < this.numHashFunctions; i++) {
const index = this.hash(word, i);
if (this.bitArray[index] === 0) {
return false;
}
}
return true;
}
// public saveToFile(filename: string): void {
// fs.writeFileSync(filename, this.bitArray);
// }
// public static loadFromFile(filename: string): BloomFilter {
// const bitArray = new Uint8Array(fs.readFileSync(filename));
// const bloomFilter = new BloomFilter();
// bloomFilter.bitArray = bitArray;
// return bloomFilter;
// }
static loadFromZipFile(zipFilename) {
// Read the zip file into memory
const zip = new adm_zip_1.default(zipFilename);
// Get the entries in the zip file
const zipEntries = zip.getEntries();
// Assuming the first file in the zip is the bit array file
const bitArrayFile = zipEntries[0];
// Read the content of the file as a buffer
const fileContents = bitArrayFile.getData();
// Create a new BloomFilter instance and populate it
const bloomFilter = new BloomFilter();
bloomFilter.bitArray = new Uint8Array(fileContents);
return bloomFilter;
}
}
exports.BloomFilter = BloomFilter;
class DictionaryMatcher {
constructor() {
this.bloomFilter = BloomFilter.loadFromZipFile(path.join((0, folder_1.getResourceFolder)(), "dict.zip"));
}
match(text) {
const input = trimNonAlphabetChars(text);
if (this.bloomFilter.contains(input)) {
return "exact";
}
return "none";
}
}
function trimNonAlphabetChars(token) {
// Regular expression to match non-alphabet characters at the beginning and end
return token.replace(/^[^a-zA-Z]+|[^a-zA-Z]+$/g, "");
}
exports.trimNonAlphabetChars = trimNonAlphabetChars;
exports.dictMatcher = new DictionaryMatcher();
//# sourceMappingURL=dict.js.map
@@ -0,0 +1 @@
{"version":3,"file":"dict.js","sourceRoot":"","sources":["../../../src/common/secretmasker/dict.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;;AAElC,uDAAiC;AACjC,mDAA6B;AAC7B,yCAAiD;AACjD,8DAA6B;AAE7B;;GAEG;AACH,MAAa,WAAW;IAKtB;QAJQ,SAAI,GAAG,SAAS,CAAC;QAEjB,qBAAgB,GAAG,CAAC,CAAC;QAG3B,IAAI,CAAC,QAAQ,GAAG,IAAI,UAAU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AAC,WAAW,CAAC,CAAC;QAEpC,kCAAkC;QAClC,MAAM,UAAU,GAAG,GAAG,CAAC,UAAU,EAAE,CAAC;QAEpC,2DAA2D;QAC3D,MAAM,YAAY,GAAG,UAAU,CAAC,CAAC,CAAC,CAAC;QAEnC,2CAA2C;QAC3C,MAAM,YAAY,GAAG,YAAY,CAAC,OAAO,EAAE,CAAC;QAE5C,oDAAoD;QACpD,MAAM,WAAW,GAAG,IAAI,WAAW,EAAE,CAAC;QACtC,WAAW,CAAC,QAAQ,GAAG,IAAI,UAAU,CAAC,YAAY,CAAC,CAAC;QAEpD,OAAO,WAAW,CAAC;IACrB,CAAC;CACF;AA9DD,kCA8DC;AAED,MAAM,iBAAiB;IAErB;QACE,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC,eAAe,CAAC,IAAI,CAAC,IAAI,CAAC,IAAA,0BAAiB,GAAE,EAAE,UAAU,CAAC,CAAC,CAAC;IAC7F,CAAC;IACD,KAAK,CAAC,IAAY;QAChB,MAAM,KAAK,GAAG,oBAAoB,CAAC,IAAI,CAAC,CAAC;QACzC,IAAI,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE;YACpC,OAAO,OAAO,CAAC;SAChB;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;CACF;AAED,SAAgB,oBAAoB,CAAC,KAAa;IAChD,+EAA+E;IAC/E,OAAO,KAAK,CAAC,OAAO,CAAC,0BAA0B,EAAE,EAAE,CAAC,CAAC;AACvD,CAAC;AAHD,oDAGC;AAEY,QAAA,WAAW,GAAG,IAAI,iBAAiB,EAAE,CAAC"}
@@ -0,0 +1,19 @@
export declare function combinations1(keys: string[]): string[];
export declare function combinations2(keys: string[]): string[];
export declare const CredKeywordsEndsWith: string[];
export declare const CredKeywordsEquals: string[];
export interface SplitterToken {
type: "splitter";
token: string;
}
export interface FeatureToken {
type: "feature";
token: string;
vector?: number[];
label?: number;
predict?: number;
}
export declare type Token = SplitterToken | FeatureToken;
export declare function tokenize(input: string): Token[];
export declare function extractFeatures(text: string): Token[];
//# sourceMappingURL=feature.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"feature.d.ts","sourceRoot":"","sources":["../../../src/common/secretmasker/feature.ts"],"names":[],"mappings":"AAKA,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,CAuBtD;AAED,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,CAQtD;AAED,eAAO,MAAM,oBAAoB,EAAE,MAAM,EAkNvC,CAAC;AAEH,eAAO,MAAM,kBAAkB,EAAE,MAAM,EAgBrC,CAAC;AAsDH,MAAM,WAAW,aAAa;IAC5B,IAAI,EAAE,UAAU,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,SAAS,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAClB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,oBAAY,KAAK,GAAG,aAAa,GAAG,YAAY,CAAC;AAEjD,wBAAgB,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,KAAK,EAAE,CAkB/C;AAED,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,KAAK,EAAE,CA4CrD"}
@@ -0,0 +1,389 @@
"use strict";
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractFeatures = exports.tokenize = exports.CredKeywordsEquals = exports.CredKeywordsEndsWith = exports.combinations2 = exports.combinations1 = void 0;
const dict_1 = require("./dict");
function combinations1(keys) {
const expandedKeys = [];
keys.forEach((key) => {
if (key.endsWith("password")) {
expandedKeys.push(key.substring(0, key.length - 4));
}
expandedKeys.push(key);
});
keys = expandedKeys;
let results = [];
results = results.concat(keys);
keys.forEach((key) => {
if (key.includes("_")) {
const key1 = key.split("_").join("");
const key2 = key.split("_").join("-");
results.push(key1);
results.push(key2);
}
});
return Array.from(new Set(results)).sort();
}
exports.combinations1 = combinations1;
function combinations2(keys) {
let results = [];
results = results.concat(keys);
keys.forEach((key) => {
results.push("-" + key);
results.push("--" + key);
});
return Array.from(new Set(results)).sort();
}
exports.combinations2 = combinations2;
exports.CredKeywordsEndsWith = combinations1([
"access_key",
"access_token",
"account_key",
"aci_token",
"ad_password",
"admin_key",
"admin_password",
"admin_token",
"api_key",
"api_key_id",
"api_secret",
"api_token",
"app_key",
"app_secret",
"application_token",
"auth_code",
"auth_header",
"auth_key",
"auth_password",
"auth_secret",
"auth_token",
"authenti",
"authorization",
"aws_access_key_id",
"aws_key",
"aws_secret_access_key",
"azure_cr",
"azure_secret",
"backup_key",
"bank_account_key",
"basic_auth",
"bearer_token",
"billing_key",
"cert_id",
"card_key",
"cert_password",
"certificate",
"client_certificate",
"client_id",
"client_key",
"client_secret",
"cloud_key",
"connection_secret",
"connection_string",
"consumer_id",
"consumer_key",
"consumer_secret",
"cookie_secret",
"credential",
"crypt_key",
"customer_key",
"data_encryption_key",
"db_password",
"db_secret",
"db_user",
"decryption_key",
"device_key",
"digital_signature",
"disk_encryption_key",
"docker_token",
"dropbox_token",
"encryption_cert",
"encryption_key",
"encryption_password",
"encryption_password_key",
"encryption_secret",
"env_key",
"firewall_password",
"ftp_password",
"ftp_user",
"gcp_credentials",
"gcp_key",
"gcp_private_key",
"git_token",
"gitlab_token",
"gpg_key",
"hash_key",
"hipaa_key",
"hmac_key",
"http_password",
"iam_access_key",
"id_token",
"install_key",
"integration_key",
"ipsec_key",
"jira_token",
"kerberos_key",
"key",
"keystore_password",
"kms_key",
"kube_config",
"kubernetes_token",
"ldap_bind_password",
"ldap_password",
"ldap_secret",
"license_key",
"login_key",
"mac_key",
"machine_key",
"management_certificate",
"master_key",
"merchant_key",
"mfa_key",
"mysql_password",
"oauth_id",
"oauth_secret",
"oauth_token",
"oracle_wallet_password",
"otp_key",
"passphrase",
"password",
"paypal_secret",
"pci_key",
"pem_key",
"pfx_password",
"pg_password",
"pgp_key",
"pre_shared_key",
"preshared_key",
"private_cert",
"private_encryption_key",
"private_key",
"private_key_password",
"private_password",
"private_ssh_key",
"private_token",
"proxy_password",
"rds_password",
"recovery_cert",
"recovery_key",
"recovery_password",
"redis_password",
"registry_key",
"registry_password",
"repo_token",
"rsa_private_key",
"s3_key",
"salt_key",
"saml_key",
"sas_key",
"sas_token",
"secret",
"secret_access_key",
"secret_id",
"secret_key_base",
"secure_string",
"security_key",
"security_token",
"sensitive_data_key",
"server_key",
"service_account",
"session_key",
"session_secret",
"session_token",
"sftp_password",
"shared_access_key",
"sign_in_key",
"sign_key",
"signing_cert",
"signing_key",
"signing_secret",
"slack_token",
"smtp_password",
"smtp_secret",
"social_security_key",
"ssh_cert",
"ssh_key",
"ssl_certificate",
"ssl_key",
"storage_account_key",
"storage_key",
"subscription_key",
"tfa_key",
"third_party_key",
"tls_key",
"tls_secret",
"token",
"token_key",
"token_secret",
"tpm_key",
"travis_token",
"trust_password",
"truststore_password",
"trust_store_password",
"two_factor_auth",
"two_factor_key",
"upload_token",
"user_key",
"user_pass",
"user_secret",
"username_password",
"validation_key",
"vault_cert",
"vault_password",
"vault_token",
"vcenter_password",
"vcs_token",
"vpn_key",
"vpn_password",
"web_auth_secret",
"webauthn_secret",
"webhook_secret",
"wifi_password",
"windows_password",
"windows_secret",
"wpa_password",
"x-functions-key",
"x509c",
"yubikey_password",
]);
exports.CredKeywordsEquals = combinations2([
"p",
"auth",
"bearer",
"code",
"creds",
"dapi",
"encrypt",
"jwt",
"pat",
"pin",
"pw",
"pwd",
"sas",
"sig",
"sign_in",
]);
// console.log(JSON.stringify(CredKeywordsEndsWith, null, 2));
function extractCharFeatures(token) {
let alphabetNum = 0;
let numberNum = 0;
let upperCaseNum = 0;
let lowerCaseNum = 0;
let specialCharNum = 0;
const frequency = {};
for (const char of token) {
if (char >= "0" && char <= "9") {
numberNum++;
}
else if ((char >= "a" && char <= "z") || (char >= "A" && char <= "Z")) {
if (char >= "a" && char <= "z") {
lowerCaseNum++;
}
else {
upperCaseNum++;
}
alphabetNum++;
}
else {
specialCharNum++;
}
frequency[char] = (frequency[char] || 0) + 1;
}
const length = token.length;
const entropy = -Object.values(frequency).reduce((acc, freq) => {
const p = freq / length;
return acc + p * Math.log2(p);
}, 0);
const specialCharRatio = specialCharNum / token.length;
const charDiversity = Object.keys(frequency).length / token.length;
let charCatDiversity = 0;
if (alphabetNum > 0)
charCatDiversity++;
if (numberNum > 0)
charCatDiversity++;
if (specialCharNum > 0)
charCatDiversity++;
if (upperCaseNum > 0)
charCatDiversity++;
if (lowerCaseNum > 0)
charCatDiversity++;
return {
specialCharRatio,
charDiversity,
charCatDiversity,
entropy,
};
}
// Helper function to check if a token contains common secret-related keywords
function containsSecretKeywords(token) {
if (exports.CredKeywordsEndsWith.some((keyword) => token.toLowerCase().endsWith(keyword)))
return 1;
if (exports.CredKeywordsEquals.some((keyword) => token.toLowerCase() === keyword))
return 1;
return 0;
}
function tokenize(input) {
// Regular expression to match JSON-specific delimiters and whitespace
const tokens = input.split(/(\s+|[{}[\],:"=;])/).filter((t) => t.length > 0); // Retain and filter out empty tokens
// Map the tokens into an array of Token objects
return tokens.map((t) => {
if (/\s+/.test(t) || /[{}[\],:"=;]/.test(t)) {
return {
type: "splitter",
token: t,
};
}
else {
return {
type: "feature",
token: t,
};
}
});
}
exports.tokenize = tokenize;
function extractFeatures(text) {
const allTokens = tokenize(text);
const featureTokens = allTokens.filter((t) => t.type === "feature");
for (let i = 0; i < featureTokens.length; i++) {
const tokenObj = featureTokens[i];
let token = tokenObj.token;
if (token.endsWith("<secret>")) {
token = token.slice(0, -8);
tokenObj.label = 1;
}
else {
tokenObj.label = 0;
}
// check if the previous token contains secret keyword
let preIndicator = 0;
if (i - 2 >= 0) {
const preToken = featureTokens[i - 1].token;
const prePreToken = featureTokens[i - 2].token;
if (containsSecretKeywords(preToken) === 1 || containsSecretKeywords(prePreToken) === 1) {
preIndicator = 1;
}
}
else if (i - 1 >= 0) {
const preToken = featureTokens[i - 1].token;
if (containsSecretKeywords(preToken) === 1) {
preIndicator = 1;
}
}
const dictMatchRes = dict_1.dictMatcher.match(token);
const isDictWord = dictMatchRes === "exact" || dictMatchRes === "contains" ? 1 : 0;
const { specialCharRatio, charDiversity, entropy, charCatDiversity } = extractCharFeatures(token);
tokenObj.vector = [
entropy,
specialCharRatio ? 1 : 0,
charDiversity,
charCatDiversity,
isDictWord,
preIndicator, //5
];
}
return allTokens;
}
exports.extractFeatures = extractFeatures;
//# sourceMappingURL=feature.js.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1,12 @@
interface SVMModel {
coef_: number[][];
intercept_: number[];
}
declare class SecretMasker {
model: SVMModel;
predict(features: number[]): number;
maskSecret(text: string, replace?: string): string;
}
export declare const secretMasker: SecretMasker;
export {};
//# sourceMappingURL=masker.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"masker.d.ts","sourceRoot":"","sources":["../../../src/common/secretmasker/masker.ts"],"names":[],"mappings":"AAYA,UAAU,QAAQ;IAChB,KAAK,EAAE,MAAM,EAAE,EAAE,CAAC;IAClB,UAAU,EAAE,MAAM,EAAE,CAAC;CACtB;AAED,cAAM,YAAY;IAChB,KAAK,EAAE,QAAQ,CAQb;IAEF,OAAO,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,MAAM;IAWnC,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,SAAQ,GAAG,MAAM;CAalD;AAED,eAAO,MAAM,YAAY,cAAqB,CAAC"}
@@ -0,0 +1,54 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.secretMasker = void 0;
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
const feature_1 = require("./feature");
const WHITE_LIST = [
"user-file-path",
"publish-app,",
"X-Correlation-ID",
"innerError",
"client-request-id",
];
class SecretMasker {
constructor() {
this.model = {
coef_: [
[
1.1407116640136614, -1.207072387304919, -0.42671866671203285, 1.760054415121175, 0.0,
1.776337354749609,
],
],
intercept_: [-9.96020839830461],
};
}
predict(features) {
const { coef_, intercept_ } = this.model;
// Calculate the dot product between the features and the coefficients
let decisionValue = intercept_[0]; // Start with the intercept
for (let i = 0; i < coef_[0].length; i++) {
decisionValue += coef_[0][i] * features[i];
}
// console.log("decisionValue", decisionValue);
// If the decision function value is positive, classify as 1 (secret), otherwise 0 (non-secret)
return decisionValue > 0 ? 1 : 0;
}
maskSecret(text, replace = "***") {
const tokens = (0, feature_1.extractFeatures)(text);
for (const token of tokens) {
if (token.type === "splitter")
continue;
if (WHITE_LIST.includes(token.token))
continue;
const prediction = this.predict(token.vector);
token.label = prediction;
if (prediction === 1) {
token.token = replace;
}
}
return tokens.map((o) => o.token).join("");
}
}
exports.secretMasker = new SecretMasker();
//# sourceMappingURL=masker.js.map
@@ -0,0 +1 @@
{"version":3,"file":"masker.js","sourceRoot":"","sources":["../../../src/common/secretmasker/masker.ts"],"names":[],"mappings":";;;AAAA,uCAAuC;AACvC,kCAAkC;AAClC,uCAA4C;AAE5C,MAAM,UAAU,GAAG;IACjB,gBAAgB;IAChB,cAAc;IACd,kBAAkB;IAClB,YAAY;IACZ,mBAAmB;CACpB,CAAC;AAOF,MAAM,YAAY;IAAlB;QACE,UAAK,GAAa;YAChB,KAAK,EAAE;gBACL;oBACE,kBAAkB,EAAE,CAAC,iBAAiB,EAAE,CAAC,mBAAmB,EAAE,iBAAiB,EAAE,GAAG;oBACpF,iBAAiB;iBAClB;aACF;YACD,UAAU,EAAE,CAAC,CAAC,gBAAgB,CAAC;SAChC,CAAC;IA0BJ,CAAC;IAxBC,OAAO,CAAC,QAAkB;QACxB,MAAM,EAAE,KAAK,EAAE,UAAU,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC;QACzC,sEAAsE;QACtE,IAAI,aAAa,GAAG,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,2BAA2B;QAC9D,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YACxC,aAAa,IAAI,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;SAC5C;QACD,+CAA+C;QAC/C,+FAA+F;QAC/F,OAAO,aAAa,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACnC,CAAC;IACD,UAAU,CAAC,IAAY,EAAE,OAAO,GAAG,KAAK;QACtC,MAAM,MAAM,GAAG,IAAA,yBAAe,EAAC,IAAI,CAAC,CAAC;QACrC,KAAK,MAAM,KAAK,IAAI,MAAM,EAAE;YAC1B,IAAI,KAAK,CAAC,IAAI,KAAK,UAAU;gBAAE,SAAS;YACxC,IAAI,UAAU,CAAC,QAAQ,CAAC,KAAK,CAAC,KAAK,CAAC;gBAAE,SAAS;YAC/C,MAAM,UAAU,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,MAAO,CAAC,CAAC;YAC/C,KAAK,CAAC,KAAK,GAAG,UAAU,CAAC;YACzB,IAAI,UAAU,KAAK,CAAC,EAAE;gBACpB,KAAK,CAAC,KAAK,GAAG,OAAO,CAAC;aACvB;SACF;QACD,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IAC7C,CAAC;CACF;AAEY,QAAA,YAAY,GAAG,IAAI,YAAY,EAAE,CAAC"}
+16
View File
@@ -0,0 +1,16 @@
export interface MaskSecretOptions {
threshold?: number;
whiteList?: string[];
replace?: string;
}
export declare function maskSecret(inputText?: string, option?: MaskSecretOptions): string;
export declare function maskSecretFromEnv(stdout: string, replace?: string): string;
export declare function convertToAlphanumericOnly(appName: string): string;
export declare function getResourceGroupNameFromResourceId(resourceId: string): string;
export declare function parseFromResourceId(pattern: RegExp, resourceId: string): string;
export declare function getUuid(): string;
export declare function getHashedEnv(envName: string): string;
export declare function loadingOptionsPlaceholder(): string;
export declare function loadingDefaultPlaceholder(): string;
export declare function isValidHttpUrl(input: string): boolean;
//# sourceMappingURL=stringUtils.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"stringUtils.d.ts","sourceRoot":"","sources":["../../src/common/stringUtils.ts"],"names":[],"mappings":"AAaA,MAAM,WAAW,iBAAiB;IAChC,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;IACrB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,wBAAgB,UAAU,CAAC,SAAS,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,iBAAiB,GAAG,MAAM,CAMjF;AAED,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,SAAiB,GAAG,MAAM,CAUlF;AAED,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAEjE;AAcD,wBAAgB,kCAAkC,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAM7E;AAED,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,MAAM,CAG/E;AAED,wBAAgB,OAAO,IAAI,MAAM,CAEhC;AAED,wBAAgB,YAAY,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAEpD;AAED,wBAAgB,yBAAyB,IAAI,MAAM,CAElD;AAED,wBAAgB,yBAAyB,IAAI,MAAM,CAElD;AAED,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAQrD"}
+91
View File
@@ -0,0 +1,91 @@
"use strict";
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.isValidHttpUrl = exports.loadingDefaultPlaceholder = exports.loadingOptionsPlaceholder = exports.getHashedEnv = exports.getUuid = exports.parseFromResourceId = exports.getResourceGroupNameFromResourceId = exports.convertToAlphanumericOnly = exports.maskSecretFromEnv = exports.maskSecret = void 0;
const tslib_1 = require("tslib");
const crypto = tslib_1.__importStar(require("crypto"));
const Handlebars = tslib_1.__importStar(require("handlebars"));
const url_1 = require("url");
const uuid = tslib_1.__importStar(require("uuid"));
const common_1 = require("../error/common");
const localizeUtils_1 = require("./localizeUtils");
const masker_1 = require("./secretmasker/masker");
const SECRET_REPLACE = "<REDACTED:secret>";
function maskSecret(inputText, option) {
if (!inputText)
return "";
const replace = (option === null || option === void 0 ? void 0 : option.replace) || SECRET_REPLACE;
let output = maskSecretFromEnv(inputText);
output = masker_1.secretMasker.maskSecret(output, replace);
return output;
}
exports.maskSecret = maskSecret;
function maskSecretFromEnv(stdout, replace = SECRET_REPLACE) {
for (const key of Object.keys(process.env)) {
if (key.startsWith("SECRET_")) {
const value = process.env[key];
if (value) {
stdout = stdout.replace(new RegExp(value, "g"), replace);
}
}
}
return stdout;
}
exports.maskSecretFromEnv = maskSecretFromEnv;
function convertToAlphanumericOnly(appName) {
return appName.replace(/[^\da-zA-Z]/g, "");
}
exports.convertToAlphanumericOnly = convertToAlphanumericOnly;
Handlebars.registerHelper("contains", (value, array) => {
array = array instanceof Array ? array : [array];
return array.indexOf(value) > -1 ? this : "";
});
Handlebars.registerHelper("notContains", (value, array) => {
array = array instanceof Array ? array : [array];
return array.indexOf(value) == -1 ? this : "";
});
Handlebars.registerHelper("equals", (value, target) => {
return value === target ? this : "";
});
function getResourceGroupNameFromResourceId(resourceId) {
const result = parseFromResourceId(/\/resourceGroups\/([^\/]*)\//i, resourceId);
if (!result) {
throw new common_1.FailedToParseResourceIdError("resource group name", resourceId);
}
return result;
}
exports.getResourceGroupNameFromResourceId = getResourceGroupNameFromResourceId;
function parseFromResourceId(pattern, resourceId) {
const result = resourceId.match(pattern);
return result ? result[1].trim() : "";
}
exports.parseFromResourceId = parseFromResourceId;
function getUuid() {
return uuid.v4();
}
exports.getUuid = getUuid;
function getHashedEnv(envName) {
return crypto.createHash("sha256").update(envName).digest("hex");
}
exports.getHashedEnv = getHashedEnv;
function loadingOptionsPlaceholder() {
return (0, localizeUtils_1.getLocalizedString)("ui.select.LoadingOptionsPlaceholder");
}
exports.loadingOptionsPlaceholder = loadingOptionsPlaceholder;
function loadingDefaultPlaceholder() {
return (0, localizeUtils_1.getLocalizedString)("ui.select.LoadingDefaultPlaceholder");
}
exports.loadingDefaultPlaceholder = loadingDefaultPlaceholder;
function isValidHttpUrl(input) {
let url;
try {
url = new url_1.URL(input);
return url.protocol === "http:" || url.protocol === "https:";
}
catch (e) {
return false;
}
}
exports.isValidHttpUrl = isValidHttpUrl;
//# sourceMappingURL=stringUtils.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"stringUtils.js","sourceRoot":"","sources":["../../src/common/stringUtils.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;;AAElC,uDAAiC;AACjC,+DAAyC;AACzC,6BAA0B;AAC1B,mDAA6B;AAC7B,4CAA+D;AAC/D,mDAAqD;AACrD,kDAAqD;AAErD,MAAM,cAAc,GAAG,mBAAmB,CAAC;AAQ3C,SAAgB,UAAU,CAAC,SAAkB,EAAE,MAA0B;IACvE,IAAI,CAAC,SAAS;QAAE,OAAO,EAAE,CAAC;IAC1B,MAAM,OAAO,GAAG,CAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,OAAO,KAAI,cAAc,CAAC;IAClD,IAAI,MAAM,GAAG,iBAAiB,CAAC,SAAS,CAAC,CAAC;IAC1C,MAAM,GAAG,qBAAY,CAAC,UAAU,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAClD,OAAO,MAAM,CAAC;AAChB,CAAC;AAND,gCAMC;AAED,SAAgB,iBAAiB,CAAC,MAAc,EAAE,OAAO,GAAG,cAAc;IACxE,KAAK,MAAM,GA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AI,GAAG,CAAC,QAAQ,KAAK,QAAQ,CAAC;KAC9D;IAAC,OAAO,CAAC,EAAE;QACV,OAAO,KAAK,CAAC;KACd;AACH,CAAC;AARD,wCAQC"}
+237
View File
@@ -0,0 +1,237 @@
import { FxError } from "@microsoft/teamsfx-api";
import { ProjectTypeResult } from "./projectTypeChecker";
export declare enum TelemetryProperty {
TriggerFrom = "trigger-from",
Component = "component",
Components = "components",
Feature = "feature",
Hosting = "hosting",
AppId = "appid",
BotId = "botid",
Success = "success",
ErrorType = "error-type",
ErrorCode = "error-code",
ErrorCat = "error-cat",
ErrorCat1 = "error-cat1",
ErrorCat2 = "error-cat2",
ErrorCat3 = "error-cat3",
ErrorComponent = "error-component",
ErrorInnerCode = "error-inner-code",
ErrorMessage = "err-message",
ErrorMethod = "error-method",
ErrorName = "error-name",
ErrorSource = "error-source",
ErrorStack = "err-stack",
ErrorData = "err-data",
ErrorStage = "error-stage",
SampleAppName = "sample-app-name",
ProjectId = "project-id",
NewProjectId = "new-project-id",
CorrelationId = "correlation-id",
Env = "env",
CustomizeResourceGroupType = "customize-resource-group-type",
EnvConfig = "env-config",
Status = "status",
HostType = "hostType",
AzureResources = "azure-resources",
Capabilities = "capabilities",
ActivePlugins = "active-plugins",
IsCopilotAllowed = "is-copilot-allowed",
IsSideloadingAllowed = "is-sideloading-allowed",
NeedMigrateAadManifest = "need-migrate-aad-manifest",
CheckCopilotTracingId = "copilot-trace-id",
CheckSideloadingStatusCode = "status-code",
CheckSideloadingMethod = "method",
CheckSideloadingUrl = "url",
TemplateGroup = "template-group",
TemplateLanguage = "template-language",
TemplateScenario = "template-scenario",
TemplateFallback = "template-fallback",
TemplateName = "template-name",
TenantId = "tenant-id",
TimeCost = "time-cost",
SampleDownloadDirectory = "sample-download-directory",
Fallback = "fallback",
HasSwitchedSubscription = "has-switched-subscription",
HasSwitchedM365Tenant = "has-switched-m365",
CustomizeSubscriptionType = "customize-subscription-type",
IsFromTdp = "is-from-developer-portal",
ToolkitVersion = "toolkit-version",
YmlName = "yml-name",
YmlSchemaVersion = "yml-schema-version",
GraphPermission = "graph-permission",
GraphPermissionHasRole = "graph-permission-has-role",
GraphPermissionHasAdminScope = "graph-permission-has-admin-scope",
GraphPermissionScopes = "graph-permission-scopes",
GraphPermissionRoles = "graph-permission-roles",
RscApplication = "rsc-application",
RscDelegated = "rsc-delegated",
WebApplicationId = "web-application-id",
AadManifest = "aad-manifest",
CustomCopilotAgent = "custom-copilot-agent",
CustomCopilotRAG = "custom-copilot-rag",
LlmService = "llm-service",
HasAzureOpenAIKey = "has-azure-openai-key",
HasAzureOpenAIEndpoint = "has-azure-openai-endpoint",
HasAzureOpenAIDeploymentName = "has-azure-openai-deployment-name",
HasOpenAIKey = "has-openai-key",
TDPTraceId = "tdp-trace-id",
MOSTraceId = "mos-trace-id",
MOSPATH = "mos-api-path"
}
export declare const TelemetryConstants: {
eventPrefix: string;
};
export declare enum TelemetryEvent {
Scaffold = "scaffold",
GenerateBicep = "generate-arm-templates",
LocalDebug = "local-debug",
PostLocalDebug = "post-local-debug",
Provision = "provision",
PostProvision = "post-provision",
PreDeploy = "pre-deploy",
Deploy = "deploy",
DownloadSampleStart = "download-sample-start",
DownloadSample = "download-sample",
CreateProject = "create",
AddFeature = "add-feature",
ProjectUpgrade = "project-upgrade",
ProjectUpgradeStart = "project-upgrade-start",
ReadJson = "read-json",
DecryptUserdata = "decrypt-userdata",
CheckCopilot = "check-copilot",
CheckResourceGroupStart = "check-resource-group-start",
CheckResourceGroup = "check-resource-group",
CheckSubscriptionStart = "check-subscription-start",
CheckSubscription = "check-subscription",
CheckSideloading = "check-sideloading",
EnvConfig = "env-config",
DisplayToolingUpdateNotification = "display-tooling-update-notification",
ProjectMigratorNotificationStart = "project-migrator-notification-start",
ProjectMigratorNotification = "project-migrator-notification",
ProjectMigratorMigrateStart = "project-migrator-migrate-start",
ProjectMigratorMigrate = "project-migrator-migrate",
ProjectMigratorPrecheckFailed = "project-migrator-pre-check-failed",
ProjectMigratorError = "project-migrator-error",
ProjectConsolidateNotificationStart = "project-consolidate-notification-start",
ProjectConsolidateNotification = "project-consolidate-notification",
ProjectConsolidateUpgradeStart = "project-consolidate-upgrade-start",
ProjectConsolidateUpgrade = "project-consolidate-upgrade",
ProjectConsolidateAddLocalEnvStart = "project-consolidate-add-local-env-start",
ProjectConsolidateAddLocalEnv = "project-consolidate-add-local-env",
ProjectConsolidateAddSPFXManifestStart = "project-consolidate-add-spfx-manifest-start",
ProjectConsolidateAddSPFXManifest = "project-consolidate-add-spfx-manifest",
ProjectConsolidateCopyAzureManifestStart = "project-consolidate-copy-azure-manifest-start",
ProjectConsolidateCopyAzureManifest = "project-consolidate-copy-azure-manifest",
ProjectConsolidateAddAzureManifestStart = "project-consolidate-add-azure-manifest-start",
ProjectConsolidateAddAzureManifest = "project-consolidate-add-azure-manifest",
ProjectConsolidateBackupConfigStart = "project-consolidate-backup-config-start",
ProjectConsolidateBackupConfig = "project-consolidate-backup-config",
ProjectConsolidateGuideStart = "project-Consolidate-guide-start",
ProjectConsolidateGuide = "project-consolidate-guide",
ProjectConsolidateError = "project-consolidate-error",
ProjectConsolidateCheckManifestError = "project-consolidate-check-manifest-error",
DetectPortStart = "detect-port-start",
DetectPort = "detect-port",
FillProjectId = "fill-project-id",
ScaffoldFromTemplatesStart = "scaffold-from-templates-start",
ScaffoldFromTemplates = "scaffold-from-templates",
GenerateTemplate = "generate-template",
GenerateSample = "generate-sample",
ConfirmProvision = "confirm-provision",
CheckLocalDebugTenant = "check-local-debug-tenant",
DebugSetUpSSO = "debug-set-up-sso",
DeploymentInfoNotFound = "deployment-info-not-found",
InstallScriptNotFound = "install-script-not-found",
SkipDeploy = "skip-deploy",
PublishInDeveloperPortal = "publish-in-developer-portal",
MetaData = "metadata",
ProjectType = "project-type",
DependencyApi = "dependency-api",
AppStudioApi = "app-studio-api",
MOSApi = "ttk-mos-api",
ViewPluginManifestAfterAdded = "view-plugin-manifest-after-added"
}
export declare enum ProjectTypeProps {
IsTeamsFx = "is-teamsfx",
TeamsfxConfigType = "teamsfx-config-type",
TeamsfxConfigVersion = "teamsfx-config-version",
TeamsfxVersionState = "teamsfx-version-state",
TeamsfxProjectId = "teamsfx-project-id",
TeamsManifest = "has-manifest",
TeamsManifestVersion = "manifest-version",
TeamsManifestAppId = "manifest-app-id",
TeamsManifestCapabilities = "manifest-capabilities",
TeamsJs = "teams-js",
Lauguages = "languages",
OfficeAddinProjectType = "office-addin-project-type"
}
export declare enum TelemetrySuccess {
Yes = "yes",
No = "no"
}
export declare enum TelemetryErrorType {
UserError = "user",
SystemError = "system"
}
export declare enum Component {
vsc = "extension",
cli = "cli",
vs = "vs",
core = "core"
}
export declare enum CustomizeResourceGroupType {
CommandLine = "command-line",
EnvConfig = "env-config",
EnvState = "env-state",
InteractiveCreateDefault = "interactive-create-default",
InteractiveCreateCustomized = "interactive-create-customized",
InteractiveUseExisting = "interactive-use-existing",
FallbackDefault = "fallback-default"
}
export declare enum CustomizeSubscriptionType {
CommandLine = "command-line",
EnvConfig = "env-config",
EnvState = "env-state",
Default = "default"
}
export declare enum ProjectMigratorStatus {
OK = "ok",
Cancel = "cancel"
}
export declare enum WebApplicationIdValue {
None = "none",
Default = "default",
Customized = "customized"
}
export declare enum ProjectMigratorGuideStatus {
Reload = "reload",
LearnMore = "learn-more",
Cancel = "cancel"
}
export declare enum ApiSpecTelemetryPropertis {
SpecNotValidDetails = "spec-not-valid-details",
InvalidApiSpec = "invalid-api-spec"
}
export declare function getQuestionValidationErrorEventName(questionName: string): string;
export declare function sendTelemetryEvent(component: string, eventName: string, properties?: {
[p: string]: string;
}, measurements?: {
[p: string]: number;
}): void;
export declare function sendTelemetryErrorEvent(component: string, eventName: string, fxError: FxError, properties?: {
[p: string]: string;
}): void;
declare class TelemetryUtils {
/**
* fill in telemetry properties for FxError
* @param error FxError
* @param props teletry properties
*/
fillInErrorProperties(props: Record<string, string>, error: FxError): void;
fillinProjectTypeProperties(props: Record<string, string>, projectTypeRes: ProjectTypeResult): void;
extractMethodNamesFromErrorStack(stack?: string): string;
}
export declare const telemetryUtils: TelemetryUtils;
export {};
//# sourceMappingURL=telemetry.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"telemetry.d.ts","sourceRoot":"","sources":["../../src/common/telemetry.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,OAAO,EAAe,MAAM,wBAAwB,CAAC;AAG9D,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAGzD,oBAAY,iBAAiB;IAC3B,WAAW,iBAAiB;IAC5B,SAAS,cAAc;IACvB,UAAU,eAAe;IACzB,OAAO,YAAY;IACnB,OAAO,YAAY;IACnB,KAAK,UAAU;IACf,KAAK,UAAU;IACf,OAAO,YAAY;IACnB,SAAS,eAAe;IACxB,SAAS,eAAe;IACxB,QAAQ,cAAc;IACtB,SAAS,eAAe;IACxB,SAAS,eAAe;IACxB,SAAS,eAAe;IACxB,cAAc,oBAAoB;IAClC,cAAc,qBAAqB;IACnC,YAAY,gBAAgB;IAC5B,WAAW,iBAAiB;IAC5B,SAAS,eAAe;IACxB,WAAW,iBAAiB;IAC5B,UAAU,cAAc;IACxB,SAAS,aAAa;IACtB,UAAU,gBAAgB;IAC1B,aAAa,oBAAoB;IACjC,SAAS,eAAe;IACxB,YAAY,mBAAmB;IAC/B,aAAa,mBAAmB;IAChC,GAAG,QAAQ;IACX,0BAA0B,kCAAkC;IAC5D,SAAS,eAAe;IACxB,MAAM,WAAW;IACjB,QAAQ,aAAa;IACrB,cAAc,oBAAoB;IAClC,YAAY,iBAAiB;IAC7B,aAAa,mBAAmB;IAChC,gBAAgB,uBAAuB;IACvC,oBAAoB,2BAA2B;IAC/C,sBAAsB,8BAA8B;IACpD,qBAAqB,qBAAqB;IAC1C,0BAA0B,gBAAgB;IAC1C,sBAAsB,WAAW;IACjC,mBAAmB,QAAQ;IAC3B,aAAa,mBAAmB;IAChC,gBAAgB,sBAAsB;IACtC,gBAAgB,sBAAsB;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M,EACjB,SAAS,EAAE,MAAM,EACjB,OAAO,EAAE,OAAO,EAChB,UAAU,CAAC,EAAE;IAAE,CAAC,CAAC,EAAE,MAAM,GAAG,MAAM,CAAA;CAAE,GACnC,IAAI,CASN;AAED,cAAM,cAAc;IAClB;;;;OAIG;IACH,qBAAqB,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI;IAoC1E,2BAA2B,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,cAAc,EAAE,iBAAiB;IAmB5F,gCAAgC,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM;CAUzD;AAED,eAAO,MAAM,cAAc,gBAAuB,CAAC"}
+327
View File
@@ -0,0 +1,327 @@
"use strict";
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.telemetryUtils = exports.sendTelemetryErrorEvent = exports.sendTelemetryEvent = exports.getQuestionValidationErrorEventName = exports.ApiSpecTelemetryPropertis = exports.ProjectMigratorGuideStatus = exports.WebApplicationIdValue = exports.ProjectMigratorStatus = exports.CustomizeSubscriptionType = exports.CustomizeResourceGroupType = exports.Component = exports.TelemetryErrorType = exports.TelemetrySuccess = exports.ProjectTypeProps = exports.TelemetryEvent = exports.TelemetryConstants = exports.TelemetryProperty = void 0;
const teamsfx_api_1 = require("@microsoft/teamsfx-api");
const lodash_1 = require("lodash");
const globalVars_1 = require("./globalVars");
const stringUtils_1 = require("./stringUtils");
var TelemetryProperty;
(function (TelemetryProperty) {
TelemetryProperty["TriggerFrom"] = "trigger-from";
TelemetryProperty["Component"] = "component";
TelemetryProperty["Components"] = "components";
TelemetryProperty["Feature"] = "feature";
TelemetryProperty["Hosting"] = "hosting";
TelemetryProperty["AppId"] = "appid";
TelemetryProperty["BotId"] = "botid";
TelemetryProperty["Success"] = "success";
TelemetryProperty["ErrorType"] = "error-type";
TelemetryProperty["ErrorCode"] = "error-code";
TelemetryProperty["ErrorCat"] = "error-cat";
TelemetryProperty["ErrorCat1"] = "error-cat1";
TelemetryProperty["ErrorCat2"] = "error-cat2";
TelemetryProperty["ErrorCat3"] = "error-cat3";
TelemetryProperty["ErrorComponent"] = "error-component";
TelemetryProperty["ErrorInnerCode"] = "error-inner-code";
TelemetryProperty["ErrorMessage"] = "err-message";
TelemetryProperty["ErrorMethod"] = "error-method";
TelemetryProperty["ErrorName"] = "error-name";
TelemetryProperty["ErrorSource"] = "error-source";
TelemetryProperty["ErrorStack"] = "err-stack";
TelemetryProperty["ErrorData"] = "err-data";
TelemetryProperty["ErrorStage"] = "error-stage";
TelemetryProperty["SampleAppName"] = "sample-app-name";
TelemetryProperty["ProjectId"] = "project-id";
TelemetryProperty["NewProjectId"] = "new-project-id";
TelemetryProperty["CorrelationId"] = "correlation-id";
TelemetryProperty["Env"] = "env";
TelemetryProperty["CustomizeResourceGroupType"] = "customize-resource-group-type";
TelemetryProperty["EnvConfig"] = "env-config";
TelemetryProperty["Status"] = "status";
TelemetryProperty["HostType"] = "hostType";
TelemetryProperty["AzureResources"] = "azure-resources";
TelemetryProperty["Capabilities"] = "capabilities";
TelemetryProperty["ActivePlugins"] = "active-plugins";
TelemetryProperty["IsCopilotAllowed"] = "is-copilot-allowed";
TelemetryProperty["IsSideloadingAllowed"] = "is-sideloading-allowed";
TelemetryProperty["NeedMigrateAadManifest"] = "need-migrate-aad-manifest";
TelemetryProperty["CheckCopilotTracingId"] = "copilot-trace-id";
TelemetryProperty["CheckSideloadingStatusCode"] = "status-code";
TelemetryProperty["CheckSideloadingMethod"] = "method";
TelemetryProperty["CheckSideloadingUrl"] = "url";
TelemetryProperty["TemplateGroup"] = "template-group";
TelemetryProperty["TemplateLanguage"] = "template-language";
TelemetryProperty["TemplateScenario"] = "template-scenario";
TelemetryProperty["TemplateFallback"] = "template-fallback";
TelemetryProperty["TemplateName"] = "template-name";
TelemetryProperty["TenantId"] = "tenant-id";
TelemetryProperty["TimeCost"] = "time-cost";
TelemetryProperty["SampleDownloadDirectory"] = "sample-download-directory";
TelemetryProperty["Fallback"] = "fallback";
TelemetryProperty["HasSwitchedSubscription"] = "has-switched-subscription";
TelemetryProperty["HasSwitchedM365Tenant"] = "has-switched-m365";
TelemetryProperty["CustomizeSubscriptionType"] = "customize-subscription-type";
TelemetryProperty["IsFromTdp"] = "is-from-developer-portal";
TelemetryProperty["ToolkitVersion"] = "toolkit-version";
TelemetryProperty["YmlName"] = "yml-name";
TelemetryProperty["YmlSchemaVersion"] = "yml-schema-version";
TelemetryProperty["GraphPermission"] = "graph-permission";
TelemetryProperty["GraphPermissionHasRole"] = "graph-permission-has-role";
TelemetryProperty["GraphPermissionHasAdminScope"] = "graph-permission-has-admin-scope";
TelemetryProperty["GraphPermissionScopes"] = "graph-permission-scopes";
TelemetryProperty["GraphPermissionRoles"] = "graph-permission-roles";
TelemetryProperty["RscApplication"] = "rsc-application";
TelemetryProperty["RscDelegated"] = "rsc-delegated";
TelemetryProperty["WebApplicationId"] = "web-application-id";
TelemetryProperty["AadManifest"] = "aad-manifest";
TelemetryProperty["CustomCopilotAgent"] = "custom-copilot-agent";
TelemetryProperty["CustomCopilotRAG"] = "custom-copilot-rag";
TelemetryProperty["LlmService"] = "llm-service";
TelemetryProperty["HasAzureOpenAIKey"] = "has-azure-openai-key";
TelemetryProperty["HasAzureOpenAIEndpoint"] = "has-azure-openai-endpoint";
TelemetryProperty["HasAzureOpenAIDeploymentName"] = "has-azure-openai-deployment-name";
TelemetryProperty["HasOpenAIKey"] = "has-openai-key";
TelemetryProperty["TDPTraceId"] = "tdp-trace-id";
TelemetryProperty["MOSTraceId"] = "mos-trace-id";
TelemetryProperty["MOSPATH"] = "mos-api-path";
})(TelemetryProperty = exports.TelemetryProperty || (exports.TelemetryProperty = {}));
exports.TelemetryConstants = {
eventPrefix: "-start",
};
var TelemetryEvent;
(function (TelemetryEvent) {
TelemetryEvent["Scaffold"] = "scaffold";
TelemetryEvent["GenerateBicep"] = "generate-arm-templates";
TelemetryEvent["LocalDebug"] = "local-debug";
TelemetryEvent["PostLocalDebug"] = "post-local-debug";
TelemetryEvent["Provision"] = "provision";
TelemetryEvent["PostProvision"] = "post-provision";
TelemetryEvent["PreDeploy"] = "pre-deploy";
TelemetryEvent["Deploy"] = "deploy";
TelemetryEvent["DownloadSampleStart"] = "download-sample-start";
TelemetryEvent["DownloadSample"] = "download-sample";
TelemetryEvent["CreateProject"] = "create";
TelemetryEvent["AddFeature"] = "add-feature";
TelemetryEvent["ProjectUpgrade"] = "project-upgrade";
TelemetryEvent["ProjectUpgradeStart"] = "project-upgrade-start";
TelemetryEvent["ReadJson"] = "read-json";
TelemetryEvent["DecryptUserdata"] = "decrypt-userdata";
TelemetryEvent["CheckCopilot"] = "check-copilot";
TelemetryEvent["CheckResourceGroupStart"] = "check-resource-group-start";
TelemetryEvent["CheckResourceGroup"] = "check-resource-group";
TelemetryEvent["CheckSubscriptionStart"] = "check-subscription-start";
TelemetryEvent["CheckSubscription"] = "check-subscription";
TelemetryEvent["CheckSideloading"] = "check-sideloading";
TelemetryEvent["EnvConfig"] = "env-config";
TelemetryEvent["DisplayToolingUpdateNotification"] = "display-tooling-update-notification";
TelemetryEvent["ProjectMigratorNotificationStart"] = "project-migrator-notification-start";
TelemetryEvent["ProjectMigratorNotification"] = "project-migrator-notification";
TelemetryEvent["ProjectMigratorMigrateStart"] = "project-migrator-migrate-start";
TelemetryEvent["ProjectMigratorMigrate"] = "project-migrator-migrate";
TelemetryEvent["ProjectMigratorPrecheckFailed"] = "project-migrator-pre-check-failed";
TelemetryEvent["ProjectMigratorError"] = "project-migrator-error";
TelemetryEvent["ProjectConsolidateNotificationStart"] = "project-consolidate-notification-start";
TelemetryEvent["ProjectConsolidateNotification"] = "project-consolidate-notification";
TelemetryEvent["ProjectConsolidateUpgradeStart"] = "project-consolidate-upgrade-start";
TelemetryEvent["ProjectConsolidateUpgrade"] = "project-consolidate-upgrade";
TelemetryEvent["ProjectConsolidateAddLocalEnvStart"] = "project-consolidate-add-local-env-start";
TelemetryEvent["ProjectConsolidateAddLocalEnv"] = "project-consolidate-add-local-env";
TelemetryEvent["ProjectConsolidateAddSPFXManifestStart"] = "project-consolidate-add-spfx-manifest-start";
TelemetryEvent["ProjectConsolidateAddSPFXManifest"] = "project-consolidate-add-spfx-manifest";
TelemetryEvent["ProjectConsolidateCopyAzureManifestStart"] = "project-consolidate-copy-azure-manifest-start";
TelemetryEvent["ProjectConsolidateCopyAzureManifest"] = "project-consolidate-copy-azure-manifest";
TelemetryEvent["ProjectConsolidateAddAzureManifestStart"] = "project-consolidate-add-azure-manifest-start";
TelemetryEvent["ProjectConsolidateAddAzureManifest"] = "project-consolidate-add-azure-manifest";
TelemetryEvent["ProjectConsolidateBackupConfigStart"] = "project-consolidate-backup-config-start";
TelemetryEvent["ProjectConsolidateBackupConfig"] = "project-consolidate-backup-config";
TelemetryEvent["ProjectConsolidateGuideStart"] = "project-Consolidate-guide-start";
TelemetryEvent["ProjectConsolidateGuide"] = "project-consolidate-guide";
TelemetryEvent["ProjectConsolidateError"] = "project-consolidate-error";
TelemetryEvent["ProjectConsolidateCheckManifestError"] = "project-consolidate-check-manifest-error";
TelemetryEvent["DetectPortStart"] = "detect-port-start";
TelemetryEvent["DetectPort"] = "detect-port";
TelemetryEvent["FillProjectId"] = "fill-project-id";
TelemetryEvent["ScaffoldFromTemplatesStart"] = "scaffold-from-templates-start";
TelemetryEvent["ScaffoldFromTemplates"] = "scaffold-from-templates";
TelemetryEvent["GenerateTemplate"] = "generate-template";
TelemetryEvent["GenerateSample"] = "generate-sample";
TelemetryEvent["ConfirmProvision"] = "confirm-provision";
TelemetryEvent["CheckLocalDebugTenant"] = "check-local-debug-tenant";
TelemetryEvent["DebugSetUpSSO"] = "debug-set-up-sso";
TelemetryEvent["DeploymentInfoNotFound"] = "deployment-info-not-found";
TelemetryEvent["InstallScriptNotFound"] = "install-script-not-found";
TelemetryEvent["SkipDeploy"] = "skip-deploy";
TelemetryEvent["PublishInDeveloperPortal"] = "publish-in-developer-portal";
TelemetryEvent["MetaData"] = "metadata";
TelemetryEvent["ProjectType"] = "project-type";
TelemetryEvent["DependencyApi"] = "dependency-api";
TelemetryEvent["AppStudioApi"] = "app-studio-api";
TelemetryEvent["MOSApi"] = "ttk-mos-api";
TelemetryEvent["ViewPluginManifestAfterAdded"] = "view-plugin-manifest-after-added";
})(TelemetryEvent = exports.TelemetryEvent || (exports.TelemetryEvent = {}));
var ProjectTypeProps;
(function (ProjectTypeProps) {
ProjectTypeProps["IsTeamsFx"] = "is-teamsfx";
ProjectTypeProps["TeamsfxConfigType"] = "teamsfx-config-type";
ProjectTypeProps["TeamsfxConfigVersion"] = "teamsfx-config-version";
ProjectTypeProps["TeamsfxVersionState"] = "teamsfx-version-state";
ProjectTypeProps["TeamsfxProjectId"] = "teamsfx-project-id";
ProjectTypeProps["TeamsManifest"] = "has-manifest";
ProjectTypeProps["TeamsManifestVersion"] = "manifest-version";
ProjectTypeProps["TeamsManifestAppId"] = "manifest-app-id";
ProjectTypeProps["TeamsManifestCapabilities"] = "manifest-capabilities";
ProjectTypeProps["TeamsJs"] = "teams-js";
ProjectTypeProps["Lauguages"] = "languages";
ProjectTypeProps["OfficeAddinProjectType"] = "office-addin-project-type";
})(ProjectTypeProps = exports.ProjectTypeProps || (exports.ProjectTypeProps = {}));
var TelemetrySuccess;
(function (TelemetrySuccess) {
TelemetrySuccess["Yes"] = "yes";
TelemetrySuccess["No"] = "no";
})(TelemetrySuccess = exports.TelemetrySuccess || (exports.TelemetrySuccess = {}));
var TelemetryErrorType;
(function (TelemetryErrorType) {
TelemetryErrorType["UserError"] = "user";
TelemetryErrorType["SystemError"] = "system";
})(TelemetryErrorType = exports.TelemetryErrorType || (exports.TelemetryErrorType = {}));
var Component;
(function (Component) {
Component["vsc"] = "extension";
Component["cli"] = "cli";
Component["vs"] = "vs";
Component["core"] = "core";
})(Component = exports.Component || (exports.Component = {}));
var CustomizeResourceGroupType;
(function (CustomizeResourceGroupType) {
CustomizeResourceGroupType["CommandLine"] = "command-line";
CustomizeResourceGroupType["EnvConfig"] = "env-config";
CustomizeResourceGroupType["EnvState"] = "env-state";
CustomizeResourceGroupType["InteractiveCreateDefault"] = "interactive-create-default";
CustomizeResourceGroupType["InteractiveCreateCustomized"] = "interactive-create-customized";
CustomizeResourceGroupType["InteractiveUseExisting"] = "interactive-use-existing";
CustomizeResourceGroupType["FallbackDefault"] = "fallback-default";
})(CustomizeResourceGroupType = exports.CustomizeResourceGroupType || (exports.CustomizeResourceGroupType = {}));
var CustomizeSubscriptionType;
(function (CustomizeSubscriptionType) {
CustomizeSubscriptionType["CommandLine"] = "command-line";
CustomizeSubscriptionType["EnvConfig"] = "env-config";
CustomizeSubscriptionType["EnvState"] = "env-state";
CustomizeSubscriptionType["Default"] = "default";
})(CustomizeSubscriptionType = exports.CustomizeSubscriptionType || (exports.CustomizeSubscriptionType = {}));
var ProjectMigratorStatus;
(function (ProjectMigratorStatus) {
ProjectMigratorStatus["OK"] = "ok";
ProjectMigratorStatus["Cancel"] = "cancel";
})(ProjectMigratorStatus = exports.ProjectMigratorStatus || (exports.ProjectMigratorStatus = {}));
var WebApplicationIdValue;
(function (WebApplicationIdValue) {
WebApplicationIdValue["None"] = "none";
WebApplicationIdValue["Default"] = "default";
WebApplicationIdValue["Customized"] = "customized";
})(WebApplicationIdValue = exports.WebApplicationIdValue || (exports.WebApplicationIdValue = {}));
var ProjectMigratorGuideStatus;
(function (ProjectMigratorGuideStatus) {
ProjectMigratorGuideStatus["Reload"] = "reload";
ProjectMigratorGuideStatus["LearnMore"] = "learn-more";
ProjectMigratorGuideStatus["Cancel"] = "cancel";
})(ProjectMigratorGuideStatus = exports.ProjectMigratorGuideStatus || (exports.ProjectMigratorGuideStatus = {}));
var ApiSpecTelemetryPropertis;
(function (ApiSpecTelemetryPropertis) {
ApiSpecTelemetryPropertis["SpecNotValidDetails"] = "spec-not-valid-details";
ApiSpecTelemetryPropertis["InvalidApiSpec"] = "invalid-api-spec";
})(ApiSpecTelemetryPropertis = exports.ApiSpecTelemetryPropertis || (exports.ApiSpecTelemetryPropertis = {}));
function getQuestionValidationErrorEventName(questionName) {
return `invalid-${questionName}`;
}
exports.getQuestionValidationErrorEventName = getQuestionValidationErrorEventName;
function sendTelemetryEvent(component, eventName, properties, measurements) {
var _a;
if (!properties) {
properties = {};
}
properties[TelemetryProperty.Component] = component;
(_a = globalVars_1.TOOLS.telemetryReporter) === null || _a === void 0 ? void 0 : _a.sendTelemetryEvent(eventName, properties, measurements);
}
exports.sendTelemetryEvent = sendTelemetryEvent;
function sendTelemetryErrorEvent(component, eventName, fxError, properties) {
var _a;
if (!properties) {
properties = {};
}
properties[TelemetryProperty.Component] = component;
exports.telemetryUtils.fillInErrorProperties(properties, fxError);
(_a = globalVars_1.TOOLS.telemetryReporter) === null || _a === void 0 ? void 0 : _a.sendTelemetryErrorEvent(eventName, properties, {});
}
exports.sendTelemetryErrorEvent = sendTelemetryErrorEvent;
class TelemetryUtils {
/**
* fill in telemetry properties for FxError
* @param error FxError
* @param props teletry properties
*/
fillInErrorProperties(props, error) {
const errorCode = error.source + "." + error.name;
const errorType = error instanceof teamsfx_api_1.SystemError ? TelemetryErrorType.SystemError : TelemetryErrorType.UserError;
props[TelemetryProperty.Success] = TelemetrySuccess.No;
props[TelemetryProperty.ErrorCode] = props[TelemetryProperty.ErrorCode] || errorCode;
props[TelemetryProperty.ErrorType] = errorType;
props[TelemetryProperty.ErrorMessage] = error.skipProcessInTelemetry
? error.message
: (0, stringUtils_1.maskSecret)(error.message);
props[TelemetryProperty.ErrorStack] = this.extractMethodNamesFromErrorStack(error.stack); // error stack will not append in error-message any more
props[TelemetryProperty.ErrorName] = error.name;
if (error.name === "ScriptExecutionError") {
props[TelemetryProperty.ErrorData] = (0, stringUtils_1.maskSecret)(error.userData); // collect error details for script execution error
}
// append global context properties
props[TelemetryProperty.ErrorComponent] = globalVars_1.globalVars.component;
props[TelemetryProperty.ErrorStage] = globalVars_1.globalVars.stage;
props[TelemetryProperty.ErrorMethod] = globalVars_1.globalVars.method;
props[TelemetryProperty.ErrorSource] = globalVars_1.globalVars.source;
if (error.innerError && error.innerError["code"]) {
props[TelemetryProperty.ErrorInnerCode] = error.innerError["code"];
}
if (error.categories) {
props[TelemetryProperty.ErrorCat] = error.categories.join("|");
props[TelemetryProperty.ErrorCat1] = error.categories[0];
props[TelemetryProperty.ErrorCat2] = error.categories[1];
props[TelemetryProperty.ErrorCat3] = error.categories[2];
}
if (error.telemetryProperties) {
(0, lodash_1.assign)(props, error.telemetryProperties);
}
}
fillinProjectTypeProperties(props, projectTypeRes) {
var _a;
const newProps = {
[ProjectTypeProps.IsTeamsFx]: projectTypeRes.isTeamsFx ? "true" : "false",
[ProjectTypeProps.TeamsfxConfigType]: projectTypeRes.teamsfxConfigType || "",
[ProjectTypeProps.TeamsfxConfigVersion]: projectTypeRes.teamsfxConfigVersion || "",
[ProjectTypeProps.TeamsfxVersionState]: projectTypeRes.teamsfxVersionState || "",
[ProjectTypeProps.TeamsJs]: projectTypeRes.dependsOnTeamsJs ? "true" : "false",
[ProjectTypeProps.TeamsManifest]: projectTypeRes.hasTeamsManifest ? "true" : "false",
[ProjectTypeProps.TeamsManifestVersion]: projectTypeRes.manifestVersion || "",
[ProjectTypeProps.TeamsManifestAppId]: projectTypeRes.manifestAppId || "",
[ProjectTypeProps.TeamsfxProjectId]: projectTypeRes.teamsfxProjectId || "",
[ProjectTypeProps.Lauguages]: projectTypeRes.lauguages.join(","),
[ProjectTypeProps.TeamsManifestCapabilities]: ((_a = projectTypeRes.manifestCapabilities) === null || _a === void 0 ? void 0 : _a.join(",")) || "",
[ProjectTypeProps.OfficeAddinProjectType]: projectTypeRes.officeAddinProjectType || "",
};
(0, lodash_1.assign)(props, newProps);
}
extractMethodNamesFromErrorStack(stack) {
if (!stack)
return "";
const methodNamesRegex = /at\s([\w.<>\[\]\s]+)\s\(/g;
let match;
const methodNames = [];
while ((match = methodNamesRegex.exec(stack)) !== null) {
methodNames.push(match[1]);
}
return methodNames.join(" | ");
}
}
exports.telemetryUtils = new TelemetryUtils();
//# sourceMappingURL=telemetry.js.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1,11 @@
{
"version": "~4.3",
"localVersion": "4.3.2",
"tagPrefix": "templates@",
"tagListURL": "https://github.com/OfficeDev/TeamsFx/releases/download/template-tag-list/template-tags.txt",
"templateDownloadBaseURL": "https://github.com/OfficeDev/TeamsFx/releases/download",
"templateReleaseURL": "https://github.com/OfficeDev/TeamsFx/releases/expanded_assets",
"templateDownloadBasePath": "/OfficeDev/TeamsFx/releases/download",
"templateExt": ".zip",
"useLocalTemplate": true
}
+8
View File
@@ -0,0 +1,8 @@
import { Tunnel } from "@microsoft/dev-tunnels-contracts";
import { FxError, M365TokenProvider, Result } from "@microsoft/teamsfx-api";
export declare function getSideloadingStatus(token: string): Promise<boolean | undefined>;
export declare function listAllTenants(token: string): Promise<Record<string, any>[]>;
export declare function getSPFxTenant(graphToken: string): Promise<string>;
export declare function getSPFxToken(m365TokenProvider: M365TokenProvider): Promise<string | undefined>;
export declare function listDevTunnels(token: string, isGitHub?: boolean): Promise<Result<Tunnel[], FxError>>;
//# sourceMappingURL=tools.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"tools.d.ts","sourceRoot":"","sources":["../../src/common/tools.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,MAAM,EAAE,MAAM,kCAAkC,CAAC;AAK1D,OAAO,EAAE,OAAO,EAAE,iBAAiB,EAAE,MAAM,EAAwB,MAAM,wBAAwB,CAAC;AAKlG,wBAAsB,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,GAAG,SAAS,CAAC,CAEtF;AAED,wBAAsB,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,CAAC,CAclF;AAED,wBAAsB,aAAa,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CASvE;AAED,wBAAsB,YAAY,CAChC,iBAAiB,EAAE,iBAAiB,GACnC,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAa7B;AAID,wBAAsB,cAAc,CAClC,KAAK,EAAE,MAAM,EACb,QAAQ,UAAQ,GACf,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,EAAE,OAAO,CAAC,CAAC,CAwBpC"}
+81
View File
@@ -0,0 +1,81 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.listDevTunnels = exports.getSPFxToken = exports.getSPFxTenant = exports.listAllTenants = exports.getSideloadingStatus = void 0;
const tslib_1 = require("tslib");
const dev_tunnels_management_1 = require("@microsoft/dev-tunnels-management");
const teamsfx_api_1 = require("@microsoft/teamsfx-api");
const axios_1 = tslib_1.__importDefault(require("axios"));
const teamsDevPortalClient_1 = require("../client/teamsDevPortalClient");
const constants_1 = require("./constants");
async function getSideloadingStatus(token) {
return teamsDevPortalClient_1.teamsDevPortalClient.getSideloadingStatus(token);
}
exports.getSideloadingStatus = getSideloadingStatus;
async function listAllTenants(token) {
const RM_ENDPOINT = "https://management.azure.com/tenants?api-version=2022-06-01";
if (token.length > 0) {
try {
const response = await axios_1.default.get(RM_ENDPOINT, {
headers: { Authorization: `Bearer ${token}` },
});
return response.data.value;
}
catch (error) {
return [];
}
}
return [];
}
exports.listAllTenants = listAllTenants;
async function getSPFxTenant(graphToken) {
const GRAPH_TENANT_ENDPT = "https://graph.microsoft.com/v1.0/sites/root?$select=webUrl";
if (graphToken.length > 0) {
const response = await axios_1.default.get(GRAPH_TENANT_ENDPT, {
headers: { Authorization: `Bearer ${graphToken}` },
});
return response.data.webUrl;
}
return "";
}
exports.getSPFxTenant = getSPFxTenant;
async function getSPFxToken(m365TokenProvider) {
const graphTokenRes = await m365TokenProvider.getAccessToken({
scopes: constants_1.GraphReadUserScopes,
});
let spoToken = undefined;
if (graphTokenRes && graphTokenRes.isOk()) {
const tenant = await getSPFxTenant(graphTokenRes.value);
const spfxTokenRes = await m365TokenProvider.getAccessToken({
scopes: (0, constants_1.SPFxScopes)(tenant),
});
spoToken = spfxTokenRes.isOk() ? spfxTokenRes.value : undefined;
}
return spoToken;
}
exports.getSPFxToken = getSPFxToken;
// this function will be deleted after VS has added get dev tunnel and list dev tunnels API
const TunnelManagementUserAgent = { name: "Teams-Toolkit" };
async function listDevTunnels(token, isGitHub = false) {
try {
const tunnelManagementClientImpl = new dev_tunnels_management_1.TunnelManagementHttpClient(TunnelManagementUserAgent, dev_tunnels_management_1.ManagementApiVersions.Version20230927preview, () => {
if (isGitHub === true) {
const res = `github client_id=a200baed193bb2088a6e ${token}`;
return Promise.resolve(res);
}
else {
const res = `Bearer ${token}`;
return Promise.resolve(res);
}
});
const options = {
includeAccessControl: true,
};
const tunnels = await tunnelManagementClientImpl.listTunnels(undefined, undefined, options);
return (0, teamsfx_api_1.ok)(tunnels);
}
catch (error) {
return (0, teamsfx_api_1.err)(new teamsfx_api_1.SystemError("DevTunnels", "ListDevTunnelsFailed", error.message));
}
}
exports.listDevTunnels = listDevTunnels;
//# sourceMappingURL=tools.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"tools.js","sourceRoot":"","sources":["../../src/common/tools.ts"],"names":[],"mappings":";;;;AAGA,8EAG2C;AAC3C,wDAAkG;AAClG,0DAA0B;AAC1B,yEAAsE;AACtE,2CAA8D;AAEvD,KAAK,UAAU,oBAAoB,CAAC,KAAa;IACtD,OAAO,2CAAoB,CAAC,oBAAoB,CAAC,KAAK,CAAC,CAAC;AAC1D,CAAC;AAFD,oDAEC;AAEM,KAAK,UAAU,cAAc,CAAC,KAAa;IAChD,MAAM,WAAW,GAAG,6DAA6D,CAAC;IAClF,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE;QACpB,IAAI;YACF,MAAM,QAAQ,GAAG,MAAM,eAAK,CAAC,GAAG,CAAC,W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A2F;AAC3F,MAAM,yBAAyB,GAAG,EAAE,IAAI,EAAE,eAAe,EAAE,CAAC;AACrD,KAAK,UAAU,cAAc,CAClC,KAAa,EACb,QAAQ,GAAG,KAAK;IAEhB,IAAI;QACF,MAAM,0BAA0B,GAAG,IAAI,mDAA0B,CAC/D,yBAAyB,EACzB,8CAAqB,CAAC,sBAAsB,EAC5C,GAAG,EAAE;YACH,IAAI,QAAQ,KAAK,IAAI,EAAE;gBACrB,MAAM,GAAG,GAAG,yCAAyC,KAAK,EAAE,CAAC;gBAC7D,OAAO,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;aAC7B;iBAAM;gBACL,MAAM,GAAG,GAAG,UAAU,KAAK,EAAE,CAAC;gBAC9B,OAAO,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;aAC7B;QACH,CAAC,CACF,CAAC;QAEF,MAAM,OAAO,GAAG;YACd,oBAAoB,EAAE,IAAI;SAC3B,CAAC;QACF,MAAM,OAAO,GAAG,MAAM,0BAA0B,CAAC,WAAW,CAAC,SAAS,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;QAC5F,OAAO,IAAA,gBAAE,EAAC,OAAO,CAAC,CAAC;KACpB;IAAC,OAAO,KAAK,EAAE;QACd,OAAO,IAAA,iBAAG,EAAC,IAAI,yBAAW,CAAC,YAAY,EAAE,sBAAsB,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;KAClF;AACH,CAAC;AA3BD,wCA2BC"}
+6
View File
@@ -0,0 +1,6 @@
import { Context, Inputs } from "@microsoft/teamsfx-api";
import { DriverContext } from "../component/driver/interface/commonArgs";
export declare function waitSeconds(second: number): Promise<void>;
export declare function generateDriverContext(ctx: Context, inputs: Inputs): DriverContext;
export declare function isJsonSpecFile(filePath: string): Promise<boolean>;
//# sourceMappingURL=utils.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/common/utils.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,0CAA0C,CAAC;AAIzE,wBAAsB,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAE/D;AAED,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,GAAG,aAAa,CAWjF;AAED,wBAAsB,cAAc,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAkBvE"}
+47
View File
@@ -0,0 +1,47 @@
"use strict";
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.isJsonSpecFile = exports.generateDriverContext = exports.waitSeconds = void 0;
const tslib_1 = require("tslib");
const axios_1 = tslib_1.__importDefault(require("axios"));
const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
async function waitSeconds(second) {
return new Promise((resolve) => setTimeout(resolve, second * 1000));
}
exports.waitSeconds = waitSeconds;
function generateDriverContext(ctx, inputs) {
return {
azureAccountProvider: ctx.tokenProvider.azureAccountProvider,
m365TokenProvider: ctx.tokenProvider.m365TokenProvider,
ui: ctx.userInteraction,
progressBar: undefined,
logProvider: ctx.logProvider,
telemetryReporter: ctx.telemetryReporter,
projectPath: ctx.projectPath,
platform: inputs.platform,
};
}
exports.generateDriverContext = generateDriverContext;
async function isJsonSpecFile(filePath) {
const specPath = filePath.toLowerCase();
if (specPath.endsWith(".yaml") || specPath.endsWith(".yml")) {
return false;
}
else if (specPath.endsWith(".json")) {
return true;
}
const isRemoteFile = specPath.startsWith("http:") || specPath.startsWith("https:");
const fileContent = isRemoteFile
? (await axios_1.default.get(specPath)).data
: await fs_extra_1.default.readFile(specPath, "utf-8");
try {
JSON.parse(fileContent);
return true;
}
catch (error) {
return false;
}
}
exports.isJsonSpecFile = isJsonSpecFile;
//# sourceMappingUR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AAC,MAAM,eAAK,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI;QAClC,CAAC,CAAC,MAAM,kBAAE,CAAC,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;IAEzC,IAAI;QACF,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;QACxB,OAAO,IAAI,CAAC;KACb;IAAC,OAAO,KAAK,EAAE;QACd,OAAO,KAAK,CAAC;KACd;AACH,CAAC;AAlBD,wCAkBC"}
+62
View File
@@ -0,0 +1,62 @@
export declare const MetadataV3: {
projectVersion: string;
unSupprotVersion: string;
platformVersion: {
vs: string;
vsc: string;
cli: string;
cli_help: string;
};
configFile: string;
localConfigFile: string;
testToolConfigFile: string;
defaultEnvironmentFolder: string;
envFilePrefix: string;
secretFileSuffix: string;
projectId: string;
teamsManifestFolder: string;
teamsManifestFileName: string;
aadManifestFileName: string;
v3UpgradeWikiLink: string;
secretFileComment: string;
secretComment: string;
envFileDevComment: string;
envFileLocalComment: string;
};
export declare const MetadataV2: {
projectVersion: string;
projectMaxVersion: string;
platformVersion: {
vs: string;
vsc: string;
cli: string;
cli_help: string;
};
configFolder: string;
stateFolder: string;
userdataSuffix: string;
configFile: string;
updateToolkitLink: string;
aadTemplateFileName: string;
};
export declare const MetadataV3Abandoned: {
projectVersion: string;
configFolder: string;
configFile: string;
};
export declare enum VersionState {
compatible = 0,
upgradeable = -1,
unsupported = 1
}
export declare enum VersionSource {
projectSettings = 0,
teamsapp = 1,
unknown = 2,
settings = 3
}
export interface VersionInfo {
version: string;
source: VersionSource;
}
//# sourceMappingURL=versionMetadata.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"versionMetadata.d.ts","sourceRoot":"","sources":["../../src/common/versionMetadata.ts"],"names":[],"mappings":"AAQA,eAAO,MAAM,UAAU;;;;;;;;;;;;;;;;;;;;;;;;CA8BtB,CAAC;AAEF,eAAO,MAAM,UAAU;;;;;;;;;;;;;;;CAetB,CAAC;AAEF,eAAO,MAAM,mBAAmB;;;;CAI/B,CAAC;AAEF,oBAAY,YAAY;IAEtB,UAAU,IAAI;IAEd,WAAW,KAAK;IAEhB,WAAW,IAAI;CAChB;AAED,oBAAY,aAAa;IACvB,eAAe,IAAA;IACf,QAAQ,IAAA;IACR,OAAO,IAAA;IACP,QAAQ,IAAA;CACT;AACD,MAAM,WAAW,WAAW;IAC1B,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,aAAa,CAAC;CACvB"}
+74
View File
@@ -0,0 +1,74 @@
"use strict";
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.VersionSource = exports.VersionState = exports.MetadataV3Abandoned = exports.MetadataV2 = exports.MetadataV3 = void 0;
/**
* @author xzf0587 <zhaofengxu@microsoft.com>
*/
const os_1 = require("os");
exports.MetadataV3 = {
projectVersion: "1.0.0",
unSupprotVersion: "2.0.0",
platformVersion: {
vs: "17.5.x.x",
vsc: "5.x.x",
cli: "2.x.x",
cli_help: "2.x.x",
},
configFile: "teamsapp.yml",
localConfigFile: "teamsapp.local.yml",
testToolConfigFile: "teamsapp.testtool.yml",
defaultEnvironmentFolder: "env",
envFilePrefix: ".env",
secretFileSuffix: "user",
projectId: "projectId",
teamsManifestFolder: "appPackage",
teamsManifestFileName: "manifest.json",
aadManifestFileName: "aad.manifest.json",
v3UpgradeWikiLink: "https://aka.ms/teams-toolkit-5.0-upgrade",
secretFileComment: "# This file includes environment variables that will not be committed to git by default. You can set these environment variables in your CI/CD system for your project." +
os_1.EOL,
secretComment: "# Secrets. Keys prefixed with `SECRET_` will be masked in Teams Toolkit logs." + os_1.EOL,
envFileDevComment: "# This file includes environment variables that will be committed to git by default." + os_1.EOL,
envFileLocalComment: "# This file includes environment variables that can be committed to git. It's gitignored by default because it represents your local development environment." +
os_1.EOL,
};
exports.MetadataV2 = {
projectVersion: "2.0.0",
projectMaxVersion: "2.1.0",
platformVersion: {
vs: "17.4.x.x",
vsc: "4.x.x",
cli: "1.x.x",
cli_help: "1.x.x",
},
configFolder: ".fx",
stateFolder: "states",
userdataSuffix: "userdata",
configFile: "projectSettings.json",
updateToolkitLink: "https://aka.ms/update-teams-toolkit",
aadTemplateFileName: "aad.template.json",
};
exports.MetadataV3Abandoned = {
projectVersion: "3.0.0",
configFolder: "teamsfx",
configFile: "settings.json",
};
var VersionState;
(function (VersionState) {
// project version compatible
VersionState[VersionState["compatible"] = 0] = "compatible";
// project version outdated, project should upgrade
VersionState[VersionState["upgradeable"] = -1] = "upgradeable";
// project version ahead, need update toolkit
VersionState[VersionState["unsupported"] = 1] = "unsupported";
})(VersionState = exports.VersionState || (exports.VersionState = {}));
var VersionSource;
(function (VersionSource) {
VersionSource[VersionSource["projectSettings"] = 0] = "projectSettings";
VersionSource[VersionSource["teamsapp"] = 1] = "teamsapp";
VersionSource[VersionSource["unknown"] = 2] = "unknown";
VersionSource[VersionSource["settings"] = 3] = "settings";
})(VersionSource = exports.VersionSource || (exports.VersionSource = {}));
//# sourceMappingURL=versionMetadata.js.map
@@ -0,0 +1 @@
{"version":3,"file":"versionMetadata.js","sourceRoot":"","sources":["../../src/common/versionMetadata.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAElC;;GAEG;AACH,2BAAyB;AAEZ,QAAA,UAAU,GAAG;IACxB,cAAc,EAAE,OAAO;IACvB,gBAAgB,EAAE,OAAO;IACzB,eAAe,EAAE;QACf,EAAE,EAAE,UAAU;QACd,GAAG,EAAE,OAAO;QACZ,GAAG,EAAE,OAAO;QACZ,QAAQ,EAAE,OAAO;KAClB;IACD,UAAU,EAAE,cAAc;IAC1B,eAAe,EAAE,oBAAoB;IACrC,kBAAkB,EAAE,uBAAuB;IAC3C,wBAAwB,EAAE,KAAK;IAC/B,aAAa,EAAE,MAAM;IACrB,gBAAgB,EAAE,MAAM;IACxB,SAAS,EAAE,WAAW;IACtB,mBAAmB,EAAE,YAAY;IACjC,qBAAqB,EAAE,eAAe;IACtC,mBAAmB,EAAE,mBAAmB;IACxC,iBAAiB,EAAE,0CAA0C;IAC7D,iBAAiB,EACf,yKAAyK;QACzK,QAAG;IACL,aAAa,EACX,+EAA+E,GAAG,QAAG;IACvF,iBAAiB,EACf,sFAAsF,GAAG,QAAG;IAC9F,mBAAmB,EACjB,+JAA+J;QAC/J,QAAG;CACN,CAAC;AAEW,QAAA,UAAU,GAAG;IACxB,cAAc,EAAE,OAAO;IACvB,iBAAiB,EAAE,OAAO;IAC1B,eAAe,EAAE;QACf,EAAE,EAAE,UAAU;QACd,GAAG,EAAE,OAAO;QACZ,GAAG,EAAE,OAAO;QACZ,QAAQ,EAAE,OAAO;KAClB;IACD,YAAY,EAAE,KAAK;IACnB,WAAW,EAAE,QAAQ;IACrB,cAAc,EAAE,UAAU;IAC1B,UAAU,EAAE,sBAAsB;IAClC,iBAAiB,EAAE,qCAAqC;IACxD,mBAAmB,EAAE,mBAAmB;CACzC,CAAC;AAEW,QAAA,mBAAmB,GAAG;IACjC,cAAc,EAAE,OAAO;IACvB,YAAY,EAAE,SAAS;IACvB,UAAU,EAAE,eAAe;CAC5B,CAAC;AAEF,IAAY,YAOX;AAPD,WAAY,YAAY;IACtB,6BAA6B;IAC7B,2DAAc,CAAA;IACd,mDAAmD;IACnD,8DAAgB,CAAA;IAChB,6CAA6C;IAC7C,6DAAe,CAAA;AACjB,CAAC,EAPW,YAAY,GAAZ,oBAAY,KAAZ,oBAAY,QAOvB;AAED,IAAY,aAKX;AALD,WAAY,aAAa;IACvB,uEAAe,CAAA;IACf,yDAAQ,CAAA;IACR,uDAAO,CAAA;IACP,yDAAQ,CAAA;AACV,CAAC,EALW,aAAa,GAAb,qBAAa,KAAb,qBAAa,QAKxB"}
@@ -0,0 +1,60 @@
import { AxiosInstance, AxiosError, CreateAxiosDefaults, AxiosResponse, InternalAxiosRequestConfig } from "axios";
/**
* This client will send telemetries to record API request trace
*/
export declare class WrappedAxiosClient {
static create(config?: CreateAxiosDefaults): AxiosInstance;
/**
* Send API start telemetry
* @param request
*/
static onRequest(request: InternalAxiosRequestConfig): InternalAxiosRequestConfig<any>;
/**
* Send API success telemetry
* @param response
* @returns
*/
static onResponse(response: AxiosResponse): AxiosResponse<any, any>;
/**
* Send API failure telemetry
* @param error
* @returns
*/
static onRejected(error: AxiosError): Promise<never>;
/**
* Convert request URL to API name, otherwise it will be redacted in telemetry
* This function should be extended when new API is added
* @param baseUrl
* @param path
* @param method
* @returns
*/
static convertUrlToApiName(fullPath: string, method: string): string;
/**
* Generate extra properties for specific requirements
* @param baseUrl
* @param path
* @param method
*/
private static generateExtraProperties;
/**
* Extract region from baseUrl, E.g. https://dev.teams.microsoft.com/amer => amer
* @param url
* @returns
*/
private static extractRegion;
/**
* Check if it's TDP Api
* @param baseUrl
* @returns
*/
private static isTDPApi;
private static getEventName;
/**
* Flattern query parameters to string, e.g. {a: 1, b: 2} => a:1;b:2
* @param params
* @returns
*/
private static generateParameters;
}
//# sourceMappingURL=wrappedAxiosClient.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"wrappedAxiosClient.d.ts","sourceRoot":"","sources":["../../src/common/wrappedAxiosClient.ts"],"names":[],"mappings":"AAEA,OAAc,EACZ,aAAa,EACb,UAAU,EACV,mBAAmB,EACnB,aAAa,EACb,0BAA0B,EAC3B,MAAM,OAAO,CAAC;AAYf;;GAEG;AACH,qBAAa,kBAAkB;WACf,MAAM,CAAC,MAAM,CAAC,EAAE,mBAAmB,GAAG,aAAa;IAWjE;;;OAGG;WACW,SAAS,CAAC,OAAO,EAAE,0BAA0B;IAgB3D;;;;OAIG;WACW,UAAU,CAAC,QAAQ,EAAE,aAAa;IAqBhD;;;;OAIG;WACW,UAAU,CAAC,KAAK,EAAE,UAAU;IA+D1C;;;;;;;OAOG;WACW,mBAAmB,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM;IA6H3E;;;;;OAKG;IACH,OAAO,CAAC,MAAM,CAAC,uBAAuB;IAoBtC;;;;OAIG;IACH,OAAO,CAAC,MAAM,CAAC,aAAa;IAU5B;;;;OAIG;IACH,OAAO,CAAC,MAAM,CAAC,QAAQ;IAMvB,OAAO,CAAC,MAAM,CAAC,YAAY;IAY3B;;;;OAIG;IACH,OAAO,CAAC,MAAM,CAAC,kBAAkB;CAUlC"}
+280
View File
@@ -0,0 +1,280 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WrappedAxiosClient = void 0;
const tslib_1 = require("tslib");
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
const axios_1 = tslib_1.__importDefault(require("axios"));
const globalVars_1 = require("./globalVars");
const constants_1 = require("../component/driver/teamsApp/constants");
const telemetry_1 = require("../component/driver/teamsApp/utils/telemetry");
const telemetry_2 = require("./telemetry");
const teamsApp_1 = require("../error/teamsApp");
const commonConstant_1 = require("../component/constant/commonConstant");
const localizeUtils_1 = require("./localizeUtils");
/**
* This client will send telemetries to record API request trace
*/
class WrappedAxiosClient {
static create(config) {
const instance = axios_1.default.create(config);
instance.interceptors.request.use((request) => this.onRequest(request));
// eslint-disable-next-line prettier/prettier
instance.interceptors.response.use((response) => this.onResponse(response), (error) => this.onRejected(error));
return instance;
}
/**
* Send API start telemetry
* @param request
*/
static onRequest(request) {
var _a, _b, _c;
const method = request.method;
const fullPath = `${(_a = request.baseURL) !== null && _a !== void 0 ? _a : ""}${(_b = request.url) !== null && _b !== void 0 ? _b : ""}`;
const apiName = this.convertUrlToApiName(fullPath, method);
const properties = Object.assign({ url: `<${apiName}-url>`, method: method, params: this.generateParameters(request.params) }, this.generateExtraProperties(fullPath, request.data));
const eventName = this.getEventName(fullPath);
(_c = globalVars_1.TOOLS === null || globalVars_1.TOOLS === void 0 ? void 0 : globalVars_1.TOOLS.telemetryReporter) === null || _c === void 0 ? void 0 : _c.sendTelemetryEvent(`${eventName}-start`, properties);
return request;
}
/**
* Send API success telemetry
* @param response
* @returns
*/
static onResponse(response) {
var _a, _b, _c;
const method = response.request.method;
const fullPath = `${(_a = response.request.host) !== null && _a !== void 0 ? _a : ""}${(_b = response.request.path) !== null && _b !== void 0 ? _b : ""}`;
const apiName = this.convertUrlToApiName(fullPath, method);
const properties = Object.assign({ url: `<${apiName}-url>`, method: method, params: this.generateParameters(response.config.params), [telemetry_2.TelemetryProperty.Success]: telemetry_2.TelemetrySuccess.Yes, "status-code": response.status.toString() }, this.generateExtraProperties(fullPath, response.data));
const eventName = this.getEventName(fullPath);
(_c = globalVars_1.TOOLS === null || globalVars_1.TOOLS === void 0 ? void 0 : globalVars_1.TOOLS.telemetryReporter) === null || _c === void 0 ? void 0 : _c.sendTelemetryEvent(eventName, properties);
return response;
}
/**
* Send API failure telemetry
* @param error
* @returns
*/
static onRejected(error) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
const method = error.request.method;
const fullPath = `${(_a = error.request.host) !== null && _a !== void 0 ? _a : ""}${(_b = error.request.path) !== null && _b !== void 0 ? _b : ""}`;
const apiName = this.convertUrlToApiName(fullPath, method);
let requestData;
if (((_c = error.config) === null || _c === void 0 ? void 0 : _c.data) && typeof error.config.data === "string") {
try {
requestData = JSON.parse(error.config.data);
}
catch (error) {
requestData = undefined;
}
}
const properties = Object.assign({ url: `<${apiName}-url>`, method: method, params: this.generateParameters(error.config.params), [telemetry_2.TelemetryProperty.Success]: telemetry_2.TelemetrySuccess.No, [telemetry_2.TelemetryProperty.ErrorMessage]: error.response
? JSON.stringify(error.response.data)
: (_d = error.message) !== null && _d !== void 0 ? _d : "undefined", "status-code": (_f = (_e = error.response) === null || _e === void 0 ? void 0 : _e.status.toString()) !== null && _f !== void 0 ? _f : "undefined" }, this.generateExtraProperties(fullPath, requestData));
const eventName = this.getEventName(fullPath);
if (eventName === telemetry_2.TelemetryEvent.AppStudioApi) {
const correlationId = (_h = (_g = error.response) === null || _g === void 0 ? void 0 : _g.headers[constants_1.Constants.CORRELATION_ID]) !== null && _h !== void 0 ? _h : "undefined";
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
const extraData = (0, localizeUtils_1.getDefaultString)("error.appstudio.apiFailed.reason.common", ((_j = error.response) === null || _j === void 0 ? void 0 : _j.data) ? `data: ${JSON.stringify(error.response.data)}` : "");
const TDPApiFailedError = new teamsApp_1.DeveloperPortalAPIFailedSystemError(error, correlationId, apiName, extraData);
properties[telemetry_2.TelemetryProperty.ErrorCode] = `${TDPApiFailedError.source}.${TDPApiFailedError.name}`;
properties[telemetry_2.TelemetryProperty.ErrorMessage] = TDPApiFailedError.message;
properties[telemetry_2.TelemetryProperty.TDPTraceId] = correlationId;
}
else if (eventName === telemetry_2.TelemetryEvent.MOSApi) {
const tracingId = ((_m = (_l = (_k = error.response) === null || _k === void 0 ? void 0 : _k.headers) === null || _l === void 0 ? void 0 : _l.traceresponse) !== null && _m !== void 0 ? _m : "undefined");
const originalMessage = error.message;
const innerError = ((_o = error.response) === null || _o === void 0 ? void 0 : _o.data).error || { code: "", message: "" };
const finalMessage = `${originalMessage} (tracingId: ${tracingId}) ${innerError.code}: ${innerError.message} `;
properties[telemetry_2.TelemetryProperty.ErrorMessage] = finalMessage;
properties[telemetry_2.TelemetryProperty.MOSTraceId] = tracingId;
const relativePath = (error.request.path || "");
properties[telemetry_2.TelemetryProperty.MOSPATH] = method + " " + relativePath.replace(/\//g, "__");
}
(_p = globalVars_1.TOOLS === null || globalVars_1.TOOLS === void 0 ? void 0 : globalVars_1.TOOLS.telemetryReporter) === null || _p === void 0 ? void 0 : _p.sendTelemetryErrorEvent(eventName, properties);
return Promise.reject(error);
}
/**
* Convert request URL to API name, otherwise it will be redacted in telemetry
* This function should be extended when new API is added
* @param baseUrl
* @param path
* @param method
* @returns
*/
static convertUrlToApiName(fullPath, method) {
if (this.isTDPApi(fullPath)) {
if (fullPath.match(new RegExp("/api/appdefinitions/partnerCenterAppPackageValidation"))) {
return constants_1.APP_STUDIO_API_NAMES.VALIDATE_APP_PACKAGE;
}
if (fullPath.match(new RegExp("/api/appdefinitions/v2/import"))) {
return constants_1.APP_STUDIO_API_NAMES.CREATE_APP;
}
if (fullPath.match(new RegExp("/api/appdefinitions/manifest"))) {
return constants_1.APP_STUDIO_API_NAMES.EXISTS_IN_TENANTS;
}
if (fullPath.match(new RegExp("/api/appdefinitions/.*/manifest"))) {
return constants_1.APP_STUDIO_API_NAMES.GET_APP_PACKAGE;
}
if (fullPath.match(new RegExp("/api/appdefinitions/.*/owner"))) {
return constants_1.APP_STUDIO_API_NAMES.UPDATE_OWNER;
}
if (fullPath.match(new RegExp(/\/api\/appdefinitions\/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/))) {
if (method.toUpperCase() === commonConstant_1.HttpMethod.GET) {
return constants_1.APP_STUDIO_API_NAMES.GET_APP;
}
if (method.toUpperCase() === commonConstant_1.HttpMethod.DELETE) {
return constants_1.APP_STUDIO_API_NAMES.DELETE_APP;
}
}
if (fullPath.match(new RegExp("/api/appdefinitions"))) {
return constants_1.APP_STUDIO_API_NAMES.LIST_APPS;
}
if (fullPath.match(new RegExp("/api/publishing/.*/appdefinitions"))) {
return constants_1.APP_STUDIO_API_NAMES.UPDATE_PUBLISHED_APP;
}
if (fullPath.match(new RegExp("/api/publishing/.*"))) {
return constants_1.APP_STUDIO_API_NAMES.GET_PUBLISHED_APP;
}
if (fullPath.match(new RegExp("/api/publishing"))) {
return constants_1.APP_STUDIO_API_NAMES.PUBLISH_APP;
}
if (fullPath.match(new RegExp("/api/usersettings/mtUserAppPolicy"))) {
return constants_1.APP_STUDIO_API_NAMES.CHECK_SIDELOADING_STATUS;
}
if (fullPath.match(new RegExp("/api/v1.0/apiSecretRegistrations/.*"))) {
if (method.toUpperCase() === commonConstant_1.HttpMethod.GET) {
return constants_1.APP_STUDIO_API_NAMES.GET_API_KEY;
}
if (method.toUpperCase() === commonConstant_1.HttpMethod.PATCH) {
return constants_1.APP_STUDIO_API_NAMES.UPDATE_API_KEY;
}
}
if (fullPath.match(new RegExp("/api/v1.0/apiSecretRegistrations"))) {
return constants_1.APP_STUDIO_API_NAMES.CREATE_API_KEY;
}
if (fullPath.match(new RegExp(/\/api\/botframework\/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/))) {
if (method.toUpperCase() === commonConstant_1.HttpMethod.GET) {
return constants_1.APP_STUDIO_API_NAMES.GET_BOT;
}
if (method.toUpperCase() === commonConstant_1.HttpMethod.POST) {
return constants_1.APP_STUDIO_API_NAMES.UPDATE_BOT;
}
if (method.toUpperCase() === commonConstant_1.HttpMethod.DELETE) {
return constants_1.APP_STUDIO_API_NAMES.DELETE_BOT;
}
}
if (fullPath.match(new RegExp("/api/botframework"))) {
if (method.toUpperCase() === commonConstant_1.HttpMethod.GET) {
return constants_1.APP_STUDIO_API_NAMES.LIST_BOT;
}
if (method.toUpperCase() === commonConstant_1.HttpMethod.POST) {
return constants_1.APP_STUDIO_API_NAMES.CREATE_BOT;
}
}
if (fullPath.match(new RegExp("/api/v1.0/appvalidations/appdefinition/validate"))) {
return constants_1.APP_STUDIO_API_NAMES.SUBMIT_APP_VALIDATION;
}
if (fullPath.match(new RegExp("/api/v1.0/appvalidations/appdefinitions/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}"))) {
return constants_1.APP_STUDIO_API_NAMES.GET_APP_VALIDATION_REQUESTS;
}
if (fullPath.match(new RegExp("/api/v1.0/appvalidations/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}"))) {
return constants_1.APP_STUDIO_API_NAMES.GET_APP_VALIDATION_RESULT;
}
if (fullPath.match(new RegExp("/api/v1.0/oAuthConfigurations/.*"))) {
if (method.toUpperCase() === commonConstant_1.HttpMethod.GET) {
return constants_1.APP_STUDIO_API_NAMES.GET_OAUTH;
}
if (method.toUpperCase() === commonConstant_1.HttpMethod.PATCH) {
return constants_1.APP_STUDIO_API_NAMES.UPDATE_OAUTH;
}
}
if (fullPath.match(new RegExp("/api/v1.0/oAuthConfigurations"))) {
return constants_1.APP_STUDIO_API_NAMES.CREATE_OAUTH;
}
}
if (fullPath.match(new RegExp(/(^https:\/\/)?authsvc\.teams\.microsoft\.com\/v1\.0\/users\/region/))) {
return "get-region";
}
return fullPath.replace(/\//g, `-`);
}
/**
* Generate extra properties for specific requirements
* @param baseUrl
* @param path
* @param method
*/
static generateExtraProperties(fullPath, data) {
const properties = {};
if (this.isTDPApi(fullPath)) {
// Add region property
properties[telemetry_1.TelemetryPropertyKey.region] = String(this.extractRegion(fullPath));
// Add bot id property
if (fullPath.match(new RegExp("/api/botframework"))) {
const regex = new RegExp(/\/api\/botframework\/([0-9a-fA-F-]+)/);
const matches = regex.exec(fullPath);
if (matches != null && matches.length > 1) {
properties[telemetry_2.TelemetryProperty.BotId] = matches[1];
}
else if (data === null || data === void 0 ? void 0 : data.botId) {
properties[telemetry_2.TelemetryProperty.BotId] = data.botId;
}
}
}
return properties;
}
/**
* Extract region from baseUrl, E.g. https://dev.teams.microsoft.com/amer => amer
* @param url
* @returns
*/
static extractRegion(fullPath) {
const regex = /dev(-int)?\.teams\.microsoft\.com\/([a-zA-Z-_]+)\/api/;
const matches = regex.exec(fullPath);
if (matches != null && matches.length > 1) {
return matches[2];
}
return telemetry_1.TelemetryPropertyValue.Global;
}
/**
* Check if it's TDP Api
* @param baseUrl
* @returns
*/
static isTDPApi(baseUrl) {
const regex = /(^https:\/\/)?dev(-int)?\.teams\.microsoft\.com/;
const matches = regex.exec(baseUrl);
return matches != null && matches.length > 0;
}
static getEventName(baseUrl) {
if (this.isTDPApi(baseUrl)) {
return telemetry_2.TelemetryEvent.AppStudioApi;
}
else if (baseUrl.includes("titles.prod.mos.microsoft.com")) {
return telemetry_2.TelemetryEvent.MOSApi;
}
else {
return telemetry_2.TelemetryEvent.DependencyApi;
}
}
/**
* Flattern query parameters to string, e.g. {a: 1, b: 2} => a:1;b:2
* @param params
* @returns
*/
static generateParameters(params) {
if (!params) {
return "";
}
const parameters = [];
for (const [key, value] of Object.entries(params)) {
parameters.push(`${key}:${value}`);
}
return parameters.join(";");
}
}
exports.WrappedAxiosClient = WrappedAxiosClient;
//# sourceMappingURL=wrappedAxiosClient.js.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1,13 @@
export declare class ActionInjector {
static hasActionWithName(provisionNode: any, action: string, name: string): any;
static getTeamsAppIdEnvName(provisionNode: any): string | undefined;
static generateAuthAction(actionName: string, authName: string, teamsAppIdEnvName: string, specRelativePath: string, envName: string, flow?: string): any;
static injectCreateOAuthAction(ymlPath: string, authName: string, specRelativePath: string, forceToAddNew: boolean): Promise<AuthActionInjectResult | undefined>;
static injectCreateAPIKeyAction(ymlPath: string, authName: string, specRelativePath: string, forceToAddNew: boolean): Promise<AuthActionInjectResult | undefined>;
static findNextAvailableEnvName(baseEnvName: string, existingEnvNames: string[]): string;
}
export interface AuthActionInjectResult {
defaultRegistrationIdEnvName: string | undefined;
registrationIdEnvName: string | undefined;
}
//# sourceMappingURL=actionInjector.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"actionInjector.d.ts","sourceRoot":"","sources":["../../../src/component/configManager/actionInjector.ts"],"names":[],"mappings":"AAQA,qBAAa,cAAc;IACzB,MAAM,CAAC,iBAAiB,CAAC,aAAa,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,GAAG;IAO/E,MAAM,CAAC,oBAAoB,CAAC,aAAa,EAAE,GAAG,GAAG,MAAM,GAAG,SAAS;IAUnE,MAAM,CAAC,kBAAkB,CACvB,UAAU,EAAE,MAAM,EAClB,QAAQ,EAAE,MAAM,EAChB,iBAAiB,EAAE,MAAM,EACzB,gBAAgB,EAAE,MAAM,EACxB,OAAO,EAAE,MAAM,EACf,IAAI,CAAC,EAAE,MAAM,GACZ,GAAG;WAwBO,uBAAuB,CAClC,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,MAAM,EAChB,gBAAgB,EAAE,MAAM,EACxB,aAAa,EAAE,OAAO,GACrB,OAAO,CAAC,sBAAsB,GAAG,SAAS,CAAC;WAgEjC,wBAAwB,CACnC,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,MAAM,EAChB,gBAAgB,EAAE,MAAM,EACxB,aAAa,EAAE,OAAO,GACrB,OAAO,CAAC,sBAAsB,GAAG,SAAS,CAAC;IA8D9C,MAAM,CAAC,wBAAwB,CAAC,WAAW,EAAE,MAAM,EAAE,gBAAgB,EAAE,MAAM,EAAE,GAAG,MAAM;CASzF;AAED,MAAM,WAAW,sBAAsB;IACrC,4BAA4B,EAAE,MAAM,GAAG,SAAS,CAAC;IACjD,qBAAqB,EAAE,MAAM,GAAG,SAAS,CAAC;CAC3C"}
@@ -0,0 +1,159 @@
"use strict";
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.ActionInjector = void 0;
const tslib_1 = require("tslib");
const m365_spec_parser_1 = require("@microsoft/m365-spec-parser");
const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
const yaml_1 = require("yaml");
const common_1 = require("../../error/common");
class ActionInjector {
static hasActionWithName(provisionNode, action, name) {
const hasAuthAction = provisionNode.items.some((item) => { var _a; return item.get("uses") === action && ((_a = item.get("with")) === null || _a === void 0 ? void 0 : _a.get("name")) === name; });
return hasAuthAction;
}
static getTeamsAppIdEnvName(provisionNode) {
var _a;
for (const item of provisionNode.items) {
if (item.get("uses") === "teamsApp/create") {
return (_a = item.get("writeToEnvironmentFile")) === null || _a === void 0 ? void 0 : _a.get("teamsAppId");
}
}
return undefined;
}
static generateAuthAction(actionName, authName, teamsAppIdEnvName, specRelativePath, envName, flow) {
const result = {
uses: actionName,
with: {
name: `${authName}`,
appId: `\${{${teamsAppIdEnvName}}}`,
apiSpecPath: specRelativePath,
},
};
if (flow) {
result.with.flow = flow;
result.writeToEnvironmentFile = {
configurationId: envName,
};
}
else {
result.writeToEnvironmentFile = {
registrationId: envName,
};
}
return result;
}
static async injectCreateOAuthAction(ymlPath, authName, specRelativePath, forceToAddNew // If it from add plugin, then we will add another CreateOAuthAction
) {
const ymlContent = await fs_extra_1.default.readFile(ymlPath, "utf-8");
const actionName = "oauth/register";
const document = (0, yaml_1.parseDocument)(ymlContent);
const provisionNode = document.get("provision");
if (provisionNode) {
const hasOAuthAction = ActionInjector.hasActionWithName(provisionNode, actionName, authName);
if (!hasOAuthAction || forceToAddNew) {
provisionNode.items = provisionNode.items.filter((item) => {
const uses = item.get("uses");
if (forceToAddNew) {
return uses;
}
else {
return uses !== actionName && uses !== "apiKey/register";
}
});
const existingConfigurationIdEnvNames = provisionNode.items
.filter((item) => {
const uses = item.get("uses");
return uses == actionName;
})
.map((item) => { var _a; return (_a = item.get("writeToEnvironmentFile")) === null || _a === void 0 ? void 0 : _a.get("configurationId"); })
.filter((item) => {
return !!item;
});
const defaultEnvName = m365_spec_parser_1.Utils.getSafeRegistrationIdEnvName(`${authName}_CONFIGURATION_ID`);
const registrationIdEnvName = this.findNextAvailableEnvName(defaultEnvName, existingConfigurationIdEnvNames);
const teamsAppIdEnvName = ActionInjector.getTeamsAppIdEnvName(provisionNode);
if (teamsAppIdEnvName) {
const index = provisionNode.items.findIndex((item) => item.get("uses") === "teamsApp/create");
const flow = "authorizationCode";
const action = ActionInjector.generateAuthAction(actionName, authName, teamsAppIdEnvName, specRelativePath, registrationIdEnvName, flow);
provisionNode.items.splice(index + 1, 0, action);
}
else {
throw new common_1.InjectOAuthActionFailedError();
}
await fs_extra_1.default.writeFile(ymlPath, document.toString(), "utf8");
return {
defaultRegistrationIdEnvName: defaultEnvName,
registrationIdEnvName: registrationIdEnvName,
};
}
}
else {
throw new common_1.InjectOAuthActionFailedError();
}
return undefined;
}
static async injectCreateAPIKeyAction(ymlPath, authName, specRelativePath, forceToAddNew // If it from add plugin, then we will add another CreateApiKeyAction
) {
const ymlContent = await fs_extra_1.default.readFile(ymlPath, "utf-8");
const actionName = "apiKey/register";
const document = (0, yaml_1.parseDocument)(ymlContent);
const provisionNode = document.get("provision");
if (provisionNode) {
const hasApiKeyAction = ActionInjector.hasActionWithName(provisionNode, actionName, authName);
if (!hasApiKeyAction || forceToAddNew) {
provisionNode.items = provisionNode.items.filter((item) => {
const uses = item.get("uses");
if (forceToAddNew) {
return uses;
}
else {
return uses !== actionName && uses !== "oauth/register";
}
});
const existingRegistrationIdEnvNames = provisionNode.items
.filter((item) => {
const uses = item.get("uses");
return uses == actionName;
})
.map((item) => { var _a; return (_a = item.get("writeToEnvironmentFile")) === null || _a === void 0 ? void 0 : _a.get("registrationId"); })
.filter((item) => {
return !!item;
});
const teamsAppIdEnvName = ActionInjector.getTeamsAppIdEnvName(provisionNode);
const defaultEnvName = m365_spec_parser_1.Utils.getSafeRegistrationIdEnvName(`${authName}_REGISTRATION_ID`);
const registrationIdEnvName = this.findNextAvailableEnvName(defaultEnvName, existingRegistrationIdEnvNames);
if (teamsAppIdEnvName) {
const index = provisionNode.items.findIndex((item) => item.get("uses") === "teamsApp/create");
const action = ActionInjector.generateAuthAction(actionName, authName, teamsAppIdEnvName, specRelativePath, registrationIdEnvName);
provisionNode.items.splice(index + 1, 0, action);
}
else {
throw new common_1.InjectAPIKeyActionFailedError();
}
await fs_extra_1.default.writeFile(ymlPath, document.toString(), "utf8");
return {
defaultRegistrationIdEnvName: defaultEnvName,
registrationIdEnvName: registrationIdEnvName,
};
}
}
else {
throw new common_1.InjectAPIKeyActionFailedError();
}
return undefined;
}
static findNextAvailableEnvName(baseEnvName, existingEnvNames) {
let suffix = 1;
let envName = baseEnvName;
while (existingEnvNames.includes(envName)) {
envName = `${baseEnvName}${suffix}`;
suffix++;
}
return envName;
}
}
exports.ActionInjector = ActionInjector;
//# sourceMappingURL=actionInjector.js.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1,19 @@
/**
* @author yefuwang@microsoft.com
*/
export declare enum SummaryConstant {
Succeeded = "(\u221A) Done:",
Failed = "(\u00D7) Error:",
NotExecuted = "(!) Warning:",
Warning = "(!) Warning:"
}
export declare const component = "ConfigManager";
export declare const lifecycleExecutionEvent = "lifecycle-execution";
export declare enum TelemetryProperty {
Lifecycle = "lifecycle",
Actions = "actions",
ResolvedPlaceholders = "resolved",
UnresolvedPlaceholders = "unresolved",
FailedAction = "failed-action"
}
//# sourceMappingURL=constant.d.ts.map

Some files were not shown because too many files have changed in this diff Show More